import { matchRoutes } from "react-router-dom"; import { contractRoutePaths, type BoundedContextModule, } from "../contexts/bounded-context-module.ts"; import { assertWithinCardinalityBudget } from "../platform/cardinality/cardinality-budget.ts"; export type DeployableAppModule = Readonly<{ id: string; contexts: readonly Context[]; budget: Readonly<{ maxContexts: number }>; }>; export function defineDeployableAppModule( definition: Readonly<{ id: string; contexts: readonly Context[]; budget: Readonly<{ maxContexts: number }>; }>, ): DeployableAppModule { assertWithinCardinalityBudget( `${definition.id}.contexts`, definition.contexts.length, definition.budget.maxContexts, ); const seen = new Set(); for (const context of definition.contexts) { if (seen.has(context.id)) { throw new TypeError(`Duplicate ${definition.id}.contexts child id: ${context.id}`); } seen.add(context.id); } assertFeatureRoutesReachOwningContext(definition.contexts); return Object.freeze({ ...definition, contexts: Object.freeze([...definition.contexts]), budget: Object.freeze({ ...definition.budget }), }); } /** * 09-06. The router mounts one gateway per context at its route root and * renders a feature route only inside that gateway, while the route registry * and navigation list every feature route wherever it points. A route its * owning root does not reach (outside the root, at the platform home, or * under another context's identical or more specific root) would be a menu * link to NOT_FOUND. Matching uses the router's own ranking, so nested roots * stay allowed as long as each route lands in its owner. Platform routes are * not checked here. */ function assertFeatureRoutesReachOwningContext( contexts: readonly BoundedContextModule[], ): void { const roots = contexts.flatMap((context) => context.route ? [{ id: context.id, path: context.route.path }] : [], ); for (const context of contexts) { for (const feature of context.features) { for (const [routeId, path] of contractRoutePaths(feature.contracts)) { const reached = matchRoutes(roots, path)?.[0]?.route; if (reached?.id === context.id) continue; throw new TypeError( `Route ${routeId} (${path}) of feature ${feature.id} is not under the route root of its context ${context.id} (${context.route?.path ?? "no route root"}): ` + (reached ? `context ${reached.id} (${reached.path}) takes that URL.` : "the router would answer NOT_FOUND."), ); } } } }