theater-client
Version:
TypeScript client library for Theater actor system TCP protocol
80 lines • 2.17 kB
JavaScript
/**
* Serialization utilities for Theater protocol
*/
/**
* Convert Uint8Array to number array for protocol compatibility
*/
export function uint8ArrayToNumbers(data) {
return Array.from(data);
}
/**
* Convert number array from protocol to Uint8Array
*/
export function numbersToUint8Array(data) {
return new Uint8Array(data);
}
/**
* Encode string to Uint8Array
*/
export function encodeString(text) {
return new TextEncoder().encode(text);
}
/**
* Decode Uint8Array to string
*/
export function decodeString(data) {
return new TextDecoder().decode(data);
}
/**
* Encode object to JSON bytes
*/
export function encodeJson(obj) {
return encodeString(JSON.stringify(obj));
}
/**
* Decode JSON bytes to object
*/
export function decodeJson(data) {
return JSON.parse(decodeString(data));
}
/**
* Create a FragmentingCodec frame for sending data
* Always creates Complete frames for outgoing messages (server handles fragmentation)
*/
export function createFrame(data) {
return {
Complete: uint8ArrayToNumbers(data)
};
}
/**
* Parse a FragmentingCodec frame
* Note: Fragment handling is now done in TheaterConnection.handleFragment()
*/
export function parseFrame(frame) {
if (frame.Complete) {
return numbersToUint8Array(frame.Complete);
}
else if (frame.Fragment) {
// Fragment messages are handled at the connection level
throw new Error('Fragment parsing should be handled by TheaterConnection');
}
else {
throw new Error('Unknown frame type');
}
}
/**
* Serialize a message for sending over TCP
* Includes length prefix as required by Theater protocol
*/
export function serializeMessage(data) {
// Convert to JSON string
const jsonString = JSON.stringify(data);
// Convert to bytes
const messageBytes = Buffer.from(jsonString, 'utf8');
// Create length prefix (4 bytes, big-endian)
const lengthPrefix = Buffer.allocUnsafe(4);
lengthPrefix.writeUInt32BE(messageBytes.length, 0);
// Combine length prefix and message
return Buffer.concat([lengthPrefix, messageBytes]);
}
//# sourceMappingURL=serialization.js.map