diff --git a/apps/builder/app/builder/features/publish/diagnostics.test.tsx b/apps/builder/app/builder/features/publish/diagnostics.test.tsx index 9f686a0557..bac95a1852 100644 --- a/apps/builder/app/builder/features/publish/diagnostics.test.tsx +++ b/apps/builder/app/builder/features/publish/diagnostics.test.tsx @@ -26,10 +26,17 @@ afterEach(() => { const render = ( findings: DiagnosticFinding[], - canViewPublishLogs = true, - items: SessionPublish[] = [], - onLoadLog?: (item: SessionPublish) => void, - open?: boolean + { + canViewPublishLogs = true, + items = [], + onLoadLog, + open, + }: { + canViewPublishLogs?: boolean; + items?: SessionPublish[]; + onLoadLog?: (item: SessionPublish) => void; + open?: boolean; + } = {} ) => { container = document.createElement("div"); document.body.appendChild(container); @@ -69,10 +76,8 @@ const openDetails = (element: HTMLElement) => { }; test("keeps audit and build findings in severity tabs, not in publish logs", async () => { - render( - [], - true, - [ + render([], { + items: [ { buildId: "build-separated", target: "site", @@ -84,9 +89,8 @@ test("keeps audit and build findings in severity tabs, not in publish logs", asy logText: "runner-output-42", }, ], - undefined, - true - ); + open: true, + }); const tabs = Array.from( document.body.querySelectorAll('[role="tab"]') ); @@ -122,22 +126,23 @@ test.each(["findings", "details", "publish"] as const)( reportText: "report", }, ], - true, - view === "publish" - ? [ - { - buildId: "scrolling-build", - target: "site", - domains: ["example.com"], - findings: [], - status: "success", - logState: "available", - logText: "line\n".repeat(200), - }, - ] - : [], - undefined, - true + { + items: + view === "publish" + ? [ + { + buildId: "scrolling-build", + target: "site", + domains: ["example.com"], + findings: [], + status: "success", + logState: "available", + logText: "line\n".repeat(200), + }, + ] + : [], + open: true, + } ); if (view === "details") { const finding = Array.from(document.body.querySelectorAll("button")).find( @@ -289,7 +294,7 @@ test("Free shows the actual short error without details, navigation, or report c reportText: "Private long diagnostic context", }, ], - false + { canViewPublishLogs: false } ); openDetails(element); expect(document.body.textContent).toContain("Invalid MDX element nesting"); @@ -304,18 +309,21 @@ test("Free shows the actual short error without details, navigation, or report c }); test("Free hides log-derived issues, stage, and code", async () => { - const element = render([createFinding("warning", 0)], false, [ - { - buildId: "build-1", - target: "site", - domains: ["example.com"], - findings: [], - status: "failed", - code: "private-code", - failedStage: "private-stage", - issues: [{ severity: "error", message: "private-log-issue" }], - }, - ]); + const element = render([createFinding("warning", 0)], { + canViewPublishLogs: false, + items: [ + { + buildId: "build-1", + target: "site", + domains: ["example.com"], + findings: [], + status: "failed", + code: "private-code", + failedStage: "private-stage", + issues: [{ severity: "error", message: "private-log-issue" }], + }, + ], + }); openDetails(element); const publishTab = Array.from( document.body.querySelectorAll('[role="tab"]') @@ -337,12 +345,10 @@ test("loads a completed publish when Publish opens and shows its log inline", as status: "failed", }; const onLoadLog = vi.fn(); - const element = render( - [createFinding("warning", 0)], - true, - [item], - onLoadLog - ); + const element = render([createFinding("warning", 0)], { + items: [item], + onLoadLog, + }); openDetails(element); expect(onLoadLog).not.toHaveBeenCalled(); const publishTab = Array.from( @@ -370,10 +376,8 @@ test("loads a completed publish when Publish opens and shows its log inline", as test("shows unavailable instead of loading forever when a publish has no log handle", async () => { const onLoadLog = vi.fn(); - const element = render( - [createFinding("warning", 0)], - true, - [ + const element = render([createFinding("warning", 0)], { + items: [ { buildId: "build-1", target: "site", @@ -382,8 +386,8 @@ test("shows unavailable instead of loading forever when a publish has no log han status: "failed", }, ], - onLoadLog - ); + onLoadLog, + }); openDetails(element); const publishTab = Array.from( document.body.querySelectorAll('[role="tab"]') @@ -399,10 +403,8 @@ test("lists each publish domain and copies the full loaded log", async () => { configurable: true, value: { writeText }, }); - render( - [], - true, - [ + render([], { + items: [ { buildId: "build-1", target: "site", @@ -422,9 +424,8 @@ test("lists each publish domain and copies the full loaded log", async () => { logText: "Second complete runner log", }, ], - undefined, - true - ); + open: true, + }); expect(document.body.textContent).toContain("first.example"); expect(document.body.textContent).toContain("second.example"); expect(document.body.textContent).toContain("third.example"); @@ -449,10 +450,8 @@ test("collapses each complete publish and copies its full log from the header", configurable: true, value: { writeText }, }); - render( - [], - true, - [ + render([], { + items: [ { buildId: "build-1", target: "site", @@ -472,9 +471,8 @@ test("collapses each complete publish and copies its full log from the header", logText: "Complete second publish log", }, ], - undefined, - true - ); + open: true, + }); const triggers = Array.from( document.body.querySelectorAll("button[aria-labelledby]") ); @@ -505,10 +503,8 @@ test("collapses each complete publish and copies its full log from the header", }); test("can maximize Diagnostics and aligns publish content with its title", async () => { - render( - [], - true, - [ + render([], { + items: [ { buildId: "build-1", target: "site", @@ -519,9 +515,8 @@ test("can maximize Diagnostics and aligns publish content with its title", async logText: "Build output", }, ], - undefined, - true - ); + open: true, + }); const dialog = document.body.querySelector('[role="dialog"]'); const titleButton = document.body.querySelector( @@ -565,18 +560,18 @@ test("publish failure is plain text and links to the Publish tab", async () => { reportText: "Build failed before deployment", }, ], - true, - [ - { - buildId: "build-1", - target: "site", - domains: ["first.example"], - findings: [], - status: "failed", - }, - ], - undefined, - true + { + items: [ + { + buildId: "build-1", + target: "site", + domains: ["first.example"], + findings: [], + status: "failed", + }, + ], + open: true, + } ); expect(document.body.textContent).toContain("Build failed before deployment"); expect(document.body.textContent).not.toContain("Audit"); @@ -613,20 +608,21 @@ test("Free publish failures link to a Publish upgrade banner without exposing lo reportText: "Publish failed", }, ], - false, - [ - { - buildId: "build-1", - target: "site", - domains: ["first.example"], - findings: [], - status: "failed", - logState: "available", - logText: "private runner output", - }, - ], - undefined, - true + { + canViewPublishLogs: false, + items: [ + { + buildId: "build-1", + target: "site", + domains: ["first.example"], + findings: [], + status: "failed", + logState: "available", + logText: "private runner output", + }, + ], + open: true, + } ); expect(document.body.textContent).toContain("Publish failed"); const link = Array.from(document.body.querySelectorAll("button")).find( @@ -647,10 +643,8 @@ test("Free publish failures link to a Publish upgrade banner without exposing lo }); test("lists publishes oldest first and opens the newest entry", () => { - render( - [], - true, - [ + render([], { + items: [ { buildId: "new", target: "site", @@ -666,9 +660,8 @@ test("lists publishes oldest first and opens the newest entry", () => { status: "failed", }, ], - undefined, - true - ); + open: true, + }); const triggers = Array.from( document.body.querySelectorAll("button[aria-labelledby]") ); @@ -692,10 +685,7 @@ test("pre-dispatch failure has no link to an absent Publish tab", () => { reportText: "Publish request failed", }, ], - true, - [], - undefined, - true + { open: true } ); expect(document.body.textContent).toContain("Publish request failed"); expect(document.body.textContent).not.toContain("Audit"); @@ -726,20 +716,21 @@ test.each([true, false])( reportText: "new-request-rejection", }, ], - paid, - [ - { - buildId: "old-build", - target: "site", - domains: ["example.com"], - status: "success", - findings: [], - logState: "available", - logText: "old-output", - }, - ], - undefined, - true + { + canViewPublishLogs: paid, + items: [ + { + buildId: "old-build", + target: "site", + domains: ["example.com"], + status: "success", + findings: [], + logState: "available", + logText: "old-output", + }, + ], + open: true, + } ); expect( document.body.querySelector('[role="tab"][aria-selected="true"]') @@ -764,7 +755,7 @@ test("Free audit summaries do not expose long cached details", () => { reportText: longSummary, }, ], - false + { canViewPublishLogs: false } ); openDetails(element); expect(document.body.textContent).toContain("Short reason"); diff --git a/apps/builder/app/builder/features/publish/publish-click.render.test.tsx b/apps/builder/app/builder/features/publish/publish-click.render.test.tsx index 3fb6292147..e105a7ee8b 100644 --- a/apps/builder/app/builder/features/publish/publish-click.render.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-click.render.test.tsx @@ -12,6 +12,7 @@ import { } from "vitest"; import { TooltipProvider, toast } from "@webstudio-is/design-system"; import type { Project } from "@webstudio-is/project"; +import { trpcFetch } from "./publish-test-utils"; const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }; const originalActEnvironment = reactEnvironment.IS_REACT_ACT_ENVIRONMENT; @@ -40,102 +41,73 @@ beforeAll(async () => { vi.resetModules(); vi.stubGlobal( "fetch", - async (requestInfo: RequestInfo | URL, requestInit?: RequestInit) => { - const url = new URL(String(requestInfo), "http://localhost"); - const input = - requestInit?.body === undefined - ? JSON.parse(url.searchParams.get("input") ?? "{}") - : JSON.parse(String(requestInit.body)); - const results = url.pathname - .slice("/trpc/".length) - .split(",") - .map((route, index) => { - const path = `/trpc/${route}`; - requests.push({ path, input: { "0": input[String(index)] } }); - let data: unknown; - switch (path) { - case "/trpc/domain.publish": - if (publishResponse instanceof Error) { - throw publishResponse; - } - data = publishResponse; - didPublish = (publishResponse as { success: boolean }).success; - break; - case "/trpc/api.publish.getJob": - data = { status: jobStatus, code: "BUILD_FAILED" }; - break; - case "/trpc/api.publish.getLog": { - const cursor = (input[String(index)] as { cursor?: number }) - .cursor; - logCursors.push(cursor); - data = { - availability: "available", - startedAt: "2026-11-13T10:00:00.000Z", - completedAt: "2026-11-13T10:00:03.000Z", - log: { - encoding: "base64url", - chunk: btoa( - String.fromCharCode( - ...(cursor === undefined ? [0xe2] : [0x82, 0xac]) - ) - ), - complete: cursor !== undefined, - nextCursor: cursor === undefined ? 1 : undefined, - issues: [ - { - severity: cursor === undefined ? "warning" : "error", - message: - cursor === undefined ? "Early warning" : "Late error", - }, - ], - }, - }; - break; - } - case "/trpc/domain.project": - data = { - success: true, - project: { - id: "project-1", - domain: "example", - domainsVirtual: [], - latestBuildVirtual: didPublish - ? { - domain: "example", - buildId: "build-1", - createdAt: new Date().toISOString(), - publishStatus: - jobStatus === "success" ? "PUBLISHED" : "FAILED", - } - : null, - }, - }; - break; - case "/trpc/domain.countTotalDomains": - data = { success: true, data: 0 }; - break; - case "/trpc/project.userPublishCount": - data = { success: true, data: 0, limit: 100 }; - break; - default: - return { - error: { - message: `Unexpected request: ${path}`, - code: -32603, - data: { - code: "INTERNAL_SERVER_ERROR", - httpStatus: 500, - path: route, - }, - }, - }; + trpcFetch( + { + "domain.publish": () => { + if (publishResponse instanceof Error) { + throw publishResponse; } - return { result: { data } }; - }); - return new Response(JSON.stringify(results), { - headers: { "Content-Type": "application/json" }, - }); - } + didPublish = (publishResponse as { success: boolean }).success; + return publishResponse; + }, + "api.publish.getJob": () => { + return { status: jobStatus, code: "BUILD_FAILED" }; + }, + "api.publish.getLog": (input) => { + const cursor = (input as { cursor?: number }).cursor; + logCursors.push(cursor); + return { + availability: "available", + startedAt: "2026-11-13T10:00:00.000Z", + completedAt: "2026-11-13T10:00:03.000Z", + log: { + encoding: "base64url", + chunk: btoa( + String.fromCharCode( + ...(cursor === undefined ? [0xe2] : [0x82, 0xac]) + ) + ), + complete: cursor !== undefined, + nextCursor: cursor === undefined ? 1 : undefined, + issues: [ + { + severity: cursor === undefined ? "warning" : "error", + message: + cursor === undefined ? "Early warning" : "Late error", + }, + ], + }, + }; + }, + "domain.project": () => { + return { + success: true, + project: { + id: "project-1", + domain: "example", + domainsVirtual: [], + latestBuildVirtual: didPublish + ? { + domain: "example", + buildId: "build-1", + createdAt: new Date().toISOString(), + publishStatus: + jobStatus === "success" ? "PUBLISHED" : "FAILED", + } + : null, + }, + }; + }, + "domain.countTotalDomains": () => ({ success: true, data: 0 }), + "project.userPublishCount": () => ({ + success: true, + data: 0, + limit: 100, + }), + }, + (route, input) => + requests.push({ path: `/trpc/${route}`, input: { "0": input } }) + ) ); publishModule = await import("./publish"); stores = await import("~/shared/sync/data-stores"); diff --git a/apps/builder/app/builder/features/publish/publish-flow.render.test.tsx b/apps/builder/app/builder/features/publish/publish-flow.render.test.tsx index bd615af808..50856a4719 100644 --- a/apps/builder/app/builder/features/publish/publish-flow.render.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-flow.render.test.tsx @@ -14,24 +14,10 @@ import { TooltipProvider, toast } from "@webstudio-is/design-system"; import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session"; import type { Project } from "@webstudio-is/project"; import type { Pages } from "@webstudio-is/sdk"; +import { deferred, trpcFetch } from "./publish-test-utils"; -const deferred = () => { - let resolve!: (value: T) => void; - let reject!: (error: Error) => void; - const promise = new Promise((done, fail) => { - resolve = done; - reject = fail; - }); - return { promise, resolve, reject }; -}; - -const respond = (data: unknown) => - new Response(JSON.stringify([{ result: { data } }]), { - headers: { "Content-Type": "application/json" }, - }); - -let checks = deferred(); -let dispatch = deferred(); +let checks = deferred(); +let dispatch = deferred(); let checkRequests = 0; let checksRead = 0; let publishRequests = 0; @@ -49,58 +35,18 @@ beforeAll(async () => { globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } ).IS_REACT_ACT_ENVIRONMENT = true; vi.resetModules(); - vi.stubGlobal("fetch", async (requestInfo: RequestInfo | URL) => { - const path = new URL(String(requestInfo), "http://localhost").pathname; - if (path.includes(",")) { - const results = path - .slice("/trpc/".length) - .split(",") - .map((route) => { - if (route === "domain.project") { - return { - result: { - data: { success: true, project: stores.$project.get() }, - }, - }; - } - if (route === "domain.countTotalDomains") { - return { result: { data: { success: true, data: 0 } } }; - } - if (route === "project.userPublishCount") { - return { result: { data: { success: true, data: 0, limit: 100 } } }; - } - if (route === "api.publish.getLog") { - return { - result: { - data: { - availability: "available", - log: { - encoding: "base64url", - chunk: btoa("older publish output"), - complete: true, - issues: [ - { severity: "error", message: "older build issue" }, - ], - }, - }, - }, - }; - } - throw new Error(`Unexpected request: ${route}`); - }); - return new Response(JSON.stringify(results), { - headers: { "Content-Type": "application/json" }, - }); - } - if (path === "/trpc/domain.publish") { - publishRequests += 1; - return dispatch.promise; - } - if (path === "/trpc/api.publish.getJob") { - return respond({ status: "failed", code: "BUILD_FAILED" }); - } - if (path === "/trpc/api.publish.getLog") { - return respond({ + vi.stubGlobal( + "fetch", + trpcFetch({ + "domain.publish": () => { + publishRequests += 1; + return dispatch.promise; + }, + "api.publish.getJob": () => ({ + status: "failed", + code: "BUILD_FAILED", + }), + "api.publish.getLog": () => ({ availability: "available", log: { encoding: "base64url", @@ -108,38 +54,41 @@ beforeAll(async () => { complete: true, issues: [{ severity: "error", message: "older build issue" }], }, - }); - } - if (path === "/trpc/domain.project") { - return respond({ success: true, project: stores.$project.get() }); - } - if (path === "/trpc/domain.countTotalDomains") { - return respond({ success: true, data: 0 }); - } - if (path === "/trpc/project.userPublishCount") { - return respond({ success: true, data: 0, limit: 100 }); - } - if ( - path === "/trpc/api.publish.validate" || - path === "/trpc/build.contentDatabasePublishDiagnostics" - ) { - checkRequests += 1; - try { - const response = (await checks.promise).clone(); - const json = response.json.bind(response); - response.json = async () => { - const result = await json(); + }), + "domain.project": () => ({ + success: true, + project: stores.$project.get(), + }), + "domain.countTotalDomains": () => ({ success: true, data: 0 }), + "project.userPublishCount": () => ({ + success: true, + data: 0, + limit: 100, + }), + "api.publish.validate": async () => { + checkRequests += 1; + try { + const result = await checks.promise; checksRead += 1; return result; - }; - return response; - } catch (error) { - checksRead += 1; - throw error; - } - } - throw new Error(`Unexpected request: ${path}`); - }); + } catch (error) { + checksRead += 1; + throw error; + } + }, + "build.contentDatabasePublishDiagnostics": async () => { + checkRequests += 1; + try { + const result = await checks.promise; + checksRead += 1; + return result; + } catch (error) { + checksRead += 1; + throw error; + } + }, + }) + ); PublishButton = (await import("./publish")).PublishButton; stores = await import("~/shared/sync/data-stores"); nanoStates = await import("~/shared/nano-states"); @@ -169,8 +118,8 @@ beforeEach(() => { getContentSession: () => contentSession, }) ); - checks = deferred(); - dispatch = deferred(); + checks = deferred(); + dispatch = deferred(); checkRequests = 0; checksRead = 0; publishRequests = 0; @@ -198,8 +147,8 @@ beforeEach(() => { afterEach(async () => { act(() => root.unmount()); - checks.resolve(respond({ mdxErrors: [], mdxOmissions: [] })); - dispatch.resolve(respond({ success: false, error: "cleanup" })); + checks.resolve({ mdxErrors: [], mdxOmissions: [] }); + dispatch.resolve({ success: false, error: "cleanup" }); await act(async () => vi.waitFor(() => expect(checksRead).toBe(checkRequests)) ); @@ -280,14 +229,12 @@ const completeChecks = async (fail: boolean) => { if (fail) { checks.reject(new Error("check failure")); } else { - checks.resolve( - respond({ - diagnostics: { mdxErrors: [], mdxOmissions: [] }, - cssValid: false, - mdxErrors: [], - mdxOmissions: [{ filename: "check.mdx", templateName: "missing" }], - }) - ); + checks.resolve({ + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: false, + mdxErrors: [], + mdxOmissions: [{ filename: "check.mdx", templateName: "missing" }], + }); } await checks.promise.catch(() => {}); await vi.waitFor(() => expect(checksRead).toBe(checkRequests)); @@ -352,12 +299,10 @@ test.each([ await completeChecks(failChecks); } await act(async () => { - dispatch.resolve( - respond({ - success: false, - auditFindings: [{ severity: "error", message: "server rejection" }], - }) - ); + dispatch.resolve({ + success: false, + auditFindings: [{ severity: "error", message: "server rejection" }], + }); await dispatch.promise; }); const errors = await openErrors(target); @@ -399,20 +344,21 @@ test("closing Publish clears a completed validation", async () => { await act(async () => validate?.click()); await act(async () => vi.waitFor(() => expect(checkRequests).toBe(1))); await act(async () => { - checks.resolve( - respond({ - diagnostics: { mdxErrors: [], mdxOmissions: [] }, - cssValid: true, - }) - ); + checks.resolve({ + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: true, + }); await checks.promise; await vi.waitFor(() => expect(checksRead).toBe(1)); }); - expect( - Array.from(document.body.querySelectorAll("button")).some( - (button) => button.textContent?.trim() === "Validated" - ) - ).toBe(true); + await vi.waitFor(async () => { + await act(async () => {}); + expect( + Array.from(document.body.querySelectorAll("button")).map((button) => + button.textContent?.trim() + ) + ).toContain("Validated"); + }); await act(async () => publishDialog.set("none")); await act(async () => publishDialog.set("publish")); expect( @@ -438,7 +384,7 @@ test.each([ const message = `${failure} failure`; await act(async () => { if (failure === "request") { - dispatch.resolve(respond({ success: false, error: message })); + dispatch.resolve({ success: false, error: message }); } else { dispatch.reject(new Error(message)); } @@ -483,22 +429,20 @@ test.each(["request", "transport"] as const)( await clickPublish("site"); await completeChecks(false); await act(async () => { - dispatch.resolve(respond({ success: false, error: "site rejection" })); + dispatch.resolve({ success: false, error: "site rejection" }); await dispatch.promise; }); const originalSiteErrors = await openErrors("site"); expect(originalSiteErrors?.textContent).toContain("site rejection"); await closeReport(); - checks = deferred(); - dispatch = deferred(); + checks = deferred(); + dispatch = deferred(); await mount("static"); await clickPublish("static", 2); await completeChecks(false); await act(async () => { if (failure === "request") { - dispatch.resolve( - respond({ success: false, error: "static rejection" }) - ); + dispatch.resolve({ success: false, error: "static rejection" }); } else { dispatch.reject(new Error("static transport")); } @@ -594,14 +538,12 @@ test("an accepted site failure links to its own publish log", async () => { await clickPublish("site"); await completeChecks(false); await act(async () => { - dispatch.resolve( - respond({ - success: true, - buildId: "accepted-build", - logHandle: "handle", - findings: [], - }) - ); + dispatch.resolve({ + success: true, + buildId: "accepted-build", + logHandle: "handle", + findings: [], + }); await dispatch.promise; }); const errors = await openErrors("site"); @@ -660,22 +602,31 @@ test.each([ await act(async () => publishDialog.set("publish")); } await act(async () => { - checks.resolve( - respond({ - diagnostics: { mdxErrors: [], mdxOmissions: [] }, - cssValid: true, - }) - ); + checks.resolve({ + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: true, + }); await checks.promise; await vi.waitFor(() => expect(checksRead).toBe(1)); }); - expect(successToast).toHaveBeenCalledTimes(expectedToasts); - if (destination === "publish" || reopen) { - expect( - Array.from(document.body.querySelectorAll("button")).some( - (button) => button.textContent?.trim() === "Validated" + if (expectedToasts > 0) { + await act(async () => + vi.waitFor(() => + expect(successToast).toHaveBeenCalledTimes(expectedToasts) ) - ).toBe(true); + ); + } else { + expect(successToast).not.toHaveBeenCalled(); + } + if (destination === "publish" || reopen) { + await vi.waitFor(async () => { + await act(async () => {}); + expect( + Array.from(document.body.querySelectorAll("button")).some( + (button) => button.textContent?.trim() === "Validated" + ) + ).toBe(true); + }); } else { await act(async () => publishDialog.set("publish")); expect( @@ -705,15 +656,13 @@ test.each([ await clickPublish(target); await completeChecks(false); await act(async () => { - dispatch.resolve( - respond({ - success: true, - buildId: "older-build", - logHandle: "older-handle", - findings: [], - ...(target === "static" ? { name: "site.zip" } : {}), - }) - ); + dispatch.resolve({ + success: true, + buildId: "older-build", + logHandle: "older-handle", + findings: [], + ...(target === "static" ? { name: "site.zip" } : {}), + }); await dispatch.promise; }); await act(async () => @@ -725,8 +674,8 @@ test.each([ ).not.toBeNull() ) ); - checks = deferred(); - dispatch = deferred(); + checks = deferred(); + dispatch = deferred(); await mount(target); await clickPublish(target, 2); const message = `new ${failure} failure`; @@ -735,14 +684,12 @@ test.each([ dispatch.reject(new Error(message)); } else { dispatch.resolve( - respond( - failure === "audit" - ? { - success: false, - auditFindings: [{ severity: "error", message }], - } - : { success: false, error: message } - ) + failure === "audit" + ? { + success: false, + auditFindings: [{ severity: "error", message }], + } + : { success: false, error: message } ); } await dispatch.promise.catch(() => {}); diff --git a/apps/builder/app/builder/features/publish/publish-progress.render.test.tsx b/apps/builder/app/builder/features/publish/publish-progress.render.test.tsx index 980bbbcca8..3c2adf166c 100644 --- a/apps/builder/app/builder/features/publish/publish-progress.render.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-progress.render.test.tsx @@ -13,20 +13,11 @@ import { import { TooltipProvider, toast } from "@webstudio-is/design-system"; import type { Project } from "@webstudio-is/project"; import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session"; +import { deferred, trpcFetch } from "./publish-test-utils"; const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }; const originalActEnvironment = reactEnvironment.IS_REACT_ACT_ENVIRONMENT; -const deferred = () => { - let resolve!: (value: T) => void; - let reject!: (error: Error) => void; - const promise = new Promise((done, fail) => { - resolve = done; - reject = fail; - }); - return { promise, resolve, reject }; -}; - let root: Root | undefined; let container: HTMLDivElement; let PublishButton: typeof import("./publish").PublishButton; @@ -71,50 +62,25 @@ beforeAll(async () => { vi.resetModules(); vi.stubGlobal( "fetch", - async (info: RequestInfo | URL, init?: RequestInit) => { - const url = new URL(String(info), location.href); - const inputs = JSON.parse( - init?.body === undefined - ? (url.searchParams.get("input") ?? "{}") - : String(init.body) - ); - const results = await Promise.all( - url.pathname - .slice("/trpc/".length) - .split(",") - .map(async (route, index) => { - requests.push({ route, input: inputs[String(index)] }); - let data: unknown; - switch (route) { - case "domain.project": - data = await refresh(); - break; - case "domain.publish": - data = await publish(); - break; - case "api.publish.validate": - case "build.contentDatabasePublishDiagnostics": - data = await validate(); - break; - case "api.publish.getJob": - data = await job(); - break; - case "domain.countTotalDomains": - data = { success: true, data: 0 }; - break; - case "project.userPublishCount": - data = { success: true, data: 0, limit: 100 }; - break; - default: - throw new Error(`Unexpected request: ${route}`); - } - return { result: { data } }; - }) - ); - return new Response(JSON.stringify(results), { - headers: { "Content-Type": "application/json" }, - }); - } + trpcFetch( + { + "domain.project": () => refresh(), + "domain.publish": () => publish(), + "api.publish.validate": () => validate(), + "build.contentDatabasePublishDiagnostics": () => validate(), + "api.publish.getJob": () => job(), + "domain.countTotalDomains": () => ({ + success: true, + data: 0, + }), + "project.userPublishCount": () => ({ + success: true, + data: 0, + limit: 100, + }), + }, + (route, input) => requests.push({ route, input }) + ) ); PublishButton = (await import("./publish")).PublishButton; stores = await import("~/shared/sync/data-stores"); diff --git a/apps/builder/app/builder/features/publish/publish-session.render.test.tsx b/apps/builder/app/builder/features/publish/publish-session.render.test.tsx index b89a3b368c..0cb81342e3 100644 --- a/apps/builder/app/builder/features/publish/publish-session.render.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-session.render.test.tsx @@ -12,14 +12,8 @@ import { } from "vitest"; import { TooltipProvider } from "@webstudio-is/design-system"; import type { Project } from "@webstudio-is/project"; +import { deferred, trpcFetch } from "./publish-test-utils"; -const deferred = () => { - let resolve!: (value: T) => void; - const promise = new Promise((done) => { - resolve = done; - }); - return { promise, resolve }; -}; const encoded = (bytes: number[]) => btoa(String.fromCharCode(...bytes)); const logRequests: Array<{ cursor?: number; @@ -57,99 +51,75 @@ beforeAll(async () => { vi.resetModules(); vi.stubGlobal( "fetch", - async (requestInfo: RequestInfo | URL, init?: RequestInit) => { - const url = new URL(String(requestInfo), "http://localhost"); - const inputs = JSON.parse( - init?.body === undefined - ? (url.searchParams.get("input") ?? "{}") - : String(init.body) - ); - const results = await Promise.all( - url.pathname - .slice("/trpc/".length) - .split(",") - .map(async (route, index) => { - const input = inputs[String(index)]; - let data: unknown; - switch (route) { - case "domain.project": - data = { - success: true, - project: { - ...stores.$project.get(), - latestBuildVirtual: { - domain: "example", - buildId: acceptedBuildId, - createdAt: new Date().toISOString(), - publishStatus: "PUBLISHED", - }, - }, - }; - break; - case "domain.countTotalDomains": - data = { success: true, data: 0 }; - break; - case "project.userPublishCount": - data = { success: true, data: 0, limit: 100 }; - break; - case "domain.publish": - publishRequests += 1; - data = heldPublish - ? await heldPublish.promise - : { - success: true, - buildId, - ...(withHandle ? { logHandle: "handle" } : {}), - findings: [], - }; - acceptedBuildId = (data as { buildId: string }).buildId; - break; - case "api.publish.getJob": - data = heldJob ? await heldJob.promise : { status: "success" }; - break; - case "api.publish.getLog": { - logRequests.push(input); - const first = input.cursor === undefined; - if ( - input.buildId === "build-1" && - holdLog && - holdLog.cursor === input.cursor - ) { - await holdLog.response.promise; - } - data = { - availability: "available", - startedAt: "2026-11-13T10:00:00.000Z", - completedAt: "2026-11-13T10:00:03.000Z", - log: { - encoding: "base64url", - chunk: first ? encoded([0xe2]) : encoded([0x82, 0xac]), - complete: !first, - nextCursor: first ? 1 : undefined, - issues: [ - { - severity: first ? "warning" : "error", - message: first ? "Early warning" : "Late error", - }, - ], - issuesOmitted: first ? 1 : 0, - }, - }; - break; - } - case "build.contentDatabasePublishDiagnostics": - data = { mdxErrors: [], mdxOmissions: [] }; - break; - default: - throw new Error(`Unexpected request: ${route}`); - } - return { result: { data } }; - }) - ); - return new Response(JSON.stringify(results), { - headers: { "Content-Type": "application/json" }, - }); - } + trpcFetch({ + "domain.project": () => ({ + success: true, + project: { + ...stores.$project.get(), + latestBuildVirtual: { + domain: "example", + buildId: acceptedBuildId, + createdAt: new Date().toISOString(), + publishStatus: "PUBLISHED", + }, + }, + }), + "domain.countTotalDomains": () => ({ success: true, data: 0 }), + "project.userPublishCount": () => ({ + success: true, + data: 0, + limit: 100, + }), + "domain.publish": async () => { + publishRequests += 1; + const data = heldPublish + ? await heldPublish.promise + : { + success: true, + buildId, + ...(withHandle ? { logHandle: "handle" } : {}), + findings: [], + }; + acceptedBuildId = (data as { buildId: string }).buildId; + return data; + }, + "api.publish.getJob": () => + heldJob ? heldJob.promise : { status: "success" }, + "api.publish.getLog": async (value) => { + const input = value as (typeof logRequests)[number]; + logRequests.push(input); + const first = input.cursor === undefined; + if ( + input.buildId === "build-1" && + holdLog && + holdLog.cursor === input.cursor + ) { + await holdLog.response.promise; + } + return { + availability: "available", + startedAt: "2026-11-13T10:00:00.000Z", + completedAt: "2026-11-13T10:00:03.000Z", + log: { + encoding: "base64url", + chunk: first ? encoded([0xe2]) : encoded([0x82, 0xac]), + complete: !first, + nextCursor: first ? 1 : undefined, + issues: [ + { + severity: first ? "warning" : "error", + message: first ? "Early warning" : "Late error", + }, + ], + issuesOmitted: first ? 1 : 0, + }, + }; + }, + "build.contentDatabasePublishDiagnostics": () => ({ + mdxErrors: [], + mdxOmissions: [], + }), + }) ); PublishButton = (await import("./publish")).PublishButton; stores = await import("~/shared/sync/data-stores"); diff --git a/apps/builder/app/builder/features/publish/publish-static.test.tsx b/apps/builder/app/builder/features/publish/publish-static.test.tsx index ef2de3038c..159e54eaf1 100644 --- a/apps/builder/app/builder/features/publish/publish-static.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-static.test.tsx @@ -4,6 +4,7 @@ import { userEvent } from "@vitest/browser/context"; import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest"; import { TooltipProvider, toast } from "@webstudio-is/design-system"; import type { Project } from "@webstudio-is/project"; +import { trpcFetch } from "./publish-test-utils"; let root: Root | undefined; let container: HTMLDivElement | undefined; @@ -33,11 +34,6 @@ const interceptDownload = (event: NavigateEvent) => { } }; -const respond = (data: unknown) => - new Response(JSON.stringify([{ result: { data } }]), { - headers: { "Content-Type": "application/json" }, - }); - ( globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } ).IS_REACT_ACT_ENVIRONMENT = true; @@ -45,36 +41,22 @@ const respond = (data: unknown) => beforeAll(async () => { window.navigation.addEventListener("navigate", interceptDownload); vi.resetModules(); - vi.stubGlobal("fetch", async (requestInfo: RequestInfo | URL) => { - const path = new URL(String(requestInfo), "http://localhost").pathname; - if (path.includes(",")) { - const responses = await Promise.all( - path - .slice("/trpc/".length) - .split(",") - .map(async (route) => { - const response = await fetch(`/trpc/${route}`); - const results = (await response.json()) as unknown[]; - return results[0]; - }) - ); - return new Response(JSON.stringify(responses), { - headers: { "Content-Type": "application/json" }, - }); - } - if (path === "/trpc/build.contentDatabasePublishDiagnostics") { - return respond({ mdxErrors: [], mdxOmissions: [] }); - } - if (path === "/trpc/domain.publish") { - publishRequests += 1; - return respond(staticResponse); - } - if (path === "/trpc/api.publish.getJob") { - jobRequests += 1; - return respond({ status: getJobStatus }); - } - if (path === "/trpc/domain.project") { - return respond({ + vi.stubGlobal( + "fetch", + trpcFetch({ + "build.contentDatabasePublishDiagnostics": () => ({ + mdxErrors: [], + mdxOmissions: [], + }), + "domain.publish": () => { + publishRequests += 1; + return staticResponse; + }, + "api.publish.getJob": () => { + jobRequests += 1; + return { status: getJobStatus }; + }, + "domain.project": () => ({ success: true, project: { ...projectStore.get(), @@ -87,10 +69,9 @@ beforeAll(async () => { publishStatus: "PUBLISHED", }, }, - }); - } - throw new Error(`Unexpected request: ${path}`); - }); + }), + }) + ); publishModule = await import("./publish"); nanoStates = await import("~/shared/nano-states"); publishDialog = (await import("~/builder/shared/nano-states")).$publishDialog; diff --git a/apps/builder/app/builder/features/publish/publish-test-utils.ts b/apps/builder/app/builder/features/publish/publish-test-utils.ts new file mode 100644 index 0000000000..7b4f8f51ee --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-test-utils.ts @@ -0,0 +1,38 @@ +export const deferred = () => { + let resolve!: (value: T) => void; + let reject!: (error: Error) => void; + const promise = new Promise((done, fail) => { + resolve = done; + reject = fail; + }); + return { promise, resolve, reject }; +}; + +export const trpcFetch = + ( + handlers: Record unknown | Promise>, + onRequest?: (route: string, input: unknown) => void + ) => + async (requestInfo: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(requestInfo), location.href); + const input = JSON.parse( + init?.body === undefined + ? (url.searchParams.get("input") ?? "{}") + : String(init.body) + ); + const routes = url.pathname.slice("/trpc/".length).split(","); + const results = await Promise.all( + routes.map(async (route, index) => { + const handler = handlers[route]; + if (handler === undefined) { + throw new Error(`Unexpected request: ${route}`); + } + const value = input[String(index)]; + onRequest?.(route, value); + return { result: { data: await handler(value) } }; + }) + ); + return new Response(JSON.stringify(results), { + headers: { "Content-Type": "application/json" }, + }); + };