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
package/src/links.ts ADDED
@@ -0,0 +1,179 @@
1
+ import { blockVersion, storedBlockVersion } from './blocks'
2
+ import { looksLikeLinkRef } from './linkref'
3
+
4
+ /**
5
+ * Links that follow their target.
6
+ *
7
+ * A page or entry an editor picks in the link picker is stored as a reference,
8
+ * `cms:<entity>/<id>`, instead of its address — in a link field (`f.text({ format:
9
+ * 'link' })`, a menu's link block) and in the `href` of a rich-text link. The website
10
+ * never sees one: on read, the content API turns each reference into the target's
11
+ * current address in the language asked for (or `null` / an unlinked text when the
12
+ * target is gone, not published or not public). Addresses typed by hand (`/path`,
13
+ * `https://…`, `mailto:`, `tel:`) are stored and served as they are.
14
+ *
15
+ * This module is the pure part: the reference format, and the walk over stored values
16
+ * (fields, lists, blocks, groups, rich text) that finds links and rewrites them.
17
+ */
18
+
19
+ export { linkRef, parseLinkRef, isLinkRef, looksLikeLinkRef, type LinkRef } from './linkref'
20
+
21
+ // ── walking stored values ──────────────────────────────────────────────────────
22
+
23
+ /** What the walk needs to know of a field (a field descriptor, or its graph entry). */
24
+ export interface LinkFieldLike {
25
+ type: string
26
+ meta?: Record<string, any>
27
+ blocks?: Record<string, { fields: Record<string, LinkFieldLike>; version?: number }>
28
+ fields?: Record<string, LinkFieldLike>
29
+ }
30
+
31
+ /** Is this a field that holds an address a link can be stored in? */
32
+ export const isLinkField = (fld: LinkFieldLike): boolean => fld.type === 'text' && fld.meta?.format === 'link'
33
+
34
+ const holds = new WeakMap<object, boolean>()
35
+
36
+ /**
37
+ * Can a value of this field contain a link, at any depth? Link fields and rich text do;
38
+ * a list, a block or a group does when one of its fields does.
39
+ */
40
+ export function holdsLinks(fld: LinkFieldLike): boolean {
41
+ const known = holds.get(fld)
42
+ if (known !== undefined) return known
43
+ holds.set(fld, false) // a field cannot contain itself: stops a cycle if one ever exists
44
+ let out = isLinkField(fld) || fld.type === 'richtext'
45
+ if (!out && fld.type === 'blocks') out = Object.values(fld.blocks ?? {}).some((def) => Object.values(def.fields).some(holdsLinks))
46
+ if (!out && fld.type === 'group') out = Object.values(fld.fields ?? {}).some(holdsLinks)
47
+ holds.set(fld, out)
48
+ return out
49
+ }
50
+
51
+ /** The fields of an entity (or any field map) that can hold a link. */
52
+ export const linkFieldsOf = <F extends LinkFieldLike>(fields: Record<string, F>): [string, F][] => Object.entries(fields).filter(([, fld]) => holdsLinks(fld))
53
+
54
+ /**
55
+ * What to do with each link found. Return `undefined` to leave a link as it is.
56
+ * - `field`: a stored link field's value (text) → the new value, or null to empty it;
57
+ * - `mark`: a rich-text link's href → the new href, or null to take the link off the text (the text stays).
58
+ */
59
+ export interface LinkVisitor {
60
+ field?: (value: string) => string | null | undefined
61
+ mark?: (href: string) => string | null | undefined
62
+ /** Blocks stored at an older version than their definition are skipped (and reported here): their fields may not be where the definition says. */
63
+ skipStale?: boolean
64
+ onStale?: (type: string) => void
65
+ }
66
+
67
+ const isPlainObject = (v: unknown): v is Record<string, any> => !!v && typeof v === 'object' && !Array.isArray(v)
68
+
69
+ /** A rich-text document with its link marks rewritten; the same object when nothing changed. */
70
+ export function mapDocLinks<T>(doc: T, visitor: LinkVisitor): T {
71
+ if (!visitor.mark) return doc
72
+ const mark = visitor.mark
73
+ const walk = (node: any): any => {
74
+ if (!isPlainObject(node)) return node
75
+ let out = node
76
+ if (Array.isArray(node.marks)) {
77
+ let changed = false
78
+ const marks: unknown[] = []
79
+ for (const m of node.marks) {
80
+ if (isPlainObject(m) && m.type === 'link' && typeof m.attrs?.href === 'string') {
81
+ const next = mark(m.attrs.href)
82
+ if (next === undefined || next === m.attrs.href) marks.push(m)
83
+ else {
84
+ changed = true
85
+ if (next !== null) marks.push({ ...m, attrs: { ...m.attrs, href: next } })
86
+ }
87
+ }
88
+ else marks.push(m)
89
+ }
90
+ if (changed) {
91
+ // A text left with no mark at all has no `marks`, as if it had never been a link.
92
+ const { marks: _old, ...rest } = out
93
+ out = marks.length ? { ...rest, marks } : rest
94
+ }
95
+ }
96
+ if (Array.isArray(node.content)) {
97
+ let changed = false
98
+ const content = node.content.map((child: unknown) => {
99
+ const next = walk(child)
100
+ if (next !== child) changed = true
101
+ return next
102
+ })
103
+ if (changed) out = { ...out, content }
104
+ }
105
+ return out
106
+ }
107
+ return walk(doc)
108
+ }
109
+
110
+ /** One field's value with its links rewritten; the same value when nothing changed. */
111
+ export function mapFieldLinks(fld: LinkFieldLike, value: unknown, visitor: LinkVisitor): unknown {
112
+ if (value === null || value === undefined) return value
113
+ if (isLinkField(fld)) {
114
+ if (typeof value !== 'string' || !value || !visitor.field) return value
115
+ const next = visitor.field(value)
116
+ return next === undefined ? value : next
117
+ }
118
+ if (fld.type === 'richtext') return mapDocLinks(value, visitor)
119
+ if (fld.type === 'blocks' && fld.blocks) return mapBlockLinks(value, fld.blocks, visitor)
120
+ if (fld.type === 'group' && fld.fields) return mapGroupLinks(value, fld.fields, visitor)
121
+ return value
122
+ }
123
+
124
+ function mapGroupLinks(value: unknown, fields: Record<string, LinkFieldLike>, visitor: LinkVisitor): unknown {
125
+ if (!isPlainObject(value)) return value
126
+ let out = value
127
+ for (const [key, fld] of linkFieldsOf(fields)) {
128
+ if (!(key in out)) continue
129
+ const next = mapFieldLinks(fld, out[key], visitor)
130
+ if (next !== out[key]) out = { ...out, [key]: next }
131
+ }
132
+ return out
133
+ }
134
+
135
+ function mapBlockLinks(value: unknown, defs: Record<string, { fields: Record<string, LinkFieldLike>; version?: number }>, visitor: LinkVisitor): unknown {
136
+ if (!Array.isArray(value)) return value
137
+ let changed = false
138
+ const out = value.map((b) => {
139
+ if (!isPlainObject(b) || typeof b.type !== 'string' || !Object.hasOwn(defs, b.type)) return b
140
+ const def = defs[b.type]!
141
+ if (visitor.skipStale && storedBlockVersion(b) < blockVersion(def)) {
142
+ visitor.onStale?.(b.type)
143
+ return b
144
+ }
145
+ let cur: Record<string, any> = b
146
+ for (const [key, fld] of linkFieldsOf(def.fields)) {
147
+ if (!(key in cur)) continue
148
+ const next = mapFieldLinks(fld, cur[key], visitor)
149
+ if (next !== cur[key]) cur = { ...cur, [key]: next }
150
+ }
151
+ if (cur !== b) changed = true
152
+ return cur
153
+ })
154
+ return changed ? out : value
155
+ }
156
+
157
+ /**
158
+ * The links of a row rewritten, as the fields that changed (`{ url: '/o-nas' }`):
159
+ * nothing is modified, so a row (or a draft someone else holds) is never touched.
160
+ */
161
+ export function mapRowLinks(fields: Record<string, LinkFieldLike>, row: Record<string, any>, visitor: LinkVisitor): Record<string, any> {
162
+ const changed: Record<string, any> = {}
163
+ for (const [key, fld] of linkFieldsOf(fields)) {
164
+ if (!(key in row)) continue
165
+ const next = mapFieldLinks(fld, row[key], visitor)
166
+ if (next !== row[key]) changed[key] = next
167
+ }
168
+ return changed
169
+ }
170
+
171
+ /** Every link reference (`cms:…`, well-formed or not) a row holds, in its link fields and rich text. */
172
+ export function linkRefsOf(fields: Record<string, LinkFieldLike>, row: Record<string, any>, out: Set<string> = new Set()): Set<string> {
173
+ const seen = (v: string) => {
174
+ if (looksLikeLinkRef(v)) out.add(v)
175
+ return undefined
176
+ }
177
+ mapRowLinks(fields, row, { field: seen, mark: seen })
178
+ return out
179
+ }
package/src/locales.ts ADDED
@@ -0,0 +1,39 @@
1
+ import type { LocalizedText } from './i18n'
2
+
3
+ /**
4
+ * The languages content is written in (not the admin interface language).
5
+ *
6
+ * export const locales = defineLocales({ default: 'cs', locales: ['cs', 'en', 'de'] })
7
+ *
8
+ * The default language lives in each entry's own row; the others are translations
9
+ * of the fields marked `.localized()`, falling back to the default when missing.
10
+ */
11
+ export interface LocalesDef {
12
+ __cms: 'locales'
13
+ default: string
14
+ locales: string[]
15
+ /** How each language is named in the admin, e.g. { cs: 'Čeština', en: 'English' }. */
16
+ labels: Record<string, LocalizedText>
17
+ /**
18
+ * How addresses carry the language on the website (used for the sitemap):
19
+ * 'except-default' (default): /blog/x and /en/blog/x; 'all': /cs/… and /en/…; 'none'.
20
+ */
21
+ prefix: 'except-default' | 'all' | 'none'
22
+ }
23
+
24
+ const KNOWN: Record<string, string> = {
25
+ cs: 'Čeština', sk: 'Slovenčina', en: 'English', de: 'Deutsch', pl: 'Polski', hu: 'Magyar',
26
+ fr: 'Français', it: 'Italiano', es: 'Español', nl: 'Nederlands', uk: 'Українська', ru: 'Русский',
27
+ }
28
+ const CODE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})?$/
29
+
30
+ export function defineLocales(def: { default: string; locales: string[]; labels?: Record<string, LocalizedText>; prefix?: LocalesDef['prefix'] }): LocalesDef {
31
+ const locales = [...new Set(def.locales)]
32
+ for (const l of locales) if (!CODE.test(l)) throw new Error(`Invalid locale code "${l}" (use e.g. "cs", "en", "pt-BR").`)
33
+ if (!locales.includes(def.default)) throw new Error(`The default locale "${def.default}" must be one of the locales.`)
34
+ // Default first, the rest in the order given.
35
+ const ordered = [def.default, ...locales.filter((l) => l !== def.default)]
36
+ const labels: Record<string, LocalizedText> = {}
37
+ for (const l of ordered) labels[l] = def.labels?.[l] ?? KNOWN[l.split('-')[0]!] ?? l
38
+ return { __cms: 'locales', default: def.default, locales: ordered, labels, prefix: def.prefix ?? 'except-default' }
39
+ }
package/src/media.ts ADDED
@@ -0,0 +1,48 @@
1
+ import { boolean, integer, jsonb, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core'
2
+
3
+ /** Built-in media entity. Blobs live in a StorageDriver; only metadata is in the DB. */
4
+ export const cmsMedia = pgTable('cms_media', {
5
+ id: uuid('id').primaryKey().defaultRandom(),
6
+ url: text('url').notNull(),
7
+ key: text('key').notNull(),
8
+ mime: text('mime').notNull(),
9
+ size: integer('size').notNull(),
10
+ width: integer('width'),
11
+ height: integer('height'),
12
+ alt: text('alt'),
13
+ // Alt text per content language ({ en: '…' }); `alt` is the default language's.
14
+ altLocales: jsonb('alt_locales'),
15
+ // The file's name as uploaded (for people finding it again; never used as a path).
16
+ name: text('name'),
17
+ // A folder in the library (one level, e.g. 'Team photos'); null = no folder.
18
+ folder: text('folder'),
19
+ // Focal point in percent of width/height (0–100): what must stay when cropping.
20
+ focalX: integer('focal_x'),
21
+ focalY: integer('focal_y'),
22
+ // Host user id of the uploader (no FK — the users table is host-owned). Drives per-user quota.
23
+ uploadedBy: uuid('uploaded_by'),
24
+ // Kept in the library: uploaded or edited there on purpose. Such a file stays when no
25
+ // entry uses it any more; only files uploaded straight into a field are cleaned up.
26
+ inLibrary: boolean('in_library').notNull().default(false),
27
+ createdAt: timestamp('created_at', { withTimezone: true, mode: 'date', precision: 3 }).notNull().defaultNow(),
28
+ })
29
+
30
+ /** Source emitted verbatim into db/schema.ts so migrations create the table. */
31
+ export const CMS_MEDIA_SOURCE = `export const cmsMedia = pgTable('cms_media', {
32
+ id: uuid('id').primaryKey().defaultRandom(),
33
+ url: text('url').notNull(),
34
+ key: text('key').notNull(),
35
+ mime: text('mime').notNull(),
36
+ size: integer('size').notNull(),
37
+ width: integer('width'),
38
+ height: integer('height'),
39
+ alt: text('alt'),
40
+ altLocales: jsonb('alt_locales'),
41
+ name: text('name'),
42
+ folder: text('folder'),
43
+ focalX: integer('focal_x'),
44
+ focalY: integer('focal_y'),
45
+ uploadedBy: uuid('uploaded_by'),
46
+ inLibrary: boolean('in_library').notNull().default(false),
47
+ createdAt: timestamp('created_at', { withTimezone: true, mode: 'date', precision: 3 }).notNull().defaultNow(),
48
+ })`
package/src/migrate.ts ADDED
@@ -0,0 +1,236 @@
1
+ /**
2
+ * Applying drizzle-kit migrations with drizzle's own bookkeeping — the same
3
+ * `drizzle.__drizzle_migrations` table, hashes and ordering as `drizzle-kit migrate`,
4
+ * so either tool can take over from the other. Web Crypto only.
5
+ * A Postgres advisory lock makes concurrent starts take turns. Upgrade steps
6
+ * (upgrades.ts) run in the same transaction and lock: `before` steps ahead of the
7
+ * pending migrations, `after` steps behind them.
8
+ */
9
+ import { docsUrl } from './docs'
10
+ import { sql, type SQL } from 'drizzle-orm'
11
+ import { assertValidSteps, runUpgradeSteps, stepIsDue, UPGRADES_TABLE_SQL, type StepOutcome, type UpgradeContext, type UpgradeStep } from './upgrades'
12
+
13
+ export interface MigrationJournal { entries: { idx: number; when: number; tag: string }[] }
14
+ export interface MigrationSource {
15
+ journal: MigrationJournal
16
+ readSql: (tag: string) => Promise<string>
17
+ }
18
+ /** Runs one SQL text with optional params; returns rows. */
19
+ export type SqlRunner = (text: string, params?: unknown[]) => Promise<any[]>
20
+ export type JournalEntry = MigrationJournal['entries'][number]
21
+
22
+ const LOCK = 72_011_003
23
+
24
+ async function sha256Hex(text: string): Promise<string> {
25
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
26
+ return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')
27
+ }
28
+
29
+ export interface MigrationClassification<T extends { idx: number; when: number }> {
30
+ applied: T[]
31
+ /** Newer than everything applied: will run. */
32
+ pending: T[]
33
+ /** Never applied, yet older than one that was: drizzle would skip it. */
34
+ outOfOrder: T[]
35
+ /** Applied in the database but absent from the journal (a newer version ran here). */
36
+ unknown: number
37
+ }
38
+
39
+ /**
40
+ * Sort the journal against what the database has recorded. Drizzle applies "everything
41
+ * newer than the last applied migration", so a migration that is older than the newest
42
+ * applied one and was never applied (two branches each generated one) would be skipped
43
+ * for good. Entries are matched by `created_at` (the journal's `when`), not by hash: a
44
+ * migration edited after it was applied must not look unapplied.
45
+ */
46
+ export function classifyMigrations<T extends { idx: number; when: number }>(entries: T[], appliedMillis: number[]): MigrationClassification<T> {
47
+ const have = new Set(appliedMillis)
48
+ const newest = appliedMillis.length ? Math.max(...appliedMillis) : null
49
+ const out: MigrationClassification<T> = { applied: [], pending: [], outOfOrder: [], unknown: 0 }
50
+ const known = new Set<number>()
51
+ for (const e of [...entries].sort((a, b) => a.idx - b.idx)) {
52
+ known.add(e.when)
53
+ if (have.has(e.when)) out.applied.push(e)
54
+ else if (newest !== null && e.when <= newest) out.outOfOrder.push(e)
55
+ else out.pending.push(e)
56
+ }
57
+ out.unknown = [...have].filter((ms) => !known.has(ms)).length
58
+ return out
59
+ }
60
+
61
+ /** An unapplied migration older than the newest applied one: stopped instead of skipped. */
62
+ export class MigrationOrderError extends Error {
63
+ constructor(public readonly entries: JournalEntry[]) {
64
+ super(orderMessage(entries))
65
+ this.name = 'MigrationOrderError'
66
+ }
67
+ }
68
+
69
+ /**
70
+ * What to do about an out-of-order migration. Regenerating gives it a later date, which is
71
+ * all that is needed if it ran nowhere; if it ran on another database that is not enough.
72
+ */
73
+ export const ORDER_FIX = {
74
+ /** The fix: take it out and let `tinyzoo generate` write it again on top of the newest one. */
75
+ regenerate: (files: string) => `Fix: in your migrations folder (server/db/migrations by default) delete ${files}, its snapshot (meta/<number>_snapshot.json) and its entry in meta/_journal.json, then run \`tinyzoo generate\` again — the new migration is dated now, so it sorts after the others.`,
76
+ /** If it already ran somewhere (production, a colleague's database), the new one would run there a second time. */
77
+ appliedElsewhere: 'If it already ran on another database (production, a colleague\'s), that is not enough: the regenerated migration is a new one to that database, and would repeat changes it already has. Before deploying, edit the new .sql so it can run twice (ADD COLUMN IF NOT EXISTS, CREATE TABLE / CREATE INDEX IF NOT EXISTS, DROP … IF EXISTS before ADD CONSTRAINT; keep any statements you wrote by hand). Deleting and regenerating without that breaks the deploy.',
78
+ }
79
+
80
+ function orderMessage(entries: JournalEntry[]): string {
81
+ const files = entries.map((e) => `${e.tag}.sql`).join(', ')
82
+ return `Migration${entries.length > 1 ? 's' : ''} ${files} ${entries.length > 1 ? 'were' : 'was'} never applied to this database, but a newer migration already was — `
83
+ + 'usually two branches each generated one. Drizzle would skip it for good, so nothing is applied until this is fixed. '
84
+ + `${ORDER_FIX.regenerate(files)} ${ORDER_FIX.appliedElsewhere} (More: ${docsUrl('neverApplied')})`
85
+ }
86
+
87
+ interface ReadMigration extends JournalEntry { hash: string; statements: string[] }
88
+
89
+ async function readMigrations(source: MigrationSource): Promise<ReadMigration[]> {
90
+ const out: ReadMigration[] = []
91
+ for (const entry of [...source.journal.entries].sort((a, b) => a.idx - b.idx)) {
92
+ const query = await source.readSql(entry.tag)
93
+ out.push({ ...entry, hash: await sha256Hex(query), statements: query.split('--> statement-breakpoint') })
94
+ }
95
+ return out
96
+ }
97
+
98
+ const statementsOf = (migrations: ReadMigration[]) => migrations.flatMap((m) => m.statements).map((s) => s.trim()).filter(Boolean)
99
+
100
+ export interface UpgradeResult {
101
+ /** Tags of the migrations applied. */
102
+ migrations: string[]
103
+ /** Upgrade steps that ran or were recorded, in order. */
104
+ steps: StepOutcome[]
105
+ /** The database had no applied migration before this run. */
106
+ freshInstall: boolean
107
+ }
108
+
109
+ /**
110
+ * Apply the pending migrations and upgrade steps. `transaction` must run the callback in
111
+ * one transaction (so a failed migration or step leaves nothing half-applied). Throws
112
+ * `MigrationOrderError` instead of skipping an out-of-order migration.
113
+ */
114
+ export async function runUpgrade(
115
+ source: MigrationSource,
116
+ transaction: <T>(fn: (run: SqlRunner) => Promise<T>) => Promise<T>,
117
+ steps: UpgradeStep[],
118
+ ): Promise<UpgradeResult> {
119
+ assertValidSteps(steps)
120
+ const migrations = await readMigrations(source)
121
+
122
+ return transaction(async (run) => {
123
+ await run('select pg_advisory_xact_lock($1)', [LOCK])
124
+ await run('CREATE SCHEMA IF NOT EXISTS "drizzle"')
125
+ await run('CREATE TABLE IF NOT EXISTS "drizzle"."__drizzle_migrations" (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint)')
126
+ await run(UPGRADES_TABLE_SQL)
127
+ const rows = await run('select created_at from "drizzle"."__drizzle_migrations"')
128
+ const { pending, outOfOrder } = classifyMigrations(migrations, rows.map((r) => Number(r.created_at)))
129
+ if (outOfOrder.length) throw new MigrationOrderError(outOfOrder)
130
+
131
+ const done = new Set<string>((await run('select id from "cms_upgrades"')).map((r) => String(r.id)))
132
+ const ctx: UpgradeContext = { run, pendingStatements: statementsOf(pending), freshInstall: rows.length === 0 }
133
+ const outcomes = await runUpgradeSteps('before', steps, ctx, done)
134
+ for (const m of pending) {
135
+ for (const stmt of m.statements) if (stmt.trim()) await run(stmt)
136
+ await run('insert into "drizzle"."__drizzle_migrations" ("hash", "created_at") values ($1, $2)', [m.hash, m.when])
137
+ }
138
+ outcomes.push(...await runUpgradeSteps('after', steps, ctx, done))
139
+ return { migrations: pending.map((m) => m.tag), steps: outcomes, freshInstall: ctx.freshInstall }
140
+ })
141
+ }
142
+
143
+ /**
144
+ * Apply every migration newer than the last one recorded, with the upgrade steps.
145
+ * Returns the tags applied (see `runUpgrade` for the steps too).
146
+ */
147
+ export async function applyMigrations(
148
+ source: MigrationSource,
149
+ transaction: <T>(fn: (run: SqlRunner) => Promise<T>) => Promise<T>,
150
+ steps: UpgradeStep[],
151
+ ): Promise<string[]> {
152
+ return (await runUpgrade(source, transaction, steps)).migrations
153
+ }
154
+
155
+ export interface StepStatus {
156
+ id: string
157
+ since: string
158
+ description: string
159
+ phase: UpgradeStep['phase']
160
+ /** applied: recorded. pending: due now. idle: has a `when` that does not hold right now. */
161
+ state: 'applied' | 'pending' | 'idle'
162
+ }
163
+ export interface MigrationStatus {
164
+ /** No migration applied yet. */
165
+ freshInstall: boolean
166
+ applied: string[]
167
+ pending: string[]
168
+ outOfOrder: string[]
169
+ /** Migrations the database has that this code's journal does not. */
170
+ unknown: number
171
+ steps: StepStatus[]
172
+ }
173
+
174
+ /**
175
+ * What the database has and has not applied, without changing anything (`tinyzoo status`).
176
+ * Missing bookkeeping tables read as "nothing applied yet".
177
+ */
178
+ export async function inspectMigrations(source: MigrationSource, run: SqlRunner, steps: UpgradeStep[]): Promise<MigrationStatus> {
179
+ assertValidSteps(steps)
180
+ const [{ migrations_table: hasMigrations, upgrades_table: hasUpgrades }] = await run(
181
+ `select to_regclass('drizzle.__drizzle_migrations') is not null as migrations_table, to_regclass('cms_upgrades') is not null as upgrades_table`)
182
+ const rows = hasMigrations ? await run('select created_at from "drizzle"."__drizzle_migrations"') : []
183
+ const done = new Set<string>(hasUpgrades ? (await run('select id from "cms_upgrades"')).map((r) => String(r.id)) : [])
184
+ const migrations = await readMigrations(source)
185
+ const c = classifyMigrations(migrations, rows.map((r) => Number(r.created_at)))
186
+ const ctx: UpgradeContext = { run, pendingStatements: statementsOf(c.pending), freshInstall: rows.length === 0 }
187
+ const stepStatus: StepStatus[] = []
188
+ for (const s of steps) {
189
+ const state = s.when ? ((await stepIsDue(s, ctx, done)) ? 'pending' : done.has(s.id) ? 'applied' : 'idle')
190
+ : done.has(s.id) ? 'applied' : 'pending'
191
+ stepStatus.push({ id: s.id, since: s.since, description: s.description, phase: s.phase, state })
192
+ }
193
+ return {
194
+ freshInstall: rows.length === 0,
195
+ applied: c.applied.map((m) => m.tag),
196
+ pending: c.pending.map((m) => m.tag),
197
+ outOfOrder: c.outOfOrder.map((m) => m.tag),
198
+ unknown: c.unknown,
199
+ steps: stepStatus,
200
+ }
201
+ }
202
+
203
+
204
+ /**
205
+ * Positional params ($1, $2…) → a drizzle sql chunk with bound values. Without
206
+ * params the text goes through untouched: migration SQL may contain `$1` in a
207
+ * function body or `'$5'` in a literal.
208
+ */
209
+ export function sqlWithParams(text: string, params: unknown[] = []): SQL {
210
+ if (!params.length) return sql.raw(text)
211
+ const chunks: SQL[] = []
212
+ let last = 0
213
+ for (const m of text.matchAll(/\$(\d+)/g)) {
214
+ const n = Number(m[1])
215
+ if (n < 1 || n > params.length) continue
216
+ chunks.push(sql.raw(text.slice(last, m.index)), sql`${params[n - 1]}`)
217
+ last = m.index! + m[0].length
218
+ }
219
+ chunks.push(sql.raw(text.slice(last)))
220
+ return sql.join(chunks, sql.raw(''))
221
+ }
222
+
223
+ const CONNECTION_ERRORS = new Set(['ECONNREFUSED', 'ECONNRESET', 'ENOTFOUND', 'EAI_AGAIN', 'ETIMEDOUT', 'EHOSTUNREACH', '57P03', '08000', '08001', '08003', '08006'])
224
+
225
+ const CONNECTION_MESSAGES = /^(Connection terminated (due to connection timeout|unexpectedly)|timeout expired)$/
226
+
227
+ /** Could not reach the database (worth retrying), as opposed to a statement that failed. */
228
+ export function isConnectionError(err: any): boolean {
229
+ for (let e = err, depth = 0; e && depth < 4; e = e.cause, depth++) {
230
+ if (CONNECTION_ERRORS.has(e.code)) return true
231
+ if (Array.isArray(e.errors) && e.errors.some((x: any) => CONNECTION_ERRORS.has(x?.code))) return true
232
+ // node-postgres reports a pool timeout and a dropped socket without a code.
233
+ if (typeof e.message === 'string' && CONNECTION_MESSAGES.test(e.message)) return true
234
+ }
235
+ return false
236
+ }