Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions packages/web/client/config.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
/**
* The configuration the page fetches, validated before it is believed.
*
* The response comes from this WebForm's own server, but the page checks it
* anyway: the value flows into the DOM, and "the server sent it" is not a shape.
* A malformed or unexpected payload becomes a failure the page can report rather
* than an `undefined` rendered into the body.
*
* `bodyHtml` was sanitized on the server by `renderBody`, and it is the only
* field the page reads. Nothing widens that.
*/

export interface FormConfig {
bodyHtml: string;
}

export class ConfigError extends Error {
override name = "ConfigError";
}

export function parseConfig(text: string): FormConfig {
let decoded: unknown;
try {
decoded = JSON.parse(text);
} catch {
throw new ConfigError("the form configuration is not JSON");
}
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
throw new ConfigError("the form configuration is not an object");
}
if (!("bodyHtml" in decoded)) {
throw new ConfigError("the form configuration has no bodyHtml");
}
const { bodyHtml } = decoded;
if (typeof bodyHtml !== "string") {
throw new ConfigError("the form configuration's bodyHtml is not a string");
}
return { bodyHtml };
}
186 changes: 166 additions & 20 deletions packages/web/client/main.tsx
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,60 @@
/**
* The form page.
*
* Everything the page does happens inside one Effection scope, opened by `run()`
* at startup and closed when the tab goes away. That is not ceremony: an
* `XMLHttpRequest` started by a React callback outlives the callback, and without
* an owner it would keep pointing at a page that is being unloaded. The scope is
* the owner, and leaving it aborts whatever is still in flight.
*
* The scope stays open by waiting on `pagehide`. Returning from the root
* operation is what ends it — there is no `destroy()` to forget and no detached
* scope to leak.
*
* React callbacks run outside any operation, so they re-enter through the
* captured scope. Each re-entry contains its own failure: a task started with
* `scope.run()` that throws propagates into the scope and takes its siblings with
* it, which here would mean one failed submission killing the whole form.
*
* ## Order of appearance
*
* Nothing operable is shown until both halves are ready — the configuration and
* the precompiled validator. A form mounted before its validator would accept
* input it cannot check, and the person would find out only after submitting.
* Until then, and on any failure, the page shows fixed text: no author content,
* no server text, nothing executable.
*/

import { createElement } from "react";
import { createRoot } from "react-dom/client";
import type { RJSFSchema, UiSchema } from "@rjsf/utils";
import withTheme from "@rjsf/core/lib/withTheme.js";
import { generateTheme } from "@rjsf/shadcn/lib/Theme/index.js";
import createPrecompiledValidator from "@rjsf/validator-ajv8/lib/createPrecompiledValidator.js";
import type { ValidatorFunctions } from "@rjsf/validator-ajv8/lib/types.js";
import { action, run, useScope, withResolvers } from "effection";
import type { Operation, Scope } from "effection";

import { resolveHelper } from "./helpers.ts";
import { parseConfig } from "./config.ts";
import type { FormConfig } from "./config.ts";
import { outcomeFor, TRANSPORT_MESSAGE } from "./outcome.ts";
import type { Outcome } from "./outcome.ts";
import { get, postJson } from "./request.ts";

interface Registration {
validateFns: ValidatorFunctions;
rootSchema: RJSFSchema;
uiSchema?: UiSchema;
}

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

const STARTUP_FAILED =
"This form could not be prepared. Close this tab and run the workflow again.";

const Form = withTheme(generateTheme());

function mount(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
const validator = createPrecompiledValidator(validateFns, rootSchema);
const container = document.getElementById("root");
if (!container) {
throw new Error("the form container element #root is missing from the page shell");
}
createRoot(container).render(
createElement(Form, { schema: rootSchema, uiSchema: uiSchema ?? {}, validator }),
);
}

function loadValidator(): void {
const script = document.createElement("script");
script.src = "validator.js";
document.head.appendChild(script);
}
const registered = withResolvers<Registration>();

// Installed before the validator script is ever requested, so the script cannot
// arrive ahead of the bridge that receives it.
globalThis.__WEBFORM__ = {
resolveHelper,
register(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
mount(validateFns, rootSchema, uiSchema);
registered.resolve({ validateFns, rootSchema, uiSchema });
},
};

loadValidator();
function element(id: string): HTMLElement {
const found = document.getElementById(id);
if (!found) {
throw new Error(`the page shell is missing #${id}`);
}
return found;
}

/** Fixed text only. Author content never reaches the status region. */
function say(message: string): void {
element("status").textContent = message;
}

/**
* Load the validator script the server precompiled for this form.
*
* The page runs under `script-src 'self'` with no `unsafe-eval`, so a validator
* cannot be compiled here; it arrives as a same-origin script that calls back
* into the bridge. Loading it is an operation so a halt removes the element's
* listeners rather than leaving them attached to a page that is going away.
*/
function loadValidatorScript(): Operation<void> {
return action<void>((resolve, reject) => {
const script = document.createElement("script");
const onLoad = (): void => resolve();
const onError = (): void => reject(new Error("the validator script failed to load"));
script.addEventListener("load", onLoad);
script.addEventListener("error", onError);
script.src = "validator.js";
document.head.appendChild(script);
return () => {
script.removeEventListener("load", onLoad);
script.removeEventListener("error", onError);
};
});
}

/** Resolves when the tab is going away, which is what ends the scope. */
function untilPageHide(): Operation<void> {
return action<void>((resolve) => {
const onHide = (): void => resolve();
globalThis.addEventListener("pagehide", onHide);
return () => globalThis.removeEventListener("pagehide", onHide);
});
}

function* submit(formData: unknown): Operation<void> {
const result = yield* postJson("submit", JSON.stringify(formData ?? null));
apply(outcomeFor(result.status));
}

function apply(outcome: Outcome): void {
say(outcome.message);
if (!outcome.formUsable) {
element("root").setAttribute("hidden", "hidden");
}
if (outcome.closable) {
// A script can only close a window it opened, so this may do nothing at
// all. The message above is the actual fallback.
globalThis.close();
}
}

function mount(config: FormConfig, registration: Registration, scope: Scope): void {
// Sanitized on the server by `renderBody`. This is the only place author
// content enters the DOM.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
element("content").innerHTML = config.bodyHtml;

const validator = createPrecompiledValidator(registration.validateFns, registration.rootSchema);

createRoot(element("root")).render(
createElement(Form, {
schema: registration.rootSchema,
uiSchema: registration.uiSchema ?? {},
validator,
onSubmit: (event: { formData?: unknown }) => {
// React calls this outside any operation. Re-entering through the
// captured scope gives the request an owner; catching inside keeps a
// failed submission from tearing the scope down with it.
scope.run(function* () {
try {
yield* submit(event.formData);
} catch {
say(TRANSPORT_MESSAGE);
}
});
},
}),
);
}

function* start(): Operation<void> {
const scope = yield* useScope();

const response = yield* get("config.json");
if (response.status !== 200) {
throw new Error(`the form configuration could not be loaded (${response.status})`);
}
const config = parseConfig(response.body);

yield* loadValidatorScript();
const registration = yield* registered.operation;

mount(config, registration, scope);
}

run(function* () {
try {
yield* start();
} catch {
// Fixed text, never the failure's own message: nothing the server or the
// author wrote is rendered on a path that has already gone wrong.
say(STARTUP_FAILED);
return;
}
yield* untilPageHide();
});
51 changes: 51 additions & 0 deletions packages/web/client/outcome.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
/**
* What a person is told after submitting, and whether they can try again.
*
* Three of these are ordinary and one is not. A 204 means the workflow has the
* answer and this tab has no further purpose. A 409 means the form was already
* answered — by another tab, or by this one before a reload — and nothing the
* person does here will change that. A 422 or a transport failure is the only
* case where trying again makes sense, so it is the only case that leaves the
* form usable.
*
* Pure and free of the DOM, so the mapping is tested directly rather than
* inferred from what a page rendered.
*/

export type OutcomeKind = "accepted" | "already-submitted" | "retryable";

export interface Outcome {
kind: OutcomeKind;
message: string;
/** Whether the person can correct their answer and submit again. */
formUsable: boolean;
/** Whether this tab has finished its job and may close. */
closable: boolean;
}

export const ACCEPTED_MESSAGE = "Submission received. You can safely close this tab.";
export const ALREADY_SUBMITTED_MESSAGE =
"This form was already submitted. You can safely close this tab.";
export const INVALID_MESSAGE = "The server rejected this submission. Correct it and try again.";
export const TRANSPORT_MESSAGE = "The submission could not be delivered. Try again.";

