tinyzoo 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (391) 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 +99 -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 +392 -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/cmsTooMany.ts +9 -0
  312. package/server/utils/cmsTranslationWrite.ts +186 -0
  313. package/server/utils/cmsTree.ts +251 -0
  314. package/server/utils/cmsTreeAddress.ts +65 -0
  315. package/server/utils/cmsUpload.ts +197 -0
  316. package/server/utils/cmsWebhooks.ts +101 -0
  317. package/shared/json.ts +11 -0
  318. package/shared/richtext-editor.ts +56 -0
  319. package/shared/richtext-normalize.ts +33 -0
  320. package/shared/richtext-paste.ts +151 -0
  321. package/shared/storage-delivery.ts +53 -0
  322. package/src/blocks.ts +624 -0
  323. package/src/changes.ts +54 -0
  324. package/src/content-shape.ts +340 -0
  325. package/src/deprecate.ts +64 -0
  326. package/src/descriptor.ts +149 -0
  327. package/src/docs.ts +27 -0
  328. package/src/emitter.ts +94 -0
  329. package/src/entity.ts +624 -0
  330. package/src/errorReport.ts +41 -0
  331. package/src/fields.ts +465 -0
  332. package/src/i18n.ts +26 -0
  333. package/src/index.ts +54 -0
  334. package/src/linkref.ts +31 -0
  335. package/src/links.ts +179 -0
  336. package/src/locales.ts +39 -0
  337. package/src/media.ts +48 -0
  338. package/src/migrate.ts +236 -0
  339. package/src/openapi.ts +377 -0
  340. package/src/paths.ts +88 -0
  341. package/src/plugin.ts +505 -0
  342. package/src/presets.ts +230 -0
  343. package/src/richtext.ts +88 -0
  344. package/src/sdk.ts +181 -0
  345. package/src/search.ts +312 -0
  346. package/src/seed.ts +225 -0
  347. package/src/setupCode.ts +30 -0
  348. package/src/system.ts +219 -0
  349. package/src/tree.ts +421 -0
  350. package/src/upgrades.ts +137 -0
  351. package/starter/.env.example +10 -0
  352. package/starter/README.md +65 -0
  353. package/starter/app/app.config.ts +10 -0
  354. package/starter/app/app.vue +12 -0
  355. package/starter/app/assets/css/main.css +15 -0
  356. package/starter/app/components/global/BlockContact.vue +15 -0
  357. package/starter/app/components/global/BlockCta.vue +15 -0
  358. package/starter/app/components/global/BlockHero.vue +23 -0
  359. package/starter/app/components/global/BlockImage.vue +13 -0
  360. package/starter/app/components/global/BlockText.vue +12 -0
  361. package/starter/app/composables/useSite.ts +77 -0
  362. package/starter/app/error.vue +28 -0
  363. package/starter/app/layouts/default.vue +106 -0
  364. package/starter/app/lib/cms-content.ts +152 -0
  365. package/starter/app/pages/[...slug].vue +66 -0
  366. package/starter/app/pages/hledat.vue +59 -0
  367. package/starter/app/pages/index.vue +20 -0
  368. package/starter/cms.config.ts +137 -0
  369. package/starter/compose.yaml +15 -0
  370. package/starter/drizzle.config.ts +8 -0
  371. package/starter/gitignore.txt +8 -0
  372. package/starter/nuxt.config.ts +13 -0
  373. package/starter/package.json +38 -0
  374. package/starter/scripts/typecheck.mjs +38 -0
  375. package/starter/seed/index.ts +297 -0
  376. package/starter/seed/media/about.jpg +0 -0
  377. package/starter/seed/media/hero.jpg +0 -0
  378. package/starter/seed/media/logo.png +0 -0
  379. package/starter/seed/media/news-bread.jpg +0 -0
  380. package/starter/seed/media/news-morning.jpg +0 -0
  381. package/starter/server/db/migrations/0000_init.sql +269 -0
  382. package/starter/server/db/migrations/0001_page_tree.sql +5 -0
  383. package/starter/server/db/migrations/0002_opening_hours_per_language.sql +1 -0
  384. package/starter/server/db/migrations/meta/0000_snapshot.json +1890 -0
  385. package/starter/server/db/migrations/meta/0001_snapshot.json +1887 -0
  386. package/starter/server/db/migrations/meta/0002_snapshot.json +1893 -0
  387. package/starter/server/db/migrations/meta/_journal.json +27 -0
  388. package/starter/server/db/schema.ts +253 -0
  389. package/starter/server/plugins/sitemap.ts +11 -0
  390. package/starter/server/routes/robots.txt.get.ts +12 -0
  391. package/starter/tsconfig.json +9 -0
