deneljs 0.0.0-stage → 1.0.0

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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +57 -2
  3. package/drizzle/0000_lonely_reptil.sql +27 -0
  4. package/drizzle/0001_misty_wendigo.sql +74 -0
  5. package/drizzle/meta/0000_snapshot.json +179 -0
  6. package/drizzle/meta/0001_snapshot.json +492 -0
  7. package/drizzle/meta/_journal.json +20 -0
  8. package/package.json +55 -4
  9. package/src/admin/auth.ts +851 -0
  10. package/src/admin/layout.ts +419 -0
  11. package/src/admin/pages/categories.ts +223 -0
  12. package/src/admin/pages/dashboard.ts +192 -0
  13. package/src/admin/pages/media.ts +270 -0
  14. package/src/admin/pages/posts.ts +804 -0
  15. package/src/admin/pages/settings.ts +169 -0
  16. package/src/admin/pages/themes.ts +461 -0
  17. package/src/admin/pages/users.ts +501 -0
  18. package/src/admin/routes.ts +455 -0
  19. package/src/admin/tiptap-bundle.ts +48 -0
  20. package/src/admin/tiptap-entry.ts +226 -0
  21. package/src/ai/generator.ts +296 -0
  22. package/src/ai/index.ts +22 -0
  23. package/src/ai/schema.ts +13 -0
  24. package/src/ai/spec.ts +193 -0
  25. package/src/cli.ts +151 -0
  26. package/src/db/index.ts +278 -0
  27. package/src/db/schema.ts +115 -0
  28. package/src/engine/index.ts +52 -0
  29. package/src/engine/renderer.ts +533 -0
  30. package/src/engine/sandbox.ts +108 -0
  31. package/src/engine/schema.ts +71 -0
  32. package/src/engine/validator.ts +404 -0
  33. package/src/routes/admin-api.ts +1035 -0
  34. package/src/routes/posts.ts +294 -0
  35. package/src/routes/uploads.ts +119 -0
  36. package/src/server.ts +672 -0
  37. package/src/utils/sanitize-html.ts +145 -0
  38. package/themes/.gitkeep +1 -0
  39. package/themes/default/assets/style.css +799 -0
  40. package/themes/default/layouts/base.liquid +31 -0
  41. package/themes/default/layouts/home.liquid +180 -0
  42. package/themes/default/layouts/page.liquid +21 -0
  43. package/themes/default/layouts/post.liquid +55 -0
  44. package/themes/default/partials/footer.liquid +33 -0
  45. package/themes/default/partials/navbar.liquid +49 -0
  46. package/themes/default/theme.json +59 -0
