payload-canvas 0.5.2 → 0.6.0

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.
Files changed (193) hide show
  1. package/README.md +333 -28
  2. package/dist/admin/ArrayRowLabel.d.ts +12 -0
  3. package/dist/admin/ArrayRowLabel.js +21 -0
  4. package/dist/admin/client.d.ts +1 -0
  5. package/dist/admin/client.js +2 -0
  6. package/dist/admin/editor/Editor.js +8 -1
  7. package/dist/admin/editor/Inspector.js +23 -17
  8. package/dist/admin/editor/Library.d.ts +2 -2
  9. package/dist/admin/editor/Library.js +7 -5
  10. package/dist/admin/editor/Outline.js +20 -12
  11. package/dist/admin/editor/Overlay.js +6 -4
  12. package/dist/admin/editor/actions.d.ts +7 -2
  13. package/dist/admin/editor/actions.js +44 -12
  14. package/dist/admin/editor/assistant/AssistantPanel.js +32 -20
  15. package/dist/admin/editor/comments/controller.d.ts +7 -0
  16. package/dist/admin/editor/comments/controller.js +12 -0
  17. package/dist/admin/editor/comments/useCommentFromURL.d.ts +2 -0
  18. package/dist/admin/editor/comments/useCommentFromURL.js +36 -0
  19. package/dist/admin/editor/dnd/smooth.js +1 -1
  20. package/dist/admin/editor/editor.scss +28 -0
  21. package/dist/admin/editor/fields/ArrayField.js +3 -3
  22. package/dist/admin/editor/fields/FormBlock.d.ts +20 -0
  23. package/dist/admin/editor/fields/FormBlock.js +167 -0
  24. package/dist/admin/editor/fields/FormFieldName.d.ts +25 -0
  25. package/dist/admin/editor/fields/FormFieldName.js +58 -0
  26. package/dist/admin/editor/fields/GroupField.d.ts +22 -2
  27. package/dist/admin/editor/fields/GroupField.js +30 -1
  28. package/dist/admin/editor/fields/MergeTags.d.ts +8 -0
  29. package/dist/admin/editor/fields/MergeTags.js +62 -0
  30. package/dist/admin/editor/fields/arrayRows.d.ts +0 -2
  31. package/dist/admin/editor/fields/arrayRows.js +0 -4
  32. package/dist/admin/editor/fields/fields.scss +150 -0
  33. package/dist/admin/editor/fields/values.d.ts +0 -2
  34. package/dist/admin/editor/fields/values.js +0 -14
  35. package/dist/admin/editor/icons.d.ts +3 -0
  36. package/dist/admin/editor/icons.js +3 -0
  37. package/dist/admin/editor/insert/InsertHandle.js +1 -1
  38. package/dist/admin/editor/insert/picker.d.ts +3 -2
  39. package/dist/admin/editor/insert/picker.js +9 -3
  40. package/dist/admin/editor/layout/LeftPanel.js +5 -3
  41. package/dist/admin/editor/layout/leftTabs.d.ts +15 -0
  42. package/dist/admin/editor/layout/leftTabs.js +18 -0
  43. package/dist/admin/editor/media/ImageEditor.d.ts +8 -2
  44. package/dist/admin/editor/media/ImageEditor.js +16 -10
  45. package/dist/admin/editor/media/media.scss +12 -2
  46. package/dist/admin/editor/media/model.d.ts +10 -1
  47. package/dist/admin/editor/media/model.js +19 -0
  48. package/dist/admin/editor/menu/blockMenu.js +3 -3
  49. package/dist/admin/editor/names.d.ts +9 -0
  50. package/dist/admin/editor/names.js +18 -0
  51. package/dist/admin/editor/regions/RegionFields.d.ts +6 -0
  52. package/dist/admin/editor/regions/RegionFields.js +122 -0
  53. package/dist/admin/editor/regions/RegionPane.js +5 -3
  54. package/dist/admin/editor/regions/RegionRows.js +2 -2
  55. package/dist/admin/editor/regions/required.d.ts +16 -0
  56. package/dist/admin/editor/regions/required.js +43 -0
  57. package/dist/admin/editor/renderField.d.ts +9 -2
  58. package/dist/admin/editor/renderField.js +86 -32
  59. package/dist/admin/editor/runtime.d.ts +3 -2
  60. package/dist/admin/editor/runtime.js +12 -18
  61. package/dist/admin/editor/styles/StylesPanel.js +4 -2
  62. package/dist/admin/editor/styles/context.js +9 -4
  63. package/dist/admin/editor/topbar/ContentModeToggle.js +1 -1
  64. package/dist/admin/editor/topbar/DocumentActions.js +4 -3
  65. package/dist/admin/editor/topbar/contentMode.scss +0 -9
  66. package/dist/admin/editor/topbar/topbar.scss +1 -41
  67. package/dist/admin/editor/ui/Tabs.d.ts +17 -0
  68. package/dist/admin/editor/ui/Tabs.js +17 -0
  69. package/dist/admin/forms/SubmissionCells.d.ts +6 -0
  70. package/dist/admin/forms/SubmissionCells.js +31 -0
  71. package/dist/admin/forms/SubmissionView.d.ts +5 -0
  72. package/dist/admin/forms/SubmissionView.js +106 -0
  73. package/dist/admin/forms/submissionData.d.ts +32 -0
  74. package/dist/admin/forms/submissionData.js +63 -0
  75. package/dist/admin/forms/submissions.scss +197 -0
  76. package/dist/admin/rsc.d.ts +2 -0
  77. package/dist/admin/rsc.js +5 -0
  78. package/dist/ai/endpoint.d.ts +5 -0
  79. package/dist/ai/endpoint.js +18 -8
  80. package/dist/ai/prompt.d.ts +8 -0
  81. package/dist/ai/prompt.js +30 -0
  82. package/dist/ai/tools.d.ts +6 -1
  83. package/dist/ai/tools.js +90 -6
  84. package/dist/blocks/builtins/carousel.js +10 -1
  85. package/dist/blocks/index.d.ts +1 -1
  86. package/dist/blocks/index.js +1 -1
  87. package/dist/blocks/payload.d.ts +7 -0
  88. package/dist/blocks/payload.js +16 -2
  89. package/dist/comments/shared.d.ts +5 -0
  90. package/dist/comments/shared.js +5 -0
  91. package/dist/core/blocks.d.ts +17 -3
  92. package/dist/core/blocks.js +92 -10
  93. package/dist/core/classes.d.ts +5 -0
  94. package/dist/core/classes.js +26 -1
  95. package/dist/core/conditions.d.ts +7 -0
  96. package/dist/core/conditions.js +22 -0
  97. package/dist/core/dropTarget.d.ts +3 -2
  98. package/dist/core/dropTarget.js +7 -1
  99. package/dist/core/index.d.ts +6 -3
  100. package/dist/core/index.js +6 -3
  101. package/dist/core/payloadBlocks.js +25 -3
  102. package/dist/core/references.d.ts +7 -0
  103. package/dist/core/references.js +29 -11
  104. package/dist/core/regions.d.ts +14 -0
  105. package/dist/core/regions.js +17 -1
  106. package/dist/core/rowLabel.d.ts +8 -0
  107. package/dist/core/rowLabel.js +98 -0
  108. package/dist/core/starter.d.ts +10 -0
  109. package/dist/core/starter.js +40 -0
  110. package/dist/core/tree.js +4 -0
  111. package/dist/core/types.d.ts +96 -0
  112. package/dist/core/uniqueProps.d.ts +40 -0
  113. package/dist/core/uniqueProps.js +156 -0
  114. package/dist/core/validate.js +43 -3
  115. package/dist/forms/answers.d.ts +21 -0
  116. package/dist/forms/answers.js +82 -0
  117. package/dist/forms/blocks.d.ts +33 -0
  118. package/dist/forms/blocks.js +178 -0
  119. package/dist/forms/conditions.d.ts +78 -0
  120. package/dist/forms/conditions.js +184 -0
  121. package/dist/forms/emails.d.ts +23 -0
  122. package/dist/forms/emails.js +64 -0
  123. package/dist/forms/fieldConfigs.d.ts +35 -0
  124. package/dist/forms/fieldConfigs.js +167 -0
  125. package/dist/forms/fieldOps.d.ts +78 -0
  126. package/dist/forms/fieldOps.js +378 -0
  127. package/dist/forms/fieldSettings.d.ts +81 -0
  128. package/dist/forms/fieldSettings.js +239 -0
  129. package/dist/forms/files.d.ts +54 -0
  130. package/dist/forms/files.js +128 -0
  131. package/dist/forms/index.d.ts +16 -0
  132. package/dist/forms/index.js +18 -0
  133. package/dist/forms/mergeTags.d.ts +103 -0
  134. package/dist/forms/mergeTags.js +150 -0
  135. package/dist/forms/noScript.d.ts +60 -0
  136. package/dist/forms/noScript.js +109 -0
  137. package/dist/forms/pageForms.d.ts +99 -0
  138. package/dist/forms/pageForms.js +294 -0
  139. package/dist/forms/pageSync.d.ts +91 -0
  140. package/dist/forms/pageSync.js +325 -0
  141. package/dist/forms/rateLimit.d.ts +21 -0
  142. package/dist/forms/rateLimit.js +50 -0
  143. package/dist/forms/settings.d.ts +13 -0
  144. package/dist/forms/settings.js +92 -0
  145. package/dist/forms/spam.d.ts +100 -0
  146. package/dist/forms/spam.js +218 -0
  147. package/dist/forms/spamSettings.d.ts +43 -0
  148. package/dist/forms/spamSettings.js +25 -0
  149. package/dist/forms/submission.d.ts +34 -0
  150. package/dist/forms/submission.js +89 -0
  151. package/dist/forms/submissionsAdmin.d.ts +26 -0
  152. package/dist/forms/submissionsAdmin.js +108 -0
  153. package/dist/forms/summary.d.ts +60 -0
  154. package/dist/forms/summary.js +113 -0
  155. package/dist/forms/uploads.d.ts +41 -0
  156. package/dist/forms/uploads.js +132 -0
  157. package/dist/index.d.ts +8 -2
  158. package/dist/index.js +8 -2
  159. package/dist/live/document.d.ts +12 -0
  160. package/dist/live/document.js +8 -1
  161. package/dist/live/endpoints.d.ts +1 -0
  162. package/dist/live/session.js +3 -1
  163. package/dist/live/storage.d.ts +13 -2
  164. package/dist/live/storage.js +18 -7
  165. package/dist/mcp/forms.d.ts +26 -0
  166. package/dist/mcp/forms.js +280 -0
  167. package/dist/mcp/index.d.ts +7 -0
  168. package/dist/mcp/index.js +29 -10
  169. package/dist/mcp/shared.d.ts +1 -0
  170. package/dist/mcp/shared.js +1 -0
  171. package/dist/plugin/forms.d.ts +30 -0
  172. package/dist/plugin/forms.js +63 -0
  173. package/dist/plugin/formsSync.d.ts +138 -0
  174. package/dist/plugin/formsSync.js +345 -0
  175. package/dist/plugin/hook.d.ts +22 -0
  176. package/dist/plugin/hook.js +19 -7
  177. package/dist/plugin/index.d.ts +14 -0
  178. package/dist/plugin/index.js +99 -28
  179. package/dist/plugin/links.d.ts +7 -2
  180. package/dist/plugin/links.js +9 -3
  181. package/dist/plugin/references.d.ts +6 -0
  182. package/dist/plugin/references.js +12 -0
  183. package/dist/react/canvas/BuilderCanvas.d.ts +2 -0
  184. package/dist/react/canvas/BuilderCanvas.js +29 -6
  185. package/dist/react/canvas/inline/mapper.d.ts +6 -1
  186. package/dist/react/canvas/inline/mapper.js +35 -4
  187. package/dist/react/render/LayoutOutlet.d.ts +7 -3
  188. package/dist/react/render/LayoutOutlet.js +9 -4
  189. package/dist/react/render/RenderLayout.js +13 -7
  190. package/dist/react/render/resolve.d.ts +1 -0
  191. package/dist/react/render/resolve.js +5 -1
  192. package/dist/react/server.js +19 -0
  193. package/package.json +5 -1
