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.
- package/LICENSE +21 -0
- package/README.md +57 -2
- package/drizzle/0000_lonely_reptil.sql +27 -0
- package/drizzle/0001_misty_wendigo.sql +74 -0
- package/drizzle/meta/0000_snapshot.json +179 -0
- package/drizzle/meta/0001_snapshot.json +492 -0
- package/drizzle/meta/_journal.json +20 -0
- package/package.json +55 -4
- package/src/admin/auth.ts +851 -0
- package/src/admin/layout.ts +419 -0
- package/src/admin/pages/categories.ts +223 -0
- package/src/admin/pages/dashboard.ts +192 -0
- package/src/admin/pages/media.ts +270 -0
- package/src/admin/pages/posts.ts +804 -0
- package/src/admin/pages/settings.ts +169 -0
- package/src/admin/pages/themes.ts +461 -0
- package/src/admin/pages/users.ts +501 -0
- package/src/admin/routes.ts +455 -0
- package/src/admin/tiptap-bundle.ts +48 -0
- package/src/admin/tiptap-entry.ts +226 -0
- package/src/ai/generator.ts +296 -0
- package/src/ai/index.ts +22 -0
- package/src/ai/schema.ts +13 -0
- package/src/ai/spec.ts +193 -0
- package/src/cli.ts +151 -0
- package/src/db/index.ts +278 -0
- package/src/db/schema.ts +115 -0
- package/src/engine/index.ts +52 -0
- package/src/engine/renderer.ts +533 -0
- package/src/engine/sandbox.ts +108 -0
- package/src/engine/schema.ts +71 -0
- package/src/engine/validator.ts +404 -0
- package/src/routes/admin-api.ts +1035 -0
- package/src/routes/posts.ts +294 -0
- package/src/routes/uploads.ts +119 -0
- package/src/server.ts +672 -0
- package/src/utils/sanitize-html.ts +145 -0
- package/themes/.gitkeep +1 -0
- package/themes/default/assets/style.css +799 -0
- package/themes/default/layouts/base.liquid +31 -0
- package/themes/default/layouts/home.liquid +180 -0
- package/themes/default/layouts/page.liquid +21 -0
- package/themes/default/layouts/post.liquid +55 -0
- package/themes/default/partials/footer.liquid +33 -0
- package/themes/default/partials/navbar.liquid +49 -0
- package/themes/default/theme.json +59 -0
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
/// <reference lib="dom" />
|
|
2
|
+
|
|
3
|
+
import { Editor } from "@tiptap/core";
|
|
4
|
+
import Image from "@tiptap/extension-image";
|
|
5
|
+
import Placeholder from "@tiptap/extension-placeholder";
|
|
6
|
+
import StarterKit from "@tiptap/starter-kit";
|
|
7
|
+
|
|
8
|
+
export interface TiptapToolbarState {
|
|
9
|
+
bold: boolean;
|
|
10
|
+
italic: boolean;
|
|
11
|
+
underline: boolean;
|
|
12
|
+
strike: boolean;
|
|
13
|
+
code: boolean;
|
|
14
|
+
paragraph: boolean;
|
|
15
|
+
heading1: boolean;
|
|
16
|
+
heading2: boolean;
|
|
17
|
+
heading3: boolean;
|
|
18
|
+
bulletList: boolean;
|
|
19
|
+
orderedList: boolean;
|
|
20
|
+
blockquote: boolean;
|
|
21
|
+
codeBlock: boolean;
|
|
22
|
+
link: boolean;
|
|
23
|
+
linkHref: string;
|
|
24
|
+
canUndo: boolean;
|
|
25
|
+
canRedo: boolean;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface CreateTiptapEditorOptions {
|
|
29
|
+
element: HTMLElement;
|
|
30
|
+
content: string;
|
|
31
|
+
placeholder?: string;
|
|
32
|
+
onUpdate?: (payload: { html: string; text: string }) => void;
|
|
33
|
+
onStateChange?: (state: TiptapToolbarState) => void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface CmsTiptapHandle {
|
|
37
|
+
getHTML: () => string;
|
|
38
|
+
getText: () => string;
|
|
39
|
+
setContent: (html: string) => void;
|
|
40
|
+
focus: () => void;
|
|
41
|
+
toggleBold: () => void;
|
|
42
|
+
toggleItalic: () => void;
|
|
43
|
+
toggleUnderline: () => void;
|
|
44
|
+
toggleStrike: () => void;
|
|
45
|
+
toggleCode: () => void;
|
|
46
|
+
setParagraph: () => void;
|
|
47
|
+
toggleHeading: (level: 1 | 2 | 3) => void;
|
|
48
|
+
toggleBulletList: () => void;
|
|
49
|
+
toggleOrderedList: () => void;
|
|
50
|
+
toggleBlockquote: () => void;
|
|
51
|
+
toggleCodeBlock: () => void;
|
|
52
|
+
setHorizontalRule: () => void;
|
|
53
|
+
clearFormatting: () => void;
|
|
54
|
+
setLink: (url: string) => void;
|
|
55
|
+
unsetLink: () => void;
|
|
56
|
+
insertImage: (src: string, alt?: string) => void;
|
|
57
|
+
undo: () => void;
|
|
58
|
+
redo: () => void;
|
|
59
|
+
getState: () => TiptapToolbarState;
|
|
60
|
+
destroy: () => void;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function readToolbarState(editor: Editor): TiptapToolbarState {
|
|
64
|
+
const linkAttrs = editor.getAttributes("link") as { href?: unknown };
|
|
65
|
+
return {
|
|
66
|
+
bold: editor.isActive("bold"),
|
|
67
|
+
italic: editor.isActive("italic"),
|
|
68
|
+
underline: editor.isActive("underline"),
|
|
69
|
+
strike: editor.isActive("strike"),
|
|
70
|
+
code: editor.isActive("code"),
|
|
71
|
+
paragraph: editor.isActive("paragraph"),
|
|
72
|
+
heading1: editor.isActive("heading", { level: 1 }),
|
|
73
|
+
heading2: editor.isActive("heading", { level: 2 }),
|
|
74
|
+
heading3: editor.isActive("heading", { level: 3 }),
|
|
75
|
+
bulletList: editor.isActive("bulletList"),
|
|
76
|
+
orderedList: editor.isActive("orderedList"),
|
|
77
|
+
blockquote: editor.isActive("blockquote"),
|
|
78
|
+
codeBlock: editor.isActive("codeBlock"),
|
|
79
|
+
link: editor.isActive("link"),
|
|
80
|
+
linkHref: typeof linkAttrs.href === "string" ? linkAttrs.href : "",
|
|
81
|
+
canUndo: editor.can().undo(),
|
|
82
|
+
canRedo: editor.can().redo(),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function createEditor(options: CreateTiptapEditorOptions): CmsTiptapHandle {
|
|
87
|
+
const notifyState = (instance: Editor) => {
|
|
88
|
+
options.onStateChange?.(readToolbarState(instance));
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const editor = new Editor({
|
|
92
|
+
element: options.element,
|
|
93
|
+
content: options.content || "",
|
|
94
|
+
extensions: [
|
|
95
|
+
StarterKit.configure({
|
|
96
|
+
heading: {
|
|
97
|
+
levels: [1, 2, 3],
|
|
98
|
+
},
|
|
99
|
+
link: {
|
|
100
|
+
openOnClick: false,
|
|
101
|
+
autolink: true,
|
|
102
|
+
defaultProtocol: "https",
|
|
103
|
+
HTMLAttributes: {
|
|
104
|
+
rel: "noopener noreferrer",
|
|
105
|
+
},
|
|
106
|
+
},
|
|
107
|
+
}),
|
|
108
|
+
Image.configure({
|
|
109
|
+
inline: false,
|
|
110
|
+
allowBase64: false,
|
|
111
|
+
}),
|
|
112
|
+
Placeholder.configure({
|
|
113
|
+
placeholder: options.placeholder || "Write your post content...",
|
|
114
|
+
}),
|
|
115
|
+
],
|
|
116
|
+
editorProps: {
|
|
117
|
+
attributes: {
|
|
118
|
+
class: "tiptap-prose focus:outline-none min-h-[320px] px-4 py-3 text-sm text-slate-800",
|
|
119
|
+
},
|
|
120
|
+
},
|
|
121
|
+
onCreate({ editor: instance }) {
|
|
122
|
+
notifyState(instance);
|
|
123
|
+
},
|
|
124
|
+
onUpdate({ editor: instance }) {
|
|
125
|
+
const html = instance.isEmpty ? "" : instance.getHTML();
|
|
126
|
+
options.onUpdate?.({
|
|
127
|
+
html,
|
|
128
|
+
text: instance.getText({ blockSeparator: " " }),
|
|
129
|
+
});
|
|
130
|
+
notifyState(instance);
|
|
131
|
+
},
|
|
132
|
+
onSelectionUpdate({ editor: instance }) {
|
|
133
|
+
notifyState(instance);
|
|
134
|
+
},
|
|
135
|
+
onTransaction({ editor: instance }) {
|
|
136
|
+
notifyState(instance);
|
|
137
|
+
},
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
return {
|
|
141
|
+
getHTML: () => (editor.isEmpty ? "" : editor.getHTML()),
|
|
142
|
+
getText: () => editor.getText({ blockSeparator: " " }),
|
|
143
|
+
setContent: (html: string) => {
|
|
144
|
+
editor.commands.setContent(html || "", { emitUpdate: false });
|
|
145
|
+
notifyState(editor);
|
|
146
|
+
},
|
|
147
|
+
focus: () => {
|
|
148
|
+
editor.chain().focus().run();
|
|
149
|
+
},
|
|
150
|
+
toggleBold: () => {
|
|
151
|
+
editor.chain().focus().toggleBold().run();
|
|
152
|
+
},
|
|
153
|
+
toggleItalic: () => {
|
|
154
|
+
editor.chain().focus().toggleItalic().run();
|
|
155
|
+
},
|
|
156
|
+
toggleUnderline: () => {
|
|
157
|
+
editor.chain().focus().toggleUnderline().run();
|
|
158
|
+
},
|
|
159
|
+
toggleStrike: () => {
|
|
160
|
+
editor.chain().focus().toggleStrike().run();
|
|
161
|
+
},
|
|
162
|
+
toggleCode: () => {
|
|
163
|
+
editor.chain().focus().toggleCode().run();
|
|
164
|
+
},
|
|
165
|
+
setParagraph: () => {
|
|
166
|
+
editor.chain().focus().setParagraph().run();
|
|
167
|
+
},
|
|
168
|
+
toggleHeading: (level: 1 | 2 | 3) => {
|
|
169
|
+
editor.chain().focus().toggleHeading({ level }).run();
|
|
170
|
+
},
|
|
171
|
+
toggleBulletList: () => {
|
|
172
|
+
editor.chain().focus().toggleBulletList().run();
|
|
173
|
+
},
|
|
174
|
+
toggleOrderedList: () => {
|
|
175
|
+
editor.chain().focus().toggleOrderedList().run();
|
|
176
|
+
},
|
|
177
|
+
toggleBlockquote: () => {
|
|
178
|
+
editor.chain().focus().toggleBlockquote().run();
|
|
179
|
+
},
|
|
180
|
+
toggleCodeBlock: () => {
|
|
181
|
+
editor.chain().focus().toggleCodeBlock().run();
|
|
182
|
+
},
|
|
183
|
+
setHorizontalRule: () => {
|
|
184
|
+
editor.chain().focus().setHorizontalRule().run();
|
|
185
|
+
},
|
|
186
|
+
clearFormatting: () => {
|
|
187
|
+
editor.chain().focus().unsetAllMarks().clearNodes().run();
|
|
188
|
+
},
|
|
189
|
+
setLink: (url: string) => {
|
|
190
|
+
const trimmed = url.trim();
|
|
191
|
+
if (!trimmed) {
|
|
192
|
+
editor.chain().focus().extendMarkRange("link").unsetLink().run();
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
editor.chain().focus().extendMarkRange("link").setLink({ href: trimmed }).run();
|
|
196
|
+
},
|
|
197
|
+
unsetLink: () => {
|
|
198
|
+
editor.chain().focus().extendMarkRange("link").unsetLink().run();
|
|
199
|
+
},
|
|
200
|
+
insertImage: (src: string, alt?: string) => {
|
|
201
|
+
const trimmed = src.trim();
|
|
202
|
+
if (!trimmed) return;
|
|
203
|
+
editor.chain().focus().setImage({ src: trimmed, alt: alt || "" }).run();
|
|
204
|
+
},
|
|
205
|
+
undo: () => {
|
|
206
|
+
editor.chain().focus().undo().run();
|
|
207
|
+
},
|
|
208
|
+
redo: () => {
|
|
209
|
+
editor.chain().focus().redo().run();
|
|
210
|
+
},
|
|
211
|
+
getState: () => readToolbarState(editor),
|
|
212
|
+
destroy: () => {
|
|
213
|
+
editor.destroy();
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
declare global {
|
|
219
|
+
interface Window {
|
|
220
|
+
CmsTiptap?: {
|
|
221
|
+
createEditor: typeof createEditor;
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
window.CmsTiptap = { createEditor };
|
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { strToU8, zipSync, type Zippable } from "fflate";
|
|
2
|
+
import { getSiteSettings } from "../db";
|
|
3
|
+
import {
|
|
4
|
+
THEME_SLUG_PATTERN,
|
|
5
|
+
validateAndInstallThemeZip,
|
|
6
|
+
type InstalledThemeSummary,
|
|
7
|
+
} from "../engine";
|
|
8
|
+
import type {
|
|
9
|
+
GeneratedThemeFilesMap,
|
|
10
|
+
LlmCompletionFn,
|
|
11
|
+
LlmMessage,
|
|
12
|
+
ThemeGenerationRequest,
|
|
13
|
+
} from "./schema";
|
|
14
|
+
import { buildThemeGeneratorSystemPrompt } from "./spec";
|
|
15
|
+
|
|
16
|
+
const THEME_SLUG_REGEX = new RegExp(THEME_SLUG_PATTERN);
|
|
17
|
+
const DEFAULT_AI_BASE_URL = "https://api.openai.com/v1";
|
|
18
|
+
const DEFAULT_AI_MODEL = "gpt-4o-mini";
|
|
19
|
+
|
|
20
|
+
export class AiConfigurationError extends Error {
|
|
21
|
+
constructor(message: string) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.name = "AiConfigurationError";
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class AiProviderError extends Error {
|
|
28
|
+
constructor(message: string) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.name = "AiProviderError";
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ThemeGenerationResult {
|
|
35
|
+
success: boolean;
|
|
36
|
+
attempts: number;
|
|
37
|
+
errors: string[];
|
|
38
|
+
theme?: InstalledThemeSummary;
|
|
39
|
+
files?: string[];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface ThemeGeneratorOptions {
|
|
43
|
+
complete?: LlmCompletionFn;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Strip optional Markdown code fences around JSON responses from an LLM.
|
|
48
|
+
*/
|
|
49
|
+
function stripCodeFences(raw: string): string {
|
|
50
|
+
const trimmed = raw.trim();
|
|
51
|
+
const fenceMatch = trimmed.match(/^```(?:json)?\s*\r?\n([\s\S]*?)\r?\n```$/i);
|
|
52
|
+
return fenceMatch?.[1] ? fenceMatch[1].trim() : trimmed;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function parseFileMapResponse(rawText: string): {
|
|
56
|
+
files?: GeneratedThemeFilesMap;
|
|
57
|
+
errors: string[];
|
|
58
|
+
} {
|
|
59
|
+
const cleaned = stripCodeFences(rawText);
|
|
60
|
+
let parsed: unknown;
|
|
61
|
+
try {
|
|
62
|
+
parsed = JSON.parse(cleaned);
|
|
63
|
+
} catch (err) {
|
|
64
|
+
const detail = err instanceof Error ? err.message : "Invalid JSON";
|
|
65
|
+
return { errors: [`LLM output is not valid JSON: ${detail}`] };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
69
|
+
return { errors: ["LLM output must be a JSON object mapping filepath to string content."] };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const entries = Object.entries(parsed as Record<string, unknown>);
|
|
73
|
+
if (entries.length === 0) {
|
|
74
|
+
return { errors: ["LLM output file map cannot be empty."] };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const fileMap: GeneratedThemeFilesMap = {};
|
|
78
|
+
const errors: string[] = [];
|
|
79
|
+
|
|
80
|
+
for (const [filepath, content] of entries) {
|
|
81
|
+
if (!filepath || filepath.endsWith("/")) {
|
|
82
|
+
errors.push(`Invalid file path "${filepath}": file paths cannot be empty or end with "/".`);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (typeof content !== "string") {
|
|
86
|
+
errors.push(`Content for "${filepath}" must be a UTF-8 string.`);
|
|
87
|
+
continue;
|
|
88
|
+
}
|
|
89
|
+
fileMap[filepath] = content;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (errors.length > 0) {
|
|
93
|
+
return { errors };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return { files: fileMap, errors: [] };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function packageAndValidateGeneratedTheme(
|
|
100
|
+
fileMap: GeneratedThemeFilesMap,
|
|
101
|
+
expectedSlug: string,
|
|
102
|
+
): { valid: boolean; errors: string[]; theme?: InstalledThemeSummary } {
|
|
103
|
+
if (Object.hasOwn(fileMap, "theme.json")) {
|
|
104
|
+
try {
|
|
105
|
+
const manifest = JSON.parse(fileMap["theme.json"]!) as { slug?: unknown };
|
|
106
|
+
if (manifest && typeof manifest === "object" && manifest.slug !== expectedSlug) {
|
|
107
|
+
return {
|
|
108
|
+
valid: false,
|
|
109
|
+
errors: [
|
|
110
|
+
`theme.json "slug" must be "${expectedSlug}", received "${String(manifest.slug ?? "")}".`,
|
|
111
|
+
],
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
} catch {
|
|
115
|
+
// Let validateAndInstallThemeZip report the exact JSON parse error.
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const zippable: Zippable = {};
|
|
120
|
+
for (const [filepath, content] of Object.entries(fileMap)) {
|
|
121
|
+
zippable[filepath] = strToU8(content);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const zipBytes = zipSync(zippable);
|
|
125
|
+
return validateAndInstallThemeZip(zipBytes);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Call an OpenAI-compatible chat completions endpoint using AI_API_KEY.
|
|
130
|
+
*/
|
|
131
|
+
export async function completeWithOpenAiCompatible(messages: LlmMessage[]): Promise<string> {
|
|
132
|
+
const apiKey = process.env.AI_API_KEY?.trim();
|
|
133
|
+
if (!apiKey) {
|
|
134
|
+
throw new AiConfigurationError(
|
|
135
|
+
"AI_API_KEY environment variable is not configured.",
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const baseUrl = (process.env.AI_BASE_URL?.trim() || DEFAULT_AI_BASE_URL).replace(/\/+$/, "");
|
|
140
|
+
const configuredModel = getSiteSettings().ai_model;
|
|
141
|
+
const model = process.env.AI_MODEL?.trim() || configuredModel || DEFAULT_AI_MODEL;
|
|
142
|
+
|
|
143
|
+
let response: Response;
|
|
144
|
+
try {
|
|
145
|
+
response = await fetch(`${baseUrl}/chat/completions`, {
|
|
146
|
+
method: "POST",
|
|
147
|
+
headers: {
|
|
148
|
+
"content-type": "application/json",
|
|
149
|
+
authorization: `Bearer ${apiKey}`,
|
|
150
|
+
},
|
|
151
|
+
body: JSON.stringify({
|
|
152
|
+
model,
|
|
153
|
+
messages,
|
|
154
|
+
temperature: 0.4,
|
|
155
|
+
response_format: { type: "json_object" },
|
|
156
|
+
}),
|
|
157
|
+
});
|
|
158
|
+
} catch (err) {
|
|
159
|
+
const message = err instanceof Error ? err.message : "Network failure";
|
|
160
|
+
throw new AiProviderError(`Failed to reach LLM provider: ${message}`);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
if (!response.ok) {
|
|
164
|
+
const errorBody = await response.text().catch(() => "");
|
|
165
|
+
throw new AiProviderError(
|
|
166
|
+
`LLM provider returned HTTP ${response.status}: ${errorBody.slice(0, 300)}`,
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const payload = (await response.json()) as {
|
|
171
|
+
choices?: Array<{ message?: { content?: unknown } }>;
|
|
172
|
+
};
|
|
173
|
+
const content = payload.choices?.[0]?.message?.content;
|
|
174
|
+
if (typeof content !== "string" || !content.trim()) {
|
|
175
|
+
throw new AiProviderError("LLM provider returned an empty completion.");
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
return content;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Validate generation request input fields.
|
|
183
|
+
*/
|
|
184
|
+
export function validateGenerationRequest(request: unknown): {
|
|
185
|
+
valid: boolean;
|
|
186
|
+
errors: string[];
|
|
187
|
+
parsed?: ThemeGenerationRequest;
|
|
188
|
+
} {
|
|
189
|
+
if (!request || typeof request !== "object" || Array.isArray(request)) {
|
|
190
|
+
return { valid: false, errors: ["Request body must be a JSON object."] };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const raw = request as Record<string, unknown>;
|
|
194
|
+
const errors: string[] = [];
|
|
195
|
+
|
|
196
|
+
const prompt = typeof raw.prompt === "string" ? raw.prompt.trim() : "";
|
|
197
|
+
if (!prompt) {
|
|
198
|
+
errors.push("Prompt is required and must be a non-empty string.");
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const slug = typeof raw.slug === "string" ? raw.slug.trim() : "";
|
|
202
|
+
if (!slug || !THEME_SLUG_REGEX.test(slug)) {
|
|
203
|
+
errors.push("Slug must be lowercase alphanumeric with hyphens only (^[a-z0-9]+(?:-[a-z0-9]+)*$).");
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (errors.length > 0) {
|
|
207
|
+
return { valid: false, errors };
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return { valid: true, errors: [], parsed: { prompt, slug } };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Generate a theme via LLM, zip in memory with fflate, validate via validator.ts,
|
|
215
|
+
* and perform one automatic self-correction pass if validation fails.
|
|
216
|
+
*/
|
|
217
|
+
export async function generateAndInstallTheme(
|
|
218
|
+
request: ThemeGenerationRequest,
|
|
219
|
+
options: ThemeGeneratorOptions = {},
|
|
220
|
+
): Promise<ThemeGenerationResult> {
|
|
221
|
+
const complete = options.complete ?? completeWithOpenAiCompatible;
|
|
222
|
+
const systemPrompt = buildThemeGeneratorSystemPrompt();
|
|
223
|
+
|
|
224
|
+
const messages: LlmMessage[] = [
|
|
225
|
+
{ role: "system", content: systemPrompt },
|
|
226
|
+
{
|
|
227
|
+
role: "user",
|
|
228
|
+
content: [
|
|
229
|
+
`Create a complete theme for slug "${request.slug}".`,
|
|
230
|
+
`Design prompt: ${request.prompt}`,
|
|
231
|
+
`Remember: theme.json must set "slug": "${request.slug}", include layouts/base.liquid, layouts/home.liquid, layouts/post.liquid, layouts/page.liquid, and assets/style.css referenced via /themes/${request.slug}/assets/style.css.`,
|
|
232
|
+
"Return ONLY the JSON object mapping filepath to string file content.",
|
|
233
|
+
].join("\n"),
|
|
234
|
+
},
|
|
235
|
+
];
|
|
236
|
+
|
|
237
|
+
const maxAttempts = 2;
|
|
238
|
+
let lastErrors: string[] = [];
|
|
239
|
+
|
|
240
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
241
|
+
const rawCompletion = await complete(messages);
|
|
242
|
+
const parsed = parseFileMapResponse(rawCompletion);
|
|
243
|
+
|
|
244
|
+
if (parsed.files) {
|
|
245
|
+
const validation = packageAndValidateGeneratedTheme(parsed.files, request.slug);
|
|
246
|
+
if (validation.valid && validation.theme) {
|
|
247
|
+
return {
|
|
248
|
+
success: true,
|
|
249
|
+
attempts: attempt,
|
|
250
|
+
errors: [],
|
|
251
|
+
theme: validation.theme,
|
|
252
|
+
files: Object.keys(parsed.files).sort(),
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
lastErrors = validation.errors;
|
|
256
|
+
} else {
|
|
257
|
+
lastErrors = parsed.errors;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
if (attempt < maxAttempts) {
|
|
261
|
+
messages.push(
|
|
262
|
+
{ role: "assistant", content: rawCompletion },
|
|
263
|
+
{
|
|
264
|
+
role: "user",
|
|
265
|
+
content: [
|
|
266
|
+
"Your generated theme failed validation with the following exact error(s):",
|
|
267
|
+
...lastErrors.map((err) => `- ${err}`),
|
|
268
|
+
"",
|
|
269
|
+
"Fix all reported issues and return ONLY the corrected JSON object mapping filepath to string file content.",
|
|
270
|
+
].join("\n"),
|
|
271
|
+
},
|
|
272
|
+
);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
return {
|
|
277
|
+
success: false,
|
|
278
|
+
attempts: maxAttempts,
|
|
279
|
+
errors: lastErrors,
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
export interface ThemeGenerator {
|
|
284
|
+
generate(request: ThemeGenerationRequest): Promise<ThemeGenerationResult>;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* Create an AI theme generator bound to an optional custom completion adapter.
|
|
289
|
+
*/
|
|
290
|
+
export function createThemeGenerator(options: ThemeGeneratorOptions = {}): ThemeGenerator {
|
|
291
|
+
return {
|
|
292
|
+
generate(request: ThemeGenerationRequest) {
|
|
293
|
+
return generateAndInstallTheme(request, options);
|
|
294
|
+
},
|
|
295
|
+
};
|
|
296
|
+
}
|
package/src/ai/index.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export {
|
|
2
|
+
AiConfigurationError,
|
|
3
|
+
AiProviderError,
|
|
4
|
+
completeWithOpenAiCompatible,
|
|
5
|
+
createThemeGenerator,
|
|
6
|
+
generateAndInstallTheme,
|
|
7
|
+
validateGenerationRequest,
|
|
8
|
+
type ThemeGenerator,
|
|
9
|
+
type ThemeGeneratorOptions,
|
|
10
|
+
type ThemeGenerationResult,
|
|
11
|
+
} from "./generator";
|
|
12
|
+
export type {
|
|
13
|
+
GeneratedThemeFilesMap,
|
|
14
|
+
LlmCompletionFn,
|
|
15
|
+
LlmMessage,
|
|
16
|
+
ThemeGenerationRequest,
|
|
17
|
+
} from "./schema";
|
|
18
|
+
export {
|
|
19
|
+
buildThemeGeneratorSystemPrompt,
|
|
20
|
+
getAiThemeSpec,
|
|
21
|
+
type AiThemeSpec,
|
|
22
|
+
} from "./spec";
|
package/src/ai/schema.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export interface ThemeGenerationRequest {
|
|
2
|
+
prompt: string;
|
|
3
|
+
slug: string;
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export interface LlmMessage {
|
|
7
|
+
role: "system" | "user" | "assistant";
|
|
8
|
+
content: string;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export type LlmCompletionFn = (messages: LlmMessage[]) => Promise<string>;
|
|
12
|
+
|
|
13
|
+
export type GeneratedThemeFilesMap = Record<string, string>;
|