Files
clean-architecture-frontend…/src/bootstrap/create-runtime-composition.ts
T
DongHyeonka fdc1db9471 feat(bootstrap): 제품이 SW blockers·observe를 composeProduct로 넘긴다
문제: SW를 켜는 선택은 제품 소유 `product-capabilities.ts`로 옮겼다
(1103/09-05 일부). 그런데 저장하지 않은 편집이 있는 탭의 활성화 거절
(`blockers`)과 page controller 관측(`observe`)은 템플릿 소유
`src/bootstrap/create-runtime-composition.ts`를 고쳐야 이어진다(매뉴얼 03
"SW 켜기", 레시피 "Service Worker를 켤 때 확인할 것" 2·3). 그 파일을 고친
제품은 템플릿 동기화마다 충돌한다.

고른 방법: 기존 제품 확장 지점에 선택 칸 하나를 더한다.
`ProductComposition.serviceWorker?: { blockers?, observe? }`
(`product-composition-contract.ts`). `createRuntimeAdapters`가 `composeProduct`
결과의 이 칸을 bundle에 `productServiceWorker`로 싣고, 템플릿 조립
(`create-runtime-composition.ts`)이 telemetry와 같은 방식으로 받아
`createOptionalRuntimeHost`에 넘긴다. blockers 목록은 한 번 복사한다. 던지는
blocker는 page controller가 이미 막는 쪽으로 본다. page controller는
`observe`의 throw를 잡지 않으므로, 제품 sink가 던져도 worker 흐름이 바뀌지
않게 조립에서 감쌌다. 매뉴얼 03과 레시피 2·3을 새 자리로 고쳤다.
버린 대안:
- `product-composition.ts`에 새 export(`composeProductServiceWorker`)를 요구.
  이미 그 파일을 가진 다운스트림이 동기화하면 import가 깨진다. 선택 칸은
  기존 `composeProduct`를 그대로 둔다.
- `composeProduct`를 조립에서 한 번 더 부르기. capability와 credential이 두
  벌 생긴다.

위험·한계: 일부만 닫는다. 남은 것:
- 활성화 화면(`onUpdateWaiting`·`requestActivation()`)과 reload 안내를 이을
  제품 소유 자리가 없다(레시피 4·5, 0925/06-05).
- realtime·Web Worker·오프라인 명령은 여전히 조립이 거절한다
  (`optional-runtime-host.ts`, 그 런타임이 템플릿에 없다).
`product-composition.ts`(제품 소유, 출하 상태 빈 값)는 고치지 않았다. 칸이
선택이라 기존 제품 파일과 1105/09-01의 타입 검사 탐침 내용이 그대로
통과한다.

검증: desktop batch에서 확인.
- node scripts/run-vitest.ts run tests/component/runtime-composition-service-worker-product-wiring.test.ts tests/component/runtime-composition-service-worker-telemetry.test.ts
- RED: "passes the product's blockers and observer to the page controller"가
  옛 조립에서 observe 기록이 비어 실패한다.
- 함께: check:types, lint, check:architecture, verify:documentation

Refs: 1103/09-05
2026-11-05 22:19:06 +09:00

116 lines
4.2 KiB
TypeScript

import { resolveRuntimeCapabilities } from "../contracts/runtime-capabilities.ts";
import { INSTALLED_RUNTIME_CAPABILITIES } from "../features/installed-runtime-capabilities.ts";
import type { TelemetryPort } from "../application/ports/telemetry-port.ts";
import { createCompositionRoot } from "./composition-root.ts";
import { loadReleaseManifest } from "./load-release-manifest.ts";
import { loadRuntimeConfig } from "./load-runtime-config.ts";
import {
createOptionalRuntimeHost,
type OptionalRuntimeHost,
type OptionalRuntimeHostInput,
} from "./optional-runtime-host.ts";
import type { ProductServiceWorkerWiring } from "./product-composition-contract.ts";
import { createRuntimeAdapters } from "./runtime-adapters.ts";
export type RuntimeCompositionDependencies = Readonly<{
fetcher?: typeof fetch;
host?: Record<string, unknown>;
}>;
/**
* §6.7 steps 7 and 14. The static capability selection is compiled against the
* runtime overrides, and the optional host objects are created without any
* start side effect. Nothing observable happens until the first committed React
* effect calls `optional.startAfterMount()`.
*/
export async function createRuntimeComposition(
dependencies: RuntimeCompositionDependencies = {},
) {
// 06-05. The optional host reports a Service Worker that did not start
// through the same telemetry port as the application.
let telemetry: TelemetryPort | undefined;
// 1103/09-05. `composeProduct` (product-owned) supplies the worker's
// blockers and observer; this template file only passes them on.
let productServiceWorker: ProductServiceWorkerWiring | null | undefined;
const root = await createCompositionRoot({
loadConfig: () => loadRuntimeConfig({ fetcher: dependencies.fetcher }),
loadRelease: (runtime) =>
loadReleaseManifest(runtime, { fetcher: dependencies.fetcher }),
createAdapters: async ({ config: runtime, release }) => {
const adapters = await createRuntimeAdapters({
runtime,
release,
fetcher: dependencies.fetcher,
host: dependencies.host,
});
telemetry = adapters.outputPorts.telemetry;
productServiceWorker = adapters.productServiceWorker;
return adapters;
},
});
const capabilities = resolveRuntimeCapabilities(
INSTALLED_RUNTIME_CAPABILITIES,
root.config.config.CAPABILITY_OVERRIDES,
);
const optional: OptionalRuntimeHost = createOptionalRuntimeHost({
capabilities,
routerBasePath: root.config.build.routerBasePath,
buildId: root.release.buildId,
...(telemetry ? { telemetry } : {}),
...serviceWorkerWiring(productServiceWorker),
...(dependencies.host
? {
host: dependencies.host as Parameters<
typeof createOptionalRuntimeHost
>[0]["host"],
}
: {}),
});
return Object.freeze({
...root,
capabilities,
optional,
async dispose(): Promise<void> {
// §20.3. Optional runtime first, then the base infrastructure: the query
// cache is cleared only after realtime and worker admission has closed,
// so a late effect cannot repopulate a cleared cache.
await optional.stop("APPLICATION_SHUTDOWN");
root.infrastructure.dispose();
},
});
}
export type RuntimeComposition = Awaited<
ReturnType<typeof createRuntimeComposition>
>;
/**
* 1103/09-05. The product's wiring in the optional host's terms. The blocker
* list is copied once; the page controller already treats a throwing blocker
* as blocking. A throwing observer is product code and must not break the
* worker flow, so its throw is dropped here.
*/
function serviceWorkerWiring(
wiring: ProductServiceWorkerWiring | null | undefined,
): Pick<OptionalRuntimeHostInput, "blockers" | "observe"> {
if (!wiring) return {};
return {
...(wiring.blockers
? { blockers: Object.freeze([...wiring.blockers]) }
: {}),
...(wiring.observe
? {
observe: (observation: Readonly<{ event: string; outcome: string }>) => {
try {
wiring.observe?.(observation);
} catch {
// A failing product sink never changes the worker's outcome.
}
},
}
: {}),
};
}