@kispi/chat 0.7.2 → 0.7.4

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
@@ -1,7 +1,10 @@
1
1
  # @kispi/chat
2
2
 
3
- Client SDK for the chat server. Many rooms over one socket, history in the right order.
4
- **Zero runtime dependencies**, both ESM and CJS, type declarations included.
3
+ Client SDK for [GravEx Chat](https://chat.gravex.app/en?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme), a managed realtime chat API.
4
+ Many rooms over one socket, history in the right order. **Zero runtime dependencies**, both ESM and CJS, type declarations included.
5
+
6
+ - **Get keys:** sign up in the [console](https://console.chat.gravex.app/?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme) to get a `ck_`; your code creates apps and `pk_`/`sk_` keys through the console API.
7
+ - **Hand it to your AI:** example prompts at [/docs/ai](https://chat.gravex.app/en/docs/ai?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme), agent summary at [llms.txt](https://chat.gravex.app/llms.txt).
5
8
 
6
9
  There are two entry points. `@kispi/chat` is the client for the browser and Node;
7
10
  `@kispi/chat/server` is for the consumer backend that holds the `sk_`.
@@ -249,7 +252,7 @@ public). A user token is required everywhere.
249
252
 
250
253
  ### Errors
251
254
 
252
- Failures are `ChatError`.
255
+ Failures are `ChatError`. A `text` message (the default kind) needs `text` (whitespace-only counts as empty) or an attachment; otherwise it is refused with `invalid`.
253
256
 
254
257
  ```ts
255
258
  try {
package/README.md CHANGED
@@ -1,7 +1,10 @@
1
1
  # @kispi/chat
2
2
 
3
- 채팅 서버의 클라이언트 SDK. 소켓 하나에 방 여러 개, 순서가 맞는 히스토리.
4
- **런타임 의존성 0개**, ESM과 CJS 둘 다, 타입 선언 포함.
3
+ [GravEx Chat](https://chat.gravex.app/?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme)(관리형 실시간 채팅 API)의 클라이언트 SDK.
4
+ 소켓 하나에 방 여러 개, 순서가 맞는 히스토리. **런타임 의존성 0개**, ESM과 CJS 둘 다, 타입 선언 포함.
5
+
6
+ - **키 받기:** [콘솔](https://console.chat.gravex.app/?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme)에서 가입하면 `ck_`가 나오고, 앱과 `pk_`·`sk_`는 콘솔 API로 코드가 만든다.
7
+ - **AI에게 시키기:** [/docs/ai](https://chat.gravex.app/docs/ai?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme)의 예시 프롬프트, 에이전트용 요약은 [llms.txt](https://chat.gravex.app/llms.txt).
5
8
 
6
9
  진입점이 둘이다. `@kispi/chat`은 브라우저와 Node에서 쓰는 클라이언트,
7
10
  `@kispi/chat/server`는 `sk_`를 들고 도는 소비자 백엔드용이다.
@@ -231,7 +234,7 @@ for (const part of splitByUrl(text)) {
231
234
 
232
235
  ### 에러
233
236
 
234
- 실패는 `ChatError`다.
237
+ 실패는 `ChatError`다. `text` 메시지(기본 kind)는 `text`(공백만이면 빈 것)나 첨부가 있어야 하고, 없으면 `invalid`로 거절된다.
235
238
 
236
239
  ```ts
237
240
  try {
package/dist/index.cjs CHANGED
@@ -1186,6 +1186,7 @@ function newClientMessageId() {
1186
1186
  // src/client.ts
1187
1187
  var MinBackoffMs = 500;
1188
1188
  var MaxBackoffMs = 3e4;
1189
+ var ResumeProbeMs = 3e3;
1189
1190
  var ChatClient = class extends Emitter {
1190
1191
  state = "closed";
1191
1192
  user;
@@ -1277,26 +1278,73 @@ var ChatClient = class extends Emitter {
1277
1278
  * - If closed by caller: does nothing.
1278
1279
  * - If disconnected or reconnecting: cancels any backoff delay and
1279
1280
  * reconnects immediately.
1280
- * - If already open: sends a ping frame to detect dead sockets, and
1281
- * triggers `resume()` on every room handle so missed messages are
1282
- * gap-filled via REST.
1281
+ * - If already open: pings and waits up to `ResumeProbeMs` for the
1282
+ * server to say anything. A reply means the socket is alive, and every
1283
+ * room resubscribes from what it holds so missed messages are filled
1284
+ * in. Silence means the socket died while the tab was away (a laptop
1285
+ * lid, a phone in a pocket, a NAT that forgot us) and nothing has
1286
+ * told the browser yet -- so it is replaced, and the new socket's
1287
+ * `hello` resubscribes every room the same way.
1288
+ *
1289
+ * 탭 복귀와 온라인 복귀가 거의 동시에 오면 하나로 합친다.
1283
1290
  */
1284
- async resume() {
1285
- if (this.stopped) return;
1291
+ resume() {
1292
+ if (this.stopped) return Promise.resolve();
1293
+ this.resuming ??= this.resumeOnce().finally(() => {
1294
+ this.resuming = void 0;
1295
+ });
1296
+ return this.resuming;
1297
+ }
1298
+ resuming;
1299
+ async resumeOnce() {
1286
1300
  if (this.state !== "open" || this.socket === void 0) {
1287
1301
  this.clearTimers();
1288
1302
  return this.connect();
1289
1303
  }
1290
- try {
1291
- this.socket.send(JSON.stringify({ type: "ping", id: `p${++this.nextFrameId}` }));
1292
- } catch {
1293
- this.clearTimers();
1294
- return this.connect();
1304
+ const socket = this.socket;
1305
+ const alive = await this.probe(socket);
1306
+ if (this.stopped) return;
1307
+ if (this.socket !== socket) {
1308
+ if (this.state !== "open" && this.opening === void 0) {
1309
+ this.clearTimers();
1310
+ return this.connect();
1311
+ }
1312
+ return;
1295
1313
  }
1314
+ if (!alive) return this.replaceSocket(socket, "no reply on resume");
1296
1315
  for (const room of this.handles.values()) {
1297
1316
  void room.resume().catch((err) => room.failed(err));
1298
1317
  }
1299
1318
  }
1319
+ /**
1320
+ * Pings `socket` and resolves whether any frame came back within
1321
+ * `ResumeProbeMs`. The server's `pong` carries no id, so "any frame on
1322
+ * this socket" is the answer -- a push that crosses the ping counts too.
1323
+ */
1324
+ probe(socket) {
1325
+ return new Promise((resolve) => {
1326
+ let done = false;
1327
+ const finish = (alive) => {
1328
+ if (done) return;
1329
+ done = true;
1330
+ clearTimeout(timer);
1331
+ this.probes.delete(finish);
1332
+ resolve(alive);
1333
+ };
1334
+ this.probes.add(finish);
1335
+ const timer = setTimeout(() => finish(false), ResumeProbeMs);
1336
+ try {
1337
+ socket.send(JSON.stringify({ type: "ping", id: `p${++this.nextFrameId}` }));
1338
+ } catch {
1339
+ finish(false);
1340
+ }
1341
+ });
1342
+ }
1343
+ /** Waiting `probe()`s on the current socket; settled by its next frame or its close. */
1344
+ probes = /* @__PURE__ */ new Set();
1345
+ settleProbes(alive) {
1346
+ for (const finish of [...this.probes]) finish(alive);
1347
+ }
1300
1348
  /** The account-level routes: the rooms this user is in, and unread. */
1301
1349
  get rooms() {
1302
1350
  return {
@@ -1437,10 +1485,15 @@ var ChatClient = class extends Emitter {
1437
1485
  });
1438
1486
  const socket = this.socket;
1439
1487
  if (socket === void 0 || this.state !== "open") return this.connect();
1488
+ return this.replaceSocket(socket, "replaced by reconnect()");
1489
+ }
1490
+ /** Drops `socket` without a reconnect of its own and opens a new one in its place. */
1491
+ replaceSocket(socket, why) {
1440
1492
  this.clearTimers();
1441
1493
  this.retired.add(socket);
1442
1494
  this.socket = void 0;
1443
- this.failPending(new ChatError("closed", "the connection was replaced by reconnect()"));
1495
+ this.settleProbes(false);
1496
+ this.failPending(new ChatError("closed", `the connection was ${why}`));
1444
1497
  try {
1445
1498
  socket.close(1e3, "client reconnecting");
1446
1499
  } catch {
@@ -1656,6 +1709,7 @@ var ChatClient = class extends Emitter {
1656
1709
  };
1657
1710
  socket.addEventListener("message", (ev) => {
1658
1711
  if (this.retired.has(socket)) return;
1712
+ if (socket === this.socket) this.settleProbes(true);
1659
1713
  const frame = JSON.parse(String(ev.data));
1660
1714
  if (frame.type === "hello") {
1661
1715
  this.onHello(frame.data);
@@ -1680,6 +1734,7 @@ var ChatClient = class extends Emitter {
1680
1734
  if (this.socket !== void 0 && this.socket !== socket) return;
1681
1735
  this.clearTimers();
1682
1736
  this.socket = void 0;
1737
+ this.settleProbes(false);
1683
1738
  this.failPending(new ChatError("closed", "the connection closed"));
1684
1739
  if (settled) {
1685
1740
  this.scheduleReconnect();
package/dist/index.d.cts CHANGED
@@ -790,11 +790,28 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
790
790
  * - If closed by caller: does nothing.
791
791
  * - If disconnected or reconnecting: cancels any backoff delay and
792
792
  * reconnects immediately.
793
- * - If already open: sends a ping frame to detect dead sockets, and
794
- * triggers `resume()` on every room handle so missed messages are
795
- * gap-filled via REST.
793
+ * - If already open: pings and waits up to `ResumeProbeMs` for the
794
+ * server to say anything. A reply means the socket is alive, and every
795
+ * room resubscribes from what it holds so missed messages are filled
796
+ * in. Silence means the socket died while the tab was away (a laptop
797
+ * lid, a phone in a pocket, a NAT that forgot us) and nothing has
798
+ * told the browser yet -- so it is replaced, and the new socket's
799
+ * `hello` resubscribes every room the same way.
800
+ *
801
+ * 탭 복귀와 온라인 복귀가 거의 동시에 오면 하나로 합친다.
796
802
  */
797
803
  resume(): Promise<void>;
804
+ private resuming;
805
+ private resumeOnce;
806
+ /**
807
+ * Pings `socket` and resolves whether any frame came back within
808
+ * `ResumeProbeMs`. The server's `pong` carries no id, so "any frame on
809
+ * this socket" is the answer -- a push that crosses the ping counts too.
810
+ */
811
+ private probe;
812
+ /** Waiting `probe()`s on the current socket; settled by its next frame or its close. */
813
+ private readonly probes;
814
+ private settleProbes;
798
815
  /** The account-level routes: the rooms this user is in, and unread. */
799
816
  get rooms(): {
800
817
  list: (options?: {
@@ -889,6 +906,8 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
889
906
  * is `connect()`.
890
907
  */
891
908
  reconnect(): Promise<void>;
909
+ /** Drops `socket` without a reconnect of its own and opens a new one in its place. */
910
+ private replaceSocket;
892
911
  /** Sockets `reconnect()` replaced: their late events are not this client's any more. */
893
912
  private readonly retired;
894
913
  /**
package/dist/index.d.ts CHANGED
@@ -790,11 +790,28 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
790
790
  * - If closed by caller: does nothing.
791
791
  * - If disconnected or reconnecting: cancels any backoff delay and
792
792
  * reconnects immediately.
793
- * - If already open: sends a ping frame to detect dead sockets, and
794
- * triggers `resume()` on every room handle so missed messages are
795
- * gap-filled via REST.
793
+ * - If already open: pings and waits up to `ResumeProbeMs` for the
794
+ * server to say anything. A reply means the socket is alive, and every
795
+ * room resubscribes from what it holds so missed messages are filled
796
+ * in. Silence means the socket died while the tab was away (a laptop
797
+ * lid, a phone in a pocket, a NAT that forgot us) and nothing has
798
+ * told the browser yet -- so it is replaced, and the new socket's
799
+ * `hello` resubscribes every room the same way.
800
+ *
801
+ * 탭 복귀와 온라인 복귀가 거의 동시에 오면 하나로 합친다.
796
802
  */
797
803
  resume(): Promise<void>;
804
+ private resuming;
805
+ private resumeOnce;
806
+ /**
807
+ * Pings `socket` and resolves whether any frame came back within
808
+ * `ResumeProbeMs`. The server's `pong` carries no id, so "any frame on
809
+ * this socket" is the answer -- a push that crosses the ping counts too.
810
+ */
811
+ private probe;
812
+ /** Waiting `probe()`s on the current socket; settled by its next frame or its close. */
813
+ private readonly probes;
814
+ private settleProbes;
798
815
  /** The account-level routes: the rooms this user is in, and unread. */
799
816
  get rooms(): {
800
817
  list: (options?: {
@@ -889,6 +906,8 @@ declare class ChatClient extends Emitter<ChatClientEvents> {
889
906
  * is `connect()`.
890
907
  */
891
908
  reconnect(): Promise<void>;
909
+ /** Drops `socket` without a reconnect of its own and opens a new one in its place. */
910
+ private replaceSocket;
892
911
  /** Sockets `reconnect()` replaced: their late events are not this client's any more. */
893
912
  private readonly retired;
894
913
  /**
package/dist/index.js CHANGED
@@ -1116,6 +1116,7 @@ function newClientMessageId() {
1116
1116
  // src/client.ts
1117
1117
  var MinBackoffMs = 500;
1118
1118
  var MaxBackoffMs = 3e4;
1119
+ var ResumeProbeMs = 3e3;
1119
1120
  var ChatClient = class extends Emitter {
1120
1121
  state = "closed";
1121
1122
  user;
@@ -1207,26 +1208,73 @@ var ChatClient = class extends Emitter {
1207
1208
  * - If closed by caller: does nothing.
1208
1209
  * - If disconnected or reconnecting: cancels any backoff delay and
1209
1210
  * reconnects immediately.
1210
- * - If already open: sends a ping frame to detect dead sockets, and
1211
- * triggers `resume()` on every room handle so missed messages are
1212
- * gap-filled via REST.
1211
+ * - If already open: pings and waits up to `ResumeProbeMs` for the
1212
+ * server to say anything. A reply means the socket is alive, and every
1213
+ * room resubscribes from what it holds so missed messages are filled
1214
+ * in. Silence means the socket died while the tab was away (a laptop
1215
+ * lid, a phone in a pocket, a NAT that forgot us) and nothing has
1216
+ * told the browser yet -- so it is replaced, and the new socket's
1217
+ * `hello` resubscribes every room the same way.
1218
+ *
1219
+ * 탭 복귀와 온라인 복귀가 거의 동시에 오면 하나로 합친다.
1213
1220
  */
1214
- async resume() {
1215
- if (this.stopped) return;
1221
+ resume() {
1222
+ if (this.stopped) return Promise.resolve();
1223
+ this.resuming ??= this.resumeOnce().finally(() => {
1224
+ this.resuming = void 0;
1225
+ });
1226
+ return this.resuming;
1227
+ }
1228
+ resuming;
1229
+ async resumeOnce() {
1216
1230
  if (this.state !== "open" || this.socket === void 0) {
1217
1231
  this.clearTimers();
1218
1232
  return this.connect();
1219
1233
  }
1220
- try {
1221
- this.socket.send(JSON.stringify({ type: "ping", id: `p${++this.nextFrameId}` }));
1222
- } catch {
1223
- this.clearTimers();
1224
- return this.connect();
1234
+ const socket = this.socket;
1235
+ const alive = await this.probe(socket);
1236
+ if (this.stopped) return;
1237
+ if (this.socket !== socket) {
1238
+ if (this.state !== "open" && this.opening === void 0) {
1239
+ this.clearTimers();
1240
+ return this.connect();
1241
+ }
1242
+ return;
1225
1243
  }
1244
+ if (!alive) return this.replaceSocket(socket, "no reply on resume");
1226
1245
  for (const room of this.handles.values()) {
1227
1246
  void room.resume().catch((err) => room.failed(err));
1228
1247
  }
1229
1248
  }
1249
+ /**
1250
+ * Pings `socket` and resolves whether any frame came back within
1251
+ * `ResumeProbeMs`. The server's `pong` carries no id, so "any frame on
1252
+ * this socket" is the answer -- a push that crosses the ping counts too.
1253
+ */
1254
+ probe(socket) {
1255
+ return new Promise((resolve) => {
1256
+ let done = false;
1257
+ const finish = (alive) => {
1258
+ if (done) return;
1259
+ done = true;
1260
+ clearTimeout(timer);
1261
+ this.probes.delete(finish);
1262
+ resolve(alive);
1263
+ };
1264
+ this.probes.add(finish);
1265
+ const timer = setTimeout(() => finish(false), ResumeProbeMs);
1266
+ try {
1267
+ socket.send(JSON.stringify({ type: "ping", id: `p${++this.nextFrameId}` }));
1268
+ } catch {
1269
+ finish(false);
1270
+ }
1271
+ });
1272
+ }
1273
+ /** Waiting `probe()`s on the current socket; settled by its next frame or its close. */
1274
+ probes = /* @__PURE__ */ new Set();
1275
+ settleProbes(alive) {
1276
+ for (const finish of [...this.probes]) finish(alive);
1277
+ }
1230
1278
  /** The account-level routes: the rooms this user is in, and unread. */
1231
1279
  get rooms() {
1232
1280
  return {
@@ -1367,10 +1415,15 @@ var ChatClient = class extends Emitter {
1367
1415
  });
1368
1416
  const socket = this.socket;
1369
1417
  if (socket === void 0 || this.state !== "open") return this.connect();
1418
+ return this.replaceSocket(socket, "replaced by reconnect()");
1419
+ }
1420
+ /** Drops `socket` without a reconnect of its own and opens a new one in its place. */
1421
+ replaceSocket(socket, why) {
1370
1422
  this.clearTimers();
1371
1423
  this.retired.add(socket);
1372
1424
  this.socket = void 0;
1373
- this.failPending(new ChatError("closed", "the connection was replaced by reconnect()"));
1425
+ this.settleProbes(false);
1426
+ this.failPending(new ChatError("closed", `the connection was ${why}`));
1374
1427
  try {
1375
1428
  socket.close(1e3, "client reconnecting");
1376
1429
  } catch {
@@ -1586,6 +1639,7 @@ var ChatClient = class extends Emitter {
1586
1639
  };
1587
1640
  socket.addEventListener("message", (ev) => {
1588
1641
  if (this.retired.has(socket)) return;
1642
+ if (socket === this.socket) this.settleProbes(true);
1589
1643
  const frame = JSON.parse(String(ev.data));
1590
1644
  if (frame.type === "hello") {
1591
1645
  this.onHello(frame.data);
@@ -1610,6 +1664,7 @@ var ChatClient = class extends Emitter {
1610
1664
  if (this.socket !== void 0 && this.socket !== socket) return;
1611
1665
  this.clearTimers();
1612
1666
  this.socket = void 0;
1667
+ this.settleProbes(false);
1613
1668
  this.failPending(new ChatError("closed", "the connection closed"));
1614
1669
  if (settled) {
1615
1670
  this.scheduleReconnect();
package/package.json CHANGED
@@ -1,7 +1,18 @@
1
1
  {
2
2
  "name": "@kispi/chat",
3
- "version": "0.7.2",
4
- "description": "Client SDK for the chat server: one WebSocket, many rooms, ordered history.",
3
+ "version": "0.7.4",
4
+ "description": "GravEx Chat SDK: managed realtime chat API. One WebSocket, many rooms, ordered history. Get an API key at chat.gravex.app.",
5
+ "homepage": "https://chat.gravex.app/?utm_source=npm&utm_medium=referral&utm_campaign=sdk_readme",
6
+ "keywords": [
7
+ "chat",
8
+ "chat-sdk",
9
+ "websocket",
10
+ "realtime",
11
+ "messaging",
12
+ "chat-api",
13
+ "typescript",
14
+ "agent-first"
15
+ ],
5
16
  "license": "MIT",
6
17
  "type": "module",
7
18
  "sideEffects": false,
@@ -41,7 +52,7 @@
41
52
  "@types/node": "^22.20.2",
42
53
  "tsup": "^8.5.0",
43
54
  "typescript": "^5.9.2",
44
- "vitest": "^4.1.11"
55
+ "vitest": "^4.1.12"
45
56
  },
46
57
  "engines": {
47
58
  "node": ">=22"