Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
import { expect, test, vi } from "vitest";
import {
formBotFieldName,
formIdFieldName,
managedFormArrayNamesFieldName,
managedFormIdFieldName,
} from "./form-fields";
import {
getManagedFormBrowserInfo,
getManagedFormResponse,
getManagedFormValues,
loadManagedFormResources,
readFormDataWithLimit,
validateManagedFormBot,
validateManagedFormBodyFormats,
validateManagedFormRecipientLimit,
} from "./managed-form-submission";
import { loadResources } from "./resource-loader";
test("formats ordered final outcomes without response headers", () => {
const graph = {
rootIds: ["second", "first"],
resources: [
{
id: "first",
outputName: "firstOutput",
name: "First Resource",
dependencies: [],
createRequest: vi.fn(),
},
{
id: "second",
outputName: "secondOutput",
name: "Second Resource",
dependencies: [],
createRequest: vi.fn(),
},
],
};
expect(
getManagedFormResponse(graph, {
firstOutput: {
ok: true,
status: 201,
statusText: "Created",
data: { id: 1 },
headers: { authorization: "private" },
},
secondOutput: {
ok: false,
status: 422,
statusText: "Invalid submission",
data: { reason: "missing field" },
headers: { "set-cookie": "private" },
},
})
).toEqual({
success: false,
status: 502,
results: [
{
resourceId: "second",
resourceName: "Second Resource",
status: 422,
body: { reason: "missing field" },
},
{
resourceId: "first",
resourceName: "First Resource",
status: 201,
body: { id: 1 },
},
],
errors: [
{
resourceId: "second",
resourceName: "Second Resource",
status: 422,
body: { reason: "missing field" },
message: "Invalid submission",
},
],
});
expect(() => getManagedFormResponse(graph, { firstOutput: {} })).toThrow(
"Form Resource results are incomplete"
);
});
test("keeps safe Email error codes without copying codes from HTTP responses", () => {
const graph = {
rootIds: ["email", "http"],
resources: [
{
id: "email",
outputName: "email",
control: "email" as const,
dependencies: [],
createRequest: vi.fn(),
},
{
id: "http",
outputName: "http",
dependencies: [],
createRequest: vi.fn(),
},
],
};
const body = {
error: { code: "E_DAILY_LIMIT_EXCEEDED", message: "Daily limit reached" },
};
const result = getManagedFormResponse(graph, {
email: {
ok: false,
status: 429,
statusText: "Daily limit reached",
data: body,
},
http: { ok: false, status: 429, statusText: "Failed", data: body },
});
expect(result.errors.map(({ code }) => code)).toEqual([
"E_DAILY_LIMIT_EXCEEDED",
undefined,
]);
expect(
getManagedFormResponse(
{ ...graph, rootIds: ["email"] },
{
email: {
ok: false,
status: 502,
statusText: "Failed",
data: { error: { code: "[email protected]" } },
},
}
).errors[0].code
).toBeUndefined();
});
test("keeps parallel results and errors in Action order when completion is reversed", async () => {
let resolveFirst: ((response: Response) => void) | undefined;
let resolveSecond: ((response: Response) => void) | undefined;
const fetch = vi.fn((input: RequestInfo | URL) => {
const url = String(input);
return new Promise<Response>((resolve) => {
if (url.endsWith("/first")) {
resolveFirst = resolve;
} else {
resolveSecond = resolve;
}
});
});
const graph = {
rootIds: ["first", "second"],
resources: [
{
id: "first",
outputName: "firstOutput",
name: "First Resource",
dependencies: [],
createRequest: () => ({
name: "First Resource",
method: "get" as const,
url: "https://api.example/first",
headers: [],
searchParams: [],
}),
},
{
id: "second",
outputName: "secondOutput",
name: "Second Resource",
dependencies: [],
createRequest: () => ({
name: "Second Resource",
method: "get" as const,
url: "https://api.example/second",
headers: [],
searchParams: [],
}),
},
],
};
const pending = loadManagedFormResources(fetch, graph);
await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
expect(resolveFirst).toBeTypeOf("function");
expect(resolveSecond).toBeTypeOf("function");
// Resolve the later Action first, and make it fail while the first succeeds.
resolveSecond!(new Response("Second failed", { status: 422 }));
resolveFirst!(Response.json({ accepted: true }, { status: 201 }));
const outcomes = await pending;
expect(Object.keys(outcomes)).toEqual(["firstOutput", "secondOutput"]);
expect(getManagedFormResponse(graph, outcomes)).toEqual({
success: false,
status: 502,
results: [
{
resourceId: "first",
resourceName: "First Resource",
status: 201,
body: { accepted: true },
},
{
resourceId: "second",
resourceName: "Second Resource",
status: 422,
body: "Second failed",
},
],
errors: [
{
resourceId: "second",
resourceName: "Second Resource",
status: 422,
body: "Second failed",
message: "Resource request failed (422)",
},
],
});
});
test("allows five team deliveries across Email Resources and counts duplicate recipients", () => {
const graph = {
rootIds: ["project-email", "custom-email", "http"],
resources: [
{
id: "project-email",
outputName: "Project email",
dependencies: [],
control: "email" as const,
emailRecipientCount: 2,
createRequest: vi.fn(),
},
{
id: "custom-email",
outputName: "Custom email",
dependencies: [],
control: "email" as const,
// Includes a recipient also listed in the project email.
emailRecipientCount: 3,
createRequest: vi.fn(),
},
{
id: "http",
outputName: "HTTP",
dependencies: [],
createRequest: vi.fn(),
},
],
};
expect(() => validateManagedFormRecipientLimit(graph)).not.toThrow();
for (const resource of graph.resources) {
expect(resource.createRequest).not.toHaveBeenCalled();
}
});
test("checks the recipient count from a resolved bound list", () => {
const graph = {
rootIds: ["custom-email"],
resources: [
{
id: "custom-email",
outputName: "Custom email",
dependencies: [],
control: "email" as const,
// This is the authored fallback count; the evaluated binding has six.
emailRecipientCount: 1,
createRequest: vi.fn(),
},
],
};
const preparedEmailRequests = new Map([
[
"custom-email",
{
name: "Custom email",
control: "email" as const,
method: "post" as const,
url: "",
headers: [],
searchParams: [],
email: {
recipientMode: "custom" as const,
recipients: Array.from({ length: 6 }, (_, index) => ({
address: `person${index}@example.com`,
})),
subject: "Submission",
body: "Body",
includeAttachments: true,
},
},
],
]);
expect(() =>
validateManagedFormRecipientLimit(graph, preparedEmailRequests)
).toThrow("Select no more than 5 team email recipients per Form submission");
});
test("rejects six team deliveries before any HTTP or Email destination runs", () => {
const httpRequest = vi.fn();
const emailRequest = vi.fn();
const graph = {
rootIds: ["http", "first-email", "second-email"],
resources: [
{
id: "http",
outputName: "HTTP",
dependencies: [],
createRequest: httpRequest,
},
{
id: "first-email",
outputName: "First email",
dependencies: [],
control: "email" as const,
emailRecipientCount: 3,
createRequest: emailRequest,
},
{
id: "second-email",
outputName: "Second email",
dependencies: [],
control: "email" as const,
emailRecipientCount: 3,
createRequest: emailRequest,
},
],
};
expect(() => validateManagedFormRecipientLimit(graph)).toThrow(
"Select no more than 5 team email recipients"
);
expect(httpRequest).not.toHaveBeenCalled();
expect(emailRequest).not.toHaveBeenCalled();
});
test("rejects Email roots without a trusted recipient count", () => {
expect(() =>
validateManagedFormRecipientLimit({
rootIds: ["email"],
resources: [
{
id: "email",
outputName: "Email",
dependencies: [],
control: "email",
createRequest: vi.fn(),
},
],
})
).toThrow("Invalid Email Resource recipient count");
});
test("rejects an Email Resource with no resolved recipient", () => {
expect(() =>
validateManagedFormRecipientLimit({
rootIds: ["email"],
resources: [
{
id: "email",
outputName: "Email",
dependencies: [],
control: "email",
emailRecipientCount: 0,
createRequest: vi.fn(),
},
],
})
).toThrow("Invalid Email Resource recipient count");
});
test("counts Email dependencies once and blocks an HTTP root before side effects", () => {
const httpRequest = vi.fn();
const emailRequest = vi.fn();
const emailResource = {
id: "email",
outputName: "Email",
dependencies: [],
control: "email" as const,
emailRecipientCount: 6,
createRequest: emailRequest,
};
const graph = {
rootIds: ["http", "other-http"],
resources: [
{
id: "http",
outputName: "HTTP",
dependencies: ["email"],
createRequest: httpRequest,
},
{
id: "other-http",
outputName: "Other HTTP",
dependencies: ["email"],
createRequest: httpRequest,
},
emailResource,
],
};
expect(() => validateManagedFormRecipientLimit(graph)).toThrow(
"Select no more than 5 team email recipients"
);
expect(httpRequest).not.toHaveBeenCalled();
expect(emailRequest).not.toHaveBeenCalled();
emailResource.emailRecipientCount = 5;
expect(() => validateManagedFormRecipientLimit(graph)).not.toThrow();
});
test("an Email destination fails preflight before another Resource dispatches", () => {
const httpRequest = vi.fn();
const graph = {
rootIds: ["http", "email"],
resources: [
{
id: "http",
outputName: "HTTP",
dependencies: [],
createRequest: httpRequest,
},
{
id: "email",
outputName: "Email",
dependencies: [],
control: "email" as const,
createRequest: () => {
throw new Error("Email must not run before preflight");
},
},
],
};
expect(() => validateManagedFormBodyFormats(graph, new FormData())).toThrow(
"Email delivery requires Webstudio Cloud"
);
expect(httpRequest).not.toHaveBeenCalled();
});
test("an Email dependency fails preflight before its HTTP destination dispatches", () => {
const httpRequest = vi.fn();
const emailRequest = vi.fn();
const graph = {
rootIds: ["http"],
resources: [
{
id: "http",
outputName: "HTTP",
dependencies: ["email"],
createRequest: httpRequest,
},
{
id: "email",
outputName: "Email",
dependencies: [],
control: "email" as const,
emailRecipientCount: 1,
createRequest: emailRequest,
},
],
};
expect(() => validateManagedFormBodyFormats(graph, new FormData())).toThrow(
"Email delivery requires Webstudio Cloud"
);
expect(httpRequest).not.toHaveBeenCalled();
expect(emailRequest).not.toHaveBeenCalled();
});
test("configured Email can pass preflight without an HTTP URL", () => {
const graph = {
rootIds: ["email"],
resources: [
{
id: "email",
outputName: "Email",
dependencies: [],
control: "email" as const,
emailRecipientCount: 1,
createRequest: () => ({
name: "Email",
control: "email" as const,
method: "post" as const,
url: "",
searchParams: [],
headers: [],
email: {
recipientMode: "project" as const,
recipients: [{ address: "[email protected]" }],
subject: "Hello",
body: "Message",
includeAttachments: false,
},
}),
},
],
};
expect(
validateManagedFormBodyFormats(graph, new FormData(), true).rootIds
).toEqual(["email"]);
});
test("rejects an invalid dependency request before any destination runs", () => {
const graph = {
rootIds: ["submit"],
resources: [
{
id: "lookup",
outputName: "Lookup",
dependencies: [],
createRequest: () => ({
name: "Lookup",
method: "post" as const,
url: "https://example.com/lookup",
searchParams: [],
headers: [],
bodyFormat: "multipart" as const,
body: "invalid scalar",
}),
},
{
id: "submit",
outputName: "Submit",
dependencies: ["lookup"],
createRequest: () => {
throw new Error("A destination must not run before preflight");
},
},
],
};
expect(() => validateManagedFormBodyFormats(graph, new FormData())).toThrow(
"Multipart body expects an object of fields"
);
});
test("reuses dependency-free requests after preflight", async () => {
const createRequest = vi.fn(() => ({
name: "Submit",
method: "post" as const,
url: "https://example.com/submit",
searchParams: [],
headers: [],
bodyFormat: "json" as const,
body: { message: "Hello" },
}));
const graph = validateManagedFormBodyFormats(
{
rootIds: ["submit"],
resources: [
{
id: "submit",
outputName: "Submit",
dependencies: [],
createRequest,
},
],
},
new FormData()
);
const fetch = vi.fn<typeof globalThis.fetch>(async () =>
Response.json({ accepted: true })
);
await loadResources(fetch, graph);
expect(createRequest).toHaveBeenCalledOnce();
expect(fetch).toHaveBeenCalledOnce();
const createLookup = vi.fn(() => ({
name: "Lookup",
method: "get" as const,
url: "https://example.com/lookup",
searchParams: [],
headers: [],
}));
const dependentGraph = validateManagedFormBodyFormats(
{
rootIds: ["submit"],
resources: [
{
id: "lookup",
outputName: "Lookup",
dependencies: [],
createRequest: createLookup,
},
{
id: "submit",
outputName: "Submit",
dependencies: ["lookup"],
createRequest: () => ({
name: "Submit",
method: "post",
url: "https://example.com/submit",
searchParams: [],
headers: [],
body: { message: "Hello" },
}),
},
],
},
new FormData()
);
await loadResources(fetch, dependentGraph);
expect(createLookup).toHaveBeenCalledOnce();
});
test("an invalid dependent body prevents every selected destination", async () => {
const requestedUrls: string[] = [];
const fetch = vi.fn<typeof globalThis.fetch>(async (input) => {
requestedUrls.push(String(input));
return Response.json({ accepted: true });
});
const graph = validateManagedFormBodyFormats(
{
rootIds: ["independent", "dependent"],
resources: [
{
id: "lookup",
outputName: "Lookup",
dependencies: [],
createRequest: () => ({
name: "Lookup",
method: "get",
url: "https://example.com/lookup",
searchParams: [],
headers: [],
}),
},
{
id: "independent",
outputName: "Independent",
dependencies: [],
createRequest: () => ({
name: "Independent",
method: "post",
url: "https://example.com/independent",
searchParams: [],
headers: [],
bodyFormat: "json",
body: { message: "Hello" },
}),
},
{
id: "dependent",
outputName: "Dependent",
dependencies: ["lookup"],
createRequest: () => ({
name: "Dependent",
method: "post",
url: "https://example.com/dependent",
searchParams: [],
headers: [],
bodyFormat: "json",
body: { attachment: new File(["hello"], "hello.txt") },
}),
},
],
},
new FormData()
);
await expect(loadManagedFormResources(fetch, graph)).rejects.toThrow(
"JSON body cannot include uploaded files"
);
expect(requestedUrls).toEqual(["https://example.com/lookup"]);
});
test("an Email dependency is rejected before its lookup or destinations dispatch", async () => {
const requestedUrls: string[] = [];
const fetch = vi.fn<typeof globalThis.fetch>(async (input) => {
requestedUrls.push(String(input));
return Response.json({ subject: "Hello\nBcc: [email protected]" });
});
await expect(
loadManagedFormResources(fetch, {
rootIds: ["http", "email"],
resources: [
{
id: "lookup",
outputName: "Lookup",
dependencies: [],
createRequest: () => ({
name: "Lookup",
method: "get",
url: "https://example.com/lookup",
searchParams: [],
headers: [],
}),
},
{
id: "http",
outputName: "HTTP",
dependencies: [],
createRequest: () => ({
name: "HTTP",
method: "post",
url: "https://example.com/destination",
searchParams: [],
headers: [],
}),
},
{
id: "email",
outputName: "Email",
dependencies: ["lookup"],
control: "email",
createRequest: (documents) => ({
name: "Email",
control: "email",
method: "post",
url: "",
searchParams: [],
headers: [],
email: {
recipientMode: "project",
recipients: [{ address: "[email protected]" }],
subject: (
documents.get("lookup") as { data: { subject: string } }
).data.subject,
body: "Text",
includeAttachments: true,
},
}),
},
],
})
).rejects.toThrow("Email Resources cannot depend on other Resources");
expect(requestedUrls).toEqual([]);
});
test("rejects duplicate IDs and cancellation before outbound requests", async () => {
const fetch = vi.fn<typeof globalThis.fetch>(async () => Response.json({}));
const resource = {
id: "first",
outputName: "First",
dependencies: [],
createRequest: () => ({
name: "First",
method: "post" as const,
url: "https://example.com",
searchParams: [],
headers: [],
}),
};
await expect(
loadManagedFormResources(fetch, {
rootIds: ["first", "first"],
resources: [resource],
})
).rejects.toThrow("duplicate selected destinations");
await expect(
loadManagedFormResources(fetch, {
rootIds: ["first"],
resources: [resource, resource],
})
).rejects.toThrow("duplicate resource IDs");
await expect(
loadManagedFormResources(
fetch,
{ rootIds: ["first"], resources: [resource] },
undefined,
{ signal: AbortSignal.abort() }
)
).rejects.toThrow();
expect(fetch).not.toHaveBeenCalled();
});
test("rejects selected-root dependencies and cycles before any outbound request", async () => {
const fetch = vi.fn<typeof globalThis.fetch>(async () => Response.json({}));
const request = () => ({
name: "Resource",
method: "post" as const,
url: "https://example.com/resource",
searchParams: [],
headers: [],
});
await expect(
loadManagedFormResources(fetch, {
rootIds: ["first", "second"],
resources: [
{
id: "first",
outputName: "First",
dependencies: ["second"],
createRequest: request,
},
{
id: "second",
outputName: "Second",
dependencies: [],
createRequest: request,
},
],
})
).rejects.toThrow("Selected Form Resources cannot depend on one another");
await expect(
loadManagedFormResources(fetch, {
rootIds: ["first"],
resources: [
{
id: "first",
outputName: "First",
dependencies: ["lookup"],
createRequest: request,
},
{
id: "lookup",
outputName: "Lookup",
dependencies: ["lookup"],
createRequest: request,
},
],
})
).rejects.toThrow("Form Resource graph contains a cycle");
expect(fetch).not.toHaveBeenCalled();
});
test("checks each destination body before a managed submission", () => {
const file = new File(["hello"], "hello.txt");
const formData = new FormData();
formData.set("attachment", file);
let jsonBody: unknown = { message: "No file here" };
const graph = {
rootIds: ["json", "multipart"],
resources: [
{
id: "json",
outputName: "JSON",
dependencies: [],
createRequest: () => ({
name: "JSON",
method: "post" as const,
url: "https://example.com/json",
searchParams: [],
headers: [],
bodyFormat: "json" as const,
body: jsonBody,
}),
},
{
id: "multipart",
outputName: "Multipart",
dependencies: [],
createRequest: () => ({
name: "Multipart",
method: "post" as const,
url: "https://example.com/multipart",
searchParams: [],
headers: [],
bodyFormat: "multipart" as const,
body: { attachment: file },
}),
},
],
};
expect(() => validateManagedFormBodyFormats(graph, formData)).not.toThrow();
jsonBody = { attachment: file };
expect(() => validateManagedFormBodyFormats(graph, formData)).toThrow(
"JSON body cannot include uploaded files"
);
});
test("ignores an unselected optional file input", () => {
const formData = new FormData();
formData.set("attachment", new File([], ""));
formData.set(managedFormArrayNamesFieldName, "[]");
expect(getManagedFormValues(formData)).toEqual({});
const graph = {
rootIds: ["submit"],
resources: [
{
id: "submit",
outputName: "Submit",
dependencies: [],
createRequest: () => ({
name: "Submit",
method: "post" as const,
url: "https://example.com/submit",
searchParams: [],
headers: [],
bodyFormat: "json" as const,
body: getManagedFormValues(formData),
}),
},
],
};
expect(() => validateManagedFormBodyFormats(graph, formData)).not.toThrow();
});
test("catches a JSON default Form body before dependent Resources run", () => {
const formData = new FormData();
formData.set("attachment", new File(["hello"], "hello.txt"));
const graph = {
rootIds: ["submit"],
resources: [
{
id: "submit",
outputName: "Submit",
dependencies: ["lookup"],
usesDefaultFormBody: true,
bodyFormat: "json" as const,
createRequest: () => {
throw new Error("Dependent requests cannot be evaluated yet");
},
},
],
};
expect(() => validateManagedFormBodyFormats(graph, formData)).toThrow(
"JSON body cannot include uploaded files"
);
});
test("parses bounded request bodies and rejects oversized streamed bodies", async () => {
const formData = new FormData();
formData.set("field", "value");
const request = new Request("https://example.com/submit", {
method: "POST",
body: formData,
});
expect((await readFormDataWithLimit(request, 1024)).get("field")).toBe(
"value"
);
const oversized = new Request("https://example.com/submit", {
method: "POST",
body: new Uint8Array([1, 2, 3, 4]),
});
await expect(readFormDataWithLimit(oversized, 3)).rejects.toThrow(
"Form submission is too large"
);
const oversizedDefault = new Request("https://example.com/submit", {
method: "POST",
headers: { "content-length": String(25 * 1024 * 1024 + 1) },
body: "x",
});
await expect(readFormDataWithLimit(oversizedDefault)).rejects.toThrow(
"Form submission exceeds the 25 MiB limit. Reduce file sizes and try again."
);
});
test("validates the managed Form bot field and keeps the Brave exception", () => {
const formData = new FormData();
expect(() => validateManagedFormBot(formData)).toThrow(
"Form bot field not found"
);
formData.set(formBotFieldName, "brave");
expect(() => validateManagedFormBot(formData)).not.toThrow();
formData.set(formBotFieldName, Date.now().toString(16));
expect(() => validateManagedFormBot(formData)).not.toThrow();
formData.set(formBotFieldName, "stale");
expect(() => validateManagedFormBot(formData)).toThrow(
"Form bot value invalid stale"
);
const malformed = `${Date.now().toString(16)}not-hex`;
formData.set(formBotFieldName, malformed);
expect(() => validateManagedFormBot(formData)).toThrow(
`Form bot value invalid ${malformed}`
);
});
test("reconstructs repeated and empty field groups without internal values", () => {
const formData = new FormData();
formData.append("choice", "first");
formData.append("choice", "second");
formData.set("scalar", "value");
formData.set(
managedFormArrayNamesFieldName,
JSON.stringify(["choice", "empty"])
);
formData.set(managedFormIdFieldName, "form");
formData.set(formIdFieldName, "legacy");
formData.set(formBotFieldName, "brave");
const values = getManagedFormValues(formData);
expect(Object.getPrototypeOf(values)).toBe(null);
expect(values).toEqual({
choice: ["first", "second"],
empty: [],
scalar: "value",
});
expect(() => {
formData.set(
managedFormArrayNamesFieldName,
JSON.stringify(["choice", "choice"])
);
getManagedFormValues(formData);
}).toThrow("Invalid Form field groups");
});
test("preserves file values and only includes explicitly trusted IP", () => {
const file = new File(["contents"], "upload.txt", { type: "text/plain" });
const formData = new FormData();
formData.set("upload", file);
formData.set(managedFormArrayNamesFieldName, "[]");
expect(getManagedFormValues(formData).upload).toBe(file);
const request = new Request("https://example.com/submit", {
headers: {
"user-agent": "browser",
"accept-language": "en",
referer: "https://example.com/page",
"cf-connecting-ip": "203.0.113.1",
},
});
const info = getManagedFormBrowserInfo(request);
expect(info).toEqual({
userAgent: "browser",
language: "en",
referrer: "https://example.com/page",
});
expect(getManagedFormBrowserInfo(request, "203.0.113.1").ip).toBe(
"203.0.113.1"
);
});
test("browser info strips referrer credentials, query secrets, and fragments", () => {
const request = new Request("https://example.com/action", {
headers: {
referer:
"https://user:[email protected]/contact?authToken=secret&email=private%40example.com#token",
},
});
expect(getManagedFormBrowserInfo(request)).toEqual({
referrer: "https://example.com/contact",
});
});
test.each(["not a URL", "javascript:secret", "data:text/plain,secret"])(
"browser info omits unsafe referrer %s",
(referer) => {
expect(
getManagedFormBrowserInfo(
new Request("https://example.com/action", { headers: { referer } })
)
).toEqual({});
}
);