@mordn/chat-widget 0.1.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 +338 -0
- package/dist/api/index.d.mts +6 -0
- package/dist/api/index.d.ts +6 -0
- package/dist/api/index.js +242 -0
- package/dist/api/index.js.map +1 -0
- package/dist/api/index.mjs +197 -0
- package/dist/api/index.mjs.map +1 -0
- package/dist/db/index.d.mts +323 -0
- package/dist/db/index.d.ts +323 -0
- package/dist/db/index.js +223 -0
- package/dist/db/index.js.map +1 -0
- package/dist/db/index.mjs +186 -0
- package/dist/db/index.mjs.map +1 -0
- package/dist/index.d.mts +187 -0
- package/dist/index.d.ts +187 -0
- package/dist/index.js +2663 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +2647 -0
- package/dist/index.mjs.map +1 -0
- package/dist/styles.css +2 -0
- package/package.json +100 -0
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import { UIMessage } from 'ai';
|
|
2
|
+
import * as drizzle_orm_postgres_js from 'drizzle-orm/postgres-js';
|
|
3
|
+
import postgres from 'postgres';
|
|
4
|
+
import * as drizzle_orm_pg_core from 'drizzle-orm/pg-core';
|
|
5
|
+
import 'drizzle-orm';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Conversations table
|
|
9
|
+
* Stores chat conversation metadata
|
|
10
|
+
*/
|
|
11
|
+
declare const conversations: drizzle_orm_pg_core.PgTableWithColumns<{
|
|
12
|
+
name: "conversations";
|
|
13
|
+
schema: undefined;
|
|
14
|
+
columns: {
|
|
15
|
+
id: drizzle_orm_pg_core.PgColumn<{
|
|
16
|
+
name: "id";
|
|
17
|
+
tableName: "conversations";
|
|
18
|
+
dataType: "string";
|
|
19
|
+
columnType: "PgText";
|
|
20
|
+
data: string;
|
|
21
|
+
driverParam: string;
|
|
22
|
+
notNull: true;
|
|
23
|
+
hasDefault: false;
|
|
24
|
+
isPrimaryKey: true;
|
|
25
|
+
isAutoincrement: false;
|
|
26
|
+
hasRuntimeDefault: false;
|
|
27
|
+
enumValues: [string, ...string[]];
|
|
28
|
+
baseColumn: never;
|
|
29
|
+
identity: undefined;
|
|
30
|
+
generated: undefined;
|
|
31
|
+
}, {}, {}>;
|
|
32
|
+
userId: drizzle_orm_pg_core.PgColumn<{
|
|
33
|
+
name: "user_id";
|
|
34
|
+
tableName: "conversations";
|
|
35
|
+
dataType: "string";
|
|
36
|
+
columnType: "PgText";
|
|
37
|
+
data: string;
|
|
38
|
+
driverParam: string;
|
|
39
|
+
notNull: true;
|
|
40
|
+
hasDefault: false;
|
|
41
|
+
isPrimaryKey: false;
|
|
42
|
+
isAutoincrement: false;
|
|
43
|
+
hasRuntimeDefault: false;
|
|
44
|
+
enumValues: [string, ...string[]];
|
|
45
|
+
baseColumn: never;
|
|
46
|
+
identity: undefined;
|
|
47
|
+
generated: undefined;
|
|
48
|
+
}, {}, {}>;
|
|
49
|
+
title: drizzle_orm_pg_core.PgColumn<{
|
|
50
|
+
name: "title";
|
|
51
|
+
tableName: "conversations";
|
|
52
|
+
dataType: "string";
|
|
53
|
+
columnType: "PgText";
|
|
54
|
+
data: string;
|
|
55
|
+
driverParam: string;
|
|
56
|
+
notNull: true;
|
|
57
|
+
hasDefault: true;
|
|
58
|
+
isPrimaryKey: false;
|
|
59
|
+
isAutoincrement: false;
|
|
60
|
+
hasRuntimeDefault: false;
|
|
61
|
+
enumValues: [string, ...string[]];
|
|
62
|
+
baseColumn: never;
|
|
63
|
+
identity: undefined;
|
|
64
|
+
generated: undefined;
|
|
65
|
+
}, {}, {}>;
|
|
66
|
+
metadata: drizzle_orm_pg_core.PgColumn<{
|
|
67
|
+
name: "metadata";
|
|
68
|
+
tableName: "conversations";
|
|
69
|
+
dataType: "json";
|
|
70
|
+
columnType: "PgJsonb";
|
|
71
|
+
data: unknown;
|
|
72
|
+
driverParam: unknown;
|
|
73
|
+
notNull: false;
|
|
74
|
+
hasDefault: false;
|
|
75
|
+
isPrimaryKey: false;
|
|
76
|
+
isAutoincrement: false;
|
|
77
|
+
hasRuntimeDefault: false;
|
|
78
|
+
enumValues: undefined;
|
|
79
|
+
baseColumn: never;
|
|
80
|
+
identity: undefined;
|
|
81
|
+
generated: undefined;
|
|
82
|
+
}, {}, {}>;
|
|
83
|
+
createdAt: drizzle_orm_pg_core.PgColumn<{
|
|
84
|
+
name: "created_at";
|
|
85
|
+
tableName: "conversations";
|
|
86
|
+
dataType: "date";
|
|
87
|
+
columnType: "PgTimestamp";
|
|
88
|
+
data: Date;
|
|
89
|
+
driverParam: string;
|
|
90
|
+
notNull: true;
|
|
91
|
+
hasDefault: true;
|
|
92
|
+
isPrimaryKey: false;
|
|
93
|
+
isAutoincrement: false;
|
|
94
|
+
hasRuntimeDefault: false;
|
|
95
|
+
enumValues: undefined;
|
|
96
|
+
baseColumn: never;
|
|
97
|
+
identity: undefined;
|
|
98
|
+
generated: undefined;
|
|
99
|
+
}, {}, {}>;
|
|
100
|
+
updatedAt: drizzle_orm_pg_core.PgColumn<{
|
|
101
|
+
name: "updated_at";
|
|
102
|
+
tableName: "conversations";
|
|
103
|
+
dataType: "date";
|
|
104
|
+
columnType: "PgTimestamp";
|
|
105
|
+
data: Date;
|
|
106
|
+
driverParam: string;
|
|
107
|
+
notNull: true;
|
|
108
|
+
hasDefault: true;
|
|
109
|
+
isPrimaryKey: false;
|
|
110
|
+
isAutoincrement: false;
|
|
111
|
+
hasRuntimeDefault: false;
|
|
112
|
+
enumValues: undefined;
|
|
113
|
+
baseColumn: never;
|
|
114
|
+
identity: undefined;
|
|
115
|
+
generated: undefined;
|
|
116
|
+
}, {}, {}>;
|
|
117
|
+
};
|
|
118
|
+
dialect: "pg";
|
|
119
|
+
}>;
|
|
120
|
+
/**
|
|
121
|
+
* Messages table
|
|
122
|
+
* Stores individual chat messages
|
|
123
|
+
*/
|
|
124
|
+
declare const messages: drizzle_orm_pg_core.PgTableWithColumns<{
|
|
125
|
+
name: "messages";
|
|
126
|
+
schema: undefined;
|
|
127
|
+
columns: {
|
|
128
|
+
id: drizzle_orm_pg_core.PgColumn<{
|
|
129
|
+
name: "id";
|
|
130
|
+
tableName: "messages";
|
|
131
|
+
dataType: "string";
|
|
132
|
+
columnType: "PgText";
|
|
133
|
+
data: string;
|
|
134
|
+
driverParam: string;
|
|
135
|
+
notNull: true;
|
|
136
|
+
hasDefault: false;
|
|
137
|
+
isPrimaryKey: true;
|
|
138
|
+
isAutoincrement: false;
|
|
139
|
+
hasRuntimeDefault: false;
|
|
140
|
+
enumValues: [string, ...string[]];
|
|
141
|
+
baseColumn: never;
|
|
142
|
+
identity: undefined;
|
|
143
|
+
generated: undefined;
|
|
144
|
+
}, {}, {}>;
|
|
145
|
+
conversationId: drizzle_orm_pg_core.PgColumn<{
|
|
146
|
+
name: "conversation_id";
|
|
147
|
+
tableName: "messages";
|
|
148
|
+
dataType: "string";
|
|
149
|
+
columnType: "PgText";
|
|
150
|
+
data: string;
|
|
151
|
+
driverParam: string;
|
|
152
|
+
notNull: true;
|
|
153
|
+
hasDefault: false;
|
|
154
|
+
isPrimaryKey: false;
|
|
155
|
+
isAutoincrement: false;
|
|
156
|
+
hasRuntimeDefault: false;
|
|
157
|
+
enumValues: [string, ...string[]];
|
|
158
|
+
baseColumn: never;
|
|
159
|
+
identity: undefined;
|
|
160
|
+
generated: undefined;
|
|
161
|
+
}, {}, {}>;
|
|
162
|
+
role: drizzle_orm_pg_core.PgColumn<{
|
|
163
|
+
name: "role";
|
|
164
|
+
tableName: "messages";
|
|
165
|
+
dataType: "string";
|
|
166
|
+
columnType: "PgText";
|
|
167
|
+
data: string;
|
|
168
|
+
driverParam: string;
|
|
169
|
+
notNull: true;
|
|
170
|
+
hasDefault: false;
|
|
171
|
+
isPrimaryKey: false;
|
|
172
|
+
isAutoincrement: false;
|
|
173
|
+
hasRuntimeDefault: false;
|
|
174
|
+
enumValues: [string, ...string[]];
|
|
175
|
+
baseColumn: never;
|
|
176
|
+
identity: undefined;
|
|
177
|
+
generated: undefined;
|
|
178
|
+
}, {}, {}>;
|
|
179
|
+
content: drizzle_orm_pg_core.PgColumn<{
|
|
180
|
+
name: "content";
|
|
181
|
+
tableName: "messages";
|
|
182
|
+
dataType: "string";
|
|
183
|
+
columnType: "PgText";
|
|
184
|
+
data: string;
|
|
185
|
+
driverParam: string;
|
|
186
|
+
notNull: true;
|
|
187
|
+
hasDefault: false;
|
|
188
|
+
isPrimaryKey: false;
|
|
189
|
+
isAutoincrement: false;
|
|
190
|
+
hasRuntimeDefault: false;
|
|
191
|
+
enumValues: [string, ...string[]];
|
|
192
|
+
baseColumn: never;
|
|
193
|
+
identity: undefined;
|
|
194
|
+
generated: undefined;
|
|
195
|
+
}, {}, {}>;
|
|
196
|
+
files: drizzle_orm_pg_core.PgColumn<{
|
|
197
|
+
name: "files";
|
|
198
|
+
tableName: "messages";
|
|
199
|
+
dataType: "json";
|
|
200
|
+
columnType: "PgJsonb";
|
|
201
|
+
data: unknown;
|
|
202
|
+
driverParam: unknown;
|
|
203
|
+
notNull: false;
|
|
204
|
+
hasDefault: false;
|
|
205
|
+
isPrimaryKey: false;
|
|
206
|
+
isAutoincrement: false;
|
|
207
|
+
hasRuntimeDefault: false;
|
|
208
|
+
enumValues: undefined;
|
|
209
|
+
baseColumn: never;
|
|
210
|
+
identity: undefined;
|
|
211
|
+
generated: undefined;
|
|
212
|
+
}, {}, {}>;
|
|
213
|
+
model: drizzle_orm_pg_core.PgColumn<{
|
|
214
|
+
name: "model";
|
|
215
|
+
tableName: "messages";
|
|
216
|
+
dataType: "string";
|
|
217
|
+
columnType: "PgText";
|
|
218
|
+
data: string;
|
|
219
|
+
driverParam: string;
|
|
220
|
+
notNull: false;
|
|
221
|
+
hasDefault: false;
|
|
222
|
+
isPrimaryKey: false;
|
|
223
|
+
isAutoincrement: false;
|
|
224
|
+
hasRuntimeDefault: false;
|
|
225
|
+
enumValues: [string, ...string[]];
|
|
226
|
+
baseColumn: never;
|
|
227
|
+
identity: undefined;
|
|
228
|
+
generated: undefined;
|
|
229
|
+
}, {}, {}>;
|
|
230
|
+
metadata: drizzle_orm_pg_core.PgColumn<{
|
|
231
|
+
name: "metadata";
|
|
232
|
+
tableName: "messages";
|
|
233
|
+
dataType: "json";
|
|
234
|
+
columnType: "PgJsonb";
|
|
235
|
+
data: unknown;
|
|
236
|
+
driverParam: unknown;
|
|
237
|
+
notNull: false;
|
|
238
|
+
hasDefault: false;
|
|
239
|
+
isPrimaryKey: false;
|
|
240
|
+
isAutoincrement: false;
|
|
241
|
+
hasRuntimeDefault: false;
|
|
242
|
+
enumValues: undefined;
|
|
243
|
+
baseColumn: never;
|
|
244
|
+
identity: undefined;
|
|
245
|
+
generated: undefined;
|
|
246
|
+
}, {}, {}>;
|
|
247
|
+
createdAt: drizzle_orm_pg_core.PgColumn<{
|
|
248
|
+
name: "created_at";
|
|
249
|
+
tableName: "messages";
|
|
250
|
+
dataType: "date";
|
|
251
|
+
columnType: "PgTimestamp";
|
|
252
|
+
data: Date;
|
|
253
|
+
driverParam: string;
|
|
254
|
+
notNull: true;
|
|
255
|
+
hasDefault: true;
|
|
256
|
+
isPrimaryKey: false;
|
|
257
|
+
isAutoincrement: false;
|
|
258
|
+
hasRuntimeDefault: false;
|
|
259
|
+
enumValues: undefined;
|
|
260
|
+
baseColumn: never;
|
|
261
|
+
identity: undefined;
|
|
262
|
+
generated: undefined;
|
|
263
|
+
}, {}, {}>;
|
|
264
|
+
};
|
|
265
|
+
dialect: "pg";
|
|
266
|
+
}>;
|
|
267
|
+
type Conversation = typeof conversations.$inferSelect;
|
|
268
|
+
type NewConversation = typeof conversations.$inferInsert;
|
|
269
|
+
type Message = typeof messages.$inferSelect;
|
|
270
|
+
type NewMessage = typeof messages.$inferInsert;
|
|
271
|
+
|
|
272
|
+
type schema_Conversation = Conversation;
|
|
273
|
+
type schema_Message = Message;
|
|
274
|
+
type schema_NewConversation = NewConversation;
|
|
275
|
+
type schema_NewMessage = NewMessage;
|
|
276
|
+
declare const schema_conversations: typeof conversations;
|
|
277
|
+
declare const schema_messages: typeof messages;
|
|
278
|
+
declare namespace schema {
|
|
279
|
+
export { type schema_Conversation as Conversation, type schema_Message as Message, type schema_NewConversation as NewConversation, type schema_NewMessage as NewMessage, schema_conversations as conversations, schema_messages as messages };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Create a new conversation
|
|
284
|
+
*/
|
|
285
|
+
declare function createChat(userId: string): Promise<string>;
|
|
286
|
+
/**
|
|
287
|
+
* Load messages for a conversation
|
|
288
|
+
*/
|
|
289
|
+
declare function loadChat(conversationId: string): Promise<UIMessage[]>;
|
|
290
|
+
/**
|
|
291
|
+
* Update conversation title
|
|
292
|
+
*/
|
|
293
|
+
declare function updateConversationTitle(chatId: string, title: string): Promise<void>;
|
|
294
|
+
/**
|
|
295
|
+
* Save messages to a conversation
|
|
296
|
+
*/
|
|
297
|
+
declare function saveChat({ chatId, messages: chatMessages, model, userId, }: {
|
|
298
|
+
chatId: string;
|
|
299
|
+
messages: UIMessage[];
|
|
300
|
+
model?: string;
|
|
301
|
+
userId: string;
|
|
302
|
+
}): Promise<void>;
|
|
303
|
+
/**
|
|
304
|
+
* Get all conversations for a user
|
|
305
|
+
*/
|
|
306
|
+
declare function getConversations(userId: string): Promise<{
|
|
307
|
+
id: string;
|
|
308
|
+
title: string;
|
|
309
|
+
createdAt: Date;
|
|
310
|
+
updatedAt: Date;
|
|
311
|
+
metadata: unknown;
|
|
312
|
+
messageCount: number;
|
|
313
|
+
}[]>;
|
|
314
|
+
/**
|
|
315
|
+
* Delete a conversation and all its messages
|
|
316
|
+
*/
|
|
317
|
+
declare function deleteConversation(chatId: string): Promise<void>;
|
|
318
|
+
|
|
319
|
+
declare const db: drizzle_orm_postgres_js.PostgresJsDatabase<typeof schema> & {
|
|
320
|
+
$client: postgres.Sql<{}>;
|
|
321
|
+
};
|
|
322
|
+
|
|
323
|
+
export { type Conversation, type Message, type NewConversation, type NewMessage, conversations, createChat, db, deleteConversation, getConversations, loadChat, messages, saveChat, updateConversationTitle };
|
package/dist/db/index.js
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc2) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc2 = __getOwnPropDesc(from, key)) || desc2.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/db/index.ts
|
|
31
|
+
var db_exports = {};
|
|
32
|
+
__export(db_exports, {
|
|
33
|
+
conversations: () => conversations,
|
|
34
|
+
createChat: () => createChat,
|
|
35
|
+
db: () => db,
|
|
36
|
+
deleteConversation: () => deleteConversation,
|
|
37
|
+
getConversations: () => getConversations,
|
|
38
|
+
loadChat: () => loadChat,
|
|
39
|
+
messages: () => messages,
|
|
40
|
+
saveChat: () => saveChat,
|
|
41
|
+
updateConversationTitle: () => updateConversationTitle
|
|
42
|
+
});
|
|
43
|
+
module.exports = __toCommonJS(db_exports);
|
|
44
|
+
var import_server_only = require("server-only");
|
|
45
|
+
var import_postgres_js = require("drizzle-orm/postgres-js");
|
|
46
|
+
var import_postgres = __toESM(require("postgres"));
|
|
47
|
+
|
|
48
|
+
// src/db/schema.ts
|
|
49
|
+
var schema_exports = {};
|
|
50
|
+
__export(schema_exports, {
|
|
51
|
+
conversations: () => conversations,
|
|
52
|
+
messages: () => messages
|
|
53
|
+
});
|
|
54
|
+
var import_pg_core = require("drizzle-orm/pg-core");
|
|
55
|
+
var conversations = (0, import_pg_core.pgTable)("conversations", {
|
|
56
|
+
id: (0, import_pg_core.text)("id").primaryKey(),
|
|
57
|
+
userId: (0, import_pg_core.text)("user_id").notNull(),
|
|
58
|
+
title: (0, import_pg_core.text)("title").notNull().default("New Chat"),
|
|
59
|
+
metadata: (0, import_pg_core.jsonb)("metadata"),
|
|
60
|
+
createdAt: (0, import_pg_core.timestamp)("created_at").defaultNow().notNull(),
|
|
61
|
+
updatedAt: (0, import_pg_core.timestamp)("updated_at").defaultNow().notNull()
|
|
62
|
+
}, (table) => [
|
|
63
|
+
(0, import_pg_core.index)("conversations_user_id_idx").on(table.userId),
|
|
64
|
+
(0, import_pg_core.index)("conversations_updated_at_idx").on(table.updatedAt)
|
|
65
|
+
]);
|
|
66
|
+
var messages = (0, import_pg_core.pgTable)("messages", {
|
|
67
|
+
id: (0, import_pg_core.text)("id").primaryKey(),
|
|
68
|
+
conversationId: (0, import_pg_core.text)("conversation_id").notNull().references(() => conversations.id, { onDelete: "cascade" }),
|
|
69
|
+
role: (0, import_pg_core.text)("role").notNull(),
|
|
70
|
+
// 'user' | 'assistant' | 'system'
|
|
71
|
+
content: (0, import_pg_core.text)("content").notNull(),
|
|
72
|
+
files: (0, import_pg_core.jsonb)("files"),
|
|
73
|
+
// Array of file attachments
|
|
74
|
+
model: (0, import_pg_core.text)("model"),
|
|
75
|
+
// AI model used
|
|
76
|
+
metadata: (0, import_pg_core.jsonb)("metadata"),
|
|
77
|
+
// Additional data (parts, reasoning, etc.)
|
|
78
|
+
createdAt: (0, import_pg_core.timestamp)("created_at").defaultNow().notNull()
|
|
79
|
+
}, (table) => [
|
|
80
|
+
(0, import_pg_core.index)("messages_conversation_id_idx").on(table.conversationId),
|
|
81
|
+
(0, import_pg_core.index)("messages_created_at_idx").on(table.createdAt)
|
|
82
|
+
]);
|
|
83
|
+
|
|
84
|
+
// src/db/chat-store.ts
|
|
85
|
+
var import_ai = require("ai");
|
|
86
|
+
var import_drizzle_orm = require("drizzle-orm");
|
|
87
|
+
async function createChat(userId) {
|
|
88
|
+
const id = (0, import_ai.generateId)();
|
|
89
|
+
await db.insert(conversations).values({
|
|
90
|
+
id,
|
|
91
|
+
userId,
|
|
92
|
+
title: "New Chat",
|
|
93
|
+
metadata: {}
|
|
94
|
+
});
|
|
95
|
+
return id;
|
|
96
|
+
}
|
|
97
|
+
async function loadChat(conversationId) {
|
|
98
|
+
try {
|
|
99
|
+
const dbMessages = await db.select().from(messages).where((0, import_drizzle_orm.eq)(messages.conversationId, conversationId)).orderBy((0, import_drizzle_orm.asc)(messages.createdAt));
|
|
100
|
+
if (!dbMessages.length) return [];
|
|
101
|
+
return dbMessages.map((msg) => {
|
|
102
|
+
const metadata = msg.metadata;
|
|
103
|
+
if (metadata?.parts && Array.isArray(metadata.parts)) {
|
|
104
|
+
return {
|
|
105
|
+
id: msg.id,
|
|
106
|
+
role: msg.role,
|
|
107
|
+
parts: metadata.parts,
|
|
108
|
+
createdAt: msg.createdAt
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
return {
|
|
112
|
+
id: msg.id,
|
|
113
|
+
role: msg.role,
|
|
114
|
+
parts: [{ type: "text", text: msg.content }],
|
|
115
|
+
createdAt: msg.createdAt
|
|
116
|
+
};
|
|
117
|
+
});
|
|
118
|
+
} catch (error) {
|
|
119
|
+
console.error("Error loading chat:", error);
|
|
120
|
+
return [];
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
async function updateConversationTitle(chatId, title) {
|
|
124
|
+
try {
|
|
125
|
+
await db.update(conversations).set({ title, updatedAt: /* @__PURE__ */ new Date() }).where((0, import_drizzle_orm.eq)(conversations.id, chatId));
|
|
126
|
+
} catch (error) {
|
|
127
|
+
console.error("Error updating conversation title:", error);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
async function saveChat({
|
|
131
|
+
chatId,
|
|
132
|
+
messages: chatMessages,
|
|
133
|
+
model,
|
|
134
|
+
userId
|
|
135
|
+
}) {
|
|
136
|
+
if (!userId) {
|
|
137
|
+
console.error("userId is required for saveChat");
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
const existingConv = await db.select({ id: conversations.id, title: conversations.title }).from(conversations).where((0, import_drizzle_orm.eq)(conversations.id, chatId)).limit(1);
|
|
142
|
+
if (!existingConv.length) {
|
|
143
|
+
console.error("Conversation not found:", chatId);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const conv = existingConv[0];
|
|
147
|
+
if (conv.title === "New Chat") {
|
|
148
|
+
const firstUserMessage = chatMessages.find((m) => m.role === "user");
|
|
149
|
+
if (firstUserMessage) {
|
|
150
|
+
const textPart = firstUserMessage.parts?.find((p) => p.type === "text");
|
|
151
|
+
if (textPart?.text) {
|
|
152
|
+
const newTitle = textPart.text.slice(0, 100);
|
|
153
|
+
await updateConversationTitle(chatId, newTitle);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const existingMessages = await db.select({ id: messages.id }).from(messages).where((0, import_drizzle_orm.eq)(messages.conversationId, chatId));
|
|
158
|
+
const existingIds = new Set(existingMessages.map((m) => m.id));
|
|
159
|
+
const newMessages = chatMessages.filter((msg) => !existingIds.has(msg.id));
|
|
160
|
+
if (newMessages.length > 0) {
|
|
161
|
+
for (const msg of newMessages) {
|
|
162
|
+
const textPart = msg.parts?.find((p) => p.type === "text");
|
|
163
|
+
const fileParts = msg.parts?.filter((p) => p.type === "file") || [];
|
|
164
|
+
await db.insert(messages).values({
|
|
165
|
+
id: msg.id,
|
|
166
|
+
conversationId: chatId,
|
|
167
|
+
role: msg.role,
|
|
168
|
+
content: textPart?.text || "",
|
|
169
|
+
files: fileParts,
|
|
170
|
+
model: model || "openai/gpt-4o-mini",
|
|
171
|
+
metadata: { parts: msg.parts || [] }
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
await db.update(conversations).set({ updatedAt: /* @__PURE__ */ new Date() }).where((0, import_drizzle_orm.eq)(conversations.id, chatId));
|
|
175
|
+
}
|
|
176
|
+
} catch (error) {
|
|
177
|
+
console.error("Error saving chat:", error);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
async function getConversations(userId) {
|
|
181
|
+
try {
|
|
182
|
+
const result = await db.select({
|
|
183
|
+
id: conversations.id,
|
|
184
|
+
title: conversations.title,
|
|
185
|
+
createdAt: conversations.createdAt,
|
|
186
|
+
updatedAt: conversations.updatedAt,
|
|
187
|
+
metadata: conversations.metadata,
|
|
188
|
+
messageCount: import_drizzle_orm.sql`(
|
|
189
|
+
SELECT COUNT(*) FROM ${messages}
|
|
190
|
+
WHERE ${messages.conversationId} = ${conversations.id}
|
|
191
|
+
)`
|
|
192
|
+
}).from(conversations).where((0, import_drizzle_orm.eq)(conversations.userId, userId)).orderBy((0, import_drizzle_orm.desc)(conversations.updatedAt));
|
|
193
|
+
return result;
|
|
194
|
+
} catch (error) {
|
|
195
|
+
console.error("Error getting conversations:", error);
|
|
196
|
+
return [];
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
async function deleteConversation(chatId) {
|
|
200
|
+
try {
|
|
201
|
+
await db.delete(conversations).where((0, import_drizzle_orm.eq)(conversations.id, chatId));
|
|
202
|
+
} catch (error) {
|
|
203
|
+
console.error("Error deleting conversation:", error);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// src/db/index.ts
|
|
208
|
+
var connectionString = process.env.DATABASE_URL;
|
|
209
|
+
var client = (0, import_postgres.default)(connectionString, { prepare: false });
|
|
210
|
+
var db = (0, import_postgres_js.drizzle)(client, { schema: schema_exports });
|
|
211
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
212
|
+
0 && (module.exports = {
|
|
213
|
+
conversations,
|
|
214
|
+
createChat,
|
|
215
|
+
db,
|
|
216
|
+
deleteConversation,
|
|
217
|
+
getConversations,
|
|
218
|
+
loadChat,
|
|
219
|
+
messages,
|
|
220
|
+
saveChat,
|
|
221
|
+
updateConversationTitle
|
|
222
|
+
});
|
|
223
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/db/index.ts","../../src/db/schema.ts","../../src/db/chat-store.ts"],"sourcesContent":["import 'server-only';\nimport { drizzle } from 'drizzle-orm/postgres-js';\nimport postgres from 'postgres';\nimport * as schema from './schema';\n\n// Create postgres connection\nconst connectionString = process.env.DATABASE_URL!;\n\n// Disable prefetch as it is not supported for \"Transaction\" pool mode\nconst client = postgres(connectionString, { prepare: false });\n\n// Create drizzle database instance\nexport const db = drizzle(client, { schema });\n\n// Export schema for convenience\nexport * from './schema';\n\n// Export chat store functions\nexport * from './chat-store';\n","import { pgTable, text, timestamp, jsonb, index } from 'drizzle-orm/pg-core';\n\n/**\n * Conversations table\n * Stores chat conversation metadata\n */\nexport const conversations = pgTable('conversations', {\n id: text('id').primaryKey(),\n userId: text('user_id').notNull(),\n title: text('title').notNull().default('New Chat'),\n metadata: jsonb('metadata'),\n createdAt: timestamp('created_at').defaultNow().notNull(),\n updatedAt: timestamp('updated_at').defaultNow().notNull(),\n}, (table) => [\n index('conversations_user_id_idx').on(table.userId),\n index('conversations_updated_at_idx').on(table.updatedAt),\n]);\n\n/**\n * Messages table\n * Stores individual chat messages\n */\nexport const messages = pgTable('messages', {\n id: text('id').primaryKey(),\n conversationId: text('conversation_id').notNull().references(() => conversations.id, { onDelete: 'cascade' }),\n role: text('role').notNull(), // 'user' | 'assistant' | 'system'\n content: text('content').notNull(),\n files: jsonb('files'), // Array of file attachments\n model: text('model'), // AI model used\n metadata: jsonb('metadata'), // Additional data (parts, reasoning, etc.)\n createdAt: timestamp('created_at').defaultNow().notNull(),\n}, (table) => [\n index('messages_conversation_id_idx').on(table.conversationId),\n index('messages_created_at_idx').on(table.createdAt),\n]);\n\n// Type exports for use in application code\nexport type Conversation = typeof conversations.$inferSelect;\nexport type NewConversation = typeof conversations.$inferInsert;\nexport type Message = typeof messages.$inferSelect;\nexport type NewMessage = typeof messages.$inferInsert;\n","import { generateId, UIMessage } from 'ai';\nimport { db, conversations, messages } from './index';\nimport { eq, desc, asc, sql } from 'drizzle-orm';\n\n/**\n * Create a new conversation\n */\nexport async function createChat(userId: string): Promise<string> {\n const id = generateId();\n\n await db.insert(conversations).values({\n id,\n userId,\n title: 'New Chat',\n metadata: {},\n });\n\n return id;\n}\n\n/**\n * Load messages for a conversation\n */\nexport async function loadChat(conversationId: string): Promise<UIMessage[]> {\n try {\n const dbMessages = await db\n .select()\n .from(messages)\n .where(eq(messages.conversationId, conversationId))\n .orderBy(asc(messages.createdAt));\n\n if (!dbMessages.length) return [];\n\n // Convert database messages to UIMessage format\n return dbMessages.map((msg) => {\n // If we have metadata with parts, use those (includes reasoning)\n const metadata = msg.metadata as { parts?: any[] } | null;\n if (metadata?.parts && Array.isArray(metadata.parts)) {\n return {\n id: msg.id,\n role: msg.role as 'user' | 'assistant' | 'system',\n parts: metadata.parts,\n createdAt: msg.createdAt,\n };\n }\n\n // Fallback to simple text message\n return {\n id: msg.id,\n role: msg.role as 'user' | 'assistant' | 'system',\n parts: [{ type: 'text', text: msg.content }],\n createdAt: msg.createdAt,\n };\n });\n } catch (error) {\n console.error('Error loading chat:', error);\n return [];\n }\n}\n\n/**\n * Update conversation title\n */\nexport async function updateConversationTitle(\n chatId: string,\n title: string\n): Promise<void> {\n try {\n await db\n .update(conversations)\n .set({ title, updatedAt: new Date() })\n .where(eq(conversations.id, chatId));\n } catch (error) {\n console.error('Error updating conversation title:', error);\n }\n}\n\n/**\n * Save messages to a conversation\n */\nexport async function saveChat({\n chatId,\n messages: chatMessages,\n model,\n userId,\n}: {\n chatId: string;\n messages: UIMessage[];\n model?: string;\n userId: string;\n}): Promise<void> {\n if (!userId) {\n console.error('userId is required for saveChat');\n return;\n }\n\n try {\n // Verify conversation exists\n const existingConv = await db\n .select({ id: conversations.id, title: conversations.title })\n .from(conversations)\n .where(eq(conversations.id, chatId))\n .limit(1);\n\n if (!existingConv.length) {\n console.error('Conversation not found:', chatId);\n return;\n }\n\n const conv = existingConv[0];\n\n // Update title if this is the first user message and title is still \"New Chat\"\n if (conv.title === 'New Chat') {\n const firstUserMessage = chatMessages.find((m) => m.role === 'user');\n if (firstUserMessage) {\n const textPart = firstUserMessage.parts?.find((p) => p.type === 'text') as { text: string } | undefined;\n if (textPart?.text) {\n const newTitle = textPart.text.slice(0, 100);\n await updateConversationTitle(chatId, newTitle);\n }\n }\n }\n\n // Get existing message IDs from database\n const existingMessages = await db\n .select({ id: messages.id })\n .from(messages)\n .where(eq(messages.conversationId, chatId));\n\n const existingIds = new Set(existingMessages.map((m) => m.id));\n\n // Insert only new messages\n const newMessages = chatMessages.filter((msg) => !existingIds.has(msg.id));\n\n if (newMessages.length > 0) {\n for (const msg of newMessages) {\n const textPart = msg.parts?.find((p) => p.type === 'text') as { text: string } | undefined;\n const fileParts = msg.parts?.filter((p) => p.type === 'file') || [];\n\n await db.insert(messages).values({\n id: msg.id,\n conversationId: chatId,\n role: msg.role,\n content: textPart?.text || '',\n files: fileParts,\n model: model || 'openai/gpt-4o-mini',\n metadata: { parts: msg.parts || [] },\n });\n }\n\n // Update conversation's updatedAt\n await db\n .update(conversations)\n .set({ updatedAt: new Date() })\n .where(eq(conversations.id, chatId));\n }\n } catch (error) {\n console.error('Error saving chat:', error);\n }\n}\n\n/**\n * Get all conversations for a user\n */\nexport async function getConversations(userId: string) {\n try {\n const result = await db\n .select({\n id: conversations.id,\n title: conversations.title,\n createdAt: conversations.createdAt,\n updatedAt: conversations.updatedAt,\n metadata: conversations.metadata,\n messageCount: sql<number>`(\n SELECT COUNT(*) FROM ${messages}\n WHERE ${messages.conversationId} = ${conversations.id}\n )`,\n })\n .from(conversations)\n .where(eq(conversations.userId, userId))\n .orderBy(desc(conversations.updatedAt));\n\n return result;\n } catch (error) {\n console.error('Error getting conversations:', error);\n return [];\n }\n}\n\n/**\n * Delete a conversation and all its messages\n */\nexport async function deleteConversation(chatId: string): Promise<void> {\n try {\n // Messages are deleted automatically due to cascade\n await db.delete(conversations).where(eq(conversations.id, chatId));\n } catch (error) {\n console.error('Error deleting conversation:', error);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAO;AACP,yBAAwB;AACxB,sBAAqB;;;ACFrB;AAAA;AAAA;AAAA;AAAA;AAAA,qBAAuD;AAMhD,IAAM,oBAAgB,wBAAQ,iBAAiB;AAAA,EACpD,QAAI,qBAAK,IAAI,EAAE,WAAW;AAAA,EAC1B,YAAQ,qBAAK,SAAS,EAAE,QAAQ;AAAA,EAChC,WAAO,qBAAK,OAAO,EAAE,QAAQ,EAAE,QAAQ,UAAU;AAAA,EACjD,cAAU,sBAAM,UAAU;AAAA,EAC1B,eAAW,0BAAU,YAAY,EAAE,WAAW,EAAE,QAAQ;AAAA,EACxD,eAAW,0BAAU,YAAY,EAAE,WAAW,EAAE,QAA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