export function outcomeFor(status: number): Outcome {
if (status === 204) {
return { kind: "accepted", message: ACCEPTED_MESSAGE, formUsable: false, closable: true };
}
if (status === 409) {
return {
kind: "already-submitted",
message: ALREADY_SUBMITTED_MESSAGE,
formUsable: false,
closable: true,
};
}
if (status === 422) {
return { kind: "retryable", message: INVALID_MESSAGE, formUsable: true, closable: false };
}
// Everything else — a refused origin, a media-type rejection, a size refusal,
// a dead connection reported as status 0 — is something the person may be able
// to get past, and none of it is a reason to take their answer away.
return { kind: "retryable", message: TRANSPORT_MESSAGE, formUsable: true, closable: false };
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all \u003cpre\u003e\u003ccode\u003e blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks"); } } catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); } })(); (function(){ try { var __m = "github.com"; var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions packages/web/client/config.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
/**
* The configuration the page fetches, validated before it is believed.
*
* The response comes from this WebForm's own server, but the page checks it
* anyway: the value flows into the DOM, and "the server sent it" is not a shape.
* A malformed or unexpected payload becomes a failure the page can report rather
* than an `undefined` rendered into the body.
*
* `bodyHtml` was sanitized on the server by `renderBody`, and it is the only
* field the page reads. Nothing widens that.
*/

export interface FormConfig {
bodyHtml: string;
}

export class ConfigError extends Error {
override name = "ConfigError";
}

export function parseConfig(text: string): FormConfig {
let decoded: unknown;
try {
decoded = JSON.parse(text);
} catch {
throw new ConfigError("the form configuration is not JSON");
}
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
throw new ConfigError("the form configuration is not an object");
}
if (!("bodyHtml" in decoded)) {
throw new ConfigError("the form configuration has no bodyHtml");
}
const { bodyHtml } = decoded;
if (typeof bodyHtml !== "string") {
throw new ConfigError("the form configuration's bodyHtml is not a string");
}
return { bodyHtml };
}
186 changes: 166 additions & 20 deletions packages/web/client/main.tsx
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,60 @@
/**
* The form page.
*
* Everything the page does happens inside one Effection scope, opened by `run()`
* at startup and closed when the tab goes away. That is not ceremony: an
* `XMLHttpRequest` started by a React callback outlives the callback, and without
* an owner it would keep pointing at a page that is being unloaded. The scope is
* the owner, and leaving it aborts whatever is still in flight.
*
* The scope stays open by waiting on `pagehide`. Returning from the root
* operation is what ends it — there is no `destroy()` to forget and no detached
* scope to leak.
*
* React callbacks run outside any operation, so they re-enter through the
* captured scope. Each re-entry contains its own failure: a task started with
* `scope.run()` that throws propagates into the scope and takes its siblings with
* it, which here would mean one failed submission killing the whole form.
*
* ## Order of appearance
*
* Nothing operable is shown until both halves are ready — the configuration and
* the precompiled validator. A form mounted before its validator would accept
* input it cannot check, and the person would find out only after submitting.
* Until then, and on any failure, the page shows fixed text: no author content,
* no server text, nothing executable.
*/

import { createElement } from "react";
import { createRoot } from "react-dom/client";
import type { RJSFSchema, UiSchema } from "@rjsf/utils";
import withTheme from "@rjsf/core/lib/withTheme.js";
import { generateTheme } from "@rjsf/shadcn/lib/Theme/index.js";
import createPrecompiledValidator from "@rjsf/validator-ajv8/lib/createPrecompiledValidator.js";
import type { ValidatorFunctions } from "@rjsf/validator-ajv8/lib/types.js";
import { action, run, useScope, withResolvers } from "effection";
import type { Operation, Scope } from "effection";

import { resolveHelper } from "./helpers.ts";
import { parseConfig } from "./config.ts";
import type { FormConfig } from "./config.ts";
import { outcomeFor, TRANSPORT_MESSAGE } from "./outcome.ts";
import type { Outcome } from "./outcome.ts";
import { get, postJson } from "./request.ts";

interface Registration {
validateFns: ValidatorFunctions;
rootSchema: RJSFSchema;
uiSchema?: UiSchema;
}

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

const STARTUP_FAILED =
"This form could not be prepared. Close this tab and run the workflow again.";

const Form = withTheme(generateTheme());

function mount(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
const validator = createPrecompiledValidator(validateFns, rootSchema);
const container = document.getElementById("root");
if (!container) {
throw new Error("the form container element #root is missing from the page shell");
}
createRoot(container).render(
createElement(Form, { schema: rootSchema, uiSchema: uiSchema ?? {}, validator }),
);
}

function loadValidator(): void {
const script = document.createElement("script");
script.src = "validator.js";
document.head.appendChild(script);
}
const registered = withResolvers<Registration>();

// Installed before the validator script is ever requested, so the script cannot
// arrive ahead of the bridge that receives it.
globalThis.__WEBFORM__ = {
resolveHelper,
register(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
mount(validateFns, rootSchema, uiSchema);
registered.resolve({ validateFns, rootSchema, uiSchema });
},
};

loadValidator();
function element(id: string): HTMLElement {
const found = document.getElementById(id);
if (!found) {
throw new Error(`the page shell is missing #${id}`);
}
return found;
}

/** Fixed text only. Author content never reaches the status region. */
function say(message: string): void {
element("status").textContent = message;
}

/**
* Load the validator script the server precompiled for this form.
*
* The page runs under `script-src 'self'` with no `unsafe-eval`, so a validator
* cannot be compiled here; it arrives as a same-origin script that calls back
* into the bridge. Loading it is an operation so a halt removes the element's
* listeners rather than leaving them attached to a page that is going away.
*/
function loadValidatorScript(): Operation<void> {
return action<void>((resolve, reject) => {
const script = document.createElement("script");
const onLoad = (): void => resolve();
const onError = (): void => reject(new Error("the validator script failed to load"));
script.addEventListener("load", onLoad);
script.addEventListener("error", onError);
script.src = "validator.js";
document.head.appendChild(script);
return () => {
script.removeEventListener("load", onLoad);
script.removeEventListener("error", onError);
};
});
}

/** Resolves when the tab is going away, which is what ends the scope. */
function untilPageHide(): Operation<void> {
return action<void>((resolve) => {
const onHide = (): void => resolve();
globalThis.addEventListener("pagehide", onHide);
return () => globalThis.removeEventListener("pagehide", onHide);
});
}

function* submit(formData: unknown): Operation<void> {
const result = yield* postJson("submit", JSON.stringify(formData ?? null));
apply(outcomeFor(result.status));
}

function apply(outcome: Outcome): void {
say(outcome.message);
if (!outcome.formUsable) {
element("root").setAttribute("hidden", "hidden");
}
if (outcome.closable) {
// A script can only close a window it opened, so this may do nothing at
// all. The message above is the actual fallback.
globalThis.close();
}
}

function mount(config: FormConfig, registration: Registration, scope: Scope): void {
// Sanitized on the server by `renderBody`. This is the only place author
// content enters the DOM.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
element("content").innerHTML = config.bodyHtml;

const validator = createPrecompiledValidator(registration.validateFns, registration.rootSchema);

createRoot(element("root")).render(
createElement(Form, {
schema: registration.rootSchema,
uiSchema: registration.uiSchema ?? {},
validator,
onSubmit: (event: { formData?: unknown }) => {
// React calls this outside any operation. Re-entering through the
// captured scope gives the request an owner; catching inside keeps a
// failed submission from tearing the scope down with it.
scope.run(function* () {
try {
yield* submit(event.formData);
} catch {
say(TRANSPORT_MESSAGE);
}
});
},
}),
);
}

function* start(): Operation<void> {
const scope = yield* useScope();

const response = yield* get("config.json");
if (response.status !== 200) {
throw new Error(`the form configuration could not be loaded (${response.status})`);
}
const config = parseConfig(response.body);

yield* loadValidatorScript();
const registration = yield* registered.operation;

mount(config, registration, scope);
}

run(function* () {
try {
yield* start();
} catch {
// Fixed text, never the failure's own message: nothing the server or the
// author wrote is rendered on a path that has already gone wrong.
say(STARTUP_FAILED);
return;
}
yield* untilPageHide();
});
51 changes: 51 additions & 0 deletions packages/web/client/outcome.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
/**
* What a person is told after submitting, and whether they can try again.
*
* Three of these are ordinary and one is not. A 204 means the workflow has the
* answer and this tab has no further purpose. A 409 means the form was already
* answered — by another tab, or by this one before a reload — and nothing the
* person does here will change that. A 422 or a transport failure is the only
* case where trying again makes sense, so it is the only case that leaves the
* form usable.
*
* Pure and free of the DOM, so the mapping is tested directly rather than
* inferred from what a page rendered.
*/

export type OutcomeKind = "accepted" | "already-submitted" | "retryable";

export interface Outcome {
kind: OutcomeKind;
message: string;
/** Whether the person can correct their answer and submit again. */
formUsable: boolean;
/** Whether this tab has finished its job and may close. */
closable: boolean;
}

export const ACCEPTED_MESSAGE = "Submission received. You can safely close this tab.";
export const ALREADY_SUBMITTED_MESSAGE =
"This form was already submitted. You can safely close this tab.";
export const INVALID_MESSAGE = "The server rejected this submission. Correct it and try again.";
export const TRANSPORT_MESSAGE = "The submission could not be delivered. Try again.";

