Files
clean-architecture-frontend…/tests/architecture/context-route-roots.test.ts
T
DongHyeonka 846955498d fix(apps): 두 기능 라우트가 같은 경로를 쓰면 조립 때 막는다 (1101/14.4)
문제: 7d85589는 플랫폼 라우트가 가리는 기능 라우트를 막지만, 기능 라우트
둘이 같은 경로를 쓰는 경우는 막지 않는다. 라우터는 순위가 같은 경로를
선언 순서로 고르므로 뒤의 라우트는 그려지지 않는다. 메뉴와 레지스트리에는
그 라우트가 나온다. 파라미터 이름(`:orderId`와 `:itemId`)은 순위를
바꾸지 않으므로 이름만 다른 경로도 같은 경로다. R-B가 남긴 것으로 보고했다.

고른 방법: 같은 함수(assertFeatureRoutesReachOwningContext)에서 플랫폼
검사를 통과한 라우트마다 파라미터 이름을 지운 경로 모양을 기록하고, 이미
있으면 두 라우트와 기능 이름을 담아 throw한다. 앱 모듈을 평가할 때
실패하므로 09-06·09-03 검사와 같이 fail-closed다. APP_HOME 대체는 이
함수의 앞쪽 continue로 빠지고, 두 기능이 같은 플랫폼 라우트를 가져가는
경우는 기존 검사(withoutTakenOverPlatformRoutes)가 막는다.
버린 대안: 레지스트리 검사(check:routes)에서 경로 중복 보기. 그 검사는
route ID 중복만 보고, 라우터가 실제로 어떤 순위로 고르는지는 모른다.

위험·한계: 일부만 겹치는 경로(`/a/new`와 `/a/:id`)는 라우터가 정적 경로를
먼저 고르므로 막지 않는다. 그 경우는 accepts 테스트로 고정했다. splat(`*`)
기능 라우트끼리의 겹침은 모양 비교로만 본다.

검증:
- RED: 새 테스트 2건 중 "같은 경로 거절"이 실패(22/23 통과)
- GREEN: tests/architecture와 라우트 component 테스트 75건 통과
- tests/unit·component·integration·features 253파일 3,153건 통과
- tsc app·test, eslint 통과
2026-11-03 20:32:46 +09:00

