1+ /**
2+ * @module
3+ * MeBus is a type safe and end-to-end runtime validated message bus for the browser.
4+ */
5+
16import z from "zod" ;
27
8+ /**
9+ * EventSchema is a record of event types and their corresponding payload schemas.
10+ * @example
11+ * const MyEventSchema: EventSchema = {
12+ * event1: z.object({ payload: z.string(), }),
13+ * event2: z.object({ id: z.number(), }),
14+ * };
15+ */
316export type EventSchema = Record < string , z . Schema > ;
417
18+ /**
19+ * Type guard for CustomEvent.
20+ * @param event - The event to check.
21+ * @returns true if the event is a CustomEvent, false otherwise.
22+ */
523const isCustomEvent = ( event : Event ) : event is CustomEvent => {
624 return event instanceof CustomEvent ;
725} ;
@@ -26,6 +44,11 @@ const isCustomEvent = (event: Event): event is CustomEvent => {
2644export class MeBus < T extends EventSchema > {
2745 private eventSchema : T ;
2846
47+ /**
48+ * Creates a new instance of MeBus.
49+ * @param eventSchema - Schema with definitions for all the event types and their payloads.
50+ * @throws Error if MeBus is not used in the browser.
51+ */
2952 constructor ( eventSchema : T ) {
3053 if ( typeof window === "undefined" ) {
3154 throw new Error ( "[MeBus] MeBus is only available in the browser" ) ;
@@ -34,12 +57,15 @@ export class MeBus<T extends EventSchema> {
3457 }
3558
3659 /**
37- * Subscribes to a specific event type and registers a listener function to be called when the event is triggered.
60+ * Subscribes to a specific event type and registers a listener function to be called when the event is triggered. Returns cleanup.
3861 * @param type - The event type to subscribe to.
3962 * @param listener - The listener function to be called when the event is triggered. It receives the payload of the event as a parameter.
4063 * @returns A function that can be called to unsubscribe from the event.
4164 */
42- public subscribe < K extends keyof T & string > ( type : K , listener : ( payload : z . infer < T [ K ] > ) => void ) {
65+ public subscribe < K extends keyof T & string > (
66+ type : K ,
67+ listener : ( payload : z . infer < T [ K ] > ) => void
68+ ) : ( ) => void {
4369 const schema = this . eventSchema [ type ] ;
4470 if ( ! schema ) {
4571 throw new Error ( `[MeBus] No schema found for event: ${ type } ` ) ;
@@ -74,7 +100,10 @@ export class MeBus<T extends EventSchema> {
74100 * @returns void
75101 * @throws Error if no schema is found for the event or if the payload fails validation.
76102 */
77- public publish < K extends keyof T & string > ( type : K , payload : z . infer < T [ K ] > ) : void {
103+ public publish < K extends keyof T & string > (
104+ type : K ,
105+ payload : z . infer < T [ K ] >
106+ ) : void {
78107 const schema = this . eventSchema [ type ] ;
79108 if ( ! schema ) {
80109 throw new Error ( `[MeBus] No schema found for event: ${ type } ` ) ;
0 commit comments