notif-agent 1.0.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.
@@ -0,0 +1,298 @@
1
+ /**
2
+ * Connection states matching the Pusher-like lifecycle.
3
+ */
4
+ type ConnectionState = 'initialized' | 'connecting' | 'connected' | 'unavailable' | 'failed' | 'disconnected';
5
+ interface StateChangePayload {
6
+ previous: ConnectionState;
7
+ current: ConnectionState;
8
+ }
9
+ interface EventMetadata {
10
+ channel?: string;
11
+ event: string;
12
+ id?: string;
13
+ timestamp?: number;
14
+ }
15
+ type EventCallback<T = any> = (data: T, metadata?: EventMetadata) => void;
16
+ type GlobalEventCallback = (eventName: string, data: any, metadata?: EventMetadata) => void;
17
+ type TransportType = 'auto' | 'eventsource' | 'fetch';
18
+ interface NotifAgentOptions {
19
+ /**
20
+ * The SSE endpoint URL.
21
+ */
22
+ url?: string;
23
+ /**
24
+ * Custom HTTP headers (forces `fetch` transport if specified in browser).
25
+ * Can be an object or a sync/async function returning an object.
26
+ */
27
+ headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
28
+ /**
29
+ * Query parameters to append to the SSE URL.
30
+ */
31
+ queryParams?: Record<string, string | number | boolean>;
32
+ /**
33
+ * Whether to send cookies with cross-origin requests.
34
+ * Defaults to false.
35
+ */
36
+ withCredentials?: boolean;
37
+ /**
38
+ * SSE Transport mechanism.
39
+ * - 'auto': uses Fetch stream if custom headers or non-browser, otherwise EventSource if available.
40
+ * - 'eventsource': uses standard EventSource.
41
+ * - 'fetch': uses fetch API with ReadableStream.
42
+ * Defaults to 'auto'.
43
+ */
44
+ transport?: TransportType;
45
+ /**
46
+ * Initial delay in ms before reconnection attempts.
47
+ * Defaults to 1000ms.
48
+ */
49
+ reconnectBaseDelay?: number;
50
+ /**
51
+ * Maximum reconnect delay in ms.
52
+ * Defaults to 30000ms.
53
+ */
54
+ reconnectMaxDelay?: number;
55
+ /**
56
+ * Maximum number of reconnect attempts before transitioning to 'failed'.
57
+ * Defaults to Infinity.
58
+ */
59
+ maxReconnectAttempts?: number;
60
+ /**
61
+ * Heartbeat timeout in ms. If no data/ping is received within this period,
62
+ * the connection is presumed dead and reconnected.
63
+ * Defaults to 45000ms (45s).
64
+ */
65
+ heartbeatTimeout?: number;
66
+ /**
67
+ * Whether to automatically connect upon instantiation.
68
+ * Defaults to true.
69
+ */
70
+ autoConnect?: boolean;
71
+ /**
72
+ * Enable verbose console logging for debugging.
73
+ * Defaults to false.
74
+ */
75
+ debug?: boolean;
76
+ /**
77
+ * Endpoint URL for channel authorization (Pusher-compatible authEndpoint).
78
+ * Automatically invoked when subscribing to private or presence channels (e.g. `private-*`).
79
+ */
80
+ authEndpoint?: string;
81
+ /**
82
+ * Custom authentication headers and parameters sent to `authEndpoint`.
83
+ */
84
+ auth?: {
85
+ headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
86
+ params?: Record<string, any>;
87
+ };
88
+ }
89
+ type ChannelSubscriptionState = 'unsubscribed' | 'subscribing' | 'subscribed' | 'error';
90
+ interface SSEMessagePayload<T = any> {
91
+ channel?: string;
92
+ event: string;
93
+ data: T;
94
+ id?: string;
95
+ timestamp?: number;
96
+ }
97
+
98
+ declare class Channel {
99
+ readonly name: string;
100
+ state: ChannelSubscriptionState;
101
+ private emitter;
102
+ constructor(name: string);
103
+ /**
104
+ * Whether the channel is currently successfully subscribed.
105
+ */
106
+ get subscribed(): boolean;
107
+ /**
108
+ * Bind an event listener to this channel.
109
+ *
110
+ * Example:
111
+ * ```ts
112
+ * channel.bind('new-comment', (data) => {
113
+ * console.log(data);
114
+ * });
115
+ * ```
116
+ */
117
+ bind<T = any>(event: string, callback: EventCallback<T>): this;
118
+ /**
119
+ * Unbind an event listener from this channel.
120
+ */
121
+ unbind<T = any>(event?: string, callback?: EventCallback<T>): this;
122
+ /**
123
+ * Bind a global listener to all events received on this channel.
124
+ *
125
+ * Example:
126
+ * ```ts
127
+ * channel.bind_global((eventName, data) => {
128
+ * console.log(`Event ${eventName}:`, data);
129
+ * });
130
+ * ```
131
+ */
132
+ bind_global(callback: GlobalEventCallback): this;
133
+ /**
134
+ * Unbind a global listener from this channel.
135
+ */
136
+ unbind_global(callback?: GlobalEventCallback): this;
137
+ /**
138
+ * Internal method to dispatch an event onto this channel.
139
+ */
140
+ handleEvent<T = any>(event: string, data: T, metadata?: EventMetadata): void;
141
+ /**
142
+ * Internal method to update subscription status and fire Pusher-compatible subscription events.
143
+ */
144
+ setSubscribed(data?: any): void;
145
+ /**
146
+ * Internal method to set subscription error.
147
+ */
148
+ setSubscriptionError(error: any): void;
149
+ /**
150
+ * Internal method called when channel is unsubscribed.
151
+ */
152
+ setUnsubscribed(): void;
153
+ }
154
+
155
+ declare class ConnectionManager {
156
+ state: ConnectionState;
157
+ clientId: string | null;
158
+ /**
159
+ * Pusher-compatible alias for clientId.
160
+ */
161
+ get socket_id(): string | null;
162
+ private emitter;
163
+ private options;
164
+ private eventSource;
165
+ private abortController;
166
+ private reconnectAttempts;
167
+ private reconnectTimer;
168
+ private heartbeatTimer;
169
+ private isManuallyClosed;
170
+ constructor(url: string, options?: NotifAgentOptions);
171
+ bind<T = any>(event: string, callback: (data: T) => void): this;
172
+ unbind<T = any>(event?: string, callback?: (data: T) => void): this;
173
+ connect(): void;
174
+ disconnect(): void;
175
+ private transition;
176
+ private establishConnection;
177
+ private connectViaEventSource;
178
+ private connectViaFetch;
179
+ private processSSEFrame;
180
+ private parseAndDispatchMessage;
181
+ private handleConnectionSuccess;
182
+ private handleConnectionFailure;
183
+ private scheduleReconnect;
184
+ private resetHeartbeat;
185
+ private clearHeartbeat;
186
+ private clearTimers;
187
+ private closeActiveTransport;
188
+ private buildUrl;
189
+ private resolveHeaders;
190
+ private log;
191
+ }
192
+
193
+ declare class NotifAgent {
194
+ readonly connection: ConnectionManager;
195
+ private options;
196
+ private channels;
197
+ private globalEmitter;
198
+ /**
199
+ * Unique client connection ID provided by NotifServer handshake.
200
+ */
201
+ get clientId(): string | null;
202
+ /**
203
+ * Pusher-compatible alias for clientId.
204
+ */
205
+ get socket_id(): string | null;
206
+ constructor(urlOrOptions: string | NotifAgentOptions, maybeOptions?: NotifAgentOptions);
207
+ /**
208
+ * Subscribe to a channel.
209
+ *
210
+ * Example:
211
+ * ```ts
212
+ * const channel = agent.subscribe('orders');
213
+ * channel.bind('created', (order) => { ... });
214
+ * ```
215
+ */
216
+ subscribe(channelName: string): Channel;
217
+ /**
218
+ * Internal authorization helper for private/presence channels.
219
+ */
220
+ private authorizeChannel;
221
+ /**
222
+ * Unsubscribe from a channel.
223
+ */
224
+ unsubscribe(channelName: string): void;
225
+ /**
226
+ * Get an existing subscribed channel by name, if any.
227
+ */
228
+ channel(channelName: string): Channel | undefined;
229
+ /**
230
+ * Return all currently subscribed channels.
231
+ */
232
+ allChannels(): Channel[];
233
+ /**
234
+ * Bind to an event across all channels or global events.
235
+ *
236
+ * Example:
237
+ * ```ts
238
+ * agent.bind('system-alert', (data) => console.log(data));
239
+ * ```
240
+ */
241
+ bind<T = any>(event: string, callback: EventCallback<T>): this;
242
+ /**
243
+ * Unbind an event listener.
244
+ */
245
+ unbind<T = any>(event?: string, callback?: EventCallback<T>): this;
246
+ /**
247
+ * Bind to all events regardless of name.
248
+ */
249
+ bind_global(callback: GlobalEventCallback): this;
250
+ /**
251
+ * Unbind a global event listener.
252
+ */
253
+ unbind_global(callback?: GlobalEventCallback): this;
254
+ /**
255
+ * Connect to the SSE endpoint.
256
+ */
257
+ connect(): void;
258
+ /**
259
+ * Disconnect from the SSE endpoint.
260
+ */
261
+ disconnect(): void;
262
+ /**
263
+ * Route incoming SSE message to global emitters and specific channels.
264
+ */
265
+ private routeMessage;
266
+ }
267
+
268
+ declare class EventEmitter {
269
+ private listeners;
270
+ private globalListeners;
271
+ /**
272
+ * Bind a callback to a specific event name.
273
+ */
274
+ bind<T = any>(event: string, callback: EventCallback<T>): this;
275
+ /**
276
+ * Unbind a callback from a specific event name, or all callbacks if callback is omitted.
277
+ * If both event and callback are omitted, all listeners are removed.
278
+ */
279
+ unbind<T = any>(event?: string, callback?: EventCallback<T>): this;
280
+ /**
281
+ * Bind a callback to ALL incoming events on this emitter.
282
+ */
283
+ bind_global(callback: GlobalEventCallback): this;
284
+ /**
285
+ * Unbind a global callback, or all global callbacks if callback is omitted.
286
+ */
287
+ unbind_global(callback?: GlobalEventCallback): this;
288
+ /**
289
+ * Emit an event to registered listeners and global listeners.
290
+ */
291
+ emit<T = any>(event: string, data: T, metadata?: EventMetadata): void;
292
+ /**
293
+ * Clear all listeners.
294
+ */
295
+ clear(): void;
296
+ }
297
+
298
+ export { Channel, type ChannelSubscriptionState, ConnectionManager, type ConnectionState, type EventCallback, EventEmitter, type EventMetadata, type GlobalEventCallback, NotifAgent, type NotifAgentOptions, type SSEMessagePayload, type StateChangePayload, type TransportType, NotifAgent as default };