@kispi/chat 0.4.0 → 0.5.1

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/README.en.md CHANGED
@@ -70,21 +70,21 @@ off()
70
70
 
71
71
  | Property | |
72
72
  |---|---|
73
- | `messages` | Ascending by seq. **The SDK handles ordering and gap filling.** A new array on every change |
73
+ | `messages` | Ascending by seq. **The SDK handles ordering and gap filling.** A new array on every change. **Thread replies are included** (rows with a `threadId`) — to draw the main timeline only, keep the rows without one |
74
74
  | `id` / `key` | Room identifiers. If opened by key, `id` is absent until you subscribe |
75
75
  | `lastSeq` | The room's last seq as reported by the server |
76
- | `presence` | `{count, users?, capped?}` |
76
+ | `presence` | `{count, users?, capped?}` — who is in this room now. **The SDK folds** the subscribe ack and the increments of `presence` events into it. `users` is there **only for rooms of 100 or fewer**; larger, or unknown, it is absent — use `presenceList()` then |
77
77
  | `hasOlder` | Whether `loadOlder()` has more past to read. Lets you decide whether to draw "load earlier" before the first `loadOlder()`. The same test as `loadOlder()`'s `hasMore`; `false` while the list is empty. Re-read it on `messages` |
78
78
 
79
79
  | Method | |
80
80
  |---|---|
81
81
  | `subscribe()` | Turns on the live feed and reads the latest 100. Does nothing if already caught up. **Fine to call before connecting** — it waits until connected (rejects with `closed` on `close()`) |
82
82
  | `unsubscribe()` | Stops viewing this room. It is not resubscribed on reconnect |
83
- | `send({text, attachments?, entities?, replyTo?, threadId?, meta?}, {clientMessageId?})` | Publish. Acked with `{messageId, seq}`. If a subscription is in progress, it waits for it |
83
+ | `send({text, attachments?, entities?, replyTo?, threadId?, meta?}, {clientMessageId?})` | Publish. Acked with `{messageId, seq}`. If a subscription is in progress, it waits for it. **While reconnecting it waits for the connection, then sends** (below) |
84
84
  | `loadOlder({limit?})` | Reads the page before the oldest message (default 100) and **prepends it to `messages`.** Returns `{messages, hasMore}`. Use it when scrolling up. If the list is empty (before subscribing), it reads nothing |
85
85
  | `history({before?, after?, limit?, view?})` | Reads the past directly. **Independent of `messages`.** `view` is `'main'`, `'all'`, or `{thread: id}` |
86
86
  | `reload()` | Re-reads the latest page |
87
- | `react(messageId, emoji)` / `unreact(...)` | Reactions. Idempotent. Updates that row's `myReactions` **before the frame goes out**, and rolls it back if the server refuses. Never touches the count |
87
+ | `react(messageId, emoji)` / `unreact(...)` | Reactions. Idempotent. Updates that row's `myReactions` **before the frame goes out**, and rolls it back if the server refuses. The count is not moved optimistically; **it is set to the server's value when the `reaction.*` event arrives** (below) |
88
88
  | `reactionsOf(messageId, {emoji?, cursor?, limit?})` | Who reacted. **Each row is a (user, emoji) pair**, so one person can appear on several rows. `limit` defaults to 50, max 100; the last page's `cursor` is an empty string |
89
89
  | `markRead(seq, {threadId?})` | Read cursor |
90
90
  | `reads({userId?, cursor?, limit?})` | Read cursors, paged. `{reads: [{userId?, seq, threadId?, withdrawn?}], cursor}`. **`userId` narrows to one person** -- `reads({userId: chat.user.id})` recovers your own per-thread cursors. Stop when `cursor` is `''` |
@@ -98,7 +98,7 @@ Event names are **exactly the wire names**, and the payloads are in the type dec
98
98
  |---|---|
99
99
  | `message.created` / `message.updated` | `Message`. On `created`, `thread` is absent and `reactions` is empty |
100
100
  | `message.deleted` | `{id, seq}`. `seq` is the one the message got **when it was published** |
