flarecms 0.1.0 → 0.1.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 (110) hide show
  1. package/LICENSE +21 -0
  2. package/dist/auth/index.js +201 -1
  3. package/dist/cli/commands.js +5554 -55
  4. package/dist/cli/index.js +5554 -55
  5. package/dist/cli/mcp.js +30 -0
  6. package/dist/db/index.js +10392 -25
  7. package/dist/index.js +56775 -7583
  8. package/package.json +31 -27
  9. package/scripts/fix-api-paths.mjs +0 -32
  10. package/scripts/fix-imports.mjs +0 -38
  11. package/scripts/prefix-css.mjs +0 -45
  12. package/src/api/lib/cache.ts +0 -45
  13. package/src/api/lib/response.ts +0 -40
  14. package/src/api/middlewares/auth.ts +0 -186
  15. package/src/api/middlewares/cors.ts +0 -10
  16. package/src/api/middlewares/rbac.ts +0 -85
  17. package/src/api/routes/auth.ts +0 -377
  18. package/src/api/routes/collections.ts +0 -205
  19. package/src/api/routes/content.ts +0 -175
  20. package/src/api/routes/device.ts +0 -160
  21. package/src/api/routes/magic.ts +0 -150
  22. package/src/api/routes/mcp.ts +0 -273
  23. package/src/api/routes/oauth.ts +0 -160
  24. package/src/api/routes/settings.ts +0 -43
  25. package/src/api/routes/setup.ts +0 -307
  26. package/src/api/routes/tokens.ts +0 -80
  27. package/src/api/schemas/auth.ts +0 -15
  28. package/src/api/schemas/index.ts +0 -51
  29. package/src/api/schemas/tokens.ts +0 -24
  30. package/src/auth/index.ts +0 -28
  31. package/src/cli/commands.ts +0 -217
  32. package/src/cli/index.ts +0 -21
  33. package/src/cli/mcp.ts +0 -210
  34. package/src/cli/tests/cli.test.ts +0 -40
  35. package/src/cli/tests/create.test.ts +0 -87
  36. package/src/client/FlareAdminRouter.tsx +0 -47
  37. package/src/client/app.tsx +0 -175
  38. package/src/client/components/app-sidebar.tsx +0 -227
  39. package/src/client/components/collection-modal.tsx +0 -215
  40. package/src/client/components/content-list.tsx +0 -247
  41. package/src/client/components/dynamic-form.tsx +0 -190
  42. package/src/client/components/field-modal.tsx +0 -221
  43. package/src/client/components/settings/api-token-section.tsx +0 -400
  44. package/src/client/components/settings/general-section.tsx +0 -224
  45. package/src/client/components/settings/security-section.tsx +0 -154
  46. package/src/client/components/settings/seo-section.tsx +0 -200
  47. package/src/client/components/settings/signup-section.tsx +0 -257
  48. package/src/client/components/ui/accordion.tsx +0 -78
  49. package/src/client/components/ui/avatar.tsx +0 -107
  50. package/src/client/components/ui/badge.tsx +0 -52
  51. package/src/client/components/ui/button.tsx +0 -60
  52. package/src/client/components/ui/card.tsx +0 -103
  53. package/src/client/components/ui/checkbox.tsx +0 -27
  54. package/src/client/components/ui/collapsible.tsx +0 -19
  55. package/src/client/components/ui/dialog.tsx +0 -162
  56. package/src/client/components/ui/icon-picker.tsx +0 -485
  57. package/src/client/components/ui/icons-data.ts +0 -8476
  58. package/src/client/components/ui/input.tsx +0 -20
  59. package/src/client/components/ui/label.tsx +0 -20
  60. package/src/client/components/ui/popover.tsx +0 -91
  61. package/src/client/components/ui/select.tsx +0 -204
  62. package/src/client/components/ui/separator.tsx +0 -23
  63. package/src/client/components/ui/sheet.tsx +0 -141
  64. package/src/client/components/ui/sidebar.tsx +0 -722
  65. package/src/client/components/ui/skeleton.tsx +0 -13
  66. package/src/client/components/ui/sonner.tsx +0 -47
  67. package/src/client/components/ui/switch.tsx +0 -30
  68. package/src/client/components/ui/table.tsx +0 -116
  69. package/src/client/components/ui/tabs.tsx +0 -80
  70. package/src/client/components/ui/textarea.tsx +0 -18
  71. package/src/client/components/ui/tooltip.tsx +0 -68
  72. package/src/client/hooks/use-mobile.ts +0 -19
  73. package/src/client/index.css +0 -149
  74. package/src/client/index.ts +0 -7
  75. package/src/client/layouts/admin-layout.tsx +0 -93
  76. package/src/client/layouts/settings-layout.tsx +0 -104
  77. package/src/client/lib/api.ts +0 -72
  78. package/src/client/lib/utils.ts +0 -6
  79. package/src/client/main.tsx +0 -10
  80. package/src/client/pages/collection-detail.tsx +0 -634
  81. package/src/client/pages/collections.tsx +0 -180
  82. package/src/client/pages/dashboard.tsx +0 -133
  83. package/src/client/pages/device.tsx +0 -66
  84. package/src/client/pages/document-detail-page.tsx +0 -139
  85. package/src/client/pages/documents-page.tsx +0 -103
  86. package/src/client/pages/login.tsx +0 -345
  87. package/src/client/pages/settings.tsx +0 -65
  88. package/src/client/pages/setup.tsx +0 -129
  89. package/src/client/pages/signup.tsx +0 -188
  90. package/src/client/store/auth.ts +0 -30
  91. package/src/client/store/collections.ts +0 -13
  92. package/src/client/store/config.ts +0 -12
  93. package/src/client/store/fetcher.ts +0 -30
  94. package/src/client/store/router.ts +0 -95
  95. package/src/client/store/schema.ts +0 -39
  96. package/src/client/store/settings.ts +0 -31
  97. package/src/client/types.ts +0 -34
  98. package/src/db/dynamic.ts +0 -70
  99. package/src/db/index.ts +0 -16
  100. package/src/db/migrations/001_initial_schema.ts +0 -57
  101. package/src/db/migrations/002_auth_tables.ts +0 -84
  102. package/src/db/migrator.ts +0 -61
  103. package/src/db/schema.ts +0 -142
  104. package/src/index.ts +0 -12
  105. package/src/server/index.ts +0 -66
  106. package/src/types.ts +0 -20
  107. package/style.css.d.ts +0 -8
  108. package/tests/css.test.ts +0 -21
  109. package/tests/modular.test.ts +0 -29
  110. package/tsconfig.json +0 -10
