Files
clean-architecture-frontend…/tests/e2e/old-tab-chunk-recovery.spec.ts
DongHyeonka 2f0730e730
frontend-quality-gates / merge / tests (pull_request) Canceled after 0s
frontend-quality-gates / merge / browser tests (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Canceled after 0s
frontend-quality-gates / external-vulnerability-provider (pull_request) Canceled after 0s
frontend-quality-gates / external-provenance-provider (pull_request) Canceled after 0s
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Canceled after 0s
frontend-quality-gates / deploy-promoted-release (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Canceled after 0s
frontend-quality-gates / merge / static checks (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Canceled after 0s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Canceled after 0s
frontend-quality-gates / main / self-tests and removal drills (pull_request) Canceled after 0s
Merge remote-tracking branch 'origin/main' into fix/r9-browser-test-fidelity
2026-11-13 04:29:26 +09:00

263 lines
9.9 KiB
TypeScript

import { appendFile, readFile } from "node:fs/promises";
import path from "node:path";
import type { RouteDefinition } from "../../src/contracts/routes.ts";
import {
ROUTE_REGISTRY,
ROUTE_RUNTIME_CONTRACT,
} from "../../src/features/installed-feature-contracts.ts";
import { expect, test } from "../support/browser/strict-browser-test.ts";
import {
prepareFixtureBuilds,
removeFixtureBuilds,
type FixtureBuilds,
} from "./support/fixture-builds.ts";
import {
addGeneratedFeature,
generatedFeature,
} from "../../scripts/lib/generated-feature.ts";
import { startBuildServer } from "./support/service-worker-builds.ts";
/**
* 11-05. A tab opened on build A, in the default configuration (no Service
* Worker), after build B is deployed. B changes two lazy route pages, so their
* A chunks no longer exist on the server. The first missing chunk reloads the
* tab once, into B. A second missing chunk (the server alternates back to A,
* as mismatched replicas do) must not reload again: the tab shows the
* recovery failure instead.
*/
// 1103/09-04. The platform overview is a platform route; a feature route is
// reached through its context gateway. The template has no feature, so both
// builds carry the one `create:feature` writes (scripts/lib/generated-feature.ts)
// and the second page is its list. The page sources are read from build A's
// Vite manifest, so this spec names no feature folder.
const installedRoutes: Readonly<Record<string, RouteDefinition>> = ROUTE_REGISTRY;
const runtimeContracts: Readonly<Record<string, { moduleId: string }>> =
ROUTE_RUNTIME_CONTRACT;
function installedRoute(routeId: string): RouteDefinition {
const definition = installedRoutes[routeId];
if (!definition) throw new Error(`${routeId} is not installed.`);
return definition;
}
type ChunkRoute = Readonly<{
path: string;
chunkId: string;
moduleId: string;
navigationLabel: string;
title: string;
}>;
const platformRoute = installedRoute("EXAMPLES_PLATFORM");
const PLATFORM: ChunkRoute = Object.freeze({
path: platformRoute.path,
chunkId: platformRoute.chunkId,
moduleId: runtimeContracts[platformRoute.routeId]!.moduleId,
navigationLabel: platformRoute.navigationLabel!,
title: platformRoute.title,
});
/** The generated feature's list, read from build A's copy. */
let featureList: ChunkRoute | undefined;
function readFeatureList(root: string): ChunkRoute {
const { list, messages } = generatedFeature(root);
return Object.freeze({
...list,
navigationLabel: messages["ko-KR"][`route.${list.routeId}.navigation`]!,
title: messages["ko-KR"][`route.${list.routeId}.title`]!,
});
}
function FEATURE(): ChunkRoute {
if (!featureList) throw new Error("Fixture builds were not prepared.");
return featureList;
}
type ViteManifest = Record<
string,
{
file: string;
name?: string;
isDynamicEntry?: boolean;
imports?: string[];
dynamicImports?: string[];
}
>;
async function viteManifest(dist: string): Promise<ViteManifest> {
return JSON.parse(
await readFile(path.join(dist, ".vite/manifest.json"), "utf8"),
) as ViteManifest;
}
/** The source of a route's page: the dynamic entry named by its module id. */
function pageSource(manifest: ViteManifest, route: ChunkRoute): string {
const sources = Object.entries(manifest)
.filter(([, entry]) => entry.isDynamicEntry && entry.name === route.moduleId)
.map(([source]) => source);
if (sources.length !== 1) {
throw new Error(`Expected one page chunk for ${route.moduleId}: ${sources.join(", ")}`);
}
return sources[0]!;
}
/** The context routes module that lazy-loads `page`. */
function routesSource(manifest: ViteManifest, page: string): string {
const sources = Object.entries(manifest)
.filter(([, entry]) => entry.isDynamicEntry && entry.dynamicImports?.includes(page))
.map(([source]) => source);
if (sources.length !== 1) {
throw new Error(`Expected one routes module for ${page}: ${sources.join(", ")}`);
}
return sources[0]!;
}
let builds: FixtureBuilds<"a" | "b"> | undefined;
test.beforeAll(async () => {
test.setTimeout(300_000);
builds = await prepareFixtureBuilds("chunk-recovery", [
{
name: "a",
edit: async (root) => {
await addGeneratedFeature(root);
featureList = readFeatureList(root);
},
},
{
name: "b",
edit: async (root) => {
const manifest = await viteManifest(path.join(root, "dist-a"));
for (const route of [PLATFORM, FEATURE()]) {
await appendFile(
path.join(root, pageSource(manifest, route)),
'\n(globalThis as Record<string, unknown>).__caFixtureBuild = "b";\n',
);
}
},
},
]);
// A worker that reused another browser project's builds ran no edit.
featureList ??= readFeatureList(builds.root);
});
test.afterAll(async () => {
await removeFixtureBuilds(builds);
});
async function routeChunk(dist: string, chunkId: string): Promise<string> {
const manifest = JSON.parse(
await readFile(path.join(dist, "release-manifest.json"), "utf8"),
) as { routeChunks: Record<string, string> };
return `/${manifest.routeChunks[chunkId]}`;
}
// Each missing chunk fails its request and the dynamic import. Chromium may
// also log the 404 itself (without its URL), Firefox logs the error object
// React caught, and WebKit logs its own import error without the URL. Nothing
// else is allowed, but for the WebKit warning below. 1103/09-04: the B tab
// misses the feature's context routes module before its page: that module
// names B's new page chunk, so its hash changed too.
function missingPageFailures(): string[] {
const missingPage = String.raw`/assets/(?:${PLATFORM.moduleId}|${FEATURE().moduleId}|context-routes)-[\w-]+\.js`;
return [
String.raw`^requestfailed:GET:${missingPage}:`,
String.raw`^console:error:TypeError: Failed to fetch dynamically imported module: http://127\.0\.0\.1:\d+${missingPage}$`,
String.raw`^console:error:\[JavaScript Error: "Loading module from “http://127\.0\.0\.1:\d+${missingPage}” was blocked`,
String.raw`^console:error:Failed to load resource: the server responded with a status of 404 \(Not Found\)$`,
String.raw`^console:error:JSHandle@object$`,
String.raw`^console:error:TypeError: Importing a module script failed\.$`,
String.raw`^preloadunused:${missingPage}$`,
];
}
/** The chunks Vite preloads with `page`: its static imports in `dist`. */
async function preloadedWith(dist: string, page: string): Promise<string[]> {
const manifest = await viteManifest(dist);
if (!manifest[page]) throw new Error(`${page} is not in ${dist}'s manifest.`);
const files = new Set<string>();
const pending = [...(manifest[page].imports ?? [])];
for (let key = pending.pop(); key !== undefined; key = pending.pop()) {
const entry = manifest[key];
if (!entry || files.has(entry.file)) continue;
files.add(entry.file);
pending.push(...(entry.imports ?? []));
}
return [...files];
}
// 1103/11-09. Vite preloads a chunk together with the chunks it imports, so a
// missing chunk leaves itself and the chunks preloaded with it unused. The
// fixture's preload check reads only the documents open at the end
// (tests/support/browser/preload-use.ts), and the A tab has become a B
// document by then, so only B's: those of B's context routes module for the
// feature's list page. The check reports them in every engine (WebKit's own
// three-second warning only did when its timer ran before the test ended).
// They are the provoked failure's own effect; only those chunks are allowed
// (1112/03-06: the A list here covered nothing but a B chunk of the same name).
test.use({
allowedBrowserFailure: async ({ browserName: _engine }, provide) => {
if (!builds) throw new Error("Fixture builds were not prepared.");
const bManifest = await viteManifest(builds.dist.b);
const files = (
await preloadedWith(builds.dist.b, routesSource(bManifest, pageSource(bManifest, FEATURE())))
).map((file) => file.replaceAll(".", String.raw`\.`));
await provide(
new RegExp(
[
...missingPageFailures(),
String.raw`^preloadunused:/(?:${files.join("|")})$`,
].join("|"),
"u",
),
);
},
});
test("an old tab reloads once into the new build, then stops reloading", async ({
page,
}) => {
if (!builds) throw new Error("Fixture builds were not prepared.");
const aPlatform = await routeChunk(builds.dist.a, PLATFORM.chunkId);
const bPlatform = await routeChunk(builds.dist.b, PLATFORM.chunkId);
const bFeature = await routeChunk(builds.dist.b, FEATURE().chunkId);
expect(bPlatform).not.toBe(aPlatform);
expect(bFeature).not.toBe(await routeChunk(builds.dist.a, FEATURE().chunkId));
const server = await startBuildServer(builds.dist);
try {
await page.goto(`${server.origin}/`);
await expect(
page.getByRole("link", { name: PLATFORM.navigationLabel, exact: true }),
).toBeVisible();
let loads = 0;
page.on("load", () => {
loads += 1;
});
// Build B is deployed while the A tab stays open.
server.serve("b");
await page
.getByRole("link", { name: PLATFORM.navigationLabel, exact: true })
.click();
await expect(page.getByRole("heading", { name: PLATFORM.title })).toBeVisible();
expect(loads).toBe(1);
const served = server.served.map((entry) => entry.path);
expect(served).not.toContain(aPlatform);
expect(served).toContain(bPlatform);
await expect
.poll(() => page.evaluate(() => (globalThis as Record<string, unknown>).__caFixtureBuild))
.toBe("b");
// The replicas alternate: the B tab now meets A, which lacks B's chunk.
server.serve("a");
await page.getByRole("link", { name: FEATURE().navigationLabel, exact: true }).click();
await expect(page.getByRole("alert")).toContainText(
"화면 자산을 복구하지 못했습니다.",
);
expect(loads).toBe(1);
expect(page.url()).toBe(`${server.origin}${FEATURE().path}`);
} finally {
await server.close();
}
});