101
- | `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}` |
101
+ | `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}`. The SDK has already updated that row's `reactions` count in `messages` (and `myReactions` if it was yours). **Rows outside the list**, such as ones read with `history()`, are the consumer's to update |
102
102
  | `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
103
103
  | `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left` are incremental, `users` replaces |
104
104
  | `typing` | `{userId, threadId?}` -- `threadId` is the thread **root** id, absent for the main timeline |
@@ -140,8 +140,27 @@ room.on('messages', m => (messages.value = m))
140
140
  - **Attach the past to the same list with `loadOlder()`.** `history()` is a direct read that
141
141
  doesn't touch the list, so merging and deduplicating fall to you.
142
142
  - **`typing` is also delivered to the sender.** If you render "X is typing", skip your own `userId`.
143
+ - **`typing` carries no name.** Look the name up in `room.presence.users` — whoever is
144
+ watching the room is there. Collecting names from message senders misses anyone who has not
145
+ spoken yet. If `users` is absent (a room over 100), fetch it once with `presenceList()`, and fall
146
+ back to a placeholder if the name is still missing.
147
+
148
+ ```ts
149
+ room.on('typing', ({ userId }) => {
150
+ if (userId === chat.user?.id) return
151
+ const name = room.presence?.users?.find(u => u.id === userId)?.name
152
+ showTyping(userId, name ?? 'Someone') // clearing it after a few seconds is yours to do
153
+ })
154
+ ```
143
155
  - **The connection comes back on its own.** It reconnects with exponential backoff, so don't
144
156
  write your own retry loop.
157
+ - **What you send while reconnecting waits, then goes out.** `send`, `react`, `unreact` and
158
+ `markRead` skip the backoff when the state is `connecting`/`reconnecting`, wait for the
159
+ connection, and send. If the socket drops before the ack, **the same frame is sent once more**
160
+ — the server dedups on `clientMessageId`, and reactions and reads are idempotent, so nothing
161
+ lands twice. Waiting plus the ack is capped at 15 seconds, then `timeout`. `closed` now comes
162
+ only from a **stopped client** (`close()`, an auth refusal, or never `connect()`ed).
163
+ `typing()` does not wait; it is dropped.
145
164
  - **The SDK handles token expiry.** When REST gets a 401 it calls `token()` again and retries
146
165
  once. There's no need to reconnect periodically.
147
166
  - **Throwing a `ChatError` from `token()` stops the client.** That is how you say a failure,
@@ -269,12 +288,17 @@ spaces don't overlap.
269
288
 
270
289
  | Group | Methods |
271
290
  |---|---|
272
- | `rooms` | `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
291
+ | `rooms` | `list({type?, cursor?, limit?})`, `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
273
292
  | `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
274
293
  | `users` | `list({cursor?, limit?})`, `update(userId, {name?, avatar?, meta?})`, `withdraw(userId, {purgeMessages?})`, `purgeMessages(userId)`, `ban(userId, {until, reason?})`, `unban(userId)`, `revokeTokens(userId)`, `disconnect(userId, {connectionId?, reason?})` |
275
294
  | `events` | `list({after?, limit?})` — catches up on missed webhook events |
276
295
  | `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` — `tolerance` is in milliseconds |
277
296
 
297
+ `rooms.list` returns the app's rooms, newest first. With no `type` it is the public listing
298
+ (`public` and `channel`); pass e.g. `type: ['private', 'dm']` for private rooms and DMs. `limit`
299
+ defaults to 50 (max 100), an empty `cursor` is the last page, and **the cursor does not carry
300
+ `type`** — start over when the filter changes.
301
+
278
302
  `rooms.ensure` is get-or-create — it returns the room as-is if it exists, so it's fine to call
279
303
  on every page load.
280
304
 
package/README.md CHANGED
@@ -70,21 +70,21 @@ off()
70
70
 
71
71
  | 프로퍼티 | |
72
72
  |---|---|
73
- | `messages` | seq 오름차순. **정렬과 구멍 메우기는 SDK가 한다.** 바뀔 때마다 새 배열이다 |
73
+ | `messages` | seq 오름차순. **정렬과 구멍 메우기는 SDK가 한다.** 바뀔 때마다 새 배열이다. **스레드 답글도 섞여 있다**(`threadId`가 있는 행) — 본 타임라인만 그리려면 `threadId`가 없는 행만 고른다 |
74
74
  | `id` / `key` | 방 식별자. 키로 열었으면 구독 전까지 `id`가 없다 |
75
75
  | `lastSeq` | 서버가 알려 준 방의 마지막 seq |
76
- | `presence` | `{count, users?, capped?}` |
76
+ | `presence` | `{count, users?, capped?}` — 지금 이 방에 누가 있나. 구독 ack와 `presence` 이벤트의 증분을 **SDK가 합쳐 둔 값**이다. `users`는 **100명 이하 방에서만** 있고, 그보다 크거나 모르면 없다 — 그때는 `presenceList()` |
77
77
  | `hasOlder` | `loadOlder()`로 더 읽을 과거가 있는지. 첫 `loadOlder()` 전에 "이전 메시지" 버튼을 그릴지 정할 때 쓴다. `loadOlder()`의 `hasMore`와 같은 판정이고, 목록이 비었으면 `false`. `messages` 이벤트 때 다시 읽는다 |
78
78
 
79
79
  | 메서드 | |
80
80
  |---|---|
81
81
  | `subscribe()` | 라이브 피드를 켜고 최근 100건을 읽는다. 이미 따라잡혔으면 아무것도 안 한다. **연결 전에 불러도 된다** — 붙을 때까지 기다린다(`close()`면 `closed`로 거절) |
82
82
  | `unsubscribe()` | 이 방 보기를 그만둔다. 재접속해도 다시 구독하지 않는다 |
83
- | `send({text, attachments?, entities?, replyTo?, threadId?, meta?}, {clientMessageId?})` | 발행. ack로 `{messageId, seq}`. 구독이 진행 중이면 그것을 기다린다 |
83
+ | `send({text, attachments?, entities?, replyTo?, threadId?, meta?}, {clientMessageId?})` | 발행. ack로 `{messageId, seq}`. 구독이 진행 중이면 그것을 기다린다. **재접속 중이면 붙을 때까지 기다렸다가 보낸다**(아래) |
84
84
  | `loadOlder({limit?})` | 가장 오래된 메시지 앞 페이지(기본 100)를 읽어 **`messages` 앞에 붙인다.** `{messages, hasMore}`. 스크롤을 올릴 때 쓴다. 목록이 비어 있으면(구독 전) 아무것도 읽지 않는다 |
