From 85d55e0cd30de05ba7523bd6f6185ae9af371f02 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sun, 1 Nov 2026 22:37:19 +0900 Subject: [PATCH] =?UTF-8?q?fix(service-worker):=20=EC=82=AC=EC=A0=84=20?= =?UTF-8?q?=EC=BA=90=EC=8B=9C=EC=99=80=20=EC=84=A4=EC=A0=95=20URL=EC=9D=B4?= =?UTF-8?q?=20router=20base=20path=EB=A5=BC=20=EB=94=B0=EB=A5=B8=EB=8B=A4?= =?UTF-8?q?=20(0929/06-02)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: SW 자산 생성기(scripts/generate-service-worker-assets.ts)가 사전 캐시 URL을 `/${relative}`로 만들어 VITE_ROUTER_BASE_PATH를 무시했다. 워커는 root-relative URL을 scope 기준으로 풀지만 base가 사라지므로 /app/ 배포에서 install이 /assets/...를 요청해 404를 받고, 워커가 설치되지 않았다. 같은 빌드의 SW 설정도 runtime config URL 기본값을 "/config.json"으로 고정해, 페이지가 쓰는 /app/config.json을 워커가 network-only로 알아보지 못했다. 앱 빌드·runtime config·06-08 fallback은 이미 base를 따르는데 이 두 곳만 빠져 있었다. 고른 방법: 리뷰가 적은 최소 방향. collectStaticAssets에 basePath 인자(기본 "/")를 더하고, 생성기 main과 SW Vite 설정이 페이지와 같은 getBuildConfig(src/contracts/env.ts)로 base와 runtime config URL을 계산한다. 결과 URL은 그대로 root-relative라 isCanonicalStaticAssetUrl 검사를 통과한다. base가 "/"이면 manifest와 digest가 전과 같다. 버린 대안: 워커가 manifest URL을 scope 상대로 풀게 바꾸기. 계약 차이는 없지만 워커 코드와 manifest 계약(root-relative)을 함께 바꿔야 해서 생성기 수정보다 크다. 위험·한계: - base마다 manifest digest가 달라진다(의도된 결과). - VITE_RUNTIME_CONFIG_URL이 빈 문자열이면 이제 base 기본값을 쓴다. 페이지(getBuildConfig)와 같은 규칙이다. - 리뷰 완료 기준의 "e2e 도우미를 base 옵션으로 돌린 첫 설치가 RELOAD_TO_ENABLE"은 하지 않았다. e2e 도우미에 base 옵션과 /app/ 서빙이 필요하고, 실제 브라우저 install은 이번에 확인하지 않았다. 검증: - RED: collectStaticAssets 단위 테스트(basePath "/app/")가 수정 전 `/assets/index-abcdefgh.js`를 받아 실패(1 failed | 9 passed). service-worker-build-output.test.ts의 새 테스트(SW ACTIVE· production·/app/ 실제 빌드)가 생성기만 되돌리면 URL 목록에서, SW 설정만 되돌리면 `Received: "/config.json"`으로 각각 실패. - GREEN: 두 테스트 통과. `node scripts/run-vitest.ts run tests/unit/service-worker tests/unit/sub-path-deployment.test.ts tests/unit/hosting-probe.test.ts tests/unit/web-push` -> 12파일 171건 통과(빌드 테스트는 flock 안에서). - `npx tsc` node·test·app·service-worker -> 오류 0. - `npx eslint <바꾼 파일 4개> --max-warnings=0` -> 통과. - `node scripts/check-adapter-inventory.ts` -> PASS. - 미실행: SW e2e(Playwright). Refs: docs/reviews/2026-09-29-maturity-review/06-adapters-service-worker-push.md 06-02, docs/reviews/2026-11-01-maturity-review/06-adapters-service-worker-push.md 2.1절 --- scripts/generate-service-worker-assets.ts | 15 ++++- .../unit/service-worker-build-output.test.ts | 58 ++++++++++++++----- ...ervice-worker-web-push-remediation.test.ts | 25 ++++++++ vite.service-worker.config.ts | 4 +- 4 files changed, 83 insertions(+), 19 deletions(-) diff --git a/scripts/generate-service-worker-assets.ts b/scripts/generate-service-worker-assets.ts index ee1a1991..5bccadec 100644 --- a/scripts/generate-service-worker-assets.ts +++ b/scripts/generate-service-worker-assets.ts @@ -9,6 +9,7 @@ import { import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises"; import path from "node:path"; +import { getBuildConfig } from "../src/contracts/env.ts"; import { HASHED_STATIC_ASSET_NAME, SERVICE_WORKER_BOUNDS, @@ -41,10 +42,15 @@ const EXCLUDED_FILES: ReadonlySet = new Set([ /** Vite emits content-hashed names; only those may be treated as immutable. */ const HASHED_NAME = HASHED_STATIC_ASSET_NAME; +/** + * `basePath` is the router base path (`VITE_ROUTER_BASE_PATH`): dist, and so + * every asset, is served under it (0929/06-02). + */ export async function collectStaticAssets( distDirectory: string, buildId: string, releaseId: string, + basePath = "/", ): Promise { const files = await walk(distDirectory, distDirectory); const assets: StaticAssetManifestV1["assets"][number][] = []; @@ -63,7 +69,7 @@ export async function collectStaticAssets( // SW-02. The URL is checked against the same predicate the runtime decoder // applies. Emitting a path the decoder will refuse turned a correct build // into a runtime contract failure discovered only at install time. - const url = `/${relative.split(path.sep).join("/")}`; + const url = `${basePath}${relative.split(path.sep).join("/")}`; if (!isCanonicalStaticAssetUrl(url)) { throw new Error( `Static asset path is not canonical for the service worker manifest: ${relative}`, @@ -129,7 +135,12 @@ async function main(): Promise { const distDirectory = process.argv[2] ?? "dist"; const buildId = process.env.VITE_BUILD_ID ?? "local-build"; const releaseId = process.env.RELEASE_ID ?? "local-release"; - const manifest = await collectStaticAssets(distDirectory, buildId, releaseId); + const manifest = await collectStaticAssets( + distDirectory, + buildId, + releaseId, + getBuildConfig(process.env).routerBasePath, + ); const source = [ "// Generated by scripts/generate-service-worker-assets.ts. Do not edit.", "", diff --git a/tests/unit/service-worker-build-output.test.ts b/tests/unit/service-worker-build-output.test.ts index b82a33fe..ae24bfa0 100644 --- a/tests/unit/service-worker-build-output.test.ts +++ b/tests/unit/service-worker-build-output.test.ts @@ -1,7 +1,7 @@ import { access, readFile } from "node:fs/promises"; import path from "node:path"; -import { afterAll, describe, expect, it } from "vitest"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { generateRuntimeConfig } from "../../scripts/generate-runtime-config.ts"; import { @@ -34,25 +34,28 @@ const BUILD_ID = "sw-profile-active"; let builds: FixtureBuilds<"active"> | undefined; +beforeAll(async () => { + builds = await prepareFixtureBuilds("sw-profile", [ + { + name: "active", + env: PROFILE, + edit: (root) => + editOnce( + path.join(root, "src/features/installed-runtime-capabilities.ts"), + "const SERVICE_WORKER: InstalledServiceWorkerSelection | null = null;", + ACTIVE_SELECTION, + ), + }, + ]); +}, 180_000); + afterAll(async () => { await removeFixtureBuilds(builds); }); -describe("Service Worker build output (0929/06-01)", () => { +describe("Service Worker build output (0929/06-01, 0929/06-02)", () => { it("keeps the profile runtime config step 4 wrote", async () => { - builds = await prepareFixtureBuilds("sw-profile", [ - { - name: "active", - env: PROFILE, - edit: (root) => - editOnce( - path.join(root, "src/features/installed-runtime-capabilities.ts"), - "const SERVICE_WORKER: InstalledServiceWorkerSelection | null = null;", - ACTIVE_SELECTION, - ), - }, - ]); - const dist = builds.dist.active; + const dist = builds!.dist.active; // The worker build really ran; otherwise nothing below tests step 6. await access(path.join(dist, "service-worker.js")); @@ -67,5 +70,28 @@ describe("Service Worker build output (0929/06-01)", () => { RELEASE_ID: BUILD_ID, }), ); - }, 180_000); + }); + + // 0929/06-02. Under /app/ the worker must precache /app/assets/... and know + // /app/config.json; root URLs 404 at install and the worker never installs. + it("gives the worker URLs under the router base path", async () => { + const generated = (await import( + path.join( + builds!.root, + ".generated/frontend-runtime/service-worker-assets.ts", + ) + )) as { SERVICE_WORKER_ASSETS: { assets: readonly { url: string }[] } }; + const urls = generated.SERVICE_WORKER_ASSETS.assets.map((asset) => asset.url); + expect(urls.length).toBeGreaterThan(0); + expect(urls.filter((url) => !url.startsWith("/app/assets/"))).toEqual([]); + + const worker = await readFile( + path.join(builds!.dist.active, "service-worker.js"), + "utf8", + ); + // Property names survive minification; the quote style does not. + expect( + /runtimeConfigUrl:\s*["'`]([^"'`]*)["'`]/u.exec(worker)?.[1], + ).toBe("/app/config.json"); + }); }); diff --git a/tests/unit/service-worker-web-push-remediation.test.ts b/tests/unit/service-worker-web-push-remediation.test.ts index 9a163265..dfb9efc9 100644 --- a/tests/unit/service-worker-web-push-remediation.test.ts +++ b/tests/unit/service-worker-web-push-remediation.test.ts @@ -125,6 +125,31 @@ describe("SW-02 the generator and the decoder share one path grammar", () => { } }); + // 0929/06-02. dist is served under the router base path; a root URL made + // the worker's install request /assets/... and fail under /app/. + it("puts every asset URL under the router base path", async () => { + const { collectStaticAssets } = await import( + "../../scripts/generate-service-worker-assets.ts" + ); + const root = await distWith({ + "assets/index-abcdefgh.js": "entry", + "assets/nested/chunk-abcdefgz.css": "style", + }); + + const manifest = await collectStaticAssets( + root, + "build-1", + "release-1", + "/app/", + ); + + expect(manifest.assets.map((asset) => asset.url)).toEqual([ + "/app/assets/index-abcdefgh.js", + "/app/assets/nested/chunk-abcdefgz.css", + ]); + expect(decodeStaticAssetManifest(manifest)).toMatchObject({ ok: true }); + }); + it.each([ { label: "an at sign", name: "bad@name-abcdefgh.js" }, { label: "a space", name: "bad name-abcdefgh.js" }, diff --git a/vite.service-worker.config.ts b/vite.service-worker.config.ts index 2477b752..aee34b9e 100644 --- a/vite.service-worker.config.ts +++ b/vite.service-worker.config.ts @@ -1,6 +1,7 @@ import { readFile } from "node:fs/promises"; import { defineConfig } from "vite"; +import { getBuildConfig } from "./src/contracts/env.ts"; import { SERVICE_WORKER_CACHE_SCHEMA_VERSION, SERVICE_WORKER_PROTOCOL_VERSION, @@ -95,8 +96,9 @@ export default defineConfig({ }), __CA_SERVICE_WORKER_ASSETS__: JSON.stringify(buildInput.assets), __CA_SERVICE_WORKER_HANDLERS__: JSON.stringify(buildInput.handlers), + // 0929/06-02. The page's own default, which follows the router base path. __CA_RUNTIME_CONFIG_URL__: JSON.stringify( - process.env.VITE_RUNTIME_CONFIG_URL ?? "/config.json", + getBuildConfig(process.env).runtimeConfigUrl, ), __CA_RELEASE_MANIFEST_URL__: JSON.stringify( buildInput.releaseManifestUrl,