nostr-websocket-utils 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 MaiQR Platform
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 ADDED
@@ -0,0 +1,152 @@
1
+ Nostr Websocket Utils
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@humanjavaenterprises/nostr-websocket-utils.svg)](https://www.npmjs.com/package/@humanjavaenterprises/nostr-websocket-utils)
4
+ [![License](https://img.shields.io/npm/l/@humanjavaenterprises/nostr-websocket-utils.svg)](https://github.com/HumanjavaEnterprises/nostr-websocket-utils/blob/main/LICENSE)
5
+ [![Build Status](https://github.com/HumanjavaEnterprises/nostr-websocket-utils/workflows/CI/badge.svg)](https://github.com/HumanjavaEnterprises/nostr-websocket-utils/actions)
6
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org)
7
+ [![code style: prettier](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
8
+
9
+ A TypeScript library providing WebSocket utilities for Nostr applications, with robust connection handling, automatic reconnection, and channel-based messaging.
10
+
11
+ ## Features
12
+
13
+ - 🔄 Automatic reconnection with configurable attempts
14
+ - 💓 Heartbeat monitoring
15
+ - 📨 Message queueing during disconnections
16
+ - 📢 Channel-based broadcasting
17
+ - 🔒 Type-safe message handling
18
+ - 📝 Built-in logging
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ npm install @humanjavaenterprises/nostr-websocket-utils
24
+ ```
25
+
26
+ ## Usage
27
+
28
+ ### Client Example
29
+
30
+ ```typescript
31
+ import { NostrWSClient } from '@humanjavaenterprises/nostr-websocket-utils';
32
+
33
+ const client = new NostrWSClient('wss://your-server.com', {
34
+ heartbeatInterval: 30000,
35
+ reconnectInterval: 5000,
36
+ maxReconnectAttempts: 5
37
+ });
38
+
39
+ client.on('connect', () => {
40
+ console.log('Connected!');
41
+ client.subscribe('my-channel');
42
+ });
43
+
44
+ client.on('message', (message) => {
45
+ console.log('Received:', message);
46
+ });
47
+
48
+ client.connect();
49
+ ```
50
+
51
+ ### Server Example
52
+
53
+ ```typescript
54
+ import express from 'express';
55
+ import { createServer } from 'http';
56
+ import { NostrWSServer } from '@humanjavaenterprises/nostr-websocket-utils';
57
+
58
+ const app = express();
59
+ const server = createServer(app);
60
+ const wss = new NostrWSServer(server, {
61
+ heartbeatInterval: 30000
62
+ });
63
+
64
+ wss.on('message', (message, client) => {
65
+ console.log('Received message:', message);
66
+
67
+ // Broadcast to specific channel
68
+ wss.broadcastToChannel('my-channel', {
69
+ type: 'event',
70
+ data: { content: 'Hello channel!' }
71
+ });
72
+ });
73
+
74
+ server.listen(3000);
75
+ ```
76
+
77
+ ## Why This Library is Perfect for Nostr Development
78
+
79
+ This library is specifically designed to accelerate Nostr application development by providing a robust foundation for WebSocket communication. Here's what makes it particularly valuable:
80
+
81
+ ### 1. Nostr-Specific Message Types
82
+ - Built-in support for core Nostr protocol message types (`subscribe`, `unsubscribe`, `event`, `request/response`)
83
+ - Perfectly aligned with Nostr's pub/sub model
84
+ - Type-safe message handling for all Nostr events
85
+
86
+ ### 2. Advanced WebSocket Management
87
+ - Zero-config connection maintenance with automatic reconnection
88
+ - Built-in heartbeat mechanism prevents stale connections
89
+ - Smart message queuing ensures no events are lost during disconnections
90
+ - Comprehensive connection state tracking
91
+
92
+ ### 3. Efficient Event Distribution
93
+ - Channel-based broadcasting for targeted event distribution
94
+ - Support for filtered subscriptions (crucial for Nostr event filtering)
95
+ - Memory-efficient subscription tracking
96
+ - Optimized message routing to relevant subscribers
97
+
98
+ ### 4. Developer Experience
99
+ - Full TypeScript support with comprehensive type definitions
100
+ - Event-driven architecture matching Nostr's event-centric nature
101
+ - Clear, consistent error handling and validation
102
+ - Minimal boilerplate needed to get started
103
+
104
+ ### 5. Production-Ready Features
105
+ - Built-in logging system
106
+ - Memory leak prevention through proper client cleanup
107
+ - Scalable client management
108
+ - Support for multiple simultaneous subscriptions
109
+
110
+ By using this library, you can skip weeks of WebSocket infrastructure development and focus on building your Nostr application's unique features.
111
+
112
+ ## API Reference
113
+
114
+ ### NostrWSClient
115
+
116
+ - `constructor(url: string, options?: NostrWSOptions)`
117
+ - `connect(): void`
118
+ - `send(message: NostrWSMessage): void`
119
+ - `subscribe(channel: string): void`
120
+ - `unsubscribe(channel: string): void`
121
+ - `close(): void`
122
+
123
+ Events:
124
+ - `connect`
125
+ - `disconnect`
126
+ - `reconnect`
127
+ - `message`
128
+ - `error`
129
+
130
+ ### NostrWSServer
131
+
132
+ - `constructor(server: any, options?: NostrWSOptions)`
133
+ - `broadcast(message: NostrWSMessage): void`
134
+ - `broadcastToChannel(channel: string, message: NostrWSMessage): void`
135
+ - `sendTo(client: ExtendedWebSocket, message: NostrWSMessage): void`
136
+ - `getClients(): Set<ExtendedWebSocket>`
137
+ - `close(): void`
138
+
139
+ Events:
140
+ - `message`
141
+
142
+ ## Contributing
143
+
144
+ 1. Fork the repository
145
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
146
+ 3. Commit your changes (`git commit -m 'Add amazing feature'`)
147
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
148
+ 5. Open a Pull Request
149
+
150
+ ## License
151
+
152
+ MIT
@@ -0,0 +1,22 @@
1
+ import { EventEmitter } from 'events';
2
+ import type { NostrWSOptions, NostrWSMessage } from './types/index.js';
3
+ export declare class NostrWSClient extends EventEmitter {
4
+ private url;
5
+ private ws;
6
+ private options;
7
+ private reconnectTimeout;
8
+ private heartbeatInterval;
9
+ private reconnectAttempts;
10
+ private messageQueue;
11
+ constructor(url: string, options?: Partial<NostrWSOptions>);
12
+ connect(): void;
13
+ private setupEventHandlers;
14
+ private startHeartbeat;
15
+ private stopHeartbeat;
16
+ private handleReconnect;
17
+ subscribe(channel: string, filter?: unknown): void;
18
+ unsubscribe(channel: string): void;
19
+ private flushMessageQueue;
20
+ send(message: NostrWSMessage): Promise<void>;
21
+ close(): void;
22
+ }
package/dist/client.js ADDED
@@ -0,0 +1,148 @@
1
+ import WebSocket from 'ws';
2
+ import { EventEmitter } from 'events';
3
+ export class NostrWSClient extends EventEmitter {
4
+ constructor(url, options = {}) {
5
+ super();
6
+ this.url = url;
7
+ this.ws = null;
8
+ this.reconnectTimeout = null;
9
+ this.heartbeatInterval = null;
10
+ this.reconnectAttempts = 0;
11
+ this.messageQueue = [];
12
+ if (!options.logger) {
13
+ throw new Error('Logger is required');
14
+ }
15
+ this.options = {
16
+ heartbeatInterval: options.heartbeatInterval || 30000,
17
+ logger: options.logger,
18
+ onMessage: options.onMessage,
19
+ onError: options.onError,
20
+ onClose: options.onClose
21
+ };
22
+ }
23
+ connect() {
24
+ if (this.ws) {
25
+ this.options.logger.info('WebSocket connection already exists');
26
+ return;
27
+ }
28
+ try {
29
+ this.ws = new WebSocket(this.url);
30
+ this.setupEventHandlers();
31
+ }
32
+ catch (error) {
33
+ this.options.logger.error('Failed to create WebSocket connection:', error);
34
+ this.handleReconnect();
35
+ }
36
+ }
37
+ setupEventHandlers() {
38
+ if (!this.ws)
39
+ return;
40
+ this.ws.on('open', () => {
41
+ this.options.logger.info('WebSocket connection established');
42
+ this.reconnectAttempts = 0;
43
+ this.startHeartbeat();
44
+ this.emit('connect');
45
+ this.flushMessageQueue();
46
+ });
47
+ this.ws.on('message', async (data) => {
48
+ try {
49
+ const message = JSON.parse(data.toString());
50
+ this.emit('message', message);
51
+ if (this.options.onMessage) {
52
+ await this.options.onMessage(this.ws, message);
53
+ }
54
+ }
55
+ catch (error) {
56
+ this.emit('error', error);
57
+ if (this.options.onError) {
58
+ this.options.onError(this.ws, error);
59
+ }
60
+ }
61
+ });
62
+ this.ws.on('close', () => {
63
+ this.options.logger.info('WebSocket connection closed');
64
+ this.stopHeartbeat();
65
+ this.handleReconnect();
66
+ this.emit('disconnect');
67
+ if (this.options.onClose) {
68
+ this.options.onClose(this.ws);
69
+ }
70
+ });
71
+ this.ws.on('error', (error) => {
72
+ this.options.logger.error('WebSocket error:', error);
73
+ this.emit('error', error);
74
+ if (this.options.onError) {
75
+ this.options.onError(this.ws, error);
76
+ }
77
+ });
78
+ }
79
+ startHeartbeat() {
80
+ if (this.heartbeatInterval)
81
+ return;
82
+ this.heartbeatInterval = setInterval(() => {
83
+ if (this.ws?.readyState === WebSocket.OPEN) {
84
+ this.ws.ping();
85
+ }
86
+ }, this.options.heartbeatInterval || 30000);
87
+ }
88
+ stopHeartbeat() {
89
+ if (this.heartbeatInterval) {
90
+ clearInterval(this.heartbeatInterval);
91
+ this.heartbeatInterval = null;
92
+ }
93
+ }
94
+ handleReconnect() {
95
+ if (this.reconnectTimeout)
96
+ return;
97
+ this.reconnectAttempts++;
98
+ this.reconnectTimeout = setTimeout(() => {
99
+ this.reconnectTimeout = null;
100
+ this.connect();
101
+ this.emit('reconnect');
102
+ }, 5000);
103
+ }
104
+ subscribe(channel, filter) {
105
+ this.send({
106
+ type: 'subscribe',
107
+ data: { channel, filter }
108
+ });
109
+ }
110
+ unsubscribe(channel) {
111
+ this.send({
112
+ type: 'unsubscribe',
113
+ data: { channel }
114
+ });
115
+ }
116
+ flushMessageQueue() {
117
+ while (this.messageQueue.length > 0 && this.ws?.readyState === WebSocket.OPEN) {
118
+ const message = this.messageQueue.shift();
119
+ if (message) {
120
+ this.send(message);
121
+ }
122
+ }
123
+ }
124
+ async send(message) {
125
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
126
+ this.messageQueue.push(message);
127
+ return;
128
+ }
129
+ try {
130
+ this.ws.send(JSON.stringify(message));
131
+ }
132
+ catch (error) {
133
+ this.options.logger.error('Failed to send message:', error);
134
+ this.handleReconnect();
135
+ }
136
+ }
137
+ close() {
138
+ this.stopHeartbeat();
139
+ if (this.reconnectTimeout) {
140
+ clearTimeout(this.reconnectTimeout);
141
+ this.reconnectTimeout = null;
142
+ }
143
+ if (this.ws) {
144
+ this.ws.close();
145
+ this.ws = null;
146
+ }
147
+ }
148
+ }
@@ -0,0 +1,4 @@
1
+ export { NostrWSClient } from './client.js';
2
+ export { NostrWSServer } from './server.js';
3
+ export { getLogger } from './utils/logger.js';
4
+ export type { NostrWSOptions, NostrWSMessage, NostrWSSubscription, NostrWSClientEvents, NostrWSServerEvents, ExtendedWebSocket, NostrWSValidationResult, NostrWSConnectionState } from './types/index.js';
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { NostrWSClient } from './client.js';
2
+ export { NostrWSServer } from './server.js';
3
+ export { getLogger } from './utils/logger.js';
@@ -0,0 +1,14 @@
1
+ import { EventEmitter } from 'events';
2
+ import { Server as HttpServer } from 'http';
3
+ import type { NostrWSOptions, NostrWSMessage } from './types/index.js';
4
+ export declare class NostrWSServer extends EventEmitter {
5
+ private wss;
6
+ private options;
7
+ private heartbeatInterval;
8
+ constructor(server: HttpServer, options?: Partial<NostrWSOptions>);
9
+ private setupServer;
10
+ private startHeartbeat;
11
+ broadcast(message: NostrWSMessage): void;
12
+ broadcastToChannel(channel: string, message: NostrWSMessage): void;
13
+ close(): void;
14
+ }
package/dist/server.js ADDED
@@ -0,0 +1,89 @@
1
+ import { EventEmitter } from 'events';
2
+ import { WebSocketServer, WebSocket } from 'ws';
3
+ export class NostrWSServer extends EventEmitter {
4
+ constructor(server, options = {}) {
5
+ super();
6
+ this.heartbeatInterval = null;
7
+ if (!options.logger) {
8
+ throw new Error('Logger is required');
9
+ }
10
+ this.options = {
11
+ heartbeatInterval: options.heartbeatInterval || 30000,
12
+ logger: options.logger,
13
+ onMessage: options.onMessage || (() => { }),
14
+ onError: options.onError || (() => { }),
15
+ onClose: options.onClose || (() => { })
16
+ };
17
+ this.wss = new WebSocketServer({ server });
18
+ this.setupServer();
19
+ }
20
+ setupServer() {
21
+ this.wss.on('connection', (ws) => {
22
+ const extWs = ws;
23
+ extWs.subscriptions = new Set();
24
+ extWs.isAlive = true;
25
+ ws.on('message', async (data) => {
26
+ try {
27
+ const message = JSON.parse(data.toString());
28
+ if (this.options.onMessage) {
29
+ await this.options.onMessage(extWs, message);
30
+ }
31
+ }
32
+ catch (error) {
33
+ if (this.options.onError) {
34
+ this.options.onError(ws, error);
35
+ }
36
+ }
37
+ });
38
+ ws.on('close', () => {
39
+ extWs.isAlive = false;
40
+ if (this.options.onClose) {
41
+ this.options.onClose(ws);
42
+ }
43
+ });
44
+ ws.on('error', (error) => {
45
+ if (this.options.onError) {
46
+ this.options.onError(ws, error);
47
+ }
48
+ });
49
+ });
50
+ if (this.options.heartbeatInterval && this.options.heartbeatInterval > 0) {
51
+ this.startHeartbeat();
52
+ }
53
+ }
54
+ startHeartbeat() {
55
+ this.heartbeatInterval = setInterval(() => {
56
+ this.wss.clients.forEach((ws) => {
57
+ if (ws.readyState === WebSocket.OPEN) {
58
+ const extWs = ws;
59
+ if (!extWs.isAlive) {
60
+ return ws.terminate();
61
+ }
62
+ ws.ping();
63
+ extWs.isAlive = false;
64
+ }
65
+ });
66
+ }, this.options.heartbeatInterval || 30000);
67
+ }
68
+ broadcast(message) {
69
+ this.wss.clients.forEach((client) => {
70
+ if (client.readyState === WebSocket.OPEN) {
71
+ client.send(JSON.stringify(message));
72
+ }
73
+ });
74
+ }
75
+ broadcastToChannel(channel, message) {
76
+ this.wss.clients.forEach((client) => {
77
+ const extClient = client;
78
+ if (client.readyState === WebSocket.OPEN && extClient.subscriptions?.has(channel)) {
79
+ client.send(JSON.stringify(message));
80
+ }
81
+ });
82
+ }
83
+ close() {
84
+ if (this.heartbeatInterval) {
85
+ clearInterval(this.heartbeatInterval);
86
+ }
87
+ this.wss.close();
88
+ }
89
+ }
@@ -0,0 +1,53 @@
1
+ import type { WebSocket } from 'ws';
2
+ export type MessageType = 'subscribe' | 'unsubscribe' | 'event' | 'request' | 'response' | 'error' | 'status';
3
+ export interface NostrWSOptions {
4
+ heartbeatInterval?: number;
5
+ reconnectInterval?: number;
6
+ maxReconnectAttempts?: number;
7
+ logger: Logger;
8
+ onMessage?: (ws: ExtendedWebSocket, message: NostrWSMessage) => Promise<void> | void;
9
+ onError?: (ws: WebSocket, error: Error) => void;
10
+ onClose?: (ws: WebSocket) => void;
11
+ }
12
+ export interface NostrWSMessage {
13
+ type: string;
14
+ id?: string;
15
+ data: Record<string, unknown>;
16
+ }
17
+ export interface NostrWSSubscription {
18
+ channel: string;
19
+ filter?: Record<string, unknown>;
20
+ }
21
+ export interface NostrWSClientEvents {
22
+ connect: () => void;
23
+ disconnect: () => void;
24
+ reconnect: () => void;
25
+ message: (message: NostrWSMessage) => void;
26
+ error: (error: Error) => void;
27
+ }
28
+ export interface NostrWSServerEvents {
29
+ connection: (client: ExtendedWebSocket) => void;
30
+ message: (message: NostrWSMessage, client: ExtendedWebSocket) => void;
31
+ error: (error: Error) => void;
32
+ }
33
+ export interface ExtendedWebSocket extends WebSocket {
34
+ isAlive?: boolean;
35
+ subscriptions?: Set<string>;
36
+ messageQueue?: NostrWSMessage[];
37
+ lastPing?: number;
38
+ reconnectAttempts?: number;
39
+ }
40
+ export interface NostrWSValidationResult {
41
+ isValid: boolean;
42
+ error?: string;
43
+ }
44
+ export interface NostrWSConnectionState {
45
+ isConnected: boolean;
46
+ reconnectAttempts: number;
47
+ lastError?: string;
48
+ }
49
+ export interface Logger {
50
+ debug: (message: string, ...args: unknown[]) => void;
51
+ info: (message: string, ...args: unknown[]) => void;
52
+ error: (message: string, ...args: unknown[]) => void;
53
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import winston from 'winston';
2
+ export declare function getLogger(name?: string): winston.Logger;
@@ -0,0 +1,16 @@
1
+ import winston from 'winston';
2
+ const logger = winston.createLogger({
3
+ level: process.env.LOG_LEVEL || 'info',
4
+ format: winston.format.combine(winston.format.timestamp(), winston.format.json()),
5
+ transports: [
6
+ new winston.transports.Console({
7
+ format: winston.format.combine(winston.format.colorize(), winston.format.simple())
8
+ })
9
+ ]
10
+ });
11
+ export function getLogger(name) {
12
+ if (name) {
13
+ return logger.child({ service: name });
14
+ }
15
+ return logger;
16
+ }
package/package.json ADDED
@@ -0,0 +1,62 @@
1
+ {
2
+ "name": "nostr-websocket-utils",
3
+ "version": "0.1.0",
4
+ "description": "WebSocket utilities for Nostr applications",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "type": "module",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "jest",
11
+ "test:watch": "jest --watch",
12
+ "test:coverage": "jest --coverage",
13
+ "lint": "eslint src --ext .ts",
14
+ "prepare": "npm run build",
15
+ "prepublishOnly": "npm test && npm run lint"
16
+ },
17
+ "keywords": [
18
+ "nostr",
19
+ "websocket",
20
+ "utils",
21
+ "maiqr"
22
+ ],
23
+ "author": "Human Java Enterprises",
24
+ "license": "MIT",
25
+ "dependencies": {
26
+ "ws": "^8.16.0",
27
+ "winston": "^3.11.0",
28
+ "@noble/curves": "^1.3.0",
29
+ "@noble/hashes": "^1.3.3",
30
+ "nostr-tools": "^2.1.4"
31
+ },
32
+ "peerDependencies": {
33
+ "nostr-tools": "^2.1.4"
34
+ },
35
+ "devDependencies": {
36
+ "@types/jest": "^29.5.11",
37
+ "@types/node": "^20.11.0",
38
+ "@types/ws": "^8.5.10",
39
+ "@typescript-eslint/eslint-plugin": "^6.18.1",
40
+ "@typescript-eslint/parser": "^6.18.1",
41
+ "eslint": "^8.56.0",
42
+ "jest": "^29.7.0",
43
+ "ts-jest": "^29.1.1",
44
+ "typescript": "^5.3.3"
45
+ },
46
+ "files": [
47
+ "dist",
48
+ "README.md",
49
+ "LICENSE"
50
+ ],
51
+ "repository": {
52
+ "type": "git",
53
+ "url": "git+https://github.com/humanjavaenterprises/nostr-websocket-utils.git"
54
+ },
55
+ "bugs": {
56
+ "url": "https://github.com/humanjavaenterprises/nostr-websocket-utils/issues"
57
+ },
58
+ "homepage": "https://github.com/humanjavaenterprises/nostr-websocket-utils#readme",
59
+ "publishConfig": {
60
+ "access": "public"
61
+ }
62
+ }