tinyzoo 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (392) hide show
  1. package/LICENSE +10 -0
  2. package/README.md +46 -2
  3. package/app/app.config.ts +35 -0
  4. package/app/assets/brand/characters/bright/bird.svg +1 -0
  5. package/app/assets/brand/characters/bright/bunny.svg +1 -0
  6. package/app/assets/brand/characters/bright/elephant.svg +1 -0
  7. package/app/assets/brand/characters/bright/fox.svg +1 -0
  8. package/app/assets/brand/characters/bright/frog.svg +1 -0
  9. package/app/assets/brand/characters/bright/octopus.svg +1 -0
  10. package/app/assets/brand/characters/muted/bee.svg +1 -0
  11. package/app/assets/brand/characters/muted/bird.svg +1 -0
  12. package/app/assets/brand/characters/muted/butterfly.svg +1 -0
  13. package/app/assets/brand/characters/muted/chick.svg +1 -0
  14. package/app/assets/brand/characters/muted/cow.svg +1 -0
  15. package/app/assets/brand/characters/muted/deer.svg +1 -0
  16. package/app/assets/brand/characters/muted/duck.svg +1 -0
  17. package/app/assets/brand/characters/muted/elephant.svg +1 -0
  18. package/app/assets/brand/characters/muted/fox.svg +1 -0
  19. package/app/assets/brand/characters/muted/hedgehog.svg +1 -0
  20. package/app/assets/brand/characters/muted/koala.svg +1 -0
  21. package/app/assets/brand/characters/muted/ladybug.svg +1 -0
  22. package/app/assets/brand/characters/muted/lion.svg +1 -0
  23. package/app/assets/brand/characters/muted/mouse.svg +1 -0
  24. package/app/assets/brand/characters/muted/octopus.svg +1 -0
  25. package/app/assets/brand/characters/muted/owl.svg +1 -0
  26. package/app/assets/brand/characters/muted/panda.svg +1 -0
  27. package/app/assets/brand/characters/muted/penguin.svg +1 -0
  28. package/app/assets/brand/characters/muted/pig.svg +1 -0
  29. package/app/assets/brand/characters/muted/poodle.svg +1 -0
  30. package/app/assets/brand/characters/muted/raccoon.svg +1 -0
  31. package/app/assets/brand/characters/muted/seal.svg +1 -0
  32. package/app/assets/brand/characters/muted/sheep.svg +1 -0
  33. package/app/assets/brand/characters/muted/snail.svg +1 -0
  34. package/app/assets/brand/characters/muted/turtle.svg +1 -0
  35. package/app/assets/brand/characters/muted/whale.svg +1 -0
  36. package/app/assets/brand/logo/favicon.svg +1 -0
  37. package/app/assets/brand/logo/logo-primary-reversed.svg +1 -0
  38. package/app/assets/brand/logo/logo-primary.svg +1 -0
  39. package/app/assets/brand/logo/mascot-reversed.svg +1 -0
  40. package/app/assets/brand/logo/mascot.svg +1 -0
  41. package/app/assets/brand/logo/wordmark-reversed.svg +1 -0
  42. package/app/assets/brand/logo/wordmark.svg +1 -0
  43. package/app/assets/css/cms-admin.css +607 -0
  44. package/app/components/CmsBlocks.vue +30 -0
  45. package/app/components/CmsCell.vue +16 -0
  46. package/app/components/CmsCellBadge.vue +18 -0
  47. package/app/components/CmsCellBlocks.vue +9 -0
  48. package/app/components/CmsCellBoolean.vue +12 -0
  49. package/app/components/CmsCellCode.vue +7 -0
  50. package/app/components/CmsCellColor.vue +13 -0
  51. package/app/components/CmsCellDate.vue +10 -0
  52. package/app/components/CmsCellExcerpt.vue +21 -0
  53. package/app/components/CmsCellGallery.vue +10 -0
  54. package/app/components/CmsCellGroup.vue +23 -0
  55. package/app/components/CmsCellNumber.vue +7 -0
  56. package/app/components/CmsCellRelation.vue +8 -0
  57. package/app/components/CmsCellText.vue +12 -0
  58. package/app/components/CmsCellThumb.vue +18 -0
  59. package/app/components/CmsConfirmDialog.vue +55 -0
  60. package/app/components/CmsContent.vue +103 -0
  61. package/app/components/CmsDayPicker.vue +44 -0
  62. package/app/components/CmsEmptyState.vue +35 -0
  63. package/app/components/CmsField.vue +111 -0
  64. package/app/components/CmsFieldBlocks.vue +353 -0
  65. package/app/components/CmsFieldBoolean.vue +8 -0
  66. package/app/components/CmsFieldColor.vue +42 -0
  67. package/app/components/CmsFieldDate.vue +131 -0
  68. package/app/components/CmsFieldGallery.vue +114 -0
  69. package/app/components/CmsFieldGroup.vue +53 -0
  70. package/app/components/CmsFieldMedia.vue +219 -0
  71. package/app/components/CmsFieldNumber.vue +11 -0
  72. package/app/components/CmsFieldRelationMany.vue +54 -0
  73. package/app/components/CmsFieldRelationOne.vue +47 -0
  74. package/app/components/CmsFieldRichText.vue +45 -0
  75. package/app/components/CmsFieldSelect.vue +41 -0
  76. package/app/components/CmsFieldSlug.vue +46 -0
  77. package/app/components/CmsFieldText.vue +75 -0
  78. package/app/components/CmsFormSections.vue +150 -0
  79. package/app/components/CmsHighlight.vue +22 -0
  80. package/app/components/CmsImage.vue +39 -0
  81. package/app/components/CmsLinkPicker.vue +122 -0
  82. package/app/components/CmsLinkTarget.vue +35 -0
  83. package/app/components/CmsListFilters.vue +107 -0
  84. package/app/components/CmsLiveNotice.vue +64 -0
  85. package/app/components/CmsLoadError.vue +24 -0
  86. package/app/components/CmsMascot.vue +10 -0
  87. package/app/components/CmsMediaLibrary.vue +114 -0
  88. package/app/components/CmsMediaPreview.vue +34 -0
  89. package/app/components/CmsMediaThumb.vue +22 -0
  90. package/app/components/CmsMoment.vue +42 -0
  91. package/app/components/CmsNav.vue +39 -0
  92. package/app/components/CmsPage.vue +86 -0
  93. package/app/components/CmsPasswordInput.vue +22 -0
  94. package/app/components/CmsPresence.vue +29 -0
  95. package/app/components/CmsPreviewPanel.vue +131 -0
  96. package/app/components/CmsPublishReview.vue +102 -0
  97. package/app/components/CmsRevisions.vue +195 -0
  98. package/app/components/CmsRichTextEditor.vue +290 -0
  99. package/app/components/CmsSearch.vue +99 -0
  100. package/app/components/CmsSection.vue +20 -0
  101. package/app/components/CmsSingletonForm.vue +283 -0
  102. package/app/components/CmsStatusBadge.vue +21 -0
  103. package/app/components/CmsTime.vue +16 -0
  104. package/app/components/CmsTranslationRef.vue +27 -0
  105. package/app/components/CmsTreeList.vue +453 -0
  106. package/app/components/CmsUnsavedText.vue +34 -0
  107. package/app/components/CmsWordmark.vue +10 -0
  108. package/app/composables/useCmsAdminHead.ts +18 -0
  109. package/app/composables/useCmsCollab.ts +165 -0
  110. package/app/composables/useCmsConfirm.ts +39 -0
  111. package/app/composables/useCmsEntryActions.ts +75 -0
  112. package/app/composables/useCmsFocus.ts +13 -0
  113. package/app/composables/useCmsForm.ts +273 -0
  114. package/app/composables/useCmsI18n.ts +185 -0
  115. package/app/composables/useCmsLinkTargets.ts +84 -0
  116. package/app/composables/useCmsLive.ts +199 -0
  117. package/app/composables/useCmsSearch.ts +62 -0
  118. package/app/composables/useCmsSeo.ts +99 -0
  119. package/app/composables/useCmsSignedIn.ts +24 -0
  120. package/app/composables/useCmsUiLocale.ts +24 -0
  121. package/app/i18n/cs.ts +781 -0
  122. package/app/i18n/de.ts +781 -0
  123. package/app/i18n/en.ts +782 -0
  124. package/app/i18n/types.ts +22 -0
  125. package/app/layouts/admin.vue +224 -0
  126. package/app/layouts/cms-auth.vue +37 -0
  127. package/app/middleware/cms-api-not-a-page.global.ts +10 -0
  128. package/app/middleware/cms-auth.global.ts +16 -0
  129. package/app/pages/admin/[entity]/[id].vue +1109 -0
  130. package/app/pages/admin/[entity]/index.vue +733 -0
  131. package/app/pages/admin/account.vue +117 -0
  132. package/app/pages/admin/forgot.vue +50 -0
  133. package/app/pages/admin/index.vue +184 -0
  134. package/app/pages/admin/invite/[token].vue +73 -0
  135. package/app/pages/admin/login.vue +84 -0
  136. package/app/pages/admin/media.vue +494 -0
  137. package/app/pages/admin/privacy.vue +193 -0
  138. package/app/pages/admin/reset/[token].vue +52 -0
  139. package/app/pages/admin/setup.vue +87 -0
  140. package/app/pages/admin/styleguide.vue +261 -0
  141. package/app/pages/admin/team.vue +258 -0
  142. package/app/plugins/cmsLivePreview.client.ts +20 -0
  143. package/app/plugins/cmsSignedOut.client.ts +31 -0
  144. package/app/utils/cmsBlockType.ts +11 -0
  145. package/app/utils/cmsBrand.ts +38 -0
  146. package/app/utils/cmsDiff.ts +83 -0
  147. package/app/utils/cmsFetch.ts +7 -0
  148. package/app/utils/cmsFocusInvalid.ts +22 -0
  149. package/app/utils/cmsIssues.ts +128 -0
  150. package/app/utils/cmsJson.ts +28 -0
  151. package/app/utils/cmsMedia.ts +63 -0
  152. package/app/utils/cmsSections.ts +154 -0
  153. package/app/utils/cmsTime.ts +41 -0
  154. package/cli/backup.ts +713 -0
  155. package/cli/breaking.ts +174 -0
  156. package/cli/content-migrate.ts +239 -0
  157. package/cli/db.ts +86 -0
  158. package/cli/export.ts +336 -0
  159. package/cli/generate.ts +146 -0
  160. package/cli/import.ts +643 -0
  161. package/cli/index.ts +140 -0
  162. package/cli/links-convert.ts +291 -0
  163. package/cli/seed-engine.ts +705 -0
  164. package/cli/seed.ts +339 -0
  165. package/cli/status.ts +49 -0
  166. package/cli/tar.ts +304 -0
  167. package/cli/transfer.ts +677 -0
  168. package/cli/up.ts +27 -0
  169. package/cli/upgrade.ts +60 -0
  170. package/cli/versions.ts +60 -0
  171. package/forms/components/CmsForm.vue +186 -0
  172. package/forms/index.ts +203 -0
  173. package/forms/messages.ts +104 -0
  174. package/forms/retention.ts +48 -0
  175. package/forms/server/form.get.ts +12 -0
  176. package/forms/server/form.post.ts +109 -0
  177. package/forms/server/formSettings.ts +12 -0
  178. package/forms/server/forms.ts +127 -0
  179. package/module.ts +373 -0
  180. package/nuxt.config.ts +43 -0
  181. package/package.json +98 -3
  182. package/server/api/cms/[entity]/[id]/revisions/[rev].get.ts +19 -0
  183. package/server/api/cms/[entity]/[id]/revisions/index.get.ts +14 -0
  184. package/server/api/cms/[entity]/[id].delete.ts +52 -0
  185. package/server/api/cms/[entity]/[id].get.ts +21 -0
  186. package/server/api/cms/[entity]/[id].patch.ts +116 -0
  187. package/server/api/cms/[entity]/_export.get.ts +69 -0
  188. package/server/api/cms/[entity]/_move.post.ts +81 -0
  189. package/server/api/cms/[entity]/_order.post.ts +49 -0
  190. package/server/api/cms/[entity]/_tree.get.ts +41 -0
  191. package/server/api/cms/[entity]/index.get.ts +62 -0
  192. package/server/api/cms/[entity]/index.post.ts +38 -0
  193. package/server/api/cms/[entity]/options.get.ts +55 -0
  194. package/server/api/cms/_auth/accept.post.ts +33 -0
  195. package/server/api/cms/_auth/forgot.post.ts +39 -0
  196. package/server/api/cms/_auth/invite/[token].get.ts +18 -0
  197. package/server/api/cms/_auth/login.post.ts +42 -0
  198. package/server/api/cms/_auth/logout.post.ts +7 -0
  199. package/server/api/cms/_auth/me.get.ts +5 -0
  200. package/server/api/cms/_auth/me.patch.ts +32 -0
  201. package/server/api/cms/_auth/password.post.ts +29 -0
  202. package/server/api/cms/_auth/reset.post.ts +34 -0
  203. package/server/api/cms/_auth/setup.post.ts +46 -0
  204. package/server/api/cms/_auth/status.get.ts +18 -0
  205. package/server/api/cms/_collab/session.get.ts +30 -0
  206. package/server/api/cms/_collab/socket.ts +51 -0
  207. package/server/api/cms/_collab/unsaved.delete.ts +16 -0
  208. package/server/api/cms/_graph.get.ts +20 -0
  209. package/server/api/cms/_links/resolve.post.ts +17 -0
  210. package/server/api/cms/_links.get.ts +81 -0
  211. package/server/api/cms/_live.ts +30 -0
  212. package/server/api/cms/_media/[id]/usage.get.ts +14 -0
  213. package/server/api/cms/_media/[id].delete.ts +29 -0
  214. package/server/api/cms/_media/[id].get.ts +13 -0
  215. package/server/api/cms/_media/[id].patch.ts +64 -0
  216. package/server/api/cms/_media/exists.post.ts +15 -0
  217. package/server/api/cms/_media/img/[id]/[file].get.ts +42 -0
  218. package/server/api/cms/_media/index.get.ts +44 -0
  219. package/server/api/cms/_media/index.post.ts +147 -0
  220. package/server/api/cms/_media/raw/[...key].get.ts +85 -0
  221. package/server/api/cms/_media/raw/[...key].head.ts +2 -0
  222. package/server/api/cms/_overview.get.ts +87 -0
  223. package/server/api/cms/_preview.post.ts +17 -0
  224. package/server/api/cms/_privacy/delete.post.ts +14 -0
  225. package/server/api/cms/_privacy/export.post.ts +25 -0
  226. package/server/api/cms/_privacy/lookup.post.ts +27 -0
  227. package/server/api/cms/_search.get.ts +17 -0
  228. package/server/api/cms/_singleton/[name].get.ts +19 -0
  229. package/server/api/cms/_singleton/[name].put.ts +76 -0
  230. package/server/api/cms/_users/[id]/resend.post.ts +25 -0
  231. package/server/api/cms/_users/[id].delete.ts +21 -0
  232. package/server/api/cms/_users/[id].patch.ts +45 -0
  233. package/server/api/cms/_users/index.get.ts +28 -0
  234. package/server/api/cms/_users/index.post.ts +39 -0
  235. package/server/api/content/[entity]/[slug].get.ts +74 -0
  236. package/server/api/content/[entity]/index.get.ts +100 -0
  237. package/server/api/content/_global/[name].get.ts +23 -0
  238. package/server/api/content/_search.get.ts +28 -0
  239. package/server/api/content/_sitemap.get.ts +8 -0
  240. package/server/api/content/_tree/[entity].get.ts +31 -0
  241. package/server/api/content-types.ts.get.ts +17 -0
  242. package/server/api/health/live.get.ts +10 -0
  243. package/server/api/health/ready.get.ts +21 -0
  244. package/server/api/openapi.get.ts +48 -0
  245. package/server/api/openapi.json.get.ts +32 -0
  246. package/server/db/driver.ts +8 -0
  247. package/server/mail/mailer.ts +43 -0
  248. package/server/middleware/cms-0-headers.ts +37 -0
  249. package/server/middleware/cms-0-migrate-gate.ts +14 -0
  250. package/server/middleware/cms-csrf.ts +28 -0
  251. package/server/middleware/cms-limits.ts +20 -0
  252. package/server/middleware/cms-redirects.ts +21 -0
  253. package/server/middleware/cms-session.ts +41 -0
  254. package/server/middleware/cms-z-plugin-access.ts +15 -0
  255. package/server/plugins/cms-0-config-check.ts +35 -0
  256. package/server/plugins/cms-changes.ts +53 -0
  257. package/server/plugins/cms-content-etag.ts +21 -0
  258. package/server/plugins/cms-errors.ts +45 -0
  259. package/server/plugins/cms-migrate.ts +5 -0
  260. package/server/plugins/cms-plugins.ts +17 -0
  261. package/server/plugins/cms-search.ts +12 -0
  262. package/server/plugins/cms-setup-code.ts +15 -0
  263. package/server/routes/sitemap.xml.get.ts +25 -0
  264. package/server/store/redis.ts +95 -0
  265. package/server/store/types.ts +21 -0
  266. package/server/tasks/cms/retention.ts +10 -0
  267. package/server/tasks/cms/scheduled.ts +10 -0
  268. package/server/tasks/cms/search-reindex.ts +12 -0
  269. package/server/utils/cmsAudit.ts +29 -0
  270. package/server/utils/cmsAuth.ts +143 -0
  271. package/server/utils/cmsBlocks.ts +47 -0
  272. package/server/utils/cmsChanges.ts +222 -0
  273. package/server/utils/cmsCollab.ts +286 -0
  274. package/server/utils/cmsCollabServer.ts +451 -0
  275. package/server/utils/cmsCollate.ts +27 -0
  276. package/server/utils/cmsContent.ts +376 -0
  277. package/server/utils/cmsCrud.ts +361 -0
  278. package/server/utils/cmsCsv.ts +24 -0
  279. package/server/utils/cmsDb.ts +23 -0
  280. package/server/utils/cmsDemo.ts +36 -0
  281. package/server/utils/cmsEmails.ts +125 -0
  282. package/server/utils/cmsErrors.ts +40 -0
  283. package/server/utils/cmsFold.ts +17 -0
  284. package/server/utils/cmsImageSizes.ts +51 -0
  285. package/server/utils/cmsJson.ts +6 -0
  286. package/server/utils/cmsLinkAddress.ts +50 -0
  287. package/server/utils/cmsLinks.ts +248 -0
  288. package/server/utils/cmsListQuery.ts +93 -0
  289. package/server/utils/cmsLive.ts +393 -0
  290. package/server/utils/cmsLocales.ts +96 -0
  291. package/server/utils/cmsMail.ts +28 -0
  292. package/server/utils/cmsMediaGc.ts +188 -0
  293. package/server/utils/cmsMediaKeys.ts +62 -0
  294. package/server/utils/cmsMigrate.ts +86 -0
  295. package/server/utils/cmsPreviewDraft.ts +72 -0
  296. package/server/utils/cmsPrivacy.ts +176 -0
  297. package/server/utils/cmsPublished.ts +57 -0
  298. package/server/utils/cmsRange.ts +38 -0
  299. package/server/utils/cmsRateLimit.ts +82 -0
  300. package/server/utils/cmsRedirects.ts +160 -0
  301. package/server/utils/cmsRetention.ts +61 -0
  302. package/server/utils/cmsRevisions.ts +103 -0
  303. package/server/utils/cmsScheduler.ts +45 -0
  304. package/server/utils/cmsScrub.ts +107 -0
  305. package/server/utils/cmsSearch.ts +354 -0
  306. package/server/utils/cmsSession.ts +102 -0
  307. package/server/utils/cmsSetupCode.ts +97 -0
  308. package/server/utils/cmsSitemap.ts +176 -0
  309. package/server/utils/cmsStorage.ts +580 -0
  310. package/server/utils/cmsStore.ts +109 -0
  311. package/server/utils/cmsTiming.ts +14 -0
  312. package/server/utils/cmsTooMany.ts +9 -0
  313. package/server/utils/cmsTranslationWrite.ts +186 -0
  314. package/server/utils/cmsTree.ts +251 -0
  315. package/server/utils/cmsTreeAddress.ts +65 -0
  316. package/server/utils/cmsUpload.ts +228 -0
  317. package/server/utils/cmsWebhooks.ts +104 -0
  318. package/shared/json.ts +11 -0
  319. package/shared/richtext-editor.ts +56 -0
  320. package/shared/richtext-normalize.ts +33 -0
  321. package/shared/richtext-paste.ts +151 -0
  322. package/shared/storage-delivery.ts +53 -0
  323. package/src/blocks.ts +624 -0
  324. package/src/changes.ts +54 -0
  325. package/src/content-shape.ts +340 -0
  326. package/src/deprecate.ts +64 -0
  327. package/src/descriptor.ts +149 -0
  328. package/src/docs.ts +27 -0
  329. package/src/emitter.ts +94 -0
  330. package/src/entity.ts +624 -0
  331. package/src/errorReport.ts +41 -0
  332. package/src/fields.ts +465 -0
  333. package/src/i18n.ts +26 -0
  334. package/src/index.ts +54 -0
  335. package/src/linkref.ts +31 -0
  336. package/src/links.ts +179 -0
  337. package/src/locales.ts +39 -0
  338. package/src/media.ts +48 -0
  339. package/src/migrate.ts +236 -0
  340. package/src/openapi.ts +377 -0
  341. package/src/paths.ts +88 -0
  342. package/src/plugin.ts +505 -0
  343. package/src/presets.ts +230 -0
  344. package/src/richtext.ts +88 -0
  345. package/src/sdk.ts +181 -0
  346. package/src/search.ts +312 -0
  347. package/src/seed.ts +225 -0
  348. package/src/setupCode.ts +30 -0
  349. package/src/system.ts +219 -0
  350. package/src/tree.ts +421 -0
  351. package/src/upgrades.ts +137 -0
  352. package/starter/.env.example +10 -0
  353. package/starter/README.md +65 -0
  354. package/starter/app/app.config.ts +10 -0
  355. package/starter/app/app.vue +12 -0
  356. package/starter/app/assets/css/main.css +15 -0
  357. package/starter/app/components/global/BlockContact.vue +15 -0
  358. package/starter/app/components/global/BlockCta.vue +15 -0
  359. package/starter/app/components/global/BlockHero.vue +23 -0
  360. package/starter/app/components/global/BlockImage.vue +13 -0
  361. package/starter/app/components/global/BlockText.vue +12 -0
  362. package/starter/app/composables/useSite.ts +77 -0
  363. package/starter/app/error.vue +28 -0
  364. package/starter/app/layouts/default.vue +106 -0
  365. package/starter/app/lib/cms-content.ts +152 -0
  366. package/starter/app/pages/[...slug].vue +66 -0
  367. package/starter/app/pages/hledat.vue +59 -0
  368. package/starter/app/pages/index.vue +20 -0
  369. package/starter/cms.config.ts +137 -0
  370. package/starter/compose.yaml +15 -0
  371. package/starter/drizzle.config.ts +8 -0
  372. package/starter/gitignore.txt +8 -0
  373. package/starter/nuxt.config.ts +13 -0
  374. package/starter/package.json +38 -0
  375. package/starter/scripts/typecheck.mjs +38 -0
  376. package/starter/seed/index.ts +297 -0
  377. package/starter/seed/media/about.jpg +0 -0
  378. package/starter/seed/media/hero.jpg +0 -0
  379. package/starter/seed/media/logo.png +0 -0
  380. package/starter/seed/media/news-bread.jpg +0 -0
  381. package/starter/seed/media/news-morning.jpg +0 -0
  382. package/starter/server/db/migrations/0000_init.sql +269 -0
  383. package/starter/server/db/migrations/0001_page_tree.sql +5 -0
  384. package/starter/server/db/migrations/0002_opening_hours_per_language.sql +1 -0
  385. package/starter/server/db/migrations/meta/0000_snapshot.json +1890 -0
  386. package/starter/server/db/migrations/meta/0001_snapshot.json +1887 -0
  387. package/starter/server/db/migrations/meta/0002_snapshot.json +1893 -0
  388. package/starter/server/db/migrations/meta/_journal.json +27 -0
  389. package/starter/server/db/schema.ts +253 -0
  390. package/starter/server/plugins/sitemap.ts +11 -0
  391. package/starter/server/routes/robots.txt.get.ts +12 -0
  392. package/starter/tsconfig.json +9 -0
