API reference

A four-part surface.

Message exposes two mutable fields, one JSON getter, one native serialization method, and one loader.

Package exports

ImportPurpose
js-messageDefault and named Message exports from the canonical module.
js-message/Message.jsSupported legacy ES-module path; resolves to the same class.
js-message/js-message-vanilla.jsSide-effect entry that assigns globalThis.Message.
js-message/package.jsonPackage metadata for tools that explicitly need it.
import Message, { Message as NamedMessage } from 'js-message';

Message === NamedMessage; // true

Constructor and fields

new Message([input])

Creates an envelope with type === '' and an independent data === {}. When supplied, input is passed through load().

input
Optional JSON string or message object.
returns
A new Message instance.

message.type

Mutable, enumerable message or event discriminator. Direct assignment is intentionally unrestricted.

default
Empty string.
wire key
type

message.data

Mutable, enumerable payload. Direct assignment follows native JSON behavior, including errors for cycles and BigInt.

default
Fresh empty object.
wire key
data

Serialization and loading

message.JSON

Returns JSON.stringify({ type: message.type, data: message.data }). Instance extras are excluded.

returns
JSON string.
throws
Native TypeError for unsupported values such as cycles or BigInt.

message.toJSON()

Returns a new plain { type, data } object. Native JSON.stringify(message) calls this method automatically.

returns
Plain object with exactly two keys.

message.load(input)

Loads a JSON string, a JSON-coercible text value, or an object with own type and data keys. Extra input keys are ignored.

returns
undefined, preserving the legacy contract.
failure
Mutates the instance into an error envelope; complete JSON serialization still requires a JSON-safe preserved response.

Error envelope

{
    type: 'error',
    data: {
        message: 'Invalid JSON response format',
        err: SyntaxError | TypeError,
        response: originalInput
    }
}

The live err remains an Error instance. Its JSON form includes stable name and message fields instead of collapsing to {}. The original response stays by reference, so cycles or BigInt still make native serialization throw.