@@ -0,0 +1,705 @@
1
+ /**
2
+ * The seed runner's core: what `s.create`, `s.upsert`, `s.translate`, `s.global` and
3
+ * `s.upload` do, written against a small `SeedBackend` (reads, writes, uploads) so it is
4
+ * the same logic whether the backend talks to a site over HTTP (`tinyzoo seed`, see
5
+ * seed.ts) or is a fake in a test.
6
+ *
7
+ * Rules the whole thing rests on:
8
+ *
9
+ * - An entry is recognised by a KEY (`by`: the address field by default). The entry's
10
+ * list is read once per entity; a key that is found is the same entry as last time.
11
+ * - Nothing is written that is already there. Before any update the stored values are
12
+ * read and compared with the seed's (`changedKeys`): only keys the seed gives are
13
+ * compared, extras the server added (a block's `v`, defaults) are ignored. A second run
14
+ * therefore makes no request that changes anything, and no new saved version appears.
15
+ * - Blocks and list items need an `id`; the seed may leave it out, and a stable one is
16
+ * made from where the block sits, so the same seed gives the same ids on every run.
17
+ * - With `apply: false` nothing is written (a dry run, and the scan `--reset` uses to
18
+ * learn which entries the seed owns); entries and files that do not exist yet get
19
+ * placeholder ids.
20
+ * - A link to an entry (`s.link`) is stored as the reference the admin's link picker
21
+ * stores (`cms:<entity>/<id>`), so a menu follows its page when the page is renamed
22
+ * or moved; only a placeholder id (a dry run) gets a readable address.
23
+ * - The seed owns an entry only when it can show it made it: created by the account the
24
+ * seed signs in with (and, for `s.create`, not changed by anybody else since), see
25
+ * `ownedBySeed`. `--reset` deletes owned entries only.
26
+ */
27
+ import { createHash } from 'node:crypto'
28
+ import { readFile } from 'node:fs/promises'
29
+ import { basename, extname, resolve } from 'node:path'
30
+ import { holdsLinks, linkFieldsOf, linkRef, linkRefsOf, mapFieldLinks, parseLinkRef, sitePath, type CmsEntity, type CmsRegistry } from '../src/index'
31
+ import { richBuilders, type SeedContext, type SeedDefinition, type SeedEntry, type SeedLink, type SeedLinkOptions, type SeedUploadOptions } from '../src/seed'
32
+
33
+ export type Row = Record<string, any>
34
+
35
+ export interface MediaRow {
36
+ id: string
37
+ name: string | null
38
+ folder: string | null
39
+ mime: string
40
+ size: number
41
+ url: string
42
+ alt: string | null
43
+ altLocales: Record<string, string> | null
44
+ focalX: number | null
45
+ focalY: number | null
46
+ }
47
+
48
+ export interface UploadRequest {
49
+ name: string
50
+ mime: string
51
+ data: Uint8Array
52
+ folder: string | null
53
+ library: boolean
54
+ }
55
+
56
+ /** What the engine needs from a site. Reads give the shapes the admin gets (relations as ids). */
57
+ export interface SeedBackend {
58
+ /** The id of the account the seed signs in as (null: unknown, so no entry can be shown to be the seed's own). */
59
+ account(): Promise<string | null>
60
+ /** Every entry of a collection (its own columns, `id` included). */
61
+ list(entity: string): Promise<Row[]>
62
+ /** One entry as the editor form gets it; in a translation language, its translated values (`__translated` says whether there are any). */
63
+ get(entity: string, id: string, locale?: string): Promise<Row | null>
64
+ create(entity: string, data: Row): Promise<Row>
65
+ update(entity: string, id: string, data: Row, locale?: string): Promise<Row>
66
+ remove(entity: string, id: string): Promise<void>
67
+ getGlobal(entity: string, locale?: string): Promise<Row | null>
68
+ putGlobal(entity: string, data: Row, locale?: string): Promise<Row>
69
+ /** The library file with this name, folder, size and type, if there is one. */
70
+ findMedia(query: { name: string; folder: string | null; size: number; mime: string }): Promise<MediaRow | null>
71
+ uploadMedia(file: UploadRequest): Promise<MediaRow>
72
+ patchMedia(id: string, details: { alt?: string | null; altLocales?: Record<string, string> | null; focal?: { x: number; y: number } | null }): Promise<MediaRow>
73
+ removeMedia(id: string): Promise<void>
74
+ }
75
+
76
+ export type SeedAction = 'created' | 'updated' | 'unchanged' | 'kept' | 'uploaded'
77
+
78
+ export interface SeedOp {
79
+ action: SeedAction
80
+ kind: 'entry' | 'translation' | 'global' | 'media'
81
+ /** Entity name (not for media). */
82
+ entity?: string
83
+ /** What a person calls it: `page home`, `news hello (en)`, `desk.jpg`. */
84
+ label: string
85
+ /** The keys that differ, for an update. */
86
+ fields?: string[]
87
+ }
88
+
89
+ /**
90
+ * What the seed owns on the site, in the order the seed declared it: entries found by key
91
+ * that the seed made (see `ownedBySeed`), and files found by name. Entries found by key
92
+ * that the seed did not make are `foreign`: `--reset` leaves them alone. A global cannot
93
+ * be deleted, the seed overwrites it; the ones it writes are `globals` (a menu of the seed
94
+ * is emptied of links to pages that are about to go).
95
+ */
96
+ export interface SeedDeclared {
97
+ entries: { entity: string; id: string; label: string }[]
98
+ media: { id: string; label: string }[]
99
+ foreign: { entity: string; id: string; label: string; why: string }[]
100
+ globals: { entity: string; label: string }[]
101
+ }
102
+
103
+ export interface SeedRunOptions {
104
+ reg: CmsRegistry
105
+ backend: SeedBackend
106
+ /** Seed file paths are relative to this folder (the site's root). */
107
+ root: string
108
+ /** False: read and plan only, write nothing. */
109
+ apply: boolean
110
+ /** Called for every step as it happens. */
111
+ onOp?: (op: SeedOp) => void
112
+ /** Reads an uploaded file; default: the disk. */
113
+ readFile?: (path: string) => Promise<Uint8Array>
114
+ }
115
+
116
+ export interface SeedRunResult {
117
+ ops: SeedOp[]
118
+ declared: SeedDeclared
119
+ }
120
+
121
+ const MIME: Record<string, string> = {
122
+ '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.gif': 'image/gif', '.webp': 'image/webp', '.avif': 'image/avif',
123
+ '.mp4': 'video/mp4', '.webm': 'video/webm', '.mp3': 'audio/mpeg', '.pdf': 'application/pdf',
124
+ }
125
+
126
+ const PLAN = 'plan:'
127
+ export const isPlaceholder = (id: string) => id.startsWith(PLAN)
128
+
129
+ /** A short stable id for a block or list item, from where it sits. */
130
+ export function stableId(scope: string): string {
131
+ return createHash('sha1').update(scope).digest('base64url').slice(0, 10)
132
+ }
133
+
134
+ // ── comparing what is stored with what the seed says ───────────────────────────
135
+
136
+ const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/
137
+
138
+ function sameInstant(a: unknown, b: unknown): boolean | null {
139
+ const asTime = (v: unknown) => (v instanceof Date ? v.getTime() : typeof v === 'string' && ISO.test(v) ? Date.parse(v) : null)
140
+ const ta = asTime(a)
141
+ const tb = asTime(b)
142
+ return ta === null || tb === null ? null : ta === tb
143
+ }
144
+
145
+ /**
146
+ * Does `stored` already say what `wanted` says? Only what the seed gives counts: an
147
+ * object is covered when every key of `wanted` is, extras in `stored` do not matter
148
+ * (the server adds `v` to blocks and fills defaults); an empty value (null, '', [])
149
+ * is covered by anything empty; arrays match item by item; dates by the instant;
150
+ * single-line text after the trimming the server does.
151
+ */
152
+ export function covers(stored: unknown, wanted: unknown): boolean {
153
+ if (wanted === undefined) return true
154
+ if (wanted === null || wanted === '' || (Array.isArray(wanted) && wanted.length === 0)) {
155
+ return stored === null || stored === undefined || stored === '' || (Array.isArray(stored) && stored.length === 0)
156
+ }
157
+ const instant = sameInstant(stored, wanted)
158
+ if (instant !== null) return instant
159
+ if (Array.isArray(wanted)) {
160
+ return Array.isArray(stored) && stored.length === wanted.length && wanted.every((w, i) => covers(stored[i], w))
161
+ }
162
+ if (typeof wanted === 'object') {
163
+ if (!stored || typeof stored !== 'object' || Array.isArray(stored)) return false
164
+ return Object.entries(wanted as Row).every(([k, v]) => covers((stored as Row)[k], v))
165
+ }
166
+ if (typeof wanted === 'string' && typeof stored === 'string') {
167
+ // A reference to an entry is the same wherever it is spelled (the id's case).
168
+ const a = parseLinkRef(stored)
169
+ const b = parseLinkRef(wanted)
170
+ if (a && b) return a.entity === b.entity && a.id === b.id
171
+ return stored === wanted || stored === wanted.trim()
172
+ }
173
+ return stored === wanted
174
+ }
175
+
176
+ /** The keys of `wanted` whose stored value differs (`many-to-many` lists compare as sets). */
177
+ export function changedKeys(stored: Row | null | undefined, wanted: Row, setKeys: ReadonlySet<string> = new Set()): string[] {
178
+ if (!stored) return Object.keys(wanted)
179
+ return Object.keys(wanted).filter((k) => {
180
+ const w = wanted[k]
181
+ if (setKeys.has(k) && Array.isArray(w) && Array.isArray(stored[k])) {
182
+ return !(w.length === stored[k].length && new Set(w).size === new Set(stored[k]).size && w.every((x) => stored[k].includes(x)))
183
+ }
184
+ return !covers(stored[k], w)
185
+ })
186
+ }
187
+
188
+ // ── preparing the seed's values ────────────────────────────────────────────────
189
+
190
+ const isEntryRef = (v: any): v is SeedEntry => !!v && typeof v === 'object' && typeof v.id === 'string' && typeof v.entity === 'string' && 'existed' in v && 'translations' in v
191
+
192
+ /** Plain JSON: dates as ISO strings, entries (given where an id is wanted) as their id. */
193
+ function jsonSafe(v: any): any {
194
+ if (v === undefined) return undefined
195
+ if (v instanceof Date) return v.toISOString()
196
+ if (isEntryRef(v)) return v.id
197
+ if (Array.isArray(v)) return v.map((x) => jsonSafe(x) ?? null)
198
+ if (v && typeof v === 'object') {
199
+ return Object.fromEntries(Object.entries(v).filter(([, x]) => x !== undefined).map(([k, x]) => [k, jsonSafe(x)]))
200
+ }
201
+ return v
202
+ }
203
+
204
+ /** Give every block and list item an `id` (and a single-type list its `type`), recursively through block fields. */
205
+ function withBlockIds(fld: any, value: unknown, scope: string): unknown {
206
+ if (!Array.isArray(value)) return value
207
+ const types = Object.keys(fld.blocks ?? {})
208
+ const seen = new Set<string>()
209
+ return value.map((raw, i) => {
210
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return raw
211
+ const block: Row = { ...raw }
212
+ if (!block.type && types.length === 1) block.type = types[0]
213
+ if (typeof block.id !== 'string' || !block.id || seen.has(block.id)) block.id = stableId(`${scope}/${i}/${block.type}/${block.id ?? ''}`)
214
+ seen.add(block.id)
215
+ const def = fld.blocks?.[block.type]
216
+ if (def) {
217
+ for (const [k, sub] of Object.entries<any>(def.fields)) {
218
+ if (sub.type === 'blocks' && Array.isArray(block[k])) block[k] = withBlockIds(sub, block[k], `${scope}/${i}/${k}`)
219
+ }
220
+ }
221
+ return block
222
+ })
223
+ }
224
+
225
+ /** Can a link point at an entry of this collection? (The server's rule: public, with an address on the website.) */
226
+ const isLinkable = (e: CmsEntity) => !e.singleton && !!e.content?.public && !!e.content?.path
227
+
228
+ const describe = (key: Record<string, string>) => Object.values(key).join(' / ')
229
+
230
+ export class SeedError extends Error {}
231
+
232
+ /** Run a seed definition against a backend. */
233
+ export async function runSeed(def: SeedDefinition, o: SeedRunOptions): Promise<SeedRunResult> {
234
+ const { reg, backend, apply } = o
235
+ const read = o.readFile ?? (async (p: string) => new Uint8Array(await readFile(p)))
236
+ const ops: SeedOp[] = []
237
+ const declared: SeedDeclared = { entries: [], media: [], foreign: [], globals: [] }
238
+ const lists = new Map<string, Promise<Row[]>>()
239
+ const handled = new Map<string, SeedEntry>()
240
+ const modes = new WeakMap<SeedEntry, 'create' | 'upsert'>()
241
+ const uploads = new Map<string, string>()
242
+ const mediaInfo = new Map<string, { url: string }>()
243
+ let placeholders = 0
244
+
245
+ const note = (op: SeedOp) => { ops.push(op); o.onOp?.(op) }
246
+ let account: Promise<string | null> | undefined
247
+ const me = () => (account ??= backend.account().catch(() => null))
248
+
249
+ /**
250
+ * Did the seed make this entry (so `--reset` may delete it)? Only an entry the seed's own
251
+ * account created counts: a page an editor made with the same slug is not the seed's, and
252
+ * neither is an entry made before the seed ran. After `s.create` the entry must also be
253
+ * untouched by anybody else (an editor's change is theirs, `create` leaves it alone);
254
+ * `s.upsert` takes the entry over, so later edits do not matter. Null: it is the seed's.
255
+ */
256
+ async function notOwned(row: Row, mode: 'create' | 'upsert'): Promise<string | null> {
257
+ const user = await me()
258
+ if (!user || !row.createdBy || row.createdBy !== user) return 'not made by the account the seed signs in with'
259
+ if (mode === 'create' && row.updatedBy && row.updatedBy !== user) return 'changed by someone else since'
260
+ return null
261
+ }
262
+ const locales = reg.locales
263
+ const defaultLocale = locales?.default ?? null
264
+
265
+ /** Wrap a failure with what the seed was doing. */
266
+ async function doing<T>(what: string, fn: () => Promise<T>): Promise<T> {
267
+ try { return await fn() }
268
+ catch (err) {
269
+ if (err instanceof SeedError) throw err
270
+ throw new SeedError(`${what}: ${err instanceof Error ? err.message : String(err)}`)
271
+ }
272
+ }
273
+
274
+ function entityOf(arg: unknown): CmsEntity {
275
+ const name = typeof arg === 'string' ? arg : (arg as any)?.name
276
+ const e = typeof name === 'string' ? reg.byName.get(name) : undefined
277
+ if (!e) {
278
+ throw new SeedError(`No content called ${JSON.stringify(typeof arg === 'string' ? arg : name)} in cms.config.ts (there is ${reg.entities.map((x) => x.name).join(', ')}).`)
279
+ }
280
+ return e
281
+ }
282
+
283
+ const listOf = (e: CmsEntity) => {
284
+ let p = lists.get(e.name)
285
+ if (!p) { p = backend.list(e.name); lists.set(e.name, p) }
286
+ return p
287
+ }
288
+
289
+ function keyFields(e: CmsEntity, by: string | string[] | undefined): string[] {
290
+ // Default key: the address field (`content.slug`), else the only slug field.
291
+ const slugs = Object.keys(e.fields).filter((k) => e.fields[k]!.type === 'slug')
292
+ const fields = by === undefined ? (e.content?.slug ? [e.content.slug] : slugs.length === 1 ? slugs : []) : Array.isArray(by) ? by : [by]
293
+ if (!fields.length) {
294
+ throw new SeedError(`${e.name}: tell the seed how to recognise this entry on a second run: { by: 'field' } (a field that is different for every entry, such as ${Object.keys(e.fields).find((k) => e.fields[k]!.isUnique) ?? e.titleField}).`)
295
+ }
296
+ for (const k of fields) {
297
+ const fld = e.fields[k]
298
+ if (!fld) throw new SeedError(`${e.name}: "by" names ${JSON.stringify(k)}, which is not a field (fields: ${Object.keys(e.fields).join(', ')}).`)
299
+ if (fld.relation || ['blocks', 'richtext', 'media', 'gallery'].includes(fld.type)) {
300
+ throw new SeedError(`${e.name}: "${k}" cannot be a key (it is ${fld.relation ? 'a relation' : fld.type}); use a text, address, number or choice field.`)
301
+ }
302
+ }
303
+ return fields
304
+ }
305
+
306
+ function checkFields(e: CmsEntity, data: Row, what: string) {
307
+ for (const k of Object.keys(data)) {
308
+ const fld = e.fields[k]
309
+ if (!fld) throw new SeedError(`${what}: ${e.name} has no field "${k}" (fields: ${Object.keys(e.fields).join(', ')}).`)
310
+ if (fld.relation?.kind === 'one-to-many') throw new SeedError(`${what}: "${k}" is the other side of a relation; set it on the entries that point here.`)
311
+ }
312
+ }
313
+
314
+ function prepare(e: CmsEntity, data: Row, scope: string, what: string, only?: string[]): Row {
315
+ if (!data || typeof data !== 'object' || Array.isArray(data)) throw new SeedError(`${what}: expected an object of values.`)
316
+ const out = jsonSafe(data) as Row
317
+ checkFields(e, out, what)
318
+ for (const k of Object.keys(out)) {
319
+ if (only && !only.includes(k)) continue
320
+ const fld = e.fields[k]!
321
+ if (fld.type === 'blocks') out[k] = withBlockIds(fld, out[k], `${scope}/${k}`)
322
+ }
323
+ return out
324
+ }
325
+
326
+ const setKeysOf = (e: CmsEntity) => new Set(Object.entries(e.fields).filter(([, f]) => f.relation?.kind === 'many-to-many').map(([k]) => k))
327
+ const planId = (e: string) => `${PLAN}${e}:${++placeholders}`
328
+
329
+ async function find(e: CmsEntity, key: Record<string, string>): Promise<Row | null> {
330
+ const rows = (await listOf(e)).filter((r) => Object.entries(key).every(([k, v]) => String(r[k] ?? '') === v))
331
+ if (rows.length > 1) throw new SeedError(`${e.name} ${describe(key)}: ${rows.length} entries have this key; the seed cannot tell which is meant.`)
332
+ return rows[0] ?? null
333
+ }
334
+
335
+ async function write(mode: 'create' | 'upsert', arg: unknown, data: Row, opts: { by?: string | string[]; translations?: Record<string, Row> } = {}): Promise<SeedEntry> {
336
+ const e = entityOf(arg)
337
+ if (e.singleton) throw new SeedError(`${e.name} is a global: use s.global(${JSON.stringify(e.name)}, { … }).`)
338
+ const fields = keyFields(e, opts.by)
339
+ const key: Record<string, string> = {}
340
+ for (const k of fields) {
341
+ const v = (data as Row)?.[k]
342
+ if (v === undefined || v === null || v === '') throw new SeedError(`${e.name}: the key field "${k}" needs a value in the seed.`)
343
+ key[k] = String(v)
344
+ }
345
+ const label = `${e.name} ${describe(key)}`
346
+ const hash = `${e.name}\0${JSON.stringify(key)}`
347
+ if (handled.has(hash)) throw new SeedError(`${label} is in the seed twice.`)
348
+ const wanted = prepare(e, data, `${e.name}/${describe(key)}`, label)
349
+ for (const k of fields) wanted[k] = (data as Row)[k] // as given (a number key stays a number)
350
+
351
+ const entry = await doing(label, async (): Promise<SeedEntry> => {
352
+ const existing = await find(e, key)
353
+ if (!existing) {
354
+ const row = apply ? await backend.create(e.name, wanted) : { id: planId(e.name) }
355
+ if (apply) (await listOf(e)).push(row)
356
+ else (await listOf(e)).push({ ...wanted, id: row.id })
357
+ note({ action: 'created', kind: 'entry', entity: e.name, label })
358
+ return { kind: 'entry', entity: e.name, id: row.id, key, existed: false, data: { ...wanted }, translations: {} }
359
+ }
360
+ if (!isPlaceholder(existing.id)) {
361
+ const why = await notOwned(existing, mode)
362
+ if (why) declared.foreign.push({ entity: e.name, id: existing.id, label, why })
363
+ else declared.entries.push({ entity: e.name, id: existing.id, label })
364
+ }
365
+ if (mode === 'create') {
366
+ note({ action: 'kept', kind: 'entry', entity: e.name, label })
367
+ return { kind: 'entry', entity: e.name, id: existing.id, key, existed: true, data: { ...existing, ...wanted }, translations: {} }
368
+ }
369
+ const stored = isPlaceholder(existing.id) ? null : await backend.get(e.name, existing.id)
370
+ const changed = changedKeys(stored, wanted, setKeysOf(e))
371
+ if (!changed.length && stored) note({ action: 'unchanged', kind: 'entry', entity: e.name, label })
372
+ else {
373
+ if (apply) await backend.update(e.name, existing.id, wanted)
374
+ note({ action: 'updated', kind: 'entry', entity: e.name, label, fields: changed })
375
+ }
376
+ return { kind: 'entry', entity: e.name, id: existing.id, key, existed: true, data: { ...stored, ...wanted }, translations: {} }
377
+ })
378
+ modes.set(entry, mode)
379
+ handled.set(hash, entry)
380
+ for (const [locale, tr] of Object.entries(opts.translations ?? {})) await translate(entry, locale, tr)
381
+ return entry
382
+ }
383
+
384
+ async function translate(entry: SeedEntry, locale: string, data: Row): Promise<void> {
385
+ const e = entityOf(entry.entity)
386
+ const label = `${e.name}${entry.kind === 'entry' ? ` ${describe(entry.key)}` : ''} (${locale})`
387
+ if (!locales) throw new SeedError(`${label}: the site has no languages (defineLocales in cms.config.ts).`)
388
+ if (locale === defaultLocale) throw new SeedError(`${label}: ${locale} is the default language; give those values to s.create / s.upsert / s.global itself.`)
389
+ if (!locales.locales.includes(locale)) throw new SeedError(`${label}: ${locale} is not one of the site's languages (${locales.locales.join(', ')}).`)
390
+ if (!e.localized.length) throw new SeedError(`${e.name} has nothing to translate (no field is .localized()).`)
391
+ const wrong = Object.keys(data ?? {}).filter((k) => !e.localized.includes(k))
392
+ if (wrong.length) throw new SeedError(`${label}: ${wrong.join(', ')} ${wrong.length > 1 ? 'are' : 'is'} not translated per language; translatable fields: ${e.localized.join(', ')}.`)
393
+ const scope = `${e.name}/${entry.kind === 'entry' ? describe(entry.key) : '-'}/${locale}`
394
+ const wanted = prepare(e, data, scope, label)
395
+ await doing(label, async () => {
396
+ const stored = isPlaceholder(entry.id) ? null
397
+ : entry.kind === 'global' ? await backend.getGlobal(e.name, locale) : await backend.get(e.name, entry.id, locale)
398
+ const translated = !!stored?.__translated
399
+ if (modes.get(entry) === 'create' && translated) {
400
+ note({ action: 'kept', kind: 'translation', entity: e.name, label })
401
+ return
402
+ }
403
+ const changed = changedKeys(translated ? stored : null, wanted)
404
+ if (!changed.length) { note({ action: 'unchanged', kind: 'translation', entity: e.name, label }); return }
405
+ if (apply) {
406
+ if (entry.kind === 'global') await backend.putGlobal(e.name, wanted, locale)
407
+ else await backend.update(e.name, entry.id, wanted, locale)
408
+ }
409
+ note({ action: translated ? 'updated' : 'created', kind: 'translation', entity: e.name, label, fields: changed })
410
+ })
411
+ ;(entry.translations as Record<string, Row>)[locale] = wanted
412
+ }
413
+
414
+ async function global(arg: unknown, data: Row, opts: { translations?: Record<string, Row>; ifMissing?: boolean } = {}): Promise<SeedEntry> {
415
+ const e = entityOf(arg)
416
+ if (!e.singleton) throw new SeedError(`${e.name} is a collection: use s.create / s.upsert.`)
417
+ const label = `${e.name}`
418
+ if (handled.has(e.name)) throw new SeedError(`${label} is in the seed twice.`)
419
+ const wanted = prepare(e, data, e.name, label)
420
+ if (!opts.ifMissing) declared.globals.push({ entity: e.name, label })
421
+ const entry = await doing(label, async (): Promise<SeedEntry> => {
422
+ const stored = await backend.getGlobal(e.name)
423
+ const id = stored?.id ?? (apply ? '' : planId(e.name))
424
+ if (stored && opts.ifMissing) {
425
+ note({ action: 'kept', kind: 'global', entity: e.name, label })
426
+ return { kind: 'global', entity: e.name, id: stored.id, key: {}, existed: true, data: { ...stored, ...wanted }, translations: {} }
427
+ }
428
+ const changed = changedKeys(stored, wanted, setKeysOf(e))
429
+ if (stored && !changed.length) note({ action: 'unchanged', kind: 'global', entity: e.name, label })
430
+ else {
431
+ const saved = apply ? await backend.putGlobal(e.name, wanted) : null
432
+ note({ action: stored ? 'updated' : 'created', kind: 'global', entity: e.name, label, fields: changed })
433
+ return { kind: 'global', entity: e.name, id: saved?.id ?? id, key: {}, existed: !!stored, data: { ...stored, ...wanted }, translations: {} }
434
+ }
435
+ return { kind: 'global', entity: e.name, id, key: {}, existed: true, data: { ...stored, ...wanted }, translations: {} }
436
+ })
437
+ modes.set(entry, opts.ifMissing ? 'create' : 'upsert')
438
+ handled.set(e.name, entry)
439
+ for (const [locale, tr] of Object.entries(opts.translations ?? {})) await translate(entry, locale, tr)
440
+ return entry
441
+ }
442
+
443
+ async function upload(file: string, opts: SeedUploadOptions = {}): Promise<string> {
444
+ const path = resolve(o.root, file)
445
+ const name = opts.name ?? basename(path)
446
+ const folder = opts.folder ?? null
447
+ const cacheKey = `${path}\0${name}\0${folder}`
448
+ const cached = uploads.get(cacheKey)
449
+ if (cached) return cached
450
+ const mime = opts.mime ?? MIME[extname(path).toLowerCase()]
451
+ if (!mime) throw new SeedError(`${file}: cannot tell the file type from its name; pass { mime: 'image/jpeg' }.`)
452
+ const label = file
453
+ return doing(label, async () => {
454
+ let data: Uint8Array
455
+ try { data = await read(path) }
456
+ catch { throw new SeedError(`${file}: no such file (looked for ${path}).`) }
457
+ const found = await backend.findMedia({ name, folder, size: data.byteLength, mime })
458
+ const details: Parameters<SeedBackend['patchMedia']>[1] = {}
459
+ if (found) {
460
+ if (opts.alt !== undefined && (found.alt ?? '') !== opts.alt) details.alt = opts.alt
461
+ if (opts.altLocales && !covers(found.altLocales, opts.altLocales)) details.altLocales = opts.altLocales
462
+ if (opts.focal && (found.focalX !== Math.round(opts.focal.x) || found.focalY !== Math.round(opts.focal.y))) details.focal = opts.focal
463
+ declared.media.push({ id: found.id, label })
464
+ if (Object.keys(details).length) {
465
+ if (apply) await backend.patchMedia(found.id, details)
466
+ note({ action: 'updated', kind: 'media', label, fields: Object.keys(details) })
467
+ }
468
+ else note({ action: 'unchanged', kind: 'media', label })
469
+ uploads.set(cacheKey, found.id)
470
+ mediaInfo.set(found.id, { url: found.url })
471
+ return found.id
472
+ }
473
+ let row: MediaRow | null = null
474
+ if (apply) {
475
+ row = await backend.uploadMedia({ name, mime, data, folder, library: opts.library ?? true })
476
+ const extra: Parameters<SeedBackend['patchMedia']>[1] = {}
477
+ if (opts.alt !== undefined) extra.alt = opts.alt
478
+ if (opts.altLocales) extra.altLocales = opts.altLocales
479
+ if (opts.focal) extra.focal = opts.focal
480
+ if (Object.keys(extra).length) row = await backend.patchMedia(row.id, extra)
481
+ }
482
+ const id = row?.id ?? planId('media')
483
+ note({ action: 'uploaded', kind: 'media', label })
484
+ uploads.set(cacheKey, id)
485
+ mediaInfo.set(id, { url: row?.url ?? `/plan/${name}` })
486
+ return id
487
+ })
488
+ }
489
+
490
+ function link(label: string, to: string | SeedEntry, opts: SeedLinkOptions = {}): SeedLink {
491
+ let url: string
492
+ if (typeof to === 'string') url = to
493
+ else {
494
+ const e = entityOf(to.entity)
495
+ if (!e.content?.path) throw new SeedError(`s.link(${JSON.stringify(label)}): ${e.name} has no address on the website (content.path in cms.config.ts); pass an address instead.`)
496
+ // A page the website can link to is stored as a reference, as the admin's link picker
497
+ // does: the link follows the page (renamed, moved under another page, translated).
498
+ const ref = linkRef(e.name, to.id)
499
+ if (isLinkable(e) && !isPlaceholder(to.id) && parseLinkRef(ref)) url = ref
500
+ else {
501
+ // Nothing to refer to yet (a dry run plans an entry without an id), or an entity the
502
+ // website does not link to: a readable address, worked out here.
503
+ const locale = opts.locale ?? defaultLocale
504
+ const values = { ...to.data, ...(locale && locale !== defaultLocale ? to.translations[locale] : {}) }
505
+ const address = sitePath(locales, e.content.path, locale, values)
506
+ if (!address) throw new SeedError(`s.link(${JSON.stringify(label)}): ${e.name} has no address on the website${locale ? ` in ${locale}` : ''} (a value for each :placeholder of content.path); pass an address instead.`)
507
+ url = address
508
+ }
509
+ }
510
+ return { id: stableId(`link/${label}/${url}`), type: 'link', label, url, newTab: opts.newTab ?? false, sub: opts.sub ?? false }
511
+ }
512
+
513
+ const s: SeedContext = {
514
+ create: ((entity: unknown, data: Row, opts?: any) => write('create', entity, data, opts)) as SeedContext['create'],
515
+ upsert: ((entity: unknown, data: Row, opts?: any) => write('upsert', entity, data, opts)) as SeedContext['upsert'],
516
+ translate: (entry, locale, data) => translate(entry, locale, data),
517
+ global: ((entity: unknown, data: Row, opts?: any) => global(entity, data, opts)) as SeedContext['global'],
518
+ upload,
519
+ link,
520
+ rich: richBuilders((id) => mediaInfo.get(id)?.url ?? ''),
521
+ locales: locales ? [locales.default, ...locales.locales.filter((l) => l !== locales.default)] : [],
522
+ }
523
+ await def.run(s)
524
+ return { ops, declared }
525
+ }
526
+
527
+ // ── --reset ─────────────────────────────────────────────────────────────────────
528
+
529
+ export interface ResetPlan {
530
+ /** What goes, in the order to delete it: an entry that links to or points at another goes before it. */
531
+ entries: { entity: string; id: string; label: string }[]
532
+ media: { id: string; label: string }[]
533
+ /** Globals of the seed that link to entries about to go: saved first without those links (the seed writes them again afterwards). */
534
+ clear: { entity: string; label: string; locale: string | null; data: Row }[]
535
+ /** Found by the seed's keys but not made by the seed: they stay. */
536
+ kept: { label: string; why: string }[]
537
+ /** Why a delete would be refused. While there is any, nothing at all is removed. */
538
+ blocked: string[]
539
+ }
540
+
541
+ export interface ResetResult { entries: number; media: number; keptMedia: number; cleared: number }
542
+
543
+ const refKey = (entity: string, id: string) => `${entity}/${id.toLowerCase()}`
544
+
545
+ /**
546
+ * Work out a reset before touching anything: which entries go and in which order, which
547
+ * globals first lose their links to them, and whether anything would be refused. The site
548
+ * refuses to delete an entry that a menu, a page or a relation still points at (409), and
549
+ * a reset over HTTP has no transaction to undo a half-way stop, so every reason is looked
550
+ * for here: a link in a global or entry (translations included), a relation (the tree's
551
+ * parent too). Whatever the seed owns itself is ordered or cleared; anything else is a
552
+ * blocker, reported with what to change.
553
+ */
554
+ export async function planReset(reg: CmsRegistry, backend: SeedBackend, declared: SeedDeclared): Promise<ResetPlan> {
555
+ const plan: ResetPlan = {
556
+ entries: [], media: [...declared.media].reverse(), clear: [],
557
+ kept: declared.foreign.map((x) => ({ label: x.label, why: x.why })), blocked: [],
558
+ }
559
+ const owned = new Map(declared.entries.filter((x) => !isPlaceholder(x.id)).map((x) => [refKey(x.entity, x.id), x]))
560
+ if (!owned.size) return plan
561
+ const ownedEntities = new Set([...owned.values()].map((x) => x.entity))
562
+ const before = new Map<string, Set<string>>() // entry → the owned entries that must go before it
563
+ const isOwnedRef = (v: string) => { const r = parseLinkRef(v); return !!r && owned.has(refKey(r.entity, r.id)) }
564
+ const dropped = (v: string) => (isOwnedRef(v) ? null : undefined)
565
+ const visitor = { field: dropped, mark: dropped }
566
+ const localesList = reg.locales ? reg.locales.locales.filter((l) => l !== reg.locales!.default) : []
567
+
568
+ for (const e of reg.entities) {
569
+ const linkKeys = linkFieldsOf(e.fields as any).map(([k]) => k)
570
+ const relations = Object.entries(e.fields).filter(([, f]) => (f.relation?.kind === 'many-to-one' || f.relation?.kind === 'many-to-many') && ownedEntities.has(f.relation.to().name))
571
+ if (!linkKeys.length && !relations.length) continue
572
+
573
+ if (e.singleton) {
574
+ for (const [k] of relations) plan.blocked.push(`${e.name} has a relation (${k}) to content the seed would remove; empty it first.`)
575
+ if (!linkKeys.length) continue
576
+ const mine = declared.globals.some((g) => g.entity === e.name)
577
+ for (const locale of [null, ...localesList]) {
578
+ const keys = locale ? linkKeys.filter((k) => e.localized.includes(k)) : linkKeys
579
+ if (!keys.length) continue
580
+ const row = await backend.getGlobal(e.name, locale ?? undefined)
581
+ if (!row || (locale && !row.__translated)) continue
582
+ const fields = Object.fromEntries(keys.map((k) => [k, e.fields[k]!]))
583
+ const hits = [...linkRefsOf(fields as any, row)].filter(isOwnedRef)
584
+ if (!hits.length) continue
585
+ const label = `${e.name}${locale ? ` (${locale})` : ''}`
586
+ if (!mine) { plan.blocked.push(`${label} links to ${hits.map((h) => owned.get(refKey(parseLinkRef(h)!.entity, parseLinkRef(h)!.id))!.label).join(', ')}, which the seed would remove, and the seed does not write it (it is left as it is: ifMissing); take those links out first.`); continue }
587
+ // Saved as the seed saves it: the whole global (the translated fields only, in a translation), without the links.
588
+ const sendKeys = locale ? e.localized : Object.keys(e.fields)
589
+ const data: Row = {}
590
+ for (const k of sendKeys) {
591
+ if (row[k] === undefined) continue
592
+ const fld = e.fields[k] as any
593
+ data[k] = holdsLinks(fld) ? withoutOwnedLinks(fld, row[k], visitor, isOwnedRef) : row[k]
594
+ }
595
+ plan.clear.push({ entity: e.name, label, locale, data })
596
+ }
597
+ continue
598
+ }
599
+
600
+ const rows = await backend.list(e.name)
601
+ const translatedLinks = !!localesList.length && linkKeys.some((k) => e.localized.includes(k))
602
+ for (const row of rows) {
603
+ const self = refKey(e.name, row.id)
604
+ const mine = owned.has(self)
605
+ const found = (target: string, how: string) => {
606
+ if (target === self) return
607
+ if (mine) { if (!before.has(target)) before.set(target, new Set()); before.get(target)!.add(self) }
608
+ else plan.blocked.push(`${e.name} ${row[e.titleField] ?? row.id} (not made by the seed) ${how} ${owned.get(target)!.label}, which the seed would remove; change that first.`)
609
+ }
610
+ const refs = linkRefsOf(Object.fromEntries(linkKeys.map((k) => [k, e.fields[k]!])) as any, row)
611
+ if (translatedLinks) {
612
+ const keys = linkKeys.filter((k) => e.localized.includes(k))
613
+ for (const locale of localesList) {
614
+ const tr = await backend.get(e.name, row.id, locale)
615
+ if (tr?.__translated) linkRefsOf(Object.fromEntries(keys.map((k) => [k, e.fields[k]!])) as any, tr, refs)
616
+ }
617
+ }
618
+ for (const ref of refs) {
619
+ const r = parseLinkRef(ref)
620
+ if (r && owned.has(refKey(r.entity, r.id))) found(refKey(r.entity, r.id), 'links to')
621
+ }
622
+ let form: Row | null | undefined
623
+ for (const [k, f] of relations) {
624
+ let v = row[k] ?? row[`${k}Id`]
625
+ if (v === undefined && f.relation!.kind === 'many-to-many') v = (form ??= await backend.get(e.name, row.id))?.[k]
626
+ const target = f.relation!.to().name
627
+ for (const id of ([] as unknown[]).concat(v ?? [])) {
628
+ if (typeof id === 'string' && owned.has(refKey(target, id))) found(refKey(target, id), `relates (${k}) to`)
629
+ }
630
+ }
631
+ }
632
+ }
633
+
634
+ // Entries that point at others go first; otherwise last declared goes first (as before).
635
+ const left = [...declared.entries].reverse().filter((x) => owned.has(refKey(x.entity, x.id)))
636
+ const gone = new Set<string>()
637
+ while (left.length) {
638
+ const i = left.findIndex((x) => [...(before.get(refKey(x.entity, x.id)) ?? [])].every((k) => gone.has(k)))
639
+ if (i < 0) {
640
+ plan.blocked.push(`These link to or point at each other, so none can go first: ${left.map((x) => x.label).join(', ')}.`)
641
+ break
642
+ }
643
+ const [x] = left.splice(i, 1)
644
+ gone.add(refKey(x!.entity, x!.id))
645
+ plan.entries.push(x!)
646
+ }
647
+ return plan
648
+ }
649
+
650
+ /** A field's value without the links to owned entries: a list item that holds one is dropped, a lone link is emptied, a rich-text link keeps its words. */
651
+ function withoutOwnedLinks(fld: any, value: unknown, visitor: { field: (v: string) => null | undefined; mark: (v: string) => null | undefined }, isOwnedRef: (v: string) => boolean): unknown {
652
+ if (fld.type === 'blocks' && fld.blocks && Array.isArray(value)) {
653
+ return value.filter((b: any) => {
654
+ const def = fld.blocks[b?.type]
655
+ return !def || ![...linkRefsOf(def.fields, b)].some(isOwnedRef)
656
+ })
657
+ }
658
+ return mapFieldLinks(fld, value, visitor)
659
+ }
660
+
661
+ /** What a plan says goes, as lines a person can read before agreeing to it. */
662
+ export function describeReset(plan: ResetPlan, where: string): string[] {
663
+ const out: string[] = []
664
+ if (plan.entries.length) out.push(` ${plan.entries.length === 1 ? 'Entry' : 'Entries'} that would be removed from ${where}, in this order:`, ...plan.entries.map((x) => ` − ${x.label}`))
665
+ if (plan.media.length) out.push(' Files (a file still in use stays):', ...plan.media.map((m) => ` − ${m.label}`))
666
+ if (plan.clear.length) out.push(' Menus and settings first lose their links to those entries (the seed writes them again):', ...plan.clear.map((c) => ` ~ ${c.label}`))
667
+ if (plan.kept.length) out.push(' Found by the seed\'s keys but not made by the seed, so they stay:', ...plan.kept.map((k) => ` · ${k.label} (${k.why})`))
668
+ if (plan.blocked.length) out.push(' Cannot be removed as things are:', ...plan.blocked.map((b) => ` ! ${b}`))
669
+ return out
670
+ }
671
+
672
+ /**
673
+ * Carry out a plan (see `planReset`). A plan with anything blocked is refused before the
674
+ * first write. Over HTTP there is no transaction: if a step still fails (somebody saved
675
+ * something in between), it stops there and says what was already done; the seed puts
676
+ * the rest back on its next run. Files still in use stay (the seed finds and reuses them).
677
+ */
678
+ export async function resetDeclared(backend: SeedBackend, plan: ResetPlan, log: (line: string) => void = () => {}): Promise<ResetResult> {
679
+ if (plan.blocked.length) throw new SeedError(`Nothing was removed. --reset cannot go through:\n${plan.blocked.map((b) => ` ! ${b}`).join('\n')}`)
680
+ const out: ResetResult = { entries: 0, media: 0, keptMedia: 0, cleared: 0 }
681
+ const partway = () => (out.entries || out.cleared ? ` Stopped part-way (${out.cleared} menus cleared, ${out.entries} entries removed); run the seed again to put it all back.` : ' Nothing was removed.')
682
+ for (const c of plan.clear) {
683
+ try { await backend.putGlobal(c.entity, c.data, c.locale ?? undefined); out.cleared++ }
684
+ catch (err) { throw new SeedError(`${c.label}: could not take the links out (${err instanceof Error ? err.message : String(err)}).${partway()}`) }
685
+ log(` ~ ${c.label}: links to removed entries taken out`)
686
+ }
687
+ for (const x of plan.entries) {
688
+ if (isPlaceholder(x.id)) continue
689
+ try { await backend.remove(x.entity, x.id); out.entries++ }
690
+ catch (err) {
691
+ if ((err as any)?.status === 404) continue
692
+ throw new SeedError(`${x.label}: could not be removed (${err instanceof Error ? err.message : String(err)}).${partway()}`)
693
+ }
694
+ log(` − ${x.label}`)
695
+ }
696
+ for (const m of plan.media) {
697
+ try { await backend.removeMedia(m.id); out.media++; log(` − ${m.label}`) }
698
+ catch (err) {
699
+ if ((err as any)?.status === 404) continue
700
+ out.keptMedia++
701
+ log(` · ${m.label} stays (${err instanceof Error ? err.message : String(err)})`)
702
+ }
703
+ }
704
+ return out
705
+ }