From 896a383e32a2dd34a68e684fcd351d0f73cfb385 Mon Sep 17 00:00:00 2001 From: Oleg Isonen Date: Sun, 15 Nov 2026 16:55:45 +0000 Subject: [PATCH] feat: show publish logs in Builder, CLI, and MCP (#6690) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Staging work for publish diagnostics. This PR pairs with webstudio-is/webstudio-saas#681. No production release is authorized. ## What changes People can open Diagnostics from a domain or static export to see warnings, errors, and publishes from the current Builder session. Each publish has its own collapsible report and copy control. A failed publish keeps a short reason and links to its own log when that publish was accepted. Builder, CLI, and MCP use the same publish reference and log access path. Status and logs stay separate. Builder keeps session reports in memory, and Edge retrieves available output from the current publish runner. Reloading Builder loses session reports. An unavailable log does not change publish success or failure. Log pages still require runner retrieval and transfer through Edge and Builder; there is no Webstudio log archive in this PR. The UI now keeps publish state in its owning component, with separate site and static actions, focused diagnostics views, and one domain status control. Both actions share completion handling while retaining their different request and download behavior. Late best-effort checks cannot erase a final rejection. A new rejected request does not make an older publish look like its log. Site errors stay scoped to the selected domains. The existing site and asset publish paths are unchanged. ## Checklist - [x] Keep confirmed session success ahead of stale Build timeout during popover reconciliation; cover an old Build timestamp. - [x] Retry a temporarily pending or failed publish-log read before marking it unavailable; cover session behavior. - [x] Verify CI on the rebased PR head and confirm review threads remain resolved. - [x] Let a matching session's confirmed result clear stale pending controls for site and static; cover success and failure. - [x] Remove redundant static-export loading icon while keeping the export button's pending state and diagnostics access. - [x] Prefer confirmed runner success over a timeout inferred from a stale matching Build; cover site and static publishes. - [x] Keep MCP publish input valid when a target union is converted to tool JSON Schema; cover both the adapter and real CLI contract. - [x] Finish an accepted publish by its build ID even if another publish becomes the project's latest; cover site and static behavior. - [x] Review docs impact, verify local checks and CI, and reply to the new review threads. - [x] Keep current validation findings ahead of an older publish success notice; cover rejected requests and manual validation. - [x] Scope accepted-publish status errors to the domains in that publish; cover another domain's Diagnostics. - [x] Make success, warning, and error publish notices distinct and readable in dark mode; use the existing PanelBanner variants and leave light mode unchanged.\n- [x] Review documentation impact and run focused tests, typecheck, lint, and CI for these fixes. The publishing guide needs no wording change. - [x] Resolve the four Builder review comments and push the focused fix. - [x] Split Diagnostics into findings, detail, publish history, and dialog shell without new copy or icons. - [x] Keep Warnings and Errors separate from Publish logs; preserve current-session history, log copying, and access checks. - [x] Consolidate site/static flow and quota reads; narrow UI access to flow internals. - [x] Preserve completed findings, final rejection, target/domain isolation, and accepted-build log links across both completion orders. - [x] Review the remaining publish UI; share the duplicated domain status control and leave cohesive baseline domain/export UI in place. - [x] Review authoritative publishing docs for this UI change. - [x] Correct the guide's statement that all validation errors block the request; the approved wording is in the publishing guide. - [x] Audit names introduced by this PR against their runtime values and existing repository terminology; fix misleading local names without changing stored or public contracts. - [x] Review docs impact of naming-only changes and verify tests, types, lint, and CI. Docs need no change; 179 publish tests, Builder typecheck, root lint, formatting, diff checks, and all non-visual CI on the previous commit passed. Visual approval remains open. - [x] Remove single-use publish hooks; keep their state/effects in the owning component and test behavior through that component. - [x] Split site and static publish actions into clear component-owned flows without the target-discriminated publish function. - [x] Review docs impact of the structural change. No user-facing copy or behavior changed, so no further docs change is needed. - [x] Verify migrated tests, coverage, Builder core tests, typecheck, lint, formatting, and package boundaries. - [x] Simplify publish component tests: share the tRPC test transport and use named Diagnostics options without losing behavior coverage. - [x] Replace the global fetch test stub with a scoped tRPC request interceptor for publish component tests. - [x] Simplify publish component tests again: share only reusable browser setup and interactions, remove duplicate scenarios and incidental assertions, and preserve behavior coverage. - [x] Review `trpc-interface` package exports and packed-package consumers. Keep the explicit source subpaths; no manifest change is needed. - [x] Review every test changed in this PR for avoidable module mocking; replace only clear cases without reducing behavior coverage. - [x] Update and validate the global testing skill with the decision learned from that review. - [x] Re-run focused tests and relevant checks for the module-mock cleanup. - [x] Finish non-visual CI on the current commit. - [x] Audit Builder-wide global fetch replacements and no-request spies; keep injected fakes and valid narrow spies. - [x] Replace backend-style global fetch stubs and the Storybook fixture override with scoped request handlers. - [x] Preserve success, HTTP/network failure, abort, cleanup, and no-request coverage with red/green checks. - [x] Run focused and broader Builder tests, typecheck, lint, formatting, and package-boundary checks for the fetch-test cleanup. - [x] Review docs impact of the test-only cleanup; no user-facing documentation changes are needed. - [x] Make user database tests verify ownership filters, inserted values, and workspace linkage. - [x] Make patch-service tests prove the intended patch was applied and remove vacuous cases. - [x] Add focused DomainCheckbox integration coverage while keeping useful helper cases. - [x] Make publish test transport fail on unexpected requests and distinguish protocol errors from network failures. - [x] Remove duplicate permission cases and run selected DOM-free tests in Node. - [x] Review documentation impact and run relevant red/green, test, type, lint, and config checks. - [x] Show the latest successful site publish and static export in their popovers with a See logs link to the Publish tab. - [x] Cover success, new-attempt reset, Free-plan access, and both flows in component tests. - [x] Review publishing docs and verify focused tests, types, lint, formatting, and diff. - [x] Review the three expected visual differences and approve the CI rerun; visual regression passed on a0c2ca73f. ## Verification Local: 177 publish tests passed after simplifying the component suites. Two duplicate scenarios were removed; the dedicated suites still cover network failures, paged logs, plan changes, and stale responses. The latest test cleanup removes 174 net lines. Builder production code is unchanged. The earlier test cleanup removed 135 net lines across seven files. Coverage increased from 84.2% statements / 83.3% branches to 88.63% / 86.98%. Builder core passed 1,698 tests with one skip. Builder typecheck, root lint, package-boundary check, formatting, and diff checks passed. Representative migrated tests were shown failing when project scoping, late-check isolation, session eviction, validation reset, or static download behavior was temporarily broken, then passing after restoration. The current commit passed the main workflow, lint, and submodule checks. Visual approval remains open for three previously identified story differences. The prior visual report had the same three known story differences; baseline approval remains open. The visual approval gate remains open for the previously identified story differences; no new local Storybook capture was run at the user's request. The agent evaluation suite remains 8/9 because of an unrelated Form-authoring failure; baselines were not changed. The Builder-wide test cleanup replaces 11 global fetch stubs and one Storybook override. It keeps two narrow no-send spies for a pure preview function. Focused checks passed (43 Node tests, 16 browser tests, typecheck, lint, formatting, package boundaries). Full local core and app runs each had one failure in an unchanged test; the app test passed alone, and the core failure reproduced in its unchanged file. CI will provide the full-matrix check. Local request-interception work remains; no product behavior changes. A follow-up review checked all 30 changed test files for module mocks. Two unnecessary wrappers were removed: the resource-preview call counter and the cross-origin guard fake. The real HTTP boundary and a cross-site request now carry those assertions. The narrow Email preview exception fake remains because malformed real inputs do not reach that catch reliably; seven older Preview-route mocks remain tied to auth, database, protected fetch, and environment setup. This test-only follow-up passed 41 focused tests, Builder typecheck, targeted lint/formatting, diff checks, and independent review. The global testing skill was updated and validated outside this repository. The previous commit's complete main CI passed; the visual baseline approval gate remains open. Commit d340a5225 is pushed to `pub.staging`. It strengthens the user, patch, permission, checkbox, and publish-transport tests; it also shows successful site publishes and static exports in a shared notice with **See logs**. A newer attempt hides an older success, and static export does not claim “Downloaded” without a download filename. The publishing and export guides describe the new notices. New behavior assertions failed before their fixes and passed afterward. The latest local Builder core run passed 1,755 tests (one skipped); 82 focused browser tests, Builder typecheck, root lint, formatting, and diff checks also passed. No fixture inputs or outputs changed. Visual checks were not run locally at the user's request. The current visual gate passed on run 43725523044 after reviewing the two Diagnostics stories and the Activity icon. Earlier notes about pending visual approval describe previous commits. Commit cae33d877e fixes the two current Builder review findings and adds a dark-mode edge to success, warning, and error banners without changing light mode. The new rejection and domain-scope tests failed before their fixes and passed afterward. Local checks passed: 185 publish tests, 287 design-system tests, Builder and design-system typechecks, lint, formatting, package boundaries, and diff checks. Main CI and the approved visual rerun passed. The first visual run failed on the same three previously reviewed light-theme differences; no new dark-theme screenshot was taken at the user's request.\n\nCommit db5984eb95 fixes two later review findings. MCP now permits branch fields at the root of a composed tool schema; the target branches and API still validate values. Completion uses the accepted build's job status when another build becomes the project's latest. The new focused tests failed before the fixes and passed afterward. Local checks passed: 189 publish tests, 146 MCP adapter tests, 74 CLI MCP tests, relevant typechecks, lint, formatting, package boundaries, and generated MCP docs. Main CI and the approved visual regression run passed on b15eebaab3. The initial unapproved visual run showed only the three previously reviewed differences.\n\nLive staging MCP smoke check: the CLI started a staging publish, its job succeeded, and `get-publish-log` returned one complete page (6,077 characters) in the same MCP session. No log text or share token was saved in the PR. The stale-Build regression failed before a04d6c287c and passed afterward. All 193 publish tests, Builder typecheck, formatting, targeted lint, and diff checks pass. The refreshed popover trusts a matching confirmed session result but still clears a retained failure when the Build reports `PUBLISHED`. Main CI and the approved visual rerun passed on a04d6c287c. The initial visual run showed only the same three previously reviewed differences. All review threads are resolved. ## Before release - Verify a live staging publish once both staging PRs are deployed. - Release and pin the existing Builder contract package before removing the temporary copied contract in the SaaS PR. Local packed-package typecheck, Worker bundle, and tests passed; registry installation is not yet verified. - Production deployment and package publication remain user-run steps. Ref #3550 Closes #6693 --- apps/builder/.env | 1 + .../app/builder/features/publish/constants.ts | 28 + .../content-database-publish-warning.tsx | 7 +- .../features/publish/diagnostics-utils.ts | 86 + ...ts.stories.tsx => diagnostics.stories.tsx} | 18 +- .../features/publish/diagnostics.test.tsx | 784 +++++ .../builder/features/publish/diagnostics.tsx | 517 +++ ...ckbox.test.ts => domain-checkbox.test.tsx} | 80 +- .../features/publish/domain-status-button.tsx | 42 + .../builder/features/publish/domains.test.tsx | 93 +- .../app/builder/features/publish/domains.tsx | 111 +- .../features/publish/publish-actions.test.tsx | 144 +- .../features/publish/publish-actions.tsx | 37 +- .../publish/publish-click.render.test.tsx | 575 ++++ .../publish/publish-flow.render.test.tsx | 759 +++++ .../publish/publish-progress.render.test.tsx | 849 +++++ .../publish/publish-progress.test.tsx | 1190 ++----- .../features/publish/publish-progress.tsx | 237 ++ .../publish/publish-session.render.test.tsx | 437 +++ .../features/publish/publish-static.test.tsx | 321 ++ .../features/publish/publish-status.test.tsx | 4 +- .../features/publish/publish-status.tsx | 84 + .../publish/publish-test-utils.test.ts | 63 + .../features/publish/publish-test-utils.ts | 109 + .../builder/features/publish/publish-ui.tsx | 1216 +++++++ .../publish-validation-results.test.tsx | 126 - .../publish/publish-validation-results.tsx | 178 -- .../features/publish/publish-validation.tsx | 261 ++ .../app/builder/features/publish/publish.tsx | 2824 ++++++----------- .../publish/session-publishes.test.ts | 52 + .../features/publish/session-publishes.ts | 54 + .../http-resource-refresh.test.tsx | 44 +- .../variable-popover-preview.test.tsx | 88 +- .../text-file-editor.stories.tsx | 37 +- .../app/services/api-router.server.test.ts | 127 + .../builder/app/services/api-router.server.ts | 109 +- .../app/services/asset-upload.server.test.ts | 64 +- .../preview-form-route.server.test.ts | 223 +- ...utils.test.ts => array-utils.node.test.ts} | 0 ...st.ts => collection-equality.node.test.ts} | 0 .../builder/app/shared/db/user.server.test.ts | 72 +- ...sions.test.ts => permissions.node.test.ts} | 22 +- .../sync/patch/patch-service.server.test.ts | 205 +- apps/builder/package.json | 1 + .../publishing-and-custom-domains.md | 42 +- docs/university/self-hosting/download.md | 10 + .../evaluations/high-impact/fixture-api.ts | 18 +- .../cli/src/commands/api-command-docs.test.ts | 5 +- .../cli/src/commands/api-command-metadata.ts | 2 + packages/cli/src/commands/api-command.test.ts | 452 ++- packages/cli/src/commands/api-command.ts | 310 +- packages/cli/src/commands/man.ts | 1 + .../commands/mcp-publish.integration.test.ts | 214 ++ packages/cli/src/commands/mcp.test.ts | 140 + packages/cli/src/commands/mcp.ts | 214 +- packages/cli/src/commands/schema.test.ts | 43 +- packages/cli/src/docs.generated.ts | 4 +- packages/cli/src/docs/api-use-cases.md | 21 + packages/cli/src/docs/manual-api.md | 9 + .../src/components/panel-banner.tsx | 9 + .../src/components/scroll-area.tsx | 5 +- .../src/project-domain-api.server.test.ts | 355 ++- .../domain/src/project-domain-api.server.ts | 128 +- packages/domain/src/trpc/domain.ts | 73 +- packages/http-client/src/index.test.ts | 18 + packages/http-client/src/index.ts | 31 +- packages/icons/icons/activity.svg | 13 + .../icons/src/__generated__/components.tsx | 22 + packages/icons/src/__generated__/svg.ts | 2 + packages/plans/src/plan-client.server.test.ts | 12 + packages/plans/src/plan-client.server.ts | 4 +- packages/plans/src/plan-features.test.ts | 32 + packages/plans/src/plan-features.ts | 20 +- .../migration.sql | 28 + packages/project-build/package.json | 1 + packages/project-build/src/db/build.test.ts | 143 +- packages/project-build/src/db/build.ts | 187 +- packages/project-build/src/mcp.test.ts | 33 + packages/project-build/src/mcp.ts | 17 +- .../src/runtime/content-model.test.tsx | 22 + .../src/runtime/content-model.ts | 9 +- .../src/runtime/pre-publish-audit.test.tsx | 82 + .../src/runtime/pre-publish-audit.ts | 91 +- .../server-only-router-operation-metadata.ts | 98 +- .../src/builder-api/operation-docs.ts | 15 +- packages/trpc-interface/package.json | 5 + .../src/shared/deployment-contract.test.ts | 40 + .../src/shared/deployment-contract.ts | 85 + .../trpc-interface/src/shared/deployment.ts | 40 +- pnpm-lock.yaml | 6 + 90 files changed, 11422 insertions(+), 3968 deletions(-) create mode 100644 apps/builder/app/builder/features/publish/constants.ts create mode 100644 apps/builder/app/builder/features/publish/diagnostics-utils.ts rename apps/builder/app/builder/features/publish/{publish-validation-results.stories.tsx => diagnostics.stories.tsx} (79%) create mode 100644 apps/builder/app/builder/features/publish/diagnostics.test.tsx create mode 100644 apps/builder/app/builder/features/publish/diagnostics.tsx rename apps/builder/app/builder/features/publish/{domain-checkbox.test.ts => domain-checkbox.test.tsx} (51%) create mode 100644 apps/builder/app/builder/features/publish/domain-status-button.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-click.render.test.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-flow.render.test.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-progress.render.test.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-progress.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-session.render.test.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-static.test.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-status.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-test-utils.test.ts create mode 100644 apps/builder/app/builder/features/publish/publish-test-utils.ts create mode 100644 apps/builder/app/builder/features/publish/publish-ui.tsx delete mode 100644 apps/builder/app/builder/features/publish/publish-validation-results.test.tsx delete mode 100644 apps/builder/app/builder/features/publish/publish-validation-results.tsx create mode 100644 apps/builder/app/builder/features/publish/publish-validation.tsx create mode 100644 apps/builder/app/builder/features/publish/session-publishes.test.ts create mode 100644 apps/builder/app/builder/features/publish/session-publishes.ts rename apps/builder/app/shared/{array-utils.test.ts => array-utils.node.test.ts} (100%) rename apps/builder/app/shared/{collection-equality.test.ts => collection-equality.node.test.ts} (100%) rename apps/builder/app/shared/{permissions.test.ts => permissions.node.test.ts} (97%) create mode 100644 packages/cli/src/commands/mcp-publish.integration.test.ts create mode 100644 packages/icons/icons/activity.svg create mode 100644 packages/prisma-client/prisma/migrations/20260720000000_publish_attempts/migration.sql create mode 100644 packages/trpc-interface/src/shared/deployment-contract.test.ts create mode 100644 packages/trpc-interface/src/shared/deployment-contract.ts diff --git a/apps/builder/.env b/apps/builder/.env index a867bea435..9f4f6c7cb2 100644 --- a/apps/builder/.env +++ b/apps/builder/.env @@ -68,6 +68,7 @@ PLANS='[ "allowAuth": true, "allowContentMode": true, "allowStagingPublish": true, + "allowPublishLogs": true, "maxContactEmailsPerProject": 5, "maxDomainsAllowedPerUser": 200, "maxDailyPublishesPerUser": 100, diff --git a/apps/builder/app/builder/features/publish/constants.ts b/apps/builder/app/builder/features/publish/constants.ts new file mode 100644 index 0000000000..0c1c67a6d3 --- /dev/null +++ b/apps/builder/app/builder/features/publish/constants.ts @@ -0,0 +1,28 @@ +import { cssVar } from "@webstudio-is/design-system"; +import { AlertIcon, CheckCircleIcon, SpinnerIcon } from "@webstudio-is/icons"; +import type { SessionPublish } from "./session-publishes"; + +export const publishLogStatus = { + pending: { + Icon: SpinnerIcon, + color: cssVar("--foreground-warning"), + text: "Publishing started", + }, + failed: { + Icon: AlertIcon, + color: cssVar("--foreground-negative"), + text: "Publish failed", + }, + success: { + Icon: CheckCircleIcon, + color: cssVar("--foreground-positive"), + text: "Published", + }, +} satisfies Record< + SessionPublish["status"], + { + Icon: typeof AlertIcon; + color: string; + text: string; + } +>; diff --git a/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx b/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx index d0c9f4a670..38d947d65f 100644 --- a/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx +++ b/apps/builder/app/builder/features/publish/content-database-publish-warning.tsx @@ -1,7 +1,7 @@ import { Flex, Text } from "@webstudio-is/design-system"; import type { nativeClient } from "~/shared/trpc/trpc-client"; import { ContentDatabasePublishWarning } from "./content-database-publish-warning-view"; -import type { PublishValidationFinding } from "./publish-validation-results"; +import type { DiagnosticFinding } from "./diagnostics"; type ContentDatabasePublishDiagnostics = Awaited< ReturnType @@ -28,7 +28,7 @@ const invalidMdxFixes = { export const getContentDatabasePublishFindings = ( diagnostics: ContentDatabasePublishDiagnostics ) => { - const findings: PublishValidationFinding[] = diagnostics.mdxErrors.map( + const findings: DiagnosticFinding[] = diagnostics.mdxErrors.map( ({ filename, diagnostic }) => { const start = "sourceRange" in diagnostic ? diagnostic.sourceRange?.start : undefined; @@ -63,6 +63,7 @@ export const getContentDatabasePublishFindings = ( return { severity: "error" as const, title: `${filename}${location}`, + summary: message.slice(0, 160), relatedInstanceId: diagnostic.blockInstanceId, details: ( @@ -95,6 +96,8 @@ export const getContentDatabasePublishFindings = ( ...diagnostics.mdxOmissions.map((issue) => ({ severity: "warning" as const, title: `${issue.filename}: ${issue.templateName}`, + summary: + "This MDX content cannot render because its custom template is missing or ambiguous.", relatedInstanceId: issue.blockInstanceId, details: ( diff --git a/apps/builder/app/builder/features/publish/diagnostics-utils.ts b/apps/builder/app/builder/features/publish/diagnostics-utils.ts new file mode 100644 index 0000000000..d4ce058cfd --- /dev/null +++ b/apps/builder/app/builder/features/publish/diagnostics-utils.ts @@ -0,0 +1,86 @@ +import type { DiagnosticFinding } from "./diagnostics"; +import type { SessionPublish } from "./session-publishes"; +import { publishLogStatus } from "./constants"; + +export const getDiagnosticsReport = ({ + findings, + items, + canViewPublishLogs, + includeLatestPublishFindings = true, +}: { + findings: DiagnosticFinding[]; + items: SessionPublish[]; + canViewPublishLogs: boolean; + includeLatestPublishFindings?: boolean; +}) => { + const latestPublish = includeLatestPublishFindings ? items[0] : undefined; + const reportFindings = [ + ...findings, + ...(latestPublish?.findings ?? []), + ...(latestPublish?.target === "static" && latestPublish.status === "failed" + ? [ + { + severity: "error" as const, + source: "publish" as const, + buildId: latestPublish.buildId, + title: publishLogStatus.failed.text, + reportText: publishLogStatus.failed.text, + }, + ] + : []), + ...(canViewPublishLogs + ? (latestPublish?.issues?.map((issue) => ({ + severity: issue.severity, + source: "build" as const, + title: issue.message, + reportText: `${issue.severity.toUpperCase()}: ${issue.message}`, + })) ?? []) + : []), + ].filter( + (finding, index, all) => + all.findIndex( + (other) => + other.source === finding.source && + other.buildId === finding.buildId && + other.reportText === finding.reportText + ) === index + ); + const findingTabs = [ + { + value: "warnings" as const, + label: "Warnings", + findings: reportFindings.filter(({ severity }) => severity === "warning"), + }, + { + value: "errors" as const, + label: "Errors", + findings: reportFindings.filter(({ severity }) => severity === "error"), + }, + ]; + const populatedTabs = findingTabs.filter( + ({ findings }) => findings.length > 0 + ); + const orderedItems = [...items].reverse(); + const reportText = reportFindings + .map(({ reportText }) => reportText) + .join("\n\n"); + const publishText = orderedItems + .filter( + (item) => item.logState === "available" && item.logText !== undefined + ) + .map((item) => + [ + ...(item.domains.length > 0 ? item.domains : ["Static export"]), + item.logText, + ].join("\n") + ) + .join("\n\n"); + return { + findings: reportFindings, + tabs: populatedTabs, + publishes: orderedItems, + reportText, + publishText, + issuesOmitted: latestPublish?.issuesOmitted, + }; +}; diff --git a/apps/builder/app/builder/features/publish/publish-validation-results.stories.tsx b/apps/builder/app/builder/features/publish/diagnostics.stories.tsx similarity index 79% rename from apps/builder/app/builder/features/publish/publish-validation-results.stories.tsx rename to apps/builder/app/builder/features/publish/diagnostics.stories.tsx index f7857537b9..c36f7506e3 100644 --- a/apps/builder/app/builder/features/publish/publish-validation-results.stories.tsx +++ b/apps/builder/app/builder/features/publish/diagnostics.stories.tsx @@ -1,16 +1,16 @@ import { useEffect } from "react"; import { StorySection } from "@webstudio-is/design-system"; import { - PublishValidationResults, - type PublishValidationFinding, -} from "./publish-validation-results"; + PublishDiagnosticsDialog, + type DiagnosticFinding, +} from "./diagnostics"; export default { title: "Publish/Validation results", - component: PublishValidationResults, + component: PublishDiagnosticsDialog, }; -const errorsAndWarnings: PublishValidationFinding[] = [ +const errorsAndWarnings: DiagnosticFinding[] = [ { severity: "error", title: "Unable to complete publish validation", @@ -25,11 +25,7 @@ const errorsAndWarnings: PublishValidationFinding[] = [ }, ]; -const ValidationStory = ({ - findings, -}: { - findings: PublishValidationFinding[]; -}) => { +const ValidationStory = ({ findings }: { findings: DiagnosticFinding[] }) => { useEffect(() => { const open = () => { const button = Array.from(document.querySelectorAll("button")).find( @@ -48,7 +44,7 @@ const ValidationStory = ({ return ( - + ); }; diff --git a/apps/builder/app/builder/features/publish/diagnostics.test.tsx b/apps/builder/app/builder/features/publish/diagnostics.test.tsx new file mode 100644 index 0000000000..bac95a1852 --- /dev/null +++ b/apps/builder/app/builder/features/publish/diagnostics.test.tsx @@ -0,0 +1,784 @@ +import { createRoot, type Root } from "react-dom/client"; +import { act } from "react-dom/test-utils"; +import { afterEach, expect, test, vi } from "vitest"; +import { userEvent } from "@vitest/browser/context"; +import { TooltipProvider } from "@webstudio-is/design-system"; +import { + PublishDiagnosticsDialog, + PublishValidationBanner, + type DiagnosticFinding, +} from "./diagnostics"; +import type { SessionPublish } from "./session-publishes"; + +let root: Root | undefined; +let container: HTMLDivElement | undefined; +( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } +).IS_REACT_ACT_ENVIRONMENT = true; + +afterEach(() => { + act(() => root?.unmount()); + root = undefined; + container?.remove(); + container = undefined; + vi.restoreAllMocks(); +}); + +const render = ( + findings: DiagnosticFinding[], + { + canViewPublishLogs = true, + items = [], + onLoadLog, + open, + }: { + canViewPublishLogs?: boolean; + items?: SessionPublish[]; + onLoadLog?: (item: SessionPublish) => void; + open?: boolean; + } = {} +) => { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + act(() => { + root?.render( + + + + ); + }); + return container; +}; + +const createFinding = ( + severity: DiagnosticFinding["severity"], + index: number +): DiagnosticFinding => ({ + severity, + title: `${severity}-${index}`, + details: `details-${severity}-${index}`, + reportText: `${severity.toUpperCase()} report-${index}`, +}); + +const openDetails = (element: HTMLElement) => { + const button = Array.from(element.querySelectorAll("button")).find( + (candidate) => candidate.textContent === "See issues" + ); + expect(button).toBeDefined(); + act(() => button?.click()); +}; + +test("keeps audit and build findings in severity tabs, not in publish logs", async () => { + render([], { + items: [ + { + buildId: "build-separated", + target: "site", + domains: ["example.com"], + status: "failed", + findings: [createFinding("warning", 42)], + issues: [{ severity: "error", message: "build-issue-42" }], + logState: "available", + logText: "runner-output-42", + }, + ], + open: true, + }); + const tabs = Array.from( + document.body.querySelectorAll('[role="tab"]') + ); + expect(tabs).toHaveLength(3); + const publishTab = tabs.find((tab) => tab.textContent === "Publish")!; + await act(async () => userEvent.click(publishTab)); + const active = document.body.querySelector( + '[role="tabpanel"][data-state="active"]' + )!; + expect(active.textContent).toContain("runner-output-42"); + expect(active.textContent).not.toContain("warning-42"); + expect(active.textContent).not.toContain("build-issue-42"); + const warningsTab = tabs.find((tab) => tab.textContent === "Warnings")!; + await act(async () => userEvent.click(warningsTab)); + expect(document.body.textContent).toContain("warning-42"); + const errorsTab = tabs.find((tab) => tab.textContent === "Errors")!; + await act(async () => userEvent.click(errorsTab)); + expect(document.body.textContent).toContain("build-issue-42"); +}); + +test.each(["findings", "details", "publish"] as const)( + "scrolls overflowing %s with the native scroll container", + async (view) => { + const content =
; + render( + view === "publish" + ? [] + : [ + { + severity: "error", + title: view === "details" ? "finding" : content, + details: content, + reportText: "report", + }, + ], + { + 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( + (button) => button.textContent === "finding" + ); + await act(async () => userEvent.click(finding!)); + } + const contentElement = document.body.querySelector( + view === "publish" ? "pre" : "[data-overflow-content]" + ); + if (view === "details") { + expect(getComputedStyle(contentElement!.parentElement!).userSelect).toBe( + "text" + ); + } + let scrollContainer = contentElement?.parentElement; + while ( + scrollContainer && + getComputedStyle(scrollContainer).overflowY !== "auto" + ) { + scrollContainer = scrollContainer.parentElement; + } + expect(scrollContainer).toBeTruthy(); + expect(scrollContainer!.clientHeight).toBeGreaterThan(0); + expect(scrollContainer!.scrollHeight).toBeGreaterThan( + scrollContainer!.clientHeight + ); + scrollContainer!.scrollTop = 100; + expect(scrollContainer!.scrollTop).toBe(100); + } +); + +test("renders no publish summary when there are no findings", () => { + expect(render([]).textContent).toBe(""); +}); + +test("shows a clean validation result without offering an empty issues dialog", () => { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + act(() => { + root?.render( + + ); + }); + + expect(container.querySelector('[role="status"]')).not.toBeNull(); + expect(container.querySelector("button")).toBeNull(); +}); + +test("shows all mixed findings, counted tabs, selectable text, and copy-all", async () => { + const findings = [ + ...Array.from({ length: 6 }, (_, index) => createFinding("error", index)), + ...Array.from({ length: 11 }, (_, index) => + createFinding("warning", index) + ), + ]; + const writeText = vi.fn(async (_text: string) => {}); + Object.defineProperty(navigator, "clipboard", { + configurable: true, + value: { writeText }, + }); + + const element = render(findings); + expect(element.textContent).toContain("6 errors · 11 warnings"); + openDetails(element); + + expect(document.body.textContent).toContain("Diagnostics"); + expect(document.body.textContent).toContain("Errors"); + expect(document.body.textContent).toContain("Warnings"); + expect(document.body.textContent).toContain("error-5"); + expect(document.body.textContent).not.toContain("warning-0"); + expect(document.body.querySelectorAll('[role="tab"]')).toHaveLength(2); + expect( + getComputedStyle(document.body.querySelector('[role="dialog"]')!).resize + ).toBe("both"); + expect(document.body.querySelector('[draggable="true"]')).not.toBeNull(); + const firstFinding = Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent === "error-0"); + expect(firstFinding).toBeDefined(); + await act(async () => userEvent.click(firstFinding as HTMLElement)); + const selectableText = Array.from(document.body.querySelectorAll("*")).find( + (candidate) => + candidate.textContent === "details-error-0" && + getComputedStyle(candidate).userSelect === "text" + ); + expect(selectableText).toBeDefined(); + const backButton = Array.from(document.body.querySelectorAll("button")).find( + (button) => button.textContent === "Back" + ); + await act(async () => userEvent.click(backButton as HTMLElement)); + + const warningTab = Array.from( + document.body.querySelectorAll('[role="tab"]') + ).find((tab) => tab.textContent === "Warnings"); + await act(async () => userEvent.click(warningTab as HTMLElement)); + expect(document.body.textContent).toContain("warning-10"); + expect(document.body.textContent).not.toContain("error-0"); + const warningFinding = Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent === "warning-0"); + await act(async () => userEvent.click(warningFinding as HTMLElement)); + const warningBack = Array.from(document.body.querySelectorAll("button")).find( + (button) => button.textContent === "Back" + ); + await act(async () => userEvent.click(warningBack as HTMLElement)); + expect( + Array.from(document.body.querySelectorAll('[role="tab"]')) + .find((tab) => tab.textContent === "Warnings") + ?.getAttribute("aria-selected") + ).toBe("true"); + + const copyButton = document.body.querySelector( + 'button[aria-label="Copy all reports"]' + ); + expect(copyButton).not.toBeNull(); + await act(async () => { + copyButton?.click(); + }); + expect(writeText).toHaveBeenCalledOnce(); + const copiedReport = writeText.mock.calls[0][0]; + expect(copiedReport).toContain("ERROR report-5"); + expect(copiedReport).toContain("WARNING report-10"); +}); + +test.each(["error", "warning"] as const)( + "shows only the populated tab in the %s-only state", + (severity) => { + const element = render([createFinding(severity, 0)]); + openDetails(element); + expect( + Array.from(document.body.querySelectorAll('[role="tab"]')).map( + (tab) => tab.textContent + ) + ).toEqual([severity === "error" ? "Errors" : "Warnings"]); + } +); + +test("Free shows the actual short error without details, navigation, or report copy", () => { + const element = render( + [ + { + severity: "error", + title: "article.mdx:2:3", + summary: "Invalid MDX element nesting", + details: "Private long diagnostic context", + link: , + reportText: "Private long diagnostic context", + }, + ], + { canViewPublishLogs: false } + ); + openDetails(element); + expect(document.body.textContent).toContain("Invalid MDX element nesting"); + expect(document.body.textContent).not.toContain("article.mdx"); + expect(document.body.textContent).not.toContain( + "Private long diagnostic context" + ); + expect(document.body.textContent).not.toContain("Show element"); + expect( + document.body.querySelector('[aria-label="Copy all reports"]') + ).toBeNull(); +}); + +test("Free hides log-derived issues, stage, and code", async () => { + 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"]') + ).find((tab) => tab.textContent === "Publish"); + await act(async () => userEvent.click(publishTab as HTMLElement)); + expect(document.body.textContent).toContain("Publish failed"); + expect(document.body.textContent).not.toContain("private-code"); + expect(document.body.textContent).not.toContain("private-stage"); + expect(document.body.textContent).not.toContain("private-log-issue"); +}); + +test("loads a completed publish when Publish opens and shows its log inline", async () => { + const item: SessionPublish = { + buildId: "build-1", + logHandle: "log-handle-1", + target: "site", + domains: ["example.com"], + findings: [], + status: "failed", + }; + const onLoadLog = vi.fn(); + const element = render([createFinding("warning", 0)], { + items: [item], + onLoadLog, + }); + openDetails(element); + expect(onLoadLog).not.toHaveBeenCalled(); + const publishTab = Array.from( + document.body.querySelectorAll('[role="tab"]') + ).find((tab) => tab.textContent === "Publish"); + await act(async () => userEvent.click(publishTab as HTMLElement)); + expect(onLoadLog).toHaveBeenCalledWith(item); + + item.logState = "available"; + item.logText = "Unstructured runner output"; + act(() => { + root?.render( + + + + ); + }); + expect(document.body.textContent).toContain("Unstructured runner output"); + expect(document.body.textContent).not.toContain("View detailed report"); +}); + +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)], { + items: [ + { + buildId: "build-1", + target: "site", + domains: ["example.com"], + findings: [], + status: "failed", + }, + ], + onLoadLog, + }); + openDetails(element); + const publishTab = Array.from( + document.body.querySelectorAll('[role="tab"]') + ).find((tab) => tab.textContent === "Publish"); + await act(async () => userEvent.click(publishTab as HTMLElement)); + expect(onLoadLog).not.toHaveBeenCalled(); + expect(document.body.textContent).toContain("Publish logs are unavailable."); +}); + +test("lists each publish domain and copies the full loaded log", async () => { + const writeText = vi.fn(async (_text: string) => {}); + Object.defineProperty(navigator, "clipboard", { + configurable: true, + value: { writeText }, + }); + render([], { + items: [ + { + buildId: "build-1", + target: "site", + domains: ["first.example", "second.example"], + findings: [], + status: "failed", + logState: "available", + logText: "First complete runner log", + }, + { + buildId: "build-2", + target: "site", + domains: ["third.example"], + findings: [], + status: "success", + logState: "available", + logText: "Second complete runner log", + }, + ], + open: true, + }); + expect(document.body.textContent).toContain("first.example"); + expect(document.body.textContent).toContain("second.example"); + expect(document.body.textContent).toContain("third.example"); + expect(document.body.textContent).toContain("first.example, second.example"); + const copyButton = document.body.querySelector( + 'button[aria-label="Copy all reports"]' + ); + expect(copyButton).not.toBeNull(); + await act(async () => userEvent.click(copyButton!)); + expect(writeText).toHaveBeenCalledOnce(); + const copied = writeText.mock.calls[0][0]; + expect(copied).toContain("First complete runner log"); + expect(copied).toContain("Second complete runner log"); + expect(copied).toContain("first.example"); + expect(copied).toContain("second.example"); + expect(copied).toContain("third.example"); +}); + +test("collapses each complete publish and copies its full log from the header", async () => { + const writeText = vi.fn(async (_text: string) => {}); + Object.defineProperty(navigator, "clipboard", { + configurable: true, + value: { writeText }, + }); + render([], { + items: [ + { + buildId: "build-1", + target: "site", + domains: ["first.example"], + findings: [], + status: "failed", + logState: "available", + logText: "Complete first publish log", + }, + { + buildId: "build-2", + target: "site", + domains: ["second.example"], + findings: [], + status: "success", + logState: "available", + logText: "Complete second publish log", + }, + ], + open: true, + }); + const triggers = Array.from( + document.body.querySelectorAll("button[aria-labelledby]") + ); + expect(triggers).toHaveLength(2); + expect(triggers[0]?.getAttribute("aria-expanded")).toBe("false"); + expect(triggers[1]?.getAttribute("aria-expanded")).toBe("true"); + expect(document.body.textContent).toContain("Complete first publish log"); + expect(document.body.textContent).not.toContain( + "Complete second publish log" + ); + await act(async () => userEvent.click(triggers[0]!)); + expect(document.body.textContent).toContain("Complete second publish log"); + const copyButtons = document.body.querySelectorAll( + 'button[aria-label="Copy log"]' + ); + expect(copyButtons).toHaveLength(2); + await act(async () => userEvent.click(copyButtons[0]!)); + expect(writeText).toHaveBeenCalledWith("Complete second publish log"); + expect(triggers[0]?.getAttribute("aria-expanded")).toBe("true"); + const keyboardCopy = document.body.querySelector( + 'button[aria-label="Copy log"]' + )!; + expect(keyboardCopy.parentElement?.closest("button")).toBeNull(); + act(() => keyboardCopy.focus()); + await act(async () => userEvent.keyboard("{Enter}")); + expect(writeText).toHaveBeenCalledTimes(2); + expect(triggers[0]?.getAttribute("aria-expanded")).toBe("true"); +}); + +test("can maximize Diagnostics and aligns publish content with its title", async () => { + render([], { + items: [ + { + buildId: "build-1", + target: "site", + domains: ["example.com"], + findings: [], + status: "success", + logState: "available", + logText: "Build output", + }, + ], + open: true, + }); + + const dialog = document.body.querySelector('[role="dialog"]'); + const titleButton = document.body.querySelector( + "button[aria-labelledby]" + ); + const title = document.getElementById( + titleButton?.getAttribute("aria-labelledby") ?? "" + ); + const log = document.body.querySelector("pre"); + expect(dialog).not.toBeNull(); + expect(title).not.toBeNull(); + expect(title?.tagName).toBe("SPAN"); + expect(log).not.toBeNull(); + expect(getComputedStyle(log!).fontFamily).toContain("Roboto Mono"); + expect( + Math.abs( + title!.getBoundingClientRect().left - log!.getBoundingClientRect().left + ) + ).toBeLessThan(1); + + const width = dialog!.getBoundingClientRect().width; + const maximize = document.body.querySelector( + 'button[aria-label="Expand"]' + ); + expect(maximize).not.toBeNull(); + await act(async () => userEvent.click(maximize!)); + expect(dialog!.getBoundingClientRect().width).not.toBe(width); + await act(async () => userEvent.click(maximize!)); + expect(dialog!.getBoundingClientRect().width).toBe(width); +}); + +test("publish failure is plain text and links to the Publish tab", async () => { + render( + [ + { + severity: "error", + source: "publish", + title: "Build failed before deployment", + buildId: "build-1", + summary: "Build failed before deployment", + reportText: "Build failed before deployment", + }, + ], + { + 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"); + expect( + Array.from(document.body.querySelectorAll("button")).some( + (button) => button.textContent === "Build failed before deployment" + ) + ).toBe(false); + const publishLink = Array.from(document.body.querySelectorAll("button")).find( + (button) => + button.getAttribute("role") !== "tab" && + button.textContent === "show logs" + ); + expect(publishLink).toBeDefined(); + expect(publishLink?.parentElement?.textContent).toContain( + "Build failed before deployment" + ); + await act(async () => userEvent.click(publishLink!)); + expect( + Array.from(document.body.querySelectorAll('[role="tab"]')) + .find((tab) => tab.textContent === "Publish") + ?.getAttribute("aria-selected") + ).toBe("true"); +}); + +test("Free publish failures link to a Publish upgrade banner without exposing logs", async () => { + render( + [ + { + severity: "error", + source: "publish", + title: "Publish failed", + buildId: "build-1", + reportText: "Publish failed", + }, + ], + { + 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( + (button) => button.textContent === "show logs" + ); + expect(link).toBeDefined(); + await act(async () => userEvent.click(link!)); + expect( + document.body.querySelector('[role="tab"][aria-selected="true"]') + ?.textContent + ).toBe("Publish"); + expect( + document.body.querySelector( + '[role="tabpanel"][data-state="active"] [role="note"]' + ) + ).not.toBeNull(); + expect(document.body.textContent).not.toContain("private runner output"); +}); + +test("lists publishes oldest first and opens the newest entry", () => { + render([], { + items: [ + { + buildId: "new", + target: "site", + domains: ["new.example"], + findings: [], + status: "success", + }, + { + buildId: "old", + target: "site", + domains: ["old.example"], + findings: [], + status: "failed", + }, + ], + open: true, + }); + const triggers = Array.from( + document.body.querySelectorAll("button[aria-labelledby]") + ); + const labels = triggers.map( + (button) => + document.getElementById(button.getAttribute("aria-labelledby") ?? "") + ?.textContent + ); + expect(labels).toEqual(["old.example", "new.example"]); + expect(triggers[0]?.getAttribute("aria-expanded")).toBe("false"); + expect(triggers[1]?.getAttribute("aria-expanded")).toBe("true"); +}); + +test("pre-dispatch failure has no link to an absent Publish tab", () => { + render( + [ + { + severity: "error", + source: "publish", + title: "Publish request failed", + reportText: "Publish request failed", + }, + ], + { open: true } + ); + expect(document.body.textContent).toContain("Publish request failed"); + expect(document.body.textContent).not.toContain("Audit"); + expect( + Array.from(document.body.querySelectorAll("button")).some( + (button) => button.textContent === "Publish request failed" + ) + ).toBe(false); + expect(document.body.querySelector('[role="tab"]')?.textContent).toBe( + "Errors" + ); + expect( + Array.from(document.body.querySelectorAll("button")).some( + (button) => button.textContent === "Publish" + ) + ).toBe(false); +}); + +test.each([true, false])( + "pre-dispatch failure does not link an older publish (paid: %s)", + (paid) => { + render( + [ + { + severity: "error", + source: "publish", + title: "new-request-rejection", + reportText: "new-request-rejection", + }, + ], + { + 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"]') + ?.textContent + ).toBe("Errors"); + expect( + Array.from(document.body.querySelectorAll("button")).some( + (button) => button.textContent === "show logs" + ) + ).toBe(false); + } +); + +test("Free audit summaries do not expose long cached details", () => { + const longSummary = `Short reason ${"private context ".repeat(30)}`; + const element = render( + [ + { + severity: "error", + title: longSummary, + summary: longSummary, + reportText: longSummary, + }, + ], + { canViewPublishLogs: false } + ); + openDetails(element); + expect(document.body.textContent).toContain("Short reason"); + expect(document.body.textContent).not.toContain(longSummary); +}); + +test("Show element closes the diagnostics dialog on ordinary navigation", async () => { + const element = render([ + { + severity: "error", + title: "Invalid element", + link: Show element, + reportText: "Invalid element", + }, + ]); + openDetails(element); + const finding = Array.from(document.body.querySelectorAll("button")).find( + (button) => button.textContent === "Invalid element" + ); + await act(async () => userEvent.click(finding as HTMLElement)); + const link = + document.body.querySelector('a[href="#element"]'); + expect(link).not.toBeNull(); + await act(async () => userEvent.click(link as HTMLElement)); + expect(document.body.querySelector('[role="dialog"]')).toBeNull(); +}); diff --git a/apps/builder/app/builder/features/publish/diagnostics.tsx b/apps/builder/app/builder/features/publish/diagnostics.tsx new file mode 100644 index 0000000000..a77030ba86 --- /dev/null +++ b/apps/builder/app/builder/features/publish/diagnostics.tsx @@ -0,0 +1,517 @@ +import { getDiagnosticsReport } from "./diagnostics-utils"; +import { Fragment, useEffect, useState, type ReactNode } from "react"; +import { + Button, + Collapsible, + Dialog, + DialogClose, + DialogContent, + DialogMaximize, + DialogTitle, + DialogTitleActions, + Flex, + IconButton, + Link, + PanelBanner, + PanelContent, + PanelTabs, + PanelTabsContent, + PanelTabsList, + PanelTabsTrigger, + ScrollAreaNative, + SectionTitle, + Separator, + Text, + theme, +} from "@webstudio-is/design-system"; +import { CopyIcon } from "@webstudio-is/icons"; +import { CopyToClipboard } from "~/shared/copy-to-clipboard"; +import type { SessionPublish } from "./session-publishes"; +import { getPublishDuration } from "./session-publishes"; +import { publishLogStatus } from "./constants"; + +export type DiagnosticFinding = { + severity: "error" | "warning"; + source?: "audit" | "build" | "publish"; + title: ReactNode; + summary?: string; + details?: ReactNode; + link?: ReactNode; + relatedInstanceId?: string; + reportText: string; + buildId?: string; +}; + +const shortFinding = (finding: DiagnosticFinding) => + ( + finding.summary ?? (typeof finding.title === "string" ? finding.title : "") + ).slice(0, 160); + +export const PublishValidationBanner = ({ + findings, + passed = false, + onOpen, +}: { + findings: DiagnosticFinding[]; + passed?: boolean; + onOpen: () => void; +}) => { + const errors = findings.filter(({ severity }) => severity === "error"); + const warnings = findings.filter(({ severity }) => severity === "warning"); + if (findings.length === 0) { + return passed ? ( + + Validation passed. Ready to publish. + + ) : null; + } + const countLabel = [ + errors.length > 0 && + `${errors.length} ${errors.length === 1 ? "error" : "errors"}`, + warnings.length > 0 && + `${warnings.length} ${warnings.length === 1 ? "warning" : "warnings"}`, + ] + .filter(Boolean) + .join(" · "); + return ( + 0 ? "error" : "warning"}> + + + Publish check found {countLabel}.{" "} + {errors.length > 0 && "Fix the errors before publishing."} + + + + + ); +}; + +const FindingList = ({ + findings, + canViewPublishLogs, + onSelect, + onOpenPublish, + issuesOmitted = 0, + publishBuildIds, +}: { + findings: DiagnosticFinding[]; + canViewPublishLogs: boolean; + onSelect: (finding: DiagnosticFinding) => void; + onOpenPublish?: () => void; + issuesOmitted?: number; + publishBuildIds: string[]; +}) => ( + + + {findings.map((finding, index) => ( + + + {finding.source !== "publish" && ( + + {finding.source === "build" ? "Build" : "Audit"} + + )} + {finding.source === "publish" ? ( + + {canViewPublishLogs ? finding.title : shortFinding(finding)} + {onOpenPublish !== undefined && + finding.buildId !== undefined && + publishBuildIds.includes(finding.buildId) && ( + <> + {" "} + + show logs + + + )} + + ) : canViewPublishLogs ? ( + + ) : ( + + {shortFinding(finding)} + + )} + + {index < findings.length - 1 && } + + ))} + {canViewPublishLogs && issuesOmitted > 0 && ( + {issuesOmitted} more issues not shown. + )} + + +); + +const FindingDetails = ({ + finding, + onBack, + onNavigate, +}: { + finding: DiagnosticFinding; + onBack: () => void; + onNavigate: () => void; +}) => ( + + + + {finding.title} + + {finding.details !== undefined && ( + + {finding.details} + + )} +
{ + if ( + event.button !== 0 || + event.metaKey || + event.ctrlKey || + event.shiftKey || + event.altKey + ) { + return; + } + onNavigate(); + }} + > + {finding.link} +
+
+); + +const SessionPublishEntry = ({ + item, + defaultOpen, + canViewPublishLogs, +}: { + item: SessionPublish; + defaultOpen: boolean; + canViewPublishLogs: boolean; +}) => { + const duration = getPublishDuration(item); + return ( + + + + } + suffix={ + canViewPublishLogs && + item.logState === "available" && + item.logText !== undefined && ( + + event.stopPropagation()} + > + + + + ) + } + > + + {item.domains.length > 0 + ? item.domains.join(", ") + : "Static export"} + + + + + + {publishLogStatus[item.status].text} + {canViewPublishLogs && item.startedAt !== undefined && ( + Started: {new Date(item.startedAt).toLocaleString()} + )} + {canViewPublishLogs && duration !== undefined && ( + Duration: {duration}s + )} + {canViewPublishLogs && + item.status === "failed" && + (item.failedStage !== undefined || item.code !== undefined) && ( + + {[item.failedStage, item.code?.replaceAll("_", " ")] + .filter(Boolean) + .join(" · ")} + + )} + {canViewPublishLogs && + item.status !== "pending" && + (item.logState === "available" ? ( + + {item.logText} + + ) : ( + + {item.logHandle === undefined || + item.logState === "unavailable" + ? "Publish logs are unavailable." + : "Loading logs…"} + + ))} + + + + + + ); +}; + +const SessionPublishList = ({ + items, + canViewPublishLogs, + onLoadLog, +}: { + items: SessionPublish[]; + canViewPublishLogs: boolean; + onLoadLog?: (item: SessionPublish) => void; +}) => { + useEffect(() => { + if (!canViewPublishLogs) { + return; + } + for (const item of items) { + if ( + item.status !== "pending" && + item.logHandle !== undefined && + item.logState === undefined + ) { + onLoadLog?.(item); + } + } + }, [canViewPublishLogs, items, onLoadLog]); + return ( + + + {!canViewPublishLogs && ( + + Upgrade to Pro to view publish logs. + + )} + {items.length === 0 && ( + No publishes in this session. + )} + {items.map((item, index) => ( + + ))} + + + ); +}; + +export const PublishDiagnosticsDialog = ({ + findings, + open, + onOpenChange, + target, + initialTab, + items = [], + canViewPublishLogs = true, + includeLatestPublishFindings = true, + onLoadLog, +}: { + findings: DiagnosticFinding[]; + open?: boolean; + onOpenChange?: (open: boolean) => void; + target?: string; + initialTab?: "warnings" | "errors" | "publish"; + items?: SessionPublish[]; + canViewPublishLogs?: boolean; + includeLatestPublishFindings?: boolean; + onLoadLog?: (item: SessionPublish) => void; +}) => { + const [internalOpen, setInternalOpen] = useState(false); + const [selectedFinding, setSelectedFinding] = useState(); + const isOpen = open ?? internalOpen; + const setIsOpen = onOpenChange ?? setInternalOpen; + + const { + findings: reportFindings, + tabs, + publishes: orderedItems, + reportText, + publishText, + issuesOmitted, + } = getDiagnosticsReport({ + findings, + items, + canViewPublishLogs, + includeLatestPublishFindings, + }); + const defaultTab = initialTab ?? tabs.at(-1)?.value ?? "publish"; + const [tab, setTab] = useState(defaultTab); + + const activeTab = + (tab === "publish" && items.length > 0) || + tabs.some(({ value }) => value === tab) + ? tab + : (tabs.at(-1)?.value ?? "publish"); + + const copyText = activeTab === "publish" ? publishText : reportText; + + useEffect(() => { + setSelectedFinding(undefined); + setTab(defaultTab); + }, [target, isOpen, defaultTab]); + + useEffect(() => { + if (canViewPublishLogs === false) { + setSelectedFinding(undefined); + } + }, [canViewPublishLogs]); + + if (open === undefined && reportFindings.length === 0 && items.length === 0) { + return null; + } + + return ( + <> + {open === undefined && ( + setIsOpen(true)} + /> + )} + + + + {canViewPublishLogs && copyText.length > 0 && ( + + event.stopPropagation()} + > + + + + )} + + + + } + > + Diagnostics + + {selectedFinding !== undefined && canViewPublishLogs ? ( + setSelectedFinding(undefined)} + onNavigate={() => setIsOpen(false)} + /> + ) : ( + setTab(value as typeof tab)} + css={{ flex: 1, minHeight: 0, overflow: "hidden" }} + > + + {tabs.map(({ value, label }) => ( + + {label} + + ))} + {items.length > 0 && ( + Publish + )} + + {tabs.map(({ value, findings }) => ( + + buildId)} + onSelect={setSelectedFinding} + onOpenPublish={ + items.length > 0 ? () => setTab("publish") : undefined + } + /> + + ))} + + + + + )} + + + + ); +}; diff --git a/apps/builder/app/builder/features/publish/domain-checkbox.test.ts b/apps/builder/app/builder/features/publish/domain-checkbox.test.tsx similarity index 51% rename from apps/builder/app/builder/features/publish/domain-checkbox.test.ts rename to apps/builder/app/builder/features/publish/domain-checkbox.test.tsx index 580217e8ca..ef2f30ee71 100644 --- a/apps/builder/app/builder/features/publish/domain-checkbox.test.ts +++ b/apps/builder/app/builder/features/publish/domain-checkbox.test.tsx @@ -1,8 +1,86 @@ -import { describe, test, expect } from "vitest"; +import { afterAll, afterEach, describe, test, expect } from "vitest"; +import { createRoot, type Root } from "react-dom/client"; +import { act } from "react-dom/test-utils"; +import { TooltipProvider } from "@webstudio-is/design-system"; +import type { Project } from "@webstudio-is/project"; +import { $project } from "~/shared/sync/data-stores"; +import { $authPermit, $planFeatures } from "~/shared/nano-states"; +import { DomainCheckbox, domainToPublishName } from "./domain-checkbox"; import { __testing__ } from "./domain-checkbox"; const { isCustomDomainPublishRestricted } = __testing__; +const initialPlan = $planFeatures.get(); +const initialAuthPermit = $authPermit.get(); +let root: Root | undefined; +let container: HTMLDivElement | undefined; + +const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }; +const originalActEnvironment = reactEnvironment.IS_REACT_ACT_ENVIRONMENT; +reactEnvironment.IS_REACT_ACT_ENVIRONMENT = true; + +afterAll(() => { + reactEnvironment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment; +}); + +afterEach(() => { + act(() => root?.unmount()); + root = undefined; + container?.remove(); + container = undefined; + $project.set(undefined); + $planFeatures.set(initialPlan); + $authPermit.set(initialAuthPermit); +}); + +const renderCheckbox = () => { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + act(() => + root?.render( + +
+ + +
+ ) + ); + return { + checkbox: container.querySelector('[role="checkbox"]')!, + form: container.querySelector("form")!, + }; +}; + +test("removes a selected custom domain from the form when publishing becomes restricted", async () => { + $project.set({ + id: "project-1", + domainsVirtual: [ + { domain: "custom.example", status: "ACTIVE", verified: true }, + ], + } as Project); + $planFeatures.set({ ...initialPlan, allowStagingPublish: true }); + $authPermit.set("own"); + const { checkbox, form } = renderCheckbox(); + expect(checkbox).toBeEnabled(); + expect(checkbox.getAttribute("aria-checked")).toBe("true"); + expect(new FormData(form).getAll(domainToPublishName)).toEqual([ + "custom.example", + ]); + + await act(async () => $authPermit.set("build")); + const restrictedCheckbox = + form.querySelector('[role="checkbox"]')!; + expect(restrictedCheckbox).toBeDisabled(); + expect(restrictedCheckbox.getAttribute("aria-checked")).toBe("false"); + expect(new FormData(form).getAll(domainToPublishName)).toEqual([]); +}); + describe("isCustomDomainPublishRestricted", () => { describe("free plan (allowStagingPublish=false), no builder role", () => { test("custom domain → restricted", () => { diff --git a/apps/builder/app/builder/features/publish/domain-status-button.tsx b/apps/builder/app/builder/features/publish/domain-status-button.tsx new file mode 100644 index 0000000000..857adf9903 --- /dev/null +++ b/apps/builder/app/builder/features/publish/domain-status-button.tsx @@ -0,0 +1,42 @@ +import type { ReactNode } from "react"; +import { IconButton, Tooltip } from "@webstudio-is/design-system"; +import type { AlertIcon } from "@webstudio-is/icons"; +import { publishLogStatus } from "./constants"; +import type { SessionPublish } from "./session-publishes"; + +export const DomainStatusButton = ({ + domain, + buildId, + latestPublish, + fallback, + onOpenReport, +}: { + domain: string; + buildId?: string; + latestPublish?: Pick; + fallback: { Icon: typeof AlertIcon; color: string; text: ReactNode }; + onOpenReport?: () => void; +}) => { + const currentPublish = + latestPublish?.buildId === buildId ? latestPublish : undefined; + const { Icon, color, text } = + currentPublish === undefined + ? fallback + : publishLogStatus[currentPublish.status]; + return ( + + { + event.preventDefault(); + event.stopPropagation(); + onOpenReport?.(); + }} + > + + + + ); +}; diff --git a/apps/builder/app/builder/features/publish/domains.test.tsx b/apps/builder/app/builder/features/publish/domains.test.tsx index b4d29a9fd8..d7fa0e9084 100644 --- a/apps/builder/app/builder/features/publish/domains.test.tsx +++ b/apps/builder/app/builder/features/publish/domains.test.tsx @@ -1,8 +1,10 @@ import { act } from "react-dom/test-utils"; import { createRoot, type Root } from "react-dom/client"; -import { afterEach, expect, test } from "vitest"; +import { afterEach, expect, test, vi } from "vitest"; import { TooltipProvider } from "@webstudio-is/design-system"; -import { __testing__, PENDING_TIMEOUT, type Domain } from "./domains"; +import { __testing__, type Domain } from "./domains"; +import { PENDING_TIMEOUT } from "./publish-status"; +import type { SessionPublish } from "./session-publishes"; const { StatusIcon } = __testing__; let root: Root | undefined; @@ -21,8 +23,19 @@ afterEach(() => { const renderStatus = ( publishStatus: "PENDING" | "PUBLISHED" | "FAILED" | undefined, - age = 0, - isLoading = false + { + age = 0, + isLoading = false, + latestPublish, + onOpenReport, + onSectionClick, + }: { + age?: number; + isLoading?: boolean; + latestPublish?: SessionPublish; + onOpenReport?: (domain: string) => void; + onSectionClick?: () => void; + } = {} ) => { if (container === undefined) { container = document.createElement("div"); @@ -34,21 +47,30 @@ const renderStatus = ( root = createRoot(container); } const projectDomain = { + domain: "example.com", status: "ACTIVE", verified: true, latestBuildVirtual: publishStatus === undefined ? null : { + buildId: "current-build", publishStatus, createdAt: new Date(Date.now() - age).toISOString(), }, } as Domain; act(() => root?.render( - - - +
+ + + +
) ); const icon = container.querySelector("svg"); @@ -69,8 +91,10 @@ test.each([ test("keeps status loading neutral and expired publishing red", () => { expect(renderStatus("PENDING")).toBe("rgb(200, 160, 0)"); - expect(renderStatus("PENDING", 0, true)).toBe("rgb(100, 100, 100)"); - expect(renderStatus("PENDING", PENDING_TIMEOUT + 1000)).toBe( + expect(renderStatus("PENDING", { isLoading: true })).toBe( + "rgb(100, 100, 100)" + ); + expect(renderStatus("PENDING", { age: PENDING_TIMEOUT + 1000 })).toBe( "rgb(200, 0, 0)" ); }); @@ -78,3 +102,54 @@ test("keeps status loading neutral and expired publishing red", () => { test("does not show success for a domain that has never been published", () => { expect(renderStatus(undefined)).toBe("rgb(100, 100, 100)"); }); + +test.each([ + ["pending", "rgb(200, 160, 0)"], + ["failed", "rgb(200, 0, 0)"], + ["success", "rgb(0, 160, 0)"], +] as const)( + "uses the matching %s session log instead of the persisted status", + (status, color) => { + expect( + renderStatus(status === "failed" ? "PUBLISHED" : "PENDING", { + age: PENDING_TIMEOUT + 1000, + latestPublish: { + buildId: "current-build", + target: "site", + domains: ["example.com"], + findings: [], + status, + }, + }) + ).toBe(color); + } +); + +test("ignores a log for a different domain build", () => { + expect( + renderStatus("PUBLISHED", { + latestPublish: { + buildId: "old-build", + target: "site", + domains: ["example.com"], + findings: [], + status: "failed", + }, + }) + ).toBe("rgb(0, 160, 0)"); +}); + +test("opening a domain report does not toggle the surrounding section", () => { + const onOpenReport = vi.fn(); + const onSectionClick = vi.fn(); + renderStatus("PUBLISHED", { onOpenReport, onSectionClick }); + const event = new MouseEvent("click", { bubbles: true, cancelable: true }); + act(() => + container! + .querySelector('button[aria-label="Publish log: example.com"]') + ?.dispatchEvent(event) + ); + expect(onOpenReport).toHaveBeenCalledExactlyOnceWith("example.com"); + expect(onSectionClick).not.toHaveBeenCalled(); + expect(event.defaultPrevented).toBe(true); +}); diff --git a/apps/builder/app/builder/features/publish/domains.tsx b/apps/builder/app/builder/features/publish/domains.tsx index b7610b773b..55c3e8186b 100644 --- a/apps/builder/app/builder/features/publish/domains.tsx +++ b/apps/builder/app/builder/features/publish/domains.tsx @@ -18,11 +18,9 @@ import { import type { Project } from "@webstudio-is/project"; import { AlertIcon, - CheckCircleIcon, CopyIcon, HelpIcon, InfoCircleIcon, - SpinnerIcon, } from "@webstudio-is/icons"; import { CollapsibleDomainSection } from "./collapsible-domain-section"; import { @@ -42,9 +40,11 @@ import { extractCname } from "./cname"; import { useEffectEvent } from "~/shared/hook-utils/effect-event"; import { DomainCheckbox } from "./domain-checkbox"; import { CopyToClipboard } from "~/shared/copy-to-clipboard"; -import { RelativeTime } from "~/builder/shared/relative-time"; +import { getPublishStatusDisplay } from "./publish-status"; import { $currentSystem } from "~/shared/system"; import { getPublishUrl } from "./publish-url"; +import type { SessionPublish } from "./session-publishes"; +import { DomainStatusButton } from "./domain-status-button"; export type Domain = Project["domainsVirtual"][number]; @@ -61,54 +61,6 @@ export const getStatus = (projectDomain: Domain) => ? (`VERIFIED_${projectDomain.status}` as const) : `UNVERIFIED`; -export const PENDING_TIMEOUT = - process.env.NODE_ENV === "production" ? 60 * 3 * 1000 : 35000; - -export const getPublishStatusAndText = ({ - createdAt, - publishStatus, -}: Pick< - NonNullable, - "createdAt" | "publishStatus" ->) => { - let status = publishStatus; - - const delta = Date.now() - new Date(createdAt).getTime(); - // Assume build failed after 3 minutes - - if (publishStatus === "PENDING" && delta > PENDING_TIMEOUT) { - status = "FAILED"; - } - - const textStart = - status === "PUBLISHED" - ? "Published" - : status === "FAILED" - ? "Publish failed" - : "Publishing started"; - - const statusText = ( - <> - {textStart} - - ); - - const color = - status === "PUBLISHED" - ? cssVar("--foreground-positive") - : status === "FAILED" - ? cssVar("--foreground-negative") - : cssVar("--foreground-warning"); - const Icon = - status === "PUBLISHED" - ? CheckCircleIcon - : status === "FAILED" - ? AlertIcon - : SpinnerIcon; - - return { statusText, status, color, Icon }; -}; - const getStatusText = (props: { projectDomain: Domain; isLoading: boolean; @@ -136,11 +88,11 @@ const getStatusText = (props: { text = "Status: Active, not published"; if (props.projectDomain.latestBuildVirtual !== null) { - const publishText = getPublishStatusAndText( + const publishText = getPublishStatusDisplay( props.projectDomain.latestBuildVirtual ); - text = publishText.statusText; + text = publishText.statusContent; color = publishText.color; Icon = publishText.Icon; } @@ -163,39 +115,39 @@ const getStatusText = (props: { }; }; -const StatusIcon = (props: { projectDomain: Domain; isLoading: boolean }) => { - const { color, Icon, text } = getStatusText(props); - +const StatusIcon = (props: { + projectDomain: Domain; + isLoading: boolean; + latestPublish?: SessionPublish; + onOpenReport?: (domain: string) => void; +}) => { + const fallback = getStatusText(props); return ( - - - - - + props.onOpenReport?.(props.projectDomain.domain)} + /> ); }; - const DomainItem = ({ initiallyOpen, projectDomain, project, refresh, validatedDomains, + onOpenReport, + latestPublish, }: { initiallyOpen: boolean; projectDomain: Domain; project: Project; refresh: () => Promise; validatedDomains?: readonly string[]; + onOpenReport?: (domain: string) => void; + latestPublish?: SessionPublish; }) => { const timeSinceLastUpdateMs = Date.now() - new Date(projectDomain.updatedAt).getTime(); @@ -368,8 +320,10 @@ const DomainItem = ({ suffix={ Promise; project: Project; validatedDomains?: readonly string[]; + onOpenReport?: (domain: string) => void; + sessionPublishes?: SessionPublish[]; }; export const Domains = ({ @@ -590,6 +546,8 @@ export const Domains = ({ refresh, project, validatedDomains, + onOpenReport, + sessionPublishes = [], }: DomainsProps) => { return ( <> @@ -601,13 +559,16 @@ export const Domains = ({ refresh={refresh} project={project} validatedDomains={validatedDomains} + onOpenReport={onOpenReport} + latestPublish={sessionPublishes.find( + (item) => + item.target === "site" && + item.domains.includes(projectDomain.domain) + )} /> ))} ); }; -undefined; -undefined; - export const __testing__ = { StatusIcon }; diff --git a/apps/builder/app/builder/features/publish/publish-actions.test.tsx b/apps/builder/app/builder/features/publish/publish-actions.test.tsx index 1d4fc47d28..d82837edbe 100644 --- a/apps/builder/app/builder/features/publish/publish-actions.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-actions.test.tsx @@ -2,8 +2,8 @@ import { createRef, useState } from "react"; import { createRoot, type Root } from "react-dom/client"; import { act } from "react-dom/test-utils"; import { afterEach, expect, test, vi } from "vitest"; -import { TooltipProvider, toast } from "@webstudio-is/design-system"; -import { PublishActions, usePublishValidationState } from "./publish-actions"; +import { TooltipProvider } from "@webstudio-is/design-system"; +import { PublishActions } from "./publish-actions"; let root: Root | undefined; let container: HTMLDivElement | undefined; @@ -74,146 +74,6 @@ test("shows the successful validation state in the action", () => { expect(validate).toBeEnabled(); }); -test("clears the validation result when the publish popover closes", async () => { - const Harness = () => { - const [isOpen, setIsOpen] = useState(true); - const { validationState, update, reset } = usePublishValidationState( - isOpen ? "publish" : "none" - ); - - return ( - - {isOpen && ( - ()} - onValidate={async () => { - update("passed"); - }} - onPublish={vi.fn()} - /> - )} - - {isOpen === false && ( - - )} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - - const [validate, , close] = Array.from( - container.querySelectorAll("button") - ); - await act(async () => validate.click()); - expect(validate.textContent).toBe("Validated"); - - act(() => close.click()); - const reopen = - container.querySelector("button:last-child"); - act(() => reopen?.click()); - - const [reopenedValidate] = Array.from( - container.querySelectorAll("button") - ); - expect(reopenedValidate.textContent).toBe("Validate"); - expect(reopenedValidate.querySelector("svg")).toBeNull(); -}); - -test.each([ - { destination: "none" as const, expectedToasts: 1 }, - { destination: "none" as const, reopen: true, expectedToasts: 0 }, - { destination: "export" as const, expectedToasts: 1 }, - { destination: "publish" as const, expectedToasts: 0 }, -])( - "reports validation success after switching to $destination (reopen: $reopen)", - async ({ destination, reopen, expectedToasts }) => { - const successToast = vi - .spyOn(toast, "success") - .mockImplementation(() => ""); - let finishValidation: () => void = () => {}; - const validation = new Promise((resolve) => { - finishValidation = resolve; - }); - - const Harness = () => { - const [dialog, setDialog] = useState<"none" | "publish" | "export">( - "publish" - ); - const { validationState, update } = usePublishValidationState(dialog); - return ( - - {dialog === "publish" && ( - ()} - onValidate={async () => { - await validation; - update("passed"); - }} - onPublish={vi.fn()} - /> - )} - - - {validationState} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [validate, , switchDialog, reopenDialog] = - container.querySelectorAll("button"); - act(() => validate.click()); - act(() => switchDialog.click()); - if (reopen) { - act(() => reopenDialog.click()); - } - await act(async () => { - finishValidation(); - await validation; - }); - - expect(successToast).toHaveBeenCalledTimes(expectedToasts); - expect(container.querySelector("output")?.textContent).toBe( - destination === "publish" || reopen ? "passed" : "idle" - ); - } -); - test("shows the countdown and disables actions during publish progress", () => { const [validate, publish] = render( "idle", diff --git a/apps/builder/app/builder/features/publish/publish-actions.tsx b/apps/builder/app/builder/features/publish/publish-actions.tsx index 534d3a2068..bc927ed032 100644 --- a/apps/builder/app/builder/features/publish/publish-actions.tsx +++ b/apps/builder/app/builder/features/publish/publish-actions.tsx @@ -1,42 +1,9 @@ -import { useCallback, useEffect, useRef, useState, type Ref } from "react"; -import { Button, Flex, Tooltip, toast } from "@webstudio-is/design-system"; +import { useState, type Ref } from "react"; +import { Button, Flex, Tooltip } from "@webstudio-is/design-system"; import { CheckCircleIcon } from "@webstudio-is/icons"; export type PublishValidationState = "idle" | "passed"; -export const usePublishValidationState = ( - dialog: "none" | "publish" | "export" -) => { - const [validationState, setValidationState] = - useState("idle"); - const dialogRef = useRef(dialog); - dialogRef.current = dialog; - - const reset = useCallback(() => { - setValidationState("idle"); - }, []); - - const update = useCallback((state: PublishValidationState) => { - if (state === "passed" && dialogRef.current !== "publish") { - toast.success("Validation passed. Ready to publish.", { - duration: Number.POSITIVE_INFINITY, - }); - return; - } - if (dialogRef.current === "publish") { - setValidationState(state); - } - }, []); - - useEffect(() => { - if (dialog !== "publish") { - reset(); - } - }, [dialog, reset]); - - return { validationState, update, reset }; -}; - export const PublishActions = ({ validationState, validateDisabled, 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 new file mode 100644 index 0000000000..7de1646704 --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-click.render.test.tsx @@ -0,0 +1,575 @@ +import { act } from "react-dom/test-utils"; +import { createRoot, type Root } from "react-dom/client"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, + vi, +} from "vitest"; +import { TooltipProvider, toast } from "@webstudio-is/design-system"; +import type { Project } from "@webstudio-is/project"; +import { createTrpcInterceptor } from "./publish-test-utils"; + +const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }; +const originalActEnvironment = reactEnvironment.IS_REACT_ACT_ENVIRONMENT; +const originalScrollIntoView = Object.getOwnPropertyDescriptor( + Element.prototype, + "scrollIntoView" +); + +let root: Root | undefined; +let publishModule: typeof import("./publish"); +let stores: typeof import("~/shared/sync/data-stores"); +let nanoStates: typeof import("~/shared/nano-states"); +let builderStates: typeof import("~/builder/shared/nano-states"); +const requests: Array<{ path: string; input: unknown }> = []; +let publishResponse: unknown = { success: false, error: "Publish blocked" }; +let jobStatus: "failed" | "success" = "failed"; +let didPublish = false; +let interceptor: ReturnType; + +beforeAll(async () => { + Object.defineProperty(Element.prototype, "scrollIntoView", { + configurable: true, + value: () => undefined, + }); + vi.resetModules(); + interceptor = createTrpcInterceptor( + { + "domain.publish": () => { + didPublish = (publishResponse as { success: boolean }).success; + return publishResponse; + }, + "api.publish.getJob": () => { + return { status: jobStatus, code: "BUILD_FAILED" }; + }, + "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, + }), + "api.publish.validate": () => ({ + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: true, + }), + "build.contentDatabasePublishDiagnostics": () => ({ + mdxErrors: [], + mdxOmissions: [], + }), + }, + (route, input) => + requests.push({ path: `/trpc/${route}`, input: { "0": input } }) + ); + interceptor.start(); + publishModule = await import("./publish"); + stores = await import("~/shared/sync/data-stores"); + nanoStates = await import("~/shared/nano-states"); + builderStates = await import("~/builder/shared/nano-states"); + const { updateCsrfToken } = await import("~/shared/csrf.client"); + updateCsrfToken("test-token"); +}); + +beforeEach(() => { + reactEnvironment.IS_REACT_ACT_ENVIRONMENT = true; + publishResponse = { success: false, error: "Publish blocked" }; + requests.length = 0; + jobStatus = "failed"; + didPublish = false; + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: false, + }); +}); + +const mount = async (dialog: "publish" | "export" = "publish") => { + stores.$project.set({ + id: "project-1", + domain: "example", + domainsVirtual: [], + latestStaticBuild: null, + } as unknown as Project); + nanoStates.$authTokenPermissions.set({ + canClone: true, + canCopy: true, + canPublish: true, + }); + builderStates.$publishDialog.set(dialog); + const container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + await act(async () => + root?.render( + + + + ) + ); +}; + +const selectStaticDestination = async () => { + const destination = document.body.querySelector( + 'button[role="combobox"]' + ); + expect(destination).not.toBeNull(); + await act(async () => { + destination?.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ); + }); + const staticOption = Array.from( + document.body.querySelectorAll('[role="option"]') + ).find((option) => option.textContent?.trim() === "Static"); + expect(staticOption).toBeDefined(); + await act(async () => staticOption?.click()); +}; + +test("a successful site runner finishes the current publish and retains its report", async () => { + jobStatus = "success"; + publishResponse = { + success: true, + buildId: "build-1", + logHandle: "log-handle", + findings: [], + }; + await mount(); + const domain = document.body.querySelector( + 'input[name="domainToPublish[]"]' + )!; + if (domain.checked === false) { + await act(async () => + document.body.querySelector('[role="checkbox"]')?.click() + ); + } + + const publish = Array.from( + document.body.querySelectorAll("button") + ) + .filter((button) => button.textContent === "Publish") + .at(-1)!; + await act(async () => publish.click()); + await act(async () => + vi.waitFor(() => + expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("build-1") + ) + ); + expect(requests.map(({ path }) => path)).toContain( + "/trpc/api.publish.getJob" + ); + expect(publish.disabled).toBe(false); + const seeLogs = Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See logs"); + expect(seeLogs).toBeDefined(); + expect(seeLogs?.parentElement?.textContent).toContain( + "Published successfully." + ); + await act(async () => seeLogs?.click()); + expect(builderStates.$publishDialog.get()).toBe("none"); + expect( + document.body.querySelector('[role="tab"][aria-selected="true"]') + ?.textContent + ).toBe("Publish"); + expect( + document.body.querySelector('[role="tabpanel"][data-state="active"]') + ?.textContent + ).toContain("Upgrade to Pro to view publish logs."); + await act(async () => builderStates.$publishDialog.set("publish")); + const report = document.body.querySelector( + 'button[aria-label^="Publish log:"]' + )!; + await act(async () => report.click()); + expect( + document.body.querySelector('[role="tab"][aria-selected="true"]') + ?.textContent + ).toBe("Publish"); + expect( + document.body.querySelector( + '[role="tabpanel"][data-state="active"] button[aria-expanded]' + ) + ).not.toBeNull(); + // The status label is the public result of a completed publish. + expect( + document.body.querySelector('[role="tabpanel"][data-state="active"]') + ?.textContent + ).toContain("Published"); + await act(async () => + document.body + .querySelector( + '[role="dialog"] button[aria-label="Close"]' + ) + ?.click() + ); + await act(async () => builderStates.$publishDialog.set("publish")); + const validate = Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "Validate"); + expect(validate).toBeDefined(); + await act(async () => validate?.click()); + await act(async () => + vi.waitFor(() => + expect( + Array.from( + document.body.querySelectorAll("button") + ).some((button) => button.textContent?.trim() === "See issues") + ).toBe(true) + ) + ); + expect(document.body.textContent).not.toContain("Published successfully."); +}); + +test("a rejected publish replaces an older success notice with its findings", async () => { + jobStatus = "success"; + publishResponse = { + success: true, + buildId: "build-1", + logHandle: "log-handle", + findings: [], + }; + await mount(); + const domain = document.body.querySelector( + 'input[name="domainToPublish[]"]' + )!; + if (domain.checked === false) { + await act(async () => + document.body.querySelector('[role="checkbox"]')?.click() + ); + } + const publish = Array.from( + document.body.querySelectorAll("button") + ) + .filter((button) => button.textContent?.trim() === "Publish") + .at(-1)!; + await act(async () => publish.click()); + await act(async () => + vi.waitFor(() => + expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("build-1") + ) + ); + expect(document.body.textContent).toContain("Published successfully."); + + publishResponse = { + success: false, + auditFindings: [{ severity: "error", message: "new audit failure" }], + }; + const publishAgain = Array.from( + document.body.querySelectorAll("button") + ) + .filter((button) => button.textContent?.trim() === "Publish") + .at(-1)!; + expect(publishAgain.disabled).toBe(false); + await act(async () => publishAgain.click()); + await act(async () => + vi.waitFor(() => + expect( + requests.filter(({ path }) => path === "/trpc/domain.publish") + ).toHaveLength(2) + ) + ); + const seeIssues = () => + Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See issues"); + await act(async () => vi.waitFor(() => expect(seeIssues()).toBeDefined())); + expect(document.body.textContent).not.toContain("Published successfully."); + await act(async () => seeIssues()?.click()); + expect(document.body.querySelector('[role="dialog"]')?.textContent).toContain( + "new audit failure" + ); +}); + +test("a successful static export links to its publish report until another export starts", async () => { + const { ExportContent } = await import("./publish-ui"); + const onOpenReport = vi.fn(); + const flow = { + isPublishing: false, + publishes: [ + { + buildId: "build-1", + target: "static" as const, + domains: [], + findings: [], + status: "success" as const, + staticName: "site.zip", + }, + ], + openStaticReport: onOpenReport, + exportStatic: () => {}, + } satisfies Parameters[0]["flow"]; + stores.$project.set({ + id: "project-1", + domain: "example", + domainsVirtual: [], + latestStaticBuild: { + buildId: "build-1", + updatedAt: new Date().toISOString(), + publishStatus: "PUBLISHED", + }, + } as unknown as Project); + const container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + await act(async () => + root?.render( + + + + ) + ); + await selectStaticDestination(); + const seeLogs = Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See logs"); + expect(seeLogs).toBeDefined(); + expect(seeLogs?.parentElement?.textContent).toContain("Downloaded"); + await act(async () => seeLogs?.click()); + expect(onOpenReport).toHaveBeenCalledWith("publish"); + await act(async () => + root?.render( + + + + ) + ); + expect( + Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See logs") + ).toBeUndefined(); + await act(async () => + root?.render( + + + + ) + ); + expect( + Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See logs") + ).toBeUndefined(); + await act(async () => + root?.render( + + + + ) + ); + expect( + Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See logs") + ).toBeUndefined(); +}); + +afterEach(() => { + act(() => { + root?.unmount(); + stores.$project.set(undefined); + builderStates.$publishDialog.set("none"); + }); + root = undefined; + document.body.innerHTML = ""; + nanoStates.$authTokenPermissions.set({ + canClone: true, + canCopy: true, + canPublish: false, + }); + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: false, + }); + vi.restoreAllMocks(); +}); + +afterAll(() => { + interceptor.stop(); + vi.resetModules(); + if (originalScrollIntoView === undefined) { + Reflect.deleteProperty(Element.prototype, "scrollIntoView"); + } else { + Object.defineProperty( + Element.prototype, + "scrollIntoView", + originalScrollIntoView + ); + } + reactEnvironment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment; +}); + +test("static export reaches the server without waiting for diagnostics", async () => { + await mount("export"); + await selectStaticDestination(); + const buildButton = Array.from( + document.body.querySelectorAll("button") + ).find( + (button) => button.textContent?.trim() === "Build and download static site" + ); + expect(buildButton).toBeDefined(); + await act(async () => { + buildButton?.click(); + await vi.waitFor(() => { + expect(requests.some(({ path }) => path === "/trpc/domain.publish")).toBe( + true + ); + }); + }); + + expect(requests).toContainEqual({ + path: "/trpc/domain.publish", + input: { + "0": { + projectId: "project-1", + destination: "static", + templates: ["ssg"], + }, + }, + }); + expect( + Array.from(document.body.querySelectorAll("a, button")).some( + (element) => element.textContent?.trim() === "Show element" + ) + ).toBe(false); +}, 10_000); + +test("keeps Diagnostics visible but disabled before there is anything to show", async () => { + await mount(); + const options = document.body.querySelector( + 'button[aria-label="Publish options"]' + ); + expect(options).not.toBeNull(); + await act(async () => { + options?.dispatchEvent( + new PointerEvent("pointerdown", { bubbles: true, pointerType: "mouse" }) + ); + }); + const diagnostics = Array.from( + document.body.querySelectorAll('[role="menuitem"]') + ).find((item) => item.textContent?.trim() === "Diagnostics"); + expect(diagnostics).toBeDefined(); + expect(diagnostics?.getAttribute("data-disabled")).not.toBeNull(); + expect( + requests.filter(({ path }) => path === "/trpc/project.userPublishCount") + ).toHaveLength(1); +}); + +test.each([ + ["Validate", "Errors", false], + ["Publish", "Errors", false], + ["Publish", "Publish", true], +] as const)( + "%s keeps the result in the popover until See issues opens %s", + async (action, expectedTab, accepted) => { + const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); + if (accepted) { + publishResponse = { + success: true, + buildId: "build-1", + logHandle: "log-handle", + findings: [], + }; + } + await mount(); + + const domain = document.body.querySelector( + 'input[name="domainToPublish[]"]' + ); + expect(domain).not.toBeNull(); + if (domain?.checked === false) { + const checkbox = + document.body.querySelector('[role="checkbox"]'); + expect(checkbox).not.toBeNull(); + await act(async () => checkbox?.click()); + } + expect( + new FormData(domain?.closest("form")!).getAll("domainToPublish[]") + ).toEqual(["example"]); + + const actionButton = Array.from( + document.body.querySelectorAll("button") + ) + .filter((button) => button.textContent?.trim() === action) + .at(-1); + expect(actionButton).toBeDefined(); + expect(actionButton?.disabled).toBe(false); + await act(async () => actionButton?.click()); + await vi.waitFor(() => { + expect( + Array.from(document.body.querySelectorAll("button")).some( + (button) => button.textContent?.trim() === "See issues" + ) + ).toBe(true); + }); + if (accepted) { + await vi.waitFor(() => { + const seeIssues = Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See issues"); + expect(seeIssues?.parentElement?.textContent).toContain( + "Publish failed" + ); + }); + } + + expect(builderStates.$publishDialog.get()).toBe("publish"); + if (action === "Validate") { + expect(errorToast).not.toHaveBeenCalled(); + } + if (accepted) { + expect(requests.map(({ path }) => path)).toContain( + "/trpc/api.publish.getJob" + ); + } + expect(document.body.querySelector('[role="tablist"]')).toBeNull(); + const seeIssues = Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See issues"); + await act(async () => seeIssues?.click()); + expect(builderStates.$publishDialog.get()).toBe("none"); + expect(document.body.querySelector('[role="tablist"]')).not.toBeNull(); + expect( + document.body.querySelector( + '[role="tab"][aria-selected="true"]' + )?.textContent + ).toBe(expectedTab); + } +); 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 new file mode 100644 index 0000000000..c77432c286 --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-flow.render.test.tsx @@ -0,0 +1,759 @@ +import { act } from "react-dom/test-utils"; +import { createRoot, type Root } from "react-dom/client"; +import { userEvent } from "@vitest/browser/context"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, + vi, +} from "vitest"; +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 { + createTrpcInterceptor, + deferred, + selectTab, +} from "./publish-test-utils"; + +let checks = deferred(); +let dispatch = deferred(); +let checkRequests = 0; +let checksRead = 0; +let publishRequests = 0; +let root: Root; +let container: HTMLDivElement; +let PublishButton: typeof import("./publish").PublishButton; +let stores: typeof import("~/shared/sync/data-stores"); +let nanoStates: typeof import("~/shared/nano-states"); +let publishDialog: typeof import("~/builder/shared/nano-states").$publishDialog; +let assetBridge: typeof import("~/shared/asset-content-bridge.client"); +let contentSession: ReturnType; +let interceptor: ReturnType; + +beforeAll(async () => { + ( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } + ).IS_REACT_ACT_ENVIRONMENT = true; + vi.resetModules(); + interceptor = createTrpcInterceptor({ + "domain.publish": () => { + publishRequests += 1; + return dispatch.promise; + }, + "api.publish.getJob": () => ({ + status: "failed", + code: "BUILD_FAILED", + }), + "api.publish.getLog": () => ({ + availability: "available", + log: { + encoding: "base64url", + chunk: btoa("older publish output"), + complete: true, + issues: [{ severity: "error", message: "older build issue" }], + }, + }), + "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; + } 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; + } + }, + }); + interceptor.start(); + PublishButton = (await import("./publish")).PublishButton; + stores = await import("~/shared/sync/data-stores"); + nanoStates = await import("~/shared/nano-states"); + publishDialog = (await import("~/builder/shared/nano-states")).$publishDialog; + assetBridge = await import("~/shared/asset-content-bridge.client"); + (await import("~/shared/csrf.client")).updateCsrfToken("test-token"); +}); + +beforeEach(() => { + contentSession = createAssetContentSession({ + authorize: () => true, + repository: { + readContent: async () => { + throw new Error("No assets in this project"); + }, + updateContent: async () => { + throw new Error("No assets in this project"); + }, + }, + }); + assetBridge.__testing__.initBridge( + assetBridge.createAssetContentBridge({ + origin: location.origin, + request: fetch, + authorize: () => true, + requireReload: () => {}, + getContentSession: () => contentSession, + }) + ); + checks = deferred(); + dispatch = deferred(); + checkRequests = 0; + checksRead = 0; + publishRequests = 0; + vi.spyOn(toast, "error").mockImplementation(() => ""); + stores.$project.set({ + id: "project", + domain: "example", + domainsVirtual: [], + latestStaticBuild: null, + } as unknown as Project); + nanoStates.$authTokenPermissions.set({ + canClone: true, + canCopy: true, + canPublish: true, + }); + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: false, + }); + publishDialog.set("none"); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); +}); + +afterEach(async () => { + act(() => root.unmount()); + checks.resolve({ mdxErrors: [], mdxOmissions: [] }); + dispatch.resolve({ success: false, error: "cleanup" }); + await act(async () => + vi.waitFor(() => expect(checksRead).toBe(checkRequests)) + ); + container.remove(); + assetBridge.__testing__.clearBridge(); + contentSession.dispose(); + stores.$project.set(undefined); + stores.$pages.set(undefined); + stores.$instances.set(new Map()); + stores.$props.set(new Map()); + stores.$dataSources.set(new Map()); + stores.$resources.set(new Map()); + stores.$assets.set(new Map()); + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: false, + }); + publishDialog.set("none"); + vi.restoreAllMocks(); +}); + +afterAll(() => interceptor.stop()); + +const mount = async (target: "site" | "static") => { + publishDialog.set(target === "site" ? "publish" : "export"); + await act(async () => + root.render( + + + + ) + ); + if (target === "static") { + const destination = document.body.querySelector( + 'button[role="combobox"]' + ); + await act(async () => + destination?.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ) + ); + const staticOption = Array.from( + document.body.querySelectorAll('[role="option"]') + ).find((option) => option.textContent?.trim() === "Static"); + await act(async () => staticOption?.click()); + return; + } + const domain = document.body.querySelector( + 'input[name="domainToPublish[]"]' + ); + if (domain?.checked === false) { + await act(async () => + document.body.querySelector('[role="checkbox"]')?.click() + ); + } +}; + +const clickPublish = async (target: "site" | "static", expected = 1) => { + const label = + target === "site" ? "Publish" : "Build and download static site"; + const button = Array.from( + document.body.querySelectorAll("button") + ) + .filter((candidate) => candidate.textContent?.trim() === label) + .at(-1); + expect(button).toBeDefined(); + await act(async () => vi.waitFor(() => expect(button?.disabled).toBe(false))); + await act(async () => button?.click()); + await act(async () => + vi.waitFor(() => + expect([checkRequests, publishRequests]).toEqual([expected, expected]) + ) + ); +}; + +const completeChecks = async (fail: boolean) => { + await act(async () => { + if (fail) { + checks.reject(new Error("check failure")); + } else { + 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)); + }); +}; + +const openErrors = async (target: "site" | "static") => { + if (target === "site") { + const issues = Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "See issues"); + const status = document.body.querySelector( + 'button[aria-label^="Publish log:"]' + ); + expect(issues ?? status).toBeDefined(); + if (issues !== undefined) { + await act(async () => userEvent.click(issues)); + } else { + await act(async () => status?.click()); + } + } + const findErrors = () => + Array.from( + document.body.querySelectorAll('[role="tab"]') + ).find((tab) => tab.textContent?.startsWith("Errors")); + await act(async () => vi.waitFor(() => expect(findErrors()).toBeDefined())); + await selectTab("Errors"); + return document.body.querySelector( + '[role="tabpanel"][data-state="active"]' + ); +}; + +const closeReport = async () => { + const close = document.body.querySelector( + '[role="dialog"] button[aria-label="Close"]' + ); + expect(close).toBeDefined(); + await act(async () => close?.click()); + await vi.waitFor(async () => { + await act(async () => {}); + expect(document.body.querySelector('[role="dialog"]')).toBeNull(); + }); +}; + +test.each([ + ["site", "checks-first", false], + ["site", "checks-first", true], + ["site", "server-first", false], + ["site", "server-first", true], + ["static", "checks-first", false], + ["static", "checks-first", true], + ["static", "server-first", false], + ["static", "server-first", true], +] as const)( + "%s audit rejection remains visible with %s (failed checks: %s)", + async (target, order, failChecks) => { + await mount(target); + await clickPublish(target); + if (order === "checks-first") { + await completeChecks(failChecks); + } + await act(async () => { + dispatch.resolve({ + success: false, + auditFindings: [{ severity: "error", message: "server rejection" }], + }); + await dispatch.promise; + }); + const errors = await openErrors(target); + expect(errors?.textContent).toContain("server rejection"); + if (order === "server-first") { + await completeChecks(failChecks); + } + if (failChecks) { + expect(errors?.textContent?.includes("check failure")).toBe( + order === "checks-first" + ); + } else { + expect( + Array.from(document.body.querySelectorAll('[role="tab"]')).some((tab) => + tab.textContent?.startsWith("Warnings") + ) + ).toBe(order === "checks-first"); + } + } +); + +test("closing Publish clears a completed validation", async () => { + stores.$pages.set({ + pages: new Map(), + folders: new Map(), + } as unknown as Pages); + stores.$instances.set(new Map()); + stores.$props.set(new Map()); + stores.$dataSources.set(new Map()); + stores.$resources.set(new Map()); + stores.$assets.set(new Map()); + await mount("site"); + const validate = Array.from( + document.body.querySelectorAll("button") + ) + .filter((button) => button.textContent?.trim() === "Validate") + .at(-1); + expect(validate).toBeDefined(); + await act(async () => validate?.click()); + await act(async () => vi.waitFor(() => expect(checkRequests).toBe(1))); + await act(async () => { + checks.resolve({ + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: true, + }); + await checks.promise; + await vi.waitFor(() => expect(checksRead).toBe(1)); + }); + 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( + Array.from(document.body.querySelectorAll("button")).some( + (button) => button.textContent?.trim() === "Validate" + ) + ).toBe(true); +}); + +test.each([ + ["request", "checks-first"], + ["request", "server-first"], + ["transport", "checks-first"], + ["transport", "server-first"], +] as const)( + "static %s failure remains visible with %s checks", + async (failure, order) => { + await mount("static"); + await clickPublish("static"); + if (order === "checks-first") { + await completeChecks(false); + } + const message = `${failure} failure`; + await act(async () => { + if (failure === "request") { + dispatch.resolve({ success: false, error: message }); + } else { + dispatch.reject(new Error(message)); + } + await dispatch.promise.catch(() => {}); + }); + if (order === "server-first") { + await completeChecks(false); + } + const status = document.body.querySelector( + 'button[aria-label="Publish log: Static export"]' + ); + await act(async () => status?.click()); + const errors = await openErrors("static"); + expect(errors?.textContent).toContain(message); + } +); + +test.each(["checks-first", "server-first"] as const)( + "site transport failure remains visible with %s checks", + async (order) => { + await mount("site"); + await clickPublish("site"); + if (order === "checks-first") { + await completeChecks(false); + } + await act(async () => { + dispatch.reject(new Error("site transport failure")); + await dispatch.promise.catch(() => {}); + }); + if (order === "server-first") { + await completeChecks(false); + } + const errors = await openErrors("site"); + expect(errors?.textContent).toContain("site transport failure"); + } +); + +test.each(["request", "transport"] as const)( + "a static %s failure does not replace an earlier site failure", + async (failure) => { + await mount("site"); + await clickPublish("site"); + await completeChecks(false); + await act(async () => { + 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(); + await mount("static"); + await clickPublish("static", 2); + await completeChecks(false); + await act(async () => { + if (failure === "request") { + dispatch.resolve({ success: false, error: "static rejection" }); + } else { + dispatch.reject(new Error("static transport")); + } + await dispatch.promise.catch(() => {}); + }); + await act(async () => + vi.waitFor(() => + expect(toast.error).toHaveBeenCalledWith( + failure === "request" ? "static rejection" : "static transport" + ) + ) + ); + const staticStatus = document.body.querySelector( + 'button[aria-label="Publish log: Static export"]' + ); + expect(staticStatus).toBeDefined(); + await act(async () => staticStatus?.click()); + const staticErrors = await openErrors("static"); + expect(staticErrors?.textContent).toContain( + failure === "request" ? "static rejection" : "static transport" + ); + await closeReport(); + await mount("site"); + const siteErrors = await openErrors("site"); + expect(siteErrors?.textContent).toContain("site rejection"); + expect(siteErrors?.textContent).not.toContain("static rejection"); + expect(siteErrors?.textContent).not.toContain("static transport"); + } +); + +test("a site transport error appears only for its attempted domain", async () => { + stores.$project.set({ + id: "project", + domain: "example", + domainsVirtual: [ + { + domain: "other.example", + projectId: "project", + domainId: "other-id", + status: "ACTIVE", + verified: true, + updatedAt: new Date().toISOString(), + latestBuildVirtual: null, + }, + ], + latestStaticBuild: null, + } as unknown as Project); + await mount("site"); + await clickPublish("site"); + await completeChecks(false); + await act(async () => { + dispatch.reject(new Error("scoped transport failure")); + await dispatch.promise.catch(() => {}); + }); + const otherDomainStatus = document.body.querySelector( + 'button[aria-label="Publish log: other.example"]' + ); + expect(otherDomainStatus).toBeDefined(); + await act(async () => otherDomainStatus?.click()); + expect( + document.body.querySelector('[role="dialog"]')?.textContent + ).not.toContain("scoped transport failure"); + await closeReport(); + await mount("site"); + const attemptedDomainStatus = Array.from( + document.body.querySelectorAll( + 'button[aria-label^="Publish log:"]' + ) + ).find( + (button) => + button.getAttribute("aria-label") !== "Publish log: other.example" + ); + expect(attemptedDomainStatus).toBeDefined(); + await act(async () => attemptedDomainStatus?.click()); + expect(document.body.querySelector('[role="dialog"]')?.textContent).toContain( + "scoped transport failure" + ); +}); + +test("an accepted publish failure appears only for its attempted domain", async () => { + stores.$project.set({ + id: "project", + domain: "example", + domainsVirtual: [ + { + domain: "other.example", + projectId: "project", + domainId: "other-id", + status: "ACTIVE", + verified: true, + updatedAt: new Date().toISOString(), + latestBuildVirtual: null, + }, + ], + latestStaticBuild: null, + } as unknown as Project); + await mount("site"); + await clickPublish("site"); + await completeChecks(false); + await act(async () => { + dispatch.resolve({ + success: true, + buildId: "accepted-build", + logHandle: "handle", + findings: [], + }); + await dispatch.promise; + }); + const otherDomainStatus = document.body.querySelector( + 'button[aria-label="Publish log: other.example"]' + ); + expect(otherDomainStatus).toBeDefined(); + await act(async () => otherDomainStatus?.click()); + expect( + Array.from(document.body.querySelectorAll('[role="tab"]')).some((tab) => + tab.textContent?.startsWith("Errors") + ) + ).toBe(false); +}); + +test.each(["site", "static"] as const)( + "%s check failure has one notice while Publish is open", + async (target) => { + await mount(target); + await clickPublish(target); + await act(async () => publishDialog.set("publish")); + await completeChecks(true); + if (target === "static") { + await vi.waitFor(() => expect(toast.error).toHaveBeenCalledOnce()); + } else { + expect(toast.error).not.toHaveBeenCalled(); + } + } +); + +test("an accepted site failure links to its own publish log", async () => { + await mount("site"); + await clickPublish("site"); + await completeChecks(false); + await act(async () => { + dispatch.resolve({ + success: true, + buildId: "accepted-build", + logHandle: "handle", + findings: [], + }); + await dispatch.promise; + }); + const errors = await openErrors("site"); + const findShowLogs = () => + Array.from( + errors?.querySelectorAll("button") ?? [] + ).find((button) => button.textContent?.trim() === "show logs"); + await vi.waitFor(async () => { + await act(async () => {}); + expect(findShowLogs()).toBeDefined(); + }); + const showLogs = findShowLogs(); + await act(async () => showLogs?.click()); + expect( + document.body.querySelector('[role="tab"][aria-selected="true"]') + ?.textContent + ).toBe("Publish"); +}); + +test.each([ + ["none", false, 1], + ["none", true, 0], + ["export", false, 1], + ["publish", false, 0], +] as const)( + "validation completed after switching to %s (reopened: %s)", + async (destination, reopen, expectedToasts) => { + const successToast = vi + .spyOn(toast, "success") + .mockImplementation(() => ""); + stores.$pages.set({ + pages: new Map(), + folders: new Map(), + } as unknown as Pages); + stores.$instances.set(new Map()); + stores.$props.set(new Map()); + stores.$dataSources.set(new Map()); + stores.$resources.set(new Map()); + stores.$assets.set(new Map()); + await mount("site"); + const validate = Array.from( + document.body.querySelectorAll("button") + ) + .filter((button) => button.textContent?.trim() === "Validate") + .at(-1); + expect(validate).toBeDefined(); + await act(async () => + vi.waitFor(() => expect(validate?.disabled).toBe(false)) + ); + expect( + new FormData(validate?.closest("form")!).getAll("domainToPublish[]") + ).toEqual(["example"]); + await act(async () => validate?.click()); + expect(validate?.dataset.state).toBe("pending"); + await act(async () => vi.waitFor(() => expect(checkRequests).toBe(1))); + await act(async () => publishDialog.set(destination)); + if (reopen) { + expect( + document.body.querySelector('input[name="domainToPublish[]"]') + ).toBeNull(); + await act(async () => publishDialog.set("publish")); + } + await act(async () => { + checks.resolve({ + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: true, + }); + await checks.promise; + await vi.waitFor(() => expect(checksRead).toBe(1)); + }); + if (expectedToasts > 0) { + await act(async () => + vi.waitFor(() => + expect(successToast).toHaveBeenCalledTimes(expectedToasts) + ) + ); + } 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( + Array.from(document.body.querySelectorAll("button")).some( + (button) => button.textContent?.trim() === "Validate" + ) + ).toBe(true); + } + } +); + +test.each([ + ["site", "request"], + ["site", "transport"], + ["site", "audit"], + ["static", "request"], + ["static", "transport"], + ["static", "audit"], +] as const)( + "a newer %s %s rejection does not show an older build issue", + async (target, failure) => { + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: true, + }); + await mount(target); + await clickPublish(target); + await completeChecks(false); + await act(async () => { + dispatch.resolve({ + success: true, + buildId: "older-build", + logHandle: "older-handle", + findings: [], + ...(target === "static" ? { name: "site.zip" } : {}), + }); + await dispatch.promise; + }); + await act(async () => + vi.waitFor(() => + expect( + document.body.querySelector( + 'button[aria-label^="Publish log:"]' + ) + ).not.toBeNull() + ) + ); + checks = deferred(); + dispatch = deferred(); + await mount(target); + await clickPublish(target, 2); + const message = `new ${failure} failure`; + await act(async () => { + if (failure === "transport") { + dispatch.reject(new Error(message)); + } else { + dispatch.resolve( + failure === "audit" + ? { + success: false, + auditFindings: [{ severity: "error", message }], + } + : { success: false, error: message } + ); + } + await dispatch.promise.catch(() => {}); + }); + await completeChecks(false); + if (target === "static") { + const status = document.body.querySelector( + 'button[aria-label="Publish log: Static export"]' + ); + await act(async () => status?.click()); + } + const errors = await openErrors(target); + expect(errors?.textContent).toContain(message); + expect(errors?.textContent).not.toContain("older build issue"); + } +); 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 new file mode 100644 index 0000000000..04f394a1d9 --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-progress.render.test.tsx @@ -0,0 +1,849 @@ +import { act } from "react-dom/test-utils"; +import { createRoot, type Root } from "react-dom/client"; +import { userEvent } from "@vitest/browser/context"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, + vi, +} from "vitest"; +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 { + createTrpcInterceptor, + deferred, + selectTab, +} from "./publish-test-utils"; + +const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }; +const originalActEnvironment = reactEnvironment.IS_REACT_ACT_ENVIRONMENT; + +let root: Root | undefined; +let container: HTMLDivElement; +let PublishButton: typeof import("./publish").PublishButton; +let stores: typeof import("~/shared/sync/data-stores"); +let nanoStates: typeof import("~/shared/nano-states"); +let dialog: typeof import("~/builder/shared/nano-states").$publishDialog; +let assetBridge: typeof import("~/shared/asset-content-bridge.client"); +let contentSession: ReturnType; +let interceptor: ReturnType; +let initialPlan: ReturnType; +let project: Project; +let publish: () => Promise; +let refresh: () => Promise; +let validate: () => Promise; +let job: () => Promise; +const requests: { route: string; input: unknown }[] = []; +const checks = { + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: true, +}; +const warningChecks = { ...checks, cssValid: false }; +const makeProject = ( + id = "project", + build?: { buildId: string; publishStatus: string } +) => + ({ + id, + domain: "example", + domainsVirtual: [], + latestStaticBuild: null, + latestBuildVirtual: + build === undefined + ? null + : { + ...build, + domain: "example", + createdAt: new Date().toISOString(), + }, + }) as unknown as Project; + +beforeAll(async () => { + reactEnvironment.IS_REACT_ACT_ENVIRONMENT = true; + vi.resetModules(); + interceptor = createTrpcInterceptor( + { + "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 }) + ); + interceptor.start(); + PublishButton = (await import("./publish")).PublishButton; + stores = await import("~/shared/sync/data-stores"); + nanoStates = await import("~/shared/nano-states"); + initialPlan = nanoStates.$planFeatures.get(); + dialog = (await import("~/builder/shared/nano-states")).$publishDialog; + assetBridge = await import("~/shared/asset-content-bridge.client"); + (await import("~/shared/csrf.client")).updateCsrfToken("test-token"); +}); + +beforeEach(() => { + contentSession = createAssetContentSession({ + authorize: () => true, + repository: { + readContent: async () => { + throw new Error("No assets in this project"); + }, + updateContent: async () => { + throw new Error("No assets in this project"); + }, + }, + }); + assetBridge.__testing__.initBridge( + assetBridge.createAssetContentBridge({ + origin: location.origin, + request: fetch, + authorize: () => true, + requireReload: () => {}, + getContentSession: () => contentSession, + }) + ); + project = makeProject(); + publish = async () => ({ success: false, error: "request rejection" }); + refresh = async () => ({ success: true, project }); + validate = async () => checks; + job = async () => ({ status: "failed", code: "runner_failed" }); + requests.length = 0; + stores.$project.set(project); + stores.$pages.set({ + homePageId: "home", + rootFolderId: "root", + pages: new Map(), + folders: new Map(), + }); + stores.$instances.set(new Map()); + stores.$props.set(new Map()); + stores.$dataSources.set(new Map()); + stores.$resources.set(new Map()); + stores.$assets.set(new Map()); + nanoStates.$authTokenPermissions.set({ + canClone: true, + canCopy: true, + canPublish: true, + }); + nanoStates.$planFeatures.set({ + ...initialPlan, + allowPublishLogs: false, + }); + dialog.set("publish"); + vi.spyOn(toast, "error").mockImplementation(() => ""); + vi.spyOn(toast, "success").mockImplementation(() => ""); + vi.spyOn(console, "error").mockImplementation(() => {}); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); +}); + +afterEach(async () => { + act(() => root?.unmount()); + root = undefined; + container.remove(); + dialog.set("none"); + stores.$project.set(undefined); + stores.$pages.set(undefined); + assetBridge.__testing__.clearBridge(); + contentSession.dispose(); + nanoStates.$planFeatures.set(initialPlan); + nanoStates.$authPermit.set("view"); + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +afterAll(() => { + interceptor.stop(); + reactEnvironment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment; +}); + +const button = (label: string) => + Array.from(document.body.querySelectorAll("button")) + .filter((candidate) => { + const copy = candidate.cloneNode(true) as HTMLElement; + copy.querySelectorAll("svg").forEach((icon) => icon.remove()); + return copy.textContent?.trim() === label; + }) + .at(-1); +const click = async (label: string) => { + const target = button(label); + expect(target).toBeDefined(); + expect(target?.disabled).toBe(false); + await act(async () => userEvent.click(target!)); +}; +const mount = async (projectId = "project") => { + await act(async () => + root?.render( + + + + ) + ); + if (vi.isFakeTimers()) { + await act(async () => vi.advanceTimersByTimeAsync(10)); + } + const domain = document.body.querySelector( + 'input[name="domainToPublish[]"]' + ); + if (domain?.checked === false) { + await act(async () => + document.body.querySelector('[role="checkbox"]')?.click() + ); + } +}; +const toggle = async (value: "publish" | "none" | "export") => { + if (value === "none") { + await act(async () => + document.dispatchEvent( + new KeyboardEvent("keydown", { key: "Escape", bubbles: true }) + ) + ); + } else if (value === "publish" && dialog.get() === "none") { + await act(async () => + container.querySelector("button")?.click() + ); + } else { + await act(async () => dialog.set(value)); + } + if (vi.isFakeTimers()) { + await act(async () => vi.advanceTimersByTimeAsync(20)); + } + if (value === "publish") { + const domains = Array.from( + document.body.querySelectorAll( + 'input[name="domainToPublish[]"]' + ) + ); + if (domains.length > 0 && domains.every((domain) => !domain.checked)) { + await act(async () => + document.body.querySelector('[role="checkbox"]')?.click() + ); + } + } +}; + +const waitFor = async (check: () => void) => { + await vi.waitFor(async () => { + await act(async () => {}); + check(); + }); +}; +const banner = () => button("See issues")?.parentElement; +const accept = () => ({ + success: true, + buildId: "accepted", + logHandle: "handle", + findings: [], +}); +const openReport = async (tab: "Errors" | "Warnings") => { + await click("See issues"); + await waitFor(() => + expect(document.body.querySelector('[role="tablist"]')).not.toBeNull() + ); + await selectTab(tab); + const report = document.body.querySelector( + '[role="tabpanel"][data-state="active"]' + ); + expect(report).not.toBeNull(); + return report!; +}; + +test.each(["open", "closed", "reopened"] as const)( + "a transport failure uses the current %s panel without duplicate notices", + async (state) => { + const response = deferred(); + publish = () => response.promise; + await mount(); + await click("Publish"); + await waitFor(() => + expect(requests.some(({ route }) => route === "domain.publish")).toBe( + true + ) + ); + if (state !== "open") { + await toggle("none"); + } + if (state === "reopened") { + await toggle("publish"); + } + await act(async () => response.reject(new Error("transport failure"))); + await waitFor(() => + expect( + state === "closed" ? toast.error : button("See issues") + ).toBeDefined() + ); + if (state === "closed") { + await waitFor(() => expect(toast.error).toHaveBeenCalledOnce()); + await toggle("publish"); + } else { + expect(toast.error).not.toHaveBeenCalled(); + } + await waitFor(() => + expect(banner()?.textContent).toContain("transport failure") + ); + await toggle("none"); + await toggle("publish"); + expect(banner()).toBeDefined(); + } +); + +test("starting validation clears a request failure", async () => { + await mount(); + await click("Publish"); + await waitFor(() => expect(banner()).toBeDefined()); + await click("Validate"); + await waitFor(() => expect(button("Validated")).toBeDefined()); + expect(banner()).toBeUndefined(); +}); + +test.each(["PUBLISHED", "none"] as const)( + "a %s refresh clears a retained status error", + async (status) => { + publish = async () => accept(); + project = makeProject("project", { + buildId: "accepted", + publishStatus: "FAILED", + }); + await mount(); + await click("Publish"); + await waitFor(() => expect(banner()).toBeDefined()); + await toggle("none"); + await toggle("publish"); + expect(banner()).toBeDefined(); + project = + status === "none" + ? makeProject() + : makeProject("project", { + buildId: "accepted", + publishStatus: status, + }); + await toggle("none"); + await toggle("publish"); + await waitFor(() => expect(banner()).toBeUndefined()); + } +); + +test.each(["PUBLISHED", "none"] as const)( + "a %s refresh preserves a rejected request error", + async (status) => { + project = + status === "none" + ? makeProject() + : makeProject("project", { buildId: "old", publishStatus: status }); + await mount(); + await click("Publish"); + await waitFor(() => expect(banner()).toBeDefined()); + await toggle("none"); + await toggle("publish"); + await waitFor(() => + expect( + requests.filter(({ route }) => route === "domain.project").length + ).toBeGreaterThan(1) + ); + expect(banner()?.textContent).toContain("request rejection"); + } +); + +test.each(["PUBLISHED", "FAILED"] as const)( + "a recovered %s build replaces a lost response only when the build changes", + async (status) => { + project = makeProject("project", { + buildId: "old", + publishStatus: "PUBLISHED", + }); + publish = async () => { + throw new Error("transport failure"); + }; + await mount(); + await click("Publish"); + await waitFor(() => + expect(banner()?.textContent).toContain("transport failure") + ); + await toggle("none"); + await toggle("publish"); + expect(banner()?.textContent).toContain("transport failure"); + project = makeProject("project", { buildId: "new", publishStatus: status }); + await toggle("none"); + await toggle("publish"); + await waitFor(() => + expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("new") + ); + if (status === "PUBLISHED") { + expect(banner()).toBeUndefined(); + } else { + expect(banner()).toBeDefined(); + expect(banner()?.textContent).not.toContain("transport failure"); + } + } +); + +test("a recovered pending build keeps polling after the popover closes", async () => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "setInterval", + "clearInterval", + "Date", + ], + }); + project = makeProject("project", { + buildId: "recovered", + publishStatus: "PENDING", + }); + await mount(); + await waitFor(() => + expect( + requests.filter(({ route }) => route === "domain.project") + ).toHaveLength(2) + ); + await act(async () => vi.advanceTimersByTimeAsync(10)); + await toggle("none"); + project = makeProject("project", { + buildId: "recovered", + publishStatus: "PUBLISHED", + }); + await act(async () => vi.advanceTimersByTimeAsync(15_100)); + expect(toast.success).toHaveBeenCalledOnce(); +}); + +test("an older recovered poll cannot replace a newer popover refresh", async () => { + const stale = deferred(); + let refreshes = 0; + project = makeProject("project", { + buildId: "recovered", + publishStatus: "PENDING", + }); + refresh = async () => + ++refreshes === 2 ? stale.promise : { success: true, project }; + await mount(); + await waitFor(() => expect(refreshes).toBe(2)); + project = makeProject("project", { + buildId: "new", + publishStatus: "PUBLISHED", + }); + await toggle("none"); + await toggle("publish"); + await waitFor(() => + expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("new") + ); + await act(async () => + stale.resolve({ + success: true, + project: makeProject("project", { + buildId: "old", + publishStatus: "PUBLISHED", + }), + }) + ); + expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("new"); +}); + +test("an old status request cannot update a remounted copy of the same project", async () => { + const stale = deferred(); + let refreshes = 0; + project = makeProject("project", { + buildId: "recovered", + publishStatus: "PENDING", + }); + refresh = async () => + ++refreshes === 2 ? stale.promise : { success: true, project }; + await mount(); + await waitFor(() => expect(refreshes).toBe(2)); + act(() => root?.unmount()); + project = makeProject("other"); + stores.$project.set(project); + project = makeProject("project", { + buildId: "new", + publishStatus: "PUBLISHED", + }); + stores.$project.set(project); + root = createRoot(container); + await mount(); + await act(async () => + stale.resolve({ + success: true, + project: makeProject("project", { + buildId: "old", + publishStatus: "PUBLISHED", + }), + }) + ); + expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe("new"); + expect(toast.success).not.toHaveBeenCalled(); +}); + +test.each(["success", "transport"] as const)( + "an old project's %s response cannot finish a new project's publish", + async (outcome) => { + const old = deferred(); + const current = deferred(); + let publishes = 0; + publish = () => (++publishes === 1 ? old.promise : current.promise); + await mount(); + await click("Publish"); + await waitFor(() => expect(publishes).toBe(1)); + project = makeProject("new-project"); + await act(async () => stores.$project.set(project)); + await mount("new-project"); + await click("Publish"); + await waitFor(() => expect(publishes).toBe(2)); + await act(async () => { + if (outcome === "success") { + old.resolve(accept()); + } else { + old.reject(new Error("old failure")); + } + }); + expect(button("Publishing (60s)")?.disabled).toBe(true); + expect(toast.error).not.toHaveBeenCalled(); + expect(toast.success).not.toHaveBeenCalled(); + await act(async () => + current.resolve({ success: false, error: "current failure" }) + ); + await waitFor(() => expect(banner()).toBeDefined()); + } +); + +test("closing publish hides its countdown while polling continues to completion", async () => { + vi.useFakeTimers({ + toFake: [ + "setTimeout", + "clearTimeout", + "setInterval", + "clearInterval", + "Date", + ], + }); + const pending = deferred(); + publish = async () => accept(); + job = () => pending.promise; + await mount(); + await click("Publish"); + await waitFor(() => + expect(requests.some(({ route }) => route === "api.publish.getJob")).toBe( + true + ) + ); + expect(button("Publishing (60s)")?.disabled).toBe(true); + await act(async () => vi.advanceTimersByTimeAsync(10_000)); + expect(button("Publishing (50s)")?.disabled).toBe(true); + await toggle("none"); + await toggle("publish"); + expect(button("Publish")?.disabled).toBe(true); + await toggle("none"); + project = makeProject("project", { + buildId: "accepted", + publishStatus: "PUBLISHED", + }); + await act(async () => pending.resolve({ status: "success" })); + await act(async () => vi.advanceTimersByTimeAsync(100)); + await toggle("publish"); + expect(button("Publish")?.disabled).toBe(false); + expect(button("Publish")?.dataset.state).not.toBe("pending"); + expect(toast.success).toHaveBeenCalledOnce(); +}); + +test.each(["success", "failed"] as const)( + "a confirmed %s site publish clears controls despite a stale pending Build", + async (outcome) => { + publish = async () => { + project = makeProject("project", { + buildId: "accepted", + publishStatus: "PENDING", + }); + return accept(); + }; + job = async () => ({ status: outcome, code: "runner_failed" }); + await mount(); + await click("Publish"); + await waitFor(() => + expect(stores.$project.get()?.latestBuildVirtual?.buildId).toBe( + "accepted" + ) + ); + await waitFor(() => + expect(requests.some(({ route }) => route === "api.publish.getJob")).toBe( + true + ) + ); + await waitFor(() => expect(button("Publish")).toBeDefined()); + expect(button("Publish")?.dataset.state).not.toBe("pending"); + expect(button("Validate")?.disabled).toBe(false); + if (outcome === "success") { + await waitFor(() => expect(button("See logs")).toBeDefined()); + } else { + await waitFor(() => expect(button("See issues")).toBeDefined()); + } + } +); + +test("a confirmed site success survives a stale Build timeout during popover refresh", async () => { + publish = async () => { + project = makeProject("project", { + buildId: "accepted", + publishStatus: "PENDING", + }); + project.latestBuildVirtual!.createdAt = new Date( + Date.now() - 10 * 60_000 + ).toISOString(); + return accept(); + }; + job = async () => ({ status: "success" }); + await mount(); + const previousRefreshes = requests.filter( + ({ route }) => route === "domain.project" + ).length; + await click("Publish"); + await waitFor(() => + expect( + requests.filter(({ route }) => route === "domain.project").length + ).toBeGreaterThanOrEqual(previousRefreshes + 2) + ); + expect(button("See logs")).toBeDefined(); + expect(button("See issues")).toBeUndefined(); +}); + +test.each(["validation", "publish"] as const)( + "%s diagnostics remain available after the popover reopens", + async (action) => { + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: true, + }); + const response = deferred(); + publish = () => response.promise; + validate = async () => warningChecks; + await mount(); + await click(action === "validation" ? "Validate" : "Publish"); + await waitFor(() => expect(banner()).toBeDefined()); + if (action === "publish") { + await act(async () => + response.resolve({ success: false, error: "request rejection" }) + ); + await waitFor(() => expect(button("Publish")?.disabled).toBe(false)); + } + await toggle("none"); + await toggle("publish"); + expect(banner()).toBeDefined(); + const report = await openReport("Warnings"); + expect(report?.querySelector("button")).not.toBeNull(); + } +); + +test("an older validation cannot replace a newer report", async () => { + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: true, + }); + const old = deferred(); + let validations = 0; + validate = async () => (++validations === 1 ? old.promise : warningChecks); + await mount(); + await click("Validate"); + await waitFor(() => expect(validations).toBe(1)); + await toggle("none"); + await toggle("publish"); + await click("Validate"); + await waitFor(() => expect(validations).toBe(2)); + await waitFor(() => expect(banner()).toBeDefined()); + await act(async () => old.resolve(checks)); + expect(banner()).toBeDefined(); + expect(button("Validated")).toBeDefined(); + const report = await openReport("Warnings"); + expect(report?.querySelector("button")).not.toBeNull(); +}); + +test("older publish diagnostics cannot replace a newer operation", async () => { + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: true, + }); + const old = deferred(); + let validations = 0; + validate = async () => (++validations === 1 ? old.promise : warningChecks); + await mount(); + await click("Publish"); + await waitFor(() => expect(button("Publish")?.disabled).toBe(false)); + await click("Validate"); + await waitFor(() => expect(validations).toBe(2)); + await waitFor(() => expect(banner()).toBeDefined()); + await act(async () => old.resolve(checks)); + expect(banner()).toBeDefined(); + const report = await openReport("Warnings"); + expect(report?.querySelector("button")).not.toBeNull(); +}); + +test("reopening restores validated domains and publishes only those domains", async () => { + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowStagingPublish: true, + }); + nanoStates.$authPermit.set("own"); + project = { + ...makeProject("project", { buildId: "old", publishStatus: "PUBLISHED" }), + domainsVirtual: [ + { + projectId: "project", + domainId: "custom", + domain: "custom.example", + status: "ACTIVE", + verified: true, + latestBuildVirtual: null, + updatedAt: new Date().toISOString(), + }, + ], + } as Project; + stores.$project.set(project); + validate = async () => warningChecks; + await mount(); + const checkboxes = () => + Array.from( + document.body.querySelectorAll('[role="checkbox"]') + ); + expect(checkboxes()).toHaveLength(2); + // The saved build makes staging selected by default. Validate only the custom domain. + await act(async () => checkboxes()[0].click()); + if (checkboxes()[1].getAttribute("aria-checked") === "false") { + await act(async () => checkboxes()[1].click()); + } + await click("Validate"); + await waitFor(() => expect(banner()).toBeDefined()); + await toggle("none"); + await toggle("publish"); + expect(checkboxes().map((item) => item.getAttribute("aria-checked"))).toEqual( + ["false", "true"] + ); + const form = button("Publish")!.closest("form")!; + expect(new FormData(form).getAll("domainToPublish[]")).toEqual([ + "custom.example", + ]); + await click("Publish"); + await waitFor(() => + expect( + requests.find(({ route }) => route === "domain.publish") + ).toBeDefined() + ); + expect( + requests.find(({ route }) => route === "domain.publish")?.input + ).toMatchObject({ domains: ["custom.example"] }); + await waitFor(() => expect(button("Publish")?.disabled).toBe(false)); + await act(async () => checkboxes()[1].click()); + expect(new FormData(form).getAll("domainToPublish[]")).toEqual([]); +}); + +const selectStatic = async () => { + await toggle("export"); + const destination = document.body.querySelector( + 'button[role="combobox"]' + ); + await act(async () => + destination?.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ) + ); + const option = Array.from( + document.body.querySelectorAll('[role="option"]') + ).find((item) => item.textContent?.trim() === "Static"); + expect(option).toBeDefined(); + await act(async () => option?.click()); +}; + +test.each(["site", "static"] as const)( + "starting diagnostics for the other target keeps %s findings", + async (first) => { + let target: "site" | "static" = first; + publish = async () => ({ + success: false, + auditFindings: [{ severity: "error", message: `${target} diagnostic` }], + }); + await mount(); + if (first === "static") { + await selectStatic(); + } + await click( + first === "site" ? "Publish" : "Build and download static site" + ); + await waitFor(() => + expect( + requests.filter(({ route }) => route === "domain.publish") + ).toHaveLength(1) + ); + await waitFor(() => { + if (first === "static") { + expect(document.body.querySelector('[role="tablist"]')).not.toBeNull(); + } else { + expect(banner()).toBeDefined(); + expect(button("Publish")?.disabled).toBe(false); + } + }); + if (first === "static") { + // Close the report before returning to the other publish target. + const close = document.body.querySelector( + '[role="dialog"] button[aria-label="Close"]' + ); + expect(close).not.toBeNull(); + await act(async () => close?.click()); + } + target = first === "site" ? "static" : "site"; + if (target === "static") { + await selectStatic(); + } else { + await toggle("publish"); + } + await click( + target === "site" ? "Publish" : "Build and download static site" + ); + await waitFor(() => + expect( + requests.filter(({ route }) => route === "domain.publish") + ).toHaveLength(2) + ); + if (target === "static") { + await waitFor(() => + expect(document.body.querySelector('[role="tablist"]')).not.toBeNull() + ); + await act(async () => + document.body + .querySelector( + '[role="dialog"] button[aria-label="Close"]' + ) + ?.click() + ); + } + if (first === "site") { + await toggle("publish"); + const report = await openReport("Errors"); + expect(report?.textContent).toContain("site diagnostic"); + expect(report?.textContent).not.toContain("static diagnostic"); + } else { + await selectStatic(); + const reportButton = document.body.querySelector( + 'button[aria-label="Publish log: Static export"]' + ); + expect(reportButton).not.toBeNull(); + await act(async () => reportButton?.click()); + await waitFor(() => + expect(document.body.querySelector('[role="tablist"]')).not.toBeNull() + ); + expect( + document.body.querySelector('[role="tabpanel"][data-state="active"]') + ?.textContent + ).toContain("static diagnostic"); + } + } +); diff --git a/apps/builder/app/builder/features/publish/publish-progress.test.tsx b/apps/builder/app/builder/features/publish/publish-progress.test.tsx index 554964ee94..cf75e9ab3b 100644 --- a/apps/builder/app/builder/features/publish/publish-progress.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-progress.test.tsx @@ -1,128 +1,214 @@ -import { useState } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { act } from "react-dom/test-utils"; import { afterEach, expect, test, vi } from "vitest"; -import { TooltipProvider, toast } from "@webstudio-is/design-system"; +import { toast } from "@webstudio-is/design-system"; import type { Project } from "@webstudio-is/project"; import { $publishDialog } from "~/builder/shared/nano-states"; import { $project } from "~/shared/sync/data-stores"; -import { __testing__ } from "./publish"; -import { DomainCheckbox, domainToPublishName } from "./domain-checkbox"; -import { PublishValidationResults } from "./publish-validation-results"; - -const { - usePublishProgress, +import { waitForPublishStatus, - refreshUntilSuccess, - useManualValidationFindings, - getRefreshedProject, + refreshProjectWithRetry, + fetchAndStoreProject, reportPublishResult, -} = __testing__; - -let root: Root | undefined; -let container: HTMLDivElement | undefined; - -( - globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } -).IS_REACT_ACT_ENVIRONMENT = true; +} from "./publish-progress"; afterEach(() => { - act(() => root?.unmount()); - root = undefined; - container?.remove(); - container = undefined; $publishDialog.set("none"); $project.set(undefined); vi.useRealTimers(); vi.restoreAllMocks(); }); -test("closing publish hides the countdown while polling continues and completion clears pending", async () => { - vi.useFakeTimers(); - vi.setSystemTime(new Date("2026-10-20T12:00:00Z")); - $project.set({ id: "project" } as Project); - - let status: "PENDING" | "PUBLISHED" = "PENDING"; - let statusRequests = 0; - - const Harness = () => { - const [isOpen, setIsOpen] = useState(true); - const [completedStatus, setCompletedStatus] = useState(); - const progress = usePublishProgress("project"); - return ( - <> - - - - {isOpen && ( - - {progress.isPublishing ? "pending" : "complete"}: - {progress.countdown ?? "no countdown"}:{completedStatus ?? "none"} - - )} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - - const [start, close, open] = container.querySelectorAll("button"); - act(() => start.click()); - expect(container.querySelector("output")?.textContent).toBe( - "pending:60:none" +test("a verified runner failure finishes the existing status wait without a project refresh", async () => { + const refresh = vi.fn(async () => undefined); + const getJob = vi.fn(async () => ({ + status: "failed", + code: "runner_failed", + })); + const result = await waitForPublishStatus( + refresh, + () => true, + undefined, + { + projectId: "project", + buildId: "build-1", + logHandle: "handle-1", + }, + getJob ); - - await act(async () => vi.advanceTimersByTimeAsync(10_000)); - expect(container.querySelector("output")?.textContent).toBe( - "pending:50:none" - ); - - act(() => close.click()); - act(() => open.click()); - expect(container.querySelector("output")?.textContent).toBe( - "pending:no countdown:none" - ); - - act(() => close.click()); - status = "PUBLISHED"; - await act(async () => vi.advanceTimersByTimeAsync(5_000)); - act(() => open.click()); - expect(container.querySelector("output")?.textContent).toBe( - "complete:no countdown:PUBLISHED" - ); - expect(statusRequests).toBe(2); + expect(result?.status).toBe("FAILED"); + expect(result?.code).toBe("runner_failed"); + expect(refresh).not.toHaveBeenCalled(); + expect(getJob).toHaveBeenCalledWith({ + projectId: "project", + jobId: "build-1", + logHandle: "handle-1", + }); }); +test("a pending runner cannot promote a refreshed Build to success", async () => { + vi.useFakeTimers(); + const refresh = vi.fn( + async () => + ({ + latestBuildVirtual: { + buildId: "build-1", + createdAt: new Date().toISOString(), + publishStatus: "PUBLISHED", + }, + }) as Project + ); + const getJob = vi + .fn() + .mockResolvedValueOnce({ status: "pending" }) + .mockResolvedValueOnce({ status: "failed", code: "runner_failed" }); + const waiting = waitForPublishStatus( + refresh, + () => true, + undefined, + { projectId: "project", buildId: "build-1", logHandle: "handle-1" }, + getJob + ); + await vi.advanceTimersByTimeAsync(15_000); + expect((await waiting)?.status).toBe("FAILED"); + expect(refresh).toHaveBeenCalledOnce(); + expect(getJob).toHaveBeenCalledTimes(2); +}); + +test("a pending runner cannot turn a timed-out Build into failure", async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-11-13T10:10:00Z")); + const refresh = vi.fn( + async () => + ({ + latestBuildVirtual: { + buildId: "build-1", + createdAt: "2026-11-13T10:00:00Z", + publishStatus: "PENDING", + }, + }) as Project + ); + const getJob = vi + .fn() + .mockResolvedValueOnce({ status: "pending" }) + .mockResolvedValueOnce({ status: "failed", code: "runner_failed" }); + const waiting = waitForPublishStatus( + refresh, + () => true, + undefined, + { projectId: "project", buildId: "build-1", logHandle: "handle-1" }, + getJob + ); + await vi.advanceTimersByTimeAsync(15_000); + expect((await waiting)?.code).toBe("runner_failed"); + expect(getJob).toHaveBeenCalledTimes(2); +}); + +test("static status waits for the matching runner before download readiness", async () => { + vi.useFakeTimers(); + const refresh = vi.fn( + async () => + ({ + latestStaticBuild: { + buildId: "static-1", + updatedAt: new Date().toISOString(), + publishStatus: "PUBLISHED", + }, + }) as Project + ); + const getJob = vi + .fn() + .mockResolvedValueOnce({ status: "pending" }) + .mockResolvedValueOnce({ status: "success" }); + const waiting = waitForPublishStatus( + refresh, + () => true, + undefined, + { + projectId: "project", + buildId: "static-1", + logHandle: "handle-1", + target: "static", + }, + getJob + ); + await vi.advanceTimersByTimeAsync(15_000); + expect((await waiting)?.status).toBe("PUBLISHED"); + expect(getJob).toHaveBeenCalledTimes(2); +}); + +test.each(["site", "static"] as const)( + "finishes an accepted %s publish when a newer build becomes latest", + async (target) => { + vi.useFakeTimers(); + const newerBuild = { + buildId: "build-2", + createdAt: new Date().toISOString(), + updatedAt: new Date().toISOString(), + publishStatus: "PUBLISHED", + }; + const refresh = vi.fn( + async () => + ({ + latestBuildVirtual: target === "site" ? newerBuild : null, + latestStaticBuild: target === "static" ? newerBuild : null, + }) as Project + ); + const getJob = vi.fn(async () => ({ status: "success" })); + const waiting = waitForPublishStatus( + refresh, + () => true, + undefined, + { + projectId: "project", + buildId: "build-1", + logHandle: "handle-1", + target, + }, + getJob + ); + + await vi.runAllTimersAsync(); + expect((await waiting)?.status).toBe("PUBLISHED"); + expect(refresh).toHaveBeenCalledOnce(); + } +); + +test.each(["site", "static"] as const)( + "does not treat a stale %s pending build as failed after runner success", + async (target) => { + vi.useFakeTimers(); + vi.setSystemTime(new Date("2026-11-13T10:10:00Z")); + const staleBuild = { + buildId: "build-1", + createdAt: "2026-11-13T10:00:00Z", + updatedAt: "2026-11-13T10:00:00Z", + publishStatus: "PENDING", + }; + const refresh = vi.fn( + async () => + ({ + latestBuildVirtual: target === "site" ? staleBuild : null, + latestStaticBuild: target === "static" ? staleBuild : null, + }) as Project + ); + const getJob = vi.fn(async () => ({ status: "success" })); + const result = await waitForPublishStatus( + refresh, + () => true, + undefined, + { + projectId: "project", + buildId: "build-1", + logHandle: "handle-1", + target, + }, + getJob + ); + + expect(result?.status).toBe("PUBLISHED"); + expect(refresh).toHaveBeenCalledOnce(); + } +); + test("reopening refresh retries after a rejected status request", async () => { vi.useFakeTimers(); const errorLog = vi.spyOn(console, "error").mockImplementation(() => {}); @@ -136,7 +222,7 @@ test("reopening refresh retries after a rejected status request", async () => { }; try { - const done = refreshUntilSuccess(refresh, () => true); + const done = refreshProjectWithRetry(refresh, () => true); expect(attempts).toBe(1); await vi.advanceTimersByTimeAsync(5_000); await done; @@ -146,6 +232,24 @@ test("reopening refresh retries after a rejected status request", async () => { } }); +test("reopening resumes a retained pending session even after the Build is published", async () => { + const project = { + latestBuildVirtual: { + buildId: "build-1", + createdAt: new Date().toISOString(), + publishStatus: "PUBLISHED", + }, + } as Project; + const onPending = vi.fn(); + await refreshProjectWithRetry( + async () => project, + () => true, + onPending, + () => true + ); + expect(onPending).toHaveBeenCalledWith(project); +}); + test("reopening stops after three unsuccessful project refreshes and shows the error", async () => { vi.useFakeTimers(); $project.set({ id: "project" } as Project); @@ -156,9 +260,9 @@ test("reopening stops after three unsuccessful project refreshes and shows the e })); let isOpen = true; - const done = refreshUntilSuccess( + const done = refreshProjectWithRetry( (showError) => - getRefreshedProject({ projectId: "project", showError, query }), + fetchAndStoreProject({ projectId: "project", showError, query }), () => isOpen ); await vi.advanceTimersByTimeAsync(15_000); @@ -170,59 +274,6 @@ test("reopening stops after three unsuccessful project refreshes and shows the e expect(errorToast).toHaveBeenCalledOnce(); }); -test("a recovered pending build keeps polling after the popover closes", async () => { - vi.useFakeTimers(); - $project.set({ id: "project" } as Project); - $publishDialog.set("publish"); - const successToast = vi.spyOn(toast, "success").mockImplementation(() => ""); - let status: "PENDING" | "PUBLISHED" = "PENDING"; - let pollRequests = 0; - const refreshedProject = () => - ({ - id: "project", - latestBuildVirtual: { - buildId: "recovered", - createdAt: new Date().toISOString(), - publishStatus: status, - }, - }) as Project; - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - await act(async () => container?.querySelector("button")?.click()); - expect(pollRequests).toBe(1); - - $publishDialog.set("none"); - status = "PUBLISHED"; - await act(async () => vi.advanceTimersByTimeAsync(15_000)); - - expect(pollRequests).toBe(2); - expect(successToast).toHaveBeenCalledOnce(); -}); - test("an in-flight status request cannot replace the project after navigation", async () => { const oldProject = { id: "old-project" } as Project; const newProject = { id: "new-project" } as Project; @@ -235,7 +286,7 @@ test("an in-flight status request cannot replace the project after navigation", const query = new Promise<{ success: true; project: Project }>((resolve) => { finishQuery = resolve; }); - const refresh = getRefreshedProject({ + const refresh = fetchAndStoreProject({ projectId: oldProject.id, showError: false, query: () => query, @@ -260,7 +311,7 @@ test("an older popover refresh cannot overwrite a newer result", async () => { } ); let isOpen = true; - const oldRefresh = getRefreshedProject({ + const oldRefresh = fetchAndStoreProject({ projectId: "project", showError: false, query: () => oldQuery, @@ -269,7 +320,7 @@ test("an older popover refresh cannot overwrite a newer result", async () => { isOpen = false; const currentProject = { id: "project", domain: "new" } as Project; - await getRefreshedProject({ + await fetchAndStoreProject({ projectId: "project", showError: false, query: async () => ({ success: true, project: currentProject }), @@ -283,54 +334,6 @@ test("an older popover refresh cannot overwrite a newer result", async () => { expect($project.get()).toBe(currentProject); }); -test("an older recovered poll cannot overwrite a newer popover refresh", async () => { - $project.set({ id: "project" } as Project); - let progress: ReturnType | undefined; - const Harness = () => { - progress = usePublishProgress("project"); - return null; - }; - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - - let finishOldQuery: (result: { - success: true; - project: Project; - }) => void = () => {}; - const oldQuery = new Promise<{ success: true; project: Project }>( - (resolve) => { - finishOldQuery = resolve; - } - ); - const oldGeneration = progress!.beginPopoverRefresh(); - const polling = progress!.watchPendingPublish( - () => - getRefreshedProject({ - projectId: "project", - query: () => oldQuery, - isCurrent: () => progress!.isRefreshCurrent(oldGeneration), - }), - oldGeneration - ); - - const newGeneration = progress!.beginPopoverRefresh(); - const currentProject = { id: "project", domain: "new" } as Project; - await getRefreshedProject({ - projectId: "project", - query: async () => ({ success: true, project: currentProject }), - isCurrent: () => progress!.isRefreshCurrent(newGeneration), - }); - finishOldQuery({ - success: true, - project: { id: "project", domain: "old" } as Project, - }); - await polling; - - expect($project.get()).toBe(currentProject); -}); - test("publish polling stops after navigating to another project", async () => { const oldProject = { id: "old-project" } as Project; const newProject = { id: "new-project" } as Project; @@ -357,50 +360,7 @@ test("publish polling stops after navigating to another project", async () => { expect($project.get()).toBe(newProject); }); -test("an old poll cannot update a newly mounted copy of the same project", async () => { - const firstProject = { id: "project" } as Project; - $project.set(firstProject); - let progress: ReturnType | undefined; - const Harness = () => { - progress = usePublishProgress("project"); - return null; - }; - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - - let finishQuery: (result: { - success: true; - project: Project; - }) => void = () => {}; - const query = new Promise<{ success: true; project: Project }>((resolve) => { - finishQuery = resolve; - }); - const polling = waitForPublishStatus( - () => - getRefreshedProject({ - projectId: "project", - isCurrent: progress!.isCurrentProject, - query: () => query, - }), - progress!.isCurrentProject - ); - - act(() => root?.unmount()); - $project.set({ id: "another-project" } as Project); - const reopenedProject = { id: "project", domain: "new" } as Project; - $project.set(reopenedProject); - finishQuery({ - success: true, - project: { id: "project", domain: "old" } as Project, - }); - - await expect(polling).resolves.toBeUndefined(); - expect($project.get()).toBe(reopenedProject); -}); - -test("publish completion does not show a toast while the Publish panel is open", () => { +test("publish failure updates the banner without a duplicate toast while Publish is open", () => { const successToast = vi.spyOn(toast, "success").mockImplementation(() => ""); const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); const setPublishError = vi.fn(); @@ -409,13 +369,13 @@ test("publish completion does not show a toast while the Publish panel is open", $publishDialog.set("publish"); reportPublishResult({ - result: { status: "PUBLISHED", statusText: publishedStatusText }, + result: { status: "PUBLISHED", statusContent: publishedStatusText }, timesLeft: 11, maxDailyPublishesPerUser: 20, setPublishError, }); reportPublishResult({ - result: { status: "FAILED", statusText: failedStatusText }, + result: { status: "FAILED", statusContent: failedStatusText }, timesLeft: 11, maxDailyPublishesPerUser: 20, setPublishError, @@ -431,7 +391,7 @@ test("an old project completion does not show a success toast over an open Publi $publishDialog.set("publish"); reportPublishResult({ - result: { status: "PUBLISHED", statusText: <>Published }, + result: { status: "PUBLISHED", statusContent: <>Published }, setPublishError: vi.fn(), isCurrentProject: () => false, }); @@ -446,13 +406,13 @@ test("publish completion does not show a success toast in the Export view", () = $publishDialog.set("export"); reportPublishResult({ - result: { status: "PUBLISHED", statusText: <>Published }, + result: { status: "PUBLISHED", statusContent: <>Published }, timesLeft: 11, maxDailyPublishesPerUser: 20, setPublishError, }); reportPublishResult({ - result: { status: "FAILED", statusText: <>Publish failed }, + result: { status: "FAILED", statusContent: <>Publish failed }, timesLeft: 11, maxDailyPublishesPerUser: 20, setPublishError, @@ -471,13 +431,13 @@ test("publish completion shows a toast after the dialog closes", () => { $publishDialog.set("none"); reportPublishResult({ - result: { status: "PUBLISHED", statusText: publishedStatusText }, + result: { status: "PUBLISHED", statusContent: publishedStatusText }, timesLeft: 11, maxDailyPublishesPerUser: 20, setPublishError, }); reportPublishResult({ - result: { status: "FAILED", statusText: failedStatusText }, + result: { status: "FAILED", statusContent: failedStatusText }, timesLeft: 11, maxDailyPublishesPerUser: 20, setPublishError, @@ -485,701 +445,5 @@ test("publish completion shows a toast after the dialog closes", () => { expect(successToast).toHaveBeenCalledOnce(); expect(errorToast).toHaveBeenCalledOnce(); - expect(setPublishError).toHaveBeenCalledWith(failedStatusText); -}); - -test("a rejected publish request shows an inline error while the dialog is open", async () => { - const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); - $publishDialog.set("publish"); - $project.set({ id: "project" } as Project); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - - await act(async () => container?.querySelector("button")?.click()); - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); - expect(errorToast).not.toHaveBeenCalled(); -}); - -test("starting validation clears a previous request failure", async () => { - $project.set({ id: "project" } as Project); - $publishDialog.set("publish"); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [publish, validate] = container.querySelectorAll("button"); - await act(async () => publish.click()); - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); - act(() => validate.click()); - expect(container.querySelector("output")?.textContent).toBe(""); -}); - -test("a rejected publish request shows a toast after the dialog closes", async () => { - const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); - $publishDialog.set("publish"); - $project.set({ id: "project" } as Project); - let rejectPublish: (error: Error) => void = () => {}; - const publish = new Promise((_, reject) => { - rejectPublish = reject; - }); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - act(() => container?.querySelector("button")?.click()); - - $publishDialog.set("none"); - await act(async () => rejectPublish(new Error("Network unavailable"))); - - expect(errorToast).toHaveBeenCalledOnce(); - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); -}); - -test("a rejected publish request appears in the panel reopened before rejection", async () => { - const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); - $publishDialog.set("publish"); - $project.set({ id: "project" } as Project); - let rejectPublish: (error: Error) => void = () => {}; - const publish = new Promise((_, reject) => { - rejectPublish = reject; - }); - - const Harness = () => { - const [isOpen, setIsOpen] = useState(true); - const progress = usePublishProgress("project"); - return ( - <> - - - - {isOpen && {progress.publishError}} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [start, close, reopen] = container.querySelectorAll("button"); - act(() => start.click()); - act(() => close.click()); - act(() => reopen.click()); - - await act(async () => rejectPublish(new Error("Network unavailable"))); - - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); - expect(errorToast).not.toHaveBeenCalled(); -}); - -test("a publish failure remains visible after the panel remounts", () => { - $project.set({ id: "project" } as Project); - $publishDialog.set("publish"); - const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); - - const Harness = () => { - const [isOpen, setIsOpen] = useState(true); - const progress = usePublishProgress("project"); - return ( - <> - - - - {isOpen && {progress.publishError}} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [close, reopen, finish] = container.querySelectorAll("button"); - act(() => close.click()); - act(() => reopen.click()); - act(() => finish.click()); - - expect(container.querySelector("output")?.textContent).toBe("Build failed"); - expect(errorToast).not.toHaveBeenCalled(); -}); - -test("a successful status refresh clears a persisted publish failure", () => { - $project.set({ id: "project" } as Project); - $publishDialog.set("publish"); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [fail, refresh] = container.querySelectorAll("button"); - act(() => fail.click()); - expect(container.querySelector("output")?.textContent).toBe("Publish failed"); - act(() => refresh.click()); - expect(container.querySelector("output")?.textContent).toBe(""); -}); - -test("refreshing a project without a build clears a status error but preserves a request error", () => { - $project.set({ id: "project" } as Project); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [fail, reject, refresh] = container.querySelectorAll("button"); - - act(() => fail.click()); - expect(container.querySelector("output")?.textContent).toBe("Publish failed"); - act(() => refresh.click()); - expect(container.querySelector("output")?.textContent).toBe(""); - - act(() => reject.click()); - act(() => refresh.click()); - expect(container.querySelector("output")?.textContent).toBe( - "Request rejected" - ); -}); - -test("refreshing an older published build preserves a rejected request error", () => { - $project.set({ id: "project" } as Project); - const oldPublishedProject = { - id: "project", - latestBuildVirtual: { - createdAt: new Date().toISOString(), - publishStatus: "PUBLISHED", - }, - } as Project; - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [reject, refresh] = container.querySelectorAll("button"); - act(() => reject.click()); - act(() => refresh.click()); - - expect(container.querySelector("output")?.textContent).toBe( - "Request rejected" - ); -}); - -test("a newer build clears a recovered transport error", async () => { - $project.set({ - id: "project", - latestBuildVirtual: { buildId: "old" }, - } as Project); - $publishDialog.set("publish"); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [publish, oldBuild, refresh] = container.querySelectorAll("button"); - await act(async () => publish.click()); - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); - act(() => oldBuild.click()); - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); - act(() => refresh.click()); - expect(container.querySelector("output")?.textContent).toBe(""); -}); - -test("a recovered failed build replaces a lost response error", async () => { - $project.set({ - id: "project", - latestBuildVirtual: { buildId: "old" }, - } as Project); - $publishDialog.set("publish"); - - const Harness = () => { - const progress = usePublishProgress("project"); - return ( - <> - - - {progress.publishError} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [publish, refresh] = container.querySelectorAll("button"); - await act(async () => publish.click()); - expect(container.querySelector("output")?.textContent).toBe( - "Network unavailable" - ); - act(() => refresh.click()); - expect(container.querySelector("output")?.textContent).toContain( - "Publish failed" - ); -}); - -test("publish diagnostics remain visible after the panel remounts", () => { - $project.set({ id: "project" } as Project); - - const Harness = () => { - const [isOpen, setIsOpen] = useState(true); - const progress = usePublishProgress("project"); - return ( - <> - - - - {isOpen && {progress.publishFindings.length}} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [close, reopen, finish] = container.querySelectorAll("button"); - act(() => close.click()); - act(() => reopen.click()); - act(() => finish.click()); - - expect(container.querySelector("output")?.textContent).toBe("1"); -}); - -test("an older validation cannot replace newer findings", () => { - const finish: ((title: string) => void)[] = []; - - const Harness = () => { - const validation = useManualValidationFindings(); - return ( - <> - - {validation.findings[0]?.title} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const validate = container.querySelector("button")!; - act(() => validate.click()); - act(() => validate.click()); - act(() => finish[1]("new")); - act(() => finish[0]("old")); - - expect(container.querySelector("output")?.textContent).toBe("new"); -}); - -test("manual validation report stays available after the popover reopens", () => { - const Harness = () => { - const [isOpen, setIsOpen] = useState(true); - const { manualValidationFindings } = usePublishProgress("project"); - return ( - <> - - - - {isOpen && ( - - )} - - ); - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - const [close, reopen, validate] = container.querySelectorAll("button"); - act(() => validate.click()); - expect(container.textContent).toContain("Publish check found 1 warning."); - act(() => close.click()); - act(() => reopen.click()); - expect(container.textContent).toContain("Publish check found 1 warning."); - expect( - [...container.querySelectorAll("button")].some( - (button) => button.textContent === "See issues" - ) - ).toBe(true); -}); - -test("reopening shows the domains used by the validation report and submits only those domains", () => { - let validation: ReturnType | undefined; - const Harness = () => { - validation = useManualValidationFindings(); - return null; - }; - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - act(() => { - const session = validation!.begin(["custom.example"]); - validation!.update(session, [ - { severity: "warning", title: "Check", reportText: "Check" }, - ]); - }); - - act(() => root?.unmount()); - $project.set({ - id: "project", - domainsVirtual: [{ status: "ACTIVE", verified: true }], - } as Project); - root = createRoot(container); - const renderCheckboxes = (validatedDomains?: string[]) => - act(() => - root?.render( - -
- - - -
- ) - ); - renderCheckboxes(); - - const form = container.querySelector("form")!; - const [staging, custom] = form.querySelectorAll('[role="checkbox"]'); - expect(staging.getAttribute("aria-checked")).toBe("true"); - expect(custom.getAttribute("aria-checked")).toBe("false"); - - renderCheckboxes(validation!.domains); - expect(staging.getAttribute("aria-checked")).toBe("false"); - expect(custom.getAttribute("aria-checked")).toBe("true"); - expect([...new FormData(form).getAll(domainToPublishName)]).toEqual([ - "custom.example", - ]); - act(() => (custom as HTMLButtonElement).click()); - renderCheckboxes(); - expect(custom.getAttribute("aria-checked")).toBe("false"); - expect([...new FormData(form).getAll(domainToPublishName)]).toEqual([]); -}); - -test("older publish diagnostics cannot replace a newer operation", () => { - let progress: ReturnType | undefined; - const Harness = () => { - progress = usePublishProgress("project"); - return {progress.publishFindings[0]?.title}; - }; - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - - const oldAttempt = progress!.beginPublishDiagnostics(); - const currentAttempt = progress!.beginPublishDiagnostics(); - act(() => - currentAttempt.setFindings([ - { severity: "warning", title: "New", reportText: "New" }, - ]) - ); - act(() => - oldAttempt.setFindings([ - { severity: "warning", title: "Old", reportText: "Old" }, - ]) - ); - - expect(oldAttempt.isCurrent()).toBe(false); - expect(container.querySelector("output")?.textContent).toBe("New"); -}); - -test("a rejected request after project navigation shows a toast", async () => { - $project.set({ id: "old-project" } as Project); - $publishDialog.set("publish"); - const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); - let rejectPublish: (error: Error) => void = () => {}; - const publish = new Promise((_, reject) => { - rejectPublish = reject; - }); - - const Harness = () => { - const progress = usePublishProgress("old-project"); - return ; - }; - - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - act(() => root?.render()); - act(() => container?.querySelector("button")?.click()); - act(() => root?.unmount()); - $project.set({ id: "new-project" } as Project); - - await act(async () => rejectPublish(new Error("Network unavailable"))); - expect(errorToast).toHaveBeenCalledOnce(); + expect(setPublishError).toHaveBeenCalledWith(failedStatusText, undefined); }); diff --git a/apps/builder/app/builder/features/publish/publish-progress.tsx b/apps/builder/app/builder/features/publish/publish-progress.tsx new file mode 100644 index 0000000000..ba211cbd14 --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-progress.tsx @@ -0,0 +1,237 @@ +import { toast } from "@webstudio-is/design-system"; +import type { Project } from "@webstudio-is/project"; +import { $project } from "~/shared/sync/data-stores"; +import { $publishDialog } from "~/builder/shared/nano-states"; +import { nativeClient } from "~/shared/trpc/trpc-client"; +import { + PENDING_TIMEOUT, + getPublishStatusDisplay, + getStaticPublishStatusDisplay, +} from "./publish-status"; + +const STATUS_REFRESH_RETRY_DELAY = 5_000; + +const STATUS_REFRESH_MAX_ATTEMPTS = 3; + +export type PublishExecution = { + projectId: string; + buildId: string; + logHandle?: string; + target?: "site" | "static"; +}; + +export const waitForPublishStatus = async ( + refresh: () => Promise, + isCurrentProject: () => boolean, + previousBuildId?: string, + execution?: PublishExecution, + getJob: (input: { + projectId: string; + jobId: string; + logHandle: string; + }) => Promise<{ status: string; code?: string }> = nativeClient.api.publish + .getJob.query +) => { + let sleepTime = 15000; + const timeToFinish = Date.now() + PENDING_TIMEOUT + 2 * sleepTime; + + while (Date.now() < timeToFinish && isCurrentProject()) { + let runnerSucceeded = false; + try { + let runnerPending = false; + if (execution?.logHandle !== undefined) { + try { + const job = await getJob({ + projectId: execution.projectId, + jobId: execution.buildId, + logHandle: execution.logHandle, + }); + if (isCurrentProject() === false) { + return; + } + if (job.status === "failed") { + return { + status: "FAILED" as const, + statusContent: "Publish failed", + code: job.code, + }; + } + runnerPending = job.status === "pending"; + runnerSucceeded = job.status === "success"; + } catch (error) { + console.error("Could not refresh publish status", error); + } + } + const refreshedProject = await refresh(); + if (isCurrentProject() === false) { + return; + } + const buildId = + execution?.target === "static" + ? refreshedProject?.latestStaticBuild?.buildId + : refreshedProject?.latestBuildVirtual?.buildId; + if ( + refreshedProject !== undefined && + (previousBuildId === undefined || buildId !== previousBuildId) && + (execution === undefined || buildId === execution.buildId) + ) { + const { statusContent, status } = + execution?.target === "static" && + refreshedProject.latestStaticBuild != null + ? getStaticPublishStatusDisplay(refreshedProject.latestStaticBuild) + : refreshedProject.latestBuildVirtual != null + ? getPublishStatusDisplay(refreshedProject.latestBuildVirtual) + : { + statusContent: "Not published", + status: "PENDING" as const, + }; + + const inferredFailure = + status === "FAILED" && + (execution?.target === "static" + ? refreshedProject.latestStaticBuild?.publishStatus + : refreshedProject.latestBuildVirtual?.publishStatus) === "PENDING"; + if ( + !runnerPending && + (status === "PUBLISHED" || status === "FAILED") && + !(runnerSucceeded && inferredFailure) + ) { + return { status, statusContent }; + } + } + } catch (error) { + if (isCurrentProject() === false) { + return; + } + // A failed status request should not stop watching an ongoing publish. + console.error("Could not refresh publish status", error); + } + if (runnerSucceeded && isCurrentProject()) { + return { + status: "PUBLISHED" as const, + statusContent: + execution?.target === "static" ? "Downloaded" : "Published", + }; + } + + await new Promise((resolve) => setTimeout(resolve, sleepTime)); + sleepTime = Math.max(5000, sleepTime - 5000); + } +}; + +export const refreshProjectWithRetry = async ( + refresh: (showError: boolean) => Promise, + isOpen: () => boolean, + onPending: (project: Project) => void = () => {}, + hasSessionPending: (project: Project) => boolean = () => false +) => { + for ( + let attempt = 1; + attempt <= STATUS_REFRESH_MAX_ATTEMPTS && isOpen(); + attempt++ + ) { + const isLastAttempt = attempt === STATUS_REFRESH_MAX_ATTEMPTS; + try { + const refreshedProject = await refresh(isLastAttempt); + if (refreshedProject !== undefined) { + if ( + (refreshedProject.latestBuildVirtual != null && + getPublishStatusDisplay(refreshedProject.latestBuildVirtual) + .status === "PENDING") || + hasSessionPending(refreshedProject) + ) { + onPending(refreshedProject); + } + return; + } + } catch (error) { + console.error("Could not refresh publish status", error); + if (isLastAttempt && isOpen()) { + toast.error(error instanceof Error ? error.message : "Unknown error"); + } + } + + if (isLastAttempt === false && isOpen()) { + await new Promise((resolve) => + setTimeout(resolve, STATUS_REFRESH_RETRY_DELAY) + ); + } + } +}; + +export const reportPublishResult = ({ + result, + buildId, + timesLeft, + maxDailyPublishesPerUser, + setPublishError, + isCurrentProject = () => true, +}: { + result: Awaited>; + buildId?: string; + timesLeft?: number; + maxDailyPublishesPerUser?: number; + setPublishError: (error: string | JSX.Element, buildId?: string) => void; + isCurrentProject?: () => boolean; +}) => { + if (isCurrentProject() === false) { + return; + } + if (result?.status === "PUBLISHED") { + if ($publishDialog.get() === "none") { + toast.success( + <> + The project has been successfully published.{" "} + {timesLeft !== undefined && + maxDailyPublishesPerUser !== undefined && + timesLeft > 0 && + timesLeft <= 10 && ( +
+ You have {timesLeft} out of {maxDailyPublishesPerUser} daily + publications remaining. The counter resets tomorrow. +
+ )} + , + { duration: 10000 } + ); + } + return; + } + + if (result?.status === "FAILED") { + if ($publishDialog.get() !== "publish") { + toast.error(result.statusContent); + } + setPublishError(result.statusContent, buildId); + } +}; + +export const fetchAndStoreProject = async ({ + projectId, + showError = true, + query = () => nativeClient.domain.project.query({ projectId }), + isCurrent = () => true, +}: { + projectId: Project["id"]; + showError?: boolean; + query?: () => ReturnType; + isCurrent?: () => boolean; +}) => { + if ($project.get()?.id !== projectId || !isCurrent()) { + return; + } + + const result = await query(); + if ($project.get()?.id !== projectId || !isCurrent()) { + return; + } + + if (result.success) { + $project.set(result.project); + return result.project; + } + + if (showError) { + toast.error(result.error); + } +}; 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 new file mode 100644 index 0000000000..5c74a8aebe --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-session.render.test.tsx @@ -0,0 +1,437 @@ +import { act } from "react-dom/test-utils"; +import { createRoot, type Root } from "react-dom/client"; +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + expect, + test, + vi, +} from "vitest"; +import { TooltipProvider } from "@webstudio-is/design-system"; +import type { Project } from "@webstudio-is/project"; +import { + createTrpcInterceptor, + deferred, + selectTab, +} from "./publish-test-utils"; + +const encoded = (bytes: number[]) => btoa(String.fromCharCode(...bytes)); +const logRequests: Array<{ + cursor?: number; + projectId: string; + buildId: string; +}> = []; +let publishRequests = 0; +let buildId = "build-1"; +let acceptedBuildId = "previous-build"; +let withHandle = true; +let pendingLogResponses = 0; +let failedLogResponses = 0; +let holdLog: + | { cursor?: number; response: ReturnType> } + | undefined; +let heldJob: ReturnType> | undefined; +let heldPublish: ReturnType> | undefined; +let interceptor: ReturnType; +let PublishButton: typeof import("./publish").PublishButton; +let stores: typeof import("~/shared/sync/data-stores"); +let nanoStates: typeof import("~/shared/nano-states"); +let publishDialog: typeof import("~/builder/shared/nano-states").$publishDialog; +let root: Root; +let container: HTMLDivElement; +const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }; +const originalActEnvironment = reactEnvironment.IS_REACT_ACT_ENVIRONMENT; +const originalScrollIntoView = Object.getOwnPropertyDescriptor( + Element.prototype, + "scrollIntoView" +); + +beforeAll(async () => { + reactEnvironment.IS_REACT_ACT_ENVIRONMENT = true; + Object.defineProperty(Element.prototype, "scrollIntoView", { + configurable: true, + value: () => {}, + }); + vi.resetModules(); + interceptor = createTrpcInterceptor({ + "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); + if (pendingLogResponses > 0) { + pendingLogResponses -= 1; + return { availability: "pending" }; + } + if (failedLogResponses > 0) { + failedLogResponses -= 1; + throw new Error("Temporary log failure"); + } + 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: [], + }), + "api.publish.validate": () => ({ + diagnostics: { mdxErrors: [], mdxOmissions: [] }, + cssValid: true, + }), + }); + interceptor.start(); + PublishButton = (await import("./publish")).PublishButton; + stores = await import("~/shared/sync/data-stores"); + nanoStates = await import("~/shared/nano-states"); + publishDialog = (await import("~/builder/shared/nano-states")).$publishDialog; + (await import("~/shared/csrf.client")).updateCsrfToken("test-token"); +}); + +const project = (id: string) => + ({ + id, + domain: "example", + domainsVirtual: [], + latestStaticBuild: null, + latestBuildVirtual: { + domain: "example", + buildId: "previous-build", + createdAt: new Date().toISOString(), + publishStatus: "PUBLISHED", + }, + }) as unknown as Project; + +beforeEach(() => { + buildId = "build-1"; + acceptedBuildId = "previous-build"; + publishRequests = 0; + logRequests.length = 0; + withHandle = true; + pendingLogResponses = 0; + failedLogResponses = 0; + holdLog = undefined; + heldJob = undefined; + heldPublish = undefined; + nanoStates.$authTokenPermissions.set({ + canClone: true, + canCopy: true, + canPublish: true, + }); + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: true, + }); + stores.$project.set(project("project-1")); + publishDialog.set("publish"); + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); +}); + +afterEach(async () => { + act(() => root.unmount()); + holdLog?.response.resolve(); + heldJob?.resolve({ status: "success" }); + heldPublish?.resolve({ success: true, buildId: "stale-build", findings: [] }); + await act(async () => {}); + container.remove(); + stores.$project.set(undefined); + publishDialog.set("none"); + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: false, + }); + vi.useRealTimers(); +}); + +afterAll(() => { + interceptor.stop(); + vi.resetModules(); + reactEnvironment.IS_REACT_ACT_ENVIRONMENT = originalActEnvironment; + if (originalScrollIntoView === undefined) { + Reflect.deleteProperty(Element.prototype, "scrollIntoView"); + } else { + Object.defineProperty( + Element.prototype, + "scrollIntoView", + originalScrollIntoView + ); + } +}); + +const render = async (projectId = "project-1") => { + await act(async () => + root.render( + + + + ) + ); +}; +const setPaid = async (allowPublishLogs: boolean) => { + await act(async () => + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs, + }) + ); +}; +const publish = async () => { + await act(async () => publishDialog.set("none")); + await act(async () => publishDialog.set("publish")); + const domain = document.body.querySelector( + 'input[name="domainToPublish[]"]' + ); + expect(domain).not.toBeNull(); + if (domain?.checked === false) { + await act(async () => + document.body.querySelector('[role="checkbox"]')?.click() + ); + } + const button = Array.from( + domain!.closest("form")!.querySelectorAll("button") + ).at(-1)!; + await waitFor(() => expect(button.disabled).toBe(false)); + const previousRequests = publishRequests; + await act(async () => button.click()); + await act(async () => + vi.waitFor(() => expect(publishRequests).toBe(previousRequests + 1)) + ); +}; +const openReport = async () => { + await act(async () => + document.body + .querySelector('button[aria-label^="Publish log:"]') + ?.click() + ); + expect(document.body.querySelector('[role="tablist"]')).not.toBeNull(); +}; +const panel = () => + document.body.querySelector( + '[role="tabpanel"][data-state="active"]' + )!; + +const waitFor = async (assertion: () => void) => { + await vi.waitFor(async () => { + await act(async () => {}); + assertion(); + }); +}; +const entries = () => + Array.from( + panel().querySelectorAll('[aria-labelledby^="publish-title-"]') + ); +const changeProject = async (id: string) => { + await act(async () => { + stores.$project.set(project(id)); + }); + await render(id); +}; + +test("a pending publish shows its local start time, then the runner time and duration", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date("2026-11-15T10:00:00.000Z")); + heldJob = deferred(); + await render(); + const localStart = new Date().toLocaleString(); + await publish(); + await openReport(); + // Timestamp and duration formatting are the report's public data contract. + expect(panel().textContent).toContain(`Started: ${localStart}`); + await act(async () => heldJob?.resolve({ status: "success" })); + await waitFor(() => + expect(panel().querySelector("pre")?.textContent).toBe("€") + ); + expect(panel().textContent).toContain( + `Started: ${new Date("2026-11-13T10:00:00.000Z").toLocaleString()}` + ); + expect(panel().textContent).toContain("Duration: 3s"); + await setPaid(false); + expect(panel().textContent).not.toContain("Started:"); + expect(panel().textContent).not.toContain("Duration:"); +}); + +test("retries pending and failed log reads before giving up on the session", async () => { + vi.useFakeTimers(); + pendingLogResponses = 1; + failedLogResponses = 1; + await render(); + await publish(); + await openReport(); + await act(async () => vi.waitFor(() => expect(logRequests).toHaveLength(1))); + await act(async () => vi.advanceTimersByTimeAsync(5_000)); + await act(async () => vi.waitFor(() => expect(logRequests).toHaveLength(2))); + await act(async () => vi.advanceTimersByTimeAsync(5_000)); + await waitFor(() => + expect(panel().querySelector("pre")?.textContent).toBe("€") + ); + expect(logRequests.map(({ cursor }) => cursor)).toEqual([ + undefined, + undefined, + undefined, + 1, + ]); +}); + +test("Free does not fetch logs; upgrading reads UTF-8 from byte zero and preserves issue severity", async () => { + await setPaid(false); + await render(); + await publish(); + await openReport(); + expect(logRequests).toHaveLength(0); + expect(panel().querySelector("pre")).toBeNull(); + expect(panel().querySelector('[role="note"]')).not.toBeNull(); + await setPaid(true); + await waitFor(() => + expect(panel().querySelector("pre")?.textContent).toBe("€") + ); + expect(logRequests.map(({ cursor }) => cursor)).toEqual([undefined, 1]); + for (const [name, message] of [ + ["Errors", "Late error"], + ["Warnings", "Early warning"], + ]) { + await selectTab(name); + expect(panel().textContent).toContain(message); + // Issue truncation is returned by the runner, not inferred from visible issues. + expect(panel().textContent).toContain("1 more issues not shown."); + } + await setPaid(false); + expect(panel().textContent).not.toContain("Late error"); + expect(panel().textContent).not.toContain("Early warning"); + expect(document.body.querySelector("pre")).toBeNull(); +}); + +test("an accepted publish without a log handle is retained without retrying dispatch or reading logs", async () => { + withHandle = false; + await render(); + await publish(); + await openReport(); + expect(entries()).toHaveLength(1); + expect(publishRequests).toBe(1); + expect(logRequests).toHaveLength(0); +}); + +test("a paid response after downgrade cannot restore logs; upgrading restarts from byte zero", async () => { + holdLog = { cursor: 1, response: deferred() }; + await render(); + await publish(); + await act(async () => vi.waitFor(() => expect(logRequests).toHaveLength(2))); + await openReport(); + await setPaid(false); + await act(async () => holdLog?.response.resolve()); + expect(panel().querySelector("pre")).toBeNull(); + await setPaid(true); + await waitFor(() => + expect(panel().querySelector("pre")?.textContent).toBe("€") + ); + expect(logRequests.slice(2).map(({ cursor }) => cursor)).toEqual([ + undefined, + 1, + ]); +}); + +test("a log response from the previous project cannot populate the new project's report", async () => { + holdLog = { response: deferred() }; + await render(); + await publish(); + await act(async () => vi.waitFor(() => expect(logRequests).toHaveLength(1))); + await changeProject("project-2"); + await act(async () => holdLog?.response.resolve()); + await openReport(); + expect(entries()).toHaveLength(0); + expect(logRequests).toHaveLength(1); +}); + +test("a dispatch accepted after leaving and returning to its project cannot restore the old session", async () => { + heldPublish = deferred(); + await render(); + await publish(); + await changeProject("project-2"); + await changeProject("project-1"); + await act(async () => + heldPublish?.resolve({ + success: true, + buildId: "stale-build", + logHandle: "stale-handle", + findings: [], + }) + ); + await openReport(); + expect(entries()).toHaveLength(0); + expect(logRequests).toHaveLength(0); +}); + +test("keeping ten publishes evicts an older in-flight reader before its next page", async () => { + holdLog = { response: deferred() }; + await render(); + await publish(); + await act(async () => vi.waitFor(() => expect(logRequests).toHaveLength(1))); + for (let index = 0; index < 10; index++) { + buildId = `new-build-${index}`; + await publish(); + } + await act(async () => holdLog?.response.resolve()); + await openReport(); + expect(entries()).toHaveLength(10); + expect(document.getElementById("publish-title-build-1")).toBeNull(); + expect( + logRequests.filter((request) => request.buildId === "build-1") + ).toHaveLength(1); +}); diff --git a/apps/builder/app/builder/features/publish/publish-static.test.tsx b/apps/builder/app/builder/features/publish/publish-static.test.tsx new file mode 100644 index 0000000000..e3e8caaca9 --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-static.test.tsx @@ -0,0 +1,321 @@ +import { createRoot, type Root } from "react-dom/client"; +import { act } from "react-dom/test-utils"; +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 { createTrpcInterceptor } from "./publish-test-utils"; + +let root: Root | undefined; +let container: HTMLDivElement | undefined; +let publishModule: typeof import("./publish"); +let nanoStates: typeof import("~/shared/nano-states"); +let publishDialog: typeof import("~/builder/shared/nano-states").$publishDialog; +const acceptedResponse = { + success: true, + buildId: "static-1", + logHandle: "handle-1", + findings: [], + name: "site.zip", +}; +let staticResponse: unknown = acceptedResponse; +let projectStore: (typeof import("~/shared/sync/data-stores"))["$project"]; +let getJobStatus: "pending" | "success" | "failed" = "pending"; +let buildStatus: "PENDING" | "PUBLISHED" = "PUBLISHED"; +let publishRequests = 0; +let jobRequests = 0; +const downloads = vi.fn(); +let interceptor: ReturnType; + +// Observe the real download URL without navigating away from the test runner. +const interceptDownload = (event: NavigateEvent) => { + const url = new URL(event.destination.url); + if (url.pathname.startsWith("/cgi/static/ssg/")) { + event.preventDefault(); + downloads(url.pathname); + } +}; + +( + globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean } +).IS_REACT_ACT_ENVIRONMENT = true; + +beforeAll(async () => { + window.navigation.addEventListener("navigate", interceptDownload); + vi.resetModules(); + interceptor = createTrpcInterceptor({ + "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(), + latestStaticBuild: + publishRequests === 0 + ? null + : { + buildId: "static-1", + updatedAt: new Date().toISOString(), + publishStatus: buildStatus, + }, + }, + }), + }); + interceptor.start(); + publishModule = await import("./publish"); + nanoStates = await import("~/shared/nano-states"); + publishDialog = (await import("~/builder/shared/nano-states")).$publishDialog; + projectStore = (await import("~/shared/sync/data-stores")).$project; + const { updateCsrfToken } = await import("~/shared/csrf.client"); + updateCsrfToken("test-token"); +}); + +afterEach(async () => { + await act(async () => root?.unmount()); + if (vi.isFakeTimers()) { + // Finish queued tRPC batches before switching back to real timers. + await act(async () => vi.runAllTimersAsync()); + } + root = undefined; + container?.remove(); + container = undefined; + projectStore.set(undefined); + publishDialog.set("none"); + getJobStatus = "pending"; + buildStatus = "PUBLISHED"; + staticResponse = acceptedResponse; + publishRequests = 0; + jobRequests = 0; + downloads.mockClear(); + vi.useRealTimers(); + vi.restoreAllMocks(); +}); + +afterAll(() => { + window.navigation.removeEventListener("navigate", interceptDownload); + interceptor.stop(); +}); + +const createProject = (id = "project-a") => + ({ + id, + domain: "example", + domainsVirtual: [], + latestStaticBuild: null, + }) as unknown as Project; + +const staticButton = () => + Array.from(document.body.querySelectorAll("button")).find( + (button) => button.textContent?.startsWith("Build and download static site") + ); + +const render = async (open: boolean, projectId = "project-a") => { + nanoStates.$authTokenPermissions.set({ + canClone: true, + canCopy: true, + canPublish: true, + }); + nanoStates.$planFeatures.set({ + ...nanoStates.$planFeatures.get(), + allowPublishLogs: false, + }); + if (container === undefined) { + container = document.createElement("div"); + document.body.appendChild(container); + root = createRoot(container); + } + await act(async () => { + publishDialog.set(open ? "export" : "none"); + root?.render( + + + + ); + }); + if (open && staticButton() === undefined) { + await act(async () => + document.body + .querySelector('button[role="combobox"]') + ?.dispatchEvent( + new KeyboardEvent("keydown", { key: "Enter", bubbles: true }) + ) + ); + const option = Array.from( + document.body.querySelectorAll('[role="option"]') + ).find((option) => option.textContent?.trim() === "Static"); + expect(option).toBeDefined(); + await act(async () => option?.click()); + } +}; + +test("reopening an active static publish keeps one status owner and one download", async () => { + vi.useFakeTimers(); + buildStatus = "PENDING"; + projectStore.set(createProject()); + await render(true); + const button = staticButton(); + expect(button).toBeDefined(); + await act(async () => button?.click()); + await act(async () => vi.waitFor(() => expect(jobRequests).toBe(1))); + expect(publishRequests).toBe(1); + expect(jobRequests).toBe(1); + expect(downloads).not.toHaveBeenCalled(); + await render(false); + await render(true); + expect(staticButton()?.dataset.state).toBe("pending"); + expect( + document.body.querySelector( + 'button[aria-label="Publish log: Static export"] svg style' + ) + ).toBeNull(); + getJobStatus = "success"; + await act(async () => vi.advanceTimersByTimeAsync(15_000)); + await vi.waitFor(async () => { + await act(async () => {}); + expect(downloads).toHaveBeenCalledOnce(); + }); + expect(downloads).toHaveBeenCalledExactlyOnceWith("/cgi/static/ssg/site.zip"); + expect(staticButton()?.dataset.state).not.toBe("pending"); + expect(staticButton()?.disabled).toBe(false); + expect(document.body.textContent).toContain("Downloaded"); + expect(publishRequests).toBe(1); + expect(jobRequests).toBe(2); +}); + +test("project navigation suppresses an old static download and error toast", async () => { + vi.useFakeTimers(); + const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); + projectStore.set(createProject()); + await render(true); + const button = staticButton(); + expect(button).toBeDefined(); + await act(async () => button?.click()); + await act(async () => vi.waitFor(() => expect(jobRequests).toBe(1))); + await act(async () => + vi.waitFor(() => + expect(projectStore.get()?.latestStaticBuild?.buildId).toBe("static-1") + ) + ); + act(() => projectStore.set(createProject("project-b"))); + await render(false, "project-b"); + act(() => projectStore.set(createProject())); + await render(false, "project-a"); + getJobStatus = "success"; + await act(async () => vi.advanceTimersByTimeAsync(15_000)); + await act(async () => vi.advanceTimersByTimeAsync(1_000)); + expect(downloads).not.toHaveBeenCalled(); + expect(errorToast).not.toHaveBeenCalled(); +}); + +test("a failed static runner clears progress without starting a download", async () => { + vi.useFakeTimers(); + const errorToast = vi.spyOn(toast, "error").mockImplementation(() => ""); + projectStore.set(createProject()); + await render(true); + const button = staticButton(); + expect(button).toBeDefined(); + await act(async () => button?.click()); + await act(async () => vi.waitFor(() => expect(jobRequests).toBe(1))); + await act(async () => + vi.waitFor(() => + expect(projectStore.get()?.latestStaticBuild?.buildId).toBe("static-1") + ) + ); + act(() => + projectStore.set({ + ...projectStore.get()!, + latestStaticBuild: { + buildId: "static-1", + projectId: "project-a", + updatedAt: new Date().toISOString(), + publishStatus: "PENDING", + }, + }) + ); + getJobStatus = "failed"; + await act(async () => vi.advanceTimersByTimeAsync(15_100)); + expect(jobRequests).toBe(2); + expect(downloads).not.toHaveBeenCalled(); + expect(errorToast).toHaveBeenCalledOnce(); + expect(staticButton()?.dataset.state).not.toBe("pending"); + expect(staticButton()?.disabled).toBe(false); + await act(async () => + document.body + .querySelector( + 'button[aria-label="Publish log: Static export"]' + ) + ?.click() + ); + const errors = Array.from( + document.body.querySelectorAll('[role="tab"]') + ).find((tab) => tab.textContent === "Errors"); + expect(errors).toBeDefined(); + await act(async () => userEvent.click(errors!)); + const showLogs = Array.from( + document.body.querySelectorAll("button") + ).find((button) => button.textContent?.trim() === "show logs"); + expect(showLogs).toBeDefined(); + await act(async () => userEvent.click(showLogs!)); + expect( + document.body.querySelector('[role="tab"][aria-selected="true"]') + ?.textContent + ).toBe("Publish"); + expect( + document.body.querySelector( + '[role="tabpanel"][data-state="active"] [role="note"]' + ) + ).not.toBeNull(); +}); + +test("the static status reopens an audit rejection instead of an older successful publish", async () => { + getJobStatus = "success"; + projectStore.set(createProject()); + await render(true); + const publish = staticButton()!; + await act(async () => publish.click()); + await vi.waitFor(async () => { + await act(async () => {}); + expect(downloads).toHaveBeenCalledOnce(); + expect(staticButton()?.dataset.state).not.toBe("pending"); + }); + staticResponse = { + success: false, + auditFindings: [{ severity: "error", message: "audit-rejection" }], + }; + await act(async () => staticButton()?.click()); + const activeTab = () => + document.body.querySelector('[role="tab"][aria-selected="true"]') + ?.textContent; + await vi.waitFor(async () => { + await act(async () => {}); + expect(activeTab()).toBe("Errors"); + }); + await act(async () => + document.body + .querySelector('button[aria-label="Close"]') + ?.click() + ); + await vi.waitFor(async () => { + await act(async () => {}); + expect(document.body.querySelector('[role="dialog"]')).toBeNull(); + }); + await render(true); + await act(async () => + document.body + .querySelector( + 'button[aria-label="Publish log: Static export"]' + ) + ?.click() + ); + expect(activeTab()).toBe("Errors"); +}); diff --git a/apps/builder/app/builder/features/publish/publish-status.test.tsx b/apps/builder/app/builder/features/publish/publish-status.test.tsx index bec979678d..4c32b6daee 100644 --- a/apps/builder/app/builder/features/publish/publish-status.test.tsx +++ b/apps/builder/app/builder/features/publish/publish-status.test.tsx @@ -1,8 +1,6 @@ import { expect, test, vi } from "vitest"; import type { Project } from "@webstudio-is/project"; -import { __testing__ } from "./publish"; - -const { waitForPublishStatus } = __testing__; +import { waitForPublishStatus } from "./publish-progress"; test("a new publish waits past the previous build's failure", async () => { vi.useFakeTimers(); diff --git a/apps/builder/app/builder/features/publish/publish-status.tsx b/apps/builder/app/builder/features/publish/publish-status.tsx new file mode 100644 index 0000000000..e151124a14 --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-status.tsx @@ -0,0 +1,84 @@ +import type { Project } from "@webstudio-is/project"; +import { cssVar } from "@webstudio-is/design-system"; +import { CheckCircleIcon, AlertIcon, SpinnerIcon } from "@webstudio-is/icons"; +import { RelativeTime } from "~/builder/shared/relative-time"; + +export const PENDING_TIMEOUT = + process.env.NODE_ENV === "production" ? 60 * 3 * 1000 : 35000; + +export const getPublishStatusDisplay = ({ + createdAt, + publishStatus, +}: Pick< + NonNullable, + "createdAt" | "publishStatus" +>) => { + let status = publishStatus; + + const delta = Date.now() - new Date(createdAt).getTime(); + // Assume build failed after 3 minutes + + if (publishStatus === "PENDING" && delta > PENDING_TIMEOUT) { + status = "FAILED"; + } + + const statusLabel = + status === "PUBLISHED" + ? "Published" + : status === "FAILED" + ? "Publish failed" + : "Publishing started"; + + const statusContent = ( + <> + {statusLabel} + + ); + + const color = + status === "PUBLISHED" + ? cssVar("--foreground-positive") + : status === "FAILED" + ? cssVar("--foreground-negative") + : cssVar("--foreground-warning"); + const Icon = + status === "PUBLISHED" + ? CheckCircleIcon + : status === "FAILED" + ? AlertIcon + : SpinnerIcon; + + return { statusContent, status, color, Icon }; +}; + +export const getStaticPublishStatusDisplay = ({ + updatedAt, + publishStatus, +}: { + updatedAt: string; + publishStatus: "PENDING" | "FAILED" | "PUBLISHED"; +}) => { + let status = publishStatus; + + const delta = Date.now() - new Date(updatedAt).getTime(); + // Assume build failed after 3 minutes + + if (publishStatus === "PENDING" && delta > PENDING_TIMEOUT) { + status = "FAILED"; + } + + const statusLabel = + status === "PUBLISHED" + ? "Downloaded" + : status === "FAILED" + ? "Download failed" + : "Download started"; + + const statusContent = ( + <> + {statusLabel} + + ); + + return { statusContent, status }; +}; diff --git a/apps/builder/app/builder/features/publish/publish-test-utils.test.ts b/apps/builder/app/builder/features/publish/publish-test-utils.test.ts new file mode 100644 index 0000000000..a66e4171e4 --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-test-utils.test.ts @@ -0,0 +1,63 @@ +import { expect, test } from "vitest"; +import { createTrpcInterceptor } from "./publish-test-utils"; + +const requestUrl = "/trpc/api.publish.getJob?input=%7B%220%22%3Anull%7D"; + +test("reports an unexpected procedure instead of treating it as a network failure", async () => { + const interceptor = createTrpcInterceptor({}); + interceptor.start(); + try { + await expect(fetch(requestUrl)).rejects.toThrow(); + } finally { + expect(() => interceptor.stop()).toThrow("Unexpected request"); + } +}); + +test("preserves an HTTP error response from a procedure", async () => { + const interceptor = createTrpcInterceptor({ + "api.publish.getJob": () => + new Response(JSON.stringify({ error: { message: "Unavailable" } }), { + status: 503, + headers: { "Content-Type": "application/json" }, + }), + }); + interceptor.start(); + try { + const response = await fetch(requestUrl); + expect(response.status).toBe(503); + expect(await response.json()).toEqual({ + error: { message: "Unavailable" }, + }); + } finally { + interceptor.stop(); + } +}); + +test("rejects unsupported request methods", async () => { + const interceptor = createTrpcInterceptor({ + "api.publish.getJob": () => ({ status: "success" }), + }); + interceptor.start(); + try { + await fetch("/trpc/api.publish.getJob", { + method: "PUT", + body: JSON.stringify({ "0": null }), + }).catch(() => {}); + } finally { + expect(() => interceptor.stop()).toThrow("Unexpected request method"); + } +}); + +test("rejects an invalid tRPC batch envelope", async () => { + const interceptor = createTrpcInterceptor({ + "api.publish.getJob": () => ({ status: "success" }), + }); + interceptor.start(); + try { + await expect( + fetch("/trpc/api.publish.getJob?input=null") + ).rejects.toThrow(); + } finally { + expect(() => interceptor.stop()).toThrow("Unexpected request input"); + } +}); 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..ca331b80f1 --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-test-utils.ts @@ -0,0 +1,109 @@ +import { FetchInterceptor } from "@mswjs/interceptors/fetch"; +import { userEvent } from "@vitest/browser/context"; +import { act } from "react-dom/test-utils"; +import { expect } from "vitest"; + +export const selectTab = async (name: string) => { + const tab = Array.from( + document.body.querySelectorAll('[role="tab"]') + ).find((candidate) => candidate.textContent?.startsWith(name)); + expect(tab).toBeDefined(); + await act(async () => userEvent.click(tab!)); +}; + +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 createTrpcInterceptor = ( + handlers: Record unknown | Promise>, + onRequest?: (route: string, input: unknown) => void +) => { + const interceptor = new FetchInterceptor(); + const unexpectedRequests: string[] = []; + interceptor.on("request", async ({ request, controller }) => { + const url = new URL(request.url); + if (url.origin !== location.origin || !url.pathname.startsWith("/trpc/")) { + return; + } + if (request.method !== "GET" && request.method !== "POST") { + const message = `Unexpected request method: ${request.method} ${url.pathname}`; + unexpectedRequests.push(message); + controller.errorWith(new Error(message)); + return; + } + let input: Record; + try { + const parsedInput: unknown = JSON.parse( + request.method === "GET" + ? (url.searchParams.get("input") ?? "{}") + : await request.clone().text() + ); + if ( + parsedInput === null || + typeof parsedInput !== "object" || + Array.isArray(parsedInput) + ) { + throw new Error("Invalid tRPC batch envelope"); + } + input = parsedInput as Record; + } catch (error) { + unexpectedRequests.push(`Unexpected request input: ${url.pathname}`); + controller.errorWith(error); + return; + } + const routes = url.pathname.slice("/trpc/".length).split(","); + const missingRoute = routes.find((route) => handlers[route] === undefined); + if (missingRoute !== undefined) { + const message = `Unexpected request: ${missingRoute}`; + unexpectedRequests.push(message); + controller.errorWith(new Error(message)); + return; + } + try { + const results = await Promise.all( + routes.map(async (route, index) => { + const value = input[String(index)]; + onRequest?.(route, value); + return handlers[route](value); + }) + ); + const response = results.find((result) => result instanceof Response); + if (response !== undefined) { + if (results.length !== 1) { + const message = `Unexpected batched HTTP response: ${url.pathname}`; + unexpectedRequests.push(message); + controller.errorWith(new Error(message)); + return; + } + controller.respondWith(response); + return; + } + controller.respondWith( + new Response( + JSON.stringify(results.map((data) => ({ result: { data } }))), + { + headers: { "Content-Type": "application/json" }, + } + ) + ); + } catch (error) { + controller.errorWith(error); + } + }); + return { + start: () => interceptor.apply(), + stop: () => { + interceptor.dispose(); + if (unexpectedRequests.length > 0) { + throw new Error(unexpectedRequests.join("\n")); + } + }, + }; +}; diff --git a/apps/builder/app/builder/features/publish/publish-ui.tsx b/apps/builder/app/builder/features/publish/publish-ui.tsx new file mode 100644 index 0000000000..4fd0553a64 --- /dev/null +++ b/apps/builder/app/builder/features/publish/publish-ui.tsx @@ -0,0 +1,1216 @@ +import stripIndent from "strip-indent"; +import { computed } from "nanostores"; +import { + useEffect, + useState, + useOptimistic, + startTransition, + useRef, + useId, +} from "react"; +import { useStore } from "@nanostores/react"; +import { + PanelContent, + Button, + cssVar, + Tooltip, + InfoTooltip, + IconButton, + Grid, + Flex, + Label, + Text, + InputField, + Separator, + ScrollArea, + rawTheme, + Select, + theme, + TextArea, + Link, + LinkButton, + PanelBanner, + toast, + RadioGroup, + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, + PopoverTitle, + PopoverClose, + PopoverTitleActions, + css, + textVariants, + SmallIconButton, +} from "@webstudio-is/design-system"; +import { validateProjectDomain, type Project } from "@webstudio-is/project"; +import { + $selectedPageId, + selectInstance, + $editingPageId, + $permissions, + $stagingUsername, + $stagingPassword, +} from "~/shared/nano-states"; +import { + $publisherHost, + $project, + $dataSources, + $instances, + $pages, + $projectSettings, + $resources, +} from "~/shared/sync/data-stores"; +import { setActiveSidebarPanel } from "../../shared/nano-states"; +import { Domains } from "./domains"; +import { CollapsibleDomainSection } from "./collapsible-domain-section"; +import { + ActivityIcon, + AlertIcon, + CheckCircleIcon, + CopyIcon, + GearIcon, + UpgradeIcon, + HelpIcon, + InfoCircleIcon, + EllipsesIcon, + PlusIcon, + TerminalIcon, +} from "@webstudio-is/icons"; +import { AddDomain } from "./add-domain"; +import { humanizeString } from "~/shared/string-utils"; +import { trpcClient, nativeClient } from "~/shared/trpc/trpc-client"; +import type { Templates } from "@webstudio-is/sdk"; +import { DomainCheckbox, domainToPublishName } from "./domain-checkbox"; +import { CopyToClipboard } from "~/shared/copy-to-clipboard"; +import { $openProjectSettings } from "~/shared/nano-states/project-settings"; +import cmsUpgradeBanner from "~/shared/cms-upgrade-banner.svg?url"; +import { $currentSystem } from "~/shared/system"; +import { getPublishUrl } from "./publish-url"; +import { + getRestrictedFeatures, + type RestrictedFeature, +} from "./restricted-features"; +import { PublishValidationBanner, type DiagnosticFinding } from "./diagnostics"; +import type { SessionPublish } from "./session-publishes"; +import { PublishActions, type PublishValidationState } from "./publish-actions"; +import { fetchAndStoreProject } from "./publish-progress"; +import { + getPublishStatusDisplay, + getStaticPublishStatusDisplay, +} from "./publish-status"; +import { DomainStatusButton } from "./domain-status-button"; + +type PublishUiState = { + isPublishing: boolean; + countdown?: number; + validationState: PublishValidationState; + validatedDomains?: string[]; + invalidateValidation: () => void; + publishes: SessionPublish[]; + siteError?: string | JSX.Element; + siteErrorSource?: "request" | "transport" | "status"; + siteFindings: DiagnosticFinding[]; + siteHasValidationResult: boolean; + staticFailureFinding?: DiagnosticFinding; + openSiteReport: ( + domain: string | undefined, + tab: "warnings" | "errors" | "publish" + ) => void; + openStaticReport: (tab?: "warnings" | "errors" | "publish") => void; + validate: (domains: string[]) => Promise; + publishSite: ( + domains: string[], + timesLeft: number, + maxDailyPublishesPerUser: number + ) => void; + exportStatic: (templates: readonly Templates[]) => void; +}; + +type StaticPublishUiState = Pick< + PublishUiState, + | "isPublishing" + | "publishes" + | "staticFailureFinding" + | "openStaticReport" + | "exportStatic" +>; + +const PublishSuccessBanner = ({ + message, + onOpen, +}: { + message: string; + onOpen: () => void; +}) => ( + + + {message} + + + +); + +type ChangeProjectDomainProps = { + project: Project; + refresh: () => Promise; + validatedDomains?: readonly string[]; + onOpenReport: (domain: string) => void; + latestPublish?: SessionPublish; +}; + +const ChangeProjectDomain = ({ + project, + refresh, + validatedDomains, + onOpenReport, + latestPublish, +}: ChangeProjectDomainProps) => { + const id = useId(); + const currentSystem = useStore($currentSystem); + const stagingUsername = useStore($stagingUsername); + const stagingPassword = useStore($stagingPassword); + const publisherHost = useStore($publisherHost); + + const [domain, setDomain] = useState(project.domain); + const [error, setError] = useState(); + const [isUpdateInProgress, setIsUpdateInProgress] = useOptimistic(false); + const [isUnpublishing, setIsUnpublishing] = useOptimistic(false); + + const pageUrl = getPublishUrl({ + domain: `${project.domain}.${publisherHost}`, + pathname: currentSystem.pathname, + username: stagingUsername, + password: stagingPassword, + }); + + const updateProjectDomain = async () => { + setIsUpdateInProgress(true); + const validationResult = validateProjectDomain(domain); + + if (validationResult.success === false) { + setError(validationResult.error); + return; + } + + const updateResult = await nativeClient.domain.updateProjectDomain.mutate({ + domain, + projectId: project.id, + }); + + if (updateResult.success === false) { + setError(updateResult.error); + return; + } + + await refresh(); + }; + + const handleUpdateProjectDomain = () => { + startTransition(async () => { + await updateProjectDomain(); + }); + }; + + const handleUnpublish = async () => { + setIsUnpublishing(true); + const result = await nativeClient.domain.unpublish.mutate({ + projectId: project.id, + domain: `${project.domain}.${publisherHost}`, + }); + if (result.success === false) { + toast.error(result.message); + return; + } + await refresh(); + toast.success(result.message); + }; + + const latestProjectDomainBuild = + project.latestBuildVirtual?.domain === project.domain + ? project.latestBuildVirtual + : undefined; + + const { statusContent, color, Icon } = + latestProjectDomainBuild != null + ? getPublishStatusDisplay(latestProjectDomainBuild) + : { + statusContent: "Not published", + color: cssVar("--foreground-secondary"), + Icon: InfoCircleIcon, + }; + + const isPublished = latestProjectDomainBuild != null; + + return ( + + } + suffix={ + + {statusContent}, + }} + onOpenReport={() => onOpenReport(project.domain)} + /> + + + + + + + + } + > + + + + + + + { + setError(undefined); + setDomain(event.target.value); + }} + onBlur={handleUpdateProjectDomain} + onKeyDown={(event) => { + if (event.key === "Enter") { + handleUpdateProjectDomain(); + } + + if (event.key === "Escape") { + if (project.domain !== domain) { + setDomain(project.domain); + event.preventDefault(); + } + } + }} + color={error !== undefined ? "error" : undefined} + /> + {error !== undefined && {error}} + + {stagingUsername && ( + + + + + )} + {stagingPassword && ( + + + + + + + + )} + {isPublished && ( + + + + )} + + + ); +}; + +const $restrictedFeatures = computed( + [ + $pages, + $projectSettings, + $dataSources, + $resources, + $instances, + $permissions, + ], + (pages, projectSettings, dataSources, resources, instances, permissions) => + getRestrictedFeatures({ + pages, + projectSettings, + dataSources, + resources, + instances, + permissions, + }) +); + +const matchesValidatedDomains = (form: HTMLFormElement, domains: string[]) => { + const selected = new Set(domains); + const current = new FormData(form) + .getAll(domainToPublishName) + .map((domain) => domain.toString()); + return ( + current.length === selected.size && + current.every((domain) => selected.has(domain)) + ); +}; + +const Publish = ({ + project, + quota, + restrictedFeatures, + flow, +}: { + project: Project; + quota: { userPublishCount: number; maxDailyPublishesPerUser: number }; + restrictedFeatures: Map; + flow: PublishUiState; +}) => { + const { + isPublishing, + countdown, + validationState, + validatedDomains, + invalidateValidation, + publishes, + siteError, + siteErrorSource, + openSiteReport: onOpenReport, + } = flow; + const { userPublishCount, maxDailyPublishesPerUser } = quota; + const buttonRef = useRef(null); + const [hasSelectedDomains, setHasSelectedDomains] = useState(false); + const [hasCustomDomainsSelected, setHasCustomDomainsSelected] = + useState(false); + const previousDomainsKey = useRef(); + const latestSitePublish = publishes.find(({ target }) => target === "site"); + const hasPendingState = project.latestBuildVirtual + ? latestSitePublish?.buildId === project.latestBuildVirtual.buildId + ? latestSitePublish.status === "pending" + : getPublishStatusDisplay(project.latestBuildVirtual).status === "PENDING" + : false; + const isPublishInProgress = isPublishing || hasPendingState; + + useEffect(() => { + const form = buttonRef.current?.closest("form"); + + if (form == null) { + return; + } + + const handleFormInput = () => { + const formData = new FormData(form); + const domainsSelected = formData + .getAll(domainToPublishName) + .map((domain) => domain.toString()); + const domainsKey = domainsSelected.join("\u0000"); + + if ( + previousDomainsKey.current !== undefined && + previousDomainsKey.current !== domainsKey + ) { + invalidateValidation(); + } + previousDomainsKey.current = domainsKey; + + setHasSelectedDomains(domainsSelected.length > 0); + + // Check if any custom domains are selected + // Custom domains are those that are NOT the staging domain (project.domain) + const hasCustom = domainsSelected.some( + (domain) => domain !== project.domain + ); + setHasCustomDomainsSelected(hasCustom); + }; + + const observer = new MutationObserver(() => { + handleFormInput(); + }); + + observer.observe(form, { + attributes: true, + childList: true, + subtree: true, + attributeFilter: ["value", "checked"], + }); + + if (validatedDomains !== undefined) { + if (matchesValidatedDomains(form, validatedDomains)) { + previousDomainsKey.current = validatedDomains.join("\u0000"); + } else { + invalidateValidation(); + } + } + + handleFormInput(); + + return () => { + observer.disconnect(); + }; + }, [invalidateValidation, project.domain, validatedDomains]); + + const getDomainsFromForm = (formData: FormData) => + formData + .getAll(domainToPublishName) + .map((domainEntry) => domainEntry.toString()); + + const getForm = () => buttonRef.current?.closest("form"); + const findings = flow.siteFindings; + const hasSessionPublish = latestSitePublish !== undefined; + + return ( + + {siteError !== undefined ? ( + + + + {typeof siteError === "string" + ? siteError.slice(0, 160) + : siteError} + + + + + ) : latestSitePublish?.status === "success" && + !isPublishInProgress && + !flow.siteHasValidationResult ? ( + onOpenReport(undefined, "publish")} + /> + ) : ( + + onOpenReport( + undefined, + findings.some(({ severity }) => severity === "error") + ? "errors" + : "warnings" + ) + } + /> + )} + 0 && hasCustomDomainsSelected) || + userPublishCount >= maxDailyPublishesPerUser + } + publishInProgress={isPublishInProgress} + publishPending={ + isPublishInProgress && (countdown === undefined || countdown === 0) + } + hasSelectedDomains={hasSelectedDomains} + publishLabel={ + countdown !== undefined && countdown > 0 + ? `Publishing (${countdown}s)` + : "Publish" + } + onValidate={async () => { + const form = getForm(); + if (form) { + await flow.validate(getDomainsFromForm(new FormData(form))); + } + }} + onPublish={() => { + const form = getForm(); + if (form) { + flow.publishSite( + getDomainsFromForm(new FormData(form)), + maxDailyPublishesPerUser - userPublishCount, + maxDailyPublishesPerUser + ); + } + }} + /> + + ); +}; + +const PublishStatic = ({ + templates, + flow, +}: { + templates: readonly Templates[]; + flow: StaticPublishUiState; +}) => { + const { + isPublishing, + publishes, + staticFailureFinding, + openStaticReport: onOpenReport, + } = flow; + const project = useStore($project); + + if (project == null) { + throw new Error("Project not found"); + } + + const { status, statusContent } = + project.latestStaticBuild == null + ? { status: "LOADED" as const, statusContent: "Not published" } + : getStaticPublishStatusDisplay(project.latestStaticBuild); + const latestPublish = publishes.find((item) => item.target === "static"); + const logStatus = + staticFailureFinding !== undefined + ? "FAILED" + : latestPublish?.status === "pending" + ? "PENDING" + : latestPublish?.status === "failed" + ? "FAILED" + : latestPublish?.status === "success" + ? "PUBLISHED" + : status; + + const isPublishInProgress = + isPublishing || + (latestPublish !== undefined && + latestPublish.buildId === project.latestStaticBuild?.buildId + ? latestPublish.status === "pending" + : status === "PENDING"); + + return ( + + {latestPublish?.status === "success" && + latestPublish.staticName !== undefined && + !isPublishInProgress && + staticFailureFinding === undefined && ( + onOpenReport("publish")} + /> + )} + + + onOpenReport()} + > + {logStatus === "FAILED" ? ( + + ) : logStatus === "PUBLISHED" ? ( + + ) : ( + + )} + + + + + + + + + ); +}; + +const refreshProject = async () => { + await fetchAndStoreProject({ projectId: $project.get()!.id }); +}; + +const buttonLinkClass = css({ + all: "unset", + cursor: "pointer", + ...textVariants.link, +}).toString(); + +const UpgradeBanner = ({ + hasCustomDomains, + quota, +}: { + hasCustomDomains: boolean; + quota: { userPublishCount: number; maxDailyPublishesPerUser: number }; +}) => { + const restrictedFeatures = useStore($restrictedFeatures); + const { load, data } = trpcClient.domain.countTotalDomains.useQuery(); + const { maxDomainsAllowedPerUser } = useStore($permissions); + const project = useStore($project); + const activeDomainsCount = project?.domainsVirtual.filter( + (domain) => domain.status === "ACTIVE" && domain.verified + ).length; + useEffect(() => { + if (project?.id !== undefined) { + load({ projectId: project.id }); + } + }, [load, activeDomainsCount, project?.id]); + const canAddDomain = data + ? data.success && data.data < maxDomainsAllowedPerUser + : true; + const { userPublishCount, maxDailyPublishesPerUser } = quota; + if (userPublishCount >= maxDailyPublishesPerUser) { + return ( + + + Upgrade to publish more than {maxDailyPublishesPerUser} times per day: + + + Upgrade + + + ); + } + + // Only show Pro feature upgrade banner if custom domains are available + // Free tier users can still publish to staging domain with Pro features + if (restrictedFeatures.size > 0 && hasCustomDomains) { + return ( + + Upgrade for CMS + Following Pro features are used: + + {Array.from(restrictedFeatures).map( + ([message, { navigate, view, info } = {}], index) => ( +
  • + + {navigate ? ( + + ) : ( + message + )} + {info && ( + + } /> + + )} + +
  • + ) + )} +
    + + You can delete these features or upgrade to publish to custom domains. + + + + + Upgrade to Pro + + +
    + ); + } + if (canAddDomain === false) { + return ( + + + + Upgrade to a Pro account + {" "} + to add unlimited domains and publish to each domain individually. + + + + + Upgrade to Pro + + + + ); + } +}; + +export const Content = (props: { + projectId: Project["id"]; + onExportClick: () => void; + flow: PublishUiState; +}) => { + const restrictedFeatures = useStore($restrictedFeatures); + const [newDomains, setNewDomains] = useState(new Set()); + const [isAddingDomain, setIsAddingDomain] = useState(false); + + const project = useStore($project); + + if (project == null) { + throw new Error("Project not found"); + } + + const { load: loadPublishCount, data: publishCount } = + trpcClient.project.userPublishCount.useQuery(); + const { maxDailyPublishesPerUser } = useStore($permissions); + useEffect(() => { + loadPublishCount({ projectId: project.id }); + }, [loadPublishCount, project.id]); + const quota = { + userPublishCount: publishCount?.success ? publishCount.data : 0, + maxDailyPublishesPerUser: + publishCount?.success && "limit" in publishCount + ? publishCount.limit + : maxDailyPublishesPerUser, + }; + + const hasUnpublishedDomains = project.domainsVirtual.some( + (domain) => + domain.verified && + domain.status === "ACTIVE" && + domain.latestBuildVirtual == null + ); + + // Check if any custom domains exist (active and verified) + const hasCustomDomains = project.domainsVirtual.some( + (domain) => domain.status === "ACTIVE" && domain.verified + ); + const hasSitePublish = props.flow.publishes.some( + ({ target }) => target === "site" + ); + const diagnosticFindings = props.flow.siteFindings; + const hasDiagnostics = + hasSitePublish || + diagnosticFindings.length > 0 || + props.flow.siteError !== undefined; + + return ( + <> + + + + + + + + + } + onSelect={() => setIsAddingDomain(true)} + > + Add new domain + + } + onSelect={props.onExportClick} + > + Export + + } + disabled={!hasDiagnostics} + onSelect={() => + props.flow.openSiteReport( + undefined, + hasSitePublish + ? "publish" + : props.flow.siteError !== undefined || + diagnosticFindings.some( + ({ severity }) => severity === "error" + ) + ? "errors" + : "warnings" + ) + } + > + Diagnostics + + + } + onSelect={() => $openProjectSettings.set("publish")} + > + Publish settings + + + + + + } + > + Publish + +
    + + + + props.flow.openSiteReport(domain, "publish") + } + latestPublish={props.flow.publishes.find( + (item) => + item.target === "site" && + item.domains.includes(project.domain) + )} + /> + + + props.flow.openSiteReport(domain, "publish") + } + sessionPublishes={props.flow.publishes} + /> + + + + + + + { + setNewDomains((prev) => new Set([...prev, domain])); + }} + /> + {isAddingDomain && } + + {hasUnpublishedDomains && ( + + + + Don't forget to publish + + + You have a custom domain that hasn't been published yet. Hit + publish to make it live. + + + )} + + +
    + + ); +}; + +type DeployTarget = { + docs?: string; + command?: string; + ssgTemplates?: Templates[]; +}; + +const deployTargets: Record = { + docker: { + docs: "https://docs.docker.com", + command: ` + docker build -t my-image . + docker run my-image + `, + }, + static: { + ssgTemplates: ["ssg"], + }, + vercel: { + docs: "https://vercel.com/docs/cli", + command: "npx vercel@latest", + ssgTemplates: ["ssg-vercel"], + }, + netlify: { + docs: "https://docs.netlify.com/cli/get-started/", + command: ` +npx netlify-cli@latest login +npx netlify-cli sites:create +npx netlify-cli build +npx netlify-cli deploy`, + ssgTemplates: ["ssg-netlify"], + }, +}; + +type DeployTargets = keyof typeof deployTargets; + +const isDeployTargets = (value: string): value is DeployTargets => + Object.keys(deployTargets).includes(value); + +export const ExportContent = (props: { flow: StaticPublishUiState }) => { + const npxCommand = "npx webstudio@latest"; + const [deployTarget, setDeployTarget] = useState("docker"); + + return ( + + +
    + + + Destination + + +