@antzsoft/chat-core 1.4.3 → 1.4.4

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/dist/index.cjs CHANGED
@@ -1013,536 +1013,16 @@ function resolveSystemMessageText(message, currentUserId) {
1013
1013
  }
1014
1014
  }
1015
1015
 
1016
- // src/api/messages.ts
1017
- var MAX_FORWARD_TARGETS = 5;
1018
- var HIGHLY_FORWARDED_DEPTH_THRESHOLD = 5;
1019
- var messagesApi = {
1020
- async list(conversationId, params = {}) {
1021
- const { cursor, direction, ...rest } = params;
1022
- const serverParams = { ...rest };
1023
- if (cursor) {
1024
- serverParams[direction === "after" ? "after" : "before"] = cursor;
1025
- }
1026
- const { data } = await getApiClient().get(
1027
- `/conversations/${conversationId}/messages`,
1028
- { params: serverParams }
1029
- );
1030
- const currentUserId = getAuthStore().useAuthStore.getState().user?.id;
1031
- if (!currentUserId) return data;
1032
- return {
1033
- ...data,
1034
- data: data.data.map(
1035
- (m) => m.content.type === "system" ? { ...m, content: { ...m.content, text: resolveSystemMessageText(m, currentUserId) } } : m
1036
- )
1037
- };
1038
- },
1039
- async get(messageId) {
1040
- const { data } = await getApiClient().get(`/messages/${messageId}`);
1041
- return data;
1042
- },
1043
- async send(conversationId, payload) {
1044
- const { data } = await getApiClient().post(
1045
- `/conversations/${conversationId}/messages`,
1046
- payload
1047
- );
1048
- return data;
1049
- },
1050
- async update(messageId, text) {
1051
- const { data } = await getApiClient().post(`/messages/${messageId}/update`, { text });
1052
- return data;
1053
- },
1054
- async delete(messageId) {
1055
- await getApiClient().post(`/messages/${messageId}/delete`);
1056
- },
1057
- async deleteForMe(messageId) {
1058
- await getApiClient().post(`/messages/${messageId}/delete-for-me`);
1059
- },
1060
- async addReaction(messageId, emoji) {
1061
- const { data } = await getApiClient().post(`/messages/${messageId}/reactions`, { emoji });
1062
- return data;
1063
- },
1064
- async removeReaction(messageId, emoji) {
1065
- const { data } = await getApiClient().post(
1066
- `/messages/${messageId}/reactions/${encodeURIComponent(emoji)}/remove`
1067
- );
1068
- return data;
1069
- },
1070
- async getReactions(messageId) {
1071
- const { data } = await getApiClient().post(`/messages/${messageId}/reactions/list`);
1072
- return data;
1073
- },
1074
- async star(messageId) {
1075
- await getApiClient().post(`/messages/${messageId}/star`);
1076
- },
1077
- async unstar(messageId) {
1078
- await getApiClient().post(`/messages/${messageId}/unstar`);
1079
- },
1080
- async getStarred(params = {}) {
1081
- const { data } = await getApiClient().get("/messages/starred", { params });
1082
- return data;
1083
- },
1084
- async search(params) {
1085
- const { data } = await getApiClient().get("/messages/search", { params });
1086
- return data;
1087
- },
1088
- async getLastRead(conversationId) {
1089
- const { data } = await getApiClient().get(
1090
- `/conversations/${conversationId}/read-receipt`
1091
- );
1092
- return data;
1093
- },
1094
- async markAsRead(conversationId, messageId) {
1095
- await getApiClient().post(`/conversations/${conversationId}/read`, messageId ? { messageId } : {});
1096
- },
1097
- async pin(messageId) {
1098
- const { data } = await getApiClient().post(`/messages/${messageId}/pin`);
1099
- return data;
1100
- },
1101
- async unpin(messageId) {
1102
- const { data } = await getApiClient().post(`/messages/${messageId}/unpin`);
1103
- return data;
1104
- },
1105
- async getPinned(conversationId) {
1106
- const { data } = await getApiClient().get(`/conversations/${conversationId}/pinned-messages`);
1107
- return data;
1108
- },
1109
- async getReceipts(messageId) {
1110
- const { data } = await getApiClient().get(`/messages/${messageId}/receipts`);
1111
- return data;
1112
- },
1113
- /**
1114
- * Forwards a message into one or more target conversations (max MAX_FORWARD_TARGETS
1115
- * per call, also enforced server-side). Each target is independent — one failing
1116
- * (e.g. no longer a participant) does not block the others; check `success`/`error`
1117
- * per entry in the returned array.
1118
- *
1119
- * Pass `attachmentIds` to forward only a subset of the source message's attachments
1120
- * (e.g. one image out of a multi-image message) — omit it to forward the whole
1121
- * message, including all its attachments, unchanged. An ID not present on the
1122
- * source message is ignored server-side.
1123
- */
1124
- async forward(messageId, targetConversationIds, attachmentIds) {
1125
- const { data } = await getApiClient().post(
1126
- `/messages/${messageId}/forward`,
1127
- { targetConversationIds, ...attachmentIds ? { attachmentIds } : {} }
1128
- );
1129
- return data;
1130
- }
1131
- };
1132
-
1133
- // src/api/conversations.ts
1134
- function normalizeParticipant(p) {
1135
- const hasUserDetails = p.displayName || p.username || p.avatarUrl;
1136
- return {
1137
- userId: p.userId,
1138
- externalId: p.externalId ?? p.user?.externalId,
1139
- role: p.role,
1140
- joinedAt: p.joinedAt,
1141
- isActive: p.isActive,
1142
- user: hasUserDetails ? {
1143
- id: p.userId,
1144
- externalId: p.externalId,
1145
- tenantId: "",
1146
- email: "",
1147
- username: p.username ?? "",
1148
- displayName: p.displayName ?? p.username ?? "",
1149
- avatarUrl: p.avatarUrl,
1150
- status: "offline",
1151
- createdAt: p.joinedAt ?? "",
1152
- updatedAt: p.joinedAt ?? ""
1153
- } : p.user
1154
- };
1155
- }
1156
- function normalizeLastMessage(lastMsg) {
1157
- if (!lastMsg) return void 0;
1158
- if (lastMsg.content !== void 0) return lastMsg;
1159
- return {
1160
- id: lastMsg.messageId ?? "",
1161
- tenantId: "",
1162
- conversationId: "",
1163
- senderId: lastMsg.senderId ?? "",
1164
- content: {
1165
- type: lastMsg.hasAttachments ? "attachment" : "text",
1166
- text: lastMsg.contentPreview
1167
- },
1168
- reactions: [],
1169
- lastReaction: lastMsg.lastReaction ?? null,
1170
- status: lastMsg.status ?? "active",
1171
- deliveryStatus: lastMsg.deliveryStatus ?? "sent",
1172
- isEdited: false,
1173
- sentAt: lastMsg.sentAt ?? "",
1174
- createdAt: lastMsg.sentAt ?? "",
1175
- ...lastMsg.senderName && { senderName: lastMsg.senderName },
1176
- ...lastMsg.attachmentType && { attachmentType: lastMsg.attachmentType }
1177
- };
1178
- }
1179
- function normalizeConversation(conv) {
1180
- return {
1181
- ...conv,
1182
- id: conv.id ?? conv.conversationId,
1183
- participants: (conv.participants ?? []).map(normalizeParticipant),
1184
- lastMessage: normalizeLastMessage(conv.lastMessage)
1185
- };
1186
- }
1187
- var conversationsApi = {
1188
- async list(params = {}) {
1189
- const { data } = await getApiClient().get("/conversations", { params });
1190
- return { ...data, data: data.data.map(normalizeConversation) };
1191
- },
1192
- async get(conversationId) {
1193
- const { data } = await getApiClient().get(`/conversations/${conversationId}`);
1194
- return normalizeConversation(data);
1195
- },
1196
- async createGroup(payload) {
1197
- const { data } = await getApiClient().post("/conversations", payload);
1198
- return normalizeConversation(data);
1199
- },
1200
- async createDirect(payload) {
1201
- const { data } = await getApiClient().post("/conversations/direct", payload);
1202
- return normalizeConversation(data);
1203
- },
1204
- async update(conversationId, payload) {
1205
- const { data } = await getApiClient().post(`/conversations/${conversationId}/update`, payload);
1206
- return normalizeConversation(data);
1207
- },
1208
- async delete(conversationId) {
1209
- await getApiClient().post(`/conversations/${conversationId}/delete`);
1210
- },
1211
- async addParticipants(conversationId, userIds, role) {
1212
- const { data } = await getApiClient().post(
1213
- `/conversations/${conversationId}/participants`,
1214
- { userIds, ...role && { role } }
1215
- );
1216
- return normalizeConversation(data);
1217
- },
1218
- async removeParticipant(conversationId, userId) {
1219
- const { data } = await getApiClient().post(
1220
- `/conversations/${conversationId}/participants/${userId}/remove`
1221
- );
1222
- return normalizeConversation(data);
1223
- },
1224
- async updateParticipantRole(conversationId, userId, role) {
1225
- const { data } = await getApiClient().post(
1226
- `/conversations/${conversationId}/participants/${userId}/role`,
1227
- { role }
1228
- );
1229
- return normalizeConversation(data);
1230
- },
1231
- async mute(conversationId, mutedUntil) {
1232
- await getApiClient().post(`/conversations/${conversationId}/mute`, mutedUntil ? { mutedUntil } : {});
1233
- },
1234
- async unmute(conversationId) {
1235
- await getApiClient().post(`/conversations/${conversationId}/unmute`);
1236
- },
1237
- async pin(conversationId) {
1238
- await getApiClient().post(`/conversations/${conversationId}/pin`);
1239
- },
1240
- async unpin(conversationId) {
1241
- await getApiClient().post(`/conversations/${conversationId}/unpin`);
1242
- },
1243
- async markUnread(conversationId) {
1244
- await getApiClient().post(`/conversations/${conversationId}/unread`);
1245
- },
1246
- async markRead(conversationId) {
1247
- await getApiClient().post(`/conversations/${conversationId}/unread/clear`);
1248
- },
1249
- async leave(conversationId, andDelete) {
1250
- const url = andDelete ? `/conversations/${conversationId}/leave?delete=true` : `/conversations/${conversationId}/leave`;
1251
- await getApiClient().post(url);
1252
- },
1253
- async getMembers(conversationId, filter) {
1254
- const { data } = await getApiClient().get(
1255
- `/conversations/${conversationId}/participants`,
1256
- filter ? { params: { filter } } : void 0
1257
- );
1258
- return (data ?? []).map(normalizeParticipant);
1259
- },
1260
- /**
1261
- * Get unread message count for a single conversation.
1262
- * Use this after app foreground or socket reconnect to refresh a specific count.
1263
- */
1264
- async getUnreadCount(conversationId) {
1265
- const { data } = await getApiClient().get(
1266
- `/conversations/${conversationId}/unread`
1267
- );
1268
- return data;
1269
- },
1270
- /**
1271
- * Get total unread count across all conversations + per-conversation breakdown.
1272
- * Use on app cold start, foreground resume, or after socket reconnect.
1273
- * The socket keeps counts live while connected — this is the source of truth
1274
- * when the socket was down.
1275
- */
1276
- async getUnreadSummary() {
1277
- const { data } = await getApiClient().get("/conversations/unread");
1278
- return data;
1279
- },
1280
- /**
1281
- * Set the group icon from an already-uploaded file (admin only).
1282
- * The fileId comes from uploadBatch() / client.uploadFiles() — same as attachments.
1283
- * Server copies storageKey into conversation.iconMeta and deletes the chat_files record.
1284
- */
1285
- async uploadIcon(conversationId, fileId) {
1286
- const { data } = await getApiClient().post(
1287
- `/conversations/${conversationId}/icon`,
1288
- { fileId }
1289
- );
1290
- return normalizeConversation(data);
1291
- },
1292
- async removeIcon(conversationId) {
1293
- const { data } = await getApiClient().post(`/conversations/${conversationId}/icon/remove`);
1294
- return normalizeConversation(data);
1295
- },
1296
- async clearChat(conversationId) {
1297
- await getApiClient().post(`/conversations/${conversationId}/clear-for-me`);
1298
- }
1299
- };
1300
-
1301
- // src/crypto/uuid.ts
1302
- function generateUUID() {
1303
- if (typeof globalThis.crypto?.randomUUID === "function") {
1304
- return globalThis.crypto.randomUUID();
1305
- }
1306
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1307
- const r = Math.random() * 16 | 0;
1308
- return (c === "x" ? r : r & 3 | 8).toString(16);
1309
- });
1310
- }
1311
-
1312
- // src/api/storage.ts
1313
- var storageApi = {
1314
- async requestPresignedUrl(payload) {
1315
- const { data } = await getApiClient().post("/storage/presigned-url", payload);
1316
- return data;
1317
- },
1318
- async requestPresignedUrlBatch(files) {
1319
- const { data } = await getApiClient().post("/storage/presigned-url/batch", { files });
1320
- return data;
1321
- },
1322
- async confirmUpload(fileId) {
1323
- const { data } = await getApiClient().post(`/storage/confirm/${fileId}`);
1324
- return data;
1325
- },
1326
- async getFile(fileId) {
1327
- const { data } = await getApiClient().get(`/storage/files/${fileId}`);
1328
- return data;
1329
- },
1330
- async getFileUrl(fileId, expiresIn) {
1331
- const { data } = await getApiClient().get(`/storage/files/${fileId}/url`, {
1332
- params: expiresIn ? { expiresIn } : {}
1333
- });
1334
- return data;
1335
- },
1336
- async deleteFile(fileId) {
1337
- await getApiClient().post(`/storage/files/${fileId}/delete`);
1338
- },
1339
- async completeMultipartUpload(fileId, uploadId, parts) {
1340
- const { data } = await getApiClient().post(
1341
- `/storage/multipart/complete/${fileId}`,
1342
- { uploadId, parts }
1343
- );
1344
- return data;
1345
- },
1346
- async getConversationFiles(conversationId, params = {}) {
1347
- const { data } = await getApiClient().get(
1348
- `/storage/conversations/${conversationId}/files`,
1349
- { params }
1350
- );
1351
- return data;
1352
- },
1353
- async getMyFiles(params = {}) {
1354
- const { data } = await getApiClient().get("/storage/my-files", { params });
1355
- return data;
1356
- }
1357
- };
1358
- async function runMultipartUpload(presigned, file, platformUploadPartFn, onProgress) {
1359
- const { multipart } = presigned;
1360
- if (!multipart) throw new Error("No multipart info on presigned response");
1361
- const CONCURRENCY = 3;
1362
- const completedParts = [];
1363
- const partProgress = {};
1364
- multipart.partUrls.forEach(({ partNumber }) => {
1365
- partProgress[partNumber] = 0;
1366
- });
1367
- const reportProgress = () => {
1368
- if (!onProgress) return;
1369
- const vals = Object.values(partProgress);
1370
- const avg = vals.reduce((s, v) => s + v, 0) / Math.max(vals.length, 1);
1371
- onProgress(Math.round(avg * 0.95));
1372
- };
1373
- const uploadPart = async (partNumber, uploadUrl, method) => {
1374
- const offset = (partNumber - 1) * multipart.chunkSize;
1375
- const end = Math.min(offset + multipart.chunkSize, file.size);
1376
- const blob = await fetch(file.uri).then((r) => r.blob());
1377
- const slice = blob.slice(offset, end);
1378
- const etag = await platformUploadPartFn(uploadUrl, slice, (pct) => {
1379
- partProgress[partNumber] = pct;
1380
- reportProgress();
1381
- }, method);
1382
- completedParts.push({ partNumber, etag });
1383
- partProgress[partNumber] = 100;
1384
- reportProgress();
1385
- };
1386
- for (let i = 0; i < multipart.partUrls.length; i += CONCURRENCY) {
1387
- const batch = multipart.partUrls.slice(i, i + CONCURRENCY);
1388
- const results = await Promise.allSettled(
1389
- batch.map(({ partNumber, uploadUrl, method }) => uploadPart(partNumber, uploadUrl, method ?? "PUT"))
1390
- );
1391
- const failed = results.find((r) => r.status === "rejected");
1392
- if (failed) throw failed.reason;
1393
- }
1394
- completedParts.sort((a, b) => a.partNumber - b.partNumber);
1395
- const fileResponse = await storageApi.completeMultipartUpload(
1396
- presigned.fileId,
1397
- multipart.uploadId,
1398
- completedParts
1399
- );
1400
- onProgress?.(100);
1401
- return fileResponse;
1402
- }
1403
- async function runUploadBatch(files, platformUploadFn, slotIds, conversationId, onProgress, platformCompressFn, compressionConfig, platformUploadPartFn) {
1404
- const compressedFiles = await Promise.all(
1405
- files.map((f) => compressFile(f, platformCompressFn, compressionConfig ?? { enabled: false, imageQuality: 0.85, imageMaxDimension: 1920, compressDocuments: true }))
1406
- );
1407
- const slotted = compressedFiles.map((f, i) => ({ file: f, slotId: slotIds[i], clientIndex: i }));
1408
- const requests = slotted.map(({ file: f, clientIndex }) => ({
1409
- filename: f.name,
1410
- mimeType: f.type,
1411
- size: f.size,
1412
- conversationId,
1413
- clientIndex,
1414
- ...f.compressed && {
1415
- metadata: {
1416
- compressed: f.compressed,
1417
- originalSize: f.originalSize,
1418
- compressionAlgorithm: f.compressionAlgorithm
1419
- }
1420
- }
1421
- }));
1422
- const { urls, errors: requestErrors } = await storageApi.requestPresignedUrlBatch(requests);
1423
- const failedSlotIds = /* @__PURE__ */ new Set();
1424
- const failed = requestErrors.map((e) => {
1425
- const idx = e.clientIndex ?? slotted.findIndex((s) => s.file.name === e.filename);
1426
- const slotId = slotted[idx]?.slotId;
1427
- if (slotId) failedSlotIds.add(slotId);
1428
- return { filename: e.filename, error: e.error };
1429
- });
1430
- const progressMap = {};
1431
- const reportProgress = () => {
1432
- if (!onProgress) return;
1433
- const vals = Object.values(progressMap);
1434
- const avg = vals.reduce((s, v) => s + v, 0) / Math.max(vals.length, 1);
1435
- onProgress(Math.round(avg));
1436
- };
1437
- const successful = [];
1438
- const slotToFile = /* @__PURE__ */ new Map();
1439
- await Promise.all(
1440
- urls.map(async (presigned, idx) => {
1441
- const originalIdx = presigned.clientIndex ?? idx;
1442
- const { file, slotId } = slotted[originalIdx];
1443
- progressMap[originalIdx] = 0;
1444
- try {
1445
- let fileResponse;
1446
- if (presigned.multipart && platformUploadPartFn) {
1447
- fileResponse = await runMultipartUpload(presigned, file, platformUploadPartFn, (pct) => {
1448
- progressMap[originalIdx] = pct;
1449
- reportProgress();
1450
- });
1451
- } else {
1452
- await platformUploadFn(presigned, file, (pct) => {
1453
- progressMap[originalIdx] = Math.round(pct * 0.9);
1454
- reportProgress();
1455
- });
1456
- fileResponse = await storageApi.confirmUpload(presigned.fileId);
1457
- }
1458
- progressMap[originalIdx] = 100;
1459
- reportProgress();
1460
- successful.push(fileResponse);
1461
- slotToFile.set(slotId, fileResponse);
1462
- } catch (err) {
1463
- failed.push({ filename: file.name, error: err.message });
1464
- }
1465
- })
1466
- );
1467
- return { result: { successful, failed }, slotToFile };
1468
- }
1469
- async function uploadBatch(files, platformUploadFn, conversationId, onProgress, platformCompressFn, compressionConfig, platformUploadPartFn) {
1470
- const slotIds = files.map(() => generateUUID());
1471
- const { result } = await runUploadBatch(files, platformUploadFn, slotIds, conversationId, onProgress, platformCompressFn, compressionConfig, platformUploadPartFn);
1472
- return result;
1473
- }
1474
-
1475
- // src/api/devices.ts
1476
- var devicesApi = {
1477
- /**
1478
- * Register or update a device push token with the chat server.
1479
- *
1480
- * Upserts by `deviceId` — calling this multiple times with the same deviceId
1481
- * simply refreshes the token value (tokens can rotate silently on some platforms).
1482
- *
1483
- * The SDK never calls this automatically. The parent app or the `tokenProvider`
1484
- * option in `pushNotifications` config is responsible for calling it after
1485
- * obtaining the token from the OS / browser.
1486
- */
1487
- async register(payload) {
1488
- await getApiClient().post("/users/me/devices", payload);
1489
- },
1490
- /**
1491
- * Remove a device token from the chat server.
1492
- * Call this on logout so the user stops receiving push notifications on this device.
1493
- */
1494
- async remove(deviceId) {
1495
- await getApiClient().post(`/users/me/devices/${deviceId}/remove`);
1496
- }
1497
- };
1498
-
1499
- // src/api/users.ts
1500
- var usersApi = {
1501
- async list(params = {}) {
1502
- const { data } = await getApiClient().get("/users", { params });
1503
- return data;
1504
- },
1505
- async getById(userId) {
1506
- const { data } = await getApiClient().get(`/users/${userId}`);
1507
- return data;
1508
- },
1509
- async getLastSeen(userId) {
1510
- const { data } = await getApiClient().get(`/users/${userId}`);
1511
- return { lastSeenAt: data.lastSeenAt ?? null };
1512
- },
1513
- /**
1514
- * Update basic profile fields for the current user.
1515
- * Works in both builtin and non-builtin modes. Use this to push an immediate
1516
- * profile update to the chat server when the host app knows a change just
1517
- * happened — without waiting for the next 2-hour sync cycle.
1518
- */
1519
- async updateProfile(payload) {
1520
- const { data } = await getApiClient().post("/users/me/update", payload);
1521
- return data;
1522
- },
1523
- /**
1524
- * Update notification preferences for the current user.
1525
- * Partial update — only send fields you want to change.
1526
- * A prefs record is automatically created with defaults when a device
1527
- * token is first registered, so this never fails with "not found".
1528
- */
1529
- async updatePreferences(prefs) {
1530
- const { data } = await getApiClient().post("/users/me/preferences", prefs);
1531
- return data;
1532
- },
1533
- /**
1534
- * Fetch current notification preferences for the current user.
1535
- * Returns null if no prefs record exists yet (all defaults apply).
1536
- */
1537
- async getPreferences() {
1538
- try {
1539
- const { data } = await getApiClient().get("/users/me/preferences");
1540
- return data;
1541
- } catch {
1542
- return null;
1543
- }
1016
+ // src/crypto/uuid.ts
1017
+ function generateUUID() {
1018
+ if (typeof globalThis.crypto?.randomUUID === "function") {
1019
+ return globalThis.crypto.randomUUID();
1544
1020
  }
1545
- };
1021
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
1022
+ const r = Math.random() * 16 | 0;
1023
+ return (c === "x" ? r : r & 3 | 8).toString(16);
1024
+ });
1025
+ }
1546
1026
 
