Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

9 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

CrossBus

CrossBus

๐Ÿ”Œ Unified messaging for browser applications

Zero dependencies. Fast. Secure by default.

CI npm version TypeScript

License Security A+ 1074 tests Zero deps

๐Ÿ“š Documentation ยท ๐ŸŽฎ Playground ยท ๐Ÿ“– Advanced Patterns


Why CrossBus?

Stop wrestling with postMessage. CrossBus gives you a simple RPC layer for iframes, workers, tabs, and AI agentsโ€”with security defaults you can't forget to configure.

// That's it. Two lines to connect an iframe.
const hub = CrossBus.createSecure({ isHub: true, allowedOrigins: ['https://app.com'] });
hub.handle('getData', async (p) => ({ users: await db.query(p.filter) }));

// In your iframe - instant RPC
const data = await agent.request('hub', 'getData', { filter: 'active' });

๐Ÿ”’ Secure by Default

  • No wildcard origins in production
  • AES-256-GCM encryption plugin
  • Rate limiting per peer
  • Handler whitelisting

โšก Fast

  • ~170M ops/sec emitSync
  • Competitive with nanoevents
  • Zero runtime dependencies
  • Tree-shakeable ESM

๐Ÿค– Browser-First Design

  • Cross-context messaging
  • Copy-paste patterns
  • Schema validation
  • Native bridge support

๐Ÿ† Feature Comparison

Feature CrossBus Comlink Penpal Post-Robot
llms.txt + agent.json โœ… โŒ โŒ โŒ
createSecure() factory โœ… โŒ โŒ โŒ
Handler rate limiting โœ… โŒ โŒ โŒ
Schema validation โœ… โŒ โŒ โŒ
healthCheck() + diagnose() โœ… โŒ โŒ โŒ
Causal ordering โœ… โŒ โŒ โŒ
7 transport types โœ… โŒ โŒ โŒ
WebSocket reconnection โœ… โŒ โŒ โŒ

โšก 30-Second Quick Start

npm install crossbus

Hub (Main Page)

import { CrossBus, PostMessageTransport } from 'crossbus';

// 1. Create secure hub (enforces security best practices)
const hub = CrossBus.createSecure({
  peerId: 'hub',
  isHub: true,
  allowedOrigins: ['https://yourdomain.com']
});

// 2. Register handlers
hub.handle('getData', async ({ userId }) => {
  return await fetchUserData(userId);
});

// 3. Connect iframe
const iframe = document.getElementById('agent-frame');
hub.addTransport(new PostMessageTransport(iframe.contentWindow), { peerId: 'agent' });

Agent (Iframe)

import { CrossBus, PostMessageTransport } from 'crossbus';

const agent = new CrossBus({ peerId: 'agent', allowedOrigins: ['*'] });
agent.addTransport(new PostMessageTransport(window.parent), { peerId: 'hub' });

// That's it! RPC to parent is now trivial
const user = await agent.request('hub', 'getData', { userId: 123 });

๐Ÿ“Š Performance That Matters

Benchmark CrossBus nanoevents EventEmitter3 mitt
emit (1 listener) 172M ops/s ๐Ÿ† 170M 131M 21M
emit (10 listeners) 57M 73M ๐Ÿ† 31M 22M
Large payloads (10KB) 111M 116M ๐Ÿ† 40M 19M

Benchmarked with bun run bench:compare on Apple Silicon. Results vary by run.


๐ŸŽฏ Use Cases

Use Case Transport Why CrossBus
Micro-frontends PostMessageTransport Orchestrate cross-domain iframes with type-safe RPC
Hybrid apps NativeBridgeTransport Bridge web โ†” native (iOS/Android)
Web workers MessageChannelTransport Parallel processing with clean async APIs
Multi-tab sync BroadcastChannelTransport Share state across browser tabs
Service workers ServiceWorkerTransport Runtime network behavior modification
Real-time collab WebSocketTransport Auto-reconnect, backpressure, streaming

๐Ÿ›ก๏ธ Security Features You'll Actually Use

// Security is NOT optionalโ€”createSecure() enforces it
const hub = CrossBus.createSecure({
  allowedOrigins: ['https://trusted.com']  // โœ… No wildcards allowed
});

