@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,1236 @@
1
+ /**
2
+ * The management API's operations: what the REST routes under `/api/cms`, the MCP tools and
3
+ * `cossack cms` do, written once. Each works on the request's site and principal and throws a
4
+ * CmsError when it refuses, so every door answers alike (`apiError` turns them into JSON).
5
+ * Content, people, settings and terms first; the appearance (menus, their locations and the
6
+ * widget areas) at the end.
7
+ */
8
+ import type { Context } from 'hono';
9
+ import {
10
+ BLOCK_ID, checkNoteRange, CmsError, CONTENT_STATUSES, findBlock, hasPermission, indexedRowField, isNetworkAdmin, MAIN_SITE, MENU_LIMITS, menuItemId, noteThreads, PERMISSIONS, recordSchema, recordTitle, richTextBlocks,
11
+ ANONYMOUS, mediaKind, mediaUrl, type MediaKind, type SnippetPart,
12
+ type Block, type FieldFilter, type MenuItem, type MenuShape, type Note, type NoteThread, type Principal, type RecordShape, type RichTextDoc, redirectProblems, type Redirect, type RedirectStatus, type FieldDeclaration, WEBHOOK_EVENTS, COMMENT_STATUSES, type Webhook, type CommentShape, type CommentStatus } from '@cossackframework/cms';
13
+ import { networkSite, type ApiToken, type CmsHost, type NetworkSite, type SiteRecord } from '@cossackframework/cms/server';
14
+ import { createApiToken, listApiTokens, manageableHere, NETWORK_ACCOUNT_LOCKED, revokeApiToken, type PublicUser } from '../auth';
15
+ import { canAssignRoles, canGrantRoles, canManageUser } from '../services/rbac';
16
+ import { changeUserPassword, createUser, deleteUser, getUser, listUsers, syncUserRoles, updateUser, type UserDetail, type UserSummary } from '../services/users';
17
+ import { apiEntries, apiPatterns, withheldFields, type ApiEntry } from './content-api';
18
+ import { entryLock } from './site';
19
+ import { routeResource } from './content';
20
+ import { siteUrl, type CmsBindings } from './index';
21
+ import { mailOrigin } from './seo';
22
+ import type { CachePurgeEvent } from '@cossackframework/cms';
23
+ import type { PurgeRecord } from '@cossackframework/cms/server';
24
+
25
+ /** Query parameters, as Hono hands them over. */
26
+ export type Query = { readonly [key: string]: string | undefined };
27
+ /** A JSON object a client sent. */
28
+ export type Body = { readonly [key: string]: unknown };
29
+
30
+ const KEY = /^[A-Za-z0-9_-]{1,80}$/;
31
+ const SITE_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
32
+
33
+ // --- Helpers ---------------------------------------------------------------
34
+
35
+ /** The signed-in principal; visitors are refused. */
36
+ export function signedIn(c: Context): Principal & { kind: 'user' } {
37
+ const principal = c.get('principal');
38
+ if (principal.kind !== 'user') throw new CmsError('CMS_UNAUTHENTICATED', 'Sign in, or send an application password.');
39
+ return principal;
40
+ }
41
+
42
+ function allowed(c: Context, permission: string, refusal: string): Principal & { kind: 'user' } {
43
+ const principal = signedIn(c);
44
+ if (!hasPermission(principal, permission)) throw new CmsError('CMS_FORBIDDEN', refusal);
45
+ return principal;
46
+ }
47
+
48
+ /** The signed-in user as the RBAC helpers see them; a token request has no `user` on the context. */
49
+ function actor(c: Context): PublicUser {
50
+ const principal = signedIn(c);
51
+ return (c.get('user') as PublicUser | undefined) ?? { id: principal.id, email: '', name: '', avatar: null, meta: null, roles: [], principal };
52
+ }
53
+
54
+ function integer(value: unknown, fallback: number, min: number, max: number): number {
55
+ const parsed = typeof value === 'number' ? value : typeof value === 'string' && value.trim() ? Number(value) : fallback;
56
+ return Number.isFinite(parsed) ? Math.min(Math.max(Math.trunc(parsed), min), max) : fallback;
57
+ }
58
+
59
+ function text(value: unknown, field: string, options: { max?: number; required?: boolean } = {}): string {
60
+ const trimmed = typeof value === 'string' ? value.trim() : '';
61
+ if (options.required !== false && !trimmed) throw new CmsError('CMS_VALIDATION', `${field} is required.`, { fields: { [field]: 'is required.' } });
62
+ if (trimmed.length > (options.max ?? 200)) throw new CmsError('CMS_VALIDATION', `${field} is too long.`, { fields: { [field]: `must be at most ${options.max ?? 200} characters.` } });
63
+ return trimmed;
64
+ }
65
+
66
+ /** The revision a write expects: the one sent, or the current one when the client did not read first. Widget areas have revision 0 before their first save. */
67
+ function expected(value: unknown, current: number, min = 1): number {
68
+ if (value === undefined || value === null || value === '') return current;
69
+ const parsed = typeof value === 'number' ? value : typeof value === 'string' ? Number(value.replaceAll('"', '')) : Number.NaN;
70
+ if (!Number.isSafeInteger(parsed) || parsed < min) throw new CmsError('CMS_VALIDATION', min === 0 ? 'rev is the revision you read, 0 before the first save.' : 'rev is the revision you read, a positive integer.');
71
+ return parsed;
72
+ }
73
+
74
+ /** A moment: an ISO 8601 string, epoch milliseconds, or `now`; undefined when absent. */
75
+ function moment(value: unknown, field: string, now: number): number | undefined {
76
+ if (value === undefined || value === null || value === '') return undefined;
77
+ if (value === 'now') return now;
78
+ const parsed = typeof value === 'number' ? value : typeof value === 'string' ? Date.parse(/[zZ]|[+-]\d\d:\d\d$/.test(value) ? value : `${value}Z`) : Number.NaN;
79
+ if (!Number.isFinite(parsed)) throw new CmsError('CMS_VALIDATION', `${field} is an ISO 8601 time, such as 2026-11-06T09:00:00Z.`, { fields: { [field]: 'must be a time.' } });
80
+ return parsed;
81
+ }
82
+
83
+ async function entryOf(cms: CmsHost, resource: string, id: string, principal: Principal): Promise<RecordShape> {
84
+ const record = KEY.test(id) ? await cms.resource(resource).get(id, { principal }) : null;
85
+ if (!record) throw new CmsError('CMS_NOT_FOUND', 'Entry not found.');
86
+ return record;
87
+ }
88
+
89
+ // --- Who am I ----------------------------------------------------------------
90
+
91
+ export interface SiteSummary {
92
+ id: string;
93
+ name: string;
94
+ host: string | null;
95
+ url: string | null;
96
+ status: string;
97
+ }
98
+
99
+ export interface Whoami {
100
+ user: { id: string; email: string; name: string; roles: { id: string; name: string }[]; permissions: string[]; networkAdmin: boolean; account: 'site' | 'network' };
101
+ site: SiteSummary;
102
+ /** The application password the request carries, or null for a session. */
103
+ token: { scope: 'read' | 'write' } | null;
104
+ network: { enabled: boolean; canAddSites: boolean; main: boolean };
105
+ }
106
+
107
+ async function siteSummary(c: Context, site: NetworkSite, cms: CmsHost): Promise<SiteSummary> {
108
+ const url = siteUrl(c.env as CmsBindings, site) ?? null;
109
+ let host = site.host;
110
+ if (!host && url) { try { host = new URL(url).host; } catch { /* APP_URL is not a URL */ } }
111
+ return { id: site.id, name: site.id === MAIN_SITE ? String(await cms.settings.get('general.siteTitle').catch(() => '')) : site.name ?? '', host, url, status: site.status };
112
+ }
113
+
114
+ export async function whoami(c: Context): Promise<Whoami> {
115
+ const principal = signedIn(c);
116
+ const cms = c.get('cms');
117
+ const site = c.get('site');
118
+ const network = c.get('network');
119
+ const member = await cms.users.get(principal.id);
120
+ const enabled = await network.enabled().catch(() => false);
121
+ return {
122
+ user: {
123
+ id: principal.id, email: member?.email ?? '', name: member?.name ?? '', roles: (member?.assignments ?? []).map(role => ({ id: role.id, name: role.name })),
124
+ permissions: [...principal.permissions], networkAdmin: isNetworkAdmin(principal), account: member?.account ?? 'network',
125
+ },
126
+ site: await siteSummary(c, site, cms),
127
+ token: c.get('cms.token') ? { scope: c.get('cms.tokenScope') ?? 'write' } : null,
128
+ network: { enabled, canAddSites: enabled && network.canAddSites, main: site.id === MAIN_SITE },
129
+ };
130
+ }
131
+
132
+ // --- Application passwords -----------------------------------------------------
133
+
134
+ export async function tokensList(c: Context): Promise<{ items: ApiToken[] }> {
135
+ return { items: await listApiTokens(signedIn(c).id) };
136
+ }
137
+
138
+ /** A new application password for the signed-in session; `token` is shown once. Passwords do not make passwords. */
139
+ export async function tokenCreate(c: Context, input: Body): Promise<{ token: string; id: string; name: string; scope: 'read' | 'write'; expiresAt: number | null }> {
140
+ const principal = signedIn(c);
141
+ if (c.get('cms.token')) throw new CmsError('CMS_FORBIDDEN', 'Create application passwords from a signed-in session.');
142
+ const name = text(input.name, 'name', { max: 80 });
143
+ const scope = input.scope === undefined ? 'write' : input.scope;
144
+ if (scope !== 'read' && scope !== 'write') throw new CmsError('CMS_VALIDATION', 'scope is read or write.');
145
+ // Days until it expires; absent or null means never.
146
+ const days = input.expiresInDays === undefined || input.expiresInDays === null ? null : integer(input.expiresInDays, 0, 1, 3650);
147
+ if (days === 0) throw new CmsError('CMS_VALIDATION', 'expiresInDays is 1 to 3650.');
148
+ const token = await createApiToken(principal.id, name, scope, days);
149
+ const record = (await listApiTokens(principal.id)).find(entry => entry.id === token.slice(4, 20));
150
+ return { token, id: token.slice(4, 20), name, scope, expiresAt: record?.expiresAt ?? null };
151
+ }
152
+
153
+ export async function tokenRevoke(c: Context, id: string): Promise<void> {
154
+ const principal = signedIn(c);
155
+ if (!(await listApiTokens(principal.id)).some(token => token.id === id)) throw new CmsError('CMS_NOT_FOUND', 'No such application password.');
156
+ await revokeApiToken(principal.id, id);
157
+ }
158
+
159
+ // --- Collections -------------------------------------------------------------
160
+
161
+ export interface CollectionSummary {
162
+ name: string; label: string; singular: string; description: string;
163
+ publishable: boolean; slug: boolean; hierarchical: boolean; managed: boolean; builtin: boolean; plugin: string | null;
164
+ path: string | null; taxonomies: string[];
165
+ fields: { name: string; kind: string; label: string; required: boolean; multiple: boolean; values?: string[] }[];
166
+ }
167
+
168
+ export function collectionsList(c: Context): { items: CollectionSummary[] } {
169
+ const cms = c.get('cms');
170
+ return { items: cms.collections().map(collection => {
171
+ const resource = cms.resourceById(`cms/${collection.name}`);
172
+ return {
173
+ name: collection.name, label: collection.label, singular: collection.singular, description: collection.description ?? '',
174
+ publishable: collection.publishable !== false, slug: collection.slug !== false, hierarchical: collection.hierarchical === true,
175
+ managed: collection.managed === true, builtin: collection.builtin === true, plugin: collection.plugin ?? null,
176
+ path: collection.path ?? null, taxonomies: [...(collection.taxonomies ?? [])],
177
+ fields: Object.entries(resource.fields).map(([name, field]) => ({
178
+ name, kind: field.kind, label: field.label ?? name, required: field.required === true, multiple: field.multiple === true,
179
+ ...(field.values ? { values: [...field.values] } : {}),
180
+ })),
181
+ };
182
+ }) };
183
+ }
184
+
185
+ export function collectionSchema(c: Context, name: string): object {
186
+ return recordSchema(routeResource(c.get('cms'), name).resource);
187
+ }
188
+
189
+ // --- Entries -----------------------------------------------------------------
190
+
191
+ export interface EntryPage {
192
+ items: ApiEntry[]; page: number; pages: number; total: number;
193
+ /** Set when the list was cut short: a filter on withheld fields reads at most 1,000 matches, and counts and pages only those. */
194
+ truncated?: true;
195
+ }
196
+
197
+ /**
198
+ * Entries of a collection. Visitors read published entries, newest first. Signed-in readers
199
+ * choose `status` (one of the statuses, or `any`), and drafts come most recently changed
200
+ * first. `term=categories:news` lists a term's entries, including those of terms below it;
201
+ * `q` searches; `locale` lists one language's entries; `filter[field]=value` matches a field;
202
+ * `format=html` adds rendered rich text and blocks beside the JSON documents.
203
+ */
204
+ export async function entriesList(c: Context, name: string, query: Query): Promise<EntryPage> {
205
+ const cms = c.get('cms');
206
+ const principal = c.get('principal');
207
+ const collection = cms.collection(name);
208
+ const repository = cms.resource(`cms/${collection.name}`);
209
+ const page = integer(query.page, 1, 1, 500);
210
+ const perPage = integer(query.perPage, 10, 1, 100);
211
+ const publishable = collection.publishable !== false;
212
+ const where: Record<string, FieldFilter> = {};
213
+ if (publishable) {
214
+ const status = principal.kind === 'user' ? query.status : undefined;
215
+ if (status === undefined || status === '') where.status = 'published';
216
+ else if (status !== 'any') {
217
+ if (!(CONTENT_STATUSES as readonly string[]).includes(status)) throw new CmsError('CMS_VALIDATION', `status is one of ${CONTENT_STATUSES.join(', ')}, or any.`);
218
+ where.status = status;
219
+ }
220
+ }
221
+ const locale = query.locale;
222
+ if (locale) {
223
+ if (!(await cms.languages()).all.includes(locale)) throw new CmsError('CMS_VALIDATION', `${locale} is not one of the site's languages.`);
224
+ where.locale = locale;
225
+ }
226
+ const [taxonomy, slug] = (query.term ?? '').split(':', 2);
227
+ if (taxonomy && slug) {
228
+ if (!(collection.taxonomies ?? []).includes(taxonomy)) throw new CmsError('CMS_VALIDATION', `${collection.label} do not use ${taxonomy}.`);
229
+ const term = await cms.taxonomies.bySlug(taxonomy, slug);
230
+ if (!term) throw new CmsError('CMS_NOT_FOUND', 'Term not found.');
231
+ where[taxonomy] = { containsAny: (await cms.taxonomies.subtree(term.id)).slice(0, 50) };
232
+ }
233
+ // `filter[price]=10`, `filter[specs.name]=Weight`: equality on a scalar field, membership on a multiple field or an indexed row field.
234
+ const fields = cms.resourceById(`cms/${collection.name}`).fields;
235
+ for (const [key, raw] of Object.entries(query)) {
236
+ const field = /^filter\[([a-zA-Z0-9_.]{1,200})\]$/.exec(key)?.[1];
237
+ if (!field || typeof raw !== 'string') continue;
238
+ const row = field.includes('.') ? indexedRowField(fields, field.split('.')) : null;
239
+ const declaration = field.includes('.') ? row : fields[field];
240
+ if (!declaration || UNQUERYABLE_FIELDS.has(field)) throw new CmsError('CMS_VALIDATION', `Cannot filter on ${field}.`);
241
+ const kind = declaration.kind;
242
+ const value = kind === 'integer' || kind === 'number' || (kind === 'datetime' && (row !== null || declaration.multiple)) ? Number(raw) : kind === 'boolean' ? raw === 'true' : raw;
243
+ where[field] = declaration.multiple || row ? { contains: value } : value;
244
+ }
245
+ const q = (query.q ?? '').trim().slice(0, 200);
246
+ const html = query.format === 'html';
247
+ if (q) {
248
+ // A locked entry the reader may not open stays out: that it matched would tell what its content says.
249
+ const signedIn = principal.kind === 'user';
250
+ const records = (await repository.search(q, { limit: perPage, where }, { principal }))
251
+ .filter(record => !entryLock(record, { editor: repository.canUpdate(record, principal), signedIn, roles: signedIn ? principal.roles : [] }));
252
+ return { items: await apiEntries(cms, collection, records, html, principal), page: 1, pages: 1, total: records.length };
253
+ }
254
+ // `sort=publishedAt:asc`, `sort=title`: a scalar field of the collection; the default follows what is listed.
255
+ const sorted = sortOf(query.sort, fields);
256
+ const order = sorted ?? (!publishable ? { field: 'title', direction: 'asc' as const }
257
+ : where.status === 'published' ? { field: 'publishedAt', direction: 'desc' as const } : { field: 'updatedAt', direction: 'desc' as const });
258
+ // Filtering or sorting on a field locked entries withhold would tell its value by what is
259
+ // listed: such a request lists only entries the reader may open.
260
+ const withheld = withheldFields(cms, collection);
261
+ const probed = [...Object.keys(where).filter(name => !BASE_FILTERS.has(name)), ...(sorted ? [sorted.field] : [])].some(name => withheld.has(name.split('.')[0]!));
262
+ const lockedOut = probed && !hasPermission(principal, `cms/${collection.name}:update`);
263
+ if (lockedOut) {
264
+ if (fields.password) where.password = { in: [null, ''] };
265
+ if (fields.membersOnly && principal.kind !== 'user') where.membersOnly = { ne: true };
266
+ }
267
+ if (lockedOut && principal.kind === 'user' && fields.membersOnly) {
268
+ // Members-only entries for other roles can't be left out by a condition, so the matches
269
+ // are read in pages and the ones the reader may open are counted and listed: page and
270
+ // total then agree with what is shown, and say nothing of the rest.
271
+ // The scan stops at LOCKED_SCAN_LIMIT matches; past it the list says it was cut short
272
+ // and its pages end where the scan did.
273
+ const open: RecordShape[] = [];
274
+ let truncated = false;
275
+ for (let offset = 0; ; offset += LOCKED_SCAN_BATCH) {
276
+ if (offset >= LOCKED_SCAN_LIMIT) { truncated = true; break; }
277
+ const batch = await repository.list({ where, order, limit: LOCKED_SCAN_BATCH, offset }, { principal });
278
+ open.push(...batch.records.filter(record => !entryLock(record, { editor: repository.canUpdate(record, principal), signedIn: true, roles: principal.roles })));
279
+ if (!batch.more && !batch.next) break;
280
+ }
281
+ const pages = Math.max(1, Math.ceil(open.length / perPage));
282
+ const shown = Math.min(page, pages);
283
+ const items = await apiEntries(cms, collection, open.slice((shown - 1) * perPage, shown * perPage), html, principal);
284
+ return { items: pickFields(items, query.fields), page: shown, pages, total: open.length, ...(truncated ? { truncated: true as const } : {}) };
285
+ }
286
+ const [list, total] = await Promise.all([
287
+ repository.list({ where, order, limit: perPage, offset: Math.min((page - 1) * perPage, 10_000) }, { principal }),
288
+ repository.count({ where }, { principal }),
289
+ ]);
290
+ const items = await apiEntries(cms, collection, list.records, html, principal);
291
+ return { items: pickFields(items, query.fields), page, pages: Math.max(1, Math.ceil(total / perPage)), total };
292
+ }
293
+
294
+ /** How many matches a filter on withheld fields reads for a signed-in reader who can't open every entry, and in what pages. */
295
+ const LOCKED_SCAN_LIMIT = 1000;
296
+ const LOCKED_SCAN_BATCH = 100;
297
+
298
+ /** Conditions the API sets itself rather than from `filter[...]`. */
299
+ const BASE_FILTERS = new Set(['status', 'locale']);
300
+
301
+ /** One result of the site's search. */
302
+ export interface SearchItem { collection: string; id: string; title: string; url: string | null; snippet: readonly SnippetPart[] }
303
+
304
+ /**
305
+ * The site's search, as its visitors get it: published entries they may read, of every
306
+ * collection (or `collection=`), best first, with snippets. `q` is what someone typed; every
307
+ * word is required, and when nothing has them all, `loose` answers with any of them.
308
+ */
309
+ export async function siteSearch(c: Context, query: Query): Promise<{ items: SearchItem[]; page: number; next: boolean; loose: boolean }> {
310
+ const cms = c.get('cms');
311
+ const q = (query.q ?? '').trim().slice(0, 200);
312
+ const page = integer(query.page, 1, 1, 1000);
313
+ const perPage = integer(query.perPage, 10, 1, 50);
314
+ const languages = await cms.languages();
315
+ if (query.locale && !languages.all.includes(query.locale)) throw new CmsError('CMS_VALIDATION', `${query.locale} is not one of the site's languages.`);
316
+ const only = query.collection ? [cms.collection(query.collection).name] : undefined;
317
+ const found = await cms.siteSearch.search(q, { page, perPage, ...(languages.multilingual ? { locale: query.locale || languages.default } : {}), ...(only ? { collections: only } : {}) });
318
+ const byCollection = new Map<string, string[]>();
319
+ for (const hit of found.hits) byCollection.set(hit.collection, [...byCollection.get(hit.collection) ?? [], hit.id]);
320
+ const shown = new Map<string, { title: string; url: string | null }>();
321
+ for (const [name, ids] of byCollection) {
322
+ const collection = cms.collections().find(entry => entry.name === name);
323
+ if (!collection) continue;
324
+ // Read as a visitor: the index is what visitors find, whoever asks.
325
+ const records = [...(await cms.resource(`cms/${name}`).getMany(ids, { principal: ANONYMOUS })).values()]
326
+ .filter(record => !entryLock(record, { editor: false, signedIn: false, roles: [] }));
327
+ const urls = await cms.entryUrls(collection, records);
328
+ for (const record of records) shown.set(`${name}:${record.id}`, { title: recordTitle(record, 'title'), url: urls.get(record.id) ?? null });
329
+ }
330
+ const items = found.hits.flatMap(hit => {
331
+ const entry = shown.get(`${hit.collection}:${hit.id}`);
332
+ return entry ? [{ collection: hit.collection, id: hit.id, ...entry, snippet: hit.snippet }] : [];
333
+ });
334
+ return { items, page, next: found.next, loose: found.loose };
335
+ }
336
+
337
+ /** `sort=field` or `sort=field:desc` on a scalar field the collection declares; null for none, an error for a field it cannot sort on. */
338
+ /**
339
+ * Fields the API never answers with, so a request may not filter or sort on them either: a
340
+ * filter that matches only when the guess is right would give a protected entry's password away.
341
+ */
342
+ const UNQUERYABLE_FIELDS = new Set(['password']);
343
+
344
+ function sortOf(sort: string | undefined, fields: { readonly [name: string]: FieldDeclaration }): { field: string; direction: 'asc' | 'desc' } | null {
345
+ if (!sort) return null;
346
+ const [field, direction = 'asc'] = sort.split(':', 2);
347
+ const declaration = field ? fields[field] : undefined;
348
+ if (!declaration || UNQUERYABLE_FIELDS.has(field!) || declaration.multiple || !['string', 'integer', 'number', 'datetime', 'boolean', 'enum'].includes(declaration.kind) || declaration.kind === 'string' && declaration.media) throw new CmsError('CMS_VALIDATION', `Cannot sort on ${String(field)}.`);
349
+ if (direction !== 'asc' && direction !== 'desc') throw new CmsError('CMS_VALIDATION', 'sort takes field or field:asc or field:desc.');
350
+ return { field: field!, direction };
351
+ }
352
+
353
+ /** `fields=title,slug,excerpt`: only those fields of each item, always with id and url. */
354
+ function pickFields<T extends { id: string; url: string | null }>(items: T[], fields: string | undefined): T[] {
355
+ if (!fields) return items;
356
+ const wanted = new Set(fields.split(',').map(name => name.trim()).filter(Boolean));
357
+ if (!wanted.size || wanted.size > 50) return items;
358
+ return items.map(item => Object.fromEntries(Object.entries(item).filter(([key]) => key === 'id' || key === 'url' || wanted.has(key))) as T);
359
+ }
360
+
361
+ export interface EntryView { item: ApiEntry; patterns: Record<string, { title: string; content: readonly unknown[] }>; translations: Record<string, { id: string; url: string | null }> }
362
+
363
+ /**
364
+ * One entry by slug (published only) or by ID (whatever the reader may see, such as their own
365
+ * drafts); `preview` reads an unpublished entry through its preview link. The answer lists the
366
+ * synced patterns its rich text uses and, on a site with several languages, its translations.
367
+ */
368
+ export async function entryRead(c: Context, name: string, key: string, options: { preview?: string; html?: boolean } = {}): Promise<EntryView | null> {
369
+ const cms = c.get('cms');
370
+ const principal = c.get('principal');
371
+ const collection = cms.collection(name);
372
+ const repository = cms.resource(`cms/${collection.name}`);
373
+ let record: RecordShape | null | undefined;
374
+ if (options.preview) {
375
+ const preview = await cms.previewByToken(options.preview);
376
+ record = preview?.resource.id === `cms/${collection.name}` && preview.record.id === key ? preview.record : null;
377
+ } else {
378
+ const bySlug = collection.slug !== false && /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(key)
379
+ ? (await repository.list({ where: { slug: key, ...(collection.publishable === false ? {} : { status: 'published' }) }, limit: 1 }, { principal })).records[0]
380
+ : undefined;
381
+ record = bySlug ?? (KEY.test(key) ? await repository.get(key, { principal }) : null);
382
+ }
383
+ if (!record) return null;
384
+ const languages = await cms.languages();
385
+ const translations = languages.multilingual ? Object.fromEntries(await Promise.all([...await cms.translations(collection, record, { principal })]
386
+ .map(async ([code, entry]) => [code, { id: entry.id, url: (await cms.entryUrls(collection, [entry])).get(entry.id) ?? null }] as const))) : {};
387
+ const item = (await apiEntries(cms, collection, [record], options.html === true, principal))[0]!;
388
+ // Patterns come from the answered item, so a locked entry's withheld content lists none.
389
+ return { item, patterns: await apiPatterns(cms, collection, [item]), translations };
390
+ }
391
+
392
+ /**
393
+ * One block of an entry by its `_id`, from any blocks field (nested blocks included) or embedded
394
+ * in a rich text field, with the field's name: `GET /api/cms/content/posts/<id>/blocks/hero`.
395
+ * Null when the entry or the block is not there.
396
+ */
397
+ export async function entryBlock(c: Context, name: string, key: string, blockId: string): Promise<{ entry: { id: string; rev: unknown }; field: string; block: Block } | null> {
398
+ if (!BLOCK_ID.test(blockId)) return null;
399
+ const view = await entryRead(c, name, key);
400
+ if (!view) return null;
401
+ const { item } = view;
402
+ for (const [field, value] of Object.entries(item)) {
403
+ if (Array.isArray(value) && value.every(entry => entry && typeof entry === 'object' && typeof (entry as Block).type === 'string' && typeof (entry as Block)._id === 'string')) {
404
+ const block = findBlock(value as Block[], blockId);
405
+ if (block) return { entry: { id: item.id, rev: item.rev }, field, block };
406
+ } else if (value && typeof value === 'object' && (value as RichTextDoc).type === 'doc' && Array.isArray((value as RichTextDoc).content)) {
407
+ const block = richTextBlocks(value as RichTextDoc).find(entry => entry._id === blockId);
408
+ if (block) return { entry: { id: item.id, rev: item.rev }, field, block: { _id: block._id, type: block.type, data: block.data, ...(block.style ? { style: block.style } : {}) } };
409
+ }
410
+ }
411
+ return null;
412
+ }
413
+
414
+ export async function entryCreate(c: Context, name: string, fields: Body): Promise<{ item: ApiEntry }> {
415
+ const cms = c.get('cms');
416
+ const collection = cms.collection(name);
417
+ const record = await cms.resource(`cms/${collection.name}`).create(fields, { principal: signedIn(c) });
418
+ return { item: (await apiEntries(cms, collection, [record], false, signedIn(c)))[0]! };
419
+ }
420
+
421
+ /** Change an entry's fields. `rev` is the revision the client read; left out, the current one. A stale revision answers 409. */
422
+ export async function entryUpdate(c: Context, name: string, id: string, fields: Body, rev: unknown): Promise<{ item: ApiEntry }> {
423
+ const cms = c.get('cms');
424
+ const principal = signedIn(c);
425
+ const collection = cms.collection(name);
426
+ const resource = `cms/${collection.name}`;
427
+ const current = await entryOf(cms, resource, id, principal);
428
+ const record = await cms.resource(resource).update(id, fields, { principal, expectedRevision: expected(rev, current.rev) });
429
+ return { item: (await apiEntries(cms, collection, [record], false, principal))[0]! };
430
+ }
431
+
432
+ export async function entryDelete(c: Context, name: string, id: string, rev: unknown): Promise<void> {
433
+ const cms = c.get('cms');
434
+ const principal = signedIn(c);
435
+ const collection = cms.collection(name);
436
+ const current = await entryOf(cms, `cms/${collection.name}`, id, principal);
437
+ await cms.resource(`cms/${collection.name}`).delete(id, { principal, expectedRevision: expected(rev, current.rev) });
438
+ }
439
+
440
+ /**
441
+ * Publish an entry now, or schedule it: `at` in the future makes it `scheduled` until then.
442
+ * An entry published before keeps its publication time unless `at` is given. With "Open notes
443
+ * hold publishing" on, an entry that is not live yet needs its notes resolved first.
444
+ */
445
+ export async function entryPublish(c: Context, name: string, id: string, input: Body): Promise<{ item: ApiEntry }> {
446
+ const cms = c.get('cms');
447
+ const principal = signedIn(c);
448
+ const collection = cms.collection(name);
449
+ if (collection.publishable === false) throw new CmsError('CMS_VALIDATION', `${collection.label} are not published.`);
450
+ const resource = `cms/${collection.name}`;
451
+ const current = await entryOf(cms, resource, id, principal);
452
+ const at = moment(input.at, 'at', cms.now());
453
+ const record = await cms.resource(resource).update(id, { status: 'published', ...(at === undefined ? {} : { publishedAt: at }) }, { principal, expectedRevision: expected(input.rev, current.rev) });
454
+ return { item: (await apiEntries(cms, collection, [record], false, principal))[0]! };
455
+ }
456
+
457
+ /** Take an entry off the site: back to a draft, keeping its publication time for a later republish. */
458
+ export async function entryUnpublish(c: Context, name: string, id: string, input: Body): Promise<{ item: ApiEntry }> {
459
+ return entrySetStatus(c, name, id, 'draft', input.rev);
460
+ }
461
+
462
+ /** Move an entry between statuses: `draft`, `pending` (for review), `published`, `trash`. */
463
+ export async function entrySetStatus(c: Context, name: string, id: string, status: string, rev: unknown): Promise<{ item: ApiEntry }> {
464
+ const cms = c.get('cms');
465
+ const principal = signedIn(c);
466
+ const collection = cms.collection(name);
467
+ if (collection.publishable === false) throw new CmsError('CMS_VALIDATION', `${collection.label} have no status.`);
468
+ if (!(CONTENT_STATUSES as readonly string[]).includes(status) || status === 'scheduled') throw new CmsError('CMS_VALIDATION', 'status is draft, pending, published or trash; publish with a future time to schedule.');
469
+ const resource = `cms/${collection.name}`;
470
+ const current = await entryOf(cms, resource, id, principal);
471
+ const record = await cms.resource(resource).update(id, { status }, { principal, expectedRevision: expected(rev, current.rev) });
472
+ return { item: (await apiEntries(cms, collection, [record], false, principal))[0]! };
473
+ }
474
+
475
+ export interface RevisionSummary { revision: number; at: number; actor: string | null; title: string; status: string | null }
476
+
477
+ export async function entryRevisions(c: Context, name: string, id: string, query: Query): Promise<{ current: number; items: RevisionSummary[] }> {
478
+ const cms = c.get('cms');
479
+ const principal = c.get('principal');
480
+ const collection = cms.collection(name);
481
+ const resource = `cms/${collection.name}`;
482
+ const current = await entryOf(cms, resource, id, principal);
483
+ const titleField = cms.resourceById(resource).titleField;
484
+ const revisions = await cms.resource(resource).revisions(id, { principal }, { limit: integer(query.limit, 20, 1, 100) });
485
+ return { current: current.rev, items: revisions.map(revision => ({
486
+ revision: revision.revision, at: revision.at, actor: revision.actor, title: recordTitle(revision.data, titleField), status: typeof revision.data.status === 'string' ? revision.data.status : null,
487
+ })) };
488
+ }
489
+
490
+ /** The content of one revision, for comparing before a restore. */
491
+ export async function entryRevision(c: Context, name: string, id: string, revision: number): Promise<{ revision: number; at: number; actor: string | null; data: RecordShape }> {
492
+ const cms = c.get('cms');
493
+ const principal = c.get('principal');
494
+ const collection = cms.collection(name);
495
+ await entryOf(cms, `cms/${collection.name}`, id, principal);
496
+ const found = Number.isSafeInteger(revision) && revision >= 1 ? await cms.resource(`cms/${collection.name}`).revision(id, revision, { principal }) : null;
497
+ if (!found) throw new CmsError('CMS_NOT_FOUND', 'Revision not found.');
498
+ return found;
499
+ }
500
+
501
+ /** Restore a revision's fields as a new revision; where and whether the entry is published stays as it is. */
502
+ export async function entryRestore(c: Context, name: string, id: string, revision: number, rev: unknown): Promise<{ item: ApiEntry }> {
503
+ const cms = c.get('cms');
504
+ const principal = signedIn(c);
505
+ const collection = cms.collection(name);
506
+ const resource = `cms/${collection.name}`;
507
+ const current = await entryOf(cms, resource, id, principal);
508
+ if (!Number.isSafeInteger(revision) || revision < 1) throw new CmsError('CMS_VALIDATION', 'revision is a positive integer.');
509
+ const record = await cms.resource(resource).restore(id, revision, { principal, expectedRevision: expected(rev, current.rev) });
510
+ return { item: (await apiEntries(cms, collection, [record], false, principal))[0]! };
511
+ }
512
+
513
+ // --- Notes -------------------------------------------------------------------
514
+
515
+ export async function notesForEntry(c: Context, name: string, id: string, status: string | undefined): Promise<{ threads: NoteThread[] }> {
516
+ const cms = c.get('cms');
517
+ const collection = cms.collection(name);
518
+ const resource = `cms/${collection.name}`;
519
+ const principal = c.get('principal');
520
+ const record = await entryOf(cms, resource, id, principal);
521
+ // Notes are the editors' discussion: publishing an entry does not publish them.
522
+ if (!cms.resource(resource).canUpdate(record, principal)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to read notes on this entry.');
523
+ if (status !== undefined && status !== '' && status !== 'open' && status !== 'resolved') throw new CmsError('CMS_VALIDATION', 'status is open or resolved.');
524
+ return { threads: noteThreads(await cms.notes.forEntry(resource, id)).filter(thread => !status || thread.root.status === status) };
525
+ }
526
+
527
+ /**
528
+ * A new thread, or a reply: `body` and, for a thread, `target` (`entry`, `field:title`,
529
+ * `block:content:<blockId>`, `text:content:<blockId>.text`) with `range` and `quote` on a
530
+ * passage; a reply names its thread as `parentId`. Whoever may edit the entry writes notes.
531
+ */
532
+ export async function noteAdd(c: Context, name: string, id: string, input: Body): Promise<{ note: Note }> {
533
+ const cms = c.get('cms');
534
+ const principal = signedIn(c);
535
+ const collection = cms.collection(name);
536
+ const resource = `cms/${collection.name}`;
537
+ const repository = cms.resource(resource);
538
+ const record = await entryOf(cms, resource, id, principal);
539
+ if (!repository.canUpdate(record, principal)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to leave notes on this entry.');
540
+ const author = await cms.users.get(principal.id).catch(() => null);
541
+ // Its webhooks and emails follow from the outbox, queued with the note.
542
+ const note = await cms.notes.create({
543
+ resource, recordId: id, userId: principal.id, body: String(input.body ?? ''),
544
+ ...(typeof input.parentId === 'string' ? { parentId: input.parentId } : { target: typeof input.target === 'string' ? input.target : 'entry', range: checkNoteRange(input.range), quote: typeof input.quote === 'string' ? input.quote : '' }),
545
+ }, { announce: { origin: mailOrigin(c), route: collection.name, collection: collection.name, title: recordTitle(record, cms.resourceById(resource).titleField), author: author?.name || author?.email || principal.id } });
546
+ cms.outboxWritten();
547
+ return { note };
548
+ }
549
+
550
+ /** The note and its entry, when the principal may edit that entry. */
551
+ async function editableNote(c: Context, noteId: string): Promise<{ note: Note; record: RecordShape; principal: Principal & { kind: 'user' } }> {
552
+ const cms = c.get('cms');
553
+ const principal = signedIn(c);
554
+ const note = KEY.test(noteId) ? await cms.notes.get(noteId) : null;
555
+ if (!note) throw new CmsError('CMS_NOT_FOUND', 'Note not found.');
556
+ const repository = cms.resource(note.resource);
557
+ const record = await repository.get(note.recordId, { principal });
558
+ if (!record) throw new CmsError('CMS_NOT_FOUND', 'Note not found.');
559
+ if (!repository.canUpdate(record, principal)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to change notes on this entry.');
560
+ return { note, record, principal };
561
+ }
562
+
563
+ /** Change a note: `body` (its author alone) and, on a thread's root, `status` (`open` or `resolved`). */
564
+ export async function noteChange(c: Context, noteId: string, input: Body): Promise<{ note: Note }> {
565
+ const cms = c.get('cms');
566
+ const found = await editableNote(c, noteId);
567
+ let { note } = found;
568
+ if (typeof input.body === 'string') {
569
+ if (note.userId !== found.principal.id) throw new CmsError('CMS_FORBIDDEN', 'Only its author changes a note.');
570
+ note = (await cms.notes.edit(note.id, input.body)) ?? note;
571
+ }
572
+ if (input.status !== undefined) {
573
+ if (note.parentId) throw new CmsError('CMS_VALIDATION', 'Resolve the thread, not a reply.');
574
+ if (input.status !== 'open' && input.status !== 'resolved') throw new CmsError('CMS_VALIDATION', 'status is open or resolved.');
575
+ const [owner, resourceName] = note.resource.split('/');
576
+ const author = await cms.users.get(found.principal.id).catch(() => null);
577
+ // Resolving queues its announcement with the write.
578
+ note = (await cms.notes.setStatus(note.id, input.status, found.principal.id, { announce: { origin: mailOrigin(c), route: owner === 'cms' ? resourceName! : `${owner}.${resourceName}`, collection: owner === 'cms' ? resourceName! : null,
579
+ title: recordTitle(found.record, cms.resourceById(note.resource).titleField), author: author?.name || author?.email || found.principal.id } })) ?? note;
580
+ if (note.status === 'resolved') cms.outboxWritten();
581
+ }
582
+ return { note };
583
+ }
584
+
585
+ /** Remove a note (its author, or a user administrator); a thread's root takes its replies. */
586
+ export async function noteRemove(c: Context, noteId: string): Promise<void> {
587
+ const found = await editableNote(c, noteId);
588
+ if (found.note.userId !== found.principal.id && !hasPermission(found.principal, PERMISSIONS.manageUsers)) throw new CmsError('CMS_FORBIDDEN', 'Only its author or an administrator removes a note.');
589
+ await c.get('cms').notes.remove(found.note.id);
590
+ }
591
+
592
+ export interface NotedEntry { collection: string; entryId: string; title: string; status: string | null; threads: NoteThread[] }
593
+
594
+ /** Entries with notes across the site (up to 100), with their threads, for whoever may edit each entry; `status` keeps open or resolved threads. */
595
+ export async function notesAcross(c: Context, status: string | undefined, limit: unknown): Promise<{ items: NotedEntry[] }> {
596
+ const cms = c.get('cms');
597
+ const principal = signedIn(c);
598
+ if (status !== undefined && status !== '' && status !== 'open' && status !== 'resolved') throw new CmsError('CMS_VALIDATION', 'status is open or resolved.');
599
+ const items: NotedEntry[] = [];
600
+ for (const entry of await cms.notes.entries(integer(limit, 50, 1, 100))) {
601
+ const [owner, resourceName] = entry.resource.split('/');
602
+ if (owner !== 'cms' || !resourceName) continue;
603
+ let record: RecordShape | null;
604
+ try { record = await cms.resource(entry.resource).get(entry.recordId, { principal }); } catch { continue; }
605
+ if (!record || !cms.resource(entry.resource).canUpdate(record, principal)) continue;
606
+ const threads = noteThreads(await cms.notes.forEntry(entry.resource, entry.recordId)).filter(thread => !status || thread.root.status === status);
607
+ if (!threads.length) continue;
608
+ items.push({ collection: resourceName, entryId: entry.recordId, title: recordTitle(record, cms.resourceById(entry.resource).titleField), status: typeof record.status === 'string' ? record.status : null, threads });
609
+ }
610
+ return { items };
611
+ }
612
+
613
+ // --- Users and roles -----------------------------------------------------------
614
+
615
+ const USERS = 'Not allowed to manage users.';
616
+
617
+ export async function usersList(c: Context, query: Query): Promise<{ items: UserSummary[]; total: number; page: number; pages: number }> {
618
+ allowed(c, PERMISSIONS.manageUsers, USERS);
619
+ const page = integer(query.page, 1, 1, 10_000);
620
+ const pageSize = integer(query.perPage, 20, 1, 100);
621
+ const result = await listUsers({ search: (query.q ?? '').trim().slice(0, 100) || undefined, roleId: query.role || undefined, page, pageSize });
622
+ return { items: result.items, total: result.total, page, pages: Math.max(1, Math.ceil(result.total / pageSize)) };
623
+ }
624
+
625
+ /** A user by ID or email. */
626
+ export async function userGet(c: Context, key: string): Promise<UserDetail> {
627
+ allowed(c, PERMISSIONS.manageUsers, USERS);
628
+ const id = key.includes('@') ? (await c.get('cms').users.findByEmail(key))?.id : KEY.test(key) ? key : undefined;
629
+ const user = id ? await getUser(id) : null;
630
+ if (!user) throw new CmsError('CMS_NOT_FOUND', 'User not found.');
631
+ return user;
632
+ }
633
+
634
+ function roleIds(value: unknown): string[] | undefined {
635
+ if (value === undefined) return undefined;
636
+ const list = Array.isArray(value) ? value : typeof value === 'string' ? value.split(',') : [];
637
+ const roles = list.map(role => String(role).trim()).filter(Boolean);
638
+ if (!roles.every(role => /^[a-z][a-z0-9_-]{0,63}$/.test(role))) throw new CmsError('CMS_VALIDATION', 'roles are role IDs, such as editor.');
639
+ return [...new Set(roles)];
640
+ }
641
+
642
+ /** Refuse roles holding permissions the caller lacks: nobody gives a stronger role than their own. */
643
+ async function grantable(c: Context, roles: readonly string[]): Promise<void> {
644
+ const found = (await Promise.all(roles.map(role => c.get('cms').users.role(role)))).filter(role => role !== null);
645
+ if (!canGrantRoles(actor(c), found)) throw new CmsError('CMS_FORBIDDEN', 'You cannot give a role with permissions you do not have.');
646
+ }
647
+
648
+ /** A new account with the chosen roles (role managers) or General settings' default role. */
649
+ export async function userCreate(c: Context, input: Body): Promise<UserDetail> {
650
+ allowed(c, PERMISSIONS.manageUsers, USERS);
651
+ const email = text(input.email, 'email', { max: 254 });
652
+ const password = typeof input.password === 'string' ? input.password : '';
653
+ if (password.length < 8) throw new CmsError('CMS_VALIDATION', 'password must be at least 8 characters.', { fields: { password: 'must be at least 8 characters.' } });
654
+ const roles = roleIds(input.roles);
655
+ if (roles && !canAssignRoles(actor(c))) throw new CmsError('CMS_FORBIDDEN', 'Only role managers choose roles; leave roles out for the default role.');
656
+ if (roles) await grantable(c, roles);
657
+ const created = await createUser({ email, password, name: text(input.name, 'name', { required: false, max: 120 }) || undefined, ...(roles ? { roleIds: roles } : {}) });
658
+ return (await getUser(created.id))!;
659
+ }
660
+
661
+ /** Change a user: `name`, `email`, `password`, `roles` (role managers) and `status` (`active` or `disabled`). */
662
+ export async function userUpdate(c: Context, id: string, input: Body): Promise<UserDetail> {
663
+ allowed(c, PERMISSIONS.manageUsers, USERS);
664
+ const target = KEY.test(id) ? await getUser(id) : null;
665
+ if (!target) throw new CmsError('CMS_NOT_FOUND', 'User not found.');
666
+ const me = actor(c);
667
+ if (!canManageUser(me, target)) throw new CmsError('CMS_FORBIDDEN', 'Only an administrator can change this account.');
668
+ const profile = {
669
+ ...(input.name !== undefined ? { name: text(input.name, 'name', { max: 120 }) } : {}),
670
+ ...(input.email !== undefined ? { email: text(input.email, 'email', { max: 254 }) } : {}),
671
+ };
672
+ // Your own email takes your password resets with it: like your password, it changes on your profile with your current password, never with an API key or open session alone.
673
+ if (profile.email !== undefined && id === me.id && profile.email.trim().toLowerCase() !== target.email.trim().toLowerCase()) {
674
+ throw new CmsError('CMS_FORBIDDEN', 'Change your own email from your user screen in the dashboard, with your current password.');
675
+ }
676
+ if (Object.keys(profile).length) await updateUser(id, profile);
677
+ if (input.password !== undefined) {
678
+ // Your own password changes on your profile, which asks for the current one: an API key or open session alone cannot take the account.
679
+ if (id === me.id) throw new CmsError('CMS_FORBIDDEN', 'Change your own password from your profile, with your current password.');
680
+ if (typeof input.password !== 'string' || input.password.length < 8) throw new CmsError('CMS_VALIDATION', 'password must be at least 8 characters.', { fields: { password: 'must be at least 8 characters.' } });
681
+ await changeUserPassword(id, input.password);
682
+ }
683
+ const roles = roleIds(input.roles);
684
+ if (roles) {
685
+ if (!canAssignRoles(me)) throw new CmsError('CMS_FORBIDDEN', 'Only role managers change roles.');
686
+ await grantable(c, roles);
687
+ await syncUserRoles(id, roles);
688
+ }
689
+ if (input.status !== undefined) {
690
+ if (input.status !== 'active' && input.status !== 'disabled') throw new CmsError('CMS_VALIDATION', 'status is active or disabled.');
691
+ if (id === me.id) throw new CmsError('CMS_VALIDATION', 'Your own account stays active.');
692
+ if (!(await manageableHere(id))) throw new CmsError('CMS_FORBIDDEN', NETWORK_ACCOUNT_LOCKED);
693
+ await c.get('cms').users.setStatus(id, input.status);
694
+ }
695
+ return (await getUser(id))!;
696
+ }
697
+
698
+ /** Delete a user, or remove them from an added site. Never the caller's own account. */
699
+ export async function userDelete(c: Context, id: string): Promise<void> {
700
+ allowed(c, PERMISSIONS.manageUsers, USERS);
701
+ const me = actor(c);
702
+ if (id === me.id) throw new CmsError('CMS_VALIDATION', 'Delete your own account from your profile, or ask another administrator.');
703
+ const target = KEY.test(id) ? await getUser(id) : null;
704
+ if (!target) throw new CmsError('CMS_NOT_FOUND', 'User not found.');
705
+ if (!canManageUser(me, target)) throw new CmsError('CMS_FORBIDDEN', 'Only an administrator can delete this account.');
706
+ await deleteUser(id);
707
+ }
708
+
709
+ export async function rolesList(c: Context): Promise<{ items: { id: string; name: string; permissions: string[]; users: number | null }[] }> {
710
+ const principal = signedIn(c);
711
+ if (!hasPermission(principal, PERMISSIONS.manageUsers) && !hasPermission(principal, PERMISSIONS.manageRoles)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to see roles.');
712
+ return { items: (await c.get('cms').users.roles({ limit: 200 })).map(role => ({ id: role.id, name: role.name, permissions: [...role.permissions], users: role.userCount ?? null })) };
713
+ }
714
+
715
+ // --- Settings ------------------------------------------------------------------
716
+
717
+ export interface SettingsGroupView { group: string; label: string; values: Record<string, unknown>; fields: { name: string; kind: string; label: string; description: string }[] }
718
+
719
+ /** The settings document the principal may edit (every portable group), or one group with its declarations. */
720
+ export async function settingsRead(c: Context, group?: string): Promise<{ document: Record<string, Record<string, unknown>> } | SettingsGroupView> {
721
+ const cms = c.get('cms');
722
+ const principal = signedIn(c);
723
+ const document = await cms.settings.snapshot({ principal });
724
+ if (group === undefined) return { document };
725
+ const declaration = cms.settings.catalog({ principal }).find(entry => entry.id === group);
726
+ if (!declaration || !document[group]) throw new CmsError('CMS_NOT_FOUND', `No settings group ${group} you may edit; the groups are ${Object.keys(document).join(', ')}.`);
727
+ return { group, label: declaration.label, values: document[group]!, fields: Object.entries(declaration.fields).map(([name, field]) => ({ name, kind: field.kind, label: field.label ?? name, description: field.description ?? '' })) };
728
+ }
729
+
730
+ /** Change some fields of one group; others keep their values. */
731
+ export async function settingsUpdate(c: Context, group: string, values: Body): Promise<SettingsGroupView> {
732
+ const cms = c.get('cms');
733
+ const principal = signedIn(c);
734
+ await cms.settings.update(group, values, { principal });
735
+ return await settingsRead(c, group) as SettingsGroupView;
736
+ }
737
+
738
+ /** Apply a settings document (`{ group: { field: value } }`), as Settings → Import does. */
739
+ export async function settingsApply(c: Context, document: unknown): Promise<{ document: Record<string, Record<string, unknown>> }> {
740
+ return { document: await c.get('cms').settings.applyDocument(document, { principal: signedIn(c) }) };
741
+ }
742
+
743
+ // --- Cache ----------------------------------------------------------------------
744
+
745
+ /**
746
+ * Purge the caches in front of the site: the tags and URLs given, or every page. The purge is
747
+ * queued like any other and the outbox run at once, so the answer carries each purger's result;
748
+ * a purger that failed retries from the outbox.
749
+ */
750
+ export async function cachePurge(c: Context, input: Body): Promise<{ event: CachePurgeEvent; purgers: string[]; results: PurgeRecord[] }> {
751
+ const cms = c.get('cms');
752
+ const principal = signedIn(c);
753
+ if (!hasPermission(principal, PERMISSIONS.manageSettings)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to purge the cache.');
754
+ const strings = (value: unknown, name: string): string[] => {
755
+ if (value === undefined || value === null) return [];
756
+ if (!Array.isArray(value) || value.some(item => typeof item !== 'string') || value.length > 500) throw new CmsError('CMS_VALIDATION', `${name} must be a list of up to 500 strings.`, { fields: { [name]: 'is invalid.' } });
757
+ return value as string[];
758
+ };
759
+ const event = await cms.purge.queue('manual', { tags: strings(input.tags, 'tags'), urls: strings(input.urls, 'urls') });
760
+ await cms.outbox.dispatch({ limit: 10 });
761
+ return { event, purgers: cms.purge.purgers.map(purger => purger.name), results: cms.purge.recent.filter(record => record.eventId === event.eventId) };
762
+ }
763
+
764
+ // --- Taxonomies and terms --------------------------------------------------------
765
+
766
+ export function taxonomiesList(c: Context): { items: { name: string; label: string; singular: string; hierarchical: boolean; path: string | null; builtin: boolean }[] } {
767
+ return { items: c.get('cms').taxonomies.declarations.map(taxonomy => ({ name: taxonomy.name, label: taxonomy.label, singular: taxonomy.singular, hierarchical: taxonomy.hierarchical, path: taxonomy.path ?? null, builtin: taxonomy.builtin === true })) };
768
+ }
769
+
770
+ /** The site's webhooks: `GET /api/cms/webhooks`. Needs the webhooks permission. */
771
+ export async function webhooksList(c: Context): Promise<{ items: Webhook[] }> {
772
+ if (!hasPermission(signedIn(c), PERMISSIONS.manageWebhooks)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to manage webhooks.');
773
+ return { items: await c.get('cms').webhooks.list() };
774
+ }
775
+
776
+ /** A new webhook: `POST /api/cms/webhooks` with `{ name, url, events, collections?, active? }`; the answer carries the signing `secret` once. */
777
+ export async function webhookCreate(c: Context, input: Body): Promise<{ item: Webhook & { readonly secret?: string } }> {
778
+ const principal = signedIn(c);
779
+ if (!hasPermission(principal, PERMISSIONS.manageWebhooks)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to manage webhooks.');
780
+ const events = Array.isArray(input.events) ? input.events.filter((event): event is string => typeof event === 'string') : [];
781
+ if (!events.length || events.some(event => !(WEBHOOK_EVENTS as readonly string[]).includes(event))) throw new CmsError('CMS_VALIDATION', `events lists one or more of ${WEBHOOK_EVENTS.join(', ')}.`);
782
+ const collections = Array.isArray(input.collections) ? input.collections.filter((name): name is string => typeof name === 'string') : [];
783
+ const item = await c.get('cms').webhooks.save({ name: text(input.name, 'name', { max: 120 }), url: text(input.url, 'url', { max: 2000 }), events, collections, active: input.active !== false }, { by: principal.kind === 'user' ? principal.id : null });
784
+ return { item };
785
+ }
786
+
787
+ export async function webhookDelete(c: Context, id: string): Promise<void> {
788
+ if (!hasPermission(signedIn(c), PERMISSIONS.manageWebhooks)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to manage webhooks.');
789
+ const cms = c.get('cms');
790
+ if (!(await cms.webhooks.get(id))) throw new CmsError('CMS_NOT_FOUND', 'Webhook not found.');
791
+ await cms.webhooks.delete(id);
792
+ }
793
+
794
+ /** The moderation queue: `GET /api/cms/comments/queue?status=pending&page=1&perPage=50`. Needs the comments permission. */
795
+ export async function commentsQueue(c: Context, query: Query): Promise<{ items: CommentShape[]; total: number; page: number; pages: number }> {
796
+ if (!hasPermission(signedIn(c), PERMISSIONS.moderateComments)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to moderate comments.');
797
+ const status = query.status ?? 'pending';
798
+ if (!(COMMENT_STATUSES as readonly string[]).includes(status)) throw new CmsError('CMS_VALIDATION', `status is one of ${COMMENT_STATUSES.join(', ')}.`);
799
+ const perPage = integer(query.perPage, 50, 1, 200);
800
+ const page = integer(query.page, 1, 1, 10_000);
801
+ const result = await c.get('cms').comments.list({ status: status as CommentStatus, limit: perPage, offset: (page - 1) * perPage, ...(typeof query.q === 'string' && query.q ? { search: query.q } : {}) });
802
+ return { ...result, page, pages: Math.max(1, Math.ceil(result.total / perPage)) };
803
+ }
804
+
805
+ /** Approve, hold, mark as spam or trash a comment: `PATCH /api/cms/comments/<id>` with `{ status }`. */
806
+ export async function commentModerate(c: Context, id: string, input: Body): Promise<{ item: CommentShape }> {
807
+ if (!hasPermission(signedIn(c), PERMISSIONS.moderateComments)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to moderate comments.');
808
+ const cms = c.get('cms');
809
+ const current = await cms.comments.get(id);
810
+ if (!current) throw new CmsError('CMS_NOT_FOUND', 'Comment not found.');
811
+ if (!(COMMENT_STATUSES as readonly string[]).includes(input.status as string)) throw new CmsError('CMS_VALIDATION', `status is one of ${COMMENT_STATUSES.join(', ')}.`);
812
+ await cms.comments.setStatus([id], input.status as CommentStatus);
813
+ return { item: (await cms.comments.get(id))! };
814
+ }
815
+
816
+ export async function commentDelete(c: Context, id: string): Promise<void> {
817
+ if (!hasPermission(signedIn(c), PERMISSIONS.moderateComments)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to moderate comments.');
818
+ const cms = c.get('cms');
819
+ if (!(await cms.comments.get(id))) throw new CmsError('CMS_NOT_FOUND', 'Comment not found.');
820
+ await cms.comments.delete([id]);
821
+ }
822
+
823
+ /** Redirects, newest first: `GET /api/cms/redirects?q=old&page=1&perPage=50`. */
824
+ export async function redirectsList(c: Context, query: Query): Promise<{ items: Redirect[]; total: number }> {
825
+ const principal = signedIn(c);
826
+ if (!hasPermission(principal, PERMISSIONS.manageRedirects)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to manage redirects.');
827
+ const perPage = integer(query.perPage, 50, 1, 200);
828
+ const page = integer(query.page, 1, 1, 10_000);
829
+ return c.get('cms').redirects.list({ ...(typeof query.q === 'string' && query.q ? { search: query.q } : {}), limit: perPage, offset: (page - 1) * perPage });
830
+ }
831
+
832
+ /** A redirect: `POST /api/cms/redirects` with `{ source, target, status?, note? }`; `source` is a path, `target` a path or URL. */
833
+ export async function redirectCreate(c: Context, input: Body): Promise<{ item: Redirect }> {
834
+ const principal = signedIn(c);
835
+ if (!hasPermission(principal, PERMISSIONS.manageRedirects)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to manage redirects.');
836
+ const problems = redirectProblems(input as never);
837
+ if (problems.length) throw new CmsError('CMS_VALIDATION', problems.join(' '));
838
+ const item = await c.get('cms').redirects.save({ source: text(input.source, 'source', { max: 500 }), target: text(input.target, 'target', { max: 2000 }),
839
+ ...(input.status !== undefined ? { status: Number(input.status) as RedirectStatus } : {}), ...(typeof input.note === 'string' ? { note: input.note.slice(0, 500) } : {}) }, { by: principal.kind === 'user' ? principal.id : null });
840
+ return { item };
841
+ }
842
+
843
+ export async function termsList(c: Context, taxonomy: string, query: Query) {
844
+ const cms = c.get('cms');
845
+ cms.taxonomies.declaration(taxonomy);
846
+ const page = integer(query.page, 1, 1, 10_000);
847
+ const perPage = integer(query.perPage, 50, 1, 200);
848
+ const { items, total } = await cms.taxonomies.list(taxonomy, { search: (query.q ?? '').trim().slice(0, 100) || undefined, limit: perPage, offset: (page - 1) * perPage });
849
+ return { items, total, page, pages: Math.max(1, Math.ceil(total / perPage)) };
850
+ }
851
+
852
+ function termInput(input: Body) {
853
+ return {
854
+ ...(input.name !== undefined ? { name: text(input.name, 'name', { max: 200 }) } : {}),
855
+ ...(input.slug !== undefined ? { slug: text(input.slug, 'slug', { required: false, max: 200 }) } : {}),
856
+ ...(input.description !== undefined ? { description: typeof input.description === 'string' ? input.description : '' } : {}),
857
+ ...(input.parent !== undefined ? { parent: typeof input.parent === 'string' && input.parent ? input.parent : null } : {}),
858
+ ...(input.meta !== undefined && input.meta && typeof input.meta === 'object' ? { meta: input.meta as { [field: string]: unknown } } : {}),
859
+ };
860
+ }
861
+
862
+ export async function termCreate(c: Context, taxonomy: string, input: Body) {
863
+ return c.get('cms').taxonomies.create(taxonomy, { ...termInput(input), name: text(input.name, 'name', { max: 200 }) }, { principal: signedIn(c) });
864
+ }
865
+
866
+ async function termIn(c: Context, taxonomy: string, id: string) {
867
+ const term = KEY.test(id) ? await c.get('cms').taxonomies.get(id) : null;
868
+ if (!term || term.taxonomy !== taxonomy) throw new CmsError('CMS_NOT_FOUND', 'Term not found.');
869
+ return term;
870
+ }
871
+
872
+ export async function termRead(c: Context, taxonomy: string, id: string) {
873
+ return termIn(c, taxonomy, id);
874
+ }
875
+
876
+ export async function termUpdate(c: Context, taxonomy: string, id: string, input: Body) {
877
+ await termIn(c, taxonomy, id);
878
+ return c.get('cms').taxonomies.update(id, termInput(input), { principal: signedIn(c) });
879
+ }
880
+
881
+ export async function termDelete(c: Context, taxonomy: string, id: string): Promise<void> {
882
+ await termIn(c, taxonomy, id);
883
+ await c.get('cms').taxonomies.delete(id, { principal: signedIn(c) });
884
+ }
885
+
886
+ // --- Media ------------------------------------------------------------------------
887
+
888
+ export interface MediaView { id: string; url: string; name: string; kind: string; title: string; alt: string; caption: string; description: string; contentType: string; size: number; width: number | null; height: number | null }
889
+
890
+ const mediaView = (file: { id: string; name: string; title: string; alt: string; caption: string; description: string; contentType: string; size: number; width: number | null; height: number | null }): MediaView => ({
891
+ id: file.id, url: mediaUrl(file), name: file.name, kind: mediaKind(file.contentType), title: file.title, alt: file.alt, caption: file.caption, description: file.description,
892
+ contentType: file.contentType, size: file.size, width: file.width, height: file.height,
893
+ });
894
+
895
+ function mediaAllowed(c: Context): Principal {
896
+ const principal = c.get('principal');
897
+ if (![PERMISSIONS.upload, PERMISSIONS.manageMedia, PERMISSIONS.manageUsers].some(permission => hasPermission(principal, permission))) {
898
+ throw new CmsError(principal.kind === 'user' ? 'CMS_FORBIDDEN' : 'CMS_UNAUTHENTICATED', 'Not allowed to see the media library.');
899
+ }
900
+ return principal;
901
+ }
902
+
903
+ /** Library files, newest first: `q` matches titles and names, `kind` (image, video, audio, document, archive) narrows them, `page` and `perPage` (40, at most 100) walk the library. */
904
+ export async function mediaList(c: Context, query: Query): Promise<{ items: MediaView[]; page: number; pages: number; total: number }> {
905
+ mediaAllowed(c);
906
+ const files = c.get('cms').files;
907
+ const perPage = integer(query.perPage, 40, 1, 100);
908
+ const page = integer(query.page, 1, 1, 10_000);
909
+ if (!files) return { items: [], page: 1, pages: 1, total: 0 };
910
+ const kind = query.kind ?? '';
911
+ const found = await files.list({ search: (query.q ?? '').slice(0, 100), limit: perPage, offset: (page - 1) * perPage, ...(['image', 'video', 'audio', 'document', 'archive'].includes(kind) ? { kind: kind as MediaKind } : {}) });
912
+ return { items: found.items.map(mediaView), page, pages: Math.max(1, Math.ceil(found.total / perPage)), total: found.total };
913
+ }
914
+
915
+ /** Change a file's title, alternative text, caption or description; the owner or a media manager may. */
916
+ export async function mediaUpdate(c: Context, id: string, input: Body): Promise<{ item: MediaView }> {
917
+ const principal = signedIn(c);
918
+ const files = c.get('cms').files;
919
+ if (!files || !KEY.test(id)) throw new CmsError('CMS_NOT_FOUND', 'No such file.');
920
+ const patch: { title?: string; alt?: string; caption?: string; description?: string } = {};
921
+ const fields: { [field: string]: string } = {};
922
+ for (const name of ['title', 'alt', 'caption', 'description'] as const) {
923
+ if (input[name] === undefined) continue;
924
+ if (typeof input[name] !== 'string') fields[name] = 'must be text.';
925
+ else patch[name] = input[name];
926
+ }
927
+ if (Object.keys(fields).length) throw new CmsError('CMS_VALIDATION', 'The file\'s details are text.', { fields });
928
+ return { item: mediaView(await files.update(id, patch, { principal })) };
929
+ }
930
+
931
+ // --- Plugins ----------------------------------------------------------------------
932
+
933
+ export interface PluginView { name: string; version: string; description: string; active: boolean; themeOnly: boolean; unrestricted: boolean; reason: string; missing: string[]; requests: string[] }
934
+
935
+ function pluginsAllowed(c: Context): Principal & { kind: 'user' } {
936
+ const principal = signedIn(c);
937
+ if (!hasPermission(principal, PERMISSIONS.managePlugins)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to manage plugins.');
938
+ return principal;
939
+ }
940
+
941
+ /** The installed plugins with what each asks for and whether it is active. */
942
+ export async function pluginsList(c: Context): Promise<{ items: PluginView[] }> {
943
+ pluginsAllowed(c);
944
+ const status = await c.get('cms').status();
945
+ return { items: status.plugins.filter(plugin => plugin.network !== 'hidden').map(plugin => ({
946
+ name: plugin.name, version: plugin.version, description: plugin.description, active: plugin.active, themeOnly: plugin.themeOnly, unrestricted: plugin.unrestricted,
947
+ reason: plugin.reason ?? '', missing: [...plugin.missing], requests: [...plugin.requests],
948
+ })) };
949
+ }
950
+
951
+ /**
952
+ * Grant a plugin everything its manifest asks for, as the Plugins screen does. Unrestricted
953
+ * access is never granted from here: it takes its own confirmation in the dashboard.
954
+ */
955
+ export async function pluginGrant(c: Context, name: string): Promise<{ item: PluginView }> {
956
+ const principal = pluginsAllowed(c);
957
+ await c.get('cms').grantPlugin(name, principal);
958
+ return { item: await pluginRead(c, name) };
959
+ }
960
+
961
+ /** Disable a plugin: its grants are removed and its code stops running. */
962
+ export async function pluginRevoke(c: Context, name: string): Promise<{ item: PluginView }> {
963
+ const principal = pluginsAllowed(c);
964
+ await c.get('cms').revokePlugin(name, principal);
965
+ return { item: await pluginRead(c, name) };
966
+ }
967
+
968
+ async function pluginRead(c: Context, name: string): Promise<PluginView> {
969
+ const item = (await pluginsList(c)).items.find(plugin => plugin.name === name);
970
+ if (!item) throw new CmsError('CMS_NOT_FOUND', `Unknown plugin ${name}.`);
971
+ return item;
972
+ }
973
+
974
+ // --- Network sites ---------------------------------------------------------------
975
+
976
+ export interface SiteView extends SiteSummary {
977
+ domains: { host: string; primary: boolean; verified: boolean }[];
978
+ createdAt: number | null;
979
+ updatedAt: number | null;
980
+ deletedAt: number | null;
981
+ }
982
+
983
+ async function networkAdmin(c: Context) {
984
+ const principal = signedIn(c);
985
+ const network = c.get('network');
986
+ if (!isNetworkAdmin(principal)) throw new CmsError('CMS_FORBIDDEN', 'Only network admins manage sites.');
987
+ if (c.get('site').id !== MAIN_SITE) throw new CmsError('CMS_FORBIDDEN', 'Manage sites on the network host (the main site).');
988
+ if (!(await network.enabled().catch(() => false))) throw new CmsError('CMS_FORBIDDEN', 'The network is off: turn it on under Settings → Network first.');
989
+ return network;
990
+ }
991
+
992
+ function siteView(c: Context, record: SiteRecord): SiteView {
993
+ const site = networkSite(record);
994
+ return {
995
+ id: record.id, name: record.name, host: site.host, url: siteUrl(c.env as CmsBindings, site) ?? null, status: record.status,
996
+ domains: record.domains.map(domain => ({ host: domain.host, primary: domain.primary, verified: domain.verifiedAt !== null })),
997
+ createdAt: record.createdAt, updatedAt: record.updatedAt, deletedAt: record.deletedAt,
998
+ };
999
+ }
1000
+
1001
+ async function mainView(c: Context): Promise<SiteView> {
1002
+ const summary = await siteSummary(c, c.get('site'), c.get('cms'));
1003
+ return { ...summary, domains: summary.host ? [{ host: summary.host, primary: true, verified: true }] : [], createdAt: null, updatedAt: null, deletedAt: null };
1004
+ }
1005
+
1006
+ /** The network's sites, the main site first: `q` searches names and addresses, `status` keeps active, archived or deleted sites. */
1007
+ export async function sitesList(c: Context, query: Query): Promise<{ items: SiteView[]; total: number; page: number; pages: number }> {
1008
+ const network = await networkAdmin(c);
1009
+ const status = query.status;
1010
+ if (status !== undefined && status !== '' && !['active', 'archived', 'deleted'].includes(status)) throw new CmsError('CMS_VALIDATION', 'status is active, archived or deleted.');
1011
+ const page = integer(query.page, 1, 1, 10_000);
1012
+ const perPage = integer(query.perPage, 50, 1, 200);
1013
+ const search = (query.q ?? '').trim().slice(0, 100);
1014
+ const { items, total } = await network.sites.list({ ...(search ? { search } : {}), ...(status ? { status: status as 'active' | 'archived' | 'deleted' } : {}), limit: perPage, offset: (page - 1) * perPage });
1015
+ const main = page === 1 && !search && (!status || status === 'active') ? [await mainView(c)] : [];
1016
+ return { items: [...main, ...items.map(record => siteView(c, record))], total: total + main.length, page, pages: Math.max(1, Math.ceil(total / perPage)) };
1017
+ }
1018
+
1019
+ export async function siteGet(c: Context, id: string): Promise<SiteView> {
1020
+ const network = await networkAdmin(c);
1021
+ if (id === MAIN_SITE) return mainView(c);
1022
+ const record = SITE_ID.test(id) ? await network.sites.get(id) : null;
1023
+ if (!record) throw new CmsError('CMS_NOT_FOUND', 'Site not found.');
1024
+ return siteView(c, record);
1025
+ }
1026
+
1027
+ /**
1028
+ * Add a site: a name, an address under the network's subdomain, its first administrator (the
1029
+ * email of a network account; the caller's when left out), a language and whether it starts
1030
+ * with starter content.
1031
+ */
1032
+ export async function siteCreate(c: Context, input: Body): Promise<SiteView> {
1033
+ const network = await networkAdmin(c);
1034
+ const principal = signedIn(c);
1035
+ if (!network.canAddSites) throw new CmsError('CMS_UNAVAILABLE', 'Sites need a place for their databases: set ROMEDB_SITES_URL and ROMEDB_SITES_TOKEN, or run on Node with a file database.');
1036
+ const name = text(input.name, 'name', { max: 120 });
1037
+ const host = text(input.host, 'host', { max: 253 }).toLowerCase();
1038
+ const email = text(input.admin, 'admin', { required: false, max: 254 });
1039
+ const admin = email ? await network.main.accounts.findByEmail(email) : await network.main.accounts.get(principal.id);
1040
+ if (!admin) throw new CmsError('CMS_VALIDATION', 'No network account has that email. Add the person under Network → Users first.', { fields: { admin: 'is not a network account.' } });
1041
+ const id = text(input.id, 'id', { required: false, max: 63 });
1042
+ const language = text(input.language, 'language', { required: false, max: 16 });
1043
+ const record = await network.createSite({ name, host, admin: admin.id, ...(id ? { id } : {}), ...(language ? { language } : {}), starter: input.starter !== false }, { principal });
1044
+ return siteView(c, record);
1045
+ }
1046
+
1047
+ /** Archive, restore (`active`) or delete a site; a deleted site can be restored for 30 days. */
1048
+ export async function siteSetStatus(c: Context, id: string, status: unknown): Promise<SiteView> {
1049
+ const network = await networkAdmin(c);
1050
+ if (status !== 'active' && status !== 'archived' && status !== 'deleted') throw new CmsError('CMS_VALIDATION', 'status is active, archived or deleted.');
1051
+ if (id === MAIN_SITE) throw new CmsError('CMS_VALIDATION', 'The main site cannot be archived or deleted.');
1052
+ if (!SITE_ID.test(id) || !(await network.sites.get(id))) throw new CmsError('CMS_NOT_FOUND', 'Site not found.');
1053
+ return siteView(c, await network.setSiteStatus(id, status, { principal: signedIn(c) }));
1054
+ }
1055
+
1056
+ // --- Appearance: menus, their locations and the widget areas ----------------------------
1057
+ // What Appearance → Menus and Appearance → Widgets do, for the appearance permission. The
1058
+ // resolved menu visitors see at a location is `GET /api/cms/menus/<location>` (content-api).
1059
+
1060
+ const APPEARANCE = 'Not allowed to manage the appearance.';
1061
+
1062
+ export interface MenuLocationView { name: string; label: string; theme: string; active: boolean; /** The menu shown there, or null. */ menu: string | null }
1063
+ export interface MenuSummaryView { id: string; name: string; /** How many items, every level counted. */ items: number; locations: string[]; updatedAt: number }
1064
+ export interface MenuView { id: string; name: string; items: readonly MenuItem[]; rev: number; locations: string[]; createdAt: number; updatedAt: number }
1065
+ export interface AreaView {
1066
+ name: string; label: string; theme: string; active: boolean;
1067
+ /** 0 while the theme's default blocks show; a save needs it. */
1068
+ rev: number;
1069
+ /** The site saved its own blocks; otherwise `blocks` are the theme's defaults. */
1070
+ saved: boolean;
1071
+ blocks: readonly Block[];
1072
+ defaults: readonly Block[];
1073
+ updatedAt: number;
1074
+ }
1075
+
1076
+ async function menuLocationNames(cms: CmsHost): Promise<string[]> {
1077
+ return (await cms.menuLocations()).map(location => location.name);
1078
+ }
1079
+
1080
+ async function menuView(cms: CmsHost, menu: MenuShape): Promise<MenuView> {
1081
+ const assigned = await cms.menus.locations();
1082
+ return { id: menu.id, name: menu.name, items: menu.items, rev: menu.revision, locations: [...assigned].filter(([, id]) => id === menu.id).map(([location]) => location), createdAt: menu.createdAt, updatedAt: menu.updatedAt };
1083
+ }
1084
+
1085
+ async function menuOf(cms: CmsHost, id: string): Promise<MenuShape> {
1086
+ const menu = await cms.menus.get(id);
1087
+ if (!menu) throw new CmsError('CMS_NOT_FOUND', 'Menu not found.');
1088
+ return menu;
1089
+ }
1090
+
1091
+ /** Items as a client sends them: a tree whose items may leave out their IDs, labels and children; the host checks the rest. */
1092
+ function menuItems(value: unknown): MenuItem[] | undefined {
1093
+ if (value === undefined) return undefined;
1094
+ if (!Array.isArray(value)) throw new CmsError('CMS_VALIDATION', 'items is a list of menu items.', { fields: { items: 'must be a list.' } });
1095
+ const fill = (list: unknown[]): MenuItem[] => list.map(item => {
1096
+ if (!item || typeof item !== 'object' || Array.isArray(item)) return item as MenuItem;
1097
+ const given = item as { [name: string]: unknown };
1098
+ return {
1099
+ ...given,
1100
+ id: typeof given.id === 'string' && given.id ? given.id : menuItemId(),
1101
+ label: typeof given.label === 'string' ? given.label : '',
1102
+ children: Array.isArray(given.children) ? fill(given.children) : given.children === undefined ? [] : given.children,
1103
+ } as MenuItem;
1104
+ });
1105
+ return fill(value);
1106
+ }
1107
+
1108
+ /** Location names a menu should show in, checked against the themes' before anything is written. */
1109
+ async function wantedLocations(cms: CmsHost, value: unknown): Promise<{ locations: string[]; known: string[] } | null> {
1110
+ if (value === undefined) return null;
1111
+ const list = Array.isArray(value) ? value : [value];
1112
+ if (!list.every(location => typeof location === 'string')) throw new CmsError('CMS_VALIDATION', 'locations is a list of menu location names.', { fields: { locations: 'must be a list of names.' } });
1113
+ const known = await menuLocationNames(cms);
1114
+ for (const location of list as string[]) if (!known.includes(location)) throw new CmsError('CMS_VALIDATION', `${location} is not a menu location of a theme; the locations are ${known.join(', ') || 'none'}.`, { fields: { locations: `${location} is not a location.` } });
1115
+ return { locations: list as string[], known };
1116
+ }
1117
+
1118
+ export interface ThemeSummaryView { name: string; label: string; description: string; version: string; active: boolean; /** Why the theme cannot be used; empty when it can. */ problems: string[] }
1119
+
1120
+ /** The themes the site may use, the active one marked. */
1121
+ export async function themesList(c: Context): Promise<{ items: ThemeSummaryView[] }> {
1122
+ allowed(c, PERMISSIONS.manageAppearance, APPEARANCE);
1123
+ const cms = c.get('cms');
1124
+ const [themes, active] = await Promise.all([cms.availableThemes(), cms.activeTheme()]);
1125
+ return { items: themes.map(theme => ({ name: theme.name, label: theme.label, description: theme.description ?? '', version: theme.version, active: theme.name === active, problems: [...theme.problems] })) };
1126
+ }
1127
+
1128
+ /** Make a theme the site's: its templates draw the site, and its patterns and field groups are stored. */
1129
+ export async function themeActivate(c: Context, name: string): Promise<{ item: ThemeSummaryView }> {
1130
+ const principal = allowed(c, PERMISSIONS.manageAppearance, APPEARANCE);
1131
+ await c.get('cms').activateTheme(name, principal);
1132
+ const item = (await themesList(c)).items.find(theme => theme.name === name);
1133
+ if (!item) throw new CmsError('CMS_NOT_FOUND', `Unknown theme ${name}.`);
1134
+ return { item };
1135
+ }
1136
+
1137
+ /** The themes' menu locations (the active theme's first) with the menu at each. */
1138
+ export async function menuLocationsList(c: Context): Promise<{ items: MenuLocationView[] }> {
1139
+ allowed(c, PERMISSIONS.manageAppearance, APPEARANCE);
1140
+ const cms = c.get('cms');
1141
+ const [locations, assigned] = await Promise.all([cms.menuLocations(), cms.menus.locations()]);
1142
+ return { items: locations.map(location => ({ ...location, menu: assigned.get(location.name) ?? null })) };
1143
+ }
1144
+
1145
+ /** Show a menu at a location (`menu` an ID), or none (`menu` null or empty). */
1146
+ export async function menuLocationAssign(c: Context, location: string, input: Body): Promise<{ item: MenuLocationView }> {
1147
+ const principal = allowed(c, PERMISSIONS.manageAppearance, APPEARANCE);
1148
+ const cms = c.get('cms');
1149
+ const menu = input.menu === undefined || input.menu === null || input.menu === '' ? null : input.menu;
1150
+ if (menu !== null && typeof menu !== 'string') throw new CmsError('CMS_VALIDATION', 'menu is a menu ID, or null for none.', { fields: { menu: 'must be a menu ID.' } });
1151
+ await cms.menus.assign(location, menu, { principal, known: await menuLocationNames(cms) });
1152
+ const item = (await menuLocationsList(c)).items.find(entry => entry.name === location);
1153
+ return { item: item ?? { name: location, label: location, theme: '', active: false, menu } };
1154
+ }
1155
+
1156
+ export async function menusList(c: Context): Promise<{ items: MenuSummaryView[] }> {
1157
+ allowed(c, PERMISSIONS.manageAppearance, APPEARANCE);
1158
+ return { items: (await c.get('cms').menus.list()).map(menu => ({ id: menu.id, name: menu.name, items: menu.items, locations: [...menu.locations], updatedAt: menu.updatedAt })) };
1159
+ }
1160
+
1161
+ export async function menuRead(c: Context, id: string): Promise<{ item: MenuView }> {
1162
+ allowed(c, PERMISSIONS.manageAppearance, APPEARANCE);
1163
+ const cms = c.get('cms');
1164
+ return { item: await menuView(cms, await menuOf(cms, id)) };
1165
+ }
1166
+
1167
+ /** A new menu from `{ name, items?, locations? }`; items may leave out their IDs. */
1168
+ export async function menuCreate(c: Context, input: Body): Promise<{ item: MenuView }> {
1169
+ const principal = allowed(c, PERMISSIONS.manageAppearance, APPEARANCE);
1170
+ const cms = c.get('cms');
1171
+ const wanted = await wantedLocations(cms, input.locations);
1172
+ const menu = await cms.menus.create({ name: text(input.name, 'name', { max: MENU_LIMITS.name }), items: menuItems(input.items) }, { principal });
1173
+ if (wanted?.locations.length) await cms.menus.place(menu.id, wanted.locations, { principal, known: wanted.known });
1174
+ return { item: await menuView(cms, menu) };
1175
+ }
1176
+
1177
+ /**
1178
+ * Rename a menu, replace its items (the whole tree) or move it to exactly the `locations`
1179
+ * given. `rev` is the revision read; a stale one answers 409. Fields left out stay.
1180
+ */
1181
+ export async function menuUpdate(c: Context, id: string, input: Body): Promise<{ item: MenuView }> {
1182
+ const principal = allowed(c, PERMISSIONS.manageAppearance, APPEARANCE);
1183
+ const cms = c.get('cms');
1184
+ let menu = await menuOf(cms, id);
1185
+ const wanted = await wantedLocations(cms, input.locations);
1186
+ if (input.name !== undefined || input.items !== undefined) {
1187
+ menu = await cms.menus.update(id, { name: input.name === undefined ? undefined : text(input.name, 'name', { max: MENU_LIMITS.name }), items: menuItems(input.items) }, { principal, expectedRevision: expected(input.rev, menu.revision) });
1188
+ }
1189
+ if (wanted) await cms.menus.place(menu.id, wanted.locations, { principal, known: wanted.known });
1190
+ return { item: await menuView(cms, menu) };
1191
+ }
1192
+
1193
+ /** Delete a menu; the locations it held show none. */
1194
+ export async function menuDelete(c: Context, id: string): Promise<void> {
1195
+ const principal = allowed(c, PERMISSIONS.manageAppearance, APPEARANCE);
1196
+ await c.get('cms').menus.delete(id, { principal });
1197
+ }
1198
+
1199
+ async function areaViews(cms: CmsHost): Promise<AreaView[]> {
1200
+ const [declared, saved] = await Promise.all([cms.areaLocations(), cms.areas.all()]);
1201
+ return declared.map(area => {
1202
+ const row = saved.get(area.name);
1203
+ return { name: area.name, label: area.label, theme: area.theme, active: area.active, rev: row?.revision ?? 0, saved: !!row, blocks: row ? row.blocks : area.defaults, defaults: area.defaults, updatedAt: row?.updatedAt ?? 0 };
1204
+ });
1205
+ }
1206
+
1207
+ /** The themes' widget areas (the active theme's first) with the blocks each shows. */
1208
+ export async function areasList(c: Context): Promise<{ items: AreaView[] }> {
1209
+ allowed(c, PERMISSIONS.manageAppearance, APPEARANCE);
1210
+ return { items: await areaViews(c.get('cms')) };
1211
+ }
1212
+
1213
+ export async function areaRead(c: Context, name: string): Promise<{ item: AreaView }> {
1214
+ allowed(c, PERMISSIONS.manageAppearance, APPEARANCE);
1215
+ const areas = await areaViews(c.get('cms'));
1216
+ const item = areas.find(area => area.name === name);
1217
+ if (!item) throw new CmsError('CMS_NOT_FOUND', `No widget area ${name}; the areas are ${areas.map(area => area.name).join(', ') || 'none'}.`);
1218
+ return { item };
1219
+ }
1220
+
1221
+ /** Replace an area's blocks (`{ blocks, rev? }`); `rev` is the revision read, 0 while the theme's defaults show. */
1222
+ export async function areaUpdate(c: Context, name: string, input: Body): Promise<{ item: AreaView }> {
1223
+ const principal = allowed(c, PERMISSIONS.manageAppearance, APPEARANCE);
1224
+ const cms = c.get('cms');
1225
+ const known = (await cms.areaLocations()).map(area => area.name);
1226
+ const current = await cms.areas.get(name);
1227
+ await cms.areas.save(name, input.blocks, { principal, expectedRevision: expected(input.rev, current.revision, 0), known });
1228
+ return areaRead(c, name);
1229
+ }
1230
+
1231
+ /** Forget an area's saved blocks: the theme's defaults show again, and its revision is 0. */
1232
+ export async function areaReset(c: Context, name: string): Promise<void> {
1233
+ const principal = allowed(c, PERMISSIONS.manageAppearance, APPEARANCE);
1234
+ const cms = c.get('cms');
1235
+ await cms.areas.reset(name, { principal, known: (await cms.areaLocations()).map(area => area.name) });
1236
+ }