@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.
Files changed (140) hide show
  1. package/assets/dashboard/BeechLogo.svg +18 -18
  2. package/assets/dashboard/BeechLogoLIght.svg +48 -48
  3. package/assets/dashboard/assets/index-CH13idU1.js +554 -0
  4. package/assets/dashboard/assets/index-CewtCjom.css +1 -0
  5. package/assets/dashboard/beechLogoDark.svg +48 -48
  6. package/assets/dashboard/index.html +18 -18
  7. package/assets/dashboard/sol.svg +3 -3
  8. package/assets/dashboard/undraw_enter_nwx3.svg +36 -36
  9. package/migrations/0000_v040_base.sql +213 -213
  10. package/package.json +2 -2
  11. package/src/auth/bcrypt-hash-provider.ts +20 -0
  12. package/src/auth/constants.ts +10 -10
  13. package/src/auth/generate-refresh-token.test.ts +19 -0
  14. package/src/auth/hash-provider.test.ts +46 -0
  15. package/src/auth/in-memory-hash-provider.ts +13 -0
  16. package/src/auth/jose-token-service.ts +55 -0
  17. package/src/auth/login.test.ts +92 -0
  18. package/src/auth/login.ts +74 -91
  19. package/src/auth/refresh.ts +5 -127
  20. package/src/auth/static-token-service.ts +18 -0
  21. package/src/auth/token-service.test.ts +82 -0
  22. package/src/factory.ts +339 -303
  23. package/src/features/content/constants.ts +10 -0
  24. package/src/features/content/handlers/create.ts +157 -0
  25. package/src/features/content/handlers/delete.ts +80 -0
  26. package/src/features/content/handlers/facets.ts +45 -0
  27. package/src/features/content/handlers/get.ts +116 -0
  28. package/src/features/content/handlers/list.ts +88 -0
  29. package/src/features/content/handlers/update.ts +211 -0
  30. package/src/features/content/index.ts +20 -0
  31. package/src/features/draft/draft.handler.ts +283 -198
  32. package/src/features/draft/index.ts +1 -1
  33. package/src/features/email/email.provider.ts +38 -38
  34. package/src/features/email/email.service.ts +80 -80
  35. package/src/features/email/email.types.ts +98 -98
  36. package/src/features/email/index.ts +28 -28
  37. package/src/features/email/providers/resend.ts +63 -63
  38. package/src/features/email/templates/password-changed.ts +59 -59
  39. package/src/features/email/templates/password-reset.ts +64 -64
  40. package/src/features/email/templates/shell.ts +92 -93
  41. package/src/features/notifications/index.ts +1 -1
  42. package/src/features/notifications/notifications.handler.ts +101 -88
  43. package/src/features/password-reset/index.ts +15 -15
  44. package/src/features/password-reset/request.ts +82 -88
  45. package/src/features/password-reset/reset.ts +92 -110
  46. package/src/features/rotate-field/index.ts +1 -1
  47. package/src/features/rotate-field/rotate-field.handler.ts +128 -82
  48. package/src/features/rotate-field/rotate-field.schema.ts +13 -9
  49. package/src/features/schema/schema.handler.ts +16 -16
  50. package/src/features/settings/settings.handler.ts +301 -249
  51. package/src/features/setup/index.ts +91 -59
  52. package/src/features/stats/index.ts +1 -1
  53. package/src/features/stats/stats.handler.ts +430 -395
  54. package/src/index.ts +24 -11
  55. package/src/media-utils.ts +78 -78
  56. package/src/middleware/auth-providers.middleware.ts +32 -0
  57. package/src/middleware/observability.middleware.ts +52 -0
  58. package/src/middleware/rate-limit.middleware.ts +41 -0
  59. package/src/middleware/repository.middleware.ts +60 -0
  60. package/src/middleware/storage.middleware.ts +21 -0
  61. package/src/middleware.ts +47 -67
  62. package/src/public/access-policy.ts +23 -23
  63. package/src/public/api-key-middleware.ts +53 -53
  64. package/src/public/index.ts +12 -12
  65. package/src/public/problem-details.ts +48 -42
  66. package/src/public/public-add.ts +156 -183
  67. package/src/public/public-edit.ts +159 -183
  68. package/src/public/public-errors.ts +15 -15
  69. package/src/public/public-read.ts +216 -217
  70. package/src/public/public-routes.ts +84 -31
  71. package/src/public/query-builder.test.ts +220 -0
  72. package/src/public/query-builder.ts +152 -241
  73. package/src/public/rate-limit-middleware.ts +30 -42
  74. package/src/public/response-builder.ts +26 -26
  75. package/src/public/sanitize.ts +65 -65
  76. package/src/public/slug-utils.ts +14 -14
  77. package/src/rate-limit/cloudflare-rate-limiter.test.ts +26 -0
  78. package/src/rate-limit/cloudflare-rate-limiter.ts +11 -0
  79. package/src/rate-limit/in-memory-rate-limiter.test.ts +33 -0
  80. package/src/rate-limit/in-memory-rate-limiter.ts +13 -0
  81. package/src/rate-limit/no-op-rate-limiter.test.ts +18 -0
  82. package/src/rate-limit/no-op-rate-limiter.ts +7 -0
  83. package/src/search-utils.test.ts +207 -0
  84. package/src/search-utils.ts +209 -192
  85. package/src/search.ts +61 -72
  86. package/src/shared/apply-policies.test.ts +77 -0
  87. package/src/shared/apply-policies.ts +63 -63
  88. package/src/shared/background-notification-service.test.ts +58 -0
  89. package/src/shared/background-notification-service.ts +48 -0
  90. package/src/shared/base.repository.d1.ts +28 -0
  91. package/src/shared/content-utils.test.ts +161 -0
  92. package/src/shared/content-utils.ts +82 -108
  93. package/src/shared/content.repository.d1.test.ts +312 -0
  94. package/src/shared/content.repository.d1.ts +382 -0
  95. package/src/shared/d1-activity-log.repository.test.ts +136 -0
  96. package/src/shared/d1-activity-log.repository.ts +101 -0
  97. package/src/shared/d1-activity-logger.test.ts +82 -0
  98. package/src/shared/d1-activity-logger.ts +63 -0
  99. package/src/shared/d1-analytics.repository.test.ts +74 -0
  100. package/src/shared/d1-analytics.repository.ts +81 -0
  101. package/src/shared/d1-content-scan.repository.ts +29 -0
  102. package/src/shared/d1-notification.repository.test.ts +124 -0
  103. package/src/shared/d1-notification.repository.ts +114 -0
  104. package/src/shared/d1-password-reset-token.repository.test.ts +77 -0
  105. package/src/shared/d1-password-reset-token.repository.ts +52 -0
  106. package/src/shared/d1-search.repository.test.ts +83 -0
  107. package/src/shared/d1-search.repository.ts +84 -0
  108. package/src/shared/d1-session.repository.test.ts +121 -0
  109. package/src/shared/d1-session.repository.ts +98 -0
  110. package/src/shared/d1-user.repository.test.ts +147 -0
  111. package/src/shared/d1-user.repository.ts +109 -0
  112. package/src/shared/d1-widget.repository.test.ts +217 -0
  113. package/src/shared/d1-widget.repository.ts +337 -0
  114. package/src/shared/fixed-clock.ts +21 -0
  115. package/src/shared/fts-sync.ts +4 -4
  116. package/src/shared/idempotency.repository.d1.test.ts +79 -0
  117. package/src/shared/idempotency.repository.d1.ts +56 -0
  118. package/src/shared/in-memory-activity-logger.ts +15 -0
  119. package/src/shared/in-memory-notification-service.ts +15 -0
  120. package/src/shared/media.repository.d1.test.ts +103 -0
  121. package/src/shared/media.repository.d1.ts +64 -0
  122. package/src/shared/query-utils.ts +137 -137
  123. package/src/shared/request-utils.ts +22 -0
  124. package/src/shared/sequential-id-generator.ts +22 -0
  125. package/src/shared/storage/factory.ts +40 -0
  126. package/src/shared/storage/r2-binding-bucket.ts +81 -0
  127. package/src/shared/storage/s3-bucket.ts +163 -0
  128. package/src/shared/storage-utils.ts +36 -36
  129. package/src/shared/system-stats.repository.d1.test.ts +54 -0
  130. package/src/shared/system-stats.repository.d1.ts +44 -0
  131. package/src/types.ts +63 -36
  132. package/src/upload.ts +186 -335
  133. package/src/widget.ts +208 -349
  134. package/assets/dashboard/assets/index-CC-jbp6g.js +0 -554
  135. package/assets/dashboard/assets/index-CQODXprH.css +0 -1
  136. package/src/content.ts +0 -502
  137. package/src/features/draft/draft.test.ts +0 -315
  138. package/src/features/rotate-field/rotate-field.test.ts +0 -297
  139. package/src/shared/activity-logger.ts +0 -79
  140. package/src/shared/notification-service.ts +0 -56
