@codingfactory/messenger-client 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1440 @@
1
+ import { ref as J, getCurrentInstance as Fe, computed as K, onUnmounted as Ee, toValue as Be, watch as me } from "vue";
2
+ import { defineStore as Ve, storeToRefs as He } from "pinia";
3
+ import Ye, { isAxiosError as je } from "axios";
4
+ import { isAxiosError as jt } from "axios";
5
+ import { useRoute as We } from "vue-router";
6
+ const Te = () => () => {
7
+ }, xe = () => {
8
+ }, qe = () => {
9
+ }, Pe = () => {
10
+ }, Le = () => {
11
+ throw new Error("messenger-client subscribeToConversation is not configured");
12
+ };
13
+ let W = "messenger-client:echo-initialized", P = () => null, Z = Te, oe = xe, ae = qe, ce = Le, ue = Pe;
14
+ function Xe(e) {
15
+ e.initializedEvent && (W = e.initializedEvent), e.getEcho && (P = e.getEcho), e.onConnectionStatusChange && (Z = e.onConnectionStatusChange), e.subscribeToPresenceStatus && (oe = e.subscribeToPresenceStatus), e.unsubscribeFromPresenceStatus && (ae = e.unsubscribeFromPresenceStatus), e.subscribeToConversation && (ce = e.subscribeToConversation), e.unsubscribeFromConversation && (ue = e.unsubscribeFromConversation);
16
+ }
17
+ function Qe() {
18
+ W = "messenger-client:echo-initialized", P = () => null, Z = Te, oe = xe, ae = qe, ce = Le, ue = Pe;
19
+ }
20
+ function X(e) {
21
+ return typeof e == "object" && e !== null;
22
+ }
23
+ function Ze(e) {
24
+ return X(e) && typeof e.conversation_id == "string" && X(e.message) && typeof e.message.id == "string" && typeof e.message.conversation_id == "string" && typeof e.message.author_id == "string";
25
+ }
26
+ function Je(e) {
27
+ return X(e) && typeof e.conversation_id == "string" && typeof e.user_id == "string" && typeof e.message_id == "string";
28
+ }
29
+ function Ke(e) {
30
+ return X(e) && typeof e.conversation_id == "string";
31
+ }
32
+ const Ue = Ye;
33
+ let l = Ue;
34
+ function et(e) {
35
+ l = e;
36
+ }
37
+ function tt() {
38
+ l = Ue;
39
+ }
40
+ const ze = {
41
+ currentUser: null
42
+ };
43
+ let L = () => ze;
44
+ function st(e) {
45
+ L = e;
46
+ }
47
+ function nt() {
48
+ L = () => ze;
49
+ }
50
+ function m(e) {
51
+ if (je(e)) {
52
+ const t = e.response?.data?.message || e.message || "An error occurred";
53
+ return t.includes("SQLSTATE") || t.includes("Connection:") || t.includes("\\Illuminate\\") ? "Something went wrong. Please try again later." : t;
54
+ }
55
+ return e instanceof Error ? e.message : typeof e == "string" ? e : typeof e == "object" && e !== null && "message" in e && typeof e.message == "string" ? e.message : "An unexpected error occurred";
56
+ }
57
+ function It(e) {
58
+ return e instanceof Error;
59
+ }
60
+ function Ot(e) {
61
+ return typeof e == "object" && e !== null && "response" in e && typeof e.response == "object";
62
+ }
63
+ const $e = {
64
+ async uploadImage() {
65
+ throw new Error("messenger-client mediaApi.uploadImage is not configured");
66
+ }
67
+ };
68
+ let de = $e;
69
+ function rt(e) {
70
+ de = e;
71
+ }
72
+ function it() {
73
+ de = $e;
74
+ }
75
+ function ot(e) {
76
+ return e !== null && typeof e == "object" && "id" in e && "type" in e && "participants" in e;
77
+ }
78
+ function Ne(e) {
79
+ return typeof e == "object" && e !== null;
80
+ }
81
+ function N(e) {
82
+ return !Ne(e) || !("data" in e) ? e : e.data;
83
+ }
84
+ function B(e, t) {
85
+ const s = e[t];
86
+ if (typeof s != "string")
87
+ throw new Error(`Invalid messaging folder payload: missing string ${t}`);
88
+ return s;
89
+ }
90
+ function pe(e, t) {
91
+ const s = e[t];
92
+ if (s == null)
93
+ return null;
94
+ if (typeof s != "string")
95
+ throw new Error(`Invalid messaging folder payload: ${t} must be a string or null`);
96
+ return s;
97
+ }
98
+ function ee(e, t) {
99
+ const s = e[t];
100
+ if (typeof s == "number" && Number.isFinite(s))
101
+ return s;
102
+ if (typeof s == "string" && s.length > 0) {
103
+ const n = Number(s);
104
+ if (Number.isFinite(n))
105
+ return n;
106
+ }
107
+ throw new Error(`Invalid messaging folder payload: missing numeric ${t}`);
108
+ }
109
+ function re(e) {
110
+ if (!Ne(e))
111
+ throw new Error("Invalid messaging folder payload: expected object");
112
+ return {
113
+ id: B(e, "id"),
114
+ name: B(e, "name"),
115
+ color: pe(e, "color"),
116
+ icon: pe(e, "icon"),
117
+ sort_order: ee(e, "sort_order"),
118
+ conversation_count: ee(e, "conversation_count"),
119
+ unread_count: ee(e, "unread_count"),
120
+ created_at: B(e, "created_at"),
121
+ updated_at: B(e, "updated_at")
122
+ };
123
+ }
124
+ function at(e) {
125
+ if (!Array.isArray(e))
126
+ throw new Error("Invalid messaging folder payload: expected array");
127
+ return e.map((t) => re(t));
128
+ }
129
+ function ve(e) {
130
+ if (!ot(e))
131
+ throw new Error("Invalid conversation payload from folder assignment endpoint");
132
+ return e;
133
+ }
134
+ const q = {
135
+ async fetchFolders() {
136
+ const e = await l.get("/v1/messaging/folders");
137
+ return at(N(e.data));
138
+ },
139
+ async createFolder(e) {
140
+ const t = await l.post("/v1/messaging/folders", e);
141
+ return re(N(t.data));
142
+ },
143
+ async updateFolder(e, t) {
144
+ const s = await l.patch(`/v1/messaging/folders/${e}`, t);
145
+ return re(N(s.data));
146
+ },
147
+ async deleteFolder(e) {
148
+ await l.delete(`/v1/messaging/folders/${e}`);
149
+ },
150
+ async reorderFolders(e) {
151
+ await l.patch("/v1/messaging/folders/reorder", { order: e });
152
+ },
153
+ async assignFolder(e, t) {
154
+ const s = await l.patch(`/v1/messaging/conversations/${e}/folder`, {
155
+ folder_id: t
156
+ });
157
+ return ve(N(s.data));
158
+ },
159
+ async acceptRequest(e) {
160
+ const t = await l.post(`/v1/messaging/conversations/${e}/accept`);
161
+ return ve(N(t.data));
162
+ },
163
+ async declineRequest(e) {
164
+ await l.post(`/v1/messaging/conversations/${e}/decline`);
165
+ }
166
+ }, _e = 1e3, le = 4e3, ct = 12e4, ut = 300, dt = 1, lt = 1600, fe = (e) => {
167
+ if (typeof e == "number" && Number.isFinite(e))
168
+ return e;
169
+ if (typeof e == "string") {
170
+ const t = Number.parseInt(e, 10);
171
+ if (Number.isFinite(t))
172
+ return t;
173
+ }
174
+ }, De = (e) => typeof e == "number" && e >= 500 && e < 600, ye = (e) => {
175
+ const s = fe(e.response?.status);
176
+ return s === void 0 ? !0 : s === 429 || De(s);
177
+ }, Ie = (e) => {
178
+ if (typeof e == "number" && Number.isFinite(e) && e > 0)
179
+ return Math.max(_e, e * 1e3);
180
+ if (typeof e == "string") {
181
+ const t = Number.parseInt(e, 10);
182
+ if (Number.isFinite(t) && t > 0)
183
+ return Math.max(_e, t * 1e3);
184
+ }
185
+ return le;
186
+ }, ft = (e) => {
187
+ const t = Math.max(0, e), s = 2 ** Math.min(t, 6), n = le * s;
188
+ return Math.min(ct, n);
189
+ }, ht = (e) => {
190
+ const t = e;
191
+ return fe(t.response?.status) === 429 ? Ie(t.response?.headers?.["retry-after"]) : ut;
192
+ }, be = async (e) => {
193
+ await new Promise((t) => {
194
+ setTimeout(t, e);
195
+ });
196
+ }, gt = (e) => {
197
+ if (!S(e))
198
+ return !1;
199
+ const s = (S(e.data) ? e.data : e).throttled;
200
+ if (typeof s == "boolean")
201
+ return s;
202
+ if (typeof s == "number")
203
+ return s === 1;
204
+ if (typeof s == "string") {
205
+ const n = s.trim().toLowerCase();
206
+ return n === "1" || n === "true";
207
+ }
208
+ return !1;
209
+ };
210
+ function mt(e, t, s) {
211
+ const n = typeof e == "string" && e.trim().length > 0 ? e.trim().toLowerCase() : void 0;
212
+ if (n)
213
+ return n;
214
+ const r = typeof t == "string" && t.trim().length > 0 ? t.trim().toLowerCase() : void 0;
215
+ if (r)
216
+ return r;
217
+ const i = typeof s == "string" && s.trim().length > 0 ? s.trim().toLowerCase() : void 0;
218
+ return i ? i === "image" ? "image/*" : i === "video" ? "video/*" : i === "audio" ? "audio/*" : i : "application/octet-stream";
219
+ }
220
+ function pt(e) {
221
+ const t = e.url || "", s = e.thumbnail_url ?? e.thumbnail, n = {
222
+ id: e.media_id ?? e.id ?? "",
223
+ name: e.name ?? vt(t),
224
+ url: t,
225
+ type: mt(e.mime, e.mime_type, e.type),
226
+ size: e.size ?? 0
227
+ };
228
+ return s !== void 0 && (n.thumbnail = s), n;
229
+ }
230
+ function vt(e) {
231
+ if (!e) return "attachment";
232
+ try {
233
+ const s = new URL(e).pathname.split("/");
234
+ return s[s.length - 1] || "attachment";
235
+ } catch {
236
+ return "attachment";
237
+ }
238
+ }
239
+ function _t(e) {
240
+ return !Array.isArray(e) || e.length === 0 ? [] : e.map(pt);
241
+ }
242
+ function Q(e) {
243
+ if (typeof e != "string")
244
+ return;
245
+ const t = e.trim();
246
+ if (t.length !== 0)
247
+ return t;
248
+ }
249
+ function yt(e) {
250
+ if (!e)
251
+ return;
252
+ const t = Q(e.avatar) ?? Q(e.avatar_url), s = typeof e.handle == "string" && e.handle.length > 0 ? e.handle : void 0;
253
+ return {
254
+ id: e.id ?? "",
255
+ name: e.name ?? "",
256
+ ...t ? { avatar: t } : {},
257
+ ...s ? { handle: s } : {}
258
+ };
259
+ }
260
+ function Y(e) {
261
+ const t = e.shared_post, s = e.author, n = t && typeof t == "object" ? {
262
+ id: t.id ?? "",
263
+ title: t.title ?? "",
264
+ url: t.url ?? "",
265
+ excerpt: t.excerpt ?? null,
266
+ media_thumbnail: t.media_thumbnail ?? t.thumbnail_url ?? null,
267
+ author: t.author ? {
268
+ id: t.author.id ?? "",
269
+ name: t.author.name ?? "",
270
+ avatar: t.author.avatar ?? t.author.avatar_url ?? null,
271
+ handle: t.author.handle ?? null
272
+ } : null
273
+ } : null;
274
+ return {
275
+ ...e,
276
+ ...s ? { author: yt(s) } : {},
277
+ shared_post: n,
278
+ attachments: _t(e.attachments)
279
+ };
280
+ }
281
+ function bt(e) {
282
+ return typeof e != "string" || e.length === 0 ? null : e;
283
+ }
284
+ function Ce(e) {
285
+ if (!(typeof e != "string" || e.length === 0))
286
+ return e;
287
+ }
288
+ function ie(e) {
289
+ return typeof e == "string" && e.length > 0 && !e.startsWith("temp-");
290
+ }
291
+ function Ct(e, t = []) {
292
+ const s = /* @__PURE__ */ new Map();
293
+ for (const n of t) {
294
+ const r = Ce(n.last_read_message_id);
295
+ r && s.set(n.user_id, r);
296
+ }
297
+ return e.map((n) => {
298
+ const r = Q(n.user?.avatar) ?? Q(n.user?.avatar_url), i = n.user ? {
299
+ id: n.user.id,
300
+ name: n.user.name,
301
+ ...r ? { avatar: r } : {},
302
+ ...n.user.handle ? { handle: n.user.handle } : {}
303
+ } : void 0, o = Ce(n.last_read_message_id);
304
+ if (o)
305
+ return {
306
+ ...n,
307
+ ...i ? { user: i } : {},
308
+ last_read_message_id: o
309
+ };
310
+ const a = s.get(n.user_id);
311
+ return a ? {
312
+ ...n,
313
+ ...i ? { user: i } : {},
314
+ last_read_message_id: a
315
+ } : {
316
+ ...n,
317
+ ...i ? { user: i } : {},
318
+ last_read_message_id: ""
319
+ };
320
+ });
321
+ }
322
+ function D(e, t) {
323
+ const s = bt(e.muted_until), n = e.is_muted ?? s !== null, r = e.last_message ? Y(e.last_message) : t?.last_message, i = e.last_message_at ?? t?.last_message_at, o = (() => {
324
+ if (!t || t.unread_count !== 0 || e.unread_count <= 0)
325
+ return !1;
326
+ const a = t.last_message?.id, u = e.last_message?.id;
327
+ return !a || !u ? !1 : a === u;
328
+ })();
329
+ return {
330
+ ...e,
331
+ unread_count: n || o ? 0 : e.unread_count,
332
+ participants: Ct(e.participants, t?.participants),
333
+ is_muted: n,
334
+ muted_until: s,
335
+ ...r ? { last_message: r } : {},
336
+ ...i ? { last_message_at: i } : {}
337
+ };
338
+ }
339
+ function St(e) {
340
+ return e.is_muted ? !0 : typeof e.muted_until == "string" && e.muted_until.length > 0;
341
+ }
342
+ function te(e) {
343
+ return St(e) ? 0 : e.unread_count || 0;
344
+ }
345
+ function Se(e, t) {
346
+ const s = t[e.id];
347
+ if (Array.isArray(s))
348
+ for (let n = s.length - 1; n >= 0; n -= 1) {
349
+ const r = s[n]?.id;
350
+ if (ie(r))
351
+ return r;
352
+ }
353
+ return ie(e.last_message?.id) ? e.last_message.id : null;
354
+ }
355
+ function S(e) {
356
+ return typeof e == "object" && e !== null;
357
+ }
358
+ function Mt(e) {
359
+ return S(e) ? (S(e.response) ? e.response : null)?.status === 401 : !1;
360
+ }
361
+ function Me(e) {
362
+ if (!Array.isArray(e))
363
+ return [];
364
+ const t = [];
365
+ for (const s of e) {
366
+ if (!S(s) || typeof s.reaction != "string" || typeof s.count != "number" || !Array.isArray(s.users))
367
+ continue;
368
+ const n = s.users.filter((r) => S(r)).filter(
369
+ (r) => typeof r.id == "string" && typeof r.name == "string"
370
+ ).map((r) => ({
371
+ id: r.id,
372
+ name: r.name
373
+ }));
374
+ t.push({
375
+ reaction: s.reaction,
376
+ count: s.count,
377
+ users: n
378
+ });
379
+ }
380
+ return t;
381
+ }
382
+ function wt(e, t) {
383
+ const s = S(t) ? t : null, n = s?.next ?? s?.next_cursor ?? e.next_cursor;
384
+ if (!(typeof n != "string" || n.length === 0))
385
+ return n;
386
+ }
387
+ function V(e, t) {
388
+ const s = S(e) ? e : {}, n = s.data ?? e;
389
+ let r = [];
390
+ return Array.isArray(n) ? r = n : S(n) && (Array.isArray(n.items) ? r = n.items : Array.isArray(n[t]) ? r = n[t] : Array.isArray(n.data) && (r = n.data)), {
391
+ items: r,
392
+ nextCursor: wt(s, n)
393
+ };
394
+ }
395
+ function we(e) {
396
+ return S(e) && typeof e.id == "string" && e.id.length > 0;
397
+ }
398
+ function Re(e) {
399
+ return S(e) ? typeof e.id == "string" && (e.type === "dm" || e.type === "group") && Array.isArray(e.participants) : !1;
400
+ }
401
+ function j(e, t) {
402
+ if (e.is_pinned !== t.is_pinned)
403
+ return e.is_pinned ? -1 : 1;
404
+ const s = e.last_message_at ?? e.created_at, r = (t.last_message_at ?? t.created_at).localeCompare(s);
405
+ return r !== 0 ? r : e.id.localeCompare(t.id);
406
+ }
407
+ function H(e, t) {
408
+ return [t, ...e.filter((s) => s.id !== t.id)];
409
+ }
410
+ function I(e) {
411
+ return [...e].sort((t, s) => t.sort_order !== s.sort_order ? t.sort_order - s.sort_order : t.name.localeCompare(s.name));
412
+ }
413
+ function Rt(e, t) {
414
+ return typeof e != "string" || e.length === 0 ? null : t.has(e) ? e : null;
415
+ }
416
+ function Ae(e, t) {
417
+ return e.map((s) => {
418
+ const n = Rt(s.folder_id, t);
419
+ return (s.folder_id ?? null) === n ? s : {
420
+ ...s,
421
+ folder_id: n
422
+ };
423
+ });
424
+ }
425
+ function se(e) {
426
+ const t = /* @__PURE__ */ new Map();
427
+ for (const s of e.requests)
428
+ s.is_request === !0 && t.set(s.id, s);
429
+ for (const s of e.conversations)
430
+ s.is_request === !0 && t.set(s.id, s);
431
+ return Array.from(t.values()).sort(j);
432
+ }
433
+ const Oe = Ve("messaging", {
434
+ state: () => ({
435
+ conversations: [],
436
+ requests: [],
437
+ folders: [],
438
+ foldersLoaded: !1,
439
+ activeFolderId: null,
440
+ messages: {},
441
+ typingUsers: {},
442
+ loading: !1,
443
+ error: null,
444
+ conversationCursors: {},
445
+ conversationHasMore: {},
446
+ loadingMessages: {},
447
+ lastFetch: 0,
448
+ searchResults: [],
449
+ searchLoading: !1,
450
+ backgroundPollRetryAfterUntil: 0,
451
+ backgroundPollTransientFailureCount: 0,
452
+ _pendingSendIds: /* @__PURE__ */ new Set(),
453
+ _activeDetailSubscriptions: /* @__PURE__ */ new Set(),
454
+ _activeGlobalConversationSubscriptions: /* @__PURE__ */ new Set()
455
+ }),
456
+ getters: {
457
+ getConversationById: (e) => (t) => e.conversations.find((s) => s.id === t),
458
+ getMessagesByConversationId: (e) => (t) => e.messages[t] || [],
459
+ getTypingUsers: (e) => (t) => e.typingUsers[t] || [],
460
+ unreadConversationsCount: (e) => e.conversations.filter((t) => te(t) > 0).length,
461
+ unreadCount: (e) => e.conversations.reduce((t, s) => t + te(s), 0),
462
+ totalUnreadCount: (e) => e.conversations.reduce((t, s) => t + te(s), 0),
463
+ sortedFolders: (e) => I(e.folders),
464
+ folderById: (e) => (t) => e.folders.find((s) => s.id === t),
465
+ conversationsInFolder: (e) => (t) => e.conversations.filter((s) => s.folder_id === t),
466
+ hasMoreMessages: (e) => (t) => e.conversationHasMore[t] ?? !1,
467
+ isLoadingMessages: (e) => (t) => e.loadingMessages[t] ?? !1,
468
+ // Message request getters
469
+ requestConversations: (e) => se(e),
470
+ requestCount: (e) => se(e).length,
471
+ unreadRequestCount: (e) => se(e).filter((t) => t.unread_count > 0).length
472
+ },
473
+ actions: {
474
+ normalizeFolderAssignmentsState() {
475
+ if (!this.foldersLoaded)
476
+ return;
477
+ const e = new Set(this.folders.map((t) => t.id));
478
+ this.conversations = Ae(this.conversations, e), this.requests = Ae(this.requests, e), this.activeFolderId !== null && !e.has(this.activeFolderId) && (this.activeFolderId = null);
479
+ },
480
+ async fetchFolders() {
481
+ try {
482
+ const e = await q.fetchFolders();
483
+ return this.folders = I(e), this.foldersLoaded = !0, this.normalizeFolderAssignmentsState(), this.folders;
484
+ } catch (e) {
485
+ throw this.error = m(e), e;
486
+ }
487
+ },
488
+ async createFolder(e) {
489
+ try {
490
+ const t = await q.createFolder(e);
491
+ return this.folders = I([...this.folders, t]), t;
492
+ } catch (t) {
493
+ throw this.error = m(t), t;
494
+ }
495
+ },
496
+ async updateFolder(e, t) {
497
+ try {
498
+ const s = await q.updateFolder(e, t);
499
+ return this.folders = I(
500
+ this.folders.map((n) => n.id === e ? s : n)
501
+ ), s;
502
+ } catch (s) {
503
+ throw this.error = m(s), s;
504
+ }
505
+ },
506
+ async deleteFolder(e) {
507
+ try {
508
+ await q.deleteFolder(e), this.folders = this.folders.filter((t) => t.id !== e), this.foldersLoaded = !0, this.activeFolderId === e && (this.activeFolderId = null), this.normalizeFolderAssignmentsState();
509
+ } catch (t) {
510
+ throw this.error = m(t), t;
511
+ }
512
+ },
513
+ async reorderFolders(e) {
514
+ try {
515
+ await q.reorderFolders(e);
516
+ const t = new Map(this.folders.map((r) => [r.id, r])), s = [];
517
+ for (const r of e) {
518
+ const i = t.get(r);
519
+ i && (s.push({
520
+ ...i,
521
+ sort_order: s.length + 1
522
+ }), t.delete(r));
523
+ }
524
+ const n = I(Array.from(t.values()));
525
+ for (const r of n)
526
+ s.push({
527
+ ...r,
528
+ sort_order: s.length + 1
529
+ });
530
+ this.folders = s;
531
+ } catch (t) {
532
+ throw this.error = m(t), t;
533
+ }
534
+ },
535
+ async assignToFolder(e, t) {
536
+ try {
537
+ const s = await q.assignFolder(e, t), n = this.conversations.findIndex((o) => o.id === e);
538
+ if (n < 0)
539
+ return;
540
+ const r = this.conversations[n];
541
+ if (!r)
542
+ return;
543
+ const i = typeof s.folder_id == "string" || s.folder_id === null ? s.folder_id : t;
544
+ this.conversations[n] = {
545
+ ...r,
546
+ folder_id: i
547
+ };
548
+ } catch (s) {
549
+ throw this.error = m(s), s;
550
+ }
551
+ },
552
+ async fetchConversations(e, t, s, n) {
553
+ this.loading = !0, this.error = null;
554
+ try {
555
+ const r = n?.includePresence ?? !0, i = {};
556
+ r && (i.include_presence = 1), e && (i.cursor = e), t && (i.filter = t), typeof s == "string" && s.length > 0 && (i.folder_id = s);
557
+ const o = await l.get("/v1/messaging/conversations", { params: i }), { items: a, nextCursor: u } = V(
558
+ o.data,
559
+ "conversations"
560
+ ), f = a.map((d) => {
561
+ const p = this.conversations.find(
562
+ (F) => F.id === d.id
563
+ );
564
+ return D(d, p);
565
+ });
566
+ e ? this.conversations.push(...f) : this.conversations = f, this.normalizeFolderAssignmentsState(), this.lastFetch = Date.now();
567
+ const _ = {
568
+ data: f,
569
+ has_more: !!u
570
+ };
571
+ return u !== void 0 && (_.next_cursor = u), _;
572
+ } catch (r) {
573
+ throw n?.background && ye(r) || (this.error = m(r)), r;
574
+ } finally {
575
+ this.loading = !1;
576
+ }
577
+ },
578
+ async pollConversationsForUnread() {
579
+ if (Date.now() < this.backgroundPollRetryAfterUntil)
580
+ return !1;
581
+ try {
582
+ return await this.fetchConversations(void 0, void 0, void 0, {
583
+ background: !0,
584
+ includePresence: !1
585
+ }), this.backgroundPollRetryAfterUntil = 0, this.backgroundPollTransientFailureCount = 0, !0;
586
+ } catch (e) {
587
+ const t = e, s = fe(t.response?.status);
588
+ return s === 429 ? (this.backgroundPollRetryAfterUntil = Date.now() + Ie(t.response?.headers?.["retry-after"]), !1) : (this.backgroundPollTransientFailureCount += 1, s === void 0 || De(s) ? (this.backgroundPollRetryAfterUntil = Date.now() + ft(this.backgroundPollTransientFailureCount), !1) : (this.backgroundPollRetryAfterUntil = Date.now() + le, !1));
589
+ }
590
+ },
591
+ async fetchConversation(e) {
592
+ this.loading = !0, this.error = null;
593
+ try {
594
+ const t = await l.get(`/v1/messaging/conversations/${e}`, {
595
+ params: { include_presence: 1 }
596
+ }), s = this.conversations.find((o) => o.id === e), n = D(t.data.data || t.data, s), r = this.conversations.findIndex((o) => o.id === e);
597
+ r >= 0 ? this.conversations[r] = n : this.conversations.push(n);
598
+ const i = this.requests.findIndex((o) => o.id === e);
599
+ return i >= 0 && (this.requests[i] = n), this.normalizeFolderAssignmentsState(), n;
600
+ } catch (t) {
601
+ throw this.error = m(t), t;
602
+ } finally {
603
+ this.loading = !1;
604
+ }
605
+ },
606
+ async fetchRequests(e) {
607
+ this.loading = !0, this.error = null;
608
+ try {
609
+ const t = {
610
+ include_presence: 1,
611
+ filter: "requests"
612
+ };
613
+ e && (t.cursor = e);
614
+ const s = await l.get("/v1/messaging/conversations", { params: t }), { items: n, nextCursor: r } = V(
615
+ s.data,
616
+ "conversations"
617
+ ), i = n.map((a) => {
618
+ const u = this.requests.find((f) => f.id === a.id);
619
+ return D(a, u);
620
+ });
621
+ e ? this.requests.push(...i) : this.requests = i, this.normalizeFolderAssignmentsState();
622
+ const o = {
623
+ data: i,
624
+ has_more: !!r
625
+ };
626
+ return r !== void 0 && (o.next_cursor = r), o;
627
+ } catch (t) {
628
+ throw this.error = m(t), t;
629
+ } finally {
630
+ this.loading = !1;
631
+ }
632
+ },
633
+ async fetchMessages(e, t) {
634
+ this.loadingMessages[e] = !0, t || (this.loading = !0), this.error = null;
635
+ try {
636
+ const s = t ? { cursor: t } : {};
637
+ let n = 0, r;
638
+ for (; ; )
639
+ try {
640
+ r = await l.get(`/v1/messaging/conversations/${e}/messages`, { params: s });
641
+ break;
642
+ } catch (d) {
643
+ if (!(n < dt && ye(d)))
644
+ throw d;
645
+ n += 1, await be(ht(d));
646
+ }
647
+ const { items: i, nextCursor: o } = V(
648
+ r.data,
649
+ "messages"
650
+ ), a = i.map(Y), u = [...a].reverse();
651
+ if (t ? this.messages[e] = [...u, ...this.messages[e] || []] : this.messages[e] = u, (() => {
652
+ const d = this.conversations.find((p) => p.id === e) ?? this.requests.find((p) => p.id === e);
653
+ return d ? !d.last_message || !d.last_message_at : !1;
654
+ })()) {
655
+ const d = this.messages[e]?.at(-1);
656
+ d && this.updateConversationLastMessage(e, d);
657
+ }
658
+ o ? (this.conversationCursors[e] = o, this.conversationHasMore[e] = !0) : (delete this.conversationCursors[e], this.conversationHasMore[e] = !1);
659
+ const _ = {
660
+ data: a,
661
+ has_more: !!o
662
+ };
663
+ return o !== void 0 && (_.next_cursor = o), _;
664
+ } catch (s) {
665
+ throw this.error = m(s), s;
666
+ } finally {
667
+ this.loadingMessages[e] = !1, this.loading = !1;
668
+ }
669
+ },
670
+ async sendMessage(e, t, s, n, r, i) {
671
+ const o = L(), a = `temp-${Date.now()}-${Math.random()}`, u = typeof i == "string" && i.trim().length > 0 ? i.trim() : null, f = o.currentUser, _ = {
672
+ id: a,
673
+ conversation_id: e,
674
+ author_id: f?.id || "",
675
+ body: t || "",
676
+ attachments: [],
677
+ meta: u ? { shared_post_id: u } : {},
678
+ is_deleted: !1,
679
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
680
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
681
+ };
682
+ f && (_.author = {
683
+ id: f.id,
684
+ name: f.name,
685
+ ...f.avatar ? { avatar: f.avatar } : {},
686
+ ...f.handle ? { handle: f.handle } : {}
687
+ }), n != null && (_.reply_to_id = n), r != null && (_.reply_to = r), this.messages[e] || (this.messages[e] = []), this.messages[e].push(_), this._pendingSendIds.add(a);
688
+ try {
689
+ let d;
690
+ const p = {
691
+ body: t || "",
692
+ ...n ? { reply_to_id: n } : {},
693
+ ...u ? { shared_post_id: u } : {}
694
+ };
695
+ if (s && s.length > 0) {
696
+ const v = await Promise.all(
697
+ s.map(async (A) => {
698
+ const y = await de.uploadImage(A);
699
+ return {
700
+ media_id: y.id,
701
+ mime: y.mime_type,
702
+ size: y.size
703
+ };
704
+ })
705
+ );
706
+ d = await l.post(`/v1/messaging/conversations/${e}/messages`, {
707
+ ...p,
708
+ attachments: v
709
+ });
710
+ } else
711
+ d = await l.post(`/v1/messaging/conversations/${e}/messages`, {
712
+ ...p,
713
+ type: "text"
714
+ });
715
+ const F = d.data.data || d.data, U = { ..._, ...F, attachments: F.attachments ?? _.attachments }, R = Y(U), E = this.messages[e], T = E.findIndex((v) => v.id === a);
716
+ T >= 0 && (E[T] = R), this._pendingSendIds.delete(a);
717
+ const z = R.id;
718
+ let h = 0;
719
+ for (let v = E.length - 1; v >= 0; v--) {
720
+ const A = E[v];
721
+ A && A.id === z && (h++, h > 1 && E.splice(v, 1));
722
+ }
723
+ return this.updateConversationLastMessage(e, R), R;
724
+ } catch (d) {
725
+ throw this._pendingSendIds.delete(a), this.messages[e] = this.messages[e].filter((p) => p.id !== a), this.error = m(d), d;
726
+ }
727
+ },
728
+ async editMessage(e, t, s) {
729
+ try {
730
+ const n = await l.patch(`/v1/messaging/conversations/${e}/messages/${t}`, {
731
+ body: s
732
+ }), r = n.data.data || n.data, i = this.messages[e] || [], o = i.findIndex((a) => a.id === t);
733
+ if (o >= 0) {
734
+ const a = i[o], u = r.id ? { ...a, ...r } : { ...a, body: s, edited_at: (/* @__PURE__ */ new Date()).toISOString() };
735
+ return i[o] = u, u;
736
+ }
737
+ return r;
738
+ } catch (n) {
739
+ throw this.error = m(n), n;
740
+ }
741
+ },
742
+ async deleteMessage(e, t) {
743
+ try {
744
+ await l.delete(`/v1/messaging/conversations/${e}/messages/${t}`);
745
+ const s = this.messages[e] || [], n = s.findIndex((r) => r.id === t);
746
+ if (n >= 0) {
747
+ const r = s[n];
748
+ if (!r)
749
+ return;
750
+ const i = { ...r, is_deleted: !0 };
751
+ delete i.body, s[n] = i;
752
+ }
753
+ } catch (s) {
754
+ throw this.error = m(s), s;
755
+ }
756
+ },
757
+ async markAsRead(e) {
758
+ try {
759
+ const t = this.conversations.find((r) => r.id === e) ?? this.requests.find((r) => r.id === e), s = (() => {
760
+ const r = this.messages[e];
761
+ if (!Array.isArray(r))
762
+ return null;
763
+ for (let i = r.length - 1; i >= 0; i -= 1) {
764
+ const o = r[i]?.id;
765
+ if (ie(o))
766
+ return o;
767
+ }
768
+ return null;
769
+ })(), n = t ? Se(t, this.messages) : s;
770
+ if (!n)
771
+ return;
772
+ await l.post(`/v1/messaging/conversations/${e}/read`, {
773
+ message_id: n
774
+ }), this.conversations.forEach((r) => {
775
+ r.id === e && (r.unread_count = 0);
776
+ }), this.requests.forEach((r) => {
777
+ r.id === e && (r.unread_count = 0);
778
+ });
779
+ } catch (t) {
780
+ throw this.error = m(t), t;
781
+ }
782
+ },
783
+ async markAllAsRead() {
784
+ const e = this.conversations.filter((r) => r.unread_count > 0);
785
+ if (e.length === 0)
786
+ return;
787
+ const t = e.map((r) => {
788
+ const i = Se(r, this.messages);
789
+ return i ? {
790
+ conversationId: r.id,
791
+ messageId: i
792
+ } : null;
793
+ }).filter((r) => r !== null);
794
+ if (t.length === 0)
795
+ return;
796
+ const s = await Promise.allSettled(
797
+ t.map(
798
+ (r) => l.post(`/v1/messaging/conversations/${r.conversationId}/read`, {
799
+ message_id: r.messageId
800
+ })
801
+ )
802
+ );
803
+ let n = null;
804
+ if (s.forEach((r, i) => {
805
+ const o = t[i];
806
+ if (o) {
807
+ if (r.status === "fulfilled") {
808
+ const a = this.conversations.find((u) => u.id === o.conversationId);
809
+ a && (a.unread_count = 0);
810
+ return;
811
+ }
812
+ n === null && (n = r.reason);
813
+ }
814
+ }), n !== null)
815
+ throw this.error = m(n), n;
816
+ },
817
+ async sendTyping(e, t = "start") {
818
+ try {
819
+ const s = await l.post(`/v1/messaging/conversations/${e}/typing`, { state: t });
820
+ if (t !== "start" || !gt(s.data))
821
+ return;
822
+ await be(lt), await l.post(`/v1/messaging/conversations/${e}/typing`, { state: t });
823
+ } catch (s) {
824
+ console.warn("Failed to send typing indicator:", s);
825
+ }
826
+ },
827
+ async muteConversation(e, t) {
828
+ try {
829
+ const s = { minutes: t }, n = await l.patch(`/v1/messaging/conversations/${e}/mute`, s), i = (n.data.data || n.data).muted_until || null, o = this.conversations.find((a) => a.id === e);
830
+ o && (o.is_muted = i !== null, o.muted_until = i);
831
+ } catch (s) {
832
+ throw this.error = m(s), s;
833
+ }
834
+ },
835
+ async unmuteConversation(e) {
836
+ try {
837
+ const t = await l.patch(`/v1/messaging/conversations/${e}/mute`, {
838
+ minutes: 0
839
+ }), n = (t.data.data || t.data).muted_until || null, r = this.conversations.find((i) => i.id === e);
840
+ r && (r.is_muted = n !== null, r.muted_until = n);
841
+ } catch (t) {
842
+ throw this.error = m(t), t;
843
+ }
844
+ },
845
+ async updateConversationTitle(e, t) {
846
+ try {
847
+ const s = await l.patch(`/v1/messaging/conversations/${e}`, {
848
+ title: t
849
+ }), n = s.data.data || s.data, r = typeof n?.title == "string" ? n.title : t, i = (o) => o.map((a) => a.id !== e ? a : {
850
+ ...a,
851
+ title: r
852
+ });
853
+ this.conversations = i(this.conversations), this.requests = i(this.requests);
854
+ } catch (s) {
855
+ throw this.error = m(s), s;
856
+ }
857
+ },
858
+ async pinConversation(e, t) {
859
+ try {
860
+ await l.patch(`/v1/messaging/conversations/${e}/pin`, { pinned: t });
861
+ const s = this.conversations.find((n) => n.id === e);
862
+ s && (s.is_pinned = t), this.conversations.sort(j);
863
+ } catch (s) {
864
+ throw this.error = m(s), s;
865
+ }
866
+ },
867
+ async archiveConversation(e, t) {
868
+ try {
869
+ await l.patch(`/v1/messaging/conversations/${e}/archive`, { archived: t }), this.conversations = this.conversations.filter((s) => s.id !== e);
870
+ } catch (s) {
871
+ throw this.error = m(s), s;
872
+ }
873
+ },
874
+ async deleteConversation(e) {
875
+ try {
876
+ await l.delete(`/v1/messaging/conversations/${e}`), this.conversations = this.conversations.filter((t) => t.id !== e), delete this.messages[e], delete this.typingUsers[e], delete this.conversationCursors[e], delete this.conversationHasMore[e], delete this.loadingMessages[e];
877
+ } catch (t) {
878
+ throw this.error = m(t), t;
879
+ }
880
+ },
881
+ async createDMConversation(e, t) {
882
+ try {
883
+ const s = {
884
+ user_id: e
885
+ };
886
+ t && (s.message = t);
887
+ const n = await l.post("/v1/messaging/conversations/dm", s), r = n.data.data || n.data;
888
+ if (!we(r))
889
+ throw new Error("Invalid conversation payload from DM create endpoint.");
890
+ const i = Re(r) ? D(r) : await this.fetchConversation(r.id);
891
+ return i.is_request === !0 ? (this.requests = H(this.requests, i), this.conversations = this.conversations.filter((o) => o.id !== i.id), i) : (this.conversations = H(this.conversations, i), this.requests = this.requests.filter((o) => o.id !== i.id), i);
892
+ } catch (s) {
893
+ throw this.error = m(s), s;
894
+ }
895
+ },
896
+ async createGroupConversation(e, t) {
897
+ try {
898
+ const s = await l.post("/v1/messaging/conversations/group", {
899
+ title: e,
900
+ participant_ids: t
901
+ }), n = s.data.data || s.data;
902
+ if (!we(n))
903
+ throw new Error("Invalid conversation payload from group create endpoint.");
904
+ const r = Re(n) ? n : await this.fetchConversation(n.id);
905
+ return this.conversations = H(this.conversations, r), r;
906
+ } catch (s) {
907
+ throw this.error = m(s), s;
908
+ }
909
+ },
910
+ async addParticipants(e, t) {
911
+ try {
912
+ await l.post(`/v1/messaging/conversations/${e}/participants`, {
913
+ user_ids: t
914
+ // Changed from participant_ids to user_ids to match backend
915
+ }), await this.fetchConversation(e);
916
+ } catch (s) {
917
+ throw this.error = m(s), s;
918
+ }
919
+ },
920
+ async removeParticipant(e, t) {
921
+ try {
922
+ await l.delete(`/v1/messaging/conversations/${e}/participants/${t}`);
923
+ const s = L();
924
+ if (t === s.currentUser?.id) {
925
+ this.conversations = this.conversations.filter((n) => n.id !== e), this.requests = this.requests.filter((n) => n.id !== e), delete this.messages[e], delete this.typingUsers[e], delete this.conversationCursors[e], delete this.conversationHasMore[e], delete this.loadingMessages[e];
926
+ return;
927
+ }
928
+ await this.fetchConversation(e);
929
+ } catch (s) {
930
+ throw this.error = m(s), s;
931
+ }
932
+ },
933
+ // Real-time event handlers
934
+ // Accepts messages with any attachment shape — broadcast events use MessageAttachment[]
935
+ // while the store uses Attachment[]. normalizeMessage converts either format.
936
+ addMessage(e) {
937
+ const t = typeof e.conversation_id == "string" ? e.conversation_id.trim() : "";
938
+ if (!t)
939
+ return;
940
+ this.messages[t] || (this.messages[t] = []);
941
+ const s = Y({ ...e, attachments: e.attachments ?? [] }), n = this.messages[t];
942
+ if (n.find((u) => u.id === s.id))
943
+ return;
944
+ const i = L();
945
+ if (s.author_id === i.currentUser?.id) {
946
+ const u = n.findIndex((f) => f.id.startsWith("temp-"));
947
+ if (u >= 0) {
948
+ const f = n[u]?.id ?? "";
949
+ n[u] = s, this._pendingSendIds.delete(f), this.updateConversationLastMessage(t, s);
950
+ return;
951
+ }
952
+ }
953
+ const o = s.created_at;
954
+ let a = n.length;
955
+ for (let u = n.length - 1; u >= 0; u--) {
956
+ const f = n[u];
957
+ if (f && f.created_at <= o)
958
+ break;
959
+ a = u;
960
+ }
961
+ n.splice(a, 0, s), a === n.length - 1 && this.updateConversationLastMessage(t, s);
962
+ },
963
+ updateMessage(e) {
964
+ const t = this.messages[e.conversation_id] || [], s = t.findIndex((n) => n.id === e.id);
965
+ s >= 0 && (t[s] = e);
966
+ },
967
+ removeMessage(e, t) {
968
+ const s = (u) => {
969
+ const f = { ...u, is_deleted: !0 };
970
+ return delete f.body, f;
971
+ };
972
+ let n = null;
973
+ const r = this.conversations.find((u) => u.id === e);
974
+ r?.last_message?.id === t && (n = s(r.last_message), r.last_message = n);
975
+ const i = this.requests.find((u) => u.id === e);
976
+ if (i?.last_message?.id === t) {
977
+ const u = s(i.last_message);
978
+ i.last_message = u, n === null && (n = u);
979
+ }
980
+ const o = this.messages[e];
981
+ if (!o) {
982
+ n && this.addMessage(n);
983
+ return;
984
+ }
985
+ const a = o.findIndex((u) => u.id === t);
986
+ if (a >= 0) {
987
+ const u = o[a];
988
+ u && (o[a] = s(u));
989
+ return;
990
+ }
991
+ n && this.addMessage(n);
992
+ },
993
+ async toggleReaction(e, t, s) {
994
+ const n = `/v1/messaging/conversations/${e}/messages/${t}/reactions`, r = { reaction: s }, o = this.messages[e]?.find((a) => a.id === t)?.reactions ?? [];
995
+ try {
996
+ let a;
997
+ try {
998
+ a = await l.post(n, r);
999
+ } catch (d) {
1000
+ if (!Mt(d))
1001
+ throw d;
1002
+ a = await l.post(n, r);
1003
+ }
1004
+ const u = S(a.data) && "data" in a.data ? a.data.data : a.data, f = Me(
1005
+ S(u) ? u.reactions : void 0
1006
+ );
1007
+ (f.length > 0 || o.length === 0) && this.updateMessageReactions(e, t, f);
1008
+ try {
1009
+ const d = await l.get(n), p = S(d.data) && "data" in d.data ? d.data.data : d.data, F = Me(
1010
+ S(p) ? p.reactions : void 0
1011
+ );
1012
+ this.updateMessageReactions(e, t, F);
1013
+ } catch {
1014
+ }
1015
+ } catch (a) {
1016
+ throw this.error = m(a), a;
1017
+ }
1018
+ },
1019
+ updateMessageReactions(e, t, s) {
1020
+ if (!Array.isArray(s))
1021
+ return;
1022
+ const n = this.messages[e];
1023
+ if (!n) return;
1024
+ const r = n.findIndex((i) => i.id === t);
1025
+ if (r >= 0) {
1026
+ const i = n[r];
1027
+ i && (n[r] = { ...i, reactions: s });
1028
+ }
1029
+ },
1030
+ addTypingUser(e, t) {
1031
+ this.typingUsers[e] || (this.typingUsers[e] = []), this.typingUsers[e].find((n) => n.id === t.id) || this.typingUsers[e].push(t);
1032
+ },
1033
+ removeTypingUser(e, t) {
1034
+ this.typingUsers[e] && (this.typingUsers[e] = this.typingUsers[e].filter((s) => s.id !== t));
1035
+ },
1036
+ updateConversationLastMessage(e, t) {
1037
+ const s = (i) => {
1038
+ const o = i.find((a) => a.id === e);
1039
+ return o ? (o.last_message = t, o.last_message_at = t.created_at, !0) : !1;
1040
+ }, n = s(this.conversations), r = s(this.requests);
1041
+ n && this.conversations.sort(j), r && this.requests.sort(j);
1042
+ },
1043
+ updatePresenceForUser(e, t) {
1044
+ const s = t === "online" || t === "idle" || t === "dnd";
1045
+ for (const n of this.conversations)
1046
+ n.type === "dm" && n.other_user_id === e && (n.other_presence_status = t, n.other_online = s);
1047
+ },
1048
+ async acceptRequest(e) {
1049
+ try {
1050
+ const t = await q.acceptRequest(e);
1051
+ this.requests = this.requests.filter((n) => n.id !== e);
1052
+ const s = D({
1053
+ ...t,
1054
+ is_pinned: t.is_pinned ?? !1,
1055
+ is_archived: t.is_archived ?? !1,
1056
+ is_muted: t.is_muted ?? !1
1057
+ });
1058
+ this.conversations = H(this.conversations, s);
1059
+ } catch (t) {
1060
+ throw this.error = m(t), t;
1061
+ }
1062
+ },
1063
+ async declineRequest(e) {
1064
+ try {
1065
+ await q.declineRequest(e), this.requests = this.requests.filter((t) => t.id !== e);
1066
+ } catch (t) {
1067
+ throw this.error = m(t), t;
1068
+ }
1069
+ },
1070
+ async searchConversations(e, t, s) {
1071
+ this.searchLoading = !0;
1072
+ try {
1073
+ const n = { search: e, limit: 20 };
1074
+ t && (n.filter = t), typeof s == "string" && s.length > 0 && (n.folder_id = s);
1075
+ const r = await l.get("/v1/messaging/conversations", {
1076
+ params: n
1077
+ }), { items: i } = V(
1078
+ r.data,
1079
+ "conversations"
1080
+ );
1081
+ return i;
1082
+ } catch (n) {
1083
+ return this.error = m(n), [];
1084
+ } finally {
1085
+ this.searchLoading = !1;
1086
+ }
1087
+ },
1088
+ async searchMessages(e, t) {
1089
+ this.searchLoading = !0;
1090
+ try {
1091
+ const s = await l.get(`/v1/messaging/conversations/${e}/search`, {
1092
+ params: { q: t }
1093
+ }), n = s.data.data || s.data || [];
1094
+ return this.searchResults = n, n;
1095
+ } catch (s) {
1096
+ return this.error = m(s), [];
1097
+ } finally {
1098
+ this.searchLoading = !1;
1099
+ }
1100
+ },
1101
+ clearSearchResults() {
1102
+ this.searchResults = [];
1103
+ },
1104
+ clearError() {
1105
+ this.error = null;
1106
+ },
1107
+ // Detail subscription tracking — prevents double unread increments
1108
+ // when both useConversationChannel and useGlobalMessaging are active
1109
+ registerDetailSubscription(e) {
1110
+ this._activeDetailSubscriptions.add(e);
1111
+ },
1112
+ unregisterDetailSubscription(e) {
1113
+ this._activeDetailSubscriptions.delete(e);
1114
+ },
1115
+ hasDetailSubscription(e) {
1116
+ return this._activeDetailSubscriptions.has(e);
1117
+ },
1118
+ registerGlobalConversationSubscription(e) {
1119
+ this._activeGlobalConversationSubscriptions.add(e);
1120
+ },
1121
+ unregisterGlobalConversationSubscription(e) {
1122
+ this._activeGlobalConversationSubscriptions.delete(e);
1123
+ },
1124
+ hasGlobalConversationSubscription(e) {
1125
+ return this._activeGlobalConversationSubscriptions.has(e);
1126
+ },
1127
+ // Utility methods
1128
+ shouldRefresh() {
1129
+ return Date.now() - this.lastFetch > 3e5;
1130
+ },
1131
+ reset() {
1132
+ this.$reset();
1133
+ }
1134
+ }
1135
+ });
1136
+ function Gt(e) {
1137
+ const t = Oe(), s = L(), n = J(!1), r = J(null), i = J(null), o = Fe(), a = o !== null, u = 20, f = 250;
1138
+ let _ = 0, d = null, p = null;
1139
+ const F = K(() => s.currentUser?.id), U = () => Be(e)?.trim() ?? "", R = () => {
1140
+ d && (clearTimeout(d), d = null), _ = 0;
1141
+ }, E = () => {
1142
+ !a || n.value || d || _ >= u || (d = setTimeout(() => {
1143
+ d = null, _ += 1, T();
1144
+ }, f));
1145
+ }, T = () => {
1146
+ const c = U();
1147
+ if (!(n.value || !c)) {
1148
+ if (!P()) {
1149
+ E();
1150
+ return;
1151
+ }
1152
+ r.value = null;
1153
+ try {
1154
+ p = ce(c, {
1155
+ onMessageSent: A,
1156
+ onMessageRead: y,
1157
+ onMessageEdited: $,
1158
+ onMessageDeleted: O,
1159
+ onReactionToggled: G,
1160
+ onRequestAccepted: k,
1161
+ onParticipantRemoved: b
1162
+ }), n.value = !0, i.value = c, t.registerDetailSubscription(c), R();
1163
+ } catch (g) {
1164
+ r.value = g instanceof Error ? g.message : "Failed to subscribe to conversation", console.error("ConversationChannel: Subscribe error", g);
1165
+ }
1166
+ }
1167
+ }, z = () => {
1168
+ n.value || T();
1169
+ };
1170
+ typeof window < "u" && window.addEventListener(W, z);
1171
+ const h = Z((c) => {
1172
+ if (c === "connected") {
1173
+ n.value || T();
1174
+ return;
1175
+ }
1176
+ (c === "disconnected" || c === "error") && (R(), p && (p(), p = null), i.value && (t.unregisterDetailSubscription(i.value), i.value = null), n.value = !1);
1177
+ }), v = () => {
1178
+ const c = i.value;
1179
+ if (R(), !(!n.value || !c))
1180
+ try {
1181
+ p && (p(), p = null), t.hasGlobalConversationSubscription(c) || ue(c), n.value = !1, t.unregisterDetailSubscription(c), i.value = null, r.value = null;
1182
+ } catch (g) {
1183
+ r.value = g instanceof Error ? g.message : "Failed to unsubscribe from conversation", console.error("ConversationChannel: Unsubscribe error", g);
1184
+ }
1185
+ }, A = (c) => {
1186
+ if (t.addMessage(c.message), c.message.author_id !== F.value) {
1187
+ const g = t.getConversationById(c.conversation_id);
1188
+ g && (g.unread_count = 0), t.markAsRead(c.conversation_id).catch(() => {
1189
+ });
1190
+ }
1191
+ }, y = (c) => {
1192
+ const g = t.getConversationById(c.conversation_id);
1193
+ if (g) {
1194
+ let M = !1;
1195
+ const w = g.participants.map((C) => C.user_id !== c.user_id || C.last_read_message_id === c.message_id ? C : (M = !0, {
1196
+ ...C,
1197
+ last_read_message_id: c.message_id
1198
+ }));
1199
+ M && (g.participants = w);
1200
+ }
1201
+ }, $ = (c) => {
1202
+ const g = t.getMessagesByConversationId(c.conversation_id), M = g.findIndex((w) => w.id === c.message.id);
1203
+ if (M >= 0) {
1204
+ const w = g[M];
1205
+ if (!w) return;
1206
+ const C = { ...w };
1207
+ c.message.body !== void 0 && (C.body = c.message.body), c.message.edited_at !== void 0 && (C.edited_at = c.message.edited_at), c.message.meta !== void 0 && (C.meta = c.message.meta), g[M] = C;
1208
+ const x = t.getConversationById(c.conversation_id);
1209
+ x && x.last_message?.id === c.message.id && (x.last_message = C);
1210
+ }
1211
+ }, O = (c) => {
1212
+ t.removeMessage(c.conversation_id, c.message_id);
1213
+ }, G = (c) => {
1214
+ t.updateMessageReactions(
1215
+ c.conversation_id,
1216
+ c.message_id,
1217
+ c.reactions
1218
+ );
1219
+ }, k = (c) => {
1220
+ const g = t.getConversationById(c.conversation_id);
1221
+ g && (g.is_request = !1), t.requests = t.requests.filter(
1222
+ (M) => M.id !== c.conversation_id
1223
+ );
1224
+ }, b = (c) => {
1225
+ c.removed_user_id === F.value && (v(), t.deleteConversation(c.conversation_id).catch(() => {
1226
+ }));
1227
+ };
1228
+ return o !== null && Ee(() => {
1229
+ R(), h(), v(), typeof window < "u" && window.removeEventListener(W, z);
1230
+ }), {
1231
+ isSubscribed: K(() => n.value),
1232
+ error: K(() => r.value),
1233
+ subscribe: T,
1234
+ unsubscribe: v
1235
+ };
1236
+ }
1237
+ const Ge = () => {
1238
+ };
1239
+ let he = Ge;
1240
+ function At(e) {
1241
+ he = e;
1242
+ }
1243
+ function Ft() {
1244
+ he = Ge;
1245
+ }
1246
+ const Et = {
1247
+ debug: () => {
1248
+ },
1249
+ info: () => {
1250
+ },
1251
+ warn: () => {
1252
+ },
1253
+ error: () => {
1254
+ }
1255
+ }, ke = () => Et;
1256
+ let ge = ke;
1257
+ function Tt(e) {
1258
+ ge = e;
1259
+ }
1260
+ function xt() {
1261
+ ge = ke;
1262
+ }
1263
+ const ne = ge("GlobalMessaging"), qt = 3, Pt = (e) => e.replace(/\/+$/, ""), Lt = (e) => Pt(window.location.pathname) === `/messages/${e}`, Ut = (e) => e.is_muted ? !0 : typeof e.muted_until == "string" && e.muted_until.length > 0;
1264
+ function kt() {
1265
+ const e = Oe(), t = L(), s = We(), n = Fe(), { conversations: r } = He(e), i = /* @__PURE__ */ new Set(), o = /* @__PURE__ */ new Map();
1266
+ let a = !1;
1267
+ function u(h) {
1268
+ const v = o.get(h);
1269
+ if (v && (o.delete(h), typeof v.channel.stopListening == "function"))
1270
+ for (const A of v.bindings)
1271
+ try {
1272
+ v.channel.stopListening(A.event, A.handler);
1273
+ } catch {
1274
+ }
1275
+ }
1276
+ function f() {
1277
+ for (const h of i)
1278
+ u(h), e.unregisterGlobalConversationSubscription(h);
1279
+ i.clear();
1280
+ }
1281
+ function _(h) {
1282
+ const v = P();
1283
+ if (!v || i.has(h)) return;
1284
+ const A = (b) => {
1285
+ const c = e.getConversationById(b.conversation_id);
1286
+ if (!c)
1287
+ return;
1288
+ let g = !1;
1289
+ const M = c.participants.map((w) => w.user_id !== b.user_id || w.last_read_message_id === b.message_id ? w : (g = !0, {
1290
+ ...w,
1291
+ last_read_message_id: b.message_id
1292
+ }));
1293
+ g && (c.participants = M);
1294
+ }, y = `conversation.${h}`;
1295
+ u(h);
1296
+ const $ = v.private(y), O = (b) => {
1297
+ if (!Ze(b)) {
1298
+ ne.warn("Dropping malformed ConversationMessageSent event", b);
1299
+ return;
1300
+ }
1301
+ const c = b, g = t.currentUser?.id;
1302
+ if (!g || c.message.author_id === g) return;
1303
+ e.addMessage(c.message);
1304
+ const M = e.hasDetailSubscription(c.conversation_id), w = Lt(c.conversation_id);
1305
+ if (M || w) {
1306
+ const x = e.getConversationById(c.conversation_id);
1307
+ x && (x.unread_count = 0), e.markAsRead(c.conversation_id).catch(() => {
1308
+ });
1309
+ return;
1310
+ }
1311
+ const C = e.getConversationById(c.conversation_id);
1312
+ if (C) {
1313
+ const x = Ut(C);
1314
+ x || C.unread_count++, he(x);
1315
+ }
1316
+ }, G = (b) => {
1317
+ if (!Je(b)) {
1318
+ ne.warn("Dropping malformed ConversationMessageRead event", b);
1319
+ return;
1320
+ }
1321
+ A(b);
1322
+ }, k = (b) => {
1323
+ if (!Ke(b)) {
1324
+ ne.warn("Dropping malformed ConversationRequestAccepted event", b);
1325
+ return;
1326
+ }
1327
+ const c = b, g = e.getConversationById(c.conversation_id);
1328
+ g && (g.is_request = !1), e.requests = e.requests.filter(
1329
+ (M) => M.id !== c.conversation_id
1330
+ );
1331
+ };
1332
+ $.listen(".ConversationMessageSent", O), $.listen(".ConversationMessageRead", G), $.listen(".ConversationRequestAccepted", k), o.set(h, {
1333
+ channel: $,
1334
+ bindings: [
1335
+ { event: ".ConversationMessageSent", handler: O },
1336
+ { event: ".ConversationMessageRead", handler: G },
1337
+ { event: ".ConversationRequestAccepted", handler: k }
1338
+ ]
1339
+ }), i.add(h), e.registerGlobalConversationSubscription(h);
1340
+ }
1341
+ function d() {
1342
+ const h = P();
1343
+ if (!h) {
1344
+ f();
1345
+ return;
1346
+ }
1347
+ for (const v of i) {
1348
+ u(v);
1349
+ try {
1350
+ h.leave(`conversation.${v}`);
1351
+ } catch {
1352
+ }
1353
+ e.unregisterGlobalConversationSubscription(v);
1354
+ }
1355
+ i.clear();
1356
+ }
1357
+ function p() {
1358
+ const h = P();
1359
+ if (!h) return;
1360
+ const v = e.conversations.slice(0, qt), A = new Set(v.map((y) => y.id));
1361
+ for (const y of i)
1362
+ if (!A.has(y) && !e.hasDetailSubscription(y)) {
1363
+ try {
1364
+ u(y), h.leave(`conversation.${y}`);
1365
+ } catch {
1366
+ }
1367
+ i.delete(y), e.unregisterGlobalConversationSubscription(y);
1368
+ }
1369
+ for (const y of v)
1370
+ _(y.id);
1371
+ }
1372
+ function F(h) {
1373
+ e.updatePresenceForUser(h.user_id, h.status);
1374
+ }
1375
+ function U() {
1376
+ !P() || a || (oe(F), a = !0);
1377
+ }
1378
+ function R() {
1379
+ a && (ae(), a = !1);
1380
+ }
1381
+ const E = me(
1382
+ r,
1383
+ () => {
1384
+ p();
1385
+ },
1386
+ { deep: !1, immediate: !0 }
1387
+ ), T = me(
1388
+ () => s.fullPath,
1389
+ () => {
1390
+ p();
1391
+ }
1392
+ ), z = Z((h) => {
1393
+ h === "connected" ? (f(), p(), R(), U()) : (h === "disconnected" || h === "error") && (f(), R());
1394
+ });
1395
+ p(), U(), n !== null && Ee(() => {
1396
+ E(), T(), z(), d(), R();
1397
+ });
1398
+ }
1399
+ function Bt(e) {
1400
+ e.apiClient && et(e.apiClient), e.authStore && st(e.authStore), e.mediaApi && rt(e.mediaApi), e.createLogger && Tt(e.createLogger), e.playMessageNotification && At(e.playMessageNotification), e.echo && Xe(e.echo);
1401
+ }
1402
+ function Vt() {
1403
+ tt(), nt(), it(), xt(), Ft(), Qe();
1404
+ }
1405
+ export {
1406
+ W as ECHO_INITIALIZED_EVENT,
1407
+ l as api,
1408
+ Bt as configureMessengerClient,
1409
+ ge as createLogger,
1410
+ P as getEcho,
1411
+ m as getErrorMessage,
1412
+ Ot as hasResponse,
1413
+ jt as isAxiosError,
1414
+ It as isError,
1415
+ Je as isValidMessageReadEvent,
1416
+ Ze as isValidMessageSentEvent,
1417
+ Ke as isValidRequestAcceptedEvent,
1418
+ de as mediaApi,
1419
+ q as messagingApi,
1420
+ Z as onConnectionStatusChange,
1421
+ Qe as resetEchoRuntimeConfig,
1422
+ xt as resetLoggerFactory,
1423
+ tt as resetMessagingApiClient,
1424
+ nt as resetMessagingAuthStoreResolver,
1425
+ it as resetMessagingMediaApi,
1426
+ Vt as resetMessengerClientConfig,
1427
+ Xe as setEchoRuntimeConfig,
1428
+ Tt as setLoggerFactory,
1429
+ et as setMessagingApiClient,
1430
+ st as setMessagingAuthStoreResolver,
1431
+ rt as setMessagingMediaApi,
1432
+ ce as subscribeToConversation,
1433
+ oe as subscribeToPresenceStatus,
1434
+ ue as unsubscribeFromConversation,
1435
+ ae as unsubscribeFromPresenceStatus,
1436
+ L as useAuthStore,
1437
+ Gt as useConversationChannel,
1438
+ kt as useGlobalMessaging,
1439
+ Oe as useMessagingStore
1440
+ };