initial Commit
This commit is contained in:
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
/node_modules
|
||||||
|
/dist
|
||||||
1046
package-lock.json
generated
Normal file
1046
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
26
package.json
Normal file
26
package.json
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"name": "minimal-sync",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "",
|
||||||
|
"main": "index.js",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"start": "tsx src/index.ts",
|
||||||
|
"test": "echo \"Error: no test specified\" && exit 1"
|
||||||
|
},
|
||||||
|
"keywords": [],
|
||||||
|
"author": "",
|
||||||
|
"license": "ISC",
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^26.1.1",
|
||||||
|
"tsx": "^4.23.1",
|
||||||
|
"typescript": "^7.0.2"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@bitauth/libauth": "^3.0.0",
|
||||||
|
"@xo-cash/crypto": "^0.0.2",
|
||||||
|
"@xo-cash/primitives": "^0.0.2",
|
||||||
|
"@xo-cash/utils": "file:../utils",
|
||||||
|
"zod": "^4.4.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
54
src/index.ts
Normal file
54
src/index.ts
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
import { PrivateKey } from "@xo-cash/primitives";
|
||||||
|
|
||||||
|
import { SSEClient } from "./sse/client.js";
|
||||||
|
import { WsClient } from './ws/client.js';
|
||||||
|
|
||||||
|
|
||||||
|
const testSSE = async () => {
|
||||||
|
const privateKey = PrivateKey.fromString('c440ce6ac5b63ae7bc4af9891b80b7a88ccdeebba5e43246885e9ec56f912ac2');
|
||||||
|
const client = new SSEClient('https://v2.sync.xo.harvmaster.com', privateKey, {
|
||||||
|
onMessage: (message) => {
|
||||||
|
console.log(message);
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error(error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await client.subscribe('test');
|
||||||
|
|
||||||
|
// await client.connect();
|
||||||
|
|
||||||
|
await client.write('test', {'message': 'Hello, world! this is the minimal sync client using SSE'});
|
||||||
|
|
||||||
|
const data = await client.read('test');
|
||||||
|
console.log(data);
|
||||||
|
|
||||||
|
// await client.disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
const testWS = async () => {
|
||||||
|
const privateKey = PrivateKey.fromString('c440ce6ac5b63ae7bc4af9891b80b7a88ccdeebba5e43246885e9ec56f912ac2');
|
||||||
|
const client = new WsClient('wss://v2.sync.xo.harvmaster.com', privateKey, {
|
||||||
|
onMessage: (message) => {
|
||||||
|
console.log(message);
|
||||||
|
},
|
||||||
|
onError: (error) => {
|
||||||
|
console.error(error);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await client.connect();
|
||||||
|
await client.subscribe('test');
|
||||||
|
|
||||||
|
await client.write('test', {'message': 'Hello, world! this is the minimal sync client using WS'});
|
||||||
|
|
||||||
|
const data = await client.read('test');
|
||||||
|
console.log(data);
|
||||||
|
|
||||||
|
// await client.unsubscribe('test');
|
||||||
|
// await client.disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
// testSSE();
|
||||||
|
testWS();
|
||||||
243
src/sse/client.ts
Normal file
243
src/sse/client.ts
Normal file
@@ -0,0 +1,243 @@
|
|||||||
|
import { SSESession, toExtendedJson } from '@xo-cash/utils';
|
||||||
|
import { PrivateKey } from '@xo-cash/primitives'
|
||||||
|
import { binToHex, flattenBinArray, secp256k1, sha256 } from '@bitauth/libauth'
|
||||||
|
import type { WriteRequest } from '../types.js';
|
||||||
|
|
||||||
|
export type AuthenticatedRequestHeaders = {
|
||||||
|
'X-Public-Key': string;
|
||||||
|
'X-Timestamp': string;
|
||||||
|
'X-Signature': string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SSEClientOptions = {
|
||||||
|
onMessage: (message: string) => void;
|
||||||
|
onError: (error: Error) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export class SSEClient {
|
||||||
|
private sseSession: SSESession;
|
||||||
|
private readonly subscriptions: Set<string> = new Set();
|
||||||
|
private readonly messageListeners = new Set<(message: string) => void>();
|
||||||
|
private readonly errorListeners = new Set<(error: Error) => void>();
|
||||||
|
|
||||||
|
private privateKey: PrivateKey;
|
||||||
|
private textEncoder = new TextEncoder();
|
||||||
|
|
||||||
|
private get subscriptionUrl() {
|
||||||
|
return `${this.url}/data/subscribe`;
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(private readonly url: string, privateKey: PrivateKey, options: Partial<SSEClientOptions> = {}) {
|
||||||
|
this.privateKey = privateKey;
|
||||||
|
this.sseSession = new SSESession(`${this.url}/data/subscribe`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ resourceId: [ ...this.subscriptions ] }),
|
||||||
|
});
|
||||||
|
this.messageListeners.add(options.onMessage ?? (() => {}));
|
||||||
|
this.errorListeners.add(options.onError ?? (() => {}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async connect() {
|
||||||
|
await this.sseSession.connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
async disconnect() {
|
||||||
|
await this.sseSession.disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
async reconnect() {
|
||||||
|
// Disconnect the current session
|
||||||
|
await this.sseSession.disconnect();
|
||||||
|
this.sseSession.off('message');
|
||||||
|
this.sseSession.off('error');
|
||||||
|
|
||||||
|
// Build the request body
|
||||||
|
const body = toExtendedJson({ resourceId: [ ...this.subscriptions ] });
|
||||||
|
|
||||||
|
// Re-create the session with the additional resource ID in the subscription list
|
||||||
|
this.sseSession = new SSESession(this.subscriptionUrl, {
|
||||||
|
onRequest: async (request) => {
|
||||||
|
// Create the request authentication headers
|
||||||
|
const requestBody = toExtendedJson(request.body);
|
||||||
|
const authHeaders = SSEClient.authenticateRequest(this.privateKey, requestBody);
|
||||||
|
|
||||||
|
// Initialize the request headers if they don't exist
|
||||||
|
request.headers ??= {};
|
||||||
|
|
||||||
|
// Add the authentication headers to the request
|
||||||
|
request.headers = {
|
||||||
|
...request.headers,
|
||||||
|
...authHeaders,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return the request with the authentication headers
|
||||||
|
return request;
|
||||||
|
},
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: body,
|
||||||
|
method: 'POST',
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create a listener to re-emit the messages
|
||||||
|
this.sseSession.on('message', (message) => {
|
||||||
|
for (const listener of this.messageListeners) {
|
||||||
|
listener(message);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create a listener to re-emit the errors
|
||||||
|
this.sseSession.on('error', (error) => {
|
||||||
|
for (const listener of this.errorListeners) {
|
||||||
|
listener(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Connect to the server
|
||||||
|
await this.connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send a POST /data/write request to the server
|
||||||
|
async write(resourceId: string, value: Record<string, unknown>) {
|
||||||
|
const url = `${this.url}/data/write`;
|
||||||
|
|
||||||
|
const valueStr = toExtendedJson(value);
|
||||||
|
const valueBytes = this.textEncoder.encode(valueStr);
|
||||||
|
const resource = SSEClient.makeWriteRequest(this.privateKey, resourceId, valueBytes);
|
||||||
|
|
||||||
|
const bodyStr = toExtendedJson({ resources: [resource] });
|
||||||
|
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
|
||||||
|
// Headers arent required unless we have payment service running
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
// ...SSEClient.authenticateRequest(this.privateKey, bodyStr),
|
||||||
|
},
|
||||||
|
|
||||||
|
body: bodyStr,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Failed to write resource: ${res.statusText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Send a POST /data/read request to the server
|
||||||
|
async read(resourceId: string) {
|
||||||
|
const url = `${this.url}/data/get`;
|
||||||
|
const body = toExtendedJson({ resourceId: [ resourceId ] });
|
||||||
|
|
||||||
|
const res = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
// ...SSEClient.authenticateRequest(this.privateKey, body),
|
||||||
|
},
|
||||||
|
body,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Failed to read resource: ${res.statusText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Destroy the current SSE Session, then re-create it with the additional resource ID in the subscription list
|
||||||
|
async subscribe(resourceId: string) {
|
||||||
|
this.subscriptions.add(resourceId);
|
||||||
|
|
||||||
|
await this.reconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Destroy the current SSE Session, then re-create it with the additional resource ID in the subscription list
|
||||||
|
async unsubscribe(resourceId: string) {
|
||||||
|
this.subscriptions.delete(resourceId);
|
||||||
|
|
||||||
|
await this.reconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Derives a resource-scoped private key from the root key and resource id.
|
||||||
|
*/
|
||||||
|
private static deriveResourcePrivateKey(privateKey: Uint8Array, resourceId: string): Uint8Array {
|
||||||
|
const resourceIdBytes = new TextEncoder().encode(resourceId);
|
||||||
|
return sha256.hash(flattenBinArray([ privateKey, resourceIdBytes ]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Signs a canonical payload string and returns the compressed public key and DER signature.
|
||||||
|
*/
|
||||||
|
private static signPayload(
|
||||||
|
privateKey: Uint8Array,
|
||||||
|
payload: string,
|
||||||
|
): { publicKey: string; signature: string } {
|
||||||
|
const payloadHash = sha256.hash(new TextEncoder().encode(payload));
|
||||||
|
|
||||||
|
const publicKey = secp256k1.derivePublicKeyCompressed(privateKey);
|
||||||
|
if (typeof publicKey === 'string') {
|
||||||
|
throw new Error('Failed to derive public key');
|
||||||
|
}
|
||||||
|
|
||||||
|
const signature = secp256k1.signMessageHashDER(privateKey, payloadHash);
|
||||||
|
if (typeof signature === 'string') {
|
||||||
|
throw new Error('Failed to sign message');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
publicKey: binToHex(publicKey),
|
||||||
|
signature: binToHex(signature),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds a signed write resource for POST /data/write.
|
||||||
|
*
|
||||||
|
* The signing key is derived per resource via sha256(privateKey + resourceId).
|
||||||
|
* The signature covers only the resource value, not the full request body.
|
||||||
|
*/
|
||||||
|
static makeWriteRequest(
|
||||||
|
privateKey: PrivateKey,
|
||||||
|
resourceId: string,
|
||||||
|
value: Uint8Array,
|
||||||
|
): WriteRequest {
|
||||||
|
const derivedKey = SSEClient.deriveResourcePrivateKey(privateKey.toBytes(), resourceId);
|
||||||
|
const timestamp = Date.now();
|
||||||
|
const payload = `${timestamp}${resourceId}${toExtendedJson(value)}`;
|
||||||
|
const { publicKey, signature } = SSEClient.signPayload(derivedKey, payload);
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: resourceId,
|
||||||
|
value,
|
||||||
|
publicKey,
|
||||||
|
timestamp,
|
||||||
|
signature,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Signs an entire request body for transport-layer authentication headers.
|
||||||
|
*
|
||||||
|
* Unlike {@link makeWriteRequest}, this uses the root private key and signs
|
||||||
|
* the full serialized body rather than an individual resource value.
|
||||||
|
*/
|
||||||
|
static authenticateRequest(
|
||||||
|
privateKey: PrivateKey,
|
||||||
|
body: string,
|
||||||
|
): AuthenticatedRequestHeaders {
|
||||||
|
const timestamp = Date.now();
|
||||||
|
const payload = `${timestamp}${body}`;
|
||||||
|
const { publicKey, signature } = SSEClient.signPayload(privateKey.toBytes(), payload);
|
||||||
|
|
||||||
|
return {
|
||||||
|
'X-Public-Key': publicKey,
|
||||||
|
'X-Timestamp': timestamp.toString(),
|
||||||
|
'X-Signature': signature,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
1
src/sse/index.ts
Normal file
1
src/sse/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './client.js';
|
||||||
11
src/types.ts
Normal file
11
src/types.ts
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
export type WriteRequest = {
|
||||||
|
id: string;
|
||||||
|
publicKey: string;
|
||||||
|
timestamp: number;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* sha256(timestamp + id + toExtendedJson(value))
|
||||||
|
*/
|
||||||
|
signature: string;
|
||||||
|
value: unknown;
|
||||||
|
};
|
||||||
257
src/ws/client.ts
Normal file
257
src/ws/client.ts
Normal file
@@ -0,0 +1,257 @@
|
|||||||
|
import { fromExtendedJson, toExtendedJson } from '@xo-cash/utils';
|
||||||
|
import type { PrivateKey } from '@xo-cash/primitives';
|
||||||
|
|
||||||
|
import { SSEClient } from '../sse/client.js';
|
||||||
|
import { WsMessageSchema, WsSuccessResponseSchema, WsErrorResponseSchema, type WsMessage } from './types.js';
|
||||||
|
|
||||||
|
/** A request sent over the sync server's WebSocket connection. */
|
||||||
|
type WsRequest = {
|
||||||
|
id?: string;
|
||||||
|
path: string;
|
||||||
|
body?: unknown;
|
||||||
|
};
|
||||||
|
|
||||||
|
type PendingRequest = {
|
||||||
|
resolve: (body: unknown) => void;
|
||||||
|
reject: (error: Error) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type WsClientOptions = {
|
||||||
|
/** Called for server-pushed events and uncorrelated server errors. */
|
||||||
|
onMessage: (message: WsMessage) => void;
|
||||||
|
|
||||||
|
/** Called for transport errors and malformed server messages. */
|
||||||
|
onError: (error: Error) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minimal WebSocket client for the XO sync server.
|
||||||
|
*
|
||||||
|
* This class intentionally owns only the basic WebSocket protocol:
|
||||||
|
*
|
||||||
|
* - one connection is opened at `/ws`;
|
||||||
|
* - request IDs correlate concurrent read/write/unsubscribe calls;
|
||||||
|
* - subscriptions stay on that connection and receive pushed events; and
|
||||||
|
* - a dropped connection fails pending requests but is not reconnected.
|
||||||
|
*
|
||||||
|
* A production client would normally wrap this class with retry, heartbeat,
|
||||||
|
* resubscription, and request-timeout behavior. Those concerns are omitted
|
||||||
|
* here to keep the transport demo easy to follow.
|
||||||
|
*/
|
||||||
|
export class WsClient {
|
||||||
|
private socket: WebSocket | undefined;
|
||||||
|
private readonly pendingRequests = new Map<string, PendingRequest>();
|
||||||
|
private readonly messageListeners = new Set<(message: WsMessage) => void>();
|
||||||
|
private readonly errorListeners = new Set<(error: Error) => void>();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly url: string,
|
||||||
|
private readonly privateKey: PrivateKey,
|
||||||
|
options: Partial<WsClientOptions> = {},
|
||||||
|
) {
|
||||||
|
this.messageListeners.add(options.onMessage ?? (() => {}));
|
||||||
|
this.errorListeners.add(options.onError ?? (() => {}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Open the socket and resolve once the WebSocket handshake completes. */
|
||||||
|
async connect(): Promise<void> {
|
||||||
|
if (this.socket?.readyState === WebSocket.OPEN) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await new Promise<void>((resolve, reject) => {
|
||||||
|
const socket = new WebSocket(WsClient.httpToWsUrl(this.url));
|
||||||
|
this.socket = socket;
|
||||||
|
|
||||||
|
socket.onopen = () => resolve();
|
||||||
|
|
||||||
|
socket.onmessage = (event) => {
|
||||||
|
this.handleMessage(String(event.data));
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.onerror = () => {
|
||||||
|
const error = new Error('WebSocket connection failed');
|
||||||
|
this.emitError(error);
|
||||||
|
reject(error);
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.onclose = () => {
|
||||||
|
if (this.socket === socket) {
|
||||||
|
this.socket = undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.rejectPendingRequests(new Error('WebSocket connection closed'));
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Close the socket.
|
||||||
|
*
|
||||||
|
* Closing a WebSocket automatically removes all of its server-side topics,
|
||||||
|
* so disconnect does not need to send an unsubscribe request first.
|
||||||
|
*/
|
||||||
|
async disconnect(): Promise<void> {
|
||||||
|
const socket = this.socket;
|
||||||
|
this.socket = undefined;
|
||||||
|
|
||||||
|
this.rejectPendingRequests(new Error('WebSocket client disconnected'));
|
||||||
|
|
||||||
|
if (!socket || socket.readyState === WebSocket.CLOSED) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for `close` so callers know the underlying connection is gone.
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
socket.onclose = () => resolve();
|
||||||
|
socket.close();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Read every stored instance of one resource. */
|
||||||
|
async read(resourceId: string): Promise<unknown> {
|
||||||
|
return this.request('/data/get', { resourceId: [resourceId] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sign and write one resource, using the same wire format as the SSE client.
|
||||||
|
*/
|
||||||
|
async write(resourceId: string, value: Record<string, unknown>): Promise<unknown> {
|
||||||
|
const valueBytes = new TextEncoder().encode(toExtendedJson(value));
|
||||||
|
const resource = SSEClient.makeWriteRequest(
|
||||||
|
this.privateKey,
|
||||||
|
resourceId,
|
||||||
|
valueBytes,
|
||||||
|
);
|
||||||
|
|
||||||
|
return this.request('/data/write', { resources: [resource] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register one resource topic on the current connection.
|
||||||
|
*
|
||||||
|
* The subscribe route is intentionally long-running and therefore does not
|
||||||
|
* send an acknowledgement. This method resolves after the request frame has
|
||||||
|
* been handed to the socket; future updates arrive through `onMessage`.
|
||||||
|
*/
|
||||||
|
async subscribe(resourceId: string): Promise<void> {
|
||||||
|
this.send({
|
||||||
|
path: '/data/subscribe',
|
||||||
|
body: { resourceId: [resourceId] },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove one resource topic without closing the shared connection. */
|
||||||
|
async unsubscribe(resourceId: string): Promise<unknown> {
|
||||||
|
return this.request('/data/unsubscribe', { resourceId: [resourceId] });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Send a request and wait for the response carrying the same ID. */
|
||||||
|
private async request(path: string, body?: unknown): Promise<unknown> {
|
||||||
|
const id = crypto.randomUUID();
|
||||||
|
|
||||||
|
const response = new Promise<unknown>((resolve, reject) => {
|
||||||
|
this.pendingRequests.set(id, { resolve, reject });
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.send({ id, path, body });
|
||||||
|
} catch (error) {
|
||||||
|
// Avoid leaving a promise in the map when the socket was not open.
|
||||||
|
this.pendingRequests.delete(id);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Encode one complete request envelope using the shared Extended JSON codec. */
|
||||||
|
private send(request: WsRequest): void {
|
||||||
|
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
|
||||||
|
throw new Error('WebSocket is not connected');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.socket.send(toExtendedJson(request));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Decode and route one frame received from the sync server. */
|
||||||
|
private handleMessage(raw: string): void {
|
||||||
|
const { success, data: message } = WsMessageSchema.safeParse(fromExtendedJson(raw));
|
||||||
|
if (!success) {
|
||||||
|
this.emitError(new Error('Invalid WebSocket message'));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Only response/error messages with an outstanding ID are RPC replies.
|
||||||
|
// Application events are left for message listeners, even if they have IDs.
|
||||||
|
const pending = message.id ? this.pendingRequests.get(message.id) : undefined;
|
||||||
|
|
||||||
|
// If the message has no outstanding ID, it is a subscription event so we will just notify the listeners
|
||||||
|
if (!pending) {
|
||||||
|
for (const listener of this.messageListeners) {
|
||||||
|
listener(message);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete the pending request
|
||||||
|
this.pendingRequests.delete(message.id!);
|
||||||
|
|
||||||
|
// If the message is an error, reject the pending request
|
||||||
|
if (message.type === 'error') {
|
||||||
|
const error = WsErrorResponseSchema.parse(message);
|
||||||
|
pending.reject(new Error(`${error.error} (${error.statusCode})`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the message is a response, resolve the pending request
|
||||||
|
if (message.type === 'response') {
|
||||||
|
const response = WsSuccessResponseSchema.parse(message);
|
||||||
|
|
||||||
|
// If the response is not successful, reject the pending request
|
||||||
|
if (response.statusCode < 200 || response.statusCode >= 300) {
|
||||||
|
pending.reject(new Error(`Request failed (${response.statusCode})`));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the response is successful, resolve the pending request
|
||||||
|
pending.resolve(response.body);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper to emit an error to all error listeners
|
||||||
|
private emitError(error: Error): void {
|
||||||
|
for (const listener of this.errorListeners) {
|
||||||
|
listener(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper for when the client disconnects
|
||||||
|
private rejectPendingRequests(error: Error): void {
|
||||||
|
for (const pending of this.pendingRequests.values()) {
|
||||||
|
pending.reject(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.pendingRequests.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper to convert an HTTP URL to a WebSocket URL
|
||||||
|
static httpToWsUrl(httpUrl: string): string {
|
||||||
|
const url = new URL(httpUrl);
|
||||||
|
|
||||||
|
if (url.protocol === 'http:') {
|
||||||
|
url.protocol = 'ws:';
|
||||||
|
} else if (url.protocol === 'https:') {
|
||||||
|
url.protocol = 'wss:';
|
||||||
|
} else if (url.protocol !== 'ws:' && url.protocol !== 'wss:') {
|
||||||
|
throw new Error(`Unsupported sync server protocol: ${url.protocol}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The constructor accepts either the server root or the complete `/ws` URL.
|
||||||
|
const pathname = url.pathname.replace(/\/+$/, '');
|
||||||
|
url.pathname = pathname.endsWith('/ws') ? pathname : `${pathname}/ws`;
|
||||||
|
|
||||||
|
return url.toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
1
src/ws/index.ts
Normal file
1
src/ws/index.ts
Normal file
@@ -0,0 +1 @@
|
|||||||
|
export * from './client.js';
|
||||||
40
src/ws/types.ts
Normal file
40
src/ws/types.ts
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
/** A normal, correlated reply to a WebSocket request. */
|
||||||
|
export const WsSuccessResponseSchema = z.object({
|
||||||
|
id: z.string().optional(),
|
||||||
|
type: z.literal('response'),
|
||||||
|
statusCode: z.number(),
|
||||||
|
body: z.unknown(),
|
||||||
|
});
|
||||||
|
export type WsSuccessResponse = z.infer<typeof WsSuccessResponseSchema>;
|
||||||
|
|
||||||
|
/** A public error returned by the server for one request. */
|
||||||
|
export const WsErrorResponseSchema = z.object({
|
||||||
|
id: z.string().optional(),
|
||||||
|
type: z.literal('error'),
|
||||||
|
statusCode: z.number(),
|
||||||
|
error: z.string(),
|
||||||
|
details: z.unknown().optional(),
|
||||||
|
});
|
||||||
|
export type WsErrorResponse = z.infer<typeof WsErrorResponseSchema>;
|
||||||
|
|
||||||
|
export const WsResponseSchema = z.discriminatedUnion('type', [WsSuccessResponseSchema, WsErrorResponseSchema]);
|
||||||
|
export type WsResponse = z.infer<typeof WsResponseSchema>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A server-pushed application event.
|
||||||
|
*
|
||||||
|
* Sync resource changes currently use the type `instance-changed`, but the
|
||||||
|
* client deliberately leaves `type` open so this demo does not need updating
|
||||||
|
* whenever the server adds another event.
|
||||||
|
*/
|
||||||
|
export const WsEventSchema = z.object({
|
||||||
|
id: z.string().optional(),
|
||||||
|
type: z.string(),
|
||||||
|
data: z.unknown(),
|
||||||
|
});
|
||||||
|
export type WsEvent = z.infer<typeof WsEventSchema>;
|
||||||
|
|
||||||
|
export const WsMessageSchema = z.union([WsResponseSchema, WsEventSchema]);
|
||||||
|
export type WsMessage = z.infer<typeof WsMessageSchema>;
|
||||||
32
tsconfig.json
Normal file
32
tsconfig.json
Normal file
@@ -0,0 +1,32 @@
|
|||||||
|
{
|
||||||
|
// Visit https://aka.ms/tsconfig to read more about this file
|
||||||
|
"compilerOptions": {
|
||||||
|
// File Layout
|
||||||
|
"rootDir": "./src",
|
||||||
|
"outDir": "./dist",
|
||||||
|
|
||||||
|
// Environment Settings
|
||||||
|
// See also https://aka.ms/tsconfig/module
|
||||||
|
"module": "nodenext",
|
||||||
|
"target": "esnext",
|
||||||
|
"types": ["node"],
|
||||||
|
|
||||||
|
// Other Outputs
|
||||||
|
"sourceMap": true,
|
||||||
|
"declaration": true,
|
||||||
|
"declarationMap": true,
|
||||||
|
|
||||||
|
// Stricter Typechecking Options
|
||||||
|
"noUncheckedIndexedAccess": true,
|
||||||
|
"exactOptionalPropertyTypes": true,
|
||||||
|
|
||||||
|
// Recommended Options
|
||||||
|
"strict": true,
|
||||||
|
"jsx": "react-jsx",
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"isolatedModules": true,
|
||||||
|
"noUncheckedSideEffectImports": true,
|
||||||
|
"moduleDetection": "force",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user