Carries 359 template commits, tag v0.2.0 plus one documentation commit: the generator-built feature index with its app, bounded-context and feature declarations, the src/platform kernel and scale tooling, the 2026-09-24 src review fixes, and the 2026-09-25 maturity review round with its CHANGELOG [보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them merged with product changes; 127 are not carried. Product identity is unchanged: name, version 0.1.0, routes, design and the TechLog domain. Three decisions worth naming. TechLog stays composed directly, as the last two syncs recorded; its directory carries a NOT_INSTALLED marker that says so, and every installed-* composer takes the template's projection with TechLog added on top. The reference sample is no longer installed: the template now installs a feature only through feature-module.ts and context-routes.ts, which load the screens this product deleted, so its three operations, six schemas and one topic leave the registries, recorded as registry change evidence. And AppRouter mounts the platform and TechLog routes only; the template's bounded-context route gateway waits for a generator-installed feature. Required fixes: readSubject on the BFF session owner (without it every HTTP Studio session would close as integration-failed), zod through the facade in nine TechLog files, noUnusedLocals, and public/config.json written out to match the local profile. Derived baselines were recomputed after reproducing both sides' values: CI contract 101 commands / 106 references / 141 artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime config schema baseline equals the schema at8210d48. Verified here: types, lint, architecture, adapter inventory, CI contract, i18n, design system, diagnostics, browser security, dev release manifest, TechLog contract and build pass; 220 component, 155 integration, 15 contract, 418 TechLog, 43 reference-feature, 18 recipe and 46 release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at8210d48first and unchanged: check:registries (byte-identical), test:runtime-schema, verify:documentation. Brought by the template and escalated rather than suppressed: check:request-fanout on TechLog's cursor pagination, check:remediation-ledger (fails upstream too), the shared-chunk hash test, and the registry-dependent sample removal and second-feature tests. Playwright suites were not run. Full record, the five open questions and the follow-ups in docs/operations/template-sync-2026-09-29.md. (cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
1016 lines
31 KiB
TypeScript
1016 lines
31 KiB
TypeScript
import { describe, expect, it, vi } from "vitest";
|
|
|
|
import {
|
|
WEB_PUSH_PROTOCOLS,
|
|
type NotificationClickDataV1,
|
|
} from "../../src/contracts/web-push.ts";
|
|
import { createPushAssociationFenceStore } from "../../src/adapters/web-push/push-association-fence-store.ts";
|
|
import { createWebPushNotificationRegistry } from "../../src/adapters/web-push/notification-registry.ts";
|
|
import { createPushEventAdapter } from "../../src/adapters/web-push/inbound/push-event-adapter.ts";
|
|
import { createNotificationClickAdapter } from "../../src/adapters/web-push/inbound/notification-click-adapter.ts";
|
|
import { createWebPushServiceWorkerRuntime } from "../../src/adapters/web-push/service-worker-runtime.ts";
|
|
import type { TimeoutScheduler } from "../../src/adapters/web-push/runtime-support.ts";
|
|
import {
|
|
createFakePushControlStoreDependencies,
|
|
} from "../helpers/fake-push-control-repository.ts";
|
|
|
|
const now = Date.parse("2026-07-28T00:00:00.000Z");
|
|
const authority = Object.freeze({
|
|
fenceGeneration: "fence_01",
|
|
sessionBindingEpoch: "session_01",
|
|
releaseEpoch: "release_01",
|
|
});
|
|
const nextAuthority = Object.freeze({
|
|
fenceGeneration: "fence_02",
|
|
sessionBindingEpoch: "session_02",
|
|
releaseEpoch: "release_01",
|
|
});
|
|
const registry = createWebPushNotificationRegistry([
|
|
{
|
|
notificationType: "INBOX_ACTIVITY",
|
|
routeIntent: "OPEN_INBOX",
|
|
title: "새 알림이 있습니다",
|
|
body: "앱을 열어 최신 내용을 확인하세요.",
|
|
path: "/inbox",
|
|
},
|
|
]);
|
|
|
|
async function activeFence() {
|
|
const store = createPushAssociationFenceStore(
|
|
createFakePushControlStoreDependencies(),
|
|
);
|
|
const prepared = await store.prepare({
|
|
authority,
|
|
updatedAt: "2026-07-28T00:00:00.000Z",
|
|
});
|
|
if (!prepared.ok) throw new Error("expected prepared push control");
|
|
const active = await store.activate({
|
|
expectedRevision: prepared.value.revision,
|
|
authority,
|
|
associationEpoch: "association_01",
|
|
updatedAt: "2026-07-28T00:00:01.000Z",
|
|
});
|
|
if (!active.ok) throw new Error("expected active push control");
|
|
return store;
|
|
}
|
|
|
|
function hint(overrides: Readonly<Record<string, unknown>> = {}) {
|
|
return {
|
|
protocol: WEB_PUSH_PROTOCOLS.hint,
|
|
notificationType: "INBOX_ACTIVITY",
|
|
notificationId: "notification_01",
|
|
associationEpoch: "association_01",
|
|
releaseEpoch: "release_01",
|
|
issuedAt: "2026-07-27T23:59:00.000Z",
|
|
expiresAt: "2026-07-28T01:00:00.000Z",
|
|
routeIntent: "OPEN_INBOX",
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function clickData(): NotificationClickDataV1 {
|
|
return {
|
|
protocol: WEB_PUSH_PROTOCOLS.click,
|
|
notificationId: "notification_01",
|
|
routeIntent: "OPEN_INBOX",
|
|
associationEpoch: "association_01",
|
|
releaseEpoch: "release_01",
|
|
expiresAt: "2026-07-28T01:00:00.000Z",
|
|
};
|
|
}
|
|
|
|
function manualScheduler(): Readonly<{
|
|
scheduler: TimeoutScheduler;
|
|
delays: readonly number[];
|
|
expireAll(): void;
|
|
}> {
|
|
let sequence = 0;
|
|
const callbacks = new Map<number, () => void>();
|
|
const delays: number[] = [];
|
|
return {
|
|
scheduler: {
|
|
setTimeout(callback, milliseconds) {
|
|
sequence += 1;
|
|
delays.push(milliseconds);
|
|
callbacks.set(sequence, callback);
|
|
return sequence;
|
|
},
|
|
clearTimeout(handle) {
|
|
if (typeof handle === "number") callbacks.delete(handle);
|
|
},
|
|
},
|
|
expireAll() {
|
|
for (const callback of [...callbacks.values()]) callback();
|
|
},
|
|
delays,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 06-01. WebIDL shape of a real `Notification`: `data` is a getter and
|
|
* `close` a method on the prototype, so the instance has no own keys
|
|
* (checked in Chromium, Firefox and WebKit).
|
|
*/
|
|
class WebIdlNotification {
|
|
readonly #data: unknown;
|
|
closed = 0;
|
|
constructor(data: unknown) {
|
|
this.#data = data;
|
|
}
|
|
get data(): unknown {
|
|
return this.#data;
|
|
}
|
|
close(): void {
|
|
this.closed += 1;
|
|
}
|
|
}
|
|
|
|
describe("Web Push worker runtime", () => {
|
|
it("waits for strict hint handling and shows only registry-owned safe copy", async () => {
|
|
const store = await activeFence();
|
|
const shown: Array<Readonly<{ title: string; options: unknown }>> = [];
|
|
let waited: Promise<void> | null = null;
|
|
const adapter = createPushEventAdapter({
|
|
fenceStore: store,
|
|
registry,
|
|
now: () => now,
|
|
tagDigest: async () => new Uint8Array(32).fill(9).buffer,
|
|
notifications: {
|
|
async showNotification(title, options) {
|
|
shown.push({ title, options });
|
|
},
|
|
},
|
|
});
|
|
const bytes = new TextEncoder().encode(JSON.stringify(hint()));
|
|
const result = await adapter.handle({
|
|
data: { arrayBuffer: () => bytes.slice().buffer },
|
|
waitUntil(task) {
|
|
waited = task;
|
|
},
|
|
});
|
|
await waited;
|
|
|
|
expect(result).toEqual({ ok: true, value: undefined });
|
|
expect(shown).toHaveLength(1);
|
|
expect(shown[0]).toMatchObject({
|
|
title: "새 알림이 있습니다",
|
|
options: {
|
|
body: "앱을 열어 최신 내용을 확인하세요.",
|
|
data: {
|
|
protocol: WEB_PUSH_PROTOCOLS.click,
|
|
notificationId: "notification_01",
|
|
},
|
|
},
|
|
});
|
|
expect(
|
|
(shown[0]?.options as { tag: string }).tag,
|
|
).not.toContain("association_01");
|
|
});
|
|
|
|
it("drops mismatched associations before notification rendering", async () => {
|
|
const store = await activeFence();
|
|
const showNotification = vi.fn(async () => {});
|
|
const adapter = createPushEventAdapter({
|
|
fenceStore: store,
|
|
registry,
|
|
now: () => now,
|
|
tagDigest: async () => new Uint8Array(32).buffer,
|
|
notifications: { showNotification },
|
|
});
|
|
const bytes = new TextEncoder().encode(
|
|
JSON.stringify(hint({ associationEpoch: "association_old" })),
|
|
);
|
|
const result = await adapter.handle({
|
|
data: { arrayBuffer: () => bytes.slice().buffer },
|
|
waitUntil() {},
|
|
});
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { code: "ASSOCIATION_MISMATCH" },
|
|
});
|
|
expect(showNotification).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("aborts late worker work at the handler deadline before notification display", async () => {
|
|
const store = await activeFence();
|
|
const clock = manualScheduler();
|
|
const showNotification = vi.fn(async () => {});
|
|
let signalDigestStarted: (() => void) | undefined;
|
|
const digestStarted = new Promise<void>((resolve) => {
|
|
signalDigestStarted = resolve;
|
|
});
|
|
let finishDigest: ((value: ArrayBuffer) => void) | undefined;
|
|
const digest = new Promise<ArrayBuffer>((resolve) => {
|
|
finishDigest = resolve;
|
|
});
|
|
const adapter = createPushEventAdapter({
|
|
fenceStore: store,
|
|
registry,
|
|
now: () => now,
|
|
handlerDeadlineMs: 1,
|
|
scheduler: clock.scheduler,
|
|
tagDigest: async () => {
|
|
signalDigestStarted?.();
|
|
return await digest;
|
|
},
|
|
notifications: { showNotification },
|
|
});
|
|
const bytes = new TextEncoder().encode(JSON.stringify(hint()));
|
|
const handling = adapter.handle({
|
|
data: { arrayBuffer: () => bytes.slice().buffer },
|
|
waitUntil() {},
|
|
});
|
|
await digestStarted;
|
|
|
|
clock.expireAll();
|
|
expect(await handling).toMatchObject({
|
|
ok: false,
|
|
error: { code: "DEADLINE_EXCEEDED" },
|
|
});
|
|
finishDigest?.(new Uint8Array(32).buffer);
|
|
await Promise.resolve();
|
|
await Promise.resolve();
|
|
expect(showNotification).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rechecks the durable generation after async push work", async () => {
|
|
const store = await activeFence();
|
|
const showNotification = vi.fn(async () => {});
|
|
const adapter = createPushEventAdapter({
|
|
fenceStore: store,
|
|
registry,
|
|
now: () => now,
|
|
notifications: { showNotification },
|
|
tagDigest: async () => {
|
|
const current = await store.read();
|
|
if (!current.ok || !current.value) {
|
|
throw new Error("expected active control");
|
|
}
|
|
const rotated = await store.rotateAndRevoke({
|
|
expectedRevision: current.value.revision,
|
|
previousAuthority: authority,
|
|
nextAuthority,
|
|
updatedAt: "2026-07-28T00:00:02.000Z",
|
|
});
|
|
if (!rotated.ok) throw new Error("expected rotated control");
|
|
return new Uint8Array(32).buffer;
|
|
},
|
|
});
|
|
const bytes = new TextEncoder().encode(JSON.stringify(hint()));
|
|
|
|
expect(
|
|
await adapter.handle({
|
|
data: { arrayBuffer: () => bytes.slice().buffer },
|
|
waitUntil() {},
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "ASSOCIATION_MISMATCH" },
|
|
});
|
|
expect(showNotification).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("revalidates persisted click authority and uses a same-origin handoff", async () => {
|
|
const store = await activeFence();
|
|
const messages: unknown[] = [];
|
|
const focus = vi.fn(async () => {});
|
|
const openWindow = vi.fn(async () => null);
|
|
const close = vi.fn();
|
|
let waited: Promise<void> | null = null;
|
|
const adapter = createNotificationClickAdapter({
|
|
fenceStore: store,
|
|
registry,
|
|
origin: "https://app.example.test",
|
|
now: () => now,
|
|
clients: {
|
|
async matchControlledWindowClients() {
|
|
return [
|
|
{
|
|
url: "https://app.example.test/current",
|
|
focus,
|
|
postMessage(message) {
|
|
messages.push(message);
|
|
},
|
|
},
|
|
];
|
|
},
|
|
openWindow,
|
|
},
|
|
});
|
|
const result = await adapter.handle({
|
|
notification: { data: clickData(), close },
|
|
waitUntil(task) {
|
|
waited = task;
|
|
},
|
|
});
|
|
await waited;
|
|
|
|
expect(result).toEqual({ ok: true, value: undefined });
|
|
expect(close).toHaveBeenCalledOnce();
|
|
expect(focus).toHaveBeenCalledOnce();
|
|
expect(openWindow).not.toHaveBeenCalled();
|
|
expect(messages).toEqual([
|
|
expect.objectContaining({
|
|
protocol: WEB_PUSH_PROTOCOLS.clickHandoff,
|
|
routeIntent: "OPEN_INBOX",
|
|
path: "/inbox",
|
|
}),
|
|
]);
|
|
});
|
|
|
|
it("rechecks the durable generation after client enumeration", async () => {
|
|
const store = await activeFence();
|
|
const postMessage = vi.fn();
|
|
const focus = vi.fn(async () => {});
|
|
const adapter = createNotificationClickAdapter({
|
|
fenceStore: store,
|
|
registry,
|
|
origin: "https://app.example.test",
|
|
now: () => now,
|
|
clients: {
|
|
async matchControlledWindowClients() {
|
|
const current = await store.read();
|
|
if (!current.ok || !current.value) {
|
|
throw new Error("expected active control");
|
|
}
|
|
const rotated = await store.rotateAndRevoke({
|
|
expectedRevision: current.value.revision,
|
|
previousAuthority: authority,
|
|
nextAuthority,
|
|
updatedAt: "2026-07-28T00:00:02.000Z",
|
|
});
|
|
if (!rotated.ok) throw new Error("expected rotated control");
|
|
return [
|
|
{
|
|
url: "https://app.example.test/",
|
|
focus,
|
|
postMessage,
|
|
},
|
|
];
|
|
},
|
|
openWindow: async () => null,
|
|
},
|
|
});
|
|
|
|
expect(
|
|
await adapter.handle({
|
|
notification: { data: clickData(), close() {} },
|
|
waitUntil() {},
|
|
}),
|
|
).toMatchObject({
|
|
ok: false,
|
|
error: { code: "ASSOCIATION_MISMATCH" },
|
|
});
|
|
expect(postMessage).not.toHaveBeenCalled();
|
|
expect(focus).not.toHaveBeenCalled();
|
|
});
|
|
|
|
describe("a rejected click opens the app root (Q-6.6-11, D-14)", () => {
|
|
async function rejectedClick(
|
|
options: Readonly<{ at?: number; data?: unknown }>,
|
|
) {
|
|
const store = await activeFence();
|
|
const postMessage = vi.fn();
|
|
const focus = vi.fn(async () => {});
|
|
const openWindow = vi.fn(async (url: string) => ({
|
|
url,
|
|
focus: async () => {},
|
|
postMessage() {},
|
|
}));
|
|
const observations: unknown[] = [];
|
|
const adapter = createNotificationClickAdapter({
|
|
fenceStore: store,
|
|
registry,
|
|
origin: "https://app.example.test",
|
|
now: () => options.at ?? now,
|
|
observer: {
|
|
record(observation) {
|
|
observations.push(observation);
|
|
},
|
|
},
|
|
clients: {
|
|
async matchControlledWindowClients() {
|
|
return [
|
|
{ url: "https://app.example.test/current", focus, postMessage },
|
|
];
|
|
},
|
|
openWindow,
|
|
},
|
|
});
|
|
let waited: Promise<void> | null = null;
|
|
const result = await adapter.handle({
|
|
notification: { data: options.data ?? clickData(), close() {} },
|
|
waitUntil(task) {
|
|
waited = task;
|
|
},
|
|
});
|
|
await waited;
|
|
return { result, openWindow, focus, postMessage, observations };
|
|
}
|
|
|
|
it("opens the root without handoff data for an expired click", async () => {
|
|
const click = await rejectedClick({
|
|
at: Date.parse("2026-07-28T02:00:00.000Z"),
|
|
});
|
|
|
|
expect(click.result).toMatchObject({
|
|
ok: false,
|
|
error: { code: "EXPIRED" },
|
|
});
|
|
expect(click.openWindow.mock.calls).toEqual([
|
|
["https://app.example.test/"],
|
|
]);
|
|
expect(click.postMessage).not.toHaveBeenCalled();
|
|
expect(click.focus).not.toHaveBeenCalled();
|
|
expect(click.observations).toContainEqual({
|
|
event: "web_push_click_dispatched",
|
|
outcome: "FAILED",
|
|
reason: "EXPIRED",
|
|
nativeEffect: "CONFIRMED",
|
|
});
|
|
});
|
|
|
|
it("opens the root for a click from another release", async () => {
|
|
const click = await rejectedClick({
|
|
data: { ...clickData(), releaseEpoch: "release_02" },
|
|
});
|
|
|
|
expect(click.result).toMatchObject({
|
|
ok: false,
|
|
error: { code: "RELEASE_MISMATCH" },
|
|
});
|
|
expect(click.openWindow.mock.calls).toEqual([
|
|
["https://app.example.test/"],
|
|
]);
|
|
expect(click.postMessage).not.toHaveBeenCalled();
|
|
});
|
|
|
|
// 06-09. Under a router base path the app root is the registration
|
|
// scope, not the origin root.
|
|
it("opens the registration scope under a base path", async () => {
|
|
const store = await activeFence();
|
|
const listeners = new Map<string, (event: unknown) => void>();
|
|
const openWindow = vi.fn(async () => null);
|
|
const runtime = createWebPushServiceWorkerRuntime({
|
|
fenceStore: store,
|
|
registry,
|
|
now: () => Date.parse("2026-07-28T02:00:00.000Z"),
|
|
host: {
|
|
origin: "https://app.example.test",
|
|
scope: "https://app.example.test/app/",
|
|
registration: { async showNotification() {} },
|
|
clients: { matchAll: async () => [], openWindow },
|
|
addEventListener(type, listener) {
|
|
listeners.set(type, listener);
|
|
},
|
|
removeEventListener() {},
|
|
},
|
|
});
|
|
let waited: Promise<void> | null = null;
|
|
listeners.get("notificationclick")?.({
|
|
notification: new WebIdlNotification(clickData()),
|
|
waitUntil(task: Promise<void>) {
|
|
waited = task;
|
|
},
|
|
});
|
|
await waited;
|
|
|
|
expect(openWindow.mock.calls).toEqual([
|
|
["https://app.example.test/app/"],
|
|
]);
|
|
runtime.dispose();
|
|
});
|
|
|
|
it("refuses an app root outside the origin", async () => {
|
|
expect(() =>
|
|
createNotificationClickAdapter({
|
|
fenceStore: createPushAssociationFenceStore(
|
|
createFakePushControlStoreDependencies(),
|
|
),
|
|
registry,
|
|
origin: "https://app.example.test",
|
|
appRootUrl: "https://other.example.test/app/",
|
|
clients: {
|
|
matchControlledWindowClients: async () => [],
|
|
openWindow: async () => null,
|
|
},
|
|
}),
|
|
).toThrow(TypeError);
|
|
});
|
|
|
|
it("does not retry the root after the browser refused the target window", async () => {
|
|
const store = await activeFence();
|
|
const openWindow = vi.fn(async () => null);
|
|
const adapter = createNotificationClickAdapter({
|
|
fenceStore: store,
|
|
registry,
|
|
origin: "https://app.example.test",
|
|
now: () => now,
|
|
clients: {
|
|
matchControlledWindowClients: async () => [],
|
|
openWindow,
|
|
},
|
|
});
|
|
|
|
const result = await adapter.handle({
|
|
notification: { data: clickData(), close() {} },
|
|
waitUntil() {},
|
|
});
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { code: "NATIVE_FAILURE" },
|
|
});
|
|
expect(openWindow.mock.calls).toEqual([
|
|
["https://app.example.test/inbox"],
|
|
]);
|
|
});
|
|
});
|
|
|
|
it("aborts in-flight push work when the worker runtime is disposed", async () => {
|
|
const store = await activeFence();
|
|
const listeners = new Map<string, (event: unknown) => void>();
|
|
const showNotification = vi.fn(async () => {});
|
|
let signalDigestStarted: (() => void) | undefined;
|
|
const digestStarted = new Promise<void>((resolve) => {
|
|
signalDigestStarted = resolve;
|
|
});
|
|
let finishDigest: ((value: ArrayBuffer) => void) | undefined;
|
|
const digest = new Promise<ArrayBuffer>((resolve) => {
|
|
finishDigest = resolve;
|
|
});
|
|
const runtime = createWebPushServiceWorkerRuntime({
|
|
fenceStore: store,
|
|
registry,
|
|
now: () => now,
|
|
tagDigest: async () => {
|
|
signalDigestStarted?.();
|
|
return await digest;
|
|
},
|
|
host: {
|
|
origin: "https://app.example.test",
|
|
registration: { showNotification },
|
|
clients: {
|
|
matchAll: async () => [],
|
|
openWindow: async () => null,
|
|
},
|
|
addEventListener(type, listener) {
|
|
listeners.set(type, listener);
|
|
},
|
|
removeEventListener(type, listener) {
|
|
if (listeners.get(type) === listener) listeners.delete(type);
|
|
},
|
|
},
|
|
});
|
|
let waited: Promise<void> | null = null;
|
|
const bytes = new TextEncoder().encode(JSON.stringify(hint()));
|
|
listeners.get("push")?.({
|
|
data: { arrayBuffer: () => bytes.slice().buffer },
|
|
waitUntil(task: Promise<void>) {
|
|
waited = task;
|
|
},
|
|
});
|
|
await digestStarted;
|
|
|
|
runtime.dispose();
|
|
await waited;
|
|
finishDigest?.(new Uint8Array(32).buffer);
|
|
for (let turn = 0; turn < 4; turn += 1) {
|
|
await Promise.resolve();
|
|
}
|
|
expect(showNotification).not.toHaveBeenCalled();
|
|
expect(listeners.size).toBe(0);
|
|
});
|
|
|
|
it("bounds a non-cooperative subscription-change handoff at ten seconds", async () => {
|
|
const store = await activeFence();
|
|
const listeners = new Map<string, (event: unknown) => void>();
|
|
const clock = manualScheduler();
|
|
const observations: unknown[] = [];
|
|
const runtime = createWebPushServiceWorkerRuntime({
|
|
fenceStore: store,
|
|
registry,
|
|
scheduler: clock.scheduler,
|
|
observer: {
|
|
record(observation) {
|
|
observations.push(observation);
|
|
},
|
|
},
|
|
host: {
|
|
origin: "https://app.example.test",
|
|
registration: { showNotification: async () => {} },
|
|
clients: {
|
|
matchAll: () => new Promise<readonly unknown[]>(() => {}),
|
|
openWindow: async () => null,
|
|
},
|
|
addEventListener(type, listener) {
|
|
listeners.set(type, listener);
|
|
},
|
|
removeEventListener(type, listener) {
|
|
if (listeners.get(type) === listener) listeners.delete(type);
|
|
},
|
|
},
|
|
});
|
|
let waited: Promise<void> | null = null;
|
|
listeners.get("pushsubscriptionchange")?.({
|
|
waitUntil(task: Promise<void>) {
|
|
waited = task;
|
|
},
|
|
});
|
|
await Promise.resolve();
|
|
|
|
expect(clock.delays).toContain(10_000);
|
|
clock.expireAll();
|
|
await waited;
|
|
expect(observations).toContainEqual({
|
|
event: "web_push_subscription_rotated",
|
|
outcome: "DEGRADED",
|
|
reason: "DEADLINE_EXCEEDED",
|
|
countBucket: expect.any(String),
|
|
truncated: expect.any(Boolean),
|
|
});
|
|
runtime.dispose();
|
|
});
|
|
|
|
it("aborts subscription-change handoff on dispose and contains waitUntil throws", async () => {
|
|
const store = await activeFence();
|
|
const listeners = new Map<string, (event: unknown) => void>();
|
|
const observations: unknown[] = [];
|
|
const runtime = createWebPushServiceWorkerRuntime({
|
|
fenceStore: store,
|
|
registry,
|
|
observer: {
|
|
record(observation) {
|
|
observations.push(observation);
|
|
},
|
|
},
|
|
host: {
|
|
origin: "https://app.example.test",
|
|
registration: { showNotification: async () => {} },
|
|
clients: {
|
|
matchAll: () => new Promise<readonly unknown[]>(() => {}),
|
|
openWindow: async () => null,
|
|
},
|
|
addEventListener(type, listener) {
|
|
listeners.set(type, listener);
|
|
},
|
|
removeEventListener(type, listener) {
|
|
if (listeners.get(type) === listener) listeners.delete(type);
|
|
},
|
|
},
|
|
});
|
|
let waited: Promise<void> | null = null;
|
|
listeners.get("pushsubscriptionchange")?.({
|
|
waitUntil(task: Promise<void>) {
|
|
waited = task;
|
|
},
|
|
});
|
|
await Promise.resolve();
|
|
runtime.dispose();
|
|
await waited;
|
|
expect(observations).toContainEqual({
|
|
event: "web_push_subscription_rotated",
|
|
outcome: "DEGRADED",
|
|
reason: "ABORTED",
|
|
countBucket: expect.any(String),
|
|
truncated: expect.any(Boolean),
|
|
});
|
|
|
|
const throwingStore = await activeFence();
|
|
const throwingListeners = new Map<
|
|
string,
|
|
(event: unknown) => void
|
|
>();
|
|
const throwingObservations: unknown[] = [];
|
|
let signalThrowingObservation: (() => void) | undefined;
|
|
const throwingObservation = new Promise<void>((resolve) => {
|
|
signalThrowingObservation = resolve;
|
|
});
|
|
const throwingRuntime = createWebPushServiceWorkerRuntime({
|
|
fenceStore: throwingStore,
|
|
registry,
|
|
observer: {
|
|
record(observation) {
|
|
throwingObservations.push(observation);
|
|
signalThrowingObservation?.();
|
|
},
|
|
},
|
|
host: {
|
|
origin: "https://app.example.test",
|
|
registration: { showNotification: async () => {} },
|
|
clients: {
|
|
matchAll: async () => [],
|
|
openWindow: async () => null,
|
|
},
|
|
addEventListener(type, listener) {
|
|
throwingListeners.set(type, listener);
|
|
},
|
|
removeEventListener(type, listener) {
|
|
if (throwingListeners.get(type) === listener) {
|
|
throwingListeners.delete(type);
|
|
}
|
|
},
|
|
},
|
|
});
|
|
|
|
expect(() =>
|
|
throwingListeners.get("pushsubscriptionchange")?.({
|
|
waitUntil() {
|
|
throw new Error("waitUntil unavailable");
|
|
},
|
|
}),
|
|
).not.toThrow();
|
|
await throwingObservation;
|
|
expect(throwingObservations).toContainEqual({
|
|
event: "web_push_subscription_rotated",
|
|
outcome: "DEGRADED",
|
|
reason: "ABORTED",
|
|
countBucket: expect.any(String),
|
|
truncated: expect.any(Boolean),
|
|
});
|
|
throwingRuntime.dispose();
|
|
});
|
|
|
|
it("installs no handlers until the uncomposed factory is called and removes all on dispose", async () => {
|
|
const store = await activeFence();
|
|
const listeners = new Map<string, (event: unknown) => void>();
|
|
const messages: unknown[] = [];
|
|
const matchPolicies: boolean[] = [];
|
|
const client = {
|
|
url: "https://app.example.test/",
|
|
focus: async () => {},
|
|
postMessage(message: unknown) {
|
|
messages.push(message);
|
|
},
|
|
};
|
|
expect(listeners.size).toBe(0);
|
|
const runtime = createWebPushServiceWorkerRuntime({
|
|
fenceStore: store,
|
|
registry,
|
|
now: () => now,
|
|
host: {
|
|
origin: "https://app.example.test",
|
|
registration: {
|
|
async showNotification() {},
|
|
},
|
|
clients: {
|
|
async matchAll(input) {
|
|
matchPolicies.push(input.includeUncontrolled);
|
|
return [client];
|
|
},
|
|
async openWindow() {
|
|
return client;
|
|
},
|
|
},
|
|
addEventListener(type, listener) {
|
|
listeners.set(type, listener);
|
|
},
|
|
removeEventListener(type, listener) {
|
|
if (listeners.get(type) === listener) listeners.delete(type);
|
|
},
|
|
},
|
|
});
|
|
expect([...listeners.keys()].sort()).toEqual([
|
|
"notificationclick",
|
|
"push",
|
|
"pushsubscriptionchange",
|
|
]);
|
|
let clickWait: Promise<void> | null = null;
|
|
const notification = new WebIdlNotification(clickData());
|
|
expect(Object.keys(notification)).toEqual(["closed"]);
|
|
expect(Object.hasOwn(notification, "data")).toBe(false);
|
|
listeners.get("notificationclick")?.({
|
|
notification,
|
|
waitUntil(task: Promise<void>) {
|
|
clickWait = task;
|
|
},
|
|
});
|
|
expect(clickWait).not.toBeNull();
|
|
await clickWait;
|
|
expect(notification.closed).toBe(1);
|
|
let subscriptionWait: Promise<void> | null = null;
|
|
listeners.get("pushsubscriptionchange")?.({
|
|
waitUntil(task: Promise<void>) {
|
|
subscriptionWait = task;
|
|
},
|
|
});
|
|
await subscriptionWait;
|
|
expect(matchPolicies).toEqual([false, true]);
|
|
expect(messages).toEqual([
|
|
expect.objectContaining({
|
|
protocol: WEB_PUSH_PROTOCOLS.clickHandoff,
|
|
}),
|
|
{ protocol: WEB_PUSH_PROTOCOLS.reconcileRequired },
|
|
]);
|
|
|
|
runtime.dispose();
|
|
expect(listeners.size).toBe(0);
|
|
});
|
|
});
|
|
|
|
/**
|
|
* WP-01. One click is one terminal record. The adapter emitted the terminal
|
|
* event from inside `process` *and* again from the `waitUntil` wrapper, so an
|
|
* ordinary click was counted twice. A late rejection also downgraded the
|
|
* certainty from `MAYBE_APPLIED` to `NOT_APPLIED`, telling operators the click
|
|
* had definitely not been applied when nobody knew that, and the late
|
|
* observation ran outside `waitUntil`, so a worker shutdown lost the evidence.
|
|
*/
|
|
describe("WP-01 the click handler has one observation authority", () => {
|
|
type Observation = Readonly<{
|
|
event: string;
|
|
outcome: string;
|
|
reason?: string;
|
|
nativeEffect?: string;
|
|
}>;
|
|
|
|
async function clickAdapterWith(
|
|
clients: Readonly<{
|
|
matchControlledWindowClients(): Promise<readonly unknown[]>;
|
|
openWindow(target: string): Promise<unknown>;
|
|
}>,
|
|
scheduler?: TimeoutScheduler,
|
|
) {
|
|
const store = await activeFence();
|
|
const observations: Observation[] = [];
|
|
const adapter = createNotificationClickAdapter({
|
|
fenceStore: store,
|
|
registry,
|
|
origin: "https://app.example.test",
|
|
now: () => now,
|
|
clients: clients as never,
|
|
observer: {
|
|
record(observation) {
|
|
observations.push(observation as Observation);
|
|
},
|
|
},
|
|
...(scheduler ? { scheduler } : {}),
|
|
});
|
|
return { adapter, observations };
|
|
}
|
|
|
|
const dispatched = (observations: readonly Observation[]) =>
|
|
observations.filter(
|
|
(observation) => observation.event === "web_push_click_dispatched",
|
|
);
|
|
|
|
it("records exactly one terminal event for an ordinary focus", async () => {
|
|
const focus = vi.fn(async () => {});
|
|
const { adapter, observations } = await clickAdapterWith({
|
|
async matchControlledWindowClients() {
|
|
return [
|
|
{
|
|
url: "https://app.example.test/current",
|
|
focus,
|
|
postMessage() {},
|
|
},
|
|
];
|
|
},
|
|
openWindow: vi.fn(async () => null),
|
|
});
|
|
let waited: Promise<void> | null = null;
|
|
const result = await adapter.handle({
|
|
notification: { data: clickData(), close() {} },
|
|
waitUntil(task) {
|
|
waited = task;
|
|
},
|
|
});
|
|
await waited;
|
|
|
|
expect(result).toEqual({ ok: true, value: undefined });
|
|
expect(dispatched(observations)).toEqual([
|
|
{
|
|
event: "web_push_click_dispatched",
|
|
outcome: "SUCCEEDED",
|
|
nativeEffect: "CONFIRMED",
|
|
},
|
|
]);
|
|
});
|
|
|
|
it("confirms NOT_APPLIED only for an explicit null window", async () => {
|
|
const { adapter, observations } = await clickAdapterWith({
|
|
async matchControlledWindowClients() {
|
|
return [];
|
|
},
|
|
openWindow: vi.fn(async () => null),
|
|
});
|
|
let waited: Promise<void> | null = null;
|
|
const result = await adapter.handle({
|
|
notification: { data: clickData(), close() {} },
|
|
waitUntil(task) {
|
|
waited = task;
|
|
},
|
|
});
|
|
await waited;
|
|
|
|
expect(result.ok).toBe(false);
|
|
expect(dispatched(observations)).toEqual([
|
|
expect.objectContaining({
|
|
outcome: "FAILED",
|
|
nativeEffect: "NOT_APPLIED",
|
|
}),
|
|
]);
|
|
});
|
|
|
|
it("keeps MAYBE_APPLIED when the native effect rejects after the deadline", async () => {
|
|
const clock = manualScheduler();
|
|
let rejectFocus: ((reason: unknown) => void) | undefined;
|
|
const { adapter, observations } = await clickAdapterWith(
|
|
{
|
|
async matchControlledWindowClients() {
|
|
return [
|
|
{
|
|
url: "https://app.example.test/current",
|
|
focus: () =>
|
|
new Promise<void>((_resolve, reject) => {
|
|
rejectFocus = reject;
|
|
}),
|
|
postMessage() {},
|
|
},
|
|
];
|
|
},
|
|
openWindow: vi.fn(async () => null),
|
|
},
|
|
clock.scheduler,
|
|
);
|
|
let waited: Promise<void> | null = null;
|
|
const handling = adapter.handle({
|
|
notification: { data: clickData(), close() {} },
|
|
waitUntil(task) {
|
|
waited = task;
|
|
},
|
|
});
|
|
await vi.waitFor(() => expect(rejectFocus).toBeDefined());
|
|
clock.expireAll();
|
|
const result = await handling;
|
|
expect(result.ok).toBe(false);
|
|
|
|
// The effect lands only now, after the terminal result.
|
|
rejectFocus?.(new Error("focus failed late"));
|
|
await waited;
|
|
|
|
const records = dispatched(observations);
|
|
expect(records).toHaveLength(2);
|
|
// The evidence record never claims the click was definitely not applied.
|
|
expect(records.at(-1)).toEqual({
|
|
event: "web_push_click_dispatched",
|
|
outcome: "DEGRADED",
|
|
reason: "ABORTED",
|
|
nativeEffect: "MAYBE_APPLIED",
|
|
});
|
|
});
|
|
|
|
it("waits for the late effect evidence inside waitUntil", async () => {
|
|
const clock = manualScheduler();
|
|
let resolveFocus: (() => void) | undefined;
|
|
const { adapter, observations } = await clickAdapterWith(
|
|
{
|
|
async matchControlledWindowClients() {
|
|
return [
|
|
{
|
|
url: "https://app.example.test/current",
|
|
focus: () =>
|
|
new Promise<void>((resolve) => {
|
|
resolveFocus = resolve;
|
|
}),
|
|
postMessage() {},
|
|
},
|
|
];
|
|
},
|
|
openWindow: vi.fn(async () => null),
|
|
},
|
|
clock.scheduler,
|
|
);
|
|
let waited: Promise<void> | null = null;
|
|
const handling = adapter.handle({
|
|
notification: { data: clickData(), close() {} },
|
|
waitUntil(task) {
|
|
waited = task;
|
|
},
|
|
});
|
|
await vi.waitFor(() => expect(resolveFocus).toBeDefined());
|
|
clock.expireAll();
|
|
await handling;
|
|
|
|
let waitUntilSettled = false;
|
|
const pendingWait = waited as Promise<void> | null;
|
|
void pendingWait?.then(() => {
|
|
waitUntilSettled = true;
|
|
});
|
|
await Promise.resolve();
|
|
await Promise.resolve();
|
|
// The handler's lifetime is still open because the effect has not landed.
|
|
expect(waitUntilSettled).toBe(false);
|
|
|
|
resolveFocus?.();
|
|
await waited;
|
|
expect(
|
|
dispatched(observations).at(-1),
|
|
).toEqual({
|
|
event: "web_push_click_dispatched",
|
|
outcome: "DEGRADED",
|
|
reason: "ABORTED",
|
|
nativeEffect: "CONFIRMED",
|
|
});
|
|
});
|
|
});
|