tinyzoo 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (392) hide show
  1. package/LICENSE +10 -0
  2. package/README.md +46 -2
  3. package/app/app.config.ts +35 -0
  4. package/app/assets/brand/characters/bright/bird.svg +1 -0
  5. package/app/assets/brand/characters/bright/bunny.svg +1 -0
  6. package/app/assets/brand/characters/bright/elephant.svg +1 -0
  7. package/app/assets/brand/characters/bright/fox.svg +1 -0
  8. package/app/assets/brand/characters/bright/frog.svg +1 -0
  9. package/app/assets/brand/characters/bright/octopus.svg +1 -0
  10. package/app/assets/brand/characters/muted/bee.svg +1 -0
  11. package/app/assets/brand/characters/muted/bird.svg +1 -0
  12. package/app/assets/brand/characters/muted/butterfly.svg +1 -0
  13. package/app/assets/brand/characters/muted/chick.svg +1 -0
  14. package/app/assets/brand/characters/muted/cow.svg +1 -0
  15. package/app/assets/brand/characters/muted/deer.svg +1 -0
  16. package/app/assets/brand/characters/muted/duck.svg +1 -0
  17. package/app/assets/brand/characters/muted/elephant.svg +1 -0
  18. package/app/assets/brand/characters/muted/fox.svg +1 -0
  19. package/app/assets/brand/characters/muted/hedgehog.svg +1 -0
  20. package/app/assets/brand/characters/muted/koala.svg +1 -0
  21. package/app/assets/brand/characters/muted/ladybug.svg +1 -0
  22. package/app/assets/brand/characters/muted/lion.svg +1 -0
  23. package/app/assets/brand/characters/muted/mouse.svg +1 -0
  24. package/app/assets/brand/characters/muted/octopus.svg +1 -0
  25. package/app/assets/brand/characters/muted/owl.svg +1 -0
  26. package/app/assets/brand/characters/muted/panda.svg +1 -0
  27. package/app/assets/brand/characters/muted/penguin.svg +1 -0
  28. package/app/assets/brand/characters/muted/pig.svg +1 -0
  29. package/app/assets/brand/characters/muted/poodle.svg +1 -0
  30. package/app/assets/brand/characters/muted/raccoon.svg +1 -0
  31. package/app/assets/brand/characters/muted/seal.svg +1 -0
  32. package/app/assets/brand/characters/muted/sheep.svg +1 -0
  33. package/app/assets/brand/characters/muted/snail.svg +1 -0
  34. package/app/assets/brand/characters/muted/turtle.svg +1 -0
  35. package/app/assets/brand/characters/muted/whale.svg +1 -0
  36. package/app/assets/brand/logo/favicon.svg +1 -0
  37. package/app/assets/brand/logo/logo-primary-reversed.svg +1 -0
  38. package/app/assets/brand/logo/logo-primary.svg +1 -0
  39. package/app/assets/brand/logo/mascot-reversed.svg +1 -0
  40. package/app/assets/brand/logo/mascot.svg +1 -0
  41. package/app/assets/brand/logo/wordmark-reversed.svg +1 -0
  42. package/app/assets/brand/logo/wordmark.svg +1 -0
  43. package/app/assets/css/cms-admin.css +607 -0
  44. package/app/components/CmsBlocks.vue +30 -0
  45. package/app/components/CmsCell.vue +16 -0
  46. package/app/components/CmsCellBadge.vue +18 -0
  47. package/app/components/CmsCellBlocks.vue +9 -0
  48. package/app/components/CmsCellBoolean.vue +12 -0
  49. package/app/components/CmsCellCode.vue +7 -0
  50. package/app/components/CmsCellColor.vue +13 -0
  51. package/app/components/CmsCellDate.vue +10 -0
  52. package/app/components/CmsCellExcerpt.vue +21 -0
  53. package/app/components/CmsCellGallery.vue +10 -0
  54. package/app/components/CmsCellGroup.vue +23 -0
  55. package/app/components/CmsCellNumber.vue +7 -0
  56. package/app/components/CmsCellRelation.vue +8 -0
  57. package/app/components/CmsCellText.vue +12 -0
  58. package/app/components/CmsCellThumb.vue +18 -0
  59. package/app/components/CmsConfirmDialog.vue +55 -0
  60. package/app/components/CmsContent.vue +103 -0
  61. package/app/components/CmsDayPicker.vue +44 -0
  62. package/app/components/CmsEmptyState.vue +35 -0
  63. package/app/components/CmsField.vue +111 -0
  64. package/app/components/CmsFieldBlocks.vue +353 -0
  65. package/app/components/CmsFieldBoolean.vue +8 -0
  66. package/app/components/CmsFieldColor.vue +42 -0
  67. package/app/components/CmsFieldDate.vue +131 -0
  68. package/app/components/CmsFieldGallery.vue +114 -0
  69. package/app/components/CmsFieldGroup.vue +53 -0
  70. package/app/components/CmsFieldMedia.vue +219 -0
  71. package/app/components/CmsFieldNumber.vue +11 -0
  72. package/app/components/CmsFieldRelationMany.vue +54 -0
  73. package/app/components/CmsFieldRelationOne.vue +47 -0
  74. package/app/components/CmsFieldRichText.vue +45 -0
  75. package/app/components/CmsFieldSelect.vue +41 -0
  76. package/app/components/CmsFieldSlug.vue +46 -0
  77. package/app/components/CmsFieldText.vue +75 -0
  78. package/app/components/CmsFormSections.vue +150 -0
  79. package/app/components/CmsHighlight.vue +22 -0
  80. package/app/components/CmsImage.vue +39 -0
  81. package/app/components/CmsLinkPicker.vue +122 -0
  82. package/app/components/CmsLinkTarget.vue +35 -0
  83. package/app/components/CmsListFilters.vue +107 -0
  84. package/app/components/CmsLiveNotice.vue +64 -0
  85. package/app/components/CmsLoadError.vue +24 -0
  86. package/app/components/CmsMascot.vue +10 -0
  87. package/app/components/CmsMediaLibrary.vue +114 -0
  88. package/app/components/CmsMediaPreview.vue +34 -0
  89. package/app/components/CmsMediaThumb.vue +22 -0
  90. package/app/components/CmsMoment.vue +42 -0
  91. package/app/components/CmsNav.vue +39 -0
  92. package/app/components/CmsPage.vue +86 -0
  93. package/app/components/CmsPasswordInput.vue +22 -0
  94. package/app/components/CmsPresence.vue +29 -0
  95. package/app/components/CmsPreviewPanel.vue +131 -0
  96. package/app/components/CmsPublishReview.vue +102 -0
  97. package/app/components/CmsRevisions.vue +195 -0
  98. package/app/components/CmsRichTextEditor.vue +290 -0
  99. package/app/components/CmsSearch.vue +99 -0
  100. package/app/components/CmsSection.vue +20 -0
  101. package/app/components/CmsSingletonForm.vue +283 -0
  102. package/app/components/CmsStatusBadge.vue +21 -0
  103. package/app/components/CmsTime.vue +16 -0
  104. package/app/components/CmsTranslationRef.vue +27 -0
  105. package/app/components/CmsTreeList.vue +453 -0
  106. package/app/components/CmsUnsavedText.vue +34 -0
  107. package/app/components/CmsWordmark.vue +10 -0
  108. package/app/composables/useCmsAdminHead.ts +18 -0
  109. package/app/composables/useCmsCollab.ts +165 -0
  110. package/app/composables/useCmsConfirm.ts +39 -0
  111. package/app/composables/useCmsEntryActions.ts +75 -0
  112. package/app/composables/useCmsFocus.ts +13 -0
  113. package/app/composables/useCmsForm.ts +273 -0
  114. package/app/composables/useCmsI18n.ts +185 -0
  115. package/app/composables/useCmsLinkTargets.ts +84 -0
  116. package/app/composables/useCmsLive.ts +199 -0
  117. package/app/composables/useCmsSearch.ts +62 -0
  118. package/app/composables/useCmsSeo.ts +99 -0
  119. package/app/composables/useCmsSignedIn.ts +24 -0
  120. package/app/composables/useCmsUiLocale.ts +24 -0
  121. package/app/i18n/cs.ts +781 -0
  122. package/app/i18n/de.ts +781 -0
  123. package/app/i18n/en.ts +782 -0
  124. package/app/i18n/types.ts +22 -0
  125. package/app/layouts/admin.vue +224 -0
  126. package/app/layouts/cms-auth.vue +37 -0
  127. package/app/middleware/cms-api-not-a-page.global.ts +10 -0
  128. package/app/middleware/cms-auth.global.ts +16 -0
  129. package/app/pages/admin/[entity]/[id].vue +1109 -0
  130. package/app/pages/admin/[entity]/index.vue +733 -0
  131. package/app/pages/admin/account.vue +117 -0
  132. package/app/pages/admin/forgot.vue +50 -0
  133. package/app/pages/admin/index.vue +184 -0
  134. package/app/pages/admin/invite/[token].vue +73 -0
  135. package/app/pages/admin/login.vue +84 -0
  136. package/app/pages/admin/media.vue +494 -0
  137. package/app/pages/admin/privacy.vue +193 -0
  138. package/app/pages/admin/reset/[token].vue +52 -0
  139. package/app/pages/admin/setup.vue +87 -0
  140. package/app/pages/admin/styleguide.vue +261 -0
  141. package/app/pages/admin/team.vue +258 -0
  142. package/app/plugins/cmsLivePreview.client.ts +20 -0
  143. package/app/plugins/cmsSignedOut.client.ts +31 -0
  144. package/app/utils/cmsBlockType.ts +11 -0
  145. package/app/utils/cmsBrand.ts +38 -0
  146. package/app/utils/cmsDiff.ts +83 -0
  147. package/app/utils/cmsFetch.ts +7 -0
  148. package/app/utils/cmsFocusInvalid.ts +22 -0
  149. package/app/utils/cmsIssues.ts +128 -0
  150. package/app/utils/cmsJson.ts +28 -0
  151. package/app/utils/cmsMedia.ts +63 -0
  152. package/app/utils/cmsSections.ts +154 -0
  153. package/app/utils/cmsTime.ts +41 -0
  154. package/cli/backup.ts +713 -0
  155. package/cli/breaking.ts +174 -0
  156. package/cli/content-migrate.ts +239 -0
  157. package/cli/db.ts +86 -0
  158. package/cli/export.ts +336 -0
  159. package/cli/generate.ts +146 -0
  160. package/cli/import.ts +643 -0
  161. package/cli/index.ts +140 -0
  162. package/cli/links-convert.ts +291 -0
  163. package/cli/seed-engine.ts +705 -0
  164. package/cli/seed.ts +339 -0
  165. package/cli/status.ts +49 -0
  166. package/cli/tar.ts +304 -0
  167. package/cli/transfer.ts +677 -0
  168. package/cli/up.ts +27 -0
  169. package/cli/upgrade.ts +60 -0
  170. package/cli/versions.ts +60 -0
  171. package/forms/components/CmsForm.vue +186 -0
  172. package/forms/index.ts +203 -0
  173. package/forms/messages.ts +104 -0
  174. package/forms/retention.ts +48 -0
  175. package/forms/server/form.get.ts +12 -0
  176. package/forms/server/form.post.ts +109 -0
  177. package/forms/server/formSettings.ts +12 -0
  178. package/forms/server/forms.ts +127 -0
  179. package/module.ts +373 -0
  180. package/nuxt.config.ts +43 -0
  181. package/package.json +98 -3
  182. package/server/api/cms/[entity]/[id]/revisions/[rev].get.ts +19 -0
  183. package/server/api/cms/[entity]/[id]/revisions/index.get.ts +14 -0
  184. package/server/api/cms/[entity]/[id].delete.ts +52 -0
  185. package/server/api/cms/[entity]/[id].get.ts +21 -0
  186. package/server/api/cms/[entity]/[id].patch.ts +116 -0
  187. package/server/api/cms/[entity]/_export.get.ts +69 -0
  188. package/server/api/cms/[entity]/_move.post.ts +81 -0
  189. package/server/api/cms/[entity]/_order.post.ts +49 -0
  190. package/server/api/cms/[entity]/_tree.get.ts +41 -0
  191. package/server/api/cms/[entity]/index.get.ts +62 -0
  192. package/server/api/cms/[entity]/index.post.ts +38 -0
  193. package/server/api/cms/[entity]/options.get.ts +55 -0
  194. package/server/api/cms/_auth/accept.post.ts +33 -0
  195. package/server/api/cms/_auth/forgot.post.ts +39 -0
  196. package/server/api/cms/_auth/invite/[token].get.ts +18 -0
  197. package/server/api/cms/_auth/login.post.ts +42 -0
  198. package/server/api/cms/_auth/logout.post.ts +7 -0
  199. package/server/api/cms/_auth/me.get.ts +5 -0
  200. package/server/api/cms/_auth/me.patch.ts +32 -0
  201. package/server/api/cms/_auth/password.post.ts +29 -0
  202. package/server/api/cms/_auth/reset.post.ts +34 -0
  203. package/server/api/cms/_auth/setup.post.ts +46 -0
  204. package/server/api/cms/_auth/status.get.ts +18 -0
  205. package/server/api/cms/_collab/session.get.ts +30 -0
  206. package/server/api/cms/_collab/socket.ts +51 -0
  207. package/server/api/cms/_collab/unsaved.delete.ts +16 -0
  208. package/server/api/cms/_graph.get.ts +20 -0
  209. package/server/api/cms/_links/resolve.post.ts +17 -0
  210. package/server/api/cms/_links.get.ts +81 -0
  211. package/server/api/cms/_live.ts +30 -0
  212. package/server/api/cms/_media/[id]/usage.get.ts +14 -0
  213. package/server/api/cms/_media/[id].delete.ts +29 -0
  214. package/server/api/cms/_media/[id].get.ts +13 -0
  215. package/server/api/cms/_media/[id].patch.ts +64 -0
  216. package/server/api/cms/_media/exists.post.ts +15 -0
  217. package/server/api/cms/_media/img/[id]/[file].get.ts +42 -0
  218. package/server/api/cms/_media/index.get.ts +44 -0
  219. package/server/api/cms/_media/index.post.ts +147 -0
  220. package/server/api/cms/_media/raw/[...key].get.ts +85 -0
  221. package/server/api/cms/_media/raw/[...key].head.ts +2 -0
  222. package/server/api/cms/_overview.get.ts +87 -0
  223. package/server/api/cms/_preview.post.ts +17 -0
  224. package/server/api/cms/_privacy/delete.post.ts +14 -0
  225. package/server/api/cms/_privacy/export.post.ts +25 -0
  226. package/server/api/cms/_privacy/lookup.post.ts +27 -0
  227. package/server/api/cms/_search.get.ts +17 -0
  228. package/server/api/cms/_singleton/[name].get.ts +19 -0
  229. package/server/api/cms/_singleton/[name].put.ts +76 -0
  230. package/server/api/cms/_users/[id]/resend.post.ts +25 -0
  231. package/server/api/cms/_users/[id].delete.ts +21 -0
  232. package/server/api/cms/_users/[id].patch.ts +45 -0
  233. package/server/api/cms/_users/index.get.ts +28 -0
  234. package/server/api/cms/_users/index.post.ts +39 -0
  235. package/server/api/content/[entity]/[slug].get.ts +74 -0
  236. package/server/api/content/[entity]/index.get.ts +100 -0
  237. package/server/api/content/_global/[name].get.ts +23 -0
  238. package/server/api/content/_search.get.ts +28 -0
  239. package/server/api/content/_sitemap.get.ts +8 -0
  240. package/server/api/content/_tree/[entity].get.ts +31 -0
  241. package/server/api/content-types.ts.get.ts +17 -0
  242. package/server/api/health/live.get.ts +10 -0
  243. package/server/api/health/ready.get.ts +21 -0
  244. package/server/api/openapi.get.ts +48 -0
  245. package/server/api/openapi.json.get.ts +32 -0
  246. package/server/db/driver.ts +8 -0
  247. package/server/mail/mailer.ts +43 -0
  248. package/server/middleware/cms-0-headers.ts +37 -0
  249. package/server/middleware/cms-0-migrate-gate.ts +14 -0
  250. package/server/middleware/cms-csrf.ts +28 -0
  251. package/server/middleware/cms-limits.ts +20 -0
  252. package/server/middleware/cms-redirects.ts +21 -0
  253. package/server/middleware/cms-session.ts +41 -0
  254. package/server/middleware/cms-z-plugin-access.ts +15 -0
  255. package/server/plugins/cms-0-config-check.ts +35 -0
  256. package/server/plugins/cms-changes.ts +53 -0
  257. package/server/plugins/cms-content-etag.ts +21 -0
  258. package/server/plugins/cms-errors.ts +45 -0
  259. package/server/plugins/cms-migrate.ts +5 -0
  260. package/server/plugins/cms-plugins.ts +17 -0
  261. package/server/plugins/cms-search.ts +12 -0
  262. package/server/plugins/cms-setup-code.ts +15 -0
  263. package/server/routes/sitemap.xml.get.ts +25 -0
  264. package/server/store/redis.ts +95 -0
  265. package/server/store/types.ts +21 -0
  266. package/server/tasks/cms/retention.ts +10 -0
  267. package/server/tasks/cms/scheduled.ts +10 -0
  268. package/server/tasks/cms/search-reindex.ts +12 -0
  269. package/server/utils/cmsAudit.ts +29 -0
  270. package/server/utils/cmsAuth.ts +143 -0
  271. package/server/utils/cmsBlocks.ts +47 -0
  272. package/server/utils/cmsChanges.ts +222 -0
  273. package/server/utils/cmsCollab.ts +286 -0
  274. package/server/utils/cmsCollabServer.ts +451 -0
  275. package/server/utils/cmsCollate.ts +27 -0
  276. package/server/utils/cmsContent.ts +376 -0
  277. package/server/utils/cmsCrud.ts +361 -0
  278. package/server/utils/cmsCsv.ts +24 -0
  279. package/server/utils/cmsDb.ts +23 -0
  280. package/server/utils/cmsDemo.ts +36 -0
  281. package/server/utils/cmsEmails.ts +125 -0
  282. package/server/utils/cmsErrors.ts +40 -0
  283. package/server/utils/cmsFold.ts +17 -0
  284. package/server/utils/cmsImageSizes.ts +51 -0
  285. package/server/utils/cmsJson.ts +6 -0
  286. package/server/utils/cmsLinkAddress.ts +50 -0
  287. package/server/utils/cmsLinks.ts +248 -0
  288. package/server/utils/cmsListQuery.ts +93 -0
  289. package/server/utils/cmsLive.ts +393 -0
  290. package/server/utils/cmsLocales.ts +96 -0
  291. package/server/utils/cmsMail.ts +28 -0
  292. package/server/utils/cmsMediaGc.ts +188 -0
  293. package/server/utils/cmsMediaKeys.ts +62 -0
  294. package/server/utils/cmsMigrate.ts +86 -0
  295. package/server/utils/cmsPreviewDraft.ts +72 -0
  296. package/server/utils/cmsPrivacy.ts +176 -0
  297. package/server/utils/cmsPublished.ts +57 -0
  298. package/server/utils/cmsRange.ts +38 -0
  299. package/server/utils/cmsRateLimit.ts +82 -0
  300. package/server/utils/cmsRedirects.ts +160 -0
  301. package/server/utils/cmsRetention.ts +61 -0
  302. package/server/utils/cmsRevisions.ts +103 -0
  303. package/server/utils/cmsScheduler.ts +45 -0
  304. package/server/utils/cmsScrub.ts +107 -0
  305. package/server/utils/cmsSearch.ts +354 -0
  306. package/server/utils/cmsSession.ts +102 -0
  307. package/server/utils/cmsSetupCode.ts +97 -0
  308. package/server/utils/cmsSitemap.ts +176 -0
  309. package/server/utils/cmsStorage.ts +580 -0
  310. package/server/utils/cmsStore.ts +109 -0
  311. package/server/utils/cmsTiming.ts +14 -0
  312. package/server/utils/cmsTooMany.ts +9 -0
  313. package/server/utils/cmsTranslationWrite.ts +186 -0
  314. package/server/utils/cmsTree.ts +251 -0
  315. package/server/utils/cmsTreeAddress.ts +65 -0
  316. package/server/utils/cmsUpload.ts +228 -0
  317. package/server/utils/cmsWebhooks.ts +104 -0
  318. package/shared/json.ts +11 -0
  319. package/shared/richtext-editor.ts +56 -0
  320. package/shared/richtext-normalize.ts +33 -0
  321. package/shared/richtext-paste.ts +151 -0
  322. package/shared/storage-delivery.ts +53 -0
  323. package/src/blocks.ts +624 -0
  324. package/src/changes.ts +54 -0
  325. package/src/content-shape.ts +340 -0
  326. package/src/deprecate.ts +64 -0
  327. package/src/descriptor.ts +149 -0
  328. package/src/docs.ts +27 -0
  329. package/src/emitter.ts +94 -0
  330. package/src/entity.ts +624 -0
  331. package/src/errorReport.ts +41 -0
  332. package/src/fields.ts +465 -0
  333. package/src/i18n.ts +26 -0
  334. package/src/index.ts +54 -0
  335. package/src/linkref.ts +31 -0
  336. package/src/links.ts +179 -0
  337. package/src/locales.ts +39 -0
  338. package/src/media.ts +48 -0
  339. package/src/migrate.ts +236 -0
  340. package/src/openapi.ts +377 -0
  341. package/src/paths.ts +88 -0
  342. package/src/plugin.ts +505 -0
  343. package/src/presets.ts +230 -0
  344. package/src/richtext.ts +88 -0
  345. package/src/sdk.ts +181 -0
  346. package/src/search.ts +312 -0
  347. package/src/seed.ts +225 -0
  348. package/src/setupCode.ts +30 -0
  349. package/src/system.ts +219 -0
  350. package/src/tree.ts +421 -0
  351. package/src/upgrades.ts +137 -0
  352. package/starter/.env.example +10 -0
  353. package/starter/README.md +65 -0
  354. package/starter/app/app.config.ts +10 -0
  355. package/starter/app/app.vue +12 -0
  356. package/starter/app/assets/css/main.css +15 -0
  357. package/starter/app/components/global/BlockContact.vue +15 -0
  358. package/starter/app/components/global/BlockCta.vue +15 -0
  359. package/starter/app/components/global/BlockHero.vue +23 -0
  360. package/starter/app/components/global/BlockImage.vue +13 -0
  361. package/starter/app/components/global/BlockText.vue +12 -0
  362. package/starter/app/composables/useSite.ts +77 -0
  363. package/starter/app/error.vue +28 -0
  364. package/starter/app/layouts/default.vue +106 -0
  365. package/starter/app/lib/cms-content.ts +152 -0
  366. package/starter/app/pages/[...slug].vue +66 -0
  367. package/starter/app/pages/hledat.vue +59 -0
  368. package/starter/app/pages/index.vue +20 -0
  369. package/starter/cms.config.ts +137 -0
  370. package/starter/compose.yaml +15 -0
  371. package/starter/drizzle.config.ts +8 -0
  372. package/starter/gitignore.txt +8 -0
  373. package/starter/nuxt.config.ts +13 -0
  374. package/starter/package.json +38 -0
  375. package/starter/scripts/typecheck.mjs +38 -0
  376. package/starter/seed/index.ts +297 -0
  377. package/starter/seed/media/about.jpg +0 -0
  378. package/starter/seed/media/hero.jpg +0 -0
  379. package/starter/seed/media/logo.png +0 -0
  380. package/starter/seed/media/news-bread.jpg +0 -0
  381. package/starter/seed/media/news-morning.jpg +0 -0
  382. package/starter/server/db/migrations/0000_init.sql +269 -0
  383. package/starter/server/db/migrations/0001_page_tree.sql +5 -0
  384. package/starter/server/db/migrations/0002_opening_hours_per_language.sql +1 -0
  385. package/starter/server/db/migrations/meta/0000_snapshot.json +1890 -0
  386. package/starter/server/db/migrations/meta/0001_snapshot.json +1887 -0
  387. package/starter/server/db/migrations/meta/0002_snapshot.json +1893 -0
  388. package/starter/server/db/migrations/meta/_journal.json +27 -0
  389. package/starter/server/db/schema.ts +253 -0
  390. package/starter/server/plugins/sitemap.ts +11 -0
  391. package/starter/server/routes/robots.txt.get.ts +12 -0
  392. package/starter/tsconfig.json +9 -0
