@cossackframework/cms 0.0.0 → 0.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +145 -2
- package/agent-docs.json +259 -0
- package/app/README.md +78 -0
- package/app/cossack-recipe.json +43 -0
- package/app/src/auth-bot-check.ts +32 -0
- package/app/src/auth-bot-token.ts +11 -0
- package/app/src/auth-input.ts +35 -0
- package/app/src/auth-options.ts +21 -0
- package/app/src/auth-providers.ts +16 -0
- package/app/src/auth.ts +1082 -0
- package/app/src/brand.ts +68 -0
- package/app/src/cms/ai.ts +54 -0
- package/app/src/cms/analytics.ts +33 -0
- package/app/src/cms/block-errors.ts +55 -0
- package/app/src/cms/block-inserter.ts +111 -0
- package/app/src/cms/block-panel.ts +68 -0
- package/app/src/cms/block-rows.ts +44 -0
- package/app/src/cms/block-tree.ts +585 -0
- package/app/src/cms/blocks.css +709 -0
- package/app/src/cms/builder.ts +126 -0
- package/app/src/cms/cache.ts +44 -0
- package/app/src/cms/carousel.client.ts +52 -0
- package/app/src/cms/collab/presence.ts +69 -0
- package/app/src/cms/collab/rich-text-collab.client.ts +197 -0
- package/app/src/cms/collab/rich-text-notes.client.ts +138 -0
- package/app/src/cms/collab/room.ts +881 -0
- package/app/src/cms/compare.client.ts +47 -0
- package/app/src/cms/condition-control.ts +109 -0
- package/app/src/cms/content-api.ts +143 -0
- package/app/src/cms/content.ts +524 -0
- package/app/src/cms/countdown.client.ts +37 -0
- package/app/src/cms/editor-layout-editor.ts +260 -0
- package/app/src/cms/editor-layout-view.ts +37 -0
- package/app/src/cms/editor.ts +381 -0
- package/app/src/cms/entry.ts +26 -0
- package/app/src/cms/feeds.ts +145 -0
- package/app/src/cms/field-controls.ts +222 -0
- package/app/src/cms/field-group-editor.ts +105 -0
- package/app/src/cms/field-group-view.ts +211 -0
- package/app/src/cms/form-view.ts +203 -0
- package/app/src/cms/form.client.ts +203 -0
- package/app/src/cms/guards.ts +27 -0
- package/app/src/cms/handoff.ts +202 -0
- package/app/src/cms/headings.ts +51 -0
- package/app/src/cms/icons.ts +80 -0
- package/app/src/cms/import.client.ts +16 -0
- package/app/src/cms/index.ts +191 -0
- package/app/src/cms/lightbox.client.ts +114 -0
- package/app/src/cms/machine.ts +118 -0
- package/app/src/cms/maintenance.ts +97 -0
- package/app/src/cms/manage.ts +1236 -0
- package/app/src/cms/mcp-tools.ts +388 -0
- package/app/src/cms/mcp.ts +242 -0
- package/app/src/cms/media-chooser.ts +123 -0
- package/app/src/cms/media-usage.ts +57 -0
- package/app/src/cms/middleware.ts +199 -0
- package/app/src/cms/middlewares.ts +13 -0
- package/app/src/cms/network-ui.ts +36 -0
- package/app/src/cms/network-view.ts +38 -0
- package/app/src/cms/notes-announce.ts +65 -0
- package/app/src/cms/notes-rail.ts +207 -0
- package/app/src/cms/notification-rules.ts +66 -0
- package/app/src/cms/recovery.ts +82 -0
- package/app/src/cms/replace.ts +63 -0
- package/app/src/cms/reserved-paths.ts +19 -0
- package/app/src/cms/rich-text-field.ts +325 -0
- package/app/src/cms/rich-text-schema.ts +91 -0
- package/app/src/cms/rich-text.client.ts +255 -0
- package/app/src/cms/search.client.ts +116 -0
- package/app/src/cms/seo-head.ts +78 -0
- package/app/src/cms/seo.ts +241 -0
- package/app/src/cms/settings-draft.ts +218 -0
- package/app/src/cms/settings-file.ts +127 -0
- package/app/src/cms/settings-form.ts +180 -0
- package/app/src/cms/settings-languages.ts +125 -0
- package/app/src/cms/settings-nav.ts +102 -0
- package/app/src/cms/settings-network.ts +151 -0
- package/app/src/cms/settings-permalinks.ts +114 -0
- package/app/src/cms/settings-scroll.ts +10 -0
- package/app/src/cms/settings-search.ts +77 -0
- package/app/src/cms/settings-section.ts +38 -0
- package/app/src/cms/share.client.ts +27 -0
- package/app/src/cms/site-editing.ts +219 -0
- package/app/src/cms/site-editor.client.ts +1008 -0
- package/app/src/cms/site-editor.ts +99 -0
- package/app/src/cms/site-export.ts +60 -0
- package/app/src/cms/site-forms.ts +143 -0
- package/app/src/cms/site-import.ts +28 -0
- package/app/src/cms/site-session.ts +36 -0
- package/app/src/cms/site-taskbar.ts +77 -0
- package/app/src/cms/site-view.ts +1014 -0
- package/app/src/cms/site.ts +1322 -0
- package/app/src/cms/sitemaps.ts +131 -0
- package/app/src/cms/stat.client.ts +56 -0
- package/app/src/cms/style-controls.ts +252 -0
- package/app/src/cms/tabs.client.ts +36 -0
- package/app/src/cms/taskbar.ts +134 -0
- package/app/src/cms/term-icons.ts +10 -0
- package/app/src/cms/traffic.ts +26 -0
- package/app/src/cms/ui.ts +170 -0
- package/app/src/cms/updates.ts +124 -0
- package/app/src/cms/uploads.ts +26 -0
- package/app/src/cms/worker.ts +13 -0
- package/app/src/config/auth.ts +30 -0
- package/app/src/config/cms.ts +18 -0
- package/app/src/dashboard/access.ts +344 -0
- package/app/src/dashboard/agent-icons.ts +44 -0
- package/app/src/dashboard/app-passwords.ts +62 -0
- package/app/src/dashboard/avatar-field.ts +58 -0
- package/app/src/dashboard/bulk.ts +22 -0
- package/app/src/dashboard/head.ts +29 -0
- package/app/src/dashboard/icons.ts +15 -0
- package/app/src/dashboard/list-table.ts +28 -0
- package/app/src/dashboard/modules/roles.ts +15 -0
- package/app/src/dashboard/modules/sessions.ts +15 -0
- package/app/src/dashboard/modules/settings.ts +15 -0
- package/app/src/dashboard/modules/users.ts +18 -0
- package/app/src/dashboard/page.ts +67 -0
- package/app/src/dashboard/registry.ts +18 -0
- package/app/src/dashboard/session-list.ts +98 -0
- package/app/src/dashboard/tabs.ts +2 -0
- package/app/src/dashboard/time-ago.ts +16 -0
- package/app/src/dashboard/types.ts +43 -0
- package/app/src/dashboard/user-sections.ts +172 -0
- package/app/src/lib/permissions.ts +84 -0
- package/app/src/middlewares/auth.ts +117 -0
- package/app/src/pages/(site)/[...path]/index.ts +609 -0
- package/app/src/pages/(site)/feed/[...rest]/index.ts +13 -0
- package/app/src/pages/(site)/feed/index.ts +12 -0
- package/app/src/pages/(site)/index.ts +11 -0
- package/app/src/pages/(site)/indexnow/[file]/index.ts +18 -0
- package/app/src/pages/(site)/layout.ts +219 -0
- package/app/src/pages/(site)/llms.txt/index.ts +23 -0
- package/app/src/pages/(site)/manifest.webmanifest/index.ts +29 -0
- package/app/src/pages/(site)/media/[id]/[name]/index.ts +59 -0
- package/app/src/pages/(site)/preview/[collection]/[id]/index.ts +115 -0
- package/app/src/pages/(site)/robots.txt/index.ts +29 -0
- package/app/src/pages/(site)/search/index.ts +36 -0
- package/app/src/pages/(site)/sitemap.xml/index.ts +26 -0
- package/app/src/pages/(site)/sitemaps/[file]/index.ts +33 -0
- package/app/src/pages/api/auth/session.ts +48 -0
- package/app/src/pages/api/cms/appearance/areas/[name].ts +12 -0
- package/app/src/pages/api/cms/appearance/areas/index.ts +6 -0
- package/app/src/pages/api/cms/appearance/locations/[location].ts +6 -0
- package/app/src/pages/api/cms/appearance/locations/index.ts +6 -0
- package/app/src/pages/api/cms/appearance/menus/[id].ts +12 -0
- package/app/src/pages/api/cms/appearance/menus/index.ts +13 -0
- package/app/src/pages/api/cms/appearance/themes/[name]/activate.ts +6 -0
- package/app/src/pages/api/cms/appearance/themes/index.ts +6 -0
- package/app/src/pages/api/cms/cache/purge.ts +6 -0
- package/app/src/pages/api/cms/collections/index.ts +6 -0
- package/app/src/pages/api/cms/commands/[plugin]/[command].ts +26 -0
- package/app/src/pages/api/cms/comments/[id].ts +9 -0
- package/app/src/pages/api/cms/comments/index.ts +126 -0
- package/app/src/pages/api/cms/comments/queue.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/autosave.ts +27 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/blocks/[block].ts +16 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/notes.ts +18 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/publish.ts +11 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/index.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/[revision]/restore.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/revisions/index.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry]/unpublish.ts +6 -0
- package/app/src/pages/api/cms/content/[collection]/[entry].ts +42 -0
- package/app/src/pages/api/cms/content/[collection]/index.ts +24 -0
- package/app/src/pages/api/cms/export/[collection].ts +37 -0
- package/app/src/pages/api/cms/forms/[slug]/index.ts +173 -0
- package/app/src/pages/api/cms/forms/[slug]/submissions/[submission]/files/[file].ts +25 -0
- package/app/src/pages/api/cms/forms/[slug]/submissions/export.ts +34 -0
- package/app/src/pages/api/cms/forms/[slug]/submissions/index.ts +24 -0
- package/app/src/pages/api/cms/import/[collection].ts +23 -0
- package/app/src/pages/api/cms/mcp.ts +29 -0
- package/app/src/pages/api/cms/me/index.ts +6 -0
- package/app/src/pages/api/cms/me/recent-blocks.ts +37 -0
- package/app/src/pages/api/cms/me/tokens/[id].ts +6 -0
- package/app/src/pages/api/cms/me/tokens/index.ts +13 -0
- package/app/src/pages/api/cms/media/[id].ts +6 -0
- package/app/src/pages/api/cms/media.ts +26 -0
- package/app/src/pages/api/cms/menus/[location].ts +14 -0
- package/app/src/pages/api/cms/network/sites/[id]/export.ts +15 -0
- package/app/src/pages/api/cms/network/sites/[id]/index.ts +9 -0
- package/app/src/pages/api/cms/network/sites/index.ts +14 -0
- package/app/src/pages/api/cms/notes/[id].ts +13 -0
- package/app/src/pages/api/cms/notes/index.ts +6 -0
- package/app/src/pages/api/cms/payments/webhook.ts +28 -0
- package/app/src/pages/api/cms/plugins/[name]/grant.ts +6 -0
- package/app/src/pages/api/cms/plugins/[name]/revoke.ts +6 -0
- package/app/src/pages/api/cms/plugins/index.ts +6 -0
- package/app/src/pages/api/cms/recovery.ts +29 -0
- package/app/src/pages/api/cms/redirects/index.ts +9 -0
- package/app/src/pages/api/cms/roles/index.ts +6 -0
- package/app/src/pages/api/cms/schema/[collection].ts +13 -0
- package/app/src/pages/api/cms/search.ts +16 -0
- package/app/src/pages/api/cms/settings/[group].ts +9 -0
- package/app/src/pages/api/cms/settings/index.ts +9 -0
- package/app/src/pages/api/cms/site-export.ts +34 -0
- package/app/src/pages/api/cms/taxonomies/index.ts +6 -0
- package/app/src/pages/api/cms/terms/[taxonomy]/[id].ts +12 -0
- package/app/src/pages/api/cms/terms/[taxonomy]/index.ts +9 -0
- package/app/src/pages/api/cms/uploads/[id]/complete.ts +15 -0
- package/app/src/pages/api/cms/uploads/[id]/index.ts +15 -0
- package/app/src/pages/api/cms/uploads/index.ts +26 -0
- package/app/src/pages/api/cms/users/[id]/index.ts +12 -0
- package/app/src/pages/api/cms/users/[id]/meta.ts +40 -0
- package/app/src/pages/api/cms/users/index.ts +12 -0
- package/app/src/pages/api/cms/webhooks/[id].ts +6 -0
- package/app/src/pages/api/cms/webhooks/index.ts +9 -0
- package/app/src/pages/auth/[provider]/callback.ts +11 -0
- package/app/src/pages/auth/[provider]/redirect.ts +9 -0
- package/app/src/pages/auth/forgot-password/index.ts +82 -0
- package/app/src/pages/auth/layout.ts +32 -0
- package/app/src/pages/auth/login/index.ts +205 -0
- package/app/src/pages/auth/magic/index.ts +68 -0
- package/app/src/pages/auth/register/index.ts +124 -0
- package/app/src/pages/auth/reset-password/index.ts +74 -0
- package/app/src/pages/auth/setup/index.ts +194 -0
- package/app/src/pages/auth/two-factor/index.ts +69 -0
- package/app/src/pages/auth/verify/index.ts +62 -0
- package/app/src/pages/dashboard/(cms)/appearance/customize/index.ts +263 -0
- package/app/src/pages/dashboard/(cms)/appearance/dashboard-menu/index.ts +241 -0
- package/app/src/pages/dashboard/(cms)/appearance/index.ts +89 -0
- package/app/src/pages/dashboard/(cms)/appearance/menus/[id]/index.ts +697 -0
- package/app/src/pages/dashboard/(cms)/appearance/menus/index.ts +145 -0
- package/app/src/pages/dashboard/(cms)/appearance/widgets/index.ts +279 -0
- package/app/src/pages/dashboard/(cms)/blocks/index.ts +84 -0
- package/app/src/pages/dashboard/(cms)/calendar/index.ts +92 -0
- package/app/src/pages/dashboard/(cms)/collections/[name]/index.ts +525 -0
- package/app/src/pages/dashboard/(cms)/collections/index.ts +72 -0
- package/app/src/pages/dashboard/(cms)/collections/new/index.ts +66 -0
- package/app/src/pages/dashboard/(cms)/comments/index.ts +237 -0
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/index.ts +2382 -0
- package/app/src/pages/dashboard/(cms)/content/[collection]/[id]/revisions/index.ts +126 -0
- package/app/src/pages/dashboard/(cms)/content/[collection]/index.ts +693 -0
- package/app/src/pages/dashboard/(cms)/field-groups/[id]/index.ts +193 -0
- package/app/src/pages/dashboard/(cms)/field-groups/index.ts +65 -0
- package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/[submission]/index.ts +279 -0
- package/app/src/pages/dashboard/(cms)/forms/[id]/submissions/index.ts +170 -0
- package/app/src/pages/dashboard/(cms)/forms/index.ts +171 -0
- package/app/src/pages/dashboard/(cms)/media/[id]/index.ts +317 -0
- package/app/src/pages/dashboard/(cms)/media/index.ts +156 -0
- package/app/src/pages/dashboard/(cms)/media/new/index.ts +9 -0
- package/app/src/pages/dashboard/(cms)/media/summary/index.ts +74 -0
- package/app/src/pages/dashboard/(cms)/my-sites/index.ts +63 -0
- package/app/src/pages/dashboard/(cms)/network/index.ts +53 -0
- package/app/src/pages/dashboard/(cms)/network/plugins/index.ts +110 -0
- package/app/src/pages/dashboard/(cms)/network/sites/[id]/index.ts +243 -0
- package/app/src/pages/dashboard/(cms)/network/sites/index.ts +186 -0
- package/app/src/pages/dashboard/(cms)/network/sites/new/index.ts +77 -0
- package/app/src/pages/dashboard/(cms)/network/themes/index.ts +82 -0
- package/app/src/pages/dashboard/(cms)/network/updates/index.ts +48 -0
- package/app/src/pages/dashboard/(cms)/network/users/[id]/index.ts +176 -0
- package/app/src/pages/dashboard/(cms)/network/users/index.ts +174 -0
- package/app/src/pages/dashboard/(cms)/network/users/new/index.ts +66 -0
- package/app/src/pages/dashboard/(cms)/plugins/index.ts +172 -0
- package/app/src/pages/dashboard/(cms)/profile/public/index.ts +105 -0
- package/app/src/pages/dashboard/(cms)/registrations/index.ts +70 -0
- package/app/src/pages/dashboard/(cms)/settings/index.ts +359 -0
- package/app/src/pages/dashboard/(cms)/settings/json/index.ts +202 -0
- package/app/src/pages/dashboard/(cms)/settings/layout.ts +67 -0
- package/app/src/pages/dashboard/(cms)/taxonomies/[name]/index.ts +85 -0
- package/app/src/pages/dashboard/(cms)/taxonomies/index.ts +98 -0
- package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/[id]/index.ts +244 -0
- package/app/src/pages/dashboard/(cms)/terms/[taxonomy]/index.ts +148 -0
- package/app/src/pages/dashboard/(cms)/tools/activity/index.ts +94 -0
- package/app/src/pages/dashboard/(cms)/tools/automations/index.ts +131 -0
- package/app/src/pages/dashboard/(cms)/tools/cache/index.ts +92 -0
- package/app/src/pages/dashboard/(cms)/tools/export/index.ts +99 -0
- package/app/src/pages/dashboard/(cms)/tools/health/index.ts +189 -0
- package/app/src/pages/dashboard/(cms)/tools/jobs/index.ts +93 -0
- package/app/src/pages/dashboard/(cms)/tools/links/index.ts +115 -0
- package/app/src/pages/dashboard/(cms)/tools/redirects/index.ts +161 -0
- package/app/src/pages/dashboard/(cms)/tools/replace/index.ts +124 -0
- package/app/src/pages/dashboard/(cms)/tools/schema/index.ts +54 -0
- package/app/src/pages/dashboard/(cms)/tools/seo/index.ts +156 -0
- package/app/src/pages/dashboard/(cms)/tools/updates/index.ts +114 -0
- package/app/src/pages/dashboard/(cms)/tools/webhooks/index.ts +183 -0
- package/app/src/pages/dashboard/index.ts +214 -0
- package/app/src/pages/dashboard/layout.ts +227 -0
- package/app/src/pages/dashboard/profile/index.ts +211 -0
- package/app/src/pages/dashboard/profile/security/index.ts +249 -0
- package/app/src/pages/dashboard/roles/[id]/index.ts +116 -0
- package/app/src/pages/dashboard/roles/index.ts +134 -0
- package/app/src/pages/dashboard/roles/new/index.ts +95 -0
- package/app/src/pages/dashboard/sessions/index.ts +105 -0
- package/app/src/pages/dashboard/users/[id]/index.ts +472 -0
- package/app/src/pages/dashboard/users/index.ts +299 -0
- package/app/src/pages/dashboard/users/new/index.ts +123 -0
- package/app/src/passkeys.client.ts +18 -0
- package/app/src/plugins/default-theme/assets/cover.svg +31 -0
- package/app/src/plugins/default-theme/assets/logo.svg +8 -0
- package/app/src/plugins/default-theme/parts/comments.ts +66 -0
- package/app/src/plugins/default-theme/parts/list.ts +38 -0
- package/app/src/plugins/default-theme/parts/media.ts +15 -0
- package/app/src/plugins/default-theme/parts/options.ts +45 -0
- package/app/src/plugins/default-theme/plugin.json +275 -0
- package/app/src/plugins/default-theme/templates/archive.ts +14 -0
- package/app/src/plugins/default-theme/templates/entry-blank.ts +13 -0
- package/app/src/plugins/default-theme/templates/entry.ts +27 -0
- package/app/src/plugins/default-theme/templates/home.ts +8 -0
- package/app/src/plugins/default-theme/templates/layout.ts +40 -0
- package/app/src/plugins/default-theme/templates/not-found.ts +10 -0
- package/app/src/plugins/default-theme/templates/search.ts +32 -0
- package/app/src/services/rbac.ts +65 -0
- package/app/src/services/roles.ts +89 -0
- package/app/src/services/users.ts +173 -0
- package/package.json +114 -2
- package/src/automations.ts +95 -0
- package/src/bindings.ts +138 -0
- package/src/block-references.ts +239 -0
- package/src/block-shape.ts +155 -0
- package/src/blocks.ts +1157 -0
- package/src/cache.ts +54 -0
- package/src/checks.ts +198 -0
- package/src/cloudflare-workers.d.ts +13 -0
- package/src/cloudflare.ts +61 -0
- package/src/collab.ts +372 -0
- package/src/collections.ts +421 -0
- package/src/comments.ts +46 -0
- package/src/cron.ts +95 -0
- package/src/dashboard-menu.ts +105 -0
- package/src/diff.ts +113 -0
- package/src/editor-layout.ts +316 -0
- package/src/errors.ts +50 -0
- package/src/field-groups.ts +498 -0
- package/src/fields.ts +411 -0
- package/src/form-builder.ts +1053 -0
- package/src/forms.ts +109 -0
- package/src/highlight.ts +134 -0
- package/src/hooks.ts +510 -0
- package/src/icon-catalog.ts +55 -0
- package/src/icons.ts +128 -0
- package/src/images.ts +149 -0
- package/src/index.ts +100 -0
- package/src/isolate-core.ts +245 -0
- package/src/isolate.ts +19 -0
- package/src/isolation.ts +69 -0
- package/src/mail.ts +182 -0
- package/src/manifest.ts +476 -0
- package/src/media.ts +193 -0
- package/src/menus.ts +287 -0
- package/src/module.ts +32 -0
- package/src/modules/content.ts +64 -0
- package/src/modules/forms.ts +35 -0
- package/src/node.ts +66 -0
- package/src/notes.ts +237 -0
- package/src/permissions.ts +139 -0
- package/src/plugin-settings.ts +114 -0
- package/src/records.ts +56 -0
- package/src/redirects.ts +59 -0
- package/src/resource.ts +245 -0
- package/src/richtext.ts +402 -0
- package/src/schema-json.ts +112 -0
- package/src/search.ts +89 -0
- package/src/seo.ts +477 -0
- package/src/server/accounts.ts +418 -0
- package/src/server/ai.ts +33 -0
- package/src/server/api-tokens.ts +91 -0
- package/src/server/areas.ts +116 -0
- package/src/server/audit.ts +94 -0
- package/src/server/auth.ts +89 -0
- package/src/server/automations.ts +190 -0
- package/src/server/autosaves.ts +69 -0
- package/src/server/brand-icons.ts +50 -0
- package/src/server/brands.ts +86 -0
- package/src/server/budget.ts +97 -0
- package/src/server/cache.ts +104 -0
- package/src/server/capabilities.ts +333 -0
- package/src/server/cloudflare.ts +92 -0
- package/src/server/comments.ts +237 -0
- package/src/server/drafts.ts +176 -0
- package/src/server/field-groups.ts +88 -0
- package/src/server/files.ts +780 -0
- package/src/server/forms.ts +726 -0
- package/src/server/handoffs.ts +107 -0
- package/src/server/host-schema.ts +312 -0
- package/src/server/host.ts +2892 -0
- package/src/server/images.ts +34 -0
- package/src/server/index.ts +59 -0
- package/src/server/indexnow.ts +91 -0
- package/src/server/isolation.ts +183 -0
- package/src/server/locked.ts +45 -0
- package/src/server/mail.ts +93 -0
- package/src/server/markdown.ts +24 -0
- package/src/server/menus.ts +286 -0
- package/src/server/network-policy.ts +60 -0
- package/src/server/network.ts +665 -0
- package/src/server/notes.ts +275 -0
- package/src/server/outbox.ts +213 -0
- package/src/server/path-moves.ts +33 -0
- package/src/server/payments.ts +59 -0
- package/src/server/previews.ts +62 -0
- package/src/server/purge.ts +140 -0
- package/src/server/reconcile.ts +38 -0
- package/src/server/redirects.ts +183 -0
- package/src/server/repository.ts +1107 -0
- package/src/server/schedules.ts +105 -0
- package/src/server/schema.ts +562 -0
- package/src/server/security.ts +391 -0
- package/src/server/seed.ts +52 -0
- package/src/server/shared-fields.ts +34 -0
- package/src/server/site-export.ts +151 -0
- package/src/server/site-import.ts +482 -0
- package/src/server/site-search.ts +289 -0
- package/src/server/site-settings.ts +286 -0
- package/src/server/sites.ts +243 -0
- package/src/server/stores.ts +314 -0
- package/src/server/stripe.ts +173 -0
- package/src/server/taxonomies.ts +415 -0
- package/src/server/tokens.ts +25 -0
- package/src/server/traffic.ts +118 -0
- package/src/server/users.ts +653 -0
- package/src/server/webhooks.ts +245 -0
- package/src/settings-controls.ts +54 -0
- package/src/settings-document.ts +111 -0
- package/src/settings.ts +426 -0
- package/src/storage/cloudflare.ts +94 -0
- package/src/storage/index.ts +30 -0
- package/src/storage/node.ts +114 -0
- package/src/taxonomy.ts +51 -0
- package/src/theme.ts +1135 -0
- package/src/to-markdown.ts +179 -0
- package/src/updates.ts +126 -0
- package/src/version.ts +2 -0
- package/src/vite.d.ts +25 -0
- package/src/vite.js +199 -0
- package/src/webhooks.ts +107 -0
|
@@ -0,0 +1,562 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema planner. Reads the live catalog through INFO, diffs it against resource
|
|
3
|
+
* declarations and plans additive DDL; renames, backfills, tightened constraints and
|
|
4
|
+
* drops are explicit versioned steps. Each step is one atomic batch sent with
|
|
5
|
+
* the next schema generation (or, before host step 11, `ifSequence` from the planning read), recorded
|
|
6
|
+
* in the relational migration ledger.
|
|
7
|
+
*/
|
|
8
|
+
import { indexedRowPaths, rowIndexPath, rowsSearchable } from '../field-groups';
|
|
9
|
+
import { ClientError, compareVersions, MAX_STATEMENTS, encodeValue, type RomeDB, type Statement, type Value } from '@cossackframework/romedb';
|
|
10
|
+
import { storageCheck, storageType, type FieldDeclaration } from '../fields';
|
|
11
|
+
import { declarationHash, SYSTEM_FIELDS, type MigrationStep, type Resource } from '../resource';
|
|
12
|
+
import { HOST_STEPS, HOST_TABLES, hostSchemaMismatch, unknownHostSteps, type HostStep } from './host-schema';
|
|
13
|
+
import { CmsError } from '../errors';
|
|
14
|
+
|
|
15
|
+
export interface FieldSpec {
|
|
16
|
+
readonly name: string;
|
|
17
|
+
readonly type: string;
|
|
18
|
+
readonly elementType: string | null;
|
|
19
|
+
readonly required: boolean;
|
|
20
|
+
readonly nullable: boolean;
|
|
21
|
+
readonly hasDefault: boolean;
|
|
22
|
+
readonly default: Value;
|
|
23
|
+
readonly check: string | null;
|
|
24
|
+
readonly flexible: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface IndexSpec {
|
|
28
|
+
readonly name: string;
|
|
29
|
+
readonly kind: 'scalar' | 'fulltext' | 'array';
|
|
30
|
+
readonly paths: readonly string[];
|
|
31
|
+
readonly unique: boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface CollectionSpec {
|
|
35
|
+
readonly resource: Resource;
|
|
36
|
+
readonly name: string;
|
|
37
|
+
readonly fields: readonly FieldSpec[];
|
|
38
|
+
readonly indexes: readonly IndexSpec[];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface CatalogField {
|
|
42
|
+
path: string[];
|
|
43
|
+
type: string;
|
|
44
|
+
element_type: string | null;
|
|
45
|
+
required: boolean;
|
|
46
|
+
nullable: boolean;
|
|
47
|
+
has_default: boolean;
|
|
48
|
+
default: Value;
|
|
49
|
+
check: string | null;
|
|
50
|
+
flexible: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface CatalogTable {
|
|
54
|
+
name: string;
|
|
55
|
+
model: string;
|
|
56
|
+
strict?: boolean;
|
|
57
|
+
fields?: CatalogField[];
|
|
58
|
+
indexes?: { name: string; kind: string; paths?: string[][]; path?: string[]; unique: boolean }[];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface LedgerState {
|
|
62
|
+
/** Applied host step versions. */
|
|
63
|
+
host: Set<number>;
|
|
64
|
+
/** Applied explicit steps by resource ID. */
|
|
65
|
+
explicit: Map<string, Set<number>>;
|
|
66
|
+
/** Declaration hash recorded by the latest step of each resource. */
|
|
67
|
+
hashes: Map<string, string>;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface Catalog {
|
|
71
|
+
readonly sequence: number;
|
|
72
|
+
readonly engineVersion: string;
|
|
73
|
+
readonly tables: ReadonlyMap<string, CatalogTable>;
|
|
74
|
+
readonly ledger: LedgerState;
|
|
75
|
+
/** The last schema generation, or null before host step 11 made the table. */
|
|
76
|
+
readonly generation: number | null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface PlannedStep {
|
|
80
|
+
/** Ledger ID: unique per step. Explicit and host steps reuse theirs, so they apply once. */
|
|
81
|
+
readonly id: string;
|
|
82
|
+
readonly resource: string | null;
|
|
83
|
+
readonly owner: string;
|
|
84
|
+
readonly kind: 'host' | 'additive' | 'explicit';
|
|
85
|
+
readonly version: number;
|
|
86
|
+
readonly description: string;
|
|
87
|
+
readonly statements: readonly Statement[];
|
|
88
|
+
readonly declarationHash: string | null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface SchemaProblem {
|
|
92
|
+
readonly resource: string;
|
|
93
|
+
readonly field?: string;
|
|
94
|
+
readonly message: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export interface SchemaPlan {
|
|
98
|
+
readonly sequence: number;
|
|
99
|
+
readonly engineVersion: string;
|
|
100
|
+
readonly steps: readonly PlannedStep[];
|
|
101
|
+
/** Changes the planner will not make: a resource with a blocked change is not migrated. */
|
|
102
|
+
readonly blocked: readonly SchemaProblem[];
|
|
103
|
+
readonly warnings: readonly SchemaProblem[];
|
|
104
|
+
/** Resources whose catalog and ledger match their declaration. */
|
|
105
|
+
readonly current: readonly string[];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export interface MigrationReport {
|
|
109
|
+
readonly applied: readonly PlannedStep[];
|
|
110
|
+
readonly failed?: { readonly step: PlannedStep; readonly code: string; readonly message: string };
|
|
111
|
+
readonly blocked: readonly SchemaProblem[];
|
|
112
|
+
readonly warnings: readonly SchemaProblem[];
|
|
113
|
+
readonly replans: number;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** A step's statements per request: the rest of the request holds its ledger rows, the generation claim and attached statements. */
|
|
117
|
+
const MAX_STEP_STATEMENTS = MAX_STATEMENTS - 4;
|
|
118
|
+
/** The first RomeDB release that indexes paths into arrays of objects, as `team.*.kind`. */
|
|
119
|
+
export const ROW_INDEX_ENGINE_VERSION = '0.2.11';
|
|
120
|
+
const quote = (name: string) => `"${name}"`;
|
|
121
|
+
const literal = (value: string | number | boolean | null): string =>
|
|
122
|
+
value === null ? 'NULL' : typeof value === 'string' ? `'${value.replaceAll("'", "''")}'` : String(value);
|
|
123
|
+
|
|
124
|
+
/** The collection a resource declaration requires. Deterministic for a declaration. */
|
|
125
|
+
export function collectionSpec(resource: Resource, storageOf: (resourceId: string) => string): CollectionSpec {
|
|
126
|
+
const system: FieldSpec[] = [
|
|
127
|
+
spec('_rev', { kind: 'integer', required: true, min: 1 }, storageOf),
|
|
128
|
+
spec('_op', { kind: 'string', required: true, max: 80 }, storageOf),
|
|
129
|
+
spec('_createdAt', { kind: 'datetime', required: true }, storageOf),
|
|
130
|
+
spec('_updatedAt', { kind: 'datetime', required: true }, storageOf),
|
|
131
|
+
spec('_owner', { kind: 'string', nullable: true, max: 80 }, storageOf),
|
|
132
|
+
];
|
|
133
|
+
// Schemaless collections type only the system fields; the host validates the rest.
|
|
134
|
+
const declared = resource.schemaless ? [] : Object.entries(resource.fields).flatMap(([name, declaration]) => [
|
|
135
|
+
spec(name, declaration, storageOf),
|
|
136
|
+
// A searchable rich text, blocks or multiple field keeps its plain text beside the document.
|
|
137
|
+
...(searchedAsText(declaration) ? [spec(searchTextPath(name), { kind: 'text', nullable: true }, storageOf)] : []),
|
|
138
|
+
]);
|
|
139
|
+
const indexes: IndexSpec[] = [{ name: `${resource.storage}___updated`, kind: 'scalar', paths: ['_updatedAt'], unique: false }];
|
|
140
|
+
if (resource.ownership) indexes.push({ name: `${resource.storage}___owner`, kind: 'scalar', paths: ['_owner'], unique: false });
|
|
141
|
+
for (const [name, declaration] of Object.entries(resource.fields)) {
|
|
142
|
+
if (declaration.unique) indexes.push({ name: `${resource.storage}__u_${name.toLowerCase()}`, kind: 'scalar', paths: [...(declaration.uniqueBy ?? []), name], unique: true });
|
|
143
|
+
else if (declaration.index || declaration.kind === 'reference') indexes.push({ name: `${resource.storage}__${name.toLowerCase()}`, kind: declaration.multiple ? 'array' : 'scalar', paths: [name], unique: false });
|
|
144
|
+
}
|
|
145
|
+
// A row field's index steps into every row of each rows field above it.
|
|
146
|
+
for (const path of indexedRowPaths(resource.fields)) indexes.push({ name: `${resource.storage}__r_${path.join('__').toLowerCase()}`, kind: 'array', paths: [rowIndexPath(path)], unique: false });
|
|
147
|
+
for (const index of resource.indexes) indexes.push({ name: `${resource.storage}__i_${index.name}`, kind: 'scalar', paths: [...index.fields], unique: index.unique === true });
|
|
148
|
+
const searchable = Object.entries(resource.fields).filter(([, declaration]) => declaration.search || rowsSearchable(declaration))
|
|
149
|
+
.map(([name, declaration]) => searchedAsText(declaration) ? searchTextPath(name) : name);
|
|
150
|
+
if (searchable.length) indexes.push({ name: `${resource.storage}__text`, kind: 'fulltext', paths: searchable, unique: false });
|
|
151
|
+
return { resource, name: resource.storage, fields: [...system, ...declared], indexes };
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function spec(name: string, declaration: FieldDeclaration, storageOf: (resourceId: string) => string): FieldSpec {
|
|
155
|
+
const type = storageType(declaration, storageOf);
|
|
156
|
+
const array = /^array<(.+)>$/.exec(type);
|
|
157
|
+
return {
|
|
158
|
+
name,
|
|
159
|
+
type: array ? 'array' : type,
|
|
160
|
+
elementType: array ? array[1]! : null,
|
|
161
|
+
required: declaration.required === true,
|
|
162
|
+
nullable: declaration.nullable === true,
|
|
163
|
+
hasDefault: declaration.default !== undefined,
|
|
164
|
+
default: declaration.default === undefined ? null : declaration.default as Value,
|
|
165
|
+
check: storageCheck(quote(name), declaration) ?? null,
|
|
166
|
+
flexible: declaration.kind === 'json' || declaration.kind === 'richtext',
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Where a searchable rich text or blocks field's plain text is stored, for the full-text index. */
|
|
171
|
+
export function searchTextPath(field: string): string {
|
|
172
|
+
return `_text_${field}`;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Whether a field is searched through its plain text beside the document: rich text, blocks, rows and multiple fields. */
|
|
176
|
+
export function searchedAsText(declaration: FieldDeclaration): boolean {
|
|
177
|
+
return (declaration.search === true && (declaration.kind === 'richtext' || declaration.kind === 'blocks' || declaration.multiple === true)) || rowsSearchable(declaration);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** `DEFINE FIELD` for a spec; `overwrite` replaces an existing definition. */
|
|
181
|
+
export function defineFieldRql(collection: string, field: FieldSpec, options: { overwrite?: boolean; optional?: boolean } = {}): string {
|
|
182
|
+
let rql = `DEFINE FIELD ${options.overwrite ? 'OVERWRITE ' : ''}${quote(field.name)} ON ${collection} TYPE ${field.elementType ? `array<${field.elementType}>` : field.type}`;
|
|
183
|
+
if (field.required && !options.optional) rql += ' REQUIRED';
|
|
184
|
+
if (field.nullable) rql += ' NULLABLE';
|
|
185
|
+
if (field.flexible) rql += ' FLEXIBLE';
|
|
186
|
+
if (field.hasDefault) rql += ` DEFAULT ${literal(field.default as string | number | boolean | null)}`;
|
|
187
|
+
if (field.check) rql += ` CHECK(${field.check})`;
|
|
188
|
+
return rql;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export function indexRql(collection: string, index: IndexSpec): string {
|
|
192
|
+
const paths = index.paths.map(indexPath).join(', ');
|
|
193
|
+
if (index.kind === 'fulltext') return `CREATE SEARCH INDEX ${index.name} ON ${collection}(${paths}) USING FULLTEXT`;
|
|
194
|
+
// One entry per element, so `array::contains(field, $value)` seeks.
|
|
195
|
+
if (index.kind === 'array') return `CREATE SEARCH INDEX ${index.name} ON ${collection}(${paths}) USING ARRAY`;
|
|
196
|
+
return `CREATE ${index.unique ? 'UNIQUE ' : ''}INDEX ${index.name} ON ${collection} (${paths})`;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** An index path with each field quoted: `team.*.kind` becomes `"team".*."kind"`. */
|
|
200
|
+
function indexPath(path: string): string {
|
|
201
|
+
return path.split('.').map(part => part === '*' ? part : quote(part)).join('.');
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Catalog reads before host step 11, when they must all see one sequence. */
|
|
205
|
+
const PRE_GENERATION_ATTEMPTS = 25;
|
|
206
|
+
|
|
207
|
+
/** The tables and their models, in a form two reads can be compared by. */
|
|
208
|
+
function tableList(info: { tables?: { name: string; model: string }[] }): string {
|
|
209
|
+
return JSON.stringify((info.tables ?? []).map(table => [table.name, table.model]).sort((a, b) => a[0]!.localeCompare(b[0]!)));
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Read the catalog. The table definitions may take several reads; each one repeats the table
|
|
214
|
+
* list and the migration ledger, and the catalog is consistent when they match the first read's.
|
|
215
|
+
* Every schema change commits ledger rows in the same batch, so writes to other rows, which land
|
|
216
|
+
* all the time on a busy site, do not make the read start over. A schema change does.
|
|
217
|
+
*/
|
|
218
|
+
export async function readCatalog(db: RomeDB, collections: readonly string[], options: { signal?: AbortSignal } = {}): Promise<Catalog> {
|
|
219
|
+
// Before host step 11, every read must see one sequence, which a busy site's other writes
|
|
220
|
+
// move: those reads get more attempts, a short random pause apart.
|
|
221
|
+
let attempts = 5;
|
|
222
|
+
for (let attempt = 0; attempt < attempts; attempt++) {
|
|
223
|
+
if (attempt > 0 && attempts > 5) await new Promise(resolve => setTimeout(resolve, 10 + Math.floor(Math.random() * 40 * Math.min(attempt, 5))));
|
|
224
|
+
const first = await db.read([{ rql: 'INFO FOR DB' }], options);
|
|
225
|
+
const info = first.results[0]!.rows[0]![0] as { tables?: { name: string; model: string }[] };
|
|
226
|
+
const names = new Map((info.tables ?? []).map(table => [table.name, table.model]));
|
|
227
|
+
const listed = tableList(info);
|
|
228
|
+
const wanted = collections.filter(name => names.get(name) === 'document');
|
|
229
|
+
const ledgerQueries = names.has('cms_migrations') && names.has('cms_schema_state');
|
|
230
|
+
const generations = names.has('cms_schema_generations');
|
|
231
|
+
if (!generations) attempts = PRE_GENERATION_ATTEMPTS;
|
|
232
|
+
const ledgerStatements: Statement[] = ledgerQueries ? [
|
|
233
|
+
{ rql: "SELECT kind, resource, version FROM cms_migrations WHERE kind IN ('host', 'explicit') ORDER BY kind, resource, version" },
|
|
234
|
+
{ rql: 'SELECT resource, declaration_hash FROM cms_schema_state ORDER BY resource' },
|
|
235
|
+
...(generations ? [{ rql: 'SELECT max(id) FROM cms_schema_generations' }] : []),
|
|
236
|
+
] : [];
|
|
237
|
+
const fixed = 1 + ledgerStatements.length;
|
|
238
|
+
const tableStatements: Statement[] = wanted.map(name => ({ rql: `INFO FOR TABLE ${name}` }));
|
|
239
|
+
const chunks: Statement[][] = [];
|
|
240
|
+
const perChunk = MAX_STATEMENTS - fixed;
|
|
241
|
+
for (let offset = 0; offset < tableStatements.length || chunks.length === 0; offset += perChunk) {
|
|
242
|
+
chunks.push([{ rql: 'INFO FOR DB' }, ...ledgerStatements, ...tableStatements.slice(offset, offset + perChunk)]);
|
|
243
|
+
}
|
|
244
|
+
const tables = new Map<string, CatalogTable>();
|
|
245
|
+
for (const [name, model] of names) tables.set(name, { name, model });
|
|
246
|
+
const ledger: LedgerState = { host: new Set(), explicit: new Map(), hashes: new Map() };
|
|
247
|
+
let ledgerSeen: string | undefined;
|
|
248
|
+
let generation: number | null = null;
|
|
249
|
+
let consistent = true;
|
|
250
|
+
let sequence = first.sequence;
|
|
251
|
+
for (const chunk of chunks) {
|
|
252
|
+
const result = await db.read(chunk, { ...options, afterSequence: first.sequence });
|
|
253
|
+
sequence = result.sequence;
|
|
254
|
+
const rows = (index: number) => result.results[index]!.rows;
|
|
255
|
+
const ledgerRows = JSON.stringify(ledgerStatements.map((_, index) => rows(1 + index)), (_key, value) => typeof value === 'bigint' ? `${value}n` : value);
|
|
256
|
+
if (result.sequence !== first.sequence) {
|
|
257
|
+
// Before host step 11 a migration guards on the global sequence alone, so every read
|
|
258
|
+
// must see the same one: a table altered between chunks would go unnoticed otherwise.
|
|
259
|
+
if (!generations) { consistent = false; break; }
|
|
260
|
+
// Something was written since: go on only if it was not the schema.
|
|
261
|
+
if (tableList(rows(0)[0]![0] as { tables?: { name: string; model: string }[] }) !== listed || (ledgerSeen !== undefined && ledgerRows !== ledgerSeen)) { consistent = false; break; }
|
|
262
|
+
}
|
|
263
|
+
if (ledgerSeen === undefined) {
|
|
264
|
+
ledgerSeen = ledgerRows;
|
|
265
|
+
if (ledgerQueries) {
|
|
266
|
+
for (const [kind, resource, version] of rows(1)) {
|
|
267
|
+
if (kind === 'host') ledger.host.add(Number(version));
|
|
268
|
+
else {
|
|
269
|
+
const set = ledger.explicit.get(resource as string) ?? new Set<number>();
|
|
270
|
+
set.add(Number(version));
|
|
271
|
+
ledger.explicit.set(resource as string, set);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
for (const [resource, hash] of rows(2)) ledger.hashes.set(resource as string, hash as string);
|
|
275
|
+
if (generations) generation = Number(rows(3)[0]?.[0] ?? 0);
|
|
276
|
+
}
|
|
277
|
+
} else if (ledgerRows !== ledgerSeen) { consistent = false; break; }
|
|
278
|
+
for (let index = fixed; index < chunk.length; index++) {
|
|
279
|
+
const table = rows(index)[0]![0] as unknown as CatalogTable;
|
|
280
|
+
tables.set(table.name, table);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
if (!consistent) continue;
|
|
284
|
+
// A ledger with steps this build does not have belongs to another build: planning against it would be wrong.
|
|
285
|
+
const unknown = unknownHostSteps(ledger.host);
|
|
286
|
+
if (unknown.length) throw new CmsError('CMS_SCHEMA_MISMATCH', hostSchemaMismatch(unknown));
|
|
287
|
+
const details = await db.preflight(options);
|
|
288
|
+
// The schema is as read up to the last read, so migrations guard on that sequence (the
|
|
289
|
+
// first one, before host step 11, since every read then saw it).
|
|
290
|
+
return { sequence, engineVersion: details.engineVersion!, tables, ledger, generation };
|
|
291
|
+
}
|
|
292
|
+
throw new Error('The database schema kept changing while it was read; retry the migration.');
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Plan host tables, then each resource in ID order. Pure: the same inputs give the same RomeQL. */
|
|
296
|
+
export async function planSchema(resources: readonly Resource[], catalog: Catalog): Promise<SchemaPlan> {
|
|
297
|
+
const steps: PlannedStep[] = [];
|
|
298
|
+
const blocked: SchemaProblem[] = [];
|
|
299
|
+
const warnings: SchemaProblem[] = [];
|
|
300
|
+
const current: string[] = [];
|
|
301
|
+
for (const step of HOST_STEPS) {
|
|
302
|
+
if (catalog.ledger.host.has(step.version)) continue;
|
|
303
|
+
steps.push(hostStep(step));
|
|
304
|
+
}
|
|
305
|
+
const byId = new Map(resources.map(resource => [resource.id, resource]));
|
|
306
|
+
const storageOf = (id: string) => {
|
|
307
|
+
const target = byId.get(id);
|
|
308
|
+
if (!target) throw new Error(`Reference target ${id} is not a registered resource.`);
|
|
309
|
+
return target.storage;
|
|
310
|
+
};
|
|
311
|
+
for (const resource of [...resources].sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0)) {
|
|
312
|
+
const problems: SchemaProblem[] = [];
|
|
313
|
+
let collection: CollectionSpec;
|
|
314
|
+
try { collection = collectionSpec(resource, storageOf); }
|
|
315
|
+
catch (error) { blocked.push({ resource: resource.id, message: (error as Error).message }); continue; }
|
|
316
|
+
const hash = await declarationHash(resource);
|
|
317
|
+
const table = catalog.tables.get(collection.name);
|
|
318
|
+
const applied = catalog.ledger.explicit.get(resource.id) ?? new Set<number>();
|
|
319
|
+
const resourceSteps: PlannedStep[] = [];
|
|
320
|
+
if (collection.indexes.some(index => index.paths.some(path => path.includes('.*.'))) && compareVersions(catalog.engineVersion, ROW_INDEX_ENGINE_VERSION) < 0) {
|
|
321
|
+
blocked.push({ resource: resource.id, message: `Filterable repeater fields need RomeDB ${ROW_INDEX_ENGINE_VERSION} or later; the database runs ${catalog.engineVersion}.` });
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
if (table && table.model !== 'document') {
|
|
325
|
+
blocked.push({ resource: resource.id, message: `${collection.name} exists as a ${table.model} table.` });
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
if (!table) {
|
|
329
|
+
const statements: Statement[] = [{ rql: `CREATE TABLE ${collection.name}` }];
|
|
330
|
+
for (const field of collection.fields) statements.push({ rql: defineFieldRql(collection.name, field) });
|
|
331
|
+
if (!resource.schemaless) statements.push({ rql: `DEFINE SCHEMA ON ${collection.name} STRICT` });
|
|
332
|
+
for (const index of collection.indexes) statements.push({ rql: indexRql(collection.name, index) });
|
|
333
|
+
resourceSteps.push(...chunkSteps(resource, 'additive', 0, `Create ${resource.id}`, statements, hash));
|
|
334
|
+
// A new collection has nothing to migrate; record its explicit steps as applied.
|
|
335
|
+
for (const step of resource.migrations) resourceSteps.push(explicitStep(resource, step, [], hash));
|
|
336
|
+
} else {
|
|
337
|
+
const additive: Statement[] = [];
|
|
338
|
+
const catalogFields = new Map((table.fields ?? []).filter(entry => entry.path.length === 1).map(entry => [entry.path[0]!, entry]));
|
|
339
|
+
const pending = resource.migrations.filter(step => !applied.has(step.version));
|
|
340
|
+
const pendingFor = (kind: MigrationStep['kind'], name: string) => pending.find(step => step.kind === kind && ('field' in step ? step.field === name : false));
|
|
341
|
+
for (const field of collection.fields) {
|
|
342
|
+
const existing = catalogFields.get(field.name);
|
|
343
|
+
if (!existing) {
|
|
344
|
+
if (field.required && !field.hasDefault) {
|
|
345
|
+
// Expand first: add the field as optional; a declared tighten step makes it required.
|
|
346
|
+
additive.push({ rql: defineFieldRql(collection.name, field, { optional: true }) });
|
|
347
|
+
if (!pendingFor('tighten', field.name)) problems.push({ resource: resource.id, field: field.name, message: `${field.name} is new and required. Declare a backfill (if records exist) and a tighten step, or make it optional.` });
|
|
348
|
+
} else additive.push({ rql: defineFieldRql(collection.name, field) });
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
const drift = fieldDrift(field, existing);
|
|
352
|
+
if (!drift.length) continue;
|
|
353
|
+
const onlyTightening = drift.every(name => ['required', 'check'].includes(name));
|
|
354
|
+
if (onlyTightening && pendingFor('tighten', field.name)) continue;
|
|
355
|
+
problems.push({ resource: resource.id, field: field.name, message: `${field.name} differs from the database in ${drift.join(', ')}. ${onlyTightening ? 'Declare a tighten step.' : 'Add a new field, migrate values, then drop the old field.'}` });
|
|
356
|
+
}
|
|
357
|
+
for (const name of catalogFields.keys()) {
|
|
358
|
+
if (collection.fields.some(field => field.name === name)) continue;
|
|
359
|
+
if (!pendingFor('drop', name)) warnings.push({ resource: resource.id, field: name, message: `${name} is in the database but not declared. Declare a drop step to remove it.` });
|
|
360
|
+
}
|
|
361
|
+
if (table.strict !== true && !resource.schemaless) problems.push({ resource: resource.id, message: `${collection.name} is not a strict collection.` });
|
|
362
|
+
const catalogIndexes = new Map((table.indexes ?? []).map(index => [index.name, index]));
|
|
363
|
+
for (const index of collection.indexes) {
|
|
364
|
+
const existing = catalogIndexes.get(index.name);
|
|
365
|
+
if (!existing) { additive.push({ rql: indexRql(collection.name, index) }); continue; }
|
|
366
|
+
const paths = (existing.paths ?? (existing.path ? [existing.path] : [])).map(path => path.join('.'));
|
|
367
|
+
if (existing.kind !== index.kind || existing.unique !== index.unique || paths.join(',') !== index.paths.join(',')) {
|
|
368
|
+
// Schemaless collections rebuild a changed index, such as full-text search over a new field; strict ones rename it.
|
|
369
|
+
if (resource.schemaless) additive.push({ rql: `DROP INDEX ${index.name}` }, { rql: indexRql(collection.name, index) });
|
|
370
|
+
else problems.push({ resource: resource.id, message: `Index ${index.name} differs from the database. Rename the index to replace it.` });
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
for (const name of catalogIndexes.keys()) {
|
|
374
|
+
if (!name.startsWith(`${collection.name}__`) || collection.indexes.some(index => index.name === name)) continue;
|
|
375
|
+
// Dropping an index loses no data; schemaless collections drop the ones they no longer declare.
|
|
376
|
+
if (resource.schemaless) additive.push({ rql: `DROP INDEX ${name}` });
|
|
377
|
+
else warnings.push({ resource: resource.id, message: `Index ${name} is no longer declared.` });
|
|
378
|
+
}
|
|
379
|
+
if (additive.length) resourceSteps.push(...chunkSteps(resource, 'additive', 0, `Extend ${resource.id}`, additive, hash));
|
|
380
|
+
for (const step of pending) {
|
|
381
|
+
const statements = explicitStatements(collection, step, catalogFields, resource.schemaless);
|
|
382
|
+
if (typeof statements === 'string') { problems.push({ resource: resource.id, message: `Migration ${step.version}: ${statements}` }); break; }
|
|
383
|
+
resourceSteps.push(explicitStep(resource, step, statements, hash));
|
|
384
|
+
}
|
|
385
|
+
if (!resourceSteps.length && catalog.ledger.hashes.get(resource.id) !== hash && !problems.length) {
|
|
386
|
+
// Equivalent declaration with a new hash (for example a label change): record it.
|
|
387
|
+
resourceSteps.push(...chunkSteps(resource, 'additive', 0, `Record ${resource.id}`, [], hash));
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
if (problems.length) { blocked.push(...problems); continue; }
|
|
391
|
+
if (!resourceSteps.length) current.push(resource.id);
|
|
392
|
+
steps.push(...resourceSteps);
|
|
393
|
+
}
|
|
394
|
+
return { sequence: catalog.sequence, engineVersion: catalog.engineVersion, steps, blocked, warnings, current };
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Apply a plan step by step. A sequence conflict (another write landed) re-plans from a
|
|
399
|
+
* fresh catalog read; any other failure stops, leaving earlier steps applied.
|
|
400
|
+
*/
|
|
401
|
+
export interface MigrateOptions {
|
|
402
|
+
signal?: AbortSignal;
|
|
403
|
+
maxReplans?: number;
|
|
404
|
+
now?: () => number;
|
|
405
|
+
/** Apply host steps and only these resources' steps. */
|
|
406
|
+
only?: readonly string[];
|
|
407
|
+
/** Statements committed with the last step of a resource, such as its stored definition. */
|
|
408
|
+
attach?: (resource: string) => readonly Statement[];
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export async function migrate(db: RomeDB, resources: readonly Resource[], options: MigrateOptions = {}): Promise<MigrationReport> {
|
|
412
|
+
const applied: PlannedStep[] = [];
|
|
413
|
+
const now = options.now ?? Date.now;
|
|
414
|
+
let replans = 0;
|
|
415
|
+
for (;;) {
|
|
416
|
+
const catalog = await readCatalog(db, resources.map(resource => resource.storage), options);
|
|
417
|
+
const plan = await planSchema(resources, catalog);
|
|
418
|
+
let sequence = plan.sequence;
|
|
419
|
+
let generation = catalog.generation;
|
|
420
|
+
let conflict = false;
|
|
421
|
+
const steps = options.only ? plan.steps.filter(step => step.resource === null || options.only!.includes(step.resource)) : plan.steps;
|
|
422
|
+
const last = new Map(steps.filter(step => step.resource).map(step => [step.resource!, step]));
|
|
423
|
+
for (const step of steps) {
|
|
424
|
+
try {
|
|
425
|
+
const attached = step.resource && last.get(step.resource) === step ? options.attach?.(step.resource) ?? [] : [];
|
|
426
|
+
// With the generations table, the batch takes the next generation: another migration
|
|
427
|
+
// since the plan holds it, and the batch rolls back. Without it (a database before host
|
|
428
|
+
// step 11), any write since the plan does.
|
|
429
|
+
const at = now();
|
|
430
|
+
const claim: Statement[] = generation === null ? [] : [{ rql: 'INSERT INTO cms_schema_generations (id, at) VALUES ($generation, $at)', params: { $generation: generation + 1, $at: at } }];
|
|
431
|
+
const result = await db.write([...step.statements, ...ledgerStatements(step, plan.engineVersion, at), ...claim, ...attached], {
|
|
432
|
+
afterSequence: sequence, ...(generation === null ? { ifSequence: sequence } : {}), kind: 'cms.migration', signal: options.signal,
|
|
433
|
+
workLimits: { rowsRead: 1_000_000, rowMutations: 100_000, vmSteps: 10_000_000 },
|
|
434
|
+
});
|
|
435
|
+
sequence = result.sequence;
|
|
436
|
+
if (generation !== null) generation++;
|
|
437
|
+
applied.push(step);
|
|
438
|
+
} catch (error) {
|
|
439
|
+
if (error instanceof ClientError && error.outcome === 'rolled-back' && (isSequenceConflict(error) || isGenerationClash(error))) { conflict = true; break; }
|
|
440
|
+
const code = error instanceof ClientError ? error.code : (error as Error).name;
|
|
441
|
+
return { applied, failed: { step, code, message: (error as Error).message }, blocked: plan.blocked, warnings: plan.warnings, replans };
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
if (!conflict) return { applied, blocked: plan.blocked, warnings: plan.warnings, replans };
|
|
445
|
+
if (++replans > (options.maxReplans ?? 3)) throw new Error('Schema migration kept conflicting with other writes; retry later.');
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* For a schema change made outside `migrate` (dropping a collection's or a form's table): take the
|
|
451
|
+
* next generation, so a migration planned before it collides and plans again.
|
|
452
|
+
*/
|
|
453
|
+
export function nextGenerationStatement(at: number): Statement {
|
|
454
|
+
return { rql: 'INSERT INTO cms_schema_generations (id, at) SELECT coalesce(max(id), 0) + 1, $at FROM cms_schema_generations', params: { $at: at } };
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
function isGenerationClash(error: ClientError): boolean {
|
|
458
|
+
return error.code === 'RDB_CONSTRAINT' && error.message.includes('cms_schema_generations');
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function isSequenceConflict(error: ClientError): boolean {
|
|
462
|
+
return error.code === 'RDB_CONFLICT' || /sequence/i.test(error.message);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function fieldDrift(desired: FieldSpec, existing: CatalogField): string[] {
|
|
466
|
+
const drift: string[] = [];
|
|
467
|
+
if (desired.type !== existing.type) drift.push('type');
|
|
468
|
+
if ((desired.elementType ?? null) !== (existing.element_type ?? null)) drift.push('item type');
|
|
469
|
+
if (desired.required !== existing.required) drift.push('required');
|
|
470
|
+
if (desired.nullable !== existing.nullable) drift.push('nullable');
|
|
471
|
+
if (desired.flexible !== existing.flexible) drift.push('flexible');
|
|
472
|
+
if (desired.hasDefault !== existing.has_default || (desired.hasDefault && JSON.stringify(encodeValue(desired.default)) !== JSON.stringify(encodeValue(existing.default)))) {
|
|
473
|
+
// Number fields keep integral defaults as integers; compare by value.
|
|
474
|
+
if (!(desired.hasDefault && existing.has_default && sameNumber(desired.default, existing.default))) drift.push('default');
|
|
475
|
+
}
|
|
476
|
+
if ((desired.check ?? null) !== (existing.check ?? null)) drift.push('check');
|
|
477
|
+
return drift;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function sameNumber(a: Value, b: Value): boolean {
|
|
481
|
+
const number = (value: Value) => typeof value === 'bigint' ? Number(value) : typeof value === 'number' ? value : value && typeof value === 'object' && 'value' in value && typeof value.value === 'number' ? value.value : NaN;
|
|
482
|
+
return number(a) === number(b);
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
function explicitStatements(collection: CollectionSpec, step: MigrationStep, catalog: Map<string, CatalogField>, schemaless: boolean): Statement[] | string {
|
|
486
|
+
const table = collection.name;
|
|
487
|
+
if (schemaless) {
|
|
488
|
+
// Only stored values change; the host validates the declared fields.
|
|
489
|
+
switch (step.kind) {
|
|
490
|
+
case 'backfill': return [{ rql: `UPDATE ${table} SET ${quote(step.field)} = $value WHERE ${quote(step.field)} IS NULL`, params: { $value: step.value } }];
|
|
491
|
+
case 'rename': return [{ rql: `UPDATE ${table} SET ${quote(step.to)} = ${quote(step.from)} WHERE ${quote(step.to)} IS NULL AND ${quote(step.from)} IS NOT NULL` }];
|
|
492
|
+
case 'tighten': return [];
|
|
493
|
+
case 'drop': return [{ rql: `UPDATE ${table} UNSET ${quote(step.field)} WHERE ${quote(step.field)} IS NOT NULL` }];
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
switch (step.kind) {
|
|
497
|
+
case 'backfill':
|
|
498
|
+
if (!catalog.has(step.field) && !collection.fields.some(field => field.name === step.field)) return `${step.field} does not exist.`;
|
|
499
|
+
return [{ rql: `UPDATE ${table} SET ${quote(step.field)} = $value WHERE ${quote(step.field)} IS NULL`, params: { $value: step.value } }];
|
|
500
|
+
case 'rename':
|
|
501
|
+
return [{ rql: `UPDATE ${table} SET ${quote(step.to)} = ${quote(step.from)} WHERE ${quote(step.to)} IS NULL AND ${quote(step.from)} IS NOT NULL` }];
|
|
502
|
+
case 'tighten': {
|
|
503
|
+
const field = collection.fields.find(entry => entry.name === step.field);
|
|
504
|
+
if (!field) return `${step.field} is not declared.`;
|
|
505
|
+
return [{ rql: defineFieldRql(table, field, { overwrite: true }) }];
|
|
506
|
+
}
|
|
507
|
+
case 'drop': {
|
|
508
|
+
const existing = catalog.get(step.field);
|
|
509
|
+
if (!existing) return [];
|
|
510
|
+
// Relax the definition first, so removing values cannot violate it.
|
|
511
|
+
const type = existing.element_type ? `array<${existing.element_type}>` : existing.type;
|
|
512
|
+
return [
|
|
513
|
+
{ rql: `DEFINE FIELD OVERWRITE ${quote(step.field)} ON ${table} TYPE ${type} NULLABLE${existing.flexible ? ' FLEXIBLE' : ''}` },
|
|
514
|
+
{ rql: `UPDATE ${table} UNSET ${quote(step.field)} WHERE ${quote(step.field)} IS NOT NULL` },
|
|
515
|
+
{ rql: `REMOVE FIELD ${quote(step.field)} ON ${table}` },
|
|
516
|
+
];
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
function explicitStep(resource: Resource, step: MigrationStep, statements: Statement[], hash: string): PlannedStep {
|
|
522
|
+
return {
|
|
523
|
+
id: `${resource.id}#${step.version}`, resource: resource.id, owner: resource.owner, kind: 'explicit', version: step.version,
|
|
524
|
+
description: `${step.kind} ${'field' in step ? step.field : `${step.from} to ${step.to}`} on ${resource.id}`,
|
|
525
|
+
statements, declarationHash: hash,
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function chunkSteps(resource: Resource, kind: 'additive', version: number, description: string, statements: Statement[], hash: string): PlannedStep[] {
|
|
530
|
+
const chunks: Statement[][] = [];
|
|
531
|
+
for (let offset = 0; offset < statements.length; offset += MAX_STEP_STATEMENTS) chunks.push(statements.slice(offset, offset + MAX_STEP_STATEMENTS));
|
|
532
|
+
if (!chunks.length) chunks.push([]);
|
|
533
|
+
return chunks.map((chunk, index) => ({
|
|
534
|
+
id: `${resource.id}@${hash.slice(0, 16)}:${index}`, resource: resource.id, owner: resource.owner, kind, version,
|
|
535
|
+
description: chunks.length > 1 ? `${description} (${index + 1}/${chunks.length})` : description, statements: chunk, declarationHash: hash,
|
|
536
|
+
}));
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
function hostStep(step: HostStep): PlannedStep {
|
|
540
|
+
return { id: `cms#host-${step.version}`, resource: null, owner: 'cms', kind: 'host', version: step.version, description: step.description, statements: step.statements, declarationHash: null };
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Ledger rows written in the same batch as the step. Additive step IDs embed the
|
|
545
|
+
* declaration hash and chunk, so re-planning the same declaration cannot record twice.
|
|
546
|
+
*/
|
|
547
|
+
function ledgerStatements(step: PlannedStep, engineVersion: string, now: number): Statement[] {
|
|
548
|
+
const statements: Statement[] = [{
|
|
549
|
+
rql: 'INSERT INTO cms_migrations (id, kind, owner, resource, version, declaration_hash, rql, engine_version, applied_at) VALUES ($id, $kind, $owner, $resource, $version, $hash, $rql, $engine, $at)',
|
|
550
|
+
params: {
|
|
551
|
+
$id: step.kind === 'additive' ? `${step.id}:${now}` : step.id, $kind: step.kind, $owner: step.owner, $resource: step.resource, $version: step.version,
|
|
552
|
+
$hash: step.declarationHash, $rql: step.statements.map(statement => statement.rql).join(';\n'), $engine: engineVersion, $at: now,
|
|
553
|
+
},
|
|
554
|
+
}];
|
|
555
|
+
if (step.resource) statements.push({
|
|
556
|
+
rql: 'INSERT INTO cms_schema_state (resource, declaration_hash, updated_at) VALUES ($resource, $hash, $at) ON CONFLICT (resource) DO UPDATE SET declaration_hash = excluded.declaration_hash, updated_at = excluded.updated_at',
|
|
557
|
+
params: { $resource: step.resource, $hash: step.declarationHash, $at: now },
|
|
558
|
+
});
|
|
559
|
+
return statements;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
export { HOST_TABLES, SYSTEM_FIELDS };
|