Creating your own adapters
An adapter's job is to map @busly/core onto the patterns a framework already uses, whether those are hooks, signals, stores, or dependency injection. The official adapters are built exactly this way, and nothing stops you from writing your own.
You have two starting points. The easiest is to wrap @busly/js. It takes only a few lines, and you get on/lazy ordering, server detection, and error isolation for free. That's the right choice most of the time.
The alternative is to build directly on @busly/core. This gives you full control, but it also makes you responsible for the rules described below.
What core gives you
Core exposes a small set of functions and types:
import {
emit, // (type, payload, { source }?) => void
subscribe, // (type, handler) => unsubscribe
detectServer, // () => boolean
isBusEvent, // value is { type: string; payload }
} from '@busly/core';
import type {
Envelope, // { v, type, payload, ts, source }
EventOptions, // { source?: string }
EnvOptions, // { server?: boolean }
IBusEvent, // { type: string; payload: T }
IBusEventCreator, // ((payload) => IBusEvent) & { type: string }
IBusEventGroup, // Record<string, IBusEventCreator>
SelfDispatchingEvents, // group → one typed function per event
SubscriptionHandler, // (envelope: Envelope<K>) => void
} from '@busly/core';Build your adapter on the structural types rather than on a specific event library. That way it accepts any creator with the right shape, without importing anything else.
Rules every adapter must follow
Whichever route you take, users expect every adapter to behave the same way. These are the rules the official ones follow.
- Do nothing on the server. Core keeps one registry per process, so on Node, events would leak between concurrent requests. Skip
emitandsubscribewheneverdetectServer()returns true, or use the framework's own check, such as Angular'sisPlatformServer. AcceptEnvOptionsso users can override the detection. - Require at least one event. Busly has no "listen to everything" mode, so throw when the list of events is empty.
- Deduplicate types. Listening to
[a, a], or to two creators that share a type string, should still deliver each event only once. - Isolate errors. A handler that throws must not stop the others. Report the error, by re-throwing it in a microtask or passing it to the framework's error handler, rather than swallowing it.
- Always offer cleanup. Every listen call should return an unsubscribe function, or be tied to the framework's lifecycle.
- Provide a default
source. Pick something recognizable, such as'busly-vue', and let users override it. - Make core a peer dependency. There should be a single copy per page, shared by every microfrontend.
Wrapping @busly/js
Here's what a Vue adapter could look like, with a set of composables modeled on @busly/react:
// busly-vue.ts
import { onScopeDispose } from 'vue';
import { createDispatcher, createReceiver, type EventHandler } from '@busly/js';
import type { IBusEventCreator, IBusEventGroup } from '@busly/core';
export function useBusDispatch<G extends IBusEventGroup>(group: G, source = 'busly-vue') {
return createDispatcher(group, { source });
}
export function useBusOn<C extends IBusEventCreator>(events: C | readonly C[], handler: EventHandler<C>) {
const receiver = createReceiver();
receiver.on(events, handler);
onScopeDispose(() => receiver.dispose());
}
export function useBusLazy<C extends IBusEventCreator>(events: C | readonly C[], handler: EventHandler<C>) {
const receiver = createReceiver();
receiver.lazy(events, handler);
onScopeDispose(() => receiver.dispose());
}That's all it takes. @busly/js already handles rules 1 through 5, and the ordering between on and lazy spans every receiver in the application.
Building on @busly/core
If you'd rather go without @busly/js, the next sections walk through the pieces you'll need.
Dispatching
A dispatcher turns each creator in a group into a function that builds the event and emits it, unless it's running on the server:
import { detectServer, emit, type EnvOptions, type EventOptions, type IBusEventGroup, type SelfDispatchingEvents } from '@busly/core';
export function createDispatcher<G extends IBusEventGroup>(
group: G,
options?: EventOptions & EnvOptions,
): SelfDispatchingEvents<G> {
const server = options?.server ?? detectServer();
const source = options?.source ?? 'busly-solid';
const out: Record<string, (payload?: unknown) => void> = {};
for (const [name, creator] of Object.entries(group)) {
out[name] = (payload) => {
if (server) return;
const event = creator(payload);
emit(event.type, event.payload, { source });
};
}
return out as SelfDispatchingEvents<G>;
}emit clones the payload before sending it, and throws a DataCloneError if it can't. Let that error propagate, since it means the caller passed a payload that can't be sent.
Listening
subscribe(type, handler) registers a handler for a single type. Core runs each handler in its own microtask, which means a handler that throws can never stop the others. A basic listener only needs to validate the input, skip the server, and deduplicate types:
import { detectServer, subscribe, type Envelope, type IBusEventCreator } from '@busly/core';
export function listen(events: readonly IBusEventCreator[], handler: (event: Envelope) => void): () => void {
if (events.length === 0) throw new Error('listen() requires at least one event creator');
if (detectServer()) return () => {};
const types = [...new Set(events.map((e) => e.type))];
const offs = types.map((type) => subscribe(type, handler));
return () => offs.forEach((off) => off());
}This is enough for an adapter with a single cohort, like @busly/react.
Adding on / lazy
Adding the two cohorts takes a bit more work. You can't get the ordering from subscription order, because core runs each handler in a microtask of its own. Instead, it comes from having a single core subscription per event type, which calls all the on handlers and then all the lazy handlers in one go. The official adapters call this a bridge:
import { subscribe, type Envelope } from '@busly/core';
type Handler = (event: Envelope) => void;
interface Bridge {
on: Set<Handler>;
lazy: Set<Handler>;
off: () => void;
}
// module level: ONE bridge per type for the whole adapter
const bridges = new Map<string, Bridge>();
function run(handlers: Set<Handler>, event: Envelope) {
for (const handler of [...handlers]) { // snapshot: added mid-delivery → next event
if (!handlers.has(handler)) continue; // removed mid-delivery → skip
try {
handler(event);
} catch (err) {
queueMicrotask(() => { throw err; }); // isolate, still report
}
}
}
function bridgeFor(type: string): Bridge {
let bridge = bridges.get(type);
if (!bridge) {
const on = new Set<Handler>();
const lazy = new Set<Handler>();
const off = subscribe(type, (event) => {
run(on, event);
run(lazy, event);
});
bridge = { on, lazy, off };
bridges.set(type, bridge);
}
return bridge;
}
export function listen(cohort: 'on' | 'lazy', type: string, handler: Handler): () => void {
const bridge = bridgeFor(type);
const own: Handler = (event) => handler(event); // same handler twice → two subscriptions
bridge[cohort].add(own);
return () => {
bridge[cohort].delete(own);
if (bridge.on.size + bridge.lazy.size === 0 && bridges.get(type) === bridge) {
bridge.off(); // last handler gone → release core subscription
bridges.delete(type);
}
};
}A few details in this code are essential. There must be only one bridge per type, shared by everyone. Two bridges for the same type would be two independent sources of delivery, with no ordering between them.
The bridge must also call the handlers synchronously, with no scheduler in between, otherwise asynchronous work could slip in between on and lazy. And it must take a snapshot of each handler set before running it, so that handlers added or removed during delivery behave predictably.
Finally, the ordering only holds within one copy of your adapter, so make sure to document that for your users.
For comparison, @busly/angular follows the same design using two RxJS Subjects per type, with a reference count shared across both cohorts.
Passing events back to the bus
Some store integrations dispatch whatever their handlers emit, like withBusEventHandlers does in @busly/ngrx. If yours works this way, it must avoid re-dispatching events it received, or it will loop forever. The solution is to mark delivered events and check for the mark before dispatching:
const delivered = new WeakSet<object>();
// in the bridge: one marked object per event, shared by both cohorts
const off = subscribe(type, (envelope) => {
delivered.add(envelope);
run(on, envelope);
run(lazy, envelope);
});
// when a handler emits a value
if (isBusEvent(value) && !delivered.has(value)) {
dispatch(value);
}@busly/angular exposes its own mark as isBusDelivered.
Checklist
Before publishing your adapter, run through this list:
- [ ] Does nothing on the server, with an
EnvOptionsoverride. - [ ] Throws on an empty event list.
- [ ] Deduplicates event types.
- [ ] Isolates and reports handler errors.
- [ ] Offers cleanup for every listener, tied to the framework's lifecycle where possible.
- [ ] Has a default
sourcethat users can override. - [ ] Declares
@busly/coreas a peer dependency. - [ ] If it has
on/lazy: one bridge per type, synchronous delivery, snapshotted handler sets. - [ ] If it dispatches handler results: never re-dispatches delivered events.