package/src/search.ts ADDED
@@ -0,0 +1,312 @@
1
+ import type { FieldDescriptor } from './descriptor'
2
+
3
+ /**
4
+ * Search over entries, without a search engine or a database extension: the server
5
+ * narrows the candidates in SQL (every word somewhere in the entry, accents and case
6
+ * ignored), then reads what an entry says the way a visitor sees it — headings, text,
7
+ * rich text and the text inside blocks, never addresses, ids or block type names —
8
+ * to check the match, rank it and cut a snippet around the first hit.
9
+ *
10
+ * Meant for the size of a typical client site (hundreds to a few thousand entries).
11
+ */
12
+
13
+ /** Lowercase, without accents ("Zimní" → "zimni"): the same folding as the SQL side. */
14
+ export function foldSearchText(text: string): string {
15
+ return text.toLowerCase().normalize('NFD').replace(/\p{M}/gu, '').replace(/ł/g, 'l').replace(/đ/g, 'd')
16
+ }
17
+
18
+ /** Longest query the search reads, and most words it matches on. */
19
+ export const SEARCH_MAX_QUERY = 100
20
+ const MAX_TERMS = 8
21
+
22
+ /**
23
+ * The words of a query, folded: each must appear in an entry (in any order, also
24
+ * inside a longer word: "kvas" finds "kvásek"). Empty when there is nothing to look for.
25
+ */
26
+ export function searchTerms(query: string): string[] {
27
+ const folded = foldSearchText(String(query ?? '').slice(0, SEARCH_MAX_QUERY))
28
+ const words = folded.split(/[\s,;]+/).map((w) => w.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, '')).filter(Boolean)
29
+ // A longer word already covers a word it contains ("chleb chlebovy" → just "chlebovy").
30
+ const unique = [...new Set(words)].filter((w, _, all) => !all.some((o) => o !== w && o.includes(w)))
31
+ return unique.slice(0, MAX_TERMS)
32
+ }
33
+
34
+ /** Text fields that hold an address or a code, not words a visitor reads. */
35
+ const NOT_PROSE = new Set(['email', 'url', 'path', 'link', 'color'])
36
+
37
+ /** Is this field something people read (and so something to search)? */
38
+ export function isSearchableField(fld: FieldDescriptor): boolean {
39
+ if (fld.relation) return false
40
+ if (fld.type === 'text') return !NOT_PROSE.has(String((fld.meta as any)?.format ?? ''))
41
+ return fld.type === 'richtext' || fld.type === 'blocks' || fld.type === 'group'
42
+ }
43
+
44
+ /** The words of a rich-text document, one line per paragraph, heading or list item. */
45
+ export function richTextPlain(doc: unknown): string {
46
+ const lines: string[] = []
47
+ let line = ''
48
+ const walk = (node: any) => {
49
+ if (!node || typeof node !== 'object') return
50
+ if (node.type === 'text' && typeof node.text === 'string') {
51
+ line += node.text
52
+ return
53
+ }
54
+ if (node.type === 'hardBreak') line += ' '
55
+ if (Array.isArray(node.content)) for (const child of node.content) walk(child)
56
+ if (node.type !== 'text' && node.type !== 'hardBreak' && node.type !== 'doc' && line.trim()) {
57
+ lines.push(line.trim())
58
+ line = ''
59
+ }
60
+ }
61
+ walk(doc)
62
+ if (line.trim()) lines.push(line.trim())
63
+ return lines.join('\n')
64
+ }
65
+
66
+ /**
67
+ * Everything an entry says, field by field in the order the fields are defined: text,
68
+ * rich text, and inside blocks their own text fields (lists included). Fields in
69
+ * `skip` (e.g. hidden from the public) and anything that is not prose are left out.
70
+ */
71
+ export function entryTexts(fields: Record<string, FieldDescriptor>, row: Record<string, any>, skip: ReadonlySet<string> = new Set()): string[] {
72
+ const out: string[] = []
73
+ for (const [key, fld] of Object.entries(fields)) {
74
+ if (skip.has(key) || !isSearchableField(fld)) continue
75
+ collect(fld, row[key], out)
76
+ }
77
+ return out
78
+ }
79
+
80
+ function collect(fld: FieldDescriptor, value: unknown, out: string[]) {
81
+ if (value === null || value === undefined || value === '') return
82
+ if (fld.type === 'text') {
83
+ if (typeof value === 'string' && value.trim()) out.push(value.trim())
84
+ }
85
+ else if (fld.type === 'richtext') {
86
+ const text = richTextPlain(value)
87
+ if (text) out.push(text)
88
+ }
89
+ else if (fld.type === 'blocks' && Array.isArray(value)) {
90
+ const blocks = fld.blocks ?? {}
91
+ for (const block of value) {
92
+ if (!block || typeof block !== 'object') continue
93
+ const def = Object.hasOwn(blocks, block.type) ? blocks[block.type] : undefined
94
+ if (!def) continue
95
+ for (const [key, inner] of Object.entries(def.fields) as [string, FieldDescriptor][]) {
96
+ if (isSearchableField(inner)) collect(inner, block[key], out)
97
+ }
98
+ }
99
+ }
100
+ else if (fld.type === 'group' && typeof value === 'object' && !Array.isArray(value)) {
101
+ for (const [key, inner] of Object.entries(fld.fields ?? {}) as [string, FieldDescriptor][]) {
102
+ if (isSearchableField(inner)) collect(inner, (value as Record<string, unknown>)[key], out)
103
+ }
104
+ }
105
+ }
106
+
107
+
108
+ // ── matching: exact or with a typo ──────────────────────────────────────────────
109
+
110
+ /**
111
+ * How many typos a word may have and still match: none under 4 letters, one up to 7,
112
+ * two from 8 ("sousterdeni" → "soustředění", "preveiw" → "preview").
113
+ */
114
+ export function allowedTypos(term: string): number {
115
+ return term.length >= 8 ? 2 : term.length >= 4 ? 1 : 0
116
+ }
117
+
118
+ /**
119
+ * Edit distance with swapped neighbours counting as one edit (optimal string
120
+ * alignment), giving up once it is over `max` (returns max + 1).
121
+ */
122
+ export function editDistance(a: string, b: string, max = Infinity): number {
123
+ if (Math.abs(a.length - b.length) > max) return max + 1
124
+ const n = b.length
125
+ let prev2 = new Int32Array(n + 1)
126
+ let prev = new Int32Array(n + 1)
127
+ let cur = new Int32Array(n + 1)
128
+ for (let j = 0; j <= n; j++) prev[j] = j
129
+ for (let i = 1; i <= a.length; i++) {
130
+ cur[0] = i
131
+ let best = i
132
+ for (let j = 1; j <= n; j++) {
133
+ const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1
134
+ let d = Math.min(prev[j]! + 1, cur[j - 1]! + 1, prev[j - 1]! + cost)
135
+ if (i > 1 && j > 1 && a.charCodeAt(i - 1) === b.charCodeAt(j - 2) && a.charCodeAt(i - 2) === b.charCodeAt(j - 1)) d = Math.min(d, prev2[j - 2]! + 1)
136
+ cur[j] = d
137
+ if (d < best) best = d
138
+ }
139
+ if (best > max) return max + 1
140
+ const spare = prev2
141
+ prev2 = prev
142
+ prev = cur
143
+ cur = spare
144
+ }
145
+ return prev[n]!
146
+ }
147
+
148
+ /**
149
+ * Does a (folded) word match a (folded) search term? 'exact' when it contains it,
150
+ * 'typo' when it or its beginning is within the allowed typos — so a word's other
151
+ * forms match too ("priprava" ~ "priprave", "zima" ~ "zimni"). Like most search
152
+ * engines, a typo match keeps the first letter (or swaps the first two).
153
+ */
154
+ export function wordMatch(term: string, word: string): 'exact' | 'typo' | null {
155
+ if (word.includes(term)) return 'exact'
156
+ const max = allowedTypos(term)
157
+ if (!max || word.length < 3) return null
158
+ if (word[0] !== term[0] && !(word[0] === term[1] && word[1] === term[0])) return null
159
+ for (let len = term.length - max; len <= term.length + max; len++) {
160
+ if (len < 3 || len > word.length) continue
161
+ // The whole word, or its beginning (an ending that differs is a word form).
162
+ if (len !== word.length && len < term.length) continue
163
+ if (editDistance(term, word.slice(0, len), max) <= max) return 'typo'
164
+ }
165
+ return null
166
+ }
167
+
168
+ /** Where a term is in a folded text: [start, end) ranges, and whether any is exact. */
169
+ function termHits(folded: string, term: string): { exact: boolean; ranges: [number, number][] } {
170
+ const ranges: [number, number][] = []
171
+ let exact = false
172
+ // A text repeats its words: each distinct one is checked once.
173
+ const seen = new Map<string, ReturnType<typeof wordMatch>>()
174
+ for (const m of folded.matchAll(/[\p{L}\p{N}]+/gu)) {
175
+ const word = m[0]
176
+ let kind = seen.get(word)
177
+ if (kind === undefined) seen.set(word, kind = wordMatch(term, word))
178
+ if (!kind) continue
179
+ if (kind === 'exact') {
180
+ exact = true
181
+ for (let i = word.indexOf(term); i !== -1; i = word.indexOf(term, i + term.length)) ranges.push([m.index + i, m.index + i + term.length])
182
+ }
183
+ else ranges.push([m.index, m.index + word.length])
184
+ }
185
+ return { exact, ranges }
186
+ }
187
+
188
+ /** One found entry: how well it matches, and a snippet of its text around the words. */
189
+ export interface SearchMatch {
190
+ score: number
191
+ /** A sentence or two around the first match (empty when only the title matched). */
192
+ excerpt: string
193
+ /** Where the words are in `excerpt`, as [start, end) pairs, for highlighting. */
194
+ highlights: [number, number][]
195
+ }
196
+
197
+ /**
198
+ * Does an entry match every word (exactly or with a typo), and how well? Null when a
199
+ * word is missing. The title counts most (the whole query in it, at its start, each
200
+ * word in it); then how often the words appear in the text. A word found only with a
201
+ * typo counts for less than the same word spelled right.
202
+ */
203
+ export function matchEntry(title: string, texts: string[], terms: string[], query = terms.join(' ')): SearchMatch | null {
204
+ if (!terms.length) return null
205
+ const foldedTitle = foldSearchText(title ?? '')
206
+ const body = texts.join('\n')
207
+ const foldedBody = foldSearchText(body)
208
+ let score = 0
209
+ for (const term of terms) {
210
+ const t = termHits(foldedTitle, term)
211
+ const b = termHits(foldedBody, term)
212
+ if (!t.ranges.length && !b.ranges.length) return null
213
+ if (t.ranges.length) score += t.exact ? 20 + (wordStart(foldedTitle, term) ? 10 : 0) : 12
214
+ if (b.ranges.length) score += Math.min(b.ranges.length, 10) * (b.exact ? 1 : 0.5) + (b.exact && wordStart(foldedBody, term) ? 2 : 0)
215
+ }
216
+ const phrase = foldSearchText(query).trim()
217
+ if (phrase && foldedTitle.includes(phrase)) score += 40 + (foldedTitle.startsWith(phrase) ? 20 : 0) + (foldedTitle === phrase ? 40 : 0)
218
+ return { score, ...excerptOf(body, terms) }
219
+ }
220
+
221
+ const wordStart = (hay: string, needle: string) => new RegExp(`(^|[^\\p{L}\\p{N}])${escapeRe(needle)}`, 'u').test(hay)
222
+ const escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
223
+
224
+ /** The text folded character by character, with each folded position's original index. */
225
+ const foldedChars = new Map<string, string>()
226
+ function foldChar(ch: string): string {
227
+ const code = ch.charCodeAt(0)
228
+ if (code < 128) return code >= 65 && code <= 90 ? String.fromCharCode(code + 32) : ch
229
+ let f = foldedChars.get(ch)
230
+ if (f === undefined) {
231
+ f = foldSearchText(ch)
232
+ if (foldedChars.size < 5000) foldedChars.set(ch, f)
233
+ }
234
+ return f
235
+ }
236
+
237
+ function foldWithMap(text: string): { folded: string; at: number[] } {
238
+ let folded = ''
239
+ const at: number[] = []
240
+ let i = 0
241
+ for (const ch of text) {
242
+ const f = foldChar(ch)
243
+ for (let k = 0; k < f.length; k++) at.push(i)
244
+ folded += f
245
+ i += ch.length
246
+ }
247
+ at.push(text.length)
248
+ return { folded, at }
249
+ }
250
+
251
+ /** Every term's hits in `text`, in the text's own characters, merged. */
252
+ function hitsIn(text: string, terms: string[]): [number, number][] {
253
+ const { folded, at } = foldWithMap(text)
254
+ const out: [number, number][] = []
255
+ for (const term of terms) for (const [s, e] of termHits(folded, term).ranges) out.push([at[s]!, at[e]!])
256
+ return mergeRanges(out)
257
+ }
258
+
259
+ const EXCERPT_LENGTH = 180
260
+
261
+ /**
262
+ * About `length` characters of `text` around the first word found (exactly or with a
263
+ * typo), cut at word boundaries, with "…" where it was cut, and where the words are.
264
+ */
265
+ export function excerptOf(text: string, terms: string[], length = EXCERPT_LENGTH): Pick<SearchMatch, 'excerpt' | 'highlights'> {
266
+ // One line per heading, paragraph or field: a line that does not end a sentence
267
+ // (a heading, a card title) is set apart from the next with " · ".
268
+ const flat = text.split(/\n+/).map((l) => l.replace(/\s+/g, ' ').trim()).filter(Boolean)
269
+ .reduce((out, line) => (!out ? line : /[.!?…:;]$/.test(out) ? `${out} ${line}` : `${out} · ${line}`), '')
270
+ if (!flat) return { excerpt: '', highlights: [] }
271
+ const hits = hitsIn(flat, terms)
272
+ if (!hits.length) return { excerpt: '', highlights: [] }
273
+ const hit = hits[0]![0]
274
+ // Start a little before the hit (at a word boundary), so it reads as a sentence.
275
+ let start = Math.max(0, hit - Math.round(length * 0.3))
276
+ if (start > 0) {
277
+ const sentence = flat.lastIndexOf('. ', hit)
278
+ if (sentence !== -1 && sentence + 2 >= start - 40 && sentence + 2 <= hit) start = sentence + 2
279
+ else {
280
+ const space = flat.indexOf(' ', start)
281
+ start = space !== -1 && space < hit ? space + 1 : start
282
+ }
283
+ }
284
+ let end = Math.min(flat.length, start + length)
285
+ if (end < flat.length) {
286
+ const space = flat.lastIndexOf(' ', end)
287
+ if (space > hit) end = space
288
+ }
289
+ const prefix = start > 0 ? '…' : ''
290
+ const suffix = end < flat.length ? '…' : ''
291
+ const excerpt = prefix + flat.slice(start, end).replace(/[\s,;:–-]+$/, '') + suffix
292
+ const highlights = hits
293
+ .filter(([s, e]) => s >= start && e <= end)
294
+ .map(([s, e]) => [s - start + prefix.length, e - start + prefix.length] as [number, number])
295
+ return { excerpt, highlights }
296
+ }
297
+
298
+ function mergeRanges(ranges: [number, number][]): [number, number][] {
299
+ const sorted = ranges.sort((a, b) => a[0] - b[0])
300
+ const out: [number, number][] = []
301
+ for (const r of sorted) {
302
+ const last = out[out.length - 1]
303
+ if (last && r[0] <= last[1]) last[1] = Math.max(last[1], r[1])
304
+ else out.push([...r])
305
+ }
306
+ return out
307
+ }
308
+
309
+ /** Highlight ranges of `terms` (exact or with a typo) in a short text (a title), as [start, end) pairs. */
310
+ export function highlightRanges(text: string, terms: string[]): [number, number][] {
311
+ return hitsIn(text, terms)
312
+ }
package/src/seed.ts ADDED
@@ -0,0 +1,225 @@
1
+ import type { Insert } from './entity'
2
+
3
+ /**
4
+ * Seeding: content a site starts with (demo pages, the first menus, its settings),
5
+ * written in code and put into the site with `tinyzoo seed`.
6
+ *
7
+ * // seed/index.ts
8
+ * import { defineSeed } from 'tinyzoo'
9
+ * import { News, Page, SiteSettings } from '../cms.config'
10
+ *
11
+ * export default defineSeed(async (s) => {
12
+ * const cover = await s.upload('seed/media/cover.jpg', { alt: 'A desk with a laptop' })
13
+ * const home = await s.upsert(Page, { title: 'Home', slug: 'home', status: 'published', sections: [] },
14
+ * { translations: { en: { title: 'Home' } } })
15
+ * await s.create(News, { title: 'Hello', slug: 'hello', body: s.rich.doc(s.rich.p('First post.')), cover })
16
+ * await s.global(SiteSettings, { siteName: 'My site' })
17
+ * })
18
+ *
19
+ * The seed is not written to the database directly: the command signs in to the running
20
+ * site and goes through the same API the admin uses, so every rule an editor meets
21
+ * (validation, translations, media handling, the search index, saved versions,
22
+ * webhooks) applies to the seed too.
23
+ *
24
+ * Running it twice changes nothing: an entry is recognised by a key field (`by`, the
25
+ * address field by default), and a value that already matches is not written again.
26
+ */
27
+
28
+ /** A rich-text node as the editor stores it. */
29
+ export interface SeedRichNode {
30
+ type: string
31
+ text?: string
32
+ content?: SeedRichNode[]
33
+ marks?: { type: string; attrs?: Record<string, unknown> }[]
34
+ attrs?: Record<string, unknown>
35
+ }
36
+
37
+ /** What a seed gets back for an entry or a global it wrote: pass `.id` wherever a relation or `s.link` wants one. */
38
+ export interface SeedEntry {
39
+ readonly kind: 'entry' | 'global'
40
+ /** The entity's name (`page`, `siteSettings`). */
41
+ readonly entity: string
42
+ readonly id: string
43
+ /** The key the entry is recognised by (`{ slug: 'home' }`); empty for a global. */
44
+ readonly key: Record<string, string>
45
+ /** True when the entry was already there and `s.create` left it as it was. */
46
+ readonly existed: boolean
47
+ /** The values the seed gave (and what was already stored for the rest). */
48
+ readonly data: Record<string, any>
49
+ /** What the seed gave per language (`s.translate`, `translations`). */
50
+ readonly translations: Record<string, Record<string, any>>
51
+ }
52
+
53
+ type EntityLike = { __cms: 'entity'; name: string }
54
+
55
+ type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never
56
+ type IsUnion<T> = [T] extends [UnionToIntersection<T>] ? false : true
57
+ /** One block or list item as a seed may write it: no `id` (the runner makes a stable one), and no `type` when there is only one. */
58
+ type SeedBlock<M, TypeOptional> = M extends unknown
59
+ ? { [K in keyof M as K extends 'id' ? never : K extends 'type' ? (TypeOptional extends true ? never : K) : K]: SeedValue<M[K]> }
60
+ & { id?: string } & (TypeOptional extends true ? { type?: M extends { type: infer Ty } ? Ty : never } : unknown)
61
+ : never
62
+ /** A stored value as a seed may write it. */
63
+ type SeedValue<T> =
64
+ T extends Date ? T
65
+ : T extends readonly (infer U)[]
66
+ ? ([U] extends [{ id: string; type: string }] ? SeedBlock<U, IsUnion<U extends { type: infer Ty } ? Ty : never> extends true ? false : true>[] : SeedValue<U>[])
67
+ : T extends object ? { [K in keyof T]: SeedValue<T[K]> }
68
+ : T
69
+
70
+ /** The values of an entry. Media fields take the id `s.upload` returned, relations the id of the other entry. */
71
+ export type SeedInsert<E> = E extends EntityLike ? { [K in keyof Insert<E>]: SeedValue<Insert<E>[K]> } : Record<string, any>
72
+
73
+ export interface SeedWriteOptions<D = Record<string, any>> {
74
+ /**
75
+ * The field (or fields) that tell an entry apart from the others, so a second run finds
76
+ * the entry it made. Default: the entity's address field (`content.slug`, e.g. `slug`).
77
+ * An entity without one needs it said here.
78
+ */
79
+ by?: (keyof D & string) | (keyof D & string)[]
80
+ /** The same entry in other languages: the translated fields only (`{ en: { title: 'Home' } }`). */
81
+ translations?: Record<string, Partial<D>>
82
+ }
83
+
84
+ export interface SeedGlobalOptions<D = Record<string, any>> {
85
+ /** The same settings in other languages: the translated fields only. */
86
+ translations?: Record<string, Partial<D>>
87
+ /** Leave the global alone when somebody saved it already (default: make it match the seed). */
88
+ ifMissing?: boolean
89
+ }
90
+
91
+ export interface SeedUploadOptions {
92
+ /** The description screen readers read. Left out: untouched. */
93
+ alt?: string
94
+ /** The description in other languages (`{ en: '…' }`). */
95
+ altLocales?: Record<string, string>
96
+ /** The point to keep in view when the picture is cropped, in percent. */
97
+ focal?: { x: number; y: number }
98
+ /** A library folder. Default: none. */
99
+ folder?: string
100
+ /** The file name shown in the library. Default: the file's name. Together with the folder and the size, it is how a second run finds the file again. */
101
+ name?: string
102
+ /** Keep the file in the library even when nothing uses it (default: true). */
103
+ library?: boolean
104
+ /** The file type, when the extension does not say. */
105
+ mime?: string
106
+ }
107
+
108
+ export interface SeedLinkOptions {
109
+ /** Open in a new tab. */
110
+ newTab?: boolean
111
+ /** Show in the dropdown of the link above it (menus). */
112
+ sub?: boolean
113
+ /** For a link to an entry: the language whose address is wanted (default: the default language). */
114
+ locale?: string
115
+ }
116
+
117
+ /** A menu link: `{ id, type: 'link', label, url, newTab, sub }`. */
118
+ export interface SeedLink {
119
+ id: string
120
+ type: 'link'
121
+ label: string
122
+ url: string
123
+ newTab: boolean
124
+ sub: boolean
125
+ }
126
+
127
+ /** Builders for the rich-text documents of `f.richtext()` fields. */
128
+ export interface SeedRich {
129
+ doc(...content: SeedRichNode[]): { type: 'doc'; content: SeedRichNode[] }
130
+ /** A paragraph from plain text and/or ready-made inline nodes (`s.rich.bold('x')`). */
131
+ p(...parts: (string | SeedRichNode)[]): SeedRichNode
132
+ h(level: 1 | 2 | 3 | 4 | 5 | 6, text: string): SeedRichNode
133
+ h2(text: string): SeedRichNode
134
+ h3(text: string): SeedRichNode
135
+ ul(...items: (string | SeedRichNode[])[]): SeedRichNode
136
+ ol(...items: (string | SeedRichNode[])[]): SeedRichNode
137
+ quote(text: string, by?: string): SeedRichNode
138
+ bold(text: string): SeedRichNode
139
+ italic(text: string): SeedRichNode
140
+ link(text: string, href: string): SeedRichNode
141
+ /** A picture from the library: pass what `s.upload` returned. */
142
+ image(media: string, alt?: string): SeedRichNode
143
+ }
144
+
145
+ export interface SeedContext {
146
+ /**
147
+ * Make sure an entry exists: made when nothing has this key yet, otherwise left exactly as
148
+ * it is (editors' changes stay). Returns the entry either way.
149
+ */
150
+ create<E extends EntityLike>(entity: E, data: SeedInsert<E>, options?: SeedWriteOptions<SeedInsert<E>>): Promise<SeedEntry>
151
+ create(entity: string, data: Record<string, any>, options?: SeedWriteOptions): Promise<SeedEntry>
152
+ /**
153
+ * Make sure an entry exists and carries these values: made when missing, otherwise brought
154
+ * up to the seed. Fields the seed leaves out are not touched.
155
+ */
156
+ upsert<E extends EntityLike>(entity: E, data: SeedInsert<E>, options?: SeedWriteOptions<SeedInsert<E>>): Promise<SeedEntry>
157
+ upsert(entity: string, data: Record<string, any>, options?: SeedWriteOptions): Promise<SeedEntry>
158
+ /**
159
+ * An entry in another language: only the `.localized()` fields. Follows how the entry was
160
+ * written: after `s.create` an existing translation is left alone, after `s.upsert` it is
161
+ * made to match.
162
+ */
163
+ translate(entry: SeedEntry, locale: string, data: Record<string, any>): Promise<void>
164
+ /** A global (site settings, menus): saved whole. */
165
+ global<E extends EntityLike>(entity: E, data: SeedInsert<E>, options?: SeedGlobalOptions<SeedInsert<E>>): Promise<SeedEntry>
166
+ global(entity: string, data: Record<string, any>, options?: SeedGlobalOptions): Promise<SeedEntry>
167
+ /**
168
+ * A file from disk (relative to the site's folder) into the media library; returns its id.
169
+ * A second run finds the file by name, folder and size and uploads nothing.
170
+ */
171
+ upload(file: string, options?: SeedUploadOptions): Promise<string>
172
+ /** A menu link. `to` is an address or an entry the seed made (its address on the website is worked out). */
173
+ link(label: string, to: string | SeedEntry, options?: SeedLinkOptions): SeedLink
174
+ /** Rich-text builders. */
175
+ rich: SeedRich
176
+ /** The languages of the site: the default first. Empty without `defineLocales`. */
177
+ locales: string[]
178
+ }
179
+
180
+ export interface SeedDefinition {
181
+ readonly __cms: 'seed'
182
+ run(s: SeedContext): Promise<void>
183
+ }
184
+
185
+ /** The seed of a site: `export default defineSeed(async (s) => { … })` in `seed/index.ts`. */
186
+ export function defineSeed(run: (s: SeedContext) => Promise<void> | void): SeedDefinition {
187
+ if (typeof run !== 'function') throw new Error('defineSeed() takes a function: defineSeed(async (s) => { … })')
188
+ return { __cms: 'seed', run: async (s) => { await run(s) } }
189
+ }
190
+
191
+ export function isSeed(value: unknown): value is SeedDefinition {
192
+ return !!value && typeof value === 'object' && (value as any).__cms === 'seed' && typeof (value as any).run === 'function'
193
+ }
194
+
195
+ // ── rich text builders ──────────────────────────────────────────────────────────
196
+
197
+ const text = (t: string, marks?: SeedRichNode['marks']): SeedRichNode => (marks ? { type: 'text', text: t, marks } : { type: 'text', text: t })
198
+ const inline = (parts: (string | SeedRichNode)[]): SeedRichNode[] => parts.map((x) => (typeof x === 'string' ? text(x) : x))
199
+ const paragraph = (...parts: (string | SeedRichNode)[]): SeedRichNode => ({ type: 'paragraph', content: inline(parts) })
200
+ const item = (x: string | SeedRichNode[]): SeedRichNode => ({
201
+ type: 'listItem',
202
+ content: [typeof x === 'string' ? paragraph(x) : { type: 'paragraph', content: x }],
203
+ })
204
+
205
+ /** The rich-text builders (also on `s.rich`); `image` needs the media's address, so the runner supplies it. */
206
+ export function richBuilders(mediaUrl: (id: string) => string): SeedRich {
207
+ const heading = (level: 1 | 2 | 3 | 4 | 5 | 6, t: string): SeedRichNode => ({ type: 'heading', attrs: { level }, content: [text(t)] })
208
+ return {
209
+ doc: (...content) => ({ type: 'doc', content }),
210
+ p: paragraph,
211
+ h: heading,
212
+ h2: (t) => heading(2, t),
213
+ h3: (t) => heading(3, t),
214
+ ul: (...items) => ({ type: 'bulletList', content: items.map(item) }),
215
+ ol: (...items) => ({ type: 'orderedList', content: items.map(item) }),
216
+ quote: (t, by) => ({
217
+ type: 'blockquote',
218
+ content: [paragraph(t), ...(by ? [{ type: 'paragraph', content: [text(`— ${by}`, [{ type: 'italic' }])] }] : [])],
219
+ }),
220
+ bold: (t) => text(t, [{ type: 'bold' }]),
221
+ italic: (t) => text(t, [{ type: 'italic' }]),
222
+ link: (t, href) => text(t, [{ type: 'link', attrs: { href } }]),
223
+ image: (media, alt) => ({ type: 'image', attrs: { src: mediaUrl(media), mediaId: media, alt: alt ?? '' } }),
224
+ }
225
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The one-time setup code of a fresh production deploy: who opens /admin/setup
3
+ * first must know it, so the first administrator is whoever can read the server log.
4
+ *
5
+ * 16 characters of a 32-letter alphabet (80 bits), shown as four groups of four:
6
+ * short enough to type, far beyond guessing. The alphabet has no I, L, O or U, so a
7
+ * code read off a log cannot be mistaken (an O typed for a 0 is accepted anyway).
8
+ */
9
+ const ALPHABET = 'ABCDEFGHJKMNPQRSTVWXYZ0123456789' // 32 symbols
10
+ const GROUPS = 4
11
+ const GROUP_SIZE = 4
12
+
13
+ /** A new random code, e.g. `K7QM-2XVD-R9TE-HC4Y`. */
14
+ export function generateSetupCode(): string {
15
+ // 256 is a multiple of 32, so a random byte maps onto the alphabet without bias.
16
+ const bytes = crypto.getRandomValues(new Uint8Array(GROUPS * GROUP_SIZE))
17
+ const chars = [...bytes].map((b) => ALPHABET[b % ALPHABET.length]!)
18
+ const groups: string[] = []
19
+ for (let i = 0; i < chars.length; i += GROUP_SIZE) groups.push(chars.slice(i, i + GROUP_SIZE).join(''))
20
+ return groups.join('-')
21
+ }
22
+
23
+ /**
24
+ * What a person typed or pasted, reduced to the code's own characters: case,
25
+ * spaces and dashes do not matter (`k7qm 2xvd…` works), nor O for 0 or I/L for 1.
26
+ */
27
+ export function normalizeSetupCode(input: unknown): string {
28
+ if (typeof input !== 'string') return ''
29
+ return input.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 64).replace(/O/g, '0').replace(/[IL]/g, '1')
30
+ }