@mailhooks/sdk 2.3.0 → 2.5.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/README.md CHANGED
@@ -161,6 +161,124 @@ const email = await mailhooks.emails.waitFor({
161
161
  - Efficiently tracks checked emails to avoid duplicates
162
162
  - Throws error on timeout or max retries exceeded
163
163
 
164
+ ## Push Notifications (SSE)
165
+
166
+ Get instant push notifications when emails arrive using Server-Sent Events. This is ideal for serverless environments, client-side apps, firewalled networks, or local development where webhooks aren't practical.
167
+
168
+ ### Basic Usage
169
+
170
+ ```typescript
171
+ import { Mailhooks } from '@mailhooks/sdk';
172
+
173
+ const mailhooks = new Mailhooks({ apiKey: 'mh_xxx' });
174
+
175
+ const subscription = mailhooks.realtime.subscribe({
176
+ onEmailReceived: (email) => {
177
+ console.log('New email:', email.subject);
178
+ console.log('From:', email.from);
179
+ },
180
+ onConnected: (payload) => {
181
+ console.log('Connected!', payload.connectionId);
182
+ },
183
+ onError: (error) => {
184
+ console.error('Error:', error);
185
+ },
186
+ });
187
+
188
+ // Later, disconnect when done
189
+ subscription.disconnect();
190
+ ```
191
+
192
+ ### Distributed Mode (Worker Load Balancing)
193
+
194
+ When running multiple workers, use distributed mode so only ONE worker receives each notification:
195
+
196
+ ```typescript
197
+ // Each worker connects with the same API key
198
+ // Only ONE worker receives each notification (random selection)
199
+ const subscription = mailhooks.realtime.subscribe({
200
+ mode: 'distributed',
201
+ onEmailReceived: async (email) => {
202
+ // Process email - only one worker will receive this
203
+ await processEmail(email.id);
204
+ },
205
+ });
206
+ ```
207
+
208
+ ### Full Event Handling
209
+
210
+ ```typescript
211
+ const subscription = mailhooks.realtime.subscribe({
212
+ mode: 'broadcast', // or 'distributed'
213
+ onConnected: (payload) => {
214
+ console.log(`Connected: ${payload.connectionId}`);
215
+ console.log(`Mode: ${payload.mode}`);
216
+ },
217
+ onEmailReceived: (email) => {
218
+ console.log(`From: ${email.from}`);
219
+ console.log(`Subject: ${email.subject}`);
220
+ console.log(`Has attachments: ${email.hasAttachments}`);
221
+ },
222
+ onEmailUpdated: (update) => {
223
+ console.log(`Email ${update.id} updated:`, update.changes);
224
+ },
225
+ onHeartbeat: () => {
226
+ // Sent every 30 seconds to keep connection alive
227
+ },
228
+ onError: (error) => {
229
+ console.error('Connection error:', error);
230
+ },
231
+ onDisconnect: () => {
232
+ console.log('Disconnected');
233
+ },
234
+ autoReconnect: true, // Automatically reconnect on disconnect (default: true)
235
+ reconnectDelay: 5000, // Delay between reconnect attempts in ms (default: 5000)
236
+ });
237
+ ```
238
+
239
+ ### Node.js Usage
240
+
241
+ In Node.js, you need to install the `eventsource` package:
242
+
243
+ ```bash
244
+ npm install eventsource
245
+ ```
246
+
247
+ Then make EventSource available globally before importing the SDK:
248
+
249
+ ```typescript
250
+ import EventSource from 'eventsource';
251
+ (global as any).EventSource = EventSource;
252
+
253
+ import { Mailhooks } from '@mailhooks/sdk';
254
+ // Use as normal
255
+ ```
256
+
257
+ ### Check Connection Limits
258
+
259
+ ```typescript
260
+ const access = await mailhooks.realtime.checkAccess();
261
+ console.log('Has access:', access.hasAccess);
262
+ console.log('Max connections:', access.maxConnections); // -1 = unlimited
263
+ console.log('Current connections:', access.currentConnections);
264
+ ```
265
+
266
+ ### Event Types
267
+
268
+ | Event | Payload | Description |
269
+ |-------|---------|-------------|
270
+ | `connected` | `{ tenantId, connectedAt, mode, connectionId }` | Connection established |
271
+ | `email.received` | `{ id, from, to, subject, hasAttachments, ... }` | New email arrived |
272
+ | `email.updated` | `{ id, changes: { read?: boolean } }` | Email was updated |
273
+ | `heartbeat` | `{ timestamp }` | Keep-alive ping (every 30s) |
274
+
275
+ ### Connection Modes
276
+
277
+ | Mode | Behavior | Use Case |
278
+ |------|----------|----------|
279
+ | `broadcast` | All connected clients receive every event | Dashboards, monitoring |
280
+ | `distributed` | One random client per API key receives each event | Worker pools, load balancing |
281
+
164
282
  ## Types
165
283
 
166
284
  The SDK includes comprehensive TypeScript types:
package/dist/index.d.ts CHANGED
@@ -152,8 +152,174 @@ declare class EmailsResource extends MailhooksClient {
152
152
  waitFor(options?: WaitForOptions): Promise<Email>;
153
153
  }
154
154
 
155
+ /**
156
+ * Connection mode for SSE subscriptions
157
+ * - broadcast: All connected clients receive every event (default)
158
+ * - distributed: Only ONE client per API key group receives each event (load balancing)
159
+ */
160
+ type ConnectionMode = 'broadcast' | 'distributed';
161
+ /**
162
+ * Event types for push notifications
163
+ */
164
+ declare enum RealtimeEventType {
165
+ EMAIL_RECEIVED = "email.received",
166
+ EMAIL_UPDATED = "email.updated",
167
+ HEARTBEAT = "heartbeat",
168
+ CONNECTED = "connected"
169
+ }
170
+ /**
171
+ * Email received event payload
172
+ */
173
+ interface EmailReceivedPayload {
174
+ id: string;
175
+ from: string;
176
+ to: string[];
177
+ subject: string;
178
+ domainId?: string;
179
+ domain?: string;
180
+ createdAt: string;
181
+ hasAttachments: boolean;
182
+ attachmentCount: number;
183
+ }
184
+ /**
185
+ * Email updated event payload
186
+ */
187
+ interface EmailUpdatedPayload {
188
+ id: string;
189
+ changes: {
190
+ read?: boolean;
191
+ };
192
+ }
193
+ /**
194
+ * Connected event payload
195
+ */
196
+ interface ConnectedPayload {
197
+ tenantId: string;
198
+ connectedAt: string;
199
+ mode?: ConnectionMode;
200
+ connectionId?: string;
201
+ }
202
+ /**
203
+ * Heartbeat event payload
204
+ */
205
+ interface HeartbeatPayload {
206
+ timestamp: string;
207
+ }
208
+ /**
209
+ * Base realtime event structure
210
+ */
211
+ interface RealtimeEvent<T = unknown> {
212
+ type: RealtimeEventType;
213
+ timestamp: string;
214
+ data: T;
215
+ }
216
+ /**
217
+ * Callback handlers for realtime events
218
+ */
219
+ interface RealtimeCallbacks {
220
+ onEmailReceived?: (payload: EmailReceivedPayload) => void;
221
+ onEmailUpdated?: (payload: EmailUpdatedPayload) => void;
222
+ onConnected?: (payload: ConnectedPayload) => void;
223
+ onHeartbeat?: (payload: HeartbeatPayload) => void;
224
+ onError?: (error: Error) => void;
225
+ onDisconnect?: () => void;
226
+ }
227
+ /**
228
+ * Subscription options
229
+ */
230
+ interface SubscribeOptions extends RealtimeCallbacks {
231
+ /**
232
+ * Connection mode (default: 'broadcast')
233
+ * - broadcast: All connected clients receive every event
234
+ * - distributed: Only ONE client per API key group receives each event (load balancing for workers)
235
+ */
236
+ mode?: ConnectionMode;
237
+ /** Auto-reconnect on disconnect (default: true) */
238
+ autoReconnect?: boolean;
239
+ /** Reconnect delay in milliseconds (default: 5000) */
240
+ reconnectDelay?: number;
241
+ }
242
+ /**
243
+ * Subscription handle returned from subscribe()
244
+ */
245
+ interface RealtimeSubscription {
246
+ /** Disconnect from the SSE stream */
247
+ disconnect: () => void;
248
+ /** Whether currently connected */
249
+ isConnected: () => boolean;
250
+ }
251
+ /**
252
+ * Realtime resource for subscribing to email notifications via SSE
253
+ *
254
+ * @example
255
+ * ```typescript
256
+ * const mailhooks = new Mailhooks({ apiKey: 'your-api-key' });
257
+ *
258
+ * // Subscribe to real-time notifications
259
+ * const subscription = mailhooks.realtime.subscribe({
260
+ * onEmailReceived: (email) => {
261
+ * console.log('New email:', email.subject);
262
+ * },
263
+ * onError: (error) => {
264
+ * console.error('Connection error:', error);
265
+ * },
266
+ * });
267
+ *
268
+ * // Later, disconnect
269
+ * subscription.disconnect();
270
+ * ```
271
+ */
272
+ declare class RealtimeResource {
273
+ private config;
274
+ private eventSource;
275
+ private reconnectTimeout;
276
+ constructor(config: MailhooksConfig);
277
+ /**
278
+ * Check if the plan allows real-time notifications and get connection quota
279
+ *
280
+ * @returns Promise resolving to access status and connection limits
281
+ */
282
+ checkAccess(): Promise<{
283
+ hasAccess: boolean;
284
+ maxConnections: number;
285
+ currentConnections: number;
286
+ }>;
287
+ /**
288
+ * Subscribe to real-time email notifications via Server-Sent Events (SSE)
289
+ *
290
+ * Note: This method requires the EventSource API, which is available in browsers
291
+ * and can be polyfilled in Node.js using packages like 'eventsource'.
292
+ *
293
+ * @param options Subscription options and callbacks
294
+ * @returns Subscription handle with disconnect method
295
+ *
296
+ * @example
297
+ * ```typescript
298
+ * const subscription = mailhooks.realtime.subscribe({
299
+ * onEmailReceived: (email) => {
300
+ * console.log('New email from:', email.from);
301
+ * console.log('Subject:', email.subject);
302
+ * },
303
+ * onConnected: () => {
304
+ * console.log('Connected to real-time notifications');
305
+ * },
306
+ * onError: (error) => {
307
+ * console.error('Error:', error);
308
+ * },
309
+ * autoReconnect: true,
310
+ * reconnectDelay: 5000,
311
+ * });
312
+ *
313
+ * // Disconnect when done
314
+ * subscription.disconnect();
315
+ * ```
316
+ */
317
+ subscribe(options?: SubscribeOptions): RealtimeSubscription;
318
+ }
319
+
155
320
  declare class Mailhooks {
156
321
  emails: EmailsResource;
322
+ realtime: RealtimeResource;
157
323
  constructor(config: MailhooksConfig);
158
324
  /**
159
325
  * Create a new Mailhooks SDK instance
@@ -354,4 +520,4 @@ interface ParsedEmail {
354
520
  */
355
521
  declare function parseEml(eml: Buffer | string): Promise<ParsedEmail>;
356
522
 
357
- export { type Attachment, type DownloadResponse, type Email, type EmailContent, type EmailFilter, type EmailListParams, type EmailSort, EmailsResource, type EmailsResponse, Mailhooks, type MailhooksConfig, type PaginationResponse, type ParsedEmail, type StorageConfigSummary, type WaitForOptions, type WebhookPayload, constructSignature, Mailhooks as default, parseEml, parseWebhookPayload, verifyWebhookSignature };
523
+ export { type Attachment, type ConnectedPayload, type DownloadResponse, type Email, type EmailContent, type EmailFilter, type EmailListParams, type EmailReceivedPayload, type EmailSort, type EmailUpdatedPayload, EmailsResource, type EmailsResponse, type HeartbeatPayload, Mailhooks, type MailhooksConfig, type PaginationResponse, type ParsedEmail, type RealtimeCallbacks, type RealtimeEvent, RealtimeEventType, RealtimeResource, type RealtimeSubscription, type StorageConfigSummary, type SubscribeOptions, type WaitForOptions, type WebhookPayload, constructSignature, Mailhooks as default, parseEml, parseWebhookPayload, verifyWebhookSignature };
package/dist/index.js CHANGED
@@ -242,10 +242,158 @@ var EmailsResource = class extends MailhooksClient {
242
242
  }
243
243
  };
244
244
 
245
+ // src/realtime.ts
246
+ var RealtimeEventType = /* @__PURE__ */ ((RealtimeEventType2) => {
247
+ RealtimeEventType2["EMAIL_RECEIVED"] = "email.received";
248
+ RealtimeEventType2["EMAIL_UPDATED"] = "email.updated";
249
+ RealtimeEventType2["HEARTBEAT"] = "heartbeat";
250
+ RealtimeEventType2["CONNECTED"] = "connected";
251
+ return RealtimeEventType2;
252
+ })(RealtimeEventType || {});
253
+ var RealtimeResource = class {
254
+ constructor(config) {
255
+ this.eventSource = null;
256
+ this.reconnectTimeout = null;
257
+ this.config = config;
258
+ }
259
+ /**
260
+ * Check if the plan allows real-time notifications and get connection quota
261
+ *
262
+ * @returns Promise resolving to access status and connection limits
263
+ */
264
+ async checkAccess() {
265
+ const baseUrl = this.config.baseUrl ?? "https://mailhooks.dev/api";
266
+ const response = await fetch(`${baseUrl}/v1/realtime/plan-access`, {
267
+ headers: {
268
+ "x-api-key": this.config.apiKey
269
+ }
270
+ });
271
+ if (!response.ok) {
272
+ throw new Error(`Failed to check plan access: ${response.statusText}`);
273
+ }
274
+ return response.json();
275
+ }
276
+ /**
277
+ * Subscribe to real-time email notifications via Server-Sent Events (SSE)
278
+ *
279
+ * Note: This method requires the EventSource API, which is available in browsers
280
+ * and can be polyfilled in Node.js using packages like 'eventsource'.
281
+ *
282
+ * @param options Subscription options and callbacks
283
+ * @returns Subscription handle with disconnect method
284
+ *
285
+ * @example
286
+ * ```typescript
287
+ * const subscription = mailhooks.realtime.subscribe({
288
+ * onEmailReceived: (email) => {
289
+ * console.log('New email from:', email.from);
290
+ * console.log('Subject:', email.subject);
291
+ * },
292
+ * onConnected: () => {
293
+ * console.log('Connected to real-time notifications');
294
+ * },
295
+ * onError: (error) => {
296
+ * console.error('Error:', error);
297
+ * },
298
+ * autoReconnect: true,
299
+ * reconnectDelay: 5000,
300
+ * });
301
+ *
302
+ * // Disconnect when done
303
+ * subscription.disconnect();
304
+ * ```
305
+ */
306
+ subscribe(options = {}) {
307
+ const {
308
+ mode = "broadcast",
309
+ onEmailReceived,
310
+ onEmailUpdated,
311
+ onConnected,
312
+ onHeartbeat,
313
+ onError,
314
+ onDisconnect,
315
+ autoReconnect = true,
316
+ reconnectDelay = 5e3
317
+ } = options;
318
+ if (this.reconnectTimeout) {
319
+ clearTimeout(this.reconnectTimeout);
320
+ this.reconnectTimeout = null;
321
+ }
322
+ if (this.eventSource) {
323
+ this.eventSource.close();
324
+ this.eventSource = null;
325
+ }
326
+ if (typeof EventSource === "undefined") {
327
+ throw new Error(
328
+ 'EventSource is not available. In Node.js, install and import the "eventsource" package.'
329
+ );
330
+ }
331
+ const baseUrl = this.config.baseUrl ?? "https://mailhooks.dev/api";
332
+ const url = `${baseUrl}/v1/realtime/events?token=${encodeURIComponent(this.config.apiKey)}&mode=${mode}`;
333
+ const connect = () => {
334
+ this.eventSource = new EventSource(url);
335
+ this.eventSource.onmessage = (event) => {
336
+ try {
337
+ const data = JSON.parse(event.data);
338
+ switch (data.type) {
339
+ case "connected" /* CONNECTED */:
340
+ onConnected?.(data.data);
341
+ break;
342
+ case "email.received" /* EMAIL_RECEIVED */:
343
+ onEmailReceived?.(data.data);
344
+ break;
345
+ case "email.updated" /* EMAIL_UPDATED */:
346
+ onEmailUpdated?.(data.data);
347
+ break;
348
+ case "heartbeat" /* HEARTBEAT */:
349
+ onHeartbeat?.(data.data);
350
+ break;
351
+ }
352
+ } catch (error) {
353
+ const message = error instanceof Error ? error.message : String(error);
354
+ onError?.(new Error(`Failed to parse event: ${message}`));
355
+ }
356
+ };
357
+ this.eventSource.onerror = (event) => {
358
+ onError?.(new Error("SSE connection error"));
359
+ this.eventSource?.close();
360
+ this.eventSource = null;
361
+ onDisconnect?.();
362
+ if (autoReconnect) {
363
+ if (this.reconnectTimeout) {
364
+ clearTimeout(this.reconnectTimeout);
365
+ }
366
+ this.reconnectTimeout = setTimeout(() => {
367
+ connect();
368
+ }, reconnectDelay);
369
+ }
370
+ };
371
+ };
372
+ connect();
373
+ return {
374
+ disconnect: () => {
375
+ if (this.reconnectTimeout) {
376
+ clearTimeout(this.reconnectTimeout);
377
+ this.reconnectTimeout = null;
378
+ }
379
+ if (this.eventSource) {
380
+ this.eventSource.close();
381
+ this.eventSource = null;
382
+ onDisconnect?.();
383
+ }
384
+ },
385
+ isConnected: () => {
386
+ return this.eventSource?.readyState === EventSource.OPEN;
387
+ }
388
+ };
389
+ }
390
+ };
391
+
245
392
  // src/mailhooks.ts
246
393
  var Mailhooks = class _Mailhooks {
247
394
  constructor(config) {
248
395
  this.emails = new EmailsResource(config);
396
+ this.realtime = new RealtimeResource(config);
249
397
  }
250
398
  /**
251
399
  * Create a new Mailhooks SDK instance
@@ -312,4 +460,4 @@ async function parseEml(eml) {
312
460
  // src/index.ts
313
461
  var index_default = Mailhooks;
314
462
 
315
- export { EmailsResource, Mailhooks, constructSignature, index_default as default, parseEml, parseWebhookPayload, verifyWebhookSignature };
463
+ export { EmailsResource, Mailhooks, RealtimeEventType, RealtimeResource, constructSignature, index_default as default, parseEml, parseWebhookPayload, verifyWebhookSignature };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mailhooks/sdk",
3
- "version": "2.3.0",
3
+ "version": "2.5.0",
4
4
  "description": "TypeScript SDK for Mailhooks API",
5
5
  "publishConfig": {
6
6
  "access": "public"