$ show pubkey/broadcast-channel
This repository is a JavaScript library providing a BroadcastChannel polyfill with leader election capabilities. It enables cross-tab/window/node-process communication through multiple fallback mechanisms (native BroadcastChannel, IndexedDB, localStorage, Node.js sockets, and a simulate method). The library implements leader election algorithms to coordinate multiple instances, ensuring only one acts as leader at a time. It supports diverse environments including old browsers, modern browsers, WebWorkers, Node.js, Deno, and iframes. The architecture centers around a core BroadcastChannel class with pluggable method implementations, a method chooser for fallback selection, and separate leader election utilities. Key entry points are the exported BroadcastChannel class and createLeaderElection function from src/index.js.
The LLM identified 4 files worth highlighting for reuse:
Provides cross-platform utility functions including microsecond timing (with worker-safe fallback), random token generation, sleep function, and promise helpers. Minimal dependencies (only detect-node) make it easily extractable for any project needing these low-level utilities.
Implements a strategy pattern for selecting optimal communication method (Native → IndexedDB → LocalStorage → Node → Simulate) based on runtime availability and user options. Encapsulates environment detection and fallback logic in an isolated module that could be reused for similar capability-based selection scenarios.
Contains leader election utilities including an ObliviousSet wrapper for automatic message ID deduplication with TTL, and functions for checking/awaiting leadership. The ObliviousSet pattern solves a recurring problem in distributed systems and could be extracted for other message-passing or caching use cases.
Manages default options merging with environment-specific overrides and user preferences. Demonstrates a clean, isolated pattern for configuration handling that avoids mutation of inputs and provides sensible defaults - easily reusable in any configurable library or application.