package/src/server.ts ADDED
@@ -0,0 +1,672 @@
1
+ import { and, asc, desc, eq, or, sql, type SQL } from "drizzle-orm";
2
+ import { Elysia, t } from "elysia";
3
+ import { authRoutes, resolveCurrentUser } from "./admin/auth";
4
+ import { adminPageRoutes } from "./admin/routes";
5
+ import {
6
+ AiConfigurationError,
7
+ AiProviderError,
8
+ generateAndInstallTheme,
9
+ getAiThemeSpec,
10
+ validateGenerationRequest,
11
+ } from "./ai";
12
+ import {
13
+ clearSiteSettingsCache,
14
+ db,
15
+ getSiteSettings,
16
+ initializeDatabase,
17
+ isDatabaseHealthy,
18
+ schema,
19
+ } from "./db";
20
+ import {
21
+ clearThemeCache,
22
+ MAX_THEME_ZIP_BYTES,
23
+ mergeThemeSettings,
24
+ parseThemeConfig,
25
+ renderThemePage,
26
+ resolveThemeAssetPath,
27
+ resolveThemeDirectory,
28
+ THEME_SLUG_PATTERN,
29
+ validateAndInstallThemeZip,
30
+ validateThemeSettingsOverrides,
31
+ type PostTemplateItem,
32
+ type SiteCategoryItem,
33
+ } from "./engine";
34
+ import { adminApiRoutes } from "./routes/admin-api";
35
+ import { postsRoutes } from "./routes/posts";
36
+ import { publicUploadsRoute } from "./routes/uploads";
37
+
38
+ const THEME_SLUG_REGEX = new RegExp(THEME_SLUG_PATTERN);
39
+
40
+ function safeJsonObject(raw: string | null | undefined): Record<string, unknown> {
41
+ if (!raw) {
42
+ return {};
43
+ }
44
+ try {
45
+ const parsed = JSON.parse(raw) as unknown;
46
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
47
+ ? (parsed as Record<string, unknown>)
48
+ : {};
49
+ } catch {
50
+ return {};
51
+ }
52
+ }
53
+
54
+ function safeStringRecord(raw: string | null | undefined): Record<string, string> {
55
+ const obj = safeJsonObject(raw);
56
+ const result: Record<string, string> = {};
57
+ for (const [key, value] of Object.entries(obj)) {
58
+ if (typeof value === "string") {
59
+ result[key] = value;
60
+ }
61
+ }
62
+ return result;
63
+ }
64
+
65
+ function extractUploadedFile(body: unknown): File | null {
66
+ if (!body || typeof body !== "object") {
67
+ return null;
68
+ }
69
+
70
+ const record = body as Record<string, unknown>;
71
+ if (record.file instanceof File) {
72
+ return record.file;
73
+ }
74
+
75
+ for (const value of Object.values(record)) {
76
+ if (value instanceof File) {
77
+ return value;
78
+ }
79
+ }
80
+
81
+ return null;
82
+ }
83
+
84
+ function htmlResponse(html: string, status = 200): Response {
85
+ return new Response(html, {
86
+ status,
87
+ headers: {
88
+ "content-type": "text/html; charset=utf-8",
89
+ },
90
+ });
91
+ }
92
+
93
+ function notFoundResponse(message: string): Response {
94
+ return new Response(message, {
95
+ status: 404,
96
+ headers: {
97
+ "content-type": "text/plain; charset=utf-8",
98
+ },
99
+ });
100
+ }
101
+
102
+ function listThemesState() {
103
+ const site = getSiteSettings();
104
+ const rows = db
105
+ .select()
106
+ .from(schema.themes)
107
+ .orderBy(asc(schema.themes.id))
108
+ .all();
109
+
110
+ return {
111
+ site,
112
+ activeTheme: site.active_theme,
113
+ themes: rows.map((row) => ({
114
+ id: row.id,
115
+ slug: row.slug,
116
+ name: row.name,
117
+ version: row.version,
118
+ author: row.author,
119
+ config: safeJsonObject(row.config_json),
120
+ customSettings: safeStringRecord(row.custom_settings_json),
121
+ active: row.slug === site.active_theme,
122
+ created_at: row.created_at,
123
+ })),
124
+ };
125
+ }
126
+
127
+ function getPublicCategories(): SiteCategoryItem[] {
128
+ const cats = db
129
+ .select({
130
+ id: schema.categories.id,
131
+ name: schema.categories.name,
132
+ slug: schema.categories.slug,
133
+ })
134
+ .from(schema.categories)
135
+ .orderBy(asc(schema.categories.name))
136
+ .all();
137
+
138
+ const countsRows = db
139
+ .select({
140
+ category_id: schema.posts.category_id,
141
+ count: sql<number>`count(*)`,
142
+ })
143
+ .from(schema.posts)
144
+ .where(eq(schema.posts.status, "published"))
145
+ .groupBy(schema.posts.category_id)
146
+ .all();
147
+
148
+ const countMap = new Map<number, number>();
149
+ for (const row of countsRows) {
150
+ if (row.category_id !== null) {
151
+ countMap.set(row.category_id, Number(row.count));
152
+ }
153
+ }
154
+
155
+ return cats.map((cat) => ({
156
+ name: cat.name,
157
+ slug: cat.slug,
158
+ post_count: countMap.get(cat.id) ?? 0,
159
+ }));
160
+ }
161
+
162
+ async function renderPublicFeed(
163
+ request: Request,
164
+ options: {
165
+ searchQuery?: string;
166
+ categorySlug?: string;
167
+ pageParam?: string;
168
+ requireCategoryExists?: boolean;
169
+ },
170
+ ): Promise<Response> {
171
+ const site = getSiteSettings();
172
+ const currentUser = resolveCurrentUser(request);
173
+ const categories = getPublicCategories();
174
+
175
+ const rawCategorySlug = (options.categorySlug ?? "").trim();
176
+ const categoryRow = rawCategorySlug
177
+ ? db
178
+ .select()
179
+ .from(schema.categories)
180
+ .where(eq(schema.categories.slug, rawCategorySlug))
181
+ .get() ?? null
182
+ : null;
183
+
184
+ if (options.requireCategoryExists && !categoryRow) {
185
+ return notFoundResponse("Category not found");
186
+ }
187
+
188
+ const searchQuery = (options.searchQuery ?? "").trim().slice(0, 100);
189
+ const conditions: SQL[] = [eq(schema.posts.status, "published")];
190
+
191
+ if (categoryRow) {
192
+ conditions.push(eq(schema.posts.category_id, categoryRow.id));
193
+ } else if (rawCategorySlug) {
194
+ conditions.push(sql`1 = 0`);
195
+ }
196
+
197
+ if (searchQuery.length > 0) {
198
+ const escaped = searchQuery.replace(/[\\%_]/g, "\\$&");
199
+ const pattern = `%${escaped}%`;
200
+ const searchCond = or(
201
+ sql`${schema.posts.title} LIKE ${pattern} ESCAPE '\\'`,
202
+ sql`${schema.posts.excerpt} LIKE ${pattern} ESCAPE '\\'`,
203
+ sql`${schema.posts.content} LIKE ${pattern} ESCAPE '\\'`,
204
+ );
205
+ if (searchCond) {
206
+ conditions.push(searchCond);
207
+ }
208
+ }
209
+
210
+ const whereClause = and(...conditions);
211
+ const perPage = Math.max(1, Math.min(50, site.posts_per_page || 10));
212
+ const totalPosts = Number(
213
+ db
214
+ .select({ count: sql<number>`count(*)` })
215
+ .from(schema.posts)
216
+ .where(whereClause)
217
+ .get()?.count ?? 0,
218
+ );
219
+
220
+ const totalPages = Math.max(1, Math.ceil(totalPosts / perPage));
221
+ const requestedPage = Number.parseInt(options.pageParam ?? "1", 10);
222
+ const currentPage =
223
+ Number.isFinite(requestedPage) && requestedPage >= 1
224
+ ? Math.min(requestedPage, totalPages)
225
+ : 1;
226
+ const offset = (currentPage - 1) * perPage;
227
+
228
+ const rows = db
229
+ .select({
230
+ id: schema.posts.id,
231
+ slug: schema.posts.slug,
232
+ title: schema.posts.title,
233
+ content: schema.posts.content,
234
+ excerpt: schema.posts.excerpt,
235
+ featured_image: schema.posts.featured_image,
236
+ status: schema.posts.status,
237
+ created_at: schema.posts.created_at,
238
+ category_name: schema.categories.name,
239
+ category_slug: schema.categories.slug,
240
+ author_name: schema.users.name,
241
+ })
242
+ .from(schema.posts)
243
+ .leftJoin(schema.categories, eq(schema.posts.category_id, schema.categories.id))
244
+ .leftJoin(schema.users, eq(schema.posts.author_id, schema.users.id))
245
+ .where(whereClause)
246
+ .orderBy(desc(schema.posts.created_at), desc(schema.posts.id))
247
+ .limit(perPage)
248
+ .offset(offset)
249
+ .all();
250
+
251
+ const posts: PostTemplateItem[] = rows.map((row) => ({
252
+ id: row.id,
253
+ slug: row.slug,
254
+ title: row.title,
255
+ content: row.content,
256
+ excerpt: row.excerpt,
257
+ featured_image: row.featured_image,
258
+ category_name: row.category_name ?? undefined,
259
+ category_slug: row.category_slug ?? undefined,
260
+ author_name: row.author_name ?? undefined,
261
+ status: row.status,
262
+ created_at: row.created_at,
263
+ }));
264
+
265
+ const pageTitle = categoryRow
266
+ ? `${categoryRow.name} — ${site.site_title}`
267
+ : searchQuery
268
+ ? `Search: ${searchQuery} — ${site.site_title}`
269
+ : site.site_title;
270
+
271
+ const html = await renderThemePage(site.active_theme, "home", {
272
+ site: {
273
+ title: site.site_title,
274
+ tagline: site.site_tagline,
275
+ logo: site.site_logo,
276
+ favicon: site.favicon,
277
+ seo_default_desc: site.seo_default_desc,
278
+ active_theme: site.active_theme,
279
+ categories,
280
+ user: currentUser ? { name: currentUser.name, role: currentUser.role } : null,
281
+ },
282
+ page: {
283
+ title: pageTitle,
284
+ meta_description: categoryRow?.description || site.seo_default_desc,
285
+ ...(searchQuery ? { search_query: searchQuery } : {}),
286
+ current_category: categoryRow
287
+ ? {
288
+ name: categoryRow.name,
289
+ slug: categoryRow.slug,
290
+ description: categoryRow.description,
291
+ }
292
+ : null,
293
+ pagination: {
294
+ page: currentPage,
295
+ per_page: perPage,
296
+ total_posts: totalPosts,
297
+ total_pages: totalPages,
298
+ has_prev: currentPage > 1,
299
+ has_next: currentPage < totalPages,
300
+ prev_page: currentPage > 1 ? currentPage - 1 : null,
301
+ next_page: currentPage < totalPages ? currentPage + 1 : null,
302
+ },
303
+ },
304
+ posts,
305
+ });
306
+
307
+ return htmlResponse(html);
308
+ }
309
+
310
+ function requireAdminSession(
311
+ request: Request,
312
+ set: { status?: number | string },
313
+ ): { ok: true } | { ok: false; body: { success: false; errors: string[] } } {
314
+ const user = resolveCurrentUser(request);
315
+ if (!user) {
316
+ set.status = 401;
317
+ return { ok: false, body: { success: false, errors: ["Authentication required."] } };
318
+ }
319
+ if (user.role !== "admin") {
320
+ set.status = 403;
321
+ return {
322
+ ok: false,
323
+ body: { success: false, errors: ["Forbidden: admin role required."] },
324
+ };
325
+ }
326
+ return { ok: true };
327
+ }
328
+
329
+ /**
330
+ * Initialize the SQLite database and build the Elysia application instance.
331
+ */
332
+ export function createApp() {
333
+ initializeDatabase();
334
+
335
+ return new Elysia()
336
+ .onError(({ code, error, set }) => {
337
+ if (code === "VALIDATION") {
338
+ set.status = 400;
339
+ const errors = error.all.map((item) => {
340
+ const field = item.path?.replace(/^\//, "");
341
+ return field ? `${field}: ${item.message}` : item.message;
342
+ });
343
+ return {
344
+ success: false,
345
+ errors: errors.length > 0 ? errors : ["Validation error."],
346
+ };
347
+ }
348
+ if (code === "PARSE") {
349
+ set.status = 400;
350
+ return {
351
+ success: false,
352
+ errors: ["Invalid request body."],
353
+ };
354
+ }
355
+ })
356
+ .use(authRoutes)
357
+ .use(adminPageRoutes)
358
+ .use(adminApiRoutes)
359
+ .use(publicUploadsRoute)
360
+ .use(postsRoutes)
361
+ .get("/health", ({ set }) => {
362
+ const dbOk = isDatabaseHealthy();
363
+ if (!dbOk) {
364
+ set.status = 503;
365
+ return {
366
+ status: "error",
367
+ database: "disconnected",
368
+ timestamp: new Date().toISOString(),
369
+ };
370
+ }
371
+
372
+ return {
373
+ status: "ok",
374
+ database: "connected",
375
+ timestamp: new Date().toISOString(),
376
+ };
377
+ })
378
+ .get("/", async ({ query, request }) => {
379
+ return renderPublicFeed(request, {
380
+ searchQuery: typeof query.q === "string" ? query.q : undefined,
381
+ categorySlug: typeof query.category === "string" ? query.category : undefined,
382
+ pageParam: typeof query.page === "string" ? query.page : undefined,
383
+ });
384
+ })
385
+ .get("/category/:slug", async ({ params, query, request }) => {
386
+ return renderPublicFeed(request, {
387
+ searchQuery: typeof query.q === "string" ? query.q : undefined,
388
+ categorySlug: params.slug,
389
+ pageParam: typeof query.page === "string" ? query.page : undefined,
390
+ requireCategoryExists: true,
391
+ });
392
+ })
393
+ .get("/post/:slug", async ({ params, request }) => {
394
+ const site = getSiteSettings();
395
+ const currentUser = resolveCurrentUser(request);
396
+ const categories = getPublicCategories();
397
+ const post = db
398
+ .select({
399
+ id: schema.posts.id,
400
+ slug: schema.posts.slug,
401
+ title: schema.posts.title,
402
+ content: schema.posts.content,
403
+ excerpt: schema.posts.excerpt,
404
+ featured_image: schema.posts.featured_image,
405
+ meta_title: schema.posts.meta_title,
406
+ meta_description: schema.posts.meta_description,
407
+ status: schema.posts.status,
408
+ created_at: schema.posts.created_at,
409
+ category_name: schema.categories.name,
410
+ category_slug: schema.categories.slug,
411
+ author_name: schema.users.name,
412
+ })
413
+ .from(schema.posts)
414
+ .leftJoin(schema.categories, eq(schema.posts.category_id, schema.categories.id))
415
+ .leftJoin(schema.users, eq(schema.posts.author_id, schema.users.id))
416
+ .where(
417
+ and(
418
+ eq(schema.posts.slug, params.slug),
419
+ eq(schema.posts.status, "published"),
420
+ ),
421
+ )
422
+ .get();
423
+
424
+ if (!post) {
425
+ return notFoundResponse("Post not found");
426
+ }
427
+
428
+ const html = await renderThemePage(site.active_theme, "post", {
429
+ site: {
430
+ title: site.site_title,
431
+ tagline: site.site_tagline,
432
+ logo: site.site_logo,
433
+ favicon: site.favicon,
434
+ seo_default_desc: site.seo_default_desc,
435
+ active_theme: site.active_theme,
436
+ categories,
437
+ user: currentUser ? { name: currentUser.name, role: currentUser.role } : null,
438
+ },
439
+ page: {
440
+ title: post.title,
441
+ slug: post.slug,
442
+ content: post.content,
443
+ excerpt: post.excerpt,
444
+ featured_image: post.featured_image,
445
+ meta_title: post.meta_title || post.title,
446
+ meta_description: post.meta_description || post.excerpt || site.seo_default_desc,
447
+ status: post.status,
448
+ created_at: post.created_at,
449
+ category_name: post.category_name ?? undefined,
450
+ category_slug: post.category_slug ?? undefined,
451
+ author_name: post.author_name ?? undefined,
452
+ },
453
+ posts: [],
454
+ });
455
+
456
+ return htmlResponse(html);
457
+ })
458
+ .get("/themes/:slug/assets/*", ({ params }) => {
459
+ const assetPath = resolveThemeAssetPath(params.slug, params["*"] ?? "");
460
+ if (!assetPath) {
461
+ return notFoundResponse("Asset not found");
462
+ }
463
+
464
+ const file = Bun.file(assetPath);
465
+ return new Response(file, {
466
+ headers: {
467
+ "content-type": file.type || "application/octet-stream",
468
+ "x-content-type-options": "nosniff",
469
+ },
470
+ });
471
+ })
472
+ .get("/api/themes", ({ set }) => {
473
+ set.headers["cache-control"] = "no-store, no-cache, must-revalidate";
474
+ const { activeTheme, themes } = listThemesState();
475
+ return { activeTheme, themes };
476
+ })
477
+ .post("/api/themes/upload", async ({ body, request, set }) => {
478
+ const guard = requireAdminSession(request, set);
479
+ if (!guard.ok) return guard.body;
480
+
481
+ const uploaded = extractUploadedFile(body);
482
+ if (!uploaded) {
483
+ set.status = 400;
484
+ return {
485
+ success: false,
486
+ errors: ["Missing .zip file upload in multipart/form-data request."],
487
+ };
488
+ }
489
+
490
+ if (uploaded.size > MAX_THEME_ZIP_BYTES) {
491
+ set.status = 400;
492
+ return {
493
+ success: false,
494
+ errors: [
495
+ `Zip archive exceeds maximum allowed size of 10MB (${MAX_THEME_ZIP_BYTES} bytes).`,
496
+ ],
497
+ };
498
+ }
499
+
500
+ const zipBytes = new Uint8Array(await uploaded.arrayBuffer());
501
+ const result = validateAndInstallThemeZip(zipBytes);
502
+ if (!result.valid) {
503
+ set.status = 400;
504
+ return {
505
+ success: false,
506
+ errors: result.errors,
507
+ };
508
+ }
509
+
510
+ set.status = 201;
511
+ return {
512
+ success: true,
513
+ theme: result.theme,
514
+ };
515
+ })
516
+ .post("/api/themes/:slug/activate", ({ params, request, set }) => {
517
+ const guard = requireAdminSession(request, set);
518
+ if (!guard.ok) return guard.body;
519
+
520
+ const slug = params.slug;
521
+ if (!THEME_SLUG_REGEX.test(slug)) {
522
+ set.status = 400;
523
+ return { success: false, errors: [`Invalid theme slug "${slug}".`] };
524
+ }
525
+
526
+ const row = db
527
+ .select()
528
+ .from(schema.themes)
529
+ .where(eq(schema.themes.slug, slug))
530
+ .get();
531
+
532
+ if (!row) {
533
+ set.status = 404;
534
+ return { success: false, errors: [`Theme "${slug}" is not installed.`] };
535
+ }
536
+
537
+ try {
538
+ resolveThemeDirectory(slug);
539
+ } catch {
540
+ set.status = 404;
541
+ return { success: false, errors: [`Theme directory for "${slug}" was not found.`] };
542
+ }
543
+
544
+ const previous = getSiteSettings().active_theme;
545
+
546
+ db.insert(schema.settings)
547
+ .values({ key: "active_theme", value: slug })
548
+ .onConflictDoUpdate({
549
+ target: schema.settings.key,
550
+ set: { value: slug },
551
+ })
552
+ .run();
553
+
554
+ clearSiteSettingsCache();
555
+ clearThemeCache(previous);
556
+ clearThemeCache(slug);
557
+
558
+ return {
559
+ success: true,
560
+ activeTheme: slug,
561
+ };
562
+ })
563
+ .post("/api/themes/:slug/settings", ({ params, body, request, set }) => {
564
+ const guard = requireAdminSession(request, set);
565
+ if (!guard.ok) return guard.body;
566
+
567
+ const slug = params.slug;
568
+ if (!THEME_SLUG_REGEX.test(slug)) {
569
+ set.status = 400;
570
+ return { success: false, errors: [`Invalid theme slug "${slug}".`] };
571
+ }
572
+
573
+ const row = db
574
+ .select()
575
+ .from(schema.themes)
576
+ .where(eq(schema.themes.slug, slug))
577
+ .get();
578
+
579
+ if (!row) {
580
+ set.status = 404;
581
+ return { success: false, errors: [`Theme "${slug}" is not installed.`] };
582
+ }
583
+
584
+ const config = parseThemeConfig(safeJsonObject(row.config_json));
585
+ const existingOverrides = safeStringRecord(row.custom_settings_json);
586
+ const validation = validateThemeSettingsOverrides(config, body, existingOverrides);
587
+
588
+ if (!validation.valid) {
589
+ set.status = 400;
590
+ return {
591
+ success: false,
592
+ errors: validation.errors,
593
+ };
594
+ }
595
+
596
+ const serialized = JSON.stringify(validation.customSettings);
597
+ db.update(schema.themes)
598
+ .set({ custom_settings_json: serialized })
599
+ .where(eq(schema.themes.slug, slug))
600
+ .run();
601
+
602
+ clearThemeCache(slug);
603
+
604
+ return {
605
+ success: true,
606
+ slug,
607
+ customSettings: validation.customSettings,
608
+ resolvedSettings: mergeThemeSettings(config, serialized),
609
+ };
610
+ })
611
+ .get("/api/ai/spec", () => getAiThemeSpec())
612
+ .post(
613
+ "/api/ai/generate-theme",
614
+ async ({ body, set }) => {
615
+ if (!getSiteSettings().ai_enabled) {
616
+ set.status = 403;
617
+ return {
618
+ success: false,
619
+ errors: ["AI theme generation is disabled in Settings."],
620
+ };
621
+ }
622
+
623
+ const validated = validateGenerationRequest(body);
624
+ if (!validated.valid || !validated.parsed) {
625
+ set.status = 400;
626
+ return {
627
+ success: false,
628
+ errors: validated.errors,
629
+ };
630
+ }
631
+
632
+ try {
633
+ const result = await generateAndInstallTheme(validated.parsed);
634
+ if (!result.success) {
635
+ set.status = 422;
636
+ return result;
637
+ }
638
+
639
+ set.status = 201;
640
+ return result;
641
+ } catch (err) {
642
+ if (err instanceof AiConfigurationError) {
643
+ set.status = 503;
644
+ return { success: false, errors: [err.message] };
645
+ }
646
+ if (err instanceof AiProviderError) {
647
+ set.status = 502;
648
+ return { success: false, errors: [err.message] };
649
+ }
650
+ throw err;
651
+ }
652
+ },
653
+ {
654
+ body: t.Object({
655
+ prompt: t.String({ minLength: 1 }),
656
+ slug: t.String({ pattern: THEME_SLUG_PATTERN }),
657
+ }),
658
+ },
659
+ );
660
+ }
661
+
662
+ export const app = createApp();
663
+
664
+ if (import.meta.main) {
665
+ const configuredPort = Number(process.env.PORT ?? 3000);
666
+ const port = Number.isFinite(configuredPort) && configuredPort >= 0 ? configuredPort : 3000;
667
+
668
+ app.listen(port);
669
+ console.log(
670
+ `Server listening at http://${app.server?.hostname ?? "localhost"}:${app.server?.port ?? port}`,
671
+ );
672
+ }