@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,220 @@
1
+ import { describe, it, expect } from 'vitest'
2
+ import {
3
+ parsePublicFilter,
4
+ toEngineFilters,
5
+ parsePublicPagination,
6
+ parseLatestCount,
7
+ } from './query-builder'
8
+ import type { Seed } from '@beechcms/core'
9
+
10
+ const SEED = {
11
+ slug: 'posts',
12
+ displayNameAlias: 'title',
13
+ branches: [
14
+ { id: 'br_01', alias: 'title', type: 'text' },
15
+ { id: 'br_02', alias: 'count', type: 'number' },
16
+ { id: 'br_03', alias: 'active', type: 'boolean' },
17
+ { id: 'br_04', alias: 'published_at', type: 'date' },
18
+ { id: 'br_05', alias: 'tags', type: 'tags' },
19
+ { id: 'br_06', alias: 'body', type: 'richtext' },
20
+ { id: 'br_07', alias: 'attachment', type: 'file' },
21
+ { id: 'br_08', alias: 'meta', type: 'json' },
22
+ ],
23
+ } as unknown as Seed
24
+
25
+ // ─── parsePublicFilter ────────────────────────────────────────────────────────
26
+
27
+ describe('parsePublicFilter', () => {
28
+ it('returns null for undefined input', () => {
29
+ expect(parsePublicFilter(undefined)).toBeNull()
30
+ })
31
+
32
+ it('returns null for empty string', () => {
33
+ expect(parsePublicFilter('')).toBeNull()
34
+ })
35
+
36
+ it('parses a valid filter with explicit AND logic', () => {
37
+ const raw = JSON.stringify({ logic: 'AND', where: [{ field: 'title', op: 'eq', value: 'Hello' }] })
38
+ const result = parsePublicFilter(raw)!
39
+ expect(result.logic).toBe('AND')
40
+ expect(result.where).toHaveLength(1)
41
+ expect(result.where[0]).toEqual({ field: 'title', op: 'eq', value: 'Hello' })
42
+ })
43
+
44
+ it('defaults logic to AND when omitted', () => {
45
+ const raw = JSON.stringify({ where: [{ field: 'title', op: 'contains', value: 'x' }] })
46
+ expect(parsePublicFilter(raw)!.logic).toBe('AND')
47
+ })
48
+
49
+ it('accepts case-insensitive logic value', () => {
50
+ const raw = JSON.stringify({ logic: 'or', where: [] })
51
+ expect(parsePublicFilter(raw)!.logic).toBe('OR')
52
+ })
53
+
54
+ it('throws for malformed JSON', () => {
55
+ expect(() => parsePublicFilter('{not-json')).toThrow('malformed JSON')
56
+ })
57
+
58
+ it('throws when parsed value is not an object', () => {
59
+ expect(() => parsePublicFilter('"a string"')).toThrow('object expected')
60
+ })
61
+
62
+ it('throws for an invalid logic value', () => {
63
+ const raw = JSON.stringify({ logic: 'BOTH', where: [] })
64
+ expect(() => parsePublicFilter(raw)).toThrow("'AND' or 'OR'")
65
+ })
66
+
67
+ it('throws for an unknown operator in a where condition', () => {
68
+ const raw = JSON.stringify({ where: [{ field: 'title', op: 'like', value: 'x' }] })
69
+ expect(() => parsePublicFilter(raw)).toThrow("unknown operator 'like'")
70
+ })
71
+
72
+ it('throws when where is not an array', () => {
73
+ const raw = JSON.stringify({ where: { field: 'title', op: 'eq' } })
74
+ expect(() => parsePublicFilter(raw)).toThrow("'where' must be an array")
75
+ })
76
+
77
+ it('filters out null conditions from where (missing field/op)', () => {
78
+ const raw = JSON.stringify({ where: [null, { field: 'title', op: 'eq', value: 'x' }] })
79
+ const result = parsePublicFilter(raw)!
80
+ expect(result.where).toHaveLength(1)
81
+ })
82
+
83
+ it('accepts all valid operators without throwing', () => {
84
+ const operators = ['eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'contains', 'not_contains',
85
+ 'starts_with', 'ends_with', 'is_empty', 'is_not_empty', 'in', 'not_in',
86
+ 'has_tag', 'has_any_tag', 'has_all_tags']
87
+ for (const op of operators) {
88
+ const raw = JSON.stringify({ where: [{ field: 'title', op, value: 'x' }] })
89
+ expect(() => parsePublicFilter(raw)).not.toThrow()
90
+ }
91
+ })
92
+ })
93
+
94
+ // ─── toEngineFilters ──────────────────────────────────────────────────────────
95
+
96
+ describe('toEngineFilters', () => {
97
+ it('returns [] for null filter', () => {
98
+ expect(toEngineFilters(SEED, null)).toEqual([])
99
+ })
100
+
101
+ it('returns [] when where array is empty', () => {
102
+ expect(toEngineFilters(SEED, { where: [], logic: 'AND' })).toEqual([])
103
+ })
104
+
105
+ it('maps text branch to FilterType "text"', () => {
106
+ const result = toEngineFilters(SEED, { where: [{ field: 'title', op: 'eq', value: 'Hi' }], logic: 'AND' })
107
+ expect(result[0].type).toBe('text')
108
+ })
109
+
110
+ it('maps number branch to FilterType "number"', () => {
111
+ const result = toEngineFilters(SEED, { where: [{ field: 'count', op: 'gt', value: 5 }], logic: 'AND' })
112
+ expect(result[0].type).toBe('number')
113
+ })
114
+
115
+ it('maps boolean branch to FilterType "boolean"', () => {
116
+ const result = toEngineFilters(SEED, { where: [{ field: 'active', op: 'eq', value: true }], logic: 'AND' })
117
+ expect(result[0].type).toBe('boolean')
118
+ })
119
+
120
+ it('maps date branch to FilterType "date"', () => {
121
+ const result = toEngineFilters(SEED, { where: [{ field: 'published_at', op: 'gt', value: '2024-01-01' }], logic: 'AND' })
122
+ expect(result[0].type).toBe('date')
123
+ })
124
+
125
+ it('maps tags branch to FilterType "tags"', () => {
126
+ const result = toEngineFilters(SEED, { where: [{ field: 'tags', op: 'has_tag', value: 'news' }], logic: 'AND' })
127
+ expect(result[0].type).toBe('tags')
128
+ })
129
+
130
+ it('maps richtext branch to FilterType "text"', () => {
131
+ const result = toEngineFilters(SEED, { where: [{ field: 'body', op: 'contains', value: 'x' }], logic: 'AND' })
132
+ expect(result[0].type).toBe('text')
133
+ })
134
+
135
+ it('maps file branch to FilterType "text"', () => {
136
+ const result = toEngineFilters(SEED, { where: [{ field: 'attachment', op: 'contains', value: 'url' }], logic: 'AND' })
137
+ expect(result[0].type).toBe('text')
138
+ })
139
+
140
+ it('maps json branch to FilterType "json"', () => {
141
+ const result = toEngineFilters(SEED, { where: [{ field: 'meta', op: 'eq', value: '{}' }], logic: 'AND' })
142
+ expect(result[0].type).toBe('json')
143
+ })
144
+
145
+ it('maps system columns (id, slug, status) to FilterType "system"', () => {
146
+ for (const field of ['id', 'slug', 'status', 'created_at', 'updated_at']) {
147
+ const result = toEngineFilters(SEED, { where: [{ field, op: 'eq', value: 'x' }], logic: 'AND' })
148
+ expect(result[0].type).toBe('system')
149
+ }
150
+ })
151
+
152
+ it('maps unknown fields to FilterType "text"', () => {
153
+ const result = toEngineFilters(SEED, { where: [{ field: 'ghost_field', op: 'eq', value: 'x' }], logic: 'AND' })
154
+ expect(result[0].type).toBe('text')
155
+ })
156
+
157
+ it('produces one FilterGroup per condition', () => {
158
+ const filter = {
159
+ where: [
160
+ { field: 'title', op: 'eq' as const, value: 'A' },
161
+ { field: 'count', op: 'gt' as const, value: 5 },
162
+ ],
163
+ logic: 'AND' as const,
164
+ }
165
+ expect(toEngineFilters(SEED, filter)).toHaveLength(2)
166
+ })
167
+
168
+ it('includes column and conditions in each FilterGroup', () => {
169
+ const filter = { where: [{ field: 'title', op: 'contains' as const, value: 'hi' }], logic: 'AND' as const }
170
+ const [group] = toEngineFilters(SEED, filter)
171
+ expect(group.column).toBe('title')
172
+ expect(group.conditions[0].op).toBe('contains')
173
+ expect(group.conditions[0].value).toBe('hi')
174
+ })
175
+ })
176
+
177
+ // ─── parsePublicPagination ────────────────────────────────────────────────────
178
+
179
+ describe('parsePublicPagination', () => {
180
+ it('defaults to page=1 and limit=25 when input is empty', () => {
181
+ expect(parsePublicPagination({})).toEqual({ page: 1, limit: 25 })
182
+ })
183
+
184
+ it('parses valid page and limit values', () => {
185
+ expect(parsePublicPagination({ page: '3', limit: '10' })).toEqual({ page: 3, limit: 10 })
186
+ })
187
+
188
+ it('clamps limit to a maximum of 100', () => {
189
+ expect(parsePublicPagination({ limit: '500' }).limit).toBe(100)
190
+ })
191
+
192
+ it('uses default for invalid (non-numeric) input', () => {
193
+ expect(parsePublicPagination({ page: 'abc', limit: 'xyz' })).toEqual({ page: 1, limit: 25 })
194
+ })
195
+ })
196
+
197
+ // ─── parseLatestCount ─────────────────────────────────────────────────────────
198
+
199
+ describe('parseLatestCount', () => {
200
+ it('returns 10 for undefined', () => {
201
+ expect(parseLatestCount(undefined)).toBe(10)
202
+ })
203
+
204
+ it('parses a valid integer string', () => {
205
+ expect(parseLatestCount('5')).toBe(5)
206
+ })
207
+
208
+ it('clamps to 1 for values below minimum', () => {
209
+ expect(parseLatestCount('0')).toBe(1)
210
+ expect(parseLatestCount('-5')).toBe(1)
211
+ })
212
+
213
+ it('clamps to 100 for values above maximum', () => {
214
+ expect(parseLatestCount('200')).toBe(100)
215
+ })
216
+
217
+ it('returns 10 for non-numeric input', () => {
218
+ expect(parseLatestCount('abc')).toBe(10)
219
+ })
220
+ })
@@ -1,241 +1,152 @@
1
- import type { Seed } from '@beechcms/core'
2
- import { parsePositiveInt } from '../shared/query-utils'
3
-
4
- export type PublicQueryInput = {
5
- page?: string
6
- limit?: string
7
- latest?: string
8
- }
9
-
10
- type PublicFilterLogic = 'AND' | 'OR'
11
- type PublicFilterOperator =
12
- | 'eq'
13
- | 'neq'
14
- | 'gt'
15
- | 'gte'
16
- | 'lt'
17
- | 'lte'
18
- | 'contains'
19
- | 'not_contains'
20
- | 'starts_with'
21
- | 'ends_with'
22
- | 'is_empty'
23
- | 'is_not_empty'
24
- | 'in'
25
- | 'not_in'
26
- | 'has_tag'
27
- | 'has_any_tag'
28
- | 'has_all_tags'
29
-
30
- type PublicFilterCondition = {
31
- field: string
32
- op: PublicFilterOperator
33
- value?: unknown
34
- }
35
-
36
- type ParsedPublicFilter = {
37
- where: PublicFilterCondition[]
38
- logic: PublicFilterLogic
39
- }
40
-
41
- const PUBLIC_FILTER_OPERATORS = new Set<PublicFilterOperator>([
42
- 'eq', 'neq', 'gt', 'gte', 'lt', 'lte',
43
- 'contains', 'not_contains', 'starts_with', 'ends_with',
44
- 'is_empty', 'is_not_empty', 'in', 'not_in',
45
- 'has_tag', 'has_any_tag', 'has_all_tags',
46
- ])
47
-
48
- const SYSTEM_COLUMNS = new Set(['id', 'slug', 'status', 'created_at', 'updated_at'])
49
-
50
- function asString(value: unknown): string | null {
51
- return typeof value === 'string' && value.trim() ? value.trim() : null
52
- }
53
-
54
- /**
55
- * Risolve il nome colonna SQL per un campo.
56
- * In v0.4.0 il nome colonna = branch.alias (nessun json_extract).
57
- */
58
- function resolveFieldExpression(
59
- seed: Seed | null,
60
- field: string
61
- ): { expr: string; fieldType: string } | null {
62
- if (SYSTEM_COLUMNS.has(field)) {
63
- const type = field === 'created_at' || field === 'updated_at' ? 'number' : 'text'
64
- return { expr: field, fieldType: type }
65
- }
66
- const branch = seed?.branches.find((b) => b.alias === field)
67
- if (!branch) return null
68
- return { expr: branch.alias, fieldType: branch.type }
69
- }
70
-
71
- function validateLogic(logicRaw: unknown): PublicFilterLogic {
72
- if (logicRaw === undefined) return 'AND'
73
- if (typeof logicRaw !== 'string') throw new TypeError("Invalid filter: 'logic' must be 'AND' or 'OR'")
74
- const normalized = logicRaw.toUpperCase()
75
- if (normalized !== 'AND' && normalized !== 'OR') throw new TypeError("Invalid filter: 'logic' must be 'AND' or 'OR'")
76
- return normalized
77
- }
78
-
79
- function parseWhereCondition(raw: unknown): PublicFilterCondition | null {
80
- if (!raw || typeof raw !== 'object') return null
81
- const maybe = raw as Record<string, unknown>
82
- const field = asString(maybe.field)
83
- const opRaw = asString(maybe.op)
84
- if (!field || !opRaw || !PUBLIC_FILTER_OPERATORS.has(opRaw as PublicFilterOperator)) {
85
- throw new TypeError(`Invalid filter: unknown operator '${opRaw ?? 'undefined'}'`)
86
- }
87
- return { field, op: opRaw as PublicFilterOperator, value: maybe.value }
88
- }
89
-
90
- export function parsePublicFilter(raw: string | undefined): ParsedPublicFilter | null {
91
- if (!raw) return null
92
- let parsed: unknown
93
- try {
94
- parsed = JSON.parse(raw)
95
- } catch {
96
- throw new TypeError('Invalid filter: malformed JSON')
97
- }
98
- if (!parsed || typeof parsed !== 'object') throw new TypeError('Invalid filter: object expected')
99
- const filterObj = parsed as Record<string, unknown>
100
- const logic = validateLogic(filterObj.logic)
101
- if (!Array.isArray(filterObj.where)) throw new TypeError("Invalid filter: 'where' must be an array")
102
- const where = filterObj.where
103
- .map(parseWhereCondition)
104
- .filter((item): item is PublicFilterCondition => item !== null)
105
- return { where, logic }
106
- }
107
-
108
- function ensureValueArray(value: unknown, op: PublicFilterOperator, field: string): unknown[] {
109
- if (!Array.isArray(value) || value.length === 0) {
110
- throw new TypeError(`Invalid filter: operator '${op}' for field '${field}' requires a non-empty array`)
111
- }
112
- return value
113
- }
114
-
115
- function buildTextOperation(
116
- op: PublicFilterOperator,
117
- expr: string,
118
- field: string,
119
- value: unknown
120
- ): { clause: string; bindings: Array<string | number> } {
121
- const str = asString(value)
122
- if (!str) throw new TypeError(`Invalid filter: operator '${op}' for field '${field}' requires a string value`)
123
- if (op === 'contains') return { clause: `LOWER(CAST(${expr} AS TEXT)) LIKE LOWER(?)`, bindings: [`%${str}%`] }
124
- if (op === 'not_contains') return { clause: `LOWER(CAST(${expr} AS TEXT)) NOT LIKE LOWER(?)`, bindings: [`%${str}%`] }
125
- if (op === 'starts_with') return { clause: `LOWER(CAST(${expr} AS TEXT)) LIKE LOWER(?)`, bindings: [`${str}%`] }
126
- return { clause: `LOWER(CAST(${expr} AS TEXT)) LIKE LOWER(?)`, bindings: [`%${str}`] }
127
- }
128
-
129
- function buildSetOperation(
130
- op: PublicFilterOperator,
131
- expr: string,
132
- field: string,
133
- value: unknown
134
- ): { clause: string; bindings: Array<string | number> } {
135
- const values = ensureValueArray(value, op, field)
136
- const placeholders = values.map(() => '?').join(',')
137
- return {
138
- clause: `${expr} ${op === 'in' ? 'IN' : 'NOT IN'} (${placeholders})`,
139
- bindings: values as Array<string | number>,
140
- }
141
- }
142
-
143
- function buildTagOperation(
144
- op: PublicFilterOperator,
145
- expr: string,
146
- field: string,
147
- value: unknown
148
- ): { clause: string; bindings: Array<string | number> } {
149
- const tags = op === 'has_tag' ? [value] : ensureValueArray(value, op, field)
150
- const cleaned = tags.map((item) => asString(item)).filter((item): item is string => item !== null)
151
- if (cleaned.length === 0) {
152
- throw new TypeError(`Invalid filter: operator '${op}' for field '${field}' requires tag string values`)
153
- }
154
- if (op === 'has_tag' || op === 'has_any_tag') {
155
- const placeholders = cleaned.map(() => '?').join(',')
156
- return {
157
- clause: `EXISTS (SELECT 1 FROM json_each(${expr}) je WHERE CAST(je.value AS TEXT) IN (${placeholders}))`,
158
- bindings: cleaned,
159
- }
160
- }
161
- const allParts = cleaned.map(() => `EXISTS (SELECT 1 FROM json_each(${expr}) je WHERE CAST(je.value AS TEXT) = ?)`)
162
- return { clause: allParts.join(' AND '), bindings: cleaned }
163
- }
164
-
165
- function buildConditionClause(
166
- condition: PublicFilterCondition,
167
- seed: Seed | null
168
- ): { clause: string; bindings: Array<string | number> } | null {
169
- const fieldMeta = resolveFieldExpression(seed, condition.field)
170
- if (!fieldMeta) return null
171
- const { expr, fieldType } = fieldMeta
172
- const { op, value, field } = condition
173
-
174
- if (op === 'is_empty') return { clause: `(${expr} IS NULL OR TRIM(CAST(${expr} AS TEXT)) = '')`, bindings: [] }
175
- if (op === 'is_not_empty') return { clause: `(${expr} IS NOT NULL AND TRIM(CAST(${expr} AS TEXT)) <> '')`, bindings: [] }
176
- if (op === 'contains' || op === 'not_contains' || op === 'starts_with' || op === 'ends_with') {
177
- return buildTextOperation(op, expr, field, value)
178
- }
179
- if (op === 'in' || op === 'not_in') return buildSetOperation(op, expr, field, value)
180
- if (op === 'has_tag' || op === 'has_any_tag' || op === 'has_all_tags') {
181
- if (fieldType !== 'json') throw new TypeError(`Invalid filter: operator '${op}' requires a json field`)
182
- return buildTagOperation(op, expr, field, value)
183
- }
184
-
185
- if (op === 'eq' || op === 'neq') {
186
- if (typeof value === 'boolean') {
187
- return { clause: `${expr} ${op === 'eq' ? '=' : '!='} ?`, bindings: [value ? 1 : 0] }
188
- }
189
- if (typeof value === 'number' && !Number.isNaN(value)) {
190
- return { clause: `${expr} ${op === 'eq' ? '=' : '!='} ?`, bindings: [value] }
191
- }
192
- const textValue = asString(value)
193
- if (!textValue) throw new TypeError(`Invalid filter: operator '${op}' for field '${field}' requires a scalar value`)
194
- return {
195
- clause: `LOWER(TRIM(CAST(${expr} AS TEXT))) ${op === 'eq' ? '=' : '!='} LOWER(TRIM(?))`,
196
- bindings: [textValue],
197
- }
198
- }
199
-
200
- const numberValue = typeof value === 'number' && !Number.isNaN(value) ? value : null
201
- const textValue = asString(value)
202
- const mathOp = op === 'gt' ? '>' : op === 'gte' ? '>=' : op === 'lt' ? '<' : op === 'lte' ? '<=' : null
203
- if (!mathOp) throw new TypeError(`Invalid filter: operator '${op}' is not supported`)
204
- if ((fieldType === 'number' || field === 'created_at' || field === 'updated_at') && numberValue !== null) {
205
- return { clause: `${expr} ${mathOp} ?`, bindings: [numberValue] }
206
- }
207
- if (textValue) return { clause: `CAST(${expr} AS TEXT) ${mathOp} ?`, bindings: [textValue] }
208
- throw new TypeError(`Invalid filter: operator '${op}' for field '${field}' requires a compatible value`)
209
- }
210
-
211
- export function buildPublicFilterWhereClause(
212
- seed: Seed | null,
213
- parsedFilter: ParsedPublicFilter | null
214
- ): { clause: string; bindings: Array<string | number> } {
215
- if (!parsedFilter || parsedFilter.where.length === 0) return { clause: '', bindings: [] }
216
- const clauses: string[] = []
217
- const bindings: Array<string | number> = []
218
- for (const condition of parsedFilter.where) {
219
- const built = buildConditionClause(condition, seed)
220
- if (!built) continue
221
- clauses.push(`(${built.clause})`)
222
- bindings.push(...built.bindings)
223
- }
224
- if (clauses.length === 0) return { clause: '', bindings: [] }
225
- return { clause: clauses.join(` ${parsedFilter.logic} `), bindings }
226
- }
227
-
228
- export function parsePublicPagination(input: PublicQueryInput): { page: number; limit: number } {
229
- const page = parsePositiveInt(input.page, 1)
230
- const limit = Math.min(parsePositiveInt(input.limit, 25), 100)
231
- return { page, limit }
232
- }
233
-
234
- export function parseLatestCount(latest: string | undefined): number {
235
- if (!latest) return 10
236
- const raw = Number.parseInt(latest, 10)
237
- const parsed = Number.isNaN(raw) ? 10 : raw
238
- if (parsed < 1) return 1
239
- if (parsed > 100) return 100
240
- return parsed
241
- }
1
+ import type { Seed, FilterGroup, FilterOperator, FilterType, BranchType } from '@beechcms/core'
2
+ import { parsePositiveInt } from '../shared/query-utils'
3
+
4
+ export type PublicQueryInput = {
5
+ page?: string
6
+ limit?: string
7
+ latest?: string
8
+ }
9
+
10
+ export type PublicFilterLogic = 'AND' | 'OR'
11
+ export type PublicFilterOperator =
12
+ | 'eq'
13
+ | 'neq'
14
+ | 'gt'
15
+ | 'gte'
16
+ | 'lt'
17
+ | 'lte'
18
+ | 'contains'
19
+ | 'not_contains'
20
+ | 'starts_with'
21
+ | 'ends_with'
22
+ | 'is_empty'
23
+ | 'is_not_empty'
24
+ | 'in'
25
+ | 'not_in'
26
+ | 'has_tag'
27
+ | 'has_any_tag'
28
+ | 'has_all_tags'
29
+
30
+ export type PublicFilterCondition = {
31
+ field: string
32
+ op: PublicFilterOperator
33
+ value?: unknown
34
+ }
35
+
36
+ export type ParsedPublicFilter = {
37
+ where: PublicFilterCondition[]
38
+ logic: PublicFilterLogic
39
+ }
40
+
41
+ const PUBLIC_FILTER_OPERATORS = new Set<PublicFilterOperator>([
42
+ 'eq', 'neq', 'gt', 'gte', 'lt', 'lte',
43
+ 'contains', 'not_contains', 'starts_with', 'ends_with',
44
+ 'is_empty', 'is_not_empty', 'in', 'not_in',
45
+ 'has_tag', 'has_any_tag', 'has_all_tags',
46
+ ])
47
+
48
+ function asString(value: unknown): string | null {
49
+ return typeof value === 'string' && value.trim() ? value.trim() : null
50
+ }
51
+
52
+ function validateLogic(logicRaw: unknown): PublicFilterLogic {
53
+ if (logicRaw === undefined) return 'AND'
54
+ if (typeof logicRaw !== 'string') throw new TypeError("Invalid filter: 'logic' must be 'AND' or 'OR'")
55
+ const normalized = logicRaw.toUpperCase()
56
+ if (normalized !== 'AND' && normalized !== 'OR') throw new TypeError("Invalid filter: 'logic' must be 'AND' or 'OR'")
57
+ return normalized
58
+ }
59
+
60
+ function parseWhereCondition(raw: unknown): PublicFilterCondition | null {
61
+ if (!raw || typeof raw !== 'object') return null
62
+ const maybe = raw as Record<string, unknown>
63
+ const field = asString(maybe.field)
64
+ const opRaw = asString(maybe.op)
65
+ if (!field || !opRaw || !PUBLIC_FILTER_OPERATORS.has(opRaw as PublicFilterOperator)) {
66
+ throw new TypeError(`Invalid filter: unknown operator '${opRaw ?? 'undefined'}'`)
67
+ }
68
+ return { field, op: opRaw as PublicFilterOperator, value: maybe.value }
69
+ }
70
+
71
+ export function parsePublicFilter(raw: string | undefined): ParsedPublicFilter | null {
72
+ if (!raw) return null
73
+ let parsed: unknown
74
+ try {
75
+ parsed = JSON.parse(raw)
76
+ } catch {
77
+ throw new TypeError('Invalid filter: malformed JSON')
78
+ }
79
+ if (!parsed || typeof parsed !== 'object') throw new TypeError('Invalid filter: object expected')
80
+ const filterObj = parsed as Record<string, unknown>
81
+ const logic = validateLogic(filterObj.logic)
82
+ if (!Array.isArray(filterObj.where)) throw new TypeError("Invalid filter: 'where' must be an array")
83
+ const where = filterObj.where
84
+ .map(parseWhereCondition)
85
+ .filter((item): item is PublicFilterCondition => item !== null)
86
+ return { where, logic }
87
+ }
88
+
89
+ const SYSTEM_COLUMNS = new Set(['id', 'slug', 'status', 'created_at', 'updated_at'])
90
+
91
+ function mapBranchToFilterType(type: BranchType): FilterType {
92
+ switch (type) {
93
+ case 'richtext':
94
+ case 'file':
95
+ return 'text'
96
+ case 'json':
97
+ return 'json'
98
+ case 'tags':
99
+ return 'tags'
100
+ case 'number':
101
+ return 'number'
102
+ case 'boolean':
103
+ return 'boolean'
104
+ case 'date':
105
+ return 'date'
106
+ case 'text':
107
+ default:
108
+ return 'text'
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Trasforma il filtro pubblico in FilterGroup[] per il Repository.
114
+ * Zero SQL: la logica di generazione query risiede esclusivamente nel Repository/Engine core.
115
+ */
116
+ export function toEngineFilters(seed: Seed, parsedFilter: ParsedPublicFilter | null): FilterGroup[] {
117
+ if (!parsedFilter || parsedFilter.where.length === 0) return []
118
+
119
+ // Note: Repository currently joins groups with AND.
120
+ // Public API supports logic: OR but the core engine currently defaults to AND for top-level groups.
121
+ // We map each condition to a group for maximum compatibility with the engine's buildFilterCondition.
122
+ return parsedFilter.where.map((cond) => {
123
+ const branch = seed.branches.find(b => b.alias === cond.field)
124
+ const type: FilterType = branch
125
+ ? mapBranchToFilterType(branch.type)
126
+ : (SYSTEM_COLUMNS.has(cond.field) ? 'system' : 'text')
127
+
128
+ return {
129
+ column: cond.field,
130
+ type,
131
+ conditions: [{
132
+ op: cond.op as FilterOperator,
133
+ value: cond.value as any
134
+ }]
135
+ }
136
+ })
137
+ }
138
+
139
+ export function parsePublicPagination(input: PublicQueryInput): { page: number; limit: number } {
140
+ const page = parsePositiveInt(input.page, 1)
141
+ const limit = Math.min(parsePositiveInt(input.limit, 25), 100)
142
+ return { page, limit }
143
+ }
144
+
145
+ export function parseLatestCount(latest: string | undefined): number {
146
+ if (!latest) return 10
147
+ const raw = Number.parseInt(latest, 10)
148
+ const parsed = Number.isNaN(raw) ? 10 : raw
149
+ if (parsed < 1) return 1
150
+ if (parsed > 100) return 100
151
+ return parsed
152
+ }