export function outcomeFor(status: number): Outcome {
if (status === 204) {
return { kind: "accepted", message: ACCEPTED_MESSAGE, formUsable: false, closable: true };
}
if (status === 409) {
return {
kind: "already-submitted",
message: ALREADY_SUBMITTED_MESSAGE,
formUsable: false,
closable: true,
};
}
if (status === 422) {
return { kind: "retryable", message: INVALID_MESSAGE, formUsable: true, closable: false };
}
// Everything else — a refused origin, a media-type rejection, a size refusal,
// a dead connection reported as status 0 — is something the person may be able
// to get past, and none of it is a reason to take their answer away.
return { kind: "retryable", message: TRANSPORT_MESSAGE, formUsable: true, closable: false };
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions packages/web/client/config.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
/**
* The configuration the page fetches, validated before it is believed.
*
* The response comes from this WebForm's own server, but the page checks it
* anyway: the value flows into the DOM, and "the server sent it" is not a shape.
* A malformed or unexpected payload becomes a failure the page can report rather
* than an `undefined` rendered into the body.
*
* `bodyHtml` was sanitized on the server by `renderBody`, and it is the only
* field the page reads. Nothing widens that.
*/

export interface FormConfig {
bodyHtml: string;
}

export class ConfigError extends Error {
override name = "ConfigError";
}

export function parseConfig(text: string): FormConfig {
let decoded: unknown;
try {
decoded = JSON.parse(text);
} catch {
throw new ConfigError("the form configuration is not JSON");
}
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
throw new ConfigError("the form configuration is not an object");
}
if (!("bodyHtml" in decoded)) {
throw new ConfigError("the form configuration has no bodyHtml");
}
const { bodyHtml } = decoded;
if (typeof bodyHtml !== "string") {
throw new ConfigError("the form configuration's bodyHtml is not a string");
}
return { bodyHtml };
}
186 changes: 166 additions & 20 deletions packages/web/client/main.tsx
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,60 @@
/**
* The form page.
*
* Everything the page does happens inside one Effection scope, opened by `run()`
* at startup and closed when the tab goes away. That is not ceremony: an
* `XMLHttpRequest` started by a React callback outlives the callback, and without
* an owner it would keep pointing at a page that is being unloaded. The scope is
* the owner, and leaving it aborts whatever is still in flight.
*
* The scope stays open by waiting on `pagehide`. Returning from the root
* operation is what ends it — there is no `destroy()` to forget and no detached
* scope to leak.
*
* React callbacks run outside any operation, so they re-enter through the
* captured scope. Each re-entry contains its own failure: a task started with
* `scope.run()` that throws propagates into the scope and takes its siblings with
* it, which here would mean one failed submission killing the whole form.
*
* ## Order of appearance
*
* Nothing operable is shown until both halves are ready — the configuration and
* the precompiled validator. A form mounted before its validator would accept
* input it cannot check, and the person would find out only after submitting.
* Until then, and on any failure, the page shows fixed text: no author content,
* no server text, nothing executable.
*/

import { createElement } from "react";
import { createRoot } from "react-dom/client";
import type { RJSFSchema, UiSchema } from "@rjsf/utils";
import withTheme from "@rjsf/core/lib/withTheme.js";
import { generateTheme } from "@rjsf/shadcn/lib/Theme/index.js";
import createPrecompiledValidator from "@rjsf/validator-ajv8/lib/createPrecompiledValidator.js";
import type { ValidatorFunctions } from "@rjsf/validator-ajv8/lib/types.js";
import { action, run, useScope, withResolvers } from "effection";
import type { Operation, Scope } from "effection";

import { resolveHelper } from "./helpers.ts";
import { parseConfig } from "./config.ts";
import type { FormConfig } from "./config.ts";
import { outcomeFor, TRANSPORT_MESSAGE } from "./outcome.ts";
import type { Outcome } from "./outcome.ts";
import { get, postJson } from "./request.ts";

interface Registration {
validateFns: ValidatorFunctions;
rootSchema: RJSFSchema;
uiSchema?: UiSchema;
}

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

const STARTUP_FAILED =
"This form could not be prepared. Close this tab and run the workflow again.";

const Form = withTheme(generateTheme());

function mount(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
const validator = createPrecompiledValidator(validateFns, rootSchema);
const container = document.getElementById("root");
if (!container) {
throw new Error("the form container element #root is missing from the page shell");
}
createRoot(container).render(
createElement(Form, { schema: rootSchema, uiSchema: uiSchema ?? {}, validator }),
);
}

function loadValidator(): void {
const script = document.createElement("script");
script.src = "validator.js";
document.head.appendChild(script);
}
const registered = withResolvers<Registration>();

// Installed before the validator script is ever requested, so the script cannot
// arrive ahead of the bridge that receives it.
globalThis.__WEBFORM__ = {
resolveHelper,
register(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
mount(validateFns, rootSchema, uiSchema);
registered.resolve({ validateFns, rootSchema, uiSchema });
},
};

loadValidator();
function element(id: string): HTMLElement {
const found = document.getElementById(id);
if (!found) {
throw new Error(`the page shell is missing #${id}`);
}
return found;
}

/** Fixed text only. Author content never reaches the status region. */
function say(message: string): void {
element("status").textContent = message;
}

/**
* Load the validator script the server precompiled for this form.
*
* The page runs under `script-src 'self'` with no `unsafe-eval`, so a validator
* cannot be compiled here; it arrives as a same-origin script that calls back
* into the bridge. Loading it is an operation so a halt removes the element's
* listeners rather than leaving them attached to a page that is going away.
*/
function loadValidatorScript(): Operation<void> {
return action<void>((resolve, reject) => {
const script = document.createElement("script");
const onLoad = (): void => resolve();
const onError = (): void => reject(new Error("the validator script failed to load"));
script.addEventListener("load", onLoad);
script.addEventListener("error", onError);
script.src = "validator.js";
document.head.appendChild(script);
return () => {
script.removeEventListener("load", onLoad);
script.removeEventListener("error", onError);
};
});
}

/** Resolves when the tab is going away, which is what ends the scope. */
function untilPageHide(): Operation<void> {
return action<void>((resolve) => {
const onHide = (): void => resolve();
globalThis.addEventListener("pagehide", onHide);
return () => globalThis.removeEventListener("pagehide", onHide);
});
}

function* submit(formData: unknown): Operation<void> {
const result = yield* postJson("submit", JSON.stringify(formData ?? null));
apply(outcomeFor(result.status));
}

function apply(outcome: Outcome): void {
say(outcome.message);
if (!outcome.formUsable) {
element("root").setAttribute("hidden", "hidden");
}
if (outcome.closable) {
// A script can only close a window it opened, so this may do nothing at
// all. The message above is the actual fallback.
globalThis.close();
}
}

function mount(config: FormConfig, registration: Registration, scope: Scope): void {
// Sanitized on the server by `renderBody`. This is the only place author
// content enters the DOM.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
element("content").innerHTML = config.bodyHtml;

const validator = createPrecompiledValidator(registration.validateFns, registration.rootSchema);

createRoot(element("root")).render(
createElement(Form, {
schema: registration.rootSchema,
uiSchema: registration.uiSchema ?? {},
validator,
onSubmit: (event: { formData?: unknown }) => {
// React calls this outside any operation. Re-entering through the
// captured scope gives the request an owner; catching inside keeps a
// failed submission from tearing the scope down with it.
scope.run(function* () {
try {
yield* submit(event.formData);
} catch {
say(TRANSPORT_MESSAGE);
}
});
},
}),
);
}

function* start(): Operation<void> {
const scope = yield* useScope();

const response = yield* get("config.json");
if (response.status !== 200) {
throw new Error(`the form configuration could not be loaded (${response.status})`);
}
const config = parseConfig(response.body);

yield* loadValidatorScript();
const registration = yield* registered.operation;

mount(config, registration, scope);
}

run(function* () {
try {
yield* start();
} catch {
// Fixed text, never the failure's own message: nothing the server or the
// author wrote is rendered on a path that has already gone wrong.
say(STARTUP_FAILED);
return;
}
yield* untilPageHide();
});
51 changes: 51 additions & 0 deletions packages/web/client/outcome.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
/**
* What a person is told after submitting, and whether they can try again.
*
* Three of these are ordinary and one is not. A 204 means the workflow has the
* answer and this tab has no further purpose. A 409 means the form was already
* answered — by another tab, or by this one before a reload — and nothing the
* person does here will change that. A 422 or a transport failure is the only
* case where trying again makes sense, so it is the only case that leaves the
* form usable.
*
* Pure and free of the DOM, so the mapping is tested directly rather than
* inferred from what a page rendered.
*/

export type OutcomeKind = "accepted" | "already-submitted" | "retryable";

export interface Outcome {
kind: OutcomeKind;
message: string;
/** Whether the person can correct their answer and submit again. */
formUsable: boolean;
/** Whether this tab has finished its job and may close. */
closable: boolean;
}

export const ACCEPTED_MESSAGE = "Submission received. You can safely close this tab.";
export const ALREADY_SUBMITTED_MESSAGE =
"This form was already submitted. You can safely close this tab.";
export const INVALID_MESSAGE = "The server rejected this submission. Correct it and try again.";
export const TRANSPORT_MESSAGE = "The submission could not be delivered. Try again.";

