mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-01 21:05:42 +09:00
feat: show publish logs in Builder, CLI, and MCP (#6690)
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. Commitd340a5225is 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 beforea04d6c287cand 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 ona04d6c287c. 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
This commit is contained in:
1 parent
23c81d64c9
commit
896a383e32
90 files changed
+11422
-3968
No files matched your search
@@ -68,6 +68,7 @@ PLANS='[
|
||||
"allowAuth": true,
|
||||
"allowContentMode": true,
|
||||
"allowStagingPublish": true,
|
||||
"allowPublishLogs": true,
|
||||
"maxContactEmailsPerProject": 5,
|
||||
"maxDomainsAllowedPerUser": 200,
|
||||
"maxDailyPublishesPerUser": 100,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
>;
|
||||
@@ -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<typeof nativeClient.build.contentDatabasePublishDiagnostics.query>
|
||||
@@ -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: (
|
||||
<Flex direction="column" gap={2}>
|
||||
@@ -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: (
|
||||
<Flex direction="column" gap={2}>
|
||||
|
||||
@@ -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<DiagnosticFinding>((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,
|
||||
};
|
||||
};
|
||||
+7
-11
@@ -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 (
|
||||
<StorySection title="Publish validation">
|
||||
<PublishValidationResults findings={findings} />
|
||||
<PublishDiagnosticsDialog findings={findings} />
|
||||
</StorySection>
|
||||
);
|
||||
};
|
||||
@@ -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(
|
||||
<TooltipProvider>
|
||||
<PublishDiagnosticsDialog
|
||||
findings={findings}
|
||||
canViewPublishLogs={canViewPublishLogs}
|
||||
items={items}
|
||||
onLoadLog={onLoadLog}
|
||||
open={open}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
});
|
||||
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<HTMLElement>('[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 = <div data-overflow-content style={{ height: 2000 }} />;
|
||||
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<HTMLElement>(
|
||||
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(
|
||||
<PublishValidationBanner findings={[]} passed onOpen={vi.fn()} />
|
||||
);
|
||||
});
|
||||
|
||||
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<HTMLButtonElement>(
|
||||
'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: <button>Show element</button>,
|
||||
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(
|
||||
<TooltipProvider>
|
||||
<PublishDiagnosticsDialog
|
||||
findings={[createFinding("warning", 0)]}
|
||||
items={[item]}
|
||||
onLoadLog={onLoadLog}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
);
|
||||
});
|
||||
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<HTMLButtonElement>(
|
||||
'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<HTMLButtonElement>("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<HTMLButtonElement>(
|
||||
'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<HTMLButtonElement>(
|
||||
'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<HTMLElement>('[role="dialog"]');
|
||||
const titleButton = document.body.querySelector<HTMLButtonElement>(
|
||||
"button[aria-labelledby]"
|
||||
);
|
||||
const title = document.getElementById(
|
||||
titleButton?.getAttribute("aria-labelledby") ?? ""
|
||||
);
|
||||
const log = document.body.querySelector<HTMLElement>("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<HTMLButtonElement>(
|
||||
'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<HTMLButtonElement>("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: <a href="#element">Show element</a>,
|
||||
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<HTMLAnchorElement>('a[href="#element"]');
|
||||
expect(link).not.toBeNull();
|
||||
await act(async () => userEvent.click(link as HTMLElement));
|
||||
expect(document.body.querySelector('[role="dialog"]')).toBeNull();
|
||||
});
|
||||
@@ -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 ? (
|
||||
<PanelBanner variant="success" role="status">
|
||||
<Text>Validation passed. Ready to publish.</Text>
|
||||
</PanelBanner>
|
||||
) : 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 (
|
||||
<PanelBanner variant={errors.length > 0 ? "error" : "warning"}>
|
||||
<Flex align="center" justify="between" gap={2}>
|
||||
<Text css={{ flex: 1, minWidth: 0 }}>
|
||||
Publish check found {countLabel}.{" "}
|
||||
{errors.length > 0 && "Fix the errors before publishing."}
|
||||
</Text>
|
||||
<Button
|
||||
type="button"
|
||||
color="ghost"
|
||||
css={{ flexShrink: 0 }}
|
||||
onClick={onOpen}
|
||||
>
|
||||
See issues
|
||||
</Button>
|
||||
</Flex>
|
||||
</PanelBanner>
|
||||
);
|
||||
};
|
||||
|
||||
const FindingList = ({
|
||||
findings,
|
||||
canViewPublishLogs,
|
||||
onSelect,
|
||||
onOpenPublish,
|
||||
issuesOmitted = 0,
|
||||
publishBuildIds,
|
||||
}: {
|
||||
findings: DiagnosticFinding[];
|
||||
canViewPublishLogs: boolean;
|
||||
onSelect: (finding: DiagnosticFinding) => void;
|
||||
onOpenPublish?: () => void;
|
||||
issuesOmitted?: number;
|
||||
publishBuildIds: string[];
|
||||
}) => (
|
||||
<ScrollAreaNative css={{ height: "100%" }}>
|
||||
<PanelContent as={Flex} direction="column" gap={3}>
|
||||
{findings.map((finding, index) => (
|
||||
<Fragment key={`${finding.severity}-${index}`}>
|
||||
<Flex direction="column" gap={2}>
|
||||
{finding.source !== "publish" && (
|
||||
<Text color="subtle" variant="labels">
|
||||
{finding.source === "build" ? "Build" : "Audit"}
|
||||
</Text>
|
||||
)}
|
||||
{finding.source === "publish" ? (
|
||||
<Text variant="labels" userSelect="text">
|
||||
{canViewPublishLogs ? finding.title : shortFinding(finding)}
|
||||
{onOpenPublish !== undefined &&
|
||||
finding.buildId !== undefined &&
|
||||
publishBuildIds.includes(finding.buildId) && (
|
||||
<>
|
||||
{" "}
|
||||
<Link
|
||||
as="button"
|
||||
type="button"
|
||||
variant="inherit"
|
||||
color="inherit"
|
||||
underline="always"
|
||||
css={{ border: 0, padding: 0, background: "none" }}
|
||||
onClick={onOpenPublish}
|
||||
>
|
||||
show logs
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</Text>
|
||||
) : canViewPublishLogs ? (
|
||||
<Button
|
||||
type="button"
|
||||
color="ghost"
|
||||
onClick={() => onSelect(finding)}
|
||||
>
|
||||
{finding.title}
|
||||
</Button>
|
||||
) : (
|
||||
<Text variant="labels" userSelect="text">
|
||||
{shortFinding(finding)}
|
||||
</Text>
|
||||
)}
|
||||
</Flex>
|
||||
{index < findings.length - 1 && <Separator />}
|
||||
</Fragment>
|
||||
))}
|
||||
{canViewPublishLogs && issuesOmitted > 0 && (
|
||||
<Text color="subtle">{issuesOmitted} more issues not shown.</Text>
|
||||
)}
|
||||
</PanelContent>
|
||||
</ScrollAreaNative>
|
||||
);
|
||||
|
||||
const FindingDetails = ({
|
||||
finding,
|
||||
onBack,
|
||||
onNavigate,
|
||||
}: {
|
||||
finding: DiagnosticFinding;
|
||||
onBack: () => void;
|
||||
onNavigate: () => void;
|
||||
}) => (
|
||||
<PanelContent
|
||||
as={Flex}
|
||||
direction="column"
|
||||
gap={3}
|
||||
css={{ minHeight: 0, flex: 1 }}
|
||||
>
|
||||
<Button type="button" color="neutral" onClick={onBack}>
|
||||
Back
|
||||
</Button>
|
||||
<Text variant="titles" userSelect="text">
|
||||
{finding.title}
|
||||
</Text>
|
||||
{finding.details !== undefined && (
|
||||
<ScrollAreaNative css={{ minHeight: 0, flex: 1 }}>
|
||||
<Text css={{ userSelect: "text" }}>{finding.details}</Text>
|
||||
</ScrollAreaNative>
|
||||
)}
|
||||
<div
|
||||
onClick={(event) => {
|
||||
if (
|
||||
event.button !== 0 ||
|
||||
event.metaKey ||
|
||||
event.ctrlKey ||
|
||||
event.shiftKey ||
|
||||
event.altKey
|
||||
) {
|
||||
return;
|
||||
}
|
||||
onNavigate();
|
||||
}}
|
||||
>
|
||||
{finding.link}
|
||||
</div>
|
||||
</PanelContent>
|
||||
);
|
||||
|
||||
const SessionPublishEntry = ({
|
||||
item,
|
||||
defaultOpen,
|
||||
canViewPublishLogs,
|
||||
}: {
|
||||
item: SessionPublish;
|
||||
defaultOpen: boolean;
|
||||
canViewPublishLogs: boolean;
|
||||
}) => {
|
||||
const duration = getPublishDuration(item);
|
||||
return (
|
||||
<Collapsible.Root asChild defaultOpen={defaultOpen}>
|
||||
<Flex direction="column" gap={2}>
|
||||
<Collapsible.Trigger asChild>
|
||||
<SectionTitle
|
||||
aria-labelledby={`publish-title-${item.buildId}`}
|
||||
suffixPlaceholder={<CopyIcon aria-hidden />}
|
||||
suffix={
|
||||
canViewPublishLogs &&
|
||||
item.logState === "available" &&
|
||||
item.logText !== undefined && (
|
||||
<CopyToClipboard text={item.logText} copyText="Copy log">
|
||||
<IconButton
|
||||
type="button"
|
||||
aria-label="Copy log"
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
<CopyIcon aria-hidden />
|
||||
</IconButton>
|
||||
</CopyToClipboard>
|
||||
)
|
||||
}
|
||||
>
|
||||
<Text
|
||||
as="span"
|
||||
id={`publish-title-${item.buildId}`}
|
||||
variant="titles"
|
||||
truncate
|
||||
css={{ flex: "0 1 auto", minWidth: 0 }}
|
||||
>
|
||||
{item.domains.length > 0
|
||||
? item.domains.join(", ")
|
||||
: "Static export"}
|
||||
</Text>
|
||||
</SectionTitle>
|
||||
</Collapsible.Trigger>
|
||||
<Collapsible.Content asChild>
|
||||
<Flex
|
||||
direction="column"
|
||||
gap={2}
|
||||
css={{
|
||||
paddingInline: theme.panel.paddingInline,
|
||||
}}
|
||||
>
|
||||
<Text color="subtle">{publishLogStatus[item.status].text}</Text>
|
||||
{canViewPublishLogs && item.startedAt !== undefined && (
|
||||
<Text>Started: {new Date(item.startedAt).toLocaleString()}</Text>
|
||||
)}
|
||||
{canViewPublishLogs && duration !== undefined && (
|
||||
<Text>Duration: {duration}s</Text>
|
||||
)}
|
||||
{canViewPublishLogs &&
|
||||
item.status === "failed" &&
|
||||
(item.failedStage !== undefined || item.code !== undefined) && (
|
||||
<Text color="destructive">
|
||||
{[item.failedStage, item.code?.replaceAll("_", " ")]
|
||||
.filter(Boolean)
|
||||
.join(" · ")}
|
||||
</Text>
|
||||
)}
|
||||
{canViewPublishLogs &&
|
||||
item.status !== "pending" &&
|
||||
(item.logState === "available" ? (
|
||||
<Text
|
||||
as="pre"
|
||||
variant="mono"
|
||||
userSelect="text"
|
||||
css={{
|
||||
whiteSpace: "pre-wrap",
|
||||
overflowWrap: "anywhere",
|
||||
}}
|
||||
>
|
||||
{item.logText}
|
||||
</Text>
|
||||
) : (
|
||||
<Text color="subtle">
|
||||
{item.logHandle === undefined ||
|
||||
item.logState === "unavailable"
|
||||
? "Publish logs are unavailable."
|
||||
: "Loading logs…"}
|
||||
</Text>
|
||||
))}
|
||||
</Flex>
|
||||
</Collapsible.Content>
|
||||
<Separator />
|
||||
</Flex>
|
||||
</Collapsible.Root>
|
||||
);
|
||||
};
|
||||
|
||||
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 (
|
||||
<ScrollAreaNative css={{ height: "100%" }}>
|
||||
<PanelContent as={Flex} direction="column" gap={3}>
|
||||
{!canViewPublishLogs && (
|
||||
<PanelBanner variant="info" role="note">
|
||||
<Text>Upgrade to Pro to view publish logs.</Text>
|
||||
</PanelBanner>
|
||||
)}
|
||||
{items.length === 0 && (
|
||||
<Text color="subtle">No publishes in this session.</Text>
|
||||
)}
|
||||
{items.map((item, index) => (
|
||||
<SessionPublishEntry
|
||||
key={item.buildId}
|
||||
item={item}
|
||||
defaultOpen={index === items.length - 1}
|
||||
canViewPublishLogs={canViewPublishLogs}
|
||||
/>
|
||||
))}
|
||||
</PanelContent>
|
||||
</ScrollAreaNative>
|
||||
);
|
||||
};
|
||||
|
||||
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<DiagnosticFinding>();
|
||||
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 && (
|
||||
<PublishValidationBanner
|
||||
findings={reportFindings}
|
||||
onOpen={() => setIsOpen(true)}
|
||||
/>
|
||||
)}
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen} draggable resize="both">
|
||||
<DialogContent
|
||||
width={640}
|
||||
height={640}
|
||||
aria-describedby={undefined}
|
||||
css={{ display: "flex", flexDirection: "column" }}
|
||||
>
|
||||
<DialogTitle
|
||||
maximizable
|
||||
suffix={
|
||||
<DialogTitleActions>
|
||||
{canViewPublishLogs && copyText.length > 0 && (
|
||||
<CopyToClipboard text={copyText} copyText="Copy all reports">
|
||||
<IconButton
|
||||
type="button"
|
||||
aria-label="Copy all reports"
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
<CopyIcon aria-hidden />
|
||||
</IconButton>
|
||||
</CopyToClipboard>
|
||||
)}
|
||||
<DialogMaximize />
|
||||
<DialogClose />
|
||||
</DialogTitleActions>
|
||||
}
|
||||
>
|
||||
Diagnostics
|
||||
</DialogTitle>
|
||||
{selectedFinding !== undefined && canViewPublishLogs ? (
|
||||
<FindingDetails
|
||||
finding={selectedFinding}
|
||||
onBack={() => setSelectedFinding(undefined)}
|
||||
onNavigate={() => setIsOpen(false)}
|
||||
/>
|
||||
) : (
|
||||
<PanelTabs
|
||||
value={activeTab}
|
||||
onValueChange={(value) => setTab(value as typeof tab)}
|
||||
css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
|
||||
>
|
||||
<PanelTabsList aria-label="Publish check severity">
|
||||
{tabs.map(({ value, label }) => (
|
||||
<PanelTabsTrigger key={value} value={value}>
|
||||
{label}
|
||||
</PanelTabsTrigger>
|
||||
))}
|
||||
{items.length > 0 && (
|
||||
<PanelTabsTrigger value="publish">Publish</PanelTabsTrigger>
|
||||
)}
|
||||
</PanelTabsList>
|
||||
{tabs.map(({ value, findings }) => (
|
||||
<PanelTabsContent
|
||||
key={value}
|
||||
value={value}
|
||||
css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
|
||||
>
|
||||
<FindingList
|
||||
findings={findings}
|
||||
canViewPublishLogs={canViewPublishLogs}
|
||||
issuesOmitted={issuesOmitted}
|
||||
publishBuildIds={items.map(({ buildId }) => buildId)}
|
||||
onSelect={setSelectedFinding}
|
||||
onOpenPublish={
|
||||
items.length > 0 ? () => setTab("publish") : undefined
|
||||
}
|
||||
/>
|
||||
</PanelTabsContent>
|
||||
))}
|
||||
<PanelTabsContent
|
||||
value="publish"
|
||||
css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
|
||||
>
|
||||
<SessionPublishList
|
||||
items={orderedItems}
|
||||
canViewPublishLogs={canViewPublishLogs}
|
||||
onLoadLog={onLoadLog}
|
||||
/>
|
||||
</PanelTabsContent>
|
||||
</PanelTabs>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
+79
-1
@@ -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(
|
||||
<TooltipProvider>
|
||||
<form>
|
||||
<DomainCheckbox
|
||||
domain="custom.example"
|
||||
buildId="build-1"
|
||||
defaultChecked
|
||||
isCustomDomain
|
||||
/>
|
||||
</form>
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
return {
|
||||
checkbox: container.querySelector<HTMLButtonElement>('[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<HTMLButtonElement>('[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", () => {
|
||||
@@ -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<SessionPublish, "buildId" | "status">;
|
||||
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 (
|
||||
<Tooltip content={text}>
|
||||
<IconButton
|
||||
type="button"
|
||||
aria-label={`Publish log: ${domain}`}
|
||||
css={{ color }}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onOpenReport?.();
|
||||
}}
|
||||
>
|
||||
<Icon />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
@@ -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(
|
||||
<TooltipProvider>
|
||||
<StatusIcon projectDomain={projectDomain} isLoading={isLoading} />
|
||||
</TooltipProvider>
|
||||
<div onClick={onSectionClick}>
|
||||
<TooltipProvider>
|
||||
<StatusIcon
|
||||
projectDomain={projectDomain}
|
||||
isLoading={isLoading}
|
||||
latestPublish={latestPublish}
|
||||
onOpenReport={onOpenReport}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
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);
|
||||
});
|
||||
@@ -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<Domain["latestBuildVirtual"]>,
|
||||
"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} <RelativeTime time={new Date(createdAt)} />
|
||||
</>
|
||||
);
|
||||
|
||||
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 (
|
||||
<Tooltip content={text}>
|
||||
<Flex
|
||||
align="center"
|
||||
justify="center"
|
||||
css={{
|
||||
cursor: "pointer",
|
||||
width: theme.sizes.controlHeight,
|
||||
height: theme.sizes.controlHeight,
|
||||
color,
|
||||
}}
|
||||
>
|
||||
<Icon />
|
||||
</Flex>
|
||||
</Tooltip>
|
||||
<DomainStatusButton
|
||||
domain={props.projectDomain.domain}
|
||||
buildId={props.projectDomain.latestBuildVirtual?.buildId}
|
||||
latestPublish={props.latestPublish}
|
||||
fallback={fallback}
|
||||
onOpenReport={() => props.onOpenReport?.(props.projectDomain.domain)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const DomainItem = ({
|
||||
initiallyOpen,
|
||||
projectDomain,
|
||||
project,
|
||||
refresh,
|
||||
validatedDomains,
|
||||
onOpenReport,
|
||||
latestPublish,
|
||||
}: {
|
||||
initiallyOpen: boolean;
|
||||
projectDomain: Domain;
|
||||
project: Project;
|
||||
refresh: () => Promise<void>;
|
||||
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={
|
||||
<Grid flow="column">
|
||||
<StatusIcon
|
||||
isLoading={isStatusLoading}
|
||||
projectDomain={projectDomain}
|
||||
isLoading={isStatusLoading}
|
||||
onOpenReport={onOpenReport}
|
||||
latestPublish={latestPublish}
|
||||
/>
|
||||
|
||||
<CopyToClipboard
|
||||
@@ -582,6 +536,8 @@ type DomainsProps = {
|
||||
refresh: () => Promise<void>;
|
||||
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 };
|
||||
@@ -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 (
|
||||
<TooltipProvider>
|
||||
{isOpen && (
|
||||
<PublishActions
|
||||
validationState={validationState}
|
||||
validateDisabled={false}
|
||||
publishDisabled={false}
|
||||
publishInProgress={false}
|
||||
publishPending={false}
|
||||
hasSelectedDomains
|
||||
publishLabel="Publish"
|
||||
publishButtonRef={createRef<HTMLButtonElement>()}
|
||||
onValidate={async () => {
|
||||
update("passed");
|
||||
}}
|
||||
onPublish={vi.fn()}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
reset();
|
||||
setIsOpen(false);
|
||||
}}
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
{isOpen === false && (
|
||||
<button type="button" onClick={() => setIsOpen(true)}>
|
||||
Open
|
||||
</button>
|
||||
)}
|
||||
</TooltipProvider>
|
||||
);
|
||||
};
|
||||
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => root?.render(<Harness />));
|
||||
|
||||
const [validate, , close] = Array.from(
|
||||
container.querySelectorAll<HTMLButtonElement>("button")
|
||||
);
|
||||
await act(async () => validate.click());
|
||||
expect(validate.textContent).toBe("Validated");
|
||||
|
||||
act(() => close.click());
|
||||
const reopen =
|
||||
container.querySelector<HTMLButtonElement>("button:last-child");
|
||||
act(() => reopen?.click());
|
||||
|
||||
const [reopenedValidate] = Array.from(
|
||||
container.querySelectorAll<HTMLButtonElement>("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<void>((resolve) => {
|
||||
finishValidation = resolve;
|
||||
});
|
||||
|
||||
const Harness = () => {
|
||||
const [dialog, setDialog] = useState<"none" | "publish" | "export">(
|
||||
"publish"
|
||||
);
|
||||
const { validationState, update } = usePublishValidationState(dialog);
|
||||
return (
|
||||
<TooltipProvider>
|
||||
{dialog === "publish" && (
|
||||
<PublishActions
|
||||
validationState={validationState}
|
||||
validateDisabled={false}
|
||||
publishDisabled={false}
|
||||
publishInProgress={false}
|
||||
publishPending={false}
|
||||
hasSelectedDomains
|
||||
publishLabel="Publish"
|
||||
publishButtonRef={createRef<HTMLButtonElement>()}
|
||||
onValidate={async () => {
|
||||
await validation;
|
||||
update("passed");
|
||||
}}
|
||||
onPublish={vi.fn()}
|
||||
/>
|
||||
)}
|
||||
<button type="button" onClick={() => setDialog(destination)}>
|
||||
Switch
|
||||
</button>
|
||||
<button type="button" onClick={() => setDialog("publish")}>
|
||||
Reopen
|
||||
</button>
|
||||
<output>{validationState}</output>
|
||||
</TooltipProvider>
|
||||
);
|
||||
};
|
||||
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => root?.render(<Harness />));
|
||||
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",
|
||||
|
||||
@@ -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<PublishValidationState>("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,
|
||||
|
||||
@@ -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<typeof createTrpcInterceptor>;
|
||||
|
||||
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(
|
||||
<TooltipProvider>
|
||||
<publishModule.PublishButton projectId="project-1" />
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const selectStaticDestination = async () => {
|
||||
const destination = document.body.querySelector<HTMLButtonElement>(
|
||||
'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<HTMLElement>('[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<HTMLInputElement>(
|
||||
'input[name="domainToPublish[]"]'
|
||||
)!;
|
||||
if (domain.checked === false) {
|
||||
await act(async () =>
|
||||
document.body.querySelector<HTMLElement>('[role="checkbox"]')?.click()
|
||||
);
|
||||
}
|
||||
|
||||
const publish = Array.from(
|
||||
document.body.querySelectorAll<HTMLButtonElement>("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<HTMLButtonElement>("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<HTMLButtonElement>(
|
||||
'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<HTMLButtonElement>(
|
||||
'[role="dialog"] button[aria-label="Close"]'
|
||||
)
|
||||
?.click()
|
||||
);
|
||||
await act(async () => builderStates.$publishDialog.set("publish"));
|
||||
const validate = Array.from(
|
||||
document.body.querySelectorAll<HTMLButtonElement>("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<HTMLButtonElement>("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<HTMLInputElement>(
|
||||
'input[name="domainToPublish[]"]'
|
||||
)!;
|
||||
if (domain.checked === false) {
|
||||
await act(async () =>
|
||||
document.body.querySelector<HTMLElement>('[role="checkbox"]')?.click()
|
||||
);
|
||||
}
|
||||
const publish = Array.from(
|
||||
document.body.querySelectorAll<HTMLButtonElement>("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<HTMLButtonElement>("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<HTMLButtonElement>("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<typeof ExportContent>[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(
|
||||
<TooltipProvider>
|
||||
<ExportContent flow={flow} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
await selectStaticDestination();
|
||||
const seeLogs = Array.from(
|
||||
document.body.querySelectorAll<HTMLButtonElement>("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(
|
||||
<TooltipProvider>
|
||||
<ExportContent
|
||||
flow={{
|
||||
...flow,
|
||||
publishes: [{ ...flow.publishes[0], staticName: undefined }],
|
||||
}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
expect(
|
||||
Array.from(
|
||||
document.body.querySelectorAll<HTMLButtonElement>("button")
|
||||
).find((button) => button.textContent?.trim() === "See logs")
|
||||
).toBeUndefined();
|
||||
await act(async () =>
|
||||
root?.render(
|
||||
<TooltipProvider>
|
||||
<ExportContent flow={{ ...flow, isPublishing: true }} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
expect(
|
||||
Array.from(
|
||||
document.body.querySelectorAll<HTMLButtonElement>("button")
|
||||
).find((button) => button.textContent?.trim() === "See logs")
|
||||
).toBeUndefined();
|
||||
await act(async () =>
|
||||
root?.render(
|
||||
<TooltipProvider>
|
||||
<ExportContent
|
||||
flow={{
|
||||
...flow,
|
||||
publishes: [
|
||||
{
|
||||
...flow.publishes[0],
|
||||
buildId: "build-2",
|
||||
status: "failed",
|
||||
},
|
||||
...flow.publishes,
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
expect(
|
||||
Array.from(
|
||||
document.body.querySelectorAll<HTMLButtonElement>("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<HTMLButtonElement>("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<HTMLButtonElement>(
|
||||
'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<HTMLElement>('[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<HTMLInputElement>(
|
||||
'input[name="domainToPublish[]"]'
|
||||
);
|
||||
expect(domain).not.toBeNull();
|
||||
if (domain?.checked === false) {
|
||||
const checkbox =
|
||||
document.body.querySelector<HTMLElement>('[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<HTMLButtonElement>("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<HTMLButtonElement>("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<HTMLButtonElement>("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<HTMLElement>(
|
||||
'[role="tab"][aria-selected="true"]'
|
||||
)?.textContent
|
||||
).toBe(expectedTab);
|
||||
}
|
||||
);
|
||||
@@ -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<unknown>();
|
||||
let dispatch = deferred<unknown>();
|
||||
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<typeof createAssetContentSession>;
|
||||
let interceptor: ReturnType<typeof createTrpcInterceptor>;
|
||||
|
||||
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<unknown>();
|
||||
dispatch = deferred<unknown>();
|
||||
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(
|
||||
<TooltipProvider>
|
||||
<PublishButton projectId="project" />
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
if (target === "static") {
|
||||
const destination = document.body.querySelector<HTMLButtonElement>(
|
||||
'button[role="combobox"]'
|
||||
);
|
||||
await act(async () =>
|
||||
destination?.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: "Enter", bubbles: true })
|
||||
)
|
||||
);
|
||||
const staticOption = Array.from(
|
||||
document.body.querySelectorAll<HTMLElement>('[role="option"]')
|
||||
).find((option) => option.textContent?.trim() === "Static");
|
||||
await act(async () => staticOption?.click());
|
||||
return;
|
||||
}
|
||||
const domain = document.body.querySelector<HTMLInputElement>(
|
||||
'input[name="domainToPublish[]"]'
|
||||
);
|
||||
if (domain?.checked === false) {
|
||||
await act(async () =>
|
||||
document.body.querySelector<HTMLElement>('[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<HTMLButtonElement>("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<HTMLButtonElement>("button")
|
||||
).find((button) => button.textContent?.trim() === "See issues");
|
||||
const status = document.body.querySelector<HTMLButtonElement>(
|
||||
'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<HTMLElement>('[role="tab"]')
|
||||
).find((tab) => tab.textContent?.startsWith("Errors"));
|
||||
await act(async () => vi.waitFor(() => expect(findErrors()).toBeDefined()));
|
||||
await selectTab("Errors");
|
||||
return document.body.querySelector<HTMLElement>(
|
||||
'[role="tabpanel"][data-state="active"]'
|
||||
);
|
||||
};
|
||||
|
||||
const closeReport = async () => {
|
||||
const close = document.body.querySelector<HTMLButtonElement>(
|
||||
'[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<HTMLButtonElement>("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<HTMLButtonElement>(
|
||||
'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<unknown>();
|
||||
dispatch = deferred<unknown>();
|
||||
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<HTMLButtonElement>(
|
||||
'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<HTMLButtonElement>(
|
||||
'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<HTMLButtonElement>(
|
||||
'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<HTMLButtonElement>(
|
||||
'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<HTMLButtonElement>("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<HTMLButtonElement>("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<HTMLButtonElement>(
|
||||
'button[aria-label^="Publish log:"]'
|
||||
)
|
||||
).not.toBeNull()
|
||||
)
|
||||
);
|
||||
checks = deferred<unknown>();
|
||||
dispatch = deferred<unknown>();
|
||||
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<HTMLButtonElement>(
|
||||
'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");
|
||||
}
|
||||
);
|
||||
@@ -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<typeof createAssetContentSession>;
|
||||
let interceptor: ReturnType<typeof createTrpcInterceptor>;
|
||||
let initialPlan: ReturnType<typeof nanoStates.$planFeatures.get>;
|
||||
let project: Project;
|
||||
let publish: () => Promise<unknown>;
|
||||
let refresh: () => Promise<unknown>;
|
||||
let validate: () => Promise<unknown>;
|
||||
let job: () => Promise<unknown>;
|
||||
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<HTMLButtonElement>("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(
|
||||
<TooltipProvider>
|
||||
<PublishButton projectId={projectId} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
if (vi.isFakeTimers()) {
|
||||
await act(async () => vi.advanceTimersByTimeAsync(10));
|
||||
}
|
||||
const domain = document.body.querySelector<HTMLInputElement>(
|
||||
'input[name="domainToPublish[]"]'
|
||||
);
|
||||
if (domain?.checked === false) {
|
||||
await act(async () =>
|
||||
document.body.querySelector<HTMLElement>('[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<HTMLButtonElement>("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<HTMLInputElement>(
|
||||
'input[name="domainToPublish[]"]'
|
||||
)
|
||||
);
|
||||
if (domains.length > 0 && domains.every((domain) => !domain.checked)) {
|
||||
await act(async () =>
|
||||
document.body.querySelector<HTMLElement>('[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<unknown>();
|
||||
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<unknown>();
|
||||
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<unknown>();
|
||||
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<unknown>();
|
||||
const current = deferred<unknown>();
|
||||
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<unknown>();
|
||||
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<unknown>();
|
||||
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<unknown>();
|
||||
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<unknown>();
|
||||
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<HTMLButtonElement>('[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<HTMLButtonElement>(
|
||||
'button[role="combobox"]'
|
||||
);
|
||||
await act(async () =>
|
||||
destination?.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: "Enter", bubbles: true })
|
||||
)
|
||||
);
|
||||
const option = Array.from(
|
||||
document.body.querySelectorAll<HTMLElement>('[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<HTMLButtonElement>(
|
||||
'[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<HTMLButtonElement>(
|
||||
'[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<HTMLButtonElement>(
|
||||
'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");
|
||||
}
|
||||
}
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<Project | undefined>,
|
||||
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<Project | undefined>,
|
||||
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<ReturnType<typeof waitForPublishStatus>>;
|
||||
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 && (
|
||||
<div>
|
||||
You have {timesLeft} out of {maxDailyPublishesPerUser} daily
|
||||
publications remaining. The counter resets tomorrow.
|
||||
</div>
|
||||
)}
|
||||
</>,
|
||||
{ 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<typeof nativeClient.domain.project.query>;
|
||||
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);
|
||||
}
|
||||
};
|
||||
@@ -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<typeof deferred<void>> }
|
||||
| undefined;
|
||||
let heldJob: ReturnType<typeof deferred<unknown>> | undefined;
|
||||
let heldPublish: ReturnType<typeof deferred<unknown>> | undefined;
|
||||
let interceptor: ReturnType<typeof createTrpcInterceptor>;
|
||||
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(
|
||||
<TooltipProvider>
|
||||
<PublishButton projectId={projectId} />
|
||||
</TooltipProvider>
|
||||
)
|
||||
);
|
||||
};
|
||||
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<HTMLInputElement>(
|
||||
'input[name="domainToPublish[]"]'
|
||||
);
|
||||
expect(domain).not.toBeNull();
|
||||
if (domain?.checked === false) {
|
||||
await act(async () =>
|
||||
document.body.querySelector<HTMLElement>('[role="checkbox"]')?.click()
|
||||
);
|
||||
}
|
||||
const button = Array.from(
|
||||
domain!.closest("form")!.querySelectorAll<HTMLButtonElement>("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<HTMLButtonElement>('button[aria-label^="Publish log:"]')
|
||||
?.click()
|
||||
);
|
||||
expect(document.body.querySelector('[role="tablist"]')).not.toBeNull();
|
||||
};
|
||||
const panel = () =>
|
||||
document.body.querySelector<HTMLElement>(
|
||||
'[role="tabpanel"][data-state="active"]'
|
||||
)!;
|
||||
|
||||
const waitFor = async (assertion: () => void) => {
|
||||
await vi.waitFor(async () => {
|
||||
await act(async () => {});
|
||||
assertion();
|
||||
});
|
||||
};
|
||||
const entries = () =>
|
||||
Array.from(
|
||||
panel().querySelectorAll<HTMLElement>('[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<unknown>();
|
||||
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<void>() };
|
||||
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<void>() };
|
||||
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<unknown>();
|
||||
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<void>() };
|
||||
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);
|
||||
});
|
||||
@@ -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<typeof createTrpcInterceptor>;
|
||||
|
||||
// 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<HTMLButtonElement>("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(
|
||||
<TooltipProvider>
|
||||
<publishModule.PublishButton projectId={projectId} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
});
|
||||
if (open && staticButton() === undefined) {
|
||||
await act(async () =>
|
||||
document.body
|
||||
.querySelector<HTMLButtonElement>('button[role="combobox"]')
|
||||
?.dispatchEvent(
|
||||
new KeyboardEvent("keydown", { key: "Enter", bubbles: true })
|
||||
)
|
||||
);
|
||||
const option = Array.from(
|
||||
document.body.querySelectorAll<HTMLElement>('[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<HTMLButtonElement>(
|
||||
'button[aria-label="Publish log: Static export"]'
|
||||
)
|
||||
?.click()
|
||||
);
|
||||
const errors = Array.from(
|
||||
document.body.querySelectorAll<HTMLElement>('[role="tab"]')
|
||||
).find((tab) => tab.textContent === "Errors");
|
||||
expect(errors).toBeDefined();
|
||||
await act(async () => userEvent.click(errors!));
|
||||
const showLogs = Array.from(
|
||||
document.body.querySelectorAll<HTMLButtonElement>("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<HTMLButtonElement>('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<HTMLButtonElement>(
|
||||
'button[aria-label="Publish log: Static export"]'
|
||||
)
|
||||
?.click()
|
||||
);
|
||||
expect(activeTab()).toBe("Errors");
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
@@ -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<Project["domainsVirtual"][number]["latestBuildVirtual"]>,
|
||||
"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} <RelativeTime time={new Date(createdAt)} />
|
||||
</>
|
||||
);
|
||||
|
||||
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} <RelativeTime time={new Date(updatedAt)} />
|
||||
</>
|
||||
);
|
||||
|
||||
return { statusContent, status };
|
||||
};
|
||||
@@ -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");
|
||||
}
|
||||
});
|
||||
@@ -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<HTMLElement>('[role="tab"]')
|
||||
).find((candidate) => candidate.textContent?.startsWith(name));
|
||||
expect(tab).toBeDefined();
|
||||
await act(async () => userEvent.click(tab!));
|
||||
};
|
||||
|
||||
export const deferred = <T>() => {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<T>((done, fail) => {
|
||||
resolve = done;
|
||||
reject = fail;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
};
|
||||
|
||||
export const createTrpcInterceptor = (
|
||||
handlers: Record<string, (input: unknown) => unknown | Promise<unknown>>,
|
||||
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<string, unknown>;
|
||||
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<string, unknown>;
|
||||
} 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"));
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,126 +0,0 @@
|
||||
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 {
|
||||
PublishValidationResults,
|
||||
type PublishValidationFinding,
|
||||
} from "./publish-validation-results";
|
||||
|
||||
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: PublishValidationFinding[]) => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
act(() => {
|
||||
root?.render(
|
||||
<TooltipProvider>
|
||||
<PublishValidationResults findings={findings} />
|
||||
</TooltipProvider>
|
||||
);
|
||||
});
|
||||
return container;
|
||||
};
|
||||
|
||||
const createFinding = (
|
||||
severity: PublishValidationFinding["severity"],
|
||||
index: number
|
||||
): PublishValidationFinding => ({
|
||||
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("renders no publish summary when there are no findings", () => {
|
||||
expect(render([]).textContent).toBe("");
|
||||
});
|
||||
|
||||
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 (6)");
|
||||
expect(document.body.textContent).toContain("Warnings (11)");
|
||||
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 selectableText = Array.from(document.body.querySelectorAll("div")).find(
|
||||
(candidate) => candidate.textContent === "details-error-0"
|
||||
);
|
||||
expect(selectableText).toBeDefined();
|
||||
expect(getComputedStyle(selectableText!).userSelect).toBe("text");
|
||||
|
||||
const warningTab = Array.from(
|
||||
document.body.querySelectorAll('[role="tab"]')
|
||||
).find((tab) => tab.textContent === "Warnings (11)");
|
||||
await act(async () => userEvent.click(warningTab as HTMLElement));
|
||||
expect(document.body.textContent).toContain("warning-10");
|
||||
expect(document.body.textContent).not.toContain("error-0");
|
||||
|
||||
const copyButton = document.body.querySelector<HTMLButtonElement>(
|
||||
'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([
|
||||
{ severity: "error" as const, otherTab: "Warnings (0)" },
|
||||
{ severity: "warning" as const, otherTab: "Errors (0)" },
|
||||
])(
|
||||
"hides the empty tab in the $severity-only state",
|
||||
({ severity, otherTab }) => {
|
||||
const element = render([createFinding(severity, 0)]);
|
||||
openDetails(element);
|
||||
|
||||
expect(document.body.textContent).not.toContain(otherTab);
|
||||
expect(document.body.querySelectorAll('[role="tab"]')).toHaveLength(1);
|
||||
}
|
||||
);
|
||||
@@ -1,178 +0,0 @@
|
||||
import { Fragment, useState, type ReactNode } from "react";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogTitle,
|
||||
DialogTitleActions,
|
||||
Flex,
|
||||
IconButton,
|
||||
PanelBanner,
|
||||
PanelContent,
|
||||
PanelTabs,
|
||||
PanelTabsContent,
|
||||
PanelTabsList,
|
||||
PanelTabsTrigger,
|
||||
ScrollArea,
|
||||
Separator,
|
||||
Text,
|
||||
} from "@webstudio-is/design-system";
|
||||
import { CopyIcon } from "@webstudio-is/icons";
|
||||
import { CopyToClipboard } from "~/shared/copy-to-clipboard";
|
||||
|
||||
export type PublishValidationFinding = {
|
||||
severity: "error" | "warning";
|
||||
title: ReactNode;
|
||||
details?: ReactNode;
|
||||
link?: ReactNode;
|
||||
relatedInstanceId?: string;
|
||||
reportText: string;
|
||||
};
|
||||
|
||||
export const PublishValidationResults = ({
|
||||
findings,
|
||||
}: {
|
||||
findings: PublishValidationFinding[];
|
||||
}) => {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const errors = findings.filter(({ severity }) => severity === "error");
|
||||
const warnings = findings.filter(({ severity }) => severity === "warning");
|
||||
|
||||
if (findings.length === 0) {
|
||||
return 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(" · ");
|
||||
const defaultTab = errors.length > 0 ? "errors" : "warnings";
|
||||
const reportText = [
|
||||
`Publish validation report: ${countLabel}`,
|
||||
errors.length > 0 &&
|
||||
[
|
||||
`Errors (${errors.length})`,
|
||||
...errors.map(({ reportText }) => reportText),
|
||||
].join("\n\n"),
|
||||
warnings.length > 0 &&
|
||||
[
|
||||
`Warnings (${warnings.length})`,
|
||||
...warnings.map(({ reportText }) => reportText),
|
||||
].join("\n\n"),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
|
||||
return (
|
||||
<>
|
||||
<PanelBanner variant={errors.length > 0 ? "error" : "warning"}>
|
||||
<Flex align="center" justify="between" gap={2}>
|
||||
<Text css={{ flex: 1, minWidth: 0 }}>
|
||||
Publish check found {countLabel}.{" "}
|
||||
{errors.length > 0 && "Fix the errors before publishing."}
|
||||
</Text>
|
||||
<Button
|
||||
type="button"
|
||||
color="ghost"
|
||||
css={{ flexShrink: 0 }}
|
||||
onClick={() => setIsOpen(true)}
|
||||
>
|
||||
See issues
|
||||
</Button>
|
||||
</Flex>
|
||||
</PanelBanner>
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen} draggable resize="both">
|
||||
<DialogContent
|
||||
width={640}
|
||||
height={640}
|
||||
aria-describedby={undefined}
|
||||
css={{ display: "flex", flexDirection: "column" }}
|
||||
>
|
||||
<DialogTitle
|
||||
suffix={
|
||||
<DialogTitleActions>
|
||||
<CopyToClipboard text={reportText} copyText="Copy all reports">
|
||||
<IconButton
|
||||
type="button"
|
||||
aria-label="Copy all reports"
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
<CopyIcon aria-hidden />
|
||||
</IconButton>
|
||||
</CopyToClipboard>
|
||||
<DialogClose />
|
||||
</DialogTitleActions>
|
||||
}
|
||||
>
|
||||
Diagnostics
|
||||
</DialogTitle>
|
||||
<PanelTabs
|
||||
key={`${errors.length}-${warnings.length}`}
|
||||
defaultValue={defaultTab}
|
||||
css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
|
||||
>
|
||||
<PanelTabsList aria-label="Publish check severity">
|
||||
{errors.length > 0 && (
|
||||
<PanelTabsTrigger value="errors">
|
||||
Errors ({errors.length})
|
||||
</PanelTabsTrigger>
|
||||
)}
|
||||
{warnings.length > 0 && (
|
||||
<PanelTabsTrigger value="warnings">
|
||||
Warnings ({warnings.length})
|
||||
</PanelTabsTrigger>
|
||||
)}
|
||||
</PanelTabsList>
|
||||
{errors.length > 0 && (
|
||||
<PanelTabsContent
|
||||
value="errors"
|
||||
css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
|
||||
>
|
||||
<FindingList findings={errors} />
|
||||
</PanelTabsContent>
|
||||
)}
|
||||
{warnings.length > 0 && (
|
||||
<PanelTabsContent
|
||||
value="warnings"
|
||||
css={{ flex: 1, minHeight: 0, overflow: "hidden" }}
|
||||
>
|
||||
<FindingList findings={warnings} />
|
||||
</PanelTabsContent>
|
||||
)}
|
||||
</PanelTabs>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
const FindingList = ({
|
||||
findings,
|
||||
}: {
|
||||
findings: PublishValidationFinding[];
|
||||
}) => (
|
||||
<ScrollArea css={{ height: "100%" }}>
|
||||
<PanelContent as={Flex} direction="column" gap={3}>
|
||||
{findings.map((finding, index) => (
|
||||
<Fragment key={`${finding.severity}-${index}`}>
|
||||
<Flex direction="column" gap={2}>
|
||||
<Text variant="labels" userSelect="text">
|
||||
{finding.title} {finding.link}
|
||||
</Text>
|
||||
{finding.details !== undefined && (
|
||||
<Text userSelect="text" color="subtle">
|
||||
{finding.details}
|
||||
</Text>
|
||||
)}
|
||||
</Flex>
|
||||
{index < findings.length - 1 && <Separator />}
|
||||
</Fragment>
|
||||
))}
|
||||
</PanelContent>
|
||||
</ScrollArea>
|
||||
);
|
||||
@@ -0,0 +1,261 @@
|
||||
import { type ReactNode } from "react";
|
||||
import { Link, toast } from "@webstudio-is/design-system";
|
||||
import type { Project } from "@webstudio-is/project";
|
||||
import {
|
||||
findPageAndSelectorByInstanceId,
|
||||
formatPrePublishAuditFinding,
|
||||
runPrePublishAudit,
|
||||
} from "@webstudio-is/project-build/runtime";
|
||||
import {
|
||||
$registeredComponentMetas,
|
||||
$selectedPageId,
|
||||
selectInstance,
|
||||
} from "~/shared/nano-states";
|
||||
import {
|
||||
$assetFolders,
|
||||
$assets,
|
||||
$pages,
|
||||
$instances,
|
||||
$props,
|
||||
$dataSources,
|
||||
$resources,
|
||||
} from "~/shared/sync/data-stores";
|
||||
import { $publishDialog } from "~/builder/shared/nano-states";
|
||||
import { getInstanceLink } from "~/shared/instance-utils/link";
|
||||
import { flushExternalContentProject } from "~/shared/external-content-roots";
|
||||
import { nativeClient } from "~/shared/trpc/trpc-client";
|
||||
import { getContentDatabasePublishFindings } from "./content-database-publish-warning";
|
||||
import { getPublishValidationErrorMessage } from "./publish-error";
|
||||
import type { DiagnosticFinding } from "./diagnostics";
|
||||
|
||||
const getPrePublishInstanceTarget = (
|
||||
instanceId: string,
|
||||
pageId?: string,
|
||||
instanceSelector?: string[]
|
||||
) => {
|
||||
const pages = $pages.get();
|
||||
const instances = $instances.get();
|
||||
if (pages === undefined || instances.has(instanceId) === false) {
|
||||
return;
|
||||
}
|
||||
const target =
|
||||
pageId === undefined || instanceSelector === undefined
|
||||
? findPageAndSelectorByInstanceId(pages, instances, instanceId)
|
||||
: { pageId, instanceSelector };
|
||||
const href = getInstanceLink(target.instanceSelector);
|
||||
if (href === undefined) {
|
||||
return;
|
||||
}
|
||||
return { ...target, href };
|
||||
};
|
||||
|
||||
const PrePublishInstanceLink = ({
|
||||
instanceId,
|
||||
pageId,
|
||||
instanceSelector,
|
||||
children,
|
||||
}: {
|
||||
instanceId: string;
|
||||
pageId?: string;
|
||||
instanceSelector?: string[];
|
||||
children: ReactNode;
|
||||
}) => {
|
||||
const target = getPrePublishInstanceTarget(
|
||||
instanceId,
|
||||
pageId,
|
||||
instanceSelector
|
||||
);
|
||||
if (target === undefined) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<Link
|
||||
href={target.href}
|
||||
onClick={(event) => {
|
||||
if (
|
||||
event.button !== 0 ||
|
||||
event.metaKey ||
|
||||
event.ctrlKey ||
|
||||
event.shiftKey ||
|
||||
event.altKey
|
||||
) {
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
$selectedPageId.set(target.pageId);
|
||||
selectInstance(target.instanceSelector);
|
||||
$publishDialog.set("none");
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</Link>
|
||||
);
|
||||
};
|
||||
|
||||
const getPrePublishAuditFindings = (): DiagnosticFinding[] => {
|
||||
const findings = runPrePublishAudit({
|
||||
pages: $pages.get(),
|
||||
instances: $instances.get(),
|
||||
props: $props.get(),
|
||||
dataSources: $dataSources.get(),
|
||||
resources: $resources.get(),
|
||||
assets: $assets.get(),
|
||||
metas: $registeredComponentMetas.get(),
|
||||
});
|
||||
return findings.flatMap((finding) => {
|
||||
if (finding.severity !== "error" && finding.severity !== "warning") {
|
||||
return [];
|
||||
}
|
||||
const context = Object.entries(finding.location)
|
||||
.filter(
|
||||
([key, value]) => key !== "instanceSelector" && value !== undefined
|
||||
)
|
||||
.map(([key, value]) => `${key}: ${value}`);
|
||||
const reportText = [
|
||||
`${finding.severity.toUpperCase()}: ${formatPrePublishAuditFinding(
|
||||
finding
|
||||
)}`,
|
||||
`Rule: ${finding.ruleId}`,
|
||||
...context,
|
||||
].join("\n");
|
||||
return [
|
||||
{
|
||||
severity: finding.severity,
|
||||
title: formatPrePublishAuditFinding(finding),
|
||||
summary: formatPrePublishAuditFinding(finding).slice(0, 160),
|
||||
link:
|
||||
finding.location.instanceId === undefined ? undefined : (
|
||||
<PrePublishInstanceLink
|
||||
instanceId={finding.location.instanceId}
|
||||
pageId={finding.location.pageId}
|
||||
instanceSelector={finding.location.instanceSelector}
|
||||
>
|
||||
Show element
|
||||
</PrePublishInstanceLink>
|
||||
),
|
||||
details: context.length === 0 ? undefined : context.join(" · "),
|
||||
reportText,
|
||||
},
|
||||
];
|
||||
});
|
||||
};
|
||||
|
||||
export const runPublishDiagnostics = async (
|
||||
projectId: Project["id"],
|
||||
domains?: string[]
|
||||
) => {
|
||||
const cssBuildWarningText =
|
||||
"Some project styles cannot be processed for publishing. Publishing can continue using base and font styles.";
|
||||
const auditFindings = getPrePublishAuditFindings();
|
||||
const validation =
|
||||
domains === undefined
|
||||
? undefined
|
||||
: await nativeClient.api.publish.validate.query({
|
||||
projectId,
|
||||
target: "staging",
|
||||
domains,
|
||||
});
|
||||
const diagnostics =
|
||||
validation?.diagnostics ??
|
||||
(await nativeClient.build.contentDatabasePublishDiagnostics.query({
|
||||
projectId,
|
||||
}));
|
||||
const contentFindings = getContentDatabasePublishFindings(diagnostics).map(
|
||||
(finding) => ({
|
||||
...finding,
|
||||
link:
|
||||
finding.relatedInstanceId === undefined ? undefined : (
|
||||
<PrePublishInstanceLink instanceId={finding.relatedInstanceId}>
|
||||
Open Content Block
|
||||
</PrePublishInstanceLink>
|
||||
),
|
||||
})
|
||||
);
|
||||
const cssWarning =
|
||||
validation?.cssValid === false
|
||||
? [
|
||||
{
|
||||
severity: "warning" as const,
|
||||
title: cssBuildWarningText,
|
||||
reportText: cssBuildWarningText,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
const findings = [...auditFindings, ...contentFindings, ...cssWarning];
|
||||
return {
|
||||
passed: findings.every(({ severity }) => severity !== "error"),
|
||||
findings,
|
||||
};
|
||||
};
|
||||
|
||||
export const runPublishValidation = async (
|
||||
projectId: Project["id"],
|
||||
domains: string[]
|
||||
) => {
|
||||
await flushExternalContentProject({ projectId });
|
||||
return runPublishDiagnostics(projectId, domains);
|
||||
};
|
||||
|
||||
export const reportPublishValidationFailure = (
|
||||
error: unknown,
|
||||
setFindings: (findings: DiagnosticFinding[]) => void,
|
||||
{
|
||||
publishingContinues = false,
|
||||
showToast = true,
|
||||
}: { publishingContinues?: boolean; showToast?: boolean } = {}
|
||||
) => {
|
||||
const diagnosticMessage = getPublishValidationErrorMessage(error, {
|
||||
assets: $assets.get(),
|
||||
assetFolders: $assetFolders.get(),
|
||||
});
|
||||
const message = publishingContinues
|
||||
? `${diagnosticMessage}\n\nThe publish request was sent without waiting for these diagnostics.`
|
||||
: diagnosticMessage;
|
||||
if (showToast) {
|
||||
toast.error(message.slice(0, 200));
|
||||
}
|
||||
const mcpUrl = "https://wstd.us/mcp";
|
||||
const mcpUrlIndex = message.indexOf(mcpUrl);
|
||||
const details =
|
||||
mcpUrlIndex === -1 ? (
|
||||
message
|
||||
) : (
|
||||
<>
|
||||
{message.slice(0, mcpUrlIndex)}
|
||||
<Link href={mcpUrl} target="_blank" rel="noreferrer">
|
||||
Webstudio MCP
|
||||
</Link>
|
||||
{message.slice(mcpUrlIndex + mcpUrl.length)}
|
||||
</>
|
||||
);
|
||||
setFindings([
|
||||
{
|
||||
severity: "error",
|
||||
title: publishingContinues
|
||||
? "Publish checks couldn’t complete"
|
||||
: "Unable to complete publish validation",
|
||||
summary: message.slice(0, 160),
|
||||
details,
|
||||
reportText: `ERROR: Unable to complete publish validation\n${message}`,
|
||||
},
|
||||
]);
|
||||
};
|
||||
|
||||
export const getServerPublishFindings = (
|
||||
findings: readonly {
|
||||
severity: "error" | "warning" | "info";
|
||||
message: string;
|
||||
}[]
|
||||
): DiagnosticFinding[] =>
|
||||
findings.flatMap((finding) =>
|
||||
finding.severity === "info"
|
||||
? []
|
||||
: [
|
||||
{
|
||||
severity: finding.severity,
|
||||
title: finding.message,
|
||||
summary: finding.message,
|
||||
reportText: `${finding.severity.toUpperCase()}: ${finding.message}`,
|
||||
},
|
||||
]
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,52 @@
|
||||
import { expect, test } from "vitest";
|
||||
import {
|
||||
getPublishDuration,
|
||||
selectSessionPublishes,
|
||||
} from "./session-publishes";
|
||||
|
||||
test("duration is omitted for invalid or reversed job timestamps", () => {
|
||||
expect(
|
||||
getPublishDuration({
|
||||
startedAt: "invalid",
|
||||
completedAt: "2026-11-13T10:00:00.000Z",
|
||||
} as never)
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
getPublishDuration({
|
||||
startedAt: "2026-11-13T10:00:03.000Z",
|
||||
completedAt: "2026-11-13T10:00:00.000Z",
|
||||
} as never)
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
test("session selection keeps repeated domain publishes separate from static exports", () => {
|
||||
const base = { findings: [], status: "success" as const };
|
||||
const items = [
|
||||
{
|
||||
...base,
|
||||
buildId: "site-1",
|
||||
target: "site" as const,
|
||||
domains: ["a.example", "b.example"],
|
||||
},
|
||||
{
|
||||
...base,
|
||||
buildId: "site-2",
|
||||
target: "site" as const,
|
||||
domains: ["b.example"],
|
||||
},
|
||||
{ ...base, buildId: "static-1", target: "static" as const, domains: [] },
|
||||
];
|
||||
expect(
|
||||
selectSessionPublishes(items, "site", "a.example").map(
|
||||
({ buildId }) => buildId
|
||||
)
|
||||
).toEqual(["site-1"]);
|
||||
expect(
|
||||
selectSessionPublishes(items, "site", "b.example").map(
|
||||
({ buildId }) => buildId
|
||||
)
|
||||
).toEqual(["site-1", "site-2"]);
|
||||
expect(
|
||||
selectSessionPublishes(items, "static").map(({ buildId }) => buildId)
|
||||
).toEqual(["static-1"]);
|
||||
});
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { DiagnosticFinding } from "./diagnostics";
|
||||
|
||||
export type SessionPublish = {
|
||||
buildId: string;
|
||||
domains: string[];
|
||||
target: "site" | "static";
|
||||
staticName?: string;
|
||||
findings: DiagnosticFinding[];
|
||||
logHandle?: string;
|
||||
status: "pending" | "success" | "failed";
|
||||
code?: string;
|
||||
startedAt?: string;
|
||||
completedAt?: string;
|
||||
failedStage?: string;
|
||||
issues?: { severity: "error" | "warning"; message: string }[];
|
||||
issuesOmitted?: number;
|
||||
logState?: "loading" | "available" | "unavailable";
|
||||
logText?: string;
|
||||
};
|
||||
|
||||
const decodeChunk = (chunk: string) => {
|
||||
const binary = atob(chunk.replaceAll("-", "+").replaceAll("_", "/"));
|
||||
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
||||
};
|
||||
|
||||
export const decodePublishLog = (chunks: string[]) => {
|
||||
const decoder = new TextDecoder();
|
||||
return chunks
|
||||
.map((chunk, index) =>
|
||||
decoder.decode(decodeChunk(chunk), { stream: index < chunks.length - 1 })
|
||||
)
|
||||
.join("");
|
||||
};
|
||||
|
||||
export const getPublishDuration = (item: SessionPublish) => {
|
||||
if (item.startedAt === undefined || item.completedAt === undefined) {
|
||||
return;
|
||||
}
|
||||
const duration = Date.parse(item.completedAt) - Date.parse(item.startedAt);
|
||||
if (Number.isFinite(duration) && duration >= 0) {
|
||||
return Math.round(duration / 1000);
|
||||
}
|
||||
};
|
||||
|
||||
export const selectSessionPublishes = (
|
||||
items: SessionPublish[],
|
||||
target: "site" | "static",
|
||||
domain?: string
|
||||
) =>
|
||||
items.filter(
|
||||
(item) =>
|
||||
item.target === target &&
|
||||
(domain === undefined || item.domains.includes(domain))
|
||||
);
|
||||
+26
-18
@@ -1,10 +1,11 @@
|
||||
import { createRef } from "react";
|
||||
import { FetchInterceptor } from "@mswjs/interceptors/fetch";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { userEvent } from "@vitest/browser/context";
|
||||
import { Dialog, TooltipProvider } from "@webstudio-is/design-system";
|
||||
import type { ResourceRequest } from "@webstudio-is/sdk";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
|
||||
|
||||
import { $resources } from "~/shared/sync/data-stores";
|
||||
|
||||
@@ -14,6 +15,9 @@ import { $resources } from "~/shared/sync/data-stores";
|
||||
|
||||
let root: Root | undefined;
|
||||
const initialResources = $resources.get();
|
||||
const interceptor = new FetchInterceptor();
|
||||
beforeAll(() => interceptor.apply());
|
||||
afterAll(() => interceptor.dispose());
|
||||
|
||||
afterEach(async () => {
|
||||
act(() => root?.unmount());
|
||||
@@ -22,24 +26,28 @@ afterEach(async () => {
|
||||
const { __testing__ } = await import("~/shared/resources");
|
||||
__testing__.reset();
|
||||
document.body.innerHTML = "";
|
||||
vi.unstubAllGlobals();
|
||||
interceptor.removeAllListeners("request");
|
||||
});
|
||||
|
||||
test("Resource editor Refresh sends its computed GET to the inspected loader", async () => {
|
||||
const url = "https://api.tilmaplatform.com/api/orgs/holyredeemer/en/";
|
||||
const loaderCalls: Array<{ input: string; init?: RequestInit }> = [];
|
||||
const nativeFetch = globalThis.fetch;
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
if (String(input).startsWith("/rest/resources-loader")) {
|
||||
loaderCalls.push({ input: String(input), init });
|
||||
return Response.json({ resources: [] });
|
||||
}
|
||||
return nativeFetch(input, init);
|
||||
const loaderCalls: Request[] = [];
|
||||
interceptor.on("request", ({ request, controller }) => {
|
||||
const requestUrl = new URL(request.url);
|
||||
if (
|
||||
requestUrl.origin !== location.origin ||
|
||||
requestUrl.pathname !== "/rest/resources-loader"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
);
|
||||
// fetch.client captures fetch at import time.
|
||||
loaderCalls.push(request.clone());
|
||||
controller.respondWith(
|
||||
request.method === "POST"
|
||||
? Response.json({ resources: [] })
|
||||
: Response.error()
|
||||
);
|
||||
});
|
||||
// Install interception before fetch.client captures fetch at import time.
|
||||
const [{ HttpResourceEditor }, { updateCsrfToken }] = await Promise.all([
|
||||
import("./http-resource-editor"),
|
||||
import("~/shared/csrf.client"),
|
||||
@@ -107,10 +115,10 @@ test("Resource editor Refresh sends its computed GET to the inspected loader", a
|
||||
);
|
||||
});
|
||||
await vi.waitFor(() => expect(loaderCalls).toHaveLength(1));
|
||||
const [{ input, init }] = loaderCalls;
|
||||
expect(input).toMatch(/^\/rest\/resources-loader\?inspect=/);
|
||||
expect(init?.method).toBe("POST");
|
||||
expect(JSON.parse(String(init?.body)) as ResourceRequest[]).toEqual([
|
||||
const [request] = loaderCalls;
|
||||
expect(new URL(request.url).searchParams.has("inspect")).toBe(true);
|
||||
expect(request.method).toBe("POST");
|
||||
expect((await request.json()) as ResourceRequest[]).toEqual([
|
||||
{
|
||||
name: variable.name,
|
||||
method: "get",
|
||||
|
||||
+40
-48
@@ -1,12 +1,12 @@
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { FetchInterceptor } from "@mswjs/interceptors/fetch";
|
||||
import { act } from "react-dom/test-utils";
|
||||
import { userEvent } from "@vitest/browser/context";
|
||||
import { TooltipProvider } from "@webstudio-is/design-system";
|
||||
import { ROOT_INSTANCE_ID, type ResourceRequest } from "@webstudio-is/sdk";
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
|
||||
|
||||
const { previewLoaderCalls, emailPreviewMockState } = vi.hoisted(() => ({
|
||||
previewLoaderCalls: vi.fn(),
|
||||
const { emailPreviewMockState } = vi.hoisted(() => ({
|
||||
emailPreviewMockState: { fail: false },
|
||||
}));
|
||||
vi.mock("./variable-editors/email-request-preview", async (importOriginal) => {
|
||||
@@ -26,18 +26,6 @@ vi.mock("./variable-editors/email-request-preview", async (importOriginal) => {
|
||||
},
|
||||
};
|
||||
});
|
||||
vi.mock("~/shared/resources", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("~/shared/resources")>();
|
||||
return {
|
||||
...actual,
|
||||
loadResourcePreview: (
|
||||
...args: Parameters<typeof actual.loadResourcePreview>
|
||||
) => {
|
||||
previewLoaderCalls(args[0]);
|
||||
return actual.loadResourcePreview(...args);
|
||||
},
|
||||
};
|
||||
});
|
||||
import {
|
||||
$dataSources,
|
||||
$instances,
|
||||
@@ -62,6 +50,32 @@ const initialDataSources = $dataSources.get();
|
||||
const initialResources = $resources.get();
|
||||
const initialProps = $props.get();
|
||||
const initialProjectSettings = $projectSettings.get();
|
||||
const interceptor = new FetchInterceptor();
|
||||
const loaderCalls: Request[] = [];
|
||||
let respond: ((response: Response) => void) | undefined;
|
||||
beforeAll(() => {
|
||||
interceptor.on("request", async ({ request, controller }) => {
|
||||
const url = new URL(request.url);
|
||||
if (
|
||||
url.origin !== location.origin ||
|
||||
url.pathname !== "/rest/resources-loader"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
loaderCalls.push(request.clone());
|
||||
if (request.method !== "POST") {
|
||||
controller.respondWith(Response.error());
|
||||
return;
|
||||
}
|
||||
controller.respondWith(
|
||||
await new Promise<Response>((resolve) => {
|
||||
respond = resolve;
|
||||
})
|
||||
);
|
||||
});
|
||||
interceptor.apply();
|
||||
});
|
||||
afterAll(() => interceptor.dispose());
|
||||
|
||||
afterEach(async () => {
|
||||
act(() => root?.unmount());
|
||||
@@ -79,31 +93,15 @@ afterEach(async () => {
|
||||
selectInstance(undefined);
|
||||
$livePreviewBrowserInfo.set(new Map());
|
||||
emailPreviewMockState.fail = false;
|
||||
vi.restoreAllMocks();
|
||||
document.body.innerHTML = "";
|
||||
vi.unstubAllGlobals();
|
||||
respond?.(Response.error());
|
||||
respond = undefined;
|
||||
loaderCalls.length = 0;
|
||||
});
|
||||
|
||||
test("loads an unsaved system resource while an unrelated page request is pending", async () => {
|
||||
const nativeFetch = globalThis.fetch;
|
||||
let respond: (response: Response) => void = () => {};
|
||||
const loaderCalls: RequestInit[] = [];
|
||||
const backend: typeof globalThis.fetch = (input, init) => {
|
||||
if (String(input).startsWith("/rest/resources-loader")) {
|
||||
loaderCalls.push(init ?? {});
|
||||
return new Promise<Response>((resolve, reject) => {
|
||||
const onAbort = () => reject(new DOMException("Aborted", "AbortError"));
|
||||
init?.signal?.addEventListener("abort", onAbort, { once: true });
|
||||
respond = (response) => {
|
||||
init?.signal?.removeEventListener("abort", onAbort);
|
||||
resolve(response);
|
||||
};
|
||||
});
|
||||
}
|
||||
return nativeFetch(input, init);
|
||||
};
|
||||
// fetch.client captures fetch at import time, so install the test backend
|
||||
// before importing the dialog and resource loader.
|
||||
vi.stubGlobal("fetch", backend);
|
||||
// The suite interceptor stays active while fetch.client retains its fetch.
|
||||
const [
|
||||
{ VariablePopoverTrigger },
|
||||
{ __testing__, getResourceKey },
|
||||
@@ -174,7 +172,7 @@ test("loads an unsaved system resource while an unrelated page request is pendin
|
||||
await userEvent.click(loadButton!);
|
||||
});
|
||||
await vi.waitFor(() => expect(loaderCalls).toHaveLength(1));
|
||||
const requests = JSON.parse(String(loaderCalls[0].body)) as ResourceRequest[];
|
||||
const requests = (await loaderCalls[0].json()) as ResourceRequest[];
|
||||
const preview = requests.find(
|
||||
(request) => request.url === "/$resources/current-date"
|
||||
);
|
||||
@@ -184,7 +182,7 @@ test("loads an unsaved system resource while an unrelated page request is pendin
|
||||
expect(requests).toContainEqual(unrelated);
|
||||
|
||||
queueResources([]);
|
||||
respond(Response.json([[getResourceKey(preview), { data: "2026-09-23" }]]));
|
||||
respond!(Response.json([[getResourceKey(preview), { data: "2026-09-23" }]]));
|
||||
await vi.waitFor(() => {
|
||||
expect(document.querySelector('[role="dialog"]')?.textContent).toContain(
|
||||
"2026-09-23"
|
||||
@@ -200,9 +198,7 @@ test("loads an unsaved system resource while an unrelated page request is pendin
|
||||
expect(sitemapLoadButton).toBeDefined();
|
||||
await act(async () => userEvent.click(sitemapLoadButton!));
|
||||
await vi.waitFor(() => expect(loaderCalls).toHaveLength(2));
|
||||
const sitemapRequests = JSON.parse(
|
||||
String(loaderCalls[1].body)
|
||||
) as ResourceRequest[];
|
||||
const sitemapRequests = (await loaderCalls[1].json()) as ResourceRequest[];
|
||||
const sitemapPreview = sitemapRequests.find(
|
||||
(request) => request.url === "/$resources/sitemap.xml"
|
||||
);
|
||||
@@ -210,7 +206,7 @@ test("loads an unsaved system resource while an unrelated page request is pendin
|
||||
|
||||
// A late response for the old subtype cannot replace the new subtype's UI.
|
||||
await selectOption("Sitemap resource", "Current date resource");
|
||||
respond(
|
||||
respond!(
|
||||
Response.json([
|
||||
[getResourceKey(sitemapPreview!), { data: "stale sitemap response" }],
|
||||
])
|
||||
@@ -409,9 +405,7 @@ test.each([
|
||||
dialog.querySelectorAll<HTMLButtonElement>("button")
|
||||
).find((button) => button.textContent === "Load data");
|
||||
expect(loadButton).toBeDefined();
|
||||
const fetchSpy = vi.spyOn(globalThis, "fetch");
|
||||
const priorCalls = fetchSpy.mock.calls.length;
|
||||
const priorPreviewLoads = previewLoaderCalls.mock.calls.length;
|
||||
const priorCalls = loaderCalls.length;
|
||||
const consoleErrorSpy = vi
|
||||
.spyOn(console, "error")
|
||||
.mockImplementation(() => {});
|
||||
@@ -434,10 +428,8 @@ test.each([
|
||||
expect(dialog.textContent).not.toContain('"preview"');
|
||||
});
|
||||
}
|
||||
expect(fetchSpy.mock.calls.length).toBe(priorCalls);
|
||||
expect(previewLoaderCalls.mock.calls.length).toBe(priorPreviewLoads);
|
||||
expect(loaderCalls.length).toBe(priorCalls);
|
||||
expect($resourcePreviewExchanges.get().size).toBe(0);
|
||||
fetchSpy.mockRestore();
|
||||
consoleErrorSpy.mockRestore();
|
||||
}
|
||||
);
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { FetchInterceptor } from "@mswjs/interceptors/fetch";
|
||||
import type { Asset } from "@webstudio-is/sdk";
|
||||
import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";
|
||||
import { AssetRevisionConflictError } from "@webstudio-is/content-engine/asset-content-repository";
|
||||
@@ -53,28 +54,38 @@ const EditorStory = ({
|
||||
useEffect(() => {
|
||||
const previousAssets = $assets.get();
|
||||
const previousPermit = $authPermit.get();
|
||||
const previousFetch = window.fetch;
|
||||
const interceptor = new FetchInterceptor();
|
||||
const currentAsset = state.startsWith("markdown") ? markdownAsset : asset;
|
||||
$assets.set(new Map([[currentAsset.id, currentAsset]]));
|
||||
$authPermit.set("own");
|
||||
window.fetch = async (input, init) => {
|
||||
if (String(input).includes(`/cgi/asset/${currentAsset.name}`)) {
|
||||
return state === "error"
|
||||
? new Response("", { status: 404 })
|
||||
: new Response(
|
||||
state.startsWith("markdown")
|
||||
? "# Article\n\nA Markdown preview.\n"
|
||||
: "Text file preview\nSecond line\n"
|
||||
);
|
||||
interceptor.on("request", ({ request, controller }) => {
|
||||
const url = new URL(request.url);
|
||||
if (
|
||||
url.origin === location.origin &&
|
||||
url.pathname === `/cgi/asset/${currentAsset.name}`
|
||||
) {
|
||||
if (request.method !== "GET") {
|
||||
controller.respondWith(Response.error());
|
||||
return;
|
||||
}
|
||||
controller.respondWith(
|
||||
state === "error"
|
||||
? new Response("", { status: 404 })
|
||||
: new Response(
|
||||
state.startsWith("markdown")
|
||||
? "# Article\n\nA Markdown preview.\n"
|
||||
: "Text file preview\nSecond line\n"
|
||||
)
|
||||
);
|
||||
}
|
||||
return previousFetch(input, init);
|
||||
};
|
||||
});
|
||||
interceptor.apply();
|
||||
setReady(true);
|
||||
return () => {
|
||||
setReady(false);
|
||||
$assets.set(previousAssets);
|
||||
$authPermit.set(previousPermit);
|
||||
window.fetch = previousFetch;
|
||||
interceptor.dispose();
|
||||
};
|
||||
}, [state]);
|
||||
return (
|
||||
|
||||
@@ -14,6 +14,7 @@ import { parseWebstudioJsxFragment } from "@webstudio-is/project-build/transfer/
|
||||
import { applyBuilderNamespacePatches } from "@webstudio-is/project-build/state";
|
||||
import { createPublishedProjectBundleFixture } from "@webstudio-is/protocol/fixtures";
|
||||
import * as projectBuild from "@webstudio-is/project-build/server";
|
||||
import { PrePublishAuditError } from "@webstudio-is/project-build/runtime";
|
||||
import * as projectApi from "@webstudio-is/project/index.server";
|
||||
import * as domainApi from "@webstudio-is/domain/index.server";
|
||||
import {
|
||||
@@ -820,6 +821,97 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("api router permits", () => {
|
||||
test.each([
|
||||
{ ownerAllowed: false, blocked: true },
|
||||
{ ownerAllowed: true, blocked: false },
|
||||
])(
|
||||
"uses owner diagnostics entitlement for publish findings ($ownerAllowed, $blocked)",
|
||||
async ({ ownerAllowed, blocked }) => {
|
||||
vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
|
||||
server.use(postgrestDb.get("Project", () => json({ userId: "owner-1" })));
|
||||
const context = createContext(true, {
|
||||
type: "user",
|
||||
userId: "collaborator",
|
||||
sessionCreatedAt: 0,
|
||||
isLoggedInToBuilder: async () => true,
|
||||
});
|
||||
context.planFeatures.allowPublishLogs = !ownerAllowed;
|
||||
const getOwnerPlanFeatures = vi.fn(async () => ({
|
||||
...defaultPlanFeatures,
|
||||
allowPublishLogs: ownerAllowed,
|
||||
}));
|
||||
context.getOwnerPlanFeatures = getOwnerPlanFeatures;
|
||||
const finding = {
|
||||
ruleId: "html-content-model",
|
||||
severity: "warning" as const,
|
||||
message: "x".repeat(200),
|
||||
location: { pageId: "page-1", instanceId: "instance-1" },
|
||||
};
|
||||
if (blocked) {
|
||||
vi.spyOn(domainApi, "publishStaticProject").mockRejectedValue(
|
||||
new PrePublishAuditError([finding])
|
||||
);
|
||||
} else {
|
||||
vi.spyOn(domainApi, "publishStaticProject").mockResolvedValue({
|
||||
success: true,
|
||||
name: "export.zip",
|
||||
build: { id: "build-1" },
|
||||
logHandle: undefined,
|
||||
findings: [finding],
|
||||
} as never);
|
||||
}
|
||||
|
||||
const result = await createCaller(context).publish.create({
|
||||
projectId: "project-1",
|
||||
target: "static",
|
||||
templates: ["ssg"],
|
||||
});
|
||||
expect(result.status).toBe(blocked ? "blocked" : "pending");
|
||||
expect(result.findings).toEqual([
|
||||
ownerAllowed
|
||||
? finding
|
||||
: { ...finding, message: "x".repeat(160), location: {} },
|
||||
]);
|
||||
expect(getOwnerPlanFeatures).toHaveBeenCalledExactlyOnceWith("owner-1");
|
||||
}
|
||||
);
|
||||
|
||||
test("keeps hosted audit failures blocked after checking domains", async () => {
|
||||
vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
|
||||
server.use(postgrestDb.get("Project", () => json({ userId: "owner-1" })));
|
||||
const context = createContext(true, {
|
||||
type: "user",
|
||||
userId: "owner-1",
|
||||
sessionCreatedAt: 0,
|
||||
isLoggedInToBuilder: async () => true,
|
||||
});
|
||||
vi.spyOn(projectApi, "loadById").mockResolvedValue({
|
||||
domain: "project.wstd.dev",
|
||||
domainsVirtual: [],
|
||||
} as never);
|
||||
vi.spyOn(domainApi, "publishProject").mockRejectedValue(
|
||||
new PrePublishAuditError([
|
||||
{
|
||||
ruleId: "json-prop-value",
|
||||
severity: "error",
|
||||
message: "Invalid prop",
|
||||
location: { propId: "prop-1" },
|
||||
},
|
||||
])
|
||||
);
|
||||
|
||||
await expect(
|
||||
createCaller(context).publish.create({
|
||||
projectId: "project-1",
|
||||
target: "staging",
|
||||
domains: ["project.wstd.dev"],
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
status: "blocked",
|
||||
findings: [{ ruleId: "json-prop-value", severity: "error" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("missing publish jobs carry a not-found error marker", async () => {
|
||||
vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
|
||||
vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());
|
||||
@@ -837,6 +929,41 @@ describe("api router permits", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("checks project access before reading a signed publish job", async () => {
|
||||
const permit = vi
|
||||
.spyOn(authorizeProject, "hasProjectPermit")
|
||||
.mockResolvedValue(true);
|
||||
vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());
|
||||
const getJob = vi
|
||||
.spyOn(domainApi, "getProjectPublishJob")
|
||||
.mockResolvedValue({ status: "pending" } as never);
|
||||
|
||||
await createCaller(createContext(true)).publish.getJob({
|
||||
projectId: "project-1",
|
||||
jobId: "build-prod",
|
||||
logHandle: "signed-handle",
|
||||
});
|
||||
expect(getJob).toHaveBeenCalledWith(
|
||||
{
|
||||
projectId: "project-1",
|
||||
jobId: "build-prod",
|
||||
logHandle: "signed-handle",
|
||||
},
|
||||
expect.anything()
|
||||
);
|
||||
|
||||
permit.mockResolvedValue(false);
|
||||
|
||||
await expect(
|
||||
createCaller(createContext(true)).publish.getJob({
|
||||
projectId: "project-1",
|
||||
jobId: "build-prod",
|
||||
logHandle: "signed-handle",
|
||||
})
|
||||
).rejects.toThrow();
|
||||
expect(getJob).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("unpublish completes without returning a nonexistent publish job", async () => {
|
||||
vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);
|
||||
vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
router,
|
||||
type AppContext,
|
||||
type AuthPermit,
|
||||
getProjectPlanFeatures,
|
||||
} from "@webstudio-is/trpc-interface/index.server";
|
||||
import {
|
||||
loadById,
|
||||
@@ -21,13 +22,17 @@ import {
|
||||
getDefaultPublishDomains,
|
||||
getVerifiedPublishDomains,
|
||||
getProjectPublishJob,
|
||||
getProjectPublishLog,
|
||||
listProjectDomains,
|
||||
listProjectPublishes,
|
||||
publishProject,
|
||||
publishStaticProject,
|
||||
getVisiblePublishFindings,
|
||||
updateProjectDomain,
|
||||
unpublishProjectDomains,
|
||||
verifyProjectDomain,
|
||||
} from "@webstudio-is/domain/index.server";
|
||||
import { PrePublishAuditError } from "@webstudio-is/project-build/runtime";
|
||||
import {
|
||||
getBuilderRuntimeOperationInputSchema,
|
||||
getBuildIntegrityIssues,
|
||||
@@ -67,6 +72,7 @@ import { componentMetas } from "~/shared/component-metas.server";
|
||||
import {
|
||||
generateCss,
|
||||
getStyleDeclKey,
|
||||
templates as templateSchema,
|
||||
type Asset,
|
||||
type AssetFolder,
|
||||
} from "@webstudio-is/sdk";
|
||||
@@ -1248,34 +1254,88 @@ export const apiRouter = router({
|
||||
),
|
||||
|
||||
create: projectMutation(
|
||||
projectIdInput.extend({
|
||||
target: z.enum(["staging", "production"]),
|
||||
domains: z.array(z.string()).optional(),
|
||||
message: z.string().optional(),
|
||||
idempotencyKey: z.string().optional(),
|
||||
}),
|
||||
z.discriminatedUnion("target", [
|
||||
projectIdInput.extend({
|
||||
target: z.enum(["staging", "production"]),
|
||||
domains: z.array(z.string()).optional(),
|
||||
message: z.string().optional(),
|
||||
idempotencyKey: z.string().optional(),
|
||||
}),
|
||||
projectIdInput.extend({
|
||||
target: z.literal("static"),
|
||||
templates: z.array(templateSchema).default(["ssg"]),
|
||||
idempotencyKey: z.string().optional(),
|
||||
}),
|
||||
]),
|
||||
"edit",
|
||||
async ({ auth, ctx, input }) => {
|
||||
const project = await loadById(input.projectId, ctx);
|
||||
const domains =
|
||||
input.domains ?? getDefaultPublishDomains(project, input.target);
|
||||
assertApiPublishDomains({ auth, domains, project });
|
||||
const { build, deploymentNotImplemented } = await publishProject(
|
||||
{ project, domains, target: input.target },
|
||||
const { allowPublishLogs } = await getProjectPlanFeatures(
|
||||
input.projectId,
|
||||
ctx
|
||||
);
|
||||
return {
|
||||
jobId: build.id,
|
||||
warning: deploymentNotImplemented
|
||||
? "Publish was recorded locally, but the deployment service is not available in this environment."
|
||||
: undefined,
|
||||
};
|
||||
try {
|
||||
if (input.target === "static") {
|
||||
const result = await publishStaticProject(
|
||||
{ projectId: input.projectId, templates: input.templates },
|
||||
ctx
|
||||
);
|
||||
if (result.success === false) {
|
||||
throw new Error(result.error);
|
||||
}
|
||||
return {
|
||||
status: "pending" as const,
|
||||
jobId: result.build.id,
|
||||
buildId: result.build.id,
|
||||
logHandle: result.logHandle,
|
||||
findings: getVisiblePublishFindings(
|
||||
result.findings,
|
||||
allowPublishLogs
|
||||
),
|
||||
artifact: { readiness: "pending" as const, name: result.name },
|
||||
};
|
||||
}
|
||||
const project = await loadById(input.projectId, ctx);
|
||||
const domains =
|
||||
input.domains ?? getDefaultPublishDomains(project, input.target);
|
||||
assertApiPublishDomains({ auth, domains, project });
|
||||
const result = await publishProject(
|
||||
{ project, domains, target: input.target },
|
||||
ctx
|
||||
);
|
||||
return {
|
||||
status: "pending" as const,
|
||||
jobId: result.build.id,
|
||||
buildId: result.build.id,
|
||||
logHandle: result.logHandle,
|
||||
findings: getVisiblePublishFindings(
|
||||
result.findings,
|
||||
allowPublishLogs
|
||||
),
|
||||
warning: result.deploymentNotImplemented
|
||||
? "Publish was recorded locally, but the deployment service is not available in this environment."
|
||||
: undefined,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof PrePublishAuditError) {
|
||||
return {
|
||||
status: "blocked" as const,
|
||||
findings: getVisiblePublishFindings(
|
||||
error.findings,
|
||||
allowPublishLogs
|
||||
),
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
{ command: "publish", client: "publish" }
|
||||
),
|
||||
|
||||
getJob: projectQuery(
|
||||
projectIdInput.extend({ jobId: z.string() }),
|
||||
projectIdInput.extend({
|
||||
jobId: z.string(),
|
||||
logHandle: z.string().max(2048).optional(),
|
||||
}),
|
||||
"view",
|
||||
async ({ ctx, input }) => {
|
||||
const publishJob = await getProjectPublishJob(input, ctx);
|
||||
@@ -1287,6 +1347,17 @@ export const apiRouter = router({
|
||||
{ command: "get-publish-job", client: "getPublishJob" }
|
||||
),
|
||||
|
||||
getLog: projectQuery(
|
||||
projectIdInput.extend({
|
||||
buildId: z.string(),
|
||||
logHandle: z.string().max(2048),
|
||||
cursor: z.number().int().nonnegative().safe().optional(),
|
||||
}),
|
||||
"view",
|
||||
async ({ ctx, input }) => getProjectPublishLog(input, ctx),
|
||||
{ command: "get-publish-log", client: "getPublishLog" }
|
||||
),
|
||||
|
||||
unpublish: projectMutation(
|
||||
projectIdInput.extend({
|
||||
target: z.enum(["staging", "production"]),
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
|
||||
import { http, HttpResponse } from "msw";
|
||||
import { setupServer } from "msw/node";
|
||||
import {
|
||||
getAssetContentHash,
|
||||
RESIZABLE_IMAGE_MIME_TYPES,
|
||||
@@ -8,9 +10,22 @@ import {
|
||||
getUrlAssetContentHash,
|
||||
} from "./asset-upload.server";
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
const server = setupServer();
|
||||
beforeAll(() =>
|
||||
server.listen({
|
||||
onUnhandledRequest(request, print) {
|
||||
const { origin } = new URL(request.url);
|
||||
if (
|
||||
origin === "https://example.com" ||
|
||||
origin === "https://source.example.com"
|
||||
) {
|
||||
print.error();
|
||||
}
|
||||
},
|
||||
})
|
||||
);
|
||||
afterEach(() => server.resetHandlers());
|
||||
afterAll(() => server.close());
|
||||
|
||||
test("keeps raw browser upload request bodies unchanged", async () => {
|
||||
const request = new Request(
|
||||
@@ -60,8 +75,17 @@ test("keeps JSON files with a root URL field as file content", async () => {
|
||||
});
|
||||
|
||||
test("keeps browser URL image uploads by fetching the remote image body", async () => {
|
||||
const fetch = vi.fn(async () => new Response("remote image"));
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
const received = vi.fn((request: Request) => {
|
||||
expect(request.headers.get("accept")).toBe(
|
||||
RESIZABLE_IMAGE_MIME_TYPES.join(",")
|
||||
);
|
||||
return new HttpResponse("remote image");
|
||||
});
|
||||
server.use(
|
||||
http.get("https://example.com/image.png", ({ request }) =>
|
||||
received(request)
|
||||
)
|
||||
);
|
||||
const request = new Request(
|
||||
"https://webstudio.is/rest/assets/uploads/image.png",
|
||||
{
|
||||
@@ -77,16 +101,19 @@ test("keeps browser URL image uploads by fetching the remote image body", async
|
||||
await expect(
|
||||
new Response(await getBrowserUploadBody(request, "application/json")).text()
|
||||
).resolves.toBe("remote image");
|
||||
expect(fetch).toHaveBeenCalledWith("https://example.com/image.png", {
|
||||
method: "GET",
|
||||
headers: { Accept: RESIZABLE_IMAGE_MIME_TYPES.join(",") },
|
||||
});
|
||||
expect(received).toHaveBeenCalledOnce();
|
||||
// The image backend must not replace other fetch requests in this process.
|
||||
await expect(
|
||||
fetch("data:text/plain,unrelated").then((response) => response.text())
|
||||
).resolves.toBe("unrelated");
|
||||
});
|
||||
|
||||
test("reports browser URL image fetch failures", async () => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => new Response("not found", { status: 404 }))
|
||||
server.use(
|
||||
http.get(
|
||||
"https://example.com/image.png",
|
||||
() => new HttpResponse("not found", { status: 404 })
|
||||
)
|
||||
);
|
||||
const request = new Request(
|
||||
"https://webstudio.is/rest/assets/uploads/image.png",
|
||||
@@ -109,8 +136,13 @@ test("reports browser URL image fetch failures", async () => {
|
||||
|
||||
test("hashes remote SVG bytes for upload deduplication", async () => {
|
||||
const svg = '<svg xmlns="http://www.w3.org/2000/svg"></svg>';
|
||||
const fetch = vi.fn(async () => new Response(svg));
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
const received = vi.fn(() => new HttpResponse(svg));
|
||||
server.use(
|
||||
http.get("https://source.example.com/cgi/image/logo.svg", ({ request }) => {
|
||||
expect(new URL(request.url).searchParams.get("format")).toBe("raw");
|
||||
return received();
|
||||
})
|
||||
);
|
||||
|
||||
await expect(
|
||||
getUrlAssetContentHash(
|
||||
@@ -118,5 +150,5 @@ test("hashes remote SVG bytes for upload deduplication", async () => {
|
||||
"logo.svg"
|
||||
)
|
||||
).resolves.toBe(await getAssetContentHash(new TextEncoder().encode(svg)));
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
expect(received).toHaveBeenCalledOnce();
|
||||
});
|
||||
@@ -2,7 +2,16 @@ import { createServer } from "node:http";
|
||||
import { createRequire } from "node:module";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { build } from "esbuild";
|
||||
import { beforeEach, expect, test, vi } from "vitest";
|
||||
import {
|
||||
afterAll,
|
||||
afterEach,
|
||||
beforeAll,
|
||||
beforeEach,
|
||||
expect,
|
||||
test,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { FetchInterceptor } from "@mswjs/interceptors/fetch";
|
||||
import { authorizeProject } from "@webstudio-is/trpc-interface/index.server";
|
||||
import * as projectApi from "@webstudio-is/project/index.server";
|
||||
import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server";
|
||||
@@ -29,9 +38,6 @@ vi.mock("@webstudio-is/sdk/protected-resource-fetch-node", () => ({
|
||||
createNodeProtectedResourceFetch: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/shared/context.server", () => ({ createContext: vi.fn() }));
|
||||
vi.mock("~/services/no-cross-origin-cookie", () => ({
|
||||
preventCrossOriginCookie: vi.fn(),
|
||||
}));
|
||||
vi.mock("~/services/csrf-session.server", () => ({ checkCsrf: vi.fn() }));
|
||||
vi.mock("~/env/env.server", () => ({
|
||||
default: {
|
||||
@@ -42,6 +48,31 @@ vi.mock("~/env/env.server", () => ({
|
||||
}));
|
||||
|
||||
const projectId = "090e6e14-ae50-4b2e-bd22-71733cec05bb";
|
||||
const interceptor = new FetchInterceptor();
|
||||
let sendEmail: typeof fetch | undefined;
|
||||
beforeAll(() => {
|
||||
interceptor.on("request", async ({ request, controller }) => {
|
||||
const endpoint = new URL(`${env.EMAIL_SERVICE_URL}/trpc/email.send`);
|
||||
const url = new URL(request.url);
|
||||
if (url.origin !== endpoint.origin || url.pathname !== endpoint.pathname) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
controller.respondWith(
|
||||
request.method === "POST" && sendEmail !== undefined
|
||||
? await sendEmail(request)
|
||||
: Response.error()
|
||||
);
|
||||
} catch (error) {
|
||||
controller.errorWith(error);
|
||||
}
|
||||
});
|
||||
interceptor.apply();
|
||||
});
|
||||
afterEach(() => {
|
||||
sendEmail = undefined;
|
||||
});
|
||||
afterAll(() => interceptor.dispose());
|
||||
type EmailServiceEnvelope = {
|
||||
to: { address: string; name?: string }[];
|
||||
subject: string;
|
||||
@@ -67,7 +98,15 @@ const request = (file?: File, headers?: HeadersInit) => {
|
||||
if (file) {
|
||||
formData.set("attachment", file);
|
||||
}
|
||||
return new Request(url, { method: "POST", body: formData, headers });
|
||||
const requestHeaders = new Headers(headers);
|
||||
if (!requestHeaders.has("sec-fetch-site")) {
|
||||
requestHeaders.set("sec-fetch-site", "same-origin");
|
||||
}
|
||||
return new Request(url, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
headers: requestHeaders,
|
||||
});
|
||||
};
|
||||
|
||||
const draftBuild = {
|
||||
@@ -149,6 +188,15 @@ beforeEach(() => {
|
||||
vi.mocked(loadDevBuildByProjectId).mockResolvedValue(draftBuild as never);
|
||||
});
|
||||
|
||||
test("unconfigured Email Service requests fail without reaching the live service", async () => {
|
||||
await expect(
|
||||
fetch(`${env.EMAIL_SERVICE_URL}/trpc/email.send`, { method: "POST" })
|
||||
).rejects.toBeInstanceOf(TypeError);
|
||||
await expect(
|
||||
fetch("data:text/plain,unrelated").then((response) => response.text())
|
||||
).resolves.toBe("unrelated");
|
||||
});
|
||||
|
||||
test("a user without project build permission cannot execute Preview actions", async () => {
|
||||
vi.mocked(authorizeProject.hasProjectPermit).mockResolvedValue(false);
|
||||
await expect(action({ request: request() } as never)).rejects.toMatchObject({
|
||||
@@ -170,14 +218,11 @@ test("an unauthenticated request cannot load the project draft", async () => {
|
||||
});
|
||||
|
||||
test("a cross-origin request cannot reach project authorization or actions", async () => {
|
||||
const { preventCrossOriginCookie } =
|
||||
await import("~/services/no-cross-origin-cookie");
|
||||
vi.mocked(preventCrossOriginCookie).mockImplementationOnce(() => {
|
||||
throw new Response("Cross-origin request", { status: 403 });
|
||||
});
|
||||
await expect(action({ request: request() } as never)).rejects.toMatchObject({
|
||||
status: 403,
|
||||
});
|
||||
await expect(
|
||||
action({
|
||||
request: request(undefined, { "sec-fetch-site": "cross-site" }),
|
||||
} as never)
|
||||
).rejects.toMatchObject({ status: 403 });
|
||||
expect(createContext).not.toHaveBeenCalled();
|
||||
expect(createNodeProtectedResourceFetch).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -269,7 +314,7 @@ test("server MCP simulation sends Email with Builder-held credentials", async ()
|
||||
expect(body.to).toEqual([{ address: "testing@webstudio.is" }]);
|
||||
return Response.json({ result: { data: { id: "sent" } } });
|
||||
});
|
||||
vi.stubGlobal("fetch", send);
|
||||
sendEmail = send;
|
||||
const result = await simulateFormSubmission({
|
||||
context: { authorization: { type: "token" } } as never,
|
||||
projectId,
|
||||
@@ -616,7 +661,7 @@ test.each([false, true])(
|
||||
Response.json({ result: { data: { id: "sent" } } })
|
||||
);
|
||||
if (delayedSave) {
|
||||
vi.stubGlobal("fetch", send);
|
||||
sendEmail = send;
|
||||
}
|
||||
const requests: string[] = [];
|
||||
let receivedHeaders: { auth?: string; csrf?: string } | undefined;
|
||||
@@ -801,7 +846,6 @@ test.each([false, true])(
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
await browser?.close();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
@@ -837,7 +881,11 @@ test("Preview returns JSON when Remix's Response has no static json method", asy
|
||||
const formData = await invalid.formData();
|
||||
formData.delete("ws--form-bot");
|
||||
const failure = await action({
|
||||
request: new Request(invalid.url, { method: "POST", body: formData }),
|
||||
request: new Request(invalid.url, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
headers: { "sec-fetch-site": "same-origin" },
|
||||
}),
|
||||
} as never);
|
||||
expect(failure.status).toBe(400);
|
||||
expect(await failure.json()).toMatchObject({
|
||||
@@ -868,6 +916,7 @@ test.each([
|
||||
request: new Request(validRequest.url, {
|
||||
method: "POST",
|
||||
body: formData,
|
||||
headers: { "sec-fetch-site": "same-origin" },
|
||||
}),
|
||||
} as never);
|
||||
expect(await response.json()).toMatchObject({
|
||||
@@ -1054,6 +1103,7 @@ test("Preview binds each page's submitted values and browser context to its own
|
||||
method: "POST",
|
||||
body: formData,
|
||||
headers: {
|
||||
"sec-fetch-site": "same-origin",
|
||||
"cf-connecting-ip": page.ip,
|
||||
"x-forwarded-for": "192.0.2.99",
|
||||
"user-agent": page.userAgent,
|
||||
@@ -1181,7 +1231,7 @@ test.each([
|
||||
{ headers: { "cache-control": "private, no-store" } }
|
||||
);
|
||||
});
|
||||
vi.stubGlobal("fetch", send);
|
||||
sendEmail = send;
|
||||
try {
|
||||
const response = await action({
|
||||
request: request(new File(["hello"], "hello.txt"), {
|
||||
@@ -1255,7 +1305,6 @@ test.each([
|
||||
} finally {
|
||||
env.DEPLOYMENT_ENVIRONMENT = previousEnvironment;
|
||||
env.EMAIL_SERVICE_URL = previousEmailServiceUrl;
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -1340,36 +1389,32 @@ test("two Email actions identify each credential failure in local Preview", asyn
|
||||
{ status: 401 }
|
||||
)
|
||||
);
|
||||
vi.stubGlobal("fetch", send);
|
||||
try {
|
||||
const response = await action({ request: request() } as never);
|
||||
const result = (await response.json()) as unknown as {
|
||||
errors: Array<{ resourceName: string; message: string }>;
|
||||
};
|
||||
expect(send).toHaveBeenCalledTimes(2);
|
||||
expect(result.errors).toHaveLength(2);
|
||||
expect(
|
||||
result.errors.map(({ resourceName, message }) => ({
|
||||
resourceName,
|
||||
message,
|
||||
}))
|
||||
).toEqual([
|
||||
{
|
||||
resourceName: "Email to owner",
|
||||
message: expect.stringContaining(
|
||||
"Email to owner: the email service rejected"
|
||||
),
|
||||
},
|
||||
{
|
||||
resourceName: "Email to visitor",
|
||||
message: expect.stringContaining(
|
||||
"Email to visitor: the email service rejected"
|
||||
),
|
||||
},
|
||||
]);
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
sendEmail = send;
|
||||
const response = await action({ request: request() } as never);
|
||||
const result = (await response.json()) as unknown as {
|
||||
errors: Array<{ resourceName: string; message: string }>;
|
||||
};
|
||||
expect(send).toHaveBeenCalledTimes(2);
|
||||
expect(result.errors).toHaveLength(2);
|
||||
expect(
|
||||
result.errors.map(({ resourceName, message }) => ({
|
||||
resourceName,
|
||||
message,
|
||||
}))
|
||||
).toEqual([
|
||||
{
|
||||
resourceName: "Email to owner",
|
||||
message: expect.stringContaining(
|
||||
"Email to owner: the email service rejected"
|
||||
),
|
||||
},
|
||||
{
|
||||
resourceName: "Email to visitor",
|
||||
message: expect.stringContaining(
|
||||
"Email to visitor: the email service rejected"
|
||||
),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("Email Service per-site limit fails the email action without HTTP egress", async () => {
|
||||
@@ -1397,26 +1442,22 @@ test("Email Service per-site limit fails the email action without HTTP egress",
|
||||
{ status: 429 }
|
||||
)
|
||||
);
|
||||
vi.stubGlobal("fetch", send);
|
||||
try {
|
||||
const response = await action({ request: request() } as never);
|
||||
expect(await response.json()).toMatchObject({
|
||||
success: false,
|
||||
errors: [
|
||||
{
|
||||
resourceId: "webhook",
|
||||
status: 429,
|
||||
message: "Email sending limit reached",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(send).toHaveBeenCalledOnce(); // a quota rejection is not retried
|
||||
expect(
|
||||
vi.mocked(createNodeProtectedResourceFetch).mock.results[0].value
|
||||
).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
sendEmail = send;
|
||||
const response = await action({ request: request() } as never);
|
||||
expect(await response.json()).toMatchObject({
|
||||
success: false,
|
||||
errors: [
|
||||
{
|
||||
resourceId: "webhook",
|
||||
status: 429,
|
||||
message: "Email sending limit reached",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(send).toHaveBeenCalledOnce(); // a quota rejection is not retried
|
||||
expect(
|
||||
vi.mocked(createNodeProtectedResourceFetch).mock.results[0].value
|
||||
).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("authenticated Preview returns bounded actual exchange metadata privately without replay", async () => {
|
||||
@@ -1507,28 +1548,24 @@ test("Email Preview inspection retains user-authored Resource subject and body",
|
||||
const send = vi.fn(async () =>
|
||||
Response.json({ result: { data: { id: "sent" } } })
|
||||
);
|
||||
vi.stubGlobal("fetch", send);
|
||||
try {
|
||||
const response = await action({ request: request() } as never);
|
||||
const result = (await response.json()) as unknown as {
|
||||
success: boolean;
|
||||
previewExchanges: PreviewFormExchange[];
|
||||
};
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.previewExchanges[0].request.body).toMatchObject({
|
||||
to: [{ address: "team@example.com" }],
|
||||
subject: "Configured Email subject",
|
||||
headers: { "X-Message-ID": expect.stringMatching(/^[a-f0-9]{16}$/) },
|
||||
text: "Configured Email body [redacted] public-example-token",
|
||||
});
|
||||
expect(result.previewExchanges[0].response.body).toEqual({
|
||||
result: { data: { id: "sent" } },
|
||||
});
|
||||
expect(JSON.stringify(result.previewExchanges)).not.toContain(
|
||||
"server-only-test-token"
|
||||
);
|
||||
expect(send).toHaveBeenCalledOnce();
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
sendEmail = send;
|
||||
const response = await action({ request: request() } as never);
|
||||
const result = (await response.json()) as unknown as {
|
||||
success: boolean;
|
||||
previewExchanges: PreviewFormExchange[];
|
||||
};
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.previewExchanges[0].request.body).toMatchObject({
|
||||
to: [{ address: "team@example.com" }],
|
||||
subject: "Configured Email subject",
|
||||
headers: { "X-Message-ID": expect.stringMatching(/^[a-f0-9]{16}$/) },
|
||||
text: "Configured Email body [redacted] public-example-token",
|
||||
});
|
||||
expect(result.previewExchanges[0].response.body).toEqual({
|
||||
result: { data: { id: "sent" } },
|
||||
});
|
||||
expect(JSON.stringify(result.previewExchanges)).not.toContain(
|
||||
"server-only-test-token"
|
||||
);
|
||||
expect(send).toHaveBeenCalledOnce();
|
||||
});
|
||||
File renamed without changes.
File renamed without changes.
@@ -38,7 +38,12 @@ const userRow = {
|
||||
|
||||
describe("getUserById (msw)", () => {
|
||||
test("returns user when found", async () => {
|
||||
server.use(db.get("User", () => json(userRow)));
|
||||
server.use(
|
||||
db.get("User", ({ request }) => {
|
||||
expect(new URL(request.url).searchParams.get("id")).toBe("eq.user-1");
|
||||
return json(userRow);
|
||||
})
|
||||
);
|
||||
|
||||
const result = await getUserById(createContext(), "user-1");
|
||||
expect(result.id).toBe("user-1");
|
||||
@@ -69,9 +74,17 @@ describe("createOrLoginWithDev (msw)", () => {
|
||||
let workspaceChecked = false;
|
||||
server.use(
|
||||
// User SELECT resolves successfully → existing user
|
||||
db.get("User", () => json(userRow)),
|
||||
db.get("User", ({ request }) => {
|
||||
expect(new URL(request.url).searchParams.get("email")).toBe(
|
||||
"eq.test@example.com"
|
||||
);
|
||||
return json(userRow);
|
||||
}),
|
||||
// Workspace check — has default workspace
|
||||
db.get("Workspace", () => {
|
||||
db.get("Workspace", ({ request }) => {
|
||||
const filters = new URL(request.url).searchParams;
|
||||
expect(filters.get("userId")).toBe("eq.user-1");
|
||||
expect(filters.get("isDefault")).toBe("eq.true");
|
||||
workspaceChecked = true;
|
||||
return json({ id: "ws-1" });
|
||||
})
|
||||
@@ -91,7 +104,12 @@ describe("createOrLoginWithDev (msw)", () => {
|
||||
db.get("User", () => json(userRow)),
|
||||
// maybeSingle returns null when no row exists
|
||||
db.get("Workspace", () => json(null)),
|
||||
db.post("Workspace", () => {
|
||||
db.post("Workspace", async ({ request }) => {
|
||||
expect(await request.json()).toEqual({
|
||||
name: "My workspace",
|
||||
isDefault: true,
|
||||
userId: "user-1",
|
||||
});
|
||||
workspaceCreated = true;
|
||||
return json({ id: "ws-new" }, { status: 201 });
|
||||
})
|
||||
@@ -106,21 +124,36 @@ describe("createOrLoginWithDev (msw)", () => {
|
||||
});
|
||||
|
||||
test("creates new user and workspace when email not found", async () => {
|
||||
let userInserted = false;
|
||||
let insertedUserId: string | undefined;
|
||||
let workspaceInserted = false;
|
||||
server.use(
|
||||
// User SELECT → PGRST116 (not found)
|
||||
db.get("User", () =>
|
||||
json(
|
||||
db.get("User", ({ request }) => {
|
||||
expect(new URL(request.url).searchParams.get("email")).toBe(
|
||||
"eq.new@example.com"
|
||||
);
|
||||
return json(
|
||||
{ code: "PGRST116", message: "Row not found", details: "", hint: "" },
|
||||
{ status: 406 }
|
||||
)
|
||||
),
|
||||
db.post("User", () => {
|
||||
userInserted = true;
|
||||
return json({ ...userRow, id: "new-user" }, { status: 201 });
|
||||
);
|
||||
}),
|
||||
db.post("Workspace", () => {
|
||||
db.post("User", async ({ request }) => {
|
||||
const body = (await request.json()) as Record<string, unknown>;
|
||||
expect(body).toMatchObject({
|
||||
email: "new@example.com",
|
||||
username: "admin",
|
||||
provider: "dev",
|
||||
});
|
||||
expect(body.id).toEqual(expect.any(String));
|
||||
insertedUserId = body.id as string;
|
||||
return json({ ...userRow, ...body }, { status: 201 });
|
||||
}),
|
||||
db.post("Workspace", async ({ request }) => {
|
||||
expect(await request.json()).toEqual({
|
||||
name: "My workspace",
|
||||
isDefault: true,
|
||||
userId: insertedUserId,
|
||||
});
|
||||
workspaceInserted = true;
|
||||
return json({ id: "ws-new" }, { status: 201 });
|
||||
})
|
||||
@@ -131,8 +164,8 @@ describe("createOrLoginWithDev (msw)", () => {
|
||||
"new@example.com"
|
||||
);
|
||||
|
||||
expect(result.email).toBe("test@example.com"); // from userRow mock
|
||||
expect(userInserted).toBe(true);
|
||||
expect(result.email).toBe("new@example.com");
|
||||
expect(insertedUserId).toBeDefined();
|
||||
expect(workspaceInserted).toBe(true);
|
||||
});
|
||||
|
||||
@@ -167,6 +200,7 @@ describe("createOrLoginWithOAuth (msw)", () => {
|
||||
server.use(
|
||||
db.get("User", () => json(userRow)),
|
||||
db.patch("User", async ({ request }) => {
|
||||
expect(new URL(request.url).searchParams.get("id")).toBe("eq.user-1");
|
||||
capturedBody = await request.json();
|
||||
return json(updatedUser);
|
||||
}),
|
||||
@@ -196,9 +230,11 @@ describe("updateUserProjectsTags (msw)", () => {
|
||||
|
||||
test("returns updated tags", async () => {
|
||||
server.use(
|
||||
db.patch("User", () =>
|
||||
json({ ...userRow, projectsTags: tags }, { status: 200 })
|
||||
)
|
||||
db.patch("User", async ({ request }) => {
|
||||
expect(new URL(request.url).searchParams.get("id")).toBe("eq.user-1");
|
||||
expect(await request.json()).toEqual({ projectsTags: tags });
|
||||
return json({ ...userRow, projectsTags: tags }, { status: 200 });
|
||||
})
|
||||
);
|
||||
|
||||
const result = await updateUserProjectsTags({ tags }, createContext());
|
||||
|
||||
+2
-20
@@ -26,6 +26,7 @@ const proPlan = {
|
||||
allowAuth: true,
|
||||
allowContentMode: true,
|
||||
allowStagingPublish: true,
|
||||
allowPublishLogs: false,
|
||||
maxContactEmailsPerProject: 5,
|
||||
maxDomainsAllowedPerUser: 100,
|
||||
maxDailyPublishesPerUser: 100,
|
||||
@@ -44,6 +45,7 @@ const freePlan = {
|
||||
allowAuth: false,
|
||||
allowContentMode: false,
|
||||
allowStagingPublish: false,
|
||||
allowPublishLogs: false,
|
||||
maxContactEmailsPerProject: 0,
|
||||
maxDomainsAllowedPerUser: 0,
|
||||
maxDailyPublishesPerUser: 10,
|
||||
@@ -597,16 +599,6 @@ describe("getPermissions", () => {
|
||||
}).maxDomainsAllowedPerUser
|
||||
).toBe(100);
|
||||
});
|
||||
|
||||
test("free plan has 0", () => {
|
||||
expect(
|
||||
getPermissions({
|
||||
role: "own",
|
||||
planFeatures: freePlan,
|
||||
workspaces: [],
|
||||
}).maxDomainsAllowedPerUser
|
||||
).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("maxDailyPublishesPerUser", () => {
|
||||
@@ -629,16 +621,6 @@ describe("getPermissions", () => {
|
||||
}).maxDailyPublishesPerUser
|
||||
).toBe(100);
|
||||
});
|
||||
|
||||
test("free plan allows limited publishes", () => {
|
||||
expect(
|
||||
getPermissions({
|
||||
role: "own",
|
||||
planFeatures: freePlan,
|
||||
workspaces: [],
|
||||
}).maxDailyPublishesPerUser
|
||||
).toBe(10);
|
||||
});
|
||||
});
|
||||
|
||||
describe("canInviteMembers", () => {
|
||||
@@ -24,11 +24,6 @@ import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
|
||||
import * as assetUploader from "@webstudio-is/asset-uploader/server";
|
||||
import type { NormalizedPatchRequest } from "./patch-normalize.server";
|
||||
|
||||
const applyPatchRequestForTest = (
|
||||
context: AppContext,
|
||||
patch: NormalizedPatchRequest
|
||||
) => applyPatchRequest(context, patch);
|
||||
|
||||
const configuredResources = JSON.stringify([
|
||||
{
|
||||
id: "posts",
|
||||
@@ -60,33 +55,42 @@ const createContext = () => {
|
||||
const context = {
|
||||
postgrest: {
|
||||
client: {
|
||||
from: () => ({
|
||||
select: (columns: string) => ({
|
||||
selectedColumns,
|
||||
eq: () => {
|
||||
selectedColumns.push(columns);
|
||||
const result = Promise.resolve({
|
||||
data: [
|
||||
Object.fromEntries(
|
||||
columns
|
||||
.split(", ")
|
||||
.map((column) => [
|
||||
column,
|
||||
buildRow[column as keyof typeof buildRow],
|
||||
])
|
||||
),
|
||||
],
|
||||
error: undefined,
|
||||
});
|
||||
return Object.assign(result, {
|
||||
single: async () => ({
|
||||
data: buildRow,
|
||||
from: (table: string) => {
|
||||
if (table !== "Build") {
|
||||
throw new Error(`Unexpected table: ${table}`);
|
||||
}
|
||||
return {
|
||||
select: (columns: string) => ({
|
||||
eq: (column: string, value: string) => {
|
||||
if (column !== "id" || value !== "build-1") {
|
||||
throw new Error(
|
||||
`Unexpected Build filter: ${column}=${value}`
|
||||
);
|
||||
}
|
||||
selectedColumns.push(columns);
|
||||
const result = Promise.resolve({
|
||||
data: [
|
||||
Object.fromEntries(
|
||||
columns
|
||||
.split(", ")
|
||||
.map((column) => [
|
||||
column,
|
||||
buildRow[column as keyof typeof buildRow],
|
||||
])
|
||||
),
|
||||
],
|
||||
error: undefined,
|
||||
}),
|
||||
});
|
||||
},
|
||||
}),
|
||||
}),
|
||||
});
|
||||
return Object.assign(result, {
|
||||
single: async () => ({
|
||||
data: buildRow,
|
||||
error: undefined,
|
||||
}),
|
||||
});
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -143,7 +147,7 @@ describe("applyPatchRequest", () => {
|
||||
});
|
||||
const context = createContext();
|
||||
await expect(
|
||||
applyPatchRequestForTest(context, { ...patch, entries: [entry] })
|
||||
applyPatchRequest(context, { ...patch, entries: [entry] })
|
||||
).resolves.toMatchObject({ status: "ok" });
|
||||
const columns = context.selectedColumns.at(-1)?.split(", ");
|
||||
expect(columns).toEqual(expect.arrayContaining(["instances", "props"]));
|
||||
@@ -152,7 +156,7 @@ describe("applyPatchRequest", () => {
|
||||
}
|
||||
);
|
||||
|
||||
test("applies a combined resource and asset patch without derived work", async () => {
|
||||
test("forwards a combined resource and asset patch", async () => {
|
||||
const combinedEntry = {
|
||||
...patch.entries[0],
|
||||
transaction: {
|
||||
@@ -192,13 +196,30 @@ describe("applyPatchRequest", () => {
|
||||
version: 4,
|
||||
build: { ...build, version: 4, resources: nextResources },
|
||||
}));
|
||||
await applyPatchRequestForTest(createContext(), {
|
||||
const context = createContext();
|
||||
const result = await applyPatchRequest(context, {
|
||||
...patch,
|
||||
entries: [combinedEntry],
|
||||
});
|
||||
expect(context.selectedColumns).toEqual([
|
||||
"projectId, version",
|
||||
"projectId, version, lastTransactionId, resources, props, instances",
|
||||
]);
|
||||
expect(patchLoadedBuild).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({
|
||||
transactions: [combinedEntry.transaction],
|
||||
build: expect.objectContaining({ resources: configuredResources }),
|
||||
}),
|
||||
{ writer: 1 }
|
||||
);
|
||||
expect(result).toEqual({
|
||||
status: "ok",
|
||||
version: 4,
|
||||
entries: [{ seq: 1, transactionId: "tx-combined", status: "accepted" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("applies asset-folder patches without derived work", async () => {
|
||||
test("forwards asset-folder patches", async () => {
|
||||
const folderEntry = {
|
||||
...patch.entries[0],
|
||||
transaction: {
|
||||
@@ -223,15 +244,22 @@ describe("applyPatchRequest", () => {
|
||||
build: { ...build, version: 4 },
|
||||
}));
|
||||
|
||||
await expect(
|
||||
applyPatchRequestForTest(createContext(), {
|
||||
...patch,
|
||||
entries: [folderEntry],
|
||||
})
|
||||
).resolves.toMatchObject({ status: "ok" });
|
||||
const result = await applyPatchRequest(createContext(), {
|
||||
...patch,
|
||||
entries: [folderEntry],
|
||||
});
|
||||
expect(patchLoadedBuild).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({ transactions: [folderEntry.transaction] }),
|
||||
{ writer: 1 }
|
||||
);
|
||||
expect(result).toEqual({
|
||||
status: "ok",
|
||||
version: 4,
|
||||
entries: [{ seq: 1, transactionId: "tx-folder", status: "accepted" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("applies added assets without derived work", async () => {
|
||||
test("forwards added assets", async () => {
|
||||
const assetEntry = {
|
||||
...patch.entries[0],
|
||||
transaction: {
|
||||
@@ -260,15 +288,22 @@ describe("applyPatchRequest", () => {
|
||||
build: { ...build, version: 4 },
|
||||
}));
|
||||
|
||||
await expect(
|
||||
applyPatchRequestForTest(createContext(), {
|
||||
...patch,
|
||||
entries: [assetEntry],
|
||||
})
|
||||
).resolves.toMatchObject({ status: "ok" });
|
||||
const result = await applyPatchRequest(createContext(), {
|
||||
...patch,
|
||||
entries: [assetEntry],
|
||||
});
|
||||
expect(patchLoadedBuild).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({ transactions: [assetEntry.transaction] }),
|
||||
{ writer: 1 }
|
||||
);
|
||||
expect(result).toEqual({
|
||||
status: "ok",
|
||||
version: 4,
|
||||
entries: [{ seq: 1, transactionId: "tx-asset-add", status: "accepted" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("applies a swapped asset revision without derived work", async () => {
|
||||
test("forwards a swapped asset revision", async () => {
|
||||
const assetEntry = {
|
||||
...patch.entries[0],
|
||||
transaction: {
|
||||
@@ -297,13 +332,24 @@ describe("applyPatchRequest", () => {
|
||||
build: { ...build, version: 4 },
|
||||
}));
|
||||
|
||||
await applyPatchRequestForTest(createContext(), {
|
||||
const result = await applyPatchRequest(createContext(), {
|
||||
...patch,
|
||||
entries: [assetEntry],
|
||||
});
|
||||
expect(patchLoadedBuild).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({ transactions: [assetEntry.transaction] }),
|
||||
{ writer: 1 }
|
||||
);
|
||||
expect(result).toEqual({
|
||||
status: "ok",
|
||||
version: 4,
|
||||
entries: [
|
||||
{ seq: 1, transactionId: "tx-asset-revision", status: "accepted" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("applies standard asset metadata changes without derived work", async () => {
|
||||
test("forwards standard asset metadata changes", async () => {
|
||||
const assetEntry = {
|
||||
...patch.entries[0],
|
||||
transaction: {
|
||||
@@ -332,13 +378,24 @@ describe("applyPatchRequest", () => {
|
||||
build: { ...build, version: 4 },
|
||||
}));
|
||||
|
||||
await applyPatchRequestForTest(createContext(), {
|
||||
const result = await applyPatchRequest(createContext(), {
|
||||
...patch,
|
||||
entries: [assetEntry],
|
||||
});
|
||||
expect(patchLoadedBuild).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({ transactions: [assetEntry.transaction] }),
|
||||
{ writer: 1 }
|
||||
);
|
||||
expect(result).toEqual({
|
||||
status: "ok",
|
||||
version: 4,
|
||||
entries: [
|
||||
{ seq: 1, transactionId: "tx-asset-filename", status: "accepted" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("applies asset descriptions without derived work", async () => {
|
||||
test("forwards asset descriptions", async () => {
|
||||
const assetEntry = {
|
||||
...patch.entries[0],
|
||||
transaction: {
|
||||
@@ -367,10 +424,21 @@ describe("applyPatchRequest", () => {
|
||||
build: { ...build, version: 4 },
|
||||
}));
|
||||
|
||||
await applyPatchRequestForTest(createContext(), {
|
||||
const result = await applyPatchRequest(createContext(), {
|
||||
...patch,
|
||||
entries: [assetEntry],
|
||||
});
|
||||
expect(patchLoadedBuild).toHaveBeenCalledExactlyOnceWith(
|
||||
expect.objectContaining({ transactions: [assetEntry.transaction] }),
|
||||
{ writer: 1 }
|
||||
);
|
||||
expect(result).toEqual({
|
||||
status: "ok",
|
||||
version: 4,
|
||||
entries: [
|
||||
{ seq: 1, transactionId: "tx-asset-description", status: "accepted" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("returns per-entry partial results while applying authorized entries", async () => {
|
||||
@@ -391,7 +459,7 @@ describe("applyPatchRequest", () => {
|
||||
|
||||
const context = createContext();
|
||||
|
||||
const result = await applyPatchRequestForTest(context, patch);
|
||||
const result = await applyPatchRequest(context, patch);
|
||||
|
||||
expect(createContentModeCapabilities).not.toHaveBeenCalled();
|
||||
expect(context.selectedColumns).toEqual([
|
||||
@@ -442,7 +510,7 @@ describe("applyPatchRequest", () => {
|
||||
}));
|
||||
const context = createContext();
|
||||
|
||||
const result = await applyPatchRequestForTest(context, patch);
|
||||
const result = await applyPatchRequest(context, patch);
|
||||
|
||||
expect(createContentModeCapabilities).toHaveBeenCalledWith({
|
||||
breakpoints: JSON.stringify([]),
|
||||
@@ -491,12 +559,12 @@ describe("applyPatchRequest", () => {
|
||||
);
|
||||
|
||||
try {
|
||||
await applyPatchRequestForTest(createContext(), folderPatch);
|
||||
await applyPatchRequest(createContext(), folderPatch);
|
||||
expect(loadFolders).toHaveBeenCalledTimes(1);
|
||||
expect(loadFolders).toHaveBeenCalledWith("project-1", expect.anything(), {
|
||||
skipPermissionsCheck: true,
|
||||
});
|
||||
await applyPatchRequestForTest(createContext(), patch);
|
||||
await applyPatchRequest(createContext(), patch);
|
||||
expect(loadFolders).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
loadFolders.mockRestore();
|
||||
@@ -515,7 +583,7 @@ describe("applyPatchRequest", () => {
|
||||
});
|
||||
const context = createContext();
|
||||
|
||||
const result = await applyPatchRequestForTest(context, patch);
|
||||
const result = await applyPatchRequest(context, patch);
|
||||
|
||||
expect(context.selectedColumns).toEqual(["projectId, version"]);
|
||||
expect(patchLoadedBuild).not.toHaveBeenCalled();
|
||||
@@ -555,7 +623,7 @@ describe("applyPatchRequest", () => {
|
||||
}));
|
||||
const context = createContext();
|
||||
|
||||
const result = await applyPatchRequestForTest(context, assetsPatch);
|
||||
const result = await applyPatchRequest(context, assetsPatch);
|
||||
|
||||
expect(context.selectedColumns).toEqual([
|
||||
"projectId, version",
|
||||
@@ -597,7 +665,7 @@ describe("applyPatchRequest", () => {
|
||||
}))
|
||||
.mockResolvedValueOnce({ status: "error", errors: "entry failed" });
|
||||
|
||||
const result = await applyPatchRequestForTest(createContext(), patch);
|
||||
const result = await applyPatchRequest(createContext(), patch);
|
||||
|
||||
expect(result).toEqual({
|
||||
status: "partial",
|
||||
@@ -627,7 +695,7 @@ describe("applyPatchRequest", () => {
|
||||
errors: "first save failed",
|
||||
});
|
||||
|
||||
const result = await applyPatchRequestForTest(createContext(), patch);
|
||||
const result = await applyPatchRequest(createContext(), patch);
|
||||
|
||||
expect(patchLoadedBuild).toHaveBeenCalledTimes(1);
|
||||
expect(result).toEqual({
|
||||
@@ -670,7 +738,7 @@ describe("applyPatchRequest", () => {
|
||||
build: { ...build, version: 5 },
|
||||
}));
|
||||
|
||||
const result = await applyPatchRequestForTest(createContext(), patch);
|
||||
const result = await applyPatchRequest(createContext(), patch);
|
||||
|
||||
expect(patchLoadedBuild).toHaveBeenCalledTimes(2);
|
||||
expect(patchLoadedBuild).toHaveBeenNthCalledWith(
|
||||
@@ -734,10 +802,7 @@ describe("applyPatchRequest", () => {
|
||||
build: { ...build, version: 4 },
|
||||
}));
|
||||
|
||||
const result = await applyPatchRequestForTest(
|
||||
createContext(),
|
||||
duplicatePatch
|
||||
);
|
||||
const result = await applyPatchRequest(createContext(), duplicatePatch);
|
||||
|
||||
expect(result).toEqual({
|
||||
status: "partial",
|
||||
@@ -772,9 +837,9 @@ describe("applyPatchRequest", () => {
|
||||
}))
|
||||
.mockRejectedValueOnce(new Error("PostgREST unavailable"));
|
||||
|
||||
await expect(
|
||||
applyPatchRequestForTest(createContext(), patch)
|
||||
).rejects.toThrow("PostgREST unavailable");
|
||||
await expect(applyPatchRequest(createContext(), patch)).rejects.toThrow(
|
||||
"PostgREST unavailable"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -152,6 +152,7 @@
|
||||
"zod-validation-error": "^5.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@mswjs/interceptors": "^0.41.2",
|
||||
"@playwright/test": "1.50.1",
|
||||
"@remix-run/dev": "^2.16.5",
|
||||
"@types/debug": "^4.1.12",
|
||||
|
||||
@@ -14,13 +14,45 @@ Choose **Validate** in the publish dialog before publishing or exporting. Webstu
|
||||
checks publishable pages for broken Resource references and invalid HTML nesting
|
||||
that could make the generated site fail or behave unexpectedly.
|
||||
|
||||
- **Errors** stop publishing until you resolve them.
|
||||
- Validation errors should be fixed before publishing. Publish also runs
|
||||
best-effort checks while sending the request; any issues found are reported in
|
||||
Diagnostics, and the server may reject the publish.
|
||||
- **Warnings** appear immediately but do not prevent publishing.
|
||||
|
||||
When a finding identifies a component, choose **Show element** to close the
|
||||
publish dialog, open the affected page, select the instance, and scroll it into
|
||||
view. Fix the problem, then publish again. Draft pages are excluded because
|
||||
they are not part of the generated site.
|
||||
On paid plans, when a finding identifies a component, choose **Show element** to
|
||||
select the affected instance. Free plans show a
|
||||
short error or warning without full details or element navigation. Fix the
|
||||
problem, then publish again. Draft pages are excluded because they are not part
|
||||
of the generated site.
|
||||
|
||||
## Publish details
|
||||
|
||||
Choose **Validate** to see a short result in the publish popover. When it finds
|
||||
issues, choose **See issues** to open the **Warnings** or **Errors** tab.
|
||||
When validation passes with no issues, the popover says it is ready to publish.
|
||||
If publishing fails, the popover shows the failure and a **See issues** button.
|
||||
It opens **Publish** for a publish that started, or **Errors** if the request
|
||||
failed before a publish started.
|
||||
After a successful publish, choose **See logs** in the success notice to open
|
||||
the **Publish** tab. Free plans can open the tab but cannot view its logs.
|
||||
Click the status icon beside a domain to open the same dialog on the
|
||||
**Publish** tab for that domain. For a static export, click its status icon.
|
||||
If a static export fails before a build starts, open its status icon to see the
|
||||
error in Diagnostics.
|
||||
|
||||
The **Publish** tab shows up to 10 recent publishes started in the current Builder tab. It keeps
|
||||
results when you close the dialog, but clears them when you reload or close the
|
||||
Builder tab. Results for other domains stay separate. An older published status
|
||||
may still appear after reload, without a session log.
|
||||
|
||||
Free plans show validation findings and a short publish failure notice, but not
|
||||
build-log issues or detailed build errors. Pro and Team plans can open finding
|
||||
details and view publish logs. Successful publishes show output from publish
|
||||
steps. Failed publishes show the failed step first and output from commands
|
||||
that ran. GitHub's runner setup output and environment listing are not shown.
|
||||
If a step fails before its command starts or its log is unavailable,
|
||||
Webstudio shows its step name and status without the raw runner log. GitHub may
|
||||
provide no log even when publishing succeeds or fails.
|
||||
|
||||
## Adding a custom domain
|
||||
|
||||
|
||||
@@ -30,8 +30,18 @@ See [export types](./#export-types) for more information about JavaScript applic
|
||||
|
||||
5. Wait while Webstudio builds and downloads the project.
|
||||
|
||||
After the download succeeds, choose **See logs** in the success notice to open
|
||||
the **Publish** tab. Free plans can open the tab but cannot view its logs.
|
||||
|
||||
The export contains a static site consisting of HTML, CSS, JS, and images ready to be uploaded to another platform.
|
||||
|
||||
To check an export, open **Publish**, choose **Export**, and click the status
|
||||
icon beside the static-site build button.
|
||||
Its **Warnings**, **Errors**, and **Publish** tabs work like the [publish details for a domain](../foundations/publishing-and-custom-domains.md#publish-details):
|
||||
Publish shows exports started in this Builder tab, while Warnings and Errors
|
||||
show current project checks. Full logs, when available on your plan, open from
|
||||
Publish in the same dialog.
|
||||
|
||||
See [static site hosting platforms](./#platforms-for-static-sites) we have documented.
|
||||
|
||||
## Related
|
||||
|
||||
@@ -113,7 +113,16 @@ export type HighImpactFixtureApi = {
|
||||
|
||||
export const startHighImpactFixtureApi = async (
|
||||
fixture: HighImpactFixture,
|
||||
{ formReceiverPort }: { formReceiverPort?: number } = {}
|
||||
{
|
||||
formReceiverPort,
|
||||
handleServerOperation,
|
||||
}: {
|
||||
formReceiverPort?: number;
|
||||
handleServerOperation?: (
|
||||
operationPath: string,
|
||||
input: unknown
|
||||
) => Promise<{ result: unknown } | undefined>;
|
||||
} = {}
|
||||
): Promise<HighImpactFixtureApi> => {
|
||||
Object.assign(globalThis, { React });
|
||||
const [stateAdapters, runtime, projectSession, restorePoints] =
|
||||
@@ -567,6 +576,13 @@ export const startHighImpactFixtureApi = async (
|
||||
};
|
||||
calls.push(call);
|
||||
try {
|
||||
const serverOperation = await handleServerOperation?.(
|
||||
operationPath,
|
||||
input
|
||||
);
|
||||
if (serverOperation !== undefined) {
|
||||
return serverOperation.result;
|
||||
}
|
||||
const result = await executeBuilderRuntimeOperation({
|
||||
id: operationPath,
|
||||
state,
|
||||
|
||||
@@ -10,8 +10,11 @@ import {
|
||||
topLevelCliCommandMetadata,
|
||||
} from "./api-command-metadata";
|
||||
import { useCaseCoverageScenarios, useCaseScenarios } from "./api-command-docs";
|
||||
import { __testing__ } from "./mcp";
|
||||
import { readCliDoc } from "../docs";
|
||||
|
||||
const { toMcpPublishOperation } = __testing__;
|
||||
|
||||
const getDocumentedCommands = () => {
|
||||
const knownCliCommands = [
|
||||
...highLevelCliCommands.map(({ command }) => command),
|
||||
@@ -41,7 +44,7 @@ const getDocumentedCommands = () => {
|
||||
|
||||
const createMetadataOnlyMcpAdapter = () =>
|
||||
createProjectSessionMcpCore({
|
||||
operations: publicApiOperations,
|
||||
operations: publicApiOperations.map(toMcpPublishOperation),
|
||||
createProjectSession: () => {
|
||||
throw new Error(
|
||||
"MCP metadata reads must not initialize a ProjectSession."
|
||||
|
||||
@@ -217,6 +217,7 @@ const apiCommandOptionsByCommand: Partial<
|
||||
publish: apiCommand.publishCommandOptions,
|
||||
"validate-publish": apiCommand.validatePublishCommandOptions,
|
||||
"get-publish-job": apiCommand.publishJobCommandOptions,
|
||||
"get-publish-log": apiCommand.publishLogCommandOptions,
|
||||
unpublish: apiCommand.unpublishCommandOptions,
|
||||
"create-domain": apiCommand.createDomainCommandOptions,
|
||||
"update-domain": apiCommand.updateDomainCommandOptions,
|
||||
@@ -279,6 +280,7 @@ export const highLevelCliCommands = [
|
||||
{ command: "publish deploy", operation: "publish" },
|
||||
{ command: "publish list", operation: "list-publishes" },
|
||||
{ command: "publish status", operation: "get-publish-job" },
|
||||
{ command: "publish log", operation: "get-publish-log" },
|
||||
{ command: "publish unpublish", operation: "unpublish" },
|
||||
{ command: "domains list", operation: "list-domains" },
|
||||
{ command: "domains create", operation: "create-domain" },
|
||||
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
auditCommandOptions,
|
||||
createPageCommandOptions,
|
||||
createPageTemplateCommandOptions,
|
||||
publishCommandOptions,
|
||||
validatePublishCommandOptions,
|
||||
unpublishCommandOptions,
|
||||
} from "./api-command";
|
||||
import type { CommonYargsArgv } from "./yargs-types";
|
||||
@@ -1879,6 +1881,437 @@ test("publishes project", async () => {
|
||||
idempotencyKey: "publish-key",
|
||||
},
|
||||
});
|
||||
expect(apiCalls.getPublishLog).not.toHaveBeenCalled();
|
||||
expect(apiCalls.getPublishJob).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("parses publish wait without changing the immediate default", async () => {
|
||||
const command = publishCommandOptions(
|
||||
makeCLI([]).exitProcess(false) as unknown as CommonYargsArgv
|
||||
).strictOptions();
|
||||
expect(
|
||||
(await command.parse(["--target", "production", "--json"])).wait
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
(await command.parse(["--target", "production", "--json", "--wait"])).wait
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("validate-publish rejects static while publish accepts it", async () => {
|
||||
const validate = validatePublishCommandOptions(
|
||||
makeCLI([]).exitProcess(false) as unknown as CommonYargsArgv
|
||||
).strictOptions();
|
||||
const publish = publishCommandOptions(
|
||||
makeCLI([]).exitProcess(false) as unknown as CommonYargsArgv
|
||||
).strictOptions();
|
||||
expect(() => validate.parse(["--target", "static", "--json"])).toThrow();
|
||||
expect((await publish.parse(["--target", "static", "--json"])).target).toBe(
|
||||
"static"
|
||||
);
|
||||
});
|
||||
|
||||
test("waits for the job before reading every log page across UTF-8 boundaries", async () => {
|
||||
mockConfig();
|
||||
apiCalls.publish.mockResolvedValue({
|
||||
status: "pending",
|
||||
jobId: "build-2",
|
||||
buildId: "build-2",
|
||||
logHandle: "signed-handle",
|
||||
findings: [],
|
||||
});
|
||||
apiCalls.getPublishLog
|
||||
.mockResolvedValueOnce({
|
||||
availability: "available",
|
||||
outcome: "succeeded",
|
||||
logAvailability: "available",
|
||||
log: {
|
||||
encoding: "base64url",
|
||||
chunk: Buffer.from([0xe2]).toString("base64url"),
|
||||
complete: false,
|
||||
nextCursor: 1,
|
||||
},
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
availability: "available",
|
||||
outcome: "succeeded",
|
||||
logAvailability: "available",
|
||||
log: {
|
||||
encoding: "base64url",
|
||||
chunk: Buffer.from([0x82, 0xac]).toString("base64url"),
|
||||
complete: true,
|
||||
},
|
||||
});
|
||||
apiCalls.getPublishJob
|
||||
.mockResolvedValueOnce({ status: "pending" })
|
||||
.mockResolvedValueOnce({ status: "success" });
|
||||
|
||||
await apiCommand(
|
||||
{ command: "publish", target: "production", json: true, wait: true },
|
||||
dependencies
|
||||
);
|
||||
|
||||
expect(apiCalls.publish).toHaveBeenCalledOnce();
|
||||
expect(apiCalls.getPublishJob.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
apiCalls.getPublishLog.mock.invocationCallOrder[0]
|
||||
);
|
||||
expect(apiCalls.getPublishLog).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expectConnection({
|
||||
buildId: "build-2",
|
||||
logHandle: "signed-handle",
|
||||
cursor: 1,
|
||||
})
|
||||
);
|
||||
expect(getLastJsonOutput()).toMatchObject({
|
||||
ok: true,
|
||||
data: {
|
||||
status: "success",
|
||||
jobId: "build-2",
|
||||
publishLog: {
|
||||
availability: "available",
|
||||
outcome: "succeeded",
|
||||
logText: "€",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(vi.mocked(console.info)).toHaveBeenCalledOnce();
|
||||
expect(vi.mocked(console.error)).toHaveBeenCalledWith(
|
||||
expect.stringContaining('"event":"publish.wait"')
|
||||
);
|
||||
});
|
||||
|
||||
test("returns nonzero with the publish result and available failure diagnostics", async () => {
|
||||
mockConfig();
|
||||
apiCalls.publish.mockResolvedValue({
|
||||
status: "pending",
|
||||
jobId: "build-2",
|
||||
buildId: "build-2",
|
||||
logHandle: "signed-handle",
|
||||
});
|
||||
apiCalls.getPublishLog.mockResolvedValue({
|
||||
availability: "available",
|
||||
outcome: "failed",
|
||||
code: "cancelled",
|
||||
failedStage: "build",
|
||||
logAvailability: "available",
|
||||
log: {
|
||||
encoding: "base64url",
|
||||
chunk: Buffer.from("Build failed").toString("base64url"),
|
||||
complete: true,
|
||||
issues: [{ severity: "error", message: "Build failed" }],
|
||||
},
|
||||
});
|
||||
apiCalls.getPublishJob.mockResolvedValue({ status: "failed" });
|
||||
|
||||
await expect(
|
||||
apiCommand(
|
||||
{ command: "publish", target: "production", json: true, wait: true },
|
||||
dependencies
|
||||
)
|
||||
).rejects.toBeInstanceOf(Error);
|
||||
expect(getLastJsonOutput()).toMatchObject({
|
||||
ok: false,
|
||||
data: {
|
||||
jobId: "build-2",
|
||||
publishLog: {
|
||||
availability: "available",
|
||||
outcome: "failed",
|
||||
code: "cancelled",
|
||||
failedStage: "build",
|
||||
log: { issues: [{ severity: "error", message: "Build failed" }] },
|
||||
},
|
||||
},
|
||||
error: { code: "PUBLISH_FAILED" },
|
||||
});
|
||||
});
|
||||
|
||||
test("clears paid bytes and issues if access changes during pagination", async () => {
|
||||
mockConfig();
|
||||
apiCalls.publish.mockResolvedValue({
|
||||
status: "pending",
|
||||
jobId: "build-2",
|
||||
buildId: "build-2",
|
||||
logHandle: "signed-handle",
|
||||
});
|
||||
apiCalls.getPublishLog
|
||||
.mockResolvedValueOnce({
|
||||
availability: "available",
|
||||
outcome: "succeeded",
|
||||
logAvailability: "available",
|
||||
log: {
|
||||
encoding: "base64url",
|
||||
chunk: "c2VjcmV0",
|
||||
complete: false,
|
||||
nextCursor: 6,
|
||||
},
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
availability: "available",
|
||||
outcome: "succeeded",
|
||||
logAvailability: "unavailable",
|
||||
log: {
|
||||
complete: true,
|
||||
issues: [{ severity: "warning", message: "Check output" }],
|
||||
},
|
||||
});
|
||||
apiCalls.getPublishJob.mockResolvedValue({ status: "success" });
|
||||
|
||||
await apiCommand(
|
||||
{ command: "publish", target: "production", json: true, wait: true },
|
||||
dependencies
|
||||
);
|
||||
|
||||
const output = getLastJsonOutput();
|
||||
expect(output.data.publishLog).toEqual({ availability: "unavailable" });
|
||||
expect(JSON.stringify(output)).not.toContain("secret");
|
||||
});
|
||||
|
||||
test("uses durable job status when the signed publishLog cannot be read", async () => {
|
||||
mockConfig();
|
||||
apiCalls.publish.mockResolvedValue({
|
||||
status: "pending",
|
||||
jobId: "build-2",
|
||||
buildId: "build-2",
|
||||
});
|
||||
apiCalls.getPublishJob.mockResolvedValue({
|
||||
id: "build-2",
|
||||
status: "success",
|
||||
});
|
||||
|
||||
await apiCommand(
|
||||
{ command: "publish", target: "production", json: true, wait: true },
|
||||
dependencies
|
||||
);
|
||||
|
||||
expect(apiCalls.getPublishLog).not.toHaveBeenCalled();
|
||||
expect(getLastJsonOutput()).toMatchObject({
|
||||
ok: true,
|
||||
data: {
|
||||
status: "success",
|
||||
job: { status: "success" },
|
||||
publishLog: { availability: "unavailable" },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("returns nonzero for a blocked submission without polling", async () => {
|
||||
mockConfig();
|
||||
apiCalls.publish.mockResolvedValue({
|
||||
status: "blocked",
|
||||
findings: [{ severity: "error", code: "INVALID" }],
|
||||
});
|
||||
|
||||
await expect(
|
||||
apiCommand(
|
||||
{ command: "publish", target: "production", json: true, wait: true },
|
||||
dependencies
|
||||
)
|
||||
).rejects.toBeInstanceOf(Error);
|
||||
|
||||
expect(apiCalls.getPublishLog).not.toHaveBeenCalled();
|
||||
expect(apiCalls.getPublishJob).not.toHaveBeenCalled();
|
||||
expect(getLastJsonOutput()).toMatchObject({
|
||||
ok: false,
|
||||
data: { status: "blocked" },
|
||||
error: { code: "PUBLISH_BLOCKED" },
|
||||
});
|
||||
});
|
||||
|
||||
test("returns nonzero for a blocked submission without --wait", async () => {
|
||||
mockConfig();
|
||||
apiCalls.publish.mockResolvedValue({
|
||||
status: "blocked",
|
||||
findings: [{ severity: "error", ruleId: "invalid", location: {} }],
|
||||
});
|
||||
|
||||
await expect(
|
||||
apiCommand(
|
||||
{ command: "publish", target: "production", json: true },
|
||||
dependencies
|
||||
)
|
||||
).rejects.toBeInstanceOf(Error);
|
||||
expect(apiCalls.getPublishLog).not.toHaveBeenCalled();
|
||||
expect(apiCalls.getPublishJob).not.toHaveBeenCalled();
|
||||
expect(getLastJsonOutput()).toMatchObject({
|
||||
ok: false,
|
||||
data: { status: "blocked" },
|
||||
error: { code: "PUBLISH_BLOCKED" },
|
||||
});
|
||||
});
|
||||
|
||||
test("returns nonzero for a failed durable job when logs are unavailable", async () => {
|
||||
mockConfig();
|
||||
apiCalls.publish.mockResolvedValue({
|
||||
status: "pending",
|
||||
jobId: "build-2",
|
||||
buildId: "build-2",
|
||||
});
|
||||
apiCalls.getPublishJob.mockResolvedValue({ id: "build-2", status: "failed" });
|
||||
|
||||
await expect(
|
||||
apiCommand(
|
||||
{ command: "publish", target: "production", json: true, wait: true },
|
||||
dependencies
|
||||
)
|
||||
).rejects.toBeInstanceOf(Error);
|
||||
|
||||
expect(getLastJsonOutput()).toMatchObject({
|
||||
ok: false,
|
||||
data: {
|
||||
status: "failed",
|
||||
job: { status: "failed" },
|
||||
publishLog: { availability: "unavailable" },
|
||||
},
|
||||
error: { code: "PUBLISH_FAILED" },
|
||||
});
|
||||
});
|
||||
|
||||
test("does not report success when the publish job was removed", async () => {
|
||||
mockConfig();
|
||||
apiCalls.publish.mockResolvedValue({
|
||||
status: "pending",
|
||||
jobId: "build-2",
|
||||
buildId: "build-2",
|
||||
});
|
||||
apiCalls.getPublishJob.mockResolvedValue({
|
||||
id: "build-2",
|
||||
status: "removed",
|
||||
});
|
||||
|
||||
await expect(
|
||||
apiCommand(
|
||||
{ command: "publish", target: "production", json: true, wait: true },
|
||||
dependencies
|
||||
)
|
||||
).rejects.toBeInstanceOf(Error);
|
||||
|
||||
expect(getLastJsonOutput()).toMatchObject({
|
||||
ok: false,
|
||||
data: { waitStatus: "unavailable", job: { status: "removed" } },
|
||||
error: { code: "PUBLISH_WAIT_UNAVAILABLE" },
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves a successful publishLog if a later log page fails", async () => {
|
||||
mockConfig();
|
||||
apiCalls.publish.mockResolvedValue({
|
||||
status: "pending",
|
||||
jobId: "build-2",
|
||||
buildId: "build-2",
|
||||
logHandle: "signed-handle",
|
||||
});
|
||||
apiCalls.getPublishLog
|
||||
.mockResolvedValueOnce({
|
||||
availability: "available",
|
||||
outcome: "succeeded",
|
||||
logAvailability: "available",
|
||||
log: {
|
||||
encoding: "base64url",
|
||||
chunk: "c2VjcmV0",
|
||||
complete: false,
|
||||
nextCursor: 6,
|
||||
},
|
||||
})
|
||||
.mockRejectedValueOnce(
|
||||
Object.assign(new Error("Forbidden"), { code: "FORBIDDEN" })
|
||||
);
|
||||
apiCalls.getPublishJob.mockResolvedValue({ status: "success" });
|
||||
|
||||
await apiCommand(
|
||||
{ command: "publish", target: "production", json: true, wait: true },
|
||||
dependencies
|
||||
);
|
||||
|
||||
const output = getLastJsonOutput();
|
||||
expect(output).toMatchObject({
|
||||
ok: true,
|
||||
data: {
|
||||
status: "success",
|
||||
publishLog: { availability: "unavailable" },
|
||||
},
|
||||
});
|
||||
expect(output.data.publishLog.logText).toBeUndefined();
|
||||
expect(JSON.stringify(output)).not.toContain("secret");
|
||||
});
|
||||
|
||||
test("returns a structured timeout without canceling a pending publish", async () => {
|
||||
mockConfig();
|
||||
apiCalls.publish.mockResolvedValue({
|
||||
status: "pending",
|
||||
jobId: "build-2",
|
||||
buildId: "build-2",
|
||||
logHandle: "signed-handle",
|
||||
});
|
||||
apiCalls.getPublishLog.mockResolvedValue({ availability: "pending" });
|
||||
apiCalls.getPublishJob.mockResolvedValue({
|
||||
id: "build-2",
|
||||
status: "pending",
|
||||
});
|
||||
|
||||
await expect(
|
||||
apiCommand(
|
||||
{ command: "publish", target: "production", json: true, wait: true },
|
||||
dependencies
|
||||
)
|
||||
).rejects.toBeInstanceOf(Error);
|
||||
|
||||
expect(apiCalls.publish).toHaveBeenCalledOnce();
|
||||
expect(apiCalls.getPublishJob).toHaveBeenCalledTimes(360);
|
||||
expect(apiCalls.getPublishLog).not.toHaveBeenCalled();
|
||||
expect(getLastJsonOutput()).toMatchObject({
|
||||
ok: false,
|
||||
data: {
|
||||
jobId: "build-2",
|
||||
waitStatus: "timeout",
|
||||
job: { status: "pending" },
|
||||
},
|
||||
error: {
|
||||
code: "PUBLISH_WAIT_TIMEOUT",
|
||||
message: "Publishing is still running. Stopped waiting.",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("returns a structured unknown outcome when job lookup fails", async () => {
|
||||
mockConfig();
|
||||
apiCalls.publish.mockResolvedValue({
|
||||
status: "pending",
|
||||
jobId: "build-2",
|
||||
buildId: "build-2",
|
||||
logHandle: "signed-handle",
|
||||
});
|
||||
apiCalls.getPublishLog.mockRejectedValueOnce(new Error("Report unavailable"));
|
||||
apiCalls.getPublishJob.mockRejectedValueOnce(new Error("Status unavailable"));
|
||||
|
||||
await expect(
|
||||
apiCommand(
|
||||
{ command: "publish", target: "production", json: true, wait: true },
|
||||
dependencies
|
||||
)
|
||||
).rejects.toBeInstanceOf(Error);
|
||||
|
||||
expect(getLastJsonOutput()).toMatchObject({
|
||||
ok: false,
|
||||
data: { jobId: "build-2", waitStatus: "unavailable" },
|
||||
error: { code: "PUBLISH_WAIT_UNAVAILABLE" },
|
||||
});
|
||||
});
|
||||
|
||||
test("publishes static export", async () => {
|
||||
await expectCommandCall({
|
||||
options: {
|
||||
command: "publish",
|
||||
target: "static",
|
||||
template: "ssg,vercel",
|
||||
idempotencyKey: "publish-key",
|
||||
},
|
||||
call: apiCalls.publish,
|
||||
connection: {
|
||||
target: "static",
|
||||
templates: ["ssg", "vercel"],
|
||||
idempotencyKey: "publish-key",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("validates publishing without publishing", async () => {
|
||||
@@ -1911,6 +2344,21 @@ test("gets publish job", async () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("gets publish log", async () => {
|
||||
await expectCommandCall({
|
||||
options: {
|
||||
command: "get-publish-log",
|
||||
buildId: "build-id",
|
||||
logHandle: "signed-handle",
|
||||
},
|
||||
call: apiCalls.getPublishLog,
|
||||
connection: {
|
||||
buildId: "build-id",
|
||||
logHandle: "signed-handle",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test("unpublishes project with confirmation", async () => {
|
||||
await expectCommandCall({
|
||||
options: {
|
||||
@@ -1933,7 +2381,7 @@ test("unpublishes project with confirmation", async () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("unpublish help does not advertise publish-only flags", async () => {
|
||||
test("unpublish help advertises only deployment options", async () => {
|
||||
const help = await unpublishCommandOptions(
|
||||
makeCLI([]).exitProcess(false) as unknown as CommonYargsArgv
|
||||
).getHelp();
|
||||
@@ -1941,6 +2389,8 @@ test("unpublish help does not advertise publish-only flags", async () => {
|
||||
expect(help).toContain("--domain");
|
||||
expect(help).not.toContain("--message");
|
||||
expect(help).not.toContain("--idempotency-key");
|
||||
expect(help).not.toContain("static");
|
||||
expect(help).not.toContain("--wait");
|
||||
});
|
||||
|
||||
test("lists domains", async () => {
|
||||
|
||||
@@ -39,6 +39,7 @@ type ApiCommandDependencies = typeof apiCommandHttpClient & {
|
||||
readFile: typeof readFile;
|
||||
createCliProjectSession: typeof createCliProjectSession;
|
||||
getServerApiContract: typeof getCliServerApiContract;
|
||||
pause: (durationMs: number) => Promise<void>;
|
||||
};
|
||||
|
||||
const defaultDependencies: ApiCommandDependencies = {
|
||||
@@ -47,6 +48,8 @@ const defaultDependencies: ApiCommandDependencies = {
|
||||
readFile,
|
||||
createCliProjectSession,
|
||||
getServerApiContract: getCliServerApiContract,
|
||||
pause: (durationMs) =>
|
||||
new Promise((resolve) => setTimeout(resolve, durationMs)),
|
||||
};
|
||||
|
||||
export type ApiCommandName = ProjectSessionApiCommand;
|
||||
@@ -1134,9 +1137,16 @@ export const deleteResourceCommandOptions = (yargs: CommonYargsArgv) =>
|
||||
"Also remove direct resource prop references that point at this resource",
|
||||
});
|
||||
|
||||
const publishTargetOption = (yargs: CommonYargsArgv) =>
|
||||
const deploymentTargetOption = (yargs: CommonYargsArgv) =>
|
||||
yargs.option("target", {
|
||||
choices: ["staging", "production"] as const,
|
||||
describe: "Required deployment target",
|
||||
demandOption: true,
|
||||
});
|
||||
|
||||
const publishTargetOption = (yargs: CommonYargsArgv) =>
|
||||
yargs.option("target", {
|
||||
choices: ["staging", "production", "static"] as const,
|
||||
describe: "Required publish target",
|
||||
demandOption: true,
|
||||
});
|
||||
@@ -1151,6 +1161,10 @@ const publishDomainsOption = (yargs: CommonYargsArgv) =>
|
||||
|
||||
export const publishCommandOptions = (yargs: CommonYargsArgv) =>
|
||||
publishDomainsOption(publishTargetOption(apiCommandOptions(yargs)))
|
||||
.option("wait", {
|
||||
type: "boolean",
|
||||
describe: "Wait for publishing to finish",
|
||||
})
|
||||
.option("message", {
|
||||
type: "string",
|
||||
describe: "Optional human-readable publish message",
|
||||
@@ -1158,10 +1172,24 @@ export const publishCommandOptions = (yargs: CommonYargsArgv) =>
|
||||
.option("idempotency-key", {
|
||||
type: "string",
|
||||
describe: "Optional idempotency key for retrying the same publish",
|
||||
})
|
||||
.option("template", {
|
||||
type: "array",
|
||||
string: true,
|
||||
choices: [
|
||||
"docker",
|
||||
"vercel",
|
||||
"netlify",
|
||||
"ssg",
|
||||
"ssg-netlify",
|
||||
"ssg-vercel",
|
||||
] as const,
|
||||
describe:
|
||||
"Static export template. Repeat to request multiple templates; defaults to ssg.",
|
||||
});
|
||||
|
||||
export const validatePublishCommandOptions = (yargs: CommonYargsArgv) =>
|
||||
publishDomainsOption(publishTargetOption(apiCommandOptions(yargs)));
|
||||
publishDomainsOption(deploymentTargetOption(apiCommandOptions(yargs)));
|
||||
|
||||
export const publishJobCommandOptions = (yargs: CommonYargsArgv) =>
|
||||
apiCommandOptions(yargs).option("job", {
|
||||
@@ -1170,9 +1198,15 @@ export const publishJobCommandOptions = (yargs: CommonYargsArgv) =>
|
||||
demandOption: true,
|
||||
});
|
||||
|
||||
export const publishLogCommandOptions = (yargs: CommonYargsArgv) =>
|
||||
apiCommandOptions(yargs)
|
||||
.option("build-id", { type: "string", demandOption: true })
|
||||
.option("log-handle", { type: "string", demandOption: true })
|
||||
.option("cursor", { type: "number" });
|
||||
|
||||
export const unpublishCommandOptions = (yargs: CommonYargsArgv) =>
|
||||
confirmOption(
|
||||
publishDomainsOption(publishTargetOption(apiCommandOptions(yargs))),
|
||||
publishDomainsOption(deploymentTargetOption(apiCommandOptions(yargs))),
|
||||
"Required. Confirm that selected domains should be unpublished"
|
||||
);
|
||||
|
||||
@@ -1371,8 +1405,11 @@ export type ApiCommandOptions = {
|
||||
asset?: string | string[];
|
||||
domain?: string | string[];
|
||||
domainId?: string;
|
||||
target?: "staging" | "production";
|
||||
target?: "staging" | "production" | "static";
|
||||
job?: string;
|
||||
buildId?: string;
|
||||
logHandle?: string;
|
||||
wait?: boolean;
|
||||
idempotencyKey?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
@@ -1650,9 +1687,23 @@ const assetListTypeOption = (
|
||||
|
||||
const publishTargetValue = (
|
||||
value: ApiCommandOptions["target"]
|
||||
): "staging" | "production" | "static" =>
|
||||
requiredChoice(value, ["staging", "production", "static"], "--target");
|
||||
|
||||
const deploymentTargetValue = (
|
||||
value: ApiCommandOptions["target"]
|
||||
): "staging" | "production" =>
|
||||
requiredChoice(value, ["staging", "production"], "--target");
|
||||
|
||||
const publishTemplateValues = (value: ApiCommandOptions["template"]) =>
|
||||
listStringOption(value)?.map((template) =>
|
||||
requiredChoice(
|
||||
template,
|
||||
["docker", "vercel", "netlify", "ssg", "ssg-netlify", "ssg-vercel"],
|
||||
"--template"
|
||||
)
|
||||
);
|
||||
|
||||
const textUpdateModeOption = (
|
||||
value: ApiCommandOptions["mode"]
|
||||
): "text" | "expression" | undefined =>
|
||||
@@ -1882,6 +1933,162 @@ const runProjectSessionCommand = async (
|
||||
refresh: activeApiCommandRefresh,
|
||||
});
|
||||
|
||||
const publishWaitDelayMs = 5_000;
|
||||
const publishWaitPolls = 360;
|
||||
const publishLogGracePolls = 12;
|
||||
|
||||
const waitForPublish = async (
|
||||
publishResult: unknown,
|
||||
connection: ApiCommandConnection,
|
||||
dependencies: ApiCommandDependencies
|
||||
) => {
|
||||
if (
|
||||
isPlainRecord(publishResult) === false ||
|
||||
publishResult.status !== "pending"
|
||||
) {
|
||||
return publishResult;
|
||||
}
|
||||
const { jobId, buildId, logHandle } = publishResult;
|
||||
if (typeof jobId !== "string") {
|
||||
return { ...publishResult, waitStatus: "unavailable" };
|
||||
}
|
||||
let job: unknown;
|
||||
console.error(
|
||||
JSON.stringify({ event: "publish.wait", jobId, status: "pending" })
|
||||
);
|
||||
for (let poll = 0; poll < publishWaitPolls; poll++) {
|
||||
try {
|
||||
job = await dependencies.getPublishJob({
|
||||
...connection,
|
||||
jobId,
|
||||
...(typeof logHandle === "string" ? { logHandle } : {}),
|
||||
});
|
||||
} catch {
|
||||
return { ...publishResult, waitStatus: "unavailable" };
|
||||
}
|
||||
const status = isPlainRecord(job) ? job.status : undefined;
|
||||
if (
|
||||
poll === 0 ||
|
||||
poll % 6 === 5 ||
|
||||
status === "success" ||
|
||||
status === "failed"
|
||||
) {
|
||||
console.error(
|
||||
JSON.stringify({
|
||||
event: "publish.wait",
|
||||
jobId,
|
||||
status: status ?? "unknown",
|
||||
})
|
||||
);
|
||||
}
|
||||
if (status === "success" || status === "failed" || status === "removed") {
|
||||
break;
|
||||
}
|
||||
if (poll < publishWaitPolls - 1) {
|
||||
await dependencies.pause(publishWaitDelayMs);
|
||||
}
|
||||
}
|
||||
const status = isPlainRecord(job) ? job.status : undefined;
|
||||
if (status !== "success" && status !== "failed") {
|
||||
return {
|
||||
...publishResult,
|
||||
job,
|
||||
waitStatus: status === "pending" ? "timeout" : "unavailable",
|
||||
};
|
||||
}
|
||||
const terminalResult = {
|
||||
...publishResult,
|
||||
status,
|
||||
job,
|
||||
publishLog: { availability: "unavailable" },
|
||||
};
|
||||
if (typeof buildId !== "string" || typeof logHandle !== "string") {
|
||||
return terminalResult;
|
||||
}
|
||||
let publishLog: unknown;
|
||||
for (let poll = 0; poll < publishLogGracePolls; poll++) {
|
||||
try {
|
||||
publishLog = await dependencies.getPublishLog({
|
||||
...connection,
|
||||
buildId,
|
||||
logHandle,
|
||||
});
|
||||
} catch {
|
||||
return terminalResult;
|
||||
}
|
||||
if (isPlainRecord(publishLog) && publishLog.availability === "available") {
|
||||
break;
|
||||
}
|
||||
if (
|
||||
isPlainRecord(publishLog) === false ||
|
||||
publishLog.availability !== "pending"
|
||||
) {
|
||||
return terminalResult;
|
||||
}
|
||||
if (poll < publishLogGracePolls - 1) {
|
||||
await dependencies.pause(publishWaitDelayMs);
|
||||
}
|
||||
}
|
||||
if (
|
||||
isPlainRecord(publishLog) === false ||
|
||||
publishLog.availability !== "available" ||
|
||||
publishLog.logAvailability !== "available"
|
||||
) {
|
||||
return terminalResult;
|
||||
}
|
||||
const firstLog = publishLog;
|
||||
const chunks: Buffer[] = [];
|
||||
const issues: unknown[] = [];
|
||||
let issuesOmitted = 0;
|
||||
let cursor: number | undefined;
|
||||
while (isPlainRecord(publishLog) && publishLog.availability === "available") {
|
||||
const log = isPlainRecord(publishLog.log) ? publishLog.log : undefined;
|
||||
if (
|
||||
publishLog.logAvailability !== "available" ||
|
||||
log?.encoding !== "base64url" ||
|
||||
typeof log.chunk !== "string"
|
||||
) {
|
||||
return terminalResult;
|
||||
}
|
||||
chunks.push(Buffer.from(log.chunk, "base64url"));
|
||||
if (Array.isArray(log.issues)) {
|
||||
issues.push(...log.issues);
|
||||
}
|
||||
if (typeof log.issuesOmitted === "number") {
|
||||
issuesOmitted += log.issuesOmitted;
|
||||
}
|
||||
if (log.complete === true) {
|
||||
return {
|
||||
...terminalResult,
|
||||
publishLog: {
|
||||
...firstLog,
|
||||
log: { complete: true, issues, issuesOmitted },
|
||||
logText: new TextDecoder().decode(Buffer.concat(chunks)),
|
||||
},
|
||||
};
|
||||
}
|
||||
if (
|
||||
log.complete !== false ||
|
||||
typeof log.nextCursor !== "number" ||
|
||||
log.nextCursor <= (cursor ?? -1)
|
||||
) {
|
||||
return terminalResult;
|
||||
}
|
||||
cursor = log.nextCursor;
|
||||
try {
|
||||
publishLog = await dependencies.getPublishLog({
|
||||
...connection,
|
||||
buildId,
|
||||
logHandle,
|
||||
cursor,
|
||||
});
|
||||
} catch {
|
||||
return terminalResult;
|
||||
}
|
||||
}
|
||||
return terminalResult;
|
||||
};
|
||||
|
||||
type ApiCommandHandler = (
|
||||
options: ApiCommandOptions,
|
||||
connection: ApiCommandConnection,
|
||||
@@ -3028,17 +3235,47 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
|
||||
);
|
||||
},
|
||||
publish: async (options, connection, dependencies) => {
|
||||
const input = {
|
||||
target: publishTargetValue(options.target),
|
||||
domains: listStringOption(options.domain),
|
||||
message: options.message,
|
||||
idempotencyKey: options.idempotencyKey,
|
||||
};
|
||||
return runProjectSessionCommand("publish", input, connection, dependencies);
|
||||
const target = publishTargetValue(options.target);
|
||||
let envelope;
|
||||
if (target === "static") {
|
||||
envelope = await runProjectSessionCommand(
|
||||
"publish",
|
||||
{
|
||||
target,
|
||||
templates: publishTemplateValues(options.template),
|
||||
idempotencyKey: options.idempotencyKey,
|
||||
},
|
||||
connection,
|
||||
dependencies
|
||||
);
|
||||
} else {
|
||||
const input = {
|
||||
target,
|
||||
domains: listStringOption(options.domain),
|
||||
message: options.message,
|
||||
idempotencyKey: options.idempotencyKey,
|
||||
};
|
||||
envelope = await runProjectSessionCommand(
|
||||
"publish",
|
||||
input,
|
||||
connection,
|
||||
dependencies
|
||||
);
|
||||
}
|
||||
return options.wait === true
|
||||
? {
|
||||
...envelope,
|
||||
result: await waitForPublish(
|
||||
envelope.result,
|
||||
connection,
|
||||
dependencies
|
||||
),
|
||||
}
|
||||
: envelope;
|
||||
},
|
||||
"validate-publish": async (options, connection, dependencies) => {
|
||||
const input = {
|
||||
target: publishTargetValue(options.target),
|
||||
target: deploymentTargetValue(options.target),
|
||||
domains: listStringOption(options.domain),
|
||||
};
|
||||
return runProjectSessionCommand(
|
||||
@@ -3068,10 +3305,23 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {
|
||||
dependencies
|
||||
);
|
||||
},
|
||||
"get-publish-log": async (options, connection, dependencies) => {
|
||||
const input = {
|
||||
buildId: requireOption(options.buildId, "--build-id"),
|
||||
logHandle: requireOption(options.logHandle, "--log-handle"),
|
||||
cursor: options.cursor === undefined ? undefined : Number(options.cursor),
|
||||
};
|
||||
return runProjectSessionCommand(
|
||||
"get-publish-log",
|
||||
input,
|
||||
connection,
|
||||
dependencies
|
||||
);
|
||||
},
|
||||
unpublish: async (options, connection, dependencies) => {
|
||||
requireTrueOption(options.confirm, "--confirm");
|
||||
const input = {
|
||||
target: publishTargetValue(options.target),
|
||||
target: deploymentTargetValue(options.target),
|
||||
domains: listStringOption(options.domain),
|
||||
};
|
||||
return runProjectSessionCommand(
|
||||
@@ -3309,14 +3559,40 @@ export const apiCommand = async (
|
||||
const result = isProjectSessionEnvelope(response)
|
||||
? response.result
|
||||
: response;
|
||||
const publishFailure =
|
||||
options.command === "publish" && isPlainRecord(result)
|
||||
? result.status === "blocked" ||
|
||||
(options.wait === true &&
|
||||
(result.waitStatus === "timeout" ||
|
||||
result.waitStatus === "unavailable" ||
|
||||
result.status === "failed"))
|
||||
: false;
|
||||
if (options.command === "audit" && options.json !== true) {
|
||||
printAuditReport(result);
|
||||
} else if (options.command === "permissions" && options.json !== true) {
|
||||
printPermissions(result);
|
||||
} else {
|
||||
printJson({
|
||||
ok: true,
|
||||
ok: publishFailure === false,
|
||||
data: result,
|
||||
...(publishFailure
|
||||
? {
|
||||
error: {
|
||||
code:
|
||||
isPlainRecord(result) && result.waitStatus === "timeout"
|
||||
? "PUBLISH_WAIT_TIMEOUT"
|
||||
: isPlainRecord(result) &&
|
||||
result.waitStatus === "unavailable"
|
||||
? "PUBLISH_WAIT_UNAVAILABLE"
|
||||
: isPlainRecord(result) && result.status === "blocked"
|
||||
? "PUBLISH_BLOCKED"
|
||||
: "PUBLISH_FAILED",
|
||||
...(isPlainRecord(result) && result.waitStatus === "timeout"
|
||||
? { message: "Publishing is still running. Stopped waiting." }
|
||||
: {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
meta: {
|
||||
command: options.command,
|
||||
projectId: connection.projectId,
|
||||
@@ -3325,7 +3601,13 @@ export const apiCommand = async (
|
||||
},
|
||||
});
|
||||
}
|
||||
if (publishFailure) {
|
||||
throw new HandledCliError();
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof HandledCliError) {
|
||||
throw error;
|
||||
}
|
||||
const issues = getCliErrorIssues(error);
|
||||
if (options.json === true) {
|
||||
const code = getErrorCode(error);
|
||||
|
||||
@@ -244,6 +244,7 @@ const taskRecipeUseCases = {
|
||||
"Publish project",
|
||||
"List publishes",
|
||||
"Check publish job",
|
||||
"Inspect publish log",
|
||||
"Unpublish",
|
||||
"List domains",
|
||||
"Create domain",
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, mkdtemp, readFile, readdir, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import { expect, test } from "vitest";
|
||||
import { authenticatedPageFixture } from "../../evaluations/high-impact/fixtures";
|
||||
import { startHighImpactFixtureApi } from "../../evaluations/high-impact/fixture-api";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
test("MCP keeps publish handles only in its live host while reading status and log pages", async () => {
|
||||
let publishMode: "accepted" | "blocked" | "no-handle" = "accepted";
|
||||
let allowLogs = true;
|
||||
const requests: Array<{ operation: string; input: unknown }> = [];
|
||||
const api = await startHighImpactFixtureApi(authenticatedPageFixture, {
|
||||
handleServerOperation: async (operation, input) => {
|
||||
if (
|
||||
operation !== "publish.create" &&
|
||||
operation !== "publish.getJob" &&
|
||||
operation !== "publish.getLog"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
requests.push({ operation, input });
|
||||
if (operation === "publish.create") {
|
||||
if (publishMode === "blocked") {
|
||||
return { result: { status: "blocked", findings: [] } };
|
||||
}
|
||||
const buildId = publishMode === "no-handle" ? "build-2" : "build-1";
|
||||
return {
|
||||
result: {
|
||||
status: "pending",
|
||||
jobId: buildId,
|
||||
buildId,
|
||||
...(publishMode === "accepted"
|
||||
? { logHandle: "private-handle" }
|
||||
: {}),
|
||||
findings: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
const request = input as {
|
||||
jobId?: string;
|
||||
buildId?: string;
|
||||
logHandle?: string;
|
||||
cursor?: number;
|
||||
};
|
||||
if (operation === "publish.getJob") {
|
||||
expect(request.logHandle).toBe(
|
||||
request.jobId === "build-1" ? "private-handle" : undefined
|
||||
);
|
||||
return { result: { id: request.jobId, status: "success" } };
|
||||
}
|
||||
expect(request.logHandle).toBe("private-handle");
|
||||
if (allowLogs === false) {
|
||||
return { result: { availability: "unavailable" } };
|
||||
}
|
||||
const first = request.cursor === undefined;
|
||||
return {
|
||||
result: {
|
||||
availability: "available",
|
||||
outcome: "succeeded",
|
||||
logAvailability: "available",
|
||||
log: first
|
||||
? {
|
||||
encoding: "base64url",
|
||||
chunk: Buffer.from([0x41, 0xe2]).toString("base64url"),
|
||||
complete: false,
|
||||
nextCursor: 2,
|
||||
}
|
||||
: {
|
||||
encoding: "base64url",
|
||||
chunk: Buffer.from([0xe2, 0x82, 0xac]).toString("base64url"),
|
||||
complete: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
const directory = await mkdtemp(join(tmpdir(), "webstudio-mcp-publish-"));
|
||||
const projectDirectory = join(directory, "project");
|
||||
const cli = resolve(import.meta.dirname, "../../local.js");
|
||||
const env = {
|
||||
...process.env,
|
||||
WEBSTUDIO_CONFIG_DIR: join(directory, "config"),
|
||||
};
|
||||
const clients: Client[] = [];
|
||||
const connect = async () => {
|
||||
const client = new Client({ name: "publish-test", version: "1.0.0" });
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [cli, "mcp"],
|
||||
cwd: projectDirectory,
|
||||
env: Object.fromEntries(
|
||||
Object.entries(env).filter(
|
||||
(entry): entry is [string, string] => typeof entry[1] === "string"
|
||||
)
|
||||
),
|
||||
stderr: "pipe",
|
||||
});
|
||||
transport.stderr?.on("data", () => undefined);
|
||||
await client.connect(transport);
|
||||
clients.push(client);
|
||||
return client;
|
||||
};
|
||||
try {
|
||||
await mkdir(projectDirectory);
|
||||
await execFileAsync(
|
||||
process.execPath,
|
||||
[cli, "init", "--link", api.shareLink, "--json"],
|
||||
{ cwd: projectDirectory, env }
|
||||
);
|
||||
const client = await connect();
|
||||
const call = async (name: string, input: Record<string, unknown> = {}) => {
|
||||
const result = await client.callTool({ name, arguments: input });
|
||||
return result.structuredContent as {
|
||||
ok: boolean;
|
||||
data?: Record<string, unknown>;
|
||||
error?: { code: string };
|
||||
};
|
||||
};
|
||||
const tools = await client.listTools();
|
||||
expect(tools.tools.some(({ name }) => name === "get-publish-log")).toBe(
|
||||
true
|
||||
);
|
||||
const publish = await call("publish", { target: "production" });
|
||||
expect(publish).toMatchObject({
|
||||
ok: true,
|
||||
data: { status: "pending", buildId: "build-1" },
|
||||
});
|
||||
expect(publish.data).not.toHaveProperty("logHandle");
|
||||
const job = await call("get-publish-job", { jobId: "build-1" });
|
||||
expect(job).toMatchObject({ ok: true, data: { status: "success" } });
|
||||
expect(job.data).not.toHaveProperty("logHandle");
|
||||
const first = await call("get-publish-log");
|
||||
expect(first).toMatchObject({
|
||||
ok: true,
|
||||
data: { log: { text: "A", nextCursor: 1 } },
|
||||
});
|
||||
expect(first.data?.log).not.toHaveProperty("chunk");
|
||||
const second = await call("get-publish-log", { cursor: 1 });
|
||||
expect(second).toMatchObject({
|
||||
ok: true,
|
||||
data: { log: { text: "€", complete: true } },
|
||||
});
|
||||
expect(
|
||||
requests.filter(({ operation }) => operation === "publish.getLog")
|
||||
).toHaveLength(2);
|
||||
allowLogs = false;
|
||||
expect(await call("get-publish-log")).toMatchObject({
|
||||
ok: true,
|
||||
data: { availability: "unavailable" },
|
||||
});
|
||||
expect(await call("get-publish-log", { buildId: "unknown" })).toMatchObject(
|
||||
{
|
||||
ok: false,
|
||||
error: { code: "PUBLISH_NOT_FOUND" },
|
||||
}
|
||||
);
|
||||
publishMode = "blocked";
|
||||
expect(await call("publish", { target: "production" })).toMatchObject({
|
||||
ok: true,
|
||||
data: { status: "blocked" },
|
||||
});
|
||||
expect(await call("get-publish-log")).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "PUBLISH_REQUIRED" },
|
||||
});
|
||||
publishMode = "no-handle";
|
||||
expect(await call("publish", { target: "production" })).toMatchObject({
|
||||
ok: true,
|
||||
data: { buildId: "build-2", status: "pending" },
|
||||
});
|
||||
expect(await call("get-publish-log")).toMatchObject({
|
||||
ok: true,
|
||||
data: { availability: "unavailable" },
|
||||
});
|
||||
expect(requests).toContainEqual(
|
||||
expect.objectContaining({
|
||||
operation: "publish.getJob",
|
||||
input: expect.objectContaining({ jobId: "build-2" }),
|
||||
})
|
||||
);
|
||||
await client.close();
|
||||
const restarted = await connect();
|
||||
expect(
|
||||
(
|
||||
await restarted.callTool({
|
||||
name: "get-publish-log",
|
||||
arguments: { buildId: "build-1" },
|
||||
})
|
||||
).structuredContent
|
||||
).toMatchObject({ ok: false, error: { code: "PUBLISH_NOT_FOUND" } });
|
||||
const stateDirectory = join(projectDirectory, ".webstudio");
|
||||
for (const entry of await readdir(stateDirectory, { recursive: true })) {
|
||||
if (entry.endsWith(".json")) {
|
||||
const contents = await readFile(join(stateDirectory, entry), "utf8");
|
||||
expect(contents).not.toContain("private-handle");
|
||||
expect(contents).not.toContain("€");
|
||||
expect(contents).not.toContain("QeI");
|
||||
expect(contents).not.toContain("4oKs");
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await Promise.all(
|
||||
clients.map((client) => client.close().catch(() => undefined))
|
||||
);
|
||||
await api.close();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
}, 120_000);
|
||||
@@ -56,6 +56,9 @@ const {
|
||||
getCliUpdateInstructions,
|
||||
getLoadedProjectSessionSnapshot,
|
||||
getMcpOperationInput,
|
||||
createMcpPublishSession,
|
||||
toMcpPublishLogPage,
|
||||
toMcpPublishOperation,
|
||||
prepareTextAssetWriteFeedback,
|
||||
withTextAssetWriteFeedback,
|
||||
validateDownloadedTextAsset,
|
||||
@@ -73,6 +76,128 @@ const {
|
||||
withMcpHost,
|
||||
} = __testing__;
|
||||
|
||||
test("keeps only ten publish handles in one MCP host and never falls back to an older publish", () => {
|
||||
const session = createMcpPublishSession();
|
||||
const first = session.begin();
|
||||
session.remember(first, {
|
||||
status: "pending",
|
||||
buildId: "build-1",
|
||||
logHandle: "handle-1",
|
||||
});
|
||||
expect(session.get(undefined)).toEqual({
|
||||
buildId: "build-1",
|
||||
logHandle: "handle-1",
|
||||
});
|
||||
const blocked = session.begin();
|
||||
session.remember(blocked, { status: "blocked" });
|
||||
expect(() => session.get(undefined)).toThrowError(
|
||||
expect.objectContaining({ code: "PUBLISH_REQUIRED" })
|
||||
);
|
||||
expect(session.get("build-1").logHandle).toBe("handle-1");
|
||||
const earlier = session.begin();
|
||||
const later = session.begin();
|
||||
session.remember(later, { status: "pending", buildId: "build-3" });
|
||||
session.remember(earlier, {
|
||||
status: "pending",
|
||||
buildId: "build-2",
|
||||
logHandle: "handle-2",
|
||||
});
|
||||
expect(session.get(undefined)).toEqual({
|
||||
buildId: "build-3",
|
||||
logHandle: undefined,
|
||||
});
|
||||
expect(() => session.get("unknown")).toThrowError(
|
||||
expect.objectContaining({ code: "PUBLISH_NOT_FOUND" })
|
||||
);
|
||||
for (let index = 4; index <= 11; index++) {
|
||||
const sequence = session.begin();
|
||||
session.remember(sequence, {
|
||||
status: "pending",
|
||||
buildId: `build-${index}`,
|
||||
logHandle: `handle-${index}`,
|
||||
});
|
||||
}
|
||||
expect(() => session.get("build-1")).toThrowError(
|
||||
expect.objectContaining({ code: "PUBLISH_NOT_FOUND" })
|
||||
);
|
||||
expect(session.getHandle("build-11")).toBe("handle-11");
|
||||
expect(createMcpPublishSession().getHandle("build-11")).toBeUndefined();
|
||||
});
|
||||
|
||||
test("exposes a session-only publish log schema without changing the public API schema", () => {
|
||||
const operation = publicApiOperations.find(
|
||||
({ command }) => command === "get-publish-log"
|
||||
);
|
||||
expect(operation).toBeDefined();
|
||||
if (operation === undefined) {
|
||||
return;
|
||||
}
|
||||
const tool = listProjectSessionMcpTools([
|
||||
toMcpPublishOperation(operation),
|
||||
]).find(({ name }) => name === "get-publish-log");
|
||||
expect(tool).toBeDefined();
|
||||
const schema = getDetailedProjectSessionMcpInputSchema(tool!);
|
||||
expect(getInputJsonSchemaMetadata(schema).requiredInputFields).toEqual([]);
|
||||
expect(getInputJsonSchemaProperties(schema)).toHaveProperty("buildId");
|
||||
expect(getInputJsonSchemaProperties(schema)).toHaveProperty("cursor");
|
||||
expect(getInputJsonSchemaProperties(schema)).not.toHaveProperty("logHandle");
|
||||
expect(operation.requiredInputFields).toContain("logHandle");
|
||||
const jobOperation = publicApiOperations.find(
|
||||
({ command }) => command === "get-publish-job"
|
||||
);
|
||||
expect(jobOperation).toBeDefined();
|
||||
const jobTool = listProjectSessionMcpTools([
|
||||
toMcpPublishOperation(jobOperation!),
|
||||
]).find(({ name }) => name === "get-publish-job");
|
||||
expect(
|
||||
getInputJsonSchemaProperties(
|
||||
getDetailedProjectSessionMcpInputSchema(jobTool!)
|
||||
)
|
||||
).not.toHaveProperty("logHandle");
|
||||
});
|
||||
|
||||
test("returns readable log pages at UTF-8 boundaries and preserves invalid bytes", () => {
|
||||
const first = toMcpPublishLogPage({
|
||||
availability: "available",
|
||||
logAvailability: "available",
|
||||
log: {
|
||||
encoding: "base64url",
|
||||
chunk: Buffer.from([0x41, 0xe2]).toString("base64url"),
|
||||
complete: false,
|
||||
nextCursor: 2,
|
||||
},
|
||||
});
|
||||
expect(first).toMatchObject({
|
||||
log: { text: "A", nextCursor: 1, complete: false },
|
||||
});
|
||||
expect(JSON.stringify(first)).not.toContain("chunk");
|
||||
const second = toMcpPublishLogPage(
|
||||
{
|
||||
availability: "available",
|
||||
logAvailability: "available",
|
||||
log: {
|
||||
encoding: "base64url",
|
||||
chunk: Buffer.from([0xe2, 0x82, 0xac]).toString("base64url"),
|
||||
complete: true,
|
||||
},
|
||||
},
|
||||
1
|
||||
);
|
||||
expect(second).toMatchObject({ log: { text: "€", complete: true } });
|
||||
const invalid = {
|
||||
availability: "available",
|
||||
log: {
|
||||
encoding: "base64url",
|
||||
chunk: Buffer.from([0xff, 0x41]).toString("base64url"),
|
||||
complete: true,
|
||||
},
|
||||
};
|
||||
expect(toMcpPublishLogPage(invalid)).toEqual(invalid);
|
||||
expect(toMcpPublishLogPage({ availability: "unavailable" })).toEqual({
|
||||
availability: "unavailable",
|
||||
});
|
||||
});
|
||||
|
||||
test("instructs connected agents to update an outdated MCP CLI", () => {
|
||||
expect(
|
||||
getCliUpdateInstructions({
|
||||
@@ -2492,6 +2617,21 @@ test("exposes asset content editing through MCP discovery", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("exposes valid inputs for both publish targets through MCP discovery", () => {
|
||||
const tool = listProjectSessionMcpTools(publicApiOperations).find(
|
||||
({ name }) => name === "publish"
|
||||
);
|
||||
|
||||
expect(tool?.inputSchema).toMatchObject({
|
||||
additionalProperties: true,
|
||||
required: ["target"],
|
||||
oneOf: [
|
||||
{ properties: { target: expect.any(Object) } },
|
||||
{ properties: { target: expect.any(Object) } },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("exposes a client-valid update-props schema", () => {
|
||||
const tool = listProjectSessionMcpTools(publicApiOperations).find(
|
||||
({ name }) => name === "update-props"
|
||||
|
||||
@@ -1104,6 +1104,140 @@ const getMcpOperationInput = (command: string, input: unknown) => {
|
||||
return input;
|
||||
};
|
||||
|
||||
const createMcpPublishSession = () => {
|
||||
const publishes = new Map<string, { sequence: number; logHandle?: string }>();
|
||||
let sequence = 0;
|
||||
let latestBuildId: string | undefined;
|
||||
return {
|
||||
begin() {
|
||||
latestBuildId = undefined;
|
||||
return ++sequence;
|
||||
},
|
||||
remember(callSequence: number, result: unknown) {
|
||||
if (
|
||||
isPlainRecord(result) === false ||
|
||||
result.status !== "pending" ||
|
||||
typeof result.buildId !== "string"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
publishes.set(result.buildId, {
|
||||
sequence: callSequence,
|
||||
logHandle:
|
||||
typeof result.logHandle === "string" ? result.logHandle : undefined,
|
||||
});
|
||||
if (callSequence === sequence) {
|
||||
latestBuildId = result.buildId;
|
||||
}
|
||||
if (publishes.size > 10) {
|
||||
const oldest = [...publishes].reduce((left, right) =>
|
||||
left[1].sequence < right[1].sequence ? left : right
|
||||
)[0];
|
||||
publishes.delete(oldest);
|
||||
}
|
||||
},
|
||||
get(buildId: string | undefined) {
|
||||
const selected = buildId ?? latestBuildId;
|
||||
if (selected === undefined) {
|
||||
throw createMcpInputError(
|
||||
"No accepted publish is available in this MCP session.",
|
||||
"PUBLISH_REQUIRED"
|
||||
);
|
||||
}
|
||||
const publish = publishes.get(selected);
|
||||
if (publish === undefined) {
|
||||
throw createMcpInputError(
|
||||
"This publish is not available in this MCP session.",
|
||||
"PUBLISH_NOT_FOUND"
|
||||
);
|
||||
}
|
||||
return { buildId: selected, logHandle: publish.logHandle };
|
||||
},
|
||||
getHandle(buildId: string) {
|
||||
return publishes.get(buildId)?.logHandle;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const toMcpPublishLogPage = (value: unknown, cursor = 0) => {
|
||||
if (isPlainRecord(value) === false || value.availability !== "available") {
|
||||
return value;
|
||||
}
|
||||
const log = value.log;
|
||||
if (
|
||||
isPlainRecord(log) === false ||
|
||||
log.encoding !== "base64url" ||
|
||||
typeof log.chunk !== "string"
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
const bytes = Buffer.from(log.chunk, "base64url");
|
||||
const decoder = new TextDecoder("utf-8", { fatal: true });
|
||||
for (let trailingBytes = 0; trailingBytes <= 3; trailingBytes++) {
|
||||
if (trailingBytes > 0 && log.complete !== false) {
|
||||
break;
|
||||
}
|
||||
try {
|
||||
const text = decoder.decode(
|
||||
bytes.subarray(0, bytes.length - trailingBytes)
|
||||
);
|
||||
const nextCursor =
|
||||
trailingBytes === 0
|
||||
? log.nextCursor
|
||||
: typeof log.nextCursor === "number" &&
|
||||
log.nextCursor === cursor + bytes.length
|
||||
? log.nextCursor - trailingBytes
|
||||
: undefined;
|
||||
if (
|
||||
trailingBytes > 0 &&
|
||||
(typeof nextCursor !== "number" || nextCursor <= cursor)
|
||||
) {
|
||||
break;
|
||||
}
|
||||
const { chunk: _chunk, encoding: _encoding, ...metadata } = log;
|
||||
return {
|
||||
...value,
|
||||
log: {
|
||||
...metadata,
|
||||
text,
|
||||
...(nextCursor === undefined ? {} : { nextCursor }),
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
// Invalid UTF-8 stays in its original byte-exact base64url form.
|
||||
}
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const toMcpPublishOperation = (
|
||||
operation: (typeof publicApiOperations)[number]
|
||||
) =>
|
||||
operation.command === "get-publish-job"
|
||||
? {
|
||||
...operation,
|
||||
inputSchema: {
|
||||
type: "object" as const,
|
||||
properties: { jobId: { type: "string" as const } },
|
||||
required: ["jobId"],
|
||||
},
|
||||
}
|
||||
: operation.command === "get-publish-log"
|
||||
? {
|
||||
...operation,
|
||||
description:
|
||||
"Read one page of the log for a publish started in this MCP session. Use nextCursor to continue. Publishes are forgotten when this MCP server stops.",
|
||||
inputSchema: {
|
||||
type: "object" as const,
|
||||
properties: {
|
||||
buildId: { type: "string" as const },
|
||||
cursor: { type: "integer" as const, minimum: 0 },
|
||||
},
|
||||
required: [],
|
||||
},
|
||||
}
|
||||
: operation;
|
||||
|
||||
const publicApiOperationByCommand = new Map<
|
||||
string,
|
||||
(typeof publicApiOperations)[number]
|
||||
@@ -2023,7 +2157,10 @@ const createCliMcpHost = async ({
|
||||
},
|
||||
};
|
||||
const apiContract = await getCliServerApiContract(apiConnection);
|
||||
const operations = getSupportedPublicApiOperations(apiContract);
|
||||
const operations = getSupportedPublicApiOperations(apiContract).map(
|
||||
toMcpPublishOperation
|
||||
);
|
||||
const publishSession = createMcpPublishSession();
|
||||
const failureTracker = createIssueReportFailureTracker();
|
||||
const targetTracker = createIssueReportTargetTracker();
|
||||
const issueReportFailureFile = getIssueReportFailureFile(
|
||||
@@ -2144,6 +2281,41 @@ const createCliMcpHost = async ({
|
||||
executeOperation: async ({ command, input, dryRun }) => {
|
||||
assertMcpToolServerSupport(command, apiContract, dryRun === true);
|
||||
let operationInput = getMcpOperationInput(command, input);
|
||||
const publishSequence =
|
||||
command === "publish" && dryRun !== true
|
||||
? publishSession.begin()
|
||||
: undefined;
|
||||
let unavailableLogBuildId: string | undefined;
|
||||
if (command === "get-publish-log") {
|
||||
const requestedBuildId =
|
||||
isPlainRecord(operationInput) &&
|
||||
typeof operationInput.buildId === "string"
|
||||
? operationInput.buildId
|
||||
: undefined;
|
||||
const publish = publishSession.get(requestedBuildId);
|
||||
if (publish.logHandle === undefined) {
|
||||
unavailableLogBuildId = publish.buildId;
|
||||
} else {
|
||||
operationInput = {
|
||||
buildId: publish.buildId,
|
||||
logHandle: publish.logHandle,
|
||||
...(isPlainRecord(operationInput) &&
|
||||
typeof operationInput.cursor === "number"
|
||||
? { cursor: operationInput.cursor }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
if (
|
||||
command === "get-publish-job" &&
|
||||
isPlainRecord(operationInput) &&
|
||||
typeof operationInput.jobId === "string"
|
||||
) {
|
||||
const logHandle = publishSession.getHandle(operationInput.jobId);
|
||||
if (logHandle !== undefined) {
|
||||
operationInput = { ...operationInput, logHandle };
|
||||
}
|
||||
}
|
||||
const projectOrigin = new URL(apiConnection.origin).origin;
|
||||
if (command === "copy-design-token" && isPlainRecord(operationInput)) {
|
||||
operationInput = { ...operationInput, sourceOrigin: projectOrigin };
|
||||
@@ -2180,8 +2352,12 @@ const createCliMcpHost = async ({
|
||||
session,
|
||||
});
|
||||
const result = await executeProjectSessionApiOperation({
|
||||
command,
|
||||
input: operationInput,
|
||||
command:
|
||||
unavailableLogBuildId === undefined ? command : "get-publish-job",
|
||||
input:
|
||||
unavailableLogBuildId === undefined
|
||||
? operationInput
|
||||
: { jobId: unavailableLogBuildId },
|
||||
connection: apiConnection,
|
||||
createProjectSession: () => session,
|
||||
apiContract,
|
||||
@@ -2190,6 +2366,35 @@ const createCliMcpHost = async ({
|
||||
if (dryRun !== true && shouldInvalidatePreview(command)) {
|
||||
previewFreshness.markStale();
|
||||
}
|
||||
if (unavailableLogBuildId !== undefined) {
|
||||
return {
|
||||
...result,
|
||||
operationId: "publish.getLog",
|
||||
result: { availability: "unavailable" },
|
||||
};
|
||||
}
|
||||
if (command === "publish" && publishSequence !== undefined) {
|
||||
publishSession.remember(publishSequence, result.result);
|
||||
if (isPlainRecord(result.result)) {
|
||||
const { logHandle: _logHandle, ...publicResult } = result.result;
|
||||
return { ...result, result: publicResult };
|
||||
}
|
||||
}
|
||||
if (command === "get-publish-log") {
|
||||
return {
|
||||
...result,
|
||||
result: toMcpPublishLogPage(
|
||||
result.result,
|
||||
isPlainRecord(input) && typeof input.cursor === "number"
|
||||
? input.cursor
|
||||
: 0
|
||||
),
|
||||
};
|
||||
}
|
||||
if (command === "get-publish-job" && isPlainRecord(result.result)) {
|
||||
const { logHandle: _logHandle, ...publicResult } = result.result;
|
||||
return { ...result, result: publicResult };
|
||||
}
|
||||
return withTextAssetWriteFeedback({
|
||||
command,
|
||||
input,
|
||||
@@ -3162,6 +3367,9 @@ export const __testing__ = {
|
||||
createMcpRunCheckpointStopPayload,
|
||||
getLoadedProjectSessionSnapshot,
|
||||
getMcpOperationInput,
|
||||
createMcpPublishSession,
|
||||
toMcpPublishLogPage,
|
||||
toMcpPublishOperation,
|
||||
prepareTextAssetWriteFeedback,
|
||||
withTextAssetWriteFeedback,
|
||||
validateDownloadedTextAsset,
|
||||
|
||||
@@ -54,14 +54,18 @@ test("prints api command schema as json", () => {
|
||||
operation: "publish",
|
||||
method: "mutation",
|
||||
inputSchema: expect.objectContaining({
|
||||
type: "object",
|
||||
properties: expect.objectContaining({
|
||||
target: expect.objectContaining({
|
||||
enum: expect.arrayContaining(["staging", "production"]),
|
||||
oneOf: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: "object",
|
||||
properties: expect.objectContaining({
|
||||
target: expect.objectContaining({
|
||||
enum: expect.arrayContaining(["staging", "production"]),
|
||||
}),
|
||||
domains: expect.objectContaining({ type: "array" }),
|
||||
message: expect.objectContaining({ type: "string" }),
|
||||
}),
|
||||
}),
|
||||
domains: expect.objectContaining({ type: "array" }),
|
||||
message: expect.objectContaining({ type: "string" }),
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
@@ -72,9 +76,11 @@ test("prints api command schema as json", () => {
|
||||
])
|
||||
);
|
||||
for (const command of output.commands) {
|
||||
expect(command.inputSchema).toEqual(
|
||||
expect.objectContaining({ type: "object" })
|
||||
);
|
||||
const schemas = command.inputSchema.oneOf ?? [command.inputSchema];
|
||||
expect(schemas).not.toHaveLength(0);
|
||||
for (const inputSchema of schemas) {
|
||||
expect(inputSchema).toEqual(expect.objectContaining({ type: "object" }));
|
||||
}
|
||||
}
|
||||
expect(output.commands).not.toEqual(
|
||||
expect.arrayContaining([
|
||||
@@ -99,7 +105,10 @@ test("prints api command schema as json", () => {
|
||||
}),
|
||||
expect.objectContaining({
|
||||
useCase: "Publish project",
|
||||
commands: ["webstudio publish deploy --target production --json"],
|
||||
commands: [
|
||||
"webstudio publish deploy --target production --json",
|
||||
"webstudio publish deploy --target production --json --wait",
|
||||
],
|
||||
}),
|
||||
])
|
||||
);
|
||||
@@ -149,8 +158,16 @@ test("prints compact mcp tool summaries as json by default", () => {
|
||||
inputSchema,
|
||||
})
|
||||
);
|
||||
// Includes Form simulation, custom response headers, screenshot, and all three style source transfer schemas.
|
||||
expect(JSON.stringify(handshakePayload).length).toBeLessThan(224_500);
|
||||
// Publish validation and execution occupy about 1.5k characters; keep the old
|
||||
// budget for all other tools and a tight overall handshake budget.
|
||||
expect(JSON.stringify(handshakePayload).length).toBeLessThan(226_000);
|
||||
expect(
|
||||
JSON.stringify(
|
||||
handshakePayload.filter(
|
||||
({ name }) => name !== "validate-publish" && name !== "get-publish-log"
|
||||
)
|
||||
).length
|
||||
).toBeLessThan(224_500);
|
||||
const screenshotTool = expectedTools.find(
|
||||
({ name }) => name === "screenshot"
|
||||
);
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
// Edit markdown files in src/docs instead.
|
||||
export const cliDocs = {
|
||||
"api-use-cases":
|
||||
'# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search values and ids across every Builder namespace without sending full project data to the model.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nest
Line truncated
|
||||
'# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get-more-tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get-more-tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search values and ids across every Builder namespace without sending full project data to the model.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nest
Line truncated
|
||||
"manual-api":
|
||||
'# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## Search project data\n\nRun `webstudio search-project \'{"query":"known value"}\'` to search all Builder\nnamespaces in the local project session. Narrow it with\n`{"query":"Brand","namespaces":["styleSources","styles"]}` when only specific\nnamespaces are relevant. Results contain the current value, stable match id,\nnamespace path, owning entity, resolved references, and affected pages.\n\nValues in recognized credential fields are excluded and reported in\n`excludedSensitiveValueCount`.\n\nThe command synchronizes its required Builder namespaces, then searches locally\nand returns only matches. Namespace filters limit values matched; related\nnamespaces may still supply route and reference context, and synchronization is\nunchanged. This reduces data sent to the model, not project synchronization. It\nsearches asset metadata, not asset binaries or document contents.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\nAn Editor link with API access can patch text and editable props inside a\nContent Block. The server checks the complete batch before saving it. Pages,\nassets, component structure, and design changes still require Builder access.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand M
Line truncated
|
||||
'# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## Publish and wait\n\nUse `webstudio publish deploy --target production --json --wait` to wait for\nthis publish and read its available diagnostics before the CLI exits. Without\n`--wait`, publish returns as soon as the job is accepted. Waiting stops after\n360 checks at five-second intervals, plus the time spent on API requests. It\ndoes not stop the remote publish or save its logs. A successful publish still\nsucceeds if its logs are unavailable.\n\n## Search project data\n\nRun `webstudio search-project \'{"query":"known value"}\'` to search all Builder\nnamespaces in the local project session. Narrow it with\n`{"query":"Brand","namespaces":["styleSources","styles"]}` when only specific\nnamespaces are relevant. Results contain the current value, stable match id,\nnamespace path, owning entity, resolved references, and affected pages.\n\nValues in recognized credential fields are excluded and reported in\n`excludedSensitiveValueCount`.\n\nThe command synchronizes its required Builder namespaces, then searches locally\nand returns only matches. Namespace filters limit values matched; related\nnamespaces may still supply route and reference context, and synchronization is\nunchanged. This reduces data sent to the model, not project synchronization. It\nsearches asset metadata, not asset binaries or document contents.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\nAn Editor link with API access can patch text and editable props inside a\nContent Block. The server checks the complete batch before saving it. Pages,\nassets, component structure, and design changes still require Builder access.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reus
Line truncated
|
||||
"manual-llm":
|
||||
'# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get-more-tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call m
Line truncated
|
||||
"manual-mcp":
|
||||
|
||||
@@ -1111,6 +1111,13 @@ Commands:
|
||||
Commands:
|
||||
|
||||
- webstudio publish deploy --target production --json
|
||||
- webstudio publish deploy --target production --json --wait
|
||||
|
||||
The default CLI command returns when the job is accepted. Use `--wait` to
|
||||
receive status updates on stderr until publishing finishes, then read available
|
||||
logs before the command exits. `--wait` does not cancel a publish if waiting
|
||||
stops. Logs are available only on Pro and Team plans. In an MCP session, call
|
||||
`publish {"target":"production"}` to start a publish.
|
||||
|
||||
## List publishes
|
||||
|
||||
@@ -1124,6 +1131,20 @@ Commands:
|
||||
|
||||
- webstudio publish status --job <buildId> --json
|
||||
|
||||
## Inspect publish log
|
||||
|
||||
Commands:
|
||||
|
||||
- webstudio publish log --build-id <buildId> --log-handle <logHandle> --json
|
||||
- MCP tool: get-publish-log {}
|
||||
- MCP tool: get-publish-log {"buildId":"<buildId>","cursor":262144}
|
||||
|
||||
An MCP server remembers at most ten publishes it started. Omit `buildId` to
|
||||
read the latest accepted publish, or pass the build ID returned by `publish`.
|
||||
Continue with `nextCursor` until the page says `complete`. Each page checks
|
||||
project access and the current plan. The MCP server forgets publishes when it
|
||||
stops; a separate one-shot CLI process cannot read its session memory.
|
||||
|
||||
## Unpublish
|
||||
|
||||
Unpublish completes without a publish job.
|
||||
|
||||
@@ -31,6 +31,15 @@ The API commands operate on the single project configured by:
|
||||
- Use --refresh on local-capable commands to refresh required namespaces before running.
|
||||
- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.
|
||||
|
||||
## Publish and wait
|
||||
|
||||
Use `webstudio publish deploy --target production --json --wait` to wait for
|
||||
this publish and read its available diagnostics before the CLI exits. Without
|
||||
`--wait`, publish returns as soon as the job is accepted. Waiting stops after
|
||||
360 checks at five-second intervals, plus the time spent on API requests. It
|
||||
does not stop the remote publish or save its logs. A successful publish still
|
||||
succeeds if its logs are unavailable.
|
||||
|
||||
## Search project data
|
||||
|
||||
Run `webstudio search-project '{"query":"known value"}'` to search all Builder
|
||||
|
||||
@@ -19,14 +19,23 @@ export const PanelBanner = styled(Box, {
|
||||
info: {},
|
||||
warning: {
|
||||
backgroundColor: cssVar("--background-warning-subtle"),
|
||||
boxShadow: `inset 0 0 0 1px light-dark(transparent, ${cssVar(
|
||||
"--border-warning"
|
||||
)})`,
|
||||
[iconColor]: cssVar("--foreground-warning"),
|
||||
},
|
||||
error: {
|
||||
backgroundColor: cssVar("--background-negative-subtle"),
|
||||
boxShadow: `inset 0 0 0 1px light-dark(transparent, ${cssVar(
|
||||
"--background-negative"
|
||||
)})`,
|
||||
[iconColor]: cssVar("--foreground-negative"),
|
||||
},
|
||||
success: {
|
||||
backgroundColor: cssVar("--background-positive-subtle"),
|
||||
boxShadow: `inset 0 0 0 1px light-dark(transparent, ${cssVar(
|
||||
"--background-positive"
|
||||
)})`,
|
||||
[iconColor]: cssVar("--foreground-positive"),
|
||||
},
|
||||
neutral: {
|
||||
|
||||
@@ -79,8 +79,9 @@ type ScrollAreaProps = {
|
||||
} & Pick<ComponentProps<"div">, "onScroll" | "children">;
|
||||
|
||||
/**
|
||||
* @deprecated Use ScrollAreaNative instead. Native scrolling avoids interaction
|
||||
* bugs from the custom Radix scroll area implementation.
|
||||
* @deprecated Do not use in new code. Use ScrollAreaNative instead. This legacy
|
||||
* Radix implementation remains only for existing callers; native scrolling
|
||||
* avoids its interaction bugs.
|
||||
*/
|
||||
export const ScrollArea = forwardRef(
|
||||
(
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { beforeEach, expect, test, vi } from "vitest";
|
||||
import {
|
||||
createTestServer,
|
||||
db,
|
||||
@@ -10,6 +10,7 @@ import { http } from "msw";
|
||||
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
|
||||
import {
|
||||
getProjectPublishJob,
|
||||
getProjectPublishLog,
|
||||
listProjectPublishes,
|
||||
getDeploymentPublishErrorDiagnostics,
|
||||
publishProject,
|
||||
@@ -18,6 +19,7 @@ import {
|
||||
} from "./project-domain-api.server";
|
||||
|
||||
const server = createTestServer();
|
||||
beforeEach(() => server.use(db.get("Asset", () => json([]))));
|
||||
const context = testContext as unknown as AppContext;
|
||||
const stagingContext = {
|
||||
...context,
|
||||
@@ -32,6 +34,9 @@ const ownershipHandler = db.get("Project", ({ request }) => {
|
||||
if (url.searchParams.has("userId")) {
|
||||
return json({ id: url.searchParams.get("id")?.replace("eq.", "") });
|
||||
}
|
||||
if (url.searchParams.get("select") === "userId") {
|
||||
return json({ userId: "user-1" });
|
||||
}
|
||||
return json(null);
|
||||
});
|
||||
|
||||
@@ -123,6 +128,9 @@ const createPublishContext = (
|
||||
({
|
||||
...testContext,
|
||||
authorization: { type: "user", userId: "user-1" },
|
||||
getOwnerPlanFeatures: async () => ({
|
||||
allowPublishLogs: false,
|
||||
}),
|
||||
deployment: {
|
||||
deploymentTrpc: {
|
||||
publish: {
|
||||
@@ -145,7 +153,7 @@ const productionBuildHandler = (
|
||||
onRequest: (body: { project_id: string; deployment: string }) => void
|
||||
) =>
|
||||
http.post(
|
||||
`${postgrestUrl}/rpc/create_production_build`,
|
||||
`${postgrestUrl}/rpc/create_production_build_expected`,
|
||||
async ({ request }) => {
|
||||
onRequest(
|
||||
(await request.json()) as { project_id: string; deployment: string }
|
||||
@@ -154,6 +162,328 @@ const productionBuildHandler = (
|
||||
}
|
||||
);
|
||||
|
||||
const logInput = {
|
||||
projectId: "project-1",
|
||||
buildId: "build-prod",
|
||||
logHandle: "signed-handle",
|
||||
cursor: 128,
|
||||
};
|
||||
|
||||
test("checks project and build ownership before fetching publish logs", async () => {
|
||||
const query = vi.fn().mockResolvedValue({ availability: "pending" });
|
||||
const publishContext = {
|
||||
...createPublishContext(),
|
||||
deployment: {
|
||||
...createPublishContext().deployment,
|
||||
deploymentTrpc: { getPublishLog: { query } },
|
||||
},
|
||||
} as unknown as AppContext;
|
||||
server.use(
|
||||
ownershipHandler,
|
||||
db.get("Build", ({ request }) => {
|
||||
const params = new URL(request.url).searchParams;
|
||||
expect(params.get("projectId")).toBe("eq.project-1");
|
||||
expect(params.get("id")).toBe("eq.build-prod");
|
||||
return empty({ status: 204 });
|
||||
})
|
||||
);
|
||||
|
||||
await expect(getProjectPublishLog(logInput, publishContext)).resolves.toEqual(
|
||||
{ availability: "unavailable" }
|
||||
);
|
||||
await expect(
|
||||
getProjectPublishLog(logInput, {
|
||||
...publishContext,
|
||||
authorization: { type: "anonymous" },
|
||||
} as AppContext)
|
||||
).rejects.toThrow();
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("uses the Free project owner's plan despite a Pro collaborator", async () => {
|
||||
const query = vi.fn().mockResolvedValue({
|
||||
availability: "available",
|
||||
outcome: "failed",
|
||||
logAvailability: "unavailable",
|
||||
code: "cancelled",
|
||||
});
|
||||
const publishContext = {
|
||||
...createPublishContext(),
|
||||
planFeatures: { allowPublishLogs: true },
|
||||
deployment: {
|
||||
...createPublishContext().deployment,
|
||||
deploymentTrpc: { getPublishLog: { query } },
|
||||
},
|
||||
} as unknown as AppContext;
|
||||
server.use(
|
||||
ownershipHandler,
|
||||
db.get("Build", () => json({ id: "build-prod" }))
|
||||
);
|
||||
|
||||
const attemptedOverride = { ...logInput, includeLog: true };
|
||||
const result = await getProjectPublishLog(attemptedOverride, publishContext);
|
||||
expect(result).toEqual({ availability: "unavailable" });
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("uses the Pro project owner's plan despite a Free collaborator", async () => {
|
||||
const response = {
|
||||
availability: "available" as const,
|
||||
outcome: "succeeded" as const,
|
||||
logAvailability: "available" as const,
|
||||
log: { encoding: "base64url" as const, chunk: "c2VjcmV0", complete: true },
|
||||
};
|
||||
const publishContext = {
|
||||
...createPublishContext(),
|
||||
planFeatures: { allowPublishLogs: false },
|
||||
getOwnerPlanFeatures: async () => ({
|
||||
allowPublishLogs: true,
|
||||
}),
|
||||
deployment: {
|
||||
...createPublishContext().deployment,
|
||||
deploymentTrpc: {
|
||||
getPublishLog: { query: vi.fn().mockResolvedValue(response) },
|
||||
},
|
||||
},
|
||||
} as unknown as AppContext;
|
||||
server.use(
|
||||
ownershipHandler,
|
||||
db.get("Build", () => json({ id: "build-prod" }))
|
||||
);
|
||||
await expect(getProjectPublishLog(logInput, publishContext)).resolves.toEqual(
|
||||
response
|
||||
);
|
||||
expect(
|
||||
publishContext.deployment.deploymentTrpc.getPublishLog.query
|
||||
).toHaveBeenCalledWith({
|
||||
buildId: "build-prod",
|
||||
logHandle: "signed-handle",
|
||||
cursor: 128,
|
||||
includeLog: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps Free publish failure status without downloading logs", async () => {
|
||||
const query = vi.fn().mockResolvedValue({
|
||||
availability: "available",
|
||||
outcome: "failed",
|
||||
logAvailability: "unavailable",
|
||||
code: "startup_failure",
|
||||
});
|
||||
const publishContext = {
|
||||
...createPublishContext(),
|
||||
planFeatures: { allowPublishLogs: false },
|
||||
deployment: {
|
||||
...createPublishContext().deployment,
|
||||
deploymentTrpc: {
|
||||
getPublishLog: { query },
|
||||
},
|
||||
},
|
||||
} as unknown as AppContext;
|
||||
server.use(
|
||||
ownershipHandler,
|
||||
db.get("Build", ({ request }) => {
|
||||
const params = new URL(request.url).searchParams;
|
||||
expect(params.get("projectId")).toBe("eq.project-1");
|
||||
expect(params.get("id")).toBe("eq.build-prod");
|
||||
return json({
|
||||
id: "build-prod",
|
||||
version: 3,
|
||||
createdAt: "2024-01-03T00:00:00.000Z",
|
||||
updatedAt: "2024-01-03T00:01:00.000Z",
|
||||
publishStatus: "PENDING",
|
||||
deployment: JSON.stringify({
|
||||
destination: "saas",
|
||||
target: "production",
|
||||
domains: ["example.com"],
|
||||
}),
|
||||
});
|
||||
})
|
||||
);
|
||||
await expect(
|
||||
getProjectPublishJob(
|
||||
{
|
||||
projectId: "project-1",
|
||||
jobId: "build-prod",
|
||||
logHandle: "signed-handle",
|
||||
},
|
||||
publishContext
|
||||
)
|
||||
).resolves.toMatchObject({ status: "failed", code: "startup_failure" });
|
||||
expect(query).toHaveBeenCalledWith({
|
||||
buildId: "build-prod",
|
||||
logHandle: "signed-handle",
|
||||
includeLog: false,
|
||||
});
|
||||
});
|
||||
|
||||
test.each([
|
||||
{
|
||||
label: "pending",
|
||||
response: { availability: "pending" },
|
||||
durableStatus: "PUBLISHED",
|
||||
status: "pending",
|
||||
code: undefined,
|
||||
completedAt: undefined,
|
||||
},
|
||||
{
|
||||
label: "succeeded",
|
||||
response: {
|
||||
availability: "available",
|
||||
outcome: "succeeded",
|
||||
completedAt: "2024-01-03T00:02:00.000Z",
|
||||
},
|
||||
durableStatus: "PENDING",
|
||||
status: "success",
|
||||
code: undefined,
|
||||
completedAt: "2024-01-03T00:02:00.000Z",
|
||||
},
|
||||
{
|
||||
label: "failed",
|
||||
response: {
|
||||
availability: "available",
|
||||
outcome: "failed",
|
||||
code: "cancelled",
|
||||
},
|
||||
durableStatus: "PUBLISHED",
|
||||
status: "failed",
|
||||
code: "cancelled",
|
||||
completedAt: undefined,
|
||||
},
|
||||
{
|
||||
label: "unavailable",
|
||||
response: { availability: "unavailable" },
|
||||
durableStatus: "PUBLISHED",
|
||||
status: "success",
|
||||
code: undefined,
|
||||
completedAt: "2024-01-03T00:01:00.000Z",
|
||||
},
|
||||
] as const)(
|
||||
"uses $label verified runner status without log transfer",
|
||||
async ({ response, durableStatus, status, code, completedAt }) => {
|
||||
const query = vi.fn().mockResolvedValue(response);
|
||||
const publishContext = {
|
||||
...createPublishContext(),
|
||||
deployment: {
|
||||
...createPublishContext().deployment,
|
||||
deploymentTrpc: { getPublishLog: { query } },
|
||||
},
|
||||
} as unknown as AppContext;
|
||||
server.use(
|
||||
db.get("Build", () =>
|
||||
json({
|
||||
id: "build-prod",
|
||||
version: 3,
|
||||
createdAt: "2024-01-03T00:00:00.000Z",
|
||||
updatedAt: "2024-01-03T00:01:00.000Z",
|
||||
publishStatus: durableStatus,
|
||||
deployment: JSON.stringify({
|
||||
destination: "saas",
|
||||
target: "production",
|
||||
domains: ["example.com"],
|
||||
}),
|
||||
})
|
||||
)
|
||||
);
|
||||
const result = await getProjectPublishJob(
|
||||
{
|
||||
projectId: "project-1",
|
||||
jobId: "build-prod",
|
||||
logHandle: "signed-handle",
|
||||
},
|
||||
publishContext
|
||||
);
|
||||
expect(result).toMatchObject({ status });
|
||||
expect(result?.completedAt).toBe(completedAt);
|
||||
if (code === undefined) {
|
||||
expect(result).not.toHaveProperty("code");
|
||||
} else {
|
||||
expect(result).toHaveProperty("code", code);
|
||||
}
|
||||
expect(query).toHaveBeenCalledWith({
|
||||
buildId: "build-prod",
|
||||
logHandle: "signed-handle",
|
||||
includeLog: false,
|
||||
});
|
||||
expect(result).not.toHaveProperty("log");
|
||||
}
|
||||
);
|
||||
|
||||
test("keeps the durable status when runner status lookup rejects", async () => {
|
||||
const query = vi.fn().mockRejectedValue(new Error("runner unavailable"));
|
||||
const publishContext = {
|
||||
...createPublishContext(),
|
||||
deployment: {
|
||||
...createPublishContext().deployment,
|
||||
deploymentTrpc: { getPublishLog: { query } },
|
||||
},
|
||||
} as unknown as AppContext;
|
||||
server.use(
|
||||
db.get("Build", () =>
|
||||
json({
|
||||
id: "build-prod",
|
||||
version: 3,
|
||||
createdAt: "2024-01-03T00:00:00.000Z",
|
||||
updatedAt: "2024-01-03T00:01:00.000Z",
|
||||
publishStatus: "FAILED",
|
||||
deployment: JSON.stringify({ destination: "saas", domains: [] }),
|
||||
})
|
||||
)
|
||||
);
|
||||
await expect(
|
||||
getProjectPublishJob(
|
||||
{
|
||||
projectId: "project-1",
|
||||
jobId: "build-prod",
|
||||
logHandle: "signed-handle",
|
||||
},
|
||||
publishContext
|
||||
)
|
||||
).resolves.toMatchObject({ status: "failed" });
|
||||
expect(query).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
test("removed and missing jobs never query the runner", async () => {
|
||||
const query = vi.fn();
|
||||
const publishContext = {
|
||||
...createPublishContext(),
|
||||
deployment: {
|
||||
...createPublishContext().deployment,
|
||||
deploymentTrpc: { getPublishLog: { query } },
|
||||
},
|
||||
} as unknown as AppContext;
|
||||
server.use(
|
||||
db.get("Build", () =>
|
||||
json({
|
||||
id: "build-prod",
|
||||
version: 3,
|
||||
createdAt: "2024-01-03T00:00:00.000Z",
|
||||
updatedAt: "2024-01-03T00:01:00.000Z",
|
||||
publishStatus: "PUBLISHED",
|
||||
deployment: null,
|
||||
})
|
||||
)
|
||||
);
|
||||
await expect(
|
||||
getProjectPublishJob(
|
||||
{
|
||||
projectId: "project-1",
|
||||
jobId: "build-prod",
|
||||
logHandle: "signed-handle",
|
||||
},
|
||||
publishContext
|
||||
)
|
||||
).resolves.toMatchObject({ status: "removed" });
|
||||
server.use(db.get("Build", () => empty({ status: 204 })));
|
||||
await expect(
|
||||
getProjectPublishJob(
|
||||
{ projectId: "project-1", jobId: "missing", logHandle: "signed-handle" },
|
||||
publishContext
|
||||
)
|
||||
).resolves.toBeUndefined();
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("publish error diagnostics expose metadata without response values", () => {
|
||||
const secret = "private-response-and-auth-sentinel";
|
||||
const error = Object.assign(new Error(secret), {
|
||||
@@ -250,19 +580,20 @@ test("publishes saas project through shared domain service", async () => {
|
||||
})
|
||||
);
|
||||
|
||||
await expect(
|
||||
publishProject(
|
||||
{
|
||||
project: loadedProject,
|
||||
domains: ["project.wstd.io", "example.com"],
|
||||
target: "production",
|
||||
},
|
||||
createPublishContext(publish)
|
||||
)
|
||||
).resolves.toMatchObject({
|
||||
const response = await publishProject(
|
||||
{
|
||||
project: loadedProject,
|
||||
domains: ["project.wstd.io", "example.com"],
|
||||
target: "production",
|
||||
},
|
||||
createPublishContext(publish)
|
||||
);
|
||||
expect(response).toMatchObject({
|
||||
build: { id: "build-prod" },
|
||||
deploymentNotImplemented: false,
|
||||
});
|
||||
expect(response.logHandle).toBeUndefined();
|
||||
expect(publish).toHaveBeenCalledOnce();
|
||||
|
||||
expect(productionBuildRequest?.project_id).toBe("project-1");
|
||||
expect(JSON.parse(productionBuildRequest?.deployment ?? "")).toEqual({
|
||||
|
||||
@@ -13,12 +13,29 @@ import {
|
||||
type Deployment,
|
||||
type PublishTarget,
|
||||
} from "@webstudio-is/sdk";
|
||||
import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
|
||||
import {
|
||||
authorizeProject,
|
||||
AuthorizationError,
|
||||
getProjectPlanFeatures,
|
||||
type AppContext,
|
||||
} from "@webstudio-is/trpc-interface/index.server";
|
||||
import { PrePublishAuditError } from "@webstudio-is/project-build/runtime";
|
||||
import { db } from "./db";
|
||||
import { validateDomain } from "./db/validate";
|
||||
|
||||
type LoadedProject = Awaited<ReturnType<typeof projectApi.loadById>>;
|
||||
type ProjectDomain = LoadedProject["domainsVirtual"][number];
|
||||
export const getVisiblePublishFindings = (
|
||||
findings: PrePublishAuditError["findings"],
|
||||
allowPublishLogs: boolean | undefined
|
||||
) =>
|
||||
allowPublishLogs === true
|
||||
? findings
|
||||
: findings.map(({ message, location, ...finding }) => ({
|
||||
...finding,
|
||||
message: message.slice(0, 160),
|
||||
location: {},
|
||||
}));
|
||||
|
||||
const publishResponseDiagnosticHeaders = [
|
||||
"content-type",
|
||||
@@ -196,7 +213,7 @@ export const listProjectPublishes = async (
|
||||
};
|
||||
|
||||
export const getProjectPublishJob = async (
|
||||
input: { projectId: string; jobId: string },
|
||||
input: { projectId: string; jobId: string; logHandle?: string },
|
||||
context: AppContext
|
||||
) => {
|
||||
const result = await context.postgrest.client
|
||||
@@ -231,7 +248,7 @@ export const getProjectPublishJob = async (
|
||||
hostedDeployment?.domains.includes(hostedDomain)
|
||||
? hostedDomain
|
||||
: undefined;
|
||||
const status =
|
||||
let status: "removed" | "success" | "failed" | "pending" =
|
||||
deployment === undefined
|
||||
? "removed"
|
||||
: publishJob.publishStatus === "PUBLISHED"
|
||||
@@ -239,25 +256,96 @@ export const getProjectPublishJob = async (
|
||||
: publishJob.publishStatus === "FAILED"
|
||||
? "failed"
|
||||
: "pending";
|
||||
let completedAt =
|
||||
status === "success" || status === "failed"
|
||||
? publishJob.updatedAt
|
||||
: undefined;
|
||||
let code: string | undefined;
|
||||
if (input.logHandle !== undefined && status !== "removed") {
|
||||
try {
|
||||
const result =
|
||||
await context.deployment.deploymentTrpc.getPublishLog.query({
|
||||
buildId: publishJob.id,
|
||||
logHandle: input.logHandle,
|
||||
includeLog: false,
|
||||
});
|
||||
if (result.availability === "pending") {
|
||||
status = "pending";
|
||||
completedAt = undefined;
|
||||
}
|
||||
if (result.availability === "available") {
|
||||
status = result.outcome === "succeeded" ? "success" : "failed";
|
||||
completedAt = result.completedAt;
|
||||
code = result.outcome === "failed" ? result.code : undefined;
|
||||
}
|
||||
} catch {
|
||||
// The durable Build status remains available when GitHub status is not.
|
||||
}
|
||||
}
|
||||
return {
|
||||
id: publishJob.id,
|
||||
version: publishJob.version,
|
||||
status,
|
||||
...(code === undefined ? {} : { code }),
|
||||
target,
|
||||
domains: hostedDeployment?.domains ?? [],
|
||||
...(stagingDomain === undefined
|
||||
? {}
|
||||
: {
|
||||
stagingUrl: `https://${stagingDomain.includes(".") ? stagingDomain : `${stagingDomain}.${context.deployment.env.PUBLISHER_HOST}`}`,
|
||||
stagingUrl: `https://${
|
||||
stagingDomain.includes(".")
|
||||
? stagingDomain
|
||||
: `${stagingDomain}.${context.deployment.env.PUBLISHER_HOST}`
|
||||
}`,
|
||||
}),
|
||||
createdAt: publishJob.createdAt,
|
||||
completedAt:
|
||||
status === "success" || status === "failed"
|
||||
? publishJob.updatedAt
|
||||
: undefined,
|
||||
completedAt,
|
||||
};
|
||||
};
|
||||
|
||||
export const getProjectPublishLog = async (
|
||||
input: {
|
||||
projectId: string;
|
||||
buildId: string;
|
||||
logHandle: string;
|
||||
cursor?: number;
|
||||
},
|
||||
context: AppContext
|
||||
) => {
|
||||
const allowed = await authorizeProject.hasProjectPermit(
|
||||
{ projectId: input.projectId, permit: "view" },
|
||||
context
|
||||
);
|
||||
if (allowed === false) {
|
||||
throw new AuthorizationError("You don't have access to this project");
|
||||
}
|
||||
const build = await context.postgrest.client
|
||||
.from("Build")
|
||||
.select("id")
|
||||
.eq("projectId", input.projectId)
|
||||
.eq("id", input.buildId)
|
||||
.maybeSingle();
|
||||
if (build.error) {
|
||||
throw build.error;
|
||||
}
|
||||
if (build.data === null) {
|
||||
return { availability: "unavailable" as const };
|
||||
}
|
||||
const { allowPublishLogs } = await getProjectPlanFeatures(
|
||||
input.projectId,
|
||||
context
|
||||
);
|
||||
if (allowPublishLogs !== true) {
|
||||
return { availability: "unavailable" as const };
|
||||
}
|
||||
return await context.deployment.deploymentTrpc.getPublishLog.query({
|
||||
buildId: input.buildId,
|
||||
logHandle: input.logHandle,
|
||||
cursor: input.cursor,
|
||||
includeLog: true,
|
||||
});
|
||||
};
|
||||
|
||||
const createPublishedDeployment = ({
|
||||
project,
|
||||
domains,
|
||||
@@ -299,6 +387,7 @@ export const publishProject = async (
|
||||
},
|
||||
context
|
||||
);
|
||||
const findings = build.auditFindings;
|
||||
const { deploymentTrpc, env } = context.deployment;
|
||||
|
||||
if (env.BUILDER_ORIGIN === undefined) {
|
||||
@@ -329,22 +418,31 @@ export const publishProject = async (
|
||||
throw new Error(String(result.error ?? "Publish failed"));
|
||||
}
|
||||
|
||||
return { build, project, deploymentNotImplemented };
|
||||
return {
|
||||
build,
|
||||
project,
|
||||
logHandle: result.success ? result.logHandle : undefined,
|
||||
findings,
|
||||
deploymentNotImplemented,
|
||||
};
|
||||
};
|
||||
|
||||
export const publishStaticProject = async (
|
||||
{
|
||||
projectId,
|
||||
templates,
|
||||
project: loadedProject,
|
||||
name = `${projectId}-${createId("nano")}.zip`,
|
||||
}: {
|
||||
projectId: string;
|
||||
templates: z.infer<typeof templateSchema>[];
|
||||
project?: LoadedProject;
|
||||
name?: string;
|
||||
},
|
||||
context: AppContext
|
||||
) => {
|
||||
const project = await projectApi.loadById(projectId, context);
|
||||
const project =
|
||||
loadedProject ?? (await projectApi.loadById(projectId, context));
|
||||
const build = await createProductionBuild(
|
||||
{
|
||||
projectId,
|
||||
@@ -358,6 +456,7 @@ export const publishStaticProject = async (
|
||||
context
|
||||
);
|
||||
|
||||
const findings = build.auditFindings;
|
||||
const { deploymentTrpc, env } = context.deployment;
|
||||
|
||||
if (env.BUILDER_ORIGIN === undefined) {
|
||||
@@ -374,7 +473,14 @@ export const publishStaticProject = async (
|
||||
});
|
||||
|
||||
return result.success
|
||||
? { success: true as const, name, build, project }
|
||||
? {
|
||||
success: true as const,
|
||||
name,
|
||||
build,
|
||||
project,
|
||||
logHandle: result.logHandle,
|
||||
findings,
|
||||
}
|
||||
: result;
|
||||
};
|
||||
|
||||
|
||||
@@ -6,14 +6,18 @@ import {
|
||||
createErrorResponse,
|
||||
authorizeProject,
|
||||
getProjectOwnerId,
|
||||
getProjectPlanFeatures,
|
||||
AuthorizationError,
|
||||
} from "@webstudio-is/trpc-interface/index.server";
|
||||
import { publishedDeploymentDestination, templates } from "@webstudio-is/sdk";
|
||||
import { PrePublishAuditError } from "@webstudio-is/project-build/runtime";
|
||||
import { db } from "../db";
|
||||
import { isDomainUsingCloudflareNameservers } from "../rdap";
|
||||
import {
|
||||
getVerifiedPublishDomains,
|
||||
listProjectPublishes,
|
||||
getPublishTargetForDomains,
|
||||
getVisiblePublishFindings,
|
||||
createProjectDomainResult,
|
||||
deleteProjectDomainResult,
|
||||
publishProject,
|
||||
@@ -23,10 +27,22 @@ import {
|
||||
} from "../project-domain-api.server";
|
||||
|
||||
export const domainRouter = router({
|
||||
publishActivity: procedure
|
||||
.input(z.object({ projectId: z.string() }))
|
||||
.query(async ({ input, ctx }) => {
|
||||
try {
|
||||
await projectApi.loadById(input.projectId, ctx);
|
||||
return {
|
||||
success: true as const,
|
||||
...(await listProjectPublishes(input.projectId, ctx)),
|
||||
};
|
||||
} catch (error) {
|
||||
return createErrorResponse(error);
|
||||
}
|
||||
}),
|
||||
getEntriToken: procedure.query(async ({ ctx }) => {
|
||||
try {
|
||||
const result = await ctx.entri.entryApi.getEntriToken();
|
||||
|
||||
return {
|
||||
success: true,
|
||||
token: result.token,
|
||||
@@ -36,7 +52,6 @@ export const domainRouter = router({
|
||||
return createErrorResponse(error);
|
||||
}
|
||||
}),
|
||||
|
||||
findDomainRegistrar: procedure
|
||||
.input(z.object({ domain: z.string() }))
|
||||
.query(async ({ input }) => {
|
||||
@@ -48,17 +63,12 @@ export const domainRouter = router({
|
||||
cnameFlattening: isCloudflare === true,
|
||||
};
|
||||
}),
|
||||
|
||||
project: procedure
|
||||
.input(z.object({ projectId: z.string() }))
|
||||
.query(async ({ input, ctx }) => {
|
||||
try {
|
||||
const project = await projectApi.loadById(input.projectId, ctx);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
project,
|
||||
} as const;
|
||||
return { success: true, project } as const;
|
||||
} catch (error) {
|
||||
return createErrorResponse(error);
|
||||
}
|
||||
@@ -79,11 +89,16 @@ export const domainRouter = router({
|
||||
])
|
||||
)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
let allowPublishLogs: boolean | undefined;
|
||||
try {
|
||||
const project = await projectApi.loadById(input.projectId, ctx);
|
||||
({ allowPublishLogs } = await getProjectPlanFeatures(
|
||||
input.projectId,
|
||||
ctx
|
||||
));
|
||||
if (input.destination === publishedDeploymentDestination) {
|
||||
const project = await projectApi.loadById(input.projectId, ctx);
|
||||
const domains = getVerifiedPublishDomains(project, input.domains);
|
||||
await publishProject(
|
||||
const result = await publishProject(
|
||||
{
|
||||
project,
|
||||
domains,
|
||||
@@ -91,23 +106,43 @@ export const domainRouter = router({
|
||||
},
|
||||
ctx
|
||||
);
|
||||
return { success: true as const };
|
||||
return {
|
||||
success: true as const,
|
||||
buildId: result.build.id,
|
||||
logHandle: result.logHandle,
|
||||
findings: getVisiblePublishFindings(
|
||||
result.findings,
|
||||
allowPublishLogs
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
const result = await publishStaticProject(
|
||||
{
|
||||
projectId: input.projectId,
|
||||
templates: input.templates,
|
||||
},
|
||||
{ projectId: input.projectId, templates: input.templates, project },
|
||||
ctx
|
||||
);
|
||||
|
||||
if (result.success) {
|
||||
return { success: true as const, name: result.name };
|
||||
return {
|
||||
success: true as const,
|
||||
name: result.name,
|
||||
buildId: result.build.id,
|
||||
logHandle: result.logHandle,
|
||||
findings: getVisiblePublishFindings(
|
||||
result.findings,
|
||||
allowPublishLogs
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (error instanceof PrePublishAuditError) {
|
||||
return {
|
||||
success: false as const,
|
||||
auditFindings: getVisiblePublishFindings(
|
||||
error.findings,
|
||||
allowPublishLogs
|
||||
),
|
||||
};
|
||||
}
|
||||
return createErrorResponse(error);
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -54,6 +54,7 @@ import {
|
||||
extractDesignToken,
|
||||
findAssetUsage,
|
||||
getPublishJob,
|
||||
getPublishLog,
|
||||
getApiCompatibilityMessage,
|
||||
getApiErrorCode,
|
||||
getErrorStatus,
|
||||
@@ -864,9 +865,21 @@ test("wraps project api trpc calls in named functions", async () => {
|
||||
message: "Ship",
|
||||
idempotencyKey: "publish-key",
|
||||
});
|
||||
await publish({
|
||||
...params,
|
||||
target: "static",
|
||||
templates: ["ssg", "vercel"],
|
||||
});
|
||||
await getPublishJob({
|
||||
...params,
|
||||
jobId: "job-id",
|
||||
logHandle: "signed-handle",
|
||||
});
|
||||
await getPublishLog({
|
||||
...params,
|
||||
buildId: "build-id",
|
||||
logHandle: "signed-handle",
|
||||
cursor: 256,
|
||||
});
|
||||
await unpublish({
|
||||
...params,
|
||||
@@ -1117,7 +1130,12 @@ test("wraps project api trpc calls in named functions", async () => {
|
||||
"/trpc/api.publish.create",
|
||||
'"idempotencyKey":"publish-key"'
|
||||
),
|
||||
expectBodyRequest(
|
||||
"/trpc/api.publish.create",
|
||||
'"templates":["ssg","vercel"]'
|
||||
),
|
||||
expectRequest("/trpc/api.publish.getJob"),
|
||||
expectRequest("/trpc/api.publish.getLog"),
|
||||
expectBodyRequest("/trpc/api.publish.unpublish", '"confirm":true'),
|
||||
expectRequest("/trpc/api.domains.list"),
|
||||
expectBodyRequest("/trpc/api.domains.create", '"domain":"example.com"'),
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type AssetFolder,
|
||||
type CustomResponseHeader,
|
||||
type ExpressionBindingMode,
|
||||
type Templates,
|
||||
} from "@webstudio-is/sdk";
|
||||
import {
|
||||
assetContentDescriptor,
|
||||
@@ -2451,18 +2452,34 @@ export const validatePublish = projectQueryInput<
|
||||
>("validate-publish");
|
||||
|
||||
export const publish = projectMutationInput<
|
||||
AuthProjectParams & {
|
||||
target: "staging" | "production";
|
||||
domains?: string[];
|
||||
message?: string;
|
||||
idempotencyKey?: string;
|
||||
}
|
||||
AuthProjectParams &
|
||||
(
|
||||
| {
|
||||
target: "staging" | "production";
|
||||
domains?: string[];
|
||||
message?: string;
|
||||
idempotencyKey?: string;
|
||||
}
|
||||
| {
|
||||
target: "static";
|
||||
templates?: Templates[];
|
||||
idempotencyKey?: string;
|
||||
}
|
||||
)
|
||||
>("publish");
|
||||
|
||||
export const getPublishJob = projectQueryInput<
|
||||
AuthProjectParams & { jobId: string }
|
||||
AuthProjectParams & { jobId: string; logHandle?: string }
|
||||
>("get-publish-job");
|
||||
|
||||
export const getPublishLog = projectQueryInput<
|
||||
AuthProjectParams & {
|
||||
buildId: string;
|
||||
logHandle: string;
|
||||
cursor?: number;
|
||||
}
|
||||
>("get-publish-log");
|
||||
|
||||
export const unpublish = projectConfirmedMutationInput<
|
||||
AuthProjectParams & {
|
||||
target: "staging" | "production";
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="1"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 346 B |
+22
@@ -31,6 +31,28 @@ export const AccordionIcon: IconComponent = forwardRef(
|
||||
);
|
||||
AccordionIcon.displayName = "AccordionIcon";
|
||||
|
||||
export const ActivityIcon: IconComponent = forwardRef(
|
||||
({ fill = "none", size = 16, ...props }, forwardedRef) => {
|
||||
return (
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
viewBox="0 0 24 24"
|
||||
width={size}
|
||||
height={size}
|
||||
fill={fill}
|
||||
{...props}
|
||||
ref={forwardedRef}
|
||||
>
|
||||
<path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
);
|
||||
ActivityIcon.displayName = "ActivityIcon";
|
||||
|
||||
export const AddTemplateInstanceIcon: IconComponent = forwardRef(
|
||||
({ fill = "none", size = 16, ...props }, forwardedRef) => {
|
||||
return (
|
||||
|
||||
Generated
+2
@@ -1,5 +1,7 @@
|
||||
export const AccordionIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M13.056 8H14.5V4.101a1.3 1.3 0 0 0-1.3-1.299H2.8a1.3 1.3 0 0 0-1.3 1.3V8H13.056ZM13.056 13.198h.145a1.3 1.3 0 0 0 1.299-1.3V8h-13v3.899a1.3 1.3 0 0 0 1.3 1.299h10.256Z"/><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="m10.026 4.913.975.976.976-.976M10.026 10.111l.975.976.976-.976"/></svg>`;
|
||||
|
||||
export const ActivityIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24" width="100%" height="100%" style="display: block;"><path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"/></svg>`;
|
||||
|
||||
export const AddTemplateInstanceIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M4.5 2H3.333A1.333 1.333 0 0 0 2 3.333V4.5M14 12.667c0 .021 0 .042-.002.063M11.5 14h1.167a1.333 1.333 0 0 0 1.331-1.27m0 0V11.5M2 11.5v1.167A1.333 1.333 0 0 0 3.333 14H4.5M7 14h2M2 7v2M8.461 4.77H14M11.23 2v5.538"/></svg>`;
|
||||
|
||||
export const AiLoadingIcon = `<svg xmlns="http://www.w3.org/2000/svg" id="c86546c68__evA4hI5dD261" shape-rendering="geometricPrecision" text-rendering="geometricPrecision" viewBox="0 0 17 17" fill="currentColor" width="100%" height="100%" style="display: block;"><style>@keyframes evA4hI5dD263_s_do{0%,to{stroke-dashoffset:6.2}17.5%,82.5%{stroke-dashoffset:-6.24}}@keyframes evA4hI5dD264_s_do{0%,10%,90%,to{stroke-dashoffset:6.8}22.5%,77.5%{stroke-dashoffset:-6.8}}@keyframes evA4hI5dD265_s_do{0%,17.5%,82.5%,to{stroke-dashoffset:2.32}27.5%,72.5%{stroke-dashoffset:-2.32}}@keyframes evA4hI5dD266_s_do{0%,22.5%,77.5%,to{stroke-dashoffset:2.47}32.5%,67.5%{stroke-dashoffset:-2.47}}@keyframes evA4hI5dD267_s_do{0%,27.5%,72.5%,to{stroke-dashoffset:5.42}40%,60%{stroke-dashoffset:-5.42}}@keyframes evA4hI5dD268_s_do{0%,32.5%,67.5%,to{stroke-dashoffset:6.13}50%{stroke-dashoffset:-6.1}}#c86546c68__evA4hI5dD263{animation:evA4hI5dD263_s_do 4000ms linear infinite normal forwards}#c86546c68__evA4hI5dD264{animation:evA4hI5dD264_s_do 4000ms linear infinite normal forwards}#c86546c68__evA4hI5dD265{animation:evA4hI5dD265_s_do 4000ms linear infinite normal forwards}#c86546c68__evA4hI5dD266{animation:evA4hI5dD266_s_do 4000ms linear infinite normal forwards}#c86546c68__evA4hI5dD267{animation:evA4hI5dD267_s_do 4000ms linear infinite normal forwards}#c86546c68__evA4hI5dD268{animation:evA4hI5dD268_s_do 4000ms linear infinite normal forwards}</style><path fill="none" stroke="currentColor" stroke-dasharray="0" stroke-linecap="round" stroke-opacity=".4" stroke-width="2.2" d="m2.816 12.956 1.513-6.051a2.563 2.563 0 0 1 4.974 0l1.159 4.634a1.888 1.888 0 0 0 1.816 1.417 1.892 1.892 0 0 0 1.872-1.872V4.956"/><path id="c86546c68__evA4hI5dD263" fill="none" stroke="currentColor" stroke-dasharray="6.24" stroke-dashoffset="6.2" stroke-linecap="round" stroke-width="3.3" d="m2.816 12.956 1.513-6.051"/><path id="c86546c68__evA4hI5dD264" fill="none" stroke="currentColor" stroke-dasharray="6.8" stroke-dashoffset="6.8" stroke-linecap="round" stroke-width="3.3" d="M4.329 6.905a2.563 2.563 0 0 1 4.974 0"/><path id="c86546c68__evA4hI5dD265" fill="none" stroke="currentColor" stroke-dasharray="2.32" stroke-dashoffset="2.32" stroke-linecap="round" stroke-width="3.3" d="m9.303 6.905.561 2.243"/><path id="c86546c68__evA4hI5dD266" fill="none" stroke="currentColor" stroke-dasharray="2.47" stroke-dashoffset="2.47" stroke-linecap="round" stroke-width="3.3" d="m9.864 9.148.598 2.391"/><path id="c86546c68__evA4hI5dD267" fill="none" stroke="currentColor" stroke-dasharray="5.42" stroke-dashoffset="5.42" stroke-linecap="round" stroke-width="3.3" d="M10.462 11.54a1.888 1.888 0 0 0 1.816 1.416 1.892 1.892 0 0 0 1.872-1.872"/><path id="c86546c68__evA4hI5dD268" fill="none" stroke="currentColor" stroke-dasharray="6.13" stroke-dashoffset="6.13" stroke-linecap="round" stroke-width="3.3" d="M14.15 11.084V4.956"/></svg>`;
|
||||
|
||||
@@ -14,6 +14,18 @@ import {
|
||||
|
||||
const { parseProductMeta, mergeProductMetas } = __testing__;
|
||||
|
||||
test("normalizes legacy Product.meta log access and honors explicit false", () => {
|
||||
expect(parseProductMeta({ allowAdvancedPublishDiagnostics: true })).toEqual({
|
||||
allowPublishLogs: true,
|
||||
});
|
||||
expect(
|
||||
parseProductMeta({
|
||||
allowAdvancedPublishDiagnostics: true,
|
||||
allowPublishLogs: false,
|
||||
})
|
||||
).toEqual({ allowPublishLogs: false });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Unit tests for private helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { Client } from "@webstudio-is/postgrest/index.server";
|
||||
import {
|
||||
type PlanFeatures,
|
||||
planFeatures,
|
||||
planFeatureOverrides,
|
||||
defaultPlanFeatures,
|
||||
parsePlansEnv,
|
||||
type Purchase,
|
||||
@@ -23,7 +23,7 @@ type PlanInfo = {
|
||||
};
|
||||
|
||||
export const parseProductMeta = (meta: unknown): Partial<PlanFeatures> => {
|
||||
const result = planFeatures.partial().safeParse(meta);
|
||||
const result = planFeatureOverrides.safeParse(meta);
|
||||
return result.success ? result.data : {};
|
||||
};
|
||||
|
||||
|
||||
@@ -173,4 +173,36 @@ describe("parsePlansEnv", () => {
|
||||
(result.get("Pro")!.features as Record<string, unknown>)["admin"]
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
test("normalizes the legacy log flag and inherits the canonical value", () => {
|
||||
const result = parsePlansEnv(
|
||||
JSON.stringify([
|
||||
{ name: "Pro", features: { allowAdvancedPublishDiagnostics: true } },
|
||||
{ name: "Team", extends: "Pro", features: {} },
|
||||
])
|
||||
);
|
||||
expect(result.get("Pro")?.features.allowPublishLogs).toBe(true);
|
||||
expect(result.get("Team")?.features.allowPublishLogs).toBe(true);
|
||||
expect(result.get("Pro")?.features).not.toHaveProperty(
|
||||
"allowAdvancedPublishDiagnostics"
|
||||
);
|
||||
const explicitFalse = parsePlansEnv(
|
||||
JSON.stringify([
|
||||
{
|
||||
name: "Pro",
|
||||
features: {
|
||||
allowAdvancedPublishDiagnostics: true,
|
||||
allowPublishLogs: false,
|
||||
},
|
||||
},
|
||||
])
|
||||
);
|
||||
expect(explicitFalse.get("Pro")?.features.allowPublishLogs).toBe(false);
|
||||
expect(result.get("Team")?.features).not.toHaveProperty(
|
||||
"publishLogRetentionDays"
|
||||
);
|
||||
expect(result.get("Team")?.features).not.toHaveProperty(
|
||||
"publishActivityRetentionDays"
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,7 @@ export const planFeatures = z.object({
|
||||
allowAuth: z.boolean(),
|
||||
allowContentMode: z.boolean(),
|
||||
allowStagingPublish: z.boolean(),
|
||||
allowPublishLogs: z.boolean(),
|
||||
maxContactEmailsPerProject: z.number().nonnegative(),
|
||||
maxDomainsAllowedPerUser: z.number().nonnegative(),
|
||||
maxDailyPublishesPerUser: z.number().nonnegative(),
|
||||
@@ -23,6 +24,18 @@ export const planFeatures = z.object({
|
||||
maxSeatsPerWorkspace: z.number().nonnegative(),
|
||||
});
|
||||
|
||||
/** Accept the previous feature name only where external plan data enters. */
|
||||
export const planFeatureOverrides = planFeatures
|
||||
.partial()
|
||||
.extend({ allowAdvancedPublishDiagnostics: z.boolean().optional() })
|
||||
.transform(({ allowAdvancedPublishDiagnostics, ...features }) => ({
|
||||
...features,
|
||||
...(features.allowPublishLogs === undefined &&
|
||||
allowAdvancedPublishDiagnostics !== undefined
|
||||
? { allowPublishLogs: allowAdvancedPublishDiagnostics }
|
||||
: {}),
|
||||
}));
|
||||
|
||||
export type PlanFeatures = z.infer<typeof planFeatures>;
|
||||
|
||||
// Compile-time guard: all PlanFeatures values must be boolean or number.
|
||||
@@ -41,6 +54,7 @@ export const defaultPlanFeatures: PlanFeatures = {
|
||||
allowAuth: false,
|
||||
allowContentMode: false,
|
||||
allowStagingPublish: false,
|
||||
allowPublishLogs: false,
|
||||
maxContactEmailsPerProject: 0,
|
||||
maxDomainsAllowedPerUser: 0,
|
||||
maxDailyPublishesPerUser: 10,
|
||||
@@ -106,9 +120,9 @@ export const parsePlansEnv = (raw: string): Map<string, PlanConfig> => {
|
||||
console.error("Invalid PLANS entry (extends must be a string):", item);
|
||||
return [];
|
||||
}
|
||||
const featuresResult = planFeatures
|
||||
.partial()
|
||||
.safeParse("features" in item ? item.features : {});
|
||||
const featuresResult = planFeatureOverrides.safeParse(
|
||||
"features" in item ? item.features : {}
|
||||
);
|
||||
if (!featuresResult.success) {
|
||||
console.error(
|
||||
`Invalid PLANS entry "${item.name}" features:`,
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
CREATE FUNCTION create_production_build_expected(
|
||||
project_id text,
|
||||
deployment text,
|
||||
expected_version integer
|
||||
) RETURNS text AS $$
|
||||
DECLARE
|
||||
new_build_id text;
|
||||
BEGIN
|
||||
INSERT INTO "Build" (
|
||||
version, "lastTransactionId", pages, breakpoints, styles, "styleSources",
|
||||
"styleSourceSelections", props, "dataSources", resources, instances,
|
||||
"marketplaceProduct", "projectSettings", "publishStatus", "projectId", id,
|
||||
deployment
|
||||
)
|
||||
SELECT
|
||||
version, "lastTransactionId", pages, breakpoints, styles, "styleSources",
|
||||
"styleSourceSelections", props, "dataSources", resources, instances,
|
||||
"marketplaceProduct", "projectSettings", "publishStatus", "projectId",
|
||||
extensions.uuid_generate_v4(), create_production_build_expected.deployment
|
||||
FROM "Build"
|
||||
WHERE "projectId" = project_id
|
||||
AND "Build".deployment IS NULL
|
||||
AND version = expected_version
|
||||
RETURNING id INTO new_build_id;
|
||||
|
||||
RETURN new_build_id;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
@@ -68,6 +68,7 @@
|
||||
"@emotion/hash": "^0.9.2",
|
||||
"@modelcontextprotocol/sdk": "^1.10.0",
|
||||
"@webstudio-is/authorization-token": "workspace:*",
|
||||
"@webstudio-is/asset-uploader": "workspace:*",
|
||||
"@webstudio-is/content-engine": "workspace:*",
|
||||
"@webstudio-is/css-data": "workspace:*",
|
||||
"@webstudio-is/css-engine": "workspace:*",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, test, expect, vi } from "vitest";
|
||||
import { beforeEach, describe, test, expect, vi } from "vitest";
|
||||
import {
|
||||
createTestServer,
|
||||
db,
|
||||
@@ -606,6 +606,126 @@ describe("createBuild (msw)", () => {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("createProductionBuild (msw)", () => {
|
||||
beforeEach(() => server.use(db.get("Asset", () => json([]))));
|
||||
test("retries a changed development version before publishing", async () => {
|
||||
const expectedVersions: number[] = [];
|
||||
let readVersion = 0;
|
||||
const createBuild = vi.fn(async ({ request }: { request: Request }) => {
|
||||
const body = (await request.json()) as { expected_version: number };
|
||||
expectedVersions.push(body.expected_version);
|
||||
return json(createBuild.mock.calls.length === 1 ? null : "build-prod");
|
||||
});
|
||||
server.use(
|
||||
ownershipHandler,
|
||||
db.get("Build", () => json([{ ...buildRow, version: readVersion++ }])),
|
||||
db.post("rpc/create_production_build_expected", createBuild)
|
||||
);
|
||||
|
||||
await expect(
|
||||
createProductionBuild(
|
||||
{
|
||||
projectId: "proj-1",
|
||||
deployment: {
|
||||
destination: "static",
|
||||
name: "export.zip",
|
||||
assetsDomain: "project-domain",
|
||||
templates: ["ssg"],
|
||||
},
|
||||
},
|
||||
createContext()
|
||||
)
|
||||
).resolves.toMatchObject({ id: "build-prod" });
|
||||
expect(createBuild).toHaveBeenCalledTimes(2);
|
||||
expect(expectedVersions).toEqual([0, 1]);
|
||||
expect(readVersion).toBe(2);
|
||||
});
|
||||
|
||||
test("stops after two changed development versions without dispatching", async () => {
|
||||
const expectedVersions: number[] = [];
|
||||
let readVersion = 0;
|
||||
const createBuild = vi.fn(async ({ request }: { request: Request }) => {
|
||||
const body = (await request.json()) as { expected_version: number };
|
||||
expectedVersions.push(body.expected_version);
|
||||
return json(null);
|
||||
});
|
||||
server.use(
|
||||
ownershipHandler,
|
||||
db.get("Build", () => json([{ ...buildRow, version: readVersion++ }])),
|
||||
db.post("rpc/create_production_build_expected", createBuild)
|
||||
);
|
||||
|
||||
await expect(
|
||||
createProductionBuild(
|
||||
{
|
||||
projectId: "proj-1",
|
||||
deployment: {
|
||||
destination: "static",
|
||||
name: "export.zip",
|
||||
assetsDomain: "project-domain",
|
||||
templates: ["ssg"],
|
||||
},
|
||||
},
|
||||
createContext()
|
||||
)
|
||||
).rejects.toThrow("The project changed during validation");
|
||||
expect(createBuild).toHaveBeenCalledTimes(2);
|
||||
expect(expectedVersions).toEqual([0, 1]);
|
||||
expect(readVersion).toBe(2);
|
||||
});
|
||||
|
||||
test("blocks when the retried development version fails audit", async () => {
|
||||
let readVersion = 0;
|
||||
const createBuild = vi.fn(() => json(null));
|
||||
server.use(
|
||||
ownershipHandler,
|
||||
db.get("Build", () => {
|
||||
const version = readVersion++;
|
||||
return json([
|
||||
{
|
||||
...buildRow,
|
||||
version,
|
||||
...(version === 0
|
||||
? {}
|
||||
: {
|
||||
props: JSON.stringify([
|
||||
{
|
||||
id: "prop-invalid",
|
||||
instanceId: "body-1",
|
||||
name: "config",
|
||||
type: "json",
|
||||
},
|
||||
]),
|
||||
}),
|
||||
},
|
||||
]);
|
||||
}),
|
||||
db.post("rpc/create_production_build_expected", createBuild)
|
||||
);
|
||||
|
||||
await expect(
|
||||
createProductionBuild(
|
||||
{
|
||||
projectId: "proj-1",
|
||||
deployment: {
|
||||
destination: "static",
|
||||
name: "export.zip",
|
||||
assetsDomain: "project-domain",
|
||||
templates: ["ssg"],
|
||||
},
|
||||
},
|
||||
createContext()
|
||||
)
|
||||
).rejects.toMatchObject({
|
||||
findings: [
|
||||
expect.objectContaining({
|
||||
ruleId: "json-prop-value",
|
||||
severity: "error",
|
||||
}),
|
||||
],
|
||||
});
|
||||
expect(readVersion).toBe(2);
|
||||
expect(createBuild).toHaveBeenCalledOnce();
|
||||
});
|
||||
test.each([
|
||||
{ label: "without custom headers", headers: [], denied: false },
|
||||
{
|
||||
@@ -641,7 +761,9 @@ describe("createProductionBuild (msw)", () => {
|
||||
}
|
||||
return json([buildRow]);
|
||||
}),
|
||||
db.post("rpc/create_production_build", () => json("build-prod")),
|
||||
db.post("rpc/create_production_build_expected", () =>
|
||||
json("build-prod")
|
||||
),
|
||||
db.delete("Build", removeBuild)
|
||||
);
|
||||
const result = createProductionBuild(
|
||||
@@ -657,7 +779,7 @@ describe("createProductionBuild (msw)", () => {
|
||||
);
|
||||
expect(removeBuild).toHaveBeenCalledOnce();
|
||||
} else {
|
||||
await expect(result).resolves.toEqual({ id: "build-prod" });
|
||||
await expect(result).resolves.toMatchObject({ id: "build-prod" });
|
||||
expect(removeBuild).not.toHaveBeenCalled();
|
||||
}
|
||||
}
|
||||
@@ -772,7 +894,7 @@ describe("createProductionBuild (msw)", () => {
|
||||
},
|
||||
])
|
||||
),
|
||||
db.post("rpc/create_production_build", createBuild),
|
||||
db.post("rpc/create_production_build_expected", createBuild),
|
||||
db.delete("Build", removeBuild)
|
||||
);
|
||||
const result = createProductionBuild(
|
||||
@@ -794,7 +916,7 @@ describe("createProductionBuild (msw)", () => {
|
||||
);
|
||||
expect(removeBuild).toHaveBeenCalledOnce();
|
||||
} else {
|
||||
await expect(result).resolves.toEqual({ id: "build-prod" });
|
||||
await expect(result).resolves.toMatchObject({ id: "build-prod" });
|
||||
expect(removeBuild).not.toHaveBeenCalled();
|
||||
}
|
||||
expect(createBuild).toHaveBeenCalledOnce();
|
||||
@@ -860,7 +982,9 @@ describe("createProductionBuild (msw)", () => {
|
||||
// Development settings change before the RPC snapshots them.
|
||||
return json([buildRow]);
|
||||
}),
|
||||
db.post("rpc/create_production_build", () => json("build-prod")),
|
||||
db.post("rpc/create_production_build_expected", () =>
|
||||
json("build-prod")
|
||||
),
|
||||
db.delete("Build", removeBuild)
|
||||
);
|
||||
const result = createProductionBuild(
|
||||
@@ -879,7 +1003,7 @@ describe("createProductionBuild (msw)", () => {
|
||||
);
|
||||
expect(removeBuild).toHaveBeenCalledOnce();
|
||||
} else {
|
||||
await expect(result).resolves.toEqual({ id: "build-prod" });
|
||||
await expect(result).resolves.toMatchObject({ id: "build-prod" });
|
||||
expect(removeBuild).not.toHaveBeenCalled();
|
||||
}
|
||||
expect(readSnapshot).toHaveBeenCalledOnce();
|
||||
@@ -895,7 +1019,7 @@ describe("createProductionBuild (msw)", () => {
|
||||
? json([])
|
||||
: json([buildRow])
|
||||
),
|
||||
db.post("rpc/create_production_build", () => json("build-prod")),
|
||||
db.post("rpc/create_production_build_expected", () => json("build-prod")),
|
||||
db.delete("Build", removeBuild)
|
||||
);
|
||||
await expect(
|
||||
@@ -929,7 +1053,8 @@ describe("createProductionBuild (msw)", () => {
|
||||
},
|
||||
])
|
||||
),
|
||||
db.post("rpc/create_production_build", () => {
|
||||
db.get("Asset", () => json([])),
|
||||
db.post("rpc/create_production_build_expected", () => {
|
||||
didCreateProductionBuild = true;
|
||||
return json("build-prod");
|
||||
})
|
||||
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
type StyleSourceSelection,
|
||||
type StyleDecl,
|
||||
} from "@webstudio-is/sdk";
|
||||
import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";
|
||||
import { loadAssetsByProjectWithClient } from "@webstudio-is/asset-uploader/patch-assets-core.server";
|
||||
import {
|
||||
hasHistoricalFormComponentIdentityVersion,
|
||||
migratePages,
|
||||
@@ -47,7 +49,10 @@ import {
|
||||
parseConfig,
|
||||
serializeData,
|
||||
} from "./build-parser";
|
||||
import { assertBuildIntegrity } from "../build-integrity";
|
||||
import {
|
||||
PrePublishAuditError,
|
||||
runPrePublishAudit,
|
||||
} from "../runtime/pre-publish-audit";
|
||||
|
||||
export {
|
||||
parseConfig,
|
||||
@@ -432,88 +437,114 @@ export const createProductionBuild = async (
|
||||
}
|
||||
}
|
||||
|
||||
const devBuild = await loadDevBuildByProjectId(context, props.projectId);
|
||||
assertBuildIntegrity(devBuild, { messagePrefix: "Cannot publish" });
|
||||
|
||||
const build = await context.postgrest.client.rpc("create_production_build", {
|
||||
project_id: props.projectId,
|
||||
deployment: JSON.stringify(props.deployment),
|
||||
});
|
||||
const buildId = build.data;
|
||||
if (build.error) {
|
||||
throw build.error;
|
||||
}
|
||||
if (buildId === null) {
|
||||
throw Error(`Project ${props.projectId} not found`);
|
||||
}
|
||||
|
||||
if (props.deployment.destination === "static") {
|
||||
return { id: buildId };
|
||||
}
|
||||
|
||||
try {
|
||||
// Check the saved snapshot so concurrent development edits cannot bypass
|
||||
// the Pro requirement. The caller publishes only after this check passes.
|
||||
const snapshot = await context.postgrest.client
|
||||
.from("Build")
|
||||
.select("projectSettings,pages")
|
||||
.eq("id", buildId);
|
||||
if (snapshot.error) {
|
||||
throw snapshot.error;
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
const devBuild = await loadDevBuildByProjectId(context, props.projectId);
|
||||
const projectAssets = await loadAssetsByProjectWithClient(
|
||||
props.projectId,
|
||||
context.postgrest.client
|
||||
);
|
||||
const findings = runPrePublishAudit({
|
||||
pages: devBuild.pages,
|
||||
instances: new Map(devBuild.instances.map((item) => [item.id, item])),
|
||||
props: new Map(devBuild.props.map((item) => [item.id, item])),
|
||||
dataSources: new Map(devBuild.dataSources.map((item) => [item.id, item])),
|
||||
resources: new Map(devBuild.resources.map((item) => [item.id, item])),
|
||||
metas: componentMetas,
|
||||
assets: new Map(projectAssets.map((item) => [item.id, item])),
|
||||
});
|
||||
if (findings.some(({ severity }) => severity === "error")) {
|
||||
throw new PrePublishAuditError(findings);
|
||||
}
|
||||
if (snapshot.data.length !== 1) {
|
||||
throw new Error("Cannot verify published response headers");
|
||||
|
||||
const build = await (
|
||||
context.postgrest.client as unknown as {
|
||||
rpc: (
|
||||
name: string,
|
||||
args: Record<string, unknown>
|
||||
) => Promise<{ data: string | null; error: unknown }>;
|
||||
}
|
||||
).rpc("create_production_build_expected", {
|
||||
project_id: props.projectId,
|
||||
deployment: JSON.stringify(props.deployment),
|
||||
expected_version: devBuild.version,
|
||||
});
|
||||
if (build.error) {
|
||||
throw build.error;
|
||||
}
|
||||
const savedBuild = snapshot.data[0];
|
||||
const settings =
|
||||
savedBuild.projectSettings === undefined ||
|
||||
savedBuild.projectSettings === null
|
||||
? createProjectSettingsFromPages(
|
||||
migratePages(parseConfig<unknown>(savedBuild.pages))
|
||||
if (build.data !== null) {
|
||||
const savedBuildId = build.data;
|
||||
if (props.deployment.destination === "static") {
|
||||
return { id: savedBuildId, auditFindings: findings };
|
||||
}
|
||||
|
||||
try {
|
||||
// Check the saved snapshot so concurrent development edits cannot bypass
|
||||
// the Pro requirement. The caller publishes only after this check passes.
|
||||
const snapshot = await context.postgrest.client
|
||||
.from("Build")
|
||||
.select("projectSettings,pages")
|
||||
.eq("id", savedBuildId);
|
||||
if (snapshot.error) {
|
||||
throw snapshot.error;
|
||||
}
|
||||
if (snapshot.data.length !== 1) {
|
||||
throw new Error("Cannot verify published response headers");
|
||||
}
|
||||
const savedBuild = snapshot.data[0];
|
||||
const settings =
|
||||
savedBuild.projectSettings === undefined ||
|
||||
savedBuild.projectSettings === null
|
||||
? createProjectSettingsFromPages(
|
||||
migratePages(parseConfig<unknown>(savedBuild.pages))
|
||||
)
|
||||
: parseProjectSettings(
|
||||
parseConfig<unknown>(savedBuild.projectSettings)
|
||||
);
|
||||
if (!hasCustomResponseHeaders(settings.meta.customHeaders)) {
|
||||
return { id: savedBuildId, auditFindings: findings };
|
||||
}
|
||||
// Use the saved staging domain, not caller-supplied deployment metadata.
|
||||
const project = await context.postgrest.client
|
||||
.from("Project")
|
||||
.select("domain")
|
||||
.eq("id", props.projectId)
|
||||
.single();
|
||||
if (project.error) {
|
||||
throw project.error;
|
||||
}
|
||||
if (
|
||||
props.deployment.domains.every(
|
||||
(domain) => domain === project.data.domain
|
||||
)
|
||||
: parseProjectSettings(
|
||||
parseConfig<unknown>(savedBuild.projectSettings)
|
||||
) {
|
||||
return { id: savedBuildId, auditFindings: findings };
|
||||
}
|
||||
const plan = await getProjectPlanFeatures(props.projectId, context);
|
||||
if (plan.allowDynamicData !== true) {
|
||||
throw new AuthorizationError(
|
||||
"Custom headers are a Pro feature. Upgrade to Pro or reset the response headers to defaults to publish to custom domains. You can still publish to staging."
|
||||
);
|
||||
if (!hasCustomResponseHeaders(settings.meta.customHeaders)) {
|
||||
return { id: buildId };
|
||||
}
|
||||
// Use the saved staging domain, not caller-supplied deployment metadata.
|
||||
const project = await context.postgrest.client
|
||||
.from("Project")
|
||||
.select("domain")
|
||||
.eq("id", props.projectId)
|
||||
.single();
|
||||
if (project.error) {
|
||||
throw project.error;
|
||||
}
|
||||
if (
|
||||
props.deployment.domains.every((domain) => domain === project.data.domain)
|
||||
) {
|
||||
return { id: buildId };
|
||||
}
|
||||
const plan = await getProjectPlanFeatures(props.projectId, context);
|
||||
if (plan.allowDynamicData !== true) {
|
||||
throw new AuthorizationError(
|
||||
"Custom headers are a Pro feature. Upgrade to Pro or reset the response headers to defaults to publish to custom domains. You can still publish to staging."
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
const cleanup = await context.postgrest.client
|
||||
.from("Build")
|
||||
.delete()
|
||||
.eq("id", buildId);
|
||||
if (cleanup.error) {
|
||||
throw new AggregateError(
|
||||
[error, cleanup.error],
|
||||
"Could not verify response headers or remove the unpublished build"
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
const cleanup = await context.postgrest.client
|
||||
.from("Build")
|
||||
.delete()
|
||||
.eq("id", savedBuildId);
|
||||
if (cleanup.error) {
|
||||
throw new AggregateError(
|
||||
[error, cleanup.error],
|
||||
"Could not verify response headers or remove the unpublished build"
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
return {
|
||||
id: buildId,
|
||||
};
|
||||
return { id: savedBuildId, auditFindings: findings };
|
||||
}
|
||||
}
|
||||
throw Error(
|
||||
"The project changed during validation. Review the latest audit and publish again."
|
||||
);
|
||||
};
|
||||
|
||||
export const __testing__ = { canTokenPublishDeployment };
|
||||
@@ -1323,6 +1323,39 @@ describe("project session mcp adapter", () => {
|
||||
expect(tool?.inputSchema.properties).not.toHaveProperty("runtime");
|
||||
});
|
||||
|
||||
test("keeps discriminated publish inputs valid in the MCP tool schema", () => {
|
||||
const [tool] = listProjectSessionMcpTools([
|
||||
publicOperation({
|
||||
command: "publish",
|
||||
id: "build.publish",
|
||||
description: "Publish a site or static export",
|
||||
localCapable: false,
|
||||
serverOnly: true,
|
||||
inputSchema: getTestInputSchema(
|
||||
z.discriminatedUnion("target", [
|
||||
z.object({
|
||||
target: z.literal("production"),
|
||||
domains: z.array(z.string()),
|
||||
}),
|
||||
z.object({
|
||||
target: z.literal("static"),
|
||||
templates: z.array(z.string()),
|
||||
}),
|
||||
])
|
||||
),
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(tool?.inputSchema).toMatchObject({
|
||||
oneOf: [
|
||||
{ properties: { target: { const: "production" } } },
|
||||
{ properties: { target: { const: "static" } } },
|
||||
],
|
||||
required: ["target"],
|
||||
additionalProperties: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("defers oversized input schemas until focused discovery", async () => {
|
||||
const description = "x".repeat(25_000);
|
||||
const operation = publicOperation({
|
||||
|
||||
@@ -683,9 +683,16 @@ const getOperationInputSchema = (
|
||||
operation.inputSchema
|
||||
);
|
||||
const properties = getInputJsonSchemaProperties(operation.inputSchema);
|
||||
const hasComposedBranches =
|
||||
operation.inputSchema.oneOf !== undefined ||
|
||||
operation.inputSchema.anyOf !== undefined ||
|
||||
operation.inputSchema.allOf !== undefined;
|
||||
const additionalProperties =
|
||||
operation.inputSchema.additionalProperties ??
|
||||
(properties === undefined || Object.keys(properties).length === 0);
|
||||
hasComposedBranches &&
|
||||
Object.keys(operation.inputSchema.properties ?? {}).length === 0
|
||||
? true
|
||||
: (operation.inputSchema.additionalProperties ??
|
||||
(properties === undefined || Object.keys(properties).length === 0));
|
||||
return {
|
||||
...emptyInputSchema,
|
||||
...operation.inputSchema,
|
||||
@@ -2010,7 +2017,10 @@ const getMcpOperationInputSchema = (
|
||||
const properties = getInputJsonSchemaProperties(schema);
|
||||
if (
|
||||
schema.additionalProperties === true &&
|
||||
(properties === undefined || Object.keys(properties).length === 0)
|
||||
(properties === undefined || Object.keys(properties).length === 0) &&
|
||||
schema.oneOf === undefined &&
|
||||
schema.anyOf === undefined &&
|
||||
schema.allOf === undefined
|
||||
) {
|
||||
schema = { ...schema, additionalProperties: false };
|
||||
}
|
||||
@@ -4659,6 +4669,7 @@ const capabilityAreas = [
|
||||
"publish",
|
||||
"list-publishes",
|
||||
"get-publish-job",
|
||||
"get-publish-log",
|
||||
"unpublish",
|
||||
"list-domains",
|
||||
"create-domain",
|
||||
|
||||
@@ -36,6 +36,28 @@ const XmlNode = createTemplateComponentFixture("XmlNode");
|
||||
|
||||
const defaultMetas = componentMetas;
|
||||
|
||||
test("keeps matcher validation short-circuited by default", () => {
|
||||
const { instances, props } = renderData(
|
||||
<ws.element ws:tag="body" ws:id="body">
|
||||
<ws.element ws:tag="p">
|
||||
<ws.element ws:tag="h2" ws:id="first" />
|
||||
<ws.element ws:tag="h2" ws:id="second" />
|
||||
</ws.element>
|
||||
</ws.element>
|
||||
);
|
||||
const errors: string[] = [];
|
||||
expect(
|
||||
isTreeSatisfyingContentModel({
|
||||
instances,
|
||||
props,
|
||||
metas: defaultMetas,
|
||||
instanceSelector: ["body"],
|
||||
onError: (_message, selector) => errors.push(selector[0]),
|
||||
})
|
||||
).toBe(false);
|
||||
expect(errors).toEqual(["first"]);
|
||||
});
|
||||
|
||||
test.each(["body", "templates", "list-item"])(
|
||||
"validates template HTML independently when starting at %s",
|
||||
(start) => {
|
||||
|
||||
@@ -444,6 +444,7 @@ export const isTreeSatisfyingContentModel = ({
|
||||
instanceSelector,
|
||||
htmlTagsByInstanceId = getHtmlTagsFromProps(props),
|
||||
onError,
|
||||
collectAllErrors = false,
|
||||
_allowedCategories: allowedCategories,
|
||||
_parentTag: parentTag,
|
||||
_allowedAncestorCategories: allowedAncestorCategories,
|
||||
@@ -455,6 +456,7 @@ export const isTreeSatisfyingContentModel = ({
|
||||
instanceSelector: InstanceSelector;
|
||||
htmlTagsByInstanceId?: HtmlTagsByInstanceId;
|
||||
onError?: (message: string, instanceSelector: InstanceSelector) => void;
|
||||
collectAllErrors?: boolean;
|
||||
_allowedCategories?: string[];
|
||||
_parentTag?: string;
|
||||
_allowedAncestorCategories?: string[];
|
||||
@@ -578,13 +580,17 @@ export const isTreeSatisfyingContentModel = ({
|
||||
}
|
||||
for (const child of instance.children) {
|
||||
if (child.type === "id") {
|
||||
isSatisfying &&= isTreeSatisfyingContentModel({
|
||||
if (collectAllErrors === false && isSatisfying === false) {
|
||||
continue;
|
||||
}
|
||||
const childSatisfies = isTreeSatisfyingContentModel({
|
||||
instances,
|
||||
props,
|
||||
metas,
|
||||
htmlTagsByInstanceId,
|
||||
instanceSelector: [child.value, ...instanceSelector],
|
||||
onError,
|
||||
collectAllErrors,
|
||||
_allowedCategories:
|
||||
instance.component === blockTemplateComponent
|
||||
? undefined
|
||||
@@ -593,6 +599,7 @@ export const isTreeSatisfyingContentModel = ({
|
||||
_allowedParentCategories: allowedParentCategories,
|
||||
_allowedAncestorCategories: allowedAncestorCategories,
|
||||
});
|
||||
isSatisfying = isSatisfying && childSatisfies;
|
||||
}
|
||||
}
|
||||
return isSatisfying;
|
||||
|
||||
@@ -16,9 +16,44 @@ import {
|
||||
} from "@webstudio-is/template";
|
||||
import {
|
||||
formatPrePublishAuditFinding,
|
||||
limitPrePublishAuditFindings,
|
||||
runPrePublishAudit,
|
||||
} from "./pre-publish-audit";
|
||||
|
||||
test("keeps the content warning within the shared 500-finding limit", () => {
|
||||
const contentWarning = {
|
||||
ruleId: "content-database-truncated",
|
||||
severity: "warning" as const,
|
||||
message: "Published content is incomplete.",
|
||||
location: {},
|
||||
};
|
||||
const existingWarnings = Array.from({ length: 499 }, (_, index) => ({
|
||||
ruleId: `warning-${index}`,
|
||||
severity: "warning" as const,
|
||||
message: "Existing warning",
|
||||
location: {},
|
||||
}));
|
||||
const previousTruncation = {
|
||||
ruleId: "audit-truncated",
|
||||
severity: "warning" as const,
|
||||
message: "Some earlier audit findings were omitted.",
|
||||
location: {},
|
||||
};
|
||||
|
||||
const findings = limitPrePublishAuditFindings([
|
||||
contentWarning,
|
||||
...existingWarnings,
|
||||
previousTruncation,
|
||||
]);
|
||||
|
||||
expect(findings).toHaveLength(500);
|
||||
expect(findings).toContainEqual(contentWarning);
|
||||
expect(findings).toContainEqual(previousTruncation);
|
||||
expect(findings.at(-1)?.ruleId).toBe("audit-truncated");
|
||||
expect(
|
||||
findings.filter(({ ruleId }) => ruleId === "audit-truncated")
|
||||
).toHaveLength(2);
|
||||
});
|
||||
const Body = createTemplateComponentFixture("Body");
|
||||
const Box = createTemplateComponentFixture("Box");
|
||||
const CodeText = createTemplateComponentFixture("CodeText");
|
||||
@@ -100,6 +135,53 @@ test("warns without blocking legacy invalid HTML", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("reports invalid sibling and descendant HTML on each published page, not drafts", () => {
|
||||
const { instances, props } = renderData(
|
||||
<>
|
||||
<Body ws:id="body">
|
||||
<Paragraph>
|
||||
<Heading ws:id="first" ws:tag="h2">
|
||||
<Heading ws:id="nested" ws:tag="h3">
|
||||
Nested
|
||||
</Heading>
|
||||
</Heading>
|
||||
<Heading ws:id="second" ws:tag="h2">
|
||||
Second
|
||||
</Heading>
|
||||
</Paragraph>
|
||||
</Body>
|
||||
<Body ws:id="draft-body">
|
||||
<Paragraph>
|
||||
<Heading ws:id="draft-heading" ws:tag="h2">
|
||||
Draft
|
||||
</Heading>
|
||||
</Paragraph>
|
||||
</Body>
|
||||
</>
|
||||
);
|
||||
const pages = createPages(marketEdgePage);
|
||||
pages.pages.set("draft", {
|
||||
...marketEdgePage,
|
||||
id: "draft",
|
||||
name: "Draft",
|
||||
path: "/draft",
|
||||
rootInstanceId: "draft-body",
|
||||
isDraft: true,
|
||||
});
|
||||
const findings = runAudit({ pages, instances, props }).filter(
|
||||
({ ruleId }) => ruleId === "html-content-model"
|
||||
);
|
||||
|
||||
expect(findings.map(({ location }) => location.instanceId)).toEqual([
|
||||
"first",
|
||||
"nested",
|
||||
"second",
|
||||
]);
|
||||
expect(
|
||||
findings.every(({ location }) => location.pagePath === "/marketedge")
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("warns for nested and shared Webhook Forms on every published page", () => {
|
||||
const pages = createPages(marketEdgePage);
|
||||
pages.pages.set("other", {
|
||||
|
||||
@@ -32,6 +32,21 @@ export type PrePublishAuditFinding = {
|
||||
};
|
||||
};
|
||||
|
||||
export class PrePublishAuditError extends Error {
|
||||
findings: PrePublishAuditFinding[];
|
||||
|
||||
constructor(findings: PrePublishAuditFinding[]) {
|
||||
const firstError = findings.find(({ severity }) => severity === "error");
|
||||
super(
|
||||
firstError === undefined
|
||||
? "Pre-publish audit failed."
|
||||
: formatPrePublishAuditFinding(firstError)
|
||||
);
|
||||
this.name = "PrePublishAuditError";
|
||||
this.findings = findings;
|
||||
}
|
||||
}
|
||||
|
||||
type PrePublishAuditContext = {
|
||||
pages: Pages;
|
||||
instances: Instances;
|
||||
@@ -66,32 +81,26 @@ const checkHtmlContentModel: PrePublishAuditCheck = ({
|
||||
}
|
||||
|
||||
for (const page of getPublishablePages(pages)) {
|
||||
let message: string | undefined;
|
||||
let instanceId: string | undefined;
|
||||
const isValid = isTreeSatisfyingContentModel({
|
||||
isTreeSatisfyingContentModel({
|
||||
instances,
|
||||
props,
|
||||
metas: auditMetas,
|
||||
instanceSelector: [page.rootInstanceId],
|
||||
collectAllErrors: true,
|
||||
onError: (error, instanceSelector) => {
|
||||
message ??= error;
|
||||
instanceId ??= instanceSelector[0];
|
||||
findings.push({
|
||||
ruleId: "html-content-model",
|
||||
severity: "warning",
|
||||
message: error,
|
||||
location: {
|
||||
pageId: page.id,
|
||||
pageName: page.name,
|
||||
pagePath: getPagePath(page.id, pages) || "/",
|
||||
instanceId: instanceSelector[0],
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
if (isValid === false) {
|
||||
findings.push({
|
||||
ruleId: "html-content-model",
|
||||
severity: "warning",
|
||||
message: message ?? "The page contains invalid element nesting.",
|
||||
location: {
|
||||
pageId: page.id,
|
||||
pageName: page.name,
|
||||
pagePath: getPagePath(page.id, pages) || "/",
|
||||
instanceId,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return findings;
|
||||
@@ -206,6 +215,8 @@ const prePublishAuditChecks: PrePublishAuditCheck[] = [
|
||||
checkBuildIntegrity,
|
||||
];
|
||||
|
||||
const maxAuditFindings = 500;
|
||||
|
||||
export const runPrePublishAudit = ({
|
||||
pages,
|
||||
...context
|
||||
@@ -224,7 +235,47 @@ export const runPrePublishAudit = ({
|
||||
];
|
||||
}
|
||||
|
||||
return prePublishAuditChecks.flatMap((check) => check({ ...context, pages }));
|
||||
const findings: PrePublishAuditFinding[] = [];
|
||||
for (const check of prePublishAuditChecks) {
|
||||
try {
|
||||
findings.push(...check({ ...context, pages }));
|
||||
} catch {
|
||||
findings.push({
|
||||
ruleId: "validation-incomplete",
|
||||
severity: "error",
|
||||
message:
|
||||
"Part of the pre-publish audit could not complete. Review the other findings and try again.",
|
||||
location: {},
|
||||
});
|
||||
}
|
||||
}
|
||||
return limitPrePublishAuditFindings(findings);
|
||||
};
|
||||
|
||||
export const limitPrePublishAuditFindings = (
|
||||
findings: PrePublishAuditFinding[]
|
||||
): PrePublishAuditFinding[] => {
|
||||
if (findings.length <= maxAuditFindings) {
|
||||
return findings;
|
||||
}
|
||||
const omittedCount = findings.length - maxAuditFindings + 1;
|
||||
const prioritizedFindings = [
|
||||
...findings.filter(({ severity }) => severity === "error"),
|
||||
...findings.filter(({ ruleId }) => ruleId === "audit-truncated"),
|
||||
...findings.filter(
|
||||
({ severity, ruleId }) =>
|
||||
severity !== "error" && ruleId !== "audit-truncated"
|
||||
),
|
||||
];
|
||||
return [
|
||||
...prioritizedFindings.slice(0, maxAuditFindings - 1),
|
||||
{
|
||||
ruleId: "audit-truncated",
|
||||
severity: "warning",
|
||||
message: `${omittedCount} additional audit findings were omitted from this report.`,
|
||||
location: {},
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
export const formatPrePublishAuditFinding = (
|
||||
|
||||
+81
-17
@@ -297,6 +297,7 @@ export const serverOnlyRouterOperationMetadata = {
|
||||
"formId",
|
||||
"requestId",
|
||||
"jobId",
|
||||
"buildId",
|
||||
"domainId",
|
||||
"blockInstanceId",
|
||||
"assetId",
|
||||
@@ -491,6 +492,7 @@ export const serverOnlyRouterOperationMetadata = {
|
||||
"formId",
|
||||
"requestId",
|
||||
"jobId",
|
||||
"buildId",
|
||||
"domainId",
|
||||
"blockInstanceId",
|
||||
"assetId",
|
||||
@@ -1747,26 +1749,58 @@ export const serverOnlyRouterOperationMetadata = {
|
||||
client: "publish",
|
||||
permit: "edit",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
target: {
|
||||
type: "string",
|
||||
enum: ["staging", "production"],
|
||||
},
|
||||
domains: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "string",
|
||||
oneOf: [
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
target: {
|
||||
type: "string",
|
||||
enum: ["staging", "production"],
|
||||
},
|
||||
domains: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
message: {
|
||||
type: "string",
|
||||
},
|
||||
idempotencyKey: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["target"],
|
||||
},
|
||||
message: {
|
||||
type: "string",
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
target: {
|
||||
type: "string",
|
||||
const: "static",
|
||||
},
|
||||
templates: {
|
||||
default: ["ssg"],
|
||||
type: "array",
|
||||
items: {
|
||||
type: "string",
|
||||
enum: [
|
||||
"docker",
|
||||
"vercel",
|
||||
"netlify",
|
||||
"ssg",
|
||||
"ssg-netlify",
|
||||
"ssg-vercel",
|
||||
],
|
||||
},
|
||||
},
|
||||
idempotencyKey: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["target"],
|
||||
},
|
||||
idempotencyKey: {
|
||||
type: "string",
|
||||
},
|
||||
},
|
||||
required: ["target"],
|
||||
],
|
||||
},
|
||||
},
|
||||
"publish.getJob": {
|
||||
@@ -1782,10 +1816,40 @@ export const serverOnlyRouterOperationMetadata = {
|
||||
jobId: {
|
||||
type: "string",
|
||||
},
|
||||
logHandle: {
|
||||
type: "string",
|
||||
maxLength: 2048,
|
||||
},
|
||||
},
|
||||
required: ["jobId"],
|
||||
},
|
||||
},
|
||||
"publish.getLog": {
|
||||
id: "publish.getLog",
|
||||
command: "get-publish-log",
|
||||
method: "query",
|
||||
path: "api.publish.getLog",
|
||||
client: "getPublishLog",
|
||||
permit: "view",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: {
|
||||
buildId: {
|
||||
type: "string",
|
||||
},
|
||||
logHandle: {
|
||||
type: "string",
|
||||
maxLength: 2048,
|
||||
},
|
||||
cursor: {
|
||||
type: "integer",
|
||||
minimum: -9007199254740991,
|
||||
maximum: 9007199254740991,
|
||||
},
|
||||
},
|
||||
required: ["buildId", "logHandle"],
|
||||
},
|
||||
},
|
||||
"publish.unpublish": {
|
||||
id: "publish.unpublish",
|
||||
command: "unpublish",
|
||||
|
||||
@@ -753,16 +753,18 @@ const curatedPublicApiOperationDocumentation = [
|
||||
{
|
||||
command: "publish",
|
||||
description:
|
||||
"Publish the configured project to staging or production. Uses the project domain by default and, for production, active verified custom domains. If local development cannot contact the deployment backend, the JSON response includes warning while still returning the local publish job id.",
|
||||
"Publish the configured project to staging or production, or prepare a static export. Uses the project domain by default and, for production, active verified custom domains. If local development cannot contact the deployment backend, the JSON response includes warning while still returning the local publish job id.",
|
||||
requiredOptions: ["target", "json"],
|
||||
examples: [
|
||||
"webstudio publish --target production --json",
|
||||
"webstudio publish --target production --domain example.com --json",
|
||||
"webstudio publish --target static --template ssg --json",
|
||||
],
|
||||
},
|
||||
{
|
||||
command: "list-publishes",
|
||||
description: "List production publish builds for the configured project",
|
||||
description:
|
||||
"List recorded staging and production publishes for the configured project. Blocked audits and static exports do not appear in this list.",
|
||||
examples: ["webstudio list-publishes --json"],
|
||||
},
|
||||
{
|
||||
@@ -772,6 +774,15 @@ const curatedPublicApiOperationDocumentation = [
|
||||
requiredOptions: ["job", "json"],
|
||||
examples: ["webstudio get-publish-job --job build-id --json"],
|
||||
},
|
||||
{
|
||||
command: "get-publish-log",
|
||||
description:
|
||||
"Read a build's publish log using the handle from this session. Full log pages require a Pro or Team plan and are not retained by Webstudio.",
|
||||
requiredOptions: ["build-id", "log-handle", "json"],
|
||||
examples: [
|
||||
"webstudio publish log --build-id build-id --log-handle signed-handle --json",
|
||||
],
|
||||
},
|
||||
{
|
||||
command: "unpublish",
|
||||
description:
|
||||
|
||||
@@ -23,6 +23,11 @@
|
||||
"vitest": "^3.1.2"
|
||||
},
|
||||
"exports": {
|
||||
"./deployment-contract": {
|
||||
"webstudio": "./src/shared/deployment-contract.ts",
|
||||
"types": "./src/shared/deployment-contract.ts",
|
||||
"import": "./src/shared/deployment-contract.ts"
|
||||
},
|
||||
"./api-compatibility": {
|
||||
"webstudio": "./src/api-compatibility.ts",
|
||||
"types": "./src/api-compatibility.ts",
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { expect, test } from "vitest";
|
||||
import {
|
||||
publishInput,
|
||||
publishLogInput,
|
||||
publishLogOutput,
|
||||
} from "@webstudio-is/trpc-interface/deployment-contract";
|
||||
|
||||
test("the public deployment contract validates publish and status-only log requests", () => {
|
||||
expect(
|
||||
publishInput.parse({
|
||||
buildId: "build-1",
|
||||
builderOrigin: "https://webstudio.is",
|
||||
destination: "static",
|
||||
branchName: "main",
|
||||
logProjectName: "Project",
|
||||
}).destination
|
||||
).toBe("static");
|
||||
expect(
|
||||
publishLogInput.parse({
|
||||
buildId: "build-1",
|
||||
logHandle: "signed-handle",
|
||||
includeLog: false,
|
||||
}).includeLog
|
||||
).toBe(false);
|
||||
expect(
|
||||
publishLogOutput.parse({
|
||||
availability: "available",
|
||||
outcome: "failed",
|
||||
logAvailability: "unavailable",
|
||||
code: "cancelled",
|
||||
}).availability
|
||||
).toBe("available");
|
||||
expect(
|
||||
publishLogInput.safeParse({
|
||||
buildId: "build-1",
|
||||
logHandle: "signed-handle",
|
||||
includeLog: "false",
|
||||
}).success
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import { z } from "zod";
|
||||
|
||||
export const publishInput = z.object({
|
||||
// used to load build data from the builder with build.loadProjectBundleByBuildId
|
||||
buildId: z.string(),
|
||||
builderOrigin: z.string(),
|
||||
githubSha: z.string().optional(),
|
||||
destination: z.enum(["saas", "static"]),
|
||||
branchName: z.string(),
|
||||
logProjectName: z.string(),
|
||||
});
|
||||
|
||||
export const unpublishInput = z.object({ domain: z.string() });
|
||||
|
||||
export const output = z.discriminatedUnion("success", [
|
||||
z.object({
|
||||
success: z.literal(true),
|
||||
logHandle: z.string().optional(),
|
||||
}),
|
||||
z.object({
|
||||
success: z.literal(false),
|
||||
error: z.string(),
|
||||
dispatchUncertain: z.boolean().optional(),
|
||||
}),
|
||||
]);
|
||||
|
||||
export const publishLogInput = z.object({
|
||||
buildId: z.string(),
|
||||
logHandle: z.string().max(2048),
|
||||
cursor: z.number().int().nonnegative().safe().optional(),
|
||||
includeLog: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export const publishLogOutput = z.discriminatedUnion("availability", [
|
||||
z.object({ availability: z.literal("pending") }),
|
||||
z.object({ availability: z.literal("unavailable") }),
|
||||
z.object({
|
||||
availability: z.literal("available"),
|
||||
outcome: z.enum(["succeeded", "failed"]),
|
||||
logAvailability: z.enum(["available", "unavailable"]),
|
||||
startedAt: z.string().datetime().optional(),
|
||||
completedAt: z.string().datetime().optional(),
|
||||
code: z
|
||||
.enum([
|
||||
"failure",
|
||||
"cancelled",
|
||||
"timed_out",
|
||||
"action_required",
|
||||
"startup_failure",
|
||||
"stale",
|
||||
"unknown",
|
||||
])
|
||||
.optional(),
|
||||
failedStage: z
|
||||
.enum([
|
||||
"setup",
|
||||
"sync",
|
||||
"project-build",
|
||||
"application-build",
|
||||
"worker-build",
|
||||
"assets",
|
||||
"deploy",
|
||||
"finalize",
|
||||
])
|
||||
.optional(),
|
||||
log: z
|
||||
.object({
|
||||
encoding: z.literal("base64url"),
|
||||
chunk: z.string().max(400_000),
|
||||
complete: z.boolean(),
|
||||
nextCursor: z.number().int().nonnegative().safe().optional(),
|
||||
issues: z
|
||||
.array(
|
||||
z.object({
|
||||
severity: z.enum(["error", "warning"]),
|
||||
message: z.string().max(1024),
|
||||
})
|
||||
)
|
||||
.max(20)
|
||||
.optional(),
|
||||
issuesOmitted: z.number().int().nonnegative().optional(),
|
||||
})
|
||||
.optional(),
|
||||
}),
|
||||
]);
|
||||
@@ -1,33 +1,11 @@
|
||||
import { z } from "zod";
|
||||
import { router, procedure } from "./trpc";
|
||||
|
||||
// Has corresponding type in saas
|
||||
export const publishInput = z.object({
|
||||
// used to load build data from the builder with build.loadProjectBundleByBuildId
|
||||
buildId: z.string(),
|
||||
builderOrigin: z.string(),
|
||||
githubSha: z.string().optional(),
|
||||
|
||||
destination: z.enum(["saas", "static"]),
|
||||
// preview support
|
||||
branchName: z.string(),
|
||||
// action log helper (not used for deployment, but for action logs readablity)
|
||||
logProjectName: z.string(),
|
||||
});
|
||||
|
||||
export const unpublishInput = z.object({
|
||||
domain: z.string(),
|
||||
});
|
||||
|
||||
export const output = z.discriminatedUnion("success", [
|
||||
z.object({
|
||||
success: z.literal(true),
|
||||
}),
|
||||
z.object({
|
||||
success: z.literal(false),
|
||||
error: z.string(),
|
||||
}),
|
||||
]);
|
||||
import {
|
||||
publishInput,
|
||||
unpublishInput,
|
||||
output,
|
||||
publishLogInput,
|
||||
publishLogOutput,
|
||||
} from "./deployment-contract";
|
||||
|
||||
/**
|
||||
* This is the ContentManagementService. It is currently used to publish content to a custom domain.
|
||||
@@ -52,4 +30,8 @@ export const deploymentRouter = router({
|
||||
error: "NOT_IMPLEMENTED",
|
||||
};
|
||||
}),
|
||||
getPublishLog: procedure
|
||||
.input(publishLogInput)
|
||||
.output(publishLogOutput)
|
||||
.query(() => ({ availability: "unavailable" as const })),
|
||||
});
|
||||
Generated
+6
@@ -479,6 +479,9 @@ importers:
|
||||
specifier: ^5.0.0
|
||||
version: 5.0.0(zod@4.4.3)
|
||||
devDependencies:
|
||||
'@mswjs/interceptors':
|
||||
specifier: ^0.41.2
|
||||
version: 0.41.3
|
||||
'@playwright/test':
|
||||
specifier: 1.50.1
|
||||
version: 1.50.1
|
||||
@@ -2296,6 +2299,9 @@ importers:
|
||||
'@modelcontextprotocol/sdk':
|
||||
specifier: ^1.10.0
|
||||
version: 1.10.0
|
||||
'@webstudio-is/asset-uploader':
|
||||
specifier: workspace:*
|
||||
version: link:../asset-uploader
|
||||
'@webstudio-is/authorization-token':
|
||||
specifier: workspace:*
|
||||
version: link:../authorization-token
|
||||
|
||||
Reference in new issue
Block a user