@composable-os/pack-forms 0.0.0-stage → 0.1.0-beta.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,431 @@
1
+ // The Forms pack's headless entry (stage 29 step 4; ADR 0418): functions and hooks over the typed
2
+ // client, no markup. A client app imports it as `@composable-os/pack-forms/client` and hands it its
3
+ // generated client; the forms blocks (web and native) and the host's form page render what it
4
+ // returns. Web and native share this logic, not their screens.
5
+ //
6
+ // As every pack's entry: the operations are typed from the pack's own tool schemas, it takes the
7
+ // client and the app's `useQuery`, `useMutation` and `useState` as arguments (no React or TanStack
8
+ // import), and it holds no rules. Whether a form takes answers from this caller, who may answer,
9
+ // once only, the spam checks, the caps and the answers' shape are the host's (`x.forms.submit`,
10
+ // the intake door, ADR 0720). Before sending, the answers are checked with the same
11
+ // `checkAnswers` the host runs, so a person sees what to fix beside the question at once; the
12
+ // host checks them again and its answer is the one shown.
13
+ //
14
+ // What a person types is kept in the screen's own state while they fill the form, and nowhere
15
+ // else: never in a URL, browser storage or a log, and the send is forgotten by the app's cache
16
+ // once it is over (`forgetAfter`).
17
+ import { forgetAfter, packHooks, } from "@composable-os/client";
18
+ import { checkAnswers, isQuestionShown, } from "@composable-os/sdk/questions";
19
+ /** What a client says about each operation at run time (a generated client's specs). */
20
+ export const FORMS_OPERATIONS = {
21
+ "x.forms.form": { kind: "query", invalidates: [] },
22
+ "x.forms.linkedForm": { kind: "query", invalidates: [] },
23
+ "x.forms.submit": { kind: "mutation", invalidates: [] },
24
+ "x.forms.submitLinked": { kind: "mutation", invalidates: ["me.attention"] },
25
+ };
26
+ // --- The form's questions ------------------------------------------------------------------------
27
+ /** The questions of a form the host opened, typed: the host checked them when it was published. */
28
+ export function formQuestions(opened) {
29
+ return { items: opened.questions.items };
30
+ }
31
+ /** Whether an item asks something. */
32
+ export function isAsked(item) {
33
+ return item.kind !== "heading" && item.kind !== "paragraph";
34
+ }
35
+ /** The ratings a rating question offers: 1 to 5 stars, or 0 to 10. */
36
+ export function ratingValues(item) {
37
+ return item.scale === "stars" ? [1, 2, 3, 4, 5] : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
38
+ }
39
+ /** The words beside a rating's number, for a screen reader and a button's label. */
40
+ export function ratingLabel(item, value) {
41
+ if (item.scale === "stars")
42
+ return value === 1 ? "1 star" : `${value} stars`;
43
+ return `${value} out of 10`;
44
+ }
45
+ /** The value one draft entry sends, or undefined when it is no answer. */
46
+ function answerOf(item, value) {
47
+ switch (item.kind) {
48
+ case "text":
49
+ case "email":
50
+ case "phone":
51
+ case "date": {
52
+ if (typeof value !== "string")
53
+ return undefined;
54
+ // Typed text is trimmed at its ends; a long text keeps its lines, written as \n.
55
+ const text = (item.kind === "text" && item.long ? value.replace(/\r\n?/g, "\n") : value)
56
+ .trim()
57
+ .normalize("NFC");
58
+ return text === "" ? undefined : text;
59
+ }
60
+ case "number": {
61
+ const text = typeof value === "number" ? String(value) : typeof value === "string" ? value : "";
62
+ const trimmed = text.trim().replace(",", ".");
63
+ if (trimmed === "")
64
+ return undefined;
65
+ const n = Number(trimmed);
66
+ // Not a number: sent as typed, so the check names it.
67
+ return Number.isFinite(n) ? n : trimmed;
68
+ }
69
+ case "rating":
70
+ return typeof value === "number" ? value : undefined;
71
+ case "choice":
72
+ if (item.multiple)
73
+ return Array.isArray(value) && value.length ? [...value] : undefined;
74
+ return typeof value === "string" && value !== "" ? value : undefined;
75
+ case "yesNo":
76
+ return typeof value === "boolean" ? value : undefined;
77
+ case "consent":
78
+ // A tick box left unticked is sent as false.
79
+ return value === true;
80
+ }
81
+ }
82
+ /**
83
+ * The answers to send, from what the screen holds: trimmed and converted as `checkAnswers` takes
84
+ * them, unanswered questions left out, and nothing for a question that is not shown.
85
+ */
86
+ export function answersFrom(questions, draft) {
87
+ const out = {};
88
+ for (const item of questions.items) {
89
+ if (!isAsked(item))
90
+ continue;
91
+ const value = answerOf(item, Object.hasOwn(draft, item.key) ? draft[item.key] : undefined);
92
+ if (value !== undefined)
93
+ out[item.key] = value;
94
+ }
95
+ // A question shown only if an earlier one has a value takes no answer while it is hidden.
96
+ for (const item of questions.items) {
97
+ if (Object.hasOwn(out, item.key) && !isQuestionShown(item, questions, out))
98
+ delete out[item.key];
99
+ }
100
+ return out;
101
+ }
102
+ /** The items to draw now: those with no "show only if", or whose condition holds. */
103
+ export function shownItems(questions, draft) {
104
+ const answers = answersFrom(questions, draft);
105
+ return questions.items.filter((item) => isQuestionShown(item, questions, answers));
106
+ }
107
+ /** The name a form field has on a page drawn as HTML (the host's form page): `a.<key>`. */
108
+ export const fieldName = (key) => `a.${key}`;
109
+ /** The hidden field a person leaves empty (the honeypot): a bot fills every field. */
110
+ export const HONEYPOT_FIELD = "website";
111
+ /**
112
+ * What a page drawn as HTML posted, as a draft: `values(name)` gives every value posted under a
113
+ * field's name (a choice of several, several). The reverse of the page's fields.
114
+ */
115
+ export function draftFromFields(questions, values) {
116
+ const draft = {};
117
+ for (const item of questions.items) {
118
+ if (!isAsked(item))
119
+ continue;
120
+ const given = values(fieldName(item.key));
121
+ const first = given[0] ?? "";
122
+ switch (item.kind) {
123
+ case "choice":
124
+ draft[item.key] = item.multiple ? given.filter((v) => v !== "") : first;
125
+ break;
126
+ case "rating":
127
+ draft[item.key] = /^\d{1,2}$/.test(first) ? Number(first) : null;
128
+ break;
129
+ case "yesNo":
130
+ draft[item.key] = first === "yes" ? true : first === "no" ? false : null;
131
+ break;
132
+ case "consent":
133
+ draft[item.key] = first !== "";
134
+ break;
135
+ default:
136
+ draft[item.key] = first;
137
+ }
138
+ }
139
+ return draft;
140
+ }
141
+ /** The words to show beside a question for one fault the check found (never its value). */
142
+ export function issueWords(issue, item) {
143
+ // The host's own faults go beyond the check's (a tick only the person may give: "consent").
144
+ switch (issue.fault) {
145
+ case "required":
146
+ if (item?.kind === "consent")
147
+ return "Tick this box to send the form";
148
+ if (item?.kind === "choice" || item?.kind === "rating" || item?.kind === "yesNo")
149
+ return "Choose an answer";
150
+ return "Answer this question";
151
+ case "type":
152
+ switch (item?.kind) {
153
+ case "email":
154
+ return "Enter an email address, like name@example.com";
155
+ case "phone":
156
+ return "Enter a phone number";
157
+ case "date":
158
+ return "Enter a date, as year-month-day (2026-03-02)";
159
+ case "rating":
160
+ return "Choose a rating";
161
+ case "choice":
162
+ return "Choose from the options";
163
+ case "number":
164
+ if (issue.message === "Expected a whole number")
165
+ return "Enter a whole number";
166
+ if (issue.message === "Expected a number")
167
+ return "Enter a number";
168
+ return `Enter a number: ${issue.message.toLowerCase()}`;
169
+ case "text":
170
+ return issue.message === "One line only" ? "Write this on one line" : "Use plain text";
171
+ default:
172
+ return "Check this answer";
173
+ }
174
+ case "length":
175
+ return issue.message;
176
+ case "links":
177
+ return issue.message;
178
+ case "hidden":
179
+ return "This question is not asked now: clear it";
180
+ case "consent":
181
+ return "Only the person themselves may tick this";
182
+ default:
183
+ return "Check this answer";
184
+ }
185
+ }
186
+ /** The faults of a check, by key and in a person's words. */
187
+ export function errorsOf(questions, issues) {
188
+ const byKey = {};
189
+ let general = null;
190
+ for (const issue of issues) {
191
+ const item = issue.key ? questions.items.find((q) => q.key === issue.key) : undefined;
192
+ if (issue.key && item) {
193
+ byKey[issue.key] ??= issueWords(issue, item);
194
+ }
195
+ else {
196
+ general ??=
197
+ issue.fault === "size"
198
+ ? "The answers are too long to send: shorten them"
199
+ : "Some answers could not be sent: load the form again";
200
+ }
201
+ }
202
+ return { byKey, general };
203
+ }
204
+ /**
205
+ * The answers to send, or what to fix first: the same check the host makes (the host makes it
206
+ * again and its answer is the one that counts).
207
+ */
208
+ export function checkDraft(questions, draft) {
209
+ const answers = answersFrom(questions, draft);
210
+ const checked = checkAnswers(questions, answers);
211
+ if (checked.ok)
212
+ return { ok: true, answers };
213
+ return { ok: false, ...errorsOf(questions, checked.issues) };
214
+ }
215
+ const rec = (value) => value !== null && typeof value === "object" ? value : null;
216
+ /** The host's answer as a Refusal. */
217
+ export function refusalOf(error, questions) {
218
+ const e = rec(error);
219
+ if (e?.name === "NetworkError") {
220
+ return {
221
+ kind: "offline",
222
+ message: "We could not reach the business just now. Check your connection and try again: what you entered is still here.",
223
+ };
224
+ }
225
+ // A tool's refusal comes back inside the surface's: its code and details are the door's.
226
+ const details = rec(e?.details);
227
+ const inner = rec(details?.details) ?? details;
228
+ const code = typeof details?.code === "string" ? details.code : String(e?.code ?? "");
229
+ const rule = typeof inner?.rule === "string" ? inner.rule : null;
230
+ const said = typeof e?.message === "string" && e.message ? e.message : null;
231
+ if (rule === "answers" && Array.isArray(inner?.issues) && questions) {
232
+ const errors = errorsOf(questions, inner.issues);
233
+ return { kind: "answers", message: "Some answers need another look", ...errors };
234
+ }
235
+ if (rule === "intake_reload") {
236
+ return { kind: "reload", message: said ?? "This form has changed: load it again and send" };
237
+ }
238
+ if (rule === "turnstile") {
239
+ return { kind: "check", message: said ?? "The spam check did not pass: try again" };
240
+ }
241
+ if (rule === "intake_unavailable") {
242
+ return {
243
+ kind: "closed",
244
+ message: said ?? "This form is not taking answers here just now",
245
+ };
246
+ }
247
+ if (rule === "personal_link") {
248
+ return {
249
+ kind: "gone",
250
+ message: said ?? "This link cannot be used: it may have been used already or have expired",
251
+ };
252
+ }
253
+ if (code === "rate_limited" || rule === "intake_cap" || rule === "turnstile_unavailable") {
254
+ return { kind: "later", message: said ?? "Too many answers just now: try again later" };
255
+ }
256
+ // No such form for the caller, or no Forms on the host at all: the same answer.
257
+ if (code === "not_found" || code === "unknown_operation") {
258
+ return { kind: "gone", message: "This form is not open just now" };
259
+ }
260
+ return { kind: "other", message: "We could not send your answers. Try again in a moment." };
261
+ }
262
+ // --- A personal link in a web page ---------------------------------------------------------------
263
+ /** The query parameter a personal link's token travels in (the SDK's PERSONAL_LINK_PARAM). */
264
+ export const LINK_PARAM = "t";
265
+ /**
266
+ * A personal link's token, read from the page's address once and taken out of it at once
267
+ * (`history.replaceState`), so it is not left in the address bar, the history or a bookmark, nor
268
+ * sent on as a referrer. The caller keeps it in memory only, for the send. Null with none.
269
+ */
270
+ export function takeLinkToken(page) {
271
+ const url = new URL(page.location.href);
272
+ const token = url.searchParams.get(LINK_PARAM);
273
+ if (token === null)
274
+ return null;
275
+ url.searchParams.delete(LINK_PARAM);
276
+ page.history.replaceState(null, "", `${url.pathname}${url.search}${url.hash}`);
277
+ return token || null;
278
+ }
279
+ /**
280
+ * How a form is kept once opened: never refetched while it is on the screen. A refetch would
281
+ * bring a new shown time, and a send within three seconds of it would be dropped as a bot's
282
+ * (review of PR #461); a form that changed meanwhile is the host's "load it again".
283
+ */
284
+ export const OPENED_FORM_QUERY = {
285
+ gcTime: 0,
286
+ staleTime: Number.POSITIVE_INFINITY,
287
+ refetchOnWindowFocus: false,
288
+ refetchOnReconnect: false,
289
+ };
290
+ /**
291
+ * The operations each hook calls (ADR 0453). A customer's or the public's client gets `useForm`
292
+ * and `useAnswer`; a signed-in customer's also `useLinkedForm` and `useAnswerLinked`, for a form
293
+ * from Needs your attention.
294
+ */
295
+ export const FORMS_HOOKS_CALL = {
296
+ useForm: ["x.forms.form"],
297
+ useLinkedForm: ["x.forms.linkedForm"],
298
+ useAnswer: ["x.forms.submit"],
299
+ useAnswerLinked: ["x.forms.submitLinked"],
300
+ };
301
+ /**
302
+ * Hooks for a React or React Native app:
303
+ * `const forms = createFormsHooks({ useQuery, useMutation, useState }, api)`. `api` is the
304
+ * customer's generated client (signed in, or the public).
305
+ */
306
+ export function createFormsHooks(react, client) {
307
+ return packHooks(client, FORMS_HOOKS_CALL, (api) => allFormsHooks(react, api));
308
+ }
309
+ /** One form's state while it is filled: the draft, what is shown, the faults and the send. */
310
+ function useFiller(react, form, send) {
311
+ const { useState } = react;
312
+ const [draft, setDraft] = useState({});
313
+ const [errors, setErrors] = useState({});
314
+ const [problem, setProblem] = useState(null);
315
+ const [status, setStatus] = useState("filling");
316
+ const questions = form ? formQuestions(form) : { items: [] };
317
+ return {
318
+ draft,
319
+ /** The items to draw now, in order (headings and paragraphs among them). */
320
+ items: shownItems(questions, draft),
321
+ /** What to fix, by question key. */
322
+ errors,
323
+ /** What the host (or the connection) said, for the form as a whole. */
324
+ problem,
325
+ status,
326
+ /** The words to show once sent: the form's own thank-you, or a plain one. */
327
+ thanks: form?.thanks ?? "Thank you. Your answers were sent.",
328
+ set(key, value) {
329
+ setDraft((previous) => ({ ...previous, [key]: value }));
330
+ // A fault goes once the person changes that answer.
331
+ setErrors((previous) => {
332
+ if (!Object.hasOwn(previous, key))
333
+ return previous;
334
+ const { [key]: _gone, ...rest } = previous;
335
+ return rest;
336
+ });
337
+ },
338
+ /**
339
+ * Checks the answers as the host will, then sends them. True when the host took them. A
340
+ * refusal stays on the screen (`problem`, `errors`), with the answers as typed.
341
+ */
342
+ async send(checks = {}) {
343
+ if (!form || status === "sending")
344
+ return false;
345
+ setProblem(null);
346
+ const checked = checkDraft(questions, draft);
347
+ if (!checked.ok) {
348
+ setErrors(checked.byKey);
349
+ setProblem(checked.general
350
+ ? { kind: "answers", message: checked.general, byKey: checked.byKey, general: null }
351
+ : null);
352
+ return false;
353
+ }
354
+ setErrors({});
355
+ setStatus("sending");
356
+ try {
357
+ await send(checked.answers, checks);
358
+ setStatus("sent");
359
+ // Sent: nothing the person typed is kept on the screen any more.
360
+ setDraft({});
361
+ return true;
362
+ }
363
+ catch (error) {
364
+ const refusal = refusalOf(error, questions);
365
+ if (refusal.kind === "answers")
366
+ setErrors(refusal.byKey);
367
+ setProblem(refusal);
368
+ setStatus("filling");
369
+ return false;
370
+ }
371
+ },
372
+ };
373
+ }
374
+ function allFormsHooks(react, api) {
375
+ const { useQuery, useMutation } = react;
376
+ return {
377
+ /**
378
+ * A form as the caller may answer it now: by its address (`slug`), or by a personal link's
379
+ * token (`link`, which opening uses nothing of). Not found when it is not open to them.
380
+ */
381
+ useForm(which) {
382
+ const options = which
383
+ ? api.query("x.forms.form", which)
384
+ : { queryKey: ["x.forms.form", null], queryFn: async () => undefined };
385
+ return useQuery({ ...options, enabled: which !== null, ...OPENED_FORM_QUERY });
386
+ },
387
+ /** The form a signed-in member's own personal link is for (Needs your attention's `linkId`). */
388
+ useLinkedForm(linkId) {
389
+ const options = linkId
390
+ ? api.query("x.forms.linkedForm", { linkId })
391
+ : { queryKey: ["x.forms.linkedForm", null], queryFn: async () => undefined };
392
+ return useQuery({ ...options, enabled: linkId !== null, ...OPENED_FORM_QUERY });
393
+ },
394
+ /**
395
+ * Filling in a form `useForm` opened, and sending it: on the business's website (`site`) or
396
+ * its app (`app`), or by a personal link's token (`link`).
397
+ */
398
+ useAnswer(form, way) {
399
+ const submitting = useMutation({ ...api.mutation("x.forms.submit"), gcTime: 0 });
400
+ return useFiller(react, form, (answers, checks) => {
401
+ if (!form)
402
+ throw new Error("No form to send");
403
+ const input = {
404
+ id: form.id,
405
+ version: form.version,
406
+ answers,
407
+ ...(way.link ? { link: way.link } : { via: way.via }),
408
+ ...(!way.link && form.shown ? { shown: form.shown } : {}),
409
+ ...(checks.turnstileToken ? { turnstileToken: checks.turnstileToken } : {}),
410
+ ...(checks.honeypot ? { honeypot: checks.honeypot } : {}),
411
+ };
412
+ return forgetAfter(submitting, input);
413
+ });
414
+ },
415
+ /** Filling in and sending the form of a signed-in member's own personal link, by its id. */
416
+ useAnswerLinked(form, linkId) {
417
+ const submitting = useMutation({ ...api.mutation("x.forms.submitLinked"), gcTime: 0 });
418
+ return useFiller(react, form, (answers, checks) => {
419
+ if (!form || !linkId)
420
+ throw new Error("No form to send");
421
+ return forgetAfter(submitting, {
422
+ linkId,
423
+ id: form.id,
424
+ version: form.version,
425
+ answers,
426
+ ...(checks.honeypot ? { honeypot: checks.honeypot } : {}),
427
+ });
428
+ });
429
+ },
430
+ };
431
+ }
@@ -0,0 +1,67 @@
1
+ import { type FetchLike } from "@composable-os/client";
2
+ import { type FormsOperations } from "./index.ts";
3
+ /** Where a form's own page is: `/f/<slug>`. */
4
+ export declare const FORM_PAGE_PREFIX = "/f/";
5
+ /** Where a personal link opens (the SDK's PERSONAL_LINK_PATH): `/form?t=<token>`. */
6
+ export declare const LINK_PAGE_PATH = "/form";
7
+ /** Turnstile's script and frames come from here, on a public form's page only. */
8
+ export declare const TURNSTILE_ORIGIN = "https://challenges.cloudflare.com";
9
+ /** Whether `pathname` is one of the form page's: `/form`, or `/f/<one part>`. */
10
+ export declare function isFormPagePath(pathname: string): boolean;
11
+ /** The typed client's `call`, for the two operations the page makes. */
12
+ export interface FormPageClient {
13
+ call<N extends "x.forms.form" | "x.forms.submit">(name: N, input: FormsOperations[N]["input"], options?: {
14
+ idempotencyKey?: string;
15
+ }): Promise<FormsOperations[N]["output"]>;
16
+ }
17
+ /**
18
+ * The page's client over a host: the typed client of the two operations, calling the HTTP surface
19
+ * through `fetch` (the host's own surface in-process, or a binding) with `headers` (the visitor's
20
+ * session cookie, and nothing else). It never retries: a send is the person's to make again.
21
+ */
22
+ export declare function formPageClient(options: {
23
+ fetch: FetchLike;
24
+ headers?: () => Record<string, string>;
25
+ }): FormPageClient;
26
+ export interface FormPageOptions {
27
+ /** The caller's client: the customer whose session the request carries, or the public. */
28
+ client: FormPageClient;
29
+ /**
30
+ * The Turnstile widget's site key, for a public form's page (TURNSTILE_SITE_KEY on the host).
31
+ * Without one, a form that needs the check says it cannot be sent here.
32
+ */
33
+ turnstileSiteKey?: string | null;
34
+ /**
35
+ * Who checked that a send comes from this page. `page` (the default, the host's own address):
36
+ * this function checks the browser's word (`Sec-Fetch-Site`, else `Origin`). `forwarded`: the
37
+ * page is served over the client-app binding, whose Worker checked its browser's request
38
+ * (the template's `formPageRoute`) and forwards none of those headers.
39
+ */
40
+ sameOrigin?: "page" | "forwarded";
41
+ }
42
+ /**
43
+ * Whether a browser's POST comes from the page's own origin (ADR 0728, review of PR #461): an
44
+ * allow-list. With `Sec-Fetch-Site`, only `same-origin` (or `none`, a person's own action); a
45
+ * sibling subdomain is `same-site` and is refused, as a customer's cookie still goes with it.
46
+ * Without it (an older browser), `Origin` must be the page's own, or `null` (the page's own
47
+ * no-referrer policy makes a browser send `null`).
48
+ */
49
+ export declare function sameOriginPost(headers: {
50
+ get(name: string): string | null;
51
+ }, pageOrigin: string): boolean;
52
+ /**
53
+ * A request's body as text, read only up to `max` bytes: null when it says (`content-length`) or
54
+ * turns out to be longer, so a large body is never held whole.
55
+ */
56
+ export declare function cappedText(request: Request, max: number): Promise<string | null>;
57
+ /** The most a posted form may be, in bytes: the answers' 20 KB, URL-encoded, and the page's own fields. */
58
+ export declare const MAX_BODY = 131072;
59
+ /** The one script the page runs, inline and allowed by its hash alone. */
60
+ export declare const PAGE_SCRIPT = "(function () {\n var url = new URL(location.href);\n if (url.searchParams.has(\"t\")) {\n url.searchParams.delete(\"t\");\n history.replaceState(null, \"\", url.pathname + url.search + url.hash);\n }\n var form = document.querySelector(\"form[data-form]\");\n if (!form) return;\n function values(key) {\n var out = [];\n form.querySelectorAll('[name=\"a.' + key + '\"]').forEach(function (field) {\n if (field.type === \"radio\" || field.type === \"checkbox\" ? field.checked : field.value !== \"\")\n out.push(field.value);\n });\n return out;\n }\n function sync() {\n form.querySelectorAll(\"[data-show-q]\").forEach(function (item) {\n var on = values(item.getAttribute(\"data-show-q\")).indexOf(item.getAttribute(\"data-show-is\")) >= 0;\n item.hidden = !on;\n item.querySelectorAll(\"input, select, textarea\").forEach(function (field) {\n field.disabled = !on;\n });\n });\n }\n form.addEventListener(\"change\", sync);\n sync();\n form.addEventListener(\"submit\", function () {\n var button = form.querySelector('button[type=\"submit\"]');\n if (button) setTimeout(function () { button.disabled = true; }, 0);\n });\n})();";
61
+ /** The script's CSP source: `'sha256-…'`. */
62
+ export declare function pageScriptSource(): Promise<string>;
63
+ /**
64
+ * Serves one request to the form page: GET (or HEAD) draws the form, POST sends it. A path that is
65
+ * not the page's is not found. Never throws.
66
+ */
67
+ export declare function formPage(request: Request, options: FormPageOptions): Promise<Response>;