payload-canvas 0.5.2 → 0.7.0-next.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 (325) hide show
  1. package/README.md +350 -45
  2. package/dist/admin/AiKeyField.d.ts +4 -3
  3. package/dist/admin/AiKeyField.js +3 -3
  4. package/dist/admin/ArrayRowLabel.d.ts +12 -0
  5. package/dist/admin/ArrayRowLabel.js +21 -0
  6. package/dist/admin/BuilderTab.js +1 -1
  7. package/dist/admin/DocumentEditView.d.ts +1 -1
  8. package/dist/admin/DocumentEditView.js +2 -3
  9. package/dist/admin/LayoutField.d.ts +1 -1
  10. package/dist/admin/LayoutField.js +2 -2
  11. package/dist/admin/TemplateConditionsField.d.ts +2 -2
  12. package/dist/admin/TemplateConditionsField.js +2 -2
  13. package/dist/admin/aiKeyField.css +58 -0
  14. package/dist/admin/client.d.ts +1 -0
  15. package/dist/admin/client.js +2 -0
  16. package/dist/admin/diff/LayoutDiff.js +3 -3
  17. package/dist/admin/diff/LayoutJsonDiff.d.ts +1 -1
  18. package/dist/admin/diff/LayoutJsonDiff.js +1 -1
  19. package/dist/admin/diff/layoutDiff.css +180 -0
  20. package/dist/admin/editor/Editor.d.ts +2 -2
  21. package/dist/admin/editor/Editor.js +10 -3
  22. package/dist/admin/editor/Inspector.js +23 -17
  23. package/dist/admin/editor/Library.d.ts +2 -2
  24. package/dist/admin/editor/Library.js +8 -7
  25. package/dist/admin/editor/Outline.js +20 -12
  26. package/dist/admin/editor/Overlay.js +6 -4
  27. package/dist/admin/editor/actions.d.ts +7 -2
  28. package/dist/admin/editor/actions.js +44 -12
  29. package/dist/admin/editor/assistant/AssistantPanel.d.ts +1 -1
  30. package/dist/admin/editor/assistant/AssistantPanel.js +33 -21
  31. package/dist/admin/editor/assistant/{assistant.scss → assistant.css} +322 -315
  32. package/dist/admin/editor/classes/ClassManager.d.ts +1 -1
  33. package/dist/admin/editor/classes/ClassManager.js +1 -1
  34. package/dist/admin/editor/classes/manager.css +258 -0
  35. package/dist/admin/editor/comments/CommentLayer.d.ts +1 -1
  36. package/dist/admin/editor/comments/CommentLayer.js +1 -1
  37. package/dist/admin/editor/comments/CommentsPanel.d.ts +1 -1
  38. package/dist/admin/editor/comments/CommentsPanel.js +1 -1
  39. package/dist/admin/editor/comments/{comments.scss → comments.css} +121 -140
  40. package/dist/admin/editor/comments/controller.d.ts +7 -0
  41. package/dist/admin/editor/comments/controller.js +12 -0
  42. package/dist/admin/editor/comments/useCommentFromURL.d.ts +2 -0
  43. package/dist/admin/editor/comments/useCommentFromURL.js +36 -0
  44. package/dist/admin/editor/dnd/{dnd.scss → dnd.css} +78 -80
  45. package/dist/admin/editor/dnd/smooth.js +1 -1
  46. package/dist/admin/editor/{editor.scss → editor.css} +798 -751
  47. package/dist/admin/editor/empty/EmptyStart.d.ts +1 -1
  48. package/dist/admin/editor/empty/EmptyStart.js +3 -3
  49. package/dist/admin/editor/empty/{empty.scss → empty.css} +12 -13
  50. package/dist/admin/editor/fields/ArrayField.js +3 -3
  51. package/dist/admin/editor/fields/FormBlock.d.ts +20 -0
  52. package/dist/admin/editor/fields/FormBlock.js +167 -0
  53. package/dist/admin/editor/fields/FormFieldName.d.ts +25 -0
  54. package/dist/admin/editor/fields/FormFieldName.js +58 -0
  55. package/dist/admin/editor/fields/GroupField.d.ts +22 -2
  56. package/dist/admin/editor/fields/GroupField.js +30 -1
  57. package/dist/admin/editor/fields/MergeTags.d.ts +8 -0
  58. package/dist/admin/editor/fields/MergeTags.js +62 -0
  59. package/dist/admin/editor/fields/arrayRows.d.ts +0 -2
  60. package/dist/admin/editor/fields/arrayRows.js +0 -4
  61. package/dist/admin/editor/fields/fields.css +786 -0
  62. package/dist/admin/editor/fields/values.d.ts +0 -2
  63. package/dist/admin/editor/fields/values.js +0 -14
  64. package/dist/admin/editor/generate/GenerateImage.d.ts +1 -1
  65. package/dist/admin/editor/generate/GenerateImage.js +1 -1
  66. package/dist/admin/editor/generate/{generate.scss → generate.css} +83 -82
  67. package/dist/admin/editor/icons.d.ts +3 -0
  68. package/dist/admin/editor/icons.js +3 -0
  69. package/dist/admin/editor/insert/InsertHandle.js +1 -1
  70. package/dist/admin/editor/insert/picker.d.ts +3 -2
  71. package/dist/admin/editor/insert/picker.js +9 -3
  72. package/dist/admin/editor/layout/LeftPanel.js +5 -3
  73. package/dist/admin/editor/layout/layout.css +243 -0
  74. package/dist/admin/editor/layout/leftTabs.d.ts +15 -0
  75. package/dist/admin/editor/layout/leftTabs.js +18 -0
  76. package/dist/admin/editor/layout/panels.js +1 -1
  77. package/dist/admin/editor/live/PresenceUI.d.ts +1 -1
  78. package/dist/admin/editor/live/PresenceUI.js +2 -2
  79. package/dist/admin/editor/live/{presence.scss → presence.css} +5 -4
  80. package/dist/admin/editor/locale/LocaleField.d.ts +1 -1
  81. package/dist/admin/editor/locale/LocaleField.js +1 -1
  82. package/dist/admin/editor/locale/LocaleSwitcher.d.ts +1 -1
  83. package/dist/admin/editor/locale/LocaleSwitcher.js +1 -1
  84. package/dist/admin/editor/locale/locale.css +153 -0
  85. package/dist/admin/editor/media/ImageEditor.d.ts +9 -3
  86. package/dist/admin/editor/media/ImageEditor.js +17 -11
  87. package/dist/admin/editor/media/{media.scss → media.css} +70 -60
  88. package/dist/admin/editor/media/model.d.ts +10 -1
  89. package/dist/admin/editor/media/model.js +19 -0
  90. package/dist/admin/editor/menu/Menu.d.ts +1 -1
  91. package/dist/admin/editor/menu/Menu.js +1 -1
  92. package/dist/admin/editor/menu/blockMenu.js +3 -3
  93. package/dist/admin/editor/menu/menu.css +132 -0
  94. package/dist/admin/editor/motion/MotionPanel.d.ts +2 -2
  95. package/dist/admin/editor/motion/MotionPanel.js +2 -2
  96. package/dist/admin/editor/motion/{motion.scss → motion.css} +24 -21
  97. package/dist/admin/editor/names.d.ts +9 -0
  98. package/dist/admin/editor/names.js +18 -0
  99. package/dist/admin/editor/regions/RegionFields.d.ts +6 -0
  100. package/dist/admin/editor/regions/RegionFields.js +122 -0
  101. package/dist/admin/editor/regions/RegionPane.js +5 -3
  102. package/dist/admin/editor/regions/RegionRows.js +2 -2
  103. package/dist/admin/editor/regions/required.d.ts +16 -0
  104. package/dist/admin/editor/regions/required.js +43 -0
  105. package/dist/admin/editor/renderField.d.ts +10 -3
  106. package/dist/admin/editor/renderField.js +87 -33
  107. package/dist/admin/editor/runtime.d.ts +3 -2
  108. package/dist/admin/editor/runtime.js +12 -18
  109. package/dist/admin/editor/sections/ComponentFields.d.ts +1 -1
  110. package/dist/admin/editor/sections/ComponentFields.js +2 -3
  111. package/dist/admin/editor/sections/PropertyControls.d.ts +1 -1
  112. package/dist/admin/editor/sections/PropertyControls.js +1 -1
  113. package/dist/admin/editor/sections/components.css +244 -0
  114. package/dist/admin/editor/sections/variants.css +93 -0
  115. package/dist/admin/editor/sections/variants.d.ts +1 -1
  116. package/dist/admin/editor/sections/variants.js +1 -1
  117. package/dist/admin/editor/styles/ClassBar.d.ts +1 -1
  118. package/dist/admin/editor/styles/ClassBar.js +1 -1
  119. package/dist/admin/editor/styles/StylesPanel.d.ts +1 -1
  120. package/dist/admin/editor/styles/StylesPanel.js +5 -3
  121. package/dist/admin/editor/styles/{classes.scss → classes.css} +128 -125
  122. package/dist/admin/editor/styles/context.js +9 -4
  123. package/dist/admin/editor/styles/{styles.scss → styles.css} +368 -370
  124. package/dist/admin/editor/templates/Bindable.d.ts +1 -1
  125. package/dist/admin/editor/templates/Bindable.js +1 -1
  126. package/dist/admin/editor/templates/binding.js +4 -1
  127. package/dist/admin/editor/templates/{templates.scss → templates.css} +207 -206
  128. package/dist/admin/editor/tooltip/Tooltips.d.ts +1 -1
  129. package/dist/admin/editor/tooltip/Tooltips.js +1 -1
  130. package/dist/admin/editor/tooltip/{tooltip.scss → tooltip.css} +11 -10
  131. package/dist/admin/editor/topbar/ContentModeToggle.d.ts +1 -1
  132. package/dist/admin/editor/topbar/ContentModeToggle.js +2 -2
  133. package/dist/admin/editor/topbar/DocumentActions.js +5 -5
  134. package/dist/admin/editor/topbar/TopBar.d.ts +1 -1
  135. package/dist/admin/editor/topbar/TopBar.js +2 -3
  136. package/dist/admin/editor/topbar/contentMode.css +25 -0
  137. package/dist/admin/editor/topbar/screens/DrawerRouter.d.ts +1 -1
  138. package/dist/admin/editor/topbar/screens/DrawerRouter.js +52 -40
  139. package/dist/admin/editor/topbar/screens/ScreenDrawer.d.ts +1 -1
  140. package/dist/admin/editor/topbar/screens/ScreenDrawer.js +4 -5
  141. package/dist/admin/editor/topbar/screens/drawerRouterSupport.d.ts +5 -5
  142. package/dist/admin/editor/topbar/screens/drawerRouterSupport.js +7 -7
  143. package/dist/admin/editor/topbar/screens/screens.css +139 -0
  144. package/dist/admin/editor/topbar/settingsDrawer.css +33 -0
  145. package/dist/admin/editor/topbar/settingsDrawer.d.ts +1 -1
  146. package/dist/admin/editor/topbar/settingsDrawer.js +3 -3
  147. package/dist/admin/editor/topbar/{topbar.scss → topbar.css} +189 -231
  148. package/dist/admin/editor/ui/Select.d.ts +1 -1
  149. package/dist/admin/editor/ui/Select.js +1 -1
  150. package/dist/admin/editor/ui/Slider.d.ts +1 -1
  151. package/dist/admin/editor/ui/Slider.js +1 -1
  152. package/dist/admin/editor/ui/Tabs.d.ts +17 -0
  153. package/dist/admin/editor/ui/Tabs.js +17 -0
  154. package/dist/admin/editor/ui/controls.css +301 -0
  155. package/dist/admin/forms/SubmissionCells.d.ts +6 -0
  156. package/dist/admin/forms/SubmissionCells.js +31 -0
  157. package/dist/admin/forms/SubmissionView.d.ts +5 -0
  158. package/dist/admin/forms/SubmissionView.js +106 -0
  159. package/dist/admin/forms/submissionData.d.ts +32 -0
  160. package/dist/admin/forms/submissionData.js +63 -0
  161. package/dist/admin/forms/submissions.css +200 -0
  162. package/dist/admin/layoutField.css +70 -0
  163. package/dist/admin/rsc.d.ts +2 -0
  164. package/dist/admin/rsc.js +5 -0
  165. package/dist/admin/screen/BuilderScreen.d.ts +1 -1
  166. package/dist/admin/screen/BuilderScreen.js +1 -1
  167. package/dist/admin/templateConditions.css +25 -0
  168. package/dist/ai/endpoint.d.ts +5 -0
  169. package/dist/ai/endpoint.js +18 -8
  170. package/dist/ai/images/service.js +2 -2
  171. package/dist/ai/prompt.d.ts +8 -0
  172. package/dist/ai/prompt.js +30 -0
  173. package/dist/ai/settings/index.js +3 -0
  174. package/dist/ai/tools.d.ts +6 -1
  175. package/dist/ai/tools.js +90 -6
  176. package/dist/blocks/builtins/carousel.js +10 -1
  177. package/dist/blocks/index.d.ts +1 -1
  178. package/dist/blocks/index.js +1 -1
  179. package/dist/blocks/payload.d.ts +7 -0
  180. package/dist/blocks/payload.js +16 -2
  181. package/dist/classes/collection.js +1 -0
  182. package/dist/classes/sheet.js +2 -0
  183. package/dist/comments/collection.js +3 -0
  184. package/dist/comments/shared.d.ts +5 -0
  185. package/dist/comments/shared.js +5 -0
  186. package/dist/core/blocks.d.ts +17 -3
  187. package/dist/core/blocks.js +92 -10
  188. package/dist/core/classes.d.ts +5 -0
  189. package/dist/core/classes.js +26 -1
  190. package/dist/core/conditions.d.ts +7 -0
  191. package/dist/core/conditions.js +22 -0
  192. package/dist/core/dropTarget.d.ts +3 -2
  193. package/dist/core/dropTarget.js +7 -1
  194. package/dist/core/fieldHooks.d.ts +1 -1
  195. package/dist/core/index.d.ts +6 -3
  196. package/dist/core/index.js +6 -3
  197. package/dist/core/payloadBlocks.js +25 -3
  198. package/dist/core/references.d.ts +7 -0
  199. package/dist/core/references.js +29 -11
  200. package/dist/core/regions.d.ts +14 -0
  201. package/dist/core/regions.js +17 -1
  202. package/dist/core/rowLabel.d.ts +8 -0
  203. package/dist/core/rowLabel.js +98 -0
  204. package/dist/core/starter.d.ts +10 -0
  205. package/dist/core/starter.js +40 -0
  206. package/dist/core/tree.js +4 -0
  207. package/dist/core/types.d.ts +96 -0
  208. package/dist/core/uniqueProps.d.ts +40 -0
  209. package/dist/core/uniqueProps.js +156 -0
  210. package/dist/core/validate.js +43 -3
  211. package/dist/forms/answers.d.ts +21 -0
  212. package/dist/forms/answers.js +82 -0
  213. package/dist/forms/blocks.d.ts +33 -0
  214. package/dist/forms/blocks.js +178 -0
  215. package/dist/forms/conditions.d.ts +78 -0
  216. package/dist/forms/conditions.js +184 -0
  217. package/dist/forms/emails.d.ts +23 -0
  218. package/dist/forms/emails.js +64 -0
  219. package/dist/forms/fieldConfigs.d.ts +35 -0
  220. package/dist/forms/fieldConfigs.js +167 -0
  221. package/dist/forms/fieldOps.d.ts +78 -0
  222. package/dist/forms/fieldOps.js +378 -0
  223. package/dist/forms/fieldSettings.d.ts +81 -0
  224. package/dist/forms/fieldSettings.js +239 -0
  225. package/dist/forms/files.d.ts +54 -0
  226. package/dist/forms/files.js +128 -0
  227. package/dist/forms/index.d.ts +16 -0
  228. package/dist/forms/index.js +18 -0
  229. package/dist/forms/mergeTags.d.ts +103 -0
  230. package/dist/forms/mergeTags.js +150 -0
  231. package/dist/forms/noScript.d.ts +60 -0
  232. package/dist/forms/noScript.js +109 -0
  233. package/dist/forms/pageForms.d.ts +99 -0
  234. package/dist/forms/pageForms.js +294 -0
  235. package/dist/forms/pageSync.d.ts +91 -0
  236. package/dist/forms/pageSync.js +325 -0
  237. package/dist/forms/rateLimit.d.ts +21 -0
  238. package/dist/forms/rateLimit.js +50 -0
  239. package/dist/forms/settings.d.ts +13 -0
  240. package/dist/forms/settings.js +92 -0
  241. package/dist/forms/spam.d.ts +100 -0
  242. package/dist/forms/spam.js +218 -0
  243. package/dist/forms/spamSettings.d.ts +43 -0
  244. package/dist/forms/spamSettings.js +25 -0
  245. package/dist/forms/submission.d.ts +34 -0
  246. package/dist/forms/submission.js +89 -0
  247. package/dist/forms/submissionsAdmin.d.ts +26 -0
  248. package/dist/forms/submissionsAdmin.js +108 -0
  249. package/dist/forms/summary.d.ts +60 -0
  250. package/dist/forms/summary.js +113 -0
  251. package/dist/forms/uploads.d.ts +41 -0
  252. package/dist/forms/uploads.js +132 -0
  253. package/dist/index.d.ts +8 -2
  254. package/dist/index.js +8 -2
  255. package/dist/live/document.d.ts +12 -0
  256. package/dist/live/document.js +8 -1
  257. package/dist/live/draftAccess.js +1 -1
  258. package/dist/live/endpoints.d.ts +1 -0
  259. package/dist/live/session.js +3 -1
  260. package/dist/live/storage.d.ts +13 -2
  261. package/dist/live/storage.js +18 -7
  262. package/dist/mcp/forms.d.ts +26 -0
  263. package/dist/mcp/forms.js +280 -0
  264. package/dist/mcp/index.d.ts +7 -0
  265. package/dist/mcp/index.js +29 -10
  266. package/dist/mcp/shared.d.ts +1 -0
  267. package/dist/mcp/shared.js +1 -0
  268. package/dist/plugin/forms.d.ts +30 -0
  269. package/dist/plugin/forms.js +63 -0
  270. package/dist/plugin/formsSync.d.ts +138 -0
  271. package/dist/plugin/formsSync.js +345 -0
  272. package/dist/plugin/hook.d.ts +22 -0
  273. package/dist/plugin/hook.js +19 -7
  274. package/dist/plugin/index.d.ts +14 -0
  275. package/dist/plugin/index.js +101 -30
  276. package/dist/plugin/links.d.ts +7 -2
  277. package/dist/plugin/links.js +9 -3
  278. package/dist/plugin/references.d.ts +6 -0
  279. package/dist/plugin/references.js +12 -0
  280. package/dist/plugin/sections.js +3 -0
  281. package/dist/plugin/templates.js +5 -1
  282. package/dist/react/canvas/BuilderCanvas.d.ts +2 -0
  283. package/dist/react/canvas/BuilderCanvas.js +29 -6
  284. package/dist/react/canvas/inline/candidates.js +2 -2
  285. package/dist/react/canvas/inline/mapper.d.ts +6 -1
  286. package/dist/react/canvas/inline/mapper.js +35 -4
  287. package/dist/react/canvas/inline/rich/editor.js +9 -1
  288. package/dist/react/components/Image.d.ts +1 -1
  289. package/dist/react/components/Image.js +2 -2
  290. package/dist/react/render/LayoutOutlet.d.ts +7 -3
  291. package/dist/react/render/LayoutOutlet.js +9 -4
  292. package/dist/react/render/RenderLayout.js +13 -7
  293. package/dist/react/render/resolve.d.ts +1 -0
  294. package/dist/react/render/resolve.js +7 -1
  295. package/dist/react/render/templates.js +3 -1
  296. package/dist/react/server.js +19 -0
  297. package/dist/react/theme/ThemeStyle.js +1 -1
  298. package/dist/theme/admin/ColorField.d.ts +4 -3
  299. package/dist/theme/admin/ColorField.js +1 -1
  300. package/dist/theme/admin/FontField.d.ts +4 -3
  301. package/dist/theme/admin/FontField.js +1 -1
  302. package/dist/theme/admin/SaveSignal.js +1 -1
  303. package/dist/theme/admin/SliderField.d.ts +1 -1
  304. package/dist/theme/admin/SliderField.js +1 -1
  305. package/dist/theme/admin/Variables.d.ts +4 -3
  306. package/dist/theme/admin/Variables.js +2 -2
  307. package/dist/theme/admin/fields.css +327 -0
  308. package/dist/theme/global.js +2 -0
  309. package/package.json +29 -24
  310. package/dist/admin/aiKeyField.scss +0 -58
  311. package/dist/admin/diff/layoutDiff.scss +0 -181
  312. package/dist/admin/editor/classes/manager.scss +0 -262
  313. package/dist/admin/editor/fields/fields.scss +0 -628
  314. package/dist/admin/editor/layout/layout.scss +0 -240
  315. package/dist/admin/editor/locale/locale.scss +0 -154
  316. package/dist/admin/editor/menu/menu.scss +0 -132
  317. package/dist/admin/editor/sections/components.scss +0 -238
  318. package/dist/admin/editor/sections/variants.scss +0 -90
  319. package/dist/admin/editor/topbar/contentMode.scss +0 -35
  320. package/dist/admin/editor/topbar/screens/screens.scss +0 -134
  321. package/dist/admin/editor/topbar/settingsDrawer.scss +0 -32
  322. package/dist/admin/editor/ui/controls.scss +0 -320
  323. package/dist/admin/layoutField.scss +0 -69
  324. package/dist/admin/templateConditions.scss +0 -24
  325. package/dist/theme/admin/fields.scss +0 -363
