@cossackframework/cms 0.0.0 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +145 -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 +21 -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 +709 -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 +114 -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 +62 -0
- package/app/src/dashboard/avatar-field.ts +58 -0
- package/app/src/dashboard/bulk.ts +22 -0
- package/app/src/dashboard/head.ts +29 -0
- package/app/src/dashboard/icons.ts +15 -0
- package/app/src/dashboard/list-table.ts +28 -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 +18 -0
- package/app/src/dashboard/session-list.ts +98 -0
- package/app/src/dashboard/tabs.ts +2 -0
- package/app/src/dashboard/time-ago.ts +16 -0
- package/app/src/dashboard/types.ts +43 -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 +82 -0
- package/app/src/pages/auth/layout.ts +32 -0
- package/app/src/pages/auth/login/index.ts +205 -0
- package/app/src/pages/auth/magic/index.ts +68 -0
- package/app/src/pages/auth/register/index.ts +124 -0
- package/app/src/pages/auth/reset-password/index.ts +74 -0
- package/app/src/pages/auth/setup/index.ts +194 -0
- package/app/src/pages/auth/two-factor/index.ts +69 -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 +183 -0
- package/app/src/pages/dashboard/index.ts +214 -0
- package/app/src/pages/dashboard/layout.ts +227 -0
- package/app/src/pages/dashboard/profile/index.ts +211 -0
- package/app/src/pages/dashboard/profile/security/index.ts +249 -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 +114 -2
- 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,275 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Notes: the rows of editors' review notes on entries (`notes.ts` has the shapes and rules).
|
|
3
|
+
* A thread is a root note and its replies; the root carries the thread's status and its last
|
|
4
|
+
* activity. Mentions get their own rows, so "notes for you" and the unseen count are one
|
|
5
|
+
* query each. The entry's room checks who may do what; this class keeps the rows.
|
|
6
|
+
*/
|
|
7
|
+
import type { RomeDB, Statement, Value } from '@cossackframework/romedb';
|
|
8
|
+
import { CmsError } from '../errors';
|
|
9
|
+
import { checkNoteBody, checkNoteQuote, checkNoteRange, mentionsIn, NOTE_LIMITS, NOTE_STATUSES, parseNoteTarget, type Note, type NoteRange, type NoteStatus } from '../notes';
|
|
10
|
+
import { inList } from './users';
|
|
11
|
+
import { readPaged } from './budget';
|
|
12
|
+
import { defineAction } from '@cossackframework/core/hooks';
|
|
13
|
+
|
|
14
|
+
/** What a note's announcement names besides the note: worked out by the caller, which knows the request and the entry. */
|
|
15
|
+
export interface NoteAnnouncement {
|
|
16
|
+
/** The site's configured origin for links, or null. */
|
|
17
|
+
readonly origin: string | null;
|
|
18
|
+
/** The entry's dashboard route (`posts`, `app.tickets`). */
|
|
19
|
+
readonly route: string;
|
|
20
|
+
/** The collection's name, for webhooks; null for a plugin's resource. */
|
|
21
|
+
readonly collection: string | null;
|
|
22
|
+
readonly title: string;
|
|
23
|
+
/** Who did it, by name. */
|
|
24
|
+
readonly author: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** The outbox job that announces a new or resolved note (webhooks, emails), queued with the note's own write. */
|
|
28
|
+
export interface NoteAnnouncedEvent {
|
|
29
|
+
readonly eventId: string;
|
|
30
|
+
readonly topic: 'note.announced';
|
|
31
|
+
readonly at: number;
|
|
32
|
+
readonly kind: 'created' | 'resolved';
|
|
33
|
+
readonly noteId: string;
|
|
34
|
+
readonly context: NoteAnnouncement;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Runs from the outbox; the application's `announceNote` handles it, plugins cannot hook it. */
|
|
38
|
+
export const noteAnnounced = defineAction<NoteAnnouncedEvent>('cms.note.announced', { version: 1, timeoutMs: 60_000 });
|
|
39
|
+
|
|
40
|
+
function announcementRow(kind: 'created' | 'resolved', noteId: string, at: number, context: NoteAnnouncement): Statement {
|
|
41
|
+
const event: NoteAnnouncedEvent = { eventId: `note:${noteId}:${kind}:${crypto.randomUUID()}`, topic: 'note.announced', at, kind, noteId, context };
|
|
42
|
+
return {
|
|
43
|
+
rql: 'INSERT INTO cms_outbox (id, topic, payload, created_at, available_at, attempts, lease_until) VALUES ($eventId, $topic, $payload, $at, $at, 0, 0)',
|
|
44
|
+
params: { $eventId: event.eventId, $topic: event.topic, $payload: JSON.stringify(event), $at: at },
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const WRITE = { kind: 'cms.notes', retryConflicts: 5 } as const;
|
|
49
|
+
const COLUMNS = 'id, resource, record_id, parent_id, user_id, target, text_range, quoted, body, status, resolved_by, resolved_at, created_at, updated_at';
|
|
50
|
+
const ID = /^[A-Za-z0-9_-]{1,80}$/;
|
|
51
|
+
|
|
52
|
+
export interface NoteInput {
|
|
53
|
+
readonly resource: string;
|
|
54
|
+
readonly recordId: string;
|
|
55
|
+
/** The thread to reply in; a root note has none. */
|
|
56
|
+
readonly parentId?: string | null;
|
|
57
|
+
readonly userId: string;
|
|
58
|
+
/** The anchor (`formatNoteTarget`); a reply takes its root's. */
|
|
59
|
+
readonly target?: string;
|
|
60
|
+
readonly range?: NoteRange | null;
|
|
61
|
+
readonly quote?: string;
|
|
62
|
+
readonly body: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export class CmsNotes {
|
|
66
|
+
readonly #db: RomeDB;
|
|
67
|
+
readonly #now: () => number;
|
|
68
|
+
|
|
69
|
+
constructor(db: RomeDB, options: { now?: () => number } = {}) {
|
|
70
|
+
this.#db = db;
|
|
71
|
+
this.#now = options.now ?? Date.now;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async get(id: string): Promise<Note | null> {
|
|
75
|
+
if (!ID.test(id)) return null;
|
|
76
|
+
const result = await this.#db.read([{ rql: `SELECT ${COLUMNS} FROM cms_notes WHERE id = $id`, params: { $id: id } }]);
|
|
77
|
+
const row = result.results[0]!.rows[0];
|
|
78
|
+
return row ? noteOf(row) : null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** An entry's notes, roots and replies, oldest first. */
|
|
82
|
+
async forEntry(resource: string, recordId: string): Promise<Note[]> {
|
|
83
|
+
check(recordId);
|
|
84
|
+
// Notes hold up to a few thousand characters each: read in pages that fit the result budget.
|
|
85
|
+
const rows = await readPaged(this.#db, (limit, offset) => ({
|
|
86
|
+
rql: `SELECT ${COLUMNS} FROM cms_notes WHERE resource = $resource AND record_id = $record ORDER BY created_at, id LIMIT $limit OFFSET $offset`,
|
|
87
|
+
params: { $resource: resource, $record: recordId, $limit: limit, $offset: offset },
|
|
88
|
+
}), NOTE_LIMITS.perEntry, 0);
|
|
89
|
+
return rows.map(noteOf);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* A new thread, or a reply in one. A reply mentions the thread's author and everyone who
|
|
94
|
+
* replied before, so they hear of it; a mention in the body adds its person.
|
|
95
|
+
*/
|
|
96
|
+
async create(input: NoteInput, options: { announce?: NoteAnnouncement } = {}): Promise<Note> {
|
|
97
|
+
check(input.recordId);
|
|
98
|
+
if (!ID.test(input.userId)) throw new CmsError('CMS_VALIDATION', 'Invalid user.');
|
|
99
|
+
const body = checkNoteBody(input.body);
|
|
100
|
+
const now = this.#now();
|
|
101
|
+
const id = crypto.randomUUID();
|
|
102
|
+
let target = input.target ?? 'entry';
|
|
103
|
+
let range: NoteRange | null = null;
|
|
104
|
+
let quote = '';
|
|
105
|
+
let mentioned = mentionsIn(body);
|
|
106
|
+
if (input.parentId) {
|
|
107
|
+
const root = await this.get(input.parentId);
|
|
108
|
+
if (!root || root.parentId || root.resource !== input.resource || root.recordId !== input.recordId) throw new CmsError('CMS_NOT_FOUND', 'The note to reply to does not exist.');
|
|
109
|
+
target = root.target;
|
|
110
|
+
const result = await this.#db.read([{ rql: 'SELECT user_id FROM cms_notes WHERE id = $root OR parent_id = $root', params: { $root: root.id } }]);
|
|
111
|
+
mentioned = [...new Set([...mentioned, ...result.results[0]!.rows.map(row => row[0] as string)])];
|
|
112
|
+
} else {
|
|
113
|
+
if (!parseNoteTarget(target)) throw new CmsError('CMS_VALIDATION', 'The note has no place to go.');
|
|
114
|
+
range = target.startsWith('text:') ? checkNoteRange(input.range) : null;
|
|
115
|
+
quote = target.startsWith('text:') ? checkNoteQuote(input.quote) : '';
|
|
116
|
+
}
|
|
117
|
+
const count = await this.#db.read([{ rql: 'SELECT count(*) FROM cms_notes WHERE resource = $resource AND record_id = $record', params: { $resource: input.resource, $record: input.recordId } }]);
|
|
118
|
+
if (Number(count.results[0]!.rows[0]![0] as bigint) >= NOTE_LIMITS.perEntry) throw new CmsError('CMS_LIMIT', `An entry holds at most ${NOTE_LIMITS.perEntry} notes. Resolve and remove some first.`);
|
|
119
|
+
const thread = input.parentId ?? id;
|
|
120
|
+
const statements: Statement[] = [{
|
|
121
|
+
rql: `INSERT INTO cms_notes (${COLUMNS}) VALUES ($id, $resource, $record, $parent, $user, $target, $range, $quote, $body, 'open', NULL, NULL, $now, $now)`,
|
|
122
|
+
params: { $id: id, $resource: input.resource, $record: input.recordId, $parent: input.parentId ?? null, $user: input.userId, $target: target, $range: range ? JSON.stringify(range) : null, $quote: quote, $body: body, $now: now },
|
|
123
|
+
}];
|
|
124
|
+
if (input.parentId) statements.push({ rql: 'UPDATE cms_notes SET updated_at = $now WHERE id = $root', params: { $now: now, $root: input.parentId } });
|
|
125
|
+
statements.push(...this.#mentionRows(id, thread, mentioned.filter(user => user !== input.userId), now, []));
|
|
126
|
+
// Its webhooks and emails follow from the outbox, queued only when the note is.
|
|
127
|
+
if (options.announce) statements.push(announcementRow('created', id, now, options.announce));
|
|
128
|
+
await this.#db.write(statements, WRITE);
|
|
129
|
+
return (await this.get(id))!;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Change a note's text; people it newly mentions hear of it. */
|
|
133
|
+
async edit(id: string, body: string): Promise<Note | null> {
|
|
134
|
+
const note = await this.get(id);
|
|
135
|
+
if (!note) return null;
|
|
136
|
+
const text = checkNoteBody(body);
|
|
137
|
+
const now = this.#now();
|
|
138
|
+
const known = await this.#db.read([{ rql: 'SELECT user_id FROM cms_note_mentions WHERE note_id = $id', params: { $id: id } }]);
|
|
139
|
+
const statements: Statement[] = [{ rql: 'UPDATE cms_notes SET body = $body, updated_at = $now WHERE id = $id', params: { $body: text, $now: now, $id: id } }];
|
|
140
|
+
if (note.parentId) statements.push({ rql: 'UPDATE cms_notes SET updated_at = $now WHERE id = $root', params: { $now: now, $root: note.parentId } });
|
|
141
|
+
statements.push(...this.#mentionRows(id, note.parentId ?? id, mentionsIn(text).filter(user => user !== note.userId), now, known.results[0]!.rows.map(row => row[0] as string)));
|
|
142
|
+
await this.#db.write(statements, WRITE);
|
|
143
|
+
return this.get(id);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Resolve or reopen a thread, by its root. */
|
|
147
|
+
async setStatus(id: string, status: NoteStatus, by: string, options: { announce?: NoteAnnouncement } = {}): Promise<Note | null> {
|
|
148
|
+
if (!NOTE_STATUSES.includes(status)) throw new CmsError('CMS_VALIDATION', 'Unknown note status.');
|
|
149
|
+
const note = await this.get(id);
|
|
150
|
+
if (!note || note.parentId) return null;
|
|
151
|
+
const now = this.#now();
|
|
152
|
+
await this.#db.write([{
|
|
153
|
+
rql: 'UPDATE cms_notes SET status = $status, resolved_by = $by, resolved_at = $at, updated_at = $now WHERE id = $id',
|
|
154
|
+
params: { $status: status, $by: status === 'resolved' ? by : null, $at: status === 'resolved' ? now : null, $now: now, $id: id },
|
|
155
|
+
}, ...(options.announce && status === 'resolved' ? [announcementRow('resolved', id, now, options.announce)] : [])], WRITE);
|
|
156
|
+
return this.get(id);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Delete a note; a root takes its replies and the thread's mentions with it. */
|
|
160
|
+
async remove(id: string): Promise<boolean> {
|
|
161
|
+
const note = await this.get(id);
|
|
162
|
+
if (!note) return false;
|
|
163
|
+
await this.#db.write(note.parentId
|
|
164
|
+
? [{ rql: 'DELETE FROM cms_note_mentions WHERE note_id = $id', params: { $id: id } }, { rql: 'DELETE FROM cms_notes WHERE id = $id', params: { $id: id } }]
|
|
165
|
+
: [{ rql: 'DELETE FROM cms_note_mentions WHERE thread_id = $id', params: { $id: id } }, { rql: 'DELETE FROM cms_notes WHERE id = $id OR parent_id = $id', params: { $id: id } }], WRITE);
|
|
166
|
+
return true;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Text notes' ranges after the passages moved, at most 100 at a time. */
|
|
170
|
+
async move(moves: readonly { id: string; range: NoteRange }[]): Promise<void> {
|
|
171
|
+
const statements: Statement[] = [];
|
|
172
|
+
for (const move of moves.slice(0, 100)) {
|
|
173
|
+
const range = checkNoteRange(move.range);
|
|
174
|
+
if (!ID.test(move.id) || !range) continue;
|
|
175
|
+
statements.push({ rql: "UPDATE cms_notes SET text_range = $range WHERE id = $id AND parent_id IS NULL AND target LIKE 'text:%'", params: { $range: JSON.stringify(range), $id: move.id } });
|
|
176
|
+
}
|
|
177
|
+
if (statements.length) await this.#db.write(statements, WRITE);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** The people a note names: its body's mentions and, for a reply, the thread's earlier voices; never its author. */
|
|
181
|
+
async mentioned(noteId: string): Promise<string[]> {
|
|
182
|
+
if (!ID.test(noteId)) return [];
|
|
183
|
+
const result = await this.#db.read([{ rql: 'SELECT user_id FROM cms_note_mentions WHERE note_id = $id ORDER BY user_id', params: { $id: noteId } }]);
|
|
184
|
+
return result.results[0]!.rows.map(row => row[0] as string);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Open threads per entry, for lists; entries without one are left out. */
|
|
188
|
+
async counts(resource: string, recordIds: readonly string[]): Promise<Map<string, number>> {
|
|
189
|
+
const ids = [...new Set(recordIds.filter(id => ID.test(id)))].slice(0, 100);
|
|
190
|
+
if (!ids.length) return new Map();
|
|
191
|
+
const list = inList('r', ids);
|
|
192
|
+
const result = await this.#db.read([{
|
|
193
|
+
rql: `SELECT record_id, count(*) FROM cms_notes WHERE resource = $resource AND parent_id IS NULL AND status = 'open' AND record_id IN ${list.rql} GROUP BY record_id`,
|
|
194
|
+
params: { $resource: resource, ...list.params },
|
|
195
|
+
}]);
|
|
196
|
+
return new Map(result.results[0]!.rows.map(([id, count]) => [id as string, Number(count as bigint)]));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Open threads a person started or is mentioned in, newest activity first. */
|
|
200
|
+
async forUser(userId: string, limit = 20): Promise<Note[]> {
|
|
201
|
+
if (!ID.test(userId)) return [];
|
|
202
|
+
// Notes hold up to 4000 characters each: a page may come in smaller reads.
|
|
203
|
+
const rows = await readPaged(this.#db, (size, at) => ({
|
|
204
|
+
rql: `SELECT ${COLUMNS} FROM cms_notes WHERE parent_id IS NULL AND status = 'open' AND (user_id = $user OR id IN (SELECT thread_id FROM cms_note_mentions WHERE user_id = $user))
|
|
205
|
+
ORDER BY updated_at DESC, id DESC LIMIT $limit OFFSET $offset`,
|
|
206
|
+
params: { $user: userId, $limit: size, $offset: at },
|
|
207
|
+
}), Math.min(Math.max(limit, 1), 100), 0);
|
|
208
|
+
return rows.map(noteOf);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Mentions of a person in open threads they have not opened yet. */
|
|
212
|
+
async unseen(userId: string): Promise<number> {
|
|
213
|
+
if (!ID.test(userId)) return 0;
|
|
214
|
+
const result = await this.#db.read([{
|
|
215
|
+
rql: "SELECT count(*) FROM cms_note_mentions WHERE user_id = $user AND seen_at IS NULL AND thread_id IN (SELECT id FROM cms_notes WHERE parent_id IS NULL AND status = 'open')",
|
|
216
|
+
params: { $user: userId },
|
|
217
|
+
}]);
|
|
218
|
+
return Number(result.results[0]!.rows[0]![0] as bigint);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** The person opened the entry: its mentions of them are seen. */
|
|
222
|
+
async markSeen(userId: string, resource: string, recordId: string): Promise<void> {
|
|
223
|
+
if (!ID.test(userId)) return;
|
|
224
|
+
check(recordId);
|
|
225
|
+
const pending = await this.#db.read([{
|
|
226
|
+
rql: 'SELECT 1 FROM cms_note_mentions WHERE user_id = $user AND seen_at IS NULL AND thread_id IN (SELECT id FROM cms_notes WHERE resource = $resource AND record_id = $record AND parent_id IS NULL) LIMIT 1',
|
|
227
|
+
params: { $user: userId, $resource: resource, $record: recordId },
|
|
228
|
+
}]);
|
|
229
|
+
if (!pending.results[0]!.rows.length) return;
|
|
230
|
+
await this.#db.write([{
|
|
231
|
+
rql: 'UPDATE cms_note_mentions SET seen_at = $now WHERE user_id = $user AND seen_at IS NULL AND thread_id IN (SELECT id FROM cms_notes WHERE resource = $resource AND record_id = $record AND parent_id IS NULL)',
|
|
232
|
+
params: { $now: this.#now(), $user: userId, $resource: resource, $record: recordId },
|
|
233
|
+
}], WRITE);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** The entries that hold notes, in a stable order from `offset`, for maintenance to check they still exist. */
|
|
237
|
+
async entries(limit = 200, offset = 0): Promise<{ resource: string; recordId: string }[]> {
|
|
238
|
+
const result = await this.#db.read([{
|
|
239
|
+
rql: `SELECT resource, record_id FROM cms_notes GROUP BY resource, record_id ORDER BY resource, record_id LIMIT ${Math.min(Math.max(limit, 1), 1000)} OFFSET ${Math.min(Math.max(Math.trunc(offset), 0), 1_000_000)}`,
|
|
240
|
+
}]);
|
|
241
|
+
return result.results[0]!.rows.map(row => ({ resource: row[0] as string, recordId: row[1] as string }));
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Every note of an entry, such as one that no longer exists. */
|
|
245
|
+
async purgeEntry(resource: string, recordId: string): Promise<void> {
|
|
246
|
+
check(recordId);
|
|
247
|
+
const params = { $resource: resource, $record: recordId };
|
|
248
|
+
await this.#db.write([
|
|
249
|
+
{ 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)', params },
|
|
250
|
+
{ rql: 'DELETE FROM cms_notes WHERE resource = $resource AND record_id = $record', params },
|
|
251
|
+
], WRITE);
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
#mentionRows(noteId: string, threadId: string, users: readonly string[], now: number, known: readonly string[]): Statement[] {
|
|
255
|
+
return users.filter(user => ID.test(user) && !known.includes(user)).slice(0, NOTE_LIMITS.mentions).map(user => ({
|
|
256
|
+
rql: 'INSERT INTO cms_note_mentions (note_id, thread_id, user_id, created_at, seen_at) VALUES ($note, $thread, $user, $now, NULL)',
|
|
257
|
+
params: { $note: noteId, $thread: threadId, $user: user, $now: now },
|
|
258
|
+
}));
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function check(recordId: string): void {
|
|
263
|
+
if (!ID.test(recordId)) throw new CmsError('CMS_VALIDATION', 'Invalid entry.');
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function noteOf(row: readonly Value[]): Note {
|
|
267
|
+
let range: NoteRange | null = null;
|
|
268
|
+
try { range = checkNoteRange(JSON.parse((row[6] as string | null) ?? 'null')); } catch { range = null; }
|
|
269
|
+
return {
|
|
270
|
+
id: row[0] as string, resource: row[1] as string, recordId: row[2] as string, parentId: (row[3] as string | null) ?? null, userId: row[4] as string,
|
|
271
|
+
target: row[5] as string, range, quote: (row[7] as string | null) ?? '', body: row[8] as string, status: row[9] as NoteStatus,
|
|
272
|
+
resolvedBy: (row[10] as string | null) ?? null, resolvedAt: row[11] === null || row[11] === undefined ? null : Number(row[11] as bigint),
|
|
273
|
+
createdAt: Number(row[12] as bigint), updatedAt: Number(row[13] as bigint),
|
|
274
|
+
};
|
|
275
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable after-commit delivery. Mutations commit their outbox row in the same batch;
|
|
3
|
+
* the dispatcher leases due rows, runs the handlers of the row's topic
|
|
4
|
+
* (`cms.resource.after-commit` for resource events, `cms.form.submitted` for form
|
|
5
|
+
* submissions), and records which plugins still need the event. Deliveries can repeat: consumers key on `eventId`.
|
|
6
|
+
*/
|
|
7
|
+
import type { RomeDB, Statement, Value } from '@cossackframework/romedb';
|
|
8
|
+
import type { HookRegistry } from '@cossackframework/core/hooks';
|
|
9
|
+
import type { ActionPoint } from '@cossackframework/core/hooks';
|
|
10
|
+
import { afterCommit, cachePurge, formSubmitted, paymentEvent, pluginJob, userRegistered, userSignedIn } from '../hooks';
|
|
11
|
+
import { searchRebuild } from './site-search';
|
|
12
|
+
import { collectionDeleted } from './comments';
|
|
13
|
+
import { sharedFields } from './shared-fields';
|
|
14
|
+
import { noteAnnounced } from './notes';
|
|
15
|
+
import { pathsMoved } from './path-moves';
|
|
16
|
+
import { readPaged } from './budget';
|
|
17
|
+
|
|
18
|
+
/** The action an outbox row runs, by its topic; resource events run `cms.resource.after-commit`. */
|
|
19
|
+
const POINTS: { readonly [topic: string]: ActionPoint<unknown> } = { 'form.submitted': formSubmitted as ActionPoint<unknown>, 'cache.purge': cachePurge as ActionPoint<unknown>, 'plugin.job': pluginJob as ActionPoint<unknown>, 'payment.event': paymentEvent as ActionPoint<unknown>, 'user.registered': userRegistered as ActionPoint<unknown>, 'user.signed-in': userSignedIn as ActionPoint<unknown>, 'search.rebuild': searchRebuild as ActionPoint<unknown>, 'collection.deleted': collectionDeleted as ActionPoint<unknown>, 'resource.shared': sharedFields as ActionPoint<unknown>, 'note.announced': noteAnnounced as ActionPoint<unknown>, 'paths.moved': pathsMoved as ActionPoint<unknown> };
|
|
20
|
+
|
|
21
|
+
export interface DispatchReport {
|
|
22
|
+
readonly delivered: readonly string[];
|
|
23
|
+
readonly retrying: readonly { id: string; plugins: readonly string[] }[];
|
|
24
|
+
/** Gave up after `maxAttempts`; the row keeps the failed plugins for inspection. */
|
|
25
|
+
readonly deadLettered: readonly string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface OutboxOptions {
|
|
29
|
+
now?: () => number;
|
|
30
|
+
leaseMs?: number;
|
|
31
|
+
maxAttempts?: number;
|
|
32
|
+
/** Delay before attempt n: `min(maxDelayMs, baseDelayMs * 2^(n-1))`. */
|
|
33
|
+
baseDelayMs?: number;
|
|
34
|
+
maxDelayMs?: number;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export class Outbox {
|
|
38
|
+
readonly #db: RomeDB;
|
|
39
|
+
readonly #hooks: HookRegistry;
|
|
40
|
+
readonly #now: () => number;
|
|
41
|
+
readonly #leaseMs: number;
|
|
42
|
+
readonly #maxAttempts: number;
|
|
43
|
+
readonly #baseDelay: number;
|
|
44
|
+
readonly #maxDelay: number;
|
|
45
|
+
|
|
46
|
+
constructor(db: RomeDB, hooks: HookRegistry, options: OutboxOptions = {}) {
|
|
47
|
+
this.#db = db;
|
|
48
|
+
this.#hooks = hooks;
|
|
49
|
+
this.#now = options.now ?? Date.now;
|
|
50
|
+
this.#leaseMs = options.leaseMs ?? 60_000;
|
|
51
|
+
this.#maxAttempts = options.maxAttempts ?? 10;
|
|
52
|
+
this.#baseDelay = options.baseDelayMs ?? 1_000;
|
|
53
|
+
this.#maxDelay = options.maxDelayMs ?? 15 * 60_000;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Rows `enqueue()` added, so a dispatch delivers what its own handlers queued. */
|
|
57
|
+
#enqueued = 0;
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Deliver up to `limit` due events. Safe to run concurrently: each row has one lease holder.
|
|
61
|
+
* A handler may queue more rows (an entry event queues a cache purge): up to three rounds
|
|
62
|
+
* deliver those now rather than after the next request.
|
|
63
|
+
*/
|
|
64
|
+
async dispatch(options: { limit?: number; signal?: AbortSignal } = {}): Promise<DispatchReport> {
|
|
65
|
+
const delivered: string[] = [];
|
|
66
|
+
const retrying: { id: string; plugins: readonly string[] }[] = [];
|
|
67
|
+
const deadLettered: string[] = [];
|
|
68
|
+
for (let round = 0; round < 3; round++) {
|
|
69
|
+
const enqueued = this.#enqueued;
|
|
70
|
+
const report = await this.#round(options);
|
|
71
|
+
delivered.push(...report.delivered);
|
|
72
|
+
retrying.push(...report.retrying);
|
|
73
|
+
deadLettered.push(...report.deadLettered);
|
|
74
|
+
if (this.#enqueued === enqueued) break;
|
|
75
|
+
}
|
|
76
|
+
return { delivered, retrying, deadLettered };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async #round(options: { limit?: number; signal?: AbortSignal }): Promise<DispatchReport> {
|
|
80
|
+
const now = this.#now();
|
|
81
|
+
const token = crypto.randomUUID();
|
|
82
|
+
const limit = Math.min(Math.max(options.limit ?? 20, 1), 100);
|
|
83
|
+
const call = options.signal ? { signal: options.signal } : {};
|
|
84
|
+
// Idle runs read only, so they do not race schema migrations for the database sequence.
|
|
85
|
+
const due = await this.#db.read([{ rql: 'SELECT 1 FROM cms_outbox WHERE delivered_at IS NULL AND available_at <= $now AND lease_until <= $now LIMIT 1', params: { $now: now } }], call);
|
|
86
|
+
if (!due.results[0]!.rows.length) return { delivered: [], retrying: [], deadLettered: [] };
|
|
87
|
+
await this.#db.write([{
|
|
88
|
+
rql: `UPDATE cms_outbox SET lease_token = $token, lease_until = $until, attempts = attempts + 1
|
|
89
|
+
WHERE id IN (SELECT id FROM cms_outbox WHERE delivered_at IS NULL AND available_at <= $now AND lease_until <= $now ORDER BY created_at, id LIMIT $limit)`,
|
|
90
|
+
params: { $token: token, $until: now + this.#leaseMs, $now: now, $limit: limit },
|
|
91
|
+
}], { ...call, kind: 'cms.outbox', retryConflicts: 5 });
|
|
92
|
+
// Payloads hold whole records: the claimed rows may come in smaller reads.
|
|
93
|
+
const claimed = await readPaged(this.#db, (size, at) => ({ rql: 'SELECT id, payload, pending_plugins, attempts, topic FROM cms_outbox WHERE lease_token = $token ORDER BY created_at, id LIMIT $limit OFFSET $offset', params: { $token: token, $limit: size, $offset: at } }), limit, 0, call);
|
|
94
|
+
const delivered: string[] = [];
|
|
95
|
+
const retrying: { id: string; plugins: readonly string[] }[] = [];
|
|
96
|
+
const deadLettered: string[] = [];
|
|
97
|
+
for (const [id, payload, pending, attempts, topic] of claimed) {
|
|
98
|
+
// Handlers run one row at a time and can outlast the batch lease. Past half of it,
|
|
99
|
+
// extend this row's lease first; a row another dispatcher claimed meanwhile is its to run.
|
|
100
|
+
if (this.#now() > now + this.#leaseMs / 2) {
|
|
101
|
+
const renewed = await this.#db.write([{
|
|
102
|
+
rql: 'UPDATE cms_outbox SET lease_until = $until WHERE id = $id AND lease_token = $token AND delivered_at IS NULL',
|
|
103
|
+
params: { $until: this.#now() + this.#leaseMs, $id: id as string, $token: token },
|
|
104
|
+
}], { ...call, kind: 'cms.outbox', retryConflicts: 5 });
|
|
105
|
+
if (renewed.results[0]!.affected !== 1n) continue;
|
|
106
|
+
}
|
|
107
|
+
const event = JSON.parse(payload as string) as unknown;
|
|
108
|
+
const only = pending ? JSON.parse(pending as string) as string[] : undefined;
|
|
109
|
+
const point = POINTS[topic as string] ?? afterCommit as ActionPoint<unknown>;
|
|
110
|
+
const report = await this.#hooks.doAction(point, event, { ...call, ...(only ? { only } : {}) });
|
|
111
|
+
const at = this.#now();
|
|
112
|
+
if (report.ok) {
|
|
113
|
+
await this.#settle(id as string, token, { $done: at, $pending: null, $available: at }, call);
|
|
114
|
+
delivered.push(id as string);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const attempt = Number(attempts as bigint);
|
|
118
|
+
if (attempt >= this.#maxAttempts) {
|
|
119
|
+
await this.#settle(id as string, token, { $done: at, $pending: JSON.stringify(report.failed), $available: at }, call);
|
|
120
|
+
deadLettered.push(id as string);
|
|
121
|
+
} else {
|
|
122
|
+
const delay = Math.min(this.#maxDelay, this.#baseDelay * 2 ** (attempt - 1));
|
|
123
|
+
await this.#settle(id as string, token, { $done: null, $pending: JSON.stringify(report.failed), $available: at + delay }, call);
|
|
124
|
+
retrying.push({ id: id as string, plugins: report.failed });
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return { delivered, retrying, deadLettered };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Queue an event of a topic outside a resource write, such as a cache purge or a plugin's job;
|
|
132
|
+
* `eventId` is the row, delivered from `availableAt` (default: now). With `ignoreDuplicate`, a
|
|
133
|
+
* row that exists is left alone and false comes back.
|
|
134
|
+
*/
|
|
135
|
+
/** The row `enqueue` writes, for a caller's own batch: the event is queued exactly when the batch commits. Call `outboxWritten()` after it. */
|
|
136
|
+
statement(topic: string, event: { readonly eventId: string; readonly at: number }, options: { availableAt?: number; ignoreDuplicate?: boolean } = {}): Statement {
|
|
137
|
+
return {
|
|
138
|
+
rql: `INSERT INTO cms_outbox (id, topic, payload, created_at, available_at, attempts, lease_until) VALUES ($outbox_id, $outbox_topic, $outbox_payload, $outbox_at, $outbox_available, 0, 0)${options.ignoreDuplicate ? ' ON CONFLICT (id) DO NOTHING' : ''}`,
|
|
139
|
+
params: { $outbox_id: event.eventId, $outbox_topic: topic, $outbox_payload: JSON.stringify(event), $outbox_at: event.at, $outbox_available: options.availableAt ?? event.at },
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async enqueue(topic: string, event: { readonly eventId: string; readonly at: number }, options: { signal?: AbortSignal; availableAt?: number; ignoreDuplicate?: boolean } = {}): Promise<boolean> {
|
|
144
|
+
const result = await this.#db.write([{
|
|
145
|
+
rql: `INSERT INTO cms_outbox (id, topic, payload, created_at, available_at, attempts, lease_until) VALUES ($id, $topic, $payload, $at, $available, 0, 0)${options.ignoreDuplicate ? ' ON CONFLICT (id) DO NOTHING' : ''}`,
|
|
146
|
+
params: { $id: event.eventId, $topic: topic, $payload: JSON.stringify(event), $at: event.at, $available: options.availableAt ?? event.at },
|
|
147
|
+
}], { ...(options.signal ? { signal: options.signal } : {}), kind: 'cms.outbox', retryConflicts: 5 });
|
|
148
|
+
const inserted = result.results[0]!.affected !== 0n;
|
|
149
|
+
if (inserted) this.#enqueued++;
|
|
150
|
+
return inserted;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Queue an event in one atomic write with `writes`, and only when `guard` (an SQL condition
|
|
155
|
+
* on the caller's rows, such as an `EXISTS`) holds as the write starts; a row that exists is
|
|
156
|
+
* left alone. The answer has whether the row was added and the results of `writes`.
|
|
157
|
+
*/
|
|
158
|
+
async enqueueWith(topic: string, event: { readonly eventId: string; readonly at: number }, guard: { readonly rql: string; readonly params: { readonly [name: string]: Value } }, writes: readonly Statement[]): Promise<{ inserted: boolean; results: readonly { readonly affected: bigint }[] }> {
|
|
159
|
+
const result = await this.#db.write([{
|
|
160
|
+
// The row's parameters have their own names, so the guard's own ($id, say) keep theirs.
|
|
161
|
+
rql: `INSERT INTO cms_outbox (id, topic, payload, created_at, available_at, attempts, lease_until) SELECT $outbox_id, $outbox_topic, $outbox_payload, $outbox_at, $outbox_at, 0, 0 WHERE ${guard.rql} ON CONFLICT (id) DO NOTHING`,
|
|
162
|
+
params: { ...guard.params, $outbox_id: event.eventId, $outbox_topic: topic, $outbox_payload: JSON.stringify(event), $outbox_at: event.at },
|
|
163
|
+
}, ...writes], { kind: 'cms.outbox', retryConflicts: 5 });
|
|
164
|
+
const inserted = result.results[0]!.affected !== 0n;
|
|
165
|
+
if (inserted) this.#enqueued++;
|
|
166
|
+
return { inserted, results: result.results.slice(1) };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Events the dispatcher gave up on: delivered, with the plugins that never took them kept in `plugins`. Newest first. */
|
|
170
|
+
async deadLettered(options: { limit?: number } = {}): Promise<{ id: string; topic: string; attempts: number; at: number; plugins: string[] }[]> {
|
|
171
|
+
const result = await this.#db.read([{ rql: 'SELECT id, topic, attempts, delivered_at, pending_plugins FROM cms_outbox WHERE delivered_at IS NOT NULL AND pending_plugins IS NOT NULL ORDER BY delivered_at DESC, id LIMIT $limit', params: { $limit: Math.min(Math.max(options.limit ?? 50, 1), 500) } }]);
|
|
172
|
+
return result.results[0]!.rows.map(row => ({ id: row[0] as string, topic: row[1] as string, attempts: Number(row[2] as bigint), at: Number(row[3] as bigint), plugins: JSON.parse(row[4] as string) as string[] }));
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Queue a waiting or dead-lettered event again, now, for the plugins that still need it. */
|
|
176
|
+
async retry(id: string): Promise<boolean> {
|
|
177
|
+
const result = await this.#db.write([{
|
|
178
|
+
rql: 'UPDATE cms_outbox SET delivered_at = NULL, attempts = 0, available_at = $now, lease_token = NULL, lease_until = 0 WHERE id = $id AND (delivered_at IS NULL OR pending_plugins IS NOT NULL)',
|
|
179
|
+
params: { $id: id, $now: this.#now() },
|
|
180
|
+
}], { kind: 'cms.outbox', retryConflicts: 5 });
|
|
181
|
+
return result.results[0]!.affected === 1n;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** Drop an event nobody will take. */
|
|
185
|
+
async remove(id: string): Promise<boolean> {
|
|
186
|
+
const result = await this.#db.write([{ rql: 'DELETE FROM cms_outbox WHERE id = $id AND (delivered_at IS NULL OR pending_plugins IS NOT NULL)', params: { $id: id } }], { kind: 'cms.outbox', retryConflicts: 5 });
|
|
187
|
+
return result.results[0]!.affected === 1n;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Events still waiting, oldest first. */
|
|
191
|
+
async pending(options: { limit?: number } = {}): Promise<{ id: string; topic: string; attempts: number; availableAt: number; plugins: string[] | null }[]> {
|
|
192
|
+
const result = await this.#db.read([{ rql: 'SELECT id, topic, attempts, available_at, pending_plugins FROM cms_outbox WHERE delivered_at IS NULL ORDER BY created_at, id LIMIT $limit', params: { $limit: options.limit ?? 50 } }]);
|
|
193
|
+
return result.results[0]!.rows.map(row => ({ id: row[0] as string, topic: row[1] as string, attempts: Number(row[2] as bigint), availableAt: Number(row[3] as bigint), plugins: row[4] ? JSON.parse(row[4] as string) : null }));
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** Delete delivered events older than `olderThanMs`. Dead letters stay until reviewed. */
|
|
197
|
+
async prune(olderThanMs = 7 * 24 * 60 * 60 * 1000): Promise<number> {
|
|
198
|
+
const old = await this.#db.read([{ rql: 'SELECT 1 FROM cms_outbox WHERE delivered_at IS NOT NULL AND delivered_at <= $before AND pending_plugins IS NULL LIMIT 1', params: { $before: this.#now() - olderThanMs } }]);
|
|
199
|
+
if (!old.results[0]!.rows.length) return 0;
|
|
200
|
+
const result = await this.#db.write([{
|
|
201
|
+
rql: 'DELETE FROM cms_outbox WHERE id IN (SELECT id FROM cms_outbox WHERE delivered_at IS NOT NULL AND delivered_at <= $before AND pending_plugins IS NULL LIMIT 1000)',
|
|
202
|
+
params: { $before: this.#now() - olderThanMs },
|
|
203
|
+
}], { kind: 'cms.outbox', retryConflicts: 5 });
|
|
204
|
+
return Number(result.results[0]!.affected);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async #settle(id: string, token: string, values: { $done: number | null; $pending: string | null; $available: number }, call: { signal?: AbortSignal }): Promise<void> {
|
|
208
|
+
await this.#db.write([{
|
|
209
|
+
rql: 'UPDATE cms_outbox SET delivered_at = $done, pending_plugins = $pending, available_at = $available, lease_token = NULL, lease_until = 0 WHERE id = $id AND lease_token = $token',
|
|
210
|
+
params: { ...values, $id: id, $token: token },
|
|
211
|
+
}], { ...call, kind: 'cms.outbox', retryConflicts: 5 });
|
|
212
|
+
}
|
|
213
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A collection or taxonomy moved to another URL path: old links keep answering through
|
|
3
|
+
* automatic redirects. The move is an outbox job, queued in the same write that saves the new
|
|
4
|
+
* path, so the redirects follow even after a crash between the two.
|
|
5
|
+
*/
|
|
6
|
+
import { defineAction } from '@cossackframework/core/hooks';
|
|
7
|
+
import type { Statement } from '@cossackframework/romedb';
|
|
8
|
+
|
|
9
|
+
export interface PathsMovedEvent {
|
|
10
|
+
readonly eventId: string;
|
|
11
|
+
readonly topic: 'paths.moved';
|
|
12
|
+
readonly at: number;
|
|
13
|
+
/** A collection's entries and archive, or a taxonomy's term archives. */
|
|
14
|
+
readonly kind: 'collection' | 'taxonomy';
|
|
15
|
+
readonly name: string;
|
|
16
|
+
/** The path before (`''` for the site root) and after. */
|
|
17
|
+
readonly from: string;
|
|
18
|
+
readonly to: string;
|
|
19
|
+
/** Who saved it, for the redirects' author. */
|
|
20
|
+
readonly by: string | null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Runs from the outbox; the host handles it, plugins cannot hook it. */
|
|
24
|
+
export const pathsMoved = defineAction<PathsMovedEvent>('cms.paths.moved', { version: 1, timeoutMs: 60_000 });
|
|
25
|
+
|
|
26
|
+
/** The outbox row of a move, for the batch that saves the new path. */
|
|
27
|
+
export function pathsMovedStatement(move: Omit<PathsMovedEvent, 'eventId' | 'topic'>): Statement {
|
|
28
|
+
const event: PathsMovedEvent = { ...move, eventId: `paths.moved:${move.kind}:${move.name}:${crypto.randomUUID()}`, topic: 'paths.moved' };
|
|
29
|
+
return {
|
|
30
|
+
rql: 'INSERT INTO cms_outbox (id, topic, payload, created_at, available_at, attempts, lease_until) VALUES ($move_id, $move_topic, $move_payload, $move_at, $move_at, 0, 0)',
|
|
31
|
+
params: { $move_id: event.eventId, $move_topic: event.topic, $move_payload: JSON.stringify(event), $move_at: event.at },
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Payments: one provider the application configures (Stripe built in, or its own) that plugins
|
|
3
|
+
* with the `payments` capability start checkouts through, and whose webhooks become
|
|
4
|
+
* `cms.payment.event` actions delivered from the outbox. Products, orders, plans and invoices are
|
|
5
|
+
* a plugin's own resources; the CMS keeps the money boundary and the event.
|
|
6
|
+
*/
|
|
7
|
+
import type { PaymentEvent } from '../hooks';
|
|
8
|
+
|
|
9
|
+
export interface CheckoutInput {
|
|
10
|
+
/** The amount in the currency's minor unit, such as cents; omitted with `priceId`. */
|
|
11
|
+
readonly amount?: number;
|
|
12
|
+
/** ISO 4217, lower or upper case. */
|
|
13
|
+
readonly currency?: string;
|
|
14
|
+
/** What is bought, shown by the provider. */
|
|
15
|
+
readonly description?: string;
|
|
16
|
+
/** A provider price for a subscription or a catalog item, instead of `amount`. */
|
|
17
|
+
readonly priceId?: string;
|
|
18
|
+
readonly mode?: 'payment' | 'subscription';
|
|
19
|
+
readonly successUrl: string;
|
|
20
|
+
readonly cancelUrl: string;
|
|
21
|
+
readonly customerEmail?: string;
|
|
22
|
+
/** The plugin's own key for the order, returned with the event as `reference`. */
|
|
23
|
+
readonly reference?: string;
|
|
24
|
+
readonly metadata?: { readonly [key: string]: string };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface Checkout {
|
|
28
|
+
readonly id: string;
|
|
29
|
+
/** Where the buyer goes to pay. */
|
|
30
|
+
readonly url: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface PaymentsProvider {
|
|
34
|
+
readonly name: string;
|
|
35
|
+
checkout(input: CheckoutInput): Promise<Checkout>;
|
|
36
|
+
/** The event a webhook request carries, verified; null for a type the CMS does not relay. Throws `CMS_FORBIDDEN` for a bad signature. */
|
|
37
|
+
webhook(request: Request): Promise<PaymentEvent | null>;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const CURRENCY = /^[A-Za-z]{3}$/;
|
|
41
|
+
const URL_OK = /^https?:\/\/[^\s]{1,2000}$/;
|
|
42
|
+
|
|
43
|
+
/** A checkout request within the rules, or an error naming what is wrong. */
|
|
44
|
+
export function checkCheckout(input: CheckoutInput): CheckoutInput {
|
|
45
|
+
if (!input || typeof input !== 'object') throw new Error('A checkout needs its fields.');
|
|
46
|
+
if (!URL_OK.test(input.successUrl ?? '') || !URL_OK.test(input.cancelUrl ?? '')) throw new Error('successUrl and cancelUrl must be absolute http(s) URLs.');
|
|
47
|
+
const mode = input.mode ?? (input.priceId ? 'subscription' : 'payment');
|
|
48
|
+
if (mode !== 'payment' && mode !== 'subscription') throw new Error('mode is payment or subscription.');
|
|
49
|
+
if (!input.priceId) {
|
|
50
|
+
if (!Number.isSafeInteger(input.amount) || (input.amount as number) <= 0) throw new Error('amount is a positive whole number of the currency\'s minor unit.');
|
|
51
|
+
if (!CURRENCY.test(input.currency ?? '')) throw new Error('currency is a three-letter code.');
|
|
52
|
+
if (typeof input.description !== 'string' || !input.description.trim() || input.description.length > 200) throw new Error('description is 1 to 200 characters.');
|
|
53
|
+
}
|
|
54
|
+
if (input.customerEmail !== undefined && (typeof input.customerEmail !== 'string' || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input.customerEmail))) throw new Error('customerEmail must be an email address.');
|
|
55
|
+
if (input.reference !== undefined && (typeof input.reference !== 'string' || !/^[\x21-\x7e]{1,200}$/.test(input.reference))) throw new Error('reference is 1-200 printable characters.');
|
|
56
|
+
const metadata = input.metadata ?? {};
|
|
57
|
+
if (Object.keys(metadata).length > 20 || Object.entries(metadata).some(([key, value]) => !/^[A-Za-z0-9_.-]{1,40}$/.test(key) || typeof value !== 'string' || value.length > 500)) throw new Error('metadata is up to 20 short string entries.');
|
|
58
|
+
return { ...input, mode, metadata };
|
|
59
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shareable preview links for unpublished entries. A link carries a random token; the table
|
|
3
|
+
* keeps only its SHA-256, the entry and an expiry, so a database read cannot preview anything.
|
|
4
|
+
*/
|
|
5
|
+
import type { RomeDB } from '@cossackframework/romedb';
|
|
6
|
+
import { sha256Hex, randomToken } from './tokens';
|
|
7
|
+
|
|
8
|
+
const WRITE = { kind: 'cms.previews', retryConflicts: 5 } as const;
|
|
9
|
+
const TOKEN = /^[A-Za-z0-9_-]{40,64}$/;
|
|
10
|
+
|
|
11
|
+
export interface PreviewLink {
|
|
12
|
+
readonly token: string;
|
|
13
|
+
readonly expiresAt: number;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export class CmsPreviews {
|
|
17
|
+
readonly #db: RomeDB;
|
|
18
|
+
readonly #now: () => number;
|
|
19
|
+
|
|
20
|
+
constructor(db: RomeDB, options: { now?: () => number } = {}) {
|
|
21
|
+
this.#db = db;
|
|
22
|
+
this.#now = options.now ?? Date.now;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** A new link to the entry. Callers check that the principal may edit it. */
|
|
26
|
+
async create(resource: string, recordId: string, createdBy: string | null, ttlMs = 7 * 24 * 60 * 60 * 1000): Promise<PreviewLink> {
|
|
27
|
+
const token = randomToken(32);
|
|
28
|
+
const now = this.#now();
|
|
29
|
+
await this.#db.write([{
|
|
30
|
+
rql: 'INSERT INTO cms_preview_tokens (id, resource, record_id, created_by, created_at, expires_at) VALUES ($id, $resource, $record, $by, $now, $expires)',
|
|
31
|
+
params: { $id: await sha256Hex(token), $resource: resource, $record: recordId, $by: createdBy, $now: now, $expires: now + ttlMs },
|
|
32
|
+
}], WRITE);
|
|
33
|
+
return { token, expiresAt: now + ttlMs };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** The entry a token opens, while it has not expired. */
|
|
37
|
+
async verify(token: string): Promise<{ resource: string; recordId: string; expiresAt: number } | null> {
|
|
38
|
+
if (typeof token !== 'string' || !TOKEN.test(token)) return null;
|
|
39
|
+
const result = await this.#db.read([{ rql: 'SELECT resource, record_id, expires_at FROM cms_preview_tokens WHERE id = $id', params: { $id: await sha256Hex(token) } }]);
|
|
40
|
+
const row = result.results[0]!.rows[0];
|
|
41
|
+
if (!row || Number(row[2] as bigint) <= this.#now()) return null;
|
|
42
|
+
return { resource: row[0] as string, recordId: row[1] as string, expiresAt: Number(row[2] as bigint) };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Links of an entry that have not expired. */
|
|
46
|
+
async count(resource: string, recordId: string): Promise<number> {
|
|
47
|
+
const result = await this.#db.read([{ rql: 'SELECT count(*) FROM cms_preview_tokens WHERE resource = $resource AND record_id = $record AND expires_at > $now',
|
|
48
|
+
params: { $resource: resource, $record: recordId, $now: this.#now() } }]);
|
|
49
|
+
return Number(result.results[0]!.rows[0]![0] as bigint);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Revoke every link of an entry. */
|
|
53
|
+
async revoke(resource: string, recordId: string): Promise<void> {
|
|
54
|
+
await this.#db.write([{ rql: 'DELETE FROM cms_preview_tokens WHERE resource = $resource AND record_id = $record', params: { $resource: resource, $record: recordId } }], WRITE);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async purgeExpired(): Promise<void> {
|
|
58
|
+
const expired = await this.#db.read([{ rql: 'SELECT 1 FROM cms_preview_tokens WHERE expires_at <= $now LIMIT 1', params: { $now: this.#now() } }]);
|
|
59
|
+
if (!expired.results[0]!.rows.length) return;
|
|
60
|
+
await this.#db.write([{ rql: 'DELETE FROM cms_preview_tokens WHERE id IN (SELECT id FROM cms_preview_tokens WHERE expires_at <= $now LIMIT 500)', params: { $now: this.#now() } }], WRITE);
|
|
61
|
+
}
|
|
62
|
+
}
|