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+
128import { createElement } from "react" ;
229import { createRoot } from "react-dom/client" ;
330import type { RJSFSchema , UiSchema } from "@rjsf/utils" ;
431import withTheme from "@rjsf/core/lib/withTheme.js" ;
532import { generateTheme } from "@rjsf/shadcn/lib/Theme/index.js" ;
633import createPrecompiledValidator from "@rjsf/validator-ajv8/lib/createPrecompiledValidator.js" ;
734import 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+
838import { 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 */
1959interface 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+
2871const 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.
4777globalThis . __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+ } ) ;
0 commit comments