2.9 KiB
2.9 KiB
msgpack-decode
Purpose
Implements decodeBinary, the inverse of encodeBinary. Given a MessagePack binary buffer produced by the encoder, it reconstructs the original JavaScript value by first decoding the msgpack wire bytes to an intermediate plain-JS-object representation and then applying the same tag-based reconstruction logic used by deserialize.
The two-phase approach (msgpack decode → tag reconstruct) keeps the decoder code minimal and reuses the same registry lookup path as the JSON decoder.
Features
- Full inverse of
encodeBinary: all built-in and custom registered types are reconstructed UnsupportedTypeErrorthrown on unrecognised__ttags (same strict policy as JSON decoder)- Reuses a single shared
Decoderinstance for zero allocation overhead across calls DeserializeOptionsparameter accepted for API consistency with the JSON codec (signal not yet applied internally, as msgpack decode is synchronous and very fast)
Usage: Basic Example
import { decodeBinary, encodeBinary } from "@suaveplan/serialize";
const original = new Map([["key", new Date()]]);
const bytes = encodeBinary(original);
const restored = decodeBinary(bytes) as Map<string, Date>;
restored instanceof Map; // true
restored.get("key") instanceof Date; // true
Usage: Advanced Example
import { decodeBinary, UnsupportedTypeError } from "@suaveplan/serialize";
async function receiveMessage(bytes: Uint8Array) {
try {
const value = decodeBinary(bytes);
return value;
} catch (err) {
if (err instanceof UnsupportedTypeError) {
// The sender used a type tag unknown to this receiver.
// Either register the type or reject the message.
throw new Error(`Unknown type: ${err.context?.tag}`);
}
throw err;
}
}
API Reference
decodeBinary(bytes: Uint8Array, opts?: DeserializeOptions): unknown
Decode a MessagePack buffer to the original JavaScript value.
Parameters:
bytes— aUint8Arrayproduced byencodeBinaryopts—DeserializeOptions(accepted for API parity; signal not currently applied within this synchronous path)
Returns: the reconstructed JavaScript value.
Throws:
UnsupportedTypeErrorwhen a__ttag has no registered decoderRangeErrororTypeErrorfrom@msgpack/msgpackif the input bytes are malformed
DeserializeOptions
See json-decode.md.
Implementation Notes
- A single shared
Decoderinstance is reused to avoid per-call setup overhead; the decoder is stateless between calls. - The
postDecodefunction is structurally identical to the innerdecodeValueused byjson-decode.ts. Future refactoring could extract it to a shared utility; currently it is kept local to avoid premature abstraction. - The
optsparameter is accepted but currently unused because the msgpack decode step is synchronous and does not lend itself to mid-stream cancellation without a streaming API.