@@ -0,0 +1,113 @@
1
+ // What a form submission says, for people: the answers in the form's order with the form's labels,
2
+ // a one-line summary (name and email when present) and a reply link. Pure and client-safe: the
3
+ // submissions admin (list cell, detail view) and the starter's dashboard widget use it.
4
+ // No characters that would add mailto headers (?, &, =) or break the link.
5
+ const EMAIL_VALUE = /^[^\s@<>()"',;:?&=#%/\\]+@[^\s@<>()"',;:?&=#%/\\]+\.[^\s@<>()"',;:?&=#%/\\.]+$/;
6
+ const EMAIL_NAME = /e-?mail/i;
7
+ const NAME_NAME = /name/i;
8
+ const FIRST_NAME = /^(first|given|fore)[\s_-]?name$/i;
9
+ const LAST_NAME = /^(last|family|sur)[\s_-]?name$|^surname$/i;
10
+ const MESSAGE_NAME = /message|comment|question|details|enquiry|inquiry|note/i;
11
+ const TRUE_VALUES = new Set(['true', 'on', '1', 'yes']);
12
+ /** True for a plain email address. */
13
+ export function isEmailAddress(value) {
14
+ return typeof value === 'string' && EMAIL_VALUE.test(value.trim());
15
+ }
16
+ function asText(value) {
17
+ if (value === null || value === undefined)
18
+ return '';
19
+ if (typeof value === 'string')
20
+ return value;
21
+ if (typeof value === 'number' || typeof value === 'boolean')
22
+ return String(value);
23
+ return JSON.stringify(value);
24
+ }
25
+ function displayOf(field, value) {
26
+ if (field?.blockType === 'checkbox')
27
+ return TRUE_VALUES.has(value.trim().toLowerCase()) ? 'Yes' : 'No';
28
+ const option = field?.options?.find((o) => o?.value === value);
29
+ return option?.label?.trim() || value;
30
+ }
31
+ /**
32
+ * The answers in the form's field order, with the form's labels. Answers for names the form no
33
+ * longer has come last, labelled with their name. Fields without an answer (hidden by display
34
+ * conditions, or added later) and messages are left out.
35
+ */
36
+ export function submissionAnswers(fields, rows) {
37
+ const byName = new Map();
38
+ for (const row of rows ?? []) {
39
+ if (typeof row?.field !== 'string' || row.field === '' || byName.has(row.field))
40
+ continue;
41
+ byName.set(row.field, asText(row.value));
42
+ }
43
+ const out = [];
44
+ const used = new Set();
45
+ for (const field of fields ?? []) {
46
+ const name = typeof field?.name === 'string' ? field.name : '';
47
+ if (!name || used.has(name) || field.blockType === 'message' || !byName.has(name))
48
+ continue;
49
+ used.add(name);
50
+ const value = byName.get(name) ?? '';
51
+ out.push({ name, label: field.label?.trim() || name, value, display: displayOf(field, value), type: field.blockType ?? null });
52
+ }
53
+ for (const [name, value] of byName) {
54
+ if (!used.has(name))
55
+ out.push({ name, label: name, value, display: value, type: null });
56
+ }
57
+ return out;
58
+ }
59
+ const filled = (answer) => answer.value.trim() !== '' && answer.type !== 'checkbox';
60
+ const key = (answer) => `${answer.name} ${answer.label}`;
61
+ /**
62
+ * Name, email and message of a submission. Email: an email field, else a field called "email",
63
+ * else the first answer that looks like an address. Name: a field called "name" (first and last
64
+ * name are joined). Text: a message-like field, else the first other answer.
65
+ */
66
+ export function submissionSummary(rows, fields) {
67
+ const answers = submissionAnswers(fields, rows).filter(filled);
68
+ const email = answers.find((a) => a.type === 'email' && isEmailAddress(a.value)) ??
69
+ answers.find((a) => EMAIL_NAME.test(key(a)) && isEmailAddress(a.value)) ??
70
+ answers.find((a) => isEmailAddress(a.value));
71
+ const rest = answers.filter((a) => a !== email);
72
+ const first = rest.find((a) => FIRST_NAME.test(a.name) || FIRST_NAME.test(a.label));
73
+ const last = rest.find((a) => LAST_NAME.test(a.name) || LAST_NAME.test(a.label));
74
+ const nameAnswers = first && last ? [first, last] : [rest.find((a) => NAME_NAME.test(key(a)))].filter((a) => Boolean(a));
75
+ const name = nameAnswers.map((a) => a.display.trim()).join(' ') || null;
76
+ const others = rest.filter((a) => !nameAnswers.includes(a));
77
+ const message = others.find((a) => MESSAGE_NAME.test(key(a))) ?? others[0];
78
+ const emailText = email?.value.trim() ?? null;
79
+ const text = message?.display.trim() || null;
80
+ return { name, email: emailText, text, line: [name, emailText].filter(Boolean).join(' · ') || text };
81
+ }
82
+ /** A `mailto:` link that replies to `email`, or null when it is not an address. */
83
+ export function replyMailto(email, options = {}) {
84
+ if (!isEmailAddress(email))
85
+ return null;
86
+ const subject = options.subject?.trim();
87
+ return `mailto:${encodeURI(email.trim())}${subject ? `?subject=${encodeURIComponent(subject)}` : ''}`;
88
+ }
89
+ /** One line of text, at most `max` characters, with an ellipsis when cut. */
90
+ export function shortAnswer(text, max = 90) {
91
+ const line = (text ?? '').replace(/\s+/g, ' ').trim();
92
+ return line.length > max ? `${line.slice(0, max - 1).trimEnd()}…` : line;
93
+ }
94
+ /**
95
+ * A page address a submission names, safe to link: an http(s) URL or a site path. Null otherwise.
96
+ * Visitors send it, so nothing else (javascript:, data:) ever becomes a link.
97
+ */
98
+ export function safePageUrl(value) {
99
+ if (typeof value !== 'string')
100
+ return null;
101
+ const url = value.trim();
102
+ if (url.length === 0 || url.length > 2000)
103
+ return null;
104
+ if (url.startsWith('/') && !url.startsWith('//'))
105
+ return url;
106
+ try {
107
+ const parsed = new URL(url);
108
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.href : null;
109
+ }
110
+ catch {
111
+ return null;
112
+ }
113
+ }
@@ -0,0 +1,41 @@
1
+ import { type AfterErrorHook, type CollectionBeforeChangeHook, type PayloadRequest } from 'payload';
2
+ export type FormFileUploadsOptions = {
3
+ /** Slug of the forms collection. Default "forms". */
4
+ forms?: string;
5
+ /**
6
+ * The upload collection the files go to. Required, and keep it private: read access for signed-in
7
+ * users only, files outside `public/` (a public collection such as Media would publish every file).
8
+ */
9
+ collection: string;
10
+ /** The submission's relationship (or upload) field with `hasMany` that links the files. Default "attachments". */
11
+ field?: string;
12
+ /** Upper limit for every file field, in MB. Default 10. */
13
+ maxSizeMb?: number;
14
+ /** Data of the new upload document. Default: `{ alt: <file name> }`. */
15
+ data?: (file: {
16
+ name: string;
17
+ mimetype: string;
18
+ size: number;
19
+ }) => Record<string, unknown>;
20
+ };
21
+ /** `context` key where `formFileUploads` lists the upload documents it created in this request. */
22
+ export declare const FORM_FILES_CONTEXT = "builderFormFiles";
23
+ /**
24
+ * The submissions hook for file fields:
25
+ * `formSubmissionOverrides: { hooks: { beforeChange: [formFileUploads({ collection: 'form-files' })] } }`. Runs on create.
26
+ */
27
+ export declare function formFileUploads(options: FormFileUploadsOptions): CollectionBeforeChangeHook;
28
+ /**
29
+ * Removes the files `formFileUploads` stored in this request: the upload documents (when they are
30
+ * still in the database) and their files on disk (a failed save rolls the documents back, not the
31
+ * files). Disk storage only (`upload.staticDir`); with a cloud storage adapter the files stay.
32
+ * Never throws.
33
+ */
34
+ export declare function removeStoredFormFiles(req: Pick<PayloadRequest, 'context' | 'payload'>): Promise<void>;
35
+ /**
36
+ * The submissions `afterError` hook that removes the files of a submission that failed after they
37
+ * were stored (a refused answer, a database error, a failed email):
38
+ * `formSubmissionOverrides: { hooks: { afterError: [formFileUploadsCleanup()] } }`. Payload runs it
39
+ * for REST and GraphQL requests; server code that creates submissions calls `removeStoredFormFiles`.
40
+ */
41
+ export declare function formFileUploadsCleanup(): AfterErrorHook;
@@ -0,0 +1,132 @@
1
+ // Files of the `file` form field (`fileFormField`): checks and storage. The site's form sends
2
+ // the submission as multipart form data (`_payload` with the JSON, one part per file, named after
3
+ // its field; a field with several files sends several parts with one name). `formFileUploads` is a
4
+ // `beforeChange` hook of the submissions collection: it checks the number of files (one, or the
5
+ // field's `maxFiles` when it allows several), their type and size, stores each file in a private
6
+ // upload collection (not a public one like Media: visitors send CVs and other private files), links
7
+ // them on a relationship field of the submission (`attachments`) and puts the file names and
8
+ // addresses in the answers, so emails show them. A file field without an accepted file has no
9
+ // answer: text a visitor sent for it is dropped. Hidden file fields are skipped, as their other
10
+ // answers are. When the submission fails after files were stored, `formFileUploadsCleanup` (an
11
+ // `afterError` hook) or `removeStoredFormFiles` removes them again.
12
+ import { ValidationError } from 'payload';
13
+ import { FILE_FIELD_MAX_MB } from './fieldConfigs.js';
14
+ import { filesProblem } from './files.js';
15
+ import { applyFormConditions } from './submission.js';
16
+ /** `context` key where `formFileUploads` lists the upload documents it created in this request. */
17
+ export const FORM_FILES_CONTEXT = 'builderFormFiles';
18
+ const idOf = (value) => {
19
+ if (typeof value === 'string' || typeof value === 'number')
20
+ return value;
21
+ if (value && typeof value === 'object' && 'id' in value)
22
+ return idOf(value.id);
23
+ return null;
24
+ };
25
+ /** The file names of an upload document: the file and its image variants. */
26
+ function filenamesOf(doc) {
27
+ const sizes = doc.variants && typeof doc.variants === 'object' ? Object.values(doc.variants) : [];
28
+ return [doc.filename, ...sizes.map((size) => size?.filename)].filter((name) => typeof name === 'string' && name !== '');
29
+ }
30
+ /**
31
+ * The submissions hook for file fields:
32
+ * `formSubmissionOverrides: { hooks: { beforeChange: [formFileUploads({ collection: 'form-files' })] } }`. Runs on create.
33
+ */
34
+ export function formFileUploads(options) {
35
+ const formsSlug = options.forms ?? 'forms';
36
+ const target = options.collection;
37
+ const linkField = options.field ?? 'attachments';
38
+ const limitMb = options.maxSizeMb ?? FILE_FIELD_MAX_MB;
39
+ return async ({ collection, data: incoming, operation, req }) => {
40
+ if (operation !== 'create' || !incoming)
41
+ return incoming;
42
+ // Only this hook links files: a visitor never links existing uploads to a submission.
43
+ const { [linkField]: _sent, ...data } = incoming;
44
+ const id = idOf(data.form);
45
+ if (id === null)
46
+ return data;
47
+ const form = (await req.payload.findByID({ collection: formsSlug, id, depth: 0, req, overrideAccess: true }).catch(() => null));
48
+ const fileFields = (form?.fields ?? []).filter((f) => f.blockType === 'file' && Boolean(f.name));
49
+ if (!form || fileFields.length === 0)
50
+ return data;
51
+ const { hidden } = applyFormConditions(form.fields, data.submissionData);
52
+ // Only stored files answer a file field: a visitor's own text for one ("invoice.pdf (https://…)") never shows in emails.
53
+ const fileNames = new Set(fileFields.map((f) => f.name));
54
+ const rows = (data.submissionData ?? []).filter((row) => typeof row?.field !== 'string' || !fileNames.has(row.field));
55
+ const files = (req.files ?? {});
56
+ const errors = [];
57
+ const accepted = [];
58
+ for (const field of fileFields) {
59
+ if (hidden.has(field.name))
60
+ continue;
61
+ const raw = files[field.name];
62
+ const list = raw ? (Array.isArray(raw) ? raw : [raw]) : [];
63
+ const problem = filesProblem(list, field, limitMb);
64
+ if (problem)
65
+ errors.push({ path: 'submissionData', message: `${field.label || field.name}: ${problem}` });
66
+ else if (list.length > 0)
67
+ accepted.push({ field, files: list });
68
+ }
69
+ if (errors.length > 0)
70
+ throw new ValidationError({ collection: collection.slug, req, errors });
71
+ if (accepted.length === 0)
72
+ return { ...data, submissionData: rows };
73
+ const base = req.payload.config.serverURL || req.headers.get('origin') || '';
74
+ const ids = [];
75
+ const stored = [];
76
+ if (req.context)
77
+ req.context[FORM_FILES_CONTEXT] = stored;
78
+ for (const { field, files: list } of accepted) {
79
+ const values = [];
80
+ for (const file of list) {
81
+ const meta = { name: file.name, mimetype: file.mimetype, size: file.size };
82
+ const doc = (await req.payload.create({
83
+ collection: target,
84
+ data: (options.data?.(meta) ?? { alt: file.name }),
85
+ file: { name: file.name, data: file.data, mimetype: file.mimetype, size: file.size },
86
+ req,
87
+ overrideAccess: true,
88
+ }));
89
+ ids.push(doc.id);
90
+ stored.push({ collection: target, id: doc.id, filenames: filenamesOf(doc) });
91
+ const url = doc.url ? (/^https?:/i.test(doc.url) || !base ? doc.url : new URL(doc.url, base).href) : '';
92
+ values.push(url ? `${doc.filename ?? file.name} (${url})` : (doc.filename ?? file.name));
93
+ }
94
+ rows.push({ field: field.name, value: values.join(', ') });
95
+ }
96
+ return { ...data, submissionData: rows, [linkField]: ids };
97
+ };
98
+ }
99
+ /**
100
+ * Removes the files `formFileUploads` stored in this request: the upload documents (when they are
101
+ * still in the database) and their files on disk (a failed save rolls the documents back, not the
102
+ * files). Disk storage only (`upload.staticDir`); with a cloud storage adapter the files stay.
103
+ * Never throws.
104
+ */
105
+ export async function removeStoredFormFiles(req) {
106
+ const stored = req.context?.[FORM_FILES_CONTEXT];
107
+ if (!Array.isArray(stored) || stored.length === 0)
108
+ return;
109
+ req.context[FORM_FILES_CONTEXT] = [];
110
+ const [{ unlink }, path] = await Promise.all([import('node:fs/promises'), import('node:path')]);
111
+ for (const file of stored) {
112
+ // Its own transaction: the request's one has failed.
113
+ await req.payload.delete({ collection: file.collection, id: file.id, overrideAccess: true }).catch(() => undefined);
114
+ const config = req.payload.collections[file.collection]?.config.upload;
115
+ const dir = config && typeof config === 'object' ? config.staticDir : undefined;
116
+ if (!dir)
117
+ continue;
118
+ for (const name of file.filenames)
119
+ await unlink(path.resolve(dir, path.basename(name))).catch(() => undefined);
120
+ }
121
+ }
122
+ /**
123
+ * The submissions `afterError` hook that removes the files of a submission that failed after they
124
+ * were stored (a refused answer, a database error, a failed email):
125
+ * `formSubmissionOverrides: { hooks: { afterError: [formFileUploadsCleanup()] } }`. Payload runs it
126
+ * for REST and GraphQL requests; server code that creates submissions calls `removeStoredFormFiles`.
127
+ */
128
+ export function formFileUploadsCleanup() {
129
+ return async ({ req }) => {
130
+ await removeStoredFormFiles(req);
131
+ };
132
+ }
package/dist/index.d.ts CHANGED
@@ -1,7 +1,13 @@
1
1
  export { websiteBuilder, cssFieldName, BUILDER_VIEW_KEY, BUILDER_VIEW_PATH, type WebsiteBuilderOptions, type BuilderCollectionOptions, type GeneratedCss, type TemplatesOptions, type FontFamilies, SITE_CSS_KEY, siteCssConfigOf, type SiteCssConfig, } from './plugin/index.js';
2
2
  export { bindingSources, templatesConfigOf, TEMPLATES_CONFIG_KEY } from './plugin/templates.js';
3
- export { backfillReferences, DEFAULT_REFERENCES_FIELD, findReferrers, FORCE_DELETE_CONTEXT, referencesConfigOf, REFERENCES_CONFIG_KEY, type BackfillResult, type ReferencesOptions, type ReferencesServerConfig, type Referrer, } from './plugin/references.js';
3
+ export { backfillReferences, DEFAULT_REFERENCES_FIELD, findReferrers, layoutReferences, FORCE_DELETE_CONTEXT, referencesConfigOf, REFERENCES_CONFIG_KEY, type BackfillResult, type ReferencesOptions, type ReferencesServerConfig, type Referrer, } from './plugin/references.js';
4
4
  export { builderViewPath } from './plugin/links.js';
5
+ export { formSubmissionConditions, applyFormConditions, type FormSubmissionConditionsOptions, type SubmissionRow } from './forms/submission.js';
6
+ export { formEmails, type FormEmailsOptions } from './forms/emails.js';
7
+ export { FORM_FILES_CONTEXT, formFileUploads, formFileUploadsCleanup, removeStoredFormFiles, type FormFileUploadsOptions } from './forms/uploads.js';
8
+ export { FORM_FIELDS_FIELD, FORM_SETTINGS_REGION, type FormsOptions } from './plugin/forms.js';
9
+ export { formSpamProtection, spamProtectionField, checkSubmission, clientIp, filledTooFast, FORM_NO_SCRIPT_CONTEXT, honeypotFilled, turnstileKeys, TURNSTILE_NEEDS_SCRIPT_MESSAGE, verifyTurnstile, type FormSpamProtectionOptions, type TrustedIpHeader, type SpamProtectionFieldOptions, type SpamReason, } from './forms/spam.js';
10
+ export { formSubmissionsAdmin, SUBMISSION_ANSWERS_FIELD, SUBMISSION_PAGE_FIELD, SUBMISSION_READ_FIELD, SUBMISSION_SUMMARY_FIELD, type FormSubmissionsAdminOptions, } from './forms/submissionsAdmin.js';
5
11
  export { DEFAULT_TEMPLATES_SLUG, DOCUMENT_TEMPLATE_FIELD, TEMPLATE_CONDITIONS_FIELD, TEMPLATE_DEFAULT_FIELD, TEMPLATE_LAYOUT_FIELD, TEMPLATE_PREVIEW_FIELD, TEMPLATE_PRIORITY_FIELD, TEMPLATE_TARGET_FIELD, } from './core/bindings.js';
6
12
  export { defaultBlocks, fromPayloadBlocks, type DefaultBlocksOptions, type FromPayloadBlocksOptions, type PayloadBlockOverride } from './blocks/index.js';
7
13
  export { convertPayloadBlocksLayout, type PayloadConversion, type PayloadConversionReport } from './core/convertPayload.js';
@@ -15,4 +21,4 @@ export type { BindingField, Block, BlockDefinition, BuilderClientConfig, DragMod
15
21
  export type { ThemeOptions } from './theme/config.js';
16
22
  export { DEFAULT_THEME_SLUG } from './theme/config.js';
17
23
  export { classUsage, DEFAULT_CLASSES_SLUG, deleteClass, importSiteClasses, loadClassesSheet, publishClass, removeUnusedClasses, renameClass, storeClassesSheet, unusedClasses, upsertClass, type BuilderClass, type ClassesOptions, type ClassUsage, } from './classes/index.js';
18
- export { DEFAULT_COMMENTS_SLUG, type BuilderComment, type CommentsOptions } from './comments/index.js';
24
+ export { COMMENT_PARAM, DEFAULT_COMMENTS_SLUG, type BuilderComment, type CommentsOptions } from './comments/index.js';
package/dist/index.js CHANGED
@@ -1,8 +1,14 @@
1
1
  // Server entry: the Payload plugin and block helpers. Owner: plugin agent.
2
2
  export { websiteBuilder, cssFieldName, BUILDER_VIEW_KEY, BUILDER_VIEW_PATH, SITE_CSS_KEY, siteCssConfigOf, } from './plugin/index.js';
3
3
  export { bindingSources, templatesConfigOf, TEMPLATES_CONFIG_KEY } from './plugin/templates.js';
4
- export { backfillReferences, DEFAULT_REFERENCES_FIELD, findReferrers, FORCE_DELETE_CONTEXT, referencesConfigOf, REFERENCES_CONFIG_KEY, } from './plugin/references.js';
4
+ export { backfillReferences, DEFAULT_REFERENCES_FIELD, findReferrers, layoutReferences, FORCE_DELETE_CONTEXT, referencesConfigOf, REFERENCES_CONFIG_KEY, } from './plugin/references.js';
5
5
  export { builderViewPath } from './plugin/links.js';
6
+ export { formSubmissionConditions, applyFormConditions } from './forms/submission.js';
7
+ export { formEmails } from './forms/emails.js';
8
+ export { FORM_FILES_CONTEXT, formFileUploads, formFileUploadsCleanup, removeStoredFormFiles } from './forms/uploads.js';
9
+ export { FORM_FIELDS_FIELD, FORM_SETTINGS_REGION } from './plugin/forms.js';
10
+ export { formSpamProtection, spamProtectionField, checkSubmission, clientIp, filledTooFast, FORM_NO_SCRIPT_CONTEXT, honeypotFilled, turnstileKeys, TURNSTILE_NEEDS_SCRIPT_MESSAGE, verifyTurnstile, } from './forms/spam.js';
11
+ export { formSubmissionsAdmin, SUBMISSION_ANSWERS_FIELD, SUBMISSION_PAGE_FIELD, SUBMISSION_READ_FIELD, SUBMISSION_SUMMARY_FIELD, } from './forms/submissionsAdmin.js';
6
12
  export { DEFAULT_TEMPLATES_SLUG, DOCUMENT_TEMPLATE_FIELD, TEMPLATE_CONDITIONS_FIELD, TEMPLATE_DEFAULT_FIELD, TEMPLATE_LAYOUT_FIELD, TEMPLATE_PREVIEW_FIELD, TEMPLATE_PRIORITY_FIELD, TEMPLATE_TARGET_FIELD, } from './core/bindings.js';
7
13
  export { defaultBlocks, fromPayloadBlocks } from './blocks/index.js';
8
14
  export { convertPayloadBlocksLayout } from './core/convertPayload.js';
@@ -15,4 +21,4 @@ export { DEFAULT_THEME_SLUG } from './theme/config.js';
15
21
  // Editable classes: the collection's options and the server actions (scripts, custom endpoints).
16
22
  export { classUsage, DEFAULT_CLASSES_SLUG, deleteClass, importSiteClasses, loadClassesSheet, publishClass, removeUnusedClasses, renameClass, storeClassesSheet, unusedClasses, upsertClass, } from './classes/index.js';
17
23
  // Comments on the canvas: the collection's options and the comment shape.
18
- export { DEFAULT_COMMENTS_SLUG } from './comments/index.js';
24
+ export { COMMENT_PARAM, DEFAULT_COMMENTS_SLUG } from './comments/index.js';
@@ -29,12 +29,24 @@ export type BuilderCollectionServer = {
29
29
  * Left out: the builder's JSON layout field.
30
30
  */
31
31
  payloadBlocks?: PayloadBlocksStorage;
32
+ /**
33
+ * The JSON layout's block types, when one of them has an `upgrade`: it runs when the builder
34
+ * reads a stored layout (`codecOf`). A Payload blocks field uses its own block types.
35
+ */
36
+ blocks?: readonly BlockDefinition[];
32
37
  };
33
38
  /** The builder collections and the templates collection. Stored on `config.custom` for the admin view. */
34
39
  export type BuilderServerConfig = {
35
40
  collections: Record<string, BuilderCollectionServer>;
36
41
  /** Slug of the templates collection, when templates are on. */
37
42
  templates: string | null;
43
+ /** The block list the plugin checks layouts against (forms on pages completed). */
44
+ blocks?: BlockDefinition[];
45
+ /** Forms on pages: the forms collection and its setting names. */
46
+ pageForms?: {
47
+ collection: string;
48
+ settings: string[];
49
+ };
38
50
  };
39
51
  /** Key under `config.custom` where the plugin stores the `BuilderServerConfig`. */
40
52
  export declare const BUILDER_CONFIG_KEY = "websiteBuilder";
@@ -26,7 +26,14 @@ import { LIVE_PATH, requestActor, targetOf } from './endpoints.js';
26
26
  export const BUILDER_CONFIG_KEY = 'websiteBuilder';
27
27
  export function builderConfigOf(payload) {
28
28
  const stored = payload.config.custom?.[BUILDER_CONFIG_KEY];
29
- return stored?.collections ? { collections: stored.collections, templates: stored.templates ?? null } : null;
29
+ if (!stored?.collections)
30
+ return null;
31
+ return {
32
+ collections: stored.collections,
33
+ templates: stored.templates ?? null,
34
+ ...(stored.blocks ? { blocks: stored.blocks } : {}),
35
+ ...(stored.pageForms ? { pageForms: stored.pageForms } : {}),
36
+ };
30
37
  }
31
38
  const api = (req) => req.payload;
32
39
  const text = (value) => (typeof value === 'string' && value ? value : null);
@@ -106,7 +106,7 @@ export async function liveReadProblem(req, target) {
106
106
  if (!config)
107
107
  return DRAFT_NOT_READABLE_MESSAGE;
108
108
  // Without `access.read` (never after Payload's sanitizing), executeAccess allows signed-in users.
109
- const result = await executeAccess({ id: target.id, collectionConfig: config, disableErrors: true, req }, config.access?.read);
109
+ const result = await executeAccess({ id: target.id, slug: target.collection, disableErrors: true, req }, config.access?.read);
110
110
  if (!result)
111
111
  return DRAFT_NOT_READABLE_MESSAGE;
112
112
  // As in Payload: anything but a Where that is not false allows.
@@ -14,6 +14,7 @@ export type LiveEndpointOptions = {
14
14
  field: string;
15
15
  localization?: LocaleSettings | null;
16
16
  payloadBlocks?: PayloadBlocksStorage;
17
+ blocks?: readonly BlockDefinition[];
17
18
  }>;
18
19
  blocks: BlockDefinition[];
19
20
  runtime: LiveRuntime;
@@ -940,7 +940,9 @@ export function createSessionManager(options = {}) {
940
940
  };
941
941
  },
942
942
  async commit(args) {
943
- const { target, store, user, actor, blocks, clientId, batchId, baseSeq } = args;
943
+ const { target, store, user, actor, clientId, batchId, baseSeq } = args;
944
+ // A Payload blocks field checks against its own block types (a form's field blocks).
945
+ const blocks = target.codec?.blocks ?? args.blocks;
944
946
  return mutex.run(channelKey(target.collection, target.id), async () => {
945
947
  let session;
946
948
  try {
@@ -1,6 +1,6 @@
1
1
  import { type PayloadRequest } from 'payload';
2
2
  import { type PayloadBlocksStorage } from '../core/payloadBlocks.js';
3
- import type { Layout, Operation } from '../core/types.js';
3
+ import type { BlockDefinition, Layout, Operation } from '../core/types.js';
4
4
  export type LayoutCodec = {
5
5
  kind: 'json' | 'payload-blocks';
6
6
  /** The stored field value as a layout. Throws a 422 when the value cannot be shown without loss. */
@@ -20,13 +20,24 @@ export type LayoutCodec = {
20
20
  prepare?(layout: Layout, ops: Operation[], owned?: ReadonlySet<string>): Operation[];
21
21
  /** The row ids of a stored value (a Payload blocks field). */
22
22
  rowIds?(value: unknown): Set<string>;
23
+ /**
24
+ * The block types the field holds (a Payload blocks field: its own definitions, such as a form's
25
+ * field blocks). Commits check against them. Left out: the builder's blocks.
26
+ */
27
+ blocks?: readonly BlockDefinition[];
23
28
  };
24
29
  export declare const JSON_CODEC: LayoutCodec;
30
+ /** The codec of the builder's JSON layout that upgrades old blocks (`BlockDefinition.upgrade`) on read. */
31
+ export declare function jsonCodec(blocks: readonly BlockDefinition[]): LayoutCodec;
25
32
  /** The codec of a Payload blocks field. */
26
33
  export declare function payloadBlocksCodec(storage: PayloadBlocksStorage): LayoutCodec;
27
- /** The codec of a builder collection's server config. JSON when it stores no Payload blocks. */
34
+ /**
35
+ * The codec of a builder collection's server config. JSON when it stores no Payload blocks; with
36
+ * `blocks`, the JSON codec upgrades old blocks on read.
37
+ */
28
38
  export declare function codecOf(collection: {
29
39
  payloadBlocks?: PayloadBlocksStorage;
40
+ blocks?: readonly BlockDefinition[];
30
41
  } | undefined): LayoutCodec;
31
42
  /**
32
43
  * True when Payload's read access lets the request's user read every value in `value` (a blocks
@@ -2,11 +2,14 @@
2
2
  // layout the live session, the canvas and the tools work on.
3
3
  //
4
4
  // - `json` (the builder's own JSON layout field): the stored value is the layout.
5
+ // Both run the block definitions' `upgrade` on the layout they read, so an open layout is in the
6
+ // current shape and the next save stores it.
5
7
  // - `payload-blocks` (the collection's own Payload `blocks` field): the stored value is Payload's
6
8
  // block rows, read and written with the lossless codec of core/payloadBlocks.ts. The field stays
7
9
  // the one source of truth; the layout is a view of it while a page is open.
8
10
  import { APIError, docAccessOperation } from 'payload';
9
11
  import { decodePayloadBlocks, encodePayloadBlocks, payloadBlocksProblems, payloadRowIds, withUniqueRowIds } from '../core/payloadBlocks.js';
12
+ import { upgradeLayout } from '../core/blocks.js';
10
13
  import { normalizeLayout } from '../core/tree.js';
11
14
  import { applyOperation } from '../core/operations.js';
12
15
  export const JSON_CODEC = {
@@ -15,15 +18,21 @@ export const JSON_CODEC = {
15
18
  encode: (layout) => layout,
16
19
  problems: () => [],
17
20
  };
21
+ /** The codec of the builder's JSON layout that upgrades old blocks (`BlockDefinition.upgrade`) on read. */
22
+ export function jsonCodec(blocks) {
23
+ return { ...JSON_CODEC, decode: (value) => upgradeLayout(normalizeLayout(value), blocks) };
24
+ }
18
25
  /** The codec of a Payload blocks field. */
19
26
  export function payloadBlocksCodec(storage) {
27
+ const blocks = storage.blocks;
20
28
  return {
21
29
  kind: 'payload-blocks',
30
+ blocks,
22
31
  decode(value) {
23
32
  const result = decodePayloadBlocks(value, storage);
24
33
  if (!result.ok)
25
34
  throw new APIError(`The builder cannot open these blocks without changing them: ${result.error}`, 422, undefined, true);
26
- return result.layout;
35
+ return upgradeLayout(result.layout, blocks);
27
36
  },
28
37
  encode: (layout, previous) => encodePayloadBlocks(layout, storage, previous),
29
38
  problems: (layout) => payloadBlocksProblems(layout, storage),
@@ -32,15 +41,17 @@ export function payloadBlocksCodec(storage) {
32
41
  };
33
42
  }
34
43
  const codecs = new WeakMap();
35
- /** The codec of a builder collection's server config. JSON when it stores no Payload blocks. */
44
+ /**
45
+ * The codec of a builder collection's server config. JSON when it stores no Payload blocks; with
46
+ * `blocks`, the JSON codec upgrades old blocks on read.
47
+ */
36
48
  export function codecOf(collection) {
37
- const storage = collection?.payloadBlocks;
38
- if (!storage)
49
+ if (!collection)
39
50
  return JSON_CODEC;
40
- let codec = codecs.get(storage);
51
+ let codec = codecs.get(collection);
41
52
  if (!codec) {
42
- codec = payloadBlocksCodec(storage);
43
- codecs.set(storage, codec);
53
+ codec = collection.payloadBlocks ? payloadBlocksCodec(collection.payloadBlocks) : collection.blocks ? jsonCodec(collection.blocks) : JSON_CODEC;
54
+ codecs.set(collection, codec);
44
55
  }
45
56
  return codec;
46
57
  }
@@ -0,0 +1,26 @@
1
+ import type { PayloadRequest } from 'payload';
2
+ import type { Layout, Operation } from '../core/types.js';
3
+ import type { CommitResult } from '../live/session.js';
4
+ import type { BuilderMcpTool, McpToolResult } from './index.js';
5
+ export type FormToolsContext = {
6
+ /** Slug of the forms collection. */
7
+ slug: string;
8
+ /** Commits operations to the document's live session as the AI collaborator. */
9
+ apply: (req: PayloadRequest, collection: string, id: string, ops: (layout: Layout) => Operation[] | string) => Promise<CommitResult>;
10
+ /** The layout people see now (the live session's, else the stored one). */
11
+ currentLayout: (req: PayloadRequest, collection: string, doc: Record<string, unknown>) => Promise<{
12
+ layout: Layout;
13
+ seq?: number;
14
+ }>;
15
+ /** The latest draft, read as the request's user. */
16
+ loadDraft: (req: PayloadRequest, collection: string, id: string) => Promise<Record<string, unknown>>;
17
+ /** The commit's warnings for the blocks it touched. */
18
+ warnings: (req: PayloadRequest, collection: string, result: Extract<CommitResult, {
19
+ ok: true;
20
+ }>) => Record<string, unknown>;
21
+ /** The site's absolute origin. */
22
+ siteOf: (req: PayloadRequest) => string;
23
+ text: (value: unknown) => McpToolResult;
24
+ fail: (message: string, details?: unknown) => McpToolResult;
25
+ };
26
+ export declare function formMcpTools(ctx: FormToolsContext): BuilderMcpTool[];