honeydrop 1.0.0 → 1.0.2

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.
Files changed (2) hide show
  1. package/README.md +121 -247
  2. package/package.json +5 -5
package/README.md CHANGED
@@ -1,298 +1,192 @@
1
+ <div align="center">
2
+
1
3
  # Honeydrop 🍯
2
4
 
3
- [![npm version](https://img.shields.io/npm/v/honeydrop.svg)](https://www.npmjs.com/package/honeydrop)
4
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
- [![Node.js](https://img.shields.io/badge/node-%3E%3D18-brightgreen.svg)](https://nodejs.org)
5
+ ### The Developer-Friendly Socket.IO Helper
6
+
7
+ [![npm version](https://img.shields.io/npm/v/honeydrop.svg?style=flat-square)](https://www.npmjs.com/package/honeydrop)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](https://opensource.org/licenses/MIT)
9
+ [![Node.js](https://img.shields.io/badge/node-%3E%3D18-brightgreen.svg?style=flat-square)](https://nodejs.org)
10
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg?style=flat-square)](https://www.typescriptlang.org/)
11
+
12
+ **Simplify your real-time applications.**<br>
13
+ Effortless connection management, automatic reconnection, and powerful utilities for Socket.IO.
14
+
15
+ [Installation](#-installation) • [Quick Start](#-quick-start) • [Features](#-features) • [API Reference](#-api-reference) • [Contributing](#-contributing)
16
+
17
+ </div>
18
+
19
+ ---
6
20
 
7
- A lightweight, developer-friendly helper library for Socket.IO applications. Simplifies real-time communication in web apps with easy connection management, automatic reconnection, and powerful utilities.
21
+ ## 💡 Motivation
8
22
 
9
- ## 💡 Why Honeydrop?
23
+ Building robust Socket.IO applications often involves repetitive boilerplate: managing room joins, handling reconnections gracefully, queuing events when the network drops, and implementing retry logic.
10
24
 
11
- I was working on a real-time project using Socket.IO myself and realized how much repetitive work was involved — managing rooms, handling reconnections, queuing events while offline, and retrying failed emits. That's why I decided to create **Honeydrop.js**, a lightweight, developer-friendly library that simplifies real-time communication and makes building robust Socket.IO apps faster and easier.
25
+ **Honeydrop** handles this complexity for you. It wraps the standard `socket.io-client` with a powerful, developer-friendly API that makes your real-time code cleaner, more reliable, and easier to maintain.
12
26
 
13
27
  ## ✨ Features
14
28
 
15
- - 🔌 **Easy Connection Management** - Simple API to connect, disconnect, and manage Socket.IO connections
16
- - 🎯 **Event Handling with Auto-Cleanup** - Register events that are automatically cleaned up on disconnect
17
- - 🔄 **Automatic Reconnection** - Configurable retry strategies (linear/exponential backoff)
18
- - 📛 **Namespaced Events** - Organize events into logical channels
19
- - **Utility Functions** - Multi-emit, multi-listen, throttle, debounce, and more
20
- - 🐛 **Debug Logging** - Pretty-printed development logs
21
- - 📦 **Lightweight** - No bundled dependencies, Socket.IO as peer dependency
22
- - 🎨 **TypeScript Support** - Full type definitions included
29
+ - **🔌 effortless Connection Management**: Simple API to connect, disconnect, and monitor health.
30
+ - **🎯 Smart Event Handling**: Auto-cleanup of listeners on disconnect.
31
+ - **🔄 Robust Reconnection**: Configurable strategies (linear/exponential backoff) with hooks.
32
+ - **📛 Namespacing Made Easy**: Organize your events into logical channels (`chat:message`, `game:score`).
33
+ - **⚡ Powerful Utilities**: Multi-emit, multi-listen, throttle, debounce, and specific event waiting.
34
+ - **📦 Offline Queue**: Automatically queue events when disconnected and flush them on reconnect.
35
+ - **🐛 Dev-Friendly**: Built-in debug logging and full TypeScript support.
23
36
 
24
37
  ## 📦 Installation
25
38
 
26
- ```bash
27
- npm install honeydrop socket.io-client
28
- ```
39
+ > [!IMPORTANT]
40
+ > Run the following command to install the package:
41
+ > ```bash
42
+ > npm install honeydrop
43
+ > ```
44
+ > *Note: `socket.io-client` is a peer dependency and will be installed if not present.*
29
45
 
30
46
  ## 🚀 Quick Start
31
47
 
32
- ```javascript
48
+ Here's how easy it is to get started:
49
+
50
+ ```typescript
33
51
  import Honeydrop from 'honeydrop';
34
52
 
35
- // Create a client with auto-connect
53
+ // 1. Initialize the client
36
54
  const client = new Honeydrop('http://localhost:3000', {
37
- debug: true,
38
- reconnection: {
39
- enabled: true,
40
- maxAttempts: 5,
41
- strategy: 'exponential'
42
- }
55
+ autoConnect: true,
56
+ debug: true
43
57
  });
44
58
 
45
- // Listen for events
59
+ // 2. Listen for events
46
60
  client.on('message', (data) => {
47
61
  console.log('Received:', data);
48
62
  });
49
63
 
50
- // Emit events
64
+ // 3. Emit events (even if currently disconnected!)
51
65
  client.emit('chat:message', { text: 'Hello, World!' });
52
66
 
53
- // Disconnect (all listeners automatically cleaned up)
54
- client.disconnect();
67
+ // 4. Cleanup when done
68
+ // client.disconnect();
55
69
  ```
56
70
 
57
71
  ## 📖 API Reference
58
72
 
59
- ### Constructor
73
+ ### Client Configuration
60
74
 
61
75
  ```javascript
62
- new Honeydrop(url, options?)
63
- ```
64
-
65
- | Option | Type | Default | Description |
66
- |--------|------|---------|-------------|
67
- | `debug` | `boolean` | `false` | Enable debug logging |
68
- | `logLevel` | `'debug' \| 'info' \| 'warn' \| 'error'` | `'info'` | Minimum log level |
69
- | `autoConnect` | `boolean` | `true` | Auto-connect on instantiation |
70
- | `namespaceDelimiter` | `':' \| '/' \| '.' \| '_'` | `':'` | Delimiter for namespaced events |
71
- | `reconnection` | `ReconnectionOptions` | — | Reconnection configuration |
72
- | `offlineQueue` | `OfflineQueueOptions` | `{ enabled: true }` | Offline message queue configuration |
73
- | `connectionMonitor` | `ConnectionMonitorOptions` | `{ enabled: true }` | Connection health monitoring |
74
- | `roomManager` | `RoomManagerOptions` | — | Room join/leave event names |
75
- | `socketOptions` | `object` | — | Socket.IO client options |
76
-
77
- #### Reconnection Options
78
-
79
- ```javascript
80
- {
81
- enabled: true, // Enable auto-reconnection
82
- maxAttempts: 10, // Maximum retry attempts
83
- delay: 1000, // Initial delay (ms)
84
- maxDelay: 30000, // Maximum delay (ms)
85
- strategy: 'exponential', // 'linear' or 'exponential'
86
- onReconnecting: (attempt) => {}, // Called on each attempt
87
- onReconnected: () => {}, // Called on success
88
- onFailed: () => {} // Called when max attempts reached
89
- }
90
- ```
91
-
92
- #### Offline Queue Options
93
-
94
- ```javascript
95
- {
96
- enabled: true, // Enable offline queueing (default: true)
97
- maxSize: 100, // Maximum events to queue (0 = unlimited)
98
- maxAge: 0, // Max age in ms before discard (0 = no expiry)
99
- onQueued: (event) => {}, // Called when event is queued
100
- onFlushed: (count) => {}, // Called when queue is flushed on reconnect
101
- onDropped: (event) => {} // Called when event is dropped (queue full)
102
- }
76
+ new Honeydrop(url, {
77
+ debug: false, // Enable debug logs
78
+ autoConnect: true, // Connect immediately
79
+ reconnection: { // Reconnection strategy
80
+ enabled: true,
81
+ maxAttempts: 10,
82
+ strategy: 'exponential' // 'linear' | 'exponential'
83
+ },
84
+ offlineQueue: { // Offline behavior
85
+ enabled: true,
86
+ maxSize: 100
87
+ }
88
+ })
103
89
  ```
104
90
 
91
+ ### Core Methods
105
92
 
106
- ### Connection Methods
107
-
108
- ```javascript
109
- // Connect to server
110
- client.connect();
111
-
112
- // Disconnect and cleanup
113
- client.disconnect();
114
-
115
- // Check connection status
116
- client.connected; // boolean
117
- client.id; // socket ID
118
-
119
- // Get detailed connection info
120
- client.getConnectionInfo();
121
- // { connected: boolean, id: string | null, transport: string | null }
122
-
123
- // Manual reconnection
124
- client.reconnect();
125
- ```
93
+ | Method | Description |
94
+ |--------|-------------|
95
+ | `connect()` | Manually connect to the server. |
96
+ | `disconnect()` | Disconnect and clean up all listeners. |
97
+ | `reconnect()` | Force a manual reconnection attempt. |
98
+ | `setDebug(bool)` | Toggle debug logging at runtime. |
126
99
 
127
100
  ### Event Handling
128
101
 
129
- ```javascript
130
- // Register event listener
131
- client.on('event', (data) => { /* ... */ });
102
+ Honeydrop provides a rich API for event management:
103
+
104
+ ```typescript
105
+ // Standard listener
106
+ client.on('user:login', (user) => console.log(user));
132
107
 
133
108
  // One-time listener
134
- client.once('event', (data) => { /* ... */ });
109
+ client.once('init', () => console.log('Initialized'));
135
110
 
136
- // Remove listener
137
- client.off('event', handler);
138
- client.off('event'); // Remove all listeners for event
111
+ // Remove listeners
112
+ client.off('user:login');
139
113
 
140
- // Listen to multiple events
141
- client.onMultiple(['user:join', 'user:leave'], (event, data) => {
142
- console.log(`${event}:`, data);
143
- });
114
+ // Listen to MULTIPLE events with one handler
115
+ client.onMultiple(['connect', 'reconnect'], () => updateStatus('online'));
144
116
 
145
- // Fire once on any of the events
146
- client.onceAny(['success', 'error'], (event, data) => {
147
- console.log(`Got ${event}:`, data);
148
- });
117
+ // Wait for a specific event (Promise-based)
118
+ const data = await client.waitFor('ready', 5000);
149
119
  ```
150
120
 
151
121
  ### Emitting Events
152
122
 
153
- ```javascript
154
- // Basic emit
155
- client.emit('event', data);
156
-
157
- // Emit multiple events
158
- client.emitMultiple([
159
- { event: 'init', data: { userId: 1 } },
160
- { event: 'status', data: { online: true } }
161
- ]);
162
-
163
- // Emit with acknowledgment
164
- const response = await client.emitWithAck('request', data, 5000);
165
-
166
- // Emit multiple with acknowledgment
167
- const responses = await client.emitMultipleWithAck([
168
- { event: 'validate', data: input1 },
169
- { event: 'validate', data: input2, timeout: 3000 }
170
- ]);
171
-
172
- // Request/Response (RPC pattern)
173
- const user = await client.request('getUser', { id: 123 });
174
- // Server should emit 'getUser:response' with the result
175
-
176
- // Emit with automatic retry
177
- const result = await client.emitWithRetry('criticalAction', data, {
178
- maxRetries: 3,
179
- retryDelay: 1000,
180
- onRetry: (attempt, error) => console.log(`Retry ${attempt}`)
181
- });
182
- ```
183
-
184
- ### Room Management
185
-
186
- ```javascript
187
- // Join a room
188
- client.join('room-1');
189
-
190
- // Leave a room
191
- client.leave('room-1');
123
+ Send data with confidence using advanced emit patterns:
192
124
 
193
- // Emit to a specific room
194
- client.toRoom('room-1').emit('message', { text: 'Hello room!' });
125
+ ```typescript
126
+ // Standard emit
127
+ client.emit('update', data);
195
128
 
196
- // Get joined rooms
197
- console.log(client.getRooms()); // ['room-1']
198
-
199
- // Check if in a room
200
- console.log(client.isInRoom('room-1')); // true
201
- ```
202
-
203
- ### Waiting for Events
129
+ // Emit with Acknowledgment (Async/Await)
130
+ try {
131
+ const response = await client.emitWithAck('createUser', userData, 5000);
132
+ } catch (err) {
133
+ console.error('Server did not acknowledge in time');
134
+ }
204
135
 
205
- ```javascript
206
- // Wait for a specific event
207
- const data = await client.waitFor('ready', 5000);
136
+ // Emit with Automatic Retry
137
+ // Great for critical actions that must reach the server
138
+ await client.emitWithRetry('saveData', payload, {
139
+ maxRetries: 3,
140
+ retryDelay: 1000
141
+ });
208
142
 
209
- // Wait for any of the events
210
- const { event, data } = await client.waitForAny(['success', 'error']);
143
+ // Throttled Emit (e.g., for mouse movement or window resize)
144
+ const updatePosition = client.throttle('cursor:move', 100);
145
+ updatePosition({ x: 10, y: 20 });
211
146
  ```
212
147
 
213
- ### Namespaced Events
214
-
215
- ```javascript
216
- // Create a namespace
217
- const chat = client.namespace('chat');
148
+ ### Namespaces
218
149
 
219
- // All events are prefixed with 'chat:'
220
- chat.on('message', handler); // Listens to 'chat:message'
221
- chat.emit('message', data); // Emits 'chat:message'
150
+ Organize your events into logical groups without creating multiple socket connections.
222
151
 
223
- // Create sub-namespaces
224
- const room = chat.sub('room1');
225
- room.emit('join'); // Emits 'chat:room1:join'
152
+ ```typescript
153
+ const chat = client.namespace('chat'); // prefixes events with 'chat:'
226
154
 
227
- // Custom delimiter
228
- const api = client.namespace('api', { delimiter: '/' });
229
- api.emit('users', query); // Emits 'api/users'
155
+ chat.emit('msg', 'hello'); // Emits 'chat:msg'
156
+ chat.on('typing', showTyping); // Listens for 'chat:typing'
230
157
  ```
231
158
 
232
- ### Throttle & Debounce
233
-
234
- ```javascript
235
- // Throttled emit (max once per interval)
236
- const throttledUpdate = client.throttle('position', 100);
237
- // Call as often as you want, emits max 10 times/sec
238
- throttledUpdate({ x: 100, y: 200 });
239
-
240
- // Debounced emit (waits for pause in calls)
241
- const debouncedSearch = client.debounce('search', 300);
242
- // Only emits after 300ms of no calls
243
- debouncedSearch({ query: 'hello' });
244
- ```
245
-
246
- ### Offline Queue
247
-
248
- Events are automatically queued when disconnected and sent when reconnected:
249
-
250
- ```javascript
251
- // Events emitted while offline are queued automatically
252
- client.emit('message', { text: 'Hello' }); // Queued if offline
253
-
254
- // Check queue status
255
- console.log(client.getQueueLength()); // Number of queued events
256
- console.log(client.getQueuedEvents()); // Array of queued events
159
+ ### Room Management
257
160
 
258
- // Clear the queue
259
- client.clearQueue();
161
+ Helper methods for room-based logic (requires server-side support for room events).
260
162
 
261
- // Disable/enable offline queueing
262
- client.setOfflineQueue(false);
163
+ ```typescript
164
+ client.join('room-123');
165
+ client.toRoom('room-123').emit('announcement', 'Welcome!');
166
+ const inRoom = client.isInRoom('room-123'); // true
263
167
  ```
264
168
 
265
- ### Connection Health
169
+ ## 🌐 Browser Support
266
170
 
267
- Monitor connection latency and quality:
171
+ Honeydrop works seamlessly in both Node.js and the Browser.
268
172
 
173
+ ### Using with Bundlers (Vite, Webpack, etc.)
269
174
  ```javascript
270
- // Perform a ping and get latency
271
- const latency = await client.ping(); // Returns latency in ms
272
-
273
- // Get average latency
274
- console.log(client.getLatency()); // Average latency in ms
275
-
276
- // Get connection quality
277
- console.log(client.getConnectionQuality()); // 'excellent' | 'good' | 'fair' | 'poor' | 'disconnected'
278
-
279
- // Disable/enable monitoring
280
- client.setConnectionMonitoring(false);
175
+ import Honeydrop from 'honeydrop';
281
176
  ```
282
177
 
283
- ### Debugging
284
-
285
- ```javascript
286
- // Enable/disable debug mode
287
- client.setDebug(true);
288
-
289
- // Set log level
290
- client.setLogLevel('debug'); // 'debug' | 'info' | 'warn' | 'error'
178
+ ### Using via CDN
179
+ ```html
180
+ <script src="https://cdn.socket.io/4.7.4/socket.io.min.js"></script>
181
+ <script src="https://unpkg.com/honeydrop/dist/honeydrop.umd.js"></script>
182
+ <script>
183
+ const client = new Honeydrop.Honeydrop('http://localhost:3000');
184
+ </script>
291
185
  ```
292
186
 
293
- ## 🎮 Demo
187
+ ## 🤝 Contributing
294
188
 
295
- Run the included demo to see Honeydrop in action:
189
+ We welcome contributions! Please feel free to verify the correctness of your changes by running the demo app:
296
190
 
297
191
  ```bash
298
192
  cd demo
@@ -300,26 +194,6 @@ npm install
300
194
  npm start
301
195
  ```
302
196
 
303
- Then open `http://localhost:3000` in multiple browser tabs to test real-time communication.
304
-
305
- ## 🌐 Browser Usage
306
-
307
- ### With Bundler (Webpack, Vite, etc.)
308
-
309
- ```javascript
310
- import Honeydrop from 'honeydrop';
311
- ```
312
-
313
- ### Via Script Tag
314
-
315
- ```html
316
- <script src="https://cdn.socket.io/4.7.4/socket.io.min.js"></script>
317
- <script src="path/to/honeydrop.umd.js"></script>
318
- <script>
319
- const client = new Honeydrop.Honeydrop('http://localhost:3000');
320
- </script>
321
- ```
322
-
323
197
  ## 📄 License
324
198
 
325
- MIT © 2024
199
+ MIT © 2024 Neeraj
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "honeydrop",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "A lightweight, developer-friendly helper library for Socket.IO applications",
5
5
  "main": "dist/honeydrop.cjs.js",
6
6
  "module": "dist/honeydrop.esm.js",
@@ -61,15 +61,15 @@
61
61
  "@rollup/plugin-node-resolve": "^15.2.3",
62
62
  "@rollup/plugin-terser": "^0.4.4",
63
63
  "@rollup/plugin-typescript": "^11.1.6",
64
- "@types/jest": "^29.5.12",
64
+ "@types/jest": "^29.5.14",
65
65
  "jest": "^29.7.0",
66
66
  "rollup": "^4.9.6",
67
67
  "rollup-plugin-dts": "^6.1.0",
68
- "ts-jest": "^29.1.2",
68
+ "ts-jest": "^29.4.6",
69
69
  "tslib": "^2.6.2",
70
- "typescript": "^5.3.3"
70
+ "typescript": "^5.9.3"
71
71
  },
72
72
  "engines": {
73
73
  "node": ">=18.0.0"
74
74
  }
75
- }
75
+ }