// Per-handler security controls
hub.handle('admin:delete', handler, {
  allowedPeers: ['admin-agent'],       // Only admin can call
  rateLimit: 10,                        // 10 calls/sec max
  validatePayload: (p) => p.id != null  // Custom validation
});

// Schema validation plugin
import { withSchemaValidation } from 'crossbus/plugins/schema-validation';

hub.handle('createUser', withSchemaValidation({
  type: 'object',
  required: ['name', 'email'],
  properties: {
    name: { type: 'string', minLength: 1 },
    email: { type: 'string', pattern: '^[^@]+@[^@]+$' }
  }
}, async (user) => createUser(user)));

Dev mode warnings alert you to insecure configurations before they reach production.


๐Ÿค– Built for Multi-Context Apps

CrossBus excels at coordinating complex browser applications:

Documentation for AI Assistants

File Purpose
llms.txt AI-optimized quick reference
agent.json A2A Agent Card manifest
GEMINI.md Google/Gemini instructions
CLAUDE.md Anthropic/Claude instructions
docs/AGENTS.md 1200+ lines multi-agent guide

๐Ÿ“ก 7 Transport Types

Transport Use Case Example
PostMessage iframe โ†” parent Chat widgets, embedded apps
BroadcastChannel Tab โ†” tab Cart sync, notifications
MessageChannel Main โ†” worker Heavy computation offload
SharedWorker Cross-tab state Shared connection pool
ServiceWorker Offline-first PWA sync
NativeBridge WebView โ†” Native Mobile apps
WebSocket Browser โ†” Server Real-time backend

๐Ÿ”Œ Plugin Ecosystem

// Encryption (AES-256-GCM)
import { withEncryption } from 'crossbus/plugins/encryption';
withEncryption(bus, await Encryption.deriveKey('password', 'salt'));

// Retry with exponential backoff
import { withRetry } from 'crossbus/plugins/retry';
withRetry(bus, { maxRetries: 3, baseDelay: 100 });

// Circuit breaker
import { createPeerCircuitBreaker } from 'crossbus/plugins/circuit-breaker';
const breaker = createPeerCircuitBreaker(bus, { failureThreshold: 5 });

// Compression for large payloads
import { withCompression } from 'crossbus/plugins/compression';
withCompression(bus, { threshold: 1024 });

// Rate limiting
import { withRateLimiter } from 'crossbus/plugins/rate-limiter';
withRateLimiter(bus, { maxRequests: 100, windowMs: 1000 });

// Batching for high-frequency updates
import { withBatching } from 'crossbus/plugins/batch';
withBatching(bus, { windowMs: 50, maxBatchSize: 100 });

๐Ÿข Enterprise Ready

// Distributed tracing (OpenTelemetry-compatible)
import { Tracer, tracingPlugin } from 'crossbus/enterprise';
const tracer = new Tracer({ serviceName: 'hub' });
bus.addOutboundHook(tracingPlugin(tracer));

// Prometheus-compatible metrics
import { globalMetrics } from 'crossbus/enterprise';
console.log(globalMetrics.toPrometheus());

// Backpressure control
import { BackpressureController } from 'crossbus/enterprise';
const bp = new BackpressureController(bus, { highWaterMark: 1000 });

// Message versioning / migration
import { MessageVersioning } from 'crossbus/enterprise';
const versioning = new MessageVersioning();
versioning.registerMigration('user', 1, 2, (data) => ({ ...data, v2Field: true }));

๐Ÿ“ฆ Bundle Size

Export Size (gzip)
Full bundle ~15 KB
Core only ~10 KB
Nano emitter 295 bytes

๐Ÿงช Test Coverage

  1074 tests passing
  98.41% line coverage on core
  0 dependencies

๐Ÿ“– Documentation

  • AGENTS.md โ€” Complete multi-agent infrastructure guide
  • API.md โ€” Full API reference
  • SECURITY.md โ€” Security features and best practices
  • examples/ โ€” Machine-readable patterns

๐Ÿš€ Get Started Now

npm install crossbus
import { CrossBus } from 'crossbus';

const bus = CrossBus.createSecure({
  peerId: 'my-app',
  allowedOrigins: ['https://myapp.com']
});

// You're ready to build something amazing.

โญ Star us on GitHub ยท ๐Ÿ“– Documentation


License: Apache 2.0 ยฉ 2026