@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.js CHANGED
@@ -161,6 +161,8 @@ var Timeline = class {
161
161
  */
162
162
  presses = /* @__PURE__ */ new Map();
163
163
  pressSeq = 0;
164
+ /** Refreshes in flight; every change to a held row records itself in each. */
165
+ refreshes = /* @__PURE__ */ new Set();
164
166
  constructor(options) {
165
167
  this.options = options;
166
168
  }
@@ -252,14 +254,14 @@ var Timeline = class {
252
254
  *
253
255
  * A caller that wants the list genuinely emptied has `discard()`.
254
256
  */
255
- reset(messages) {
257
+ reset(messages, options = {}) {
256
258
  this.epoch++;
257
259
  this.fills.clear();
258
260
  const page = [...messages].sort((a, b) => a.seq - b.seq);
259
261
  for (const m of page) this.serverRendered(m.id);
260
262
  const top = page.at(-1)?.seq ?? 0;
261
263
  this.items = [...page, ...this.items.filter((m) => m.seq > top)];
262
- this.exhausted = false;
264
+ this.exhausted = options.exhausted ?? false;
263
265
  this.shared = false;
264
266
  for (const m of this.items) {
265
267
  if (this.pendingDeletes.has(m.id)) this.applyDelete(m.id);
@@ -281,6 +283,20 @@ var Timeline = class {
281
283
  }
282
284
  return Promise.resolve();
283
285
  }
286
+ /**
287
+ * Takes one row in seq order **without** looking for holes.
288
+ *
289
+ * For a list whose seqs are not contiguous by nature -- a thread's
290
+ * replies are scattered over the room's stream, so every arrival would
291
+ * look like a hole and `add` would go fetching it.
292
+ */
293
+ put(message) {
294
+ this.insert(message);
295
+ }
296
+ /** Whether a row with this id is held. */
297
+ has(id) {
298
+ return this.items.some((m) => m.id === id);
299
+ }
284
300
  /**
285
301
  * Applies a `message.updated`.
286
302
  *
@@ -295,6 +311,7 @@ var Timeline = class {
295
311
  if (at === -1) return;
296
312
  const current = this.items[at];
297
313
  if (current.deletedAt !== void 0) return;
314
+ this.touch(message.id);
298
315
  this.own();
299
316
  this.items[at] = { ...current, ...message };
300
317
  this.changed();
@@ -383,6 +400,7 @@ var Timeline = class {
383
400
  else if (!mine && has) myReactions = held.filter((e) => e !== emoji);
384
401
  }
385
402
  if (reactions === current.reactions && myReactions === current.myReactions) return;
403
+ this.touch(messageId);
386
404
  const next = { ...current };
387
405
  if (reactions !== void 0) next.reactions = reactions;
388
406
  if (myReactions !== void 0) next.myReactions = myReactions;
@@ -403,6 +421,7 @@ var Timeline = class {
403
421
  const thread = { count };
404
422
  if (lastSeq !== void 0) thread.lastSeq = lastSeq;
405
423
  if (lastAt !== void 0) thread.lastAt = lastAt;
424
+ this.touch(rootId);
406
425
  this.own();
407
426
  this.items[at] = { ...current, thread };
408
427
  this.changed();
@@ -411,6 +430,93 @@ var Timeline = class {
411
430
  remove(id) {
412
431
  if (!this.applyDelete(id)) this.pendingDeletes.add(id);
413
432
  }
433
+ /**
434
+ * Starts a background refresh of the rows already held (see `applyRefresh`).
435
+ *
436
+ * Call it **before** the read goes out: from here on every change to a held
437
+ * row -- a live frame, a fill, this client's own press -- is remembered,
438
+ * because the page being fetched may predate it.
439
+ */
440
+ beginRefresh() {
441
+ const handle = { epoch: this.epoch, touched: /* @__PURE__ */ new Set() };
442
+ this.refreshes.add(handle);
443
+ return handle;
444
+ }
445
+ /** Stops tracking. Idempotent; `applyRefresh` ends its handle itself. */
446
+ endRefresh(handle) {
447
+ this.refreshes.delete(handle);
448
+ }
449
+ /**
450
+ * Merges a page the server rendered into the rows already held.
451
+ *
452
+ * Reconnecting recovers new messages (`catchUp`) and says nothing about
453
+ * rows this client already has: a reaction, a thread count, an edit or a
454
+ * delete that happened while it was away rides on no event it will ever
455
+ * see. This is the read that finds them, and it is a **merge**, not
456
+ * `reset`:
457
+ *
458
+ * - Only held rows are updated. A row in the page that is not held is left
459
+ * alone (a hole is `fill`'s business), and rows below the page -- older
460
+ * than the newest window -- are not looked at.
461
+ * - A row changes only when something differs, so a reconnect does not
462
+ * announce every row. Absent and empty `reactions`/`myReactions` are the
463
+ * same thing (a live `message.created` has `[]`, a history row nobody
464
+ * reacted to has none).
465
+ * - A held row inside the page's seq range that the page does not contain,
466
+ * or contains as a tombstone, becomes a tombstone here too.
467
+ * - **Live wins.** Rows touched since `beginRefresh` are skipped: whatever
468
+ * touched them came from a socket or a press newer than the read. A row
469
+ * with a press still waiting on the server keeps its `myReactions` for
470
+ * the same reason -- the page may have been rendered before that frame
471
+ * landed -- and keeps its press, so the answer still settles it.
472
+ * - Nothing is applied once the timeline was reset or discarded.
473
+ *
474
+ * Returns what changed; the caller emits the events a live frame would.
475
+ */
476
+ applyRefresh(handle, page, options = {}) {
477
+ this.refreshes.delete(handle);
478
+ const result = { updated: [], deleted: [] };
479
+ if (handle.epoch !== this.epoch || page.length === 0) return result;
480
+ if (options.insertMissing === true) {
481
+ const missing = page.filter((m) => !this.has(m.id));
482
+ for (const m of missing) this.insert(m, false);
483
+ if (missing.length > 0) this.changed();
484
+ }
485
+ const byId = new Map(page.map((m) => [m.id, m]));
486
+ let low = Number.POSITIVE_INFINITY;
487
+ let high = 0;
488
+ for (const m of page) {
489
+ low = Math.min(low, m.seq);
490
+ high = Math.max(high, m.seq);
491
+ }
492
+ let items;
493
+ for (let at = 0; at < this.items.length; at++) {
494
+ const held = this.items[at];
495
+ if (held.seq < low || held.seq > high || handle.touched.has(held.id) || held.deletedAt !== void 0) continue;
496
+ const fresh = byId.get(held.id);
497
+ const next = fresh === void 0 ? emptied(held) : mergeRow(held, fresh, this.hasPress(held.id));
498
+ if (next === void 0) continue;
499
+ items ??= this.items.slice();
500
+ items[at] = next;
501
+ if (next.deletedAt !== void 0) result.deleted.push(next);
502
+ else result.updated.push(next);
503
+ }
504
+ if (items !== void 0) {
505
+ this.items = items;
506
+ this.shared = false;
507
+ this.changed();
508
+ }
509
+ return result;
510
+ }
511
+ /** Records that a held row was just changed by something newer than any read in flight. */
512
+ touch(id) {
513
+ for (const handle of this.refreshes) handle.touched.add(id);
514
+ }
515
+ hasPress(messageId) {
516
+ const prefix = `${messageId}\0`;
517
+ for (const key of this.presses.keys()) if (key.startsWith(prefix)) return true;
518
+ return false;
519
+ }
414
520
  /**
415
521
  * Prepends the page just below the oldest message held.
416
522
  *
@@ -489,6 +595,7 @@ var Timeline = class {
489
595
  /** Inserts at the seq position, replacing an existing row with that seq. */
490
596
  insert(message, notify = true) {
491
597
  this.serverRendered(message.id);
598
+ this.touch(message.id);
492
599
  const pending = this.pendingDeletes.has(message.id);
493
600
  if (pending) this.pendingDeletes.delete(message.id);
494
601
  const withDelete = pending ? emptied(message) : message;
@@ -508,6 +615,7 @@ var Timeline = class {
508
615
  const at = this.items.findIndex((m) => m.id === id);
509
616
  if (at === -1) return false;
510
617
  this.pendingDeletes.delete(id);
618
+ this.touch(id);
511
619
  this.own();
512
620
  this.items[at] = emptied(this.items[at]);
513
621
  this.changed();
@@ -542,6 +650,37 @@ var Timeline = class {
542
650
  function emptied(message) {
543
651
  return { ...message, body: {}, deletedAt: message.deletedAt ?? Date.now() };
544
652
  }
653
+ var RefreshFields = ["body", "editedAt", "deletedAt", "reactions", "myReactions", "thread", "meta", "appMeta", "sender"];
654
+ function mergeRow(held, fresh, pressed) {
655
+ if (fresh.deletedAt !== void 0) return emptied({ ...held, ...fresh });
656
+ const next = { ...held };
657
+ let changed = false;
658
+ for (const field of RefreshFields) {
659
+ if (field === "myReactions" && (pressed || fresh.myReactions === void 0)) continue;
660
+ if (deepEqual(normalized(field, held[field]), normalized(field, fresh[field]))) continue;
661
+ changed = true;
662
+ if (fresh[field] === void 0) delete next[field];
663
+ else next[field] = fresh[field];
664
+ }
665
+ return changed ? next : void 0;
666
+ }
667
+ function normalized(field, value) {
668
+ if (field === "reactions") {
669
+ return [...value ?? []].sort((a, b) => a.emoji < b.emoji ? -1 : a.emoji > b.emoji ? 1 : 0);
670
+ }
671
+ if (field === "myReactions") return [...value ?? []].sort();
672
+ if (field === "meta" || field === "appMeta") return value ?? {};
673
+ return value;
674
+ }
675
+ function deepEqual(a, b) {
676
+ if (a === b) return true;
677
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
678
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
679
+ const defined = (o) => Object.keys(o).filter((k) => o[k] !== void 0);
680
+ const ka = defined(a);
681
+ if (ka.length !== defined(b).length) return false;
682
+ return ka.every((k) => deepEqual(a[k], b[k]));
683
+ }
545
684
  function pairKey(messageId, emoji) {
546
685
  return `${messageId}\0${emoji}`;
547
686
  }
@@ -549,9 +688,192 @@ function createTimeline(options) {
549
688
  return new Timeline(options);
550
689
  }
551
690
 
691
+ // src/thread.ts
692
+ var Thread = class extends Emitter {
693
+ rootId;
694
+ /** The newest page has been read at least once (`load()`). */
695
+ loaded = false;
696
+ room;
697
+ /** @internal The replies. */
698
+ replies;
699
+ /** @internal The root, when the room's own list does not hold it (an old message). */
700
+ rootLine;
701
+ lastRoot;
702
+ markedSeq = 0;
703
+ closed = false;
704
+ /** Moves on `load()` and on `close()`; a read from before is dropped. */
705
+ generation = 0;
706
+ offRoom;
707
+ onClose;
708
+ /** @internal Made by `room.thread()`. */
709
+ constructor(room, rootId, onClose) {
710
+ super();
711
+ this.room = room;
712
+ this.rootId = rootId;
713
+ this.onClose = onClose;
714
+ this.replies = createTimeline({
715
+ fetchRange: ({ after, before, limit }) => room.history({ ...after > 0 ? { after } : {}, before, limit, view: { thread: rootId } }),
716
+ onChange: (messages) => this.emit("messages", messages)
717
+ });
718
+ this.rootLine = createTimeline({
719
+ // 루트 ν•œ 쀄은 읽어 올 길이 μ—†λ‹€(λ©”μ‹œμ§€ ν•˜λ‚˜λ₯Ό μ½λŠ” λΌμš°νŠΈκ°€ μ—†λ‹€). λ“€κ³ λ§Œ μžˆλŠ”λ‹€.
720
+ fetchRange: async () => [],
721
+ onChange: () => this.checkRoot()
722
+ });
723
+ this.offRoom = room.on("messages", () => this.checkRoot());
724
+ this.lastRoot = this.root;
725
+ }
726
+ /** The replies held, in seq order. Tombstones keep their place, as in `room.messages`. */
727
+ get messages() {
728
+ return this.replies.messages;
729
+ }
730
+ /**
731
+ * The root message: the room's own row when it holds it, or the copy passed
732
+ * to `room.thread(rootId, { root })`. Undefined when neither has it.
733
+ */
734
+ get root() {
735
+ return this.room.messages.find((m) => m.id === this.rootId) ?? this.rootLine.messages[0];
736
+ }
737
+ /** Whether `loadOlder()` would find more replies. False until `load()` and after a short page. */
738
+ get hasOlder() {
739
+ return this.replies.hasOlder;
740
+ }
741
+ /**
742
+ * Reads the newest page of replies and replaces what is held (replies that
743
+ * arrived live while it was in flight survive). Call it when the panel opens.
744
+ */
745
+ async load(options = {}) {
746
+ const gen = ++this.generation;
747
+ const limit = Math.min(options.limit ?? MaxPageSize, MaxPageSize);
748
+ const page = await this.room.history({ view: { thread: this.rootId }, limit });
749
+ if (gen !== this.generation || this.closed) return;
750
+ this.loaded = true;
751
+ this.replies.reset(page, { exhausted: page.length < limit });
752
+ }
753
+ /** Reads the page just above the oldest reply held and prepends it. Concurrent calls share one request. */
754
+ loadOlder(options = {}) {
755
+ return this.replies.loadOlder(options.limit);
756
+ }
757
+ /**
758
+ * Moves this user's read cursor for the thread to `seq` -- by default the
759
+ * newest reply held. Skips the frame when this handle already marked that
760
+ * far, so it can be called on every `messages` event.
761
+ */
762
+ async markRead(seq) {
763
+ const target = seq ?? this.messages.at(-1)?.seq ?? 0;
764
+ if (target <= this.markedSeq) return { seq: this.markedSeq, advanced: false };
765
+ const before = this.markedSeq;
766
+ this.markedSeq = target;
767
+ try {
768
+ return await this.room.markRead(target, { threadId: this.rootId });
769
+ } catch (err) {
770
+ if (this.markedSeq === target) this.markedSeq = before;
771
+ throw err;
772
+ }
773
+ }
774
+ /** Stops following the thread. `room.thread(rootId)` afterwards gives a new handle. */
775
+ close() {
776
+ if (this.closed) return;
777
+ this.closed = true;
778
+ this.generation++;
779
+ this.offRoom();
780
+ this.onClose(this);
781
+ this.dropRows();
782
+ }
783
+ /** @internal Applies a room event to the rows this thread holds. */
784
+ apply(type, data) {
785
+ switch (type) {
786
+ case "message.created": {
787
+ const m = data;
788
+ if (m.threadId === this.rootId) this.replies.put(m);
789
+ break;
790
+ }
791
+ case "message.updated":
792
+ this.replies.update(data);
793
+ this.rootLine.update(data);
794
+ break;
795
+ case "message.deleted": {
796
+ const id = data.id;
797
+ if (this.replies.has(id)) this.replies.remove(id);
798
+ if (this.rootLine.has(id)) this.rootLine.remove(id);
799
+ break;
800
+ }
801
+ case "thread.updated": {
802
+ const t = data;
803
+ if (t.rootId === this.rootId) this.rootLine.thread(t.rootId, t.count, t.lastSeq, t.lastAt);
804
+ break;
805
+ }
806
+ default:
807
+ break;
808
+ }
809
+ }
810
+ /** @internal Seeds the root copy (`room.thread(rootId, { root })`). */
811
+ seedRoot(root) {
812
+ if (root.id === this.rootId && !this.rootLine.has(root.id)) this.rootLine.put(root);
813
+ }
814
+ /**
815
+ * @internal
816
+ * After a reconnect: re-reads the newest page and merges it -- replies that
817
+ * arrived while away are added (a thread has no hole filling), held ones get
818
+ * their reactions, edits and deletes. Live frames that landed meanwhile win.
819
+ */
820
+ async sync(stillCurrent) {
821
+ if (!this.loaded || this.closed) return;
822
+ const gen = this.generation;
823
+ const handle = this.replies.beginRefresh();
824
+ try {
825
+ const page = await this.room.history({ view: { thread: this.rootId }, limit: MaxPageSize });
826
+ if (!stillCurrent() || gen !== this.generation || this.closed) return;
827
+ this.replies.applyRefresh(handle, page, { insertMissing: true });
828
+ } catch (err) {
829
+ if (stillCurrent() && !this.closed) this.emit("error", err instanceof Error ? err : new Error(String(err)));
830
+ } finally {
831
+ this.replies.endRefresh(handle);
832
+ }
833
+ }
834
+ /**
835
+ * @internal
836
+ * The user changed: the rows carried the previous user's `myReactions`.
837
+ * Dropped now; `reload()` reads them again once the room is back.
838
+ */
839
+ discard() {
840
+ this.reloadPending ||= this.loaded;
841
+ this.generation++;
842
+ this.dropRows();
843
+ }
844
+ /**
845
+ * @internal
846
+ * The room's list was rebuilt (`reset`): a thread that was showing is read
847
+ * again, since what it held may be gone from the room's retention or belong
848
+ * to the previous user.
849
+ */
850
+ reload() {
851
+ const wanted = this.reloadPending || this.loaded;
852
+ this.reloadPending = false;
853
+ if (!wanted || this.closed) return;
854
+ this.load().catch((err) => {
855
+ if (!this.closed) this.emit("error", err instanceof Error ? err : new Error(String(err)));
856
+ });
857
+ }
858
+ reloadPending = false;
859
+ dropRows() {
860
+ this.loaded = false;
861
+ this.markedSeq = 0;
862
+ this.replies.discard();
863
+ this.rootLine.discard();
864
+ }
865
+ checkRoot() {
866
+ const root = this.root;
867
+ if (root === this.lastRoot) return;
868
+ this.lastRoot = root;
869
+ this.emit("root", root);
870
+ }
871
+ };
872
+
552
873
  // src/room.ts
553
874
  var HistoryPageSize = 100;
554
875
  var TypingSendIntervalMs = 1e3;
876
+ var TypingTtlMs = 5e3;
555
877
  var MaxRepairs = 5;
556
878
  var RepairBaseMs = 1e3;
557
879
  var Room = class extends Emitter {
@@ -601,12 +923,27 @@ var Room = class extends Emitter {
601
923
  wanted = false;
602
924
  /** 신원이 λ°”λ€Œμ–΄ 버린 λͺ©λ‘μ„ λ‹€μŒ ꡬ독이 λ‹€μ‹œ μ±„μš°κ³  `reset`으둜 μ•Œλ €μ•Ό ν•œλ‹€. */
603
925
  rebuildPending = false;
926
+ /**
927
+ * The next successful catch-up follows a real reconnect, so the held rows
928
+ * get re-read (`refreshHeld`).
929
+ *
930
+ * Set by a restarting `resume`, cleared once the refresh was started or
931
+ * the timeline was rebuilt anyway, and **kept across a failed
932
+ * attempt**: the self-repair `subscribe()` that finally succeeds is still
933
+ * the one that follows the reconnect.
934
+ */
935
+ refreshPending = false;
604
936
  /** When `typing()` last tried to send (a closed socket still spends the window). See TypingSendIntervalMs. */
605
937
  typingSentAt = Number.NEGATIVE_INFINITY;
606
938
  subscribing;
607
939
  /** Self-repair: the armed retry, and how many have run since the last success. */
608
940
  repairTimer;
609
941
  repairs = 0;
942
+ /** Open thread handles by root id (`thread()`). */
943
+ threads = /* @__PURE__ */ new Map();
944
+ /** Who is typing, by `<threadId>|<userId>` (empty threadId: the main timeline). */
945
+ typers = /* @__PURE__ */ new Map();
946
+ typingTimer;
610
947
  constructor(chat, rest, address) {
611
948
  super();
612
949
  this.chat = chat;
@@ -637,6 +974,73 @@ var Room = class extends Emitter {
637
974
  get messages() {
638
975
  return this.timeline.messages;
639
976
  }
977
+ /**
978
+ * A handle on one thread's replies -- what a thread panel draws.
979
+ *
980
+ * Cached per root id until `thread.close()`. Call `thread.load()` to read
981
+ * the newest replies; from then on new replies, reactions (including this
982
+ * client's optimistic `myReactions`), edits and deletes reach its rows like
983
+ * they reach `room.messages`, and a reconnect re-reads its newest page.
984
+ *
985
+ * `root` seeds `thread.root` for a root the room's list does not hold (an
986
+ * old message opened from search or a link). Without it `thread.root` is the
987
+ * room's own row, or undefined.
988
+ */
989
+ thread(rootId, options = {}) {
990
+ let thread = this.threads.get(rootId);
991
+ if (thread === void 0) {
992
+ thread = new Thread(this, rootId, (t) => {
993
+ if (this.threads.get(rootId) === t) this.threads.delete(rootId);
994
+ });
995
+ this.threads.set(rootId, thread);
996
+ }
997
+ if (options.root !== void 0) thread.seedRoot(options.root);
998
+ return thread;
999
+ }
1000
+ /**
1001
+ * Who is typing right now in one place: the main timeline, or the thread
1002
+ * whose root is `threadId`. User ids, oldest signal first, **without this
1003
+ * client's own user**. Someone drops out five seconds after their last
1004
+ * signal, or as soon as their message arrives. `typing.changed` fires
1005
+ * whenever this changes.
1006
+ */
1007
+ typists(options = {}) {
1008
+ const now = Date.now();
1009
+ const scope = options.threadId ?? "";
1010
+ const out = [];
1011
+ for (const t of this.typers.values()) {
1012
+ if ((t.threadId ?? "") === scope && now - t.at < TypingTtlMs) out.push(t.userId);
1013
+ }
1014
+ return out;
1015
+ }
1016
+ /**
1017
+ * Edits one of this user's own messages. The server allows only the
1018
+ * sender, within the app's edit window, and answers `forbidden` otherwise.
1019
+ *
1020
+ * The body is **replaced**: pass `attachments` (and `entities`) back to keep
1021
+ * them. The returned row is applied to `messages` (and an open thread) right
1022
+ * away; the `message.updated` broadcast that follows changes nothing more.
1023
+ */
1024
+ async edit(messageId, input) {
1025
+ const body = {};
1026
+ if (input.text !== void 0) body["text"] = input.text;
1027
+ if (input.entities !== void 0) body["entities"] = input.entities;
1028
+ if (input.attachments !== void 0) body["attachments"] = input.attachments;
1029
+ const row = await this.rest.patch(`/v1/rooms/${await this.resolveId("editing")}/messages/${messageId}`, { body });
1030
+ this.timeline.update(row);
1031
+ for (const t of this.threads.values()) t.apply("message.updated", row);
1032
+ return row;
1033
+ }
1034
+ /**
1035
+ * Deletes a message: this user's own, or anyone's for the room's owner and
1036
+ * admins. Idempotent. The row becomes a tombstone in `messages` (and an
1037
+ * open thread) right away.
1038
+ */
1039
+ async delete(messageId) {
1040
+ await this.rest.delete(`/v1/rooms/${await this.resolveId("deleting")}/messages/${messageId}`);
1041
+ if (this.timeline.has(messageId)) this.timeline.remove(messageId);
1042
+ for (const t of this.threads.values()) t.apply("message.deleted", { id: messageId });
1043
+ }
640
1044
  /**
641
1045
  * Reads the page just before the oldest message held and **prepends it to
642
1046
  * `messages`**.
@@ -655,18 +1059,22 @@ var Room = class extends Emitter {
655
1059
  return this.timeline.loadOlder(options.limit);
656
1060
  }
657
1061
  /**
658
- * Reloads recent history, discarding what is held.
659
- *
660
- * A reconnect recovers the **message timeline** and nothing else: the
661
- * only history route is `GET .../messages`, and reactions, thread
662
- * counts, read cursors, membership and room metadata ride along only
663
- * for the rows that page happens to contain. So a reaction added to an
664
- * older message while this client was away is never seen, and no
665
- * amount of gap filling will find it.
666
- *
667
- * The SDK does not hide that behind a background refresh, because the
668
- * refresh would have to be either wasteful or wrong. It gives the
669
- * consumer the one honest tool -- ask again -- and says when to use it.
1062
+ * Reloads recent history, replacing what is held.
1063
+ *
1064
+ * A reconnect already brings the held rows up to date by itself: after
1065
+ * the catch-up it re-reads the newest page (one `GET .../messages`,
1066
+ * `limit=100`) and **merges** it into the rows it holds -- reactions,
1067
+ * `myReactions`, thread counts, edits and deletes that happened while
1068
+ * the socket was away -- see `refreshHeld`. Reactions, thread counts and
1069
+ * the like ride on history rows only, and no event replays them, so
1070
+ * without that read nothing would ever show them. Rows **older than the
1071
+ * newest page** are not re-read; they stay as they were until
1072
+ * `reload()`/`loadOlder()` or the next event for them.
1073
+ *
1074
+ * `reload()` is the manual version and a stronger one: it **replaces**
1075
+ * the list with the newest page (rows newer than the page survive) and
1076
+ * drops older pages loaded with `loadOlder()`. Use it for "refresh"
1077
+ * buttons, or after anything the reconnect refresh does not cover.
670
1078
  */
671
1079
  async reload() {
672
1080
  const gen = this.generation;
@@ -717,22 +1125,70 @@ var Room = class extends Emitter {
717
1125
  await this.loadRecent(current);
718
1126
  if (!current()) return;
719
1127
  this.rebuildPending = false;
1128
+ this.refreshPending = false;
720
1129
  this.subscribed = true;
721
1130
  this.emit("reset", this.timeline.messages);
1131
+ for (const t of this.threads.values()) t.reload();
722
1132
  return;
723
1133
  }
724
1134
  if (since > 0) {
725
1135
  await this.timeline.catchUp(ack.lastSeq);
726
1136
  if (!current()) return;
727
1137
  this.subscribed = true;
1138
+ if (this.refreshPending) {
1139
+ this.refreshPending = false;
1140
+ void this.refreshHeld(current);
1141
+ }
728
1142
  return;
729
1143
  }
730
1144
  if (ack.lastSeq > 0) {
731
1145
  await this.loadRecent(current);
732
1146
  }
733
1147
  if (!current()) return;
1148
+ this.refreshPending = false;
734
1149
  this.subscribed = true;
735
1150
  }
1151
+ /**
1152
+ * Re-reads the newest page and merges it into the rows already held.
1153
+ *
1154
+ * What a reconnect's catch-up cannot bring: it fetches rows this client
1155
+ * does not have, and a reaction, a thread count, an edit or a delete that
1156
+ * happened to a row it **does** have rides on no event it will see. One
1157
+ * `GET .../messages?limit=100` per reconnect, so the newest 100 rows of
1158
+ * the room are refreshed and anything older is not -- that is the bound
1159
+ * on the cost, and it is the part of the room people are looking at.
1160
+ * Thread replies live in the same timeline, so they and their roots come
1161
+ * along.
1162
+ *
1163
+ * It is a merge (`Timeline.applyRefresh`): no `reset`, no rows dropped,
1164
+ * older pages from `loadOlder()` untouched, and a row a live frame or a
1165
+ * press changed after the read began is left to that newer value. A row
1166
+ * that changed raises `message.updated`, a row now deleted raises
1167
+ * `message.deleted`, as the live frames would.
1168
+ *
1169
+ * **Failure is background and local**: an `error` event, no repair loop
1170
+ * (the live feed is fine and the next reconnect tries again), and the
1171
+ * room stays subscribed. A refresh from before another reconnect, a
1172
+ * reset or an unsubscribe is discarded (`stillCurrent`, the generation).
1173
+ */
1174
+ async refreshHeld(stillCurrent) {
1175
+ for (const t of this.threads.values()) void t.sync(stillCurrent);
1176
+ if (this.timeline.messages.length === 0) return;
1177
+ const handle = this.timeline.beginRefresh();
1178
+ try {
1179
+ const page = await this.rest.get(`/v1/rooms/${this.requireId("refreshing history")}/messages`, {
1180
+ limit: HistoryPageSize
1181
+ });
1182
+ if (!stillCurrent()) return;
1183
+ const { updated, deleted } = this.timeline.applyRefresh(handle, page.messages);
1184
+ for (const m of updated) this.emit("message.updated", m);
1185
+ for (const m of deleted) this.emit("message.deleted", { id: m.id, seq: m.seq });
1186
+ } catch (err) {
1187
+ if (stillCurrent()) this.emit("error", err instanceof Error ? err : new Error(String(err)));
1188
+ } finally {
1189
+ this.timeline.endRefresh(handle);
1190
+ }
1191
+ }
736
1192
  /**
737
1193
  * Reads a page of history directly, without touching `messages`.
738
1194
  *
@@ -788,7 +1244,8 @@ var Room = class extends Emitter {
788
1244
  * 두고 λ‚˜μ˜¨λ‹€(`Timeline.settleReaction`).
789
1245
  */
790
1246
  async toggleReaction(messageId, emoji, mine) {
791
- const press = this.timeline.pressReaction(messageId, emoji, mine);
1247
+ const lines = [this.timeline, ...this.sideLines()];
1248
+ const presses = lines.map((line) => line.pressReaction(messageId, emoji, mine));
792
1249
  const owner = this.chat.user?.id;
793
1250
  try {
794
1251
  await this.chat.sendFrame("react", {
@@ -798,11 +1255,22 @@ var Room = class extends Emitter {
798
1255
  op: mine ? "add" : "remove"
799
1256
  }, void 0, { resendOnDrop: true, owner });
800
1257
  } catch (err) {
801
- if (press !== void 0) this.timeline.settleReaction(press, false);
1258
+ presses.forEach((press, i) => {
1259
+ if (press !== void 0) lines[i].settleReaction(press, false);
1260
+ });
802
1261
  throw err;
803
1262
  }
804
- if (press !== void 0) this.timeline.settleReaction(press, true);
805
- else this.timeline.reaction(messageId, emoji, void 0, mine);
1263
+ presses.forEach((press, i) => {
1264
+ const line = lines[i];
1265
+ if (press !== void 0) line.settleReaction(press, true);
1266
+ else line.reaction(messageId, emoji, void 0, mine);
1267
+ });
1268
+ }
1269
+ /** The lists open threads hold beside the room's own: their replies and root copies. */
1270
+ sideLines() {
1271
+ const out = [];
1272
+ for (const t of this.threads.values()) out.push(t.replies, t.rootLine);
1273
+ return out;
806
1274
  }
807
1275
  /**
808
1276
  * Moves this user's read cursor.
@@ -813,9 +1281,12 @@ var Room = class extends Emitter {
813
1281
  */
814
1282
  async markRead(seq, options = {}) {
815
1283
  const owner = this.chat.user?.id;
816
- const data = { roomId: await this.resolveId("marking read"), seq };
1284
+ const roomId = await this.resolveId("marking read");
1285
+ const data = { roomId, seq };
817
1286
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
818
- return await this.chat.sendFrame("read", data, void 0, { resendOnDrop: true, owner });
1287
+ const ack = await this.chat.sendFrame("read", data, void 0, { resendOnDrop: true, owner });
1288
+ if (options.threadId === void 0) this.chat.noteRead(roomId, seq);
1289
+ return ack;
819
1290
  }
820
1291
  /**
821
1292
  * Lists read cursors in this room, one page at a time.
@@ -927,8 +1398,11 @@ var Room = class extends Emitter {
927
1398
  * page.
928
1399
  */
929
1400
  async resume(restart = true, userChanged = false) {
1401
+ if (restart && !userChanged && this.wanted) this.refreshPending = true;
930
1402
  if (userChanged) {
1403
+ this.refreshPending = false;
931
1404
  this.timeline.discard();
1405
+ for (const t of this.threads.values()) t.discard();
932
1406
  if (this.wanted) this.rebuildPending = true;
933
1407
  }
934
1408
  if (!this.wanted) return;
@@ -984,8 +1458,10 @@ var Room = class extends Emitter {
984
1458
  this.wanted = false;
985
1459
  this.subscribed = false;
986
1460
  this.rebuildPending = false;
1461
+ this.refreshPending = this.timeline.messages.length > 0 || this.threads.size > 0;
987
1462
  this.generation++;
988
1463
  this.subscribing = void 0;
1464
+ this.clearTypists();
989
1465
  await this.chat.sendFrame("unsubscribe", { roomId: this.id }, void 0, { wait: false });
990
1466
  }
991
1467
  /**
@@ -1060,6 +1536,7 @@ var Room = class extends Emitter {
1060
1536
  const me = this.chat.user?.id;
1061
1537
  const mine = me !== void 0 && r.userId === me ? type === "reaction.added" : void 0;
1062
1538
  this.timeline.reaction(r.messageId, r.emoji, r.count, mine);
1539
+ for (const line of this.sideLines()) line.reaction(r.messageId, r.emoji, r.count, mine);
1063
1540
  break;
1064
1541
  }
1065
1542
  case "thread.updated": {
@@ -1073,7 +1550,57 @@ var Room = class extends Emitter {
1073
1550
  default:
1074
1551
  break;
1075
1552
  }
1553
+ for (const t of this.threads.values()) t.apply(type, data);
1076
1554
  this.emit(type, data);
1555
+ if (type === "typing") this.noteTyping(data);
1556
+ else if (type === "message.created") {
1557
+ const m = data;
1558
+ if (m.sender !== void 0) this.dropTypist(m.sender.id, m.threadId);
1559
+ }
1560
+ }
1561
+ noteTyping(ev) {
1562
+ if (ev.userId === this.chat.user?.id) return;
1563
+ const key = `${ev.threadId ?? ""}|${ev.userId}`;
1564
+ const held = this.typers.get(key);
1565
+ if (held !== void 0) held.at = Date.now();
1566
+ else this.typers.set(key, { userId: ev.userId, ...ev.threadId === void 0 ? {} : { threadId: ev.threadId }, at: Date.now() });
1567
+ if (held === void 0) this.emitTypists(ev.threadId);
1568
+ this.armTypingTimer();
1569
+ }
1570
+ dropTypist(userId, threadId) {
1571
+ if (this.typers.delete(`${threadId ?? ""}|${userId}`)) this.emitTypists(threadId);
1572
+ }
1573
+ emitTypists(threadId) {
1574
+ const userIds = this.typists(threadId === void 0 ? {} : { threadId });
1575
+ this.emit("typing.changed", threadId === void 0 ? { userIds } : { threadId, userIds });
1576
+ }
1577
+ /** One timer for the earliest expiry; re-armed after it fires. */
1578
+ armTypingTimer() {
1579
+ if (this.typingTimer !== void 0) clearTimeout(this.typingTimer);
1580
+ this.typingTimer = void 0;
1581
+ let earliest = Number.POSITIVE_INFINITY;
1582
+ for (const t of this.typers.values()) earliest = Math.min(earliest, t.at);
1583
+ if (earliest === Number.POSITIVE_INFINITY) return;
1584
+ this.typingTimer = setTimeout(() => {
1585
+ this.typingTimer = void 0;
1586
+ const now = Date.now();
1587
+ const scopes = /* @__PURE__ */ new Set();
1588
+ for (const [key, t] of this.typers) {
1589
+ if (now - t.at < TypingTtlMs) continue;
1590
+ this.typers.delete(key);
1591
+ scopes.add(t.threadId);
1592
+ }
1593
+ for (const scope of scopes) this.emitTypists(scope);
1594
+ this.armTypingTimer();
1595
+ }, Math.max(0, earliest + TypingTtlMs - Date.now()));
1596
+ this.typingTimer.unref?.();
1597
+ }
1598
+ clearTypists() {
1599
+ const scopes = new Set([...this.typers.values()].map((t) => t.threadId));
1600
+ this.typers.clear();
1601
+ if (this.typingTimer !== void 0) clearTimeout(this.typingTimer);
1602
+ this.typingTimer = void 0;
1603
+ for (const scope of scopes) this.emitTypists(scope);
1077
1604
  }
1078
1605
  /**
1079
1606
  * Replaces the timeline with the most recent page.
@@ -1113,6 +1640,158 @@ function newClientMessageId() {
1113
1640
  return `cm-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
1114
1641
  }
1115
1642
 
1643
+ // src/rooms.ts
1644
+ var PageSize = 100;
1645
+ var MaxPages = 10;
1646
+ var RoomList = class extends Emitter {
1647
+ /** At least one `load()` finished. */
1648
+ loaded = false;
1649
+ list = [];
1650
+ pager;
1651
+ loading;
1652
+ again = false;
1653
+ /** @internal Made by `chat.roomList()`. */
1654
+ constructor(pager) {
1655
+ super();
1656
+ this.pager = pager;
1657
+ }
1658
+ /** The rooms, as of the last change. A new array whenever it changes. */
1659
+ get rooms() {
1660
+ return this.list;
1661
+ }
1662
+ get(roomId) {
1663
+ return this.list.find((r) => r.id === roomId);
1664
+ }
1665
+ /**
1666
+ * Reads the list from the server and replaces what is held. A call while
1667
+ * one is in flight runs once more after it, so the last answer is never
1668
+ * older than the last call.
1669
+ */
1670
+ load() {
1671
+ if (this.loading !== void 0) {
1672
+ this.again = true;
1673
+ return this.loading;
1674
+ }
1675
+ this.loading = this.readAll().catch((err) => {
1676
+ this.emit("error", err instanceof Error ? err : new Error(String(err)));
1677
+ throw err;
1678
+ }).finally(() => {
1679
+ this.loading = void 0;
1680
+ if (this.again) {
1681
+ this.again = false;
1682
+ void this.load().catch(() => {
1683
+ });
1684
+ }
1685
+ });
1686
+ return this.loading;
1687
+ }
1688
+ async readAll() {
1689
+ const rows = [];
1690
+ let cursor;
1691
+ for (let page = 0; page < MaxPages; page++) {
1692
+ const res = await this.pager(cursor === void 0 ? { limit: PageSize } : { cursor, limit: PageSize });
1693
+ for (const r of res.rooms ?? []) rows.push(summaryOf(r));
1694
+ if (!res.cursor) break;
1695
+ cursor = res.cursor;
1696
+ }
1697
+ this.loaded = true;
1698
+ this.set(rows);
1699
+ }
1700
+ /** @internal `notification.message`. */
1701
+ notification(raw) {
1702
+ const n = raw ?? {};
1703
+ if (!this.loaded || typeof n.roomId !== "string") return;
1704
+ const held = this.get(n.roomId);
1705
+ if (held === void 0) {
1706
+ void this.load().catch(() => {
1707
+ });
1708
+ return;
1709
+ }
1710
+ this.patch(n.roomId, (r) => ({
1711
+ ...r,
1712
+ unread: typeof n.unread === "number" ? n.unread : r.unread + 1,
1713
+ mentions: typeof n.unreadMentions === "number" ? n.unreadMentions : r.mentions,
1714
+ ...n.unreadCapped === true ? { unreadCapped: true } : {},
1715
+ lastSeq: Math.max(r.lastSeq, typeof n.seq === "number" ? n.seq : 0)
1716
+ }));
1717
+ }
1718
+ /** @internal A frame from a subscribed room. */
1719
+ roomEvent(roomId, type, data, me) {
1720
+ if (!this.loaded) return;
1721
+ switch (type) {
1722
+ case "message.created": {
1723
+ const seq = data.seq;
1724
+ if (typeof seq === "number") this.patch(roomId, (r) => seq > r.lastSeq ? { ...r, lastSeq: seq } : r);
1725
+ break;
1726
+ }
1727
+ case "room.updated": {
1728
+ const room = data;
1729
+ if (room?.id === roomId) this.patch(roomId, (r) => ({ ...r, room: { ...r.room, ...room } }));
1730
+ break;
1731
+ }
1732
+ case "room.deleted":
1733
+ this.drop(roomId);
1734
+ break;
1735
+ case "member.left":
1736
+ if (me !== void 0 && data.userId === me) this.drop(roomId);
1737
+ break;
1738
+ default:
1739
+ break;
1740
+ }
1741
+ }
1742
+ /** @internal This client moved its main-timeline read cursor. */
1743
+ read(roomId, seq) {
1744
+ this.patch(roomId, (r) => {
1745
+ const readSeq = Math.max(r.readSeq, seq);
1746
+ if (readSeq >= r.lastSeq) return { ...r, readSeq, unread: 0, mentions: 0 };
1747
+ return readSeq === r.readSeq ? r : { ...r, readSeq };
1748
+ });
1749
+ }
1750
+ /** @internal This client renamed or deleted a room through `chat.rooms`. */
1751
+ updated(room) {
1752
+ this.roomEvent(room.id, "room.updated", room, void 0);
1753
+ }
1754
+ /** @internal */
1755
+ drop(roomId) {
1756
+ if (!this.list.some((r) => r.id === roomId)) return;
1757
+ this.set(this.list.filter((r) => r.id !== roomId));
1758
+ }
1759
+ /** @internal The user changed: the counts were the previous user's. */
1760
+ forget() {
1761
+ const had = this.loaded;
1762
+ this.loaded = false;
1763
+ this.set([]);
1764
+ if (had) void this.load().catch(() => {
1765
+ });
1766
+ }
1767
+ patch(roomId, fn) {
1768
+ const at = this.list.findIndex((r) => r.id === roomId);
1769
+ if (at === -1) return;
1770
+ const next = fn(this.list[at]);
1771
+ if (next === this.list[at]) return;
1772
+ const list = this.list.slice();
1773
+ list[at] = next;
1774
+ this.set(list);
1775
+ }
1776
+ set(list) {
1777
+ this.list = list;
1778
+ this.emit("rooms", list);
1779
+ }
1780
+ };
1781
+ function summaryOf(r) {
1782
+ const s = {
1783
+ id: r.room.id,
1784
+ room: r.room,
1785
+ lastSeq: r.lastSeq ?? r.room.lastSeq ?? 0,
1786
+ readSeq: r.readSeq ?? 0,
1787
+ unread: r.unread ?? 0,
1788
+ mentions: r.unreadMentions ?? 0
1789
+ };
1790
+ if (r.unreadCapped === true) s.unreadCapped = true;
1791
+ if (r.lastMessage !== void 0) s.lastMessage = r.lastMessage;
1792
+ return s;
1793
+ }
1794
+
1116
1795
  // src/client.ts
1117
1796
  var MinBackoffMs = 500;
1118
1797
  var MaxBackoffMs = 3e4;
@@ -1196,6 +1875,11 @@ var ChatClient = class extends Emitter {
1196
1875
  };
1197
1876
  window.addEventListener("online", onOnline);
1198
1877
  this.teardowns.push(() => window.removeEventListener("online", onOnline));
1878
+ const onPageShow = (ev) => {
1879
+ if (ev.persisted === true) void this.resume();
1880
+ };
1881
+ window.addEventListener("pageshow", onPageShow);
1882
+ this.teardowns.push(() => window.removeEventListener("pageshow", onPageShow));
1199
1883
  }
1200
1884
  }
1201
1885
  /**
@@ -1245,6 +1929,13 @@ var ChatClient = class extends Emitter {
1245
1929
  for (const room of this.handles.values()) {
1246
1930
  void room.resume().catch((err) => room.failed(err));
1247
1931
  }
1932
+ this.cameBack(false);
1933
+ }
1934
+ /** `resumed`, after the rooms were told. The live room list reloads first. */
1935
+ cameBack(reconnected) {
1936
+ if (this.list?.loaded === true) void this.list.load().catch(() => {
1937
+ });
1938
+ this.emit("resumed", { reconnected });
1248
1939
  }
1249
1940
  /**
1250
1941
  * Pings `socket` and resolves whether any frame came back within
@@ -1280,6 +1971,18 @@ var ChatClient = class extends Emitter {
1280
1971
  return {
1281
1972
  list: (options) => this.rest.get("/v1/me/rooms", { cursor: options?.cursor, limit: options?.limit }),
1282
1973
  discover: (options) => this.rest.get("/v1/rooms", { type: options?.type, cursor: options?.cursor, limit: options?.limit }),
1974
+ // λ°©μž₯Β·κ΄€λ¦¬μžλ§Œ λœλ‹€(μ•„λ‹ˆλ©΄ forbidden). 바뀐 방은 κ΅¬λ…μž λͺ¨λ‘μ—κ²Œ
1975
+ // `room.updated`둜 κ°„λ‹€. keyλŠ” λ°±μ—”λ“œ(sk_)κ°€ μ •ν•˜λŠ” 것이라 λ°›μ§€ μ•ŠλŠ”λ‹€.
1976
+ // κ΅¬λ…ν•˜μ§€ μ•Šμ€ 방은 κ·Έ μ΄λ²€νŠΈκ°€ μ•ˆ μ˜€λ―€λ‘œ μ‚΄μ•„ μžˆλŠ” λ°© λͺ©λ‘μ€ μ‘λ‹΅μœΌλ‘œ κ³ μΉœλ‹€.
1977
+ update: async (roomId, patch) => {
1978
+ const room = await this.rest.patch(`/v1/rooms/${roomId}`, patch);
1979
+ this.list?.updated(room);
1980
+ return room;
1981
+ },
1982
+ delete: async (roomId) => {
1983
+ await this.rest.delete(`/v1/rooms/${roomId}`);
1984
+ this.list?.drop(roomId);
1985
+ },
1283
1986
  members: (roomId) => ({
1284
1987
  list: (options) => this.rest.get(`/v1/rooms/${roomId}/members`, { cursor: options?.cursor, limit: options?.limit }),
1285
1988
  add: async (userId, role) => {
@@ -1327,6 +2030,19 @@ var ChatClient = class extends Emitter {
1327
2030
  async updateMe(meta) {
1328
2031
  return this.rest.patch("/v1/me", { meta });
1329
2032
  }
2033
+ /**
2034
+ * The rooms this user is in, with unread counts the SDK keeps current --
2035
+ * see `RoomList`. One per client; call `load()` once to fill it.
2036
+ */
2037
+ roomList() {
2038
+ this.list ??= new RoomList((options) => this.rooms.list(options));
2039
+ return this.list;
2040
+ }
2041
+ list;
2042
+ /** @internal `room.markRead()` on a main timeline went through. */
2043
+ noteRead(roomId, seq) {
2044
+ this.list?.read(roomId, seq);
2045
+ }
1330
2046
  /**
1331
2047
  * A handle on a room by id.
1332
2048
  *
@@ -1691,11 +2407,13 @@ var ChatClient = class extends Emitter {
1691
2407
  this.everOpened = true;
1692
2408
  this.setState("open");
1693
2409
  this.settleOpenWaiters();
2410
+ if (userChanged) this.list?.forget();
1694
2411
  for (const room of this.handles.values()) {
1695
2412
  void room.resume(reconnected, userChanged).catch((err) => {
1696
2413
  room.failed(err);
1697
2414
  });
1698
2415
  }
2416
+ if (reconnected && !userChanged) this.cameBack(true);
1699
2417
  }
1700
2418
  onFrame(frame) {
1701
2419
  if (frame.id !== void 0) {
@@ -1739,6 +2457,7 @@ var ChatClient = class extends Emitter {
1739
2457
  return;
1740
2458
  }
1741
2459
  if (event === "notification.message") {
2460
+ this.list?.notification(push?.data);
1742
2461
  this.emit("notification", push?.data);
1743
2462
  return;
1744
2463
  }
@@ -1752,6 +2471,7 @@ var ChatClient = class extends Emitter {
1752
2471
  return;
1753
2472
  }
1754
2473
  room.handle(event, push?.data);
2474
+ if (push?.roomId !== void 0) this.list?.roomEvent(push.roomId, event, push?.data, this.user?.id);
1755
2475
  }
1756
2476
  plannedDelayMs;
1757
2477
  // When a server-directed delay (drain, rate limit) ends; a send does not cut it short.
@@ -1844,10 +2564,87 @@ function isChatError(err) {
1844
2564
  function createChatClient(options) {
1845
2565
  return new ChatClient(options);
1846
2566
  }
2567
+
2568
+ // src/mentions.ts
2569
+ var MaxEntities = 100;
2570
+ var NameChar = /[\p{L}\p{N}_]/u;
2571
+ function buildMentions(text, people, options = {}) {
2572
+ if (!text.includes("@")) return [];
2573
+ const groups = /* @__PURE__ */ new Map();
2574
+ for (const p of people) {
2575
+ if (!p.id || !p.name) continue;
2576
+ const ids = groups.get(p.name) ?? [];
2577
+ if (!ids.includes(p.id)) groups.set(p.name, [...ids, p.id]);
2578
+ }
2579
+ if (groups.size === 0) return [];
2580
+ const names = [...groups.keys()].sort((a, b) => b.length - a.length);
2581
+ const code = options.skipCode === false ? [] : codeRanges(text);
2582
+ const used = /* @__PURE__ */ new Map();
2583
+ const out = [];
2584
+ for (let i = text.indexOf("@"); i >= 0 && out.length < MaxEntities; i = text.indexOf("@", i + 1)) {
2585
+ if (i > 0 && /[\p{L}\p{N}_.@]/u.test(text[i - 1])) continue;
2586
+ if (code.some(([s, e]) => i >= s && i < e)) continue;
2587
+ const name = names.find((n2) => {
2588
+ if (!text.startsWith(n2, i + 1)) return false;
2589
+ const next = text[i + 1 + n2.length];
2590
+ return next === void 0 || !NameChar.test(next);
2591
+ });
2592
+ if (name === void 0) continue;
2593
+ const n = used.get(name) ?? 0;
2594
+ const ids = groups.get(name);
2595
+ if (n >= ids.length && ids.length > 1) continue;
2596
+ used.set(name, n + 1);
2597
+ out.push({ type: "mention", userId: ids[Math.min(n, ids.length - 1)], offset: i, length: name.length + 1 });
2598
+ }
2599
+ return out;
2600
+ }
2601
+ function mentionSpans(text, entities) {
2602
+ if (!Array.isArray(entities) || !text) return [];
2603
+ const out = [];
2604
+ for (const raw of entities.slice(0, MaxEntities)) {
2605
+ const e = raw;
2606
+ if (e === null || typeof e !== "object" || e.type !== "mention" || typeof e.userId !== "string" || !e.userId) continue;
2607
+ const { offset, length } = e;
2608
+ if (!Number.isInteger(offset) || !Number.isInteger(length)) continue;
2609
+ const start = offset;
2610
+ const end = start + length;
2611
+ if (start < 0 || length < 2 || end > text.length) continue;
2612
+ if (text[start] !== "@" || text.slice(start, end).includes("\n")) continue;
2613
+ out.push({ start, end, userId: e.userId });
2614
+ }
2615
+ out.sort((a, b) => a.start - b.start);
2616
+ const kept = [];
2617
+ for (const s of out) if (kept.length === 0 || s.start >= kept.at(-1).end) kept.push(s);
2618
+ return kept;
2619
+ }
2620
+ function codeRanges(text) {
2621
+ const out = [];
2622
+ let pos = 0;
2623
+ let open = -1;
2624
+ for (const line of text.split("\n")) {
2625
+ const end = pos + line.length;
2626
+ if (/^\s{0,3}```/.test(line)) {
2627
+ if (open < 0) open = pos;
2628
+ else {
2629
+ out.push([open, end]);
2630
+ open = -1;
2631
+ }
2632
+ } else if (open < 0) {
2633
+ for (const m of line.matchAll(/`[^`\n]+`/g)) out.push([pos + m.index, pos + m.index + m[0].length]);
2634
+ }
2635
+ pos = end + 1;
2636
+ }
2637
+ if (open >= 0) out.push([open, text.length]);
2638
+ return out;
2639
+ }
1847
2640
  export {
1848
2641
  ChatClient,
1849
2642
  ChatEndpoint,
1850
2643
  ChatError,
1851
2644
  Room,
1852
- createChatClient
2645
+ RoomList,
2646
+ Thread,
2647
+ buildMentions,
2648
+ createChatClient,
2649
+ mentionSpans
1853
2650
  };