@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,173 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stripe as the payments provider: Checkout Sessions over its REST API (form-encoded, no SDK),
|
|
3
|
+
* and webhooks verified with the signing secret (HMAC-SHA256 over `t.payload`, five minutes of
|
|
4
|
+
* tolerance). The events the CMS relays: a completed checkout (pending while its payment is
|
|
5
|
+
* on its way, completed or failed when it arrives), a succeeded or failed payment, a paid or
|
|
6
|
+
* failed invoice (a subscription's payments), a subscription change or end, a refund. Others
|
|
7
|
+
* answer 200 and are not relayed.
|
|
8
|
+
*
|
|
9
|
+
* Which event completes a payment (`completes`, what `payment.completed` fires for) rests on
|
|
10
|
+
* documented fields only: a paid checkout, and a paid invoice unless it is the first invoice
|
|
11
|
+
* (`billing_reason: subscription_create`) of a subscription a CMS checkout made, which that
|
|
12
|
+
* checkout already completed. A payment intent repeats one of those, so it never completes.
|
|
13
|
+
*/
|
|
14
|
+
import { CmsError } from '../errors';
|
|
15
|
+
import type { PaymentEvent } from '../hooks';
|
|
16
|
+
import { checkCheckout, type Checkout, type CheckoutInput, type PaymentsProvider } from './payments';
|
|
17
|
+
import { sha256Hex, timingSafeEqual } from './tokens';
|
|
18
|
+
|
|
19
|
+
export const STRIPE_API = 'https://api.stripe.com';
|
|
20
|
+
/** The metadata key that marks a payment or subscription a CMS checkout made. */
|
|
21
|
+
const CHECKOUT_MARK = 'cms_checkout';
|
|
22
|
+
/** How old a webhook's timestamp may be. */
|
|
23
|
+
export const STRIPE_TOLERANCE_MS = 5 * 60_000;
|
|
24
|
+
/** How long a webhook waits for a lookup in Stripe's API before relaying without it. */
|
|
25
|
+
export const STRIPE_LOOKUP_MS = 5_000;
|
|
26
|
+
|
|
27
|
+
export interface StripePaymentsOptions {
|
|
28
|
+
readonly secretKey: string;
|
|
29
|
+
/** The endpoint's signing secret (`whsec_…`); without it webhooks are refused. */
|
|
30
|
+
readonly webhookSecret?: string;
|
|
31
|
+
readonly api?: string;
|
|
32
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
33
|
+
readonly now?: () => number;
|
|
34
|
+
/** How long a webhook waits for a lookup in Stripe's API; {@link STRIPE_LOOKUP_MS} by default. */
|
|
35
|
+
readonly lookupMs?: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const TYPES: { readonly [stripe: string]: PaymentEvent['type'] } = {
|
|
39
|
+
// A completed checkout whose payment is still on its way (a bank transfer, SEPA) is pending until one of the async events says how it went.
|
|
40
|
+
'checkout.session.completed': 'checkout.completed', 'checkout.session.async_payment_succeeded': 'checkout.completed', 'checkout.session.async_payment_failed': 'payment.failed',
|
|
41
|
+
'payment_intent.succeeded': 'payment.succeeded', 'payment_intent.payment_failed': 'payment.failed',
|
|
42
|
+
'invoice.paid': 'payment.succeeded', 'invoice.payment_failed': 'payment.failed',
|
|
43
|
+
'customer.subscription.created': 'subscription.updated', 'customer.subscription.updated': 'subscription.updated', 'customer.subscription.deleted': 'subscription.cancelled',
|
|
44
|
+
'charge.refunded': 'refund',
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export function stripePayments(options: StripePaymentsOptions): PaymentsProvider {
|
|
48
|
+
const api = (options.api ?? STRIPE_API).replace(/\/$/, '');
|
|
49
|
+
const fetcher = options.fetch ?? globalThis.fetch;
|
|
50
|
+
const now = options.now ?? Date.now;
|
|
51
|
+
/**
|
|
52
|
+
* A GET of Stripe's API; nothing when Stripe has no such object. When Stripe does not answer
|
|
53
|
+
* in time, is rate limiting or fails (429, 5xx), the webhook fails too (`CMS_UNAVAILABLE`),
|
|
54
|
+
* so Stripe sends it again instead of the event going out without the order it belongs to.
|
|
55
|
+
* Any other refusal (a key without read access, say) would answer the same on every retry,
|
|
56
|
+
* until Stripe drops the event or disables the endpoint: the event goes out without it.
|
|
57
|
+
*/
|
|
58
|
+
const lookup = async <T>(path: string): Promise<T | undefined> => {
|
|
59
|
+
let response: Response;
|
|
60
|
+
try {
|
|
61
|
+
response = await fetcher(`${api}${path}`, { headers: { authorization: `Bearer ${options.secretKey}` }, signal: AbortSignal.timeout(options.lookupMs ?? STRIPE_LOOKUP_MS) });
|
|
62
|
+
} catch (error) {
|
|
63
|
+
throw new CmsError('CMS_UNAVAILABLE', `Stripe did not answer a lookup: ${(error as Error).message}`);
|
|
64
|
+
}
|
|
65
|
+
if (response.status === 404) return undefined;
|
|
66
|
+
if (response.status === 429 || response.status >= 500) throw new CmsError('CMS_UNAVAILABLE', `Stripe answered a lookup with ${response.status}.`);
|
|
67
|
+
if (!response.ok) {
|
|
68
|
+
console.warn(`[cms] Stripe refused a lookup with ${response.status}; the event goes out without the order it belongs to. Check the key's read access.`);
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
try { return await response.json() as T; } catch { throw new CmsError('CMS_UNAVAILABLE', 'Stripe answered a lookup with something other than JSON.'); }
|
|
72
|
+
};
|
|
73
|
+
/** The metadata of an invoice's subscription, or nothing when Stripe does not answer. */
|
|
74
|
+
const invoiceMetadata = async (id: string): Promise<Record<string, unknown> | undefined> => {
|
|
75
|
+
if (!/^in_[A-Za-z0-9]{1,200}$/.test(id)) return undefined;
|
|
76
|
+
const data = await lookup<{ parent?: { subscription_details?: { metadata?: Record<string, unknown> } }; subscription_details?: { metadata?: Record<string, unknown> } }>(`/v1/invoices/${id}`);
|
|
77
|
+
return data?.parent?.subscription_details?.metadata ?? data?.subscription_details?.metadata;
|
|
78
|
+
};
|
|
79
|
+
/**
|
|
80
|
+
* The invoice a charge paid. Charges name it (`invoice`) before Stripe's 2025-03-31 (basil) API
|
|
81
|
+
* version; from then on the invoice's payment record links it to the charge's payment intent.
|
|
82
|
+
*/
|
|
83
|
+
const chargeInvoice = async (charge: Record<string, unknown>): Promise<string | undefined> => {
|
|
84
|
+
if (typeof charge.invoice === 'string') return charge.invoice;
|
|
85
|
+
const intent = charge.payment_intent;
|
|
86
|
+
if (typeof intent !== 'string' || !/^pi_[A-Za-z0-9]{1,200}$/.test(intent)) return undefined;
|
|
87
|
+
const payments = await lookup<{ data?: { invoice?: unknown }[] }>(`/v1/invoice_payments?payment[type]=payment_intent&payment[payment_intent]=${intent}&limit=1`);
|
|
88
|
+
const invoice = payments?.data?.[0]?.invoice;
|
|
89
|
+
return typeof invoice === 'string' ? invoice : (invoice as { id?: unknown } | undefined)?.id as string | undefined;
|
|
90
|
+
};
|
|
91
|
+
return {
|
|
92
|
+
name: 'stripe',
|
|
93
|
+
async checkout(raw: CheckoutInput): Promise<Checkout> {
|
|
94
|
+
const input = checkCheckout(raw);
|
|
95
|
+
const form = new URLSearchParams();
|
|
96
|
+
form.set('mode', input.mode!);
|
|
97
|
+
form.set('success_url', input.successUrl);
|
|
98
|
+
form.set('cancel_url', input.cancelUrl);
|
|
99
|
+
if (input.customerEmail) form.set('customer_email', input.customerEmail);
|
|
100
|
+
if (input.reference) form.set('client_reference_id', input.reference);
|
|
101
|
+
// The session's metadata stays on the session: the payment and subscription it makes carry their own copy,
|
|
102
|
+
// with the reference, so their later events (payments, invoices, refunds) name the order too.
|
|
103
|
+
// Both are marked as a checkout's, so the first invoice of its subscription is not counted twice.
|
|
104
|
+
const carried = { ...(input.metadata ?? {}), ...(input.reference ? { reference: input.reference } : {}), [CHECKOUT_MARK]: '1' };
|
|
105
|
+
for (const [key, value] of Object.entries(carried)) form.set(input.mode === 'subscription' ? `subscription_data[metadata][${key}]` : `payment_intent_data[metadata][${key}]`, value);
|
|
106
|
+
if (input.priceId) { form.set('line_items[0][price]', input.priceId); form.set('line_items[0][quantity]', '1'); }
|
|
107
|
+
else {
|
|
108
|
+
form.set('line_items[0][price_data][currency]', input.currency!.toLowerCase());
|
|
109
|
+
form.set('line_items[0][price_data][unit_amount]', String(input.amount));
|
|
110
|
+
form.set('line_items[0][price_data][product_data][name]', input.description!.trim());
|
|
111
|
+
form.set('line_items[0][quantity]', '1');
|
|
112
|
+
}
|
|
113
|
+
for (const [key, value] of Object.entries(input.metadata ?? {})) form.set(`metadata[${key}]`, value);
|
|
114
|
+
const response = await fetcher(`${api}/v1/checkout/sessions`, { method: 'POST', headers: { authorization: `Bearer ${options.secretKey}`, 'content-type': 'application/x-www-form-urlencoded' }, body: form.toString() });
|
|
115
|
+
const data = await response.json().catch(() => ({})) as { id?: string; url?: string; error?: { message?: string } };
|
|
116
|
+
if (!response.ok || !data.id || !data.url) throw new CmsError('CMS_UNAVAILABLE', `Stripe refused the checkout: ${data.error?.message ?? response.status}`);
|
|
117
|
+
return { id: data.id, url: data.url };
|
|
118
|
+
},
|
|
119
|
+
async webhook(request: Request): Promise<PaymentEvent | null> {
|
|
120
|
+
if (!options.webhookSecret) throw new CmsError('CMS_FORBIDDEN', 'No Stripe webhook secret is configured.');
|
|
121
|
+
const body = await request.text();
|
|
122
|
+
const header = request.headers.get('stripe-signature') ?? '';
|
|
123
|
+
const parts = Object.fromEntries(header.split(',').map(part => part.split('=', 2) as [string, string]));
|
|
124
|
+
const timestamp = Number(parts.t);
|
|
125
|
+
const signatures = header.split(',').filter(part => part.startsWith('v1=')).map(part => part.slice(3));
|
|
126
|
+
if (!Number.isFinite(timestamp) || !signatures.length) throw new CmsError('CMS_FORBIDDEN', 'The webhook signature is missing.');
|
|
127
|
+
if (Math.abs(now() - timestamp * 1000) > STRIPE_TOLERANCE_MS) throw new CmsError('CMS_FORBIDDEN', 'The webhook is too old.');
|
|
128
|
+
const expected = await hmacHex(options.webhookSecret, `${timestamp}.${body}`);
|
|
129
|
+
if (!signatures.some(signature => signature.length === expected.length && timingSafeEqual(signature, expected))) throw new CmsError('CMS_FORBIDDEN', 'The webhook signature does not match.');
|
|
130
|
+
const event = JSON.parse(body) as { id: string; type: string; created: number; data: { object: Record<string, unknown> } };
|
|
131
|
+
const object = event.data?.object ?? {};
|
|
132
|
+
const mapped = TYPES[event.type];
|
|
133
|
+
if (!mapped) return null;
|
|
134
|
+
const type: PaymentEvent['type'] = event.type === 'checkout.session.completed' && object.payment_status === 'unpaid' ? 'checkout.pending' : mapped;
|
|
135
|
+
const invoice = event.type.startsWith('invoice.');
|
|
136
|
+
// An invoice has no metadata of its own for a subscription: its subscription's copy is in
|
|
137
|
+
// `parent.subscription_details` (`subscription_details` before Stripe's 2025 API versions).
|
|
138
|
+
const subscription = (object.parent as { subscription_details?: { metadata?: unknown } } | undefined)?.subscription_details ?? (object.subscription_details as { metadata?: unknown } | undefined);
|
|
139
|
+
let given = (invoice ? subscription?.metadata : object.metadata) as Record<string, unknown> | undefined;
|
|
140
|
+
// A refunded subscription payment's charge has no metadata; its invoice's subscription has the order's.
|
|
141
|
+
if (event.type === 'charge.refunded' && !Object.keys(given ?? {}).length) {
|
|
142
|
+
const paid = await chargeInvoice(object);
|
|
143
|
+
if (paid) given = await invoiceMetadata(paid);
|
|
144
|
+
}
|
|
145
|
+
given = given && typeof given === 'object' ? given : {};
|
|
146
|
+
const metadata = Object.fromEntries(Object.entries(given).filter(([key, value]) => typeof value === 'string' && key !== CHECKOUT_MARK)) as Record<string, string>;
|
|
147
|
+
const marked = given[CHECKOUT_MARK] === '1';
|
|
148
|
+
const fromCheckout = event.type.startsWith('checkout.') || marked;
|
|
149
|
+
const completes = (type === 'checkout.completed')
|
|
150
|
+
|| (event.type === 'invoice.paid' && !(object.billing_reason === 'subscription_create' && marked));
|
|
151
|
+
// A refund's amount is what was refunded, not the charge it came from; an invoice's is what was paid.
|
|
152
|
+
const amount = event.type === 'charge.refunded' ? (typeof object.amount_refunded === 'number' ? object.amount_refunded : null)
|
|
153
|
+
: invoice ? (typeof object.amount_paid === 'number' && event.type === 'invoice.paid' ? object.amount_paid : typeof object.amount_due === 'number' ? object.amount_due : null)
|
|
154
|
+
: typeof object.amount_total === 'number' ? object.amount_total : typeof object.amount === 'number' ? object.amount : typeof object.amount_received === 'number' ? object.amount_received : null;
|
|
155
|
+
return {
|
|
156
|
+
eventId: `payment:stripe:${event.id}`, topic: 'payment.event', at: now(), provider: 'stripe', type, providerType: event.type,
|
|
157
|
+
checkoutId: typeof object.id === 'string' && event.type.startsWith('checkout.') ? object.id : null, fromCheckout, completes,
|
|
158
|
+
reference: typeof object.client_reference_id === 'string' ? object.client_reference_id : metadata.reference ?? null,
|
|
159
|
+
customerEmail: typeof object.customer_email === 'string' ? object.customer_email : (object.customer_details as { email?: string } | undefined)?.email ?? null,
|
|
160
|
+
amount, currency: typeof object.currency === 'string' ? object.currency.toUpperCase() : null, metadata, object,
|
|
161
|
+
};
|
|
162
|
+
},
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
async function hmacHex(secret: string, text: string): Promise<string> {
|
|
167
|
+
const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
168
|
+
const signature = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(text));
|
|
169
|
+
return [...new Uint8Array(signature)].map(byte => byte.toString(16).padStart(2, '0')).join('');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The event ID Stripe gives, for tests and logs. */
|
|
173
|
+
export { sha256Hex as stripeHash };
|
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Taxonomies: categories, tags and plugin vocabularies as rows of `cms_terms`. Each term
|
|
3
|
+
* stores the path of ancestor IDs (`/a/b/`), so a subtree is one prefix match, a move is
|
|
4
|
+
* one UPDATE of that prefix, and a delete moves the children to the parent in the same
|
|
5
|
+
* batch. Records hold term IDs in indexed arrays.
|
|
6
|
+
*/
|
|
7
|
+
import { ClientError, type RomeDB, type Statement, type Value } from '@cossackframework/romedb';
|
|
8
|
+
import { CmsError } from '../errors';
|
|
9
|
+
import { slugify } from '../fields';
|
|
10
|
+
import { hasPermission, PERMISSIONS, principalId, type Principal } from '../permissions';
|
|
11
|
+
import type { TermDraft, TermWriteInput, WriteActor } from '../hooks';
|
|
12
|
+
import type { TaxonomyDeclaration, TermShape } from '../taxonomy';
|
|
13
|
+
import { containsPattern, inList } from './users';
|
|
14
|
+
import { uuidv7 } from '@cossackframework/core';
|
|
15
|
+
import { readBatches, readByIds, readPaged } from './budget';
|
|
16
|
+
|
|
17
|
+
export type { TaxonomyDeclaration, TermShape };
|
|
18
|
+
|
|
19
|
+
/** Where records reference a taxonomy: one indexed array field of a resource collection. */
|
|
20
|
+
export interface TermUsage {
|
|
21
|
+
readonly resource: string;
|
|
22
|
+
readonly storage: string;
|
|
23
|
+
readonly field: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface TermInput {
|
|
27
|
+
readonly name?: string;
|
|
28
|
+
readonly slug?: string;
|
|
29
|
+
readonly description?: string;
|
|
30
|
+
/** Parent term ID, or null for a top-level term. Hierarchical taxonomies only. */
|
|
31
|
+
readonly parent?: string | null;
|
|
32
|
+
/** Solar icon name, such as `tag`, or empty for none. */
|
|
33
|
+
readonly icon?: string;
|
|
34
|
+
/** Values of the field groups attached to the taxonomy; omitted fields keep their values. */
|
|
35
|
+
readonly meta?: { readonly [field: string]: unknown };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** A target's meta, checked against its field groups: errors by field, or the values to store. */
|
|
39
|
+
/** Checks meta against the field groups; Custom HTML in it needs `principal` to hold `cms:html`. */
|
|
40
|
+
export type MetaCheck = (meta: unknown, previous: { readonly [field: string]: unknown } | null, principal?: Principal) => Promise<{ readonly [field: string]: unknown }>;
|
|
41
|
+
|
|
42
|
+
const ID = /^[A-Za-z0-9_-]{1,80}$/;
|
|
43
|
+
const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
44
|
+
const WRITE = { kind: 'cms.terms', retryConflicts: 5 } as const;
|
|
45
|
+
const COLUMNS = 'id, taxonomy, name, slug, description, parent_id, path, depth, created_at, updated_at, icon, meta';
|
|
46
|
+
const ICON = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
47
|
+
const MAX_TERMS = 1000;
|
|
48
|
+
|
|
49
|
+
export class CmsTaxonomies {
|
|
50
|
+
readonly #db: RomeDB;
|
|
51
|
+
readonly #now: () => number;
|
|
52
|
+
readonly #taxonomies: () => ReadonlyMap<string, TaxonomyDeclaration>;
|
|
53
|
+
readonly #usage: (taxonomy: string) => readonly TermUsage[];
|
|
54
|
+
readonly #canAssign: (principal: Principal, taxonomy: TaxonomyDeclaration) => boolean;
|
|
55
|
+
readonly #slugChanged: ((taxonomy: TaxonomyDeclaration, from: string, to: string, guard: { rql: string; params: { [key: string]: Value } }) => Statement[]) | undefined;
|
|
56
|
+
readonly #beforeSave: ((draft: TermDraft, input: TermWriteInput) => Promise<TermDraft>) | undefined;
|
|
57
|
+
readonly #checkMeta: ((taxonomy: string) => MetaCheck) | undefined;
|
|
58
|
+
readonly #changed: (() => void | Promise<void>) | undefined;
|
|
59
|
+
|
|
60
|
+
constructor(db: RomeDB, options: {
|
|
61
|
+
/** Current declarations: built-in and those defined in the dashboard. */
|
|
62
|
+
taxonomies: () => ReadonlyMap<string, TaxonomyDeclaration>;
|
|
63
|
+
usage: (taxonomy: string) => readonly TermUsage[];
|
|
64
|
+
/** Whether the principal may write records that use the taxonomy (to add tags while editing). */
|
|
65
|
+
canAssign: (principal: Principal, taxonomy: TaxonomyDeclaration) => boolean;
|
|
66
|
+
/** Statements to add when a term's slug changes, such as a redirect, run only when `guard` holds. */
|
|
67
|
+
slugChanged?: (taxonomy: TaxonomyDeclaration, from: string, to: string, guard: { rql: string; params: { [key: string]: Value } }) => Statement[];
|
|
68
|
+
/** The `cms.term.before-save` filter: plugins adjust or refuse a term before it is written. */
|
|
69
|
+
beforeSave?: (draft: TermDraft, input: TermWriteInput) => Promise<TermDraft>;
|
|
70
|
+
/** The meta check for a taxonomy's field groups. */
|
|
71
|
+
checkMeta?: (taxonomy: string) => MetaCheck;
|
|
72
|
+
/** Called after a committed change, for the host to purge the site's pages: terms show on entries and in menus. */
|
|
73
|
+
changed?: () => void | Promise<void>;
|
|
74
|
+
now?: () => number;
|
|
75
|
+
}) {
|
|
76
|
+
this.#db = db;
|
|
77
|
+
this.#now = options.now ?? Date.now;
|
|
78
|
+
this.#taxonomies = options.taxonomies;
|
|
79
|
+
this.#usage = options.usage;
|
|
80
|
+
this.#canAssign = options.canAssign;
|
|
81
|
+
this.#slugChanged = options.slugChanged;
|
|
82
|
+
this.#beforeSave = options.beforeSave;
|
|
83
|
+
this.#checkMeta = options.checkMeta;
|
|
84
|
+
this.#changed = options.changed;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
get declarations(): readonly TaxonomyDeclaration[] { return [...this.#taxonomies().values()]; }
|
|
88
|
+
|
|
89
|
+
declaration(name: string): TaxonomyDeclaration {
|
|
90
|
+
const taxonomy = this.#taxonomies().get(name);
|
|
91
|
+
if (!taxonomy) throw new CmsError('CMS_NOT_FOUND', `Unknown taxonomy ${name}.`);
|
|
92
|
+
return taxonomy;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Where records use the taxonomy. */
|
|
96
|
+
usage(taxonomy: string): readonly TermUsage[] { return this.#usage(taxonomy); }
|
|
97
|
+
|
|
98
|
+
async get(id: string): Promise<TermShape | null> {
|
|
99
|
+
return (await this.getMany([id])).get(id) ?? null;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async getMany(ids: readonly string[]): Promise<Map<string, TermShape>> {
|
|
103
|
+
const wanted = [...new Set(ids.filter(id => typeof id === 'string' && ID.test(id)))].slice(0, 200);
|
|
104
|
+
if (!wanted.length) return new Map();
|
|
105
|
+
// Terms hold a description and meta: many may come in smaller reads.
|
|
106
|
+
const rows = await readByIds(this.#db, wanted, slice => { const list = inList('t', slice); return { rql: `SELECT ${COLUMNS} FROM cms_terms WHERE id IN ${list.rql}`, params: list.params }; });
|
|
107
|
+
return new Map(rows.map(row => { const term = termOf(row); return [term.id, term]; }));
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
async bySlug(taxonomy: string, slug: string): Promise<TermShape | null> {
|
|
111
|
+
this.declaration(taxonomy);
|
|
112
|
+
if (!SLUG.test(slug)) return null;
|
|
113
|
+
const result = await this.#db.read([{ rql: `SELECT ${COLUMNS} FROM cms_terms WHERE taxonomy = $taxonomy AND slug = $slug`, params: { $taxonomy: taxonomy, $slug: slug } }]);
|
|
114
|
+
const row = result.results[0]!.rows[0];
|
|
115
|
+
return row ? termOf(row) : null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Terms by name, with search and pagination. */
|
|
119
|
+
async list(taxonomy: string, options: { search?: string; limit?: number; offset?: number } = {}): Promise<{ items: TermShape[]; total: number }> {
|
|
120
|
+
this.declaration(taxonomy);
|
|
121
|
+
const params: { [key: string]: Value } = { $taxonomy: taxonomy };
|
|
122
|
+
let where = 'taxonomy = $taxonomy';
|
|
123
|
+
if (options.search?.trim()) { where += " AND (lower(name) LIKE $q ESCAPE '\\' OR slug LIKE $q ESCAPE '\\')"; params.$q = containsPattern(options.search.trim().slice(0, 100)); }
|
|
124
|
+
const counted = await this.#db.read([{ rql: `SELECT count(*) FROM cms_terms WHERE ${where}`, params }]);
|
|
125
|
+
const rows = await readPaged(this.#db, (size, at) => ({ rql: `SELECT ${COLUMNS} FROM cms_terms WHERE ${where} ORDER BY lower(name), id LIMIT $limit OFFSET $offset`, params: { ...params, $limit: size, $offset: at } }),
|
|
126
|
+
Math.min(Math.max(options.limit ?? 50, 1), 200), Math.max(options.offset ?? 0, 0), { afterSequence: counted.sequence });
|
|
127
|
+
return { items: rows.map(termOf), total: Number(counted.results[0]!.rows[0]![0] as bigint) };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Every term in tree order: each parent before its children, siblings by name. */
|
|
131
|
+
async tree(taxonomy: string): Promise<TermShape[]> {
|
|
132
|
+
this.declaration(taxonomy);
|
|
133
|
+
const terms = (await readPaged(this.#db, (size, at) => ({ rql: `SELECT ${COLUMNS} FROM cms_terms WHERE taxonomy = $taxonomy ORDER BY path LIMIT $limit OFFSET $offset`, params: { $taxonomy: taxonomy, $limit: size, $offset: at } }), MAX_TERMS, 0)).map(termOf);
|
|
134
|
+
const children = new Map<string | null, TermShape[]>();
|
|
135
|
+
const known = new Set(terms.map(term => term.id));
|
|
136
|
+
for (const term of terms) {
|
|
137
|
+
const parent = term.parent && known.has(term.parent) ? term.parent : null;
|
|
138
|
+
children.set(parent, [...(children.get(parent) ?? []), term]);
|
|
139
|
+
}
|
|
140
|
+
const ordered: TermShape[] = [];
|
|
141
|
+
const visit = (parent: string | null) => {
|
|
142
|
+
for (const term of (children.get(parent) ?? []).sort((a, b) => a.name.localeCompare(b.name) || (a.id < b.id ? -1 : 1))) {
|
|
143
|
+
ordered.push(term);
|
|
144
|
+
visit(term.id);
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
visit(null);
|
|
148
|
+
return ordered;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The term's ancestors, root first. */
|
|
152
|
+
async ancestors(term: TermShape): Promise<TermShape[]> {
|
|
153
|
+
const ids = term.path.split('/').filter(Boolean).slice(0, -1);
|
|
154
|
+
const found = await this.getMany(ids);
|
|
155
|
+
return ids.map(id => found.get(id)).filter((entry): entry is TermShape => entry !== undefined);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The term and every term below it. */
|
|
159
|
+
async subtree(id: string): Promise<string[]> {
|
|
160
|
+
const term = await this.get(id);
|
|
161
|
+
if (!term) return [];
|
|
162
|
+
const result = await this.#db.read([{ rql: `SELECT id FROM cms_terms WHERE taxonomy = $taxonomy AND path LIKE $prefix LIMIT ${MAX_TERMS}`, params: { $taxonomy: term.taxonomy, $prefix: `${term.path}%` } }]);
|
|
163
|
+
return result.results[0]!.rows.map(row => row[0] as string);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Records that reference each term, across the resources that use the taxonomy. */
|
|
167
|
+
async counts(taxonomy: string, ids: readonly string[]): Promise<Map<string, number>> {
|
|
168
|
+
const usage = this.#usage(taxonomy);
|
|
169
|
+
const counts = new Map(ids.map(id => [id, 0]));
|
|
170
|
+
const statements: { id: string; statement: Statement }[] = [];
|
|
171
|
+
for (const id of ids) for (const use of usage) {
|
|
172
|
+
statements.push({ id, statement: { rql: `SELECT count(*) FROM ${use.storage} WHERE array::contains("${use.field}", $term)`, params: { $term: id } } });
|
|
173
|
+
}
|
|
174
|
+
for (const chunk of readBatches(statements)) {
|
|
175
|
+
const result = await this.#db.read(chunk.map(entry => entry.statement));
|
|
176
|
+
chunk.forEach((entry, index) => counts.set(entry.id, (counts.get(entry.id) ?? 0) + Number(result.results[index]!.rows[0]![0] as bigint)));
|
|
177
|
+
}
|
|
178
|
+
return counts;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
async create(taxonomy: string, input: TermInput, context: { principal: Principal }): Promise<TermShape> {
|
|
182
|
+
this.#authorize(context.principal);
|
|
183
|
+
const declaration = this.declaration(taxonomy);
|
|
184
|
+
const meta = await this.#meta(taxonomy, input.meta, null, context.principal);
|
|
185
|
+
const draft = await this.#filtered({ name: checkName(input.name), slug: input.slug?.trim() ?? '', description: checkDescription(input.description), parent: input.parent ?? null, icon: checkIcon(input.icon), meta },
|
|
186
|
+
{ taxonomy, action: 'create', id: null, previous: null, actor: actorOf(context.principal) });
|
|
187
|
+
const name = checkName(draft.name);
|
|
188
|
+
const parent = await this.#parent(declaration, draft.parent);
|
|
189
|
+
const id = uuidv7();
|
|
190
|
+
const slug = await this.#uniqueSlug(taxonomy, draft.slug.trim() ? checkSlug(draft.slug) : slugify(name, 120) || 'term', null);
|
|
191
|
+
const now = this.#now();
|
|
192
|
+
const params = {
|
|
193
|
+
$id: id, $taxonomy: taxonomy, $name: name, $slug: slug, $description: checkDescription(draft.description), $parent: parent?.id ?? null,
|
|
194
|
+
$path: `${parent?.path ?? '/'}${id}/`, $depth: parent ? parent.depth + 1 : 0, $now: now, $parentPath: parent?.path ?? null, $icon: checkIcon(draft.icon),
|
|
195
|
+
$meta: JSON.stringify(draft.meta ?? {}),
|
|
196
|
+
};
|
|
197
|
+
// A parent that moved or disappeared since it was read inserts nothing.
|
|
198
|
+
const guard = parent ? ' WHERE EXISTS (SELECT 1 FROM cms_terms WHERE id = $parent AND path = $parentPath)' : '';
|
|
199
|
+
const result = await this.#write([bound(`INSERT INTO cms_terms (${COLUMNS}) SELECT $id, $taxonomy, $name, $slug, $description, $parent, $path, $depth, $now, $now, $icon, $meta${guard}`, params)]);
|
|
200
|
+
if (result.results[0]!.affected !== 1n) throw new CmsError('CMS_CONFLICT', 'The parent changed while the term was saved. Try again.');
|
|
201
|
+
return (await this.get(id))!;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Rename, re-slug, describe or move a term. A move rewrites the subtree's paths in the same batch. */
|
|
205
|
+
async update(id: string, input: TermInput, context: { principal: Principal }): Promise<TermShape> {
|
|
206
|
+
this.#authorize(context.principal);
|
|
207
|
+
const term = await this.get(id);
|
|
208
|
+
if (!term) throw new CmsError('CMS_NOT_FOUND', 'Term not found.');
|
|
209
|
+
const declaration = this.declaration(term.taxonomy);
|
|
210
|
+
const draft = await this.#filtered({
|
|
211
|
+
name: input.name === undefined ? term.name : checkName(input.name), slug: input.slug === undefined ? term.slug : input.slug.trim(),
|
|
212
|
+
description: input.description === undefined ? term.description : checkDescription(input.description), parent: input.parent === undefined ? term.parent : input.parent,
|
|
213
|
+
icon: input.icon === undefined ? term.icon : checkIcon(input.icon),
|
|
214
|
+
meta: input.meta === undefined ? term.meta : await this.#meta(term.taxonomy, input.meta, term.meta, context.principal),
|
|
215
|
+
}, { taxonomy: term.taxonomy, action: 'update', id, previous: term, actor: actorOf(context.principal) });
|
|
216
|
+
const name = checkName(draft.name);
|
|
217
|
+
const slug = draft.slug.trim() === term.slug ? term.slug
|
|
218
|
+
: await this.#uniqueSlug(term.taxonomy, draft.slug.trim() ? checkSlug(draft.slug) : slugify(name, 120) || 'term', id);
|
|
219
|
+
const description = checkDescription(draft.description);
|
|
220
|
+
const icon = checkIcon(draft.icon);
|
|
221
|
+
const now = this.#now();
|
|
222
|
+
const statements: Statement[] = [];
|
|
223
|
+
let path = term.path;
|
|
224
|
+
let parentId = term.parent;
|
|
225
|
+
if (draft.parent !== term.parent) {
|
|
226
|
+
const parent = await this.#parent(declaration, draft.parent);
|
|
227
|
+
if (parent && parent.path.startsWith(term.path)) throw new CmsError('CMS_VALIDATION', 'A term cannot move below itself.', { fields: { parent: 'is inside this term.' } });
|
|
228
|
+
path = `${parent?.path ?? '/'}${id}/`;
|
|
229
|
+
parentId = parent?.id ?? null;
|
|
230
|
+
const depth = parent ? parent.depth + 1 : 0;
|
|
231
|
+
const parentGuard = parent ? ' AND EXISTS (SELECT 1 FROM cms_terms p WHERE p.id = $parent AND p.path = $parentPath)' : '';
|
|
232
|
+
// The subtree moves only while its old path and the new parent's path are unchanged.
|
|
233
|
+
statements.push(bound(`UPDATE cms_terms SET path = $path || substr(path, $oldLength + 1), depth = depth + $delta, updated_at = $now
|
|
234
|
+
WHERE taxonomy = $taxonomy AND path LIKE $oldPrefix${parentGuard}`, {
|
|
235
|
+
$path: path, $oldLength: term.path.length, $delta: depth - term.depth, $now: now, $taxonomy: term.taxonomy, $oldPrefix: `${term.path}%`,
|
|
236
|
+
$parent: parent?.id ?? null, $parentPath: parent?.path ?? null,
|
|
237
|
+
}));
|
|
238
|
+
}
|
|
239
|
+
statements.push({ rql: `UPDATE cms_terms SET name = $name, slug = $slug, description = $description, parent_id = $parentId, icon = $icon, meta = $meta, updated_at = $now WHERE id = $id AND path = $path`,
|
|
240
|
+
params: { $name: name, $slug: slug, $description: description, $parentId: parentId, $icon: icon, $meta: JSON.stringify(draft.meta ?? {}), $now: now, $id: id, $path: path } });
|
|
241
|
+
const own = statements.length - 1;
|
|
242
|
+
if (slug !== term.slug && this.#slugChanged) {
|
|
243
|
+
statements.push(...this.#slugChanged(declaration, term.slug, slug, { rql: 'EXISTS (SELECT 1 FROM cms_terms WHERE id = $tId AND slug = $tSlug AND updated_at = $tNow)', params: { $tId: id, $tSlug: slug, $tNow: now } }));
|
|
244
|
+
}
|
|
245
|
+
const result = await this.#write(statements);
|
|
246
|
+
if (result.results[own]!.affected !== 1n) throw new CmsError('CMS_CONFLICT', 'The term changed while it was saved. Reload and try again.');
|
|
247
|
+
return (await this.get(id))!;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Delete a term. Its children move to its parent in the same batch. Records keep the ID,
|
|
252
|
+
* which readers ignore once the term is gone.
|
|
253
|
+
*/
|
|
254
|
+
async delete(id: string, context: { principal: Principal }): Promise<void> {
|
|
255
|
+
this.#authorize(context.principal);
|
|
256
|
+
const term = await this.get(id);
|
|
257
|
+
if (!term) throw new CmsError('CMS_NOT_FOUND', 'Term not found.');
|
|
258
|
+
const parentPath = term.path.slice(0, term.path.slice(0, -1).lastIndexOf('/') + 1);
|
|
259
|
+
const guard = 'EXISTS (SELECT 1 FROM cms_terms t WHERE t.id = $id AND t.path = $path)';
|
|
260
|
+
const params = { $id: id, $path: term.path, $parent: term.parent, $parentPath: parentPath, $length: term.path.length, $prefix: `${term.path}%`, $taxonomy: term.taxonomy, $now: this.#now() };
|
|
261
|
+
const result = await this.#write([
|
|
262
|
+
bound(`UPDATE cms_terms SET parent_id = $parent, updated_at = $now WHERE parent_id = $id AND ${guard}`, params),
|
|
263
|
+
bound(`UPDATE cms_terms SET path = $parentPath || substr(path, $length + 1), depth = depth - 1, updated_at = $now
|
|
264
|
+
WHERE taxonomy = $taxonomy AND path LIKE $prefix AND id != $id AND ${guard}`, params),
|
|
265
|
+
bound('DELETE FROM cms_terms WHERE id = $id AND path = $path', params),
|
|
266
|
+
]);
|
|
267
|
+
if (result.results[2]!.affected !== 1n) throw new CmsError('CMS_CONFLICT', 'The term changed while it was deleted. Reload and try again.');
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Term IDs for names typed into a flat taxonomy's field, creating the missing terms.
|
|
272
|
+
* Anyone who may write a record that uses the taxonomy may add its terms this way.
|
|
273
|
+
*/
|
|
274
|
+
async ensure(taxonomy: string, names: readonly string[], context: { principal: Principal }): Promise<string[]> {
|
|
275
|
+
const declaration = this.declaration(taxonomy);
|
|
276
|
+
if (declaration.hierarchical) throw new CmsError('CMS_VALIDATION', `${declaration.label} are chosen, not typed.`);
|
|
277
|
+
const wanted = [...new Map(names.map(name => name.trim()).filter(Boolean).slice(0, 50).map(name => [slugify(name, 120) || name.toLowerCase(), name])).entries()];
|
|
278
|
+
if (!wanted.length) return [];
|
|
279
|
+
const list = inList('s', wanted.map(([slug]) => slug));
|
|
280
|
+
const existing = await this.#db.read([{ rql: `SELECT id, slug FROM cms_terms WHERE taxonomy = $taxonomy AND slug IN ${list.rql}`, params: { $taxonomy: taxonomy, ...list.params } }]);
|
|
281
|
+
const bySlug = new Map(existing.results[0]!.rows.map(row => [row[1] as string, row[0] as string]));
|
|
282
|
+
const missing = wanted.filter(([slug]) => !bySlug.has(slug));
|
|
283
|
+
if (missing.length) {
|
|
284
|
+
if (!this.#canAssign(context.principal, declaration) && !hasPermission(context.principal, PERMISSIONS.manageTerms)) throw new CmsError('CMS_FORBIDDEN', `Not allowed to add ${declaration.label.toLowerCase()}.`);
|
|
285
|
+
const now = this.#now();
|
|
286
|
+
const statements = missing.map(([slug, name]) => {
|
|
287
|
+
const id = uuidv7();
|
|
288
|
+
bySlug.set(slug, id);
|
|
289
|
+
// A term another request created first wins; its ID is read back below.
|
|
290
|
+
return { rql: `INSERT INTO cms_terms (${COLUMNS}) VALUES ($id, $taxonomy, $name, $slug, '', NULL, $path, 0, $now, $now, '', '{}') ON CONFLICT (taxonomy, slug) DO NOTHING`,
|
|
291
|
+
params: { $id: id, $taxonomy: taxonomy, $name: checkName(name), $slug: SLUG.test(slug) ? slug : slugify(slug) || `term-${id.slice(0, 8)}`, $path: `/${id}/`, $now: now } };
|
|
292
|
+
});
|
|
293
|
+
await this.#write(statements);
|
|
294
|
+
const again = await this.#db.read([{ rql: `SELECT id, slug FROM cms_terms WHERE taxonomy = $taxonomy AND slug IN ${list.rql}`, params: { $taxonomy: taxonomy, ...list.params } }]);
|
|
295
|
+
for (const row of again.results[0]!.rows) bySlug.set(row[1] as string, row[0] as string);
|
|
296
|
+
}
|
|
297
|
+
return wanted.map(([slug]) => bySlug.get(slug)!).filter(Boolean);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Throw unless every ID is a term of the taxonomy. */
|
|
301
|
+
async assertTerms(taxonomy: string, ids: readonly string[], field: string): Promise<void> {
|
|
302
|
+
this.declaration(taxonomy);
|
|
303
|
+
if (!ids.length) return;
|
|
304
|
+
if (ids.length > 100) throw new CmsError('CMS_VALIDATION', `${field} can hold at most 100 terms.`, { fields: { [field]: 'has too many terms.' } });
|
|
305
|
+
const unique = [...new Set(ids)];
|
|
306
|
+
if (unique.some(id => !ID.test(id))) throw new CmsError('CMS_VALIDATION', `${field} holds an invalid term ID.`, { fields: { [field]: 'holds an invalid term ID.' } });
|
|
307
|
+
const list = inList('t', unique);
|
|
308
|
+
const result = await this.#db.read([{ rql: `SELECT count(*) FROM cms_terms WHERE taxonomy = $taxonomy AND id IN ${list.rql}`, params: { $taxonomy: taxonomy, ...list.params } }]);
|
|
309
|
+
if (Number(result.results[0]!.rows[0]![0] as bigint) !== unique.length) throw new CmsError('CMS_VALIDATION', `${field} names a term that does not exist.`, { fields: { [field]: 'names a missing term.' } });
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** The draft after the before-save filter, when the host has one. */
|
|
313
|
+
/** The meta to store: the field groups' check, or the input as given when the taxonomy has none. */
|
|
314
|
+
async #meta(taxonomy: string, meta: unknown, previous: { readonly [field: string]: unknown } | null, principal: Principal): Promise<{ readonly [field: string]: unknown }> {
|
|
315
|
+
if (this.#checkMeta) return this.#checkMeta(taxonomy)(meta, previous, principal);
|
|
316
|
+
if (meta === undefined) return previous ?? {};
|
|
317
|
+
if (meta === null || typeof meta !== 'object' || Array.isArray(meta)) throw new CmsError('CMS_VALIDATION', 'Meta must be an object of fields.', { fields: { meta: 'must be an object of fields.' } });
|
|
318
|
+
return { ...previous, ...(meta as { [field: string]: unknown }) };
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async #filtered(draft: TermDraft, input: TermWriteInput): Promise<TermDraft> {
|
|
322
|
+
if (!this.#beforeSave) return draft;
|
|
323
|
+
const next = await this.#beforeSave(Object.freeze(draft), Object.freeze(input));
|
|
324
|
+
if (!next || typeof next !== 'object') throw new CmsError('CMS_VALIDATION', 'A plugin returned an invalid term.');
|
|
325
|
+
return { name: next.name, slug: typeof next.slug === 'string' ? next.slug : '', description: next.description ?? '', parent: next.parent ?? null, icon: typeof next.icon === 'string' ? next.icon : '', meta: next.meta && typeof next.meta === 'object' && !Array.isArray(next.meta) ? next.meta : draft.meta };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
#authorize(principal: Principal): void {
|
|
329
|
+
if (!hasPermission(principal, PERMISSIONS.manageTerms)) throw new CmsError(principal.kind === 'anonymous' ? 'CMS_UNAUTHENTICATED' : 'CMS_FORBIDDEN', 'Not allowed to manage terms.');
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async #parent(taxonomy: TaxonomyDeclaration, id: string | null): Promise<TermShape | null> {
|
|
333
|
+
if (id === null || id === '') return null;
|
|
334
|
+
if (!taxonomy.hierarchical) throw new CmsError('CMS_VALIDATION', `${taxonomy.label} have no parents.`, { fields: { parent: 'is not allowed.' } });
|
|
335
|
+
const parent = await this.get(id);
|
|
336
|
+
if (!parent || parent.taxonomy !== taxonomy.name) throw new CmsError('CMS_VALIDATION', 'The parent term does not exist.', { fields: { parent: 'does not exist.' } });
|
|
337
|
+
if (parent.depth >= 15) throw new CmsError('CMS_LIMIT', 'Terms nest at most 16 levels deep.');
|
|
338
|
+
return parent;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** The slug, or the first free `slug-2`, `slug-3`, … in the taxonomy. */
|
|
342
|
+
async #uniqueSlug(taxonomy: string, base: string, except: string | null): Promise<string> {
|
|
343
|
+
const result = await this.#db.read([bound(`SELECT slug FROM cms_terms WHERE taxonomy = $taxonomy AND (slug = $slug OR slug LIKE $prefix ESCAPE '\\')${except ? ' AND id != $except' : ''} LIMIT 1000`,
|
|
344
|
+
{ $taxonomy: taxonomy, $slug: base, $prefix: `${base.replace(/[\\%_]/g, character => `\\${character}`)}-%`, $except: except })]);
|
|
345
|
+
return freeSlug(base, result.results[0]!.rows.map(row => row[0] as string));
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
async #write(statements: Statement[]) {
|
|
349
|
+
try {
|
|
350
|
+
const result = await this.#db.write(statements, WRITE);
|
|
351
|
+
await this.#changed?.();
|
|
352
|
+
return result;
|
|
353
|
+
} catch (error) {
|
|
354
|
+
if (error instanceof ClientError && error.outcome === 'rolled-back' && /UNIQUE|constraint/i.test(error.message)) throw new CmsError('CMS_CONFLICT', 'A term with this slug already exists.', { fields: { slug: 'is taken.' } });
|
|
355
|
+
throw error;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** `base`, or `base-N` with the smallest N ≥ 2 not in `taken`. */
|
|
361
|
+
export function freeSlug(base: string, taken: readonly string[]): string {
|
|
362
|
+
const used = new Set(taken);
|
|
363
|
+
if (!used.has(base)) return base;
|
|
364
|
+
for (let suffix = 2; ; suffix++) if (!used.has(`${base}-${suffix}`)) return `${base}-${suffix}`;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function bound(rql: string, params: { readonly [key: string]: Value }): Statement {
|
|
368
|
+
const used = Object.entries(params).filter(([name]) => new RegExp(`\\${name}(?![A-Za-z0-9_])`).test(rql));
|
|
369
|
+
return used.length ? { rql, params: Object.fromEntries(used) } : { rql };
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function termOf(row: readonly Value[]): TermShape {
|
|
373
|
+
return Object.freeze({
|
|
374
|
+
id: row[0] as string, taxonomy: row[1] as string, name: row[2] as string, slug: row[3] as string, description: row[4] as string,
|
|
375
|
+
parent: row[5] as string | null, path: row[6] as string, depth: Number(row[7] as bigint), createdAt: Number(row[8] as bigint), updatedAt: Number(row[9] as bigint),
|
|
376
|
+
icon: typeof row[10] === 'string' ? row[10] : '',
|
|
377
|
+
meta: parseMeta(row[11]),
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** Stored meta as an object; anything else reads as empty. */
|
|
382
|
+
export function parseMeta(value: unknown): { readonly [field: string]: unknown } {
|
|
383
|
+
if (typeof value !== 'string' || !value) return Object.freeze({});
|
|
384
|
+
try {
|
|
385
|
+
const parsed = JSON.parse(value) as unknown;
|
|
386
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? Object.freeze(parsed as { [field: string]: unknown }) : Object.freeze({});
|
|
387
|
+
} catch { return Object.freeze({}); }
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
function actorOf(principal: Principal): WriteActor {
|
|
391
|
+
return { kind: principal.kind, id: principalId(principal) };
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function checkIcon(icon: unknown): string {
|
|
395
|
+
if (icon === undefined || icon === null || icon === '') return '';
|
|
396
|
+
if (typeof icon !== 'string' || icon.length > 60 || !ICON.test(icon)) throw new CmsError('CMS_VALIDATION', 'Icons are Solar icon names, such as tag.', { fields: { icon: 'is not an icon name.' } });
|
|
397
|
+
return icon;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function checkName(name: unknown): string {
|
|
401
|
+
if (typeof name !== 'string' || !name.trim() || name.trim().length > 120) throw new CmsError('CMS_VALIDATION', 'Enter a name of at most 120 characters.', { fields: { name: 'is required.' } });
|
|
402
|
+
return name.trim();
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function checkSlug(slug: string): string {
|
|
406
|
+
const value = slug.trim();
|
|
407
|
+
if (!SLUG.test(value) || value.length > 120) throw new CmsError('CMS_VALIDATION', 'Slugs use lowercase letters, digits and single hyphens.', { fields: { slug: 'has an invalid format.' } });
|
|
408
|
+
return value;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function checkDescription(description: unknown): string {
|
|
412
|
+
if (description === undefined || description === null) return '';
|
|
413
|
+
if (typeof description !== 'string' || description.length > 2000) throw new CmsError('CMS_VALIDATION', 'Descriptions can be at most 2000 characters.', { fields: { description: 'is too long.' } });
|
|
414
|
+
return description.trim();
|
|
415
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Random tokens and their hashes, for links and credentials stored as hashes. */
|
|
2
|
+
|
|
3
|
+
export async function sha256Hex(text: string): Promise<string> {
|
|
4
|
+
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));
|
|
5
|
+
return [...new Uint8Array(digest)].map(byte => byte.toString(16).padStart(2, '0')).join('');
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function base64Url(bytes: Uint8Array): string {
|
|
9
|
+
let binary = '';
|
|
10
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
11
|
+
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/, '');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** `bytes` random bytes as base64url. */
|
|
15
|
+
export function randomToken(bytes = 32): string {
|
|
16
|
+
return base64Url(crypto.getRandomValues(new Uint8Array(bytes)));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** Compare two strings in time that does not depend on where they differ. */
|
|
20
|
+
export function timingSafeEqual(a: string, b: string): boolean {
|
|
21
|
+
if (a.length !== b.length) return false;
|
|
22
|
+
let difference = 0;
|
|
23
|
+
for (let index = 0; index < a.length; index++) difference |= a.charCodeAt(index) ^ b.charCodeAt(index);
|
|
24
|
+
return difference === 0;
|
|
25
|
+
}
|