85
85
  | `history({before?, after?, limit?, view?})` | 과거를 직접 읽는다. **`messages`와 따로 논다.** `view`는 `'main'`, `'all'`, `{thread: id}` |
86
86
  | `reload()` | 최근 페이지를 다시 읽는다 |
87
- | `react(messageId, emoji)` / `unreact(...)` | 리액션. 멱등. **프레임보다 먼저** 그 행의 `myReactions`를 고치고, 서버가 거절하면 되돌린다. 개수는 건드리지 않는다 |
87
+ | `react(messageId, emoji)` / `unreact(...)` | 리액션. 멱등. **프레임보다 먼저** 그 행의 `myReactions`를 고치고, 서버가 거절하면 되돌린다. 개수는 낙관적으로 올리지 않고 **`reaction.*` 이벤트가 올 때 서버 값으로 고친다**(아래) |
88
88
  | `reactionsOf(messageId, {emoji?, cursor?, limit?})` | 누가 눌렀는지. **한 행은 (유저, 이모지) 쌍**이라 한 사람이 여러 줄일 수 있다. `limit` 기본 50 최대 100, 마지막 페이지의 `cursor`는 빈 문자열 |
89
89
  | `markRead(seq, {threadId?})` | 읽음 커서 |
90
90
  | `reads({userId?, cursor?, limit?})` | 읽음 커서 목록. `{reads: [{userId?, seq, threadId?, withdrawn?}], cursor}`. **`userId`로 한 사람만** — 자기 스레드별 커서를 되찾을 때 `reads({userId: chat.user.id})`. `cursor`가 `''`이면 끝 |
@@ -98,7 +98,7 @@ off()
98
98
  |---|---|
99
99
  | `message.created` / `message.updated` | `Message`. `created`에는 `thread`가 없고 `reactions`가 비어 있다 |
100
100
  | `message.deleted` | `{id, seq}`. `seq`는 그 메시지가 **발행될 때** 받은 값이다 |
101
- | `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}` |
101
+ | `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}`. SDK가 `messages` 안의 그 행의 `reactions` 개수를(내 것이면 `myReactions`도) 이미 고쳐 두었다. `history()`로 따로 읽은 행처럼 **목록 밖의 행은 소비자가 고친다** |
102
102
  | `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
103
103
  | `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left`는 증분, `users`는 교체다 |
104
104
  | `typing` | `{userId, threadId?}` — `threadId`는 스레드 **루트** id, 본 타임라인이면 없다 |
@@ -138,7 +138,24 @@ room.on('messages', m => (messages.value = m))
138
138
  - **과거는 `loadOlder()`로 같은 목록에 붙인다.** `history()`는 목록을 건드리지 않는 직접
139
139
  읽기이므로 합치고 중복을 거르는 일이 소비자 몫이 된다.
140
140
  - **`typing`은 보낸 사람에게도 온다.** "X가 입력 중"을 그린다면 자기 `userId`를 건너뛴다.
141
+ - **`typing`은 이름을 싣지 않는다.** 이름은 `room.presence.users`에서 찾는다 — 방을 보고 있는
142
+ 사람이 거기 있다. 메시지 발신자에서 이름을 모으면 아직 말하지 않은 사람을 모른다.
143
+ `users`가 없으면(100명 넘는 방) `presenceList()`로 한 번 받아 오고, 그래도 없으면 대체 이름을 쓴다.
144
+
145
+ ```ts
146
+ room.on('typing', ({ userId }) => {
147
+ if (userId === chat.user?.id) return
148
+ const name = room.presence?.users?.find(u => u.id === userId)?.name
149
+ showTyping(userId, name ?? '누군가') // 몇 초 뒤 지우는 것은 소비자 몫이다
150
+ })
151
+ ```
141
152
  - **연결은 알아서 돌아온다.** 끊기면 지수 백오프로 다시 붙으니 재시도 루프를 짜지 않는다.
153
+ - **재접속 중에 보낸 것은 기다렸다가 나간다.** `send`·`react`·`unreact`·`markRead`는 상태가
154
+ `connecting`/`reconnecting`이면 백오프를 건너뛰고 붙기를 기다려 보낸다. ack 전에 소켓이
155
+ 끊기면 **같은 프레임을 한 번 더** 보낸다 — 서버가 `clientMessageId`로 중복을 거르고 리액션·읽음은
156
+ 멱등이라 두 번 반영되지 않는다. 대기와 ack를 합쳐 15초가 넘으면 `timeout`이다.
157
+ `closed`는 이제 **멈춘 클라이언트**(`close()`, 인증 거절, 한 번도 `connect()`하지 않음)에서만
158
+ 온다. `typing()`은 기다리지 않고 버린다.
142
159
  - **토큰 만료는 SDK가 처리한다.** REST가 401을 받으면 `token()`을 다시 불러 한 번
143
160
  재시도한다. 주기적으로 재접속할 필요가 없다.
144
161
  - **`token()`이 `ChatError`를 던지면 멈춘다.** 밴처럼 다시 해도 소용없는 실패를 그렇게 알린다.
@@ -259,7 +276,7 @@ app.post('/api/chat-token', (req, res) => {
259
276
 
260
277
  | 그룹 | 메서드 |
261
278
  |---|---|
262
- | `rooms` | `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
279
+ | `rooms` | `list({type?, cursor?, limit?})`, `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
263
280
  | `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
