@cstar.help/js 0.1.0 → 0.2.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.
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/chat/index.ts
@@ -23,16 +33,265 @@ __export(chat_exports, {
23
33
  ChatClient: () => ChatClient
24
34
  });
25
35
  module.exports = __toCommonJS(chat_exports);
36
+
37
+ // src/chat/realtime.ts
38
+ var RealtimeManager = class {
39
+ constructor(options) {
40
+ this.client = null;
41
+ this.initPromise = null;
42
+ this.channels = /* @__PURE__ */ new Map();
43
+ this.refreshTimer = null;
44
+ this.currentToken = null;
45
+ this.options = options;
46
+ }
47
+ /**
48
+ * Initialize the Supabase client and authenticate with a realtime token.
49
+ * Returns true if successful, false if @supabase/supabase-js is unavailable.
50
+ */
51
+ init() {
52
+ if (this.initPromise) return this.initPromise;
53
+ this.initPromise = this.doInit();
54
+ return this.initPromise;
55
+ }
56
+ async doInit() {
57
+ try {
58
+ const { createClient } = await import(
59
+ /* webpackIgnore: true */
60
+ "@supabase/supabase-js"
61
+ );
62
+ this.client = createClient(this.options.supabaseUrl, this.options.supabaseAnonKey, {
63
+ auth: { persistSession: false, autoRefreshToken: false },
64
+ realtime: { params: { eventsPerSecond: 10 } }
65
+ });
66
+ const tokenData = await this.options.fetchToken();
67
+ this.setToken(tokenData);
68
+ return true;
69
+ } catch {
70
+ this.initPromise = null;
71
+ return false;
72
+ }
73
+ }
74
+ setToken(tokenData) {
75
+ this.currentToken = tokenData.token;
76
+ if (this.client) {
77
+ this.client.realtime.setAuth(tokenData.token);
78
+ }
79
+ this.scheduleRefresh(tokenData.refreshAt);
80
+ }
81
+ scheduleRefresh(refreshAt) {
82
+ if (this.refreshTimer) {
83
+ clearTimeout(this.refreshTimer);
84
+ }
85
+ const msUntilRefresh = new Date(refreshAt).getTime() - Date.now();
86
+ const delay = Math.max(msUntilRefresh, 1e4);
87
+ this.refreshTimer = setTimeout(() => this.doRefresh(), delay);
88
+ }
89
+ async doRefresh() {
90
+ try {
91
+ const tokenData = await this.options.fetchToken();
92
+ this.setToken(tokenData);
93
+ } catch {
94
+ this.refreshTimer = setTimeout(() => this.doRefresh(), 3e4);
95
+ }
96
+ }
97
+ /**
98
+ * Subscribe to new messages on a ticket via Postgres Changes.
99
+ * Returns an unsubscribe function.
100
+ */
101
+ subscribeToMessages(ticketId, callback) {
102
+ if (!this.client) return () => {
103
+ };
104
+ const channelName = `messages:${ticketId}`;
105
+ this.removeChannel(channelName);
106
+ const channel = this.client.channel(channelName).on(
107
+ "postgres_changes",
108
+ {
109
+ event: "INSERT",
110
+ schema: "public",
111
+ table: "messages",
112
+ filter: `ticket_id=eq.${ticketId}`
113
+ },
114
+ (payload) => {
115
+ const row = payload.new;
116
+ if (!row) return;
117
+ const message = {
118
+ id: row.id,
119
+ content: row.content,
120
+ sender: row.sender,
121
+ sender_name: row.sender_name ?? "",
122
+ created_at: row.created_at,
123
+ read_at: row.read_at ?? null,
124
+ attachments: row.attachments ?? []
125
+ };
126
+ callback(message);
127
+ }
128
+ ).subscribe();
129
+ this.channels.set(channelName, channel);
130
+ return () => this.removeChannel(channelName);
131
+ }
132
+ /** Get the underlying Supabase client (for sharing with PresenceManager). */
133
+ getClient() {
134
+ return this.client;
135
+ }
136
+ /** Whether the realtime manager is initialized and has a token. */
137
+ get isReady() {
138
+ return this.client !== null && this.currentToken !== null;
139
+ }
140
+ removeChannel(name) {
141
+ const existing = this.channels.get(name);
142
+ if (existing && this.client) {
143
+ this.client.removeChannel(existing);
144
+ this.channels.delete(name);
145
+ }
146
+ }
147
+ /** Clean up all channels, timers, and the client. */
148
+ destroy() {
149
+ if (this.refreshTimer) {
150
+ clearTimeout(this.refreshTimer);
151
+ this.refreshTimer = null;
152
+ }
153
+ for (const [name] of this.channels) {
154
+ this.removeChannel(name);
155
+ }
156
+ this.channels.clear();
157
+ this.client = null;
158
+ this.initPromise = null;
159
+ this.currentToken = null;
160
+ }
161
+ };
162
+
163
+ // src/chat/presence.ts
164
+ var TYPING_THROTTLE_MS = 2e3;
165
+ var TYPING_CLEAR_DELAY_MS = 3e3;
166
+ var PresenceManager = class {
167
+ constructor(options) {
168
+ this.client = null;
169
+ this.channels = /* @__PURE__ */ new Map();
170
+ this.lastTypingSentAt = /* @__PURE__ */ new Map();
171
+ this.typingClearTimers = /* @__PURE__ */ new Map();
172
+ this.options = options;
173
+ }
174
+ /** Set the Supabase client (shared from RealtimeManager). */
175
+ setClient(client) {
176
+ this.client = client;
177
+ }
178
+ /**
179
+ * Subscribe to agent typing events on a ticket.
180
+ * Only fires callback for agent typing (has `agent_id`), not customer typing echoes.
181
+ *
182
+ * @returns Unsubscribe function
183
+ */
184
+ subscribeToTyping(ticketId, callback) {
185
+ if (!this.client) return () => {
186
+ };
187
+ const channelName = `typing:${ticketId}`;
188
+ this.removeChannel(channelName);
189
+ const channel = this.client.channel(`ticket:${ticketId}`).on("broadcast", { event: "typing" }, (data) => {
190
+ const payload = data?.payload;
191
+ if (!payload) return;
192
+ if (payload.agent_id) {
193
+ const typingPayload = {
194
+ agent_id: payload.agent_id,
195
+ agent_name: payload.agent_name || "Agent",
196
+ is_typing: !!payload.is_typing
197
+ };
198
+ callback(typingPayload);
199
+ }
200
+ }).subscribe();
201
+ this.channels.set(channelName, channel);
202
+ return () => this.removeChannel(channelName);
203
+ }
204
+ /**
205
+ * Send a customer typing indicator.
206
+ * Throttled: max 1 typing=true per 2s, auto-clears after 3s.
207
+ */
208
+ async sendTyping(ticketId, isTyping) {
209
+ if (!this.client) return;
210
+ const existingTimer = this.typingClearTimers.get(ticketId);
211
+ if (existingTimer) {
212
+ clearTimeout(existingTimer);
213
+ this.typingClearTimers.delete(ticketId);
214
+ }
215
+ if (isTyping) {
216
+ const lastSent = this.lastTypingSentAt.get(ticketId) || 0;
217
+ const now = Date.now();
218
+ if (now - lastSent < TYPING_THROTTLE_MS) {
219
+ const timer2 = setTimeout(() => {
220
+ this.doSendTyping(ticketId, false);
221
+ }, TYPING_CLEAR_DELAY_MS);
222
+ this.typingClearTimers.set(ticketId, timer2);
223
+ return;
224
+ }
225
+ this.lastTypingSentAt.set(ticketId, now);
226
+ const timer = setTimeout(() => {
227
+ this.doSendTyping(ticketId, false);
228
+ }, TYPING_CLEAR_DELAY_MS);
229
+ this.typingClearTimers.set(ticketId, timer);
230
+ }
231
+ await this.doSendTyping(ticketId, isTyping);
232
+ }
233
+ async doSendTyping(ticketId, isTyping) {
234
+ if (!this.client) return;
235
+ try {
236
+ const sendChannelName = `typing-send:${ticketId}`;
237
+ let channel = this.channels.get(sendChannelName);
238
+ if (!channel) {
239
+ channel = this.client.channel(`ticket:${ticketId}`);
240
+ channel.subscribe();
241
+ this.channels.set(sendChannelName, channel);
242
+ }
243
+ await channel.send({
244
+ type: "broadcast",
245
+ event: "typing",
246
+ payload: {
247
+ customer_id: this.options.customerId,
248
+ customer_name: this.options.customerName,
249
+ is_typing: isTyping
250
+ }
251
+ });
252
+ } catch {
253
+ }
254
+ }
255
+ removeChannel(name) {
256
+ const existing = this.channels.get(name);
257
+ if (existing && this.client) {
258
+ this.client.removeChannel(existing);
259
+ this.channels.delete(name);
260
+ }
261
+ }
262
+ /** Clean up all channels and timers. */
263
+ destroy() {
264
+ for (const timer of this.typingClearTimers.values()) {
265
+ clearTimeout(timer);
266
+ }
267
+ this.typingClearTimers.clear();
268
+ this.lastTypingSentAt.clear();
269
+ for (const [name] of this.channels) {
270
+ this.removeChannel(name);
271
+ }
272
+ this.channels.clear();
273
+ this.client = null;
274
+ }
275
+ };
276
+
277
+ // src/chat/index.ts
26
278
  var DEFAULT_BASE_URL = "https://app.cstar.help";