356 lines
12 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { defineDeployableAppModule } from "../../src/apps/deployable-app-module.ts";
import { defineBoundedContextModule } from "../../src/contexts/bounded-context-module.ts";
import { withoutTakenOverPlatformRoutes } from "../../src/contracts/routes.ts";
import { defineFeatureModule } from "../../src/features/feature-module.ts";
/**
* 09-06. The router mounts one gateway per context at its route root and
* renders a feature route only inside it, while the registry and navigation
* list every feature route. A route its owning root does not reach is a menu
* link to NOT_FOUND, so composing the app has to refuse it.
*/
function feature(id: string, paths: Readonly<Record<string, string>>) {
const routes = Object.fromEntries(
Object.entries(paths).map(([routeId, path]) => [routeId, { routeId, path }]),
);
return defineFeatureModule({
id,
contracts: { featureId: id, routes },
routes,
messages: {},
loadRuntime: async () => ({
featureId: id,
apiContract: {},
adapters: [],
contractContributions: [],
}),
});
}
function context(
id: string,
path: string,
features: readonly ReturnType<typeof feature>[],
loadLayout?: () => Promise<() => null>,
) {
return defineBoundedContextModule({
id,
features,
budget: { maxFeatures: 10 },
route: { path, loadRoutes: async () => [], ...(loadLayout ? { loadLayout } : {}) },
});
}
function app(...contexts: readonly ReturnType<typeof context>[]) {
return defineDeployableAppModule({
id: "shop-app",
contexts,
budget: { maxContexts: 10 },
});
}
describe("feature routes and their context route root", () => {
it("accepts routes at and under the owning context root", () => {
expect(() =>
app(
context("shop-context", "shop/*", [
feature("shop-feature", {
SHOP_ITEMS: "/shop",
SHOP_ITEM: "/shop/items/:itemId",
SHOP_NEW: "/shop/items/new",
}),
]),
),
).not.toThrow();
});
it("rejects a route outside the owning root, naming the feature, route and root", () => {
// E2: the menu would list /catalog and the URL would render NOT_FOUND.
expect(() =>
app(
context("shop-context", "shop/*", [
feature("shop-feature", {
SHOP_ITEMS: "/shop/items",
SHOP_CATALOG: "/catalog",
}),
]),
),
).toThrow(/SHOP_CATALOG.*\/catalog.*shop-feature.*shop-context.*shop\/\*/);
});
it("rejects a feature route at the platform home", () => {
expect(() =>
app(
context("shop-context", "shop/*", [
feature("shop-feature", { SHOP_HOME: "/" }),
]),
),
).toThrow(/SHOP_HOME/);
});
it("accepts the platform home a feature replaces whatever its root (09-03)", () => {
// The router mounts a replaced platform route at its own path.
expect(() =>
app(
context("home-context", "home/*", [
feature("home-feature", { APP_HOME: "/", HOME_FEED: "/home/feed" }),
]),
),
).not.toThrow();
});
it("rejects a route whose feature belongs to a context without a route root", () => {
expect(() =>
app(
defineBoundedContextModule({
id: "silent-context",
features: [feature("silent-feature", { SILENT: "/silent" })],
budget: { maxFeatures: 10 },
}),
),
).toThrow(/SILENT.*silent-feature.*silent-context/);
});
it("rejects a second context on the same root, which the router never reaches", () => {
// E5: the first context's gateway takes every URL under shop/*.
expect(() =>
app(
context("shop-a", "shop/*", [feature("feature-a", { A: "/shop/a" })]),
context("shop-b", "shop/*", [feature("feature-b", { B: "/shop/b" })]),
),
).toThrow(/B.*\/shop\/b.*feature-b.*shop-b.*shop-a/);
});
it("accepts nested roots when each route resolves to its own context", () => {
expect(() =>
app(
context("items", "fixture/items/*", [
feature("list", { LIST: "/fixture/items" }),
]),
context("status", "fixture/items/status/*", [
feature("status", { STATUS: "/fixture/items/status" }),
]),
),
).not.toThrow();
});
it("rejects a route a nested root of another context takes over", () => {
expect(() =>
app(
context("items", "fixture/items/*", [
feature("list", { DETAIL: "/fixture/items/status/detail" }),
]),
context("status", "fixture/items/status/*", [
feature("status", { STATUS: "/fixture/items/status" }),
]),
),
).toThrow(/DETAIL.*list.*items.*status/);
});
});
/**
* 09-03. Several context roots may sit under one layout, and layouts are
* siblings of AppShell at `/`: a root still takes the URLs under it whatever
* layout either context has, so the rule above spans every layout.
*/
describe("context route roots under layouts", () => {
const siteLayout = async () => () => null;
const studioLayout = async () => () => null;
it("accepts several roots under one layout and nested roots across layouts", () => {
expect(() =>
app(
context("site", "*", [feature("site", { APP_HOME: "/", EXPLORE: "/explore" })], siteLayout),
context("topics", "topics/*", [feature("topics", { TOPICS: "/topics" })], siteLayout),
context("studio", "studio/*", [feature("studio", { STUDIO: "/studio" })], studioLayout),
context("shop", "shop/*", [feature("shop", { SHOP: "/shop" })]),
),
).not.toThrow();
});
it("rejects a route another layout's root takes over", () => {
expect(() =>
app(
context("site", "*", [feature("site", { DRAFTS: "/studio/drafts" })], siteLayout),
context("studio", "studio/*", [feature("studio", { STUDIO: "/studio" })], studioLayout),
),
).toThrow(/DRAFTS.*site.*studio \(studio\/\*\)/);
});
});
/**
* 09-03 (1101/14.4). AppShell mounts the platform routes ahead of every
* context, so a feature route a platform route also answers is never
* rendered: the router picks the platform route without an error. Only the
* home a feature takes over by its id is allowed.
*/
describe("feature routes and platform routes", () => {
const layout = async () => () => null;
it("rejects a feature route at a platform route's path, naming both", () => {
expect(() =>
app(
context("examples", "examples/*", [
feature("examples-feature", { EXAMPLES_UI_COPY: "/examples/ui" }),
]),
),
).toThrow(/EXAMPLES_UI_COPY.*\/examples\/ui.*examples-feature.*examples.*EXAMPLES_UI/);
});
it("rejects the same path under a layout of its own", () => {
// Layout routes sit after AppShell, so the tie goes to the platform.
expect(() =>
app(
context("examples", "examples/*", [
feature("examples-feature", { EXAMPLES_UI_COPY: "/examples/ui" }),
], layout),
),
).toThrow(/EXAMPLES_UI_COPY.*EXAMPLES_UI/);
});
it("rejects two feature routes with the same path, naming both", () => {
// The router ranks equal paths by order, so the second is never rendered.
// Parameter names do not change the rank.
expect(() =>
app(
context("shop", "shop/*", [
feature("orders", { ORDER_DETAIL: "/shop/items/:orderId" }),
feature("items", { ITEM_DETAIL: "/shop/items/:itemId" }),
]),
),
).toThrow(/ITEM_DETAIL.*\/shop\/items\/:itemId.*items.*ORDER_DETAIL.*orders/);
});
it("accepts a static path next to a parameter at the same depth", () => {
expect(() =>
app(
context("shop", "shop/*", [
feature("items", {
ITEM_NEW: "/shop/items/new",
ITEM_DETAIL: "/shop/items/:itemId",
}),
]),
),
).not.toThrow();
});
it("rejects `/` under another id, which the platform home answers", () => {
expect(() =>
app(context("site", "*", [feature("site", { SITE_HOME: "/" })], layout)),
).toThrow(/SITE_HOME.*\/.*site.*APP_HOME/);
});
it("rejects a `*` root without a layout, which NOT_FOUND answers", () => {
// AppShell's NOT_FOUND splat comes before the context's `*` gateway.
expect(() =>
app(context("site", "*", [feature("site", { EXPLORE: "/explore" })])),
).toThrow(/EXPLORE.*\/explore.*site.*NOT_FOUND/);
});
it("accepts `/` once a feature took over the platform home", () => {
expect(() =>
app(
context("site", "*", [feature("site", { APP_HOME: "/", EXPLORE: "/explore" })], layout),
context("examples", "examples/*", [
feature("examples-feature", { EXAMPLES_REFERENCE: "/examples/reference" }),
]),
),
).not.toThrow();
});
});
/** 09-03. The platform names the routes a feature may take over; one feature may. */
describe("replaceable platform routes", () => {
const contract = (featureId: string, ...routeIds: string[]) => ({
featureId,
routes: Object.fromEntries(routeIds.map((routeId) => [routeId, {}])),
});
const platform = { APP_HOME: "platform home", NOT_FOUND: "platform not found" };
it("drops the platform routes a feature took over and keeps the rest", () => {
expect(
withoutTakenOverPlatformRoutes(platform, [contract("site", "APP_HOME", "EXPLORE")]),
).toEqual({ NOT_FOUND: "platform not found" });
expect(withoutTakenOverPlatformRoutes(platform, [contract("shop", "SHOP")])).toEqual(platform);
});
it("keeps a platform route the platform does not let features take over", () => {
// The registry composition then refuses the duplicate id as before.
expect(
withoutTakenOverPlatformRoutes(platform, [contract("shop", "NOT_FOUND")]),
).toEqual(platform);
});
it("rejects a second feature taking over the same platform route, naming both", () => {
expect(() =>
withoutTakenOverPlatformRoutes(platform, [
contract("site", "APP_HOME"),
contract("blog", "APP_HOME"),
]),
).toThrow(/APP_HOME.*site.*blog/);
});
});
/**
* 09-06 (3). The gateway renders the registered route a loaded route's handle
* names. A handle no feature of the context declares in its contract fails
* when the context's routes load, not later when that URL renders.
*/
describe("context route handles and their features' contract routes", () => {
function contextLoading(
features: readonly ReturnType<typeof feature>[],
handles: readonly unknown[],
) {
const loadRoutes = vi.fn(async () =>
handles.map((handle, index) => ({
id: `route-${index}`,
path: `/shop/${index}`,
handle,
})),
);
const module = defineBoundedContextModule({
id: "shop-context",
features,
budget: { maxFeatures: 10 },
route: { path: "shop/*", loadRoutes },
});
return { module, loadRoutes };
}
it("loads routes whose handles name the context's contract routes", async () => {
const { module } = contextLoading(
[
feature("shop-feature", { SHOP_ITEMS: "/shop/items" }),
feature("cart-feature", { CART: "/shop/cart" }),
],
[{ routeId: "SHOP_ITEMS" }, { routeId: "CART" }],
);
await expect(module.route?.loadRoutes()).resolves.toHaveLength(2);
});
it("rejects an unregistered handle at load, naming the feature and route ids", async () => {
// E7: a typo in context-routes.ts used to surface only as a context
// boundary failure when that URL rendered.
const { module, loadRoutes } = contextLoading(
[feature("shop-feature", { SHOP_ITEMS: "/shop/items" })],
[{ routeId: "SHOP_ITEMS" }, { routeId: "SHOP_ITEMSS" }],
);
// Defining the context still does not load its routes.
expect(loadRoutes).not.toHaveBeenCalled();
await expect(module.route?.loadRoutes()).rejects.toThrow(
/SHOP_ITEMSS.*shop-context.*shop-feature/,
);
});
it("rejects a handle without a route id", async () => {
const { module } = contextLoading(
[feature("shop-feature", { SHOP_ITEMS: "/shop/items" })],
[{ runtime: {} }],
);
await expect(module.route?.loadRoutes()).rejects.toThrow(/shop-feature/);
});
});