ima2-gen 1.1.4 → 1.1.6
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/config.js +5 -0
- package/lib/assetLifecycle.js +21 -0
- package/lib/db.js +41 -3
- package/lib/generationErrors.js +24 -0
- package/lib/historyList.js +19 -1
- package/lib/imageMetadata.js +107 -0
- package/lib/imageMetadataStore.js +67 -0
- package/lib/nodeStore.js +13 -1
- package/lib/oauthProxy.js +387 -24
- package/lib/refs.js +65 -2
- package/package.json +1 -1
- package/routes/edit.js +1 -22
- package/routes/generate.js +35 -25
- package/routes/history.js +53 -2
- package/routes/index.js +6 -0
- package/routes/metadata.js +71 -0
- package/routes/multimode.js +264 -0
- package/routes/nodes.js +20 -26
- package/routes/prompts.js +379 -0
- package/ui/dist/assets/index-3X-6VjbF.css +1 -0
- package/ui/dist/assets/index-DPSq9qEs.js +31 -0
- package/ui/dist/assets/index-DPSq9qEs.js.map +1 -0
- package/ui/dist/index.html +2 -2
- package/ui/dist/assets/index-DHeTnSPD.css +0 -1
- package/ui/dist/assets/index-fDTlOt4w.js +0 -23
- package/ui/dist/assets/index-fDTlOt4w.js.map +0 -1
package/routes/nodes.js
CHANGED
|
@@ -13,8 +13,6 @@ import { normalizeOAuthParams } from "../lib/oauthNormalize.js";
|
|
|
13
13
|
import { normalizeImageModel } from "../lib/imageModels.js";
|
|
14
14
|
import { generateViaOAuth, editViaOAuth } from "../lib/oauthProxy.js";
|
|
15
15
|
import { isNonRetryableGenerationError, normalizeGenerationFailure } from "../lib/generationErrors.js";
|
|
16
|
-
import { getStyleSheet } from "../lib/sessionStore.js";
|
|
17
|
-
import { renderStyleSheetPrefix } from "../lib/styleSheet.js";
|
|
18
16
|
import { logEvent, logError } from "../lib/logger.js";
|
|
19
17
|
|
|
20
18
|
function validateModeration(ctx, moderation) {
|
|
@@ -87,7 +85,7 @@ export function registerNodeRoutes(app, ctx) {
|
|
|
87
85
|
externalSrc = null,
|
|
88
86
|
mode: promptMode = "auto",
|
|
89
87
|
contextMode: rawContextMode = "parent-plus-refs",
|
|
90
|
-
searchMode: rawSearchMode = "
|
|
88
|
+
searchMode: rawSearchMode = "on",
|
|
91
89
|
model: rawModel,
|
|
92
90
|
} = body;
|
|
93
91
|
const { provider = "oauth" } = body;
|
|
@@ -107,7 +105,7 @@ export function registerNodeRoutes(app, ctx) {
|
|
|
107
105
|
const contextMode = ["parent-plus-refs", "parent-only", "ancestry"].includes(rawContextMode)
|
|
108
106
|
? rawContextMode
|
|
109
107
|
: "parent-plus-refs";
|
|
110
|
-
const searchMode = ["off", "auto", "on"].includes(rawSearchMode) ? rawSearchMode : "
|
|
108
|
+
const searchMode = ["off", "auto", "on"].includes(rawSearchMode) ? rawSearchMode : "on";
|
|
111
109
|
if (contextMode === "ancestry") {
|
|
112
110
|
finishStatus = "error";
|
|
113
111
|
finishHttpStatus = 400;
|
|
@@ -158,21 +156,6 @@ export function registerNodeRoutes(app, ctx) {
|
|
|
158
156
|
});
|
|
159
157
|
}
|
|
160
158
|
|
|
161
|
-
let effectivePrompt = prompt;
|
|
162
|
-
let styleSheetApplied = null;
|
|
163
|
-
if (sessionId) {
|
|
164
|
-
try {
|
|
165
|
-
const data = getStyleSheet(sessionId);
|
|
166
|
-
if (data && data.enabled && data.styleSheet) {
|
|
167
|
-
const prefix = renderStyleSheetPrefix(data.styleSheet);
|
|
168
|
-
if (prefix) {
|
|
169
|
-
effectivePrompt = `${prefix} ${prompt}`.slice(0, 4000);
|
|
170
|
-
styleSheetApplied = data.styleSheet;
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
} catch {}
|
|
174
|
-
}
|
|
175
|
-
|
|
176
159
|
const startTime = Date.now();
|
|
177
160
|
let parentB64 = null;
|
|
178
161
|
if (parentNodeId) {
|
|
@@ -181,8 +164,11 @@ export function registerNodeRoutes(app, ctx) {
|
|
|
181
164
|
parentB64 = await loadAssetB64(ctx.rootDir, externalSrc, ctx.config.storage.generatedDir);
|
|
182
165
|
}
|
|
183
166
|
const operation = parentB64 ? "edit" : "generate";
|
|
184
|
-
const
|
|
185
|
-
const
|
|
167
|
+
const referenceDiagnostics = refCheck.referenceDiagnostics || [];
|
|
168
|
+
const generateReferenceDiagnostics = operation === "generate" ? referenceDiagnostics : [];
|
|
169
|
+
const referenceMismatchCount = generateReferenceDiagnostics.filter((ref) => ref.warnings?.includes("mime_mismatch")).length;
|
|
170
|
+
const refsForRequest = contextMode === "parent-only" ? [] : (refCheck.refDetails || refCheck.refs);
|
|
171
|
+
const webSearchEnabled = true;
|
|
186
172
|
const parentImagePresent = !!parentB64;
|
|
187
173
|
const inputImageCount = (parentImagePresent ? 1 : 0) + refsForRequest.length;
|
|
188
174
|
logEvent("node", "request", {
|
|
@@ -196,6 +182,9 @@ export function registerNodeRoutes(app, ctx) {
|
|
|
196
182
|
size,
|
|
197
183
|
moderation,
|
|
198
184
|
refs: refsForRequest.length,
|
|
185
|
+
referenceMismatchCount,
|
|
186
|
+
refDetectedMimes: [...new Set(generateReferenceDiagnostics.map((ref) => ref.detectedMime).filter(Boolean))].join(","),
|
|
187
|
+
refDeclaredMimes: [...new Set(generateReferenceDiagnostics.map((ref) => ref.declaredMime).filter(Boolean))].join(","),
|
|
199
188
|
inputImageCount,
|
|
200
189
|
parentImagePresent,
|
|
201
190
|
contextMode,
|
|
@@ -203,7 +192,6 @@ export function registerNodeRoutes(app, ctx) {
|
|
|
203
192
|
webSearchEnabled,
|
|
204
193
|
promptChars: prompt.length,
|
|
205
194
|
promptMode: normalizedPromptMode,
|
|
206
|
-
styleSheetApplied: !!styleSheetApplied,
|
|
207
195
|
});
|
|
208
196
|
|
|
209
197
|
if (streamResponse) {
|
|
@@ -239,9 +227,9 @@ export function registerNodeRoutes(app, ctx) {
|
|
|
239
227
|
webSearchEnabled,
|
|
240
228
|
});
|
|
241
229
|
const r = parentB64
|
|
242
|
-
? await editViaOAuth(
|
|
230
|
+
? await editViaOAuth(prompt, parentB64, quality, size, moderation, normalizedPromptMode, ctx, requestId, { model: imageModel, references: refsForRequest, searchMode: "on" })
|
|
243
231
|
: await generateViaOAuth(
|
|
244
|
-
|
|
232
|
+
prompt,
|
|
245
233
|
quality,
|
|
246
234
|
size,
|
|
247
235
|
moderation,
|
|
@@ -302,6 +290,9 @@ export function registerNodeRoutes(app, ctx) {
|
|
|
302
290
|
upstreamCode: lastErr?.upstreamCode || lastErr?.code,
|
|
303
291
|
errorEventType: lastErr?.eventType,
|
|
304
292
|
errorEventCount: lastErr?.eventCount,
|
|
293
|
+
diagnosticReason: lastErr?.diagnosticReason,
|
|
294
|
+
retryKind: lastErr?.retryKind,
|
|
295
|
+
referencesDroppedOnRetry: lastErr?.referencesDroppedOnRetry,
|
|
305
296
|
attempts: MAX_RETRIES + 1,
|
|
306
297
|
outerHttpAlreadyCommitted: res.headersSent,
|
|
307
298
|
sseErrorSent: streamResponse,
|
|
@@ -318,6 +309,11 @@ export function registerNodeRoutes(app, ctx) {
|
|
|
318
309
|
upstreamParam: lastErr?.upstreamParam || null,
|
|
319
310
|
errorEventType: lastErr?.eventType || null,
|
|
320
311
|
errorEventCount: lastErr?.eventCount ?? null,
|
|
312
|
+
diagnosticReason: finalErr.diagnosticReason || lastErr?.diagnosticReason || null,
|
|
313
|
+
retryKind: finalErr.retryKind || lastErr?.retryKind || null,
|
|
314
|
+
referencesDroppedOnRetry: finalErr.referencesDroppedOnRetry ?? lastErr?.referencesDroppedOnRetry ?? null,
|
|
315
|
+
refsCount: finalErr.refsCount ?? lastErr?.refsCount ?? null,
|
|
316
|
+
inputImageCount: finalErr.inputImageCount ?? lastErr?.inputImageCount ?? null,
|
|
321
317
|
},
|
|
322
318
|
);
|
|
323
319
|
}
|
|
@@ -333,8 +329,6 @@ export function registerNodeRoutes(app, ctx) {
|
|
|
333
329
|
userPrompt: prompt,
|
|
334
330
|
revisedPrompt,
|
|
335
331
|
promptMode: normalizedPromptMode,
|
|
336
|
-
effectivePrompt: styleSheetApplied ? effectivePrompt : undefined,
|
|
337
|
-
styleSheetApplied: styleSheetApplied || undefined,
|
|
338
332
|
options: { quality, size, format, moderation },
|
|
339
333
|
model: imageModel,
|
|
340
334
|
createdAt: Date.now(),
|
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
import { logError, logEvent } from "../lib/logger.js";
|
|
2
|
+
import { getDb } from "../lib/db.js";
|
|
3
|
+
|
|
4
|
+
function getPromptsDb() {
|
|
5
|
+
return getDb();
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function generateId() {
|
|
9
|
+
return `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function registerPromptRoutes(app, ctx) {
|
|
13
|
+
// ── Prompts ───────────────────────────────────────────────────────────────
|
|
14
|
+
|
|
15
|
+
app.get("/api/prompts", async (req, res) => {
|
|
16
|
+
try {
|
|
17
|
+
const db = getPromptsDb();
|
|
18
|
+
const search = typeof req.query.search === "string" ? req.query.search.trim() : "";
|
|
19
|
+
const folderId = typeof req.query.folderId === "string" ? req.query.folderId : null;
|
|
20
|
+
const favoritesOnly = req.query.favoritesOnly === "1" || req.query.favoritesOnly === "true";
|
|
21
|
+
|
|
22
|
+
let where = "WHERE 1=1";
|
|
23
|
+
const params = [];
|
|
24
|
+
|
|
25
|
+
if (folderId) {
|
|
26
|
+
where += " AND p.folder_id = ?";
|
|
27
|
+
params.push(folderId);
|
|
28
|
+
} else {
|
|
29
|
+
where += " AND p.folder_id != '__trash__'";
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (favoritesOnly) {
|
|
33
|
+
where += " AND p.is_favorite = 1";
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (search) {
|
|
37
|
+
where += " AND (p.name LIKE ? OR p.text LIKE ? OR p.tags LIKE ?)";
|
|
38
|
+
const like = `%${search}%`;
|
|
39
|
+
params.push(like, like, like);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const prompts = db
|
|
43
|
+
.prepare(
|
|
44
|
+
`SELECT p.*, f.name as folder_name
|
|
45
|
+
FROM prompts p
|
|
46
|
+
LEFT JOIN prompt_folders f ON p.folder_id = f.id
|
|
47
|
+
${where}
|
|
48
|
+
ORDER BY p.updated_at DESC`
|
|
49
|
+
)
|
|
50
|
+
.all(...params);
|
|
51
|
+
|
|
52
|
+
const folders = db
|
|
53
|
+
.prepare("SELECT * FROM prompt_folders WHERE id NOT IN ('__root__', '__trash__') ORDER BY name COLLATE NOCASE")
|
|
54
|
+
.all();
|
|
55
|
+
|
|
56
|
+
res.json({ prompts: prompts.map(normalizePrompt), folders: folders.map(normalizeFolder) });
|
|
57
|
+
} catch (err) {
|
|
58
|
+
logError("prompts", "list_error", err);
|
|
59
|
+
res.status(500).json({ error: err.message });
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
app.post("/api/prompts", async (req, res) => {
|
|
64
|
+
try {
|
|
65
|
+
const db = getPromptsDb();
|
|
66
|
+
const { name, text, tags, folderId, mode } = req.body || {};
|
|
67
|
+
|
|
68
|
+
if (!text || typeof text !== "string") {
|
|
69
|
+
return res.status(400).json({ error: "text is required" });
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const promptName = typeof name === "string" && name.trim() ? name.trim() : text.slice(0, 30);
|
|
73
|
+
const folder_id = typeof folderId === "string" && folderId ? folderId : "__root__";
|
|
74
|
+
const tagsJson = Array.isArray(tags) ? JSON.stringify(tags) : null;
|
|
75
|
+
const id = generateId();
|
|
76
|
+
const now = Math.floor(Date.now() / 1000);
|
|
77
|
+
|
|
78
|
+
db.prepare(
|
|
79
|
+
`INSERT INTO prompts (id, folder_id, name, text, tags, mode, created_at, updated_at)
|
|
80
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
|
|
81
|
+
).run(id, folder_id, promptName, text, tagsJson, mode || null, now, now);
|
|
82
|
+
|
|
83
|
+
logEvent("prompts", "created", { id, folder_id });
|
|
84
|
+
res.status(201).json({ prompt: normalizePrompt(db.prepare("SELECT * FROM prompts WHERE id = ?").get(id)) });
|
|
85
|
+
} catch (err) {
|
|
86
|
+
logError("prompts", "create_error", err);
|
|
87
|
+
res.status(500).json({ error: err.message });
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
app.get("/api/prompts/:id", async (req, res) => {
|
|
92
|
+
try {
|
|
93
|
+
const db = getPromptsDb();
|
|
94
|
+
const row = db.prepare("SELECT * FROM prompts WHERE id = ?").get(req.params.id);
|
|
95
|
+
if (!row) return res.status(404).json({ error: "Not found" });
|
|
96
|
+
res.json({ prompt: normalizePrompt(row) });
|
|
97
|
+
} catch (err) {
|
|
98
|
+
logError("prompts", "get_error", err);
|
|
99
|
+
res.status(500).json({ error: err.message });
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
app.patch("/api/prompts/:id", async (req, res) => {
|
|
104
|
+
try {
|
|
105
|
+
const db = getPromptsDb();
|
|
106
|
+
const { name, text, tags, folderId, mode } = req.body || {};
|
|
107
|
+
const sets = [];
|
|
108
|
+
const params = [];
|
|
109
|
+
|
|
110
|
+
if (typeof name === "string") { sets.push("name = ?"); params.push(name); }
|
|
111
|
+
if (typeof text === "string") { sets.push("text = ?"); params.push(text); }
|
|
112
|
+
if (Array.isArray(tags)) { sets.push("tags = ?"); params.push(JSON.stringify(tags)); }
|
|
113
|
+
if (typeof folderId === "string") { sets.push("folder_id = ?"); params.push(folderId); }
|
|
114
|
+
if (typeof mode === "string") { sets.push("mode = ?"); params.push(mode); }
|
|
115
|
+
|
|
116
|
+
if (sets.length === 0) return res.status(400).json({ error: "No fields to update" });
|
|
117
|
+
|
|
118
|
+
sets.push("updated_at = ?");
|
|
119
|
+
params.push(Math.floor(Date.now() / 1000));
|
|
120
|
+
params.push(req.params.id);
|
|
121
|
+
|
|
122
|
+
db.prepare(`UPDATE prompts SET ${sets.join(", ")} WHERE id = ?`).run(...params);
|
|
123
|
+
|
|
124
|
+
const row = db.prepare("SELECT * FROM prompts WHERE id = ?").get(req.params.id);
|
|
125
|
+
res.json({ prompt: normalizePrompt(row) });
|
|
126
|
+
} catch (err) {
|
|
127
|
+
logError("prompts", "patch_error", err);
|
|
128
|
+
res.status(500).json({ error: err.message });
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
app.delete("/api/prompts/:id", async (req, res) => {
|
|
133
|
+
try {
|
|
134
|
+
const db = getPromptsDb();
|
|
135
|
+
db.prepare("UPDATE prompts SET folder_id = '__trash__', updated_at = ? WHERE id = ?").run(
|
|
136
|
+
Math.floor(Date.now() / 1000),
|
|
137
|
+
req.params.id,
|
|
138
|
+
);
|
|
139
|
+
logEvent("prompts", "soft_deleted", { id: req.params.id });
|
|
140
|
+
res.json({ ok: true });
|
|
141
|
+
} catch (err) {
|
|
142
|
+
logError("prompts", "delete_error", err);
|
|
143
|
+
res.status(500).json({ error: err.message });
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
app.post("/api/prompts/:id/favorite", async (req, res) => {
|
|
148
|
+
try {
|
|
149
|
+
const db = getPromptsDb();
|
|
150
|
+
const row = db.prepare("SELECT is_favorite FROM prompts WHERE id = ?").get(req.params.id);
|
|
151
|
+
if (!row) return res.status(404).json({ error: "Not found" });
|
|
152
|
+
|
|
153
|
+
const newVal = row.is_favorite ? 0 : 1;
|
|
154
|
+
const now = Math.floor(Date.now() / 1000);
|
|
155
|
+
db.prepare("UPDATE prompts SET is_favorite = ?, favorited_at = ? WHERE id = ?").run(
|
|
156
|
+
newVal,
|
|
157
|
+
newVal ? now : null,
|
|
158
|
+
req.params.id,
|
|
159
|
+
);
|
|
160
|
+
|
|
161
|
+
res.json({ isFavorite: !!newVal, favoritedAt: newVal ? now : null });
|
|
162
|
+
} catch (err) {
|
|
163
|
+
logError("prompts", "favorite_error", err);
|
|
164
|
+
res.status(500).json({ error: err.message });
|
|
165
|
+
}
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
// ── Import / Export ───────────────────────────────────────────────────────
|
|
169
|
+
|
|
170
|
+
app.post("/api/prompts/import", async (req, res) => {
|
|
171
|
+
try {
|
|
172
|
+
const db = getPromptsDb();
|
|
173
|
+
const { folders: importFolders = [], prompts: importPrompts = [] } = req.body || {};
|
|
174
|
+
|
|
175
|
+
const result = { foldersCreated: 0, promptsImported: 0, duplicatesSkipped: 0 };
|
|
176
|
+
const now = Math.floor(Date.now() / 1000);
|
|
177
|
+
|
|
178
|
+
// Build name→id map for existing folders
|
|
179
|
+
const existingFolders = db.prepare("SELECT * FROM prompt_folders").all();
|
|
180
|
+
const folderMap = new Map(existingFolders.map((f) => [f.id, f]));
|
|
181
|
+
const namePathMap = new Map();
|
|
182
|
+
for (const f of existingFolders) {
|
|
183
|
+
const parent = folderMap.get(f.parent_id);
|
|
184
|
+
const path = parent && parent.id !== "__root__" ? `${parent.name}/${f.name}` : f.name;
|
|
185
|
+
namePathMap.set(path.toLowerCase(), f.id);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Import folders
|
|
189
|
+
for (const f of importFolders) {
|
|
190
|
+
if (!f.name) continue;
|
|
191
|
+
const path = f.parentId && f.parentId !== "__root__"
|
|
192
|
+
? `${folderMap.get(f.parentId)?.name || ""}/${f.name}`
|
|
193
|
+
: f.name;
|
|
194
|
+
if (namePathMap.has(path.toLowerCase())) continue;
|
|
195
|
+
|
|
196
|
+
const id = f.id || generateId();
|
|
197
|
+
db.prepare(
|
|
198
|
+
"INSERT INTO prompt_folders (id, parent_id, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)"
|
|
199
|
+
).run(id, f.parentId || "__root__", f.name, now, now);
|
|
200
|
+
namePathMap.set(path.toLowerCase(), id);
|
|
201
|
+
folderMap.set(id, { id, parent_id: f.parentId || "__root__", name: f.name });
|
|
202
|
+
result.foldersCreated++;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Import prompts
|
|
206
|
+
for (const p of importPrompts) {
|
|
207
|
+
if (!p.text) continue;
|
|
208
|
+
const folderId = p.folderId && folderMap.has(p.folderId) ? p.folderId : "__root__";
|
|
209
|
+
// Check duplicate by text + folder
|
|
210
|
+
const dup = db.prepare("SELECT 1 FROM prompts WHERE text = ? AND folder_id = ? LIMIT 1").get(p.text, folderId);
|
|
211
|
+
if (dup) {
|
|
212
|
+
result.duplicatesSkipped++;
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const id = p.id || generateId();
|
|
216
|
+
const tagsJson = Array.isArray(p.tags) ? JSON.stringify(p.tags) : null;
|
|
217
|
+
db.prepare(
|
|
218
|
+
`INSERT INTO prompts (id, folder_id, name, text, tags, mode, is_favorite, created_at, updated_at)
|
|
219
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
|
|
220
|
+
).run(id, folderId, p.name || p.text.slice(0, 30), p.text, tagsJson, p.mode || null, p.isFavorite ? 1 : 0, now, now);
|
|
221
|
+
result.promptsImported++;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
logEvent("prompts", "imported", result);
|
|
225
|
+
res.json(result);
|
|
226
|
+
} catch (err) {
|
|
227
|
+
logError("prompts", "import_error", err);
|
|
228
|
+
res.status(500).json({ error: err.message });
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
app.get("/api/prompts/export", async (req, res) => {
|
|
233
|
+
try {
|
|
234
|
+
const db = getPromptsDb();
|
|
235
|
+
const prompts = db.prepare("SELECT * FROM prompts WHERE folder_id != '__trash__'").all();
|
|
236
|
+
const folders = db.prepare("SELECT * FROM prompt_folders WHERE id NOT IN ('__root__', '__trash__')").all();
|
|
237
|
+
|
|
238
|
+
res.json({
|
|
239
|
+
version: 1,
|
|
240
|
+
exportedAt: new Date().toISOString(),
|
|
241
|
+
folders: folders.map((f) => ({ id: f.id, name: f.name, parentId: f.parent_id })),
|
|
242
|
+
prompts: prompts.map((p) => ({
|
|
243
|
+
id: p.id,
|
|
244
|
+
name: p.name,
|
|
245
|
+
text: p.text,
|
|
246
|
+
tags: p.tags ? JSON.parse(p.tags) : [],
|
|
247
|
+
folderId: p.folder_id,
|
|
248
|
+
mode: p.mode,
|
|
249
|
+
isFavorite: !!p.is_favorite,
|
|
250
|
+
})),
|
|
251
|
+
});
|
|
252
|
+
} catch (err) {
|
|
253
|
+
logError("prompts", "export_error", err);
|
|
254
|
+
res.status(500).json({ error: err.message });
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
|
|
258
|
+
// ── Folders ───────────────────────────────────────────────────────────────
|
|
259
|
+
|
|
260
|
+
app.get("/api/prompts/folders", async (req, res) => {
|
|
261
|
+
try {
|
|
262
|
+
const db = getPromptsDb();
|
|
263
|
+
const rows = db.prepare("SELECT * FROM prompt_folders WHERE id NOT IN ('__root__', '__trash__') ORDER BY name COLLATE NOCASE").all();
|
|
264
|
+
res.json({ folders: rows.map(normalizeFolder) });
|
|
265
|
+
} catch (err) {
|
|
266
|
+
logError("prompts", "folders_list_error", err);
|
|
267
|
+
res.status(500).json({ error: err.message });
|
|
268
|
+
}
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
app.post("/api/prompts/folders", async (req, res) => {
|
|
272
|
+
try {
|
|
273
|
+
const db = getPromptsDb();
|
|
274
|
+
const { name, parentId } = req.body || {};
|
|
275
|
+
if (!name || typeof name !== "string" || !name.trim()) {
|
|
276
|
+
return res.status(400).json({ error: "name is required" });
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const parent_id = typeof parentId === "string" && parentId ? parentId : "__root__";
|
|
280
|
+
const now = Math.floor(Date.now() / 1000);
|
|
281
|
+
const id = generateId();
|
|
282
|
+
|
|
283
|
+
try {
|
|
284
|
+
db.prepare(
|
|
285
|
+
"INSERT INTO prompt_folders (id, parent_id, name, created_at, updated_at) VALUES (?, ?, ?, ?, ?)"
|
|
286
|
+
).run(id, parent_id, name.trim(), now, now);
|
|
287
|
+
} catch (err) {
|
|
288
|
+
if (err.message && err.message.includes("UNIQUE constraint failed")) {
|
|
289
|
+
return res.status(409).json({ error: "Folder name already exists in this parent" });
|
|
290
|
+
}
|
|
291
|
+
throw err;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
res.status(201).json({ folder: normalizeFolder(db.prepare("SELECT * FROM prompt_folders WHERE id = ?").get(id)) });
|
|
295
|
+
} catch (err) {
|
|
296
|
+
logError("prompts", "folder_create_error", err);
|
|
297
|
+
res.status(500).json({ error: err.message });
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
app.patch("/api/prompts/folders/:id", async (req, res) => {
|
|
302
|
+
try {
|
|
303
|
+
const db = getPromptsDb();
|
|
304
|
+
const { name, parentId } = req.body || {};
|
|
305
|
+
const sets = [];
|
|
306
|
+
const params = [];
|
|
307
|
+
|
|
308
|
+
if (typeof name === "string" && name.trim()) { sets.push("name = ?"); params.push(name.trim()); }
|
|
309
|
+
if (typeof parentId === "string") { sets.push("parent_id = ?"); params.push(parentId); }
|
|
310
|
+
if (sets.length === 0) return res.status(400).json({ error: "No fields to update" });
|
|
311
|
+
|
|
312
|
+
sets.push("updated_at = ?");
|
|
313
|
+
params.push(Math.floor(Date.now() / 1000));
|
|
314
|
+
params.push(req.params.id);
|
|
315
|
+
|
|
316
|
+
try {
|
|
317
|
+
db.prepare(`UPDATE prompt_folders SET ${sets.join(", ")} WHERE id = ?`).run(...params);
|
|
318
|
+
} catch (err) {
|
|
319
|
+
if (err.message && err.message.includes("UNIQUE constraint failed")) {
|
|
320
|
+
return res.status(409).json({ error: "Folder name already exists in this parent" });
|
|
321
|
+
}
|
|
322
|
+
throw err;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const row = db.prepare("SELECT * FROM prompt_folders WHERE id = ?").get(req.params.id);
|
|
326
|
+
res.json({ folder: normalizeFolder(row) });
|
|
327
|
+
} catch (err) {
|
|
328
|
+
logError("prompts", "folder_patch_error", err);
|
|
329
|
+
res.status(500).json({ error: err.message });
|
|
330
|
+
}
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
app.delete("/api/prompts/folders/:id", async (req, res) => {
|
|
334
|
+
try {
|
|
335
|
+
const db = getPromptsDb();
|
|
336
|
+
const strategy = req.query.strategy === "deleteItems" ? "deleteItems" : "moveToRoot";
|
|
337
|
+
|
|
338
|
+
if (strategy === "moveToRoot") {
|
|
339
|
+
db.prepare("UPDATE prompts SET folder_id = '__root__' WHERE folder_id = ?").run(req.params.id);
|
|
340
|
+
} else {
|
|
341
|
+
db.prepare("UPDATE prompts SET folder_id = '__trash__' WHERE folder_id = ?").run(req.params.id);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
db.prepare("DELETE FROM prompt_folders WHERE id = ?").run(req.params.id);
|
|
345
|
+
logEvent("prompts", "folder_deleted", { id: req.params.id, strategy });
|
|
346
|
+
res.json({ ok: true });
|
|
347
|
+
} catch (err) {
|
|
348
|
+
logError("prompts", "folder_delete_error", err);
|
|
349
|
+
res.status(500).json({ error: err.message });
|
|
350
|
+
}
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// ── Helpers ─────────────────────────────────────────────────────────────────
|
|
355
|
+
|
|
356
|
+
function normalizePrompt(row) {
|
|
357
|
+
return {
|
|
358
|
+
id: row.id,
|
|
359
|
+
folderId: row.folder_id,
|
|
360
|
+
name: row.name,
|
|
361
|
+
text: row.text,
|
|
362
|
+
tags: row.tags ? JSON.parse(row.tags) : [],
|
|
363
|
+
mode: row.mode,
|
|
364
|
+
isFavorite: !!row.is_favorite,
|
|
365
|
+
favoritedAt: row.favorited_at || null,
|
|
366
|
+
createdAt: row.created_at,
|
|
367
|
+
updatedAt: row.updated_at,
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function normalizeFolder(row) {
|
|
372
|
+
return {
|
|
373
|
+
id: row.id,
|
|
374
|
+
parentId: row.parent_id,
|
|
375
|
+
name: row.name,
|
|
376
|
+
createdAt: row.created_at,
|
|
377
|
+
updatedAt: row.updated_at,
|
|
378
|
+
};
|
|
379
|
+
}
|