27
279
  var DEFAULT_POLLING_INTERVAL = 3e3;
28
280
  var ChatClient = class {
29
281
  constructor(config) {
30
282
  this.sessionToken = null;
31
283
  this.teamId = null;
284
+ this.customerId = null;
32
285
  this.pollingTimers = /* @__PURE__ */ new Map();
286
+ this.realtimeManager = null;
287
+ this.presenceManager = null;
288
+ this.realtimeReady = false;
289
+ this.realtimeInitPromise = null;
33
290
  this.baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
34
291
  this.teamSlug = config.teamSlug;
35
292
  this.pollingInterval = config.pollingInterval ?? DEFAULT_POLLING_INTERVAL;
293
+ this.supabaseUrl = config.supabaseUrl;
294
+ this.supabaseAnonKey = config.supabaseAnonKey;
36
295
  this.conversations = new ConversationsApi(this);
37
296
  this.messages = new MessagesApi(this);
38
297
  }
@@ -40,6 +299,9 @@ var ChatClient = class {
40
299
  * Identify a customer using HMAC signature verification.
41
300
  * Must be called before accessing conversations or messages.
42
301
  *
302
+ * If `supabaseUrl` and `supabaseAnonKey` were provided in the config,
303
+ * this will also initialize real-time subscriptions (non-blocking).
304
+ *
43
305
  * @param customer - Customer identity fields
44
306
  * @param signature - HMAC-SHA256 hex signature of the signed fields
45
307
  * @param testMode - Whether to use test mode (relaxed timestamp validation)
@@ -58,40 +320,27 @@ var ChatClient = class {
58
320
  }
59
321
  );
60
322
  this.sessionToken = response.data.sessionToken;
323
+ this.teamId = response.data.teamId;
324
+ this.customerId = response.data.customer.id;
325
+ if (this.supabaseUrl && this.supabaseAnonKey) {
326
+ this.realtimeInitPromise = this.initRealtime(
327
+ response.data.customer.id,
328
+ response.data.customer.name || customer.name || customer.email
329
+ );
330
+ }
61
331
  return response.data;
62
332
  }