@@ -0,0 +1,150 @@
1
+ // Merge tags in form emails, as in Contact Form 7: `{{name}}` is the answer of the field named
2
+ // "name", `{{*}}` is every answer as a table. The To, CC, BCC, Reply-To, From and Subject lines
3
+ // and the body use them. Pure and client-safe: the email hook (`formEmails`), the tests and the
4
+ // builder's "Insert field" menu use it.
5
+ import { TICK_FIELD_TYPES } from './answers.js';
6
+ /** The tag for every answer, as a table in an HTML body and as "Label: value" lines in text. */
7
+ export const ALL_ANSWERS_TAG = '{{*}}';
8
+ /** The tag for one field: `{{email}}`. */
9
+ export const mergeTag = (name) => `{{${name}}}`;
10
+ const TAG = /\{\{\s*([^{}]+?)\s*\}\}/g;
11
+ const HTML_ESCAPES = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
12
+ export const escapeHtml = (text) => text.replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]);
13
+ /** Every answer as an HTML table: the field label, then the answer (line breaks kept). */
14
+ export function answersTable(answers) {
15
+ const rows = answers.map((a) => `<tr><th align="left" valign="top" style="padding:4px 12px 4px 0">${escapeHtml(a.label)}</th><td style="padding:4px 0">${escapeHtml(a.value).replace(/\r?\n/g, '<br>')}</td></tr>`);
16
+ return `<table cellpadding="0" cellspacing="0" style="border-collapse:collapse">${rows.join('')}</table>`;
17
+ }
18
+ /** Every answer as "Label: value" lines. */
19
+ export const answersText = (answers) => answers.map((a) => `${a.label}: ${a.value}`).join('\n');
20
+ /**
21
+ * The template with its tags replaced. `{{*}}` (also `{{*:table}}`, the form-builder plugin's
22
+ * name) gives every answer. A field the visitor left empty or that was hidden gives ''. A tag
23
+ * that names no field of the form stays as it is, so the editor sees the typo in the email.
24
+ */
25
+ export function mergeTags(template, answers, options, known = new Set()) {
26
+ if (!template)
27
+ return '';
28
+ const byName = new Map(answers.map((a) => [a.name, a.value]));
29
+ return template.replace(TAG, (whole, raw) => {
30
+ const name = raw.trim();
31
+ if (name === '*' || name === '*:table')
32
+ return options.html ? answersTable(answers) : answersText(answers);
33
+ const value = byName.get(name) ?? options.extra?.[name] ?? (known.has(name) ? '' : null);
34
+ if (value === null)
35
+ return whole;
36
+ return options.html ? escapeHtml(value).replace(/\r?\n/g, '<br>') : value;
37
+ });
38
+ }
39
+ /** A header line without line breaks, so an answer cannot add headers. */
40
+ export const headerText = (text) => text.replace(/[\r\n]+/g, ' ').trim();
41
+ const ADDRESS = /^[^\s@<>",;:]+@[^\s@<>",;:]+\.[^\s@<>",;:]+$/;
42
+ const NAMED_ADDRESS = /^(?:"[^"<>\r\n]*"|[^"<>,;:\r\n]*)\s*<[^\s@<>",;:]+@[^\s@<>",;:]+\.[^\s@<>",;:]+>$/;
43
+ /**
44
+ * The valid addresses of an address line (To, CC, BCC, Reply-To), separated by commas: a bare
45
+ * address or `"Name" <address>`. Anything else goes, so an answer such as
46
+ * `a@example.com Bcc: b@example.com` can never add a recipient.
47
+ */
48
+ export function addressLine(text) {
49
+ return headerText(text)
50
+ .split(/[,;]/)
51
+ .map((part) => part.trim())
52
+ .filter((part) => ADDRESS.test(part) || NAMED_ADDRESS.test(part))
53
+ .join(', ');
54
+ }
55
+ /**
56
+ * The answers of a submission in the form's field order, with the fields' labels. Ticked boxes
57
+ * read "Yes", unticked ones "No". Answers for names the form does not have come last.
58
+ */
59
+ export function formAnswers(fields, rows, skip = new Set()) {
60
+ const values = new Map();
61
+ for (const row of rows ?? []) {
62
+ if (typeof row?.field !== 'string' || skip.has(row.field))
63
+ continue;
64
+ values.set(row.field, row.value === null || row.value === undefined ? '' : String(row.value));
65
+ }
66
+ const out = [];
67
+ for (const field of fields ?? []) {
68
+ const name = field.name;
69
+ if (!name || !values.has(name))
70
+ continue;
71
+ let value = values.get(name);
72
+ if (TICK_FIELD_TYPES.has(field.blockType ?? ''))
73
+ value = ['true', 'on', '1', 'yes'].includes(value.trim().toLowerCase()) ? 'Yes' : 'No';
74
+ out.push({ name, label: field.label || name, value });
75
+ values.delete(name);
76
+ }
77
+ for (const [name, value] of values)
78
+ out.push({ name, label: name, value });
79
+ return out;
80
+ }
81
+ const ALL_IN_PARAGRAPH = /<p([^>]*)>((?:(?!<\/p>)[\s\S])*?)(\{\{\s*\*(?::table)?\s*\}\})((?:(?!<\/p>)[\s\S])*?)<\/p>/g;
82
+ /**
83
+ * Rich text HTML with every `{{*}}` moved out of its paragraph, so the answers table never sits in
84
+ * a `<p>`: "<p>Hi {{*}} bye</p>" -> "<p>Hi</p>{{*}}<p>bye</p>". Empty paragraphs go.
85
+ */
86
+ export function tablesOutsideParagraphs(html) {
87
+ let out = html;
88
+ // A paragraph with two tags needs two rounds.
89
+ for (let round = 0; round < 10; round++) {
90
+ const next = out.replace(ALL_IN_PARAGRAPH, (_, attrs, before, tag, after) => `<p${attrs}>${before.trimEnd()}</p>${tag}<p${attrs}>${after.trimStart()}</p>`);
91
+ if (next === out)
92
+ break;
93
+ out = next.replace(/<p[^>]*>\s*<\/p>/g, '');
94
+ }
95
+ return out;
96
+ }
97
+ /** Plain text of an HTML body, for the text part of the email. */
98
+ export function htmlToText(html) {
99
+ return html
100
+ .replace(/<(style|script)[\s\S]*?<\/\1>/gi, '')
101
+ .replace(/<br\s*\/?>/gi, '\n')
102
+ .replace(/<\/(p|div|h[1-6]|li|tr|table|blockquote)>/gi, '\n')
103
+ .replace(/<\/th>/gi, ': ')
104
+ .replace(/<\/td>/gi, ' ')
105
+ .replace(/<[^>]+>/g, '')
106
+ .replace(/&nbsp;/g, ' ')
107
+ .replace(/&lt;/g, '<')
108
+ .replace(/&gt;/g, '>')
109
+ .replace(/&quot;/g, '"')
110
+ .replace(/&#39;/g, "'")
111
+ .replace(/&amp;/g, '&')
112
+ .replace(/[ \t]+\n/g, '\n')
113
+ .replace(/\n{3,}/g, '\n\n')
114
+ .trim();
115
+ }
116
+ /** `"Name" <address>`, or the address alone. Quotes in the name are dropped. */
117
+ function mailbox(name, address) {
118
+ const clean = name.replace(/["<>]/g, '').trim();
119
+ return clean ? `"${clean}" <${address}>` : address;
120
+ }
121
+ /**
122
+ * The message of one form email for a submission. Every line and the body take merge tags; the
123
+ * address lines keep only valid addresses (`addressLine`). From:
124
+ * the From name with the From email; without a From email the site's own address; without both
125
+ * the site's sender. A From email written as `"Name" <address>` (the plugin's style) stays.
126
+ */
127
+ export function formEmailMessage(email, context) {
128
+ const known = context.fieldNames ?? new Set(context.answers.map((a) => a.name));
129
+ const line = (template) => headerText(mergeTags(template, context.answers, { html: false, extra: context.extra }, known));
130
+ const fromName = line(email.fromName);
131
+ const fromEmail = line(email.emailFrom);
132
+ const from = fromEmail && /<.+>/.test(fromEmail)
133
+ ? fromEmail
134
+ : mailbox(fromName || (fromEmail ? '' : context.defaults.fromName), fromEmail || context.defaults.fromAddress);
135
+ const source = email.bodyType === 'html' ? (email.html ?? '') : (context.richTextHtml ?? '');
136
+ const html = mergeTags(source, context.answers, { html: true, extra: context.extra }, known);
137
+ const replyTo = addressLine(line(email.replyTo));
138
+ const cc = addressLine(line(email.cc));
139
+ const bcc = addressLine(line(email.bcc));
140
+ return {
141
+ to: addressLine(line(email.emailTo)) || context.defaults.to || '',
142
+ from,
143
+ ...(replyTo ? { replyTo } : {}),
144
+ ...(cc ? { cc } : {}),
145
+ ...(bcc ? { bcc } : {}),
146
+ subject: line(email.subject),
147
+ html,
148
+ text: htmlToText(html),
149
+ };
150
+ }
@@ -0,0 +1,60 @@
1
+ import type { SubmissionRow } from './submission.js';
2
+ /** The hidden input with the form's id. */
3
+ export declare const NO_SCRIPT_FORM_INPUT = "_form";
4
+ /** The hidden input with the page path to come back to. */
5
+ export declare const NO_SCRIPT_RETURN_INPUT = "_return";
6
+ /** Query keys of the result: `form-result` ("sent" or "error"), the form id, the message and the problems. */
7
+ export declare const FORM_RESULT_PARAM = "form-result";
8
+ /** The result of a no-JavaScript post, as the page shows it. */
9
+ export type FormResult = {
10
+ form: string;
11
+ status: 'sent' | 'error';
12
+ message?: string;
13
+ problems?: string[];
14
+ };
15
+ /** A file of the post, as Payload's `req.files` holds it. */
16
+ export type PostedFile = {
17
+ name: string;
18
+ data: Buffer;
19
+ mimetype: string;
20
+ size: number;
21
+ };
22
+ type FieldLike = {
23
+ blockType?: string | null;
24
+ name?: string | null;
25
+ };
26
+ /** The element id of a form's result on the page, for the redirect's `#…`. */
27
+ export declare const formResultAnchor: (form: string | number) => string;
28
+ /** The query (with `?`) and the anchor of a result. Texts are cut, so the address stays short. */
29
+ export declare function formResultSearch(result: FormResult): string;
30
+ /**
31
+ * A page address without a no-JavaScript result in it (its query keys and its `#form-…` anchor), so
32
+ * a submission sent from a result view records the page itself. Works on paths and full addresses.
33
+ */
34
+ export declare function withoutFormResult(address: string): string;
35
+ /** The result in a page's query, or null. Takes `URLSearchParams` or Next's `searchParams` object. */
36
+ export declare function readFormResult(query: URLSearchParams | Record<string, string | string[] | undefined>): FormResult | null;
37
+ /**
38
+ * A path on this site to come back to: starts with one "/", no scheme or host, no backslashes.
39
+ * Anything else (an outside address someone put in the post) becomes "/".
40
+ */
41
+ export declare function safeReturnPath(value: unknown): string;
42
+ /**
43
+ * The submission a native post of the form holds, as the site's script sends it: one answer per
44
+ * named field (several values joined with ", "; a ticked box is "true"), the files of each file
45
+ * field (its answer is left to the upload hook), and the honeypot's value.
46
+ */
47
+ export declare function noScriptSubmission(fields: readonly FieldLike[], data: Pick<FormData, 'getAll'>): Promise<{
48
+ submissionData: SubmissionRow[];
49
+ files: Record<string, PostedFile[]>;
50
+ honeypot: string;
51
+ }>;
52
+ /**
53
+ * The problems and message of a refused submission (Payload's ValidationError rows, else the
54
+ * error's message), for the result. Unknown errors get a general message, never their text.
55
+ */
56
+ export declare function refusalOf(error: unknown): {
57
+ message: string;
58
+ problems: string[];
59
+ };
60
+ export {};
@@ -0,0 +1,109 @@
1
+ // Forms without JavaScript: the site's `<form>` posts natively (`method="post"`, multipart) to a
2
+ // route of the app, which turns the form data into the same submission the site's script sends
3
+ // (`noScriptSubmission`), creates it with the Local API as the visitor, and redirects (303) back
4
+ // to the page with the result in the query (`formResultSearch`). The page reads it
5
+ // (`readFormResult`) and shows the confirmation or the problems. Pure and client-safe.
6
+ import { HONEYPOT_NAME } from './spamSettings.js';
7
+ /** The hidden input with the form's id. */
8
+ export const NO_SCRIPT_FORM_INPUT = '_form';
9
+ /** The hidden input with the page path to come back to. */
10
+ export const NO_SCRIPT_RETURN_INPUT = '_return';
11
+ /** Query keys of the result: `form-result` ("sent" or "error"), the form id, the message and the problems. */
12
+ export const FORM_RESULT_PARAM = 'form-result';
13
+ const FORM_PARAM = 'form-id';
14
+ const MESSAGE_PARAM = 'form-message';
15
+ const PROBLEM_PARAM = 'form-problem';
16
+ /** The element id of a form's result on the page, for the redirect's `#…`. */
17
+ export const formResultAnchor = (form) => `form-${String(form)}`;
18
+ /** The query (with `?`) and the anchor of a result. Texts are cut, so the address stays short. */
19
+ export function formResultSearch(result) {
20
+ const params = new URLSearchParams({ [FORM_RESULT_PARAM]: result.status, [FORM_PARAM]: result.form });
21
+ if (result.message)
22
+ params.set(MESSAGE_PARAM, result.message.slice(0, 300));
23
+ for (const problem of (result.problems ?? []).slice(0, 10))
24
+ params.append(PROBLEM_PARAM, problem.slice(0, 200));
25
+ return `?${params.toString()}#${formResultAnchor(result.form)}`;
26
+ }
27
+ /**
28
+ * A page address without a no-JavaScript result in it (its query keys and its `#form-…` anchor), so
29
+ * a submission sent from a result view records the page itself. Works on paths and full addresses.
30
+ */
31
+ export function withoutFormResult(address) {
32
+ if (!address.includes(FORM_RESULT_PARAM))
33
+ return address;
34
+ const [rest = '', hash = ''] = address.split('#');
35
+ const [path = '', query = ''] = rest.split('?');
36
+ const params = new URLSearchParams(query);
37
+ for (const key of [FORM_RESULT_PARAM, FORM_PARAM, MESSAGE_PARAM, PROBLEM_PARAM])
38
+ params.delete(key);
39
+ const search = params.toString();
40
+ return `${path}${search ? `?${search}` : ''}${hash && !hash.startsWith('form-') ? `#${hash}` : ''}`;
41
+ }
42
+ /** The result in a page's query, or null. Takes `URLSearchParams` or Next's `searchParams` object. */
43
+ export function readFormResult(query) {
44
+ const all = (key) => {
45
+ if (query instanceof URLSearchParams)
46
+ return query.getAll(key);
47
+ const value = query[key];
48
+ return Array.isArray(value) ? value : value === undefined ? [] : [value];
49
+ };
50
+ const status = all(FORM_RESULT_PARAM)[0];
51
+ const form = all(FORM_PARAM)[0];
52
+ if ((status !== 'sent' && status !== 'error') || !form)
53
+ return null;
54
+ const message = all(MESSAGE_PARAM)[0];
55
+ const problems = all(PROBLEM_PARAM).filter(Boolean);
56
+ return { form, status, ...(message ? { message } : {}), ...(problems.length > 0 ? { problems } : {}) };
57
+ }
58
+ /** True when the text holds a control character (a line break someone put in an address). */
59
+ const hasControlCharacter = (text) => [...text].some((char) => char.charCodeAt(0) < 0x20);
60
+ /**
61
+ * A path on this site to come back to: starts with one "/", no scheme or host, no backslashes.
62
+ * Anything else (an outside address someone put in the post) becomes "/".
63
+ */
64
+ export function safeReturnPath(value) {
65
+ if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//') || value.includes('\\') || hasControlCharacter(value))
66
+ return '/';
67
+ return value.split('#')[0].split('?')[0] || '/';
68
+ }
69
+ /** A posted file part: a `File` with a name (an empty file input posts one without). */
70
+ const isPostedFile = (value) => typeof value !== 'string' && value.name !== '' && value.size > 0;
71
+ /**
72
+ * The submission a native post of the form holds, as the site's script sends it: one answer per
73
+ * named field (several values joined with ", "; a ticked box is "true"), the files of each file
74
+ * field (its answer is left to the upload hook), and the honeypot's value.
75
+ */
76
+ export async function noScriptSubmission(fields, data) {
77
+ const submissionData = [];
78
+ const files = {};
79
+ for (const field of fields) {
80
+ const name = field.name;
81
+ if (!name || field.blockType === 'message')
82
+ continue;
83
+ const values = data.getAll(name);
84
+ if (field.blockType === 'file') {
85
+ const posted = values.filter(isPostedFile);
86
+ if (posted.length > 0) {
87
+ files[name] = await Promise.all(posted.map(async (file) => ({ name: file.name, data: Buffer.from(await file.arrayBuffer()), mimetype: file.type || 'application/octet-stream', size: file.size })));
88
+ }
89
+ continue;
90
+ }
91
+ const texts = values.filter((v) => typeof v === 'string').map((v) => v.trim()).filter(Boolean);
92
+ if (texts.length === 0)
93
+ continue;
94
+ const tick = field.blockType === 'checkbox' || field.blockType === 'consent';
95
+ submissionData.push({ field: name, value: tick ? 'true' : texts.join(', ') });
96
+ }
97
+ const honeypot = data.getAll(HONEYPOT_NAME).find((v) => typeof v === 'string') ?? '';
98
+ return { submissionData, files, honeypot };
99
+ }
100
+ /**
101
+ * The problems and message of a refused submission (Payload's ValidationError rows, else the
102
+ * error's message), for the result. Unknown errors get a general message, never their text.
103
+ */
104
+ export function refusalOf(error) {
105
+ const problems = (error?.data?.errors ?? []).flatMap((e) => (typeof e.message === 'string' && e.message ? [e.message] : []));
106
+ const isPublic = error?.isPublic === true || problems.length > 0;
107
+ const message = isPublic && error instanceof Error && error.message ? error.message : 'Your message was not sent. Please try again later.';
108
+ return { message: problems.length > 0 ? 'Your message was not sent. Check the problems below.' : message, problems: [...new Set(problems)] };
109
+ }
@@ -0,0 +1,99 @@
1
+ import type { Field } from 'payload';
2
+ import type { Block, BlockDefinition } from '../core/types.js';
3
+ export { FORM_FIELD_PARTS, formFieldParts, type FormFieldPartName } from './blocks.js';
4
+ /** The Form block's type. */
5
+ export declare const FORM_BLOCK = "form";
6
+ /** The Submit button block's type. */
7
+ export declare const FORM_SUBMIT_BLOCK = "formSubmit";
8
+ /** The Form block's slot for its content. */
9
+ export declare const FORM_SLOT = "children";
10
+ /** `admin.custom.builderFormActions`: the inspector shows "Edit form" and "Move into this page" here. */
11
+ export declare const FORM_ACTIONS_MARKER = "builderFormActions";
12
+ /** `admin.custom` key of a collapsible the inspector draws as a settings panel section, like the form builder's. */
13
+ export declare const PANEL_SECTION_MARKER = "builderPanelSection";
14
+ /** `admin.custom` key of a group drawn without its own heading: the section around it already names it. */
15
+ export declare const PLAIN_GROUP_MARKER = "builderPlainGroup";
16
+ /** Layout blocks a Form block takes next to its fields, when the site has them. */
17
+ export declare const FORM_LAYOUT_TYPES: readonly ['stack', 'grid', 'heading', 'text', 'richText', 'divider', 'image'];
18
+ /** "build": the Form block holds its fields. "saved": it shows a form of the forms collection. */
19
+ export type FormMode = 'build' | 'saved';
20
+ /** The form-wide parts: every field inside uses these classes unless it sets its own. */
21
+ export declare const FORM_PARTS: {
22
+ readonly label: 'Labels';
23
+ readonly input: 'Inputs';
24
+ readonly help: 'Help texts';
25
+ readonly error: 'Error messages';
26
+ readonly button: 'Submit button';
27
+ };
28
+ export type FormPartName = keyof typeof FORM_PARTS;
29
+ /** Default classes of the form-wide parts. */
30
+ export type FormPartClasses = Partial<Record<FormPartName, string>>;
31
+ /**
32
+ * The mode of a Form block: its `mode`; else "build" when it holds blocks (a Form block that MCP or
33
+ * the assistant inserted without a mode, also after the publish gave it its form id); else "saved"
34
+ * when it names a form (layouts from before the modes); else "build".
35
+ */
36
+ export declare function formBlockMode(props: Record<string, unknown> | undefined, slots?: Block['slots']): FormMode;
37
+ /** The id of the form a Form block names (stored as an id, or a loaded document). Null without one. */
38
+ export declare function formIdOf(value: unknown): string | number | null;
39
+ /** True for the builder type of a form field block (`formText`), never the Form or Submit block. */
40
+ export declare const isFormFieldType: (type: string) => boolean;
41
+ /**
42
+ * The form field blocks in `blocks`, in tree order: inside layout blocks too, never inside another
43
+ * Form block (its fields belong to that form).
44
+ */
45
+ export declare function formFieldsIn(blocks: readonly Block[]): Block[];
46
+ /** The field blocks of a Form block, in tree order. */
47
+ export declare function formBlockFields(form: Block): Block[];
48
+ /** The Submit button blocks of a Form block, in tree order. */
49
+ export declare function formSubmitBlocks(form: Block): Block[];
50
+ export type FormBlocksOptions = {
51
+ /** Slug of the forms collection. Default "forms". */
52
+ collection?: string;
53
+ /** Default classes of the form-wide parts (labels, inputs, help texts, errors, the button). */
54
+ partClassNames?: FormPartClasses;
55
+ /** Classes a new Form block starts with. */
56
+ defaultClassName?: string;
57
+ };
58
+ /**
59
+ * The Form block and the Submit button block, for the app's block list. The plugin completes the
60
+ * Form block (settings, the slot's block types) and adds the field blocks, when `websiteBuilder({ forms })`
61
+ * is on and the list has a Form block.
62
+ */
63
+ export declare function formBlocks(options?: FormBlocksOptions): BlockDefinition[];
64
+ /** The settings sections of a form (the form builder's panel and the Form block), with the forms collection's own setting fields. */
65
+ export declare const FORM_SETTINGS_SECTIONS: readonly [{
66
+ readonly label: 'General';
67
+ readonly fields: readonly ['title', 'submitButtonLabel'];
68
+ }, {
69
+ readonly label: 'After submit';
70
+ readonly fields: readonly ['confirmationType', 'confirmationMessage', 'redirect'];
71
+ }, {
72
+ readonly label: 'Mail';
73
+ readonly fields: readonly ['emails'];
74
+ }];
75
+ /** The forms collection's settings in the order of the sections, then its other groups (spam protection). */
76
+ export declare function formSettingNames(fields: readonly Field[]): string[];
77
+ /**
78
+ * The Form block's settings fields: the sections General, After submit and Mail, then one section
79
+ * per other group (spam protection), all shown only in "build" mode. `fields` are the forms
80
+ * collection's top-level fields (functions already turned into builder conditions).
81
+ */
82
+ export declare function formSettingsFields(fields: readonly Field[]): Field[];
83
+ /** The parts of a field definition for pages and the form builder, with its type's parts. */
84
+ export declare function withFieldParts(def: BlockDefinition): BlockDefinition;
85
+ export type PageFormsInput = {
86
+ /** The field block definitions of the forms collection (`formFieldBlocks`). */
87
+ fields: readonly BlockDefinition[];
88
+ /** The Form block's settings fields (`formSettingsFields`). */
89
+ settings: readonly Field[];
90
+ /** Slug of the forms collection. */
91
+ collection: string;
92
+ };
93
+ /**
94
+ * The app's block list with forms on pages completed: the Form block gets its settings, the saved
95
+ * form's collection and the block types its slot takes; the field blocks join the list (replacing
96
+ * any of the same type) and go only inside a Form block. Returns the list as it is when it has no
97
+ * Form block with a children slot.
98
+ */
99
+ export declare function withPageForms(blocks: readonly BlockDefinition[], input: PageFormsInput): BlockDefinition[];