@beechcms/api 0.4.0-preview.10 → 0.4.0-preview.11

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.
@@ -0,0 +1,116 @@
1
+ import { Context } from 'hono'
2
+ import { applyVisibility } from '../../../shared/apply-policies'
3
+ import { publicProblem } from '../../../public/problem-details'
4
+ import { CONTENT_ERRORS } from '../constants'
5
+ import { AppEnv } from '../../../types'
6
+ import { EntryNotFoundError } from '@beechcms/core'
7
+
8
+ export async function getByIdHandler(context: Context<AppEnv>) {
9
+ const slug = context.req.param('slug')
10
+ const id = context.req.param('id')
11
+ if (!slug || !id) {
12
+ return publicProblem(context, {
13
+ type: 'content-invalid-slug-or-id',
14
+ title: 'Bad Request',
15
+ status: 400,
16
+ detail: CONTENT_ERRORS.INVALID_SLUG_OR_ID
17
+ })
18
+ }
19
+
20
+ const seed = context.get('getSeed')(slug)
21
+ if (!seed) {
22
+ return publicProblem(context, {
23
+ type: 'content-seed-not-found',
24
+ title: 'Not Found',
25
+ status: 404,
26
+ detail: CONTENT_ERRORS.SEED_NOT_FOUND
27
+ })
28
+ }
29
+
30
+ try {
31
+ const repository = context.get('repository')
32
+ const item = await repository.findById(seed, id)
33
+
34
+ let hasPendingDraft = false
35
+ if (seed.allowDrafts) {
36
+ hasPendingDraft = await repository.hasDraft(seed, id)
37
+ }
38
+
39
+ return context.json({
40
+ ...item,
41
+ has_pending_draft: hasPendingDraft,
42
+ data: applyVisibility(item, seed)
43
+ })
44
+ } catch (error) {
45
+ if (error instanceof EntryNotFoundError) {
46
+ return publicProblem(context, {
47
+ type: 'content-not-found',
48
+ title: 'Not Found',
49
+ status: 404,
50
+ detail: CONTENT_ERRORS.NOT_FOUND
51
+ })
52
+ }
53
+ console.error('Content detail error:', error)
54
+ return publicProblem(context, {
55
+ type: 'content-database-error',
56
+ title: 'Internal Server Error',
57
+ status: 500,
58
+ detail: CONTENT_ERRORS.DATABASE_ERROR
59
+ })
60
+ }
61
+ }
62
+
63
+ export async function getBySlugHandler(context: Context<AppEnv>) {
64
+ const schemaSlug = context.req.param('schema_slug')
65
+ const entrySlug = context.req.param('entry_slug')
66
+ if (!schemaSlug || !entrySlug) {
67
+ return publicProblem(context, {
68
+ type: 'content-invalid-slug-or-id',
69
+ title: 'Bad Request',
70
+ status: 400,
71
+ detail: CONTENT_ERRORS.INVALID_SLUG_OR_ID
72
+ })
73
+ }
74
+
75
+ const seed = context.get('getSeed')(schemaSlug)
76
+ if (!seed) {
77
+ return publicProblem(context, {
78
+ type: 'content-seed-not-found',
79
+ title: 'Not Found',
80
+ status: 404,
81
+ detail: CONTENT_ERRORS.SEED_NOT_FOUND
82
+ })
83
+ }
84
+
85
+ try {
86
+ const repository = context.get('repository')
87
+ const item = await repository.findBySlug(seed, entrySlug)
88
+
89
+ let hasPendingDraft = false
90
+ if (seed.allowDrafts) {
91
+ hasPendingDraft = await repository.hasDraft(seed, item.id)
92
+ }
93
+
94
+ return context.json({
95
+ ...item,
96
+ has_pending_draft: hasPendingDraft,
97
+ data: applyVisibility(item, seed)
98
+ })
99
+ } catch (error) {
100
+ if (error instanceof EntryNotFoundError) {
101
+ return publicProblem(context, {
102
+ type: 'content-not-found',
103
+ title: 'Not Found',
104
+ status: 404,
105
+ detail: CONTENT_ERRORS.NOT_FOUND
106
+ })
107
+ }
108
+ console.error('Content by-slug error:', error)
109
+ return publicProblem(context, {
110
+ type: 'content-database-error',
111
+ title: 'Internal Server Error',
112
+ status: 500,
113
+ detail: CONTENT_ERRORS.DATABASE_ERROR
114
+ })
115
+ }
116
+ }
@@ -0,0 +1,88 @@
1
+ import { Context } from 'hono'
2
+ import { parsePositiveInt, parseQueryFilters, cleanStr, toEngineFilters } from '../../../shared/query-utils'
3
+ import { applyVisibility } from '../../../shared/apply-policies'
4
+ import { publicProblem } from '../../../public/problem-details'
5
+ import { CONTENT_ERRORS } from '../constants'
6
+ import { AppEnv } from '../../../types'
7
+
8
+ export async function listHandler(context: Context<AppEnv>) {
9
+ const slug = context.req.param('slug')
10
+ if (!slug) {
11
+ return publicProblem(context, {
12
+ type: 'content-invalid-slug',
13
+ title: 'Bad Request',
14
+ status: 400,
15
+ detail: CONTENT_ERRORS.INVALID_SLUG
16
+ })
17
+ }
18
+
19
+ const seed = context.get('getSeed')(slug)
20
+ if (!seed) {
21
+ return publicProblem(context, {
22
+ type: 'content-seed-not-found',
23
+ title: 'Not Found',
24
+ status: 404,
25
+ detail: CONTENT_ERRORS.SEED_NOT_FOUND
26
+ })
27
+ }
28
+
29
+ try {
30
+ const query = context.req.query()
31
+ const search = cleanStr(query.search) ?? ''
32
+ const sortBy = cleanStr(query.sortBy) ?? ''
33
+ const sortDirRaw = cleanStr(query.sortDir)?.toLowerCase() ?? 'asc'
34
+ const rawFilters = parseQueryFilters(query.filters)
35
+ const engineFilters = toEngineFilters(rawFilters)
36
+
37
+ // Note: repository doesn't yet support has_pending_draft filter/column natively
38
+ // in findMany without SQL manipulation. We'll stick to basic findMany for now
39
+ // and might need to enhance the repository if this feature is critical for v1 of this refactor.
40
+ // The legacy code was doing a lot of SQL injection here.
41
+
42
+ const page = parsePositiveInt(query.page, 1)
43
+ const limit = Math.min(parsePositiveInt(query.limit, 25), 100)
44
+ const offset = (page - 1) * limit
45
+
46
+ const orderBy = sortBy
47
+ ? { column: sortBy, dir: (sortDirRaw === 'desc' ? 'DESC' : 'ASC') as 'ASC' | 'DESC' }
48
+ : undefined
49
+
50
+ const repository = context.get('repository')
51
+ const { items, total } = await repository.findMany(seed, {
52
+ filters: engineFilters,
53
+ orderBy,
54
+ search: search || undefined,
55
+ pagination: { limit, offset },
56
+ })
57
+
58
+ const entries = await Promise.all(items.map(async (item) => {
59
+ // Check for pending draft if allowed
60
+ let hasPendingDraft = false
61
+ if (seed.allowDrafts) {
62
+ hasPendingDraft = await repository.hasDraft(seed, item.id)
63
+ }
64
+
65
+ return {
66
+ ...item,
67
+ has_pending_draft: hasPendingDraft,
68
+ data: applyVisibility(item, seed) // Repository returns "pure" data including system fields
69
+ }
70
+ }))
71
+
72
+ // If no query params (except slug), return array directly (legacy compatibility)
73
+ const hasQueryParams = Boolean(search) || Boolean(sortBy) || Boolean(query.filters) || query.page !== undefined || query.limit !== undefined
74
+ if (!hasQueryParams) {
75
+ return context.json(entries)
76
+ }
77
+
78
+ return context.json({ items: entries, total, page, limit })
79
+ } catch (error) {
80
+ console.error('Content list error:', error)
81
+ return publicProblem(context, {
82
+ type: 'content-database-error',
83
+ title: 'Internal Server Error',
84
+ status: 500,
85
+ detail: CONTENT_ERRORS.DATABASE_ERROR
86
+ })
87
+ }
88
+ }
@@ -0,0 +1,216 @@
1
+ import { Context } from 'hono'
2
+ import {
3
+ slugify,
4
+ isValidContentStatus,
5
+ validateAndSanitizeSeedPayload,
6
+ resolvePolicies,
7
+ EntryNotFoundError,
8
+ SlugConflictError
9
+ } from '@beechcms/core'
10
+ import { applyPrivacy, PrivacyPolicyError } from '../../../shared/apply-policies'
11
+ import { publicProblem } from '../../../public/problem-details'
12
+ import { CONTENT_ERRORS } from '../constants'
13
+ import { logActivity } from '../../../shared/activity-logger'
14
+ import { logContentEvent } from '../../../shared/content-utils'
15
+ import { cleanStr } from '../../../shared/query-utils'
16
+ import { AppEnv } from '../../../types'
17
+
18
+ function normalizeBody(raw: unknown): Record<string, unknown> {
19
+ return typeof raw === 'object' && raw !== null ? (raw as Record<string, unknown>) : {}
20
+ }
21
+
22
+ function contentValidationProblem(
23
+ context: Context,
24
+ details: Array<{ field: string; expected: string; received: string; message: string }>
25
+ ) {
26
+ return publicProblem(context, {
27
+ type: 'content-validation-failed',
28
+ title: 'Bad Request',
29
+ status: 400,
30
+ detail: 'Validation failed',
31
+ errors: details
32
+ })
33
+ }
34
+
35
+ export async function updateHandler(context: Context<AppEnv>) {
36
+ const slug = context.req.param('slug')
37
+ const id = context.req.param('id')
38
+ if (!slug || !id) {
39
+ return publicProblem(context, {
40
+ type: 'content-invalid-slug-or-id',
41
+ title: 'Bad Request',
42
+ status: 400,
43
+ detail: CONTENT_ERRORS.INVALID_SLUG_OR_ID
44
+ })
45
+ }
46
+
47
+ const seed = context.get('getSeed')(slug)
48
+ if (!seed) {
49
+ return publicProblem(context, {
50
+ type: 'content-seed-not-found',
51
+ title: 'Not Found',
52
+ status: 404,
53
+ detail: CONTENT_ERRORS.SEED_NOT_FOUND
54
+ })
55
+ }
56
+
57
+ let body: Record<string, unknown>
58
+ try {
59
+ body = normalizeBody(await context.req.json<unknown>())
60
+ } catch {
61
+ return publicProblem(context, {
62
+ type: 'content-invalid-json',
63
+ title: 'Bad Request',
64
+ status: 400,
65
+ detail: CONTENT_ERRORS.INVALID_JSON_BODY
66
+ })
67
+ }
68
+
69
+ const bodyForData = { ...body }
70
+ delete bodyForData.slug
71
+ delete bodyForData.status
72
+
73
+ try {
74
+ const repository = context.get('repository')
75
+ // We need current data to handle slug and status if not provided,
76
+ // and to verify existence.
77
+ const current = await repository.findById(seed, id)
78
+
79
+ const newSlug = body.slug !== undefined ? slugify(String(body.slug)) : (current.slug as string)
80
+ const newStatus = body.status !== undefined ? (cleanStr(body.status) ?? current.status as string) : current.status as string
81
+
82
+ if (!isValidContentStatus(newStatus)) {
83
+ return publicProblem(context, {
84
+ type: 'content-invalid-status',
85
+ title: 'Bad Request',
86
+ status: 400,
87
+ detail: 'Invalid status. Allowed values are: draft, review, published'
88
+ })
89
+ }
90
+
91
+ if (!newSlug) {
92
+ return publicProblem(context, {
93
+ type: 'content-missing-slug',
94
+ title: 'Bad Request',
95
+ status: 400,
96
+ detail: 'Missing required field: slug'
97
+ })
98
+ }
99
+
100
+ let mergedData: Record<string, unknown> = {}
101
+
102
+ if (Object.keys(bodyForData).length > 0) {
103
+ const sensitiveAliases = Object.keys(bodyForData).filter((alias) => {
104
+ const branch = seed.branches.find((b) => b.alias === alias)
105
+ return branch != null && resolvePolicies(branch).privacy !== 'plain'
106
+ })
107
+
108
+ if (sensitiveAliases.length > 0) {
109
+ return publicProblem(context, {
110
+ type: 'content-sensitive-field-edit',
111
+ title: 'Unprocessable Entity',
112
+ status: 422,
113
+ detail: `${CONTENT_ERRORS.SENSITIVE_FIELD_EDIT}: ${sensitiveAliases.join(', ')}`
114
+ })
115
+ }
116
+
117
+ const validation = validateAndSanitizeSeedPayload(seed, bodyForData, {
118
+ operation: 'update',
119
+ allowNull: true,
120
+ requireAtLeastOneValidField: true,
121
+ enforceRequiredFields: true,
122
+ })
123
+
124
+ if (validation.dangerousFields.length > 0) {
125
+ return publicProblem(context, {
126
+ type: 'content-dangerous-content',
127
+ title: 'Unprocessable Entity',
128
+ status: 422,
129
+ detail: `Content rejected: dangerous markup detected in field '${validation.dangerousFields[0]}'`
130
+ })
131
+ }
132
+
133
+ if (validation.details.length > 0) return contentValidationProblem(context, validation.details)
134
+
135
+ let privacyPatch: Record<string, unknown>
136
+ try {
137
+ privacyPatch = await applyPrivacy(validation.data, seed)
138
+ } catch (error) {
139
+ if (error instanceof PrivacyPolicyError) {
140
+ return publicProblem(context, {
141
+ type: 'content-policy-not-implemented',
142
+ title: 'Not Implemented',
143
+ status: 501,
144
+ detail: error.message
145
+ })
146
+ }
147
+ throw error
148
+ }
149
+
150
+ // Remove null values from patch (patch semantics: null = leave unchanged)
151
+ for (const [k, v] of Object.entries(privacyPatch)) {
152
+ if (v !== null) mergedData[k] = v
153
+ }
154
+ }
155
+
156
+ if (newSlug !== current.slug) {
157
+ if (await repository.existsSlug(seed, newSlug, id)) {
158
+ return publicProblem(context, {
159
+ type: 'content-slug-conflict',
160
+ title: 'Conflict',
161
+ status: 409,
162
+ detail: CONTENT_ERRORS.SLUG_CONFLICT
163
+ })
164
+ }
165
+ // Add slug to mergedData if changed
166
+ mergedData.slug = newSlug
167
+ }
168
+
169
+ await repository.update(seed, id, mergedData, newStatus)
170
+
171
+ const userId = context.get('jwtPayload')?.sub
172
+ const title = mergedData.title || mergedData.name || newSlug
173
+
174
+ logContentEvent(context.env.DB, {
175
+ action: 'update',
176
+ schemaSlug: slug,
177
+ entryId: id,
178
+ userId,
179
+ details: { title }
180
+ }).catch(() => {})
181
+
182
+ logActivity(context, {
183
+ action: 'update',
184
+ entityType: 'content',
185
+ entityId: id,
186
+ entitySlug: slug,
187
+ details: { title }
188
+ })
189
+
190
+ return context.json({ success: true })
191
+ } catch (error) {
192
+ if (error instanceof EntryNotFoundError) {
193
+ return publicProblem(context, {
194
+ type: 'content-not-found',
195
+ title: 'Not Found',
196
+ status: 404,
197
+ detail: CONTENT_ERRORS.NOT_FOUND
198
+ })
199
+ }
200
+ if (error instanceof SlugConflictError) {
201
+ return publicProblem(context, {
202
+ type: 'content-slug-conflict',
203
+ title: 'Conflict',
204
+ status: 409,
205
+ detail: CONTENT_ERRORS.SLUG_CONFLICT
206
+ })
207
+ }
208
+ console.error('Content update error:', error)
209
+ return publicProblem(context, {
210
+ type: 'content-database-error',
211
+ title: 'Internal Server Error',
212
+ status: 500,
213
+ detail: CONTENT_ERRORS.DATABASE_ERROR
214
+ })
215
+ }
216
+ }
@@ -0,0 +1,20 @@
1
+ import { Hono } from 'hono'
2
+ import { AppEnv } from '../../types'
3
+ import { listHandler } from './handlers/list'
4
+ import { getByIdHandler, getBySlugHandler } from './handlers/get'
5
+ import { createHandler } from './handlers/create'
6
+ import { updateHandler } from './handlers/update'
7
+ import { deleteHandler } from './handlers/delete'
8
+ import { facetsHandler } from './handlers/facets'
9
+
10
+ const content = new Hono<AppEnv>()
11
+
12
+ content.get('/:slug', listHandler)
13
+ content.get('/:slug/facets', facetsHandler)
14
+ content.get('/:schema_slug/by-slug/:entry_slug', getBySlugHandler)
15
+ content.get('/:slug/:id', getByIdHandler)
16
+ content.post('/:slug', createHandler)
17
+ content.put('/:slug/:id', updateHandler)
18
+ content.delete('/:slug/:id', deleteHandler)
19
+
20
+ export default content