1547
1027
  // src/socket/socket.ts
1548
1028
  var import_socket = require("socket.io-client");
@@ -1861,127 +1341,684 @@ async function drainSendQueue(conversationId) {
1861
1341
  entry.reject(new AntzChatNetworkError("Message dropped: queued too long", "MESSAGE_DROPPED"));
1862
1342
  continue;
1863
1343
  }
1864
- entry.run().then(entry.resolve).catch(entry.reject);
1344
+ entry.run().then(entry.resolve).catch(entry.reject);
1345
+ }
1346
+ sendQueues.delete(conversationId);
1347
+ sendQueueRunning.delete(conversationId);
1348
+ }
1349
+ function queueSendMessage(payload) {
1350
+ const conversationId = payload.conversationId;
1351
+ if (!sendQueues.has(conversationId)) sendQueues.set(conversationId, []);
1352
+ const queue = sendQueues.get(conversationId);
1353
+ if (queue.length >= QUEUE_MAX_SIZE) {
1354
+ return Promise.reject(new AntzChatNetworkError("Send queue full: too many messages in flight", "SEND_QUEUE_FULL", { conversationId }));
1355
+ }
1356
+ return new Promise((resolve, reject) => {
1357
+ queue.push({ run: () => withAck("send_message", payload), resolve, reject, enqueuedAt: Date.now() });
1358
+ drainSendQueue(conversationId);
1359
+ });
1360
+ }
1361
+ function waitForReconnect() {
1362
+ return new Promise((resolve, reject) => {
1363
+ const timer = setTimeout(() => {
1364
+ unsubscribe();
1365
+ reject(new AntzChatNetworkError("Socket reconnect timeout", "SOCKET_TIMEOUT"));
1366
+ }, RECONNECT_WAIT_TIMEOUT);
1367
+ const unsubscribe = onSocketStatus((status) => {
1368
+ if (status === "connected") {
1369
+ clearTimeout(timer);
1370
+ unsubscribe();
1371
+ resolve();
1372
+ } else if (status === "error") {
1373
+ clearTimeout(timer);
1374
+ unsubscribe();
1375
+ reject(new AntzChatNetworkError("Socket reconnect failed", "SOCKET_NOT_CONNECTED"));
1376
+ }
1377
+ });
1378
+ });
1379
+ }
1380
+ async function withAck(event, payload) {
1381
+ let socket = tryGetSocket();
1382
+ if (!socket) {
1383
+ await waitForReconnect();
1384
+ socket = tryGetSocket();
1385
+ }
1386
+ if (!socket) return Promise.reject(new AntzChatNetworkError(`Socket not connected (event: ${event})`, "SOCKET_NOT_CONNECTED", { event }));
1387
+ return new Promise((resolve, reject) => {
1388
+ let timer;
1389
+ secureEmit(socket, event, payload, (response) => {
1390
+ clearTimeout(timer);
1391
+ resolve(response);
1392
+ }).then(() => {
1393
+ timer = setTimeout(() => reject(new AntzChatNetworkError(`Socket ack timeout: ${event}`, "SOCKET_TIMEOUT", { event })), ACK_TIMEOUT);
1394
+ }).catch(reject);
1395
+ });
1396
+ }
1397
+ function fireAndForget(event, payload) {
1398
+ const socket = tryGetSocket();
1399
+ if (!socket) return;
1400
+ secureEmit(socket, event, payload);
1401
+ }
1402
+ var socketEmit = {
1403
+ joinRoom(conversationId) {
1404
+ fireAndForget("join_room", { conversationId });
1405
+ },
1406
+ leaveRoom(conversationId) {
1407
+ fireAndForget("leave_room", { conversationId });
1408
+ },
1409
+ sendMessage(payload) {
1410
+ return queueSendMessage({ ...payload, sentAt: Date.now() });
1411
+ },
1412
+ // Not queued like sendMessage — forward targets are independent conversations,
1413
+ // not the single conversation ordering that queueSendMessage protects, and each
1414
+ // target's own new_message/push already fires server-side via MessagesService.forward()'s
1415
+ // internal create() calls, so there's nothing here that needs in-order draining.
1416
+ forwardMessage(payload) {
1417
+ return withAck("forward_message", payload);
1418
+ },
1419
+ updateMessage(messageId, text) {
1420
+ return withAck("update_message", { messageId, text });
1421
+ },
1422
+ deleteMessage(messageId) {
1423
+ return withAck("delete_message", { messageId });
1424
+ },
1425
+ deleteMessageForMe(messageId) {
1426
+ return withAck("delete_message_for_me", { messageId });
1427
+ },
1428
+ clearChat(conversationId) {
1429
+ return withAck("clear_chat_for_me", { conversationId });
1430
+ },
1431
+ addReaction(messageId, emoji) {
1432
+ return withAck("add_reaction", { messageId, emoji });
1433
+ },
1434
+ removeReaction(messageId, emoji) {
1435
+ return withAck("remove_reaction", { messageId, emoji });
1436
+ },
1437
+ pinMessage(messageId) {
1438
+ return withAck("pin_message", { messageId });
1439
+ },
1440
+ unpinMessage(messageId) {
1441
+ return withAck("unpin_message", { messageId });
1442
+ },
1443
+ // markRead and typing are best-effort — silently dropped if socket not ready
1444
+ typing(conversationId, isTyping) {
1445
+ fireAndForget("typing", { conversationId, isTyping });
1446
+ },
1447
+ markRead(conversationId, messageId) {
1448
+ fireAndForget("mark_read", { conversationId, ...messageId ? { messageId } : {} });
1449
+ },
1450
+ getOnlineUsers(userIds) {
1451
+ const socket = tryGetSocket();
1452
+ if (!socket) return Promise.resolve([]);
1453
+ return new Promise((resolve, reject) => {
1454
+ let timer;
1455
+ secureEmit(socket, "get_online_users", { userIds }, (response) => {
1456
+ clearTimeout(timer);
1457
+ if (response && typeof response === "object" && "onlineStatus" in response) {
1458
+ const status = response.onlineStatus;
1459
+ resolve(Object.entries(status).filter(([, v]) => v).map(([k]) => k));
1460
+ } else if (Array.isArray(response)) {
1461
+ resolve(response);
1462
+ } else {
1463
+ resolve([]);
1464
+ }
1465
+ }).then(() => {
1466
+ timer = setTimeout(() => reject(new AntzChatNetworkError("Socket ack timeout: get_online_users", "SOCKET_TIMEOUT", { event: "get_online_users" })), ACK_TIMEOUT);
1467
+ }).catch(reject);
1468
+ });
1469
+ },
1470
+ getTypingUsers(conversationId) {
1471
+ return withAck("get_typing_users", { conversationId });
1472
+ }
1473
+ };
1474
+
1475
+ // src/api/messages.ts
1476
+ var MAX_FORWARD_TARGETS = 5;
1477
+ var HIGHLY_FORWARDED_DEPTH_THRESHOLD = 5;
1478
+ var messagesApi = {
1479
+ async list(conversationId, params = {}) {
1480
+ const { cursor, direction, ...rest } = params;
1481
+ const serverParams = { ...rest };
1482
+ if (cursor) {
1483
+ serverParams[direction === "after" ? "after" : "before"] = cursor;
1484
+ }
1485
+ const { data } = await getApiClient().get(
1486
+ `/conversations/${conversationId}/messages`,
1487
+ { params: serverParams }
1488
+ );
1489
+ const currentUserId = getAuthStore().useAuthStore.getState().user?.id;
1490
+ if (!currentUserId) return data;
1491
+ return {
1492
+ ...data,
1493
+ data: data.data.map(
1494
+ (m) => m.content.type === "system" ? { ...m, content: { ...m.content, text: resolveSystemMessageText(m, currentUserId) } } : m
1495
+ )
1496
+ };
1497
+ },
1498
+ async get(messageId) {
1499
+ const { data } = await getApiClient().get(`/messages/${messageId}`);
1500
+ return data;
1501
+ },
1502
+ /**
1503
+ * Sends a message via REST. For real-time delivery use `socketEmit.sendMessage`
1504
+ * instead — this is a lower-level entry point (used e.g. by the socket path's
1505
+ * REST-mirror flows). Pass `payload.tempId` and reuse the SAME value on retry to
1506
+ * make a retry-after-timeout safe — see `SendData.tempId`.
1507
+ */
1508
+ async send(conversationId, payload) {
1509
+ const { data } = await getApiClient().post(
1510
+ `/conversations/${conversationId}/messages`,
1511
+ payload
1512
+ );
1513
+ return data;
1514
+ },
1515
+ async update(messageId, text) {
1516
+ const { data } = await getApiClient().post(`/messages/${messageId}/update`, { text });
1517
+ return data;
1518
+ },
1519
+ async delete(messageId) {
1520
+ await getApiClient().post(`/messages/${messageId}/delete`);
1521
+ },
1522
+ async deleteForMe(messageId) {
1523
+ await getApiClient().post(`/messages/${messageId}/delete-for-me`);
1524
+ },
1525
+ async addReaction(messageId, emoji) {
1526
+ const { data } = await getApiClient().post(`/messages/${messageId}/reactions`, { emoji });
1527
+ return data;
1528
+ },
1529
+ async removeReaction(messageId, emoji) {
1530
+ const { data } = await getApiClient().post(
1531
+ `/messages/${messageId}/reactions/${encodeURIComponent(emoji)}/remove`
1532
+ );
1533
+ return data;
1534
+ },
1535
+ async getReactions(messageId) {
1536
+ const { data } = await getApiClient().post(`/messages/${messageId}/reactions/list`);
1537
+ return data;
1538
+ },
1539
+ async star(messageId) {
1540
+ await getApiClient().post(`/messages/${messageId}/star`);
1541
+ },
1542
+ async unstar(messageId) {
1543
+ await getApiClient().post(`/messages/${messageId}/unstar`);
1544
+ },
1545
+ async getStarred(params = {}) {
1546
+ const { data } = await getApiClient().get("/messages/starred", { params });
1547
+ return data;
1548
+ },
1549
+ async search(params) {
1550
+ const { data } = await getApiClient().get("/messages/search", { params });
1551
+ return data;
1552
+ },
1553
+ async getLastRead(conversationId) {
1554
+ const { data } = await getApiClient().get(
1555
+ `/conversations/${conversationId}/read-receipt`
1556
+ );
1557
+ return data;
1558
+ },
1559
+ async markAsRead(conversationId, messageId) {
1560
+ await getApiClient().post(`/conversations/${conversationId}/read`, messageId ? { messageId } : {});
1561
+ },
1562
+ async pin(messageId) {
1563
+ const { data } = await getApiClient().post(`/messages/${messageId}/pin`);
1564
+ return data;
1565
+ },
1566
+ async unpin(messageId) {
1567
+ const { data } = await getApiClient().post(`/messages/${messageId}/unpin`);
1568
+ return data;
1569
+ },
1570
+ async getPinned(conversationId) {
1571
+ const { data } = await getApiClient().get(`/conversations/${conversationId}/pinned-messages`);
1572
+ return data;
1573
+ },
1574
+ async getReceipts(messageId) {
1575
+ const { data } = await getApiClient().get(`/messages/${messageId}/receipts`);
1576
+ return data;
1577
+ },
1578
+ /**
1579
+ * Forwards a message into one or more target conversations (max MAX_FORWARD_TARGETS
1580
+ * per call, also enforced server-side). Each target is independent — one failing
1581
+ * (e.g. no longer a participant) does not block the others; check `success`/`error`
1582
+ * per entry in the returned array.
1583
+ *
1584
+ * Pass `attachmentIds` to forward only a subset of the source message's attachments
1585
+ * (e.g. one image out of a multi-image message) — omit it to forward the whole
1586
+ * message, including all its attachments, unchanged. An ID not present on the
1587
+ * source message is ignored server-side.
1588
+ *
1589
+ * Idempotency: pass `tempId` — generate ONE value per forward action (e.g. via
1590
+ * `generateUUID` from '@antzsoft/chat-core/internal') and reuse that SAME value if
1591
+ * you retry this exact forward (e.g. after a client-side timeout). The server then
1592
+ * recognizes the retry per target and returns the already-created message instead
1593
+ * of creating a duplicate. Never mint a new tempId for a retry — only when the user
1594
+ * initiates a genuinely new forward action. If omitted, a fresh one is generated
1595
+ * per call, which means a retry without an explicit tempId gets NO dedup protection.
1596
+ *
1597
+ * Transport: uses the 'forward_message' socket event when a socket is connected
1598
+ * (lower latency, same server-side MessagesService.forward() path, so broadcast/
1599
+ * push notification behavior is identical either way) and transparently falls back
1600
+ * to the REST endpoint when no socket is available.
1601
+ */
1602
+ async forward(messageId, targetConversationIds, attachmentIds, tempId) {
1603
+ const resolvedTempId = tempId ?? generateUUID();
1604
+ if (tryGetSocket()) {
1605
+ const ack = await socketEmit.forwardMessage({
1606
+ messageId,
1607
+ targetConversationIds,
1608
+ ...attachmentIds ? { attachmentIds } : {},
1609
+ tempId: resolvedTempId
1610
+ });
1611
+ if (ack.error) throw new Error(ack.error);
1612
+ return ack.results;
1613
+ }
1614
+ const { data } = await getApiClient().post(
1615
+ `/messages/${messageId}/forward`,
1616
+ { targetConversationIds, ...attachmentIds ? { attachmentIds } : {}, tempId: resolvedTempId }
1617
+ );
1618
+ return data;
1865
1619
  }
1866
- sendQueues.delete(conversationId);
1867
- sendQueueRunning.delete(conversationId);
1620
+ };
1621
+
1622
+ // src/api/conversations.ts
1623
+ function normalizeParticipant(p) {
1624
+ const hasUserDetails = p.displayName || p.username || p.avatarUrl;
1625
+ return {
1626
+ userId: p.userId,
1627
+ externalId: p.externalId ?? p.user?.externalId,
1628
+ role: p.role,
1629
+ joinedAt: p.joinedAt,
1630
+ isActive: p.isActive,
1631
+ user: hasUserDetails ? {
1632
+ id: p.userId,
1633
+ externalId: p.externalId,
1634
+ tenantId: "",
1635
+ email: "",
1636
+ username: p.username ?? "",
1637
+ displayName: p.displayName ?? p.username ?? "",
1638
+ avatarUrl: p.avatarUrl,
1639
+ status: "offline",
1640
+ createdAt: p.joinedAt ?? "",
1641
+ updatedAt: p.joinedAt ?? ""
1642
+ } : p.user
1643
+ };
1868
1644
  }
