@cstar.help/js 0.1.0 → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 cStar
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -23,8 +23,8 @@ Manage tickets, customers, articles, and webhooks with your secret API key.
23
23
  import { CStarClient } from '@cstar.help/js';
24
24
 
25
25
  const cstar = new CStarClient({
26
- apiKey: 'sk_live_abc123...',
27
- teamId: 'tm_your_team_id',
26
+ apiKey: 'sk_live_abc123...',
27
+ teamId: 'tm_your_team_id'
28
28
  });
29
29
 
30
30
  // List open tickets
@@ -32,8 +32,8 @@ const { data: tickets } = await cstar.tickets.list({ status: 'open' });
32
32
 
33
33
  // Create a ticket
34
34
  const { data: ticket } = await cstar.tickets.create({
35
- title: 'Help with billing',
36
- customerId: 'cus_abc123',
35
+ title: 'Help with billing',
36
+ customerId: 'cus_abc123'
37
37
  });
38
38
 
39
39
  // Get a customer with expanded fields
@@ -41,7 +41,7 @@ const { data: customer } = await cstar.customers.get('cus_abc123');
41
41
 
42
42
  // Auto-paginate through all tickets
43
43
  for await (const ticket of cstar.tickets.listAutoPaginating({ status: 'open' })) {
44
- console.log(ticket.title);
44
+ console.log(ticket.title);
45
45
  }
46
46
  ```
47
47
 
@@ -56,8 +56,8 @@ const chat = new ChatClient({ teamSlug: 'acme' });
56
56
 
57
57
  // Identify the customer (HMAC signature from your server)
58
58
  await chat.identify(
59
- { externalId: 'usr_123', email: 'jane@example.com', name: 'Jane', timestamp: Date.now() / 1000 },
60
- hmacSignature
59
+ { externalId: 'usr_123', email: 'jane@example.com', name: 'Jane', timestamp: Date.now() / 1000 },
60
+ hmacSignature
61
61
  );
62
62
 
63
63
  // List conversations
@@ -68,7 +68,7 @@ await chat.messages.send('tkt_abc123', 'Thanks for the help!');
68
68
 
69
69
  // Subscribe to new messages (polling)
70
70
  const unsubscribe = chat.onMessage('tkt_abc123', (message) => {
71
- console.log(`${message.sender_name}: ${message.content}`);
71
+ console.log(`${message.sender_name}: ${message.content}`);
72
72
  });
73
73
 
74
74
  // Clean up
@@ -105,12 +105,12 @@ import { constructEvent } from '@cstar.help/js/webhook';
105
105
  const event = constructEvent(rawBody, signature, 'whsec_your_secret');
106
106
 
107
107
  switch (event.type) {
108
- case 'ticket.created':
109
- console.log('New ticket:', event.data.title);
110
- break;
111
- case 'customer.created':
112
- console.log('New customer:', event.data.email);
113
- break;
108
+ case 'ticket.created':
109
+ console.log('New ticket:', event.data.title);
110
+ break;
111
+ case 'customer.created':
112
+ console.log('New customer:', event.data.email);
113
+ break;
114
114
  }
115
115
  ```
116
116
 
@@ -126,24 +126,24 @@ const event = await constructEventAsync(rawBody, signature, secret);
126
126
 
127
127
  ### CStarClient
128
128
 
129
- | Resource | Methods |
130
- |----------|---------|
131
- | `cstar.tickets` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.listAutoPaginating()` |
132
- | `cstar.tickets.messages` | `.list(ticketId)` `.create(ticketId, params)` |
133
- | `cstar.customers` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.listAutoPaginating()` |
134
- | `cstar.articles` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.listAutoPaginating()` |
135
- | `cstar.webhooks` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.test(id)` |
129
+ | Resource | Methods |
130
+ | ------------------------ | ----------------------------------------------------------------------------------------------- |
131
+ | `cstar.tickets` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.listAutoPaginating()` |
132
+ | `cstar.tickets.messages` | `.list(ticketId)` `.create(ticketId, params)` |
133
+ | `cstar.customers` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.listAutoPaginating()` |
134
+ | `cstar.articles` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.listAutoPaginating()` |
135
+ | `cstar.webhooks` | `.list()` `.get(id)` `.create(params)` `.update(id, params)` `.del(id)` `.test(id)` |
136
136
 
137
137
  ### Configuration
138
138
 
139
139
  ```typescript
140
140
  const cstar = new CStarClient({
141
- apiKey: 'sk_live_...', // Required — secret or publishable key
142
- teamId: 'tm_...', // Required — your team ID
143
- baseUrl: 'https://...', // Optional — defaults to https://app.cstar.help
144
- version: '2026-03-01', // Optional — API version header
145
- maxRetries: 3, // Optional — retry attempts for 5xx/429
146
- timeout: 30000, // Optional — request timeout in ms
141
+ apiKey: 'sk_live_...', // Required — secret or publishable key
142
+ teamId: 'tm_...', // Required — your team ID
143
+ baseUrl: 'https://...', // Optional — defaults to https://app.cstar.help
144
+ version: '2026-03-01', // Optional — API version header
145
+ maxRetries: 3, // Optional — retry attempts for 5xx/429
146
+ timeout: 30000 // Optional — request timeout in ms
147
147
  });
148
148
  ```
149
149
 
@@ -154,8 +154,8 @@ Test mode is auto-detected from your API key prefix:
154
154
  ```typescript
155
155
  // Uses test data — no real customers affected
156
156
  const cstar = new CStarClient({
157
- apiKey: 'sk_test_abc123...',
158
- teamId: 'tm_your_team_id',
157
+ apiKey: 'sk_test_abc123...',
158
+ teamId: 'tm_your_team_id'
159
159
  });
160
160
 
161
161
  console.log(cstar.isTestMode); // true
@@ -169,15 +169,15 @@ All API errors throw typed exceptions:
169
169
  import { CStarError, CStarNotFoundError, CStarValidationError } from '@cstar.help/js';
170
170
 
171
171
  try {
172
- await cstar.tickets.get('tkt_nonexistent');
172
+ await cstar.tickets.get('tkt_nonexistent');
173
173
  } catch (err) {
174
- if (err instanceof CStarNotFoundError) {
175
- console.log('Ticket not found:', err.message);
176
- } else if (err instanceof CStarValidationError) {
177
- console.log('Invalid param:', err.param);
178
- } else if (err instanceof CStarError) {
179
- console.log('API error:', err.code, err.statusCode);
180
- }
174
+ if (err instanceof CStarNotFoundError) {
175
+ console.log('Ticket not found:', err.message);
176
+ } else if (err instanceof CStarValidationError) {
177
+ console.log('Invalid param:', err.param);
178
+ } else if (err instanceof CStarError) {
179
+ console.log('API error:', err.code, err.statusCode);
180
+ }
181
181
  }
182
182
  ```
183
183
 
@@ -187,8 +187,8 @@ Safely retry create operations:
187
187
 
188
188
  ```typescript
189
189
  const { data: ticket } = await cstar.tickets.create(
190
- { title: 'Billing issue', customerId: 'cus_abc' },
191
- { idempotencyKey: 'create-billing-issue-usr123' }
190
+ { title: 'Billing issue', customerId: 'cus_abc' },
191
+ { idempotencyKey: 'create-billing-issue-usr123' }
192
192
  );
193
193
  ```
194
194
 
@@ -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;