librats 0.3.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/lib/index.d.ts ADDED
@@ -0,0 +1,522 @@
1
+ /**
2
+ * LibRats Node.js Bindings - TypeScript Definitions
3
+ *
4
+ * High-performance peer-to-peer networking library with support for DHT, GossipSub,
5
+ * file transfer, NAT traversal, and more.
6
+ */
7
+
8
+ /**
9
+ * Version information structure
10
+ */
11
+ export interface VersionInfo {
12
+ major: number;
13
+ minor: number;
14
+ patch: number;
15
+ build: number;
16
+ }
17
+
18
+ /**
19
+ * Connection strategy options for connecting to peers
20
+ */
21
+ export enum ConnectionStrategy {
22
+ /** Direct connection only, no NAT traversal */
23
+ DIRECT_ONLY = 0,
24
+ /** STUN-assisted connection */
25
+ STUN_ASSISTED = 1,
26
+ /** Full ICE negotiation with STUN and connection checks */
27
+ ICE_FULL = 2,
28
+ /** TURN relay connection */
29
+ TURN_RELAY = 3,
30
+ /** Automatic strategy selection based on network conditions */
31
+ AUTO_ADAPTIVE = 4
32
+ }
33
+
34
+ /**
35
+ * Error codes returned by various operations
36
+ */
37
+ export enum ErrorCodes {
38
+ /** Operation completed successfully */
39
+ SUCCESS = 0,
40
+ /** Invalid client handle */
41
+ INVALID_HANDLE = -1,
42
+ /** Invalid parameter provided */
43
+ INVALID_PARAMETER = -2,
44
+ /** Client is not running */
45
+ NOT_RUNNING = -3,
46
+ /** Operation failed */
47
+ OPERATION_FAILED = -4,
48
+ /** Peer not found */
49
+ PEER_NOT_FOUND = -5,
50
+ /** Memory allocation error */
51
+ MEMORY_ALLOCATION = -6,
52
+ /** JSON parsing error */
53
+ JSON_PARSE = -7
54
+ }
55
+
56
+ /**
57
+ * Main RatsClient class for peer-to-peer networking
58
+ */
59
+ export class RatsClient {
60
+ /**
61
+ * Create a new RatsClient instance
62
+ * @param listenPort - Port to listen on for incoming connections
63
+ */
64
+ constructor(listenPort: number);
65
+
66
+ // ============ Basic Operations ============
67
+
68
+ /**
69
+ * Start the client
70
+ * @returns true if started successfully, false otherwise
71
+ */
72
+ start(): boolean;
73
+
74
+ /**
75
+ * Stop the client
76
+ */
77
+ stop(): void;
78
+
79
+ /**
80
+ * Connect to a peer
81
+ * @param host - IP address or hostname of the peer
82
+ * @param port - Port number of the peer
83
+ * @returns true if connection initiated successfully
84
+ */
85
+ connect(host: string, port: number): boolean;
86
+
87
+ /**
88
+ * Connect to a peer with a specific connection strategy
89
+ * @param host - IP address or hostname of the peer
90
+ * @param port - Port number of the peer
91
+ * @param strategy - Connection strategy to use
92
+ * @returns true if connection initiated successfully
93
+ */
94
+ connectWithStrategy(host: string, port: number, strategy: ConnectionStrategy): boolean;
95
+
96
+ /**
97
+ * Disconnect from a peer
98
+ * @param peerId - ID of the peer to disconnect from
99
+ */
100
+ disconnect(peerId: string): void;
101
+
102
+ // ============ Information ============
103
+
104
+ /**
105
+ * Get the number of connected peers
106
+ * @returns Number of connected peers
107
+ */
108
+ getPeerCount(): number;
109
+
110
+ /**
111
+ * Get our own peer ID
112
+ * @returns Our peer ID, or null if not started
113
+ */
114
+ getOurPeerId(): string | null;
115
+
116
+ /**
117
+ * Get list of connected peer IDs
118
+ * @returns Array of peer IDs
119
+ */
120
+ getPeerIds(): string[];
121
+
122
+ /**
123
+ * Get connection statistics as JSON string
124
+ * @returns JSON string with statistics, or null if unavailable
125
+ */
126
+ getConnectionStatistics(): string | null;
127
+
128
+ /**
129
+ * Get file transfer statistics as JSON string
130
+ * @returns JSON string with statistics, or null if unavailable
131
+ */
132
+ getFileTransferStatistics(): string | null;
133
+
134
+ // ============ Peer Management ============
135
+
136
+ /**
137
+ * Set maximum number of peers
138
+ * @param maxPeers - Maximum number of peers to allow
139
+ * @returns true if set successfully
140
+ */
141
+ setMaxPeers(maxPeers: number): boolean;
142
+
143
+ /**
144
+ * Get maximum number of peers
145
+ * @returns Maximum number of peers allowed
146
+ */
147
+ getMaxPeers(): number;
148
+
149
+ /**
150
+ * Check if peer limit has been reached
151
+ * @returns true if at or over peer limit
152
+ */
153
+ isPeerLimitReached(): boolean;
154
+
155
+ // ============ Messaging ============
156
+
157
+ /**
158
+ * Send a string message to a peer
159
+ * @param peerId - ID of the peer to send to
160
+ * @param message - String message to send
161
+ * @returns true if sent successfully
162
+ */
163
+ sendString(peerId: string, message: string): boolean;
164
+
165
+ /**
166
+ * Send binary data to a peer
167
+ * @param peerId - ID of the peer to send to
168
+ * @param data - Buffer containing binary data
169
+ * @returns true if sent successfully
170
+ */
171
+ sendBinary(peerId: string, data: Buffer): boolean;
172
+
173
+ /**
174
+ * Send JSON data to a peer
175
+ * @param peerId - ID of the peer to send to
176
+ * @param jsonStr - JSON string to send
177
+ * @returns true if sent successfully
178
+ */
179
+ sendJson(peerId: string, jsonStr: string): boolean;
180
+
181
+ /**
182
+ * Broadcast a string message to all connected peers
183
+ * @param message - String message to broadcast
184
+ * @returns Number of peers the message was sent to
185
+ */
186
+ broadcastString(message: string): number;
187
+
188
+ /**
189
+ * Broadcast binary data to all connected peers
190
+ * @param data - Buffer containing binary data
191
+ * @returns Number of peers the data was sent to
192
+ */
193
+ broadcastBinary(data: Buffer): number;
194
+
195
+ /**
196
+ * Broadcast JSON data to all connected peers
197
+ * @param jsonStr - JSON string to broadcast
198
+ * @returns Number of peers the data was sent to
199
+ */
200
+ broadcastJson(jsonStr: string): number;
201
+
202
+ // ============ File Transfer ============
203
+
204
+ /**
205
+ * Send a file to a peer
206
+ * @param peerId - ID of the peer to send to
207
+ * @param filePath - Local path to the file
208
+ * @param remoteFilename - Optional filename on remote side
209
+ * @returns Transfer ID, or null if failed
210
+ */
211
+ sendFile(peerId: string, filePath: string, remoteFilename?: string): string | null;
212
+
213
+ /**
214
+ * Send a directory to a peer
215
+ * @param peerId - ID of the peer to send to
216
+ * @param dirPath - Local path to the directory
217
+ * @param remoteDirName - Optional directory name on remote side
218
+ * @param recursive - Whether to send recursively (default: true)
219
+ * @returns Transfer ID, or null if failed
220
+ */
221
+ sendDirectory(peerId: string, dirPath: string, remoteDirName?: string, recursive?: boolean): string | null;
222
+
223
+ /**
224
+ * Request a file from a peer
225
+ * @param peerId - ID of the peer to request from
226
+ * @param remoteFilePath - Path to the file on remote side
227
+ * @param localPath - Local path where file should be saved
228
+ * @returns Transfer ID, or null if failed
229
+ */
230
+ requestFile(peerId: string, remoteFilePath: string, localPath: string): string | null;
231
+
232
+ /**
233
+ * Request a directory from a peer
234
+ * @param peerId - ID of the peer to request from
235
+ * @param remoteDirPath - Path to the directory on remote side
236
+ * @param localDirPath - Local path where directory should be saved
237
+ * @param recursive - Whether to request recursively (default: true)
238
+ * @returns Transfer ID, or null if failed
239
+ */
240
+ requestDirectory(peerId: string, remoteDirPath: string, localDirPath: string, recursive?: boolean): string | null;
241
+
242
+ /**
243
+ * Accept an incoming file transfer
244
+ * @param transferId - ID of the transfer to accept
245
+ * @param localPath - Local path where file should be saved
246
+ * @returns true if accepted successfully
247
+ */
248
+ acceptFileTransfer(transferId: string, localPath: string): boolean;
249
+
250
+ /**
251
+ * Reject an incoming file transfer
252
+ * @param transferId - ID of the transfer to reject
253
+ * @param reason - Optional reason for rejection
254
+ * @returns true if rejected successfully
255
+ */
256
+ rejectFileTransfer(transferId: string, reason?: string): boolean;
257
+
258
+ /**
259
+ * Cancel an ongoing file transfer
260
+ * @param transferId - ID of the transfer to cancel
261
+ * @returns true if cancelled successfully
262
+ */
263
+ cancelFileTransfer(transferId: string): boolean;
264
+
265
+ /**
266
+ * Pause a file transfer
267
+ * @param transferId - ID of the transfer to pause
268
+ * @returns true if paused successfully
269
+ */
270
+ pauseFileTransfer(transferId: string): boolean;
271
+
272
+ /**
273
+ * Resume a paused file transfer
274
+ * @param transferId - ID of the transfer to resume
275
+ * @returns true if resumed successfully
276
+ */
277
+ resumeFileTransfer(transferId: string): boolean;
278
+
279
+ // ============ GossipSub ============
280
+
281
+ /**
282
+ * Check if GossipSub is available
283
+ * @returns true if GossipSub is available
284
+ */
285
+ isGossipsubAvailable(): boolean;
286
+
287
+ /**
288
+ * Check if GossipSub is running
289
+ * @returns true if GossipSub is running
290
+ */
291
+ isGossipsubRunning(): boolean;
292
+
293
+ /**
294
+ * Subscribe to a topic
295
+ * @param topic - Topic name to subscribe to
296
+ * @returns true if subscribed successfully
297
+ */
298
+ subscribeToTopic(topic: string): boolean;
299
+
300
+ /**
301
+ * Unsubscribe from a topic
302
+ * @param topic - Topic name to unsubscribe from
303
+ * @returns true if unsubscribed successfully
304
+ */
305
+ unsubscribeFromTopic(topic: string): boolean;
306
+
307
+ /**
308
+ * Check if subscribed to a topic
309
+ * @param topic - Topic name to check
310
+ * @returns true if subscribed
311
+ */
312
+ isSubscribedToTopic(topic: string): boolean;
313
+
314
+ /**
315
+ * Publish a message to a topic
316
+ * @param topic - Topic name to publish to
317
+ * @param message - Message to publish
318
+ * @returns true if published successfully
319
+ */
320
+ publishToTopic(topic: string, message: string): boolean;
321
+
322
+ /**
323
+ * Publish JSON data to a topic
324
+ * @param topic - Topic name to publish to
325
+ * @param jsonStr - JSON string to publish
326
+ * @returns true if published successfully
327
+ */
328
+ publishJsonToTopic(topic: string, jsonStr: string): boolean;
329
+
330
+ /**
331
+ * Get list of subscribed topics
332
+ * @returns Array of topic names
333
+ */
334
+ getSubscribedTopics(): string[];
335
+
336
+ /**
337
+ * Get peers subscribed to a topic
338
+ * @param topic - Topic name
339
+ * @returns Array of peer IDs
340
+ */
341
+ getTopicPeers(topic: string): string[];
342
+
343
+ // ============ DHT ============
344
+
345
+ /**
346
+ * Start DHT discovery
347
+ * @param dhtPort - Port to use for DHT
348
+ * @returns true if started successfully
349
+ */
350
+ startDhtDiscovery(dhtPort: number): boolean;
351
+
352
+ /**
353
+ * Stop DHT discovery
354
+ */
355
+ stopDhtDiscovery(): void;
356
+
357
+ /**
358
+ * Check if DHT is running
359
+ * @returns true if DHT is running
360
+ */
361
+ isDhtRunning(): boolean;
362
+
363
+ /**
364
+ * Get DHT routing table size
365
+ * @returns Number of entries in the routing table
366
+ */
367
+ getDhtRoutingTableSize(): number;
368
+
369
+ /**
370
+ * Announce availability for a content hash
371
+ * @param contentHash - Hash to announce for
372
+ * @param port - Port to announce
373
+ * @returns true if announced successfully
374
+ */
375
+ announceForHash(contentHash: string, port: number): boolean;
376
+
377
+ // ============ mDNS ============
378
+
379
+ /**
380
+ * Start mDNS discovery
381
+ * @param serviceName - Service name to advertise
382
+ * @returns true if started successfully
383
+ */
384
+ startMdnsDiscovery(serviceName: string): boolean;
385
+
386
+ /**
387
+ * Stop mDNS discovery
388
+ */
389
+ stopMdnsDiscovery(): void;
390
+
391
+ /**
392
+ * Check if mDNS is running
393
+ * @returns true if mDNS is running
394
+ */
395
+ isMdnsRunning(): boolean;
396
+
397
+ // ============ Encryption ============
398
+
399
+ /**
400
+ * Enable or disable encryption
401
+ * @param enabled - Whether encryption should be enabled
402
+ * @returns true if set successfully
403
+ */
404
+ setEncryptionEnabled(enabled: boolean): boolean;
405
+
406
+ /**
407
+ * Check if encryption is enabled
408
+ * @returns true if encryption is enabled
409
+ */
410
+ isEncryptionEnabled(): boolean;
411
+
412
+ /**
413
+ * Generate a new encryption key
414
+ * @returns Hex-encoded encryption key, or null if failed
415
+ */
416
+ generateEncryptionKey(): string | null;
417
+
418
+ /**
419
+ * Set the encryption key
420
+ * @param keyHex - Hex-encoded encryption key
421
+ * @returns true if set successfully
422
+ */
423
+ setEncryptionKey(keyHex: string): boolean;
424
+
425
+ /**
426
+ * Get the current encryption key
427
+ * @returns Hex-encoded encryption key, or null if not set
428
+ */
429
+ getEncryptionKey(): string | null;
430
+
431
+ // ============ Configuration Persistence ============
432
+
433
+ /**
434
+ * Set data directory for configuration files
435
+ * @param directory - Path to data directory
436
+ * @returns true if set successfully
437
+ */
438
+ setDataDirectory(directory: string): boolean;
439
+
440
+ /**
441
+ * Get current data directory
442
+ * @returns Path to data directory, or null if not set
443
+ */
444
+ getDataDirectory(): string | null;
445
+
446
+ /**
447
+ * Save current configuration to disk
448
+ * @returns true if saved successfully
449
+ */
450
+ saveConfiguration(): boolean;
451
+
452
+ /**
453
+ * Load configuration from disk
454
+ * @returns true if loaded successfully
455
+ */
456
+ loadConfiguration(): boolean;
457
+
458
+ // ============ Event Handlers ============
459
+
460
+ /**
461
+ * Set callback for when a peer connects
462
+ * @param callback - Function to call with peer ID
463
+ */
464
+ onConnection(callback: (peerId: string) => void): void;
465
+
466
+ /**
467
+ * Set callback for string messages
468
+ * @param callback - Function to call with peer ID and message
469
+ */
470
+ onString(callback: (peerId: string, message: string) => void): void;
471
+
472
+ /**
473
+ * Set callback for binary messages
474
+ * @param callback - Function to call with peer ID and data
475
+ */
476
+ onBinary(callback: (peerId: string, data: Buffer) => void): void;
477
+
478
+ /**
479
+ * Set callback for JSON messages
480
+ * @param callback - Function to call with peer ID and JSON string
481
+ */
482
+ onJson(callback: (peerId: string, jsonStr: string) => void): void;
483
+
484
+ /**
485
+ * Set callback for when a peer disconnects
486
+ * @param callback - Function to call with peer ID
487
+ */
488
+ onDisconnect(callback: (peerId: string) => void): void;
489
+
490
+ /**
491
+ * Set callback for file transfer progress updates
492
+ * @param callback - Function to call with transfer ID, progress percentage, and status
493
+ */
494
+ onFileProgress(callback: (transferId: string, progressPercent: number, status: string) => void): void;
495
+ }
496
+
497
+ // ============ Utility Functions ============
498
+
499
+ /**
500
+ * Get the library version as a string
501
+ * @returns Version string (e.g., "1.0.0.123")
502
+ */
503
+ export function getVersionString(): string;
504
+
505
+ /**
506
+ * Get the library version components
507
+ * @returns Version information object
508
+ */
509
+ export function getVersion(): VersionInfo;
510
+
511
+ /**
512
+ * Get git describe string
513
+ * @returns Git describe string
514
+ */
515
+ export function getGitDescribe(): string;
516
+
517
+ /**
518
+ * Get ABI version number
519
+ * @returns ABI version
520
+ */
521
+ export function getAbi(): number;
522
+
package/lib/index.js ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * LibRats Node.js Bindings
3
+ *
4
+ * High-performance peer-to-peer networking library with support for DHT, GossipSub,
5
+ * file transfer, NAT traversal, and more.
6
+ */
7
+
8
+ const path = require('path');
9
+ const fs = require('fs');
10
+
11
+ // Try to load the native addon from the build directory
12
+ let addon;
13
+ let addonPath;
14
+
15
+ // Possible locations for the built addon
16
+ const possiblePaths = [
17
+ // Standard node-gyp build location
18
+ path.join(__dirname, '..', 'build', 'Release', 'librats.node'),
19
+ path.join(__dirname, '..', 'build', 'Debug', 'librats.node'),
20
+ // Alternative build locations
21
+ path.join(__dirname, '..', 'build', 'librats.node'),
22
+ ];
23
+
24
+ // Try each path
25
+ for (const tryPath of possiblePaths) {
26
+ try {
27
+ if (fs.existsSync(tryPath)) {
28
+ addon = require(tryPath);
29
+ addonPath = tryPath;
30
+ break;
31
+ }
32
+ } catch (err) {
33
+ // Continue to next path
34
+ }
35
+ }
36
+
37
+ if (!addon) {
38
+ throw new Error(
39
+ 'Could not load librats native addon. ' +
40
+ 'Make sure the package is installed correctly and the native library is built. ' +
41
+ 'Try running: npm rebuild librats'
42
+ );
43
+ }
44
+
45
+ // Export all native bindings
46
+ module.exports = {
47
+ // Main class
48
+ RatsClient: addon.RatsClient,
49
+
50
+ // Version functions
51
+ getVersionString: addon.getVersionString,
52
+ getVersion: addon.getVersion,
53
+ getGitDescribe: addon.getGitDescribe,
54
+ getAbi: addon.getAbi,
55
+
56
+ // Constants
57
+ ConnectionStrategy: {
58
+ DIRECT_ONLY: 0,
59
+ STUN_ASSISTED: 1,
60
+ ICE_FULL: 2,
61
+ TURN_RELAY: 3,
62
+ AUTO_ADAPTIVE: 4
63
+ },
64
+
65
+ ErrorCodes: {
66
+ SUCCESS: 0,
67
+ INVALID_HANDLE: -1,
68
+ INVALID_PARAMETER: -2,
69
+ NOT_RUNNING: -3,
70
+ OPERATION_FAILED: -4,
71
+ PEER_NOT_FOUND: -5,
72
+ MEMORY_ALLOCATION: -6,
73
+ JSON_PARSE: -7
74
+ }
75
+ };
76
+
77
+ // Log successful load for debugging
78
+ if (process.env.LIBRATS_DEBUG) {
79
+ console.log(`[librats] Loaded native addon from: ${addonPath}`);
80
+ console.log(`[librats] Version: ${addon.getVersionString()}`);
81
+ }
82
+
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "librats",
3
+ "version": "0.3.1",
4
+ "description": "Node.js bindings for librats - A high-performance peer-to-peer networking library",
5
+ "main": "lib/index.js",
6
+ "types": "lib/index.d.ts",
7
+ "engines": {
8
+ "node": ">=20.0.0"
9
+ },
10
+ "scripts": {
11
+ "build": "node-gyp rebuild",
12
+ "clean": "node-gyp clean",
13
+ "preinstall": "node scripts/build-librats.js",
14
+ "install": "node-gyp rebuild",
15
+ "postinstall": "node scripts/postinstall.js",
16
+ "test": "node test/test.js",
17
+ "verify": "node scripts/verify-installation.js",
18
+ "prepare": "node scripts/prepare-package.js",
19
+ "prepublishOnly": "npm run build"
20
+ },
21
+ "keywords": [
22
+ "p2p",
23
+ "peer-to-peer",
24
+ "networking",
25
+ "dht",
26
+ "gossipsub",
27
+ "file-transfer",
28
+ "mdns",
29
+ "stun",
30
+ "ice",
31
+ "nat-traversal",
32
+ "encryption",
33
+ "native"
34
+ ],
35
+ "author": "librats team",
36
+ "license": "MIT",
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "https://github.com/librats/librats.git",
40
+ "directory": "nodejs"
41
+ },
42
+ "bugs": {
43
+ "url": "https://github.com/librats/librats/issues"
44
+ },
45
+ "homepage": "https://github.com/librats/librats#readme",
46
+ "dependencies": {
47
+ "node-addon-api": "^8.5.0"
48
+ },
49
+ "devDependencies": {
50
+ "node-gyp": "^11.4.2",
51
+ "@types/node": "^24.3.1"
52
+ },
53
+ "files": [
54
+ "lib/**/*",
55
+ "src/**/*",
56
+ "scripts/**/*",
57
+ "binding.gyp",
58
+ "README.md",
59
+ "../src/**/*.cpp",
60
+ "../src/**/*.h",
61
+ "../src/**/*.in",
62
+ "../3rdparty/**/*",
63
+ "../CMakeLists.txt",
64
+ "../LICENSE",
65
+ "!../src/main.cpp"
66
+ ],
67
+ "gypfile": true
68
+ }