@standard-server/peer
v0.9.2
Published
Message-based adapter for Standard Server: transport-agnostic requests, responses, and streaming over WebSocket, MessagePort, and custom peer transports
Maintainers
Readme
@standard-server/peer
@standard-server/peer adapts message-based transports to the transport-agnostic request and response model defined by Standard Server.
Standard Server provides a unified interface for client-server communication across HTTP and message-based transports. It lets you write handlers and clients against the same request, response, body, and streaming primitives whether the underlying transport is Fetch, Node.js HTTP, WebSocket, MessagePort, or another peer-style channel.
Standard Server ships as a small ecosystem of packages:
| Package | Description |
| --------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| @standard-server/core | The shared contract: types, body parsing rules, validators, and SSE helpers |
| @standard-server/fetch | Fetch API adapter for browsers, workers, and other Fetch-based runtimes |
| @standard-server/node | Node.js HTTP and HTTP/2 adapter |
| @standard-server/fastify | Fastify adapter built on the Node.js adapter |
| @standard-server/aws-lambda | AWS Lambda adapter with response streaming |
| @standard-server/peer | Message-based adapter for WebSocket, MessagePort, and custom transports |
| @standard-server/shared | Internal utilities shared across the ecosystem |
This package is the peer adapter for that model. It converts between Standard Server requests and responses and a structured peer message protocol that can be sent through any transport capable of carrying strings or binary data.
Package overview
The package exposes four groups of helpers:
| Group | Exports | Purpose |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- |
| Peer runtime | ClientPeer, ServerPeer | Send Standard Server requests and responses over a peer transport |
| Message codec | encodePeerMessage(), decodePeerMessage() | Encode peer messages as strings or bytes for transport |
| Stream utilities | toAsyncIteratorObject(), EventStreamTransmitter, HibernationAsyncIteratorClass | Bridge peer messages with Standard Server event-stream semantics |
| Types and validators | PeerMessage, PeerRequestMessage, PeerResponseMessage, PeerCancelMessage, PeerEventStreamMessage, PeerOctetStreamMessage, PeerStreamCancelMessage, ClientPeerSendMessage, ServerPeerSendMessage, isPeerMessage(), isPeerRequestMessage(), isPeerResponseMessage(), isPeerCancelMessage(), isPeerEventStreamMessage(), isPeerOctetStreamMessage(), isPeerStreamCancelMessage(), isClientPeerSendMessage(), isServerPeerSendMessage() | Describe and validate the peer protocol payloads |
Use these helpers when you want Standard Server handlers or clients to run over message-based transports such as MessagePort, WebSocket, Electron IPC, or a custom channel.
Request and response flow
ClientPeer starts a request and waits for a StandardLazyResponse. ServerPeer receives peer messages, reconstructs a StandardLazyRequest, calls your handler, and sends the resulting StandardResponse back over the same transport.
import type { StandardLazyRequest, StandardResponse } from '@standard-server/core'
import {
ClientPeer,
decodePeerMessage,
encodePeerMessage,
isClientPeerSendMessage,
isServerPeerSendMessage,
ServerPeer,
} from '@standard-server/peer'
async function handle(request: StandardLazyRequest): Promise<StandardResponse> {
const body = await request.resolveBody()
return {
status: 200,
headers: { 'content-type': 'application/json' },
body: {
ok: true,
method: request.method,
url: request.url,
received: body,
},
}
}
const { port1, port2 } = new MessageChannel()
const clientPeer = new ClientPeer(async (message) => {
port1.postMessage(await encodePeerMessage(message, { /** options */ }))
})
const serverPeer = new ServerPeer(async (message) => {
port2.postMessage(await encodePeerMessage(message, { /** options */ }))
})
port1.addEventListener('message', async (event) => {
const decoded = decodePeerMessage(event.data, { /** options */ })
if (decoded.matched && isServerPeerSendMessage(decoded.message)) {
await clientPeer.message(decoded.message)
}
})
port2.addEventListener('message', async (event) => {
const decoded = decodePeerMessage(event.data, { /** options */ })
if (decoded.matched && isClientPeerSendMessage(decoded.message)) {
await serverPeer.message(decoded.message, handle)
}
})
port1.start()
port2.start()
const response = await clientPeer.request({
method: 'POST',
url: '/echo',
headers: { 'content-type': 'application/json' },
body: { message: 'hello' },
})
const payload = await response.resolveBody()[!TIP] When encoding or decoding peer messages, you can pass additional options, such as
prefix, to prevent collisions when the same peer is used for multiple purposes.
Body resolution
Unlike the HTTP adapters, resolveBody(hint?) ignores the hint argument in this adapter. HTTP adapters receive the body as a raw byte stream and must decide how to parse it, so a hint can steer that decision. The peer protocol instead encodes the body in structured form at send time: JSON values travel as JSON, binary payloads travel as binary, event and octet streams flow as dedicated stream messages, and markers in the message distinguish the ambiguous cases such as form-data vs. file. By the time a message arrives, there are no raw bytes left to reinterpret — the body always resolves to exactly the representation the sender had, so a hint has nothing to override.
Codec helpers
Use encodePeerMessage() and decodePeerMessage() to bridge between the peer protocol and your underlying transport.
import { decodePeerMessage, encodePeerMessage } from '@standard-server/peer'
const encoded = await encodePeerMessage(
{
id: '1',
kind: 'request',
json: { method: 'GET', url: '/health', headers: {}, body: undefined },
},
{ prefix: 'rpc:' },
)
const decoded = decodePeerMessage(encoded, { prefix: 'rpc:' })
if (decoded.matched) {
console.log(decoded.message.kind)
}Encoding rules:
- Messages without binary payloads are encoded as strings.
- Messages with binary payloads are encoded as
Uint8Arrayvalues containing JSON, a delimiter byte, and the raw binary bytes. - The optional
prefixlets you share the same transport between multiple protocols without collisions.
Learn more
For the project overview and the shared contract this adapter implements, see the core documentation.
Sponsors
Like what we build over at middleapi? You can help keep it going through GitHub Sponsors or Open Collective. Every bit helps! 🚀
Special Sponsors
Organization Sponsors
Sponsors
Backers
With thanks to 36 past sponsors who helped get us here.
License
Distributed under the MIT License. See LICENCE for more information.
