tinyzoo 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (392) hide show
  1. package/LICENSE +10 -0
  2. package/README.md +46 -2
  3. package/app/app.config.ts +35 -0
  4. package/app/assets/brand/characters/bright/bird.svg +1 -0
  5. package/app/assets/brand/characters/bright/bunny.svg +1 -0
  6. package/app/assets/brand/characters/bright/elephant.svg +1 -0
  7. package/app/assets/brand/characters/bright/fox.svg +1 -0
  8. package/app/assets/brand/characters/bright/frog.svg +1 -0
  9. package/app/assets/brand/characters/bright/octopus.svg +1 -0
  10. package/app/assets/brand/characters/muted/bee.svg +1 -0
  11. package/app/assets/brand/characters/muted/bird.svg +1 -0
  12. package/app/assets/brand/characters/muted/butterfly.svg +1 -0
  13. package/app/assets/brand/characters/muted/chick.svg +1 -0
  14. package/app/assets/brand/characters/muted/cow.svg +1 -0
  15. package/app/assets/brand/characters/muted/deer.svg +1 -0
  16. package/app/assets/brand/characters/muted/duck.svg +1 -0
  17. package/app/assets/brand/characters/muted/elephant.svg +1 -0
  18. package/app/assets/brand/characters/muted/fox.svg +1 -0
  19. package/app/assets/brand/characters/muted/hedgehog.svg +1 -0
  20. package/app/assets/brand/characters/muted/koala.svg +1 -0
  21. package/app/assets/brand/characters/muted/ladybug.svg +1 -0
  22. package/app/assets/brand/characters/muted/lion.svg +1 -0
  23. package/app/assets/brand/characters/muted/mouse.svg +1 -0
  24. package/app/assets/brand/characters/muted/octopus.svg +1 -0
  25. package/app/assets/brand/characters/muted/owl.svg +1 -0
  26. package/app/assets/brand/characters/muted/panda.svg +1 -0
  27. package/app/assets/brand/characters/muted/penguin.svg +1 -0
  28. package/app/assets/brand/characters/muted/pig.svg +1 -0
  29. package/app/assets/brand/characters/muted/poodle.svg +1 -0
  30. package/app/assets/brand/characters/muted/raccoon.svg +1 -0
  31. package/app/assets/brand/characters/muted/seal.svg +1 -0
  32. package/app/assets/brand/characters/muted/sheep.svg +1 -0
  33. package/app/assets/brand/characters/muted/snail.svg +1 -0
  34. package/app/assets/brand/characters/muted/turtle.svg +1 -0
  35. package/app/assets/brand/characters/muted/whale.svg +1 -0
  36. package/app/assets/brand/logo/favicon.svg +1 -0
  37. package/app/assets/brand/logo/logo-primary-reversed.svg +1 -0
  38. package/app/assets/brand/logo/logo-primary.svg +1 -0
  39. package/app/assets/brand/logo/mascot-reversed.svg +1 -0
  40. package/app/assets/brand/logo/mascot.svg +1 -0
  41. package/app/assets/brand/logo/wordmark-reversed.svg +1 -0
  42. package/app/assets/brand/logo/wordmark.svg +1 -0
  43. package/app/assets/css/cms-admin.css +607 -0
  44. package/app/components/CmsBlocks.vue +30 -0
  45. package/app/components/CmsCell.vue +16 -0
  46. package/app/components/CmsCellBadge.vue +18 -0
  47. package/app/components/CmsCellBlocks.vue +9 -0
  48. package/app/components/CmsCellBoolean.vue +12 -0
  49. package/app/components/CmsCellCode.vue +7 -0
  50. package/app/components/CmsCellColor.vue +13 -0
  51. package/app/components/CmsCellDate.vue +10 -0
  52. package/app/components/CmsCellExcerpt.vue +21 -0
  53. package/app/components/CmsCellGallery.vue +10 -0
  54. package/app/components/CmsCellGroup.vue +23 -0
  55. package/app/components/CmsCellNumber.vue +7 -0
  56. package/app/components/CmsCellRelation.vue +8 -0
  57. package/app/components/CmsCellText.vue +12 -0
  58. package/app/components/CmsCellThumb.vue +18 -0
  59. package/app/components/CmsConfirmDialog.vue +55 -0
  60. package/app/components/CmsContent.vue +103 -0
  61. package/app/components/CmsDayPicker.vue +44 -0
  62. package/app/components/CmsEmptyState.vue +35 -0
  63. package/app/components/CmsField.vue +111 -0
  64. package/app/components/CmsFieldBlocks.vue +353 -0
  65. package/app/components/CmsFieldBoolean.vue +8 -0
  66. package/app/components/CmsFieldColor.vue +42 -0
  67. package/app/components/CmsFieldDate.vue +131 -0
  68. package/app/components/CmsFieldGallery.vue +114 -0
  69. package/app/components/CmsFieldGroup.vue +53 -0
  70. package/app/components/CmsFieldMedia.vue +219 -0
  71. package/app/components/CmsFieldNumber.vue +11 -0
  72. package/app/components/CmsFieldRelationMany.vue +54 -0
  73. package/app/components/CmsFieldRelationOne.vue +47 -0
  74. package/app/components/CmsFieldRichText.vue +45 -0
  75. package/app/components/CmsFieldSelect.vue +41 -0
  76. package/app/components/CmsFieldSlug.vue +46 -0
  77. package/app/components/CmsFieldText.vue +75 -0
  78. package/app/components/CmsFormSections.vue +150 -0
  79. package/app/components/CmsHighlight.vue +22 -0
  80. package/app/components/CmsImage.vue +39 -0
  81. package/app/components/CmsLinkPicker.vue +122 -0
  82. package/app/components/CmsLinkTarget.vue +35 -0
  83. package/app/components/CmsListFilters.vue +107 -0
  84. package/app/components/CmsLiveNotice.vue +64 -0
  85. package/app/components/CmsLoadError.vue +24 -0
  86. package/app/components/CmsMascot.vue +10 -0
  87. package/app/components/CmsMediaLibrary.vue +114 -0
  88. package/app/components/CmsMediaPreview.vue +34 -0
  89. package/app/components/CmsMediaThumb.vue +22 -0
  90. package/app/components/CmsMoment.vue +42 -0
  91. package/app/components/CmsNav.vue +39 -0
  92. package/app/components/CmsPage.vue +86 -0
  93. package/app/components/CmsPasswordInput.vue +22 -0
  94. package/app/components/CmsPresence.vue +29 -0
  95. package/app/components/CmsPreviewPanel.vue +131 -0
  96. package/app/components/CmsPublishReview.vue +102 -0
  97. package/app/components/CmsRevisions.vue +195 -0
  98. package/app/components/CmsRichTextEditor.vue +290 -0
  99. package/app/components/CmsSearch.vue +99 -0
  100. package/app/components/CmsSection.vue +20 -0
  101. package/app/components/CmsSingletonForm.vue +283 -0
  102. package/app/components/CmsStatusBadge.vue +21 -0
  103. package/app/components/CmsTime.vue +16 -0
  104. package/app/components/CmsTranslationRef.vue +27 -0
  105. package/app/components/CmsTreeList.vue +453 -0
  106. package/app/components/CmsUnsavedText.vue +34 -0
  107. package/app/components/CmsWordmark.vue +10 -0
  108. package/app/composables/useCmsAdminHead.ts +18 -0
  109. package/app/composables/useCmsCollab.ts +165 -0
  110. package/app/composables/useCmsConfirm.ts +39 -0
  111. package/app/composables/useCmsEntryActions.ts +75 -0
  112. package/app/composables/useCmsFocus.ts +13 -0
  113. package/app/composables/useCmsForm.ts +273 -0
  114. package/app/composables/useCmsI18n.ts +185 -0
  115. package/app/composables/useCmsLinkTargets.ts +84 -0
  116. package/app/composables/useCmsLive.ts +199 -0
  117. package/app/composables/useCmsSearch.ts +62 -0
  118. package/app/composables/useCmsSeo.ts +99 -0
  119. package/app/composables/useCmsSignedIn.ts +24 -0
  120. package/app/composables/useCmsUiLocale.ts +24 -0
  121. package/app/i18n/cs.ts +781 -0
  122. package/app/i18n/de.ts +781 -0
  123. package/app/i18n/en.ts +782 -0
  124. package/app/i18n/types.ts +22 -0
  125. package/app/layouts/admin.vue +224 -0
  126. package/app/layouts/cms-auth.vue +37 -0
  127. package/app/middleware/cms-api-not-a-page.global.ts +10 -0
  128. package/app/middleware/cms-auth.global.ts +16 -0
  129. package/app/pages/admin/[entity]/[id].vue +1109 -0
  130. package/app/pages/admin/[entity]/index.vue +733 -0
  131. package/app/pages/admin/account.vue +117 -0
  132. package/app/pages/admin/forgot.vue +50 -0
  133. package/app/pages/admin/index.vue +184 -0
  134. package/app/pages/admin/invite/[token].vue +73 -0
  135. package/app/pages/admin/login.vue +84 -0
  136. package/app/pages/admin/media.vue +494 -0
  137. package/app/pages/admin/privacy.vue +193 -0
  138. package/app/pages/admin/reset/[token].vue +52 -0
  139. package/app/pages/admin/setup.vue +87 -0
  140. package/app/pages/admin/styleguide.vue +261 -0
  141. package/app/pages/admin/team.vue +258 -0
  142. package/app/plugins/cmsLivePreview.client.ts +20 -0
  143. package/app/plugins/cmsSignedOut.client.ts +31 -0
  144. package/app/utils/cmsBlockType.ts +11 -0
  145. package/app/utils/cmsBrand.ts +38 -0
  146. package/app/utils/cmsDiff.ts +83 -0
  147. package/app/utils/cmsFetch.ts +7 -0
  148. package/app/utils/cmsFocusInvalid.ts +22 -0
  149. package/app/utils/cmsIssues.ts +128 -0
  150. package/app/utils/cmsJson.ts +28 -0
  151. package/app/utils/cmsMedia.ts +63 -0
  152. package/app/utils/cmsSections.ts +154 -0
  153. package/app/utils/cmsTime.ts +41 -0
  154. package/cli/backup.ts +713 -0
  155. package/cli/breaking.ts +174 -0
  156. package/cli/content-migrate.ts +239 -0
  157. package/cli/db.ts +86 -0
  158. package/cli/export.ts +336 -0
  159. package/cli/generate.ts +146 -0
  160. package/cli/import.ts +643 -0
  161. package/cli/index.ts +140 -0
  162. package/cli/links-convert.ts +291 -0
  163. package/cli/seed-engine.ts +705 -0
  164. package/cli/seed.ts +339 -0
  165. package/cli/status.ts +49 -0
  166. package/cli/tar.ts +304 -0
  167. package/cli/transfer.ts +677 -0
  168. package/cli/up.ts +27 -0
  169. package/cli/upgrade.ts +60 -0
  170. package/cli/versions.ts +60 -0
  171. package/forms/components/CmsForm.vue +186 -0
  172. package/forms/index.ts +203 -0
  173. package/forms/messages.ts +104 -0
  174. package/forms/retention.ts +48 -0
  175. package/forms/server/form.get.ts +12 -0
  176. package/forms/server/form.post.ts +109 -0
  177. package/forms/server/formSettings.ts +12 -0
  178. package/forms/server/forms.ts +127 -0
  179. package/module.ts +373 -0
  180. package/nuxt.config.ts +43 -0
  181. package/package.json +98 -3
  182. package/server/api/cms/[entity]/[id]/revisions/[rev].get.ts +19 -0
  183. package/server/api/cms/[entity]/[id]/revisions/index.get.ts +14 -0
  184. package/server/api/cms/[entity]/[id].delete.ts +52 -0
  185. package/server/api/cms/[entity]/[id].get.ts +21 -0
  186. package/server/api/cms/[entity]/[id].patch.ts +116 -0
  187. package/server/api/cms/[entity]/_export.get.ts +69 -0
  188. package/server/api/cms/[entity]/_move.post.ts +81 -0
  189. package/server/api/cms/[entity]/_order.post.ts +49 -0
  190. package/server/api/cms/[entity]/_tree.get.ts +41 -0
  191. package/server/api/cms/[entity]/index.get.ts +62 -0
  192. package/server/api/cms/[entity]/index.post.ts +38 -0
  193. package/server/api/cms/[entity]/options.get.ts +55 -0
  194. package/server/api/cms/_auth/accept.post.ts +33 -0
  195. package/server/api/cms/_auth/forgot.post.ts +39 -0
  196. package/server/api/cms/_auth/invite/[token].get.ts +18 -0
  197. package/server/api/cms/_auth/login.post.ts +42 -0
  198. package/server/api/cms/_auth/logout.post.ts +7 -0
  199. package/server/api/cms/_auth/me.get.ts +5 -0
  200. package/server/api/cms/_auth/me.patch.ts +32 -0
  201. package/server/api/cms/_auth/password.post.ts +29 -0
  202. package/server/api/cms/_auth/reset.post.ts +34 -0
  203. package/server/api/cms/_auth/setup.post.ts +46 -0
  204. package/server/api/cms/_auth/status.get.ts +18 -0
  205. package/server/api/cms/_collab/session.get.ts +30 -0
  206. package/server/api/cms/_collab/socket.ts +51 -0
  207. package/server/api/cms/_collab/unsaved.delete.ts +16 -0
  208. package/server/api/cms/_graph.get.ts +20 -0
  209. package/server/api/cms/_links/resolve.post.ts +17 -0
  210. package/server/api/cms/_links.get.ts +81 -0
  211. package/server/api/cms/_live.ts +30 -0
  212. package/server/api/cms/_media/[id]/usage.get.ts +14 -0
  213. package/server/api/cms/_media/[id].delete.ts +29 -0
  214. package/server/api/cms/_media/[id].get.ts +13 -0
  215. package/server/api/cms/_media/[id].patch.ts +64 -0
  216. package/server/api/cms/_media/exists.post.ts +15 -0
  217. package/server/api/cms/_media/img/[id]/[file].get.ts +42 -0
  218. package/server/api/cms/_media/index.get.ts +44 -0
  219. package/server/api/cms/_media/index.post.ts +147 -0
  220. package/server/api/cms/_media/raw/[...key].get.ts +85 -0
  221. package/server/api/cms/_media/raw/[...key].head.ts +2 -0
  222. package/server/api/cms/_overview.get.ts +87 -0
  223. package/server/api/cms/_preview.post.ts +17 -0
  224. package/server/api/cms/_privacy/delete.post.ts +14 -0
  225. package/server/api/cms/_privacy/export.post.ts +25 -0
  226. package/server/api/cms/_privacy/lookup.post.ts +27 -0
  227. package/server/api/cms/_search.get.ts +17 -0
  228. package/server/api/cms/_singleton/[name].get.ts +19 -0
  229. package/server/api/cms/_singleton/[name].put.ts +76 -0
  230. package/server/api/cms/_users/[id]/resend.post.ts +25 -0
  231. package/server/api/cms/_users/[id].delete.ts +21 -0
  232. package/server/api/cms/_users/[id].patch.ts +45 -0
  233. package/server/api/cms/_users/index.get.ts +28 -0
  234. package/server/api/cms/_users/index.post.ts +39 -0
  235. package/server/api/content/[entity]/[slug].get.ts +74 -0
  236. package/server/api/content/[entity]/index.get.ts +100 -0
  237. package/server/api/content/_global/[name].get.ts +23 -0
  238. package/server/api/content/_search.get.ts +28 -0
  239. package/server/api/content/_sitemap.get.ts +8 -0
  240. package/server/api/content/_tree/[entity].get.ts +31 -0
  241. package/server/api/content-types.ts.get.ts +17 -0
  242. package/server/api/health/live.get.ts +10 -0
  243. package/server/api/health/ready.get.ts +21 -0
  244. package/server/api/openapi.get.ts +48 -0
  245. package/server/api/openapi.json.get.ts +32 -0
  246. package/server/db/driver.ts +8 -0
  247. package/server/mail/mailer.ts +43 -0
  248. package/server/middleware/cms-0-headers.ts +37 -0
  249. package/server/middleware/cms-0-migrate-gate.ts +14 -0
  250. package/server/middleware/cms-csrf.ts +28 -0
  251. package/server/middleware/cms-limits.ts +20 -0
  252. package/server/middleware/cms-redirects.ts +21 -0
  253. package/server/middleware/cms-session.ts +41 -0
  254. package/server/middleware/cms-z-plugin-access.ts +15 -0
  255. package/server/plugins/cms-0-config-check.ts +35 -0
  256. package/server/plugins/cms-changes.ts +53 -0
  257. package/server/plugins/cms-content-etag.ts +21 -0
  258. package/server/plugins/cms-errors.ts +45 -0
  259. package/server/plugins/cms-migrate.ts +5 -0
  260. package/server/plugins/cms-plugins.ts +17 -0
  261. package/server/plugins/cms-search.ts +12 -0
  262. package/server/plugins/cms-setup-code.ts +15 -0
  263. package/server/routes/sitemap.xml.get.ts +25 -0
  264. package/server/store/redis.ts +95 -0
  265. package/server/store/types.ts +21 -0
  266. package/server/tasks/cms/retention.ts +10 -0
  267. package/server/tasks/cms/scheduled.ts +10 -0
  268. package/server/tasks/cms/search-reindex.ts +12 -0
  269. package/server/utils/cmsAudit.ts +29 -0
  270. package/server/utils/cmsAuth.ts +143 -0
  271. package/server/utils/cmsBlocks.ts +47 -0
  272. package/server/utils/cmsChanges.ts +222 -0
  273. package/server/utils/cmsCollab.ts +286 -0
  274. package/server/utils/cmsCollabServer.ts +451 -0
  275. package/server/utils/cmsCollate.ts +27 -0
  276. package/server/utils/cmsContent.ts +376 -0
  277. package/server/utils/cmsCrud.ts +361 -0
  278. package/server/utils/cmsCsv.ts +24 -0
  279. package/server/utils/cmsDb.ts +23 -0
  280. package/server/utils/cmsDemo.ts +36 -0
  281. package/server/utils/cmsEmails.ts +125 -0
  282. package/server/utils/cmsErrors.ts +40 -0
  283. package/server/utils/cmsFold.ts +17 -0
  284. package/server/utils/cmsImageSizes.ts +51 -0
  285. package/server/utils/cmsJson.ts +6 -0
  286. package/server/utils/cmsLinkAddress.ts +50 -0
  287. package/server/utils/cmsLinks.ts +248 -0
  288. package/server/utils/cmsListQuery.ts +93 -0
  289. package/server/utils/cmsLive.ts +393 -0
  290. package/server/utils/cmsLocales.ts +96 -0
  291. package/server/utils/cmsMail.ts +28 -0
  292. package/server/utils/cmsMediaGc.ts +188 -0
  293. package/server/utils/cmsMediaKeys.ts +62 -0
  294. package/server/utils/cmsMigrate.ts +86 -0
  295. package/server/utils/cmsPreviewDraft.ts +72 -0
  296. package/server/utils/cmsPrivacy.ts +176 -0
  297. package/server/utils/cmsPublished.ts +57 -0
  298. package/server/utils/cmsRange.ts +38 -0
  299. package/server/utils/cmsRateLimit.ts +82 -0
  300. package/server/utils/cmsRedirects.ts +160 -0
  301. package/server/utils/cmsRetention.ts +61 -0
  302. package/server/utils/cmsRevisions.ts +103 -0
  303. package/server/utils/cmsScheduler.ts +45 -0
  304. package/server/utils/cmsScrub.ts +107 -0
  305. package/server/utils/cmsSearch.ts +354 -0
  306. package/server/utils/cmsSession.ts +102 -0
  307. package/server/utils/cmsSetupCode.ts +97 -0
  308. package/server/utils/cmsSitemap.ts +176 -0
  309. package/server/utils/cmsStorage.ts +580 -0
  310. package/server/utils/cmsStore.ts +109 -0
  311. package/server/utils/cmsTiming.ts +14 -0
  312. package/server/utils/cmsTooMany.ts +9 -0
  313. package/server/utils/cmsTranslationWrite.ts +186 -0
  314. package/server/utils/cmsTree.ts +251 -0
  315. package/server/utils/cmsTreeAddress.ts +65 -0
  316. package/server/utils/cmsUpload.ts +228 -0
  317. package/server/utils/cmsWebhooks.ts +104 -0
  318. package/shared/json.ts +11 -0
  319. package/shared/richtext-editor.ts +56 -0
  320. package/shared/richtext-normalize.ts +33 -0
  321. package/shared/richtext-paste.ts +151 -0
  322. package/shared/storage-delivery.ts +53 -0
  323. package/src/blocks.ts +624 -0
  324. package/src/changes.ts +54 -0
  325. package/src/content-shape.ts +340 -0
  326. package/src/deprecate.ts +64 -0
  327. package/src/descriptor.ts +149 -0
  328. package/src/docs.ts +27 -0
  329. package/src/emitter.ts +94 -0
  330. package/src/entity.ts +624 -0
  331. package/src/errorReport.ts +41 -0
  332. package/src/fields.ts +465 -0
  333. package/src/i18n.ts +26 -0
  334. package/src/index.ts +54 -0
  335. package/src/linkref.ts +31 -0
  336. package/src/links.ts +179 -0
  337. package/src/locales.ts +39 -0
  338. package/src/media.ts +48 -0
  339. package/src/migrate.ts +236 -0
  340. package/src/openapi.ts +377 -0
  341. package/src/paths.ts +88 -0
  342. package/src/plugin.ts +505 -0
  343. package/src/presets.ts +230 -0
  344. package/src/richtext.ts +88 -0
  345. package/src/sdk.ts +181 -0
  346. package/src/search.ts +312 -0
  347. package/src/seed.ts +225 -0
  348. package/src/setupCode.ts +30 -0
  349. package/src/system.ts +219 -0
  350. package/src/tree.ts +421 -0
  351. package/src/upgrades.ts +137 -0
  352. package/starter/.env.example +10 -0
  353. package/starter/README.md +65 -0
  354. package/starter/app/app.config.ts +10 -0
  355. package/starter/app/app.vue +12 -0
  356. package/starter/app/assets/css/main.css +15 -0
  357. package/starter/app/components/global/BlockContact.vue +15 -0
  358. package/starter/app/components/global/BlockCta.vue +15 -0
  359. package/starter/app/components/global/BlockHero.vue +23 -0
  360. package/starter/app/components/global/BlockImage.vue +13 -0
  361. package/starter/app/components/global/BlockText.vue +12 -0
  362. package/starter/app/composables/useSite.ts +77 -0
  363. package/starter/app/error.vue +28 -0
  364. package/starter/app/layouts/default.vue +106 -0
  365. package/starter/app/lib/cms-content.ts +152 -0
  366. package/starter/app/pages/[...slug].vue +66 -0
  367. package/starter/app/pages/hledat.vue +59 -0
  368. package/starter/app/pages/index.vue +20 -0
  369. package/starter/cms.config.ts +137 -0
  370. package/starter/compose.yaml +15 -0
  371. package/starter/drizzle.config.ts +8 -0
  372. package/starter/gitignore.txt +8 -0
  373. package/starter/nuxt.config.ts +13 -0
  374. package/starter/package.json +38 -0
  375. package/starter/scripts/typecheck.mjs +38 -0
  376. package/starter/seed/index.ts +297 -0
  377. package/starter/seed/media/about.jpg +0 -0
  378. package/starter/seed/media/hero.jpg +0 -0
  379. package/starter/seed/media/logo.png +0 -0
  380. package/starter/seed/media/news-bread.jpg +0 -0
  381. package/starter/seed/media/news-morning.jpg +0 -0
  382. package/starter/server/db/migrations/0000_init.sql +269 -0
  383. package/starter/server/db/migrations/0001_page_tree.sql +5 -0
  384. package/starter/server/db/migrations/0002_opening_hours_per_language.sql +1 -0
  385. package/starter/server/db/migrations/meta/0000_snapshot.json +1890 -0
  386. package/starter/server/db/migrations/meta/0001_snapshot.json +1887 -0
  387. package/starter/server/db/migrations/meta/0002_snapshot.json +1893 -0
  388. package/starter/server/db/migrations/meta/_journal.json +27 -0
  389. package/starter/server/db/schema.ts +253 -0
  390. package/starter/server/plugins/sitemap.ts +11 -0
  391. package/starter/server/routes/robots.txt.get.ts +12 -0
  392. package/starter/tsconfig.json +9 -0
