@poolse/sdk 1.0.5 → 1.1.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/CHANGELOG.md +15 -0
- package/README.md +342 -37
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,21 @@ All notable changes to `@poolse/sdk` are documented here. Format follows
|
|
|
4
4
|
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow
|
|
5
5
|
[semver](https://semver.org).
|
|
6
6
|
|
|
7
|
+
## [1.1.0] — 2026-06-02
|
|
8
|
+
|
|
9
|
+
Lockstep release with `@poolse/react@1.1.0` and `@poolse/react-ui@1.1.0`.
|
|
10
|
+
No API changes in `@poolse/sdk` itself — version bumped to keep the
|
|
11
|
+
three packages in sync, so customers can pin one version across the
|
|
12
|
+
whole client surface.
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
|
|
16
|
+
- README rewritten as a full reference: authentication model, every
|
|
17
|
+
resource and method with its HTTP path, the realtime channel event
|
|
18
|
+
catalogue with payload shapes, token caching semantics, idempotency
|
|
19
|
+
conventions, retry behaviour, and the typed error hierarchy.
|
|
20
|
+
- Repo-wide prettier formatting fixes (whitespace only).
|
|
21
|
+
|
|
7
22
|
## [1.0.0-beta.0] — 2026-06-01
|
|
8
23
|
|
|
9
24
|
First beta of the stable API surface. Consolidates everything from
|
package/README.md
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
# `@poolse/sdk`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Headless TypeScript SDK for [poolse](https://poolse.dev) — REST + WebSocket client for the poolse chat backend. No UI, no framework dependency. Runs in any environment with `fetch` and `WebSocket` (browsers, Node ≥ 18, Deno, Bun, React Native).
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
> Most React apps will want **[`@poolse/react`](https://www.npmjs.com/package/@poolse/react)** (hooks) or **[`@poolse/react-ui`](https://www.npmjs.com/package/@poolse/react-ui)** (prebuilt chat surface) instead. This package is the foundation underneath both.
|
|
5
|
+
If you're using React, you'll usually want [`@poolse/react`](https://www.npmjs.com/package/@poolse/react) (hooks) or [`@poolse/react-ui`](https://www.npmjs.com/package/@poolse/react-ui) (prebuilt chat surface). Both sit on top of this package; you can drop down to it whenever you outgrow them.
|
|
8
6
|
|
|
9
7
|
## Install
|
|
10
8
|
|
|
@@ -12,67 +10,374 @@ REST + WebSocket + presence + typing + reactions + threads + attachments, all in
|
|
|
12
10
|
npm install @poolse/sdk
|
|
13
11
|
```
|
|
14
12
|
|
|
13
|
+
The Phoenix Channels client (`phoenix@^1.8`) is bundled into the dist — you don't need to install it separately.
|
|
14
|
+
|
|
15
|
+
## Authentication model
|
|
16
|
+
|
|
17
|
+
poolse separates **API keys** (server-side, full tenant scope) from **End User JWTs** (client-side, short-lived, single-user). The SDK is designed for the JWT side: your backend exchanges its API key for an End User JWT (`POST /v1/users/:user_id/tokens`), and the SDK uses that JWT for every REST call and the WebSocket handshake.
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
┌────────────┐ API key ┌─────────┐ user JWT ┌─────────────┐
|
|
21
|
+
│ your │ ────────▶ │ poolse │ ─────────▶ │ your │
|
|
22
|
+
│ backend │ │ REST │ │ frontend │
|
|
23
|
+
│ (mints │ │ │ │ (this SDK) │
|
|
24
|
+
│ JWTs) │ ◀──────── │ │ ◀───────── │ │
|
|
25
|
+
└────────────┘ └─────────┘ └─────────────┘
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
Never embed an API key in a client bundle. The SDK calls your `getToken` whenever it needs the JWT; cache + refresh happen inside the SDK.
|
|
29
|
+
|
|
15
30
|
## Quick start
|
|
16
31
|
|
|
17
32
|
```ts
|
|
18
33
|
import { Poolse } from '@poolse/sdk';
|
|
19
34
|
|
|
20
35
|
const chat = new Poolse({
|
|
21
|
-
apiUrl: 'https://
|
|
22
|
-
// Your backend mints a JWT for the signed-in End User and returns it.
|
|
23
|
-
// The SDK caches + refreshes via this callback — never embed an API key
|
|
24
|
-
// in the browser.
|
|
36
|
+
apiUrl: 'https://api.poolse.dev', // optional; this is the default
|
|
25
37
|
getToken: async () => {
|
|
26
38
|
const res = await fetch('/api/chat-token', { method: 'POST' });
|
|
27
39
|
const { token } = await res.json();
|
|
28
|
-
return token;
|
|
40
|
+
return token; // string, or null for an anonymous request
|
|
29
41
|
},
|
|
30
42
|
});
|
|
31
43
|
|
|
32
44
|
// REST
|
|
33
45
|
const me = await chat.me.show();
|
|
34
46
|
const { data: conversations } = await chat.conversations.list();
|
|
47
|
+
const conv = chat.conversations.one('00000000-0000-0000-0000-000000000000');
|
|
48
|
+
const { data: messages } = await conv.messages.list({ limit: 50 });
|
|
49
|
+
await conv.messages.send({ body: 'Hello' });
|
|
35
50
|
|
|
36
|
-
//
|
|
37
|
-
const
|
|
38
|
-
const
|
|
51
|
+
// Realtime — socket opens lazily on the first conversation() / user() call.
|
|
52
|
+
const live = chat.realtime.conversation(conv.id);
|
|
53
|
+
const off = live.onMessage((msg) => console.log('new', msg));
|
|
39
54
|
|
|
40
|
-
|
|
41
|
-
.conversation('<conversation-id>')
|
|
42
|
-
.onMessage((msg) => console.log('new message', msg));
|
|
43
|
-
|
|
44
|
-
// Later
|
|
55
|
+
// Clean up when you're done.
|
|
45
56
|
off();
|
|
46
|
-
chat.destroy();
|
|
57
|
+
chat.destroy(); // closes WebSocket, leaves every joined channel
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Configuration
|
|
61
|
+
|
|
62
|
+
`new Poolse(config)` — every field but `getToken` has a default.
|
|
63
|
+
|
|
64
|
+
| Field | Type | Default | Notes |
|
|
65
|
+
| ------------------------ | ------------------------------------------------------------------------------------- | --------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
66
|
+
| `getToken` | `() => Promise<string \| null> \| string \| null` | — _required_ | Called when the SDK needs a JWT. Return `null` to make an unauthenticated request (rare — the server requires a JWT for most routes). |
|
|
67
|
+
| `apiUrl` | `string` | `https://api.poolse.dev` | Base URL **without** `/v1`. Strip the trailing slash if present (the SDK does this too). |
|
|
68
|
+
| `wsUrl` | `string` | `apiUrl` with `http(s)` → `ws(s)` | Override for split-host deployments where the WebSocket gateway is on a different origin. |
|
|
69
|
+
| `socketPath` | `string` | `/socket` | Phoenix Channels mount point. |
|
|
70
|
+
| `fetch` | `typeof fetch` | `globalThis.fetch` | Inject a fetch implementation (tests, restricted environments). Must be bound to `globalThis` if you pass the global one explicitly. |
|
|
71
|
+
| `maxRetries` | `number` | `3` | Retry budget for transient failures, per request. |
|
|
72
|
+
| `baseBackoffMs` | `number` | `250` | Base of the exponential backoff. |
|
|
73
|
+
| `maxBackoffMs` | `number` | `30000` | Hard ceiling on a single retry delay. |
|
|
74
|
+
| `generateIdempotencyKey` | `() => string` | `crypto.randomUUID()` | Override the key generator. Defaults throws at construction time if no `crypto.randomUUID` is available. |
|
|
75
|
+
| `onSocketError` | `(err: Error) => void` | — | Fired on non-fatal socket errors (Phoenix handles reconnect internally; this is for surface-level banners). |
|
|
76
|
+
| `userResolver` | `(userId: string) => Promise<PoolseUserProfile \| null> \| PoolseUserProfile \| null` | — | Optional. Resolve a poolse `user_id` to a `{ displayName, avatarUrl }` pair from your app's user data. The UI packages pick this up automatically. |
|
|
77
|
+
|
|
78
|
+
## REST surface
|
|
79
|
+
|
|
80
|
+
All methods accept an optional `AbortSignal` (or `{ signal }`) and return parsed JSON. Errors throw typed exceptions — see [Errors](#errors) below.
|
|
81
|
+
|
|
82
|
+
### `chat.me`
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
chat.me.show(signal?): Promise<Me>; // GET /v1/me
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### `chat.conversations`
|
|
89
|
+
|
|
90
|
+
```ts
|
|
91
|
+
chat.conversations.list(signal?): Promise<{ data: Conversation[] }>;
|
|
92
|
+
chat.conversations.create(attrs, signal?): Promise<Conversation>;
|
|
93
|
+
chat.conversations.one(id): ConversationHandle;
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`ConversationCreateRequest`:
|
|
97
|
+
|
|
98
|
+
```ts
|
|
99
|
+
{
|
|
100
|
+
type: 'direct' | 'group';
|
|
101
|
+
name?: string | null;
|
|
102
|
+
avatar_url?: string | null;
|
|
103
|
+
member_limit?: number | null;
|
|
104
|
+
member_external_ids?: string[]; // your IDs; poolse looks them up by tenant
|
|
105
|
+
custom_data?: Record<string, unknown>;
|
|
106
|
+
settings?: Record<string, unknown>;
|
|
107
|
+
}
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
`ConversationHandle` (returned by `chat.conversations.one(id)`):
|
|
111
|
+
|
|
112
|
+
```ts
|
|
113
|
+
handle.show(signal?): Promise<Conversation>; // GET /v1/conversations/:id
|
|
114
|
+
handle.update(attrs, signal?): Promise<Conversation>; // PATCH /v1/conversations/:id
|
|
115
|
+
|
|
116
|
+
handle.listMembers(signal?): Promise<{ data: Membership[] }>; // GET /v1/conversations/:id/members
|
|
117
|
+
handle.addMembers(externalIds, { role?, signal? }?): Promise<{ data: Membership[] }>;
|
|
118
|
+
handle.addMember(externalId, { role?, signal? }?): Promise<Membership>;
|
|
119
|
+
handle.removeMember(userId, signal?): Promise<void>;
|
|
120
|
+
|
|
121
|
+
handle.messages: ConversationMessages;
|
|
47
122
|
```
|
|
48
123
|
|
|
49
|
-
|
|
124
|
+
`handle.messages`:
|
|
50
125
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
126
|
+
```ts
|
|
127
|
+
handle.messages.list({ limit?, before? }?, signal?): Promise<{ data: Message[] }>;
|
|
128
|
+
handle.messages.send(attrs, signal?): Promise<Message>;
|
|
129
|
+
handle.messages.markRead(messageId, signal?): Promise<void>; // POST /v1/conversations/:id/read
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Messages are paginated **newest-first** by per-conversation `sequence`. To load older messages: `list({ limit: 50, before: oldestSequence })`.
|
|
133
|
+
|
|
134
|
+
`MessageCreateRequest`:
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
{
|
|
138
|
+
id?: Uuid; // optional client-supplied id for retry-safe sends
|
|
139
|
+
body?: string | null; // optional ONLY when attachment_ids is non-empty
|
|
140
|
+
type?: 'text' | 'system' | 'custom';
|
|
141
|
+
reply_to_id?: Uuid; // setting this promotes the message to a thread reply
|
|
142
|
+
quoted_message_id?: Uuid; // WhatsApp-style quote — stays in main feed
|
|
143
|
+
mentions?: Uuid[]; // user_ids to notify
|
|
144
|
+
attachment_ids?: Uuid[]; // attach pre-uploaded files; max 10
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
If you omit `id`, `send` auto-generates one via `crypto.randomUUID()` so retries are idempotent and the realtime echo can be deduped against your optimistic insert.
|
|
149
|
+
|
|
150
|
+
### `chat.messages`
|
|
151
|
+
|
|
152
|
+
The message handle is keyed by message id (not conversation), because some operations need the message id but not the conversation id.
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
chat.messages.one(id): MessageHandle;
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
`MessageHandle`:
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
handle.update({ body }, signal?): Promise<Message>; // PATCH /v1/messages/:id
|
|
162
|
+
handle.delete(signal?): Promise<void>; // DELETE /v1/messages/:id (soft-delete)
|
|
163
|
+
handle.replies({ limit?, after? }?, signal?): Promise<{ data: Message[] }>; // GET /v1/messages/:id/replies
|
|
164
|
+
handle.addReaction(emoji, signal?): Promise<Message>; // POST /v1/messages/:id/reactions
|
|
165
|
+
handle.removeReaction(emoji, signal?): Promise<Message>; // DELETE /v1/messages/:id/reactions/:emoji
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Thread replies are paginated **oldest-first** with an `after` cursor (opposite of the main feed). The default `limit` for replies is 500 — most threads load in one request.
|
|
169
|
+
|
|
170
|
+
### `chat.attachments`
|
|
171
|
+
|
|
172
|
+
Two-step upload: presign → PUT. The SDK has a one-call helper too.
|
|
59
173
|
|
|
60
|
-
|
|
174
|
+
```ts
|
|
175
|
+
chat.attachments.requestUpload(attrs, opts?): Promise<AttachmentUploadResponse>; // POST /v1/attachments/upload-url
|
|
176
|
+
chat.attachments.upload(input, opts?): Promise<Attachment>; // presign + PUT, returns the row
|
|
177
|
+
chat.attachments.one(id): AttachmentHandle;
|
|
178
|
+
```
|
|
61
179
|
|
|
180
|
+
`AttachmentUploadInput`:
|
|
181
|
+
|
|
182
|
+
```ts
|
|
183
|
+
{
|
|
184
|
+
body: BodyInit; // Blob, File, ArrayBufferView, string, etc.
|
|
185
|
+
contentType: string; // matches what you'll PUT
|
|
186
|
+
byteSize: number; // matches Content-Length of `body`
|
|
187
|
+
filename?: string; // shown in the download UI
|
|
188
|
+
}
|
|
62
189
|
```
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
190
|
+
|
|
191
|
+
`AttachmentOptions`:
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
{
|
|
195
|
+
signal?: AbortSignal;
|
|
196
|
+
onProgress?: (event: { loaded: number; total: number }) => void;
|
|
197
|
+
}
|
|
69
198
|
```
|
|
70
199
|
|
|
71
|
-
|
|
200
|
+
`onProgress` switches the PUT to `XMLHttpRequest` (the only browser API that exposes upload progress). When you don't pass `onProgress`, the SDK uses `fetch` and you get no progress events. `XMLHttpRequest` is browser-only, so progress in Node will silently no-op.
|
|
201
|
+
|
|
202
|
+
To attach to a message, take the returned `attachment.id` and pass it as part of `attachment_ids` on the next `send`. The server links + flips status to `ready` in the same transaction.
|
|
203
|
+
|
|
204
|
+
`AttachmentHandle`:
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
handle.downloadUrl(opts?): Promise<{ url: string; method: 'get' }>; // ~1h TTL
|
|
208
|
+
handle.delete(opts?): Promise<void>;
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
### `chat.users`
|
|
212
|
+
|
|
213
|
+
A small read-through cache for the **customer-supplied** profile (display name + avatar). The SDK doesn't store these — it asks your `config.userResolver` when it doesn't have them.
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
chat.users.peek(userId): PoolseUserProfile | null | undefined;
|
|
217
|
+
// undefined → not yet fetched (or no resolver)
|
|
218
|
+
// null → resolver ran, returned null
|
|
219
|
+
// profile → cached hit
|
|
220
|
+
|
|
221
|
+
chat.users.get(userId): Promise<PoolseUserProfile | null>;
|
|
222
|
+
chat.users.subscribe(userId, listener): () => void; // fires when an entry changes
|
|
223
|
+
chat.users.invalidate(userId): void;
|
|
224
|
+
chat.users.invalidateAll(): void; // sign-out, tenant swap
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
Concurrent `get(userId)` calls for the same id share one in-flight resolver promise — a busy chat with 50 messages from 5 senders calls your resolver 5 times.
|
|
228
|
+
|
|
229
|
+
### `chat.rest`
|
|
230
|
+
|
|
231
|
+
Escape hatch for endpoints not yet covered by the typed resources (e.g., admin routes). Same retry + auth + idempotency behavior as the typed methods.
|
|
232
|
+
|
|
233
|
+
```ts
|
|
234
|
+
const result = await chat.rest.request<MyShape>({
|
|
235
|
+
method: 'POST',
|
|
236
|
+
path: '/v1/something',
|
|
237
|
+
body: { foo: 'bar' },
|
|
238
|
+
query: { limit: 10 },
|
|
239
|
+
idempotencyKey: 'my-custom-key', // or null to omit; defaults to a fresh UUID for non-GETs
|
|
240
|
+
signal,
|
|
241
|
+
});
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
## Realtime
|
|
245
|
+
|
|
246
|
+
The WebSocket is **lazily opened** on the first `conversation()` or `user()` call — until then the realtime layer is dormant and won't try to authenticate.
|
|
247
|
+
|
|
248
|
+
```ts
|
|
249
|
+
chat.realtime.connect(): void; // idempotent; usually you don't call this directly
|
|
250
|
+
chat.realtime.disconnect(): void;
|
|
251
|
+
chat.realtime.getStatus(): RealtimeStatus;
|
|
252
|
+
chat.realtime.onStatus(fn): Unsubscribe;
|
|
253
|
+
chat.realtime.conversation(id): ConversationChannel;
|
|
254
|
+
chat.realtime.user(id): UserChannel;
|
|
255
|
+
chat.realtime.leave(id): void; // drop a conversation handle
|
|
256
|
+
```
|
|
257
|
+
|
|
258
|
+
`RealtimeStatus`: `'idle' | 'connecting' | 'connected' | 'reconnecting' | 'closed'`.
|
|
259
|
+
|
|
260
|
+
Reconnect with backoff is handled by the underlying Phoenix Socket. On reconnect the JWT is re-read via `getToken`, so a refreshed token lands on the next handshake without manual intervention.
|
|
261
|
+
|
|
262
|
+
### `ConversationChannel`
|
|
263
|
+
|
|
264
|
+
Returned by `chat.realtime.conversation(id)`. Reusing the same id returns the same handle (no second channel join).
|
|
265
|
+
|
|
266
|
+
```ts
|
|
267
|
+
channel.onMessage(fn): Unsubscribe; // message:new
|
|
268
|
+
channel.onMessageUpdated(fn): Unsubscribe; // message:updated
|
|
269
|
+
channel.onMessageDeleted(fn): Unsubscribe; // message:deleted
|
|
270
|
+
channel.onReactionAdded(fn): Unsubscribe; // reaction:added
|
|
271
|
+
channel.onReactionRemoved(fn): Unsubscribe; // reaction:removed
|
|
272
|
+
channel.onMemberRead(fn): Unsubscribe; // member:read (read receipts)
|
|
273
|
+
channel.onTypingStart(fn): Unsubscribe;
|
|
274
|
+
channel.onTypingStop(fn): Unsubscribe;
|
|
275
|
+
channel.onPresenceState(fn): Unsubscribe; // initial snapshot (replayed to late subscribers)
|
|
276
|
+
channel.onPresenceDiff(fn): Unsubscribe; // joins/leaves deltas
|
|
277
|
+
channel.getPresenceState(): PresenceSnapshot; // synchronous read
|
|
278
|
+
|
|
279
|
+
channel.sendTyping(): void; // server is rate-limited; safe to spam
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
The server filters `typing` to peers — you won't receive your own typing event back.
|
|
283
|
+
|
|
284
|
+
Payload shapes are exact:
|
|
285
|
+
|
|
286
|
+
| Event | Payload |
|
|
287
|
+
| ------------------------------------- | ------------------------------------------------------------------------------------------- |
|
|
288
|
+
| `message:new` / `message:updated` | `Message` (full row, with `attachments` preloaded and `quoted_message` set when applicable) |
|
|
289
|
+
| `message:deleted` | `{ id: Uuid; conversation_id: Uuid; deleted_at: string \| null }` |
|
|
290
|
+
| `reaction:added` / `reaction:removed` | `{ message_id, conversation_id, emoji, user_id }` |
|
|
291
|
+
| `member:read` | `{ user_id, conversation_id, last_read_message_id, last_read_at }` |
|
|
292
|
+
| `typing:start` / `typing:stop` | `{ user_id }` |
|
|
293
|
+
| `presence_state` | `Record<user_id, { metas: Array<{ phx_ref, online_at, external_id? }> }>` |
|
|
294
|
+
| `presence_diff` | Same shape, partitioned into `{ joins, leaves }` |
|
|
295
|
+
|
|
296
|
+
### `UserChannel`
|
|
297
|
+
|
|
298
|
+
Returned by `chat.realtime.user(id)`. Only the user matching the JWT can join their own channel — the server rejects other ids.
|
|
299
|
+
|
|
300
|
+
```ts
|
|
301
|
+
channel.onMention(fn): Unsubscribe; // mention:new
|
|
302
|
+
channel.onConversationCreated(fn): Unsubscribe; // conversation:created
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
`mention:new` carries `{ message_id, conversation_id, sender_id }` — fetch the full message via REST if you need the body. `conversation:created` fires whenever the user is added to a conversation (including ones they created themselves) and carries the full `Conversation`.
|
|
306
|
+
|
|
307
|
+
## Token caching
|
|
308
|
+
|
|
309
|
+
`config.getToken` is called once per JWT lifetime, not per request. The cache decodes the JWT's `exp` claim and refreshes 30s before expiry. Concurrent callers share the in-flight refresh promise.
|
|
310
|
+
|
|
311
|
+
On a 401, the SDK invalidates the cache and retries the request **once** with a fresh token. If the second attempt also 401s, `AuthError` is thrown.
|
|
312
|
+
|
|
313
|
+
If you sign the user out or rotate tenants, drop the current `Poolse` instance (or, in `@poolse/react`, give `<PoolseProvider>` a new `key`) — there's no in-place invalidate API at the SDK level because mutating connection-shaped config after construction doesn't reach the open socket anyway.
|
|
314
|
+
|
|
315
|
+
## Idempotency
|
|
316
|
+
|
|
317
|
+
Every non-GET request carries an auto-generated `Idempotency-Key` header. The server caches 2xx responses per `(tenant, method, path, key)` for 24 hours, so a retry after a flaky network drop returns the same row instead of creating a duplicate. Non-2xx responses are never cached — you can retry with the same key after fixing a validation error.
|
|
318
|
+
|
|
319
|
+
To override the key (e.g., to make a deliberate retry intentional), pass `idempotencyKey` on `chat.rest.request`. Pass `null` to omit the header entirely. Resource methods auto-generate a fresh key per call.
|
|
320
|
+
|
|
321
|
+
## Retry behavior
|
|
322
|
+
|
|
323
|
+
Transient failures (network errors, 5xx, 429) are retried with exponential backoff + full jitter, capped by `maxBackoffMs`. On a 429 the server's `Retry-After` (seconds) is honored if present and larger than the computed backoff. Aborts (`DOMException('AbortError')`) are propagated, never wrapped.
|
|
324
|
+
|
|
325
|
+
The retry budget is `maxRetries` (default 3) attempts after the initial request — up to 4 attempts total per logical call.
|
|
326
|
+
|
|
327
|
+
## Errors
|
|
328
|
+
|
|
329
|
+
All errors extend `PoolseError` and are `instanceof`-checkable:
|
|
330
|
+
|
|
331
|
+
```ts
|
|
332
|
+
import { ApiError, AuthError, RateLimitedError, NetworkError, PoolseError } from '@poolse/sdk';
|
|
333
|
+
|
|
334
|
+
try {
|
|
335
|
+
await chat.messages.one(id).update({ body: 'edit' });
|
|
336
|
+
} catch (err) {
|
|
337
|
+
if (err instanceof AuthError) {
|
|
338
|
+
// 401: the JWT is invalid even after one refresh attempt. Re-auth the user.
|
|
339
|
+
} else if (err instanceof RateLimitedError) {
|
|
340
|
+
// 429: err.retryAfterMs is parsed from the Retry-After header (0 if absent).
|
|
341
|
+
} else if (err instanceof ApiError) {
|
|
342
|
+
// Other 4xx/5xx with a canonical envelope: err.status, err.code, err.docUrl, err.details
|
|
343
|
+
} else if (err instanceof NetworkError) {
|
|
344
|
+
// fetch() rejected; err.cause is the original failure.
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
The server's error envelope is exposed via the `code` / `docUrl` / `details` fields on `ApiError`. Codes are stable strings like `validation_failed`, `forbidden`, `message_deleted`, `attachment_too_large` — see the docs at `err.docUrl` for the full list per endpoint.
|
|
350
|
+
|
|
351
|
+
## Sequence numbers
|
|
352
|
+
|
|
353
|
+
Every message has a monotonic per-conversation `sequence`. It's assigned in the same transaction as the insert, so server order is unambiguous regardless of clock skew. The SDK uses it for pagination (`before` / `after` cursors) and for sorting optimistic-vs-server-echo races: the optimistic local insert can sort to the very end until the server-assigned `sequence` arrives, at which point the dedup-by-id upsert puts it in the right place.
|
|
354
|
+
|
|
355
|
+
## Cancellation
|
|
356
|
+
|
|
357
|
+
Every method that touches the network accepts an `AbortSignal`. The SDK propagates abort to the underlying `fetch` (and to `XMLHttpRequest` on the progress-enabled upload path). Aborted requests throw `DOMException('AbortError')` — they are **not** retried.
|
|
358
|
+
|
|
359
|
+
```ts
|
|
360
|
+
const controller = new AbortController();
|
|
361
|
+
const promise = chat.messages.one(id).replies({ limit: 100 }, controller.signal);
|
|
362
|
+
// later:
|
|
363
|
+
controller.abort();
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
## Environments
|
|
367
|
+
|
|
368
|
+
- **Browsers (modern)** — works out of the box.
|
|
369
|
+
- **Node ≥ 18** — uses the global `fetch` and `WebSocket`. Upload progress is browser-only (silently no-ops in Node).
|
|
370
|
+
- **React Native** — works on RN ≥ 0.72 (`fetch` + `WebSocket` are built in). The `phoenix` client is bundled.
|
|
371
|
+
- **Bun / Deno** — works; same caveat on upload progress.
|
|
372
|
+
- **Web Workers** — works for REST; sockets work where `WebSocket` is available.
|
|
373
|
+
|
|
374
|
+
## Exports
|
|
375
|
+
|
|
376
|
+
The package exports the `Poolse` class, the resource and channel classes (`ConversationsResource`, `ConversationHandle`, `MessagesResource`, `MessageHandle`, `AttachmentsResource`, `AttachmentHandle`, `MeResource`, `UsersResource`, `PoolseRealtime`, `ConversationChannel`, `UserChannel`), all error classes, every interface from the wire protocol (`Message`, `Conversation`, `Membership`, `User`, `Attachment`, etc.), the `RealtimeStatus` union, the `POOLSE_API_URL` default, and a `version` constant for diagnostics.
|
|
72
377
|
|
|
73
|
-
##
|
|
378
|
+
## Links
|
|
74
379
|
|
|
75
|
-
- Full
|
|
380
|
+
- Full docs — <https://poolse.dev/docs>
|
|
76
381
|
- Source — <https://github.com/poolse-hq/js-sdk>
|
|
77
382
|
- Issues — <https://github.com/poolse-hq/js-sdk/issues>
|
|
78
383
|
|