@beechcms/api 0.4.0 → 0.4.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.
- package/assets/dashboard/assets/index-BKWnlvnV.css +1 -0
- package/assets/dashboard/assets/index-C1P9BXnU.js +629 -0
- package/assets/dashboard/index.html +2 -2
- package/migrations/0000_v040_base.sql +25 -0
- package/migrations/0029_automations.sql +14 -0
- package/package.json +4 -3
- package/src/auth/bcrypt-hash-provider.ts +20 -0
- package/src/auth/constants.ts +3 -3
- package/src/auth/generate-refresh-token.test.ts +19 -0
- package/src/auth/hash-provider.test.ts +46 -0
- package/src/auth/in-memory-hash-provider.ts +13 -0
- package/src/auth/jose-token-service.ts +55 -0
- package/src/auth/login.test.ts +92 -0
- package/src/auth/login.ts +15 -32
- package/src/auth/refresh.ts +0 -122
- package/src/auth/static-token-service.ts +18 -0
- package/src/auth/token-service.test.ts +82 -0
- package/src/factory.ts +80 -80
- package/src/features/automations/__tests__/action-executors.test.ts +268 -0
- package/src/features/automations/__tests__/automation-runner.test.ts +192 -0
- package/src/features/automations/__tests__/automation-runner.utils.test.ts +56 -0
- package/src/features/automations/__tests__/automations.handler.test.ts +260 -0
- package/src/features/automations/__tests__/automations.repository.test.ts +159 -0
- package/src/features/automations/__tests__/automations.schema.test.ts +134 -0
- package/src/features/automations/__tests__/context-resolver.test.ts +122 -0
- package/src/features/automations/__tests__/cron-runner.test.ts +263 -0
- package/src/features/automations/__tests__/cron-runner.utils.test.ts +140 -0
- package/src/features/automations/__tests__/set-variable.executor.test.ts +306 -0
- package/src/features/automations/__tests__/template-grammar.test.ts +304 -0
- package/src/features/automations/__tests__/when-evaluator.test.ts +270 -0
- package/src/features/automations/__tests__/when-pushdown.test.ts +277 -0
- package/src/features/automations/action-executors/create-entry.executor.ts +23 -0
- package/src/features/automations/action-executors/edit-field.executor.ts +22 -0
- package/src/features/automations/action-executors/index.ts +33 -0
- package/src/features/automations/action-executors/send-mail.executor.ts +42 -0
- package/src/features/automations/action-executors/set-variable.executor.ts +146 -0
- package/src/features/automations/action-executors/webhook.executor.ts +25 -0
- package/src/features/automations/automation-runner.ts +81 -0
- package/src/features/automations/automation-runner.utils.ts +43 -0
- package/src/features/automations/automations.handler.ts +193 -0
- package/src/features/automations/automations.schema.ts +160 -0
- package/src/features/automations/context-resolver.ts +148 -0
- package/src/features/automations/cron-runner.ts +136 -0
- package/src/features/automations/cron-runner.utils.ts +40 -0
- package/src/features/automations/filter-translation.ts +42 -0
- package/src/features/automations/index.ts +12 -0
- package/src/features/automations/template-grammar.ts +241 -0
- package/src/features/automations/var-access-resolver.ts +136 -0
- package/src/features/automations/when-evaluator.ts +83 -0
- package/src/features/automations/when-pushdown.ts +53 -0
- package/src/features/content/handlers/create.ts +22 -10
- package/src/features/content/handlers/delete.ts +21 -10
- package/src/features/content/handlers/update.ts +21 -9
- package/src/features/draft/draft.handler.ts +51 -153
- package/src/features/draft/draft.middleware.ts +62 -0
- package/src/features/email/email.service.ts +13 -0
- package/src/features/email/email.types.ts +10 -0
- package/src/features/email/index.ts +2 -1
- package/src/features/email/templates/automation-mail.ts +15 -0
- package/src/features/notifications/notifications.handler.ts +25 -54
- package/src/features/password-reset/request.ts +17 -41
- package/src/features/password-reset/reset.ts +18 -54
- package/src/features/rotate-field/rotate-field.handler.ts +15 -19
- package/src/features/schema/schema.handler.ts +1 -1
- package/src/features/settings/settings.handler.ts +64 -176
- package/src/features/setup/index.ts +12 -17
- package/src/features/stats/stats.handler.ts +110 -138
- package/src/index.ts +40 -8
- package/src/middleware/auth-providers.middleware.ts +32 -0
- package/src/middleware/observability.middleware.ts +52 -0
- package/src/middleware/rate-limit.middleware.ts +41 -0
- package/src/middleware/repository.middleware.ts +72 -5
- package/src/middleware.ts +15 -35
- package/src/public/cache-utils.ts +34 -0
- package/src/public/entry-projection.ts +42 -0
- package/src/public/idempotency.ts +19 -0
- package/src/public/problem-details.ts +5 -0
- package/src/public/public-add.ts +110 -166
- package/src/public/public-edit.ts +4 -3
- package/src/public/public-read.ts +59 -216
- package/src/public/public-routes.ts +2 -2
- package/src/public/query-builder.test.ts +220 -0
- package/src/public/rate-limit-middleware.ts +7 -19
- package/src/public/read-list.ts +50 -0
- package/src/public/read-single.ts +44 -0
- package/src/rate-limit/cloudflare-rate-limiter.test.ts +26 -0
- package/src/rate-limit/cloudflare-rate-limiter.ts +11 -0
- package/src/rate-limit/in-memory-rate-limiter.test.ts +33 -0
- package/src/rate-limit/in-memory-rate-limiter.ts +13 -0
- package/src/rate-limit/no-op-rate-limiter.test.ts +18 -0
- package/src/rate-limit/no-op-rate-limiter.ts +7 -0
- package/src/search-utils.test.ts +207 -0
- package/src/search-utils.ts +18 -1
- package/src/search.ts +24 -35
- package/src/shared/apply-policies.test.ts +77 -0
- package/src/shared/automations.repository.d1.ts +146 -0
- package/src/shared/background-notification-service.test.ts +58 -0
- package/src/shared/background-notification-service.ts +48 -0
- package/src/shared/content-utils.test.ts +161 -0
- package/src/shared/content.repository.d1.test.ts +312 -0
- package/src/shared/d1-activity-log.repository.test.ts +136 -0
- package/src/shared/d1-activity-log.repository.ts +101 -0
- package/src/shared/d1-activity-logger.test.ts +82 -0
- package/src/shared/d1-activity-logger.ts +63 -0
- package/src/shared/d1-analytics.repository.test.ts +74 -0
- package/src/shared/d1-analytics.repository.ts +81 -0
- package/src/shared/d1-content-scan.repository.test.ts +76 -0
- package/src/shared/d1-content-scan.repository.ts +29 -0
- package/src/shared/d1-notification.repository.test.ts +124 -0
- package/src/shared/d1-notification.repository.ts +114 -0
- package/src/shared/d1-password-reset-token.repository.test.ts +77 -0
- package/src/shared/d1-password-reset-token.repository.ts +52 -0
- package/src/shared/d1-search.repository.test.ts +83 -0
- package/src/shared/d1-search.repository.ts +84 -0
- package/src/shared/d1-session.repository.test.ts +121 -0
- package/src/shared/d1-session.repository.ts +98 -0
- package/src/shared/d1-user.repository.test.ts +147 -0
- package/src/shared/d1-user.repository.ts +109 -0
- package/src/shared/d1-widget.repository.test.ts +217 -0
- package/src/shared/d1-widget.repository.ts +337 -0
- package/src/shared/execution-context-scheduler.ts +9 -0
- package/src/shared/fixed-clock.ts +21 -0
- package/src/shared/idempotency.repository.d1.test.ts +79 -0
- package/src/shared/in-memory-activity-logger.ts +15 -0
- package/src/shared/in-memory-notification-service.ts +15 -0
- package/src/shared/media.repository.d1.test.ts +103 -0
- package/src/shared/media.repository.d1.ts +1 -1
- package/src/shared/request-utils.ts +22 -0
- package/src/shared/sequential-id-generator.ts +22 -0
- package/src/shared/storage-utils.ts +3 -3
- package/src/shared/system-stats.repository.d1.test.ts +54 -0
- package/src/types.ts +24 -3
- package/src/upload.ts +17 -9
- package/src/widget.ts +112 -253
- package/assets/dashboard/assets/index-CewtCjom.css +0 -1
- package/assets/dashboard/assets/index-FQ6JhvRH.js +0 -554
- package/src/shared/activity-logger.ts +0 -79
- package/src/shared/notification-service.ts +0 -56
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
2
|
+
import { BackgroundNotificationService } from './background-notification-service'
|
|
3
|
+
import type { INotificationRepository, NotificationRecord } from '@beechcms/core'
|
|
4
|
+
|
|
5
|
+
function makeRepository(opts: { createShouldThrow?: boolean } = {}): INotificationRepository {
|
|
6
|
+
return {
|
|
7
|
+
list: vi.fn().mockResolvedValue([]),
|
|
8
|
+
stats: vi.fn().mockResolvedValue({ totalCount: 0, latestCreatedAt: 0, readCount: 0 }),
|
|
9
|
+
create: opts.createShouldThrow
|
|
10
|
+
? vi.fn().mockRejectedValue(new Error('db down'))
|
|
11
|
+
: vi.fn().mockResolvedValue('generated-id'),
|
|
12
|
+
markRead: vi.fn(),
|
|
13
|
+
markUnread: vi.fn(),
|
|
14
|
+
markAllRead: vi.fn(),
|
|
15
|
+
delete: vi.fn(),
|
|
16
|
+
} as unknown as INotificationRepository & {
|
|
17
|
+
create: ReturnType<typeof vi.fn>
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
describe('BackgroundNotificationService', () => {
|
|
22
|
+
it('delegates persistence to the repository with the provided fields', async () => {
|
|
23
|
+
const repo = makeRepository()
|
|
24
|
+
await new BackgroundNotificationService(repo).notify({
|
|
25
|
+
title: 'Hello',
|
|
26
|
+
message: 'World',
|
|
27
|
+
type: 'success',
|
|
28
|
+
})
|
|
29
|
+
expect(repo.create).toHaveBeenCalledWith({
|
|
30
|
+
title: 'Hello',
|
|
31
|
+
message: 'World',
|
|
32
|
+
type: 'success',
|
|
33
|
+
})
|
|
34
|
+
})
|
|
35
|
+
|
|
36
|
+
it('defaults to type "info" when none is provided', async () => {
|
|
37
|
+
const repo = makeRepository()
|
|
38
|
+
await new BackgroundNotificationService(repo).notify({ title: 'T', message: 'M' })
|
|
39
|
+
expect(repo.create).toHaveBeenCalledWith({ title: 'T', message: 'M', type: 'info' })
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
it('delegates to the background scheduler when provided', () => {
|
|
43
|
+
const repo = makeRepository()
|
|
44
|
+
const schedule = vi.fn()
|
|
45
|
+
new BackgroundNotificationService(repo, schedule).notify({ title: 'T', message: 'M' })
|
|
46
|
+
expect(schedule).toHaveBeenCalledTimes(1)
|
|
47
|
+
expect(schedule.mock.calls[0][0]).toBeInstanceOf(Promise)
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
it('never throws to the caller when the repository write fails', async () => {
|
|
51
|
+
const repo = makeRepository({ createShouldThrow: true })
|
|
52
|
+
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
53
|
+
const service = new BackgroundNotificationService(repo)
|
|
54
|
+
await expect(service.notify({ title: 'T', message: 'M' })).resolves.toBeUndefined()
|
|
55
|
+
expect(consoleSpy).toHaveBeenCalled()
|
|
56
|
+
consoleSpy.mockRestore()
|
|
57
|
+
})
|
|
58
|
+
})
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
INotificationService,
|
|
3
|
+
CreateNotificationInput,
|
|
4
|
+
INotificationRepository,
|
|
5
|
+
NotificationType,
|
|
6
|
+
} from '@beechcms/core'
|
|
7
|
+
|
|
8
|
+
const DEFAULT_NOTIFICATION_TYPE: NotificationType = 'info'
|
|
9
|
+
|
|
10
|
+
type ScheduleBackgroundTask = (task: Promise<unknown>) => void
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Production implementation of {@link INotificationService}.
|
|
14
|
+
*
|
|
15
|
+
* Delegates persistence to the injected {@link INotificationRepository}.
|
|
16
|
+
* When `scheduleBackgroundTask` is provided (wired to
|
|
17
|
+
* `c.executionCtx.waitUntil`), the repository write runs after the response
|
|
18
|
+
* is flushed so the public-API request that triggered it is never delayed.
|
|
19
|
+
*/
|
|
20
|
+
export class BackgroundNotificationService implements INotificationService {
|
|
21
|
+
constructor(
|
|
22
|
+
private readonly notificationRepository: INotificationRepository,
|
|
23
|
+
private readonly scheduleBackgroundTask?: ScheduleBackgroundTask
|
|
24
|
+
) {}
|
|
25
|
+
|
|
26
|
+
notify(input: CreateNotificationInput): Promise<void> | void {
|
|
27
|
+
const persistPromise = this.runPersist(input)
|
|
28
|
+
|
|
29
|
+
if (this.scheduleBackgroundTask) {
|
|
30
|
+
this.scheduleBackgroundTask(persistPromise)
|
|
31
|
+
return
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
return persistPromise
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
private async runPersist(input: CreateNotificationInput): Promise<void> {
|
|
38
|
+
try {
|
|
39
|
+
await this.notificationRepository.create({
|
|
40
|
+
title: input.title,
|
|
41
|
+
message: input.message,
|
|
42
|
+
type: input.type ?? DEFAULT_NOTIFICATION_TYPE,
|
|
43
|
+
})
|
|
44
|
+
} catch (error) {
|
|
45
|
+
console.error('BackgroundNotificationService: failed to create notification', error)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
2
|
+
import { rowToApiData, rowToEntry, buildInsertBindings, buildUpdateBindings, hasDraft } from './content-utils'
|
|
3
|
+
import type { Seed } from '@beechcms/core'
|
|
4
|
+
|
|
5
|
+
const SEED = {
|
|
6
|
+
slug: 'articoli',
|
|
7
|
+
displayNameAlias: 'title',
|
|
8
|
+
allowDrafts: true,
|
|
9
|
+
branches: [
|
|
10
|
+
{ id: 'br_01', alias: 'title', type: 'text' },
|
|
11
|
+
{ id: 'br_02', alias: 'body', type: 'text' },
|
|
12
|
+
],
|
|
13
|
+
} as unknown as Seed
|
|
14
|
+
|
|
15
|
+
const NO_DRAFT_SEED = {
|
|
16
|
+
slug: 'prodotti',
|
|
17
|
+
displayNameAlias: 'nome',
|
|
18
|
+
allowDrafts: false,
|
|
19
|
+
branches: [
|
|
20
|
+
{ id: 'br_01', alias: 'nome', type: 'text' },
|
|
21
|
+
],
|
|
22
|
+
} as unknown as Seed
|
|
23
|
+
|
|
24
|
+
// ─── rowToApiData ─────────────────────────────────────────────────────────────
|
|
25
|
+
|
|
26
|
+
describe('rowToApiData', () => {
|
|
27
|
+
it('returns an object keyed by branch aliases with deserialized values', () => {
|
|
28
|
+
const result = rowToApiData(SEED, { title: 'Hello', body: 'World' })
|
|
29
|
+
expect(result).toHaveProperty('title', 'Hello')
|
|
30
|
+
expect(result).toHaveProperty('body', 'World')
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
it('uses null for missing branch values', () => {
|
|
34
|
+
const result = rowToApiData(SEED, {})
|
|
35
|
+
expect(result.title).toBeNull()
|
|
36
|
+
expect(result.body).toBeNull()
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('only includes keys for branches defined in the seed', () => {
|
|
40
|
+
const result = rowToApiData(SEED, { title: 'Hi', unknownCol: 'ignored' })
|
|
41
|
+
expect(Object.keys(result)).toEqual(['title', 'body'])
|
|
42
|
+
expect(result).not.toHaveProperty('unknownCol')
|
|
43
|
+
})
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
// ─── rowToEntry ───────────────────────────────────────────────────────────────
|
|
47
|
+
|
|
48
|
+
describe('rowToEntry', () => {
|
|
49
|
+
it('maps a DB row to a ContentEntry with correct system fields', () => {
|
|
50
|
+
const row = {
|
|
51
|
+
id: 'entry-1', slug: 'my-post', status: 'published',
|
|
52
|
+
title: 'Hello', body: 'World', created_at: 1000, updated_at: 2000,
|
|
53
|
+
}
|
|
54
|
+
const entry = rowToEntry(SEED, row)
|
|
55
|
+
expect(entry.id).toBe('entry-1')
|
|
56
|
+
expect(entry.schema_slug).toBe('articoli')
|
|
57
|
+
expect(entry.slug).toBe('my-post')
|
|
58
|
+
expect(entry.status).toBe('published')
|
|
59
|
+
expect(entry.created_at).toBe(1000)
|
|
60
|
+
expect(entry.updated_at).toBe(2000)
|
|
61
|
+
expect(entry.hasPendingDraft).toBe(false)
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('defaults hasPendingDraft to false when not provided', () => {
|
|
65
|
+
const entry = rowToEntry(SEED, { id: 'e1', slug: null, status: 'draft', title: null, body: null, created_at: null, updated_at: null })
|
|
66
|
+
expect(entry.hasPendingDraft).toBe(false)
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it('passes through hasPendingDraft when explicitly set to true', () => {
|
|
70
|
+
const entry = rowToEntry(SEED, { id: 'e1', slug: null, status: 'draft', title: null, body: null }, true)
|
|
71
|
+
expect(entry.hasPendingDraft).toBe(true)
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it('defaults slug to null and status to draft for missing values', () => {
|
|
75
|
+
const entry = rowToEntry(SEED, { id: 'e1' })
|
|
76
|
+
expect(entry.slug).toBeNull()
|
|
77
|
+
expect(entry.status).toBe('draft')
|
|
78
|
+
})
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
// ─── buildInsertBindings ──────────────────────────────────────────────────────
|
|
82
|
+
|
|
83
|
+
describe('buildInsertBindings', () => {
|
|
84
|
+
it('returns cols, placeholders, and bindings for each matching branch alias', () => {
|
|
85
|
+
const { cols, placeholders, bindings } = buildInsertBindings(SEED, { title: 'Hi', body: 'There' })
|
|
86
|
+
expect(cols).toContain('title')
|
|
87
|
+
expect(cols).toContain('body')
|
|
88
|
+
expect(placeholders).toHaveLength(2)
|
|
89
|
+
expect(placeholders.every(p => p === '?')).toBe(true)
|
|
90
|
+
expect(bindings).toHaveLength(2)
|
|
91
|
+
})
|
|
92
|
+
|
|
93
|
+
it('omits branches not present in the payload', () => {
|
|
94
|
+
const { cols, bindings } = buildInsertBindings(SEED, { title: 'Only title' })
|
|
95
|
+
expect(cols).toEqual(['title'])
|
|
96
|
+
expect(bindings).toHaveLength(1)
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
it('returns empty arrays when payload has no matching aliases', () => {
|
|
100
|
+
const { cols, placeholders, bindings } = buildInsertBindings(SEED, { unknownField: 'x' })
|
|
101
|
+
expect(cols).toHaveLength(0)
|
|
102
|
+
expect(placeholders).toHaveLength(0)
|
|
103
|
+
expect(bindings).toHaveLength(0)
|
|
104
|
+
})
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
// ─── buildUpdateBindings ──────────────────────────────────────────────────────
|
|
108
|
+
|
|
109
|
+
describe('buildUpdateBindings', () => {
|
|
110
|
+
it('returns a SET clause and bindings for each matching branch alias', () => {
|
|
111
|
+
const { setClause, bindings } = buildUpdateBindings(SEED, { title: 'New', body: 'Content' })
|
|
112
|
+
expect(setClause).toContain('title = ?')
|
|
113
|
+
expect(setClause).toContain('body = ?')
|
|
114
|
+
expect(bindings).toHaveLength(2)
|
|
115
|
+
})
|
|
116
|
+
|
|
117
|
+
it('builds a single-field SET clause', () => {
|
|
118
|
+
const { setClause, bindings } = buildUpdateBindings(SEED, { title: 'Updated' })
|
|
119
|
+
expect(setClause).toBe('title = ?')
|
|
120
|
+
expect(bindings).toHaveLength(1)
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
it('returns empty setClause and bindings for non-matching payload', () => {
|
|
124
|
+
const { setClause, bindings } = buildUpdateBindings(SEED, { ghost: 'field' })
|
|
125
|
+
expect(setClause).toBe('')
|
|
126
|
+
expect(bindings).toHaveLength(0)
|
|
127
|
+
})
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
// ─── hasDraft ─────────────────────────────────────────────────────────────────
|
|
131
|
+
|
|
132
|
+
describe('hasDraft', () => {
|
|
133
|
+
function makeMockDb(firstResult: unknown) {
|
|
134
|
+
const firstMock = vi.fn().mockResolvedValue(firstResult)
|
|
135
|
+
const bindMock = vi.fn(() => ({ first: firstMock }))
|
|
136
|
+
const prepareMock = vi.fn(() => ({ bind: bindMock }))
|
|
137
|
+
return { db: { prepare: prepareMock } as any, prepareMock, bindMock }
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
it('returns false immediately when seed does not allow drafts', async () => {
|
|
141
|
+
const { db, prepareMock } = makeMockDb(null)
|
|
142
|
+
expect(await hasDraft(db, NO_DRAFT_SEED, 'e1')).toBe(false)
|
|
143
|
+
expect(prepareMock).not.toHaveBeenCalled()
|
|
144
|
+
})
|
|
145
|
+
|
|
146
|
+
it('returns true when a draft row exists', async () => {
|
|
147
|
+
const { db } = makeMockDb({ 1: 1 })
|
|
148
|
+
expect(await hasDraft(db, SEED, 'entry-1')).toBe(true)
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
it('returns false when no draft row is found', async () => {
|
|
152
|
+
const { db } = makeMockDb(null)
|
|
153
|
+
expect(await hasDraft(db, SEED, 'entry-1')).toBe(false)
|
|
154
|
+
})
|
|
155
|
+
|
|
156
|
+
it('queries the correct drafts table for the seed slug', async () => {
|
|
157
|
+
const { db, prepareMock } = makeMockDb(null)
|
|
158
|
+
await hasDraft(db, SEED, 'entry-1')
|
|
159
|
+
expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('content_articoli_drafts'))
|
|
160
|
+
})
|
|
161
|
+
})
|
|
@@ -0,0 +1,312 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
2
|
+
import { D1ContentRepository } from './content.repository.d1'
|
|
3
|
+
import { EntryNotFoundError, SlugConflictError } from '@beechcms/core'
|
|
4
|
+
import type { Seed } from '@beechcms/core'
|
|
5
|
+
|
|
6
|
+
const SEED = {
|
|
7
|
+
slug: 'posts',
|
|
8
|
+
displayNameAlias: 'title',
|
|
9
|
+
allowDrafts: true,
|
|
10
|
+
branches: [
|
|
11
|
+
{ id: 'br_01', alias: 'title', type: 'text' },
|
|
12
|
+
{ id: 'br_02', alias: 'body', type: 'text' },
|
|
13
|
+
],
|
|
14
|
+
} as unknown as Seed
|
|
15
|
+
|
|
16
|
+
const NO_DRAFT_SEED = {
|
|
17
|
+
slug: 'produtos',
|
|
18
|
+
displayNameAlias: 'name',
|
|
19
|
+
allowDrafts: false,
|
|
20
|
+
branches: [{ id: 'br_01', alias: 'name', type: 'text' }],
|
|
21
|
+
} as unknown as Seed
|
|
22
|
+
|
|
23
|
+
function makeMockDb(opts: {
|
|
24
|
+
firstResult?: unknown
|
|
25
|
+
allResults?: unknown[]
|
|
26
|
+
runChanges?: number
|
|
27
|
+
batchResults?: unknown[]
|
|
28
|
+
} = {}) {
|
|
29
|
+
const { firstResult = null, allResults = [], runChanges = 1, batchResults = [] } = opts
|
|
30
|
+
const runMock = vi.fn().mockResolvedValue({ success: true, meta: { changes: runChanges } })
|
|
31
|
+
const firstMock = vi.fn().mockResolvedValue(firstResult)
|
|
32
|
+
const allMock = vi.fn().mockResolvedValue({ results: allResults })
|
|
33
|
+
const bindMock = vi.fn(() => ({ run: runMock, first: firstMock, all: allMock }))
|
|
34
|
+
const stmt = { bind: bindMock, run: runMock, first: firstMock, all: allMock }
|
|
35
|
+
const prepareMock = vi.fn(() => stmt)
|
|
36
|
+
const batchMock = vi.fn().mockResolvedValue(batchResults)
|
|
37
|
+
return { db: { prepare: prepareMock, batch: batchMock } as any, prepareMock, bindMock, runMock, firstMock, allMock, batchMock }
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// ─── findMany ─────────────────────────────────────────────────────────────────
|
|
41
|
+
|
|
42
|
+
describe('D1ContentRepository', () => {
|
|
43
|
+
describe('findMany', () => {
|
|
44
|
+
it('returns mapped items and total from batch results', async () => {
|
|
45
|
+
const row = { id: 'e1', slug: 'post-1', status: 'published', title: 'Hello', body: null, created_at: 1000, updated_at: 1000 }
|
|
46
|
+
const { db } = makeMockDb({
|
|
47
|
+
batchResults: [
|
|
48
|
+
{ results: [row] },
|
|
49
|
+
{ results: [{ total: 1 }] },
|
|
50
|
+
],
|
|
51
|
+
})
|
|
52
|
+
const result = await new D1ContentRepository(db).findMany(SEED, { pagination: { limit: 10, offset: 0 } })
|
|
53
|
+
expect(result.items).toHaveLength(1)
|
|
54
|
+
expect(result.items[0].id).toBe('e1')
|
|
55
|
+
expect(result.total).toBe(1)
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('returns empty items and zero total when table is empty', async () => {
|
|
59
|
+
const { db } = makeMockDb({
|
|
60
|
+
batchResults: [{ results: [] }, { results: [{ total: 0 }] }],
|
|
61
|
+
})
|
|
62
|
+
const result = await new D1ContentRepository(db).findMany(SEED, {})
|
|
63
|
+
expect(result.items).toHaveLength(0)
|
|
64
|
+
expect(result.total).toBe(0)
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
it('wraps D1 errors in RepositoryError', async () => {
|
|
68
|
+
const { db } = makeMockDb()
|
|
69
|
+
db.batch = vi.fn().mockRejectedValue(new Error('D1 error'))
|
|
70
|
+
await expect(new D1ContentRepository(db).findMany(SEED, {})).rejects.toThrow('findMany')
|
|
71
|
+
})
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
// ─── findById ───────────────────────────────────────────────────────────────
|
|
75
|
+
|
|
76
|
+
describe('findById', () => {
|
|
77
|
+
it('returns the entry when found', async () => {
|
|
78
|
+
const row = { id: 'e1', slug: 'p', status: 'draft', title: 'T', body: null, created_at: 0, updated_at: 0 }
|
|
79
|
+
const { db } = makeMockDb({ firstResult: row })
|
|
80
|
+
const result = await new D1ContentRepository(db).findById(SEED, 'e1')
|
|
81
|
+
expect(result.id).toBe('e1')
|
|
82
|
+
expect(result.title).toBe('T')
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
it('throws EntryNotFoundError when the row does not exist', async () => {
|
|
86
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
87
|
+
await expect(new D1ContentRepository(db).findById(SEED, 'missing')).rejects.toBeInstanceOf(EntryNotFoundError)
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
it('queries the correct content table', async () => {
|
|
91
|
+
const { db, prepareMock } = makeMockDb({ firstResult: { id: 'e1', slug: null, status: 'draft', title: null, body: null } })
|
|
92
|
+
await new D1ContentRepository(db).findById(SEED, 'e1')
|
|
93
|
+
expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('content_posts'))
|
|
94
|
+
})
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
// ─── findBySlug ─────────────────────────────────────────────────────────────
|
|
98
|
+
|
|
99
|
+
describe('findBySlug', () => {
|
|
100
|
+
it('returns the entry when the slug is found', async () => {
|
|
101
|
+
const row = { id: 'e1', slug: 'my-post', status: 'published', title: 'T', body: null }
|
|
102
|
+
const { db } = makeMockDb({ firstResult: row })
|
|
103
|
+
const result = await new D1ContentRepository(db).findBySlug(SEED, 'my-post')
|
|
104
|
+
expect(result.slug).toBe('my-post')
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
it('throws EntryNotFoundError when slug does not exist', async () => {
|
|
108
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
109
|
+
await expect(new D1ContentRepository(db).findBySlug(SEED, 'ghost')).rejects.toBeInstanceOf(EntryNotFoundError)
|
|
110
|
+
})
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
// ─── getFacets ───────────────────────────────────────────────────────────────
|
|
114
|
+
|
|
115
|
+
describe('getFacets', () => {
|
|
116
|
+
it('returns status counts mapped from status GROUP BY results', async () => {
|
|
117
|
+
const { db, allMock } = makeMockDb()
|
|
118
|
+
allMock.mockResolvedValueOnce({ results: [{ status: 'published', count: 3 }, { status: 'draft', count: 1 }] })
|
|
119
|
+
const result = await new D1ContentRepository(db).getFacets(SEED)
|
|
120
|
+
expect(result.statuses).toEqual({ published: 3, draft: 1 })
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
it('returns empty tagsByColumn when seed has no tag branches', async () => {
|
|
124
|
+
const { db, allMock } = makeMockDb()
|
|
125
|
+
allMock.mockResolvedValueOnce({ results: [] })
|
|
126
|
+
const result = await new D1ContentRepository(db).getFacets(SEED)
|
|
127
|
+
expect(result.tagsByColumn).toEqual({})
|
|
128
|
+
})
|
|
129
|
+
})
|
|
130
|
+
|
|
131
|
+
// ─── existsSlug ─────────────────────────────────────────────────────────────
|
|
132
|
+
|
|
133
|
+
describe('existsSlug', () => {
|
|
134
|
+
it('returns true when the slug row is found', async () => {
|
|
135
|
+
const { db } = makeMockDb({ firstResult: { 1: 1 } })
|
|
136
|
+
expect(await new D1ContentRepository(db).existsSlug(SEED, 'existing-slug')).toBe(true)
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
it('returns false when the slug row is not found', async () => {
|
|
140
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
141
|
+
expect(await new D1ContentRepository(db).existsSlug(SEED, 'new-slug')).toBe(false)
|
|
142
|
+
})
|
|
143
|
+
|
|
144
|
+
it('appends AND id != ? clause when excludeId is provided', async () => {
|
|
145
|
+
const { db, bindMock } = makeMockDb({ firstResult: null })
|
|
146
|
+
await new D1ContentRepository(db).existsSlug(SEED, 'slug', 'exclude-me')
|
|
147
|
+
expect(bindMock).toHaveBeenCalledWith('slug', 'exclude-me')
|
|
148
|
+
})
|
|
149
|
+
})
|
|
150
|
+
|
|
151
|
+
// ─── create ─────────────────────────────────────────────────────────────────
|
|
152
|
+
|
|
153
|
+
describe('create', () => {
|
|
154
|
+
it('calls INSERT INTO the content table', async () => {
|
|
155
|
+
const { db, prepareMock } = makeMockDb({ firstResult: null }) // existsSlug → null
|
|
156
|
+
await new D1ContentRepository(db).create(SEED, 'new-id', 'my-slug', 'draft', { title: 'Hello' })
|
|
157
|
+
const calls = prepareMock.mock.calls.map(c => c[0] as string)
|
|
158
|
+
expect(calls.some(sql => sql.includes('INSERT INTO content_posts'))).toBe(true)
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
it('throws SlugConflictError when the slug already exists', async () => {
|
|
162
|
+
const { db } = makeMockDb({ firstResult: { 1: 1 } }) // existsSlug → found
|
|
163
|
+
await expect(
|
|
164
|
+
new D1ContentRepository(db).create(SEED, 'id', 'taken-slug', 'draft', {}),
|
|
165
|
+
).rejects.toBeInstanceOf(SlugConflictError)
|
|
166
|
+
})
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
// ─── update ─────────────────────────────────────────────────────────────────
|
|
170
|
+
|
|
171
|
+
describe('update', () => {
|
|
172
|
+
it('calls UPDATE with provided status and branch data', async () => {
|
|
173
|
+
const { db, prepareMock, runMock } = makeMockDb({ runChanges: 1 })
|
|
174
|
+
runMock.mockResolvedValue({ success: true, meta: { changes: 1 } })
|
|
175
|
+
await new D1ContentRepository(db).update(SEED, 'e1', { title: 'New' }, 'published')
|
|
176
|
+
const calls = prepareMock.mock.calls.map(c => c[0] as string)
|
|
177
|
+
expect(calls.some(sql => sql.includes('UPDATE content_posts'))).toBe(true)
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
it('throws EntryNotFoundError when no rows are updated', async () => {
|
|
181
|
+
const { db } = makeMockDb({ runChanges: 0 })
|
|
182
|
+
await expect(new D1ContentRepository(db).update(SEED, 'ghost', { title: 'X' })).rejects.toBeInstanceOf(EntryNotFoundError)
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
it('returns early without a DB call when there is nothing to update', async () => {
|
|
186
|
+
const { db, prepareMock } = makeMockDb()
|
|
187
|
+
await new D1ContentRepository(db).update(SEED, 'e1', {}) // no data, no status
|
|
188
|
+
// existsSlug is not called; only prepare calls would be for UPDATE which shouldn't happen
|
|
189
|
+
const updateCalls = prepareMock.mock.calls.filter(c => (c[0] as string).includes('UPDATE content_posts'))
|
|
190
|
+
expect(updateCalls).toHaveLength(0)
|
|
191
|
+
})
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
// ─── delete ─────────────────────────────────────────────────────────────────
|
|
195
|
+
|
|
196
|
+
describe('delete', () => {
|
|
197
|
+
it('returns the row data and calls DELETE', async () => {
|
|
198
|
+
const row = { id: 'e1', slug: 'p', status: 'published', title: 'T', body: null }
|
|
199
|
+
const { db, prepareMock } = makeMockDb({ firstResult: row })
|
|
200
|
+
const result = await new D1ContentRepository(db).delete(SEED, 'e1')
|
|
201
|
+
expect(result.row.id).toBe('e1')
|
|
202
|
+
const sqls = prepareMock.mock.calls.map(c => c[0] as string)
|
|
203
|
+
expect(sqls.some(s => s.includes('DELETE FROM content_posts'))).toBe(true)
|
|
204
|
+
})
|
|
205
|
+
|
|
206
|
+
it('throws EntryNotFoundError when the entry does not exist', async () => {
|
|
207
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
208
|
+
await expect(new D1ContentRepository(db).delete(SEED, 'missing')).rejects.toBeInstanceOf(EntryNotFoundError)
|
|
209
|
+
})
|
|
210
|
+
})
|
|
211
|
+
|
|
212
|
+
// ─── saveDraft ───────────────────────────────────────────────────────────────
|
|
213
|
+
|
|
214
|
+
describe('saveDraft', () => {
|
|
215
|
+
it('calls INSERT OR REPLACE into the draft table', async () => {
|
|
216
|
+
const { db, prepareMock } = makeMockDb()
|
|
217
|
+
await new D1ContentRepository(db).saveDraft(SEED, 'e1', { title: 'Draft title' })
|
|
218
|
+
const sqls = prepareMock.mock.calls.map(c => c[0] as string)
|
|
219
|
+
expect(sqls.some(s => s.includes('content_posts_drafts'))).toBe(true)
|
|
220
|
+
})
|
|
221
|
+
|
|
222
|
+
it('throws RepositoryError when seed does not allow drafts', async () => {
|
|
223
|
+
const { db } = makeMockDb()
|
|
224
|
+
await expect(new D1ContentRepository(db).saveDraft(NO_DRAFT_SEED, 'e1', {})).rejects.toThrow('Drafts not allowed')
|
|
225
|
+
})
|
|
226
|
+
})
|
|
227
|
+
|
|
228
|
+
// ─── getDraft ────────────────────────────────────────────────────────────────
|
|
229
|
+
|
|
230
|
+
describe('getDraft', () => {
|
|
231
|
+
it('returns null when seed does not allow drafts', async () => {
|
|
232
|
+
const { db } = makeMockDb()
|
|
233
|
+
expect(await new D1ContentRepository(db).getDraft(NO_DRAFT_SEED, 'e1')).toBeNull()
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
it('returns null when no draft row exists', async () => {
|
|
237
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
238
|
+
expect(await new D1ContentRepository(db).getDraft(SEED, 'e1')).toBeNull()
|
|
239
|
+
})
|
|
240
|
+
|
|
241
|
+
it('returns deserialized draft data for non-null branch values', async () => {
|
|
242
|
+
const draftRow = { entry_id: 'e1', title: 'Draft T', body: null }
|
|
243
|
+
const { db } = makeMockDb({ firstResult: draftRow })
|
|
244
|
+
const result = await new D1ContentRepository(db).getDraft(SEED, 'e1')
|
|
245
|
+
expect(result).not.toBeNull()
|
|
246
|
+
expect(result!.title).toBe('Draft T')
|
|
247
|
+
expect(result).not.toHaveProperty('body') // null branch values are omitted
|
|
248
|
+
})
|
|
249
|
+
})
|
|
250
|
+
|
|
251
|
+
// ─── hasDraft ─────────────────────────────────────────────────────────────────
|
|
252
|
+
|
|
253
|
+
describe('hasDraft', () => {
|
|
254
|
+
it('returns false immediately when seed does not allow drafts', async () => {
|
|
255
|
+
const { db, prepareMock } = makeMockDb()
|
|
256
|
+
expect(await new D1ContentRepository(db).hasDraft(NO_DRAFT_SEED, 'e1')).toBe(false)
|
|
257
|
+
expect(prepareMock).not.toHaveBeenCalled()
|
|
258
|
+
})
|
|
259
|
+
|
|
260
|
+
it('returns true when a draft exists', async () => {
|
|
261
|
+
const { db } = makeMockDb({ firstResult: { 1: 1 } })
|
|
262
|
+
expect(await new D1ContentRepository(db).hasDraft(SEED, 'e1')).toBe(true)
|
|
263
|
+
})
|
|
264
|
+
|
|
265
|
+
it('returns false when no draft exists', async () => {
|
|
266
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
267
|
+
expect(await new D1ContentRepository(db).hasDraft(SEED, 'e1')).toBe(false)
|
|
268
|
+
})
|
|
269
|
+
})
|
|
270
|
+
|
|
271
|
+
// ─── publishDraft ─────────────────────────────────────────────────────────────
|
|
272
|
+
|
|
273
|
+
describe('publishDraft', () => {
|
|
274
|
+
it('returns early when seed does not allow drafts', async () => {
|
|
275
|
+
const { db, batchMock } = makeMockDb()
|
|
276
|
+
await new D1ContentRepository(db).publishDraft(NO_DRAFT_SEED, 'e1')
|
|
277
|
+
expect(batchMock).not.toHaveBeenCalled()
|
|
278
|
+
})
|
|
279
|
+
|
|
280
|
+
it('throws EntryNotFoundError when no draft exists', async () => {
|
|
281
|
+
const { db } = makeMockDb({ firstResult: null })
|
|
282
|
+
await expect(new D1ContentRepository(db).publishDraft(SEED, 'e1')).rejects.toBeInstanceOf(EntryNotFoundError)
|
|
283
|
+
})
|
|
284
|
+
|
|
285
|
+
it('calls batch with UPDATE and DELETE statements when draft exists', async () => {
|
|
286
|
+
const draftRow = { entry_id: 'e1', title: 'Draft', body: null }
|
|
287
|
+
const { db, batchMock, firstMock } = makeMockDb()
|
|
288
|
+
firstMock.mockResolvedValueOnce(draftRow)
|
|
289
|
+
batchMock.mockResolvedValueOnce([{}, {}])
|
|
290
|
+
await new D1ContentRepository(db).publishDraft(SEED, 'e1')
|
|
291
|
+
expect(batchMock).toHaveBeenCalledTimes(1)
|
|
292
|
+
const batchArgs: any[] = batchMock.mock.calls[0][0]
|
|
293
|
+
expect(batchArgs).toHaveLength(2)
|
|
294
|
+
})
|
|
295
|
+
})
|
|
296
|
+
|
|
297
|
+
// ─── deleteDraft ─────────────────────────────────────────────────────────────
|
|
298
|
+
|
|
299
|
+
describe('deleteDraft', () => {
|
|
300
|
+
it('returns early when seed does not allow drafts', async () => {
|
|
301
|
+
const { db, prepareMock } = makeMockDb()
|
|
302
|
+
await new D1ContentRepository(db).deleteDraft(NO_DRAFT_SEED, 'e1')
|
|
303
|
+
expect(prepareMock).not.toHaveBeenCalled()
|
|
304
|
+
})
|
|
305
|
+
|
|
306
|
+
it('calls DELETE on the draft table when drafts are allowed', async () => {
|
|
307
|
+
const { db, prepareMock } = makeMockDb()
|
|
308
|
+
await new D1ContentRepository(db).deleteDraft(SEED, 'e1')
|
|
309
|
+
expect(prepareMock).toHaveBeenCalledWith(expect.stringContaining('content_posts_drafts'))
|
|
310
|
+
})
|
|
311
|
+
})
|
|
312
|
+
})
|