@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,665 @@
1
+ /**
2
+ * A network of sites in one isolate or process: which site a request's host names, and one
3
+ * CMS host per site database, kept for the sites used last. The main site is the network
4
+ * database; while it is the only site, or while the network is off, every host serves it.
5
+ */
6
+ import type { RomeDB } from '@cossackframework/romedb';
7
+ import type { StorageMetadata, StorageProvider } from '@cossackframework/core/storage';
8
+ import { CmsError } from '../errors';
9
+ import { LOCALE } from '../collections';
10
+ import { slugify } from '../fields';
11
+ import { DEFAULT_ROLES, isNetworkAdmin, principalId, systemPrincipal, type Principal } from '../permissions';
12
+ import { unrestrictedGrantAudit } from './audit';
13
+ import { PLUGIN_ENABLED, type CmsHost, type PluginStatus } from './host';
14
+ import { pluginState, POLICY_KEYS, readPolicy, type NetworkPluginState, type NetworkPolicy, type NetworkThemeState, type StoredPluginStates, type StoredThemeStates } from './network-policy';
15
+ import { CmsHandoffs } from './handoffs';
16
+ import { seedStarterContent } from './seed';
17
+ import { CmsSites, MAIN_SITE, RESERVED_SITE_IDS, siteHost, type SiteRecord, type SiteStatus } from './sites';
18
+ import type { EndedSessions } from './stores';
19
+
20
+ /** The site a CMS host serves. */
21
+ export interface NetworkSite {
22
+ /** `main`, or the registry ID. */
23
+ readonly id: string;
24
+ /** The registry name; null for the main site, which its settings name. */
25
+ readonly name: string | null;
26
+ /** The database ID with its provider; `main` for the network database. */
27
+ readonly database: string;
28
+ readonly status: SiteStatus;
29
+ /** The primary domain; null for the main site, which `APP_URL` names. */
30
+ readonly host: string | null;
31
+ }
32
+
33
+ export type SiteResolution =
34
+ | { readonly kind: 'site'; readonly site: NetworkSite }
35
+ /** An alias: answer with a permanent redirect to the same path on this host. */
36
+ | { readonly kind: 'redirect'; readonly host: string; readonly site: string }
37
+ /** Visitors get "This site is archived"; members can still read the dashboard. */
38
+ | { readonly kind: 'archived'; readonly site: NetworkSite }
39
+ /** No site at this address. */
40
+ | { readonly kind: 'missing' };
41
+
42
+ export interface CmsNetworkOptions {
43
+ /** The network database: the main site's, with the accounts and the site registry. */
44
+ readonly db: RomeDB;
45
+ /** Builds the CMS host of a site on its database. */
46
+ readonly host: (site: NetworkSite, db: RomeDB) => CmsHost;
47
+ /** Opens an added site's database. Without it, the network is the main site only. */
48
+ readonly open?: (site: NetworkSite) => RomeDB;
49
+ /** Creates and deletes site databases (a RomeDB organization, or files). Without it, sites cannot be added. */
50
+ readonly directory?: { create(name: string): Promise<string>; delete(id: string): Promise<void> };
51
+ /** The base URL of a host, for domain checks. Default `https://<host>`. */
52
+ readonly hostUrl?: (host: string) => string;
53
+ /** What new sites' addresses end with, such as `example.com` for `blog.example.com`. Default: the network host without `www.`. */
54
+ readonly subdomainSuffix?: () => string | undefined;
55
+ readonly fetch?: typeof globalThis.fetch;
56
+ /** The network's host name (`APP_URL`'s), which always serves the main site. */
57
+ readonly networkHost?: () => string | undefined;
58
+ /** Hosts kept per isolate. Default 32; the one used longest ago is dropped first. */
59
+ readonly maxHosts?: number;
60
+ /** How long a host's lookup is reused. Default 30 seconds. */
61
+ readonly cacheMs?: number;
62
+ readonly now?: () => number;
63
+ }
64
+
65
+ export const MAIN: NetworkSite = Object.freeze({ id: MAIN_SITE, name: null, database: MAIN_SITE, status: 'active', host: null });
66
+
67
+ export class CmsNetwork {
68
+ readonly db: RomeDB;
69
+ readonly sites: CmsSites;
70
+ /** One-use codes that sign a network session in on a site. */
71
+ readonly handoffs: CmsHandoffs;
72
+ readonly #options: CmsNetworkOptions;
73
+ readonly #now: () => number;
74
+ readonly #hosts = new Map<string, CmsHost>();
75
+ readonly #lookups = new Map<string, { at: number; value: Promise<SiteResolution> }>();
76
+ #count: { at: number; value: Promise<number> } | undefined;
77
+ #enabled: { at: number; value: Promise<boolean> } | undefined;
78
+
79
+ constructor(options: CmsNetworkOptions) {
80
+ this.db = options.db;
81
+ this.#options = options;
82
+ this.#now = options.now ?? Date.now;
83
+ this.sites = new CmsSites(options.db, { now: this.#now });
84
+ this.handoffs = new CmsHandoffs(options.db, { now: this.#now });
85
+ }
86
+
87
+ /**
88
+ * End the child sessions sites made from these network sessions. Pass it to every host as
89
+ * `sessionsEnded`: signing out, a password reset, a suspension or a new network role end
90
+ * the account's sessions on every site it reached.
91
+ */
92
+ async endSessions(ended: EndedSessions): Promise<void> {
93
+ if (!this.multisite) return;
94
+ for (const id of await this.handoffs.reached(ended)) {
95
+ const record = await this.sites.get(id);
96
+ if (record && record.status !== 'creating') await this.hostOf(networkSite(record)).authSessions.revokeChildren(ended);
97
+ }
98
+ await this.handoffs.forget(ended);
99
+ }
100
+
101
+ /** Whether added sites can open their databases. */
102
+ get multisite(): boolean {
103
+ return this.#options.open !== undefined;
104
+ }
105
+
106
+ /** The main site's host: sign-in, accounts and the network dashboard live there. */
107
+ get main(): CmsHost {
108
+ return this.hostOf(MAIN);
109
+ }
110
+
111
+ /** The host of a site by ID, for calls that name the site rather than arrive at its domain (an isolated plugin's bridge). */
112
+ async hostById(id: string): Promise<CmsHost | null> {
113
+ if (id === MAIN_SITE) return this.main;
114
+ const record = await this.sites.get(id);
115
+ return record && record.status !== 'creating' && record.status !== 'deleted' ? this.hostOf(networkSite(record)) : null;
116
+ }
117
+
118
+ /** The CMS host of a site, built on first use and kept while it is among the last used. */
119
+ hostOf(site: NetworkSite): CmsHost {
120
+ const kept = this.#hosts.get(site.database);
121
+ if (kept) {
122
+ this.#hosts.delete(site.database);
123
+ this.#hosts.set(site.database, kept);
124
+ return kept;
125
+ }
126
+ if (site.database !== MAIN_SITE && !this.#options.open) throw new Error(`Site ${site.id} needs a site database provider.`);
127
+ const db = site.database === MAIN_SITE ? this.db : this.#options.open!(site);
128
+ const host = this.#options.host(site, db);
129
+ // Members are recorded under the host's site, so a host made for another site would misfile them.
130
+ if (host.site !== site.id && (host as { site?: string }).site !== undefined) throw new Error(`The host factory must pass site: '${site.id}' to createCMS.`);
131
+ this.#hosts.set(site.database, host);
132
+ const limit = Math.max(this.#options.maxHosts ?? 32, 2);
133
+ for (const [database, dropped] of this.#hosts) {
134
+ if (this.#hosts.size <= limit) break;
135
+ if (database === MAIN_SITE) continue;
136
+ this.#hosts.delete(database);
137
+ // Requests may still hold the host; close its database once they are done.
138
+ const timer = setTimeout(() => { dropped.db.close().catch(() => undefined); }, 60_000) as { unref?: () => void };
139
+ timer.unref?.();
140
+ }
141
+ return host;
142
+ }
143
+
144
+ /** The site a request's host names. Lookups are reused for 30 seconds. */
145
+ resolve(host: string): Promise<SiteResolution> {
146
+ const name = siteHost(host);
147
+ const now = this.#now();
148
+ const cached = this.#lookups.get(name);
149
+ if (cached && now - cached.at < (this.#options.cacheMs ?? 30_000)) return cached.value;
150
+ const value = this.#resolve(name);
151
+ if (this.#lookups.size >= 1000) this.#lookups.delete(this.#lookups.keys().next().value!);
152
+ this.#lookups.set(name, { at: now, value });
153
+ value.catch(() => this.#lookups.delete(name));
154
+ return value;
155
+ }
156
+
157
+ /**
158
+ * Whether the network serves its added sites. Off until a network admin turns it on: until
159
+ * then the install is one site, and the network dashboard is hidden. Reused for 30 seconds.
160
+ */
161
+ enabled(): Promise<boolean> {
162
+ const now = this.#now();
163
+ if (!this.#enabled || now - this.#enabled.at >= (this.#options.cacheMs ?? 30_000)) {
164
+ // Before setup `cms_network` does not exist yet: the network is off.
165
+ const value = this.state<boolean>(ENABLED).then(stored => stored === true, () => false);
166
+ this.#enabled = { at: now, value };
167
+ }
168
+ return this.#enabled.value;
169
+ }
170
+
171
+ /** Turn the network on or off. Off, added sites stop answering; their databases and registry rows stay. */
172
+ async setEnabled(enabled: boolean, context: { principal: Principal }): Promise<void> {
173
+ requireNetworkAdmin(context.principal);
174
+ await this.setState(ENABLED, enabled);
175
+ this.invalidate();
176
+ }
177
+
178
+ /** Whether sites can be added: the network opens and creates site databases. */
179
+ get canAddSites(): boolean {
180
+ return this.multisite && this.#options.directory !== undefined;
181
+ }
182
+
183
+ /** What new sites' addresses end with, such as `example.com`. */
184
+ get subdomainSuffix(): string {
185
+ return siteHost(this.#options.subdomainSuffix?.() ?? '') || siteHost(this.#options.networkHost?.() ?? '').replace(/^www\./, '');
186
+ }
187
+
188
+ /**
189
+ * Add a site, or finish one an earlier call left half made: create its database, apply the
190
+ * schema, seed the roles and settings, then add its first administrator. Each step is
191
+ * recorded in the registry, so a failure resumes after the last step done.
192
+ */
193
+ async createSite(input: NewSite, context: { principal: Principal }): Promise<SiteRecord> {
194
+ requireNetworkAdmin(context.principal);
195
+ const directory = this.#options.directory;
196
+ if (!directory || !this.#options.open) throw new CmsError('CMS_UNAVAILABLE', 'This network cannot add sites yet: it needs a provider for site databases.');
197
+ if (!(await this.enabled())) throw new CmsError('CMS_UNAVAILABLE', 'Turn the network on in Settings before adding sites.');
198
+ const slug = slugify(input.name, 40) || 'site';
199
+ const id = input.id ?? (RESERVED_SITE_IDS.has(slug) ? `${slug}-site` : slug);
200
+ if (input.language && !LOCALE.test(input.language)) throw new CmsError('CMS_VALIDATION', 'Enter a language code, such as en or pt-br.', { fields: { language: 'is invalid.' } });
201
+ const admin = await this.main.accounts.get(input.admin);
202
+ if (!admin || admin.status !== 'active') throw new CmsError('CMS_VALIDATION', 'Choose an active account as the first administrator.', { fields: { admin: 'is invalid.' } });
203
+ let record = await this.sites.get(id);
204
+ if (record && record.status !== 'creating') throw new CmsError('CMS_CONFLICT', 'A site with this ID exists.', { fields: { id: 'is taken.' } });
205
+ if (!record) {
206
+ record = await this.sites.create({ id, name: input.name, database: `pending-${id}`, status: 'creating', domains: [{ host: await this.#address(input.host), primary: true, verifiedAt: this.#now() }] });
207
+ this.invalidate();
208
+ }
209
+ const done = (step: CreationStep) => record!.step !== null && CREATION_STEPS.indexOf(record!.step as CreationStep) >= CREATION_STEPS.indexOf(step);
210
+ if (!done('database')) record = (await this.sites.update(id, { database: await directory.create(`site-${id}`), step: 'database' }))!;
211
+ const host = this.hostOf(networkSite(record));
212
+ if (!done('schema')) {
213
+ const report = await host.migrate();
214
+ if (report.failed) throw new CmsError('CMS_UNAVAILABLE', `The site's schema could not be applied: ${report.failed.message}`);
215
+ await host.ready({ force: true });
216
+ record = (await this.sites.update(id, { step: 'schema' }))!;
217
+ }
218
+ if (!done('seeded')) {
219
+ const system = systemPrincipal('network');
220
+ const defaults = await this.settings();
221
+ for (const role of DEFAULT_ROLES) await host.users.defineRole({ ...role, permissions: [...role.permissions] });
222
+ await host.settings.update('general', { siteTitle: record.name, adminEmail: admin.email }, { principal: system });
223
+ const language = input.language || defaults.defaultLanguage;
224
+ // Languages come with the content module.
225
+ if (language && host.settings.groups.some(group => group.id === 'languages')) await host.settings.update('languages', { default: language }, { principal: system });
226
+ // The network's defaults, as a site admin would choose them; one the network hid since is left out.
227
+ if (defaults.defaultTheme && (await host.availableThemes()).some(theme => theme.name === defaults.defaultTheme)) await host.activateTheme(defaults.defaultTheme, system);
228
+ const policy = await this.policy();
229
+ for (const name of defaults.defaultPlugins) {
230
+ if (pluginState(policy, name) === 'available') await host.grantPlugin(name, system).catch(error => console.warn(`[cms] site ${id} could not enable ${name}: ${(error as Error).message}`));
231
+ }
232
+ record = (await this.sites.update(id, { step: 'seeded' }))!;
233
+ }
234
+ if (!done('members')) {
235
+ await host.users.addMember(admin.id);
236
+ await host.users.setRoles(admin.id, ['admin']);
237
+ const principal = input.starter ? await host.users.principal(admin.id) : null;
238
+ if (principal) await seedStarterContent(host, { principal }).catch(error => console.warn(`[cms] starter content for site ${id}: ${(error as Error).message}`));
239
+ record = (await this.sites.update(id, { step: 'members' }))!;
240
+ }
241
+ record = (await this.sites.update(id, { status: 'active', step: null }))!;
242
+ this.invalidate();
243
+ return record;
244
+ }
245
+
246
+ /** Archive, delete or restore a site. A deleted site can be restored for 30 days. */
247
+ async setSiteStatus(id: string, status: 'active' | 'archived' | 'deleted', context: { principal: Principal }): Promise<SiteRecord> {
248
+ requireNetworkAdmin(context.principal);
249
+ const record = await this.sites.get(id);
250
+ if (!record || record.status === 'creating') throw new CmsError('CMS_NOT_FOUND', 'There is no such site.');
251
+ const updated = (await this.sites.update(id, { status }))!;
252
+ this.invalidate();
253
+ return updated;
254
+ }
255
+
256
+ /** Delete for good the sites deleted 30 days ago or more: their media, database and registry row. Run it from the schedule. */
257
+ async purgeDeleted(options: { olderThanMs?: number } = {}): Promise<string[]> {
258
+ const directory = this.#options.directory;
259
+ if (!directory) return [];
260
+ const purged: string[] = [];
261
+ for (const record of await this.sites.deletedBefore(this.#now() - (options.olderThanMs ?? 30 * 24 * 60 * 60_000))) {
262
+ if (!record.database.startsWith('pending-')) {
263
+ await this.hostOf(networkSite(record)).files?.purgeStorage();
264
+ await this.release(record.database);
265
+ await directory.delete(record.database);
266
+ }
267
+ await this.sites.remove(record.id);
268
+ purged.push(record.id);
269
+ }
270
+ if (purged.length) this.invalidate();
271
+ return purged;
272
+ }
273
+
274
+ /** Drop a site's host from this isolate and close its database now, before its database is deleted. */
275
+ async release(database: string): Promise<void> {
276
+ const host = this.#hosts.get(database);
277
+ if (!host || database === MAIN_SITE) return;
278
+ this.#hosts.delete(database);
279
+ await host.db.close();
280
+ }
281
+
282
+ /** Add a domain to a site. It answers as an alias until `checkDomain` finds the site there. */
283
+ async addDomain(id: string, host: string, context: { principal: Principal }): Promise<SiteRecord | null> {
284
+ requireNetworkAdmin(context.principal);
285
+ const record = await this.sites.addDomain(id, host);
286
+ this.invalidate();
287
+ return record;
288
+ }
289
+
290
+ /**
291
+ * Ask a domain which site it serves (`/.well-known/cossack-site`). When it answers with this
292
+ * site's ID, the domain points here: record that, and make it primary unless told otherwise.
293
+ */
294
+ async checkDomain(id: string, host: string, context: { principal: Principal; primary?: boolean }): Promise<boolean> {
295
+ requireNetworkAdmin(context.principal);
296
+ const name = siteHost(host);
297
+ if (!name) return false;
298
+ const base = this.#options.hostUrl?.(name) ?? `https://${name}`;
299
+ const answer = await (this.#options.fetch ?? ((input, init) => globalThis.fetch(input, init)))(`${base}/.well-known/cossack-site`, { redirect: 'manual', signal: AbortSignal.timeout(5000) })
300
+ .then(async response => response.ok ? (await response.text()).trim() : '', () => '');
301
+ if (answer !== id) return false;
302
+ const verified = await this.sites.verifyDomain(id, name, { primary: context.primary ?? true });
303
+ this.invalidate();
304
+ return verified;
305
+ }
306
+
307
+ async removeDomain(id: string, host: string, context: { principal: Principal }): Promise<boolean> {
308
+ requireNetworkAdmin(context.principal);
309
+ const removed = await this.sites.removeDomain(id, host);
310
+ this.invalidate();
311
+ return removed;
312
+ }
313
+
314
+ /** Network settings: its name, what new sites' addresses end with, and what new sites start with. */
315
+ async settings(): Promise<NetworkSettings> {
316
+ const stored = await this.state<Partial<NetworkSettings>>('settings') ?? {};
317
+ const text = (value: unknown) => typeof value === 'string' ? value : '';
318
+ return {
319
+ name: text(stored.name), subdomainSuffix: text(stored.subdomainSuffix), defaultTheme: text(stored.defaultTheme), defaultLanguage: text(stored.defaultLanguage),
320
+ defaultPlugins: Array.isArray(stored.defaultPlugins) ? stored.defaultPlugins.filter((name): name is string => typeof name === 'string') : [],
321
+ siteExports: stored.siteExports === 'self' ? 'self' : 'request',
322
+ };
323
+ }
324
+
325
+ async saveSettings(patch: Partial<NetworkSettings>, context: { principal: Principal }): Promise<NetworkSettings> {
326
+ requireNetworkAdmin(context.principal);
327
+ const next = { ...await this.settings(), ...patch };
328
+ if (typeof next.name !== 'string' || next.name.length > 120) throw new CmsError('CMS_VALIDATION', 'Enter a network name of at most 120 characters.', { fields: { name: 'is too long.' } });
329
+ if (next.subdomainSuffix && !siteHost(next.subdomainSuffix)) throw new CmsError('CMS_VALIDATION', 'Enter a domain, such as example.com.', { fields: { subdomainSuffix: 'is invalid.' } });
330
+ if (next.defaultTheme && !this.main.themes().some(theme => theme.name === next.defaultTheme && !theme.problems.length)) throw new CmsError('CMS_VALIDATION', 'Choose an installed theme.', { fields: { defaultTheme: 'is unknown.' } });
331
+ const plugins = new Set((await this.main.status()).plugins.filter(plugin => !plugin.themeOnly).map(plugin => plugin.name));
332
+ const unknown = next.defaultPlugins.filter(name => !plugins.has(name));
333
+ if (unknown.length) throw new CmsError('CMS_VALIDATION', `Unknown plugins: ${unknown.join(', ')}.`, { fields: { defaultPlugins: 'are unknown.' } });
334
+ if (next.defaultLanguage && !LOCALE.test(next.defaultLanguage)) throw new CmsError('CMS_VALIDATION', 'Enter a language code, such as en or pt-br.', { fields: { defaultLanguage: 'is invalid.' } });
335
+ if (next.siteExports !== 'request' && next.siteExports !== 'self') throw new CmsError('CMS_VALIDATION', 'Site exports are request or self.', { fields: { siteExports: 'is invalid.' } });
336
+ const saved: NetworkSettings = {
337
+ name: next.name.trim(), subdomainSuffix: next.subdomainSuffix ? siteHost(next.subdomainSuffix) : '',
338
+ defaultTheme: next.defaultTheme, defaultPlugins: [...new Set(next.defaultPlugins)], defaultLanguage: next.defaultLanguage, siteExports: next.siteExports,
339
+ };
340
+ await this.setState('settings', saved);
341
+ return saved;
342
+ }
343
+
344
+ /** Sites' export requests by site: those waiting for a network admin, and approvals that have not expired. */
345
+ async exportRequests(): Promise<Map<string, ExportRequest>> {
346
+ const now = this.#now();
347
+ const stored = await this.state<StoredExportRequests>(EXPORTS) ?? {};
348
+ const requests = new Map<string, ExportRequest>();
349
+ for (const [site, entry] of Object.entries(stored)) {
350
+ const expiresAt = entry.approvedAt ? entry.approvedAt + EXPORT_APPROVAL_MS : null;
351
+ if (expiresAt === null || expiresAt > now) requests.set(site, { site, requestedBy: entry.requestedBy, requestedAt: entry.requestedAt, approvedBy: entry.approvedBy ?? null, approvedAt: entry.approvedAt ?? null, expiresAt });
352
+ }
353
+ return requests;
354
+ }
355
+
356
+ /**
357
+ * Whether a site may download its database export now: the main site always; another site
358
+ * when the network lets sites export themselves, or for 7 days after a network admin
359
+ * approved its request. The site's own permission is the caller's to check.
360
+ */
361
+ async exportAccess(site: string): Promise<{ allowed: boolean; request: ExportRequest | null }> {
362
+ const request = site === MAIN_SITE ? null : (await this.exportRequests()).get(site) ?? null;
363
+ const allowed = site === MAIN_SITE || (await this.settings()).siteExports === 'self' || request?.approvedAt != null;
364
+ return { allowed, request };
365
+ }
366
+
367
+ /** A site asks a network admin for its export. Asking again while a request waits changes nothing. */
368
+ async requestExport(site: string, context: { principal: Principal }): Promise<ExportRequest> {
369
+ if (context.principal.kind !== 'user') throw new CmsError('CMS_UNAUTHENTICATED', 'Sign in to request an export.');
370
+ const record = await this.sites.get(site);
371
+ if (!record || (record.status !== 'active' && record.status !== 'archived')) throw new CmsError('CMS_NOT_FOUND', 'There is no such site.');
372
+ const by = context.principal.id;
373
+ await this.#updateExports(stored => {
374
+ if (stored[site] && !stored[site]!.approvedAt) return;
375
+ stored[site] = { requestedBy: by, requestedAt: this.#now() };
376
+ });
377
+ return (await this.exportRequests()).get(site)!;
378
+ }
379
+
380
+ /** The site withdraws its request, or gives up an approval it no longer needs. */
381
+ async withdrawExport(site: string, context: { principal: Principal }): Promise<void> {
382
+ if (context.principal.kind !== 'user') throw new CmsError('CMS_UNAUTHENTICATED', 'Sign in to withdraw an export request.');
383
+ await this.#updateExports(stored => { delete stored[site]; });
384
+ }
385
+
386
+ /** A network admin approves a site's request, for 7 days of downloads, or declines it. */
387
+ async answerExport(site: string, approve: boolean, context: { principal: Principal }): Promise<ExportRequest | null> {
388
+ requireNetworkAdmin(context.principal);
389
+ const by = principalId(context.principal);
390
+ await this.#updateExports(stored => {
391
+ const current = stored[site];
392
+ if (!current) throw new CmsError('CMS_NOT_FOUND', 'This site has not requested an export.');
393
+ if (!approve) delete stored[site];
394
+ else stored[site] = { requestedBy: current.requestedBy, requestedAt: current.requestedAt, approvedBy: by, approvedAt: this.#now() };
395
+ });
396
+ return approve ? (await this.exportRequests()).get(site)! : null;
397
+ }
398
+
399
+ /**
400
+ * Change the sites' export requests, which share one value: written only if it is still the
401
+ * value read, read again and changed again otherwise, so one site's request never drops
402
+ * another's, nor an admin's answer.
403
+ */
404
+ async #updateExports(change: (stored: StoredExportRequests) => void): Promise<void> {
405
+ await this.#updateValue<StoredExportRequests>(EXPORTS, stored => {
406
+ // Expired approvals go with the next change.
407
+ for (const [id, value] of Object.entries(stored)) if (value.approvedAt && value.approvedAt + EXPORT_APPROVAL_MS <= this.#now()) delete stored[id];
408
+ change(stored);
409
+ }, 'Export requests changed meanwhile. Try again.');
410
+ }
411
+
412
+ /**
413
+ * Change one of the network's values, written only while it is still the value read, read
414
+ * again when another change landed first, so two changes never drop one another.
415
+ */
416
+ async #updateValue<T extends object>(key: string, change: (stored: T) => void, conflict: string): Promise<void> {
417
+ for (let attempt = 0; attempt < 8; attempt++) {
418
+ const read = await this.db.read([{ rql: 'SELECT value FROM cms_network WHERE key = $key', params: { $key: key } }]);
419
+ const previous = read.results[0]!.rows[0]?.[0] as string | undefined;
420
+ const stored = (previous === undefined ? {} : JSON.parse(previous)) as T;
421
+ change(stored);
422
+ const params = { $key: key, $value: JSON.stringify(stored), $now: this.#now(), ...(previous === undefined ? {} : { $previous: previous }) };
423
+ const written = await this.db.write([previous === undefined
424
+ ? { rql: 'INSERT INTO cms_network (key, value, updated_at) VALUES ($key, $value, $now) ON CONFLICT (key) DO NOTHING', params }
425
+ : { rql: 'UPDATE cms_network SET value = $value, updated_at = $now WHERE key = $key AND value = $previous', params }], { kind: 'cms.network', retryConflicts: 5 });
426
+ if (written.results[0]!.affected === 1n) return;
427
+ }
428
+ throw new CmsError('CMS_CONFLICT', conflict);
429
+ }
430
+
431
+ /** The network's plugin and theme states. */
432
+ policy(): Promise<NetworkPolicy> {
433
+ return readPolicy(this.db);
434
+ }
435
+
436
+ /**
437
+ * Set a plugin's state on every site. `network` approves everything its manifest requests
438
+ * now, and each site migrates it as it loads; an upgrade that requests more waits until a
439
+ * network admin sets it again. Hosts in other isolates see the change within their activation TTL.
440
+ */
441
+ async setPluginState(name: string, state: NetworkPluginState, context: { principal: Principal; unrestricted?: boolean }): Promise<PluginStatus> {
442
+ requireNetworkAdmin(context.principal);
443
+ const plugin = (await this.main.status()).plugins.find(entry => entry.name === name && !entry.themeOnly);
444
+ if (!plugin) throw new CmsError('CMS_NOT_FOUND', `Unknown plugin ${name}.`);
445
+ if (state === 'network' && plugin.reason?.startsWith('Invalid manifest')) throw new CmsError('CMS_VALIDATION', `${name} cannot be activated: ${plugin.reason}`);
446
+ if (state === 'network' && plugin.unrestricted && !context.unrestricted) throw new CmsError('CMS_CONFLICT', `Plugin ${name} was not enabled: unrestricted access has to be confirmed on its own.`);
447
+ await this.#updateValue<StoredPluginStates>(POLICY_KEYS.plugins, stored => {
448
+ if (state === 'available') delete stored[name];
449
+ else stored[name] = state === 'network' ? { state, grants: plugin.requests.filter(grant => grant !== PLUGIN_ENABLED) } : { state };
450
+ }, 'Plugin states changed meanwhile. Try again.');
451
+ if (state === 'network' && plugin.unrestricted) await this.main.db.write([unrestrictedGrantAudit(name, principalId(context.principal), this.#now())], { kind: 'cms.grants' });
452
+ this.#expireHosts();
453
+ await this.main.ready();
454
+ return (await this.main.status()).plugins.find(entry => entry.name === name)!;
455
+ }
456
+
457
+ /** Hide a theme from every site, or make it available again. A site whose theme is hidden falls back to another. */
458
+ async setThemeState(name: string, state: NetworkThemeState, context: { principal: Principal }): Promise<void> {
459
+ requireNetworkAdmin(context.principal);
460
+ if (!this.main.themes().some(theme => theme.name === name)) throw new CmsError('CMS_NOT_FOUND', `Unknown theme ${name}.`);
461
+ await this.#updateValue<StoredThemeStates>(POLICY_KEYS.themes, stored => {
462
+ if (state === 'hidden') stored[name] = 'hidden';
463
+ else delete stored[name];
464
+ }, 'Theme states changed meanwhile. Try again.');
465
+ this.#expireHosts();
466
+ }
467
+
468
+ /** Open hosts read the network's states again on their next request. */
469
+ #expireHosts(): void {
470
+ this.main.expire();
471
+ for (const host of this.#hosts.values()) host.expire();
472
+ }
473
+
474
+ /** A value the network keeps by key in its database, such as where scheduled work stopped. */
475
+ async state<T>(key: string): Promise<T | undefined> {
476
+ const result = await this.db.read([{ rql: 'SELECT value FROM cms_network WHERE key = $key', params: { $key: key } }]);
477
+ const value = result.results[0]!.rows[0]?.[0];
478
+ return value === undefined ? undefined : JSON.parse(value as string) as T;
479
+ }
480
+
481
+ async setState(key: string, value: unknown): Promise<void> {
482
+ await this.db.write([{ rql: 'INSERT INTO cms_network (key, value, updated_at) SELECT $key, $value, $now WHERE 1 = 1 ON CONFLICT (key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at',
483
+ params: { $key: key, $value: JSON.stringify(value), $now: this.#now() } }], { kind: 'cms.network', retryConflicts: 5 });
484
+ }
485
+
486
+ /** The sites an account is a member of, the main site first, without opening their databases. Off, the network is its main site. */
487
+ async memberSites(accountId: string): Promise<NetworkSite[]> {
488
+ const ids = (await this.main.accounts.memberships([accountId])).get(accountId) ?? [];
489
+ const sites: NetworkSite[] = ids.includes(MAIN_SITE) ? [MAIN] : [];
490
+ if (!(await this.enabled())) return sites;
491
+ const records = new Map((await this.sites.getMany(ids)).map(record => [record.id, record]));
492
+ for (const id of ids) {
493
+ const record = records.get(id);
494
+ if (record && (record.status === 'active' || record.status === 'archived')) sites.push(networkSite(record));
495
+ }
496
+ return sites;
497
+ }
498
+
499
+ /** Delete an account: first its membership of every site, through each site's own user deletion, then the account. */
500
+ async deleteAccount(id: string, context: { principal: Principal }): Promise<boolean> {
501
+ requireNetworkAdmin(context.principal);
502
+ const account = await this.main.accounts.get(id);
503
+ if (!account) return false;
504
+ // Refuse the last network admin before anything changes.
505
+ if (account.networkRole && !(await this.main.accounts.list({ networkAdmins: true, limit: 2 })).items.some(other => other.id !== id && other.status === 'active')) {
506
+ throw new CmsError('CMS_FORBIDDEN', 'The last network admin cannot be deleted.');
507
+ }
508
+ for (const site of (await this.main.accounts.memberships([id])).get(id) ?? []) {
509
+ const record = site === MAIN_SITE ? null : await this.sites.get(site);
510
+ if (site === MAIN_SITE) await this.main.users.delete(id);
511
+ else if (record && record.status !== 'creating') await this.hostOf(networkSite(record)).users.delete(id);
512
+ }
513
+ return this.main.accounts.delete(id);
514
+ }
515
+
516
+ /** Sites whose schema has steps to apply after a deploy, with how many; each site applies its own when it next loads. */
517
+ async updates(options: { limit?: number; offset?: number } = {}): Promise<{ site: NetworkSite; name: string; pending: number }[]> {
518
+ const records = (await this.sites.list({ status: 'active', limit: options.limit ?? 50, offset: options.offset ?? 0 })).items;
519
+ const sites: { site: NetworkSite; name: string }[] = [{ site: MAIN, name: (await this.settings()).name || 'Main site' }, ...records.map(record => ({ site: networkSite(record), name: record.name }))];
520
+ const found: { site: NetworkSite; name: string; pending: number }[] = [];
521
+ for (const entry of sites) {
522
+ const plan = await this.hostOf(entry.site).plan().catch(() => null);
523
+ const pending = plan ? plan.steps.filter(step => step.kind === 'host').length : 0;
524
+ if (pending) found.push({ ...entry, pending });
525
+ }
526
+ return found;
527
+ }
528
+
529
+ /** Apply pending host steps, up to `limit` sites at a time. Returns the sites upgraded and those that failed. */
530
+ async upgrade(context: { principal: Principal; limit?: number }): Promise<{ upgraded: string[]; failed: { site: string; message: string }[] }> {
531
+ requireNetworkAdmin(context.principal);
532
+ const upgraded: string[] = [];
533
+ const failed: { site: string; message: string }[] = [];
534
+ for (const { site } of (await this.updates()).slice(0, context.limit ?? 10)) {
535
+ const report = await this.hostOf(site).migrate().catch(error => ({ failed: { message: (error as Error).message } }));
536
+ if (report.failed) failed.push({ site: site.id, message: report.failed.message });
537
+ else upgraded.push(site.id);
538
+ }
539
+ return { upgraded, failed };
540
+ }
541
+
542
+ /** A new site's address: a host under the network's suffix, or any `.localhost` host in development. */
543
+ async #address(host: string): Promise<string> {
544
+ const name = siteHost(host);
545
+ const suffix = (await this.settings()).subdomainSuffix || this.subdomainSuffix;
546
+ if (!name || (suffix && !name.endsWith(`.${suffix}`) && !name.endsWith('.localhost'))) {
547
+ throw new CmsError('CMS_VALIDATION', suffix ? `New sites start at an address ending in .${suffix}; add their own domains once they exist.` : 'Enter the site\'s address, such as blog.example.com.', { fields: { host: 'is invalid.' } });
548
+ }
549
+ return name;
550
+ }
551
+
552
+ /** Forget cached lookups, after a registry change made in this isolate. */
553
+ invalidate(): void {
554
+ this.#lookups.clear();
555
+ this.#count = undefined;
556
+ this.#enabled = undefined;
557
+ }
558
+
559
+ async #resolve(name: string): Promise<SiteResolution> {
560
+ const main: SiteResolution = { kind: 'site', site: MAIN };
561
+ // While the network is the main site, every host serves it, so preview URLs and tunnels keep working.
562
+ if (!this.multisite || (await this.#siteCount()) === 0) return main;
563
+ const network = siteHost(this.#options.networkHost?.() ?? '');
564
+ if (!name) return { kind: 'missing' };
565
+ if (name === network) return main;
566
+ const found = await this.sites.siteOf(name);
567
+ // Off, the main site answers everywhere except at an added site's domains, which serve nothing.
568
+ if (!(await this.enabled())) return found && found.site !== MAIN_SITE ? { kind: 'missing' } : main;
569
+ if (!found) return { kind: 'missing' };
570
+ if (found.site === MAIN_SITE) return found.domain.primary || !network ? main : { kind: 'redirect', host: network, site: MAIN_SITE };
571
+ const record = await this.sites.get(found.site);
572
+ if (!record || record.status === 'creating' || record.status === 'deleted') return { kind: 'missing' };
573
+ const site = networkSite(record);
574
+ if (!found.domain.primary && site.host) return { kind: 'redirect', host: site.host, site: site.id };
575
+ return record.status === 'archived' ? { kind: 'archived', site } : { kind: 'site', site };
576
+ }
577
+
578
+ #siteCount(): Promise<number> {
579
+ const now = this.#now();
580
+ if (!this.#count || now - this.#count.at >= (this.#options.cacheMs ?? 30_000)) {
581
+ const value = this.sites.count();
582
+ this.#count = { at: now, value };
583
+ value.catch(() => { this.#count = undefined; });
584
+ }
585
+ return this.#count.value;
586
+ }
587
+ }
588
+
589
+ export interface NetworkSettings {
590
+ /** Shown on the network dashboard and sign-in; empty for the main site's title. */
591
+ readonly name: string;
592
+ /** What new sites' addresses end with; empty for the network host without `www.`. */
593
+ readonly subdomainSuffix: string;
594
+ /** The theme new sites start with; empty for the first available one. */
595
+ readonly defaultTheme: string;
596
+ /** Plugins granted on new sites, as a site admin would grant them. */
597
+ readonly defaultPlugins: readonly string[];
598
+ /** New sites' default language; empty for English. */
599
+ readonly defaultLanguage: string;
600
+ /** How added sites export their databases: `request` a network admin's approval (the default), or download them `self`. */
601
+ readonly siteExports: SiteExportPolicy;
602
+ }
603
+
604
+ export type SiteExportPolicy = 'request' | 'self';
605
+
606
+ /** A site's request to export its database, and the network admin's answer. */
607
+ export interface ExportRequest {
608
+ readonly site: string;
609
+ /** The account that asked. */
610
+ readonly requestedBy: string;
611
+ readonly requestedAt: number;
612
+ readonly approvedBy: string | null;
613
+ readonly approvedAt: number | null;
614
+ /** Until when the site may download after the approval; null while it waits. */
615
+ readonly expiresAt: number | null;
616
+ }
617
+
618
+ type StoredExportRequests = Record<string, { requestedBy: string; requestedAt: number; approvedBy?: string; approvedAt?: number }>;
619
+
620
+ /** What adding a site asks for. */
621
+ export interface NewSite {
622
+ readonly name: string;
623
+ /** The registry ID; made from the name when left out. */
624
+ readonly id?: string;
625
+ /** The site's address, under the network's subdomain suffix, such as `blog.example.com`. */
626
+ readonly host: string;
627
+ /** The account that becomes the site's first administrator. */
628
+ readonly admin: string;
629
+ /** A first post, a category, a contact form and its page. */
630
+ readonly starter?: boolean;
631
+ /** The site's default language; the network's default when left out. */
632
+ readonly language?: string;
633
+ }
634
+
635
+ /** The `cms_network` key of whether the network is on. */
636
+ const ENABLED = 'enabled';
637
+ /** The `cms_network` key of sites' export requests. */
638
+ const EXPORTS = 'exports';
639
+ /** How long an approved export stays downloadable. */
640
+ const EXPORT_APPROVAL_MS = 7 * 24 * 60 * 60_000;
641
+
642
+ const CREATION_STEPS = ['database', 'schema', 'seeded', 'members'] as const;
643
+ type CreationStep = typeof CREATION_STEPS[number];
644
+
645
+ function requireNetworkAdmin(principal: Principal): void {
646
+ if (principal.kind !== 'system' && !isNetworkAdmin(principal)) throw new CmsError('CMS_FORBIDDEN', 'Only network admins manage sites.');
647
+ }
648
+
649
+ export function networkSite(record: SiteRecord): NetworkSite {
650
+ return Object.freeze({ id: record.id, name: record.name, database: record.database, status: record.status, host: record.domains.find(domain => domain.primary)?.host ?? null });
651
+ }
652
+
653
+ /** A site's media: the same storage under a key prefix, such as `sites/blog/`. Keys come back without it. */
654
+ export function prefixedStorage(storage: StorageProvider, prefix: string): StorageProvider {
655
+ if (!/^[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*\/$/.test(prefix)) throw new TypeError('A storage prefix is path segments ending in a slash.');
656
+ const strip = <T extends StorageMetadata | null>(metadata: T): T => metadata && metadata.key.startsWith(prefix) ? { ...metadata, key: metadata.key.slice(prefix.length) } : metadata;
657
+ return {
658
+ name: storage.name,
659
+ put: async (key, body, options) => strip(await storage.put(prefix + key, body, options)),
660
+ get: async (key, options) => strip(await storage.get(prefix + key, options)),
661
+ head: async (key, options) => strip(await storage.head(prefix + key, options)),
662
+ delete: (key, options) => storage.delete(prefix + key, options),
663
+ ...(storage.presign ? { presign: (key: string, options: Parameters<NonNullable<StorageProvider['presign']>>[1]) => storage.presign!(prefix + key, options) } : {}),
664
+ };
665
+ }