@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,1322 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The public site on the CMS: the active theme, its menus, entries and archives as views, and
|
|
3
|
+
* which entry, archive or term a URL names, in which language. Server-only; pages call these
|
|
4
|
+
* from `init()` and hand the views to the theme's templates.
|
|
5
|
+
*/
|
|
6
|
+
import {
|
|
7
|
+
ENTRY_VIEW_REFUSED_BLOCKS, siteEntryView, validateBlocks, type EntryViewParts,
|
|
8
|
+
ANONYMOUS, ARTICLE_TYPES, withContentFields, authorUrl, entryAuthors, blockDocuments, SHARE_BRAND_URLS, blockIsData, blocksPlain, editedSize, fieldGroupDeclarations, hasBlockReference, parseBlockText, PATTERN_REFERENCE, resolveBindings, resolveBlockBindings, siteBindingScope, textBlocks, usesUserBinding, type BindingScopes, type ParsedText, flattenBlocks, escapeHtml, formatSiteDate, formInputs, formSettings, imageSrcset, imageUrl, imageWidths, IMAGE_WIDTHS, isCmsError, languageFlag, languageName, mediaUrl, notificationRules, recordTitle, resolvePresets, richTextBlocks, richTextParts, richTextPlain, systemPrincipal, templateCandidates, transformable, urlList,
|
|
9
|
+
type AuthorView, type Block,
|
|
10
|
+
type Principal, type TemplatePage, type ThemeData, type ThemePresets,
|
|
11
|
+
type ArchiveView, type BodyPart, type BrandIcon, type CollectionDefinition, type CommentShape, type CommentView, type CommentsView, type EntryReference, type EntryView, type FieldDeclaration, type FieldFilter,
|
|
12
|
+
type BreadcrumbView, type FieldView, type LanguageLink, type MediaView, type MenuItemView, type Paging, type RecordShape, type RenderedBlock, type ResolvedMenuItem, type RichTextDoc, type SiteSettings, type SiteView, type TermLink, type TermShape,
|
|
13
|
+
} from '@cossackframework/cms';
|
|
14
|
+
import { brandIcon, excerptOf, lockedView, renderMarkdown, type CmsFile, type CmsHost, type CmsUser, type LoadedForm, type SiteLanguages } from '@cossackframework/cms/server';
|
|
15
|
+
import type { FormView } from '@cossackframework/cms';
|
|
16
|
+
import { formView, type FormRequest } from './site-forms';
|
|
17
|
+
import { withHeadingAnchors } from './headings';
|
|
18
|
+
|
|
19
|
+
/** The active theme, the theme it extends, its option values and presets, which every site page renders with. */
|
|
20
|
+
export interface ThemeState {
|
|
21
|
+
name: string | null;
|
|
22
|
+
parent?: string | null;
|
|
23
|
+
options: Record<string, unknown>;
|
|
24
|
+
/** The presets blocks pick from, the site's color changes applied. */
|
|
25
|
+
presets?: Required<ThemePresets>;
|
|
26
|
+
/** The site's Additional CSS, already checked. */
|
|
27
|
+
customCss?: string;
|
|
28
|
+
/** Active plugins apart from the theme and its parent: their `ui.ts` `head` runs on the site. */
|
|
29
|
+
plugins?: readonly string[];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const visitor = { principal: ANONYMOUS };
|
|
33
|
+
/** Patterns are private; the site reads them to render the entries that use them. */
|
|
34
|
+
const renderer = { principal: systemPrincipal('site') };
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Texts with block references, parsed once per site in each isolate: saving checks them, so
|
|
38
|
+
* serving a page parses each text once. Sites can have different block types active.
|
|
39
|
+
*/
|
|
40
|
+
const PARSED = new WeakMap<CmsHost, Map<string, ParsedText>>();
|
|
41
|
+
|
|
42
|
+
function parsedText(cms: CmsHost, text: string): ParsedText {
|
|
43
|
+
let texts = PARSED.get(cms);
|
|
44
|
+
if (!texts) PARSED.set(cms, texts = new Map());
|
|
45
|
+
let parsed = texts.get(text);
|
|
46
|
+
if (!parsed) {
|
|
47
|
+
parsed = parseBlockText(text, cms.blockTypes);
|
|
48
|
+
if (texts.size >= 500) texts.delete(texts.keys().next().value!);
|
|
49
|
+
texts.set(text, parsed);
|
|
50
|
+
}
|
|
51
|
+
return parsed;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The blocks a block's Markdown fields reference, for collecting their media and patterns. */
|
|
55
|
+
function referencedBlocks(cms: CmsHost, block: { type: string; data: Record<string, unknown> }): Block[] {
|
|
56
|
+
const found: Block[] = [];
|
|
57
|
+
for (const [key, declaration] of Object.entries(cms.blockTypes.get(block.type)?.fields ?? {})) {
|
|
58
|
+
const value = block.data[key];
|
|
59
|
+
if (declaration.kind === 'text' && declaration.format === 'markdown' && hasBlockReference(value)) found.push(...flattenBlocks(textBlocks(parsedText(cms, value))));
|
|
60
|
+
}
|
|
61
|
+
return found;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** What bindings read on a page: the entry (when there is one), the site's public settings and the signed-in user. */
|
|
65
|
+
export function bindingScopes(settings: SiteSettings, options: { entry?: Readonly<Record<string, unknown>> | null; user?: { readonly name: string } | null } = {}): BindingScopes {
|
|
66
|
+
return {
|
|
67
|
+
entry: options.entry ?? null,
|
|
68
|
+
site: siteBindingScope(settings),
|
|
69
|
+
user: options.user ?? null,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Theme options with their bindings resolved, so a footer text can say `© {{ $site.title }}`. */
|
|
74
|
+
export function resolvedOptions(options: Readonly<Record<string, unknown>>, scopes: BindingScopes): Record<string, unknown> {
|
|
75
|
+
return Object.fromEntries(Object.entries(options).map(([name, value]) => [name, typeof value === 'string' ? resolveBindings(value, scopes) : value]));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export async function themeState(cms: CmsHost): Promise<ThemeState> {
|
|
79
|
+
const name = await cms.activeTheme();
|
|
80
|
+
const theme = cms.themes().find(entry => entry.name === name);
|
|
81
|
+
const settings = await cms.settings.all();
|
|
82
|
+
const options = Object.fromEntries(Object.keys(theme?.options?.fields ?? {}).map(option => [option, settings[`${name}.${option}`]]));
|
|
83
|
+
return { name, parent: theme?.parent ?? null, options, presets: resolvePresets(theme?.presets, name ? settings['appearance.presets']?.[name] : null), customCss: settings['appearance.customCss'] ?? '',
|
|
84
|
+
plugins: cms.activePluginNames().filter(entry => entry !== name && entry !== theme?.parent) };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The active theme's presets with the site's changes, for the editors' Style tab. */
|
|
88
|
+
export async function activePresets(cms: CmsHost): Promise<Required<ThemePresets>> {
|
|
89
|
+
const name = await cms.activeTheme();
|
|
90
|
+
const theme = cms.themes().find(entry => entry.name === name);
|
|
91
|
+
const settings = await cms.settings.all();
|
|
92
|
+
return resolvePresets(theme?.presets, name ? settings['appearance.presets']?.[name] : null);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* What the active theme's loader for a page returns: the first of the page's template
|
|
97
|
+
* candidates the theme has a loader for (`layout` for the layout). Empty when there is none.
|
|
98
|
+
*/
|
|
99
|
+
export function themeData(cms: CmsHost, theme: ThemeState, page: TemplatePage | 'layout', view: SiteView | EntryView | ArchiveView, principal: Principal, locale?: string): Promise<ThemeData> {
|
|
100
|
+
// The loader gets the key its template does: the layout's site, the page's entry or its list.
|
|
101
|
+
const input = page === 'layout' ? { site: view as SiteView } : page.kind === 'entry' ? { entry: view as EntryView } : { view: view as ArchiveView };
|
|
102
|
+
return cms.themeData(theme.name, page === 'layout' ? ['layout'] : templateCandidates(page), input, { principal, options: theme.options, ...(locale ? { locale } : {}) });
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The URL prefix of a language: empty for the default one. */
|
|
106
|
+
export function localePrefix(languages: SiteLanguages, locale: string): string {
|
|
107
|
+
if (!languages.multilingual) return '';
|
|
108
|
+
const code = languages.all.includes(locale) ? locale : languages.default;
|
|
109
|
+
return code !== languages.default || languages.prefixDefault ? `/${code}` : '';
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Language filter for queries: only on a site with several languages. */
|
|
113
|
+
function localeWhere(languages: SiteLanguages, locale: string): { [field: string]: FieldFilter } {
|
|
114
|
+
return languages.multilingual ? { locale } : {};
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The layout's data: site title, tagline, the menus of the active theme's locations and the language links. */
|
|
118
|
+
export async function siteView(cms: CmsHost, theme: ThemeState, options: { locale?: string; languages?: readonly LanguageLink[]; forms?: FormRequest; template?: string | null; entry?: RecordShape | null; user?: { name: string } | null; usage?: { user: boolean };
|
|
119
|
+
/** The page's absolute URL, for sharing. */ url?: string; /** The page resolved, for its breadcrumbs. */ page?: Resolved | { kind: string; locale: string } } = {}): Promise<SiteView & { noindex: boolean }> {
|
|
120
|
+
const settings = await cms.settings.all();
|
|
121
|
+
useImageSettings(cms, settings);
|
|
122
|
+
const languages = await cms.languages();
|
|
123
|
+
const locale = options.locale ?? languages.default;
|
|
124
|
+
const info = cms.themes().find(entry => entry.name === theme.name);
|
|
125
|
+
const menus = await siteMenus(cms, theme, { locale, user: options.user, forms: options.forms, usage: options.usage });
|
|
126
|
+
let blog: string | null = null;
|
|
127
|
+
try { blog = await cms.archiveUrl(cms.collection('posts'), locale); } catch { /* no posts */ }
|
|
128
|
+
return {
|
|
129
|
+
title: settings['general.siteTitle'], tagline: settings['general.tagline'], logo: settings['general.logo'] || null, blog, menus, noindex: settings['reading.discourageSearchEngines'],
|
|
130
|
+
locale, languages: options.languages ?? [], searchUrl: `${localePrefix(languages, locale)}/search`, homeUrl: localePrefix(languages, locale) || '/',
|
|
131
|
+
areas: await areaViews(cms, info?.areas ?? [], options.forms, bindingScopes(settings, options), options.usage),
|
|
132
|
+
template: options.template ?? null,
|
|
133
|
+
url: options.url ?? '',
|
|
134
|
+
breadcrumbs: await breadcrumbTrail(cms, options.page, languages, locale),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* The way to a page: Home (the language's), then an entry's collection archive and ancestors, a
|
|
140
|
+
* term's ancestors, or the archive, search or author page, and last the page itself without a
|
|
141
|
+
* URL. The `core/breadcrumbs` block and `helpers.breadcrumbs` draw it; the SEO graph has its own.
|
|
142
|
+
*/
|
|
143
|
+
async function breadcrumbTrail(cms: CmsHost, page: Resolved | { kind: string; locale: string } | undefined, languages: SiteLanguages, locale: string): Promise<BreadcrumbView[]> {
|
|
144
|
+
const prefix = localePrefix(languages, locale);
|
|
145
|
+
const home: BreadcrumbView = { label: __('Home'), url: prefix || '/' };
|
|
146
|
+
if (!page || page.kind === 'home') return [{ label: home.label, url: null }];
|
|
147
|
+
const crumbs: BreadcrumbView[] = [home];
|
|
148
|
+
const resolved = page as Resolved;
|
|
149
|
+
switch (resolved.kind) {
|
|
150
|
+
case 'entry': {
|
|
151
|
+
const archive = resolved.collection.hierarchical ? null : await cms.archiveUrl(resolved.collection, locale).catch(() => null);
|
|
152
|
+
if (archive && archive !== home.url) crumbs.push({ label: resolved.collection.label, url: archive });
|
|
153
|
+
if (resolved.collection.hierarchical) for (const ancestor of await entryAncestors(cms, resolved.collection, resolved.record)) crumbs.push({ label: ancestor.name, url: ancestor.url });
|
|
154
|
+
crumbs.push({ label: recordTitle(resolved.record, 'title'), url: null });
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
case 'archive': crumbs.push({ label: resolved.collection.label, url: null }); break;
|
|
158
|
+
case 'term': {
|
|
159
|
+
const taxonomy = cms.taxonomies.declaration(resolved.term.taxonomy);
|
|
160
|
+
for (const ancestor of resolved.ancestors) crumbs.push({ label: ancestor.name, url: taxonomy.path ? `${prefix}/${taxonomy.path}/${ancestor.slug}` : null });
|
|
161
|
+
crumbs.push({ label: resolved.term.name, url: null });
|
|
162
|
+
break;
|
|
163
|
+
}
|
|
164
|
+
case 'search': crumbs.push({ label: __('Search'), url: null }); break;
|
|
165
|
+
case 'author': crumbs.push({ label: resolved.user.name, url: null }); break;
|
|
166
|
+
default: break;
|
|
167
|
+
}
|
|
168
|
+
return crumbs;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Ancestors of a nested entry, top first, each with its URL; the SEO graph's breadcrumbs use it too. */
|
|
172
|
+
export async function entryAncestors(cms: CmsHost, collection: CollectionDefinition, record: RecordShape): Promise<{ name: string; url: string }[]> {
|
|
173
|
+
const chain: RecordShape[] = [];
|
|
174
|
+
let parent = typeof record.parent === 'string' ? record.parent : null;
|
|
175
|
+
for (let depth = 0; parent && depth < 8; depth++) {
|
|
176
|
+
const found = (await cms.resource(`cms/${collection.name}`).getMany([parent], { principal: { kind: 'anonymous' } })).get(parent);
|
|
177
|
+
if (!found) break;
|
|
178
|
+
chain.unshift(found);
|
|
179
|
+
parent = typeof found.parent === 'string' ? found.parent : null;
|
|
180
|
+
}
|
|
181
|
+
const urls = await cms.entryUrls(collection, chain);
|
|
182
|
+
return chain.flatMap(entry => urls.get(entry.id) ? [{ name: String(entry.title ?? ''), url: urls.get(entry.id)! }] : []);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** What the site blocks need of the site and the page, in the page's language: the logo and search blocks, the share buttons (`url`) and the breadcrumbs. */
|
|
186
|
+
export interface SiteInfo { readonly title: string; readonly tagline: string; readonly logo: string | null; readonly homeUrl: string; readonly searchUrl: string; readonly locale: string; readonly url: string; readonly breadcrumbs: readonly BreadcrumbView[] }
|
|
187
|
+
|
|
188
|
+
export async function siteInfo(cms: CmsHost, locale?: string, page: { /** The page's absolute URL. */ url?: string; /** The page resolved, for its breadcrumbs. */ page?: Resolved | { kind: string; locale: string } } = {}): Promise<SiteInfo> {
|
|
189
|
+
const settings = await cms.settings.all();
|
|
190
|
+
const languages = await cms.languages();
|
|
191
|
+
const prefix = localePrefix(languages, locale ?? languages.default);
|
|
192
|
+
return { title: settings['general.siteTitle'], tagline: settings['general.tagline'], logo: settings['general.logo'] || null, homeUrl: prefix || '/', searchUrl: `${prefix}/search`,
|
|
193
|
+
locale: locale ?? languages.default, url: page.url ?? '', breadcrumbs: await breadcrumbTrail(cms, page.page, languages, locale ?? languages.default) };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* The menus of the active theme's locations, finished for the site (`menuViews`); an unassigned
|
|
198
|
+
* primary location lists the top-level pages. Menus bind to the site and the signed-in user,
|
|
199
|
+
* never to the entry shown, so a panel reads the same on every page.
|
|
200
|
+
*/
|
|
201
|
+
export async function siteMenus(cms: CmsHost, theme: ThemeState, options: { locale?: string; user?: { name: string } | null; forms?: FormRequest; usage?: { user: boolean }; patternDrafts?: ReadonlyMap<string, readonly Block[]> } = {}): Promise<Record<string, readonly MenuItemView[]>> {
|
|
202
|
+
const settings = await cms.settings.all();
|
|
203
|
+
const languages = await cms.languages();
|
|
204
|
+
const locale = options.locale ?? languages.default;
|
|
205
|
+
const info = cms.themes().find(entry => entry.name === theme.name);
|
|
206
|
+
const declared = info?.locations.map(location => location.name) ?? [];
|
|
207
|
+
const locations = declared.length ? declared : ['primary'];
|
|
208
|
+
const menus: Record<string, readonly MenuItemView[]> = {};
|
|
209
|
+
const scopes = bindingScopes(settings, { user: options.user ?? null });
|
|
210
|
+
// The locations are finished side by side: each may read its panels and their media.
|
|
211
|
+
const views = await Promise.all(locations.map(async location => {
|
|
212
|
+
const menu = await cms.menus.forLocation(location, languages.multilingual ? locale : undefined).catch(() => null);
|
|
213
|
+
if (menu) return menuViews(cms, menu, { scopes, locale, forms: options.forms, usage: options.usage, patternDrafts: options.patternDrafts });
|
|
214
|
+
return location === 'primary' ? pageMenu(cms, languages, locale) : null;
|
|
215
|
+
}));
|
|
216
|
+
locations.forEach((location, index) => { if (views[index]) menus[location] = views[index]!; });
|
|
217
|
+
return menus;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** The menus a page's own blocks show: those of the theme's locations when a Navigation block is among the blocks, nothing otherwise. */
|
|
221
|
+
export async function contentMenus(cms: CmsHost, theme: ThemeState, blocks: readonly RenderedBlock[], options: { locale?: string; user?: { name: string } | null; forms?: FormRequest; usage?: { user: boolean } } = {}): Promise<Record<string, readonly MenuItemView[]>> {
|
|
222
|
+
let found = false;
|
|
223
|
+
walkBlocks(blocks, block => { if (block.type === 'core/navigation') found = true; });
|
|
224
|
+
return found ? siteMenus(cms, theme, options) : {};
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** The blocks of the theme's widget areas, rendered: the saved blocks, or the theme's defaults until the site saves its own; blocks of inactive plugins are left out. */
|
|
228
|
+
export async function areaViews(cms: CmsHost, declared: readonly { name: string; defaults: readonly Block[] }[], forms?: FormRequest, scopes?: BindingScopes, usage?: { user: boolean }, drafts?: ReadonlyMap<string, readonly Block[]>, patternDrafts?: ReadonlyMap<string, readonly Block[]>): Promise<Record<string, RenderedBlock[]>> {
|
|
229
|
+
if (!declared.length) return {};
|
|
230
|
+
const saved = await cms.areas.all().catch(() => new Map<string, { blocks: readonly Block[] }>());
|
|
231
|
+
const available = new Set((await cms.blocks()).map(block => block.name));
|
|
232
|
+
const blocks = new Map(declared.map(area => [area.name, (drafts?.get(area.name) ?? saved.get(area.name)?.blocks ?? area.defaults).filter(block => available.has(block.type))]));
|
|
233
|
+
const all = [...blocks.values()].flat() as Block[];
|
|
234
|
+
const patterns = withPatternDrafts(await usedPatterns(cms, blockDocuments(all, cms.blockTypes), all), patternDrafts);
|
|
235
|
+
const expanded = new Map([...blocks].map(([name, list]) => [name, expandPatterns(list as Block[], patterns)]));
|
|
236
|
+
const ids = new Set<string>();
|
|
237
|
+
for (const list of expanded.values()) for (const block of list) blockMediaIds(cms, block as { type: string; data: Record<string, unknown> }, ids);
|
|
238
|
+
const files = cms.files && ids.size ? await cms.files.getMany([...ids]) : new Map<string, CmsFile>();
|
|
239
|
+
const richText = bodyRenderer(cms, files, patterns);
|
|
240
|
+
// Widgets bind like entry blocks: on an entry's page `$` is that entry, and `$site` and `$user` are there everywhere.
|
|
241
|
+
const areas = Object.fromEntries([...expanded].map(([name, list]) => [name, list.map(block => renderedBlock(cms, block as { _id: string; type: string; data: Record<string, unknown> }, files, doc => richText(doc, scopes), scopes, { patterns, usage }))]));
|
|
242
|
+
await withForms(cms, Object.values(areas).flat(), forms);
|
|
243
|
+
await withLatest(cms, Object.values(areas).flat());
|
|
244
|
+
return areas;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Give each `core/latest-entries` block among these its entries: the newest published entries
|
|
249
|
+
* of the collection it names, with the term it asks for, as list views (no bodies).
|
|
250
|
+
*/
|
|
251
|
+
async function withLatest(cms: CmsHost, blocks: readonly RenderedBlock[], locale?: string, options: { exclude?: string } = {}): Promise<void> {
|
|
252
|
+
const found: RenderedBlock[] = [];
|
|
253
|
+
walkBlocks(blocks, block => { if (block.type === 'core/latest-entries') found.push(block); });
|
|
254
|
+
const languages = found.length ? await cms.languages() : null;
|
|
255
|
+
for (const block of found) {
|
|
256
|
+
const name = typeof block.data.collection === 'string' ? block.data.collection : '';
|
|
257
|
+
const collection = cms.collections().find(entry => entry.name === name);
|
|
258
|
+
if (!collection || collection.publishable === false) continue;
|
|
259
|
+
const term = typeof block.data.term === 'string' && block.data.term ? block.data.term : '';
|
|
260
|
+
const count = Math.min(Math.max(Number(block.data.count) || 5, 1), 24);
|
|
261
|
+
const order = block.data.order === 'title' ? { field: 'title', direction: 'asc' as const } : { field: 'publishedAt', direction: block.data.order === 'oldest' ? 'asc' as const : 'desc' as const };
|
|
262
|
+
try {
|
|
263
|
+
const where: { [field: string]: FieldFilter } = { status: 'published', ...(languages && locale ? localeWhere(languages, locale) : {}) };
|
|
264
|
+
if (term) {
|
|
265
|
+
const found = await cms.taxonomies.get(term);
|
|
266
|
+
const field = found ? collection.taxonomies?.find(taxonomy => taxonomy === found.taxonomy) : undefined;
|
|
267
|
+
if (!field) { (block as { entries?: readonly EntryView[] }).entries = []; continue; }
|
|
268
|
+
where[field] = { containsAny: (await cms.taxonomies.subtree(term)).slice(0, 50) };
|
|
269
|
+
}
|
|
270
|
+
const resource = cms.resourceById(`cms/${collection.name}`);
|
|
271
|
+
const author = typeof block.data.author === 'string' && block.data.author && 'authors' in resource.fields ? block.data.author : '';
|
|
272
|
+
if (author) where.authors = { contains: author };
|
|
273
|
+
const offset = Math.min(Math.max(Math.trunc(Number(block.data.offset) || 0), 0), 100);
|
|
274
|
+
const exclude = block.data.excludeCurrent !== false && options.exclude ? options.exclude : '';
|
|
275
|
+
const stickyFirst = block.data.stickyFirst === true && 'sticky' in resource.fields;
|
|
276
|
+
// The page reads a few more than it shows: the entry being shown is left out, and sticky entries move to the front.
|
|
277
|
+
const page = await cms.resource(`cms/${collection.name}`).list({ where, order, limit: Math.min(count + offset + (exclude ? 1 : 0) + (stickyFirst ? 10 : 0), 100) }, visitor);
|
|
278
|
+
let records = page.records.filter(record => record.id !== exclude);
|
|
279
|
+
if (stickyFirst) records = [...records.filter(record => record.sticky === true), ...records.filter(record => record.sticky !== true)];
|
|
280
|
+
(block as { entries?: readonly EntryView[] }).entries = await entryViews(cms, collection, records.slice(offset, offset + count));
|
|
281
|
+
} catch (error) { if (!isCmsError(error)) throw error; }
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Visit these blocks, their children and the blocks embedded in their rich text, depth first. */
|
|
286
|
+
function walkBlocks(blocks: readonly RenderedBlock[], visit: (block: RenderedBlock) => void): void {
|
|
287
|
+
for (const block of blocks) {
|
|
288
|
+
visit(block);
|
|
289
|
+
if (block.children) walkBlocks(block.children, visit);
|
|
290
|
+
for (const parts of Object.values(block.content ?? {})) walkBlocks(parts.flatMap(part => part.kind === 'block' ? [part.block] : []), visit);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Rich text as body parts: HTML runs and rendered blocks, synced patterns expanded one level.
|
|
296
|
+
* For the rich text inside blocks, the entry's rich text fields among them.
|
|
297
|
+
*/
|
|
298
|
+
function bodyRenderer(cms: CmsHost, files: ReadonlyMap<string, CmsFile>, patterns: ReadonlyMap<string, Block[]>, usage?: { user: boolean }): (doc: RichTextDoc, scope?: BindingScopes, depth?: number) => BodyPart[] {
|
|
299
|
+
const resizes = imageOptions(cms);
|
|
300
|
+
const media = (id: string) => {
|
|
301
|
+
const view = mediaView(files.get(id), resizes);
|
|
302
|
+
return view ? { url: view.url, width: view.width, height: view.height, srcset: view.srcset } : null;
|
|
303
|
+
};
|
|
304
|
+
// Bindings resolve in each text run, as in a block's text fields; a run that names the user makes the page per user.
|
|
305
|
+
const text = (scope: BindingScopes) => (value: string) => {
|
|
306
|
+
if (scope.user && usage && usesUserBinding(value)) usage.user = true;
|
|
307
|
+
return resolveBindings(value, scope);
|
|
308
|
+
};
|
|
309
|
+
const parts = (doc: RichTextDoc, scope?: BindingScopes, depth = 0): BodyPart[] => richTextParts(doc, { media, ...(scope ? { text: text(scope) } : {}) }).flatMap((part): BodyPart[] => {
|
|
310
|
+
if (part.kind === 'html') return [part];
|
|
311
|
+
const inner = depth === 0 ? (doc: RichTextDoc) => parts(doc, scope, 1) : undefined;
|
|
312
|
+
if (part.block.type === 'core/pattern') {
|
|
313
|
+
// A pattern embedded in rich text: its blocks in its place, once.
|
|
314
|
+
return depth === 0 ? expandPatterns([part.block as Block], patterns).map(block => ({ kind: 'block' as const, block: renderedBlock(cms, block, files, inner, scope, { patterns, usage }) })) : [];
|
|
315
|
+
}
|
|
316
|
+
return [{ kind: 'block' as const, block: renderedBlock(cms, part.block as RenderedBlock, files, inner, scope, { patterns, usage }) }];
|
|
317
|
+
});
|
|
318
|
+
return parts;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Give each `core/form` block among these its form, for the page's request. A form that is gone renders nothing. */
|
|
322
|
+
async function withForms(cms: CmsHost, blocks: readonly RenderedBlock[], request: FormRequest | undefined): Promise<void> {
|
|
323
|
+
if (!request) return;
|
|
324
|
+
const found: RenderedBlock[] = [];
|
|
325
|
+
walkBlocks(blocks, block => { if (block.type === 'core/form') found.push(block); });
|
|
326
|
+
for (const block of found) {
|
|
327
|
+
const slug = typeof block.data.form === 'string' ? block.data.form : '';
|
|
328
|
+
try {
|
|
329
|
+
const form = slug ? await cms.forms.get(slug) : null;
|
|
330
|
+
if (!form?.published) continue;
|
|
331
|
+
const ids = new Set<string>();
|
|
332
|
+
for (const entry of form.blocks) blockMediaIds(cms, entry, ids);
|
|
333
|
+
const files = cms.files && ids.size ? await cms.files.getMany([...ids]) : new Map<string, CmsFile>();
|
|
334
|
+
(block as { form?: FormView }).form = await formView(cms, form, request, entry => renderedBlock(cms, entry, files));
|
|
335
|
+
} catch (error) {
|
|
336
|
+
if (!isCmsError(error)) throw error;
|
|
337
|
+
// The page still renders, without the form; say why, or a missing form cannot be told from a bug.
|
|
338
|
+
console.warn(`[cms] the form "${slug}" was left off the page: ${error.message}`);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Without an assigned menu, the primary location lists the published top-level pages. */
|
|
344
|
+
async function pageMenu(cms: CmsHost, languages: SiteLanguages, locale: string): Promise<MenuItemView[]> {
|
|
345
|
+
try {
|
|
346
|
+
const pages = cms.collection('pages');
|
|
347
|
+
const where = { status: 'published', parent: null, ...localeWhere(languages, locale) };
|
|
348
|
+
const repository = cms.resource('cms/pages');
|
|
349
|
+
const top = await repository.list({ where, order: { field: 'menuOrder', direction: 'asc' }, limit: 12 }, visitor);
|
|
350
|
+
const urls = await cms.entryUrls(pages, top.records);
|
|
351
|
+
return top.records.flatMap(record => {
|
|
352
|
+
const url = urls.get(record.id);
|
|
353
|
+
return url ? [{ id: record.id, label: recordTitle(record, 'title'), url, newTab: false, kind: 'entry' as const, description: '', className: '', attributes: {}, fields: {}, panel: null, children: [] }] : [];
|
|
354
|
+
});
|
|
355
|
+
} catch { return []; /* before setup, or without pages */ }
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Resolved menu items finished for the site and the content API: each item's meta becomes typed
|
|
360
|
+
* `fields` (media as views, blocks rendered, references with titles and URLs) through the field
|
|
361
|
+
* groups attached to menu items, and its panel pattern renders like a widget area: expanded one
|
|
362
|
+
* level, media resolved, latest entries filled, forms placed. A panel that is gone is null.
|
|
363
|
+
*/
|
|
364
|
+
export async function menuViews(cms: CmsHost, items: readonly ResolvedMenuItem[], options: { scopes?: BindingScopes; locale?: string; forms?: FormRequest; usage?: { user: boolean }; patternDrafts?: ReadonlyMap<string, readonly Block[]> } = {}): Promise<MenuItemView[]> {
|
|
365
|
+
const all = flattenResolved(items);
|
|
366
|
+
if (!all.length) return [];
|
|
367
|
+
const settings = await cms.settings.all();
|
|
368
|
+
useImageSettings(cms, settings);
|
|
369
|
+
const scopes = options.scopes ?? bindingScopes(settings);
|
|
370
|
+
const locale = options.locale ?? (await cms.languages()).default;
|
|
371
|
+
const declarations = Object.entries(fieldGroupDeclarations(cms.fieldGroupsFor({ kind: 'menus' }).flatMap(group => group.blocks), cms.blockTypes));
|
|
372
|
+
// The panels' patterns, read as the site renders patterns; a missing one leaves the item without a panel.
|
|
373
|
+
const panelIds = [...new Set(all.map(item => item.panel).filter((id): id is string => !!id))];
|
|
374
|
+
const panels = new Map<string, Block[]>();
|
|
375
|
+
if (panelIds.length) {
|
|
376
|
+
try {
|
|
377
|
+
for (const [id, record] of await cms.resource('cms/patterns').getMany(panelIds, renderer)) if (Array.isArray(record.content)) panels.set(id, record.content as Block[]);
|
|
378
|
+
} catch (error) { if (!isCmsError(error)) throw error; }
|
|
379
|
+
for (const id of panelIds) { const draft = options.patternDrafts?.get(id); if (draft) panels.set(id, [...draft]); }
|
|
380
|
+
// A panel's blocks are the pattern's own: marked as such, so Live Edit edits the pattern.
|
|
381
|
+
for (const [id, blocks] of panels) panels.set(id, blocks.map(block => fromPattern(block, id)));
|
|
382
|
+
}
|
|
383
|
+
const metaBlocks = all.flatMap(item => declarations.flatMap(([name, declaration]) => declaration.kind === 'blocks' && Array.isArray(item.meta[name]) ? item.meta[name] as Block[] : []));
|
|
384
|
+
const stored = [...[...panels.values()].flat(), ...metaBlocks];
|
|
385
|
+
const patterns = withPatternDrafts(await usedPatterns(cms, blockDocuments(stored, cms.blockTypes), stored), options.patternDrafts);
|
|
386
|
+
const expanded = new Map([...panels].map(([id, blocks]) => [id, expandPatterns(blocks, patterns)]));
|
|
387
|
+
const ids = new Set<string>();
|
|
388
|
+
for (const list of expanded.values()) for (const block of list) blockMediaIds(cms, block, ids);
|
|
389
|
+
for (const item of all) for (const [name, declaration] of declarations) {
|
|
390
|
+
const value = item.meta[name];
|
|
391
|
+
if (declaration.media && typeof value === 'string') ids.add(value);
|
|
392
|
+
if (declaration.media && Array.isArray(value)) for (const id of value) ids.add(String(id));
|
|
393
|
+
if (declaration.kind === 'blocks' && Array.isArray(value)) for (const block of expandPatterns(value as Block[], patterns)) blockMediaIds(cms, block, ids);
|
|
394
|
+
}
|
|
395
|
+
const files = cms.files && ids.size ? await cms.files.getMany([...ids]) : new Map<string, CmsFile>();
|
|
396
|
+
const richText = bodyRenderer(cms, files, patterns, options.usage);
|
|
397
|
+
const render = (block: RenderedBlock) => renderedBlock(cms, block, files, doc => richText(doc, scopes), scopes, { patterns, ...(options.usage ? { usage: options.usage } : {}) });
|
|
398
|
+
const references = await referencedRecords(cms, declarations, all.map(item => ({ id: item.id, rev: 0, createdAt: 0, updatedAt: 0, owner: null, ...item.meta })));
|
|
399
|
+
const context: FieldViewContext = { full: true, files, resizes: imageOptions(cms), terms: new Map(), termUrl: () => null, references, patterns, richText: doc => richText(doc, scopes), render };
|
|
400
|
+
const rendered: RenderedBlock[] = [];
|
|
401
|
+
const view = (item: ResolvedMenuItem): MenuItemView => {
|
|
402
|
+
const fields: Record<string, FieldView> = {};
|
|
403
|
+
for (const [name, declaration] of declarations) {
|
|
404
|
+
const typed = fieldViewOf(name, declaration, item.meta[name], locale, item.meta, context);
|
|
405
|
+
if (typed !== undefined) fields[name] = typed;
|
|
406
|
+
}
|
|
407
|
+
const panel = item.panel && expanded.has(item.panel) ? expanded.get(item.panel)!.map(block => render(block as RenderedBlock)) : null;
|
|
408
|
+
if (panel) rendered.push(...panel);
|
|
409
|
+
return { id: item.id, label: item.label, url: item.url, newTab: item.newTab, kind: item.kind, description: item.description, className: item.className, attributes: item.attributes, fields, panel, children: item.children.map(view) };
|
|
410
|
+
};
|
|
411
|
+
const views = items.map(view);
|
|
412
|
+
await withForms(cms, rendered, options.forms);
|
|
413
|
+
await withLatest(cms, rendered, locale);
|
|
414
|
+
return views;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function flattenResolved(items: readonly ResolvedMenuItem[]): ResolvedMenuItem[] {
|
|
418
|
+
return items.flatMap(item => [item, ...flattenResolved(item.children)]);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** How a site shows images: whether it resizes them, and Settings → Files. */
|
|
422
|
+
export interface ImageOptions { readonly resizes: boolean; readonly widths: readonly number[]; readonly placeholder: boolean; readonly sizes: string }
|
|
423
|
+
|
|
424
|
+
/** Each site's Settings → Files, as its last page read them; they are the same for every visitor. */
|
|
425
|
+
const IMAGE_SETTINGS = new WeakMap<CmsHost, Omit<ImageOptions, 'resizes'>>();
|
|
426
|
+
|
|
427
|
+
function useImageSettings(cms: CmsHost, settings: SiteSettings): void {
|
|
428
|
+
IMAGE_SETTINGS.set(cms, { widths: imageWidths(settings['media.imageWidths']), placeholder: settings['media.placeholder'] !== 'none', sizes: settings['media.sizes'] || '(min-width: 768px) 768px, 100vw' });
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function imageOptions(cms: CmsHost): ImageOptions {
|
|
432
|
+
return { resizes: cms.files?.resizes ?? false, ...(IMAGE_SETTINGS.get(cms) ?? { widths: IMAGE_WIDTHS, placeholder: true, sizes: '(min-width: 768px) 768px, 100vw' }) };
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** A file as themes show it: cropped through a variant when the host resizes images, with `srcset`s. */
|
|
436
|
+
export function mediaView(file: CmsFile | undefined, imageOptions: ImageOptions): MediaView | null {
|
|
437
|
+
if (!file) return null;
|
|
438
|
+
const source = { ...file, version: file.updatedAt };
|
|
439
|
+
const variants = imageOptions.resizes && transformable(file.contentType);
|
|
440
|
+
const size = variants ? editedSize(file) : null;
|
|
441
|
+
const { widths } = imageOptions;
|
|
442
|
+
const url = variants && file.edits?.crop && size ? imageUrl(source, { width: Math.min(size.width, widths[widths.length - 1]!) }) : mediaUrl(file);
|
|
443
|
+
return {
|
|
444
|
+
url, alt: file.alt, width: size?.width ?? file.width, height: size?.height ?? file.height, contentType: file.contentType, name: file.name, size: file.size, caption: file.caption,
|
|
445
|
+
srcset: variants ? imageSrcset(source, { widths }) : '',
|
|
446
|
+
placeholder: imageOptions.placeholder ? file.placeholder : null, sizes: imageOptions.sizes, focus: file.edits?.focus ?? null,
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/** Mark the first image of an entry to load at once: the featured image, or else the first image of its content, an Image block or the image behind a container. */
|
|
451
|
+
function markFirstImage(image: MediaView | null, content: readonly RenderedBlock[]): MediaView | null {
|
|
452
|
+
if (image) return { ...image, priority: true };
|
|
453
|
+
let done = false;
|
|
454
|
+
walkBlocks(content, block => {
|
|
455
|
+
if (done) return;
|
|
456
|
+
const behind = typeof block.style?.image === 'string' ? block.style.image : '';
|
|
457
|
+
const key = behind && block.media[behind]?.contentType.startsWith('image/') ? behind : block.type === 'core/image' && block.media.image ? 'image' : '';
|
|
458
|
+
if (!key) return;
|
|
459
|
+
(block.media as Record<string, MediaView>)[key] = { ...block.media[key]!, priority: true };
|
|
460
|
+
done = true;
|
|
461
|
+
});
|
|
462
|
+
return image;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* A block with its Markdown rendered, its rich text as parts (through `richText`, when given),
|
|
467
|
+
* its media resolved and its children rendered. With `scopes`, text fields show what their
|
|
468
|
+
* bindings read (`{{ $.price }}`, `{{ $site.title }}`). Markdown with block references renders
|
|
469
|
+
* as `content.<field>`: its text runs and the referenced blocks, synced patterns expanded.
|
|
470
|
+
*/
|
|
471
|
+
function renderedBlock(cms: CmsHost, block: { _id: string; type: string; data: Record<string, unknown>; layout?: RenderedBlock['layout']; style?: RenderedBlock['style']; when?: RenderedBlock['when']; children?: readonly unknown[]; pattern?: string; sourceId?: string },
|
|
472
|
+
files: ReadonlyMap<string, CmsFile>, richText?: (doc: RichTextDoc) => BodyPart[], scope?: BindingScopes, refs: { patterns?: ReadonlyMap<string, Block[]>; usage?: { user: boolean }; depth?: number } = {}): RenderedBlock {
|
|
473
|
+
const html: Record<string, string> = {};
|
|
474
|
+
const media: Record<string, MediaView> = {};
|
|
475
|
+
const icons: Record<string, BrandIcon> = {};
|
|
476
|
+
const content: Record<string, BodyPart[]> = {};
|
|
477
|
+
const resizes = imageOptions(cms);
|
|
478
|
+
const type = cms.blockTypes.get(block.type);
|
|
479
|
+
// Code keeps its text: a value put into a Custom HTML block's HTML would run as markup.
|
|
480
|
+
const bound = Object.entries(type?.fields ?? {}).filter(([, declaration]) => (declaration.kind === 'string' && !declaration.media) || (declaration.kind === 'text' && declaration.format !== 'code')).map(([key]) => key);
|
|
481
|
+
const data = scope && bound.length ? resolveBlockBindings(block.data, bound, scope) : block.data;
|
|
482
|
+
if (scope?.user && refs.usage && bound.some(key => usesUserBinding(block.data[key]))) refs.usage.user = true;
|
|
483
|
+
for (const [key, declaration] of Object.entries(type?.fields ?? {})) {
|
|
484
|
+
const entry = data[key];
|
|
485
|
+
const raw = block.data[key];
|
|
486
|
+
if (declaration.kind === 'text' && declaration.format === 'markdown' && hasBlockReference(raw) && (refs.depth ?? 0) === 0) {
|
|
487
|
+
// References are parsed from the text as written, then each run's bindings resolve: a value with quotes cannot break a tag.
|
|
488
|
+
const parsed = parsedText(cms, raw);
|
|
489
|
+
if (scope?.user && refs.usage && usesUserBinding(raw)) refs.usage.user = true;
|
|
490
|
+
const resolve = (text: string) => scope ? resolveBindings(text, scope) : text;
|
|
491
|
+
const inner = { ...refs, depth: 1 };
|
|
492
|
+
content[key] = parsed.parts.flatMap((part): BodyPart[] => {
|
|
493
|
+
if (part.kind === 'text') return part.text.trim() ? [{ kind: 'html', html: renderMarkdown(resolve(part.text)) }] : [];
|
|
494
|
+
const child = { ...part.block, _id: `${block._id}-${part.block._id}`.slice(0, 40) };
|
|
495
|
+
if (child.type === PATTERN_REFERENCE) {
|
|
496
|
+
const blocks = refs.patterns?.get(String(child.data.pattern ?? '')) ?? [];
|
|
497
|
+
return blocks.filter(entry => entry.type !== PATTERN_REFERENCE).map(entry => ({ kind: 'block' as const, block: renderedBlock(cms, prefixIds(entry, `${child._id}-`), files, richText, scope, inner) }));
|
|
498
|
+
}
|
|
499
|
+
return [{ kind: 'block', block: renderedBlock(cms, child, files, richText, scope, inner) }];
|
|
500
|
+
});
|
|
501
|
+
html[key] = parsed.parts.map(part => part.kind === 'text' ? renderMarkdown(resolve(part.text)) : '').join('');
|
|
502
|
+
} else if (declaration.kind === 'text' && declaration.format === 'markdown' && typeof entry === 'string') html[key] = renderMarkdown(entry);
|
|
503
|
+
if (declaration.kind === 'richtext' && entry && typeof entry === 'object') content[key] = richText ? richText(entry as RichTextDoc) : richTextParts(entry as RichTextDoc).filter(part => part.kind === 'html');
|
|
504
|
+
for (const id of declaration.media ? (Array.isArray(entry) ? entry : [entry]) : []) {
|
|
505
|
+
const view = mediaView(files.get(id as string), resizes);
|
|
506
|
+
if (view) media[id as string] = view;
|
|
507
|
+
}
|
|
508
|
+
// The networks a brand field links to, resolved here so the page ships only the icons it shows.
|
|
509
|
+
for (const url of declaration.brand ? (Array.isArray(entry) ? entry : [entry]) : []) {
|
|
510
|
+
const brand = typeof url === 'string' ? brandIcon(url) : null;
|
|
511
|
+
if (brand) icons[url as string] = brand;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
// Share buttons name networks, not URLs: each gets its network's icon, by name.
|
|
515
|
+
if (block.type === 'core/share') for (const network of Array.isArray(data.networks) ? data.networks as string[] : []) {
|
|
516
|
+
const brand = SHARE_BRAND_URLS[network as keyof typeof SHARE_BRAND_URLS];
|
|
517
|
+
const icon = brand ? brandIcon(brand) : null;
|
|
518
|
+
if (icon) icons[network] = icon;
|
|
519
|
+
}
|
|
520
|
+
// The files a container's background shows, resolved like a media field's.
|
|
521
|
+
for (const id of [block.style?.image, block.style?.video]) {
|
|
522
|
+
const view = typeof id === 'string' && id ? mediaView(files.get(id), resizes) : null;
|
|
523
|
+
if (view) media[id as string] = view;
|
|
524
|
+
}
|
|
525
|
+
const children = Array.isArray(block.children) ? (block.children as RenderedBlock[]).map(child => renderedBlock(cms, child, files, richText, scope, refs)) : undefined;
|
|
526
|
+
return { _id: block._id, type: block.type, data, html, media, ...(Object.keys(icons).length ? { icons } : {}), ...(Object.keys(content).length ? { content } : {}), ...(type && blockIsData(type) ? { dataOnly: true } : {}),
|
|
527
|
+
...(block.pattern ? { pattern: block.pattern, sourceId: block.sourceId ?? block._id } : {}),
|
|
528
|
+
...(block.layout ? { layout: block.layout } : {}), ...(block.style ? { style: block.style } : {}), ...(block.when ? { when: block.when } : {}), ...(children ? { children } : {}) };
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function blockMediaIds(cms: CmsHost, block: { type: string; data: Record<string, unknown>; style?: RenderedBlock['style']; children?: readonly unknown[] }, into: Set<string>): void {
|
|
532
|
+
for (const id of [block.style?.image, block.style?.video]) if (typeof id === 'string' && id) into.add(id);
|
|
533
|
+
for (const [key, declaration] of Object.entries(cms.blockTypes.get(block.type)?.fields ?? {})) {
|
|
534
|
+
const entry = block.data[key];
|
|
535
|
+
if (declaration.media && typeof entry === 'string') into.add(entry);
|
|
536
|
+
if (declaration.media && Array.isArray(entry)) for (const id of entry) into.add(id as string);
|
|
537
|
+
if (declaration.kind === 'richtext' && entry && typeof entry === 'object') docMediaIds(cms, entry as RichTextDoc, into);
|
|
538
|
+
}
|
|
539
|
+
for (const child of Array.isArray(block.children) ? block.children as RenderedBlock[] : []) blockMediaIds(cms, child, into);
|
|
540
|
+
for (const referenced of referencedBlocks(cms, block)) if (referenced.type !== PATTERN_REFERENCE) blockMediaIds(cms, referenced, into);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
function docMediaIds(cms: CmsHost, doc: RichTextDoc, into: Set<string>): void {
|
|
544
|
+
for (const node of doc.content) {
|
|
545
|
+
if (node.type === 'cmsBlock' && node.attrs) blockMediaIds(cms, node.attrs as unknown as RenderedBlock, into);
|
|
546
|
+
if (node.type === 'image' && typeof node.attrs?.mediaId === 'string') into.add(node.attrs.mediaId);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** Synced patterns the blocks and documents use, by ID: their blocks. Patterns inside patterns are not expanded. */
|
|
551
|
+
async function usedPatterns(cms: CmsHost, docs: readonly RichTextDoc[], blocks: readonly Block[] = []): Promise<Map<string, Block[]>> {
|
|
552
|
+
const all = [...docs.flatMap(doc => richTextBlocks(doc)), ...flattenBlocks(blocks)];
|
|
553
|
+
const ids = [...new Set(all.filter(block => block.type === 'core/pattern').map(block => String(block.data.pattern ?? '')))].filter(Boolean);
|
|
554
|
+
// `{{ pattern hero /}}` in text names a pattern by its slug.
|
|
555
|
+
const slugs = [...new Set(all.flatMap(block => referencedBlocks(cms, block as { type: string; data: Record<string, unknown> })).filter(block => block.type === PATTERN_REFERENCE).map(block => String(block.data.pattern ?? '')))].filter(Boolean).slice(0, 50);
|
|
556
|
+
if (!ids.length && !slugs.length) return new Map();
|
|
557
|
+
try {
|
|
558
|
+
const repository = cms.resource('cms/patterns');
|
|
559
|
+
const patterns = ids.length ? await repository.getMany(ids, renderer) : new Map<string, RecordShape>();
|
|
560
|
+
const named = slugs.length ? (await repository.list({ where: { slug: { in: slugs } }, limit: 50 }, renderer)).records : [];
|
|
561
|
+
return new Map([...[...patterns].flatMap(([id, record]) => Array.isArray(record.content) ? [[id, record.content as Block[]] as const] : []),
|
|
562
|
+
...named.flatMap(record => Array.isArray(record.content) && typeof record.slug === 'string' ? [[record.slug, record.content as Block[]] as const] : [])]);
|
|
563
|
+
} catch (error) {
|
|
564
|
+
if (isCmsError(error)) return new Map();
|
|
565
|
+
throw error;
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
/**
|
|
570
|
+
* Blocks with each Pattern block replaced by the pattern's blocks, their IDs prefixed so they
|
|
571
|
+
* stay distinct; patterns inside patterns are left out. Each expanded block remembers the
|
|
572
|
+
* pattern and its own ID there (`pattern`, `sourceId`), so Live Edit edits the pattern.
|
|
573
|
+
*/
|
|
574
|
+
function expandPatterns(blocks: readonly Block[], patterns: ReadonlyMap<string, Block[]>): Block[] {
|
|
575
|
+
return blocks.flatMap(block => {
|
|
576
|
+
if (block.type === 'core/pattern') {
|
|
577
|
+
const id = String(block.data.pattern ?? '');
|
|
578
|
+
return (patterns.get(id) ?? []).filter(inner => inner.type !== 'core/pattern').map(inner => prefixIds(fromPattern(inner, id), `${block._id}-`));
|
|
579
|
+
}
|
|
580
|
+
return [block.children ? { ...block, children: expandPatterns(block.children, patterns) } : block];
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
/** A pattern's block as a page shows it: marked with the pattern and its ID there, children too. */
|
|
585
|
+
export function fromPattern(block: Block, pattern: string): Block {
|
|
586
|
+
return { ...block, pattern, sourceId: block._id, ...(block.children ? { children: block.children.map(child => fromPattern(child, pattern)) } : {}) } as Block;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/** The patterns a page uses, with the editor's drafts of them in place of what is saved. */
|
|
590
|
+
function withPatternDrafts(patterns: Map<string, Block[]>, drafts?: ReadonlyMap<string, readonly Block[]>): Map<string, Block[]> {
|
|
591
|
+
for (const [id, blocks] of drafts ?? []) patterns.set(id, [...blocks]);
|
|
592
|
+
return patterns;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
function prefixIds(block: Block, prefix: string): Block {
|
|
596
|
+
return { ...block, _id: `${prefix}${block._id}`.slice(0, 40), ...(block.children ? { children: block.children.map(child => prefixIds(child, prefix)) } : {}) };
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/** The `?comment=` result of posting a comment, as the comment view's notice or error. */
|
|
600
|
+
export function commentResult(value: string | undefined): Pick<CommentsView, 'notice' | 'error'> {
|
|
601
|
+
if (value === 'held' || value === 'posted') return { notice: value, error: '' };
|
|
602
|
+
if (value === 'closed' || value === 'sign-in' || value === 'too-fast' || value === 'invalid' || value === 'bot') return { notice: '', error: value };
|
|
603
|
+
return { notice: '', error: '' };
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
export interface EntryViewOptions {
|
|
607
|
+
/** Bodies, blocks and comments, for an entry's own page. */
|
|
608
|
+
full?: boolean;
|
|
609
|
+
/** After posting a comment, for the message above the form. */
|
|
610
|
+
comment?: Pick<CommentsView, 'notice' | 'error'>;
|
|
611
|
+
/** The signed-in user, who comments without a name and email. */
|
|
612
|
+
user?: { name: string } | null;
|
|
613
|
+
/** The signed-in reader's role IDs, for members-only entries limited to roles. */
|
|
614
|
+
roles?: readonly string[];
|
|
615
|
+
/** IDs of entries the reader may edit: nothing of them is locked. */
|
|
616
|
+
editable?: ReadonlySet<string>;
|
|
617
|
+
/** Set when a binding reads the signed-in user, so the page is not cached for everyone. */
|
|
618
|
+
usage?: { user: boolean };
|
|
619
|
+
/** IDs of protected entries this visitor unlocked, whose content shows. */
|
|
620
|
+
unlocked?: ReadonlySet<string>;
|
|
621
|
+
/** The request, for the forms the entry places; without it they render nothing. */
|
|
622
|
+
forms?: FormRequest;
|
|
623
|
+
/** Live Edit: the editor's drafts of synced patterns, in place of what is saved. */
|
|
624
|
+
patternDrafts?: ReadonlyMap<string, readonly Block[]>;
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/** Fields a details list leaves out: core fields themes show on their own, and internal ones. */
|
|
628
|
+
const NOT_DETAILS = new Set(['title', 'slug', 'status', 'publishedAt', 'parent', 'menuOrder', 'excerpt', 'summary', 'sticky', 'seo', 'locale', 'translationGroup', 'commentsOpen', 'template']);
|
|
629
|
+
/** Fields entry views leave out: search settings have their own head tags; translations their own links. */
|
|
630
|
+
const NOT_FIELDS = new Set(['seo', 'translationGroup']);
|
|
631
|
+
|
|
632
|
+
/** The titles and URLs of the records reference fields point at, by `<target>:<id>`. Records visitors cannot read are left out. */
|
|
633
|
+
async function referencedRecords(cms: CmsHost, fields: readonly (readonly [string, FieldDeclaration])[], records: readonly RecordShape[]): Promise<Map<string, EntryReference>> {
|
|
634
|
+
const byTarget = new Map<string, Set<string>>();
|
|
635
|
+
for (const [name, declaration] of fields) {
|
|
636
|
+
if (declaration.kind !== 'reference' || !declaration.target) continue;
|
|
637
|
+
for (const record of records) if (typeof record[name] === 'string' && record[name]) byTarget.set(declaration.target, (byTarget.get(declaration.target) ?? new Set()).add(record[name] as string));
|
|
638
|
+
}
|
|
639
|
+
const found = new Map<string, EntryReference>();
|
|
640
|
+
for (const [target, ids] of byTarget) {
|
|
641
|
+
try {
|
|
642
|
+
const resource = cms.resourceById(target);
|
|
643
|
+
const rows = await cms.resource(target).getMany([...ids].slice(0, 100), visitor);
|
|
644
|
+
const collection = target.startsWith('cms/') ? cms.collections().find(entry => entry.name === target.slice(4)) : undefined;
|
|
645
|
+
const urls = collection ? await cms.entryUrls(collection, [...rows.values()]) : new Map<string, string | null>();
|
|
646
|
+
for (const row of rows.values()) found.set(`${target}:${row.id}`, { id: row.id, title: recordTitle(row, resource.titleField ?? 'title'), url: urls.get(row.id) ?? null });
|
|
647
|
+
} catch (error) { if (!isCmsError(error)) throw error; }
|
|
648
|
+
}
|
|
649
|
+
return found;
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
/** A rich text or Markdown field: part of the entry's content, rendered as one `core/richtext` block. */
|
|
653
|
+
function isTextField(declaration: FieldDeclaration): boolean {
|
|
654
|
+
return declaration.kind === 'richtext' || (declaration.kind === 'text' && declaration.format === 'markdown');
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/** A rich text or Markdown field as a block of the entry's content: `field` names it, so the site editor opens the field. */
|
|
658
|
+
function textBlock(field: string, parts: readonly BodyPart[]): RenderedBlock {
|
|
659
|
+
return { _id: `field-${field}`.slice(0, 40), type: 'core/richtext', data: {}, html: {}, media: {}, content: { text: parts }, field };
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/** Whether an entry has a password visitors must type. */
|
|
663
|
+
export function isProtected(record: RecordShape): boolean {
|
|
664
|
+
return typeof record.password === 'string' && record.password.length > 0;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/** Whether only signed-in users read an entry's content. */
|
|
668
|
+
export function isMembersOnly(record: RecordShape): boolean {
|
|
669
|
+
return record.membersOnly === true;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
/** The roles a members-only entry is for; empty for every signed-in user. */
|
|
673
|
+
export function memberRoles(record: RecordShape): string[] {
|
|
674
|
+
return Array.isArray(record.memberRoles) ? record.memberRoles.filter((role): role is string => typeof role === 'string' && role !== '') : [];
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
/** Who reads an entry: signed in or not, with which role IDs, and whether they may edit it. */
|
|
678
|
+
export interface EntryReader {
|
|
679
|
+
readonly signedIn: boolean;
|
|
680
|
+
readonly roles?: readonly string[];
|
|
681
|
+
/** May edit the entry: nothing is locked for them. */
|
|
682
|
+
readonly editor?: boolean;
|
|
683
|
+
/** IDs of protected entries this visitor unlocked with their password. */
|
|
684
|
+
readonly unlocked?: ReadonlySet<string> | undefined;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Why a reader cannot read an entry's content: `password` for a protected entry they have not
|
|
689
|
+
* unlocked, `members` for a members-only entry and a reader who is not signed in or has none
|
|
690
|
+
* of its roles; null when they can. A password wins: signing in does not unlock a protected entry.
|
|
691
|
+
*/
|
|
692
|
+
export function entryLock(record: RecordShape, reader: EntryReader): 'password' | 'members' | null {
|
|
693
|
+
if (reader.editor) return null;
|
|
694
|
+
if (isProtected(record) && !reader.unlocked?.has(record.id)) return 'password';
|
|
695
|
+
if (!isMembersOnly(record)) return null;
|
|
696
|
+
if (!reader.signedIn) return 'members';
|
|
697
|
+
const roles = memberRoles(record);
|
|
698
|
+
return roles.length && !roles.some(role => reader.roles?.includes(role)) ? 'members' : null;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/**
|
|
702
|
+
* Search results a signed-in dashboard user may see: a locked entry (`entryLock`) that matched
|
|
703
|
+
* would tell what its content says, so only entries open to them stay, as the content API's search.
|
|
704
|
+
*/
|
|
705
|
+
export function openMatches(cms: CmsHost, resourceId: string, records: readonly RecordShape[], principal: Principal): RecordShape[] {
|
|
706
|
+
const repository = cms.resource(resourceId);
|
|
707
|
+
const signedIn = principal.kind === 'user';
|
|
708
|
+
return records.filter(record => !entryLock(record, { editor: signedIn && repository.canUpdate(record, principal), signedIn, roles: signedIn ? principal.roles : [] }));
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/**
|
|
712
|
+
* Why the request's reader cannot read the entry (`entryLock`), from its principal and the
|
|
713
|
+
* entry's unlock cookie, as the entry's page decides: for the comments API and form.
|
|
714
|
+
*/
|
|
715
|
+
export async function requestLock(cms: CmsHost, record: RecordShape, resourceId: string, principal: Principal, cookie: string | undefined): Promise<'password' | 'members' | null> {
|
|
716
|
+
const editor = principal.kind === 'user' && cms.resource(resourceId).canUpdate(record, principal);
|
|
717
|
+
const unlocked = isProtected(record) && cookie !== undefined && cookie === await unlockToken(record);
|
|
718
|
+
return entryLock(record, { signedIn: principal.kind === 'user', roles: principal.kind === 'user' ? principal.roles : [], editor, unlocked: unlocked ? new Set([record.id]) : undefined });
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/**
|
|
722
|
+
* The entry a theme's `$` bindings read (widgets, theme options): whole for a reader the site's
|
|
723
|
+
* gate lets in, less its password, else the reader's view (`lockedView`), so a binding can never
|
|
724
|
+
* print a locked entry's content or anyone's password.
|
|
725
|
+
*/
|
|
726
|
+
export async function bindableEntry(cms: CmsHost, collection: string, record: RecordShape, principal: Principal, cookie: string | undefined): Promise<RecordShape> {
|
|
727
|
+
const resource = `cms/${collection}`;
|
|
728
|
+
if (await requestLock(cms, record, resource, principal, cookie)) return lockedView(record, cms.resourceById(resource).fields);
|
|
729
|
+
const { password: _password, ...open } = record;
|
|
730
|
+
return open as RecordShape;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/** The cookie that remembers an unlocked entry, and its value: a digest of the entry and its password. */
|
|
734
|
+
export function unlockCookie(record: RecordShape): string {
|
|
735
|
+
return `cms_unlock_${record.id}`;
|
|
736
|
+
}
|
|
737
|
+
export async function unlockToken(record: RecordShape): Promise<string> {
|
|
738
|
+
const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`cms-unlock:${record.id}:${String(record.password)}`)));
|
|
739
|
+
return [...bytes].map(byte => byte.toString(16).padStart(2, '0')).join('');
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/** What typed field views are built from: the files, terms and references already read, and how rich text and blocks render. */
|
|
743
|
+
interface FieldViewContext {
|
|
744
|
+
/** Bodies and blocks are included; lists leave them out. */
|
|
745
|
+
readonly full: boolean;
|
|
746
|
+
readonly files: ReadonlyMap<string, CmsFile>;
|
|
747
|
+
readonly resizes: ImageOptions;
|
|
748
|
+
readonly terms: ReadonlyMap<string, TermShape>;
|
|
749
|
+
readonly termUrl: (term: TermShape, locale: string) => string | null;
|
|
750
|
+
readonly references: ReadonlyMap<string, EntryReference>;
|
|
751
|
+
readonly patterns: ReadonlyMap<string, Block[]>;
|
|
752
|
+
/** Rich text as body parts, its bindings read against `scope`. */
|
|
753
|
+
readonly richText: (doc: RichTextDoc, scope: Readonly<Record<string, unknown>>) => BodyPart[];
|
|
754
|
+
/** A block rendered, its bindings read against `scope`. */
|
|
755
|
+
readonly render: (block: RenderedBlock, scope: Readonly<Record<string, unknown>>) => RenderedBlock;
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
/**
|
|
759
|
+
* A field's typed value (`FieldView`) for entry views and menu items; undefined leaves it out
|
|
760
|
+
* (rich text, Markdown and blocks in lists, vectors). `scope` is what the field's bindings read.
|
|
761
|
+
*/
|
|
762
|
+
function fieldViewOf(name: string, declaration: FieldDeclaration, value: unknown, locale: string, scope: Readonly<Record<string, unknown>>, context: FieldViewContext): FieldView | undefined {
|
|
763
|
+
const { full, files, resizes, terms, termUrl, references, patterns } = context;
|
|
764
|
+
if (declaration.kind === 'vector' || declaration.kind === 'bigint') return undefined;
|
|
765
|
+
if ((declaration.kind === 'richtext' || declaration.kind === 'blocks' || (declaration.kind === 'text' && declaration.format === 'markdown')) && !full) return undefined;
|
|
766
|
+
if (value === undefined || value === null || value === '') return null;
|
|
767
|
+
// A multiple field is the list of its kind's views; its rich text and Markdown items are one block each.
|
|
768
|
+
if (declaration.multiple && !declaration.taxonomy && !declaration.media && Array.isArray(value)) {
|
|
769
|
+
const items = value.map((item, index) => fieldViewOf(`${name}-${index + 1}`, { ...declaration, multiple: false }, item, locale, scope, context));
|
|
770
|
+
if (items.some(item => item === undefined)) return undefined;
|
|
771
|
+
return declaration.kind === 'richtext' || (declaration.kind === 'text' && declaration.format === 'markdown')
|
|
772
|
+
? items.flatMap(item => (item as readonly RenderedBlock[] | null) ?? []).map(block => ({ ...block, field: name }))
|
|
773
|
+
: items.filter((item): item is Exclude<FieldView, null> => item !== null) as FieldView;
|
|
774
|
+
}
|
|
775
|
+
if (declaration.taxonomy) return ((value as string[] | undefined) ?? []).map(id => terms.get(id)).filter((term): term is TermShape => !!term).map((term): TermLink => ({ name: term.name, url: termUrl(term, locale), icon: term.icon }));
|
|
776
|
+
if (declaration.media && Array.isArray(value)) return value.map(id => mediaView(files.get(String(id)), resizes)).filter((view): view is MediaView => !!view);
|
|
777
|
+
if (declaration.media) return mediaView(files.get(String(value)), resizes);
|
|
778
|
+
if (declaration.kind === 'reference') return references.get(`${declaration.target}:${String(value)}`) ?? null;
|
|
779
|
+
if (declaration.kind === 'richtext') return typeof value === 'object' ? [textBlock(name, context.richText(value as RichTextDoc, scope))] : null;
|
|
780
|
+
if (declaration.kind === 'text' && declaration.format === 'markdown') {
|
|
781
|
+
// Block references render through a paragraph of the text, which parses them.
|
|
782
|
+
if (hasBlockReference(value)) return [textBlock(name, context.render({ _id: name, type: 'core/paragraph', data: { text: value }, html: {}, media: {} }, scope).content?.text ?? [])];
|
|
783
|
+
return [textBlock(name, [{ kind: 'html', html: renderMarkdown(String(value)) }])];
|
|
784
|
+
}
|
|
785
|
+
if (declaration.kind === 'blocks') return Array.isArray(value) ? (expandPatterns(value as Block[], patterns) as RenderedBlock[]).map(block => context.render(block, scope)) : [];
|
|
786
|
+
return value as FieldView;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/** Views of entries: content rendered with its blocks, patterns and media, authors, URLs, term links, typed fields and comments. */
|
|
790
|
+
/** Minutes to read a text at 200 words a minute: at least 1 when there are words, 0 when there are none. */
|
|
791
|
+
export function readingTime(text: string): number {
|
|
792
|
+
const words = text.trim() ? text.trim().split(/\s+/).length : 0;
|
|
793
|
+
return words ? Math.max(1, Math.round(words / 200)) : 0;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
export async function entryViews(cms: CmsHost, collection: CollectionDefinition, records: readonly RecordShape[], options: EntryViewOptions = {}): Promise<EntryView[]> {
|
|
797
|
+
const resource = cms.resourceById(`cms/${collection.name}`);
|
|
798
|
+
const settings = await cms.settings.all();
|
|
799
|
+
useImageSettings(cms, settings);
|
|
800
|
+
const languages = await cms.languages();
|
|
801
|
+
const resizes = imageOptions(cms);
|
|
802
|
+
const fields = Object.entries(resource.fields);
|
|
803
|
+
// The entry's content is its blocks fields and its rich text and Markdown fields, rendered into `entry.content` in declared order; `entry.fields` keeps them apart.
|
|
804
|
+
const contentFields = fields.filter(([, declaration]) => (declaration.kind === 'blocks' && !declaration.form) || isTextField(declaration));
|
|
805
|
+
const blocksFields = contentFields.filter(([, declaration]) => declaration.kind === 'blocks');
|
|
806
|
+
const imageField = fields.find(([, declaration]) => declaration.kind === 'string' && declaration.media);
|
|
807
|
+
const excerptField = fields.find(([name, declaration]) => name === 'excerpt' && declaration.kind === 'text');
|
|
808
|
+
const docs = options.full ? records.flatMap(record => [
|
|
809
|
+
...fields.filter(([, declaration]) => declaration.kind === 'richtext').map(([name]) => record[name]).filter((value): value is RichTextDoc => !!value && typeof value === 'object'),
|
|
810
|
+
...fields.filter(([, declaration]) => declaration.kind === 'blocks').flatMap(([name]) => Array.isArray(record[name]) ? blockDocuments(record[name] as Block[], cms.blockTypes) : []),
|
|
811
|
+
]) : [];
|
|
812
|
+
const stored = (record: RecordShape) => blocksFields.flatMap(([name]) => Array.isArray(record[name]) ? record[name] as Block[] : []);
|
|
813
|
+
const patterns = withPatternDrafts(await usedPatterns(cms, docs, options.full ? records.flatMap(stored) : []), options.patternDrafts);
|
|
814
|
+
/**
|
|
815
|
+
* The content's plain text for an excerpt: every content field in order, 4,000 characters at most.
|
|
816
|
+
* Bindings resolve against the entry alone: excerpts and descriptions are the same for every visitor.
|
|
817
|
+
*/
|
|
818
|
+
const contentPlain = (record: RecordShape): string => {
|
|
819
|
+
let text = '';
|
|
820
|
+
for (const [name, declaration] of contentFields) {
|
|
821
|
+
const value = record[name];
|
|
822
|
+
if (text.length >= 4000) break;
|
|
823
|
+
if (declaration.kind === 'blocks' && Array.isArray(value)) text += ` ${blocksPlain(value as Block[], cms.blockTypes, doc => richTextPlain(doc), 4000 - text.length)}`;
|
|
824
|
+
else if (declaration.kind === 'richtext' && value && typeof value === 'object') text += ` ${richTextPlain(value as RichTextDoc)}`;
|
|
825
|
+
else if (declaration.kind === 'text' && typeof value === 'string') text += ` ${value}`;
|
|
826
|
+
}
|
|
827
|
+
return resolveBindings(text.trim(), bindingScopes(settings, { entry: record, user: null })).slice(0, 4000);
|
|
828
|
+
};
|
|
829
|
+
const mediaIds = new Set<string>();
|
|
830
|
+
for (const record of records) for (const [name, declaration] of fields) {
|
|
831
|
+
const value = record[name];
|
|
832
|
+
if (declaration.media && typeof value === 'string') mediaIds.add(value);
|
|
833
|
+
if (declaration.media && Array.isArray(value)) for (const id of value) mediaIds.add(id as string);
|
|
834
|
+
if (!options.full) continue;
|
|
835
|
+
if (declaration.kind === 'blocks' && Array.isArray(value)) for (const block of expandPatterns(value as Block[], patterns) as RenderedBlock[]) blockMediaIds(cms, block, mediaIds);
|
|
836
|
+
}
|
|
837
|
+
for (const doc of docs) docMediaIds(cms, doc, mediaIds);
|
|
838
|
+
if (options.full) for (const list of patterns.values()) for (const block of list as RenderedBlock[]) blockMediaIds(cms, block, mediaIds);
|
|
839
|
+
const files = cms.files ? await cms.files.getMany([...mediaIds]) : new Map<string, CmsFile>();
|
|
840
|
+
// Articles name their authors; with author pages on, the names link to the authors' pages, so the users need slugs.
|
|
841
|
+
const articles = ARTICLE_TYPES.has(collection.schema?.type ?? 'WebPage');
|
|
842
|
+
const found = articles ? await cms.users.getMany([...new Set(records.flatMap(record => entryAuthors(record)))]) : new Map<string, CmsUser>();
|
|
843
|
+
const owners = articles && settings['seo.authorPages'] ? await cms.users.withSlugs(found) : found;
|
|
844
|
+
const references = await referencedRecords(cms, fields, records);
|
|
845
|
+
const taxonomyFields = fields.filter(([, declaration]) => declaration.taxonomy);
|
|
846
|
+
const terms = await cms.taxonomies.getMany(records.flatMap(record => taxonomyFields.flatMap(([name]) => (record[name] as string[] | undefined) ?? [])));
|
|
847
|
+
const urls = await cms.entryUrls(collection, records);
|
|
848
|
+
const termUrl = (term: TermShape, locale: string) => {
|
|
849
|
+
const taxonomy = cms.taxonomies.declaration(term.taxonomy);
|
|
850
|
+
return taxonomy.path ? `${localePrefix(languages, locale)}/${taxonomy.path}/${term.slug}` : null;
|
|
851
|
+
};
|
|
852
|
+
// Blocks bind to the entry's own fields (`{{ $.price }}`), so each record renders with itself as the scope.
|
|
853
|
+
const parts = bodyRenderer(cms, files, patterns, options.usage);
|
|
854
|
+
const render = (block: RenderedBlock, record: RecordShape) => {
|
|
855
|
+
const scopes = bindingScopes(settings, { entry: record, user: options.user ?? null });
|
|
856
|
+
return renderedBlock(cms, block, files, doc => parts(doc, scopes), scopes, { patterns, ...(options.usage ? { usage: options.usage } : {}) });
|
|
857
|
+
};
|
|
858
|
+
const context: FieldViewContext = {
|
|
859
|
+
full: options.full === true, files, resizes, terms, termUrl, references, patterns,
|
|
860
|
+
richText: (doc, scope) => parts(doc, bindingScopes(settings, { entry: scope, user: options.user ?? null })),
|
|
861
|
+
render: (block, scope) => render(block, scope as RecordShape),
|
|
862
|
+
};
|
|
863
|
+
const views: EntryView[] = [];
|
|
864
|
+
for (const record of records) {
|
|
865
|
+
const locale = typeof record.locale === 'string' ? record.locale : languages.default;
|
|
866
|
+
// A protected entry a visitor has not unlocked, or a members-only one and a visitor not signed in, shows its title alone.
|
|
867
|
+
const lock = entryLock(record, { unlocked: options.unlocked, signedIn: Boolean(options.user), roles: options.roles ?? [], editor: options.editable?.has(record.id) === true });
|
|
868
|
+
const locked = lock !== null;
|
|
869
|
+
// A members-only entry reads differently for signed-in users: the page is theirs alone.
|
|
870
|
+
if (isMembersOnly(record) && options.usage) options.usage.user = true;
|
|
871
|
+
const typed: Record<string, FieldView> = {};
|
|
872
|
+
for (const [name, declaration] of fields) {
|
|
873
|
+
// A locked entry shows nothing of its fields; the password itself is never a field of the view.
|
|
874
|
+
if (NOT_FIELDS.has(name) || name === 'password' || locked) continue;
|
|
875
|
+
const view = fieldViewOf(name, declaration, record[name], locale, record, context);
|
|
876
|
+
if (view !== undefined) typed[name] = view;
|
|
877
|
+
}
|
|
878
|
+
// Each content field is rendered once, for `content` and for `fields`; the headings get anchors and a table of contents its list.
|
|
879
|
+
const parts = options.full && !locked ? contentFields.map(([name]) => [name, ((typed[name] as readonly RenderedBlock[] | null | undefined) ?? []).length] as const).filter(([, count]) => count > 0) : [];
|
|
880
|
+
const content = withHeadingAnchors(parts.flatMap(([name]) => typed[name] as readonly RenderedBlock[]));
|
|
881
|
+
// `fields` reads these from `content` (`withContentFields`), so the page's state carries the blocks once.
|
|
882
|
+
for (const [name] of parts) delete typed[name];
|
|
883
|
+
const details = options.full ? fields.filter(([name, declaration]) => !NOT_DETAILS.has(name) && !declaration.taxonomy && !declaration.media
|
|
884
|
+
&& !['text', 'blocks', 'richtext', 'json', 'reference', 'vector', 'bigint'].includes(declaration.kind) && typed[name] !== null && typed[name] !== undefined && typed[name] !== '' && !(Array.isArray(typed[name]) && !(typed[name] as unknown[]).length))
|
|
885
|
+
.map(([name, declaration]) => ({ label: declaration.label ?? name, value: displayValue(declaration.kind, typed[name], settings) })) : [];
|
|
886
|
+
const featured = imageField ? mediaView(files.get(String(record[imageField[0]] ?? '')), resizes) : null;
|
|
887
|
+
views.push(withContentFields({
|
|
888
|
+
id: record.id, title: recordTitle(record, 'title'), url: urls.get(record.id) ?? null, collection: collection.name, kind: collection.singular,
|
|
889
|
+
date: typeof record.publishedAt === 'number' ? formatSiteDate(record.publishedAt, settings) : '',
|
|
890
|
+
updated: collection.publishable === false ? '' : formatSiteDate(record.updatedAt, settings),
|
|
891
|
+
readingTime: locked ? 0 : readingTime(contentPlain(record)),
|
|
892
|
+
authors: articles ? entryAuthors(record).map(id => owners.get(id)).filter(user => user !== undefined)
|
|
893
|
+
.map(user => ({ name: user.name, url: settings['seo.authorPages'] ? authorUrl(user.slug, localePrefix(languages, locale)) : null, avatar: user.avatar })) : [],
|
|
894
|
+
excerpt: locked ? '' : excerptField && record.excerpt ? String(record.excerpt) : typeof record.summary === 'string' && record.summary ? excerptOf(record.summary, 40) : excerptOf(contentPlain(record), 40),
|
|
895
|
+
summary: locked || typeof record.summary !== 'string' ? '' : record.summary,
|
|
896
|
+
content,
|
|
897
|
+
contentFields: parts,
|
|
898
|
+
image: options.full && settings['media.eagerFirstImage'] && records.length === 1 ? markFirstImage(featured, content) : featured,
|
|
899
|
+
terms: taxonomyFields.map(([name, declaration]) => ({
|
|
900
|
+
label: cms.taxonomies.declaration(declaration.taxonomy!).label,
|
|
901
|
+
terms: ((record[name] as string[] | undefined) ?? []).map(id => terms.get(id)).filter((term): term is TermShape => !!term).map(term => ({ name: term.name, url: termUrl(term, locale), icon: term.icon })),
|
|
902
|
+
})),
|
|
903
|
+
fields: typed,
|
|
904
|
+
details,
|
|
905
|
+
template: typeof record.template === 'string' && record.template ? record.template : null,
|
|
906
|
+
locale,
|
|
907
|
+
comments: options.full && collection.comments && !locked && cms.discussions(settings) ? await commentsView(cms, collection, record, urls.get(record.id) ?? '/', settings, options) : null,
|
|
908
|
+
locked: lock,
|
|
909
|
+
}));
|
|
910
|
+
if (options.full && !locked) {
|
|
911
|
+
// Active plugins change the title and excerpt, and add blocks around the content, through `cms.site.entry-view`.
|
|
912
|
+
const parts = await entryViewParts(cms, collection, record, views.at(-1)!, Boolean(options.user));
|
|
913
|
+
if (parts) {
|
|
914
|
+
const view = views.at(-1)!;
|
|
915
|
+
const around = (blocks: readonly Block[]) => (expandPatterns(blocks, patterns) as RenderedBlock[]).map(block => render(block, record));
|
|
916
|
+
content.unshift(...around(parts.before));
|
|
917
|
+
content.push(...around(parts.after));
|
|
918
|
+
views[views.length - 1] = { ...view, title: parts.title, excerpt: parts.excerpt };
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
if (options.full) {
|
|
922
|
+
await withForms(cms, content, options.forms);
|
|
923
|
+
await withLatest(cms, content, locale, { exclude: record.id });
|
|
924
|
+
}
|
|
925
|
+
}
|
|
926
|
+
return views;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
/**
|
|
930
|
+
* The `cms.site.entry-view` filters' changes to a full entry view, checked: a title and excerpt
|
|
931
|
+
* of bounded text, and valid blocks of known types other than `core/html`, at most ten each side.
|
|
932
|
+
* Null without a change, or when a filter failed or returned something else.
|
|
933
|
+
*/
|
|
934
|
+
export async function entryViewParts(cms: CmsHost, collection: CollectionDefinition, record: RecordShape, view: EntryView, signedIn: boolean): Promise<EntryViewParts | null> {
|
|
935
|
+
const original: EntryViewParts = { title: view.title, excerpt: view.excerpt, before: [], after: [] };
|
|
936
|
+
const { password: _password, ...visible } = record;
|
|
937
|
+
const changed = await cms.hooks.applyFilters(siteEntryView, original, { collection: collection.name, id: record.id, url: view.url, record: visible as RecordShape, signedIn }).catch(() => original);
|
|
938
|
+
if (changed === original || !changed || typeof changed !== 'object') return null;
|
|
939
|
+
const blocks = (value: unknown): Block[] => {
|
|
940
|
+
if (!Array.isArray(value) || !value.length || value.length > 10 || JSON.stringify(value).length > 64_000) return [];
|
|
941
|
+
const { blocks: valid, errors } = validateBlocks(value as Block[], cms.blockTypes);
|
|
942
|
+
return Object.keys(errors).length || flattenBlocks(valid).some(block => ENTRY_VIEW_REFUSED_BLOCKS.has(block.type)) ? [] : valid;
|
|
943
|
+
};
|
|
944
|
+
const text = (value: unknown, fallback: string, max: number) => typeof value === 'string' ? value.slice(0, max) : fallback;
|
|
945
|
+
return { title: text(changed.title, view.title, 300) || view.title, excerpt: text(changed.excerpt, view.excerpt, 1000), before: blocks(changed.before), after: blocks(changed.after) };
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
/** Comment text as escaped paragraphs, with line breaks kept. */
|
|
949
|
+
function commentHtml(text: string): string {
|
|
950
|
+
return text.split(/\n{2,}/).map(paragraph => `<p>${escapeHtml(paragraph).replaceAll('\n', '<br>')}</p>`).join('');
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/** An entry's approved comments as a thread, and the form when comments are open. */
|
|
954
|
+
async function commentsView(cms: CmsHost, collection: CollectionDefinition, record: RecordShape, url: string, settings: SiteSettings, options: EntryViewOptions): Promise<CommentsView> {
|
|
955
|
+
const open = cms.commentsOpen(collection, record, settings);
|
|
956
|
+
let comments: CommentShape[] = [];
|
|
957
|
+
let users = new Map<string, CmsUser>();
|
|
958
|
+
// The entry still shows when its comments or their authors cannot be read.
|
|
959
|
+
try {
|
|
960
|
+
comments = await cms.comments.forEntry(`cms/${collection.name}`, record.id);
|
|
961
|
+
users = await cms.users.getMany(comments.map(comment => comment.userId).filter((id): id is string => !!id));
|
|
962
|
+
} catch (error) {
|
|
963
|
+
comments = [];
|
|
964
|
+
console.warn(`[cms] the comments of ${collection.name}/${record.id} were left off the page: ${error instanceof Error ? error.message : String(error)}`);
|
|
965
|
+
}
|
|
966
|
+
const depth = settings['discussion.threadDepth'];
|
|
967
|
+
const byParent = new Map<string | null, CommentShape[]>();
|
|
968
|
+
const known = new Set(comments.map(comment => comment.id));
|
|
969
|
+
// Replies to comments that are no longer shown move to the top level.
|
|
970
|
+
for (const comment of comments) {
|
|
971
|
+
const parent = comment.parentId && known.has(comment.parentId) ? comment.parentId : null;
|
|
972
|
+
byParent.set(parent, [...(byParent.get(parent) ?? []), comment]);
|
|
973
|
+
}
|
|
974
|
+
const thread = (parent: string | null, level: number): CommentView[] => (byParent.get(parent) ?? []).map(comment => ({
|
|
975
|
+
id: comment.id, author: comment.userId ? users.get(comment.userId)?.name ?? comment.authorName : comment.authorName || __('Anonymous'),
|
|
976
|
+
authorUrl: /^https?:\/\//.test(comment.authorUrl) ? comment.authorUrl : null,
|
|
977
|
+
avatar: comment.userId ? users.get(comment.userId)?.avatar ?? null : null,
|
|
978
|
+
date: formatSiteDate(comment.createdAt, settings, { time: settings['general.timeFormat'] }),
|
|
979
|
+
html: commentHtml(comment.content),
|
|
980
|
+
replies: level < depth ? thread(comment.id, level + 1) : [],
|
|
981
|
+
replyable: open && level < depth,
|
|
982
|
+
}));
|
|
983
|
+
const siteKey = env('TURNSTILE_SITE_KEY', '');
|
|
984
|
+
return {
|
|
985
|
+
open, count: comments.length, items: thread(null, 1), notice: options.comment?.notice ?? '', error: options.comment?.error ?? '',
|
|
986
|
+
form: open ? {
|
|
987
|
+
action: '/api/cms/comments', collection: collection.name, entry: record.id, userName: options.user?.name ?? '',
|
|
988
|
+
requireNameEmail: settings['discussion.requireNameEmail'], requireSignIn: settings['discussion.requireSignIn'] && !options.user,
|
|
989
|
+
signInUrl: `/auth/login?next=${encodeURIComponent(url)}`,
|
|
990
|
+
turnstileSiteKey: siteKey && env('TURNSTILE_SECRET_KEY', '') ? siteKey : null,
|
|
991
|
+
} : null,
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
function displayValue(kind: string, value: unknown, settings: SiteSettings): string {
|
|
996
|
+
if (kind === 'boolean') return value ? 'Yes' : 'No';
|
|
997
|
+
if (kind === 'datetime' && typeof value === 'number') return formatSiteDate(value, settings, { time: settings['general.timeFormat'] });
|
|
998
|
+
if (kind === 'number' && typeof value === 'number') return value.toLocaleString('en-US');
|
|
999
|
+
if (Array.isArray(value)) return value.join(', ');
|
|
1000
|
+
return String(value);
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
/** Published entries newest first, sticky posts first on the first page, in one language. */
|
|
1004
|
+
export async function archive(cms: CmsHost, collection: CollectionDefinition, page: number, options: { where?: { [field: string]: FieldFilter }; base: string; perPage?: number; locale?: string }): Promise<Pick<ArchiveView, 'entries' | 'paging'>> {
|
|
1005
|
+
const perPage = options.perPage ?? await cms.settings.get('reading.postsPerPage');
|
|
1006
|
+
const languages = await cms.languages();
|
|
1007
|
+
const repository = cms.resource(`cms/${collection.name}`);
|
|
1008
|
+
const publishable = collection.publishable !== false;
|
|
1009
|
+
const where = { ...(publishable ? { status: 'published' } : {}), ...localeWhere(languages, options.locale ?? languages.default), ...(options.where ?? {}) };
|
|
1010
|
+
const order = publishable ? { field: 'publishedAt', direction: 'desc' as const } : { field: 'title', direction: 'asc' as const };
|
|
1011
|
+
const [list, total] = await Promise.all([
|
|
1012
|
+
repository.list({ where, order, limit: Math.min(perPage, 100), offset: Math.min((page - 1) * perPage, 10_000) }, visitor),
|
|
1013
|
+
repository.count({ where }, visitor),
|
|
1014
|
+
]);
|
|
1015
|
+
let records = [...list.records];
|
|
1016
|
+
if (page === 1 && collection.name === 'posts' && !options.where) records = [...records.filter(record => record.sticky === true), ...records.filter(record => record.sticky !== true)];
|
|
1017
|
+
return { entries: await entryViews(cms, collection, records), paging: { page, pages: Math.max(1, Math.ceil(total / perPage)), base: options.base } };
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
export type Resolved =
|
|
1021
|
+
| { kind: 'entry'; collection: CollectionDefinition; record: RecordShape; locale: string }
|
|
1022
|
+
| { kind: 'archive'; collection: CollectionDefinition; locale: string }
|
|
1023
|
+
| { kind: 'term'; term: TermShape; ancestors: TermShape[]; locale: string }
|
|
1024
|
+
| { kind: 'home'; locale: string }
|
|
1025
|
+
| { kind: 'search'; locale: string }
|
|
1026
|
+
| { kind: 'author'; user: CmsUser; locale: string }
|
|
1027
|
+
| { kind: 'redirect'; url: string; status?: 301 | 302 | 307 | 308 }
|
|
1028
|
+
| { kind: 'gone' }
|
|
1029
|
+
| { kind: 'none'; locale: string };
|
|
1030
|
+
|
|
1031
|
+
/**
|
|
1032
|
+
* What a site path names: a language's home page, a collection archive or entry, a term
|
|
1033
|
+
* archive, or a nested page. Paths of other languages start with their code (`/fr/...`).
|
|
1034
|
+
* Entries answer only at their own URL; other paths to them redirect there.
|
|
1035
|
+
*/
|
|
1036
|
+
export async function resolvePath(cms: CmsHost, segments: readonly string[]): Promise<Resolved> {
|
|
1037
|
+
const languages = await cms.languages();
|
|
1038
|
+
// Both URL modes take the default language's code, so links from the other mode redirect.
|
|
1039
|
+
const prefixed = languages.multilingual && segments.length > 0 && languages.all.includes(segments[0]!);
|
|
1040
|
+
const locale = prefixed ? segments[0]! : languages.default;
|
|
1041
|
+
const rest = prefixed ? segments.slice(1) : segments;
|
|
1042
|
+
const resolved = await resolveIn(cms, languages, locale, rest, segments);
|
|
1043
|
+
// Pages other than entries (which redirect to their own URL) move to their language's prefix.
|
|
1044
|
+
// The default language can change, so these redirects are temporary.
|
|
1045
|
+
const prefix = localePrefix(languages, locale);
|
|
1046
|
+
if (['home', 'archive', 'term', 'author', 'search'].includes(resolved.kind) && prefix !== (prefixed ? `/${segments[0]}` : '')) {
|
|
1047
|
+
return { kind: 'redirect', url: `${prefix}/${rest.join('/')}`.replace(/\/$/, '') || '/', status: 302 };
|
|
1048
|
+
}
|
|
1049
|
+
return resolved;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
async function resolveIn(cms: CmsHost, languages: SiteLanguages, locale: string, rest: readonly string[], segments: readonly string[]): Promise<Resolved> {
|
|
1053
|
+
const prefixed = rest.length < segments.length;
|
|
1054
|
+
// `/` and `/<language>` are home pages.
|
|
1055
|
+
if (!rest.length) return { kind: 'home', locale };
|
|
1056
|
+
if (prefixed && rest.length === 1 && rest[0] === 'search') return { kind: 'search', locale };
|
|
1057
|
+
if (rest.some(segment => !/^[a-z0-9-]{1,200}$/.test(segment))) return { kind: 'none', locale };
|
|
1058
|
+
const path = rest.join('/');
|
|
1059
|
+
// Collections served under a path: /<path> is the archive, /<path>/<slug> an entry.
|
|
1060
|
+
for (const collection of cms.collections()) {
|
|
1061
|
+
if (!collection.path) continue;
|
|
1062
|
+
if (path === collection.path) return { kind: 'archive', collection, locale };
|
|
1063
|
+
if (!path.startsWith(`${collection.path}/`)) continue;
|
|
1064
|
+
const slugs = path.slice(collection.path.length + 1).split('/');
|
|
1065
|
+
// Category permalinks take /<path>/<category>/<slug>; the entry then answers at its own address only.
|
|
1066
|
+
if (!collection.hierarchical && slugs.length > (collection.permalink === 'category' ? 2 : 1)) return { kind: 'none', locale };
|
|
1067
|
+
const found = await bySlug(cms, collection, slugs.at(-1)!, languages, locale);
|
|
1068
|
+
return found ? canonical(cms, collection, found, segments) : { kind: 'none', locale };
|
|
1069
|
+
}
|
|
1070
|
+
// Author pages at /author/<slug>, when Settings → SEO turns them on.
|
|
1071
|
+
if (rest.length === 2 && rest[0] === 'author' && await cms.settings.get('seo.authorPages')) {
|
|
1072
|
+
const user = await cms.users.bySlug(rest[1]!);
|
|
1073
|
+
return user && user.status === 'active' ? { kind: 'author', user, locale } : { kind: 'none', locale };
|
|
1074
|
+
}
|
|
1075
|
+
for (const taxonomy of cms.taxonomies.declarations) {
|
|
1076
|
+
if (!taxonomy.path || rest[0] !== taxonomy.path || rest.length < 2) continue;
|
|
1077
|
+
const term = await cms.taxonomies.bySlug(taxonomy.name, rest.at(-1)!);
|
|
1078
|
+
if (!term) return { kind: 'none', locale };
|
|
1079
|
+
return { kind: 'term', term, ancestors: await cms.taxonomies.ancestors(term), locale };
|
|
1080
|
+
}
|
|
1081
|
+
// Collections at the site root share one namespace: nested ones (pages) first, then the others by name.
|
|
1082
|
+
const roots = cms.collections().filter(collection => collection.path === '').sort((a, b) => Number(!a.hierarchical) - Number(!b.hierarchical) || a.name.localeCompare(b.name));
|
|
1083
|
+
// Each is asked at once; the first in that order with the slug answers.
|
|
1084
|
+
const candidates = roots.filter(root => root.hierarchical || rest.length <= (root.permalink === 'category' ? 2 : 1));
|
|
1085
|
+
const found = await Promise.all(candidates.map(root => bySlug(cms, root, rest.at(-1)!, languages, locale)));
|
|
1086
|
+
const index = found.findIndex(record => record !== null);
|
|
1087
|
+
return index < 0 ? { kind: 'none', locale } : canonical(cms, candidates[index]!, found[index]!, segments);
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
/** The redirect for a path without content, if any; its use is counted in the background. */
|
|
1091
|
+
export async function redirectFor(cms: CmsHost, path: string, query: string, later: (work: Promise<unknown>) => void): Promise<Resolved | null> {
|
|
1092
|
+
let match;
|
|
1093
|
+
let prefix = '';
|
|
1094
|
+
try {
|
|
1095
|
+
match = await cms.redirects.match(path);
|
|
1096
|
+
// A moved collection's or taxonomy's redirects are written without a language prefix: under
|
|
1097
|
+
// a language's prefix the same redirect applies, and its target keeps that prefix.
|
|
1098
|
+
if (!match) {
|
|
1099
|
+
const languages = await cms.languages();
|
|
1100
|
+
const code = path.split('/')[1] ?? '';
|
|
1101
|
+
if (languages.multilingual && languages.all.includes(code)) {
|
|
1102
|
+
const rest = path.slice(code.length + 1) || '/';
|
|
1103
|
+
const unprefixed = await cms.redirects.match(rest);
|
|
1104
|
+
if (unprefixed?.redirect.prefix && unprefixed.location?.startsWith('/')) { match = unprefixed; prefix = `/${code}`; }
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
}
|
|
1108
|
+
catch (error) { if (isCmsError(error) || /cms_redirects|no such table/i.test(String((error as Error).message))) return null; throw error; }
|
|
1109
|
+
if (!match) return null;
|
|
1110
|
+
later(cms.redirects.hit(match.redirect.id));
|
|
1111
|
+
if (match.location === null) return { kind: 'gone' };
|
|
1112
|
+
const target = prefix ? `${prefix}${match.location === '/' ? '' : match.location}` || '/' : match.location;
|
|
1113
|
+
const location = query && !target.includes('?') ? `${target}?${query}` : target;
|
|
1114
|
+
return { kind: 'redirect', url: location, status: match.redirect.status as 301 | 302 | 307 | 308 };
|
|
1115
|
+
}
|
|
1116
|
+
|
|
1117
|
+
/**
|
|
1118
|
+
* The published entry with a slug in a language; each language has its own slugs. A slug
|
|
1119
|
+
* only another language has finds that entry, which then redirects to its own URL.
|
|
1120
|
+
*/
|
|
1121
|
+
async function bySlug(cms: CmsHost, collection: CollectionDefinition, slug: string, languages: SiteLanguages, locale: string): Promise<RecordShape | null> {
|
|
1122
|
+
if (collection.slug === false) return null;
|
|
1123
|
+
const where: { [field: string]: FieldFilter } = { slug, ...(collection.publishable === false ? {} : { status: 'published' }) };
|
|
1124
|
+
const repository = cms.resource(`cms/${collection.name}`);
|
|
1125
|
+
const found = (await repository.list({ where: { ...where, ...localeWhere(languages, locale) }, limit: 1 }, visitor)).records[0];
|
|
1126
|
+
if (found || !languages.multilingual) return found ?? null;
|
|
1127
|
+
return (await repository.list({ where, limit: 1 }, visitor)).records[0] ?? null;
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
/** An entry answers only at its URL (ancestors' slugs, language prefix); other paths redirect there. */
|
|
1131
|
+
async function canonical(cms: CmsHost, collection: CollectionDefinition, record: RecordShape, segments: readonly string[]): Promise<Resolved> {
|
|
1132
|
+
const url = (await cms.entryUrls(collection, [record])).get(record.id);
|
|
1133
|
+
if (!url) return { kind: 'none', locale: (await cms.languages()).default };
|
|
1134
|
+
const languages = await cms.languages();
|
|
1135
|
+
const locale = typeof record.locale === 'string' && languages.all.includes(record.locale) ? record.locale : languages.default;
|
|
1136
|
+
if (url === `/${segments.join('/')}`) return { kind: 'entry', collection, record, locale };
|
|
1137
|
+
// Which language a prefix names follows the settings, which can change (a new default language,
|
|
1138
|
+
// another URL mode): a browser must not keep that redirect. Other paths to the entry move for good.
|
|
1139
|
+
const requested = languages.multilingual && languages.all.includes(segments[0] ?? '') ? `/${segments[0]}` : '';
|
|
1140
|
+
return { kind: 'redirect', url, ...(requested !== localePrefix(languages, locale) ? { status: 302 as const } : {}) };
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
/** Entries of every collection that uses the term's taxonomy, including terms below it, in one language. */
|
|
1144
|
+
export async function termArchive(cms: CmsHost, term: TermShape, page: number, base: string, locale?: string): Promise<Pick<ArchiveView, 'entries' | 'paging' | 'collection' | 'taxonomy'>> {
|
|
1145
|
+
const subtree = (await cms.taxonomies.subtree(term.id)).slice(0, 50);
|
|
1146
|
+
const usage = cms.taxonomies.usage(term.taxonomy).filter(entry => entry.resource.startsWith('cms/'));
|
|
1147
|
+
const collection = usage.length ? cms.collection(usage[0]!.resource.slice(4)) : null;
|
|
1148
|
+
if (!collection) return { entries: [], paging: { page: 1, pages: 1, base }, collection: null, taxonomy: term.taxonomy };
|
|
1149
|
+
return { ...await archive(cms, collection, page, { where: { [usage[0]!.field]: { containsAny: subtree } }, base, ...(locale ? { locale } : {}) }), collection: collection.name, taxonomy: term.taxonomy };
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
/** An author as their page shows them, from their profile meta. */
|
|
1153
|
+
export function authorView(user: CmsUser, prefix = ''): AuthorView {
|
|
1154
|
+
const meta = user.meta;
|
|
1155
|
+
return {
|
|
1156
|
+
name: user.name, slug: user.slug ?? '', url: authorUrl(user.slug, prefix) ?? '#', avatar: user.avatar,
|
|
1157
|
+
bio: typeof meta.bio === 'string' ? meta.bio : '', jobTitle: typeof meta.jobTitle === 'string' ? meta.jobTitle : '',
|
|
1158
|
+
website: typeof meta.website === 'string' && /^https?:\/\//.test(meta.website) ? meta.website : null, profiles: urlList(meta.profiles),
|
|
1159
|
+
};
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
/** The collections an author page lists: article collections on the site. */
|
|
1163
|
+
export function authorCollections(cms: CmsHost): CollectionDefinition[] {
|
|
1164
|
+
return cms.collections().filter(collection => typeof collection.path === 'string' && collection.publishable !== false && ARTICLE_TYPES.has(collection.schema?.type ?? 'WebPage'));
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
/** An author's published articles across the site's article collections, newest first, in one language. */
|
|
1168
|
+
export async function authorArchive(cms: CmsHost, user: CmsUser, page: number, base: string, locale?: string): Promise<Pick<ArchiveView, 'entries' | 'paging' | 'collection'>> {
|
|
1169
|
+
const perPage = await cms.settings.get('reading.postsPerPage');
|
|
1170
|
+
const languages = await cms.languages();
|
|
1171
|
+
const collections = authorCollections(cms);
|
|
1172
|
+
const where = { status: 'published', ...localeWhere(languages, locale ?? languages.default) };
|
|
1173
|
+
const wanted = Math.min(page * perPage, 10_000);
|
|
1174
|
+
const found: { collection: CollectionDefinition; record: RecordShape }[] = [];
|
|
1175
|
+
let total = 0;
|
|
1176
|
+
for (const collection of collections) {
|
|
1177
|
+
const repository = cms.resource(`cms/${collection.name}`);
|
|
1178
|
+
try {
|
|
1179
|
+
const [list, count] = await Promise.all([
|
|
1180
|
+
repository.list({ where, owner: user.id, order: { field: 'publishedAt', direction: 'desc' }, limit: Math.min(wanted, 100) }, visitor),
|
|
1181
|
+
repository.count({ where, owner: user.id }, visitor),
|
|
1182
|
+
]);
|
|
1183
|
+
total += count;
|
|
1184
|
+
found.push(...list.records.map(record => ({ collection, record })));
|
|
1185
|
+
} catch (error) { if (!isCmsError(error)) throw error; }
|
|
1186
|
+
}
|
|
1187
|
+
found.sort((a, b) => Number(b.record.publishedAt ?? 0) - Number(a.record.publishedAt ?? 0));
|
|
1188
|
+
const slice = found.slice((page - 1) * perPage, page * perPage);
|
|
1189
|
+
const entries: EntryView[] = [];
|
|
1190
|
+
for (const collection of collections) {
|
|
1191
|
+
const records = slice.filter(entry => entry.collection === collection).map(entry => entry.record);
|
|
1192
|
+
if (records.length) entries.push(...await entryViews(cms, collection, records));
|
|
1193
|
+
}
|
|
1194
|
+
entries.sort((a, b) => slice.findIndex(entry => entry.record.id === a.id) - slice.findIndex(entry => entry.record.id === b.id));
|
|
1195
|
+
return { entries, paging: { page, pages: Math.max(1, Math.ceil(total / perPage)), base }, collection: collections.length === 1 ? collections[0]!.name : null };
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
/**
|
|
1199
|
+
* One page of the site's search: entries visitors may read, from every collection, best first,
|
|
1200
|
+
* with snippets, in the page's language. `base` is the first page's URL (`/search?q=…`).
|
|
1201
|
+
*/
|
|
1202
|
+
export async function searchEntries(cms: CmsHost, query: string, options: { locale?: string; page?: number; base: string }): Promise<{ entries: EntryView[]; paging: Paging; loose: boolean }> {
|
|
1203
|
+
const languages = await cms.languages();
|
|
1204
|
+
const page = options.page ?? 1;
|
|
1205
|
+
const none = { entries: [], paging: { page, pages: page, base: options.base }, loose: false };
|
|
1206
|
+
const perPage = Math.min(await cms.settings.get('reading.postsPerPage'), 50);
|
|
1207
|
+
const found = await cms.siteSearch.search(query, { page, perPage, ...(languages.multilingual ? { locale: options.locale ?? languages.default } : {}) })
|
|
1208
|
+
.catch(error => { if (isCmsError(error)) return null; throw error; });
|
|
1209
|
+
if (!found) return none;
|
|
1210
|
+
// The hits load as the visitor, who may still be refused one; they render in score order.
|
|
1211
|
+
const byCollection = new Map<string, string[]>();
|
|
1212
|
+
for (const hit of found.hits) byCollection.set(hit.collection, [...byCollection.get(hit.collection) ?? [], hit.id]);
|
|
1213
|
+
const views = new Map<string, EntryView>();
|
|
1214
|
+
for (const [name, ids] of byCollection) {
|
|
1215
|
+
const collection = cms.collections().find(entry => entry.name === name);
|
|
1216
|
+
if (!collection) continue;
|
|
1217
|
+
const records = await cms.resource(`cms/${name}`).getMany(ids, visitor);
|
|
1218
|
+
const readable = ids.map(id => records.get(id)).filter((record): record is RecordShape => record !== undefined && !isProtected(record) && !isMembersOnly(record));
|
|
1219
|
+
for (const view of await entryViews(cms, collection, readable)) views.set(`${name}:${view.id}`, view);
|
|
1220
|
+
}
|
|
1221
|
+
const entries = found.hits.flatMap(hit => { const view = views.get(`${hit.collection}:${hit.id}`); return view ? [{ ...view, snippet: hit.snippet }] : []; });
|
|
1222
|
+
return { entries, paging: { page, pages: found.next ? page + 1 : page, base: options.base }, loose: found.loose };
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
/** The search page's own URL for a query: `?q=` on the search path, and `page=N` after it. */
|
|
1226
|
+
export function searchBase(path: string, query: string): string {
|
|
1227
|
+
return query ? `${path}?q=${encodeURIComponent(query)}` : path;
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
/**
|
|
1231
|
+
* The page in each of the site's languages: an entry's translations (or that language's home
|
|
1232
|
+
* page), archives and term archives under each prefix. Empty for a site with one language.
|
|
1233
|
+
*/
|
|
1234
|
+
export async function languageLinks(cms: CmsHost, resolved: Resolved | { kind: 'other'; locale: string }): Promise<LanguageLink[]> {
|
|
1235
|
+
const languages = await cms.languages();
|
|
1236
|
+
if (!languages.multilingual) return [];
|
|
1237
|
+
const current = 'locale' in resolved ? resolved.locale : languages.default;
|
|
1238
|
+
const home = (code: string) => localePrefix(languages, code) || '/';
|
|
1239
|
+
let urls = new Map<string, string>();
|
|
1240
|
+
if (resolved.kind === 'entry') {
|
|
1241
|
+
const translations = await cms.translations(resolved.collection, resolved.record);
|
|
1242
|
+
const entryUrls = await cms.entryUrls(resolved.collection, [...translations.values()]);
|
|
1243
|
+
urls = new Map([...translations].flatMap(([code, record]) => {
|
|
1244
|
+
const url = entryUrls.get(record.id);
|
|
1245
|
+
return url && (resolved.collection.publishable === false || record.status === 'published') ? [[code, url]] : [];
|
|
1246
|
+
}));
|
|
1247
|
+
} else if (resolved.kind === 'archive') {
|
|
1248
|
+
for (const code of languages.all) {
|
|
1249
|
+
const url = await cms.archiveUrl(resolved.collection, code);
|
|
1250
|
+
if (url) urls.set(code, url);
|
|
1251
|
+
}
|
|
1252
|
+
} else if (resolved.kind === 'term') {
|
|
1253
|
+
const taxonomy = cms.taxonomies.declaration(resolved.term.taxonomy);
|
|
1254
|
+
if (taxonomy.path) for (const code of languages.all) urls.set(code, `${localePrefix(languages, code)}/${taxonomy.path}/${resolved.term.slug}`);
|
|
1255
|
+
} else if (resolved.kind === 'author') {
|
|
1256
|
+
for (const code of languages.all) { const url = authorUrl(resolved.user.slug, localePrefix(languages, code)); if (url) urls.set(code, url); }
|
|
1257
|
+
}
|
|
1258
|
+
return languages.all.map(code => ({ code, label: languageName(code), flag: languageFlag(code), url: urls.get(code) ?? home(code), current: code === current }));
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
/**
|
|
1262
|
+
* A language's home page: Settings → Reading's front page (its translation in other
|
|
1263
|
+
* languages), or that language's latest posts.
|
|
1264
|
+
*/
|
|
1265
|
+
export async function homeView(cms: CmsHost, locale: string, page: number, options: EntryViewOptions = {}): Promise<{ page: EntryView | null; record: RecordShape | null; view: Pick<ArchiveView, 'entries' | 'paging' | 'title' | 'description' | 'collection'> }> {
|
|
1266
|
+
const settings = await cms.settings.all();
|
|
1267
|
+
const languages = await cms.languages();
|
|
1268
|
+
const front = settings['reading.showOnFront'] === 'page' ? settings['reading.pageOnFront'] : '';
|
|
1269
|
+
if (front) {
|
|
1270
|
+
let record = await cms.resource('cms/pages').get(front, visitor);
|
|
1271
|
+
if (record && languages.multilingual && (record.locale ?? languages.default) !== locale) record = (await cms.translations(cms.collection('pages'), record)).get(locale) ?? null;
|
|
1272
|
+
if (record && record.status === 'published') {
|
|
1273
|
+
return { page: (await entryViews(cms, cms.collection('pages'), [record], { ...options, full: true }))[0]!, record, view: { title: '', description: '', entries: [], paging: { page: 1, pages: 1, base: '/' }, collection: null } };
|
|
1274
|
+
}
|
|
1275
|
+
}
|
|
1276
|
+
const result = await archive(cms, cms.collection('posts'), page, { base: localePrefix(languages, locale) || '/', locale });
|
|
1277
|
+
return { page: null, record: null, view: { title: settings['general.siteTitle'], description: settings['general.tagline'], collection: 'posts', ...result } };
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
/** The page Settings → Reading shows for missing addresses, in the language, as a full entry view; null when none is chosen, unpublished or absent. */
|
|
1281
|
+
export async function notFoundPage(cms: CmsHost, locale: string): Promise<EntryView | null> {
|
|
1282
|
+
const id = String((await cms.settings.get('reading.notFoundPage').catch(() => '')) ?? '');
|
|
1283
|
+
if (!id || !cms.collections().some(collection => collection.name === 'pages')) return null;
|
|
1284
|
+
const languages = await cms.languages();
|
|
1285
|
+
let record = await cms.resource('cms/pages').get(id, visitor).catch(() => null);
|
|
1286
|
+
if (record && languages.multilingual && (record.locale ?? languages.default) !== locale) record = (await cms.translations(cms.collection('pages'), record)).get(locale) ?? null;
|
|
1287
|
+
if (!record || record.status !== 'published') return null;
|
|
1288
|
+
return (await entryViews(cms, cms.collection('pages'), [record], { full: true }))[0] ?? null;
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
export function pageNumber(value: string | undefined): number {
|
|
1292
|
+
const page = Number(value);
|
|
1293
|
+
return Number.isSafeInteger(page) && page > 0 && page <= 500 ? page : 1;
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
declare module 'hono' {
|
|
1297
|
+
interface ContextVariableMap {
|
|
1298
|
+
/** What the site path names, set by the catch-all route's middleware. */
|
|
1299
|
+
'cms.site': Resolved | { kind: 'unavailable' };
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
/**
|
|
1304
|
+
* A form as its preview shows it: the `core/form` block with the form attached, built from
|
|
1305
|
+
* the record given (the saved form, or it with an editor's unsaved changes) whatever its
|
|
1306
|
+
* status. The saved form's submissions table is used as is: nothing is migrated for a draft.
|
|
1307
|
+
*/
|
|
1308
|
+
export async function formPreviewBlock(cms: CmsHost, saved: LoadedForm, record: RecordShape, request: FormRequest): Promise<RenderedBlock> {
|
|
1309
|
+
const blocks = Array.isArray(record.body) ? record.body as Block[] : [];
|
|
1310
|
+
const title = typeof record.title === 'string' ? record.title : '';
|
|
1311
|
+
const form: LoadedForm = Object.freeze({
|
|
1312
|
+
...saved, record, blocks, settings: formSettings(record.settings), enabled: record.enabled !== false, published: true,
|
|
1313
|
+
ref: Object.freeze({ id: record.id, slug: typeof record.slug === 'string' ? record.slug : record.id, title, inputs: formInputs(blocks, cms.blockTypes) }),
|
|
1314
|
+
rules: Object.freeze(notificationRules(record.notifications).filter(rule => rule.enabled !== false)),
|
|
1315
|
+
});
|
|
1316
|
+
const ids = new Set<string>();
|
|
1317
|
+
for (const entry of blocks) blockMediaIds(cms, entry, ids);
|
|
1318
|
+
const files = cms.files && ids.size ? await cms.files.getMany([...ids]) : new Map<string, CmsFile>();
|
|
1319
|
+
const block: RenderedBlock & { form?: FormView } = { _id: 'preview', type: 'core/form', data: { form: form.ref.slug }, html: {}, media: {} };
|
|
1320
|
+
block.form = await formView(cms, form, request, entry => renderedBlock(cms, entry, files));
|
|
1321
|
+
return block;
|
|
1322
|
+
}
|