package/cli/up.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * `tinyzoo up`: apply the site's migrations and tinyzoo's upgrade steps to the database in
3
+ * DATABASE_URL — the same runner (and the same bookkeeping) as the app's start-up
4
+ * migrations, so either can take over from the other.
5
+ */
6
+ import { MigrationOrderError, runUpgrade } from '../src/index'
7
+ import { databaseUrl, describeDatabase, diskSource, errorText, siteUpgradeSteps, withDatabase } from './db'
8
+
9
+ /** Returns the process exit code. */
10
+ export async function up(cwd: string): Promise<number> {
11
+ try {
12
+ const url = databaseUrl(cwd)
13
+ const source = diskSource(cwd)
14
+ const steps = await siteUpgradeSteps(cwd)
15
+ const result = await withDatabase(url, ({ transaction }) => runUpgrade(source, transaction, steps))
16
+ const ran = result.steps.filter((s) => s.ran).map((s) => s.id)
17
+ if (ran.length) console.log(`✓ ran upgrade steps: ${ran.join(', ')}`)
18
+ console.log(result.migrations.length
19
+ ? `✓ applied migrations on ${describeDatabase(url)}: ${result.migrations.join(', ')}`
20
+ : `✓ ${describeDatabase(url)} is up to date`)
21
+ return 0
22
+ }
23
+ catch (err) {
24
+ console.error(err instanceof MigrationOrderError ? `✗ ${err.message}` : `✗ ${errorText(err)}`)
25
+ return 1
26
+ }
27
+ }
package/cli/upgrade.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * `tinyzoo upgrade`: after `pnpm up tinyzoo @tinyzoo/client` — check the site's versions
3
+ * against what this tinyzoo wants, generate the migration (with the breaking-statement
4
+ * guard), regenerate the typed client, and show what the database still has to apply.
5
+ */
6
+ import { docsUrl } from '../src/docs'
7
+ import { execFileSync } from 'node:child_process'
8
+ import { existsSync, readFileSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+ import { checkVersions } from './versions'
11
+ import { status } from './status'
12
+
13
+ export interface UpgradeDeps {
14
+ /** Emit schema.ts and generate the migration (with the guard). Returns an exit code. */
15
+ generate: () => Promise<number>
16
+ }
17
+
18
+ /** Returns the process exit code. */
19
+ export async function upgrade(cwd: string, pkgDir: string, deps: UpgradeDeps): Promise<number> {
20
+ const own = JSON.parse(readFileSync(join(pkgDir, 'package.json'), 'utf8'))
21
+ console.log(`tinyzoo ${own.version}\n`)
22
+
23
+ console.log('1. Versions')
24
+ const problems = checkVersions(cwd, own)
25
+ if (!problems.length) console.log(' ✓ nuxt, @nuxt/ui, drizzle-orm and zod fit this tinyzoo')
26
+ for (const p of problems) {
27
+ console.warn(` ⚠ ${p.name}: ${p.installed ? `${p.installed} is installed` : 'not installed'}, tinyzoo ${own.version} wants ${p.wanted} — update it (\`pnpm up ${p.name}\`) before deploying`)
28
+ }
29
+
30
+ console.log('\n2. Schema and migration')
31
+ const code = await deps.generate()
32
+ if (code !== 0) {
33
+ console.error('\n✗ Stopped: fix the above and run `tinyzoo upgrade` again.')
34
+ return code
35
+ }
36
+
37
+ const pkgPath = join(cwd, 'package.json')
38
+ const hostScripts = existsSync(pkgPath) ? JSON.parse(readFileSync(pkgPath, 'utf8')).scripts ?? {} : {}
39
+ if (hostScripts['cms:client']) {
40
+ console.log('\n3. Typed client')
41
+ try {
42
+ execFileSync('pnpm', ['run', 'cms:client'], { cwd, stdio: 'inherit' })
43
+ }
44
+ catch {
45
+ console.error('\n✗ `pnpm run cms:client` failed.')
46
+ return 1
47
+ }
48
+ }
49
+
50
+ console.log('\n4. Database')
51
+ const statusCode = await status(cwd)
52
+ if (statusCode === 2) console.log(' (Could not check the database from here. Run `tinyzoo status` where DATABASE_URL points at it.)')
53
+
54
+ console.log(`\nNext:
55
+ 1. Read the new migration in server/db/migrations — that is the change your database will get.
56
+ 2. pnpm typecheck, then commit the migration, schema.ts and the typed client together with the package update.
57
+ 3. Deploy. The app migrates itself at start (NUXT_CMS_MIGRATIONS_ON_START=true), or run \`tinyzoo up\` yourself.
58
+ Details: ${docsUrl('upgrading')}`)
59
+ return 0
60
+ }
@@ -0,0 +1,60 @@
1
+ /** Version checks for `tinyzoo upgrade`: does the site's own nuxt, @nuxt/ui, drizzle-orm and zod fit? */
2
+ import { existsSync, readFileSync } from 'node:fs'
3
+ import { dirname, join, parse } from 'node:path'
4
+
5
+ export const CHECKED_PACKAGES = ['nuxt', '@nuxt/ui', 'drizzle-orm', 'zod'] as const
6
+
7
+ const parseVersion = (v: string): [number, number, number] | null => {
8
+ const m = /^[v=\s]*(\d+)(?:\.(\d+|x|\*))?(?:\.(\d+|x|\*))?/.exec(v)
9
+ return m ? [Number(m[1]), m[2] && /^\d+$/.test(m[2]) ? Number(m[2]) : 0, m[3] && /^\d+$/.test(m[3]) ? Number(m[3]) : 0] : null
10
+ }
11
+ const cmp = (a: number[], b: number[]) => a[0]! - b[0]! || a[1]! - b[1]! || a[2]! - b[2]!
12
+
13
+ /** The common range forms: `^1.2.3`, `~1.2.3`, `>=1.2.3`, `1.2.3`, `1.x`, `*`, joined by `||`. */
14
+ export function satisfiesRange(version: string, range: string): boolean {
15
+ const v = parseVersion(version)
16
+ if (!v) return false
17
+ return range.split('||').some((alt) => {
18
+ const r = alt.trim()
19
+ if (!r || r === '*' || r === 'x') return true
20
+ const [, op = '', rest = ''] = /^([\^~]|>=|>|<=|<|=)?\s*(.*)$/.exec(r) ?? []
21
+ const base = parseVersion(rest)
22
+ if (!base) return false
23
+ if (op === '>=') return cmp(v, base) >= 0
24
+ if (op === '>') return cmp(v, base) > 0
25
+ if (op === '<=') return cmp(v, base) <= 0
26
+ if (op === '<') return cmp(v, base) < 0
27
+ if (op === '^') {
28
+ // Compatible with the leftmost non-zero part: ^1.2.3 → <2.0.0, ^0.44.0 → <0.45.0, ^0.0.3 → <0.0.4.
29
+ const upper = base[0] ? [base[0] + 1, 0, 0] : base[1] ? [0, base[1] + 1, 0] : [0, 0, base[2]! + 1]
30
+ return cmp(v, base) >= 0 && cmp(v, upper) < 0
31
+ }
32
+ if (op === '~') return cmp(v, base) >= 0 && cmp(v, [base[0]!, base[1]! + 1, 0]) < 0
33
+ // Exact, or a partial like "1.x" / "1.2".
34
+ const parts = rest.split('.')
35
+ return parts.every((p, i) => p === 'x' || p === '*' || Number(p) === v[i])
36
+ })
37
+ }
38
+
39
+ /** The version of a package as the site has it installed, or null. Walks up for hoisted installs. */
40
+ export function installedVersion(cwd: string, name: string): string | null {
41
+ for (let dir = cwd; ; dir = dirname(dir)) {
42
+ const file = join(dir, 'node_modules', name, 'package.json')
43
+ if (existsSync(file)) return JSON.parse(readFileSync(file, 'utf8')).version ?? null
44
+ if (dir === parse(dir).root) return null
45
+ }
46
+ }
47
+
48
+ export interface VersionProblem { name: string; installed: string | null; wanted: string }
49
+
50
+ /** Installed versions that do not fit what tinyzoo asks for (not installed counts too). */
51
+ export function checkVersions(cwd: string, tinyzooPackage: { peerDependencies?: Record<string, string>; dependencies?: Record<string, string> }): VersionProblem[] {
52
+ const problems: VersionProblem[] = []
53
+ for (const name of CHECKED_PACKAGES) {
54
+ const wanted = tinyzooPackage.peerDependencies?.[name] ?? tinyzooPackage.dependencies?.[name]
55
+ if (!wanted) continue
56
+ const installed = installedVersion(cwd, name)
57
+ if (!installed || !satisfiesRange(installed, wanted)) problems.push({ name, installed, wanted })
58
+ }
59
+ return problems
60
+ }
@@ -0,0 +1,186 @@
1
+ <script setup lang="ts">
2
+ // A website form from the CMS (defineForm), for the host site's pages:
3
+ //
4
+ // <CmsForm name="contactForm" /> // fields, labels and messages from cms.config
5
+ // <CmsForm name="contactForm" locale="en" class="my-form" />
6
+ //
7
+ // Plain HTML (label, input, textarea, select, a button) with default styles in the base
8
+ // layer that follow the text colour (light or dark page), so the site's own CSS wins without
9
+ // fighting. Required fields carry a *, a choice with a default starts on it. Errors show per
10
+ // field, in the visitor's language (the server words them); the thank-you message replaces
11
+ // the form (slot `success`).
12
+ // Spam: a hidden field, the time the form was open, and Cloudflare Turnstile when the
13
+ // site key is configured.
14
+ const props = defineProps<{ name: string; locale?: string }>()
15
+ const emit = defineEmits<{ sent: [] }>()
16
+
17
+ // The site's language for this form (the CMS's default language when not given).
18
+ const locale = computed(() => props.locale || undefined)
19
+ const { data: schema, error: loadError } = await useFetch<any>(() => `/api/content/_form/${props.name}`, {
20
+ query: { locale }, key: `cms-form-${props.name}-${props.locale ?? ''}`,
21
+ })
22
+
23
+ const values = reactive<Record<string, any>>({})
24
+ // A choice with a default starts on it (and has no empty option to go back to).
25
+ watch(schema, (s) => {
26
+ for (const f of s?.fields ?? []) if (f.default != null && values[f.key] === undefined) values[f.key] = f.default
27
+ }, { immediate: true })
28
+ const errors = reactive<Record<string, string>>({})
29
+ const sending = ref(false)
30
+ const sent = ref(false)
31
+ const failure = ref('')
32
+ const openedAt = ref(0)
33
+ const formEl = ref<HTMLFormElement | null>(null)
34
+ onMounted(() => {
35
+ openedAt.value = Date.now()
36
+ const key = schema.value?.turnstileSiteKey
37
+ if (key && !document.querySelector('script[data-cms-turnstile]')) {
38
+ const s = document.createElement('script')
39
+ s.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js'
40
+ s.async = true
41
+ s.defer = true
42
+ s.dataset.cmsTurnstile = ''
43
+ document.head.appendChild(s)
44
+ }
45
+ })
46
+
47
+ // The form's own messages in the website's language (Czech, English or German; English otherwise).
48
+ // What is wrong with a field comes from the server, already in the visitor's language.
49
+ const MESSAGES = {
50
+ cs: {
51
+ invalid: 'Zkontrolujte prosím tuto hodnotu.',
52
+ failed: 'Odeslání se nepovedlo. Zkuste to prosím znovu.', tooMany: 'Odeslali jste toho hodně najednou. Zkuste to prosím za pár minut.',
53
+ },
54
+ en: {
55
+ invalid: 'Please check this value.',
56
+ failed: 'Sending failed. Please try again.', tooMany: 'That was a lot at once. Please try again in a few minutes.',
57
+ },
58
+ de: {
59
+ invalid: 'Bitte prüfen Sie diesen Wert.',
60
+ failed: 'Das Senden hat nicht geklappt. Bitte versuchen Sie es noch einmal.', tooMany: 'Das war viel auf einmal. Bitte versuchen Sie es in ein paar Minuten noch einmal.',
61
+ },
62
+ }
63
+ const lang = computed(() => (locale.value ?? schema.value?.locale ?? 'en').split('-')[0] as keyof typeof MESSAGES)
64
+ const msg = (k: keyof typeof MESSAGES.en) => (MESSAGES[lang.value] ?? MESSAGES.en)[k]
65
+
66
+ const fid = (key: string) => `cms-form-${props.name}-${key}`
67
+
68
+ async function submit() {
69
+ if (sending.value || !schema.value) return
70
+ failure.value = ''
71
+ for (const k of Object.keys(errors)) delete errors[k]
72
+ const body: Record<string, any> = { _locale: lang.value, _t: Date.now() - openedAt.value, _hp: (formEl.value?.elements.namedItem('website') as HTMLInputElement | null)?.value ?? '' }
73
+ for (const f of schema.value.fields) {
74
+ const v = values[f.key]
75
+ // An unchosen option is "nothing", not an empty text (which no option matches).
76
+ body[f.key] = f.type === 'select' ? (v || null) : v ?? (f.type === 'boolean' ? false : '')
77
+ }
78
+ const turnstile = formEl.value?.querySelector<HTMLInputElement>('input[name="cf-turnstile-response"]')
79
+ if (turnstile) body['cf-turnstile-response'] = turnstile.value
80
+ sending.value = true
81
+ try {
82
+ // Someone quick (autofill + Enter) waits a moment instead of looking like a robot.
83
+ const wait = 1600 - (Date.now() - openedAt.value)
84
+ if (wait > 0) await new Promise((r) => setTimeout(r, wait))
85
+ body._t = Date.now() - openedAt.value
86
+ await $fetch(`/api/content/_form/${props.name}`, { method: 'POST', body })
87
+ sent.value = true
88
+ emit('sent')
89
+ }
90
+ catch (err: any) {
91
+ const issues = Array.isArray(err?.data?.data) ? err.data.data : []
92
+ for (const i of issues) {
93
+ const key = String(i?.path?.[0] ?? '')
94
+ if (!key) continue
95
+ errors[key] = typeof i?.message === 'string' && i.message ? i.message : msg('invalid')
96
+ }
97
+ if (!issues.length) failure.value = err?.statusCode === 429 ? msg('tooMany') : msg('failed')
98
+ nextTick(() => formEl.value?.querySelector<HTMLElement>('[aria-invalid="true"]')?.focus())
99
+ }
100
+ finally {
101
+ sending.value = false
102
+ }
103
+ }
104
+ </script>
105
+
106
+ <template>
107
+ <div v-if="schema" class="cms-form">
108
+ <div v-if="sent" class="cms-form__success" role="status">
109
+ <slot name="success" :message="schema.successMessage">
110
+ <p>{{ schema.successMessage }}</p>
111
+ </slot>
112
+ </div>
113
+ <form v-else ref="formEl" novalidate :aria-label="schema.label" @submit.prevent="submit">
114
+ <div v-for="f in schema.fields" :key="f.key" class="cms-form__field" :class="`cms-form__field--${f.type}`">
115
+ <template v-if="f.type === 'boolean'">
116
+ <label class="cms-form__check">
117
+ <input :id="fid(f.key)" v-model="values[f.key]" type="checkbox" :name="f.key" :required="f.required" :aria-required="f.required || undefined" :aria-invalid="!!errors[f.key]" :aria-describedby="errors[f.key] ? `${fid(f.key)}-error` : undefined">
118
+ <span>{{ f.label }}<span v-if="f.required" aria-hidden="true"> *</span></span>
119
+ </label>
120
+ </template>
121
+ <template v-else>
122
+ <label :for="fid(f.key)" class="cms-form__label">{{ f.label }}<span v-if="f.required" aria-hidden="true"> *</span></label>
123
+ <textarea
124
+ v-if="f.type === 'text' && f.multiline" :id="fid(f.key)" v-model="values[f.key]" :name="f.key" rows="5" :required="f.required" :maxlength="f.max ?? undefined"
125
+ :aria-invalid="!!errors[f.key]" :aria-describedby="errors[f.key] ? `${fid(f.key)}-error` : f.help ? `${fid(f.key)}-help` : undefined"
126
+ />
127
+ <select
128
+ v-else-if="f.type === 'select'" :id="fid(f.key)" v-model="values[f.key]" :name="f.key" :required="f.required"
129
+ :aria-invalid="!!errors[f.key]" :aria-describedby="errors[f.key] ? `${fid(f.key)}-error` : f.help ? `${fid(f.key)}-help` : undefined"
130
+ >
131
+ <!-- a choice with a default has no empty option; a required one has an empty one nobody can send; an optional one may stay empty -->
132
+ <option v-if="f.default == null" value="" :disabled="f.required" :selected="!values[f.key]">—</option>
133
+ <option v-for="o in f.options" :key="o.value" :value="o.value">{{ o.label }}</option>
134
+ </select>
135
+ <input
136
+ v-else :id="fid(f.key)" v-model="values[f.key]" :name="f.key" :required="f.required" :maxlength="f.max ?? undefined"
137
+ :type="f.type === 'number' ? 'number' : f.type === 'datetime' ? 'date' : f.format === 'email' ? 'email' : f.format === 'url' ? 'url' : 'text'"
138
+ :autocomplete="f.format === 'email' ? 'email' : f.key === 'name' ? 'name' : f.key === 'phone' ? 'tel' : undefined"
139
+ :aria-invalid="!!errors[f.key]" :aria-describedby="errors[f.key] ? `${fid(f.key)}-error` : f.help ? `${fid(f.key)}-help` : undefined"
140
+ >
141
+ </template>
142
+ <p v-if="f.help && !errors[f.key]" :id="`${fid(f.key)}-help`" class="cms-form__help">{{ f.help }}</p>
143
+ <p v-if="errors[f.key]" :id="`${fid(f.key)}-error`" class="cms-form__error">{{ errors[f.key] }}</p>
144
+ </div>
145
+ <!-- people never see or fill this; robots do -->
146
+ <div class="cms-form__hp" aria-hidden="true">
147
+ <label>Website <input type="text" name="website" tabindex="-1" autocomplete="off"></label>
148
+ </div>
149
+ <div v-if="schema.turnstileSiteKey" class="cf-turnstile" :data-sitekey="schema.turnstileSiteKey" />
150
+ <p v-if="failure" class="cms-form__error" role="alert">{{ failure }}</p>
151
+ <button type="submit" class="cms-form__submit" :disabled="sending" :aria-busy="sending">{{ schema.submitLabel }}</button>
152
+ </form>
153
+ </div>
154
+ <p v-else-if="loadError" class="cms-form__error">{{ msg('failed') }}</p>
155
+ </template>
156
+
157
+ <style>
158
+ /* Defaults only, in the base layer: they beat the browser's and Tailwind's resets (one
159
+ class), and any class, utility or unlayered CSS of the site's own wins over them. Colours
160
+ follow the text colour (currentColor), so the form reads on a light and on a dark page. */
161
+ @layer base {
162
+ .cms-form form { display: grid; gap: 1rem; }
163
+ .cms-form__field { display: grid; gap: 0.375rem; }
164
+ .cms-form__label { font-weight: 500; }
165
+ .cms-form input:not([type='checkbox']), .cms-form textarea, .cms-form select {
166
+ width: 100%; padding: 0.5rem 0.75rem; border: 1px solid color-mix(in srgb, currentColor 35%, transparent); border-radius: 0.375rem;
167
+ font: inherit; background: transparent; color: inherit;
168
+ }
169
+ .cms-form option { background: Canvas; color: CanvasText; }
170
+ .cms-form :is(input, textarea, select):focus-visible { outline: 2px solid currentColor; outline-offset: 1px; }
171
+ /* More specific than the field rule above (which also matches an input), so a refused field is red. */
172
+ .cms-form .cms-form__field [aria-invalid='true'] { border-color: var(--cms-form-error, color-mix(in srgb, #d93025 75%, currentColor)); }
173
+ .cms-form .cms-form__field input[type='checkbox'][aria-invalid='true'] { outline: 2px solid var(--cms-form-error, color-mix(in srgb, #d93025 75%, currentColor)); outline-offset: 2px; }
174
+ .cms-form__check { display: flex; gap: 0.5rem; align-items: flex-start; }
175
+ .cms-form__help { font-size: 0.875em; opacity: 0.75; }
176
+ .cms-form__error { font-size: 0.875em; color: var(--cms-form-error, color-mix(in srgb, #d93025 75%, currentColor)); }
177
+ .cms-form__submit {
178
+ justify-self: start; padding: 0.625rem 1.25rem; border: 1.5px solid currentColor; border-radius: 0.375rem;
179
+ background: color-mix(in srgb, currentColor 8%, transparent); color: inherit; font: inherit; font-weight: 600; cursor: pointer;
180
+ }
181
+ .cms-form__submit:hover { background: color-mix(in srgb, currentColor 16%, transparent); }
182
+ .cms-form__submit:focus-visible { outline: 2px solid currentColor; outline-offset: 2px; }
183
+ .cms-form__submit[disabled] { opacity: 0.6; cursor: progress; }
184
+ .cms-form__hp { position: absolute; left: -10000px; width: 1px; height: 1px; overflow: hidden; }
185
+ }
186
+ </style>
package/forms/index.ts ADDED
@@ -0,0 +1,203 @@
1
+ /**
2
+ * Website forms, as a plugin (`tinyzoo/forms`): visitors fill in a form, every submission
3
+ * lands in the admin as an entry, and editors are told by email.
4
+ *
5
+ * // cms.config.ts
6
+ * import { defineForm, defineFormSettings, formsPlugin } from 'tinyzoo/forms'
7
+ *
8
+ * export const plugins = [formsPlugin()]
9
+ * export const ContactForm = defineForm('contactForm', { label: 'Contact form', fields: { … } })
10
+ * export const FormSettings = defineFormSettings()
11
+ * // on a page: <CmsForm name="contactForm" />
12
+ *
13
+ * What the plugin brings: the endpoints `GET/POST /api/content/_form/:name` (spam checks,
14
+ * rate limits, Turnstile, notifications), the `<CmsForm>` component, the retention of
15
+ * submissions (`retentionDays`) and the admin's form bits (no "New" button, the retention
16
+ * note under the list). The forms and the settings stay the site's own entities: the
17
+ * tables and their names are exactly what `defineForm` has always made.
18
+ *
19
+ * `defineForm` and `defineFormSettings` are also exported from `tinyzoo`, deprecated:
20
+ * they still work, register this plugin by themselves and say so once.
21
+ */
22
+ import { defineEntity, defineSingleton, type EntityDef } from '../src/entity'
23
+ import { f } from '../src/fields'
24
+ import type { LocalizedText } from '../src/i18n'
25
+ import { defineCmsPlugin, pluginFile, type CmsPlugin, type CmsPluginRequirement } from '../src/plugin'
26
+ import pkg from '../package.json'
27
+ import { retainForms } from './retention'
28
+
29
+ /**
30
+ * Who may read a form's messages (list, open, export, search) and the recipients in the
31
+ * Forms settings, unless the site says otherwise with `defineForm({ access })`: administrators
32
+ * and editors. Messages are personal data of people who are not users of the site — an
33
+ * author, who writes posts, has no business reading them. (A custom role of an external
34
+ * sign-in gets no access either, until the form's `access.read` names it.)
35
+ */
36
+ export const formsReadAccess: NonNullable<EntityDef<any>['access']>['read'] = ({ user }) => user?.role === 'admin' || user?.role === 'editor'
37
+
38
+ /** Field types a visitor can fill in on a website form. */
39
+ export const FORM_FIELD_TYPES = new Set(['text', 'number', 'boolean', 'select', 'datetime'])
40
+
41
+ export interface FormOptions<F extends Record<string, any>> {
42
+ /** The form's name in the admin ("Contact form", { cs: 'Kontaktní formulář' }). */
43
+ label: LocalizedText
44
+ /** One submission ("Message"); the list of submissions is labelled with `label`. */
45
+ labelSingular?: LocalizedText
46
+ description?: LocalizedText
47
+ /** What visitors fill in: text (also `format: 'email'`, `multiline`), number, yes/no, a choice, a date. */
48
+ fields: F
49
+ /** The field that names a submission in the list (default: the first text field). */
50
+ titleField?: keyof F & string
51
+ /** The button under the form on the website. */
52
+ submitLabel?: LocalizedText
53
+ /** Shown after sending. */
54
+ successMessage?: LocalizedText
55
+ /**
56
+ * Who is told about a new submission, by email. Addresses set by editors in the
57
+ * Forms settings (defineFormSettings) come first; these are the fallback.
58
+ */
59
+ notify?: { to?: string[] }
60
+ /**
61
+ * Delete a submission this many days after it arrived (a scheduled task does it, daily;
62
+ * the admin says so under the list). Default: keep them until someone deletes them.
63
+ * Set it to what the site's privacy policy promises.
64
+ */
65
+ retentionDays?: number
66
+ /**
67
+ * Who may read, change and delete the messages. By default only administrators and
68
+ * editors read them (authors do not, whatever else they may do): write a rule to widen
69
+ * or narrow that, the same rules entities have everywhere:
70
+ *
71
+ * access: { read: ({ user }) => user.role !== 'author' || user.id === '…' }
72
+ *
73
+ * A rule given here for `read` replaces the default; `update` and `delete` narrow what the
74
+ * roles allow, as always. It decides the list, a message, the CSV export, search and the
75
+ * form's place in the admin menu.
76
+ */
77
+ access?: EntityDef<F>['access']
78
+ }
79
+
80
+ /** What an entity made by this plugin's helpers says about the plugin it needs. */
81
+ export const FORMS_REQUIREMENT: CmsPluginRequirement = {
82
+ plugin: 'forms',
83
+ hint: 'add `export const plugins = [formsPlugin()]` to cms.config.ts (`import { formsPlugin } from \'tinyzoo/forms\'`).',
84
+ }
85
+
86
+ /**
87
+ * A form on the website (contact, sign-up, order): visitors fill it in, every
88
+ * submission lands in the admin as an entry of this collection, and editors are told
89
+ * by email. Spam is kept out by a hidden field, a minimum time to fill it in, a rate
90
+ * limit per visitor and, when configured, Cloudflare Turnstile.
91
+ *
92
+ * export const ContactForm = defineForm('contactForm', {
93
+ * label: { en: 'Contact form', cs: 'Kontaktní formulář' },
94
+ * fields: {
95
+ * name: f.text({ required: true }).label({ en: 'Name', cs: 'Jméno' }),
96
+ * email: f.text({ required: true, format: 'email' }).label({ en: 'Email', cs: 'E-mail' }),
97
+ * message: f.text({ required: true, multiline: true, max: 5000 }).label({ en: 'Message', cs: 'Zpráva' }),
98
+ * },
99
+ * })
100
+ * // on the website: <CmsForm name="contactForm" />
101
+ * // or POST /api/content/_form/contactForm { name, email, message }
102
+ *
103
+ * Needs `formsPlugin()` in the site's `plugins`.
104
+ */
105
+ export function defineForm<F extends Record<string, any>>(name: string, opts: FormOptions<F>) {
106
+ if (opts.retentionDays !== undefined && (!Number.isInteger(opts.retentionDays) || opts.retentionDays < 1)) {
107
+ throw new Error(`Form "${name}": retentionDays must be a whole number of days, at least 1 (leave it out to keep submissions).`)
108
+ }
109
+ for (const [key, fld] of Object.entries(opts.fields) as [string, any][]) {
110
+ if (key === 'status' || key === 'id') throw new Error(`Form field "${key}" is reserved.`)
111
+ if (!FORM_FIELD_TYPES.has(fld.type) || fld.relation) {
112
+ throw new Error(`Form field "${key}" has type "${fld.type}", which website forms do not support (allowed: ${[...FORM_FIELD_TYPES].join(', ')}).`)
113
+ }
114
+ }
115
+ const keys = Object.keys(opts.fields)
116
+ const titleField = opts.titleField ?? keys.find((k) => (opts.fields as any)[k].type === 'text') ?? keys[0]!
117
+ const e = defineEntity(name, {
118
+ label: opts.label,
119
+ labelSingular: opts.labelSingular ?? { en: 'Submission', cs: 'Odpověď', de: 'Nachricht' },
120
+ description: opts.description,
121
+ icon: 'i-lucide-inbox',
122
+ titleField,
123
+ fields: {
124
+ ...opts.fields,
125
+ status: f.select({
126
+ options: ['new', 'read', 'done'] as const, default: 'new',
127
+ labels: { new: { en: 'New', cs: 'Nové', de: 'Neu' }, read: { en: 'Read', cs: 'Přečtené', de: 'Gelesen' }, done: { en: 'Done', cs: 'Vyřízené', de: 'Erledigt' } },
128
+ icons: { new: 'i-lucide-mail', read: 'i-lucide-mail-open', done: 'i-lucide-check' },
129
+ }).position('sidebar').label({ en: 'State', cs: 'Stav', de: 'Status' }),
130
+ },
131
+ admin: { list: { columns: [...keys.slice(0, 3), 'status'] as any, searchable: keys.filter((k) => (opts.fields as any)[k].type === 'text') as any } },
132
+ access: { read: formsReadAccess, ...opts.access },
133
+ } as any)
134
+ ;(e as any).preset = 'form'
135
+ ;(e as any).requiresPlugin = FORMS_REQUIREMENT
136
+ ;(e as any).form = {
137
+ fields: keys,
138
+ submitLabel: opts.submitLabel ?? null,
139
+ successMessage: opts.successMessage ?? null,
140
+ notify: { to: opts.notify?.to ?? [] },
141
+ retentionDays: opts.retentionDays ?? null,
142
+ }
143
+ return e
144
+ }
145
+
146
+ /**
147
+ * Settings for every website form: who gets an email about new submissions. Optional;
148
+ * without it, each form's `notify.to` (code) or `cms.forms.notifyTo` (env) is used.
149
+ */
150
+ export function defineFormSettings(opts: { name?: string; access?: EntityDef<any>['access'] } = {}) {
151
+ const e = defineSingleton(opts.name ?? 'formSettings', {
152
+ label: { en: 'Forms', cs: 'Formuláře', de: 'Formulare' },
153
+ description: { en: 'Who is told about new messages from the website.', cs: 'Komu přijde e-mail o nových zprávách z webu.', de: 'Wer über neue Nachrichten von der Website informiert wird.' },
154
+ icon: 'i-lucide-inbox',
155
+ titleField: 'notifyTo',
156
+ fields: {
157
+ notifyTo: f.list({
158
+ fields: { email: f.text({ required: true, format: 'email' }).label({ en: 'Email', cs: 'E-mail', de: 'E-Mail' }) },
159
+ max: 20, itemLabel: { en: 'Recipient', cs: 'Příjemce', de: 'Empfänger' },
160
+ }).label({ en: 'Send new messages to', cs: 'Nové zprávy posílat na', de: 'Neue Nachrichten senden an' })
161
+ .help({ en: 'Everyone here gets an email when someone sends a form on the website.', cs: 'Všem zde přijde e-mail, když někdo odešle formulář na webu.', de: 'Alle hier erhalten eine E-Mail, wenn jemand ein Formular auf der Website absendet.' }),
162
+ },
163
+ // The recipients are people's addresses, and the settings of messages authors do not read.
164
+ access: { read: formsReadAccess, ...opts.access },
165
+ } as any)
166
+ ;(e as any).preset = 'formSettings'
167
+ ;(e as any).requiresPlugin = FORMS_REQUIREMENT
168
+ return e
169
+ }
170
+
171
+ /** The plugin: endpoints, `<CmsForm>`, retention, and the admin's form bits. */
172
+ export function formsPlugin(): CmsPlugin {
173
+ return defineCmsPlugin({
174
+ name: 'forms',
175
+ version: pkg.version,
176
+ // <CmsForm> for the website's pages.
177
+ components: pluginFile(import.meta.url, './components'),
178
+ // The public form endpoints keep the address they have always had.
179
+ serverHandlers: [
180
+ { method: 'get', contentPath: '_form/:name', handler: pluginFile(import.meta.url, './server/form.get.ts') },
181
+ { method: 'post', contentPath: '_form/:name', handler: pluginFile(import.meta.url, './server/form.post.ts') },
182
+ ],
183
+ hooks: { retention: retainForms },
184
+ // A form's submissions arrive from the website, so the admin offers no "New" button,
185
+ // and says when they are deleted.
186
+ graph: (e) => {
187
+ if ((e as any).preset !== 'form') return
188
+ const days = (e as any).form?.retentionDays as number | null | undefined
189
+ return {
190
+ create: false,
191
+ notices: days ? [{ icon: 'i-lucide-clock', key: 'plugins.forms.retention', params: { count: days } }] : [],
192
+ }
193
+ },
194
+ i18n: {
195
+ en: { retention: { one: 'Messages are deleted automatically {count} day after they arrive.', other: 'Messages are deleted automatically {count} days after they arrive.' } },
196
+ cs: { retention: { one: 'Zprávy se automaticky mažou {count} den po přijetí.', few: 'Zprávy se automaticky mažou {count} dny po přijetí.', other: 'Zprávy se automaticky mažou {count} dní po přijetí.' } },
197
+ de: { retention: { one: 'Nachrichten werden {count} Tag nach Eingang automatisch gelöscht.', other: 'Nachrichten werden {count} Tage nach Eingang automatisch gelöscht.' } },
198
+ },
199
+ })
200
+ }
201
+
202
+ /** The registration the deprecated `defineForm` / `defineFormSettings` of `tinyzoo` leave to the plugin. */
203
+ export const IMPLICIT_FORMS_REQUIREMENT: CmsPluginRequirement = { ...FORMS_REQUIREMENT, create: formsPlugin }
@@ -0,0 +1,104 @@
1
+ // What a visitor is told when a website form is refused, in their language. Pure functions
2
+ // (no server context): the POST route turns the validation issues of a submission into
3
+ // these, so the form shows "Vyberte jednu z možností." and not a validator's English.
4
+
5
+ type Messages = {
6
+ required: string
7
+ invalid: string
8
+ email: string
9
+ url: string
10
+ choose: string
11
+ number: string
12
+ tooLong: (max: number) => string
13
+ tooShort: (min: number) => string
14
+ tooSmall: (min: number) => string
15
+ tooBig: (max: number) => string
16
+ tick: string
17
+ }
18
+
19
+ const MESSAGES: Record<string, Messages> = {
20
+ cs: {
21
+ required: 'Vyplňte prosím.',
22
+ invalid: 'Zkontrolujte prosím tuto hodnotu.',
23
+ email: 'Zadejte prosím platný e-mail.',
24
+ url: 'Zadejte prosím platnou adresu (https://…).',
25
+ choose: 'Vyberte jednu z možností.',
26
+ number: 'Zadejte prosím číslo.',
27
+ tooLong: (max) => `Text je příliš dlouhý (nejvýše ${max} znaků).`,
28
+ tooShort: (min) => `Text je příliš krátký (alespoň ${min} znaků).`,
29
+ tooSmall: (min) => `Číslo musí být alespoň ${min}.`,
30
+ tooBig: (max) => `Číslo musí být nejvýše ${max}.`,
31
+ tick: 'Pro odeslání je potřeba toto políčko zaškrtnout.',
32
+ },
33
+ en: {
34
+ required: 'Please fill this in.',
35
+ invalid: 'Please check this value.',
36
+ email: 'Please enter a valid email.',
37
+ url: 'Please enter a valid address (https://…).',
38
+ choose: 'Please choose one of the options.',
39
+ number: 'Please enter a number.',
40
+ tooLong: (max) => `This is too long (at most ${max} characters).`,
41
+ tooShort: (min) => `This is too short (at least ${min} characters).`,
42
+ tooSmall: (min) => `The number must be at least ${min}.`,
43
+ tooBig: (max) => `The number must be at most ${max}.`,
44
+ tick: 'Please tick this box to send the form.',
45
+ },
46
+ de: {
47
+ required: 'Bitte ausfüllen.',
48
+ invalid: 'Bitte prüfen Sie diesen Wert.',
49
+ email: 'Bitte geben Sie eine gültige E-Mail-Adresse ein.',
50
+ url: 'Bitte geben Sie eine gültige Adresse ein (https://…).',
51
+ choose: 'Bitte wählen Sie eine der Möglichkeiten.',
52
+ number: 'Bitte geben Sie eine Zahl ein.',
53
+ tooLong: (max) => `Der Text ist zu lang (höchstens ${max} Zeichen).`,
54
+ tooShort: (min) => `Der Text ist zu kurz (mindestens ${min} Zeichen).`,
55
+ tooSmall: (min) => `Die Zahl muss mindestens ${min} sein.`,
56
+ tooBig: (max) => `Die Zahl darf höchstens ${max} sein.`,
57
+ tick: 'Bitte setzen Sie dieses Häkchen, um das Formular abzusenden.',
58
+ },
59
+ }
60
+
61
+ /** The messages for a language code ('cs', 'cs-CZ'); English for a language without its own. */
62
+ export function formMessages(locale: string | null | undefined): Messages {
63
+ return MESSAGES[String(locale ?? '').split(/[-_]/)[0]!.toLowerCase()] ?? MESSAGES.en!
64
+ }
65
+
66
+ interface Issue {
67
+ code?: string
68
+ path?: PropertyKey[]
69
+ message?: string
70
+ format?: string
71
+ minimum?: number | bigint
72
+ maximum?: number | bigint
73
+ origin?: string
74
+ expected?: string
75
+ input?: unknown
76
+ [k: string]: unknown
77
+ }
78
+
79
+ /**
80
+ * One validation issue as the visitor should read it. `field` is the form field it is
81
+ * about (`type`, `meta`), which says whether a choice, a number or a ticked box was meant.
82
+ */
83
+ export function formIssueMessage(issue: Issue, field: { type?: string; meta?: Record<string, any> } | undefined, locale: string | null | undefined): string {
84
+ const m = formMessages(locale)
85
+ const type = field?.type
86
+ if (type === 'boolean') return m.tick
87
+ if (type === 'select') return m.choose
88
+ const missing = issue.code === 'invalid_type' && /received (undefined|null)/.test(String(issue.message ?? ''))
89
+ if (missing) return type === 'number' ? m.number : m.required
90
+ if (issue.code === 'invalid_format' || issue.code === 'invalid_string') return issue.format === 'url' ? m.url : issue.format === 'email' ? m.email : m.invalid
91
+ if (issue.code === 'invalid_type') return type === 'number' ? m.number : m.invalid
92
+ if (issue.code === 'too_big') return issue.origin === 'number' || issue.origin === 'int' ? m.tooBig(Number(issue.maximum)) : m.tooLong(Number(issue.maximum))
93
+ if (issue.code === 'too_small') {
94
+ if (issue.origin === 'number' || issue.origin === 'int') return m.tooSmall(Number(issue.minimum))
95
+ // An empty text is "not filled in"; a longer minimum is a rule.
96
+ return Number(issue.minimum) <= 1 ? m.required : m.tooShort(Number(issue.minimum))
97
+ }
98
+ return m.invalid
99
+ }
100
+
101
+ /** The issues of a refused submission with a message in the visitor's language (the other keys stay: `code`, `path`). */
102
+ export function localizeFormIssues(issues: Issue[], fields: Record<string, { type?: string; meta?: Record<string, any> }>, locale: string | null | undefined): Issue[] {
103
+ return issues.map((i) => ({ ...i, message: formIssueMessage(i, fields[String(i.path?.[0] ?? '')], locale) }))
104
+ }