mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-01 21:05:42 +09:00
feat: show successful publish and export reports
This commit is contained in:
1 parent
2418f9005a
commit
d340a52252
13 files changed
+590
-145
No files matched your search
+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", () => {
|
||||
@@ -71,6 +71,14 @@ beforeAll(async () => {
|
||||
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 } })
|
||||
@@ -121,6 +129,23 @@ const mount = async (dialog: "publish" | "export" = "publish") => {
|
||||
);
|
||||
};
|
||||
|
||||
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 = {
|
||||
@@ -154,6 +179,24 @@ test("a successful site runner finishes the current publish and retains its repo
|
||||
"/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:"]'
|
||||
)!;
|
||||
@@ -174,6 +217,107 @@ test("a successful site runner finishes the current publish and retains its repo
|
||||
).toContain("Published");
|
||||
});
|
||||
|
||||
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();
|
||||
@@ -211,23 +355,7 @@ afterAll(() => {
|
||||
|
||||
test("static export reaches the server without waiting for diagnostics", async () => {
|
||||
await mount("export");
|
||||
|
||||
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();
|
||||
});
|
||||
await selectStaticDestination();
|
||||
const buildButton = Array.from(
|
||||
document.body.querySelectorAll<HTMLButtonElement>("button")
|
||||
).find(
|
||||
|
||||
@@ -121,6 +121,10 @@ beforeAll(async () => {
|
||||
mdxErrors: [],
|
||||
mdxOmissions: [],
|
||||
}),
|
||||
"api.publish.validate": () => ({
|
||||
diagnostics: { mdxErrors: [], mdxOmissions: [] },
|
||||
cssValid: true,
|
||||
}),
|
||||
});
|
||||
interceptor.start();
|
||||
PublishButton = (await import("./publish")).PublishButton;
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
});
|
||||
@@ -26,33 +26,72 @@ export const createTrpcInterceptor = (
|
||||
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 input = JSON.parse(
|
||||
const parsedInput: unknown = JSON.parse(
|
||||
request.method === "GET"
|
||||
? (url.searchParams.get("input") ?? "{}")
|
||||
: await request.clone().text()
|
||||
);
|
||||
const routes = url.pathname.slice("/trpc/".length).split(",");
|
||||
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 handler = handlers[route];
|
||||
if (handler === undefined) {
|
||||
throw new Error(`Unexpected request: ${route}`);
|
||||
}
|
||||
const value = input[String(index)];
|
||||
onRequest?.(route, value);
|
||||
return { result: { data: await handler(value) } };
|
||||
return 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), {
|
||||
headers: { "Content-Type": "application/json" },
|
||||
})
|
||||
new Response(
|
||||
JSON.stringify(results.map((data) => ({ result: { data } }))),
|
||||
{
|
||||
headers: { "Content-Type": "application/json" },
|
||||
}
|
||||
)
|
||||
);
|
||||
} catch (error) {
|
||||
controller.errorWith(error);
|
||||
@@ -60,6 +99,11 @@ export const createTrpcInterceptor = (
|
||||
});
|
||||
return {
|
||||
start: () => interceptor.apply(),
|
||||
stop: () => interceptor.dispose(),
|
||||
stop: () => {
|
||||
interceptor.dispose();
|
||||
if (unexpectedRequests.length > 0) {
|
||||
throw new Error(unexpectedRequests.join("\n"));
|
||||
}
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -128,6 +128,37 @@ type PublishUiState = {
|
||||
exportStatic: (templates: readonly Templates[]) => void;
|
||||
};
|
||||
|
||||
type StaticPublishUiState = Pick<
|
||||
PublishUiState,
|
||||
| "isPublishing"
|
||||
| "publishes"
|
||||
| "staticFailureFinding"
|
||||
| "openStaticReport"
|
||||
| "exportStatic"
|
||||
>;
|
||||
|
||||
const PublishSuccessBanner = ({
|
||||
message,
|
||||
onOpen,
|
||||
}: {
|
||||
message: string;
|
||||
onOpen: () => void;
|
||||
}) => (
|
||||
<PanelBanner variant="success" role="status">
|
||||
<Flex align="center" justify="between" gap={2}>
|
||||
<Text css={{ flex: 1, minWidth: 0 }}>{message}</Text>
|
||||
<Button
|
||||
type="button"
|
||||
color="ghost"
|
||||
css={{ flexShrink: 0 }}
|
||||
onClick={onOpen}
|
||||
>
|
||||
See logs
|
||||
</Button>
|
||||
</Flex>
|
||||
</PanelBanner>
|
||||
);
|
||||
|
||||
type ChangeProjectDomainProps = {
|
||||
project: Project;
|
||||
refresh: () => Promise<void>;
|
||||
@@ -473,7 +504,8 @@ const Publish = ({
|
||||
|
||||
const getForm = () => buttonRef.current?.closest("form");
|
||||
const findings = flow.siteFindings;
|
||||
const hasSessionPublish = publishes.some(({ target }) => target === "site");
|
||||
const latestSitePublish = publishes.find(({ target }) => target === "site");
|
||||
const hasSessionPublish = latestSitePublish !== undefined;
|
||||
|
||||
return (
|
||||
<Flex gap={2} shrink={false} direction={"column"}>
|
||||
@@ -502,6 +534,11 @@ const Publish = ({
|
||||
</Button>
|
||||
</Flex>
|
||||
</PanelBanner>
|
||||
) : latestSitePublish?.status === "success" && !isPublishInProgress ? (
|
||||
<PublishSuccessBanner
|
||||
message="Published successfully."
|
||||
onOpen={() => onOpenReport(undefined, "publish")}
|
||||
/>
|
||||
) : (
|
||||
<PublishValidationBanner
|
||||
findings={findings}
|
||||
@@ -561,7 +598,7 @@ const PublishStatic = ({
|
||||
flow,
|
||||
}: {
|
||||
templates: readonly Templates[];
|
||||
flow: PublishUiState;
|
||||
flow: StaticPublishUiState;
|
||||
}) => {
|
||||
const {
|
||||
isPublishing,
|
||||
@@ -579,11 +616,7 @@ const PublishStatic = ({
|
||||
project.latestStaticBuild == null
|
||||
? { status: "LOADED" as const, statusContent: "Not published" }
|
||||
: getStaticPublishStatusDisplay(project.latestStaticBuild);
|
||||
const latestPublish = publishes.find(
|
||||
(item) =>
|
||||
item.target === "static" &&
|
||||
item.buildId === project.latestStaticBuild?.buildId
|
||||
);
|
||||
const latestPublish = publishes.find((item) => item.target === "static");
|
||||
const logStatus =
|
||||
staticFailureFinding !== undefined
|
||||
? "FAILED"
|
||||
@@ -599,6 +632,15 @@ const PublishStatic = ({
|
||||
|
||||
return (
|
||||
<Flex gap={2} shrink={false} direction={"column"}>
|
||||
{latestPublish?.status === "success" &&
|
||||
latestPublish.staticName !== undefined &&
|
||||
!isPublishInProgress &&
|
||||
staticFailureFinding === undefined && (
|
||||
<PublishSuccessBanner
|
||||
message="Downloaded"
|
||||
onOpen={() => onOpenReport("publish")}
|
||||
/>
|
||||
)}
|
||||
<Flex gap={2} align="center">
|
||||
<Tooltip
|
||||
content={
|
||||
@@ -991,7 +1033,7 @@ type DeployTargets = keyof typeof deployTargets;
|
||||
const isDeployTargets = (value: string): value is DeployTargets =>
|
||||
Object.keys(deployTargets).includes(value);
|
||||
|
||||
export const ExportContent = (props: { flow: PublishUiState }) => {
|
||||
export const ExportContent = (props: { flow: StaticPublishUiState }) => {
|
||||
const npxCommand = "npx webstudio@latest";
|
||||
const [deployTarget, setDeployTarget] = useState<DeployTargets>("docker");
|
||||
|
||||
|
||||
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());
|
||||
|
||||
-20
@@ -599,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", () => {
|
||||
@@ -631,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"
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -33,6 +33,8 @@ 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
|
||||
|
||||
@@ -30,6 +30,9 @@ 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
|
||||
|
||||
Reference in new issue
Block a user