63
333
  /**
64
334
  * Subscribe to new messages on a conversation.
65
- * Falls back to polling when Supabase Realtime is not available.
335
+ * Uses Supabase Realtime (Postgres Changes) when available, falls back to polling.
66
336
  *
67
337
  * @returns Unsubscribe function
68
338
  */
69
339
  onMessage(ticketId, callback) {
70
- let lastMessageId = null;
71
- const poll = async () => {
72
- try {
73
- const messages = await this.messages.list(ticketId);
74
- if (messages.length > 0) {
75
- const latest = messages[messages.length - 1];
76
- if (lastMessageId && latest.id !== lastMessageId) {
77
- const lastIdx = messages.findIndex((m) => m.id === lastMessageId);
78
- const newMessages = lastIdx >= 0 ? messages.slice(lastIdx + 1) : [latest];
79
- for (const msg of newMessages) {
80
- callback(msg);
81
- }
82
- }
83
- lastMessageId = latest.id;
84
- }
85
- } catch {
86
- }
87
- };
88
- poll();
89
- const timer = setInterval(poll, this.pollingInterval);
90
- this.pollingTimers.set(ticketId, timer);
91
- return () => {
92
- clearInterval(timer);
93
- this.pollingTimers.delete(ticketId);
94
- };
340
+ if (this.realtimeReady && this.realtimeManager) {
341
+ return this.realtimeManager.subscribeToMessages(ticketId, callback);
342
+ }
343
+ return this.pollMessages(ticketId, callback);
95
344
  }
