Skip to content

Commit 77b51f8

Browse files
authored
Merge pull request #243 from taras/feat/web-form-server
✨ feat: loopback form server and browser protocol (#195)
2 parents 5197cfc + 7d645af commit 77b51f8

17 files changed

Lines changed: 2223 additions & 27 deletions

‎bun.lock‎

Lines changed: 2 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎deno.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/web/client/config.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* The configuration the page fetches, validated before it is believed.
3+
*
4+
* The response comes from this WebForm's own server, but the page checks it
5+
* anyway: the value flows into the DOM, and "the server sent it" is not a shape.
6+
* A malformed or unexpected payload becomes a failure the page can report rather
7+
* than an `undefined` rendered into the body.
8+
*
9+
* `bodyHtml` was sanitized on the server by `renderBody`, and it is the only
10+
* field the page reads. Nothing widens that.
11+
*/
12+
13+
export interface FormConfig {
14+
bodyHtml: string;
15+
}
16+
17+
export class ConfigError extends Error {
18+
override name = "ConfigError";
19+
}
20+
21+
export function parseConfig(text: string): FormConfig {
22+
let decoded: unknown;
23+
try {
24+
decoded = JSON.parse(text);
25+
} catch {
26+
throw new ConfigError("the form configuration is not JSON");
27+
}
28+
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
29+
throw new ConfigError("the form configuration is not an object");
30+
}
31+
if (!("bodyHtml" in decoded)) {
32+
throw new ConfigError("the form configuration has no bodyHtml");
33+
}
34+
const { bodyHtml } = decoded;
35+
if (typeof bodyHtml !== "string") {
36+
throw new ConfigError("the form configuration's bodyHtml is not a string");
37+
}
38+
return { bodyHtml };
39+
}

‎packages/web/client/main.tsx‎

Lines changed: 166 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,60 @@
1+
/**
2+
* The form page.
3+
*
4+
* Everything the page does happens inside one Effection scope, opened by `run()`
5+
* at startup and closed when the tab goes away. That is not ceremony: an
6+
* `XMLHttpRequest` started by a React callback outlives the callback, and without
7+
* an owner it would keep pointing at a page that is being unloaded. The scope is
8+
* the owner, and leaving it aborts whatever is still in flight.
9+
*
10+
* The scope stays open by waiting on `pagehide`. Returning from the root
11+
* operation is what ends it — there is no `destroy()` to forget and no detached
12+
* scope to leak.
13+
*
14+
* React callbacks run outside any operation, so they re-enter through the
15+
* captured scope. Each re-entry contains its own failure: a task started with
16+
* `scope.run()` that throws propagates into the scope and takes its siblings with
17+
* it, which here would mean one failed submission killing the whole form.
18+
*
19+
* ## Order of appearance
20+
*
21+
* Nothing operable is shown until both halves are ready — the configuration and
22+
* the precompiled validator. A form mounted before its validator would accept
23+
* input it cannot check, and the person would find out only after submitting.
24+
* Until then, and on any failure, the page shows fixed text: no author content,
25+
* no server text, nothing executable.
26+
*/
27+
128
import { createElement } from "react";
229
import { createRoot } from "react-dom/client";
330
import type { RJSFSchema, UiSchema } from "@rjsf/utils";
431
import withTheme from "@rjsf/core/lib/withTheme.js";
532
import { generateTheme } from "@rjsf/shadcn/lib/Theme/index.js";
633
import createPrecompiledValidator from "@rjsf/validator-ajv8/lib/createPrecompiledValidator.js";
734
import type { ValidatorFunctions } from "@rjsf/validator-ajv8/lib/types.js";
35+
import { action, run, useScope, withResolvers } from "effection";
36+
import type { Operation, Scope } from "effection";
37+
838
import { resolveHelper } from "./helpers.ts";
39+
import { parseConfig } from "./config.ts";
40+
import type { FormConfig } from "./config.ts";
41+
import { outcomeFor, TRANSPORT_MESSAGE } from "./outcome.ts";
42+
import type { Outcome } from "./outcome.ts";
43+
import { get, postJson } from "./request.ts";
44+
45+
interface Registration {
46+
validateFns: ValidatorFunctions;
47+
rootSchema: RJSFSchema;
48+
uiSchema?: UiSchema;
49+
}
950

