@librechat/data-schemas 0.0.7 → 0.0.8

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 (65) hide show
  1. package/dist/index.cjs +1470 -3
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.es.js +1467 -6
  4. package/dist/index.es.js.map +1 -1
  5. package/dist/types/config/meiliLogger.d.ts +4 -0
  6. package/dist/types/config/parsers.d.ts +32 -0
  7. package/dist/types/config/winston.d.ts +4 -0
  8. package/dist/types/crypto/index.d.ts +3 -0
  9. package/dist/types/index.d.ts +7 -46
  10. package/dist/types/methods/index.d.ts +67 -0
  11. package/dist/types/methods/role.d.ts +35 -0
  12. package/dist/types/methods/session.d.ts +48 -0
  13. package/dist/types/methods/token.d.ts +34 -0
  14. package/dist/types/methods/user.d.ts +38 -0
  15. package/dist/types/methods/user.test.d.ts +1 -0
  16. package/dist/types/models/action.d.ts +30 -0
  17. package/dist/types/models/agent.d.ts +30 -0
  18. package/dist/types/models/assistant.d.ts +30 -0
  19. package/dist/types/models/balance.d.ts +30 -0
  20. package/dist/types/models/banner.d.ts +30 -0
  21. package/dist/types/models/conversationTag.d.ts +30 -0
  22. package/dist/types/models/convo.d.ts +30 -0
  23. package/dist/types/models/file.d.ts +30 -0
  24. package/dist/types/models/index.d.ts +53 -0
  25. package/dist/types/models/key.d.ts +30 -0
  26. package/dist/types/models/message.d.ts +30 -0
  27. package/dist/types/models/pluginAuth.d.ts +30 -0
  28. package/dist/types/models/plugins/mongoMeili.d.ts +52 -0
  29. package/dist/types/models/preset.d.ts +30 -0
  30. package/dist/types/models/project.d.ts +30 -0
  31. package/dist/types/models/prompt.d.ts +30 -0
  32. package/dist/types/models/promptGroup.d.ts +30 -0
  33. package/dist/types/models/role.d.ts +30 -0
  34. package/dist/types/models/session.d.ts +30 -0
  35. package/dist/types/models/sharedLink.d.ts +30 -0
  36. package/dist/types/models/token.d.ts +30 -0
  37. package/dist/types/models/toolCall.d.ts +30 -0
  38. package/dist/types/models/transaction.d.ts +30 -0
  39. package/dist/types/models/user.d.ts +30 -0
  40. package/dist/types/schema/action.d.ts +2 -27
  41. package/dist/types/schema/agent.d.ts +4 -31
  42. package/dist/types/schema/assistant.d.ts +4 -16
  43. package/dist/types/schema/balance.d.ts +4 -12
  44. package/dist/types/schema/convo.d.ts +2 -49
  45. package/dist/types/schema/file.d.ts +2 -26
  46. package/dist/types/schema/index.d.ts +23 -0
  47. package/dist/types/schema/message.d.ts +2 -36
  48. package/dist/types/schema/role.d.ts +2 -5
  49. package/dist/types/schema/session.d.ts +2 -6
  50. package/dist/types/schema/token.d.ts +2 -11
  51. package/dist/types/schema/user.d.ts +5 -36
  52. package/dist/types/types/action.d.ts +52 -0
  53. package/dist/types/types/agent.d.ts +55 -0
  54. package/dist/types/types/assistant.d.ts +39 -0
  55. package/dist/types/types/balance.d.ts +35 -0
  56. package/dist/types/types/banner.d.ts +34 -0
  57. package/dist/types/types/convo.d.ts +74 -0
  58. package/dist/types/types/file.d.ts +51 -0
  59. package/dist/types/types/index.d.ts +12 -0
  60. package/dist/types/types/message.d.ts +67 -0
  61. package/dist/types/types/role.d.ts +30 -0
  62. package/dist/types/types/session.d.ts +61 -0
  63. package/dist/types/types/token.d.ts +62 -0
  64. package/dist/types/types/user.d.ts +91 -0
  65. package/package.json +12 -5
package/dist/index.cjs CHANGED
@@ -1,7 +1,25 @@
1
1
  'use strict';
2
2
 
3
+ var jwt = require('jsonwebtoken');
4
+ var node_crypto = require('node:crypto');
3
5
  var mongoose = require('mongoose');
4
6
  var librechatDataProvider = require('librechat-data-provider');
7
+ var _ = require('lodash');
8
+ var meilisearch = require('meilisearch');
9
+ var path = require('path');
10
+ var winston = require('winston');
11
+ require('winston-daily-rotate-file');
12
+ var klona = require('klona');
13
+ var traverse = require('traverse');
14
+
15
+ async function signPayload({ payload, secret, expirationTime, }) {
16
+ return jwt.sign(payload, secret, { expiresIn: expirationTime });
17
+ }
18
+ async function hashToken(str) {
19
+ const data = new TextEncoder().encode(str);
20
+ const hashBuffer = await node_crypto.webcrypto.subtle.digest('SHA-256', data);
21
+ return Buffer.from(hashBuffer).toString('hex');
22
+ }
5
23
 
6
24
  // Define the Auth sub-schema with type-safety.