export function outcomeFor(status: number): Outcome {
if (status === 204) {
return { kind: "accepted", message: ACCEPTED_MESSAGE, formUsable: false, closable: true };
}
if (status === 409) {
return {
kind: "already-submitted",
message: ALREADY_SUBMITTED_MESSAGE,
formUsable: false,
closable: true,
};
}
if (status === 422) {
return { kind: "retryable", message: INVALID_MESSAGE, formUsable: true, closable: false };
}
// Everything else — a refused origin, a media-type rejection, a size refusal,
// a dead connection reported as status 0 — is something the person may be able
// to get past, and none of it is a reason to take their answer away.
return { kind: "retryable", message: TRANSPORT_MESSAGE, formUsable: true, closable: false };
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length \u003e 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions packages/web/client/config.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
/**
* The configuration the page fetches, validated before it is believed.
*
* The response comes from this WebForm's own server, but the page checks it
* anyway: the value flows into the DOM, and "the server sent it" is not a shape.
* A malformed or unexpected payload becomes a failure the page can report rather
* than an `undefined` rendered into the body.
*
* `bodyHtml` was sanitized on the server by `renderBody`, and it is the only
* field the page reads. Nothing widens that.
*/

export interface FormConfig {
bodyHtml: string;
}

export class ConfigError extends Error {
override name = "ConfigError";
}

export function parseConfig(text: string): FormConfig {
let decoded: unknown;
try {
decoded = JSON.parse(text);
} catch {
throw new ConfigError("the form configuration is not JSON");
}
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
throw new ConfigError("the form configuration is not an object");
}
if (!("bodyHtml" in decoded)) {
throw new ConfigError("the form configuration has no bodyHtml");
}
const { bodyHtml } = decoded;
if (typeof bodyHtml !== "string") {
throw new ConfigError("the form configuration's bodyHtml is not a string");
}
return { bodyHtml };
}
186 changes: 166 additions & 20 deletions packages/web/client/main.tsx
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,60 @@
/**
* The form page.
*
* Everything the page does happens inside one Effection scope, opened by `run()`
* at startup and closed when the tab goes away. That is not ceremony: an
* `XMLHttpRequest` started by a React callback outlives the callback, and without
* an owner it would keep pointing at a page that is being unloaded. The scope is
* the owner, and leaving it aborts whatever is still in flight.
*
* The scope stays open by waiting on `pagehide`. Returning from the root
* operation is what ends it — there is no `destroy()` to forget and no detached
* scope to leak.
*
* React callbacks run outside any operation, so they re-enter through the
* captured scope. Each re-entry contains its own failure: a task started with
* `scope.run()` that throws propagates into the scope and takes its siblings with
* it, which here would mean one failed submission killing the whole form.
*
* ## Order of appearance
*
* Nothing operable is shown until both halves are ready — the configuration and
* the precompiled validator. A form mounted before its validator would accept
* input it cannot check, and the person would find out only after submitting.
* Until then, and on any failure, the page shows fixed text: no author content,
* no server text, nothing executable.
*/

import { createElement } from "react";
import { createRoot } from "react-dom/client";
import type { RJSFSchema, UiSchema } from "@rjsf/utils";
import withTheme from "@rjsf/core/lib/withTheme.js";
import { generateTheme } from "@rjsf/shadcn/lib/Theme/index.js";
import createPrecompiledValidator from "@rjsf/validator-ajv8/lib/createPrecompiledValidator.js";
import type { ValidatorFunctions } from "@rjsf/validator-ajv8/lib/types.js";
import { action, run, useScope, withResolvers } from "effection";
import type { Operation, Scope } from "effection";

import { resolveHelper } from "./helpers.ts";
import { parseConfig } from "./config.ts";
import type { FormConfig } from "./config.ts";
import { outcomeFor, TRANSPORT_MESSAGE } from "./outcome.ts";
import type { Outcome } from "./outcome.ts";
import { get, postJson } from "./request.ts";

interface Registration {
validateFns: ValidatorFunctions;
rootSchema: RJSFSchema;
uiSchema?: UiSchema;
}

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

const STARTUP_FAILED =
"This form could not be prepared. Close this tab and run the workflow again.";

const Form = withTheme(generateTheme());

function mount(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
const validator = createPrecompiledValidator(validateFns, rootSchema);
const container = document.getElementById("root");
if (!container) {
throw new Error("the form container element #root is missing from the page shell");
}
createRoot(container).render(
createElement(Form, { schema: rootSchema, uiSchema: uiSchema ?? {}, validator }),
);
}

function loadValidator(): void {
const script = document.createElement("script");
script.src = "validator.js";
document.head.appendChild(script);
}
const registered = withResolvers<Registration>();

// Installed before the validator script is ever requested, so the script cannot
// arrive ahead of the bridge that receives it.
globalThis.__WEBFORM__ = {
resolveHelper,
register(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
mount(validateFns, rootSchema, uiSchema);
registered.resolve({ validateFns, rootSchema, uiSchema });
},
};

loadValidator();
function element(id: string): HTMLElement {
const found = document.getElementById(id);
if (!found) {
throw new Error(`the page shell is missing #${id}`);
}
return found;
}

/** Fixed text only. Author content never reaches the status region. */
function say(message: string): void {
element("status").textContent = message;
}

/**
* Load the validator script the server precompiled for this form.
*
* The page runs under `script-src 'self'` with no `unsafe-eval`, so a validator
* cannot be compiled here; it arrives as a same-origin script that calls back
* into the bridge. Loading it is an operation so a halt removes the element's
* listeners rather than leaving them attached to a page that is going away.
*/
function loadValidatorScript(): Operation<void> {
return action<void>((resolve, reject) => {
const script = document.createElement("script");
const onLoad = (): void => resolve();
const onError = (): void => reject(new Error("the validator script failed to load"));
script.addEventListener("load", onLoad);
script.addEventListener("error", onError);
script.src = "validator.js";
document.head.appendChild(script);
return () => {
script.removeEventListener("load", onLoad);
script.removeEventListener("error", onError);
};
});
}

/** Resolves when the tab is going away, which is what ends the scope. */
function untilPageHide(): Operation<void> {
return action<void>((resolve) => {
const onHide = (): void => resolve();
globalThis.addEventListener("pagehide", onHide);
return () => globalThis.removeEventListener("pagehide", onHide);
});
}

function* submit(formData: unknown): Operation<void> {
const result = yield* postJson("submit", JSON.stringify(formData ?? null));
apply(outcomeFor(result.status));
}

function apply(outcome: Outcome): void {
say(outcome.message);
if (!outcome.formUsable) {
element("root").setAttribute("hidden", "hidden");
}
if (outcome.closable) {
// A script can only close a window it opened, so this may do nothing at
// all. The message above is the actual fallback.
globalThis.close();
}
}

function mount(config: FormConfig, registration: Registration, scope: Scope): void {
// Sanitized on the server by `renderBody`. This is the only place author
// content enters the DOM.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
element("content").innerHTML = config.bodyHtml;

const validator = createPrecompiledValidator(registration.validateFns, registration.rootSchema);

createRoot(element("root")).render(
createElement(Form, {
schema: registration.rootSchema,
uiSchema: registration.uiSchema ?? {},
validator,
onSubmit: (event: { formData?: unknown }) => {
// React calls this outside any operation. Re-entering through the
// captured scope gives the request an owner; catching inside keeps a
// failed submission from tearing the scope down with it.
scope.run(function* () {
try {
yield* submit(event.formData);
} catch {
say(TRANSPORT_MESSAGE);
}
});
},
}),
);
}

function* start(): Operation<void> {
const scope = yield* useScope();

const response = yield* get("config.json");
if (response.status !== 200) {
throw new Error(`the form configuration could not be loaded (${response.status})`);
}
const config = parseConfig(response.body);

yield* loadValidatorScript();
const registration = yield* registered.operation;

mount(config, registration, scope);
}

run(function* () {
try {
yield* start();
} catch {
// Fixed text, never the failure's own message: nothing the server or the
// author wrote is rendered on a path that has already gone wrong.
say(STARTUP_FAILED);
return;
}
yield* untilPageHide();
});
51 changes: 51 additions & 0 deletions packages/web/client/outcome.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
/**
* What a person is told after submitting, and whether they can try again.
*
* Three of these are ordinary and one is not. A 204 means the workflow has the
* answer and this tab has no further purpose. A 409 means the form was already
* answered — by another tab, or by this one before a reload — and nothing the
* person does here will change that. A 422 or a transport failure is the only
* case where trying again makes sense, so it is the only case that leaves the
* form usable.
*
* Pure and free of the DOM, so the mapping is tested directly rather than
* inferred from what a page rendered.
*/

export type OutcomeKind = "accepted" | "already-submitted" | "retryable";

export interface Outcome {
kind: OutcomeKind;
message: string;
/** Whether the person can correct their answer and submit again. */
formUsable: boolean;
/** Whether this tab has finished its job and may close. */
closable: boolean;
}

export const ACCEPTED_MESSAGE = "Submission received. You can safely close this tab.";
export const ALREADY_SUBMITTED_MESSAGE =
"This form was already submitted. You can safely close this tab.";
export const INVALID_MESSAGE = "The server rejected this submission. Correct it and try again.";
export const TRANSPORT_MESSAGE = "The submission could not be delivered. Try again.";

