Files
clean-architecture-frontend…/tests/component/runtime-composition-service-worker-product-wiring.test.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

163 lines
5.0 KiB
TypeScript

// @vitest-environment jsdom
import { describe, expect, it, vi } from "vitest";
import { createRuntimeComposition } from "../../src/bootstrap/create-runtime-composition.ts";
import type { ProductComposition } from "../../src/bootstrap/product-composition-contract.ts";
/**
* 1103/09-05. A product that turns the worker on wires its activation blockers
* (a tab with unsaved edits) and the page controller's observer in its own
* `product-composition.ts`, not in the template's composition file. This runs
* the real composition with an ACTIVE selection, a product composition that
* returns `serviceWorker`, and a registration whose update is waiting.
*/
const product = vi.hoisted(() => ({
observed: [] as Array<Readonly<{ event: string; outcome: string }>>,
dirty: true,
}));
vi.mock("../../src/features/installed-runtime-capabilities.ts", async (importOriginal) => {
const original =
await importOriginal<typeof import("../../src/features/installed-runtime-capabilities.ts")>();
return {
INSTALLED_RUNTIME_CAPABILITIES: Object.freeze({
...original.INSTALLED_RUNTIME_CAPABILITIES,
serviceWorker: Object.freeze({
mode: "ACTIVE",
scriptPath: "service-worker.js",
handlers: Object.freeze(["PWA_STATIC_ASSETS"]),
}),
}),
};
});
/** The product's `src/bootstrap/product-composition.ts`. */
vi.mock("../../src/bootstrap/product-composition.ts", () => ({
composeProductSessionOwner: () => null,
composeProduct: (): ProductComposition => ({
capabilities: {},
credentialProviders: {},
serviceWorker: {
blockers: [() => product.dirty],
observe(observation) {
product.observed.push(observation);
// The composition drops a throwing product sink.
throw new Error("product sink failure");
},
},
}),
}));
const origin = "http://localhost";
const runtimeConfig = {
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
REQUEST_TIMEOUT_MS: 10_000,
MAX_RETRY_ATTEMPTS: 2,
TELEMETRY_ENABLED: false,
AUTH_MODE: "demo",
CONFIG_SCHEMA_VERSION: "1",
API_CONTRACT_VERSION: "1",
RELEASE_MANIFEST_URL: "/release-manifest.json",
BUILD_ID: "local-build",
RELEASE_ID: "local-release",
};
const releaseManifest = {
schemaVersion: 1,
appVersion: "0.2.0",
buildId: "local-build",
commitSha: "local",
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: "test-hash",
releaseId: "local-release",
builtAt: "2026-07-26T00:00:00.000Z",
routeChunks: {
"route-home": "assets/home.js",
"route-examples-ui": "assets/ui.js",
"route-examples-states": "assets/states.js",
"route-examples-auth": "assets/auth.js",
"route-not-found": "assets/not-found.js",
},
};
async function fetcher(input: RequestInfo | URL): Promise<Response> {
const url =
typeof input === "string"
? input
: input instanceof URL
? input.href
: input.url;
return Response.json(
url.includes("release-manifest") ? releaseManifest : runtimeConfig,
);
}
/** This page's worker is active and the next build's is waiting. */
function updateWaitingContainer(): ServiceWorkerContainer {
const worker = (scriptURL: string, state: string) => ({
scriptURL,
state,
postMessage: vi.fn(),
addEventListener() {},
removeEventListener() {},
});
const register = vi.fn(
async (scriptURL: string | URL, options?: RegistrationOptions) => {
const script = new URL(scriptURL, origin).href;
return {
scope: new URL(options?.scope ?? "/", origin).href,
installing: null,
waiting: worker(script, "installed"),
active: worker(script, "activated"),
addEventListener() {},
removeEventListener() {},
update: vi.fn(async () => {}),
} as unknown as ServiceWorkerRegistration;
},
);
return {
controller: null,
register,
getRegistration: vi.fn(async () => undefined),
getRegistrations: vi.fn(async () => []),
addEventListener() {},
removeEventListener() {},
} as unknown as ServiceWorkerContainer;
}
describe("1103/09-05 the product wires the worker in product-composition.ts", () => {
it("passes the product's blockers and observer to the page controller", async () => {
const container = updateWaitingContainer();
const composition = await createRuntimeComposition({
fetcher,
host: {
location: { origin },
navigator: { serviceWorker: container },
},
});
try {
await composition.optional.startAfterMount();
expect(container.register).toHaveBeenCalledTimes(1);
expect(product.observed).toEqual([
{ event: "register", outcome: "UPDATE_WAITING" },
]);
await expect(
composition.optional.serviceWorker!.requestActivation(),
).resolves.toEqual({ kind: "BLOCKED_DIRTY_CLIENT" });
expect(product.observed.at(-1)).toEqual({
event: "activation",
outcome: "BLOCKED_DIRTY_CLIENT",
});
} finally {
await composition.dispose();
}
});
});