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
package/src/blocks.ts ADDED
@@ -0,0 +1,624 @@
1
+ import { z, type ZodTypeAny } from 'zod'
2
+ import type { AnyFieldDescriptor, FieldDescriptor, FieldKind } from './descriptor'
3
+ import type { LocalizedText } from './i18n'
4
+ import { upgradeRichText } from './richtext'
5
+
6
+ /**
7
+ * Blocks: an ordered list of typed sections a client arranges into a page (hero,
8
+ * text, gallery, call to action…). The developer defines each block type in code,
9
+ * with its own fields; the editor picks, orders and fills them. Stored as one jsonb
10
+ * array per entry:
11
+ *
12
+ * [{ id: 'k3j…', type: 'hero', heading: 'Vítejte', image: '<media id>' }, …]
13
+ *
14
+ * Block fields use the regular field catalog, minus relations (v1): text, slug,
15
+ * number, boolean, datetime, select, rich text, media, and one level of lists
16
+ * (`f.list()`: FAQ questions, feature cards, price rows inside one block). Rich text
17
+ * is sanitised on write like everywhere else; media ids (also inside a block's
18
+ * lists) are resolved by the content API and counted by media cleanup.
19
+ *
20
+ * Stored JSON outlives the code that wrote it, so a block (or `f.list`) can carry a
21
+ * `version`: stored blocks are stamped `v` (left out while it is 1) and anything
22
+ * behind runs through `upgrade` whenever it is read (see upgradeBlocks). A block
23
+ * whose type was removed from the config is kept as it is, not dropped or refused,
24
+ * for as long as it is stored (a new one of an unknown type is refused).
25
+ *
26
+ * A WRITE does not take the client's word for any of this (see `blocksSchema`): a
27
+ * block that says it is behind, or whose `upgrade` throws, or whose type is gone, is
28
+ * only kept when the same block is already stored; a block without `v` is checked
29
+ * against the current definition and, when it does not fit, upgraded from version 1.
30
+ */
31
+
32
+ /**
33
+ * Field types allowed inside a block, a list item or a group ('blocks' = a list, one
34
+ * level deep; 'group' = a named object of fields).
35
+ */
36
+ export const BLOCK_FIELD_TYPES = new Set(['text', 'slug', 'number', 'boolean', 'datetime', 'select', 'richtext', 'media', 'blocks', 'group'])
37
+
38
+ export interface BlockDef<F extends Record<string, AnyFieldDescriptor> = Record<string, AnyFieldDescriptor>> {
39
+ /** Name in the block picker ("Hero", { cs: 'Úvod', en: 'Hero' }). */
40
+ label: LocalizedText
41
+ /** One line in the block picker on what the block is for. */
42
+ description?: LocalizedText
43
+ /** Iconify name, e.g. 'i-lucide-image'. */
44
+ icon?: string
45
+ fields: F
46
+ /**
47
+ * The shape's version, 1 when left out. Raise it whenever a stored block of the old
48
+ * shape needs changing (a renamed or removed field, a new required one) and describe
49
+ * the change in `upgrade`. Needed from 2 on.
50
+ */
51
+ version?: number
52
+ /**
53
+ * Bring a block stored at `fromVersion` to `fromVersion + 1` and return it (it is
54
+ * called once per step: 1 → 2, then 2 → 3). `data` is a copy holding `id`, `type`
55
+ * and the stored fields; `id` and `type` are kept whatever is returned. Must be pure
56
+ * (no database, no clock): it runs on every read of an old block until
57
+ * `tinyzoo content:migrate` rewrites the data.
58
+ */
59
+ upgrade?: (data: Record<string, any>, fromVersion: number) => Record<string, any>
60
+ }
61
+
62
+ /** Keys of a stored block that are not its fields. */
63
+ const BLOCK_META_KEYS = new Set(['id', 'type', 'v'])
64
+
65
+ /** The version a block definition is at. */
66
+ export const blockVersion = (def: Pick<BlockDef, 'version'>): number => def.version ?? 1
67
+
68
+ export function defineBlock<F extends Record<string, AnyFieldDescriptor>>(def: BlockDef<F>): BlockDef<F> {
69
+ checkVersioning('Block', def)
70
+ checkContainedFields('Block', def.fields)
71
+ return def
72
+ }
73
+
74
+ /** Does a set of fields hold a list (`f.list`, `f.blocks`), directly or inside a group? */
75
+ export function holdsList(fields: Record<string, AnyFieldDescriptor>): boolean {
76
+ return (Object.values(fields) as FieldDescriptor[]).some((fld) => fld.type === 'blocks' || (fld.type === 'group' && holdsList(fld.fields ?? {})))
77
+ }
78
+
79
+ /**
80
+ * The rules for fields that sit inside something else (a block, a list item, a group):
81
+ * only the field types blocks support; a list inside is one level (its items hold
82
+ * plain fields and groups, not more lists); a group inside a block or a list holds no
83
+ * list (only a group straight on an entry may).
84
+ */
85
+ export function checkContainedFields(what: string, fields: Record<string, AnyFieldDescriptor>, opts: { reserved?: boolean } = { reserved: true }) {
86
+ for (const [key, fld] of Object.entries(fields) as [string, FieldDescriptor][]) {
87
+ if (opts.reserved && (key === 'id' || key === 'type' || key === 'v')) throw new Error(`${what} field "${key}" is reserved (every block has an id, a type and a version).`)
88
+ if (!BLOCK_FIELD_TYPES.has(fld.type)) {
89
+ throw new Error(`${what} field "${key}" has type "${fld.type}", which blocks, lists and groups do not support (allowed: ${[...BLOCK_FIELD_TYPES].join(', ')}).`)
90
+ }
91
+ // A list inside a block is one level: its items hold plain fields, not more lists.
92
+ if (fld.type === 'blocks') {
93
+ for (const inner of Object.values(fld.blocks ?? {})) {
94
+ for (const [innerKey, innerFld] of Object.entries(inner.fields) as [string, FieldDescriptor][]) {
95
+ if (innerFld.type === 'blocks' || (innerFld.type === 'group' && holdsList(innerFld.fields ?? {}))) {
96
+ throw new Error(`${what} field "${key}" is a list whose items have a list ("${innerKey}"). Lists inside a block are one level deep.`)
97
+ }
98
+ }
99
+ }
100
+ }
101
+ if (fld.type === 'group' && holdsList(fld.fields ?? {})) {
102
+ throw new Error(`${what} field "${key}" is a group with a list inside. Inside a block or a list a group holds plain fields only (a group straight on an entry may hold a list).`)
103
+ }
104
+ }
105
+ }
106
+
107
+ /** A version must be a whole number from 1, and from 2 on says how to get there. */
108
+ export function checkVersioning(what: string, o: { version?: number; upgrade?: unknown }) {
109
+ if (o.version !== undefined && (!Number.isInteger(o.version) || o.version < 1)) throw new Error(`${what} version must be a whole number from 1 (got ${String(o.version)}).`)
110
+ if ((o.version ?? 1) > 1 && typeof o.upgrade !== 'function') {
111
+ throw new Error(`${what} is at version ${o.version} but has no \`upgrade(data, fromVersion)\`: stored items of the older shape could not be brought up to date.`)
112
+ }
113
+ if (o.upgrade !== undefined && typeof o.upgrade !== 'function') throw new Error(`${what} \`upgrade\` must be a function.`)
114
+ }
115
+
116
+ type KindOf<D> = D extends FieldDescriptor<infer K> ? K : never
117
+ type Prettify<T> = { [K in keyof T]: T[K] } & {}
118
+ /** One stored block of type K. Media fields hold a media id (string). */
119
+ export type BlockValue<K extends string, F> = Prettify<
120
+ { id: string; type: K }
121
+ & { [P in keyof F & string as KindOf<F[P]>['optionalIn'] extends true ? never : P]: KindOf<F[P]>['out'] }
122
+ & { [P in keyof F & string as KindOf<F[P]>['optionalIn'] extends true ? P : never]?: KindOf<F[P]>['out'] | null }
123
+ >
124
+ /**
125
+ * The stored value of a group: an object of its fields, each typed by its own kind
126
+ * (media fields hold a media id). Every key is optional and may be null: which fields
127
+ * must be filled in is a runtime rule (`required: true`) the types cannot see, and a
128
+ * group is saved with the empty ones left out.
129
+ */
130
+ export type GroupValue<F> = Prettify<{ [P in keyof F & string]?: KindOf<F[P]>['out'] | null }>
131
+ /** The value of a blocks field: an array of any of its block types. */
132
+ export type BlocksValue<B extends Record<string, BlockDef<any>>> = Array<{ [K in keyof B & string]: BlockValue<K, B[K]['fields']> }[keyof B & string]>
133
+
134
+ /** Erased shape of any stored block (what the emitted schema types the column as). */
135
+ export interface CmsBlock { id: string; type: string; [field: string]: unknown }
136
+
137
+ // ── stored versions ──────────────────────────────────────────────────────────
138
+
139
+ /** The stored value of a block's `v`: a whole number from 1; anything else (or nothing) reads as 1. */
140
+ export function storedBlockVersion(block: object): number {
141
+ const v = (block as { v?: unknown }).v
142
+ return typeof v === 'number' && Number.isInteger(v) && v >= 1 ? v : 1
143
+ }
144
+
145
+ /** Marks a block whose `upgrade` threw (admin only): shown as needing attention, kept as stored. */
146
+ export const UPGRADE_FAILED_KEY = '__upgradeFailed'
147
+
148
+ export interface UpgradeIssue {
149
+ type: string
150
+ /** The block's id, when it has one. */
151
+ id: string | null
152
+ from: number
153
+ to: number
154
+ /** Where the block is inside the value: `[index, 'items', 2]` (the field key first when called with a row). */
155
+ path: (string | number)[]
156
+ error: unknown
157
+ }
158
+
159
+ export interface UpgradeOptions {
160
+ /** Called for each block whose `upgrade` threw; that block is then left as it was stored. */
161
+ onError?: (issue: UpgradeIssue) => void
162
+ /** Called for each block that was brought to a newer version (`tinyzoo content:migrate` counts them). */
163
+ onUpgrade?: (info: { type: string; id: string | null; from: number; to: number; path: (string | number)[] }) => void
164
+ /** Put `v` (the stored one) and `__upgradeFailed: true` on such blocks, so the admin can show them as needing attention. */
165
+ markFailed?: boolean
166
+ /** Put `v` on every block that has none (version 1 included), so a client always sends it back: what the admin reads. */
167
+ stamp?: boolean
168
+ /** What the value belongs to ("page 3f2a… · sections"), named in the development warnings. */
169
+ where?: string
170
+ }
171
+
172
+ const isPlainObject = (v: unknown): v is Record<string, any> => !!v && typeof v === 'object' && !Array.isArray(v)
173
+
174
+ /**
175
+ * Bring ONE block (not the lists inside it) from its stored version to the current
176
+ * one, by calling `upgrade` once per step, and stamp `v` (left out at version 1).
177
+ * Returns the block itself when it is not behind. Throws when a step does.
178
+ */
179
+ export function upgradeBlock<B extends Record<string, any>>(def: BlockDef, block: B): B {
180
+ const to = blockVersion(def)
181
+ const from = storedBlockVersion(block)
182
+ if (from >= to) return block
183
+ const { v: _v, ...rest } = block
184
+ let data: Record<string, any> = structuredClone(rest)
185
+ for (let step = from; step < to; step++) {
186
+ const out = def.upgrade!(data, step)
187
+ if (!isPlainObject(out)) throw new Error(`upgrade(data, ${step}) must return the block's data (got ${out === null ? 'null' : typeof out}).`)
188
+ data = { ...out, id: block.id, type: block.type }
189
+ }
190
+ if (to > 1) data.v = to
191
+ return data as B
192
+ }
193
+
194
+ const warned = new Set<string>()
195
+ const once = (key: string, fn: () => void) => {
196
+ if (warned.has(key)) return
197
+ if (warned.size > 500) warned.clear()
198
+ warned.add(key)
199
+ fn()
200
+ }
201
+
202
+ /** Log a failed upgrade once per block (not on every request). */
203
+ export function logUpgradeFailure(issue: UpgradeIssue, where = ''): void {
204
+ const at = issue.path.join('.')
205
+ once(`fail|${where}|${at}|${issue.id}|${issue.type}|${issue.from}`, () => {
206
+ console.error(`[cms] could not upgrade the "${issue.type}" block${issue.id ? ` ${issue.id}` : ''} (stored at version ${issue.from}, now ${issue.to})${where ? ` in ${where}` : ''}${at ? ` at ${at}` : ''}: ${(issue.error as Error)?.message ?? issue.error}. It is shown as stored.`)
207
+ })
208
+ }
209
+
210
+ const isProduction = () => typeof process !== 'undefined' && process.env?.NODE_ENV === 'production'
211
+
212
+ /**
213
+ * Development warning: a stored block has keys its definition does not know — the
214
+ * case that silently loses data today (a field was renamed or removed without a
215
+ * `version` and an `upgrade`). They are dropped on the next save.
216
+ */
217
+ function warnUnknownKeys(def: BlockDef, block: Record<string, any>, where?: string) {
218
+ if (isProduction()) return
219
+ const unknown = Object.keys(block).filter((k) => !BLOCK_META_KEYS.has(k) && !k.startsWith('__') && !Object.hasOwn(def.fields, k))
220
+ if (!unknown.length) return
221
+ once(`keys|${block.type}|${unknown.join(',')}`, () => {
222
+ console.warn(`[cms] A stored "${block.type}" block has keys its definition does not know (${unknown.join(', ')})${where ? ` in ${where}` : ''}. They are ignored and lost on the next save. If the block changed shape, raise its \`version\` and rename or move that data in \`upgrade(data, fromVersion)\`.`)
223
+ })
224
+ }
225
+
226
+ /**
227
+ * One stored field value brought to the current shape: a list's items run through
228
+ * `upgrade`, rich text through `richTextUpgrades`, a group's fields one by one.
229
+ * The same value when nothing changed.
230
+ */
231
+ function upgradeFieldValue(fld: FieldDescriptor, value: unknown, opts: UpgradeOptions, path: (string | number)[]): unknown {
232
+ if (fld.type === 'blocks' && fld.blocks) return upgradeBlocks(value, fld.blocks, opts, path)
233
+ if (fld.type === 'richtext') return upgradeRichText(value)
234
+ if (fld.type === 'group' && fld.fields && isPlainObject(value)) {
235
+ let cur: Record<string, any> = value
236
+ for (const [key, inner] of Object.entries(fld.fields) as [string, FieldDescriptor][]) {
237
+ if (!(key in cur)) continue
238
+ const next = upgradeFieldValue(inner, cur[key], opts, [...path, key])
239
+ if (next !== cur[key]) cur = { ...cur, [key]: next }
240
+ }
241
+ return cur
242
+ }
243
+ return value
244
+ }
245
+
246
+ /**
247
+ * Bring a stored blocks array (or list) to the versions in `defs`: every block that
248
+ * is behind runs through its definition's `upgrade`, step by step, and is stamped
249
+ * `v`; the lists inside blocks (and rich text, see `richTextUpgrades`) too.
250
+ *
251
+ * Pure: the input is not changed, and what needs no change comes back as the same
252
+ * object. Blocks of a type that is not in `defs` pass through untouched (the config
253
+ * dropped them; they are kept, not fatal). A block whose `upgrade` throws is left as
254
+ * it was stored and reported through `onError`, so one bad block never takes a page down.
255
+ */
256
+ export function upgradeBlocks<T = unknown>(value: T, defs: Record<string, BlockDef>, opts: UpgradeOptions = {}, path: (string | number)[] = []): T {
257
+ if (!Array.isArray(value)) return value
258
+ let changed = false
259
+ const out = (value as unknown[]).map((b, i) => {
260
+ if (!isPlainObject(b) || typeof b.type !== 'string' || !Object.hasOwn(defs, b.type)) return b
261
+ const def = defs[b.type]!
262
+ let cur: Record<string, any> = b
263
+ try {
264
+ cur = upgradeBlock(def, b)
265
+ if (cur !== b) opts.onUpgrade?.({ type: b.type, id: typeof b.id === 'string' ? b.id : null, from: storedBlockVersion(b), to: blockVersion(def), path: [...path, i] })
266
+ }
267
+ catch (error) {
268
+ opts.onError?.({ type: b.type, id: typeof b.id === 'string' ? b.id : null, from: storedBlockVersion(b), to: blockVersion(def), path: [...path, i], error })
269
+ changed = changed || !!opts.markFailed
270
+ return opts.markFailed ? { ...b, v: storedBlockVersion(b), [UPGRADE_FAILED_KEY]: true } : b
271
+ }
272
+ for (const [key, fld] of Object.entries(def.fields) as [string, FieldDescriptor][]) {
273
+ if (!(key in cur)) continue
274
+ const next = upgradeFieldValue(fld, cur[key], opts, [...path, i, key])
275
+ if (next !== cur[key]) cur = { ...cur, [key]: next }
276
+ }
277
+ if (opts.stamp && cur.v !== storedBlockVersion(cur)) cur = { ...cur, v: storedBlockVersion(cur) }
278
+ warnUnknownKeys(def, cur, opts.where)
279
+ if (cur !== b) changed = true
280
+ return cur
281
+ })
282
+ return (changed ? out : value) as T
283
+ }
284
+
285
+ /** The same for the items of an `f.list` (a blocks field with one item type): `upgradeBlocks` on its definition. */
286
+ export const upgradeListItems = upgradeBlocks
287
+
288
+ /**
289
+ * Upgrade the stored JSON of a row in place: blocks and lists (to their current
290
+ * versions) and rich text (`richTextUpgrades`). Keys the row does not have (a
291
+ * translation holds only the localized ones) are left alone.
292
+ */
293
+ export function upgradeStoredRow<R extends Record<string, any>>(
294
+ fields: Record<string, { type: string; blocks?: Record<string, BlockDef>; fields?: Record<string, any> }>, row: R, opts: UpgradeOptions = {},
295
+ ): R {
296
+ for (const [key, fld] of Object.entries(fields)) {
297
+ if (!(key in row) || row[key] == null) continue
298
+ const was = row[key]
299
+ const next = upgradeFieldValue(fld as FieldDescriptor, was, { ...opts, where: opts.where ? `${opts.where} · ${key}` : key }, [key])
300
+ if (next !== was) (row as Record<string, any>)[key] = next
301
+ }
302
+ return row
303
+ }
304
+
305
+ // ── validation ───────────────────────────────────────────────────────────────
306
+
307
+ /**
308
+ * What an unknown block type (one the config no longer has) may be called: lower
309
+ * case, digits, `_` and `-`, starting with a letter or digit. Anything else
310
+ * (`Link`, `_hero`, `-hero`) could be drawn as the component of a known type.
311
+ */
312
+ export const UNKNOWN_BLOCK_TYPE = /^[a-z0-9][a-z0-9_-]*$/
313
+ const squash = (type: string) => type.toLowerCase().replace(/[_-]/g, '')
314
+
315
+ const NOT_UP_TO_DATE = 'This block could not be brought up to date — remove it or fix it'
316
+ const OUT_OF_DATE = 'This block is out of date — reload the page and try again'
317
+
318
+ /** Structural equality of two JSON values. */
319
+ function deepEqual(a: unknown, b: unknown): boolean {
320
+ if (a === b) return true
321
+ if (typeof a !== 'object' || typeof b !== 'object' || !a || !b) return false
322
+ if (Array.isArray(a) !== Array.isArray(b)) return false
323
+ if (Array.isArray(a)) return a.length === (b as unknown[]).length && a.every((x, i) => deepEqual(x, (b as unknown[])[i]))
324
+ const ka = Object.keys(a)
325
+ const kb = Object.keys(b)
326
+ return ka.length === kb.length && ka.every((k) => Object.hasOwn(b, k) && deepEqual((a as any)[k], (b as any)[k]))
327
+ }
328
+
329
+ /** A block as it is compared with its stored copy: no failure marker, and `v` always spelled out (a missing one is 1). */
330
+ const comparable = (block: Record<string, any>) => {
331
+ const { [UPGRADE_FAILED_KEY]: _marker, v: _v, ...rest } = block
332
+ return { ...rest, v: storedBlockVersion(block) }
333
+ }
334
+ const sameAsStored = (item: Record<string, any>, stored: Record<string, any> | undefined) => !!stored && deepEqual(comparable(item), comparable(stored))
335
+
336
+ interface Compiled {
337
+ loose: z.ZodObject<any>
338
+ strict: z.ZodObject<any>
339
+ /** Fields holding a list of blocks: validated by `validateBlockList`, with their own stored values. */
340
+ lists: [string, FieldDescriptor][]
341
+ }
342
+
343
+ const compiled = new WeakMap<Record<string, BlockDef>, Map<string, Compiled>>()
344
+
345
+ function compile(blocks: Record<string, BlockDef>): Map<string, Compiled> {
346
+ const known = compiled.get(blocks)
347
+ if (known) return known
348
+ const out = new Map<string, Compiled>()
349
+ for (const [type, def] of Object.entries(blocks)) {
350
+ const shape: Record<string, ZodTypeAny> = {
351
+ id: z.string().min(1).max(64),
352
+ type: z.literal(type),
353
+ }
354
+ const lists: [string, FieldDescriptor][] = []
355
+ for (const [key, fld] of Object.entries(def.fields) as [string, FieldDescriptor][]) {
356
+ if (fld.type === 'blocks' && fld.blocks) {
357
+ // Checked on its own afterwards, against what is stored inside this block.
358
+ lists.push([key, fld])
359
+ shape[key] = z.unknown().optional()
360
+ continue
361
+ }
362
+ // Inside a block every field may be left empty while the editor is still
363
+ // filling it in, unless it is explicitly required.
364
+ let s = fld.zod('create')
365
+ if (!fld.isRequired) s = s.nullish()
366
+ shape[key] = s
367
+ }
368
+ const o = z.object(shape)
369
+ out.set(type, { loose: o, strict: o.strict(), lists })
370
+ }
371
+ compiled.set(blocks, out)
372
+ return out
373
+ }
374
+
375
+ type Problem = { code: string; path: (string | number)[]; message: string; [k: string]: unknown }
376
+ const problem = (path: (string | number)[], message: string): Problem => ({ code: 'custom', path, message })
377
+ const idOf = (b: Record<string, any>) => (typeof b.id === 'string' ? b.id : null)
378
+
379
+ /** Keys of a block that are neither its fields nor its envelope. */
380
+ const unknownKeys = (def: BlockDef, block: Record<string, any>) => Object.keys(block).filter((k) => !BLOCK_META_KEYS.has(k) && k !== UPGRADE_FAILED_KEY && !Object.hasOwn(def.fields, k))
381
+
382
+ /**
383
+ * Check a blocks array against its definitions, for a WRITE. `stored` is what the
384
+ * same field holds right now (raw, as in the database), or nothing when the row is
385
+ * new; the schema alone cannot see it, so the handlers that have the row pass it in.
386
+ * It decides two things that must never be taken on the client's word:
387
+ *
388
+ * - a block that says it is behind (`v` below the current version), or whose
389
+ * `upgrade` throws, or whose type is not defined any more, is only kept when it
390
+ * is a block that is already stored (same id, and for a stale one the same
391
+ * version; for a failing or unknown one identical to the stored copy). Anything
392
+ * else is refused: it would be stored without being checked.
393
+ * - a block without `v` is not trusted to be current: it is checked against the
394
+ * current definition, and only when that does not fit is it taken for version 1.
395
+ *
396
+ * Returns the checked list (blocks stamped with the current `v`), or null with the
397
+ * problems added to `problems`.
398
+ */
399
+ function validateBlockList(
400
+ blocks: Record<string, BlockDef>, max: number, list: unknown, stored: unknown, base: (string | number)[], problems: Problem[],
401
+ ): unknown[] | null {
402
+ if (!Array.isArray(list)) {
403
+ problems.push({ code: 'invalid_type', path: base, message: 'Invalid input: expected array' })
404
+ return null
405
+ }
406
+ if (list.length > max) {
407
+ problems.push({ code: 'too_big', path: base, message: `Too big: expected array to have <=${max} items` })
408
+ return null
409
+ }
410
+ const types = compile(blocks)
411
+ const storedById = new Map<string, Record<string, any>>()
412
+ if (Array.isArray(stored)) for (const s of stored) if (isPlainObject(s) && typeof s.id === 'string' && !storedById.has(s.id)) storedById.set(s.id, s)
413
+ const envelope = z.object({ id: z.string().min(1).max(64), type: z.string().min(1).max(64) })
414
+ const squashed = Object.keys(blocks).map(squash)
415
+
416
+ const out: unknown[] = []
417
+ const seen = new Set<string>()
418
+ let ok = true
419
+ const fail = (path: (string | number)[], ...found: Problem[]) => {
420
+ ok = false
421
+ problems.push(...found.map((p) => ({ ...p, path: [...path, ...p.path] })))
422
+ }
423
+ const failZod = (index: number, issues: readonly any[]) => fail([...base, index], ...issues.map((is) => ({ ...is, path: is.path ?? [] })))
424
+ const keep = (index: number, id: string, block: unknown) => {
425
+ if (seen.has(id)) return fail([...base, index], problem(['id'], 'Duplicate block id'))
426
+ seen.add(id)
427
+ out.push(block)
428
+ }
429
+
430
+ list.forEach((item, i) => {
431
+ const at = [...base, i]
432
+ if (!isPlainObject(item)) return failZod(i, envelope.safeParse(item).error?.issues ?? [])
433
+ const type = typeof item.type === 'string' ? item.type : ''
434
+ const def = Object.hasOwn(blocks, type) ? blocks[type] : undefined
435
+ const env = envelope.safeParse(item)
436
+ const sb = typeof item.id === 'string' ? storedById.get(item.id) : undefined
437
+ const storedOfType = sb && sb.type === type ? sb : undefined
438
+
439
+ // ── a type the config does not have (any more) ──
440
+ if (!def) {
441
+ if (!env.success) return failZod(i, env.error.issues)
442
+ const { [UPGRADE_FAILED_KEY]: _marker, ...kept } = item
443
+ // Only a block that is already stored, exactly as it is stored, stays; it could not be checked.
444
+ if (sameAsStored(item, sb)) return keep(i, env.data.id, kept)
445
+ if (!UNKNOWN_BLOCK_TYPE.test(type) || squashed.includes(squash(type))) return fail(at, problem(['type'], 'Unknown block type'))
446
+ return fail(at, problem([], 'This block type does not exist (any more), so no such block can be added or changed — remove it'))
447
+ }
448
+
449
+ // ── a known type ──
450
+ const current = blockVersion(def)
451
+ const { v: claimed, [UPGRADE_FAILED_KEY]: _marker, ...rest } = item
452
+ const compiledDef = types.get(type)!
453
+ let from = current
454
+ let strictResult: ReturnType<z.ZodObject<any>['safeParse']> | null = null
455
+ if (claimed !== undefined && claimed !== null) {
456
+ if (typeof claimed !== 'number' || !Number.isInteger(claimed) || claimed < 1) return fail(at, problem(['v'], 'The version must be a whole number from 1'))
457
+ if (claimed > current) return fail(at, problem(['v'], `Saved by a newer version of this site (block version ${claimed}, this one knows ${current})`))
458
+ from = claimed
459
+ // A stale block is taken as stale only when it is stored that way: the client's word is not enough.
460
+ if (from < current && !(storedOfType && storedBlockVersion(storedOfType) === from)) return fail(at, problem(['v'], OUT_OF_DATE))
461
+ }
462
+ else {
463
+ // No `v`: is it a block of the current shape? Nothing may be dropped silently.
464
+ strictResult = compiledDef.strict.safeParse(rest)
465
+ if (!strictResult.success) {
466
+ if (current > 1) from = 1
467
+ else {
468
+ const extra = unknownKeys(def, item)
469
+ if (extra.length) return fail(at, problem([], `This block has fields this site does not know (${extra.join(', ')}) — the editor is out of date, reload the page`))
470
+ return failZod(i, strictResult.error.issues)
471
+ }
472
+ }
473
+ }
474
+
475
+ let data: Record<string, any> = rest
476
+ let upgraded = false
477
+ if (from < current) {
478
+ try {
479
+ data = upgradeBlock(def, { ...rest, v: from })
480
+ upgraded = true
481
+ }
482
+ catch (error) {
483
+ logUpgradeFailure({ type, id: idOf(item), from, to: current, path: at, error })
484
+ // Not brought up to date, so not checked: only the copy that is already stored may stay.
485
+ if (sameAsStored(item, sb) && env.success) return keep(i, env.data.id, sb)
486
+ return fail(at, problem([], NOT_UP_TO_DATE))
487
+ }
488
+ }
489
+ const { v: _v, ...fields } = data
490
+ const r = strictResult?.success ? strictResult : (upgraded ? compiledDef.strict : compiledDef.loose).safeParse(fields)
491
+ const own: Problem[] = []
492
+ if (!r.success) own.push(...r.error.issues.map((is: any) => ({ ...is, path: is.path ?? [] })))
493
+ const value: Record<string, any> = r.success ? { ...(r.data as Record<string, any>) } : {}
494
+ // Lists inside the block, against the same list stored inside the same block.
495
+ for (const [key, fld] of compiledDef.lists) {
496
+ const raw = fields[key]
497
+ if (raw === undefined || raw === null) {
498
+ if (fld.isRequired) own.push({ code: 'invalid_type', path: [key], message: 'Required' })
499
+ else if (r.success && raw === null) value[key] = null
500
+ continue
501
+ }
502
+ const nested: Problem[] = []
503
+ const checked = validateBlockList(fld.blocks!, (fld.meta?.list as { max?: number | null } | undefined)?.max ?? 500, raw, storedOfType?.[key], [key], nested)
504
+ own.push(...nested)
505
+ if (checked) value[key] = checked
506
+ }
507
+ if (own.length) return fail(at, ...own)
508
+ if (!env.success) return failZod(i, env.error.issues)
509
+ keep(i, String(value.id), current > 1 ? { ...value, v: current } : value)
510
+ })
511
+ return ok ? out : null
512
+ }
513
+
514
+ /**
515
+ * Zod for a blocks array. Each block is checked against its own type's fields, after
516
+ * `upgrade` when it was stored at an older version (and then strictly: a key the
517
+ * upgrade forgot to rename is an error, not silently dropped). Blocks come out
518
+ * stamped with the current `v`.
519
+ *
520
+ * Writing is stricter than reading, because the server must not take the client's
521
+ * word for what it stores (see `validateBlockList`): a block of a type that is no
522
+ * longer defined, a block that is behind, and a block whose `upgrade` throws are kept
523
+ * only when `stored` (what the field holds now) has the same block; a block without
524
+ * `v` is checked as the current shape, and as version 1 only when it does not fit. With
525
+ * no `stored` (a new row) none of those exist.
526
+ */
527
+ export function blocksSchema(blocks: Record<string, BlockDef>, max = 500, stored?: unknown): ZodTypeAny {
528
+ return z.array(z.any()).max(max).transform((list, ctx) => {
529
+ const problems: Problem[] = []
530
+ const out = validateBlockList(blocks, max, list, stored, [], problems)
531
+ for (const p of problems) ctx.addIssue(p as any)
532
+ return out ?? z.NEVER
533
+ })
534
+ }
535
+
536
+ /** The admin graph's description of one field inside a block, list item or group. */
537
+ export function innerFieldGraph(key: string, fld: FieldDescriptor) {
538
+ return {
539
+ key,
540
+ type: fld.type,
541
+ optional: !fld.isRequired,
542
+ required: fld.isRequired,
543
+ unique: false,
544
+ ui: fld.ui,
545
+ meta: fld.meta,
546
+ }
547
+ }
548
+
549
+ /** Serializable description of the block types for the admin graph. */
550
+ export function blocksGraph(blocks: Record<string, BlockDef>) {
551
+ return Object.fromEntries(Object.entries(blocks).map(([type, def]) => [type, {
552
+ label: def.label,
553
+ description: def.description ?? null,
554
+ icon: def.icon ?? 'i-lucide-square',
555
+ fields: (Object.entries(def.fields) as [string, FieldDescriptor][]).map(([key, fld]) => innerFieldGraph(key, fld)),
556
+ }]))
557
+ }
558
+
559
+ /** The fields of a group for the admin graph (a group's own `meta.fields`). */
560
+ export function groupGraph(fields: Record<string, AnyFieldDescriptor>) {
561
+ return (Object.entries(fields) as [string, FieldDescriptor][]).map(([key, fld]) => innerFieldGraph(key, fld))
562
+ }
563
+
564
+ /** For each block type, the keys of its media fields (for population and cleanup). */
565
+ export function blockMediaKeys(blocks: Record<string, BlockDef>): Map<string, string[]> {
566
+ return new Map(Object.entries(blocks).map(([type, def]) => [
567
+ type,
568
+ (Object.entries(def.fields) as [string, FieldDescriptor][]).filter(([, f]) => f.type === 'media').map(([k]) => k),
569
+ ]))
570
+ }
571
+
572
+ /** Every media id referenced by a stored blocks array (media fields, images in rich text, and both inside a block's lists). */
573
+ export function mediaIdsInBlocks(value: unknown, blocks: Record<string, BlockDef>, out: string[] = []): string[] {
574
+ if (!Array.isArray(value)) return out
575
+ for (const block of value as CmsBlock[]) {
576
+ if (!block || typeof block !== 'object') continue
577
+ const def = Object.hasOwn(blocks, block.type) ? blocks[block.type] : undefined
578
+ // A block we cannot read by its definition (its type is gone, or it is stored at an
579
+ // older shape): every id inside it counts, so its files are not deleted under it.
580
+ if (!def || storedBlockVersion(block) < blockVersion(def)) {
581
+ collectAnyMedia(block, out, true)
582
+ continue
583
+ }
584
+ mediaIdsInFields(def.fields, block, out)
585
+ }
586
+ return out
587
+ }
588
+
589
+ /** Every media id in the values of a set of fields (a block's, or a group's): media fields, images in rich text, lists and groups inside. */
590
+ export function mediaIdsInFields(fields: Record<string, AnyFieldDescriptor>, values: Record<string, any>, out: string[] = []): string[] {
591
+ for (const [key, fld] of Object.entries(fields) as [string, FieldDescriptor][]) {
592
+ const v = values[key]
593
+ if (fld.type === 'media' && typeof v === 'string' && v) out.push(v)
594
+ else if (fld.type === 'richtext') collectEmbedded(v, out)
595
+ else if (fld.type === 'blocks' && fld.blocks) mediaIdsInBlocks(v, fld.blocks, out)
596
+ else if (fld.type === 'group' && fld.fields && isPlainObject(v)) mediaIdsInFields(fld.fields, v, out)
597
+ }
598
+ return out
599
+ }
600
+
601
+ const UUID_LIKE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
602
+
603
+ /** Every media-looking id in a JSON value we have no definition for: uuid strings and rich-text `mediaId`s (not the block's own id). */
604
+ function collectAnyMedia(node: unknown, out: string[], top = false) {
605
+ if (typeof node === 'string') {
606
+ if (UUID_LIKE.test(node)) out.push(node)
607
+ }
608
+ else if (Array.isArray(node)) for (const child of node) collectAnyMedia(child, out)
609
+ else if (node && typeof node === 'object') {
610
+ for (const [k, v] of Object.entries(node)) {
611
+ if (top && (k === 'id' || k === 'type' || k === 'v')) continue
612
+ if (k === 'mediaId' && typeof v === 'string' && v) out.push(v)
613
+ else collectAnyMedia(v, out)
614
+ }
615
+ }
616
+ }
617
+
618
+ function collectEmbedded(doc: any, out: string[]) {
619
+ if (!doc || typeof doc !== 'object') return
620
+ if (typeof doc.attrs?.mediaId === 'string') out.push(doc.attrs.mediaId)
621
+ if (Array.isArray(doc.content)) for (const child of doc.content) collectEmbedded(child, out)
622
+ }
623
+
624
+ export type { FieldKind }
package/src/changes.ts ADDED
@@ -0,0 +1,54 @@
1
+ /**
2
+ * A content change, as the CMS reports it: to the other replicas, to the realtime
3
+ * hub, to the `cms:change` Nitro hook and (when public) to publish webhooks.
4
+ */
5
+ export type CmsChangeType =
6
+ | 'entry.created' | 'entry.updated' | 'entry.deleted' | 'entry.published' | 'entry.unpublished'
7
+ | 'translation.updated' | 'translation.deleted' | 'global.updated'
8
+
9
+ export interface CmsChange {
10
+ type: CmsChangeType
11
+ entity: string
12
+ id: string
13
+ /** The language a translation change is about; null for the entry itself. */
14
+ locale: string | null
15
+ /** Whether the change can be seen on the public website (live content of a public collection). */
16
+ public: boolean
17
+ /**
18
+ * Website addresses the change touches (from `content.path`), old and new — and, when
19
+ * the entry's address changed or it stopped being reachable, the addresses of the
20
+ * entries that link to it (their links read differently now).
21
+ */
22
+ paths: string[]
23
+ /**
24
+ * Public globals (menus, site settings) that link to this entry and read differently
25
+ * now, when its address changed or it stopped being reachable. Left out when none.
26
+ * Whatever shows them (a menu: every page) is stale.
27
+ */
28
+ globals?: string[]
29
+ /**
30
+ * Addresses that changed with this write (a page tree: the page and everything below it
31
+ * moved because a slug or a parent changed), old → new, per language. Absent when nothing
32
+ * moved. Every address in here is also in `paths`.
33
+ */
34
+ moved?: { id: string; locale: string | null; from: string; to: string }[]
35
+ /** Who made it (user id), when known. */
36
+ by: string | null
37
+ /** The entry's version after the change (its updatedAt, ISO), null when deleted. */
38
+ version: string | null
39
+ /** ISO timestamp. */
40
+ at: string
41
+ }
42
+
43
+ /**
44
+ * One address in the sitemap (`/sitemap.xml`, `/api/content/_sitemap`). The `cms:sitemap`
45
+ * Nitro hook gets the list and may push more: `loc` is the full address (language prefix
46
+ * included), `locale` its language (null without languages), `lastmod` an ISO date or
47
+ * null, `alternates` the same page in the other languages (hreflang), itself included.
48
+ */
49
+ export interface CmsSitemapEntry {
50
+ loc: string
51
+ locale: string | null
52
+ lastmod: string | null
53
+ alternates: { locale: string; loc: string }[]
54
+ }