tinyzoo 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (392) hide show
  1. package/LICENSE +10 -0
  2. package/README.md +46 -2
  3. package/app/app.config.ts +35 -0
  4. package/app/assets/brand/characters/bright/bird.svg +1 -0
  5. package/app/assets/brand/characters/bright/bunny.svg +1 -0
  6. package/app/assets/brand/characters/bright/elephant.svg +1 -0
  7. package/app/assets/brand/characters/bright/fox.svg +1 -0
  8. package/app/assets/brand/characters/bright/frog.svg +1 -0
  9. package/app/assets/brand/characters/bright/octopus.svg +1 -0
  10. package/app/assets/brand/characters/muted/bee.svg +1 -0
  11. package/app/assets/brand/characters/muted/bird.svg +1 -0
  12. package/app/assets/brand/characters/muted/butterfly.svg +1 -0
  13. package/app/assets/brand/characters/muted/chick.svg +1 -0
  14. package/app/assets/brand/characters/muted/cow.svg +1 -0
  15. package/app/assets/brand/characters/muted/deer.svg +1 -0
  16. package/app/assets/brand/characters/muted/duck.svg +1 -0
  17. package/app/assets/brand/characters/muted/elephant.svg +1 -0
  18. package/app/assets/brand/characters/muted/fox.svg +1 -0
  19. package/app/assets/brand/characters/muted/hedgehog.svg +1 -0
  20. package/app/assets/brand/characters/muted/koala.svg +1 -0
  21. package/app/assets/brand/characters/muted/ladybug.svg +1 -0
  22. package/app/assets/brand/characters/muted/lion.svg +1 -0
  23. package/app/assets/brand/characters/muted/mouse.svg +1 -0
  24. package/app/assets/brand/characters/muted/octopus.svg +1 -0
  25. package/app/assets/brand/characters/muted/owl.svg +1 -0
  26. package/app/assets/brand/characters/muted/panda.svg +1 -0
  27. package/app/assets/brand/characters/muted/penguin.svg +1 -0
  28. package/app/assets/brand/characters/muted/pig.svg +1 -0
  29. package/app/assets/brand/characters/muted/poodle.svg +1 -0
  30. package/app/assets/brand/characters/muted/raccoon.svg +1 -0
  31. package/app/assets/brand/characters/muted/seal.svg +1 -0
  32. package/app/assets/brand/characters/muted/sheep.svg +1 -0
  33. package/app/assets/brand/characters/muted/snail.svg +1 -0
  34. package/app/assets/brand/characters/muted/turtle.svg +1 -0
  35. package/app/assets/brand/characters/muted/whale.svg +1 -0
  36. package/app/assets/brand/logo/favicon.svg +1 -0
  37. package/app/assets/brand/logo/logo-primary-reversed.svg +1 -0
  38. package/app/assets/brand/logo/logo-primary.svg +1 -0
  39. package/app/assets/brand/logo/mascot-reversed.svg +1 -0
  40. package/app/assets/brand/logo/mascot.svg +1 -0
  41. package/app/assets/brand/logo/wordmark-reversed.svg +1 -0
  42. package/app/assets/brand/logo/wordmark.svg +1 -0
  43. package/app/assets/css/cms-admin.css +607 -0
  44. package/app/components/CmsBlocks.vue +30 -0
  45. package/app/components/CmsCell.vue +16 -0
  46. package/app/components/CmsCellBadge.vue +18 -0
  47. package/app/components/CmsCellBlocks.vue +9 -0
  48. package/app/components/CmsCellBoolean.vue +12 -0
  49. package/app/components/CmsCellCode.vue +7 -0
  50. package/app/components/CmsCellColor.vue +13 -0
  51. package/app/components/CmsCellDate.vue +10 -0
  52. package/app/components/CmsCellExcerpt.vue +21 -0
  53. package/app/components/CmsCellGallery.vue +10 -0
  54. package/app/components/CmsCellGroup.vue +23 -0
  55. package/app/components/CmsCellNumber.vue +7 -0
  56. package/app/components/CmsCellRelation.vue +8 -0
  57. package/app/components/CmsCellText.vue +12 -0
  58. package/app/components/CmsCellThumb.vue +18 -0
  59. package/app/components/CmsConfirmDialog.vue +55 -0
  60. package/app/components/CmsContent.vue +103 -0
  61. package/app/components/CmsDayPicker.vue +44 -0
  62. package/app/components/CmsEmptyState.vue +35 -0
  63. package/app/components/CmsField.vue +111 -0
  64. package/app/components/CmsFieldBlocks.vue +353 -0
  65. package/app/components/CmsFieldBoolean.vue +8 -0
  66. package/app/components/CmsFieldColor.vue +42 -0
  67. package/app/components/CmsFieldDate.vue +131 -0
  68. package/app/components/CmsFieldGallery.vue +114 -0
  69. package/app/components/CmsFieldGroup.vue +53 -0
  70. package/app/components/CmsFieldMedia.vue +219 -0
  71. package/app/components/CmsFieldNumber.vue +11 -0
  72. package/app/components/CmsFieldRelationMany.vue +54 -0
  73. package/app/components/CmsFieldRelationOne.vue +47 -0
  74. package/app/components/CmsFieldRichText.vue +45 -0
  75. package/app/components/CmsFieldSelect.vue +41 -0
  76. package/app/components/CmsFieldSlug.vue +46 -0
  77. package/app/components/CmsFieldText.vue +75 -0
  78. package/app/components/CmsFormSections.vue +150 -0
  79. package/app/components/CmsHighlight.vue +22 -0
  80. package/app/components/CmsImage.vue +39 -0
  81. package/app/components/CmsLinkPicker.vue +122 -0
  82. package/app/components/CmsLinkTarget.vue +35 -0
  83. package/app/components/CmsListFilters.vue +107 -0
  84. package/app/components/CmsLiveNotice.vue +64 -0
  85. package/app/components/CmsLoadError.vue +24 -0
  86. package/app/components/CmsMascot.vue +10 -0
  87. package/app/components/CmsMediaLibrary.vue +114 -0
  88. package/app/components/CmsMediaPreview.vue +34 -0
  89. package/app/components/CmsMediaThumb.vue +22 -0
  90. package/app/components/CmsMoment.vue +42 -0
  91. package/app/components/CmsNav.vue +39 -0
  92. package/app/components/CmsPage.vue +86 -0
  93. package/app/components/CmsPasswordInput.vue +22 -0
  94. package/app/components/CmsPresence.vue +29 -0
  95. package/app/components/CmsPreviewPanel.vue +131 -0
  96. package/app/components/CmsPublishReview.vue +102 -0
  97. package/app/components/CmsRevisions.vue +195 -0
  98. package/app/components/CmsRichTextEditor.vue +290 -0
  99. package/app/components/CmsSearch.vue +99 -0
  100. package/app/components/CmsSection.vue +20 -0
  101. package/app/components/CmsSingletonForm.vue +283 -0
  102. package/app/components/CmsStatusBadge.vue +21 -0
  103. package/app/components/CmsTime.vue +16 -0
  104. package/app/components/CmsTranslationRef.vue +27 -0
  105. package/app/components/CmsTreeList.vue +453 -0
  106. package/app/components/CmsUnsavedText.vue +34 -0
  107. package/app/components/CmsWordmark.vue +10 -0
  108. package/app/composables/useCmsAdminHead.ts +18 -0
  109. package/app/composables/useCmsCollab.ts +165 -0
  110. package/app/composables/useCmsConfirm.ts +39 -0
  111. package/app/composables/useCmsEntryActions.ts +75 -0
  112. package/app/composables/useCmsFocus.ts +13 -0
  113. package/app/composables/useCmsForm.ts +273 -0
  114. package/app/composables/useCmsI18n.ts +185 -0
  115. package/app/composables/useCmsLinkTargets.ts +84 -0
  116. package/app/composables/useCmsLive.ts +199 -0
  117. package/app/composables/useCmsSearch.ts +62 -0
  118. package/app/composables/useCmsSeo.ts +99 -0
  119. package/app/composables/useCmsSignedIn.ts +24 -0
  120. package/app/composables/useCmsUiLocale.ts +24 -0
  121. package/app/i18n/cs.ts +781 -0
  122. package/app/i18n/de.ts +781 -0
  123. package/app/i18n/en.ts +782 -0
  124. package/app/i18n/types.ts +22 -0
  125. package/app/layouts/admin.vue +224 -0
  126. package/app/layouts/cms-auth.vue +37 -0
  127. package/app/middleware/cms-api-not-a-page.global.ts +10 -0
  128. package/app/middleware/cms-auth.global.ts +16 -0
  129. package/app/pages/admin/[entity]/[id].vue +1109 -0
  130. package/app/pages/admin/[entity]/index.vue +733 -0
  131. package/app/pages/admin/account.vue +117 -0
  132. package/app/pages/admin/forgot.vue +50 -0
  133. package/app/pages/admin/index.vue +184 -0
  134. package/app/pages/admin/invite/[token].vue +73 -0
  135. package/app/pages/admin/login.vue +84 -0
  136. package/app/pages/admin/media.vue +494 -0
  137. package/app/pages/admin/privacy.vue +193 -0
  138. package/app/pages/admin/reset/[token].vue +52 -0
  139. package/app/pages/admin/setup.vue +87 -0
  140. package/app/pages/admin/styleguide.vue +261 -0
  141. package/app/pages/admin/team.vue +258 -0
  142. package/app/plugins/cmsLivePreview.client.ts +20 -0
  143. package/app/plugins/cmsSignedOut.client.ts +31 -0
  144. package/app/utils/cmsBlockType.ts +11 -0
  145. package/app/utils/cmsBrand.ts +38 -0
  146. package/app/utils/cmsDiff.ts +83 -0
  147. package/app/utils/cmsFetch.ts +7 -0
  148. package/app/utils/cmsFocusInvalid.ts +22 -0
  149. package/app/utils/cmsIssues.ts +128 -0
  150. package/app/utils/cmsJson.ts +28 -0
  151. package/app/utils/cmsMedia.ts +63 -0
  152. package/app/utils/cmsSections.ts +154 -0
  153. package/app/utils/cmsTime.ts +41 -0
  154. package/cli/backup.ts +713 -0
  155. package/cli/breaking.ts +174 -0
  156. package/cli/content-migrate.ts +239 -0
  157. package/cli/db.ts +86 -0
  158. package/cli/export.ts +336 -0
  159. package/cli/generate.ts +146 -0
  160. package/cli/import.ts +643 -0
  161. package/cli/index.ts +140 -0
  162. package/cli/links-convert.ts +291 -0
  163. package/cli/seed-engine.ts +705 -0
  164. package/cli/seed.ts +339 -0
  165. package/cli/status.ts +49 -0
  166. package/cli/tar.ts +304 -0
  167. package/cli/transfer.ts +677 -0
  168. package/cli/up.ts +27 -0
  169. package/cli/upgrade.ts +60 -0
  170. package/cli/versions.ts +60 -0
  171. package/forms/components/CmsForm.vue +186 -0
  172. package/forms/index.ts +203 -0
  173. package/forms/messages.ts +104 -0
  174. package/forms/retention.ts +48 -0
  175. package/forms/server/form.get.ts +12 -0
  176. package/forms/server/form.post.ts +109 -0
  177. package/forms/server/formSettings.ts +12 -0
  178. package/forms/server/forms.ts +127 -0
  179. package/module.ts +373 -0
  180. package/nuxt.config.ts +43 -0
  181. package/package.json +98 -3
  182. package/server/api/cms/[entity]/[id]/revisions/[rev].get.ts +19 -0
  183. package/server/api/cms/[entity]/[id]/revisions/index.get.ts +14 -0
  184. package/server/api/cms/[entity]/[id].delete.ts +52 -0
  185. package/server/api/cms/[entity]/[id].get.ts +21 -0
  186. package/server/api/cms/[entity]/[id].patch.ts +116 -0
  187. package/server/api/cms/[entity]/_export.get.ts +69 -0
  188. package/server/api/cms/[entity]/_move.post.ts +81 -0
  189. package/server/api/cms/[entity]/_order.post.ts +49 -0
  190. package/server/api/cms/[entity]/_tree.get.ts +41 -0
  191. package/server/api/cms/[entity]/index.get.ts +62 -0
  192. package/server/api/cms/[entity]/index.post.ts +38 -0
  193. package/server/api/cms/[entity]/options.get.ts +55 -0
  194. package/server/api/cms/_auth/accept.post.ts +33 -0
  195. package/server/api/cms/_auth/forgot.post.ts +39 -0
  196. package/server/api/cms/_auth/invite/[token].get.ts +18 -0
  197. package/server/api/cms/_auth/login.post.ts +42 -0
  198. package/server/api/cms/_auth/logout.post.ts +7 -0
  199. package/server/api/cms/_auth/me.get.ts +5 -0
  200. package/server/api/cms/_auth/me.patch.ts +32 -0
  201. package/server/api/cms/_auth/password.post.ts +29 -0
  202. package/server/api/cms/_auth/reset.post.ts +34 -0
  203. package/server/api/cms/_auth/setup.post.ts +46 -0
  204. package/server/api/cms/_auth/status.get.ts +18 -0
  205. package/server/api/cms/_collab/session.get.ts +30 -0
  206. package/server/api/cms/_collab/socket.ts +51 -0
  207. package/server/api/cms/_collab/unsaved.delete.ts +16 -0
  208. package/server/api/cms/_graph.get.ts +20 -0
  209. package/server/api/cms/_links/resolve.post.ts +17 -0
  210. package/server/api/cms/_links.get.ts +81 -0
  211. package/server/api/cms/_live.ts +30 -0
  212. package/server/api/cms/_media/[id]/usage.get.ts +14 -0
  213. package/server/api/cms/_media/[id].delete.ts +29 -0
  214. package/server/api/cms/_media/[id].get.ts +13 -0
  215. package/server/api/cms/_media/[id].patch.ts +64 -0
  216. package/server/api/cms/_media/exists.post.ts +15 -0
  217. package/server/api/cms/_media/img/[id]/[file].get.ts +42 -0
  218. package/server/api/cms/_media/index.get.ts +44 -0
  219. package/server/api/cms/_media/index.post.ts +147 -0
  220. package/server/api/cms/_media/raw/[...key].get.ts +85 -0
  221. package/server/api/cms/_media/raw/[...key].head.ts +2 -0
  222. package/server/api/cms/_overview.get.ts +87 -0
  223. package/server/api/cms/_preview.post.ts +17 -0
  224. package/server/api/cms/_privacy/delete.post.ts +14 -0
  225. package/server/api/cms/_privacy/export.post.ts +25 -0
  226. package/server/api/cms/_privacy/lookup.post.ts +27 -0
  227. package/server/api/cms/_search.get.ts +17 -0
  228. package/server/api/cms/_singleton/[name].get.ts +19 -0
  229. package/server/api/cms/_singleton/[name].put.ts +76 -0
  230. package/server/api/cms/_users/[id]/resend.post.ts +25 -0
  231. package/server/api/cms/_users/[id].delete.ts +21 -0
  232. package/server/api/cms/_users/[id].patch.ts +45 -0
  233. package/server/api/cms/_users/index.get.ts +28 -0
  234. package/server/api/cms/_users/index.post.ts +39 -0
  235. package/server/api/content/[entity]/[slug].get.ts +74 -0
  236. package/server/api/content/[entity]/index.get.ts +100 -0
  237. package/server/api/content/_global/[name].get.ts +23 -0
  238. package/server/api/content/_search.get.ts +28 -0
  239. package/server/api/content/_sitemap.get.ts +8 -0
  240. package/server/api/content/_tree/[entity].get.ts +31 -0
  241. package/server/api/content-types.ts.get.ts +17 -0
  242. package/server/api/health/live.get.ts +10 -0
  243. package/server/api/health/ready.get.ts +21 -0
  244. package/server/api/openapi.get.ts +48 -0
  245. package/server/api/openapi.json.get.ts +32 -0
  246. package/server/db/driver.ts +8 -0
  247. package/server/mail/mailer.ts +43 -0
  248. package/server/middleware/cms-0-headers.ts +37 -0
  249. package/server/middleware/cms-0-migrate-gate.ts +14 -0
  250. package/server/middleware/cms-csrf.ts +28 -0
  251. package/server/middleware/cms-limits.ts +20 -0
  252. package/server/middleware/cms-redirects.ts +21 -0
  253. package/server/middleware/cms-session.ts +41 -0
  254. package/server/middleware/cms-z-plugin-access.ts +15 -0
  255. package/server/plugins/cms-0-config-check.ts +35 -0
  256. package/server/plugins/cms-changes.ts +53 -0
  257. package/server/plugins/cms-content-etag.ts +21 -0
  258. package/server/plugins/cms-errors.ts +45 -0
  259. package/server/plugins/cms-migrate.ts +5 -0
  260. package/server/plugins/cms-plugins.ts +17 -0
  261. package/server/plugins/cms-search.ts +12 -0
  262. package/server/plugins/cms-setup-code.ts +15 -0
  263. package/server/routes/sitemap.xml.get.ts +25 -0
  264. package/server/store/redis.ts +95 -0
  265. package/server/store/types.ts +21 -0
  266. package/server/tasks/cms/retention.ts +10 -0
  267. package/server/tasks/cms/scheduled.ts +10 -0
  268. package/server/tasks/cms/search-reindex.ts +12 -0
  269. package/server/utils/cmsAudit.ts +29 -0
  270. package/server/utils/cmsAuth.ts +143 -0
  271. package/server/utils/cmsBlocks.ts +47 -0
  272. package/server/utils/cmsChanges.ts +222 -0
  273. package/server/utils/cmsCollab.ts +286 -0
  274. package/server/utils/cmsCollabServer.ts +451 -0
  275. package/server/utils/cmsCollate.ts +27 -0
  276. package/server/utils/cmsContent.ts +376 -0
  277. package/server/utils/cmsCrud.ts +361 -0
  278. package/server/utils/cmsCsv.ts +24 -0
  279. package/server/utils/cmsDb.ts +23 -0
  280. package/server/utils/cmsDemo.ts +36 -0
  281. package/server/utils/cmsEmails.ts +125 -0
  282. package/server/utils/cmsErrors.ts +40 -0
  283. package/server/utils/cmsFold.ts +17 -0
  284. package/server/utils/cmsImageSizes.ts +51 -0
  285. package/server/utils/cmsJson.ts +6 -0
  286. package/server/utils/cmsLinkAddress.ts +50 -0
  287. package/server/utils/cmsLinks.ts +248 -0
  288. package/server/utils/cmsListQuery.ts +93 -0
  289. package/server/utils/cmsLive.ts +393 -0
  290. package/server/utils/cmsLocales.ts +96 -0
  291. package/server/utils/cmsMail.ts +28 -0
  292. package/server/utils/cmsMediaGc.ts +188 -0
  293. package/server/utils/cmsMediaKeys.ts +62 -0
  294. package/server/utils/cmsMigrate.ts +86 -0
  295. package/server/utils/cmsPreviewDraft.ts +72 -0
  296. package/server/utils/cmsPrivacy.ts +176 -0
  297. package/server/utils/cmsPublished.ts +57 -0
  298. package/server/utils/cmsRange.ts +38 -0
  299. package/server/utils/cmsRateLimit.ts +82 -0
  300. package/server/utils/cmsRedirects.ts +160 -0
  301. package/server/utils/cmsRetention.ts +61 -0
  302. package/server/utils/cmsRevisions.ts +103 -0
  303. package/server/utils/cmsScheduler.ts +45 -0
  304. package/server/utils/cmsScrub.ts +107 -0
  305. package/server/utils/cmsSearch.ts +354 -0
  306. package/server/utils/cmsSession.ts +102 -0
  307. package/server/utils/cmsSetupCode.ts +97 -0
  308. package/server/utils/cmsSitemap.ts +176 -0
  309. package/server/utils/cmsStorage.ts +580 -0
  310. package/server/utils/cmsStore.ts +109 -0
  311. package/server/utils/cmsTiming.ts +14 -0
  312. package/server/utils/cmsTooMany.ts +9 -0
  313. package/server/utils/cmsTranslationWrite.ts +186 -0
  314. package/server/utils/cmsTree.ts +251 -0
  315. package/server/utils/cmsTreeAddress.ts +65 -0
  316. package/server/utils/cmsUpload.ts +228 -0
  317. package/server/utils/cmsWebhooks.ts +104 -0
  318. package/shared/json.ts +11 -0
  319. package/shared/richtext-editor.ts +56 -0
  320. package/shared/richtext-normalize.ts +33 -0
  321. package/shared/richtext-paste.ts +151 -0
  322. package/shared/storage-delivery.ts +53 -0
  323. package/src/blocks.ts +624 -0
  324. package/src/changes.ts +54 -0
  325. package/src/content-shape.ts +340 -0
  326. package/src/deprecate.ts +64 -0
  327. package/src/descriptor.ts +149 -0
  328. package/src/docs.ts +27 -0
  329. package/src/emitter.ts +94 -0
  330. package/src/entity.ts +624 -0
  331. package/src/errorReport.ts +41 -0
  332. package/src/fields.ts +465 -0
  333. package/src/i18n.ts +26 -0
  334. package/src/index.ts +54 -0
  335. package/src/linkref.ts +31 -0
  336. package/src/links.ts +179 -0
  337. package/src/locales.ts +39 -0
  338. package/src/media.ts +48 -0
  339. package/src/migrate.ts +236 -0
  340. package/src/openapi.ts +377 -0
  341. package/src/paths.ts +88 -0
  342. package/src/plugin.ts +505 -0
  343. package/src/presets.ts +230 -0
  344. package/src/richtext.ts +88 -0
  345. package/src/sdk.ts +181 -0
  346. package/src/search.ts +312 -0
  347. package/src/seed.ts +225 -0
  348. package/src/setupCode.ts +30 -0
  349. package/src/system.ts +219 -0
  350. package/src/tree.ts +421 -0
  351. package/src/upgrades.ts +137 -0
  352. package/starter/.env.example +10 -0
  353. package/starter/README.md +65 -0
  354. package/starter/app/app.config.ts +10 -0
  355. package/starter/app/app.vue +12 -0
  356. package/starter/app/assets/css/main.css +15 -0
  357. package/starter/app/components/global/BlockContact.vue +15 -0
  358. package/starter/app/components/global/BlockCta.vue +15 -0
  359. package/starter/app/components/global/BlockHero.vue +23 -0
  360. package/starter/app/components/global/BlockImage.vue +13 -0
  361. package/starter/app/components/global/BlockText.vue +12 -0
  362. package/starter/app/composables/useSite.ts +77 -0
  363. package/starter/app/error.vue +28 -0
  364. package/starter/app/layouts/default.vue +106 -0
  365. package/starter/app/lib/cms-content.ts +152 -0
  366. package/starter/app/pages/[...slug].vue +66 -0
  367. package/starter/app/pages/hledat.vue +59 -0
  368. package/starter/app/pages/index.vue +20 -0
  369. package/starter/cms.config.ts +137 -0
  370. package/starter/compose.yaml +15 -0
  371. package/starter/drizzle.config.ts +8 -0
  372. package/starter/gitignore.txt +8 -0
  373. package/starter/nuxt.config.ts +13 -0
  374. package/starter/package.json +38 -0
  375. package/starter/scripts/typecheck.mjs +38 -0
  376. package/starter/seed/index.ts +297 -0
  377. package/starter/seed/media/about.jpg +0 -0
  378. package/starter/seed/media/hero.jpg +0 -0
  379. package/starter/seed/media/logo.png +0 -0
  380. package/starter/seed/media/news-bread.jpg +0 -0
  381. package/starter/seed/media/news-morning.jpg +0 -0
  382. package/starter/server/db/migrations/0000_init.sql +269 -0
  383. package/starter/server/db/migrations/0001_page_tree.sql +5 -0
  384. package/starter/server/db/migrations/0002_opening_hours_per_language.sql +1 -0
  385. package/starter/server/db/migrations/meta/0000_snapshot.json +1890 -0
  386. package/starter/server/db/migrations/meta/0001_snapshot.json +1887 -0
  387. package/starter/server/db/migrations/meta/0002_snapshot.json +1893 -0
  388. package/starter/server/db/migrations/meta/_journal.json +27 -0
  389. package/starter/server/db/schema.ts +253 -0
  390. package/starter/server/plugins/sitemap.ts +11 -0
  391. package/starter/server/routes/robots.txt.get.ts +12 -0
  392. package/starter/tsconfig.json +9 -0