1051
/**
1152
* The receiving side of the token-scoped external validator script. The server
1253
* precompiles a WebForm's schema with RJSF/Ajv and serves the result as a
1354
* same-origin script under the fixed `script-src 'self'` policy — no inline
1455
* script, nonce, `unsafe-eval`, blob, or data script. This bridge is what that
1556
* script resolves its helpers through and registers its validators with, so the
16-
* browser bundle carries no `new Function` and no eval path of its
17-
* own.
57+
* browser bundle carries no `new Function` and no eval path of its own.
1858
*/
1959
interface WebFormBridge {
2060
resolveHelper(id: string): { default: unknown };
@@ -25,30 +65,136 @@ declare global {
2565
var __WEBFORM__: WebFormBridge;
2666
}
2767

68+
const STARTUP_FAILED =
69+
"This form could not be prepared. Close this tab and run the workflow again.";
70+
2871
const Form = withTheme(generateTheme());
2972

30-
function mount(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
31-
const validator = createPrecompiledValidator(validateFns, rootSchema);
32-
const container = document.getElementById("root");
33-
if (!container) {
34-
throw new Error("the form container element #root is missing from the page shell");
35-
}
36-
createRoot(container).render(
37-
createElement(Form, { schema: rootSchema, uiSchema: uiSchema ?? {}, validator }),
38-
);
39-
}
40-
41-
function loadValidator(): void {
42-
const script = document.createElement("script");
43-
script.src = "validator.js";
44-
document.head.appendChild(script);
45-
}
73+
const registered = withResolvers<Registration>();
4674

75+
// Installed before the validator script is ever requested, so the script cannot
76+
// arrive ahead of the bridge that receives it.
4777
globalThis.__WEBFORM__ = {
4878
resolveHelper,
4979
register(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
50-
mount(validateFns, rootSchema, uiSchema);
80+
registered.resolve({ validateFns, rootSchema, uiSchema });
5181
},
5282
};
5383

54-
loadValidator();
84+
function element(id: string): HTMLElement {
85+
const found = document.getElementById(id);
86+
if (!found) {
87+
throw new Error(`the page shell is missing #${id}`);
88+
}
89+
return found;
90+
}
91+
92+
/** Fixed text only. Author content never reaches the status region. */
93+
function say(message: string): void {
94+
element("status").textContent = message;
95+
}
96+
97+
/**
98+
* Load the validator script the server precompiled for this form.
99+
*
100+
* The page runs under `script-src 'self'` with no `unsafe-eval`, so a validator
101+
* cannot be compiled here; it arrives as a same-origin script that calls back
102+
* into the bridge. Loading it is an operation so a halt removes the element's
103+
* listeners rather than leaving them attached to a page that is going away.
104+
*/
105+
function loadValidatorScript(): Operation<void> {
106+
return action<void>((resolve, reject) => {
107+
const script = document.createElement("script");
108+
const onLoad = (): void => resolve();
109+
const onError = (): void => reject(new Error("the validator script failed to load"));
110+
script.addEventListener("load", onLoad);
111+
script.addEventListener("error", onError);
112+
script.src = "validator.js";
113+
document.head.appendChild(script);
114+
return () => {
115+
script.removeEventListener("load", onLoad);
116+
script.removeEventListener("error", onError);
117+
};
118+
});
119+
}
120+
121+
/** Resolves when the tab is going away, which is what ends the scope. */
122+
function untilPageHide(): Operation<void> {
123+
return action<void>((resolve) => {
124+
const onHide = (): void => resolve();
125+
globalThis.addEventListener("pagehide", onHide);
126+
return () => globalThis.removeEventListener("pagehide", onHide);
127+
});
128+
}
129+
130+
function* submit(formData: unknown): Operation<void> {
131+
const result = yield* postJson("submit", JSON.stringify(formData ?? null));
132+
apply(outcomeFor(result.status));
133+
}
134+
135+
function apply(outcome: Outcome): void {
136+
say(outcome.message);
137+
if (!outcome.formUsable) {
138+
element("root").setAttribute("hidden", "hidden");
139+
}
140+
if (outcome.closable) {
141+
// A script can only close a window it opened, so this may do nothing at
142+
// all. The message above is the actual fallback.
143+
globalThis.close();
144+
}
145+
}
146+
147+
function mount(config: FormConfig, registration: Registration, scope: Scope): void {
148+
// Sanitized on the server by `renderBody`. This is the only place author
149+
// content enters the DOM.
150+
element("content").innerHTML = config.bodyHtml;
151+
152+
const validator = createPrecompiledValidator(registration.validateFns, registration.rootSchema);
153+
154+
createRoot(element("root")).render(
155+
createElement(Form, {
156+
schema: registration.rootSchema,
157+
uiSchema: registration.uiSchema ?? {},
158+
validator,
159+
onSubmit: (event: { formData?: unknown }) => {
160+
// React calls this outside any operation. Re-entering through the
161+
// captured scope gives the request an owner; catching inside keeps a
162+
// failed submission from tearing the scope down with it.
163+
scope.run(function* () {
164+
try {
165+
yield* submit(event.formData);
166+
} catch {
167+
say(TRANSPORT_MESSAGE);
168+
}
169+
});
170+
},
171+
}),
172+
);
173+
}
174+
175+
function* start(): Operation<void> {
176+
const scope = yield* useScope();
177+
178+
const response = yield* get("config.json");
179+
if (response.status !== 200) {
180+
throw new Error(`the form configuration could not be loaded (${response.status})`);
181+
}
182+
const config = parseConfig(response.body);
183+
184+
yield* loadValidatorScript();
185+
const registration = yield* registered.operation;
186+
187+
mount(config, registration, scope);
188+
}
189+
190+
run(function* () {
191+
try {
192+
yield* start();
193+
} catch {
194+
// Fixed text, never the failure's own message: nothing the server or the
195+
// author wrote is rendered on a path that has already gone wrong.
196+
say(STARTUP_FAILED);
197+
return;
198+
}
199+
yield* untilPageHide();
200+
});

‎packages/web/client/outcome.ts‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/**
2+
* What a person is told after submitting, and whether they can try again.
3+
*
4+
* Three of these are ordinary and one is not. A 204 means the workflow has the
5+
* answer and this tab has no further purpose. A 409 means the form was already
6+
* answered — by another tab, or by this one before a reload — and nothing the
7+
* person does here will change that. A 422 or a transport failure is the only
8+
* case where trying again makes sense, so it is the only case that leaves the
9+
* form usable.
10+
*
11+
* Pure and free of the DOM, so the mapping is tested directly rather than
12+
* inferred from what a page rendered.
13+
*/
14+
15+
export type OutcomeKind = "accepted" | "already-submitted" | "retryable";
16+
17+
export interface Outcome {
18+
kind: OutcomeKind;
19+
message: string;
20+
/** Whether the person can correct their answer and submit again. */
21+
formUsable: boolean;
22+
/** Whether this tab has finished its job and may close. */
23+
closable: boolean;
24+
}
25+
26+
export const ACCEPTED_MESSAGE = "Submission received. You can safely close this tab.";
27+
export const ALREADY_SUBMITTED_MESSAGE =
28+
"This form was already submitted. You can safely close this tab.";
29+
export const INVALID_MESSAGE = "The server rejected this submission. Correct it and try again.";
30+
export const TRANSPORT_MESSAGE = "The submission could not be delivered. Try again.";
31+
32+
export function outcomeFor(status: number): Outcome {
33+
if (status === 204) {
34+
return { kind: "accepted", message: ACCEPTED_MESSAGE, formUsable: false, closable: true };
35+
}
36+
if (status === 409) {
37+
return {
38+
kind: "already-submitted",
39+
message: ALREADY_SUBMITTED_MESSAGE,
40+
formUsable: false,
41+
closable: true,
42+
};
43+
}
44+
if (status === 422) {
45+
return { kind: "retryable", message: INVALID_MESSAGE, formUsable: true, closable: false };
46+
}
47+
// Everything else — a refused origin, a media-type rejection, a size refusal,
48+
// a dead connection reported as status 0 — is something the person may be able
49+
// to get past, and none of it is a reason to take their answer away.
50+
return { kind: "retryable", message: TRANSPORT_MESSAGE, formUsable: true, closable: false };
51+
}

0 commit comments

Comments
 (0)