@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,881 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The entry's room: one live instance per entry (`transport: 'durable-object'`), shared by
|
|
3
|
+
* every editor of it, on Workers as a Durable Object and on Node in the process. The room is
|
|
4
|
+
* the authority of the shared draft: it holds the entry's values, applies every change in the
|
|
5
|
+
* order it receives them (the action queue), broadcasts each one, and keeps the draft in
|
|
6
|
+
* `cms_drafts` between saves. See `collab.ts` in the CMS package for the convergence rules.
|
|
7
|
+
*
|
|
8
|
+
* - Scalars: `set` replaces a field's value; editors apply the pending-key rule.
|
|
9
|
+
* - Blocks: `tree` applies one op by block ID and answers with the tree's hash; `blocks`
|
|
10
|
+
* returns a field's tree to an editor whose hash differs.
|
|
11
|
+
* - Rich text: `steps` is the `prosemirror-collab` authority of one document, applying a batch
|
|
12
|
+
* to the shared schema and logging it; `richText` returns a document to start over from.
|
|
13
|
+
* - Presence: `presence` carries a tab's focus, selection and drag; `participants` groups the
|
|
14
|
+
* peers by user for the header; the draft row names who is editing, for the entries list.
|
|
15
|
+
*
|
|
16
|
+
* Saving stays the editor page's HTTP action; `saved` tells the room, which reads the record
|
|
17
|
+
* again and refreshes everyone. A record changed outside the room sets `diverged`.
|
|
18
|
+
*/
|
|
19
|
+
import { Client, Component, Cossack, OnEvent, OnWindow, Server, State, defineServerMiddleware } from '@cossackframework/core';
|
|
20
|
+
import { html, type TemplateResult } from '@cossackframework/renderer';
|
|
21
|
+
import type { Context, MiddlewareHandler } from 'hono';
|
|
22
|
+
import { Node as ProseMirrorNode } from '@tiptap/pm/model';
|
|
23
|
+
import { Step } from '@tiptap/pm/transform';
|
|
24
|
+
import {
|
|
25
|
+
applyTreeOp, checkNoteAction, checkPresence, CmsError, expiredPeers, findBlock, groupPeers, hasPermission, htmlBlocksChanged, isCmsError, livePeers, parseRichTextPath, participantColor, PERMISSIONS, richTextProblem, stableJson, StepLog, systemPrincipal, treeHash, updateBlock,
|
|
26
|
+
type Block, type Note, type NoteAction, type NoteRange, type Participant, type PeerPresence, type PeerState, type Principal, type RichTextDoc, type TreeOp,
|
|
27
|
+
} from '@cossackframework/cms';
|
|
28
|
+
import type { CmsHost } from '@cossackframework/cms/server';
|
|
29
|
+
import { editorView, entryValues, routeResource } from '../content';
|
|
30
|
+
import type { EditorValues, EditorView } from '../editor';
|
|
31
|
+
import { collabEditors } from '../rich-text-field';
|
|
32
|
+
import type { CollabTransport, StepsResult } from '../rich-text.client';
|
|
33
|
+
import { richTextSchema } from '../rich-text-schema';
|
|
34
|
+
import { mailOrigin } from '../seo';
|
|
35
|
+
import { avatarStack, type Someone } from './presence';
|
|
36
|
+
|
|
37
|
+
const PEER = /^[A-Za-z0-9_-]{8,64}$/;
|
|
38
|
+
/** Peer IDs one user may hold in a room at once (a tab each), and in all. */
|
|
39
|
+
const PEERS_PER_USER = 50;
|
|
40
|
+
const PEER_OWNERS_MAX = 10_000;
|
|
41
|
+
/** How long a silent peer ID stays its owner's before another user's claim may free it, when the room is full of IDs. */
|
|
42
|
+
const PEER_GRACE = 24 * 60 * 60 * 1000;
|
|
43
|
+
/** A scalar value or a block op, as JSON, at most. */
|
|
44
|
+
const VALUE_MAX = 64 * 1024;
|
|
45
|
+
/** Steps in one batch, at most; a paste is one step. */
|
|
46
|
+
const STEPS_MAX = 500;
|
|
47
|
+
/** The draft is written this long after the last change, and at least this often while changes keep coming. */
|
|
48
|
+
const PERSIST_IDLE = 1000;
|
|
49
|
+
const PERSIST_MAX = 5000;
|
|
50
|
+
/** How often a room with people in it says so in the draft row, and prunes peers that fell silent. */
|
|
51
|
+
const EDITORS_EVERY = 30_000;
|
|
52
|
+
/** Editors send their presence at least this often, so the room's timeout never fires on an idle tab. */
|
|
53
|
+
const HEARTBEAT = 15_000;
|
|
54
|
+
/**
|
|
55
|
+
* Editors' access by user and entry: a guard runs for every frame to every peer. `checked` is
|
|
56
|
+
* when the database last answered yes; `until` is when to ask again.
|
|
57
|
+
*/
|
|
58
|
+
const RECENT_ACCESS = new Map<string, { checked: number; until: number }>();
|
|
59
|
+
const ACCESS_TTL = 5000;
|
|
60
|
+
/** While the database cannot answer, an earlier yes holds this long after it was given, then the editor is refused. */
|
|
61
|
+
export const ACCESS_GRACE = 3 * ACCESS_TTL;
|
|
62
|
+
/** While the database cannot answer, frames ask again at most this often. */
|
|
63
|
+
export const ACCESS_BACKOFF = 1000;
|
|
64
|
+
|
|
65
|
+
/** Forget every kept access decision (tests). */
|
|
66
|
+
export function clearRoomAccess(): void { RECENT_ACCESS.clear(); }
|
|
67
|
+
|
|
68
|
+
const forbidden = (c: Context) => c.json({ error: 'Forbidden', code: 'COSSACK_RPC_FORBIDDEN' }, 403);
|
|
69
|
+
|
|
70
|
+
/** The room's key: one instance per entry of a site. Fails closed without an entry. */
|
|
71
|
+
export function entryScope(c: Context): string {
|
|
72
|
+
const collection = c.req.param('collection');
|
|
73
|
+
const id = c.req.param('id');
|
|
74
|
+
const site = (c.get('site') as { id?: string } | undefined)?.id ?? 'main';
|
|
75
|
+
if (!collection || !id || id === 'new') throw Object.assign(new Error('An entry room needs a saved entry.'), { authorizationCode: 'COSSACK_AUTH_FORBIDDEN' });
|
|
76
|
+
return `site:${site}:${collection}:${id}`;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** A dashboard user who may edit the entry; the check is kept for a few seconds, since it runs again for every frame. */
|
|
80
|
+
export const requireEntryEditor: MiddlewareHandler = defineServerMiddleware(async (c, next) => {
|
|
81
|
+
const cms = c.get('cms') as CmsHost | undefined;
|
|
82
|
+
const principal = c.get('principal') as Principal | undefined;
|
|
83
|
+
const route = c.req.param('collection');
|
|
84
|
+
const id = c.req.param('id');
|
|
85
|
+
if (!cms || !principal || principal.kind !== 'user' || !route || !id || id === 'new') return forbidden(c);
|
|
86
|
+
const key = `${principal.id}:${(c.get('site') as { id?: string } | undefined)?.id ?? 'main'}:${route}:${id}`;
|
|
87
|
+
const now = Date.now();
|
|
88
|
+
const previous = RECENT_ACCESS.get(key);
|
|
89
|
+
if (!previous || previous.until <= now) {
|
|
90
|
+
let allowed = false;
|
|
91
|
+
try {
|
|
92
|
+
const { resource } = routeResource(cms, route);
|
|
93
|
+
const repository = cms.resource(resource.id);
|
|
94
|
+
const record = await repository.get(id, { principal });
|
|
95
|
+
allowed = record !== null && repository.canUpdate(record, principal);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
// Only a passing database error keeps an earlier yes, and only for a while: a lost
|
|
98
|
+
// entry, collection or right, an inactive plugin or a pending migration refuses.
|
|
99
|
+
const passing = !isCmsError(error) || ((error.code === 'CMS_UNAVAILABLE' || error.code === 'CMS_UNCERTAIN') && !error.lasting);
|
|
100
|
+
if (!passing || !previous || now - previous.checked > ACCESS_GRACE) { RECENT_ACCESS.delete(key); return forbidden(c); }
|
|
101
|
+
console.warn('[cms] the room could not check access again; it keeps the last answer for now', error);
|
|
102
|
+
RECENT_ACCESS.set(key, { checked: previous.checked, until: now + ACCESS_BACKOFF });
|
|
103
|
+
await next();
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (!allowed) { RECENT_ACCESS.delete(key); return forbidden(c); }
|
|
107
|
+
if (RECENT_ACCESS.size >= 1000) for (const [entry, kept] of RECENT_ACCESS) if (now - kept.checked > ACCESS_GRACE) RECENT_ACCESS.delete(entry);
|
|
108
|
+
RECENT_ACCESS.set(key, { checked: now, until: now + ACCESS_TTL });
|
|
109
|
+
}
|
|
110
|
+
await next();
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
/** What `join` answers: the room's draft as it stands. */
|
|
114
|
+
export interface RoomSnapshot {
|
|
115
|
+
values: EditorValues;
|
|
116
|
+
/** Rich text versions by document path. */
|
|
117
|
+
versions: Record<string, number>;
|
|
118
|
+
/** Tree hashes by blocks field. */
|
|
119
|
+
hashes: Record<string, string>;
|
|
120
|
+
rev: number;
|
|
121
|
+
peers: PeerState[];
|
|
122
|
+
/** The entry's notes, roots and replies, oldest first. */
|
|
123
|
+
notes: Note[];
|
|
124
|
+
/** The people the notes name, by user ID: their authors, and everyone who joined. */
|
|
125
|
+
people: Record<string, Someone>;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** What the room tells every tab about a note. */
|
|
129
|
+
export type NoteChange =
|
|
130
|
+
| { kind: 'created'; note: Note; author: Someone }
|
|
131
|
+
| { kind: 'edited'; note: Note }
|
|
132
|
+
| { kind: 'status'; note: Note }
|
|
133
|
+
| { kind: 'removed'; ids: string[] }
|
|
134
|
+
| { kind: 'moved'; moves: { id: string; range: NoteRange }[] };
|
|
135
|
+
|
|
136
|
+
/** What the editor page does with the room, in the browser. */
|
|
137
|
+
export interface RoomHandle {
|
|
138
|
+
/** This browser tab's ID in the room. */
|
|
139
|
+
readonly peer: string;
|
|
140
|
+
set(field: string, value: unknown): Promise<{ applied: boolean }>;
|
|
141
|
+
tree(op: TreeOp): Promise<{ applied: boolean; hash: string }>;
|
|
142
|
+
blocks(field: string): Promise<{ blocks: Block[]; hash: string }>;
|
|
143
|
+
/** The room as one rich text document's authority, for its editor. */
|
|
144
|
+
transport(path: string): CollabTransport;
|
|
145
|
+
/** The room's draft as it stands, before a save. */
|
|
146
|
+
fresh(): Promise<RoomSnapshot>;
|
|
147
|
+
/** Where this tab is now; sent at once, merged into what was sent before. */
|
|
148
|
+
presence(state: PeerPresence): void;
|
|
149
|
+
/** The page saved the entry: the room reads it again and refreshes everyone. */
|
|
150
|
+
saved(): Promise<void>;
|
|
151
|
+
/** Start the draft over from the record, after a change outside the room. */
|
|
152
|
+
reload(): Promise<void>;
|
|
153
|
+
/** Leave, change, resolve or remove a note; everyone hears of it. Answers the note made or changed. */
|
|
154
|
+
note(action: NoteAction): Promise<Note | null>;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export type EntryRoomProps = {
|
|
158
|
+
/** The room is ready to be talked to. */
|
|
159
|
+
onReady(handle: RoomHandle): void;
|
|
160
|
+
/** The room's draft, on joining and after a save or a reload: replace the values; `resets` names rich text documents to load again. */
|
|
161
|
+
onSnapshot(snapshot: RoomSnapshot, options: { initial: boolean; resets: readonly string[] }): void;
|
|
162
|
+
onSet(peer: string, field: string, value: unknown): void;
|
|
163
|
+
onTree(peer: string, op: TreeOp, hash: string): void;
|
|
164
|
+
/** The peers in the room, this tab included. */
|
|
165
|
+
onPeers(peers: readonly PeerState[], self: string): void;
|
|
166
|
+
onSaved(by: string, rev: number): void;
|
|
167
|
+
/** A note was made, changed, resolved, removed or moved, by anyone in the room, this tab included. */
|
|
168
|
+
onNote(change: NoteChange): void;
|
|
169
|
+
/** Connection and draft state for the page's indicators. */
|
|
170
|
+
onStatus(status: { connected: boolean; dirty: boolean; diverged: boolean; oversized: boolean }): void;
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
type ServerBlocksResult = { blocks: Block[]; hash: string };
|
|
174
|
+
|
|
175
|
+
@Component({ transport: 'durable-object', scope: entryScope, middlewares: [requireEntryEditor] })
|
|
176
|
+
export class EntryRoom extends Cossack {
|
|
177
|
+
declare props: EntryRoomProps;
|
|
178
|
+
/** The record's revision as the room last saw it saved. */
|
|
179
|
+
@State() rev = 0;
|
|
180
|
+
@State() dirty = false;
|
|
181
|
+
/** The record changed outside the room since the draft started. */
|
|
182
|
+
@State() diverged = false;
|
|
183
|
+
/** The draft outgrew what a RomeDB request carries: it lives in memory alone until it is saved. */
|
|
184
|
+
@State() oversized = false;
|
|
185
|
+
@State() participants: Participant[] = [];
|
|
186
|
+
|
|
187
|
+
// --- Server: the shared draft ------------------------------------------------------------
|
|
188
|
+
private cmsHost: CmsHost | undefined;
|
|
189
|
+
private view: EditorView | undefined;
|
|
190
|
+
private resourceId = '';
|
|
191
|
+
private entryId = '';
|
|
192
|
+
private values: EditorValues = {};
|
|
193
|
+
private scalarFields = new Set<string>();
|
|
194
|
+
private blockFields = new Set<string>();
|
|
195
|
+
private richFields = new Set<string>();
|
|
196
|
+
/** Fields with an `access` rule of their own, kept out of the room. */
|
|
197
|
+
private restricted = new Set<string>();
|
|
198
|
+
/** Rich text keys by block type. */
|
|
199
|
+
private richKeys = new Map<string, Set<string>>();
|
|
200
|
+
private docs = new Map<string, ProseMirrorNode>();
|
|
201
|
+
private logs = new Map<string, StepLog>();
|
|
202
|
+
private roomPeers = new Map<string, PeerState>();
|
|
203
|
+
/**
|
|
204
|
+
* Who each peer ID belongs to: the first user to use it. Tabs learn every peer's ID from the
|
|
205
|
+
* presence broadcasts, so a call naming a peer of another user is refused.
|
|
206
|
+
*/
|
|
207
|
+
private peerOwners = new Map<string, string>();
|
|
208
|
+
/** How many peer IDs each user holds in `peerOwners`. */
|
|
209
|
+
private ownedPeers = new Map<string, number>();
|
|
210
|
+
/** When each owned peer ID was last used by its owner. */
|
|
211
|
+
private peerSeen = new Map<string, number>();
|
|
212
|
+
/** The entry's notes as the room holds them, the authority while it lives; `cms.notes` keeps them. */
|
|
213
|
+
private notes: Note[] = [];
|
|
214
|
+
/** Who the notes and the peers name, so tabs show names without looking anyone up. */
|
|
215
|
+
private people = new Map<string, Someone>();
|
|
216
|
+
private baseRev = 0;
|
|
217
|
+
private entryLoading: Promise<void> | undefined;
|
|
218
|
+
private persistTimer: ReturnType<typeof setTimeout> | undefined;
|
|
219
|
+
private persistSince = 0;
|
|
220
|
+
private editorsTimer: ReturnType<typeof setInterval> | undefined;
|
|
221
|
+
|
|
222
|
+
/** The request's CMS and principal; the guard made sure of both. */
|
|
223
|
+
private contextOf(): { cms: CmsHost; principal: Principal & { kind: 'user' } } {
|
|
224
|
+
const cms = this.c.get('cms') as CmsHost;
|
|
225
|
+
const principal = this.c.get('principal') as Principal;
|
|
226
|
+
if (!cms || principal?.kind !== 'user') throw new Error('The room needs a signed-in editor.');
|
|
227
|
+
return { cms, principal };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Load the entry once: its draft when one is newer than the record, else the record itself. */
|
|
231
|
+
private load(cms: CmsHost): Promise<void> {
|
|
232
|
+
return this.entryLoading ??= (async () => {
|
|
233
|
+
const route = this.c.req.param('collection') ?? '';
|
|
234
|
+
const id = this.c.req.param('id') ?? '';
|
|
235
|
+
const view = await editorView(cms, route);
|
|
236
|
+
const { resource } = routeResource(cms, route);
|
|
237
|
+
const record = await cms.resource(resource.id).get(id, { principal: systemPrincipal('collab') });
|
|
238
|
+
if (!record) throw new Error('The entry does not exist.');
|
|
239
|
+
this.cmsHost = cms;
|
|
240
|
+
this.view = view;
|
|
241
|
+
this.resourceId = resource.id;
|
|
242
|
+
this.entryId = id;
|
|
243
|
+
// Fields with their own read or write rule are not shared: each editor reads and saves them as the repository lets them.
|
|
244
|
+
this.restricted = new Set(view.restricted);
|
|
245
|
+
// A multiple rich text field is a list of documents: it travels as one value, like a scalar.
|
|
246
|
+
for (const field of view.fields) {
|
|
247
|
+
if (this.restricted.has(field.name)) continue;
|
|
248
|
+
if (field.kind === 'blocks') this.blockFields.add(field.name);
|
|
249
|
+
else if (field.kind === 'richtext' && !field.multiple) this.richFields.add(field.name);
|
|
250
|
+
}
|
|
251
|
+
for (const option of view.blocks) {
|
|
252
|
+
const keys = option.fields.filter(field => field.kind === 'richtext').map(field => field.name);
|
|
253
|
+
if (keys.length) this.richKeys.set(option.name, new Set(keys));
|
|
254
|
+
}
|
|
255
|
+
const values = this.shared(await entryValues(cms, view, record));
|
|
256
|
+
for (const name of Object.keys(values)) if (!this.blockFields.has(name) && !this.richFields.has(name)) this.scalarFields.add(name);
|
|
257
|
+
this.rev = record.rev;
|
|
258
|
+
this.baseRev = record.rev;
|
|
259
|
+
const draft = await cms.drafts.get(resource.id, id).catch(() => null);
|
|
260
|
+
if (draft && draft.at > record.updatedAt && draft.baseRev === record.rev && Object.keys(draft.values).length) {
|
|
261
|
+
this.values = { ...values, ...this.shared(draft.values) };
|
|
262
|
+
for (const [path, version] of Object.entries(draft.versions)) if (Number.isSafeInteger(version) && version >= 0) this.logs.set(path, new StepLog(version));
|
|
263
|
+
this.dirty = true;
|
|
264
|
+
} else this.values = values;
|
|
265
|
+
this.notes = await cms.notes.forEntry(resource.id, id).catch(() => []);
|
|
266
|
+
await this.know(cms, this.notes.map(note => note.userId));
|
|
267
|
+
})().catch(error => { this.entryLoading = undefined; throw error; });
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** The values without the restricted fields, which never enter the room's draft, snapshots or broadcasts. */
|
|
271
|
+
private shared(values: EditorValues): EditorValues {
|
|
272
|
+
return Object.fromEntries(Object.entries(values).filter(([name]) => !this.restricted.has(name)));
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Make sure the people are known by name and picture, looking up those who are not yet. */
|
|
276
|
+
private async know(cms: CmsHost, userIds: readonly string[]): Promise<void> {
|
|
277
|
+
const missing = [...new Set(userIds)].filter(id => !this.people.has(id));
|
|
278
|
+
if (!missing.length) return;
|
|
279
|
+
const users = await cms.users.getMany(missing).catch(() => new Map());
|
|
280
|
+
for (const id of missing) {
|
|
281
|
+
const user = users.get(id);
|
|
282
|
+
this.people.set(id, { user: id, name: user?.name || user?.email || id, avatar: user?.avatar ?? null, color: participantColor(id) });
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
private richTextAt(path: string): { field: string; block?: { id: string; key: string } } | null {
|
|
287
|
+
const parsed = parseRichTextPath(path);
|
|
288
|
+
if (!parsed) return null;
|
|
289
|
+
if (parsed.block) {
|
|
290
|
+
if (!this.blockFields.has(parsed.field)) return null;
|
|
291
|
+
const block = findBlock((this.values[parsed.field] as Block[] | undefined) ?? [], parsed.block.id);
|
|
292
|
+
if (!block || !this.richKeys.get(block.type)?.has(parsed.block.key)) return null;
|
|
293
|
+
return parsed;
|
|
294
|
+
}
|
|
295
|
+
return this.richFields.has(parsed.field) ? parsed : null;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
private docJson(path: { field: string; block?: { id: string; key: string } }, values: EditorValues = this.values): RichTextDoc | null {
|
|
299
|
+
const value = path.block
|
|
300
|
+
? findBlock((values[path.field] as Block[] | undefined) ?? [], path.block.id)?.data[path.block.key]
|
|
301
|
+
: values[path.field];
|
|
302
|
+
return value && typeof value === 'object' && (value as RichTextDoc).type === 'doc' ? value as RichTextDoc : null;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
private docAt(path: string, at: { field: string; block?: { id: string; key: string } }): ProseMirrorNode {
|
|
306
|
+
let doc = this.docs.get(path);
|
|
307
|
+
if (!doc) {
|
|
308
|
+
const json = this.docJson(at);
|
|
309
|
+
doc = json && json.content.length ? ProseMirrorNode.fromJSON(richTextSchema(), json) : richTextSchema().topNodeType.createAndFill()!;
|
|
310
|
+
this.docs.set(path, doc);
|
|
311
|
+
}
|
|
312
|
+
return doc;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
private logAt(path: string): StepLog {
|
|
316
|
+
let log = this.logs.get(path);
|
|
317
|
+
if (!log) { log = new StepLog(); this.logs.set(path, log); }
|
|
318
|
+
return log;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
private writeDoc(at: { field: string; block?: { id: string; key: string } }, doc: RichTextDoc): void {
|
|
322
|
+
if (at.block) {
|
|
323
|
+
const { id, key } = at.block;
|
|
324
|
+
this.values = { ...this.values, [at.field]: updateBlock((this.values[at.field] as Block[] | undefined) ?? [], id, block => ({ ...block, data: { ...block.data, [key]: doc } })) };
|
|
325
|
+
} else this.values = { ...this.values, [at.field]: doc };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
private versions(): Record<string, number> {
|
|
329
|
+
return Object.fromEntries([...this.logs].map(([path, log]) => [path, log.version]));
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
private hashes(): Record<string, string> {
|
|
333
|
+
return Object.fromEntries([...this.blockFields].map(field => [field, treeHash((this.values[field] as Block[] | undefined) ?? [])]));
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
private snapshot(): RoomSnapshot {
|
|
337
|
+
return { values: this.values, versions: this.versions(), hashes: this.hashes(), rev: this.rev, peers: [...this.roomPeers.values()], notes: this.notes, people: Object.fromEntries(this.people) };
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** A change happened: the draft is dirty and gets written soon. */
|
|
341
|
+
private changed(): void {
|
|
342
|
+
this.dirty = true;
|
|
343
|
+
const now = Date.now();
|
|
344
|
+
if (!this.persistSince) this.persistSince = now;
|
|
345
|
+
if (this.persistTimer) clearTimeout(this.persistTimer);
|
|
346
|
+
const wait = Math.max(0, Math.min(PERSIST_IDLE, this.persistSince + PERSIST_MAX - now));
|
|
347
|
+
this.persistTimer = setTimeout(() => { void this.persist(); }, wait);
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
private async persist(): Promise<void> {
|
|
351
|
+
this.persistTimer = undefined;
|
|
352
|
+
this.persistSince = 0;
|
|
353
|
+
const cms = this.cmsHost;
|
|
354
|
+
if (!cms) return;
|
|
355
|
+
try {
|
|
356
|
+
await cms.drafts.save(this.resourceId, this.entryId, { baseRev: this.baseRev, values: this.values, versions: this.versions(), editors: this.editors() });
|
|
357
|
+
if (this.oversized) this.oversized = false;
|
|
358
|
+
} catch (error) {
|
|
359
|
+
if ((error as { code?: string }).code === 'CMS_LIMIT') { if (!this.oversized) this.oversized = true; }
|
|
360
|
+
else console.error('[cms] the shared draft could not be written', error);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
private editors(): string[] {
|
|
365
|
+
return [...new Set(livePeers(this.roomPeers.values(), Date.now()).map(peer => peer.user))];
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** Peers that fell silent leave, and every tab hears it; the participants follow; the draft row names who is here. */
|
|
369
|
+
private presenceChanged(): void {
|
|
370
|
+
for (const id of expiredPeers(this.roomPeers.values(), Date.now())) {
|
|
371
|
+
this.roomPeers.delete(id);
|
|
372
|
+
// The ID stays its owner's: an idle tab that wakes up takes its place again, and
|
|
373
|
+
// nobody else who heard the ID in presence can claim it meanwhile.
|
|
374
|
+
this.broadcastEvent('left', id);
|
|
375
|
+
}
|
|
376
|
+
const participants = groupPeers(this.roomPeers.values());
|
|
377
|
+
if (stableJson(participants) !== stableJson(this.participants)) this.participants = participants;
|
|
378
|
+
if (this.roomPeers.size && !this.editorsTimer) this.editorsTimer = setInterval(() => { this.presenceChanged(); void this.reportEditors(); }, EDITORS_EVERY);
|
|
379
|
+
if (!this.roomPeers.size && this.editorsTimer) { clearInterval(this.editorsTimer); this.editorsTimer = undefined; }
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
private async reportEditors(): Promise<void> {
|
|
383
|
+
const cms = this.cmsHost;
|
|
384
|
+
if (!cms) return;
|
|
385
|
+
await cms.drafts.editing(this.resourceId, this.entryId, this.editors()).catch(() => undefined);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** The record's revision moved without the room: someone wrote it elsewhere. */
|
|
389
|
+
private async checkDivergence(cms: CmsHost): Promise<void> {
|
|
390
|
+
const record = await cms.resource(this.resourceId).get(this.entryId, { principal: systemPrincipal('collab') }).catch(() => null);
|
|
391
|
+
const diverged = !record || record.rev !== this.baseRev;
|
|
392
|
+
if (diverged !== this.diverged) this.diverged = diverged;
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Start the draft over from the record: values, rich text logs at new versions, nothing pending. */
|
|
396
|
+
private async restart(cms: CmsHost, resets: string[]): Promise<RoomSnapshot> {
|
|
397
|
+
const record = await cms.resource(this.resourceId).get(this.entryId, { principal: systemPrincipal('collab') });
|
|
398
|
+
if (!record) throw new Error('The entry does not exist.');
|
|
399
|
+
const values = this.shared(await entryValues(cms, this.view!, record));
|
|
400
|
+
// A document the record holds differently from the room restarts its log, so editors load it again.
|
|
401
|
+
for (const [path, log] of this.logs) {
|
|
402
|
+
const at = parseRichTextPath(path);
|
|
403
|
+
if (!at || stableJson(this.docJson(at)) !== stableJson(this.docJson(at, values)) || resets.includes(path)) {
|
|
404
|
+
this.logs.set(path, new StepLog(log.version + 1000));
|
|
405
|
+
this.docs.delete(path);
|
|
406
|
+
if (!resets.includes(path)) resets.push(path);
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
this.values = values;
|
|
410
|
+
this.rev = record.rev;
|
|
411
|
+
this.baseRev = record.rev;
|
|
412
|
+
this.dirty = false;
|
|
413
|
+
this.diverged = false;
|
|
414
|
+
await this.persist();
|
|
415
|
+
return this.snapshot();
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** The peer ID when it is well formed and belongs to the caller (claimed on first use), else null. */
|
|
419
|
+
private ownPeer(peer: unknown, principal: Principal & { kind: 'user' }): string | null {
|
|
420
|
+
if (typeof peer !== 'string' || !PEER.test(peer)) return null;
|
|
421
|
+
const owner = this.peerOwners.get(peer);
|
|
422
|
+
if (owner !== undefined) {
|
|
423
|
+
if (owner !== principal.id) return null;
|
|
424
|
+
this.peerSeen.set(peer, Date.now());
|
|
425
|
+
return peer;
|
|
426
|
+
}
|
|
427
|
+
// A user claims a few IDs (one per tab); claims past that first give up the user's own
|
|
428
|
+
// silent ones. A peer still in the room is never given up, so its ID cannot be taken over.
|
|
429
|
+
if ((this.ownedPeers.get(principal.id) ?? 0) >= PEERS_PER_USER && !this.releaseSilent(owned => owned === principal.id)) return null;
|
|
430
|
+
if (this.peerOwners.size >= PEER_OWNERS_MAX && !this.releaseSilent(() => true, Date.now() - PEER_GRACE)) return null;
|
|
431
|
+
this.peerOwners.set(peer, principal.id);
|
|
432
|
+
this.peerSeen.set(peer, Date.now());
|
|
433
|
+
this.ownedPeers.set(principal.id, (this.ownedPeers.get(principal.id) ?? 0) + 1);
|
|
434
|
+
return peer;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Give up the oldest claimed ID whose peer is not in the room, whose owner matches and, with
|
|
439
|
+
* `silentSince`, that was last used before then; false when there is none.
|
|
440
|
+
*/
|
|
441
|
+
private releaseSilent(matches: (owner: string) => boolean, silentSince = Infinity): boolean {
|
|
442
|
+
for (const [id, owner] of this.peerOwners) {
|
|
443
|
+
if (this.roomPeers.has(id) || !matches(owner) || (this.peerSeen.get(id) ?? 0) >= silentSince) continue;
|
|
444
|
+
this.releasePeer(id);
|
|
445
|
+
return true;
|
|
446
|
+
}
|
|
447
|
+
return false;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** A peer left: its ID is free again. */
|
|
451
|
+
private releasePeer(id: string): void {
|
|
452
|
+
const owner = this.peerOwners.get(id);
|
|
453
|
+
if (owner === undefined) return;
|
|
454
|
+
this.peerOwners.delete(id);
|
|
455
|
+
this.peerSeen.delete(id);
|
|
456
|
+
const count = (this.ownedPeers.get(owner) ?? 1) - 1;
|
|
457
|
+
if (count > 0) this.ownedPeers.set(owner, count); else this.ownedPeers.delete(owner);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** A tab's state as the room keeps it: the user's name and picture, looked up when the tab arrives. */
|
|
461
|
+
private async peerState(cms: CmsHost, peer: string, userId: string, presence: unknown): Promise<PeerState> {
|
|
462
|
+
const user = await cms.users.get(userId).catch(() => null);
|
|
463
|
+
const state: PeerState = { peer, user: userId, name: user?.name || user?.email || userId, avatar: user?.avatar ?? null, color: participantColor(userId), at: Date.now(), presence: checkPresence(presence) };
|
|
464
|
+
this.people.set(userId, { user: userId, name: state.name, avatar: state.avatar, color: state.color });
|
|
465
|
+
return state;
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
@Server()
|
|
469
|
+
async join(peer: unknown, presence: unknown): Promise<RoomSnapshot> {
|
|
470
|
+
const { cms, principal } = this.contextOf();
|
|
471
|
+
await this.load(cms);
|
|
472
|
+
if (!this.ownPeer(peer, principal)) throw new Error('Invalid peer.');
|
|
473
|
+
const state = await this.peerState(cms, peer as string, principal.id, presence);
|
|
474
|
+
// Notes written outside the room (the API) show to whoever joins next.
|
|
475
|
+
this.notes = await cms.notes.forEntry(this.resourceId, this.entryId).catch(() => this.notes);
|
|
476
|
+
await this.know(cms, this.notes.map(note => note.userId));
|
|
477
|
+
this.roomPeers.set(peer as string, state);
|
|
478
|
+
this.presenceChanged();
|
|
479
|
+
this.broadcastEvent('presence', state);
|
|
480
|
+
void this.reportEditors();
|
|
481
|
+
await this.checkDivergence(cms);
|
|
482
|
+
return this.snapshot();
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Whether the change adds or alters a Custom HTML block the editor may not post. The room's
|
|
487
|
+
* draft is saved by whoever presses Save, so the check is made here, per editor.
|
|
488
|
+
*/
|
|
489
|
+
private htmlRefused(principal: Principal, next: unknown, previous: unknown): boolean {
|
|
490
|
+
return !hasPermission(principal, PERMISSIONS.unfilteredHtml) && htmlBlocksChanged(next, previous);
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
@Server()
|
|
494
|
+
async set(peer: unknown, field: unknown, value: unknown): Promise<{ applied: boolean }> {
|
|
495
|
+
const { cms, principal } = this.contextOf();
|
|
496
|
+
await this.load(cms);
|
|
497
|
+
if (!this.ownPeer(peer, principal) || typeof field !== 'string' || !this.scalarFields.has(field) || stableJson(value).length > VALUE_MAX) return { applied: false };
|
|
498
|
+
if (this.htmlRefused(principal, value, this.values[field])) return { applied: false };
|
|
499
|
+
this.values = { ...this.values, [field]: value };
|
|
500
|
+
this.changed();
|
|
501
|
+
this.broadcastEvent('set', peer, field, value);
|
|
502
|
+
return { applied: true };
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
@Server()
|
|
506
|
+
async tree(peer: unknown, op: unknown): Promise<{ applied: boolean; hash: string }> {
|
|
507
|
+
const { cms, principal } = this.contextOf();
|
|
508
|
+
await this.load(cms);
|
|
509
|
+
const checked = this.ownPeer(peer, principal) ? this.checkOp(op) : null;
|
|
510
|
+
const field = checked?.field ?? '';
|
|
511
|
+
const current = (this.values[field] as Block[] | undefined) ?? [];
|
|
512
|
+
if (!checked) return { applied: false, hash: treeHash(current) };
|
|
513
|
+
const next = applyTreeOp(current, checked);
|
|
514
|
+
if (!next || this.htmlRefused(principal, next, current)) return { applied: false, hash: treeHash(current) };
|
|
515
|
+
this.values = { ...this.values, [field]: next };
|
|
516
|
+
for (const path of this.docs.keys()) if (path.startsWith(`${field}:`) && !this.richTextAt(path)) { this.docs.delete(path); this.logs.delete(path); }
|
|
517
|
+
this.changed();
|
|
518
|
+
const hash = treeHash(next);
|
|
519
|
+
this.broadcastEvent('tree', peer, checked, hash);
|
|
520
|
+
return { applied: true, hash };
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/** A tree op from client input: known kinds, a blocks field, bounded size, and no patch of a rich text key (its steps own it). */
|
|
524
|
+
private checkOp(value: unknown): TreeOp | null {
|
|
525
|
+
if (!value || typeof value !== 'object' || stableJson(value).length > VALUE_MAX) return null;
|
|
526
|
+
const op = value as Record<string, unknown>;
|
|
527
|
+
if (typeof op.field !== 'string' || !this.blockFields.has(op.field)) return null;
|
|
528
|
+
const id = typeof op.id === 'string' && /^[A-Za-z0-9_-]{1,40}$/.test(op.id) ? op.id : null;
|
|
529
|
+
const anchor = (entry: unknown): entry is string | null => entry === null || (typeof entry === 'string' && /^[A-Za-z0-9_-]{1,40}$/.test(entry));
|
|
530
|
+
switch (op.kind) {
|
|
531
|
+
case 'insert': return op.block && typeof op.block === 'object' && anchor(op.parent) && anchor(op.after) ? { kind: 'insert', field: op.field, block: op.block as Block, parent: op.parent, after: op.after } : null;
|
|
532
|
+
case 'move': return id && anchor(op.parent) && anchor(op.after) ? { kind: 'move', field: op.field, id, parent: op.parent, after: op.after } : null;
|
|
533
|
+
case 'remove': return id ? { kind: 'remove', field: op.field, id } : null;
|
|
534
|
+
case 'patch': {
|
|
535
|
+
if (!id || typeof op.path !== 'string') return null;
|
|
536
|
+
const block = findBlock((this.values[op.field] as Block[] | undefined) ?? [], id);
|
|
537
|
+
if (block && op.path.startsWith('data.') && this.richKeys.get(block.type)?.has(op.path.slice(5))) return null;
|
|
538
|
+
return { kind: 'patch', field: op.field, id, path: op.path, ...('value' in op ? { value: op.value } : {}) };
|
|
539
|
+
}
|
|
540
|
+
default: return null;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
@Server()
|
|
545
|
+
async blocks(field: unknown): Promise<ServerBlocksResult> {
|
|
546
|
+
const { cms } = this.contextOf();
|
|
547
|
+
await this.load(cms);
|
|
548
|
+
const blocks = typeof field === 'string' && this.blockFields.has(field) ? (this.values[field] as Block[] | undefined) ?? [] : [];
|
|
549
|
+
return { blocks, hash: treeHash(blocks) };
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
@Server()
|
|
553
|
+
async steps(peer: unknown, path: unknown, version: unknown, steps: unknown, clientID: unknown): Promise<StepsResult> {
|
|
554
|
+
const { cms, principal } = this.contextOf();
|
|
555
|
+
await this.load(cms);
|
|
556
|
+
const at = typeof path === 'string' ? this.richTextAt(path) : null;
|
|
557
|
+
if (!at || !this.ownPeer(peer, principal) || typeof clientID !== 'string' || clientID.length > 64 || !Number.isSafeInteger(version) || !Array.isArray(steps) || steps.length > STEPS_MAX) return { status: 'reload' };
|
|
558
|
+
const log = this.logAt(path as string);
|
|
559
|
+
if (!log.accepts(version as number)) {
|
|
560
|
+
const since = log.since(version as number);
|
|
561
|
+
return since ? { status: 'behind', ...since } : { status: 'reload' };
|
|
562
|
+
}
|
|
563
|
+
if (!steps.length) return { status: 'accepted', version: log.version };
|
|
564
|
+
let doc = this.docAt(path as string, at);
|
|
565
|
+
const before = doc;
|
|
566
|
+
try {
|
|
567
|
+
for (const json of steps) {
|
|
568
|
+
const result = Step.fromJSON(richTextSchema(), json).apply(doc);
|
|
569
|
+
if (result.failed || !result.doc) return { status: 'reload' };
|
|
570
|
+
doc = result.doc;
|
|
571
|
+
}
|
|
572
|
+
} catch { return { status: 'reload' }; }
|
|
573
|
+
// ProseMirror attribute objects have no prototype; the validator and the draft want plain JSON.
|
|
574
|
+
const json = JSON.parse(JSON.stringify(doc.toJSON())) as RichTextDoc;
|
|
575
|
+
const problem = richTextProblem(json);
|
|
576
|
+
if (problem || this.htmlRefused(principal, json, before.toJSON())) return { status: 'reload' };
|
|
577
|
+
this.docs.set(path as string, doc);
|
|
578
|
+
this.writeDoc(at, json);
|
|
579
|
+
const next = log.push(steps, clientID);
|
|
580
|
+
this.changed();
|
|
581
|
+
this.broadcastEvent('steps', path, steps, steps.map(() => clientID), next);
|
|
582
|
+
return { status: 'accepted', version: next };
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/** The draft as it stands, for a save: every editor's changes, this tab's included. */
|
|
586
|
+
@Server()
|
|
587
|
+
async draft(): Promise<RoomSnapshot> {
|
|
588
|
+
const { cms } = this.contextOf();
|
|
589
|
+
await this.load(cms);
|
|
590
|
+
return this.snapshot();
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
@Server()
|
|
594
|
+
async richText(path: unknown): Promise<{ doc: RichTextDoc | null; version: number }> {
|
|
595
|
+
const { cms, principal } = this.contextOf();
|
|
596
|
+
await this.load(cms);
|
|
597
|
+
const at = typeof path === 'string' ? this.richTextAt(path) : null;
|
|
598
|
+
if (!at) return { doc: null, version: 0 };
|
|
599
|
+
return { doc: JSON.parse(JSON.stringify(this.docAt(path as string, at).toJSON())) as RichTextDoc, version: this.logAt(path as string).version };
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
@Server()
|
|
603
|
+
async presence(peer: unknown, state: unknown): Promise<void> {
|
|
604
|
+
const { cms, principal } = this.contextOf();
|
|
605
|
+
await this.load(cms);
|
|
606
|
+
if (!this.ownPeer(peer, principal)) return;
|
|
607
|
+
const known = this.roomPeers.get(peer as string);
|
|
608
|
+
// A tab the room dropped as silent (throttled in the background, or the instance restarted) comes back under its user's name, not their ID.
|
|
609
|
+
const next: PeerState = known ? { ...known, at: Date.now(), presence: checkPresence(state) } : await this.peerState(cms, peer as string, principal.id, state);
|
|
610
|
+
this.roomPeers.set(peer as string, next);
|
|
611
|
+
this.presenceChanged();
|
|
612
|
+
this.broadcastEvent('presence', next);
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* A note from a tab: stored, applied to the room's threads and told to everyone. Anyone in the
|
|
617
|
+
* room (so, anyone who may edit the entry) leaves, resolves and reopens notes; authors change
|
|
618
|
+
* their own, and authors and user administrators remove them.
|
|
619
|
+
*/
|
|
620
|
+
@Server()
|
|
621
|
+
async note(peer: unknown, action: unknown): Promise<Note | null> {
|
|
622
|
+
const { cms, principal } = this.contextOf();
|
|
623
|
+
await this.load(cms);
|
|
624
|
+
if (!this.ownPeer(peer, principal)) throw new CmsError('CMS_VALIDATION', 'Invalid peer.');
|
|
625
|
+
const input = checkNoteAction(action);
|
|
626
|
+
const tell = (change: NoteChange) => this.broadcastEvent('note', change);
|
|
627
|
+
// Webhooks and emails follow from the outbox job the note's write queues; the tab is answered first.
|
|
628
|
+
const announcement = {
|
|
629
|
+
origin: mailOrigin(this.c), route: this.c.req.param('collection') ?? '', collection: this.resourceId.startsWith('cms/') ? this.resourceId.slice(4) : null,
|
|
630
|
+
title: String(this.values[this.view?.titleField ?? 'title'] ?? ''), author: this.people.get(principal.id)?.name ?? principal.id,
|
|
631
|
+
};
|
|
632
|
+
const current = (id: string) => {
|
|
633
|
+
const note = this.notes.find(entry => entry.id === id);
|
|
634
|
+
if (!note) throw new CmsError('CMS_NOT_FOUND', 'The note no longer exists.');
|
|
635
|
+
return note;
|
|
636
|
+
};
|
|
637
|
+
switch (input.kind) {
|
|
638
|
+
case 'create': {
|
|
639
|
+
const note = await cms.notes.create({ resource: this.resourceId, recordId: this.entryId, userId: principal.id, target: input.target, range: input.range ?? null, quote: input.quote ?? '', body: input.body, parentId: input.parentId ?? null }, { announce: announcement });
|
|
640
|
+
cms.outboxWritten();
|
|
641
|
+
await this.know(cms, [principal.id]);
|
|
642
|
+
this.notes = [...this.notes.map(entry => entry.id === note.parentId ? { ...entry, updatedAt: note.createdAt } : entry), note];
|
|
643
|
+
tell({ kind: 'created', note, author: this.people.get(principal.id)! });
|
|
644
|
+
return note;
|
|
645
|
+
}
|
|
646
|
+
case 'edit': {
|
|
647
|
+
if (current(input.id).userId !== principal.id) throw new CmsError('CMS_FORBIDDEN', 'Only its author changes a note.');
|
|
648
|
+
const note = await cms.notes.edit(input.id, input.body);
|
|
649
|
+
if (!note) throw new CmsError('CMS_NOT_FOUND', 'The note no longer exists.');
|
|
650
|
+
this.notes = this.notes.map(entry => entry.id === note.id ? note : entry.id === note.parentId ? { ...entry, updatedAt: note.updatedAt } : entry);
|
|
651
|
+
tell({ kind: 'edited', note });
|
|
652
|
+
return note;
|
|
653
|
+
}
|
|
654
|
+
case 'resolve':
|
|
655
|
+
case 'reopen': {
|
|
656
|
+
if (current(input.id).parentId) throw new CmsError('CMS_VALIDATION', 'Resolve the thread, not a reply.');
|
|
657
|
+
const note = await cms.notes.setStatus(input.id, input.kind === 'resolve' ? 'resolved' : 'open', principal.id, { announce: announcement });
|
|
658
|
+
if (!note) throw new CmsError('CMS_NOT_FOUND', 'The note no longer exists.');
|
|
659
|
+
this.notes = this.notes.map(entry => entry.id === note.id ? note : entry);
|
|
660
|
+
tell({ kind: 'status', note });
|
|
661
|
+
if (note.status === 'resolved') cms.outboxWritten();
|
|
662
|
+
return note;
|
|
663
|
+
}
|
|
664
|
+
case 'remove': {
|
|
665
|
+
const note = current(input.id);
|
|
666
|
+
if (note.userId !== principal.id && !hasPermission(principal, PERMISSIONS.manageUsers)) throw new CmsError('CMS_FORBIDDEN', 'Only its author or an administrator removes a note.');
|
|
667
|
+
await cms.notes.remove(note.id);
|
|
668
|
+
const ids = [note.id, ...this.notes.filter(entry => entry.parentId === note.id).map(entry => entry.id)];
|
|
669
|
+
this.notes = this.notes.filter(entry => !ids.includes(entry.id));
|
|
670
|
+
tell({ kind: 'removed', ids });
|
|
671
|
+
return null;
|
|
672
|
+
}
|
|
673
|
+
case 'move': {
|
|
674
|
+
// Only threads on a passage of this entry move, and only their roots carry a range.
|
|
675
|
+
const moves = input.moves.filter(move => { const note = this.notes.find(entry => entry.id === move.id); return !!note && !note.parentId && note.target.startsWith('text:'); });
|
|
676
|
+
if (!moves.length) return null;
|
|
677
|
+
await cms.notes.move(moves);
|
|
678
|
+
this.notes = this.notes.map(entry => { const move = moves.find(candidate => candidate.id === entry.id); return move ? { ...entry, range: move.range } : entry; });
|
|
679
|
+
tell({ kind: 'moved', moves: moves.map(move => ({ id: move.id, range: move.range })) });
|
|
680
|
+
return null;
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
@Server()
|
|
686
|
+
async leave(peer: unknown): Promise<void> {
|
|
687
|
+
const { principal } = this.contextOf();
|
|
688
|
+
const own = this.ownPeer(peer, principal);
|
|
689
|
+
if (!own) return;
|
|
690
|
+
const present = this.roomPeers.delete(own);
|
|
691
|
+
this.releasePeer(own);
|
|
692
|
+
if (!present) return;
|
|
693
|
+
this.presenceChanged();
|
|
694
|
+
this.broadcastEvent('left', own);
|
|
695
|
+
void this.reportEditors();
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
@Server()
|
|
699
|
+
async saved(peer: unknown): Promise<RoomSnapshot> {
|
|
700
|
+
const { cms, principal } = this.contextOf();
|
|
701
|
+
await this.load(cms);
|
|
702
|
+
const resets: string[] = [];
|
|
703
|
+
const snapshot = await this.restart(cms, resets);
|
|
704
|
+
const user = await cms.users.get(principal.id).catch(() => null);
|
|
705
|
+
this.broadcastEvent('saved', user?.name || principal.id, snapshot.rev, snapshot, resets, this.ownPeer(peer, principal) ?? '');
|
|
706
|
+
return snapshot;
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
@Server()
|
|
710
|
+
async reload(): Promise<RoomSnapshot> {
|
|
711
|
+
const { cms } = this.contextOf();
|
|
712
|
+
await this.load(cms);
|
|
713
|
+
const resets: string[] = [];
|
|
714
|
+
const snapshot = await this.restart(cms, resets);
|
|
715
|
+
this.broadcastEvent('reloaded', snapshot, resets);
|
|
716
|
+
return snapshot;
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// --- Browser: this tab in the room ---------------------------------------------------------
|
|
720
|
+
// The renderer assigns a child's props onto the instance, so no method below may share a name
|
|
721
|
+
// with a prop (`onSet`, `onSaved`…): the event dispatch would call the page's callback instead.
|
|
722
|
+
private peerId = '';
|
|
723
|
+
private joined = false;
|
|
724
|
+
private wasOpen = false;
|
|
725
|
+
private current: PeerPresence = {};
|
|
726
|
+
private peers = new Map<string, PeerState>();
|
|
727
|
+
private heartbeat: ReturnType<typeof setInterval> | undefined;
|
|
728
|
+
private joining: Promise<void> | undefined;
|
|
729
|
+
|
|
730
|
+
onMount() {
|
|
731
|
+
this.peerId = crypto.randomUUID();
|
|
732
|
+
void this.enter(0);
|
|
733
|
+
this.heartbeat = setInterval(() => {
|
|
734
|
+
if (!this.joined) return;
|
|
735
|
+
void this.presence(this.peerId, this.current).catch(() => undefined);
|
|
736
|
+
// Peers this tab has not heard from have gone, whether or not the room said so (a restarted instance never does).
|
|
737
|
+
this.forget(expiredPeers(this.peers.values(), Date.now()));
|
|
738
|
+
}, HEARTBEAT);
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/** Peers heard from, stamped with this tab's clock: the room's `at` is on another. */
|
|
742
|
+
@Client()
|
|
743
|
+
private hear(peers: readonly PeerState[]): void {
|
|
744
|
+
const now = Date.now();
|
|
745
|
+
for (const peer of peers) this.peers.set(peer.peer, { ...peer, at: now });
|
|
746
|
+
this.props.onPeers([...this.peers.values()], this.peerId);
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
@Client()
|
|
750
|
+
private forget(ids: readonly string[]): void {
|
|
751
|
+
let gone = false;
|
|
752
|
+
for (const id of ids) if (this.peers.delete(id)) gone = true;
|
|
753
|
+
if (gone) this.props.onPeers([...this.peers.values()], this.peerId);
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
onCleanup() {
|
|
757
|
+
if (this.heartbeat) clearInterval(this.heartbeat);
|
|
758
|
+
if (this.joined) void this.leave(this.peerId).catch(() => undefined);
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
@OnWindow('pagehide')
|
|
762
|
+
@Client()
|
|
763
|
+
goodbye() {
|
|
764
|
+
if (this.joined) void this.leave(this.peerId).catch(() => undefined);
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** Join, trying again while the connection comes up; after a reconnect, join again for a fresh draft. */
|
|
768
|
+
@Client()
|
|
769
|
+
private enter(attempt: number): Promise<void> {
|
|
770
|
+
return this.joining ??= (async () => {
|
|
771
|
+
try {
|
|
772
|
+
const snapshot = await this.join(this.peerId, this.current);
|
|
773
|
+
const initial = !this.joined;
|
|
774
|
+
this.joined = true;
|
|
775
|
+
this.peers = new Map();
|
|
776
|
+
this.hear(snapshot.peers);
|
|
777
|
+
// The page gets the room once it is joined: calls before the connection opens would fail.
|
|
778
|
+
if (initial) this.props.onReady(this.handle());
|
|
779
|
+
this.props.onSnapshot(snapshot, { initial, resets: initial ? [] : Object.keys(snapshot.versions) });
|
|
780
|
+
if (!initial) for (const path of Object.keys(snapshot.versions)) { const editor = collabEditors.get(path); if (editor?.collab && editor.collab.version !== snapshot.versions[path]) void editor.collab.reload(); }
|
|
781
|
+
this.status();
|
|
782
|
+
} catch {
|
|
783
|
+
if (attempt < 20 && !this.isDestroyed()) setTimeout(() => { this.joining = undefined; void this.enter(attempt + 1); }, Math.min(5000, 250 * 2 ** attempt));
|
|
784
|
+
} finally { this.joining = undefined; }
|
|
785
|
+
})();
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
@Client()
|
|
789
|
+
private isDestroyed(): boolean {
|
|
790
|
+
return (this as unknown as { _phase?: string })._phase === 'Destroyed';
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
@Client()
|
|
794
|
+
updated(changed: Map<string | number | symbol, unknown>) {
|
|
795
|
+
super.updated(changed);
|
|
796
|
+
const open = this.realtime.websocket.state === 'open';
|
|
797
|
+
if (open && !this.wasOpen && this.joined) void this.enter(0);
|
|
798
|
+
if (open !== this.wasOpen) { this.wasOpen = open; this.status(); }
|
|
799
|
+
if (changed.has('dirty') || changed.has('diverged') || changed.has('oversized')) this.status();
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
@Client()
|
|
803
|
+
private status(): void {
|
|
804
|
+
this.props.onStatus({ connected: this.joined && this.realtime.websocket.state === 'open', dirty: this.dirty, diverged: this.diverged, oversized: this.oversized });
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
@Client()
|
|
808
|
+
private handle(): RoomHandle {
|
|
809
|
+
const room = this;
|
|
810
|
+
return {
|
|
811
|
+
peer: this.peerId,
|
|
812
|
+
set: (field, value) => room.set(room.peerId, field, value),
|
|
813
|
+
tree: op => room.tree(room.peerId, op),
|
|
814
|
+
blocks: field => room.blocks(field),
|
|
815
|
+
transport: path => ({
|
|
816
|
+
steps: (version, steps, clientID) => room.steps(room.peerId, path, version, steps, clientID),
|
|
817
|
+
document: () => room.richText(path),
|
|
818
|
+
}),
|
|
819
|
+
fresh: () => room.draft(),
|
|
820
|
+
presence: state => {
|
|
821
|
+
room.current = { ...room.current, ...state };
|
|
822
|
+
if (room.joined) void room.presence(room.peerId, room.current).catch(() => undefined);
|
|
823
|
+
},
|
|
824
|
+
saved: async () => { await room.saved(room.peerId); },
|
|
825
|
+
reload: async () => { await room.reload(); },
|
|
826
|
+
note: action => room.note(room.peerId, action),
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
@OnEvent('set')
|
|
831
|
+
private receiveSet(peer: string, field: string, value: unknown) {
|
|
832
|
+
this.props.onSet(peer, field, value);
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
@OnEvent('tree')
|
|
836
|
+
private receiveTree(peer: string, op: TreeOp, hash: string) {
|
|
837
|
+
this.props.onTree(peer, op, hash);
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
@OnEvent('steps')
|
|
841
|
+
private receiveSteps(path: string, steps: unknown[], clientIDs: (string | number)[], version: number) {
|
|
842
|
+
collabEditors.get(path)?.collab?.receive(version, steps, clientIDs);
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
@OnEvent('presence')
|
|
846
|
+
private receivePresence(peer: PeerState) {
|
|
847
|
+
this.hear([peer]);
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
@OnEvent('left')
|
|
851
|
+
private receiveLeft(peer: string) {
|
|
852
|
+
this.forget([peer]);
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
@OnEvent('note')
|
|
856
|
+
private receiveNote(change: NoteChange) {
|
|
857
|
+
this.props.onNote(change);
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
/** Someone saved: everyone takes the saved values; the others hear who it was (the saver's own tab said "Saved." already). */
|
|
861
|
+
@OnEvent('saved')
|
|
862
|
+
private receiveSaved(by: string, rev: number, snapshot: RoomSnapshot, resets: string[], peer: string) {
|
|
863
|
+
this.props.onSnapshot(snapshot, { initial: false, resets });
|
|
864
|
+
for (const path of resets) void collabEditors.get(path)?.collab?.reload();
|
|
865
|
+
if (peer !== this.peerId) this.props.onSaved(by, rev);
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
@OnEvent('reloaded')
|
|
869
|
+
private receiveReloaded(snapshot: RoomSnapshot, resets: string[]) {
|
|
870
|
+
this.props.onSnapshot(snapshot, { initial: false, resets });
|
|
871
|
+
for (const path of resets) void collabEditors.get(path)?.collab?.reload();
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
/** Everyone in the entry as an avatar stack, the viewer first; the page shows the rest. */
|
|
875
|
+
render(): TemplateResult | null {
|
|
876
|
+
const me = this.peers.get(this.peerId)?.user ?? '';
|
|
877
|
+
const everyone = [...this.participants.filter(participant => participant.user === me), ...this.participants.filter(participant => participant.user !== me)];
|
|
878
|
+
if (!everyone.length) return null;
|
|
879
|
+
return html`<div class="flex items-center gap-2" data-room-participants=${everyone.length}>${avatarStack(everyone, { size: 16, max: 5, label: __('In this entry'), self: me })}</div>`;
|
|
880
|
+
}
|
|
881
|
+
}
|