@@ -0,0 +1,361 @@
1
+ import { and, eq, inArray, isNull, ne, or, sql } from 'tinyzoo'
2
+ import { propOf, snake, type CmsEntity, type CmsRegistry } from 'tinyzoo'
3
+ import type { CmsUser } from './cmsSession'
4
+
5
+ export function getEntity(reg: CmsRegistry, name: string | undefined): CmsEntity {
6
+ const e = name ? reg.byName.get(name) : undefined
7
+ if (!e) throw createError({ statusCode: 404, statusMessage: `Unknown entity: ${name}` })
8
+ return e
9
+ }
10
+
11
+ /** Split a validated payload into scalar/FK column values and m2m id-lists. */
12
+ export function splitPayload(e: CmsEntity, data: Record<string, any>) {
13
+ const values: Record<string, any> = {}
14
+ const m2m: Record<string, string[]> = {}
15
+ for (const [key, fld] of Object.entries(e.fields)) {
16
+ if (!(key in data)) continue
17
+ if (fld.relation?.kind === 'one-to-many') continue
18
+ if (fld.relation?.kind === 'many-to-many') {
19
+ m2m[key] = Array.isArray(data[key]) ? data[key] : []
20
+ continue
21
+ }
22
+ values[propOf(key, fld)] = data[key]
23
+ }
24
+ return { values, m2m }
25
+ }
26
+
27
+ /**
28
+ * Shape a DB row for the admin edit form: m2m → id arrays, owned FKs (media +
29
+ * to-one) aliased from `${key}Id` back to the field key, the media record
30
+ * attached as `${key}__media` for the preview, and blocks upgraded to their current
31
+ * versions. Mutates + returns the row.
32
+ */
33
+ export async function hydrateRowForForm(db: any, reg: CmsRegistry, e: CmsEntity, row: any, opts: { markFailed?: boolean } = {}) {
34
+ // Blocks and lists stored at an older version are upgraded (and stamped) for the editor;
35
+ // one whose upgrade failed is flagged (`__upgradeFailed`) and kept as stored.
36
+ upgradeStoredJson(e, row, { admin: opts.markFailed !== false })
37
+ for (const [key, fld] of Object.entries(e.fields)) {
38
+ if (fld.relation?.kind !== 'many-to-many') continue
39
+ const j = reg.junctionByOwnerField.get(`${e.name}.${key}`)!
40
+ const links: any[] = await db.select().from(j.table).where(eq(j.table[j.ownerCol], row.id))
41
+ row[key] = links.map((l) => l[j.targetCol])
42
+ }
43
+ for (const [key, fld] of Object.entries(e.fields)) {
44
+ const ownsFk = (fld as any).type === 'media' || fld.relation?.kind === 'many-to-one'
45
+ if (!ownsFk) continue
46
+ const fkId = row[`${key}Id`] ?? null
47
+ row[key] = fkId
48
+ if ((fld as any).type === 'media') {
49
+ row[`${key}__media`] = fkId
50
+ ? (await db.select().from(reg.cmsMedia).where(eq(reg.cmsMedia.id, fkId)))[0] ?? null
51
+ : null
52
+ }
53
+ }
54
+ return row
55
+ }
56
+
57
+ /** Diff-write m2m junction rows in the surrounding transaction. */
58
+ export async function writeM2M(
59
+ db: any, reg: CmsRegistry, e: CmsEntity, rowId: string,
60
+ m2m: Record<string, string[]>, replace = false,
61
+ ) {
62
+ for (const [key, ids] of Object.entries(m2m)) {
63
+ const j = reg.junctionByOwnerField.get(`${e.name}.${key}`)
64
+ if (!j) continue
65
+ if (replace) await db.delete(j.table).where(eq(j.table[j.ownerCol], rowId))
66
+ if (ids.length) {
67
+ await db.insert(j.table)
68
+ .values(ids.map((tid) => ({ [j.ownerCol]: rowId, [j.targetCol]: tid })))
69
+ .onConflictDoNothing()
70
+ }
71
+ }
72
+ }
73
+
74
+ export function parseOr422(schema: any, body: unknown) {
75
+ const r = schema.safeParse(body)
76
+ if (!r.success) {
77
+ throw createError({ statusCode: 422, statusMessage: 'Validation failed', data: r.error.issues })
78
+ }
79
+ return r.data
80
+ }
81
+
82
+ /** Does a file type match a field's `accept` ("image/*", "application/pdf", "image/png,image/jpeg")? Extensions (".pdf") are only for the browser's file dialog. */
83
+ export function mimeAccepted(accept: string, mime: string): boolean {
84
+ const wanted = accept.split(',').map((a) => a.trim().toLowerCase()).filter((a) => a && !a.startsWith('.'))
85
+ if (!wanted.length) return true
86
+ const type = mime.toLowerCase()
87
+ return wanted.some((a) => a === '*/*' || a === type || (a.endsWith('/*') && type.startsWith(a.slice(0, -1))))
88
+ }
89
+
90
+ /**
91
+ * A media, file or gallery field with an `accept` only takes files of those types — the
92
+ * admin's picker filters by it, but the API must too (a video's id in a field that shows
93
+ * pictures would only be a broken image on the site). 422, like any invalid value.
94
+ */
95
+ export async function assertMediaAccepted(db: any, reg: CmsRegistry, e: CmsEntity, data: Record<string, any>): Promise<void> {
96
+ const wanted: { key: string; accept: string; ids: string[] }[] = []
97
+ for (const [key, fld] of Object.entries(e.fields) as [string, any][]) {
98
+ const accept = fld.meta?.accept
99
+ if (typeof accept !== 'string' || !accept.trim() || !(key in data)) continue
100
+ const value = data[key]
101
+ if (fld.type === 'media' && typeof value === 'string') wanted.push({ key, accept, ids: [value] })
102
+ else if (fld.type === 'gallery' && Array.isArray(value)) wanted.push({ key, accept, ids: value.map((i: any) => i?.mediaId).filter((id: unknown) => typeof id === 'string') })
103
+ }
104
+ const ids = [...new Set(wanted.flatMap((w) => w.ids))]
105
+ if (!ids.length) return
106
+ const rows: { id: string; mime: string }[] = await db.select({ id: reg.cmsMedia.id, mime: reg.cmsMedia.mime }).from(reg.cmsMedia).where(inArray(reg.cmsMedia.id, ids))
107
+ const mimeOf = new Map(rows.map((r) => [r.id, r.mime]))
108
+ const issues: { code: string; path: string[]; message: string }[] = []
109
+ for (const w of wanted) {
110
+ const bad = w.ids.map((id) => mimeOf.get(id)).find((mime) => mime && !mimeAccepted(w.accept, mime))
111
+ if (bad) issues.push({ code: 'custom', path: [w.key], message: 'This field takes ' + w.accept + ', not ' + bad })
112
+ }
113
+ if (issues.length) throw createError({ statusCode: 422, statusMessage: 'Validation failed', data: issues })
114
+ }
115
+
116
+ /**
117
+ * Evaluate an access rule. Returns `{ allowed, where }`:
118
+ * - rule returns `true` → full access
119
+ * - rule returns `false` → denied
120
+ * - rule returns a Drizzle condition → allowed, but AND that into the query (row-level)
121
+ */
122
+ export function accessWhere(
123
+ e: CmsEntity, op: 'read' | 'create' | 'update' | 'delete', user: CmsUser,
124
+ ): { allowed: boolean; where: any } {
125
+ // 1. The built-in role decides first …
126
+ const byRole = roleAccess(e, op, user)
127
+ if (!byRole.allowed) return byRole
128
+ // 2. … then the entity's own `access` rule narrows it further (AND).
129
+ const rule = (e.access as any)?.[op]
130
+ if (!rule) return byRole
131
+ const res = rule({ user, table: e.table })
132
+ if (res === false || res === null || res === undefined) return { allowed: false, where: undefined }
133
+ return { allowed: true, where: both(byRole.where, res === true ? undefined : res) }
134
+ }
135
+
136
+ /**
137
+ * Built-in roles (cms_users.role):
138
+ * - admin, editor: everything (admins also manage people — see requireCmsAdmin)
139
+ * - author: reads everything, creates entries, changes and deletes only entries
140
+ * they created, never touches settings (singletons), cannot publish
141
+ * Any other role (e.g. from an external auth provider) is left to the entities'
142
+ * own `access` rules, as before roles existed.
143
+ */
144
+ export function roleAccess(e: CmsEntity, op: 'read' | 'create' | 'update' | 'delete', user: CmsUser): { allowed: boolean; where: any } {
145
+ if (user.role !== 'author') return { allowed: true, where: undefined }
146
+ if (op === 'read') return { allowed: true, where: undefined }
147
+ if (e.singleton) return { allowed: false, where: undefined }
148
+ // Content that is live the moment it is saved (public without a publish workflow,
149
+ // or marked `live`, e.g. redirects) — writing it would be publishing.
150
+ if (e.live || (e.content?.public && !e.publish)) return { allowed: false, where: undefined }
151
+ if (op === 'create') return { allowed: true, where: undefined }
152
+ return { allowed: true, where: eq(e.table.createdBy, user.id) }
153
+ }
154
+
155
+ /** Rows that are not live (for writes by people who may not publish), or undefined. */
156
+ export function notLiveCond(e: CmsEntity, user: CmsUser): any {
157
+ const p = e.publish
158
+ if (!p || canPublish(user)) return undefined
159
+ const col = e.table[propOf(p.field, e.fields[p.field]!)]
160
+ return or(isNull(col), ne(col, p.publishedValue))
161
+ }
162
+
163
+ /**
164
+ * May this person change this entry (or, with no id, the entity's one global)? The same
165
+ * rules a save applies, told to the form beforehand so it opens read-only instead of
166
+ * failing on save. `why` says which rule says no: the role, somebody else's entry,
167
+ * or an entry that is live (people who may not publish cannot change what is live).
168
+ */
169
+ export async function updateVerdict(db: any, e: CmsEntity, user: CmsUser, id?: string | null): Promise<{ update: boolean; why?: 'role' | 'owner' | 'published' }> {
170
+ const a = accessWhere(e, 'update', user)
171
+ if (!a.allowed) return { update: false, why: 'role' }
172
+ if (!id) return { update: true }
173
+ const [ok] = await db.select({ id: e.table.id }).from(e.table).where(both(both(eq(e.table.id, id), a.where), notLiveCond(e, user)))
174
+ if (ok) return { update: true }
175
+ const [mine] = await db.select({ id: e.table.id }).from(e.table).where(both(eq(e.table.id, id), a.where))
176
+ return { update: false, why: mine ? 'published' : 'owner' }
177
+ }
178
+
179
+ /** The id to record as createdBy/updatedBy — only a UUID fits the column (external auth may use others). */
180
+ export function actorId(user: CmsUser): string | null {
181
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(user.id) ? user.id : null
182
+ }
183
+
184
+ /** May this person publish (or unpublish) entries? Authors write drafts only. */
185
+ export function canPublish(user: CmsUser): boolean {
186
+ return user.role !== 'author'
187
+ }
188
+
189
+ /**
190
+ * Refuse a write that would change publication state for someone who may not
191
+ * publish: setting the publish field to its published value, or editing an entry
192
+ * that is already live (their change would go straight to the website).
193
+ */
194
+ export function assertPublishAllowed(e: CmsEntity, user: CmsUser, values: Record<string, any>, current?: Record<string, any> | null) {
195
+ const p = e.publish
196
+ if (!p || canPublish(user)) return
197
+ const field = propOf(p.field, e.fields[p.field]!)
198
+ const live = (v: unknown) => v === p.publishedValue
199
+ if (live(values[field]) || (current && live(current[field]))) {
200
+ throw createError({ statusCode: 403, statusMessage: 'Your role can write drafts but not publish' })
201
+ }
202
+ }
203
+
204
+ /** 'entry.publish' / 'entry.unpublish' when a write changed publication state, else null. */
205
+ export function publishAction(e: CmsEntity, before: Record<string, any> | null, after: Record<string, any>): string | null {
206
+ const p = e.publish
207
+ if (!p) return null
208
+ const field = propOf(p.field, e.fields[p.field]!)
209
+ const was = before?.[field] === p.publishedValue
210
+ const is = after[field] === p.publishedValue
211
+ if (was === is) return null
212
+ return is ? 'entry.publish' : 'entry.unpublish'
213
+ }
214
+
215
+ /** Authors may change or delete only files they uploaded themselves. */
216
+ export function assertMediaOwner(user: CmsUser, media: { uploadedBy?: string | null }) {
217
+ if (user.role === 'author' && media.uploadedBy !== user.id) {
218
+ throw createError({ statusCode: 403, statusMessage: 'You can only change files you uploaded' })
219
+ }
220
+ }
221
+
222
+ /** Admin-only endpoints (people management, audit log). */
223
+ export function requireCmsAdmin(event: any): CmsUser {
224
+ const user = requireCmsUser(event)
225
+ if (user.role !== 'admin') throw createError({ statusCode: 403, statusMessage: 'Administrators only' })
226
+ return user
227
+ }
228
+
229
+ /** Throw 403 if not allowed; return the row-level filter (or undefined). */
230
+ export function authorize(e: CmsEntity, op: 'read' | 'create' | 'update' | 'delete', user: CmsUser) {
231
+ const { allowed, where } = accessWhere(e, op, user)
232
+ if (!allowed) throw createError({ statusCode: 403, statusMessage: `Not allowed to ${op} ${e.name}` })
233
+ return where
234
+ }
235
+
236
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
237
+
238
+ /** The `:id` route param, or 404 when it cannot be a row id (Postgres would 500 on a non-uuid). */
239
+ export function getIdParam(event: any, name = 'id'): string {
240
+ const id = getRouterParam(event, name)
241
+ if (!id || !UUID_RE.test(id)) throw createError({ statusCode: 404, statusMessage: 'Not found' })
242
+ return id
243
+ }
244
+
245
+ /** Field key whose column a Postgres unique constraint (`<table>_<column>_unique`) is on. */
246
+ function fieldOfConstraint(e: CmsEntity, constraint: string | undefined): string | undefined {
247
+ if (!constraint) return undefined
248
+ for (const [key, fld] of Object.entries(e.fields)) {
249
+ const col = (e.table as any)[propOf(key, fld)]
250
+ if (col?.name && (constraint === `${snake(e.name)}_${col.name}_unique` || constraint === `${snake(e.name)}_locales_${col.name}_unique`)) return key
251
+ }
252
+ return undefined
253
+ }
254
+
255
+ /**
256
+ * Translate Postgres constraint violations into answers an editor can act on,
257
+ * instead of a 500. Rethrows anything else untouched.
258
+ * - unique violation → 409, with a Zod-shaped issue on the field when known
259
+ * - FK violation on delete → 409 (still referenced, e.g. `onDelete: 'restrict'`)
260
+ * - FK violation on write → 422 (points at a row that does not exist)
261
+ */
262
+ export function rethrowDbError(err: any, e: CmsEntity, op: 'write' | 'delete'): never {
263
+ // Drizzle wraps driver errors (DrizzleQueryError) and keeps the original as `cause`.
264
+ const pgErr = err?.code ? err : err?.cause
265
+ if (pgErr?.code === '23505') {
266
+ const field = fieldOfConstraint(e, pgErr.constraint)
267
+ throw createError({
268
+ statusCode: 409,
269
+ statusMessage: 'Value already in use',
270
+ data: field ? [{ path: [field], code: 'unique', message: 'Already in use' }] : undefined,
271
+ })
272
+ }
273
+ if (pgErr?.code === '23503') {
274
+ if (op === 'delete') {
275
+ throw createError({ statusCode: 409, statusMessage: 'Still in use by other content; remove those references first' })
276
+ }
277
+ throw createError({ statusCode: 422, statusMessage: 'Refers to an item that does not exist' })
278
+ }
279
+ throw err
280
+ }
281
+
282
+ /** AND two optional Drizzle conditions. */
283
+ export function both(a: any, b: any) {
284
+ return b ? (a ? and(a, b) : b) : a
285
+ }
286
+
287
+ /**
288
+ * The version an edit is based on: the entry's `updatedAt` as the editor loaded it,
289
+ * sent in the `X-CMS-Version` header. Null when absent (no check: API clients and
290
+ * scripts that want last-write-wins simply leave it out).
291
+ */
292
+ export function baseVersion(event: any): Date | null {
293
+ const raw = getRequestHeader(event, 'x-cms-version')
294
+ if (!raw) return null
295
+ const d = new Date(raw)
296
+ if (Number.isNaN(d.getTime())) throw createError({ statusCode: 400, statusMessage: 'Invalid X-CMS-Version' })
297
+ return d
298
+ }
299
+
300
+ /**
301
+ * 409 when the entry changed since the editor loaded it, saying who changed it and
302
+ * when, so the admin can offer to reload or to save over it.
303
+ */
304
+ export async function assertCurrentVersion(e: CmsEntity, current: Record<string, any> | null | undefined, base: Date | null): Promise<void> {
305
+ if (!base || !current?.updatedAt) return
306
+ if (new Date(current.updatedAt).getTime() === base.getTime()) return
307
+ let byName: string | null = null
308
+ if (current.updatedBy) {
309
+ const { db, reg } = useCms()
310
+ const [u] = await db.select({ name: reg.cmsUsers.name, email: reg.cmsUsers.email }).from(reg.cmsUsers).where(eq(reg.cmsUsers.id, current.updatedBy))
311
+ byName = u ? displayName(u.name, u.email) || null : null
312
+ }
313
+ throw createError({
314
+ statusCode: 409,
315
+ statusMessage: 'Changed by someone else since you opened it',
316
+ data: { code: 'stale', entity: e.name, version: new Date(current.updatedAt).toISOString(), updatedBy: current.updatedBy ?? null, updatedByName: byName },
317
+ })
318
+ }
319
+
320
+ /**
321
+ * The next version stamp for a row: now, but always at least 1 ms after the current
322
+ * one — two saves never share a version, even with replica clocks out of step.
323
+ */
324
+ export function nextVersion(col: any) {
325
+ return sql`greatest(date_trunc('milliseconds', clock_timestamp()), ${col} + interval '1 millisecond')`
326
+ }
327
+
328
+ /**
329
+ * Publishing without a publish date stamps "now" — the database's clock, not the
330
+ * browser's. A date given is kept: ahead schedules the entry (the scheduler announces
331
+ * it when it comes, even seconds later), behind back-dates it.
332
+ */
333
+ export function stampPublishDate(e: CmsEntity, values: Record<string, any>, before: Record<string, any> | null) {
334
+ const p = e.publish
335
+ if (!p?.dateField) return
336
+ const statusKey = propOf(p.field, e.fields[p.field]!)
337
+ const dateKey = propOf(p.dateField, e.fields[p.dateField]!)
338
+ const status = statusKey in values ? values[statusKey] : before?.[statusKey]
339
+ if (status !== p.publishedValue) return
340
+ const date = dateKey in values ? values[dateKey] : before?.[dateKey]
341
+ if (date == null || date === '') values[dateKey] = sql`date_trunc('milliseconds', clock_timestamp())`
342
+ }
343
+
344
+ /**
345
+ * What still points at an entry (many-to-one relations of other collections), so a
346
+ * refused delete can say where it is used: a few titles per collection.
347
+ */
348
+ export async function usedBy(db: any, reg: CmsRegistry, target: CmsEntity, id: string): Promise<{ entity: string; id: string; title: string }[]> {
349
+ const out: { entity: string; id: string; title: string }[] = []
350
+ for (const e of reg.entities) {
351
+ for (const [key, fld] of Object.entries(e.fields) as [string, any][]) {
352
+ if (fld.type !== 'relation' || fld.relation?.kind !== 'many-to-one') continue
353
+ if ((fld.relation.to() as CmsEntity).name !== target.name) continue
354
+ const col = e.table[`${key}Id`]
355
+ if (!col) continue
356
+ const rows: any[] = await db.select({ id: e.table.id, title: e.table[e.titleField] ?? e.table.id }).from(e.table).where(eq(col, id)).limit(5)
357
+ for (const r of rows) out.push({ entity: e.name, id: r.id, title: r.title == null ? '' : String(r.title) })
358
+ }
359
+ }
360
+ return out
361
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * A cell of a CSV file for Excel or Sheets, made safe: a text that starts like a formula
3
+ * would be *run* by the spreadsheet (`=HYPERLINK(…)`, `+cmd|…`, `@SUM(…)`) with whatever a
4
+ * visitor typed into a form. Those get a leading apostrophe, which shows as plain text.
5
+ *
6
+ * - `=` and `@` always (nothing real starts with them), and a leading tab or carriage return
7
+ * (some programs read them as the start of a formula);
8
+ * - `+` and `-` only when what follows is not a number: a phone number ("+420 777 123 456",
9
+ * "+1 (555) 123-4567") or a negative amount is data, while "+SUM(…)", "-2+cmd|…" are not.
10
+ * A formula made of digits and operators only cannot do anything but arithmetic.
11
+ */
12
+ const NUMBER_LIKE = /^[+-]\s?[0-9][0-9 ()./-]*$/
13
+
14
+ export function neutraliseCell(s: string): string {
15
+ if (/^[=@\t\r]/.test(s)) return `'${s}`
16
+ if (/^[+-]/.test(s) && !NUMBER_LIKE.test(s)) return `'${s}`
17
+ return s
18
+ }
19
+
20
+ /** One cell, neutralised and quoted when it holds a separator, a quote or a line break. */
21
+ export function csvCell(s: string): string {
22
+ const safe = neutraliseCell(s)
23
+ return /[",\n\r;]/.test(safe) ? '"' + safe.replace(/"/g, '""') + '"' : safe
24
+ }
@@ -0,0 +1,23 @@
1
+ import { buildRegistry, type CmsRegistry } from 'tinyzoo'
2
+ import { createCmsDb } from '../db/driver'
3
+ import * as cmsConfig from '#cms/config'
4
+
5
+ let _db: ReturnType<typeof createCmsDb> | undefined
6
+
7
+ /**
8
+ * DataSource seam. The DB instance is memoized (persistent process / isolate).
9
+ * The driver is chosen at build time via `cms.db.driver` ('node' | 'edge'); the
10
+ * runtime code here is identical for both — a single Postgres dialect.
11
+ */
12
+ export function useCms(): { db: ReturnType<typeof createCmsDb>; reg: CmsRegistry } {
13
+ const reg = buildRegistry(cmsConfig as Record<string, any>)
14
+ if (!_db) {
15
+ // The runtime environment wins over anything set at build time (the platform
16
+ // injects DATABASE_URL for a linked database).
17
+ const env: Record<string, string | undefined> = typeof process !== 'undefined' ? process.env : {}
18
+ const url = env.NUXT_CMS_DATABASE_URL || env.DATABASE_URL || (useRuntimeConfig().cms as any)?.databaseUrl
19
+ if (!url) throw createError({ statusCode: 500, statusMessage: 'No database address: set DATABASE_URL (or NUXT_CMS_DATABASE_URL), or cms.databaseUrl in nuxt.config' })
20
+ _db = createCmsDb(url, reg.schema)
21
+ }
22
+ return { db: _db, reg }
23
+ }
@@ -0,0 +1,36 @@
1
+ import { eq, sql } from 'tinyzoo'
2
+
3
+ // A public demo admin (cms.demo / NUXT_PUBLIC_CMS_DEMO_*): one shared editor account
4
+ // whose sign-in details are printed on the sign-in page. It is created, or put back
5
+ // (editor, active, the published password), whenever someone signs in with exactly
6
+ // those details, so a nightly content reset or a broken account never locks people
7
+ // out. It cannot change its name or password, and gets no reset emails.
8
+
9
+ /** The demo account's details, or null when the site has no demo. */
10
+ export function cmsDemo(): { email: string; password: string } | null {
11
+ const d = (useRuntimeConfig().public as any)?.cmsDemo
12
+ const email = String(d?.email ?? '').trim().toLowerCase()
13
+ const password = String(d?.password ?? '')
14
+ return email && password ? { email, password } : null
15
+ }
16
+
17
+ export function isDemoAccount(email: string | null | undefined): boolean {
18
+ const d = cmsDemo()
19
+ return !!d && !!email && email.trim().toLowerCase() === d.email
20
+ }
21
+
22
+ /** Before a sign-in: when these are the demo details, make sure the account works. */
23
+ // The account's name, the same in every admin language.
24
+ const DEMO_NAME = 'Demo'
25
+
26
+ export async function ensureDemoAccount(email: string, password: string): Promise<void> {
27
+ const d = cmsDemo()
28
+ if (!d || email !== d.email || password !== d.password) return
29
+ const { db, reg } = useCms()
30
+ const [user] = await db.select().from(reg.cmsUsers).where(eq(reg.cmsUsers.email, d.email))
31
+ const fine = user && user.name === DEMO_NAME && user.status === 'active' && user.role === 'editor' && user.passwordHash && await verifyPassword(user.passwordHash, d.password)
32
+ if (fine) return
33
+ const values = { name: DEMO_NAME, role: 'editor', status: 'active', passwordHash: await hashPassword(d.password), updatedAt: new Date() }
34
+ if (user) await db.update(reg.cmsUsers).set({ ...values, sessionVersion: sql`${reg.cmsUsers.sessionVersion} + 1` }).where(eq(reg.cmsUsers.id, user.id))
35
+ else await db.insert(reg.cmsUsers).values({ email: d.email, ...values }).onConflictDoNothing()
36
+ }
@@ -0,0 +1,125 @@
1
+ import { INVITE_TTL_MS } from './cmsAuth'
2
+ import { resolveText } from 'tinyzoo'
3
+
4
+ // The emails the CMS sends: an invitation and a password-reset link. Plain, neutral
5
+ // HTML that survives every mail client, with a text version. Czech, English and German,
6
+ // chosen by the recipient's interface language (or the admin's default).
7
+
8
+ type Locale = 'cs' | 'en' | 'de'
9
+
10
+ const copy = {
11
+ en: {
12
+ inviteSubject: (site: string) => `You're invited to ${site}`,
13
+ inviteIntro: (inviter: string, site: string, role: string) => `${inviter} invited you to manage the content of ${site} as ${role}.`,
14
+ inviteAction: 'Accept the invitation',
15
+ inviteExpiry: (days: number) => `The link works for ${days} days. If you weren't expecting this, you can ignore it.`,
16
+ resetSubject: (site: string) => `Reset your password for ${site}`,
17
+ resetIntro: 'Someone asked to reset the password for this email address. Choose a new password with the link below.',
18
+ resetAction: 'Choose a new password',
19
+ resetExpiry: 'The link works for 1 hour. If you didn’t ask for this, ignore this email — your password stays the same.',
20
+ fallback: 'If the button does not work, copy this address into your browser:',
21
+ },
22
+ cs: {
23
+ inviteSubject: (site: string) => `Pozvánka: ${site}`,
24
+ inviteIntro: (inviter: string, site: string, role: string) => `${inviter} vás zve ke správě obsahu webu ${site} jako ${role}.`,
25
+ inviteAction: 'Přijmout pozvánku',
26
+ inviteExpiry: (days: number) => `Odkaz platí ${days} dní. Pokud jste pozvánku nečekali, můžete ji ignorovat.`,
27
+ resetSubject: (site: string) => `Obnovení hesla: ${site}`,
28
+ resetIntro: 'Někdo požádal o obnovení hesla k této e-mailové adrese. Nové heslo nastavíte přes odkaz níže.',
29
+ resetAction: 'Nastavit nové heslo',
30
+ resetExpiry: 'Odkaz platí 1 hodinu. Pokud jste o obnovení nežádali, e-mail ignorujte — vaše heslo zůstává stejné.',
31
+ fallback: 'Pokud tlačítko nefunguje, zkopírujte tuto adresu do prohlížeče:',
32
+ },
33
+ de: {
34
+ inviteSubject: (site: string) => `Einladung zu ${site}`,
35
+ inviteIntro: (inviter: string, site: string, role: string) => `${inviter} lädt Sie ein, die Inhalte von ${site} als ${role} zu verwalten.`,
36
+ inviteAction: 'Einladung annehmen',
37
+ inviteExpiry: (days: number) => `Der Link ist ${days} Tage gültig. Wenn Sie keine Einladung erwartet haben, können Sie diese E-Mail ignorieren.`,
38
+ resetSubject: (site: string) => `Passwort für ${site} zurücksetzen`,
39
+ resetIntro: 'Für diese E-Mail-Adresse wurde ein neues Passwort angefordert. Über den Link unten können Sie ein neues Passwort festlegen.',
40
+ resetAction: 'Neues Passwort festlegen',
41
+ resetExpiry: 'Der Link ist 1 Stunde gültig. Wenn Sie das nicht angefordert haben, ignorieren Sie diese E-Mail. Ihr Passwort bleibt unverändert.',
42
+ fallback: 'Falls die Schaltfläche nicht funktioniert, kopieren Sie diese Adresse in Ihren Browser:',
43
+ },
44
+ } satisfies Record<Locale, Record<string, unknown>>
45
+
46
+ /** The role as the invitation names it, in the sentence's language (the admin's own names: Administrátor, Editor, Autor). */
47
+ const roleNames: Record<Locale, Record<string, string>> = {
48
+ en: { admin: 'an administrator', editor: 'an editor', author: 'an author' },
49
+ cs: { admin: 'administrátor', editor: 'editor', author: 'autor' },
50
+ de: { admin: 'Administrator', editor: 'Redakteur', author: 'Autor' },
51
+ }
52
+
53
+ const escapeHtml = (s: string) => s.replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&#39;' }[c]!))
54
+
55
+ const SUPPORTED: Locale[] = ['cs', 'en', 'de']
56
+
57
+ /**
58
+ * The language of the person whose request this is: the language they chose in the admin
59
+ * (the `cms_admin_locale` cookie), else the first of their browser's languages we write
60
+ * in (Accept-Language, by weight). Null when neither says. Used when the recipient has no
61
+ * saved language: a reset link goes to whoever asked, in their language, and an
62
+ * invitation in the inviting administrator's.
63
+ */
64
+ export function requestLocale(event: any): Locale | null {
65
+ const pick = (code: string): Locale | null => {
66
+ const base = code.trim().toLowerCase().split('-')[0] as Locale
67
+ return SUPPORTED.includes(base) ? base : null
68
+ }
69
+ const chosen = pick(String(getCookie(event, 'cms_admin_locale') ?? ''))
70
+ if (chosen) return chosen
71
+ const header = String(getRequestHeader(event, 'accept-language') ?? '')
72
+ const ranked = header.split(',').map((part, i) => {
73
+ const [code, ...params] = part.split(';')
74
+ const q = Number(/q=([\d.]+)/.exec(params.join(';'))?.[1] ?? 1)
75
+ return { code: (code ?? '').trim(), q: Number.isFinite(q) ? q : 0, i }
76
+ }).filter((x) => x.code && x.q > 0).sort((a, b) => b.q - a.q || a.i - b.i)
77
+ for (const { code } of ranked) {
78
+ const found = pick(code)
79
+ if (found) return found
80
+ }
81
+ return null
82
+ }
83
+
84
+ /** The admin's settings that emails need: product name and default language. */
85
+ export function emailContext(locale?: string | null): { locale: Locale; site: string } {
86
+ const admin = ((useAppConfig() as any)?.cms?.admin ?? {}) as Record<string, any>
87
+ const wanted = (locale || admin.defaultLocale || 'en') as string
88
+ const base = wanted.toLowerCase().split('-')[0]
89
+ const lang: Locale = base === 'cs' || base === 'de' ? base : 'en'
90
+ return { locale: lang, site: resolveText(admin.name, lang, ['en']) || 'CMS' }
91
+ }
92
+
93
+ function layout(opts: { intro: string; action: string; url: string; footer: string; fallback: string }) {
94
+ const url = escapeHtml(opts.url)
95
+ const html = `<!doctype html><html><body style="margin:0;padding:24px;background:#fafafa;font-family:-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;color:#171717">
96
+ <div style="max-width:480px;margin:0 auto;background:#fff;border:1px solid #e5e5e5;border-radius:8px;padding:28px">
97
+ <p style="margin:0 0 20px;font-size:15px;line-height:1.55">${escapeHtml(opts.intro)}</p>
98
+ <p style="margin:0 0 24px"><a href="${url}" style="display:inline-block;background:#171717;color:#fff;text-decoration:none;padding:10px 16px;border-radius:6px;font-size:14px;font-weight:600">${escapeHtml(opts.action)}</a></p>
99
+ <p style="margin:0 0 16px;font-size:13px;line-height:1.5;color:#737373">${escapeHtml(opts.footer)}</p>
100
+ <p style="margin:0;font-size:12px;line-height:1.5;color:#a3a3a3">${escapeHtml(opts.fallback)}<br><span style="word-break:break-all">${url}</span></p>
101
+ </div></body></html>`
102
+ const text = `${opts.intro}\n\n${opts.action}: ${opts.url}\n\n${opts.footer}\n`
103
+ return { html, text }
104
+ }
105
+
106
+ export function inviteEmail(opts: { to: string; inviter: string; url: string; role?: string; locale?: string | null }) {
107
+ const { locale, site } = emailContext(opts.locale)
108
+ const c = copy[locale]
109
+ const days = Math.round(INVITE_TTL_MS / 86_400_000)
110
+ return {
111
+ to: opts.to,
112
+ subject: c.inviteSubject(site),
113
+ ...layout({ intro: c.inviteIntro(opts.inviter, site, roleNames[locale][opts.role ?? ''] ?? roleNames[locale].editor!), action: c.inviteAction, url: opts.url, footer: c.inviteExpiry(days), fallback: c.fallback }),
114
+ }
115
+ }
116
+
117
+ export function resetEmail(opts: { to: string; url: string; locale?: string | null }) {
118
+ const { locale, site } = emailContext(opts.locale)
119
+ const c = copy[locale]
120
+ return {
121
+ to: opts.to,
122
+ subject: c.resetSubject(site),
123
+ ...layout({ intro: c.resetIntro, action: c.resetAction, url: opts.url, footer: c.resetExpiry, fallback: c.fallback }),
124
+ }
125
+ }
@@ -0,0 +1,40 @@
1
+ import type { CmsErrorReport } from 'tinyzoo'
2
+
3
+ /**
4
+ * Error reporting for the host: besides the JSON log line, a server error runs the
5
+ * `cms:error` Nitro hook (see CmsErrorReport), so a host plugin can forward it to
6
+ * Sentry or anything else. Reporting never throws, never waits for the host's code
7
+ * to finish before the response is gone, and a failing hook is only logged.
8
+ */
9
+
10
+ /** Run the `cms:error` hook for one report, in the background. Never rejects. */
11
+ export function reportCmsError(report: Omit<CmsErrorReport, 'message' | 'error' | 'rawError'> & { error: unknown; message?: string }, event?: any): void {
12
+ const { error: raw, ...rest } = report
13
+ const error = scrubError(raw)
14
+ const full: CmsErrorReport = { ...rest, error, rawError: raw, message: report.message ?? error.message }
15
+ const run = async () => {
16
+ try {
17
+ await useNitroApp().hooks.callHook('cms:error', full)
18
+ }
19
+ catch (err) {
20
+ console.error('[cms] cms:error hook failed', safeErrorMessage(err))
21
+ }
22
+ }
23
+ // After the response: the next turn of the event loop, and the platform is told to
24
+ // keep a serverless worker alive until the host's code has finished.
25
+ const done = new Promise<void>((resolve) => setTimeout(() => { run().finally(resolve) }, 0))
26
+ if (typeof event?.waitUntil === 'function') event.waitUntil(done)
27
+ }
28
+
29
+ /** Run a scheduled task body; a failure is reported through `cms:error` (source 'task') and thrown again. */
30
+ export async function runReportedTask<T>(task: string, body: () => Promise<T>): Promise<T> {
31
+ try {
32
+ return await body()
33
+ }
34
+ catch (err) {
35
+ const cause = (err as any)?.cause instanceof Error ? (err as any).cause : err
36
+ console.error(JSON.stringify({ level: 'error', msg: 'cms task failed', task, error: safeErrorMessage(cause) }))
37
+ reportCmsError({ source: 'task', error: err, status: null, requestId: null, method: null, path: null, userId: null, task })
38
+ throw err
39
+ }
40
+ }
@@ -0,0 +1,17 @@
1
+ import { foldSearchText, sql } from 'tinyzoo'
2
+
3
+ // Search that ignores letter case and accents ("zimni" finds "Zimní"), without a
4
+ // database extension: both sides lowercased, accented letters replaced by plain ones.
5
+ // (Czech, Slovak, German, Polish, Hungarian, Romanian, Croatian and the like.)
6
+ const ACCENTED = 'áàâäãåčćçďéèêëěíìîïľĺłňńñóòôöõőřŕšśťúùûüůűýÿžźżąęășşțţđ'
7
+ const PLAIN = 'aaaaaacccdeeeeeiiiilllnnnoooooorrsstuuuuuuyyzzzaeassttd'
8
+
9
+ /** The search text, folded the same way as the column. */
10
+ export function foldAccents(text: string): string {
11
+ return foldSearchText(text)
12
+ }
13
+
14
+ /** A text column, lowercased and without accents (for `like`). */
15
+ export function foldedColumn(col: any) {
16
+ return sql`translate(lower(cast(${col} as text)), ${ACCENTED}, ${PLAIN})`
17
+ }