문제
워커 보호 장치 넷은 지워도 테스트가 모두 통과한다(1101/06-04, 이번
리뷰에서 다시 생존). install fetch의 credentials: "omit"·redirect:
"error"(M1), activate nonce 한 번만 쓰기(M3), 요청받지 않은 client의
CLIENT_DRAINED 거절(M9), 첫 설치를 "업데이트 대기"로 알리지 않기(N8).
고른 방법
- service-worker-runtime.test.ts에 테스트 3건을 더한다.
- install이 자산마다 cache no-store, credentials omit, redirect error로
요청한다(M1).
- 같은 nonce의 두 번째 ACTIVATE_REQUEST는 REJECTED, 요청받지 않은
client의 drain 응답은 세지 않는다(M3, M9).
- active 워커가 없는 첫 설치는 onUpdateWaiting을 부르지 않는다(N8).
- 동작은 바꾸지 않는다.
위험·한계
- N8 테스트는 시작 뒤 registration.active를 null로 바꿔 첫 설치를
흉내 낸다. 실제 브라우저 첫 설치 순서는 e2e가 본다.
검증
- service-worker-runtime 64건 통과.
- 변이 4건(M1·M3·M9·N8)을 하나씩 넣어 각각 1건 실패를 확인하고
되돌렸다.
- 바꾼 파일 eslint, check:types:test 통과.
Refs: docs/reviews/2026-11-03-maturity-review/06-adapters-service-worker-push.md 2절 1101/06-04
2099 lines
70 KiB
TypeScript
2099 lines
70 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import { createServiceWorkerPageController } from "../../src/adapters/service-worker/service-worker-page-controller.ts";
|
|
import { createServiceWorkerRuntime } from "../../src/adapters/service-worker/service-worker-lifecycle.ts";
|
|
import { createServiceWorkerMessage } from "../../src/adapters/service-worker/service-worker-protocol.ts";
|
|
import {
|
|
classifyFetch,
|
|
installStaticAssets,
|
|
} from "../../src/adapters/service-worker/service-worker-static-assets.ts";
|
|
import { createServiceWorkerRuntimeHost } from "../../src/bootstrap/register-service-worker.ts";
|
|
import { resolveRuntimeCapabilities } from "../../src/contracts/runtime-capabilities.ts";
|
|
import {
|
|
SERVICE_WORKER_BOUNDS,
|
|
SERVICE_WORKER_SCRIPT_PATH,
|
|
STATIC_CACHE_PREFIX,
|
|
staticCacheName,
|
|
type ServiceWorkerProtocolIdentity,
|
|
type StaticAssetManifestV1,
|
|
} from "../../src/contracts/service-worker.ts";
|
|
|
|
const ORIGIN = "https://app.example";
|
|
const SCRIPT_URL = `${ORIGIN}/service-worker.js`;
|
|
|
|
/** A `ServiceWorker` stand-in that can fire `statechange`. */
|
|
function fakeWorker(
|
|
messages: unknown[] = [],
|
|
state: ServiceWorkerState = "activated",
|
|
) {
|
|
return Object.assign(new EventTarget(), {
|
|
scriptURL: SCRIPT_URL,
|
|
state,
|
|
postMessage(message: unknown) {
|
|
messages.push(message);
|
|
},
|
|
});
|
|
}
|
|
|
|
function setWorkerState(
|
|
worker: ReturnType<typeof fakeWorker>,
|
|
state: ServiceWorkerState,
|
|
) {
|
|
worker.state = state;
|
|
worker.dispatchEvent(new Event("statechange"));
|
|
}
|
|
|
|
function pageContainer(
|
|
options: { waiting?: boolean; controlled?: boolean; installing?: boolean } = {},
|
|
) {
|
|
const listeners = new Set<(event: MessageEvent) => void>();
|
|
const waitingMessages: unknown[] = [];
|
|
const controllerMessages: unknown[] = [];
|
|
const worker = (messages: unknown[], state?: ServiceWorkerState) =>
|
|
fakeWorker(messages, state) as unknown as ServiceWorker;
|
|
const waiting = options.waiting ? worker(waitingMessages, "installed") : null;
|
|
// A first visit: `register()` resolves while the only worker is installing.
|
|
const installing = options.installing ? fakeWorker([], "installing") : null;
|
|
const active = options.waiting || options.installing ? null : worker([]);
|
|
const controlled = options.controlled ? worker(controllerMessages) : null;
|
|
const registration = Object.assign(new EventTarget(), {
|
|
scope: `${ORIGIN}/`,
|
|
installing,
|
|
waiting,
|
|
active,
|
|
update: vi.fn(async () => {}),
|
|
}) as unknown as ServiceWorkerRegistration;
|
|
const container = {
|
|
controller: controlled,
|
|
register: vi.fn(async () => registration),
|
|
addEventListener(_type: string, listener: (event: MessageEvent) => void) {
|
|
listeners.add(listener);
|
|
},
|
|
removeEventListener(_type: string, listener: (event: MessageEvent) => void) {
|
|
listeners.delete(listener);
|
|
},
|
|
} as unknown as ServiceWorkerContainer;
|
|
return {
|
|
container,
|
|
waiting,
|
|
installing,
|
|
controlled,
|
|
registration,
|
|
waitingMessages,
|
|
controllerMessages,
|
|
listenerCount: () => listeners.size,
|
|
dispatch(data: unknown, source?: { postMessage(message: unknown): void }) {
|
|
const event = { data, origin: ORIGIN, source } as unknown as MessageEvent;
|
|
for (const listener of [...listeners]) listener(event);
|
|
},
|
|
};
|
|
}
|
|
|
|
function pageController(container: ServiceWorkerContainer, blockers = [() => false]) {
|
|
return createServiceWorkerPageController({
|
|
selection: {
|
|
mode: "ACTIVE",
|
|
scriptPath: SERVICE_WORKER_SCRIPT_PATH,
|
|
handlers: [],
|
|
},
|
|
disabledCleanup: false,
|
|
routerBasePath: "/",
|
|
origin: ORIGIN,
|
|
buildId: "page-build",
|
|
container,
|
|
blockers,
|
|
});
|
|
}
|
|
|
|
const identity: ServiceWorkerProtocolIdentity = {
|
|
serviceWorkerProtocolVersion: 1,
|
|
cacheSchemaVersion: 1,
|
|
buildId: "worker-build",
|
|
releaseId: "release-1",
|
|
contractSetDigest: `sha256:${"1".repeat(64)}`,
|
|
staticAssetSetDigest: `sha256:${"2".repeat(64)}`,
|
|
};
|
|
|
|
function workerScope() {
|
|
const deleted: string[] = [];
|
|
const clients = ["client-a", "client-b"].map((id) => ({
|
|
id,
|
|
url: `${ORIGIN}/app/${id}`,
|
|
messages: [] as unknown[],
|
|
postMessage(message: unknown) {
|
|
this.messages.push(message);
|
|
},
|
|
}));
|
|
const scope = {
|
|
caches: {
|
|
open: vi.fn(),
|
|
keys: vi.fn(async () => [
|
|
`${STATIC_CACHE_PREFIX}${"a".repeat(16)}`,
|
|
`${STATIC_CACHE_PREFIX}${"b".repeat(16)}`,
|
|
"foreign-cache",
|
|
]),
|
|
delete: vi.fn(async (name: string) => {
|
|
deleted.push(name);
|
|
return true;
|
|
}),
|
|
match: vi.fn(),
|
|
},
|
|
clients: { matchAll: vi.fn(async () => clients) },
|
|
registrationScope: `${ORIGIN}/app/`,
|
|
skipWaiting: vi.fn(async () => {}),
|
|
fetcher: vi.fn(),
|
|
digest: vi.fn(),
|
|
};
|
|
return { scope, clients, deleted };
|
|
}
|
|
|
|
describe("service worker static cache authority", () => {
|
|
const setDigest = `sha256:${"c".repeat(64)}` as const;
|
|
const currentCacheName = `${STATIC_CACHE_PREFIX}${setDigest.slice(
|
|
"sha256:".length,
|
|
"sha256:".length + 16,
|
|
)}`;
|
|
|
|
function staticRuntime(
|
|
caches: Readonly<{
|
|
open: (name: string) => Promise<unknown>;
|
|
keys: () => Promise<readonly string[]>;
|
|
delete: (name: string) => Promise<boolean>;
|
|
}>,
|
|
assetUrl = "/assets/app.0123456789abcdef.js",
|
|
) {
|
|
return createServiceWorkerRuntime(
|
|
{
|
|
caches,
|
|
clients: { matchAll: vi.fn(async () => []) },
|
|
registrationScope: `${ORIGIN}/app/`,
|
|
skipWaiting: vi.fn(async () => {}),
|
|
fetcher: vi.fn(),
|
|
digest: vi.fn(),
|
|
} as never,
|
|
{
|
|
identity: { ...identity, staticAssetSetDigest: setDigest },
|
|
handlers: ["PWA_STATIC_ASSETS"],
|
|
manifest: {
|
|
schemaVersion: 1,
|
|
buildId: identity.buildId,
|
|
releaseId: identity.releaseId,
|
|
setDigest,
|
|
// SW-URL-01. Generator output is root-relative.
|
|
assets: [
|
|
{
|
|
url: assetUrl,
|
|
sha256: `sha256:${"d".repeat(64)}`,
|
|
bytes: 10,
|
|
contentType: "text/javascript",
|
|
},
|
|
],
|
|
},
|
|
runtimeConfigUrl: "/runtime-config.json",
|
|
releaseManifestUrl: "/release-manifest.json",
|
|
},
|
|
);
|
|
}
|
|
|
|
it("classifies a generated root-relative asset against an absolute Request URL", async () => {
|
|
const currentResponse = new Response("current", { status: 200 });
|
|
const opened: string[] = [];
|
|
const runtime = staticRuntime({
|
|
open: vi.fn(async (name: string) => {
|
|
opened.push(name);
|
|
return {
|
|
match: async () => currentResponse.clone(),
|
|
delete: async () => true,
|
|
};
|
|
}),
|
|
keys: vi.fn(async () => [currentCacheName]),
|
|
delete: vi.fn(async () => true),
|
|
});
|
|
|
|
const served = await runtime.onFetch({
|
|
method: "GET",
|
|
url: `${ORIGIN}/assets/app.0123456789abcdef.js`,
|
|
});
|
|
expect(served).not.toBeNull();
|
|
expect(opened).toEqual([currentCacheName]);
|
|
});
|
|
|
|
it("matches static responses only in the current release cache", async () => {
|
|
const previousCacheName = `${STATIC_CACHE_PREFIX}${"e".repeat(16)}`;
|
|
const previousMatch = vi.fn(
|
|
async () => new Response("previous", { status: 200 }),
|
|
);
|
|
const deleteEntry = async (): Promise<boolean> => true;
|
|
const emptyMatch = async (): Promise<Response | undefined> => undefined;
|
|
const previousCache = { match: previousMatch, delete: deleteEntry };
|
|
const emptyCache = { match: emptyMatch, delete: deleteEntry };
|
|
const runtime = staticRuntime({
|
|
open: vi.fn(async (name: string) =>
|
|
name === previousCacheName ? previousCache : emptyCache,
|
|
),
|
|
keys: vi.fn(async () => [currentCacheName, previousCacheName]),
|
|
delete: vi.fn(async () => true),
|
|
});
|
|
|
|
// Only the previous cache holds the entry, so the request falls through to
|
|
// the network rather than serving a stale release.
|
|
await expect(
|
|
runtime.onFetch({
|
|
method: "GET",
|
|
url: `${ORIGIN}/assets/app.0123456789abcdef.js`,
|
|
}),
|
|
).resolves.toBeNull();
|
|
expect(previousMatch).not.toHaveBeenCalled();
|
|
});
|
|
|
|
/** Current cache is empty; the marked previous release cache holds `url`. */
|
|
function previousReleaseCaches(assetUrl: string) {
|
|
const previousCacheName = `${STATIC_CACHE_PREFIX}${"e".repeat(16)}`;
|
|
const previousAsset = vi.fn(
|
|
async () => new Response("previous", { status: 200 }),
|
|
);
|
|
const previousCache = {
|
|
match: async (url: string) =>
|
|
url === `${ORIGIN}${assetUrl}`
|
|
? previousAsset()
|
|
: new Response(
|
|
JSON.stringify({
|
|
schemaVersion: 1,
|
|
cacheName: previousCacheName,
|
|
activationSequence: 1,
|
|
}),
|
|
{ status: 200 },
|
|
),
|
|
delete: async () => true,
|
|
};
|
|
const emptyCache = {
|
|
match: async (): Promise<Response | undefined> => undefined,
|
|
delete: async () => true,
|
|
};
|
|
return {
|
|
previousAsset,
|
|
caches: {
|
|
open: vi.fn(async (name: string) =>
|
|
name === previousCacheName ? previousCache : emptyCache,
|
|
),
|
|
keys: vi.fn(async () => [currentCacheName, previousCacheName]),
|
|
delete: vi.fn(async () => true),
|
|
},
|
|
};
|
|
}
|
|
|
|
it("serves a hashed asset missing from the current cache from the previous release cache (R-6.3)", async () => {
|
|
const assetUrl = "/assets/app-Dq3x8Yk2.js";
|
|
const fixture = previousReleaseCaches(assetUrl);
|
|
const runtime = staticRuntime(fixture.caches, assetUrl);
|
|
|
|
const served = await runtime.onFetch({
|
|
method: "GET",
|
|
url: `${ORIGIN}${assetUrl}`,
|
|
});
|
|
await expect(served?.text()).resolves.toBe("previous");
|
|
});
|
|
|
|
it("serves an old build's hashed chunk that the current manifest does not list from the previous release cache (Q-6.6-6b)", async () => {
|
|
// The page still runs the previous build and lazy-loads a chunk the new
|
|
// manifest (and so the current cache) no longer has. The fixture scope is
|
|
// `/app/`, so the build's asset directory is `/app/assets/` (06-08).
|
|
const oldChunk = "/app/assets/settings-page-Zz9Yy8Xx.js";
|
|
const fixture = previousReleaseCaches(oldChunk);
|
|
const runtime = staticRuntime(fixture.caches, "/assets/app-Dq3x8Yk2.js");
|
|
|
|
const served = await runtime.onFetch({
|
|
method: "GET",
|
|
url: `${ORIGIN}${oldChunk}`,
|
|
mode: "cors",
|
|
});
|
|
await expect(served?.text()).resolves.toBe("previous");
|
|
});
|
|
|
|
it("never answers a non-hashed URL from the previous release cache (D-7)", async () => {
|
|
const assetUrl = "/assets/app.js";
|
|
const fixture = previousReleaseCaches(assetUrl);
|
|
const runtime = staticRuntime(fixture.caches, assetUrl);
|
|
|
|
await expect(
|
|
runtime.onFetch({ method: "GET", url: `${ORIGIN}${assetUrl}` }),
|
|
).resolves.toBeNull();
|
|
expect(fixture.previousAsset).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("deletes an invalid hit only from the current release cache", async () => {
|
|
const deletes: string[] = [];
|
|
const runtime = staticRuntime({
|
|
open: vi.fn(async (name: string) => {
|
|
const recordDelete = async (url: string): Promise<boolean> => {
|
|
deletes.push(`${name}:${url}`);
|
|
return true;
|
|
};
|
|
return {
|
|
match: async () => new Response("bad", { status: 500 }),
|
|
delete: recordDelete,
|
|
};
|
|
}),
|
|
keys: vi.fn(async () => [currentCacheName]),
|
|
delete: vi.fn(async () => true),
|
|
});
|
|
|
|
await expect(
|
|
runtime.onFetch({
|
|
method: "GET",
|
|
url: `${ORIGIN}/assets/app.0123456789abcdef.js`,
|
|
}),
|
|
).resolves.toBeNull();
|
|
expect(deletes).toEqual([
|
|
`${currentCacheName}:${ORIGIN}/assets/app.0123456789abcdef.js`,
|
|
]);
|
|
});
|
|
});
|
|
|
|
describe("service worker exact ownership and truthful removal", () => {
|
|
it("deletes only exact owned static cache names", async () => {
|
|
const fixture = workerScope();
|
|
fixture.scope.caches.keys = vi.fn(async () => [
|
|
`${STATIC_CACHE_PREFIX}${"a".repeat(16)}`,
|
|
`${STATIC_CACHE_PREFIX}${"b".repeat(16)}`,
|
|
// SW-02. Same prefix, not owned.
|
|
`${STATIC_CACHE_PREFIX}not-owned`,
|
|
`${STATIC_CACHE_PREFIX}${"c".repeat(17)}`,
|
|
`${STATIC_CACHE_PREFIX}${"A".repeat(16)}`,
|
|
"foreign-cache",
|
|
]);
|
|
const runtime = createServiceWorkerRuntime(fixture.scope as never, {
|
|
identity,
|
|
handlers: [],
|
|
manifest: null,
|
|
runtimeConfigUrl: "/runtime-config.json",
|
|
releaseManifestUrl: "/release-manifest.json",
|
|
});
|
|
const request = createServiceWorkerMessage({
|
|
kind: "CACHE_RESET_REQUEST",
|
|
sourceBuildId: "page-build",
|
|
targetBuildId: identity.buildId,
|
|
nonce: "nonce-reset-0001",
|
|
});
|
|
await runtime.onCacheResetRequest(request, fixture.clients[0] as never);
|
|
|
|
expect(fixture.deleted).toEqual([
|
|
`${STATIC_CACHE_PREFIX}${"a".repeat(16)}`,
|
|
`${STATIC_CACHE_PREFIX}${"b".repeat(16)}`,
|
|
]);
|
|
});
|
|
it.each([
|
|
{
|
|
label: "unregister false",
|
|
unregister: async () => false,
|
|
expected: { kind: "FAILED" },
|
|
},
|
|
{
|
|
label: "unregister rejects",
|
|
unregister: async () => {
|
|
throw new TypeError("unregister exploded");
|
|
},
|
|
expected: { kind: "FAILED" },
|
|
},
|
|
{
|
|
label: "unregister true",
|
|
unregister: async () => true,
|
|
expected: { kind: "DISABLED" },
|
|
},
|
|
])(
|
|
"does not hide $label behind DISABLED",
|
|
async ({ unregister, expected }) => {
|
|
const registration = {
|
|
scope: `${ORIGIN}/`,
|
|
installing: null,
|
|
waiting: null,
|
|
active: { scriptURL: SCRIPT_URL },
|
|
unregister: vi.fn(unregister),
|
|
update: vi.fn(async () => {}),
|
|
} as unknown as ServiceWorkerRegistration;
|
|
const controller = createServiceWorkerPageController({
|
|
container: {
|
|
controller: null,
|
|
register: vi.fn(),
|
|
getRegistration: vi.fn(async () => registration),
|
|
addEventListener: vi.fn(),
|
|
removeEventListener: vi.fn(),
|
|
} as never,
|
|
routerBasePath: "/",
|
|
origin: ORIGIN,
|
|
selection: {
|
|
mode: "REMOVE_REGISTRATION",
|
|
scriptPath: "service-worker.js",
|
|
handlers: [],
|
|
},
|
|
} as never);
|
|
|
|
await expect(controller.start()).resolves.toMatchObject(expected);
|
|
},
|
|
);
|
|
|
|
it("reports an ownership mismatch as INCOMPATIBLE rather than DISABLED", async () => {
|
|
const foreign = {
|
|
scope: `${ORIGIN}/`,
|
|
installing: null,
|
|
waiting: null,
|
|
active: { scriptURL: `${ORIGIN}/someone-else.js` },
|
|
unregister: vi.fn(async () => true),
|
|
update: vi.fn(async () => {}),
|
|
} as unknown as ServiceWorkerRegistration;
|
|
const controller = createServiceWorkerPageController({
|
|
container: {
|
|
controller: null,
|
|
register: vi.fn(),
|
|
getRegistration: vi.fn(async () => foreign),
|
|
addEventListener: vi.fn(),
|
|
removeEventListener: vi.fn(),
|
|
} as never,
|
|
routerBasePath: "/",
|
|
origin: ORIGIN,
|
|
selection: {
|
|
mode: "REMOVE_REGISTRATION",
|
|
scriptPath: "service-worker.js",
|
|
handlers: [],
|
|
},
|
|
} as never);
|
|
|
|
await expect(controller.start()).resolves.toMatchObject({
|
|
kind: "INCOMPATIBLE",
|
|
});
|
|
expect(foreign.unregister).not.toHaveBeenCalled();
|
|
});
|
|
|
|
// 06-04. The runtime kill switch: `CAPABILITY_OVERRIDES.SERVICE_WORKER =
|
|
// "DISABLED"` over a static ACTIVE worker unregisters the owned registration
|
|
// without registering anything.
|
|
it("resolves runtime DISABLED over a static ACTIVE worker to disabled cleanup", () => {
|
|
expect(
|
|
resolveRuntimeCapabilities(
|
|
{
|
|
realtime: [],
|
|
webWorkers: [],
|
|
serviceWorker: {
|
|
mode: "ACTIVE",
|
|
scriptPath: SERVICE_WORKER_SCRIPT_PATH,
|
|
handlers: [],
|
|
},
|
|
offlineCommands: null,
|
|
},
|
|
{
|
|
REALTIME: "DEFAULT",
|
|
WEB_WORKER: "DEFAULT",
|
|
SERVICE_WORKER: "DISABLED",
|
|
OFFLINE_COMMANDS: "DEFAULT",
|
|
},
|
|
),
|
|
).toMatchObject({ serviceWorker: null, serviceWorkerDisabledCleanup: true });
|
|
});
|
|
|
|
it.each([
|
|
{ owner: "owned", scriptURL: SCRIPT_URL, unregisters: 1, expected: "DISABLED" },
|
|
{
|
|
owner: "foreign",
|
|
scriptURL: `${ORIGIN}/someone-else.js`,
|
|
unregisters: 0,
|
|
expected: "INCOMPATIBLE",
|
|
},
|
|
])(
|
|
"runtime DISABLED unregisters only an $owner registration",
|
|
async ({ scriptURL, unregisters, expected }) => {
|
|
const registration = {
|
|
scope: `${ORIGIN}/`,
|
|
installing: null,
|
|
waiting: null,
|
|
active: { scriptURL },
|
|
unregister: vi.fn(async () => true),
|
|
update: vi.fn(async () => {}),
|
|
} as unknown as ServiceWorkerRegistration;
|
|
const container = {
|
|
controller: null,
|
|
register: vi.fn(),
|
|
getRegistration: vi.fn(async () => registration),
|
|
addEventListener: vi.fn(),
|
|
removeEventListener: vi.fn(),
|
|
};
|
|
const controller = createServiceWorkerPageController({
|
|
selection: null,
|
|
disabledCleanup: true,
|
|
routerBasePath: "/",
|
|
origin: ORIGIN,
|
|
buildId: "page-build",
|
|
container: container as unknown as ServiceWorkerContainer,
|
|
});
|
|
|
|
await expect(controller.start()).resolves.toEqual({ kind: expected });
|
|
expect(container.register).not.toHaveBeenCalled();
|
|
expect(container.getRegistration).toHaveBeenCalledOnce();
|
|
expect(registration.unregister).toHaveBeenCalledTimes(unregisters);
|
|
},
|
|
);
|
|
});
|
|
|
|
describe("service worker page protocol", () => {
|
|
it("does not attach late listeners when stopped during registration", async () => {
|
|
const browser = pageContainer();
|
|
let completeRegistration: ((value: ServiceWorkerRegistration) => void) | undefined;
|
|
const deferredRegistration = new Promise<ServiceWorkerRegistration>((resolve) => {
|
|
completeRegistration = resolve;
|
|
});
|
|
vi.mocked(browser.container.register).mockReturnValue(deferredRegistration);
|
|
const controller = pageController(browser.container);
|
|
|
|
const starting = controller.start();
|
|
await Promise.resolve();
|
|
await controller.stop();
|
|
completeRegistration?.(browser.registration);
|
|
|
|
await expect(starting).resolves.toEqual({ kind: "FAILED", code: "STOPPED" });
|
|
expect(browser.listenerCount()).toBe(0);
|
|
});
|
|
|
|
it("answers a worker drain request only after local blockers are clear", async () => {
|
|
const browser = pageContainer({ waiting: true });
|
|
const controller = pageController(browser.container);
|
|
await controller.start();
|
|
// SW-06. Replies are correlated by source identity, so the fake request
|
|
// comes from the registration's waiting worker.
|
|
const source = browser.waiting as unknown as {
|
|
postMessage(message: unknown): void;
|
|
};
|
|
const sourceMessages = vi.spyOn(source, "postMessage");
|
|
|
|
browser.dispatch(
|
|
createServiceWorkerMessage({
|
|
kind: "CLIENT_DRAIN_REQUEST",
|
|
sourceBuildId: "worker-build",
|
|
targetBuildId: "page-build",
|
|
nonce: "drain-1",
|
|
}),
|
|
source,
|
|
);
|
|
|
|
expect(sourceMessages).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
kind: "CLIENT_DRAINED",
|
|
sourceBuildId: "page-build",
|
|
targetBuildId: "worker-build",
|
|
nonce: "drain-1",
|
|
}),
|
|
);
|
|
await controller.stop();
|
|
});
|
|
|
|
it("settles a pending activation and removes its listener when stopped", async () => {
|
|
const browser = pageContainer({ waiting: true });
|
|
const controller = pageController(browser.container);
|
|
await controller.start();
|
|
|
|
const activation = controller.requestActivation();
|
|
await Promise.resolve();
|
|
expect(browser.listenerCount()).toBe(2);
|
|
|
|
await controller.stop();
|
|
|
|
await expect(activation).resolves.toEqual({ kind: "FAILED", code: "STOPPED" });
|
|
expect(browser.listenerCount()).toBe(0);
|
|
});
|
|
|
|
it("waits for the correlated cache reset result", async () => {
|
|
const browser = pageContainer({ controlled: true });
|
|
const controller = pageController(browser.container);
|
|
await controller.start();
|
|
|
|
let settled = false;
|
|
const result = controller.resetOwnedCaches().then((outcome) => {
|
|
settled = true;
|
|
return outcome;
|
|
});
|
|
await Promise.resolve();
|
|
expect(settled).toBe(false);
|
|
|
|
const request = browser.controllerMessages.at(-1) as { nonce?: string };
|
|
browser.dispatch({
|
|
...createServiceWorkerMessage({
|
|
kind: "CACHE_RESET_RESULT",
|
|
sourceBuildId: "worker-build",
|
|
targetBuildId: "page-build",
|
|
nonce: request.nonce,
|
|
}),
|
|
cachesDeleted: 2,
|
|
}, browser.controlled ?? undefined);
|
|
|
|
await expect(result).resolves.toEqual({ kind: "RESET", cachesDeleted: 2 });
|
|
await controller.stop();
|
|
});
|
|
});
|
|
|
|
describe("service worker worker-side protocol", () => {
|
|
it("retains the immediately previous verified static cache on activation", async () => {
|
|
const current = staticCacheName(identity.staticAssetSetDigest);
|
|
const stale = `${STATIC_CACHE_PREFIX}${"3".repeat(16)}`;
|
|
const previous = `${STATIC_CACHE_PREFIX}${"4".repeat(16)}`;
|
|
const names = [stale, previous, current, "foreign-cache"];
|
|
const deleted: string[] = [];
|
|
const markerPut = vi.fn(async () => {});
|
|
const cache = {
|
|
match: vi.fn(async () => undefined),
|
|
put: markerPut,
|
|
delete: vi.fn(async () => true),
|
|
} as unknown as Cache;
|
|
const scope = {
|
|
caches: {
|
|
open: vi.fn(async () => cache),
|
|
keys: vi.fn(async () => names),
|
|
delete: vi.fn(async (name: string) => {
|
|
deleted.push(name);
|
|
return true;
|
|
}),
|
|
match: vi.fn(),
|
|
},
|
|
clients: { matchAll: vi.fn(async () => []) },
|
|
skipWaiting: vi.fn(async () => {}),
|
|
fetcher: vi.fn(),
|
|
digest: vi.fn(),
|
|
};
|
|
const runtime = createServiceWorkerRuntime(scope as never, {
|
|
identity,
|
|
handlers: ["PWA_STATIC_ASSETS"],
|
|
manifest: {
|
|
schemaVersion: 1,
|
|
buildId: identity.buildId,
|
|
releaseId: identity.releaseId,
|
|
setDigest: identity.staticAssetSetDigest as `sha256:${string}`,
|
|
assets: [],
|
|
},
|
|
runtimeConfigUrl: "/runtime-config.json",
|
|
releaseManifestUrl: "/release-manifest.json",
|
|
});
|
|
|
|
await expect(runtime.onActivate()).resolves.toBe(1);
|
|
expect(deleted).toEqual([stale]);
|
|
expect(markerPut).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("deletes stale caches before, and regardless of, the marker write (Q-6.6-9)", async () => {
|
|
const current = staticCacheName(identity.staticAssetSetDigest);
|
|
const stale = `${STATIC_CACHE_PREFIX}${"3".repeat(16)}`;
|
|
const previous = `${STATIC_CACHE_PREFIX}${"4".repeat(16)}`;
|
|
const order: string[] = [];
|
|
// Storage is full: the marker write fails.
|
|
const cache = {
|
|
match: vi.fn(async () => undefined),
|
|
put: vi.fn(async () => {
|
|
order.push("marker");
|
|
throw new DOMException("full", "QuotaExceededError");
|
|
}),
|
|
} as unknown as Cache;
|
|
const runtime = createServiceWorkerRuntime(
|
|
{
|
|
caches: {
|
|
open: vi.fn(async () => cache),
|
|
keys: vi.fn(async () => [stale, previous, current]),
|
|
delete: vi.fn(async (name: string) => {
|
|
order.push(`delete:${name}`);
|
|
return true;
|
|
}),
|
|
},
|
|
clients: { matchAll: vi.fn(async () => []) },
|
|
skipWaiting: vi.fn(async () => {}),
|
|
fetcher: vi.fn(),
|
|
digest: vi.fn(),
|
|
} as never,
|
|
{
|
|
identity,
|
|
handlers: ["PWA_STATIC_ASSETS"],
|
|
manifest: {
|
|
schemaVersion: 1,
|
|
buildId: identity.buildId,
|
|
releaseId: identity.releaseId,
|
|
setDigest: identity.staticAssetSetDigest as `sha256:${string}`,
|
|
assets: [],
|
|
},
|
|
runtimeConfigUrl: "/runtime-config.json",
|
|
releaseManifestUrl: "/release-manifest.json",
|
|
},
|
|
);
|
|
|
|
await expect(runtime.onActivate()).resolves.toBe(1);
|
|
expect(order).toEqual([`delete:${stale}`, "marker"]);
|
|
});
|
|
|
|
it("waits for every exact client drain acknowledgement before activation", async () => {
|
|
const fixture = workerScope();
|
|
const runtime = createServiceWorkerRuntime(fixture.scope as never, {
|
|
identity,
|
|
handlers: [],
|
|
manifest: null,
|
|
runtimeConfigUrl: "/runtime-config.json",
|
|
releaseManifestUrl: "/release-manifest.json",
|
|
});
|
|
const request = createServiceWorkerMessage({
|
|
kind: "ACTIVATE_REQUEST",
|
|
sourceBuildId: "page-build",
|
|
targetBuildId: "worker-build",
|
|
nonce: "activation-1",
|
|
});
|
|
|
|
const activation = runtime.onActivateRequest(request);
|
|
await Promise.resolve();
|
|
expect(fixture.scope.skipWaiting).not.toHaveBeenCalled();
|
|
|
|
runtime.onClientMessage(
|
|
createServiceWorkerMessage({
|
|
kind: "CLIENT_DRAINED",
|
|
sourceBuildId: "page-build",
|
|
targetBuildId: "worker-build",
|
|
nonce: "activation-1",
|
|
}),
|
|
"client-a",
|
|
);
|
|
await Promise.resolve();
|
|
expect(fixture.scope.skipWaiting).not.toHaveBeenCalled();
|
|
|
|
runtime.onClientMessage(
|
|
createServiceWorkerMessage({
|
|
kind: "CLIENT_DRAINED",
|
|
sourceBuildId: "page-build",
|
|
targetBuildId: "worker-build",
|
|
nonce: "activation-1",
|
|
}),
|
|
"client-b",
|
|
);
|
|
|
|
await expect(activation).resolves.toBe("ACCEPTED");
|
|
expect(fixture.scope.skipWaiting).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
// 1101/06-04 (M3, M9). An activation nonce is single-use, and only a client
|
|
// the worker asked to drain can acknowledge it.
|
|
it("refuses a reused nonce and a drain reply from a client it did not ask", async () => {
|
|
const fixture = workerScope();
|
|
const runtime = createServiceWorkerRuntime(fixture.scope as never, {
|
|
identity,
|
|
handlers: [],
|
|
manifest: null,
|
|
runtimeConfigUrl: "/runtime-config.json",
|
|
releaseManifestUrl: "/release-manifest.json",
|
|
});
|
|
const message = (kind: "ACTIVATE_REQUEST" | "CLIENT_DRAINED") =>
|
|
createServiceWorkerMessage({
|
|
kind,
|
|
sourceBuildId: "page-build",
|
|
targetBuildId: "worker-build",
|
|
nonce: "activation-1",
|
|
});
|
|
|
|
const activation = runtime.onActivateRequest(message("ACTIVATE_REQUEST"));
|
|
let settled = false;
|
|
void activation.then(() => {
|
|
settled = true;
|
|
});
|
|
await Promise.resolve();
|
|
runtime.onClientMessage(message("CLIENT_DRAINED"), "client-a");
|
|
runtime.onClientMessage(message("CLIENT_DRAINED"), "client-unasked");
|
|
for (let turn = 0; turn < 10; turn += 1) await Promise.resolve();
|
|
expect(settled).toBe(false);
|
|
expect(fixture.scope.skipWaiting).not.toHaveBeenCalled();
|
|
|
|
runtime.onClientMessage(message("CLIENT_DRAINED"), "client-b");
|
|
await expect(activation).resolves.toBe("ACCEPTED");
|
|
await expect(
|
|
runtime.onActivateRequest(message("ACTIVATE_REQUEST")),
|
|
).resolves.toBe("REJECTED");
|
|
expect(fixture.scope.skipWaiting).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
it("enumerates uncontrolled window clients before an activation drain", async () => {
|
|
const fixture = workerScope();
|
|
const runtime = createServiceWorkerRuntime(fixture.scope as never, {
|
|
identity,
|
|
handlers: [],
|
|
manifest: null,
|
|
runtimeConfigUrl: "/runtime-config.json",
|
|
releaseManifestUrl: "/release-manifest.json",
|
|
});
|
|
const request = createServiceWorkerMessage({
|
|
kind: "ACTIVATE_REQUEST",
|
|
sourceBuildId: "page-build",
|
|
targetBuildId: "worker-build",
|
|
nonce: "activation-uncontrolled",
|
|
});
|
|
|
|
const activation = runtime.onActivateRequest(request);
|
|
await Promise.resolve();
|
|
for (const client of fixture.clients) {
|
|
runtime.onClientMessage(
|
|
createServiceWorkerMessage({
|
|
kind: "CLIENT_DRAINED",
|
|
sourceBuildId: "page-build",
|
|
targetBuildId: "worker-build",
|
|
nonce: "activation-uncontrolled",
|
|
}),
|
|
client.id,
|
|
);
|
|
}
|
|
|
|
await expect(activation).resolves.toBe("ACCEPTED");
|
|
expect(fixture.scope.clients.matchAll).toHaveBeenCalledWith({
|
|
type: "window",
|
|
includeUncontrolled: true,
|
|
});
|
|
});
|
|
|
|
it("drains only page clients inside the exact registration scope", async () => {
|
|
const inScope = {
|
|
id: "client-in-scope",
|
|
url: `${ORIGIN}/app/nested/page`,
|
|
messages: [] as unknown[],
|
|
postMessage(message: unknown) {
|
|
this.messages.push(message);
|
|
},
|
|
};
|
|
const outOfScope = {
|
|
id: "client-out-of-scope",
|
|
url: `${ORIGIN}/application/page`,
|
|
messages: [] as unknown[],
|
|
postMessage(message: unknown) {
|
|
this.messages.push(message);
|
|
},
|
|
};
|
|
const fixture = workerScope();
|
|
fixture.scope.clients.matchAll.mockResolvedValue([
|
|
inScope,
|
|
outOfScope,
|
|
]);
|
|
const runtime = createServiceWorkerRuntime(fixture.scope as never, {
|
|
identity,
|
|
handlers: [],
|
|
manifest: null,
|
|
runtimeConfigUrl: "/runtime-config.json",
|
|
releaseManifestUrl: "/release-manifest.json",
|
|
});
|
|
const activation = runtime.onActivateRequest(
|
|
createServiceWorkerMessage({
|
|
kind: "ACTIVATE_REQUEST",
|
|
sourceBuildId: "page-build",
|
|
targetBuildId: "worker-build",
|
|
nonce: "activation-scope",
|
|
}),
|
|
);
|
|
await Promise.resolve();
|
|
runtime.onClientMessage(
|
|
createServiceWorkerMessage({
|
|
kind: "CLIENT_DRAINED",
|
|
sourceBuildId: "page-build",
|
|
targetBuildId: "worker-build",
|
|
nonce: "activation-scope",
|
|
}),
|
|
inScope.id,
|
|
);
|
|
runtime.onClientMessage(
|
|
createServiceWorkerMessage({
|
|
kind: "CLIENT_DRAINED",
|
|
sourceBuildId: "page-build",
|
|
targetBuildId: "worker-build",
|
|
nonce: "activation-scope",
|
|
}),
|
|
outOfScope.id,
|
|
);
|
|
|
|
await expect(activation).resolves.toBe("ACCEPTED");
|
|
expect(inScope.messages).not.toHaveLength(0);
|
|
expect(outOfScope.messages).toEqual([]);
|
|
});
|
|
|
|
it("deletes only owned caches and returns the correlated reset count", async () => {
|
|
const fixture = workerScope();
|
|
const runtime = createServiceWorkerRuntime(fixture.scope as never, {
|
|
identity,
|
|
handlers: [],
|
|
manifest: null,
|
|
runtimeConfigUrl: "/runtime-config.json",
|
|
releaseManifestUrl: "/release-manifest.json",
|
|
});
|
|
const source = {
|
|
id: "client-a",
|
|
url: `${ORIGIN}/app/client-a`,
|
|
postMessage: vi.fn(),
|
|
};
|
|
|
|
await runtime.onCacheResetRequest(
|
|
createServiceWorkerMessage({
|
|
kind: "CACHE_RESET_REQUEST",
|
|
sourceBuildId: "page-build",
|
|
targetBuildId: "worker-build",
|
|
nonce: "reset-1",
|
|
}),
|
|
source,
|
|
);
|
|
|
|
expect(fixture.deleted).toEqual([
|
|
`${STATIC_CACHE_PREFIX}${"a".repeat(16)}`,
|
|
`${STATIC_CACHE_PREFIX}${"b".repeat(16)}`,
|
|
]);
|
|
expect(source.postMessage).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
kind: "CACHE_RESET_RESULT",
|
|
nonce: "reset-1",
|
|
cachesDeleted: 2,
|
|
}),
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("service worker static asset install", () => {
|
|
const manifest: StaticAssetManifestV1 = {
|
|
schemaVersion: 1,
|
|
buildId: "worker-build",
|
|
releaseId: "release-1",
|
|
setDigest: `sha256:${"a".repeat(64)}`,
|
|
assets: [
|
|
{
|
|
url: `${ORIGIN}/assets/app.js`,
|
|
sha256: `sha256:${"b".repeat(64)}`,
|
|
bytes: 1,
|
|
contentType: "application/javascript",
|
|
},
|
|
],
|
|
};
|
|
|
|
it("aborts and rolls back a candidate cache at the overall install deadline", async () => {
|
|
vi.useFakeTimers();
|
|
const deleteCache = vi.fn(async (_name: string) => true);
|
|
const fetcher = vi.fn(
|
|
(_input: RequestInfo | URL, init?: RequestInit) =>
|
|
new Promise<Response>((_resolve, reject) => {
|
|
init?.signal?.addEventListener("abort", () => {
|
|
reject(new DOMException("Install deadline", "AbortError"));
|
|
});
|
|
}),
|
|
);
|
|
|
|
const result = installStaticAssets(manifest, {
|
|
caches: {
|
|
open: vi.fn(async () => ({ put: vi.fn() }) as unknown as Cache),
|
|
delete: deleteCache,
|
|
},
|
|
fetcher: fetcher as typeof fetch,
|
|
digest: vi.fn(),
|
|
});
|
|
await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.installDeadlineMs);
|
|
|
|
await expect(result).resolves.toEqual({
|
|
kind: "REJECTED",
|
|
code: "INSTALL_DEADLINE_EXCEEDED",
|
|
});
|
|
expect(fetcher.mock.calls[0]?.[1]?.signal?.aborted).toBe(true);
|
|
// SW-09. The public result closes at the deadline with one exact delete,
|
|
// and a second exact delete is registered once the abandoned install work
|
|
// actually settles. Both target the same owned candidate cache.
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(deleteCache).toHaveBeenCalledTimes(2);
|
|
expect(new Set(deleteCache.mock.calls.map((call) => call[0])).size).toBe(1);
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
it("observes and cleans non-cooperative late install work", async () => {
|
|
vi.useFakeTimers();
|
|
const deleteCache = vi.fn(async (_name: string) => true);
|
|
const cancel = vi.fn(async () => {});
|
|
let releaseFetch: ((response: Response) => void) | undefined;
|
|
// A fetch that ignores the abort signal entirely.
|
|
const fetcher = vi.fn(
|
|
() =>
|
|
new Promise<Response>((resolve) => {
|
|
releaseFetch = resolve;
|
|
}),
|
|
);
|
|
|
|
const result = installStaticAssets(manifest, {
|
|
caches: {
|
|
open: vi.fn(async () => ({ put: vi.fn() }) as unknown as Cache),
|
|
delete: deleteCache,
|
|
},
|
|
fetcher: fetcher as typeof fetch,
|
|
digest: vi.fn(),
|
|
});
|
|
await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.installDeadlineMs);
|
|
await expect(result).resolves.toEqual({
|
|
kind: "REJECTED",
|
|
code: "INSTALL_DEADLINE_EXCEEDED",
|
|
});
|
|
|
|
// The late response arrives after the public bound; its body is cancelled
|
|
// and no unhandled rejection escapes.
|
|
releaseFetch?.({ body: { cancel } } as unknown as Response);
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
expect(cancel).toHaveBeenCalledOnce();
|
|
vi.useRealTimers();
|
|
});
|
|
|
|
it("stops reading as soon as the streamed body exceeds declared bytes", async () => {
|
|
const put = vi.fn(async () => {});
|
|
const cancel = vi.fn(async () => {});
|
|
const body = new ReadableStream<Uint8Array>({
|
|
start(controller) {
|
|
controller.enqueue(new Uint8Array([1, 2]));
|
|
},
|
|
cancel,
|
|
});
|
|
|
|
await expect(
|
|
installStaticAssets(manifest, {
|
|
caches: {
|
|
open: vi.fn(async () => ({ put }) as unknown as Cache),
|
|
delete: vi.fn(async () => true),
|
|
},
|
|
fetcher: vi.fn(async () =>
|
|
new Response(body, {
|
|
status: 200,
|
|
headers: { "content-type": "application/javascript" },
|
|
}),
|
|
),
|
|
digest: vi.fn(),
|
|
}),
|
|
).resolves.toEqual({ kind: "REJECTED", code: "BYTES_MISMATCH" });
|
|
expect(put).not.toHaveBeenCalled();
|
|
expect(cancel).toHaveBeenCalledTimes(1);
|
|
});
|
|
|
|
function installOne(response: Response) {
|
|
const put = vi.fn(async () => {});
|
|
const jsManifest: StaticAssetManifestV1 = {
|
|
...manifest,
|
|
assets: [{ ...manifest.assets[0]!, contentType: "text/javascript" }],
|
|
};
|
|
const result = installStaticAssets(jsManifest, {
|
|
caches: {
|
|
open: vi.fn(async () => ({ put }) as unknown as Cache),
|
|
delete: vi.fn(async () => true),
|
|
},
|
|
fetcher: vi.fn(async () => response),
|
|
digest: vi.fn(async () => manifest.assets[0]!.sha256),
|
|
});
|
|
return { result, put };
|
|
}
|
|
|
|
// 1101/06-04 (M1). The precache holds only public assets: no cookie or
|
|
// credential goes with the request, a redirect is refused rather than
|
|
// followed to another resource, and the HTTP cache is bypassed.
|
|
it("fetches each asset without credentials, redirects or the HTTP cache", async () => {
|
|
const fetcher = vi.fn(
|
|
async (_url: RequestInfo | URL, _init?: RequestInit) =>
|
|
new Response(new Uint8Array([1]), {
|
|
status: 200,
|
|
headers: { "content-type": "text/javascript" },
|
|
}),
|
|
);
|
|
await expect(
|
|
installStaticAssets(
|
|
{
|
|
...manifest,
|
|
assets: [{ ...manifest.assets[0]!, contentType: "text/javascript" }],
|
|
},
|
|
{
|
|
caches: {
|
|
open: vi.fn(async () => ({ put: vi.fn(async () => {}) }) as unknown as Cache),
|
|
delete: vi.fn(async () => true),
|
|
},
|
|
fetcher,
|
|
digest: vi.fn(async () => manifest.assets[0]!.sha256),
|
|
},
|
|
),
|
|
).resolves.toMatchObject({ kind: "INSTALLED" });
|
|
expect(fetcher).toHaveBeenCalledOnce();
|
|
expect(fetcher.mock.calls[0]![1]).toMatchObject({
|
|
cache: "no-store",
|
|
credentials: "omit",
|
|
redirect: "error",
|
|
});
|
|
});
|
|
|
|
it("installs JavaScript served under a JavaScript MIME synonym (R-6.5)", async () => {
|
|
const { result, put } = installOne(
|
|
new Response(new Uint8Array([1]), {
|
|
status: 200,
|
|
headers: { "content-type": "application/javascript; charset=utf-8" },
|
|
}),
|
|
);
|
|
await expect(result).resolves.toMatchObject({ kind: "INSTALLED" });
|
|
expect(put).toHaveBeenCalledOnce();
|
|
});
|
|
|
|
it("does not compare an encoded Content-Length with the decoded size (R-6.5)", async () => {
|
|
const { result } = installOne(
|
|
new Response(new Uint8Array([1]), {
|
|
status: 200,
|
|
headers: {
|
|
"content-type": "text/javascript",
|
|
"content-encoding": "gzip",
|
|
"content-length": "21",
|
|
},
|
|
}),
|
|
);
|
|
await expect(result).resolves.toMatchObject({ kind: "INSTALLED" });
|
|
});
|
|
|
|
it("still checks the decoded byte count of an encoded response (R-6.5)", async () => {
|
|
const { result } = installOne(
|
|
new Response(new Uint8Array([1, 2]), {
|
|
status: 200,
|
|
headers: {
|
|
"content-type": "text/javascript",
|
|
"content-encoding": "gzip",
|
|
"content-length": "21",
|
|
},
|
|
}),
|
|
);
|
|
await expect(result).resolves.toEqual({
|
|
kind: "REJECTED",
|
|
code: "BYTES_MISMATCH",
|
|
});
|
|
});
|
|
|
|
it("aborts sibling asset fetches after the first install failure", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
let siblingSignal: AbortSignal | undefined;
|
|
const twoAssetManifest: StaticAssetManifestV1 = {
|
|
...manifest,
|
|
assets: [
|
|
manifest.assets[0]!,
|
|
{
|
|
url: `${ORIGIN}/assets/chunk.js`,
|
|
sha256: `sha256:${"c".repeat(64)}`,
|
|
bytes: 1,
|
|
contentType: "application/javascript",
|
|
},
|
|
],
|
|
};
|
|
const fetcher = vi.fn(
|
|
async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
if (String(input).endsWith("app.js")) {
|
|
return new Response(null, { status: 500 });
|
|
}
|
|
siblingSignal = init?.signal ?? undefined;
|
|
await new Promise<void>((resolve) => setTimeout(resolve, 10));
|
|
return new Response(new Uint8Array([1]), {
|
|
status: 200,
|
|
headers: { "content-type": "application/javascript" },
|
|
});
|
|
},
|
|
);
|
|
|
|
const installing = installStaticAssets(twoAssetManifest, {
|
|
caches: {
|
|
open: vi.fn(async () => ({ put: vi.fn() }) as unknown as Cache),
|
|
delete: vi.fn(async () => true),
|
|
},
|
|
fetcher: fetcher as typeof fetch,
|
|
digest: vi.fn(async () => twoAssetManifest.assets[1]!.sha256),
|
|
});
|
|
await vi.advanceTimersByTimeAsync(10);
|
|
|
|
await expect(installing).resolves.toEqual({
|
|
kind: "REJECTED",
|
|
code: "STATUS_INVALID",
|
|
});
|
|
expect(siblingSignal?.aborted).toBe(true);
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
|
|
/** A failing install through the runtime, with `existing` caches present. */
|
|
async function failInstall(existing: readonly string[]) {
|
|
const deleteCache = vi.fn(async (_name: string) => true);
|
|
const runtime = createServiceWorkerRuntime(
|
|
{
|
|
caches: {
|
|
open: vi.fn(async () => ({ put: vi.fn() }) as unknown as Cache),
|
|
keys: vi.fn(async () => existing),
|
|
delete: deleteCache,
|
|
},
|
|
clients: { matchAll: vi.fn(async () => []) },
|
|
registrationScope: `${ORIGIN}/`,
|
|
skipWaiting: vi.fn(async () => {}),
|
|
fetcher: vi.fn(async () => new Response(null, { status: 500 })),
|
|
digest: vi.fn(),
|
|
} as never,
|
|
{
|
|
identity,
|
|
handlers: ["PWA_STATIC_ASSETS"],
|
|
manifest,
|
|
runtimeConfigUrl: "/runtime-config.json",
|
|
releaseManifestUrl: "/release-manifest.json",
|
|
},
|
|
);
|
|
await expect(runtime.onInstall()).rejects.toThrow(
|
|
"STATIC_INSTALL_REJECTED:STATUS_INVALID",
|
|
);
|
|
return deleteCache;
|
|
}
|
|
|
|
it("keeps a candidate cache that already existed when install fails (Q-6.6-8)", async () => {
|
|
// Same asset set as the active worker (same build id, new worker code):
|
|
// the candidate name is the cache the active worker is serving from.
|
|
const candidate = staticCacheName(manifest.setDigest);
|
|
const deleteCache = await failInstall([candidate]);
|
|
expect(deleteCache).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("still deletes a candidate cache that this install created (Q-6.6-8)", async () => {
|
|
const candidate = staticCacheName(manifest.setDigest);
|
|
const deleteCache = await failInstall([
|
|
`${STATIC_CACHE_PREFIX}${"e".repeat(16)}`,
|
|
]);
|
|
expect(deleteCache.mock.calls.map((call) => call[0])).toEqual([candidate]);
|
|
});
|
|
|
|
it("accepts replies only from the captured waiting or controller source", async () => {
|
|
const browser = pageContainer({ waiting: true });
|
|
const controller = pageController(browser.container);
|
|
await controller.start();
|
|
const foreign = { postMessage: vi.fn() };
|
|
|
|
// SW-06. A same-origin but unrecognised source must not close admission.
|
|
browser.dispatch(
|
|
createServiceWorkerMessage({
|
|
kind: "CLIENT_DRAIN_REQUEST",
|
|
sourceBuildId: "worker-build",
|
|
targetBuildId: "page-build",
|
|
nonce: "drain-foreign",
|
|
}),
|
|
foreign,
|
|
);
|
|
expect(foreign.postMessage).not.toHaveBeenCalled();
|
|
await controller.stop();
|
|
});
|
|
|
|
it("coalesces concurrent activation and reset commands", async () => {
|
|
const browser = pageContainer({ waiting: true });
|
|
const controller = pageController(browser.container);
|
|
await controller.start();
|
|
|
|
// SW-06. Ten concurrent callers issue exactly one request.
|
|
const activations = Array.from({ length: 10 }, () =>
|
|
controller.requestActivation(),
|
|
);
|
|
await Promise.resolve();
|
|
expect(browser.waitingMessages).toHaveLength(1);
|
|
expect(new Set(activations).size).toBe(1);
|
|
|
|
await controller.stop();
|
|
await Promise.allSettled(activations);
|
|
});
|
|
|
|
it("ends an activation whose reply source was swapped", async () => {
|
|
const browser = pageContainer({ waiting: true });
|
|
const controller = pageController(browser.container);
|
|
await controller.start();
|
|
const activation = controller.requestActivation();
|
|
await Promise.resolve();
|
|
|
|
const request = browser.waitingMessages.at(-1) as { nonce?: string };
|
|
// A different worker answers: terminate immediately rather than waiting for
|
|
// the drain timeout.
|
|
browser.dispatch(
|
|
createServiceWorkerMessage({
|
|
kind: "ACTIVATED_RELOAD_REQUIRED",
|
|
sourceBuildId: "worker-build",
|
|
targetBuildId: "page-build",
|
|
nonce: request.nonce,
|
|
}),
|
|
{ postMessage: vi.fn() },
|
|
);
|
|
|
|
await expect(activation).resolves.toEqual({ kind: "PROTOCOL_MISMATCH" });
|
|
await controller.stop();
|
|
});
|
|
|
|
it("does not report a first install as ACTIVE while it is installing (R-6.4)", async () => {
|
|
const browser = pageContainer({ installing: true });
|
|
const controller = pageController(browser.container);
|
|
let outcome: unknown = "pending";
|
|
const starting = controller.start().then((value) => {
|
|
outcome = value;
|
|
return value;
|
|
});
|
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
expect(outcome).toBe("pending");
|
|
|
|
// Install finished; without clients.claim() this page stays uncontrolled.
|
|
const registration = browser.registration as unknown as {
|
|
installing: ServiceWorker | null;
|
|
active: ServiceWorker | null;
|
|
};
|
|
registration.installing = null;
|
|
registration.active = browser.installing as unknown as ServiceWorker;
|
|
setWorkerState(browser.installing!, "activated");
|
|
|
|
await expect(starting).resolves.toEqual({ kind: "RELOAD_TO_ENABLE" });
|
|
await controller.stop();
|
|
});
|
|
|
|
it("reports a failed first install instead of ACTIVE (R-6.4)", async () => {
|
|
const browser = pageContainer({ installing: true });
|
|
const controller = pageController(browser.container);
|
|
const starting = controller.start();
|
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
|
|
(browser.registration as unknown as { installing: null }).installing = null;
|
|
setWorkerState(browser.installing!, "redundant");
|
|
|
|
await expect(starting).resolves.toEqual({
|
|
kind: "FAILED",
|
|
code: "INSTALL_FAILED",
|
|
});
|
|
await controller.stop();
|
|
});
|
|
|
|
it("skips update checks while the injected host document is hidden (Q-6.6-12)", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
const browser = pageContainer({ controlled: true });
|
|
const hostDocument = { visibilityState: "hidden" as DocumentVisibilityState };
|
|
const host = createServiceWorkerRuntimeHost({
|
|
capabilities: {
|
|
serviceWorker: {
|
|
mode: "ACTIVE",
|
|
scriptPath: SERVICE_WORKER_SCRIPT_PATH,
|
|
handlers: [],
|
|
},
|
|
serviceWorkerDisabledCleanup: false,
|
|
} as never,
|
|
routerBasePath: "/",
|
|
buildId: "page-build",
|
|
host: {
|
|
location: { origin: ORIGIN },
|
|
navigator: { serviceWorker: browser.container },
|
|
document: hostDocument,
|
|
},
|
|
});
|
|
await expect(host?.start()).resolves.toMatchObject({ kind: "ACTIVE" });
|
|
|
|
await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.updateCheckIntervalMs);
|
|
expect(browser.registration.update).not.toHaveBeenCalled();
|
|
|
|
hostDocument.visibilityState = "visible";
|
|
await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.updateCheckIntervalMs);
|
|
expect(browser.registration.update).toHaveBeenCalledOnce();
|
|
await host?.stop();
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
|
|
it("announces an update that finished installing as waiting (R-6.3)", async () => {
|
|
const browser = pageContainer({ controlled: true });
|
|
const controller = pageController(browser.container);
|
|
await expect(controller.start()).resolves.toMatchObject({ kind: "ACTIVE" });
|
|
const updateWaiting = vi.fn();
|
|
controller.onUpdateWaiting?.(updateWaiting);
|
|
|
|
// What the browser does after a periodic `registration.update()` finds a
|
|
// new worker.
|
|
const registration = browser.registration as unknown as EventTarget & {
|
|
installing: ServiceWorker | null;
|
|
waiting: ServiceWorker | null;
|
|
};
|
|
const update = fakeWorker([], "installing");
|
|
registration.installing = update as unknown as ServiceWorker;
|
|
registration.dispatchEvent(new Event("updatefound"));
|
|
expect(updateWaiting).not.toHaveBeenCalled();
|
|
registration.installing = null;
|
|
registration.waiting = update as unknown as ServiceWorker;
|
|
setWorkerState(update, "installed");
|
|
|
|
expect(updateWaiting).toHaveBeenCalledTimes(1);
|
|
await controller.stop();
|
|
});
|
|
|
|
// 1101/06-04 (N8). A first install has no active worker to replace. It
|
|
// activates on its own, so it is never announced as an update waiting.
|
|
it("does not announce a first install as an update waiting", async () => {
|
|
const browser = pageContainer({ controlled: true });
|
|
const controller = pageController(browser.container);
|
|
await expect(controller.start()).resolves.toMatchObject({ kind: "ACTIVE" });
|
|
const updateWaiting = vi.fn();
|
|
controller.onUpdateWaiting?.(updateWaiting);
|
|
const registration = browser.registration as unknown as EventTarget & {
|
|
installing: ServiceWorker | null;
|
|
waiting: ServiceWorker | null;
|
|
active: ServiceWorker | null;
|
|
};
|
|
registration.active = null;
|
|
const first = fakeWorker([], "installing");
|
|
registration.installing = first as unknown as ServiceWorker;
|
|
registration.dispatchEvent(new Event("updatefound"));
|
|
registration.installing = null;
|
|
registration.waiting = first as unknown as ServiceWorker;
|
|
setWorkerState(first, "installed");
|
|
|
|
expect(updateWaiting).not.toHaveBeenCalled();
|
|
await controller.stop();
|
|
});
|
|
|
|
it("accepts a post-commit reply after the waiting worker was promoted (R-6.1)", async () => {
|
|
const browser = pageContainer({ waiting: true });
|
|
const controller = pageController(browser.container);
|
|
await controller.start();
|
|
const activation = controller.requestActivation();
|
|
await Promise.resolve();
|
|
const request = browser.waitingMessages.at(-1) as { nonce?: string };
|
|
|
|
// skipWaiting() already ran: the registration update can land before the
|
|
// worker's message does.
|
|
const registration = browser.registration as unknown as {
|
|
waiting: ServiceWorker | null;
|
|
active: ServiceWorker | null;
|
|
};
|
|
registration.active = browser.waiting;
|
|
registration.waiting = null;
|
|
browser.dispatch(
|
|
createServiceWorkerMessage({
|
|
kind: "ACTIVATE_ACCEPTED",
|
|
sourceBuildId: "worker-build",
|
|
targetBuildId: "page-build",
|
|
nonce: request.nonce,
|
|
}),
|
|
browser.waiting ?? undefined,
|
|
);
|
|
|
|
await expect(activation).resolves.toEqual({
|
|
kind: "ACTIVATED_RELOAD_REQUIRED",
|
|
});
|
|
await controller.stop();
|
|
});
|
|
|
|
it("ignores unrelated worker messages while an activation is pending (R-6.1)", async () => {
|
|
const browser = pageContainer({ waiting: true, controlled: true });
|
|
const controller = pageController(browser.container);
|
|
await controller.start();
|
|
const activation = controller.requestActivation();
|
|
await Promise.resolve();
|
|
const request = browser.waitingMessages.at(-1) as { nonce?: string };
|
|
|
|
browser.dispatch(
|
|
createServiceWorkerMessage({
|
|
kind: "SYNC_WAKE_OBSERVED",
|
|
sourceBuildId: "worker-build",
|
|
}),
|
|
browser.controlled ?? undefined,
|
|
);
|
|
browser.dispatch(
|
|
createServiceWorkerMessage({
|
|
kind: "ACTIVATED_RELOAD_REQUIRED",
|
|
sourceBuildId: "worker-build",
|
|
targetBuildId: "page-build",
|
|
nonce: request.nonce,
|
|
}),
|
|
browser.waiting ?? undefined,
|
|
);
|
|
|
|
await expect(activation).resolves.toEqual({
|
|
kind: "ACTIVATED_RELOAD_REQUIRED",
|
|
});
|
|
await controller.stop();
|
|
});
|
|
});
|
|
|
|
/**
|
|
* Page controllers and the worker runtime wired together. Each tab sees the
|
|
* waiting worker through its own `ServiceWorker` object; messages are
|
|
* delivered asynchronously in both directions, like postMessage.
|
|
*/
|
|
function activationSeam(tabBuildIds: readonly string[]) {
|
|
const workerScope = {
|
|
caches: { open: vi.fn(), keys: vi.fn(async () => []), delete: vi.fn() },
|
|
clients: {
|
|
matchAll: vi.fn(async () => tabs.map((tab) => tab.client)),
|
|
},
|
|
registrationScope: `${ORIGIN}/`,
|
|
skipWaiting: vi.fn(async () => {
|
|
for (const tab of tabs) {
|
|
tab.registration.active = tab.waiting;
|
|
tab.registration.waiting = null;
|
|
}
|
|
}),
|
|
fetcher: vi.fn(),
|
|
digest: vi.fn(),
|
|
};
|
|
const runtime = createServiceWorkerRuntime(workerScope as never, {
|
|
identity,
|
|
handlers: [],
|
|
manifest: null,
|
|
runtimeConfigUrl: "/runtime-config.json",
|
|
releaseManifestUrl: "/release-manifest.json",
|
|
});
|
|
const tabs = tabBuildIds.map((buildId, index) => {
|
|
const id = `tab-${index}`;
|
|
const listeners = new Set<(event: MessageEvent) => void>();
|
|
// Page → worker, routed like `service-worker-entry.ts` does.
|
|
const waiting = {
|
|
scriptURL: SCRIPT_URL,
|
|
postMessage(message: { kind: string }) {
|
|
queueMicrotask(() => {
|
|
if (message.kind === "ACTIVATE_REQUEST") {
|
|
void runtime.onActivateRequest(message);
|
|
} else {
|
|
runtime.onClientMessage(message, id);
|
|
}
|
|
});
|
|
},
|
|
};
|
|
const registration: EventTarget & {
|
|
scope: string;
|
|
installing: null;
|
|
waiting: typeof waiting | null;
|
|
active: typeof waiting | null;
|
|
update(): Promise<void>;
|
|
} = Object.assign(new EventTarget(), {
|
|
scope: `${ORIGIN}/`,
|
|
installing: null,
|
|
waiting: waiting as typeof waiting | null,
|
|
active: null as typeof waiting | null,
|
|
update: async () => {},
|
|
});
|
|
const container = {
|
|
controller: null,
|
|
register: vi.fn(async () => registration),
|
|
addEventListener(_type: string, listener: (event: MessageEvent) => void) {
|
|
listeners.add(listener);
|
|
},
|
|
removeEventListener(
|
|
_type: string,
|
|
listener: (event: MessageEvent) => void,
|
|
) {
|
|
listeners.delete(listener);
|
|
},
|
|
};
|
|
// Worker → page: the sender is this tab's view of the waiting worker.
|
|
const client = {
|
|
id,
|
|
url: `${ORIGIN}/page-${index}`,
|
|
postMessage(data: unknown) {
|
|
queueMicrotask(() => {
|
|
const event = { data, origin: ORIGIN, source: waiting };
|
|
for (const listener of [...listeners]) {
|
|
listener(event as unknown as MessageEvent);
|
|
}
|
|
});
|
|
},
|
|
};
|
|
const controller = createServiceWorkerPageController({
|
|
selection: {
|
|
mode: "ACTIVE",
|
|
scriptPath: SERVICE_WORKER_SCRIPT_PATH,
|
|
handlers: [],
|
|
},
|
|
disabledCleanup: false,
|
|
routerBasePath: "/",
|
|
origin: ORIGIN,
|
|
buildId,
|
|
container: container as unknown as ServiceWorkerContainer,
|
|
blockers: [() => false],
|
|
});
|
|
return { id, waiting, registration, client, controller };
|
|
});
|
|
return { runtime, workerScope, tabs };
|
|
}
|
|
|
|
describe("page ↔ worker activation seam", () => {
|
|
it("drains tabs of another build and completes the activation (R-6.2)", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
const seam = activationSeam(["page-build-n", "page-build-n1"]);
|
|
for (const tab of seam.tabs) await tab.controller.start();
|
|
|
|
// The freshly reloaded tab (build N+1) asks; the older tab must drain.
|
|
const activation = seam.tabs[1]!.controller.requestActivation();
|
|
await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.clientDrainMs);
|
|
|
|
await expect(activation).resolves.toEqual({
|
|
kind: "ACTIVATED_RELOAD_REQUIRED",
|
|
});
|
|
expect(seam.workerScope.skipWaiting).toHaveBeenCalledTimes(1);
|
|
for (const tab of seam.tabs) await tab.controller.stop();
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
|
|
it("tells a tab that did not ask that a reload is required (R-6.3)", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
const seam = activationSeam(["page-build-n", "page-build-n1"]);
|
|
for (const tab of seam.tabs) await tab.controller.start();
|
|
const reloadRequired = vi.fn();
|
|
seam.tabs[0]!.controller.onReloadRequired?.(reloadRequired);
|
|
|
|
const activation = seam.tabs[1]!.controller.requestActivation();
|
|
await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.clientDrainMs);
|
|
|
|
await expect(activation).resolves.toEqual({
|
|
kind: "ACTIVATED_RELOAD_REQUIRED",
|
|
});
|
|
expect(reloadRequired).toHaveBeenCalledTimes(1);
|
|
for (const tab of seam.tabs) await tab.controller.stop();
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
|
|
it("waits past the worker's drain window for its commit reply (Q-6.6-10b)", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
const seam = activationSeam(["page-build-n", "page-build-n1"]);
|
|
for (const tab of seam.tabs) await tab.controller.start();
|
|
// The last tab answers 1ms before the worker's drain deadline, and
|
|
// skipWaiting() then takes 50ms: the worker commits after 30s.
|
|
const slowTab = seam.tabs[0]!.waiting;
|
|
const deliver = slowTab.postMessage.bind(slowTab);
|
|
slowTab.postMessage = (message) => {
|
|
if (message.kind !== "CLIENT_DRAINED") return deliver(message);
|
|
setTimeout(
|
|
() => deliver(message),
|
|
SERVICE_WORKER_BOUNDS.clientDrainMs - 1,
|
|
);
|
|
};
|
|
const promote = seam.workerScope.skipWaiting.getMockImplementation()!;
|
|
seam.workerScope.skipWaiting.mockImplementation(async () => {
|
|
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
await promote();
|
|
});
|
|
|
|
const activation = seam.tabs[1]!.controller.requestActivation();
|
|
await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.clientDrainMs + 100);
|
|
|
|
await expect(activation).resolves.toEqual({
|
|
kind: "ACTIVATED_RELOAD_REQUIRED",
|
|
});
|
|
for (const tab of seam.tabs) await tab.controller.stop();
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
|
|
// 06-07. A window without a page controller (a tab showing /config.json, a
|
|
// frozen background tab) never answers the drain. That is a timeout, not a
|
|
// tab with unsaved edits.
|
|
it("reports a window that never answers as CLIENT_DRAIN_TIMEOUT", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
const seam = activationSeam(["page-build-n", "page-build-n1"]);
|
|
for (const tab of seam.tabs) await tab.controller.start();
|
|
seam.workerScope.clients.matchAll.mockResolvedValue([
|
|
...seam.tabs.map((tab) => tab.client),
|
|
{ id: "raw-json", url: `${ORIGIN}/config.json`, postMessage() {} },
|
|
]);
|
|
|
|
const activation = seam.tabs[1]!.controller.requestActivation();
|
|
await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.clientDrainMs);
|
|
|
|
await expect(activation).resolves.toEqual({
|
|
kind: "CLIENT_DRAIN_TIMEOUT",
|
|
});
|
|
expect(seam.workerScope.skipWaiting).not.toHaveBeenCalled();
|
|
for (const tab of seam.tabs) await tab.controller.stop();
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
|
|
it("reports a failed skipWaiting() as FAILED, not as a dirty tab", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
const seam = activationSeam(["page-build-n", "page-build-n1"]);
|
|
for (const tab of seam.tabs) await tab.controller.start();
|
|
seam.workerScope.skipWaiting.mockRejectedValue(new Error("commit"));
|
|
|
|
const activation = seam.tabs[1]!.controller.requestActivation();
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
|
|
await expect(activation).resolves.toEqual({
|
|
kind: "FAILED",
|
|
code: "ACTIVATION_COMMIT_FAILED",
|
|
});
|
|
for (const tab of seam.tabs) await tab.controller.stop();
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
|
|
it("still reports a tab that refuses the drain as BLOCKED_DIRTY_CLIENT", async () => {
|
|
vi.useFakeTimers();
|
|
try {
|
|
const seam = activationSeam(["page-build-n", "page-build-n1"]);
|
|
for (const tab of seam.tabs) await tab.controller.start();
|
|
// Tab 0 answers the drain with an explicit rejection (unsaved edits).
|
|
const dirtyTab = seam.tabs[0]!.waiting;
|
|
const deliver = dirtyTab.postMessage.bind(dirtyTab);
|
|
dirtyTab.postMessage = (message) =>
|
|
deliver(
|
|
message.kind === "CLIENT_DRAINED"
|
|
? { ...message, kind: "ACTIVATE_REJECTED" }
|
|
: message,
|
|
);
|
|
|
|
const activation = seam.tabs[1]!.controller.requestActivation();
|
|
await vi.advanceTimersByTimeAsync(0);
|
|
|
|
await expect(activation).resolves.toEqual({
|
|
kind: "BLOCKED_DIRTY_CLIENT",
|
|
});
|
|
for (const tab of seam.tabs) await tab.controller.stop();
|
|
} finally {
|
|
vi.useRealTimers();
|
|
}
|
|
});
|
|
});
|
|
|
|
/**
|
|
* Loads the real worker entry against stubbed worker globals and build-time
|
|
* constants, and returns the listeners it registered on `self`.
|
|
*/
|
|
async function loadWorkerEntry(
|
|
handlers: readonly string[],
|
|
cacheStorage: unknown = {
|
|
open: async () => ({ match: async () => new Response("cached") }),
|
|
keys: async () => [],
|
|
delete: async () => true,
|
|
},
|
|
) {
|
|
const listeners = new Map<string, (event: unknown) => void>();
|
|
vi.stubGlobal("self", {
|
|
addEventListener: (type: string, listener: (event: unknown) => void) => {
|
|
listeners.set(type, listener);
|
|
},
|
|
registration: { scope: `${ORIGIN}/` },
|
|
clients: { matchAll: async () => [] },
|
|
skipWaiting: async () => {},
|
|
});
|
|
vi.stubGlobal("__CA_SERVICE_WORKER_BUILD_INFO__", identity);
|
|
vi.stubGlobal("__CA_SERVICE_WORKER_ASSETS__", {
|
|
schemaVersion: 1,
|
|
buildId: identity.buildId,
|
|
releaseId: identity.releaseId,
|
|
setDigest: identity.staticAssetSetDigest,
|
|
assets: [
|
|
{
|
|
url: "/assets/app-Dq3x8Yk2.js",
|
|
sha256: `sha256:${"d".repeat(64)}`,
|
|
bytes: 6,
|
|
contentType: "text/javascript",
|
|
},
|
|
],
|
|
});
|
|
vi.stubGlobal("__CA_SERVICE_WORKER_HANDLERS__", handlers);
|
|
vi.stubGlobal("__CA_RUNTIME_CONFIG_URL__", "/runtime-config.json");
|
|
vi.stubGlobal("__CA_RELEASE_MANIFEST_URL__", "/release-manifest.json");
|
|
vi.stubGlobal("caches", cacheStorage);
|
|
vi.stubGlobal("fetch", async () => new Response("network"));
|
|
vi.resetModules();
|
|
// A computed specifier keeps the WebWorker-lib entry out of the DOM-lib
|
|
// test type program.
|
|
const entry = "../../src/adapters/service-worker/service-worker-entry.ts";
|
|
await import(/* @vite-ignore */ entry);
|
|
return listeners;
|
|
}
|
|
|
|
describe("service worker entry fetch interception (R-6.6, Q-6.6-6b)", () => {
|
|
function fetchEvent(request: { method: string; url: string; mode: string }) {
|
|
return { request, respondWith: vi.fn() };
|
|
}
|
|
|
|
it("answers manifest assets and leaves navigations, API, cross-origin and unhashed requests alone", async () => {
|
|
try {
|
|
const listeners = await loadWorkerEntry(["PWA_STATIC_ASSETS"]);
|
|
const onFetch = listeners.get("fetch")!;
|
|
const asset = `${ORIGIN}/assets/app-Dq3x8Yk2.js`;
|
|
const passthrough = [
|
|
{ method: "GET", url: `${ORIGIN}/`, mode: "navigate" },
|
|
{ method: "GET", url: asset, mode: "navigate" },
|
|
{ method: "POST", url: asset, mode: "cors" },
|
|
{ method: "GET", url: `${ORIGIN}/api/users`, mode: "cors" },
|
|
{ method: "GET", url: `${ORIGIN}/runtime-config.json`, mode: "cors" },
|
|
// `-manifest.json` looks like a content hash; it is still network-only.
|
|
{ method: "GET", url: `${ORIGIN}/release-manifest.json`, mode: "cors" },
|
|
{ method: "GET", url: "https://cdn.example/assets/app-Dq3x8Yk2.js", mode: "cors" },
|
|
{ method: "GET", url: "https://cdn.example/assets/old-Zz9Yy8Xx.js", mode: "cors" },
|
|
// Q-6.6-6b. Same-origin but not a content-hashed name.
|
|
{ method: "GET", url: `${ORIGIN}/assets/app.js`, mode: "cors" },
|
|
{ method: "GET", url: `${ORIGIN}/favicon.ico`, mode: "no-cors" },
|
|
{ method: "POST", url: `${ORIGIN}/assets/old-Zz9Yy8Xx.js`, mode: "cors" },
|
|
{ method: "GET", url: `${ORIGIN}/assets/old-Zz9Yy8Xx.js`, mode: "navigate" },
|
|
];
|
|
for (const request of passthrough) {
|
|
const event = fetchEvent(request);
|
|
onFetch(event);
|
|
expect(event.respondWith, `${request.method} ${request.url} ${request.mode}`).not.toHaveBeenCalled();
|
|
}
|
|
|
|
const event = fetchEvent({ method: "GET", url: asset, mode: "cors" });
|
|
onFetch(event);
|
|
expect(event.respondWith).toHaveBeenCalledOnce();
|
|
const response = (await event.respondWith.mock.calls[0]![0]) as Response;
|
|
await expect(response.text()).resolves.toBe("cached");
|
|
} finally {
|
|
vi.unstubAllGlobals();
|
|
}
|
|
});
|
|
|
|
/**
|
|
* Q-6.6-6b. The current cache is empty; the previous release cache (found by
|
|
* its activation marker) still holds the old build's lazy chunk.
|
|
*/
|
|
function previousReleaseStorage(oldChunk: string) {
|
|
const current = staticCacheName(identity.staticAssetSetDigest);
|
|
const previous = `${STATIC_CACHE_PREFIX}${"e".repeat(16)}`;
|
|
const marker = JSON.stringify({
|
|
schemaVersion: 1,
|
|
cacheName: previous,
|
|
activationSequence: 1,
|
|
});
|
|
return {
|
|
open: async (name: string) => ({
|
|
match: async (url: string) => {
|
|
if (name !== previous) return undefined;
|
|
if (url === oldChunk) return new Response("previous");
|
|
return url.startsWith("https://clean-architecture.invalid/")
|
|
? new Response(marker)
|
|
: undefined;
|
|
},
|
|
}),
|
|
keys: async () => [current, previous],
|
|
delete: async () => true,
|
|
};
|
|
}
|
|
|
|
it("serves an old build's hashed chunk from the previous release cache (Q-6.6-6b)", async () => {
|
|
try {
|
|
const oldChunk = `${ORIGIN}/assets/settings-Zz9Yy8Xx.js`;
|
|
const listeners = await loadWorkerEntry(
|
|
["PWA_STATIC_ASSETS"],
|
|
previousReleaseStorage(oldChunk),
|
|
);
|
|
const event = fetchEvent({ method: "GET", url: oldChunk, mode: "cors" });
|
|
listeners.get("fetch")!(event);
|
|
|
|
expect(event.respondWith).toHaveBeenCalledOnce();
|
|
const response = (await event.respondWith.mock.calls[0]![0]) as Response;
|
|
await expect(response.text()).resolves.toBe("previous");
|
|
} finally {
|
|
vi.unstubAllGlobals();
|
|
}
|
|
});
|
|
|
|
it("falls back to the network when the previous release cache misses too (Q-6.6-6b)", async () => {
|
|
try {
|
|
const listeners = await loadWorkerEntry(
|
|
["PWA_STATIC_ASSETS"],
|
|
previousReleaseStorage(`${ORIGIN}/assets/settings-Zz9Yy8Xx.js`),
|
|
);
|
|
const event = fetchEvent({
|
|
method: "GET",
|
|
url: `${ORIGIN}/assets/unknown-Qq1Ww2Ee.js`,
|
|
mode: "cors",
|
|
});
|
|
listeners.get("fetch")!(event);
|
|
|
|
expect(event.respondWith).toHaveBeenCalledOnce();
|
|
const response = (await event.respondWith.mock.calls[0]![0]) as Response;
|
|
await expect(response.text()).resolves.toBe("network");
|
|
} finally {
|
|
vi.unstubAllGlobals();
|
|
}
|
|
});
|
|
|
|
it("registers no fetch listener without the static asset handler", async () => {
|
|
try {
|
|
const listeners = await loadWorkerEntry(["WEB_PUSH"]);
|
|
expect(listeners.has("fetch")).toBe(false);
|
|
} finally {
|
|
vi.unstubAllGlobals();
|
|
}
|
|
});
|
|
});
|
|
|
|
/**
|
|
* SW-01. The marker read must be bounded in bytes, not only in logic. Adding a
|
|
* whole chunk and *then* comparing the running total meant a corrupt body could
|
|
* hand activation a 1 MiB chunk against a 257-byte ceiling, and the reader lock
|
|
* was never released.
|
|
*/
|
|
describe("SW-01 the activation marker read is bounded in bytes", () => {
|
|
function scopeWithMarkerBody(
|
|
body: ReadableStream<Uint8Array> | null,
|
|
headers: Readonly<Record<string, string>> = {},
|
|
) {
|
|
const markerUrl = "__service-worker-activation-v1__";
|
|
const response = body
|
|
? new Response(body, { status: 200, headers })
|
|
: new Response("", { status: 200, headers });
|
|
const cache = {
|
|
match: vi.fn(async (request: RequestInfo | URL) =>
|
|
String(request).includes(markerUrl) ? response : undefined,
|
|
),
|
|
put: vi.fn(async () => {}),
|
|
delete: vi.fn(async () => true),
|
|
} as unknown as Cache;
|
|
return {
|
|
response,
|
|
scope: {
|
|
caches: {
|
|
open: vi.fn(async () => cache),
|
|
// The current static cache must exist for its marker to be read.
|
|
keys: vi.fn(async () => [
|
|
staticCacheName(identity.staticAssetSetDigest),
|
|
]),
|
|
delete: vi.fn(async () => true),
|
|
match: vi.fn(),
|
|
},
|
|
clients: { matchAll: vi.fn(async () => []) },
|
|
skipWaiting: vi.fn(async () => {}),
|
|
fetcher: vi.fn(),
|
|
digest: vi.fn(),
|
|
},
|
|
};
|
|
}
|
|
|
|
const runtimeFor = (scope: unknown) =>
|
|
createServiceWorkerRuntime(scope as never, {
|
|
identity,
|
|
handlers: ["PWA_STATIC_ASSETS"],
|
|
manifest: {
|
|
schemaVersion: 1,
|
|
buildId: identity.buildId,
|
|
releaseId: identity.releaseId,
|
|
setDigest: identity.staticAssetSetDigest as `sha256:${string}`,
|
|
assets: [],
|
|
},
|
|
runtimeConfigUrl: "/runtime-config.json",
|
|
releaseManifestUrl: "/release-manifest.json",
|
|
});
|
|
|
|
it("never retains a single chunk larger than the marker ceiling", async () => {
|
|
let delivered = 0;
|
|
let cancels = 0;
|
|
const oversized = new ReadableStream<Uint8Array>({
|
|
pull(controller) {
|
|
delivered += 1;
|
|
controller.enqueue(new Uint8Array(1_048_576));
|
|
},
|
|
cancel() {
|
|
cancels += 1;
|
|
},
|
|
});
|
|
const fixture = scopeWithMarkerBody(oversized);
|
|
|
|
// Activation still completes; the marker is simply not admitted.
|
|
await expect(runtimeFor(fixture.scope).onActivate()).resolves.toBeTypeOf(
|
|
"number",
|
|
);
|
|
// Every oversized chunk that arrived was refused before being retained,
|
|
// and the reader that saw it was cancelled. The marker is probed once per
|
|
// candidate cache, so the counts track each other rather than a constant.
|
|
expect(cancels).toBeGreaterThanOrEqual(1);
|
|
expect(delivered).toBeLessThanOrEqual(2);
|
|
expect(fixture.response.body?.locked).toBe(false);
|
|
});
|
|
|
|
it("bounds a stream that never produces a chunk", async () => {
|
|
let cancels = 0;
|
|
const stalled = new ReadableStream<Uint8Array>({
|
|
pull() {
|
|
return new Promise<void>(() => {});
|
|
},
|
|
cancel() {
|
|
cancels += 1;
|
|
},
|
|
});
|
|
const fixture = scopeWithMarkerBody(stalled);
|
|
|
|
await expect(
|
|
runtimeFor(fixture.scope).onActivate(),
|
|
).resolves.toBeTypeOf("number");
|
|
expect(cancels).toBeGreaterThanOrEqual(1);
|
|
}, 10_000);
|
|
|
|
it("cancels the body it refuses for a declared oversize", async () => {
|
|
let cancels = 0;
|
|
const declared = new ReadableStream<Uint8Array>({
|
|
pull(controller) {
|
|
controller.enqueue(new Uint8Array(8));
|
|
},
|
|
cancel() {
|
|
cancels += 1;
|
|
},
|
|
});
|
|
const fixture = scopeWithMarkerBody(declared, {
|
|
"content-length": "1048576",
|
|
});
|
|
|
|
await expect(
|
|
runtimeFor(fixture.scope).onActivate(),
|
|
).resolves.toBeTypeOf("number");
|
|
await new Promise((resolve) => setTimeout(resolve, 0));
|
|
expect(cancels).toBeGreaterThanOrEqual(1);
|
|
});
|
|
|
|
it("refuses a marker body that is not valid UTF-8", async () => {
|
|
const invalid = new ReadableStream<Uint8Array>({
|
|
start(controller) {
|
|
controller.enqueue(new Uint8Array([0xff, 0xfe, 0xfd]));
|
|
controller.close();
|
|
},
|
|
});
|
|
const fixture = scopeWithMarkerBody(invalid);
|
|
|
|
await expect(
|
|
runtimeFor(fixture.scope).onActivate(),
|
|
).resolves.toBeTypeOf("number");
|
|
expect(fixture.response.body?.locked).toBe(false);
|
|
});
|
|
});
|
|
|
|
/**
|
|
* 06-08. The previous-release fallback is for old build chunks only. A hashed
|
|
* looking API or download name outside the build asset directory is left to
|
|
* the browser.
|
|
*/
|
|
describe("fetch classification of hashed-looking URLs", () => {
|
|
const classify = (path: string, scopeUrl = `${ORIGIN}/`) =>
|
|
classifyFetch({
|
|
method: "GET",
|
|
requestUrl: `${ORIGIN}${path}`,
|
|
isNavigation: false,
|
|
runtimeConfigUrl: `${ORIGIN}/config.json`,
|
|
releaseManifestUrl: `${ORIGIN}/release-manifest.json`,
|
|
manifestUrls: new Set(),
|
|
scopeUrl,
|
|
});
|
|
|
|
it.each([
|
|
"/api/v1/user-profiles.json",
|
|
"/api/reports/monthly-summary2026.csv",
|
|
"/media/onboarding-video-final.mp4",
|
|
"/downloads/release-notes-20260925.pdf",
|
|
])("passes %s through", (path) => {
|
|
expect(classify(path)).toBe("NETWORK_PASSTHROUGH");
|
|
});
|
|
|
|
it("falls back only for a hashed name under the build asset directory", () => {
|
|
expect(classify("/assets/route-chunk-AbCd1234.js")).toBe(
|
|
"PREVIOUS_RELEASE_FALLBACK",
|
|
);
|
|
expect(classify("/app/assets/route-chunk-AbCd1234.js", `${ORIGIN}/app/`)).toBe(
|
|
"PREVIOUS_RELEASE_FALLBACK",
|
|
);
|
|
expect(classify("/assets/route-chunk-AbCd1234.js", `${ORIGIN}/app/`)).toBe(
|
|
"NETWORK_PASSTHROUGH",
|
|
);
|
|
});
|
|
});
|