264
281
  | `users` | `list({cursor?, limit?})`, `update(userId, {name?, avatar?, meta?})`, `withdraw(userId, {purgeMessages?})`, `purgeMessages(userId)`, `ban(userId, {until, reason?})`, `unban(userId)`, `revokeTokens(userId)`, `disconnect(userId, {connectionId?, reason?})` |
265
282
  | `events` | `list({after?, limit?})` — 놓친 웹훅 이벤트를 따라잡는다 |
@@ -267,6 +284,10 @@ app.post('/api/chat-token', (req, res) => {
267
284
 
268
285
  `rooms.ensure`는 get-or-create다 — 있으면 그대로 돌려주므로 페이지를 열 때마다 불러도 된다.
269
286
 
287
+ `rooms.list`는 앱의 방을 최신순으로 준다. `type`이 없으면 공개 목록(`public`·`channel`)이고,
288
+ `type: ['private', 'dm']`처럼 주면 비공개 방과 DM도 나온다. `limit` 기본 50 최대 100, 빈 `cursor`가
289
+ 마지막 페이지이고, **커서는 `type`을 싣지 않으므로** 필터를 바꾸면 처음부터 받는다.
290
+
270
291
  `rooms.presence(roomId)`는 `{count}`이고, `{full: true}`면 `users`(최대 1000명, 잘리면
271
292
  `capped: true`)가 붙는다. 빈 방은 404가 아니라 `{count: 0}`이다.
272
293
 
package/dist/index.cjs CHANGED
@@ -621,6 +621,15 @@ var Room = class extends Emitter {
621
621
  key;
622
622
  /** The last seq the server reported for this room. */
623
623
  lastSeq = 0;
624
+ /**
625
+ * Who is here, as far as this client can tell: `{count, users?, capped?}`.
626
+ *
627
+ * Not the last `presence` frame. A `joined`/`left` frame is an increment
628
+ * and carries no `users`, so holding the frame itself dropped the list
629
+ * the moment anyone came or went. The SDK folds increments into the list
630
+ * it holds; `users` is absent when it does not know the list (a room over
631
+ * 100 people, or an ack that could not look it up) -- `presenceList()`.
632
+ */
624
633
  presence;
625
634
  chat;
626
635
  rest;
@@ -842,7 +851,7 @@ var Room = class extends Emitter {
842
851
  messageId,
843
852
  emoji,
844
853
  op: mine ? "add" : "remove"
845
- });
854
+ }, void 0, { resendOnDrop: true });
846
855
  } catch (err) {
847
856
  if (press !== void 0) this.timeline.settleReaction(press, false);
848
857
  throw err;
@@ -860,7 +869,7 @@ var Room = class extends Emitter {
860
869
  async markRead(seq, options = {}) {
861
870
  const data = { roomId: await this.resolveId("marking read"), seq };
862
871
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
863
- return await this.chat.sendFrame("read", data);
872
+ return await this.chat.sendFrame("read", data, void 0, { resendOnDrop: true });
864
873
  }
865
874
  /**
866
875
  * Lists read cursors in this room, one page at a time.
@@ -913,7 +922,7 @@ var Room = class extends Emitter {
913
922
  try {
914
923
  const data = { roomId: this.requireId("typing") };
915
924
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
916
- void this.chat.sendFrame("typing", data).catch(() => {
925
+ void this.chat.sendFrame("typing", data, void 0, { wait: false }).catch(() => {
917
926
  });
918
927
  } catch {
919
928
  }
@@ -1011,7 +1020,7 @@ var Room = class extends Emitter {
1011
1020
  this.subscribed = false;
1012
1021
  this.generation++;
1013
1022
  this.subscribing = void 0;
1014
- await this.chat.sendFrame("unsubscribe", { roomId: this.id });
1023
+ await this.chat.sendFrame("unsubscribe", { roomId: this.id }, void 0, { wait: false });
1015
1024
  }
1016
1025
  /**
1017
1026
  * The room's id, or a refusal.
@@ -1056,7 +1065,7 @@ var Room = class extends Emitter {
1056
1065
  if (input.replyTo !== void 0) frame["replyTo"] = input.replyTo;
1057
1066
  if (input.threadId !== void 0) frame["threadId"] = input.threadId;
1058
1067
  if (input.meta !== void 0) frame["meta"] = input.meta;
1059
- return await this.chat.sendFrame("publish", frame);
1068
+ return await this.chat.sendFrame("publish", frame, void 0, { resendOnDrop: true });
1060
1069
  }
1061
1070
  /** @internal Routes a frame the client decided belongs to this room. */
1062
1071
  handle(type, data) {
@@ -1091,7 +1100,7 @@ var Room = class extends Emitter {
1091
1100
  break;
1092
1101
  }
1093
1102
  case "presence":
1094
- this.presence = data;
1103
+ this.presence = foldPresence(this.presence, data);
1095
1104
  break;
1096
1105
  default:
1097
1106
  break;
@@ -1116,6 +1125,20 @@ var Room = class extends Emitter {
1116
1125
  this.timeline.reset(page.messages);
1117
1126
  }
1118
1127
  };
1128
+ function foldPresence(held, frame) {
1129
+ if (frame.users !== void 0) {
1130
+ return frame.capped === void 0 ? { count: frame.count, users: frame.users } : { count: frame.count, users: frame.users, capped: frame.capped };
1131
+ }
1132
+ const list = held?.users;
1133
+ if (list === void 0 || frame.joined === void 0 && frame.left === void 0) {
1134
+ return { count: frame.count };
1135
+ }
1136
+ const gone = new Set(frame.left ?? []);
1137
+ const arrived = frame.joined ?? [];
1138
+ const fresh = new Set(arrived.map((u) => u.id));
1139
+ const users = [...list.filter((u) => !gone.has(u.id) && !fresh.has(u.id)), ...arrived];
1140
+ return { count: frame.count, users };
1141
+ }
1119
1142
  function newClientMessageId() {
1120
1143
  const c = globalThis.crypto;
1121
1144
  if (c?.randomUUID !== void 0) return `cm-${c.randomUUID()}`;
@@ -1467,7 +1490,57 @@ var ChatClient = class extends Emitter {
1467
1490
  * 읽혔다 — 실제로는 와이어 프레임 이름을 직접 적는 탈출구라 계약이
1468
1491
  * 바뀌면 같이 깨진다. 1.0에서 얼릴 표면에 둘 것이 아니다.
1469
1492
  */
1470
- sendFrame(type, data, timeoutMs = 15e3) {
1493
+ sendFrame(type, data, timeoutMs = 15e3, options = {}) {
1494
+ const deadline = Date.now() + timeoutMs;
1495
+ const wait = options.wait ?? true;
1496
+ const run = async (resends) => {
1497
+ if (this.socket === void 0 || this.state !== "open") {
1498
+ if (!wait || this.stopped || this.state === "closed") {
1499
+ throw new ChatError("closed", `cannot send ${type}: the connection is ${this.state}`);
1500
+ }
1501
+ const serverSaidWait = this.serverDelayUntil !== void 0 && Date.now() < this.serverDelayUntil;
1502
+ if (this.state === "reconnecting" && this.opening === void 0 && !serverSaidWait) {
1503
+ void this.resume().catch(() => {
1504
+ });
1505
+ }
1506
+ await this.untilOpen(type, deadline);
1507
+ }
1508
+ try {
1509
+ return await this.sendOnSocket(type, data, Math.max(0, deadline - Date.now()));
1510
+ } catch (err) {
1511
+ if (options.resendOnDrop === true && resends === 0 && isChatError(err) && err.code === "closed" && !this.stopped && Date.now() < deadline) {
1512
+ return run(resends + 1);
1513
+ }
1514
+ throw err;
1515
+ }
1516
+ };
1517
+ return run(0);
1518
+ }
1519
+ // whenOpen, bounded by the frame's deadline: running out is `timeout`, not `closed`.
1520
+ // The waiter leaves the list when it times out, so a long offline spell of
1521
+ // repeated sends does not pile closures up until the next hello.
1522
+ untilOpen(type, deadline) {
1523
+ if (this.state === "open" && this.socket !== void 0) return Promise.resolve();
1524
+ if (this.stopped) return Promise.reject(new ChatError("closed", "the connection is closed"));
1525
+ return new Promise((resolve, reject) => {
1526
+ const waiter = {
1527
+ resolve: () => {
1528
+ clearTimeout(timer);
1529
+ resolve();
1530
+ },
1531
+ reject: (err) => {
1532
+ clearTimeout(timer);
1533
+ reject(err);
1534
+ }
1535
+ };
1536
+ const timer = setTimeout(() => {
1537
+ this.openWaiters = this.openWaiters.filter((w) => w !== waiter);
1538
+ reject(new ChatError("timeout", `cannot send ${type}: the connection did not reopen in time`));
1539
+ }, Math.max(0, deadline - Date.now()));
1540
+ this.openWaiters.push(waiter);
1541
+ });
1542
+ }
1543
+ sendOnSocket(type, data, timeoutMs) {
1471
1544
  const socket = this.socket;
1472
1545
  if (socket === void 0 || this.state !== "open") {
1473
1546
  return Promise.reject(new ChatError("closed", `cannot send ${type}: the connection is ${this.state}`));
@@ -1645,6 +1718,8 @@ var ChatClient = class extends Emitter {
1645
1718
  room.handle(event, push?.data);
1646
1719
  }
1647
1720
  plannedDelayMs;
1721
+ // When a server-directed delay (drain, rate limit) ends; a send does not cut it short.
1722
+ serverDelayUntil;
1648
1723
  startHeartbeat(intervalMs) {
1649
1724
  this.clearHeartbeat();
1650
1725
  this.heartbeat = setInterval(() => {
@@ -1676,6 +1751,7 @@ var ChatClient = class extends Emitter {
1676
1751
  nextDelay() {
1677
1752
  const planned = this.plannedDelayMs;
1678
1753
  this.plannedDelayMs = void 0;
1754
+ this.serverDelayUntil = planned === void 0 ? void 0 : Date.now() + planned;
1679
1755
  if (planned !== void 0) return planned;
1680
1756
  const ceiling = Math.min(MaxBackoffMs, MinBackoffMs * 2 ** this.attempt);
1681
1757
  this.attempt++;
package/dist/index.d.cts CHANGED
@@ -352,6 +352,15 @@ declare class Room extends Emitter<RoomEvents> {
352
352
  readonly key: string | undefined;
353
353
  /** The last seq the server reported for this room. */
354
354
  lastSeq: number;
355
+ /**
356
+ * Who is here, as far as this client can tell: `{count, users?, capped?}`.
357
+ *
358
+ * Not the last `presence` frame. A `joined`/`left` frame is an increment
359
+ * and carries no `users`, so holding the frame itself dropped the list
360
+ * the moment anyone came or went. The SDK folds increments into the list
361
+ * it holds; `users` is absent when it does not know the list (a room over
362
+ * 100 people, or an ack that could not look it up) -- `presenceList()`.
363
+ */
355
364
  presence: PresenceEvent | undefined;
356
365
  private readonly chat;
357
366
  private readonly rest;
@@ -862,6 +871,8 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
862
871
  private stop;
863
872
  private openWaiters;
864
873
  private settleOpenWaiters;
874
+ private untilOpen;
875
+ private sendOnSocket;
865
876
  /**
866
877
  * Frames waiting for an ack, by frame id.
867
878
  *
@@ -888,6 +899,7 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
888
899
  */
889
900
  private onPush;
890
901
  private plannedDelayMs;
902
+ private serverDelayUntil;
891
903
  private startHeartbeat;
892
904
  private scheduleReconnect;
893
905
  /**
package/dist/index.d.ts CHANGED
@@ -352,6 +352,15 @@ declare class Room extends Emitter<RoomEvents> {
352
352
  readonly key: string | undefined;
353
353
  /** The last seq the server reported for this room. */
354
354
  lastSeq: number;
355
+ /**
356
+ * Who is here, as far as this client can tell: `{count, users?, capped?}`.
357
+ *
358
+ * Not the last `presence` frame. A `joined`/`left` frame is an increment
359
+ * and carries no `users`, so holding the frame itself dropped the list
360
+ * the moment anyone came or went. The SDK folds increments into the list
361
+ * it holds; `users` is absent when it does not know the list (a room over
362
+ * 100 people, or an ack that could not look it up) -- `presenceList()`.
363
+ */
355
364
  presence: PresenceEvent | undefined;
356
365
  private readonly chat;
357
366
  private readonly rest;
@@ -862,6 +871,8 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
862
871
  private stop;
863
872
  private openWaiters;
864
873
  private settleOpenWaiters;
874
+ private untilOpen;
875
+ private sendOnSocket;
865
876
  /**
866
877
  * Frames waiting for an ack, by frame id.
867
878
  *
@@ -888,6 +899,7 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
888
899
  */
889
900
  private onPush;
890
901
  private plannedDelayMs;
902
+ private serverDelayUntil;
891
903
  private startHeartbeat;
892
904
  private scheduleReconnect;
893
905
  /**
package/dist/index.js CHANGED
@@ -551,6 +551,15 @@ var Room = class extends Emitter {
551
551
  key;
552
552
  /** The last seq the server reported for this room. */
553
553
  lastSeq = 0;
554
+ /**
555
+ * Who is here, as far as this client can tell: `{count, users?, capped?}`.
556
+ *
557
+ * Not the last `presence` frame. A `joined`/`left` frame is an increment
558
+ * and carries no `users`, so holding the frame itself dropped the list
559
+ * the moment anyone came or went. The SDK folds increments into the list
560
+ * it holds; `users` is absent when it does not know the list (a room over
561
+ * 100 people, or an ack that could not look it up) -- `presenceList()`.
562
+ */
554
563
  presence;
555
564
  chat;
556
565
  rest;
@@ -772,7 +781,7 @@ var Room = class extends Emitter {
772
781
  messageId,
773
782
  emoji,
774
783
  op: mine ? "add" : "remove"
775
- });
784
+ }, void 0, { resendOnDrop: true });
776
785
  } catch (err) {
777
786
  if (press !== void 0) this.timeline.settleReaction(press, false);
778
787
  throw err;
@@ -790,7 +799,7 @@ var Room = class extends Emitter {
790
799
  async markRead(seq, options = {}) {
791
800
  const data = { roomId: await this.resolveId("marking read"), seq };
792
801
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
793
- return await this.chat.sendFrame("read", data);
802
+ return await this.chat.sendFrame("read", data, void 0, { resendOnDrop: true });
794
803
  }
795
804
  /**
796
805
  * Lists read cursors in this room, one page at a time.
@@ -843,7 +852,7 @@ var Room = class extends Emitter {
843
852
  try {
844
853
  const data = { roomId: this.requireId("typing") };
845
854
  if (options.threadId !== void 0) data["threadId"] = options.threadId;
846
- void this.chat.sendFrame("typing", data).catch(() => {
855
+ void this.chat.sendFrame("typing", data, void 0, { wait: false }).catch(() => {
847
856
  });
848
857
  } catch {
849
858
  }
@@ -941,7 +950,7 @@ var Room = class extends Emitter {
941
950
  this.subscribed = false;
942
951
  this.generation++;
943
952
  this.subscribing = void 0;
944
- await this.chat.sendFrame("unsubscribe", { roomId: this.id });
953
+ await this.chat.sendFrame("unsubscribe", { roomId: this.id }, void 0, { wait: false });
945
954
  }
946
955
  /**
947
956
  * The room's id, or a refusal.
@@ -986,7 +995,7 @@ var Room = class extends Emitter {
986
995
  if (input.replyTo !== void 0) frame["replyTo"] = input.replyTo;
987
996
  if (input.threadId !== void 0) frame["threadId"] = input.threadId;
988
997
  if (input.meta !== void 0) frame["meta"] = input.meta;
989
- return await this.chat.sendFrame("publish", frame);
998
+ return await this.chat.sendFrame("publish", frame, void 0, { resendOnDrop: true });
990
999
  }
991
1000
  /** @internal Routes a frame the client decided belongs to this room. */
992
1001
  handle(type, data) {
@@ -1021,7 +1030,7 @@ var Room = class extends Emitter {
1021
1030
  break;
1022
1031
  }
1023
1032
  case "presence":
1024
- this.presence = data;
1033
+ this.presence = foldPresence(this.presence, data);
1025
1034
  break;
1026
1035
  default:
1027
1036
  break;
@@ -1046,6 +1055,20 @@ var Room = class extends Emitter {
1046
1055
  this.timeline.reset(page.messages);
1047
1056
  }
1048
1057
  };
1058
+ function foldPresence(held, frame) {
1059
+ if (frame.users !== void 0) {
1060
+ return frame.capped === void 0 ? { count: frame.count, users: frame.users } : { count: frame.count, users: frame.users, capped: frame.capped };
1061
+ }
1062
+ const list = held?.users;
1063
+ if (list === void 0 || frame.joined === void 0 && frame.left === void 0) {
1064
+ return { count: frame.count };
1065
+ }
1066
+ const gone = new Set(frame.left ?? []);
1067
+ const arrived = frame.joined ?? [];
1068
+ const fresh = new Set(arrived.map((u) => u.id));
1069
+ const users = [...list.filter((u) => !gone.has(u.id) && !fresh.has(u.id)), ...arrived];
1070
+ return { count: frame.count, users };
1071
+ }
1049
1072
  function newClientMessageId() {
1050
1073
  const c = globalThis.crypto;
1051
1074
  if (c?.randomUUID !== void 0) return `cm-${c.randomUUID()}`;
@@ -1397,7 +1420,57 @@ var ChatClient = class extends Emitter {
1397
1420
  * 읽혔다 — 실제로는 와이어 프레임 이름을 직접 적는 탈출구라 계약이
1398
1421
  * 바뀌면 같이 깨진다. 1.0에서 얼릴 표면에 둘 것이 아니다.
1399
1422
  */
1400
- sendFrame(type, data, timeoutMs = 15e3) {
1423
+ sendFrame(type, data, timeoutMs = 15e3, options = {}) {
1424
+ const deadline = Date.now() + timeoutMs;
1425
+ const wait = options.wait ?? true;
1426
+ const run = async (resends) => {
1427
+ if (this.socket === void 0 || this.state !== "open") {
1428
+ if (!wait || this.stopped || this.state === "closed") {
1429
+ throw new ChatError("closed", `cannot send ${type}: the connection is ${this.state}`);
1430
+ }
1431
+ const serverSaidWait = this.serverDelayUntil !== void 0 && Date.now() < this.serverDelayUntil;
1432
+ if (this.state === "reconnecting" && this.opening === void 0 && !serverSaidWait) {
1433
+ void this.resume().catch(() => {
1434
+ });
1435
+ }
1436
+ await this.untilOpen(type, deadline);
1437
+ }
1438
+ try {
1439
+ return await this.sendOnSocket(type, data, Math.max(0, deadline - Date.now()));
1440
+ } catch (err) {
1441
+ if (options.resendOnDrop === true && resends === 0 && isChatError(err) && err.code === "closed" && !this.stopped && Date.now() < deadline) {
1442
+ return run(resends + 1);
1443
+ }
1444
+ throw err;
1445
+ }
1446
+ };
1447
+ return run(0);
1448
+ }
1449
+ // whenOpen, bounded by the frame's deadline: running out is `timeout`, not `closed`.
1450
+ // The waiter leaves the list when it times out, so a long offline spell of
1451
+ // repeated sends does not pile closures up until the next hello.
1452
+ untilOpen(type, deadline) {
1453
+ if (this.state === "open" && this.socket !== void 0) return Promise.resolve();
1454
+ if (this.stopped) return Promise.reject(new ChatError("closed", "the connection is closed"));
1455
+ return new Promise((resolve, reject) => {
1456
+ const waiter = {
1457
+ resolve: () => {
1458
+ clearTimeout(timer);
1459
+ resolve();
1460
+ },
1461
+ reject: (err) => {
1462
+ clearTimeout(timer);
1463
+ reject(err);
1464
+ }
1465
+ };
1466
+ const timer = setTimeout(() => {
1467
+ this.openWaiters = this.openWaiters.filter((w) => w !== waiter);
1468
+ reject(new ChatError("timeout", `cannot send ${type}: the connection did not reopen in time`));
1469
+ }, Math.max(0, deadline - Date.now()));
1470
+ this.openWaiters.push(waiter);
1471
+ });
1472
+ }
1473
+ sendOnSocket(type, data, timeoutMs) {
1401
1474
  const socket = this.socket;
1402
1475
  if (socket === void 0 || this.state !== "open") {
1403
1476
  return Promise.reject(new ChatError("closed", `cannot send ${type}: the connection is ${this.state}`));
@@ -1575,6 +1648,8 @@ var ChatClient = class extends Emitter {
1575
1648
  room.handle(event, push?.data);
1576
1649
  }
1577
1650
  plannedDelayMs;
1651
+ // When a server-directed delay (drain, rate limit) ends; a send does not cut it short.
1652
+ serverDelayUntil;
1578
1653
  startHeartbeat(intervalMs) {
1579
1654
  this.clearHeartbeat();
1580
1655
  this.heartbeat = setInterval(() => {
@@ -1606,6 +1681,7 @@ var ChatClient = class extends Emitter {
1606
1681
  nextDelay() {
1607
1682
  const planned = this.plannedDelayMs;
1608
1683
  this.plannedDelayMs = void 0;
1684
+ this.serverDelayUntil = planned === void 0 ? void 0 : Date.now() + planned;
1609
1685
  if (planned !== void 0) return planned;
1610
1686
  const ceiling = Math.min(MaxBackoffMs, MinBackoffMs * 2 ** this.attempt);
1611
1687
  this.attempt++;
@@ -286,6 +286,14 @@ function createChatServer(options) {
286
286
  };
287
287
  },
288
288
  rooms: {
289
+ list: (o) => rest.call(
290
+ "GET",
291
+ `/v1/rooms${rest.query({
292
+ type: Array.isArray(o?.type) ? o.type.join(",") : o?.type,
293
+ cursor: o?.cursor,
294
+ limit: o?.limit
295
+ })}`
296
+ ),
289
297
  ensure: (input) => rest.call("PUT", "/v1/rooms", input),
290
298
  ensureDM: (members) => rest.call("PUT", "/v1/rooms", { type: "dm", members }),
291
299
  get: (roomId) => rest.call("GET", `/v1/rooms/${roomId}`),
@@ -151,6 +151,21 @@ type ChatServer = {
151
151
  */
152
152
  guest: (input: GuestInput) => GuestIdentity;
153
153
  rooms: {
154
+ /**
155
+ * The app's rooms, newest first. With no `type` it is the public
156
+ * listing (`public` and `channel`) -- the same page a client's
157
+ * `rooms.discover()` gets; name `private` and `dm` to find the rest.
158
+ * `cursor` is opaque, empty on the last page, and does not carry
159
+ * `type`: start over when the filter changes.
160
+ */
161
+ list: (options?: {
162
+ type?: EnsureRoomInput['type'] | EnsureRoomInput['type'][];
163
+ cursor?: string;
164
+ limit?: number;
165
+ }) => Promise<{
166
+ rooms: unknown[];
167
+ cursor: string;
168
+ }>;
154
169
  /** get-or-create. The same call whether the room exists or not. */
155
170
  ensure: (input: EnsureRoomInput) => Promise<{
156
171
  id: string;
@@ -151,6 +151,21 @@ type ChatServer = {
151
151
  */
152
152
  guest: (input: GuestInput) => GuestIdentity;
153
153
  rooms: {
154
+ /**
155
+ * The app's rooms, newest first. With no `type` it is the public
156
+ * listing (`public` and `channel`) -- the same page a client's
157
+ * `rooms.discover()` gets; name `private` and `dm` to find the rest.
158
+ * `cursor` is opaque, empty on the last page, and does not carry
159
+ * `type`: start over when the filter changes.
160
+ */
161
+ list: (options?: {
162
+ type?: EnsureRoomInput['type'] | EnsureRoomInput['type'][];
163
+ cursor?: string;
164
+ limit?: number;
165
+ }) => Promise<{
166
+ rooms: unknown[];
167
+ cursor: string;
168
+ }>;
154
169
  /** get-or-create. The same call whether the room exists or not. */
155
170
  ensure: (input: EnsureRoomInput) => Promise<{
156
171
  id: string;
@@ -215,6 +215,14 @@ function createChatServer(options) {
215
215
  };
216
216
  },
217
217
  rooms: {
218
+ list: (o) => rest.call(
219
+ "GET",
220
+ `/v1/rooms${rest.query({
221
+ type: Array.isArray(o?.type) ? o.type.join(",") : o?.type,
222
+ cursor: o?.cursor,
223
+ limit: o?.limit
224
+ })}`
225
+ ),
218
226
  ensure: (input) => rest.call("PUT", "/v1/rooms", input),
219
227
  ensureDM: (members) => rest.call("PUT", "/v1/rooms", { type: "dm", members }),
220
228
  get: (roomId) => rest.call("GET", `/v1/rooms/${roomId}`),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kispi/chat",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Client SDK for the chat server: one WebSocket, many rooms, ordered history.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -33,6 +33,7 @@
33
33
  },
34
34
  "scripts": {
35
35
  "build": "tsup",
36
+ "prepack": "npm run build",
36
37
  "test": "vitest run",
37
38
  "typecheck": "tsc --noEmit"
38
39
  },