tinyzoo 0.0.0-stage → 0.2.0
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 +10 -0
- package/README.md +46 -2
- package/app/app.config.ts +35 -0
- package/app/assets/brand/characters/bright/bird.svg +1 -0
- package/app/assets/brand/characters/bright/bunny.svg +1 -0
- package/app/assets/brand/characters/bright/elephant.svg +1 -0
- package/app/assets/brand/characters/bright/fox.svg +1 -0
- package/app/assets/brand/characters/bright/frog.svg +1 -0
- package/app/assets/brand/characters/bright/octopus.svg +1 -0
- package/app/assets/brand/characters/muted/bee.svg +1 -0
- package/app/assets/brand/characters/muted/bird.svg +1 -0
- package/app/assets/brand/characters/muted/butterfly.svg +1 -0
- package/app/assets/brand/characters/muted/chick.svg +1 -0
- package/app/assets/brand/characters/muted/cow.svg +1 -0
- package/app/assets/brand/characters/muted/deer.svg +1 -0
- package/app/assets/brand/characters/muted/duck.svg +1 -0
- package/app/assets/brand/characters/muted/elephant.svg +1 -0
- package/app/assets/brand/characters/muted/fox.svg +1 -0
- package/app/assets/brand/characters/muted/hedgehog.svg +1 -0
- package/app/assets/brand/characters/muted/koala.svg +1 -0
- package/app/assets/brand/characters/muted/ladybug.svg +1 -0
- package/app/assets/brand/characters/muted/lion.svg +1 -0
- package/app/assets/brand/characters/muted/mouse.svg +1 -0
- package/app/assets/brand/characters/muted/octopus.svg +1 -0
- package/app/assets/brand/characters/muted/owl.svg +1 -0
- package/app/assets/brand/characters/muted/panda.svg +1 -0
- package/app/assets/brand/characters/muted/penguin.svg +1 -0
- package/app/assets/brand/characters/muted/pig.svg +1 -0
- package/app/assets/brand/characters/muted/poodle.svg +1 -0
- package/app/assets/brand/characters/muted/raccoon.svg +1 -0
- package/app/assets/brand/characters/muted/seal.svg +1 -0
- package/app/assets/brand/characters/muted/sheep.svg +1 -0
- package/app/assets/brand/characters/muted/snail.svg +1 -0
- package/app/assets/brand/characters/muted/turtle.svg +1 -0
- package/app/assets/brand/characters/muted/whale.svg +1 -0
- package/app/assets/brand/logo/favicon.svg +1 -0
- package/app/assets/brand/logo/logo-primary-reversed.svg +1 -0
- package/app/assets/brand/logo/logo-primary.svg +1 -0
- package/app/assets/brand/logo/mascot-reversed.svg +1 -0
- package/app/assets/brand/logo/mascot.svg +1 -0
- package/app/assets/brand/logo/wordmark-reversed.svg +1 -0
- package/app/assets/brand/logo/wordmark.svg +1 -0
- package/app/assets/css/cms-admin.css +607 -0
- package/app/components/CmsBlocks.vue +30 -0
- package/app/components/CmsCell.vue +16 -0
- package/app/components/CmsCellBadge.vue +18 -0
- package/app/components/CmsCellBlocks.vue +9 -0
- package/app/components/CmsCellBoolean.vue +12 -0
- package/app/components/CmsCellCode.vue +7 -0
- package/app/components/CmsCellColor.vue +13 -0
- package/app/components/CmsCellDate.vue +10 -0
- package/app/components/CmsCellExcerpt.vue +21 -0
- package/app/components/CmsCellGallery.vue +10 -0
- package/app/components/CmsCellGroup.vue +23 -0
- package/app/components/CmsCellNumber.vue +7 -0
- package/app/components/CmsCellRelation.vue +8 -0
- package/app/components/CmsCellText.vue +12 -0
- package/app/components/CmsCellThumb.vue +18 -0
- package/app/components/CmsConfirmDialog.vue +55 -0
- package/app/components/CmsContent.vue +103 -0
- package/app/components/CmsDayPicker.vue +44 -0
- package/app/components/CmsEmptyState.vue +35 -0
- package/app/components/CmsField.vue +111 -0
- package/app/components/CmsFieldBlocks.vue +353 -0
- package/app/components/CmsFieldBoolean.vue +8 -0
- package/app/components/CmsFieldColor.vue +42 -0
- package/app/components/CmsFieldDate.vue +131 -0
- package/app/components/CmsFieldGallery.vue +114 -0
- package/app/components/CmsFieldGroup.vue +53 -0
- package/app/components/CmsFieldMedia.vue +219 -0
- package/app/components/CmsFieldNumber.vue +11 -0
- package/app/components/CmsFieldRelationMany.vue +54 -0
- package/app/components/CmsFieldRelationOne.vue +47 -0
- package/app/components/CmsFieldRichText.vue +45 -0
- package/app/components/CmsFieldSelect.vue +41 -0
- package/app/components/CmsFieldSlug.vue +46 -0
- package/app/components/CmsFieldText.vue +75 -0
- package/app/components/CmsFormSections.vue +150 -0
- package/app/components/CmsHighlight.vue +22 -0
- package/app/components/CmsImage.vue +39 -0
- package/app/components/CmsLinkPicker.vue +122 -0
- package/app/components/CmsLinkTarget.vue +35 -0
- package/app/components/CmsListFilters.vue +107 -0
- package/app/components/CmsLiveNotice.vue +64 -0
- package/app/components/CmsLoadError.vue +24 -0
- package/app/components/CmsMascot.vue +10 -0
- package/app/components/CmsMediaLibrary.vue +114 -0
- package/app/components/CmsMediaPreview.vue +34 -0
- package/app/components/CmsMediaThumb.vue +22 -0
- package/app/components/CmsMoment.vue +42 -0
- package/app/components/CmsNav.vue +39 -0
- package/app/components/CmsPage.vue +86 -0
- package/app/components/CmsPasswordInput.vue +22 -0
- package/app/components/CmsPresence.vue +29 -0
- package/app/components/CmsPreviewPanel.vue +131 -0
- package/app/components/CmsPublishReview.vue +102 -0
- package/app/components/CmsRevisions.vue +195 -0
- package/app/components/CmsRichTextEditor.vue +290 -0
- package/app/components/CmsSearch.vue +99 -0
- package/app/components/CmsSection.vue +20 -0
- package/app/components/CmsSingletonForm.vue +283 -0
- package/app/components/CmsStatusBadge.vue +21 -0
- package/app/components/CmsTime.vue +16 -0
- package/app/components/CmsTranslationRef.vue +27 -0
- package/app/components/CmsTreeList.vue +453 -0
- package/app/components/CmsUnsavedText.vue +34 -0
- package/app/components/CmsWordmark.vue +10 -0
- package/app/composables/useCmsAdminHead.ts +18 -0
- package/app/composables/useCmsCollab.ts +165 -0
- package/app/composables/useCmsConfirm.ts +39 -0
- package/app/composables/useCmsEntryActions.ts +75 -0
- package/app/composables/useCmsFocus.ts +13 -0
- package/app/composables/useCmsForm.ts +273 -0
- package/app/composables/useCmsI18n.ts +185 -0
- package/app/composables/useCmsLinkTargets.ts +84 -0
- package/app/composables/useCmsLive.ts +199 -0
- package/app/composables/useCmsSearch.ts +62 -0
- package/app/composables/useCmsSeo.ts +99 -0
- package/app/composables/useCmsSignedIn.ts +24 -0
- package/app/composables/useCmsUiLocale.ts +24 -0
- package/app/i18n/cs.ts +781 -0
- package/app/i18n/de.ts +781 -0
- package/app/i18n/en.ts +782 -0
- package/app/i18n/types.ts +22 -0
- package/app/layouts/admin.vue +224 -0
- package/app/layouts/cms-auth.vue +37 -0
- package/app/middleware/cms-api-not-a-page.global.ts +10 -0
- package/app/middleware/cms-auth.global.ts +16 -0
- package/app/pages/admin/[entity]/[id].vue +1109 -0
- package/app/pages/admin/[entity]/index.vue +733 -0
- package/app/pages/admin/account.vue +117 -0
- package/app/pages/admin/forgot.vue +50 -0
- package/app/pages/admin/index.vue +184 -0
- package/app/pages/admin/invite/[token].vue +73 -0
- package/app/pages/admin/login.vue +84 -0
- package/app/pages/admin/media.vue +494 -0
- package/app/pages/admin/privacy.vue +193 -0
- package/app/pages/admin/reset/[token].vue +52 -0
- package/app/pages/admin/setup.vue +87 -0
- package/app/pages/admin/styleguide.vue +261 -0
- package/app/pages/admin/team.vue +258 -0
- package/app/plugins/cmsLivePreview.client.ts +20 -0
- package/app/plugins/cmsSignedOut.client.ts +31 -0
- package/app/utils/cmsBlockType.ts +11 -0
- package/app/utils/cmsBrand.ts +38 -0
- package/app/utils/cmsDiff.ts +83 -0
- package/app/utils/cmsFetch.ts +7 -0
- package/app/utils/cmsFocusInvalid.ts +22 -0
- package/app/utils/cmsIssues.ts +128 -0
- package/app/utils/cmsJson.ts +28 -0
- package/app/utils/cmsMedia.ts +63 -0
- package/app/utils/cmsSections.ts +154 -0
- package/app/utils/cmsTime.ts +41 -0
- package/cli/backup.ts +713 -0
- package/cli/breaking.ts +174 -0
- package/cli/content-migrate.ts +239 -0
- package/cli/db.ts +86 -0
- package/cli/export.ts +336 -0
- package/cli/generate.ts +146 -0
- package/cli/import.ts +643 -0
- package/cli/index.ts +140 -0
- package/cli/links-convert.ts +291 -0
- package/cli/seed-engine.ts +705 -0
- package/cli/seed.ts +339 -0
- package/cli/status.ts +49 -0
- package/cli/tar.ts +304 -0
- package/cli/transfer.ts +677 -0
- package/cli/up.ts +27 -0
- package/cli/upgrade.ts +60 -0
- package/cli/versions.ts +60 -0
- package/forms/components/CmsForm.vue +186 -0
- package/forms/index.ts +203 -0
- package/forms/messages.ts +104 -0
- package/forms/retention.ts +48 -0
- package/forms/server/form.get.ts +12 -0
- package/forms/server/form.post.ts +109 -0
- package/forms/server/formSettings.ts +12 -0
- package/forms/server/forms.ts +127 -0
- package/module.ts +373 -0
- package/nuxt.config.ts +43 -0
- package/package.json +99 -3
- package/server/api/cms/[entity]/[id]/revisions/[rev].get.ts +19 -0
- package/server/api/cms/[entity]/[id]/revisions/index.get.ts +14 -0
- package/server/api/cms/[entity]/[id].delete.ts +52 -0
- package/server/api/cms/[entity]/[id].get.ts +21 -0
- package/server/api/cms/[entity]/[id].patch.ts +116 -0
- package/server/api/cms/[entity]/_export.get.ts +69 -0
- package/server/api/cms/[entity]/_move.post.ts +81 -0
- package/server/api/cms/[entity]/_order.post.ts +49 -0
- package/server/api/cms/[entity]/_tree.get.ts +41 -0
- package/server/api/cms/[entity]/index.get.ts +62 -0
- package/server/api/cms/[entity]/index.post.ts +38 -0
- package/server/api/cms/[entity]/options.get.ts +55 -0
- package/server/api/cms/_auth/accept.post.ts +33 -0
- package/server/api/cms/_auth/forgot.post.ts +39 -0
- package/server/api/cms/_auth/invite/[token].get.ts +18 -0
- package/server/api/cms/_auth/login.post.ts +42 -0
- package/server/api/cms/_auth/logout.post.ts +7 -0
- package/server/api/cms/_auth/me.get.ts +5 -0
- package/server/api/cms/_auth/me.patch.ts +32 -0
- package/server/api/cms/_auth/password.post.ts +29 -0
- package/server/api/cms/_auth/reset.post.ts +34 -0
- package/server/api/cms/_auth/setup.post.ts +46 -0
- package/server/api/cms/_auth/status.get.ts +18 -0
- package/server/api/cms/_collab/session.get.ts +30 -0
- package/server/api/cms/_collab/socket.ts +51 -0
- package/server/api/cms/_collab/unsaved.delete.ts +16 -0
- package/server/api/cms/_graph.get.ts +20 -0
- package/server/api/cms/_links/resolve.post.ts +17 -0
- package/server/api/cms/_links.get.ts +81 -0
- package/server/api/cms/_live.ts +30 -0
- package/server/api/cms/_media/[id]/usage.get.ts +14 -0
- package/server/api/cms/_media/[id].delete.ts +29 -0
- package/server/api/cms/_media/[id].get.ts +13 -0
- package/server/api/cms/_media/[id].patch.ts +64 -0
- package/server/api/cms/_media/exists.post.ts +15 -0
- package/server/api/cms/_media/img/[id]/[file].get.ts +42 -0
- package/server/api/cms/_media/index.get.ts +44 -0
- package/server/api/cms/_media/index.post.ts +147 -0
- package/server/api/cms/_media/raw/[...key].get.ts +85 -0
- package/server/api/cms/_media/raw/[...key].head.ts +2 -0
- package/server/api/cms/_overview.get.ts +87 -0
- package/server/api/cms/_preview.post.ts +17 -0
- package/server/api/cms/_privacy/delete.post.ts +14 -0
- package/server/api/cms/_privacy/export.post.ts +25 -0
- package/server/api/cms/_privacy/lookup.post.ts +27 -0
- package/server/api/cms/_search.get.ts +17 -0
- package/server/api/cms/_singleton/[name].get.ts +19 -0
- package/server/api/cms/_singleton/[name].put.ts +76 -0
- package/server/api/cms/_users/[id]/resend.post.ts +25 -0
- package/server/api/cms/_users/[id].delete.ts +21 -0
- package/server/api/cms/_users/[id].patch.ts +45 -0
- package/server/api/cms/_users/index.get.ts +28 -0
- package/server/api/cms/_users/index.post.ts +39 -0
- package/server/api/content/[entity]/[slug].get.ts +74 -0
- package/server/api/content/[entity]/index.get.ts +100 -0
- package/server/api/content/_global/[name].get.ts +23 -0
- package/server/api/content/_search.get.ts +28 -0
- package/server/api/content/_sitemap.get.ts +8 -0
- package/server/api/content/_tree/[entity].get.ts +31 -0
- package/server/api/content-types.ts.get.ts +17 -0
- package/server/api/health/live.get.ts +10 -0
- package/server/api/health/ready.get.ts +21 -0
- package/server/api/openapi.get.ts +48 -0
- package/server/api/openapi.json.get.ts +32 -0
- package/server/db/driver.ts +8 -0
- package/server/mail/mailer.ts +43 -0
- package/server/middleware/cms-0-headers.ts +37 -0
- package/server/middleware/cms-0-migrate-gate.ts +14 -0
- package/server/middleware/cms-csrf.ts +28 -0
- package/server/middleware/cms-limits.ts +20 -0
- package/server/middleware/cms-redirects.ts +21 -0
- package/server/middleware/cms-session.ts +41 -0
- package/server/middleware/cms-z-plugin-access.ts +15 -0
- package/server/plugins/cms-0-config-check.ts +35 -0
- package/server/plugins/cms-changes.ts +53 -0
- package/server/plugins/cms-content-etag.ts +21 -0
- package/server/plugins/cms-errors.ts +45 -0
- package/server/plugins/cms-migrate.ts +5 -0
- package/server/plugins/cms-plugins.ts +17 -0
- package/server/plugins/cms-search.ts +12 -0
- package/server/plugins/cms-setup-code.ts +15 -0
- package/server/routes/sitemap.xml.get.ts +25 -0
- package/server/store/redis.ts +95 -0
- package/server/store/types.ts +21 -0
- package/server/tasks/cms/retention.ts +10 -0
- package/server/tasks/cms/scheduled.ts +10 -0
- package/server/tasks/cms/search-reindex.ts +12 -0
- package/server/utils/cmsAudit.ts +29 -0
- package/server/utils/cmsAuth.ts +143 -0
- package/server/utils/cmsBlocks.ts +47 -0
- package/server/utils/cmsChanges.ts +222 -0
- package/server/utils/cmsCollab.ts +286 -0
- package/server/utils/cmsCollabServer.ts +451 -0
- package/server/utils/cmsCollate.ts +27 -0
- package/server/utils/cmsContent.ts +376 -0
- package/server/utils/cmsCrud.ts +361 -0
- package/server/utils/cmsCsv.ts +24 -0
- package/server/utils/cmsDb.ts +23 -0
- package/server/utils/cmsDemo.ts +36 -0
- package/server/utils/cmsEmails.ts +125 -0
- package/server/utils/cmsErrors.ts +40 -0
- package/server/utils/cmsFold.ts +17 -0
- package/server/utils/cmsImageSizes.ts +51 -0
- package/server/utils/cmsJson.ts +6 -0
- package/server/utils/cmsLinkAddress.ts +50 -0
- package/server/utils/cmsLinks.ts +248 -0
- package/server/utils/cmsListQuery.ts +93 -0
- package/server/utils/cmsLive.ts +392 -0
- package/server/utils/cmsLocales.ts +96 -0
- package/server/utils/cmsMail.ts +28 -0
- package/server/utils/cmsMediaGc.ts +188 -0
- package/server/utils/cmsMediaKeys.ts +62 -0
- package/server/utils/cmsMigrate.ts +86 -0
- package/server/utils/cmsPreviewDraft.ts +72 -0
- package/server/utils/cmsPrivacy.ts +176 -0
- package/server/utils/cmsPublished.ts +57 -0
- package/server/utils/cmsRange.ts +38 -0
- package/server/utils/cmsRateLimit.ts +82 -0
- package/server/utils/cmsRedirects.ts +160 -0
- package/server/utils/cmsRetention.ts +61 -0
- package/server/utils/cmsRevisions.ts +103 -0
- package/server/utils/cmsScheduler.ts +45 -0
- package/server/utils/cmsScrub.ts +107 -0
- package/server/utils/cmsSearch.ts +354 -0
- package/server/utils/cmsSession.ts +102 -0
- package/server/utils/cmsSetupCode.ts +97 -0
- package/server/utils/cmsSitemap.ts +176 -0
- package/server/utils/cmsStorage.ts +580 -0
- package/server/utils/cmsStore.ts +109 -0
- package/server/utils/cmsTooMany.ts +9 -0
- package/server/utils/cmsTranslationWrite.ts +186 -0
- package/server/utils/cmsTree.ts +251 -0
- package/server/utils/cmsTreeAddress.ts +65 -0
- package/server/utils/cmsUpload.ts +197 -0
- package/server/utils/cmsWebhooks.ts +101 -0
- package/shared/json.ts +11 -0
- package/shared/richtext-editor.ts +56 -0
- package/shared/richtext-normalize.ts +33 -0
- package/shared/richtext-paste.ts +151 -0
- package/shared/storage-delivery.ts +53 -0
- package/src/blocks.ts +624 -0
- package/src/changes.ts +54 -0
- package/src/content-shape.ts +340 -0
- package/src/deprecate.ts +64 -0
- package/src/descriptor.ts +149 -0
- package/src/docs.ts +27 -0
- package/src/emitter.ts +94 -0
- package/src/entity.ts +624 -0
- package/src/errorReport.ts +41 -0
- package/src/fields.ts +465 -0
- package/src/i18n.ts +26 -0
- package/src/index.ts +54 -0
- package/src/linkref.ts +31 -0
- package/src/links.ts +179 -0
- package/src/locales.ts +39 -0
- package/src/media.ts +48 -0
- package/src/migrate.ts +236 -0
- package/src/openapi.ts +377 -0
- package/src/paths.ts +88 -0
- package/src/plugin.ts +505 -0
- package/src/presets.ts +230 -0
- package/src/richtext.ts +88 -0
- package/src/sdk.ts +181 -0
- package/src/search.ts +312 -0
- package/src/seed.ts +225 -0
- package/src/setupCode.ts +30 -0
- package/src/system.ts +219 -0
- package/src/tree.ts +421 -0
- package/src/upgrades.ts +137 -0
- package/starter/.env.example +10 -0
- package/starter/README.md +65 -0
- package/starter/app/app.config.ts +10 -0
- package/starter/app/app.vue +12 -0
- package/starter/app/assets/css/main.css +15 -0
- package/starter/app/components/global/BlockContact.vue +15 -0
- package/starter/app/components/global/BlockCta.vue +15 -0
- package/starter/app/components/global/BlockHero.vue +23 -0
- package/starter/app/components/global/BlockImage.vue +13 -0
- package/starter/app/components/global/BlockText.vue +12 -0
- package/starter/app/composables/useSite.ts +77 -0
- package/starter/app/error.vue +28 -0
- package/starter/app/layouts/default.vue +106 -0
- package/starter/app/lib/cms-content.ts +152 -0
- package/starter/app/pages/[...slug].vue +66 -0
- package/starter/app/pages/hledat.vue +59 -0
- package/starter/app/pages/index.vue +20 -0
- package/starter/cms.config.ts +137 -0
- package/starter/compose.yaml +15 -0
- package/starter/drizzle.config.ts +8 -0
- package/starter/gitignore.txt +8 -0
- package/starter/nuxt.config.ts +13 -0
- package/starter/package.json +38 -0
- package/starter/scripts/typecheck.mjs +38 -0
- package/starter/seed/index.ts +297 -0
- package/starter/seed/media/about.jpg +0 -0
- package/starter/seed/media/hero.jpg +0 -0
- package/starter/seed/media/logo.png +0 -0
- package/starter/seed/media/news-bread.jpg +0 -0
- package/starter/seed/media/news-morning.jpg +0 -0
- package/starter/server/db/migrations/0000_init.sql +269 -0
- package/starter/server/db/migrations/0001_page_tree.sql +5 -0
- package/starter/server/db/migrations/0002_opening_hours_per_language.sql +1 -0
- package/starter/server/db/migrations/meta/0000_snapshot.json +1890 -0
- package/starter/server/db/migrations/meta/0001_snapshot.json +1887 -0
- package/starter/server/db/migrations/meta/0002_snapshot.json +1893 -0
- package/starter/server/db/migrations/meta/_journal.json +27 -0
- package/starter/server/db/schema.ts +253 -0
- package/starter/server/plugins/sitemap.ts +11 -0
- package/starter/server/routes/robots.txt.get.ts +12 -0
- package/starter/tsconfig.json +9 -0
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
import { and, eq, inArray, sql } from 'tinyzoo'
|
|
2
|
+
import { Hocuspocus } from '@hocuspocus/server'
|
|
3
|
+
import * as Y from 'yjs'
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The shared-editing engine (Hocuspocus), on the app's own port: it opens no server
|
|
7
|
+
* of its own — api/cms/_collab/socket.ts hands it sockets Nitro already accepted.
|
|
8
|
+
* See cmsCollab.ts for what a document is.
|
|
9
|
+
*
|
|
10
|
+
* Who may join is decided per document in onAuthenticate, from the account behind
|
|
11
|
+
* the socket — read fresh from the database every time, never trusted from the
|
|
12
|
+
* upgrade alone — and the epoch the browser presents as its token. People who may
|
|
13
|
+
* only read join read-only. Every 30 seconds each open connection is checked again
|
|
14
|
+
* (also ones that only listen); a failed check closes the whole socket, so the
|
|
15
|
+
* browser reconnects and is authorised afresh — or not.
|
|
16
|
+
*
|
|
17
|
+
* Several replicas share documents through Redis (when configured) and all store
|
|
18
|
+
* into the same `cms_collab` row. Who has a document open is then known per replica
|
|
19
|
+
* only, so each replica also lists its open documents in Redis (see `Presence`), and
|
|
20
|
+
* "the last one left" means: no connection here and none listed by another replica.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
interface CollabContext {
|
|
24
|
+
user: CmsUser
|
|
25
|
+
/** The name other people see on this person's cursor (from the account, not the browser). */
|
|
26
|
+
displayName: string
|
|
27
|
+
/** The one Yjs client this connection may speak for in cursor (awareness) updates. */
|
|
28
|
+
clientId?: number
|
|
29
|
+
sv: number
|
|
30
|
+
epoch: string
|
|
31
|
+
access: 'write' | 'read'
|
|
32
|
+
checkedAt: number
|
|
33
|
+
checking?: Promise<void>
|
|
34
|
+
target: { entityName: string; id: string; locale: string | null }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const RECHECK_MS = 30_000
|
|
38
|
+
const HEARTBEAT_MS = 30_000
|
|
39
|
+
/** Limits: per message, per stored document, per socket. */
|
|
40
|
+
const MAX_UPDATE_BYTES = 1024 * 1024
|
|
41
|
+
const MAX_STATE_BYTES = 8 * 1024 * 1024
|
|
42
|
+
const MAX_DOCS_PER_SOCKET = 10
|
|
43
|
+
// Hocuspocus message types (y-protocols / Hocuspocus numbering).
|
|
44
|
+
const AWARENESS = 1
|
|
45
|
+
// …and ones this admin never sends.
|
|
46
|
+
const STATELESS = 5
|
|
47
|
+
const BROADCAST_STATELESS = 6
|
|
48
|
+
|
|
49
|
+
/** Who is in a document, across replicas: this replica's entries in a Redis sorted set per document. */
|
|
50
|
+
const PRESENCE_TTL_MS = 90_000
|
|
51
|
+
/** This replica, as the presence lists name it. */
|
|
52
|
+
const REPLICA_ID = crypto.randomUUID()
|
|
53
|
+
|
|
54
|
+
interface Presence {
|
|
55
|
+
/** This replica has a connection in the document (refreshed every heartbeat; expires if the replica dies). */
|
|
56
|
+
here(documentName: string): Promise<void>
|
|
57
|
+
/** This replica has no connection left in the document. */
|
|
58
|
+
left(documentName: string): Promise<void>
|
|
59
|
+
/** Does another replica list a connection in the document? Throws when Redis cannot say. */
|
|
60
|
+
othersHere(documentName: string): Promise<boolean>
|
|
61
|
+
close(): Promise<void>
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function createPresence(redisUrl: string, prefix: string): Promise<Presence> {
|
|
65
|
+
const { default: IORedis } = await import('ioredis')
|
|
66
|
+
// Like the shared store: never wait on a Redis that is down (callers fall back to the 90 s window).
|
|
67
|
+
const redis = new IORedis(redisUrl, { maxRetriesPerRequest: 1, enableOfflineQueue: false, commandTimeout: 500, connectTimeout: 2_000 })
|
|
68
|
+
redis.on('error', (err) => console.error('[cms] collab presence', err.message))
|
|
69
|
+
const key = (name: string) => `${prefix}:presence:${name}`
|
|
70
|
+
return {
|
|
71
|
+
async here(name) {
|
|
72
|
+
await redis.multi().zadd(key(name), Date.now() + PRESENCE_TTL_MS, REPLICA_ID).pexpire(key(name), PRESENCE_TTL_MS * 2).exec()
|
|
73
|
+
},
|
|
74
|
+
async left(name) {
|
|
75
|
+
await redis.zrem(key(name), REPLICA_ID)
|
|
76
|
+
},
|
|
77
|
+
async othersHere(name) {
|
|
78
|
+
const res = await redis.multi().zremrangebyscore(key(name), '-inf', Date.now()).zrange(key(name), 0, -1).exec()
|
|
79
|
+
const [err, members] = res?.[1] ?? [new Error('empty transaction result'), null]
|
|
80
|
+
if (err || !Array.isArray(members)) throw err ?? new Error('presence list missing')
|
|
81
|
+
return members.some((m) => m !== REPLICA_ID)
|
|
82
|
+
},
|
|
83
|
+
async close() {
|
|
84
|
+
await redis.quit().catch(() => redis.disconnect())
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
let presence: Presence | null = null
|
|
90
|
+
|
|
91
|
+
let instance: Hocuspocus | null = null
|
|
92
|
+
let starting: Promise<Hocuspocus> | null = null
|
|
93
|
+
let heartbeat: ReturnType<typeof setInterval> | null = null
|
|
94
|
+
let lastPurge = 0
|
|
95
|
+
/** The epoch each loaded document belongs to (what it may store into). */
|
|
96
|
+
const loadedEpoch = new Map<string, string>()
|
|
97
|
+
/** Documents opened on each socket. */
|
|
98
|
+
const docsBySocket = new Map<string, Set<string>>()
|
|
99
|
+
|
|
100
|
+
export function useCollabServer(): Promise<Hocuspocus> {
|
|
101
|
+
starting ??= startCollabServer().catch((err) => {
|
|
102
|
+
starting = null
|
|
103
|
+
throw err
|
|
104
|
+
})
|
|
105
|
+
return starting
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Close a whole socket: the browser reconnects and is authorised afresh. */
|
|
109
|
+
function dropSocket(ws: any, code = 4401, reason = 'Not permitted') {
|
|
110
|
+
try {
|
|
111
|
+
ws?.close?.(code, reason)
|
|
112
|
+
}
|
|
113
|
+
catch { /* already closing */ }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Is this account still allowed this document, and with which access? */
|
|
117
|
+
async function recheck(ctx: CollabContext): Promise<'write' | 'read' | null> {
|
|
118
|
+
const u = await activeAccountOf({ cms: { uid: ctx.user.id, sv: ctx.sv } })
|
|
119
|
+
if (!u || u.role !== ctx.user.role) return null
|
|
120
|
+
const target = parseCollabName(collabName(ctx.target.entityName, ctx.target.id, ctx.target.locale))
|
|
121
|
+
return target ? collabAccess({ ...ctx.user, role: u.role }, target) : null
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Reads the lib0 encoding Hocuspocus messages use (varUint, length-prefixed strings). */
|
|
125
|
+
function reader(bytes: Uint8Array) {
|
|
126
|
+
let pos = 0
|
|
127
|
+
const varUint = () => {
|
|
128
|
+
let n = 0
|
|
129
|
+
let mult = 1
|
|
130
|
+
while (pos < bytes.length) {
|
|
131
|
+
const b = bytes[pos++]!
|
|
132
|
+
n += (b & 0x7F) * mult
|
|
133
|
+
if (b < 0x80) return n
|
|
134
|
+
mult *= 128
|
|
135
|
+
}
|
|
136
|
+
throw new Error('truncated')
|
|
137
|
+
}
|
|
138
|
+
const bytesOf = () => {
|
|
139
|
+
const len = varUint()
|
|
140
|
+
if (pos + len > bytes.length) throw new Error('truncated')
|
|
141
|
+
const out = bytes.subarray(pos, pos + len)
|
|
142
|
+
pos += len
|
|
143
|
+
return out
|
|
144
|
+
}
|
|
145
|
+
return { varUint, bytesOf, string: () => new TextDecoder().decode(bytesOf()) }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** A message's type and the rest of it: after the document name. */
|
|
149
|
+
function parseMessage(update: Uint8Array): { type: number; body: ReturnType<typeof reader> } | null {
|
|
150
|
+
try {
|
|
151
|
+
const r = reader(update)
|
|
152
|
+
r.bytesOf() // document name
|
|
153
|
+
return { type: r.varUint(), body: r }
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
return null
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* A cursor (awareness) update is accepted when its own entry — this connection's
|
|
162
|
+
* Yjs client, the first one it announced — carries the account's own name, and any
|
|
163
|
+
* other entries are echoes (a browser answering "who is here?" repeats everyone it
|
|
164
|
+
* knows): not newer than what the server already has, and not removing anyone. So
|
|
165
|
+
* nobody can pass as someone else, or move or remove other people's cursors.
|
|
166
|
+
*/
|
|
167
|
+
function awarenessAllowed(ctx: CollabContext, body: ReturnType<typeof reader>, awareness: any): boolean {
|
|
168
|
+
try {
|
|
169
|
+
const r = reader(body.bytesOf())
|
|
170
|
+
const count = r.varUint()
|
|
171
|
+
if (count > 200) return false
|
|
172
|
+
const entries: { clientId: number; clock: number; state: any }[] = []
|
|
173
|
+
for (let i = 0; i < count; i++) entries.push({ clientId: r.varUint(), clock: r.varUint(), state: JSON.parse(r.string()) })
|
|
174
|
+
if (ctx.clientId === undefined && entries.length === 1) ctx.clientId = entries[0]!.clientId
|
|
175
|
+
for (const e of entries) {
|
|
176
|
+
if (e.clientId === ctx.clientId) {
|
|
177
|
+
// No `user` yet (the first, empty state) is fine; a name must be the account's.
|
|
178
|
+
if (e.state?.user !== undefined && e.state.user?.name !== ctx.displayName) return false
|
|
179
|
+
continue
|
|
180
|
+
}
|
|
181
|
+
const known = awareness?.meta?.get(e.clientId)
|
|
182
|
+
if (!known) return false
|
|
183
|
+
if (e.clock > known.clock) return false
|
|
184
|
+
if (e.clock === known.clock && e.state === null) return false
|
|
185
|
+
}
|
|
186
|
+
return true
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
return false
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async function startCollabServer(): Promise<Hocuspocus> {
|
|
194
|
+
const extensions: any[] = []
|
|
195
|
+
const redisUrl = String((useRuntimeConfig().cms as any)?.redis?.url || process.env.REDIS_URL || '')
|
|
196
|
+
if (redisUrl) {
|
|
197
|
+
const [{ Redis: RedisExtension }, { default: IORedis }] = await Promise.all([import('@hocuspocus/extension-redis'), import('ioredis')])
|
|
198
|
+
extensions.push(new RedisExtension({ createClient: () => new IORedis(redisUrl, { maxRetriesPerRequest: null }) as any, prefix: `${cmsStorePrefix()}:collab` } as any))
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// "Nobody has it open" is known the moment the last tab leaves: with one instance
|
|
202
|
+
// from its own connections, with several (Redis) from the replicas' presence lists.
|
|
203
|
+
// If Redis cannot say, only the 90 s activity window does.
|
|
204
|
+
presence = redisUrl ? await createPresence(redisUrl, `${cmsStorePrefix()}:collab`).catch((err) => {
|
|
205
|
+
console.error('[cms] collab presence unavailable', safeErrorMessage(err))
|
|
206
|
+
return null
|
|
207
|
+
}) : null
|
|
208
|
+
const redisPresence = presence
|
|
209
|
+
/** Does anyone have the document open (here, or on another replica)? A guess of yes when unsure. */
|
|
210
|
+
const occupied = async (document: { name: string; getConnectionsCount(): number }): Promise<boolean> => {
|
|
211
|
+
if (document.getConnectionsCount() > 0) return true
|
|
212
|
+
if (redisUrl && !redisPresence) return true
|
|
213
|
+
if (!redisPresence) return false
|
|
214
|
+
try {
|
|
215
|
+
return await redisPresence.othersHere(document.name)
|
|
216
|
+
}
|
|
217
|
+
catch {
|
|
218
|
+
return true
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const server: Hocuspocus = new Hocuspocus({
|
|
222
|
+
name: 'cms',
|
|
223
|
+
extensions,
|
|
224
|
+
// Store a few seconds after typing stops, and at least every 15 s while it goes on.
|
|
225
|
+
debounce: 3_000,
|
|
226
|
+
maxDebounce: 15_000,
|
|
227
|
+
quiet: true,
|
|
228
|
+
|
|
229
|
+
async onAuthenticate({ documentName, token, context, connectionConfig, socketId }) {
|
|
230
|
+
const socketUser = context?.user as CmsUser | undefined
|
|
231
|
+
if (!socketUser) throw new Error('Not signed in')
|
|
232
|
+
const target = parseCollabName(documentName)
|
|
233
|
+
// Only the canonical spelling of a name.
|
|
234
|
+
if (!target || target.name !== documentName) throw new Error('Unknown document')
|
|
235
|
+
// The account as it is now (disabled, demoted, signed out everywhere?).
|
|
236
|
+
const u = await activeAccountOf({ cms: { uid: socketUser.id, sv: context.sv } })
|
|
237
|
+
if (!u) throw new Error('Session no longer valid')
|
|
238
|
+
const user: CmsUser = { ...socketUser, role: u.role, name: u.name || socketUser.name }
|
|
239
|
+
const access = await collabAccess(user, target)
|
|
240
|
+
if (!access) throw new Error('Not permitted')
|
|
241
|
+
const docs = docsBySocket.get(socketId) ?? new Set<string>()
|
|
242
|
+
if (!docs.has(documentName) && docs.size >= MAX_DOCS_PER_SOCKET) throw new Error('Too many documents on one socket')
|
|
243
|
+
const { db, reg } = useCms()
|
|
244
|
+
const [row] = await db.select({ epoch: reg.cmsCollab.epoch }).from(reg.cmsCollab).where(eq(reg.cmsCollab.name, target.name))
|
|
245
|
+
// An older history (or none): the browser starts over with a fresh session.
|
|
246
|
+
if (!row || row.epoch !== token) throw new Error('Stale document')
|
|
247
|
+
// Loaded here from an older history (restarted meanwhile): unload it first, so
|
|
248
|
+
// this connection gets the current one.
|
|
249
|
+
const loaded = loadedEpoch.get(documentName)
|
|
250
|
+
if (loaded && loaded !== row.epoch) {
|
|
251
|
+
const doc = server.documents.get(documentName)
|
|
252
|
+
// Nobody is in it: it only waits to be unloaded (with Redis, a second after the last
|
|
253
|
+
// tab left). Unload it now and let this connection load the current history.
|
|
254
|
+
if (doc && doc.getConnectionsCount() === 0) await server.unloadDocument(doc)
|
|
255
|
+
if (loadedEpoch.get(documentName) === loaded) {
|
|
256
|
+
// Still in use by others: they are sent away, and this connection comes back for the current one.
|
|
257
|
+
server.closeConnections(documentName)
|
|
258
|
+
if (doc) await server.unloadDocument(doc)
|
|
259
|
+
throw new Error('Stale document')
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
docs.add(documentName)
|
|
263
|
+
docsBySocket.set(socketId, docs)
|
|
264
|
+
if (access === 'read') connectionConfig.readOnly = true
|
|
265
|
+
return { user, displayName: displayName(u.name, u.email), sv: context.sv, epoch: row.epoch, access, checkedAt: Date.now(), target: { entityName: target.entity.name, id: target.id, locale: target.locale } } satisfies CollabContext
|
|
266
|
+
},
|
|
267
|
+
|
|
268
|
+
async onLoadDocument({ documentName, document, context }) {
|
|
269
|
+
const { db, reg } = useCms()
|
|
270
|
+
const [row] = await db.select().from(reg.cmsCollab).where(eq(reg.cmsCollab.name, documentName))
|
|
271
|
+
if (!row) throw new Error('No such document')
|
|
272
|
+
// Restarted between the check and the load: refuse, the browser starts over.
|
|
273
|
+
if (context?.epoch && row.epoch !== context.epoch) throw new Error('Stale document')
|
|
274
|
+
loadedEpoch.set(documentName, row.epoch)
|
|
275
|
+
Y.applyUpdate(document, decodeState(row.state))
|
|
276
|
+
await db.update(reg.cmsCollab).set({ activeAt: sql`now()` }).where(eq(reg.cmsCollab.name, documentName))
|
|
277
|
+
return document
|
|
278
|
+
},
|
|
279
|
+
|
|
280
|
+
async onStoreDocument({ documentName, document, context }) {
|
|
281
|
+
const epoch = loadedEpoch.get(documentName)
|
|
282
|
+
if (!epoch) return
|
|
283
|
+
const state = encodeState(document)
|
|
284
|
+
if (state.length > MAX_STATE_BYTES) {
|
|
285
|
+
console.error(`[cms] collab: ${documentName} grew past ${MAX_STATE_BYTES} bytes; not stored, connections closed`)
|
|
286
|
+
server.closeConnections(documentName)
|
|
287
|
+
return
|
|
288
|
+
}
|
|
289
|
+
const { db, reg } = useCms()
|
|
290
|
+
const c = reg.cmsCollab
|
|
291
|
+
// Only into the history it came from: a document restarted meanwhile is not overwritten.
|
|
292
|
+
// An error is thrown on: Hocuspocus keeps the document loaded and tries again.
|
|
293
|
+
// Active while someone has it open; the last save after everyone left does not make it so.
|
|
294
|
+
const active = await occupied(document)
|
|
295
|
+
const stored: any[] = await db.update(c).set({ state, updatedAt: sql`now()`, activeAt: active ? sql`now()` : null })
|
|
296
|
+
.where(and(eq(c.name, documentName), eq(c.epoch, epoch))).returning({ name: c.name })
|
|
297
|
+
// Who typed last: shown with text that is left behind unsaved.
|
|
298
|
+
const typist = (context as CollabContext | undefined)?.displayName
|
|
299
|
+
if (stored.length && typist) await noteCollabEditor(documentName, typist).catch(() => {})
|
|
300
|
+
if (!stored.length) {
|
|
301
|
+
// Restarted (or deleted) meanwhile: what is loaded here is an old history.
|
|
302
|
+
console.warn(`[cms] collab: ${documentName} was restarted elsewhere; closing its old copy here`)
|
|
303
|
+
server.closeConnections(documentName)
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
|
|
307
|
+
async connected({ documentName }) {
|
|
308
|
+
await redisPresence?.here(documentName).catch(() => {})
|
|
309
|
+
},
|
|
310
|
+
|
|
311
|
+
async afterUnloadDocument({ documentName }) {
|
|
312
|
+
loadedEpoch.delete(documentName)
|
|
313
|
+
},
|
|
314
|
+
|
|
315
|
+
async onDisconnect({ socketId, documentName, clientsCount }) {
|
|
316
|
+
const docs = docsBySocket.get(socketId)
|
|
317
|
+
docs?.delete(documentName)
|
|
318
|
+
if (docs && !docs.size) docsBySocket.delete(socketId)
|
|
319
|
+
// The last one left: nobody has it open now (not for another minute and a half).
|
|
320
|
+
if (clientsCount === 0) {
|
|
321
|
+
if (redisPresence) {
|
|
322
|
+
// Leave the list first: of two replicas losing their last tab at once, the later one sees it empty.
|
|
323
|
+
await redisPresence.left(documentName).catch(() => {})
|
|
324
|
+
if (await redisPresence.othersHere(documentName).catch(() => true)) return
|
|
325
|
+
}
|
|
326
|
+
else if (redisUrl) return
|
|
327
|
+
const { db, reg } = useCms()
|
|
328
|
+
await db.update(reg.cmsCollab).set({ activeAt: null }).where(eq(reg.cmsCollab.name, documentName)).catch(() => {})
|
|
329
|
+
}
|
|
330
|
+
},
|
|
331
|
+
|
|
332
|
+
async beforeHandleMessage({ context, update, connection, document }) {
|
|
333
|
+
const ctx = context as CollabContext
|
|
334
|
+
if (update.length > MAX_UPDATE_BYTES) {
|
|
335
|
+
dropSocket(connection.webSocket, 1009, 'Message too large')
|
|
336
|
+
throw new Error('Message too large')
|
|
337
|
+
}
|
|
338
|
+
const message = parseMessage(update)
|
|
339
|
+
if (!message || message.type === STATELESS || message.type === BROADCAST_STATELESS) {
|
|
340
|
+
dropSocket(connection.webSocket, 4400, 'Unsupported message')
|
|
341
|
+
throw new Error('Unsupported message')
|
|
342
|
+
}
|
|
343
|
+
if (message.type === AWARENESS && !awarenessAllowed(ctx, message.body, document.awareness)) {
|
|
344
|
+
dropSocket(connection.webSocket, 4403, 'Not your cursor')
|
|
345
|
+
throw new Error('Cursor update for someone else')
|
|
346
|
+
}
|
|
347
|
+
// Messages wait for a check in progress, so none slips past a revocation.
|
|
348
|
+
if (ctx.checking) await ctx.checking
|
|
349
|
+
if (Date.now() - ctx.checkedAt < RECHECK_MS) return
|
|
350
|
+
ctx.checking = (async () => {
|
|
351
|
+
const access = await recheck(ctx)
|
|
352
|
+
ctx.checkedAt = Date.now()
|
|
353
|
+
if (!access || (ctx.access === 'write' && access !== 'write')) {
|
|
354
|
+
dropSocket(connection.webSocket)
|
|
355
|
+
throw new Error('Not permitted any more')
|
|
356
|
+
}
|
|
357
|
+
})().finally(() => { ctx.checking = undefined })
|
|
358
|
+
await ctx.checking
|
|
359
|
+
},
|
|
360
|
+
})
|
|
361
|
+
instance = server
|
|
362
|
+
|
|
363
|
+
heartbeat ??= setInterval(() => { void beat() }, HEARTBEAT_MS)
|
|
364
|
+
;(heartbeat as any).unref?.()
|
|
365
|
+
return server
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Every 30 s: re-check every open connection (also ones that only listen), mark
|
|
370
|
+
* documents someone is editing as active (they are never restarted under them), and
|
|
371
|
+
* now and then forget documents nobody touched for a month.
|
|
372
|
+
*/
|
|
373
|
+
async function beat() {
|
|
374
|
+
const server = instance
|
|
375
|
+
if (!server) return
|
|
376
|
+
const { db, reg } = useCms()
|
|
377
|
+
const editing: string[] = []
|
|
378
|
+
for (const doc of server.documents.values()) {
|
|
379
|
+
let writers = 0
|
|
380
|
+
for (const conn of doc.getConnections()) {
|
|
381
|
+
const ctx = conn.context as CollabContext | undefined
|
|
382
|
+
if (!ctx?.user) continue
|
|
383
|
+
try {
|
|
384
|
+
const access = await recheck(ctx)
|
|
385
|
+
ctx.checkedAt = Date.now()
|
|
386
|
+
if (!access || (ctx.access === 'write' && access !== 'write')) {
|
|
387
|
+
dropSocket(conn.webSocket)
|
|
388
|
+
continue
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
catch (err) {
|
|
392
|
+
console.error('[cms] collab re-check failed', safeErrorMessage(err))
|
|
393
|
+
}
|
|
394
|
+
if (!conn.readOnly) writers++
|
|
395
|
+
}
|
|
396
|
+
if (writers) editing.push(doc.name)
|
|
397
|
+
// Keep this replica's place in the document's presence list from expiring.
|
|
398
|
+
if (presence && doc.getConnectionsCount() > 0) await presence.here(doc.name).catch(() => {})
|
|
399
|
+
}
|
|
400
|
+
try {
|
|
401
|
+
if (editing.length) await db.update(reg.cmsCollab).set({ activeAt: sql`now()` }).where(inArray(reg.cmsCollab.name, editing))
|
|
402
|
+
if (Date.now() - lastPurge > 60 * 60_000) {
|
|
403
|
+
lastPurge = Date.now()
|
|
404
|
+
await db.delete(reg.cmsCollab).where(sql`${reg.cmsCollab.updatedAt} < now() - interval '30 days' and (${reg.cmsCollab.activeAt} is null or ${reg.cmsCollab.activeAt} < now() - interval '1 day')`)
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
catch (err) {
|
|
408
|
+
console.error('[cms] collab heartbeat failed', safeErrorMessage(err))
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* Forget the shared documents of a deleted entry (or one deleted translation): their
|
|
414
|
+
* text must not outlive it, and nobody may keep typing into it.
|
|
415
|
+
*/
|
|
416
|
+
export async function dropCollabDocuments(entity: string, id: string, locale?: string | null): Promise<void> {
|
|
417
|
+
const name = collabName(entity, id, locale ?? null)
|
|
418
|
+
try {
|
|
419
|
+
const { db, reg } = useCms()
|
|
420
|
+
const c = reg.cmsCollab
|
|
421
|
+
// The document, its side rows (left-over text, last typist), and a translation's own.
|
|
422
|
+
const names: string[] = locale
|
|
423
|
+
? [name, `${name}~unsaved`, `${name}~by`]
|
|
424
|
+
: (await db.select({ name: c.name }).from(c).where(sql`${c.name} = ${name} or starts_with(${c.name}, ${name + '/'}) or starts_with(${c.name}, ${name + '~'})`)).map((r: any) => r.name)
|
|
425
|
+
if (!names.length) return
|
|
426
|
+
await db.delete(c).where(inArray(c.name, names))
|
|
427
|
+
for (const n of names) instance?.closeConnections(n)
|
|
428
|
+
}
|
|
429
|
+
catch (err) {
|
|
430
|
+
console.error('[cms] collab: could not drop documents of', name, safeErrorMessage(err))
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
export async function stopCollabServer(): Promise<void> {
|
|
435
|
+
if (heartbeat) clearInterval(heartbeat)
|
|
436
|
+
heartbeat = null
|
|
437
|
+
const server = instance
|
|
438
|
+
instance = null
|
|
439
|
+
starting = null
|
|
440
|
+
const p = presence
|
|
441
|
+
presence = null
|
|
442
|
+
if (!server) {
|
|
443
|
+
await p?.close()
|
|
444
|
+
return
|
|
445
|
+
}
|
|
446
|
+
server.closeConnections()
|
|
447
|
+
// Store what is still pending, then let extensions (Redis) close their clients.
|
|
448
|
+
await Promise.allSettled([...server.documents.values()].map((d) => server.storeDocumentHooks(d, { clientsCount: 0, context: {}, document: d, documentName: d.name, instance: server, requestHeaders: {}, requestParameters: new URLSearchParams(), socketId: 'shutdown' } as any, true)))
|
|
449
|
+
await Promise.resolve(server.hooks('onDestroy', { instance: server } as any)).catch(() => {})
|
|
450
|
+
await p?.close()
|
|
451
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { sql } from 'tinyzoo'
|
|
2
|
+
|
|
3
|
+
// Sorting text the way people of a language expect it: in Czech "Č" comes after
|
|
4
|
+
// "C" (not after "Z", as plain byte order puts it), "ch" after "h". Postgres does it
|
|
5
|
+
// with its ICU collations ("cs-x-icu"); a server built without ICU has none, and then
|
|
6
|
+
// the list sorts as before.
|
|
7
|
+
let available: Promise<Set<string>> | null = null
|
|
8
|
+
|
|
9
|
+
function icuCollations(db: any): Promise<Set<string>> {
|
|
10
|
+
available ??= db.execute(sql`select collname from pg_collation where collprovider = 'i'`)
|
|
11
|
+
.then((res: any) => new Set<string>((res.rows ?? res).map((r: any) => r.collname)))
|
|
12
|
+
.catch(() => new Set<string>())
|
|
13
|
+
return available!
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const TEXT = new Set(['PgText', 'PgVarchar', 'PgChar'])
|
|
17
|
+
|
|
18
|
+
/** The column to order by, with the language's collation when it is text and the
|
|
19
|
+
* database has one (`lang`: "cs", "en-GB"…). */
|
|
20
|
+
export async function collated(db: any, col: any, lang: string | null | undefined) {
|
|
21
|
+
if (!lang || !TEXT.has(col?.columnType)) return col
|
|
22
|
+
const names = await icuCollations(db)
|
|
23
|
+
const base = lang.split('-')[0]!
|
|
24
|
+
const name = [`${lang}-x-icu`, `${base}-x-icu`].find((n) => names.has(n))
|
|
25
|
+
// The name comes from the database's own list, never straight from the request.
|
|
26
|
+
return name ? sql`${col} collate ${sql.identifier(name)}` : col
|
|
27
|
+
}
|