@beechcms/api 0.4.0-preview.9 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/dashboard/BeechLogo.svg +18 -18
- package/assets/dashboard/BeechLogoLIght.svg +48 -48
- package/assets/dashboard/assets/index-CH13idU1.js +554 -0
- package/assets/dashboard/assets/index-CewtCjom.css +1 -0
- package/assets/dashboard/beechLogoDark.svg +48 -48
- package/assets/dashboard/index.html +18 -18
- package/assets/dashboard/sol.svg +3 -3
- package/assets/dashboard/undraw_enter_nwx3.svg +36 -36
- package/migrations/0000_v040_base.sql +213 -213
- package/package.json +2 -2
- package/src/auth/bcrypt-hash-provider.ts +20 -0
- package/src/auth/constants.ts +10 -10
- 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 +74 -91
- package/src/auth/refresh.ts +5 -127
- package/src/auth/static-token-service.ts +18 -0
- package/src/auth/token-service.test.ts +82 -0
- package/src/factory.ts +339 -303
- package/src/features/content/constants.ts +10 -0
- package/src/features/content/handlers/create.ts +157 -0
- package/src/features/content/handlers/delete.ts +80 -0
- package/src/features/content/handlers/facets.ts +45 -0
- package/src/features/content/handlers/get.ts +116 -0
- package/src/features/content/handlers/list.ts +88 -0
- package/src/features/content/handlers/update.ts +211 -0
- package/src/features/content/index.ts +20 -0
- package/src/features/draft/draft.handler.ts +283 -198
- package/src/features/draft/index.ts +1 -1
- package/src/features/email/email.provider.ts +38 -38
- package/src/features/email/email.service.ts +80 -80
- package/src/features/email/email.types.ts +98 -98
- package/src/features/email/index.ts +28 -28
- package/src/features/email/providers/resend.ts +63 -63
- package/src/features/email/templates/password-changed.ts +59 -59
- package/src/features/email/templates/password-reset.ts +64 -64
- package/src/features/email/templates/shell.ts +92 -93
- package/src/features/notifications/index.ts +1 -1
- package/src/features/notifications/notifications.handler.ts +101 -88
- package/src/features/password-reset/index.ts +15 -15
- package/src/features/password-reset/request.ts +82 -88
- package/src/features/password-reset/reset.ts +92 -110
- package/src/features/rotate-field/index.ts +1 -1
- package/src/features/rotate-field/rotate-field.handler.ts +128 -82
- package/src/features/rotate-field/rotate-field.schema.ts +13 -9
- package/src/features/schema/schema.handler.ts +16 -16
- package/src/features/settings/settings.handler.ts +301 -249
- package/src/features/setup/index.ts +91 -59
- package/src/features/stats/index.ts +1 -1
- package/src/features/stats/stats.handler.ts +430 -395
- package/src/index.ts +24 -11
- package/src/media-utils.ts +78 -78
- 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 +60 -0
- package/src/middleware/storage.middleware.ts +21 -0
- package/src/middleware.ts +47 -67
- package/src/public/access-policy.ts +23 -23
- package/src/public/api-key-middleware.ts +53 -53
- package/src/public/index.ts +12 -12
- package/src/public/problem-details.ts +48 -42
- package/src/public/public-add.ts +156 -183
- package/src/public/public-edit.ts +159 -183
- package/src/public/public-errors.ts +15 -15
- package/src/public/public-read.ts +216 -217
- package/src/public/public-routes.ts +84 -31
- package/src/public/query-builder.test.ts +220 -0
- package/src/public/query-builder.ts +152 -241
- package/src/public/rate-limit-middleware.ts +30 -42
- package/src/public/response-builder.ts +26 -26
- package/src/public/sanitize.ts +65 -65
- package/src/public/slug-utils.ts +14 -14
- 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 +209 -192
- package/src/search.ts +61 -72
- package/src/shared/apply-policies.test.ts +77 -0
- package/src/shared/apply-policies.ts +63 -63
- package/src/shared/background-notification-service.test.ts +58 -0
- package/src/shared/background-notification-service.ts +48 -0
- package/src/shared/base.repository.d1.ts +28 -0
- package/src/shared/content-utils.test.ts +161 -0
- package/src/shared/content-utils.ts +82 -108
- package/src/shared/content.repository.d1.test.ts +312 -0
- package/src/shared/content.repository.d1.ts +382 -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.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/fixed-clock.ts +21 -0
- package/src/shared/fts-sync.ts +4 -4
- package/src/shared/idempotency.repository.d1.test.ts +79 -0
- package/src/shared/idempotency.repository.d1.ts +56 -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 +64 -0
- package/src/shared/query-utils.ts +137 -137
- package/src/shared/request-utils.ts +22 -0
- package/src/shared/sequential-id-generator.ts +22 -0
- package/src/shared/storage/factory.ts +40 -0
- package/src/shared/storage/r2-binding-bucket.ts +81 -0
- package/src/shared/storage/s3-bucket.ts +163 -0
- package/src/shared/storage-utils.ts +36 -36
- package/src/shared/system-stats.repository.d1.test.ts +54 -0
- package/src/shared/system-stats.repository.d1.ts +44 -0
- package/src/types.ts +63 -36
- package/src/upload.ts +186 -335
- package/src/widget.ts +208 -349
- package/assets/dashboard/assets/index-CC-jbp6g.js +0 -554
- package/assets/dashboard/assets/index-CQODXprH.css +0 -1
- package/src/content.ts +0 -502
- package/src/features/draft/draft.test.ts +0 -315
- package/src/features/rotate-field/rotate-field.test.ts +0 -297
- package/src/shared/activity-logger.ts +0 -79
- package/src/shared/notification-service.ts +0 -56
|
@@ -1,63 +1,63 @@
|
|
|
1
|
-
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
-
import { resolvePolicies, sha256hex } from '@beechcms/core'
|
|
3
|
-
import type { Seed } from '@beechcms/core'
|
|
4
|
-
|
|
5
|
-
class PrivacyPolicyError extends Error {
|
|
6
|
-
readonly status = 501 as const
|
|
7
|
-
constructor(message: string) {
|
|
8
|
-
super(message)
|
|
9
|
-
this.name = 'PrivacyPolicyError'
|
|
10
|
-
}
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
export { PrivacyPolicyError }
|
|
14
|
-
|
|
15
|
-
/** Applica la privacy policy ai campi del payload prima della scrittura su DB. */
|
|
16
|
-
export async function applyPrivacy(
|
|
17
|
-
data: Record<string, unknown>,
|
|
18
|
-
seed: Seed,
|
|
19
|
-
): Promise<Record<string, unknown>> {
|
|
20
|
-
const result: Record<string, unknown> = {}
|
|
21
|
-
for (const [alias, value] of Object.entries(data)) {
|
|
22
|
-
const branch = seed.branches.find((b) => b.alias === alias)
|
|
23
|
-
if (!branch) {
|
|
24
|
-
result[alias] = value
|
|
25
|
-
continue
|
|
26
|
-
}
|
|
27
|
-
const { privacy } = resolvePolicies(branch)
|
|
28
|
-
if (privacy === 'encrypt') {
|
|
29
|
-
throw new PrivacyPolicyError(
|
|
30
|
-
`Field '${alias}' uses 'encrypt' privacy which is not yet implemented.`,
|
|
31
|
-
)
|
|
32
|
-
}
|
|
33
|
-
if (privacy === 'hash' && value != null) {
|
|
34
|
-
result[alias] = await sha256hex(String(value))
|
|
35
|
-
} else {
|
|
36
|
-
result[alias] = value
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
return result
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/** Applica la visibility policy ai campi del payload in uscita verso il client. */
|
|
43
|
-
export function applyVisibility(
|
|
44
|
-
data: Record<string, unknown>,
|
|
45
|
-
seed: Seed,
|
|
46
|
-
): Record<string, unknown> {
|
|
47
|
-
const result: Record<string, unknown> = {}
|
|
48
|
-
for (const [alias, value] of Object.entries(data)) {
|
|
49
|
-
const branch = seed.branches.find((b) => b.alias === alias)
|
|
50
|
-
if (!branch) {
|
|
51
|
-
result[alias] = value
|
|
52
|
-
continue
|
|
53
|
-
}
|
|
54
|
-
const { visibility } = resolvePolicies(branch)
|
|
55
|
-
if (visibility === 'hidden') continue
|
|
56
|
-
if (visibility === 'masked') {
|
|
57
|
-
result[alias] = typeof value === 'string' && value.length > 0 ? '••••••••' : null
|
|
58
|
-
} else {
|
|
59
|
-
result[alias] = value
|
|
60
|
-
}
|
|
61
|
-
}
|
|
62
|
-
return result
|
|
63
|
-
}
|
|
1
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
+
import { resolvePolicies, sha256hex } from '@beechcms/core'
|
|
3
|
+
import type { Seed } from '@beechcms/core'
|
|
4
|
+
|
|
5
|
+
class PrivacyPolicyError extends Error {
|
|
6
|
+
readonly status = 501 as const
|
|
7
|
+
constructor(message: string) {
|
|
8
|
+
super(message)
|
|
9
|
+
this.name = 'PrivacyPolicyError'
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export { PrivacyPolicyError }
|
|
14
|
+
|
|
15
|
+
/** Applica la privacy policy ai campi del payload prima della scrittura su DB. */
|
|
16
|
+
export async function applyPrivacy(
|
|
17
|
+
data: Record<string, unknown>,
|
|
18
|
+
seed: Seed,
|
|
19
|
+
): Promise<Record<string, unknown>> {
|
|
20
|
+
const result: Record<string, unknown> = {}
|
|
21
|
+
for (const [alias, value] of Object.entries(data)) {
|
|
22
|
+
const branch = seed.branches.find((b) => b.alias === alias)
|
|
23
|
+
if (!branch) {
|
|
24
|
+
result[alias] = value
|
|
25
|
+
continue
|
|
26
|
+
}
|
|
27
|
+
const { privacy } = resolvePolicies(branch)
|
|
28
|
+
if (privacy === 'encrypt') {
|
|
29
|
+
throw new PrivacyPolicyError(
|
|
30
|
+
`Field '${alias}' uses 'encrypt' privacy which is not yet implemented.`,
|
|
31
|
+
)
|
|
32
|
+
}
|
|
33
|
+
if (privacy === 'hash' && value != null) {
|
|
34
|
+
result[alias] = await sha256hex(String(value))
|
|
35
|
+
} else {
|
|
36
|
+
result[alias] = value
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return result
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Applica la visibility policy ai campi del payload in uscita verso il client. */
|
|
43
|
+
export function applyVisibility(
|
|
44
|
+
data: Record<string, unknown>,
|
|
45
|
+
seed: Seed,
|
|
46
|
+
): Record<string, unknown> {
|
|
47
|
+
const result: Record<string, unknown> = {}
|
|
48
|
+
for (const [alias, value] of Object.entries(data)) {
|
|
49
|
+
const branch = seed.branches.find((b) => b.alias === alias)
|
|
50
|
+
if (!branch) {
|
|
51
|
+
result[alias] = value
|
|
52
|
+
continue
|
|
53
|
+
}
|
|
54
|
+
const { visibility } = resolvePolicies(branch)
|
|
55
|
+
if (visibility === 'hidden') continue
|
|
56
|
+
if (visibility === 'masked') {
|
|
57
|
+
result[alias] = typeof value === 'string' && value.length > 0 ? '••••••••' : null
|
|
58
|
+
} else {
|
|
59
|
+
result[alias] = value
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return result
|
|
63
|
+
}
|
|
@@ -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,28 @@
|
|
|
1
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
+
import { RepositoryError } from '@beechcms/core'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Base class for D1-backed repositories.
|
|
6
|
+
* Handles the D1 instance and provides common database utilities and error mapping.
|
|
7
|
+
*/
|
|
8
|
+
export abstract class BaseD1Repository {
|
|
9
|
+
constructor(protected readonly database: D1Database) {}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Utility method to extract a table name for a given seed.
|
|
13
|
+
*/
|
|
14
|
+
protected getTableName(slug: string, isDraft = false): string {
|
|
15
|
+
return isDraft ? `content_${slug}_drafts` : `content_${slug}`
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Helper to map generic D1 errors to Beech RepositoryErrors.
|
|
20
|
+
* This centralizes error handling for all D1 repositories.
|
|
21
|
+
*/
|
|
22
|
+
protected mapError(error: any, context: string): RepositoryError {
|
|
23
|
+
const message = error?.message || 'Unknown database error'
|
|
24
|
+
// In the future, we can add more specific SQLite error code checks here
|
|
25
|
+
// (e.g., checking for UNIQUE constraint via string matching or codes if available)
|
|
26
|
+
return new RepositoryError(`${context}: ${message}`, error)
|
|
27
|
+
}
|
|
28
|
+
}
|
|
@@ -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
|
+
})
|
|
@@ -1,108 +1,82 @@
|
|
|
1
|
-
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
-
import { deserializeFromDb, serializeForDb } from '@beechcms/core'
|
|
3
|
-
import type { Seed } from '@beechcms/core'
|
|
4
|
-
import type { ContentEntry } from './query-utils'
|
|
5
|
-
|
|
6
|
-
/** Deserializza ogni branch colonna di un DB row in formato API alias. */
|
|
7
|
-
export function rowToApiData(seed: Seed, row: Record<string, unknown>): Record<string, unknown> {
|
|
8
|
-
const data: Record<string, unknown> = {}
|
|
9
|
-
for (const branch of seed.branches) {
|
|
10
|
-
data[branch.alias] = deserializeFromDb(branch, row[branch.alias] ?? null)
|
|
11
|
-
}
|
|
12
|
-
return data
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
/** Converte un row della tabella content_{slug} in ContentEntry per le risposte API. */
|
|
16
|
-
export function rowToEntry(
|
|
17
|
-
seed: Seed,
|
|
18
|
-
row: Record<string, unknown>,
|
|
19
|
-
hasPendingDraft = false
|
|
20
|
-
): ContentEntry {
|
|
21
|
-
return {
|
|
22
|
-
id: row.id as string,
|
|
23
|
-
schema_slug: seed.slug,
|
|
24
|
-
slug: (row.slug as string | null) ?? null,
|
|
25
|
-
status: (row.status as string) ?? 'draft',
|
|
26
|
-
data: rowToApiData(seed, row),
|
|
27
|
-
hasPendingDraft,
|
|
28
|
-
created_at: (row.created_at as number | null) ?? null,
|
|
29
|
-
updated_at: (row.updated_at as number | null) ?? null,
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export interface InsertBindings {
|
|
34
|
-
cols: string[]
|
|
35
|
-
placeholders: string[]
|
|
36
|
-
bindings: (string | number | null)[]
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** Costruisce colonne, placeholders e bindings per INSERT INTO content_{slug}. */
|
|
40
|
-
export function buildInsertBindings(seed: Seed, payload: Record<string, unknown>): InsertBindings {
|
|
41
|
-
const cols: string[] = []
|
|
42
|
-
const placeholders: string[] = []
|
|
43
|
-
const bindings: (string | number | null)[] = []
|
|
44
|
-
for (const branch of seed.branches) {
|
|
45
|
-
if (Object.hasOwn(payload, branch.alias)) {
|
|
46
|
-
cols.push(branch.alias)
|
|
47
|
-
placeholders.push('?')
|
|
48
|
-
bindings.push(serializeForDb(branch, payload[branch.alias]))
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
return { cols, placeholders, bindings }
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export interface UpdateBindings {
|
|
55
|
-
setClause: string
|
|
56
|
-
bindings: (string | number | null)[]
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/** Costruisce SET clause e bindings per UPDATE content_{slug}. */
|
|
60
|
-
export function buildUpdateBindings(seed: Seed, payload: Record<string, unknown>): UpdateBindings {
|
|
61
|
-
const setParts: string[] = []
|
|
62
|
-
const bindings: (string | number | null)[] = []
|
|
63
|
-
for (const branch of seed.branches) {
|
|
64
|
-
if (Object.hasOwn(payload, branch.alias)) {
|
|
65
|
-
setParts.push(`${branch.alias} = ?`)
|
|
66
|
-
bindings.push(serializeForDb(branch, payload[branch.alias]))
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
return { setClause: setParts.join(', '), bindings }
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/** Controlla se esiste un draft pendente in content_{slug}_drafts. */
|
|
73
|
-
export async function hasDraft(db: D1Database, seed: Seed, entryId: string): Promise<boolean> {
|
|
74
|
-
if (!seed.allowDrafts) return false
|
|
75
|
-
const row = await db
|
|
76
|
-
.prepare(`SELECT 1 FROM content_${seed.slug}_drafts WHERE entry_id = ? LIMIT 1`)
|
|
77
|
-
.bind(entryId)
|
|
78
|
-
.first()
|
|
79
|
-
return row !== null
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
export async function logContentEvent(
|
|
84
|
-
db: D1Database,
|
|
85
|
-
opts: {
|
|
86
|
-
action: 'create' | 'update' | 'delete'
|
|
87
|
-
schemaSlug: string
|
|
88
|
-
entryId: string
|
|
89
|
-
userId?: string | null
|
|
90
|
-
details?: Record<string, unknown>
|
|
91
|
-
}
|
|
92
|
-
): Promise<void> {
|
|
93
|
-
await db
|
|
94
|
-
.prepare(
|
|
95
|
-
`INSERT INTO content_event_log (id, schema_slug, entry_id, action, user_id, details, created_at)
|
|
96
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
|
97
|
-
)
|
|
98
|
-
.bind(
|
|
99
|
-
crypto.randomUUID(),
|
|
100
|
-
opts.schemaSlug,
|
|
101
|
-
opts.entryId,
|
|
102
|
-
opts.action,
|
|
103
|
-
opts.userId ?? null,
|
|
104
|
-
opts.details ? JSON.stringify(opts.details) : null,
|
|
105
|
-
Math.floor(Date.now() / 1000)
|
|
106
|
-
)
|
|
107
|
-
.run()
|
|
108
|
-
}
|
|
1
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
+
import { deserializeFromDb, serializeForDb } from '@beechcms/core'
|
|
3
|
+
import type { Seed } from '@beechcms/core'
|
|
4
|
+
import type { ContentEntry } from './query-utils'
|
|
5
|
+
|
|
6
|
+
/** Deserializza ogni branch colonna di un DB row in formato API alias. */
|
|
7
|
+
export function rowToApiData(seed: Seed, row: Record<string, unknown>): Record<string, unknown> {
|
|
8
|
+
const data: Record<string, unknown> = {}
|
|
9
|
+
for (const branch of seed.branches) {
|
|
10
|
+
data[branch.alias] = deserializeFromDb(branch, row[branch.alias] ?? null)
|
|
11
|
+
}
|
|
12
|
+
return data
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Converte un row della tabella content_{slug} in ContentEntry per le risposte API. */
|
|
16
|
+
export function rowToEntry(
|
|
17
|
+
seed: Seed,
|
|
18
|
+
row: Record<string, unknown>,
|
|
19
|
+
hasPendingDraft = false
|
|
20
|
+
): ContentEntry {
|
|
21
|
+
return {
|
|
22
|
+
id: row.id as string,
|
|
23
|
+
schema_slug: seed.slug,
|
|
24
|
+
slug: (row.slug as string | null) ?? null,
|
|
25
|
+
status: (row.status as string) ?? 'draft',
|
|
26
|
+
data: rowToApiData(seed, row),
|
|
27
|
+
hasPendingDraft,
|
|
28
|
+
created_at: (row.created_at as number | null) ?? null,
|
|
29
|
+
updated_at: (row.updated_at as number | null) ?? null,
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface InsertBindings {
|
|
34
|
+
cols: string[]
|
|
35
|
+
placeholders: string[]
|
|
36
|
+
bindings: (string | number | null)[]
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Costruisce colonne, placeholders e bindings per INSERT INTO content_{slug}. */
|
|
40
|
+
export function buildInsertBindings(seed: Seed, payload: Record<string, unknown>): InsertBindings {
|
|
41
|
+
const cols: string[] = []
|
|
42
|
+
const placeholders: string[] = []
|
|
43
|
+
const bindings: (string | number | null)[] = []
|
|
44
|
+
for (const branch of seed.branches) {
|
|
45
|
+
if (Object.hasOwn(payload, branch.alias)) {
|
|
46
|
+
cols.push(branch.alias)
|
|
47
|
+
placeholders.push('?')
|
|
48
|
+
bindings.push(serializeForDb(branch, payload[branch.alias]))
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return { cols, placeholders, bindings }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface UpdateBindings {
|
|
55
|
+
setClause: string
|
|
56
|
+
bindings: (string | number | null)[]
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Costruisce SET clause e bindings per UPDATE content_{slug}. */
|
|
60
|
+
export function buildUpdateBindings(seed: Seed, payload: Record<string, unknown>): UpdateBindings {
|
|
61
|
+
const setParts: string[] = []
|
|
62
|
+
const bindings: (string | number | null)[] = []
|
|
63
|
+
for (const branch of seed.branches) {
|
|
64
|
+
if (Object.hasOwn(payload, branch.alias)) {
|
|
65
|
+
setParts.push(`${branch.alias} = ?`)
|
|
66
|
+
bindings.push(serializeForDb(branch, payload[branch.alias]))
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return { setClause: setParts.join(', '), bindings }
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Controlla se esiste un draft pendente in content_{slug}_drafts. */
|
|
73
|
+
export async function hasDraft(db: D1Database, seed: Seed, entryId: string): Promise<boolean> {
|
|
74
|
+
if (!seed.allowDrafts) return false
|
|
75
|
+
const row = await db
|
|
76
|
+
.prepare(`SELECT 1 FROM content_${seed.slug}_drafts WHERE entry_id = ? LIMIT 1`)
|
|
77
|
+
.bind(entryId)
|
|
78
|
+
.first()
|
|
79
|
+
return row !== null
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
|