@kispi/chat 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +74 -48
- package/README.md +70 -47
- package/dist/{chunk-5QQRM7BH.js → chunk-WSBOTTBM.js} +21 -3
- package/dist/index.cjs +183 -46
- package/dist/index.d.cts +172 -328
- package/dist/index.d.ts +172 -328
- package/dist/index.js +166 -42
- package/dist/server/index.cjs +37 -9
- package/dist/server/index.d.cts +20 -14
- package/dist/server/index.d.ts +20 -14
- package/dist/server/index.js +22 -8
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
|
+
ChatEndpoint,
|
|
2
3
|
ChatError,
|
|
3
|
-
errorFrom
|
|
4
|
-
|
|
4
|
+
errorFrom,
|
|
5
|
+
restURLFrom
|
|
6
|
+
} from "./chunk-WSBOTTBM.js";
|
|
5
7
|
|
|
6
8
|
// src/emitter.ts
|
|
7
9
|
var Emitter = class {
|
|
@@ -87,9 +89,7 @@ var Rest = class {
|
|
|
87
89
|
const text = await res.text();
|
|
88
90
|
const parsed = text === "" ? void 0 : JSON.parse(text);
|
|
89
91
|
if (!res.ok) {
|
|
90
|
-
|
|
91
|
-
err.status = res.status;
|
|
92
|
-
throw err;
|
|
92
|
+
throw errorFrom(parsed, `${method} ${path} failed with ${res.status}`, res.status);
|
|
93
93
|
}
|
|
94
94
|
return parsed;
|
|
95
95
|
}
|
|
@@ -103,11 +103,6 @@ function queryString(query) {
|
|
|
103
103
|
const s = params.toString();
|
|
104
104
|
return s === "" ? "" : `?${s}`;
|
|
105
105
|
}
|
|
106
|
-
function restURLFrom(socketURL) {
|
|
107
|
-
if (socketURL.startsWith("wss://")) return `https://${socketURL.slice("wss://".length)}`;
|
|
108
|
-
if (socketURL.startsWith("ws://")) return `http://${socketURL.slice("ws://".length)}`;
|
|
109
|
-
return socketURL;
|
|
110
|
-
}
|
|
111
106
|
|
|
112
107
|
// src/timeline.ts
|
|
113
108
|
var MaxPageSize = 100;
|
|
@@ -154,6 +149,18 @@ var Timeline = class {
|
|
|
154
149
|
floor = 1;
|
|
155
150
|
/** A `loadOlder` came back short: the top of what the server keeps was reached. */
|
|
156
151
|
exhausted = false;
|
|
152
|
+
/**
|
|
153
|
+
* Presses this client has made and the server has not answered yet, one
|
|
154
|
+
* entry per (message, emoji) pair, each remembering the last value the
|
|
155
|
+
* **server** gave for that pair.
|
|
156
|
+
*
|
|
157
|
+
* 되돌릴 자리로 "누르기 직전 화면값"을 쓰면 안 된다. 눌렀다 곧바로 취소하고
|
|
158
|
+
* 두 거절이 차례로 오면, 두 번째 거절이 첫 번째의 낙관값 — 서버가 한 번도
|
|
159
|
+
* 가진 적 없는 값 — 을 화면에 되살린다. 마지막으로 서버가 말한 값만이
|
|
160
|
+
* 되돌릴 자리다.
|
|
161
|
+
*/
|
|
162
|
+
presses = /* @__PURE__ */ new Map();
|
|
163
|
+
pressSeq = 0;
|
|
157
164
|
constructor(options) {
|
|
158
165
|
this.options = options;
|
|
159
166
|
}
|
|
@@ -221,6 +228,7 @@ var Timeline = class {
|
|
|
221
228
|
this.epoch++;
|
|
222
229
|
this.fills.clear();
|
|
223
230
|
this.pendingDeletes.clear();
|
|
231
|
+
this.presses.clear();
|
|
224
232
|
this.items = [];
|
|
225
233
|
this.exhausted = false;
|
|
226
234
|
this.shared = false;
|
|
@@ -248,6 +256,7 @@ var Timeline = class {
|
|
|
248
256
|
this.epoch++;
|
|
249
257
|
this.fills.clear();
|
|
250
258
|
const page = [...messages].sort((a, b) => a.seq - b.seq);
|
|
259
|
+
for (const m of page) this.serverRendered(m.id);
|
|
251
260
|
const top = page.at(-1)?.seq ?? 0;
|
|
252
261
|
this.items = [...page, ...this.items.filter((m) => m.seq > top)];
|
|
253
262
|
this.exhausted = false;
|
|
@@ -304,8 +313,57 @@ var Timeline = class {
|
|
|
304
313
|
* cannot drift the way `+1`/`-1` would. `count` undefined leaves the
|
|
305
314
|
* aggregate alone (the react ack path); `mine` undefined leaves
|
|
306
315
|
* `myReactions` alone (somebody else's event).
|
|
316
|
+
*
|
|
317
|
+
* This is the **authoritative** entry point: a value the server sent.
|
|
318
|
+
* So a press still waiting on an answer for the same pair is finished
|
|
319
|
+
* here -- a refusal landing afterwards must not push this value back
|
|
320
|
+
* to the older one it was going to restore.
|
|
307
321
|
*/
|
|
308
322
|
reaction(messageId, emoji, count, mine) {
|
|
323
|
+
if (mine !== void 0) this.presses.delete(pairKey(messageId, emoji));
|
|
324
|
+
this.applyReaction(messageId, emoji, count, mine);
|
|
325
|
+
}
|
|
326
|
+
/**
|
|
327
|
+
* Applies this client's own react/unreact to `myReactions` **before the
|
|
328
|
+
* frame goes out**, and returns the press so its answer can settle it.
|
|
329
|
+
*
|
|
330
|
+
* 누른 값은 (사용자, 이모지)로 로컬에서 정해지고 엔진은 멱등이므로, 미리
|
|
331
|
+
* 적용해도 ack가 새로 알려 줄 것이 없다. `count`는 일부러 건드리지 않는다 —
|
|
332
|
+
* 그 사이 남이 같은 이모지를 누르면 로컬 +1/-1은 서버가 보낼 수와 다르고,
|
|
333
|
+
* 그 차이를 고칠 이벤트는 이미 지나갔다.
|
|
334
|
+
*
|
|
335
|
+
* Undefined when the row is not held: there is nothing to show now and
|
|
336
|
+
* nothing to put back later.
|
|
337
|
+
*/
|
|
338
|
+
pressReaction(messageId, emoji, mine) {
|
|
339
|
+
const at = this.items.findIndex((m) => m.id === messageId);
|
|
340
|
+
if (at === -1) return void 0;
|
|
341
|
+
const key = pairKey(messageId, emoji);
|
|
342
|
+
const base = this.presses.get(key)?.base ?? (this.items[at].myReactions ?? []).includes(emoji);
|
|
343
|
+
const press = { messageId, emoji, mine, seq: ++this.pressSeq };
|
|
344
|
+
this.presses.set(key, { seq: press.seq, base });
|
|
345
|
+
this.applyReaction(messageId, emoji, void 0, mine);
|
|
346
|
+
return press;
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Settles a press with what the server said.
|
|
350
|
+
*
|
|
351
|
+
* `accepted` re-asserts the value the press asked for; a refusal puts
|
|
352
|
+
* the last server-given value back. Either way it does nothing once
|
|
353
|
+
* this press no longer owns the pair -- a newer press took it over
|
|
354
|
+
* (and that one's answer decides), or something authoritative already
|
|
355
|
+
* landed on it (a `reaction.*` event carrying this user's id, a
|
|
356
|
+
* `reload()`, a reconnect's catch-up page). Reverting there would
|
|
357
|
+
* resurrect a value older than what is on screen.
|
|
358
|
+
*/
|
|
359
|
+
settleReaction(press, accepted) {
|
|
360
|
+
const key = pairKey(press.messageId, press.emoji);
|
|
361
|
+
const held = this.presses.get(key);
|
|
362
|
+
if (held === void 0 || held.seq !== press.seq) return;
|
|
363
|
+
this.presses.delete(key);
|
|
364
|
+
this.applyReaction(press.messageId, press.emoji, void 0, accepted ? press.mine : held.base);
|
|
365
|
+
}
|
|
366
|
+
applyReaction(messageId, emoji, count, mine) {
|
|
309
367
|
const at = this.items.findIndex((m) => m.id === messageId);
|
|
310
368
|
if (at === -1) return;
|
|
311
369
|
const current = this.items[at];
|
|
@@ -422,6 +480,7 @@ var Timeline = class {
|
|
|
422
480
|
}
|
|
423
481
|
/** Inserts at the seq position, replacing an existing row with that seq. */
|
|
424
482
|
insert(message, notify = true) {
|
|
483
|
+
this.serverRendered(message.id);
|
|
425
484
|
const pending = this.pendingDeletes.has(message.id);
|
|
426
485
|
if (pending) this.pendingDeletes.delete(message.id);
|
|
427
486
|
const withDelete = pending ? emptied(message) : message;
|
|
@@ -446,6 +505,21 @@ var Timeline = class {
|
|
|
446
505
|
this.changed();
|
|
447
506
|
return true;
|
|
448
507
|
}
|
|
508
|
+
/**
|
|
509
|
+
* Forgets the presses on a row the server has just re-rendered.
|
|
510
|
+
*
|
|
511
|
+
* 히스토리 응답의 행은 뷰어별 `myReactions`를 싣고 오므로 그 값이 서버의
|
|
512
|
+
* 값이다. 누름을 남겨 두면 그 뒤에 온 거절이 더 새로운 진실 위에 옛 값을
|
|
513
|
+
* 덮어쓴다. 행 전체 단위인 것은 페이지가 그 행의 이모지 전부를 다시 그려
|
|
514
|
+
* 주기 때문이다.
|
|
515
|
+
*/
|
|
516
|
+
serverRendered(messageId) {
|
|
517
|
+
if (this.presses.size === 0) return;
|
|
518
|
+
const prefix = `${messageId}\0`;
|
|
519
|
+
for (const key of this.presses.keys()) {
|
|
520
|
+
if (key.startsWith(prefix)) this.presses.delete(key);
|
|
521
|
+
}
|
|
522
|
+
}
|
|
449
523
|
/** Makes `items` safe to mutate: a copy, if the current one was handed out. */
|
|
450
524
|
own() {
|
|
451
525
|
if (!this.shared) return;
|
|
@@ -460,6 +534,9 @@ var Timeline = class {
|
|
|
460
534
|
function emptied(message) {
|
|
461
535
|
return { ...message, body: {}, deletedAt: message.deletedAt ?? Date.now() };
|
|
462
536
|
}
|
|
537
|
+
function pairKey(messageId, emoji) {
|
|
538
|
+
return `${messageId}\0${emoji}`;
|
|
539
|
+
}
|
|
463
540
|
function createTimeline(options) {
|
|
464
541
|
return new Timeline(options);
|
|
465
542
|
}
|
|
@@ -659,17 +736,49 @@ var Room = class extends Emitter {
|
|
|
659
736
|
/**
|
|
660
737
|
* Adds a reaction. Idempotent, like the frame.
|
|
661
738
|
*
|
|
662
|
-
* The
|
|
663
|
-
*
|
|
739
|
+
* The row's `myReactions` moves **before the frame goes out** and rolls
|
|
740
|
+
* back if the server refuses; its count stays the server's. See
|
|
741
|
+
* `toggleReaction`.
|
|
664
742
|
*/
|
|
665
743
|
async react(messageId, emoji) {
|
|
666
|
-
await this.
|
|
667
|
-
this.timeline.reaction(messageId, emoji, void 0, true);
|
|
744
|
+
await this.toggleReaction(messageId, emoji, true);
|
|
668
745
|
}
|
|
669
|
-
/** Removes a reaction. Idempotent
|
|
746
|
+
/** Removes a reaction. Idempotent, and optimistic the same way `react` is. */
|
|
670
747
|
async unreact(messageId, emoji) {
|
|
671
|
-
await this.
|
|
672
|
-
|
|
748
|
+
await this.toggleReaction(messageId, emoji, false);
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* Moves `myReactions` now, sends the frame after.
|
|
752
|
+
*
|
|
753
|
+
* 누른 값은 (사용자, 이모지)로 로컬에서 정해지고 엔진은 멱등이므로 ack를
|
|
754
|
+
* 기다릴 이유가 없다 — 기다리면 누른 느낌이 왕복 시간만큼 늦는다. 소비자가
|
|
755
|
+
* 자기 낙관 계층을 덧대면 이 필드의 주인이 둘이 되므로, SDK가 한다.
|
|
756
|
+
* **발행은 다르다**: `before_publish` 훅이 본문을 바꿀 수 있어 미리 그릴 값이
|
|
757
|
+
* 로컬에 없다. 그래서 `send()`는 낙관적이지 않다.
|
|
758
|
+
*
|
|
759
|
+
* 개수는 옮기지 않는다. ack가 오기 전에 남이 같은 이모지를 누르면 로컬
|
|
760
|
+
* +1/-1은 서버가 보낸 수와 다른 값이 되고, 그것을 고칠 이벤트는 이미
|
|
761
|
+
* 지나갔다. 또 ack와 방 프레임은 다른 길로 와 순서가 없으므로, 늦게 온 내
|
|
762
|
+
* ack(count 1)가 앞서 온 남의 이벤트(count 2)를 되돌린다.
|
|
763
|
+
*
|
|
764
|
+
* 거절·타임아웃·끊김이면 되돌리지만, 그 사이 더 새로운 값이 자리를 차지했다면
|
|
765
|
+
* 두고 나온다(`Timeline.settleReaction`).
|
|
766
|
+
*/
|
|
767
|
+
async toggleReaction(messageId, emoji, mine) {
|
|
768
|
+
const press = this.timeline.pressReaction(messageId, emoji, mine);
|
|
769
|
+
try {
|
|
770
|
+
await this.chat.sendFrame("react", {
|
|
771
|
+
roomId: await this.resolveId("reacting"),
|
|
772
|
+
messageId,
|
|
773
|
+
emoji,
|
|
774
|
+
op: mine ? "add" : "remove"
|
|
775
|
+
});
|
|
776
|
+
} catch (err) {
|
|
777
|
+
if (press !== void 0) this.timeline.settleReaction(press, false);
|
|
778
|
+
throw err;
|
|
779
|
+
}
|
|
780
|
+
if (press !== void 0) this.timeline.settleReaction(press, true);
|
|
781
|
+
else this.timeline.reaction(messageId, emoji, void 0, mine);
|
|
673
782
|
}
|
|
674
783
|
/**
|
|
675
784
|
* Moves this user's read cursor.
|
|
@@ -681,7 +790,7 @@ var Room = class extends Emitter {
|
|
|
681
790
|
async markRead(seq, options = {}) {
|
|
682
791
|
const data = { roomId: await this.resolveId("marking read"), seq };
|
|
683
792
|
if (options.threadId !== void 0) data["threadId"] = options.threadId;
|
|
684
|
-
return await this.chat.
|
|
793
|
+
return await this.chat.sendFrame("read", data);
|
|
685
794
|
}
|
|
686
795
|
/**
|
|
687
796
|
* Says this user is typing.
|
|
@@ -699,7 +808,7 @@ var Room = class extends Emitter {
|
|
|
699
808
|
*/
|
|
700
809
|
typing() {
|
|
701
810
|
try {
|
|
702
|
-
void this.chat.
|
|
811
|
+
void this.chat.sendFrame("typing", { roomId: this.requireId("typing") }).catch(() => {
|
|
703
812
|
});
|
|
704
813
|
} catch {
|
|
705
814
|
}
|
|
@@ -733,6 +842,7 @@ var Room = class extends Emitter {
|
|
|
733
842
|
});
|
|
734
843
|
}
|
|
735
844
|
/**
|
|
845
|
+
* @internal
|
|
736
846
|
* Re-subscribes after a reconnect. Called by the client.
|
|
737
847
|
*
|
|
738
848
|
* The test is "was this room ever asked for", not "did the last
|
|
@@ -750,6 +860,7 @@ var Room = class extends Emitter {
|
|
|
750
860
|
await this.subscribe();
|
|
751
861
|
}
|
|
752
862
|
/**
|
|
863
|
+
* @internal
|
|
753
864
|
* Reports a failure no caller was waiting for, and repairs.
|
|
754
865
|
*
|
|
755
866
|
* 백그라운드 실패(재접속 뒤 다시 구독, 구멍 메우기)에는 거절을 받을 호출자가
|
|
@@ -780,13 +891,13 @@ var Room = class extends Emitter {
|
|
|
780
891
|
*/
|
|
781
892
|
async subscribeFrame(data) {
|
|
782
893
|
try {
|
|
783
|
-
return { ack: await this.chat.
|
|
894
|
+
return { ack: await this.chat.sendFrame("subscribe", data), wasReset: false };
|
|
784
895
|
} catch (err) {
|
|
785
896
|
if (err.code !== "cursor_too_old") throw err;
|
|
786
897
|
this.timeline.discard();
|
|
787
898
|
const retry = { ...data };
|
|
788
899
|
delete retry["since"];
|
|
789
|
-
return { ack: await this.chat.
|
|
900
|
+
return { ack: await this.chat.sendFrame("subscribe", retry), wasReset: true };
|
|
790
901
|
}
|
|
791
902
|
}
|
|
792
903
|
async unsubscribe() {
|
|
@@ -795,7 +906,7 @@ var Room = class extends Emitter {
|
|
|
795
906
|
this.subscribed = false;
|
|
796
907
|
this.generation++;
|
|
797
908
|
this.subscribing = void 0;
|
|
798
|
-
await this.chat.
|
|
909
|
+
await this.chat.sendFrame("unsubscribe", { roomId: this.id });
|
|
799
910
|
}
|
|
800
911
|
/**
|
|
801
912
|
* The room's id, or a refusal.
|
|
@@ -840,9 +951,9 @@ var Room = class extends Emitter {
|
|
|
840
951
|
if (input.replyTo !== void 0) frame["replyTo"] = input.replyTo;
|
|
841
952
|
if (input.threadId !== void 0) frame["threadId"] = input.threadId;
|
|
842
953
|
if (input.meta !== void 0) frame["meta"] = input.meta;
|
|
843
|
-
return await this.chat.
|
|
954
|
+
return await this.chat.sendFrame("publish", frame);
|
|
844
955
|
}
|
|
845
|
-
/** Routes a frame the client decided belongs to this room. */
|
|
956
|
+
/** @internal Routes a frame the client decided belongs to this room. */
|
|
846
957
|
handle(type, data) {
|
|
847
958
|
switch (type) {
|
|
848
959
|
case "message.created":
|
|
@@ -915,6 +1026,8 @@ var ChatClient = class extends Emitter {
|
|
|
915
1026
|
connectionId;
|
|
916
1027
|
hello;
|
|
917
1028
|
options;
|
|
1029
|
+
/** 소켓 주소. 상수이고, 테스트만 `endpoint`로 바꾼다. */
|
|
1030
|
+
socketURL;
|
|
918
1031
|
makeSocket;
|
|
919
1032
|
socket;
|
|
920
1033
|
heartbeat;
|
|
@@ -953,6 +1066,7 @@ var ChatClient = class extends Emitter {
|
|
|
953
1066
|
constructor(options) {
|
|
954
1067
|
super();
|
|
955
1068
|
this.options = options;
|
|
1069
|
+
this.socketURL = options.endpoint ?? ChatEndpoint;
|
|
956
1070
|
const ctor = options.WebSocket ?? globalThis.WebSocket;
|
|
957
1071
|
if (ctor === void 0) {
|
|
958
1072
|
throw new TypeError(
|
|
@@ -961,7 +1075,7 @@ var ChatClient = class extends Emitter {
|
|
|
961
1075
|
}
|
|
962
1076
|
this.makeSocket = ctor;
|
|
963
1077
|
this.rest = new Rest({
|
|
964
|
-
url:
|
|
1078
|
+
url: restURLFrom(this.socketURL),
|
|
965
1079
|
key: options.key,
|
|
966
1080
|
token: async () => this.lastToken,
|
|
967
1081
|
refreshToken: () => this.refreshToken(),
|
|
@@ -1036,17 +1150,23 @@ var ChatClient = class extends Emitter {
|
|
|
1036
1150
|
/**
|
|
1037
1151
|
* The unread totals across every room this user is a member of.
|
|
1038
1152
|
*
|
|
1039
|
-
*
|
|
1040
|
-
*
|
|
1041
|
-
*
|
|
1042
|
-
*
|
|
1043
|
-
*
|
|
1153
|
+
* `{total, mentions}` — `chat.hello.unread`와 **같은 이름**이다. 와이어는
|
|
1154
|
+
* 같은 두 숫자를 두 가지로 부르고(hello는 `total`/`mentions`, 이 라우트는
|
|
1155
|
+
* `unread`/`unreadMentions`), 그것을 그대로 넘기면 배지 하나를 그리는
|
|
1156
|
+
* 코드가 어디서 읽었느냐에 따라 다른 필드를 봐야 한다. 두 출처가 한 타입
|
|
1157
|
+
* (`UnreadCounts`)이면 그 분기가 아예 없다.
|
|
1044
1158
|
*
|
|
1045
1159
|
* `roomsCapped` means the totals cover a subset -- this route does not
|
|
1046
1160
|
* page, so past 500 rooms it stops counting and says so.
|
|
1047
1161
|
*/
|
|
1048
1162
|
async unread() {
|
|
1049
|
-
|
|
1163
|
+
const body = await this.rest.get("/v1/me/unread");
|
|
1164
|
+
return {
|
|
1165
|
+
total: body.unread,
|
|
1166
|
+
mentions: body.unreadMentions,
|
|
1167
|
+
...body.roomsCapped === void 0 ? {} : { roomsCapped: body.roomsCapped },
|
|
1168
|
+
rooms: (body.rooms ?? []).map((r) => ({ roomId: r.roomId, total: r.unread, mentions: r.unreadMentions }))
|
|
1169
|
+
};
|
|
1050
1170
|
}
|
|
1051
1171
|
/**
|
|
1052
1172
|
* Updates this user's own profile.
|
|
@@ -1087,6 +1207,7 @@ var ChatClient = class extends Emitter {
|
|
|
1087
1207
|
return room;
|
|
1088
1208
|
}
|
|
1089
1209
|
/**
|
|
1210
|
+
* @internal
|
|
1090
1211
|
* Files a room under its id once `subscribe` has resolved one.
|
|
1091
1212
|
*
|
|
1092
1213
|
* A room addressed by key is filed under `key:<key>`, and every push
|
|
@@ -1210,6 +1331,7 @@ var ChatClient = class extends Emitter {
|
|
|
1210
1331
|
this.emit("error", err);
|
|
1211
1332
|
}
|
|
1212
1333
|
/**
|
|
1334
|
+
* @internal
|
|
1213
1335
|
* Resolves once the connection is open. Used by `Room.subscribe`.
|
|
1214
1336
|
*
|
|
1215
1337
|
* 연결 전에 부른 `subscribe()`를 `closed`로 거절하면 소비자는 "언제 다시
|
|
@@ -1231,8 +1353,16 @@ var ChatClient = class extends Emitter {
|
|
|
1231
1353
|
else w.reject(err);
|
|
1232
1354
|
}
|
|
1233
1355
|
}
|
|
1234
|
-
/**
|
|
1235
|
-
|
|
1356
|
+
/**
|
|
1357
|
+
* @internal
|
|
1358
|
+
* Sends a raw frame and resolves with its ack, or rejects with its error.
|
|
1359
|
+
*
|
|
1360
|
+
* `Room`이 자기 프레임을 내보내는 통로다. 예전 이름은 `chat.send()`였고,
|
|
1361
|
+
* 그 이름은 `room.send()`(메시지 발행) 옆에서 "이걸로도 보낼 수 있나"로
|
|
1362
|
+
* 읽혔다 — 실제로는 와이어 프레임 이름을 직접 적는 탈출구라 계약이
|
|
1363
|
+
* 바뀌면 같이 깨진다. 1.0에서 얼릴 표면에 둘 것이 아니다.
|
|
1364
|
+
*/
|
|
1365
|
+
sendFrame(type, data, timeoutMs = 15e3) {
|
|
1236
1366
|
const socket = this.socket;
|
|
1237
1367
|
if (socket === void 0 || this.state !== "open") {
|
|
1238
1368
|
return Promise.reject(new ChatError("closed", `cannot send ${type}: the connection is ${this.state}`));
|
|
@@ -1286,7 +1416,7 @@ var ChatClient = class extends Emitter {
|
|
|
1286
1416
|
if (this.stopped) {
|
|
1287
1417
|
throw new ChatError("closed", "the client was closed while connecting");
|
|
1288
1418
|
}
|
|
1289
|
-
const socket = new this.makeSocket(`${this.
|
|
1419
|
+
const socket = new this.makeSocket(`${this.socketURL}/v1/ws?v=1`);
|
|
1290
1420
|
this.socket = socket;
|
|
1291
1421
|
return new Promise((resolve, reject) => {
|
|
1292
1422
|
let settled = false;
|
|
@@ -1448,10 +1578,6 @@ var ChatClient = class extends Emitter {
|
|
|
1448
1578
|
}
|
|
1449
1579
|
async authData() {
|
|
1450
1580
|
const data = { key: this.options.key };
|
|
1451
|
-
if (this.options.externalToken !== void 0) {
|
|
1452
|
-
data["externalToken"] = await this.options.externalToken();
|
|
1453
|
-
return data;
|
|
1454
|
-
}
|
|
1455
1581
|
const token = await this.options.token();
|
|
1456
1582
|
this.lastToken = token;
|
|
1457
1583
|
data["token"] = token;
|
|
@@ -1466,7 +1592,6 @@ var ChatClient = class extends Emitter {
|
|
|
1466
1592
|
* 각자 부르지 않도록 진행 중인 것 하나를 나눠 쓴다.
|
|
1467
1593
|
*/
|
|
1468
1594
|
refreshToken() {
|
|
1469
|
-
if (this.options.externalToken !== void 0) return Promise.resolve(void 0);
|
|
1470
1595
|
this.refreshing ??= (async () => {
|
|
1471
1596
|
try {
|
|
1472
1597
|
const token = await this.options.token();
|
|
@@ -1504,9 +1629,8 @@ function createChatClient(options) {
|
|
|
1504
1629
|
}
|
|
1505
1630
|
export {
|
|
1506
1631
|
ChatClient,
|
|
1632
|
+
ChatEndpoint,
|
|
1507
1633
|
ChatError,
|
|
1508
1634
|
Room,
|
|
1509
|
-
|
|
1510
|
-
createChatClient,
|
|
1511
|
-
createTimeline
|
|
1635
|
+
createChatClient
|
|
1512
1636
|
};
|
package/dist/server/index.cjs
CHANGED
|
@@ -28,6 +28,14 @@ __export(server_exports, {
|
|
|
28
28
|
});
|
|
29
29
|
module.exports = __toCommonJS(server_exports);
|
|
30
30
|
|
|
31
|
+
// src/endpoint.ts
|
|
32
|
+
var ChatEndpoint = "wss://api.chat.gravex.app";
|
|
33
|
+
function restURLFrom(socketURL) {
|
|
34
|
+
if (socketURL.startsWith("wss://")) return `https://${socketURL.slice("wss://".length)}`;
|
|
35
|
+
if (socketURL.startsWith("ws://")) return `http://${socketURL.slice("ws://".length)}`;
|
|
36
|
+
return socketURL;
|
|
37
|
+
}
|
|
38
|
+
|
|
31
39
|
// src/errors.ts
|
|
32
40
|
var ChatError = class extends Error {
|
|
33
41
|
code;
|
|
@@ -35,7 +43,13 @@ var ChatError = class extends Error {
|
|
|
35
43
|
retryAfterMs;
|
|
36
44
|
/** The consumer's own code, when a before_publish hook denied this. */
|
|
37
45
|
appCode;
|
|
38
|
-
/**
|
|
46
|
+
/**
|
|
47
|
+
* The HTTP status, when this came from a REST call.
|
|
48
|
+
*
|
|
49
|
+
* 읽기 전용이다. 이 값은 실패를 만든 응답의 성질이지 나중에 붙이는
|
|
50
|
+
* 꼬리표가 아니고, 쓸 수 있게 두면 소비자가 고쳐 쓴 상태가 SDK가
|
|
51
|
+
* 붙인 것과 구별되지 않는다.
|
|
52
|
+
*/
|
|
39
53
|
status;
|
|
40
54
|
constructor(code, message, extra) {
|
|
41
55
|
super(message);
|
|
@@ -43,9 +57,10 @@ var ChatError = class extends Error {
|
|
|
43
57
|
this.code = code;
|
|
44
58
|
if (extra?.retryAfterMs !== void 0) this.retryAfterMs = extra.retryAfterMs;
|
|
45
59
|
if (extra?.appCode !== void 0) this.appCode = extra.appCode;
|
|
60
|
+
if (extra?.status !== void 0) this.status = extra.status;
|
|
46
61
|
}
|
|
47
62
|
};
|
|
48
|
-
function errorFrom(data, fallback = "the server refused the request") {
|
|
63
|
+
function errorFrom(data, fallback = "the server refused the request", status) {
|
|
49
64
|
if (typeof data === "object" && data !== null) {
|
|
50
65
|
const d = data;
|
|
51
66
|
const inner = d["error"] ?? d;
|
|
@@ -54,9 +69,10 @@ function errorFrom(data, fallback = "the server refused the request") {
|
|
|
54
69
|
const extra = {};
|
|
55
70
|
if (typeof inner["retryAfterMs"] === "number") extra.retryAfterMs = inner["retryAfterMs"];
|
|
56
71
|
if (typeof inner["appCode"] === "string") extra.appCode = inner["appCode"];
|
|
72
|
+
if (status !== void 0) extra.status = status;
|
|
57
73
|
return new ChatError(code, message, extra);
|
|
58
74
|
}
|
|
59
|
-
return new ChatError("internal", fallback);
|
|
75
|
+
return new ChatError("internal", fallback, status === void 0 ? void 0 : { status });
|
|
60
76
|
}
|
|
61
77
|
|
|
62
78
|
// src/server/api.ts
|
|
@@ -235,17 +251,23 @@ function createChatServer(options) {
|
|
|
235
251
|
if (!options.secretKey.startsWith("sk_")) {
|
|
236
252
|
throw new TypeError("secretKey must be an sk_ key; a pk_ cannot sign tokens or reach server routes");
|
|
237
253
|
}
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
254
|
+
const keyId = keyIdFrom(options.secretKey);
|
|
255
|
+
const rest = new ServerRest(
|
|
256
|
+
restURLFrom(options.endpoint ?? ChatEndpoint),
|
|
257
|
+
options.secretKey,
|
|
258
|
+
options.fetch ?? globalThis.fetch.bind(globalThis)
|
|
259
|
+
);
|
|
242
260
|
const guestSecrets = options.guestSecret === void 0 ? [] : typeof options.guestSecret === "string" ? [options.guestSecret] : options.guestSecret;
|
|
243
261
|
for (const secret of guestSecrets) {
|
|
244
262
|
if (secret.length < MinGuestSecretLength) {
|
|
245
263
|
throw new RangeError(`guestSecret must be at least ${MinGuestSecretLength} characters`);
|
|
246
264
|
}
|
|
247
265
|
}
|
|
248
|
-
const sign = (input) => signHS256(
|
|
266
|
+
const sign = (input) => signHS256(
|
|
267
|
+
{ alg: "HS256", typ: "JWT", ...keyId === void 0 ? {} : { kid: keyId } },
|
|
268
|
+
tokenClaims(input, /* @__PURE__ */ new Date()),
|
|
269
|
+
options.secretKey
|
|
270
|
+
);
|
|
249
271
|
return {
|
|
250
272
|
token: sign,
|
|
251
273
|
guest(input) {
|
|
@@ -320,7 +342,7 @@ function createChatServer(options) {
|
|
|
320
342
|
// with 200 and `purgedMessages: 0`, the identity anonymized and
|
|
321
343
|
// the messages left standing. Nothing failed; the caller was told
|
|
322
344
|
// it had worked.
|
|
323
|
-
|
|
345
|
+
withdraw: (userId, o) => rest.call("DELETE", `/v1/users/${userId}${rest.query({ purge_messages: o?.purgeMessages ? "true" : void 0 })}`),
|
|
324
346
|
purgeMessages: (userId) => rest.call("DELETE", `/v1/users/${userId}/messages`),
|
|
325
347
|
revokeTokens: async (userId) => {
|
|
326
348
|
await rest.call("POST", `/v1/users/${userId}/revoke-tokens`);
|
|
@@ -352,6 +374,12 @@ function createChatServer(options) {
|
|
|
352
374
|
}
|
|
353
375
|
};
|
|
354
376
|
}
|
|
377
|
+
function keyIdFrom(secretKey) {
|
|
378
|
+
const parts = secretKey.split("_");
|
|
379
|
+
if (parts.length < 3) return void 0;
|
|
380
|
+
const id = parts[1];
|
|
381
|
+
return id !== void 0 && /^[0-9A-HJKMNP-TV-Z]{13}$/.test(id) ? id : void 0;
|
|
382
|
+
}
|
|
355
383
|
// Annotate the CommonJS export names for ESM import in node:
|
|
356
384
|
0 && (module.exports = {
|
|
357
385
|
DefaultTokenTtlSeconds,
|
package/dist/server/index.d.cts
CHANGED
|
@@ -58,20 +58,15 @@ type VerifyOptions = {
|
|
|
58
58
|
declare const GuestIdPrefix = "g_";
|
|
59
59
|
|
|
60
60
|
type ChatServerOptions = {
|
|
61
|
-
/** The chat server's base URL, e.g. `https://chat.example.com`. */
|
|
62
|
-
url: string;
|
|
63
|
-
/** An `sk_` key. Never ship this to a browser. */
|
|
64
|
-
secretKey: string;
|
|
65
61
|
/**
|
|
66
|
-
*
|
|
67
|
-
* `chat-server app create --json`.
|
|
62
|
+
* An `sk_` key. Never ship this to a browser.
|
|
68
63
|
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
64
|
+
* 키가 자기 id를 안에 들고 있다(`sk_<id>_<토큰>`). 그래서 토큰의
|
|
65
|
+
* `kid`를 이것에서 뽑는다 — 키 id를 따로 받던 옵션이 있던 동안, 그
|
|
66
|
+
* 둘이 어긋난 배포(키는 돌렸는데 id는 옛것)는 "서명은 맞는데 401"로만
|
|
67
|
+
* 보였고 그 둘을 대조할 방법이 소비자 쪽에 없었다.
|
|
73
68
|
*/
|
|
74
|
-
|
|
69
|
+
secretKey: string;
|
|
75
70
|
/** Needed only by `webhooks.verify`. */
|
|
76
71
|
webhookSecret?: string;
|
|
77
72
|
/**
|
|
@@ -251,11 +246,22 @@ type ChatServer = {
|
|
|
251
246
|
* Ban first (`ban`), then call this: a message posted while it runs is
|
|
252
247
|
* not in its listing. Bounded per call -- loop while `purgeCapped`.
|
|
253
248
|
* A withdrawn user is 404; their messages go with
|
|
254
|
-
* `
|
|
249
|
+
* `withdraw(userId, { purgeMessages: true })`.
|
|
255
250
|
*/
|
|
256
251
|
purgeMessages: (userId: string) => Promise<PurgeMessagesResult>;
|
|
257
|
-
/**
|
|
258
|
-
|
|
252
|
+
/**
|
|
253
|
+
* 탈퇴. 행을 지우는 것이 아니라 **익명화**한다.
|
|
254
|
+
*
|
|
255
|
+
* 이름이 `delete`였을 때 그것은 옆의 `rooms.delete`·`messages.delete`와
|
|
256
|
+
* 같은 말로 읽혔고, 그 둘은 정말로 없앤다. 여기서 남는 것은 메시지다
|
|
257
|
+
* — `purgeMessages: true`를 주지 않으면 그 사람이 쓴 글은 그대로
|
|
258
|
+
* 있고, 그 차이를 이름이 감추고 있었다. `withdraw`는 무엇이 일어나는지
|
|
259
|
+
* 말하고, 지우는 쪽을 고르라고 한다.
|
|
260
|
+
*
|
|
261
|
+
* `purgeMessages: true`는 상한까지만 지운다. 끝까지 지우려면
|
|
262
|
+
* `purgeMessages(userId)`를 `purgeCapped`가 `false`가 될 때까지 부른다.
|
|
263
|
+
*/
|
|
264
|
+
withdraw: (userId: string, options?: {
|
|
259
265
|
purgeMessages?: boolean;
|
|
260
266
|
}) => Promise<unknown>;
|
|
261
267
|
revokeTokens: (userId: string) => Promise<void>;
|
package/dist/server/index.d.ts
CHANGED
|
@@ -58,20 +58,15 @@ type VerifyOptions = {
|
|
|
58
58
|
declare const GuestIdPrefix = "g_";
|
|
59
59
|
|
|
60
60
|
type ChatServerOptions = {
|
|
61
|
-
/** The chat server's base URL, e.g. `https://chat.example.com`. */
|
|
62
|
-
url: string;
|
|
63
|
-
/** An `sk_` key. Never ship this to a browser. */
|
|
64
|
-
secretKey: string;
|
|
65
61
|
/**
|
|
66
|
-
*
|
|
67
|
-
* `chat-server app create --json`.
|
|
62
|
+
* An `sk_` key. Never ship this to a browser.
|
|
68
63
|
*
|
|
69
|
-
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
72
|
-
*
|
|
64
|
+
* 키가 자기 id를 안에 들고 있다(`sk_<id>_<토큰>`). 그래서 토큰의
|
|
65
|
+
* `kid`를 이것에서 뽑는다 — 키 id를 따로 받던 옵션이 있던 동안, 그
|
|
66
|
+
* 둘이 어긋난 배포(키는 돌렸는데 id는 옛것)는 "서명은 맞는데 401"로만
|
|
67
|
+
* 보였고 그 둘을 대조할 방법이 소비자 쪽에 없었다.
|
|
73
68
|
*/
|
|
74
|
-
|
|
69
|
+
secretKey: string;
|
|
75
70
|
/** Needed only by `webhooks.verify`. */
|
|
76
71
|
webhookSecret?: string;
|
|
77
72
|
/**
|
|
@@ -251,11 +246,22 @@ type ChatServer = {
|
|
|
251
246
|
* Ban first (`ban`), then call this: a message posted while it runs is
|
|
252
247
|
* not in its listing. Bounded per call -- loop while `purgeCapped`.
|
|
253
248
|
* A withdrawn user is 404; their messages go with
|
|
254
|
-
* `
|
|
249
|
+
* `withdraw(userId, { purgeMessages: true })`.
|
|
255
250
|
*/
|
|
256
251
|
purgeMessages: (userId: string) => Promise<PurgeMessagesResult>;
|
|
257
|
-
/**
|
|
258
|
-
|
|
252
|
+
/**
|
|
253
|
+
* 탈퇴. 행을 지우는 것이 아니라 **익명화**한다.
|
|
254
|
+
*
|
|
255
|
+
* 이름이 `delete`였을 때 그것은 옆의 `rooms.delete`·`messages.delete`와
|
|
256
|
+
* 같은 말로 읽혔고, 그 둘은 정말로 없앤다. 여기서 남는 것은 메시지다
|
|
257
|
+
* — `purgeMessages: true`를 주지 않으면 그 사람이 쓴 글은 그대로
|
|
258
|
+
* 있고, 그 차이를 이름이 감추고 있었다. `withdraw`는 무엇이 일어나는지
|
|
259
|
+
* 말하고, 지우는 쪽을 고르라고 한다.
|
|
260
|
+
*
|
|
261
|
+
* `purgeMessages: true`는 상한까지만 지운다. 끝까지 지우려면
|
|
262
|
+
* `purgeMessages(userId)`를 `purgeCapped`가 `false`가 될 때까지 부른다.
|
|
263
|
+
*/
|
|
264
|
+
withdraw: (userId: string, options?: {
|
|
259
265
|
purgeMessages?: boolean;
|
|
260
266
|
}) => Promise<unknown>;
|
|
261
267
|
revokeTokens: (userId: string) => Promise<void>;
|