From d6b563c265ac7e9b7e716c908d3c0e37fd61869b Mon Sep 17 00:00:00 2001 From: elliotBraem <16282460+elliotBraem@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:05:05 -0600 Subject: [PATCH 1/2] =?UTF-8?q?feat(every-plugin,everything-dev,host,ui):?= =?UTF-8?q?=20the=20reverse=20facade=20=E2=80=94=20plugin=20ui=20component?= =?UTF-8?q?=20exports=20consumable=20as=20/$[key]/ui=20(issue=20#1265)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The pluginsClient shape, mirrored for components (ADR 0010 §3, the unbuilt half): a plugin ui workspace declares `ui/src/ui-exports.ts` and the build exposes it as `./ui` (web + node) and publishes its export surface into the manifest's `components` capability — the same discovery block #1260 shipped for the core, now collected for every composed source. Consumers typecheck against generated facades at `/$[key]/ui` (wildcard tsconfig mapping to `src/ui-remote.gen/$[key]/ui/index.ts`), emitted per (consumer, source) pair by the generalized facade generator — the core ui is a consumer too. Server-side, #1260's expose resolver was already source-agnostic, so plugin components render in the SSR document through the same generation-keyed, integrity-verified session loads. Preloads generalize per source: any composed source whose manifest declares the capability gets its expose's static chunks preloaded from its mf-manifest. First source: docs exposes NavTree + StatusBadge. Consumer wiring (auth's profile.sections migration off the hand-rolled remoteComponent, mf-check per-consumer capability gates, remote-only-source types from deployed manifests) follows as this lane's next slices. --- .gitignore | 1 + host/src/services/ui-compose.ts | 64 ++++-- .../src/build/ui/generated-config.ts | 59 +++-- .../src/services/codegen/artifacts.ts | 36 ++- .../src/services/codegen/ui-facade.ts | 214 +++++++++++------- plugins/ai/ui/tsconfig.json | 3 +- plugins/auth/ui/tsconfig.json | 3 +- plugins/deployments/ui/tsconfig.json | 3 +- .../docs/ui/src/components/docs/nav-tree.tsx | 2 +- plugins/docs/ui/src/ui-exports.ts | 2 + plugins/docs/ui/tsconfig.json | 3 +- ui/tsconfig.json | 3 +- 12 files changed, 255 insertions(+), 138 deletions(-) create mode 100644 plugins/docs/ui/src/ui-exports.ts diff --git a/.gitignore b/.gitignore index eae29f0ab..b472eae2f 100644 --- a/.gitignore +++ b/.gitignore @@ -322,6 +322,7 @@ fabric.properties **/*.gen.tsx **/*.gen.json **/ui-types.gen/ +**/ui-remote.gen/ .bos/generated/ # Module Federation DTS artifacts diff --git a/host/src/services/ui-compose.ts b/host/src/services/ui-compose.ts index 13b36262d..5b90a9054 100644 --- a/host/src/services/ui-compose.ts +++ b/host/src/services/ui-compose.ts @@ -94,8 +94,7 @@ export interface UiSource { /** * SSR availability: a production pin, or a local ui whose supervisor-computed - * session intent (BOS_DEV_SSR_INTENT, plan 078 phase 2) materializes the dev - * container — ambient shell exports never count. Loud when requested. + * session intent (BOS_DEV_SSR_INTENT, plan 078) materializes the container. */ export function isSsrAvailable(config: RuntimeConfig): boolean { return ssrEntryResolvable(config); @@ -450,7 +449,7 @@ const digestOfSources = Effect.fn("digestOfSources")(function* (composable: Comp const clientPayloadOf = ( composable: ComposableSource[], digest: string, - facadePreload?: string[], + facadePreload?: Record, ): ComposePayload => ({ digest, remotes: composable.flatMap(({ source, manifest }) => { @@ -463,16 +462,20 @@ const clientPayloadOf = ( name: source.mfName, entry: source.uiEntry, ...(source.browserManifestUrl ? { manifestUrl: source.browserManifestUrl } : {}), - ...(source.key === CORE_UI_KEY && facadePreload?.length ? { preload: facadePreload } : {}), + ...(facadePreload?.[source.key]?.length ? { preload: facadePreload[source.key] } : {}), }, ]; }), 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[] { +/** The components-expose `sync` chunks from the mf-manifest — preload + * hints. */ +export function facadeChunkUrlsOf( + doc: unknown, + base: string, + exposeNames: Set = new Set(["components"]), +): string[] { if (!doc || typeof doc !== "object") return []; const exposes = (doc as { exposes?: unknown }).exposes; if (!Array.isArray(exposes)) return []; @@ -487,7 +490,7 @@ export function facadeChunkUrlsOf(doc: unknown, base: string): string[] { 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; + if (typeof name !== "string" || !exposeNames.has(name.replace(/^\.\//, ""))) continue; collect((assets as { js?: { sync?: unknown } } | undefined)?.js?.sync); } return [ @@ -507,22 +510,35 @@ function browserManifestUrlOf(source: UiSource): string | undefined { return base ? `${base}/${MF_MANIFEST_FILENAME}` : undefined; } -const coreFacadePreloadOf = Effect.fn("coreFacadePreloadOf")(function* ( - source: UiSource, +/** Preload chunk URLs per composed source declaring the components + * capability (`./components`, or a plugin's `./ui` — issue #1265). */ +const facadePreloadsOf = Effect.fn("facadePreloadsOf")(function* ( + composable: ComposableSource[], 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; + const out: Record = {}; + for (const { source, manifest } of composable) { + if (!manifest.components?.length) continue; + const url = browserManifestUrlOf(source); + if (!url) continue; + const cached = cache.facadePreload.get(url); + const now = yield* Clock.currentTimeMillis; + if (cached && now - cached.fetchedAt < MANIFEST_TTL_MS) { + if (cached.chunks.length > 0) out[source.key] = cached.chunks; + continue; + } + const chunks = yield* Effect.tryPromise(async () => { + const response = await runFetch(url); + if (!response.ok) throw new Error(`mf-manifest fetch ${response.status} for ${url}`); + const doc = JSON.parse(await response.text()); + const exposes = manifest.components ?? []; + const names = new Set(exposes.map((surface) => surface.expose.replace(/^\.\//, ""))); + return facadeChunkUrlsOf(doc, manifestBaseOf(url), names); + }).pipe(Effect.catch(() => Effect.succeed([] as string[]))); + cache.facadePreload.set(url, { chunks, fetchedAt: now }); + if (chunks.length > 0) out[source.key] = chunks; + } + return out; }); function rememberVariant( @@ -741,7 +757,7 @@ export const composeUi = Effect.fn("composeUi")(function* ( const digest = yield* digestOfSources(healthy); - const facadePreload = yield* coreFacadePreloadOf(core, cache); + const facadePreloads = yield* facadePreloadsOf(healthy, cache); const variantKey = `${digest}::${variantCacheKey(healthySources)}`; const isDev = healthySources.some((source) => source.localRoot); const now = yield* Clock.currentTimeMillis; @@ -797,7 +813,7 @@ export const composeUi = Effect.fn("composeUi")(function* ( routeTree: constructed.rootRoute, digest, nav: constructed.nav, - clientPayload: clientPayloadOf(healthy, digest, facadePreload), + clientPayload: clientPayloadOf(healthy, digest, facadePreloads), }; rememberVariant( cache, diff --git a/packages/every-plugin/src/build/ui/generated-config.ts b/packages/every-plugin/src/build/ui/generated-config.ts index 69d9c4fe4..1aff2286b 100644 --- a/packages/every-plugin/src/build/ui/generated-config.ts +++ b/packages/every-plugin/src/build/ui/generated-config.ts @@ -5,12 +5,13 @@ import { findBosConfigPath } from "../rspack/compose"; const UI_DIR = "ui"; const GENERATED_CONFIG_DIR = ".every-plugin"; const GENERATED_UI_CONFIG = "ui.rsbuild.config.generated.mjs"; +/** ADR 0010 §3: present — exposes `./ui` + the manifest capability. */ +const UI_EXPORTS_ENTRY = "src/ui-exports.ts"; /** * Folder-form UI source: a `ui/` directory with route files but no own - * package.json — the plugin workspace owns the build (single-workspace - * plugin, one dev process, one deploy train). Workspace-form ui sources - * (own package.json + scripts) are NOT managed here. + * package.json — the plugin workspace owns the build (one dev process, one + * deploy train). Workspace-form ui sources are NOT managed here. */ export function hasFolderFormUi(cwd: string): boolean { const uiDir = path.join(cwd, UI_DIR); @@ -24,26 +25,33 @@ export function uiDistDirFor(cwd: string): string { return path.join(cwd, UI_DIR, "dist"); } -function generatedUiConfig(pluginId: string): string { - return `import path from "node:path"; -import { createUiRsbuildConfig } from "every-plugin/build/ui"; -import pkg from "../package.json"; - -const workspaceRoot = path.resolve(import.meta.dirname, "..", "ui"); - -export default createUiRsbuildConfig({ - workspaceRoot, - pkg, - role: "consumer", - manifestName: ${JSON.stringify(pluginId)}, - devPort: Number(process.env.BOS_UI_PORT) || 0, - webEntry: "./ui/src/routeConfig.gen.ts", - webExposes: { "./routeConfig": "./ui/src/routeConfig.gen.ts" }, - nodeEntry: "./ui/src/routeConfig.gen.ts", - nodeExposes: { "./routeConfig": "./ui/src/routeConfig.gen.ts" }, - routesDirectory: "./ui/src/routes", -}); -`; +function generatedUiConfig(pluginId: string, componentExpose: string | null): string { + const uiExposeEntry = componentExpose ? `, "./ui": "./ui/${componentExpose}"` : ""; + const capabilityEntry = componentExpose + ? '\n componentExposeFiles: [{ expose: "./ui", file: "' + componentExpose + '" }],' + : ""; + return ( + [ + 'import path from "node:path";', + 'import { createUiRsbuildConfig } from "every-plugin/build/ui";', + 'import pkg from "../package.json";', + "", + 'const workspaceRoot = path.resolve(import.meta.dirname, "..", "ui");', + "", + "export default createUiRsbuildConfig({", + " workspaceRoot,", + " pkg,", + ' role: "consumer",', + " manifestName: " + JSON.stringify(pluginId) + ",", + " devPort: Number(process.env.BOS_UI_PORT) || 0,", + ' webEntry: "./ui/src/routeConfig.gen.ts",', + ' webExposes: { "./routeConfig": "./ui/src/routeConfig.gen.ts"' + uiExposeEntry + " },", + ' nodeEntry: "./ui/src/routeConfig.gen.ts",', + ' nodeExposes: { "./routeConfig": "./ui/src/routeConfig.gen.ts"' + uiExposeEntry + " },", + ].join("\n") + + capabilityEntry + + '\n routesDirectory: "./ui/src/routes",\n});\n' + ); } /** @@ -81,7 +89,10 @@ export function ensureGeneratedUiRsbuildConfig(cwd: string): string | null { const outDir = path.join(cwd, GENERATED_CONFIG_DIR); fs.mkdirSync(outDir, { recursive: true }); const outPath = path.join(outDir, GENERATED_UI_CONFIG); - const next = generatedUiConfig(pluginId); + const componentExpose = fs.existsSync(path.join(cwd, UI_DIR, UI_EXPORTS_ENTRY)) + ? UI_EXPORTS_ENTRY + : null; + const next = generatedUiConfig(pluginId, componentExpose); if (!fs.existsSync(outPath) || fs.readFileSync(outPath, "utf8") !== next) { fs.writeFileSync(outPath, next); } diff --git a/packages/everything-dev/src/services/codegen/artifacts.ts b/packages/everything-dev/src/services/codegen/artifacts.ts index 83bbdf4ef..6e9350ae9 100644 --- a/packages/everything-dev/src/services/codegen/artifacts.ts +++ b/packages/everything-dev/src/services/codegen/artifacts.ts @@ -47,8 +47,26 @@ interface UiManifestTarget { workspaceRoot: string; pluginName: string; emitRouteTree: boolean; + /** the source's component-expose convention file, when present */ + componentExposeFile?: { expose: string; file: string }; } +const UI_EXPORTS_ENTRY = "src/ui-exports.ts"; +const CORE_EXPOSE_ENTRY = "src/components/expose.ts"; + +/** The source's component-expose convention file — the core publishes + * `./components` from its primitives expose, a plugin publishes `./ui` from + * the ui-exports convention file (ADR 0010 §3, issue #1265). */ +const componentExposeFileOf = ( + workspaceRoot: string, + isCore: boolean, +): { expose: string; file: string } | undefined => { + const entry = isCore ? CORE_EXPOSE_ENTRY : UI_EXPORTS_ENTRY; + return existsSync(join(workspaceRoot, entry)) + ? { expose: isCore ? "./components" : "./ui", file: entry } + : undefined; +}; + export function uiManifestTargets( runtimeConfig: RuntimeConfig, forceRouteTree?: boolean, @@ -62,6 +80,7 @@ export function uiManifestTargets( emitRouteTree: forceRouteTree ? true : !existsSync(join(ui.localPath, "src/routeTree.gen.ts")), + componentExposeFile: componentExposeFileOf(ui.localPath, true), }); } const authUi = runtimeConfig.auth?.ui; @@ -81,7 +100,12 @@ export function uiManifestTargets( for (const [key, plugin] of Object.entries(runtimeConfig.plugins ?? {})) { const uiPath = plugin.ui?.localPath; if (plugin.ui?.source === "local" && uiPath && existsSync(join(uiPath, "src/routes"))) { - targets.push({ workspaceRoot: uiPath, pluginName: key, emitRouteTree: false }); + targets.push({ + workspaceRoot: uiPath, + pluginName: key, + emitRouteTree: false, + componentExposeFile: componentExposeFileOf(uiPath, false), + }); } } return targets; @@ -142,7 +166,15 @@ export const generateCodeArtifactsEffect = Effect.fn("generateCodeArtifacts")(fu }); } yield* Effect.tryPromise({ - try: () => generateUiManifest(target), + try: () => + generateUiManifest({ + workspaceRoot: target.workspaceRoot, + pluginName: target.pluginName, + emitRouteTree: target.emitRouteTree, + ...(target.componentExposeFile + ? { componentExposeFiles: [target.componentExposeFile] } + : {}), + }), catch: (cause) => new ArtifactGenError({ phase: `generate ui manifest (${target.pluginName})`, cause }), }); diff --git a/packages/everything-dev/src/services/codegen/ui-facade.ts b/packages/everything-dev/src/services/codegen/ui-facade.ts index 8c5b1e385..57bce6921 100644 --- a/packages/everything-dev/src/services/codegen/ui-facade.ts +++ b/packages/everything-dev/src/services/codegen/ui-facade.ts @@ -27,9 +27,41 @@ export class UiFacadeError extends Schema.TaggedError()("UiFacade } const FACADE_FILENAME = "src/ui.gen.ts"; +const REVERSE_FACADE_DIR = "src/ui-remote.gen"; const TYPES_TREE_DIRNAME = "src/lib/ui-types.gen"; const PROVIDER_GEN_DIR = join(".bos", "ui-types"); -const PROVIDER_KEY = CORE_UI_PLUGIN_KEY; + +export interface UiFacadeSource { + readonly key: string; + readonly root: string; + readonly entryRel: string; + readonly expose: string; + readonly relFromProject: string; +} + +export function facadeSourcesOf(config: RuntimeConfig, configDir: string): UiFacadeSource[] { + const sources: UiFacadeSource[] = []; + const push = (key: string, root: string, entryRel: string, expose: string): void => { + const relFromProject = relative(configDir, root).split("\\").join("/"); + if (!existsSync(join(root, entryRel))) return; + sources.push({ key, root, entryRel, expose, relFromProject }); + }; + if (config.ui?.source === "local" && config.ui.localPath) { + push( + CORE_UI_PLUGIN_KEY, + config.ui.localPath, + join("src", "components", "expose.ts"), + "./components", + ); + } + for (const [key, plugin] of Object.entries(config.plugins ?? {})) { + const ui = plugin?.ui; + if (ui?.source === "local" && ui.localPath) { + push(key, ui.localPath, join("src", "ui-exports.ts"), "./ui"); + } + } + return sources; +} export function uiFacadeConsumers(runtimeConfig: RuntimeConfig): UiFacadeConsumer[] { const providerPath = @@ -54,27 +86,19 @@ export function uiFacadeConsumers(runtimeConfig: RuntimeConfig): UiFacadeConsume }); } -function emitProviderDeclarations(providerRoot: string, projectRoot: string): string { - const entry = join(providerRoot, "src", "components", "expose.ts"); - if (!existsSync(entry)) { - throw new Error( - `the core ui provider publishes no components expose — expected src/components/expose.ts`, - ); - } - if (!existsSync(join(providerRoot, "tsconfig.json"))) { - throw new Error( - "the core ui provider workspace has no tsconfig.json — cannot emit declarations", - ); +function emitSourceDeclarations(source: UiFacadeSource, projectRoot: string): string { + const entry = join(source.root, source.entryRel); + if (!existsSync(join(source.root, "tsconfig.json"))) { + throw new Error(`ui source "${source.key}" has no tsconfig.json — cannot emit declarations`); } - const genDir = join(providerRoot, PROVIDER_GEN_DIR); + const genDir = join(PROVIDER_GEN_DIR, source.key); const outDir = join(genDir, "types"); const emittedEntry = join( outDir, - relative(projectRoot, join(providerRoot, "src")), - "components", - "expose.d.ts", + relative(projectRoot, source.root).split("\\").join("/"), + source.entryRel.replace(/\.tsx?$/, ".d.ts"), ); - const newestSource = newestSourceMtime(join(providerRoot, "src")); + const newestSource = newestSourceMtime(source.root); if (existsSync(emittedEntry) && statSync(emittedEntry).mtimeMs >= newestSource) { return outDir; } @@ -83,7 +107,7 @@ function emitProviderDeclarations(providerRoot: string, projectRoot: string): st join(genDir, "tsconfig.json"), `${JSON.stringify( { - extends: relative(genDir, join(providerRoot, "tsconfig.json")).split("\\").join("/"), + extends: relative(genDir, join(source.root, "tsconfig.json")).split("\\").join("/"), include: [relative(genDir, entry).split("\\").join("/")], compilerOptions: { noEmit: false, @@ -104,7 +128,7 @@ function emitProviderDeclarations(providerRoot: string, projectRoot: string): st ); if (result.status !== 0 || !existsSync(emittedEntry)) { throw new Error( - `declaration emit for the components barrel failed:\n${[result.stdout, result.stderr] + `declaration emit for "${source.key}" failed:\n${[result.stdout, result.stderr] .filter(Boolean) .join("\n")}`, ); @@ -269,8 +293,8 @@ interface FacadeSurface { readonly bare: Array<{ from: string; names: string[] }>; } -function facadeSurface(treeRoot: string): FacadeSurface { - const exposeDts = join(treeRoot, "components", "expose.d.ts"); +function facadeSurface(treeRoot: string, entryRel: string): FacadeSurface { + const exposeDts = join(treeRoot, entryRel.replace(/\.tsx?$/, ".d.ts")); const barrelDir = dirname(exposeDts); const surface: FacadeSurface = { components: [], types: [], bare: [] }; for (const entry of parseBarrelExports(readFileSync(exposeDts, "utf8"))) { @@ -290,16 +314,20 @@ function facadeSurface(treeRoot: string): FacadeSurface { return surface; } -function facadeContent(treeImportPath: string, surface: FacadeSurface): string { +function facadeContent( + source: { key: string; expose: string }, + treeImportPath: string, + surface: FacadeSurface, +): string { const lines: string[] = [ "// GENERATED FILE — do not edit. Regenerated by `bos types gen` / `bos dev` /", - "// `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 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.", + "// `bos build` (gitignored). Typed facade over the composed ui source", + `// "${source.key}" (${source.expose} expose — ADR 0059 §4, ADR 0064):`, + "// components resolve the source through the runtime compose payload, are", + "// typed against its 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 expose lands; hooks and helpers", + "// ride `loadComponents()` inside a client effect.", 'import { remoteComponent, remoteModule } from "everything-dev/ui/remote";', ]; if (surface.components.length > 0) { @@ -310,12 +338,12 @@ function facadeContent(treeImportPath: string, surface: FacadeSurface): string { lines.push(""); lines.push("export const loadComponents = () =>"); lines.push( - ` remoteModule("${PROVIDER_KEY}", "./components");`, + ` remoteModule("${source.key}", "${source.expose}");`, ); for (const name of surface.components) { lines.push(""); lines.push( - `export const ${name} = remoteComponent("${PROVIDER_KEY}", "./components", "${name}") as unknown as typeof ${aliasOf(name)};`, + `export const ${name} = remoteComponent("${source.key}", "${source.expose}", "${name}") as unknown as typeof ${aliasOf(name)};`, ); } for (const bare of surface.bare) { @@ -338,64 +366,86 @@ export const emitUiFacadesEffect = Effect.fn("emitUiFacades")(function* ( opts?: { strict?: boolean }, ): Effect.fn.Return { const result: UiFacadeResult = { generated: [], skipped: [] }; - const consumers = uiFacadeConsumers(runtimeConfig); - if (runtimeConfig.ui?.source !== "local" || !runtimeConfig.ui.localPath) { - for (const consumer of consumers) { - result.skipped.push( - `${consumer.name}: the active core ui provider is remote — no published component types to facade yet`, - ); - } - return result; - } - const providerRoot = runtimeConfig.ui.localPath; const projectRoot = resolve(configDir); - let outTree: string; - try { - outTree = emitProviderDeclarations(providerRoot, projectRoot); - } catch (cause) { - const detail = cause instanceof Error ? cause.message : String(cause); - for (const consumer of consumers) { - result.skipped.push(`${consumer.name}: ${detail}`); - } - if (opts?.strict) { - return yield* new UiFacadeError({ consumer: PROVIDER_KEY, cause: detail }); - } - console.warn(`[ui-facade] provider declarations skipped: ${detail}`); - return result; + const sources = facadeSourcesOf(runtimeConfig, projectRoot); + const consumers = uiFacadeConsumers(runtimeConfig); + + const workspaces = new Map(); + if (runtimeConfig.ui?.source === "local" && runtimeConfig.ui.localPath) { + workspaces.set(runtimeConfig.ui.localPath, "ui"); } - const providerRelFromRoot = relative(projectRoot, providerRoot).split("\\").join("/"); - for (const consumer of consumers) { + for (const consumer of consumers) workspaces.set(consumer.workspaceRoot, consumer.name); + + const failures: string[] = []; + const emitted = new Set(); + const declarationsBySource = new Map(); + for (const source of sources) { try { - const consumerTreeDir = join(consumer.workspaceRoot, TYPES_TREE_DIRNAME); - const consumerSrcInTree = join(consumerTreeDir, providerRelFromRoot, "src"); - let copied = 0; - for (const file of walkFiles(outTree)) { - const treePath = relative(outTree, file).split("\\").join("/"); - const target = join(consumerTreeDir, treePath); - const rewritten = rewriteAliasSpecifiers( - readFileSync(file, "utf8"), - target, - consumerSrcInTree, - ); - if (writeIfChanged(target, rewritten)) copied++; - } - const facadePath = join(consumer.workspaceRoot, FACADE_FILENAME); - const treeImportPath = `./lib/ui-types.gen/${providerRelFromRoot}/src/components/expose`; - if ( - writeIfChanged(facadePath, facadeContent(treeImportPath, facadeSurface(consumerSrcInTree))) - ) { - copied++; - } - if (copied > 0) { - result.generated.push(relativeOnCwd(facadePath)); - } + declarationsBySource.set(source.key, emitSourceDeclarations(source, projectRoot)); } catch (cause) { const detail = cause instanceof Error ? cause.message : String(cause); if (opts?.strict) { - return yield* new UiFacadeError({ consumer: consumer.name, cause: detail }); + return yield* new UiFacadeError({ consumer: source.key, cause: detail }); + } + console.warn(`[ui-facade] declarations for "${source.key}" skipped: ${detail}`); + failures.push(detail); + } + } + + for (const [workspaceRoot, consumerName] of workspaces) { + for (const source of sources) { + if (source.root === workspaceRoot) continue; + const outTree = declarationsBySource.get(source.key); + if (!outTree) continue; + const facadePath = + source.key === CORE_UI_PLUGIN_KEY + ? join(workspaceRoot, FACADE_FILENAME) + : join(workspaceRoot, REVERSE_FACADE_DIR, `$${source.key}`, "ui", "index.ts"); + const dedupeKey = `${facadePath}`; + try { + const consumerTreeDir = join(workspaceRoot, TYPES_TREE_DIRNAME); + const consumerSrcInTree = join(consumerTreeDir, source.relFromProject, "src"); + let copied = 0; + for (const file of walkFiles(outTree)) { + const treePath = relative(outTree, file).split("\\").join("/"); + const target = join(consumerTreeDir, treePath); + const rewritten = rewriteAliasSpecifiers( + readFileSync(file, "utf8"), + target, + consumerSrcInTree, + ); + if (writeIfChanged(target, rewritten)) copied++; + } + const facadeDir = dirname(facadePath); + const upRaw = relative(facadeDir, join(workspaceRoot, "src", "lib")) + .split("\\") + .join("/"); + const up = upRaw.startsWith(".") ? upRaw : `./${upRaw}`; + const treeImportPath = `${up}/ui-types.gen/${source.relFromProject}/${source.entryRel.replace(/\.tsx?$/, "")}`; + if ( + writeIfChanged( + facadePath, + facadeContent( + source, + treeImportPath, + facadeSurface(consumerSrcInTree, source.entryRel.replace(/^src\//, "")), + ), + ) + ) { + copied++; + } + if (copied > 0 && !emitted.has(dedupeKey)) { + emitted.add(dedupeKey); + result.generated.push(relativeOnCwd(facadePath)); + } + } catch (cause) { + const detail = cause instanceof Error ? cause.message : String(cause); + if (opts?.strict) { + return yield* new UiFacadeError({ consumer: consumerName, cause: detail }); + } + console.warn(`[ui-facade] ${consumerName} <- ${source.key} skipped: ${detail}`); + result.skipped.push(`${consumerName} <- ${source.key}: ${detail}`); } - console.warn(`[ui-facade] ${consumer.name} skipped: ${detail}`); - result.skipped.push(`${consumer.name}: ${detail}`); } } return result; diff --git a/plugins/ai/ui/tsconfig.json b/plugins/ai/ui/tsconfig.json index 3fec97d8c..86b646e8a 100644 --- a/plugins/ai/ui/tsconfig.json +++ b/plugins/ai/ui/tsconfig.json @@ -23,7 +23,8 @@ "noUncheckedSideEffectImports": true, "paths": { "@/ui": ["./src/ui.gen.ts"], - "@/*": ["./src/*"] + "@/*": ["./src/*"], + "/*": ["./src/ui-remote.gen/*"] } } } diff --git a/plugins/auth/ui/tsconfig.json b/plugins/auth/ui/tsconfig.json index 3fec97d8c..86b646e8a 100644 --- a/plugins/auth/ui/tsconfig.json +++ b/plugins/auth/ui/tsconfig.json @@ -23,7 +23,8 @@ "noUncheckedSideEffectImports": true, "paths": { "@/ui": ["./src/ui.gen.ts"], - "@/*": ["./src/*"] + "@/*": ["./src/*"], + "/*": ["./src/ui-remote.gen/*"] } } } diff --git a/plugins/deployments/ui/tsconfig.json b/plugins/deployments/ui/tsconfig.json index 3fec97d8c..86b646e8a 100644 --- a/plugins/deployments/ui/tsconfig.json +++ b/plugins/deployments/ui/tsconfig.json @@ -23,7 +23,8 @@ "noUncheckedSideEffectImports": true, "paths": { "@/ui": ["./src/ui.gen.ts"], - "@/*": ["./src/*"] + "@/*": ["./src/*"], + "/*": ["./src/ui-remote.gen/*"] } } } diff --git a/plugins/docs/ui/src/components/docs/nav-tree.tsx b/plugins/docs/ui/src/components/docs/nav-tree.tsx index 551dcd5eb..bdc7bff81 100644 --- a/plugins/docs/ui/src/components/docs/nav-tree.tsx +++ b/plugins/docs/ui/src/components/docs/nav-tree.tsx @@ -2,7 +2,7 @@ import { CaretDownIcon } from "@phosphor-icons/react"; import { Link } from "@tanstack/react-router"; import type { NavNodeShape } from "../../../../src/contract"; -interface NavTreeProps { +export interface NavTreeProps { nodes: readonly NavNodeShape[]; currentSlug?: string; depth?: number; diff --git a/plugins/docs/ui/src/ui-exports.ts b/plugins/docs/ui/src/ui-exports.ts new file mode 100644 index 000000000..99857feb0 --- /dev/null +++ b/plugins/docs/ui/src/ui-exports.ts @@ -0,0 +1,2 @@ +export { NavTree, type NavTreeProps } from "./components/docs/nav-tree"; +export { StatusBadge, type StatusBadgeProps } from "./components/docs/status-badge"; diff --git a/plugins/docs/ui/tsconfig.json b/plugins/docs/ui/tsconfig.json index 3fec97d8c..86b646e8a 100644 --- a/plugins/docs/ui/tsconfig.json +++ b/plugins/docs/ui/tsconfig.json @@ -23,7 +23,8 @@ "noUncheckedSideEffectImports": true, "paths": { "@/ui": ["./src/ui.gen.ts"], - "@/*": ["./src/*"] + "@/*": ["./src/*"], + "/*": ["./src/ui-remote.gen/*"] } } } diff --git a/ui/tsconfig.json b/ui/tsconfig.json index 3b7208811..451d74f75 100644 --- a/ui/tsconfig.json +++ b/ui/tsconfig.json @@ -28,7 +28,8 @@ } ], "paths": { - "@/*": ["./src/*"] + "@/*": ["./src/*"], + "/*": ["./src/ui-remote.gen/*"] } } } From 9a1a317fd3eb76399a944014b3c16016523ecfe2 Mon Sep 17 00:00:00 2001 From: elliotBraem <16282460+elliotBraem@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:41:50 -0600 Subject: [PATCH 2/2] =?UTF-8?q?fix(everything-dev,every-plugin,ui):=20reve?= =?UTF-8?q?rse-facade=20review=20=E2=80=94=20load=20by=20container=20name,?= =?UTF-8?q?=20narrow=20/$*=20mapping,=20package-only=20bare=20re-exports?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review findings on the reverse facade (issue #1265): 1. remoteModule resolved loadRemote by the COMPOSITION KEY while the runtime registers containers by MF container name (hydrate + self-registration both use remote.name) — every source whose key differs from its container name (deployments vs deployments-ui, docs vs _everything_dev_docs_plugin) failed client loads with #RUNTIME-004. remoteModule now resolves the payload by key (or name) and loads by container name; server-side resolution already mapped key -> entry correctly. 2. The generated tsconfig mapping narrowed from /* to /$* — a bare /* would shadow absolute-style /x imports across the workspace. 3. Facades re-export only package specifiers: a workspace-alias bare re-export (@/..., #/...) in a source barrel would have resolved against the CONSUMER's tree — wrong types or a missing module. 4. The loadRemote-by-key behavior the old unit test encoded is corrected to assert the container-name load; rationale recorded in ADR 0064. --- docs/adr/0064-facade-ssr-and-primitive-expose.md | 10 ++++++++++ .../everything-dev/src/services/codegen/ui-facade.ts | 2 +- packages/everything-dev/src/ui/remote.tsx | 6 +++--- packages/everything-dev/tests/unit/ui-remote.test.ts | 1 + plugins/ai/ui/tsconfig.json | 2 +- plugins/auth/ui/tsconfig.json | 2 +- plugins/deployments/ui/tsconfig.json | 2 +- plugins/docs/ui/tsconfig.json | 2 +- ui/tsconfig.json | 2 +- 9 files changed, 20 insertions(+), 9 deletions(-) diff --git a/docs/adr/0064-facade-ssr-and-primitive-expose.md b/docs/adr/0064-facade-ssr-and-primitive-expose.md index 6aef590e2..8c202c1dd 100644 --- a/docs/adr/0064-facade-ssr-and-primitive-expose.md +++ b/docs/adr/0064-facade-ssr-and-primitive-expose.md @@ -83,6 +83,16 @@ The scaffold prune protects the expose file: a child runtime acts as its own pro and `bos mf check` gates the capability against the expose, so pruning it would break the child's own facade contract. +## Load semantics (review finding, same PR) + +Consumer facades address sources by composition key; the runtime registers +containers by MF container name, and the two differ (`deployments` vs +`deployments-ui`). `remoteModule` therefore resolves the compose payload by +key (or name) and loads by container name — `loadRemote` never sees the key. +Facades re-export only package specifiers (a workspace-alias `@/...` bare +re-export would resolve against the consumer's tree), and the generated +tsconfig mapping is `/$*` — a bare `/*` would shadow absolute-style imports. + ## Consequences - Facade components render in the SSR document; the docs search input and settings tabs diff --git a/packages/everything-dev/src/services/codegen/ui-facade.ts b/packages/everything-dev/src/services/codegen/ui-facade.ts index 57bce6921..1909298cf 100644 --- a/packages/everything-dev/src/services/codegen/ui-facade.ts +++ b/packages/everything-dev/src/services/codegen/ui-facade.ts @@ -305,7 +305,7 @@ function facadeSurface(treeRoot: string, entryRel: string): FacadeSurface { const origin = resolveExportOrigin(barrelDir, entry); if (origin.kind === "component") { surface.components.push(entry.name); - } else if (origin.kind === "bare") { + } else if (origin.kind === "bare" && !/^[@#]\//.test(origin.from)) { const bare = surface.bare.find((candidate) => candidate.from === origin.from); if (bare) bare.names.push(entry.name); else surface.bare.push({ from: origin.from, names: [entry.name] }); diff --git a/packages/everything-dev/src/ui/remote.tsx b/packages/everything-dev/src/ui/remote.tsx index fb95fe83b..18a26a311 100644 --- a/packages/everything-dev/src/ui/remote.tsx +++ b/packages/everything-dev/src/ui/remote.tsx @@ -71,16 +71,16 @@ async function resolveServerModule( } 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`, + `remote module "${providerName}/${normalizeExpose(expose)}" cannot load on the server — no SSR compose session is registered; read non-component values in a client effect`, ); } return loaded; } + const moduleId = `${composeRemoteOf(providerName).name}/${normalizeExpose(expose)}`; const { loadRemote } = await import("@module-federation/enhanced/runtime"); try { await ensureProviderRegistered(providerName); @@ -91,7 +91,7 @@ export async function remoteModule(providerName: string, expose: string): Pro return loaded as T; } catch (error) { throw new Error( - `remote module "${moduleId}" failed to load: ${error instanceof Error ? error.message : String(error)}`, + `remote module "${providerName}/${normalizeExpose(expose)}" failed to load as "${moduleId}": ${error instanceof Error ? error.message : String(error)}`, { cause: error }, ); } diff --git a/packages/everything-dev/tests/unit/ui-remote.test.ts b/packages/everything-dev/tests/unit/ui-remote.test.ts index d4344152f..3bd2c8d1f 100644 --- a/packages/everything-dev/tests/unit/ui-remote.test.ts +++ b/packages/everything-dev/tests/unit/ui-remote.test.ts @@ -92,6 +92,7 @@ describe("remoteModule", () => { const mod = await remoteModule<{ Button: unknown }>("ui-key-match", "./components"); expect(mod.Button).toBeDefined(); + expect(loadRemote).toHaveBeenCalledWith("tenant-ui-cdn/components", { from: "build" }); expect(registerRemotes).toHaveBeenCalledWith([ { name: "tenant-ui-cdn", diff --git a/plugins/ai/ui/tsconfig.json b/plugins/ai/ui/tsconfig.json index 86b646e8a..cf1f65ebc 100644 --- a/plugins/ai/ui/tsconfig.json +++ b/plugins/ai/ui/tsconfig.json @@ -24,7 +24,7 @@ "paths": { "@/ui": ["./src/ui.gen.ts"], "@/*": ["./src/*"], - "/*": ["./src/ui-remote.gen/*"] + "/$*": ["./src/ui-remote.gen/$*"] } } } diff --git a/plugins/auth/ui/tsconfig.json b/plugins/auth/ui/tsconfig.json index 86b646e8a..cf1f65ebc 100644 --- a/plugins/auth/ui/tsconfig.json +++ b/plugins/auth/ui/tsconfig.json @@ -24,7 +24,7 @@ "paths": { "@/ui": ["./src/ui.gen.ts"], "@/*": ["./src/*"], - "/*": ["./src/ui-remote.gen/*"] + "/$*": ["./src/ui-remote.gen/$*"] } } } diff --git a/plugins/deployments/ui/tsconfig.json b/plugins/deployments/ui/tsconfig.json index 86b646e8a..cf1f65ebc 100644 --- a/plugins/deployments/ui/tsconfig.json +++ b/plugins/deployments/ui/tsconfig.json @@ -24,7 +24,7 @@ "paths": { "@/ui": ["./src/ui.gen.ts"], "@/*": ["./src/*"], - "/*": ["./src/ui-remote.gen/*"] + "/$*": ["./src/ui-remote.gen/$*"] } } } diff --git a/plugins/docs/ui/tsconfig.json b/plugins/docs/ui/tsconfig.json index 86b646e8a..cf1f65ebc 100644 --- a/plugins/docs/ui/tsconfig.json +++ b/plugins/docs/ui/tsconfig.json @@ -24,7 +24,7 @@ "paths": { "@/ui": ["./src/ui.gen.ts"], "@/*": ["./src/*"], - "/*": ["./src/ui-remote.gen/*"] + "/$*": ["./src/ui-remote.gen/$*"] } } } diff --git a/ui/tsconfig.json b/ui/tsconfig.json index 451d74f75..5b12b3e6d 100644 --- a/ui/tsconfig.json +++ b/ui/tsconfig.json @@ -29,7 +29,7 @@ ], "paths": { "@/*": ["./src/*"], - "/*": ["./src/ui-remote.gen/*"] + "/$*": ["./src/ui-remote.gen/$*"] } } }