7
25
  const AuthSchema = new mongoose.Schema({
@@ -133,6 +151,10 @@ const agentSchema = new mongoose.Schema({
133
151
  ref: 'Project',
134
152
  index: true,
135
153
  },
154
+ versions: {
155
+ type: [mongoose.Schema.Types.Mixed],
156
+ default: [],
157
+ },
136
158
  }, {
137
159
  timestamps: true,
138
160
  });
@@ -619,6 +641,25 @@ const messageSchema = new mongoose.Schema({
619
641
  finish_reason: {
620
642
  type: String,
621
643
  },
644
+ feedback: {
645
+ type: {
646
+ rating: {
647
+ type: String,
648
+ enum: ['thumbsUp', 'thumbsDown'],
649
+ required: true,
650
+ },
651
+ tag: {
652
+ type: mongoose.Schema.Types.Mixed,
653
+ required: false,
654
+ },
655
+ text: {
656
+ type: String,
657
+ required: false,
658
+ },
659
+ },
660
+ default: undefined,
661
+ required: false,
662
+ },
622
663
  _meiliIndex: {
623
664
  type: Boolean,
624
665
  required: false,
@@ -865,6 +906,9 @@ const rolePermissionsSchema = new mongoose.Schema({
865
906
  [librechatDataProvider.PermissionTypes.RUN_CODE]: {
866
907
  [librechatDataProvider.Permissions.USE]: { type: Boolean, default: true },
867
908
  },
909
+ [librechatDataProvider.PermissionTypes.WEB_SEARCH]: {
910
+ [librechatDataProvider.Permissions.USE]: { type: Boolean, default: true },
911
+ },
868
912
  }, { _id: false });
869
913
  const roleSchema = new mongoose.Schema({
870
914
  name: { type: String, required: true, unique: true, index: true },
@@ -885,6 +929,7 @@ const roleSchema = new mongoose.Schema({
885
929
  [librechatDataProvider.PermissionTypes.MULTI_CONVO]: { [librechatDataProvider.Permissions.USE]: true },
886
930
  [librechatDataProvider.PermissionTypes.TEMPORARY_CHAT]: { [librechatDataProvider.Permissions.USE]: true },
887
931
  [librechatDataProvider.PermissionTypes.RUN_CODE]: { [librechatDataProvider.Permissions.USE]: true },
932
+ [librechatDataProvider.PermissionTypes.WEB_SEARCH]: { [librechatDataProvider.Permissions.USE]: true },
888
933
  }),
889
934
  },
890
935
  });
@@ -1048,7 +1093,7 @@ const BackupCodeSchema = new mongoose.Schema({
1048
1093
  used: { type: Boolean, default: false },
1049
1094
  usedAt: { type: Date, default: null },
1050
1095
  }, { _id: false });
1051
- const User = new mongoose.Schema({
1096
+ const userSchema = new mongoose.Schema({
1052
1097
  name: {
1053
1098
  type: String,
1054
1099
  },
@@ -1059,7 +1104,7 @@ const User = new mongoose.Schema({
1059
1104
  },
1060
1105
  email: {
1061
1106
  type: String,
1062
- required: [true, 'can\'t be blank'],
1107
+ required: [true, "can't be blank"],
1063
1108
  lowercase: true,
1064
1109
  unique: true,
1065
1110
  match: [/\S+@\S+\.\S+/, 'is invalid'],
@@ -1104,6 +1149,11 @@ const User = new mongoose.Schema({
1104
1149
  unique: true,
1105
1150
  sparse: true,
1106
1151
  },
1152
+ samlId: {
1153
+ type: String,
1154
+ unique: true,
1155
+ sparse: true,
1156
+ },
1107
1157
  ldapId: {
1108
1158
  type: String,
1109
1159
  unique: true,
@@ -1150,6 +1200,1417 @@ const User = new mongoose.Schema({
1150
1200
  },
1151
1201
  }, { timestamps: true });
1152
1202
 
1203
+ /**
1204
+ * Creates or returns the User model using the provided mongoose instance and schema
1205
+ */
1206
+ function createUserModel(mongoose) {
1207
+ return mongoose.models.User || mongoose.model('User', userSchema);
1208
+ }
1209
+
1210
+ /**
1211
+ * Creates or returns the Token model using the provided mongoose instance and schema
1212
+ */
1213
+ function createTokenModel(mongoose) {
1214
+ return mongoose.models.Token || mongoose.model('Token', tokenSchema);
1215
+ }
1216
+
1217
+ /**
1218
+ * Creates or returns the Session model using the provided mongoose instance and schema
1219
+ */
1220
+ function createSessionModel(mongoose) {
1221
+ return mongoose.models.Session || mongoose.model('Session', sessionSchema);
1222
+ }
1223
+
1224
+ /**
1225
+ * Creates or returns the Balance model using the provided mongoose instance and schema
1226
+ */
1227
+ function createBalanceModel(mongoose) {
1228
+ return mongoose.models.Balance || mongoose.model('Balance', balanceSchema);
1229
+ }
1230
+
1231
+ const logDir$1 = path.join(__dirname, '..', 'logs');
1232
+ const { NODE_ENV: NODE_ENV$1, DEBUG_LOGGING: DEBUG_LOGGING$1 = 'false' } = process.env;
1233
+ const useDebugLogging$1 = (typeof DEBUG_LOGGING$1 === 'string' && DEBUG_LOGGING$1.toLowerCase() === 'true') ||
1234
+ DEBUG_LOGGING$1 === 'true';
1235
+ const levels$1 = {
1236
+ error: 0,
1237
+ warn: 1,
1238
+ info: 2,
1239
+ http: 3,
1240
+ verbose: 4,
1241
+ debug: 5,
1242
+ activity: 6,
1243
+ silly: 7,
1244
+ };
1245
+ winston.addColors({
1246
+ info: 'green',
1247
+ warn: 'italic yellow',
1248
+ error: 'red',
1249
+ debug: 'blue',
1250
+ });
1251
+ const level$1 = () => {
1252
+ const env = NODE_ENV$1 || 'development';
1253
+ const isDevelopment = env === 'development';
1254
+ return isDevelopment ? 'debug' : 'warn';
1255
+ };
1256
+ const fileFormat$1 = winston.format.combine(winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston.format.errors({ stack: true }), winston.format.splat());
1257
+ const logLevel = useDebugLogging$1 ? 'debug' : 'error';
1258
+ const transports$1 = [
1259
+ new winston.transports.DailyRotateFile({
1260
+ level: logLevel,
1261
+ filename: `${logDir$1}/meiliSync-%DATE%.log`,
1262
+ datePattern: 'YYYY-MM-DD',
1263
+ zippedArchive: true,
1264
+ maxSize: '20m',
1265
+ maxFiles: '14d',
1266
+ format: fileFormat$1,
1267
+ }),
1268
+ ];
1269
+ const consoleFormat$1 = winston.format.combine(winston.format.colorize({ all: true }), winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston.format.printf((info) => `${info.timestamp} ${info.level}: ${info.message}`));
1270
+ transports$1.push(new winston.transports.Console({
1271
+ level: 'info',
1272
+ format: consoleFormat$1,
1273
+ }));
1274
+ const logger$1 = winston.createLogger({
1275
+ level: level$1(),
1276
+ levels: levels$1,
1277
+ transports: transports$1,
1278
+ });
1279
+
1280
+ // Environment flags
1281
+ /**
1282
+ * Flag to indicate if search is enabled based on environment variables.
1283
+ */
1284
+ const searchEnabled = process.env.SEARCH != null && process.env.SEARCH.toLowerCase() === 'true';
1285
+ /**
1286
+ * Flag to indicate if MeiliSearch is enabled based on required environment variables.
1287
+ */
1288
+ const meiliEnabled = process.env.MEILI_HOST != null && process.env.MEILI_MASTER_KEY != null && searchEnabled;
1289
+ /**
1290
+ * Local implementation of parseTextParts to avoid dependency on librechat-data-provider
1291
+ * Extracts text content from an array of content items
1292
+ */
1293
+ const parseTextParts = (content) => {
1294
+ if (!Array.isArray(content)) {
1295
+ return '';
1296
+ }
1297
+ return content
1298
+ .filter((item) => item.type === 'text' && typeof item.text === 'string')
1299
+ .map((item) => item.text)
1300
+ .join(' ')
1301
+ .trim();
1302
+ };
1303
+ /**
1304
+ * Local implementation to handle Bing convoId conversion
1305
+ */
1306
+ const cleanUpPrimaryKeyValue = (value) => {
1307
+ return value.replace(/--/g, '|');
1308
+ };
1309
+ /**
1310
+ * Validates the required options for configuring the mongoMeili plugin.
1311
+ */
1312
+ const validateOptions = (options) => {
1313
+ const requiredKeys = ['host', 'apiKey', 'indexName'];
1314
+ requiredKeys.forEach((key) => {
1315
+ if (!options[key]) {
1316
+ throw new Error(`Missing mongoMeili Option: ${key}`);
1317
+ }
1318
+ });
1319
+ };
1320
+ /**
1321
+ * Factory function to create a MeiliMongooseModel class which extends a Mongoose model.
1322
+ * This class contains static and instance methods to synchronize and manage the MeiliSearch index
1323
+ * corresponding to the MongoDB collection.
1324
+ *
1325
+ * @param config - Configuration object.
1326
+ * @param config.index - The MeiliSearch index object.
1327
+ * @param config.attributesToIndex - List of attributes to index.
1328
+ * @returns A class definition that will be loaded into the Mongoose schema.
1329
+ */
1330
+ const createMeiliMongooseModel = ({ index, attributesToIndex, }) => {
1331
+ const primaryKey = attributesToIndex[0];
1332
+ class MeiliMongooseModel {
1333
+ /**
1334
+ * Synchronizes the data between the MongoDB collection and the MeiliSearch index.
1335
+ *
1336
+ * The synchronization process involves:
1337
+ * 1. Fetching all documents from the MongoDB collection and MeiliSearch index.
1338
+ * 2. Comparing documents from both sources.
1339
+ * 3. Deleting documents from MeiliSearch that no longer exist in MongoDB.
1340
+ * 4. Adding documents to MeiliSearch that exist in MongoDB but not in the index.
1341
+ * 5. Updating documents in MeiliSearch if key fields (such as `text` or `title`) differ.
1342
+ * 6. Updating the `_meiliIndex` field in MongoDB to indicate the indexing status.
1343
+ *
1344
+ * Note: The function processes documents in batches because MeiliSearch's
1345
+ * `index.getDocuments` requires an exact limit and `index.addDocuments` does not handle
1346
+ * partial failures in a batch.
1347
+ *
1348
+ * @returns {Promise<void>} Resolves when the synchronization is complete.
1349
+ */
1350
+ static async syncWithMeili() {
1351
+ try {
1352
+ let moreDocuments = true;
1353
+ const mongoDocuments = await this.find().lean();
1354
+ const format = (doc) => _.omitBy(_.pick(doc, attributesToIndex), (v, k) => k.startsWith('$'));
1355
+ const mongoMap = new Map(mongoDocuments.map((doc) => {
1356
+ const typedDoc = doc;
1357
+ return [typedDoc[primaryKey], format(typedDoc)];
1358
+ }));
1359
+ const indexMap = new Map();
1360
+ let offset = 0;
1361
+ const batchSize = 1000;
1362
+ while (moreDocuments) {
1363
+ const batch = await index.getDocuments({ limit: batchSize, offset });
1364
+ if (batch.results.length === 0) {
1365
+ moreDocuments = false;
1366
+ }
1367
+ for (const doc of batch.results) {
1368
+ indexMap.set(doc[primaryKey], format(doc));
1369
+ }
1370
+ offset += batchSize;
1371
+ }
1372
+ logger$1.debug('[syncWithMeili]', { indexMap: indexMap.size, mongoMap: mongoMap.size });
1373
+ const updateOps = [];
1374
+ // Process documents present in the MeiliSearch index
1375
+ for (const [id, doc] of indexMap) {
1376
+ const update = {};
1377
+ update[primaryKey] = id;
1378
+ if (mongoMap.has(id)) {
1379
+ const mongoDoc = mongoMap.get(id);
1380
+ if ((doc.text && doc.text !== (mongoDoc === null || mongoDoc === void 0 ? void 0 : mongoDoc.text)) ||
1381
+ (doc.title && doc.title !== (mongoDoc === null || mongoDoc === void 0 ? void 0 : mongoDoc.title))) {
1382
+ logger$1.debug(`[syncWithMeili] ${id} had document discrepancy in ${doc.text ? 'text' : 'title'} field`);
1383
+ updateOps.push({
1384
+ updateOne: { filter: update, update: { $set: { _meiliIndex: true } } },
1385
+ });
1386
+ await index.addDocuments([doc]);
1387
+ }
1388
+ }
1389
+ else {
1390
+ await index.deleteDocument(id);
1391
+ updateOps.push({
1392
+ updateOne: { filter: update, update: { $set: { _meiliIndex: false } } },
1393
+ });
1394
+ }
1395
+ }
1396
+ // Process documents present in MongoDB
1397
+ for (const [id, doc] of mongoMap) {
1398
+ const update = {};
1399
+ update[primaryKey] = id;
1400
+ if (!indexMap.has(id)) {
1401
+ await index.addDocuments([doc]);
1402
+ updateOps.push({
1403
+ updateOne: { filter: update, update: { $set: { _meiliIndex: true } } },
1404
+ });
1405
+ }
1406
+ else if (doc._meiliIndex === false) {
1407
+ updateOps.push({
1408
+ updateOne: { filter: update, update: { $set: { _meiliIndex: true } } },
1409
+ });
1410
+ }
1411
+ }
1412
+ if (updateOps.length > 0) {
1413
+ await this.collection.bulkWrite(updateOps);
1414
+ logger$1.debug(`[syncWithMeili] Finished indexing ${primaryKey === 'messageId' ? 'messages' : 'conversations'}`);
1415
+ }
1416
+ }
1417
+ catch (error) {
1418
+ logger$1.error('[syncWithMeili] Error adding document to Meili', error);
1419
+ }
1420
+ }
1421
+ /**
1422
+ * Updates settings for the MeiliSearch index
1423
+ */
1424
+ static async setMeiliIndexSettings(settings) {
1425
+ return await index.updateSettings(settings);
1426
+ }
1427
+ /**
1428
+ * Searches the MeiliSearch index and optionally populates results
1429
+ */
1430
+ static async meiliSearch(q, params, populate) {
1431
+ const data = await index.search(q, params);
1432
+ if (populate) {
1433
+ const query = {};
1434
+ query[primaryKey] = _.map(data.hits, (hit) => cleanUpPrimaryKeyValue(hit[primaryKey]));
1435
+ const projection = Object.keys(this.schema.obj).reduce((results, key) => {
1436
+ if (!key.startsWith('$')) {
1437
+ results[key] = 1;
1438
+ }
1439
+ return results;
1440
+ }, { _id: 1, __v: 1 });
1441
+ const hitsFromMongoose = await this.find(query, projection).lean();
1442
+ const populatedHits = data.hits.map((hit) => {
1443
+ hit[primaryKey];
1444
+ const originalHit = _.find(hitsFromMongoose, (item) => {
1445
+ const typedItem = item;
1446
+ return typedItem[primaryKey] === hit[primaryKey];
1447
+ });
1448
+ return {
1449
+ ...(originalHit && typeof originalHit === 'object' ? originalHit : {}),
1450
+ ...hit,
1451
+ };
1452
+ });
1453
+ data.hits = populatedHits;
1454
+ }
1455
+ return data;
1456
+ }
1457
+ /**
1458
+ * Preprocesses the current document for indexing
1459
+ */
1460
+ preprocessObjectForIndex() {
1461
+ const object = _.omitBy(_.pick(this.toJSON(), attributesToIndex), (v, k) => k.startsWith('$'));
1462
+ if (object.conversationId &&
1463
+ typeof object.conversationId === 'string' &&
1464
+ object.conversationId.includes('|')) {
1465
+ object.conversationId = object.conversationId.replace(/\|/g, '--');
1466
+ }
1467
+ if (object.content && Array.isArray(object.content)) {
1468
+ object.text = parseTextParts(object.content);
1469
+ delete object.content;
1470
+ }
1471
+ return object;
1472
+ }
1473
+ /**
1474
+ * Adds the current document to the MeiliSearch index
1475
+ */
1476
+ async addObjectToMeili() {
1477
+ const object = this.preprocessObjectForIndex();
1478
+ try {
1479
+ await index.addDocuments([object]);
1480
+ }
1481
+ catch (error) {
1482
+ logger$1.error('[addObjectToMeili] Error adding document to Meili', error);
1483
+ }
1484
+ await this.collection.updateMany({ _id: this._id }, { $set: { _meiliIndex: true } });
1485
+ }
1486
+ /**
1487
+ * Updates the current document in the MeiliSearch index
1488
+ */
1489
+ async updateObjectToMeili() {
1490
+ const object = _.omitBy(_.pick(this.toJSON(), attributesToIndex), (v, k) => k.startsWith('$'));
1491
+ await index.updateDocuments([object]);
1492
+ }
1493
+ /**
1494
+ * Deletes the current document from the MeiliSearch index.
1495
+ *
1496
+ * @returns {Promise<void>}
1497
+ */
1498
+ async deleteObjectFromMeili() {
1499
+ await index.deleteDocument(this._id);
1500
+ }
1501
+ /**
1502
+ * Post-save hook to synchronize the document with MeiliSearch.
1503
+ *
1504
+ * If the document is already indexed (i.e. `_meiliIndex` is true), it updates it;
1505
+ * otherwise, it adds the document to the index.
1506
+ */
1507
+ postSaveHook() {
1508
+ if (this._meiliIndex) {
1509
+ this.updateObjectToMeili();
1510
+ }
1511
+ else {
1512
+ this.addObjectToMeili();
1513
+ }
1514
+ }
1515
+ /**
1516
+ * Post-update hook to update the document in MeiliSearch.
1517
+ *
1518
+ * This hook is triggered after a document update, ensuring that changes are
1519
+ * propagated to the MeiliSearch index if the document is indexed.
1520
+ */
1521
+ postUpdateHook() {
1522
+ if (this._meiliIndex) {
1523
+ this.updateObjectToMeili();
1524
+ }
1525
+ }
1526
+ /**
1527
+ * Post-remove hook to delete the document from MeiliSearch.
1528
+ *
1529
+ * This hook is triggered after a document is removed, ensuring that the document
1530
+ * is also removed from the MeiliSearch index if it was previously indexed.
1531
+ */
1532
+ postRemoveHook() {
1533
+ if (this._meiliIndex) {
1534
+ this.deleteObjectFromMeili();
1535
+ }
1536
+ }
1537
+ }
1538
+ return MeiliMongooseModel;
1539
+ };
1540
+ /**
1541
+ * Mongoose plugin to synchronize MongoDB collections with a MeiliSearch index.
1542
+ *
1543
+ * This plugin:
1544
+ * - Validates the provided options.
1545
+ * - Adds a `_meiliIndex` field to the schema to track indexing status.
1546
+ * - Sets up a MeiliSearch client and creates an index if it doesn't already exist.
1547
+ * - Loads class methods for syncing, searching, and managing documents in MeiliSearch.
1548
+ * - Registers Mongoose hooks (post-save, post-update, post-remove, etc.) to maintain index consistency.
1549
+ *
1550
+ * @param schema - The Mongoose schema to which the plugin is applied.
1551
+ * @param options - Configuration options.
1552
+ * @param options.host - The MeiliSearch host.
1553
+ * @param options.apiKey - The MeiliSearch API key.
1554
+ * @param options.indexName - The name of the MeiliSearch index.
1555
+ * @param options.primaryKey - The primary key field for indexing.
1556
+ */
1557
+ function mongoMeili(schema, options) {
1558
+ const mongoose = options.mongoose;
1559
+ validateOptions(options);
1560
+ // Add _meiliIndex field to the schema to track if a document has been indexed in MeiliSearch.
1561
+ schema.add({
1562
+ _meiliIndex: {
1563
+ type: Boolean,
1564
+ required: false,
1565
+ select: false,
1566
+ default: false,
1567
+ },
1568
+ });
1569
+ const { host, apiKey, indexName, primaryKey } = options;
1570
+ const client = new meilisearch.MeiliSearch({ host, apiKey });
1571
+ client.createIndex(indexName, { primaryKey });
1572
+ const index = client.index(indexName);
1573
+ // Collect attributes from the schema that should be indexed
1574
+ const attributesToIndex = [
1575
+ ...Object.entries(schema.obj).reduce((results, [key, value]) => {
1576
+ const schemaValue = value;
1577
+ return schemaValue.meiliIndex ? [...results, key] : results;
1578
+ }, []),
1579
+ ];
1580
+ schema.loadClass(createMeiliMongooseModel({ index, attributesToIndex }));
1581
+ // Register Mongoose hooks
1582
+ schema.post('save', function (doc) {
1583
+ var _a;
1584
+ (_a = doc.postSaveHook) === null || _a === void 0 ? void 0 : _a.call(doc);
1585
+ });
1586
+ schema.post('updateOne', function (doc) {
1587
+ var _a;
1588
+ (_a = doc.postUpdateHook) === null || _a === void 0 ? void 0 : _a.call(doc);
1589
+ });
1590
+ schema.post('deleteOne', function (doc) {
1591
+ var _a;
1592
+ (_a = doc.postRemoveHook) === null || _a === void 0 ? void 0 : _a.call(doc);
1593
+ });
1594
+ // Pre-deleteMany hook: remove corresponding documents from MeiliSearch when multiple documents are deleted.
1595
+ schema.pre('deleteMany', async function (next) {
1596
+ if (!meiliEnabled) {
1597
+ return next();
1598
+ }
1599
+ try {
1600
+ const conditions = this.getQuery();
1601
+ if (Object.prototype.hasOwnProperty.call(schema.obj, 'messages')) {
1602
+ const convoIndex = client.index('convos');
1603
+ const deletedConvos = await mongoose
1604
+ .model('Conversation')
1605
+ .find(conditions)
1606
+ .lean();
1607
+ const promises = deletedConvos.map((convo) => convoIndex.deleteDocument(convo.conversationId));
1608
+ await Promise.all(promises);
1609
+ }
1610
+ if (Object.prototype.hasOwnProperty.call(schema.obj, 'messageId')) {
1611
+ const messageIndex = client.index('messages');
1612
+ const deletedMessages = await mongoose
1613
+ .model('Message')
1614
+ .find(conditions)
1615
+ .lean();
1616
+ const promises = deletedMessages.map((message) => messageIndex.deleteDocument(message.messageId));
1617
+ await Promise.all(promises);
1618
+ }
1619
+ return next();
1620
+ }
1621
+ catch (error) {
1622
+ if (meiliEnabled) {
1623
+ logger$1.error('[MeiliMongooseModel.deleteMany] There was an issue deleting conversation indexes upon deletion. Next startup may be slow due to syncing.', error);
1624
+ }
1625
+ return next();
1626
+ }
1627
+ });
1628
+ // Post-findOneAndUpdate hook
1629
+ schema.post('findOneAndUpdate', async function (doc) {
1630
+ var _a;
1631
+ if (!meiliEnabled) {
1632
+ return;
1633
+ }
1634
+ if (doc.unfinished) {
1635
+ return;
1636
+ }
1637
+ let meiliDoc;
1638
+ if (doc.messages) {
1639
+ try {
1640
+ meiliDoc = await client.index('convos').getDocument(doc.conversationId);
1641
+ }
1642
+ catch (error) {
1643
+ logger$1.debug('[MeiliMongooseModel.findOneAndUpdate] Convo not found in MeiliSearch and will index ' +
1644
+ doc.conversationId, error);
1645
+ }
1646
+ }
1647
+ if (meiliDoc && meiliDoc.title === doc.title) {
1648
+ return;
1649
+ }
1650
+ (_a = doc.postSaveHook) === null || _a === void 0 ? void 0 : _a.call(doc);
1651
+ });
1652
+ }
1653
+
1654
+ /**
1655
+ * Creates or returns the Conversation model using the provided mongoose instance and schema
1656
+ */
1657
+ function createConversationModel(mongoose) {
1658
+ if (process.env.MEILI_HOST && process.env.MEILI_MASTER_KEY) {
1659
+ convoSchema.plugin(mongoMeili, {
1660
+ mongoose,
1661
+ host: process.env.MEILI_HOST,
1662
+ apiKey: process.env.MEILI_MASTER_KEY,
1663
+ /** Note: Will get created automatically if it doesn't exist already */
1664
+ indexName: 'convos',
1665
+ primaryKey: 'conversationId',
1666
+ });
1667
+ }
1668
+ return (mongoose.models.Conversation || mongoose.model('Conversation', convoSchema));
1669
+ }
1670
+
1671
+ /**
1672
+ * Creates or returns the Message model using the provided mongoose instance and schema
1673
+ */
1674
+ function createMessageModel(mongoose) {
1675
+ if (process.env.MEILI_HOST && process.env.MEILI_MASTER_KEY) {
1676
+ messageSchema.plugin(mongoMeili, {
1677
+ mongoose,
1678
+ host: process.env.MEILI_HOST,
1679
+ apiKey: process.env.MEILI_MASTER_KEY,
1680
+ indexName: 'messages',
1681
+ primaryKey: 'messageId',
1682
+ });
1683
+ }
1684
+ return mongoose.models.Message || mongoose.model('Message', messageSchema);
1685
+ }
1686
+
1687
+ /**
1688
+ * Creates or returns the Agent model using the provided mongoose instance and schema
1689
+ */
1690
+ function createAgentModel(mongoose) {
1691
+ return mongoose.models.Agent || mongoose.model('Agent', agentSchema);
1692
+ }
1693
+
1694
+ /**
1695
+ * Creates or returns the Role model using the provided mongoose instance and schema
1696
+ */
1697
+ function createRoleModel(mongoose) {
1698
+ return mongoose.models.Role || mongoose.model('Role', roleSchema);
1699
+ }
1700
+
1701
+ /**
1702
+ * Creates or returns the Action model using the provided mongoose instance and schema
1703
+ */
1704
+ function createActionModel(mongoose) {
1705
+ return mongoose.models.Action || mongoose.model('Action', Action);
1706
+ }
1707
+
1708
+ /**
1709
+ * Creates or returns the Assistant model using the provided mongoose instance and schema
1710
+ */
1711
+ function createAssistantModel(mongoose) {
1712
+ return mongoose.models.Assistant || mongoose.model('Assistant', assistantSchema);
1713
+ }
1714
+
1715
+ /**
1716
+ * Creates or returns the File model using the provided mongoose instance and schema
1717
+ */
1718
+ function createFileModel(mongoose) {
1719
+ return mongoose.models.File || mongoose.model('File', file);
1720
+ }
1721
+
1722
+ /**
1723
+ * Creates or returns the Banner model using the provided mongoose instance and schema
1724
+ */
1725
+ function createBannerModel(mongoose) {
1726
+ return mongoose.models.Banner || mongoose.model('Banner', bannerSchema);
1727
+ }
1728
+
1729
+ /**
1730
+ * Creates or returns the Project model using the provided mongoose instance and schema
1731
+ */
1732
+ function createProjectModel(mongoose) {
1733
+ return mongoose.models.Project || mongoose.model('Project', projectSchema);
1734
+ }
1735
+
1736
+ /**
1737
+ * Creates or returns the Key model using the provided mongoose instance and schema
1738
+ */
1739
+ function createKeyModel(mongoose) {
1740
+ return mongoose.models.Key || mongoose.model('Key', keySchema);
1741
+ }
1742
+
1743
+ /**
1744
+ * Creates or returns the PluginAuth model using the provided mongoose instance and schema
1745
+ */
1746
+ function createPluginAuthModel(mongoose) {
1747
+ return mongoose.models.PluginAuth || mongoose.model('PluginAuth', pluginAuthSchema);
1748
+ }
1749
+
1750
+ /**
1751
+ * Creates or returns the Transaction model using the provided mongoose instance and schema
1752
+ */
1753
+ function createTransactionModel(mongoose) {
1754
+ return (mongoose.models.Transaction || mongoose.model('Transaction', transactionSchema));
1755
+ }
1756
+
1757
+ /**
1758
+ * Creates or returns the Preset model using the provided mongoose instance and schema
1759
+ */
1760
+ function createPresetModel(mongoose) {
1761
+ return mongoose.models.Preset || mongoose.model('Preset', presetSchema);
1762
+ }
1763
+
1764
+ /**
1765
+ * Creates or returns the Prompt model using the provided mongoose instance and schema
1766
+ */
1767
+ function createPromptModel(mongoose) {
1768
+ return mongoose.models.Prompt || mongoose.model('Prompt', promptSchema);
1769
+ }
1770
+
1771
+ /**
1772
+ * Creates or returns the PromptGroup model using the provided mongoose instance and schema
1773
+ */
1774
+ function createPromptGroupModel(mongoose) {
1775
+ return (mongoose.models.PromptGroup ||
1776
+ mongoose.model('PromptGroup', promptGroupSchema));
1777
+ }
1778
+
1779
+ /**
1780
+ * Creates or returns the ConversationTag model using the provided mongoose instance and schema
1781
+ */
1782
+ function createConversationTagModel(mongoose) {
1783
+ return (mongoose.models.ConversationTag ||
1784
+ mongoose.model('ConversationTag', conversationTag));
1785
+ }
1786
+
1787
+ /**
1788
+ * Creates or returns the SharedLink model using the provided mongoose instance and schema
1789
+ */
1790
+ function createSharedLinkModel(mongoose) {
1791
+ return mongoose.models.SharedLink || mongoose.model('SharedLink', shareSchema);
1792
+ }
1793
+
1794
+ /**
1795
+ * Creates or returns the ToolCall model using the provided mongoose instance and schema
1796
+ */
1797
+ function createToolCallModel(mongoose) {
1798
+ return mongoose.models.ToolCall || mongoose.model('ToolCall', toolCallSchema);
1799
+ }
1800
+
1801
+ /**
1802
+ * Creates all database models for all collections
1803
+ */
1804
+ function createModels(mongoose) {
1805
+ return {
1806
+ User: createUserModel(mongoose),
1807
+ Token: createTokenModel(mongoose),
1808
+ Session: createSessionModel(mongoose),
1809
+ Balance: createBalanceModel(mongoose),
1810
+ Conversation: createConversationModel(mongoose),
1811
+ Message: createMessageModel(mongoose),
1812
+ Agent: createAgentModel(mongoose),
1813
+ Role: createRoleModel(mongoose),
1814
+ Action: createActionModel(mongoose),
1815
+ Assistant: createAssistantModel(mongoose),
1816
+ File: createFileModel(mongoose),
1817
+ Banner: createBannerModel(mongoose),
1818
+ Project: createProjectModel(mongoose),
1819
+ Key: createKeyModel(mongoose),
1820
+ PluginAuth: createPluginAuthModel(mongoose),
1821
+ Transaction: createTransactionModel(mongoose),
1822
+ Preset: createPresetModel(mongoose),
1823
+ Prompt: createPromptModel(mongoose),
1824
+ PromptGroup: createPromptGroupModel(mongoose),
1825
+ ConversationTag: createConversationTagModel(mongoose),
1826
+ SharedLink: createSharedLinkModel(mongoose),
1827
+ ToolCall: createToolCallModel(mongoose),
1828
+ };
1829
+ }
1830
+
1831
+ /** Factory function that takes mongoose instance and returns the methods */
1832
+ function createUserMethods(mongoose) {
1833
+ /**
1834
+ * Search for a single user based on partial data and return matching user document as plain object.
1835
+ */
1836
+ async function findUser(searchCriteria, fieldsToSelect) {
1837
+ const User = mongoose.models.User;
1838
+ const query = User.findOne(searchCriteria);
1839
+ if (fieldsToSelect) {
1840
+ query.select(fieldsToSelect);
1841
+ }
1842
+ return (await query.lean());
1843
+ }
1844
+ /**
1845
+ * Count the number of user documents in the collection based on the provided filter.
1846
+ */
1847
+ async function countUsers(filter = {}) {
1848
+ const User = mongoose.models.User;
1849
+ return await User.countDocuments(filter);
1850
+ }
1851
+ /**
1852
+ * Creates a new user, optionally with a TTL of 1 week.
1853
+ */
1854
+ async function createUser(data, balanceConfig, disableTTL = true, returnUser = false) {
1855
+ const User = mongoose.models.User;
1856
+ const Balance = mongoose.models.Balance;
1857
+ const userData = {
1858
+ ...data,
1859
+ expiresAt: disableTTL ? undefined : new Date(Date.now() + 604800 * 1000), // 1 week in milliseconds
1860
+ };
1861
+ if (disableTTL) {
1862
+ delete userData.expiresAt;
1863
+ }
1864
+ const user = await User.create(userData);
1865
+ // If balance is enabled, create or update a balance record for the user
1866
+ if ((balanceConfig === null || balanceConfig === void 0 ? void 0 : balanceConfig.enabled) && (balanceConfig === null || balanceConfig === void 0 ? void 0 : balanceConfig.startBalance)) {
1867
+ const update = {
1868
+ $inc: { tokenCredits: balanceConfig.startBalance },
1869
+ };
1870
+ if (balanceConfig.autoRefillEnabled &&
1871
+ balanceConfig.refillIntervalValue != null &&
1872
+ balanceConfig.refillIntervalUnit != null &&
1873
+ balanceConfig.refillAmount != null) {
1874
+ update.$set = {
1875
+ autoRefillEnabled: true,
1876
+ refillIntervalValue: balanceConfig.refillIntervalValue,
1877
+ refillIntervalUnit: balanceConfig.refillIntervalUnit,
1878
+ refillAmount: balanceConfig.refillAmount,
1879
+ };
1880
+ }
1881
+ await Balance.findOneAndUpdate({ user: user._id }, update, {
1882
+ upsert: true,
1883
+ new: true,
1884
+ }).lean();
1885
+ }
1886
+ if (returnUser) {
1887
+ return user.toObject();
1888
+ }
1889
+ return user._id;
1890
+ }
1891
+ /**
1892
+ * Update a user with new data without overwriting existing properties.
1893
+ */
1894
+ async function updateUser(userId, updateData) {
1895
+ const User = mongoose.models.User;
1896
+ const updateOperation = {
1897
+ $set: updateData,
1898
+ $unset: { expiresAt: '' }, // Remove the expiresAt field to prevent TTL
1899
+ };
1900
+ return (await User.findByIdAndUpdate(userId, updateOperation, {
1901
+ new: true,
1902
+ runValidators: true,
1903
+ }).lean());
1904
+ }
1905
+ /**
1906
+ * Retrieve a user by ID and convert the found user document to a plain object.
1907
+ */
1908
+ async function getUserById(userId, fieldsToSelect) {
1909
+ const User = mongoose.models.User;
1910
+ const query = User.findById(userId);
1911
+ if (fieldsToSelect) {
1912
+ query.select(fieldsToSelect);
1913
+ }
1914
+ return (await query.lean());
1915
+ }
1916
+ /**
1917
+ * Delete a user by their unique ID.
1918
+ */
1919
+ async function deleteUserById(userId) {
1920
+ try {
1921
+ const User = mongoose.models.User;
1922
+ const result = await User.deleteOne({ _id: userId });
1923
+ if (result.deletedCount === 0) {
1924
+ return { deletedCount: 0, message: 'No user found with that ID.' };
1925
+ }
1926
+ return { deletedCount: result.deletedCount, message: 'User was deleted successfully.' };
1927
+ }
1928
+ catch (error) {
1929
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
1930
+ throw new Error('Error deleting user: ' + errorMessage);
1931
+ }
1932
+ }
1933
+ /**
1934
+ * Generates a JWT token for a given user.
1935
+ */
1936
+ async function generateToken(user) {
1937
+ if (!user) {
1938
+ throw new Error('No user provided');
1939
+ }
1940
+ let expires = 1000 * 60 * 15;
1941
+ if (process.env.SESSION_EXPIRY !== undefined && process.env.SESSION_EXPIRY !== '') {
1942
+ try {
1943
+ const evaluated = eval(process.env.SESSION_EXPIRY);
1944
+ if (evaluated) {
1945
+ expires = evaluated;
1946
+ }
1947
+ }
1948
+ catch (error) {
1949
+ console.warn('Invalid SESSION_EXPIRY expression, using default:', error);
1950
+ }
1951
+ }
1952
+ return await signPayload({
1953
+ payload: {
1954
+ id: user._id,
1955
+ username: user.username,
1956
+ provider: user.provider,
1957
+ email: user.email,
1958
+ },
1959
+ secret: process.env.JWT_SECRET,
1960
+ expirationTime: expires / 1000,
1961
+ });
1962
+ }
1963
+ // Return all methods
1964
+ return {
1965
+ findUser,
1966
+ countUsers,
1967
+ createUser,
1968
+ updateUser,
1969
+ getUserById,
1970
+ deleteUserById,
1971
+ generateToken,
1972
+ };
1973
+ }
1974
+
1975
+ const SPLAT_SYMBOL = Symbol.for('splat');
1976
+ const MESSAGE_SYMBOL = Symbol.for('message');
1977
+ const CONSOLE_JSON_STRING_LENGTH = parseInt(process.env.CONSOLE_JSON_STRING_LENGTH || '', 10) || 255;
1978
+ const sensitiveKeys = [
1979
+ /^(sk-)[^\s]+/, // OpenAI API key pattern
1980
+ /(Bearer )[^\s]+/, // Header: Bearer token pattern
1981
+ /(api-key:? )[^\s]+/, // Header: API key pattern
1982
+ /(key=)[^\s]+/, // URL query param: sensitive key pattern (Google)
1983
+ ];
1984
+ /**
1985
+ * Determines if a given value string is sensitive and returns matching regex patterns.
1986
+ *
1987
+ * @param valueStr - The value string to check.
1988
+ * @returns An array of regex patterns that match the value string.
1989
+ */
1990
+ function getMatchingSensitivePatterns(valueStr) {
1991
+ if (valueStr) {
1992
+ // Filter and return all regex patterns that match the value string
1993
+ return sensitiveKeys.filter((regex) => regex.test(valueStr));
1994
+ }
1995
+ return [];
1996
+ }
1997
+ /**
1998
+ * Redacts sensitive information from a console message and trims it to a specified length if provided.
1999
+ * @param str - The console message to be redacted.
2000
+ * @param trimLength - The optional length at which to trim the redacted message.
2001
+ * @returns The redacted and optionally trimmed console message.
2002
+ */
2003
+ function redactMessage(str, trimLength) {
2004
+ if (!str) {
2005
+ return '';
2006
+ }
2007
+ const patterns = getMatchingSensitivePatterns(str);
2008
+ patterns.forEach((pattern) => {
2009
+ str = str.replace(pattern, '$1[REDACTED]');
2010
+ });
2011
+ return str;
2012
+ }
2013
+ /**
2014
+ * Redacts sensitive information from log messages if the log level is 'error'.
2015
+ * Note: Intentionally mutates the object.
2016
+ * @param info - The log information object.
2017
+ * @returns The modified log information object.
2018
+ */
2019
+ const redactFormat = winston.format((info) => {
2020
+ if (info.level === 'error') {
2021
+ // Type guard to ensure message is a string
2022
+ if (typeof info.message === 'string') {
2023
+ info.message = redactMessage(info.message);
2024
+ }
2025
+ // Handle MESSAGE_SYMBOL with type safety
2026
+ const symbolValue = info[MESSAGE_SYMBOL];
2027
+ if (typeof symbolValue === 'string') {
2028
+ info[MESSAGE_SYMBOL] = redactMessage(symbolValue);
2029
+ }
2030
+ }
2031
+ return info;
2032
+ });
2033
+ /**
2034
+ * Truncates long strings, especially base64 image data, within log messages.
2035
+ *
2036
+ * @param value - The value to be inspected and potentially truncated.
2037
+ * @param length - The length at which to truncate the value. Default: 100.
2038
+ * @returns The truncated or original value.
2039
+ */
2040
+ const truncateLongStrings = (value, length = 100) => {
2041
+ if (typeof value === 'string') {
2042
+ return value.length > length ? value.substring(0, length) + '... [truncated]' : value;
2043
+ }
2044
+ return value;
2045
+ };
2046
+ /**
2047
+ * An array mapping function that truncates long strings (objects converted to JSON strings).
2048
+ * @param item - The item to be condensed.
2049
+ * @returns The condensed item.
2050
+ */
2051
+ const condenseArray = (item) => {
2052
+ if (typeof item === 'string') {
2053
+ return truncateLongStrings(JSON.stringify(item));
2054
+ }
2055
+ else if (typeof item === 'object') {
2056
+ return truncateLongStrings(JSON.stringify(item));
2057
+ }
2058
+ return item;
2059
+ };
2060
+ /**
2061
+ * Formats log messages for debugging purposes.
2062
+ * - Truncates long strings within log messages.
2063
+ * - Condenses arrays by truncating long strings and objects as strings within array items.
2064
+ * - Redacts sensitive information from log messages if the log level is 'error'.
2065
+ * - Converts log information object to a formatted string.
2066
+ *
2067
+ * @param options - The options for formatting log messages.
2068
+ * @returns The formatted log message.
2069
+ */
2070
+ const debugTraverse = winston.format.printf(({ level, message, timestamp, ...metadata }) => {
2071
+ if (!message) {
2072
+ return `${timestamp} ${level}`;
2073
+ }
2074
+ // Type-safe version of the CJS logic: !message?.trim || typeof message !== 'string'
2075
+ if (typeof message !== 'string' || !message.trim) {
2076
+ return `${timestamp} ${level}: ${JSON.stringify(message)}`;
2077
+ }
2078
+ let msg = `${timestamp} ${level}: ${truncateLongStrings(message.trim(), 150)}`;
2079
+ try {
2080
+ if (level !== 'debug') {
2081
+ return msg;
2082
+ }
2083
+ if (!metadata) {
2084
+ return msg;
2085
+ }
2086
+ // Type-safe access to SPLAT_SYMBOL using bracket notation
2087
+ const metadataRecord = metadata;
2088
+ const splatArray = metadataRecord[SPLAT_SYMBOL];
2089
+ const debugValue = Array.isArray(splatArray) ? splatArray[0] : undefined;
2090
+ if (!debugValue) {
2091
+ return msg;
2092
+ }
2093
+ if (debugValue && Array.isArray(debugValue)) {
2094
+ msg += `\n${JSON.stringify(debugValue.map(condenseArray))}`;
2095
+ return msg;
2096
+ }
2097
+ if (typeof debugValue !== 'object') {
2098
+ return (msg += ` ${debugValue}`);
2099
+ }
2100
+ msg += '\n{';
2101
+ const copy = klona.klona(metadata);
2102
+ traverse(copy).forEach(function (value) {
2103
+ var _a;
2104
+ if (typeof (this === null || this === void 0 ? void 0 : this.key) === 'symbol') {
2105
+ return;
2106
+ }
2107
+ let _parentKey = '';
2108
+ const parent = this.parent;
2109
+ if (typeof (parent === null || parent === void 0 ? void 0 : parent.key) !== 'symbol' && (parent === null || parent === void 0 ? void 0 : parent.key)) {
2110
+ _parentKey = parent.key;
2111
+ }
2112
+ const parentKey = `${parent && parent.notRoot ? _parentKey + '.' : ''}`;
2113
+ const tabs = `${parent && parent.notRoot ? ' ' : ' '}`;
2114
+ const currentKey = (_a = this === null || this === void 0 ? void 0 : this.key) !== null && _a !== void 0 ? _a : 'unknown';
2115
+ if (this.isLeaf && typeof value === 'string') {
2116
+ const truncatedText = truncateLongStrings(value);
2117
+ msg += `\n${tabs}${parentKey}${currentKey}: ${JSON.stringify(truncatedText)},`;
2118
+ }
2119
+ else if (this.notLeaf && Array.isArray(value) && value.length > 0) {
2120
+ const currentMessage = `\n${tabs}// ${value.length} ${currentKey.replace(/s$/, '')}(s)`;
2121
+ this.update(currentMessage, true);
2122
+ msg += currentMessage;
2123
+ const stringifiedArray = value.map(condenseArray);
2124
+ msg += `\n${tabs}${parentKey}${currentKey}: [${stringifiedArray}],`;
2125
+ }
2126
+ else if (this.isLeaf && typeof value === 'function') {
2127
+ msg += `\n${tabs}${parentKey}${currentKey}: function,`;
2128
+ }
2129
+ else if (this.isLeaf) {
2130
+ msg += `\n${tabs}${parentKey}${currentKey}: ${value},`;
2131
+ }
2132
+ });
2133
+ msg += '\n}';
2134
+ return msg;
2135
+ }
2136
+ catch (e) {
2137
+ const errorMessage = e instanceof Error ? e.message : 'Unknown error';
2138
+ return (msg += `\n[LOGGER PARSING ERROR] ${errorMessage}`);
2139
+ }
2140
+ });
2141
+ /**
2142
+ * Truncates long string values in JSON log objects.
2143
+ * Prevents outputting extremely long values (e.g., base64, blobs).
2144
+ */
2145
+ const jsonTruncateFormat = winston.format((info) => {
2146
+ const truncateLongStrings = (str, maxLength) => str.length > maxLength ? str.substring(0, maxLength) + '...' : str;
2147
+ const seen = new WeakSet();
2148
+ const truncateObject = (obj) => {
2149
+ if (typeof obj !== 'object' || obj === null) {
2150
+ return obj;
2151
+ }
2152
+ // Handle circular references - now with proper object type
2153
+ if (seen.has(obj)) {
2154
+ return '[Circular]';
2155
+ }
2156
+ seen.add(obj);
2157
+ if (Array.isArray(obj)) {
2158
+ return obj.map((item) => truncateObject(item));
2159
+ }
2160
+ // We know this is an object at this point
2161
+ const objectRecord = obj;
2162
+ const newObj = {};
2163
+ Object.entries(objectRecord).forEach(([key, value]) => {
2164
+ if (typeof value === 'string') {
2165
+ newObj[key] = truncateLongStrings(value, CONSOLE_JSON_STRING_LENGTH);
2166
+ }
2167
+ else {
2168
+ newObj[key] = truncateObject(value);
2169
+ }
2170
+ });
2171
+ return newObj;
2172
+ };
2173
+ return truncateObject(info);
2174
+ });
2175
+
2176
+ // Define log directory
2177
+ const logDir = path.join(__dirname, '..', 'logs');
2178
+ // Type-safe environment variables
2179
+ const { NODE_ENV, DEBUG_LOGGING, CONSOLE_JSON, DEBUG_CONSOLE } = process.env;
2180
+ const useConsoleJson = typeof CONSOLE_JSON === 'string' && CONSOLE_JSON.toLowerCase() === 'true';
2181
+ const useDebugConsole = typeof DEBUG_CONSOLE === 'string' && DEBUG_CONSOLE.toLowerCase() === 'true';
2182
+ const useDebugLogging = typeof DEBUG_LOGGING === 'string' && DEBUG_LOGGING.toLowerCase() === 'true';
2183
+ // Define custom log levels
2184
+ const levels = {
2185
+ error: 0,
2186
+ warn: 1,
2187
+ info: 2,
2188
+ http: 3,
2189
+ verbose: 4,
2190
+ debug: 5,
2191
+ activity: 6,
2192
+ silly: 7,
2193
+ };
2194
+ winston.addColors({
2195
+ info: 'green',
2196
+ warn: 'italic yellow',
2197
+ error: 'red',
2198
+ debug: 'blue',
2199
+ });
2200
+ const level = () => {
2201
+ const env = NODE_ENV || 'development';
2202
+ return env === 'development' ? 'debug' : 'warn';
2203
+ };
2204
+ const fileFormat = winston.format.combine(redactFormat(), winston.format.timestamp({ format: () => new Date().toISOString() }), winston.format.errors({ stack: true }), winston.format.splat());
2205
+ const transports = [
2206
+ new winston.transports.DailyRotateFile({
2207
+ level: 'error',
2208
+ filename: `${logDir}/error-%DATE%.log`,
2209
+ datePattern: 'YYYY-MM-DD',
2210
+ zippedArchive: true,
2211
+ maxSize: '20m',
2212
+ maxFiles: '14d',
2213
+ format: fileFormat,
2214
+ }),
2215
+ ];
2216
+ if (useDebugLogging) {
2217
+ transports.push(new winston.transports.DailyRotateFile({
2218
+ level: 'debug',
2219
+ filename: `${logDir}/debug-%DATE%.log`,
2220
+ datePattern: 'YYYY-MM-DD',
2221
+ zippedArchive: true,
2222
+ maxSize: '20m',
2223
+ maxFiles: '14d',
2224
+ format: winston.format.combine(fileFormat, debugTraverse),
2225
+ }));
2226
+ }
2227
+ const consoleFormat = winston.format.combine(redactFormat(), winston.format.colorize({ all: true }), winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }), winston.format.printf((info) => {
2228
+ const message = `${info.timestamp} ${info.level}: ${info.message}`;
2229
+ return info.level.includes('error') ? redactMessage(message) : message;
2230
+ }));
2231
+ let consoleLogLevel = 'info';
2232
+ if (useDebugConsole) {
2233
+ consoleLogLevel = 'debug';
2234
+ }
2235
+ // Add console transport
2236
+ if (useDebugConsole) {
2237
+ transports.push(new winston.transports.Console({
2238
+ level: consoleLogLevel,
2239
+ format: useConsoleJson
2240
+ ? winston.format.combine(fileFormat, jsonTruncateFormat(), winston.format.json())
2241
+ : winston.format.combine(fileFormat, debugTraverse),
2242
+ }));
2243
+ }
2244
+ else if (useConsoleJson) {
2245
+ transports.push(new winston.transports.Console({
2246
+ level: consoleLogLevel,
2247
+ format: winston.format.combine(fileFormat, jsonTruncateFormat(), winston.format.json()),
2248
+ }));
2249
+ }
2250
+ else {
2251
+ transports.push(new winston.transports.Console({
2252
+ level: consoleLogLevel,
2253
+ format: consoleFormat,
2254
+ }));
2255
+ }
2256
+ // Create logger
2257
+ const logger = winston.createLogger({
2258
+ level: level(),
2259
+ levels,
2260
+ transports,
2261
+ });
2262
+
2263
+ var _a, _b;
2264
+ class SessionError extends Error {
2265
+ constructor(message, code = 'SESSION_ERROR') {
2266
+ super(message);
2267
+ this.name = 'SessionError';
2268
+ this.code = code;
2269
+ }
2270
+ }
2271
+ const { REFRESH_TOKEN_EXPIRY } = (_a = process.env) !== null && _a !== void 0 ? _a : {};
2272
+ const expires = (_b = eval(REFRESH_TOKEN_EXPIRY !== null && REFRESH_TOKEN_EXPIRY !== void 0 ? REFRESH_TOKEN_EXPIRY : '0')) !== null && _b !== void 0 ? _b : 1000 * 60 * 60 * 24 * 7; // 7 days default
2273
+ // Factory function that takes mongoose instance and returns the methods
2274
+ function createSessionMethods(mongoose) {
2275
+ const Session = mongoose.models.Session;
2276
+ /**
2277
+ * Creates a new session for a user
2278
+ */
2279
+ async function createSession(userId, options = {}) {
2280
+ if (!userId) {
2281
+ throw new SessionError('User ID is required', 'INVALID_USER_ID');
2282
+ }
2283
+ try {
2284
+ const session = new Session({
2285
+ user: userId,
2286
+ expiration: options.expiration || new Date(Date.now() + expires),
2287
+ });
2288
+ const refreshToken = await generateRefreshToken(session);
2289
+ return { session, refreshToken };
2290
+ }
2291
+ catch (error) {
2292
+ logger.error('[createSession] Error creating session:', error);
2293
+ throw new SessionError('Failed to create session', 'CREATE_SESSION_FAILED');
2294
+ }
2295
+ }
2296
+ /**
2297
+ * Finds a session by various parameters
2298
+ */
2299
+ async function findSession(params, options = { lean: true }) {
2300
+ try {
2301
+ const query = {};
2302
+ if (!params.refreshToken && !params.userId && !params.sessionId) {
2303
+ throw new SessionError('At least one search parameter is required', 'INVALID_SEARCH_PARAMS');
2304
+ }
2305
+ if (params.refreshToken) {
2306
+ const tokenHash = await hashToken(params.refreshToken);
2307
+ query.refreshTokenHash = tokenHash;
2308
+ }
2309
+ if (params.userId) {
2310
+ query.user = params.userId;
2311
+ }
2312
+ if (params.sessionId) {
2313
+ const sessionId = typeof params.sessionId === 'object' &&
2314
+ params.sessionId !== null &&
2315
+ 'sessionId' in params.sessionId
2316
+ ? params.sessionId.sessionId
2317
+ : params.sessionId;
2318
+ if (!mongoose.Types.ObjectId.isValid(sessionId)) {
2319
+ throw new SessionError('Invalid session ID format', 'INVALID_SESSION_ID');
2320
+ }
2321
+ query._id = sessionId;
2322
+ }
2323
+ // Add expiration check to only return valid sessions
2324
+ query.expiration = { $gt: new Date() };
2325
+ const sessionQuery = Session.findOne(query);
2326
+ if (options.lean) {
2327
+ return (await sessionQuery.lean());
2328
+ }
2329
+ return await sessionQuery.exec();
2330
+ }
2331
+ catch (error) {
2332
+ logger.error('[findSession] Error finding session:', error);
2333
+ throw new SessionError('Failed to find session', 'FIND_SESSION_FAILED');
2334
+ }
2335
+ }
2336
+ /**
2337
+ * Updates session expiration
2338
+ */
2339
+ async function updateExpiration(session, newExpiration) {
2340
+ try {
2341
+ const sessionDoc = typeof session === 'string' ? await Session.findById(session) : session;
2342
+ if (!sessionDoc) {
2343
+ throw new SessionError('Session not found', 'SESSION_NOT_FOUND');
2344
+ }
2345
+ sessionDoc.expiration = newExpiration || new Date(Date.now() + expires);
2346
+ return await sessionDoc.save();
2347
+ }
2348
+ catch (error) {
2349
+ logger.error('[updateExpiration] Error updating session:', error);
2350
+ throw new SessionError('Failed to update session expiration', 'UPDATE_EXPIRATION_FAILED');
2351
+ }
2352
+ }
2353
+ /**
2354
+ * Deletes a session by refresh token or session ID
2355
+ */
2356
+ async function deleteSession(params) {
2357
+ try {
2358
+ if (!params.refreshToken && !params.sessionId) {
2359
+ throw new SessionError('Either refreshToken or sessionId is required', 'INVALID_DELETE_PARAMS');
2360
+ }
2361
+ const query = {};
2362
+ if (params.refreshToken) {
2363
+ query.refreshTokenHash = await hashToken(params.refreshToken);
2364
+ }
2365
+ if (params.sessionId) {
2366
+ query._id = params.sessionId;
2367
+ }
2368
+ const result = await Session.deleteOne(query);
2369
+ if (result.deletedCount === 0) {
2370
+ logger.warn('[deleteSession] No session found to delete');
2371
+ }
2372
+ return result;
2373
+ }
2374
+ catch (error) {
2375
+ logger.error('[deleteSession] Error deleting session:', error);
2376
+ throw new SessionError('Failed to delete session', 'DELETE_SESSION_FAILED');
2377
+ }
2378
+ }
2379
+ /**
2380
+ * Deletes all sessions for a user
2381
+ */
2382
+ async function deleteAllUserSessions(userId, options = {}) {
2383
+ try {
2384
+ if (!userId) {
2385
+ throw new SessionError('User ID is required', 'INVALID_USER_ID');
2386
+ }
2387
+ const userIdString = typeof userId === 'object' && userId !== null ? userId.userId : userId;
2388
+ if (!mongoose.Types.ObjectId.isValid(userIdString)) {
2389
+ throw new SessionError('Invalid user ID format', 'INVALID_USER_ID_FORMAT');
2390
+ }
2391
+ const query = { user: userIdString };
2392
+ if (options.excludeCurrentSession && options.currentSessionId) {
2393
+ query._id = { $ne: options.currentSessionId };
2394
+ }
2395
+ const result = await Session.deleteMany(query);
2396
+ if (result.deletedCount && result.deletedCount > 0) {
2397
+ logger.debug(`[deleteAllUserSessions] Deleted ${result.deletedCount} sessions for user ${userIdString}.`);
2398
+ }
2399
+ return result;
2400
+ }
2401
+ catch (error) {
2402
+ logger.error('[deleteAllUserSessions] Error deleting user sessions:', error);
2403
+ throw new SessionError('Failed to delete user sessions', 'DELETE_ALL_SESSIONS_FAILED');
2404
+ }
2405
+ }
2406
+ /**
2407
+ * Generates a refresh token for a session
2408
+ */
2409
+ async function generateRefreshToken(session) {
2410
+ if (!session || !session.user) {
2411
+ throw new SessionError('Invalid session object', 'INVALID_SESSION');
2412
+ }
2413
+ try {
2414
+ const expiresIn = session.expiration ? session.expiration.getTime() : Date.now() + expires;
2415
+ if (!session.expiration) {
2416
+ session.expiration = new Date(expiresIn);
2417
+ }
2418
+ const refreshToken = await signPayload({
2419
+ payload: {
2420
+ id: session.user,
2421
+ sessionId: session._id,
2422
+ },
2423
+ secret: process.env.JWT_REFRESH_SECRET,
2424
+ expirationTime: Math.floor((expiresIn - Date.now()) / 1000),
2425
+ });
2426
+ session.refreshTokenHash = await hashToken(refreshToken);
2427
+ await session.save();
2428
+ return refreshToken;
2429
+ }
2430
+ catch (error) {
2431
+ logger.error('[generateRefreshToken] Error generating refresh token:', error);
2432
+ throw new SessionError('Failed to generate refresh token', 'GENERATE_TOKEN_FAILED');
2433
+ }
2434
+ }
2435
+ /**
2436
+ * Counts active sessions for a user
2437
+ */
2438
+ async function countActiveSessions(userId) {
2439
+ try {
2440
+ if (!userId) {
2441
+ throw new SessionError('User ID is required', 'INVALID_USER_ID');
2442
+ }
2443
+ return await Session.countDocuments({
2444
+ user: userId,
2445
+ expiration: { $gt: new Date() },
2446
+ });
2447
+ }
2448
+ catch (error) {
2449
+ logger.error('[countActiveSessions] Error counting active sessions:', error);
2450
+ throw new SessionError('Failed to count active sessions', 'COUNT_SESSIONS_FAILED');
2451
+ }
2452
+ }
2453
+ return {
2454
+ findSession,
2455
+ SessionError,
2456
+ deleteSession,
2457
+ createSession,
2458
+ updateExpiration,
2459
+ countActiveSessions,
2460
+ generateRefreshToken,
2461
+ deleteAllUserSessions,
2462
+ };
2463
+ }
2464
+
2465
+ // Factory function that takes mongoose instance and returns the methods
2466
+ function createTokenMethods(mongoose) {
2467
+ /**
2468
+ * Creates a new Token instance.
2469
+ */
2470
+ async function createToken(tokenData) {
2471
+ try {
2472
+ const Token = mongoose.models.Token;
2473
+ const currentTime = new Date();
2474
+ const expiresAt = new Date(currentTime.getTime() + tokenData.expiresIn * 1000);
2475
+ const newTokenData = {
2476
+ ...tokenData,
2477
+ createdAt: currentTime,
2478
+ expiresAt,
2479
+ };
2480
+ return await Token.create(newTokenData);
2481
+ }
2482
+ catch (error) {
2483
+ logger.debug('An error occurred while creating token:', error);
2484
+ throw error;
2485
+ }
2486
+ }
2487
+ /**
2488
+ * Updates a Token document that matches the provided query.
2489
+ */
2490
+ async function updateToken(query, updateData) {
2491
+ try {
2492
+ const Token = mongoose.models.Token;
2493
+ return await Token.findOneAndUpdate(query, updateData, { new: true });
2494
+ }
2495
+ catch (error) {
2496
+ logger.debug('An error occurred while updating token:', error);
2497
+ throw error;
2498
+ }
2499
+ }
2500
+ /**
2501
+ * Deletes all Token documents that match the provided token, user ID, or email.
2502
+ */
2503
+ async function deleteTokens(query) {
2504
+ try {
2505
+ const Token = mongoose.models.Token;
2506
+ return await Token.deleteMany({
2507
+ $or: [
2508
+ { userId: query.userId },
2509
+ { token: query.token },
2510
+ { email: query.email },
2511
+ { identifier: query.identifier },
2512
+ ],
2513
+ });
2514
+ }
2515
+ catch (error) {
2516
+ logger.debug('An error occurred while deleting tokens:', error);
2517
+ throw error;
2518
+ }
2519
+ }
2520
+ /**
2521
+ * Finds a Token document that matches the provided query.
2522
+ */
2523
+ async function findToken(query) {
2524
+ try {
2525
+ const Token = mongoose.models.Token;
2526
+ const conditions = [];
2527
+ if (query.userId) {
2528
+ conditions.push({ userId: query.userId });
2529
+ }
2530
+ if (query.token) {
2531
+ conditions.push({ token: query.token });
2532
+ }
2533
+ if (query.email) {
2534
+ conditions.push({ email: query.email });
2535
+ }
2536
+ if (query.identifier) {
2537
+ conditions.push({ identifier: query.identifier });
2538
+ }
2539
+ const token = await Token.findOne({
2540
+ $and: conditions,
2541
+ }).lean();
2542
+ return token;
2543
+ }
2544
+ catch (error) {
2545
+ logger.debug('An error occurred while finding token:', error);
2546
+ throw error;
2547
+ }
2548
+ }
2549
+ // Return all methods
2550
+ return {
2551
+ findToken,
2552
+ createToken,
2553
+ updateToken,
2554
+ deleteTokens,
2555
+ };
2556
+ }
2557
+
2558
+ // Factory function that takes mongoose instance and returns the methods
2559
+ function createRoleMethods(mongoose) {
2560
+ /**
2561
+ * Initialize default roles in the system.
2562
+ * Creates the default roles (ADMIN, USER) if they don't exist in the database.
2563
+ * Updates existing roles with new permission types if they're missing.
2564
+ */
2565
+ async function initializeRoles() {
2566
+ const Role = mongoose.models.Role;
2567
+ for (const roleName of [librechatDataProvider.SystemRoles.ADMIN, librechatDataProvider.SystemRoles.USER]) {
2568
+ let role = await Role.findOne({ name: roleName });
2569
+ const defaultPerms = librechatDataProvider.roleDefaults[roleName].permissions;
2570
+ if (!role) {
2571
+ // Create new role if it doesn't exist.
2572
+ role = new Role(librechatDataProvider.roleDefaults[roleName]);
2573
+ }
2574
+ else {
2575
+ // Ensure role.permissions is defined.
2576
+ role.permissions = role.permissions || {};
2577
+ // For each permission type in defaults, add it if missing.
2578
+ for (const permType of Object.keys(defaultPerms)) {
2579
+ if (role.permissions[permType] == null) {
2580
+ role.permissions[permType] = defaultPerms[permType];
2581
+ }
2582
+ }
2583
+ }
2584
+ await role.save();
2585
+ }
2586
+ }
2587
+ /**
2588
+ * List all roles in the system (for testing purposes)
2589
+ * Returns an array of all roles with their names and permissions
2590
+ */
2591
+ async function listRoles() {
2592
+ const Role = mongoose.models.Role;
2593
+ return await Role.find({}).select('name permissions').lean();
2594
+ }
2595
+ // Return all methods you want to expose
2596
+ return {
2597
+ listRoles,
2598
+ initializeRoles,
2599
+ };
2600
+ }
2601
+
2602
+ /**
2603
+ * Creates all database methods for all collections
2604
+ */
2605
+ function createMethods(mongoose) {
2606
+ return {
2607
+ ...createUserMethods(mongoose),
2608
+ ...createSessionMethods(mongoose),
2609
+ ...createTokenMethods(mongoose),
2610
+ ...createRoleMethods(mongoose),
2611
+ };
2612
+ }
2613
+
1153
2614
  exports.actionSchema = Action;
1154
2615
  exports.agentSchema = agentSchema;
1155
2616
  exports.assistantSchema = assistantSchema;
@@ -1158,8 +2619,13 @@ exports.bannerSchema = bannerSchema;
1158
2619
  exports.categoriesSchema = categoriesSchema;
1159
2620
  exports.conversationTagSchema = conversationTag;
1160
2621
  exports.convoSchema = convoSchema;
2622
+ exports.createMethods = createMethods;
2623
+ exports.createModels = createModels;
1161
2624
  exports.fileSchema = file;
2625
+ exports.hashToken = hashToken;
1162
2626
  exports.keySchema = keySchema;
2627
+ exports.logger = logger;
2628
+ exports.meiliLogger = logger$1;
1163
2629
  exports.messageSchema = messageSchema;
1164
2630
  exports.pluginAuthSchema = pluginAuthSchema;
1165
2631
  exports.presetSchema = presetSchema;
@@ -1169,8 +2635,9 @@ exports.promptSchema = promptSchema;
1169
2635
  exports.roleSchema = roleSchema;
1170
2636
  exports.sessionSchema = sessionSchema;
1171
2637
  exports.shareSchema = shareSchema;
2638
+ exports.signPayload = signPayload;
1172
2639
  exports.tokenSchema = tokenSchema;
1173
2640
  exports.toolCallSchema = toolCallSchema;
1174
2641
  exports.transactionSchema = transactionSchema;
1175
- exports.userSchema = User;
2642
+ exports.userSchema = userSchema;
1176
2643
  //# sourceMappingURL=index.cjs.map