Run Preview authoring in its build process

This commit is contained in:
Oleg Isonen committed 2026-11-16 01:27:00 +00:00
1 parent 4b8e74d14a
commit b89c68acf0
5 files changed
+108 -95

No files matched your search

@@ -25,7 +25,9 @@ import {
executeBuilderRuntimeOperation,
type BuilderRuntimeMutation,
} from "@webstudio-is/project-build/runtime";
import { mkdir, writeFile } from "node:fs/promises";
import { loadDevBuild, updateBuild } from "../db";
import { createLocalBundleFromDevBuild } from "../flows/generated-app";
const commands = new Set([
"create-page",
@@ -59,11 +61,7 @@ const operations: PublicMcpOperation[] = runtimeOperationContracts
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
if (projectId === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
const author = async () => {
const author = async (projectId: string) => {
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
@@ -443,11 +441,20 @@ const author = async () => {
const formData = await authorReadableFormData();
const contact = await authorDefaultContact();
const context = await authorFormContext();
process.stdout.write(`${JSON.stringify({ formData, contact, context })}\n`);
return { formData, contact, context };
} finally {
await client.close();
await server.close();
}
};
await author();
export const preparePreviewBundle = async (projectId: string) => {
const authored = await author(projectId);
const build = await loadDevBuild({ projectId });
await mkdir(".webstudio", { recursive: true });
await writeFile(
".webstudio/data.json",
`${JSON.stringify(createLocalBundleFromDevBuild(build))}\n`
);
return authored;
};
@@ -29,6 +29,14 @@ if (
throw new Error("Expected Preview, email receiver, and HTTP receiver ports");
}
const prepareModule = process.argv[5];
const authorProjectId = process.argv[6];
if (prepareModule !== undefined && authorProjectId !== undefined) {
const { preparePreviewBundle } = await import(prepareModule);
const prepared = await preparePreviewBundle(authorProjectId);
await writeFile("preview-prepared.json", JSON.stringify(prepared));
}
const project = await preparePreviewProject({
assets: false,
template: ["defaults", "react-router"],
@@ -1,5 +1,5 @@
import { spawn, type ChildProcess } from "node:child_process";
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -30,9 +30,9 @@ export const withMcpEmailHttpPreview = async <Result>({
}: {
emailPort: number;
httpPort: number;
callback: ({ url }: { url: string }) => Promise<Result>;
callback: (preview: { url: string; prepared?: unknown }) => Promise<Result>;
} & (
| { projectId: string }
| { projectId: string; prepareModule?: string }
| { build: Awaited<ReturnType<typeof loadDevBuild>> }
)) => {
const tempDir = await mkdtemp(
@@ -40,15 +40,21 @@ export const withMcpEmailHttpPreview = async <Result>({
);
let preview: ChildProcess | undefined;
try {
const build =
"build" in source
? source.build
: await loadDevBuild({ projectId: source.projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
`${JSON.stringify(createLocalBundleFromDevBuild(build))}\n`
);
const prepareArgs =
"projectId" in source && source.prepareModule !== undefined
? [source.prepareModule, source.projectId]
: [];
if (prepareArgs.length === 0) {
const build =
"build" in source
? source.build
: await loadDevBuild({ projectId: source.projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
`${JSON.stringify(createLocalBundleFromDevBuild(build))}\n`
);
}
const port = await getAvailablePort();
const output: string[] = [];
preview = spawn(
@@ -63,6 +69,7 @@ export const withMcpEmailHttpPreview = async <Result>({
String(port),
String(emailPort),
String(httpPort),
...prepareArgs,
],
{
cwd: tempDir,
@@ -89,7 +96,13 @@ export const withMcpEmailHttpPreview = async <Result>({
url,
output: () => output.join(""),
});
return await callback({ url });
if (prepareArgs.length === 0) {
return await callback({ url });
}
const prepared = JSON.parse(
await readFile(join(tempDir, "preview-prepared.json"), "utf8")
) as unknown;
return await callback({ url, prepared });
} finally {
if (preview !== undefined) {
await stopChildProcess(preview, { killGroup: true });
+2 -8
View File
@@ -1,10 +1,6 @@
import type { Page } from "@playwright/test";
import { chooseAssetByFilename } from "./assets-panel";
import {
waitForChangeToBeSaved,
waitForSyncComplete,
waitForSyncStatus,
} from "./sync-status";
import { waitForChangeToBeSaved, waitForSyncComplete } from "./sync-status";
const getPropertyLabel = ({ page, label }: { page: Page; label: string }) =>
page.getByText(label, { exact: true }).first();
@@ -77,9 +73,7 @@ export const chooseSelectedAssetProperty = async ({
timeout: 10_000,
});
await waitForSyncStatus({ page, status: "idle", timeout: 3_000 }).catch(
() => undefined
);
await waitForSyncComplete({ page });
await page.getByRole("button", { name: triggerName }).click();
const save = waitForChangeToBeSaved({ page });
if (assetFilename !== undefined) {
@@ -7,28 +7,17 @@ import { loadDevBuild } from "../db";
import type { CapturedEmail } from "../flows/mcp-email-preview";
import { withMcpEmailHttpPreview } from "../flows/mcp-email-http-preview";
import { startFormContextReceiver } from "../flows/form-context-receiver";
import { runFormAuthor } from "../flows/mcp-form-author";
import type { preparePreviewBundle } from "../fixtures/mcp-default-contact-email-author";
import { test } from "../test";
import {
startPreviewFormMcpClient,
submitPreviewFormViaMcp,
} from "../flows/mcp-preview-submit";
const authorForms = async (projectId: string) => {
const { stdout } = await runFormAuthor(
"mcp-default-contact-email-author",
projectId
);
return JSON.parse(stdout) as {
contact: {
formId: string;
ownerResourceId: string;
visitorResourceId: string;
};
formData: { formId: string; ownerResourceId: string; expression: string };
context: { formId: string };
};
};
const prepareModule = new URL(
"../fixtures/mcp-default-contact-email-author.ts",
import.meta.url
).href;
const submitContactForm = async (url: string, formId: string) =>
await submitPreviewFormViaMcp({
@@ -70,56 +59,6 @@ test("Generated Preview delivers MCP-authored forms with readable email and brow
});
await setupPage.close();
const {
formData: {
formId: formDataFormId,
ownerResourceId: formDataResourceId,
expression: formDataExpression,
},
contact: { formId, ownerResourceId, visitorResourceId },
context: { formId: contextFormId },
} = await authorForms(projectId);
expect(formDataExpression).toContain(".toString()");
const build = await loadDevBuild({ projectId });
const resources = JSON.parse(build.resources) as Array<{
id: string;
email?: Record<string, unknown>;
}>;
expect(
resources.find(({ id }) => id === formDataResourceId)?.email?.body
).toBe(formDataExpression);
const dataSources = JSON.parse(build.dataSources) as Array<{
id: string;
name: string;
scopeInstanceId?: string;
}>;
const formData = dataSources.find(
({ name, scopeInstanceId }) =>
name === formDataParameterName && scopeInstanceId === formId
);
expect(formData).toBeDefined();
expect(
resources.find(({ id }) => id === ownerResourceId)?.email
).toMatchObject({
recipientMode: "project",
body: expect.stringContaining(encodeDataSourceVariable(formData!.id)),
});
expect(
resources.find(({ id }) => id === visitorResourceId)?.email
).toMatchObject({
recipientMode: "visitor",
visitorEmailField: "email",
subject: expect.stringContaining(".subject"),
body: JSON.stringify(
"Thank you for your message.\n\nWe received it and will respond as soon as possible."
),
});
expect(JSON.parse(build.projectSettings)).toMatchObject({
meta: {
contactEmail: "owner@mcp.test",
emailSender: "Contact Form <forms@mcp.test>",
},
});
const messages: CapturedEmail[] = [];
let rejectVisitor = false;
const server = createServer(async (request, response) => {
@@ -166,9 +105,61 @@ test("Generated Preview delivers MCP-authored forms with readable email and brow
try {
await withMcpEmailHttpPreview({
projectId,
prepareModule,
emailPort: address.port,
httpPort: receiver.port,
callback: async ({ url }) => {
callback: async ({ url, prepared }) => {
const {
formData: {
formId: formDataFormId,
ownerResourceId: formDataResourceId,
expression: formDataExpression,
},
contact: { formId, ownerResourceId, visitorResourceId },
context: { formId: contextFormId },
} = prepared as Awaited<ReturnType<typeof preparePreviewBundle>>;
expect(formDataExpression).toContain(".toString()");
const build = await loadDevBuild({ projectId });
const resources = JSON.parse(build.resources) as Array<{
id: string;
email?: Record<string, unknown>;
}>;
expect(
resources.find(({ id }) => id === formDataResourceId)?.email?.body
).toBe(formDataExpression);
const dataSources = JSON.parse(build.dataSources) as Array<{
id: string;
name: string;
scopeInstanceId?: string;
}>;
const formData = dataSources.find(
({ name, scopeInstanceId }) =>
name === formDataParameterName && scopeInstanceId === formId
);
expect(formData).toBeDefined();
expect(
resources.find(({ id }) => id === ownerResourceId)?.email
).toMatchObject({
recipientMode: "project",
body: expect.stringContaining(encodeDataSourceVariable(formData!.id)),
});
expect(
resources.find(({ id }) => id === visitorResourceId)?.email
).toMatchObject({
recipientMode: "visitor",
visitorEmailField: "email",
subject: expect.stringContaining(".subject"),
body: JSON.stringify(
"Thank you for your message.\n\nWe received it and will respond as soon as possible."
),
});
expect(JSON.parse(build.projectSettings)).toMatchObject({
meta: {
contactEmail: "owner@mcp.test",
emailSender: "Contact Form <forms@mcp.test>",
},
});
await test.step("Form data email has readable fields and no private values", async () => {
const formDataSubmission = (
await submitPreviewFormViaMcp({