@beechcms/api 0.6.0-preview.2 → 0.6.0-preview.4

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 (388) hide show
  1. package/README.md +4 -4
  2. package/assets/dashboard/BeechLogo.svg +18 -18
  3. package/assets/dashboard/BeechLogoLIght.svg +48 -48
  4. package/assets/dashboard/assets/chart-BwlCt-IA.js +39 -0
  5. package/assets/dashboard/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
  6. package/assets/dashboard/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
  7. package/assets/dashboard/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
  8. package/assets/dashboard/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
  9. package/assets/dashboard/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
  10. package/assets/dashboard/assets/index-BcVN-DNy.js +642 -0
  11. package/assets/dashboard/assets/index-Cf1yRCqG.css +1 -0
  12. package/assets/dashboard/assets/lora-cyrillic-ext-wght-normal-YcVxMP-u.woff2 +0 -0
  13. package/assets/dashboard/assets/lora-cyrillic-wght-normal-UWPuZLjM.woff2 +0 -0
  14. package/assets/dashboard/assets/lora-latin-ext-wght-normal-C2Wlntb9.woff2 +0 -0
  15. package/assets/dashboard/assets/lora-latin-wght-normal-BiLcIKcI.woff2 +0 -0
  16. package/assets/dashboard/assets/lora-math-wght-normal-sOy7rEfW.woff2 +0 -0
  17. package/assets/dashboard/assets/lora-symbols-wght-normal-DQ5VrUkH.woff2 +0 -0
  18. package/assets/dashboard/assets/lora-vietnamese-wght-normal-CfJ7gtf3.woff2 +0 -0
  19. package/assets/dashboard/assets/pie-chart-recharts-BMWpjFzf.js +1 -0
  20. package/assets/dashboard/assets/timeseries-chart-recharts-8_GwAFR0.js +1 -0
  21. package/assets/dashboard/beechLogoDark.svg +48 -48
  22. package/assets/dashboard/index.html +18 -18
  23. package/assets/dashboard/noResult.svg +42 -42
  24. package/assets/dashboard/sol.svg +3 -3
  25. package/assets/dashboard/undraw_enter_nwx3.svg +36 -36
  26. package/dist/auth/__fixtures__/in-memory-hash-provider.d.ts +5 -0
  27. package/dist/auth/__fixtures__/static-token-service.d.ts +6 -0
  28. package/dist/auth/bcrypt-hash-provider.d.ts +8 -0
  29. package/dist/auth/constants.d.ts +10 -0
  30. package/dist/auth/jose-token-service.d.ts +14 -0
  31. package/dist/auth/login.d.ts +32 -0
  32. package/dist/auth/refresh.d.ts +1 -0
  33. package/dist/factory.d.ts +45 -0
  34. package/dist/features/automations/action-executors/create-entry.executor.d.ts +7 -0
  35. package/dist/features/automations/action-executors/edit-field.executor.d.ts +7 -0
  36. package/dist/features/automations/action-executors/index.d.ts +13 -0
  37. package/dist/features/automations/action-executors/send-mail.executor.d.ts +7 -0
  38. package/dist/features/automations/action-executors/set-variable.executor.d.ts +15 -0
  39. package/dist/features/automations/action-executors/webhook.executor.d.ts +7 -0
  40. package/dist/features/automations/automation-runner.d.ts +13 -0
  41. package/dist/features/automations/automation-runner.utils.d.ts +3 -0
  42. package/dist/features/automations/automations.handler.d.ts +7 -0
  43. package/dist/features/automations/automations.schema.d.ts +191 -0
  44. package/dist/features/automations/context-resolver.d.ts +8 -0
  45. package/dist/features/automations/cron-runner.d.ts +9 -0
  46. package/dist/features/automations/cron-runner.utils.d.ts +1 -0
  47. package/dist/features/automations/filter-translation.d.ts +9 -0
  48. package/dist/features/automations/index.d.ts +7 -0
  49. package/dist/features/automations/template-grammar.d.ts +73 -0
  50. package/dist/features/automations/var-access-resolver.d.ts +6 -0
  51. package/dist/features/automations/when-evaluator.d.ts +3 -0
  52. package/dist/features/automations/when-pushdown.d.ts +2 -0
  53. package/dist/features/backrefs/backrefs.handler.d.ts +3 -0
  54. package/dist/features/backrefs/d1-backref.repository.d.ts +17 -0
  55. package/dist/features/backrefs/index.d.ts +1 -0
  56. package/dist/features/content/constants.d.ts +12 -0
  57. package/dist/features/content/handlers/bulk.handler.d.ts +3 -0
  58. package/dist/features/content/handlers/create.d.ts +3 -0
  59. package/dist/features/content/handlers/delete.d.ts +3 -0
  60. package/dist/features/content/handlers/facets.d.ts +3 -0
  61. package/dist/features/content/handlers/get.d.ts +4 -0
  62. package/dist/features/content/handlers/helpers.d.ts +12 -0
  63. package/dist/features/content/handlers/list.d.ts +3 -0
  64. package/dist/features/content/handlers/update.d.ts +3 -0
  65. package/dist/features/content/index.d.ts +4 -0
  66. package/dist/features/dashboard-layout/dashboard-layout.handler.d.ts +7 -0
  67. package/dist/features/dashboard-layout/index.d.ts +1 -0
  68. package/dist/features/draft/draft.handler.d.ts +4 -0
  69. package/dist/features/draft/draft.middleware.d.ts +9 -0
  70. package/dist/features/draft/index.d.ts +1 -0
  71. package/{src/features/email/email.provider.ts → dist/features/email/email.provider.d.ts} +19 -24
  72. package/dist/features/email/email.service.d.ts +13 -0
  73. package/dist/features/email/email.types.d.ts +94 -0
  74. package/{src/features/email/index.ts → dist/features/email/index.d.ts} +3 -16
  75. package/dist/features/email/providers/resend.d.ts +36 -0
  76. package/dist/features/email/providers/smtp.d.ts +11 -0
  77. package/dist/features/email/templates/automation-mail.d.ts +8 -0
  78. package/dist/features/email/templates/password-changed.d.ts +15 -0
  79. package/dist/features/email/templates/password-reset.d.ts +18 -0
  80. package/dist/features/email/templates/shell.d.ts +58 -0
  81. package/dist/features/notifications/index.d.ts +1 -0
  82. package/dist/features/notifications/notifications.handler.d.ts +15 -0
  83. package/dist/features/password-reset/index.d.ts +6 -0
  84. package/dist/features/password-reset/request.d.ts +10 -0
  85. package/dist/features/password-reset/reset.d.ts +9 -0
  86. package/dist/features/rotate-field/index.d.ts +1 -0
  87. package/dist/features/rotate-field/rotate-field.handler.d.ts +7 -0
  88. package/dist/features/rotate-field/rotate-field.schema.d.ts +11 -0
  89. package/dist/features/schema/schema.handler.d.ts +7 -0
  90. package/dist/features/seeds/index.d.ts +1 -0
  91. package/dist/features/seeds/seeds.handler.d.ts +6 -0
  92. package/dist/features/settings/settings.handler.d.ts +7 -0
  93. package/dist/features/setup/index.d.ts +7 -0
  94. package/dist/features/stats/index.d.ts +1 -0
  95. package/dist/features/stats/stats.handler.d.ts +7 -0
  96. package/dist/features/webhooks/index.d.ts +3 -0
  97. package/dist/index.d.ts +7 -0
  98. package/dist/index.js +9732 -0
  99. package/dist/media-utils.d.ts +25 -0
  100. package/dist/middleware/auth-providers.middleware.d.ts +8 -0
  101. package/dist/middleware/observability.middleware.d.ts +20 -0
  102. package/dist/middleware/queue.middleware.d.ts +11 -0
  103. package/dist/middleware/rate-limit.middleware.d.ts +9 -0
  104. package/dist/middleware/repository.middleware.d.ts +34 -0
  105. package/dist/middleware/seed-registry.middleware.d.ts +10 -0
  106. package/dist/middleware/storage.middleware.d.ts +7 -0
  107. package/dist/middleware.d.ts +11 -0
  108. package/dist/public/access-policy.d.ts +12 -0
  109. package/dist/public/api-key-middleware.d.ts +6 -0
  110. package/dist/public/cache-utils.d.ts +10 -0
  111. package/dist/public/entry-projection.d.ts +2 -0
  112. package/dist/public/idempotency.d.ts +9 -0
  113. package/dist/public/index.d.ts +11 -0
  114. package/dist/public/problem-details.d.ts +31 -0
  115. package/dist/public/public-add.d.ts +3 -0
  116. package/dist/public/public-edit.d.ts +5 -0
  117. package/dist/public/public-errors.d.ts +13 -0
  118. package/dist/public/public-read.d.ts +3 -0
  119. package/dist/public/public-routes.d.ts +3 -0
  120. package/dist/public/query-builder.d.ts +28 -0
  121. package/dist/public/rate-limit-middleware.d.ts +3 -0
  122. package/dist/public/read-list.d.ts +26 -0
  123. package/dist/public/read-single.d.ts +22 -0
  124. package/dist/public/response-builder.d.ts +22 -0
  125. package/dist/public/sanitize.d.ts +23 -0
  126. package/{src/public/slug-utils.ts → dist/public/slug-utils.d.ts} +3 -10
  127. package/dist/rate-limit/cloudflare-rate-limiter.d.ts +6 -0
  128. package/dist/rate-limit/in-memory-rate-limiter.d.ts +7 -0
  129. package/dist/rate-limit/no-op-rate-limiter.d.ts +4 -0
  130. package/dist/search-utils.d.ts +54 -0
  131. package/dist/search.d.ts +6 -0
  132. package/dist/shared/apply-policies.d.ts +10 -0
  133. package/dist/shared/automations.repository.d1.d.ts +12 -0
  134. package/dist/shared/background-notification-service.d.ts +18 -0
  135. package/dist/shared/base.repository.d1.d.ts +18 -0
  136. package/dist/shared/cloudflare-queue-service.d.ts +11 -0
  137. package/dist/shared/content-utils.d.ts +21 -0
  138. package/dist/shared/content.repository.d1.d.ts +68 -0
  139. package/dist/shared/d1-activity-log.repository.d.ts +13 -0
  140. package/dist/shared/d1-activity-logger.d.ts +20 -0
  141. package/dist/shared/d1-analytics.repository.d.ts +20 -0
  142. package/dist/shared/d1-content-scan.repository.d.ts +7 -0
  143. package/dist/shared/d1-notification.repository.d.ts +17 -0
  144. package/dist/shared/d1-password-reset-token.repository.d.ts +10 -0
  145. package/dist/shared/d1-search.repository.d.ts +14 -0
  146. package/dist/shared/d1-session.repository.d.ts +12 -0
  147. package/dist/shared/d1-setup-checklist.repository.d.ts +12 -0
  148. package/dist/shared/d1-user.repository.d.ts +18 -0
  149. package/dist/shared/d1-widget.repository.d.ts +31 -0
  150. package/dist/shared/dashboard-layout.repository.d1.d.ts +9 -0
  151. package/dist/shared/demo-data-sql.d.ts +1 -0
  152. package/dist/shared/demo-data.repository.d1.d.ts +6 -0
  153. package/dist/shared/execution-context-scheduler.d.ts +6 -0
  154. package/dist/shared/fixed-clock.d.ts +13 -0
  155. package/dist/shared/fts-sync.d.ts +1 -0
  156. package/dist/shared/idempotency.repository.d1.d.ts +16 -0
  157. package/dist/shared/in-memory-activity-logger.d.ts +11 -0
  158. package/dist/shared/in-memory-notification-service.d.ts +11 -0
  159. package/dist/shared/in-memory-queue-service.d.ts +16 -0
  160. package/dist/shared/in-memory-seed.repository.d.ts +18 -0
  161. package/dist/shared/media.repository.d1.d.ts +35 -0
  162. package/dist/shared/qstash-notification-service.d.ts +18 -0
  163. package/dist/shared/query-utils.d.ts +36 -0
  164. package/dist/shared/queue-consumer.d.ts +9 -0
  165. package/dist/shared/request-utils.d.ts +13 -0
  166. package/dist/shared/schema-mutator.d1.d.ts +12 -0
  167. package/dist/shared/seed-layout.repository.d1.d.ts +9 -0
  168. package/dist/shared/seed-registry-cache.d.ts +12 -0
  169. package/dist/shared/seed.repository.d1.d.ts +13 -0
  170. package/dist/shared/sequential-id-generator.d.ts +13 -0
  171. package/dist/shared/site-settings.repository.d1.d.ts +7 -0
  172. package/dist/shared/storage/factory.d.ts +8 -0
  173. package/dist/shared/storage/s3-bucket.d.ts +43 -0
  174. package/dist/shared/storage-utils.d.ts +7 -0
  175. package/dist/shared/system-stats.repository.d1.d.ts +25 -0
  176. package/dist/types.d.ts +87 -0
  177. package/dist/upload.d.ts +16 -0
  178. package/dist/widget.d.ts +7 -0
  179. package/migrations/0000_v040_base.sql +265 -265
  180. package/migrations/0029_automations.sql +14 -14
  181. package/migrations/0030_test_seeds.sql +125 -125
  182. package/package.json +28 -18
  183. package/assets/dashboard/assets/chart-BrJFdsGZ.js +0 -39
  184. package/assets/dashboard/assets/index-CIaoMxuB.css +0 -1
  185. package/assets/dashboard/assets/index-wTKgygsg.js +0 -636
  186. package/assets/dashboard/assets/pie-chart-recharts-BEaE1FOE.js +0 -1
  187. package/assets/dashboard/assets/timeseries-chart-recharts-DmWM6imF.js +0 -1
  188. package/src/auth/__fixtures__/in-memory-hash-provider.ts +0 -17
  189. package/src/auth/__fixtures__/static-token-service.ts +0 -22
  190. package/src/auth/bcrypt-hash-provider.ts +0 -24
  191. package/src/auth/constants.ts +0 -14
  192. package/src/auth/generate-refresh-token.test.ts +0 -23
  193. package/src/auth/hash-provider.test.ts +0 -55
  194. package/src/auth/jose-token-service.ts +0 -62
  195. package/src/auth/jwt-claims-passthrough.test.ts +0 -87
  196. package/src/auth/login.test.ts +0 -100
  197. package/src/auth/login.ts +0 -78
  198. package/src/auth/refresh.ts +0 -11
  199. package/src/auth/token-service.test.ts +0 -90
  200. package/src/factory.ts +0 -370
  201. package/src/features/automations/__tests__/action-executors.test.ts +0 -255
  202. package/src/features/automations/__tests__/automation-runner.test.ts +0 -196
  203. package/src/features/automations/__tests__/automation-runner.utils.test.ts +0 -60
  204. package/src/features/automations/__tests__/automations.handler.test.ts +0 -264
  205. package/src/features/automations/__tests__/automations.repository.test.ts +0 -163
  206. package/src/features/automations/__tests__/automations.schema.test.ts +0 -224
  207. package/src/features/automations/__tests__/context-resolver.test.ts +0 -126
  208. package/src/features/automations/__tests__/cron-runner.test.ts +0 -267
  209. package/src/features/automations/__tests__/cron-runner.utils.test.ts +0 -144
  210. package/src/features/automations/__tests__/set-variable.executor.test.ts +0 -383
  211. package/src/features/automations/__tests__/template-grammar.test.ts +0 -308
  212. package/src/features/automations/__tests__/webhook.executor.test.ts +0 -142
  213. package/src/features/automations/__tests__/when-evaluator.test.ts +0 -274
  214. package/src/features/automations/__tests__/when-pushdown.test.ts +0 -281
  215. package/src/features/automations/action-executors/create-entry.executor.ts +0 -27
  216. package/src/features/automations/action-executors/edit-field.executor.ts +0 -26
  217. package/src/features/automations/action-executors/index.ts +0 -37
  218. package/src/features/automations/action-executors/send-mail.executor.ts +0 -53
  219. package/src/features/automations/action-executors/set-variable.executor.ts +0 -159
  220. package/src/features/automations/action-executors/webhook.executor.ts +0 -67
  221. package/src/features/automations/automation-runner.ts +0 -85
  222. package/src/features/automations/automation-runner.utils.ts +0 -47
  223. package/src/features/automations/automations.handler.ts +0 -197
  224. package/src/features/automations/automations.schema.ts +0 -177
  225. package/src/features/automations/context-resolver.ts +0 -152
  226. package/src/features/automations/cron-runner.ts +0 -140
  227. package/src/features/automations/cron-runner.utils.ts +0 -44
  228. package/src/features/automations/filter-translation.ts +0 -46
  229. package/src/features/automations/index.ts +0 -16
  230. package/src/features/automations/template-grammar.ts +0 -245
  231. package/src/features/automations/var-access-resolver.ts +0 -140
  232. package/src/features/automations/when-evaluator.ts +0 -87
  233. package/src/features/automations/when-pushdown.ts +0 -57
  234. package/src/features/backrefs/__tests__/backrefs.handler.test.ts +0 -359
  235. package/src/features/backrefs/backrefs.handler.ts +0 -168
  236. package/src/features/backrefs/d1-backref.repository.ts +0 -84
  237. package/src/features/backrefs/index.ts +0 -5
  238. package/src/features/content/constants.ts +0 -16
  239. package/src/features/content/handlers/bulk.handler.ts +0 -185
  240. package/src/features/content/handlers/create.ts +0 -129
  241. package/src/features/content/handlers/delete.ts +0 -62
  242. package/src/features/content/handlers/facets.ts +0 -49
  243. package/src/features/content/handlers/get.ts +0 -120
  244. package/src/features/content/handlers/helpers.test.ts +0 -180
  245. package/src/features/content/handlers/helpers.ts +0 -93
  246. package/src/features/content/handlers/list.ts +0 -174
  247. package/src/features/content/handlers/update.ts +0 -174
  248. package/src/features/content/index.ts +0 -26
  249. package/src/features/dashboard-layout/__tests__/dashboard-layout.handler.test.ts +0 -388
  250. package/src/features/dashboard-layout/dashboard-layout.handler.ts +0 -206
  251. package/src/features/dashboard-layout/index.ts +0 -5
  252. package/src/features/draft/draft.handler.ts +0 -195
  253. package/src/features/draft/draft.middleware.ts +0 -66
  254. package/src/features/draft/index.ts +0 -5
  255. package/src/features/email/email.service.ts +0 -98
  256. package/src/features/email/email.types.ts +0 -119
  257. package/src/features/email/providers/resend.ts +0 -67
  258. package/src/features/email/providers/smtp.ts +0 -55
  259. package/src/features/email/templates/automation-mail.ts +0 -19
  260. package/src/features/email/templates/password-changed.ts +0 -63
  261. package/src/features/email/templates/password-reset.ts +0 -68
  262. package/src/features/email/templates/shell.ts +0 -96
  263. package/src/features/notifications/index.ts +0 -5
  264. package/src/features/notifications/notifications.handler.ts +0 -105
  265. package/src/features/password-reset/index.ts +0 -19
  266. package/src/features/password-reset/request.ts +0 -92
  267. package/src/features/password-reset/reset.ts +0 -102
  268. package/src/features/rotate-field/index.ts +0 -5
  269. package/src/features/rotate-field/rotate-field.handler.ts +0 -132
  270. package/src/features/rotate-field/rotate-field.schema.ts +0 -17
  271. package/src/features/schema/schema.handler.ts +0 -131
  272. package/src/features/seeds/index.ts +0 -5
  273. package/src/features/seeds/seeds.handler.test.ts +0 -1199
  274. package/src/features/seeds/seeds.handler.ts +0 -558
  275. package/src/features/settings/__tests__/settings.handler.test.ts +0 -555
  276. package/src/features/settings/settings.handler.ts +0 -392
  277. package/src/features/setup/index.ts +0 -288
  278. package/src/features/stats/index.ts +0 -5
  279. package/src/features/stats/stats.handler.ts +0 -420
  280. package/src/features/webhooks/index.ts +0 -63
  281. package/src/index.ts +0 -65
  282. package/src/media-utils.ts +0 -82
  283. package/src/middleware/auth-providers.middleware.test.ts +0 -85
  284. package/src/middleware/auth-providers.middleware.ts +0 -45
  285. package/src/middleware/observability.middleware.test.ts +0 -93
  286. package/src/middleware/observability.middleware.ts +0 -70
  287. package/src/middleware/rate-limit.middleware.ts +0 -45
  288. package/src/middleware/repository.middleware.ts +0 -117
  289. package/src/middleware/seed-registry.middleware.test.ts +0 -97
  290. package/src/middleware/seed-registry.middleware.ts +0 -21
  291. package/src/middleware/storage.middleware.ts +0 -25
  292. package/src/middleware.ts +0 -45
  293. package/src/public/access-policy.ts +0 -27
  294. package/src/public/api-key-middleware.ts +0 -57
  295. package/src/public/cache-utils.ts +0 -38
  296. package/src/public/entry-projection.ts +0 -46
  297. package/src/public/idempotency.ts +0 -23
  298. package/src/public/index.ts +0 -16
  299. package/src/public/problem-details.ts +0 -124
  300. package/src/public/public-add.ts +0 -114
  301. package/src/public/public-edit.ts +0 -163
  302. package/src/public/public-errors.ts +0 -19
  303. package/src/public/public-read.ts +0 -63
  304. package/src/public/public-routes.ts +0 -88
  305. package/src/public/query-builder.test.ts +0 -224
  306. package/src/public/query-builder.ts +0 -156
  307. package/src/public/rate-limit-middleware.ts +0 -34
  308. package/src/public/read-list.ts +0 -54
  309. package/src/public/read-single.ts +0 -48
  310. package/src/public/response-builder.ts +0 -30
  311. package/src/public/sanitize.ts +0 -69
  312. package/src/rate-limit/cloudflare-rate-limiter.test.ts +0 -30
  313. package/src/rate-limit/cloudflare-rate-limiter.ts +0 -15
  314. package/src/rate-limit/in-memory-rate-limiter.test.ts +0 -37
  315. package/src/rate-limit/in-memory-rate-limiter.ts +0 -17
  316. package/src/rate-limit/no-op-rate-limiter.test.ts +0 -22
  317. package/src/rate-limit/no-op-rate-limiter.ts +0 -11
  318. package/src/search-utils.test.ts +0 -211
  319. package/src/search-utils.ts +0 -213
  320. package/src/search.ts +0 -65
  321. package/src/shared/apply-policies.test.ts +0 -81
  322. package/src/shared/apply-policies.ts +0 -67
  323. package/src/shared/automations.repository.d1.ts +0 -150
  324. package/src/shared/background-notification-service.test.ts +0 -62
  325. package/src/shared/background-notification-service.ts +0 -52
  326. package/src/shared/base.repository.d1.ts +0 -32
  327. package/src/shared/content-utils.test.ts +0 -165
  328. package/src/shared/content-utils.ts +0 -86
  329. package/src/shared/content.repository.d1.test.ts +0 -507
  330. package/src/shared/content.repository.d1.ts +0 -851
  331. package/src/shared/d1-activity-log.repository.test.ts +0 -140
  332. package/src/shared/d1-activity-log.repository.ts +0 -105
  333. package/src/shared/d1-activity-logger.test.ts +0 -86
  334. package/src/shared/d1-activity-logger.ts +0 -67
  335. package/src/shared/d1-analytics.repository.test.ts +0 -78
  336. package/src/shared/d1-analytics.repository.ts +0 -85
  337. package/src/shared/d1-content-scan.repository.test.ts +0 -80
  338. package/src/shared/d1-content-scan.repository.ts +0 -37
  339. package/src/shared/d1-notification.repository.test.ts +0 -128
  340. package/src/shared/d1-notification.repository.ts +0 -118
  341. package/src/shared/d1-password-reset-token.repository.test.ts +0 -81
  342. package/src/shared/d1-password-reset-token.repository.ts +0 -56
  343. package/src/shared/d1-search.repository.test.ts +0 -87
  344. package/src/shared/d1-search.repository.ts +0 -88
  345. package/src/shared/d1-session.repository.test.ts +0 -125
  346. package/src/shared/d1-session.repository.ts +0 -102
  347. package/src/shared/d1-setup-checklist.repository.ts +0 -36
  348. package/src/shared/d1-user.repository.test.ts +0 -151
  349. package/src/shared/d1-user.repository.ts +0 -119
  350. package/src/shared/d1-widget.repository.test.ts +0 -267
  351. package/src/shared/d1-widget.repository.ts +0 -385
  352. package/src/shared/dashboard-layout.repository.d1.test.ts +0 -135
  353. package/src/shared/dashboard-layout.repository.d1.ts +0 -58
  354. package/src/shared/demo-data-sql.ts +0 -216
  355. package/src/shared/demo-data.repository.d1.ts +0 -20
  356. package/src/shared/execution-context-scheduler.ts +0 -13
  357. package/src/shared/fixed-clock.ts +0 -25
  358. package/src/shared/fts-sync.ts +0 -8
  359. package/src/shared/idempotency.repository.d1.test.ts +0 -83
  360. package/src/shared/idempotency.repository.d1.ts +0 -60
  361. package/src/shared/in-memory-activity-logger.ts +0 -19
  362. package/src/shared/in-memory-notification-service.ts +0 -19
  363. package/src/shared/in-memory-seed.repository.ts +0 -58
  364. package/src/shared/media.repository.d1.test.ts +0 -107
  365. package/src/shared/media.repository.d1.ts +0 -68
  366. package/src/shared/qstash-notification-service.test.ts +0 -67
  367. package/src/shared/qstash-notification-service.ts +0 -55
  368. package/src/shared/query-utils.ts +0 -141
  369. package/src/shared/request-utils.ts +0 -26
  370. package/src/shared/schema-mutator.d1.test.ts +0 -142
  371. package/src/shared/schema-mutator.d1.ts +0 -64
  372. package/src/shared/seed-layout.repository.d1.test.ts +0 -114
  373. package/src/shared/seed-layout.repository.d1.ts +0 -62
  374. package/src/shared/seed-registry-cache.test.ts +0 -68
  375. package/src/shared/seed-registry-cache.ts +0 -49
  376. package/src/shared/seed.repository.d1.test.ts +0 -143
  377. package/src/shared/seed.repository.d1.ts +0 -98
  378. package/src/shared/sequential-id-generator.ts +0 -33
  379. package/src/shared/site-settings.repository.d1.ts +0 -53
  380. package/src/shared/storage/factory.ts +0 -41
  381. package/src/shared/storage/s3-bucket.ts +0 -195
  382. package/src/shared/storage-utils.ts +0 -40
  383. package/src/shared/system-stats.repository.d1.test.ts +0 -58
  384. package/src/shared/system-stats.repository.d1.ts +0 -48
  385. package/src/types.ts +0 -90
  386. package/src/upload.ts +0 -198
  387. package/src/widget.test.ts +0 -85
  388. package/src/widget.ts +0 -251