@@ -0,0 +1,174 @@
1
+ /**
2
+ * The breaking-statement guard of `tinyzoo generate`: reads a freshly generated
3
+ * migration and names, in plain words, two classes of statements:
4
+ *
5
+ * - **destructive** — loses data or breaks the version of the site that is still
6
+ * running during a rolling deploy (drops, type changes, renames); kept with
7
+ * `--allow-drop`;
8
+ * - **risky** — may fail on rows that already exist, so the new version cannot finish
9
+ * its migration at start, exits, and restarts in a loop (a required column without a
10
+ * default, `SET NOT NULL`, a new unique constraint or index); kept with `--allow-risky`.
11
+ *
12
+ * A table the same migration creates is empty, so nothing on it can fail.
13
+ */
14
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
15
+ import { join } from 'node:path'
16
+
17
+ export type DestructiveKind = 'drop-table' | 'drop-column' | 'drop-type' | 'change-type' | 'rename'
18
+ export type RiskyKind = 'required-column' | 'set-not-null' | 'unique' | 'check'
19
+ export type BreakingKind = DestructiveKind | RiskyKind
20
+
21
+ const RISKY: ReadonlySet<BreakingKind> = new Set<RiskyKind>(['required-column', 'set-not-null', 'unique', 'check'])
22
+ /** True for statements that may fail on existing rows (as opposed to losing data). */
23
+ export const isRisky = (c: BreakingChange): boolean => RISKY.has(c.kind)
24
+
25
+ export interface BreakingChange {
26
+ kind: BreakingKind
27
+ /** Plain-language description, e.g. "drops column `x` of `post` — its content is lost". */
28
+ message: string
29
+ /** The SQL statement it came from, trimmed. */
30
+ statement: string
31
+ }
32
+
33
+ // An identifier as drizzle-kit writes it: "name" or "schema"."name".
34
+ const ID = String.raw`(?:"[^"]+"\.)?"([^"]+)"`
35
+ const tick = (s: string) => `\`${s}\``
36
+
37
+ /** Blank out comments and string literals, so `'DROP TABLE'` in a default is not a statement. */
38
+ function stripNoise(statement: string): string {
39
+ return statement
40
+ .replace(/\/\*[\s\S]*?\*\//g, ' ')
41
+ .replace(/--[^\n]*/g, ' ')
42
+ .replace(/'(?:[^']|'')*'/g, "''")
43
+ }
44
+
45
+ /** Split at commas that are not inside parentheses (`numeric(10, 2)` stays whole). */
46
+ function splitTopLevel(body: string): string[] {
47
+ const parts: string[] = []
48
+ let depth = 0
49
+ let from = 0
50
+ for (let i = 0; i < body.length; i++) {
51
+ const ch = body[i]
52
+ if (ch === '(') depth++
53
+ else if (ch === ')') depth--
54
+ else if (ch === ',' && depth === 0) { parts.push(body.slice(from, i)); from = i + 1 }
55
+ }
56
+ parts.push(body.slice(from))
57
+ return parts.map((p) => p.trim()).filter(Boolean)
58
+ }
59
+
60
+ /** `("a","b")` → `a, b`, for the message. */
61
+ const columnList = (cols: string) => cols.split(',').map((c) => c.trim().replace(/^"|"$/g, '')).map(tick).join(', ')
62
+
63
+ /** Everything in one migration file's SQL that the guard stops on. */
64
+ export function scanBreaking(migrationSql: string): BreakingChange[] {
65
+ const found: BreakingChange[] = []
66
+ // Tables this migration creates: empty, so a required column or unique index on them cannot fail.
67
+ const created = new Set<string>()
68
+ // A renamed table gets its indexes and constraints re-created under the new name (drop, then
69
+ // create): the rows and their values are unchanged, so the unique ones cannot newly fail.
70
+ const renamedFrom = new Map<string, string>() // new table → old table
71
+ const dropped = new Set<string>() // names of dropped indexes and constraints
72
+ const recreated = (table: string, name: string | undefined) => {
73
+ const old = renamedFrom.get(table)
74
+ return !!old && !!name && name.startsWith(table) && dropped.has(old + name.slice(table.length))
75
+ }
76
+ for (const raw of migrationSql.split('--> statement-breakpoint')) {
77
+ const statement = stripNoise(raw).trim()
78
+ if (!statement) continue
79
+ const add = (kind: BreakingChange['kind'], message: string) => found.push({ kind, message, statement: raw.trim() })
80
+
81
+ const createTable = new RegExp(String.raw`^CREATE\s+(?:UNLOGGED\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?${ID}`, 'i').exec(statement)
82
+ if (createTable) { created.add(createTable[1]!); continue }
83
+
84
+ const dropIndex = new RegExp(String.raw`^DROP\s+INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+EXISTS\s+)?${ID}`, 'i').exec(statement)
85
+ if (dropIndex) { dropped.add(dropIndex[1]!); continue }
86
+
87
+ const uniqueIndex = new RegExp(String.raw`^CREATE\s+UNIQUE\s+INDEX\s+(?:CONCURRENTLY\s+)?(?:IF\s+NOT\s+EXISTS\s+)?${ID}\s+ON\s+(?:ONLY\s+)?${ID}[^(]*\(([\s\S]*)\)`, 'i').exec(statement)
88
+ if (uniqueIndex) {
89
+ if (!created.has(uniqueIndex[2]!) && !recreated(uniqueIndex[2]!, uniqueIndex[1])) add('unique', `adds a unique index ${tick(uniqueIndex[1]!)} on ${columnList(uniqueIndex[3]!)} of ${tick(uniqueIndex[2]!)} — fails if rows there already share a value; check the existing rows (or clean them up) first`)
90
+ continue
91
+ }
92
+
93
+ const dropTable = new RegExp(String.raw`^DROP\s+TABLE\s+(?:IF\s+EXISTS\s+)?${ID}`, 'i').exec(statement)
94
+ if (dropTable) { add('drop-table', `drops table ${tick(dropTable[1]!)} — every row in it is lost`); continue }
95
+
96
+ const dropType = new RegExp(String.raw`^DROP\s+TYPE\s+(?:IF\s+EXISTS\s+)?${ID}`, 'i').exec(statement)
97
+ if (dropType) { add('drop-type', `drops type ${tick(dropType[1]!)} — a column that still uses it breaks`); continue }
98
+
99
+ const renameType = new RegExp(String.raw`^ALTER\s+TYPE\s+${ID}\s+RENAME\s+TO\s+${ID}`, 'i').exec(statement)
100
+ if (renameType) { add('rename', `renames type ${tick(renameType[1]!)} to ${tick(renameType[2]!)} — the running version still uses the old name`); continue }
101
+
102
+ const alter = new RegExp(String.raw`^ALTER\s+TABLE\s+(?:IF\s+EXISTS\s+)?(?:ONLY\s+)?${ID}\s+([\s\S]*)$`, 'i').exec(statement)
103
+ if (!alter) continue
104
+ const table = alter[1]!
105
+ const body = alter[2]!
106
+ // Several actions may share one statement when it was written by hand.
107
+ for (const m of body.matchAll(new RegExp(String.raw`DROP\s+COLUMN\s+(?:IF\s+EXISTS\s+)?${ID}`, 'gi'))) {
108
+ add('drop-column', `drops column ${tick(m[1]!)} of ${tick(table)} — its content is lost`)
109
+ }
110
+ for (const m of body.matchAll(new RegExp(String.raw`ALTER\s+COLUMN\s+${ID}\s+(?:SET\s+DATA\s+)?TYPE\s+((?:\([^)]*\)|[^,;(])+)`, 'gi'))) {
111
+ add('change-type', `changes the type of column ${tick(m[1]!)} of ${tick(table)} to ${m[2]!.trim().split(/\s+USING\s/i)[0]} — values that do not convert are lost, or the migration fails`)
112
+ }
113
+ for (const m of body.matchAll(new RegExp(String.raw`RENAME\s+COLUMN\s+${ID}\s+TO\s+${ID}`, 'gi'))) {
114
+ add('rename', `renames column ${tick(m[1]!)} of ${tick(table)} to ${tick(m[2]!)} — the running version still reads the old name`)
115
+ }
116
+ for (const m of body.matchAll(new RegExp(String.raw`DROP\s+CONSTRAINT\s+(?:IF\s+EXISTS\s+)?${ID}`, 'gi'))) dropped.add(m[1]!)
117
+ // What may fail on rows that exist. Skipped for a table created above in the same file.
118
+ if (!created.has(table)) {
119
+ for (const part of splitTopLevel(body)) {
120
+ const addColumn = new RegExp(String.raw`^ADD\s+(?:COLUMN\s+)?(?:IF\s+NOT\s+EXISTS\s+)?${ID}\s+([\s\S]*)$`, 'i').exec(part)
121
+ if (addColumn && !/^(?:CONSTRAINT|PRIMARY|UNIQUE|CHECK|FOREIGN)\b/i.test(part.replace(/^ADD\s+/i, ''))) {
122
+ const [, column, def] = addColumn
123
+ const hasDefault = /\bDEFAULT\b|\bGENERATED\b|^(?:big|small)?serial\b/i.test(def!)
124
+ if (/\bNOT\s+NULL\b/i.test(def!) && !hasDefault) {
125
+ add('required-column', `adds required column ${tick(column!)} to ${tick(table)} without a default — fails if ${tick(table)} has rows; give the field a default, or add it optional first, fill it, then make it required`)
126
+ }
127
+ if (/\bUNIQUE\b/i.test(def!) && hasDefault) {
128
+ add('unique', `adds a unique column ${tick(column!)} to ${tick(table)} with a default — every existing row gets the same value, so it fails if ${tick(table)} has more than one row`)
129
+ }
130
+ continue
131
+ }
132
+ const setNotNull = new RegExp(String.raw`^ALTER\s+(?:COLUMN\s+)?${ID}\s+SET\s+NOT\s+NULL\b`, 'i').exec(part)
133
+ if (setNotNull) {
134
+ add('set-not-null', `makes column ${tick(setNotNull[1]!)} of ${tick(table)} required — fails if any row has no value there; fill the empty ones first (in an earlier release), then make it required`)
135
+ continue
136
+ }
137
+ const addUnique = new RegExp(String.raw`^ADD\s+(?:CONSTRAINT\s+${ID}\s+)?UNIQUE\s*(?:NULLS\s+NOT\s+DISTINCT\s*)?\(([^)]*)\)`, 'i').exec(part)
138
+ if (addUnique) {
139
+ if (!recreated(table, addUnique[1])) add('unique', `adds a unique constraint${addUnique[1] ? ` ${tick(addUnique[1])}` : ''} on ${columnList(addUnique[2]!)} of ${tick(table)} — fails if rows there already share a value; check the existing rows (or clean them up) first`)
140
+ continue
141
+ }
142
+ const addCheck = new RegExp(String.raw`^ADD\s+(?:CONSTRAINT\s+${ID}\s+)?CHECK\b`, 'i').exec(part)
143
+ if (addCheck) add('check', `adds a check${addCheck[1] ? ` ${tick(addCheck[1])}` : ''} to ${tick(table)} — fails if a row already breaks it`)
144
+ }
145
+ }
146
+ // Constraint and index renames never break a running version; only tables do.
147
+ const renameTable = new RegExp(String.raw`^RENAME\s+TO\s+${ID}`, 'i').exec(body)
148
+ if (renameTable) renamedFrom.set(renameTable[1]!, table)
149
+ if (renameTable) add('rename', `renames table ${tick(table)} to ${tick(renameTable[1]!)} — the running version still reads the old name`)
150
+ }
151
+ return found
152
+ }
153
+
154
+ /**
155
+ * Take a generated migration back out: its SQL file, its snapshot and its entry in the
156
+ * journal. Leaves everything else in the migrations folder as it was. `journalBefore` is
157
+ * the journal's text from before the migration was generated; it is put back verbatim
158
+ * (drizzle-kit rewrites the file with its own formatting).
159
+ */
160
+ export function removeMigrations(migrationsDir: string, tags: string[], journalBefore?: string): void {
161
+ const journalPath = join(migrationsDir, 'meta/_journal.json')
162
+ const original = readFileSync(journalPath, 'utf8')
163
+ const journal = JSON.parse(original) as { entries: { idx: number; tag: string }[] }
164
+ for (const tag of tags) {
165
+ rmSync(join(migrationsDir, `${tag}.sql`), { force: true })
166
+ const prefix = /^(\d+)_/.exec(tag)?.[1]
167
+ const entry = journal.entries.find((e) => e.tag === tag)
168
+ const snapshot = join(migrationsDir, 'meta', `${prefix ?? String(entry?.idx ?? 0).padStart(4, '0')}_snapshot.json`)
169
+ if (existsSync(snapshot)) rmSync(snapshot)
170
+ }
171
+ if (journalBefore !== undefined) { writeFileSync(journalPath, journalBefore); return }
172
+ journal.entries = journal.entries.filter((e) => !tags.includes(e.tag))
173
+ writeFileSync(journalPath, JSON.stringify(journal, null, 2) + (original.endsWith('\n') ? '\n' : ''))
174
+ }
@@ -0,0 +1,239 @@
1
+ /**
2
+ * `tinyzoo content:migrate` — rewrite stored JSON (blocks, lists, rich text) to the
3
+ * current versions.
4
+ *
5
+ * Nothing has to be run on deploy: older blocks are upgraded whenever they are read
6
+ * (content API, admin, search, revisions). This rewrites the stored copies, so the
7
+ * `upgrade` functions can be retired and the database matches the code. It walks every
8
+ * entity's blocks and list columns (the entries, their translations) and the saved
9
+ * versions in `cms_revisions`, in batches inside transactions, and reports what it
10
+ * changed and what it could not upgrade (those blocks stay as they are).
11
+ *
12
+ * tinyzoo content:migrate [--dry-run] [--batch <n>]
13
+ *
14
+ * Connects with DATABASE_URL (or NUXT_CMS_DATABASE_URL) from the environment or the site's .env. Run from the host app root.
15
+ * Entries' `updatedAt` is not touched: this is not an edit.
16
+ */
17
+ import { and, asc, eq, gt, or, sql } from 'drizzle-orm'
18
+ import { drizzle } from 'drizzle-orm/node-postgres'
19
+ import pg from 'pg'
20
+ import { databaseUrl } from './db'
21
+ import { buildRegistry, propOf, upgradeStoredRow, type CmsEntity, type CmsRegistry, type UpgradeIssue } from '../src/index'
22
+
23
+ export type MigrateSource = 'entries' | 'translations' | 'revisions'
24
+
25
+ export interface MigrateFieldReport {
26
+ entity: string
27
+ field: string
28
+ source: MigrateSource
29
+ /** Rows that hold this field with a value. */
30
+ scanned: number
31
+ /** Rows that were (or, in a dry run, would be) rewritten. */
32
+ upgraded: number
33
+ /** Blocks and list items brought to a newer version inside those rows. */
34
+ blocks: number
35
+ }
36
+
37
+ export interface MigrateFailure {
38
+ entity: string
39
+ source: MigrateSource
40
+ recordId: string
41
+ locale: string | null
42
+ field: string
43
+ /** Where inside the field: `[1, 'items', 0]`. */
44
+ path: (string | number)[]
45
+ type: string
46
+ blockId: string | null
47
+ from: number
48
+ to: number
49
+ message: string
50
+ }
51
+
52
+ export interface MigrateReport {
53
+ dryRun: boolean
54
+ fields: MigrateFieldReport[]
55
+ failures: MigrateFailure[]
56
+ rowsScanned: number
57
+ rowsUpgraded: number
58
+ /** Revisions of an entity the config no longer has (left alone). */
59
+ skippedRevisions: number
60
+ }
61
+
62
+ export interface MigrateOptions {
63
+ dryRun?: boolean
64
+ batchSize?: number
65
+ log?: (line: string) => void
66
+ }
67
+
68
+ /** The fields of an entity that hold versioned JSON. */
69
+ const jsonFields = (fields: CmsEntity['fields'], only?: readonly string[]) =>
70
+ Object.fromEntries(Object.entries(fields).filter(([k, f]) => (!only || only.includes(k)) && (((f as any).type === 'blocks' && (f as any).blocks) || ((f as any).type === 'group' && (f as any).fields) || (f as any).type === 'richtext'))) as CmsEntity['fields']
71
+
72
+ /**
73
+ * Walk everything and bring stored JSON to the current versions. `db` is a drizzle
74
+ * node-postgres database; every table is reached through the registry.
75
+ */
76
+ export async function migrateContent(db: any, reg: CmsRegistry, opts: MigrateOptions = {}): Promise<MigrateReport> {
77
+ const dryRun = !!opts.dryRun
78
+ const batch = Math.max(1, opts.batchSize ?? 200)
79
+ const report: MigrateReport = { dryRun, fields: [], failures: [], rowsScanned: 0, rowsUpgraded: 0, skippedRevisions: 0 }
80
+ const counters = new Map<string, MigrateFieldReport>()
81
+ const counter = (entity: string, field: string, source: MigrateSource) => {
82
+ const key = `${entity}\u0000${source}\u0000${field}`
83
+ let c = counters.get(key)
84
+ if (!c) counters.set(key, c = { entity, field, source, scanned: 0, upgraded: 0, blocks: 0 })
85
+ return c
86
+ }
87
+
88
+ /**
89
+ * Upgrade the JSON fields of one row's values. Returns the changed values by field
90
+ * key (empty when nothing changed). Failures are collected, those blocks left as stored.
91
+ */
92
+ function upgradeValues(e: CmsEntity, source: MigrateSource, recordId: string, locale: string | null, fields: CmsEntity['fields'], values: Record<string, any>): Record<string, any> {
93
+ const changed: Record<string, any> = {}
94
+ for (const key of Object.keys(fields)) {
95
+ if (values[key] == null) continue
96
+ const c = counter(e.name, key, source)
97
+ c.scanned++
98
+ const row: Record<string, any> = { [key]: values[key] }
99
+ let blocks = 0
100
+ upgradeStoredRow({ [key]: fields[key] } as any, row, {
101
+ onUpgrade: () => { blocks++ },
102
+ onError: (issue: UpgradeIssue) => report.failures.push({
103
+ entity: e.name, source, recordId, locale, field: key, path: issue.path.slice(1), type: issue.type, blockId: issue.id,
104
+ from: issue.from, to: issue.to, message: (issue.error as Error)?.message ?? String(issue.error),
105
+ }),
106
+ })
107
+ // Rich-text steps clone the document even when nothing changes: compare the content.
108
+ if (row[key] !== values[key] && JSON.stringify(row[key]) !== JSON.stringify(values[key])) {
109
+ changed[key] = row[key]
110
+ c.upgraded++
111
+ c.blocks += blocks
112
+ }
113
+ }
114
+ return changed
115
+ }
116
+
117
+ // ── entries and their translations ──
118
+ for (const e of reg.entities) {
119
+ const main = jsonFields(e.fields)
120
+ if (Object.keys(main).length) {
121
+ let after: string | null = null
122
+ for (;;) {
123
+ const done = await db.transaction(async (tx: any) => {
124
+ const rows: any[] = await tx.select().from(e.table).where(after ? gt(e.table.id, after) : undefined).orderBy(asc(e.table.id)).limit(batch).for('update')
125
+ for (const row of rows) {
126
+ report.rowsScanned++
127
+ const changed = upgradeValues(e, 'entries', row.id, null, main, row)
128
+ if (!Object.keys(changed).length) continue
129
+ report.rowsUpgraded++
130
+ if (!dryRun) await tx.update(e.table).set(Object.fromEntries(Object.entries(changed).map(([k, v]) => [propOf(k, e.fields[k]!), v]))).where(eq(e.table.id, row.id))
131
+ }
132
+ after = rows.length ? rows[rows.length - 1].id : after
133
+ return rows.length < batch
134
+ })
135
+ if (done) break
136
+ }
137
+ }
138
+
139
+ const t = e.localesTable
140
+ const translated = t && e.localized.length ? jsonFields(e.fields, e.localized) : {}
141
+ if (t && Object.keys(translated).length) {
142
+ type Cursor = { parentId: string; locale: string }
143
+ let last = null as Cursor | null
144
+ for (;;) {
145
+ const cursor = last as Cursor | null
146
+ const done = await db.transaction(async (tx: any) => {
147
+ const where = cursor ? or(gt(t.parentId, cursor.parentId), and(eq(t.parentId, cursor.parentId), gt(t.locale, cursor.locale))) : undefined
148
+ const rows: any[] = await tx.select().from(t).where(where).orderBy(asc(t.parentId), asc(t.locale)).limit(batch).for('update')
149
+ for (const row of rows) {
150
+ report.rowsScanned++
151
+ const changed = upgradeValues(e, 'translations', row.parentId, row.locale, translated, row)
152
+ if (!Object.keys(changed).length) continue
153
+ report.rowsUpgraded++
154
+ if (!dryRun) await tx.update(t).set(changed).where(and(eq(t.parentId, row.parentId), eq(t.locale, row.locale)))
155
+ }
156
+ if (rows.length) last = { parentId: rows[rows.length - 1].parentId, locale: rows[rows.length - 1].locale }
157
+ return rows.length < batch
158
+ })
159
+ if (done) break
160
+ }
161
+ }
162
+ }
163
+
164
+ // ── saved versions ──
165
+ const rev = reg.cmsRevisions
166
+ let afterRev: string | null = null
167
+ for (;;) {
168
+ const done = await db.transaction(async (tx: any) => {
169
+ const rows: any[] = await tx.select({ id: rev.id, entity: rev.entity, recordId: rev.recordId, locale: rev.locale, data: rev.data })
170
+ .from(rev).where(afterRev ? gt(rev.id, afterRev) : undefined).orderBy(asc(rev.id)).limit(batch).for('update')
171
+ for (const row of rows) {
172
+ const e = reg.byName.get(row.entity)
173
+ if (!e || !row.data || typeof row.data !== 'object') {
174
+ if (!e) report.skippedRevisions++
175
+ continue
176
+ }
177
+ const fields = jsonFields(e.fields, row.locale ? e.localized : undefined)
178
+ if (!Object.keys(fields).length) continue
179
+ report.rowsScanned++
180
+ const changed = upgradeValues(e, 'revisions', row.recordId, row.locale, fields, row.data)
181
+ if (!Object.keys(changed).length) continue
182
+ report.rowsUpgraded++
183
+ if (!dryRun) await tx.update(rev).set({ data: sql`${JSON.stringify({ ...row.data, ...changed })}::jsonb` }).where(eq(rev.id, row.id))
184
+ }
185
+ afterRev = rows.length ? rows[rows.length - 1].id : afterRev
186
+ return rows.length < batch
187
+ })
188
+ if (done) break
189
+ }
190
+
191
+ report.fields = [...counters.values()].filter((c) => c.scanned > 0)
192
+ return report
193
+ }
194
+
195
+ const where = (f: MigrateFailure) => `${f.entity} ${f.recordId}${f.locale ? ` [${f.locale}]` : ''} · ${[f.field, ...f.path].join('.')}`
196
+
197
+ /** The report as the lines the command prints. */
198
+ export function formatReport(r: MigrateReport): string[] {
199
+ const lines: string[] = []
200
+ const rows = r.fields.filter((f) => f.upgraded > 0)
201
+ if (!rows.length && !r.failures.length) lines.push('Everything is already at the current versions.')
202
+ for (const f of rows) {
203
+ lines.push(`${`${f.entity}.${f.field}`.padEnd(34)} ${f.source.padEnd(12)} ${String(f.upgraded).padStart(5)} of ${String(f.scanned).padStart(5)} ${r.dryRun ? 'would be rewritten' : 'rewritten'}${f.blocks ? ` (${f.blocks} block${f.blocks === 1 ? '' : 's'} upgraded)` : ''}`)
204
+ }
205
+ if (r.failures.length) {
206
+ lines.push('', `Could not upgrade ${r.failures.length} block${r.failures.length === 1 ? '' : 's'} (left as stored):`)
207
+ for (const f of r.failures) lines.push(` ${where(f)} — "${f.type}"${f.blockId ? ` ${f.blockId}` : ''} v${f.from} → v${f.to}: ${f.message}`)
208
+ }
209
+ if (r.skippedRevisions) lines.push('', `${r.skippedRevisions} saved version${r.skippedRevisions === 1 ? '' : 's'} of entities that are no longer in the config were left alone.`)
210
+ lines.push('', `${r.rowsScanned} rows read, ${r.rowsUpgraded} ${r.dryRun ? 'would be rewritten (dry run: nothing was written)' : 'rewritten'}.`)
211
+ return lines
212
+ }
213
+
214
+ /** The command: connect, migrate, print. Exits 1 when something could not be upgraded. */
215
+ export async function contentMigrateCommand(config: Record<string, any>, args: string[]): Promise<void> {
216
+ const dryRun = args.includes('--dry-run')
217
+ const bi = args.indexOf('--batch')
218
+ const batchSize = bi >= 0 ? Number(args[bi + 1]) : undefined
219
+ if (bi >= 0 && !(Number.isInteger(batchSize) && batchSize! > 0)) {
220
+ console.error('usage: tinyzoo content:migrate [--dry-run] [--batch <n>]')
221
+ process.exit(1)
222
+ }
223
+ let url: string
224
+ try { url = databaseUrl(process.cwd()) }
225
+ catch (err) {
226
+ console.error(`✗ ${(err as Error).message}`)
227
+ process.exit(1)
228
+ }
229
+ const reg = buildRegistry(config)
230
+ const pool = new pg.Pool({ connectionString: url, max: 2 })
231
+ try {
232
+ const report = await migrateContent(drizzle(pool, { schema: reg.schema }), reg, { dryRun, batchSize })
233
+ for (const line of formatReport(report)) console.log(line)
234
+ if (report.failures.length) process.exitCode = 1
235
+ }
236
+ finally {
237
+ await pool.end()
238
+ }
239
+ }
package/cli/db.ts ADDED
@@ -0,0 +1,86 @@
1
+ /** Connecting to the host's database from the command line (`up`, `status`, `upgrade`). */
2
+ import { existsSync, readFileSync } from 'node:fs'
3
+ import { join, resolve } from 'node:path'
4
+ import { pathToFileURL } from 'node:url'
5
+ import { allUpgradeSteps, collectPlugins, type MigrationSource, type SqlRunner, type UpgradeStep } from '../src/index'
6
+
7
+ /** `NUXT_CMS_DATABASE_URL` / `DATABASE_URL` from the environment, else from the host's `.env`. */
8
+ export function databaseUrl(cwd: string): string {
9
+ const envFile = join(cwd, '.env')
10
+ if (!process.env.DATABASE_URL && !process.env.NUXT_CMS_DATABASE_URL && existsSync(envFile)) {
11
+ try { process.loadEnvFile(envFile) } catch { /* unreadable .env: reported below */ }
12
+ }
13
+ const url = process.env.NUXT_CMS_DATABASE_URL || process.env.DATABASE_URL
14
+ if (!url) throw new Error('No database address: set DATABASE_URL (in the environment or the site\'s .env).')
15
+ return url
16
+ }
17
+
18
+ /** Where the connection goes, without the credentials — safe to print. */
19
+ export function describeDatabase(url: string): string {
20
+ try {
21
+ const u = new URL(url)
22
+ return `${u.hostname}${u.port ? `:${u.port}` : ''}${u.pathname}`
23
+ }
24
+ catch { return 'the database' }
25
+ }
26
+
27
+ /** The host's drizzle-kit migrations folder, read from disk. */
28
+ export function diskSource(cwd: string, dir = 'server/db/migrations'): MigrationSource {
29
+ const root = resolve(cwd, dir)
30
+ const journalFile = join(root, 'meta/_journal.json')
31
+ if (!existsSync(journalFile)) throw new Error(`No migrations found (${journalFile}) — run \`tinyzoo generate\` first.`)
32
+ return {
33
+ journal: JSON.parse(readFileSync(journalFile, 'utf8')),
34
+ readSql: async (tag) => readFileSync(join(root, `${tag}.sql`), 'utf8'),
35
+ }
36
+ }
37
+
38
+ /** Connect, hand over a runner and a transaction helper, and always disconnect. */
39
+ export async function withDatabase<T>(
40
+ url: string,
41
+ fn: (db: { run: SqlRunner; transaction: <R>(f: (run: SqlRunner) => Promise<R>) => Promise<R> }) => Promise<T>,
42
+ ): Promise<T> {
43
+ const { default: pg } = await import('pg')
44
+ const pool = new pg.Pool({ connectionString: url, max: 2, connectionTimeoutMillis: 10_000 })
45
+ try {
46
+ return await fn({
47
+ run: async (text, params) => (await pool.query(text, params as any[])).rows,
48
+ transaction: async (f) => {
49
+ const client = await pool.connect()
50
+ try {
51
+ await client.query('begin')
52
+ const out = await f(async (text, params) => (await client.query(text, params as any[])).rows)
53
+ await client.query('commit')
54
+ return out
55
+ }
56
+ catch (err) {
57
+ await client.query('rollback').catch(() => {})
58
+ throw err
59
+ }
60
+ finally {
61
+ client.release()
62
+ }
63
+ },
64
+ })
65
+ }
66
+ finally {
67
+ await pool.end()
68
+ }
69
+ }
70
+
71
+ /** A readable one-liner for an error thrown while talking to the database. */
72
+ export function errorText(err: unknown): string {
73
+ const e = err as any
74
+ const parts = [e?.message, e?.code && `(${e.code})`, ...(Array.isArray(e?.errors) ? e.errors.map((x: any) => x?.message) : [])].filter(Boolean)
75
+ return parts.join(' ') || String(err)
76
+ }
77
+
78
+ /**
79
+ * tinyzoo's upgrade steps plus those of the plugins registered in the site's
80
+ * `cms.config.ts` (no config, or none with plugins: tinyzoo's alone).
81
+ */
82
+ export async function siteUpgradeSteps(cwd: string): Promise<UpgradeStep[]> {
83
+ const file = resolve(cwd, 'cms.config.ts')
84
+ if (!existsSync(file)) return allUpgradeSteps([])
85
+ return allUpgradeSteps(collectPlugins(await import(pathToFileURL(file).href)))
86
+ }