1869
- function queueSendMessage(payload) {
1870
- const conversationId = payload.conversationId;
1871
- if (!sendQueues.has(conversationId)) sendQueues.set(conversationId, []);
1872
- const queue = sendQueues.get(conversationId);
1873
- if (queue.length >= QUEUE_MAX_SIZE) {
1874
- return Promise.reject(new AntzChatNetworkError("Send queue full: too many messages in flight", "SEND_QUEUE_FULL", { conversationId }));
1875
- }
1876
- return new Promise((resolve, reject) => {
1877
- queue.push({ run: () => withAck("send_message", payload), resolve, reject, enqueuedAt: Date.now() });
1878
- drainSendQueue(conversationId);
1879
- });
1645
+ function normalizeLastMessage(lastMsg) {
1646
+ if (!lastMsg) return void 0;
1647
+ if (lastMsg.content !== void 0) return lastMsg;
1648
+ return {
1649
+ id: lastMsg.messageId ?? "",
1650
+ tenantId: "",
1651
+ conversationId: "",
1652
+ senderId: lastMsg.senderId ?? "",
1653
+ content: {
1654
+ type: lastMsg.hasAttachments ? "attachment" : "text",
1655
+ text: lastMsg.contentPreview
1656
+ },
1657
+ reactions: [],
1658
+ lastReaction: lastMsg.lastReaction ?? null,
1659
+ status: lastMsg.status ?? "active",
1660
+ deliveryStatus: lastMsg.deliveryStatus ?? "sent",
1661
+ isEdited: false,
1662
+ sentAt: lastMsg.sentAt ?? "",
1663
+ createdAt: lastMsg.sentAt ?? "",
1664
+ ...lastMsg.senderName && { senderName: lastMsg.senderName },
1665
+ ...lastMsg.attachmentType && { attachmentType: lastMsg.attachmentType }
1666
+ };
1880
1667
  }
1881
- function waitForReconnect() {
1882
- return new Promise((resolve, reject) => {
1883
- const timer = setTimeout(() => {
1884
- unsubscribe();
1885
- reject(new AntzChatNetworkError("Socket reconnect timeout", "SOCKET_TIMEOUT"));
1886
- }, RECONNECT_WAIT_TIMEOUT);
1887
- const unsubscribe = onSocketStatus((status) => {
1888
- if (status === "connected") {
1889
- clearTimeout(timer);
1890
- unsubscribe();
1891
- resolve();
1892
- } else if (status === "error") {
1893
- clearTimeout(timer);
1894
- unsubscribe();
1895
- reject(new AntzChatNetworkError("Socket reconnect failed", "SOCKET_NOT_CONNECTED"));
1896
- }
1897
- });
1898
- });
1668
+ function normalizeConversation(conv) {
1669
+ return {
1670
+ ...conv,
1671
+ id: conv.id ?? conv.conversationId,
1672
+ participants: (conv.participants ?? []).map(normalizeParticipant),
1673
+ lastMessage: normalizeLastMessage(conv.lastMessage)
1674
+ };
1899
1675
  }
1900
- async function withAck(event, payload) {
1901
- let socket = tryGetSocket();
1902
- if (!socket) {
1903
- await waitForReconnect();
1904
- socket = tryGetSocket();
1676
+ var conversationsApi = {
1677
+ async list(params = {}) {
1678
+ const { data } = await getApiClient().get("/conversations", { params });
1679
+ return { ...data, data: data.data.map(normalizeConversation) };
1680
+ },
1681
+ async get(conversationId) {
1682
+ const { data } = await getApiClient().get(`/conversations/${conversationId}`);
1683
+ return normalizeConversation(data);
1684
+ },
1685
+ async createGroup(payload) {
1686
+ const { data } = await getApiClient().post("/conversations", payload);
1687
+ return normalizeConversation(data);
1688
+ },
1689
+ async createDirect(payload) {
1690
+ const { data } = await getApiClient().post("/conversations/direct", payload);
1691
+ return normalizeConversation(data);
1692
+ },
1693
+ async update(conversationId, payload) {
1694
+ const { data } = await getApiClient().post(`/conversations/${conversationId}/update`, payload);
1695
+ return normalizeConversation(data);
1696
+ },
1697
+ async delete(conversationId) {
1698
+ await getApiClient().post(`/conversations/${conversationId}/delete`);
1699
+ },
1700
+ async addParticipants(conversationId, userIds, role) {
1701
+ const { data } = await getApiClient().post(
1702
+ `/conversations/${conversationId}/participants`,
1703
+ { userIds, ...role && { role } }
1704
+ );
1705
+ return normalizeConversation(data);
1706
+ },
1707
+ async removeParticipant(conversationId, userId) {
1708
+ const { data } = await getApiClient().post(
1709
+ `/conversations/${conversationId}/participants/${userId}/remove`
1710
+ );
1711
+ return normalizeConversation(data);
1712
+ },
1713
+ async updateParticipantRole(conversationId, userId, role) {
1714
+ const { data } = await getApiClient().post(
1715
+ `/conversations/${conversationId}/participants/${userId}/role`,
1716
+ { role }
1717
+ );
1718
+ return normalizeConversation(data);
1719
+ },
1720
+ async mute(conversationId, mutedUntil) {
1721
+ await getApiClient().post(`/conversations/${conversationId}/mute`, mutedUntil ? { mutedUntil } : {});
1722
+ },
1723
+ async unmute(conversationId) {
1724
+ await getApiClient().post(`/conversations/${conversationId}/unmute`);
1725
+ },
1726
+ async pin(conversationId) {
1727
+ await getApiClient().post(`/conversations/${conversationId}/pin`);
1728
+ },
1729
+ async unpin(conversationId) {
1730
+ await getApiClient().post(`/conversations/${conversationId}/unpin`);
1731
+ },
1732
+ async markUnread(conversationId) {
1733
+ await getApiClient().post(`/conversations/${conversationId}/unread`);
1734
+ },
1735
+ async markRead(conversationId) {
1736
+ await getApiClient().post(`/conversations/${conversationId}/unread/clear`);
1737
+ },
1738
+ async leave(conversationId, andDelete) {
1739
+ const url = andDelete ? `/conversations/${conversationId}/leave?delete=true` : `/conversations/${conversationId}/leave`;
1740
+ await getApiClient().post(url);
1741
+ },
1742
+ async getMembers(conversationId, filter) {
1743
+ const { data } = await getApiClient().get(
1744
+ `/conversations/${conversationId}/participants`,
1745
+ filter ? { params: { filter } } : void 0
1746
+ );
1747
+ return (data ?? []).map(normalizeParticipant);
1748
+ },
1749
+ /**
1750
+ * Get unread message count for a single conversation.
1751
+ * Use this after app foreground or socket reconnect to refresh a specific count.
1752
+ */
1753
+ async getUnreadCount(conversationId) {
1754
+ const { data } = await getApiClient().get(
1755
+ `/conversations/${conversationId}/unread`
1756
+ );
1757
+ return data;
1758
+ },
1759
+ /**
1760
+ * Get total unread count across all conversations + per-conversation breakdown.
1761
+ * Use on app cold start, foreground resume, or after socket reconnect.
1762
+ * The socket keeps counts live while connected — this is the source of truth
1763
+ * when the socket was down.
1764
+ */
1765
+ async getUnreadSummary() {
1766
+ const { data } = await getApiClient().get("/conversations/unread");
1767
+ return data;
1768
+ },
1769
+ /**
1770
+ * Set the group icon from an already-uploaded file (admin only).
1771
+ * The fileId comes from uploadBatch() / client.uploadFiles() — same as attachments.
1772
+ * Server copies storageKey into conversation.iconMeta and deletes the chat_files record.
1773
+ */
1774
+ async uploadIcon(conversationId, fileId) {
1775
+ const { data } = await getApiClient().post(
1776
+ `/conversations/${conversationId}/icon`,
1777
+ { fileId }
1778
+ );
1779
+ return normalizeConversation(data);
1780
+ },
1781
+ async removeIcon(conversationId) {
1782
+ const { data } = await getApiClient().post(`/conversations/${conversationId}/icon/remove`);
1783
+ return normalizeConversation(data);
1784
+ },
1785
+ async clearChat(conversationId) {
1786
+ await getApiClient().post(`/conversations/${conversationId}/clear-for-me`);
1905
1787
  }
1906
- if (!socket) return Promise.reject(new AntzChatNetworkError(`Socket not connected (event: ${event})`, "SOCKET_NOT_CONNECTED", { event }));
1907
- return new Promise((resolve, reject) => {
1908
- let timer;
1909
- secureEmit(socket, event, payload, (response) => {
1910
- clearTimeout(timer);
1911
- resolve(response);
1912
- }).then(() => {
1913
- timer = setTimeout(() => reject(new AntzChatNetworkError(`Socket ack timeout: ${event}`, "SOCKET_TIMEOUT", { event })), ACK_TIMEOUT);
1914
- }).catch(reject);
1915
- });
1916
- }
1917
- function fireAndForget(event, payload) {
1918
- const socket = tryGetSocket();
1919
- if (!socket) return;
1920
- secureEmit(socket, event, payload);
1921
- }
1922
- var socketEmit = {
1923
- joinRoom(conversationId) {
1924
- fireAndForget("join_room", { conversationId });
1788
+ };
1789
+
1790
+ // src/api/storage.ts
1791
+ var storageApi = {
1792
+ async requestPresignedUrl(payload) {
1793
+ const { data } = await getApiClient().post("/storage/presigned-url", payload);
1794
+ return data;
1925
1795
  },
1926
- leaveRoom(conversationId) {
1927
- fireAndForget("leave_room", { conversationId });
1796
+ async requestPresignedUrlBatch(files) {
1797
+ const { data } = await getApiClient().post("/storage/presigned-url/batch", { files });
1798
+ return data;
1928
1799
  },
1929
- sendMessage(payload) {
1930
- return queueSendMessage({ ...payload, sentAt: Date.now() });
1800
+ async confirmUpload(fileId) {
1801
+ const { data } = await getApiClient().post(`/storage/confirm/${fileId}`);
1802
+ return data;
1931
1803
  },
1932
- updateMessage(messageId, text) {
1933
- return withAck("update_message", { messageId, text });
1804
+ async getFile(fileId) {
1805
+ const { data } = await getApiClient().get(`/storage/files/${fileId}`);
1806
+ return data;
1934
1807
  },
1935
- deleteMessage(messageId) {
1936
- return withAck("delete_message", { messageId });
1808
+ async getFileUrl(fileId, expiresIn) {
1809
+ const { data } = await getApiClient().get(`/storage/files/${fileId}/url`, {
1810
+ params: expiresIn ? { expiresIn } : {}
1811
+ });
1812
+ return data;
1937
1813
  },
1938
- deleteMessageForMe(messageId) {
1939
- return withAck("delete_message_for_me", { messageId });
1814
+ async deleteFile(fileId) {
1815
+ await getApiClient().post(`/storage/files/${fileId}/delete`);
1940
1816
  },
1941
- clearChat(conversationId) {
1942
- return withAck("clear_chat_for_me", { conversationId });
1817
+ async completeMultipartUpload(fileId, uploadId, parts) {
1818
+ const { data } = await getApiClient().post(
1819
+ `/storage/multipart/complete/${fileId}`,
1820
+ { uploadId, parts }
1821
+ );
1822
+ return data;
1943
1823
  },
1944
- addReaction(messageId, emoji) {
1945
- return withAck("add_reaction", { messageId, emoji });
1824
+ async getConversationFiles(conversationId, params = {}) {
1825
+ const { data } = await getApiClient().get(
1826
+ `/storage/conversations/${conversationId}/files`,
1827
+ { params }
1828
+ );
1829
+ return data;
1946
1830
  },
1947
- removeReaction(messageId, emoji) {
1948
- return withAck("remove_reaction", { messageId, emoji });
1831
+ async getMyFiles(params = {}) {
1832
+ const { data } = await getApiClient().get("/storage/my-files", { params });
1833
+ return data;
1834
+ }
1835
+ };
1836
+ async function runMultipartUpload(presigned, file, platformUploadPartFn, onProgress) {
1837
+ const { multipart } = presigned;
1838
+ if (!multipart) throw new Error("No multipart info on presigned response");
1839
+ const CONCURRENCY = 3;
1840
+ const completedParts = [];
1841
+ const partProgress = {};
1842
+ multipart.partUrls.forEach(({ partNumber }) => {
1843
+ partProgress[partNumber] = 0;
1844
+ });
1845
+ const reportProgress = () => {
1846
+ if (!onProgress) return;
1847
+ const vals = Object.values(partProgress);
1848
+ const avg = vals.reduce((s, v) => s + v, 0) / Math.max(vals.length, 1);
1849
+ onProgress(Math.round(avg * 0.95));
1850
+ };
1851
+ const uploadPart = async (partNumber, uploadUrl, method) => {
1852
+ const offset = (partNumber - 1) * multipart.chunkSize;
1853
+ const end = Math.min(offset + multipart.chunkSize, file.size);
1854
+ const blob = await fetch(file.uri).then((r) => r.blob());
1855
+ const slice = blob.slice(offset, end);
1856
+ const etag = await platformUploadPartFn(uploadUrl, slice, (pct) => {
1857
+ partProgress[partNumber] = pct;
1858
+ reportProgress();
1859
+ }, method);
1860
+ completedParts.push({ partNumber, etag });
1861
+ partProgress[partNumber] = 100;
1862
+ reportProgress();
1863
+ };
1864
+ for (let i = 0; i < multipart.partUrls.length; i += CONCURRENCY) {
1865
+ const batch = multipart.partUrls.slice(i, i + CONCURRENCY);
1866
+ const results = await Promise.allSettled(
1867
+ batch.map(({ partNumber, uploadUrl, method }) => uploadPart(partNumber, uploadUrl, method ?? "PUT"))
1868
+ );
1869
+ const failed = results.find((r) => r.status === "rejected");
1870
+ if (failed) throw failed.reason;
1871
+ }
1872
+ completedParts.sort((a, b) => a.partNumber - b.partNumber);
1873
+ const fileResponse = await storageApi.completeMultipartUpload(
1874
+ presigned.fileId,
1875
+ multipart.uploadId,
1876
+ completedParts
1877
+ );
1878
+ onProgress?.(100);
1879
+ return fileResponse;
1880
+ }
1881
+ async function runUploadBatch(files, platformUploadFn, slotIds, conversationId, onProgress, platformCompressFn, compressionConfig, platformUploadPartFn) {
1882
+ const compressedFiles = await Promise.all(
1883
+ files.map((f) => compressFile(f, platformCompressFn, compressionConfig ?? { enabled: false, imageQuality: 0.85, imageMaxDimension: 1920, compressDocuments: true }))
1884
+ );
1885
+ const slotted = compressedFiles.map((f, i) => ({ file: f, slotId: slotIds[i], clientIndex: i }));
1886
+ const requests = slotted.map(({ file: f, clientIndex }) => ({
1887
+ filename: f.name,
1888
+ mimeType: f.type,
1889
+ size: f.size,
1890
+ conversationId,
1891
+ clientIndex,
1892
+ ...f.compressed && {
1893
+ metadata: {
1894
+ compressed: f.compressed,
1895
+ originalSize: f.originalSize,
1896
+ compressionAlgorithm: f.compressionAlgorithm
1897
+ }
1898
+ }
1899
+ }));
1900
+ const { urls, errors: requestErrors } = await storageApi.requestPresignedUrlBatch(requests);
1901
+ const failedSlotIds = /* @__PURE__ */ new Set();
1902
+ const failed = requestErrors.map((e) => {
1903
+ const idx = e.clientIndex ?? slotted.findIndex((s) => s.file.name === e.filename);
1904
+ const slotId = slotted[idx]?.slotId;
1905
+ if (slotId) failedSlotIds.add(slotId);
1906
+ return { filename: e.filename, error: e.error };
1907
+ });
1908
+ const progressMap = {};
1909
+ const reportProgress = () => {
1910
+ if (!onProgress) return;
1911
+ const vals = Object.values(progressMap);
1912
+ const avg = vals.reduce((s, v) => s + v, 0) / Math.max(vals.length, 1);
1913
+ onProgress(Math.round(avg));
1914
+ };
1915
+ const successful = [];
1916
+ const slotToFile = /* @__PURE__ */ new Map();
1917
+ await Promise.all(
1918
+ urls.map(async (presigned, idx) => {
1919
+ const originalIdx = presigned.clientIndex ?? idx;
1920
+ const { file, slotId } = slotted[originalIdx];
1921
+ progressMap[originalIdx] = 0;
1922
+ try {
1923
+ let fileResponse;
1924
+ if (presigned.multipart && platformUploadPartFn) {
1925
+ fileResponse = await runMultipartUpload(presigned, file, platformUploadPartFn, (pct) => {
1926
+ progressMap[originalIdx] = pct;
1927
+ reportProgress();
1928
+ });
1929
+ } else {
1930
+ await platformUploadFn(presigned, file, (pct) => {
1931
+ progressMap[originalIdx] = Math.round(pct * 0.9);
1932
+ reportProgress();
1933
+ });
1934
+ fileResponse = await storageApi.confirmUpload(presigned.fileId);
1935
+ }
1936
+ progressMap[originalIdx] = 100;
1937
+ reportProgress();
1938
+ successful.push(fileResponse);
1939
+ slotToFile.set(slotId, fileResponse);
1940
+ } catch (err) {
1941
+ failed.push({ filename: file.name, error: err.message });
1942
+ }
1943
+ })
1944
+ );
1945
+ return { result: { successful, failed }, slotToFile };
1946
+ }
1947
+ async function uploadBatch(files, platformUploadFn, conversationId, onProgress, platformCompressFn, compressionConfig, platformUploadPartFn) {
1948
+ const slotIds = files.map(() => generateUUID());
1949
+ const { result } = await runUploadBatch(files, platformUploadFn, slotIds, conversationId, onProgress, platformCompressFn, compressionConfig, platformUploadPartFn);
1950
+ return result;
1951
+ }
1952
+
1953
+ // src/api/devices.ts
1954
+ var devicesApi = {
1955
+ /**
1956
+ * Register or update a device push token with the chat server.
1957
+ *
1958
+ * Upserts by `deviceId` — calling this multiple times with the same deviceId
1959
+ * simply refreshes the token value (tokens can rotate silently on some platforms).
1960
+ *
1961
+ * The SDK never calls this automatically. The parent app or the `tokenProvider`
1962
+ * option in `pushNotifications` config is responsible for calling it after
1963
+ * obtaining the token from the OS / browser.
1964
+ */
1965
+ async register(payload) {
1966
+ await getApiClient().post("/users/me/devices", payload);
1949
1967
  },
1950
- pinMessage(messageId) {
1951
- return withAck("pin_message", { messageId });
1968
+ /**
1969
+ * Remove a device token from the chat server.
1970
+ * Call this on logout so the user stops receiving push notifications on this device.
1971
+ */
1972
+ async remove(deviceId) {
1973
+ await getApiClient().post(`/users/me/devices/${deviceId}/remove`);
1974
+ }
1975
+ };
1976
+
1977
+ // src/api/users.ts
1978
+ var usersApi = {
1979
+ async list(params = {}) {
1980
+ const { data } = await getApiClient().get("/users", { params });
1981
+ return data;
1952
1982
  },
1953
- unpinMessage(messageId) {
1954
- return withAck("unpin_message", { messageId });
1983
+ async getById(userId) {
1984
+ const { data } = await getApiClient().get(`/users/${userId}`);
1985
+ return data;
1955
1986
  },
1956
- // markRead and typing are best-effort — silently dropped if socket not ready
1957
- typing(conversationId, isTyping) {
1958
- fireAndForget("typing", { conversationId, isTyping });
1987
+ async getLastSeen(userId) {
1988
+ const { data } = await getApiClient().get(`/users/${userId}`);
1989
+ return { lastSeenAt: data.lastSeenAt ?? null };
1959
1990
  },
1960
- markRead(conversationId, messageId) {
1961
- fireAndForget("mark_read", { conversationId, ...messageId ? { messageId } : {} });
1991
+ /**
1992
+ * Update basic profile fields for the current user.
1993
+ * Works in both builtin and non-builtin modes. Use this to push an immediate
1994
+ * profile update to the chat server when the host app knows a change just
1995
+ * happened — without waiting for the next 2-hour sync cycle.
1996
+ */
1997
+ async updateProfile(payload) {
1998
+ const { data } = await getApiClient().post("/users/me/update", payload);
1999
+ return data;
1962
2000
  },
1963
- getOnlineUsers(userIds) {
1964
- const socket = tryGetSocket();
1965
- if (!socket) return Promise.resolve([]);
1966
- return new Promise((resolve, reject) => {
1967
- let timer;
1968
- secureEmit(socket, "get_online_users", { userIds }, (response) => {
1969
- clearTimeout(timer);
1970
- if (response && typeof response === "object" && "onlineStatus" in response) {
1971
- const status = response.onlineStatus;
1972
- resolve(Object.entries(status).filter(([, v]) => v).map(([k]) => k));
1973
- } else if (Array.isArray(response)) {
1974
- resolve(response);
1975
- } else {
1976
- resolve([]);
1977
- }
1978
- }).then(() => {
1979
- timer = setTimeout(() => reject(new AntzChatNetworkError("Socket ack timeout: get_online_users", "SOCKET_TIMEOUT", { event: "get_online_users" })), ACK_TIMEOUT);
1980
- }).catch(reject);
1981
- });
2001
+ /**
2002
+ * Update notification preferences for the current user.
2003
+ * Partial update — only send fields you want to change.
2004
+ * A prefs record is automatically created with defaults when a device
2005
+ * token is first registered, so this never fails with "not found".
2006
+ */
2007
+ async updatePreferences(prefs) {
2008
+ const { data } = await getApiClient().post("/users/me/preferences", prefs);
2009
+ return data;
1982
2010
  },
1983
- getTypingUsers(conversationId) {
1984
- return withAck("get_typing_users", { conversationId });
2011
+ /**
2012
+ * Fetch current notification preferences for the current user.
2013
+ * Returns null if no prefs record exists yet (all defaults apply).
2014
+ */
2015
+ async getPreferences() {
2016
+ try {
2017
+ const { data } = await getApiClient().get("/users/me/preferences");
2018
+ return data;
2019
+ } catch {
2020
+ return null;
2021
+ }
1985
2022
  }
1986
2023
  };
1987
2024