@api.global/typedsocket Documentation for @api.global/typedsocket readme.md for @api.global/typedsocket A TypeScript library for creating typed WebSocket connections with bi-directional communication support. Extends @api.global/typedrequest to bring type-safe request/response patterns to WebSocket connections. Issue Reporting and Security For reporting bugs, issues, or security vulnerabilities, please visit community.foss.global/. This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a code.foss.global/ account to submit Pull Requests directly. Features 🔒 Full Type Safety - Leverages TypeScript for compile-time checking of all request/response payloads 🔄 Bi-directional Communication - Both server and client can initiate requests 🔌 Auto-reconnect - Client automatically reconnects on connection loss 🏷️ Connection Tagging - Tag and filter connections for targeted messaging 🌐 Browser Compatible - Works in both Node.js and browser environments 🚀 SmartServe Integration - Native support for SmartServe's WebSocket handling Install npm install @api.global/typedsocket Or with pnpm: pnpm add @api.global/typedsocket Usage Prerequisites TypeScript project setup Basic understanding of async/await patterns Familiarity with @api.global/typedrequest concepts Define Your Request Interface First, define the typed request interface that both client and server will use: import * as typedrequestInterfaces from '@api.global/typedrequest-interfaces'; interface IGreetingRequest extends typedrequestInterfaces.implementsTR< typedrequestInterfaces.ITypedRequest, IGreetingRequest > { method: 'greet'; request: { name: string; }; response: { message: string; }; } Server Setup Create a WebSocket server that handles typed requests: import { TypedSocket } from '@api.global/typedsocket'; import * as typedrequest from '@api.global/typedrequest'; // Create the router and add handlers const typedRouter = new typedrequest.TypedRouter(); typedRouter.addTypedHandler( new typedrequest.TypedHandler('greet', async (requestData) => { return { message: `Hello, ${requestData.name}! 👋`, }; }) ); // Start the TypedSocket server (defaults to port 3000) const server = await TypedSocket.createServer(typedRouter); Integration with SmartServe For SmartServe-based applications, use fromSmartServe() for native integration: import { TypedSocket } from '@api.global/typedsocket'; import { SmartServe } from '@push.rocks/smartserve'; import * as typedrequest from '@api.global/typedrequest'; const typedRouter = new typedrequest.TypedRouter(); // Add handlers for client-to-server requests typedRouter.addTypedHandler( new typedrequest.TypedHandler('greet', async (requestData) => { return { message: `Hello, ${requestData.name}!` }; }) ); // Create SmartServe with typedRouter in websocket options const smartServe = new SmartServe({ port: 3000, websocket: { typedRouter, onConnectionOpen: (peer) => { // Tag connections for later filtering peer.tags.add('client'); } } }); await smartServe.start(); // Create TypedSocket bound to SmartServe const typedSocket = TypedSocket.fromSmartServe(smartServe, typedRouter); // Push notifications to tagged clients const clients = await typedSocket.findAllTargetConnectionsByTag('client'); for (const client of clients) { const request = typedSocket.createTypedRequest('notify', client); await request.fire({ message: 'Hello from server!' }); } Note: When using SmartServe, the WebSocket transport is managed by SmartServe. TypedSocket acts as a convenience layer for finding connections and sending server-initiated requests. Client Setup Connect to the WebSocket server from a client: import { TypedSocket } from '@api.global/typedsocket'; import * as typedrequest from '@api.global/typedrequest'; // Create a router for handling server-initiated requests (if needed) const clientRouter = new typedrequest.TypedRouter(); // Connect to the server const client = await TypedSocket.createClient( clientRouter, 'http://localhost:3000' ); Using Window Location (Browser) In browser environments, you can automatically use the current page's origin: const client = await TypedSocket.createClient( clientRouter, TypedSocket.useWindowLocationOriginUrl() ); Sending Requests Client to Server const request = client.createTypedRequest('greet'); const response = await request.fire({ name: 'World', }); console.log(response.message); // "Hello, World! 👋" Server to Client The server can also initiate requests to connected clients: // When only one client is connected, it's automatically selected const request = server.createTypedRequest('greet'); const response = await request.fire({ name: 'Client', }); // For multiple clients, specify the target connection const connection = await server.findTargetConnection(async (conn) => { // Your filter logic here return true; }); const targetedRequest = server.createTypedRequest('greet', connection); Connection Tagging Tag connections for organized, targeted communication: // Client side: add a tag interface IUserTag extends typedrequestInterfaces.ITag { name: 'userRole'; payload: 'admin' | 'user' | 'guest'; } client.addTag('userRole', 'admin'); // Server side: find connections by tag const adminConnections = await server.findAllTargetConnectionsByTag( 'userRole', 'admin' ); // Send to all admins for (const conn of adminConnections) { const request = server.createTypedRequest('notify', conn); await request.fire({ message: 'Admin notification' }); } // Find a single connection const firstAdmin = await server.findTargetConnectionByTag('userRole', 'admin'); Event Handling Subscribe to connection status events: client.eventSubject.subscribe((status) => { console.log('Connection status:', status); }); server.eventSubject.subscribe((status) => { console.log('Server connection event:', status); }); Cleanup Properly close connections when done: // Client await client.stop(); // Server await server.stop(); API Reference TypedSocket Static Methods Method Description createServer(router) Creates a WebSocket server (defaults to port 3000). createClient(router, serverUrl, alias?) Creates a WebSocket client that connects to the specified server URL. fromSmartServe(smartServe, router) Creates a TypedSocket bound to an existing SmartServe instance. useWindowLocationOriginUrl() Returns the current window location origin (browser only). Instance Properties Property Description side Whether this instance is a 'server' or 'client'. typedrouter The TypedRouter instance handling requests. eventSubject RxJS Subject for connection status events. Instance Methods Method Description createTypedRequest(method, targetConnection?) Creates a typed request for the specified method. addTag(name, payload) Adds a tag to the client connection (client-side only). findAllTargetConnections(filterFn) Finds all connections matching the filter (server-side only). findTargetConnection(filterFn) Finds the first connection matching the filter (server-side only). findAllTargetConnectionsByTag(key, payload?) Finds all connections with the specified tag. findTargetConnectionByTag(key, payload?) Finds the first connection with the specified tag. stop() Closes the WebSocket connection. License and Legal Information This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the LICENSE file. Please note: The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file. Trademarks This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH or third parties, and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar. Company Information Task Venture Capital GmbH Registered at District Court Bremen HRB 35230 HB, Germany For any legal inquiries or further information, please contact us via email at hello@task.vc. By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works. changelog.md for @api.global/typedsocket 2026-02-26 - 4.1.2 - fix(ci) update npmextra.json to rename keys, add release registries and add CI entry; remove legacy npmci configuration Renamed top-level key "gitzone" to "@git.zone/cli" and "tsdoc" to "@git.zone/tsdoc" to use scoped configuration keys. Added release configuration under @git.zone/cli with registries [https://verdaccio.lossless.digital, https://registry.npmjs.org] and accessLevel set to public. Removed legacy "npmci" block and introduced an "@ship.zone/szci" section (npmGlobalTools: []). No source code changes; this is a configuration/CI/publishing metadata update. Current package.json version is 4.1.1, recommend a patch bump. 2026-02-26 - 4.1.1 - fix(typedsocket) reject pending requests on disconnect to avoid hanging promises Rejects all pending requests with Error('TypedSocket disconnected') when connection is lost Clears pendingRequests map to prevent memory leaks Preserves existing auto-reconnect scheduling behavior 2025-12-04 - 4.1.0 - feat(typedsocket) Add SmartServe integration, tagging and improved client reconnect/backoff; update deps and tests Add SmartServe integration: new TypedSocket.fromSmartServe(smartServe, typedRouter) with SmartServe connection wrappers and tag compatibility Implement server-side tag handlers and storage (__typedsocket_setTag / __typedsocket_removeTag) with payloads stored under internal TAG_PREFIX Add client improvements: TypedSocket.createClient(...) with autoReconnect, configurable exponential backoff (initialBackoffMs, maxBackoffMs, maxRetries) and connection status observable (statusSubject) Expose client tag API: setTag(name, payload) and removeTag(name) to manage server-side tags Server-side APIs for connection discovery: findAllTargetConnections, findTargetConnection, findAllTargetConnectionsByTag, findTargetConnectionByTag Plugins and internal tooling updated: replace smartsocket exports with smartdelay and smartpromise; export smartpromise and smartdelay for internal use Tests updated to use SmartServe for end-to-end scenarios (server/client message flow, tagging and connection discovery); test script changed to run in verbose mode Bumped dependency versions and adjusted peer dependency for @push.rocks/smartserve to >=1.1.0 2025-12-03 - 4.0.0 - BREAKING CHANGE(TypedSocket.createServer) Remove SmartExpress attachment support from createServer and upgrade smartsocket to ^3.0.0 Bump dependency @push.rocks/smartsocket from ^2.1.0 to ^3.0.0. Remove optional SmartExpress attachment parameter from TypedSocket.createServer and remove the setExternalServer call — createServer now only accepts a TypedRouter and starts its own Smartsocket server. Update README: remove the SmartExpress integration section and adjust the API docs to reflect the new createServer(router) signature. Adjust TypeScript implementation to match the simplified createServer signature and behavior. 2025-12-02 - 3.1.1 - fix(package) Include pnpm packageManager metadata in package.json Added packageManager field to package.json: pnpm@10.18.1+sha512.77a884a165cbba2d8d1c19e3b4880eee6d2fcabd0d879121e282196b80042351d5eb3ca0935fa599da1dc51265cc68816ad2bddd2a2de5ea9fdf92adbec7cd34 No runtime or API changes — metadata-only change 2025-12-02 - 3.1.0 - feat(TypedSocket) Add SmartServe integration to TypedSocket, support SmartServe connections and tagging; update dependencies and docs; remove GitLab CI config Add TypedSocket.fromSmartServe(smartServe, typedRouter) to bind TypedSocket to an existing SmartServe instance for native WebSocket handling. Introduce ISmartServeConnectionWrapper and wrapSmartServePeer to provide tag compatibility between SmartServe (Set) and TypedSocket (id/payload). Tag payloads are stored in peer.data with 'typedsocket_tag' prefix. Server-initiated requests in SmartServe mode use TypedRouter.fireEventInterestMap to correlate requests and responses asynchronously. Extend createTypedRequest, findAllTargetConnections, findTargetConnection, findAllTargetConnectionsByTag and findTargetConnectionByTag to support both Smartsocket and SmartServe backends (via wrappers). eventSubject: Emit a warning and return a new Subject in SmartServe mode (SmartServe lifecycle/events should be consumed via SmartServe hooks). stop(): In SmartServe mode TypedSocket clears internal wrappers but does not stop SmartServe (SmartServe lifecycle is managed externally). Add optional peer dependency @push.rocks/smartserve and expose type-only imports in ts/typedsocket.plugins.ts. Bump several devDependencies and runtime dependencies to newer versions (tsbuild, tsbundle, tsrun, tstest, smartenv, smartserve, smartjson, smartrx, smartsocket, smartstring, smarturl). Update README and readme.hints with SmartServe integration docs and examples. Remove .gitlab-ci.yml (CI configuration removed). 2024-04-18 - 3.0.1 - patch Small patch release. Version bump to 3.0.1. No additional details provided in commits. 2024-04-18 - 3.0.0 - core Major 3.0.0 release with core updates and documentation improvements. Core fixes and updates applied. Documentation updated (commit dated 2024-04-14). General maintenance and polishing for the 3.x line. 2023-08-06 - 2.0.28 - core (BREAKING CHANGE) Breaking change in core introduced in 2.0.28; important compatibility considerations. BREAKING CHANGE(core): update — review integration points before upgrading. This capstone release follows a series of patch releases addressing stability and core behavior. 2022-03-24 - 2.0.0 - core Introduction of the 2.x stable line and subsequent patch series. 2.0.0 initial release of the 2.x series. Follow-up patch releases (2.0.1 through 2.0.27) contain numerous "fix(core): update" changes — ongoing bug fixes, stability improvements, and small core adjustments across 2022–2023. Users upgrading from 1.x should review 2.x changes and the 2.0.28 breaking change above. 2020-12-26 - 1.0.2 - core Initial implemented functionality and the start of 1.x maintenance. fix(core): implement basic functionality — initial usable feature set implemented in 1.0.2. Subsequent 1.0.3 through 1.0.27 releases (2020–2022) included ongoing fixes and minor updates to stabilize the 1.x line.