@cossackframework/cms 0.0.0-stage → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +147 -2
- package/agent-docs.json +259 -0
- package/app/README.md +78 -0
- package/app/cossack-recipe.json +43 -0
- package/app/src/auth-bot-check.ts +32 -0
- package/app/src/auth-bot-token.ts +11 -0
- package/app/src/auth-input.ts +35 -0
- package/app/src/auth-options.ts +18 -0
- package/app/src/auth-providers.ts +16 -0
- package/app/src/auth.ts +1082 -0
- package/app/src/brand.ts +68 -0
- package/app/src/cms/ai.ts +54 -0
- package/app/src/cms/analytics.ts +33 -0
- package/app/src/cms/block-errors.ts +55 -0
- package/app/src/cms/block-inserter.ts +111 -0
- package/app/src/cms/block-panel.ts +68 -0
- package/app/src/cms/block-rows.ts +44 -0
- package/app/src/cms/block-tree.ts +585 -0
- package/app/src/cms/blocks.css +708 -0
- package/app/src/cms/builder.ts +126 -0
- package/app/src/cms/cache.ts +44 -0
- package/app/src/cms/carousel.client.ts +52 -0
- package/app/src/cms/collab/presence.ts +69 -0
- package/app/src/cms/collab/rich-text-collab.client.ts +197 -0
- package/app/src/cms/collab/rich-text-notes.client.ts +138 -0
- package/app/src/cms/collab/room.ts +881 -0
- package/app/src/cms/compare.client.ts +47 -0
- package/app/src/cms/condition-control.ts +109 -0
- package/app/src/cms/content-api.ts +143 -0
- package/app/src/cms/content.ts +524 -0
- package/app/src/cms/countdown.client.ts +37 -0
- package/app/src/cms/editor-layout-editor.ts +260 -0
- package/app/src/cms/editor-layout-view.ts +37 -0
- package/app/src/cms/editor.ts +381 -0
- package/app/src/cms/entry.ts +26 -0
- package/app/src/cms/feeds.ts +145 -0
- package/app/src/cms/field-controls.ts +222 -0
- package/app/src/cms/field-group-editor.ts +105 -0
- package/app/src/cms/field-group-view.ts +211 -0
- package/app/src/cms/form-view.ts +203 -0
- package/app/src/cms/form.client.ts +203 -0
- package/app/src/cms/guards.ts +27 -0
- package/app/src/cms/handoff.ts +202 -0
- package/app/src/cms/headings.ts +51 -0
- package/app/src/cms/icons.ts +80 -0
- package/app/src/cms/import.client.ts +16 -0
- package/app/src/cms/index.ts +191 -0
- package/app/src/cms/lightbox.client.ts +109 -0
- package/app/src/cms/machine.ts +118 -0
- package/app/src/cms/maintenance.ts +97 -0
- package/app/src/cms/manage.ts +1236 -0
- package/app/src/cms/mcp-tools.ts +388 -0
- package/app/src/cms/mcp.ts +242 -0
- package/app/src/cms/media-chooser.ts +123 -0
- package/app/src/cms/media-usage.ts +57 -0
- package/app/src/cms/middleware.ts +199 -0
- package/app/src/cms/middlewares.ts +13 -0
- package/app/src/cms/network-ui.ts +36 -0
- package/app/src/cms/network-view.ts +38 -0
- package/app/src/cms/notes-announce.ts +65 -0
- package/app/src/cms/notes-rail.ts +207 -0
- package/app/src/cms/notification-rules.ts +66 -0
- package/app/src/cms/recovery.ts +82 -0
- package/app/src/cms/replace.ts +63 -0
- package/app/src/cms/reserved-paths.ts +19 -0
- package/app/src/cms/rich-text-field.ts +325 -0
- package/app/src/cms/rich-text-schema.ts +91 -0
- package/app/src/cms/rich-text.client.ts +255 -0
- package/app/src/cms/search.client.ts +116 -0
- package/app/src/cms/seo-head.ts +78 -0
- package/app/src/cms/seo.ts +241 -0
- package/app/src/cms/settings-draft.ts +218 -0
- package/app/src/cms/settings-file.ts +127 -0
- package/app/src/cms/settings-form.ts +180 -0
- package/app/src/cms/settings-languages.ts +125 -0
- package/app/src/cms/settings-nav.ts +102 -0
- package/app/src/cms/settings-network.ts +151 -0
- package/app/src/cms/settings-permalinks.ts +114 -0
- package/app/src/cms/settings-scroll.ts +10 -0
- package/app/src/cms/settings-search.ts +77 -0
- package/app/src/cms/settings-section.ts +38 -0
- package/app/src/cms/share.client.ts +27 -0
- package/app/src/cms/site-editing.ts +219 -0
- package/app/src/cms/site-editor.client.ts +1008 -0
- package/app/src/cms/site-editor.ts +99 -0
- package/app/src/cms/site-export.ts +60 -0
- package/app/src/cms/site-forms.ts +143 -0
- package/app/src/cms/site-import.ts +28 -0
- package/app/src/cms/site-session.ts +36 -0
- package/app/src/cms/site-taskbar.ts +77 -0
- package/app/src/cms/site-view.ts +1014 -0
- package/app/src/cms/site.ts +1322 -0
- package/app/src/cms/sitemaps.ts +131 -0
- package/app/src/cms/stat.client.ts +56 -0
- package/app/src/cms/style-controls.ts +252 -0
- package/app/src/cms/tabs.client.ts +36 -0
- package/app/src/cms/taskbar.ts +134 -0
- package/app/src/cms/term-icons.ts +10 -0
- package/app/src/cms/traffic.ts +26 -0
- package/app/src/cms/ui.ts +170 -0
- package/app/src/cms/updates.ts +124 -0
- package/app/src/cms/uploads.ts +26 -0
- package/app/src/cms/worker.ts +13 -0
- package/app/src/config/auth.ts +30 -0
- package/app/src/config/cms.ts +18 -0
- package/app/src/dashboard/access.ts +344 -0
- package/app/src/dashboard/agent-icons.ts +44 -0
- package/app/src/dashboard/app-passwords.ts +74 -0
- package/app/src/dashboard/avatar-field.ts +58 -0
- package/app/src/dashboard/bulk.ts +53 -0
- package/app/src/dashboard/head.ts +29 -0
- package/app/src/dashboard/icons.ts +15 -0
- package/app/src/dashboard/list-table.ts +120 -0
- package/app/src/dashboard/modules/roles.ts +15 -0
- package/app/src/dashboard/modules/sessions.ts +15 -0
- package/app/src/dashboard/modules/settings.ts +15 -0
- package/app/src/dashboard/modules/users.ts +18 -0
- package/app/src/dashboard/page.ts +67 -0
- package/app/src/dashboard/registry.ts +13 -0
- package/app/src/dashboard/session-list.ts +98 -0
- package/app/src/dashboard/tabs.ts +26 -0
- package/app/src/dashboard/time-ago.ts +16 -0
- package/app/src/dashboard/types.ts +40 -0
- package/app/src/dashboard/user-sections.ts +172 -0
- package/app/src/lib/permissions.ts +84 -0
- package/app/src/middlewares/auth.ts +117 -0
- package/app/src/pages/(site)/[...path]/index.ts +609 -0
- package/app/src/pages/(site)/feed/[...rest]/index.ts +13 -0
- package/app/src/pages/(site)/feed/index.ts +12 -0
- package/app/src/pages/(site)/index.ts +11 -0
- package/app/src/pages/(site)/indexnow/[file]/index.ts +18 -0
- package/app/src/pages/(site)/layout.ts +219 -0
- package/app/src/pages/(site)/llms.txt/index.ts +23 -0
- package/app/src/pages/(site)/manifest.webmanifest/index.ts +29 -0
- package/app/src/pages/(site)/media/[id]/[name]/index.ts +59 -0
- package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +115 -0
- package/app/src/pages/(site)/robots.txt/index.ts +29 -0
- package/app/src/pages/(site)/search/index.ts +36 -0
- package/app/src/pages/(site)/sitemap.xml/index.ts +26 -0
- package/app/src/pages/(site)/sitemaps/[file]/index.ts +33 -0
- package/app/src/pages/api/auth/session.ts +48 -0
- package/app/src/pages/api/cms/appearance/areas/[name].ts +12 -0
- package/app/src/pages/api/cms/appearance/areas/index.ts +6 -0
- package/app/src/pages/api/cms/appearance/locations/[location].ts +6 -0
- package/app/src/pages/api/cms/appearance/locations/index.ts +6 -0
- package/app/src/pages/api/cms/appearance/menus/[id].ts +12 -0
- package/app/src/pages/api/cms/appearance/menus/index.ts +13 -0
- package/app/src/pages/api/cms/appearance/themes/[name]/activate.ts +6 -0
- package/app/src/pages/api/cms/appearance/themes/index.ts +6 -0
- package/app/src/pages/api/cms/cache/purge.ts +6 -0
- package/app/src/pages/api/cms/collections/index.ts +6 -0
- package/app/src/pages/api/cms/commands/[plugin]/[command].ts +26 -0
- package/app/src/pages/api/cms/comments/[id].ts +9 -0
- package/app/src/pages/api/cms/comments/index.ts +126 -0
- package/app/src/pages/api/cms/comments/queue.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/autosave.ts +27 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/blocks/[block].ts +16 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/notes.ts +18 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/publish.ts +11 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/index.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/restore.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/index.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/unpublish.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry].ts +42 -0
- package/app/src/pages/api/cms/content/[collection]/index.ts +24 -0
- package/app/src/pages/api/cms/export/[collection].ts +37 -0
- package/app/src/pages/api/cms/forms/[slug]/index.ts +173 -0
- package/app/src/pages/api/cms/forms/[slug]/submissions/[submission]/files/[file].ts +25 -0
- package/app/src/pages/api/cms/forms/[slug]/submissions/export.ts +34 -0
- package/app/src/pages/api/cms/forms/[slug]/submissions/index.ts +24 -0
- package/app/src/pages/api/cms/import/[collection].ts +23 -0
- package/app/src/pages/api/cms/mcp.ts +29 -0
- package/app/src/pages/api/cms/me/index.ts +6 -0
- package/app/src/pages/api/cms/me/recent-blocks.ts +37 -0
- package/app/src/pages/api/cms/me/tokens/[id].ts +6 -0
- package/app/src/pages/api/cms/me/tokens/index.ts +13 -0
- package/app/src/pages/api/cms/media/[id].ts +6 -0
- package/app/src/pages/api/cms/media.ts +26 -0
- package/app/src/pages/api/cms/menus/[location].ts +14 -0
- package/app/src/pages/api/cms/network/sites/[id]/export.ts +15 -0
- package/app/src/pages/api/cms/network/sites/[id]/index.ts +9 -0
- package/app/src/pages/api/cms/network/sites/index.ts +14 -0
- package/app/src/pages/api/cms/notes/[id].ts +13 -0
- package/app/src/pages/api/cms/notes/index.ts +6 -0
- package/app/src/pages/api/cms/payments/webhook.ts +28 -0
- package/app/src/pages/api/cms/plugins/[name]/grant.ts +6 -0
- package/app/src/pages/api/cms/plugins/[name]/revoke.ts +6 -0
- package/app/src/pages/api/cms/plugins/index.ts +6 -0
- package/app/src/pages/api/cms/recovery.ts +29 -0
- package/app/src/pages/api/cms/redirects/index.ts +9 -0
- package/app/src/pages/api/cms/roles/index.ts +6 -0
- package/app/src/pages/api/cms/schema/[collection].ts +13 -0
- package/app/src/pages/api/cms/search.ts +16 -0
- package/app/src/pages/api/cms/settings/[group].ts +9 -0
- package/app/src/pages/api/cms/settings/index.ts +9 -0
- package/app/src/pages/api/cms/site-export.ts +34 -0
- package/app/src/pages/api/cms/taxonomies/index.ts +6 -0
- package/app/src/pages/api/cms/terms/[taxonomy]/[id].ts +12 -0
- package/app/src/pages/api/cms/terms/[taxonomy]/index.ts +9 -0
- package/app/src/pages/api/cms/uploads/[id]/complete.ts +15 -0
- package/app/src/pages/api/cms/uploads/[id]/index.ts +15 -0
- package/app/src/pages/api/cms/uploads/index.ts +26 -0
- package/app/src/pages/api/cms/users/[id]/index.ts +12 -0
- package/app/src/pages/api/cms/users/[id]/meta.ts +40 -0
- package/app/src/pages/api/cms/users/index.ts +12 -0
- package/app/src/pages/api/cms/webhooks/[id].ts +6 -0
- package/app/src/pages/api/cms/webhooks/index.ts +9 -0
- package/app/src/pages/auth/[provider]/callback.ts +11 -0
- package/app/src/pages/auth/[provider]/redirect.ts +9 -0
- package/app/src/pages/auth/forgot-password/index.ts +75 -0
- package/app/src/pages/auth/layout.ts +32 -0
- package/app/src/pages/auth/login/index.ts +198 -0
- package/app/src/pages/auth/magic/index.ts +68 -0
- package/app/src/pages/auth/register/index.ts +117 -0
- package/app/src/pages/auth/reset-password/index.ts +65 -0
- package/app/src/pages/auth/setup/index.ts +194 -0
- package/app/src/pages/auth/two-factor/index.ts +67 -0
- package/app/src/pages/auth/verify/index.ts +62 -0
- package/app/src/pages/dashboard/(cms)/appearance/customize/index.ts +263 -0
- package/app/src/pages/dashboard/(cms)/appearance/dashboard-menu/index.ts +241 -0
- package/app/src/pages/dashboard/(cms)/appearance/index.ts +89 -0
- package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +697 -0
- package/app/src/pages/dashboard/(cms)/appearance/menus/index.ts +145 -0
- package/app/src/pages/dashboard/(cms)/appearance/widgets/index.ts +279 -0
- package/app/src/pages/dashboard/(cms)/blocks/index.ts +84 -0
- package/app/src/pages/dashboard/(cms)/calendar/index.ts +92 -0
- package/app/src/pages/dashboard/(cms)/collections/[name]/index.ts +525 -0
- package/app/src/pages/dashboard/(cms)/collections/index.ts +72 -0
- package/app/src/pages/dashboard/(cms)/collections/new/index.ts +66 -0
- package/app/src/pages/dashboard/(cms)/comments/index.ts +237 -0
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +2382 -0
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +126 -0
- package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +693 -0
- package/app/src/pages/dashboard/(cms)/field-groups/[id]/index.ts +193 -0
- package/app/src/pages/dashboard/(cms)/field-groups/index.ts +65 -0
- package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/[submission]/index.ts +279 -0
- package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/index.ts +170 -0
- package/app/src/pages/dashboard/(cms)/forms/index.ts +171 -0
- package/app/src/pages/dashboard/(cms)/media/[id]/index.ts +317 -0
- package/app/src/pages/dashboard/(cms)/media/index.ts +156 -0
- package/app/src/pages/dashboard/(cms)/media/new/index.ts +9 -0
- package/app/src/pages/dashboard/(cms)/media/summary/index.ts +74 -0
- package/app/src/pages/dashboard/(cms)/my-sites/index.ts +63 -0
- package/app/src/pages/dashboard/(cms)/network/index.ts +53 -0
- package/app/src/pages/dashboard/(cms)/network/plugins/index.ts +110 -0
- package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +243 -0
- package/app/src/pages/dashboard/(cms)/network/sites/index.ts +186 -0
- package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +77 -0
- package/app/src/pages/dashboard/(cms)/network/themes/index.ts +82 -0
- package/app/src/pages/dashboard/(cms)/network/updates/index.ts +48 -0
- package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +176 -0
- package/app/src/pages/dashboard/(cms)/network/users/index.ts +174 -0
- package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +66 -0
- package/app/src/pages/dashboard/(cms)/plugins/index.ts +172 -0
- package/app/src/pages/dashboard/(cms)/profile/public/index.ts +105 -0
- package/app/src/pages/dashboard/(cms)/registrations/index.ts +70 -0
- package/app/src/pages/dashboard/(cms)/settings/index.ts +359 -0
- package/app/src/pages/dashboard/(cms)/settings/json/index.ts +202 -0
- package/app/src/pages/dashboard/(cms)/settings/layout.ts +67 -0
- package/app/src/pages/dashboard/(cms)/taxonomies/[name]/index.ts +85 -0
- package/app/src/pages/dashboard/(cms)/taxonomies/index.ts +98 -0
- package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/[id]/index.ts +244 -0
- package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/index.ts +148 -0
- package/app/src/pages/dashboard/(cms)/tools/activity/index.ts +94 -0
- package/app/src/pages/dashboard/(cms)/tools/automations/index.ts +131 -0
- package/app/src/pages/dashboard/(cms)/tools/cache/index.ts +92 -0
- package/app/src/pages/dashboard/(cms)/tools/export/index.ts +99 -0
- package/app/src/pages/dashboard/(cms)/tools/health/index.ts +189 -0
- package/app/src/pages/dashboard/(cms)/tools/jobs/index.ts +93 -0
- package/app/src/pages/dashboard/(cms)/tools/links/index.ts +115 -0
- package/app/src/pages/dashboard/(cms)/tools/redirects/index.ts +161 -0
- package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +124 -0
- package/app/src/pages/dashboard/(cms)/tools/schema/index.ts +54 -0
- package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +156 -0
- package/app/src/pages/dashboard/(cms)/tools/updates/index.ts +114 -0
- package/app/src/pages/dashboard/(cms)/tools/webhooks/index.ts +182 -0
- package/app/src/pages/dashboard/index.ts +214 -0
- package/app/src/pages/dashboard/layout.ts +320 -0
- package/app/src/pages/dashboard/profile/index.ts +211 -0
- package/app/src/pages/dashboard/profile/security/index.ts +255 -0
- package/app/src/pages/dashboard/roles/[id]/index.ts +116 -0
- package/app/src/pages/dashboard/roles/index.ts +134 -0
- package/app/src/pages/dashboard/roles/new/index.ts +95 -0
- package/app/src/pages/dashboard/sessions/index.ts +105 -0
- package/app/src/pages/dashboard/users/[id]/index.ts +472 -0
- package/app/src/pages/dashboard/users/index.ts +299 -0
- package/app/src/pages/dashboard/users/new/index.ts +123 -0
- package/app/src/passkeys.client.ts +18 -0
- package/app/src/plugins/default-theme/assets/cover.svg +31 -0
- package/app/src/plugins/default-theme/assets/logo.svg +8 -0
- package/app/src/plugins/default-theme/parts/comments.ts +66 -0
- package/app/src/plugins/default-theme/parts/list.ts +38 -0
- package/app/src/plugins/default-theme/parts/media.ts +15 -0
- package/app/src/plugins/default-theme/parts/options.ts +45 -0
- package/app/src/plugins/default-theme/plugin.json +275 -0
- package/app/src/plugins/default-theme/templates/archive.ts +14 -0
- package/app/src/plugins/default-theme/templates/entry-blank.ts +13 -0
- package/app/src/plugins/default-theme/templates/entry.ts +27 -0
- package/app/src/plugins/default-theme/templates/home.ts +8 -0
- package/app/src/plugins/default-theme/templates/layout.ts +40 -0
- package/app/src/plugins/default-theme/templates/not-found.ts +10 -0
- package/app/src/plugins/default-theme/templates/search.ts +32 -0
- package/app/src/services/rbac.ts +65 -0
- package/app/src/services/roles.ts +89 -0
- package/app/src/services/users.ts +173 -0
- package/package.json +123 -3
- package/src/automations.ts +95 -0
- package/src/bindings.ts +138 -0
- package/src/block-references.ts +239 -0
- package/src/block-shape.ts +155 -0
- package/src/blocks.ts +1157 -0
- package/src/cache.ts +54 -0
- package/src/checks.ts +198 -0
- package/src/cloudflare-workers.d.ts +13 -0
- package/src/cloudflare.ts +61 -0
- package/src/collab.ts +372 -0
- package/src/collections.ts +421 -0
- package/src/comments.ts +46 -0
- package/src/cron.ts +95 -0
- package/src/dashboard-menu.ts +105 -0
- package/src/diff.ts +113 -0
- package/src/editor-layout.ts +316 -0
- package/src/errors.ts +50 -0
- package/src/field-groups.ts +498 -0
- package/src/fields.ts +411 -0
- package/src/form-builder.ts +1053 -0
- package/src/forms.ts +109 -0
- package/src/highlight.ts +134 -0
- package/src/hooks.ts +510 -0
- package/src/icon-catalog.ts +55 -0
- package/src/icons.ts +128 -0
- package/src/images.ts +149 -0
- package/src/index.ts +100 -0
- package/src/isolate-core.ts +245 -0
- package/src/isolate.ts +19 -0
- package/src/isolation.ts +69 -0
- package/src/mail.ts +182 -0
- package/src/manifest.ts +476 -0
- package/src/media.ts +193 -0
- package/src/menus.ts +287 -0
- package/src/module.ts +32 -0
- package/src/modules/content.ts +64 -0
- package/src/modules/forms.ts +35 -0
- package/src/node.ts +66 -0
- package/src/notes.ts +237 -0
- package/src/permissions.ts +139 -0
- package/src/plugin-settings.ts +114 -0
- package/src/records.ts +56 -0
- package/src/redirects.ts +59 -0
- package/src/resource.ts +245 -0
- package/src/richtext.ts +402 -0
- package/src/schema-json.ts +112 -0
- package/src/search.ts +89 -0
- package/src/seo.ts +477 -0
- package/src/server/accounts.ts +418 -0
- package/src/server/ai.ts +33 -0
- package/src/server/api-tokens.ts +91 -0
- package/src/server/areas.ts +116 -0
- package/src/server/audit.ts +94 -0
- package/src/server/auth.ts +89 -0
- package/src/server/automations.ts +190 -0
- package/src/server/autosaves.ts +69 -0
- package/src/server/brand-icons.ts +50 -0
- package/src/server/brands.ts +86 -0
- package/src/server/budget.ts +97 -0
- package/src/server/cache.ts +104 -0
- package/src/server/capabilities.ts +333 -0
- package/src/server/cloudflare.ts +92 -0
- package/src/server/comments.ts +237 -0
- package/src/server/drafts.ts +176 -0
- package/src/server/field-groups.ts +88 -0
- package/src/server/files.ts +780 -0
- package/src/server/forms.ts +726 -0
- package/src/server/handoffs.ts +107 -0
- package/src/server/host-schema.ts +312 -0
- package/src/server/host.ts +2892 -0
- package/src/server/images.ts +34 -0
- package/src/server/index.ts +59 -0
- package/src/server/indexnow.ts +91 -0
- package/src/server/isolation.ts +183 -0
- package/src/server/locked.ts +45 -0
- package/src/server/mail.ts +93 -0
- package/src/server/markdown.ts +24 -0
- package/src/server/menus.ts +286 -0
- package/src/server/network-policy.ts +60 -0
- package/src/server/network.ts +665 -0
- package/src/server/notes.ts +275 -0
- package/src/server/outbox.ts +213 -0
- package/src/server/path-moves.ts +33 -0
- package/src/server/payments.ts +59 -0
- package/src/server/previews.ts +62 -0
- package/src/server/purge.ts +140 -0
- package/src/server/reconcile.ts +38 -0
- package/src/server/redirects.ts +183 -0
- package/src/server/repository.ts +1107 -0
- package/src/server/schedules.ts +105 -0
- package/src/server/schema.ts +562 -0
- package/src/server/security.ts +391 -0
- package/src/server/seed.ts +52 -0
- package/src/server/shared-fields.ts +34 -0
- package/src/server/site-export.ts +151 -0
- package/src/server/site-import.ts +482 -0
- package/src/server/site-search.ts +289 -0
- package/src/server/site-settings.ts +286 -0
- package/src/server/sites.ts +243 -0
- package/src/server/stores.ts +314 -0
- package/src/server/stripe.ts +173 -0
- package/src/server/taxonomies.ts +415 -0
- package/src/server/tokens.ts +25 -0
- package/src/server/traffic.ts +118 -0
- package/src/server/users.ts +653 -0
- package/src/server/webhooks.ts +245 -0
- package/src/settings-controls.ts +54 -0
- package/src/settings-document.ts +111 -0
- package/src/settings.ts +426 -0
- package/src/storage/cloudflare.ts +94 -0
- package/src/storage/index.ts +30 -0
- package/src/storage/node.ts +114 -0
- package/src/taxonomy.ts +51 -0
- package/src/theme.ts +1135 -0
- package/src/to-markdown.ts +179 -0
- package/src/updates.ts +126 -0
- package/src/version.ts +2 -0
- package/src/vite.d.ts +25 -0
- package/src/vite.js +199 -0
- package/src/webhooks.ts +107 -0
|
@@ -0,0 +1,2892 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The CMS host: resource registry, repositories, plugin hooks and commands, schema and
|
|
3
|
+
* grant activation, outbox, users and stores, all over one RomeDB binding.
|
|
4
|
+
*/
|
|
5
|
+
import type { UpdatesOptions } from '../updates';
|
|
6
|
+
import { createHookRegistry, type ActionHandler, type ActionPoint, type ActionReport, type ExtensionPoint, type FilterContext, type FilterHandler, type FilterPoint, type HookRegistry, type InvokeOptions } from '@cossackframework/core/hooks';
|
|
7
|
+
import type { StorageProvider } from '@cossackframework/core/storage';
|
|
8
|
+
import { ClientError, MAX_STATEMENTS, type RomeDB, type Statement, type Value, type WorkLimits } from '@cossackframework/romedb';
|
|
9
|
+
import { normalizeRichText, richTextBlocks, withRichTextBlocks } from '../richtext';
|
|
10
|
+
import { blockId, blockMedia, blockProblems, htmlBlocksChanged, textFieldProblem, validateBlocks, type Block, type BlockDeclaration } from '../blocks';
|
|
11
|
+
import { blocksShapeProblem, type FieldDeclaration } from '../fields';
|
|
12
|
+
import { collectionProblems, collectionResource, contentBlocks, entryUrl, extendCollection, languageName, LOCALE, translationGroupOf, orderedFields, RESERVED_FIELDS, type CollectionDefinition } from '../collections';
|
|
13
|
+
import type { EditorLayoutAddition } from '../editor-layout';
|
|
14
|
+
import { fieldGroupDeclarations, fieldGroupProblems, fieldVisibility, flattenGroupFields, groupsForTarget, metaProblems, withTarget, type FieldGroup, type FieldGroupTarget } from '../field-groups';
|
|
15
|
+
import { AUTHOR_FIELDS, collectionSeoProblems } from '../seo';
|
|
16
|
+
import { CmsFieldGroups } from './field-groups';
|
|
17
|
+
import { CmsError } from '../errors';
|
|
18
|
+
import type { CmsModule } from '../module';
|
|
19
|
+
import { analytics as analyticsGroup, appearance, cache as cacheGroup, dashboard as dashboardGroup, email as emailGroup, general, interfaceGroup, media, type SettingsGroup } from '../settings';
|
|
20
|
+
import { pluginSettingsGroupId } from '../plugin-settings';
|
|
21
|
+
import { assembleSiteTheme, entryTemplateChoices, layerPresets, siteThemeProblems, type ArchiveView, type SiteTheme, type EntryView, type SiteView, type ThemeData, type ThemeManifest, type ThemePresets , themeArea } from '../theme';
|
|
22
|
+
import type { MenuItem, ResolvedMenuItem } from '../menus';
|
|
23
|
+
import { recordTitle } from '../forms';
|
|
24
|
+
import type { RecordShape } from '../records';
|
|
25
|
+
import { taxonomyProblems, type TaxonomyDeclaration, type TermShape } from '../taxonomy';
|
|
26
|
+
import { isPluginPoint, manifestProblems, providedPoints, requestedGrants, UNRESTRICTED_GRANT, type CmsPluginManifest, type PluginCommand, type SlotLink } from '../manifest';
|
|
27
|
+
import { ANONYMOUS, evaluateRule, hasPermission, isNetworkAdmin, PERMISSIONS, principalId, systemPrincipal, type Principal } from '../permissions';
|
|
28
|
+
import { AVATAR_TYPES, mediaUrl } from '../media';
|
|
29
|
+
import { canonicalJson, declarationHash, resolveResource, type Resource, type ResourceAction, type ResourceDeclaration } from '../resource';
|
|
30
|
+
import { Outbox, type OutboxOptions } from './outbox';
|
|
31
|
+
import { JOIN_GROUP, ResourceRepository, type FieldFilter, type ListOptions, type OperationContext } from './repository';
|
|
32
|
+
import { migrate, nextGenerationStatement, planSchema, readCatalog, type MigrationReport, type SchemaPlan } from './schema';
|
|
33
|
+
import { FileService, type CmsFile, type FileServiceOptions, type ImageSettings, LIBRARY_KEYS } from './files';
|
|
34
|
+
import { CmsCache } from './cache';
|
|
35
|
+
import { imageWidths } from '../images';
|
|
36
|
+
|
|
37
|
+
import { HOST_STEPS, HOST_TABLES, hostSchemaMismatch, unknownHostSteps } from './host-schema';
|
|
38
|
+
import { SiteSearch, SITE_SEARCH, searchRebuild } from './site-search';
|
|
39
|
+
import { sharedFields } from './shared-fields';
|
|
40
|
+
import { pathsMoved, pathsMovedStatement } from './path-moves';
|
|
41
|
+
import { noteAnnounced, type NoteAnnouncedEvent } from './notes';
|
|
42
|
+
import { readPaged } from './budget';
|
|
43
|
+
import { isLockedRecord, lockedView } from './locked';
|
|
44
|
+
import { OPEN_POLICY, pluginState, readPolicy, type NetworkPluginState, type NetworkPolicy } from './network-policy';
|
|
45
|
+
import { CmsSettings } from './site-settings';
|
|
46
|
+
import { createAuthSessionStore, createJobStore, createNotificationStore, createOAuthStateStore, createSessionStore, type EndedSessions } from './stores';
|
|
47
|
+
import { CmsMenus } from './menus';
|
|
48
|
+
import { CmsAreas } from './areas';
|
|
49
|
+
import { CmsTaxonomies } from './taxonomies';
|
|
50
|
+
import { CmsUsers } from './users';
|
|
51
|
+
import { CmsAccounts } from './accounts';
|
|
52
|
+
import { CmsPreviews, type PreviewLink } from './previews';
|
|
53
|
+
import { CmsAutosaves, type Autosave } from './autosaves';
|
|
54
|
+
import { CmsDrafts } from './drafts';
|
|
55
|
+
import { CmsNotes } from './notes';
|
|
56
|
+
import { CmsRedirects } from './redirects';
|
|
57
|
+
import { CmsApiTokens, type ApiTokenScope } from './api-tokens';
|
|
58
|
+
import { CmsWebhooks } from './webhooks';
|
|
59
|
+
import { CmsIndexNow } from './indexnow';
|
|
60
|
+
import { CmsPurge, type CachePurger } from './purge';
|
|
61
|
+
import { CmsTraffic } from './traffic';
|
|
62
|
+
import type { WebhookEvent } from '../webhooks';
|
|
63
|
+
import { afterCommit, commentBeforeSave, EXTENSION_POINTS, formSubmitted, menuBeforeSave, pluginJob, termBeforeSave, type FormSubmittedEvent, type ResourceEvent, type WriteActor, paymentEvent, registrationDraftOf, userBeforeRegister, type RegistrationDraft, type UserRef, type UserRegisteredEvent, type UserSignedInEvent } from '../hooks';
|
|
64
|
+
import { ISOLATE_PROTOCOL, type IsolateCall, type IsolatePoint, type IsolateRun } from '../isolation';
|
|
65
|
+
import { serveIsolatedCall, type IsolatedPluginCode, type IsolatedWork, type PluginRunner } from './isolation';
|
|
66
|
+
import { CmsForms } from './forms';
|
|
67
|
+
import { siteMailer, type CmsMailer, type MailTransport } from './mail';
|
|
68
|
+
import { pluginCapabilities, type PluginAi, type PluginCache, type PluginFiles, type PluginJobContext, type PluginJobs, type PluginMail, type PluginPayments, type PluginSecrets, type PluginUsers } from './capabilities';
|
|
69
|
+
import { CmsSchedules, type DueSchedule } from './schedules';
|
|
70
|
+
import { CmsAudit, unrestrictedGrantAudit } from './audit';
|
|
71
|
+
import type { AiProvider } from './ai';
|
|
72
|
+
import type { PaymentsProvider } from './payments';
|
|
73
|
+
import type { PaymentEvent } from '../hooks';
|
|
74
|
+
import { siteBindingScope, type BindingScopes } from '../bindings';
|
|
75
|
+
import { CmsAutomations } from './automations';
|
|
76
|
+
import { CmsComments, collectionDeleted, collectionDeletedStatement } from './comments';
|
|
77
|
+
import { CmsSecurity } from './security';
|
|
78
|
+
import type { ImageTransformer } from './images';
|
|
79
|
+
import { checkComment, COMMENT_STATUSES, type CommentShape, type CommentStatus } from '../comments';
|
|
80
|
+
import { sha256Hex } from './tokens';
|
|
81
|
+
import type { SiteSettings } from '../settings';
|
|
82
|
+
import { getClientIp, uuidv7 } from '@cossackframework/core';
|
|
83
|
+
|
|
84
|
+
/** Structural plugin registration, as `@cossackframework/framework/plugins` provides it. */
|
|
85
|
+
export interface PluginRegistrationLike {
|
|
86
|
+
readonly name: string;
|
|
87
|
+
readonly version: string;
|
|
88
|
+
readonly manifest?: { readonly [field: string]: unknown };
|
|
89
|
+
readonly module?: { readonly [name: string]: unknown } | null;
|
|
90
|
+
readonly ui?: { readonly [name: string]: unknown } | null;
|
|
91
|
+
/** The plugin's `templates/*.ts` modules by file stem; a theme's templates. */
|
|
92
|
+
readonly templates?: { readonly [stem: string]: { readonly [name: string]: unknown } };
|
|
93
|
+
/** URLs of the plugin's images by path, such as `assets/logo.png`. */
|
|
94
|
+
readonly assets?: { readonly [path: string]: string };
|
|
95
|
+
/** Where the server code runs, when the application isolates plugins: see `@cossackframework/framework/plugins`. */
|
|
96
|
+
readonly isolation?: {
|
|
97
|
+
readonly mode: 'isolated' | 'app';
|
|
98
|
+
readonly reason?: string;
|
|
99
|
+
readonly code?: string;
|
|
100
|
+
readonly hash?: string;
|
|
101
|
+
readonly bytes?: number;
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export type { CmsModule };
|
|
106
|
+
|
|
107
|
+
export interface CmsOptions {
|
|
108
|
+
/** The site's database. */
|
|
109
|
+
readonly db: RomeDB;
|
|
110
|
+
/** The site runs in development: webhooks may use plain HTTP and go to this machine or a private network. */
|
|
111
|
+
readonly localWebhooks?: boolean;
|
|
112
|
+
/**
|
|
113
|
+
* The `fetch` webhook deliveries and pings use, default `fetch`. On Node pass `publicOnlyFetch`
|
|
114
|
+
* from `@cossackframework/cms/node` (unless `localWebhooks`), which refuses names that resolve
|
|
115
|
+
* to this machine or a private network; Workers' own `fetch` cannot reach them.
|
|
116
|
+
*/
|
|
117
|
+
readonly webhookFetch?: typeof globalThis.fetch;
|
|
118
|
+
/**
|
|
119
|
+
* The network database: accounts and what signs them in (second factors, reset tokens,
|
|
120
|
+
* application passwords, the main site's sessions). It is the main site's database; default `db`.
|
|
121
|
+
*/
|
|
122
|
+
readonly network?: RomeDB;
|
|
123
|
+
/**
|
|
124
|
+
* Announce a new or resolved note (its webhooks and emails). It runs from the outbox job the
|
|
125
|
+
* note's write queued, so a note that was saved is announced even after a crash.
|
|
126
|
+
*/
|
|
127
|
+
readonly announceNote?: (host: CmsHost, event: NoteAnnouncedEvent) => Promise<void>;
|
|
128
|
+
/** Network sessions ended: end the child sessions that sites made from them. */
|
|
129
|
+
readonly sessionsEnded?: (ended: EndedSessions) => Promise<void>;
|
|
130
|
+
/** This site's ID in the network; default `main`. */
|
|
131
|
+
readonly site?: string;
|
|
132
|
+
/** Application resources; owner defaults to `app`. */
|
|
133
|
+
readonly resources?: readonly ResourceDeclaration[];
|
|
134
|
+
readonly modules?: readonly CmsModule[];
|
|
135
|
+
/** Rendered plugins from the static registry. */
|
|
136
|
+
readonly plugins?: readonly PluginRegistrationLike[];
|
|
137
|
+
readonly hooks?: HookRegistry;
|
|
138
|
+
readonly now?: () => number;
|
|
139
|
+
readonly workLimits?: { readonly read?: WorkLimits; readonly write?: WorkLimits };
|
|
140
|
+
/** How long schema and grant activation stays cached. Default 30 seconds. */
|
|
141
|
+
readonly activationTtlMs?: number;
|
|
142
|
+
readonly outbox?: OutboxOptions;
|
|
143
|
+
/** Network access for plugins, checked against granted hosts. Default `globalThis.fetch`. */
|
|
144
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
145
|
+
/**
|
|
146
|
+
* Runs isolated plugins' server code in Workers of their own (`workerLoaderRunner` on
|
|
147
|
+
* Cloudflare). Without it an isolated plugin cannot run, and stays inactive with that reason.
|
|
148
|
+
*/
|
|
149
|
+
readonly runner?: PluginRunner | null;
|
|
150
|
+
/** The site's public origin, such as `https://example.com` (`APP_URL`), for IndexNow pings. */
|
|
151
|
+
readonly siteUrl?: string | (() => string | undefined);
|
|
152
|
+
/** The caches in front of the site that changes purge: the Cloudflare purger, or another CDN's. Plugins add theirs as `cms.cache.purge` handlers. */
|
|
153
|
+
readonly purgers?: readonly CachePurger[];
|
|
154
|
+
/** Object storage for media: R2 on Workers, S3 or a local directory on Node. Without it, `files` is null. */
|
|
155
|
+
readonly storage?: StorageProvider;
|
|
156
|
+
readonly files?: FileServiceOptions;
|
|
157
|
+
/** Makes resized image variants: the Images binding on Workers, sharp on Node. */
|
|
158
|
+
readonly images?: ImageTransformer;
|
|
159
|
+
/** Taxonomies beyond those of the modules. */
|
|
160
|
+
readonly taxonomies?: readonly TaxonomyDeclaration[];
|
|
161
|
+
/** Block types beyond those of the modules and plugins. */
|
|
162
|
+
readonly blocks?: readonly BlockDeclaration[];
|
|
163
|
+
/** Settings groups beyond General, Media and those of the modules. */
|
|
164
|
+
readonly settings?: readonly SettingsGroup[];
|
|
165
|
+
/**
|
|
166
|
+
* First path segments the application routes itself, which entries at the site root
|
|
167
|
+
* cannot take as slugs. Default: api, auth, dashboard, feed, media, preview and search.
|
|
168
|
+
*/
|
|
169
|
+
readonly reservedPaths?: readonly string[];
|
|
170
|
+
/** How long a theme loader may run before the page renders without its data. Default 1500 ms. */
|
|
171
|
+
readonly themeLoaderTimeoutMs?: number;
|
|
172
|
+
/** The largest JSON a theme loader may return, in characters. Default 65536. */
|
|
173
|
+
readonly themeDataLimit?: number;
|
|
174
|
+
/**
|
|
175
|
+
* Sends the site's emails: Cloudflare's `EMAIL` binding, the Node adapter's SMTP sender, or
|
|
176
|
+
* any `{ send(message) }` taking `{ to, from, subject, text, html, replyTo? }`. The host lays
|
|
177
|
+
* each message out as HTML (Settings → Email) and runs `cms.mail.before-send` first. Without
|
|
178
|
+
* it no email is sent.
|
|
179
|
+
*/
|
|
180
|
+
readonly mail?: MailTransport;
|
|
181
|
+
/** The sender of the site's emails. Default `no-reply@example.com`. */
|
|
182
|
+
readonly mailFrom?: string;
|
|
183
|
+
/**
|
|
184
|
+
* OAuth providers the sign-in page offers (`github`, `google`, `gitlab`, `facebook`,
|
|
185
|
+
* `microsoft`). Each reads `<PROVIDER>_CLIENT_ID` and `<PROVIDER>_CLIENT_SECRET`, and
|
|
186
|
+
* `OAUTH_SECRET` signs the state. Default: none.
|
|
187
|
+
*/
|
|
188
|
+
readonly oauth?: readonly string[];
|
|
189
|
+
/** Bindings plugins name in `permissions.secrets`, read when a granted plugin asks (`context.secrets.get`). Default: none. */
|
|
190
|
+
readonly secrets?: (name: string) => string | undefined;
|
|
191
|
+
/** The application's bindings, for a plugin granted unrestricted access (`context.unrestricted()`). Default: none. */
|
|
192
|
+
readonly env?: Readonly<Record<string, unknown>>;
|
|
193
|
+
/** The AI provider for the editor's assistant and plugins with `ai`; none without it. */
|
|
194
|
+
readonly ai?: AiProvider;
|
|
195
|
+
/** The payments provider for plugins with `payments`; its webhooks come through `receivePayment()`. */
|
|
196
|
+
readonly payments?: PaymentsProvider;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** The site's languages: the others under `/<code>/`, and the default one too when `prefixDefault`. */
|
|
200
|
+
export interface SiteLanguages {
|
|
201
|
+
readonly default: string;
|
|
202
|
+
readonly others: readonly string[];
|
|
203
|
+
readonly all: readonly string[];
|
|
204
|
+
/** More than one language. */
|
|
205
|
+
readonly multilingual: boolean;
|
|
206
|
+
/** Settings → Languages → Language in URLs is *Every language*: the default's pages are under `/<code>/` too. */
|
|
207
|
+
readonly prefixDefault: boolean;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** A theme from a rendered plugin. */
|
|
211
|
+
export interface ThemeInfo {
|
|
212
|
+
/** The plugin's name. */
|
|
213
|
+
readonly name: string;
|
|
214
|
+
readonly version: string;
|
|
215
|
+
readonly label: string;
|
|
216
|
+
readonly description: string;
|
|
217
|
+
/** From the plugin's manifest; null when it names none. */
|
|
218
|
+
readonly author: PluginAuthorView | null;
|
|
219
|
+
readonly locations: readonly { readonly name: string; readonly label: string }[];
|
|
220
|
+
/** Its widget areas, its parent's first, each with the blocks shown until the site saves its own. */
|
|
221
|
+
readonly areas: readonly { readonly name: string; readonly label: string; readonly defaults: readonly Block[] }[];
|
|
222
|
+
/** The theme it extends, or null. */
|
|
223
|
+
readonly parent: string | null;
|
|
224
|
+
/** Image URLs from the plugin's assets, or null for the default artwork. */
|
|
225
|
+
readonly logo: string | null;
|
|
226
|
+
readonly cover: string | null;
|
|
227
|
+
/** The settings group of its options (its parent's and its own), named after the plugin, or null. */
|
|
228
|
+
readonly options: SettingsGroup | null;
|
|
229
|
+
/** Its presets over its parent's, slug by slug; `resolvePresets` adds the defaults and the site's changes. */
|
|
230
|
+
readonly presets: ThemePresets;
|
|
231
|
+
/** Why the theme cannot be used; empty when it can. */
|
|
232
|
+
readonly problems: readonly string[];
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export interface CommandContext {
|
|
236
|
+
readonly principal: Principal;
|
|
237
|
+
readonly signal?: AbortSignal;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export type CommandHandler = (input: { readonly [name: string]: string | number | boolean }, context: CommandContext) => unknown | Promise<unknown>;
|
|
241
|
+
|
|
242
|
+
/** What a plugin's `server.ts` `register()` receives. Everything is limited to the manifest and its grant. */
|
|
243
|
+
export interface PluginContext {
|
|
244
|
+
readonly name: string;
|
|
245
|
+
readonly version: string;
|
|
246
|
+
/** Resource IDs the plugin declares. */
|
|
247
|
+
readonly resources: readonly string[];
|
|
248
|
+
readonly hooks: {
|
|
249
|
+
/** Handle a point the manifest lists in `hooks`: the CMS's own or one another plugin provides. */
|
|
250
|
+
addAction<P>(point: ActionPoint<P>, handler: ActionHandler<P>, options?: { priority?: number }): void;
|
|
251
|
+
addFilter<V, I>(point: FilterPoint<V, I>, handler: FilterHandler<V, I>, options?: { priority?: number }): void;
|
|
252
|
+
/**
|
|
253
|
+
* A point by name: one the manifest lists in `hooks` or `provides`, as the host built it
|
|
254
|
+
* from its provider's declaration. Cast it to the payload types the provider documents.
|
|
255
|
+
*/
|
|
256
|
+
point<P>(name: string, kind: 'action'): ActionPoint<P>;
|
|
257
|
+
point<V, I = undefined>(name: string, kind: 'filter'): FilterPoint<V, I>;
|
|
258
|
+
/** Run the handlers of a point the plugin provides. Nothing runs while the plugin is inactive. */
|
|
259
|
+
doAction<P>(point: ActionPoint<P>, payload: P, options?: InvokeOptions): Promise<ActionReport>;
|
|
260
|
+
applyFilters<V, I>(point: FilterPoint<V, I>, value: V, input: I, options?: InvokeOptions): Promise<V>;
|
|
261
|
+
};
|
|
262
|
+
/** Handlers for the manifest's commands: `cossack <plugin>:<command>`. */
|
|
263
|
+
readonly commands: { add(name: string, handler: CommandHandler): void };
|
|
264
|
+
/** Data access limited to the plugin's own resources and its granted ones. */
|
|
265
|
+
readonly cms: PluginCms;
|
|
266
|
+
/** Own declared settings, with defaults. Reads require the plugin to be active. */
|
|
267
|
+
readonly settings: {
|
|
268
|
+
get(name: string): Promise<unknown>;
|
|
269
|
+
all(): Promise<Readonly<Record<string, unknown>>>;
|
|
270
|
+
};
|
|
271
|
+
/** `fetch` limited to the manifest's granted network hosts. */
|
|
272
|
+
readonly fetch: typeof globalThis.fetch;
|
|
273
|
+
/** Library files the plugin owns; needs `permissions.files`. */
|
|
274
|
+
readonly files: PluginFiles;
|
|
275
|
+
/** Email from the site's sender; needs `permissions.mail`. */
|
|
276
|
+
readonly mail: PluginMail;
|
|
277
|
+
/** Handlers for jobs queued later and for the manifest's `schedules`; needs `permissions.jobs`. */
|
|
278
|
+
readonly jobs: PluginJobs;
|
|
279
|
+
/** The site's members; needs `permissions.users`. */
|
|
280
|
+
readonly users: PluginUsers;
|
|
281
|
+
/** A namespace in the site's cache; needs `permissions.cache`. */
|
|
282
|
+
readonly cache: PluginCache;
|
|
283
|
+
/** The bindings named in `permissions.secrets`. */
|
|
284
|
+
readonly secrets: PluginSecrets;
|
|
285
|
+
/** The application's AI provider; needs `permissions.ai`. */
|
|
286
|
+
readonly ai: PluginAi;
|
|
287
|
+
/** Checkouts with the application's payments provider; needs `permissions.payments`. */
|
|
288
|
+
readonly payments: PluginPayments;
|
|
289
|
+
/**
|
|
290
|
+
* Everything, with no limits: needs `permissions.unrestricted`, and is refused until the
|
|
291
|
+
* plugin is active and a network admin has granted it. The grant also lifts the limits of
|
|
292
|
+
* the members above.
|
|
293
|
+
*/
|
|
294
|
+
readonly unrestricted: () => Promise<PluginUnrestricted>;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** What `context.unrestricted()` gives a plugin. Nothing here checks anything. */
|
|
298
|
+
export interface PluginUnrestricted {
|
|
299
|
+
/** The site's database with no access rules: `read` and `write` take RomeQL statements. */
|
|
300
|
+
readonly db: RomeDB;
|
|
301
|
+
/** The whole host: repositories, accounts, settings, files and the outbox. */
|
|
302
|
+
readonly host: CmsHost;
|
|
303
|
+
/** Every binding and secret of the application, including what reaches other sites' databases. */
|
|
304
|
+
readonly env: Readonly<Record<string, unknown>>;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export interface PluginCms {
|
|
308
|
+
resource(id: string): PluginResource;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* What every theme loader receives, as one object it destructures:
|
|
313
|
+
* `({ entry, cms, principal }) => ...`. Reads go through the plugin's grants as the visitor.
|
|
314
|
+
*/
|
|
315
|
+
export interface ThemeLoaderContext {
|
|
316
|
+
/** The theme plugin's repositories: its own resources and its granted ones. */
|
|
317
|
+
readonly cms: PluginCms;
|
|
318
|
+
/** The visitor; pass it to every read, such as `cms.resource(id).list(query, { principal })`. */
|
|
319
|
+
readonly principal: Principal;
|
|
320
|
+
/** Aborts when the loader runs out of time. */
|
|
321
|
+
readonly signal: AbortSignal;
|
|
322
|
+
/** The active theme's option values. */
|
|
323
|
+
readonly options: { readonly [name: string]: unknown };
|
|
324
|
+
/** The page's language. */
|
|
325
|
+
readonly locale: string;
|
|
326
|
+
/** The loader's key, such as `entry-projects`. */
|
|
327
|
+
readonly template: string;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** The `layout` loader's context: the site, as the layout template gets it. */
|
|
331
|
+
export interface LayoutLoaderContext extends ThemeLoaderContext {
|
|
332
|
+
readonly site: SiteView;
|
|
333
|
+
}
|
|
334
|
+
/** An entry loader's context (`entry`, `entry-<collection>`, a chosen `entry-*`). */
|
|
335
|
+
export interface EntryLoaderContext extends ThemeLoaderContext {
|
|
336
|
+
readonly entry: EntryView;
|
|
337
|
+
}
|
|
338
|
+
/** A list loader's context (`archive`, `home`, `search`, `term`, `author`, `not-found`). */
|
|
339
|
+
export interface ArchiveLoaderContext extends ThemeLoaderContext {
|
|
340
|
+
readonly view: ArchiveView;
|
|
341
|
+
}
|
|
342
|
+
/** What a loader reads: the layout's site, the page's entry or the page's list. */
|
|
343
|
+
export type ThemeLoaderInput = { readonly site: SiteView } | { readonly entry: EntryView } | { readonly view: ArchiveView };
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* A theme loader, exported from the theme's `server.ts` as `loaders[<template>]`, with the key
|
|
347
|
+
* its template gets: `layout` the `site`, entry loaders the `entry`, list loaders the `view`. It
|
|
348
|
+
* returns plain JSON, which templates read as `helpers.data`.
|
|
349
|
+
*/
|
|
350
|
+
export type ThemeLoader = { bivarianceHack(context: LayoutLoaderContext | EntryLoaderContext | ArchiveLoaderContext): unknown }['bivarianceHack'];
|
|
351
|
+
export type ThemeLoaders = { readonly [template: string]: ThemeLoader };
|
|
352
|
+
|
|
353
|
+
export type PluginResource = Pick<ResourceRepository, 'get' | 'list' | 'count' | 'search' | 'create' | 'update' | 'delete'>;
|
|
354
|
+
|
|
355
|
+
export interface PluginStatus {
|
|
356
|
+
readonly name: string;
|
|
357
|
+
readonly version: string;
|
|
358
|
+
readonly description: string;
|
|
359
|
+
/** From the manifest; null when it names none. */
|
|
360
|
+
readonly author: PluginAuthorView | null;
|
|
361
|
+
/** Image URLs from the plugin's assets, or null for the default artwork. */
|
|
362
|
+
readonly logo: string | null;
|
|
363
|
+
readonly cover: string | null;
|
|
364
|
+
/** Only a theme: nothing to grant, managed under Appearance. */
|
|
365
|
+
readonly themeOnly: boolean;
|
|
366
|
+
/** Asks for unrestricted access: the dashboard warns, and granting it takes a separate yes. */
|
|
367
|
+
readonly unrestricted: boolean;
|
|
368
|
+
/**
|
|
369
|
+
* Where its server code runs: `isolated` in a Worker of its own, where its permissions are
|
|
370
|
+
* enforced, or `app`, where the build's checks are all that holds it (specs/cms-plugin-isolation.md).
|
|
371
|
+
*/
|
|
372
|
+
readonly runtime: 'isolated' | 'app';
|
|
373
|
+
/** Why it runs in the application, when the build said. */
|
|
374
|
+
readonly runtimeReason?: string;
|
|
375
|
+
readonly active: boolean;
|
|
376
|
+
readonly reason?: string;
|
|
377
|
+
/** Grants the manifest requests that are not granted yet. */
|
|
378
|
+
readonly missing: readonly string[];
|
|
379
|
+
/** Everything the manifest requests, for a network admin's approval. */
|
|
380
|
+
readonly requests: readonly string[];
|
|
381
|
+
/** What the network decides: active on every site, the site's choice, or hidden. */
|
|
382
|
+
readonly network: NetworkPluginState;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
export interface ActivationStatus {
|
|
386
|
+
readonly resources: { readonly id: string; readonly active: boolean }[];
|
|
387
|
+
readonly plugins: readonly PluginStatus[];
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/** How long an isolated command or job may run; hooks keep their point's deadline. */
|
|
391
|
+
const ISOLATED_WORK_MS = 60_000;
|
|
392
|
+
|
|
393
|
+
/** The bundle of a plugin the build isolated, or null when its server code runs in the application. */
|
|
394
|
+
function isolatedCode(registration: PluginRegistrationLike): IsolatedPluginCode | null {
|
|
395
|
+
const isolation = registration.isolation;
|
|
396
|
+
return isolation?.mode === 'isolated' && typeof isolation.code === 'string' && typeof isolation.hash === 'string'
|
|
397
|
+
? { name: registration.name, version: registration.version, code: isolation.code, hash: isolation.hash } : null;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
interface HostedPlugin {
|
|
401
|
+
readonly registration: PluginRegistrationLike;
|
|
402
|
+
readonly manifest: CmsPluginManifest;
|
|
403
|
+
readonly problems: readonly string[];
|
|
404
|
+
readonly resources: readonly string[];
|
|
405
|
+
readonly requested: readonly string[];
|
|
406
|
+
readonly commands: Map<string, CommandHandler>;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
interface Activation {
|
|
410
|
+
readonly hashes: ReadonlyMap<string, string>;
|
|
411
|
+
readonly grants: ReadonlyMap<string, ReadonlySet<string>>;
|
|
412
|
+
/** Host schema versions in the ledger; empty before setup. */
|
|
413
|
+
readonly hostVersions: ReadonlySet<number>;
|
|
414
|
+
/** The network's plugin and theme states. */
|
|
415
|
+
readonly policy: NetworkPolicy;
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Every plugin needs this grant; disabling a plugin removes it with the others. */
|
|
419
|
+
export const PLUGIN_ENABLED = 'plugin:enabled';
|
|
420
|
+
|
|
421
|
+
/** Where an account and what signs it in live: the site's own database, or the network's. */
|
|
422
|
+
export interface AccountStores {
|
|
423
|
+
readonly kind: 'site' | 'network';
|
|
424
|
+
readonly accounts: CmsAccounts;
|
|
425
|
+
readonly security: CmsSecurity;
|
|
426
|
+
readonly apiTokens: CmsApiTokens;
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
export class CmsHost {
|
|
430
|
+
readonly db: RomeDB;
|
|
431
|
+
/** The network database; the same as `db` on the main site. */
|
|
432
|
+
readonly network: RomeDB;
|
|
433
|
+
/** This site's ID in the network: `main`, or the registry ID. */
|
|
434
|
+
readonly site: string;
|
|
435
|
+
readonly hooks: HookRegistry;
|
|
436
|
+
/** Network accounts: who signs in on the network host, on the network database. */
|
|
437
|
+
readonly accounts: CmsAccounts;
|
|
438
|
+
/**
|
|
439
|
+
* Site accounts: people who sign in on this site only, on its own database, with their own
|
|
440
|
+
* second factors, passkeys and application passwords. Null on the main site, whose accounts
|
|
441
|
+
* are the network's.
|
|
442
|
+
*/
|
|
443
|
+
readonly siteAccounts: CmsAccounts | null;
|
|
444
|
+
/** This site's members and roles. */
|
|
445
|
+
readonly users: CmsUsers;
|
|
446
|
+
readonly outbox: Outbox;
|
|
447
|
+
readonly authSessions: ReturnType<typeof createAuthSessionStore>;
|
|
448
|
+
readonly oauthStates: ReturnType<typeof createOAuthStateStore>;
|
|
449
|
+
readonly sessions: ReturnType<typeof createSessionStore>;
|
|
450
|
+
readonly taxonomies: CmsTaxonomies;
|
|
451
|
+
readonly settings: CmsSettings;
|
|
452
|
+
readonly menus: CmsMenus;
|
|
453
|
+
/** Widget areas of themes: block lists edited under Appearance → Widgets. */
|
|
454
|
+
readonly areas: CmsAreas;
|
|
455
|
+
/** Field groups: meta boxes attached to collections, taxonomies, users and menu items. */
|
|
456
|
+
readonly fieldGroups: CmsFieldGroups;
|
|
457
|
+
readonly previews: CmsPreviews;
|
|
458
|
+
readonly autosaves: CmsAutosaves;
|
|
459
|
+
/** Shared drafts of entries edited together, one per entry. */
|
|
460
|
+
readonly drafts: CmsDrafts;
|
|
461
|
+
/** Editors' review notes on entries, fields, blocks and passages. */
|
|
462
|
+
readonly notes: CmsNotes;
|
|
463
|
+
readonly redirects: CmsRedirects;
|
|
464
|
+
readonly apiTokens: CmsApiTokens;
|
|
465
|
+
readonly webhooks: CmsWebhooks;
|
|
466
|
+
readonly indexnow: CmsIndexNow;
|
|
467
|
+
/** Purges of the caches in front of the site, queued by changes and sent from the outbox. */
|
|
468
|
+
readonly purge: CmsPurge;
|
|
469
|
+
/** The site's search index over what visitors may read, kept with each entry write. */
|
|
470
|
+
readonly siteSearch: SiteSearch;
|
|
471
|
+
readonly traffic: CmsTraffic;
|
|
472
|
+
readonly comments: CmsComments;
|
|
473
|
+
/** Forms' submissions: taking them, notifications, and handling them in the dashboard. */
|
|
474
|
+
readonly forms: CmsForms;
|
|
475
|
+
/**
|
|
476
|
+
* Sends email as the site, when the application gave a transport (`createCMS({ mail })`);
|
|
477
|
+
* null skips every email. Each message gets the HTML layout and `cms.mail.before-send`; say
|
|
478
|
+
* what it is with `kind`.
|
|
479
|
+
*/
|
|
480
|
+
readonly mail: CmsMailer | null;
|
|
481
|
+
/** The sender of the emails the CMS sends. */
|
|
482
|
+
readonly mailFrom: string;
|
|
483
|
+
/** The OAuth providers the sign-in page offers. */
|
|
484
|
+
readonly oauth: readonly string[];
|
|
485
|
+
/** Plugin schedules: `tick()` from maintenance queues the due occurrences as jobs. */
|
|
486
|
+
readonly schedules: CmsSchedules;
|
|
487
|
+
/** The audit trail of writes, for Tools → Activity. */
|
|
488
|
+
readonly audit: CmsAudit;
|
|
489
|
+
/** The application's AI provider, or null. */
|
|
490
|
+
readonly ai: AiProvider | null;
|
|
491
|
+
/** The application's payments provider, or null. */
|
|
492
|
+
readonly payments: PaymentsProvider | null;
|
|
493
|
+
/** Automations: emails and webhooks run from the site's events (Tools → Automations). */
|
|
494
|
+
readonly automations: CmsAutomations;
|
|
495
|
+
readonly #secrets: (name: string) => string | undefined;
|
|
496
|
+
readonly #env: Readonly<Record<string, unknown>>;
|
|
497
|
+
/** Second factors and passkeys of network accounts, on the network database. */
|
|
498
|
+
readonly security: CmsSecurity;
|
|
499
|
+
/** Second factors and passkeys of site accounts; null on the main site. */
|
|
500
|
+
readonly siteSecurity: CmsSecurity | null;
|
|
501
|
+
/** Application passwords of site accounts; null on the main site. */
|
|
502
|
+
readonly siteApiTokens: CmsApiTokens | null;
|
|
503
|
+
/** Media files, when the host has object storage. */
|
|
504
|
+
readonly files: FileService | null;
|
|
505
|
+
/** A cache shared by every isolate, on RomeDB: values slow to compute, such as the library's summary. */
|
|
506
|
+
readonly cache: CmsCache;
|
|
507
|
+
readonly readLimits: WorkLimits;
|
|
508
|
+
readonly writeLimits: WorkLimits;
|
|
509
|
+
/** Increments on every committed mutation, so request middleware can schedule delivery. */
|
|
510
|
+
outboxWrites = 0;
|
|
511
|
+
/** Code-declared resources: modules, the application and plugins. */
|
|
512
|
+
readonly #static = new Map<string, Resource>();
|
|
513
|
+
/** Static resources and the current collections. */
|
|
514
|
+
#resources = new Map<string, Resource>();
|
|
515
|
+
readonly #repositories = new Map<string, ResourceRepository>();
|
|
516
|
+
readonly #plugins = new Map<string, HostedPlugin>();
|
|
517
|
+
readonly #runner: PluginRunner | null;
|
|
518
|
+
/** Isolated plugins: the context the bridge serves, and the bundle the runner loads. */
|
|
519
|
+
readonly #isolated = new Map<string, { readonly context: PluginContext; readonly code: IsolatedPluginCode }>();
|
|
520
|
+
/** Extension points plugins provide, by name, built from their manifests. */
|
|
521
|
+
readonly #pluginPoints = new Map<string, { readonly point: ExtensionPoint; readonly plugin: string }>();
|
|
522
|
+
readonly #builtinCollections = new Map<string, CollectionDefinition>();
|
|
523
|
+
readonly #builtinTaxonomies = new Map<string, TaxonomyDeclaration>();
|
|
524
|
+
#collections = new Map<string, CollectionDefinition>();
|
|
525
|
+
/** Stored field groups, as last loaded; `#apply` merges their fields into the targets. */
|
|
526
|
+
#groups: readonly FieldGroup[] = [];
|
|
527
|
+
#taxonomies = new Map<string, TaxonomyDeclaration>();
|
|
528
|
+
readonly #blocks = new Map<string, BlockDeclaration & { readonly plugin?: string }>();
|
|
529
|
+
readonly #themes = new Map<string, ThemeInfo>();
|
|
530
|
+
/** Plugins that are active, as of the last `ready()` or grant: their collections are on the site. */
|
|
531
|
+
#activePlugins = new Set<string>();
|
|
532
|
+
readonly #reservedPaths: ReadonlySet<string>;
|
|
533
|
+
readonly #now: () => number;
|
|
534
|
+
readonly #activationTtl: number;
|
|
535
|
+
readonly #fetch: typeof globalThis.fetch;
|
|
536
|
+
readonly #loaderTimeout: number;
|
|
537
|
+
readonly #dataLimit: number;
|
|
538
|
+
#activation: { at: number; state: Promise<Activation> } | undefined;
|
|
539
|
+
/** The active theme's field groups are being stored: `#refreshPlugins` runs again meanwhile and must not start over. */
|
|
540
|
+
#seedingTheme = false;
|
|
541
|
+
#definitions: { at: number; state: Promise<void> } | undefined;
|
|
542
|
+
#upgrading: Promise<void> | undefined;
|
|
543
|
+
#installed = false;
|
|
544
|
+
|
|
545
|
+
constructor(options: CmsOptions) {
|
|
546
|
+
this.db = options.db;
|
|
547
|
+
this.network = options.network ?? options.db;
|
|
548
|
+
this.site = options.site ?? 'main';
|
|
549
|
+
this.hooks = options.hooks ?? createHookRegistry();
|
|
550
|
+
this.#now = options.now ?? Date.now;
|
|
551
|
+
this.#activationTtl = options.activationTtlMs ?? 30_000;
|
|
552
|
+
this.#reservedPaths = new Set(options.reservedPaths ?? DEFAULT_RESERVED_PATHS);
|
|
553
|
+
this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
|
|
554
|
+
this.#loaderTimeout = options.themeLoaderTimeoutMs ?? 1500;
|
|
555
|
+
this.#dataLimit = options.themeDataLimit ?? 65_536;
|
|
556
|
+
this.readLimits = { rowsRead: 50_000, vmSteps: 2_000_000, ...options.workLimits?.read };
|
|
557
|
+
this.writeLimits = { rowsRead: 50_000, rowMutations: 1_000, vmSteps: 2_000_000, ...options.workLimits?.write };
|
|
558
|
+
const modules = options.modules ?? [];
|
|
559
|
+
for (const module of modules) for (const declaration of module.resources) this.#register(resolveResource(declaration, module.owner));
|
|
560
|
+
for (const declaration of options.resources ?? []) this.#register(resolveResource(declaration, declaration.owner ?? 'app'));
|
|
561
|
+
this.#runner = options.runner ?? null;
|
|
562
|
+
for (const registration of options.plugins ?? []) this.#host(registration);
|
|
563
|
+
this.#resolvePluginPoints();
|
|
564
|
+
for (const taxonomy of [...modules.flatMap(module => module.taxonomies ?? []), ...(options.taxonomies ?? [])]) {
|
|
565
|
+
const problems = taxonomyProblems(taxonomy);
|
|
566
|
+
if (problems.length || this.#builtinTaxonomies.has(taxonomy.name)) throw new Error(`Taxonomy ${taxonomy.name}: ${problems.join(' ') || 'declared twice.'}`);
|
|
567
|
+
this.#builtinTaxonomies.set(taxonomy.name, Object.freeze({ ...taxonomy, builtin: true }));
|
|
568
|
+
}
|
|
569
|
+
for (const definition of modules.flatMap(module => module.collections ?? [])) {
|
|
570
|
+
const problems = collectionProblems(definition);
|
|
571
|
+
if (problems.length || this.#builtinCollections.has(definition.name)) throw new Error(`Collection ${definition.name}: ${problems.join(' ') || 'declared twice.'}`);
|
|
572
|
+
this.#builtinCollections.set(definition.name, Object.freeze({ ...definition, builtin: true }));
|
|
573
|
+
}
|
|
574
|
+
// Plugin collections are built in, tagged with the plugin; a name another declares makes the plugin invalid.
|
|
575
|
+
for (const plugin of [...this.#plugins.values()]) {
|
|
576
|
+
if (plugin.problems.length) continue;
|
|
577
|
+
const taken = (plugin.manifest.collections ?? []).filter(definition => this.#builtinCollections.has(definition.name)).map(definition => `Collection ${definition.name} is already declared.`);
|
|
578
|
+
if (taken.length) { this.#plugins.set(plugin.manifest.name, { ...plugin, problems: taken, requested: [] }); continue; }
|
|
579
|
+
for (const definition of plugin.manifest.collections ?? []) this.#builtinCollections.set(definition.name, Object.freeze({ ...definition, builtin: true, plugin: plugin.manifest.name }));
|
|
580
|
+
}
|
|
581
|
+
const blocks = [...modules.flatMap(module => (module.blocks ?? []).map(block => ({ block, owner: undefined as string | undefined }))), ...(options.blocks ?? []).map(block => ({ block, owner: undefined }))];
|
|
582
|
+
for (const plugin of this.#plugins.values()) if (!plugin.problems.length) blocks.push(...(plugin.manifest.blocks ?? []).map(block => ({ block, owner: plugin.manifest.name })));
|
|
583
|
+
for (const { block, owner } of blocks) {
|
|
584
|
+
const problems = blockProblems(block);
|
|
585
|
+
if (problems.length || this.#blocks.has(block.name)) throw new Error(`Block ${block.name}: ${problems.join(' ') || 'declared twice.'}`);
|
|
586
|
+
this.#blocks.set(block.name, Object.freeze({ ...block, ...(owner ? { plugin: owner } : {}) }));
|
|
587
|
+
}
|
|
588
|
+
this.#apply(new Map(), new Map());
|
|
589
|
+
this.fieldGroups = new CmsFieldGroups(this.db, { now: this.#now });
|
|
590
|
+
this.accounts = new CmsAccounts(this.network, { now: this.#now, ...(options.sessionsEnded ? { sessionsEnded: options.sessionsEnded } : {}) });
|
|
591
|
+
const added = this.network !== this.db;
|
|
592
|
+
// A site account's sessions are this site's: ending them ends nothing elsewhere.
|
|
593
|
+
this.siteAccounts = added ? new CmsAccounts(this.db, { now: this.#now, sessionsEnded: async ended => { if ('user' in ended) await this.authSessions.revokeAllForUser(ended.user, ended.except); } }) : null;
|
|
594
|
+
this.users = new CmsUsers(this.db, { accounts: this.accounts, ...(this.siteAccounts ? { siteAccounts: this.siteAccounts } : {}), ...(options.site ? { site: options.site } : {}), now: this.#now, checkMeta: (meta, previous, principal) => this.#checkMeta({ kind: 'users' }, meta, previous, principal) });
|
|
595
|
+
this.redirects = new CmsRedirects(this.db, { now: this.#now, changed: () => this.#purgeSite('redirects') });
|
|
596
|
+
this.traffic = new CmsTraffic(this.db, { now: this.#now });
|
|
597
|
+
this.apiTokens = new CmsApiTokens(this.network, { now: this.#now });
|
|
598
|
+
this.siteApiTokens = added ? new CmsApiTokens(this.db, { now: this.#now }) : null;
|
|
599
|
+
this.webhooks = new CmsWebhooks(this.db, { now: this.#now, fetch: options.webhookFetch ?? this.#fetch, local: options.localWebhooks === true });
|
|
600
|
+
this.comments = new CmsComments(this.db, { now: this.#now, changed: entries => this.#purgeLater('comments', { tags: entries.filter(entry => entry.resource.startsWith('cms/')).map(entry => this.purge.tag.entry(entry.resource.slice(4), entry.recordId)) }) });
|
|
601
|
+
this.mailFrom = options.mailFrom ?? 'no-reply@example.com';
|
|
602
|
+
this.oauth = Object.freeze([...new Set((options.oauth ?? []).filter(provider => /^[a-z0-9_-]{1,64}$/.test(provider)))]);
|
|
603
|
+
this.mail = options.mail ? siteMailer({ transport: options.mail, from: this.mailFrom, site: this.site, hooks: this.hooks, settings: () => this.settings.all(),
|
|
604
|
+
siteUrl: typeof options.siteUrl === 'function' ? options.siteUrl : () => options.siteUrl as string | undefined }) : null;
|
|
605
|
+
const mail = this.mail;
|
|
606
|
+
this.forms = new CmsForms(this, { ...(mail ? { mail: { send: message => mail.send({ ...message, kind: 'form' }) } } : {}), mailFrom: this.mailFrom });
|
|
607
|
+
this.security = new CmsSecurity(this.network, { now: this.#now });
|
|
608
|
+
this.siteSecurity = added ? new CmsSecurity(this.db, { now: this.#now }) : null;
|
|
609
|
+
this.siteSearch = new SiteSearch(this);
|
|
610
|
+
// Rebuilds of the site's search index run from the outbox, a round of entries at a time.
|
|
611
|
+
this.hooks.addAction(searchRebuild, (event, context) => this.siteSearch.step(event, context.signal ? { signal: context.signal } : {}), { plugin: 'cms-search' });
|
|
612
|
+
// Entry events become webhook deliveries; the outbox retries this until they are queued.
|
|
613
|
+
this.hooks.addAction(afterCommit, event => this.#queueWebhooks(event), { plugin: 'cms' });
|
|
614
|
+
// Published, changed and unpublished entries are pinged to IndexNow; a failed ping retries with the outbox.
|
|
615
|
+
this.hooks.addAction(afterCommit, event => this.#pingIndexNow(event), { plugin: 'cms' });
|
|
616
|
+
// A changed page is purged from the caches in front of the site; the purge itself runs from the outbox too. Its own owner, so a retry of another handler does not queue it twice.
|
|
617
|
+
this.hooks.addAction(afterCommit, event => this.#queuePurge(event), { plugin: 'cms-cache' });
|
|
618
|
+
// Automations run from the same events, under their own name, so their retries are theirs alone.
|
|
619
|
+
this.hooks.addAction(afterCommit, event => this.#automate(event), { plugin: 'cms-automations' });
|
|
620
|
+
this.hooks.addAction(formSubmitted, async event => { await this.automations.run('form.submitted', { form: event.form.slug, formTitle: event.form.title, submission: event.submission.id, values: event.submission.values, origin: event.origin ?? '' }, await this.#automationScopes(), event.eventId); }, { plugin: 'cms-automations' });
|
|
621
|
+
this.hooks.addAction(paymentEvent, async event => { if (paymentCompleted(event)) await this.automations.run('payment.completed', { ...event, customerEmail: event.customerEmail ?? '', reference: event.reference ?? '', amount: event.amount ?? '', currency: event.currency ?? '' }, await this.#automationScopes(), event.eventId); }, { plugin: 'cms-automations' });
|
|
622
|
+
// A completed payment goes to the webhooks that take every collection's events.
|
|
623
|
+
this.hooks.addAction(paymentEvent, async event => {
|
|
624
|
+
if (!paymentCompleted(event)) return;
|
|
625
|
+
if (!(await this.webhooks.wants(['payment.completed'], ''))) return;
|
|
626
|
+
const { object: _object, ...payment } = event;
|
|
627
|
+
await this.webhooks.enqueue({ event: 'payment.completed', eventId: `${event.eventId}:payment.completed`, at: this.#now(), collection: '', payment });
|
|
628
|
+
}, { plugin: 'cms' });
|
|
629
|
+
// A deleted entry takes its comments along; under its own name, so its retries are its alone.
|
|
630
|
+
// Only those made up to the delete: an entry made again under the same ID keeps its own.
|
|
631
|
+
this.hooks.addAction(afterCommit, async event => { if (event.topic === 'resource.deleted') await this.comments.deleteForEntry(event.resource, event.id, event.at); }, { plugin: 'cms-comments' });
|
|
632
|
+
// And its revisions, drafts, autosaves, notes and preview links, each written up to the delete.
|
|
633
|
+
this.hooks.addAction(afterCommit, async event => { if (event.topic === 'resource.deleted') await this.#entryDeleted(event.resource, event.id, event.at); }, { plugin: 'cms-revisions' });
|
|
634
|
+
this.hooks.addAction(collectionDeleted, event => this.comments.deleteForResource(event.resource, event.at), { plugin: 'cms-comments' });
|
|
635
|
+
// And its entries' revisions, a page at a time; under its own name, so its retries are its alone.
|
|
636
|
+
this.hooks.addAction(collectionDeleted, event => this.#deleteRevisions(event.resource, event.at), { plugin: 'cms-revisions' });
|
|
637
|
+
// Shared fields' rows for an entry's other translations; under its own name, so its retries are its alone.
|
|
638
|
+
// A collection or taxonomy that moved: its old links redirect. Under its own name, so its retries are its alone.
|
|
639
|
+
this.hooks.addAction(pathsMoved, async event => {
|
|
640
|
+
// This isolate may hold the collection or taxonomy as it was before the move. Each
|
|
641
|
+
// move's job redirects its own old path to where the links live now, so a path that
|
|
642
|
+
// moved again before this job ran still reaches the latest one.
|
|
643
|
+
await this.ready({ force: true });
|
|
644
|
+
if (event.kind === 'taxonomy') {
|
|
645
|
+
const now = this.#taxonomies.get(event.name)?.path;
|
|
646
|
+
if (!now || now === event.from) return;
|
|
647
|
+
await this.redirects.record([{ from: `/${event.from}`, to: `/${now}`, prefix: true }], event.by);
|
|
648
|
+
// The new path serves the taxonomy again: an older redirect away from it goes, or moving back would loop.
|
|
649
|
+
await this.redirects.dropPrefix(`/${now}`);
|
|
650
|
+
return;
|
|
651
|
+
}
|
|
652
|
+
const after = this.#collections.get(event.name);
|
|
653
|
+
if (!after || after.path === event.from) return;
|
|
654
|
+
await this.#pathRedirects({ ...after, path: event.from }, after, event.by);
|
|
655
|
+
}, { plugin: 'cms-paths' });
|
|
656
|
+
const announceNote = options.announceNote;
|
|
657
|
+
if (announceNote) this.hooks.addAction(noteAnnounced, event => announceNote(this, event), { plugin: 'cms-notes' });
|
|
658
|
+
this.hooks.addAction(sharedFields, async (event, context) => {
|
|
659
|
+
if (!this.resources.some(resource => resource.id === event.resource)) return;
|
|
660
|
+
await this.resource(event.resource).sharedSideEffects(event, context.signal ? { signal: context.signal } : {});
|
|
661
|
+
}, { plugin: 'cms-shared' });
|
|
662
|
+
// A saved form brings its submissions table up to date; a deleted one takes its table along.
|
|
663
|
+
this.hooks.addAction(afterCommit, async event => {
|
|
664
|
+
if (event.resource !== 'cms/forms') return;
|
|
665
|
+
if (event.topic === 'resource.deleted') { await this.forms.dropTable(event.id); return; }
|
|
666
|
+
if (!event.record) return;
|
|
667
|
+
// A retry can run after the form was deleted or saved again: only the form as it stands
|
|
668
|
+
// now, at this event's revision, loads (and so makes its table); a later save's event loads its own.
|
|
669
|
+
const current = await this.resource('cms/forms').get(event.id, { principal: systemPrincipal('forms') });
|
|
670
|
+
if (current && current.rev === event.revision) await this.forms.load(current);
|
|
671
|
+
}, { plugin: 'cms' });
|
|
672
|
+
// Submissions send the form's notifications and queue webhooks; both retry with the outbox.
|
|
673
|
+
this.hooks.addAction(formSubmitted, event => this.forms.notify(event), { plugin: 'cms' });
|
|
674
|
+
this.hooks.addAction(formSubmitted, event => this.#queueFormWebhooks(event), { plugin: 'cms' });
|
|
675
|
+
this.outbox = new Outbox(this.db, this.hooks, { now: this.#now, ...options.outbox });
|
|
676
|
+
// The main site's sessions are the network's; another site's are child sessions handed off from them.
|
|
677
|
+
this.authSessions = createAuthSessionStore(this.db, { now: this.#now, request: requestMetadata, ...(options.sessionsEnded ? { sessionsEnded: options.sessionsEnded } : {}) });
|
|
678
|
+
this.oauthStates = createOAuthStateStore(this.network);
|
|
679
|
+
this.sessions = createSessionStore(this.db, { now: this.#now });
|
|
680
|
+
this.taxonomies = new CmsTaxonomies(this.db, {
|
|
681
|
+
taxonomies: () => this.#taxonomies,
|
|
682
|
+
now: this.#now,
|
|
683
|
+
beforeSave: (draft, input) => this.hooks.applyFilters(termBeforeSave, draft, input),
|
|
684
|
+
checkMeta: taxonomy => (meta, previous, principal) => this.#checkMeta({ kind: 'taxonomy', name: taxonomy }, meta, previous, principal),
|
|
685
|
+
usage: name => this.resources.flatMap(resource => Object.entries(resource.fields)
|
|
686
|
+
.filter(([, declaration]) => declaration.taxonomy === name).map(([field]) => ({ resource: resource.id, storage: resource.storage, field }))),
|
|
687
|
+
canAssign: (principal, taxonomy) => this.taxonomies.usage(taxonomy.name).some(({ resource: id }) => {
|
|
688
|
+
const resource = this.#resources.get(id);
|
|
689
|
+
return resource !== undefined && (evaluateRule(resource.access.create, principal) !== 'deny' || evaluateRule(resource.access.update, principal) !== 'deny');
|
|
690
|
+
}),
|
|
691
|
+
// A term archive keeps answering at its old slug.
|
|
692
|
+
slugChanged: (taxonomy, from, to, guard) => taxonomy.path ? this.redirects.automatic(`/${taxonomy.path}/${from}`, `/${taxonomy.path}/${to}`, { guard: guard.rql, params: guard.params }) : [],
|
|
693
|
+
changed: () => this.#purgeSite('terms'),
|
|
694
|
+
});
|
|
695
|
+
for (const resource of this.#static.values()) for (const [name, declaration] of Object.entries(resource.fields)) {
|
|
696
|
+
if (declaration.taxonomy && !this.#builtinTaxonomies.has(declaration.taxonomy)) throw new Error(`${resource.id}.${name} uses taxonomy ${declaration.taxonomy}, which no module declares.`);
|
|
697
|
+
}
|
|
698
|
+
const groups = [general, interfaceGroup, media, emailGroup, appearance, dashboardGroup, cacheGroup, analyticsGroup, ...modules.flatMap(module => module.settings ?? []), ...(options.settings ?? [])];
|
|
699
|
+
for (const group of groups) {
|
|
700
|
+
if (group.plugin !== undefined || group.id.startsWith('plugin:')) throw new Error('Plugin settings namespaces and ownership are assigned by the CMS host.');
|
|
701
|
+
}
|
|
702
|
+
for (const plugin of this.#plugins.values()) {
|
|
703
|
+
const declaration = plugin.manifest.settings;
|
|
704
|
+
if (plugin.problems.length || !declaration) continue;
|
|
705
|
+
groups.push({ ...declaration, id: pluginSettingsGroupId(plugin.manifest.name), plugin: plugin.manifest.name, json: true, permission: PERMISSIONS.manageSettings });
|
|
706
|
+
}
|
|
707
|
+
for (const plugin of this.#plugins.values()) {
|
|
708
|
+
if (!plugin.manifest.theme) continue;
|
|
709
|
+
const theme = this.#hostTheme(plugin, new Set(groups.map(group => group.id)));
|
|
710
|
+
if (theme.options && !theme.problems.length) groups.push(theme.options);
|
|
711
|
+
this.#themes.set(theme.name, theme);
|
|
712
|
+
}
|
|
713
|
+
this.settings = new CmsSettings(this.db, groups, { now: this.#now, changed: () => this.#purgeSite('settings') });
|
|
714
|
+
this.indexnow = new CmsIndexNow(this.settings, { now: this.#now, fetch: this.#fetch, siteUrl: typeof options.siteUrl === 'function' ? options.siteUrl : () => options.siteUrl as string | undefined });
|
|
715
|
+
this.menus = new CmsMenus(this.db, { now: this.#now, checkMeta: (meta, previous, principal) => this.#checkMeta({ kind: 'menus' }, meta, previous, principal), resolve: (items, locale) => this.#resolveMenu(items, locale), beforeSave: (items, input) => this.hooks.applyFilters(menuBeforeSave, items, input), changed: () => this.#purgeSite('menus') });
|
|
716
|
+
this.areas = new CmsAreas(this.db, { now: this.#now, check: blocks => this.#checkBlocks(blocks), changed: () => this.#purgeSite('areas') });
|
|
717
|
+
this.previews = new CmsPreviews(this.db, { now: this.#now });
|
|
718
|
+
const sharedFieldsOf = (id: string) => this.#sharedFields(id);
|
|
719
|
+
this.autosaves = new CmsAutosaves(this.db, { now: this.#now, sharedFields: sharedFieldsOf });
|
|
720
|
+
this.drafts = new CmsDrafts(this.db, { now: this.#now, sharedFields: sharedFieldsOf });
|
|
721
|
+
this.notes = new CmsNotes(this.db, { now: this.#now });
|
|
722
|
+
this.files = options.storage ? new FileService(this.db, options.storage, { now: this.#now, ...(options.images ? { images: options.images } : {}), imageSettings: () => this.#imageSettings(), changed: () => this.#purgeSite('media'), ...options.files }) : null;
|
|
723
|
+
this.cache = new CmsCache(this.db, { now: this.#now });
|
|
724
|
+
this.#secrets = options.secrets ?? (() => undefined);
|
|
725
|
+
this.#env = options.env ?? {};
|
|
726
|
+
this.audit = new CmsAudit(this.db, { now: this.#now });
|
|
727
|
+
this.ai = options.ai ?? null;
|
|
728
|
+
this.payments = options.payments ?? null;
|
|
729
|
+
this.automations = new CmsAutomations(this.db, {
|
|
730
|
+
mail: this.mail, mailFrom: this.mailFrom, now: this.#now,
|
|
731
|
+
principal: id => this.users.principal(id),
|
|
732
|
+
// As the repository answers the author: without the fields their permissions do not read,
|
|
733
|
+
// and a locked entry as its readers see it unless the author may update it.
|
|
734
|
+
redact: (collection, record, principal) => {
|
|
735
|
+
const fields = this.#collections.has(collection) ? this.resourceById(`cms/${collection}`).fields : {};
|
|
736
|
+
const editor = this.#collections.has(collection) && this.resource(`cms/${collection}`).canUpdate(record as RecordShape, principal);
|
|
737
|
+
const seen = editor ? record : lockedView(record as RecordShape, fields);
|
|
738
|
+
const hidden = Object.entries(fields).filter(([, field]) => field.access?.read && !hasPermission(principal, field.access.read)).map(([name]) => name);
|
|
739
|
+
return hidden.length ? Object.fromEntries(Object.entries(seen).filter(([name]) => !hidden.includes(name))) : seen;
|
|
740
|
+
},
|
|
741
|
+
});
|
|
742
|
+
this.schedules = new CmsSchedules(this.db, { outbox: this.outbox, now: this.#now, schedules: () => this.#dueSchedules(), queued: () => this.outboxWritten() });
|
|
743
|
+
this.purge = new CmsPurge({ outbox: this.outbox, hooks: this.hooks, cache: this.cache, site: this.site, purgers: options.purgers ?? [], now: this.#now, queued: () => this.outboxWritten() });
|
|
744
|
+
for (const module of modules) module.register?.({ hooks: this.hooks, settings: this.settings, taxonomies: this.taxonomies, collection: name => this.#collections.get(name), blocks: () => this.#blocks, now: this.#now });
|
|
745
|
+
for (const plugin of this.#plugins.values()) this.#registerPlugin(plugin);
|
|
746
|
+
if (!options.hooks) this.hooks.freeze();
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
now(): number { return this.#now(); }
|
|
750
|
+
|
|
751
|
+
get resources(): readonly Resource[] { return [...this.#resources.values()]; }
|
|
752
|
+
|
|
753
|
+
/** Revisions of a dropped collection's entries written up to `before`. */
|
|
754
|
+
async #deleteRevisions(resource: string, before: number): Promise<void> {
|
|
755
|
+
await this.#deletePages('cms_revisions', 'resource = $resource AND at <= $before', { $resource: resource, $before: before });
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* What a deleted entry leaves behind, written up to its delete at `before`: its revisions, the
|
|
760
|
+
* room's draft, autosaves, notes and preview links. An entry made again under the same ID
|
|
761
|
+
* (seeded patterns are) starts afresh and keeps whatever it got after the delete.
|
|
762
|
+
*/
|
|
763
|
+
async #entryDeleted(resource: string, id: string, deletedAt: number): Promise<void> {
|
|
764
|
+
// Made again already: only what was written before the new record began goes.
|
|
765
|
+
const again = this.#resources.has(resource) ? await this.resource(resource).get(id, { principal: systemPrincipal('cleanup') }).catch(() => null) : null;
|
|
766
|
+
const before = again ? Math.min(deletedAt, again.createdAt - 1) : deletedAt;
|
|
767
|
+
const params = { $resource: resource, $record: id, $before: before };
|
|
768
|
+
await this.#deletePages('cms_revisions', 'resource = $resource AND record_id = $record AND at <= $before', params);
|
|
769
|
+
await this.db.write([
|
|
770
|
+
{ rql: 'DELETE FROM cms_drafts WHERE resource = $resource AND record_id = $record AND at <= $before', params },
|
|
771
|
+
{ rql: 'DELETE FROM cms_autosaves WHERE resource = $resource AND record_id = $record AND at <= $before', params },
|
|
772
|
+
{ rql: 'DELETE FROM cms_preview_tokens WHERE resource = $resource AND record_id = $record AND created_at <= $before', params },
|
|
773
|
+
{ rql: 'DELETE FROM cms_note_mentions WHERE thread_id IN (SELECT id FROM cms_notes WHERE resource = $resource AND record_id = $record AND parent_id IS NULL AND created_at <= $before)', params },
|
|
774
|
+
{ rql: 'DELETE FROM cms_notes WHERE resource = $resource AND record_id = $record AND created_at <= $before', params },
|
|
775
|
+
], { kind: 'cms.revisions', retryConflicts: 5, workLimits: this.writeLimits });
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/** Delete matching rows of a table with an `id` key, 500 at a time (under a write's row limit). */
|
|
779
|
+
async #deletePages(table: 'cms_revisions', where: string, params: { [key: string]: Value }): Promise<void> {
|
|
780
|
+
for (;;) {
|
|
781
|
+
const result = await this.db.write([{ rql: `DELETE FROM ${table} WHERE id IN (SELECT id FROM ${table} WHERE ${where} LIMIT 500)`, params }], { kind: 'cms.revisions', retryConflicts: 5, workLimits: this.writeLimits });
|
|
782
|
+
if (Number(result.results[0]!.affected) < 500) return;
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
/** A translated resource's fields that are the same in every language. */
|
|
787
|
+
#sharedFields(id: string): readonly string[] {
|
|
788
|
+
const resource = this.#resources.get(id);
|
|
789
|
+
if (!resource?.fields.translationGroup) return [];
|
|
790
|
+
return Object.entries(resource.fields).filter(([, declaration]) => declaration.translatable === false).map(([name]) => name);
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
resourceById(id: string): Resource {
|
|
794
|
+
const resource = this.#resources.get(id) ?? this.forms.resourceById(id);
|
|
795
|
+
if (!resource) throw new CmsError('CMS_NOT_FOUND', `Unknown resource ${id}.`);
|
|
796
|
+
return resource;
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
resource(id: string): ResourceRepository {
|
|
800
|
+
let repository = this.#repositories.get(id);
|
|
801
|
+
if (!repository) {
|
|
802
|
+
this.resourceById(id);
|
|
803
|
+
repository = new ResourceRepository(this, id);
|
|
804
|
+
this.#repositories.set(id, repository);
|
|
805
|
+
}
|
|
806
|
+
return repository;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
/**
|
|
810
|
+
* Load collection and taxonomy definitions made in the dashboard. Cached like activation;
|
|
811
|
+
* request middleware awaits this so `resource()` sees current collections.
|
|
812
|
+
*/
|
|
813
|
+
ready(options: { force?: boolean } = {}): Promise<void> {
|
|
814
|
+
const now = this.#now();
|
|
815
|
+
if (options.force || !this.#definitions || now - this.#definitions.at > this.#activationTtl) {
|
|
816
|
+
// The activation state and the settings are read by the steps that need them, not started here
|
|
817
|
+
// beside the definitions. Starting them early made a Worker stop answering: after two page
|
|
818
|
+
// renders before setup, every later request waited on this promise for good
|
|
819
|
+
// (generated-runtime-cms.test.js, the Workers case).
|
|
820
|
+
const state = this.#loadDefinitions().then(() => options.force ? undefined : this.#upgrade()).then(() => this.#refreshPlugins());
|
|
821
|
+
this.#definitions = { at: now, state };
|
|
822
|
+
state.catch(() => { this.#definitions = undefined; });
|
|
823
|
+
}
|
|
824
|
+
return this.#definitions.state;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
/** Current collections: built-in ones first, then by label. Collections of inactive plugins are left out. */
|
|
828
|
+
collections(): CollectionDefinition[] {
|
|
829
|
+
return [...this.#collections.values()].filter(collection => this.#shown(collection))
|
|
830
|
+
.sort((a, b) => Number(!a.builtin) - Number(!b.builtin) || a.label.localeCompare(b.label));
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
#shown(collection: CollectionDefinition): boolean {
|
|
834
|
+
return !collection.plugin || this.#activePlugins.has(collection.plugin);
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
/** Which plugins are active, for the collections they ship; and the active theme's field groups, stored once the site is set up. */
|
|
838
|
+
async #refreshPlugins(): Promise<void> {
|
|
839
|
+
const state = await this.#state().catch(() => null);
|
|
840
|
+
const active = new Set<string>();
|
|
841
|
+
if (state) for (const plugin of this.#plugins.values()) if ((await this.#pluginStatus(plugin, state)).active) active.add(plugin.manifest.name);
|
|
842
|
+
this.#activePlugins = active;
|
|
843
|
+
// A theme needs no grant, so nothing else would store the groups it ships. Storing them loads the definitions again, hence the guard.
|
|
844
|
+
if (state?.hostVersions.has(1) && !this.#seedingTheme) {
|
|
845
|
+
this.#seedingTheme = true;
|
|
846
|
+
try { await this.#seedThemeGroups(await this.activeTheme().catch(() => null)); }
|
|
847
|
+
finally { this.#seedingTheme = false; }
|
|
848
|
+
}
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
/** The module's definition of a built-in collection, without fields an administrator added. */
|
|
852
|
+
builtinCollection(name: string): CollectionDefinition | undefined {
|
|
853
|
+
return this.#builtinCollections.get(name);
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
collection(name: string): CollectionDefinition {
|
|
857
|
+
const definition = this.#collections.get(name);
|
|
858
|
+
if (!definition || !this.#shown(definition)) throw new CmsError('CMS_NOT_FOUND', `Unknown collection ${name}.`);
|
|
859
|
+
return definition;
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/** Block types from modules and active plugins, for the editor's block picker. */
|
|
863
|
+
async blocks(): Promise<(BlockDeclaration & { readonly plugin?: string })[]> {
|
|
864
|
+
const available: (BlockDeclaration & { readonly plugin?: string })[] = [];
|
|
865
|
+
for (const block of this.#blocks.values()) if (!block.plugin || await this.pluginActive(block.plugin)) available.push(block);
|
|
866
|
+
return available;
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/** Every registered block type, for validation and rendering. */
|
|
870
|
+
get blockTypes(): ReadonlyMap<string, BlockDeclaration> { return this.#blocks; }
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* Store a profile picture in the media library and set it on the user. The user themself or
|
|
874
|
+
* a user manager may; still and animated images up to 5 MB. Returns the picture's URL.
|
|
875
|
+
*/
|
|
876
|
+
async uploadAvatar(userId: string, file: { name: string; contentType: string; size: number; body: ReadableStream<Uint8Array> }, context: { principal: Principal; signal?: AbortSignal }): Promise<string> {
|
|
877
|
+
const self = context.principal.kind === 'user' && context.principal.id === userId;
|
|
878
|
+
if (!self && !hasPermission(context.principal, PERMISSIONS.manageUsers)) throw new CmsError(context.principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', 'Not allowed to change this picture.');
|
|
879
|
+
if (!this.files) throw new CmsError('CMS_UNAVAILABLE', 'File storage is not configured.');
|
|
880
|
+
if (!AVATAR_TYPES.includes(file.contentType.split(';')[0]!.trim().toLowerCase())) throw new CmsError('CMS_VALIDATION', 'Choose a PNG, JPEG, GIF, WebP or AVIF image.');
|
|
881
|
+
const user = await this.users.get(userId);
|
|
882
|
+
if (!user) throw new CmsError('CMS_NOT_FOUND', 'User not found.');
|
|
883
|
+
const stored = await this.files.upload({ ...file, title: `Avatar of ${user.name}` }, { principal: systemPrincipal('avatar'), owner: userId, maxBytes: 5 * 1024 * 1024, ...(context.signal ? { signal: context.signal } : {}) });
|
|
884
|
+
const url = mediaUrl(stored);
|
|
885
|
+
await this.users.update(userId, { avatar: url });
|
|
886
|
+
return url;
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* Publish scheduled entries whose publication time has come, and take back to draft the
|
|
891
|
+
* published entries whose `unpublishAt` has passed, as `system:scheduler`, so their webhooks
|
|
892
|
+
* and outbox events fire at that moment. Returns how many of each changed.
|
|
893
|
+
*/
|
|
894
|
+
async runSchedule(options: { limit?: number } = {}): Promise<{ published: number; unpublished: number }> {
|
|
895
|
+
const scheduler = { principal: systemPrincipal('scheduler') };
|
|
896
|
+
const done = { published: 0, unpublished: 0 };
|
|
897
|
+
for (const collection of this.#collections.values()) {
|
|
898
|
+
if (collection.publishable === false) continue;
|
|
899
|
+
const repository = this.resource(`cms/${collection.name}`);
|
|
900
|
+
const now = this.#now();
|
|
901
|
+
const due = [
|
|
902
|
+
{ kind: 'published', where: { status: 'scheduled', publishedAt: { lte: now } }, order: 'publishedAt', change: { status: 'published' } },
|
|
903
|
+
{ kind: 'unpublished', where: { status: 'published', unpublishAt: { lte: now } }, order: 'unpublishAt', change: { status: 'draft', unpublishAt: null } },
|
|
904
|
+
] as const;
|
|
905
|
+
for (const step of due) {
|
|
906
|
+
const limit = options.limit ?? 50;
|
|
907
|
+
// An entry that fails each time (a plugin filter refusing it, a size limit) is logged and
|
|
908
|
+
// passed over: the run goes on, and pages past a full page of such entries.
|
|
909
|
+
let skipped = 0;
|
|
910
|
+
for (let round = 0; round < 5; round++) {
|
|
911
|
+
let records: readonly RecordShape[];
|
|
912
|
+
try {
|
|
913
|
+
records = (await repository.list({ where: step.where, order: { field: step.order, direction: 'asc' }, limit, offset: skipped }, scheduler)).records;
|
|
914
|
+
} catch (error) {
|
|
915
|
+
if (error instanceof CmsError && error.code === 'CMS_UNAVAILABLE') break;
|
|
916
|
+
throw error;
|
|
917
|
+
}
|
|
918
|
+
let failed = 0;
|
|
919
|
+
for (const record of records) {
|
|
920
|
+
try {
|
|
921
|
+
await repository.update(record.id, step.change, { ...scheduler, expectedRevision: record.rev });
|
|
922
|
+
done[step.kind]++;
|
|
923
|
+
} catch (error) {
|
|
924
|
+
// Changed meanwhile: the next run sees the current revision.
|
|
925
|
+
if (error instanceof CmsError && error.code === 'CMS_CONFLICT') continue;
|
|
926
|
+
if (error instanceof CmsError && error.code === 'CMS_UNAVAILABLE') throw error;
|
|
927
|
+
failed++;
|
|
928
|
+
console.error(`[cms] could not ${step.kind === 'published' ? 'publish' : 'unpublish'} the scheduled entry ${collection.name}/${record.id}`, error);
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
skipped += failed;
|
|
932
|
+
if (records.length < limit || failed < records.length) break;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
return done;
|
|
937
|
+
}
|
|
938
|
+
|
|
939
|
+
/**
|
|
940
|
+
* Published, indexable entries of a collection on the site for its XML sitemap, oldest
|
|
941
|
+
* first, `limit` (at most 1,000) from `offset`: their URLs, last changes and featured images.
|
|
942
|
+
*/
|
|
943
|
+
async sitemapEntries(name: string, options: { offset?: number; limit?: number } = {}): Promise<{ id: string; url: string; title: string; locale: string | null; translationGroup: string | null; publishedAt: number | null; updatedAt: number; image?: string }[]> {
|
|
944
|
+
const collection = this.collection(name);
|
|
945
|
+
if (collection.path === null || collection.path === undefined || collection.slug === false || collection.sitemap === false || collection.robots?.noindex || (collection.publishable === false && collection.visibility !== 'public')) return [];
|
|
946
|
+
const limit = Math.min(Math.max(options.limit ?? 1000, 1), 1000);
|
|
947
|
+
const offset = Math.min(Math.max(options.offset ?? 0, 0), 1_000_000);
|
|
948
|
+
const resource = this.resourceById(`cms/${collection.name}`);
|
|
949
|
+
await this.assertActive(resource);
|
|
950
|
+
const taxonomy = collection.permalink === 'category' ? collection.taxonomies?.[0] : undefined;
|
|
951
|
+
const image = resource.fields.featuredImage?.media ? 'featuredImage' : undefined;
|
|
952
|
+
// Search engines send no password or session: protected and members-only entries stay out, as in feeds and search.
|
|
953
|
+
const conditions = [
|
|
954
|
+
...(collection.publishable === false ? [] : [`"status" = 'published'`]),
|
|
955
|
+
...(resource.fields.password ? [`("password" IS NULL OR "password" = '')`] : []),
|
|
956
|
+
...(resource.fields.membersOnly ? ['NOT coalesce("membersOnly", false)'] : []),
|
|
957
|
+
];
|
|
958
|
+
// A thousand entries' SEO fields can pass the result budget: the page may come in smaller reads.
|
|
959
|
+
const rows = await readPaged(this.db, (size, at) => ({
|
|
960
|
+
rql: `SELECT id, "slug", "parent", "locale", "seo", "_updatedAt", "_createdAt", "_owner", ${taxonomy ? `"${taxonomy}"` : 'NULL'}, ${image ? `"${image}"` : 'NULL'}, "title", "translationGroup", ${collection.publishable === false ? 'NULL' : '"publishedAt"'} FROM ${resource.storage}${conditions.length ? ` WHERE ${conditions.join(' AND ')}` : ''} ORDER BY "_createdAt", record::id(id) LIMIT $limit OFFSET $offset`,
|
|
961
|
+
params: { $limit: size, $offset: at },
|
|
962
|
+
}), limit, offset, { workLimits: this.readLimits });
|
|
963
|
+
const records = rows.map(([id, slug, parent, locale, seo, updatedAt, createdAt, owner, terms, picture, title, translationGroup, publishedAt]) => Object.freeze({
|
|
964
|
+
id: String((id as { key: unknown }).key), rev: 0, slug, parent: parent && typeof parent === 'object' && 'key' in parent ? String((parent as { key: unknown }).key) : null,
|
|
965
|
+
locale, seo, title, translationGroup, publishedAt: publishedAt === null || publishedAt === undefined ? null : Number(publishedAt as bigint), status: 'published', updatedAt: Number(updatedAt as bigint), createdAt: Number(createdAt as bigint), owner: (owner as string | null) ?? null,
|
|
966
|
+
...(taxonomy ? { [taxonomy]: Array.isArray(terms) ? terms : [] } : {}),
|
|
967
|
+
...(image ? { [image]: typeof picture === 'string' ? picture : null } : {}),
|
|
968
|
+
}) as RecordShape);
|
|
969
|
+
const indexable = records.filter(record => !(record.seo && typeof record.seo === 'object' && (record.seo as { noindex?: unknown }).noindex === true));
|
|
970
|
+
const urls = await this.entryUrls(collection, indexable);
|
|
971
|
+
// Featured images, as image sitemap entries.
|
|
972
|
+
const files = image && this.files ? await this.files.getMany(indexable.map(record => record[image]).filter((id): id is string => typeof id === 'string')) : new Map<string, CmsFile>();
|
|
973
|
+
return indexable.flatMap(record => {
|
|
974
|
+
const url = urls.get(record.id);
|
|
975
|
+
if (!url) return [];
|
|
976
|
+
const file = image ? files.get(String(record[image] ?? '')) : undefined;
|
|
977
|
+
return [{ id: record.id, url, title: String(record.title ?? ''), locale: typeof record.locale === 'string' ? record.locale : null, translationGroup: typeof record.translationGroup === 'string' ? record.translationGroup : null, publishedAt: record.publishedAt as number | null, updatedAt: record.updatedAt, ...(file && file.contentType.startsWith('image/') ? { image: mediaUrl(file) } : {}) }];
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
/** A shareable link to preview an entry the principal may edit. */
|
|
982
|
+
async createPreviewLink(resourceId: string, id: string, principal: Principal, ttlMs?: number): Promise<PreviewLink> {
|
|
983
|
+
await this.#editable(resourceId, id, principal);
|
|
984
|
+
return this.previews.create(resourceId, id, principalId(principal), ttlMs);
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
async revokePreviewLinks(resourceId: string, id: string, principal: Principal): Promise<void> {
|
|
988
|
+
await this.#editable(resourceId, id, principal);
|
|
989
|
+
await this.previews.revoke(resourceId, id);
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
/** The entry a preview link opens, read whatever its status, or null. */
|
|
993
|
+
async previewByToken(token: string): Promise<{ resource: Resource; record: RecordShape } | null> {
|
|
994
|
+
const link = await this.previews.verify(token);
|
|
995
|
+
if (!link || !this.#resources.has(link.resource)) return null;
|
|
996
|
+
const record = await this.resource(link.resource).get(link.recordId, { principal: systemPrincipal('preview') });
|
|
997
|
+
return record ? { resource: this.resourceById(link.resource), record } : null;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
/** Store the editor's unsaved values of an entry (`new` before its first save) for its user. */
|
|
1001
|
+
async autosave(resourceId: string, id: string, principal: Principal, data: unknown): Promise<number> {
|
|
1002
|
+
const user = await this.#autosaver(resourceId, id, principal);
|
|
1003
|
+
return this.autosaves.save(resourceId, id, user, data);
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
async latestAutosave(resourceId: string, id: string, principal: Principal): Promise<Autosave | null> {
|
|
1007
|
+
if (principal.kind !== 'user') return null;
|
|
1008
|
+
return this.autosaves.get(resourceId, id, principal.id);
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
async discardAutosave(resourceId: string, id: string, principal: Principal): Promise<void> {
|
|
1012
|
+
if (principal.kind === 'user') await this.autosaves.discard(resourceId, id, principal.id);
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
async #autosaver(resourceId: string, id: string, principal: Principal): Promise<string> {
|
|
1016
|
+
if (principal.kind !== 'user') throw new CmsError('CMS_UNAUTHENTICATED', 'Sign in to save drafts.');
|
|
1017
|
+
if (id === 'new') {
|
|
1018
|
+
if (evaluateRule(this.resourceById(resourceId).access.create, principal) === 'deny') throw new CmsError('CMS_FORBIDDEN', `Not allowed to create ${resourceId}.`);
|
|
1019
|
+
} else await this.#editable(resourceId, id, principal);
|
|
1020
|
+
return principal.id;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
/** The record, when the principal may read and update it. */
|
|
1024
|
+
async #editable(resourceId: string, id: string, principal: Principal): Promise<RecordShape> {
|
|
1025
|
+
const repository = this.resource(resourceId);
|
|
1026
|
+
const record = await repository.get(id, { principal });
|
|
1027
|
+
if (!record) throw new CmsError('CMS_NOT_FOUND', 'Record not found.');
|
|
1028
|
+
if (!repository.canUpdate(record, principal)) throw new CmsError(principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', 'Not allowed to edit this entry.');
|
|
1029
|
+
return record;
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
/**
|
|
1033
|
+
* The principal of an application password, with its access, or null. Only the content
|
|
1034
|
+
* API accepts these; `read` access may only read.
|
|
1035
|
+
*/
|
|
1036
|
+
/**
|
|
1037
|
+
* The stores that sign people in on this host: the site's own on an added site, the
|
|
1038
|
+
* network's on the main site. Sign-in by email, passkey or reset token starts here.
|
|
1039
|
+
*/
|
|
1040
|
+
get signIn(): AccountStores {
|
|
1041
|
+
return this.siteAccounts ? { kind: 'site', accounts: this.siteAccounts, security: this.siteSecurity!, apiTokens: this.siteApiTokens! }
|
|
1042
|
+
: { kind: 'network', accounts: this.accounts, security: this.security, apiTokens: this.apiTokens };
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
/** The stores holding a user's account: the site's for a site account, the network's otherwise. */
|
|
1046
|
+
async storesOf(userId: string): Promise<AccountStores> {
|
|
1047
|
+
return this.siteAccounts && await this.siteAccounts.get(userId) ? this.signIn
|
|
1048
|
+
: { kind: 'network', accounts: this.accounts, security: this.security, apiTokens: this.apiTokens };
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
async tokenPrincipal(token: string): Promise<{ principal: Principal; scope: ApiTokenScope; userId: string } | null> {
|
|
1052
|
+
const verified = await this.siteApiTokens?.verify(token) ?? await this.apiTokens.verify(token);
|
|
1053
|
+
if (!verified) return null;
|
|
1054
|
+
const user = await this.users.resolve(verified.userId);
|
|
1055
|
+
return user ? { principal: user.principal, scope: verified.scope, userId: user.id } : null;
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
/** Whether the site has discussions at all (Settings → Discussion → Allow discussions). Off hides every comment; stored ones are kept. */
|
|
1059
|
+
discussions(settings: SiteSettings): boolean {
|
|
1060
|
+
return settings['discussion.enabled'] !== false;
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
/** Whether visitors can comment on the entry: discussions are on, its collection takes comments, it is open, and not too old. */
|
|
1064
|
+
commentsOpen(collection: CollectionDefinition, record: RecordShape, settings: SiteSettings): boolean {
|
|
1065
|
+
if (!this.discussions(settings) || !collection.comments || record.commentsOpen === false) return false;
|
|
1066
|
+
const days = settings['discussion.closeAfterDays'];
|
|
1067
|
+
const since = typeof record.publishedAt === 'number' ? record.publishedAt : record.createdAt;
|
|
1068
|
+
return !days || this.#now() - since < days * 24 * 60 * 60 * 1000;
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
/**
|
|
1072
|
+
* Post a comment on an entry visitors can read and comment on. Discussion settings decide
|
|
1073
|
+
* whether it appears at once, waits for moderation or goes to spam; moderators' comments
|
|
1074
|
+
* appear at once. `trap` is the form's hidden field, which only bots fill in.
|
|
1075
|
+
*/
|
|
1076
|
+
async postComment(input: { collection: string; entry: string; parent?: string | null; content?: string; authorName?: string; authorEmail?: string; authorUrl?: string; trap?: string },
|
|
1077
|
+
context: { principal: Principal; ip?: string; userAgent?: string }): Promise<{ comment: CommentShape; collection: CollectionDefinition; entry: RecordShape; url: string | null }> {
|
|
1078
|
+
const collection = this.#collections.get(input.collection);
|
|
1079
|
+
if (!collection?.comments) throw new CmsError('CMS_NOT_FOUND', 'This entry does not take comments.');
|
|
1080
|
+
const resource = `cms/${collection.name}`;
|
|
1081
|
+
const record = await this.resource(resource).get(input.entry, { principal: ANONYMOUS });
|
|
1082
|
+
if (!record || (collection.publishable !== false && record.status !== 'published')) throw new CmsError('CMS_NOT_FOUND', 'This entry does not take comments.');
|
|
1083
|
+
const settings = await this.settings.all();
|
|
1084
|
+
if (!this.discussions(settings)) throw new CmsError('CMS_FORBIDDEN', 'Discussions are turned off on this site.');
|
|
1085
|
+
if (!this.commentsOpen(collection, record, settings)) throw new CmsError('CMS_FORBIDDEN', 'Comments are closed.');
|
|
1086
|
+
const user = context.principal.kind === 'user' ? await this.users.get(context.principal.id) : null;
|
|
1087
|
+
if (settings['discussion.requireSignIn'] && !user) throw new CmsError('CMS_UNAUTHENTICATED', 'Sign in to comment.');
|
|
1088
|
+
const fields = checkComment(user ? { content: input.content, authorName: user.name, authorEmail: user.email, authorUrl: input.authorUrl } : input, !user && settings['discussion.requireNameEmail']);
|
|
1089
|
+
let parentId: string | null = null;
|
|
1090
|
+
if (input.parent) {
|
|
1091
|
+
const parent = await this.comments.get(input.parent);
|
|
1092
|
+
if (!parent || parent.resource !== resource || parent.recordId !== record.id || parent.status !== 'approved') throw new CmsError('CMS_VALIDATION', 'The comment you reply to is gone.');
|
|
1093
|
+
let depth = 1;
|
|
1094
|
+
for (let current: CommentShape | null = parent; current?.parentId && depth <= 10; depth++) current = await this.comments.get(current.parentId);
|
|
1095
|
+
if (depth >= settings['discussion.threadDepth']) throw new CmsError('CMS_VALIDATION', 'Replies cannot nest deeper here.');
|
|
1096
|
+
parentId = parent.id;
|
|
1097
|
+
}
|
|
1098
|
+
const ipHash = context.ip ? await sha256Hex(`cms-comment:${context.ip}`) : null;
|
|
1099
|
+
// One comment per address in 15 seconds, counted in one conditional write so a burst gets one through.
|
|
1100
|
+
if (ipHash && !(await this.security.attempt('comment', ipHash, 1, 15_000))) throw new CmsError('CMS_LIMIT', 'You are posting comments too quickly. Wait a moment and try again.');
|
|
1101
|
+
// "An earlier approved comment" counts for signed-in users only: an anonymous commenter types any email.
|
|
1102
|
+
const status: CommentStatus = input.trap ? 'spam' : hasPermission(context.principal, PERMISSIONS.moderateComments) ? 'approved'
|
|
1103
|
+
: await commentStatus(fields, settings, async () => user !== null && await this.comments.hasApproved(fields.authorEmail));
|
|
1104
|
+
// Plugins check, change or hold the comment: spam filters, profanity lists, extra rules.
|
|
1105
|
+
const filtered = await this.hooks.applyFilters(commentBeforeSave, Object.freeze({ ...fields, status }), Object.freeze({
|
|
1106
|
+
collection: collection.name, entry: record.id, parent: parentId, actor: writeActorOf(context.principal), ...(context.ip ? { ip: context.ip } : {}), ...(context.userAgent ? { userAgent: context.userAgent } : {}),
|
|
1107
|
+
}));
|
|
1108
|
+
if (!filtered || typeof filtered !== 'object' || !(COMMENT_STATUSES as readonly string[]).includes(filtered.status)) throw new CmsError('CMS_VALIDATION', 'A plugin returned an invalid comment.');
|
|
1109
|
+
const checked = checkComment(filtered, !user && settings['discussion.requireNameEmail']);
|
|
1110
|
+
// The entry may have been deleted while plugins checked the comment: then the comment is not added.
|
|
1111
|
+
const storage = this.resourceById(resource).storage;
|
|
1112
|
+
const comment = await this.comments.create({ id: uuidv7(), resource, recordId: record.id, parentId, userId: user?.id ?? null, ...checked,
|
|
1113
|
+
status: filtered.status, ipHash, userAgent: context.userAgent?.slice(0, 300) ?? null },
|
|
1114
|
+
{ rql: `EXISTS (SELECT 1 FROM ${storage} WHERE id = type::record('${storage}', $commentEntry))`, params: { $commentEntry: record.id } });
|
|
1115
|
+
const url = (await this.entryUrls(collection, [record])).get(record.id) ?? null;
|
|
1116
|
+
return { comment, collection, entry: record, url };
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
/** Moderate comments; needs `cms:comments`. */
|
|
1120
|
+
async moderateComments(ids: readonly string[], status: CommentStatus | 'delete', principal: Principal): Promise<void> {
|
|
1121
|
+
if (!hasPermission(principal, PERMISSIONS.moderateComments)) throw new CmsError(principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', 'Not allowed to moderate comments.');
|
|
1122
|
+
if (status === 'delete') await this.comments.delete(ids);
|
|
1123
|
+
else await this.comments.setStatus(ids, status);
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
async #queueFormWebhooks(event: FormSubmittedEvent): Promise<void> {
|
|
1127
|
+
if (!(await this.webhooks.wants(['form.submitted'], 'forms'))) return;
|
|
1128
|
+
const { submission } = event;
|
|
1129
|
+
await this.webhooks.enqueue({
|
|
1130
|
+
event: 'form.submitted', eventId: `${event.eventId}:form.submitted`, at: event.at, collection: 'forms',
|
|
1131
|
+
form: { id: event.form.id, slug: event.form.slug, title: event.form.title },
|
|
1132
|
+
submission: { id: submission.id, status: submission.status, values: submission.values, meta: submission.meta, user: submission.user, createdAt: submission.createdAt, stored: event.stored },
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
/**
|
|
1137
|
+
* Purge what an entry event changed: its page and the lists of its collection, or the whole
|
|
1138
|
+
* site when a menu names the entry. Drafts and private collections show on no page. Other
|
|
1139
|
+
* resources of the CMS (patterns, forms) may show anywhere, so they purge the site. A plugin's
|
|
1140
|
+
* resources purge nothing: the plugin knows which pages show them (`cms.purge.queue`).
|
|
1141
|
+
*/
|
|
1142
|
+
async #queuePurge(event: ResourceEvent): Promise<void> {
|
|
1143
|
+
if (!event.resource.startsWith('cms/')) return;
|
|
1144
|
+
const name = event.resource.slice(4);
|
|
1145
|
+
const collection = this.#collections.get(name);
|
|
1146
|
+
if (!collection) {
|
|
1147
|
+
await this.purge.everything(name);
|
|
1148
|
+
return;
|
|
1149
|
+
}
|
|
1150
|
+
const publishable = collection.publishable !== false;
|
|
1151
|
+
const shown = publishable ? event.previousStatus === 'published' || event.record?.status === 'published' : collection.visibility === 'public';
|
|
1152
|
+
if (!shown) return;
|
|
1153
|
+
if (event.topic !== 'resource.created' && await this.#menusName(name, event.id)) {
|
|
1154
|
+
await this.purge.everything(`entry:${name}`);
|
|
1155
|
+
return;
|
|
1156
|
+
}
|
|
1157
|
+
const origin = this.indexnow.origin();
|
|
1158
|
+
const url = event.record && origin ? (await this.entryUrls(collection, [event.record])).get(event.record.id) : undefined;
|
|
1159
|
+
await this.purge.queue(`entry:${name}`, {
|
|
1160
|
+
tags: [this.purge.tag.entry(name, event.id), this.purge.tag.collection(name)],
|
|
1161
|
+
urls: url ? [`${origin}${url}`, `${origin}${url}${url.includes('?') ? '&' : '?'}format=md`] : [],
|
|
1162
|
+
});
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
/** Whether a menu item links to the entry, whose title or address then shows on every page. */
|
|
1166
|
+
async #menusName(collection: string, id: string): Promise<boolean> {
|
|
1167
|
+
const names = (items: readonly MenuItem[]): boolean => items.some(item => (item.kind === 'entry' && item.collection === collection && item.entry === id) || names(item.children));
|
|
1168
|
+
for (const summary of await this.menus.list()) {
|
|
1169
|
+
const menu = await this.menus.get(summary.id);
|
|
1170
|
+
if (menu && names(menu.items)) return true;
|
|
1171
|
+
}
|
|
1172
|
+
return false;
|
|
1173
|
+
}
|
|
1174
|
+
|
|
1175
|
+
/** Queue a purge of every page after a change that may show anywhere; a failure to queue is logged, never the save's. */
|
|
1176
|
+
#purgeSite(reason: string): Promise<void> {
|
|
1177
|
+
return this.#purgeLater(reason, {});
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
async #purgeLater(reason: string, input: { tags?: readonly string[]; urls?: readonly string[] }): Promise<void> {
|
|
1181
|
+
if (input.tags && !input.tags.length && !input.urls?.length) return;
|
|
1182
|
+
try { await this.purge.queue(reason, input); }
|
|
1183
|
+
catch (error) { console.error(`[cms] could not queue a cache purge (${reason})`, error); }
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
async #pingIndexNow(event: ResourceEvent): Promise<void> {
|
|
1187
|
+
const collection = event.resource.startsWith('cms/') ? this.#collections.get(event.resource.slice(4)) : undefined;
|
|
1188
|
+
if (!collection || !(await this.settings.get('indexnow.enabled'))) return;
|
|
1189
|
+
if (!CmsIndexNow.concerns(event, collection)) return;
|
|
1190
|
+
const url = (await this.entryUrls(collection, [event.record!])).get(event.record!.id);
|
|
1191
|
+
if (url) await this.indexnow.submit([url]);
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
async #queueWebhooks(event: ResourceEvent): Promise<void> {
|
|
1195
|
+
const collection = event.resource.startsWith('cms/') ? this.#collections.get(event.resource.slice(4)) : undefined;
|
|
1196
|
+
if (!collection) return;
|
|
1197
|
+
const publishable = collection.publishable !== false;
|
|
1198
|
+
const was = event.previousStatus === 'published';
|
|
1199
|
+
const is = event.record?.status === 'published';
|
|
1200
|
+
const events: WebhookEvent[] = event.topic === 'resource.created' ? ['entry.created', ...(publishable && is ? ['entry.published' as const] : [])]
|
|
1201
|
+
: event.topic === 'resource.deleted' ? ['entry.deleted']
|
|
1202
|
+
: publishable && !was && is ? ['entry.published'] : publishable && was && !is ? ['entry.unpublished'] : ['entry.updated'];
|
|
1203
|
+
if (!(await this.webhooks.wants(events, collection.name))) return;
|
|
1204
|
+
const url = event.record && (!publishable || is) ? (await this.entryUrls(collection, [event.record])).get(event.record.id) ?? null : null;
|
|
1205
|
+
const entry = event.record ? { ...event.record, url } : { id: event.id };
|
|
1206
|
+
for (const name of events) {
|
|
1207
|
+
await this.webhooks.enqueue({ event: name, eventId: `${event.eventId}:${name}`, at: event.at, collection: collection.name, entry, previousStatus: event.previousStatus ?? null });
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
/** Themes from rendered plugins, valid ones first, by label. */
|
|
1212
|
+
themes(): ThemeInfo[] {
|
|
1213
|
+
return [...this.#themes.values()].sort((a, b) => Number(a.problems.length > 0) - Number(b.problems.length > 0) || a.label.localeCompare(b.label));
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
/**
|
|
1217
|
+
* The active theme's name: the Appearance setting when it names a usable theme, otherwise
|
|
1218
|
+
* the first usable one. Null when there is none.
|
|
1219
|
+
*/
|
|
1220
|
+
async activeTheme(): Promise<string | null> {
|
|
1221
|
+
const chosen = await this.settings.get('appearance.theme').catch(() => '');
|
|
1222
|
+
const usable = (await this.availableThemes()).filter(theme => !theme.problems.length).sort((a, b) => a.name.localeCompare(b.name));
|
|
1223
|
+
return usable.find(theme => theme.name === chosen)?.name ?? usable[0]?.name ?? null;
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
/** The themes this site may choose: every theme the network does not hide. */
|
|
1227
|
+
async availableThemes(): Promise<ThemeInfo[]> {
|
|
1228
|
+
const hidden = (await this.#state().catch(() => null))?.policy.hiddenThemes ?? new Set<string>();
|
|
1229
|
+
return this.themes().filter(theme => !hidden.has(theme.name));
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
async activateTheme(name: string, principal: Principal): Promise<void> {
|
|
1233
|
+
const theme = (await this.availableThemes()).find(entry => entry.name === name);
|
|
1234
|
+
if (!theme) throw new CmsError('CMS_NOT_FOUND', `Unknown theme ${name}.`);
|
|
1235
|
+
if (theme.problems.length) throw new CmsError('CMS_VALIDATION', `${theme.label} cannot be used: ${theme.problems.join(' ')}`);
|
|
1236
|
+
await this.settings.update('appearance', { theme: name }, { principal });
|
|
1237
|
+
await this.#seedThemeGroups(name, { activation: true });
|
|
1238
|
+
}
|
|
1239
|
+
|
|
1240
|
+
/** The field groups the active theme and its parent ship: a theme needs no grant, so they are stored here, once (`#refreshPlugins`, `activateTheme`). */
|
|
1241
|
+
async #seedThemeGroups(name: string | null, options: { activation?: boolean } = {}): Promise<void> {
|
|
1242
|
+
for (const plugin of this.#themeChain(name)) {
|
|
1243
|
+
if (plugin.problems.length) continue;
|
|
1244
|
+
if (plugin.manifest.fieldGroups?.length && !this.#groups.some(group => group.plugin === plugin.manifest.name)) await this.#seedFieldGroups(plugin, systemPrincipal('site')).catch(error => console.error(`[cms] could not add the field groups of ${plugin.manifest.name}`, error));
|
|
1245
|
+
// At a start, the theme's patterns are added only when the site has none of them: a deleted one stays deleted.
|
|
1246
|
+
await this.#seedPatterns(plugin, systemPrincipal('site'), { onlyIfNone: !options.activation }).catch(error => console.error(`[cms] could not add the patterns of ${plugin.manifest.name}`, error));
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
|
|
1250
|
+
/**
|
|
1251
|
+
* Templates an editor can choose for one entry: the active theme's `entry-*` templates,
|
|
1252
|
+
* except those named after a collection (`entry-posts`), which apply to it already.
|
|
1253
|
+
*/
|
|
1254
|
+
async entryTemplates(): Promise<string[]> {
|
|
1255
|
+
const theme = this.#siteTheme(await this.activeTheme());
|
|
1256
|
+
const collections = new Set([...this.#collections.keys()].map(collection => `entry-${collection}`));
|
|
1257
|
+
return entryTemplateChoices(theme && !siteThemeProblems(theme).length ? theme as SiteTheme : undefined).filter(template => !collections.has(template));
|
|
1258
|
+
}
|
|
1259
|
+
|
|
1260
|
+
/** The keys of a theme's loaders, from its `server.ts` `loaders` export. */
|
|
1261
|
+
themeLoaders(name: string | null): string[] {
|
|
1262
|
+
return [...new Set(this.#themeChain(name).flatMap(plugin => Object.keys(loadersOf(plugin))))];
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
/** A theme's plugin and its parent's, child first. */
|
|
1266
|
+
#themeChain(name: string | null): HostedPlugin[] {
|
|
1267
|
+
const plugin = name ? this.#plugins.get(name) : undefined;
|
|
1268
|
+
if (!plugin?.manifest.theme) return [];
|
|
1269
|
+
const parent = this.#parentOf(plugin);
|
|
1270
|
+
return parent ? [plugin, parent] : [plugin];
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
#parentOf(plugin: HostedPlugin): HostedPlugin | undefined {
|
|
1274
|
+
const name = (plugin.manifest.theme as ThemeManifest | undefined)?.extends;
|
|
1275
|
+
const parent = name && name !== plugin.manifest.name ? this.#plugins.get(name) : undefined;
|
|
1276
|
+
return parent?.manifest.theme ? parent : undefined;
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
/** A usable theme's templates, layered over its parent's; undefined when it has problems. */
|
|
1280
|
+
#siteTheme(name: string | null): SiteTheme | undefined {
|
|
1281
|
+
const info = name ? this.#themes.get(name) : undefined;
|
|
1282
|
+
if (!info || info.problems.length) return undefined;
|
|
1283
|
+
const [plugin, parent] = this.#themeChain(name);
|
|
1284
|
+
return assembleSiteTheme(plugin!.registration, parent?.registration) as SiteTheme;
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
/**
|
|
1288
|
+
* Run the first of the candidates a theme has a loader for, with the theme plugin's grants,
|
|
1289
|
+
* the visitor principal and a time limit. Returns its plain JSON, or `{}` when the theme has
|
|
1290
|
+
* no such loader, is not active, fails, runs out of time or returns too much.
|
|
1291
|
+
*/
|
|
1292
|
+
async themeData(name: string | null, candidates: readonly string[], input: ThemeLoaderInput,
|
|
1293
|
+
context: { principal: Principal; options?: { readonly [name: string]: unknown }; locale?: string }): Promise<ThemeData> {
|
|
1294
|
+
// A child's loader wins over its parent's for the same key; each runs with its own plugin's grants.
|
|
1295
|
+
const chain = this.#themeChain(name);
|
|
1296
|
+
let plugin: HostedPlugin | undefined;
|
|
1297
|
+
let template: string | undefined;
|
|
1298
|
+
for (const candidate of candidates) {
|
|
1299
|
+
plugin = chain.find(entry => typeof loadersOf(entry)[candidate] === 'function');
|
|
1300
|
+
if (plugin) { template = candidate; break; }
|
|
1301
|
+
}
|
|
1302
|
+
const loaders = plugin ? loadersOf(plugin) : undefined;
|
|
1303
|
+
if (!plugin || !template || !loaders || plugin.problems.length || this.#themes.get(name!)?.problems.length) return {};
|
|
1304
|
+
if (!(await this.pluginActive(plugin.manifest.name))) return {};
|
|
1305
|
+
const controller = new AbortController();
|
|
1306
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
1307
|
+
const timeout = new Promise<never>((_, reject) => {
|
|
1308
|
+
timer = setTimeout(() => { controller.abort(); reject(new Error(`timed out after ${this.#loaderTimeout} ms`)); }, this.#loaderTimeout);
|
|
1309
|
+
});
|
|
1310
|
+
try {
|
|
1311
|
+
const own = 'site' in input ? input.site.locale : 'entry' in input ? input.entry.locale : undefined;
|
|
1312
|
+
const result = await Promise.race([Promise.resolve().then(() => loaders![template]!({
|
|
1313
|
+
...input, cms: this.pluginCms(plugin.manifest.name), principal: context.principal, signal: controller.signal,
|
|
1314
|
+
options: context.options ?? {}, locale: context.locale ?? own ?? 'en', template,
|
|
1315
|
+
} as LayoutLoaderContext | EntryLoaderContext | ArchiveLoaderContext)), timeout]);
|
|
1316
|
+
if (result === undefined || result === null) return {};
|
|
1317
|
+
if (typeof result !== 'object' || Array.isArray(result)) throw new Error('it must return an object.');
|
|
1318
|
+
const json = JSON.stringify(result);
|
|
1319
|
+
if (json.length > this.#dataLimit) throw new Error(`it returned ${json.length} characters, more than ${this.#dataLimit}.`);
|
|
1320
|
+
return JSON.parse(json) as ThemeData;
|
|
1321
|
+
} catch (error) {
|
|
1322
|
+
console.warn(`[cms] theme loader ${plugin.manifest.name}.${template} failed: ${(error as Error).message}`);
|
|
1323
|
+
return {};
|
|
1324
|
+
} finally {
|
|
1325
|
+
clearTimeout(timer);
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
/** Widget areas of the active theme, then those only other themes declare. */
|
|
1330
|
+
async areaLocations(): Promise<{ name: string; label: string; defaults: readonly Block[]; theme: string; active: boolean }[]> {
|
|
1331
|
+
const active = await this.activeTheme();
|
|
1332
|
+
const seen = new Set<string>();
|
|
1333
|
+
const areas: { name: string; label: string; defaults: readonly Block[]; theme: string; active: boolean }[] = [];
|
|
1334
|
+
for (const theme of [...this.themes()].sort((a, b) => Number(b.name === active) - Number(a.name === active))) {
|
|
1335
|
+
if (theme.problems.length) continue;
|
|
1336
|
+
for (const area of theme.areas) {
|
|
1337
|
+
if (seen.has(area.name)) continue;
|
|
1338
|
+
seen.add(area.name);
|
|
1339
|
+
areas.push({ ...area, theme: theme.name, active: theme.name === active });
|
|
1340
|
+
}
|
|
1341
|
+
}
|
|
1342
|
+
return areas;
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
/** Blocks for a widget area, checked as a blocks field checks them; their files must be ready. */
|
|
1346
|
+
async #checkBlocks(value: unknown): Promise<Block[]> {
|
|
1347
|
+
const shape = blocksShapeProblem(value);
|
|
1348
|
+
if (shape) throw new CmsError('CMS_VALIDATION', `Widgets ${shape}`, { fields: { blocks: shape } });
|
|
1349
|
+
const { blocks, errors } = validateBlocks(value as Block[], this.#blocks);
|
|
1350
|
+
const first = Object.entries(errors)[0];
|
|
1351
|
+
if (first) throw new CmsError('CMS_VALIDATION', `${first[0]}: ${first[1]}`, { fields: errors });
|
|
1352
|
+
const plugins = [...new Set(blocks.map(block => this.#blocks.get(block.type)?.plugin).filter((plugin): plugin is string => !!plugin))];
|
|
1353
|
+
for (const plugin of plugins) if (!(await this.pluginActive(plugin))) throw new CmsError('CMS_VALIDATION', `Blocks of ${plugin} are not available while the plugin is inactive.`);
|
|
1354
|
+
const files = [...new Set(blockMedia(blocks, this.#blocks))];
|
|
1355
|
+
if (files.length > 100) throw new CmsError('CMS_VALIDATION', 'Widgets name too many files.');
|
|
1356
|
+
if (files.length) {
|
|
1357
|
+
const list = files.map((_, index) => `$m${index}`).join(', ');
|
|
1358
|
+
const found = await this.db.read([{ rql: `SELECT count(*) FROM cms_files WHERE status = 'ready' AND ${LIBRARY_KEYS} AND id IN (${list})`, params: Object.fromEntries(files.map((file, index) => [`$m${index}`, file])) }]);
|
|
1359
|
+
if (Number(found.results[0]!.rows[0]![0] as bigint) !== files.length) throw new CmsError('CMS_VALIDATION', 'Widgets name a missing file.');
|
|
1360
|
+
}
|
|
1361
|
+
return blocks;
|
|
1362
|
+
}
|
|
1363
|
+
|
|
1364
|
+
/** Menu locations of the active theme, then those only other themes declare. */
|
|
1365
|
+
async menuLocations(): Promise<{ name: string; label: string; theme: string; active: boolean }[]> {
|
|
1366
|
+
const active = await this.activeTheme();
|
|
1367
|
+
const seen = new Set<string>();
|
|
1368
|
+
const locations: { name: string; label: string; theme: string; active: boolean }[] = [];
|
|
1369
|
+
for (const theme of [...this.themes()].sort((a, b) => Number(b.name === active) - Number(a.name === active))) {
|
|
1370
|
+
if (theme.problems.length) continue;
|
|
1371
|
+
for (const location of theme.locations) {
|
|
1372
|
+
if (seen.has(location.name)) continue;
|
|
1373
|
+
seen.add(location.name);
|
|
1374
|
+
locations.push({ ...location, theme: theme.name, active: theme.name === active });
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
return locations;
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
/**
|
|
1381
|
+
* Slugs an entry of a collection served at the site root cannot take, among `base` and
|
|
1382
|
+
* `base-N`: routes of the application, the first segments of collection and taxonomy
|
|
1383
|
+
* paths, and the slugs of other root collections' entries in the same language.
|
|
1384
|
+
*/
|
|
1385
|
+
async rootSlugConflicts(resourceId: string, base: string, locale: string | null = null): Promise<string[]> {
|
|
1386
|
+
const name = resourceId.startsWith('cms/') ? resourceId.slice(4) : '';
|
|
1387
|
+
const collection = this.#collections.get(name);
|
|
1388
|
+
if (!collection || collection.path !== '') return [];
|
|
1389
|
+
const reserved = new Set(this.#reservedPaths);
|
|
1390
|
+
// Language prefixes, such as /fr, on a site with several languages.
|
|
1391
|
+
const languages = await this.languages();
|
|
1392
|
+
if (languages.multilingual) for (const code of languages.all) reserved.add(code);
|
|
1393
|
+
for (const other of this.#collections.values()) if (other.path) reserved.add(other.path.split('/')[0]!);
|
|
1394
|
+
for (const taxonomy of this.#taxonomies.values()) if (taxonomy.path) reserved.add(taxonomy.path);
|
|
1395
|
+
const taken = [...reserved].filter(word => word === base || word.startsWith(`${base}-`));
|
|
1396
|
+
const others = [...this.#collections.values()].filter(other => other.name !== name && other.path === '' && other.slug !== false);
|
|
1397
|
+
const statements = others.map(other => ({
|
|
1398
|
+
rql: `SELECT "slug" FROM ${this.resourceById(`cms/${other.name}`).storage} WHERE ("slug" = $slug OR "slug" LIKE $prefix)${locale ? ' AND "locale" = $locale' : ''} LIMIT 1000`,
|
|
1399
|
+
params: { $slug: base, $prefix: `${base}-%`, ...(locale ? { $locale: locale } : {}) },
|
|
1400
|
+
}));
|
|
1401
|
+
if (statements.length) for (const result of (await this.db.read(statements)).results) for (const row of result.rows) taken.push(row[0] as string);
|
|
1402
|
+
return taken;
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
/**
|
|
1406
|
+
* Where a collection's archive lists its entries: `/<path>`, or for posts served at the site
|
|
1407
|
+
* root, the Reading settings' posts page (or the home page when it shows the latest posts).
|
|
1408
|
+
*/
|
|
1409
|
+
async archiveUrl(collection: CollectionDefinition, locale?: string | null): Promise<string | null> {
|
|
1410
|
+
const prefix = this.localePrefix(locale, await this.languages());
|
|
1411
|
+
if (collection.path) return `${prefix}/${collection.path}`;
|
|
1412
|
+
if (collection.path !== '' || collection.name !== 'posts') return null;
|
|
1413
|
+
const settings = await this.settings.all();
|
|
1414
|
+
let page = settings['reading.pageForPosts'] && this.#collections.has('pages')
|
|
1415
|
+
? await this.resource('cms/pages').get(settings['reading.pageForPosts'], { principal: ANONYMOUS }).catch(() => null) : null;
|
|
1416
|
+
// In another language, the posts page's translation lists that language's posts; without a locale, the default language's.
|
|
1417
|
+
if (page && prefix) page = (await this.translations(this.collection('pages'), page)).get(locale ?? (await this.languages()).default) ?? null;
|
|
1418
|
+
if (page?.status === 'published') return (await this.entryUrls(this.collection('pages'), [page])).get(page.id) ?? null;
|
|
1419
|
+
return settings['reading.showOnFront'] === 'posts' ? prefix || '/' : null;
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
/** The site's languages from Settings → Languages; the first is the default, served without a prefix. */
|
|
1423
|
+
async languages(): Promise<SiteLanguages> {
|
|
1424
|
+
const settings = await this.settings.all().catch(() => null);
|
|
1425
|
+
const configured = settings?.['languages.default'];
|
|
1426
|
+
const main = typeof configured === 'string' && LOCALE.test(configured) ? configured : 'en';
|
|
1427
|
+
const others = [...new Set(String(settings?.['languages.others'] ?? '').split(',').map(code => code.trim()).filter(code => LOCALE.test(code) && code !== main))];
|
|
1428
|
+
return { default: main, others, all: [main, ...others], multilingual: others.length > 0, prefixDefault: others.length > 0 && settings?.['languages.urls'] === 'all' };
|
|
1429
|
+
}
|
|
1430
|
+
|
|
1431
|
+
/** `/<code>` for an entry in another language than the default, or in any language when `prefixDefault`; empty otherwise. */
|
|
1432
|
+
localePrefix(locale: unknown, languages: SiteLanguages): string {
|
|
1433
|
+
if (!languages.multilingual) return '';
|
|
1434
|
+
const code = typeof locale === 'string' && languages.all.includes(locale) ? locale : languages.default;
|
|
1435
|
+
return code !== languages.default || languages.prefixDefault ? `/${code}` : '';
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
/** Change the site's languages. New entries take the default language, so every entry belongs to one. */
|
|
1439
|
+
async saveLanguages(input: { default: string; others: readonly string[]; urls?: 'hide-default' | 'all' }, principal: Principal): Promise<SiteLanguages> {
|
|
1440
|
+
const codes = [input.default, ...input.others].map(code => String(code).trim().toLowerCase());
|
|
1441
|
+
if (codes.some(code => !LOCALE.test(code)) || new Set(codes).size !== codes.length || codes.length > 20) {
|
|
1442
|
+
throw new CmsError('CMS_VALIDATION', 'Languages are distinct codes such as en, fr or pt-br, at most 20.');
|
|
1443
|
+
}
|
|
1444
|
+
if (input.urls !== undefined && input.urls !== 'hide-default' && input.urls !== 'all') throw new CmsError('CMS_VALIDATION', 'Language in URLs is hide-default or all.');
|
|
1445
|
+
await this.settings.update('languages', { default: codes[0], others: codes.slice(1).join(','), ...(input.urls ? { urls: input.urls } : {}) }, { principal });
|
|
1446
|
+
this.menus.refresh();
|
|
1447
|
+
return this.languages();
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
|
|
1451
|
+
/**
|
|
1452
|
+
* An entry's translations by language, itself included, as the principal may read them.
|
|
1453
|
+
* A translation group is named after its first entry, which keeps no group of its own.
|
|
1454
|
+
*/
|
|
1455
|
+
async translations(collection: CollectionDefinition, record: RecordShape, context: OperationContext = { principal: ANONYMOUS }): Promise<Map<string, RecordShape>> {
|
|
1456
|
+
return (await this.translationsOf(collection, [record], context)).get(translationGroupOf(record))!;
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
/**
|
|
1460
|
+
* The translations of several entries, such as a page of the dashboard's list, by
|
|
1461
|
+
* translation group and then language, each entry itself included. One request per
|
|
1462
|
+
* hundred translations, as the principal may read them.
|
|
1463
|
+
*/
|
|
1464
|
+
async translationsOf(collection: CollectionDefinition, records: readonly RecordShape[], context: OperationContext = { principal: ANONYMOUS }): Promise<Map<string, Map<string, RecordShape>>> {
|
|
1465
|
+
const languages = await this.languages();
|
|
1466
|
+
const localeOf = (entry: RecordShape) => typeof entry.locale === 'string' ? entry.locale : languages.default;
|
|
1467
|
+
const groups = [...new Set(records.map(translationGroupOf))].slice(0, 100);
|
|
1468
|
+
const found = new Map(groups.map(group => [group, new Map<string, RecordShape>()]));
|
|
1469
|
+
const add = (entry: RecordShape) => {
|
|
1470
|
+
const members = found.get(translationGroupOf(entry));
|
|
1471
|
+
if (members && !members.has(localeOf(entry))) members.set(localeOf(entry), entry);
|
|
1472
|
+
};
|
|
1473
|
+
for (const record of records) add(record);
|
|
1474
|
+
if (!groups.length) return found;
|
|
1475
|
+
const repository = this.resource(`cms/${collection.name}`);
|
|
1476
|
+
const known = new Set(records.map(record => record.id));
|
|
1477
|
+
for (const source of (await repository.getMany(groups.filter(group => !known.has(group)), context)).values()) add(source);
|
|
1478
|
+
// At most 20 languages each: 2,000 translations for a full page.
|
|
1479
|
+
for (let offset = 0; offset < 2000; offset += 100) {
|
|
1480
|
+
const page = (await repository.list({ where: { translationGroup: { in: groups } }, limit: 100, offset, order: { field: 'createdAt', direction: 'asc' } }, context)).records;
|
|
1481
|
+
for (const entry of page) add(entry);
|
|
1482
|
+
if (page.length < 100) break;
|
|
1483
|
+
}
|
|
1484
|
+
return found;
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
/**
|
|
1488
|
+
* Start a translation of an entry: a draft copy in the language and the entry's translation
|
|
1489
|
+
* group, with its parent's translation as parent. An existing translation is returned instead.
|
|
1490
|
+
*/
|
|
1491
|
+
async translateEntry(collectionName: string, id: string, locale: string, principal: Principal): Promise<RecordShape> {
|
|
1492
|
+
const languages = await this.languages();
|
|
1493
|
+
if (!languages.all.includes(locale)) throw new CmsError('CMS_VALIDATION', `${locale} is not one of the site's languages.`);
|
|
1494
|
+
const collection = this.collection(collectionName);
|
|
1495
|
+
const repository = this.resource(`cms/${collection.name}`);
|
|
1496
|
+
const source = await repository.get(id, { principal });
|
|
1497
|
+
if (!source) throw new CmsError('CMS_NOT_FOUND', 'Entry not found.');
|
|
1498
|
+
// A translation starts as a copy: a reader the entry is locked for gets none to open.
|
|
1499
|
+
if (lockedCopy(source, repository.canUpdate(source, principal))) throw new CmsError('CMS_FORBIDDEN', 'Only its editors can translate a protected or members-only entry.');
|
|
1500
|
+
// A translation the principal cannot read still exists: never start a second one.
|
|
1501
|
+
const existing = (await this.translations(collection, source, { principal: systemPrincipal('translations') })).get(locale);
|
|
1502
|
+
if (existing) {
|
|
1503
|
+
if ((await repository.getMany([existing.id], { principal })).has(existing.id)) return existing;
|
|
1504
|
+
throw new CmsError('CMS_CONFLICT', `A ${languageName(locale)} translation exists that you cannot open.`);
|
|
1505
|
+
}
|
|
1506
|
+
const input: { [field: string]: unknown } = {};
|
|
1507
|
+
for (const [name, declaration] of Object.entries(repository.resource.fields)) {
|
|
1508
|
+
if (['slug', 'status', 'publishedAt', 'locale', 'translationGroup', 'parent'].includes(name) || source[name] === undefined || source[name] === null) continue;
|
|
1509
|
+
if (declaration.access?.write && !hasPermission(principal, declaration.access.write)) continue;
|
|
1510
|
+
input[name] = source[name];
|
|
1511
|
+
}
|
|
1512
|
+
if (collection.hierarchical && typeof source.parent === 'string') {
|
|
1513
|
+
const parent = (await repository.getMany([source.parent], { principal })).get(source.parent);
|
|
1514
|
+
const translated = parent ? (await this.translations(collection, parent, { principal })).get(locale) : undefined;
|
|
1515
|
+
if (translated) input.parent = translated.id;
|
|
1516
|
+
}
|
|
1517
|
+
const group = typeof source.translationGroup === 'string' ? source.translationGroup : source.id;
|
|
1518
|
+
return repository.create({ ...input, locale, translationGroup: group, ...(collection.publishable === false ? {} : { status: 'draft' }) }, { principal, [JOIN_GROUP]: group } as OperationContext);
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
/**
|
|
1522
|
+
* Public URLs of a collection's entries: the collection's path and, for nested
|
|
1523
|
+
* collections, the slugs of their ancestors, fetched through the parent link in one request.
|
|
1524
|
+
*/
|
|
1525
|
+
async entryUrls(collection: CollectionDefinition, records: readonly RecordShape[], context: OperationContext = { principal: ANONYMOUS }): Promise<Map<string, string | null>> {
|
|
1526
|
+
const urls = new Map<string, string | null>();
|
|
1527
|
+
if (collection.path === null || collection.path === undefined || collection.slug === false) {
|
|
1528
|
+
for (const record of records) urls.set(record.id, null);
|
|
1529
|
+
return urls;
|
|
1530
|
+
}
|
|
1531
|
+
const known = new Map(records.map(record => [record.id, record]));
|
|
1532
|
+
const languages = await this.languages();
|
|
1533
|
+
if (collection.hierarchical) {
|
|
1534
|
+
// Every ancestor chain in one request, through the parent link's record projections.
|
|
1535
|
+
const roots = records.filter(record => typeof record.parent === 'string' && record.parent && !known.has(record.parent)).map(record => record.id);
|
|
1536
|
+
const chains = await this.resource(`cms/${collection.name}`).ancestors(roots, 'parent', context);
|
|
1537
|
+
for (const chain of chains.values()) for (const ancestor of chain) known.set(ancestor.id, ancestor);
|
|
1538
|
+
}
|
|
1539
|
+
// Category permalinks: the slug of each entry's first term, read in one request.
|
|
1540
|
+
const taxonomy = collection.permalink === 'category' ? collection.taxonomies?.[0] : undefined;
|
|
1541
|
+
const terms = taxonomy ? await this.taxonomies.getMany([...new Set(records.map(record => this.#firstTerm(record, taxonomy)).filter((id): id is string => !!id))]) : new Map<string, TermShape>();
|
|
1542
|
+
// The page Settings → Reading shows on the front is the home page: its address is the site's (its language's), never its slug's.
|
|
1543
|
+
const front = collection.name === 'pages' ? await this.#frontPage(records, languages, context) : null;
|
|
1544
|
+
for (const record of records) {
|
|
1545
|
+
if (front && (record.id === front.id || (front.group && translationGroupOf(record) === front.group))) {
|
|
1546
|
+
urls.set(record.id, this.localePrefix(record.locale, languages) || '/');
|
|
1547
|
+
continue;
|
|
1548
|
+
}
|
|
1549
|
+
const slugs: string[] = [];
|
|
1550
|
+
let current: RecordShape | undefined = record;
|
|
1551
|
+
for (let depth = 0; current && depth < 9; depth++) {
|
|
1552
|
+
if (typeof current.slug !== 'string') { slugs.length = 0; break; }
|
|
1553
|
+
slugs.unshift(current.slug);
|
|
1554
|
+
const parent: string | null = collection.hierarchical ? current.parent as string | null : null;
|
|
1555
|
+
current = parent ? known.get(parent) : undefined;
|
|
1556
|
+
if (parent && !current) { slugs.length = 0; break; }
|
|
1557
|
+
}
|
|
1558
|
+
const term = taxonomy ? terms.get(this.#firstTerm(record, taxonomy) ?? '') : undefined;
|
|
1559
|
+
if (term && slugs.length) slugs.unshift(term.slug);
|
|
1560
|
+
const url = entryUrl(collection.path, slugs);
|
|
1561
|
+
urls.set(record.id, url ? `${this.localePrefix(record.locale, languages)}${url}` : null);
|
|
1562
|
+
}
|
|
1563
|
+
return urls;
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
/** The front page's ID and, on a site with several languages, its translation group; null while the front shows the latest posts. */
|
|
1567
|
+
async #frontPage(records: readonly RecordShape[], languages: SiteLanguages, context: OperationContext): Promise<{ id: string; group: string } | null> {
|
|
1568
|
+
const settings = await this.settings.all().catch(() => null);
|
|
1569
|
+
const id = settings && settings['reading.showOnFront'] === 'page' ? String(settings['reading.pageOnFront'] ?? '') : '';
|
|
1570
|
+
if (!id) return null;
|
|
1571
|
+
if (!languages.multilingual) return { id, group: '' };
|
|
1572
|
+
// Its translations are the other languages' home pages. Read it only when it is not among the records.
|
|
1573
|
+
const page = records.find(record => record.id === id) ?? await this.resource('cms/pages').get(id, context).catch(() => null);
|
|
1574
|
+
return { id, group: page ? translationGroupOf(page) : '' };
|
|
1575
|
+
}
|
|
1576
|
+
|
|
1577
|
+
/** The first term of a record's taxonomy field, which category permalinks use. */
|
|
1578
|
+
#firstTerm(record: RecordShape, taxonomy: string): string | null {
|
|
1579
|
+
const value = record[taxonomy];
|
|
1580
|
+
return Array.isArray(value) && typeof value[0] === 'string' ? value[0] : null;
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
/**
|
|
1584
|
+
* Create or change a collection. Its table and indexes change in one migration step that
|
|
1585
|
+
* also stores the definition; built-in collections store only what was changed. With
|
|
1586
|
+
* `groups`, the field groups attached to the collection are set to that list in that order:
|
|
1587
|
+
* groups it leaves out are detached, and the schema is planned once for all of it.
|
|
1588
|
+
*/
|
|
1589
|
+
async saveCollection(given: CollectionDefinition, principal: Principal, options: { readonly groups?: readonly { readonly id: string; readonly order?: number }[] } = {}): Promise<CollectionDefinition> {
|
|
1590
|
+
this.#authorizeBuilder(principal);
|
|
1591
|
+
await this.ready({ force: true });
|
|
1592
|
+
const before = this.#collections.get(given.name);
|
|
1593
|
+
const searched = this.siteSearch.signature(given.name);
|
|
1594
|
+
const builtin = this.#builtinCollections.get(given.name);
|
|
1595
|
+
if (builtin?.managed) throw new CmsError('CMS_FORBIDDEN', `${builtin.label} is managed by its module and has its own screens.`);
|
|
1596
|
+
// Managed is the module's to declare.
|
|
1597
|
+
const { managed: _managed, ...input } = given;
|
|
1598
|
+
const stored: CollectionDefinition = builtin ? {
|
|
1599
|
+
name: input.name, label: input.label, singular: input.singular, ...(input.description !== undefined ? { description: input.description } : {}),
|
|
1600
|
+
...(input.icon !== undefined ? { icon: input.icon } : {}), ...(input.path !== undefined ? { path: input.path } : {}),
|
|
1601
|
+
...(input.permalink !== undefined ? { permalink: input.permalink } : {}),
|
|
1602
|
+
...(input.sitemap !== undefined ? { sitemap: input.sitemap } : {}),
|
|
1603
|
+
...(input.schema !== undefined ? { schema: input.schema } : {}),
|
|
1604
|
+
...(input.robots !== undefined ? { robots: input.robots } : {}),
|
|
1605
|
+
...(input.seoTemplates !== undefined ? { seoTemplates: input.seoTemplates } : {}),
|
|
1606
|
+
...(input.comments !== undefined ? { comments: input.comments } : {}),
|
|
1607
|
+
...(input.features !== undefined ? { features: input.features } : {}),
|
|
1608
|
+
...(input.template !== undefined ? { template: input.template } : {}),
|
|
1609
|
+
...(input.templateLock !== undefined ? { templateLock: input.templateLock } : {}),
|
|
1610
|
+
...(input.editor !== undefined ? { editor: input.editor } : {}),
|
|
1611
|
+
taxonomies: (input.taxonomies ?? []).filter(name => !(builtin.taxonomies ?? []).includes(name)),
|
|
1612
|
+
fields: Object.fromEntries(Object.entries(input.fields ?? {}).filter(([name]) => !Object.hasOwn(builtin.fields, name))),
|
|
1613
|
+
// The module's fields are not stored, so their place among the added ones is.
|
|
1614
|
+
fieldOrder: [...(input.fieldOrder ?? Object.keys(input.fields ?? {}))],
|
|
1615
|
+
} : (({ fieldOrder, ...rest }) => ({ ...rest, fields: orderedFields(input.fields ?? {}, fieldOrder), builtin: false }))(input);
|
|
1616
|
+
const definition = builtin ? extendCollection(builtin, stored) : stored;
|
|
1617
|
+
const problems = collectionProblems(definition);
|
|
1618
|
+
if (!builtin && this.#static.has(`cms/${definition.name}`)) problems.push(`cms/${definition.name} is already a resource.`);
|
|
1619
|
+
// Structured data maps name fields of the collection: its own, the features' and its groups'.
|
|
1620
|
+
if (!problems.length && definition.schema?.map) problems.push(...collectionSeoProblems({ schema: definition.schema, fields: Object.keys(this.#collectionResource(definition, this.#taxonomyLabels()).fields) }));
|
|
1621
|
+
for (const taxonomy of definition.taxonomies ?? []) if (!this.#taxonomies.has(taxonomy)) problems.push(`Taxonomy ${taxonomy} does not exist.`);
|
|
1622
|
+
for (const [name, declaration] of Object.entries(definition.fields)) {
|
|
1623
|
+
if (declaration.kind === 'reference' && declaration.target !== `cms/${definition.name}` && !this.#resources.has(declaration.target!)) problems.push(`Field ${name} refers to ${declaration.target}, which does not exist.`);
|
|
1624
|
+
for (const type of declaration.blocks ?? []) if (!this.#blocks.has(type)) problems.push(`Field ${name} allows ${type}, which is not a block type.`);
|
|
1625
|
+
}
|
|
1626
|
+
// The content template is checked like an entry's blocks, against the content's allowed types.
|
|
1627
|
+
if (definition.template?.length && !problems.length) {
|
|
1628
|
+
const allowed = contentBlocks(definition.features?.content) ?? [];
|
|
1629
|
+
const { errors } = validateBlocks(definition.template, this.#blocks, allowed.length ? { allowed } : {});
|
|
1630
|
+
problems.push(...Object.entries(errors).map(([path, message]) => `Template block ${path}: ${message}`));
|
|
1631
|
+
if (!hasPermission(principal, PERMISSIONS.unfilteredHtml) && htmlBlocksChanged(definition.template, before?.template)) problems.push('The template has a Custom HTML block, which only people allowed to post HTML can add or change.');
|
|
1632
|
+
}
|
|
1633
|
+
// The attached groups: each checked against the collection's fields and the other attached groups.
|
|
1634
|
+
const target: FieldGroupTarget = { kind: 'collection', name: definition.name };
|
|
1635
|
+
const changed: FieldGroup[] = [];
|
|
1636
|
+
if (options.groups) {
|
|
1637
|
+
const wanted = new Map(options.groups.map((entry, index) => [entry.id, entry.order ?? index]));
|
|
1638
|
+
for (const id of wanted.keys()) if (!this.#groups.some(group => group.id === id)) problems.push(`Field group ${id} does not exist.`);
|
|
1639
|
+
// A plugin's group is attached by its manifest; the list cannot detach or reorder it.
|
|
1640
|
+
const attached = this.#groups.map(group => group.plugin ? group : wanted.has(group.id) ? withTarget(group, target, true, wanted.get(group.id)) : withTarget(group, target, false));
|
|
1641
|
+
for (const [index, group] of attached.entries()) if (canonicalJson(group) !== canonicalJson(this.#groups[index])) changed.push(group);
|
|
1642
|
+
const scope = [...RESERVED_FIELDS, ...(definition.taxonomies ?? []), ...Object.keys(definition.fields)];
|
|
1643
|
+
const taken = new Map<string, string>();
|
|
1644
|
+
for (const group of groupsForTarget(attached, target)) {
|
|
1645
|
+
const checked = fieldGroupProblems(group, this.#blocks, scope);
|
|
1646
|
+
problems.push(...checked.problems.map(problem => `Field group ${group.title}: ${problem}`));
|
|
1647
|
+
for (const name of Object.keys(checked.fields)) {
|
|
1648
|
+
if (taken.has(name)) problems.push(`Field ${name} is in both “${taken.get(name)}” and “${group.title}”.`);
|
|
1649
|
+
taken.set(name, group.title);
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1653
|
+
if (problems.length) throw new CmsError('CMS_VALIDATION', problems.join(' '), { fields: { definition: problems.join(' ') } });
|
|
1654
|
+
for (const group of changed) await this.fieldGroups.put(group, principal);
|
|
1655
|
+
if (changed.length) this.#groups = await this.fieldGroups.all();
|
|
1656
|
+
// The same resource `ready()` builds from the stored definition; its hash is what the migration records.
|
|
1657
|
+
const resource = this.#collectionResource(definition, this.#taxonomyLabels());
|
|
1658
|
+
const row: Statement = {
|
|
1659
|
+
rql: 'INSERT INTO cms_collections (name, definition, updated_at, updated_by) VALUES ($name, $definition, $now, $by) ON CONFLICT (name) DO UPDATE SET definition = excluded.definition, updated_at = excluded.updated_at, updated_by = excluded.updated_by',
|
|
1660
|
+
params: { $name: definition.name, $definition: JSON.stringify(stored), $now: this.#now(), $by: principalId(principal) },
|
|
1661
|
+
};
|
|
1662
|
+
// A new path: old links redirect, from the outbox job this write queues.
|
|
1663
|
+
const moved = before && before.path !== definition.path && typeof before.path === 'string' && typeof definition.path === 'string' && before.slug !== false
|
|
1664
|
+
? pathsMovedStatement({ at: this.#now(), kind: 'collection', name: definition.name, from: before.path, to: definition.path, by: principalId(principal) }) : null;
|
|
1665
|
+
const saving = moved ? [row, moved] : [row];
|
|
1666
|
+
const resources = [...[...this.#resources.values()].filter(entry => entry.id !== resource.id), resource];
|
|
1667
|
+
let attached = false;
|
|
1668
|
+
const plan = await planSchema(resources, await readCatalog(this.db, resources.map(entry => entry.storage)));
|
|
1669
|
+
const blocked = plan.blocked.filter(problem => problem.resource === resource.id);
|
|
1670
|
+
if (blocked.length) throw new CmsError('CMS_VALIDATION', blocked.map(problem => problem.message).join(' '));
|
|
1671
|
+
const report = await migrate(this.db, resources, { now: this.#now, only: [resource.id], attach: id => id === resource.id ? (attached = true, saving) : [] });
|
|
1672
|
+
if (report.failed) throw new CmsError('CMS_CONFLICT', `The collection could not be saved: ${report.failed.message}`);
|
|
1673
|
+
if (!attached) await this.db.write(saving, { kind: 'cms.collections', retryConflicts: 5 });
|
|
1674
|
+
if (moved) this.outboxWritten();
|
|
1675
|
+
this.#activation = undefined;
|
|
1676
|
+
await this.ready({ force: true });
|
|
1677
|
+
const saved = this.collection(definition.name);
|
|
1678
|
+
// A new path, status rule or searched field changes which entries visitors find, and what in them.
|
|
1679
|
+
if (before && this.siteSearch.signature(saved.name) !== searched) await this.siteSearch.rebuild({ only: saved.name });
|
|
1680
|
+
return saved;
|
|
1681
|
+
}
|
|
1682
|
+
|
|
1683
|
+
/**
|
|
1684
|
+
* Automatic redirects for an entry whose URL changes while it stays published, added to the
|
|
1685
|
+
* entry's write and guarded by it. Called by repositories.
|
|
1686
|
+
*/
|
|
1687
|
+
async redirectStatements(resource: Resource, before: RecordShape, after: RecordShape, guard: { rql: string; params: { [key: string]: Value } }, by: string | null): Promise<Statement[]> {
|
|
1688
|
+
const collection = resource.owner === 'cms' ? this.#collections.get(resource.name) : undefined;
|
|
1689
|
+
if (!collection || collection.path === null || collection.path === undefined || collection.slug === false) return [];
|
|
1690
|
+
const live = (record: RecordShape) => collection.publishable === false || record.status === 'published';
|
|
1691
|
+
const taxonomy = collection.permalink === 'category' ? collection.taxonomies?.[0] : undefined;
|
|
1692
|
+
const sameTerm = !taxonomy || this.#firstTerm(before, taxonomy) === this.#firstTerm(after, taxonomy);
|
|
1693
|
+
if (!live(before) || !live(after) || (before.slug === after.slug && before.parent === after.parent && before.locale === after.locale && sameTerm)) return [];
|
|
1694
|
+
const from = (await this.entryUrls(collection, [before])).get(before.id);
|
|
1695
|
+
const to = (await this.entryUrls(collection, [after])).get(after.id);
|
|
1696
|
+
return from && to && from !== to ? this.redirects.automatic(from, to, { guard: guard.rql, params: guard.params, by }) : [];
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1699
|
+
/**
|
|
1700
|
+
* Old links keep working after a collection's URL path changes: `/<old>/*` redirects to the
|
|
1701
|
+
* new path, the archive to the new archive, and entries that leave the site root one by one.
|
|
1702
|
+
*/
|
|
1703
|
+
async #pathRedirects(before: CollectionDefinition, after: CollectionDefinition, by: string | null): Promise<void> {
|
|
1704
|
+
if (before.path === null || before.path === undefined || after.path === null || after.path === undefined || before.slug === false) return;
|
|
1705
|
+
const pairs: { from: string; to: string; prefix?: boolean }[] = [];
|
|
1706
|
+
if (before.path) {
|
|
1707
|
+
pairs.push({ from: `/${before.path}`, to: after.path ? `/${after.path}` : '/', prefix: true });
|
|
1708
|
+
const archive = await this.archiveUrl(after);
|
|
1709
|
+
if (archive) pairs.push({ from: `/${before.path}`, to: archive });
|
|
1710
|
+
} else {
|
|
1711
|
+
// Entries leave the site root: a prefix of / would catch every missing page.
|
|
1712
|
+
const repository = this.resource(`cms/${after.name}`);
|
|
1713
|
+
const languages = await this.languages();
|
|
1714
|
+
const where: { [field: string]: FieldFilter } = after.publishable === false ? {} : { status: 'published' };
|
|
1715
|
+
for (let offset = 0; offset < 1000; offset += 100) {
|
|
1716
|
+
const page = await repository.list({ where, order: { field: 'createdAt', direction: 'asc' }, limit: 100, offset }, { principal: systemPrincipal('redirects') });
|
|
1717
|
+
const urls = await this.entryUrls(after, page.records);
|
|
1718
|
+
for (const record of page.records) {
|
|
1719
|
+
const to = urls.get(record.id);
|
|
1720
|
+
// Each entry answered under its own language's prefix.
|
|
1721
|
+
if (to && typeof record.slug === 'string') pairs.push({ from: `${this.localePrefix(record.locale, languages)}/${record.slug}`, to });
|
|
1722
|
+
}
|
|
1723
|
+
if (!page.more) break;
|
|
1724
|
+
}
|
|
1725
|
+
}
|
|
1726
|
+
await this.redirects.record(pairs, by);
|
|
1727
|
+
// The new path serves the collection again: an older redirect away from it goes.
|
|
1728
|
+
if (after.path) await this.redirects.dropPrefix(`/${after.path}`);
|
|
1729
|
+
}
|
|
1730
|
+
|
|
1731
|
+
/** Delete a collection the dashboard defined, with its table and entries. */
|
|
1732
|
+
async deleteCollection(name: string, principal: Principal): Promise<void> {
|
|
1733
|
+
this.#authorizeBuilder(principal);
|
|
1734
|
+
await this.ready({ force: true });
|
|
1735
|
+
if (this.#builtinCollections.has(name)) throw new CmsError('CMS_FORBIDDEN', 'Built-in collections cannot be deleted.');
|
|
1736
|
+
const definition = this.collection(name);
|
|
1737
|
+
const id = `cms/${definition.name}`;
|
|
1738
|
+
const referrers = this.resources.filter(resource => resource.id !== id && Object.values(resource.fields).some(field => field.kind === 'reference' && field.target === id));
|
|
1739
|
+
if (referrers.length) throw new CmsError('CMS_CONFLICT', `${referrers.map(resource => resource.label ?? resource.id).join(', ')} refer to this collection.`);
|
|
1740
|
+
const storage = this.resourceById(id).storage;
|
|
1741
|
+
// The groups attached to it stay, for other targets, without it: in the batch that drops
|
|
1742
|
+
// it, so a failure leaves both as they were. Groups that do not fit go first, each batch
|
|
1743
|
+
// a schema change the other servers reload, and a retry finds them detached.
|
|
1744
|
+
const detach = groupsForTarget(this.#groups, { kind: 'collection', name }).map(group => this.fieldGroups.putStatement(withTarget(group, { kind: 'collection', name }, false), principal));
|
|
1745
|
+
const room = MAX_STATEMENTS - 7;
|
|
1746
|
+
try {
|
|
1747
|
+
while (detach.length > room) await this.db.write([...detach.splice(0, room), nextGenerationStatement(this.#now())], { kind: 'cms.fieldGroups' });
|
|
1748
|
+
} finally {
|
|
1749
|
+
this.fieldGroups.reset();
|
|
1750
|
+
}
|
|
1751
|
+
const info = await this.db.read([{ rql: 'INFO FOR DB' }]);
|
|
1752
|
+
const exists = ((info.results[0]!.rows[0]![0] as { tables?: { name: string }[] }).tables ?? []).some(table => table.name === storage);
|
|
1753
|
+
const at = this.#now();
|
|
1754
|
+
try {
|
|
1755
|
+
await this.db.write([
|
|
1756
|
+
...detach,
|
|
1757
|
+
...(exists ? [{ rql: `DROP TABLE ${storage}` }] : []),
|
|
1758
|
+
{ rql: 'DELETE FROM cms_collections WHERE name = $name', params: { $name: name } },
|
|
1759
|
+
{ rql: 'DELETE FROM cms_schema_state WHERE resource = $id', params: { $id: id } },
|
|
1760
|
+
{ rql: `DELETE FROM ${SITE_SEARCH.collection} WHERE collection = $name`, params: { $name: name } },
|
|
1761
|
+
// Its comments go from the outbox, which retries until they are gone.
|
|
1762
|
+
collectionDeletedStatement(id, `collection.deleted:${id}:${uuidv7()}`, at),
|
|
1763
|
+
nextGenerationStatement(at),
|
|
1764
|
+
], { kind: 'cms.collections' });
|
|
1765
|
+
} finally {
|
|
1766
|
+
this.fieldGroups.reset();
|
|
1767
|
+
}
|
|
1768
|
+
this.outboxWritten();
|
|
1769
|
+
this.#activation = undefined;
|
|
1770
|
+
await this.ready({ force: true });
|
|
1771
|
+
}
|
|
1772
|
+
|
|
1773
|
+
/** Create or change a taxonomy. Built-in taxonomies keep their name and nesting. */
|
|
1774
|
+
async saveTaxonomy(input: TaxonomyDeclaration, principal: Principal): Promise<TaxonomyDeclaration> {
|
|
1775
|
+
this.#authorizeBuilder(principal);
|
|
1776
|
+
await this.ready({ force: true });
|
|
1777
|
+
const builtin = this.#builtinTaxonomies.get(input.name);
|
|
1778
|
+
const extras = { ...(input.description !== undefined ? { description: input.description } : {}), ...(input.noindex !== undefined ? { noindex: input.noindex } : {}) };
|
|
1779
|
+
const declaration: TaxonomyDeclaration = builtin ? { ...builtin, label: input.label, singular: input.singular, path: input.path ?? null, ...extras }
|
|
1780
|
+
: { name: input.name, label: input.label, singular: input.singular, hierarchical: input.hierarchical, path: input.path ?? null, ...extras };
|
|
1781
|
+
const problems = taxonomyProblems(declaration);
|
|
1782
|
+
// Collections store a taxonomy's terms in a field of the same name.
|
|
1783
|
+
if (!builtin && (RESERVED_FIELDS.includes(declaration.name) || [...this.#collections.values()].some(collection => Object.hasOwn(collection.fields, declaration.name)))) problems.push(`${declaration.name} is already a field name.`);
|
|
1784
|
+
if (problems.length) throw new CmsError('CMS_VALIDATION', problems.join(' '));
|
|
1785
|
+
const current = this.#taxonomies.get(declaration.name);
|
|
1786
|
+
if (current?.hierarchical && !declaration.hierarchical) {
|
|
1787
|
+
const nested = await this.db.read([{ rql: 'SELECT count(*) FROM cms_terms WHERE taxonomy = $taxonomy AND parent_id IS NOT NULL', params: { $taxonomy: declaration.name } }]);
|
|
1788
|
+
if (Number(nested.results[0]!.rows[0]![0] as bigint)) throw new CmsError('CMS_CONFLICT', `Some ${declaration.label.toLowerCase()} have parents. Move them to the top level first.`);
|
|
1789
|
+
}
|
|
1790
|
+
// Term archives keep answering at the old path, from the outbox job this write queues.
|
|
1791
|
+
const moved = current?.path && declaration.path && current.path !== declaration.path
|
|
1792
|
+
? pathsMovedStatement({ at: this.#now(), kind: 'taxonomy', name: declaration.name, from: current.path, to: declaration.path, by: principalId(principal) }) : null;
|
|
1793
|
+
await this.db.write([{
|
|
1794
|
+
rql: 'INSERT INTO cms_taxonomies (name, definition, updated_at, updated_by) VALUES ($name, $definition, $now, $by) ON CONFLICT (name) DO UPDATE SET definition = excluded.definition, updated_at = excluded.updated_at, updated_by = excluded.updated_by',
|
|
1795
|
+
params: { $name: declaration.name, $definition: JSON.stringify(declaration), $now: this.#now(), $by: principalId(principal) },
|
|
1796
|
+
}, ...(moved ? [moved] : [])], { kind: 'cms.collections', retryConflicts: 5 });
|
|
1797
|
+
if (moved) this.outboxWritten();
|
|
1798
|
+
await this.ready({ force: true });
|
|
1799
|
+
return this.taxonomies.declaration(declaration.name);
|
|
1800
|
+
}
|
|
1801
|
+
|
|
1802
|
+
/** Delete a taxonomy the dashboard defined, with its terms. Collections must stop using it first. */
|
|
1803
|
+
async deleteTaxonomy(name: string, principal: Principal): Promise<void> {
|
|
1804
|
+
this.#authorizeBuilder(principal);
|
|
1805
|
+
await this.ready({ force: true });
|
|
1806
|
+
if (this.#builtinTaxonomies.has(name)) throw new CmsError('CMS_FORBIDDEN', 'Built-in taxonomies cannot be deleted.');
|
|
1807
|
+
this.taxonomies.declaration(name);
|
|
1808
|
+
const users = this.collections().filter(collection => collection.taxonomies?.includes(name));
|
|
1809
|
+
if (users.length) throw new CmsError('CMS_CONFLICT', `${users.map(collection => collection.label).join(', ')} use this taxonomy.`);
|
|
1810
|
+
await this.db.write([
|
|
1811
|
+
{ rql: 'DELETE FROM cms_terms WHERE taxonomy = $name', params: { $name: name } },
|
|
1812
|
+
{ rql: 'DELETE FROM cms_taxonomies WHERE name = $name', params: { $name: name } },
|
|
1813
|
+
], { kind: 'cms.collections' });
|
|
1814
|
+
await this.ready({ force: true });
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
/** Resources the principal may read, for navigation. */
|
|
1818
|
+
readable(principal: Principal): Resource[] {
|
|
1819
|
+
return this.resources.filter(resource => evaluateRule(resource.access.read, principal) !== 'deny');
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
async plan(options: { signal?: AbortSignal } = {}): Promise<SchemaPlan> {
|
|
1823
|
+
return planSchema(this.resources, await readCatalog(this.db, this.resources.map(resource => resource.storage), options));
|
|
1824
|
+
}
|
|
1825
|
+
|
|
1826
|
+
async migrate(options: { signal?: AbortSignal } = {}): Promise<MigrationReport> {
|
|
1827
|
+
const report = await migrate(this.db, this.resources, { ...options, now: this.#now });
|
|
1828
|
+
this.#activation = undefined;
|
|
1829
|
+
return report;
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
/**
|
|
1833
|
+
* A resource is active when the database records its current declaration and its plugin is
|
|
1834
|
+
* active. Writes to collections read the recorded hash fresh: a definition changed by another
|
|
1835
|
+
* isolate is reloaded before the write is validated.
|
|
1836
|
+
*/
|
|
1837
|
+
async assertActive(resource: Resource, options: { fresh?: boolean } = {}): Promise<void> {
|
|
1838
|
+
const collection = resource.owner === 'cms' && this.#collections.has(resource.name);
|
|
1839
|
+
const recorded = async () => {
|
|
1840
|
+
if (!(options.fresh && collection)) return (await this.#state()).hashes.get(resource.id);
|
|
1841
|
+
const result = await this.db.read([{ rql: 'SELECT declaration_hash FROM cms_schema_state WHERE resource = $id', params: { $id: resource.id } }]);
|
|
1842
|
+
return result.results[0]!.rows[0]?.[0] as string | undefined;
|
|
1843
|
+
};
|
|
1844
|
+
let current = this.#resources.get(resource.id) ?? resource;
|
|
1845
|
+
let hash = await recorded();
|
|
1846
|
+
if (hash !== await declarationHash(current) && collection) {
|
|
1847
|
+
// Another isolate changed the collection: reload its definition and activation once.
|
|
1848
|
+
this.#activation = undefined;
|
|
1849
|
+
await this.ready({ force: true });
|
|
1850
|
+
current = this.#resources.get(resource.id) ?? current;
|
|
1851
|
+
hash = await recorded();
|
|
1852
|
+
}
|
|
1853
|
+
if (hash !== await declarationHash(current)) {
|
|
1854
|
+
throw new CmsError('CMS_UNAVAILABLE', `${resource.id} is waiting for a schema migration.`, { lasting: true });
|
|
1855
|
+
}
|
|
1856
|
+
const owner = collection ? this.#collections.get(resource.name)?.plugin ?? resource.owner : resource.owner;
|
|
1857
|
+
const plugin = this.#plugins.get(owner);
|
|
1858
|
+
if (plugin && !(await this.#pluginStatus(plugin, await this.#state())).active) throw new CmsError('CMS_UNAVAILABLE', `Plugin ${owner} is not active.`, { lasting: true });
|
|
1859
|
+
}
|
|
1860
|
+
|
|
1861
|
+
async status(): Promise<ActivationStatus> {
|
|
1862
|
+
const state = await this.#state();
|
|
1863
|
+
const resources = await Promise.all(this.resources.map(async resource => ({ id: resource.id, active: state.hashes.get(resource.id) === await declarationHash(resource) })));
|
|
1864
|
+
const plugins = await Promise.all([...this.#plugins.values()].map(plugin => this.#pluginStatus(plugin, state)));
|
|
1865
|
+
return { resources, plugins };
|
|
1866
|
+
}
|
|
1867
|
+
|
|
1868
|
+
/** The names of the plugins active on this site, themes included, as of the last refresh. */
|
|
1869
|
+
activePluginNames(): readonly string[] {
|
|
1870
|
+
return [...this.#activePlugins];
|
|
1871
|
+
}
|
|
1872
|
+
|
|
1873
|
+
async pluginActive(name: string): Promise<boolean> {
|
|
1874
|
+
const plugin = this.#plugins.get(name);
|
|
1875
|
+
return plugin ? (await this.#pluginStatus(plugin, await this.#state())).active : false;
|
|
1876
|
+
}
|
|
1877
|
+
|
|
1878
|
+
/**
|
|
1879
|
+
* Record an administrator's grant of everything the plugin's manifest requests. An upgrade
|
|
1880
|
+
* that requests more leaves the plugin inactive until it is granted again. A plugin asking
|
|
1881
|
+
* for unrestricted access also takes `{ unrestricted: true }` and a network admin, since it
|
|
1882
|
+
* can reach every site, and the grant is written to the audit trail.
|
|
1883
|
+
*/
|
|
1884
|
+
async grantPlugin(name: string, principal: Principal, options: { unrestricted?: boolean } = {}): Promise<PluginStatus> {
|
|
1885
|
+
if (!hasPermission(principal, PERMISSIONS.managePlugins)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to manage plugins.');
|
|
1886
|
+
const plugin = this.#plugins.get(name);
|
|
1887
|
+
const network = pluginState((await this.#state()).policy, name);
|
|
1888
|
+
if (!plugin || network === 'hidden') throw new CmsError('CMS_NOT_FOUND', `Unknown plugin ${name}.`);
|
|
1889
|
+
if (network === 'network') throw new CmsError('CMS_FORBIDDEN', `The network activates ${name} on every site.`);
|
|
1890
|
+
if (plugin.problems.length) throw new CmsError('CMS_VALIDATION', `Plugin ${name} has an invalid manifest: ${plugin.problems.join(' ')}`);
|
|
1891
|
+
const unrestricted = plugin.requested.includes(UNRESTRICTED_GRANT);
|
|
1892
|
+
if (unrestricted && !options.unrestricted) throw new CmsError('CMS_CONFLICT', `Plugin ${name} was not enabled: unrestricted access has to be confirmed on its own.`);
|
|
1893
|
+
if (unrestricted && !isNetworkAdmin(principal)) throw new CmsError('CMS_FORBIDDEN', 'Only a network admin can grant unrestricted access.');
|
|
1894
|
+
const now = this.#now();
|
|
1895
|
+
await this.db.write([
|
|
1896
|
+
...(unrestricted ? [unrestrictedGrantAudit(name, principalId(principal), now)] : []),
|
|
1897
|
+
{ rql: 'DELETE FROM cms_grants WHERE subject = $subject', params: { $subject: `plugin:${name}` } },
|
|
1898
|
+
...[PLUGIN_ENABLED, ...plugin.requested].map((permission, index) => ({
|
|
1899
|
+
rql: 'INSERT INTO cms_grants (id, subject, permission, revision, created_at) VALUES ($id, $subject, $permission, $revision, $now)',
|
|
1900
|
+
params: { $id: `${name}:${index}:${now}`, $subject: `plugin:${name}`, $permission: permission, $revision: now, $now: now },
|
|
1901
|
+
})),
|
|
1902
|
+
], { kind: 'cms.grants', retryConflicts: 5 });
|
|
1903
|
+
this.#activation = undefined;
|
|
1904
|
+
await this.#refreshPlugins();
|
|
1905
|
+
await this.#purgeSite('plugins');
|
|
1906
|
+
await this.#seedFieldGroups(plugin, principal);
|
|
1907
|
+
await this.#seedPatterns(plugin, principal);
|
|
1908
|
+
return this.#pluginStatus(plugin, await this.#state());
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
/**
|
|
1912
|
+
* Store the patterns a plugin's manifest ships, as `<plugin>-<slug>`: sections a theme or a
|
|
1913
|
+
* plugin offers in the pattern picker. A pattern the site already has is left as it is, edited
|
|
1914
|
+
* or not; with `onlyIfNone`, nothing is added while the site has any of them, so a pattern it
|
|
1915
|
+
* deleted stays deleted across starts and comes back with the plugin's next grant or activation.
|
|
1916
|
+
*/
|
|
1917
|
+
async #seedPatterns(plugin: HostedPlugin, principal: Principal, options: { onlyIfNone?: boolean } = {}): Promise<void> {
|
|
1918
|
+
const declared = plugin.manifest.patterns ?? [];
|
|
1919
|
+
if (!declared.length || !this.#collections.has('patterns')) return;
|
|
1920
|
+
const repository = this.resource('cms/patterns');
|
|
1921
|
+
const ids = declared.map(pattern => `${plugin.manifest.name}-${pattern.slug}`);
|
|
1922
|
+
const existing = await repository.getMany(ids, { principal });
|
|
1923
|
+
if (options.onlyIfNone && existing.size) return;
|
|
1924
|
+
for (const [index, pattern] of declared.entries()) {
|
|
1925
|
+
if (existing.has(ids[index]!)) continue;
|
|
1926
|
+
await repository.create({ title: pattern.title, content: pattern.blocks, synced: pattern.synced === true, starter: [...(pattern.starter ?? [])] }, { principal, id: ids[index]! });
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
/**
|
|
1931
|
+
* Store the field groups a plugin's manifest ships, tagged with the plugin, and plan their
|
|
1932
|
+
* targets' schemas. Granting the plugin again after an upgrade replaces them; the groups
|
|
1933
|
+
* stay, with their fields' values, while the plugin is inactive, and go with the plugin.
|
|
1934
|
+
*/
|
|
1935
|
+
async #seedFieldGroups(plugin: HostedPlugin, principal: Principal): Promise<void> {
|
|
1936
|
+
if (!plugin.manifest.fieldGroups?.length) return;
|
|
1937
|
+
await this.ready({ force: true });
|
|
1938
|
+
for (const declared of plugin.manifest.fieldGroups) {
|
|
1939
|
+
const group: FieldGroup = { ...declared, plugin: plugin.manifest.name };
|
|
1940
|
+
const scope = [...new Set(group.targets.flatMap(target => this.#targetScope(target)))];
|
|
1941
|
+
const checked = fieldGroupProblems(group, this.#blocks, scope);
|
|
1942
|
+
for (const target of group.targets) if (target.kind === 'collection' && !this.#collections.has(target.name)) checked.problems.push(`Collection ${target.name} does not exist.`);
|
|
1943
|
+
if (checked.problems.length) throw new CmsError('CMS_VALIDATION', `Field group ${group.id} of ${plugin.manifest.name}: ${checked.problems.join(' ')}`);
|
|
1944
|
+
await this.fieldGroups.put({ ...group, blocks: checked.blocks }, principal);
|
|
1945
|
+
await this.#migrateTargets(group, principal);
|
|
1946
|
+
}
|
|
1947
|
+
}
|
|
1948
|
+
|
|
1949
|
+
/** What active plugins add to a collection's entry editor: their tabs and sidebar boxes, in plugin order. */
|
|
1950
|
+
editorLayoutAdditions(collection: string): EditorLayoutAddition[] {
|
|
1951
|
+
return [...this.#plugins.values()].filter(plugin => !plugin.problems.length && this.#activePlugins.has(plugin.manifest.name))
|
|
1952
|
+
.flatMap(plugin => (plugin.manifest.editor ?? []).filter(entry => entry.collection === collection)
|
|
1953
|
+
.map(entry => ({ plugin: plugin.manifest.name, layout: { tabs: entry.tabs ?? [], sidebar: entry.sidebar ?? [] } })));
|
|
1954
|
+
}
|
|
1955
|
+
|
|
1956
|
+
/** Disable a plugin: its grants are removed; its hooks, commands and resources stop. Data stays. */
|
|
1957
|
+
async revokePlugin(name: string, principal: Principal): Promise<void> {
|
|
1958
|
+
if (!hasPermission(principal, PERMISSIONS.managePlugins)) throw new CmsError('CMS_FORBIDDEN', 'Not allowed to manage plugins.');
|
|
1959
|
+
if (pluginState((await this.#state()).policy, name) === 'network') throw new CmsError('CMS_FORBIDDEN', `The network keeps ${name} active on every site.`);
|
|
1960
|
+
await this.db.write([{ rql: 'DELETE FROM cms_grants WHERE subject = $subject', params: { $subject: `plugin:${name}` } }], { kind: 'cms.grants', retryConflicts: 5 });
|
|
1961
|
+
this.#activation = undefined;
|
|
1962
|
+
await this.#refreshPlugins();
|
|
1963
|
+
await this.#purgeSite('plugins');
|
|
1964
|
+
}
|
|
1965
|
+
|
|
1966
|
+
/** Commands plugin manifests declare. */
|
|
1967
|
+
commands(): { plugin: string; command: PluginCommand }[] {
|
|
1968
|
+
return [...this.#plugins.values()].flatMap(plugin => (plugin.manifest.commands ?? []).map(command => ({ plugin: plugin.manifest.name, command })));
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
/** Run a plugin command as the principal: dashboard access, the command's permission and an active plugin are required. */
|
|
1972
|
+
async runCommand(plugin: string, name: string, input: { readonly [option: string]: string | number | boolean }, context: CommandContext): Promise<unknown> {
|
|
1973
|
+
const hosted = this.#plugins.get(plugin);
|
|
1974
|
+
const command = hosted?.manifest.commands?.find(entry => entry.name === name);
|
|
1975
|
+
const handler = hosted?.commands.get(name);
|
|
1976
|
+
if (!hosted || !command || !handler) throw new CmsError('CMS_NOT_FOUND', `Unknown command ${plugin}:${name}.`);
|
|
1977
|
+
if (!hasPermission(context.principal, PERMISSIONS.dashboard) || (command.permission && !hasPermission(context.principal, command.permission))) {
|
|
1978
|
+
throw new CmsError(context.principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', `Not allowed to run ${plugin}:${name}.`);
|
|
1979
|
+
}
|
|
1980
|
+
if (!(await this.pluginActive(plugin))) throw new CmsError('CMS_UNAVAILABLE', `Plugin ${plugin} is not active.`);
|
|
1981
|
+
return handler(input, context);
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
/** Links plugins add to a dashboard slot, for active plugins and permitted principals. */
|
|
1985
|
+
async slotLinks(slot: string, principal: Principal): Promise<(SlotLink & { plugin: string })[]> {
|
|
1986
|
+
const links: (SlotLink & { plugin: string })[] = [];
|
|
1987
|
+
for (const plugin of this.#plugins.values()) {
|
|
1988
|
+
const entries = plugin.manifest.ui?.slots?.[slot] ?? [];
|
|
1989
|
+
if (!entries.length || !(await this.pluginActive(plugin.manifest.name))) continue;
|
|
1990
|
+
for (const link of entries) if (!link.permission || hasPermission(principal, link.permission)) links.push({ ...link, plugin: plugin.manifest.name });
|
|
1991
|
+
}
|
|
1992
|
+
return links;
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
/** True once every host table exists. Background work waits for it on a fresh database. */
|
|
1996
|
+
async installed(): Promise<boolean> {
|
|
1997
|
+
if (this.#installed) return true;
|
|
1998
|
+
const result = await this.db.read([{ rql: 'INFO FOR DB' }]);
|
|
1999
|
+
const tables = new Set(((result.results[0]!.rows[0]![0] as { tables?: { name: string }[] }).tables ?? []).map(table => table.name));
|
|
2000
|
+
this.#installed = HOST_TABLES.every(name => tables.has(name));
|
|
2001
|
+
return this.#installed;
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
/** Forget cached activation, for example after a migration or grant made elsewhere. */
|
|
2005
|
+
refreshActivation(): void {
|
|
2006
|
+
this.#activation = undefined;
|
|
2007
|
+
// The next ready() re-reads which plugins are active, for their collections.
|
|
2008
|
+
this.#definitions = undefined;
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
/** Repositories limited to a plugin's own resources and its granted ones. */
|
|
2012
|
+
pluginCms(name: string): PluginCms {
|
|
2013
|
+
return {
|
|
2014
|
+
resource: id => {
|
|
2015
|
+
const plugin = this.#plugins.get(name);
|
|
2016
|
+
// Its own resources and the collections it ships.
|
|
2017
|
+
const own = (plugin?.resources.includes(id) || plugin?.manifest.collections?.some(collection => `cms/${collection.name}` === id)) ?? false;
|
|
2018
|
+
const requested = new Set((plugin?.requested ?? []).filter(grant => grant.startsWith(`resource:${id}:`)).map(grant => grant.slice(`resource:${id}:`.length) as ResourceAction));
|
|
2019
|
+
const unrestricted = plugin?.requested.includes(UNRESTRICTED_GRANT) ?? false;
|
|
2020
|
+
if (!own && !requested.size && !unrestricted) throw new CmsError('CMS_FORBIDDEN', `Plugin ${name} has no grant for ${id}.`);
|
|
2021
|
+
const repository = this.resource(id);
|
|
2022
|
+
// Requested in the manifest and granted by an administrator.
|
|
2023
|
+
const check = (action: ResourceAction): Promise<void> => {
|
|
2024
|
+
if (own) return Promise.resolve();
|
|
2025
|
+
if (!unrestricted && !requested.has(action)) throw new CmsError('CMS_FORBIDDEN', `Plugin ${name} may not ${action} ${id}.`);
|
|
2026
|
+
return this.#state().then(state => {
|
|
2027
|
+
const granted = this.#granted(name, state);
|
|
2028
|
+
if (!granted.has(`resource:${id}:${action}`) && !granted.has(UNRESTRICTED_GRANT)) throw new CmsError('CMS_FORBIDDEN', `Plugin ${name} is not granted ${action} on ${id}.`);
|
|
2029
|
+
});
|
|
2030
|
+
};
|
|
2031
|
+
return {
|
|
2032
|
+
get: (key, context) => check('read').then(() => repository.get(key, context)),
|
|
2033
|
+
list: (options: ListOptions, context: OperationContext) => check('read').then(() => repository.list(options, context)),
|
|
2034
|
+
count: (filter, context) => check('read').then(() => repository.count(filter, context)),
|
|
2035
|
+
search: (query, options, context) => check('read').then(() => repository.search(query, options, context)),
|
|
2036
|
+
create: (input, context) => check('create').then(() => repository.create(input, context)),
|
|
2037
|
+
update: (key, patch, context) => check('update').then(() => repository.update(key, patch, context)),
|
|
2038
|
+
delete: (key, context) => check('delete').then(() => repository.delete(key, context)),
|
|
2039
|
+
};
|
|
2040
|
+
},
|
|
2041
|
+
};
|
|
2042
|
+
}
|
|
2043
|
+
|
|
2044
|
+
/** Called after each committed mutation. Menus link to entries, so their cache is dropped. */
|
|
2045
|
+
outboxWritten(): void {
|
|
2046
|
+
this.outboxWrites++;
|
|
2047
|
+
this.menus.refresh();
|
|
2048
|
+
}
|
|
2049
|
+
|
|
2050
|
+
jobs() { return createJobStore(this.db); }
|
|
2051
|
+
notifications() { return createNotificationStore(this.db); }
|
|
2052
|
+
|
|
2053
|
+
#register(resource: Resource): Resource {
|
|
2054
|
+
if (this.#static.has(resource.id)) throw new Error(`Resource ${resource.id} is declared twice.`);
|
|
2055
|
+
if ([...this.#static.values()].some(other => other.storage === resource.storage)) throw new Error(`Resource ${resource.id} collides with another storage name.`);
|
|
2056
|
+
this.#static.set(resource.id, resource);
|
|
2057
|
+
this.#resources.set(resource.id, resource);
|
|
2058
|
+
return resource;
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
#authorizeBuilder(principal: Principal): void {
|
|
2062
|
+
if (!hasPermission(principal, PERMISSIONS.manageCollections)) throw new CmsError(principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', 'Not allowed to change collections.');
|
|
2063
|
+
}
|
|
2064
|
+
|
|
2065
|
+
/**
|
|
2066
|
+
* A collection's resource: its declared fields, then its groups' (a group field named as a
|
|
2067
|
+
* core field or a feature is left out), with the groups' layout. Saving and reloading
|
|
2068
|
+
* build it the same way, so the declaration hash a migration records is the one `ready()`
|
|
2069
|
+
* checks writes against.
|
|
2070
|
+
*/
|
|
2071
|
+
#collectionResource(definition: CollectionDefinition, labels: { [name: string]: string }): Resource {
|
|
2072
|
+
const groups = this.#groupFields({ kind: 'collection', name: definition.name });
|
|
2073
|
+
const taken = new Set([...RESERVED_FIELDS, ...(definition.taxonomies ?? []), ...Object.keys(definition.fields)]);
|
|
2074
|
+
const fields = { ...definition.fields, ...Object.fromEntries(Object.entries(groups.fields).filter(([name]) => !taken.has(name))) };
|
|
2075
|
+
const layout = groups.layout;
|
|
2076
|
+
return resolveResource({ ...collectionResource({ ...definition, fields }, labels), ...(layout.length ? { layout } : {}) }, 'cms');
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
#taxonomyLabels(): { [name: string]: string } {
|
|
2080
|
+
return Object.fromEntries([...this.#taxonomies.values()].map(taxonomy => [taxonomy.name, taxonomy.label]));
|
|
2081
|
+
}
|
|
2082
|
+
|
|
2083
|
+
/**
|
|
2084
|
+
* After a package upgrade, apply what the CMS owns on the next request: new host tables and
|
|
2085
|
+
* built-in or dashboard collections whose declaration changed. Code-declared resources and
|
|
2086
|
+
* plugins wait for Tools → Schema. Concurrent isolates replan against the ledger.
|
|
2087
|
+
*/
|
|
2088
|
+
async #upgrade(): Promise<void> {
|
|
2089
|
+
const state = await this.#state();
|
|
2090
|
+
if (!state.hostVersions.has(1)) return; // before setup
|
|
2091
|
+
const hostPending = HOST_STEPS.some(step => !state.hostVersions.has(step.version));
|
|
2092
|
+
const stale: string[] = [];
|
|
2093
|
+
for (const collection of this.#collections.values()) {
|
|
2094
|
+
const resource = this.#resources.get(`cms/${collection.name}`);
|
|
2095
|
+
if (resource && state.hashes.get(resource.id) !== await declarationHash(resource)) stale.push(resource.id);
|
|
2096
|
+
}
|
|
2097
|
+
// A plugin the network activates is migrated on every site as the site loads.
|
|
2098
|
+
const networkActive = [...this.#plugins.values()].filter(plugin => !plugin.problems.length && pluginState(state.policy, plugin.manifest.name) === 'network');
|
|
2099
|
+
for (const id of networkActive.flatMap(plugin => plugin.resources)) {
|
|
2100
|
+
const resource = this.#resources.get(id);
|
|
2101
|
+
if (resource && !stale.includes(id) && state.hashes.get(id) !== await declarationHash(resource)) stale.push(id);
|
|
2102
|
+
}
|
|
2103
|
+
if (hostPending || stale.length) {
|
|
2104
|
+
this.#upgrading ??= migrate(this.db, this.resources, { now: this.#now, only: stale }).then(report => {
|
|
2105
|
+
if (report.failed) console.error(`[cms] could not upgrade the schema: ${report.failed.message}`);
|
|
2106
|
+
}).catch(error => console.error('[cms] could not upgrade the schema', error)).finally(() => {
|
|
2107
|
+
this.#upgrading = undefined;
|
|
2108
|
+
this.#activation = undefined;
|
|
2109
|
+
this.#installed = false;
|
|
2110
|
+
});
|
|
2111
|
+
await this.#upgrading;
|
|
2112
|
+
}
|
|
2113
|
+
// And gets the field groups its manifest ships, once, as a site admin's grant would store them.
|
|
2114
|
+
for (const plugin of networkActive) {
|
|
2115
|
+
if (plugin.manifest.fieldGroups?.length && !this.#groups.some(group => group.plugin === plugin.manifest.name)) await this.#seedFieldGroups(plugin, systemPrincipal('network')).catch(error => console.error(`[cms] could not add the field groups of ${plugin.manifest.name}`, error));
|
|
2116
|
+
await this.#seedPatterns(plugin, systemPrincipal('network'), { onlyIfNone: true }).catch(error => console.error(`[cms] could not add the patterns of ${plugin.manifest.name}`, error));
|
|
2117
|
+
}
|
|
2118
|
+
}
|
|
2119
|
+
|
|
2120
|
+
/** Forget cached activation and definitions, so the next request reads the network's and the site's current state. */
|
|
2121
|
+
expire(): void {
|
|
2122
|
+
this.#activation = undefined;
|
|
2123
|
+
this.#definitions = undefined;
|
|
2124
|
+
}
|
|
2125
|
+
|
|
2126
|
+
async #loadDefinitions(): Promise<void> {
|
|
2127
|
+
let collections: readonly (readonly unknown[])[] = [];
|
|
2128
|
+
let taxonomies: readonly (readonly unknown[])[] = [];
|
|
2129
|
+
this.fieldGroups.reset();
|
|
2130
|
+
const groups = this.fieldGroups.all();
|
|
2131
|
+
// Awaited below; when the definitions fail first, its own failure is not left unhandled.
|
|
2132
|
+
groups.catch(() => undefined);
|
|
2133
|
+
try {
|
|
2134
|
+
// Definitions are JSON of many fields: forty large collections may come in smaller reads. Collections, taxonomies and field groups are read side by side.
|
|
2135
|
+
[collections, taxonomies] = await Promise.all([
|
|
2136
|
+
readPaged(this.db, (size, at) => ({ rql: 'SELECT name, definition FROM cms_collections ORDER BY name LIMIT $limit OFFSET $offset', params: { $limit: size, $offset: at } }), 200, 0),
|
|
2137
|
+
readPaged(this.db, (size, at) => ({ rql: 'SELECT name, definition FROM cms_taxonomies ORDER BY name LIMIT $limit OFFSET $offset', params: { $limit: size, $offset: at } }), 200, 0),
|
|
2138
|
+
]);
|
|
2139
|
+
} catch (error) {
|
|
2140
|
+
// Before setup the tables do not exist; built-ins apply.
|
|
2141
|
+
if (!(error instanceof ClientError) || !/cms_collections|cms_taxonomies|no such table|not found/i.test(error.message)) throw error;
|
|
2142
|
+
}
|
|
2143
|
+
const parse = <T>(rows: readonly (readonly unknown[])[]) => new Map(rows.flatMap(([name, definition]) => {
|
|
2144
|
+
try { return [[name as string, JSON.parse(definition as string) as T] as const]; } catch { return []; }
|
|
2145
|
+
}));
|
|
2146
|
+
this.#groups = await groups;
|
|
2147
|
+
this.#apply(parse<CollectionDefinition>(collections), parse<TaxonomyDeclaration>(taxonomies));
|
|
2148
|
+
}
|
|
2149
|
+
|
|
2150
|
+
/** The groups attached to a target, in their order there. */
|
|
2151
|
+
#groupsFor(target: FieldGroupTarget): FieldGroup[] {
|
|
2152
|
+
return groupsForTarget(this.#groups, target);
|
|
2153
|
+
}
|
|
2154
|
+
|
|
2155
|
+
/** A target's fields from its groups, after the group blocks are checked against the current types. */
|
|
2156
|
+
#groupFields(target: FieldGroupTarget): { fields: { [name: string]: FieldDeclaration }; layout: Block[] } {
|
|
2157
|
+
const fields: { [name: string]: FieldDeclaration } = {};
|
|
2158
|
+
const layout: Block[] = [];
|
|
2159
|
+
for (const group of this.#groupsFor(target)) {
|
|
2160
|
+
const { blocks } = validateBlocks(group.blocks, this.#blocks, { fieldGroup: true });
|
|
2161
|
+
Object.assign(fields, fieldGroupDeclarations(blocks, this.#blocks));
|
|
2162
|
+
layout.push(...blocks);
|
|
2163
|
+
}
|
|
2164
|
+
return { fields, layout };
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
/**
|
|
2168
|
+
* A target's meta as it is stored: the groups' fields checked, hidden fields cleared, the
|
|
2169
|
+
* fields the input leaves out kept from `previous`.
|
|
2170
|
+
*/
|
|
2171
|
+
/** Settings → Files as the file service reads them. */
|
|
2172
|
+
async #imageSettings(): Promise<ImageSettings> {
|
|
2173
|
+
const settings = await this.settings.all();
|
|
2174
|
+
return { widths: imageWidths(settings['media.imageWidths']), quality: settings['media.imageQuality'], maxWidth: settings['media.maxImageWidth'] };
|
|
2175
|
+
}
|
|
2176
|
+
|
|
2177
|
+
async #checkMeta(target: FieldGroupTarget, meta: unknown, previous: { readonly [field: string]: unknown } | null, principal?: Principal): Promise<{ readonly [field: string]: unknown }> {
|
|
2178
|
+
const { fields: groupFields, layout } = this.#groupFields(target);
|
|
2179
|
+
// Users carry their public author profile besides their groups' fields.
|
|
2180
|
+
const fields = target.kind === 'users' ? { ...AUTHOR_FIELDS, ...groupFields } : groupFields;
|
|
2181
|
+
if (meta !== undefined && (meta === null || typeof meta !== 'object' || Array.isArray(meta))) throw new CmsError('CMS_VALIDATION', 'Meta must be an object of fields.', { fields: { meta: 'must be an object of fields.' } });
|
|
2182
|
+
const merged = { ...previous, ...(meta as { [field: string]: unknown } | undefined) };
|
|
2183
|
+
const { errors, values } = metaProblems(fields, merged, () => blockId());
|
|
2184
|
+
const { hidden, values: cleared } = fieldVisibility(layout, this.#blocks, values);
|
|
2185
|
+
const names = new Map(flattenGroupFields(layout).map(block => [block._id, block.data.name as string]));
|
|
2186
|
+
for (const key of hidden) { const name = key.includes('/') ? undefined : names.get(key); if (name) { delete errors[name]; delete cleared[name]; } }
|
|
2187
|
+
// Blocks, rich text and Markdown render on the site: their blocks are checked as an
|
|
2188
|
+
// entry's are, and Custom HTML needs the HTML permission (no principal: never).
|
|
2189
|
+
const html = principal !== undefined && hasPermission(principal, PERMISSIONS.unfilteredHtml);
|
|
2190
|
+
for (const [name, value] of Object.entries(cleared)) {
|
|
2191
|
+
const declaration = Object.hasOwn(fields, name) ? fields[name] : undefined;
|
|
2192
|
+
if (!declaration || errors[name] || value === undefined || value === null) continue;
|
|
2193
|
+
if ((declaration.kind === 'blocks' || declaration.kind === 'richtext') && !html && htmlBlocksChanged(value, previous?.[name])) { errors[name] = 'has a Custom HTML block, which only people allowed to post HTML can add or change.'; continue; }
|
|
2194
|
+
if (declaration.kind === 'blocks') {
|
|
2195
|
+
const checked = validateBlocks(value as Block[], this.#blocks, declaration.blocks ? { allowed: declaration.blocks } : {});
|
|
2196
|
+
const [path, message] = Object.entries(checked.errors)[0] ?? [];
|
|
2197
|
+
if (path) errors[name] = `block ${path} ${message}`;
|
|
2198
|
+
else cleared[name] = checked.blocks;
|
|
2199
|
+
} else if (declaration.kind === 'richtext') {
|
|
2200
|
+
const doc = normalizeRichText(value);
|
|
2201
|
+
const checked = validateBlocks(richTextBlocks(doc), this.#blocks, declaration.blocks ? { allowed: declaration.blocks } : {});
|
|
2202
|
+
const [path, message] = Object.entries(checked.errors)[0] ?? [];
|
|
2203
|
+
if (path) errors[name] = `block ${path} ${message}`;
|
|
2204
|
+
else cleared[name] = withRichTextBlocks(doc, checked.blocks);
|
|
2205
|
+
} else {
|
|
2206
|
+
const problem = textFieldProblem(declaration, value, this.#blocks);
|
|
2207
|
+
if (problem) errors[name] = problem;
|
|
2208
|
+
}
|
|
2209
|
+
}
|
|
2210
|
+
if (Object.keys(errors).length) throw new CmsError('CMS_VALIDATION', Object.entries(errors).map(([name, error]) => `${fields[name]?.label ?? name} ${error}`).join(' '), { fields: errors });
|
|
2211
|
+
return cleared;
|
|
2212
|
+
}
|
|
2213
|
+
|
|
2214
|
+
/** The field groups attached to a target, with their blocks, for editors. */
|
|
2215
|
+
fieldGroupsFor(target: FieldGroupTarget): FieldGroup[] {
|
|
2216
|
+
return this.#groupsFor(target);
|
|
2217
|
+
}
|
|
2218
|
+
|
|
2219
|
+
/** Field names a group attached to the target cannot take: the target's own, core fields included. */
|
|
2220
|
+
#targetScope(target: FieldGroupTarget): string[] {
|
|
2221
|
+
switch (target.kind) {
|
|
2222
|
+
case 'collection': {
|
|
2223
|
+
const definition = this.#collections.get(target.name);
|
|
2224
|
+
return [...RESERVED_FIELDS, ...(definition?.taxonomies ?? []), ...Object.keys(definition?.fields ?? {})];
|
|
2225
|
+
}
|
|
2226
|
+
case 'taxonomy': return ['name', 'slug', 'description', 'parent', 'icon', 'path', 'depth', 'taxonomy'];
|
|
2227
|
+
case 'users': return ['email', 'name', 'avatar', 'status', 'roles', 'password', 'slug', ...Object.keys(AUTHOR_FIELDS)];
|
|
2228
|
+
case 'menus': return ['label', 'kind', 'url', 'collection', 'entry', 'taxonomy', 'term', 'description', 'panel', 'newTab', 'className', 'attributes', 'children'];
|
|
2229
|
+
}
|
|
2230
|
+
}
|
|
2231
|
+
|
|
2232
|
+
/** Save a field group: checked against the block types and each target's own fields, then the targets' schemas are planned. */
|
|
2233
|
+
async saveFieldGroup(input: FieldGroup, principal: Principal): Promise<FieldGroup> {
|
|
2234
|
+
this.#authorizeBuilder(principal);
|
|
2235
|
+
await this.ready({ force: true });
|
|
2236
|
+
const existing = await this.fieldGroups.get(input.id);
|
|
2237
|
+
if (existing?.plugin) throw new CmsError('CMS_FORBIDDEN', `The group ${existing.title} comes from the plugin ${existing.plugin}; it is changed in its manifest.`);
|
|
2238
|
+
const problems: string[] = [];
|
|
2239
|
+
for (const target of input.targets ?? []) {
|
|
2240
|
+
if (target.kind === 'collection' && !this.#collections.has(target.name)) problems.push(`Collection ${target.name} does not exist.`);
|
|
2241
|
+
else if (target.kind === 'collection' && this.#collections.get(target.name)?.managed) problems.push(`${this.#collections.get(target.name)!.label} is managed by its module; groups cannot attach to it.`);
|
|
2242
|
+
if (target.kind === 'taxonomy' && !this.#taxonomies.has(target.name)) problems.push(`Taxonomy ${target.name} does not exist.`);
|
|
2243
|
+
}
|
|
2244
|
+
const scope = [...new Set((input.targets ?? []).flatMap(target => this.#targetScope(target)))];
|
|
2245
|
+
const checked = fieldGroupProblems(input, this.#blocks, scope);
|
|
2246
|
+
problems.push(...checked.problems);
|
|
2247
|
+
// Names are distinct across the groups of one target.
|
|
2248
|
+
for (const target of input.targets ?? []) for (const other of this.#groupsFor(target)) {
|
|
2249
|
+
if (other.id === input.id) continue;
|
|
2250
|
+
for (const name of Object.keys(fieldGroupDeclarations(other.blocks, this.#blocks))) if (Object.hasOwn(checked.fields, name)) problems.push(`Field ${name} is already in the group “${other.title}”.`);
|
|
2251
|
+
}
|
|
2252
|
+
for (const [name, declaration] of Object.entries(checked.fields)) {
|
|
2253
|
+
if (declaration.kind === 'reference' && !this.#resources.has(declaration.target!)) problems.push(`Field ${name} refers to ${declaration.target}, which does not exist.`);
|
|
2254
|
+
for (const type of declaration.blocks ?? []) if (!this.#blocks.has(type)) problems.push(`Field ${name} allows ${type}, which is not a block type.`);
|
|
2255
|
+
}
|
|
2256
|
+
if (problems.length) throw new CmsError('CMS_VALIDATION', problems.join(' '), { fields: { definition: problems.join(' ') } });
|
|
2257
|
+
const group: FieldGroup = {
|
|
2258
|
+
id: input.id, title: input.title.trim(), ...(input.description?.trim() ? { description: input.description.trim() } : {}),
|
|
2259
|
+
...(input.placement ? { placement: input.placement } : {}), ...(input.order !== undefined ? { order: input.order } : {}),
|
|
2260
|
+
targets: [...input.targets], blocks: checked.blocks,
|
|
2261
|
+
};
|
|
2262
|
+
await this.fieldGroups.put(group, principal);
|
|
2263
|
+
await this.#migrateTargets(group, principal);
|
|
2264
|
+
return (await this.fieldGroups.get(group.id))!;
|
|
2265
|
+
}
|
|
2266
|
+
|
|
2267
|
+
async deleteFieldGroup(id: string, principal: Principal): Promise<void> {
|
|
2268
|
+
this.#authorizeBuilder(principal);
|
|
2269
|
+
const group = await this.fieldGroups.get(id);
|
|
2270
|
+
if (!group) throw new CmsError('CMS_NOT_FOUND', 'Field group not found.');
|
|
2271
|
+
if (group.plugin) throw new CmsError('CMS_FORBIDDEN', `The group ${group.title} comes from the plugin ${group.plugin}; it is removed with the plugin.`);
|
|
2272
|
+
await this.fieldGroups.remove(id);
|
|
2273
|
+
await this.#migrateTargets(group, principal);
|
|
2274
|
+
}
|
|
2275
|
+
|
|
2276
|
+
/** Re-resolve the collections a group touches and plan their schemas: indexes come and go, old values stay. */
|
|
2277
|
+
async #migrateTargets(group: FieldGroup, principal: Principal): Promise<void> {
|
|
2278
|
+
this.#activation = undefined;
|
|
2279
|
+
await this.ready({ force: true });
|
|
2280
|
+
const ids = group.targets.filter(target => target.kind === 'collection').map(target => `cms/${(target as { name: string }).name}`).filter(id => this.#resources.has(id));
|
|
2281
|
+
if (!ids.length) return;
|
|
2282
|
+
const resources = [...this.#resources.values()];
|
|
2283
|
+
const plan = await planSchema(resources, await readCatalog(this.db, resources.filter(entry => ids.includes(entry.id)).map(entry => entry.storage)));
|
|
2284
|
+
const blocked = plan.blocked.filter(problem => ids.includes(problem.resource));
|
|
2285
|
+
if (blocked.length) throw new CmsError('CMS_VALIDATION', blocked.map(problem => problem.message).join(' '));
|
|
2286
|
+
const report = await migrate(this.db, resources, { now: this.#now, only: ids });
|
|
2287
|
+
if (report.failed) throw new CmsError('CMS_CONFLICT', `The schema could not be updated: ${report.failed.message}`);
|
|
2288
|
+
void principal;
|
|
2289
|
+
this.#activation = undefined;
|
|
2290
|
+
await this.ready({ force: true });
|
|
2291
|
+
}
|
|
2292
|
+
|
|
2293
|
+
/** Rebuild the registry from built-ins and stored definitions. Invalid stored definitions are skipped. */
|
|
2294
|
+
#apply(storedCollections: ReadonlyMap<string, CollectionDefinition>, storedTaxonomies: ReadonlyMap<string, TaxonomyDeclaration>): void {
|
|
2295
|
+
const taxonomies = new Map(this.#builtinTaxonomies);
|
|
2296
|
+
for (const [name, stored] of storedTaxonomies) {
|
|
2297
|
+
const builtin = this.#builtinTaxonomies.get(name);
|
|
2298
|
+
const next = builtin ? { ...builtin, label: stored.label ?? builtin.label, singular: stored.singular ?? builtin.singular, path: stored.path === undefined ? builtin.path : stored.path, ...(stored.description !== undefined ? { description: stored.description } : {}), ...(stored.noindex !== undefined ? { noindex: stored.noindex } : {}) } : { ...stored, builtin: false };
|
|
2299
|
+
if (!taxonomyProblems(next).length) taxonomies.set(name, Object.freeze(next));
|
|
2300
|
+
}
|
|
2301
|
+
const collections = new Map<string, CollectionDefinition>();
|
|
2302
|
+
for (const builtin of this.#builtinCollections.values()) {
|
|
2303
|
+
const stored = storedCollections.get(builtin.name);
|
|
2304
|
+
collections.set(builtin.name, stored ? extendCollection(builtin, stored) : builtin);
|
|
2305
|
+
}
|
|
2306
|
+
for (const [name, stored] of storedCollections) if (!this.#builtinCollections.has(name)) collections.set(name, { ...stored, builtin: false });
|
|
2307
|
+
const labels = Object.fromEntries([...taxonomies.values()].map(taxonomy => [taxonomy.name, taxonomy.label]));
|
|
2308
|
+
const resources = new Map(this.#static);
|
|
2309
|
+
const effective = new Map<string, CollectionDefinition>();
|
|
2310
|
+
for (const definition of collections.values()) {
|
|
2311
|
+
const known = { ...definition, taxonomies: (definition.taxonomies ?? []).filter(name => taxonomies.has(name)) };
|
|
2312
|
+
if (collectionProblems(known).length || this.#static.has(`cms/${known.name}`)) continue;
|
|
2313
|
+
try {
|
|
2314
|
+
const resource = this.#collectionResource(known, labels);
|
|
2315
|
+
const previous = this.#resources.get(resource.id);
|
|
2316
|
+
// Keep the same object when nothing changed, so callers holding it stay current. Field order counts.
|
|
2317
|
+
resources.set(resource.id, previous && canonicalJson(previous) === canonicalJson(resource) && sameKeyOrder(previous.fields, resource.fields) ? previous : resource);
|
|
2318
|
+
effective.set(known.name, Object.freeze(known));
|
|
2319
|
+
} catch { /* an invalid stored definition stays inactive */ }
|
|
2320
|
+
}
|
|
2321
|
+
this.#taxonomies = taxonomies;
|
|
2322
|
+
this.#collections = effective;
|
|
2323
|
+
this.#resources = resources;
|
|
2324
|
+
for (const id of this.#repositories.keys()) if (!resources.has(id)) this.#repositories.delete(id);
|
|
2325
|
+
}
|
|
2326
|
+
|
|
2327
|
+
#hostTheme(plugin: HostedPlugin, groups: ReadonlySet<string>): ThemeInfo {
|
|
2328
|
+
const manifest = plugin.manifest.theme as ThemeManifest;
|
|
2329
|
+
const problems = [...plugin.problems];
|
|
2330
|
+
const parent = this.#parentOf(plugin);
|
|
2331
|
+
const parentManifest = parent?.manifest.theme as ThemeManifest | undefined;
|
|
2332
|
+
if (!problems.length && manifest?.extends) {
|
|
2333
|
+
if (manifest.extends === plugin.manifest.name) problems.push('A theme cannot extend itself.');
|
|
2334
|
+
else if (!parent) problems.push(`It extends ${manifest.extends}, which is not an installed theme.`);
|
|
2335
|
+
else if (parent.problems.length) problems.push(`Its parent theme ${manifest.extends} is invalid.`);
|
|
2336
|
+
else if (parentManifest?.extends) problems.push(`Its parent theme ${manifest.extends} extends another theme; themes extend one level.`);
|
|
2337
|
+
}
|
|
2338
|
+
if (!problems.length) problems.push(...siteThemeProblems(assembleSiteTheme(plugin.registration, parent?.registration)));
|
|
2339
|
+
// A child's options, locations and areas are layered over its parent's; its option values are its own.
|
|
2340
|
+
const inherited = manifest?.extends && parentManifest ? parentManifest : undefined;
|
|
2341
|
+
const fields = { ...inherited?.options, ...manifest?.options };
|
|
2342
|
+
const options = manifest && Object.keys(fields).length ? { id: plugin.manifest.name, label: manifest.label, permission: PERMISSIONS.manageAppearance, fields } : null;
|
|
2343
|
+
if (options && (groups.has(options.id) || ['plugins', 'json', '__proto__', 'constructor', 'prototype'].includes(options.id) || !/^[a-z][a-z0-9-]{0,40}$/.test(options.id))) problems.push(`Its options need a settings group named ${options.id}, which is taken, reserved or too long.`);
|
|
2344
|
+
const named = (entries: { readonly [name: string]: string }) => Object.entries(entries).map(([name, label]) => ({ name, label }));
|
|
2345
|
+
return Object.freeze({
|
|
2346
|
+
name: plugin.registration.name, version: plugin.registration.version, ...authorOf(plugin),
|
|
2347
|
+
label: typeof manifest?.label === 'string' ? manifest.label : plugin.registration.name, description: typeof manifest?.description === 'string' ? manifest.description : '',
|
|
2348
|
+
locations: named({ ...inherited?.locations, ...manifest?.locations }), areas: Object.entries({ ...inherited?.areas, ...manifest?.areas }).map(([name, entry]) => themeArea(name, entry)),
|
|
2349
|
+
parent: inherited ? manifest.extends! : null, ...artwork(plugin), options, presets: layerPresets(inherited?.presets, manifest?.presets), problems,
|
|
2350
|
+
});
|
|
2351
|
+
}
|
|
2352
|
+
|
|
2353
|
+
/**
|
|
2354
|
+
* Menu items for visitors: entries, archives and terms get their current titles and URLs;
|
|
2355
|
+
* items whose target is gone are left out, their children move up. Headings keep no URL.
|
|
2356
|
+
* Meta stays raw and the panel a pattern ID: the site renders them (`menuViews`).
|
|
2357
|
+
*/
|
|
2358
|
+
async #resolveMenu(items: readonly MenuItem[], locale?: string): Promise<ResolvedMenuItem[]> {
|
|
2359
|
+
const languages = await this.languages();
|
|
2360
|
+
const translate = Boolean(locale && languages.multilingual);
|
|
2361
|
+
const entries = new Map<string, Set<string>>();
|
|
2362
|
+
const terms = new Set<string>();
|
|
2363
|
+
const collect = (list: readonly MenuItem[]) => {
|
|
2364
|
+
for (const item of list) {
|
|
2365
|
+
if (item.kind === 'entry' && item.collection && item.entry) entries.set(item.collection, (entries.get(item.collection) ?? new Set()).add(item.entry));
|
|
2366
|
+
if (item.kind === 'term' && item.term) terms.add(item.term);
|
|
2367
|
+
collect(item.children);
|
|
2368
|
+
}
|
|
2369
|
+
};
|
|
2370
|
+
collect(items);
|
|
2371
|
+
const found = new Map<string, { title: string; url: string | null }>();
|
|
2372
|
+
for (const [name, ids] of entries) {
|
|
2373
|
+
const collection = this.#collections.get(name);
|
|
2374
|
+
if (!collection) continue;
|
|
2375
|
+
try {
|
|
2376
|
+
const records = await this.resource(`cms/${name}`).getMany([...ids], { principal: ANONYMOUS });
|
|
2377
|
+
// In another language, an entry item shows the entry's translation when there is one.
|
|
2378
|
+
const shown = new Map<string, RecordShape>();
|
|
2379
|
+
const translations = translate ? await this.translationsOf(collection, [...records.values()]) : null;
|
|
2380
|
+
for (const record of records.values()) shown.set(record.id, translations?.get(translationGroupOf(record))?.get(locale!) ?? record);
|
|
2381
|
+
const urls = await this.entryUrls(collection, [...shown.values()]);
|
|
2382
|
+
for (const [id, record] of shown) found.set(`${name}:${id}`, { title: recordTitle(record, 'title'), url: urls.get(record.id) ?? null });
|
|
2383
|
+
} catch (error) {
|
|
2384
|
+
if (!(error instanceof CmsError)) throw error;
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
const termRows = terms.size ? await this.taxonomies.getMany([...terms]) : new Map();
|
|
2388
|
+
const archives = new Map<string, string | null>();
|
|
2389
|
+
const visitArchives = async (list: readonly MenuItem[]): Promise<void> => {
|
|
2390
|
+
for (const item of list) {
|
|
2391
|
+
const collection = item.kind === 'archive' && item.collection ? this.#collections.get(item.collection) : undefined;
|
|
2392
|
+
if (collection && !archives.has(collection.name)) archives.set(collection.name, await this.archiveUrl(collection, translate ? locale : null));
|
|
2393
|
+
await visitArchives(item.children);
|
|
2394
|
+
}
|
|
2395
|
+
};
|
|
2396
|
+
await visitArchives(items);
|
|
2397
|
+
const resolve = (list: readonly MenuItem[]): ResolvedMenuItem[] => list.flatMap(item => {
|
|
2398
|
+
const children = resolve(item.children);
|
|
2399
|
+
let target: { title: string; url: string | null } | undefined;
|
|
2400
|
+
if (item.kind === 'link') target = { title: item.label, url: item.url ?? null };
|
|
2401
|
+
else if (item.kind === 'heading') target = { title: item.label, url: null };
|
|
2402
|
+
else if (item.kind === 'entry') target = found.get(`${item.collection}:${item.entry}`);
|
|
2403
|
+
else if (item.kind === 'archive') {
|
|
2404
|
+
const collection = item.collection ? this.#collections.get(item.collection) : undefined;
|
|
2405
|
+
const url = collection ? archives.get(collection.name) : null;
|
|
2406
|
+
target = collection && url ? { title: collection.label, url } : undefined;
|
|
2407
|
+
} else {
|
|
2408
|
+
const term = termRows.get(item.term ?? '');
|
|
2409
|
+
const taxonomy = term && term.taxonomy === item.taxonomy ? this.#taxonomies.get(term.taxonomy) : undefined;
|
|
2410
|
+
target = term && taxonomy?.path ? { title: term.name, url: `${translate ? this.localePrefix(locale, languages) : ''}/${taxonomy.path}/${term.slug}` } : undefined;
|
|
2411
|
+
}
|
|
2412
|
+
if (!target || (!target.url && item.kind !== 'heading')) return children;
|
|
2413
|
+
return [Object.freeze({ id: item.id, label: item.label || target.title, url: target.url, newTab: item.newTab === true, kind: item.kind, description: item.description ?? '',
|
|
2414
|
+
className: item.className ?? '', attributes: Object.freeze({ ...item.attributes }), meta: Object.freeze({ ...item.meta }), panel: item.panel || null, children: Object.freeze(children) })];
|
|
2415
|
+
});
|
|
2416
|
+
return resolve(items);
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2419
|
+
#host(registration: PluginRegistrationLike): void {
|
|
2420
|
+
const manifest = (registration.manifest ?? { schemaVersion: 1, name: registration.name, version: registration.version }) as CmsPluginManifest;
|
|
2421
|
+
const problems = manifestProblems(manifest);
|
|
2422
|
+
if (manifest.name !== registration.name) problems.push(`The manifest names ${String(manifest.name)}, not ${registration.name}.`);
|
|
2423
|
+
// Never in the application instead: the build left its code out of it.
|
|
2424
|
+
if (isolatedCode(registration) && !this.#runner) problems.push('It runs isolated, and this application has no Worker Loader binding (LOADER) to run it. Add the binding, or add the plugin with --in-app.');
|
|
2425
|
+
const resources: string[] = [];
|
|
2426
|
+
if (!problems.length) {
|
|
2427
|
+
for (const declaration of manifest.resources ?? []) resources.push(this.#register(resolveResource({ ...declaration, owner: registration.name }, registration.name)).id);
|
|
2428
|
+
}
|
|
2429
|
+
this.#plugins.set(registration.name, { registration, manifest, problems, resources, requested: problems.length ? [] : requestedGrants(manifest), commands: new Map() });
|
|
2430
|
+
}
|
|
2431
|
+
|
|
2432
|
+
/**
|
|
2433
|
+
* Pair each plugin's `hooks` on another plugin's points with that plugin's `provides`. A
|
|
2434
|
+
* consumer of a point no installed plugin provides, or of another version, is invalid.
|
|
2435
|
+
* Registration order never matters: the registry matches points by name, and every point
|
|
2436
|
+
* is built here before any plugin's `register()` runs.
|
|
2437
|
+
*/
|
|
2438
|
+
#resolvePluginPoints(): void {
|
|
2439
|
+
for (const plugin of this.#plugins.values()) {
|
|
2440
|
+
if (plugin.problems.length) continue;
|
|
2441
|
+
for (const point of providedPoints(plugin.manifest)) this.#pluginPoints.set(point.name, { point, plugin: plugin.manifest.name });
|
|
2442
|
+
}
|
|
2443
|
+
for (const plugin of [...this.#plugins.values()]) {
|
|
2444
|
+
if (plugin.problems.length) continue;
|
|
2445
|
+
const problems: string[] = [];
|
|
2446
|
+
for (const hook of plugin.manifest.hooks ?? []) {
|
|
2447
|
+
if (!isPluginPoint(hook.point)) continue;
|
|
2448
|
+
const provided = this.#pluginPoints.get(hook.point);
|
|
2449
|
+
if (!provided) problems.push(`hooks: ${hook.point} is provided by no installed plugin.`);
|
|
2450
|
+
else if (provided.point.version !== hook.version) problems.push(`hooks: ${hook.point} is version ${provided.point.version}, not ${hook.version}.`);
|
|
2451
|
+
}
|
|
2452
|
+
if (problems.length) this.#plugins.set(plugin.manifest.name, { ...plugin, problems, requested: [] });
|
|
2453
|
+
}
|
|
2454
|
+
}
|
|
2455
|
+
|
|
2456
|
+
#registerPlugin(plugin: HostedPlugin): void {
|
|
2457
|
+
const register = plugin.registration.module?.register;
|
|
2458
|
+
const isolated = isolatedCode(plugin.registration);
|
|
2459
|
+
if (plugin.problems.length || (!isolated && typeof register !== 'function')) return;
|
|
2460
|
+
const name = plugin.manifest.name;
|
|
2461
|
+
const active = () => this.pluginActive(name);
|
|
2462
|
+
const declared = new Set((plugin.manifest.hooks ?? []).map(hook => hook.point));
|
|
2463
|
+
const provided = new Set((plugin.manifest.provides ?? []).map(declaration => declaration.point));
|
|
2464
|
+
const declaredCommands = new Set((plugin.manifest.commands ?? []).map(command => command.name));
|
|
2465
|
+
// Unrestricted: any extension point, though handlers still run only while the plugin is active.
|
|
2466
|
+
const anyPoint = plugin.manifest.permissions?.unrestricted === true;
|
|
2467
|
+
const checkHook = (point: ExtensionPoint) => {
|
|
2468
|
+
if (!anyPoint && !declared.has(point.name)) throw new Error(`Plugin ${name} registers ${point.name}, which its manifest does not declare in hooks.`);
|
|
2469
|
+
const known = this.#pluginPoints.get(point.name);
|
|
2470
|
+
if (known && (known.point.kind !== point.kind || known.point.version !== point.version)) throw new Error(`Plugin ${name} registers ${point.name} as a version ${point.version} ${point.kind}; ${known.plugin} provides a version ${known.point.version} ${known.point.kind}.`);
|
|
2471
|
+
};
|
|
2472
|
+
const checkProvided = (point: ExtensionPoint) => {
|
|
2473
|
+
const known = this.#pluginPoints.get(point.name);
|
|
2474
|
+
if (!provided.has(point.name) || !known) throw new Error(`Plugin ${name} invokes ${point.name}, which its manifest does not declare in provides.`);
|
|
2475
|
+
if (known.point.kind !== point.kind || known.point.version !== point.version) throw new Error(`Plugin ${name} invokes ${point.name} as a version ${point.version} ${point.kind}, not the version ${known.point.version} ${known.point.kind} it provides.`);
|
|
2476
|
+
};
|
|
2477
|
+
const allowed = async (grant: string, what: string): Promise<void> => {
|
|
2478
|
+
if (!(await active())) throw new CmsError('CMS_UNAVAILABLE', `Plugin ${name} is not active.`);
|
|
2479
|
+
const granted = this.#granted(name, await this.#state());
|
|
2480
|
+
if (!granted.has(grant) && !granted.has(UNRESTRICTED_GRANT)) throw new CmsError('CMS_FORBIDDEN', `Plugin ${name} is not granted ${what}.`);
|
|
2481
|
+
};
|
|
2482
|
+
const capabilities = pluginCapabilities({ name, manifest: plugin.manifest, allowed, files: this.files, mail: this.mail, mailFrom: this.mailFrom, users: this.users, cache: this.cache,
|
|
2483
|
+
outbox: this.outbox, secrets: this.#secrets, ai: this.ai, payments: this.payments, now: this.#now, queued: () => this.outboxWritten(),
|
|
2484
|
+
// An isolated plugin's job handlers live in its Worker.
|
|
2485
|
+
...(isolated ? { jobRunner: (job: string, payload: unknown, ctx: PluginJobContext) => this.#runIsolated(name, { kind: 'job', name: job, payload, scheduledAt: ctx.scheduledAt, principal: ctx.principal }, 'work', [ctx.principal]) } : {}) });
|
|
2486
|
+
// The plugin's jobs, queued or scheduled, run its handlers; other plugins' events pass by.
|
|
2487
|
+
this.hooks.addAction(pluginJob, async (event, ctx) => { if (event.plugin === name) await capabilities.runJob(event, { signal: ctx.signal }); }, { plugin: name });
|
|
2488
|
+
const context: PluginContext = {
|
|
2489
|
+
name,
|
|
2490
|
+
version: plugin.manifest.version,
|
|
2491
|
+
resources: plugin.resources,
|
|
2492
|
+
hooks: {
|
|
2493
|
+
// A disabled, unmigrated or ungranted plugin's handlers do not run.
|
|
2494
|
+
addAction: (point, handler, options = {}) => {
|
|
2495
|
+
checkHook(point);
|
|
2496
|
+
this.hooks.addAction(point, async (payload, ctx) => { if (await active()) await handler(payload, ctx); }, { ...options, plugin: name });
|
|
2497
|
+
},
|
|
2498
|
+
addFilter: (point, handler, options = {}) => {
|
|
2499
|
+
checkHook(point);
|
|
2500
|
+
this.hooks.addFilter(point, async (value, ctx) => await active() ? handler(value, ctx) : value, { ...options, plugin: name });
|
|
2501
|
+
},
|
|
2502
|
+
point: ((pointName: string, kind: 'action' | 'filter') => {
|
|
2503
|
+
const known = this.#pluginPoints.get(pointName);
|
|
2504
|
+
if (!known || (!anyPoint && !declared.has(pointName) && !provided.has(pointName))) throw new Error(`Plugin ${name} asks for ${pointName}, which its manifest does not declare in hooks or provides.`);
|
|
2505
|
+
if (known.point.kind !== kind) throw new Error(`${pointName} is ${known.point.kind === 'action' ? 'an action' : 'a filter'}, not ${kind === 'action' ? 'an action' : 'a filter'}.`);
|
|
2506
|
+
return known.point;
|
|
2507
|
+
}) as PluginContext['hooks']['point'],
|
|
2508
|
+
doAction: async (point, payload, options) => {
|
|
2509
|
+
checkProvided(point);
|
|
2510
|
+
if (!(await active())) return Object.freeze({ ok: true, outcomes: Object.freeze([]), failed: Object.freeze([]) });
|
|
2511
|
+
return this.hooks.doAction(point, payload, options);
|
|
2512
|
+
},
|
|
2513
|
+
applyFilters: async (point, value, input, options) => {
|
|
2514
|
+
checkProvided(point);
|
|
2515
|
+
if (!(await active())) return value;
|
|
2516
|
+
return this.hooks.applyFilters(point, value, ...[input, options] as never);
|
|
2517
|
+
},
|
|
2518
|
+
},
|
|
2519
|
+
commands: {
|
|
2520
|
+
add: (command, handler) => {
|
|
2521
|
+
if (!declaredCommands.has(command)) throw new Error(`Plugin ${name} adds command ${command}, which its manifest does not declare.`);
|
|
2522
|
+
plugin.commands.set(command, handler);
|
|
2523
|
+
},
|
|
2524
|
+
},
|
|
2525
|
+
cms: this.pluginCms(name),
|
|
2526
|
+
files: capabilities.files,
|
|
2527
|
+
mail: capabilities.mail,
|
|
2528
|
+
jobs: capabilities.jobs,
|
|
2529
|
+
users: capabilities.users,
|
|
2530
|
+
cache: capabilities.cache,
|
|
2531
|
+
secrets: capabilities.secrets,
|
|
2532
|
+
ai: capabilities.ai,
|
|
2533
|
+
payments: capabilities.payments,
|
|
2534
|
+
unrestricted: async () => {
|
|
2535
|
+
await allowed(UNRESTRICTED_GRANT, 'unrestricted access');
|
|
2536
|
+
return { db: this.db, host: this, env: this.#env };
|
|
2537
|
+
},
|
|
2538
|
+
settings: {
|
|
2539
|
+
get: async field => {
|
|
2540
|
+
if (!(await active())) throw new CmsError('CMS_UNAVAILABLE', `Plugin ${name} is not active.`);
|
|
2541
|
+
const fields = plugin.manifest.settings?.fields;
|
|
2542
|
+
if (typeof field !== 'string' || !fields || !Object.hasOwn(fields, field)) throw new CmsError('CMS_NOT_FOUND', `Unknown setting of plugin ${name}.`);
|
|
2543
|
+
return structuredClone(await this.settings.get(`${pluginSettingsGroupId(name)}.${field}`));
|
|
2544
|
+
},
|
|
2545
|
+
all: async () => {
|
|
2546
|
+
if (!(await active())) throw new CmsError('CMS_UNAVAILABLE', `Plugin ${name} is not active.`);
|
|
2547
|
+
const values = await this.settings.all();
|
|
2548
|
+
return Object.fromEntries(Object.keys(plugin.manifest.settings?.fields ?? {}).map(field => [field, structuredClone(values[`${pluginSettingsGroupId(name)}.${field}`])]));
|
|
2549
|
+
},
|
|
2550
|
+
},
|
|
2551
|
+
fetch: async (input, init) => {
|
|
2552
|
+
const granted = this.#granted(name, await this.#state());
|
|
2553
|
+
const unrestricted = granted.has(UNRESTRICTED_GRANT);
|
|
2554
|
+
const hosts = [...granted].filter(grant => grant.startsWith('network:')).map(grant => grant.slice('network:'.length));
|
|
2555
|
+
const check = (url: URL) => {
|
|
2556
|
+
if (!unrestricted && !hosts.some(host => host === url.hostname || (host.startsWith('*.') && url.hostname.endsWith(host.slice(1))))) {
|
|
2557
|
+
throw new CmsError('CMS_FORBIDDEN', `Plugin ${name} is not granted network access to ${url.hostname}.`);
|
|
2558
|
+
}
|
|
2559
|
+
};
|
|
2560
|
+
let url = new URL(input instanceof Request ? input.url : String(input));
|
|
2561
|
+
check(url);
|
|
2562
|
+
if (unrestricted) return this.#fetch(input, init);
|
|
2563
|
+
// Redirects are followed here, one hop at a time, so a granted host cannot pass the request on to a host that is not.
|
|
2564
|
+
const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();
|
|
2565
|
+
const redirect = init?.redirect ?? (input instanceof Request ? input.redirect : 'follow');
|
|
2566
|
+
let response = await this.#fetch(input, { ...init, redirect: 'manual' });
|
|
2567
|
+
const location = () => response.status >= 300 && response.status < 400 ? response.headers.get('location') : null;
|
|
2568
|
+
if (redirect === 'manual' || !location()) return response;
|
|
2569
|
+
if (redirect === 'error') throw new TypeError(`Plugin ${name}'s request was redirected.`);
|
|
2570
|
+
// A request with a body is not sent again: its redirect is returned as it came.
|
|
2571
|
+
if (method !== 'GET' && method !== 'HEAD') return response;
|
|
2572
|
+
const headers = init?.headers ?? (input instanceof Request ? input.headers : undefined);
|
|
2573
|
+
const signal = init?.signal ?? (input instanceof Request ? input.signal : undefined);
|
|
2574
|
+
for (let hop = 0; hop < 5 && location(); hop++) {
|
|
2575
|
+
url = new URL(location()!, url);
|
|
2576
|
+
check(url);
|
|
2577
|
+
await response.body?.cancel().catch(() => undefined);
|
|
2578
|
+
response = await this.#fetch(url.href, { method, redirect: 'manual', ...(headers ? { headers } : {}), ...(signal ? { signal } : {}) });
|
|
2579
|
+
}
|
|
2580
|
+
if (location()) throw new CmsError('CMS_UNAVAILABLE', `Plugin ${name}'s request was redirected too many times.`);
|
|
2581
|
+
return response;
|
|
2582
|
+
},
|
|
2583
|
+
};
|
|
2584
|
+
if (isolated) this.#registerIsolated(plugin, context, isolated);
|
|
2585
|
+
else (register as (context: PluginContext) => void)(context);
|
|
2586
|
+
}
|
|
2587
|
+
|
|
2588
|
+
/**
|
|
2589
|
+
* An isolated plugin's handlers are stand-ins built from its manifest: each forwards its
|
|
2590
|
+
* call to the plugin's Worker, which runs the handlers `register()` added there. The context
|
|
2591
|
+
* the host would have given `register()` is what the bridge serves.
|
|
2592
|
+
*/
|
|
2593
|
+
#registerIsolated(plugin: HostedPlugin, context: PluginContext, code: IsolatedPluginCode): void {
|
|
2594
|
+
const name = plugin.manifest.name;
|
|
2595
|
+
this.#isolated.set(name, { context, code });
|
|
2596
|
+
for (const hook of plugin.manifest.hooks ?? []) {
|
|
2597
|
+
const point = this.#pointNamed(hook.point);
|
|
2598
|
+
if (!point) continue;
|
|
2599
|
+
const options = { priority: hook.priority ?? 10 };
|
|
2600
|
+
if (point.kind === 'action') {
|
|
2601
|
+
context.hooks.addAction(point as ActionPoint<unknown>, async (payload, ctx) => { await this.#runIsolated(name, { kind: 'action', point: point.name, payload }, 'hook', [], ctx.deadline); }, options);
|
|
2602
|
+
} else {
|
|
2603
|
+
context.hooks.addFilter(point as FilterPoint<unknown, unknown>, (value, ctx) => this.#runIsolated(name, { kind: 'filter', point: point.name, value, input: (ctx as FilterContext<unknown>).input }, 'hook', [], ctx.deadline), options);
|
|
2604
|
+
}
|
|
2605
|
+
}
|
|
2606
|
+
for (const command of plugin.manifest.commands ?? []) {
|
|
2607
|
+
context.commands.add(command.name, (input, { principal }) => this.#runIsolated(name, { kind: 'command', name: command.name, input, principal }, 'work', [principal]));
|
|
2608
|
+
}
|
|
2609
|
+
}
|
|
2610
|
+
|
|
2611
|
+
/** A CMS point or one an installed plugin provides, by name. */
|
|
2612
|
+
#pointNamed(name: string): ExtensionPoint | undefined {
|
|
2613
|
+
return this.#pluginPoints.get(name)?.point ?? EXTENSION_POINTS.find(point => point.name === name);
|
|
2614
|
+
}
|
|
2615
|
+
|
|
2616
|
+
#isolatePoints(plugin: HostedPlugin): IsolatePoint[] {
|
|
2617
|
+
const names = [...(plugin.manifest.hooks ?? []).map(hook => hook.point), ...(plugin.manifest.provides ?? []).map(point => point.point)];
|
|
2618
|
+
return names.flatMap(pointName => {
|
|
2619
|
+
const point = this.#pointNamed(pointName);
|
|
2620
|
+
return point ? [{ name: point.name, kind: point.kind, version: point.version, timeoutMs: point.timeoutMs }] : [];
|
|
2621
|
+
});
|
|
2622
|
+
}
|
|
2623
|
+
|
|
2624
|
+
async #runIsolated(name: string, run: IsolateRun, work: IsolatedWork, principals: readonly Principal[], deadline = Date.now() + ISOLATED_WORK_MS): Promise<unknown> {
|
|
2625
|
+
const isolated = this.#isolated.get(name);
|
|
2626
|
+
const plugin = this.#plugins.get(name);
|
|
2627
|
+
if (!isolated || !plugin || !this.#runner) throw new CmsError('CMS_UNAVAILABLE', `Plugin ${name} cannot run isolated here.`);
|
|
2628
|
+
const call: IsolateCall = { protocol: ISOLATE_PROTOCOL, site: this.site, deadline, resources: plugin.resources, points: this.#isolatePoints(plugin), payments: this.payments?.name ?? null, run };
|
|
2629
|
+
try {
|
|
2630
|
+
return await this.#runner.run(isolated.code, call, { site: this.site, plugin: name, deadline, principals }, work);
|
|
2631
|
+
} catch (error) {
|
|
2632
|
+
// A payload with functions or class instances cannot cross; say so instead of the platform's words.
|
|
2633
|
+
if ((error as { name?: unknown } | null)?.name === 'DataCloneError') {
|
|
2634
|
+
throw Object.assign(new Error(`Plugin ${name} could not be called with ${run.kind === 'action' || run.kind === 'filter' ? run.point : run.name}: its data cannot be copied into the plugin's Worker (${(error as Error).message}).`), { code: 'COSSACK_PLUGIN_PAYLOAD' });
|
|
2635
|
+
}
|
|
2636
|
+
throw error;
|
|
2637
|
+
}
|
|
2638
|
+
}
|
|
2639
|
+
|
|
2640
|
+
/** What the application's `PluginBridge` serves: one call from an isolated plugin's Worker, checked as the plugin's context checks it. */
|
|
2641
|
+
isolatedCall(name: string, member: string, args: readonly unknown[], principals: readonly Principal[]): Promise<unknown> {
|
|
2642
|
+
const isolated = this.#isolated.get(name);
|
|
2643
|
+
if (!isolated) return Promise.reject(new CmsError('CMS_NOT_FOUND', `Plugin ${name} does not run isolated on this site.`));
|
|
2644
|
+
return serveIsolatedCall(isolated.context, member, args, principals);
|
|
2645
|
+
}
|
|
2646
|
+
|
|
2647
|
+
async #pluginStatus(plugin: HostedPlugin, state: Activation): Promise<PluginStatus> {
|
|
2648
|
+
const themeOnly = isThemeOnly(plugin.manifest);
|
|
2649
|
+
const network = themeOnly ? 'available' : pluginState(state.policy, plugin.manifest.name);
|
|
2650
|
+
const base = { name: plugin.registration.name, version: plugin.registration.version, description: typeof plugin.manifest.description === 'string' ? plugin.manifest.description : '', ...authorOf(plugin), ...artwork(plugin), themeOnly,
|
|
2651
|
+
unrestricted: plugin.requested.includes(UNRESTRICTED_GRANT), requests: [PLUGIN_ENABLED, ...plugin.requested], network,
|
|
2652
|
+
runtime: plugin.registration.isolation?.mode === 'isolated' ? 'isolated' as const : 'app' as const,
|
|
2653
|
+
...(plugin.registration.isolation?.mode === 'app' && plugin.registration.isolation.reason ? { runtimeReason: plugin.registration.isolation.reason } : {}) };
|
|
2654
|
+
if (plugin.problems.length) return { ...base, active: false, reason: `Invalid manifest: ${plugin.problems.join(' ')}`, missing: [] };
|
|
2655
|
+
// A theme alone runs nothing on the server: choosing it under Appearance is all it needs.
|
|
2656
|
+
if (themeOnly) return { ...base, active: true, missing: [] };
|
|
2657
|
+
if (network === 'hidden') return { ...base, active: false, reason: 'Hidden by the network.', missing: [] };
|
|
2658
|
+
const unmigrated: string[] = [];
|
|
2659
|
+
for (const id of [...plugin.resources, ...(plugin.manifest.collections ?? []).map(collection => `cms/${collection.name}`)]) {
|
|
2660
|
+
const resource = this.#resources.get(id);
|
|
2661
|
+
if (!resource || state.hashes.get(id) !== await declarationHash(resource)) unmigrated.push(id);
|
|
2662
|
+
}
|
|
2663
|
+
const granted = this.#granted(plugin.manifest.name, state);
|
|
2664
|
+
const missing = [PLUGIN_ENABLED, ...plugin.requested].filter(grant => !granted.has(grant));
|
|
2665
|
+
if (unmigrated.length) return { ...base, active: false, reason: `Waiting for a migration of ${unmigrated.join(', ')}.`, missing };
|
|
2666
|
+
if (missing.length && network === 'network') return { ...base, active: false, reason: `Needs the network's grant for ${missing.join(', ')}.`, missing };
|
|
2667
|
+
if (missing.length) return { ...base, active: false, reason: granted.size ? `Needs a new grant for ${missing.join(', ')}.` : 'Not enabled.', missing };
|
|
2668
|
+
return { ...base, active: true, missing: [] };
|
|
2669
|
+
}
|
|
2670
|
+
|
|
2671
|
+
/**
|
|
2672
|
+
* Register a visitor: `cms.user.before-register` filters may refuse it (`CMS_VALIDATION`
|
|
2673
|
+
* with their message), change its name and roles, or hold it for approval. Returns the
|
|
2674
|
+
* draft the account is made from.
|
|
2675
|
+
*/
|
|
2676
|
+
async registrationDraft(input: { email: string; name: string; roles: readonly string[]; approval: boolean }, context: { origin: string }): Promise<RegistrationDraft> {
|
|
2677
|
+
const original: RegistrationDraft = { email: input.email, name: input.name, roles: [...input.roles], approval: input.approval, refused: null };
|
|
2678
|
+
const known = new Set((await this.users.roles({ limit: 200 })).map(role => role.id));
|
|
2679
|
+
const draft = registrationDraftOf(await this.hooks.applyFilters(userBeforeRegister, original, context), original, known);
|
|
2680
|
+
if (draft.refused) throw new CmsError('CMS_VALIDATION', draft.refused);
|
|
2681
|
+
return draft;
|
|
2682
|
+
}
|
|
2683
|
+
|
|
2684
|
+
/** Queue `cms.user.registered` for a new account. */
|
|
2685
|
+
async userRegistered(user: UserRef, state: UserRegisteredEvent['state']): Promise<void> {
|
|
2686
|
+
const event: UserRegisteredEvent = { eventId: `user.registered:${user.id}`, topic: 'user.registered', at: this.#now(), user: { id: user.id, email: user.email, name: user.name }, state };
|
|
2687
|
+
if (await this.outbox.enqueue('user.registered', event, { ignoreDuplicate: true })) this.outboxWritten();
|
|
2688
|
+
}
|
|
2689
|
+
|
|
2690
|
+
/** Queue `cms.user.signed-in` for a session that just started; `sessionId` keeps repeated deliveries one event. */
|
|
2691
|
+
async userSignedIn(user: UserRef, sessionId: string): Promise<void> {
|
|
2692
|
+
await this.outbox.enqueue('user.signed-in', await this.#signedInEvent(user, sessionId), { ignoreDuplicate: true }).then(inserted => { if (inserted) this.outboxWritten(); });
|
|
2693
|
+
}
|
|
2694
|
+
|
|
2695
|
+
/** The outbox row of `cms.user.signed-in`, for the batch that stores the session: the event is queued exactly when the session is. */
|
|
2696
|
+
async userSignedInStatement(user: UserRef, sessionId: string): Promise<Statement> {
|
|
2697
|
+
return this.outbox.statement('user.signed-in', await this.#signedInEvent(user, sessionId), { ignoreDuplicate: true });
|
|
2698
|
+
}
|
|
2699
|
+
|
|
2700
|
+
async #signedInEvent(user: UserRef, sessionId: string): Promise<UserSignedInEvent> {
|
|
2701
|
+
return { eventId: `user.signed-in:${await sha256Hex(sessionId)}`, topic: 'user.signed-in', at: this.#now(), user: { id: user.id, email: user.email, name: user.name } };
|
|
2702
|
+
}
|
|
2703
|
+
|
|
2704
|
+
/**
|
|
2705
|
+
* A payments webhook: the provider verifies the request and names the event; a known event is
|
|
2706
|
+
* queued as `cms.payment.event` for plugins and delivered from the outbox, so a handler that
|
|
2707
|
+
* fails is retried. Returns the event, or null for one the CMS does not relay. Throws
|
|
2708
|
+
* `CMS_FORBIDDEN` for a bad signature and `CMS_UNAVAILABLE` without a provider.
|
|
2709
|
+
*/
|
|
2710
|
+
async receivePayment(request: Request): Promise<PaymentEvent | null> {
|
|
2711
|
+
if (!this.payments) throw new CmsError('CMS_UNAVAILABLE', 'The application has no payments provider.');
|
|
2712
|
+
const event = await this.payments.webhook(request);
|
|
2713
|
+
if (!event) return null;
|
|
2714
|
+
if (await this.outbox.enqueue('payment.event', event, { ignoreDuplicate: true })) this.outboxWritten();
|
|
2715
|
+
return event;
|
|
2716
|
+
}
|
|
2717
|
+
|
|
2718
|
+
/** An entry's event as the automations see it: created, updated or deleted, and published when it just went live. */
|
|
2719
|
+
async #automate(event: ResourceEvent): Promise<void> {
|
|
2720
|
+
if (!event.resource.startsWith('cms/')) return;
|
|
2721
|
+
const name = event.resource.slice('cms/'.length);
|
|
2722
|
+
const collection = this.#collections.get(name);
|
|
2723
|
+
if (!collection) return;
|
|
2724
|
+
const record = event.record;
|
|
2725
|
+
const path = record ? (await this.entryUrls(collection, [record]).catch(() => new Map<string, string | null>())).get(record.id) ?? '' : '';
|
|
2726
|
+
const origin = this.indexnow.origin() ?? '';
|
|
2727
|
+
const vars = { collection: name, collectionLabel: collection.label, id: event.id, title: record ? recordTitle(record, 'title') : '', status: record?.status ?? '', path, url: path ? `${origin}${path}` : '', actor: event.actor.id, record };
|
|
2728
|
+
const scopes = await this.#automationScopes(event.actor);
|
|
2729
|
+
await this.automations.run(event.topic === 'resource.deleted' ? 'entry.deleted' : event.topic === 'resource.created' ? 'entry.created' : 'entry.updated', vars, scopes, event.eventId);
|
|
2730
|
+
if (collection.publishable !== false && event.topic !== 'resource.deleted' && record?.status === 'published' && event.previousStatus !== 'published') await this.automations.run('entry.published', vars, scopes, `${event.eventId}:published`);
|
|
2731
|
+
}
|
|
2732
|
+
|
|
2733
|
+
/** What `$site` and `$user` read in an automation's templates: the site's public settings and the account that acted, when a user did. */
|
|
2734
|
+
async #automationScopes(actor?: WriteActor): Promise<Omit<BindingScopes, 'entry'>> {
|
|
2735
|
+
const settings = await this.settings.all().catch(() => null);
|
|
2736
|
+
const account = actor?.kind === 'user' ? await this.accounts.get(actor.id).catch(() => null) : null;
|
|
2737
|
+
return { site: settings ? siteBindingScope(settings) : null, user: account ? { name: account.name, email: account.email } : null };
|
|
2738
|
+
}
|
|
2739
|
+
|
|
2740
|
+
/** The schedules of active plugins that hold the jobs grant, for the clock. */
|
|
2741
|
+
async #dueSchedules(): Promise<DueSchedule[]> {
|
|
2742
|
+
const state = await this.#state();
|
|
2743
|
+
const due: DueSchedule[] = [];
|
|
2744
|
+
for (const plugin of this.#plugins.values()) {
|
|
2745
|
+
if (plugin.problems.length || !plugin.manifest.schedules?.length) continue;
|
|
2746
|
+
const granted = this.#granted(plugin.manifest.name, state);
|
|
2747
|
+
if (!granted.has('capability:jobs') && !granted.has(UNRESTRICTED_GRANT)) continue;
|
|
2748
|
+
if (!(await this.#pluginStatus(plugin, state)).active) continue;
|
|
2749
|
+
for (const schedule of plugin.manifest.schedules) due.push({ plugin: plugin.manifest.name, name: schedule.name, cron: schedule.cron });
|
|
2750
|
+
}
|
|
2751
|
+
return due;
|
|
2752
|
+
}
|
|
2753
|
+
|
|
2754
|
+
/** What a plugin is granted: the network's approval when the network activates it, else the site's own grant. */
|
|
2755
|
+
#granted(name: string, state: Activation): ReadonlySet<string> {
|
|
2756
|
+
const network = state.policy.plugins.get(name);
|
|
2757
|
+
if (network?.state === 'hidden') return new Set();
|
|
2758
|
+
if (network?.state === 'network') return new Set([PLUGIN_ENABLED, ...network.grants]);
|
|
2759
|
+
return state.grants.get(`plugin:${name}`) ?? new Set<string>();
|
|
2760
|
+
}
|
|
2761
|
+
|
|
2762
|
+
#state(): Promise<Activation> {
|
|
2763
|
+
const now = this.#now();
|
|
2764
|
+
if (!this.#activation || now - this.#activation.at > this.#activationTtl) {
|
|
2765
|
+
const policy = readPolicy(this.network).catch(error => { console.error('[cms] could not read the network policy', error); return OPEN_POLICY; });
|
|
2766
|
+
const state = this.db.read([
|
|
2767
|
+
{ rql: 'SELECT resource, declaration_hash FROM cms_schema_state ORDER BY resource LIMIT 1000' },
|
|
2768
|
+
{ rql: "SELECT subject, permission FROM cms_grants WHERE subject LIKE 'plugin:%' ORDER BY subject, permission LIMIT 1000" },
|
|
2769
|
+
{ rql: "SELECT version FROM cms_migrations WHERE kind = 'host' LIMIT 100" },
|
|
2770
|
+
]).then(async result => {
|
|
2771
|
+
const hostVersions = new Set(result.results[2]!.rows.map(([version]) => Number(version as bigint)));
|
|
2772
|
+
// A database made by another build is refused on every request, rather than read with the wrong schema.
|
|
2773
|
+
const unknown = unknownHostSteps(hostVersions);
|
|
2774
|
+
if (unknown.length) throw new CmsError('CMS_SCHEMA_MISMATCH', hostSchemaMismatch(unknown));
|
|
2775
|
+
const grants = new Map<string, Set<string>>();
|
|
2776
|
+
for (const [subject, permission] of result.results[1]!.rows) {
|
|
2777
|
+
const set = grants.get(subject as string) ?? new Set<string>();
|
|
2778
|
+
set.add(permission as string);
|
|
2779
|
+
grants.set(subject as string, set);
|
|
2780
|
+
}
|
|
2781
|
+
return {
|
|
2782
|
+
hashes: new Map(result.results[0]!.rows.map(([resource, hash]) => [resource as string, hash as string])), grants,
|
|
2783
|
+
hostVersions, policy: await policy,
|
|
2784
|
+
};
|
|
2785
|
+
}).catch(async error => {
|
|
2786
|
+
// Before the first migration the host tables do not exist yet.
|
|
2787
|
+
if (/cms_schema_state|cms_grants|cms_migrations|no such table|not found/i.test(String((error as Error).message))) return { hashes: new Map<string, string>(), grants: new Map<string, Set<string>>(), hostVersions: new Set<number>(), policy: await policy };
|
|
2788
|
+
throw error;
|
|
2789
|
+
});
|
|
2790
|
+
this.#activation = { at: now, state };
|
|
2791
|
+
state.catch(() => { this.#activation = undefined; });
|
|
2792
|
+
}
|
|
2793
|
+
return this.#activation.state;
|
|
2794
|
+
}
|
|
2795
|
+
}
|
|
2796
|
+
|
|
2797
|
+
function sameKeyOrder(a: object, b: object): boolean {
|
|
2798
|
+
return Object.keys(a).join('\n') === Object.keys(b).join('\n');
|
|
2799
|
+
}
|
|
2800
|
+
|
|
2801
|
+
/** Where a visitor's comment goes: spam for disallowed words, held for links or moderation rules, else approved. */
|
|
2802
|
+
function writeActorOf(principal: Principal): WriteActor {
|
|
2803
|
+
return { kind: principal.kind, id: principalId(principal) };
|
|
2804
|
+
}
|
|
2805
|
+
|
|
2806
|
+
async function commentStatus(fields: { content: string; authorName: string; authorEmail: string; authorUrl: string }, settings: SiteSettings, approvedBefore: () => Promise<boolean>): Promise<CommentStatus> {
|
|
2807
|
+
const text = `${fields.content}\n${fields.authorName}\n${fields.authorEmail}\n${fields.authorUrl}`.toLowerCase();
|
|
2808
|
+
const blocked = settings['discussion.blockedWords'].split('\n').map(word => word.trim().toLowerCase()).filter(Boolean);
|
|
2809
|
+
if (blocked.some(word => text.includes(word))) return 'spam';
|
|
2810
|
+
const links = (fields.content.match(/https?:\/\//gi) ?? []).length;
|
|
2811
|
+
if (settings['discussion.maxLinks'] > 0 && links >= settings['discussion.maxLinks']) return 'pending';
|
|
2812
|
+
const moderation = settings['discussion.moderation'];
|
|
2813
|
+
if (moderation === 'all') return 'pending';
|
|
2814
|
+
if (moderation === 'first') return await approvedBefore() ? 'approved' : 'pending';
|
|
2815
|
+
return 'approved';
|
|
2816
|
+
}
|
|
2817
|
+
|
|
2818
|
+
/** A plugin's theme loaders, from its `server.ts` `loaders` export. */
|
|
2819
|
+
function loadersOf(plugin: HostedPlugin): ThemeLoaders {
|
|
2820
|
+
const loaders = plugin.registration.module?.loaders;
|
|
2821
|
+
return loaders && typeof loaders === 'object' ? Object.fromEntries(Object.entries(loaders).filter(([, loader]) => typeof loader === 'function')) as ThemeLoaders : {};
|
|
2822
|
+
}
|
|
2823
|
+
|
|
2824
|
+
/** A plugin that only ships a theme: no resources, blocks, hooks, commands, slots or permissions. */
|
|
2825
|
+
function isThemeOnly(manifest: CmsPluginManifest): boolean {
|
|
2826
|
+
return manifest.theme !== undefined && manifest.settings === undefined && !manifest.resources?.length && !manifest.collections?.length && !manifest.blocks?.length && !manifest.hooks?.length && !manifest.commands?.length
|
|
2827
|
+
&& !Object.keys(manifest.ui?.slots ?? {}).length && !Object.keys(manifest.permissions?.resources ?? {}).length && !manifest.permissions?.network?.length && !manifest.permissions?.define?.length && manifest.permissions?.unrestricted !== true;
|
|
2828
|
+
}
|
|
2829
|
+
|
|
2830
|
+
/** The plugin's logo and cover: the manifest's files, else `assets/logo.*` and `assets/cover.*`. */
|
|
2831
|
+
/** A plugin's maker, with empty strings for what the manifest leaves out. */
|
|
2832
|
+
export interface PluginAuthorView { readonly name: string; readonly url: string; readonly email: string }
|
|
2833
|
+
|
|
2834
|
+
function authorOf(plugin: HostedPlugin): { author: PluginAuthorView | null } {
|
|
2835
|
+
const author = plugin.manifest.author;
|
|
2836
|
+
if (!author || typeof author !== 'object' || typeof author.name !== 'string') return { author: null };
|
|
2837
|
+
return { author: { name: author.name.trim(), url: typeof author.url === 'string' ? author.url : '', email: typeof author.email === 'string' ? author.email : '' } };
|
|
2838
|
+
}
|
|
2839
|
+
|
|
2840
|
+
function artwork(plugin: HostedPlugin): { logo: string | null; cover: string | null } {
|
|
2841
|
+
const assets = plugin.registration.assets ?? {};
|
|
2842
|
+
const pick = (declared: unknown, name: string) => (typeof declared === 'string' ? assets[declared] : undefined)
|
|
2843
|
+
?? ['svg', 'png', 'webp', 'jpg', 'jpeg', 'gif', 'avif'].map(extension => assets[`assets/${name}.${extension}`]).find(Boolean) ?? null;
|
|
2844
|
+
return { logo: pick(plugin.manifest.logo, 'logo'), cover: pick(plugin.manifest.cover, 'cover') };
|
|
2845
|
+
}
|
|
2846
|
+
|
|
2847
|
+
/** First path segments of the CMS's own routes: an entry served at the site root cannot take one as its slug. */
|
|
2848
|
+
export const DEFAULT_RESERVED_PATHS: readonly string[] = Object.freeze(['api', 'auth', 'dashboard', 'feed', 'media', 'preview', 'search', 'author', 'indexnow', 'sitemaps']);
|
|
2849
|
+
|
|
2850
|
+
/**
|
|
2851
|
+
* What a project may set for each site's CMS host, in `src/cms.config.ts`. An unset option
|
|
2852
|
+
* keeps the default the CMS application gives it. `reservedPaths` and `purgers` are added to
|
|
2853
|
+
* the defaults; every other option replaces its default.
|
|
2854
|
+
*/
|
|
2855
|
+
export type CmsProjectOptions = Partial<Pick<CmsOptions,
|
|
2856
|
+
'reservedPaths' | 'blocks' | 'settings' | 'taxonomies' | 'payments' | 'ai' | 'purgers' | 'mail' | 'mailFrom' | 'files' | 'oauth'>> & {
|
|
2857
|
+
/** The update notice: whether the CMS asks the update server, and which one (specs/cms-updates.md). */
|
|
2858
|
+
readonly updates?: UpdatesOptions;
|
|
2859
|
+
};
|
|
2860
|
+
|
|
2861
|
+
/** The options as a value, or computed from the environment bindings and the site. */
|
|
2862
|
+
export type CmsProjectConfig = CmsProjectOptions |
|
|
2863
|
+
((env: Readonly<Record<string, unknown>>, site: { readonly id: string; readonly host?: string | null }) => CmsProjectOptions);
|
|
2864
|
+
|
|
2865
|
+
export function createCMS(options: CmsOptions): CmsHost {
|
|
2866
|
+
return new CmsHost(options);
|
|
2867
|
+
}
|
|
2868
|
+
|
|
2869
|
+
/** Client address and browser of a sign-in, from a Hono context, for the sessions list. */
|
|
2870
|
+
function requestMetadata(context: unknown): { ip?: string; userAgent?: string } {
|
|
2871
|
+
const request = (context as { req?: { header(name: string): string | undefined } } | undefined)?.req;
|
|
2872
|
+
if (!request || typeof request.header !== 'function') return {};
|
|
2873
|
+
// The address the deployment trusts (TRUSTED_PROXY_HEADER, Cloudflare's, or the socket's), not a header anyone sends.
|
|
2874
|
+
const address = getClientIp(context as Parameters<typeof getClientIp>[0]);
|
|
2875
|
+
const ip = address && address !== 'anonymous' ? address : undefined;
|
|
2876
|
+
const userAgent = request.header('user-agent');
|
|
2877
|
+
return { ...(ip ? { ip } : {}), ...(userAgent ? { userAgent } : {}) };
|
|
2878
|
+
}
|
|
2879
|
+
|
|
2880
|
+
/** Whether a payment event completes a payment, once per payment: what its provider says in `completes`. */
|
|
2881
|
+
export function paymentCompleted(event: PaymentEvent): boolean {
|
|
2882
|
+
return event.completes;
|
|
2883
|
+
}
|
|
2884
|
+
|
|
2885
|
+
/**
|
|
2886
|
+
* Whether a copy of an entry (a duplicate, a translation) would hand someone what the entry
|
|
2887
|
+
* locks: a protected or members-only entry is copied only by those who may edit it. Members it
|
|
2888
|
+
* is for read it, but a copy they own would also carry its password, or outlive its roles.
|
|
2889
|
+
*/
|
|
2890
|
+
export function lockedCopy(record: RecordShape, editor: boolean): boolean {
|
|
2891
|
+
return !editor && isLockedRecord(record);
|
|
2892
|
+
}
|