// @vitest-environment jsdom import { render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { http, HttpResponse } from "msw"; import { afterAll, afterEach, beforeAll, describe, expect, it, vi, } from "vitest"; import { createRuntimeComposition } from "../../../src/bootstrap/create-runtime-composition.ts"; import { RuntimeApplication } from "../../../src/bootstrap/runtime-application.tsx"; import { createBootstrapHandlers } from "../../mocks/handlers/bootstrap.ts"; import { createReferenceScenarioHandlers } from "../../mocks/handlers/reference-resources.ts"; import { createStrictMockServer } from "../../mocks/server.ts"; const runtimeConfig = { APP_ENV: "local", API_BASE_URL: "https://api.test", REQUEST_TIMEOUT_MS: 10_000, MAX_RETRY_ATTEMPTS: 0, TELEMETRY_ENABLED: false, AUTH_MODE: "demo", CONFIG_SCHEMA_VERSION: "1", API_CONTRACT_VERSION: "1", RELEASE_MANIFEST_URL: "/release-manifest.json", BUILD_ID: "local-build", RELEASE_ID: "local-release", }; const releaseManifest = { schemaVersion: 1, appVersion: "0.2.0", buildId: "local-build", commitSha: "local", configSchemaVersion: "1", apiContractVersion: "1", assetManifestHash: "test-hash", releaseId: "local-release", builtAt: "2026-07-26T00:00:00.000Z", routeChunks: { "route-home": "assets/home.js", "route-examples-ui": "assets/ui.js", "route-examples-states": "assets/states.js", "route-examples-auth": "assets/auth.js", "route-reference-resources": "assets/reference.js", "route-reference-resource-detail": "assets/reference-detail.js", "route-reference-resource-form": "assets/reference-form.js", "route-reference-resource-status": "assets/reference-status.js", "route-not-found": "assets/not-found.js", }, }; const listRequests = vi.fn(); const createRequests = vi.fn(); const resources = [{ id: "reference-1", name: "Existing" }]; const mockApi = createStrictMockServer( ...createBootstrapHandlers(runtimeConfig, releaseManifest), ...createReferenceScenarioHandlers({ resources, onList: listRequests, onCreate: createRequests, }), ); beforeAll(mockApi.listen); afterEach(() => { mockApi.reset(); listRequests.mockClear(); createRequests.mockClear(); resources.splice(1); }); afterAll(mockApi.close); const absoluteFetch: typeof fetch = (input, init) => { if (input instanceof Request) return fetch(input, init); const url = new URL( input instanceof URL ? input.href : input, "http://app.test", ); return fetch(url, init); }; describe("reference feature production vertical path", () => { it("traverses bootstrap, router, application, HTTP schema/mapper and query cache", async () => { const user = userEvent.setup(); const composition = await createRuntimeComposition({ fetcher: absoluteFetch, host: {}, }); window.history.pushState( {}, "", "/examples/reference-resources?tags=open&tags=new&limit=5", ); render(); await user.click( await screen.findByRole("button", { name: "로그인 시작" }), ); expect(await screen.findByText("Existing")).toBeVisible(); expect(listRequests).toHaveBeenCalledWith( "?limit=5&tags=open&tags=new", ); await user.click(screen.getByRole("button", { name: "새 항목 만들기" })); await user.type( await screen.findByRole("textbox", { name: /새 항목 이름/ }), " Created ", ); await user.click(screen.getByRole("button", { name: "저장" })); expect(await screen.findByText("저장했습니다.")).toBeVisible(); await user.click(screen.getByRole("button", { name: "목록으로 돌아가기" })); expect(await screen.findByText("Created")).toBeVisible(); expect(createRequests).toHaveBeenCalledWith({ name: "Created" }); expect(listRequests.mock.calls.length).toBeGreaterThanOrEqual(2); }); it("resends a create whose 504 lost the response with the same Idempotency-Key", async () => { const user = userEvent.setup(); const idempotencyKeys: (string | null)[] = []; mockApi.server.use( http.post("https://api.test/api/reference-resources", async ({ request }) => { idempotencyKeys.push(request.headers.get("idempotency-key")); // The first request reaches the server; only its response is lost. if (idempotencyKeys.length === 1) { return new HttpResponse(null, { status: 504 }); } const body = (await request.json()) as { name: string }; return HttpResponse.json( { id: "reference-created", name: body.name, createdAt: "2026-07-26T00:00:00.000Z", }, { status: 201 }, ); }), ); const composition = await createRuntimeComposition({ fetcher: absoluteFetch, host: {}, }); window.history.pushState({}, "", "/examples/reference-resources/new"); render(); await user.click( await screen.findByRole("button", { name: "로그인 시작" }), ); await user.type( await screen.findByRole("textbox", { name: /새 항목 이름/ }), "Lost response", ); await user.click(screen.getByRole("button", { name: "저장" })); await user.click( await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }), ); expect(await screen.findByText("저장했습니다.")).toBeVisible(); expect(idempotencyKeys).toHaveLength(2); expect(idempotencyKeys[0]).toMatch(/^[\x21-\x7e]+$/u); expect(idempotencyKeys[1]).toBe(idempotencyKeys[0]); }); it("keeps the key when the resend meets the first attempt still in flight (0929/03-01)", async () => { const user = userEvent.setup(); const idempotencyKeys: (string | null)[] = []; // A server that deduplicates by key: one receipt per created resource. const receipts = new Map>(); let firstAttemptRunning = true; mockApi.server.use( http.post("https://api.test/api/reference-resources", async ({ request }) => { const key = request.headers.get("idempotency-key") ?? ""; idempotencyKeys.push(key); const receipt = receipts.get(key); if (receipt) { if (firstAttemptRunning) { // The paired backend answers a same-key request while the first // attempt still runs with 409 IDEMPOTENT_IN_FLIGHT. firstAttemptRunning = false; return HttpResponse.json( { type: "https://api.test/problems/idempotent_in_flight", title: "IDEMPOTENT_IN_FLIGHT", status: 409, code: "IDEMPOTENT_IN_FLIGHT", }, { status: 409, headers: { "content-type": "application/problem+json" }, }, ); } return HttpResponse.json(receipt, { status: 201 }); } const body = (await request.json()) as { name: string }; const resource = { id: `reference-created-${receipts.size + 1}`, name: body.name, createdAt: "2026-07-26T00:00:00.000Z", }; receipts.set(key, resource); // The first attempt reaches the server; only its response is lost. if (receipts.size === 1) return new HttpResponse(null, { status: 504 }); return HttpResponse.json(resource, { status: 201 }); }), ); const composition = await createRuntimeComposition({ fetcher: absoluteFetch, host: {}, }); window.history.pushState({}, "", "/examples/reference-resources/new"); render(); await user.click( await screen.findByRole("button", { name: "로그인 시작" }), ); await user.type( await screen.findByRole("textbox", { name: /새 항목 이름/ }), "Slow write", ); await user.click(screen.getByRole("button", { name: "저장" })); await user.click( await screen.findByRole("button", { name: "같은 요청으로 다시 보내기" }), ); await waitFor(() => expect(idempotencyKeys).toHaveLength(2)); // After the 409 the user takes the next step the screen offers. const next = await waitFor(() => { const resend = screen.queryByRole("button", { name: "같은 요청으로 다시 보내기", }); if (resend) return resend; const save = screen.getByRole("button", { name: "저장" }); expect(save).toBeEnabled(); return save; }); const shownAfterInFlight = { unknown: screen.queryByText("변경 결과를 확인할 수 없습니다.") !== null, conflict: screen.queryAllByText(/충돌/).length > 0, }; await user.click(next); await waitFor(() => expect(idempotencyKeys).toHaveLength(3)); const [first] = idempotencyKeys; expect(idempotencyKeys).toEqual([first, first, first]); expect(receipts.size).toBe(1); expect(shownAfterInFlight).toEqual({ unknown: true, conflict: false }); expect(await screen.findByText("저장했습니다.")).toBeVisible(); }); it.each([ // The demo session treats a server 401 as signed out; the route guard // then asks for sign-in and the form is gone. [401, "세션이 필요합니다."], [403, "이 작업을 수행할 권한이 없습니다."], [429, "요청이 많습니다. 잠시 후 다시 시도해 주세요."], ])( "treats a create rejected with %i as not applied, not unknown", async (status, guidance) => { const user = userEvent.setup(); mockApi.server.use( http.post( "https://api.test/api/reference-resources", () => new HttpResponse(null, { status }), ), ); const composition = await createRuntimeComposition({ fetcher: absoluteFetch, host: {}, }); window.history.pushState({}, "", "/examples/reference-resources/new"); render(); await user.click( await screen.findByRole("button", { name: "로그인 시작" }), ); await user.type( await screen.findByRole("textbox", { name: /새 항목 이름/ }), "Rejected", ); await user.click(screen.getByRole("button", { name: "저장" })); expect(await screen.findByText(guidance)).toBeVisible(); expect( screen.queryByText("변경 결과를 확인할 수 없습니다."), ).not.toBeInTheDocument(); expect( screen.queryByRole("button", { name: "같은 요청으로 다시 보내기" }), ).not.toBeInTheDocument(); expect(document.body).not.toHaveTextContent("입력 내용을 확인해 주세요."); }, ); it("shows a server 422 field error on its field (03-04)", async () => { const user = userEvent.setup(); mockApi.server.use( http.post("https://api.test/api/reference-resources", () => HttpResponse.json( { type: "https://api.test/problems/validation_rejected", title: "VALIDATION_REJECTED", status: 422, code: "VALIDATION_REJECTED", issues: [ { path: "name", code: "too_big", message: "backend copy" }, { path: "serverOnly", code: "REQUIRED" }, ], }, { status: 422 }, ), ), ); const composition = await createRuntimeComposition({ fetcher: absoluteFetch, host: {}, }); window.history.pushState({}, "", "/examples/reference-resources/new"); render(); await user.click( await screen.findByRole("button", { name: "로그인 시작" }), ); const name = await screen.findByRole("textbox", { name: /새 항목 이름/ }); await user.type(name, "Too long for the server"); await user.click(screen.getByRole("button", { name: "저장" })); const summary = await screen.findByRole("alert"); expect(summary).toHaveTextContent("새 항목 이름: 입력값이 너무 깁니다."); expect(summary).toHaveTextContent("서버가 확인하지 못한 입력 항목이 있습니다."); expect(name).toHaveAttribute("aria-invalid", "true"); expect(document.body).not.toHaveTextContent("backend copy"); }); });