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

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 (222) hide show
  1. package/assets/dashboard/BeechLogo.svg +18 -18
  2. package/assets/dashboard/BeechLogoLIght.svg +48 -48
  3. package/assets/dashboard/assets/chart-BrJFdsGZ.js +39 -0
  4. package/assets/dashboard/assets/index-CIaoMxuB.css +1 -0
  5. package/assets/dashboard/assets/index-wTKgygsg.js +636 -0
  6. package/assets/dashboard/assets/pie-chart-recharts-BEaE1FOE.js +1 -0
  7. package/assets/dashboard/assets/timeseries-chart-recharts-DmWM6imF.js +1 -0
  8. package/assets/dashboard/beechLogoDark.svg +48 -48
  9. package/assets/dashboard/index.html +18 -18
  10. package/assets/dashboard/noResult.svg +42 -42
  11. package/assets/dashboard/sol.svg +3 -3
  12. package/assets/dashboard/undraw_enter_nwx3.svg +36 -36
  13. package/migrations/0000_v040_base.sql +265 -265
  14. package/migrations/0029_automations.sql +14 -14
  15. package/migrations/0030_test_seeds.sql +125 -125
  16. package/package.json +2 -2
  17. package/src/auth/__fixtures__/in-memory-hash-provider.ts +17 -17
  18. package/src/auth/__fixtures__/static-token-service.ts +22 -22
  19. package/src/auth/bcrypt-hash-provider.ts +24 -24
  20. package/src/auth/constants.ts +14 -14
  21. package/src/auth/generate-refresh-token.test.ts +23 -23
  22. package/src/auth/hash-provider.test.ts +55 -55
  23. package/src/auth/jose-token-service.ts +62 -62
  24. package/src/auth/jwt-claims-passthrough.test.ts +87 -87
  25. package/src/auth/login.test.ts +100 -100
  26. package/src/auth/login.ts +78 -78
  27. package/src/auth/refresh.ts +11 -11
  28. package/src/auth/token-service.test.ts +90 -90
  29. package/src/factory.ts +370 -368
  30. package/src/features/automations/__tests__/action-executors.test.ts +255 -255
  31. package/src/features/automations/__tests__/automation-runner.test.ts +196 -196
  32. package/src/features/automations/__tests__/automation-runner.utils.test.ts +60 -60
  33. package/src/features/automations/__tests__/automations.handler.test.ts +264 -264
  34. package/src/features/automations/__tests__/automations.repository.test.ts +163 -163
  35. package/src/features/automations/__tests__/automations.schema.test.ts +224 -224
  36. package/src/features/automations/__tests__/context-resolver.test.ts +126 -126
  37. package/src/features/automations/__tests__/cron-runner.test.ts +267 -267
  38. package/src/features/automations/__tests__/cron-runner.utils.test.ts +144 -144
  39. package/src/features/automations/__tests__/set-variable.executor.test.ts +383 -383
  40. package/src/features/automations/__tests__/template-grammar.test.ts +308 -308
  41. package/src/features/automations/__tests__/webhook.executor.test.ts +142 -142
  42. package/src/features/automations/__tests__/when-evaluator.test.ts +274 -274
  43. package/src/features/automations/__tests__/when-pushdown.test.ts +281 -281
  44. package/src/features/automations/action-executors/create-entry.executor.ts +27 -27
  45. package/src/features/automations/action-executors/edit-field.executor.ts +26 -26
  46. package/src/features/automations/action-executors/index.ts +37 -37
  47. package/src/features/automations/action-executors/send-mail.executor.ts +53 -53
  48. package/src/features/automations/action-executors/set-variable.executor.ts +159 -159
  49. package/src/features/automations/action-executors/webhook.executor.ts +67 -67
  50. package/src/features/automations/automation-runner.ts +85 -85
  51. package/src/features/automations/automation-runner.utils.ts +47 -47
  52. package/src/features/automations/automations.handler.ts +197 -197
  53. package/src/features/automations/automations.schema.ts +177 -177
  54. package/src/features/automations/context-resolver.ts +152 -152
  55. package/src/features/automations/cron-runner.ts +140 -140
  56. package/src/features/automations/cron-runner.utils.ts +44 -44
  57. package/src/features/automations/filter-translation.ts +46 -46
  58. package/src/features/automations/index.ts +16 -16
  59. package/src/features/automations/template-grammar.ts +245 -245
  60. package/src/features/automations/var-access-resolver.ts +140 -140
  61. package/src/features/automations/when-evaluator.ts +87 -87
  62. package/src/features/automations/when-pushdown.ts +57 -57
  63. package/src/features/backrefs/__tests__/backrefs.handler.test.ts +359 -359
  64. package/src/features/backrefs/backrefs.handler.ts +168 -168
  65. package/src/features/backrefs/d1-backref.repository.ts +84 -84
  66. package/src/features/backrefs/index.ts +5 -5
  67. package/src/features/content/constants.ts +16 -16
  68. package/src/features/content/handlers/bulk.handler.ts +185 -185
  69. package/src/features/content/handlers/create.ts +129 -129
  70. package/src/features/content/handlers/delete.ts +62 -62
  71. package/src/features/content/handlers/facets.ts +49 -49
  72. package/src/features/content/handlers/get.ts +120 -120
  73. package/src/features/content/handlers/helpers.test.ts +180 -180
  74. package/src/features/content/handlers/helpers.ts +93 -93
  75. package/src/features/content/handlers/list.ts +174 -174
  76. package/src/features/content/handlers/update.ts +174 -174
  77. package/src/features/content/index.ts +26 -26
  78. package/src/features/dashboard-layout/__tests__/dashboard-layout.handler.test.ts +388 -0
  79. package/src/features/dashboard-layout/dashboard-layout.handler.ts +206 -0
  80. package/src/features/dashboard-layout/index.ts +5 -0
  81. package/src/features/draft/draft.handler.ts +195 -195
  82. package/src/features/draft/draft.middleware.ts +66 -66
  83. package/src/features/draft/index.ts +5 -5
  84. package/src/features/email/email.provider.ts +42 -42
  85. package/src/features/email/email.service.ts +98 -98
  86. package/src/features/email/email.types.ts +119 -119
  87. package/src/features/email/index.ts +33 -33
  88. package/src/features/email/providers/resend.ts +67 -67
  89. package/src/features/email/providers/smtp.ts +55 -55
  90. package/src/features/email/templates/automation-mail.ts +19 -19
  91. package/src/features/email/templates/password-changed.ts +63 -63
  92. package/src/features/email/templates/password-reset.ts +68 -68
  93. package/src/features/email/templates/shell.ts +96 -96
  94. package/src/features/notifications/index.ts +5 -5
  95. package/src/features/notifications/notifications.handler.ts +105 -105
  96. package/src/features/password-reset/index.ts +19 -19
  97. package/src/features/password-reset/request.ts +92 -92
  98. package/src/features/password-reset/reset.ts +102 -102
  99. package/src/features/rotate-field/index.ts +5 -5
  100. package/src/features/rotate-field/rotate-field.handler.ts +132 -132
  101. package/src/features/rotate-field/rotate-field.schema.ts +17 -17
  102. package/src/features/schema/schema.handler.ts +131 -131
  103. package/src/features/seeds/index.ts +5 -5
  104. package/src/features/seeds/seeds.handler.test.ts +1199 -632
  105. package/src/features/seeds/seeds.handler.ts +558 -693
  106. package/src/features/settings/__tests__/settings.handler.test.ts +555 -555
  107. package/src/features/settings/settings.handler.ts +392 -392
  108. package/src/features/setup/index.ts +288 -204
  109. package/src/features/stats/index.ts +5 -5
  110. package/src/features/stats/stats.handler.ts +420 -420
  111. package/src/features/webhooks/index.ts +63 -63
  112. package/src/index.ts +65 -65
  113. package/src/media-utils.ts +82 -82
  114. package/src/middleware/auth-providers.middleware.test.ts +85 -0
  115. package/src/middleware/auth-providers.middleware.ts +45 -45
  116. package/src/middleware/observability.middleware.test.ts +93 -0
  117. package/src/middleware/observability.middleware.ts +70 -70
  118. package/src/middleware/rate-limit.middleware.ts +45 -45
  119. package/src/middleware/repository.middleware.ts +117 -114
  120. package/src/middleware/seed-registry.middleware.test.ts +97 -97
  121. package/src/middleware/seed-registry.middleware.ts +21 -21
  122. package/src/middleware/storage.middleware.ts +25 -25
  123. package/src/middleware.ts +45 -45
  124. package/src/public/access-policy.ts +27 -27
  125. package/src/public/api-key-middleware.ts +57 -57
  126. package/src/public/cache-utils.ts +38 -38
  127. package/src/public/entry-projection.ts +46 -46
  128. package/src/public/idempotency.ts +23 -23
  129. package/src/public/index.ts +16 -16
  130. package/src/public/problem-details.ts +124 -124
  131. package/src/public/public-add.ts +114 -114
  132. package/src/public/public-edit.ts +163 -163
  133. package/src/public/public-errors.ts +19 -19
  134. package/src/public/public-read.ts +63 -63
  135. package/src/public/public-routes.ts +88 -88
  136. package/src/public/query-builder.test.ts +224 -224
  137. package/src/public/query-builder.ts +156 -156
  138. package/src/public/rate-limit-middleware.ts +34 -34
  139. package/src/public/read-list.ts +54 -54
  140. package/src/public/read-single.ts +48 -48
  141. package/src/public/response-builder.ts +30 -30
  142. package/src/public/sanitize.ts +69 -69
  143. package/src/public/slug-utils.ts +18 -18
  144. package/src/rate-limit/cloudflare-rate-limiter.test.ts +30 -30
  145. package/src/rate-limit/cloudflare-rate-limiter.ts +15 -15
  146. package/src/rate-limit/in-memory-rate-limiter.test.ts +37 -37
  147. package/src/rate-limit/in-memory-rate-limiter.ts +17 -17
  148. package/src/rate-limit/no-op-rate-limiter.test.ts +22 -22
  149. package/src/rate-limit/no-op-rate-limiter.ts +11 -11
  150. package/src/search-utils.test.ts +211 -211
  151. package/src/search-utils.ts +213 -213
  152. package/src/search.ts +65 -65
  153. package/src/shared/apply-policies.test.ts +81 -81
  154. package/src/shared/apply-policies.ts +67 -67
  155. package/src/shared/automations.repository.d1.ts +150 -150
  156. package/src/shared/background-notification-service.test.ts +62 -62
  157. package/src/shared/background-notification-service.ts +52 -52
  158. package/src/shared/base.repository.d1.ts +32 -32
  159. package/src/shared/content-utils.test.ts +165 -165
  160. package/src/shared/content-utils.ts +86 -86
  161. package/src/shared/content.repository.d1.test.ts +507 -458
  162. package/src/shared/content.repository.d1.ts +851 -851
  163. package/src/shared/d1-activity-log.repository.test.ts +140 -140
  164. package/src/shared/d1-activity-log.repository.ts +105 -105
  165. package/src/shared/d1-activity-logger.test.ts +86 -86
  166. package/src/shared/d1-activity-logger.ts +67 -67
  167. package/src/shared/d1-analytics.repository.test.ts +78 -78
  168. package/src/shared/d1-analytics.repository.ts +85 -85
  169. package/src/shared/d1-content-scan.repository.test.ts +80 -80
  170. package/src/shared/d1-content-scan.repository.ts +37 -37
  171. package/src/shared/d1-notification.repository.test.ts +128 -128
  172. package/src/shared/d1-notification.repository.ts +118 -118
  173. package/src/shared/d1-password-reset-token.repository.test.ts +81 -81
  174. package/src/shared/d1-password-reset-token.repository.ts +56 -56
  175. package/src/shared/d1-search.repository.test.ts +87 -87
  176. package/src/shared/d1-search.repository.ts +88 -88
  177. package/src/shared/d1-session.repository.test.ts +125 -125
  178. package/src/shared/d1-session.repository.ts +102 -102
  179. package/src/shared/d1-setup-checklist.repository.ts +36 -36
  180. package/src/shared/d1-user.repository.test.ts +151 -151
  181. package/src/shared/d1-user.repository.ts +119 -119
  182. package/src/shared/d1-widget.repository.test.ts +267 -221
  183. package/src/shared/d1-widget.repository.ts +385 -341
  184. package/src/shared/dashboard-layout.repository.d1.test.ts +135 -0
  185. package/src/shared/dashboard-layout.repository.d1.ts +58 -0
  186. package/src/shared/demo-data-sql.ts +216 -54
  187. package/src/shared/demo-data.repository.d1.ts +20 -20
  188. package/src/shared/execution-context-scheduler.ts +13 -13
  189. package/src/shared/fixed-clock.ts +25 -25
  190. package/src/shared/fts-sync.ts +8 -8
  191. package/src/shared/idempotency.repository.d1.test.ts +83 -83
  192. package/src/shared/idempotency.repository.d1.ts +60 -60
  193. package/src/shared/in-memory-activity-logger.ts +19 -19
  194. package/src/shared/in-memory-notification-service.ts +19 -19
  195. package/src/shared/in-memory-seed.repository.ts +58 -51
  196. package/src/shared/media.repository.d1.test.ts +107 -107
  197. package/src/shared/media.repository.d1.ts +68 -68
  198. package/src/shared/qstash-notification-service.test.ts +67 -67
  199. package/src/shared/qstash-notification-service.ts +55 -55
  200. package/src/shared/query-utils.ts +141 -141
  201. package/src/shared/request-utils.ts +26 -26
  202. package/src/shared/schema-mutator.d1.test.ts +142 -0
  203. package/src/shared/schema-mutator.d1.ts +64 -64
  204. package/src/shared/seed-layout.repository.d1.test.ts +114 -114
  205. package/src/shared/seed-layout.repository.d1.ts +62 -62
  206. package/src/shared/seed-registry-cache.test.ts +68 -68
  207. package/src/shared/seed-registry-cache.ts +49 -49
  208. package/src/shared/seed.repository.d1.test.ts +143 -143
  209. package/src/shared/seed.repository.d1.ts +98 -98
  210. package/src/shared/sequential-id-generator.ts +33 -33
  211. package/src/shared/site-settings.repository.d1.ts +53 -53
  212. package/src/shared/storage/factory.ts +41 -41
  213. package/src/shared/storage/s3-bucket.ts +195 -195
  214. package/src/shared/storage-utils.ts +40 -40
  215. package/src/shared/system-stats.repository.d1.test.ts +58 -58
  216. package/src/shared/system-stats.repository.d1.ts +48 -48
  217. package/src/types.ts +90 -87
  218. package/src/upload.ts +198 -198
  219. package/src/widget.test.ts +85 -0
  220. package/src/widget.ts +251 -212
  221. package/assets/dashboard/assets/index-BSjk0Sx9.js +0 -634
  222. package/assets/dashboard/assets/index-kRCYVN2B.css +0 -1
