@kispi/chat 0.2.3 → 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 +46 -46
- package/README.md +43 -45
- package/dist/{chunk-5QQRM7BH.js → chunk-WSBOTTBM.js} +21 -3
- package/dist/index.cjs +63 -40
- package/dist/index.d.cts +141 -388
- package/dist/index.d.ts +141 -388
- package/dist/index.js +46 -36
- 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/README.en.md
CHANGED
|
@@ -10,7 +10,8 @@ There are two entry points. `@kispi/chat` is the client for the browser and Node
|
|
|
10
10
|
npm install @kispi/chat
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
This document covers **the entire surface**.
|
|
13
|
+
This document covers **the entire surface**. Anything not here is internal and
|
|
14
|
+
changes without notice. How to get started is here too.
|
|
14
15
|
|
|
15
16
|
---
|
|
16
17
|
|
|
@@ -20,17 +21,20 @@ This document covers **the entire surface**. How to get started is here too.
|
|
|
20
21
|
|
|
21
22
|
| Option | Type | |
|
|
22
23
|
|---|---|---|
|
|
23
|
-
| `url` | `string` | **Required.** Pass the origin only. The SDK appends `/v1/ws?v=1` |
|
|
24
24
|
| `key` | `string` | **Required.** A `pk_`. It is public, so it is fine to put in the browser |
|
|
25
25
|
| `token` | `() => string \| Promise<string>` | **Required.** A user token signed by your backend. Called again on every connect and whenever REST gets a 401, so an expired one is never reused. A throw is retried with backoff; **throwing a `ChatError` means do not retry** (see below) |
|
|
26
|
-
| `
|
|
27
|
-
| `externalToken` | `() => string \| Promise<string>` | External mode. If given, it **takes precedence over `token`** (same order the server checks in). **The server still rejects it, so there is no use for it today** |
|
|
28
|
-
| `WebSocket` | `new (url) => WebSocketLike` | Implementation to use instead of the global. Injected in tests |
|
|
26
|
+
| `WebSocket` | `new (url) => WebSocketLike` | Implementation to use instead of the global |
|
|
29
27
|
| `fetch` | `typeof fetch` | Same as above |
|
|
30
28
|
|
|
31
29
|
Do not create `token` in the browser. Signing requires the `sk_`, and if the `sk_`
|
|
32
30
|
is in the browser, the whole app is open.
|
|
33
31
|
|
|
32
|
+
**You do not configure the address.** There is one engine, `wss://api.chat.gravex.app`,
|
|
33
|
+
and the SDK holds it as a constant (readable as `ChatEndpoint`). REST is the same
|
|
34
|
+
place with the scheme swapped. To separate development from production, **create a
|
|
35
|
+
separate app in the console**: different apps have different `pk_`/`sk_`, rooms and
|
|
36
|
+
users, which is the separation you actually want.
|
|
37
|
+
|
|
34
38
|
### `ChatClient`
|
|
35
39
|
|
|
36
40
|
| Property | |
|
|
@@ -38,7 +42,7 @@ is in the browser, the whole app is open.
|
|
|
38
42
|
| `state` | `'connecting' \| 'open' \| 'reconnecting' \| 'closed'` |
|
|
39
43
|
| `user` | The connected user. `{id, name, avatar?}` — **the identity the server accepted from the token** (what `hello` carried). Use this instead of parsing your token response. Set once `connect()`/`reconnect()` resolves |
|
|
40
44
|
| `connectionId` | Identifier used for support requests and forced disconnects |
|
|
41
|
-
| `hello` | Everything the server sent on connect (
|
|
45
|
+
| `hello` | Everything the server sent on connect: `limits` (effective), `unread` (`{total, mentions, roomsCapped?}` — **absent is not zero, it means the count could not be read**, so recover with `unread()`), `warnings`, `serverTime`, `heartbeatMs` |
|
|
42
46
|
|
|
43
47
|
| Method | |
|
|
44
48
|
|---|---|
|
|
@@ -50,9 +54,8 @@ is in the browser, the whole app is open.
|
|
|
50
54
|
| `rooms.list({cursor?, limit?})` | Rooms I'm a member of + unread + last message |
|
|
51
55
|
| `rooms.discover({type?, cursor?, limit?})` | Browse public rooms |
|
|
52
56
|
| `rooms.members(roomId).list/add/remove` | Member management |
|
|
53
|
-
| `unread()` |
|
|
57
|
+
| `unread()` | `{total, mentions, roomsCapped?, rooms}` — the **same field names** as `chat.hello?.unread` |
|
|
54
58
|
| `updateMe(meta)` | My `meta`. **`name` and `avatar` come from the token claims** |
|
|
55
|
-
| `send(type, data?, timeoutMs?)` | Raw frame. Only for calling things not on the surface |
|
|
56
59
|
|
|
57
60
|
| Event | |
|
|
58
61
|
|---|---|
|
|
@@ -93,12 +96,23 @@ off()
|
|
|
93
96
|
| `typing()` | Typing indicator. Does not throw |
|
|
94
97
|
| `join()` / `leave()` | Membership |
|
|
95
98
|
| `presenceList()` | Who is in this room right now |
|
|
96
|
-
| `resume()` | Resubscribes after reconnecting. The SDK calls it for you |
|
|
97
99
|
|
|
98
|
-
Event names are **exactly the wire names
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
100
|
+
Event names are **exactly the wire names**, and the payloads are typed after the
|
|
101
|
+
shapes in `docs/protocol.md`.
|
|
102
|
+
|
|
103
|
+
| Event | Payload |
|
|
104
|
+
|---|---|
|
|
105
|
+
| `message.created` / `message.updated` | `Message`. On `created`, `thread` is absent and `reactions` is empty |
|
|
106
|
+
| `message.deleted` | `{id, seq}`. `seq` is the one the message got **when it was published** |
|
|
107
|
+
| `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}` |
|
|
108
|
+
| `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
|
|
109
|
+
| `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left` are incremental, `users` replaces |
|
|
110
|
+
| `typing` | `{userId}` |
|
|
111
|
+
| `read` | `{userId, seq, threadId?}` |
|
|
112
|
+
| `member.joined` / `member.left` | `{userId, role?}` |
|
|
113
|
+
| `room.updated` | The room object (`unknown` — the server's own representation) |
|
|
114
|
+
| `room.deleted` | `{roomId}` |
|
|
115
|
+
| `custom` | Exactly the object `rooms.custom(roomId, payload)` sent |
|
|
102
116
|
|
|
103
117
|
The SDK emits three more that have no wire counterpart.
|
|
104
118
|
|
|
@@ -132,9 +146,7 @@ const messages = shallowRef<Message[]>([])
|
|
|
132
146
|
room.on('messages', m => (messages.value = m))
|
|
133
147
|
```
|
|
134
148
|
|
|
135
|
-
Wrapping it in `$state` (a deep proxy) or `ref` works, but does unnecessary work.
|
|
136
|
-
modified the same array in place and emitted it again, so on the reference-comparing side
|
|
137
|
-
the screen froze.
|
|
149
|
+
Wrapping it in `$state` (a deep proxy) or `ref` works, but does unnecessary work.
|
|
138
150
|
|
|
139
151
|
**Reactions: `reactions` is everyone's counts, `myReactions` is the emoji you pressed.**
|
|
140
152
|
The SDK keeps both live — counts from the `count` on `reaction.*` events, `myReactions` from
|
|
@@ -192,10 +204,10 @@ immediately with `closed`. Publishing while `chat.state` is `reconnecting` also
|
|
|
192
204
|
**Opening by key does not create a room.** `roomByKey(key).subscribe()` only looks up an
|
|
193
205
|
existing room, and if there is none it's `not_found`. Rooms are created by the backend with
|
|
194
206
|
the `sk_` (`rooms.ensure({key, type})` in `@kispi/chat/server` — it's get-or-create, returning
|
|
195
|
-
the room as-is if it exists, so it's fine to call on every page load).
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
207
|
+
the room as-is if it exists, so it's fine to call on every page load). There is an app setting
|
|
208
|
+
that lets user tokens create rooms, but it is off by default and can't be turned on from the
|
|
209
|
+
console — since the `pk_` is public, turning it on opens a door through which anyone can stamp
|
|
210
|
+
out rooms.
|
|
199
211
|
|
|
200
212
|
**The connection comes back on its own.** If the socket drops or `token()` throws, it
|
|
201
213
|
reconnects with exponential backoff (0.5 s up to 30 s, with jitter). **The first `connect()`
|
|
@@ -296,10 +308,11 @@ If the origin isn't on the list, REST rejects with 401, and the message states t
|
|
|
296
308
|
origin not allowed for this publishable key: add it to the key's allowed_origins
|
|
297
309
|
```
|
|
298
310
|
|
|
299
|
-
**
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
311
|
+
**The connection consults the same list.** WebSocket isn't subject to browser CORS, but the
|
|
312
|
+
engine checks the `pk_`'s `allowed_origins` itself during the handshake. So from an origin
|
|
313
|
+
that isn't on the list, it isn't just REST that fails — the connection is refused too, and an
|
|
314
|
+
authentication refusal is a failure the SDK doesn't retry, so the client stops at `closed`.
|
|
315
|
+
The reason arrives on `chat.on('error')`.
|
|
303
316
|
|
|
304
317
|
### Errors
|
|
305
318
|
|
|
@@ -317,7 +330,7 @@ try {
|
|
|
317
330
|
|
|
318
331
|
| Field | |
|
|
319
332
|
|---|---|
|
|
320
|
-
| `code` | `unauthorized`, `
|
|
333
|
+
| `code` | A union of the known values (`ChatErrorCode`), so a typo fails to compile. From the server: `unauthorized`, `forbidden`, `not_found`, `invalid`, `too_large`, `rate_limited`, `banned`, `moderation_denied`, `cursor_too_old`, `internal`. From the SDK: `timeout`, `closed`. A code the server adds later still type-checks |
|
|
321
334
|
| `retryAfterMs` | Wait time reported by the server when you hit a limit |
|
|
322
335
|
| `appCode` | Consumer-side code attached by a `before_publish` webhook when rejecting |
|
|
323
336
|
| `status` | HTTP status, if the error came from a REST call |
|
|
@@ -332,14 +345,16 @@ Uses the `sk_`. **Never put it in the browser.**
|
|
|
332
345
|
import { createChatServer } from '@kispi/chat/server'
|
|
333
346
|
|
|
334
347
|
const chat = createChatServer({
|
|
335
|
-
|
|
336
|
-
secretKey: process.env.CHAT_SECRET_KEY!,
|
|
337
|
-
keyId: process.env.CHAT_KEY_ID!,
|
|
348
|
+
secretKey: process.env.CHAT_SECRET_KEY!, // sk_…
|
|
338
349
|
webhookSecret: process.env.CHAT_WEBHOOK_SECRET,
|
|
339
350
|
guestSecret: process.env.CHAT_GUEST_SECRET, // only if you use guest()
|
|
340
351
|
})
|
|
341
352
|
```
|
|
342
353
|
|
|
354
|
+
One key is all it takes. The value that tells the server which key signed a token
|
|
355
|
+
(`kid`) lives inside the `sk_`, so the SDK reads it from there — you do not pass
|
|
356
|
+
the console's key ID separately. The address is a constant here too.
|
|
357
|
+
|
|
343
358
|
### `chat.token(input): string`
|
|
344
359
|
|
|
345
360
|
A local signature that doesn't touch the network.
|
|
@@ -392,9 +407,9 @@ spaces don't overlap.
|
|
|
392
407
|
|---|---|
|
|
393
408
|
| `rooms` | `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
|
|
394
409
|
| `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
|
|
395
|
-
| `users` | `list({cursor?, limit?})`, `update`, `
|
|
410
|
+
| `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?})` |
|
|
396
411
|
| `events` | `list({after?, limit?})` — the outbox. Catches up on missed webhooks |
|
|
397
|
-
| `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` |
|
|
412
|
+
| `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` — `tolerance` is in milliseconds |
|
|
398
413
|
|
|
399
414
|
`rooms.presence(roomId)` is `{count}`; with `{full: true}` it adds `users` (at most 1000,
|
|
400
415
|
`capped: true` when cut). An empty room is `{count: 0}`, not a 404.
|
|
@@ -403,7 +418,7 @@ spaces don't overlap.
|
|
|
403
418
|
app (tombstones: seq is untouched, and watching clients get `message.deleted`) **without
|
|
404
419
|
withdrawing them.** The name stays. For spam, **ban first**, then call it — a message posted
|
|
405
420
|
while it runs is not in its listing. It does a bounded amount per call, so call again while
|
|
406
|
-
`purgeCapped` is `true`. A withdrawn user is a 404 (use `
|
|
421
|
+
`purgeCapped` is `true`. A withdrawn user is a 404 (use `withdraw(userId, {purgeMessages: true})`).
|
|
407
422
|
|
|
408
423
|
```ts
|
|
409
424
|
await chat.users.ban(userId, { until: Date.now() + 7 * 86_400_000, reason: 'spam' })
|
|
@@ -451,18 +466,3 @@ outside the signature, a single captured delivery could be counted as any number
|
|
|
451
466
|
Keep three things. `verify` checks the signature and the timestamp (default 5 minutes),
|
|
452
467
|
**deduplication is on you** (by `delivery`), and you must respond with a 2xx within 10 seconds.
|
|
453
468
|
Going over counts as a failure and backoff begins.
|
|
454
|
-
|
|
455
|
-
---
|
|
456
|
-
|
|
457
|
-
## Development
|
|
458
|
-
|
|
459
|
-
```sh
|
|
460
|
-
pnpm install
|
|
461
|
-
pnpm build # ESM + CJS + type declarations
|
|
462
|
-
pnpm exec vitest run
|
|
463
|
-
pnpm exec tsc --noEmit
|
|
464
|
-
```
|
|
465
|
-
|
|
466
|
-
Tests use **injection**, not mocks. Swapping in `WebSocket` and `fetch` means there's no need to
|
|
467
|
-
imitate the server, and the integration-style files connect to a **live server** outright.
|
|
468
|
-
Running them requires Postgres and Redis.
|
package/README.md
CHANGED
|
@@ -10,7 +10,8 @@
|
|
|
10
10
|
npm install @kispi/chat
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
이 문서가 **표면 전체**를 적는다.
|
|
13
|
+
이 문서가 **표면 전체**를 적는다. 여기 없는 것은 내부 구현이고, 다음 버전에
|
|
14
|
+
말 없이 바뀐다. 시작하는 법도 여기 있다.
|
|
14
15
|
|
|
15
16
|
---
|
|
16
17
|
|
|
@@ -20,17 +21,19 @@ npm install @kispi/chat
|
|
|
20
21
|
|
|
21
22
|
| 옵션 | 타입 | |
|
|
22
23
|
|---|---|---|
|
|
23
|
-
| `url` | `string` | **필수.** 오리진만 준다. SDK가 `/v1/ws?v=1`을 붙인다 |
|
|
24
24
|
| `key` | `string` | **필수.** `pk_`. 공개값이라 브라우저에 넣어도 된다 |
|
|
25
25
|
| `token` | `() => string \| Promise<string>` | **필수.** 백엔드가 서명한 유저 토큰. 접속할 때마다, 그리고 REST가 401을 받을 때 다시 부르므로 만료된 것이 재사용되지 않는다. 던지면 백오프로 다시 부르고, **`ChatError`를 던지면 다시 부르지 않는다**(아래) |
|
|
26
|
-
| `
|
|
27
|
-
| `externalToken` | `() => string \| Promise<string>` | external 모드. 주면 **`token`보다 우선한다**(서버의 판정 순서와 같다). **서버가 아직 거절하므로 오늘은 쓸 곳이 없다** |
|
|
28
|
-
| `WebSocket` | `new (url) => WebSocketLike` | 전역 대신 쓸 구현. 테스트에서 주입한다 |
|
|
26
|
+
| `WebSocket` | `new (url) => WebSocketLike` | 전역 대신 쓸 구현 |
|
|
29
27
|
| `fetch` | `typeof fetch` | 위와 같음 |
|
|
30
28
|
|
|
31
29
|
`token`을 브라우저에서 만들지 않는다. 서명에 `sk_`가 필요하고, `sk_`가
|
|
32
30
|
브라우저에 있으면 그 앱 전체가 열린다.
|
|
33
31
|
|
|
32
|
+
**주소는 설정하지 않는다.** 엔진은 `wss://api.chat.gravex.app` 하나이고
|
|
33
|
+
SDK가 상수로 들고 있다(`ChatEndpoint`로 읽을 수 있다). REST도 같은 곳이다 —
|
|
34
|
+
스킴만 바뀐다. 개발용과 운영용을 나누려면 **콘솔에서 앱을 따로 만든다**:
|
|
35
|
+
앱이 다르면 `pk_`·`sk_`·방·유저가 전부 다르고, 그것이 실제로 원하는 분리다.
|
|
36
|
+
|
|
34
37
|
### `ChatClient`
|
|
35
38
|
|
|
36
39
|
| 프로퍼티 | |
|
|
@@ -38,7 +41,7 @@ npm install @kispi/chat
|
|
|
38
41
|
| `state` | `'connecting' \| 'open' \| 'reconnecting' \| 'closed'` |
|
|
39
42
|
| `user` | 접속한 사람. `{id, name, avatar?}` — **서버가 토큰에서 받아들인 신원**(hello가 준 것)이다. 토큰 응답을 따로 파싱하지 말고 이것을 쓴다. `connect()`/`reconnect()`가 끝나면 채워져 있다 |
|
|
40
43
|
| `connectionId` | 지원 문의와 강제 종료에 쓰는 식별자 |
|
|
41
|
-
| `hello` | 서버가 접속 때 준 것
|
|
44
|
+
| `hello` | 서버가 접속 때 준 것 전부. `limits`(실효 한도), `unread`(`{total, mentions, roomsCapped?}`, **없는 것은 0이 아니라 '못 셌다'이니 `unread()`로 복구한다**), `warnings`, `serverTime`, `heartbeatMs` |
|
|
42
45
|
|
|
43
46
|
| 메서드 | |
|
|
44
47
|
|---|---|
|
|
@@ -50,9 +53,8 @@ npm install @kispi/chat
|
|
|
50
53
|
| `rooms.list({cursor?, limit?})` | 내가 멤버인 방 + unread + 마지막 메시지 |
|
|
51
54
|
| `rooms.discover({type?, cursor?, limit?})` | 공개 방 탐색 |
|
|
52
55
|
| `rooms.members(roomId).list/add/remove` | 멤버 관리 |
|
|
53
|
-
| `unread()` |
|
|
56
|
+
| `unread()` | `{total, mentions, roomsCapped?, rooms}`. `chat.hello?.unread`와 **같은 이름**이다 |
|
|
54
57
|
| `updateMe(meta)` | 내 `meta`. **`name`과 `avatar`는 토큰 claim에서 온다** |
|
|
55
|
-
| `send(type, data?, timeoutMs?)` | 날 프레임. 표면에 없는 것을 부를 때만 |
|
|
56
58
|
|
|
57
59
|
| 이벤트 | |
|
|
58
60
|
|---|---|
|
|
@@ -93,12 +95,23 @@ off()
|
|
|
93
95
|
| `typing()` | 입력 중. 던지지 않는다 |
|
|
94
96
|
| `join()` / `leave()` | 멤버십 |
|
|
95
97
|
| `presenceList()` | 지금 이 방에 있는 사람 |
|
|
96
|
-
| `resume()` | 재접속 후 다시 구독. SDK가 알아서 부른다 |
|
|
97
98
|
|
|
98
|
-
이벤트 이름은 **와이어의 이름 그대로**다.
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
99
|
+
이벤트 이름은 **와이어의 이름 그대로**다. 페이로드는 `docs/protocol.md`의
|
|
100
|
+
모양대로 타입이 붙어 있다.
|
|
101
|
+
|
|
102
|
+
| 이벤트 | 페이로드 |
|
|
103
|
+
|---|---|
|
|
104
|
+
| `message.created` / `message.updated` | `Message`. `created`에는 `thread`가 없고 `reactions`가 비어 있다 |
|
|
105
|
+
| `message.deleted` | `{id, seq}`. `seq`는 그 메시지가 **발행될 때** 받은 값이다 |
|
|
106
|
+
| `reaction.added` / `reaction.removed` | `{messageId, emoji, count, userId?}` |
|
|
107
|
+
| `thread.updated` | `{rootId, count, lastSeq?, lastAt?}` |
|
|
108
|
+
| `presence` | `{count, joined?, left?, users?, capped?}`. `joined`/`left`는 증분, `users`는 교체다 |
|
|
109
|
+
| `typing` | `{userId}` |
|
|
110
|
+
| `read` | `{userId, seq, threadId?}` |
|
|
111
|
+
| `member.joined` / `member.left` | `{userId, role?}` |
|
|
112
|
+
| `room.updated` | 방 객체(`unknown` — 서버 표현 그대로다) |
|
|
113
|
+
| `room.deleted` | `{roomId}` |
|
|
114
|
+
| `custom` | `rooms.custom(roomId, payload)`이 보낸 객체 그대로 |
|
|
102
115
|
|
|
103
116
|
와이어에 대응물이 없는 셋을 SDK가 더 낸다.
|
|
104
117
|
|
|
@@ -131,8 +144,7 @@ const messages = shallowRef<Message[]>([])
|
|
|
131
144
|
room.on('messages', m => (messages.value = m))
|
|
132
145
|
```
|
|
133
146
|
|
|
134
|
-
`$state`(깊은 프록시)나 `ref`로 감싸도 동작하지만 필요 없는 일을 한다.
|
|
135
|
-
배열을 제자리에서 고쳐 다시 내보내서, 참조로 비교하는 쪽에서는 화면이 멈췄다.
|
|
147
|
+
`$state`(깊은 프록시)나 `ref`로 감싸도 동작하지만 필요 없는 일을 한다.
|
|
136
148
|
|
|
137
149
|
**리액션: `reactions`는 모두의 개수, `myReactions`는 내가 누른 이모지다.** 둘 다
|
|
138
150
|
SDK가 라이브로 맞춘다 — 개수는 `reaction.*` 이벤트의 `count`로, `myReactions`는 그
|
|
@@ -186,10 +198,9 @@ const { hasMore } = await room.loadOlder()
|
|
|
186
198
|
**키로 연다고 방이 생기지 않는다.** `roomByKey(key).subscribe()`는 있는 방을 찾기만
|
|
187
199
|
하고, 없으면 `not_found`다. 방은 백엔드가 `sk_`로 만든다
|
|
188
200
|
(`@kispi/chat/server`의 `rooms.ensure({key, type})` — 있으면 그대로 돌려주는
|
|
189
|
-
get-or-create라 페이지를 열 때마다 불러도 된다).
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
끄는 쪽을 권한다.
|
|
201
|
+
get-or-create라 페이지를 열 때마다 불러도 된다). 유저 토큰으로 방을 만들게 하는 앱 설정도
|
|
202
|
+
있지만 기본은 꺼져 있고 콘솔에서 켤 수 없다 — `pk_`는 공개값이라, 켜면 누구나 방을
|
|
203
|
+
찍어낼 수 있는 문이 된다.
|
|
193
204
|
|
|
194
205
|
**연결은 알아서 돌아온다.** 소켓이 끊기거나 `token()`이 던지면 지수 백오프(0.5초에서
|
|
195
206
|
30초까지, 지터)로 다시 붙는다. **첫 `connect()`도 같다** — 실패하면 `await`는 거절해서
|
|
@@ -285,10 +296,10 @@ chat-server key create <app-id> pk --origins https://staging.example.com
|
|
|
285
296
|
origin not allowed for this publishable key: add it to the key's allowed_origins
|
|
286
297
|
```
|
|
287
298
|
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
REST
|
|
291
|
-
|
|
299
|
+
**접속도 같은 목록을 본다.** WebSocket은 브라우저 CORS의 대상이 아니지만, 엔진이
|
|
300
|
+
핸드셰이크에서 `pk_`의 `allowed_origins`를 직접 검사한다. 그래서 목록에 없는
|
|
301
|
+
오리진에서는 REST만이 아니라 접속부터 막히고, 인증 거절은 SDK가 다시 시도하지 않는
|
|
302
|
+
실패라 클라이언트가 `closed`에서 멈춘다 — 이유는 `chat.on('error')`로 온다.
|
|
292
303
|
|
|
293
304
|
### 에러
|
|
294
305
|
|
|
@@ -306,7 +317,7 @@ try {
|
|
|
306
317
|
|
|
307
318
|
| 필드 | |
|
|
308
319
|
|---|---|
|
|
309
|
-
| `code` | `unauthorized`, `
|
|
320
|
+
| `code` | 알려진 값의 유니온(`ChatErrorCode`)이라 오타가 컴파일에서 잡힌다. 서버: `unauthorized`, `forbidden`, `not_found`, `invalid`, `too_large`, `rate_limited`, `banned`, `moderation_denied`, `cursor_too_old`, `internal`. SDK: `timeout`, `closed`. 서버가 새 코드를 내도 좁혀 놓은 타입이 막지 않는다 |
|
|
310
321
|
| `retryAfterMs` | 한도에 걸렸을 때 서버가 알려 준 대기 시간 |
|
|
311
322
|
| `appCode` | `before_publish` 웹훅이 거절하며 붙인 소비자 쪽 코드 |
|
|
312
323
|
| `status` | REST 호출에서 난 에러면 HTTP 상태 |
|
|
@@ -321,14 +332,16 @@ try {
|
|
|
321
332
|
import { createChatServer } from '@kispi/chat/server'
|
|
322
333
|
|
|
323
334
|
const chat = createChatServer({
|
|
324
|
-
|
|
325
|
-
secretKey: process.env.CHAT_SECRET_KEY!,
|
|
326
|
-
keyId: process.env.CHAT_KEY_ID!,
|
|
335
|
+
secretKey: process.env.CHAT_SECRET_KEY!, // sk_…
|
|
327
336
|
webhookSecret: process.env.CHAT_WEBHOOK_SECRET,
|
|
328
337
|
guestSecret: process.env.CHAT_GUEST_SECRET, // guest()를 쓸 때만
|
|
329
338
|
})
|
|
330
339
|
```
|
|
331
340
|
|
|
341
|
+
키 하나면 된다. 어느 키로 서명했는지를 서버에 알리는 값(`kid`)은 `sk_`
|
|
342
|
+
안에 들어 있어서 SDK가 거기서 읽는다 — 콘솔의 키 ID를 따로 넣지 않는다.
|
|
343
|
+
주소도 클라이언트와 같이 상수다.
|
|
344
|
+
|
|
332
345
|
### `chat.token(input): string`
|
|
333
346
|
|
|
334
347
|
네트워크를 타지 않는 로컬 서명이다.
|
|
@@ -380,9 +393,9 @@ app.post('/api/chat-token', (req, res) => {
|
|
|
380
393
|
|---|---|
|
|
381
394
|
| `rooms` | `ensure({key?, type, name?, meta?, members?})`, `ensureDM([a, b])`, `get`, `update`, `delete`, `custom(roomId, payload)`, `presence(roomId, {full?})`, `members.list/add/remove` |
|
|
382
395
|
| `messages` | `send(roomId, {sender, text?, kind?, attachments?, appMeta?, replyTo?, threadId?, clientMessageId?})`, `list`, `delete` |
|
|
383
|
-
| `users` | `list({cursor?, limit?})`, `update`, `
|
|
396
|
+
| `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?})` |
|
|
384
397
|
| `events` | `list({after?, limit?})` — outbox. 놓친 웹훅을 따라잡는다 |
|
|
385
|
-
| `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` |
|
|
398
|
+
| `webhooks` | `verify(headers, rawBody, {now?, tolerance?})` — `tolerance`는 밀리초 |
|
|
386
399
|
|
|
387
400
|
`rooms.presence(roomId)`는 `{count}`이고, `{full: true}`면 `users`(최대 1000명, 잘리면
|
|
388
401
|
`capped: true`)가 붙는다. 빈 방은 404가 아니라 `{count: 0}`이다.
|
|
@@ -391,7 +404,7 @@ app.post('/api/chat-token', (req, res) => {
|
|
|
391
404
|
전부 지우되(tombstone: seq는 그대로, 보고 있는 클라이언트에는 `message.deleted`가
|
|
392
405
|
간다) **탈퇴시키지 않는다.** 이름도 남는다. 스팸이면 **밴을 먼저** 하고 부른다 — 도는
|
|
393
406
|
사이에 올라온 메시지는 목록에 없다. 한 번에 상한만큼만 하므로 `purgeCapped`가
|
|
394
|
-
`true`인 동안 다시 부른다. 탈퇴한 유저는 404다(그때는 `
|
|
407
|
+
`true`인 동안 다시 부른다. 탈퇴한 유저는 404다(그때는 `withdraw(userId, {purgeMessages: true})`).
|
|
395
408
|
|
|
396
409
|
```ts
|
|
397
410
|
await chat.users.ban(userId, { until: Date.now() + 7 * 86_400_000, reason: 'spam' })
|
|
@@ -438,18 +451,3 @@ app.post('/chat-hook', express.raw({ type: 'application/json' }), (req, res) =>
|
|
|
438
451
|
세 가지를 지킨다. `verify`가 서명과 시각(기본 5분)을 보고, **중복 제거는 직접**
|
|
439
452
|
해야 하며(`delivery`로), 10초 안에 2xx로 답해야 한다. 넘기면 실패로 치고 백오프가
|
|
440
453
|
시작된다.
|
|
441
|
-
|
|
442
|
-
---
|
|
443
|
-
|
|
444
|
-
## 개발
|
|
445
|
-
|
|
446
|
-
```sh
|
|
447
|
-
pnpm install
|
|
448
|
-
pnpm build # ESM + CJS + 타입 선언
|
|
449
|
-
pnpm exec vitest run
|
|
450
|
-
pnpm exec tsc --noEmit
|
|
451
|
-
```
|
|
452
|
-
|
|
453
|
-
테스트는 목이 아니라 **주입**을 쓴다. `WebSocket`과 `fetch`를 갈아 끼우면 서버를
|
|
454
|
-
흉내 낼 필요가 없고, 통합 계열 파일은 아예 **살아 있는 서버**에 붙는다. 실행에는
|
|
455
|
-
Postgres와 Redis가 필요하다.
|
|
@@ -1,3 +1,11 @@
|
|
|
1
|
+
// src/endpoint.ts
|
|
2
|
+
var ChatEndpoint = "wss://api.chat.gravex.app";
|
|
3
|
+
function restURLFrom(socketURL) {
|
|
4
|
+
if (socketURL.startsWith("wss://")) return `https://${socketURL.slice("wss://".length)}`;
|
|
5
|
+
if (socketURL.startsWith("ws://")) return `http://${socketURL.slice("ws://".length)}`;
|
|
6
|
+
return socketURL;
|
|
7
|
+
}
|
|
8
|
+
|
|
1
9
|
// src/errors.ts
|
|
2
10
|
var ChatError = class extends Error {
|
|
3
11
|
code;
|
|
@@ -5,7 +13,13 @@ var ChatError = class extends Error {
|
|
|
5
13
|
retryAfterMs;
|
|
6
14
|
/** The consumer's own code, when a before_publish hook denied this. */
|
|
7
15
|
appCode;
|
|
8
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* The HTTP status, when this came from a REST call.
|
|
18
|
+
*
|
|
19
|
+
* 읽기 전용이다. 이 값은 실패를 만든 응답의 성질이지 나중에 붙이는
|
|
20
|
+
* 꼬리표가 아니고, 쓸 수 있게 두면 소비자가 고쳐 쓴 상태가 SDK가
|
|
21
|
+
* 붙인 것과 구별되지 않는다.
|
|
22
|
+
*/
|
|
9
23
|
status;
|
|
10
24
|
constructor(code, message, extra) {
|
|
11
25
|
super(message);
|
|
@@ -13,9 +27,10 @@ var ChatError = class extends Error {
|
|
|
13
27
|
this.code = code;
|
|
14
28
|
if (extra?.retryAfterMs !== void 0) this.retryAfterMs = extra.retryAfterMs;
|
|
15
29
|
if (extra?.appCode !== void 0) this.appCode = extra.appCode;
|
|
30
|
+
if (extra?.status !== void 0) this.status = extra.status;
|
|
16
31
|
}
|
|
17
32
|
};
|
|
18
|
-
function errorFrom(data, fallback = "the server refused the request") {
|
|
33
|
+
function errorFrom(data, fallback = "the server refused the request", status) {
|
|
19
34
|
if (typeof data === "object" && data !== null) {
|
|
20
35
|
const d = data;
|
|
21
36
|
const inner = d["error"] ?? d;
|
|
@@ -24,12 +39,15 @@ function errorFrom(data, fallback = "the server refused the request") {
|
|
|
24
39
|
const extra = {};
|
|
25
40
|
if (typeof inner["retryAfterMs"] === "number") extra.retryAfterMs = inner["retryAfterMs"];
|
|
26
41
|
if (typeof inner["appCode"] === "string") extra.appCode = inner["appCode"];
|
|
42
|
+
if (status !== void 0) extra.status = status;
|
|
27
43
|
return new ChatError(code, message, extra);
|
|
28
44
|
}
|
|
29
|
-
return new ChatError("internal", fallback);
|
|
45
|
+
return new ChatError("internal", fallback, status === void 0 ? void 0 : { status });
|
|
30
46
|
}
|
|
31
47
|
|
|
32
48
|
export {
|
|
49
|
+
ChatEndpoint,
|
|
50
|
+
restURLFrom,
|
|
33
51
|
ChatError,
|
|
34
52
|
errorFrom
|
|
35
53
|
};
|