@oxog/emitter 1.2.0 → 1.3.0

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/index.d.cts CHANGED
@@ -143,24 +143,26 @@ interface EmitterInstance<TEvents extends object> {
143
143
  * @param handler - Handler function
144
144
  * @returns Unsubscribe function
145
145
  */
146
- on<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
147
146
  on(event: '*', handler: WildcardHandler): Unsubscribe;
148
147
  on(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
148
+ on<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
149
149
  /**
150
150
  * Subscribe to an event once (auto-unsubscribe after first emit).
151
151
  * @param event - Event name
152
152
  * @param handler - Handler function
153
153
  * @returns Unsubscribe function
154
154
  */
155
- once<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
156
155
  once(event: '*', handler: WildcardHandler): Unsubscribe;
157
156
  once(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
157
+ once<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
158
158
  /**
159
159
  * Add handler to the beginning of the listener queue.
160
160
  * @param event - Event name
161
161
  * @param handler - Handler function
162
162
  * @returns Unsubscribe function
163
163
  */
164
+ prependListener(event: '*', handler: WildcardHandler): Unsubscribe;
165
+ prependListener(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
164
166
  prependListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
165
167
  /**
166
168
  * Add once-handler to the beginning of the listener queue.
@@ -168,32 +170,34 @@ interface EmitterInstance<TEvents extends object> {
168
170
  * @param handler - Handler function
169
171
  * @returns Unsubscribe function
170
172
  */
173
+ prependOnceListener(event: '*', handler: WildcardHandler): Unsubscribe;
174
+ prependOnceListener(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
171
175
  prependOnceListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
172
176
  /**
173
177
  * Remove a specific handler from an event.
174
178
  * @param event - Event name
175
179
  * @param handler - Handler to remove
176
180
  */
177
- off<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
178
181
  off(event: '*', handler: WildcardHandler): void;
179
182
  off(event: `${string}:*`, handler: PatternHandler): void;
183
+ off<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
180
184
  /**
181
185
  * Alias for `on`. Node.js EventEmitter compatibility.
182
186
  * @param event - Event name
183
187
  * @param handler - Handler function
184
188
  * @returns Unsubscribe function
185
189
  */
186
- addListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
187
190
  addListener(event: '*', handler: WildcardHandler): Unsubscribe;
188
191
  addListener(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
192
+ addListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
189
193
  /**
190
194
  * Alias for `off`. Node.js EventEmitter compatibility.
191
195
  * @param event - Event name
192
196
  * @param handler - Handler to remove
193
197
  */
194
- removeListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
195
198
  removeListener(event: '*', handler: WildcardHandler): void;
196
199
  removeListener(event: `${string}:*`, handler: PatternHandler): void;
200
+ removeListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
197
201
  /**
198
202
  * Alias for `offAll`. Node.js EventEmitter compatibility.
199
203
  * @param event - Optional event name. If omitted, removes all handlers.
@@ -315,6 +319,8 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
315
319
  private options;
316
320
  /** Debug logger instance */
317
321
  private debugLogger;
322
+ /** Event names that already triggered the max-listeners warning */
323
+ private warnedEvents;
318
324
  /**
319
325
  * Create a new Emitter instance.
320
326
  *
@@ -359,9 +365,9 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
359
365
  * });
360
366
  * ```
361
367
  */
362
- on<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
363
368
  on(event: '*', handler: WildcardHandler): Unsubscribe;
364
369
  on(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
370
+ on<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
365
371
  /**
366
372
  * Subscribe to an event once.
367
373
  * Handler is automatically removed after first emission.
@@ -378,9 +384,9 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
378
384
  * });
379
385
  * ```
380
386
  */
381
- once<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
382
387
  once(event: '*', handler: WildcardHandler): Unsubscribe;
383
388
  once(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
389
+ once<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
384
390
  /**
385
391
  * Add handler to the beginning of the listener queue.
386
392
  *
@@ -396,6 +402,8 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
396
402
  * // Output: First, Second
397
403
  * ```
398
404
  */
405
+ prependListener(event: '*', handler: WildcardHandler): Unsubscribe;
406
+ prependListener(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
399
407
  prependListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
400
408
  /**
401
409
  * Add once-handler to the beginning of the listener queue.
@@ -411,6 +419,8 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
411
419
  * });
412
420
  * ```
413
421
  */
422
+ prependOnceListener(event: '*', handler: WildcardHandler): Unsubscribe;
423
+ prependOnceListener(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
414
424
  prependOnceListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
415
425
  /**
416
426
  * Remove a specific handler from an event.
@@ -425,9 +435,9 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
425
435
  * emitter.off('message', handler);
426
436
  * ```
427
437
  */
428
- off<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
429
438
  off(event: '*', handler: WildcardHandler): void;
430
439
  off(event: `${string}:*`, handler: PatternHandler): void;
440
+ off<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
431
441
  /**
432
442
  * Alias for `on`. Node.js EventEmitter compatibility.
433
443
  *
@@ -435,18 +445,18 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
435
445
  * @param handler - Handler function
436
446
  * @returns Unsubscribe function
437
447
  */
438
- addListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
439
448
  addListener(event: '*', handler: WildcardHandler): Unsubscribe;
440
449
  addListener(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
450
+ addListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
441
451
  /**
442
452
  * Alias for `off`. Node.js EventEmitter compatibility.
443
453
  *
444
454
  * @param event - Event name
445
455
  * @param handler - Handler to remove
446
456
  */
447
- removeListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
448
457
  removeListener(event: '*', handler: WildcardHandler): void;
449
458
  removeListener(event: `${string}:*`, handler: PatternHandler): void;
459
+ removeListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
450
460
  /**
451
461
  * Alias for `offAll`. Node.js EventEmitter compatibility.
452
462
  *
@@ -655,6 +665,20 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
655
665
  * Handle errors during emission.
656
666
  */
657
667
  private handleEmitError;
668
+ /**
669
+ * Handle a rejection from an async handler started by the synchronous `emit()`.
670
+ *
671
+ * `emit()` has already returned, so the error cannot be thrown to its caller: with
672
+ * `errorHandling: 'throw'` it is passed to `'error'` listeners (or logged) as in
673
+ * `'emit'` mode. This runs inside a promise callback and must never throw, or the
674
+ * rejection would become an unhandled rejection that terminates Node.
675
+ */
676
+ private handleLateEmitError;
677
+ /**
678
+ * Pass an error to 'error' listeners (never re-entering 'error' itself). Without a
679
+ * listener, log the error instead of dropping it silently.
680
+ */
681
+ private dispatchError;
658
682
  }
659
683
  /**
660
684
  * Create a new typed event emitter.
package/dist/index.d.ts CHANGED
@@ -143,24 +143,26 @@ interface EmitterInstance<TEvents extends object> {
143
143
  * @param handler - Handler function
144
144
  * @returns Unsubscribe function
145
145
  */
146
- on<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
147
146
  on(event: '*', handler: WildcardHandler): Unsubscribe;
148
147
  on(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
148
+ on<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
149
149
  /**
150
150
  * Subscribe to an event once (auto-unsubscribe after first emit).
151
151
  * @param event - Event name
152
152
  * @param handler - Handler function
153
153
  * @returns Unsubscribe function
154
154
  */
155
- once<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
156
155
  once(event: '*', handler: WildcardHandler): Unsubscribe;
157
156
  once(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
157
+ once<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
158
158
  /**
159
159
  * Add handler to the beginning of the listener queue.
160
160
  * @param event - Event name
161
161
  * @param handler - Handler function
162
162
  * @returns Unsubscribe function
163
163
  */
164
+ prependListener(event: '*', handler: WildcardHandler): Unsubscribe;
165
+ prependListener(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
164
166
  prependListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
165
167
  /**
166
168
  * Add once-handler to the beginning of the listener queue.
@@ -168,32 +170,34 @@ interface EmitterInstance<TEvents extends object> {
168
170
  * @param handler - Handler function
169
171
  * @returns Unsubscribe function
170
172
  */
173
+ prependOnceListener(event: '*', handler: WildcardHandler): Unsubscribe;
174
+ prependOnceListener(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
171
175
  prependOnceListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
172
176
  /**
173
177
  * Remove a specific handler from an event.
174
178
  * @param event - Event name
175
179
  * @param handler - Handler to remove
176
180
  */
177
- off<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
178
181
  off(event: '*', handler: WildcardHandler): void;
179
182
  off(event: `${string}:*`, handler: PatternHandler): void;
183
+ off<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
180
184
  /**
181
185
  * Alias for `on`. Node.js EventEmitter compatibility.
182
186
  * @param event - Event name
183
187
  * @param handler - Handler function
184
188
  * @returns Unsubscribe function
185
189
  */
186
- addListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
187
190
  addListener(event: '*', handler: WildcardHandler): Unsubscribe;
188
191
  addListener(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
192
+ addListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
189
193
  /**
190
194
  * Alias for `off`. Node.js EventEmitter compatibility.
191
195
  * @param event - Event name
192
196
  * @param handler - Handler to remove
193
197
  */
194
- removeListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
195
198
  removeListener(event: '*', handler: WildcardHandler): void;
196
199
  removeListener(event: `${string}:*`, handler: PatternHandler): void;
200
+ removeListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
197
201
  /**
198
202
  * Alias for `offAll`. Node.js EventEmitter compatibility.
199
203
  * @param event - Optional event name. If omitted, removes all handlers.
@@ -315,6 +319,8 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
315
319
  private options;
316
320
  /** Debug logger instance */
317
321
  private debugLogger;
322
+ /** Event names that already triggered the max-listeners warning */
323
+ private warnedEvents;
318
324
  /**
319
325
  * Create a new Emitter instance.
320
326
  *
@@ -359,9 +365,9 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
359
365
  * });
360
366
  * ```
361
367
  */
362
- on<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
363
368
  on(event: '*', handler: WildcardHandler): Unsubscribe;
364
369
  on(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
370
+ on<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
365
371
  /**
366
372
  * Subscribe to an event once.
367
373
  * Handler is automatically removed after first emission.
@@ -378,9 +384,9 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
378
384
  * });
379
385
  * ```
380
386
  */
381
- once<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
382
387
  once(event: '*', handler: WildcardHandler): Unsubscribe;
383
388
  once(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
389
+ once<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
384
390
  /**
385
391
  * Add handler to the beginning of the listener queue.
386
392
  *
@@ -396,6 +402,8 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
396
402
  * // Output: First, Second
397
403
  * ```
398
404
  */
405
+ prependListener(event: '*', handler: WildcardHandler): Unsubscribe;
406
+ prependListener(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
399
407
  prependListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
400
408
  /**
401
409
  * Add once-handler to the beginning of the listener queue.
@@ -411,6 +419,8 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
411
419
  * });
412
420
  * ```
413
421
  */
422
+ prependOnceListener(event: '*', handler: WildcardHandler): Unsubscribe;
423
+ prependOnceListener(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
414
424
  prependOnceListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
415
425
  /**
416
426
  * Remove a specific handler from an event.
@@ -425,9 +435,9 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
425
435
  * emitter.off('message', handler);
426
436
  * ```
427
437
  */
428
- off<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
429
438
  off(event: '*', handler: WildcardHandler): void;
430
439
  off(event: `${string}:*`, handler: PatternHandler): void;
440
+ off<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
431
441
  /**
432
442
  * Alias for `on`. Node.js EventEmitter compatibility.
433
443
  *
@@ -435,18 +445,18 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
435
445
  * @param handler - Handler function
436
446
  * @returns Unsubscribe function
437
447
  */
438
- addListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
439
448
  addListener(event: '*', handler: WildcardHandler): Unsubscribe;
440
449
  addListener(event: `${string}:*`, handler: PatternHandler): Unsubscribe;
450
+ addListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): Unsubscribe;
441
451
  /**
442
452
  * Alias for `off`. Node.js EventEmitter compatibility.
443
453
  *
444
454
  * @param event - Event name
445
455
  * @param handler - Handler to remove
446
456
  */
447
- removeListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
448
457
  removeListener(event: '*', handler: WildcardHandler): void;
449
458
  removeListener(event: `${string}:*`, handler: PatternHandler): void;
459
+ removeListener<K extends keyof TEvents>(event: K, handler: Handler<TEvents[K]>): void;
450
460
  /**
451
461
  * Alias for `offAll`. Node.js EventEmitter compatibility.
452
462
  *
@@ -655,6 +665,20 @@ declare class Emitter<TEvents extends object = EventMap> implements EmitterInsta
655
665
  * Handle errors during emission.
656
666
  */
657
667
  private handleEmitError;
668
+ /**
669
+ * Handle a rejection from an async handler started by the synchronous `emit()`.
670
+ *
671
+ * `emit()` has already returned, so the error cannot be thrown to its caller: with
672
+ * `errorHandling: 'throw'` it is passed to `'error'` listeners (or logged) as in
673
+ * `'emit'` mode. This runs inside a promise callback and must never throw, or the
674
+ * rejection would become an unhandled rejection that terminates Node.
675
+ */
676
+ private handleLateEmitError;
677
+ /**
678
+ * Pass an error to 'error' listeners (never re-entering 'error' itself). Without a
679
+ * listener, log the error instead of dropping it silently.
680
+ */
681
+ private dispatchError;
658
682
  }
659
683
  /**
660
684
  * Create a new typed event emitter.
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- function l(s){return s.endsWith(":*")&&s.length>2?s.slice(0,-2):null}function c(s){return s==="*"}function g(s){return s.endsWith(":*")&&s.length>2}function m(s,r){for(let e=s.length-1;e>=0;e--){let n=s[e]?.handler;if(n===r||n?.listener===r)return e}return -1}var f=class{handlers=new Map;wildcardHandlers=[];patternHandlers=new Map;priorityCounter=0;prependPriorityCounter=0;add(r,e,n=false){let i=n?--this.prependPriorityCounter:++this.priorityCounter,t={handler:e,priority:i};if(c(r)){this.wildcardHandlers.push(t);return}if(g(r)){let a=l(r);if(a){let h=this.patternHandlers.get(a)??[];h.push(t),this.patternHandlers.set(a,h);}return}let o=this.handlers.get(r)??[];o.push(t),this.handlers.set(r,o);}remove(r,e){if(c(r)){let i=m(this.wildcardHandlers,e);return i!==-1?(this.wildcardHandlers.splice(i,1),true):false}if(g(r)){let i=l(r);if(i){let t=this.patternHandlers.get(i);if(t){let o=m(t,e);if(o!==-1)return t.splice(o,1),t.length===0&&this.patternHandlers.delete(i),true}}return false}let n=this.handlers.get(r);if(n){let i=m(n,e);if(i!==-1)return n.splice(i,1),n.length===0&&this.handlers.delete(r),true}return false}get(r){let e;if(c(r))e=this.wildcardHandlers;else if(g(r)){let n=l(r);e=this.patternHandlers.get(n)??[];}else e=this.handlers.get(r)??[];return [...e].sort((n,i)=>n.priority-i.priority).map(n=>n.handler)}getMatching(r){let e=[],n=this.handlers.get(r)??[];for(let{handler:t,priority:o}of n)e.push({handler:t,isWildcard:false,priority:o});for(let{handler:t,priority:o}of this.wildcardHandlers)e.push({handler:t,isWildcard:true,priority:o});let i=r.indexOf(":");if(i>0){let t=r.slice(0,i),o=this.patternHandlers.get(t);if(o)for(let{handler:a,priority:h}of o)e.push({handler:a,isWildcard:false,pattern:`${t}:*`,priority:h});}return e.sort((t,o)=>t.priority-o.priority),e}clear(r){if(r===void 0){this.handlers.clear(),this.wildcardHandlers=[],this.patternHandlers.clear();return}if(c(r)){this.wildcardHandlers=[];return}if(g(r)){let e=l(r);e&&this.patternHandlers.delete(e);return}this.handlers.delete(r);}count(r){if(c(r))return this.wildcardHandlers.length;if(g(r)){let e=l(r);return this.patternHandlers.get(e)?.length??0}return this.handlers.get(r)?.length??0}events(){let r=[];for(let e of this.handlers.keys())r.push(e);this.wildcardHandlers.length>0&&r.push("*");for(let e of this.patternHandlers.keys())r.push(`${e}:*`);return r}};var u=class extends Error{constructor(e,n){super("EMIT_ERROR_MARKER");this.originalError=e;this.eventName=n;this.name="EmitErrorMarker";}};function H(s,r){let{strategy:e,eventName:n,customHandler:i,logger:t}=r;if(i){try{i(s,n);}catch(o){(t??console).error("[Emitter] Error in custom error handler:",o);}return}switch(e){case "throw":throw s;case "silent":break;default:throw new u(s,n)}}var p={log:(s,...r)=>console.log(`[Emitter] ${s}`,...r),warn:(s,...r)=>console.warn(`[Emitter] ${s}`,...r),error:(s,...r)=>console.error(`[Emitter] ${s}`,...r)},L={log:()=>{},warn:()=>{},error:()=>{}};function b(s,r){return s?r??p:L}var d={subscribe:s=>`Subscribed to "${s}"`,unsubscribe:s=>`Unsubscribed from "${s}"`,emit:s=>`Emitting "${s}"`,emitAsync:s=>`Emitting async "${s}"`,clear:s=>s?`Cleared handlers for "${s}"`:"Cleared all handlers",maxListeners:(s,r)=>`Possible memory leak detected. ${r} listeners for "${s}" event.`};async function x(s,r){let e=[];for(let{handler:n,args:i}of s)try{let t=n(...i);e.push(await Promise.resolve(t));}catch(t){r(t instanceof Error?t:new Error(String(t)));}return e}async function v(s,r){let e=s.map(async({handler:n,args:i})=>{try{let t=n(...i);return await Promise.resolve(t)}catch(t){r(t instanceof Error?t:new Error(String(t)));return}});return Promise.all(e)}function y(s,r){for(let{handler:e,args:n}of s)try{let i=e(...n);i&&typeof i=="object"&&"catch"in i&&i.catch(t=>{r(t instanceof Error?t:new Error(String(t)));});}catch(i){r(i instanceof Error?i:new Error(String(i)));}}var E=class{store;options;debugLogger;constructor(r){this.store=new f,this.options={errorHandling:r?.errorHandling??"emit",maxListeners:r?.maxListeners??10,debug:r?.debug??false,onError:r?.onError,logger:r?.logger},this.debugLogger=b(this.options.debug,this.options.logger);}on(r,e){return this.validateEvent(r),this.validateHandler(e),this.store.add(r,e),this.checkMaxListeners(r),this.debugLogger.log(d.subscribe(r)),()=>this.off(r,e)}once(r,e){this.validateEvent(r),this.validateHandler(e);let n=(...i)=>(this.store.remove(r,n),e(...i));return n.listener=e,this.store.add(r,n),this.checkMaxListeners(r),this.debugLogger.log(d.subscribe(r)),()=>{this.store.remove(r,n);}}prependListener(r,e){return this.validateEvent(r),this.validateHandler(e),this.store.add(r,e,true),this.checkMaxListeners(r),this.debugLogger.log(d.subscribe(r)),()=>this.off(r,e)}prependOnceListener(r,e){this.validateEvent(r),this.validateHandler(e);let n=(...i)=>(this.store.remove(r,n),e(...i));return n.listener=e,this.store.add(r,n,true),this.checkMaxListeners(r),this.debugLogger.log(d.subscribe(r)),()=>{this.store.remove(r,n);}}off(r,e){this.store.remove(r,e),this.debugLogger.log(d.unsubscribe(r));}addListener(r,e){return this.on(r,e)}removeListener(r,e){this.off(r,e);}removeAllListeners(r){this.offAll(r);}offAll(r){this.store.clear(r),this.debugLogger.log(d.clear(r));}clear(){this.store.clear(),this.debugLogger.log(d.clear());}emit(r,e){this.debugLogger.log(d.emit(r));let i=this.store.getMatching(r).map(({handler:t,isWildcard:o,pattern:a})=>({handler:t,args:o||a?[r,e]:[e]}));y(i,t=>this.handleEmitError(t,r));}async emitAsync(r,e){this.debugLogger.log(d.emitAsync(r));let i=this.store.getMatching(r).map(({handler:t,isWildcard:o,pattern:a})=>({handler:t,args:o||a?[r,e]:[e]}));return x(i,t=>this.handleEmitError(t,r))}async emitParallel(r,e){this.debugLogger.log(d.emitAsync(r));let i=this.store.getMatching(r).map(({handler:t,isWildcard:o,pattern:a})=>({handler:t,args:o||a?[r,e]:[e]}));return v(i,t=>this.handleEmitError(t,r))}listenerCount(r){return this.store.count(r)}listeners(r){return this.store.get(r).map(e=>e.listener??e)}eventNames(){return this.store.events()}hasListeners(r){return this.store.count(r)>0}getMaxListeners(){return this.options.maxListeners}setMaxListeners(r){return this.options.maxListeners=r,this}isDebug(){return this.options.debug}setDebug(r){return this.options.debug=r,this.debugLogger=b(r,this.options.logger),this}validateEvent(r){if(!r||typeof r!="string")throw new Error("Event name must be a non-empty string")}validateHandler(r){if(typeof r!="function")throw new Error("Handler must be a function")}checkMaxListeners(r){let{maxListeners:e}=this.options;if(e>0){let n=this.store.count(r);n>e&&(this.options.logger??p).warn(d.maxListeners(r,n));}}handleEmitError(r,e){try{H(r,{strategy:this.options.errorHandling,eventName:e,customHandler:this.options.onError,logger:this.options.logger});}catch(n){if(n instanceof u){let i=(o,a)=>{(this.options.logger??p).error(a,o);},t=e==="error"?[]:this.store.get("error");t.length>0?y(t.map(o=>({handler:o,args:[n.originalError]})),o=>i(o,`Error in 'error' handler while handling '${e}':`)):i(n.originalError,`Unhandled error in '${e}' handler:`);}else if(n instanceof Error)throw n}}};function w(s){return new E(s)}export{E as Emitter,w as createEmitter};//# sourceMappingURL=index.js.map
1
+ function l(s){return s.endsWith(":*")&&s.length>2?s.slice(0,-2):null}function c(s){return s==="*"}function g(s){return s.endsWith(":*")&&s.length>2}function m(s,r){for(let e=s.length-1;e>=0;e--){let n=s[e]?.handler;if(n===r||n?.listener===r)return e}return -1}var p=class{handlers=new Map;wildcardHandlers=[];patternHandlers=new Map;priorityCounter=0;prependPriorityCounter=0;add(r,e,n=false){let i=n?--this.prependPriorityCounter:++this.priorityCounter,t={handler:e,priority:i};if(c(r)){this.wildcardHandlers.push(t);return}if(g(r)){let a=l(r);if(a){let f=this.patternHandlers.get(a)??[];f.push(t),this.patternHandlers.set(a,f);}return}let o=this.handlers.get(r)??[];o.push(t),this.handlers.set(r,o);}remove(r,e){if(c(r)){let i=m(this.wildcardHandlers,e);return i!==-1?(this.wildcardHandlers.splice(i,1),true):false}if(g(r)){let i=l(r);if(i){let t=this.patternHandlers.get(i);if(t){let o=m(t,e);if(o!==-1)return t.splice(o,1),t.length===0&&this.patternHandlers.delete(i),true}}return false}let n=this.handlers.get(r);if(n){let i=m(n,e);if(i!==-1)return n.splice(i,1),n.length===0&&this.handlers.delete(r),true}return false}get(r){let e;if(c(r))e=this.wildcardHandlers;else if(g(r)){let n=l(r);e=this.patternHandlers.get(n)??[];}else e=this.handlers.get(r)??[];return [...e].sort((n,i)=>n.priority-i.priority).map(n=>n.handler)}getMatching(r){let e=[],n=this.handlers.get(r)??[];for(let{handler:t,priority:o}of n)e.push({handler:t,isWildcard:false,priority:o});for(let{handler:t,priority:o}of this.wildcardHandlers)e.push({handler:t,isWildcard:true,priority:o});let i=r.indexOf(":");if(i>0){let t=r.slice(0,i),o=this.patternHandlers.get(t);if(o)for(let{handler:a,priority:f}of o)e.push({handler:a,isWildcard:false,pattern:`${t}:*`,priority:f});}return e.sort((t,o)=>t.priority-o.priority),e}clear(r){if(r===void 0){this.handlers.clear(),this.wildcardHandlers=[],this.patternHandlers.clear();return}if(c(r)){this.wildcardHandlers=[];return}if(g(r)){let e=l(r);e&&this.patternHandlers.delete(e);return}this.handlers.delete(r);}count(r){if(c(r))return this.wildcardHandlers.length;if(g(r)){let e=l(r);return this.patternHandlers.get(e)?.length??0}return this.handlers.get(r)?.length??0}events(){let r=[];for(let e of this.handlers.keys())r.push(e);this.wildcardHandlers.length>0&&r.push("*");for(let e of this.patternHandlers.keys())r.push(`${e}:*`);return r}};var u=class extends Error{constructor(e,n){super("EMIT_ERROR_MARKER");this.originalError=e;this.eventName=n;this.name="EmitErrorMarker";}};function H(s,r){let{strategy:e,eventName:n,customHandler:i,logger:t}=r;if(i){try{i(s,n);}catch(o){(t??console).error("[Emitter] Error in custom error handler:",o);}return}switch(e){case "throw":throw s;case "silent":break;default:throw new u(s,n)}}var h={log:(s,...r)=>console.log(`[Emitter] ${s}`,...r),warn:(s,...r)=>console.warn(`[Emitter] ${s}`,...r),error:(s,...r)=>console.error(`[Emitter] ${s}`,...r)},L={log:()=>{},warn:()=>{},error:()=>{}};function b(s,r){return s?r??h:L}var d={subscribe:s=>`Subscribed to "${s}"`,unsubscribe:s=>`Unsubscribed from "${s}"`,emit:s=>`Emitting "${s}"`,emitAsync:s=>`Emitting async "${s}"`,clear:s=>s?`Cleared handlers for "${s}"`:"Cleared all handlers",maxListeners:(s,r)=>`Possible memory leak detected. ${r} listeners for "${s}" event.`};async function v(s,r){let e=[];for(let{handler:n,args:i}of s)try{let t=n(...i);e.push(await Promise.resolve(t));}catch(t){r(t instanceof Error?t:new Error(String(t))),e.push(void 0);}return e}async function x(s,r){let e=s.map(async({handler:n,args:i})=>{try{let t=n(...i);return await Promise.resolve(t)}catch(t){r(t instanceof Error?t:new Error(String(t)));return}});return Promise.all(e)}function y(s,r,e=r){for(let{handler:n,args:i}of s)try{let t=n(...i);t&&typeof t=="object"&&"catch"in t&&t.catch(o=>{e(o instanceof Error?o:new Error(String(o)));});}catch(t){r(t instanceof Error?t:new Error(String(t)));}}var E=class{store;options;debugLogger;warnedEvents=new Set;constructor(r){this.store=new p,this.options={errorHandling:r?.errorHandling??"emit",maxListeners:r?.maxListeners??10,debug:r?.debug??false,onError:r?.onError,logger:r?.logger},this.debugLogger=b(this.options.debug,this.options.logger);}on(r,e){return this.validateEvent(r),this.validateHandler(e),this.store.add(r,e),this.checkMaxListeners(r),this.debugLogger.log(d.subscribe(r)),()=>this.off(r,e)}once(r,e){this.validateEvent(r),this.validateHandler(e);let n=(...i)=>(this.store.remove(r,n),e(...i));return n.listener=e,this.store.add(r,n),this.checkMaxListeners(r),this.debugLogger.log(d.subscribe(r)),()=>{this.store.remove(r,n);}}prependListener(r,e){return this.validateEvent(r),this.validateHandler(e),this.store.add(r,e,true),this.checkMaxListeners(r),this.debugLogger.log(d.subscribe(r)),()=>this.off(r,e)}prependOnceListener(r,e){this.validateEvent(r),this.validateHandler(e);let n=(...i)=>(this.store.remove(r,n),e(...i));return n.listener=e,this.store.add(r,n,true),this.checkMaxListeners(r),this.debugLogger.log(d.subscribe(r)),()=>{this.store.remove(r,n);}}off(r,e){this.store.remove(r,e),this.debugLogger.log(d.unsubscribe(r));}addListener(r,e){return this.on(r,e)}removeListener(r,e){this.off(r,e);}removeAllListeners(r){this.offAll(r);}offAll(r){this.store.clear(r),r===void 0?this.warnedEvents.clear():this.warnedEvents.delete(r),this.debugLogger.log(d.clear(r));}clear(){this.store.clear(),this.warnedEvents.clear(),this.debugLogger.log(d.clear());}emit(r,e){this.debugLogger.log(d.emit(r));let i=this.store.getMatching(r).map(({handler:t,isWildcard:o,pattern:a})=>({handler:t,args:o||a?[r,e]:[e]}));y(i,t=>this.handleEmitError(t,r),t=>this.handleLateEmitError(t,r));}async emitAsync(r,e){this.debugLogger.log(d.emitAsync(r));let i=this.store.getMatching(r).map(({handler:t,isWildcard:o,pattern:a})=>({handler:t,args:o||a?[r,e]:[e]}));return v(i,t=>this.handleEmitError(t,r))}async emitParallel(r,e){this.debugLogger.log(d.emitAsync(r));let i=this.store.getMatching(r).map(({handler:t,isWildcard:o,pattern:a})=>({handler:t,args:o||a?[r,e]:[e]}));return x(i,t=>this.handleEmitError(t,r))}listenerCount(r){return this.store.count(r)}listeners(r){return this.store.get(r).map(e=>e.listener??e)}eventNames(){return this.store.events()}hasListeners(r){return this.store.count(r)>0}getMaxListeners(){return this.options.maxListeners}setMaxListeners(r){return this.options.maxListeners=r,this}isDebug(){return this.options.debug}setDebug(r){return this.options.debug=r,this.debugLogger=b(r,this.options.logger),this}validateEvent(r){if(!r||typeof r!="string")throw new Error("Event name must be a non-empty string")}validateHandler(r){if(typeof r!="function")throw new Error("Handler must be a function")}checkMaxListeners(r){let{maxListeners:e}=this.options;if(e>0&&!this.warnedEvents.has(r)){let n=this.store.count(r);n>e&&(this.warnedEvents.add(r),(this.options.logger??h).warn(d.maxListeners(r,n)));}}handleEmitError(r,e){try{H(r,{strategy:this.options.errorHandling,eventName:e,customHandler:this.options.onError,logger:this.options.logger});}catch(n){if(n instanceof u)this.dispatchError(n.originalError,e);else throw n}}handleLateEmitError(r,e){try{this.options.errorHandling==="throw"&&!this.options.onError?this.dispatchError(r,e):this.handleEmitError(r,e);}catch(n){h.error(`Error while handling a rejected '${e}' handler:`,n);}}dispatchError(r,e){let n=(t,o)=>{(this.options.logger??h).error(o,t);},i=e==="error"?[]:this.store.get("error");i.length>0?y(i.map(t=>({handler:t,args:[r]})),t=>n(t,`Error in 'error' handler while handling '${e}':`)):n(r,`Unhandled error in '${e}' handler:`);}};function w(s){return new E(s)}export{E as Emitter,w as createEmitter};//# sourceMappingURL=index.js.map
2
2
  //# sourceMappingURL=index.js.map