@ahoo-wang/fetcher-eventbus 2.8.8 → 2.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/broadcastTypedEventBus.d.ts +122 -28
- package/dist/broadcastTypedEventBus.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.es.js +176 -46
- package/dist/index.es.js.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/index.umd.js.map +1 -1
- package/dist/messengers/broadcastChannelMessenger.d.ts +19 -0
- package/dist/messengers/broadcastChannelMessenger.d.ts.map +1 -0
- package/dist/messengers/crossTabMessenger.d.ts +29 -0
- package/dist/messengers/crossTabMessenger.d.ts.map +1 -0
- package/dist/messengers/index.d.ts +4 -0
- package/dist/messengers/index.d.ts.map +1 -0
- package/dist/messengers/storageMessenger.d.ts +41 -0
- package/dist/messengers/storageMessenger.d.ts.map +1 -0
- package/package.json +1 -1
|
@@ -1,66 +1,160 @@
|
|
|
1
1
|
import { TypedEventBus } from './typedEventBus';
|
|
2
2
|
import { EventHandler, EventType } from './types';
|
|
3
|
+
import { CrossTabMessenger } from './messengers';
|
|
3
4
|
/**
|
|
4
|
-
*
|
|
5
|
+
* Configuration options for BroadcastTypedEventBus
|
|
5
6
|
*
|
|
6
|
-
*
|
|
7
|
-
|
|
8
|
-
|
|
7
|
+
* @template EVENT - The event type this bus will handle
|
|
8
|
+
*/
|
|
9
|
+
export interface BroadcastTypedEventBusOptions<EVENT> {
|
|
10
|
+
/**
|
|
11
|
+
* The underlying event bus that handles local event processing and storage.
|
|
12
|
+
* This bus manages event handlers and local event emission.
|
|
13
|
+
*/
|
|
14
|
+
delegate: TypedEventBus<EVENT>;
|
|
15
|
+
/**
|
|
16
|
+
* Optional messenger for cross-tab/window communication.
|
|
17
|
+
* If not provided, a default BroadcastChannel-based messenger will be created
|
|
18
|
+
* using the pattern `_broadcast_:{type}`. Must be a valid CrossTabMessenger
|
|
19
|
+
* implementation when provided.
|
|
20
|
+
*/
|
|
21
|
+
messenger?: CrossTabMessenger;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Broadcast event bus that enables cross-tab/window communication
|
|
25
|
+
*
|
|
26
|
+
* This class extends a local TypedEventBus with cross-context broadcasting capabilities.
|
|
27
|
+
* When events are emitted, they are first processed locally by the delegate bus, then
|
|
28
|
+
* broadcasted to other browser contexts (tabs, windows, etc.) through the provided messenger.
|
|
9
29
|
*
|
|
10
|
-
*
|
|
30
|
+
* Incoming broadcast messages from other contexts are automatically forwarded to the
|
|
31
|
+
* local delegate bus for processing by registered event handlers.
|
|
11
32
|
*
|
|
12
|
-
* @template EVENT - The type
|
|
33
|
+
* @template EVENT - The event type this bus handles (must be serializable for cross-context transport)
|
|
13
34
|
*
|
|
14
|
-
* @example
|
|
35
|
+
* @example Basic usage with default messenger
|
|
15
36
|
* ```typescript
|
|
37
|
+
* import { SerialTypedEventBus } from './serialTypedEventBus';
|
|
38
|
+
* import { BroadcastTypedEventBus } from './broadcastTypedEventBus';
|
|
39
|
+
*
|
|
40
|
+
* // Create local event bus
|
|
16
41
|
* const delegate = new SerialTypedEventBus<string>('user-events');
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
42
|
+
*
|
|
43
|
+
* // Create broadcast event bus with default messenger
|
|
44
|
+
* const bus = new BroadcastTypedEventBus({
|
|
45
|
+
* delegate
|
|
46
|
+
* // messenger will be auto-created as '_broadcast_:user-events'
|
|
47
|
+
* });
|
|
48
|
+
*
|
|
49
|
+
* // Register event handler
|
|
50
|
+
* bus.on({
|
|
51
|
+
* name: 'user-login',
|
|
52
|
+
* order: 1,
|
|
53
|
+
* handle: (username: string) => console.log(`User ${username} logged in`)
|
|
54
|
+
* });
|
|
55
|
+
*
|
|
56
|
+
* // Emit event (will be processed locally and broadcasted to other tabs)
|
|
57
|
+
* await bus.emit('john-doe');
|
|
20
58
|
* ```
|
|
21
59
|
*
|
|
22
|
-
* @example
|
|
60
|
+
* @example Using custom messenger
|
|
23
61
|
* ```typescript
|
|
24
|
-
*
|
|
62
|
+
* import { SerialTypedEventBus } from './serialTypedEventBus';
|
|
63
|
+
* import { createCrossTabMessenger } from './messengers';
|
|
64
|
+
* import { BroadcastTypedEventBus } from './broadcastTypedEventBus';
|
|
65
|
+
*
|
|
66
|
+
* // Create local event bus
|
|
67
|
+
* const delegate = new SerialTypedEventBus<string>('user-events');
|
|
68
|
+
*
|
|
69
|
+
* // Create custom cross-tab messenger
|
|
70
|
+
* const messenger = createCrossTabMessenger('my-custom-channel');
|
|
71
|
+
*
|
|
72
|
+
* // Create broadcast event bus
|
|
73
|
+
* const bus = new BroadcastTypedEventBus({
|
|
74
|
+
* delegate,
|
|
75
|
+
* messenger
|
|
76
|
+
* });
|
|
77
|
+
*
|
|
78
|
+
* // Register event handler and emit events...
|
|
79
|
+
* ```
|
|
80
|
+
*
|
|
81
|
+
* @example Using custom messenger implementation
|
|
82
|
+
* ```typescript
|
|
83
|
+
* class CustomMessenger implements CrossTabMessenger {
|
|
84
|
+
* // ... implementation
|
|
85
|
+
* }
|
|
86
|
+
*
|
|
87
|
+
* const customMessenger = new CustomMessenger();
|
|
88
|
+
* const bus = new BroadcastTypedEventBus({
|
|
89
|
+
* delegate: new SerialTypedEventBus('events'),
|
|
90
|
+
* messenger: customMessenger
|
|
91
|
+
* });
|
|
25
92
|
* ```
|
|
26
93
|
*/
|
|
27
94
|
export declare class BroadcastTypedEventBus<EVENT> implements TypedEventBus<EVENT> {
|
|
28
|
-
private readonly delegate;
|
|
29
95
|
readonly type: EventType;
|
|
30
|
-
private readonly
|
|
96
|
+
private readonly delegate;
|
|
97
|
+
private messenger;
|
|
31
98
|
/**
|
|
32
|
-
* Creates a broadcast
|
|
99
|
+
* Creates a new broadcast event bus with cross-context communication
|
|
33
100
|
*
|
|
34
|
-
* @param
|
|
35
|
-
* @
|
|
101
|
+
* @param options - Configuration object containing delegate bus and optional messenger
|
|
102
|
+
* @throws {Error} If messenger creation fails when no messenger is provided
|
|
36
103
|
*/
|
|
37
|
-
constructor(
|
|
104
|
+
constructor(options: BroadcastTypedEventBusOptions<EVENT>);
|
|
38
105
|
/**
|
|
39
|
-
*
|
|
106
|
+
* Returns a copy of all currently registered event handlers
|
|
107
|
+
*
|
|
108
|
+
* This getter delegates to the underlying event bus and returns the current
|
|
109
|
+
* list of handlers that will process incoming events.
|
|
110
|
+
*
|
|
111
|
+
* @returns Array of event handlers registered with this bus
|
|
40
112
|
*/
|
|
41
113
|
get handlers(): EventHandler<EVENT>[];
|
|
42
114
|
/**
|
|
43
|
-
* Emits an event locally and broadcasts it to other
|
|
115
|
+
* Emits an event locally and broadcasts it to other browser contexts
|
|
116
|
+
*
|
|
117
|
+
* This method first processes the event through the local delegate bus,
|
|
118
|
+
* allowing all registered local handlers to process it. Then, if successful,
|
|
119
|
+
* the event is broadcasted to other tabs/windows through the messenger.
|
|
44
120
|
*
|
|
45
|
-
*
|
|
121
|
+
* Note: If broadcasting fails (e.g., due to messenger errors), the local
|
|
122
|
+
* emission is still completed and a warning is logged to console.
|
|
123
|
+
*
|
|
124
|
+
* @param event - The event data to emit and broadcast
|
|
125
|
+
* @returns Promise that resolves when local processing is complete
|
|
126
|
+
* @throws Propagates any errors from local event processing
|
|
46
127
|
*/
|
|
47
128
|
emit(event: EVENT): Promise<void>;
|
|
48
129
|
/**
|
|
49
|
-
* Removes an event handler by
|
|
130
|
+
* Removes an event handler by its registered name
|
|
131
|
+
*
|
|
132
|
+
* This method delegates to the underlying event bus to remove the specified
|
|
133
|
+
* handler. The handler will no longer receive events emitted to this bus.
|
|
50
134
|
*
|
|
51
|
-
* @param name - The name of the handler to remove
|
|
52
|
-
* @returns true if a handler was removed, false otherwise
|
|
135
|
+
* @param name - The unique name of the handler to remove
|
|
136
|
+
* @returns true if a handler with the given name was found and removed, false otherwise
|
|
53
137
|
*/
|
|
54
138
|
off(name: string): boolean;
|
|
55
139
|
/**
|
|
56
|
-
*
|
|
140
|
+
* Registers a new event handler with this bus
|
|
57
141
|
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
142
|
+
* The handler will receive all events emitted to this bus, both locally
|
|
143
|
+
* generated and received from other browser contexts via broadcasting.
|
|
144
|
+
*
|
|
145
|
+
* @param handler - The event handler configuration to register
|
|
146
|
+
* @returns true if the handler was successfully added, false if a handler with the same name already exists
|
|
60
147
|
*/
|
|
61
148
|
on(handler: EventHandler<EVENT>): boolean;
|
|
62
149
|
/**
|
|
63
|
-
* Cleans up resources
|
|
150
|
+
* Cleans up resources and stops cross-context communication
|
|
151
|
+
*
|
|
152
|
+
* This method closes the messenger connection, preventing further
|
|
153
|
+
* cross-tab communication. Local event handling continues to work
|
|
154
|
+
* through the delegate bus. After calling destroy(), the bus should
|
|
155
|
+
* not be used for broadcasting operations.
|
|
156
|
+
*
|
|
157
|
+
* Note: This does not remove event handlers or affect local event processing.
|
|
64
158
|
*/
|
|
65
159
|
destroy(): void;
|
|
66
160
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"broadcastTypedEventBus.d.ts","sourceRoot":"","sources":["../src/broadcastTypedEventBus.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"broadcastTypedEventBus.d.ts","sourceRoot":"","sources":["../src/broadcastTypedEventBus.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAClD,OAAO,EAA2B,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAE1E;;;;GAIG;AACH,MAAM,WAAW,6BAA6B,CAAC,KAAK;IAClD;;;OAGG;IACH,QAAQ,EAAE,aAAa,CAAC,KAAK,CAAC,CAAC;IAE/B;;;;;OAKG;IACH,SAAS,CAAC,EAAE,iBAAiB,CAAC;CAC/B;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsEG;AACH,qBAAa,sBAAsB,CAAC,KAAK,CAAE,YAAW,aAAa,CAAC,KAAK,CAAC;IACxE,SAAgB,IAAI,EAAE,SAAS,CAAC;IAChC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAuB;IAChD,OAAO,CAAC,SAAS,CAAoB;IAErC;;;;;OAKG;gBACS,OAAO,EAAE,6BAA6B,CAAC,KAAK,CAAC;IAczD;;;;;;;OAOG;IACH,IAAI,QAAQ,IAAI,YAAY,CAAC,KAAK,CAAC,EAAE,CAEpC;IAED;;;;;;;;;;;;;OAaG;IACG,IAAI,CAAC,KAAK,EAAE,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IAKvC;;;;;;;;OAQG;IACH,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO;IAI1B;;;;;;;;OAQG;IACH,EAAE,CAAC,OAAO,EAAE,YAAY,CAAC,KAAK,CAAC,GAAG,OAAO;IAIzC;;;;;;;;;OASG;IACH,OAAO,IAAI,IAAI;CAGhB"}
|
package/dist/index.d.ts
CHANGED
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,YAAY,CAAC;AAC3B,cAAc,yBAAyB,CAAC;AACxC,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,SAAS,CAAC;AACxB,cAAc,iBAAiB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAaA,cAAc,YAAY,CAAC;AAC3B,cAAc,yBAAyB,CAAC;AACxC,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,0BAA0B,CAAC;AACzC,cAAc,SAAS,CAAC;AACxB,cAAc,iBAAiB,CAAC;AAChC,cAAc,cAAc,CAAC"}
|
package/dist/index.es.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { toSorted as
|
|
2
|
-
class
|
|
1
|
+
import { toSorted as r } from "@ahoo-wang/fetcher";
|
|
2
|
+
class y {
|
|
3
3
|
/**
|
|
4
4
|
* Creates a generic event bus
|
|
5
5
|
*
|
|
@@ -72,7 +72,7 @@ class i {
|
|
|
72
72
|
}
|
|
73
73
|
}
|
|
74
74
|
}
|
|
75
|
-
class
|
|
75
|
+
class w extends i {
|
|
76
76
|
/**
|
|
77
77
|
* Creates a parallel typed event bus
|
|
78
78
|
*
|
|
@@ -90,11 +90,11 @@ class u extends i {
|
|
|
90
90
|
* @param event - The event to emit
|
|
91
91
|
*/
|
|
92
92
|
async emit(e) {
|
|
93
|
-
const t = [], s = this.eventHandlers.map(async (
|
|
94
|
-
await this.handleEvent(
|
|
93
|
+
const t = [], s = this.eventHandlers.map(async (a) => {
|
|
94
|
+
await this.handleEvent(a, e), a.once && t.push(a);
|
|
95
95
|
});
|
|
96
96
|
await Promise.all(s), t.length > 0 && (this.eventHandlers = this.eventHandlers.filter(
|
|
97
|
-
(
|
|
97
|
+
(a) => !t.includes(a)
|
|
98
98
|
));
|
|
99
99
|
}
|
|
100
100
|
/**
|
|
@@ -120,7 +120,7 @@ class u extends i {
|
|
|
120
120
|
return t.some((s) => s.name === e.name) ? !1 : (this.eventHandlers = [...t, e], !0);
|
|
121
121
|
}
|
|
122
122
|
}
|
|
123
|
-
class
|
|
123
|
+
class E extends i {
|
|
124
124
|
/**
|
|
125
125
|
* Creates an in-memory typed event bus
|
|
126
126
|
*
|
|
@@ -141,7 +141,7 @@ class d extends i {
|
|
|
141
141
|
const t = [];
|
|
142
142
|
for (const s of this.eventHandlers)
|
|
143
143
|
await this.handleEvent(s, e), s.once && t.push(s);
|
|
144
|
-
t.length > 0 && (this.eventHandlers =
|
|
144
|
+
t.length > 0 && (this.eventHandlers = r(
|
|
145
145
|
this.eventHandlers.filter((s) => !t.includes(s))
|
|
146
146
|
));
|
|
147
147
|
}
|
|
@@ -153,7 +153,7 @@ class d extends i {
|
|
|
153
153
|
*/
|
|
154
154
|
off(e) {
|
|
155
155
|
const t = this.eventHandlers;
|
|
156
|
-
return t.some((s) => s.name === e) ? (this.eventHandlers =
|
|
156
|
+
return t.some((s) => s.name === e) ? (this.eventHandlers = r(t, (s) => s.name !== e), !0) : !1;
|
|
157
157
|
}
|
|
158
158
|
/**
|
|
159
159
|
* Adds an event handler if not already present
|
|
@@ -165,67 +165,192 @@ class d extends i {
|
|
|
165
165
|
*/
|
|
166
166
|
on(e) {
|
|
167
167
|
const t = this.eventHandlers;
|
|
168
|
-
return t.some((s) => s.name === e.name) ? !1 : (this.eventHandlers =
|
|
168
|
+
return t.some((s) => s.name === e.name) ? !1 : (this.eventHandlers = r([...t, e]), !0);
|
|
169
169
|
}
|
|
170
170
|
}
|
|
171
|
-
class
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
}
|
|
171
|
+
class h {
|
|
172
|
+
constructor(e) {
|
|
173
|
+
this.broadcastChannel = new BroadcastChannel(e);
|
|
174
|
+
}
|
|
175
|
+
postMessage(e) {
|
|
176
|
+
this.broadcastChannel.postMessage(e);
|
|
177
|
+
}
|
|
178
|
+
/**
|
|
179
|
+
* Set the message handler for incoming messages
|
|
180
|
+
*
|
|
181
|
+
* @param handler - Function to handle incoming messages, or undefined to remove handler
|
|
182
|
+
*/
|
|
183
|
+
set onmessage(e) {
|
|
184
|
+
this.broadcastChannel.onmessage = (t) => {
|
|
185
|
+
e(t.data);
|
|
187
186
|
};
|
|
188
187
|
}
|
|
189
188
|
/**
|
|
190
|
-
*
|
|
189
|
+
* Close the messenger and clean up resources
|
|
190
|
+
*
|
|
191
|
+
* After calling close(), the messenger cannot be used again.
|
|
192
|
+
*/
|
|
193
|
+
close() {
|
|
194
|
+
this.broadcastChannel.close();
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const c = 1e3, u = 6e4;
|
|
198
|
+
class d {
|
|
199
|
+
constructor(e) {
|
|
200
|
+
this.storageEventHandler = (t) => {
|
|
201
|
+
if (!(t.storageArea !== this.storage || !t.key?.startsWith(this.messageKeyPrefix) || !t.newValue))
|
|
202
|
+
try {
|
|
203
|
+
const s = JSON.parse(t.newValue);
|
|
204
|
+
this.messageHandler?.(s.data);
|
|
205
|
+
} catch (s) {
|
|
206
|
+
console.warn("Failed to parse storage message:", s);
|
|
207
|
+
}
|
|
208
|
+
}, this.channelName = e.channelName, this.storage = e.storage ?? localStorage, this.messageKeyPrefix = `_storage_msg_${this.channelName}`, this.ttl = e.ttl ?? c, this.cleanupInterval = e.cleanupInterval ?? u, this.cleanupTimer = window.setInterval(
|
|
209
|
+
() => this.cleanup(),
|
|
210
|
+
this.cleanupInterval
|
|
211
|
+
), window.addEventListener("storage", this.storageEventHandler);
|
|
212
|
+
}
|
|
213
|
+
generateMessageKey() {
|
|
214
|
+
return `${this.messageKeyPrefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Send a message to other tabs/windows via localStorage
|
|
218
|
+
*/
|
|
219
|
+
postMessage(e) {
|
|
220
|
+
const t = this.generateMessageKey(), s = {
|
|
221
|
+
data: e,
|
|
222
|
+
timestamp: Date.now()
|
|
223
|
+
};
|
|
224
|
+
this.storage.setItem(t, JSON.stringify(s)), setTimeout(() => this.storage.removeItem(t), this.ttl);
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Set the message handler for incoming messages
|
|
228
|
+
*/
|
|
229
|
+
set onmessage(e) {
|
|
230
|
+
this.messageHandler = e;
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Clean up expired messages from storage
|
|
234
|
+
*/
|
|
235
|
+
cleanup() {
|
|
236
|
+
const e = Date.now(), t = [];
|
|
237
|
+
for (let s = 0; s < this.storage.length; s++) {
|
|
238
|
+
const a = this.storage.key(s);
|
|
239
|
+
if (a?.startsWith(this.messageKeyPrefix))
|
|
240
|
+
try {
|
|
241
|
+
const o = this.storage.getItem(a);
|
|
242
|
+
if (o) {
|
|
243
|
+
const l = JSON.parse(o);
|
|
244
|
+
e > l.timestamp + this.ttl && t.push(a);
|
|
245
|
+
}
|
|
246
|
+
} catch {
|
|
247
|
+
t.push(a);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
t.forEach((s) => this.storage.removeItem(s));
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Close the messenger and clean up resources
|
|
254
|
+
*/
|
|
255
|
+
close() {
|
|
256
|
+
this.cleanupTimer && clearInterval(this.cleanupTimer), window.removeEventListener("storage", this.storageEventHandler);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
function g() {
|
|
260
|
+
return typeof BroadcastChannel < "u" && typeof BroadcastChannel.prototype?.postMessage == "function";
|
|
261
|
+
}
|
|
262
|
+
function f() {
|
|
263
|
+
return typeof StorageEvent < "u" && typeof window < "u" && typeof window.addEventListener == "function" && (typeof localStorage < "u" || typeof sessionStorage < "u");
|
|
264
|
+
}
|
|
265
|
+
function m(n) {
|
|
266
|
+
if (g())
|
|
267
|
+
return new h(n);
|
|
268
|
+
if (f())
|
|
269
|
+
return new d({ channelName: n });
|
|
270
|
+
}
|
|
271
|
+
class H {
|
|
272
|
+
/**
|
|
273
|
+
* Creates a new broadcast event bus with cross-context communication
|
|
274
|
+
*
|
|
275
|
+
* @param options - Configuration object containing delegate bus and optional messenger
|
|
276
|
+
* @throws {Error} If messenger creation fails when no messenger is provided
|
|
277
|
+
*/
|
|
278
|
+
constructor(e) {
|
|
279
|
+
this.delegate = e.delegate, this.type = this.delegate.type;
|
|
280
|
+
const t = e.messenger ?? m(`_broadcast_:${this.type}`);
|
|
281
|
+
if (!t)
|
|
282
|
+
throw new Error("Messenger setup failed");
|
|
283
|
+
this.messenger = t, this.messenger.onmessage = async (s) => {
|
|
284
|
+
await this.delegate.emit(s);
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Returns a copy of all currently registered event handlers
|
|
289
|
+
*
|
|
290
|
+
* This getter delegates to the underlying event bus and returns the current
|
|
291
|
+
* list of handlers that will process incoming events.
|
|
292
|
+
*
|
|
293
|
+
* @returns Array of event handlers registered with this bus
|
|
191
294
|
*/
|
|
192
295
|
get handlers() {
|
|
193
296
|
return this.delegate.handlers;
|
|
194
297
|
}
|
|
195
298
|
/**
|
|
196
|
-
* Emits an event locally and broadcasts it to other
|
|
299
|
+
* Emits an event locally and broadcasts it to other browser contexts
|
|
197
300
|
*
|
|
198
|
-
*
|
|
301
|
+
* This method first processes the event through the local delegate bus,
|
|
302
|
+
* allowing all registered local handlers to process it. Then, if successful,
|
|
303
|
+
* the event is broadcasted to other tabs/windows through the messenger.
|
|
304
|
+
*
|
|
305
|
+
* Note: If broadcasting fails (e.g., due to messenger errors), the local
|
|
306
|
+
* emission is still completed and a warning is logged to console.
|
|
307
|
+
*
|
|
308
|
+
* @param event - The event data to emit and broadcast
|
|
309
|
+
* @returns Promise that resolves when local processing is complete
|
|
310
|
+
* @throws Propagates any errors from local event processing
|
|
199
311
|
*/
|
|
200
312
|
async emit(e) {
|
|
201
|
-
await this.delegate.emit(e), this.
|
|
313
|
+
await this.delegate.emit(e), this.messenger.postMessage(e);
|
|
202
314
|
}
|
|
203
315
|
/**
|
|
204
|
-
* Removes an event handler by
|
|
316
|
+
* Removes an event handler by its registered name
|
|
205
317
|
*
|
|
206
|
-
*
|
|
207
|
-
*
|
|
318
|
+
* This method delegates to the underlying event bus to remove the specified
|
|
319
|
+
* handler. The handler will no longer receive events emitted to this bus.
|
|
320
|
+
*
|
|
321
|
+
* @param name - The unique name of the handler to remove
|
|
322
|
+
* @returns true if a handler with the given name was found and removed, false otherwise
|
|
208
323
|
*/
|
|
209
324
|
off(e) {
|
|
210
325
|
return this.delegate.off(e);
|
|
211
326
|
}
|
|
212
327
|
/**
|
|
213
|
-
*
|
|
328
|
+
* Registers a new event handler with this bus
|
|
214
329
|
*
|
|
215
|
-
*
|
|
216
|
-
*
|
|
330
|
+
* The handler will receive all events emitted to this bus, both locally
|
|
331
|
+
* generated and received from other browser contexts via broadcasting.
|
|
332
|
+
*
|
|
333
|
+
* @param handler - The event handler configuration to register
|
|
334
|
+
* @returns true if the handler was successfully added, false if a handler with the same name already exists
|
|
217
335
|
*/
|
|
218
336
|
on(e) {
|
|
219
337
|
return this.delegate.on(e);
|
|
220
338
|
}
|
|
221
339
|
/**
|
|
222
|
-
* Cleans up resources
|
|
340
|
+
* Cleans up resources and stops cross-context communication
|
|
341
|
+
*
|
|
342
|
+
* This method closes the messenger connection, preventing further
|
|
343
|
+
* cross-tab communication. Local event handling continues to work
|
|
344
|
+
* through the delegate bus. After calling destroy(), the bus should
|
|
345
|
+
* not be used for broadcasting operations.
|
|
346
|
+
*
|
|
347
|
+
* Note: This does not remove event handlers or affect local event processing.
|
|
223
348
|
*/
|
|
224
349
|
destroy() {
|
|
225
|
-
this.
|
|
350
|
+
this.messenger.close();
|
|
226
351
|
}
|
|
227
352
|
}
|
|
228
|
-
class
|
|
353
|
+
class p {
|
|
229
354
|
constructor() {
|
|
230
355
|
this.namingCounter = 0;
|
|
231
356
|
}
|
|
@@ -238,14 +363,19 @@ class l {
|
|
|
238
363
|
return this.namingCounter++, `${e}_${this.namingCounter}`;
|
|
239
364
|
}
|
|
240
365
|
}
|
|
241
|
-
const
|
|
366
|
+
const b = new p();
|
|
242
367
|
export {
|
|
243
368
|
i as AbstractTypedEventBus,
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
369
|
+
h as BroadcastChannelMessenger,
|
|
370
|
+
H as BroadcastTypedEventBus,
|
|
371
|
+
p as DefaultNameGenerator,
|
|
372
|
+
y as EventBus,
|
|
373
|
+
w as ParallelTypedEventBus,
|
|
374
|
+
E as SerialTypedEventBus,
|
|
375
|
+
d as StorageMessenger,
|
|
376
|
+
m as createCrossTabMessenger,
|
|
377
|
+
g as isBroadcastChannelSupported,
|
|
378
|
+
f as isStorageEventSupported,
|
|
379
|
+
b as nameGenerator
|
|
250
380
|
};
|
|
251
381
|
//# sourceMappingURL=index.es.js.map
|
package/dist/index.es.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.es.js","sources":["../src/eventBus.ts","../src/abstractTypedEventBus.ts","../src/parallelTypedEventBus.ts","../src/serialTypedEventBus.ts","../src/broadcastTypedEventBus.ts","../src/nameGenerator.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { TypedEventBus } from './typedEventBus';\n\n/**\n * Supplier function for creating TypedEventBus instances by event type\n */\nexport type TypeEventBusSupplier = (type: EventType) => TypedEventBus<unknown>;\n\n/**\n * Generic event bus that manages multiple event types using lazy-loaded TypedEventBus instances\n *\n * @template Events - A record mapping event types to their event data types\n *\n * @example\n * ```typescript\n * const supplier = (type: EventType) => new SerialTypedEventBus(type);\n * const bus = new EventBus<{ 'user-login': string; 'order-update': number }>(supplier);\n * bus.on('user-login', { name: 'logger', order: 1, handle: (event) => console.log(event) });\n * await bus.emit('user-login', 'john-doe');\n * ```\n */\nexport class EventBus<Events extends Record<EventType, unknown>> {\n private readonly buses: Map<EventType, TypedEventBus<unknown>> = new Map();\n\n /**\n * Creates a generic event bus\n *\n * @param typeEventBusSupplier - Function to create TypedEventBus for specific event types\n */\n constructor(private readonly typeEventBusSupplier: TypeEventBusSupplier) {\n }\n\n /**\n * Adds an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to listen for\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on<Key extends EventType>(\n type: Key,\n handler: EventHandler<Events[Key]>,\n ): boolean {\n let bus = this.buses.get(type);\n if (!bus) {\n bus = this.typeEventBusSupplier(type);\n this.buses.set(type, bus);\n }\n return bus?.on(handler) ?? false;\n }\n\n /**\n * Removes an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type\n * @param name - The name of the event handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off<Key extends EventType>(\n type: Key,\n name: string,\n ): boolean {\n return this.buses.get(type)?.off(name) ?? false;\n }\n\n /**\n * Emits an event for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to emit\n * @param event - The event data\n * @returns Promise if the underlying bus is async, void otherwise\n */\n emit<Key extends EventType>(\n type: Key,\n event: Events[Key],\n ): void | Promise<void> {\n return this.buses.get(type)?.emit(event);\n }\n\n /**\n * Cleans up all managed event buses\n */\n destroy(): void {\n for (const bus of this.buses.values()) {\n bus.destroy();\n }\n this.buses.clear();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\nexport abstract class AbstractTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n protected eventHandlers: EventHandler<EVENT>[] = [];\n abstract type: EventType;\n\n /**\n * Gets a copy of all registered event handlers, sorted by order\n */\n get handlers(): EventHandler<EVENT>[] {\n return [...this.eventHandlers];\n }\n\n destroy() {\n this.eventHandlers = [];\n }\n\n protected async handleEvent(handler: EventHandler<EVENT>, event: EVENT): Promise<void> {\n try {\n handler.handle(event);\n } catch (e) {\n console.warn(`Event handler error for ${handler.name}:`, e);\n }\n }\n\n abstract emit(event: EVENT): Promise<void>;\n\n abstract off(name: string): boolean;\n\n abstract on(handler: EventHandler<EVENT>): boolean;\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { AbstractTypedEventBus } from './abstractTypedEventBus';\n\n/**\n * Parallel implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers in parallel.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new ParallelTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // Both handlers execute in parallel\n * ```\n */\nexport class ParallelTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {\n\n /**\n * Creates a parallel typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n super();\n }\n\n /**\n * Emits an event to all registered handlers in parallel\n *\n * Handlers are executed concurrently. Once-only handlers are removed after all executions complete.\n * Errors in individual handlers are logged but do not affect other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n const promises = this.eventHandlers.map(async handler => {\n await this.handleEvent(handler, event);\n if (handler.once) {\n onceHandlers.push(handler);\n }\n });\n await Promise.all(promises);\n if (onceHandlers.length > 0) {\n this.eventHandlers = this.eventHandlers.filter(\n item => !onceHandlers.includes(item),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = original.filter(item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = [...original, handler];\n return true;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { toSorted } from '@ahoo-wang/fetcher';\nimport { AbstractTypedEventBus } from './abstractTypedEventBus';\n\n/**\n * Serial implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers serially in order of priority.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new SerialTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // handler1 executes first, then handler2\n * ```\n */\nexport class SerialTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {\n\n /**\n * Creates an in-memory typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n super();\n }\n\n /**\n * Emits an event to all registered handlers serially\n *\n * Handlers are executed in order of their priority. Once-only handlers are removed after execution.\n * Errors in individual handlers are logged but do not stop other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n for (const handler of this.eventHandlers) {\n await this.handleEvent(handler, event);\n if (handler.once) {\n onceHandlers.push(handler);\n }\n }\n if (onceHandlers.length > 0) {\n this.eventHandlers = toSorted(\n this.eventHandlers.filter(item => !onceHandlers.includes(item)),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = toSorted(original, item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = toSorted([...original, handler]);\n return true;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\n/**\n * Broadcast implementation of TypedEventBus using BroadcastChannel API\n *\n * Enables cross-tab/window event broadcasting within the same origin. Events are first emitted\n * locally via the delegate, then broadcasted to other tabs/windows. Incoming broadcasts from\n * other tabs are handled by the delegate as well.\n *\n * Note: BroadcastChannel is only supported in modern browsers and requires same-origin policy.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const delegate = new SerialTypedEventBus<string>('user-events');\n * const bus = new BroadcastTypedEventBus(delegate);\n * bus.on({ name: 'user-login', order: 1, handle: (event) => console.log('User logged in:', event) });\n * await bus.emit('john-doe'); // Emits locally and broadcasts to other tabs\n * ```\n *\n * @example Custom channel name\n * ```typescript\n * const bus = new BroadcastTypedEventBus(delegate, 'my-custom-channel');\n * ```\n */\nexport class BroadcastTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n public readonly type: EventType;\n private readonly broadcastChannel: BroadcastChannel;\n\n /**\n * Creates a broadcast typed event bus\n *\n * @param delegate - The underlying TypedEventBus for local event handling\n * @param channel - Optional custom BroadcastChannel name; defaults to `_broadcast_:{type}`\n */\n constructor(\n private readonly delegate: TypedEventBus<EVENT>,\n channel?: string,\n ) {\n this.type = delegate.type;\n const channelName = channel ?? `_broadcast_:${this.type}`;\n this.broadcastChannel = new BroadcastChannel(channelName);\n this.broadcastChannel.onmessage = async event => {\n try {\n await this.delegate.emit(event.data);\n } catch (e) {\n console.warn(`Broadcast event handler error for ${this.type}:`, e);\n }\n };\n }\n\n /**\n * Gets a copy of all registered event handlers from the delegate\n */\n get handlers(): EventHandler<EVENT>[] {\n return this.delegate.handlers;\n }\n\n /**\n * Emits an event locally and broadcasts it to other tabs/windows\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n await this.delegate.emit(event);\n this.broadcastChannel.postMessage(event);\n }\n\n /**\n * Removes an event handler by name from the delegate\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n return this.delegate.off(name);\n }\n\n /**\n * Adds an event handler to the delegate\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n return this.delegate.on(handler);\n }\n\n /**\n * Cleans up resources by closing the BroadcastChannel\n */\n destroy() {\n this.broadcastChannel.close();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Interface for generating unique names with a prefix\n */\nexport interface NameGenerator {\n generate(prefix: string): string;\n}\n\n/**\n * Default implementation of NameGenerator that generates names with incrementing counters\n */\nexport class DefaultNameGenerator implements NameGenerator {\n private namingCounter: number = 0;\n\n /**\n * Generates a unique name by appending an incrementing counter to the prefix\n * @param prefix - The prefix for the generated name\n * @returns The generated unique name\n */\n generate(prefix: string): string {\n this.namingCounter++;\n return `${prefix}_${this.namingCounter}`;\n }\n}\n\n/**\n * Default instance of NameGenerator\n */\nexport const nameGenerator = new DefaultNameGenerator();\n"],"names":["EventBus","typeEventBusSupplier","type","handler","bus","name","event","AbstractTypedEventBus","e","ParallelTypedEventBus","onceHandlers","promises","item","original","SerialTypedEventBus","toSorted","BroadcastTypedEventBus","delegate","channel","channelName","DefaultNameGenerator","prefix","nameGenerator"],"mappings":";AAkCO,MAAMA,EAAoD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ/D,YAA6BC,GAA4C;AAA5C,SAAA,uBAAAA,GAP7B,KAAiB,4BAAoD,IAAA;AAAA,EAQrE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,GACEC,GACAC,GACS;AACT,QAAIC,IAAM,KAAK,MAAM,IAAIF,CAAI;AAC7B,WAAKE,MACHA,IAAM,KAAK,qBAAqBF,CAAI,GACpC,KAAK,MAAM,IAAIA,GAAME,CAAG,IAEnBA,GAAK,GAAGD,CAAO,KAAK;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,IACED,GACAG,GACS;AACT,WAAO,KAAK,MAAM,IAAIH,CAAI,GAAG,IAAIG,CAAI,KAAK;AAAA,EAC5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,KACEH,GACAI,GACsB;AACtB,WAAO,KAAK,MAAM,IAAIJ,CAAI,GAAG,KAAKI,CAAK;AAAA,EACzC;AAAA;AAAA;AAAA;AAAA,EAKA,UAAgB;AACd,eAAWF,KAAO,KAAK,MAAM,OAAA;AAC3B,MAAAA,EAAI,QAAA;AAEN,SAAK,MAAM,MAAA;AAAA,EACb;AACF;ACxFO,MAAeG,EAA6D;AAAA,EAA5E,cAAA;AACL,SAAU,gBAAuC,CAAA;AAAA,EAAC;AAAA;AAAA;AAAA;AAAA,EAMlD,IAAI,WAAkC;AACpC,WAAO,CAAC,GAAG,KAAK,aAAa;AAAA,EAC/B;AAA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W,GACxD,KAAK,iBAAiB,YAAY,OAAMb,MAAS;AAC/C,UAAI;AACF,cAAM,KAAK,SAAS,KAAKA,EAAM,IAAI;AAAA,MACrC,SAASE,GAAG;AACV,gBAAQ,KAAK,qCAAqC,KAAK,IAAI,KAAKA,CAAC;AAAA,MACnE;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,WAAkC;AACpC,WAAO,KAAK,SAAS;AAAA,EACvB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,KAAKF,GAA6B;AACtC,UAAM,KAAK,SAAS,KAAKA,CAAK,GAC9B,KAAK,iBAAiB,YAAYA,CAAK;AAAA,EACzC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,IAAID,GAAuB;AACzB,WAAO,KAAK,SAAS,IAAIA,CAAI;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,GAAGF,GAAuC;AACxC,WAAO,KAAK,SAAS,GAAGA,CAAO;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA,EAKA,UAAU;AACR,SAAK,iBAAiB,MAAA;AAAA,EACxB;AACF;ACtFO,MAAMiB,EAA8C;AAAA,EAApD,cAAA;AACL,SAAQ,gBAAwB;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOhC,SAASC,GAAwB;AAC/B,gBAAK,iBACE,GAAGA,CAAM,IAAI,KAAK,aAAa;AAAA,EACxC;AACF;AAKO,MAAMC,IAAgB,IAAIF,EAAA;"}
|
|
1
|
+
{"version":3,"file":"index.es.js","sources":["../src/eventBus.ts","../src/abstractTypedEventBus.ts","../src/parallelTypedEventBus.ts","../src/serialTypedEventBus.ts","../src/messengers/broadcastChannelMessenger.ts","../src/messengers/storageMessenger.ts","../src/messengers/crossTabMessenger.ts","../src/broadcastTypedEventBus.ts","../src/nameGenerator.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { TypedEventBus } from './typedEventBus';\n\n/**\n * Supplier function for creating TypedEventBus instances by event type\n */\nexport type TypeEventBusSupplier = (type: EventType) => TypedEventBus<unknown>;\n\n/**\n * Generic event bus that manages multiple event types using lazy-loaded TypedEventBus instances\n *\n * @template Events - A record mapping event types to their event data types\n *\n * @example\n * ```typescript\n * const supplier = (type: EventType) => new SerialTypedEventBus(type);\n * const bus = new EventBus<{ 'user-login': string; 'order-update': number }>(supplier);\n * bus.on('user-login', { name: 'logger', order: 1, handle: (event) => console.log(event) });\n * await bus.emit('user-login', 'john-doe');\n * ```\n */\nexport class EventBus<Events extends Record<EventType, unknown>> {\n private readonly buses: Map<EventType, TypedEventBus<unknown>> = new Map();\n\n /**\n * Creates a generic event bus\n *\n * @param typeEventBusSupplier - Function to create TypedEventBus for specific event types\n */\n constructor(private readonly typeEventBusSupplier: TypeEventBusSupplier) {\n }\n\n /**\n * Adds an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to listen for\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on<Key extends EventType>(\n type: Key,\n handler: EventHandler<Events[Key]>,\n ): boolean {\n let bus = this.buses.get(type);\n if (!bus) {\n bus = this.typeEventBusSupplier(type);\n this.buses.set(type, bus);\n }\n return bus?.on(handler) ?? false;\n }\n\n /**\n * Removes an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type\n * @param name - The name of the event handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off<Key extends EventType>(\n type: Key,\n name: string,\n ): boolean {\n return this.buses.get(type)?.off(name) ?? false;\n }\n\n /**\n * Emits an event for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to emit\n * @param event - The event data\n * @returns Promise if the underlying bus is async, void otherwise\n */\n emit<Key extends EventType>(\n type: Key,\n event: Events[Key],\n ): void | Promise<void> {\n return this.buses.get(type)?.emit(event);\n }\n\n /**\n * Cleans up all managed event buses\n */\n destroy(): void {\n for (const bus of this.buses.values()) {\n bus.destroy();\n }\n this.buses.clear();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\nexport abstract class AbstractTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n protected eventHandlers: EventHandler<EVENT>[] = [];\n abstract type: EventType;\n\n /**\n * Gets a copy of all registered event handlers, sorted by order\n */\n get handlers(): EventHandler<EVENT>[] {\n return [...this.eventHandlers];\n }\n\n destroy() {\n this.eventHandlers = [];\n }\n\n protected async handleEvent(handler: EventHandler<EVENT>, event: EVENT): Promise<void> {\n try {\n handler.handle(event);\n } catch (e) {\n console.warn(`Event handler error for ${handler.name}:`, e);\n }\n }\n\n abstract emit(event: EVENT): Promise<void>;\n\n abstract off(name: string): boolean;\n\n abstract on(handler: EventHandler<EVENT>): boolean;\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { AbstractTypedEventBus } from './abstractTypedEventBus';\n\n/**\n * Parallel implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers in parallel.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new ParallelTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // Both handlers execute in parallel\n * ```\n */\nexport class ParallelTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {\n\n /**\n * Creates a parallel typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n super();\n }\n\n /**\n * Emits an event to all registered handlers in parallel\n *\n * Handlers are executed concurrently. Once-only handlers are removed after all executions complete.\n * Errors in individual handlers are logged but do not affect other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n const promises = this.eventHandlers.map(async handler => {\n await this.handleEvent(handler, event);\n if (handler.once) {\n onceHandlers.push(handler);\n }\n });\n await Promise.all(promises);\n if (onceHandlers.length > 0) {\n this.eventHandlers = this.eventHandlers.filter(\n item => !onceHandlers.includes(item),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = original.filter(item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = [...original, handler];\n return true;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { toSorted } from '@ahoo-wang/fetcher';\nimport { AbstractTypedEventBus } from './abstractTypedEventBus';\n\n/**\n * Serial implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers serially in order of priority.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new SerialTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // handler1 executes first, then handler2\n * ```\n */\nexport class SerialTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {\n\n /**\n * Creates an in-memory typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n super();\n }\n\n /**\n * Emits an event to all registered handlers serially\n *\n * Handlers are executed in order of their priority. Once-only handlers are removed after execution.\n * Errors in individual handlers are logged but do not stop other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n for (const handler of this.eventHandlers) {\n await this.handleEvent(handler, event);\n if (handler.once) {\n onceHandlers.push(handler);\n }\n }\n if (onceHandlers.length > 0) {\n this.eventHandlers = toSorted(\n this.eventHandlers.filter(item => !onceHandlers.includes(item)),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = toSorted(original, item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = toSorted([...original, handler]);\n return true;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';\n\nexport class BroadcastChannelMessenger implements CrossTabMessenger {\n private readonly broadcastChannel: BroadcastChannel;\n\n constructor(channelName: string) {\n this.broadcastChannel = new BroadcastChannel(channelName);\n }\n\n postMessage(message: any): void {\n this.broadcastChannel.postMessage(message);\n }\n\n /**\n * Set the message handler for incoming messages\n *\n * @param handler - Function to handle incoming messages, or undefined to remove handler\n */\n set onmessage(handler: CrossTabMessageHandler) {\n this.broadcastChannel.onmessage = (event: MessageEvent) => {\n handler(event.data);\n };\n }\n\n /**\n * Close the messenger and clean up resources\n *\n * After calling close(), the messenger cannot be used again.\n */\n close(): void {\n this.broadcastChannel.close();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';\n\nexport interface StorageMessengerOptions {\n channelName: string;\n /** Storage instance to use. Defaults to localStorage */\n storage?: Storage;\n ttl?: number;\n cleanupInterval?: number;\n}\n\nexport interface StorageMessage {\n data: any;\n timestamp: number;\n}\n\nconst DEFAULT_TTL = 1000;\nconst DEFAULT_CLEANUP_INTERVAL = 60000;\n\nexport class StorageMessenger implements CrossTabMessenger {\n private readonly channelName: string;\n private readonly storage: Storage;\n private messageHandler?: CrossTabMessageHandler;\n private readonly messageKeyPrefix: string;\n private readonly ttl: number;\n private readonly cleanupInterval: number;\n private cleanupTimer?: number;\n private readonly storageEventHandler = (event: StorageEvent) => {\n if (\n event.storageArea !== this.storage ||\n !event.key?.startsWith(this.messageKeyPrefix) ||\n !event.newValue\n ) {\n return;\n }\n try {\n const storageMessage = JSON.parse(event.newValue) as StorageMessage;\n this.messageHandler?.(storageMessage.data);\n } catch (error) {\n console.warn('Failed to parse storage message:', error);\n }\n };\n\n constructor(options: StorageMessengerOptions) {\n this.channelName = options.channelName;\n this.storage = options.storage ?? localStorage;\n this.messageKeyPrefix = `_storage_msg_${this.channelName}`;\n this.ttl = options.ttl ?? DEFAULT_TTL;\n this.cleanupInterval = options.cleanupInterval ?? DEFAULT_CLEANUP_INTERVAL;\n this.cleanupTimer = window.setInterval(\n () => this.cleanup(),\n this.cleanupInterval,\n );\n window.addEventListener('storage', this.storageEventHandler);\n }\n\n private generateMessageKey(): string {\n return `${this.messageKeyPrefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;\n }\n\n /**\n * Send a message to other tabs/windows via localStorage\n */\n postMessage(message: any): void {\n const key = this.generateMessageKey();\n const storageMessage: StorageMessage = {\n data: message,\n timestamp: Date.now(),\n };\n this.storage.setItem(key, JSON.stringify(storageMessage));\n // Delay removal to ensure all listeners have processed the event\n setTimeout(() => this.storage.removeItem(key), this.ttl);\n }\n\n /**\n * Set the message handler for incoming messages\n */\n set onmessage(handler: CrossTabMessageHandler) {\n this.messageHandler = handler;\n }\n\n /**\n * Clean up expired messages from storage\n */\n private cleanup(): void {\n const now = Date.now();\n const keysToRemove: string[] = [];\n for (let i = 0; i < this.storage.length; i++) {\n const key = this.storage.key(i);\n if (key?.startsWith(this.messageKeyPrefix)) {\n try {\n const value = this.storage.getItem(key);\n if (value) {\n const message: StorageMessage = JSON.parse(value);\n if (now > message.timestamp + this.ttl) {\n keysToRemove.push(key);\n }\n }\n } catch {\n // Invalid data, remove it\n keysToRemove.push(key);\n }\n }\n }\n keysToRemove.forEach(key => this.storage.removeItem(key));\n }\n\n /**\n * Close the messenger and clean up resources\n */\n close(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n window.removeEventListener('storage', this.storageEventHandler);\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BroadcastChannelMessenger } from './broadcastChannelMessenger';\nimport { StorageMessenger } from './storageMessenger';\n\nexport type CrossTabMessageHandler = (message: any) => void;\n\n/**\n * Interface for cross-tab communication messengers\n *\n * Provides a unified API for different cross-tab communication mechanisms\n * like BroadcastChannel, StorageEvent, SharedWorker, etc.\n */\nexport interface CrossTabMessenger {\n /**\n * Send a message to other tabs/windows\n *\n * @param message - The data to send\n */\n postMessage(message: any): void;\n\n /**\n * Set the message handler for incoming messages\n *\n * @param handler - Function to handle incoming messages\n */\n set onmessage(handler: CrossTabMessageHandler);\n\n /**\n * Close the messenger and clean up resources\n */\n close(): void;\n}\n\nexport function isBroadcastChannelSupported(): boolean {\n return (\n typeof BroadcastChannel !== 'undefined' &&\n typeof BroadcastChannel.prototype?.postMessage === 'function'\n );\n}\n\nexport function isStorageEventSupported(): boolean {\n return (\n typeof StorageEvent !== 'undefined' &&\n typeof window !== 'undefined' &&\n typeof window.addEventListener === 'function' &&\n (typeof localStorage !== 'undefined' ||\n typeof sessionStorage !== 'undefined')\n );\n}\n\nexport function createCrossTabMessenger(\n channelName: string,\n): CrossTabMessenger | undefined {\n if (isBroadcastChannelSupported()) {\n return new BroadcastChannelMessenger(channelName);\n }\n\n if (isStorageEventSupported()) {\n return new StorageMessenger({ channelName });\n }\n\n return undefined;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\nimport { createCrossTabMessenger, CrossTabMessenger } from './messengers';\n\n/**\n * Configuration options for BroadcastTypedEventBus\n *\n * @template EVENT - The event type this bus will handle\n */\nexport interface BroadcastTypedEventBusOptions<EVENT> {\n /**\n * The underlying event bus that handles local event processing and storage.\n * This bus manages event handlers and local event emission.\n */\n delegate: TypedEventBus<EVENT>;\n\n /**\n * Optional messenger for cross-tab/window communication.\n * If not provided, a default BroadcastChannel-based messenger will be created\n * using the pattern `_broadcast_:{type}`. Must be a valid CrossTabMessenger\n * implementation when provided.\n */\n messenger?: CrossTabMessenger;\n}\n\n/**\n * Broadcast event bus that enables cross-tab/window communication\n *\n * This class extends a local TypedEventBus with cross-context broadcasting capabilities.\n * When events are emitted, they are first processed locally by the delegate bus, then\n * broadcasted to other browser contexts (tabs, windows, etc.) through the provided messenger.\n *\n * Incoming broadcast messages from other contexts are automatically forwarded to the\n * local delegate bus for processing by registered event handlers.\n *\n * @template EVENT - The event type this bus handles (must be serializable for cross-context transport)\n *\n * @example Basic usage with default messenger\n * ```typescript\n * import { SerialTypedEventBus } from './serialTypedEventBus';\n * import { BroadcastTypedEventBus } from './broadcastTypedEventBus';\n *\n * // Create local event bus\n * const delegate = new SerialTypedEventBus<string>('user-events');\n *\n * // Create broadcast event bus with default messenger\n * const bus = new BroadcastTypedEventBus({\n * delegate\n * // messenger will be auto-created as '_broadcast_:user-events'\n * });\n *\n * // Register event handler\n * bus.on({\n * name: 'user-login',\n * order: 1,\n * handle: (username: string) => console.log(`User ${username} logged in`)\n * });\n *\n * // Emit event (will be processed locally and broadcasted to other tabs)\n * await bus.emit('john-doe');\n * ```\n *\n * @example Using custom messenger\n * ```typescript\n * import { SerialTypedEventBus } from './serialTypedEventBus';\n * import { createCrossTabMessenger } from './messengers';\n * import { BroadcastTypedEventBus } from './broadcastTypedEventBus';\n *\n * // Create local event bus\n * const delegate = new SerialTypedEventBus<string>('user-events');\n *\n * // Create custom cross-tab messenger\n * const messenger = createCrossTabMessenger('my-custom-channel');\n *\n * // Create broadcast event bus\n * const bus = new BroadcastTypedEventBus({\n * delegate,\n * messenger\n * });\n *\n * // Register event handler and emit events...\n * ```\n *\n * @example Using custom messenger implementation\n * ```typescript\n * class CustomMessenger implements CrossTabMessenger {\n * // ... implementation\n * }\n *\n * const customMessenger = new CustomMessenger();\n * const bus = new BroadcastTypedEventBus({\n * delegate: new SerialTypedEventBus('events'),\n * messenger: customMessenger\n * });\n * ```\n */\nexport class BroadcastTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n public readonly type: EventType;\n private readonly delegate: TypedEventBus<EVENT>;\n private messenger: CrossTabMessenger;\n\n /**\n * Creates a new broadcast event bus with cross-context communication\n *\n * @param options - Configuration object containing delegate bus and optional messenger\n * @throws {Error} If messenger creation fails when no messenger is provided\n */\n constructor(options: BroadcastTypedEventBusOptions<EVENT>) {\n this.delegate = options.delegate;\n this.type = this.delegate.type;\n const messenger =\n options.messenger ?? createCrossTabMessenger(`_broadcast_:${this.type}`);\n if (!messenger) {\n throw new Error('Messenger setup failed');\n }\n this.messenger = messenger;\n this.messenger.onmessage = async (event: EVENT) => {\n await this.delegate.emit(event);\n };\n }\n\n /**\n * Returns a copy of all currently registered event handlers\n *\n * This getter delegates to the underlying event bus and returns the current\n * list of handlers that will process incoming events.\n *\n * @returns Array of event handlers registered with this bus\n */\n get handlers(): EventHandler<EVENT>[] {\n return this.delegate.handlers;\n }\n\n /**\n * Emits an event locally and broadcasts it to other browser contexts\n *\n * This method first processes the event through the local delegate bus,\n * allowing all registered local handlers to process it. Then, if successful,\n * the event is broadcasted to other tabs/windows through the messenger.\n *\n * Note: If broadcasting fails (e.g., due to messenger errors), the local\n * emission is still completed and a warning is logged to console.\n *\n * @param event - The event data to emit and broadcast\n * @returns Promise that resolves when local processing is complete\n * @throws Propagates any errors from local event processing\n */\n async emit(event: EVENT): Promise<void> {\n await this.delegate.emit(event);\n this.messenger.postMessage(event);\n }\n\n /**\n * Removes an event handler by its registered name\n *\n * This method delegates to the underlying event bus to remove the specified\n * handler. The handler will no longer receive events emitted to this bus.\n *\n * @param name - The unique name of the handler to remove\n * @returns true if a handler with the given name was found and removed, false otherwise\n */\n off(name: string): boolean {\n return this.delegate.off(name);\n }\n\n /**\n * Registers a new event handler with this bus\n *\n * The handler will receive all events emitted to this bus, both locally\n * generated and received from other browser contexts via broadcasting.\n *\n * @param handler - The event handler configuration to register\n * @returns true if the handler was successfully added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n return this.delegate.on(handler);\n }\n\n /**\n * Cleans up resources and stops cross-context communication\n *\n * This method closes the messenger connection, preventing further\n * cross-tab communication. Local event handling continues to work\n * through the delegate bus. After calling destroy(), the bus should\n * not be used for broadcasting operations.\n *\n * Note: This does not remove event handlers or affect local event processing.\n */\n destroy(): void {\n this.messenger.close();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Interface for generating unique names with a prefix\n */\nexport interface NameGenerator {\n generate(prefix: string): string;\n}\n\n/**\n * Default implementation of NameGenerator that generates names with incrementing counters\n */\nexport class DefaultNameGenerator implements NameGenerator {\n private namingCounter: number = 0;\n\n /**\n * Generates a unique name by appending an incrementing counter to the prefix\n * @param prefix - The prefix for the generated name\n * @returns The generated unique name\n */\n generate(prefix: string): string {\n this.namingCounter++;\n return `${prefix}_${this.namingCounter}`;\n }\n}\n\n/**\n * Default instance of NameGenerator\n */\nexport const nameGenerator = new DefaultNameGenerator();\n"],"names":["EventBus","typeEventBusSupplier","type","handler","bus","name","event","AbstractTypedEventBus","e","ParallelTypedEventBus","onceHandlers","promises","item","original","SerialTypedEventBus","toSorted","BroadcastChannelMessenger","channelName","message","DEFAULT_TTL","DEFAULT_CLEANUP_INTERVAL","StorageMessenger","options","storageMessage","error","key","now","keysToRemove","i","value","isBroadcastChannelSupported","isStorageEventSupported","createCrossTabMessenger","BroadcastTypedEventBus","messenger","DefaultNameGenerator","prefix","nameGenerator"],"mappings":";AAkCO,MAAMA,EAAoD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQ/D,YAA6BC,GAA4C;AAA5C,SAAA,uBAAAA,GAP7B,KAAiB,4BAAoD,IAAA;AAAA,EAQrE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,GACEC,GACAC,GACS;AACT,QAAIC,IAAM,KAAK,MAAM,IAAIF,CAAI;AAC7B,WAAKE,MACHA,IAAM,KAAK,qBAAqBF,CAAI,GACpC,KAAK,MAAM,IAAIA,GAAME,CAAG,IAEnBA,GAAK,GAAGD,CAAO,KAAK;AAAA,EAC7B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,IACED,GACAG,GACS;AACT,WAAO,KAAK,MAAM,IAAIH,CAAI,GAAG,IAAIG,CAAI,KAAK;AAAA,EAC5C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,KACEH,GACAI,GACsB;AACtB,WAAO,KAAK,MAAM,IAAIJ,CAAI,GAAG,KAAKI,CAAK;AAAA,EACzC;AAAA;AAAA;AAAA;AAAA,EAKA,UAAgB;AACd,eAAWF,KAAO,KAAK,MAAM,OAAA;AAC3B,MAAAA,EAAI,QAAA;AAEN,SAAK,MAAM,MAAA;AAAA,EACb;AACF;ACxFO,MAAeG,EAA6D;AAAA,EAA5E,cAAA;AACL,SAAU,gBAAuC,CAAA;AAAA,EAAC;AAAA;AAAA;AAAA;AAAA,EAMlD,IAAI,WAAkC;AACpC,WAAO,CAAC,GAAG,KAAK,aAAa;AAAA,EAC/B;AAAA,EAEA,UAAU;AACR,SAAK,gBAAgB,CAA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,GAAwB;AAC/B,gBAAK,iBACE,GAAGA,CAAM,IAAI,KAAK,aAAa;AAAA,EACxC;AACF;AAKO,MAAMC,IAAgB,IAAIF,EAAA;"}
|
package/dist/index.umd.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(n,
|
|
1
|
+
(function(n,o){typeof exports=="object"&&typeof module<"u"?o(exports,require("@ahoo-wang/fetcher")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher"],o):(n=typeof globalThis<"u"?globalThis:n||self,o(n.FetcherEventBus={},n.Fetcher))})(this,(function(n,o){"use strict";class m{constructor(e){this.typeEventBusSupplier=e,this.buses=new Map}on(e,t){let s=this.buses.get(e);return s||(s=this.typeEventBusSupplier(e),this.buses.set(e,s)),s?.on(t)??!1}off(e,t){return this.buses.get(e)?.off(t)??!1}emit(e,t){return this.buses.get(e)?.emit(t)}destroy(){for(const e of this.buses.values())e.destroy();this.buses.clear()}}class i{constructor(){this.eventHandlers=[]}get handlers(){return[...this.eventHandlers]}destroy(){this.eventHandlers=[]}async handleEvent(e,t){try{e.handle(t)}catch(s){console.warn(`Event handler error for ${e.name}:`,s)}}}class p extends i{constructor(e){super(),this.type=e}async emit(e){const t=[],s=this.eventHandlers.map(async r=>{await this.handleEvent(r,e),r.once&&t.push(r)});await Promise.all(s),t.length>0&&(this.eventHandlers=this.eventHandlers.filter(r=>!t.includes(r)))}off(e){const t=this.eventHandlers;return t.some(s=>s.name===e)?(this.eventHandlers=t.filter(s=>s.name!==e),!0):!1}on(e){const t=this.eventHandlers;return t.some(s=>s.name===e.name)?!1:(this.eventHandlers=[...t,e],!0)}}class v extends i{constructor(e){super(),this.type=e}async emit(e){const t=[];for(const s of this.eventHandlers)await this.handleEvent(s,e),s.once&&t.push(s);t.length>0&&(this.eventHandlers=o.toSorted(this.eventHandlers.filter(s=>!t.includes(s))))}off(e){const t=this.eventHandlers;return t.some(s=>s.name===e)?(this.eventHandlers=o.toSorted(t,s=>s.name!==e),!0):!1}on(e){const t=this.eventHandlers;return t.some(s=>s.name===e.name)?!1:(this.eventHandlers=o.toSorted([...t,e]),!0)}}class l{constructor(e){this.broadcastChannel=new BroadcastChannel(e)}postMessage(e){this.broadcastChannel.postMessage(e)}set onmessage(e){this.broadcastChannel.onmessage=t=>{e(t.data)}}close(){this.broadcastChannel.close()}}const y=1e3,w=6e4;class h{constructor(e){this.storageEventHandler=t=>{if(!(t.storageArea!==this.storage||!t.key?.startsWith(this.messageKeyPrefix)||!t.newValue))try{const s=JSON.parse(t.newValue);this.messageHandler?.(s.data)}catch(s){console.warn("Failed to parse storage message:",s)}},this.channelName=e.channelName,this.storage=e.storage??localStorage,this.messageKeyPrefix=`_storage_msg_${this.channelName}`,this.ttl=e.ttl??y,this.cleanupInterval=e.cleanupInterval??w,this.cleanupTimer=window.setInterval(()=>this.cleanup(),this.cleanupInterval),window.addEventListener("storage",this.storageEventHandler)}generateMessageKey(){return`${this.messageKeyPrefix}_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}postMessage(e){const t=this.generateMessageKey(),s={data:e,timestamp:Date.now()};this.storage.setItem(t,JSON.stringify(s)),setTimeout(()=>this.storage.removeItem(t),this.ttl)}set onmessage(e){this.messageHandler=e}cleanup(){const e=Date.now(),t=[];for(let s=0;s<this.storage.length;s++){const r=this.storage.key(s);if(r?.startsWith(this.messageKeyPrefix))try{const f=this.storage.getItem(r);if(f){const H=JSON.parse(f);e>H.timestamp+this.ttl&&t.push(r)}}catch{t.push(r)}}t.forEach(s=>this.storage.removeItem(s))}close(){this.cleanupTimer&&clearInterval(this.cleanupTimer),window.removeEventListener("storage",this.storageEventHandler)}}function c(){return typeof BroadcastChannel<"u"&&typeof BroadcastChannel.prototype?.postMessage=="function"}function d(){return typeof StorageEvent<"u"&&typeof window<"u"&&typeof window.addEventListener=="function"&&(typeof localStorage<"u"||typeof sessionStorage<"u")}function u(a){if(c())return new l(a);if(d())return new h({channelName:a})}class E{constructor(e){this.delegate=e.delegate,this.type=this.delegate.type;const t=e.messenger??u(`_broadcast_:${this.type}`);if(!t)throw new Error("Messenger setup failed");this.messenger=t,this.messenger.onmessage=async s=>{await this.delegate.emit(s)}}get handlers(){return this.delegate.handlers}async emit(e){await this.delegate.emit(e),this.messenger.postMessage(e)}off(e){return this.delegate.off(e)}on(e){return this.delegate.on(e)}destroy(){this.messenger.close()}}class g{constructor(){this.namingCounter=0}generate(e){return this.namingCounter++,`${e}_${this.namingCounter}`}}const S=new g;n.AbstractTypedEventBus=i,n.BroadcastChannelMessenger=l,n.BroadcastTypedEventBus=E,n.DefaultNameGenerator=g,n.EventBus=m,n.ParallelTypedEventBus=p,n.SerialTypedEventBus=v,n.StorageMessenger=h,n.createCrossTabMessenger=u,n.isBroadcastChannelSupported=c,n.isStorageEventSupported=d,n.nameGenerator=S,Object.defineProperty(n,Symbol.toStringTag,{value:"Module"})}));
|
|
2
2
|
//# sourceMappingURL=index.umd.js.map
|
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","sources":["../src/eventBus.ts","../src/abstractTypedEventBus.ts","../src/parallelTypedEventBus.ts","../src/serialTypedEventBus.ts","../src/broadcastTypedEventBus.ts","../src/nameGenerator.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { TypedEventBus } from './typedEventBus';\n\n/**\n * Supplier function for creating TypedEventBus instances by event type\n */\nexport type TypeEventBusSupplier = (type: EventType) => TypedEventBus<unknown>;\n\n/**\n * Generic event bus that manages multiple event types using lazy-loaded TypedEventBus instances\n *\n * @template Events - A record mapping event types to their event data types\n *\n * @example\n * ```typescript\n * const supplier = (type: EventType) => new SerialTypedEventBus(type);\n * const bus = new EventBus<{ 'user-login': string; 'order-update': number }>(supplier);\n * bus.on('user-login', { name: 'logger', order: 1, handle: (event) => console.log(event) });\n * await bus.emit('user-login', 'john-doe');\n * ```\n */\nexport class EventBus<Events extends Record<EventType, unknown>> {\n private readonly buses: Map<EventType, TypedEventBus<unknown>> = new Map();\n\n /**\n * Creates a generic event bus\n *\n * @param typeEventBusSupplier - Function to create TypedEventBus for specific event types\n */\n constructor(private readonly typeEventBusSupplier: TypeEventBusSupplier) {\n }\n\n /**\n * Adds an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to listen for\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on<Key extends EventType>(\n type: Key,\n handler: EventHandler<Events[Key]>,\n ): boolean {\n let bus = this.buses.get(type);\n if (!bus) {\n bus = this.typeEventBusSupplier(type);\n this.buses.set(type, bus);\n }\n return bus?.on(handler) ?? false;\n }\n\n /**\n * Removes an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type\n * @param name - The name of the event handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off<Key extends EventType>(\n type: Key,\n name: string,\n ): boolean {\n return this.buses.get(type)?.off(name) ?? false;\n }\n\n /**\n * Emits an event for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to emit\n * @param event - The event data\n * @returns Promise if the underlying bus is async, void otherwise\n */\n emit<Key extends EventType>(\n type: Key,\n event: Events[Key],\n ): void | Promise<void> {\n return this.buses.get(type)?.emit(event);\n }\n\n /**\n * Cleans up all managed event buses\n */\n destroy(): void {\n for (const bus of this.buses.values()) {\n bus.destroy();\n }\n this.buses.clear();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\nexport abstract class AbstractTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n protected eventHandlers: EventHandler<EVENT>[] = [];\n abstract type: EventType;\n\n /**\n * Gets a copy of all registered event handlers, sorted by order\n */\n get handlers(): EventHandler<EVENT>[] {\n return [...this.eventHandlers];\n }\n\n destroy() {\n this.eventHandlers = [];\n }\n\n protected async handleEvent(handler: EventHandler<EVENT>, event: EVENT): Promise<void> {\n try {\n handler.handle(event);\n } catch (e) {\n console.warn(`Event handler error for ${handler.name}:`, e);\n }\n }\n\n abstract emit(event: EVENT): Promise<void>;\n\n abstract off(name: string): boolean;\n\n abstract on(handler: EventHandler<EVENT>): boolean;\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { AbstractTypedEventBus } from './abstractTypedEventBus';\n\n/**\n * Parallel implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers in parallel.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new ParallelTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // Both handlers execute in parallel\n * ```\n */\nexport class ParallelTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {\n\n /**\n * Creates a parallel typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n super();\n }\n\n /**\n * Emits an event to all registered handlers in parallel\n *\n * Handlers are executed concurrently. Once-only handlers are removed after all executions complete.\n * Errors in individual handlers are logged but do not affect other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n const promises = this.eventHandlers.map(async handler => {\n await this.handleEvent(handler, event);\n if (handler.once) {\n onceHandlers.push(handler);\n }\n });\n await Promise.all(promises);\n if (onceHandlers.length > 0) {\n this.eventHandlers = this.eventHandlers.filter(\n item => !onceHandlers.includes(item),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = original.filter(item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = [...original, handler];\n return true;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { toSorted } from '@ahoo-wang/fetcher';\nimport { AbstractTypedEventBus } from './abstractTypedEventBus';\n\n/**\n * Serial implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers serially in order of priority.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new SerialTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // handler1 executes first, then handler2\n * ```\n */\nexport class SerialTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {\n\n /**\n * Creates an in-memory typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n super();\n }\n\n /**\n * Emits an event to all registered handlers serially\n *\n * Handlers are executed in order of their priority. Once-only handlers are removed after execution.\n * Errors in individual handlers are logged but do not stop other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n for (const handler of this.eventHandlers) {\n await this.handleEvent(handler, event);\n if (handler.once) {\n onceHandlers.push(handler);\n }\n }\n if (onceHandlers.length > 0) {\n this.eventHandlers = toSorted(\n this.eventHandlers.filter(item => !onceHandlers.includes(item)),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = toSorted(original, item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = toSorted([...original, handler]);\n return true;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\n/**\n * Broadcast implementation of TypedEventBus using BroadcastChannel API\n *\n * Enables cross-tab/window event broadcasting within the same origin. Events are first emitted\n * locally via the delegate, then broadcasted to other tabs/windows. Incoming broadcasts from\n * other tabs are handled by the delegate as well.\n *\n * Note: BroadcastChannel is only supported in modern browsers and requires same-origin policy.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const delegate = new SerialTypedEventBus<string>('user-events');\n * const bus = new BroadcastTypedEventBus(delegate);\n * bus.on({ name: 'user-login', order: 1, handle: (event) => console.log('User logged in:', event) });\n * await bus.emit('john-doe'); // Emits locally and broadcasts to other tabs\n * ```\n *\n * @example Custom channel name\n * ```typescript\n * const bus = new BroadcastTypedEventBus(delegate, 'my-custom-channel');\n * ```\n */\nexport class BroadcastTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n public readonly type: EventType;\n private readonly broadcastChannel: BroadcastChannel;\n\n /**\n * Creates a broadcast typed event bus\n *\n * @param delegate - The underlying TypedEventBus for local event handling\n * @param channel - Optional custom BroadcastChannel name; defaults to `_broadcast_:{type}`\n */\n constructor(\n private readonly delegate: TypedEventBus<EVENT>,\n channel?: string,\n ) {\n this.type = delegate.type;\n const channelName = channel ?? `_broadcast_:${this.type}`;\n this.broadcastChannel = new BroadcastChannel(channelName);\n this.broadcastChannel.onmessage = async event => {\n try {\n await this.delegate.emit(event.data);\n } catch (e) {\n console.warn(`Broadcast event handler error for ${this.type}:`, e);\n }\n };\n }\n\n /**\n * Gets a copy of all registered event handlers from the delegate\n */\n get handlers(): EventHandler<EVENT>[] {\n return this.delegate.handlers;\n }\n\n /**\n * Emits an event locally and broadcasts it to other tabs/windows\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n await this.delegate.emit(event);\n this.broadcastChannel.postMessage(event);\n }\n\n /**\n * Removes an event handler by name from the delegate\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n return this.delegate.off(name);\n }\n\n /**\n * Adds an event handler to the delegate\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n return this.delegate.on(handler);\n }\n\n /**\n * Cleans up resources by closing the BroadcastChannel\n */\n destroy() {\n this.broadcastChannel.close();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Interface for generating unique names with a prefix\n */\nexport interface NameGenerator {\n generate(prefix: string): string;\n}\n\n/**\n * Default implementation of NameGenerator that generates names with incrementing counters\n */\nexport class DefaultNameGenerator implements NameGenerator {\n private namingCounter: number = 0;\n\n /**\n * Generates a unique name by appending an incrementing counter to the prefix\n * @param prefix - The prefix for the generated name\n * @returns The generated unique name\n */\n generate(prefix: string): string {\n this.namingCounter++;\n return `${prefix}_${this.namingCounter}`;\n }\n}\n\n/**\n * Default instance of NameGenerator\n */\nexport const nameGenerator = new DefaultNameGenerator();\n"],"names":["EventBus","typeEventBusSupplier","type","handler","bus","name","event","AbstractTypedEventBus","e","ParallelTypedEventBus","onceHandlers","promises","item","original","SerialTypedEventBus","toSorted","BroadcastTypedEventBus","delegate","channel","channelName","DefaultNameGenerator","prefix","nameGenerator"],"mappings":"uSAkCO,MAAMA,CAAoD,CAQ/D,YAA6BC,EAA4C,CAA5C,KAAA,qBAAAA,EAP7B,KAAiB,UAAoD,GAQrE,CAUA,GACEC,EACAC,EACS,CACT,IAAIC,EAAM,KAAK,MAAM,IAAIF,CAAI,EAC7B,OAAKE,IACHA,EAAM,KAAK,qBAAqBF,CAAI,EACpC,KAAK,MAAM,IAAIA,EAAME,CAAG,GAEnBA,GAAK,GAAGD,CAAO,GAAK,EAC7B,CAUA,IACED,EACAG,EACS,CACT,OAAO,KAAK,MAAM,IAAIH,CAAI,GAAG,IAAIG,CAAI,GAAK,EAC5C,CAUA,KACEH,EACAI,EACsB,CACtB,OAAO,KAAK,MAAM,IAAIJ,CAAI,GAAG,KAAKI,CAAK,CACzC,CAKA,SAAgB,CACd,UAAWF,KAAO,KAAK,MAAM,OAAA,EAC3BA,EAAI,QAAA,EAEN,KAAK,MAAM,MAAA,CACb,CACF,CCxFO,MAAeG,CAA6D,CAA5E,aAAA,CACL,KAAU,cAAuC,CAAA,CAAC,CAMlD,IAAI,UAAkC,CACpC,MAAO,CAAC,GAAG,KAAK,aAAa,CAC/B,CAEA,SAAU,CACR,KAAK,cAAgB,CAAA,CACvB,CAEA,MAAgB,YAAYJ,EAA8BG,EAA6B,CACrF,GAAI,CACFH,EAAQ,OAAOG,CAAK,CACtB,OAASE,EAAG,CACV,QAAQ,KAAK,2BAA2BL,EAAQ,IAAI,IAAKK,CAAC,CAC5D,CACF,CAOF,CCZO,MAAMC,UAAq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AA,SAASF,EAAUD,GAAQA,EAAK,OAASP,CAAI,EAC3D,IAHE,EAIX,CAUA,GAAGF,EAAuC,CACxC,MAAMU,EAAW,KAAK,cACtB,OAAIA,EAAS,KAAKD,GAAQA,EAAK,OAAST,EAAQ,IAAI,EAC3C,IAET,KAAK,cAAgBY,EAAAA,SAAS,CAAC,GAAGF,EAAUV,CAAO,CAAC,EAC7C,GACT,CACF,CC1DO,MAAMa,CAA8D,CAUzE,YACmBC,EACjBC,EACA,CAFiB,KAAA,SAAAD,EAGjB,KAAK,KAAOA,EAAS,KACrB,MAAME,EAAcD,GAAW,eAAe,KAAK,IAAI,GACvD,KAAK,iBAAmB,IAAI,iBAAiBC,CAAW,EACxD,KAAK,iBAAiB,UAAY,MAAMb,GAAS,CAC/C,GAAI,CACF,MAAM,KAAK,SAAS,KAAKA,EAAM,IAAI,CACrC,OAASE,EAAG,CACV,QAAQ,KAAK,qCAAqC,KAAK,IAAI,IAAKA,CAAC,CACnE,CACF,CACF,CAKA,IAAI,UAAkC,CACpC,OAAO,KAAK,SAAS,QACvB,CAOA,MAAM,KAAKF,EAA6B,CACtC,MAAM,KAAK,SAAS,KAAKA,CAAK,EAC9B,KAAK,iBAAiB,YAAYA,CAAK,CACzC,CAQA,IAAID,EAAuB,CACzB,OAAO,KAAK,SAAS,IAAIA,CAAI,CAC/B,CAQA,GAAGF,EAAuC,CACxC,OAAO,KAAK,SAAS,GAAGA,CAAO,CACjC,CAKA,SAAU,CACR,KAAK,iBAAiB,MAAA,CACxB,CACF,CCtFO,MAAMiB,CAA8C,CAApD,aAAA,CACL,KAAQ,cAAwB,CAAA,CAOhC,SAASC,EAAwB,CAC/B,YAAK,gBACE,GAAGA,CAAM,IAAI,KAAK,aAAa,EACxC,CACF,CAKO,MAAMC,EAAgB,IAAIF"}
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../src/eventBus.ts","../src/abstractTypedEventBus.ts","../src/parallelTypedEventBus.ts","../src/serialTypedEventBus.ts","../src/messengers/broadcastChannelMessenger.ts","../src/messengers/storageMessenger.ts","../src/messengers/crossTabMessenger.ts","../src/broadcastTypedEventBus.ts","../src/nameGenerator.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { TypedEventBus } from './typedEventBus';\n\n/**\n * Supplier function for creating TypedEventBus instances by event type\n */\nexport type TypeEventBusSupplier = (type: EventType) => TypedEventBus<unknown>;\n\n/**\n * Generic event bus that manages multiple event types using lazy-loaded TypedEventBus instances\n *\n * @template Events - A record mapping event types to their event data types\n *\n * @example\n * ```typescript\n * const supplier = (type: EventType) => new SerialTypedEventBus(type);\n * const bus = new EventBus<{ 'user-login': string; 'order-update': number }>(supplier);\n * bus.on('user-login', { name: 'logger', order: 1, handle: (event) => console.log(event) });\n * await bus.emit('user-login', 'john-doe');\n * ```\n */\nexport class EventBus<Events extends Record<EventType, unknown>> {\n private readonly buses: Map<EventType, TypedEventBus<unknown>> = new Map();\n\n /**\n * Creates a generic event bus\n *\n * @param typeEventBusSupplier - Function to create TypedEventBus for specific event types\n */\n constructor(private readonly typeEventBusSupplier: TypeEventBusSupplier) {\n }\n\n /**\n * Adds an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to listen for\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on<Key extends EventType>(\n type: Key,\n handler: EventHandler<Events[Key]>,\n ): boolean {\n let bus = this.buses.get(type);\n if (!bus) {\n bus = this.typeEventBusSupplier(type);\n this.buses.set(type, bus);\n }\n return bus?.on(handler) ?? false;\n }\n\n /**\n * Removes an event handler for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type\n * @param name - The name of the event handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off<Key extends EventType>(\n type: Key,\n name: string,\n ): boolean {\n return this.buses.get(type)?.off(name) ?? false;\n }\n\n /**\n * Emits an event for a specific event type\n *\n * @template Key - The event type\n * @param type - The event type to emit\n * @param event - The event data\n * @returns Promise if the underlying bus is async, void otherwise\n */\n emit<Key extends EventType>(\n type: Key,\n event: Events[Key],\n ): void | Promise<void> {\n return this.buses.get(type)?.emit(event);\n }\n\n /**\n * Cleans up all managed event buses\n */\n destroy(): void {\n for (const bus of this.buses.values()) {\n bus.destroy();\n }\n this.buses.clear();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\n\nexport abstract class AbstractTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n protected eventHandlers: EventHandler<EVENT>[] = [];\n abstract type: EventType;\n\n /**\n * Gets a copy of all registered event handlers, sorted by order\n */\n get handlers(): EventHandler<EVENT>[] {\n return [...this.eventHandlers];\n }\n\n destroy() {\n this.eventHandlers = [];\n }\n\n protected async handleEvent(handler: EventHandler<EVENT>, event: EVENT): Promise<void> {\n try {\n handler.handle(event);\n } catch (e) {\n console.warn(`Event handler error for ${handler.name}:`, e);\n }\n }\n\n abstract emit(event: EVENT): Promise<void>;\n\n abstract off(name: string): boolean;\n\n abstract on(handler: EventHandler<EVENT>): boolean;\n}","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { AbstractTypedEventBus } from './abstractTypedEventBus';\n\n/**\n * Parallel implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers in parallel.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new ParallelTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // Both handlers execute in parallel\n * ```\n */\nexport class ParallelTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {\n\n /**\n * Creates a parallel typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n super();\n }\n\n /**\n * Emits an event to all registered handlers in parallel\n *\n * Handlers are executed concurrently. Once-only handlers are removed after all executions complete.\n * Errors in individual handlers are logged but do not affect other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n const promises = this.eventHandlers.map(async handler => {\n await this.handleEvent(handler, event);\n if (handler.once) {\n onceHandlers.push(handler);\n }\n });\n await Promise.all(promises);\n if (onceHandlers.length > 0) {\n this.eventHandlers = this.eventHandlers.filter(\n item => !onceHandlers.includes(item),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = original.filter(item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = [...original, handler];\n return true;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { EventHandler, EventType } from './types';\nimport { toSorted } from '@ahoo-wang/fetcher';\nimport { AbstractTypedEventBus } from './abstractTypedEventBus';\n\n/**\n * Serial implementation of TypedEventBus\n *\n * Provides an in-memory event bus that executes event handlers serially in order of priority.\n * Supports ordering and once-only execution of handlers.\n *\n * @template EVENT - The type of events this bus handles\n *\n * @example\n * ```typescript\n * const bus = new SerialTypedEventBus<string>('test');\n * bus.on({ name: 'handler1', order: 1, handle: (event) => console.log(event) });\n * bus.on({ name: 'handler2', order: 2, handle: (event) => console.log('second', event) });\n * await bus.emit('hello'); // handler1 executes first, then handler2\n * ```\n */\nexport class SerialTypedEventBus<EVENT> extends AbstractTypedEventBus<EVENT> {\n\n /**\n * Creates an in-memory typed event bus\n *\n * @param type - The event type identifier for this bus\n */\n constructor(public readonly type: EventType) {\n super();\n }\n\n /**\n * Emits an event to all registered handlers serially\n *\n * Handlers are executed in order of their priority. Once-only handlers are removed after execution.\n * Errors in individual handlers are logged but do not stop other handlers.\n *\n * @param event - The event to emit\n */\n async emit(event: EVENT): Promise<void> {\n const onceHandlers: EventHandler<EVENT>[] = [];\n for (const handler of this.eventHandlers) {\n await this.handleEvent(handler, event);\n if (handler.once) {\n onceHandlers.push(handler);\n }\n }\n if (onceHandlers.length > 0) {\n this.eventHandlers = toSorted(\n this.eventHandlers.filter(item => !onceHandlers.includes(item)),\n );\n }\n }\n\n /**\n * Removes an event handler by name\n *\n * @param name - The name of the handler to remove\n * @returns true if a handler was removed, false otherwise\n */\n off(name: string): boolean {\n const original = this.eventHandlers;\n if (!original.some(item => item.name === name)) {\n return false;\n }\n this.eventHandlers = toSorted(original, item => item.name !== name);\n return true;\n }\n\n /**\n * Adds an event handler if not already present\n *\n * Handlers are sorted by their order property after addition.\n *\n * @param handler - The event handler to add\n * @returns true if the handler was added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n const original = this.eventHandlers;\n if (original.some(item => item.name === handler.name)) {\n return false;\n }\n this.eventHandlers = toSorted([...original, handler]);\n return true;\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';\n\nexport class BroadcastChannelMessenger implements CrossTabMessenger {\n private readonly broadcastChannel: BroadcastChannel;\n\n constructor(channelName: string) {\n this.broadcastChannel = new BroadcastChannel(channelName);\n }\n\n postMessage(message: any): void {\n this.broadcastChannel.postMessage(message);\n }\n\n /**\n * Set the message handler for incoming messages\n *\n * @param handler - Function to handle incoming messages, or undefined to remove handler\n */\n set onmessage(handler: CrossTabMessageHandler) {\n this.broadcastChannel.onmessage = (event: MessageEvent) => {\n handler(event.data);\n };\n }\n\n /**\n * Close the messenger and clean up resources\n *\n * After calling close(), the messenger cannot be used again.\n */\n close(): void {\n this.broadcastChannel.close();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';\n\nexport interface StorageMessengerOptions {\n channelName: string;\n /** Storage instance to use. Defaults to localStorage */\n storage?: Storage;\n ttl?: number;\n cleanupInterval?: number;\n}\n\nexport interface StorageMessage {\n data: any;\n timestamp: number;\n}\n\nconst DEFAULT_TTL = 1000;\nconst DEFAULT_CLEANUP_INTERVAL = 60000;\n\nexport class StorageMessenger implements CrossTabMessenger {\n private readonly channelName: string;\n private readonly storage: Storage;\n private messageHandler?: CrossTabMessageHandler;\n private readonly messageKeyPrefix: string;\n private readonly ttl: number;\n private readonly cleanupInterval: number;\n private cleanupTimer?: number;\n private readonly storageEventHandler = (event: StorageEvent) => {\n if (\n event.storageArea !== this.storage ||\n !event.key?.startsWith(this.messageKeyPrefix) ||\n !event.newValue\n ) {\n return;\n }\n try {\n const storageMessage = JSON.parse(event.newValue) as StorageMessage;\n this.messageHandler?.(storageMessage.data);\n } catch (error) {\n console.warn('Failed to parse storage message:', error);\n }\n };\n\n constructor(options: StorageMessengerOptions) {\n this.channelName = options.channelName;\n this.storage = options.storage ?? localStorage;\n this.messageKeyPrefix = `_storage_msg_${this.channelName}`;\n this.ttl = options.ttl ?? DEFAULT_TTL;\n this.cleanupInterval = options.cleanupInterval ?? DEFAULT_CLEANUP_INTERVAL;\n this.cleanupTimer = window.setInterval(\n () => this.cleanup(),\n this.cleanupInterval,\n );\n window.addEventListener('storage', this.storageEventHandler);\n }\n\n private generateMessageKey(): string {\n return `${this.messageKeyPrefix}_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`;\n }\n\n /**\n * Send a message to other tabs/windows via localStorage\n */\n postMessage(message: any): void {\n const key = this.generateMessageKey();\n const storageMessage: StorageMessage = {\n data: message,\n timestamp: Date.now(),\n };\n this.storage.setItem(key, JSON.stringify(storageMessage));\n // Delay removal to ensure all listeners have processed the event\n setTimeout(() => this.storage.removeItem(key), this.ttl);\n }\n\n /**\n * Set the message handler for incoming messages\n */\n set onmessage(handler: CrossTabMessageHandler) {\n this.messageHandler = handler;\n }\n\n /**\n * Clean up expired messages from storage\n */\n private cleanup(): void {\n const now = Date.now();\n const keysToRemove: string[] = [];\n for (let i = 0; i < this.storage.length; i++) {\n const key = this.storage.key(i);\n if (key?.startsWith(this.messageKeyPrefix)) {\n try {\n const value = this.storage.getItem(key);\n if (value) {\n const message: StorageMessage = JSON.parse(value);\n if (now > message.timestamp + this.ttl) {\n keysToRemove.push(key);\n }\n }\n } catch {\n // Invalid data, remove it\n keysToRemove.push(key);\n }\n }\n }\n keysToRemove.forEach(key => this.storage.removeItem(key));\n }\n\n /**\n * Close the messenger and clean up resources\n */\n close(): void {\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n }\n window.removeEventListener('storage', this.storageEventHandler);\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BroadcastChannelMessenger } from './broadcastChannelMessenger';\nimport { StorageMessenger } from './storageMessenger';\n\nexport type CrossTabMessageHandler = (message: any) => void;\n\n/**\n * Interface for cross-tab communication messengers\n *\n * Provides a unified API for different cross-tab communication mechanisms\n * like BroadcastChannel, StorageEvent, SharedWorker, etc.\n */\nexport interface CrossTabMessenger {\n /**\n * Send a message to other tabs/windows\n *\n * @param message - The data to send\n */\n postMessage(message: any): void;\n\n /**\n * Set the message handler for incoming messages\n *\n * @param handler - Function to handle incoming messages\n */\n set onmessage(handler: CrossTabMessageHandler);\n\n /**\n * Close the messenger and clean up resources\n */\n close(): void;\n}\n\nexport function isBroadcastChannelSupported(): boolean {\n return (\n typeof BroadcastChannel !== 'undefined' &&\n typeof BroadcastChannel.prototype?.postMessage === 'function'\n );\n}\n\nexport function isStorageEventSupported(): boolean {\n return (\n typeof StorageEvent !== 'undefined' &&\n typeof window !== 'undefined' &&\n typeof window.addEventListener === 'function' &&\n (typeof localStorage !== 'undefined' ||\n typeof sessionStorage !== 'undefined')\n );\n}\n\nexport function createCrossTabMessenger(\n channelName: string,\n): CrossTabMessenger | undefined {\n if (isBroadcastChannelSupported()) {\n return new BroadcastChannelMessenger(channelName);\n }\n\n if (isStorageEventSupported()) {\n return new StorageMessenger({ channelName });\n }\n\n return undefined;\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TypedEventBus } from './typedEventBus';\nimport { EventHandler, EventType } from './types';\nimport { createCrossTabMessenger, CrossTabMessenger } from './messengers';\n\n/**\n * Configuration options for BroadcastTypedEventBus\n *\n * @template EVENT - The event type this bus will handle\n */\nexport interface BroadcastTypedEventBusOptions<EVENT> {\n /**\n * The underlying event bus that handles local event processing and storage.\n * This bus manages event handlers and local event emission.\n */\n delegate: TypedEventBus<EVENT>;\n\n /**\n * Optional messenger for cross-tab/window communication.\n * If not provided, a default BroadcastChannel-based messenger will be created\n * using the pattern `_broadcast_:{type}`. Must be a valid CrossTabMessenger\n * implementation when provided.\n */\n messenger?: CrossTabMessenger;\n}\n\n/**\n * Broadcast event bus that enables cross-tab/window communication\n *\n * This class extends a local TypedEventBus with cross-context broadcasting capabilities.\n * When events are emitted, they are first processed locally by the delegate bus, then\n * broadcasted to other browser contexts (tabs, windows, etc.) through the provided messenger.\n *\n * Incoming broadcast messages from other contexts are automatically forwarded to the\n * local delegate bus for processing by registered event handlers.\n *\n * @template EVENT - The event type this bus handles (must be serializable for cross-context transport)\n *\n * @example Basic usage with default messenger\n * ```typescript\n * import { SerialTypedEventBus } from './serialTypedEventBus';\n * import { BroadcastTypedEventBus } from './broadcastTypedEventBus';\n *\n * // Create local event bus\n * const delegate = new SerialTypedEventBus<string>('user-events');\n *\n * // Create broadcast event bus with default messenger\n * const bus = new BroadcastTypedEventBus({\n * delegate\n * // messenger will be auto-created as '_broadcast_:user-events'\n * });\n *\n * // Register event handler\n * bus.on({\n * name: 'user-login',\n * order: 1,\n * handle: (username: string) => console.log(`User ${username} logged in`)\n * });\n *\n * // Emit event (will be processed locally and broadcasted to other tabs)\n * await bus.emit('john-doe');\n * ```\n *\n * @example Using custom messenger\n * ```typescript\n * import { SerialTypedEventBus } from './serialTypedEventBus';\n * import { createCrossTabMessenger } from './messengers';\n * import { BroadcastTypedEventBus } from './broadcastTypedEventBus';\n *\n * // Create local event bus\n * const delegate = new SerialTypedEventBus<string>('user-events');\n *\n * // Create custom cross-tab messenger\n * const messenger = createCrossTabMessenger('my-custom-channel');\n *\n * // Create broadcast event bus\n * const bus = new BroadcastTypedEventBus({\n * delegate,\n * messenger\n * });\n *\n * // Register event handler and emit events...\n * ```\n *\n * @example Using custom messenger implementation\n * ```typescript\n * class CustomMessenger implements CrossTabMessenger {\n * // ... implementation\n * }\n *\n * const customMessenger = new CustomMessenger();\n * const bus = new BroadcastTypedEventBus({\n * delegate: new SerialTypedEventBus('events'),\n * messenger: customMessenger\n * });\n * ```\n */\nexport class BroadcastTypedEventBus<EVENT> implements TypedEventBus<EVENT> {\n public readonly type: EventType;\n private readonly delegate: TypedEventBus<EVENT>;\n private messenger: CrossTabMessenger;\n\n /**\n * Creates a new broadcast event bus with cross-context communication\n *\n * @param options - Configuration object containing delegate bus and optional messenger\n * @throws {Error} If messenger creation fails when no messenger is provided\n */\n constructor(options: BroadcastTypedEventBusOptions<EVENT>) {\n this.delegate = options.delegate;\n this.type = this.delegate.type;\n const messenger =\n options.messenger ?? createCrossTabMessenger(`_broadcast_:${this.type}`);\n if (!messenger) {\n throw new Error('Messenger setup failed');\n }\n this.messenger = messenger;\n this.messenger.onmessage = async (event: EVENT) => {\n await this.delegate.emit(event);\n };\n }\n\n /**\n * Returns a copy of all currently registered event handlers\n *\n * This getter delegates to the underlying event bus and returns the current\n * list of handlers that will process incoming events.\n *\n * @returns Array of event handlers registered with this bus\n */\n get handlers(): EventHandler<EVENT>[] {\n return this.delegate.handlers;\n }\n\n /**\n * Emits an event locally and broadcasts it to other browser contexts\n *\n * This method first processes the event through the local delegate bus,\n * allowing all registered local handlers to process it. Then, if successful,\n * the event is broadcasted to other tabs/windows through the messenger.\n *\n * Note: If broadcasting fails (e.g., due to messenger errors), the local\n * emission is still completed and a warning is logged to console.\n *\n * @param event - The event data to emit and broadcast\n * @returns Promise that resolves when local processing is complete\n * @throws Propagates any errors from local event processing\n */\n async emit(event: EVENT): Promise<void> {\n await this.delegate.emit(event);\n this.messenger.postMessage(event);\n }\n\n /**\n * Removes an event handler by its registered name\n *\n * This method delegates to the underlying event bus to remove the specified\n * handler. The handler will no longer receive events emitted to this bus.\n *\n * @param name - The unique name of the handler to remove\n * @returns true if a handler with the given name was found and removed, false otherwise\n */\n off(name: string): boolean {\n return this.delegate.off(name);\n }\n\n /**\n * Registers a new event handler with this bus\n *\n * The handler will receive all events emitted to this bus, both locally\n * generated and received from other browser contexts via broadcasting.\n *\n * @param handler - The event handler configuration to register\n * @returns true if the handler was successfully added, false if a handler with the same name already exists\n */\n on(handler: EventHandler<EVENT>): boolean {\n return this.delegate.on(handler);\n }\n\n /**\n * Cleans up resources and stops cross-context communication\n *\n * This method closes the messenger connection, preventing further\n * cross-tab communication. Local event handling continues to work\n * through the delegate bus. After calling destroy(), the bus should\n * not be used for broadcasting operations.\n *\n * Note: This does not remove event handlers or affect local event processing.\n */\n destroy(): void {\n this.messenger.close();\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Interface for generating unique names with a prefix\n */\nexport interface NameGenerator {\n generate(prefix: string): string;\n}\n\n/**\n * Default implementation of NameGenerator that generates names with incrementing counters\n */\nexport class DefaultNameGenerator implements NameGenerator {\n private namingCounter: number = 0;\n\n /**\n * Generates a unique name by appending an incrementing counter to the prefix\n * @param prefix - The prefix for the generated name\n * @returns The generated unique name\n */\n generate(prefix: string): string {\n this.namingCounter++;\n return `${prefix}_${this.namingCounter}`;\n }\n}\n\n/**\n * Default instance of NameGenerator\n */\nexport const nameGenerator = new DefaultNameGenerator();\n"],"names":["EventBus","typeEventBusSupplier","type","handler","bus","name","event","AbstractTypedEventBus","e","ParallelTypedEventBus","onceHandlers","promises","item","original","SerialTypedEventBus","toSorted","BroadcastChannelMessenger","channelName","message","DEFAULT_TTL","DEFAULT_CLEANUP_INTERVAL","StorageMessenger","options","storageMessage","error","key","now","keysToRemove","i","value","isBroadcastChannelSupported","isStorageEventSupported","createCrossTabMessenger","BroadcastTypedEventBus","messenger","DefaultNameGenerator","prefix","nameGenerator"],"mappings":"uSAkCO,MAAMA,CAAoD,CAQ/D,YAA6BC,EAA4C,CAA5C,KAAA,qBAAAA,EAP7B,KAAiB,UAAoD,GAQrE,CAUA,GACEC,EACAC,EACS,CACT,IAAIC,EAAM,KAAK,MAAM,IAAIF,CAAI,EAC7B,OAAKE,IACHA,EAAM,KAAK,qBAAqBF,CAAI,EACpC,KAAK,MAAM,IAAIA,EAAME,CAAG,GAEnBA,GAAK,GAAGD,CAAO,GAAK,EAC7B,CAUA,IACED,EACAG,EACS,CACT,OAAO,KAAK,MAAM,IAAIH,CAAI,GAAG,IAAIG,CAAI,GAAK,EAC5C,CAUA,KACEH,EACAI,EACsB,CACtB,OAAO,KAAK,MAAM,IAAIJ,CAAI,GAAG,KAAKI,CAAK,CACzC,CAKA,SAAgB,CACd,UAAWF,KAAO,KAAK,MAAM,OAAA,EAC3BA,EAAI,QAAA,EAEN,KAAK,MAAM,MAAA,CACb,CACF,CCxFO,MAAeG,CAA6D,CAA5E,aAAA,CACL,KAAU,cAAuC,CAAA,CAAC,CAMlD,IAAI,UAAkC,CACpC,MAAO,CAAC,GAAG,KAAK,aAAa,CAC/B,CAEA,SAAU,CACR,KAAK,cAAgB,CAAA,CACvB,CAEA,MAAgB,YAAYJ,EAA8BG,EAA6B,CACrF,GAAI,CACFH,EAAQ,OAAOG,CAAK,CACtB,OAASE,EAAG,CACV,QAAQ,KAAK,2BAA2BL,EAAQ,IAAI,IAAKK,CAAC,CAC5D,CACF,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aAClC,OAAO,aAAiB,KACvB,OAAO,eAAmB,IAEhC,CAEO,SAASC,EACdf,EAC+B,CAC/B,GAAIa,IACF,OAAO,IAAId,EAA0BC,CAAW,EAGlD,GAAIc,IACF,OAAO,IAAIV,EAAiB,CAAE,YAAAJ,EAAa,CAI/C,CCmCO,MAAMgB,CAA8D,CAWzE,YAAYX,EAA+C,CACzD,KAAK,SAAWA,EAAQ,SACxB,KAAK,KAAO,KAAK,SAAS,KAC1B,MAAMY,EACJZ,EAAQ,WAAaU,EAAwB,eAAe,KAAK,IAAI,EAAE,EACzE,GAAI,CAACE,EACH,MAAM,IAAI,MAAM,wBAAwB,EAE1C,KAAK,UAAYA,EACjB,KAAK,UAAU,UAAY,MAAO5B,GAAiB,CACjD,MAAM,KAAK,SAAS,KAAKA,CAAK,CAChC,CACF,CAUA,IAAI,UAAkC,CACpC,OAAO,KAAK,SAAS,QACvB,CAgBA,MAAM,KAAKA,EAA6B,CACtC,MAAM,KAAK,SAAS,KAAKA,CAAK,EAC9B,KAAK,UAAU,YAAYA,CAAK,CAClC,CAWA,IAAID,EAAuB,CACzB,OAAO,KAAK,SAAS,IAAIA,CAAI,CAC/B,CAWA,GAAGF,EAAuC,CACxC,OAAO,KAAK,SAAS,GAAGA,CAAO,CACjC,CAYA,SAAgB,CACd,KAAK,UAAU,MAAA,CACjB,CACF,CCrLO,MAAMgC,CAA8C,CAApD,aAAA,CACL,KAAQ,cAAwB,CAAA,CAOhC,SAASC,EAAwB,CAC/B,YAAK,gBACE,GAAGA,CAAM,IAAI,KAAK,aAAa,EACxC,CACF,CAKO,MAAMC,EAAgB,IAAIF"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';
|
|
2
|
+
export declare class BroadcastChannelMessenger implements CrossTabMessenger {
|
|
3
|
+
private readonly broadcastChannel;
|
|
4
|
+
constructor(channelName: string);
|
|
5
|
+
postMessage(message: any): void;
|
|
6
|
+
/**
|
|
7
|
+
* Set the message handler for incoming messages
|
|
8
|
+
*
|
|
9
|
+
* @param handler - Function to handle incoming messages, or undefined to remove handler
|
|
10
|
+
*/
|
|
11
|
+
set onmessage(handler: CrossTabMessageHandler);
|
|
12
|
+
/**
|
|
13
|
+
* Close the messenger and clean up resources
|
|
14
|
+
*
|
|
15
|
+
* After calling close(), the messenger cannot be used again.
|
|
16
|
+
*/
|
|
17
|
+
close(): void;
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=broadcastChannelMessenger.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"broadcastChannelMessenger.d.ts","sourceRoot":"","sources":["../../src/messengers/broadcastChannelMessenger.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAEhF,qBAAa,yBAA0B,YAAW,iBAAiB;IACjE,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAmB;gBAExC,WAAW,EAAE,MAAM;IAI/B,WAAW,CAAC,OAAO,EAAE,GAAG,GAAG,IAAI;IAI/B;;;;OAIG;IACH,IAAI,SAAS,CAAC,OAAO,EAAE,sBAAsB,EAI5C;IAED;;;;OAIG;IACH,KAAK,IAAI,IAAI;CAGd"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export type CrossTabMessageHandler = (message: any) => void;
|
|
2
|
+
/**
|
|
3
|
+
* Interface for cross-tab communication messengers
|
|
4
|
+
*
|
|
5
|
+
* Provides a unified API for different cross-tab communication mechanisms
|
|
6
|
+
* like BroadcastChannel, StorageEvent, SharedWorker, etc.
|
|
7
|
+
*/
|
|
8
|
+
export interface CrossTabMessenger {
|
|
9
|
+
/**
|
|
10
|
+
* Send a message to other tabs/windows
|
|
11
|
+
*
|
|
12
|
+
* @param message - The data to send
|
|
13
|
+
*/
|
|
14
|
+
postMessage(message: any): void;
|
|
15
|
+
/**
|
|
16
|
+
* Set the message handler for incoming messages
|
|
17
|
+
*
|
|
18
|
+
* @param handler - Function to handle incoming messages
|
|
19
|
+
*/
|
|
20
|
+
set onmessage(handler: CrossTabMessageHandler);
|
|
21
|
+
/**
|
|
22
|
+
* Close the messenger and clean up resources
|
|
23
|
+
*/
|
|
24
|
+
close(): void;
|
|
25
|
+
}
|
|
26
|
+
export declare function isBroadcastChannelSupported(): boolean;
|
|
27
|
+
export declare function isStorageEventSupported(): boolean;
|
|
28
|
+
export declare function createCrossTabMessenger(channelName: string): CrossTabMessenger | undefined;
|
|
29
|
+
//# sourceMappingURL=crossTabMessenger.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"crossTabMessenger.d.ts","sourceRoot":"","sources":["../../src/messengers/crossTabMessenger.ts"],"names":[],"mappings":"AAgBA,MAAM,MAAM,sBAAsB,GAAG,CAAC,OAAO,EAAE,GAAG,KAAK,IAAI,CAAC;AAE5D;;;;;GAKG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;;OAIG;IACH,WAAW,CAAC,OAAO,EAAE,GAAG,GAAG,IAAI,CAAC;IAEhC;;;;OAIG;IACH,IAAI,SAAS,CAAC,OAAO,EAAE,sBAAsB,EAAE;IAE/C;;OAEG;IACH,KAAK,IAAI,IAAI,CAAC;CACf;AAED,wBAAgB,2BAA2B,IAAI,OAAO,CAKrD;AAED,wBAAgB,uBAAuB,IAAI,OAAO,CAQjD;AAED,wBAAgB,uBAAuB,CACrC,WAAW,EAAE,MAAM,GAClB,iBAAiB,GAAG,SAAS,CAU/B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/messengers/index.ts"],"names":[],"mappings":"AAaA,cAAc,qBAAqB,CAAC;AACpC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,oBAAoB,CAAC"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { CrossTabMessenger, CrossTabMessageHandler } from './crossTabMessenger';
|
|
2
|
+
export interface StorageMessengerOptions {
|
|
3
|
+
channelName: string;
|
|
4
|
+
/** Storage instance to use. Defaults to localStorage */
|
|
5
|
+
storage?: Storage;
|
|
6
|
+
ttl?: number;
|
|
7
|
+
cleanupInterval?: number;
|
|
8
|
+
}
|
|
9
|
+
export interface StorageMessage {
|
|
10
|
+
data: any;
|
|
11
|
+
timestamp: number;
|
|
12
|
+
}
|
|
13
|
+
export declare class StorageMessenger implements CrossTabMessenger {
|
|
14
|
+
private readonly channelName;
|
|
15
|
+
private readonly storage;
|
|
16
|
+
private messageHandler?;
|
|
17
|
+
private readonly messageKeyPrefix;
|
|
18
|
+
private readonly ttl;
|
|
19
|
+
private readonly cleanupInterval;
|
|
20
|
+
private cleanupTimer?;
|
|
21
|
+
private readonly storageEventHandler;
|
|
22
|
+
constructor(options: StorageMessengerOptions);
|
|
23
|
+
private generateMessageKey;
|
|
24
|
+
/**
|
|
25
|
+
* Send a message to other tabs/windows via localStorage
|
|
26
|
+
*/
|
|
27
|
+
postMessage(message: any): void;
|
|
28
|
+
/**
|
|
29
|
+
* Set the message handler for incoming messages
|
|
30
|
+
*/
|
|
31
|
+
set onmessage(handler: CrossTabMessageHandler);
|
|
32
|
+
/**
|
|
33
|
+
* Clean up expired messages from storage
|
|
34
|
+
*/
|
|
35
|
+
private cleanup;
|
|
36
|
+
/**
|
|
37
|
+
* Close the messenger and clean up resources
|
|
38
|
+
*/
|
|
39
|
+
close(): void;
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=storageMessenger.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"storageMessenger.d.ts","sourceRoot":"","sources":["../../src/messengers/storageMessenger.ts"],"names":[],"mappings":"AAaA,OAAO,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAEhF,MAAM,WAAW,uBAAuB;IACtC,WAAW,EAAE,MAAM,CAAC;IACpB,wDAAwD;IACxD,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,GAAG,CAAC;IACV,SAAS,EAAE,MAAM,CAAC;CACnB;AAKD,qBAAa,gBAAiB,YAAW,iBAAiB;IACxD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAU;IAClC,OAAO,CAAC,cAAc,CAAC,CAAyB;IAChD,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAS;IAC1C,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAS;IAC7B,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAS;IACzC,OAAO,CAAC,YAAY,CAAC,CAAS;IAC9B,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAclC;gBAEU,OAAO,EAAE,uBAAuB;IAa5C,OAAO,CAAC,kBAAkB;IAI1B;;OAEG;IACH,WAAW,CAAC,OAAO,EAAE,GAAG,GAAG,IAAI;IAW/B;;OAEG;IACH,IAAI,SAAS,CAAC,OAAO,EAAE,sBAAsB,EAE5C;IAED;;OAEG;IACH,OAAO,CAAC,OAAO;IAuBf;;OAEG;IACH,KAAK,IAAI,IAAI;CAMd"}
|