@@ -1,1199 +0,0 @@
1
- // SPDX-License-Identifier: BUSL-1.1
2
- // Copyright (c) 2024–2026 Flavio De Musso. All rights reserved.
3
- // See LICENSE in the repository root for license terms.
4
-
5
- import { describe, it, expect, vi, beforeEach } from 'vitest'
6
- import { Hono } from 'hono'
7
- import type { Branch, ISeedRepository, ISchemaMutator, Seed, SeedRecord } from '@beechcms/core'
8
- import { seedsApp } from './seeds.handler'
9
-
10
- // ─── Fixtures ────────────────────────────────────────────────────────────────
11
-
12
- const baseSeed: Seed = {
13
- slug: 'articles',
14
- label: 'Articles',
15
- displayNameAlias: 'title',
16
- branches: [
17
- { id: 'br_01', alias: 'title', label: 'Title', type: 'text' },
18
- { id: 'br_02', alias: 'body', label: 'Body', type: 'richtext' },
19
- ],
20
- }
21
-
22
- const baseRecord: SeedRecord = {
23
- slug: 'articles',
24
- definition: baseSeed,
25
- status: 'active',
26
- source: 'runtime',
27
- createdAt: 0,
28
- updatedAt: 0,
29
- }
30
-
31
- // ─── Fake repositories ────────────────────────────────────────────────────────
32
-
33
- function makeRepo(overrides: Partial<ISeedRepository> = {}): ISeedRepository {
34
- return {
35
- listActive: vi.fn().mockResolvedValue([baseSeed]),
36
- listAll: vi.fn().mockResolvedValue([baseRecord]),
37
- get: vi.fn().mockResolvedValue(null),
38
- upsert: vi.fn().mockResolvedValue(undefined),
39
- softDelete: vi.fn().mockResolvedValue(undefined),
40
- hardDelete: vi.fn().mockResolvedValue(undefined),
41
- getRegistryVersion: vi.fn().mockResolvedValue(1),
42
- bumpRegistryVersion: vi.fn().mockResolvedValue(2),
43
- ...overrides,
44
- }
45
- }
46
-
47
- function makeMutator(overrides: Partial<ISchemaMutator> = {}): ISchemaMutator {
48
- return {
49
- getColumns: vi.fn().mockResolvedValue(null),
50
- execDdl: vi.fn().mockResolvedValue(undefined),
51
- dropTable: vi.fn().mockResolvedValue(undefined),
52
- dropColumn: vi.fn().mockResolvedValue(undefined),
53
- renameColumn: vi.fn().mockResolvedValue(undefined),
54
- execDestructive: vi.fn().mockResolvedValue(undefined),
55
- ...overrides,
56
- }
57
- }
58
-
59
- function makeActivityLogger() {
60
- return { log: vi.fn() }
61
- }
62
-
63
- // ─── App builder ─────────────────────────────────────────────────────────────
64
-
65
- function buildApp(opts: {
66
- role?: string
67
- jwtPayload?: Record<string, unknown> | null
68
- repo?: ISeedRepository
69
- mutator?: ISchemaMutator
70
- backrefMap?: Map<string, any[]>
71
- automationRepository?: any
72
- db?: any
73
- bucket?: any
74
- mediaRepository?: any
75
- systemStatsRepository?: any
76
- } = {}) {
77
- const app = new Hono()
78
- const repo = opts.repo ?? makeRepo()
79
- const mutator = opts.mutator ?? makeMutator()
80
- const backrefMap = opts.backrefMap ?? new Map()
81
- const activityLogger = makeActivityLogger()
82
- // Default stub DB (used by hard-delete R2 cascade) — no results
83
- const db = opts.db ?? { prepare: () => ({ all: async () => ({ results: [] }) }) }
84
- const automationRepository = opts.automationRepository ?? { list: async () => [] }
85
- const bucket = opts.bucket ?? { delete: vi.fn().mockResolvedValue(undefined) }
86
- const mediaRepository = opts.mediaRepository ?? { getByKey: vi.fn().mockResolvedValue(null), untrack: vi.fn().mockResolvedValue(undefined) }
87
- const systemStatsRepository = opts.systemStatsRepository ?? { decrementStorage: vi.fn().mockResolvedValue(undefined) }
88
-
89
- app.use('*', async (c, next) => {
90
- const jwtPayload = opts.jwtPayload !== undefined
91
- ? opts.jwtPayload
92
- : (opts.role ? { sub: 'u1', email: 'a@b.com', role: opts.role } : null)
93
- c.set('jwtPayload' as never, jwtPayload)
94
- c.set('seedRepository' as never, repo)
95
- c.set('schemaMutator' as never, mutator)
96
- c.set('backrefMap' as never, backrefMap)
97
- c.set('activityLogger' as never, activityLogger)
98
- c.set('automationRepository' as never, automationRepository)
99
- c.set('env' as never, { ENV: 'test', DB: db })
100
- c.set('bucket' as never, bucket)
101
- c.set('mediaRepository' as never, mediaRepository)
102
- c.set('systemStatsRepository' as never, systemStatsRepository)
103
- await next()
104
- })
105
- app.route('/', seedsApp)
106
-
107
- // Default `c.env` (used by internalErrorDetail) so error paths don't crash
108
- // on `context.env.ENV` when the test doesn't pass an explicit env binding.
109
- const defaultEnv = { ENV: 'test', DB: db }
110
- const originalRequest = app.request.bind(app)
111
- app.request = ((input: any, init?: any, env?: any, executionCtx?: any) =>
112
- originalRequest(input, init, env ?? defaultEnv, executionCtx)) as typeof app.request
113
-
114
- return { app, repo, mutator, activityLogger, bucket, mediaRepository, systemStatsRepository, db }
115
- }
116
-
117
- // ─── Tests ────────────────────────────────────────────────────────────────────
118
-
119
- describe('GET /', () => {
120
- it('403 for non-admin', async () => {
121
- const { app } = buildApp({ role: 'user' })
122
- const res = await app.request('/', { method: 'GET' })
123
- expect(res.status).toBe(403)
124
- })
125
-
126
- it('200 returns all records', async () => {
127
- const { app } = buildApp({ role: 'admin' })
128
- const res = await app.request('/', { method: 'GET' })
129
- expect(res.status).toBe(200)
130
- const body = await res.json() as any[]
131
- expect(body).toHaveLength(1)
132
- expect(body[0].slug).toBe('articles')
133
- })
134
- })
135
-
136
- describe('GET /:slug', () => {
137
- it('404 for missing seed', async () => {
138
- const { app } = buildApp({ role: 'admin' })
139
- const res = await app.request('/nope', { method: 'GET' })
140
- expect(res.status).toBe(404)
141
- })
142
-
143
- it('200 returns the record', async () => {
144
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
145
- const { app } = buildApp({ role: 'admin', repo })
146
- const res = await app.request('/articles', { method: 'GET' })
147
- expect(res.status).toBe(200)
148
- const body = await res.json() as any
149
- expect(body.slug).toBe('articles')
150
- })
151
- })
152
-
153
- describe('POST / (create)', () => {
154
- it('403 for non-admin', async () => {
155
- const { app } = buildApp({ role: 'user' })
156
- const res = await app.request('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(baseSeed) })
157
- expect(res.status).toBe(403)
158
- })
159
-
160
- it('409 when slug already active', async () => {
161
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
162
- const { app } = buildApp({ role: 'admin', repo })
163
- const res = await app.request('/', {
164
- method: 'POST',
165
- headers: { 'Content-Type': 'application/json' },
166
- body: JSON.stringify(baseSeed),
167
- })
168
- expect(res.status).toBe(409)
169
- })
170
-
171
- it('creates new seed: planCreateSeed DDL emitted, upsert called, 201', async () => {
172
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
173
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(null) })
174
- const { app, activityLogger } = buildApp({ role: 'admin', repo, mutator })
175
-
176
- const newSeed: Seed = {
177
- slug: 'notes',
178
- label: 'Notes',
179
- displayNameAlias: 'title',
180
- branches: [{ id: 'br_01', alias: 'title', label: 'Title', type: 'text' }],
181
- }
182
- const res = await app.request('/', {
183
- method: 'POST',
184
- headers: { 'Content-Type': 'application/json' },
185
- body: JSON.stringify(newSeed),
186
- })
187
- expect(res.status).toBe(201)
188
-
189
- const ddlCalls = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls
190
- expect(ddlCalls.length).toBe(1)
191
- const stmts: string[] = ddlCalls[0][0]
192
- expect(stmts.some((s: string) => s.includes('CREATE TABLE') && s.includes('content_notes'))).toBe(true)
193
- expect(stmts.some((s: string) => s.includes('DROP'))).toBe(false)
194
-
195
- expect((repo.upsert as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
196
- expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
197
- expect(activityLogger.log.mock.calls.length).toBe(1)
198
- expect(activityLogger.log.mock.calls[0][0].action).toBe('create')
199
-
200
- const body = await res.json() as any
201
- expect(body.slug).toBe('notes')
202
- })
203
-
204
- it('assigns br_NN ids to branches without ids', async () => {
205
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
206
- const mutator = makeMutator()
207
- const { app } = buildApp({ role: 'admin', repo, mutator })
208
-
209
- const noIdSeed = {
210
- slug: 'tags',
211
- label: 'Tags',
212
- displayNameAlias: 'name',
213
- branches: [{ alias: 'name', label: 'Name', type: 'text' }],
214
- }
215
- const res = await app.request('/', {
216
- method: 'POST',
217
- headers: { 'Content-Type': 'application/json' },
218
- body: JSON.stringify(noIdSeed),
219
- })
220
- expect(res.status).toBe(201)
221
- const upsertArg = (repo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as Seed
222
- expect(upsertArg.branches[0].id).toMatch(/^br_\d+$/)
223
- })
224
-
225
- it('revives a soft-deleted seed without failing on IF NOT EXISTS', async () => {
226
- const deletedRecord: SeedRecord = { ...baseRecord, status: 'deleted' }
227
- const repo = makeRepo({
228
- get: vi.fn().mockResolvedValue(deletedRecord),
229
- listActive: vi.fn().mockResolvedValue([]),
230
- })
231
- const existingCols = new Set(['id', 'title'])
232
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
233
- const { app } = buildApp({ role: 'admin', repo, mutator })
234
-
235
- const res = await app.request('/', {
236
- method: 'POST',
237
- headers: { 'Content-Type': 'application/json' },
238
- body: JSON.stringify(baseSeed),
239
- })
240
- expect(res.status).toBe(201)
241
- // No CREATE TABLE was emitted (table already exists), planExtendSeed path taken
242
- const stmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls[0]?.[0] ?? []
243
- expect(stmts.every((s: string) => !s.includes('CREATE TABLE IF NOT EXISTS content_articles') || s.includes('IF NOT EXISTS'))).toBe(true)
244
- })
245
-
246
- it('422 for unknown relation target', async () => {
247
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
248
- const { app } = buildApp({ role: 'admin', repo })
249
-
250
- const relSeed: Seed = {
251
- slug: 'posts',
252
- label: 'Posts',
253
- displayNameAlias: 'title',
254
- branches: [
255
- { id: 'br_01', alias: 'title', label: 'Title', type: 'text' },
256
- { id: 'br_02', alias: 'author', label: 'Author', type: 'relation', targetSeed: 'nonexistent' },
257
- ],
258
- }
259
- const res = await app.request('/', {
260
- method: 'POST',
261
- headers: { 'Content-Type': 'application/json' },
262
- body: JSON.stringify(relSeed),
263
- })
264
- expect(res.status).toBe(422)
265
- })
266
- })
267
-
268
- describe('PUT /:slug (edit)', () => {
269
- it('403 for non-admin', async () => {
270
- const { app } = buildApp({ role: 'user' })
271
- const res = await app.request('/articles', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(baseSeed) })
272
- expect(res.status).toBe(403)
273
- })
274
-
275
- it('422 on alias rename (same id, different alias)', async () => {
276
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
277
- const { app } = buildApp({ role: 'admin', repo })
278
-
279
- const renamed: Seed = {
280
- ...baseSeed,
281
- branches: [
282
- { id: 'br_01', alias: 'headline', label: 'Headline', type: 'text' }, // alias changed
283
- { id: 'br_02', alias: 'body', label: 'Body', type: 'richtext' },
284
- ],
285
- }
286
- const res = await app.request('/articles', {
287
- method: 'PUT',
288
- headers: { 'Content-Type': 'application/json' },
289
- body: JSON.stringify(renamed),
290
- })
291
- expect(res.status).toBe(422)
292
- const body = await res.json() as any
293
- expect(body.type).toContain('alias-rename-not-supported')
294
- })
295
-
296
- it('422 on branch type change', async () => {
297
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
298
- const { app } = buildApp({ role: 'admin', repo })
299
-
300
- const typeChanged: Seed = {
301
- ...baseSeed,
302
- branches: [
303
- { id: 'br_01', alias: 'title', label: 'Title', type: 'number' }, // type changed
304
- { id: 'br_02', alias: 'body', label: 'Body', type: 'richtext' },
305
- ],
306
- }
307
- const res = await app.request('/articles', {
308
- method: 'PUT',
309
- headers: { 'Content-Type': 'application/json' },
310
- body: JSON.stringify(typeChanged),
311
- })
312
- expect(res.status).toBe(422)
313
- const body = await res.json() as any
314
- expect(body.type).toContain('branch-type-change-not-supported')
315
- })
316
-
317
- it('add branch emits ADD COLUMN, no DROP', async () => {
318
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
319
- const existingCols = new Set(['id', 'title', 'body'])
320
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
321
- const { app } = buildApp({ role: 'admin', repo, mutator })
322
-
323
- const withNew: Seed = {
324
- ...baseSeed,
325
- branches: [
326
- ...baseSeed.branches,
327
- { id: 'br_03', alias: 'summary', label: 'Summary', type: 'text' },
328
- ],
329
- }
330
- const res = await app.request('/articles', {
331
- method: 'PUT',
332
- headers: { 'Content-Type': 'application/json' },
333
- body: JSON.stringify(withNew),
334
- })
335
- expect(res.status).toBe(200)
336
-
337
- const stmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls[0][0]
338
- expect(stmts.some((s: string) => s.includes('ADD COLUMN') && s.includes('summary'))).toBe(true)
339
- expect(stmts.every((s: string) => !s.includes('DROP'))).toBe(true)
340
- })
341
-
342
- it('removing a branch: no DROP emitted, column retained', async () => {
343
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
344
- const existingCols = new Set(['id', 'title', 'body'])
345
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
346
- const { app } = buildApp({ role: 'admin', repo, mutator })
347
-
348
- const withRemoved: Seed = {
349
- ...baseSeed,
350
- branches: [baseSeed.branches[0]], // body removed
351
- }
352
- const res = await app.request('/articles', {
353
- method: 'PUT',
354
- headers: { 'Content-Type': 'application/json' },
355
- body: JSON.stringify(withRemoved),
356
- })
357
- expect(res.status).toBe(200)
358
-
359
- const allStmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls.flatMap((c: any) => c[0])
360
- expect(allStmts.every((s: string) => !s.includes('DROP'))).toBe(true)
361
- })
362
- })
363
-
364
- describe('POST /:slug/branches (add branch)', () => {
365
- it('assigns id and emits ADD COLUMN', async () => {
366
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
367
- const existingCols = new Set(['id', 'title', 'body'])
368
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
369
- const { app } = buildApp({ role: 'admin', repo, mutator })
370
-
371
- const res = await app.request('/articles/branches', {
372
- method: 'POST',
373
- headers: { 'Content-Type': 'application/json' },
374
- body: JSON.stringify({ alias: 'excerpt', label: 'Excerpt', type: 'text' }),
375
- })
376
- expect(res.status).toBe(200)
377
- const body = await res.json() as any
378
- expect(body.id).toMatch(/^br_\d+$/)
379
-
380
- const stmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls[0][0]
381
- expect(stmts.some((s: string) => s.includes('ADD COLUMN') && s.includes('excerpt'))).toBe(true)
382
- })
383
-
384
- it('column already present: no ADD COLUMN emitted', async () => {
385
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
386
- const existingCols = new Set(['id', 'title', 'body', 'excerpt'])
387
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
388
- const { app } = buildApp({ role: 'admin', repo, mutator })
389
-
390
- const res = await app.request('/articles/branches', {
391
- method: 'POST',
392
- headers: { 'Content-Type': 'application/json' },
393
- body: JSON.stringify({ alias: 'excerpt', label: 'Excerpt', type: 'text' }),
394
- })
395
- expect(res.status).toBe(200)
396
-
397
- const stmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls[0]?.[0] ?? []
398
- expect(stmts.every((s: string) => !s.includes('ADD COLUMN'))).toBe(true)
399
- })
400
- })
401
-
402
- describe('DELETE /:slug', () => {
403
- it('403 for non-admin', async () => {
404
- const { app } = buildApp({ role: 'user' })
405
- const res = await app.request('/articles', { method: 'DELETE' })
406
- expect(res.status).toBe(403)
407
- })
408
-
409
- it('soft-deletes: status flips, table not dropped, version bumped', async () => {
410
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
411
- const mutator = makeMutator()
412
- const { app } = buildApp({ role: 'admin', repo, mutator })
413
-
414
- const res = await app.request('/articles', { method: 'DELETE' })
415
- expect(res.status).toBe(200)
416
-
417
- expect((repo.softDelete as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
418
- expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
419
-
420
- // No DDL involving DROP was emitted
421
- const allStmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls.flatMap((c: any) => c[0])
422
- expect(allStmts.every((s: string) => !s.includes('DROP'))).toBe(true)
423
- })
424
-
425
- it('409 when seed is referenced by another seed relation', async () => {
426
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
427
- const backrefMap = new Map([['articles', [{ seedSlug: 'comments', branchAlias: 'article' }]]])
428
- const { app } = buildApp({ role: 'admin', repo, backrefMap })
429
-
430
- const res = await app.request('/articles', { method: 'DELETE' })
431
- expect(res.status).toBe(409)
432
- const body = await res.json() as any
433
- expect(body.type).toContain('seed-referenced')
434
- })
435
-
436
- it('404 for non-existent seed', async () => {
437
- const { app } = buildApp({ role: 'admin' })
438
- const res = await app.request('/nope', { method: 'DELETE' })
439
- expect(res.status).toBe(404)
440
- })
441
- })
442
-
443
- // ─── Sprint 06 Danger Zone routes ────────────────────────────────────────────
444
-
445
- describe('GET /:slug/orphans', () => {
446
- it('returns orphan columns not in the definition', async () => {
447
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
448
- // DB has 'id', 'slug', 'status', 'created_at', 'updated_at', 'title', 'body', 'legacy'
449
- const dbCols = new Set(['id', 'slug', 'status', 'created_at', 'updated_at', 'title', 'body', 'legacy'])
450
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(dbCols) })
451
- const { app } = buildApp({ role: 'admin', repo, mutator })
452
-
453
- const res = await app.request('/articles/orphans', { method: 'GET' })
454
- expect(res.status).toBe(200)
455
- const body = await res.json() as any
456
- expect(body.orphans).toContain('legacy')
457
- expect(body.orphans).not.toContain('title')
458
- })
459
-
460
- it('returns empty when DB has no orphans', async () => {
461
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
462
- const dbCols = new Set(['id', 'slug', 'status', 'created_at', 'updated_at', 'title', 'body'])
463
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(dbCols) })
464
- const { app } = buildApp({ role: 'admin', repo, mutator })
465
-
466
- const res = await app.request('/articles/orphans', { method: 'GET' })
467
- expect(res.status).toBe(200)
468
- const body = await res.json() as any
469
- expect(body.orphans).toHaveLength(0)
470
- })
471
- })
472
-
473
- describe('DELETE /:slug/hard', () => {
474
- it('400 on confirm mismatch', async () => {
475
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
476
- const { app } = buildApp({ role: 'admin', repo })
477
-
478
- const res = await app.request('/articles/hard', {
479
- method: 'DELETE',
480
- headers: { 'Content-Type': 'application/json' },
481
- body: JSON.stringify({ confirm: 'wrong' }),
482
- })
483
- expect(res.status).toBe(400)
484
- const body = await res.json() as any
485
- expect(body.type).toContain('confirmation-required')
486
- })
487
-
488
- it('409 when seed is referenced', async () => {
489
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
490
- const backrefMap = new Map([['articles', [{ sourceSlug: 'comments' }]]])
491
- const { app } = buildApp({ role: 'admin', repo, backrefMap })
492
-
493
- const res = await app.request('/articles/hard', {
494
- method: 'DELETE',
495
- headers: { 'Content-Type': 'application/json' },
496
- body: JSON.stringify({ confirm: 'articles' }),
497
- })
498
- expect(res.status).toBe(409)
499
- })
500
-
501
- it('hard delete: execDestructive called, hardDelete called, version bumped, audit logged', async () => {
502
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
503
- const mutator = makeMutator()
504
- const { app, activityLogger } = buildApp({ role: 'admin', repo, mutator })
505
-
506
- const res = await app.request('/articles/hard', {
507
- method: 'DELETE',
508
- headers: { 'Content-Type': 'application/json' },
509
- body: JSON.stringify({ confirm: 'articles' }),
510
- })
511
- expect(res.status).toBe(200)
512
-
513
- expect((mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls.length).toBeGreaterThan(0)
514
- // execDdl must NOT have been called for DROP
515
- const ddlCalls: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls.flatMap((c: any) => c[0])
516
- expect(ddlCalls.every((s: string) => !s.toUpperCase().includes('DROP'))).toBe(true)
517
-
518
- expect((repo.hardDelete as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
519
- expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
520
- expect(activityLogger.log.mock.calls[0][0].action).toBe('delete')
521
- expect(activityLogger.log.mock.calls[0][0].details.op).toBe('hard-delete')
522
- })
523
- })
524
-
525
- describe('DELETE /:slug/branches/:branchId', () => {
526
- it('400 on confirm mismatch', async () => {
527
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
528
- const { app } = buildApp({ role: 'admin', repo })
529
-
530
- const res = await app.request('/articles/branches/br_01', {
531
- method: 'DELETE',
532
- headers: { 'Content-Type': 'application/json' },
533
- body: JSON.stringify({ confirm: 'wrong' }),
534
- })
535
- expect(res.status).toBe(400)
536
- })
537
-
538
- it('drops branch: execDestructive called, definition updated, version bumped', async () => {
539
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
540
- const mutator = makeMutator()
541
- const { app } = buildApp({ role: 'admin', repo, mutator })
542
-
543
- const res = await app.request('/articles/branches/br_02', {
544
- method: 'DELETE',
545
- headers: { 'Content-Type': 'application/json' },
546
- body: JSON.stringify({ confirm: 'articles.body' }),
547
- })
548
- expect(res.status).toBe(200)
549
-
550
- expect((mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
551
- const upsertArg = (repo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as any
552
- expect(upsertArg.branches.find((b: any) => b.id === 'br_02')).toBeUndefined()
553
- expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
554
- })
555
-
556
- it('404 for unknown branchId', async () => {
557
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
558
- const { app } = buildApp({ role: 'admin', repo })
559
-
560
- const res = await app.request('/articles/branches/br_99', {
561
- method: 'DELETE',
562
- headers: { 'Content-Type': 'application/json' },
563
- body: JSON.stringify({ confirm: 'articles.unknown' }),
564
- })
565
- expect(res.status).toBe(404)
566
- })
567
- })
568
-
569
- describe('PATCH /:slug/branches/:branchId/rename', () => {
570
- it('400 on confirm mismatch', async () => {
571
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
572
- const { app } = buildApp({ role: 'admin', repo })
573
-
574
- const res = await app.request('/articles/branches/br_01/rename', {
575
- method: 'PATCH',
576
- headers: { 'Content-Type': 'application/json' },
577
- body: JSON.stringify({ newAlias: 'headline', confirm: 'wrong' }),
578
- })
579
- expect(res.status).toBe(400)
580
- })
581
-
582
- it('renames alias: execDestructive called with RENAME, definition updated, automation warnings returned', async () => {
583
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
584
- const mutator = makeMutator()
585
- const automationRepository = { list: vi.fn().mockResolvedValue([{ id: 'auto_1', conditions: 'title' }]) }
586
- const { app } = buildApp({ role: 'admin', repo, mutator, automationRepository })
587
-
588
- const res = await app.request('/articles/branches/br_01/rename', {
589
- method: 'PATCH',
590
- headers: { 'Content-Type': 'application/json' },
591
- body: JSON.stringify({ newAlias: 'headline', confirm: 'articles.title' }),
592
- })
593
- expect(res.status).toBe(200)
594
-
595
- const destructiveCalls: string[] = (mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls[0][0]
596
- expect(destructiveCalls.some((s: string) => s.toUpperCase().includes('RENAME COLUMN') || s.toUpperCase().includes('RENAME TO'))).toBe(true)
597
-
598
- const upsertArg = (repo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as any
599
- const renamed = upsertArg.branches.find((b: any) => b.id === 'br_01')
600
- expect(renamed?.alias).toBe('headline')
601
-
602
- const body = await res.json() as any
603
- expect(body.affectedAutomations).toContain('auto_1')
604
- })
605
- })
606
-
607
- describe('PATCH /:slug/branches/:branchId/retype', () => {
608
- it('400 on confirm mismatch', async () => {
609
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
610
- const { app } = buildApp({ role: 'admin', repo })
611
-
612
- const res = await app.request('/articles/branches/br_01/retype', {
613
- method: 'PATCH',
614
- headers: { 'Content-Type': 'application/json' },
615
- body: JSON.stringify({ newType: 'number', confirm: 'wrong' }),
616
- })
617
- expect(res.status).toBe(400)
618
- })
619
-
620
- it('retypes branch: execDestructive called, definition updated, version bumped', async () => {
621
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
622
- const mutator = makeMutator()
623
- const { app } = buildApp({ role: 'admin', repo, mutator })
624
-
625
- const res = await app.request('/articles/branches/br_01/retype', {
626
- method: 'PATCH',
627
- headers: { 'Content-Type': 'application/json' },
628
- body: JSON.stringify({ newType: 'number', confirm: 'articles.title' }),
629
- })
630
- expect(res.status).toBe(200)
631
-
632
- expect((mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
633
- const upsertArg = (repo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as any
634
- expect(upsertArg.branches.find((b: any) => b.id === 'br_01')?.type).toBe('number')
635
- expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
636
- })
637
-
638
- it('422 retype-not-supported when retyping a repeater branch away', async () => {
639
- const repeaterRecord: SeedRecord = {
640
- ...baseRecord,
641
- definition: {
642
- ...baseSeed,
643
- branches: [
644
- baseSeed.branches[0],
645
- { id: 'br_02', alias: 'items', label: 'Items', type: 'repeater', fields: [] },
646
- ],
647
- },
648
- }
649
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(repeaterRecord) })
650
- const { app } = buildApp({ role: 'admin', repo })
651
-
652
- const res = await app.request('/articles/branches/br_02/retype', {
653
- method: 'PATCH',
654
- headers: { 'Content-Type': 'application/json' },
655
- body: JSON.stringify({ newType: 'text', confirm: 'articles.items' }),
656
- })
657
- expect(res.status).toBe(422)
658
- const problem = await res.json() as any
659
- expect(problem.type).toContain('retype-not-supported')
660
- })
661
-
662
- it('422 retype-not-supported when retyping a branch to repeater', async () => {
663
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
664
- const { app } = buildApp({ role: 'admin', repo })
665
-
666
- const res = await app.request('/articles/branches/br_01/retype', {
667
- method: 'PATCH',
668
- headers: { 'Content-Type': 'application/json' },
669
- body: JSON.stringify({ newType: 'repeater', confirm: 'articles.title' }),
670
- })
671
- expect(res.status).toBe(422)
672
- const problem = await res.json() as any
673
- expect(problem.type).toContain('retype-not-supported')
674
- })
675
- })
676
-
677
- describe('POST /:slug/fts/rebuild', () => {
678
- it('calls execDestructive with FTS statements and logs audit', async () => {
679
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
680
- const mutator = makeMutator()
681
- const { app, activityLogger } = buildApp({ role: 'admin', repo, mutator })
682
-
683
- const res = await app.request('/articles/fts/rebuild', { method: 'POST' })
684
- expect(res.status).toBe(200)
685
-
686
- expect((mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
687
- const stmts: string[] = (mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls[0][0]
688
- expect(stmts.some((s: string) => s.includes('fts_articles'))).toBe(true)
689
- expect(activityLogger.log.mock.calls[0][0].details.op).toBe('fts-rebuild')
690
- })
691
-
692
- it('404 for non-existent seed', async () => {
693
- const { app } = buildApp({ role: 'admin' })
694
- const res = await app.request('/nope/fts/rebuild', { method: 'POST' })
695
- expect(res.status).toBe(404)
696
- })
697
- })
698
-
699
- // ─── Malformed JSON bodies ────────────────────────────────────────────────────
700
-
701
- describe('Malformed JSON body', () => {
702
- it('POST / returns 400 invalid-json on bad body', async () => {
703
- const { app } = buildApp({ role: 'admin' })
704
- const res = await app.request('/', {
705
- method: 'POST',
706
- headers: { 'Content-Type': 'application/json' },
707
- body: '{not valid json',
708
- })
709
- expect(res.status).toBe(400)
710
- const body = await res.json() as any
711
- expect(body.type).toContain('invalid-json')
712
- })
713
-
714
- it('PUT /:slug returns 400 invalid-json on bad body', async () => {
715
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
716
- const { app } = buildApp({ role: 'admin', repo })
717
- const res = await app.request('/articles', {
718
- method: 'PUT',
719
- headers: { 'Content-Type': 'application/json' },
720
- body: '{not valid json',
721
- })
722
- expect(res.status).toBe(400)
723
- })
724
-
725
- it('POST /:slug/branches returns 400 invalid-json on bad body', async () => {
726
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
727
- const { app } = buildApp({ role: 'admin', repo })
728
- const res = await app.request('/articles/branches', {
729
- method: 'POST',
730
- headers: { 'Content-Type': 'application/json' },
731
- body: '{not valid json',
732
- })
733
- expect(res.status).toBe(400)
734
- })
735
-
736
- it('DELETE /:slug/hard returns 400 invalid-json on bad body', async () => {
737
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
738
- const { app } = buildApp({ role: 'admin', repo })
739
- const res = await app.request('/articles/hard', {
740
- method: 'DELETE',
741
- headers: { 'Content-Type': 'application/json' },
742
- body: '{not valid json',
743
- })
744
- expect(res.status).toBe(400)
745
- })
746
-
747
- it('DELETE /:slug/branches/:branchId returns 400 invalid-json on bad body', async () => {
748
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
749
- const { app } = buildApp({ role: 'admin', repo })
750
- const res = await app.request('/articles/branches/br_01', {
751
- method: 'DELETE',
752
- headers: { 'Content-Type': 'application/json' },
753
- body: '{not valid json',
754
- })
755
- expect(res.status).toBe(400)
756
- })
757
-
758
- it('PATCH rename returns 400 invalid-json on bad body', async () => {
759
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
760
- const { app } = buildApp({ role: 'admin', repo })
761
- const res = await app.request('/articles/branches/br_01/rename', {
762
- method: 'PATCH',
763
- headers: { 'Content-Type': 'application/json' },
764
- body: '{not valid json',
765
- })
766
- expect(res.status).toBe(400)
767
- })
768
-
769
- it('PATCH retype returns 400 invalid-json on bad body', async () => {
770
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
771
- const { app } = buildApp({ role: 'admin', repo })
772
- const res = await app.request('/articles/branches/br_01/retype', {
773
- method: 'PATCH',
774
- headers: { 'Content-Type': 'application/json' },
775
- body: '{not valid json',
776
- })
777
- expect(res.status).toBe(400)
778
- })
779
- })
780
-
781
- // ─── Additional 404 / validation paths ───────────────────────────────────────
782
-
783
- describe('Additional validation and 404 paths', () => {
784
- it('POST / 400 on invalid slug format', async () => {
785
- const { app } = buildApp({ role: 'admin' })
786
- const invalid: Seed = { ...baseSeed, slug: 'Invalid Slug!' }
787
- const res = await app.request('/', {
788
- method: 'POST',
789
- headers: { 'Content-Type': 'application/json' },
790
- body: JSON.stringify(invalid),
791
- })
792
- expect(res.status).toBe(400)
793
- })
794
-
795
- it('POST / infers displayNameAlias from the first text branch when missing', async () => {
796
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
797
- const { app, repo: usedRepo } = buildApp({ role: 'admin', repo })
798
- const noDisplaySeed = {
799
- slug: 'snippets',
800
- label: 'Snippets',
801
- branches: [
802
- { id: 'br_01', alias: 'amount', label: 'Amount', type: 'number' },
803
- { id: 'br_02', alias: 'headline', label: 'Headline', type: 'text' },
804
- ],
805
- }
806
- const res = await app.request('/', {
807
- method: 'POST',
808
- headers: { 'Content-Type': 'application/json' },
809
- body: JSON.stringify(noDisplaySeed),
810
- })
811
- expect(res.status).toBe(201)
812
- const upsertArg = (usedRepo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as Seed
813
- expect(upsertArg.displayNameAlias).toBe('headline')
814
- })
815
-
816
- it('POST / 400 when displayNameAlias missing and no text branch to infer from', async () => {
817
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
818
- const { app } = buildApp({ role: 'admin', repo })
819
- const noTextSeed = {
820
- slug: 'numbers_only',
821
- label: 'Numbers',
822
- branches: [{ id: 'br_01', alias: 'amount', label: 'Amount', type: 'number' }],
823
- }
824
- const res = await app.request('/', {
825
- method: 'POST',
826
- headers: { 'Content-Type': 'application/json' },
827
- body: JSON.stringify(noTextSeed),
828
- })
829
- expect(res.status).toBe(400)
830
- })
831
-
832
- it('POST / 422 ddl-failed when execDdl throws', async () => {
833
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
834
- const mutator = makeMutator({ execDdl: vi.fn().mockRejectedValue(new Error('boom')) })
835
- const { app } = buildApp({ role: 'admin', repo, mutator })
836
-
837
- const newSeed: Seed = {
838
- slug: 'broken',
839
- label: 'Broken',
840
- displayNameAlias: 'title',
841
- branches: [{ id: 'br_01', alias: 'title', label: 'Title', type: 'text' }],
842
- }
843
- const res = await app.request('/', {
844
- method: 'POST',
845
- headers: { 'Content-Type': 'application/json' },
846
- body: JSON.stringify(newSeed),
847
- })
848
- expect(res.status).toBe(422)
849
- const body = await res.json() as any
850
- expect(body.type).toContain('ddl-failed')
851
- expect(body.detail).toContain('boom')
852
- })
853
-
854
- it('PUT /:slug 404 for non-existent seed', async () => {
855
- const { app } = buildApp({ role: 'admin' })
856
- const res = await app.request('/nope', {
857
- method: 'PUT',
858
- headers: { 'Content-Type': 'application/json' },
859
- body: JSON.stringify(baseSeed),
860
- })
861
- expect(res.status).toBe(404)
862
- })
863
-
864
- it('PUT /:slug assigns an id to a newly added branch without one', async () => {
865
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
866
- const existingCols = new Set(['id', 'title', 'body'])
867
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
868
- const { app, repo: usedRepo } = buildApp({ role: 'admin', repo, mutator })
869
-
870
- const withNewUnidentified: Seed = {
871
- ...baseSeed,
872
- branches: [
873
- ...baseSeed.branches,
874
- { alias: 'extra', label: 'Extra', type: 'text' } as Branch,
875
- ],
876
- }
877
- const res = await app.request('/articles', {
878
- method: 'PUT',
879
- headers: { 'Content-Type': 'application/json' },
880
- body: JSON.stringify(withNewUnidentified),
881
- })
882
- expect(res.status).toBe(200)
883
- const upsertArg = (usedRepo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as Seed
884
- const extra = upsertArg.branches.find((b) => b.alias === 'extra')
885
- expect(extra?.id).toMatch(/^br_\d+$/)
886
- })
887
-
888
- it('POST /:slug/branches 404 for non-existent seed', async () => {
889
- const { app } = buildApp({ role: 'admin' })
890
- const res = await app.request('/nope/branches', {
891
- method: 'POST',
892
- headers: { 'Content-Type': 'application/json' },
893
- body: JSON.stringify({ alias: 'x', label: 'X', type: 'text' }),
894
- })
895
- expect(res.status).toBe(404)
896
- })
897
-
898
- it('GET /:slug/orphans 404 for non-existent seed', async () => {
899
- const { app } = buildApp({ role: 'admin' })
900
- const res = await app.request('/nope/orphans', { method: 'GET' })
901
- expect(res.status).toBe(404)
902
- })
903
-
904
- it('GET /:slug/orphans returns empty when DB columns are unknown (table does not exist)', async () => {
905
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
906
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(null) })
907
- const { app } = buildApp({ role: 'admin', repo, mutator })
908
-
909
- const res = await app.request('/articles/orphans', { method: 'GET' })
910
- expect(res.status).toBe(200)
911
- const body = await res.json() as any
912
- expect(body.orphans).toEqual([])
913
- })
914
- })
915
-
916
- // ─── Hard delete: media cascade ──────────────────────────────────────────────
917
-
918
- describe('DELETE /:slug/hard — media cascade (deleteSeedMediaObjects)', () => {
919
- const seedWithFile: Seed = {
920
- slug: 'articles',
921
- label: 'Articles',
922
- displayNameAlias: 'title',
923
- branches: [
924
- { id: 'br_01', alias: 'title', label: 'Title', type: 'text' },
925
- { id: 'br_02', alias: 'cover', label: 'Cover', type: 'file' },
926
- ],
927
- }
928
- const recordWithFile: SeedRecord = { ...baseRecord, definition: seedWithFile }
929
-
930
- it('400 on confirm mismatch', async () => {
931
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
932
- const { app } = buildApp({ role: 'admin', repo })
933
- const res = await app.request('/articles/hard', {
934
- method: 'DELETE',
935
- headers: { 'Content-Type': 'application/json' },
936
- body: JSON.stringify({ confirm: 'wrong' }),
937
- })
938
- expect(res.status).toBe(400)
939
- })
940
-
941
- it('404 for non-existent seed', async () => {
942
- const { app } = buildApp({ role: 'admin' })
943
- const res = await app.request('/nope/hard', {
944
- method: 'DELETE',
945
- headers: { 'Content-Type': 'application/json' },
946
- body: JSON.stringify({ confirm: 'nope' }),
947
- })
948
- expect(res.status).toBe(404)
949
- })
950
-
951
- it('skips media cleanup when dbCols is null (table missing)', async () => {
952
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(recordWithFile) })
953
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(null) })
954
- const { app, bucket } = buildApp({ role: 'admin', repo, mutator })
955
-
956
- const res = await app.request('/articles/hard', {
957
- method: 'DELETE',
958
- headers: { 'Content-Type': 'application/json' },
959
- body: JSON.stringify({ confirm: 'articles' }),
960
- })
961
- expect(res.status).toBe(200)
962
- expect(bucket.delete).not.toHaveBeenCalled()
963
- })
964
-
965
- it('skips media cleanup when no file column is present in DB', async () => {
966
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(recordWithFile) })
967
- const dbCols = new Set(['id', 'title']) // 'cover' column absent
968
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(dbCols) })
969
- const { app, bucket } = buildApp({ role: 'admin', repo, mutator })
970
-
971
- const res = await app.request('/articles/hard', {
972
- method: 'DELETE',
973
- headers: { 'Content-Type': 'application/json' },
974
- body: JSON.stringify({ confirm: 'articles' }),
975
- })
976
- expect(res.status).toBe(200)
977
- expect(bucket.delete).not.toHaveBeenCalled()
978
- })
979
-
980
- it('extracts R2 keys from rows and deletes them via deleteR2Objects', async () => {
981
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(recordWithFile) })
982
- const dbCols = new Set(['id', 'title', 'cover'])
983
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(dbCols) })
984
- const db = {
985
- prepare: (sql: string) => ({
986
- all: async () => {
987
- expect(sql).toContain('cover')
988
- expect(sql).toContain('content_articles')
989
- return { results: [{ cover: '/api/media/abc123.png' }, { cover: null }] }
990
- },
991
- }),
992
- }
993
- const { app, bucket, mediaRepository } = buildApp({ role: 'admin', repo, mutator, db })
994
-
995
- const res = await app.request(
996
- '/articles/hard',
997
- {
998
- method: 'DELETE',
999
- headers: { 'Content-Type': 'application/json' },
1000
- body: JSON.stringify({ confirm: 'articles' }),
1001
- },
1002
- { DB: db }
1003
- )
1004
- expect(res.status).toBe(200)
1005
- expect(bucket.delete).toHaveBeenCalledWith('abc123.png')
1006
- expect(mediaRepository.untrack).toHaveBeenCalledWith('abc123.png')
1007
- })
1008
-
1009
- it('non-fatal: swallows errors thrown while gathering media keys', async () => {
1010
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(recordWithFile) })
1011
- const mutator = makeMutator({ getColumns: vi.fn().mockRejectedValue(new Error('schema unavailable')) })
1012
- const { app } = buildApp({ role: 'admin', repo, mutator })
1013
-
1014
- const res = await app.request('/articles/hard', {
1015
- method: 'DELETE',
1016
- headers: { 'Content-Type': 'application/json' },
1017
- body: JSON.stringify({ confirm: 'articles' }),
1018
- })
1019
- expect(res.status).toBe(200)
1020
- })
1021
-
1022
- it('non-fatal: swallows errors thrown by deleteR2Objects itself', async () => {
1023
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(recordWithFile) })
1024
- const dbCols = new Set(['id', 'title', 'cover'])
1025
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(dbCols) })
1026
- const db = {
1027
- prepare: () => ({
1028
- all: async () => ({ results: [{ cover: '/api/media/abc123.png' }] }),
1029
- }),
1030
- }
1031
- const bucket = { delete: vi.fn().mockRejectedValue(new Error('r2 down')) }
1032
- const mediaRepository = { getByKey: vi.fn().mockRejectedValue(new Error('lookup failed')), untrack: vi.fn().mockRejectedValue(new Error('untrack failed')) }
1033
- const { app } = buildApp({ role: 'admin', repo, mutator, db, bucket, mediaRepository })
1034
-
1035
- const res = await app.request(
1036
- '/articles/hard',
1037
- {
1038
- method: 'DELETE',
1039
- headers: { 'Content-Type': 'application/json' },
1040
- body: JSON.stringify({ confirm: 'articles' }),
1041
- },
1042
- { DB: db }
1043
- )
1044
- expect(res.status).toBe(200)
1045
- })
1046
- })
1047
-
1048
- // ─── DELETE /:slug/branches/:branchId — DDL failure ──────────────────────────
1049
-
1050
- describe('DELETE /:slug/branches/:branchId — DDL failure', () => {
1051
- it('404 for non-existent seed', async () => {
1052
- const { app } = buildApp({ role: 'admin' })
1053
- const res = await app.request('/nope/branches/br_01', {
1054
- method: 'DELETE',
1055
- headers: { 'Content-Type': 'application/json' },
1056
- body: JSON.stringify({ confirm: 'nope.x' }),
1057
- })
1058
- expect(res.status).toBe(404)
1059
- })
1060
-
1061
- it('422 ddl-failed when execDestructive throws', async () => {
1062
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1063
- const mutator = makeMutator({ execDestructive: vi.fn().mockRejectedValue(new Error('drop failed')) })
1064
- const { app } = buildApp({ role: 'admin', repo, mutator })
1065
-
1066
- const res = await app.request('/articles/branches/br_02', {
1067
- method: 'DELETE',
1068
- headers: { 'Content-Type': 'application/json' },
1069
- body: JSON.stringify({ confirm: 'articles.body' }),
1070
- })
1071
- expect(res.status).toBe(422)
1072
- const body = await res.json() as any
1073
- expect(body.type).toContain('ddl-failed')
1074
- })
1075
- })
1076
-
1077
- // ─── PATCH rename — extra validation paths ───────────────────────────────────
1078
-
1079
- describe('PATCH /:slug/branches/:branchId/rename — extra validation paths', () => {
1080
- it('400 when newAlias is invalid', async () => {
1081
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1082
- const { app } = buildApp({ role: 'admin', repo })
1083
-
1084
- const res = await app.request('/articles/branches/br_01/rename', {
1085
- method: 'PATCH',
1086
- headers: { 'Content-Type': 'application/json' },
1087
- body: JSON.stringify({ newAlias: 'Not Valid!', confirm: 'articles.title' }),
1088
- })
1089
- expect(res.status).toBe(400)
1090
- })
1091
-
1092
- it('404 for non-existent seed', async () => {
1093
- const { app } = buildApp({ role: 'admin' })
1094
- const res = await app.request('/nope/branches/br_01/rename', {
1095
- method: 'PATCH',
1096
- headers: { 'Content-Type': 'application/json' },
1097
- body: JSON.stringify({ newAlias: 'headline', confirm: 'nope.x' }),
1098
- })
1099
- expect(res.status).toBe(404)
1100
- })
1101
-
1102
- it('404 for unknown branchId', async () => {
1103
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1104
- const { app } = buildApp({ role: 'admin', repo })
1105
-
1106
- const res = await app.request('/articles/branches/br_99/rename', {
1107
- method: 'PATCH',
1108
- headers: { 'Content-Type': 'application/json' },
1109
- body: JSON.stringify({ newAlias: 'headline', confirm: 'articles.unknown' }),
1110
- })
1111
- expect(res.status).toBe(404)
1112
- })
1113
-
1114
- it('non-fatal: swallows errors from automationRepository.list', async () => {
1115
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1116
- const mutator = makeMutator()
1117
- const automationRepository = { list: vi.fn().mockRejectedValue(new Error('automations unavailable')) }
1118
- const { app } = buildApp({ role: 'admin', repo, mutator, automationRepository })
1119
-
1120
- const res = await app.request('/articles/branches/br_01/rename', {
1121
- method: 'PATCH',
1122
- headers: { 'Content-Type': 'application/json' },
1123
- body: JSON.stringify({ newAlias: 'headline', confirm: 'articles.title' }),
1124
- })
1125
- expect(res.status).toBe(200)
1126
- const body = await res.json() as any
1127
- expect(body.affectedAutomations).toEqual([])
1128
- })
1129
- })
1130
-
1131
- // ─── PATCH retype — extra validation paths ───────────────────────────────────
1132
-
1133
- describe('PATCH /:slug/branches/:branchId/retype — extra validation paths', () => {
1134
- it('400 when newType is invalid', async () => {
1135
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1136
- const { app } = buildApp({ role: 'admin', repo })
1137
-
1138
- const res = await app.request('/articles/branches/br_01/retype', {
1139
- method: 'PATCH',
1140
- headers: { 'Content-Type': 'application/json' },
1141
- body: JSON.stringify({ newType: 'not-a-type', confirm: 'articles.title' }),
1142
- })
1143
- expect(res.status).toBe(400)
1144
- })
1145
-
1146
- it('404 for non-existent seed', async () => {
1147
- const { app } = buildApp({ role: 'admin' })
1148
- const res = await app.request('/nope/branches/br_01/retype', {
1149
- method: 'PATCH',
1150
- headers: { 'Content-Type': 'application/json' },
1151
- body: JSON.stringify({ newType: 'number', confirm: 'nope.x' }),
1152
- })
1153
- expect(res.status).toBe(404)
1154
- })
1155
-
1156
- it('404 for unknown branchId', async () => {
1157
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1158
- const { app } = buildApp({ role: 'admin', repo })
1159
-
1160
- const res = await app.request('/articles/branches/br_99/retype', {
1161
- method: 'PATCH',
1162
- headers: { 'Content-Type': 'application/json' },
1163
- body: JSON.stringify({ newType: 'number', confirm: 'articles.unknown' }),
1164
- })
1165
- expect(res.status).toBe(404)
1166
- })
1167
-
1168
- it('422 ddl-failed when execDestructive throws', async () => {
1169
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1170
- const mutator = makeMutator({ execDestructive: vi.fn().mockRejectedValue(new Error('retype failed')) })
1171
- const { app } = buildApp({ role: 'admin', repo, mutator })
1172
-
1173
- const res = await app.request('/articles/branches/br_01/retype', {
1174
- method: 'PATCH',
1175
- headers: { 'Content-Type': 'application/json' },
1176
- body: JSON.stringify({ newType: 'number', confirm: 'articles.title' }),
1177
- })
1178
- expect(res.status).toBe(422)
1179
- const body = await res.json() as any
1180
- expect(body.type).toContain('ddl-failed')
1181
- })
1182
- })
1183
-
1184
- // ─── actorFromContext fallbacks ──────────────────────────────────────────────
1185
-
1186
- describe('actorFromContext fallbacks', () => {
1187
- it('falls back to "unknown" id/email and null name when JWT lacks those claims', async () => {
1188
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
1189
- const { app, activityLogger } = buildApp({ jwtPayload: { role: 'admin' }, repo })
1190
-
1191
- const res = await app.request('/articles', { method: 'DELETE' })
1192
- expect(res.status).toBe(200)
1193
-
1194
- const actor = activityLogger.log.mock.calls[0][0].actor
1195
- expect(actor.id).toBe('unknown')
1196
- expect(actor.email).toBe('unknown')
1197
- expect(actor.name).toBeNull()
1198
- })
1199
- })