# @api.global/typedrequest A TypeScript library for making **fully typed request/response cycles** across any transport β€” HTTP, WebSockets, broadcast channels, or custom protocols. Define your API contract once as a TypeScript interface, then use it on both client and server with compile-time safety, automatic routing, virtual streams for real-time data, and built-in traffic monitoring hooks. ## Issue Reporting and Security For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/](https://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/](https://code.foss.global/) account to submit Pull Requests directly. ## Install ```bash pnpm install @api.global/typedrequest ``` ## Usage All examples use ESM imports and TypeScript. ```typescript import { TypedRequest, TypedHandler, TypedRouter, TypedTarget, VirtualStream, TypedResponseError, } from '@api.global/typedrequest'; ``` ### πŸ”‘ Define Your API Contract Every request/response pair is described by a simple interface extending `ITypedRequest`: ```typescript interface IGetUser { method: 'getUser'; request: { userId: string }; response: { username: string; email: string }; } interface IAddNumbers { method: 'add'; request: { a: number; b: number }; response: { result: number }; } ``` The `method` field acts as a discriminator β€” it's what the router uses to match requests to handlers. ### πŸ“‘ Making Typed Requests (Client Side) `TypedRequest` fires a typed request against an HTTP endpoint or a `TypedTarget`: ```typescript // Against an HTTP endpoint const getUser = new TypedRequest('https://api.example.com/rpc', 'getUser'); const user = await getUser.fire({ userId: 'user-123' }); console.log(user.username); // fully typed! // With response caching const cachedUser = await getUser.fire({ userId: 'user-123' }, true); ``` ### πŸ› οΈ Handling Requests (Server Side) `TypedHandler` processes a specific method and returns a typed response: ```typescript const addHandler = new TypedHandler('add', async (req) => { return { result: req.a + req.b }; }); ``` The second argument to the handler function is an optional `TypedTools` instance that gives access to guard validation and transport-layer context: ```typescript const secureHandler = new TypedHandler('getUser', async (req, tools) => { // Access transport-layer context (e.g., authenticated user info) const peer = tools.localData.peer; // Validate with guards await tools.passGuards([myAuthGuard], req); return { username: 'Alice', email: 'alice@example.com' }; }); ``` ### 🚦 Routing Requests `TypedRouter` dispatches incoming requests to the correct handler based on the `method` field: ```typescript const router = new TypedRouter(); router.addTypedHandler(addHandler); router.addTypedHandler(secureHandler); // Route an incoming request object const response = await router.routeAndAddResponse(incomingTypedRequest); ``` Routers are **composable** β€” you can nest them to build modular API architectures: ```typescript const coreRouter = new TypedRouter(); const authRouter = new TypedRouter(); // Each sub-router manages its own handlers coreRouter.addTypedHandler(addHandler); authRouter.addTypedHandler(secureHandler); // Link them together β€” requests flow through the entire chain const mainRouter = new TypedRouter(); mainRouter.addTypedRouter(coreRouter); mainRouter.addTypedRouter(authRouter); ``` ### 🎯 Custom Targets with TypedTarget For non-HTTP transports (WebSockets, broadcast channels, IPC), use `TypedTarget` with a custom post function: ```typescript // Synchronous target (post returns the response directly) const target = new TypedTarget({ postMethod: async (payload) => { // Send via your custom transport and return the response return await myWebSocket.sendAndWait(payload); }, }); const request = new TypedRequest(target, 'getUser'); const user = await request.fire({ userId: 'user-123' }); ``` For **async targets** where the response arrives separately (e.g., WebSocket push), pair a `TypedTarget` with a `TypedRouter`: ```typescript const router = new TypedRouter(); const asyncTarget = new TypedTarget({ postMethodWithTypedRouter: async (payload) => { // Fire-and-forget β€” response will arrive via router mySocket.send(JSON.stringify(payload)); }, typedRouterRef: router, }); // When the response arrives later, route it back: mySocket.onMessage((data) => { router.routeAndAddResponse(JSON.parse(data)); }); ``` ### 🌊 Virtual Streams `VirtualStream` enables **bidirectional binary streaming** over any transport that supports typed requests. Data is automatically chunked with backpressure control: ```typescript import type { IVirtualStream } from '@api.global/typedrequest-interfaces'; // Define a streaming endpoint interface IFileUpload { method: 'uploadFile'; request: { filename: string; dataStream: IVirtualStream }; response: { bytesReceived: number }; } // Client side: create and send a stream const uploadStream = new VirtualStream(); const upload = new TypedRequest('https://api.example.com/rpc', 'uploadFile'); const responsePromise = upload.fire({ filename: 'data.bin', dataStream: uploadStream, }); // Send data through the stream await uploadStream.sendData(new TextEncoder().encode('Hello, World!')); await uploadStream.close(); const result = await responsePromise; console.log(result.bytesReceived); ``` ```typescript // Server side: receive and process the stream const uploadHandler = new TypedHandler('uploadFile', async (req) => { let total = 0; // Read chunks from the stream const chunk = await req.dataStream.fetchData(); total += chunk.byteLength; return { bytesReceived: total }; }); ``` VirtualStreams also integrate with the Web Streams API: ```typescript // Pipe a ReadableStream into a VirtualStream await virtualStream.readFromWebstream(readableStream); // Pipe a VirtualStream into a WritableStream await virtualStream.writeToWebstream(writableStream); ``` ### ⚠️ Error Handling Throw `TypedResponseError` inside handlers to send structured errors back to the caller: ```typescript const handler = new TypedHandler('getUser', async (req) => { const user = await db.findUser(req.userId); if (!user) { throw new TypedResponseError('User not found', { userId: req.userId }); } return { username: user.name, email: user.email }; }); ``` On the client side, `TypedResponseError` is thrown when the server responds with an error: ```typescript try { await getUser.fire({ userId: 'nonexistent' }); } catch (err) { if (err instanceof TypedResponseError) { console.error(err.errorText); // 'User not found' console.error(err.errorData); // { userId: 'nonexistent' } } } ``` ### πŸ“Š Traffic Monitoring Hooks Monitor all TypedRequest traffic with global or per-router hooks: ```typescript // Global hooks β€” apply to ALL routers and requests across bundles TypedRouter.setGlobalHooks({ onOutgoingRequest: (entry) => { console.log(`β†’ ${entry.method} [${entry.correlationId}]`); }, onIncomingResponse: (entry) => { console.log(`← ${entry.method} took ${entry.durationMs}ms`); }, onIncomingRequest: (entry) => { console.log(`β‡’ handling ${entry.method}`); }, onOutgoingResponse: (entry) => { if (entry.error) console.error(`⇐ ${entry.method} error: ${entry.error}`); }, }); // Per-router hooks router.setHooks({ onIncomingRequest: (entry) => metrics.trackRequest(entry), }); // Skip hooks for internal requests (e.g., health checks) const internalReq = new TypedRequest(target, 'healthCheck'); internalReq.skipHooks = true; ``` ### πŸ—οΈ Architecture Overview ``` β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ TypedRequest │──────▢│ HTTP / WS / │──────▢│ TypedRouter β”‚ β”‚ (client) β”‚ β”‚ TypedTarget β”‚ β”‚ (server) β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β” β”‚ TypedHandler β”‚ β”‚ (your logic) β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ ``` - **TypedRequest** β€” fires typed requests against a URL or TypedTarget - **TypedTarget** β€” abstracts the transport layer (HTTP, WebSocket, custom) - **TypedRouter** β€” routes incoming requests to the correct handler; composable via `addTypedRouter()` - **TypedHandler** β€” processes a single method and returns a typed response - **VirtualStream** β€” bidirectional binary streaming with backpressure over any supported transport - **TypedResponseError** β€” structured error propagation - **TypedTools** β€” guard validation and transport-layer context in handlers ## 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](./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.