96
345
  /**
97
346
  * Subscribe to typing indicator events.
@@ -99,17 +348,41 @@ var ChatClient = class {
99
348
  *
100
349
  * @returns Unsubscribe function
101
350
  */
102
- onTyping(_ticketId, _callback) {
351
+ onTyping(ticketId, callback) {
352
+ if (this.realtimeReady && this.presenceManager) {
353
+ return this.presenceManager.subscribeToTyping(ticketId, callback);
354
+ }
103
355
  return () => {
104
356
  };
105
357
  }
358
+ /**
359
+ * Send a customer typing indicator (requires realtime).
360
+ * No-op if realtime is not available.
361
+ */
362
+ async sendTyping(ticketId, isTyping) {
363
+ if (this.presenceManager) {
364
+ await this.presenceManager.sendTyping(ticketId, isTyping);
365
+ }
366
+ }
106
367
  /** Disconnect all subscriptions and clean up. */
107
368
  disconnect() {
369
+ if (this.realtimeManager) {
370
+ this.realtimeManager.destroy();
371
+ this.realtimeManager = null;
372
+ }
373
+ if (this.presenceManager) {
374
+ this.presenceManager.destroy();
375
+ this.presenceManager = null;
376
+ }
377
+ this.realtimeReady = false;
378
+ this.realtimeInitPromise = null;
108
379
  for (const timer of this.pollingTimers.values()) {
109
380
  clearInterval(timer);
110
381
  }
111
382
  this.pollingTimers.clear();
112
383
  this.sessionToken = null;
384
+ this.teamId = null;
385
+ this.customerId = null;
113
386
  }
114
387
  /** @internal Make an authenticated request to the widget API. */
115
388
  async fetch(path, options) {
@@ -139,6 +412,72 @@ var ChatClient = class {
139
412
  setTeamId(teamId) {
140
413
  this.teamId = teamId;
141
414
  }
415
+ /** @internal Wait for realtime to be initialized (for testing). */
416
+ async waitForRealtime() {
417
+ if (this.realtimeInitPromise) {
418
+ await this.realtimeInitPromise;
419
+ }
420
+ }
421
+ async initRealtime(customerId, customerName) {
422
+ try {
423
+ this.realtimeManager = new RealtimeManager({
424
+ supabaseUrl: this.supabaseUrl,
425
+ supabaseAnonKey: this.supabaseAnonKey,
426
+ fetchToken: () => this.fetchRealtimeToken()
427
+ });
428
+ const ready = await this.realtimeManager.init();
429
+ if (ready) {
430
+ this.realtimeReady = true;
431
+ this.presenceManager = new PresenceManager({
432
+ customerId,
433
+ customerName
434
+ });
435
+ const client = this.realtimeManager.getClient();
436
+ if (client) {
437
+ this.presenceManager.setClient(client);
438
+ }
439
+ }
440
+ } catch {
441
+ this.realtimeReady = false;
442
+ }
443
+ }
444
+ async fetchRealtimeToken() {
445
+ const response = await this.fetch(
446
+ "/api/widget/realtime-token",
447
+ {
448
+ method: "POST",
449
+ body: { teamId: this.teamId }
450
+ }
451
+ );
452
+ return response.data;
453
+ }
454
+ pollMessages(ticketId, callback) {
455
+ let lastMessageId = null;
456
+ const poll = async () => {
457
+ try {
458
+ const messages = await this.messages.list(ticketId);
459
+ if (messages.length > 0) {
460
+ const latest = messages[messages.length - 1];
461
+ if (lastMessageId && latest.id !== lastMessageId) {
462
+ const lastIdx = messages.findIndex((m) => m.id === lastMessageId);
463
+ const newMessages = lastIdx >= 0 ? messages.slice(lastIdx + 1) : [latest];
464
+ for (const msg of newMessages) {
465
+ callback(msg);
466
+ }
467
+ }
468
+ lastMessageId = latest.id;
469
+ }
470
+ } catch {
471
+ }
472
+ };
473
+ poll();
474
+ const timer = setInterval(poll, this.pollingInterval);
475
+ this.pollingTimers.set(ticketId, timer);
476
+ return () => {
477
+ clearInterval(timer);
478
+ this.pollingTimers.delete(ticketId);
479
+ };
480
+ }
142
481
  buildUrl(path, query) {
143
482
  const base = `${this.baseUrl}${path}`;
144
483
  if (!query) return base;
@@ -173,17 +512,14 @@ var ConversationsApi = class {
173
512
  /** Create a new conversation (ticket). */
174
513
  async create(params) {
175
514
  const teamId = this.chat.getTeamId();
176
- const response = await this.chat.fetch(
177
- "/api/widget/tickets",
178
- {
179
- method: "POST",
180
- body: {
181
- teamId,
182
- subject: params.subject,
183
- message: params.message
184
- }
515
+ const response = await this.chat.fetch("/api/widget/tickets", {
516
+ method: "POST",
517
+ body: {
518
+ teamId,
519
+ subject: params.subject,
520
+ message: params.message
185
521
  }
186
- );
522
+ });
187
523
  return {
188
524
  id: response.data.id,
189
525
  ticketNumber: "",
@@ -40,6 +40,14 @@ interface IdentifyResult {
40
40
  };
41
41
  sessionToken: string;
42
42
  expiresAt: string;
43
+ /** Team UUID — used for realtime token requests. */
44
+ teamId: string;
45
+ }
46
+ /** Response from the realtime-token endpoint. */
47
+ interface RealtimeTokenResponse {
48
+ token: string;
49
+ expiresAt: string;
50
+ refreshAt: string;
43
51
  }
44
52
  /** A customer conversation (maps to a ticket). */
45
53
  interface Conversation {
@@ -92,22 +100,38 @@ type TypingCallback = (payload: TypingPayload) => void;
92
100
  /**
93
101
  * Customer-facing chat client for the cStar widget API.
94
102
  *
103
+ * Supports real-time messages and typing indicators when `supabaseUrl`
104
+ * and `supabaseAnonKey` are provided and `@supabase/supabase-js` is installed.
105
+ * Falls back to polling otherwise.
106
+ *
95
107
  * ```typescript
96
- * const chat = new ChatClient({ teamSlug: 'acme' });
108
+ * const chat = new ChatClient({
109
+ * teamSlug: 'acme',
110
+ * supabaseUrl: 'https://xxx.supabase.co',
111
+ * supabaseAnonKey: 'eyJ...',
112
+ * });
97
113
  * await chat.identify(
98
114
  * { externalId: 'usr_123', email: 'jane@co.com', name: 'Jane', timestamp: Date.now() / 1000 },
99
115
  * 'hmac_signature_hex'
100
116
  * );
101
- * const { conversations } = await chat.conversations.list();
117
+ * chat.onMessage('tkt_abc', (msg) => console.log(msg));
118
+ * chat.onTyping('tkt_abc', ({ agent_name }) => console.log(agent_name, 'is typing'));
102
119
  * ```
103
120
  */
104
121
  declare class ChatClient {
105
122
  private readonly baseUrl;
106
123
  private readonly teamSlug;
107
124
  private readonly pollingInterval;
125
+ private readonly supabaseUrl?;
126
+ private readonly supabaseAnonKey?;
108
127
  private sessionToken;
109
128
  private teamId;
129
+ private customerId;
110
130
  private pollingTimers;
131
+ private realtimeManager;
132
+ private presenceManager;
133
+ private realtimeReady;
134
+ private realtimeInitPromise;
111
135
  /** Sub-resource for managing conversations. */
112
136
  readonly conversations: ConversationsApi;
113
137
  /** Sub-resource for managing messages. */
@@ -117,6 +141,9 @@ declare class ChatClient {
117
141
  * Identify a customer using HMAC signature verification.
118
142
  * Must be called before accessing conversations or messages.
119
143
  *
144
+ * If `supabaseUrl` and `supabaseAnonKey` were provided in the config,
145
+ * this will also initialize real-time subscriptions (non-blocking).
146
+ *
120
147
  * @param customer - Customer identity fields
121
148
  * @param signature - HMAC-SHA256 hex signature of the signed fields
122
149
  * @param testMode - Whether to use test mode (relaxed timestamp validation)
@@ -124,7 +151,7 @@ declare class ChatClient {
124
151
  identify(customer: IdentifyParams, signature: string, testMode?: boolean): Promise<IdentifyResult>;
125
152
  /**
126
153
  * Subscribe to new messages on a conversation.
127
- * Falls back to polling when Supabase Realtime is not available.
154
+ * Uses Supabase Realtime (Postgres Changes) when available, falls back to polling.
128
155
  *
129
156
  * @returns Unsubscribe function
130
157
  */
@@ -135,7 +162,12 @@ declare class ChatClient {
135
162
  *
136
163
  * @returns Unsubscribe function
137
164
  */
138
- onTyping(_ticketId: string, _callback: TypingCallback): () => void;
165
+ onTyping(ticketId: string, callback: TypingCallback): () => void;
166
+ /**
167
+ * Send a customer typing indicator (requires realtime).
168
+ * No-op if realtime is not available.
169
+ */
170
+ sendTyping(ticketId: string, isTyping: boolean): Promise<void>;
139
171
  /** Disconnect all subscriptions and clean up. */
140
172
  disconnect(): void;
141
173
  /** @internal Make an authenticated request to the widget API. */
@@ -148,6 +180,11 @@ declare class ChatClient {
148
180
  getTeamId(): string | null;
149
181
  /** @internal Set team ID from identify response or other source. */
150
182
  setTeamId(teamId: string): void;
183
+ /** @internal Wait for realtime to be initialized (for testing). */
184
+ waitForRealtime(): Promise<void>;
185
+ private initRealtime;
186
+ private fetchRealtimeToken;
187
+ private pollMessages;
151
188
  private buildUrl;
152
189
  }
153
190
  /** Conversations sub-resource on ChatClient. */
@@ -169,4 +206,4 @@ declare class MessagesApi {
169
206
  send(ticketId: string, content: string): Promise<WidgetMessage>;
170
207
  }
171
208
 
172
- export { ChatClient, type ChatConfig, type Conversation, type ConversationCreateParams, type ConversationListParams, type ConversationListResponse, type IdentifyParams, type IdentifyResult, type MessageCallback, type TypingCallback, type WidgetMessage };
209
+ export { ChatClient, type ChatConfig, type Conversation, type ConversationCreateParams, type ConversationListParams, type ConversationListResponse, type IdentifyParams, type IdentifyResult, type MessageCallback, type RealtimeTokenResponse, type TypingCallback, type TypingPayload, type WidgetMessage };
@@ -40,6 +40,14 @@ interface IdentifyResult {
40
40
  };
41
41
  sessionToken: string;
42
42
  expiresAt: string;
43
+ /** Team UUID — used for realtime token requests. */
44
+ teamId: string;
45
+ }
46
+ /** Response from the realtime-token endpoint. */
47
+ interface RealtimeTokenResponse {
48
+ token: string;
49
+ expiresAt: string;
50
+ refreshAt: string;
43
51
  }
44
52
  /** A customer conversation (maps to a ticket). */
45
53
  interface Conversation {
@@ -92,22 +100,38 @@ type TypingCallback = (payload: TypingPayload) => void;
92
100
  /**
93
101
  * Customer-facing chat client for the cStar widget API.
94
102
  *
103
+ * Supports real-time messages and typing indicators when `supabaseUrl`
104
+ * and `supabaseAnonKey` are provided and `@supabase/supabase-js` is installed.
105
+ * Falls back to polling otherwise.
106
+ *
95
107
  * ```typescript
96
- * const chat = new ChatClient({ teamSlug: 'acme' });
108
+ * const chat = new ChatClient({
109
+ * teamSlug: 'acme',
110
+ * supabaseUrl: 'https://xxx.supabase.co',
111
+ * supabaseAnonKey: 'eyJ...',
112
+ * });
97
113
  * await chat.identify(
98
114
  * { externalId: 'usr_123', email: 'jane@co.com', name: 'Jane', timestamp: Date.now() / 1000 },
99
115
  * 'hmac_signature_hex'
100
116
  * );
101
- * const { conversations } = await chat.conversations.list();
117
+ * chat.onMessage('tkt_abc', (msg) => console.log(msg));
118
+ * chat.onTyping('tkt_abc', ({ agent_name }) => console.log(agent_name, 'is typing'));
102
119
  * ```
103
120
  */
104
121
  declare class ChatClient {
105
122
  private readonly baseUrl;
106
123
  private readonly teamSlug;
107
124
  private readonly pollingInterval;
125
+ private readonly supabaseUrl?;
126
+ private readonly supabaseAnonKey?;
108
127
  private sessionToken;
109
128
  private teamId;
129
+ private customerId;
110
130
  private pollingTimers;
131
+ private realtimeManager;
132
+ private presenceManager;
133
+ private realtimeReady;
134
+ private realtimeInitPromise;
111
135
  /** Sub-resource for managing conversations. */
112
136
  readonly conversations: ConversationsApi;
113
137
  /** Sub-resource for managing messages. */
@@ -117,6 +141,9 @@ declare class ChatClient {
117
141
  * Identify a customer using HMAC signature verification.
118
142
  * Must be called before accessing conversations or messages.
119
143
  *
144
+ * If `supabaseUrl` and `supabaseAnonKey` were provided in the config,
145
+ * this will also initialize real-time subscriptions (non-blocking).
146
+ *
120
147
  * @param customer - Customer identity fields
121
148
  * @param signature - HMAC-SHA256 hex signature of the signed fields
122
149
  * @param testMode - Whether to use test mode (relaxed timestamp validation)
@@ -124,7 +151,7 @@ declare class ChatClient {
124
151
  identify(customer: IdentifyParams, signature: string, testMode?: boolean): Promise<IdentifyResult>;
125
152
  /**
126
153
  * Subscribe to new messages on a conversation.
127
- * Falls back to polling when Supabase Realtime is not available.
154
+ * Uses Supabase Realtime (Postgres Changes) when available, falls back to polling.
128
155
  *
129
156
  * @returns Unsubscribe function
130
157
  */
@@ -135,7 +162,12 @@ declare class ChatClient {
135
162
  *
136
163
  * @returns Unsubscribe function
137
164
  */
138
- onTyping(_ticketId: string, _callback: TypingCallback): () => void;
165
+ onTyping(ticketId: string, callback: TypingCallback): () => void;
166
+ /**
167
+ * Send a customer typing indicator (requires realtime).
168
+ * No-op if realtime is not available.
169
+ */
170
+ sendTyping(ticketId: string, isTyping: boolean): Promise<void>;
139
171
  /** Disconnect all subscriptions and clean up. */
140
172
  disconnect(): void;
141
173
  /** @internal Make an authenticated request to the widget API. */
@@ -148,6 +180,11 @@ declare class ChatClient {
148
180
  getTeamId(): string | null;
149
181
  /** @internal Set team ID from identify response or other source. */
150
182
  setTeamId(teamId: string): void;
183
+ /** @internal Wait for realtime to be initialized (for testing). */
184
+ waitForRealtime(): Promise<void>;
185
+ private initRealtime;
186
+ private fetchRealtimeToken;
187
+ private pollMessages;
151
188
  private buildUrl;
152
189
  }
153
190
  /** Conversations sub-resource on ChatClient. */
@@ -169,4 +206,4 @@ declare class MessagesApi {
169
206
  send(ticketId: string, content: string): Promise<WidgetMessage>;
170
207
  }
171
208
 
172
- export { ChatClient, type ChatConfig, type Conversation, type ConversationCreateParams, type ConversationListParams, type ConversationListResponse, type IdentifyParams, type IdentifyResult, type MessageCallback, type TypingCallback, type WidgetMessage };
209
+ export { ChatClient, type ChatConfig, type Conversation, type ConversationCreateParams, type ConversationListParams, type ConversationListResponse, type IdentifyParams, type IdentifyResult, type MessageCallback, type RealtimeTokenResponse, type TypingCallback, type TypingPayload, type WidgetMessage };