@cossackframework/cms 0.0.0 → 0.9.2

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 +21 -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 +709 -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 +114 -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 +62 -0
  110. package/app/src/dashboard/avatar-field.ts +58 -0
  111. package/app/src/dashboard/bulk.ts +22 -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 +28 -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 +18 -0
  121. package/app/src/dashboard/session-list.ts +98 -0
  122. package/app/src/dashboard/tabs.ts +2 -0
  123. package/app/src/dashboard/time-ago.ts +16 -0
  124. package/app/src/dashboard/types.ts +43 -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 +82 -0
  212. package/app/src/pages/auth/layout.ts +32 -0
  213. package/app/src/pages/auth/login/index.ts +205 -0
  214. package/app/src/pages/auth/magic/index.ts +68 -0
  215. package/app/src/pages/auth/register/index.ts +124 -0
  216. package/app/src/pages/auth/reset-password/index.ts +74 -0
  217. package/app/src/pages/auth/setup/index.ts +194 -0
  218. package/app/src/pages/auth/two-factor/index.ts +69 -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 +183 -0
  278. package/app/src/pages/dashboard/index.ts +214 -0
  279. package/app/src/pages/dashboard/layout.ts +227 -0
  280. package/app/src/pages/dashboard/profile/index.ts +211 -0
  281. package/app/src/pages/dashboard/profile/security/index.ts +249 -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,1053 @@
