@cossackframework/cms 0.0.0 → 0.9.1

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 (427) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +145 -2
  3. package/agent-docs.json +259 -0
  4. package/app/README.md +78 -0
  5. package/app/cossack-recipe.json +43 -0
  6. package/app/src/auth-bot-check.ts +32 -0
  7. package/app/src/auth-bot-token.ts +11 -0
  8. package/app/src/auth-input.ts +35 -0
  9. package/app/src/auth-options.ts +18 -0
  10. package/app/src/auth-providers.ts +16 -0
  11. package/app/src/auth.ts +1082 -0
  12. package/app/src/brand.ts +68 -0
  13. package/app/src/cms/ai.ts +54 -0
  14. package/app/src/cms/analytics.ts +33 -0
  15. package/app/src/cms/block-errors.ts +55 -0
  16. package/app/src/cms/block-inserter.ts +111 -0
  17. package/app/src/cms/block-panel.ts +68 -0
  18. package/app/src/cms/block-rows.ts +44 -0
  19. package/app/src/cms/block-tree.ts +585 -0
  20. package/app/src/cms/blocks.css +708 -0
  21. package/app/src/cms/builder.ts +126 -0
  22. package/app/src/cms/cache.ts +44 -0
  23. package/app/src/cms/carousel.client.ts +52 -0
  24. package/app/src/cms/collab/presence.ts +69 -0
  25. package/app/src/cms/collab/rich-text-collab.client.ts +197 -0
  26. package/app/src/cms/collab/rich-text-notes.client.ts +138 -0
  27. package/app/src/cms/collab/room.ts +881 -0
  28. package/app/src/cms/compare.client.ts +47 -0
  29. package/app/src/cms/condition-control.ts +109 -0
  30. package/app/src/cms/content-api.ts +143 -0
  31. package/app/src/cms/content.ts +524 -0
  32. package/app/src/cms/countdown.client.ts +37 -0
  33. package/app/src/cms/editor-layout-editor.ts +260 -0
  34. package/app/src/cms/editor-layout-view.ts +37 -0
  35. package/app/src/cms/editor.ts +381 -0
  36. package/app/src/cms/entry.ts +26 -0
  37. package/app/src/cms/feeds.ts +145 -0
  38. package/app/src/cms/field-controls.ts +222 -0
  39. package/app/src/cms/field-group-editor.ts +105 -0
  40. package/app/src/cms/field-group-view.ts +211 -0
  41. package/app/src/cms/form-view.ts +203 -0
  42. package/app/src/cms/form.client.ts +203 -0
  43. package/app/src/cms/guards.ts +27 -0
  44. package/app/src/cms/handoff.ts +202 -0
  45. package/app/src/cms/headings.ts +51 -0
  46. package/app/src/cms/icons.ts +80 -0
  47. package/app/src/cms/import.client.ts +16 -0
  48. package/app/src/cms/index.ts +191 -0
  49. package/app/src/cms/lightbox.client.ts +109 -0
  50. package/app/src/cms/machine.ts +118 -0
  51. package/app/src/cms/maintenance.ts +97 -0
  52. package/app/src/cms/manage.ts +1236 -0
  53. package/app/src/cms/mcp-tools.ts +388 -0
  54. package/app/src/cms/mcp.ts +242 -0
  55. package/app/src/cms/media-chooser.ts +123 -0
  56. package/app/src/cms/media-usage.ts +57 -0
  57. package/app/src/cms/middleware.ts +199 -0
  58. package/app/src/cms/middlewares.ts +13 -0
  59. package/app/src/cms/network-ui.ts +36 -0
  60. package/app/src/cms/network-view.ts +38 -0
  61. package/app/src/cms/notes-announce.ts +65 -0
  62. package/app/src/cms/notes-rail.ts +207 -0
  63. package/app/src/cms/notification-rules.ts +66 -0
  64. package/app/src/cms/recovery.ts +82 -0
  65. package/app/src/cms/replace.ts +63 -0
  66. package/app/src/cms/reserved-paths.ts +19 -0
  67. package/app/src/cms/rich-text-field.ts +325 -0
  68. package/app/src/cms/rich-text-schema.ts +91 -0
  69. package/app/src/cms/rich-text.client.ts +255 -0
  70. package/app/src/cms/search.client.ts +116 -0
  71. package/app/src/cms/seo-head.ts +78 -0
  72. package/app/src/cms/seo.ts +241 -0
  73. package/app/src/cms/settings-draft.ts +218 -0
  74. package/app/src/cms/settings-file.ts +127 -0
  75. package/app/src/cms/settings-form.ts +180 -0
  76. package/app/src/cms/settings-languages.ts +125 -0
  77. package/app/src/cms/settings-nav.ts +102 -0
  78. package/app/src/cms/settings-network.ts +151 -0
  79. package/app/src/cms/settings-permalinks.ts +114 -0
  80. package/app/src/cms/settings-scroll.ts +10 -0
  81. package/app/src/cms/settings-search.ts +77 -0
  82. package/app/src/cms/settings-section.ts +38 -0
  83. package/app/src/cms/share.client.ts +27 -0
  84. package/app/src/cms/site-editing.ts +219 -0
  85. package/app/src/cms/site-editor.client.ts +1008 -0
  86. package/app/src/cms/site-editor.ts +99 -0
  87. package/app/src/cms/site-export.ts +60 -0
  88. package/app/src/cms/site-forms.ts +143 -0
  89. package/app/src/cms/site-import.ts +28 -0
  90. package/app/src/cms/site-session.ts +36 -0
  91. package/app/src/cms/site-taskbar.ts +77 -0
  92. package/app/src/cms/site-view.ts +1014 -0
  93. package/app/src/cms/site.ts +1322 -0
  94. package/app/src/cms/sitemaps.ts +131 -0
  95. package/app/src/cms/stat.client.ts +56 -0
  96. package/app/src/cms/style-controls.ts +252 -0
  97. package/app/src/cms/tabs.client.ts +36 -0
  98. package/app/src/cms/taskbar.ts +134 -0
  99. package/app/src/cms/term-icons.ts +10 -0
  100. package/app/src/cms/traffic.ts +26 -0
  101. package/app/src/cms/ui.ts +170 -0
  102. package/app/src/cms/updates.ts +124 -0
  103. package/app/src/cms/uploads.ts +26 -0
  104. package/app/src/cms/worker.ts +13 -0
  105. package/app/src/config/auth.ts +30 -0
  106. package/app/src/config/cms.ts +18 -0
  107. package/app/src/dashboard/access.ts +344 -0
  108. package/app/src/dashboard/agent-icons.ts +44 -0
  109. package/app/src/dashboard/app-passwords.ts +74 -0
  110. package/app/src/dashboard/avatar-field.ts +58 -0
  111. package/app/src/dashboard/bulk.ts +53 -0
  112. package/app/src/dashboard/head.ts +29 -0
  113. package/app/src/dashboard/icons.ts +15 -0
  114. package/app/src/dashboard/list-table.ts +120 -0
  115. package/app/src/dashboard/modules/roles.ts +15 -0
  116. package/app/src/dashboard/modules/sessions.ts +15 -0
  117. package/app/src/dashboard/modules/settings.ts +15 -0
  118. package/app/src/dashboard/modules/users.ts +18 -0
  119. package/app/src/dashboard/page.ts +67 -0
  120. package/app/src/dashboard/registry.ts +13 -0
  121. package/app/src/dashboard/session-list.ts +98 -0
  122. package/app/src/dashboard/tabs.ts +26 -0
  123. package/app/src/dashboard/time-ago.ts +16 -0
  124. package/app/src/dashboard/types.ts +40 -0
  125. package/app/src/dashboard/user-sections.ts +172 -0
  126. package/app/src/lib/permissions.ts +84 -0
  127. package/app/src/middlewares/auth.ts +117 -0
  128. package/app/src/pages/(site)/[...path]/index.ts +609 -0
  129. package/app/src/pages/(site)/feed/[...rest]/index.ts +13 -0
  130. package/app/src/pages/(site)/feed/index.ts +12 -0
  131. package/app/src/pages/(site)/index.ts +11 -0
  132. package/app/src/pages/(site)/indexnow/[file]/index.ts +18 -0
  133. package/app/src/pages/(site)/layout.ts +219 -0
  134. package/app/src/pages/(site)/llms.txt/index.ts +23 -0
  135. package/app/src/pages/(site)/manifest.webmanifest/index.ts +29 -0
  136. package/app/src/pages/(site)/media/[id]/[name]/index.ts +59 -0
  137. package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +115 -0
  138. package/app/src/pages/(site)/robots.txt/index.ts +29 -0
  139. package/app/src/pages/(site)/search/index.ts +36 -0
  140. package/app/src/pages/(site)/sitemap.xml/index.ts +26 -0
  141. package/app/src/pages/(site)/sitemaps/[file]/index.ts +33 -0
  142. package/app/src/pages/api/auth/session.ts +48 -0
  143. package/app/src/pages/api/cms/appearance/areas/[name].ts +12 -0
  144. package/app/src/pages/api/cms/appearance/areas/index.ts +6 -0
  145. package/app/src/pages/api/cms/appearance/locations/[location].ts +6 -0
  146. package/app/src/pages/api/cms/appearance/locations/index.ts +6 -0
  147. package/app/src/pages/api/cms/appearance/menus/[id].ts +12 -0
  148. package/app/src/pages/api/cms/appearance/menus/index.ts +13 -0
  149. package/app/src/pages/api/cms/appearance/themes/[name]/activate.ts +6 -0
  150. package/app/src/pages/api/cms/appearance/themes/index.ts +6 -0
  151. package/app/src/pages/api/cms/cache/purge.ts +6 -0
  152. package/app/src/pages/api/cms/collections/index.ts +6 -0
  153. package/app/src/pages/api/cms/commands/[plugin]/[command].ts +26 -0
  154. package/app/src/pages/api/cms/comments/[id].ts +9 -0
  155. package/app/src/pages/api/cms/comments/index.ts +126 -0
  156. package/app/src/pages/api/cms/comments/queue.ts +6 -0
  157. package/app/src/pages/api/cms/content/[collection]/[entry]/autosave.ts +27 -0
  158. package/app/src/pages/api/cms/content/[collection]/[entry]/blocks/[block].ts +16 -0
  159. package/app/src/pages/api/cms/content/[collection]/[entry]/notes.ts +18 -0
  160. package/app/src/pages/api/cms/content/[collection]/[entry]/publish.ts +11 -0
  161. package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/index.ts +6 -0
  162. package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/restore.ts +6 -0
  163. package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/index.ts +6 -0
  164. package/app/src/pages/api/cms/content/[collection]/[entry]/unpublish.ts +6 -0
  165. package/app/src/pages/api/cms/content/[collection]/[entry].ts +42 -0
  166. package/app/src/pages/api/cms/content/[collection]/index.ts +24 -0
  167. package/app/src/pages/api/cms/export/[collection].ts +37 -0
  168. package/app/src/pages/api/cms/forms/[slug]/index.ts +173 -0
  169. package/app/src/pages/api/cms/forms/[slug]/submissions/[submission]/files/[file].ts +25 -0
  170. package/app/src/pages/api/cms/forms/[slug]/submissions/export.ts +34 -0
  171. package/app/src/pages/api/cms/forms/[slug]/submissions/index.ts +24 -0
  172. package/app/src/pages/api/cms/import/[collection].ts +23 -0
  173. package/app/src/pages/api/cms/mcp.ts +29 -0
  174. package/app/src/pages/api/cms/me/index.ts +6 -0
  175. package/app/src/pages/api/cms/me/recent-blocks.ts +37 -0
  176. package/app/src/pages/api/cms/me/tokens/[id].ts +6 -0
  177. package/app/src/pages/api/cms/me/tokens/index.ts +13 -0
  178. package/app/src/pages/api/cms/media/[id].ts +6 -0
  179. package/app/src/pages/api/cms/media.ts +26 -0
  180. package/app/src/pages/api/cms/menus/[location].ts +14 -0
  181. package/app/src/pages/api/cms/network/sites/[id]/export.ts +15 -0
  182. package/app/src/pages/api/cms/network/sites/[id]/index.ts +9 -0
  183. package/app/src/pages/api/cms/network/sites/index.ts +14 -0
  184. package/app/src/pages/api/cms/notes/[id].ts +13 -0
  185. package/app/src/pages/api/cms/notes/index.ts +6 -0
  186. package/app/src/pages/api/cms/payments/webhook.ts +28 -0
  187. package/app/src/pages/api/cms/plugins/[name]/grant.ts +6 -0
  188. package/app/src/pages/api/cms/plugins/[name]/revoke.ts +6 -0
  189. package/app/src/pages/api/cms/plugins/index.ts +6 -0
  190. package/app/src/pages/api/cms/recovery.ts +29 -0
  191. package/app/src/pages/api/cms/redirects/index.ts +9 -0
  192. package/app/src/pages/api/cms/roles/index.ts +6 -0
  193. package/app/src/pages/api/cms/schema/[collection].ts +13 -0
  194. package/app/src/pages/api/cms/search.ts +16 -0
  195. package/app/src/pages/api/cms/settings/[group].ts +9 -0
  196. package/app/src/pages/api/cms/settings/index.ts +9 -0
  197. package/app/src/pages/api/cms/site-export.ts +34 -0
  198. package/app/src/pages/api/cms/taxonomies/index.ts +6 -0
  199. package/app/src/pages/api/cms/terms/[taxonomy]/[id].ts +12 -0
  200. package/app/src/pages/api/cms/terms/[taxonomy]/index.ts +9 -0
  201. package/app/src/pages/api/cms/uploads/[id]/complete.ts +15 -0
  202. package/app/src/pages/api/cms/uploads/[id]/index.ts +15 -0
  203. package/app/src/pages/api/cms/uploads/index.ts +26 -0
  204. package/app/src/pages/api/cms/users/[id]/index.ts +12 -0
  205. package/app/src/pages/api/cms/users/[id]/meta.ts +40 -0
  206. package/app/src/pages/api/cms/users/index.ts +12 -0
  207. package/app/src/pages/api/cms/webhooks/[id].ts +6 -0
  208. package/app/src/pages/api/cms/webhooks/index.ts +9 -0
  209. package/app/src/pages/auth/[provider]/callback.ts +11 -0
  210. package/app/src/pages/auth/[provider]/redirect.ts +9 -0
  211. package/app/src/pages/auth/forgot-password/index.ts +75 -0
  212. package/app/src/pages/auth/layout.ts +32 -0
  213. package/app/src/pages/auth/login/index.ts +198 -0
  214. package/app/src/pages/auth/magic/index.ts +68 -0
  215. package/app/src/pages/auth/register/index.ts +117 -0
  216. package/app/src/pages/auth/reset-password/index.ts +65 -0
  217. package/app/src/pages/auth/setup/index.ts +194 -0
  218. package/app/src/pages/auth/two-factor/index.ts +67 -0
  219. package/app/src/pages/auth/verify/index.ts +62 -0
  220. package/app/src/pages/dashboard/(cms)/appearance/customize/index.ts +263 -0
  221. package/app/src/pages/dashboard/(cms)/appearance/dashboard-menu/index.ts +241 -0
  222. package/app/src/pages/dashboard/(cms)/appearance/index.ts +89 -0
  223. package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +697 -0
  224. package/app/src/pages/dashboard/(cms)/appearance/menus/index.ts +145 -0
  225. package/app/src/pages/dashboard/(cms)/appearance/widgets/index.ts +279 -0
  226. package/app/src/pages/dashboard/(cms)/blocks/index.ts +84 -0
  227. package/app/src/pages/dashboard/(cms)/calendar/index.ts +92 -0
  228. package/app/src/pages/dashboard/(cms)/collections/[name]/index.ts +525 -0
  229. package/app/src/pages/dashboard/(cms)/collections/index.ts +72 -0
  230. package/app/src/pages/dashboard/(cms)/collections/new/index.ts +66 -0
  231. package/app/src/pages/dashboard/(cms)/comments/index.ts +237 -0
  232. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +2382 -0
  233. package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +126 -0
  234. package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +693 -0
  235. package/app/src/pages/dashboard/(cms)/field-groups/[id]/index.ts +193 -0
  236. package/app/src/pages/dashboard/(cms)/field-groups/index.ts +65 -0
  237. package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/[submission]/index.ts +279 -0
  238. package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/index.ts +170 -0
  239. package/app/src/pages/dashboard/(cms)/forms/index.ts +171 -0
  240. package/app/src/pages/dashboard/(cms)/media/[id]/index.ts +317 -0
  241. package/app/src/pages/dashboard/(cms)/media/index.ts +156 -0
  242. package/app/src/pages/dashboard/(cms)/media/new/index.ts +9 -0
  243. package/app/src/pages/dashboard/(cms)/media/summary/index.ts +74 -0
  244. package/app/src/pages/dashboard/(cms)/my-sites/index.ts +63 -0
  245. package/app/src/pages/dashboard/(cms)/network/index.ts +53 -0
  246. package/app/src/pages/dashboard/(cms)/network/plugins/index.ts +110 -0
  247. package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +243 -0
  248. package/app/src/pages/dashboard/(cms)/network/sites/index.ts +186 -0
  249. package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +77 -0
  250. package/app/src/pages/dashboard/(cms)/network/themes/index.ts +82 -0
  251. package/app/src/pages/dashboard/(cms)/network/updates/index.ts +48 -0
  252. package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +176 -0
  253. package/app/src/pages/dashboard/(cms)/network/users/index.ts +174 -0
  254. package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +66 -0
  255. package/app/src/pages/dashboard/(cms)/plugins/index.ts +172 -0
  256. package/app/src/pages/dashboard/(cms)/profile/public/index.ts +105 -0
  257. package/app/src/pages/dashboard/(cms)/registrations/index.ts +70 -0
  258. package/app/src/pages/dashboard/(cms)/settings/index.ts +359 -0
  259. package/app/src/pages/dashboard/(cms)/settings/json/index.ts +202 -0
  260. package/app/src/pages/dashboard/(cms)/settings/layout.ts +67 -0
  261. package/app/src/pages/dashboard/(cms)/taxonomies/[name]/index.ts +85 -0
  262. package/app/src/pages/dashboard/(cms)/taxonomies/index.ts +98 -0
  263. package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/[id]/index.ts +244 -0
  264. package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/index.ts +148 -0
  265. package/app/src/pages/dashboard/(cms)/tools/activity/index.ts +94 -0
  266. package/app/src/pages/dashboard/(cms)/tools/automations/index.ts +131 -0
  267. package/app/src/pages/dashboard/(cms)/tools/cache/index.ts +92 -0
  268. package/app/src/pages/dashboard/(cms)/tools/export/index.ts +99 -0
  269. package/app/src/pages/dashboard/(cms)/tools/health/index.ts +189 -0
  270. package/app/src/pages/dashboard/(cms)/tools/jobs/index.ts +93 -0
  271. package/app/src/pages/dashboard/(cms)/tools/links/index.ts +115 -0
  272. package/app/src/pages/dashboard/(cms)/tools/redirects/index.ts +161 -0
  273. package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +124 -0
  274. package/app/src/pages/dashboard/(cms)/tools/schema/index.ts +54 -0
  275. package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +156 -0
  276. package/app/src/pages/dashboard/(cms)/tools/updates/index.ts +114 -0
  277. package/app/src/pages/dashboard/(cms)/tools/webhooks/index.ts +182 -0
  278. package/app/src/pages/dashboard/index.ts +214 -0
  279. package/app/src/pages/dashboard/layout.ts +320 -0
  280. package/app/src/pages/dashboard/profile/index.ts +211 -0
  281. package/app/src/pages/dashboard/profile/security/index.ts +255 -0
  282. package/app/src/pages/dashboard/roles/[id]/index.ts +116 -0
  283. package/app/src/pages/dashboard/roles/index.ts +134 -0
  284. package/app/src/pages/dashboard/roles/new/index.ts +95 -0
  285. package/app/src/pages/dashboard/sessions/index.ts +105 -0
  286. package/app/src/pages/dashboard/users/[id]/index.ts +472 -0
  287. package/app/src/pages/dashboard/users/index.ts +299 -0
  288. package/app/src/pages/dashboard/users/new/index.ts +123 -0
  289. package/app/src/passkeys.client.ts +18 -0
  290. package/app/src/plugins/default-theme/assets/cover.svg +31 -0
  291. package/app/src/plugins/default-theme/assets/logo.svg +8 -0
  292. package/app/src/plugins/default-theme/parts/comments.ts +66 -0
  293. package/app/src/plugins/default-theme/parts/list.ts +38 -0
  294. package/app/src/plugins/default-theme/parts/media.ts +15 -0
  295. package/app/src/plugins/default-theme/parts/options.ts +45 -0
  296. package/app/src/plugins/default-theme/plugin.json +275 -0
  297. package/app/src/plugins/default-theme/templates/archive.ts +14 -0
  298. package/app/src/plugins/default-theme/templates/entry-blank.ts +13 -0
  299. package/app/src/plugins/default-theme/templates/entry.ts +27 -0
  300. package/app/src/plugins/default-theme/templates/home.ts +8 -0
  301. package/app/src/plugins/default-theme/templates/layout.ts +40 -0
  302. package/app/src/plugins/default-theme/templates/not-found.ts +10 -0
  303. package/app/src/plugins/default-theme/templates/search.ts +32 -0
  304. package/app/src/services/rbac.ts +65 -0
  305. package/app/src/services/roles.ts +89 -0
  306. package/app/src/services/users.ts +173 -0
  307. package/package.json +114 -2
  308. package/src/automations.ts +95 -0
  309. package/src/bindings.ts +138 -0
  310. package/src/block-references.ts +239 -0
  311. package/src/block-shape.ts +155 -0
  312. package/src/blocks.ts +1157 -0
  313. package/src/cache.ts +54 -0
  314. package/src/checks.ts +198 -0
  315. package/src/cloudflare-workers.d.ts +13 -0
  316. package/src/cloudflare.ts +61 -0
  317. package/src/collab.ts +372 -0
  318. package/src/collections.ts +421 -0
  319. package/src/comments.ts +46 -0
  320. package/src/cron.ts +95 -0
  321. package/src/dashboard-menu.ts +105 -0
  322. package/src/diff.ts +113 -0
  323. package/src/editor-layout.ts +316 -0
  324. package/src/errors.ts +50 -0
  325. package/src/field-groups.ts +498 -0
  326. package/src/fields.ts +411 -0
  327. package/src/form-builder.ts +1053 -0
  328. package/src/forms.ts +109 -0
  329. package/src/highlight.ts +134 -0
  330. package/src/hooks.ts +510 -0
  331. package/src/icon-catalog.ts +55 -0
  332. package/src/icons.ts +128 -0
  333. package/src/images.ts +149 -0
  334. package/src/index.ts +100 -0
  335. package/src/isolate-core.ts +245 -0
  336. package/src/isolate.ts +19 -0
  337. package/src/isolation.ts +69 -0
  338. package/src/mail.ts +182 -0
  339. package/src/manifest.ts +476 -0
  340. package/src/media.ts +193 -0
  341. package/src/menus.ts +287 -0
  342. package/src/module.ts +32 -0
  343. package/src/modules/content.ts +64 -0
  344. package/src/modules/forms.ts +35 -0
  345. package/src/node.ts +66 -0
  346. package/src/notes.ts +237 -0
  347. package/src/permissions.ts +139 -0
  348. package/src/plugin-settings.ts +114 -0
  349. package/src/records.ts +56 -0
  350. package/src/redirects.ts +59 -0
  351. package/src/resource.ts +245 -0
  352. package/src/richtext.ts +402 -0
  353. package/src/schema-json.ts +112 -0
  354. package/src/search.ts +89 -0
  355. package/src/seo.ts +477 -0
  356. package/src/server/accounts.ts +418 -0
  357. package/src/server/ai.ts +33 -0
  358. package/src/server/api-tokens.ts +91 -0
  359. package/src/server/areas.ts +116 -0
  360. package/src/server/audit.ts +94 -0
  361. package/src/server/auth.ts +89 -0
  362. package/src/server/automations.ts +190 -0
  363. package/src/server/autosaves.ts +69 -0
  364. package/src/server/brand-icons.ts +50 -0
  365. package/src/server/brands.ts +86 -0
  366. package/src/server/budget.ts +97 -0
  367. package/src/server/cache.ts +104 -0
  368. package/src/server/capabilities.ts +333 -0
  369. package/src/server/cloudflare.ts +92 -0
  370. package/src/server/comments.ts +237 -0
  371. package/src/server/drafts.ts +176 -0
  372. package/src/server/field-groups.ts +88 -0
  373. package/src/server/files.ts +780 -0
  374. package/src/server/forms.ts +726 -0
  375. package/src/server/handoffs.ts +107 -0
  376. package/src/server/host-schema.ts +312 -0
  377. package/src/server/host.ts +2892 -0
  378. package/src/server/images.ts +34 -0
  379. package/src/server/index.ts +59 -0
  380. package/src/server/indexnow.ts +91 -0
  381. package/src/server/isolation.ts +183 -0
  382. package/src/server/locked.ts +45 -0
  383. package/src/server/mail.ts +93 -0
  384. package/src/server/markdown.ts +24 -0
  385. package/src/server/menus.ts +286 -0
  386. package/src/server/network-policy.ts +60 -0
  387. package/src/server/network.ts +665 -0
  388. package/src/server/notes.ts +275 -0
  389. package/src/server/outbox.ts +213 -0
  390. package/src/server/path-moves.ts +33 -0
  391. package/src/server/payments.ts +59 -0
  392. package/src/server/previews.ts +62 -0
  393. package/src/server/purge.ts +140 -0
  394. package/src/server/reconcile.ts +38 -0
  395. package/src/server/redirects.ts +183 -0
  396. package/src/server/repository.ts +1107 -0
  397. package/src/server/schedules.ts +105 -0
  398. package/src/server/schema.ts +562 -0
  399. package/src/server/security.ts +391 -0
  400. package/src/server/seed.ts +52 -0
  401. package/src/server/shared-fields.ts +34 -0
  402. package/src/server/site-export.ts +151 -0
  403. package/src/server/site-import.ts +482 -0
  404. package/src/server/site-search.ts +289 -0
  405. package/src/server/site-settings.ts +286 -0
  406. package/src/server/sites.ts +243 -0
  407. package/src/server/stores.ts +314 -0
  408. package/src/server/stripe.ts +173 -0
  409. package/src/server/taxonomies.ts +415 -0
  410. package/src/server/tokens.ts +25 -0
  411. package/src/server/traffic.ts +118 -0
  412. package/src/server/users.ts +653 -0
  413. package/src/server/webhooks.ts +245 -0
  414. package/src/settings-controls.ts +54 -0
  415. package/src/settings-document.ts +111 -0
  416. package/src/settings.ts +426 -0
  417. package/src/storage/cloudflare.ts +94 -0
  418. package/src/storage/index.ts +30 -0
  419. package/src/storage/node.ts +114 -0
  420. package/src/taxonomy.ts +51 -0
  421. package/src/theme.ts +1135 -0
  422. package/src/to-markdown.ts +179 -0
  423. package/src/updates.ts +126 -0
  424. package/src/version.ts +2 -0
  425. package/src/vite.d.ts +25 -0
  426. package/src/vite.js +199 -0
  427. package/src/webhooks.ts +107 -0
