npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@jucie-engine/message

v1.0.5

Published

Message bus system with event registry, channels, and subscriptions

Readme

Message Extension

A robust message passing system for the Jucie engine that enables typed, reliable communication between different parts of an application using Web Workers' MessageChannel API.

Overview

The Message extension provides a MessageBus (primary/central hub) and Channel (secondary/client) architecture for inter-process communication. It supports typed events, message routing, subscription management, and error handling.

Architecture

┌─────────────────┐    MessageChannel    ┌─────────────────┐
│   MessageBus    │◄────────────────────►│     Channel     │
│   (Primary)     │                      │   (Secondary)   │
│                 │                      │                 │
│ • Manages ports │                      │ • Connects to   │
│ • Routes msgs   │                      │   MessageBus    │
│ • Handles subs  │                      │ • Publishes     │
│ • Validates     │                      │ • Subscribes    │
└─────────────────┘                      └─────────────────┘

Key Components

  • MessageBus: Central message router that manages multiple channels and routes messages between them
  • Channel: Client that connects to MessageBus and can publish/subscribe to typed events
  • Port: Low-level communication layer handling MessageChannel handshaking and message transport
  • EventRegistry: Manages event schemas, validation, and symbol-to-string conversion

Installation

import { Engine } from '@jucie-engine/core';
import { MessageBus, Channel } from '@jucie-engine/message';

const engine = Engine.create()
  .install(MessageBus.configure({ 
    mode: 'development',
    schemas: [userEvents, systemEvents] 
  }))
  .install(Channel.configure());

Event Schema Definition

Define typed events using the defineEvents function:

import { defineEvents } from '@brickworks/message';

const userEvents = defineEvents('user', () => ({
  login: ['String', 'String'], // username, password
  logout: ['String'], // username
  profile: { 
    update: ['Object'], 
    delete: ['String'] 
  }
}));

const systemEvents = defineEvents('system', () => ({
  ready: '*', // wildcard - accepts any payload
  error: ['String', 'Object'],
  config: null // no payload validation
}));

Schema Types

  • Array: ['String', 'Object'] - Validates argument count and types
  • Wildcard: '*' - Accepts any payload
  • Null: null - No payload validation
  • Nested: Objects create namespaced events

Usage

Basic Setup

// MessageBus (Primary) - typically on main thread
const messageBusEngine = Engine.create()
  .install(MessageBus.configure({ 
    mode: 'development',
    schemas: [userEvents] 
  }))
  .install(Channel.configure());

// Channel (Secondary) - typically in worker/iframe
const channelEngine = Engine.create()
  .install(Channel.configure());

Creating and Connecting Channels

// Create a channel from MessageBus
const port = messageBusEngine.messageBus.createChannel('worker1');

// Connect Channel to MessageBus
await channelEngine.channel.connect(port);

// Verify connection and event schemas are available
expect(channelEngine.channel.events).toBeDefined();

Publishing and Subscribing

// Subscribe to events
channelEngine.channel.subscribe(
  channelEngine.channel.events.user.login, 
  (username, password) => {
    console.log('User login:', username);
  }
);

// Publish events
channelEngine.channel.publish(
  channelEngine.channel.events.user.login, 
  'john_doe', 
  'secret123'
);

Advanced Features

One-time Subscriptions

channelEngine.channel.subscribeOnce(
  channelEngine.channel.events.system.ready,
  () => console.log('System is ready!')
);

Namespaced Events

// Subscribe to namespaced event
channelEngine.channel.namespace('admin').subscribe(
  channelEngine.channel.events.user.login,
  (username) => console.log('Admin login:', username)
);

// Publish to namespaced event
channelEngine.channel.namespace('admin').publish(
  channelEngine.channel.events.user.login,
  'admin_user'
);

Targeted Messaging

// Send message to specific channel only
channelEngine.channel.to('worker1').publish(
  channelEngine.channel.events.user.logout,
  'username'
);

Multiple Subscribers