export function outcomeFor(status: number): Outcome {
if (status === 204) {
return { kind: "accepted", message: ACCEPTED_MESSAGE, formUsable: false, closable: true };
}
if (status === 409) {
return {
kind: "already-submitted",
message: ALREADY_SUBMITTED_MESSAGE,
formUsable: false,
closable: true,
};
}
if (status === 422) {
return { kind: "retryable", message: INVALID_MESSAGE, formUsable: true, closable: false };
}
// Everything else — a refused origin, a media-type rejection, a size refusal,
// a dead connection reported as status 0 — is something the person may be able
// to get past, and none of it is a reason to take their answer away.
return { kind: "retryable", message: TRANSPORT_MESSAGE, formUsable: true, closable: false };
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions packages/web/client/config.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
/**
* The configuration the page fetches, validated before it is believed.
*
* The response comes from this WebForm's own server, but the page checks it
* anyway: the value flows into the DOM, and "the server sent it" is not a shape.
* A malformed or unexpected payload becomes a failure the page can report rather
* than an `undefined` rendered into the body.
*
* `bodyHtml` was sanitized on the server by `renderBody`, and it is the only
* field the page reads. Nothing widens that.
*/

export interface FormConfig {
bodyHtml: string;
}

export class ConfigError extends Error {
override name = "ConfigError";
}

export function parseConfig(text: string): FormConfig {
let decoded: unknown;
try {
decoded = JSON.parse(text);
} catch {
throw new ConfigError("the form configuration is not JSON");
}
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
throw new ConfigError("the form configuration is not an object");
}
if (!("bodyHtml" in decoded)) {
throw new ConfigError("the form configuration has no bodyHtml");
}
const { bodyHtml } = decoded;
if (typeof bodyHtml !== "string") {
throw new ConfigError("the form configuration's bodyHtml is not a string");
}
return { bodyHtml };
}
186 changes: 166 additions & 20 deletions packages/web/client/main.tsx
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,60 @@
/**
* The form page.
*
* Everything the page does happens inside one Effection scope, opened by `run()`
* at startup and closed when the tab goes away. That is not ceremony: an
* `XMLHttpRequest` started by a React callback outlives the callback, and without
* an owner it would keep pointing at a page that is being unloaded. The scope is
* the owner, and leaving it aborts whatever is still in flight.
*
* The scope stays open by waiting on `pagehide`. Returning from the root
* operation is what ends it — there is no `destroy()` to forget and no detached
* scope to leak.
*
* React callbacks run outside any operation, so they re-enter through the
* captured scope. Each re-entry contains its own failure: a task started with
* `scope.run()` that throws propagates into the scope and takes its siblings with
* it, which here would mean one failed submission killing the whole form.
*
* ## Order of appearance
*
* Nothing operable is shown until both halves are ready — the configuration and
* the precompiled validator. A form mounted before its validator would accept
* input it cannot check, and the person would find out only after submitting.
* Until then, and on any failure, the page shows fixed text: no author content,
* no server text, nothing executable.
*/

import { createElement } from "react";
import { createRoot } from "react-dom/client";
import type { RJSFSchema, UiSchema } from "@rjsf/utils";
import withTheme from "@rjsf/core/lib/withTheme.js";
import { generateTheme } from "@rjsf/shadcn/lib/Theme/index.js";
import createPrecompiledValidator from "@rjsf/validator-ajv8/lib/createPrecompiledValidator.js";
import type { ValidatorFunctions } from "@rjsf/validator-ajv8/lib/types.js";
import { action, run, useScope, withResolvers } from "effection";
import type { Operation, Scope } from "effection";

import { resolveHelper } from "./helpers.ts";
import { parseConfig } from "./config.ts";
import type { FormConfig } from "./config.ts";
import { outcomeFor, TRANSPORT_MESSAGE } from "./outcome.ts";
import type { Outcome } from "./outcome.ts";
import { get, postJson } from "./request.ts";

interface Registration {
validateFns: ValidatorFunctions;
rootSchema: RJSFSchema;
uiSchema?: UiSchema;
}

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

const STARTUP_FAILED =
"This form could not be prepared. Close this tab and run the workflow again.";

const Form = withTheme(generateTheme());

function mount(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
const validator = createPrecompiledValidator(validateFns, rootSchema);
const container = document.getElementById("root");
if (!container) {
throw new Error("the form container element #root is missing from the page shell");
}
createRoot(container).render(
createElement(Form, { schema: rootSchema, uiSchema: uiSchema ?? {}, validator }),
);
}

function loadValidator(): void {
const script = document.createElement("script");
script.src = "validator.js";
document.head.appendChild(script);
}
const registered = withResolvers<Registration>();

// Installed before the validator script is ever requested, so the script cannot
// arrive ahead of the bridge that receives it.
globalThis.__WEBFORM__ = {
resolveHelper,
register(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
mount(validateFns, rootSchema, uiSchema);
registered.resolve({ validateFns, rootSchema, uiSchema });
},
};

loadValidator();
function element(id: string): HTMLElement {
const found = document.getElementById(id);
if (!found) {
throw new Error(`the page shell is missing #${id}`);
}
return found;
}

/** Fixed text only. Author content never reaches the status region. */
function say(message: string): void {
element("status").textContent = message;
}

/**
* Load the validator script the server precompiled for this form.
*
* The page runs under `script-src 'self'` with no `unsafe-eval`, so a validator
* cannot be compiled here; it arrives as a same-origin script that calls back
* into the bridge. Loading it is an operation so a halt removes the element's
* listeners rather than leaving them attached to a page that is going away.
*/
function loadValidatorScript(): Operation<void> {
return action<void>((resolve, reject) => {
const script = document.createElement("script");
const onLoad = (): void => resolve();
const onError = (): void => reject(new Error("the validator script failed to load"));
script.addEventListener("load", onLoad);
script.addEventListener("error", onError);
script.src = "validator.js";
document.head.appendChild(script);
return () => {
script.removeEventListener("load", onLoad);
script.removeEventListener("error", onError);
};
});
}

/** Resolves when the tab is going away, which is what ends the scope. */
function untilPageHide(): Operation<void> {
return action<void>((resolve) => {
const onHide = (): void => resolve();
globalThis.addEventListener("pagehide", onHide);
return () => globalThis.removeEventListener("pagehide", onHide);
});
}

function* submit(formData: unknown): Operation<void> {
const result = yield* postJson("submit", JSON.stringify(formData ?? null));
apply(outcomeFor(result.status));
}

function apply(outcome: Outcome): void {
say(outcome.message);
if (!outcome.formUsable) {
element("root").setAttribute("hidden", "hidden");
}
if (outcome.closable) {
// A script can only close a window it opened, so this may do nothing at
// all. The message above is the actual fallback.
globalThis.close();
}
}

function mount(config: FormConfig, registration: Registration, scope: Scope): void {
// Sanitized on the server by `renderBody`. This is the only place author
// content enters the DOM.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
element("content").innerHTML = config.bodyHtml;

const validator = createPrecompiledValidator(registration.validateFns, registration.rootSchema);

createRoot(element("root")).render(
createElement(Form, {
schema: registration.rootSchema,
uiSchema: registration.uiSchema ?? {},
validator,
onSubmit: (event: { formData?: unknown }) => {
// React calls this outside any operation. Re-entering through the
// captured scope gives the request an owner; catching inside keeps a
// failed submission from tearing the scope down with it.
scope.run(function* () {
try {
yield* submit(event.formData);
} catch {
say(TRANSPORT_MESSAGE);
}
});
},
}),
);
}

function* start(): Operation<void> {
const scope = yield* useScope();

const response = yield* get("config.json");
if (response.status !== 200) {
throw new Error(`the form configuration could not be loaded (${response.status})`);
}
const config = parseConfig(response.body);

yield* loadValidatorScript();
const registration = yield* registered.operation;

mount(config, registration, scope);
}

run(function* () {
try {
yield* start();
} catch {
// Fixed text, never the failure's own message: nothing the server or the
// author wrote is rendered on a path that has already gone wrong.
say(STARTUP_FAILED);
return;
}
yield* untilPageHide();
});
51 changes: 51 additions & 0 deletions packages/web/client/outcome.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
/**
* What a person is told after submitting, and whether they can try again.
*
* Three of these are ordinary and one is not. A 204 means the workflow has the
* answer and this tab has no further purpose. A 409 means the form was already
* answered — by another tab, or by this one before a reload — and nothing the
* person does here will change that. A 422 or a transport failure is the only
* case where trying again makes sense, so it is the only case that leaves the
* form usable.
*
* Pure and free of the DOM, so the mapping is tested directly rather than
* inferred from what a page rendered.
*/

export type OutcomeKind = "accepted" | "already-submitted" | "retryable";

export interface Outcome {
kind: OutcomeKind;
message: string;
/** Whether the person can correct their answer and submit again. */
formUsable: boolean;
/** Whether this tab has finished its job and may close. */
closable: boolean;
}

export const ACCEPTED_MESSAGE = "Submission received. You can safely close this tab.";
export const ALREADY_SUBMITTED_MESSAGE =
"This form was already submitted. You can safely close this tab.";
export const INVALID_MESSAGE = "The server rejected this submission. Correct it and try again.";
export const TRANSPORT_MESSAGE = "The submission could not be delivered. Try again.";

