@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,192 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
2
|
+
import { AutomationRunner } from '../automation-runner'
|
|
3
|
+
import type { AutomationRunnerDeps } from '../automation-runner'
|
|
4
|
+
import type { IAutomationRepository, ContentRepository, Seed, IIdGenerator, Automation } from '@beechcms/core'
|
|
5
|
+
import { resolveVarAccess } from '../var-access-resolver'
|
|
6
|
+
import { parseTemplateKey } from '../template-grammar'
|
|
7
|
+
|
|
8
|
+
function makeAutomation(overrides: Partial<Automation> = {}): Automation {
|
|
9
|
+
return {
|
|
10
|
+
id: 'auto-1',
|
|
11
|
+
seed_slug: 'posts',
|
|
12
|
+
name: 'Test Automation',
|
|
13
|
+
enabled: true,
|
|
14
|
+
triggers: [{ event: 'create' as const }],
|
|
15
|
+
trigger_conditions: null,
|
|
16
|
+
actions: [],
|
|
17
|
+
created_at: 0,
|
|
18
|
+
updated_at: 0,
|
|
19
|
+
...overrides,
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function makeDeps(overrides: Partial<AutomationRunnerDeps> = {}): AutomationRunnerDeps {
|
|
24
|
+
return {
|
|
25
|
+
automationRepository: {
|
|
26
|
+
findActive: vi.fn().mockResolvedValue([]),
|
|
27
|
+
} as unknown as IAutomationRepository,
|
|
28
|
+
contentRepository: {} as ContentRepository,
|
|
29
|
+
getSeed: vi.fn().mockReturnValue({ slug: 'posts', branches: [] } as unknown as Seed),
|
|
30
|
+
idGenerator: { uuid: vi.fn().mockReturnValue('new-id') } as unknown as IIdGenerator,
|
|
31
|
+
env: {},
|
|
32
|
+
...overrides,
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
describe('AutomationRunner', () => {
|
|
37
|
+
beforeEach(() => { vi.restoreAllMocks() })
|
|
38
|
+
|
|
39
|
+
it('does nothing when no automations match', async () => {
|
|
40
|
+
const deps = makeDeps()
|
|
41
|
+
const runner = new AutomationRunner(deps)
|
|
42
|
+
await runner.run({ seedSlug: 'posts', event: 'create', entry: { id: '1' } })
|
|
43
|
+
expect(deps.automationRepository.findActive).toHaveBeenCalledWith('posts', 'create')
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it('does nothing when getSeed returns null', async () => {
|
|
47
|
+
const deps = makeDeps({ getSeed: vi.fn().mockReturnValue(null) })
|
|
48
|
+
const runner = new AutomationRunner(deps)
|
|
49
|
+
await runner.run({ seedSlug: 'unknown', event: 'create', entry: { id: '1' } })
|
|
50
|
+
expect(deps.automationRepository.findActive).not.toHaveBeenCalled()
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('skips actions when trigger conditions are not met', async () => {
|
|
54
|
+
const automation = makeAutomation({
|
|
55
|
+
trigger_conditions: {
|
|
56
|
+
kind: 'group',
|
|
57
|
+
op: 'AND',
|
|
58
|
+
children: [{ kind: 'predicate', left: { kind: 'ref', key: 'this.status' }, op: 'eq', right: { kind: 'literal', value: 'published' } }],
|
|
59
|
+
},
|
|
60
|
+
actions: [{ type: 'webhook', url: 'https://example.com' }],
|
|
61
|
+
})
|
|
62
|
+
const fetchMock = vi.fn().mockResolvedValue({ ok: true })
|
|
63
|
+
vi.stubGlobal('fetch', fetchMock)
|
|
64
|
+
|
|
65
|
+
const deps = makeDeps({
|
|
66
|
+
automationRepository: {
|
|
67
|
+
findActive: vi.fn().mockResolvedValue([automation]),
|
|
68
|
+
} as unknown as IAutomationRepository,
|
|
69
|
+
})
|
|
70
|
+
const runner = new AutomationRunner(deps)
|
|
71
|
+
await runner.run({ seedSlug: 'posts', event: 'create', entry: { id: '1', status: 'draft' } })
|
|
72
|
+
|
|
73
|
+
expect(fetchMock).not.toHaveBeenCalled()
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
it('continues to next action when first action throws', async () => {
|
|
77
|
+
const secondActionFetch = vi.fn().mockResolvedValue({ ok: true })
|
|
78
|
+
vi.stubGlobal('fetch', vi.fn()
|
|
79
|
+
.mockRejectedValueOnce(new Error('network error'))
|
|
80
|
+
.mockResolvedValue({ ok: true }),
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
const automation = makeAutomation({
|
|
84
|
+
actions: [
|
|
85
|
+
{ type: 'webhook', url: 'https://fail.example.com' },
|
|
86
|
+
{ type: 'webhook', url: 'https://success.example.com' },
|
|
87
|
+
],
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
|
|
91
|
+
|
|
92
|
+
const deps = makeDeps({
|
|
93
|
+
automationRepository: {
|
|
94
|
+
findActive: vi.fn().mockResolvedValue([automation]),
|
|
95
|
+
} as unknown as IAutomationRepository,
|
|
96
|
+
})
|
|
97
|
+
const runner = new AutomationRunner(deps)
|
|
98
|
+
await runner.run({ seedSlug: 'posts', event: 'create', entry: { id: '1', status: 'published' } })
|
|
99
|
+
|
|
100
|
+
expect(consoleSpy).toHaveBeenCalledWith('[automations] action failed', expect.objectContaining({
|
|
101
|
+
automationId: 'auto-1',
|
|
102
|
+
actionType: 'webhook',
|
|
103
|
+
}))
|
|
104
|
+
|
|
105
|
+
// fetch was called twice (first failed, second succeeded)
|
|
106
|
+
const fetchCalls = (global.fetch as ReturnType<typeof vi.fn>).mock.calls
|
|
107
|
+
expect(fetchCalls).toHaveLength(2)
|
|
108
|
+
expect(fetchCalls[1][0]).toBe('https://success.example.com')
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
it('runs actions when conditions pass', async () => {
|
|
112
|
+
const fetchMock = vi.fn().mockResolvedValue({ ok: true })
|
|
113
|
+
vi.stubGlobal('fetch', fetchMock)
|
|
114
|
+
|
|
115
|
+
const automation = makeAutomation({
|
|
116
|
+
trigger_conditions: {
|
|
117
|
+
kind: 'group',
|
|
118
|
+
op: 'AND',
|
|
119
|
+
children: [{ kind: 'predicate', left: { kind: 'ref', key: 'this.status' }, op: 'eq', right: { kind: 'literal', value: 'published' } }],
|
|
120
|
+
},
|
|
121
|
+
actions: [{ type: 'webhook', url: 'https://example.com/hook' }],
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
const deps = makeDeps({
|
|
125
|
+
automationRepository: {
|
|
126
|
+
findActive: vi.fn().mockResolvedValue([automation]),
|
|
127
|
+
} as unknown as IAutomationRepository,
|
|
128
|
+
})
|
|
129
|
+
const runner = new AutomationRunner(deps)
|
|
130
|
+
await runner.run({ seedSlug: 'posts', event: 'create', entry: { id: '1', status: 'published' } })
|
|
131
|
+
|
|
132
|
+
expect(fetchMock).toHaveBeenCalledOnce()
|
|
133
|
+
expect(fetchMock.mock.calls[0][0]).toBe('https://example.com/hook')
|
|
134
|
+
})
|
|
135
|
+
})
|
|
136
|
+
|
|
137
|
+
// ── Sprint 07: resolveVarAccess unit tests ─────────────────────────────────────
|
|
138
|
+
|
|
139
|
+
describe('resolveVarAccess (Sprint 07)', () => {
|
|
140
|
+
function makeCollectionVar(items: Array<Record<string, unknown>>) {
|
|
141
|
+
const out: Record<string, unknown> = {
|
|
142
|
+
count: items.length,
|
|
143
|
+
firstone: items[0] ?? null,
|
|
144
|
+
lastone: items[items.length - 1] ?? null,
|
|
145
|
+
sum: {},
|
|
146
|
+
avg: {},
|
|
147
|
+
min: {},
|
|
148
|
+
max: {},
|
|
149
|
+
pluck: {},
|
|
150
|
+
}
|
|
151
|
+
Object.defineProperty(out, '_items', { value: items, enumerable: false })
|
|
152
|
+
return out
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const items = [
|
|
156
|
+
{ id: 'a', status: 'paid', amount: 100, created_at: 1 },
|
|
157
|
+
{ id: 'b', status: 'draft', amount: 50, created_at: 2 },
|
|
158
|
+
{ id: 'c', status: 'paid', amount: 200, created_at: 3 },
|
|
159
|
+
]
|
|
160
|
+
|
|
161
|
+
it('array[id] selector filters _items and rebuilds collection', () => {
|
|
162
|
+
const variables = { ordini: makeCollectionVar(items) }
|
|
163
|
+
const parsed = parseTemplateKey('ordini.array[a,c].count')!
|
|
164
|
+
expect(parsed.kind).toBe('var_access')
|
|
165
|
+
const result = resolveVarAccess(parsed as any, variables)
|
|
166
|
+
expect(result).toBe(2)
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
it('inline condition (status=paid) reduces count', () => {
|
|
170
|
+
const variables = { ordini: makeCollectionVar(items) }
|
|
171
|
+
const parsed = parseTemplateKey('ordini.count.(status=paid)')!
|
|
172
|
+
const result = resolveVarAccess(parsed as any, variables)
|
|
173
|
+
expect(result).toBe(2)
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
it('conditions on firstone.id return undefined when record fails predicate', () => {
|
|
177
|
+
const variables = { ordini: makeCollectionVar(items) }
|
|
178
|
+
// firstone is items[0] which has status=paid, so (status=draft) should fail
|
|
179
|
+
const parsed = parseTemplateKey('ordini.firstone.status.(status=draft)')!
|
|
180
|
+
const result = resolveVarAccess(parsed as any, variables)
|
|
181
|
+
// firstone.status = 'paid', condition says status=draft → undefined
|
|
182
|
+
expect(result).toBeUndefined()
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
it('returns undefined when variable is missing and calls onMissing', () => {
|
|
186
|
+
const onMissing = vi.fn()
|
|
187
|
+
const parsed = parseTemplateKey('missing.count.(status=paid)')!
|
|
188
|
+
const result = resolveVarAccess(parsed as any, {}, onMissing)
|
|
189
|
+
expect(result).toBeUndefined()
|
|
190
|
+
expect(onMissing).toHaveBeenCalledWith('missing')
|
|
191
|
+
})
|
|
192
|
+
})
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest'
|
|
2
|
+
import { interpolate } from '../automation-runner.utils'
|
|
3
|
+
import { resolveAutomationContext } from '../context-resolver'
|
|
4
|
+
|
|
5
|
+
async function makeCtx(entry: Record<string, unknown>) {
|
|
6
|
+
return resolveAutomationContext({} as any, entry, [entry])
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
describe('interpolate', () => {
|
|
10
|
+
it('replaces a single placeholder', async () => {
|
|
11
|
+
expect(interpolate('Hello {{name}}!', await makeCtx({ name: 'World' }))).toBe('Hello World!')
|
|
12
|
+
})
|
|
13
|
+
|
|
14
|
+
it('replaces multiple placeholders', async () => {
|
|
15
|
+
expect(interpolate('{{name}} is {{status}}', await makeCtx({ name: 'Alice', status: 'active' }))).toBe('Alice is active')
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
it('missing field becomes empty string by default', async () => {
|
|
19
|
+
expect(interpolate('Hello {{name}}!', await makeCtx({}))).toBe('Hello !')
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('no placeholders returns template unchanged', async () => {
|
|
23
|
+
expect(interpolate('No placeholders here', await makeCtx({ name: 'World' }))).toBe('No placeholders here')
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
it('handles numeric values', async () => {
|
|
27
|
+
expect(interpolate('Count: {{count}}', await makeCtx({ count: 42 }))).toBe('Count: 42')
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('supports spaces inside double braces', async () => {
|
|
31
|
+
expect(interpolate('Hello {{ name }}!', await makeCtx({ name: 'DoubleSpace' }))).toBe('Hello DoubleSpace!')
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('uses custom default value when a field is missing', async () => {
|
|
35
|
+
expect(interpolate('Hello {{name}}!', await makeCtx({}), '[missing]')).toBe('Hello [missing]!')
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('triggers onMissing callback when field is absent', async () => {
|
|
39
|
+
const missing: string[] = []
|
|
40
|
+
const res = interpolate('Hello {{name}}! From {{city}}', await makeCtx({}), '[mancante]', (f) => missing.push(f))
|
|
41
|
+
expect(res).toBe('Hello [mancante]! From [mancante]')
|
|
42
|
+
expect(missing).toEqual(['name', 'city'])
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('returns empty string when template is falsy', async () => {
|
|
46
|
+
expect(interpolate('' as any, await makeCtx({}))).toBe('')
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
it('resolves {{this.field}} dot notation against the trigger entry', async () => {
|
|
50
|
+
expect(interpolate('{{this.customer_id}}', await makeCtx({ customer_id: 'cust-42' }))).toBe('cust-42')
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
it('resolves {{this:field}} colon notation against the trigger entry', async () => {
|
|
54
|
+
expect(interpolate('{{this:customer_id}}', await makeCtx({ customer_id: 'cust-42' }))).toBe('cust-42')
|
|
55
|
+
})
|
|
56
|
+
})
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
|
2
|
+
import { Hono } from 'hono'
|
|
3
|
+
import type { IAutomationRepository, Automation } from '@beechcms/core'
|
|
4
|
+
import { automationsApp } from '../automations.handler'
|
|
5
|
+
|
|
6
|
+
const baseAutomation: Automation = {
|
|
7
|
+
id: 'test-id',
|
|
8
|
+
seed_slug: 'posts',
|
|
9
|
+
name: 'test',
|
|
10
|
+
enabled: true,
|
|
11
|
+
triggers: [{ event: 'create' }],
|
|
12
|
+
trigger_conditions: null,
|
|
13
|
+
actions: [{ type: 'webhook', url: 'https://example.com' }],
|
|
14
|
+
created_at: 1000,
|
|
15
|
+
updated_at: 1000,
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function makeStub(overrides: Partial<IAutomationRepository> = {}): IAutomationRepository {
|
|
19
|
+
return {
|
|
20
|
+
list: vi.fn().mockResolvedValue([baseAutomation]),
|
|
21
|
+
findById: vi.fn().mockResolvedValue(baseAutomation),
|
|
22
|
+
findActive: vi.fn().mockResolvedValue([]),
|
|
23
|
+
create: vi.fn().mockResolvedValue('new-id'),
|
|
24
|
+
update: vi.fn().mockResolvedValue(undefined),
|
|
25
|
+
toggle: vi.fn().mockResolvedValue(undefined),
|
|
26
|
+
delete: vi.fn().mockResolvedValue(undefined),
|
|
27
|
+
...overrides,
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function buildApp(stub: IAutomationRepository) {
|
|
32
|
+
const app = new Hono()
|
|
33
|
+
app.use('*', async (c, next) => {
|
|
34
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
35
|
+
;(c as any).set('automationRepository', stub)
|
|
36
|
+
await next()
|
|
37
|
+
})
|
|
38
|
+
app.route('/', automationsApp)
|
|
39
|
+
return app
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
describe('GET /', () => {
|
|
43
|
+
it('returns 400 missing-seed without ?seed=', async () => {
|
|
44
|
+
const app = buildApp(makeStub())
|
|
45
|
+
const res = await app.request('/')
|
|
46
|
+
expect(res.status).toBe(400)
|
|
47
|
+
const body = await res.json() as { type: string }
|
|
48
|
+
expect(body.type).toContain('missing-seed')
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('returns 200 with automations list', async () => {
|
|
52
|
+
const app = buildApp(makeStub())
|
|
53
|
+
const res = await app.request('/?seed=posts')
|
|
54
|
+
expect(res.status).toBe(200)
|
|
55
|
+
const body = await res.json() as Automation[]
|
|
56
|
+
expect(body).toHaveLength(1)
|
|
57
|
+
expect(body[0].id).toBe('test-id')
|
|
58
|
+
})
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
describe('POST /', () => {
|
|
62
|
+
it('returns 400 invalid-json for malformed JSON body', async () => {
|
|
63
|
+
const app = buildApp(makeStub())
|
|
64
|
+
const res = await app.request('/', {
|
|
65
|
+
method: 'POST',
|
|
66
|
+
headers: { 'Content-Type': 'application/json' },
|
|
67
|
+
body: 'malformed-not-json',
|
|
68
|
+
})
|
|
69
|
+
expect(res.status).toBe(400)
|
|
70
|
+
const body = await res.json() as { type: string }
|
|
71
|
+
expect(body.type).toContain('invalid-json')
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it('returns 400 automation-validation-failed for schema non-compliant body', async () => {
|
|
75
|
+
const app = buildApp(makeStub())
|
|
76
|
+
const res = await app.request('/', {
|
|
77
|
+
method: 'POST',
|
|
78
|
+
headers: { 'Content-Type': 'application/json' },
|
|
79
|
+
body: JSON.stringify({ seed_slug: 'posts' }), // missing name, triggers, actions
|
|
80
|
+
})
|
|
81
|
+
expect(res.status).toBe(400)
|
|
82
|
+
const body = await res.json() as { type: string }
|
|
83
|
+
expect(body.type).toContain('automation-validation-failed')
|
|
84
|
+
})
|
|
85
|
+
|
|
86
|
+
it('returns 201 with id for valid body including optional trigger fields', async () => {
|
|
87
|
+
const app = buildApp(makeStub())
|
|
88
|
+
const res = await app.request('/', {
|
|
89
|
+
method: 'POST',
|
|
90
|
+
headers: { 'Content-Type': 'application/json' },
|
|
91
|
+
body: JSON.stringify({
|
|
92
|
+
seed_slug: 'posts',
|
|
93
|
+
name: 'test-cron-automation',
|
|
94
|
+
triggers: [{ event: 'cron', cron: '0 0 * * *' }],
|
|
95
|
+
trigger_conditions: {
|
|
96
|
+
kind: 'group',
|
|
97
|
+
op: 'AND',
|
|
98
|
+
children: [
|
|
99
|
+
{ kind: 'predicate', left: { kind: 'ref', key: 'this.status' }, op: 'eq', right: { kind: 'literal', value: 'draft' } },
|
|
100
|
+
],
|
|
101
|
+
},
|
|
102
|
+
actions: [{ type: 'webhook', url: 'https://example.com' }],
|
|
103
|
+
}),
|
|
104
|
+
})
|
|
105
|
+
expect(res.status).toBe(201)
|
|
106
|
+
const body = await res.json() as { id: string }
|
|
107
|
+
expect(body.id).toBe('new-id')
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
it('returns 201 with id for valid body omitting optional trigger fields', async () => {
|
|
111
|
+
const app = buildApp(makeStub())
|
|
112
|
+
const res = await app.request('/', {
|
|
113
|
+
method: 'POST',
|
|
114
|
+
headers: { 'Content-Type': 'application/json' },
|
|
115
|
+
body: JSON.stringify({
|
|
116
|
+
seed_slug: 'posts',
|
|
117
|
+
name: 'test-create-automation',
|
|
118
|
+
triggers: [{ event: 'create' }],
|
|
119
|
+
actions: [{ type: 'webhook', url: 'https://example.com' }],
|
|
120
|
+
}),
|
|
121
|
+
})
|
|
122
|
+
expect(res.status).toBe(201)
|
|
123
|
+
const body = await res.json() as { id: string }
|
|
124
|
+
expect(body.id).toBe('new-id')
|
|
125
|
+
})
|
|
126
|
+
})
|
|
127
|
+
|
|
128
|
+
describe('GET /:id', () => {
|
|
129
|
+
it('returns 404 when not found', async () => {
|
|
130
|
+
const app = buildApp(makeStub({ findById: vi.fn().mockResolvedValue(null) }))
|
|
131
|
+
const res = await app.request('/unknown-id')
|
|
132
|
+
expect(res.status).toBe(404)
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
it('returns 200 with automation', async () => {
|
|
136
|
+
const app = buildApp(makeStub())
|
|
137
|
+
const res = await app.request('/test-id')
|
|
138
|
+
expect(res.status).toBe(200)
|
|
139
|
+
})
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
describe('PUT /:id', () => {
|
|
143
|
+
it('returns 404 when not found', async () => {
|
|
144
|
+
const app = buildApp(makeStub({ findById: vi.fn().mockResolvedValue(null) }))
|
|
145
|
+
const res = await app.request('/unknown-id', {
|
|
146
|
+
method: 'PUT',
|
|
147
|
+
headers: { 'Content-Type': 'application/json' },
|
|
148
|
+
body: JSON.stringify({ name: 'renamed' }),
|
|
149
|
+
})
|
|
150
|
+
expect(res.status).toBe(404)
|
|
151
|
+
})
|
|
152
|
+
|
|
153
|
+
it('returns 400 invalid-json for malformed JSON body', async () => {
|
|
154
|
+
const app = buildApp(makeStub())
|
|
155
|
+
const res = await app.request('/test-id', {
|
|
156
|
+
method: 'PUT',
|
|
157
|
+
headers: { 'Content-Type': 'application/json' },
|
|
158
|
+
body: 'malformed-not-json',
|
|
159
|
+
})
|
|
160
|
+
expect(res.status).toBe(400)
|
|
161
|
+
const body = await res.json() as { type: string }
|
|
162
|
+
expect(body.type).toContain('invalid-json')
|
|
163
|
+
})
|
|
164
|
+
|
|
165
|
+
it('returns 400 automation-validation-failed for invalid update values', async () => {
|
|
166
|
+
const app = buildApp(makeStub())
|
|
167
|
+
const res = await app.request('/test-id', {
|
|
168
|
+
method: 'PUT',
|
|
169
|
+
headers: { 'Content-Type': 'application/json' },
|
|
170
|
+
body: JSON.stringify({ name: 12345 }), // name must be string
|
|
171
|
+
})
|
|
172
|
+
expect(res.status).toBe(400)
|
|
173
|
+
const body = await res.json() as { type: string }
|
|
174
|
+
expect(body.type).toContain('automation-validation-failed')
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
it('returns 400 when cron trigger has no cron expression', async () => {
|
|
178
|
+
const app = buildApp(makeStub())
|
|
179
|
+
const res = await app.request('/test-id', {
|
|
180
|
+
method: 'PUT',
|
|
181
|
+
headers: { 'Content-Type': 'application/json' },
|
|
182
|
+
body: JSON.stringify({ triggers: [{ event: 'cron' }] }),
|
|
183
|
+
})
|
|
184
|
+
expect(res.status).toBe(400)
|
|
185
|
+
const body = await res.json() as { type: string }
|
|
186
|
+
expect(body.type).toContain('automation-validation-failed')
|
|
187
|
+
})
|
|
188
|
+
|
|
189
|
+
it('returns 204 for valid update', async () => {
|
|
190
|
+
const app = buildApp(makeStub())
|
|
191
|
+
const res = await app.request('/test-id', {
|
|
192
|
+
method: 'PUT',
|
|
193
|
+
headers: { 'Content-Type': 'application/json' },
|
|
194
|
+
body: JSON.stringify({ name: 'renamed' }),
|
|
195
|
+
})
|
|
196
|
+
expect(res.status).toBe(204)
|
|
197
|
+
})
|
|
198
|
+
})
|
|
199
|
+
|
|
200
|
+
describe('PATCH /:id/toggle', () => {
|
|
201
|
+
it('returns 404 when automation not found', async () => {
|
|
202
|
+
const app = buildApp(makeStub({ findById: vi.fn().mockResolvedValue(null) }))
|
|
203
|
+
const res = await app.request('/unknown-id/toggle', {
|
|
204
|
+
method: 'PATCH',
|
|
205
|
+
headers: { 'Content-Type': 'application/json' },
|
|
206
|
+
body: JSON.stringify({ enabled: false }),
|
|
207
|
+
})
|
|
208
|
+
expect(res.status).toBe(404)
|
|
209
|
+
})
|
|
210
|
+
|
|
211
|
+
it('returns 400 invalid-json for malformed JSON body', async () => {
|
|
212
|
+
const app = buildApp(makeStub())
|
|
213
|
+
const res = await app.request('/test-id/toggle', {
|
|
214
|
+
method: 'PATCH',
|
|
215
|
+
headers: { 'Content-Type': 'application/json' },
|
|
216
|
+
body: 'malformed-not-json',
|
|
217
|
+
})
|
|
218
|
+
expect(res.status).toBe(400)
|
|
219
|
+
const body = await res.json() as { type: string }
|
|
220
|
+
expect(body.type).toContain('invalid-json')
|
|
221
|
+
})
|
|
222
|
+
|
|
223
|
+
it('returns 400 automation-validation-failed for invalid payload', async () => {
|
|
224
|
+
const app = buildApp(makeStub())
|
|
225
|
+
const res = await app.request('/test-id/toggle', {
|
|
226
|
+
method: 'PATCH',
|
|
227
|
+
headers: { 'Content-Type': 'application/json' },
|
|
228
|
+
body: JSON.stringify({ enabled: 'not-a-boolean' }),
|
|
229
|
+
})
|
|
230
|
+
expect(res.status).toBe(400)
|
|
231
|
+
const body = await res.json() as { type: string }
|
|
232
|
+
expect(body.type).toContain('automation-validation-failed')
|
|
233
|
+
})
|
|
234
|
+
|
|
235
|
+
it('returns 204 and calls toggle(id, false)', async () => {
|
|
236
|
+
const stub = makeStub()
|
|
237
|
+
const app = buildApp(stub)
|
|
238
|
+
const res = await app.request('/test-id/toggle', {
|
|
239
|
+
method: 'PATCH',
|
|
240
|
+
headers: { 'Content-Type': 'application/json' },
|
|
241
|
+
body: JSON.stringify({ enabled: false }),
|
|
242
|
+
})
|
|
243
|
+
expect(res.status).toBe(204)
|
|
244
|
+
expect(stub.toggle).toHaveBeenCalledWith('test-id', false)
|
|
245
|
+
})
|
|
246
|
+
})
|
|
247
|
+
|
|
248
|
+
describe('DELETE /:id', () => {
|
|
249
|
+
it('returns 404 when not found', async () => {
|
|
250
|
+
const app = buildApp(makeStub({ findById: vi.fn().mockResolvedValue(null) }))
|
|
251
|
+
const res = await app.request('/unknown-id', { method: 'DELETE' })
|
|
252
|
+
expect(res.status).toBe(404)
|
|
253
|
+
})
|
|
254
|
+
|
|
255
|
+
it('returns 204 on success', async () => {
|
|
256
|
+
const app = buildApp(makeStub())
|
|
257
|
+
const res = await app.request('/test-id', { method: 'DELETE' })
|
|
258
|
+
expect(res.status).toBe(204)
|
|
259
|
+
})
|
|
260
|
+
})
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { describe, it, expect, vi } from 'vitest'
|
|
2
|
+
import { D1AutomationRepository } from '../../../shared/automations.repository.d1'
|
|
3
|
+
|
|
4
|
+
function makeDb() {
|
|
5
|
+
const calls: { sql: string; bindings: unknown[] }[] = []
|
|
6
|
+
let nextAllResult: unknown[] = []
|
|
7
|
+
let nextFirstResult: unknown = null
|
|
8
|
+
|
|
9
|
+
const db = {
|
|
10
|
+
_calls: calls,
|
|
11
|
+
_setAllResult(rows: unknown[]) { nextAllResult = rows },
|
|
12
|
+
_setFirstResult(row: unknown) { nextFirstResult = row },
|
|
13
|
+
prepare(sql: string) {
|
|
14
|
+
let boundValues: unknown[] = []
|
|
15
|
+
const stmt = {
|
|
16
|
+
bind(...args: unknown[]) { boundValues = args; return stmt },
|
|
17
|
+
async run() {
|
|
18
|
+
calls.push({ sql, bindings: boundValues })
|
|
19
|
+
return { success: true }
|
|
20
|
+
},
|
|
21
|
+
async all() {
|
|
22
|
+
calls.push({ sql, bindings: boundValues })
|
|
23
|
+
return { results: nextAllResult }
|
|
24
|
+
},
|
|
25
|
+
async first() {
|
|
26
|
+
calls.push({ sql, bindings: boundValues })
|
|
27
|
+
return nextFirstResult
|
|
28
|
+
},
|
|
29
|
+
}
|
|
30
|
+
return stmt
|
|
31
|
+
},
|
|
32
|
+
}
|
|
33
|
+
return db as unknown as D1Database & typeof db
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const fixtureRow = {
|
|
37
|
+
id: 'abc',
|
|
38
|
+
seed_slug: 'posts',
|
|
39
|
+
name: 'test',
|
|
40
|
+
enabled: 1,
|
|
41
|
+
triggers: JSON.stringify([{ event: 'create' }]),
|
|
42
|
+
trigger_conditions: null,
|
|
43
|
+
actions: JSON.stringify([{ type: 'webhook', url: 'https://example.com' }]),
|
|
44
|
+
created_at: 1000,
|
|
45
|
+
updated_at: 1000,
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
describe('D1AutomationRepository.create', () => {
|
|
49
|
+
it('serialises actions and trigger_conditions to JSON', async () => {
|
|
50
|
+
const db = makeDb()
|
|
51
|
+
const repo = new D1AutomationRepository(db)
|
|
52
|
+
const whenNode = {
|
|
53
|
+
kind: 'group' as const,
|
|
54
|
+
op: 'AND' as const,
|
|
55
|
+
children: [{ kind: 'predicate' as const, left: { kind: 'ref' as const, key: 'this.status' }, op: 'eq' as const, right: { kind: 'literal' as const, value: 'published' } }],
|
|
56
|
+
}
|
|
57
|
+
await repo.create({
|
|
58
|
+
seed_slug: 'posts',
|
|
59
|
+
name: 'test',
|
|
60
|
+
triggers: [{ event: 'create' }],
|
|
61
|
+
trigger_conditions: whenNode,
|
|
62
|
+
actions: [{ type: 'webhook', url: 'https://example.com' }],
|
|
63
|
+
})
|
|
64
|
+
expect(db._calls).toHaveLength(1)
|
|
65
|
+
const { bindings } = db._calls[0]
|
|
66
|
+
// triggers is index 3, trigger_conditions is index 4, actions is index 5
|
|
67
|
+
expect(typeof bindings[3]).toBe('string')
|
|
68
|
+
expect(JSON.parse(bindings[3] as string)).toEqual([{ event: 'create' }])
|
|
69
|
+
expect(typeof bindings[4]).toBe('string')
|
|
70
|
+
expect(JSON.parse(bindings[4] as string)).toEqual(whenNode)
|
|
71
|
+
expect(typeof bindings[5]).toBe('string')
|
|
72
|
+
expect(JSON.parse(bindings[5] as string)).toEqual([{ type: 'webhook', url: 'https://example.com' }])
|
|
73
|
+
})
|
|
74
|
+
|
|
75
|
+
it('stores null for missing trigger_conditions', async () => {
|
|
76
|
+
const db = makeDb()
|
|
77
|
+
const repo = new D1AutomationRepository(db)
|
|
78
|
+
await repo.create({
|
|
79
|
+
seed_slug: 'posts',
|
|
80
|
+
name: 'test',
|
|
81
|
+
triggers: [{ event: 'create' }],
|
|
82
|
+
trigger_conditions: null,
|
|
83
|
+
actions: [{ type: 'webhook', url: 'https://example.com' }],
|
|
84
|
+
})
|
|
85
|
+
const { bindings } = db._calls[0]
|
|
86
|
+
expect(bindings[4]).toBeNull()
|
|
87
|
+
})
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
describe('D1AutomationRepository.update', () => {
|
|
91
|
+
it('builds SET clause only from provided keys', async () => {
|
|
92
|
+
const db = makeDb()
|
|
93
|
+
const repo = new D1AutomationRepository(db)
|
|
94
|
+
await repo.update('abc', { name: 'renamed' })
|
|
95
|
+
expect(db._calls).toHaveLength(1)
|
|
96
|
+
expect(db._calls[0].sql).toContain('name = ?')
|
|
97
|
+
expect(db._calls[0].sql).not.toContain('seed_slug')
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
it('short-circuits when no fields provided', async () => {
|
|
101
|
+
const db = makeDb()
|
|
102
|
+
const repo = new D1AutomationRepository(db)
|
|
103
|
+
await repo.update('abc', {})
|
|
104
|
+
expect(db._calls).toHaveLength(0)
|
|
105
|
+
})
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
describe('D1AutomationRepository.toggle', () => {
|
|
109
|
+
it('only writes enabled and updated_at', async () => {
|
|
110
|
+
const db = makeDb()
|
|
111
|
+
const repo = new D1AutomationRepository(db)
|
|
112
|
+
await repo.toggle('abc', false)
|
|
113
|
+
expect(db._calls).toHaveLength(1)
|
|
114
|
+
const { sql, bindings } = db._calls[0]
|
|
115
|
+
expect(sql).toBe('UPDATE automations SET enabled = ?, updated_at = ? WHERE id = ?')
|
|
116
|
+
expect(bindings[0]).toBe(0)
|
|
117
|
+
expect(bindings[2]).toBe('abc')
|
|
118
|
+
})
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
describe('rowToAutomation JSON round-trip', () => {
|
|
122
|
+
it('deserialises trigger_conditions as null when column is null', async () => {
|
|
123
|
+
const db = makeDb()
|
|
124
|
+
db._setAllResult([fixtureRow])
|
|
125
|
+
const repo = new D1AutomationRepository(db)
|
|
126
|
+
const rows = await repo.list('posts')
|
|
127
|
+
expect(rows[0].trigger_conditions).toBeNull()
|
|
128
|
+
})
|
|
129
|
+
|
|
130
|
+
it('deserialises trigger_conditions as WhenNode when column contains WhenNode JSON', async () => {
|
|
131
|
+
const db = makeDb()
|
|
132
|
+
const whenNode = {
|
|
133
|
+
kind: 'group',
|
|
134
|
+
op: 'AND',
|
|
135
|
+
children: [{
|
|
136
|
+
kind: 'predicate',
|
|
137
|
+
left: { kind: 'ref', key: 'this.status' },
|
|
138
|
+
op: 'eq',
|
|
139
|
+
right: { kind: 'literal', value: 'published' },
|
|
140
|
+
}],
|
|
141
|
+
}
|
|
142
|
+
const rowWithConditions = {
|
|
143
|
+
...fixtureRow,
|
|
144
|
+
trigger_conditions: JSON.stringify(whenNode),
|
|
145
|
+
}
|
|
146
|
+
db._setAllResult([rowWithConditions])
|
|
147
|
+
const repo = new D1AutomationRepository(db)
|
|
148
|
+
const rows = await repo.list('posts')
|
|
149
|
+
expect(rows[0].trigger_conditions).toEqual(whenNode)
|
|
150
|
+
})
|
|
151
|
+
|
|
152
|
+
it('deserialises actions as parsed array', async () => {
|
|
153
|
+
const db = makeDb()
|
|
154
|
+
db._setAllResult([fixtureRow])
|
|
155
|
+
const repo = new D1AutomationRepository(db)
|
|
156
|
+
const rows = await repo.list('posts')
|
|
157
|
+
expect(rows[0].actions).toEqual([{ type: 'webhook', url: 'https://example.com' }])
|
|
158
|
+
})
|
|
159
|
+
})
|