@@ -0,0 +1,726 @@
1
+ /**
2
+ * Forms on the host. Each form's submissions resource is kept in step with the form: its own
3
+ * table, created and extended by the migrator when the form's inputs change. Submitting runs
4
+ * the form's rules, the validation filters and one atomic write of the submission, its
5
+ * receipt and its outbox event; notifications, webhooks and plugin actions run from the
6
+ * outbox. Handling submissions needs `cms:submissions`.
7
+ *
8
+ * Files of a file input are private files (`FileService.stashPrivate`), under
9
+ * `cms/private/forms/<form>/<submission>/`: stored once the submission is valid, made ready
10
+ * in the submission's own batch, read only through `file()` by whoever handles submissions,
11
+ * and deleted with the submission or the form. Records, hooks, emails, exports and webhooks
12
+ * carry their metadata (`FormFile`), never their bytes.
13
+ */
14
+ import { MAX_STATEMENTS, type Statement, type Value } from '@cossackframework/romedb';
15
+ import type { FilterPoint } from '@cossackframework/core/hooks';
16
+ import { CmsError, isCmsError } from '../errors';
17
+ import { fileType } from '../media';
18
+ import { SLUG_PATTERN } from '../fields';
19
+ import type { Block } from '../blocks';
20
+ import {
21
+ conditionShows, displayRows, displayValue, emailAddresses, escapeMarkdown, formFiles, formInputs, formSettings, notificationRules, renderMergeTags, submissionOf, submissionResource, submissionResourceName,
22
+ FORM_FILE_MAX_MB, FORM_UPLOAD_LIMIT_MB, SUBMISSION_STATUSES, validateSubmission, type FormFile, type FormSettings, type FormValues, type MergeContext, type NotificationRule, type SubmissionMeta, type SubmissionShape,
23
+ type SubmissionStatus, type SubmittedValues,
24
+ } from '../form-builder';
25
+ import {
26
+ formBeforeSubmit, formConfirmation, formNotification, formPrefill, formValidate, type FormConfirmation, type FormEmail, type FormErrors, type FormRef, type FormSubmittedEvent, type WriteActor,
27
+ } from '../hooks';
28
+ import { hasPermission, PERMISSIONS, principalId, systemPrincipal, type Principal } from '../permissions';
29
+ import type { RecordShape } from '../records';
30
+ import { declarationHash, resolveResource, storageName, type Resource } from '../resource';
31
+ import { migrate, nextGenerationStatement } from './schema';
32
+ import { sha256Hex } from './tokens';
33
+ import { bound, type ResourceRepository } from './repository';
34
+ import type { CmsHost } from './host';
35
+ import type { CmsFile } from './files';
36
+ import { uuidv7 } from '@cossackframework/core';
37
+ import { readBatches, requestBatches } from './budget';
38
+
39
+ /** Sends email, such as Cloudflare's `EMAIL` binding or an SMTP client. */
40
+ export interface CmsMail {
41
+ send(message: { readonly to: string; readonly from: string; readonly subject: string; readonly text: string; readonly replyTo?: string }): Promise<unknown>;
42
+ }
43
+
44
+ /** A form with what the host needs to take its submissions. */
45
+ export interface LoadedForm {
46
+ readonly record: RecordShape;
47
+ readonly ref: FormRef;
48
+ readonly blocks: readonly Block[];
49
+ readonly settings: FormSettings;
50
+ /** The rules that are on. */
51
+ readonly rules: readonly NotificationRule[];
52
+ readonly enabled: boolean;
53
+ /** Published forms are on the site and take submissions; drafts are only in the dashboard. */
54
+ readonly published: boolean;
55
+ readonly resource: Resource;
56
+ }
57
+
58
+ export interface SubmitContext {
59
+ readonly principal: Principal;
60
+ readonly ip?: string;
61
+ readonly userAgent?: string;
62
+ readonly referrer?: string;
63
+ /** The page the form was on. */
64
+ readonly page?: string;
65
+ readonly locale?: string;
66
+ /** The site's address, such as `https://example.com`, for links in notifications. */
67
+ readonly origin?: string;
68
+ /** The form's hidden trap field, which only bots fill in. */
69
+ readonly trap?: string;
70
+ /** When the page rendered the form, in Unix milliseconds of the server; quicker submissions are spam. */
71
+ readonly startedAt?: number;
72
+ /** Checks the bot challenge, when the form asks for one; resolves false to reject. */
73
+ readonly botCheck?: () => Promise<boolean>;
74
+ readonly signal?: AbortSignal;
75
+ }
76
+
77
+ export interface SubmitResult {
78
+ readonly form: LoadedForm;
79
+ readonly submission: SubmissionShape;
80
+ readonly confirmation: FormConfirmation;
81
+ }
82
+
83
+ export interface SubmissionList {
84
+ readonly items: readonly SubmissionShape[];
85
+ readonly next?: string;
86
+ }
87
+
88
+ const SYSTEM = systemPrincipal('forms');
89
+ const SLUG = new RegExp(`^${SLUG_PATTERN}$`);
90
+ const ID = /^[A-Za-z0-9_-]{1,80}$/;
91
+ /** One submission per address and form in this time. */
92
+ const THROTTLE_MS = 5_000;
93
+ /** How long a once-per-user or once-per-address send holds its key against sends at the same moment; stored sends are found by lookup after. */
94
+ const ONCE_CLAIM_MS = 60_000;
95
+ /** Filled in faster than people can: spam. */
96
+ const MIN_FILL_MS = 2_000;
97
+ const DAY = 24 * 60 * 60 * 1000;
98
+ const MB = 1024 * 1024;
99
+ const WRITE = { kind: 'cms.forms', retryConflicts: 5 } as const;
100
+ /** What a handled submission may be set to. */
101
+ const STATUSES = new Set<string>(SUBMISSION_STATUSES);
102
+
103
+ /** The actor of a form event, named as resource events name it (`system:<reason>` for the system). */
104
+ function writeActor(principal: Principal): WriteActor {
105
+ return { kind: principal.kind, id: principalId(principal) };
106
+ }
107
+
108
+ export class CmsForms {
109
+ readonly #host: CmsHost;
110
+ readonly #mail: CmsMail | undefined;
111
+ readonly #from: string;
112
+ /** Submission resources by ID, as last loaded. */
113
+ readonly #resources = new Map<string, Resource>();
114
+ /** The declaration hash each resource's table is known to have. */
115
+ readonly #synced = new Map<string, string>();
116
+ /** Forms loaded in this isolate, by ID, with the revision they were loaded at. */
117
+ readonly #loaded = new Map<string, { key: string; form: LoadedForm }>();
118
+ #warned = false;
119
+
120
+ constructor(host: CmsHost, options: { mail?: CmsMail; mailFrom?: string } = {}) {
121
+ this.#host = host;
122
+ this.#mail = options.mail;
123
+ this.#from = options.mailFrom ?? 'no-reply@example.com';
124
+ }
125
+
126
+ /** A submission resource this isolate has loaded, for `CmsHost.resourceById`. */
127
+ resourceById(id: string): Resource | undefined {
128
+ return this.#resources.get(id);
129
+ }
130
+
131
+ /** A form by slug or ID, with its submissions table in step. Null when there is none. */
132
+ async get(key: string, options: { signal?: AbortSignal } = {}): Promise<LoadedForm | null> {
133
+ const forms = this.#host.resource('cms/forms');
134
+ const context = { principal: SYSTEM, ...(options.signal ? { signal: options.signal } : {}) };
135
+ let record = SLUG.test(key) ? (await forms.list({ where: { slug: key }, limit: 1 }, context)).records[0] ?? null : null;
136
+ if (!record && ID.test(key)) record = await forms.get(key, context);
137
+ return record ? this.load(record) : null;
138
+ }
139
+
140
+ /** Forms by title, at most 200, with their submission tables in step. */
141
+ async all(): Promise<LoadedForm[]> {
142
+ const page = await this.#host.resource('cms/forms').list({ order: { field: 'title', direction: 'asc' }, limit: 100 }, { principal: SYSTEM });
143
+ const second = page.more ? await this.#host.resource('cms/forms').list({ order: { field: 'title', direction: 'asc' }, limit: 100, offset: 100 }, { principal: SYSTEM }) : { records: [] };
144
+ return Promise.all([...page.records, ...second.records].filter(record => record.status !== 'trash').map(record => this.load(record)));
145
+ }
146
+
147
+ /** A form from its record. Brings its submissions table up to date when the inputs changed. */
148
+ async load(record: RecordShape): Promise<LoadedForm> {
149
+ // A form at the same revision, with the same block types, has the same table.
150
+ const key = `${record.rev}:${record.updatedAt}:${this.#host.blockTypes.size}`;
151
+ const cached = this.#loaded.get(record.id);
152
+ if (cached?.key === key && this.#synced.has(cached.form.resource.id)) {
153
+ this.#resources.set(cached.form.resource.id, cached.form.resource);
154
+ return cached.form;
155
+ }
156
+ const form = await this.#build(record);
157
+ this.#loaded.set(record.id, { key, form });
158
+ return form;
159
+ }
160
+
161
+ async #build(record: RecordShape): Promise<LoadedForm> {
162
+ const blocks = Array.isArray(record.body) ? record.body as Block[] : [];
163
+ const inputs = formInputs(blocks, this.#host.blockTypes);
164
+ const settings = formSettings(record.settings);
165
+ const title = typeof record.title === 'string' ? record.title : '';
166
+ const resource = resolveResource(submissionResource({ id: record.id, title }, inputs, { indexed: settings.oncePerEmail ? [settings.oncePerEmail] : [] }), 'cms');
167
+ await this.#sync(resource);
168
+ return Object.freeze({
169
+ record, blocks, settings, resource, enabled: record.enabled !== false, published: record.status === 'published',
170
+ ref: Object.freeze({ id: record.id, slug: typeof record.slug === 'string' ? record.slug : record.id, title, inputs }),
171
+ rules: Object.freeze(notificationRules(record.notifications).filter(rule => rule.enabled !== false)),
172
+ });
173
+ }
174
+
175
+ async #sync(resource: Resource): Promise<void> {
176
+ this.#resources.set(resource.id, resource);
177
+ const hash = await declarationHash(resource);
178
+ if (this.#synced.get(resource.id) === hash) return;
179
+ // Sends arriving together share one migration in this isolate.
180
+ const key = `${resource.id}:${hash}`;
181
+ let syncing = this.#syncing.get(key);
182
+ if (!syncing) {
183
+ syncing = this.#migrate(resource, hash).finally(() => this.#syncing.delete(key));
184
+ this.#syncing.set(key, syncing);
185
+ }
186
+ await syncing;
187
+ }
188
+
189
+ readonly #syncing = new Map<string, Promise<void>>();
190
+
191
+ async #migrate(resource: Resource, hash: string): Promise<void> {
192
+ // Another isolate can migrate the same table at the same moment, and one of the two
193
+ // then fails: read the recorded hash again, and migrate once more only when it is still old.
194
+ for (let attempt = 0; ; attempt++) {
195
+ const state = await this.#host.db.read([{ rql: 'SELECT declaration_hash FROM cms_schema_state WHERE resource = $id', params: { $id: resource.id } }]);
196
+ if (state.results[0]!.rows[0]?.[0] === hash) break;
197
+ const report = await migrate(this.#host.db, [resource], { now: () => this.#host.now(), only: [resource.id] });
198
+ const blocked = report.blocked.filter(problem => problem.resource === resource.id);
199
+ if (!report.failed && !blocked.length) break;
200
+ if (attempt >= 2) throw new CmsError('CMS_UNAVAILABLE', `The form's submissions table could not be updated: ${report.failed?.message ?? blocked.map(problem => problem.message).join(' ')}`);
201
+ }
202
+ this.#synced.set(resource.id, hash);
203
+ // Activation caches the recorded hashes; read them again.
204
+ this.#host.refreshActivation();
205
+ }
206
+
207
+ /** Drop a deleted form's submissions table and their files. Runs from the outbox after the form is deleted. */
208
+ async dropTable(formId: string): Promise<void> {
209
+ // Named as the submissions resource was made, so a renamed rule cannot orphan the table.
210
+ const name = submissionResourceName(formId);
211
+ // The files first: a retry finds the rest, and none outlive the table.
212
+ await this.#host.files?.deletePrivate(filesScope(formId));
213
+ const id = `cms/${name}`;
214
+ const storage = storageName('cms', name);
215
+ const info = await this.#host.db.read([{ rql: 'INFO FOR DB' }]);
216
+ const exists = ((info.results[0]!.rows[0]![0] as { tables?: { name: string }[] }).tables ?? []).some(table => table.name === storage);
217
+ await this.#host.db.write([
218
+ ...(exists ? [{ rql: `DROP TABLE ${storage}` }] : []),
219
+ { rql: 'DELETE FROM cms_schema_state WHERE resource = $id', params: { $id: id } },
220
+ nextGenerationStatement(this.#host.now()),
221
+ ], { kind: 'cms.migration' });
222
+ this.#resources.delete(id);
223
+ this.#synced.delete(id);
224
+ this.#loaded.delete(formId);
225
+ this.#host.refreshActivation();
226
+ }
227
+
228
+ // --- Submitting ---------------------------------------------------------------------
229
+
230
+ /** Why the form takes no submissions now, or null when it is open. Counts kept submissions against the limit. */
231
+ async closed(form: LoadedForm): Promise<string | null> {
232
+ const { settings } = form;
233
+ const now = this.#host.now();
234
+ if (!form.enabled || (settings.opensAt !== null && now < settings.opensAt) || (settings.closesAt !== null && now >= settings.closesAt)) return settings.closedMessage;
235
+ if (settings.limit !== null && settings.store && await this.#kept(form) >= settings.limit) return settings.closedMessage;
236
+ return null;
237
+ }
238
+
239
+ /** Values the form starts with: input defaults, hidden inputs from the page's query, then `cms.form.prefill`. */
240
+ async prefill(form: LoadedForm, query: { readonly [name: string]: string }, principal: Principal): Promise<FormValues> {
241
+ const values: { [name: string]: FormValues[string] } = {};
242
+ for (const input of form.ref.inputs) {
243
+ const fallback = input.data.defaultValue;
244
+ if (input.type === 'form/hidden' && typeof query[input.name] === 'string') values[input.name] = query[input.name]!.slice(0, 500);
245
+ else if (fallback !== undefined && fallback !== null && fallback !== '') values[input.name] = fallback as FormValues[string];
246
+ }
247
+ try {
248
+ return await this.#host.hooks.applyFilters(formPrefill, Object.freeze(values), { form: form.ref, actor: writeActor(principal), query: Object.freeze({ ...query }) });
249
+ } catch { return Object.freeze(values); }
250
+ }
251
+
252
+ /**
253
+ * Take a submission: the form must be open, the sender allowed and not too quick, the
254
+ * values valid by the form and by `cms.form.validate`. Spam (the trap filled in, or sent
255
+ * faster than people can) is kept as spam when the form keeps submissions, runs no hooks
256
+ * and answers like a real submission, so bots learn nothing.
257
+ */
258
+ async submit(key: string, raw: SubmittedValues, context: SubmitContext): Promise<SubmitResult> {
259
+ const form = await this.get(key, context.signal ? { signal: context.signal } : {});
260
+ if (!form?.published) throw new CmsError('CMS_NOT_FOUND', 'This form does not exist.');
261
+ const { settings } = form;
262
+ const types = this.#host.blockTypes;
263
+ const closed = await this.closed(form);
264
+ if (closed !== null) throw new CmsError('CMS_FORBIDDEN', closed);
265
+ const user = context.principal.kind === 'user' ? context.principal.id : null;
266
+ if ((settings.requireSignIn || settings.oncePerUser) && !user) throw new CmsError('CMS_UNAUTHENTICATED', 'Sign in to send this form.');
267
+ if (settings.turnstile && context.botCheck && !(await context.botCheck())) throw new CmsError('CMS_FORBIDDEN', 'The check against bots failed. Try again.');
268
+ const now = this.#host.now();
269
+ const ipHash = context.ip ? await sha256Hex(`cms-form:${form.ref.id}:${context.ip}`) : null;
270
+ const spam = Boolean(context.trap) || (typeof context.startedAt === 'number' && Number.isFinite(context.startedAt) && now - context.startedAt < MIN_FILL_MS);
271
+ const actor = writeActor(context.principal);
272
+ const hookContext = { form: form.ref, actor, ...(context.ip ? { ip: context.ip } : {}), ...(context.userAgent ? { userAgent: context.userAgent } : {}), ...(context.page ? { page: context.page } : {}) };
273
+ const check = validateSubmission(form.blocks, types, raw);
274
+ // Posted files stay aside: hooks see their metadata, and they are stored once the submission is valid.
275
+ const uploads = new Map<string, readonly FormFile[]>();
276
+ for (const input of form.ref.inputs) if (input.kind === 'file' && check.values[input.name]) uploads.set(input.name, check.values[input.name] as readonly FormFile[]);
277
+ const withFiles = (from: FormValues): FormValues => {
278
+ if (!uploads.size && !form.ref.inputs.some(input => input.kind === 'file')) return from;
279
+ const next: { [name: string]: FormValues[string] } = { ...from };
280
+ for (const input of form.ref.inputs) if (input.kind === 'file') delete next[input.name];
281
+ for (const [name, files] of uploads) next[name] = Object.freeze(formFiles(files));
282
+ return Object.freeze(next);
283
+ };
284
+ let values = withFiles(check.values);
285
+ if (!spam) {
286
+ const errors = await this.#filter(formValidate, check.errors, { ...hookContext, values });
287
+ if (Object.keys(errors).length) throw new CmsError('CMS_VALIDATION', 'Check the fields marked below.', { fields: { ...errors } });
288
+ const changed = await this.#filter(formBeforeSubmit, values, hookContext);
289
+ if (changed !== values) {
290
+ const again = validateSubmission(form.blocks, types, changed);
291
+ const problem = Object.entries(again.errors)[0];
292
+ if (problem) throw new CmsError('CMS_VALIDATION', `A plugin set ${problem[0]} to a value the form does not take: ${problem[1]}`);
293
+ // Files are the posted ones: a plugin can check them but not replace them.
294
+ values = withFiles(again.values);
295
+ }
296
+ }
297
+ // One send per address in the window, counted in one conditional write once the send is checked, so a burst gets one through.
298
+ if (ipHash && !(await this.#host.security.attempt('form', ipHash, 1, THROTTLE_MS))) throw new CmsError('CMS_LIMIT', 'You sent this form a moment ago. Wait a few seconds and try again.');
299
+ // Once per user or address: sends at the same moment are held to one by a claim on the key
300
+ // (a minute, by which time the first is stored), and stored ones by looking them up. A send
301
+ // that goes no further gives its claims back, so a retry is not refused for nothing.
302
+ const claims: string[] = [];
303
+ const release = () => Promise.all(claims.map(key => this.#host.security.release('form-once', key).catch(() => undefined)));
304
+ const claim = async (key: string) => {
305
+ const scoped = `${form.ref.id}:${key}`;
306
+ if (!(await this.#host.security.attempt('form-once', scoped, 1, ONCE_CLAIM_MS))) return false;
307
+ claims.push(scoped);
308
+ return true;
309
+ };
310
+ try {
311
+ if (!spam && settings.store && settings.oncePerUser && user && (!(await claim(`u:${user}`)) || await this.#exists(form, '"_owner" = $value', user))) throw new CmsError('CMS_CONFLICT', 'You already sent this form.');
312
+ const email = !spam && settings.oncePerEmail ? values[settings.oncePerEmail] : undefined;
313
+ if (settings.store && typeof email === 'string' && (!(await claim(`e:${await sha256Hex(email.toLowerCase())}`)) || await this.#exists(form, `lower("${settings.oncePerEmail}") = $value`, email.toLowerCase()))) {
314
+ throw new CmsError('CMS_CONFLICT', 'This address already sent this form.', { fields: { [settings.oncePerEmail]: 'This address already sent this form.' } });
315
+ }
316
+ } catch (error) {
317
+ await release();
318
+ throw error;
319
+ }
320
+ const releasing = async <T>(work: () => Promise<T>): Promise<T> => {
321
+ try { return await work(); } catch (error) { await release(); throw error; }
322
+ };
323
+ const id = uuidv7();
324
+ const op = uuidv7();
325
+ // Files are stored before the record, pending; the record's batch makes them ready, and a refused write removes them.
326
+ let stashed: readonly string[] = [];
327
+ if (settings.store && uploads.size) ({ values, ids: stashed } = await releasing(() => this.#stash(form, id, uploads, values, user, context.signal)));
328
+ const meta: { -readonly [K in keyof SubmissionMeta]: string } = {};
329
+ if (settings.recordIp && context.ip) meta.ip = context.ip.slice(0, 64);
330
+ if (context.userAgent) meta.userAgent = context.userAgent.slice(0, 300);
331
+ if (context.referrer) meta.referrer = context.referrer.slice(0, 2048);
332
+ if (context.page) meta.page = context.page.slice(0, 2048);
333
+ if (context.locale) meta.locale = context.locale.slice(0, 16);
334
+ const status: SubmissionStatus = spam ? 'spam' : 'new';
335
+ const submission: SubmissionShape = Object.freeze({ id, form: form.ref.id, status, values, note: '', meta: Object.freeze(meta), user, createdAt: now, updatedAt: now });
336
+ const event: FormSubmittedEvent = { eventId: op, topic: 'form.submitted', form: form.ref, submission, actor, at: now, stored: settings.store, ...(context.origin ? { origin: context.origin } : {}) };
337
+ const sendParams = { $op: op, $form: form.ref.id, $ip: ipHash, $at: now };
338
+ const eventParams = { $op: op, $payload: JSON.stringify(event), $at: now };
339
+ if (settings.store) {
340
+ const limited = settings.limit !== null && !spam;
341
+ try {
342
+ await releasing(() => this.#host.resource(form.resource.id).insert({ ...values, status, ...(Object.keys(meta).length ? { meta } : {}) }, {
343
+ principal: SYSTEM, id, op, owner: user, kind: 'cms.forms.submit', ...(context.signal ? { signal: context.signal } : {}),
344
+ attach: written => {
345
+ // Under a limit, the receipt and event need the kept count, this one included, within it:
346
+ // writes to one database run one at a time, so sends at the same moment cannot pass it together.
347
+ const guard = limited ? { rql: `${written.rql} AND (SELECT count(*) FROM ${form.resource.storage} WHERE status IN ('new', 'read')) <= $limit`, params: { ...written.params, $limit: settings.limit! } } : written;
348
+ return [
349
+ bound(`INSERT INTO cms_form_sends (id, form_id, ip_hash, at) SELECT $op, $form, $ip, $at WHERE ${guard.rql}`, { ...guard.params, ...sendParams }),
350
+ ...(spam ? [] : [bound(`INSERT INTO cms_outbox (id, topic, payload, created_at, available_at, attempts, lease_until) SELECT $op, 'form.submitted', $payload, $at, $at, 0, 0 WHERE ${guard.rql}`, { ...guard.params, ...eventParams })]),
351
+ // The receipt is the guard: RomeQL's UPDATE takes a relational row, not the record's.
352
+ ...(stashed.length ? [this.#host.files!.privateReady(stashed, { rql: 'EXISTS (SELECT 1 FROM cms_form_sends WHERE id = $op)', params: { $op: op } })] : []),
353
+ // Past the limit, no receipt was written: the record goes in the same batch, so it is never kept.
354
+ ...(limited ? [{ rql: `DELETE FROM ${form.resource.storage} WHERE id = type::record('${form.resource.storage}', $id) AND NOT EXISTS (SELECT 1 FROM cms_form_sends WHERE id = $op)`, params: { $id: id, $op: op } }] : []),
355
+ ];
356
+ },
357
+ }));
358
+ // Past the limit: the batch removed the record; its files go below, and the send is refused as closed.
359
+ if (limited && !await this.#received(op)) throw new CmsError('CMS_FORBIDDEN', settings.closedMessage);
360
+ } catch (error) {
361
+ await release();
362
+ if (stashed.length) await this.#host.files?.discardPrivate(stashed).catch(() => undefined);
363
+ throw error;
364
+ }
365
+ } else {
366
+ const statements: Statement[] = [{ rql: 'INSERT INTO cms_form_sends (id, form_id, ip_hash, at) VALUES ($op, $form, $ip, $at)', params: sendParams }];
367
+ if (!spam) statements.push({ rql: "INSERT INTO cms_outbox (id, topic, payload, created_at, available_at, attempts, lease_until) VALUES ($op, 'form.submitted', $payload, $at, $at, 0, 0)", params: eventParams });
368
+ await releasing(() => this.#host.db.write(statements, { requestId: op, kind: 'cms.forms.submit', ...(context.signal ? { signal: context.signal } : {}) }));
369
+ this.#host.outboxWritten();
370
+ }
371
+ const merge = await this.#mergeContext(form.ref, submission, context.origin ?? '');
372
+ let confirmation: FormConfirmation = settings.confirmation === 'redirect' && settings.redirectUrl
373
+ ? { kind: 'redirect', url: settings.redirectUrl }
374
+ : { kind: 'message', message: renderMergeTags(settings.message, merge, { escape: escapeMarkdown }) };
375
+ if (!spam) {
376
+ try { confirmation = await this.#host.hooks.applyFilters(formConfirmation, confirmation, { form: form.ref, submission }); }
377
+ catch (error) { console.error('[cms] a cms.form.confirmation handler failed; the form\'s own confirmation is shown', error); }
378
+ }
379
+ return { form, submission, confirmation };
380
+ }
381
+
382
+ /**
383
+ * Store a submission's posted files as private files of it, each checked by its input's
384
+ * size and the content against its type, and answer the values with their references. A
385
+ * file that fails is the input's error; the files stored before it are removed.
386
+ */
387
+ async #stash(form: LoadedForm, submission: string, uploads: ReadonlyMap<string, readonly FormFile[]>, values: FormValues, owner: string | null, signal?: AbortSignal): Promise<{ values: FormValues; ids: string[] }> {
388
+ const files = this.#host.files;
389
+ const refuse = (name: string, message: string) => new CmsError('CMS_VALIDATION', 'Check the fields marked below.', { fields: { [name]: message } });
390
+ if (!files) throw refuse(uploads.keys().next().value!, 'This site cannot take files: it has no file storage.');
391
+ const total = [...uploads.values()].flat().reduce((sum, file) => sum + file.size, 0);
392
+ if (total > FORM_UPLOAD_LIMIT_MB * MB) throw new CmsError('CMS_LIMIT', `The files add up to more than ${FORM_UPLOAD_LIMIT_MB} MB.`);
393
+ const ids: string[] = [];
394
+ const stored: { [name: string]: readonly FormFile[] } = {};
395
+ try {
396
+ for (const [name, list] of uploads) {
397
+ const input = form.ref.inputs.find(entry => entry.name === name)!;
398
+ const largest = Math.min(typeof input.data.maxSize === 'number' ? input.data.maxSize : FORM_FILE_MAX_MB, FORM_FILE_MAX_MB) * MB;
399
+ const kept: FormFile[] = [];
400
+ for (const file of list) {
401
+ const label = file.name.slice(0, 80) || 'The file';
402
+ // A JSON post names files without sending them.
403
+ const blob = file as Partial<Blob>;
404
+ if (typeof blob.stream !== 'function') throw refuse(name, `Attach ${label} itself: send the form as multipart form data.`);
405
+ let saved: { id: string; name: string; contentType: string; size: number };
406
+ try {
407
+ saved = await files.stashPrivate({ name: file.name, contentType: fileType(file.name, file.type), size: file.size, body: blob.stream() as ReadableStream<Uint8Array> },
408
+ { principal: SYSTEM, scope: `${filesScope(form.ref.id)}/${submission}`, maxBytes: largest, ...(owner ? { owner } : {}), ...(signal ? { signal } : {}) });
409
+ } catch (error) {
410
+ if (isCmsError(error, 'CMS_VALIDATION') || isCmsError(error, 'CMS_LIMIT')) throw refuse(name, `${label}: ${error.message}`);
411
+ throw error;
412
+ }
413
+ ids.push(saved.id);
414
+ kept.push(Object.freeze({ id: saved.id, name: saved.name, size: saved.size, type: saved.contentType }));
415
+ }
416
+ stored[name] = Object.freeze(kept);
417
+ }
418
+ } catch (error) {
419
+ await files.discardPrivate(ids).catch(() => undefined);
420
+ throw error;
421
+ }
422
+ return { values: Object.freeze({ ...values, ...stored }), ids };
423
+ }
424
+
425
+ /** Run a filter, reporting a failing or slow handler as a validation error. */
426
+ async #filter<V, I>(point: FilterPoint<V, I>, value: V, input: I): Promise<V> {
427
+ const apply = this.#host.hooks.applyFilters.bind(this.#host.hooks) as unknown as (point: FilterPoint<V, I>, value: V, input: I) => Promise<V>;
428
+ try {
429
+ return await apply(point, value, input);
430
+ } catch (error) {
431
+ const cause = (error as { cause?: unknown }).cause;
432
+ throw new CmsError('CMS_VALIDATION', cause instanceof Error ? cause.message : 'A plugin rejected the submission.', { cause: error });
433
+ }
434
+ }
435
+
436
+ /** Whether a submission's receipt was written: its batch kept it within the form's limit. */
437
+ async #received(op: string): Promise<boolean> {
438
+ const result = await this.#host.db.read([{ rql: 'SELECT 1 FROM cms_form_sends WHERE id = $op', params: { $op: op } }]);
439
+ return result.results[0]!.rows.length > 0;
440
+ }
441
+
442
+ async #kept(form: LoadedForm): Promise<number> {
443
+ const result = await this.#host.db.read([{ rql: `SELECT count(*) FROM ${form.resource.storage} WHERE status IN ('new', 'read')` }]);
444
+ return Number(result.results[0]!.rows[0]![0] as bigint);
445
+ }
446
+
447
+ async #exists(form: LoadedForm, condition: string, value: Value): Promise<boolean> {
448
+ const result = await this.#host.db.read([{ rql: `SELECT 1 FROM ${form.resource.storage} WHERE ${condition} AND status != 'trash' LIMIT 1`, params: { $value: value } }]);
449
+ return result.results[0]!.rows.length > 0;
450
+ }
451
+
452
+ async #mergeContext(form: FormRef, submission: SubmissionShape, origin: string): Promise<MergeContext> {
453
+ const settings = await this.#host.settings.all();
454
+ const user = submission.user ? await this.#host.users.get(submission.user) : null;
455
+ return {
456
+ form: { id: form.id, title: form.title }, inputs: form.inputs, values: submission.values,
457
+ submission: { id: submission.id, url: `${origin}/dashboard/forms/${form.id}/submissions/${submission.id}`, date: new Date(submission.createdAt).toISOString() },
458
+ user: user ? { email: user.email, name: user.name } : null,
459
+ site: { title: String(settings['general.siteTitle'] ?? ''), url: origin, adminEmail: String(settings['general.adminEmail'] ?? '') },
460
+ };
461
+ }
462
+
463
+ // --- After a submission ---------------------------------------------------------------
464
+
465
+ /**
466
+ * Send the form's notification emails for a submission. Runs from the outbox; an email
467
+ * already sent for the event, rule and address is not sent again when delivery repeats.
468
+ */
469
+ async notify(event: FormSubmittedEvent): Promise<void> {
470
+ const form = await this.get(event.form.id).catch(() => null);
471
+ if (!form || !form.rules.length) return;
472
+ if (!this.#mail) {
473
+ if (!this.#warned) console.warn('[cms] form notifications are skipped: createCMS has no mail option.');
474
+ this.#warned = true;
475
+ return;
476
+ }
477
+ const context = await this.#mergeContext(event.form, event.submission, event.origin ?? '');
478
+ for (const rule of form.rules) {
479
+ if (!conditionShows(rule.when, event.submission.values)) continue;
480
+ const replyTo = rule.replyTo ? emailAddresses(renderMergeTags(rule.replyTo, context))[0] : undefined;
481
+ const drafted: FormEmail = {
482
+ to: emailAddresses(renderMergeTags(rule.to, context)),
483
+ subject: renderMergeTags(rule.subject, context).replace(/[\r\n]+/g, ' ').trim().slice(0, 300),
484
+ text: renderMergeTags(rule.body, context),
485
+ ...(replyTo ? { replyTo } : {}),
486
+ };
487
+ const email = await this.#host.hooks.applyFilters(formNotification, drafted, { form: event.form, submission: event.submission, rule });
488
+ if (!email) continue;
489
+ for (const to of emailAddresses(email.to.join(','))) {
490
+ const key = `${event.eventId}:${rule.id}:${to.toLowerCase()}`;
491
+ const sent = await this.#host.db.read([{ rql: 'SELECT 1 FROM cms_form_mail WHERE id = $id', params: { $id: key } }]);
492
+ if (sent.results[0]!.rows.length) continue;
493
+ const reply = email.replyTo ? emailAddresses(email.replyTo)[0] : undefined;
494
+ await this.#mail.send({ to, from: this.#from, subject: email.subject.replace(/[\r\n]+/g, ' ').slice(0, 300), text: email.text, ...(reply ? { replyTo: reply } : {}) });
495
+ await this.#host.db.write([{ rql: 'INSERT INTO cms_form_mail (id, sent_at) VALUES ($id, $now) ON CONFLICT (id) DO NOTHING', params: { $id: key, $now: this.#host.now() } }], WRITE);
496
+ }
497
+ }
498
+ }
499
+
500
+ // --- Handling submissions ---------------------------------------------------------------
501
+
502
+ #authorize(principal: Principal): void {
503
+ if (!hasPermission(principal, PERMISSIONS.manageSubmissions)) throw new CmsError(principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', 'Not allowed to handle form submissions.');
504
+ }
505
+
506
+ #repository(form: LoadedForm): ResourceRepository {
507
+ return this.#host.resource(form.resource.id);
508
+ }
509
+
510
+ /**
511
+ * Submissions newest first: those with a status, or new and read ones; or those whose text
512
+ * matches a search, best first. Pages through `next`.
513
+ */
514
+ async list(form: LoadedForm, options: { status?: SubmissionStatus; search?: string; after?: string; limit?: number }, principal: Principal): Promise<SubmissionList> {
515
+ this.#authorize(principal);
516
+ const where = { status: options.status && STATUSES.has(options.status) ? options.status : { in: ['new', 'read'] } };
517
+ const context = { principal };
518
+ if (options.search?.trim()) {
519
+ if (!Object.values(form.resource.fields).some(field => field.search)) return { items: [] };
520
+ const found = await this.#repository(form).search(options.search.trim(), { where, limit: Math.min(options.limit ?? 50, 100) }, context);
521
+ return { items: found.map(record => submissionOf(form.ref.id, record, form.ref.inputs)) };
522
+ }
523
+ const page = await this.#repository(form).list({ where, order: { field: 'createdAt', direction: 'desc' }, limit: Math.min(Math.max(options.limit ?? 50, 1), 100), ...(options.after ? { after: options.after } : {}) }, context);
524
+ return { items: page.records.map(record => submissionOf(form.ref.id, record, form.ref.inputs)), ...(page.next ? { next: page.next } : {}) };
525
+ }
526
+
527
+ /** How many submissions have each status. */
528
+ async counts(form: LoadedForm, principal: Principal): Promise<{ [K in SubmissionStatus]: number }> {
529
+ this.#authorize(principal);
530
+ const counts = await this.#repository(form).countMany(SUBMISSION_STATUSES.map(status => ({ where: { status } })), { principal });
531
+ return Object.fromEntries(SUBMISSION_STATUSES.map((status, index) => [status, counts[index]!])) as { [K in SubmissionStatus]: number };
532
+ }
533
+
534
+ /**
535
+ * New and kept (new and read) submissions of each form, for the navigation and the forms
536
+ * list. Forms whose table cannot be read count 0.
537
+ */
538
+ async inboxCounts(forms: readonly LoadedForm[], principal: Principal): Promise<Map<string, { fresh: number; kept: number }>> {
539
+ if (!hasPermission(principal, PERMISSIONS.manageSubmissions) || !forms.length) return new Map();
540
+ const counts = new Map<string, { fresh: number; kept: number }>();
541
+ // Two counts a form.
542
+ for (const chunk of readBatches(forms, MAX_STATEMENTS / 2)) {
543
+ try {
544
+ const result = await this.#host.db.read(chunk.flatMap(form => [
545
+ { rql: `SELECT count(*) FROM ${form.resource.storage} WHERE status = 'new'` },
546
+ { rql: `SELECT count(*) FROM ${form.resource.storage} WHERE status IN ('new', 'read')` },
547
+ ]));
548
+ chunk.forEach((form, index) => counts.set(form.ref.id, { fresh: Number(result.results[index * 2]!.rows[0]![0] as bigint), kept: Number(result.results[index * 2 + 1]!.rows[0]![0] as bigint) }));
549
+ } catch { for (const form of chunk) counts.set(form.ref.id, { fresh: 0, kept: 0 }); }
550
+ }
551
+ return counts;
552
+ }
553
+
554
+ async submission(form: LoadedForm, id: string, principal: Principal): Promise<SubmissionShape | null> {
555
+ this.#authorize(principal);
556
+ const record = await this.#repository(form).get(id, { principal });
557
+ return record ? submissionOf(form.ref.id, record, form.ref.inputs) : null;
558
+ }
559
+
560
+ /**
561
+ * A file of a submission with its bytes, for whoever handles submissions; null when the
562
+ * submission or the file is gone. Files are private: nothing else serves them.
563
+ */
564
+ async file(form: LoadedForm, submission: string, fileId: string, principal: Principal, options: { signal?: AbortSignal } = {}): Promise<{ file: CmsFile; body: ReadableStream<Uint8Array> } | null> {
565
+ this.#authorize(principal);
566
+ if (!this.#host.files || !ID.test(submission)) return null;
567
+ if (!(await this.#repository(form).get(submission, { principal }))) return null;
568
+ return this.#host.files.openPrivate(`${filesScope(form.ref.id)}/${submission}`, fileId, options);
569
+ }
570
+
571
+ /** Mark submissions read, unread (`new`), spam or trash. Returns how many changed. */
572
+ async setStatus(form: LoadedForm, ids: readonly string[], status: SubmissionStatus, principal: Principal): Promise<number> {
573
+ this.#authorize(principal);
574
+ if (!STATUSES.has(status)) throw new CmsError('CMS_VALIDATION', 'Unknown submission status.');
575
+ await this.#host.assertActive(form.resource, { fresh: true });
576
+ const storage = form.resource.storage;
577
+ const now = this.#host.now();
578
+ return this.#each(ids, (key, index) => bound(
579
+ `UPDATE ${storage} SET status = $status, "_updatedAt" = $now, "_rev" = "_rev" + 1 WHERE id = type::record('${storage}', $k${index}) AND status != $status`,
580
+ { $status: status, $now: now, [`$k${index}`]: key },
581
+ ));
582
+ }
583
+
584
+ /** Delete submissions for good, with their files. Returns how many were deleted. */
585
+ async delete(form: LoadedForm, ids: readonly string[], principal: Principal): Promise<number> {
586
+ this.#authorize(principal);
587
+ await this.#host.assertActive(form.resource, { fresh: true });
588
+ const storage = form.resource.storage;
589
+ // The files first, so none outlive their submission; a retry finds the rest.
590
+ if (this.#host.files) for (const key of submissionKeys(ids)) await this.#host.files.deletePrivate(`${filesScope(form.ref.id)}/${key}`);
591
+ return this.#each(ids, (key, index) => ({ rql: `DELETE FROM ${storage} WHERE id = type::record('${storage}', $k${index})`, params: { [`$k${index}`]: key } }));
592
+ }
593
+
594
+ async #each(ids: readonly string[], statement: (key: string, index: number) => Statement): Promise<number> {
595
+ const keys = submissionKeys(ids);
596
+ let changed = 0;
597
+ for (const batch of await requestBatches(this.#host.db, keys.map((key, index) => statement(key, index)))) {
598
+ const result = await this.#host.db.write(batch, WRITE);
599
+ changed += result.results.reduce((sum, entry) => sum + Number(entry.affected), 0);
600
+ }
601
+ return changed;
602
+ }
603
+
604
+ /** Save a note on a submission, for whoever handles it. */
605
+ async setNote(form: LoadedForm, id: string, note: string, principal: Principal): Promise<SubmissionShape> {
606
+ this.#authorize(principal);
607
+ const repository = this.#repository(form);
608
+ const record = await repository.get(id, { principal });
609
+ if (!record) throw new CmsError('CMS_NOT_FOUND', 'The submission is gone.');
610
+ const updated = await repository.update(id, { note: note.trim() ? note.trim() : null }, { principal, expectedRevision: record.rev });
611
+ return submissionOf(form.ref.id, updated, form.ref.inputs);
612
+ }
613
+
614
+ /**
615
+ * Replace a submission's answers, for whoever handles it: the values are checked as a post
616
+ * is, by the form's inputs and conditions; the form's limits, bot checks and a plugin's
617
+ * validation do not apply. Inputs the values leave out are cleared.
618
+ */
619
+ async setValues(form: LoadedForm, id: string, raw: SubmittedValues, principal: Principal): Promise<SubmissionShape> {
620
+ this.#authorize(principal);
621
+ const repository = this.#repository(form);
622
+ const record = await repository.get(id, { principal });
623
+ if (!record) throw new CmsError('CMS_NOT_FOUND', 'The submission is gone.');
624
+ // Files are not edited here: they stay as sent, and are checked as kept, whatever the values say.
625
+ const files = form.ref.inputs.filter(field => field.kind === 'file').map(field => field.name);
626
+ const kept = submissionOf(form.ref.id, record, form.ref.inputs).values;
627
+ const check = validateSubmission(form.blocks, this.#host.blockTypes, { ...raw, ...Object.fromEntries(files.map(name => [name, kept[name] ?? []])) });
628
+ const errors = Object.fromEntries(Object.entries(check.errors).filter(([key]) => !files.includes(key)));
629
+ if (Object.keys(errors).length) throw new CmsError('CMS_VALIDATION', 'Check the fields marked below.', { fields: errors });
630
+ const input: { [name: string]: unknown } = {};
631
+ for (const field of form.ref.inputs) if (field.kind !== 'file') input[field.name] = check.values[field.name] ?? null;
632
+ const updated = await repository.update(id, input, { principal, expectedRevision: record.rev });
633
+ return submissionOf(form.ref.id, updated, form.ref.inputs);
634
+ }
635
+
636
+ /**
637
+ * Submissions as CSV, newest first, in pages: the time, the status, one column per input
638
+ * with its label, then the details. Cells that spreadsheets would run as formulas are quoted.
639
+ */
640
+ async *csv(form: LoadedForm, options: { status?: SubmissionStatus }, principal: Principal): AsyncGenerator<string> {
641
+ this.#authorize(principal);
642
+ const inputs = form.ref.inputs;
643
+ yield csvRow(['Submitted at', 'Status', ...inputs.map(input => input.label), 'IP address', 'Page', 'Browser', 'User', 'Note', 'ID']);
644
+ let after: string | undefined;
645
+ do {
646
+ const page = await this.list(form, { ...(options.status ? { status: options.status } : {}), limit: 100, ...(after ? { after } : {}) }, principal);
647
+ let rows = '';
648
+ for (const item of page.items) {
649
+ rows += csvRow([
650
+ new Date(item.createdAt).toISOString(), item.status,
651
+ // A repeater is one cell: its rows as lines.
652
+ ...inputs.map(input => input.kind === 'rows' ? displayRows(input, item.values[input.name]).join('\n') : displayValue(input, item.values[input.name])),
653
+ item.meta.ip ?? '', item.meta.page ?? '', item.meta.userAgent ?? '', item.user ?? '', item.note, item.id,
654
+ ]);
655
+ }
656
+ if (rows) yield rows;
657
+ after = page.next;
658
+ } while (after);
659
+ }
660
+
661
+ // --- Maintenance ----------------------------------------------------------------------
662
+
663
+ /**
664
+ * Forget sends after a day and sent-email records after 30 days, drop expired post
665
+ * results, and empty each form's trash of submissions trashed over 30 days ago.
666
+ */
667
+ async maintain(): Promise<{ emptied: number }> {
668
+ const now = this.#host.now();
669
+ const old = await this.#host.db.read([
670
+ { rql: 'SELECT 1 FROM cms_form_sends WHERE at < $before LIMIT 1', params: { $before: now - DAY } },
671
+ { rql: 'SELECT 1 FROM cms_form_mail WHERE sent_at < $before LIMIT 1', params: { $before: now - 30 * DAY } },
672
+ { rql: 'SELECT 1 FROM cms_form_results WHERE expires_at < $now LIMIT 1', params: { $now: now } },
673
+ ]);
674
+ const statements: Statement[] = [];
675
+ if (old.results[0]!.rows.length) statements.push({ rql: 'DELETE FROM cms_form_sends WHERE at < $before', params: { $before: now - DAY } });
676
+ if (old.results[1]!.rows.length) statements.push({ rql: 'DELETE FROM cms_form_mail WHERE sent_at < $before', params: { $before: now - 30 * DAY } });
677
+ if (old.results[2]!.rows.length) statements.push({ rql: 'DELETE FROM cms_form_results WHERE expires_at < $now', params: { $now: now } });
678
+ if (statements.length) await this.#host.db.write(statements, WRITE);
679
+ let emptied = 0;
680
+ for (const form of await this.all()) {
681
+ const trashed = await this.#host.db.read([{ rql: `SELECT record::id(id) FROM ${form.resource.storage} WHERE status = 'trash' AND "_updatedAt" < $before LIMIT 500`, params: { $before: now - 30 * DAY } }]);
682
+ const ids = trashed.results[0]!.rows.map(row => row[0] as string);
683
+ if (ids.length) emptied += await this.delete(form, ids, SYSTEM);
684
+ }
685
+ return { emptied };
686
+ }
687
+
688
+ // --- Results of form posts ------------------------------------------------------------
689
+
690
+ /** Keep what a form post returns to its page after the redirect, for ten minutes. Returns its key. */
691
+ async saveResult(formId: string, data: unknown): Promise<string> {
692
+ const id = uuidv7();
693
+ await this.#host.db.write([{ rql: 'INSERT INTO cms_form_results (id, form_id, data, expires_at) VALUES ($id, $form, $data, $expires)', params: { $id: id, $form: formId, $data: JSON.stringify(data), $expires: this.#host.now() + 10 * 60_000 } }], WRITE);
694
+ return id;
695
+ }
696
+
697
+ /** The result kept under a key for a form, once: reading it deletes it. */
698
+ async takeResult(formId: string, id: string): Promise<unknown> {
699
+ if (!/^[0-9a-f-]{36}$/.test(id)) return null;
700
+ const result = await this.#host.db.read([{ rql: 'SELECT data FROM cms_form_results WHERE id = $id AND form_id = $form AND expires_at >= $now', params: { $id: id, $form: formId, $now: this.#host.now() } }]);
701
+ const data = result.results[0]!.rows[0]?.[0];
702
+ if (typeof data !== 'string') return null;
703
+ await this.#host.db.write([{ rql: 'DELETE FROM cms_form_results WHERE id = $id', params: { $id: id } }], WRITE);
704
+ try { return JSON.parse(data); } catch { return null; }
705
+ }
706
+ }
707
+
708
+ /** The scope of a form's private files; a submission's are under `<scope>/<submission>`. */
709
+ function filesScope(formId: string): string {
710
+ return `forms/${formId}`;
711
+ }
712
+
713
+ /** Distinct submission IDs, at most 100 at a time. */
714
+ function submissionKeys(ids: readonly string[]): string[] {
715
+ return [...new Set(ids.filter(id => typeof id === 'string' && ID.test(id)))].slice(0, 100);
716
+ }
717
+
718
+ /** One CSV line. Cells starting like a formula get a leading apostrophe. */
719
+ function csvRow(cells: readonly string[]): string {
720
+ return `${cells.map(cell => {
721
+ const text = /^[=+\-@\t\r]/.test(cell) ? `'${cell}` : cell;
722
+ return /[",\n\r]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
723
+ }).join(',')}\r\n`;
724
+ }
725
+
726
+ export type { FormErrors };