@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,116 @@
1
+ /**
2
+ * Widget areas: one `cms_areas` row per area, its blocks as JSON with a revision. Themes name
3
+ * the areas they render (`theme.areas`); an area keeps its blocks across theme switches, as a
4
+ * menu location keeps its menu. Saving is one conditional write on the revision, so a stale
5
+ * editor writes nothing. Blocks are checked like a blocks field before they are stored.
6
+ */
7
+ import { ClientError, type RomeDB, type Statement } from '@cossackframework/romedb';
8
+ import { htmlBlocksChanged, type Block } from '../blocks';
9
+ import { CmsError } from '../errors';
10
+ import { MENU_LOCATION } from '../menus';
11
+ import { hasPermission, PERMISSIONS, principalId, type Principal } from '../permissions';
12
+ import { readPaged } from './budget';
13
+
14
+ export interface AreaShape {
15
+ readonly name: string;
16
+ readonly blocks: readonly Block[];
17
+ /** 0 before the area is first saved. */
18
+ readonly revision: number;
19
+ readonly updatedAt: number;
20
+ }
21
+
22
+ export interface CmsAreasOptions {
23
+ /** Validate blocks as a blocks field would, returning them normalized. */
24
+ readonly check: (blocks: unknown) => Promise<Block[]>;
25
+ readonly now?: () => number;
26
+ readonly ttlMs?: number;
27
+ /** Called after a committed change, for the host to purge the site's pages. */
28
+ readonly changed?: () => void | Promise<void>;
29
+ }
30
+
31
+ const WRITE = { kind: 'cms.areas' } as const;
32
+
33
+ export class CmsAreas {
34
+ readonly #db: RomeDB;
35
+ readonly #check: CmsAreasOptions['check'];
36
+ readonly #changed: CmsAreasOptions['changed'];
37
+ readonly #now: () => number;
38
+ readonly #ttl: number;
39
+ #cache: { at: number; value: Promise<Map<string, AreaShape>> } | undefined;
40
+
41
+ constructor(db: RomeDB, options: CmsAreasOptions) {
42
+ this.#db = db;
43
+ this.#check = options.check;
44
+ this.#changed = options.changed;
45
+ this.#now = options.now ?? Date.now;
46
+ this.#ttl = options.ttlMs ?? 30_000;
47
+ }
48
+
49
+ /** Every saved area by name. Cached per isolate; writes made here drop the cache. */
50
+ all(): Promise<Map<string, AreaShape>> {
51
+ const now = this.#now();
52
+ if (this.#cache && now - this.#cache.at <= this.#ttl) return this.#cache.value;
53
+ const value = this.#read();
54
+ this.#cache = { at: now, value };
55
+ value.catch(() => { this.#cache = undefined; });
56
+ return value;
57
+ }
58
+
59
+ /** One area; empty with revision 0 before its first save. */
60
+ async get(name: string): Promise<AreaShape> {
61
+ return (await this.all()).get(name) ?? Object.freeze({ name, blocks: Object.freeze([]), revision: 0, updatedAt: 0 });
62
+ }
63
+
64
+ /** Replace an area's blocks. Revision 0 creates it; another revision than the stored one is a conflict. */
65
+ async save(name: string, blocks: unknown, context: { principal: Principal; expectedRevision: number; known: readonly string[] }): Promise<AreaShape> {
66
+ if (!hasPermission(context.principal, PERMISSIONS.manageAppearance)) throw new CmsError(context.principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', 'Not allowed to manage widgets.');
67
+ if (typeof name !== 'string' || !MENU_LOCATION.test(name) || !context.known.includes(name)) throw new CmsError('CMS_VALIDATION', `${String(name)} is not a widget area of a theme.`);
68
+ const checked = await this.#check(blocks);
69
+ if (!hasPermission(context.principal, PERMISSIONS.unfilteredHtml) && htmlBlocksChanged(checked, (await this.get(name)).blocks)) {
70
+ throw new CmsError('CMS_FORBIDDEN', 'Only people allowed to post HTML can add or change Custom HTML blocks.');
71
+ }
72
+ const params = { $name: name, $blocks: JSON.stringify(checked), $now: this.#now(), $by: principalId(context.principal) };
73
+ const statement: Statement = context.expectedRevision === 0
74
+ ? { rql: 'INSERT INTO cms_areas (name, blocks, revision, updated_at, updated_by) VALUES ($name, $blocks, 1, $now, $by) ON CONFLICT (name) DO NOTHING', params }
75
+ : { rql: 'UPDATE cms_areas SET blocks = $blocks, revision = revision + 1, updated_at = $now, updated_by = $by WHERE name = $name AND revision = $revision', params: { ...params, $revision: context.expectedRevision } };
76
+ try {
77
+ const result = await this.#db.write([statement], WRITE);
78
+ if (result.results[0]!.affected !== 1n) throw new CmsError('CMS_CONFLICT', 'These widgets changed since you opened them. Reload and try again.');
79
+ } finally {
80
+ this.#cache = undefined;
81
+ }
82
+ await this.#changed?.();
83
+ return this.get(name);
84
+ }
85
+
86
+ /** Forget an area's saved blocks: the theme's defaults show again, and the revision is 0. */
87
+ async reset(name: string, context: { principal: Principal; known: readonly string[] }): Promise<void> {
88
+ if (!hasPermission(context.principal, PERMISSIONS.manageAppearance)) throw new CmsError(context.principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', 'Not allowed to manage widgets.');
89
+ if (typeof name !== 'string' || !MENU_LOCATION.test(name) || !context.known.includes(name)) throw new CmsError('CMS_VALIDATION', `${String(name)} is not a widget area of a theme.`);
90
+ try { await this.#db.write([{ rql: 'DELETE FROM cms_areas WHERE name = $name', params: { $name: name } }], WRITE); }
91
+ finally { this.#cache = undefined; }
92
+ await this.#changed?.();
93
+ }
94
+
95
+ async #read(): Promise<Map<string, AreaShape>> {
96
+ let rows: readonly (readonly unknown[])[] = [];
97
+ try {
98
+ // Each area holds its blocks: a few large ones may come in smaller reads.
99
+ rows = await readPaged(this.#db, (size, at) => ({ rql: 'SELECT name, blocks, revision, updated_at FROM cms_areas ORDER BY name LIMIT $limit OFFSET $offset', params: { $limit: size, $offset: at } }), 200, 0);
100
+ } catch (error) {
101
+ // Before setup, or before the host step that adds the table.
102
+ if (error instanceof ClientError && /cms_areas|no such table|not found/i.test(error.message)) return new Map();
103
+ throw error;
104
+ }
105
+ return new Map(rows.map(([name, blocks, revision, updatedAt]) => [name as string, Object.freeze({
106
+ name: name as string, blocks: Object.freeze(parseBlocks(blocks as string)), revision: Number(revision as bigint), updatedAt: Number(updatedAt as bigint),
107
+ })]));
108
+ }
109
+ }
110
+
111
+ function parseBlocks(value: string): Block[] {
112
+ try {
113
+ const blocks = JSON.parse(value) as unknown;
114
+ return Array.isArray(blocks) ? blocks as Block[] : [];
115
+ } catch { return []; }
116
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * The audit trail: one row per write of a resource (who, what, which record, which revision,
3
+ * when), written in the record's own batch by the repository. Read here for Tools → Activity and
4
+ * pruned by maintenance after a year.
5
+ */
6
+ import type { RomeDB, Statement, Value } from '@cossackframework/romedb';
7
+
8
+ export interface AuditEntry {
9
+ readonly id: string;
10
+ /** The actor as `principalId` wrote it: a user ID, `system:<reason>` or `anonymous`. */
11
+ readonly actor: string | null;
12
+ readonly action: string;
13
+ readonly resource: string;
14
+ readonly recordId: string;
15
+ readonly revision: number | null;
16
+ readonly at: number;
17
+ }
18
+
19
+ export interface AuditQuery {
20
+ readonly limit?: number;
21
+ readonly offset?: number;
22
+ readonly resource?: string;
23
+ readonly actor?: string;
24
+ readonly action?: string;
25
+ /** Rows at or after this time. */
26
+ readonly since?: number;
27
+ }
28
+
29
+ /** Rows older than this are pruned. */
30
+ export const AUDIT_RETENTION_MS = 365 * 24 * 60 * 60_000;
31
+ const WRITE = { kind: 'cms.audit', retryConflicts: 5 } as const;
32
+
33
+ /** The audit row of an unrestricted grant: who approved it, for Tools → Activity. */
34
+ export function unrestrictedGrantAudit(plugin: string, actor: string, at: number): Statement {
35
+ return {
36
+ rql: "INSERT INTO cms_audit (id, actor, action, resource, record_id, revision, at) VALUES ($id, $actor, 'grant-unrestricted', 'cms/plugins', $plugin, NULL, $at)",
37
+ params: { $id: crypto.randomUUID(), $actor: actor, $plugin: plugin, $at: at },
38
+ };
39
+ }
40
+
41
+ export class CmsAudit {
42
+ readonly #db: RomeDB;
43
+ readonly #now: () => number;
44
+
45
+ constructor(db: RomeDB, options: { now?: () => number } = {}) {
46
+ this.#db = db;
47
+ this.#now = options.now ?? Date.now;
48
+ }
49
+
50
+ /** Newest first, with the count of what matches. */
51
+ async list(query: AuditQuery = {}): Promise<{ items: AuditEntry[]; total: number }> {
52
+ const limit = Math.min(Math.max(query.limit ?? 50, 1), 200);
53
+ const offset = Math.min(Math.max(query.offset ?? 0, 0), 100_000);
54
+ const conditions: string[] = [];
55
+ const params: { [name: string]: Value } = {};
56
+ if (query.resource) { conditions.push('resource = $resource'); params.$resource = query.resource; }
57
+ if (query.actor) { conditions.push('actor = $actor'); params.$actor = query.actor; }
58
+ if (query.action) { conditions.push('action = $action'); params.$action = query.action; }
59
+ if (query.since !== undefined) { conditions.push('at >= $since'); params.$since = query.since; }
60
+ const where = conditions.length ? ` WHERE ${conditions.join(' AND ')}` : '';
61
+ const result = await this.#db.read([
62
+ { rql: `SELECT id, actor, action, resource, record_id, revision, at FROM cms_audit${where} ORDER BY at DESC, id DESC LIMIT $limit OFFSET $offset`, params: { ...params, $limit: limit, $offset: offset } },
63
+ { rql: `SELECT count(*) FROM cms_audit${where}`, params },
64
+ ]);
65
+ return {
66
+ items: result.results[0]!.rows.map(row => ({ id: row[0] as string, actor: (row[1] as string | null) ?? null, action: row[2] as string, resource: row[3] as string, recordId: row[4] as string,
67
+ revision: row[5] === null ? null : Number(row[5] as bigint), at: Number(row[6] as bigint) })),
68
+ total: Number(result.results[1]!.rows[0]![0] as bigint),
69
+ };
70
+ }
71
+
72
+ /** The distinct actions and resources seen lately, for the filters. */
73
+ async facets(): Promise<{ actions: string[]; resources: string[] }> {
74
+ const result = await this.#db.read([
75
+ { rql: 'SELECT DISTINCT action FROM cms_audit ORDER BY action LIMIT 50' },
76
+ { rql: 'SELECT DISTINCT resource FROM cms_audit ORDER BY resource LIMIT 200' },
77
+ ]);
78
+ return { actions: result.results[0]!.rows.map(row => row[0] as string), resources: result.results[1]!.rows.map(row => row[0] as string) };
79
+ }
80
+
81
+ /** Write one row for something that is not a resource write, such as an account recovery. */
82
+ async record(entry: { actor: string; action: string; resource: string; recordId: string }): Promise<void> {
83
+ await this.#db.write([{ rql: 'INSERT INTO cms_audit (id, actor, action, resource, record_id, revision, at) VALUES ($id, $actor, $action, $resource, $record, NULL, $at)',
84
+ params: { $id: crypto.randomUUID(), $actor: entry.actor, $action: entry.action, $resource: entry.resource, $record: entry.recordId, $at: this.#now() } }], WRITE);
85
+ }
86
+
87
+ /** Drop rows older than the retention, a thousand at a time. */
88
+ async prune(olderThanMs = AUDIT_RETENTION_MS): Promise<void> {
89
+ const before = this.#now() - olderThanMs;
90
+ const old = await this.#db.read([{ rql: 'SELECT 1 FROM cms_audit WHERE at < $before LIMIT 1', params: { $before: before } }]);
91
+ if (!old.results[0]!.rows.length) return;
92
+ await this.#db.write([{ rql: 'DELETE FROM cms_audit WHERE id IN (SELECT id FROM cms_audit WHERE at < $before LIMIT 1000)', params: { $before: before } }], WRITE);
93
+ }
94
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Auth integration: `@cossackframework/auth` primitives backed by CMS users and RomeDB
3
+ * auth sessions. The request user is a CMS principal resolved from current storage.
4
+ */
5
+ import { createAuth, createSessionManager, type AuthKit, type AuthRealtimeProvider, type AuthSessionManager } from '@cossackframework/auth';
6
+ import type { Context } from 'hono';
7
+ import { getCookie } from 'hono/cookie';
8
+ import { ANONYMOUS, type Principal } from '../permissions';
9
+ import type { CmsHost } from './host';
10
+ import type { CmsUser } from './users';
11
+
12
+ /** The user placed on the request context by the auth middleware. */
13
+ export interface CmsRequestUser extends CmsUser {
14
+ readonly principal: Principal;
15
+ }
16
+
17
+ export interface CmsAuth {
18
+ readonly sessions: AuthSessionManager;
19
+ /** Realtime descriptor provider: a stable session reference plus a token fingerprint. */
20
+ readonly realtime: AuthRealtimeProvider;
21
+ readonly auth: AuthKit<CmsRequestUser>;
22
+ readonly cookieName: string;
23
+ /** Sign in with email and password; returns the cookie headers to apply, or null. */
24
+ signIn(email: string, password: string, c: Context): Promise<{ user: CmsRequestUser; headers: Headers } | null>;
25
+ signOut(c: Context): Promise<Headers>;
26
+ /** The principal of the current request: the signed-in user, or anonymous. */
27
+ principal(c: Context): Principal;
28
+ }
29
+
30
+ export interface CmsAuthOptions {
31
+ /** Session lifetime in seconds. Default 7 days. */
32
+ ttlSeconds?: number;
33
+ cookieName?: string;
34
+ secure?: boolean;
35
+ }
36
+
37
+ const sha256 = async (text: string) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))]
38
+ .map(byte => byte.toString(16).padStart(2, '0')).join('');
39
+
40
+ export function createCmsAuth(cms: CmsHost, options: CmsAuthOptions = {}): CmsAuth {
41
+ const cookieName = options.cookieName ?? 'cms_session';
42
+ const sessions = createSessionManager({
43
+ store: cms.authSessions,
44
+ ttlSeconds: options.ttlSeconds ?? 7 * 24 * 60 * 60,
45
+ cookie: { name: cookieName, ...(options.secure === undefined ? {} : { secure: options.secure }) },
46
+ now: () => cms.now(),
47
+ });
48
+ const resolve = (userId: string): Promise<CmsRequestUser | null> => cms.users.resolve(userId);
49
+ const realtime: AuthRealtimeProvider = {
50
+ key: 'cossack.session',
51
+ // The public reference survives rotation; the fingerprint does not.
52
+ capture: async sessionId => ({ reference: await cms.authSessions.publicReference(sessionId), fingerprint: await sha256(sessionId) }),
53
+ validate: async data => {
54
+ const descriptor = data as { reference?: unknown; fingerprint?: unknown };
55
+ if (typeof descriptor?.reference !== 'string' || typeof descriptor.fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(descriptor.fingerprint)) return null;
56
+ const row = await cms.authSessions.findByReference(descriptor.reference);
57
+ if (!row || row.expiresAt <= cms.now() || await sha256(row.id) !== descriptor.fingerprint) return null;
58
+ return row.userId;
59
+ },
60
+ };
61
+ const auth = createAuth<CmsRequestUser>({
62
+ extractSessionId: c => getCookie(c, cookieName),
63
+ validateSessionId: async (id, c) => (await sessions.validate(id, c))?.userId ?? null,
64
+ resolveUserById: id => resolve(id),
65
+ createSession: async (user, c) => ({ headers: (await sessions.create(user.id, c)).headers }),
66
+ realtime,
67
+ });
68
+ return {
69
+ sessions,
70
+ realtime,
71
+ auth,
72
+ cookieName,
73
+ async signIn(email, password, c) {
74
+ const verified = await cms.accounts.verifier.verify(email, password);
75
+ if (!verified || verified.status !== 'active') return null;
76
+ // An account signs in where it is a member.
77
+ const user = await resolve(verified.id);
78
+ if (!user) return null;
79
+ return { user, headers: (await sessions.create(user.id, c)).headers };
80
+ },
81
+ async signOut(c) {
82
+ const id = getCookie(c, cookieName);
83
+ return id ? sessions.revoke(id, c) : sessions.expiredCookie();
84
+ },
85
+ principal(c) {
86
+ return (c.get('user') as CmsRequestUser | undefined)?.principal ?? ANONYMOUS;
87
+ },
88
+ };
89
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Automations run: the host turns its outbox events (entries, forms, payments) into variables
3
+ * and asks this service to run the active automations that match. An email goes out as the
4
+ * site. A failure is kept on the automation as its last error; one that can pass on another
5
+ * try is thrown, so the outbox retries the delivery, and the automations that already sent for
6
+ * it are skipped then. An automation emails what its event carries, so saving or switching one
7
+ * on needs read access to that: the entries of its collection, or form submissions. It runs as
8
+ * the user who did: with their permissions at the time it runs, and an entry without the fields
9
+ * they may not read.
10
+ */
11
+ import type { RomeDB } from '@cossackframework/romedb';
12
+ import type { BindingScopes } from '../bindings';
13
+ import { automationMatches, automationProblems, renderAutomationTemplate, type Automation, type AutomationAction, type AutomationConditions, type AutomationEvent, type AutomationInput } from '../automations';
14
+ import { CmsError } from '../errors';
15
+ import { hasPermission, PERMISSIONS, principalId, systemPrincipal, type Principal } from '../permissions';
16
+ import type { CmsMailer } from './mail';
17
+ import { randomToken } from './tokens';
18
+ import { readPaged } from './budget';
19
+
20
+ const WRITE = { kind: 'cms.automations', retryConflicts: 5 } as const;
21
+ const COLUMNS = 'id, name, event, conditions, action, active, runs, last_run_at, last_error, created_at, updated_at, author';
22
+
23
+ export interface AutomationsOptions {
24
+ readonly mail?: CmsMailer | null;
25
+ readonly mailFrom?: string;
26
+ readonly now?: () => number;
27
+ readonly changed?: () => void | Promise<void>;
28
+ /** The principal of an automation's author as of now, or null when they can no longer act (deleted, disabled). */
29
+ readonly principal?: (userId: string) => Promise<Principal | null>;
30
+ /** An entry as the principal may read it: without the fields they may not. */
31
+ readonly redact?: (collection: string, record: Record<string, unknown>, principal: Principal) => Record<string, unknown>;
32
+ }
33
+
34
+ export class CmsAutomations {
35
+ readonly #db: RomeDB;
36
+ readonly #options: AutomationsOptions;
37
+ readonly #now: () => number;
38
+
39
+ constructor(db: RomeDB, options: AutomationsOptions = {}) {
40
+ this.#db = db;
41
+ this.#options = options;
42
+ this.#now = options.now ?? Date.now;
43
+ }
44
+
45
+ async list(): Promise<Automation[]> {
46
+ // Conditions and actions are JSON: many automations may come in smaller reads.
47
+ const rows = await readPaged(this.#db, (size, at) => ({ rql: `SELECT ${COLUMNS} FROM cms_automations ORDER BY created_at, id LIMIT $limit OFFSET $offset`, params: { $limit: size, $offset: at } }), 500, 0);
48
+ return rows.map(rowOf);
49
+ }
50
+
51
+ async get(id: string): Promise<Automation | null> {
52
+ if (!/^[A-Za-z0-9_-]{1,40}$/.test(id)) return null;
53
+ const result = await this.#db.read([{ rql: `SELECT ${COLUMNS} FROM cms_automations WHERE id = $id`, params: { $id: id } }]);
54
+ const row = result.results[0]!.rows[0];
55
+ return row ? rowOf(row) : null;
56
+ }
57
+
58
+ /** Create or change an automation; problems are refused as `CMS_VALIDATION`, data the principal may not read as `CMS_FORBIDDEN`. */
59
+ async save(input: AutomationInput, options: { id?: string; principal: Principal }): Promise<Automation> {
60
+ const problems = automationProblems(input);
61
+ if (problems.length) throw new CmsError('CMS_VALIDATION', problems.join(' '));
62
+ assertReads(options.principal, input.event, input.conditions?.collection);
63
+ const now = this.#now();
64
+ const conditions: AutomationConditions = { ...(input.conditions?.collection ? { collection: input.conditions.collection } : {}), ...(input.conditions?.form ? { form: input.conditions.form } : {}) };
65
+ const action: AutomationAction = { kind: 'email', to: input.action.to.split(',').map(part => part.trim()).filter(Boolean).join(', '), subject: input.action.subject.trim(), text: input.action.text };
66
+ const active = input.active !== false;
67
+ if (options.id) {
68
+ const current = await this.get(options.id);
69
+ if (!current) throw new CmsError('CMS_NOT_FOUND', 'Automation not found.');
70
+ await this.#db.write([{ rql: 'UPDATE cms_automations SET name = $name, event = $event, conditions = $conditions, action = $action, active = $active, updated_at = $now, author = $author WHERE id = $id',
71
+ params: { $id: options.id, $name: input.name.trim(), $event: input.event, $conditions: JSON.stringify(conditions), $action: JSON.stringify(action), $active: active ? 1 : 0, $now: now, $author: authorOf(options.principal) } }], WRITE);
72
+ } else {
73
+ options = { ...options, id: randomToken(12) };
74
+ await this.#db.write([{ rql: `INSERT INTO cms_automations (${COLUMNS}) VALUES ($id, $name, $event, $conditions, $action, $active, 0, NULL, '', $now, $now, $author)`,
75
+ params: { $id: options.id!, $name: input.name.trim(), $event: input.event, $conditions: JSON.stringify(conditions), $action: JSON.stringify(action), $active: active ? 1 : 0, $now: now, $author: authorOf(options.principal) } }], WRITE);
76
+ }
77
+ await this.#options.changed?.();
78
+ return (await this.get(options.id!))!;
79
+ }
80
+
81
+ async setActive(id: string, active: boolean, principal: Principal): Promise<boolean> {
82
+ if (active) {
83
+ const current = await this.get(id);
84
+ if (current) assertReads(principal, current.event, current.conditions?.collection);
85
+ }
86
+ // Whoever switches one on takes it over: it runs as them from then on.
87
+ const result = await this.#db.write([active
88
+ ? { rql: 'UPDATE cms_automations SET active = 1, updated_at = $now, author = $author WHERE id = $id', params: { $id: id, $now: this.#now(), $author: authorOf(principal) } }
89
+ : { rql: 'UPDATE cms_automations SET active = 0, updated_at = $now WHERE id = $id', params: { $id: id, $now: this.#now() } }], WRITE);
90
+ return result.results[0]!.affected === 1n;
91
+ }
92
+
93
+ async delete(id: string): Promise<void> {
94
+ await this.#db.write([{ rql: 'DELETE FROM cms_automations WHERE id = $id', params: { $id: id } }], WRITE);
95
+ await this.#options.changed?.();
96
+ }
97
+
98
+ /**
99
+ * Run every active automation of the event whose conditions hold. Each failure is recorded on
100
+ * its automation; the first error is thrown after the rest ran, so the outbox retries the
101
+ * delivery (an email sent before a failure is sent again then: keep actions idempotent at the receiver).
102
+ */
103
+ async run(event: AutomationEvent, vars: Record<string, unknown>, scopes: Omit<BindingScopes, 'entry'> = {}, delivery?: string): Promise<{ ran: string[]; failed: string[] }> {
104
+ const ran: string[] = [];
105
+ const failed: string[] = [];
106
+ let first: unknown;
107
+ const matching = (await this.list()).filter(entry => entry.active && automationMatches(entry, event, vars));
108
+ // On a retry of the same delivery, the automations that sent already are done.
109
+ const done = delivery && matching.length ? await this.#done(matching.map(entry => doneKey(entry.id, delivery))) : new Set<string>();
110
+ for (const automation of matching) {
111
+ const key = delivery ? doneKey(automation.id, delivery) : null;
112
+ if (key && done.has(key)) continue;
113
+ try {
114
+ await this.#perform(automation, await this.#asAuthor(automation, event, vars), scopes);
115
+ await this.#db.write([
116
+ { rql: "UPDATE cms_automations SET runs = runs + 1, last_run_at = $now, last_error = '' WHERE id = $id", params: { $id: automation.id, $now: this.#now() } },
117
+ ...(key ? [{ rql: "INSERT INTO cms_cache (key, value, expires_at) VALUES ($key, '1', $until) ON CONFLICT (key) DO NOTHING", params: { $key: key, $until: this.#now() + DONE_MS } }] : []),
118
+ ], WRITE);
119
+ ran.push(automation.id);
120
+ } catch (error) {
121
+ failed.push(automation.id);
122
+ // Nothing to send to, or no sender: another try fails the same way, so it is only recorded.
123
+ if (!(error instanceof AutomationSkipped)) first ??= error;
124
+ await this.#db.write([{ rql: 'UPDATE cms_automations SET last_run_at = $now, last_error = $error WHERE id = $id', params: { $id: automation.id, $now: this.#now(), $error: String((error as Error)?.message ?? error).slice(0, 500) } }], WRITE).catch(() => undefined);
125
+ }
126
+ }
127
+ if (first !== undefined) throw first;
128
+ return { ran, failed };
129
+ }
130
+
131
+ async #done(keys: readonly string[]): Promise<Set<string>> {
132
+ const result = await this.#db.read([{ rql: `SELECT key FROM cms_cache WHERE key IN (${keys.map((_, index) => `$k${index}`).join(', ')})`, params: Object.fromEntries(keys.map((key, index) => [`$k${index}`, key])) }]);
133
+ return new Set(result.results[0]!.rows.map(row => row[0] as string));
134
+ }
135
+
136
+ /**
137
+ * The event's variables as the automation's author may read them: refused when they can no
138
+ * longer act or read what the event carries, and an entry without the fields they may not read.
139
+ */
140
+ async #asAuthor(automation: Automation, event: AutomationEvent, vars: Record<string, unknown>): Promise<Record<string, unknown>> {
141
+ if (!this.#options.principal) return vars;
142
+ const author = automation.author;
143
+ const principal = !author ? null : author.startsWith('system:') ? systemPrincipal(author.slice('system:'.length)) : await this.#options.principal(author);
144
+ if (!principal) throw new AutomationSkipped('Its author can no longer run it: switch it on again to run it as you.');
145
+ try { assertReads(principal, event, automation.conditions?.collection); }
146
+ catch (error) { throw new AutomationSkipped((error as Error).message); }
147
+ const { record, collection } = vars;
148
+ if (!record || typeof record !== 'object' || typeof collection !== 'string' || !this.#options.redact) return vars;
149
+ return { ...vars, record: this.#options.redact(collection, record as Record<string, unknown>, principal) };
150
+ }
151
+
152
+ async #perform(automation: Automation, vars: Record<string, unknown>, scopes: Omit<BindingScopes, 'entry'>): Promise<void> {
153
+ const action = automation.action;
154
+ if (!this.#options.mail) throw new AutomationSkipped('No email sender is configured.');
155
+ const recipients = renderAutomationTemplate(action.to, vars, scopes).split(',').map(part => part.trim()).filter(part => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(part));
156
+ if (!recipients.length) throw new AutomationSkipped('No recipient: the address was empty.');
157
+ for (const to of recipients) await this.#options.mail.send({ kind: 'automation', to, from: this.#options.mailFrom ?? 'no-reply@example.com', subject: renderAutomationTemplate(action.subject, vars, scopes).slice(0, 200), text: renderAutomationTemplate(action.text, vars, scopes) });
158
+ }
159
+ }
160
+
161
+ /** Automations that sent for a delivery are remembered this long: past the outbox's retries. */
162
+ const DONE_MS = 8 * 24 * 60 * 60 * 1000;
163
+
164
+ function doneKey(id: string, delivery: string): string {
165
+ return `automation:${id}:${delivery}`.slice(0, 200);
166
+ }
167
+
168
+ /** Who an automation runs as: a user's ID, or `system:<reason>` for host work (setup, imports, tests). */
169
+ function authorOf(principal: Principal): string | null {
170
+ return principal.kind === 'anonymous' ? null : principalId(principal);
171
+ }
172
+
173
+ /** A failure another try would repeat: recorded on the automation, not retried. */
174
+ class AutomationSkipped extends Error {}
175
+
176
+ /** Whether the principal may read what an automation of this event sends: entries of the collection (all collections without one), or form submissions and payments. */
177
+ function assertReads(principal: Principal, event: AutomationEvent, collection: string | undefined): void {
178
+ const permission = event === 'form.submitted' ? PERMISSIONS.manageSubmissions
179
+ : event === 'payment.completed' ? PERMISSIONS.manageSettings
180
+ : collection ? `cms/${collection}:read` : 'cms/*';
181
+ if (!hasPermission(principal, permission)) throw new CmsError('CMS_FORBIDDEN', `This automation sends what you may not read (${permission}).`);
182
+ }
183
+
184
+ function rowOf(row: readonly unknown[]): Automation {
185
+ return Object.freeze({
186
+ id: row[0] as string, name: row[1] as string, event: row[2] as AutomationEvent, conditions: JSON.parse(row[3] as string) as AutomationConditions, action: JSON.parse(row[4] as string) as AutomationAction,
187
+ active: Number(row[5] as bigint) === 1, runs: Number(row[6] as bigint), lastRunAt: row[7] === null ? null : Number(row[7] as bigint), lastError: (row[8] as string) ?? '',
188
+ createdAt: Number(row[9] as bigint), updatedAt: Number(row[10] as bigint), author: (row[11] as string | null) ?? null,
189
+ });
190
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Autosaves: the editor's unsaved form values, one row per user and entry, so a closed tab or
3
+ * a crash loses at most a few seconds of work. `new` stands for an entry not saved yet.
4
+ */
5
+ import type { RomeDB } from '@cossackframework/romedb';
6
+ import { CmsError } from '../errors';
7
+ import { checkDraftSize, type SharedFieldsOf } from './drafts';
8
+
9
+ const WRITE = { kind: 'cms.autosaves', retryConflicts: 5 } as const;
10
+ const KEY = /^[A-Za-z0-9_-]{1,80}$/;
11
+
12
+ export interface Autosave {
13
+ readonly data: unknown;
14
+ readonly at: number;
15
+ }
16
+
17
+ export class CmsAutosaves {
18
+ readonly #db: RomeDB;
19
+ readonly #now: () => number;
20
+ readonly #shared: SharedFieldsOf;
21
+
22
+ constructor(db: RomeDB, options: { now?: () => number; sharedFields?: SharedFieldsOf } = {}) {
23
+ this.#db = db;
24
+ this.#now = options.now ?? Date.now;
25
+ this.#shared = options.sharedFields ?? (() => []);
26
+ }
27
+
28
+ /** Store the values, replacing the user's previous autosave of the entry, capped as a draft is. */
29
+ async save(resource: string, recordId: string, userId: string, data: unknown): Promise<number> {
30
+ check(recordId, userId);
31
+ const json = JSON.stringify(data ?? null);
32
+ await checkDraftSize(this.#db, json, 'autosave', this.#shared(resource));
33
+ const at = this.#now();
34
+ await this.#db.write([{
35
+ rql: `INSERT INTO cms_autosaves (id, resource, record_id, user_id, data, at) VALUES ($id, $resource, $record, $user, $data, $at)
36
+ ON CONFLICT (id) DO UPDATE SET data = excluded.data, at = excluded.at`,
37
+ params: { $id: key(resource, recordId, userId), $resource: resource, $record: recordId, $user: userId, $data: json, $at: at },
38
+ }], WRITE);
39
+ return at;
40
+ }
41
+
42
+ async get(resource: string, recordId: string, userId: string): Promise<Autosave | null> {
43
+ check(recordId, userId);
44
+ const result = await this.#db.read([{ rql: 'SELECT data, at FROM cms_autosaves WHERE id = $id', params: { $id: key(resource, recordId, userId) } }]);
45
+ const row = result.results[0]!.rows[0];
46
+ if (!row) return null;
47
+ try { return { data: JSON.parse(row[0] as string), at: Number(row[1] as bigint) }; } catch { return null; }
48
+ }
49
+
50
+ async discard(resource: string, recordId: string, userId: string): Promise<void> {
51
+ check(recordId, userId);
52
+ await this.#db.write([{ rql: 'DELETE FROM cms_autosaves WHERE id = $id', params: { $id: key(resource, recordId, userId) } }], WRITE);
53
+ }
54
+
55
+ /** Drop autosaves older than `olderThanMs` (default 30 days). */
56
+ async purge(olderThanMs = 30 * 24 * 60 * 60 * 1000): Promise<void> {
57
+ const old = await this.#db.read([{ rql: 'SELECT 1 FROM cms_autosaves WHERE at <= $before LIMIT 1', params: { $before: this.#now() - olderThanMs } }]);
58
+ if (!old.results[0]!.rows.length) return;
59
+ await this.#db.write([{ rql: 'DELETE FROM cms_autosaves WHERE id IN (SELECT id FROM cms_autosaves WHERE at <= $before LIMIT 500)', params: { $before: this.#now() - olderThanMs } }], WRITE);
60
+ }
61
+ }
62
+
63
+ function key(resource: string, recordId: string, userId: string): string {
64
+ return `${resource}:${recordId}:${userId}`;
65
+ }
66
+
67
+ function check(recordId: string, userId: string): void {
68
+ if (!KEY.test(recordId) || !KEY.test(userId)) throw new CmsError('CMS_VALIDATION', 'Invalid entry or user.');
69
+ }