export function outcomeFor(status: number): Outcome {
if (status === 204) {
return { kind: "accepted", message: ACCEPTED_MESSAGE, formUsable: false, closable: true };
}
if (status === 409) {
return {
kind: "already-submitted",
message: ALREADY_SUBMITTED_MESSAGE,
formUsable: false,
closable: true,
};
}
if (status === 422) {
return { kind: "retryable", message: INVALID_MESSAGE, formUsable: true, closable: false };
}
// Everything else — a refused origin, a media-type rejection, a size refusal,
// a dead connection reported as status 0 — is something the person may be able
// to get past, and none of it is a reason to take their answer away.
return { kind: "retryable", message: TRANSPORT_MESSAGE, formUsable: true, closable: false };
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions packages/web/client/config.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
/**
* The configuration the page fetches, validated before it is believed.
*
* The response comes from this WebForm's own server, but the page checks it
* anyway: the value flows into the DOM, and "the server sent it" is not a shape.
* A malformed or unexpected payload becomes a failure the page can report rather
* than an `undefined` rendered into the body.
*
* `bodyHtml` was sanitized on the server by `renderBody`, and it is the only
* field the page reads. Nothing widens that.
*/

export interface FormConfig {
bodyHtml: string;
}

export class ConfigError extends Error {
override name = "ConfigError";
}

export function parseConfig(text: string): FormConfig {
let decoded: unknown;
try {
decoded = JSON.parse(text);
} catch {
throw new ConfigError("the form configuration is not JSON");
}
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
throw new ConfigError("the form configuration is not an object");
}
if (!("bodyHtml" in decoded)) {
throw new ConfigError("the form configuration has no bodyHtml");
}
const { bodyHtml } = decoded;
if (typeof bodyHtml !== "string") {
throw new ConfigError("the form configuration's bodyHtml is not a string");
}
return { bodyHtml };
}
186 changes: 166 additions & 20 deletions packages/web/client/main.tsx
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,60 @@
/**
* The form page.
*
* Everything the page does happens inside one Effection scope, opened by `run()`
* at startup and closed when the tab goes away. That is not ceremony: an
* `XMLHttpRequest` started by a React callback outlives the callback, and without
* an owner it would keep pointing at a page that is being unloaded. The scope is
* the owner, and leaving it aborts whatever is still in flight.
*
* The scope stays open by waiting on `pagehide`. Returning from the root
* operation is what ends it — there is no `destroy()` to forget and no detached
* scope to leak.
*
* React callbacks run outside any operation, so they re-enter through the
* captured scope. Each re-entry contains its own failure: a task started with
* `scope.run()` that throws propagates into the scope and takes its siblings with
* it, which here would mean one failed submission killing the whole form.
*
* ## Order of appearance
*
* Nothing operable is shown until both halves are ready — the configuration and
* the precompiled validator. A form mounted before its validator would accept
* input it cannot check, and the person would find out only after submitting.
* Until then, and on any failure, the page shows fixed text: no author content,
* no server text, nothing executable.
*/

import { createElement } from "react";
import { createRoot } from "react-dom/client";
import type { RJSFSchema, UiSchema } from "@rjsf/utils";
import withTheme from "@rjsf/core/lib/withTheme.js";
import { generateTheme } from "@rjsf/shadcn/lib/Theme/index.js";
import createPrecompiledValidator from "@rjsf/validator-ajv8/lib/createPrecompiledValidator.js";
import type { ValidatorFunctions } from "@rjsf/validator-ajv8/lib/types.js";
import { action, run, useScope, withResolvers } from "effection";
import type { Operation, Scope } from "effection";

import { resolveHelper } from "./helpers.ts";
import { parseConfig } from "./config.ts";
import type { FormConfig } from "./config.ts";
import { outcomeFor, TRANSPORT_MESSAGE } from "./outcome.ts";
import type { Outcome } from "./outcome.ts";
import { get, postJson } from "./request.ts";

interface Registration {
validateFns: ValidatorFunctions;
rootSchema: RJSFSchema;
uiSchema?: UiSchema;
}

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

const STARTUP_FAILED =
"This form could not be prepared. Close this tab and run the workflow again.";

const Form = withTheme(generateTheme());

function mount(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
const validator = createPrecompiledValidator(validateFns, rootSchema);
const container = document.getElementById("root");
if (!container) {
throw new Error("the form container element #root is missing from the page shell");
}
createRoot(container).render(
createElement(Form, { schema: rootSchema, uiSchema: uiSchema ?? {}, validator }),
);
}

function loadValidator(): void {
const script = document.createElement("script");
script.src = "validator.js";
document.head.appendChild(script);
}
const registered = withResolvers<Registration>();

// Installed before the validator script is ever requested, so the script cannot
// arrive ahead of the bridge that receives it.
globalThis.__WEBFORM__ = {
resolveHelper,
register(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
mount(validateFns, rootSchema, uiSchema);
registered.resolve({ validateFns, rootSchema, uiSchema });
},
};

loadValidator();
function element(id: string): HTMLElement {
const found = document.getElementById(id);
if (!found) {
throw new Error(`the page shell is missing #${id}`);
}
return found;
}

/** Fixed text only. Author content never reaches the status region. */
function say(message: string): void {
element("status").textContent = message;
}

/**
* Load the validator script the server precompiled for this form.
*
* The page runs under `script-src 'self'` with no `unsafe-eval`, so a validator
* cannot be compiled here; it arrives as a same-origin script that calls back
* into the bridge. Loading it is an operation so a halt removes the element's
* listeners rather than leaving them attached to a page that is going away.
*/
function loadValidatorScript(): Operation<void> {
return action<void>((resolve, reject) => {
const script = document.createElement("script");
const onLoad = (): void => resolve();
const onError = (): void => reject(new Error("the validator script failed to load"));
script.addEventListener("load", onLoad);
script.addEventListener("error", onError);
script.src = "validator.js";
document.head.appendChild(script);
return () => {
script.removeEventListener("load", onLoad);
script.removeEventListener("error", onError);
};
});
}

/** Resolves when the tab is going away, which is what ends the scope. */
function untilPageHide(): Operation<void> {
return action<void>((resolve) => {
const onHide = (): void => resolve();
globalThis.addEventListener("pagehide", onHide);
return () => globalThis.removeEventListener("pagehide", onHide);
});
}

function* submit(formData: unknown): Operation<void> {
const result = yield* postJson("submit", JSON.stringify(formData ?? null));
apply(outcomeFor(result.status));
}

function apply(outcome: Outcome): void {
say(outcome.message);
if (!outcome.formUsable) {
element("root").setAttribute("hidden", "hidden");
}
if (outcome.closable) {
// A script can only close a window it opened, so this may do nothing at
// all. The message above is the actual fallback.
globalThis.close();
}
}

function mount(config: FormConfig, registration: Registration, scope: Scope): void {
// Sanitized on the server by `renderBody`. This is the only place author
// content enters the DOM.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
element("content").innerHTML = config.bodyHtml;

const validator = createPrecompiledValidator(registration.validateFns, registration.rootSchema);

createRoot(element("root")).render(
createElement(Form, {
schema: registration.rootSchema,
uiSchema: registration.uiSchema ?? {},
validator,
onSubmit: (event: { formData?: unknown }) => {
// React calls this outside any operation. Re-entering through the
// captured scope gives the request an owner; catching inside keeps a
// failed submission from tearing the scope down with it.
scope.run(function* () {
try {
yield* submit(event.formData);
} catch {
say(TRANSPORT_MESSAGE);
}
});
},
}),
);
}

function* start(): Operation<void> {
const scope = yield* useScope();

const response = yield* get("config.json");
if (response.status !== 200) {
throw new Error(`the form configuration could not be loaded (${response.status})`);
}
const config = parseConfig(response.body);

yield* loadValidatorScript();
const registration = yield* registered.operation;

mount(config, registration, scope);
}

run(function* () {
try {
yield* start();
} catch {
// Fixed text, never the failure's own message: nothing the server or the
// author wrote is rendered on a path that has already gone wrong.
say(STARTUP_FAILED);
return;
}
yield* untilPageHide();
});
51 changes: 51 additions & 0 deletions packages/web/client/outcome.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
/**
* What a person is told after submitting, and whether they can try again.
*
* Three of these are ordinary and one is not. A 204 means the workflow has the
* answer and this tab has no further purpose. A 409 means the form was already
* answered — by another tab, or by this one before a reload — and nothing the
* person does here will change that. A 422 or a transport failure is the only
* case where trying again makes sense, so it is the only case that leaves the
* form usable.
*
* Pure and free of the DOM, so the mapping is tested directly rather than
* inferred from what a page rendered.
*/

export type OutcomeKind = "accepted" | "already-submitted" | "retryable";

export interface Outcome {
kind: OutcomeKind;
message: string;
/** Whether the person can correct their answer and submit again. */
formUsable: boolean;
/** Whether this tab has finished its job and may close. */
closable: boolean;
}

export const ACCEPTED_MESSAGE = "Submission received. You can safely close this tab.";
export const ALREADY_SUBMITTED_MESSAGE =
"This form was already submitted. You can safely close this tab.";
export const INVALID_MESSAGE = "The server rejected this submission. Correct it and try again.";
export const TRANSPORT_MESSAGE = "The submission could not be delivered. Try again.";