const subscriber1 = (data) => console.log('Sub1:', data);
const subscriber2 = (data) => console.log('Sub2:', data);

// Both subscribers will receive the message
channelEngine.channel.subscribe(event, subscriber1);
channelEngine.channel.subscribe(event, subscriber2);

Channel Management

// Check if channel is active
const isActive = messageBusEngine.messageBus.isChannelActive('worker1');

// Enable/disable channels
await messageBusEngine.messageBus.disableChannel('worker1');
await messageBusEngine.messageBus.enableChannel('worker1');

// Use external MessageChannel
const { MessageChannel } = await import('worker_threads');
const messageChannel = new MessageChannel();
messageBusEngine.messageBus.useChannel('external', messageChannel.port1);

Error Handling

The system provides comprehensive error handling:

// Unknown events throw errors
try {
  channelEngine.channel.publish('unknown:event', 'data');
} catch (error) {
  console.error('Unknown event:', error.message);
}

// Connection errors are handled gracefully
const result = await channelEngine.channel.connect(invalidPort);
if (result === false) {
  console.error('Connection failed');
}

Event Validation

Events are automatically validated against their schemas:

// This will pass validation
channelEngine.channel.publish(
  channelEngine.channel.events.user.login,
  'username', // String
  'password'  // String
);

// This will fail validation and log warnings
channelEngine.channel.publish(
  channelEngine.channel.events.user.login,
  'username', // String ✓
  123         // Number ✗ (expected String)
);

Configuration Options

MessageBus Configuration

MessageBus.configure({
  mode: 'development', // 'development' | 'production' | 'test'
  schemas: [userEvents, systemEvents] // Event schema definitions
})

Channel Configuration

Channel.configure({
  port: messagePort, // Optional: pre-configured MessagePort
  subscriptions: [   // Optional: pre-configured subscriptions
    {
      name: 'user.login',
      action: 'subscribe',
      event: 'user:login',
      namespace: 'admin',
      subscriber: (username) => console.log(username)
    }
  ]
})

Testing

The extension includes comprehensive test coverage:

npm test

Tests cover:

  • Basic connection flow
  • Message publishing and subscribing
  • Multiple subscribers and one-time subscriptions
  • Namespace functionality
  • Targeted messaging
  • Error handling
  • Channel management
  • Event validation
  • Complex event schemas

API Reference

MessageBus

  • createChannel(name, callback?) - Create a new channel
  • useChannel(name, port, callback?) - Use external MessageChannel
  • disableChannel(name) - Disable a channel
  • enableChannel(name) - Enable a channel
  • isChannelActive(name) - Check if channel is active

Channel

  • connect(port, callback?) - Connect to MessageBus
  • publish(event, ...payload) - Publish an event
  • subscribe(event, subscriber) - Subscribe to an event
  • subscribeOnce(event, subscriber) - Subscribe once to an event
  • unsubscribe(event, subscriber) - Unsubscribe from an event
  • namespace(name) - Create namespaced channel
  • to(...channels) - Create targeted channel

EventRegistry

  • processSchemas(schemas) - Process event schemas
  • validateEvent(event, payload) - Validate event payload
  • getEventObject() - Get nested event object with symbols
  • getPath(symbol) - Convert symbol to string path
  • getSymbol(path) - Convert string path to symbol

Best Practices

  1. Define schemas early - Set up event schemas before creating channels
  2. Use typed events - Leverage schema validation for better debugging
  3. Handle errors gracefully - Always wrap channel operations in try-catch
  4. Clean up subscriptions - Use unsubscribe functions to prevent memory leaks
  5. Use namespaces - Organize events with namespaces for better structure
  6. Test thoroughly - Use the comprehensive test suite as a reference

Examples

See the test files for complete working examples:

  • __tests__/MessageBus.test.js - Integration tests
  • __tests__/EventRegistry.test.js - Event schema tests
  • __tests__/Port.test.js - Low-level communication tests