@@ -0,0 +1,10 @@
1
+ export const CONTENT_ERRORS = {
2
+ INVALID_SLUG: 'Invalid slug',
3
+ INVALID_SLUG_OR_ID: 'Invalid slug or id',
4
+ INVALID_JSON_BODY: 'Invalid JSON body',
5
+ NOT_FOUND: 'Not found',
6
+ SEED_NOT_FOUND: 'Seed not found',
7
+ DATABASE_ERROR: 'Database error',
8
+ SLUG_CONFLICT: 'Slug already exists for this schema',
9
+ SENSITIVE_FIELD_EDIT: 'Cannot edit sensitive fields',
10
+ } as const
@@ -0,0 +1,157 @@
1
+ import { Context } from 'hono'
2
+ import {
3
+ slugify,
4
+ isValidContentStatus,
5
+ validateAndSanitizeSeedPayload,
6
+ SlugConflictError
7
+ } from '@beechcms/core'
8
+ import { applyPrivacy, PrivacyPolicyError } from '../../../shared/apply-policies'
9
+ import { publicProblem } from '../../../public/problem-details'
10
+ import { CONTENT_ERRORS } from '../constants'
11
+ import { cleanStr } from '../../../shared/query-utils'
12
+ import { AppEnv } from '../../../types'
13
+
14
+ function normalizeBody(raw: unknown): Record<string, unknown> {
15
+ return typeof raw === 'object' && raw !== null ? (raw as Record<string, unknown>) : {}
16
+ }
17
+
18
+ function contentValidationProblem(
19
+ context: Context,
20
+ details: Array<{ field: string; expected: string; received: string; message: string }>
21
+ ) {
22
+ return publicProblem(context, {
23
+ type: 'content-validation-failed',
24
+ title: 'Bad Request',
25
+ status: 400,
26
+ detail: 'Validation failed',
27
+ errors: details
28
+ })
29
+ }
30
+
31
+ export async function createHandler(context: Context<AppEnv>) {
32
+ const slug = context.req.param('slug')
33
+ if (!slug) {
34
+ return publicProblem(context, {
35
+ type: 'content-invalid-slug',
36
+ title: 'Bad Request',
37
+ status: 400,
38
+ detail: CONTENT_ERRORS.INVALID_SLUG
39
+ })
40
+ }
41
+
42
+ const seed = context.get('getSeed')(slug)
43
+ if (!seed) {
44
+ return publicProblem(context, {
45
+ type: 'content-seed-not-found',
46
+ title: 'Not Found',
47
+ status: 404,
48
+ detail: CONTENT_ERRORS.SEED_NOT_FOUND
49
+ })
50
+ }
51
+
52
+ let body: Record<string, unknown>
53
+ try {
54
+ body = normalizeBody(await context.req.json<unknown>())
55
+ } catch {
56
+ return publicProblem(context, {
57
+ type: 'content-invalid-json',
58
+ title: 'Bad Request',
59
+ status: 400,
60
+ detail: CONTENT_ERRORS.INVALID_JSON_BODY
61
+ })
62
+ }
63
+
64
+ const entrySlug = body.slug ? slugify(String(body.slug)) : null
65
+ const status = cleanStr(body.status) ?? 'draft'
66
+ if (!isValidContentStatus(status)) {
67
+ return publicProblem(context, {
68
+ type: 'content-invalid-status',
69
+ title: 'Bad Request',
70
+ status: 400,
71
+ detail: 'Invalid status. Allowed values are: draft, review, published'
72
+ })
73
+ }
74
+
75
+ const bodyForData = { ...body }
76
+ delete bodyForData.slug
77
+ delete bodyForData.status
78
+
79
+ const validation = validateAndSanitizeSeedPayload(seed, bodyForData, {
80
+ operation: 'create',
81
+ allowNull: false,
82
+ requireAtLeastOneValidField: true,
83
+ enforceRequiredFields: true,
84
+ })
85
+
86
+ if (validation.dangerousFields.length > 0) {
87
+ return publicProblem(context, {
88
+ type: 'content-dangerous-content',
89
+ title: 'Unprocessable Entity',
90
+ status: 422,
91
+ detail: `Content rejected: dangerous markup detected in field '${validation.dangerousFields[0]}'`
92
+ })
93
+ }
94
+
95
+ if (validation.details.length > 0) return contentValidationProblem(context, validation.details)
96
+
97
+ let privacyData: Record<string, unknown>
98
+ try {
99
+ privacyData = await applyPrivacy(validation.data, seed)
100
+ } catch (error) {
101
+ if (error instanceof PrivacyPolicyError) {
102
+ return publicProblem(context, {
103
+ type: 'content-policy-not-implemented',
104
+ title: 'Not Implemented',
105
+ status: 501,
106
+ detail: error.message
107
+ })
108
+ }
109
+ throw error
110
+ }
111
+
112
+ const id = context.get('idGenerator').uuid()
113
+ let finalSlug = entrySlug
114
+ if (!finalSlug) {
115
+ const fallbackSource = privacyData[seed.displayNameAlias ?? 'title'] || privacyData.title || privacyData.name || id
116
+ finalSlug = slugify(String(fallbackSource))
117
+ }
118
+
119
+ try {
120
+ const repository = context.get('repository')
121
+ await repository.create(seed, id, finalSlug, status, privacyData)
122
+
123
+ const jwtPayload = context.get('jwtPayload')
124
+ const title = privacyData.title || privacyData.name || finalSlug
125
+
126
+ context.get('activityLogger').log({
127
+ action: 'create',
128
+ entityType: 'content',
129
+ entityId: id,
130
+ entitySlug: slug,
131
+ details: { title },
132
+ actor: {
133
+ id: jwtPayload.sub,
134
+ email: jwtPayload.email ?? 'unknown',
135
+ name: jwtPayload.name ?? null,
136
+ },
137
+ })
138
+
139
+ return context.json({ id }, 201)
140
+ } catch (error) {
141
+ if (error instanceof SlugConflictError) {
142
+ return publicProblem(context, {
143
+ type: 'content-slug-conflict',
144
+ title: 'Conflict',
145
+ status: 409,
146
+ detail: CONTENT_ERRORS.SLUG_CONFLICT
147
+ })
148
+ }
149
+ console.error('Content create error:', error)
150
+ return publicProblem(context, {
151
+ type: 'content-database-error',
152
+ title: 'Internal Server Error',
153
+ status: 500,
154
+ detail: CONTENT_ERRORS.DATABASE_ERROR
155
+ })
156
+ }
157
+ }
@@ -0,0 +1,80 @@
1
+ import { Context } from 'hono'
2
+ import { EntryNotFoundError } from '@beechcms/core'
3
+ import { deleteR2Objects } from '../../../upload'
4
+ import { extractMediaKeysFromData } from '../../../media-utils'
5
+ import { publicProblem } from '../../../public/problem-details'
6
+ import { CONTENT_ERRORS } from '../constants'
7
+ import { AppEnv } from '../../../types'
8
+
9
+ export async function deleteHandler(context: Context<AppEnv>) {
10
+ const schemaSlug = context.req.param('slug')
11
+ const entryId = context.req.param('id')
12
+ if (!schemaSlug || !entryId) {
13
+ return publicProblem(context, {
14
+ type: 'content-invalid-slug-or-id',
15
+ title: 'Bad Request',
16
+ status: 400,
17
+ detail: CONTENT_ERRORS.INVALID_SLUG_OR_ID
18
+ })
19
+ }
20
+
21
+ const seed = context.get('getSeed')(schemaSlug)
22
+ if (!seed) {
23
+ return publicProblem(context, {
24
+ type: 'content-seed-not-found',
25
+ title: 'Not Found',
26
+ status: 404,
27
+ detail: CONTENT_ERRORS.SEED_NOT_FOUND
28
+ })
29
+ }
30
+
31
+ try {
32
+ const repository = context.get('repository')
33
+ // Repository.delete returns the row data for cleanup
34
+ const { row } = await repository.delete(seed, entryId)
35
+
36
+ const jwtPayload = context.get('jwtPayload')
37
+ const title = row.title || row.name || entryId
38
+
39
+ context.get('activityLogger').log({
40
+ action: 'delete',
41
+ entityType: 'content',
42
+ entityId: entryId,
43
+ entitySlug: schemaSlug,
44
+ details: { title },
45
+ actor: {
46
+ id: jwtPayload.sub,
47
+ email: jwtPayload.email ?? 'unknown',
48
+ name: jwtPayload.name ?? null,
49
+ },
50
+ })
51
+
52
+
53
+ const r2ObjectKeys = extractMediaKeysFromData(seed, row)
54
+ if (r2ObjectKeys.length > 0) {
55
+ await deleteR2Objects(context, r2ObjectKeys).catch((error) => {
56
+ if (context.env.ENV !== 'production') {
57
+ console.warn('R2 cleanup on delete failed (orphaned files):', error)
58
+ }
59
+ })
60
+ }
61
+
62
+ return context.json({ success: true })
63
+ } catch (error) {
64
+ if (error instanceof EntryNotFoundError) {
65
+ return publicProblem(context, {
66
+ type: 'content-not-found',
67
+ title: 'Not Found',
68
+ status: 404,
69
+ detail: CONTENT_ERRORS.NOT_FOUND
70
+ })
71
+ }
72
+ console.error('Content delete error:', error)
73
+ return publicProblem(context, {
74
+ type: 'content-database-error',
75
+ title: 'Internal Server Error',
76
+ status: 500,
77
+ detail: CONTENT_ERRORS.DATABASE_ERROR
78
+ })
79
+ }
80
+ }
@@ -0,0 +1,45 @@
1
+ import { Context } from 'hono'
2
+ import { publicProblem } from '../../../public/problem-details'
3
+ import { CONTENT_ERRORS } from '../constants'
4
+ import { AppEnv } from '../../../types'
5
+
6
+ export async function facetsHandler(context: Context<AppEnv>) {
7
+ const slug = context.req.param('slug')
8
+ if (!slug) {
9
+ return publicProblem(context, {
10
+ type: 'content-invalid-slug',
11
+ title: 'Bad Request',
12
+ status: 400,
13
+ detail: CONTENT_ERRORS.INVALID_SLUG
14
+ })
15
+ }
16
+
17
+ const seed = context.get('getSeed')(slug)
18
+ if (!seed) {
19
+ return publicProblem(context, {
20
+ type: 'content-seed-not-found',
21
+ title: 'Not Found',
22
+ status: 404,
23
+ detail: CONTENT_ERRORS.SEED_NOT_FOUND
24
+ })
25
+ }
26
+
27
+ try {
28
+ const repository = context.get('repository')
29
+ const { statuses, tagsByColumn } = await repository.getFacets(seed)
30
+
31
+ // Legacy format expected by the dashboard
32
+ return context.json({
33
+ statuses: Object.keys(statuses).sort((a, b) => a.localeCompare(b, 'it')),
34
+ tagsByColumnId: tagsByColumn,
35
+ })
36
+ } catch (error) {
37
+ console.error('Content facets error:', error)
38
+ return publicProblem(context, {
39
+ type: 'content-database-error',
40
+ title: 'Internal Server Error',
41
+ status: 500,
42
+ detail: CONTENT_ERRORS.DATABASE_ERROR
43
+ })
44
+ }
45
+ }
@@ -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
+ }