@ooneex/socket-client 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ooneex
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,177 @@
1
+ # @ooneex/socket-client
2
+
3
+ WebSocket client for real-time bidirectional communication with automatic reconnection, event handling, and typed message serialization.
4
+
5
+ ![Browser](https://img.shields.io/badge/Browser-Compatible-green?style=flat-square&logo=googlechrome)
6
+ ![Bun](https://img.shields.io/badge/Bun-Compatible-orange?style=flat-square&logo=bun)
7
+ ![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue?style=flat-square&logo=typescript)
8
+ ![MIT License](https://img.shields.io/badge/License-MIT-yellow?style=flat-square)
9
+
10
+ ## Features
11
+
12
+ ✅ **Socket Class** - WebSocket client with typed send and receive operations via the `Socket` class
13
+
14
+ ✅ **Message Queuing** - Automatically queues messages sent before the connection is open and flushes them on connect
15
+
16
+ ✅ **Typed Events** - Register handlers for `onMessage`, `onOpen`, `onClose`, and `onError` with typed responses
17
+
18
+ ✅ **JSON Serialization** - Automatic JSON serialization for outgoing messages and deserialization for incoming responses
19
+
20
+ ✅ **Protocol Auto-Detection** - Automatically converts HTTP/HTTPS URLs to WS/WSS WebSocket protocols
21
+
22
+ ✅ **Generic Type Parameters** - Parameterize `Socket<SendData, Response>` for type-safe request and response data
23
+
24
+ ✅ **ISocket Interface** - Standard interface defining the WebSocket client contract
25
+
26
+ ✅ **Locale Support** - Request data type includes optional language/locale information
27
+
28
+ ## Installation
29
+
30
+ ```bash
31
+ bun add @ooneex/socket-client
32
+ ```
33
+
34
+ ## Usage
35
+
36
+ ### Basic Connection
37
+
38
+ ```typescript
39
+ import { Socket } from '@ooneex/socket-client';
40
+
41
+ const socket = new Socket('wss://api.example.com/ws/chat');
42
+
43
+ socket.onOpen(() => {
44
+ console.log('Connected');
45
+ });
46
+
47
+ socket.onMessage((response) => {
48
+ console.log('Received:', response);
49
+ });
50
+
51
+ socket.onClose((event) => {
52
+ console.log('Disconnected:', event.code, event.reason);
53
+ });
54
+
55
+ socket.onError((event) => {
56
+ console.error('Error:', event);
57
+ });
58
+ ```
59
+
60
+ ### Sending Messages
61
+
62
+ ```typescript
63
+ import { Socket } from '@ooneex/socket-client';
64
+
65
+ const socket = new Socket('wss://api.example.com/ws/messages');
66
+
67
+ // Messages are queued if the connection is not yet open
68
+ socket.send({
69
+ payload: { message: 'Hello, world!' },
70
+ queries: { room: 'general' }
71
+ });
72
+ ```
73
+
74
+ ### Typed Socket
75
+
76
+ ```typescript
77
+ import { Socket, type RequestDataType } from '@ooneex/socket-client';
78
+
79
+ interface ChatRequest extends RequestDataType {
80
+ payload: { message: string; type: 'text' | 'image' };
81
+ }
82
+
83
+ interface ChatResponse {
84
+ event: string;
85
+ data: { messageId: string; timestamp: string };
86
+ }
87
+
88
+ const socket = new Socket<ChatRequest, ChatResponse>(
89
+ 'wss://api.example.com/ws/chat'
90
+ );
91
+
92
+ socket.onMessage((response) => {
93
+ // response is typed as ResponseDataType<ChatResponse>
94
+ console.log(response.data.event);
95
+ });
96
+
97
+ socket.send({
98
+ payload: { message: 'Hello!', type: 'text' }
99
+ });
100
+ ```
101
+
102
+ ### Closing a Connection
103
+
104
+ ```typescript
105
+ import { Socket } from '@ooneex/socket-client';
106
+
107
+ const socket = new Socket('wss://api.example.com/ws');
108
+
109
+ // Close with a status code and reason
110
+ socket.close(1000, 'User disconnected');
111
+ ```
112
+
113
+ ## API Reference
114
+
115
+ ### Classes
116
+
117
+ #### `Socket<SendData, Response>`
118
+
119
+ WebSocket client class with typed messaging.
120
+
121
+ **Constructor:**
122
+ - `url: string` - WebSocket URL (supports `ws://`, `wss://`, `http://`, `https://`, or bare hostnames)
123
+
124
+ **Methods:**
125
+
126
+ | Method | Returns | Description |
127
+ |--------|---------|-------------|
128
+ | `send(data)` | `void` | Send typed data as JSON (queued if not yet connected) |
129
+ | `close(code?, reason?)` | `void` | Close the WebSocket connection |
130
+ | `onMessage(handler)` | `void` | Register a handler for incoming messages |
131
+ | `onOpen(handler)` | `void` | Register a handler for connection open |
132
+ | `onClose(handler)` | `void` | Register a handler for connection close |
133
+ | `onError(handler)` | `void` | Register a handler for errors |
134
+
135
+ ### Interfaces
136
+
137
+ #### `ISocket<SendData, Response>`
138
+
139
+ Interface defining the WebSocket client contract.
140
+
141
+ ### Types
142
+
143
+ #### `RequestDataType`
144
+
145
+ ```typescript
146
+ type RequestDataType = {
147
+ payload?: Record<string, unknown>;
148
+ queries?: Record<string, boolean | number | bigint | string>;
149
+ language?: LocaleInfoType;
150
+ };
151
+ ```
152
+
153
+ ## License
154
+
155
+ This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.
156
+
157
+ ## Contributing
158
+
159
+ Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
160
+
161
+ ### Development Setup
162
+
163
+ 1. Clone the repository
164
+ 2. Install dependencies: `bun install`
165
+ 3. Run tests: `bun run test`
166
+ 4. Build the project: `bun run build`
167
+
168
+ ### Guidelines
169
+
170
+ - Write tests for new features
171
+ - Follow the existing code style
172
+ - Update documentation for API changes
173
+ - Ensure all tests pass before submitting PR
174
+
175
+ ---
176
+
177
+ Made with ❤️ by the Ooneex team
@@ -0,0 +1,43 @@
1
+ import { ResponseDataType as ResponseDataType2 } from "@ooneex/http-response";
2
+ import { ResponseDataType } from "@ooneex/http-response";
3
+ import { LocaleInfoType } from "@ooneex/translation";
4
+ type RequestDataType = {
5
+ payload?: Record<string, unknown>;
6
+ queries?: Record<string, boolean | number | bigint | string>;
7
+ language?: LocaleInfoType;
8
+ };
9
+ interface ISocket<
10
+ SendData extends RequestDataType = RequestDataType,
11
+ Response extends Record<string, unknown> = Record<string, unknown>
12
+ > {
13
+ close: (code?: number, reason?: string) => void;
14
+ send: (data: SendData) => void;
15
+ onMessage: (handler: (response: ResponseDataType<Response>) => void) => void;
16
+ onOpen: (handler: (event: Event) => void) => void;
17
+ onClose: (handler: (event: CloseEvent) => void) => void;
18
+ onError: (handler: (event: Event, response?: ResponseDataType<Response>) => void) => void;
19
+ }
20
+ declare class Socket<
21
+ SendData extends RequestDataType = RequestDataType,
22
+ Response extends Record<string, unknown> = Record<string, unknown>
23
+ > implements ISocket<SendData, Response> {
24
+ private readonly url;
25
+ private ws;
26
+ private messageHandler?;
27
+ private openHandler?;
28
+ private errorHandler?;
29
+ private closeHandler?;
30
+ private queuedMessages;
31
+ constructor(url: string);
32
+ close(code?: number, reason?: string): void;
33
+ send(data: SendData): void;
34
+ private sendRaw;
35
+ onMessage(handler: (response: ResponseDataType2<Response>) => void): void;
36
+ onOpen(handler: (event: Event) => void): void;
37
+ onClose(handler: (event: CloseEvent) => void): void;
38
+ onError(handler: (event: Event, response?: ResponseDataType2<Response>) => void): void;
39
+ private buildURL;
40
+ private setupEventHandlers;
41
+ private flushQueuedMessages;
42
+ }
43
+ export { Socket, RequestDataType, ISocket };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ class n{url;ws;messageHandler;openHandler;errorHandler;closeHandler;queuedMessages=[];constructor(e){this.url=e;let o=this.buildURL(this.url);this.ws=new WebSocket(o),this.setupEventHandlers()}close(e,o){this.ws.close(e,o)}send(e){let o=JSON.stringify(e);this.sendRaw(o)}sendRaw(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN)this.ws.send(e);else this.queuedMessages.push(e)}onMessage(e){this.messageHandler=e}onOpen(e){this.openHandler=e}onClose(e){this.closeHandler=e}onError(e){this.errorHandler=e}buildURL(e){if(e.startsWith("ws://")||e.startsWith("wss://"))return e;if(e.startsWith("http://"))e=e.replace("http://","ws://");else if(e.startsWith("https://"))e=e.replace("https://","wss://");else if(!e.startsWith("ws://")&&!e.startsWith("wss://"))e=`wss://${e}`;return e}setupEventHandlers(){this.ws.onmessage=(e)=>{if(this.messageHandler){let o=JSON.parse(e.data);if(o.done)this.ws.close();if(o.success){this.messageHandler(o);return}if(this.errorHandler)this.errorHandler(e,o)}},this.ws.onopen=(e)=>{if(this.flushQueuedMessages(),this.openHandler)this.openHandler(e)},this.ws.onerror=(e)=>{if(this.errorHandler)this.errorHandler(e)},this.ws.onclose=(e)=>{if(this.closeHandler)this.closeHandler(e)}}flushQueuedMessages(){while(this.queuedMessages.length>0){let e=this.queuedMessages.shift();if(e!==void 0&&this.ws.readyState===WebSocket.OPEN)this.ws.send(e)}}}export{n as Socket};
2
+
3
+ //# debugId=222449767EFA071D64756E2164756E21
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["src/Socket.ts"],
4
+ "sourcesContent": [
5
+ "import type { ResponseDataType } from \"@ooneex/http-response\";\nimport type { ISocket, RequestDataType } from \"./types\";\n\nexport class Socket<\n SendData extends RequestDataType = RequestDataType,\n Response extends Record<string, unknown> = Record<string, unknown>,\n> implements ISocket<SendData, Response>\n{\n private ws: WebSocket;\n private messageHandler?: (response: ResponseDataType<Response>) => void;\n private openHandler?: (event: Event) => void;\n private errorHandler?: (event: Event, response?: ResponseDataType<Response>) => void;\n private closeHandler?: (event: CloseEvent) => void;\n private queuedMessages: (string | ArrayBufferLike | Blob | ArrayBufferView)[] = [];\n\n constructor(private readonly url: string) {\n const fullURL = this.buildURL(this.url);\n this.ws = new WebSocket(fullURL);\n this.setupEventHandlers();\n }\n\n public close(code?: number, reason?: string): void {\n this.ws.close(code, reason);\n }\n\n public send(data: SendData): void {\n const text = JSON.stringify(data);\n this.sendRaw(text);\n }\n\n private sendRaw(payload: string | ArrayBufferLike | Blob | ArrayBufferView): void {\n if (this.ws && this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(payload);\n } else {\n this.queuedMessages.push(payload);\n }\n }\n\n public onMessage(handler: (response: ResponseDataType<Response>) => void): void {\n this.messageHandler = handler;\n }\n\n public onOpen(handler: (event: Event) => void): void {\n this.openHandler = handler;\n }\n\n public onClose(handler: (event: CloseEvent) => void): void {\n this.closeHandler = handler;\n }\n\n public onError(handler: (event: Event, response?: ResponseDataType<Response>) => void): void {\n this.errorHandler = handler;\n }\n\n private buildURL(url: string): string {\n if (url.startsWith(\"ws://\") || url.startsWith(\"wss://\")) {\n return url;\n }\n\n // Convert HTTP(S) to WebSocket protocol\n if (url.startsWith(\"http://\")) {\n url = url.replace(\"http://\", \"ws://\");\n } else if (url.startsWith(\"https://\")) {\n url = url.replace(\"https://\", \"wss://\");\n } else if (!url.startsWith(\"ws://\") && !url.startsWith(\"wss://\")) {\n url = `wss://${url}`;\n }\n\n return url;\n }\n\n private setupEventHandlers(): void {\n this.ws.onmessage = (event: MessageEvent) => {\n if (this.messageHandler) {\n const data = JSON.parse(event.data) as ResponseDataType<Response>;\n\n if (data.done) {\n this.ws.close();\n }\n\n if (data.success) {\n this.messageHandler(data);\n\n return;\n }\n\n if (this.errorHandler) {\n this.errorHandler(event, data);\n }\n }\n };\n\n this.ws.onopen = (event: Event) => {\n this.flushQueuedMessages();\n if (this.openHandler) {\n this.openHandler(event);\n }\n };\n\n this.ws.onerror = (event: Event) => {\n if (this.errorHandler) {\n this.errorHandler(event);\n }\n };\n\n this.ws.onclose = (event: CloseEvent) => {\n if (this.closeHandler) {\n this.closeHandler(event);\n }\n };\n }\n\n private flushQueuedMessages(): void {\n while (this.queuedMessages.length > 0) {\n const message = this.queuedMessages.shift();\n if (message !== undefined && this.ws.readyState === WebSocket.OPEN) {\n this.ws.send(message);\n }\n }\n }\n}\n"
6
+ ],
7
+ "mappings": "AAGO,MAAM,CAIb,CAQ+B,IAPrB,GACA,eACA,YACA,aACA,aACA,eAAwE,CAAC,EAEjF,WAAW,CAAkB,EAAa,CAAb,WAC3B,IAAM,EAAU,KAAK,SAAS,KAAK,GAAG,EACtC,KAAK,GAAK,IAAI,UAAU,CAAO,EAC/B,KAAK,mBAAmB,EAGnB,KAAK,CAAC,EAAe,EAAuB,CACjD,KAAK,GAAG,MAAM,EAAM,CAAM,EAGrB,IAAI,CAAC,EAAsB,CAChC,IAAM,EAAO,KAAK,UAAU,CAAI,EAChC,KAAK,QAAQ,CAAI,EAGX,OAAO,CAAC,EAAkE,CAChF,GAAI,KAAK,IAAM,KAAK,GAAG,aAAe,UAAU,KAC9C,KAAK,GAAG,KAAK,CAAO,EAEpB,UAAK,eAAe,KAAK,CAAO,EAI7B,SAAS,CAAC,EAA+D,CAC9E,KAAK,eAAiB,EAGjB,MAAM,CAAC,EAAuC,CACnD,KAAK,YAAc,EAGd,OAAO,CAAC,EAA4C,CACzD,KAAK,aAAe,EAGf,OAAO,CAAC,EAA8E,CAC3F,KAAK,aAAe,EAGd,QAAQ,CAAC,EAAqB,CACpC,GAAI,EAAI,WAAW,OAAO,GAAK,EAAI,WAAW,QAAQ,EACpD,OAAO,EAIT,GAAI,EAAI,WAAW,SAAS,EAC1B,EAAM,EAAI,QAAQ,UAAW,OAAO,EAC/B,QAAI,EAAI,WAAW,UAAU,EAClC,EAAM,EAAI,QAAQ,WAAY,QAAQ,EACjC,QAAI,CAAC,EAAI,WAAW,OAAO,GAAK,CAAC,EAAI,WAAW,QAAQ,EAC7D,EAAM,SAAS,IAGjB,OAAO,EAGD,kBAAkB,EAAS,CACjC,KAAK,GAAG,UAAY,CAAC,IAAwB,CAC3C,GAAI,KAAK,eAAgB,CACvB,IAAM,EAAO,KAAK,MAAM,EAAM,IAAI,EAElC,GAAI,EAAK,KACP,KAAK,GAAG,MAAM,EAGhB,GAAI,EAAK,QAAS,CAChB,KAAK,eAAe,CAAI,EAExB,OAGF,GAAI,KAAK,aACP,KAAK,aAAa,EAAO,CAAI,IAKnC,KAAK,GAAG,OAAS,CAAC,IAAiB,CAEjC,GADA,KAAK,oBAAoB,EACrB,KAAK,YACP,KAAK,YAAY,CAAK,GAI1B,KAAK,GAAG,QAAU,CAAC,IAAiB,CAClC,GAAI,KAAK,aACP,KAAK,aAAa,CAAK,GAI3B,KAAK,GAAG,QAAU,CAAC,IAAsB,CACvC,GAAI,KAAK,aACP,KAAK,aAAa,CAAK,GAKrB,mBAAmB,EAAS,CAClC,MAAO,KAAK,eAAe,OAAS,EAAG,CACrC,IAAM,EAAU,KAAK,eAAe,MAAM,EAC1C,GAAI,IAAY,QAAa,KAAK,GAAG,aAAe,UAAU,KAC5D,KAAK,GAAG,KAAK,CAAO,GAI5B",
8
+ "debugId": "222449767EFA071D64756E2164756E21",
9
+ "names": []
10
+ }
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@ooneex/socket-client",
3
+ "description": "WebSocket client for real-time bidirectional communication with automatic reconnection, event handling, and typed message serialization",
4
+ "version": "1.0.0",
5
+ "type": "module",
6
+ "files": [
7
+ "dist",
8
+ "LICENSE",
9
+ "README.md",
10
+ "package.json"
11
+ ],
12
+ "module": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "import": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ }
20
+ },
21
+ "./package.json": "./package.json"
22
+ },
23
+ "license": "MIT",
24
+ "scripts": {
25
+ "test": "bun test tests",
26
+ "build": "bunup",
27
+ "lint": "tsgo --noEmit && bunx biome lint",
28
+ "npm:publish": "bun publish --tolerate-republish --access public"
29
+ },
30
+ "devDependencies": {
31
+ "@ooneex/translation": "0.0.18",
32
+ "@ooneex/http-response": "0.17.0",
33
+ "@ooneex/app-env": "0.0.19"
34
+ },
35
+ "keywords": [
36
+ "bun",
37
+ "ooneex",
38
+ "realtime",
39
+ "socket",
40
+ "typescript",
41
+ "websocket",
42
+ "ws"
43
+ ]
44
+ }