@kispi/chat 0.7.4 → 0.7.5

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
@@ -24,7 +24,11 @@ __export(src_exports, {
24
24
  ChatEndpoint: () => ChatEndpoint,
25
25
  ChatError: () => ChatError,
26
26
  Room: () => Room,
27
- createChatClient: () => createChatClient
27
+ RoomList: () => RoomList,
28
+ Thread: () => Thread,
29
+ buildMentions: () => buildMentions,
30
+ createChatClient: () => createChatClient,
31
+ mentionSpans: () => mentionSpans
28
32
  });
29
33
  module.exports = __toCommonJS(src_exports);
30
34
 
@@ -231,6 +235,8 @@ var Timeline = class {
231
235
  */
232
236
  presses = /* @__PURE__ */ new Map();
233
237
  pressSeq = 0;
238
+ /** Refreshes in flight; every change to a held row records itself in each. */
239
+ refreshes = /* @__PURE__ */ new Set();
234
240
  constructor(options) {
235
241
  this.options = options;
236
242
  }
@@ -322,14 +328,14 @@ var Timeline = class {
322
328
  *
323
329
  * A caller that wants the list genuinely emptied has `discard()`.
324
330
  */
325
- reset(messages) {
331
+ reset(messages, options = {}) {
326
332
  this.epoch++;
327
333
  this.fills.clear();
328
334
  const page = [...messages].sort((a, b) => a.seq - b.seq);
329
335
  for (const m of page) this.serverRendered(m.id);
330
336
  const top = page.at(-1)?.seq ?? 0;
331
337
  this.items = [...page, ...this.items.filter((m) => m.seq > top)];
332
- this.exhausted = false;
338
+ this.exhausted = options.exhausted ?? false;
333
339
  this.shared = false;
334
340
  for (const m of this.items) {
335
341
  if (this.pendingDeletes.has(m.id)) this.applyDelete(m.id);
@@ -351,6 +357,20 @@ var Timeline = class {
351
357
  }
352
358
  return Promise.resolve();
353
359
  }
360
+ /**
361
+ * Takes one row in seq order **without** looking for holes.
362
+ *
363
+ * For a list whose seqs are not contiguous by nature -- a thread's
364
+ * replies are scattered over the room's stream, so every arrival would
365
+ * look like a hole and `add` would go fetching it.
366
+ */
367
+ put(message) {
368
+ this.insert(message);
369
+ }
370
+ /** Whether a row with this id is held. */
371
+ has(id) {
372
+ return this.items.some((m) => m.id === id);
373
+ }
354
374
  /**
355
375
  * Applies a `message.updated`.
356
376
  *
@@ -365,6 +385,7 @@ var Timeline = class {
365
385
  if (at === -1) return;
366
386
  const current = this.items[at];
367
387
  if (current.deletedAt !== void 0) return;
388
+ this.touch(message.id);
368
389
  this.own();
369
390
  this.items[at] = { ...current, ...message };
370
391
  this.changed();
@@ -453,6 +474,7 @@ var Timeline = class {
453
474
  else if (!mine && has) myReactions = held.filter((e) => e !== emoji);
454
475
  }
455
476
  if (reactions === current.reactions && myReactions === current.myReactions) return;
477
+ this.touch(messageId);
456
478
  const next = { ...current };
457
479
  if (reactions !== void 0) next.reactions = reactions;
458
480
  if (myReactions !== void 0) next.myReactions = myReactions;
@@ -473,6 +495,7 @@ var Timeline = class {
473
495
  const thread = { count };
474
496
  if (lastSeq !== void 0) thread.lastSeq = lastSeq;
475
497
  if (lastAt !== void 0) thread.lastAt = lastAt;
498
+ this.touch(rootId);
476
499
  this.own();
477
500
  this.items[at] = { ...current, thread };
478
501
  this.changed();
@@ -481,6 +504,93 @@ var Timeline = class {
481
504
  remove(id) {
482
505
  if (!this.applyDelete(id)) this.pendingDeletes.add(id);
483
506
  }
507
+ /**
508
+ * Starts a background refresh of the rows already held (see `applyRefresh`).
509
+ *
510
+ * Call it **before** the read goes out: from here on every change to a held
511
+ * row -- a live frame, a fill, this client's own press -- is remembered,
512
+ * because the page being fetched may predate it.
513
+ */
514
+ beginRefresh() {
515
+ const handle = { epoch: this.epoch, touched: /* @__PURE__ */ new Set() };
516
+ this.refreshes.add(handle);
517
+ return handle;
518
+ }
519
+ /** Stops tracking. Idempotent; `applyRefresh` ends its handle itself. */
520
+ endRefresh(handle) {
521
+ this.refreshes.delete(handle);
522
+ }
523
+ /**
524
+ * Merges a page the server rendered into the rows already held.
525
+ *
526
+ * Reconnecting recovers new messages (`catchUp`) and says nothing about
527
+ * rows this client already has: a reaction, a thread count, an edit or a
528
+ * delete that happened while it was away rides on no event it will ever
529
+ * see. This is the read that finds them, and it is a **merge**, not
530
+ * `reset`:
531
+ *
532
+ * - Only held rows are updated. A row in the page that is not held is left
533
+ * alone (a hole is `fill`'s business), and rows below the page -- older
534
+ * than the newest window -- are not looked at.
535
+ * - A row changes only when something differs, so a reconnect does not
536
+ * announce every row. Absent and empty `reactions`/`myReactions` are the
537
+ * same thing (a live `message.created` has `[]`, a history row nobody
538
+ * reacted to has none).
539
+ * - A held row inside the page's seq range that the page does not contain,
540
+ * or contains as a tombstone, becomes a tombstone here too.
541
+ * - **Live wins.** Rows touched since `beginRefresh` are skipped: whatever
542
+ * touched them came from a socket or a press newer than the read. A row
543
+ * with a press still waiting on the server keeps its `myReactions` for
544
+ * the same reason -- the page may have been rendered before that frame
545
+ * landed -- and keeps its press, so the answer still settles it.
546
+ * - Nothing is applied once the timeline was reset or discarded.
547
+ *
548
+ * Returns what changed; the caller emits the events a live frame would.
549
+ */
550
+ applyRefresh(handle, page, options = {}) {
551
+ this.refreshes.delete(handle);
552
+ const result = { updated: [], deleted: [] };
553
+ if (handle.epoch !== this.epoch || page.length === 0) return result;
554
+ if (options.insertMissing === true) {
555
+ const missing = page.filter((m) => !this.has(m.id));
556
+ for (const m of missing) this.insert(m, false);
557
+ if (missing.length > 0) this.changed();
558
+ }
559
+ const byId = new Map(page.map((m) => [m.id, m]));
560
+ let low = Number.POSITIVE_INFINITY;
561
+ let high = 0;
562
+ for (const m of page) {
563
+ low = Math.min(low, m.seq);
564
+ high = Math.max(high, m.seq);
565
+ }
566
+ let items;
567
+ for (let at = 0; at < this.items.length; at++) {
568
+ const held = this.items[at];
569
+ if (held.seq < low || held.seq > high || handle.touched.has(held.id) || held.deletedAt !== void 0) continue;
570
+ const fresh = byId.get(held.id);
571
+ const next = fresh === void 0 ? emptied(held) : mergeRow(held, fresh, this.hasPress(held.id));
572
+ if (next === void 0) continue;
573
+ items ??= this.items.slice();
574
+ items[at] = next;
575
+ if (next.deletedAt !== void 0) result.deleted.push(next);
576
+ else result.updated.push(next);
577
+ }
578
+ if (items !== void 0) {
579
+ this.items = items;
580
+ this.shared = false;
581
+ this.changed();
582
+ }
583
+ return result;
584
+ }
585
+ /** Records that a held row was just changed by something newer than any read in flight. */
586
+ touch(id) {
587
+ for (const handle of this.refreshes) handle.touched.add(id);
588
+ }
589
+ hasPress(messageId) {
590
+ const prefix = `${messageId}\0`;
591
+ for (const key of this.presses.keys()) if (key.startsWith(prefix)) return true;
592
+ return false;
593
+ }
484
594
  /**
485
595
  * Prepends the page just below the oldest message held.
486
596
  *
@@ -559,6 +669,7 @@ var Timeline = class {
559
669
  /** Inserts at the seq position, replacing an existing row with that seq. */
560
670
  insert(message, notify = true) {
561
671
  this.serverRendered(message.id);
672
+ this.touch(message.id);
562
673
  const pending = this.pendingDeletes.has(message.id);
563
674
  if (pending) this.pendingDeletes.delete(message.id);
564
675
  const withDelete = pending ? emptied(message) : message;
@@ -578,6 +689,7 @@ var Timeline = class {
578
689
  const at = this.items.findIndex((m) => m.id === id);
579
690
  if (at === -1) return false;
580
691
  this.pendingDeletes.delete(id);
692
+ this.touch(id);
581
693
  this.own();
582
694
  this.items[at] = emptied(this.items[at]);
583
695
  this.changed();
@@ -612,6 +724,37 @@ var Timeline = class {
612
724
  function emptied(message) {
613
725
  return { ...message, body: {}, deletedAt: message.deletedAt ?? Date.now() };
614
726
  }
727
+ var RefreshFields = ["body", "editedAt", "deletedAt", "reactions", "myReactions", "thread", "meta", "appMeta", "sender"];
728
+ function mergeRow(held, fresh, pressed) {
729
+ if (fresh.deletedAt !== void 0) return emptied({ ...held, ...fresh });
730
+ const next = { ...held };
731
+ let changed = false;
732
+ for (const field of RefreshFields) {
733
+ if (field === "myReactions" && (pressed || fresh.myReactions === void 0)) continue;
734
+ if (deepEqual(normalized(field, held[field]), normalized(field, fresh[field]))) continue;
735
+ changed = true;
736
+ if (fresh[field] === void 0) delete next[field];
737
+ else next[field] = fresh[field];
738
+ }
739
+ return changed ? next : void 0;
740
+ }
741
+ function normalized(field, value) {
742
+ if (field === "reactions") {
743
+ return [...value ?? []].sort((a, b) => a.emoji < b.emoji ? -1 : a.emoji > b.emoji ? 1 : 0);
744
+ }
745
+ if (field === "myReactions") return [...value ?? []].sort();
746
+ if (field === "meta" || field === "appMeta") return value ?? {};
747
+ return value;
748
+ }
749
+ function deepEqual(a, b) {
750
+ if (a === b) return true;
751
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
752
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
753
+ const defined = (o) => Object.keys(o).filter((k) => o[k] !== void 0);
754
+ const ka = defined(a);
755
+ if (ka.length !== defined(b).length) return false;
756
+ return ka.every((k) => deepEqual(a[k], b[k]));
757
+ }
615
758
  function pairKey(messageId, emoji) {
616
759
  return `${messageId}\0${emoji}`;
617
760
  }
@@ -619,9 +762,192 @@ function createTimeline(options) {
619
762
  return new Timeline(options);
620
763
  }
621
764
 
765
+ // src/thread.ts
766
+ var Thread = class extends Emitter {
767
+ rootId;
768
+ /** The newest page has been read at least once (`load()`). */
769
+ loaded = false;
770
+ room;
771
+ /** @internal The replies. */
772
+ replies;
773
+ /** @internal The root, when the room's own list does not hold it (an old message). */
774
+ rootLine;
775
+ lastRoot;
776
+ markedSeq = 0;
777
+ closed = false;
778
+ /** Moves on `load()` and on `close()`; a read from before is dropped. */
779
+ generation = 0;
780
+ offRoom;
781
+ onClose;
782
+ /** @internal Made by `room.thread()`. */
783
+ constructor(room, rootId, onClose) {
784
+ super();
785
+ this.room = room;
786
+ this.rootId = rootId;
787
+ this.onClose = onClose;
788
+ this.replies = createTimeline({
789
+ fetchRange: ({ after, before, limit }) => room.history({ ...after > 0 ? { after } : {}, before, limit, view: { thread: rootId } }),
790
+ onChange: (messages) => this.emit("messages", messages)
791
+ });
792
+ this.rootLine = createTimeline({
793
+ // 루트 한 줄은 읽어 올 길이 없다(메시지 하나를 읽는 라우트가 없다). 들고만 있는다.
794
+ fetchRange: async () => [],
795
+ onChange: () => this.checkRoot()
796
+ });
797
+ this.offRoom = room.on("messages", () => this.checkRoot());
798
+ this.lastRoot = this.root;
799
+ }
800
+ /** The replies held, in seq order. Tombstones keep their place, as in `room.messages`. */
801
+ get messages() {
802
+ return this.replies.messages;
803
+ }
804
+ /**
805
+ * The root message: the room's own row when it holds it, or the copy passed
806
+ * to `room.thread(rootId, { root })`. Undefined when neither has it.
807
+ */
808
+ get root() {
809
+ return this.room.messages.find((m) => m.id === this.rootId) ?? this.rootLine.messages[0];
810
+ }
811
+ /** Whether `loadOlder()` would find more replies. False until `load()` and after a short page. */
812
+ get hasOlder() {
813
+ return this.replies.hasOlder;
814
+ }
815
+ /**
816
+ * Reads the newest page of replies and replaces what is held (replies that
817
+ * arrived live while it was in flight survive). Call it when the panel opens.
818
+ */
819
+ async load(options = {}) {
820
+ const gen = ++this.generation;
821
+ const limit = Math.min(options.limit ?? MaxPageSize, MaxPageSize);
822
+ const page = await this.room.history({ view: { thread: this.rootId }, limit });
823
+ if (gen !== this.generation || this.closed) return;
824
+ this.loaded = true;
825
+ this.replies.reset(page, { exhausted: page.length < limit });
826
+ }
827
+ /** Reads the page just above the oldest reply held and prepends it. Concurrent calls share one request. */
828
+ loadOlder(options = {}) {
829
+ return this.replies.loadOlder(options.limit);
830
+ }
831
+ /**
832
+ * Moves this user's read cursor for the thread to `seq` -- by default the
833
+ * newest reply held. Skips the frame when this handle already marked that
834
+ * far, so it can be called on every `messages` event.
835
+ */
836
+ async markRead(seq) {
837
+ const target = seq ?? this.messages.at(-1)?.seq ?? 0;
838
+ if (target <= this.markedSeq) return { seq: this.markedSeq, advanced: false };
839
+ const before = this.markedSeq;
840
+ this.markedSeq = target;
841
+ try {
842
+ return await this.room.markRead(target, { threadId: this.rootId });
843
+ } catch (err) {
844
+ if (this.markedSeq === target) this.markedSeq = before;
845
+ throw err;
846
+ }
847
+ }
848
+ /** Stops following the thread. `room.thread(rootId)` afterwards gives a new handle. */
849
+ close() {
850
+ if (this.closed) return;
851
+ this.closed = true;
852
+ this.generation++;
853
+ this.offRoom();
854
+ this.onClose(this);
855
+ this.dropRows();
856
+ }
857
+ /** @internal Applies a room event to the rows this thread holds. */
858
+ apply(type, data) {
859
+ switch (type) {
860
+ case "message.created": {
861
+ const m = data;
862
+ if (m.threadId === this.rootId) this.replies.put(m);
863
+ break;
864
+ }
865
+ case "message.updated":
866
+ this.replies.update(data);
867
+ this.rootLine.update(data);
868
+ break;
869
+ case "message.deleted": {
870
+ const id = data.id;
871
+ if (this.replies.has(id)) this.replies.remove(id);
872
+ if (this.rootLine.has(id)) this.rootLine.remove(id);
873
+ break;
874
+ }
875
+ case "thread.updated": {
876
+ const t = data;
877
+ if (t.rootId === this.rootId) this.rootLine.thread(t.rootId, t.count, t.lastSeq, t.lastAt);
878
+ break;
879
+ }
880
+ default:
881
+ break;
882
+ }
883
+ }
884
+ /** @internal Seeds the root copy (`room.thread(rootId, { root })`). */
885
+ seedRoot(root) {
886
+ if (root.id === this.rootId && !this.rootLine.has(root.id)) this.rootLine.put(root);
887
+ }
888
+ /**
889
+ * @internal
890
+ * After a reconnect: re-reads the newest page and merges it -- replies that
891
+ * arrived while away are added (a thread has no hole filling), held ones get
892
+ * their reactions, edits and deletes. Live frames that landed meanwhile win.
893
+ */
894
+ async sync(stillCurrent) {
895
+ if (!this.loaded || this.closed) return;
896
+ const gen = this.generation;
897
+ const handle = this.replies.beginRefresh();
898
+ try {
899
+ const page = await this.room.history({ view: { thread: this.rootId }, limit: MaxPageSize });
900
+ if (!stillCurrent() || gen !== this.generation || this.closed) return;
901
+ this.replies.applyRefresh(handle, page, { insertMissing: true });
902
+ } catch (err) {
903
+ if (stillCurrent() && !this.closed) this.emit("error", err instanceof Error ? err : new Error(String(err)));
904
+ } finally {
905
+ this.replies.endRefresh(handle);
906
+ }
907
+ }
908
+ /**
909
+ * @internal
910
+ * The user changed: the rows carried the previous user's `myReactions`.
911
+ * Dropped now; `reload()` reads them again once the room is back.
912
+ */
913
+ discard() {
914
+ this.reloadPending ||= this.loaded;
915
+ this.generation++;
916
+ this.dropRows();
917
+ }
918
+ /**
919
+ * @internal
920
+ * The room's list was rebuilt (`reset`): a thread that was showing is read
921
+ * again, since what it held may be gone from the room's retention or belong
922
+ * to the previous user.
923
+ */
924
+ reload() {
925
+ const wanted = this.reloadPending || this.loaded;
926
+ this.reloadPending = false;
927
+ if (!wanted || this.closed) return;
928
+ this.load().catch((err) => {
929
+ if (!this.closed) this.emit("error", err instanceof Error ? err : new Error(String(err)));
930
+ });
931
+ }
932
+ reloadPending = false;
933
+ dropRows() {
934
+ this.loaded = false;
935
+ this.markedSeq = 0;
936
+ this.replies.discard();
937
+ this.rootLine.discard();
938
+ }
939
+ checkRoot() {
940
+ const root = this.root;
941
+ if (root === this.lastRoot) return;
942
+ this.lastRoot = root;
943
+ this.emit("root", root);
944
+ }
945
+ };
946
+
622
947
  // src/room.ts
623
948
  var HistoryPageSize = 100;
624
949
  var TypingSendIntervalMs = 1e3;
950
+ var TypingTtlMs = 5e3;
625
951
  var MaxRepairs = 5;
626
952
  var RepairBaseMs = 1e3;
627
953
  var Room = class extends Emitter {
@@ -671,12 +997,27 @@ var Room = class extends Emitter {
671
997
  wanted = false;
672
998
  /** 신원이 바뀌어 버린 목록을 다음 구독이 다시 채우고 `reset`으로 알려야 한다. */
673
999
  rebuildPending = false;
1000
+ /**
1001
+ * The next successful catch-up follows a real reconnect, so the held rows
1002
+ * get re-read (`refreshHeld`).
1003
+ *
1004
+ * Set by a restarting `resume`, cleared once the refresh was started or
1005
+ * the timeline was rebuilt anyway, and **kept across a failed
1006
+ * attempt**: the self-repair `subscribe()` that finally succeeds is still
1007
+ * the one that follows the reconnect.
1008
+ */
1009
+ refreshPending = false;
674
1010
  /** When `typing()` last tried to send (a closed socket still spends the window). See TypingSendIntervalMs. */
675
1011
  typingSentAt = Number.NEGATIVE_INFINITY;
676
1012
  subscribing;
677
1013
  /** Self-repair: the armed retry, and how many have run since the last success. */
678
1014
  repairTimer;
679
1015
  repairs = 0;
1016
+ /** Open thread handles by root id (`thread()`). */
1017
+ threads = /* @__PURE__ */ new Map();
1018
+ /** Who is typing, by `<threadId>|<userId>` (empty threadId: the main timeline). */
1019
+ typers = /* @__PURE__ */ new Map();
1020
+ typingTimer;
680
1021
  constructor(chat, rest, address) {
681
1022
  super();
682
1023
  this.chat = chat;
@@ -707,6 +1048,73 @@ var Room = class extends Emitter {
707
1048
  get messages() {
708
1049
  return this.timeline.messages;
709
1050
  }
1051
+ /**
1052
+ * A handle on one thread's replies -- what a thread panel draws.
1053
+ *
1054
+ * Cached per root id until `thread.close()`. Call `thread.load()` to read
1055
+ * the newest replies; from then on new replies, reactions (including this
1056
+ * client's optimistic `myReactions`), edits and deletes reach its rows like
1057
+ * they reach `room.messages`, and a reconnect re-reads its newest page.
1058
+ *
1059
+ * `root` seeds `thread.root` for a root the room's list does not hold (an
1060
+ * old message opened from search or a link). Without it `thread.root` is the
1061
+ * room's own row, or undefined.
1062
+ */
1063
+ thread(rootId, options = {}) {
1064
+ let thread = this.threads.get(rootId);
1065
+ if (thread === void 0) {
1066
+ thread = new Thread(this, rootId, (t) => {
1067
+ if (this.threads.get(rootId) === t) this.threads.delete(rootId);
1068
+ });
1069
+ this.threads.set(rootId, thread);
1070
+ }
1071
+ if (options.root !== void 0) thread.seedRoot(options.root);
1072
+ return thread;
1073
+ }
1074
+ /**
1075
+ * Who is typing right now in one place: the main timeline, or the thread
1076
+ * whose root is `threadId`. User ids, oldest signal first, **without this
1077
+ * client's own user**. Someone drops out five seconds after their last
1078
+ * signal, or as soon as their message arrives. `typing.changed` fires
1079
+ * whenever this changes.
1080
+ */
1081
+ typists(options = {}) {
1082
+ const now = Date.now();
1083
+ const scope = options.threadId ?? "";
1084
+ const out = [];
1085
+ for (const t of this.typers.values()) {
1086
+ if ((t.threadId ?? "") === scope && now - t.at < TypingTtlMs) out.push(t.userId);
1087
+ }
1088
+ return out;
1089
+ }
1090
+ /**
1091
+ * Edits one of this user's own messages. The server allows only the
1092
+ * sender, within the app's edit window, and answers `forbidden` otherwise.
1093
+ *
1094
+ * The body is **replaced**: pass `attachments` (and `entities`) back to keep
1095
+ * them. The returned row is applied to `messages` (and an open thread) right
1096
+ * away; the `message.updated` broadcast that follows changes nothing more.
1097
+ */
1098
+ async edit(messageId, input) {
1099
+ const body = {};
1100
+ if (input.text !== void 0) body["text"] = input.text;
1101
+ if (input.entities !== void 0) body["entities"] = input.entities;
1102
+ if (input.attachments !== void 0) body["attachments"] = input.attachments;
1103
+ const row = await this.rest.patch(`/v1/rooms/${await this.resolveId("editing")}/messages/${messageId}`, { body });
1104
+ this.timeline.update(row);
1105
+ for (const t of this.threads.values()) t.apply("message.updated", row);
1106
+ return row;
1107
+ }
1108
+ /**
1109
+ * Deletes a message: this user's own, or anyone's for the room's owner and
1110
+ * admins. Idempotent. The row becomes a tombstone in `messages` (and an
1111
+ * open thread) right away.
1112
+ */
1113
+ async delete(messageId) {
1114
+ await this.rest.delete(`/v1/rooms/${await this.resolveId("deleting")}/messages/${messageId}`);
1115
+ if (this.timeline.has(messageId)) this.timeline.remove(messageId);
1116
+ for (const t of this.threads.values()) t.apply("message.deleted", { id: messageId });
1117
+ }
710
1118
  /**
711
1119
  * Reads the page just before the oldest message held and **prepends it to
712
1120
  * `messages`**.
@@ -725,18 +1133,22 @@ var Room = class extends Emitter {
725
1133
  return this.timeline.loadOlder(options.limit);
726
1134
  }
727
1135
  /**
728
- * Reloads recent history, discarding what is held.
729
- *
730
- * A reconnect recovers the **message timeline** and nothing else: the
731
- * only history route is `GET .../messages`, and reactions, thread
732
- * counts, read cursors, membership and room metadata ride along only
733
- * for the rows that page happens to contain. So a reaction added to an
734
- * older message while this client was away is never seen, and no
735
- * amount of gap filling will find it.
736
- *
737
- * The SDK does not hide that behind a background refresh, because the
738
- * refresh would have to be either wasteful or wrong. It gives the
739
- * consumer the one honest tool -- ask again -- and says when to use it.
1136
+ * Reloads recent history, replacing what is held.
1137
+ *
1138
+ * A reconnect already brings the held rows up to date by itself: after
1139
+ * the catch-up it re-reads the newest page (one `GET .../messages`,
1140
+ * `limit=100`) and **merges** it into the rows it holds -- reactions,
1141
+ * `myReactions`, thread counts, edits and deletes that happened while
1142
+ * the socket was away -- see `refreshHeld`. Reactions, thread counts and
1143
+ * the like ride on history rows only, and no event replays them, so
1144
+ * without that read nothing would ever show them. Rows **older than the
1145
+ * newest page** are not re-read; they stay as they were until
1146
+ * `reload()`/`loadOlder()` or the next event for them.
1147
+ *
1148
+ * `reload()` is the manual version and a stronger one: it **replaces**
1149
+ * the list with the newest page (rows newer than the page survive) and
1150
+ * drops older pages loaded with `loadOlder()`. Use it for "refresh"
1151
+ * buttons, or after anything the reconnect refresh does not cover.
740
1152
  */
741
1153
  async reload() {
742
1154
  const gen = this.generation;
@@ -787,22 +1199,70 @@ var Room = class extends Emitter {
787
1199
  await this.loadRecent(current);
788
1200
  if (!current()) return;
789
1201
  this.rebuildPending = false;
1202
+ this.refreshPending = false;
790
1203
  this.subscribed = true;
791
1204
  this.emit("reset", this.timeline.messages);
1205
+ for (const t of this.threads.values()) t.reload();
792
1206
  return;
793
1207
  }
794
1208
  if (since > 0) {
795
1209
  await this.timeline.catchUp(ack.lastSeq);
796
1210
  if (!current()) return;
797
1211
  this.subscribed = true;
1212
+ if (this.refreshPending) {
1213
+ this.refreshPending = false;
1214
+ void this.refreshHeld(current);
1215
+ }
798
1216
  return;
799
1217
  }
800
1218
  if (ack.lastSeq > 0) {
801
1219
  await this.loadRecent(current);
802
1220
  }
803
1221
  if (!current()) return;
1222
+ this.refreshPending = false;
804
1223
  this.subscribed = true;
805
1224
  }
1225
+ /**
1226
+ * Re-reads the newest page and merges it into the rows already held.
1227
+ *
1228
+ * What a reconnect's catch-up cannot bring: it fetches rows this client
1229
+ * does not have, and a reaction, a thread count, an edit or a delete that
1230
+ * happened to a row it **does** have rides on no event it will see. One
1231
+ * `GET .../messages?limit=100` per reconnect, so the newest 100 rows of
1232
+ * the room are refreshed and anything older is not -- that is the bound
1233
+ * on the cost, and it is the part of the room people are looking at.
1234
+ * Thread replies live in the same timeline, so they and their roots come
1235
+ * along.
1236
+ *
1237
+ * It is a merge (`Timeline.applyRefresh`): no `reset`, no rows dropped,
1238
+ * older pages from `loadOlder()` untouched, and a row a live frame or a
1239
+ * press changed after the read began is left to that newer value. A row
1240
+ * that changed raises `message.updated`, a row now deleted raises
1241
+ * `message.deleted`, as the live frames would.
1242
+ *
1243
+ * **Failure is background and local**: an `error` event, no repair loop
1244
+ * (the live feed is fine and the next reconnect tries again), and the
1245
+ * room stays subscribed. A refresh from before another reconnect, a
1246
+ * reset or an unsubscribe is discarded (`stillCurrent`, the generation).
1247
+ */
1248
+ async refreshHeld(stillCurrent) {
1249
+ for (const t of this.threads.values()) void t.sync(stillCurrent);
1250
+ if (this.timeline.messages.length === 0) return;
1251
+ const handle = this.timeline.beginRefresh();
1252
+ try {
1253
+ const page = await this.rest.get(`/v1/rooms/${this.requireId("refreshing history")}/messages`, {
1254
+ limit: HistoryPageSize
1255
+ });
1256
+ if (!stillCurrent()) return;
1257
+ const { updated, deleted } = this.timeline.applyRefresh(handle, page.messages);
1258
+ for (const m of updated) this.emit("message.updated", m);
1259
+ for (const m of deleted) this.emit("message.deleted", { id: m.id, seq: m.seq });
1260
+ } catch (err) {
1261
+ if (stillCurrent()) this.emit("error", err instanceof Error ? err : new Error(String(err)));
1262
+ } finally {
1263
+ this.timeline.endRefresh(handle);
1264
+ }
1265
+ }
806
1266
  /**
807
1267
  * Reads a page of history directly, without touching `messages`.
808
1268
  *
@@ -858,7 +1318,8 @@ var Room = class extends Emitter {
858
1318
  * 두고 나온다(`Timeline.settleReaction`).
859
1319
  */
860
1320
  async toggleReaction(messageId, emoji, mine) {
861
- const press = this.timeline.pressReaction(messageId, emoji, mine);
1321
+ const lines = [this.timeline, ...this.sideLines()];
1322
+ const presses = lines.map((line) => line.pressReaction(messageId, emoji, mine));
862
1323
  const owner = this.chat.user?.id;
863
1324
  try {
864
1325
  await this.chat.sendFrame("react", {
@@ -868,11 +1329,22 @@ var Room = class extends Emitter {
868
1329
  op: mine ? "add" : "remove"
869
1330
  }, void 0, { resendOnDrop: true, owner });
870
1331
  } catch (err) {
871
- if (press !== void 0) this.timeline.settleReaction(press, false);
1332
+ presses.forEach((press, i) => {
1333
+ if (press !== void 0) lines[i].settleReaction(press, false);
1334
+ });
872
1335
  throw err;
873
1336
  }
874
- if (press !== void 0) this.timeline.settleReaction(press, true);
875
- else this.timeline.reaction(messageId, emoji, void 0, mine);
1337
+ presses.forEach((press, i) => {
1338
+ const line = lines[i];
1339
+ if (press !== void 0) line.settleReaction(press, true);
1340
+ else line.reaction(messageId, emoji, void 0, mine);
1341
+ });
1342
+ }
1343
+ /** The lists open threads hold beside the room's own: their replies and root copies. */
1344
+ sideLines() {
1345
+ const out = [];
1346
+ for (const t of this.threads.values()) out.push(t.replies, t.rootLine);
1347
+ return out;
876
1348
  }
877
1349
  /**
878
1350
  * Moves this user's read cursor.
@@ -883,9 +1355,12 @@ var Room = class extends Emitter {
883
1355
  */
884
1356
  async markRead(seq, options = {}) {
885
1357
  const owner = this.chat.user?.id;
886
- const data = { roomId: await this.resolveId("marking read"), seq };
1358
+ const roomId = await this.resolveId("marking read");
1359
+ const data = { roomId, seq };
887
1360
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
888
- return await this.chat.sendFrame("read", data, void 0, { resendOnDrop: true, owner });
1361
+ const ack = await this.chat.sendFrame("read", data, void 0, { resendOnDrop: true, owner });
1362
+ if (options.threadId === void 0) this.chat.noteRead(roomId, seq);
1363
+ return ack;
889
1364
  }
890
1365
  /**
891
1366
  * Lists read cursors in this room, one page at a time.
@@ -997,8 +1472,11 @@ var Room = class extends Emitter {
997
1472
  * page.
998
1473
  */
999
1474
  async resume(restart = true, userChanged = false) {
1475
+ if (restart && !userChanged && this.wanted) this.refreshPending = true;
1000
1476
  if (userChanged) {
1477
+ this.refreshPending = false;
1001
1478
  this.timeline.discard();
1479
+ for (const t of this.threads.values()) t.discard();
1002
1480
  if (this.wanted) this.rebuildPending = true;
1003
1481
  }
1004
1482
  if (!this.wanted) return;
@@ -1054,8 +1532,10 @@ var Room = class extends Emitter {
1054
1532
  this.wanted = false;
1055
1533
  this.subscribed = false;
1056
1534
  this.rebuildPending = false;
1535
+ this.refreshPending = this.timeline.messages.length > 0 || this.threads.size > 0;
1057
1536
  this.generation++;
1058
1537
  this.subscribing = void 0;
1538
+ this.clearTypists();
1059
1539
  await this.chat.sendFrame("unsubscribe", { roomId: this.id }, void 0, { wait: false });
1060
1540
  }
1061
1541
  /**
@@ -1130,6 +1610,7 @@ var Room = class extends Emitter {
1130
1610
  const me = this.chat.user?.id;
1131
1611
  const mine = me !== void 0 && r.userId === me ? type === "reaction.added" : void 0;
1132
1612
  this.timeline.reaction(r.messageId, r.emoji, r.count, mine);
1613
+ for (const line of this.sideLines()) line.reaction(r.messageId, r.emoji, r.count, mine);
1133
1614
  break;
1134
1615
  }
1135
1616
  case "thread.updated": {
@@ -1143,7 +1624,57 @@ var Room = class extends Emitter {
1143
1624
  default:
1144
1625
  break;
1145
1626
  }
1627
+ for (const t of this.threads.values()) t.apply(type, data);
1146
1628
  this.emit(type, data);
1629
+ if (type === "typing") this.noteTyping(data);
1630
+ else if (type === "message.created") {
1631
+ const m = data;
1632
+ if (m.sender !== void 0) this.dropTypist(m.sender.id, m.threadId);
1633
+ }
1634
+ }
1635
+ noteTyping(ev) {
1636
+ if (ev.userId === this.chat.user?.id) return;
1637
+ const key = `${ev.threadId ?? ""}|${ev.userId}`;
1638
+ const held = this.typers.get(key);
1639
+ if (held !== void 0) held.at = Date.now();
1640
+ else this.typers.set(key, { userId: ev.userId, ...ev.threadId === void 0 ? {} : { threadId: ev.threadId }, at: Date.now() });
1641
+ if (held === void 0) this.emitTypists(ev.threadId);
1642
+ this.armTypingTimer();
1643
+ }
1644
+ dropTypist(userId, threadId) {
1645
+ if (this.typers.delete(`${threadId ?? ""}|${userId}`)) this.emitTypists(threadId);
1646
+ }
1647
+ emitTypists(threadId) {
1648
+ const userIds = this.typists(threadId === void 0 ? {} : { threadId });
1649
+ this.emit("typing.changed", threadId === void 0 ? { userIds } : { threadId, userIds });
1650
+ }
1651
+ /** One timer for the earliest expiry; re-armed after it fires. */
1652
+ armTypingTimer() {
1653
+ if (this.typingTimer !== void 0) clearTimeout(this.typingTimer);
1654
+ this.typingTimer = void 0;
1655
+ let earliest = Number.POSITIVE_INFINITY;
1656
+ for (const t of this.typers.values()) earliest = Math.min(earliest, t.at);
1657
+ if (earliest === Number.POSITIVE_INFINITY) return;
1658
+ this.typingTimer = setTimeout(() => {
1659
+ this.typingTimer = void 0;
1660
+ const now = Date.now();
1661
+ const scopes = /* @__PURE__ */ new Set();
1662
+ for (const [key, t] of this.typers) {
1663
+ if (now - t.at < TypingTtlMs) continue;
1664
+ this.typers.delete(key);
1665
+ scopes.add(t.threadId);
1666
+ }
1667
+ for (const scope of scopes) this.emitTypists(scope);
1668
+ this.armTypingTimer();
1669
+ }, Math.max(0, earliest + TypingTtlMs - Date.now()));
1670
+ this.typingTimer.unref?.();
1671
+ }
1672
+ clearTypists() {
1673
+ const scopes = new Set([...this.typers.values()].map((t) => t.threadId));
1674
+ this.typers.clear();
1675
+ if (this.typingTimer !== void 0) clearTimeout(this.typingTimer);
1676
+ this.typingTimer = void 0;
1677
+ for (const scope of scopes) this.emitTypists(scope);
1147
1678
  }
1148
1679
  /**
1149
1680
  * Replaces the timeline with the most recent page.
@@ -1183,6 +1714,158 @@ function newClientMessageId() {
1183
1714
  return `cm-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1184
1715
  }
1185
1716
 
1717
+ // src/rooms.ts
1718
+ var PageSize = 100;
1719
+ var MaxPages = 10;
1720
+ var RoomList = class extends Emitter {
1721
+ /** At least one `load()` finished. */
1722
+ loaded = false;
1723
+ list = [];
1724
+ pager;
1725
+ loading;
1726
+ again = false;
1727
+ /** @internal Made by `chat.roomList()`. */
1728
+ constructor(pager) {
1729
+ super();
1730
+ this.pager = pager;
1731
+ }
1732
+ /** The rooms, as of the last change. A new array whenever it changes. */
1733
+ get rooms() {
1734
+ return this.list;
1735
+ }
1736
+ get(roomId) {
1737
+ return this.list.find((r) => r.id === roomId);
1738
+ }
1739
+ /**
1740
+ * Reads the list from the server and replaces what is held. A call while
1741
+ * one is in flight runs once more after it, so the last answer is never
1742
+ * older than the last call.
1743
+ */
1744
+ load() {
1745
+ if (this.loading !== void 0) {
1746
+ this.again = true;
1747
+ return this.loading;
1748
+ }
1749
+ this.loading = this.readAll().catch((err) => {
1750
+ this.emit("error", err instanceof Error ? err : new Error(String(err)));
1751
+ throw err;
1752
+ }).finally(() => {
1753
+ this.loading = void 0;
1754
+ if (this.again) {
1755
+ this.again = false;
1756
+ void this.load().catch(() => {
1757
+ });
1758
+ }
1759
+ });
1760
+ return this.loading;
1761
+ }
1762
+ async readAll() {
1763
+ const rows = [];
1764
+ let cursor;
1765
+ for (let page = 0; page < MaxPages; page++) {
1766
+ const res = await this.pager(cursor === void 0 ? { limit: PageSize } : { cursor, limit: PageSize });
1767
+ for (const r of res.rooms ?? []) rows.push(summaryOf(r));
1768
+ if (!res.cursor) break;
1769
+ cursor = res.cursor;
1770
+ }
1771
+ this.loaded = true;
1772
+ this.set(rows);
1773
+ }
1774
+ /** @internal `notification.message`. */
1775
+ notification(raw) {
1776
+ const n = raw ?? {};
1777
+ if (!this.loaded || typeof n.roomId !== "string") return;
1778
+ const held = this.get(n.roomId);
1779
+ if (held === void 0) {
1780
+ void this.load().catch(() => {
1781
+ });
1782
+ return;
1783
+ }
1784
+ this.patch(n.roomId, (r) => ({
1785
+ ...r,
1786
+ unread: typeof n.unread === "number" ? n.unread : r.unread + 1,
1787
+ mentions: typeof n.unreadMentions === "number" ? n.unreadMentions : r.mentions,
1788
+ ...n.unreadCapped === true ? { unreadCapped: true } : {},
1789
+ lastSeq: Math.max(r.lastSeq, typeof n.seq === "number" ? n.seq : 0)
1790
+ }));
1791
+ }
1792
+ /** @internal A frame from a subscribed room. */
1793
+ roomEvent(roomId, type, data, me) {
1794
+ if (!this.loaded) return;
1795
+ switch (type) {
1796
+ case "message.created": {
1797
+ const seq = data.seq;
1798
+ if (typeof seq === "number") this.patch(roomId, (r) => seq > r.lastSeq ? { ...r, lastSeq: seq } : r);
1799
+ break;
1800
+ }
1801
+ case "room.updated": {
1802
+ const room = data;
1803
+ if (room?.id === roomId) this.patch(roomId, (r) => ({ ...r, room: { ...r.room, ...room } }));
1804
+ break;
1805
+ }
1806
+ case "room.deleted":
1807
+ this.drop(roomId);
1808
+ break;
1809
+ case "member.left":
1810
+ if (me !== void 0 && data.userId === me) this.drop(roomId);
1811
+ break;
1812
+ default:
1813
+ break;
1814
+ }
1815
+ }
1816
+ /** @internal This client moved its main-timeline read cursor. */
1817
+ read(roomId, seq) {
1818
+ this.patch(roomId, (r) => {
1819
+ const readSeq = Math.max(r.readSeq, seq);
1820
+ if (readSeq >= r.lastSeq) return { ...r, readSeq, unread: 0, mentions: 0 };
1821
+ return readSeq === r.readSeq ? r : { ...r, readSeq };
1822
+ });
1823
+ }
1824
+ /** @internal This client renamed or deleted a room through `chat.rooms`. */
1825
+ updated(room) {
1826
+ this.roomEvent(room.id, "room.updated", room, void 0);
1827
+ }
1828
+ /** @internal */
1829
+ drop(roomId) {
1830
+ if (!this.list.some((r) => r.id === roomId)) return;
1831
+ this.set(this.list.filter((r) => r.id !== roomId));
1832
+ }
1833
+ /** @internal The user changed: the counts were the previous user's. */
1834
+ forget() {
1835
+ const had = this.loaded;
1836
+ this.loaded = false;
1837
+ this.set([]);
1838
+ if (had) void this.load().catch(() => {
1839
+ });
1840
+ }
1841
+ patch(roomId, fn) {
1842
+ const at = this.list.findIndex((r) => r.id === roomId);
1843
+ if (at === -1) return;
1844
+ const next = fn(this.list[at]);
1845
+ if (next === this.list[at]) return;
1846
+ const list = this.list.slice();
1847
+ list[at] = next;
1848
+ this.set(list);
1849
+ }
1850
+ set(list) {
1851
+ this.list = list;
1852
+ this.emit("rooms", list);
1853
+ }
1854
+ };
1855
+ function summaryOf(r) {
1856
+ const s = {
1857
+ id: r.room.id,
1858
+ room: r.room,
1859
+ lastSeq: r.lastSeq ?? r.room.lastSeq ?? 0,
1860
+ readSeq: r.readSeq ?? 0,
1861
+ unread: r.unread ?? 0,
1862
+ mentions: r.unreadMentions ?? 0
1863
+ };
1864
+ if (r.unreadCapped === true) s.unreadCapped = true;
1865
+ if (r.lastMessage !== void 0) s.lastMessage = r.lastMessage;
1866
+ return s;
1867
+ }
1868
+
1186
1869
  // src/client.ts
1187
1870
  var MinBackoffMs = 500;
1188
1871
  var MaxBackoffMs = 3e4;
@@ -1266,6 +1949,11 @@ var ChatClient = class extends Emitter {
1266
1949
  };
1267
1950
  window.addEventListener("online", onOnline);
1268
1951
  this.teardowns.push(() => window.removeEventListener("online", onOnline));
1952
+ const onPageShow = (ev) => {
1953
+ if (ev.persisted === true) void this.resume();
1954
+ };
1955
+ window.addEventListener("pageshow", onPageShow);
1956
+ this.teardowns.push(() => window.removeEventListener("pageshow", onPageShow));
1269
1957
  }
1270
1958
  }
1271
1959
  /**
@@ -1315,6 +2003,13 @@ var ChatClient = class extends Emitter {
1315
2003
  for (const room of this.handles.values()) {
1316
2004
  void room.resume().catch((err) => room.failed(err));
1317
2005
  }
2006
+ this.cameBack(false);
2007
+ }
2008
+ /** `resumed`, after the rooms were told. The live room list reloads first. */
2009
+ cameBack(reconnected) {
2010
+ if (this.list?.loaded === true) void this.list.load().catch(() => {
2011
+ });
2012
+ this.emit("resumed", { reconnected });
1318
2013
  }
1319
2014
  /**
1320
2015
  * Pings `socket` and resolves whether any frame came back within
@@ -1350,6 +2045,18 @@ var ChatClient = class extends Emitter {
1350
2045
  return {
1351
2046
  list: (options) => this.rest.get("/v1/me/rooms", { cursor: options?.cursor, limit: options?.limit }),
1352
2047
  discover: (options) => this.rest.get("/v1/rooms", { type: options?.type, cursor: options?.cursor, limit: options?.limit }),
2048
+ // 방장·관리자만 된다(아니면 forbidden). 바뀐 방은 구독자 모두에게
2049
+ // `room.updated`로 간다. key는 백엔드(sk_)가 정하는 것이라 받지 않는다.
2050
+ // 구독하지 않은 방은 그 이벤트가 안 오므로 살아 있는 방 목록은 응답으로 고친다.
2051
+ update: async (roomId, patch) => {
2052
+ const room = await this.rest.patch(`/v1/rooms/${roomId}`, patch);
2053
+ this.list?.updated(room);
2054
+ return room;
2055
+ },
2056
+ delete: async (roomId) => {
2057
+ await this.rest.delete(`/v1/rooms/${roomId}`);
2058
+ this.list?.drop(roomId);
2059
+ },
1353
2060
  members: (roomId) => ({
1354
2061
  list: (options) => this.rest.get(`/v1/rooms/${roomId}/members`, { cursor: options?.cursor, limit: options?.limit }),
1355
2062
  add: async (userId, role) => {
@@ -1397,6 +2104,19 @@ var ChatClient = class extends Emitter {
1397
2104
  async updateMe(meta) {
1398
2105
  return this.rest.patch("/v1/me", { meta });
1399
2106
  }
2107
+ /**
2108
+ * The rooms this user is in, with unread counts the SDK keeps current --
2109
+ * see `RoomList`. One per client; call `load()` once to fill it.
2110
+ */
2111
+ roomList() {
2112
+ this.list ??= new RoomList((options) => this.rooms.list(options));
2113
+ return this.list;
2114
+ }
2115
+ list;
2116
+ /** @internal `room.markRead()` on a main timeline went through. */
2117
+ noteRead(roomId, seq) {
2118
+ this.list?.read(roomId, seq);
2119
+ }
1400
2120
  /**
1401
2121
  * A handle on a room by id.
1402
2122
  *
@@ -1761,11 +2481,13 @@ var ChatClient = class extends Emitter {
1761
2481
  this.everOpened = true;
1762
2482
  this.setState("open");
1763
2483
  this.settleOpenWaiters();
2484
+ if (userChanged) this.list?.forget();
1764
2485
  for (const room of this.handles.values()) {
1765
2486
  void room.resume(reconnected, userChanged).catch((err) => {
1766
2487
  room.failed(err);
1767
2488
  });
1768
2489
  }
2490
+ if (reconnected && !userChanged) this.cameBack(true);
1769
2491
  }
1770
2492
  onFrame(frame) {
1771
2493
  if (frame.id !== void 0) {
@@ -1809,6 +2531,7 @@ var ChatClient = class extends Emitter {
1809
2531
  return;
1810
2532
  }
1811
2533
  if (event === "notification.message") {
2534
+ this.list?.notification(push?.data);
1812
2535
  this.emit("notification", push?.data);
1813
2536
  return;
1814
2537
  }
@@ -1822,6 +2545,7 @@ var ChatClient = class extends Emitter {
1822
2545
  return;
1823
2546
  }
1824
2547
  room.handle(event, push?.data);
2548
+ if (push?.roomId !== void 0) this.list?.roomEvent(push.roomId, event, push?.data, this.user?.id);
1825
2549
  }
1826
2550
  plannedDelayMs;
1827
2551
  // When a server-directed delay (drain, rate limit) ends; a send does not cut it short.
@@ -1914,11 +2638,88 @@ function isChatError(err) {
1914
2638
  function createChatClient(options) {
1915
2639
  return new ChatClient(options);
1916
2640
  }
2641
+
2642
+ // src/mentions.ts
2643
+ var MaxEntities = 100;
2644
+ var NameChar = /[\p{L}\p{N}_]/u;
2645
+ function buildMentions(text, people, options = {}) {
2646
+ if (!text.includes("@")) return [];
2647
+ const groups = /* @__PURE__ */ new Map();
2648
+ for (const p of people) {
2649
+ if (!p.id || !p.name) continue;
2650
+ const ids = groups.get(p.name) ?? [];
2651
+ if (!ids.includes(p.id)) groups.set(p.name, [...ids, p.id]);
2652
+ }
2653
+ if (groups.size === 0) return [];
2654
+ const names = [...groups.keys()].sort((a, b) => b.length - a.length);
2655
+ const code = options.skipCode === false ? [] : codeRanges(text);
2656
+ const used = /* @__PURE__ */ new Map();
2657
+ const out = [];
2658
+ for (let i = text.indexOf("@"); i >= 0 && out.length < MaxEntities; i = text.indexOf("@", i + 1)) {
2659
+ if (i > 0 && /[\p{L}\p{N}_.@]/u.test(text[i - 1])) continue;
2660
+ if (code.some(([s, e]) => i >= s && i < e)) continue;
2661
+ const name = names.find((n2) => {
2662
+ if (!text.startsWith(n2, i + 1)) return false;
2663
+ const next = text[i + 1 + n2.length];
2664
+ return next === void 0 || !NameChar.test(next);
2665
+ });
2666
+ if (name === void 0) continue;
2667
+ const n = used.get(name) ?? 0;
2668
+ const ids = groups.get(name);
2669
+ if (n >= ids.length && ids.length > 1) continue;
2670
+ used.set(name, n + 1);
2671
+ out.push({ type: "mention", userId: ids[Math.min(n, ids.length - 1)], offset: i, length: name.length + 1 });
2672
+ }
2673
+ return out;
2674
+ }
2675
+ function mentionSpans(text, entities) {
2676
+ if (!Array.isArray(entities) || !text) return [];
2677
+ const out = [];
2678
+ for (const raw of entities.slice(0, MaxEntities)) {
2679
+ const e = raw;
2680
+ if (e === null || typeof e !== "object" || e.type !== "mention" || typeof e.userId !== "string" || !e.userId) continue;
2681
+ const { offset, length } = e;
2682
+ if (!Number.isInteger(offset) || !Number.isInteger(length)) continue;
2683
+ const start = offset;
2684
+ const end = start + length;
2685
+ if (start < 0 || length < 2 || end > text.length) continue;
2686
+ if (text[start] !== "@" || text.slice(start, end).includes("\n")) continue;
2687
+ out.push({ start, end, userId: e.userId });
2688
+ }
2689
+ out.sort((a, b) => a.start - b.start);
2690
+ const kept = [];
2691
+ for (const s of out) if (kept.length === 0 || s.start >= kept.at(-1).end) kept.push(s);
2692
+ return kept;
2693
+ }
2694
+ function codeRanges(text) {
2695
+ const out = [];
2696
+ let pos = 0;
2697
+ let open = -1;
2698
+ for (const line of text.split("\n")) {
2699
+ const end = pos + line.length;
2700
+ if (/^\s{0,3}```/.test(line)) {
2701
+ if (open < 0) open = pos;
2702
+ else {
2703
+ out.push([open, end]);
2704
+ open = -1;
2705
+ }
2706
+ } else if (open < 0) {
2707
+ for (const m of line.matchAll(/`[^`\n]+`/g)) out.push([pos + m.index, pos + m.index + m[0].length]);
2708
+ }
2709
+ pos = end + 1;
2710
+ }
2711
+ if (open >= 0) out.push([open, text.length]);
2712
+ return out;
2713
+ }
1917
2714
  // Annotate the CommonJS export names for ESM import in node:
1918
2715
  0 && (module.exports = {
1919
2716
  ChatClient,
1920
2717
  ChatEndpoint,
1921
2718
  ChatError,
1922
2719
  Room,
1923
- createChatClient
2720
+ RoomList,
2721
+ Thread,
2722
+ buildMentions,
2723
+ createChatClient,
2724
+ mentionSpans
1924
2725
  });