Files
clean-architecture-frontend…/tests/unit/runtime-adapters.test.ts
T
DongHyeonka b96d61d8f7 feat(examples)!: 예제 화면 3개를 끌 수 있는 기능으로 옮긴다
문제
/examples/ui, /examples/states, /examples/auth(와 /examples/platform)는
플랫폼 라우트 레지스트리에 고정이었다. VITE_PRODUCT_FEATURES와
FEATURE_OVERRIDES는 기능만 빼므로 제품은 이 화면을 끌 수 없었다.
릴리스 게이트 FE-GATE-028은 ROUTE_REGISTRY의 모든 라우트에 서명된
수동 접근성 기록을 요구해서, 제품은 템플릿 갤러리를 운영 메뉴에 두고
서명하거나 템플릿 파일 5개와 src/presentation/examples/를 지워야 했다.

고른 방법
- UI 갤러리·화면 상태·인증 연동을 platform-examples-feature로 옮겼다.
  자기 context platform-examples-context(루트 examples/*)에 산다.
  reference-context의 examples/reference-resources/*와 플랫폼 라우트
  /examples/platform이 더 구체적이라 그 URL은 그대로 간다.
- 라우트 ID·경로·청크 ID·표면은 바꾸지 않았다. 시각·e2e 테스트와 a11y
  기록(artifacts/tests/a11y-manual/EXAMPLES_*.md)이 그대로 이 이름을
  쓴다. 기능을 빼면 a11y 목록은 ROUTE_REGISTRY에서 오므로 같이 빠진다.
- 실행부는 비어 있다(스키마·adapter·계약 기여 없음). 페이지는 context
  routes에서 페이지마다 lazy로 받는다.
- 플랫폼 구성 화면(EXAMPLES_PLATFORM)은 플랫폼 라우트로 남겼다. 처음에는
  같이 옮겼다. 같은 호스트·같은 부하(15~19)에서 d99301b와 번갈아 잰
  lab이 기능 라우트로는 443·432 ms FAIL이었다(d99301b 133·183 ms
  PASS). 기능 라우트의 첫 진입은 context routes 모듈을 받은 뒤에 페이지
  청크를 받는다(요청 추적: 939 B + 177 B 다음에 5,183 B + 3개). 페이지를
  routes 모듈에 정적으로 넣으면 릴리스 매니페스트의 routeChunks 계약
  (페이지마다 dynamic entry)이 깨진다. 15-01의 "예산을 올리지 않는다"를
  지키려고 이 한 화면은 남겼다.
- 홈 화면은 예제 라우트 ID를 적지 않는다. 내비게이션의 처음 세 화면을
  "{title} 보기"로 보여 준다. 템플릿에서는 예전과 같은 세 링크(플랫폼
  구성·UI 구성요소·화면 상태)가 나오고, 예제를 뺀 제품에서는 그 제품의
  화면이 나온다. home.starter.platform·ui·states 키를 home.starter.open
  하나로 바꿨다. VITE_PRODUCT_FEATURES=none 빌드 검사
  (product-feature-selection-build)가 홈 청크의 예제 라우트 ID를 잡았다.
- 예제 화면 component 테스트는 tests/features/platform-examples-feature/로
  옮겼다. 제거 드릴이 같이 지운다. runtime-adapters 테스트는 API가 있는
  기능만 센다(예제 기능은 API가 없다). context-route-roots 테스트의
  "플랫폼 라우트와 같은 경로" 예는 /examples/platform으로 바꿨다.
- old-tab-chunk-recovery e2e는 페이지 소스를 빌드 A의 Vite manifest에서
  찾는다(기능 폴더 이름을 적지 않음). UI 갤러리가 기능 라우트라 B 탭이
  잃는 청크는 그 context routes 모듈이다. 허용 패턴에 넣었다.
- 예제 화면 문구는 08-07대로 한국어 고정이다. 화면 문구 ESLint 규칙의
  예외에 새 폴더를 넣었다.
- 버린 대안: 빌드 변수로 숨김(선택 장치가 하나 더 생김), 예제 화면만
  제품이 지우게 둠(동기화 충돌 자리가 남음).

위험·한계
- 공개 경로가 바뀌었다. src/presentation/examples/{ui-gallery,
  state-gallery,auth-example}-page.tsx, PLATFORM_ROUTE_REGISTRY·
  PLATFORM_ROUTE_RUNTIME(_CONTRACT)의 EXAMPLES_UI·STATES·AUTH,
  home.starter.platform/ui/states 키를 쓰던 다운스트림은 깨진다.
- 플랫폼 구성 화면은 여전히 끌 수 없고 FE-GATE-028 서명 대상이다.
- tests/e2e와 tests/visual의 여러 spec이 예제 화면을 자기 페이지로 쓴다.
  예제를 뺀 제품은 그 spec을 자기 화면으로 바꾸거나 지워야 한다
  (starter-experience.md에 적음). 제거 드릴은 브라우저 테스트를 돌리지
  않아 이것을 보지 않는다.
- 예제 기능 제거 드릴은 16-02(빈 ciScripts로 CI 기준선 사유가 공백)
  때문에 그대로는 시작하자마자 실패한다. 아래 드릴 결과는 그 한 줄을
  임시로 고친 상태에서 낸 것이다(커밋하지 않음).
- 기능 라우트 첫 진입이 이 lab 조건에서 약 430 ms라는 것은 어느 게이트도
  재지 않는다.

검증
- product-feature-selection-build(VITE_PRODUCT_FEATURES=none 빌드):
  홈 청크의 예제 라우트 ID 3건으로 실패한 것을 확인하고 홈 화면을 고친
  뒤 통과.
- test:sample-removal -- --feature=platform-examples-feature(heavy lock,
  16-02 한 줄 임시 패치): PASS, 13 checks(typecheck, architecture,
  registries, test:all, coverage, test-evidence, ci, home-smoke, build,
  route-absent, 잔여 ID 0). 첫 시도에서는 lab-performance 단위 테스트가
  측정 라우트 조회가 포트 검사보다 먼저여서 실패했다(그 뒤 이 변경에서
  측정 라우트를 플랫폼에 남겨 조회 변경 자체를 뺐다).
- test:unit 2,587, test:component 253, tests/features·platform·
  architecture 383 통과. check:types, lint, check:architecture,
  check:i18n, check:registries(additive), verify:documentation 통과.
- test:e2e 세 엔진 187 passed, 3 skipped(Firefox SW quarantine).
  old-tab-chunk-recovery 포함. test:a11y 60 passed.
- build + check:bundle: 초기 JS 201,940 / 204,800 B(+92 B).
- lab(측정 라우트를 기능으로 옮긴 시도): 443·432 ms FAIL, 같은 묶음
  d99301b 133·183 ms PASS(부하 15~19). 남긴 뒤 136·134 ms PASS.

Refs: docs/reviews/2026-11-03-maturity-review/09-app-core.md 09-04
BREAKING CHANGE: 예제 라우트 EXAMPLES_UI·EXAMPLES_STATES·EXAMPLES_AUTH가
플랫폼 레지스트리에서 platform-examples-feature로 옮겨졌다. 페이지 파일은
src/features/platform-examples-feature/presentation/으로 갔고,
PLATFORM_ROUTE_REGISTRY·PLATFORM_ROUTE_RUNTIME_CONTRACT·
PLATFORM_ROUTE_RUNTIME에 이 키들이 없다. 홈 문구 키
home.starter.platform·ui·states는 home.starter.open({title})로 바뀌었다.
예제를 지운 다운스트림은 이 기능 폴더와 context를 지우면 된다.
2026-11-04 22:59:03 +09:00

498 lines
16 KiB
TypeScript

import { describe, expect, it, vi } from "vitest";
import { createRuntimeAdapters } from "../../src/bootstrap/runtime-adapters.ts";
import { createBrowserMutationIntentFactory } from "../../src/adapters/platform/browser-mutation-intent-factory.ts";
import { createApplication } from "../../src/application/create-application.ts";
import type { ApplicationFeatureId } from "../../src/application/ports/in/application-api.ts";
import { loadFeatureRuntime } from "../../src/features/feature-module.ts";
import { INSTALLED_PRODUCT_FEATURE_MODULES } from "../../src/features/installed-product-manifest.ts";
type Runtime = Parameters<typeof createRuntimeAdapters>[0]["runtime"];
type Release = Parameters<typeof createRuntimeAdapters>[0]["release"];
const runtime: Runtime = {
config: {
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
TELEMETRY_ENABLED: false,
AUTH_MODE: "demo",
REQUEST_TIMEOUT_MS: 4321,
MAX_RETRY_ATTEMPTS: 0,
RELEASE_MANIFEST_URL: "/release-manifest.json",
CONFIG_SCHEMA_VERSION: "2.0",
CAPABILITY_OVERRIDES: {
REALTIME: "DEFAULT",
WEB_WORKER: "DEFAULT",
SERVICE_WORKER: "DEFAULT",
OFFLINE_COMMANDS: "DEFAULT",
},
FEATURE_OVERRIDES: {},
},
configSchema: "V2",
build: {
buildId: "build-a",
commitSha: "abc123",
routerBasePath: "/",
runtimeConfigUrl: "/config.json",
},
validationDurationMs: 0,
};
const release: Release = {
schemaVersion: 2,
appVersion: "0.1.0",
buildId: "build-a",
commitSha: "abc123",
configSchemaVersion: "2.0",
contractSet: {
setAlgorithm: "CA_CONTRACT_SET_V1",
setDigest: `sha256:${"0".repeat(64)}`,
packages: [],
},
assetManifestHash: "hash-a",
releaseId: "release-a",
builtAt: "2026-07-25T00:00:00Z",
routeChunks: { "route-home": "assets/home.js" },
};
/**
* 1103/09-04. The installed features that contribute an application API. The
* template's example screens call none: loading them
* installs no input.
*/
const API_FEATURE_IDS: readonly string[] = (
await Promise.all(
INSTALLED_PRODUCT_FEATURE_MODULES.map(async (module) =>
(await loadFeatureRuntime(module)).adapters.length > 0 ? [module.id] : [],
),
)
).flat();
describe("runtime adapter composition", () => {
it("creates validated intent and idempotency identities with independent UUID calls", () => {
const randomUUID = vi
.fn<() => string>()
.mockReturnValueOnce("intent-uuid")
.mockReturnValueOnce("idempotency-uuid");
const factory = createBrowserMutationIntentFactory({
randomUUID,
monotonicNow: () => 12.5,
});
const intent = factory.create({
operationId: "CREATE_ENTITY",
canonicalInputIdentity: "opaque-canonical-input",
requiresIdempotencyKey: true,
});
expect(intent).toEqual({
intentId: "intent-uuid",
operationId: "CREATE_ENTITY",
canonicalInputIdentity: "opaque-canonical-input",
idempotencyKey: "idempotency-uuid",
createdAtMonotonicMs: 12.5,
});
expect(Object.isFrozen(intent)).toBe(true);
expect(randomUUID).toHaveBeenCalledTimes(2);
});
it("rejects invalid or unbounded mutation intent values", () => {
const factory = createBrowserMutationIntentFactory({
randomUUID: () => "opaque-runtime-identifier",
monotonicNow: () => 1,
});
expect(() =>
factory.create({
operationId: " ",
canonicalInputIdentity: "valid-identity",
requiresIdempotencyKey: false,
}),
).toThrow(TypeError);
expect(() =>
factory.create({
operationId: "CREATE_ENTITY",
canonicalInputIdentity: "x".repeat(16_385),
requiresIdempotencyKey: false,
}),
).toThrow(TypeError);
expect(() =>
createBrowserMutationIntentFactory({
randomUUID: () => "opaque-runtime-identifier",
monotonicNow: () => -1,
}).create({
operationId: "CREATE_ENTITY",
canonicalInputIdentity: "valid-identity",
requiresIdempotencyKey: false,
}),
).toThrow(TypeError);
});
it("constructs the local demo seam and infrastructure adapters", async () => {
const adapters = await createRuntimeAdapters({
runtime,
release,
host: {},
});
expect(adapters.outputPorts.session.getState()).toBe("unauthenticated");
await expect(adapters.outputPorts.releaseInfo.getCurrent()).resolves.toMatchObject({
releaseId: "release-a",
});
expect(adapters.infrastructure.queryClient).toBeDefined();
expect(adapters.infrastructure.queryInvalidation).toBeDefined();
expect(adapters.infrastructure.mutationIntentFactory).toBeDefined();
expect(
adapters.infrastructure.crossContextInvalidationStatus(),
).toBe("DEGRADED_LOCAL_ONLY");
expect(adapters.outputPorts.diagnostics.record).toEqual(expect.any(Function));
expect(adapters.outputPorts.telemetry.emit).toEqual(expect.any(Function));
expect(adapters.outputPorts.telemetry.pendingCount()).toBe(0);
expect(adapters).not.toHaveProperty("http");
expect(adapters).not.toHaveProperty("storage");
adapters.infrastructure.dispose();
});
it("runtime infrastructure disposal disposes telemetry first", async () => {
const fetcher = vi.fn(async () => new Response(null, { status: 204 }));
const adapters = await createRuntimeAdapters({
runtime: {
...runtime,
config: {
...runtime.config,
TELEMETRY_ENABLED: true,
TELEMETRY_ENDPOINT: "https://telemetry.test/events",
},
} as Runtime,
release,
host: {},
fetcher: fetcher as unknown as typeof fetch,
});
adapters.outputPorts.telemetry.emit("api.request.failed", {
error_kind: "SERVER_FAILURE",
http_status_group: "5xx",
attempt_count_bucket: "1",
route_id: "TEST_ROUTE",
});
expect(adapters.outputPorts.telemetry.pendingCount()).toBe(1);
adapters.infrastructure.dispose();
expect(adapters.outputPorts.telemetry.pendingCount()).toBe(0);
await Promise.resolve();
await Promise.resolve();
expect(fetcher).not.toHaveBeenCalled();
});
it("sends telemetry stamped with the release identity (13-11)", async () => {
const bodies: { events: Record<string, unknown>[] }[] = [];
const fetcher = vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
if (String(_url) === "https://telemetry.test/events") {
bodies.push(JSON.parse(String(init?.body)));
}
return new Response(null, { status: 204 });
});
const adapters = await createRuntimeAdapters({
runtime: {
...runtime,
config: {
...runtime.config,
TELEMETRY_ENABLED: true,
TELEMETRY_ENDPOINT: "https://telemetry.test/events",
},
} as Runtime,
release,
host: {},
fetcher: fetcher as unknown as typeof fetch,
});
adapters.outputPorts.telemetry.emit("api.request.failed", {
error_kind: "SERVER_FAILURE",
http_status_group: "5xx",
attempt_count_bucket: "1",
route_id: "TEST_ROUTE",
});
await adapters.outputPorts.telemetry.flush();
expect(bodies[0]?.events[0]).toMatchObject({
eventName: "api.request.failed",
build_id: "build-a",
release_id: "release-a",
});
adapters.infrastructure.dispose();
});
it("replaces the QueryClient and coordinator for each session generation", async () => {
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
const previousClient = adapters.infrastructure.queryClient;
const previousCoordinator = adapters.infrastructure.queryInvalidation;
const runtimeMutationIntentFactory =
adapters.infrastructure.mutationIntentFactory;
const clearPrevious = vi.spyOn(previousClient, "clear");
await adapters.outputPorts.session.beginSignIn();
await vi.waitFor(() =>
expect(adapters.infrastructure.queryClient).not.toBe(previousClient),
);
expect(adapters.infrastructure.queryInvalidation).not.toBe(
previousCoordinator,
);
expect(adapters.infrastructure.mutationIntentFactory).toBe(
runtimeMutationIntentFactory,
);
const clearCallsAfterReplacement = clearPrevious.mock.calls.length;
await previousCoordinator.resetLocal();
expect(clearPrevious).toHaveBeenCalledTimes(clearCallsAfterReplacement);
adapters.infrastructure.dispose();
});
it("does not fail boot when Web Storage capability getters throw", async () => {
const host: Record<string, unknown> = {};
Object.defineProperties(host, {
localStorage: {
get() {
throw new DOMException("denied", "SecurityError");
},
},
sessionStorage: {
get() {
throw new DOMException("denied", "SecurityError");
},
},
});
const adapters = await createRuntimeAdapters({
runtime,
release,
host,
});
expect(adapters.infrastructure.queryClient).toBeDefined();
expect(adapters.outputPorts.preferences.read("COLOR_SCHEME")).toEqual({
ok: true,
value: undefined,
});
adapters.infrastructure.dispose();
});
it("fails closed when an external auth owner was not installed", async () => {
const adapters = await createRuntimeAdapters({
runtime: {
...runtime,
config: { ...runtime.config, AUTH_MODE: "external" },
},
release,
host: {},
});
expect(adapters.outputPorts.session.getState()).toBe("integration-failed");
});
describe("installed external auth owner shape", () => {
const externalRuntime: Runtime = {
...runtime,
config: { ...runtime.config, AUTH_MODE: "external" },
};
const completeOwner = () => ({
readState: () => "authenticated",
readSubject: () => "user-a",
subscribe: () => () => {},
beginSignIn: async () => {},
signOut: async () => {},
attachCredential: async () => ({ headers: {} }),
recoverSession: async () => "no-session",
notifyUnauthenticated: () => {},
});
it("uses an owner that implements every method", async () => {
const adapters = await createRuntimeAdapters({
runtime: externalRuntime,
release,
host: { __CA_FRONTEND_AUTH_OWNER__: completeOwner() },
});
expect(adapters.outputPorts.session.getState()).toBe("authenticated");
expect(adapters.outputPorts.session.getSubject()).toBe("user-a");
adapters.infrastructure.dispose();
});
it.each(["readSubject", "readState"])(
"fails closed when the owner lacks %s",
async (method) => {
const owner: Record<string, unknown> = completeOwner();
delete owner[method];
const adapters = await createRuntimeAdapters({
runtime: externalRuntime,
release,
host: { __CA_FRONTEND_AUTH_OWNER__: owner },
});
expect(adapters.outputPorts.session.getState()).toBe(
"integration-failed",
);
adapters.infrastructure.dispose();
},
);
});
it("reports the static selection when no capability override disables it", async () => {
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
const snapshot = adapters.outputPorts.runtimeCapabilities.getSnapshot();
expect(snapshot.map((status) => status.capabilityId)).toEqual([
"REALTIME",
"WEB_WORKER",
"SERVICE_WORKER",
"OFFLINE_COMMANDS",
]);
expect(snapshot.every((status) => status.override === "DEFAULT")).toBe(true);
});
it("carries a disabling override into the capability snapshot", async () => {
const adapters = await createRuntimeAdapters({
runtime: {
...runtime,
config: {
...runtime.config,
CAPABILITY_OVERRIDES: {
...runtime.config.CAPABILITY_OVERRIDES,
SERVICE_WORKER: "DISABLED",
},
FEATURE_OVERRIDES: {},
},
},
release,
host: {},
});
const serviceWorker = adapters.outputPorts.runtimeCapabilities
.getSnapshot()
.find((status) => status.capabilityId === "SERVICE_WORKER");
expect(serviceWorker?.override).toBe("DISABLED");
expect(serviceWorker?.active).toBe(0);
});
it("gives a feature switched off by FEATURE_OVERRIDES no application API (Q-6.9-5)", async () => {
const [disabledId, ...activeIds] = API_FEATURE_IDS;
const adapters = await createRuntimeAdapters({
runtime: {
...runtime,
config: {
...runtime.config,
FEATURE_OVERRIDES: { [disabledId!]: "DISABLED" },
},
},
release,
host: {},
});
const application = createApplication(
adapters.outputPorts,
{},
adapters.featureLoaders,
);
expect(adapters.outputPorts.productFeatures.isActive(disabledId!)).toBe(false);
// 15-01. A switched-off feature gets no loader, so loading installs nothing.
await application.features.load(disabledId!);
expect(application.features.has(disabledId!)).toBe(false);
expect(() =>
application.features.get(disabledId as ApplicationFeatureId),
).toThrow(/not installed/u);
for (const featureId of activeIds) {
await application.features.load(featureId);
expect(application.features.has(featureId)).toBe(true);
}
adapters.infrastructure.dispose();
});
it("still resolves every installed feature API when nothing is switched off", async () => {
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
const application = createApplication(
adapters.outputPorts,
{},
adapters.featureLoaders,
);
for (const featureId of API_FEATURE_IDS) {
// 15-01. Not loaded until the router asks for the feature's routes.
expect(() =>
application.features.get(featureId as ApplicationFeatureId),
).toThrow(/not loaded yet/u);
await application.features.load(featureId);
expect(application.features.has(featureId)).toBe(true);
expect(
application.features.get(featureId as ApplicationFeatureId),
).toBeDefined();
}
adapters.infrastructure.dispose();
});
it("states contract identity as a digest for a V2 release manifest", async () => {
const adapters = await createRuntimeAdapters({ runtime, release, host: {} });
const current = await adapters.outputPorts.releaseInfo.getCurrent();
expect(current.contractSetDigest).toBe(release.contractSet?.setDigest);
expect(current.apiContractVersion).toBeUndefined();
expect(current).not.toHaveProperty("contractSet");
});
it("states contract identity as the legacy scalar for a V1 release manifest", async () => {
const adapters = await createRuntimeAdapters({
runtime,
release: {
...release,
schemaVersion: 1,
contractSet: null,
legacyApiContractVersion: "1.4",
},
host: {},
});
const current = await adapters.outputPorts.releaseInfo.getCurrent();
expect(current.apiContractVersion).toBe("1.4");
expect(current.contractSetDigest).toBeUndefined();
expect(current).not.toHaveProperty("legacyApiContractVersion");
});
it("refetches the active release manifest with no-store semantics", async () => {
const activeRelease = {
...release,
buildId: "build-b",
releaseId: "release-b",
routeChunks: { "route-home": "assets/home-b.js" },
};
const fetcher = vi.fn(async () =>
new Response(JSON.stringify(activeRelease), {
headers: { "content-type": "application/json" },
}),
);
const adapters = await createRuntimeAdapters({
runtime,
release,
fetcher,
host: {},
});
await expect(adapters.outputPorts.releaseInfo.refresh()).resolves.toMatchObject({
buildId: "build-b",
releaseId: "release-b",
});
expect(fetcher).toHaveBeenCalledWith(
"/release-manifest.json",
expect.objectContaining({
method: "GET",
cache: "no-store",
credentials: "same-origin",
redirect: "error",
referrerPolicy: "no-referrer",
headers: { Accept: "application/json" },
}),
);
});
});