@mitway/sdk 0.2.2 → 0.2.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/dist/index.cjs +615 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +304 -24
- package/dist/index.d.ts +304 -24
- package/dist/index.js +613 -0
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
package/dist/index.d.cts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { Socket } from 'socket.io-client';
|
|
1
2
|
import * as _supabase_postgrest_js from '@supabase/postgrest-js';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -29,6 +30,301 @@ interface User {
|
|
|
29
30
|
updated_at: string;
|
|
30
31
|
}
|
|
31
32
|
|
|
33
|
+
/**
|
|
34
|
+
* Token Manager for the MITWAY-BaaS SDK.
|
|
35
|
+
*
|
|
36
|
+
* In-memory storage for the access token + user. Browser CSRF token lives
|
|
37
|
+
* in a cookie so the cookie-based refresh flow works across page reloads.
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
declare class TokenManager {
|
|
41
|
+
private accessToken;
|
|
42
|
+
private user;
|
|
43
|
+
/** Fired when the access token changes (used by long-lived consumers). */
|
|
44
|
+
onTokenChange: (() => void) | null;
|
|
45
|
+
saveSession(session: AuthSession): void;
|
|
46
|
+
getSession(): AuthSession | null;
|
|
47
|
+
getAccessToken(): string | null;
|
|
48
|
+
setAccessToken(token: string): void;
|
|
49
|
+
getUser(): User | null;
|
|
50
|
+
setUser(user: User): void;
|
|
51
|
+
clearSession(): void;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Realtime module — Socket.IO client exposing the channel API.
|
|
56
|
+
*
|
|
57
|
+
* Design goals:
|
|
58
|
+
* 1. `client.realtime.channel(topic).on(type, filter, cb).subscribe()` is
|
|
59
|
+
* the single entry point for every primitive.
|
|
60
|
+
* 2. Three binding types coexist on a channel:
|
|
61
|
+
* * `postgres_changes` — WAL-based auto-broadcast of DB events,
|
|
62
|
+
* gated by per-subscriber RLS replay in the backend.
|
|
63
|
+
* * `broadcast` — fire-and-forget custom events published
|
|
64
|
+
* via `channel.send({...})` (in-memory fan-out) or via the
|
|
65
|
+
* server-side `realtime.send()` SQL helper.
|
|
66
|
+
* * `presence` — per-channel live "who's here" state.
|
|
67
|
+
* 3. One socket per `Realtime` instance. Multiple channels share it.
|
|
68
|
+
*
|
|
69
|
+
* The wire protocol is defined in the backend's socket.manager.ts.
|
|
70
|
+
*/
|
|
71
|
+
|
|
72
|
+
type PostgresChangesEventSelector = 'INSERT' | 'UPDATE' | 'DELETE' | '*';
|
|
73
|
+
interface PostgresChangesFilter {
|
|
74
|
+
event: PostgresChangesEventSelector;
|
|
75
|
+
schema?: string;
|
|
76
|
+
table: string;
|
|
77
|
+
/** PostgREST-style filter: `column=op.value` or `column=in.(a,b,c)`. */
|
|
78
|
+
filter?: string;
|
|
79
|
+
}
|
|
80
|
+
interface PostgresChangesPayload<T = Record<string, unknown>> {
|
|
81
|
+
type: 'INSERT' | 'UPDATE' | 'DELETE';
|
|
82
|
+
schema: string;
|
|
83
|
+
table: string;
|
|
84
|
+
commit_timestamp: string;
|
|
85
|
+
columns: Array<{
|
|
86
|
+
name: string;
|
|
87
|
+
type: string;
|
|
88
|
+
}>;
|
|
89
|
+
record?: T;
|
|
90
|
+
old_record?: T;
|
|
91
|
+
errors?: string[];
|
|
92
|
+
}
|
|
93
|
+
interface BroadcastFilter {
|
|
94
|
+
event: string;
|
|
95
|
+
}
|
|
96
|
+
interface BroadcastPayload<T = Record<string, unknown>> {
|
|
97
|
+
type: 'broadcast';
|
|
98
|
+
event: string;
|
|
99
|
+
payload: T;
|
|
100
|
+
}
|
|
101
|
+
/** Presence event selector used with `.on('presence', { event }, cb)`. */
|
|
102
|
+
type PresenceEventSelector = 'sync' | 'join' | 'leave';
|
|
103
|
+
interface PresenceFilter {
|
|
104
|
+
event: PresenceEventSelector;
|
|
105
|
+
}
|
|
106
|
+
/** State map keyed by opaque client key (the socket id on our server side).
|
|
107
|
+
* The client treats these keys as blackboxes — just compare across sync /
|
|
108
|
+
* join / leave deltas to track which participants appeared or departed. */
|
|
109
|
+
type PresenceState<T = Record<string, unknown>> = Record<string, T>;
|
|
110
|
+
interface PresenceSyncPayload<T = Record<string, unknown>> {
|
|
111
|
+
event: 'sync';
|
|
112
|
+
state: PresenceState<T>;
|
|
113
|
+
}
|
|
114
|
+
interface PresenceJoinPayload<T = Record<string, unknown>> {
|
|
115
|
+
event: 'join';
|
|
116
|
+
/** One-entry map `{ [key]: state }` with the new or updated state. */
|
|
117
|
+
joins: PresenceState<T>;
|
|
118
|
+
}
|
|
119
|
+
interface PresenceLeavePayload<T = Record<string, unknown>> {
|
|
120
|
+
event: 'leave';
|
|
121
|
+
/** One-entry map `{ [key]: state }` with the state just before leaving. */
|
|
122
|
+
leaves: PresenceState<T>;
|
|
123
|
+
}
|
|
124
|
+
type PresencePayload<T = Record<string, unknown>> = PresenceSyncPayload<T> | PresenceJoinPayload<T> | PresenceLeavePayload<T>;
|
|
125
|
+
interface RealtimeMessageMeta {
|
|
126
|
+
channel?: string;
|
|
127
|
+
message_id: string;
|
|
128
|
+
sender_id?: string;
|
|
129
|
+
timestamp: string;
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Channel configuration — passed to `client.realtime.channel(topic, opts)`.
|
|
133
|
+
* Every option has a safe default so apps can omit `opts` entirely for the
|
|
134
|
+
* common case.
|
|
135
|
+
*/
|
|
136
|
+
interface ChannelOptions {
|
|
137
|
+
config?: {
|
|
138
|
+
/** When true, subscribe is gated on `realtime.authorize_subscribe(role,
|
|
139
|
+
* claims, topic)` at the server side. Replay is also gated if
|
|
140
|
+
* requested on a private channel. Default: `false` (open topic). */
|
|
141
|
+
private?: boolean;
|
|
142
|
+
broadcast?: {
|
|
143
|
+
/** When true, `channel.send(...)` resolves only after the server
|
|
144
|
+
* ack'd the publish — useful if the app wants to know the
|
|
145
|
+
* message_id assigned by the server. Default: `false`
|
|
146
|
+
* (fire-and-forget). */
|
|
147
|
+
ack?: boolean;
|
|
148
|
+
/** When `false`, the sending socket is excluded from the fan-out.
|
|
149
|
+
* Default: `true` (sender also receives its own broadcasts). */
|
|
150
|
+
self?: boolean;
|
|
151
|
+
};
|
|
152
|
+
presence?: {
|
|
153
|
+
/** Optional stable key that replaces the socket id in the presence
|
|
154
|
+
* hash. Useful to group multiple tabs of the same user under one
|
|
155
|
+
* entry. Default: socket id (each tab is a separate entry). */
|
|
156
|
+
key?: string;
|
|
157
|
+
};
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
type ChannelStatus = 'SUBSCRIBED' | 'CHANNEL_ERROR' | 'TIMED_OUT' | 'CLOSED';
|
|
161
|
+
type ChannelStatusCallback = (status: ChannelStatus, error?: {
|
|
162
|
+
code: string;
|
|
163
|
+
message: string;
|
|
164
|
+
}) => void;
|
|
165
|
+
interface RealtimeOptions {
|
|
166
|
+
path?: string;
|
|
167
|
+
transports?: Array<'websocket' | 'polling'>;
|
|
168
|
+
timeoutMs?: number;
|
|
169
|
+
extraAuth?: Record<string, string>;
|
|
170
|
+
}
|
|
171
|
+
type PostgresChangesCallback<T = Record<string, unknown>> = (payload: PostgresChangesPayload<T>) => void;
|
|
172
|
+
type BroadcastCallback<T = Record<string, unknown>> = (payload: BroadcastPayload<T>) => void;
|
|
173
|
+
type PresenceCallback<T = Record<string, unknown>> = (payload: PresencePayload<T>) => void;
|
|
174
|
+
declare class RealtimeChannel {
|
|
175
|
+
readonly topic: string;
|
|
176
|
+
private readonly realtime;
|
|
177
|
+
private bindings;
|
|
178
|
+
private state;
|
|
179
|
+
private statusCallback;
|
|
180
|
+
/** Local presence state mirror — populated from `presence_state` /
|
|
181
|
+
* `presence_join` / `presence_leave` events. Read via `presenceState()`. */
|
|
182
|
+
private presence;
|
|
183
|
+
/** Latest state this client has tracked. Non-null means the heartbeat
|
|
184
|
+
* timer is active and we'll re-emit this state every TTL/2. */
|
|
185
|
+
private trackedState;
|
|
186
|
+
private presenceHeartbeat;
|
|
187
|
+
/** Timestamp of the most recently received broadcast on this channel —
|
|
188
|
+
* used as the `since` anchor on replay after reconnect. ISO-8601. */
|
|
189
|
+
private lastBroadcastTimestamp;
|
|
190
|
+
/** Configuration from `channel(topic, opts)`. Frozen at construction. */
|
|
191
|
+
private readonly options;
|
|
192
|
+
constructor(topic: string, realtime: Realtime, options?: ChannelOptions);
|
|
193
|
+
/** Whether this channel was opened as `private: true`. */
|
|
194
|
+
private get isPrivate();
|
|
195
|
+
/** The user-supplied presence key, if any. */
|
|
196
|
+
private get presenceKey();
|
|
197
|
+
/** Internal — exposed for Realtime to drive resubscription after a
|
|
198
|
+
* network hiccup. Returns the current lifecycle state. */
|
|
199
|
+
_state(): 'closed' | 'joining' | 'joined' | 'errored';
|
|
200
|
+
/** Internal — called by `Realtime` when Socket.IO reconnects after a
|
|
201
|
+
* drop. Re-runs the registration flow; the backend assigns fresh
|
|
202
|
+
* subscription_ids and Socket.IO rejoins the per-subscription rooms,
|
|
203
|
+
* so events resume without developer intervention. The user-provided
|
|
204
|
+
* statusCallback (from the original subscribe()) fires again with
|
|
205
|
+
* 'SUBSCRIBED' or 'CHANNEL_ERROR' so the app can reflect state. */
|
|
206
|
+
_rejoinAfterReconnect(): Promise<void>;
|
|
207
|
+
on<T = Record<string, unknown>>(type: 'postgres_changes', filter: PostgresChangesFilter, callback: PostgresChangesCallback<T>): this;
|
|
208
|
+
on<T = Record<string, unknown>>(type: 'broadcast', filter: BroadcastFilter, callback: BroadcastCallback<T>): this;
|
|
209
|
+
on<T = Record<string, unknown>>(type: 'presence', filter: PresenceFilter, callback: PresenceCallback<T>): this;
|
|
210
|
+
/**
|
|
211
|
+
* Register or refresh this client's presence entry on the channel. Safe
|
|
212
|
+
* to call many times — state replaces (not merges). Starts a heartbeat
|
|
213
|
+
* timer at TTL/2 so the entry stays alive while the socket is open.
|
|
214
|
+
* The channel must be `subscribe()`d first (the server enforces this).
|
|
215
|
+
*/
|
|
216
|
+
track(state: Record<string, unknown>): Promise<void>;
|
|
217
|
+
/**
|
|
218
|
+
* Remove this client's presence entry immediately, stopping the
|
|
219
|
+
* heartbeat. Safe if the client never called `track`.
|
|
220
|
+
*/
|
|
221
|
+
untrack(): void;
|
|
222
|
+
/** Snapshot of the current presence state on this channel. Keys are
|
|
223
|
+
* opaque client identifiers (server-assigned). Re-read inside your
|
|
224
|
+
* `.on('presence', { event: 'sync' }, ...)` handler. */
|
|
225
|
+
presenceState<T = Record<string, unknown>>(): PresenceState<T>;
|
|
226
|
+
/**
|
|
227
|
+
* Register all bindings with the server:
|
|
228
|
+
* * For each `broadcast` binding, ensure we're subscribed to the topic
|
|
229
|
+
* (one `realtime:subscribe` for the channel as a whole).
|
|
230
|
+
* * For each `postgres_changes` binding, emit
|
|
231
|
+
* `realtime:postgres_changes:subscribe` and record the assigned
|
|
232
|
+
* subscription_id.
|
|
233
|
+
*
|
|
234
|
+
* `statusCallback` is invoked with `'SUBSCRIBED'` when every binding
|
|
235
|
+
* has ack'd, or with `'CHANNEL_ERROR' | 'TIMED_OUT'` on failure.
|
|
236
|
+
*/
|
|
237
|
+
subscribe(statusCallback?: ChannelStatusCallback): this;
|
|
238
|
+
/**
|
|
239
|
+
* Tear down every binding: unsubscribe from the broadcast topic (if
|
|
240
|
+
* any broadcast bindings exist) and remove every postgres_changes
|
|
241
|
+
* subscription by id. Safe to call when state is already closed.
|
|
242
|
+
*/
|
|
243
|
+
unsubscribe(): Promise<void>;
|
|
244
|
+
/**
|
|
245
|
+
* Publish a broadcast event to the topic. Broadcasts are always
|
|
246
|
+
* ephemeral — the server fans out to every subscribed socket in memory,
|
|
247
|
+
* with no DB persistence or webhook fan-out. For audited / durable
|
|
248
|
+
* events, write to your own application table and enable
|
|
249
|
+
* `postgres_changes` on it; the SDK will surface the INSERT as a
|
|
250
|
+
* `postgres_changes` event without a separate channel.send call.
|
|
251
|
+
*/
|
|
252
|
+
send<T extends Record<string, unknown>>(args: {
|
|
253
|
+
type: 'broadcast';
|
|
254
|
+
event: string;
|
|
255
|
+
payload: T;
|
|
256
|
+
}): Promise<{
|
|
257
|
+
ok: true;
|
|
258
|
+
message_id: string;
|
|
259
|
+
} | {
|
|
260
|
+
ok: false;
|
|
261
|
+
error: {
|
|
262
|
+
code: string;
|
|
263
|
+
message: string;
|
|
264
|
+
};
|
|
265
|
+
} | void>;
|
|
266
|
+
/**
|
|
267
|
+
* Replay SQL-originated broadcasts on this topic since the given
|
|
268
|
+
* timestamp. Delivered only to this socket (same envelope format as
|
|
269
|
+
* live broadcasts; the SDK routes them through `.on('broadcast', ...)`
|
|
270
|
+
* bindings just like the real-time path). Backend caps the window at
|
|
271
|
+
* 24 h and the limit at 1000.
|
|
272
|
+
*/
|
|
273
|
+
replay(args: {
|
|
274
|
+
since: string;
|
|
275
|
+
limit?: number;
|
|
276
|
+
}): Promise<void>;
|
|
277
|
+
/** Internal — called by Realtime's event router on every incoming event. */
|
|
278
|
+
_dispatch(event: string, envelope: Record<string, unknown>): void;
|
|
279
|
+
private firePresence;
|
|
280
|
+
private registerAllBindings;
|
|
281
|
+
}
|
|
282
|
+
declare class Realtime {
|
|
283
|
+
private socket;
|
|
284
|
+
private readonly baseUrl;
|
|
285
|
+
private readonly options;
|
|
286
|
+
private readonly anonKey;
|
|
287
|
+
private readonly tokenManager;
|
|
288
|
+
private channels;
|
|
289
|
+
private connecting;
|
|
290
|
+
/** Flips to `true` once the initial handshake resolves. Differentiates
|
|
291
|
+
* the first `connect` event (part of `openSocket`) from subsequent
|
|
292
|
+
* reconnect events (which should trigger auto-resubscribe). */
|
|
293
|
+
private firstConnected;
|
|
294
|
+
constructor(baseUrl: string, tokenManager: TokenManager, anonKey: string | undefined, options?: RealtimeOptions);
|
|
295
|
+
get isConnected(): boolean;
|
|
296
|
+
get socketId(): string | undefined;
|
|
297
|
+
/**
|
|
298
|
+
* Get (or create) a channel for `topic`. Channels are cached so multiple
|
|
299
|
+
* `.channel('same')` calls return the same instance.
|
|
300
|
+
*
|
|
301
|
+
* The optional `opts` argument lets the caller configure the channel:
|
|
302
|
+
* * `config.private` — enable subscribe-side authorization against
|
|
303
|
+
* `realtime.authorize_subscribe(...)` on the tenant DB.
|
|
304
|
+
* * `config.broadcast.ack` — `channel.send()` resolves with the
|
|
305
|
+
* server's ack (message_id) instead of fire-and-forget.
|
|
306
|
+
* * `config.broadcast.self` — `false` excludes the sender from the
|
|
307
|
+
* fan-out (defaults to `true`).
|
|
308
|
+
* * `config.presence.key` — stable presence key to group multiple
|
|
309
|
+
* tabs of the same user under one entry.
|
|
310
|
+
*
|
|
311
|
+
* Options are locked in when the channel is first created; subsequent
|
|
312
|
+
* `.channel('same')` calls with different opts are ignored. Pass a
|
|
313
|
+
* different topic to get a different-configured channel.
|
|
314
|
+
*/
|
|
315
|
+
channel(topic: string, opts?: ChannelOptions): RealtimeChannel;
|
|
316
|
+
connect(): Promise<void>;
|
|
317
|
+
/**
|
|
318
|
+
* Close the socket. Channels are left as-is so they can re-subscribe
|
|
319
|
+
* on the next `connect()` — useful for auth token refresh flows.
|
|
320
|
+
*/
|
|
321
|
+
disconnect(): void;
|
|
322
|
+
_getSocket(): Socket | null;
|
|
323
|
+
_detachChannel(channel: RealtimeChannel): void;
|
|
324
|
+
private openSocket;
|
|
325
|
+
private dispatch;
|
|
326
|
+
}
|
|
327
|
+
|
|
32
328
|
/**
|
|
33
329
|
* MITWAY-BaaS SDK types — only SDK-specific shapes live here.
|
|
34
330
|
* The `User` shape is inlined in `./lib/user` so this package has zero
|
|
@@ -89,6 +385,10 @@ interface MitwayBaasConfig {
|
|
|
89
385
|
* @default true
|
|
90
386
|
*/
|
|
91
387
|
autoRefreshToken?: boolean;
|
|
388
|
+
/**
|
|
389
|
+
* Realtime transport options. See `RealtimeOptions`.
|
|
390
|
+
*/
|
|
391
|
+
realtime?: RealtimeOptions;
|
|
92
392
|
}
|
|
93
393
|
/**
|
|
94
394
|
* Active user session in memory. Mirrors what the auth endpoints return.
|
|
@@ -146,27 +446,6 @@ declare class Logger {
|
|
|
146
446
|
logResponse(method: string, url: string, status: number, durationMs: number, body?: any): void;
|
|
147
447
|
}
|
|
148
448
|
|
|
149
|
-
/**
|
|
150
|
-
* Token Manager for the MITWAY-BaaS SDK.
|
|
151
|
-
*
|
|
152
|
-
* In-memory storage for the access token + user. Browser CSRF token lives
|
|
153
|
-
* in a cookie so the cookie-based refresh flow works across page reloads.
|
|
154
|
-
*/
|
|
155
|
-
|
|
156
|
-
declare class TokenManager {
|
|
157
|
-
private accessToken;
|
|
158
|
-
private user;
|
|
159
|
-
/** Fired when the access token changes (used by long-lived consumers). */
|
|
160
|
-
onTokenChange: (() => void) | null;
|
|
161
|
-
saveSession(session: AuthSession): void;
|
|
162
|
-
getSession(): AuthSession | null;
|
|
163
|
-
getAccessToken(): string | null;
|
|
164
|
-
setAccessToken(token: string): void;
|
|
165
|
-
getUser(): User | null;
|
|
166
|
-
setUser(user: User): void;
|
|
167
|
-
clearSession(): void;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
449
|
/**
|
|
171
450
|
* HttpClient with retry, timeout, abort signal composition, and automatic
|
|
172
451
|
* token refresh on 401 INVALID_TOKEN responses.
|
|
@@ -409,6 +688,7 @@ declare class MitwayBaasClient {
|
|
|
409
688
|
private tokenManager;
|
|
410
689
|
readonly auth: Auth;
|
|
411
690
|
readonly database: Database;
|
|
691
|
+
readonly realtime: Realtime;
|
|
412
692
|
constructor(config?: MitwayBaasConfig);
|
|
413
693
|
/**
|
|
414
694
|
* Escape hatch for callers that need to make custom requests against the
|
|
@@ -423,19 +703,19 @@ declare class MitwayBaasClient {
|
|
|
423
703
|
* Currently ships:
|
|
424
704
|
* - auth (signUp, signInWithPassword, signOut, refreshSession, getSession, getUser)
|
|
425
705
|
* - database (PostgREST-backed query builder via @supabase/postgrest-js)
|
|
706
|
+
* - realtime (Socket.IO transport: subscribe / unsubscribe / publish / on)
|
|
426
707
|
*
|
|
427
708
|
* Not yet included (no backend support):
|
|
428
709
|
* - storage
|
|
429
710
|
* - functions
|
|
430
711
|
* - email
|
|
431
712
|
* - ai
|
|
432
|
-
* - realtime
|
|
433
713
|
*
|
|
434
714
|
* @packageDocumentation
|
|
435
715
|
*/
|
|
436
716
|
|
|
437
717
|
/**
|
|
438
|
-
* Factory function for creating SDK clients
|
|
718
|
+
* Factory function for creating SDK clients.
|
|
439
719
|
*
|
|
440
720
|
* @example
|
|
441
721
|
* ```typescript
|
|
@@ -449,4 +729,4 @@ declare class MitwayBaasClient {
|
|
|
449
729
|
*/
|
|
450
730
|
declare function createClient(config: MitwayBaasConfig): MitwayBaasClient;
|
|
451
731
|
|
|
452
|
-
export { type ApiError, Auth, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, Database, HttpClient, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type SignInRequest, type SignUpRequest, TokenManager, type User, createClient, MitwayBaasClient as default };
|
|
732
|
+
export { type ApiError, Auth, type AuthRefreshResponse, type AuthResponse, type AuthResult, type AuthSession, type BroadcastFilter, type BroadcastPayload, type ChannelOptions, type ChannelStatus, type ChannelStatusCallback, Database, HttpClient, Logger, MitwayBaasClient, type MitwayBaasConfig, MitwayBaasError, type PostgresChangesEventSelector, type PostgresChangesFilter, type PostgresChangesPayload, type PresenceEventSelector, type PresenceFilter, type PresenceJoinPayload, type PresenceLeavePayload, type PresencePayload, type PresenceState, type PresenceSyncPayload, Realtime, RealtimeChannel, type RealtimeMessageMeta, type RealtimeOptions, type SignInRequest, type SignUpRequest, TokenManager, type User, createClient, MitwayBaasClient as default };
|