Skip to content

Commit 2a66708

Browse files
authored
Merge pull request #250 from taras/feat/web-form-seams
✨ feat: opener and responder seams for WebForm (#195)
2 parents 97d9c35 + 25fcc01 commit 2a66708

4 files changed

Lines changed: 671 additions & 0 deletions

File tree

‎packages/web/src/opener.ts‎

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
/**
2+
* Getting a person to the form.
3+
*
4+
* The URL is printed before anything tries to open it. Opening is the part that
5+
* fails — no browser, no display, no `xdg-open`, a workflow over SSH or in a
6+
* container — and none of that should end a form that is already listening. So a
7+
* failed launch is a warning, the printed URL stands on its own, and the workflow
8+
* keeps waiting.
9+
*
10+
* Contextual rather than a parameter, so browser-launching stays out of the
11+
* authoring contract entirely.
12+
*/
13+
14+
import { type Api, createApi, type Operations } from "@effectionx/context-api";
15+
import { spawn } from "effection";
16+
import type { Operation, Task } from "effection";
17+
import { exec, platform } from "@executablemd/runtime";
18+
19+
export interface FormOpenerApi {
20+
/** Ask the host to open this URL. Failure is the caller's to tolerate. */
21+
open(url: string): Operation<void>;
22+
}
23+
24+
/** `start` reads a lone quoted argument as a window title, hence the empty one. */
25+
function openCommand(os: string, url: string): string[] {
26+
if (os === "darwin") {
27+
return ["open", url];
28+
}
29+
if (os === "win32") {
30+
return ["cmd", "/c", "start", "", url];
31+
}
32+
return ["xdg-open", url];
33+
}
34+
35+
export const FormOpener: Api<FormOpenerApi> = createApi<FormOpenerApi>("FormOpener", {
36+
*open(url: string): Operation<void> {
37+
const { os } = yield* platform();
38+
const command = openCommand(os, url);
39+
const result = yield* exec({ command });
40+
if (result.exitCode !== 0) {
41+
throw new Error(
42+
`the browser command exited ${result.exitCode}: ${command[0]}` +
43+
(result.stderr.trim() ? ` — ${result.stderr.trim()}` : ""),
44+
);
45+
}
46+
},
47+
});
48+
49+
export const open: Operations<FormOpenerApi>["open"] = FormOpener.operations.open;
50+
51+
/** Where the URL and any warning go. Stderr, never the document. */
52+
export interface OpenerOutput {
53+
url(text: string): void;
54+
warn(text: string): void;
55+
}
56+
57+
const consoleOutput: OpenerOutput = {
58+
url(text: string): void {
59+
console.error(text);
60+
},
61+
warn(text: string): void {
62+
console.error(text);
63+
},
64+
};
65+
66+
/**
67+
* Print the form's URL, then try to open it, and return without waiting.
68+
*
69+
* Nothing awaits the launch: a browser command that blocks until the browser
70+
* quits would hold the workflow open long after the person had answered. The task
71+
* belongs to the calling scope, so leaving it halts a launch still in flight.
72+
*/
73+
export function* announceForm(
74+
url: string,
75+
output: OpenerOutput = consoleOutput,
76+
): Operation<Task<void>> {
77+
output.url(url);
78+
79+
return yield* spawn(function* () {
80+
try {
81+
yield* open(url);
82+
} catch (error) {
83+
// Caught rather than left to the scope: an unobserved failure here would
84+
// take the form down with it, the one outcome a failed launch must not have.
85+
const reason = error instanceof Error ? error.message : String(error);
86+
output.warn(
87+
`could not open a browser automatically (${reason}). Open the URL above to continue.`,
88+
);
89+
}
90+
});
91+
}

‎packages/web/src/responder.ts‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
/**
2+
* Answering a form without a person.
3+
*
4+
* Two pieces, deliberately separate. `FormResponder.respond` receives only the
5+
* form's URL: whoever installs it has already closed over the answer, so nothing
6+
* downstream ever carries predetermined data — not a component prop, not a
7+
* live-form input, not the authoring contract. Production answers nothing.
8+
*
9+
* `submitForm` is the submission itself, and it speaks the same HTTP a browser
10+
* speaks to the same token-scoped URL. An injected responder goes through it, so
11+
* the token, the exact `Host`, the loopback `Origin`, the media type, the 1 MiB
12+
* ceiling, schema validation, the single reservation, the 409, and the wait for
13+
* the 204 all still apply. A responder able to skip any of those would make a
14+
* green test say nothing about whether a browser could submit.
15+
*/
16+
17+
import { type Api, createApi, type Operations } from "@effectionx/context-api";
18+
import { action } from "effection";
19+
import type { Operation } from "effection";
20+
import { request } from "node:http";
21+
22+
import type { Json } from "./json.ts";
23+
24+
export interface FormResponderApi {
25+
/**
26+
* Answer the form at `url`.
27+
*
28+
* The URL is the only input. An implementation that needs an answer holds it
29+
* already; asking for one here is what would push test data into the caller.
30+
*/
31+
respond(url: string): Operation<void>;
32+
}
33+
34+
export const FormResponder: Api<FormResponderApi> = createApi<FormResponderApi>("FormResponder", {
35+
// A live form is answered by a person, so the default does nothing at all and
36+
// the submission stays pending until one arrives.
37+
// deno-lint-ignore require-yield
38+
*respond(): Operation<void> {},
39+
});
40+
41+
export const respond: Operations<FormResponderApi>["respond"] = FormResponder.operations.respond;
42+
43+
export interface FormResponse {
44+
status: number;
45+
body: string;
46+
}
47+
48+
/**
49+
* Submit to a form's URL exactly as its page would.
50+
*
51+
* `Origin` is set to the form's own origin because the server refuses a
52+
* submission without it. That is not a bypass — it is what a browser on that page
53+
* sends, and the server still checks it. `Host` is left to `node:http` to derive
54+
* from the URL, so it names where the request is actually going.
55+
*/
56+
export function submitForm(url: string, data: Json): Operation<FormResponse> {
57+
return postJson(new URL("submit", url), JSON.stringify(data));
58+
}
59+
60+
function postJson(url: URL, body: string): Operation<FormResponse> {
61+
return action<FormResponse>((resolve, reject) => {
62+
const payload = new TextEncoder().encode(body);
63+
64+
const outgoing = request(
65+
{
66+
protocol: url.protocol,
67+
hostname: url.hostname,
68+
port: url.port,
69+
path: url.pathname,
70+
method: "POST",
71+
headers: {
72+
"Content-Type": "application/json",
73+
"Content-Length": String(payload.byteLength),
74+
Origin: url.origin,
75+
},
76+
},
77+
(incoming) => {
78+
let received = "";
79+
incoming.setEncoding("utf8");
80+
incoming.on("data", (chunk: string) => {
81+
received += chunk;
82+
});
83+
incoming.on("end", () => {
84+
resolve({ status: incoming.statusCode ?? 0, body: received });
85+
});
86+
incoming.on("error", (error: Error) => reject(error));
87+
},
88+
);
89+
90+
outgoing.on("error", (error: Error) => reject(error));
91+
outgoing.end(payload);
92+
93+
// Runs however the action ends, so a halted responder leaves no socket.
94+
return () => {
95+
outgoing.destroy();
96+
};
97+
});
98+
}

0 commit comments

Comments
 (0)