1
+ /**
2
+ * Forms built from blocks. A form is an entry of the built-in `forms` collection whose `body`
3
+ * holds input blocks laid out with the core containers. Its submissions are records of a
4
+ * resource of their own, typed from its inputs and stored in a table of their own. Pure
5
+ * functions: the site's script and the host validate a submission with the same code.
6
+ */
7
+ import { field, type FieldDeclaration } from './fields';
8
+ import { INPUT_NAME, flattenBlocks, type Block, type BlockCondition, type BlockDeclaration, type ConditionRule, type InputKind } from './blocks';
9
+ import { boxBlock, EDIT_TAB } from './editor-layout';
10
+ import { blockConditionProblem } from './block-shape';
11
+ import type { CollectionDefinition } from './collections';
12
+ import type { RecordShape } from './records';
13
+ import type { ResourceDeclaration } from './resource';
14
+ import { PERMISSIONS } from './permissions';
15
+ import { fileExtension, fileType, formatBytes } from './media';
16
+
17
+ // --- Input blocks -----------------------------------------------------------------------
18
+
19
+ const NAME = field.string({ max: 40, pattern: INPUT_NAME.source.slice(1, -1), label: 'Field name', description: 'Submissions and exports keep the value under this name. Taken from the label when empty.' });
20
+ const LABEL = field.string({ required: true, max: 200, label: 'Label' });
21
+ const HELP = field.string({ max: 500, label: 'Help text' });
22
+ const REQUIRED = field.boolean({ default: false, label: 'Required' });
23
+ const PLACEHOLDER = field.string({ max: 200, label: 'Placeholder' });
24
+ const OPTIONS = field.list('string', { label: 'Choices', description: 'One per line. Write value|Label to store a value other than the label.' });
25
+ const INLINE = field.boolean({ default: false, label: 'Show choices in a row' });
26
+ /** How much of the form's row an input takes: a half or a third shares its row with the inputs beside it, where the form is wide enough. */
27
+ export const FORM_INPUT_WIDTHS = Object.freeze(['full', 'half', 'third'] as const);
28
+ const WIDTH = field.enum([...FORM_INPUT_WIDTHS], { default: 'full', label: 'Width', choices: { full: 'Full width', half: 'Half', third: 'A third' } });
29
+ const DATE = '\\d{4}-\\d{2}-\\d{2}';
30
+ /** Items a multiple input takes at most, whatever its settings. */
31
+ export const FORM_ITEM_LIMIT = 50;
32
+ /** The input kinds that take `multiple`: one control per value, added one at a time. */
33
+ export const MULTIPLE_INPUT_KINDS: readonly InputKind[] = Object.freeze(['string', 'text', 'email', 'url', 'phone', 'number', 'date']);
34
+ /** The settings of an input that can take several values; the same four a field block has. */
35
+ const MULTIPLE_SETTINGS: { readonly [name: string]: FieldDeclaration } = {
36
+ multiple: field.boolean({ default: false, label: 'Multiple', description: 'Several values, added one at a time.' }),
37
+ minItems: field.integer({ min: 0, max: FORM_ITEM_LIMIT, label: 'Fewest values' }),
38
+ maxItems: field.integer({ min: 1, max: FORM_ITEM_LIMIT, label: 'Most values' }),
39
+ addLabel: field.string({ max: 80, default: 'Add another', label: 'Add button' }),
40
+ };
41
+
42
+ /** The largest file a file input takes, in MB, whatever its settings. */
43
+ export const FORM_FILE_MAX_MB = 10;
44
+ /** Files one file input takes at most, whatever its settings. */
45
+ export const FORM_FILE_LIMIT = 10;
46
+ /** The files of one submission add up to at most this many MB: a post is read whole. */
47
+ export const FORM_UPLOAD_LIMIT_MB = 25;
48
+ const MB = 1024 * 1024;
49
+ /** One allowed type of a file input: an extension such as `.pdf`, a type such as `application/pdf`, or a family such as `image/*`. */
50
+ const ACCEPT_TOKEN = '(?:\\.[A-Za-z0-9]{1,16}|[a-z]+/(?:\\*|[a-z0-9][a-z0-9.+\\-]*))';
51
+
52
+ /** The fields every input block has, then its own. Plugins build their input blocks with it. */
53
+ export function inputFields(own: { readonly [name: string]: FieldDeclaration } = {}): { [name: string]: FieldDeclaration } {
54
+ return { label: LABEL, name: NAME, description: HELP, required: REQUIRED, width: WIDTH, ...own };
55
+ }
56
+
57
+ const textInput = (name: string, label: string, icon: string, kind: InputKind, description: string, keywords: readonly string[]): BlockDeclaration => ({
58
+ name, label, icon, category: 'form', description, input: { kind }, keywords,
59
+ fields: inputFields({ placeholder: PLACEHOLDER, defaultValue: field.string({ max: 500, label: 'Default value' }), ...MULTIPLE_SETTINGS }),
60
+ });
61
+
62
+ /** Built-in input blocks. A submit button is not a block: the form's settings label it. */
63
+ export const FORM_BLOCKS: readonly BlockDeclaration[] = Object.freeze([
64
+ { name: 'form/text', keywords: ['single line', 'input', 'string', 'name'], label: 'Text', icon: 'text-field', category: 'form', description: 'One line of text.', input: { kind: 'string' }, fields: inputFields({
65
+ placeholder: PLACEHOLDER,
66
+ defaultValue: field.string({ max: 500, label: 'Default value' }),
67
+ minLength: field.integer({ min: 0, max: 10_000, label: 'Minimum length' }),
68
+ maxLength: field.integer({ default: 255, min: 1, max: 10_000, label: 'Maximum length' }),
69
+ pattern: field.string({ max: 200, label: 'Pattern', description: 'A regular expression the whole value must match.' }),
70
+ ...MULTIPLE_SETTINGS,
71
+ }) },
72
+ textInput('form/email', 'Email', 'letter', 'email', 'An email address.', ['mail', 'address', 'contact']),
73
+ textInput('form/url', 'Website', 'link', 'url', 'A web address.', ['url', 'link', 'homepage']),
74
+ textInput('form/phone', 'Phone', 'phone', 'phone', 'A phone number.', ['tel', 'telephone', 'mobile', 'number']),
75
+ { name: 'form/textarea', keywords: ['multi line', 'textarea', 'message', 'long text'], label: 'Paragraph text', icon: 'text-square', category: 'form', description: 'Several lines of text.', input: { kind: 'text' }, fields: inputFields({
76
+ placeholder: PLACEHOLDER,
77
+ defaultValue: field.text({ max: 5000, label: 'Default value' }),
78
+ rows: field.integer({ default: 5, min: 2, max: 20, label: 'Rows' }),
79
+ minLength: field.integer({ min: 0, max: 50_000, label: 'Minimum length' }),
80
+ maxLength: field.integer({ default: 5000, min: 1, max: 50_000, label: 'Maximum length' }),
81
+ ...MULTIPLE_SETTINGS,
82
+ }) },
83
+ { name: 'form/number', keywords: ['numeric', 'quantity', 'amount'], label: 'Number', icon: 'calculator', category: 'form', description: 'A number, within limits.', input: { kind: 'number' }, fields: inputFields({
84
+ placeholder: PLACEHOLDER,
85
+ defaultValue: field.number({ nullable: true, label: 'Default value' }),
86
+ min: field.number({ nullable: true, label: 'Minimum' }),
87
+ max: field.number({ nullable: true, label: 'Maximum' }),
88
+ step: field.number({ nullable: true, min: 0, label: 'Step', description: 'Values go up in steps of this size from the minimum. Empty for any value; 1 for whole numbers.' }),
89
+ ...MULTIPLE_SETTINGS,
90
+ }) },
91
+ { name: 'form/date', keywords: ['calendar', 'day'], label: 'Date', icon: 'calendar', category: 'form', description: 'A day of the calendar.', input: { kind: 'date' }, fields: inputFields({
92
+ defaultValue: field.string({ max: 10, pattern: DATE, label: 'Default value' }),
93
+ min: field.string({ max: 10, pattern: DATE, label: 'Earliest' }),
94
+ max: field.string({ max: 10, pattern: DATE, label: 'Latest' }),
95
+ ...MULTIPLE_SETTINGS,
96
+ }) },
97
+ { name: 'form/select', keywords: ['select', 'list', 'choice', 'option'], label: 'Dropdown', icon: 'list-down', category: 'form', description: 'One choice from a list.', input: { kind: 'choice' }, fields: inputFields({
98
+ options: OPTIONS,
99
+ placeholder: field.string({ max: 200, default: 'Choose…', label: 'Prompt' }),
100
+ defaultValue: field.string({ max: 200, label: 'Default value' }),
101
+ }) },
102
+ { name: 'form/radio', keywords: ['radio', 'choice', 'option', 'single'], label: 'Multiple choice', icon: 'record-circle', category: 'form', description: 'One choice, all shown.', input: { kind: 'choice' }, fields: inputFields({
103
+ options: OPTIONS, inline: INLINE,
104
+ defaultValue: field.string({ max: 200, label: 'Default value' }),
105
+ }) },
106
+ { name: 'form/checkboxes', keywords: ['multiple', 'choices', 'options', 'tick'], label: 'Checkboxes', icon: 'checklist', category: 'form', description: 'Any number of choices.', input: { kind: 'choices' }, fields: inputFields({
107
+ options: OPTIONS, inline: INLINE,
108
+ }) },
109
+ { name: 'form/checkbox', keywords: ['tick', 'boolean', 'yes no', 'toggle'], label: 'Checkbox', icon: 'check-square', category: 'form', description: 'A yes or no.', input: { kind: 'boolean' }, fields: inputFields({
110
+ text: field.string({ max: 500, label: 'Checkbox text', description: 'Shown beside the box; the label when empty.' }),
111
+ defaultValue: field.boolean({ default: false, label: 'Checked at first' }),
112
+ }) },
113
+ { name: 'form/consent', keywords: ['agree', 'terms', 'gdpr', 'privacy'], label: 'Consent', icon: 'shield-check', category: 'form', description: 'A box people must tick to agree.', input: { kind: 'boolean' }, fields: {
114
+ ...inputFields(),
115
+ required: field.boolean({ default: true, label: 'Required' }),
116
+ text: field.text({ required: true, max: 2000, format: 'markdown', label: 'Agreement', description: 'Shown beside the box. Links are allowed.' }),
117
+ } },
118
+ { name: 'form/hidden', keywords: ['utm', 'tracking', 'source', 'secret'], label: 'Hidden', icon: 'eye-closed', category: 'form', description: 'A value visitors do not see, from the default or the page address.', input: { kind: 'string' }, fields: inputFields({
119
+ defaultValue: field.string({ max: 500, label: 'Value' }),
120
+ }) },
121
+ { name: 'form/file', keywords: ['upload', 'attachment', 'document', 'resume', 'cv', 'photo'], label: 'File upload', icon: 'upload-minimalistic', category: 'form', description: 'Files people attach, kept privately with the submission.', input: { kind: 'file' }, fields: inputFields({
122
+ accept: field.string({ required: true, max: 300, default: '.pdf, .jpg, .jpeg, .png', pattern: `\\s*${ACCEPT_TOKEN}(?:\\s*,\\s*${ACCEPT_TOKEN})*\\s*`, label: 'Allowed types', description: 'Extensions or types, separated by commas, such as .pdf, .docx, image/*. Each file\'s content is checked against its type.' }),
123
+ maxSize: field.integer({ default: 5, min: 1, max: FORM_FILE_MAX_MB, label: 'Largest file (MB)' }),
124
+ multipleFiles: field.boolean({ default: false, label: 'Several files' }),
125
+ maxFiles: field.integer({ default: 3, min: 1, max: FORM_FILE_LIMIT, label: 'Most files', description: 'When several files are allowed.' }),
126
+ }) },
127
+ { name: 'form/repeater', keywords: ['rows', 'repeat', 'list', 'passengers', 'attendees', 'items', 'group'], label: 'Repeater', icon: 'layers-minimalistic', category: 'form', description: 'A set of fields people fill in once per row: passengers, attendees, items.', input: { kind: 'rows' }, children: {}, fields: inputFields({
128
+ rowLabel: field.string({ max: 60, label: 'Row name', description: 'What one row is, such as Passenger: rows are numbered with it.' }),
129
+ addLabel: field.string({ max: 80, default: 'Add another', label: 'Add button' }),
130
+ min: field.integer({ min: 0, max: 50, label: 'Fewest rows' }),
131
+ max: field.integer({ min: 1, max: 50, label: 'Most rows' }),
132
+ }) },
133
+ ] satisfies BlockDeclaration[]);
134
+
135
+ /** Rows a repeater takes at most, whatever its settings. */
136
+ export const FORM_ROW_LIMIT = 50;
137
+ /** The row id of a repeater's template row on a page, replaced by the page's script when a row is added. */
138
+ export const TEMPLATE_ROW = '__row__';
139
+
140
+ /** The type that places a form in content: `form` is the form's slug. */
141
+ export const FORM_EMBED_BLOCK: BlockDeclaration = Object.freeze({
142
+ name: 'core/form', label: 'Form', icon: 'checklist-minimalistic', category: 'widgets', description: 'One of the site\'s forms.',
143
+ fields: { form: field.string({ required: true, max: 200, pattern: '[a-z0-9]+(?:-[a-z0-9]+)*', choicesFrom: 'forms', label: 'Form', description: 'The form to show.' }) },
144
+ });
145
+
146
+ // --- Inputs of a form ---------------------------------------------------------------------
147
+
148
+ export interface ChoiceOption {
149
+ readonly value: string;
150
+ readonly label: string;
151
+ }
152
+
153
+ /** A form input, read from its block. */
154
+ export interface FormField {
155
+ /** The input block's `_id`. */
156
+ readonly _id: string;
157
+ readonly type: string;
158
+ readonly name: string;
159
+ readonly label: string;
160
+ readonly kind: InputKind;
161
+ readonly required: boolean;
162
+ /** Several values of the kind, each its own control; `minItems`, `maxItems` and `addLabel` in `data`. */
163
+ readonly multiple: boolean;
164
+ /** For choice kinds. */
165
+ readonly options: readonly ChoiceOption[];
166
+ readonly data: { readonly [field: string]: unknown };
167
+ /** A repeater's inputs, those of each of its rows; empty for other kinds. */
168
+ readonly inputs: readonly FormField[];
169
+ /** The name of the repeater this input belongs to; null at the form's top level. */
170
+ readonly parent: string | null;
171
+ }
172
+
173
+ /** Choices of an input: `value|Label` or a label that is also the value, at most 100, distinct values. */
174
+ export function choiceOptions(lines: unknown): ChoiceOption[] {
175
+ if (!Array.isArray(lines)) return [];
176
+ const options: ChoiceOption[] = [];
177
+ const seen = new Set<string>();
178
+ for (const line of lines) {
179
+ if (typeof line !== 'string') continue;
180
+ const bar = line.indexOf('|');
181
+ const value = (bar === -1 ? line : line.slice(0, bar)).trim();
182
+ const label = (bar === -1 ? line : line.slice(bar + 1)).trim() || value;
183
+ if (!value || seen.has(value)) continue;
184
+ seen.add(value);
185
+ options.push(Object.freeze({ value, label }));
186
+ if (options.length === 100) break;
187
+ }
188
+ return options;
189
+ }
190
+
191
+ /**
192
+ * The inputs of a form in document order: those of its top level, a repeater among them
193
+ * carrying its rows' inputs as `inputs`. Blocks of unknown types are left out.
194
+ */
195
+ export function formInputs(blocks: readonly Block[], types: ReadonlyMap<string, BlockDeclaration>, parent: string | null = null): FormField[] {
196
+ const inputs: FormField[] = [];
197
+ const walk = (list: readonly Block[]) => {
198
+ for (const block of list) {
199
+ const kind = types.get(block.type)?.input?.kind;
200
+ if (kind && typeof block.data.name === 'string') {
201
+ inputs.push(Object.freeze({
202
+ _id: block._id, type: block.type, name: block.data.name, kind,
203
+ label: typeof block.data.label === 'string' && block.data.label ? block.data.label : block.data.name,
204
+ required: block.data.required === true,
205
+ multiple: block.data.multiple === true && MULTIPLE_INPUT_KINDS.includes(kind),
206
+ options: kind === 'choice' || kind === 'choices' ? choiceOptions(block.data.options) : [],
207
+ data: block.data,
208
+ // A repeater inside a repeater is not valid; its inputs are left out, as the form check refuses it.
209
+ inputs: kind === 'rows' && parent === null ? formInputs(block.children ?? [], types, block.data.name) : [],
210
+ parent,
211
+ }));
212
+ if (kind === 'rows') continue;
213
+ }
214
+ if (block.children) walk(block.children);
215
+ }
216
+ };
217
+ walk(blocks);
218
+ return inputs;
219
+ }
220
+
221
+ /** Every input of a form, the repeaters' rows' inputs after their repeater, in document order. */
222
+ export function flatFormInputs(inputs: readonly FormField[]): FormField[] {
223
+ return inputs.flatMap(input => [input, ...input.inputs]);
224
+ }
225
+
226
+ // --- Conditions ---------------------------------------------------------------------------
227
+
228
+ /** A value of an input: text, a number, a yes or no, the chosen values or a multiple input's items, a repeater's rows, or a file input's files. */
229
+ export type FormValue = string | number | boolean | readonly string[] | readonly number[] | readonly FormRow[] | readonly FormFile[];
230
+ export type FormValues = { readonly [name: string]: FormValue };
231
+ /** One row of a repeater: its inputs' values under `_id`, which names the row in errors and in the page. */
232
+ export type FormRow = { readonly _id: string; readonly [name: string]: FormValue };
233
+
234
+ /**
235
+ * A file of a file input: as posted (a `File`, until the host stores it) or as kept with the
236
+ * submission, with its `id`. Hooks, notifications, webhooks and exports see this metadata,
237
+ * never the bytes; once stored, `type` is the type its content was checked against.
238
+ */
239
+ export interface FormFile {
240
+ readonly id?: string;
241
+ readonly name: string;
242
+ readonly size: number;
243
+ readonly type: string;
244
+ }
245
+
246
+ const isFileLike = (entry: unknown): entry is FormFile => !!entry && typeof entry === 'object' && !Array.isArray(entry)
247
+ && typeof (entry as FormFile).name === 'string' && typeof (entry as FormFile).size === 'number' && Number.isSafeInteger((entry as FormFile).size) && typeof (entry as FormFile).type === 'string';
248
+
249
+ /** The files of a file input's value as plain `{ id?, name, size, type }`, posted `File`s included; anything else is left out. */
250
+ export function formFiles(value: unknown): FormFile[] {
251
+ if (!Array.isArray(value)) return [];
252
+ return value.filter(isFileLike).map(file => Object.freeze({ ...(typeof file.id === 'string' ? { id: file.id } : {}), name: file.name, size: file.size, type: file.type }));
253
+ }
254
+
255
+ /** A file input's allowed types, lowercase: extensions with their dot, types and `family/*`. */
256
+ export function acceptList(value: unknown): string[] {
257
+ return typeof value === 'string' ? value.split(',').map(token => token.trim().toLowerCase()).filter(Boolean) : [];
258
+ }
259
+
260
+ /**
261
+ * Whether a file is one of the allowed types: by its extension, or by its type, which follows
262
+ * the extension when it is a known one (`fileType`), so a renamed file cannot pass as another
263
+ * family. An empty list allows any type. The host also checks the content against the type.
264
+ */
265
+ export function acceptsFile(accept: readonly string[], name: string, declared: string): boolean {
266
+ if (!accept.length) return true;
267
+ const extension = fileExtension(name);
268
+ const type = fileType(name, declared);
269
+ return accept.some(token => token.startsWith('.') ? token.slice(1) === extension : token.endsWith('/*') ? type.startsWith(token.slice(0, -1)) : type === token);
270
+ }
271
+
272
+ /** Whether a value is a repeater's rows. An empty list is blank either way. */
273
+ export function isRows(value: unknown): value is readonly FormRow[] {
274
+ return Array.isArray(value) && value.length > 0 && value.every(entry => entry && typeof entry === 'object' && !Array.isArray(entry));
275
+ }
276
+ /** A row's values keyed by input name, without `_id`. */
277
+ export function rowValues(row: FormRow): FormValues {
278
+ const { _id, ...values } = row;
279
+ return values;
280
+ }
281
+
282
+ const blank = (value: FormValue | null | undefined): boolean =>
283
+ value === undefined || value === null || value === '' || value === false || (Array.isArray(value) && value.length === 0);
284
+ /** Text to compare: a repeater counts as its number of rows. */
285
+ const asText = (value: FormValue): string => typeof value === 'string' ? value : typeof value === 'number' ? String(value) : typeof value === 'boolean' ? String(value) : isRows(value) ? String(value.length) : (value as readonly (string | number)[]).join(',');
286
+ /** Case-blind equality; a multiple Number input holds numbers, compared as their text. */
287
+ const same = (a: string | number, b: string) => String(a).trim().toLocaleLowerCase() === b.trim().toLocaleLowerCase();
288
+
289
+ function compare(value: FormValue, expected: string): number | null {
290
+ if (Array.isArray(value) || typeof value === 'boolean') return null;
291
+ const a = typeof value === 'number' ? value : Number(value);
292
+ const b = Number(expected);
293
+ if (String(value).trim() !== '' && expected.trim() !== '' && Number.isFinite(a) && Number.isFinite(b)) return a - b;
294
+ // Dates as YYYY-MM-DD compare as text.
295
+ const text = String(value);
296
+ return text < expected ? -1 : text > expected ? 1 : 0;
297
+ }
298
+
299
+ /** Whether one rule matches the values. A repeater's value is its number of rows. */
300
+ export function ruleMatches(rule: ConditionRule, values: FormValues): boolean {
301
+ const raw = values[rule.field];
302
+ const value: FormValue | undefined = isRows(raw) ? raw.length : raw;
303
+ const expected = rule.value ?? '';
304
+ switch (rule.op) {
305
+ case 'empty': return blank(value);
306
+ case 'notEmpty': return !blank(value);
307
+ case 'is': case 'isNot': {
308
+ const match = value !== undefined && (Array.isArray(value) ? value.some(entry => same(entry, expected)) : same(asText(value as FormValue), expected));
309
+ return rule.op === 'is' ? match : !match;
310
+ }
311
+ case 'contains':
312
+ if (blank(value)) return false;
313
+ return Array.isArray(value) ? value.some(entry => same(entry, expected)) : asText(value as FormValue).toLocaleLowerCase().includes(expected.trim().toLocaleLowerCase());
314
+ case 'in': {
315
+ if (blank(value) && value !== false) return false;
316
+ const list = expected.split(',').map(entry => entry.trim()).filter(Boolean);
317
+ const entries = Array.isArray(value) ? value : [asText(value as FormValue)];
318
+ return entries.some(entry => list.some(item => same(item, entry)));
319
+ }
320
+ case 'gt': case 'lt': {
321
+ if (blank(value)) return false;
322
+ const order = compare(value as FormValue, expected);
323
+ return order !== null && (rule.op === 'gt' ? order > 0 : order < 0);
324
+ }
325
+ }
326
+ }
327
+
328
+ /** Whether a block with this condition shows. A block without one always shows. */
329
+ export function conditionShows(when: BlockCondition | undefined, values: FormValues): boolean {
330
+ if (!when) return true;
331
+ const results = when.rules.map(rule => ruleMatches(rule, values));
332
+ const matched = when.match === 'any' ? results.some(Boolean) : results.every(Boolean);
333
+ return when.action === 'hide' ? !matched : matched;
334
+ }
335
+
336
+ /**
337
+ * Which blocks of a form are hidden by their conditions, or inside a hidden container, and
338
+ * the values that count: hidden inputs count as empty, so conditions that depend on them
339
+ * follow. Settles after a few rounds; a cycle stops at the last round.
340
+ */
341
+ export function formVisibility(blocks: readonly Block[], types: ReadonlyMap<string, BlockDeclaration>, values: FormValues): { hidden: ReadonlySet<string>; values: FormValues } {
342
+ const inputs = new Map(formInputs(blocks, types).map(input => [input._id, input.name]));
343
+ let current: FormValues = values;
344
+ let hidden = new Set<string>();
345
+ for (let round = 0; round <= inputs.size; round++) {
346
+ const next = new Set<string>();
347
+ const walk = (list: readonly Block[], inside: boolean) => {
348
+ for (const block of list) {
349
+ const off = inside || !conditionShows(block.when, current);
350
+ if (off) next.add(block._id);
351
+ // A repeater's rows have conditions of their own, settled per row with the row's values.
352
+ if (types.get(block.type)?.input?.kind !== 'rows') walk(block.children ?? [], off);
353
+ }
354
+ };
355
+ walk(blocks, false);
356
+ const counted: { [name: string]: FormValue } = {};
357
+ for (const [name, value] of Object.entries(values)) counted[name] = value;
358
+ for (const [id, name] of inputs) if (next.has(id)) delete counted[name];
359
+ const settled = next.size === hidden.size && [...next].every(id => hidden.has(id));
360
+ hidden = next;
361
+ current = counted;
362
+ if (settled) break;
363
+ }
364
+ return { hidden, values: current };
365
+ }
366
+
367
+ /** The form's blocks without those its conditions hide. */
368
+ export function visibleBlocks(blocks: readonly Block[], types: ReadonlyMap<string, BlockDeclaration>, values: FormValues): Block[] {
369
+ const { hidden } = formVisibility(blocks, types, values);
370
+ const keep = (list: readonly Block[]): Block[] => list.filter(block => !hidden.has(block._id)).map(block => block.children ? { ...block, children: keep(block.children) } : block);
371
+ return keep(blocks);
372
+ }
373
+
374
+ // --- Submissions --------------------------------------------------------------------------
375
+
376
+ /** What a form posts: text, or several texts for checkboxes, or rows of those for a repeater. JSON may send numbers and booleans too. */
377
+ export type SubmittedValues = { readonly [name: string]: unknown };
378
+ /** A posted value as form data carries it. */
379
+ export type PostedValue = string | string[] | { [name: string]: string | string[] }[];
380
+
381
+ /** The HTML name of an input: `name` at the top level, `repeater[row id][name]` in a row. Errors use the dotted key. */
382
+ export function inputHtmlName(key: string): string {
383
+ const [head, ...rest] = key.split('.');
384
+ return `${head}${rest.map(part => `[${part}]`).join('')}`;
385
+ }
386
+ /** The dotted key of a posted field, from its HTML name. */
387
+ export function inputKey(htmlName: string): string {
388
+ return htmlName.replace(/\[([^\]]*)\]/g, '.$1');
389
+ }
390
+
391
+ export interface SubmissionCheck {
392
+ /** Values of the shown inputs that were filled in, typed by kind. */
393
+ readonly values: FormValues;
394
+ /** Messages by input name, for the shown inputs. */
395
+ readonly errors: { readonly [name: string]: string };
396
+ /** IDs of hidden blocks. */
397
+ readonly hidden: ReadonlySet<string>;
398
+ }
399
+
400
+ /**
401
+ * Read the inputs of a form from posted form data: every value of a checkboxes or multiple
402
+ * input, one of the others, and a repeater's rows from `repeater[row id][input]` names, in
403
+ * the order the rows appear, at most `FORM_ROW_LIMIT` of them.
404
+ */
405
+ export function formDataValues(form: Pick<FormData, 'get' | 'getAll' | 'keys'>, inputs: readonly FormField[]): { [name: string]: PostedValue | File[] } {
406
+ const values: { [name: string]: PostedValue | File[] } = {};
407
+ const read = (input: FormField, htmlName: string): string | string[] | undefined => {
408
+ if (input.kind === 'choices' || input.multiple) return form.getAll(htmlName).filter((entry): entry is string => typeof entry === 'string');
409
+ const value = form.get(htmlName);
410
+ return typeof value === 'string' ? value : undefined;
411
+ };
412
+ let keys: string[] | undefined;
413
+ for (const input of inputs) {
414
+ if (input.kind === 'rows') {
415
+ keys ??= [...form.keys()];
416
+ const ids: string[] = [];
417
+ const pattern = new RegExp(`^${input.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\[([A-Za-z0-9_-]{1,40})\\]\\[`);
418
+ for (const key of keys) {
419
+ const id = pattern.exec(key)?.[1];
420
+ if (id && !ids.includes(id)) ids.push(id);
421
+ }
422
+ values[input.name] = ids.slice(0, FORM_ROW_LIMIT).map(id => {
423
+ const row: { [name: string]: string | string[] } = { _id: id };
424
+ for (const child of input.inputs) {
425
+ const value = read(child, `${input.name}[${id}][${child.name}]`);
426
+ if (value !== undefined) row[child.name] = value;
427
+ }
428
+ return row;
429
+ });
430
+ continue;
431
+ }
432
+ // A file input's files, as the multipart post carries them.
433
+ if (input.kind === 'file') { values[input.name] = form.getAll(input.name).filter((entry): entry is File => typeof entry !== 'string'); continue; }
434
+ const value = read(input, input.name);
435
+ if (value !== undefined) values[input.name] = value;
436
+ }
437
+ return values;
438
+ }
439
+
440
+ const EMAIL = /^[^\s@<>()[\]\\,;:"]+@[^\s@<>()[\]\\,;:"]+\.[^\s@<>()[\]\\,;:"]+$/;
441
+ const PHONE = /^\+?[0-9 ().-]{5,30}$/;
442
+
443
+ /** Read one posted value as the input's kind. */
444
+ function readValue(input: FormField, raw: unknown): { value: FormValue | null; error?: string } {
445
+ const one = Array.isArray(raw) ? raw[0] : raw;
446
+ switch (input.kind) {
447
+ case 'boolean': return { value: one === true || (typeof one === 'string' && ['on', 'true', '1', 'yes'].includes(one.toLowerCase())) };
448
+ case 'choices': {
449
+ const list = (Array.isArray(raw) ? raw : raw === undefined || raw === null || raw === '' ? [] : [raw]).filter((entry): entry is string => typeof entry === 'string').map(entry => entry.trim()).filter(Boolean);
450
+ return { value: [...new Set(list)] };
451
+ }
452
+ case 'number': {
453
+ if (typeof one === 'number') return Number.isFinite(one) ? { value: one } : { value: null, error: 'Enter a number.' };
454
+ const text = typeof one === 'string' ? one.trim() : '';
455
+ if (!text) return { value: null };
456
+ const value = Number(text);
457
+ return Number.isFinite(value) ? { value } : { value: null, error: 'Enter a number.' };
458
+ }
459
+ default: {
460
+ if (one !== undefined && one !== null && typeof one !== 'string') return { value: null, error: 'Enter text.' };
461
+ const text = input.kind === 'text' ? (one ?? '').replace(/\r\n?/g, '\n').trim() : (one ?? '').trim();
462
+ // Addresses compare without case: A@x.com and a@x.com are one address.
463
+ return { value: (input.kind === 'email' ? text.toLowerCase() : text) || null };
464
+ }
465
+ }
466
+ }
467
+
468
+ /** The posted items of a multiple input, each read as the kind, in posted order, at most `FORM_ITEM_LIMIT`; a scalar is one item. */
469
+ function readItems(input: FormField, raw: unknown): { value: FormValue | null; error?: string }[] {
470
+ const list = Array.isArray(raw) ? raw : raw === undefined || raw === null || raw === '' ? [] : [raw];
471
+ return list.slice(0, FORM_ITEM_LIMIT).map(item => readValue(input, item));
472
+ }
473
+
474
+ const numberData = (value: unknown): number | undefined => typeof value === 'number' && Number.isFinite(value) ? value : undefined;
475
+
476
+ /** Why a filled-in value is not right for its input, as a sentence for the visitor. */
477
+ function valueProblem(input: FormField, value: FormValue): string | undefined {
478
+ const data = input.data;
479
+ switch (input.kind) {
480
+ case 'string': case 'text': case 'email': case 'url': case 'phone': {
481
+ const text = value as string;
482
+ const length = [...text].length;
483
+ const fallback = input.kind === 'text' ? 5000 : input.kind === 'url' ? 2048 : input.kind === 'email' ? 254 : input.kind === 'phone' ? 30 : 255;
484
+ const max = numberData(data.maxLength) ?? fallback;
485
+ const min = numberData(data.minLength);
486
+ if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(text)) return 'Enter well-formed text.';
487
+ if (length > max) return `Use at most ${max} characters.`;
488
+ if (min !== undefined && length < min) return `Use at least ${min} characters.`;
489
+ if (input.kind === 'email' && !EMAIL.test(text)) return 'Enter an email address, such as name@example.com.';
490
+ if (input.kind === 'url') {
491
+ let url: URL | undefined;
492
+ try { url = new URL(text); } catch { /* not a URL */ }
493
+ if (!url || (url.protocol !== 'https:' && url.protocol !== 'http:')) return 'Enter a web address starting with https://.';
494
+ }
495
+ if (input.kind === 'phone' && (!PHONE.test(text) || text.replace(/\D/g, '').length < 5)) return 'Enter a phone number.';
496
+ if (input.kind === 'string' && typeof data.pattern === 'string' && data.pattern) {
497
+ let pattern: RegExp | undefined;
498
+ try { pattern = new RegExp(`^(?:${data.pattern})$`, 'u'); } catch { /* an invalid pattern checks nothing */ }
499
+ if (pattern && !pattern.test(text)) return 'Enter a value in the expected format.';
500
+ }
501
+ return undefined;
502
+ }
503
+ case 'number': {
504
+ const number = value as number;
505
+ const min = numberData(data.min);
506
+ const max = numberData(data.max);
507
+ const step = numberData(data.step);
508
+ if (min !== undefined && number < min) return `Enter ${min} or more.`;
509
+ if (max !== undefined && number > max) return `Enter ${max} or less.`;
510
+ if (step) {
511
+ const steps = (number - (min ?? 0)) / step;
512
+ if (Math.abs(steps - Math.round(steps)) > 1e-9) return step === 1 ? 'Enter a whole number.' : `Enter a multiple of ${step}${min ? ` from ${min}` : ''}.`;
513
+ }
514
+ return undefined;
515
+ }
516
+ case 'date': {
517
+ const text = value as string;
518
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
519
+ const date = match ? new Date(Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3]))) : null;
520
+ if (!match || !date || date.toISOString().slice(0, 10) !== text) return 'Enter a date.';
521
+ if (typeof data.min === 'string' && data.min && text < data.min) return `Choose ${data.min} or later.`;
522
+ if (typeof data.max === 'string' && data.max && text > data.max) return `Choose ${data.max} or earlier.`;
523
+ return undefined;
524
+ }
525
+ case 'choice': return input.options.some(option => option.value === value) ? undefined : 'Choose one of the options.';
526
+ case 'choices': return (value as readonly string[]).every(entry => input.options.some(option => option.value === entry)) ? undefined : 'Choose from the options.';
527
+ case 'boolean': return undefined;
528
+ }
529
+ }
530
+
531
+ /** The posted files of a file input, at most one more than it takes; a control left empty posts a nameless empty file, which is none. */
532
+ function postedFiles(raw: unknown): FormFile[] {
533
+ const list = Array.isArray(raw) ? raw : raw === undefined || raw === null || raw === '' ? [] : [raw];
534
+ return list.filter((entry): entry is FormFile => isFileLike(entry) && !(entry.name === '' && entry.size === 0)).slice(0, FORM_FILE_LIMIT + 1);
535
+ }
536
+
537
+ /** Why a file input's files are not right for it, as a sentence for the visitor: their number, size and type. */
538
+ function filesProblem(input: FormField, files: readonly FormFile[]): string | undefined {
539
+ const most = input.data.multipleFiles === true ? Math.min(numberData(input.data.maxFiles) ?? FORM_FILE_LIMIT, FORM_FILE_LIMIT) : 1;
540
+ if (files.length > most) return most === 1 ? 'Choose one file.' : `Choose at most ${most} files.`;
541
+ const largest = Math.min(numberData(input.data.maxSize) ?? FORM_FILE_MAX_MB, FORM_FILE_MAX_MB);
542
+ const accept = acceptList(input.data.accept);
543
+ for (const file of files) {
544
+ const name = file.name.slice(0, 80) || 'The file';
545
+ if (file.size < 1) return `${name} is empty.`;
546
+ if (file.size > largest * MB) return `${name} is larger than ${largest} MB.`;
547
+ if (!acceptsFile(accept, file.name, file.type)) return `${name} is not an allowed type. Choose ${accept.join(', ')}.`;
548
+ }
549
+ if (files.reduce((sum, file) => sum + file.size, 0) > FORM_UPLOAD_LIMIT_MB * MB) return `The files add up to more than ${FORM_UPLOAD_LIMIT_MB} MB.`;
550
+ return undefined;
551
+ }
552
+
553
+ /** The posted rows of a repeater as objects, in order, at most `FORM_ROW_LIMIT`; anything else is no rows. */
554
+ function postedRows(raw: unknown): { [name: string]: unknown }[] {
555
+ return (Array.isArray(raw) ? raw : []).filter((row): row is { [name: string]: unknown } => !!row && typeof row === 'object' && !Array.isArray(row)).slice(0, FORM_ROW_LIMIT);
556
+ }
557
+
558
+ /** What a repeater calls one row, lowercase, for its messages. */
559
+ function rowName(input: FormField, count: number): string {
560
+ const label = typeof input.data.rowLabel === 'string' && input.data.rowLabel.trim() ? input.data.rowLabel.trim() : '';
561
+ if (!label) return count === 1 ? 'row' : 'rows';
562
+ return count === 1 ? label : `${label} rows`;
563
+ }
564
+
565
+ /**
566
+ * Check a submission against a form: read each value as its input's kind, apply the
567
+ * conditions, and check the shown inputs. Hidden inputs are neither required nor kept. A
568
+ * repeater's rows are checked the same way, each with its own values over the form's: its
569
+ * errors are keyed `repeater.<row id>.<input>`, its hidden blocks `<row id>:<block id>`.
570
+ */
571
+ export function validateSubmission(blocks: readonly Block[], types: ReadonlyMap<string, BlockDeclaration>, raw: SubmittedValues): SubmissionCheck {
572
+ const errors: { [name: string]: string } = {};
573
+ const hidden = new Set<string>();
574
+ const values = checkLevel(blocks, formInputs(blocks, types), types, raw, {}, { key: '', id: '' }, errors, hidden);
575
+ return { values: Object.freeze(values), errors: Object.freeze(errors), hidden };
576
+ }
577
+
578
+ /** One level of a submission: the form's top level, or one row of a repeater with the form's values as `outer`. */
579
+ function checkLevel(blocks: readonly Block[], inputs: readonly FormField[], types: ReadonlyMap<string, BlockDeclaration>, raw: SubmittedValues, outer: FormValues,
580
+ prefix: { readonly key: string; readonly id: string }, errors: { [name: string]: string }, hidden: Set<string>): { [name: string]: FormValue } {
581
+ const read: { [name: string]: FormValue } = {};
582
+ const unreadable: { [name: string]: string } = {};
583
+ for (const input of inputs) {
584
+ if (input.kind === 'rows') {
585
+ const entry = raw[input.name];
586
+ if (entry !== undefined && entry !== null && entry !== '' && !Array.isArray(entry)) unreadable[input.name] = 'Send the rows as a list.';
587
+ else if (postedRows(entry).length) read[input.name] = postedRows(entry).map(row => ({ _id: '' }));
588
+ continue;
589
+ }
590
+ // Conditions see a file input's number of files.
591
+ if (input.kind === 'file') { const files = postedFiles(raw[input.name]); if (files.length) read[input.name] = files; continue; }
592
+ if (input.multiple) {
593
+ const items = readItems(input, raw[input.name]).flatMap(item => item.value === null ? [] : [item.value]);
594
+ if (items.length) read[input.name] = items as string[] | number[];
595
+ continue;
596
+ }
597
+ const { value, error } = readValue(input, raw[input.name]);
598
+ if (error) unreadable[input.name] = error;
599
+ else if (value !== null) read[input.name] = value;
600
+ }
601
+ const { hidden: off } = formVisibility(blocks, types, { ...outer, ...read });
602
+ for (const id of off) hidden.add(prefix.id ? `${prefix.id}:${id}` : id);
603
+ const values: { [name: string]: FormValue } = {};
604
+ for (const input of inputs) {
605
+ if (off.has(input._id)) continue;
606
+ const key = `${prefix.key}${input.name}`;
607
+ if (unreadable[input.name]) { errors[key] = unreadable[input.name]!; continue; }
608
+ if (input.kind === 'rows') {
609
+ const children = (blocks.length ? flattenBlocks(blocks).find(entry => entry._id === input._id) : undefined)?.children ?? [];
610
+ // A row nobody filled in, such as the empty one a form starts with, is not a row: it is neither checked nor kept, though its conditions still settle on the page.
611
+ const posted = postedRows(raw[input.name]);
612
+ const filled = (row: { [name: string]: unknown }) => input.inputs.some(child => !blank(readValue(child, row[child.name]).value));
613
+ const count = posted.filter(filled).length;
614
+ const most = Math.min(numberData(input.data.max) ?? FORM_ROW_LIMIT, FORM_ROW_LIMIT);
615
+ const fewest = Math.max(numberData(input.data.min) ?? 0, input.required ? 1 : 0);
616
+ if (count > most) errors[key] = `Add at most ${most} ${rowName(input, most)}.`;
617
+ else if (count < fewest) errors[key] = `Add at least ${fewest} ${rowName(input, fewest)}.`;
618
+ const ids = new Set<string>();
619
+ const rows: FormRow[] = [];
620
+ posted.forEach((row, index) => {
621
+ const id = typeof row._id === 'string' && /^[A-Za-z0-9_-]{1,40}$/.test(row._id) && !ids.has(row._id) ? row._id : `r${index + 1}`;
622
+ ids.add(id);
623
+ if (filled(row)) {
624
+ rows.push(Object.freeze({ _id: id, ...checkLevel(children, input.inputs, types, row, { ...outer, ...read }, { key: `${key}.${id}.`, id }, errors, hidden) }));
625
+ return;
626
+ }
627
+ const own: { [name: string]: FormValue } = {};
628
+ for (const child of input.inputs) { const { value } = readValue(child, row[child.name]); if (value !== null) own[child.name] = value; }
629
+ for (const off of formVisibility(children, types, { ...outer, ...read, ...own }).hidden) hidden.add(`${id}:${off}`);
630
+ });
631
+ values[input.name] = rows;
632
+ continue;
633
+ }
634
+ if (input.kind === 'file') {
635
+ // The files stay as posted: the host stores them once the whole submission is valid.
636
+ const files = postedFiles(raw[input.name]);
637
+ const problem = files.length ? filesProblem(input, files) : input.required ? 'Choose a file.' : undefined;
638
+ if (problem) errors[key] = problem;
639
+ else if (files.length) values[input.name] = files;
640
+ continue;
641
+ }
642
+ if (input.multiple) {
643
+ // Each item is checked as the kind; a blank item, such as the empty control a form starts with, is dropped. Errors name the item's position as posted.
644
+ const items = readItems(input, raw[input.name]);
645
+ const kept: (string | number)[] = [];
646
+ let count = 0;
647
+ items.forEach((item, index) => {
648
+ if (item.error) { errors[`${key}.${index + 1}`] = item.error; count++; return; }
649
+ if (item.value === null) return;
650
+ count++;
651
+ const problem = valueProblem(input, item.value);
652
+ if (problem) errors[`${key}.${index + 1}`] = problem;
653
+ else kept.push(item.value as string | number);
654
+ });
655
+ const most = Math.min(numberData(input.data.maxItems) ?? FORM_ITEM_LIMIT, FORM_ITEM_LIMIT);
656
+ const fewest = Math.max(numberData(input.data.minItems) ?? 0, input.required ? 1 : 0);
657
+ if (count > most) errors[key] = `Add at most ${most} ${most === 1 ? 'value' : 'values'}.`;
658
+ else if (count === 0 && fewest === 1) errors[key] = 'This field is required.';
659
+ else if (count < fewest) errors[key] = `Add at least ${fewest} values.`;
660
+ if (kept.length) values[input.name] = kept as string[] | number[];
661
+ continue;
662
+ }
663
+ const value = read[input.name];
664
+ if (blank(value)) {
665
+ if (input.required) errors[key] = input.kind === 'boolean' ? 'Tick this box to continue.' : input.kind === 'choices' ? 'Choose at least one option.' : 'This field is required.';
666
+ // An unticked box is a no.
667
+ if (input.kind === 'boolean') values[input.name] = false;
668
+ continue;
669
+ }
670
+ const problem = valueProblem(input, value!);
671
+ if (problem) errors[key] = problem;
672
+ else values[input.name] = value!;
673
+ }
674
+ return values;
675
+ }
676
+
677
+ /**
678
+ * How a value reads in emails, lists and exports: choice labels, Yes or No, values joined by
679
+ * commas, a repeater as its number of rows ("Passenger × 3"; `displayRows` has the rows), and
680
+ * files by name and size, never their content.
681
+ */
682
+ export function displayValue(input: Pick<FormField, 'kind' | 'options'> & { readonly data?: FormField['data'] }, value: FormValue | null | undefined): string {
683
+ if (value === undefined || value === null) return '';
684
+ if (typeof value === 'boolean') return value ? 'Yes' : 'No';
685
+ if (input.kind === 'file') return formFiles(value).map(file => `${file.name} (${formatBytes(file.size)})`).join(', ');
686
+ if (input.kind === 'rows') {
687
+ const count = Array.isArray(value) ? value.length : 0;
688
+ const label = typeof input.data?.rowLabel === 'string' && input.data.rowLabel.trim() ? input.data.rowLabel.trim() : '';
689
+ return label ? `${label} × ${count}` : `${count} ${count === 1 ? 'row' : 'rows'}`;
690
+ }
691
+ const label = (entry: string | number) => input.options.find(option => option.value === entry)?.label ?? String(entry);
692
+ if (isRows(value)) return `${value.length} ${value.length === 1 ? 'row' : 'rows'}`;
693
+ if (Array.isArray(value)) return (value as readonly (string | number)[]).map(label).join(', ');
694
+ return input.kind === 'choice' ? label(String(value)) : String(value);
695
+ }
696
+
697
+ /** A repeater's rows as lines of text, one per row: `Label: value, Label: value`, inputs without a value left out. */
698
+ export function displayRows(input: Pick<FormField, 'inputs'>, value: FormValue | null | undefined): string[] {
699
+ if (!isRows(value)) return [];
700
+ return value.map(row => input.inputs
701
+ .filter(child => !blank(row[child.name]) || row[child.name] === false)
702
+ .map(child => `${child.label}: ${displayValue(child, row[child.name])}`).join(', '));
703
+ }
704
+
705
+ // --- The forms collection -----------------------------------------------------------------
706
+
707
+ /** What a form does around its inputs. Every setting is optional; `formSettings` fills the defaults. */
708
+ export const FORM_SETTINGS = Object.freeze({
709
+ submitLabel: field.string({ max: 80, default: 'Submit', label: 'Submit button' }),
710
+ confirmation: field.enum(['message', 'redirect'], { default: 'message', label: 'After submitting', choices: { message: 'Show a message', redirect: 'Go to a page' } }),
711
+ message: field.text({ max: 5000, format: 'markdown', default: 'Thanks! We received your submission.', label: 'Message' }),
712
+ redirectUrl: field.string({ max: 2048, pattern: '(?:https?://\\S+|/\\S*)?', label: 'Page address', description: 'A path such as /thanks, or a full address.' }),
713
+ closedMessage: field.text({ max: 2000, format: 'markdown', default: 'This form is closed.', label: 'Closed message' }),
714
+ limit: field.integer({ min: 1, max: 10_000_000, label: 'Submission limit', description: 'Close the form after this many submissions. Empty for no limit.' }),
715
+ opensAt: field.datetime({ label: 'Opens' }),
716
+ closesAt: field.datetime({ label: 'Closes' }),
717
+ requireSignIn: field.boolean({ default: false, label: 'Only signed-in people can submit' }),
718
+ oncePerUser: field.boolean({ default: false, label: 'One submission per person', description: 'People sign in to submit.' }),
719
+ oncePerEmail: field.string({ max: 40, pattern: `(?:${INPUT_NAME.source.slice(1, -1)})?`, label: 'One submission per address in', description: 'The name of an email field. Empty to allow repeats.' }),
720
+ store: field.boolean({ default: true, label: 'Keep submissions', description: 'Off sends the notifications and keeps nothing.' }),
721
+ recordIp: field.boolean({ default: true, label: 'Keep the sender\'s IP address' }),
722
+ turnstile: field.boolean({ default: true, label: 'Check for bots with Turnstile', description: 'When the site has Turnstile keys.' }),
723
+ });
724
+
725
+ export interface FormSettings {
726
+ readonly submitLabel: string;
727
+ readonly confirmation: 'message' | 'redirect';
728
+ readonly message: string;
729
+ readonly redirectUrl: string;
730
+ readonly closedMessage: string;
731
+ readonly limit: number | null;
732
+ readonly opensAt: number | null;
733
+ readonly closesAt: number | null;
734
+ readonly requireSignIn: boolean;
735
+ readonly oncePerUser: boolean;
736
+ readonly oncePerEmail: string;
737
+ readonly store: boolean;
738
+ readonly recordIp: boolean;
739
+ readonly turnstile: boolean;
740
+ }
741
+
742
+ /** A form's settings with defaults for those it does not set. */
743
+ export function formSettings(value: unknown): FormSettings {
744
+ const stored = value && typeof value === 'object' && !Array.isArray(value) ? value as { [key: string]: unknown } : {};
745
+ const settings: { [key: string]: unknown } = {};
746
+ for (const [name, declaration] of Object.entries(FORM_SETTINGS)) {
747
+ const entry = stored[name];
748
+ settings[name] = entry !== undefined && entry !== null && entry !== '' ? entry : declaration.default ?? (declaration.kind === 'string' || declaration.kind === 'text' ? '' : null);
749
+ }
750
+ return Object.freeze(settings) as unknown as FormSettings;
751
+ }
752
+
753
+ /**
754
+ * Built-in forms: their inputs and layout are blocks, their settings and notifications are
755
+ * fields. The slug names a form on the site and in the API; submissions are kept apart.
756
+ */
757
+ export const forms: CollectionDefinition = {
758
+ name: 'forms',
759
+ label: 'Forms',
760
+ singular: 'Form',
761
+ icon: 'checklist-minimalistic',
762
+ builtin: true,
763
+ // Forms have their own screens; the collection manager and field groups stay out of them.
764
+ managed: true,
765
+ // Draft forms are built in the dashboard; the site shows and takes only published ones.
766
+ visibility: 'private',
767
+ description: 'Forms built from blocks, with their own submissions.',
768
+ fields: {
769
+ body: { ...field.blocks({ label: 'Form' }), form: true },
770
+ enabled: field.boolean({ default: true, placement: 'sidebar', label: 'Accepting submissions' }),
771
+ settings: field.group(FORM_SETTINGS, { label: 'Settings' }),
772
+ notifications: field.json({ label: 'Notifications', description: 'Emails sent for each submission.' }),
773
+ },
774
+ // The form on its own tab, its settings and notifications on a second; see editor-layout.ts.
775
+ editor: {
776
+ tabs: [
777
+ { _id: EDIT_TAB, type: 'editor/tab', data: { label: 'Form' }, children: [boxBlock('field:body')] },
778
+ { _id: 'settings', type: 'editor/tab', data: { label: 'Settings' }, children: [boxBlock('field:settings'), boxBlock('field:notifications')] },
779
+ ],
780
+ sidebar: [boxBlock('languages'), boxBlock('field:enabled'), boxBlock('revisions')],
781
+ },
782
+ };
783
+
784
+ // --- Submission storage -------------------------------------------------------------------
785
+
786
+ export const SUBMISSION_STATUSES = Object.freeze(['new', 'read', 'spam', 'trash'] as const);
787
+ export type SubmissionStatus = (typeof SUBMISSION_STATUSES)[number];
788
+
789
+ /** What the host records beside the values. */
790
+ export const SUBMISSION_META = Object.freeze({
791
+ ip: field.string({ max: 64, label: 'IP address' }),
792
+ userAgent: field.string({ max: 300, label: 'Browser' }),
793
+ referrer: field.string({ max: 2048, label: 'Referrer' }),
794
+ page: field.string({ max: 2048, label: 'Page' }),
795
+ locale: field.string({ max: 16, label: 'Language' }),
796
+ });
797
+
798
+ export interface SubmissionMeta {
799
+ readonly ip?: string;
800
+ readonly userAgent?: string;
801
+ readonly referrer?: string;
802
+ readonly page?: string;
803
+ readonly locale?: string;
804
+ }
805
+
806
+ /**
807
+ * The resource holding a form's submissions, `cms/form_<form id>`: its table is the form's
808
+ * own, so a busy form never grows another's. Named by the form's ID, so renaming the form or
809
+ * changing its slug keeps the table.
810
+ */
811
+ export function submissionResourceName(formId: string): string {
812
+ const name = `form_${formId.toLowerCase().replace(/[^a-z0-9]/g, '')}`;
813
+ if (name.length === 5 || name.length > 41) throw new Error(`Form ${formId} cannot name a submissions table.`);
814
+ return name;
815
+ }
816
+
817
+ /** Prefix of submission resources in the `cms` namespace; collections cannot take it. */
818
+ export const SUBMISSION_PREFIX = 'form_';
819
+
820
+ function inputField(input: FormField): FieldDeclaration {
821
+ const declaration = singleInputField(input);
822
+ if (!input.multiple) return declaration;
823
+ // A multiple input is a list of the kind's values: never null, empty when nothing was entered.
824
+ const { nullable, ...rest } = declaration;
825
+ return { ...rest, multiple: true };
826
+ }
827
+
828
+ function singleInputField(input: FormField): FieldDeclaration {
829
+ const label = input.label.slice(0, 200);
830
+ switch (input.kind) {
831
+ case 'rows': {
832
+ // Rows are not searched or indexed: submissions are found by their top-level inputs.
833
+ const fields = Object.fromEntries(input.inputs.filter(child => child.kind !== 'rows').map(child => { const { search, ...declaration } = inputField(child); return [child.name, declaration]; }));
834
+ return field.rows(fields, { nullable: true, max: FORM_ROW_LIMIT, label });
835
+ }
836
+ case 'text': return field.text({ nullable: true, max: 50_000, search: true, label });
837
+ // References to the stored files, never their bytes; see CmsForms.
838
+ case 'file': return field.rows({
839
+ id: field.string({ required: true, max: 80 }), name: field.string({ required: true, max: 200 }),
840
+ size: field.integer({ required: true, min: 1 }), type: field.string({ required: true, max: 255 }),
841
+ }, { nullable: true, max: FORM_FILE_LIMIT, label });
842
+ case 'number': return field.number({ nullable: true, label });
843
+ case 'boolean': return field.boolean({ nullable: true, label });
844
+ case 'choices': return field.list('string', { label });
845
+ case 'string': case 'email': return field.string({ nullable: true, max: 10_000, search: true, label });
846
+ default: return field.string({ nullable: true, max: 10_000, label });
847
+ }
848
+ }
849
+
850
+ /**
851
+ * Submissions of a form: one field per input, then the status, a note and what the host
852
+ * records. Only the host writes them; reading and handling need `cms:submissions`. Added
853
+ * inputs are new fields; removed ones keep their stored values.
854
+ */
855
+ export function submissionResource(form: { readonly id: string; readonly title?: string }, inputs: readonly FormField[], options: { readonly indexed?: readonly string[] } = {}): ResourceDeclaration {
856
+ const fields: { [name: string]: FieldDeclaration } = {};
857
+ let searched = 0;
858
+ for (const input of inputs) {
859
+ let declaration = inputField(input);
860
+ if (declaration.search && ++searched > 16) declaration = { ...declaration, search: false };
861
+ // Inputs looked up on every submission, such as the email of "one per address".
862
+ if (options.indexed?.includes(input.name) && declaration.kind === 'string') declaration = { ...declaration, index: true };
863
+ fields[input.name] = declaration;
864
+ }
865
+ fields.status = field.enum(SUBMISSION_STATUSES, { required: true, default: 'new', label: 'Status' });
866
+ fields.note = field.text({ max: 5000, nullable: true, label: 'Note' });
867
+ fields.meta = field.group(SUBMISSION_META, { label: 'Details' });
868
+ const handle = { permission: PERMISSIONS.manageSubmissions };
869
+ return {
870
+ name: submissionResourceName(form.id),
871
+ owner: 'cms',
872
+ label: `${form.title ?? 'Form'} submissions`.slice(0, 120),
873
+ ownership: true,
874
+ revisions: false,
875
+ schemaless: true,
876
+ fields,
877
+ indexes: [{ name: 'inbox', fields: ['status', '_createdAt'] }],
878
+ access: { read: handle, create: 'none', update: handle, delete: handle },
879
+ };
880
+ }
881
+
882
+ /** A submission as the dashboard, hooks and notifications see it. */
883
+ export interface SubmissionShape {
884
+ readonly id: string;
885
+ /** The form's ID. */
886
+ readonly form: string;
887
+ readonly status: SubmissionStatus;
888
+ readonly values: FormValues;
889
+ readonly note: string;
890
+ readonly meta: SubmissionMeta;
891
+ /** The signed-in person who submitted, if any. */
892
+ readonly user: string | null;
893
+ readonly createdAt: number;
894
+ readonly updatedAt: number;
895
+ }
896
+
897
+ /** A submission from its record. Values of removed inputs stay out; files read as `FormFile`s. */
898
+ export function submissionOf(formId: string, record: RecordShape, inputs: readonly FormField[]): SubmissionShape {
899
+ const values: { [name: string]: FormValue } = {};
900
+ for (const input of inputs) {
901
+ const value = record[input.name];
902
+ if (value !== undefined && value !== null) values[input.name] = input.kind === 'file' ? Object.freeze(formFiles(value)) : value as FormValue;
903
+ }
904
+ return Object.freeze({
905
+ id: record.id, form: formId,
906
+ status: (SUBMISSION_STATUSES as readonly unknown[]).includes(record.status) ? record.status as SubmissionStatus : 'new',
907
+ values: Object.freeze(values), note: typeof record.note === 'string' ? record.note : '',
908
+ meta: Object.freeze({ ...(record.meta && typeof record.meta === 'object' ? record.meta as SubmissionMeta : {}) }),
909
+ user: record.owner, createdAt: record.createdAt, updatedAt: record.updatedAt,
910
+ });
911
+ }
912
+
913
+ // --- Notifications ------------------------------------------------------------------------
914
+
915
+ /** An email sent for each submission. Text fields take merge tags such as `{field:email}`. */
916
+ export interface NotificationRule {
917
+ /** Stable within the form: 1-40 letters, digits, `_` or `-`. */
918
+ readonly id: string;
919
+ readonly label: string;
920
+ readonly enabled?: boolean;
921
+ /** Comma-separated addresses or tags, such as `{admin_email}, {field:email}`. */
922
+ readonly to: string;
923
+ readonly subject: string;
924
+ /** Plain text; `{all_fields}` lists the answers. */
925
+ readonly body: string;
926
+ readonly replyTo?: string;
927
+ /** Send only when the submission's values match. */
928
+ readonly when?: BlockCondition;
929
+ }
930
+
931
+ export const NOTIFICATION_LIMIT = 10;
932
+ const RULE_ID = /^[A-Za-z0-9_-]{1,40}$/;
933
+ const TAG = /\{([a-z_]+)(?::([A-Za-z0-9_]+))?\}/g;
934
+
935
+ /** The rules stored in a form's `notifications` field: `{ rules: [...] }`. */
936
+ export function notificationRules(value: unknown): NotificationRule[] {
937
+ const rules = value && typeof value === 'object' && !Array.isArray(value) ? (value as { rules?: unknown }).rules : undefined;
938
+ return Array.isArray(rules) ? rules as NotificationRule[] : [];
939
+ }
940
+
941
+ /** Problems in a form's notification rules against its inputs; empty when they are fine. */
942
+ export function notificationProblems(value: unknown, inputs: readonly FormField[]): string[] {
943
+ if (value === null || value === undefined) return [];
944
+ if (typeof value !== 'object' || Array.isArray(value) || !Array.isArray((value as { rules?: unknown }).rules) || Object.keys(value).some(key => key !== 'rules')) return ['Notifications are { rules: [...] }.'];
945
+ const rules = (value as { rules: unknown[] }).rules;
946
+ if (rules.length > NOTIFICATION_LIMIT) return [`A form sends at most ${NOTIFICATION_LIMIT} notifications.`];
947
+ const problems: string[] = [];
948
+ const ids = new Set<string>();
949
+ const names = new Map(inputs.map(input => [input.name, input]));
950
+ for (const rule of rules) {
951
+ if (!rule || typeof rule !== 'object' || Array.isArray(rule)) { problems.push('Each notification is an object.'); continue; }
952
+ const { id, label, enabled, to, subject, body, replyTo, when } = rule as { [key: string]: unknown };
953
+ const at = `Notification ${typeof label === 'string' && label ? label : String(id)}`;
954
+ if (typeof id !== 'string' || !RULE_ID.test(id) || ids.has(id)) problems.push(`${at}: needs a distinct ID.`);
955
+ else ids.add(id);
956
+ if (typeof label !== 'string' || !label.trim() || label.length > 80) problems.push(`${at}: needs a name of at most 80 characters.`);
957
+ if (enabled !== undefined && typeof enabled !== 'boolean') problems.push(`${at}: is on or off.`);
958
+ for (const [key, entry, max, required] of [['to', to, 1000, true], ['replyTo', replyTo, 1000, false], ['subject', subject, 300, true], ['body', body, 20_000, true]] as const) {
959
+ if (entry === undefined && !required) continue;
960
+ if (typeof entry !== 'string' || (required && !entry.trim()) || entry.length > max) { problems.push(`${at}: ${key === 'replyTo' ? 'reply-to' : key} must be ${required ? '1' : '0'} to ${max} characters.`); continue; }
961
+ for (const match of entry.matchAll(TAG)) {
962
+ const problem = tagProblem(match[1]!, match[2], names);
963
+ if (problem) problems.push(`${at}: ${problem}`);
964
+ }
965
+ }
966
+ for (const [key, entry] of [['to', to], ['replyTo', replyTo]] as const) {
967
+ if (typeof entry !== 'string') continue;
968
+ for (const part of entry.split(',').map(item => item.trim()).filter(Boolean)) {
969
+ const tag = /^\{(field|admin_email|user)(?::([A-Za-z0-9_]+))?\}$/.exec(part);
970
+ if (tag) {
971
+ if (tag[1] === 'field' && names.get(tag[2] ?? '')?.kind !== 'email') problems.push(`${at}: ${key === 'to' ? 'recipients' : 'reply-to'} can use only email fields, not ${part}.`);
972
+ if (tag[1] === 'user' && tag[2] !== 'email') problems.push(`${at}: use {user:email} for the person who submitted.`);
973
+ } else if (!EMAIL.test(part)) problems.push(`${at}: ${part} is not an email address.`);
974
+ }
975
+ }
976
+ if (when !== undefined) {
977
+ const problem = blockConditionProblem(when);
978
+ if (problem) problems.push(`${at}: ${problem.replace('block when', 'the condition')}`);
979
+ else for (const condition of (when as BlockCondition).rules) if (!names.has(condition.field)) problems.push(`${at}: its condition names ${condition.field}, which is not a field of this form.`);
980
+ }
981
+ }
982
+ return problems;
983
+ }
984
+
985
+ /** Tags a template can use. */
986
+ export const MERGE_TAGS = Object.freeze([
987
+ { tag: '{all_fields}', label: 'All answers' },
988
+ { tag: '{form:title}', label: 'Form title' },
989
+ { tag: '{submission:id}', label: 'Submission ID' },
990
+ { tag: '{submission:url}', label: 'Submission in the dashboard' },
991
+ { tag: '{submission:date}', label: 'Submission time' },
992
+ { tag: '{user:email}', label: 'Email of the signed-in sender' },
993
+ { tag: '{user:name}', label: 'Name of the signed-in sender' },
994
+ { tag: '{site:title}', label: 'Site title' },
995
+ { tag: '{site:url}', label: 'Site address' },
996
+ { tag: '{admin_email}', label: 'Administration email' },
997
+ ] as const);
998
+
999
+ function tagProblem(name: string, argument: string | undefined, inputs: ReadonlyMap<string, FormField>): string | undefined {
1000
+ if (name === 'field') return argument && inputs.has(argument) ? undefined : `{field:${argument ?? ''}} is not a field of this form.`;
1001
+ const known = MERGE_TAGS.some(entry => entry.tag === `{${name}${argument ? `:${argument}` : ''}}`);
1002
+ return known ? undefined : `{${name}${argument ? `:${argument}` : ''}} is not a merge tag.`;
1003
+ }
1004
+
1005
+ export interface MergeContext {
1006
+ readonly form: { readonly id: string; readonly title: string };
1007
+ readonly inputs: readonly FormField[];
1008
+ readonly values: FormValues;
1009
+ readonly submission?: { readonly id: string; readonly url?: string; readonly date?: string };
1010
+ readonly user?: { readonly email: string; readonly name: string } | null;
1011
+ readonly site: { readonly title: string; readonly url: string; readonly adminEmail: string };
1012
+ }
1013
+
1014
+ /** Markdown's special characters escaped, so a sender's answer shows as typed in a Markdown message. */
1015
+ export function escapeMarkdown(text: string): string {
1016
+ return text.replace(/[\\`*_{}[\]()#+\-.!<>|~]/g, character => `\\${character}`);
1017
+ }
1018
+
1019
+ /**
1020
+ * Fill a template's merge tags. Tags it does not know stay as written, so mistakes show.
1021
+ * `escape` applies to what senders typed, such as `escapeMarkdown` for a Markdown message.
1022
+ */
1023
+ export function renderMergeTags(template: string, context: MergeContext, options: { readonly escape?: (text: string) => string } = {}): string {
1024
+ const inputs = new Map(context.inputs.map(input => [input.name, input]));
1025
+ const escape = options.escape ?? ((text: string) => text);
1026
+ return template.replace(TAG, (whole, name: string, argument?: string) => {
1027
+ switch (argument ? `${name}:${argument}` : name) {
1028
+ case 'all_fields': return context.inputs.filter(input => !blank(context.values[input.name]) || context.values[input.name] === false)
1029
+ .map(input => input.kind === 'rows'
1030
+ ? `${escape(input.label)}:\n${displayRows(input, context.values[input.name]).map((line, index) => `${index + 1}. ${escape(line)}`).join('\n')}`
1031
+ : `${escape(input.label)}: ${escape(displayValue(input, context.values[input.name]))}`).join('\n');
1032
+ case 'form:title': return context.form.title;
1033
+ case 'submission:id': return context.submission?.id ?? '';
1034
+ case 'submission:url': return context.submission?.url ?? '';
1035
+ case 'submission:date': return context.submission?.date ?? '';
1036
+ case 'user:email': return escape(context.user?.email ?? '');
1037
+ case 'user:name': return escape(context.user?.name ?? '');
1038
+ case 'site:title': return context.site.title;
1039
+ case 'site:url': return context.site.url;
1040
+ case 'admin_email': return context.site.adminEmail;
1041
+ }
1042
+ if (name === 'field' && argument && inputs.has(argument)) {
1043
+ const input = inputs.get(argument)!;
1044
+ return input.kind === 'rows' ? displayRows(input, context.values[argument]).map((line, index) => `${index + 1}. ${escape(line)}`).join('\n') : escape(displayValue(input, context.values[argument]));
1045
+ }
1046
+ return whole;
1047
+ });
1048
+ }
1049
+
1050
+ /** Addresses from a filled-in recipient list; parts that are not addresses are left out. */
1051
+ export function emailAddresses(list: string): string[] {
1052
+ return [...new Set(list.split(',').map(part => part.trim()).filter(part => EMAIL.test(part) && part.length <= 254))];
1053
+ }