@@ -1,377 +0,0 @@
1
- import { Hono } from 'hono';
2
- import { getCookie, setCookie, deleteCookie } from 'hono/cookie';
3
- import { createDb } from '../../db';
4
- import { verifyPassword, hashPassword, generateSessionToken } from '../../auth';
5
- import { ulid } from 'ulidx';
6
- import { loginSchema, signupSchema, webauthnVerifySchema } from '../schemas';
7
- import {
8
- generateRegistrationOptions,
9
- verifyRegistrationResponse,
10
- generateAuthenticationOptions,
11
- verifyAuthenticationResponse
12
- } from '@simplewebauthn/server';
13
- import { decodeBase64url, encodeBase64url } from '@oslojs/encoding';
14
- import type { Bindings, Variables } from '../index';
15
-
16
- import { apiResponse } from '../lib/response';
17
-
18
- export const authRoutes = new Hono<{ Bindings: Bindings; Variables: Variables }>();
19
-
20
- // Get current user info
21
- authRoutes.get('/me', async (c) => {
22
- return apiResponse.ok(c, c.get('user'));
23
- });
24
-
25
- // Get registration settings (public)
26
- authRoutes.get('/registration-settings', async (c) => {
27
- const db = createDb(c.env.DB);
28
- const options = await db.selectFrom('options')
29
- .select(['name', 'value'])
30
- .where('name', 'in', ['flare:signup_enabled', 'flare:signup_default_role'])
31
- .execute();
32
-
33
- const settings = options.reduce((acc, opt) => {
34
- acc[opt.name.replace('flare:', '')] = opt.value;
35
- return acc;
36
- }, {} as Record<string, string>);
37
-
38
- return apiResponse.ok(c, settings);
39
- });
40
-
41
- async function getRoleForEmail(db: any, email: string): Promise<string> {
42
- const options = await db.selectFrom('options')
43
- .select('value')
44
- .where('name', '=', 'flare:signup_domain_rules')
45
- .executeTakeFirst();
46
-
47
- const defaultRoleOpt = await db.selectFrom('options')
48
- .select('value')
49
- .where('name', '=', 'flare:signup_default_role')
50
- .executeTakeFirst();
51
-
52
- const domain = email.split('@')[1] as string;
53
- const rules = JSON.parse(options?.value || '{}');
54
- const defaultRole = defaultRoleOpt?.value || 'viewer';
55
-
56
- return rules[domain] || defaultRole;
57
- }
58
-
59
- // Signup (public)
60
- authRoutes.post('/signup', async (c) => {
61
- const body = await c.req.json();
62
- const parsed = signupSchema.safeParse(body);
63
- if (!parsed.success) return apiResponse.error(c, parsed.error.format());
64
-
65
- const { email, password } = parsed.data;
66
- const db = createDb(c.env.DB);
67
-
68
- // Check if signup is enabled
69
- const signupEnabled = await db.selectFrom('options')
70
- .select('value')
71
- .where('name', '=', 'flare:signup_enabled')
72
- .executeTakeFirst();
73
-
74
- if (signupEnabled?.value !== 'true') {
75
- return apiResponse.error(c, 'Self-registration is currently disabled', 403);
76
- }
77
-
78
- // Check if user already exists
79
- const existing = await db.selectFrom('fc_users')
80
- .select('id')
81
- .where('email', '=', email)
82
- .executeTakeFirst();
83
-
84
- if (existing) return apiResponse.error(c, 'Email already in use');
85
-
86
- const role = await getRoleForEmail(db, email);
87
- const userId = ulid();
88
- const hashedPassword = await hashPassword(password);
89
-
90
- await db.insertInto('fc_users')
91
- .values({
92
- id: userId,
93
- email,
94
- password: hashedPassword,
95
- role,
96
- disabled: 0,
97
- })
98
- .execute();
99
-
100
- // Create Session
101
- const sessionId = generateSessionToken();
102
- const expiresAt = new Date();
103
- expiresAt.setDate(expiresAt.getDate() + 30);
104
-
105
- await db.insertInto('fc_sessions')
106
- .values({ id: sessionId, user_id: userId, expires_at: expiresAt.toISOString() })
107
- .execute();
108
-
109
- setCookie(c, 'session', sessionId, {
110
- httpOnly: true,
111
- secure: true,
112
- sameSite: 'Lax',
113
- expires: expiresAt,
114
- path: '/'
115
- });
116
-
117
- return apiResponse.ok(c, { success: true, user: { email, role } });
118
- });
119
-
120
- // List user's passkeys
121
- authRoutes.get('/passkeys', async (c) => {
122
- const user = c.get('user');
123
- const db = createDb(c.env.DB);
124
- const passkeys = await db.selectFrom('fc_passkeys')
125
- .select(['id', 'device_type', 'last_used_at', 'created_at'])
126
- .where('user_id', '=', user.id)
127
- .execute();
128
- return apiResponse.ok(c, passkeys);
129
- });
130
-
131
- // Passkey Registration Options (Authenticated)
132
- authRoutes.post('/passkey/register/options', async (c) => {
133
- const user = c.get('user');
134
- const db = createDb(c.env.DB);
135
-
136
- const existingPasskeys = await db.selectFrom('fc_passkeys')
137
- .select('id')
138
- .where('user_id', '=', user.id)
139
- .execute();
140
-
141
- const options = await generateRegistrationOptions({
142
- rpName: 'FlareCMS',
143
- rpID: new URL(c.req.url).hostname,
144
- userID: new TextEncoder().encode(user.id) as Uint8Array<ArrayBuffer>,
145
- userName: user.email,
146
- attestationType: 'none',
147
- excludeCredentials: existingPasskeys.map(pk => ({
148
- id: pk.id,
149
- type: 'public-key' as const,
150
- })),
151
- authenticatorSelection: {
152
- residentKey: 'required',
153
- userVerification: 'preferred',
154
- },
155
- });
156
-
157
- // Save challenge to KV
158
- await c.env.KV.put(`webauthn_reg_auth_${user.id}`, options.challenge, { expirationTtl: 300 });
159
-
160
- return apiResponse.ok(c, options);
161
- });
162
-
163
- // Passkey Registration Verification (Authenticated)
164
- authRoutes.post('/passkey/register/verify', async (c) => {
165
- const user = c.get('user');
166
- const body = await c.req.json();
167
- const db = createDb(c.env.DB);
168
-
169
- const expectedChallenge = await c.env.KV.get(`webauthn_reg_auth_${user.id}`);
170
- if (!expectedChallenge) return apiResponse.error(c, 'Registration session expired');
171
-
172
- const origin = c.req.header('Origin') || new URL(c.req.url).origin;
173
- const rpID = new URL(origin).hostname;
174
-
175
- let verification;
176
- try {
177
- verification = await verifyRegistrationResponse({
178
- response: body,
179
- expectedChallenge,
180
- expectedOrigin: origin,
181
- expectedRPID: rpID,
182
- });
183
- } catch (error: any) {
184
- return c.json({ error: error.message }, 400);
185
- }
186
-
187
- if (verification.verified && verification.registrationInfo) {
188
- const { credential } = verification.registrationInfo;
189
-
190
- await db.insertInto('fc_passkeys')
191
- .values({
192
- id: credential.id,
193
- user_id: user.id,
194
- name: body.name || null,
195
- public_key: encodeBase64url(credential.publicKey),
196
- counter: credential.counter,
197
- device_type: verification.registrationInfo.credentialDeviceType,
198
- backed_up: verification.registrationInfo.credentialBackedUp ? 1 : 0,
199
- transports: JSON.stringify(body.response.transports || []),
200
- })
201
- .execute();
202
-
203
- await c.env.KV.delete(`webauthn_reg_auth_${user.id}`);
204
- return apiResponse.ok(c, { success: true });
205
- }
206
-
207
- return apiResponse.error(c, 'Passkey verification failed');
208
- });
209
-
210
- // Revoke a passkey
211
- authRoutes.delete('/passkey/:id', async (c) => {
212
- const user = c.get('user');
213
- const id = c.req.param('id');
214
- const db = createDb(c.env.DB);
215
-
216
- await db.deleteFrom('fc_passkeys')
217
- .where('id', '=', id)
218
- .where('user_id', '=', user.id)
219
- .execute();
220
-
221
- return apiResponse.ok(c, { success: true });
222
- });
223
-
224
- authRoutes.post('/login', async (c) => {
225
- const body = await c.req.json();
226
- const parsed = loginSchema.safeParse(body);
227
- if (!parsed.success) {
228
- return apiResponse.error(c, parsed.error.format());
229
- }
230
-
231
- const { email, password } = parsed.data;
232
- const db = createDb(c.env.DB);
233
-
234
- const user = await db.selectFrom('fc_users')
235
- .selectAll()
236
- .where('email', '=', email)
237
- .executeTakeFirst();
238
-
239
- if (!user || !user.password || !(await verifyPassword(password, user.password))) {
240
- return apiResponse.error(c, 'Invalid credentials', 401);
241
- }
242
-
243
- // Create Session
244
- const sessionId = generateSessionToken();
245
- const expiresAt = new Date();
246
- expiresAt.setDate(expiresAt.getDate() + 30); // 30 days session
247
-
248
- await db.insertInto('fc_sessions')
249
- .values({
250
- id: sessionId,
251
- user_id: user.id,
252
- expires_at: expiresAt.toISOString(),
253
- })
254
- .execute();
255
-
256
- setCookie(c, 'session', sessionId, {
257
- httpOnly: true,
258
- secure: true, // Always secure for simplicity in workers
259
- sameSite: 'Lax',
260
- expires: expiresAt,
261
- path: '/'
262
- });
263
-
264
- return apiResponse.ok(c, { success: true, message: 'Logged in' });
265
- });
266
-
267
- authRoutes.post('/logout', async (c) => {
268
- const sessionId = getCookie(c, 'session');
269
- if (sessionId) {
270
- const db = createDb(c.env.DB);
271
- await db.deleteFrom('fc_sessions').where('id', '=', sessionId).execute();
272
- deleteCookie(c, 'session');
273
- }
274
- return apiResponse.ok(c, { success: true });
275
- });
276
-
277
- // Passkey Authentication Options (Can be public for login)
278
- authRoutes.post('/passkey/options', async (c) => {
279
- const body = await c.req.json();
280
- const db = createDb(c.env.DB);
281
-
282
- // If user is authenticated, use context, otherwise use email from body
283
- const ctxUser = c.get('user');
284
- const email = ctxUser?.email || body.email;
285
-
286
- if (!email) return apiResponse.error(c, 'Email required for passkey challenge');
287
-
288
- const user = await db.selectFrom('fc_users').selectAll().where('email', '=', email).executeTakeFirst();
289
- if (!user) return apiResponse.error(c, 'User not found', 404);
290
-
291
- const passkeys = await db.selectFrom('fc_passkeys').selectAll().where('user_id', '=', user.id).execute();
292
-
293
- const options = await generateAuthenticationOptions({
294
- rpID: new URL(c.req.url).hostname,
295
- allowCredentials: passkeys.map(pk => ({
296
- id: pk.id,
297
- transports: pk.transports ? JSON.parse(pk.transports) : undefined,
298
- })),
299
- });
300
-
301
- // Save challenge to KV (expires in 5 minutes)
302
- await c.env.KV.put(`webauthn_auth_${user.id}`, options.challenge, { expirationTtl: 300 });
303
-
304
- return apiResponse.ok(c, options);
305
- });
306
-
307
- // Passkey Verification
308
- authRoutes.post('/passkey/verify', async (c) => {
309
- const body = await c.req.json();
310
- const parsed = webauthnVerifySchema.safeParse(body);
311
- if (!parsed.success) return apiResponse.error(c, parsed.error.format());
312
-
313
- const db = createDb(c.env.DB);
314
- const user = await db.selectFrom('fc_users').selectAll().where('email', '=', parsed.data.email).executeTakeFirst();
315
- if (!user) return apiResponse.error(c, 'User not found', 404);
316
-
317
- const expectedChallenge = await c.env.KV.get(`webauthn_auth_${user.id}`);
318
- if (!expectedChallenge) return apiResponse.error(c, 'Challenge expired or invalid');
319
-
320
- const passkey = await db.selectFrom('fc_passkeys').selectAll().where('id', '=', parsed.data.response.id).where('user_id', '=', user.id).executeTakeFirst();
321
- if (!passkey) return apiResponse.error(c, 'Passkey not found', 404);
322
-
323
- const origin = c.req.header('Origin') || new URL(c.req.url).origin;
324
- const rpID = new URL(origin).hostname;
325
-
326
- let verification;
327
- try {
328
- verification = await verifyAuthenticationResponse({
329
- response: parsed.data.response,
330
- expectedChallenge,
331
- expectedOrigin: origin,
332
- expectedRPID: rpID,
333
- credential: {
334
- id: passkey.id,
335
- publicKey: decodeBase64url(passkey.public_key) as Uint8Array<ArrayBuffer>,
336
- counter: passkey.counter,
337
- transports: passkey.transports ? JSON.parse(passkey.transports) : undefined,
338
- },
339
- });
340
- } catch (error: any) {
341
- return apiResponse.error(c, error.message);
342
- }
343
-
344
- if (verification.verified) {
345
- await db.updateTable('fc_passkeys')
346
- .set({ counter: verification.authenticationInfo.newCounter })
347
- .where('id', '=', passkey.id)
348
- .execute();
349
-
350
- // Create Session
351
- const sessionId = generateSessionToken();
352
- const expiresAt = new Date();
353
- expiresAt.setDate(expiresAt.getDate() + 30); // 30 days session
354
-
355
- await db.insertInto('fc_sessions')
356
- .values({
357
- id: sessionId,
358
- user_id: user.id,
359
- expires_at: expiresAt.toISOString(),
360
- })
361
- .execute();
362
-
363
- setCookie(c, 'session', sessionId, {
364
- httpOnly: true,
365
- secure: true,
366
- sameSite: 'Lax',
367
- expires: expiresAt,
368
- path: '/'
369
- });
370
-
371
- await c.env.KV.delete(`webauthn_auth_${user.id}`);
372
-
373
- return apiResponse.ok(c, { success: true, message: 'Logged in' });
374
- }
375
-
376
- return apiResponse.error(c, 'Verification failed');
377
- });
@@ -1,205 +0,0 @@
1
- import { Hono } from 'hono';
2
- import { createDb, createCollectionTable, addFieldToTable } from '../../db';
3
- import { sql } from 'kysely';
4
- import { ulid } from 'ulidx';
5
- import { collectionSchema, fieldSchema } from '../schemas';
6
- import { cache } from '../lib/cache';
7
- import { apiResponse } from '../lib/response';
8
-
9
- import { requireRole } from '../middlewares/rbac';
10
- import type { Bindings, Variables } from '../../types';
11
-
12
- export const collectionsRoutes = new Hono<{ Bindings: Bindings; Variables: Variables }>();
13
-
14
- // Only admins can modify collections. Everyone authenticated can read.
15
- collectionsRoutes.post('/*', requireRole(['admin']));
16
- collectionsRoutes.post('/', requireRole(['admin']));
17
-
18
- collectionsRoutes.get('/', async (c) => {
19
- // 1. Try Cache
20
- const cached = await cache.getCollectionList(c.env.KV);
21
- if (cached) return apiResponse.ok(c, cached);
22
-
23
- // 2. Fallback to D1
24
- const db = createDb(c.env.DB);
25
- const result = await db.selectFrom('fc_collections').selectAll().execute();
26
-
27
- // 3. Populate Cache
28
- await cache.setCollectionList(c.env.KV, result);
29
-
30
- return apiResponse.ok(c, result);
31
- });
32
-
33
- collectionsRoutes.post('/', async (c) => {
34
- const body = await c.req.json();
35
- const parsed = collectionSchema.safeParse(body);
36
- if (!parsed.success) {
37
- return apiResponse.error(c, parsed.error.format());
38
- }
39
-
40
- const db = createDb(c.env.DB);
41
- const id = ulid();
42
- const data = parsed.data;
43
-
44
- // Check reserved slugs
45
- const reservedSlugs = c.get('reservedSlugs') || [];
46
- if (reservedSlugs.includes(data.slug)) {
47
- return apiResponse.error(c, `The slug '${data.slug}' is reserved for system use. Please choose another one.`, 400);
48
- }
49
-
50
- try {
51
- // 1. Save metadata
52
- await db.insertInto('fc_collections')
53
- .values({
54
- id,
55
- slug: data.slug,
56
- label: data.label,
57
- label_singular: data.labelSingular || null,
58
- description: data.description || null,
59
- icon: data.icon || null,
60
- is_public: data.isPublic ? 1 : 0,
61
- features: data.features ? JSON.stringify(data.features) : null,
62
- url_pattern: data.urlPattern || null,
63
- })
64
- .execute();
65
-
66
- // 2. Create physical table
67
- await createCollectionTable(db, data.slug);
68
-
69
- // 3. Initialize cache
70
- await cache.setSchema(c.env.KV, data.slug, {
71
- id,
72
- slug: data.slug,
73
- label: data.label,
74
- is_public: data.isPublic ? 1 : 0,
75
- features: data.features || [],
76
- url_pattern: data.urlPattern || null,
77
- fields: [],
78
- });
79
-
80
- // 4. Invalidate List Cache
81
- await cache.invalidateCollectionList(c.env.KV);
82
-
83
- return apiResponse.created(c, { id, slug: data.slug });
84
- } catch (e: any) {
85
- return apiResponse.error(c, e.message);
86
- }
87
- });
88
-
89
- collectionsRoutes.get('/:slug/schema', async (c) => {
90
- const slug = c.req.param('slug');
91
-
92
- // 1. Try Cache
93
- const cached = await cache.getSchema(c.env.KV, slug);
94
- if (cached) return apiResponse.ok(c, cached);
95
-
96
- // 2. Fallback to D1
97
- const db = createDb(c.env.DB);
98
- const collection = await db.selectFrom('fc_collections')
99
- .selectAll()
100
- .where('slug', '=', slug)
101
- .executeTakeFirst();
102
-
103
- if (!collection) return apiResponse.error(c, 'Collection not found', 404);
104
-
105
- const colFields = await db.selectFrom('fc_fields')
106
- .selectAll()
107
- .where('collection_id', '=', collection.id)
108
- .execute();
109
-
110
- const schema = {
111
- ...collection,
112
- features: collection.features ? JSON.parse(collection.features) : [],
113
- fields: colFields
114
- };
115
-
116
- // 3. Populate Cache
117
- await cache.setSchema(c.env.KV, slug, schema);
118
-
119
- return apiResponse.ok(c, schema);
120
- });
121
-
122
- collectionsRoutes.post('/:id/fields', async (c) => {
123
- const id = c.req.param('id');
124
- const body = await c.req.json();
125
- const parsed = fieldSchema.safeParse(body);
126
- if (!parsed.success) {
127
- return apiResponse.error(c, parsed.error.format());
128
- }
129
-
130
- const db = createDb(c.env.DB);
131
- const fieldId = ulid();
132
- const data = parsed.data;
133
-
134
- try {
135
- // Get collection slug
136
- const collection = await db.selectFrom('fc_collections')
137
- .select('slug')
138
- .where('id', '=', id)
139
- .executeTakeFirst();
140
-
141
- if (!collection) return apiResponse.error(c, 'Collection not found', 404);
142
-
143
- // 1. Save field metadata
144
- await db.insertInto('fc_fields')
145
- .values({
146
- id: fieldId,
147
- collection_id: id,
148
- slug: data.slug,
149
- label: data.label,
150
- type: data.type,
151
- required: data.required ? 1 : 0,
152
- })
153
- .execute();
154
-
155
- // 2. Alter physical table
156
- await addFieldToTable(db, collection.slug, data.slug, data.type);
157
-
158
- // 3. Invalidate cache to force re-fetch from D1 next time or update it
159
- await cache.invalidateSchema(c.env.KV, collection.slug);
160
-
161
- return apiResponse.created(c, { id: fieldId });
162
- } catch (e: any) {
163
- return apiResponse.error(c, e.message);
164
- }
165
- });
166
-
167
- collectionsRoutes.patch('/:id', async (c) => {
168
- const id = c.req.param('id');
169
- const body = await c.req.json();
170
- const db = createDb(c.env.DB);
171
-
172
- // Partial update support
173
- const data: any = {};
174
- if (body.label !== undefined) data.label = body.label;
175
- if (body.labelSingular !== undefined) data.label_singular = body.labelSingular;
176
- if (body.description !== undefined) data.description = body.description;
177
- if (body.icon !== undefined) data.icon = body.icon;
178
- if (body.isPublic !== undefined) data.is_public = body.isPublic ? 1 : 0;
179
- if (body.features !== undefined) data.features = JSON.stringify(body.features);
180
- if (body.urlPattern !== undefined) data.url_pattern = body.urlPattern;
181
-
182
- try {
183
- const collection = await db.selectFrom('fc_collections')
184
- .select('slug')
185
- .where('id', '=', id)
186
- .executeTakeFirst();
187
-
188
- if (!collection) return apiResponse.error(c, 'Collection not found', 404);
189
-
190
- await db.updateTable('fc_collections')
191
- .set({
192
- ...data,
193
- updated_at: sql`CURRENT_TIMESTAMP`
194
- })
195
- .where('id', '=', id)
196
- .execute();
197
-
198
- await cache.invalidateSchema(c.env.KV, collection.slug);
199
- await cache.invalidateCollectionList(c.env.KV);
200
-
201
- return apiResponse.ok(c, { success: true });
202
- } catch (e: any) {
203
- return apiResponse.error(c, e.message);
204
- }
205
- });