export function outcomeFor(status: number): Outcome {
if (status === 204) {
return { kind: "accepted", message: ACCEPTED_MESSAGE, formUsable: false, closable: true };
}
if (status === 409) {
return {
kind: "already-submitted",
message: ALREADY_SUBMITTED_MESSAGE,
formUsable: false,
closable: true,
};
}
if (status === 422) {
return { kind: "retryable", message: INVALID_MESSAGE, formUsable: true, closable: false };
}
// Everything else — a refused origin, a media-type rejection, a size refusal,
// a dead connection reported as status 0 — is something the person may be able
// to get past, and none of it is a reason to take their answer away.
return { kind: "retryable", message: TRANSPORT_MESSAGE, formUsable: true, closable: false };
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions packages/web/client/config.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
/**
* The configuration the page fetches, validated before it is believed.
*
* The response comes from this WebForm's own server, but the page checks it
* anyway: the value flows into the DOM, and "the server sent it" is not a shape.
* A malformed or unexpected payload becomes a failure the page can report rather
* than an `undefined` rendered into the body.
*
* `bodyHtml` was sanitized on the server by `renderBody`, and it is the only
* field the page reads. Nothing widens that.
*/

export interface FormConfig {
bodyHtml: string;
}

export class ConfigError extends Error {
override name = "ConfigError";
}

export function parseConfig(text: string): FormConfig {
let decoded: unknown;
try {
decoded = JSON.parse(text);
} catch {
throw new ConfigError("the form configuration is not JSON");
}
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
throw new ConfigError("the form configuration is not an object");
}
if (!("bodyHtml" in decoded)) {
throw new ConfigError("the form configuration has no bodyHtml");
}
const { bodyHtml } = decoded;
if (typeof bodyHtml !== "string") {
throw new ConfigError("the form configuration's bodyHtml is not a string");
}
return { bodyHtml };
}
186 changes: 166 additions & 20 deletions packages/web/client/main.tsx
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,60 @@
/**
* The form page.
*
* Everything the page does happens inside one Effection scope, opened by `run()`
* at startup and closed when the tab goes away. That is not ceremony: an
* `XMLHttpRequest` started by a React callback outlives the callback, and without
* an owner it would keep pointing at a page that is being unloaded. The scope is
* the owner, and leaving it aborts whatever is still in flight.
*
* The scope stays open by waiting on `pagehide`. Returning from the root
* operation is what ends it — there is no `destroy()` to forget and no detached
* scope to leak.
*
* React callbacks run outside any operation, so they re-enter through the
* captured scope. Each re-entry contains its own failure: a task started with
* `scope.run()` that throws propagates into the scope and takes its siblings with
* it, which here would mean one failed submission killing the whole form.
*
* ## Order of appearance
*
* Nothing operable is shown until both halves are ready — the configuration and
* the precompiled validator. A form mounted before its validator would accept
* input it cannot check, and the person would find out only after submitting.
* Until then, and on any failure, the page shows fixed text: no author content,
* no server text, nothing executable.
*/

import { createElement } from "react";
import { createRoot } from "react-dom/client";
import type { RJSFSchema, UiSchema } from "@rjsf/utils";
import withTheme from "@rjsf/core/lib/withTheme.js";
import { generateTheme } from "@rjsf/shadcn/lib/Theme/index.js";
import createPrecompiledValidator from "@rjsf/validator-ajv8/lib/createPrecompiledValidator.js";
import type { ValidatorFunctions } from "@rjsf/validator-ajv8/lib/types.js";
import { action, run, useScope, withResolvers } from "effection";
import type { Operation, Scope } from "effection";

import { resolveHelper } from "./helpers.ts";
import { parseConfig } from "./config.ts";
import type { FormConfig } from "./config.ts";
import { outcomeFor, TRANSPORT_MESSAGE } from "./outcome.ts";
import type { Outcome } from "./outcome.ts";
import { get, postJson } from "./request.ts";

interface Registration {
validateFns: ValidatorFunctions;
rootSchema: RJSFSchema;
uiSchema?: UiSchema;
}

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

const STARTUP_FAILED =
"This form could not be prepared. Close this tab and run the workflow again.";

const Form = withTheme(generateTheme());

function mount(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
const validator = createPrecompiledValidator(validateFns, rootSchema);
const container = document.getElementById("root");
if (!container) {
throw new Error("the form container element #root is missing from the page shell");
}
createRoot(container).render(
createElement(Form, { schema: rootSchema, uiSchema: uiSchema ?? {}, validator }),
);
}

function loadValidator(): void {
const script = document.createElement("script");
script.src = "validator.js";
document.head.appendChild(script);
}
const registered = withResolvers<Registration>();

// Installed before the validator script is ever requested, so the script cannot
// arrive ahead of the bridge that receives it.
globalThis.__WEBFORM__ = {
resolveHelper,
register(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
mount(validateFns, rootSchema, uiSchema);
registered.resolve({ validateFns, rootSchema, uiSchema });
},
};

loadValidator();
function element(id: string): HTMLElement {
const found = document.getElementById(id);
if (!found) {
throw new Error(`the page shell is missing #${id}`);
}
return found;
}

/** Fixed text only. Author content never reaches the status region. */
function say(message: string): void {
element("status").textContent = message;
}

/**
* Load the validator script the server precompiled for this form.
*
* The page runs under `script-src 'self'` with no `unsafe-eval`, so a validator
* cannot be compiled here; it arrives as a same-origin script that calls back
* into the bridge. Loading it is an operation so a halt removes the element's
* listeners rather than leaving them attached to a page that is going away.
*/
function loadValidatorScript(): Operation<void> {
return action<void>((resolve, reject) => {
const script = document.createElement("script");
const onLoad = (): void => resolve();
const onError = (): void => reject(new Error("the validator script failed to load"));
script.addEventListener("load", onLoad);
script.addEventListener("error", onError);
script.src = "validator.js";
document.head.appendChild(script);
return () => {
script.removeEventListener("load", onLoad);
script.removeEventListener("error", onError);
};
});
}

/** Resolves when the tab is going away, which is what ends the scope. */
function untilPageHide(): Operation<void> {
return action<void>((resolve) => {
const onHide = (): void => resolve();
globalThis.addEventListener("pagehide", onHide);
return () => globalThis.removeEventListener("pagehide", onHide);
});
}

function* submit(formData: unknown): Operation<void> {
const result = yield* postJson("submit", JSON.stringify(formData ?? null));
apply(outcomeFor(result.status));
}

function apply(outcome: Outcome): void {
say(outcome.message);
if (!outcome.formUsable) {
element("root").setAttribute("hidden", "hidden");
}
if (outcome.closable) {
// A script can only close a window it opened, so this may do nothing at
// all. The message above is the actual fallback.
globalThis.close();
}
}

function mount(config: FormConfig, registration: Registration, scope: Scope): void {
// Sanitized on the server by `renderBody`. This is the only place author
// content enters the DOM.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
element("content").innerHTML = config.bodyHtml;

const validator = createPrecompiledValidator(registration.validateFns, registration.rootSchema);

createRoot(element("root")).render(
createElement(Form, {
schema: registration.rootSchema,
uiSchema: registration.uiSchema ?? {},
validator,
onSubmit: (event: { formData?: unknown }) => {
// React calls this outside any operation. Re-entering through the
// captured scope gives the request an owner; catching inside keeps a
// failed submission from tearing the scope down with it.
scope.run(function* () {
try {
yield* submit(event.formData);
} catch {
say(TRANSPORT_MESSAGE);
}
});
},
}),
);
}

function* start(): Operation<void> {
const scope = yield* useScope();

const response = yield* get("config.json");
if (response.status !== 200) {
throw new Error(`the form configuration could not be loaded (${response.status})`);
}
const config = parseConfig(response.body);

yield* loadValidatorScript();
const registration = yield* registered.operation;

mount(config, registration, scope);
}

run(function* () {
try {
yield* start();
} catch {
// Fixed text, never the failure's own message: nothing the server or the
// author wrote is rendered on a path that has already gone wrong.
say(STARTUP_FAILED);
return;
}
yield* untilPageHide();
});
51 changes: 51 additions & 0 deletions packages/web/client/outcome.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
/**
* What a person is told after submitting, and whether they can try again.
*
* Three of these are ordinary and one is not. A 204 means the workflow has the
* answer and this tab has no further purpose. A 409 means the form was already
* answered — by another tab, or by this one before a reload — and nothing the
* person does here will change that. A 422 or a transport failure is the only
* case where trying again makes sense, so it is the only case that leaves the
* form usable.
*
* Pure and free of the DOM, so the mapping is tested directly rather than
* inferred from what a page rendered.
*/

export type OutcomeKind = "accepted" | "already-submitted" | "retryable";

export interface Outcome {
kind: OutcomeKind;
message: string;
/** Whether the person can correct their answer and submit again. */
formUsable: boolean;
/** Whether this tab has finished its job and may close. */
closable: boolean;
}

export const ACCEPTED_MESSAGE = "Submission received. You can safely close this tab.";
export const ALREADY_SUBMITTED_MESSAGE =
"This form was already submitted. You can safely close this tab.";
export const INVALID_MESSAGE = "The server rejected this submission. Correct it and try again.";
export const TRANSPORT_MESSAGE = "The submission could not be delivered. Try again.";

export function outcomeFor(status: number): Outcome {
if (status === 204) {
return { kind: "accepted", message: ACCEPTED_MESSAGE, formUsable: false, closable: true };
}
if (status === 409) {
return {
kind: "already-submitted",
message: ALREADY_SUBMITTED_MESSAGE,
formUsable: false,
closable: true,
};
}
if (status === 422) {
return { kind: "retryable", message: INVALID_MESSAGE, formUsable: true, closable: false };
}
// Everything else — a refused origin, a media-type rejection, a size refusal,
// a dead connection reported as status 0 — is something the person may be able
// to get past, and none of it is a reason to take their answer away.
return { kind: "retryable", message: TRANSPORT_MESSAGE, formUsable: true, closable: false };
}
Loading
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion bun.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions deno.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions packages/web/client/config.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
/**
* The configuration the page fetches, validated before it is believed.
*
* The response comes from this WebForm's own server, but the page checks it
* anyway: the value flows into the DOM, and "the server sent it" is not a shape.
* A malformed or unexpected payload becomes a failure the page can report rather
* than an `undefined` rendered into the body.
*
* `bodyHtml` was sanitized on the server by `renderBody`, and it is the only
* field the page reads. Nothing widens that.
*/