@@ -1,632 +1,1199 @@
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 { 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
- repo?: ISeedRepository
68
- mutator?: ISchemaMutator
69
- backrefMap?: Map<string, any[]>
70
- automationRepository?: any
71
- db?: any
72
- } = {}) {
73
- const app = new Hono()
74
- const repo = opts.repo ?? makeRepo()
75
- const mutator = opts.mutator ?? makeMutator()
76
- const backrefMap = opts.backrefMap ?? new Map()
77
- const activityLogger = makeActivityLogger()
78
- // Default stub DB (used by hard-delete R2 cascade) — no results
79
- const db = opts.db ?? { prepare: () => ({ all: async () => ({ results: [] }) }) }
80
- const automationRepository = opts.automationRepository ?? { list: async () => [] }
81
-
82
- app.use('*', async (c, next) => {
83
- c.set('jwtPayload' as never, opts.role ? { sub: 'u1', email: 'a@b.com', role: opts.role } : null)
84
- c.set('seedRepository' as never, repo)
85
- c.set('schemaMutator' as never, mutator)
86
- c.set('backrefMap' as never, backrefMap)
87
- c.set('activityLogger' as never, activityLogger)
88
- c.set('automationRepository' as never, automationRepository)
89
- c.set('env' as never, { ENV: 'test', DB: db })
90
- await next()
91
- })
92
- app.route('/', seedsApp)
93
- return { app, repo, mutator, activityLogger }
94
- }
95
-
96
- // ─── Tests ────────────────────────────────────────────────────────────────────
97
-
98
- describe('GET /', () => {
99
- it('403 for non-admin', async () => {
100
- const { app } = buildApp({ role: 'user' })
101
- const res = await app.request('/', { method: 'GET' })
102
- expect(res.status).toBe(403)
103
- })
104
-
105
- it('200 returns all records', async () => {
106
- const { app } = buildApp({ role: 'admin' })
107
- const res = await app.request('/', { method: 'GET' })
108
- expect(res.status).toBe(200)
109
- const body = await res.json() as any[]
110
- expect(body).toHaveLength(1)
111
- expect(body[0].slug).toBe('articles')
112
- })
113
- })
114
-
115
- describe('GET /:slug', () => {
116
- it('404 for missing seed', async () => {
117
- const { app } = buildApp({ role: 'admin' })
118
- const res = await app.request('/nope', { method: 'GET' })
119
- expect(res.status).toBe(404)
120
- })
121
-
122
- it('200 returns the record', async () => {
123
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
124
- const { app } = buildApp({ role: 'admin', repo })
125
- const res = await app.request('/articles', { method: 'GET' })
126
- expect(res.status).toBe(200)
127
- const body = await res.json() as any
128
- expect(body.slug).toBe('articles')
129
- })
130
- })
131
-
132
- describe('POST / (create)', () => {
133
- it('403 for non-admin', async () => {
134
- const { app } = buildApp({ role: 'user' })
135
- const res = await app.request('/', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(baseSeed) })
136
- expect(res.status).toBe(403)
137
- })
138
-
139
- it('409 when slug already active', async () => {
140
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
141
- const { app } = buildApp({ role: 'admin', repo })
142
- const res = await app.request('/', {
143
- method: 'POST',
144
- headers: { 'Content-Type': 'application/json' },
145
- body: JSON.stringify(baseSeed),
146
- })
147
- expect(res.status).toBe(409)
148
- })
149
-
150
- it('creates new seed: planCreateSeed DDL emitted, upsert called, 201', async () => {
151
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
152
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(null) })
153
- const { app, activityLogger } = buildApp({ role: 'admin', repo, mutator })
154
-
155
- const newSeed: Seed = {
156
- slug: 'notes',
157
- label: 'Notes',
158
- displayNameAlias: 'title',
159
- branches: [{ id: 'br_01', alias: 'title', label: 'Title', type: 'text' }],
160
- }
161
- const res = await app.request('/', {
162
- method: 'POST',
163
- headers: { 'Content-Type': 'application/json' },
164
- body: JSON.stringify(newSeed),
165
- })
166
- expect(res.status).toBe(201)
167
-
168
- const ddlCalls = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls
169
- expect(ddlCalls.length).toBe(1)
170
- const stmts: string[] = ddlCalls[0][0]
171
- expect(stmts.some((s: string) => s.includes('CREATE TABLE') && s.includes('content_notes'))).toBe(true)
172
- expect(stmts.some((s: string) => s.includes('DROP'))).toBe(false)
173
-
174
- expect((repo.upsert as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
175
- expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
176
- expect(activityLogger.log.mock.calls.length).toBe(1)
177
- expect(activityLogger.log.mock.calls[0][0].action).toBe('create')
178
-
179
- const body = await res.json() as any
180
- expect(body.slug).toBe('notes')
181
- })
182
-
183
- it('assigns br_NN ids to branches without ids', async () => {
184
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
185
- const mutator = makeMutator()
186
- const { app } = buildApp({ role: 'admin', repo, mutator })
187
-
188
- const noIdSeed = {
189
- slug: 'tags',
190
- label: 'Tags',
191
- displayNameAlias: 'name',
192
- branches: [{ alias: 'name', label: 'Name', type: 'text' }],
193
- }
194
- const res = await app.request('/', {
195
- method: 'POST',
196
- headers: { 'Content-Type': 'application/json' },
197
- body: JSON.stringify(noIdSeed),
198
- })
199
- expect(res.status).toBe(201)
200
- const upsertArg = (repo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as Seed
201
- expect(upsertArg.branches[0].id).toMatch(/^br_\d+$/)
202
- })
203
-
204
- it('revives a soft-deleted seed without failing on IF NOT EXISTS', async () => {
205
- const deletedRecord: SeedRecord = { ...baseRecord, status: 'deleted' }
206
- const repo = makeRepo({
207
- get: vi.fn().mockResolvedValue(deletedRecord),
208
- listActive: vi.fn().mockResolvedValue([]),
209
- })
210
- const existingCols = new Set(['id', 'title'])
211
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
212
- const { app } = buildApp({ role: 'admin', repo, mutator })
213
-
214
- const res = await app.request('/', {
215
- method: 'POST',
216
- headers: { 'Content-Type': 'application/json' },
217
- body: JSON.stringify(baseSeed),
218
- })
219
- expect(res.status).toBe(201)
220
- // No CREATE TABLE was emitted (table already exists), planExtendSeed path taken
221
- const stmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls[0]?.[0] ?? []
222
- expect(stmts.every((s: string) => !s.includes('CREATE TABLE IF NOT EXISTS content_articles') || s.includes('IF NOT EXISTS'))).toBe(true)
223
- })
224
-
225
- it('422 for unknown relation target', async () => {
226
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(null), listActive: vi.fn().mockResolvedValue([]) })
227
- const { app } = buildApp({ role: 'admin', repo })
228
-
229
- const relSeed: Seed = {
230
- slug: 'posts',
231
- label: 'Posts',
232
- displayNameAlias: 'title',
233
- branches: [
234
- { id: 'br_01', alias: 'title', label: 'Title', type: 'text' },
235
- { id: 'br_02', alias: 'author', label: 'Author', type: 'relation', targetSeed: 'nonexistent' },
236
- ],
237
- }
238
- const res = await app.request('/', {
239
- method: 'POST',
240
- headers: { 'Content-Type': 'application/json' },
241
- body: JSON.stringify(relSeed),
242
- })
243
- expect(res.status).toBe(422)
244
- })
245
- })
246
-
247
- describe('PUT /:slug (edit)', () => {
248
- it('403 for non-admin', async () => {
249
- const { app } = buildApp({ role: 'user' })
250
- const res = await app.request('/articles', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(baseSeed) })
251
- expect(res.status).toBe(403)
252
- })
253
-
254
- it('422 on alias rename (same id, different alias)', async () => {
255
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
256
- const { app } = buildApp({ role: 'admin', repo })
257
-
258
- const renamed: Seed = {
259
- ...baseSeed,
260
- branches: [
261
- { id: 'br_01', alias: 'headline', label: 'Headline', type: 'text' }, // alias changed
262
- { id: 'br_02', alias: 'body', label: 'Body', type: 'richtext' },
263
- ],
264
- }
265
- const res = await app.request('/articles', {
266
- method: 'PUT',
267
- headers: { 'Content-Type': 'application/json' },
268
- body: JSON.stringify(renamed),
269
- })
270
- expect(res.status).toBe(422)
271
- const body = await res.json() as any
272
- expect(body.type).toContain('alias-rename-not-supported')
273
- })
274
-
275
- it('422 on branch type change', async () => {
276
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
277
- const { app } = buildApp({ role: 'admin', repo })
278
-
279
- const typeChanged: Seed = {
280
- ...baseSeed,
281
- branches: [
282
- { id: 'br_01', alias: 'title', label: 'Title', type: 'number' }, // type 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(typeChanged),
290
- })
291
- expect(res.status).toBe(422)
292
- const body = await res.json() as any
293
- expect(body.type).toContain('branch-type-change-not-supported')
294
- })
295
-
296
- it('add branch emits ADD COLUMN, no DROP', async () => {
297
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
298
- const existingCols = new Set(['id', 'title', 'body'])
299
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
300
- const { app } = buildApp({ role: 'admin', repo, mutator })
301
-
302
- const withNew: Seed = {
303
- ...baseSeed,
304
- branches: [
305
- ...baseSeed.branches,
306
- { id: 'br_03', alias: 'summary', label: 'Summary', type: 'text' },
307
- ],
308
- }
309
- const res = await app.request('/articles', {
310
- method: 'PUT',
311
- headers: { 'Content-Type': 'application/json' },
312
- body: JSON.stringify(withNew),
313
- })
314
- expect(res.status).toBe(200)
315
-
316
- const stmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls[0][0]
317
- expect(stmts.some((s: string) => s.includes('ADD COLUMN') && s.includes('summary'))).toBe(true)
318
- expect(stmts.every((s: string) => !s.includes('DROP'))).toBe(true)
319
- })
320
-
321
- it('removing a branch: no DROP emitted, column retained', async () => {
322
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
323
- const existingCols = new Set(['id', 'title', 'body'])
324
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
325
- const { app } = buildApp({ role: 'admin', repo, mutator })
326
-
327
- const withRemoved: Seed = {
328
- ...baseSeed,
329
- branches: [baseSeed.branches[0]], // body removed
330
- }
331
- const res = await app.request('/articles', {
332
- method: 'PUT',
333
- headers: { 'Content-Type': 'application/json' },
334
- body: JSON.stringify(withRemoved),
335
- })
336
- expect(res.status).toBe(200)
337
-
338
- const allStmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls.flatMap((c: any) => c[0])
339
- expect(allStmts.every((s: string) => !s.includes('DROP'))).toBe(true)
340
- })
341
- })
342
-
343
- describe('POST /:slug/branches (add branch)', () => {
344
- it('assigns id and emits ADD COLUMN', async () => {
345
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
346
- const existingCols = new Set(['id', 'title', 'body'])
347
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
348
- const { app } = buildApp({ role: 'admin', repo, mutator })
349
-
350
- const res = await app.request('/articles/branches', {
351
- method: 'POST',
352
- headers: { 'Content-Type': 'application/json' },
353
- body: JSON.stringify({ alias: 'excerpt', label: 'Excerpt', type: 'text' }),
354
- })
355
- expect(res.status).toBe(200)
356
- const body = await res.json() as any
357
- expect(body.id).toMatch(/^br_\d+$/)
358
-
359
- const stmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls[0][0]
360
- expect(stmts.some((s: string) => s.includes('ADD COLUMN') && s.includes('excerpt'))).toBe(true)
361
- })
362
-
363
- it('column already present: no ADD COLUMN emitted', async () => {
364
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
365
- const existingCols = new Set(['id', 'title', 'body', 'excerpt'])
366
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(existingCols) })
367
- const { app } = buildApp({ role: 'admin', repo, mutator })
368
-
369
- const res = await app.request('/articles/branches', {
370
- method: 'POST',
371
- headers: { 'Content-Type': 'application/json' },
372
- body: JSON.stringify({ alias: 'excerpt', label: 'Excerpt', type: 'text' }),
373
- })
374
- expect(res.status).toBe(200)
375
-
376
- const stmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls[0]?.[0] ?? []
377
- expect(stmts.every((s: string) => !s.includes('ADD COLUMN'))).toBe(true)
378
- })
379
- })
380
-
381
- describe('DELETE /:slug', () => {
382
- it('403 for non-admin', async () => {
383
- const { app } = buildApp({ role: 'user' })
384
- const res = await app.request('/articles', { method: 'DELETE' })
385
- expect(res.status).toBe(403)
386
- })
387
-
388
- it('soft-deletes: status flips, table not dropped, version bumped', async () => {
389
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
390
- const mutator = makeMutator()
391
- const { app } = buildApp({ role: 'admin', repo, mutator })
392
-
393
- const res = await app.request('/articles', { method: 'DELETE' })
394
- expect(res.status).toBe(200)
395
-
396
- expect((repo.softDelete as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
397
- expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
398
-
399
- // No DDL involving DROP was emitted
400
- const allStmts: string[] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls.flatMap((c: any) => c[0])
401
- expect(allStmts.every((s: string) => !s.includes('DROP'))).toBe(true)
402
- })
403
-
404
- it('409 when seed is referenced by another seed relation', async () => {
405
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
406
- const backrefMap = new Map([['articles', [{ seedSlug: 'comments', branchAlias: 'article' }]]])
407
- const { app } = buildApp({ role: 'admin', repo, backrefMap })
408
-
409
- const res = await app.request('/articles', { method: 'DELETE' })
410
- expect(res.status).toBe(409)
411
- const body = await res.json() as any
412
- expect(body.type).toContain('seed-referenced')
413
- })
414
-
415
- it('404 for non-existent seed', async () => {
416
- const { app } = buildApp({ role: 'admin' })
417
- const res = await app.request('/nope', { method: 'DELETE' })
418
- expect(res.status).toBe(404)
419
- })
420
- })
421
-
422
- // ─── Sprint 06 Danger Zone routes ────────────────────────────────────────────
423
-
424
- describe('GET /:slug/orphans', () => {
425
- it('returns orphan columns not in the definition', async () => {
426
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
427
- // DB has 'id', 'slug', 'status', 'created_at', 'updated_at', 'title', 'body', 'legacy'
428
- const dbCols = new Set(['id', 'slug', 'status', 'created_at', 'updated_at', 'title', 'body', 'legacy'])
429
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(dbCols) })
430
- const { app } = buildApp({ role: 'admin', repo, mutator })
431
-
432
- const res = await app.request('/articles/orphans', { method: 'GET' })
433
- expect(res.status).toBe(200)
434
- const body = await res.json() as any
435
- expect(body.orphans).toContain('legacy')
436
- expect(body.orphans).not.toContain('title')
437
- })
438
-
439
- it('returns empty when DB has no orphans', async () => {
440
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
441
- const dbCols = new Set(['id', 'slug', 'status', 'created_at', 'updated_at', 'title', 'body'])
442
- const mutator = makeMutator({ getColumns: vi.fn().mockResolvedValue(dbCols) })
443
- const { app } = buildApp({ role: 'admin', repo, mutator })
444
-
445
- const res = await app.request('/articles/orphans', { method: 'GET' })
446
- expect(res.status).toBe(200)
447
- const body = await res.json() as any
448
- expect(body.orphans).toHaveLength(0)
449
- })
450
- })
451
-
452
- describe('DELETE /:slug/hard', () => {
453
- it('400 on confirm mismatch', async () => {
454
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
455
- const { app } = buildApp({ role: 'admin', repo })
456
-
457
- const res = await app.request('/articles/hard', {
458
- method: 'DELETE',
459
- headers: { 'Content-Type': 'application/json' },
460
- body: JSON.stringify({ confirm: 'wrong' }),
461
- })
462
- expect(res.status).toBe(400)
463
- const body = await res.json() as any
464
- expect(body.type).toContain('confirmation-required')
465
- })
466
-
467
- it('409 when seed is referenced', async () => {
468
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
469
- const backrefMap = new Map([['articles', [{ sourceSlug: 'comments' }]]])
470
- const { app } = buildApp({ role: 'admin', repo, backrefMap })
471
-
472
- const res = await app.request('/articles/hard', {
473
- method: 'DELETE',
474
- headers: { 'Content-Type': 'application/json' },
475
- body: JSON.stringify({ confirm: 'articles' }),
476
- })
477
- expect(res.status).toBe(409)
478
- })
479
-
480
- it('hard delete: execDestructive called, hardDelete called, version bumped, audit logged', async () => {
481
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
482
- const mutator = makeMutator()
483
- const { app, activityLogger } = buildApp({ role: 'admin', repo, mutator })
484
-
485
- const res = await app.request('/articles/hard', {
486
- method: 'DELETE',
487
- headers: { 'Content-Type': 'application/json' },
488
- body: JSON.stringify({ confirm: 'articles' }),
489
- })
490
- expect(res.status).toBe(200)
491
-
492
- expect((mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls.length).toBeGreaterThan(0)
493
- // execDdl must NOT have been called for DROP
494
- const ddlCalls: string[][] = (mutator.execDdl as ReturnType<typeof vi.fn>).mock.calls.flatMap((c: any) => c[0])
495
- expect(ddlCalls.every((s: string) => !s.toUpperCase().includes('DROP'))).toBe(true)
496
-
497
- expect((repo.hardDelete as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
498
- expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
499
- expect(activityLogger.log.mock.calls[0][0].action).toBe('delete')
500
- expect(activityLogger.log.mock.calls[0][0].details.op).toBe('hard-delete')
501
- })
502
- })
503
-
504
- describe('DELETE /:slug/branches/:branchId', () => {
505
- it('400 on confirm mismatch', async () => {
506
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
507
- const { app } = buildApp({ role: 'admin', repo })
508
-
509
- const res = await app.request('/articles/branches/br_01', {
510
- method: 'DELETE',
511
- headers: { 'Content-Type': 'application/json' },
512
- body: JSON.stringify({ confirm: 'wrong' }),
513
- })
514
- expect(res.status).toBe(400)
515
- })
516
-
517
- it('drops branch: execDestructive called, definition updated, version bumped', async () => {
518
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
519
- const mutator = makeMutator()
520
- const { app } = buildApp({ role: 'admin', repo, mutator })
521
-
522
- const res = await app.request('/articles/branches/br_02', {
523
- method: 'DELETE',
524
- headers: { 'Content-Type': 'application/json' },
525
- body: JSON.stringify({ confirm: 'articles.body' }),
526
- })
527
- expect(res.status).toBe(200)
528
-
529
- expect((mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
530
- const upsertArg = (repo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as any
531
- expect(upsertArg.branches.find((b: any) => b.id === 'br_02')).toBeUndefined()
532
- expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
533
- })
534
-
535
- it('404 for unknown branchId', async () => {
536
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
537
- const { app } = buildApp({ role: 'admin', repo })
538
-
539
- const res = await app.request('/articles/branches/br_99', {
540
- method: 'DELETE',
541
- headers: { 'Content-Type': 'application/json' },
542
- body: JSON.stringify({ confirm: 'articles.unknown' }),
543
- })
544
- expect(res.status).toBe(404)
545
- })
546
- })
547
-
548
- describe('PATCH /:slug/branches/:branchId/rename', () => {
549
- it('400 on confirm mismatch', async () => {
550
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
551
- const { app } = buildApp({ role: 'admin', repo })
552
-
553
- const res = await app.request('/articles/branches/br_01/rename', {
554
- method: 'PATCH',
555
- headers: { 'Content-Type': 'application/json' },
556
- body: JSON.stringify({ newAlias: 'headline', confirm: 'wrong' }),
557
- })
558
- expect(res.status).toBe(400)
559
- })
560
-
561
- it('renames alias: execDestructive called with RENAME, definition updated, automation warnings returned', async () => {
562
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
563
- const mutator = makeMutator()
564
- const automationRepository = { list: vi.fn().mockResolvedValue([{ id: 'auto_1', conditions: 'title' }]) }
565
- const { app } = buildApp({ role: 'admin', repo, mutator, automationRepository })
566
-
567
- const res = await app.request('/articles/branches/br_01/rename', {
568
- method: 'PATCH',
569
- headers: { 'Content-Type': 'application/json' },
570
- body: JSON.stringify({ newAlias: 'headline', confirm: 'articles.title' }),
571
- })
572
- expect(res.status).toBe(200)
573
-
574
- const destructiveCalls: string[][] = (mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls[0][0]
575
- expect(destructiveCalls.some((s: string) => s.toUpperCase().includes('RENAME COLUMN') || s.toUpperCase().includes('RENAME TO'))).toBe(true)
576
-
577
- const upsertArg = (repo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as any
578
- const renamed = upsertArg.branches.find((b: any) => b.id === 'br_01')
579
- expect(renamed?.alias).toBe('headline')
580
-
581
- const body = await res.json() as any
582
- expect(body.affectedAutomations).toContain('auto_1')
583
- })
584
- })
585
-
586
- describe('PATCH /:slug/branches/:branchId/retype', () => {
587
- it('400 on confirm mismatch', async () => {
588
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
589
- const { app } = buildApp({ role: 'admin', repo })
590
-
591
- const res = await app.request('/articles/branches/br_01/retype', {
592
- method: 'PATCH',
593
- headers: { 'Content-Type': 'application/json' },
594
- body: JSON.stringify({ newType: 'number', confirm: 'wrong' }),
595
- })
596
- expect(res.status).toBe(400)
597
- })
598
-
599
- it('retypes branch: execDestructive called, definition updated, version bumped', async () => {
600
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
601
- const mutator = makeMutator()
602
- const { app } = buildApp({ role: 'admin', repo, mutator })
603
-
604
- const res = await app.request('/articles/branches/br_01/retype', {
605
- method: 'PATCH',
606
- headers: { 'Content-Type': 'application/json' },
607
- body: JSON.stringify({ newType: 'number', confirm: 'articles.title' }),
608
- })
609
- expect(res.status).toBe(200)
610
-
611
- expect((mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
612
- const upsertArg = (repo.upsert as ReturnType<typeof vi.fn>).mock.calls[0][1] as any
613
- expect(upsertArg.branches.find((b: any) => b.id === 'br_01')?.type).toBe('number')
614
- expect((repo.bumpRegistryVersion as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
615
- })
616
- })
617
-
618
- describe('POST /:slug/fts/rebuild', () => {
619
- it('calls execDestructive with FTS statements and logs audit', async () => {
620
- const repo = makeRepo({ get: vi.fn().mockResolvedValue(baseRecord) })
621
- const mutator = makeMutator()
622
- const { app, activityLogger } = buildApp({ role: 'admin', repo, mutator })
623
-
624
- const res = await app.request('/articles/fts/rebuild', { method: 'POST' })
625
- expect(res.status).toBe(200)
626
-
627
- expect((mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls.length).toBe(1)
628
- const stmts: string[] = (mutator.execDestructive as ReturnType<typeof vi.fn>).mock.calls[0][0]
629
- expect(stmts.some((s: string) => s.includes('fts_articles'))).toBe(true)
630
- expect(activityLogger.log.mock.calls[0][0].details.op).toBe('fts-rebuild')
631
- })
632
- })
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
+ })