export interface FormConfig {
bodyHtml: string;
}

export class ConfigError extends Error {
override name = "ConfigError";
}

export function parseConfig(text: string): FormConfig {
let decoded: unknown;
try {
decoded = JSON.parse(text);
} catch {
throw new ConfigError("the form configuration is not JSON");
}
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
throw new ConfigError("the form configuration is not an object");
}
if (!("bodyHtml" in decoded)) {
throw new ConfigError("the form configuration has no bodyHtml");
}
const { bodyHtml } = decoded;
if (typeof bodyHtml !== "string") {
throw new ConfigError("the form configuration's bodyHtml is not a string");
}
return { bodyHtml };
}
186 changes: 166 additions & 20 deletions packages/web/client/main.tsx
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,60 @@
/**
* The form page.
*
* Everything the page does happens inside one Effection scope, opened by `run()`
* at startup and closed when the tab goes away. That is not ceremony: an
* `XMLHttpRequest` started by a React callback outlives the callback, and without
* an owner it would keep pointing at a page that is being unloaded. The scope is
* the owner, and leaving it aborts whatever is still in flight.
*
* The scope stays open by waiting on `pagehide`. Returning from the root
* operation is what ends it — there is no `destroy()` to forget and no detached
* scope to leak.
*
* React callbacks run outside any operation, so they re-enter through the
* captured scope. Each re-entry contains its own failure: a task started with
* `scope.run()` that throws propagates into the scope and takes its siblings with
* it, which here would mean one failed submission killing the whole form.
*
* ## Order of appearance
*
* Nothing operable is shown until both halves are ready — the configuration and
* the precompiled validator. A form mounted before its validator would accept
* input it cannot check, and the person would find out only after submitting.
* Until then, and on any failure, the page shows fixed text: no author content,
* no server text, nothing executable.
*/

import { createElement } from "react";
import { createRoot } from "react-dom/client";
import type { RJSFSchema, UiSchema } from "@rjsf/utils";
import withTheme from "@rjsf/core/lib/withTheme.js";
import { generateTheme } from "@rjsf/shadcn/lib/Theme/index.js";
import createPrecompiledValidator from "@rjsf/validator-ajv8/lib/createPrecompiledValidator.js";
import type { ValidatorFunctions } from "@rjsf/validator-ajv8/lib/types.js";
import { action, run, useScope, withResolvers } from "effection";
import type { Operation, Scope } from "effection";

import { resolveHelper } from "./helpers.ts";
import { parseConfig } from "./config.ts";
import type { FormConfig } from "./config.ts";
import { outcomeFor, TRANSPORT_MESSAGE } from "./outcome.ts";
import type { Outcome } from "./outcome.ts";
import { get, postJson } from "./request.ts";

interface Registration {
validateFns: ValidatorFunctions;
rootSchema: RJSFSchema;
uiSchema?: UiSchema;
}

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

const STARTUP_FAILED =
"This form could not be prepared. Close this tab and run the workflow again.";

const Form = withTheme(generateTheme());

function mount(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
const validator = createPrecompiledValidator(validateFns, rootSchema);
const container = document.getElementById("root");
if (!container) {
throw new Error("the form container element #root is missing from the page shell");
}
createRoot(container).render(
createElement(Form, { schema: rootSchema, uiSchema: uiSchema ?? {}, validator }),
);
}

function loadValidator(): void {
const script = document.createElement("script");
script.src = "validator.js";
document.head.appendChild(script);
}
const registered = withResolvers<Registration>();

// Installed before the validator script is ever requested, so the script cannot
// arrive ahead of the bridge that receives it.
globalThis.__WEBFORM__ = {
resolveHelper,
register(validateFns: ValidatorFunctions, rootSchema: RJSFSchema, uiSchema?: UiSchema): void {
mount(validateFns, rootSchema, uiSchema);
registered.resolve({ validateFns, rootSchema, uiSchema });
},
};

loadValidator();
function element(id: string): HTMLElement {
const found = document.getElementById(id);
if (!found) {
throw new Error(`the page shell is missing #${id}`);
}
return found;
}

/** Fixed text only. Author content never reaches the status region. */
function say(message: string): void {
element("status").textContent = message;
}

/**
* Load the validator script the server precompiled for this form.
*
* The page runs under `script-src 'self'` with no `unsafe-eval`, so a validator
* cannot be compiled here; it arrives as a same-origin script that calls back
* into the bridge. Loading it is an operation so a halt removes the element's
* listeners rather than leaving them attached to a page that is going away.
*/
function loadValidatorScript(): Operation<void> {
return action<void>((resolve, reject) => {
const script = document.createElement("script");
const onLoad = (): void => resolve();
const onError = (): void => reject(new Error("the validator script failed to load"));
script.addEventListener("load", onLoad);
script.addEventListener("error", onError);
script.src = "validator.js";
document.head.appendChild(script);
return () => {
script.removeEventListener("load", onLoad);
script.removeEventListener("error", onError);
};
});
}

/** Resolves when the tab is going away, which is what ends the scope. */
function untilPageHide(): Operation<void> {
return action<void>((resolve) => {
const onHide = (): void => resolve();
globalThis.addEventListener("pagehide", onHide);
return () => globalThis.removeEventListener("pagehide", onHide);
});
}

function* submit(formData: unknown): Operation<void> {
const result = yield* postJson("submit", JSON.stringify(formData ?? null));
apply(outcomeFor(result.status));
}

function apply(outcome: Outcome): void {
say(outcome.message);
if (!outcome.formUsable) {
element("root").setAttribute("hidden", "hidden");
}
if (outcome.closable) {
// A script can only close a window it opened, so this may do nothing at
// all. The message above is the actual fallback.
globalThis.close();
}
}

function mount(config: FormConfig, registration: Registration, scope: Scope): void {
// Sanitized on the server by `renderBody`. This is the only place author
// content enters the DOM.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
Comment thread
taras marked this conversation as resolved.
element("content").innerHTML = config.bodyHtml;

const validator = createPrecompiledValidator(registration.validateFns, registration.rootSchema);

createRoot(element("root")).render(
createElement(Form, {
schema: registration.rootSchema,
uiSchema: registration.uiSchema ?? {},
validator,
onSubmit: (event: { formData?: unknown }) => {
// React calls this outside any operation. Re-entering through the
// captured scope gives the request an owner; catching inside keeps a
// failed submission from tearing the scope down with it.
scope.run(function* () {
try {
yield* submit(event.formData);
} catch {
say(TRANSPORT_MESSAGE);
}
});
},
}),
);
}

function* start(): Operation<void> {
const scope = yield* useScope();

const response = yield* get("config.json");
if (response.status !== 200) {
throw new Error(`the form configuration could not be loaded (${response.status})`);
}
const config = parseConfig(response.body);

yield* loadValidatorScript();
const registration = yield* registered.operation;

mount(config, registration, scope);
}

run(function* () {
try {
yield* start();
} catch {
// Fixed text, never the failure's own message: nothing the server or the
// author wrote is rendered on a path that has already gone wrong.
say(STARTUP_FAILED);
return;
}
yield* untilPageHide();
});
51 changes: 51 additions & 0 deletions packages/web/client/outcome.ts
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
/**
* What a person is told after submitting, and whether they can try again.
*
* Three of these are ordinary and one is not. A 204 means the workflow has the
* answer and this tab has no further purpose. A 409 means the form was already
* answered — by another tab, or by this one before a reload — and nothing the
* person does here will change that. A 422 or a transport failure is the only
* case where trying again makes sense, so it is the only case that leaves the
* form usable.
*
* Pure and free of the DOM, so the mapping is tested directly rather than
* inferred from what a page rendered.
*/

export type OutcomeKind = "accepted" | "already-submitted" | "retryable";

export interface Outcome {
kind: OutcomeKind;
message: string;
/** Whether the person can correct their answer and submit again. */
formUsable: boolean;
/** Whether this tab has finished its job and may close. */
closable: boolean;
}

export const ACCEPTED_MESSAGE = "Submission received. You can safely close this tab.";
export const ALREADY_SUBMITTED_MESSAGE =
"This form was already submitted. You can safely close this tab.";
export const INVALID_MESSAGE = "The server rejected this submission. Correct it and try again.";
export const TRANSPORT_MESSAGE = "The submission could not be delivered. Try again.";

export function outcomeFor(status: number): Outcome {
if (status === 204) {
return { kind: "accepted", message: ACCEPTED_MESSAGE, formUsable: false, closable: true };
}
if (status === 409) {
return {
kind: "already-submitted",
message: ALREADY_SUBMITTED_MESSAGE,
formUsable: false,
closable: true,
};
}
if (status === 422) {
return { kind: "retryable", message: INVALID_MESSAGE, formUsable: true, closable: false };
}
// Everything else — a refused origin, a media-type rejection, a size refusal,
// a dead connection reported as status 0 — is something the person may be able
// to get past, and none of it is a reason to take their answer away.
return { kind: "retryable", message: TRANSPORT_MESSAGE, formUsable: true, closable: false };
}
Loading
Loading