@fluid-internal/client-utils 3.12.0 → 3.13.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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # @fluid-internal/client-utils
2
2
 
3
+ ## 3.13.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Reduce the memory used by event emitters with one listener per event ([#28719](https://github.com/microsoft/FluidFramework/pull/28719)) [d7730b8aaf5](https://github.com/microsoft/FluidFramework/commit/d7730b8aaf507aef4505cf012456f29a226be9cd)
8
+
9
+ An event emitter now keeps an event's only listener directly, and creates a set of listeners only when the event has a second one.
10
+ Most emitters have one listener per event: for example, a tree node with a `nodeChanged` listener uses about 300 bytes less memory.
11
+
3
12
  ## 3.12.0
4
13
 
5
14
  Dependency updates only.
@@ -58,7 +58,15 @@ import type { HasListeners, IEmitter, Listenable, Listeners, NoListenersCallback
58
58
  */
59
59
  export declare class CustomEventEmitter<TListeners extends Listeners<TListeners>> implements Listenable<TListeners>, HasListeners<TListeners> {
60
60
  private readonly noListeners?;
61
- protected readonly listeners: Map<keyof TListeners, Set<(...args: any[]) => TListeners[keyof TListeners]>>;
61
+ /**
62
+ * The listeners of each event with listeners: the listener itself while it is the only one,
63
+ * and a set of them once a second is added.
64
+ * @remarks
65
+ * Most emitters have at most one listener per event, so this saves a set for each of their events.
66
+ * A set is kept until the event has no listeners, so that listeners added or removed by another listener
67
+ * during an emit are treated the same whether or not the event had a set.
68
+ */
69
+ protected readonly listeners: Map<keyof TListeners, Set<(...args: any[]) => TListeners[keyof TListeners]> | ((...args: any[]) => TListeners[keyof TListeners])>;
62
70
  protected constructor(noListeners?: NoListenersCallback<TListeners> | undefined);
63
71
  protected emit<K extends keyof TListeners>(eventName: K, ...args: Parameters<TListeners[K]>): void;
64
72
  protected emitAndCollect<K extends keyof TListeners>(eventName: K, ...args: Parameters<TListeners[K]>): ReturnType<TListeners[K]>[];
@@ -1 +1 @@
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S,MAAM,UAAU,EAClD,SAAS,EAAE,CAAC,EACZ,GAAG,IAAI,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAChC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE;IAgBvB,EAAE,CAAC,CAAC,SAAS,MAAM,SAAS,CAAC,UAAU,CAAC,EAC9C,SAAS,EAAE,CAAC,EACZ,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC,GACrB,GAAG;IAyBC,GAAG,CAAC,CAAC,SAAS,MAAM,SAAS,CAAC,UAAU,CAAC,EAC/C,SAAS,EAAE,CAAC,EACZ,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC,GACrB,IAAI;IAYA,YAAY,CAAC,SAAS,CAAC,EAAE,MAAM,UAAU,GAAG,OAAO;CAM1D;AA6BD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,aAAa,CAAC,UAAU,SAAS,MAAM,EACtD,WAAW,CAAC,EAAE,mBAAmB,CAAC,UAAU,CAAC,GAC3C,UAAU,CAAC,UAAU,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,YAAY,CAAC,UAAU,CAAC,CAE1E"}
@@ -6,22 +6,6 @@
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
7
  exports.CustomEventEmitter = void 0;
8
8
  exports.createEmitter = createEmitter;
9
- /**
10
- * Retrieve a value from a map with the given key, or create a new entry if the key is not in the map.
11
- * @param map - The map to query/update
12
- * @param key - The key to lookup in the map
13
- * @param defaultValue - a function which returns a default value. This is called and used to set an initial value for the given key in the map if none exists
14
- * @returns either the existing value for the given key, or the newly-created value (the result of `defaultValue`)
15
- * @internal
16
- */
17
- function getOrCreate(map, key, defaultValue) {
18
- let value = map.get(key);
19
- if (value === undefined) {
20
- value = defaultValue(key);
21
- map.set(key, value);
22
- }
23
- return value;
24
- }
25
9
  /**
26
10
  * Provides an API for subscribing to and listening to events.
27
11
  *
@@ -77,6 +61,14 @@ function getOrCreate(map, key, defaultValue) {
77
61
  */
78
62
  class CustomEventEmitter {
79
63
  noListeners;
64
+ /**
65
+ * The listeners of each event with listeners: the listener itself while it is the only one,
66
+ * and a set of them once a second is added.
67
+ * @remarks
68
+ * Most emitters have at most one listener per event, so this saves a set for each of their events.
69
+ * A set is kept until the event has no listeners, so that listeners added or removed by another listener
70
+ * during an emit are treated the same whether or not the event had a set.
71
+ */
80
72
  listeners = new Map();
81
73
  // Because this is protected and not public, calling this externally (not from a subclass) makes sending events to the constructed instance impossible.
82
74
  // Instead, use the static `create` function to get an instance which allows emitting events.
@@ -85,9 +77,12 @@ class CustomEventEmitter {
85
77
  }
86
78
  emit(eventName, ...args) {
87
79
  const listeners = this.listeners.get(eventName);
88
- if (listeners !== undefined) {
89
- // Current tsc (5.4.5) cannot spread `args` into `listener()`.
90
- const argArray = args;
80
+ // Current tsc (5.4.5) cannot spread `args` into `listener()`.
81
+ const argArray = args;
82
+ if (typeof listeners === "function") {
83
+ listeners(...argArray);
84
+ }
85
+ else if (listeners !== undefined) {
91
86
  // This explicitly copies listeners so that new listeners added during this call to emit will not receive this event.
92
87
  for (const listener of [...listeners]) {
93
88
  // If listener has been unsubscribed while invoking other listeners, skip it.
@@ -99,8 +94,11 @@ class CustomEventEmitter {
99
94
  }
100
95
  emitAndCollect(eventName, ...args) {
101
96
  const listeners = this.listeners.get(eventName);
97
+ const argArray = args;
98
+ if (typeof listeners === "function") {
99
+ return [listeners(...argArray)];
100
+ }
102
101
  if (listeners !== undefined) {
103
- const argArray = args;
104
102
  const resultArray = [];
105
103
  for (const listener of [...listeners.values()]) {
106
104
  resultArray.push(listener(...argArray));
@@ -110,17 +108,31 @@ class CustomEventEmitter {
110
108
  return [];
111
109
  }
112
110
  on(eventName, listener) {
113
- const listeners = getOrCreate(this.listeners, eventName, () => new Set());
114
- if (listeners.has(listener)) {
111
+ const listeners = this.listeners.get(eventName);
112
+ if (listeners === undefined) {
113
+ this.listeners.set(eventName, listener);
114
+ }
115
+ else if (typeof listeners === "function" ? listeners === listener : listeners.has(listener)) {
115
116
  const eventDescription = typeof eventName === "symbol" ? eventName.description : String(eventName.toString());
116
117
  throw new Error(`Attempted to register the same listener object twice for event ${eventDescription}`);
117
118
  }
118
- listeners.add(listener);
119
+ else if (typeof listeners === "function") {
120
+ // Added one at a time: a set built from an array is allocated with a larger table.
121
+ const set = new Set();
122
+ set.add(listeners);
123
+ set.add(listener);
124
+ this.listeners.set(eventName, set);
125
+ }
126
+ else {
127
+ listeners.add(listener);
128
+ }
119
129
  return () => this.off(eventName, listener);
120
130
  }
121
131
  off(eventName, listener) {
122
132
  const listeners = this.listeners.get(eventName);
123
- if (listeners?.delete(listener) === true && listeners.size === 0) {
133
+ if (typeof listeners === "function"
134
+ ? listeners === listener
135
+ : listeners?.delete(listener) === true && listeners.size === 0) {
124
136
  this.listeners.delete(eventName);
125
137
  this.noListeners?.(eventName);
126
138
  }
@@ -1 +1 @@
1
- {"version":3,"file":"emitter.js","sourceRoot":"","sources":["../../src/events/emitter.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AA4NH,sCAIC;AApND;;;;;;;GAOG;AACH,SAAS,WAAW,CAAO,GAAoB,EAAE,GAAM,EAAE,YAA2B;IACnF,IAAI,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACzB,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACzB,KAAK,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC;QAC1B,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACrB,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AACH,MAAa,kBAAkB;IAUS;IAPpB,SAAS,GAAG,IAAI,GAAG,EAGnC,CAAC;IAEJ,uJAAuJ;IACvJ,6FAA6F;IAC7F,YAAuC,WAA6C;QA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Y,EACZ,GAAG,IAA+B;QAElC,OAAO,KAAK,CAAC,cAAc,CAAC,SAAS,EAAE,GAAG,IAAI,CAAC,CAAC;IACjD,CAAC;CACD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,SAAgB,aAAa,CAC5B,WAA6C;IAE7C,OAAO,IAAI,sBAAsB,CAAa,WAAW,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type {\n\tHasListeners,\n\tIEmitter,\n\tListenable,\n\tListeners,\n\tMapGetSet,\n\tNoListenersCallback,\n\tOff,\n} from \"@fluidframework/core-interfaces/internal\";\n\n/**\n * Retrieve a value from a map with the given key, or create a new entry if the key is not in the map.\n * @param map - The map to query/update\n * @param key - The key to lookup in the map\n * @param defaultValue - a function which returns a default value. This is called and used to set an initial value for the given key in the map if none exists\n * @returns either the existing value for the given key, or the newly-created value (the result of `defaultValue`)\n * @internal\n */\nfunction getOrCreate<K, V>(map: MapGetSet<K, V>, key: K, defaultValue: (key: K) => V): V {\n\tlet value = map.get(key);\n\tif (value === undefined) {\n\t\tvalue = defaultValue(key);\n\t\tmap.set(key, value);\n\t}\n\treturn value;\n}\n\n/**\n * Provides an API for subscribing to and listening to events.\n *\n * @remarks Classes wishing to emit events may either extend this class, compose over it, or expose it as a property of type {@link @fluidframework/core-interfaces#Listenable}.\n *\n * @example Extending this class\n *\n * ```typescript\n * interface MyEvents {\n * \tloaded: () => void;\n * \tcomputed: () => number;\n * }\n *\n * class MyInheritanceClass extends EventEmitter<MyEvents> {\n * \tprivate load() {\n * \t\tthis.emit(\"loaded\");\n * \t\tconst results: number[] = this.emitAndCollect(\"computed\");\n * \t}\n * }\n * ```\n *\n * @example Composing over this class\n *\n * ```typescript\n * class MyCompositionClass implements Listenable<MyEvents> {\n * \tprivate readonly events = createEmitter<MyEvents>();\n *\n * \tprivate load() {\n * \t\tthis.events.emit(\"loaded\");\n * \t\tconst results: number[] = this.events.emitAndCollect(\"computed\");\n * \t}\n *\n * \tpublic on<K extends keyof MyEvents>(eventName: K, listener: MyEvents[K]): () => void {\n * \t\treturn this.events.on(eventName, listener);\n * \t}\n * }\n * ```\n *\n * @example Exposing this class as a property\n *\n * ```typescript\n * class MyExposingClass {\n * \tprivate readonly _events = createEmitter<MyEvents>();\n * \tpublic readonly events: Listenable<MyEvents> = this._events;\n *\n * \tprivate load() {\n * \t\tthis._events.emit(\"loaded\");\n * \t\tconst results: number[] = this._events.emitAndCollect(\"computed\");\n * \t}\n * }\n * ```\n * @internal\n */\nexport class CustomEventEmitter<TListeners extends Listeners<TListeners>>\n\timplements Listenable<TListeners>, HasListeners<TListeners>\n{\n\tprotected readonly listeners = new Map<\n\t\tkeyof TListeners,\n\t\tSet<(...args: any[]) => TListeners[keyof TListeners]>\n\t>();\n\n\t// Because this is protected and not public, calling this externally (not from a subclass) makes sending events to the constructed instance impossible.\n\t// Instead, use the static `create` function to get an instance which allows emitting events.\n\tprotected constructor(private readonly noListeners?: NoListenersCallback<TListeners>) {}\n\n\tprotected emit<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): void {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\tif (listeners !== undefined) {\n\t\t\t// Current tsc (5.4.5) cannot spread `args` into `listener()`.\n\t\t\tconst argArray: unknown[] = args;\n\t\t\t// This explicitly copies listeners so that new listeners added during this call to emit will not receive this event.\n\t\t\tfor (const listener of [...listeners]) {\n\t\t\t\t// If listener has been unsubscribed while invoking other listeners, skip it.\n\t\t\t\tif (listeners.has(listener)) {\n\t\t\t\t\tlistener(...argArray);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected emitAndCollect<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): ReturnType<TListeners[K]>[] {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\tif (listeners !== undefined) {\n\t\t\tconst argArray: unknown[] = args;\n\t\t\tconst resultArray: ReturnType<TListeners[K]>[] = [];\n\t\t\tfor (const listener of [...listeners.values()]) {\n\t\t\t\tresultArray.push(listener(...argArray));\n\t\t\t}\n\t\t\treturn resultArray;\n\t\t}\n\t\treturn [];\n\t}\n\n\tpublic on<K extends keyof Listeners<TListeners>>(\n\t\teventName: K,\n\t\tlistener: TListeners[K],\n\t): Off {\n\t\tconst listeners = getOrCreate(this.listeners, eventName, () => new Set());\n\t\tif (listeners.has(listener)) {\n\t\t\tconst eventDescription =\n\t\t\t\ttypeof eventName === \"symbol\" ? eventName.description : String(eventName.toString());\n\n\t\t\tthrow new Error(\n\t\t\t\t`Attempted to register the same listener object twice for event ${eventDescription}`,\n\t\t\t);\n\t\t}\n\t\tlisteners.add(listener);\n\t\treturn () => this.off(eventName, listener);\n\t}\n\n\tpublic off<K extends keyof Listeners<TListeners>>(\n\t\teventName: K,\n\t\tlistener: TListeners[K],\n\t): void {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\tif (listeners?.delete(listener) === true && listeners.size === 0) {\n\t\t\tthis.listeners.delete(eventName);\n\t\t\tthis.noListeners?.(eventName);\n\t\t}\n\t}\n\n\tpublic hasListeners(eventName?: keyof TListeners): boolean {\n\t\tif (eventName === undefined) {\n\t\t\treturn this.listeners.size > 0;\n\t\t}\n\t\treturn this.listeners.has(eventName);\n\t}\n}\n\n/**\n * This class exposes the constructor and the `emit` method of `EventEmitter`, elevating them from protected to public\n * @internal\n */\nclass ComposableEventEmitter<TListeners extends Listeners<TListeners>>\n\textends CustomEventEmitter<TListeners>\n\timplements IEmitter<TListeners>\n{\n\tpublic constructor(noListeners?: NoListenersCallback<TListeners>) {\n\t\tsuper(noListeners);\n\t}\n\n\tpublic override emit<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): void {\n\t\treturn super.emit(eventName, ...args);\n\t}\n\n\tpublic override emitAndCollect<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): ReturnType<TListeners[K]>[] {\n\t\treturn super.emitAndCollect(eventName, ...args);\n\t}\n}\n\n/**\n * Create a {@link @fluidframework/core-interfaces#Listenable} that can be instructed to emit events via the {@link @fluidframework/core-interfaces#IEmitter} interface.\n *\n * A class can delegate handling {@link @fluidframework/core-interfaces#Listenable} to the returned value while using it to emit the events.\n * See also CustomEventEmitter which be used as a base class to implement {@link @fluidframework/core-interfaces#Listenable} via extension.\n * @example Forwarding events to the emitter\n * ```typescript\n * interface MyEvents {\n * \tloaded(): void;\n * }\n *\n * class MyClass implements Listenable<MyEvents> {\n * \tprivate readonly events = createEmitter<MyEvents>();\n *\n * \tprivate load(): void {\n * \t\tthis.events.emit(\"loaded\");\n * \t}\n *\n * \tpublic on<K extends keyof MyEvents>(eventName: K, listener: MyEvents[K]): Off {\n * \t\treturn this.events.on(eventName, listener);\n * \t}\n *\n * \tpublic off<K extends keyof MyEvents>(eventName: K, listener: MyEvents[K]): void {\n * \t\treturn this.events.off(eventName, listener);\n * \t}\n * }\n * ```\n * @internal\n */\nexport function createEmitter<TListeners extends object>(\n\tnoListeners?: NoListenersCallback<TListeners>,\n): Listenable<TListeners> & IEmitter<TListeners> & HasListeners<TListeners> {\n\treturn new ComposableEventEmitter<TListeners>(noListeners);\n}\n"]}
1
+ {"version":3,"file":"emitter.js","sourceRoot":"","sources":["../../src/events/emitter.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAuOH,sCAIC;AAhOD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AACH,MAAa,kBAAkB;IAmBS;IAhBvC;;;;;;;OAOG;IACgB,SAAS,GAAG,IAAI,GAAG,EAInC,CAAC;IAEJ,uJAAuJ;IACvJ,6FAA6F;IAC7F,YAAuC,WAA6C;QAA7C,gBAAW,GAAX,WAAW,CAAkC;IAAG,CAAC;IAE9E,IAAI,CACb,SAAY,EACZ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CAAC,KAAK,IAAI,IAAI,SAAS,CAAC,IAAI,KAAK,CAAC,EAC9D,CAAC;YACF,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;YACjC,IAAI,CAAC,WAAW,EAAE,CAAC,SAAS,CAAC,CAAC;QAC/B,CAAC;IACF,CAAC;IAEM,YAAY,CAAC,SAA4B;QAC/C,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;YAC7B,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,GAAG,CAAC,CAAC;QAChC,CAAC;QACD,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACtC,CAAC;CACD;AA7GD,gDA6GC;AAED;;;GAGG;AACH,MAAM,sBACL,SAAQ,kBAA8B;IAGtC,YAAmB,WAA6C;QAC/D,KAAK,CAAC,WAAW,CAAC,CAAC;IACpB,CAAC;IAEe,IAAI,CACnB,SAAY,EACZ,GAAG,IAA+B;QAElC,OAAO,KAAK,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,IAAI,CAAC,CAAC;IACvC,CAAC;IAEe,cAAc,CAC7B,SAAY,EACZ,GAAG,IAA+B;QAElC,OAAO,KAAK,CAAC,cAAc,CAAC,SAAS,EAAE,GAAG,IAAI,CAAC,CAAC;IACjD,CAAC;CACD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,SAAgB,aAAa,CAC5B,WAA6C;IAE7C,OAAO,IAAI,sBAAsB,CAAa,WAAW,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type {\n\tHasListeners,\n\tIEmitter,\n\tListenable,\n\tListeners,\n\tNoListenersCallback,\n\tOff,\n} from \"@fluidframework/core-interfaces/internal\";\n\n/**\n * Provides an API for subscribing to and listening to events.\n *\n * @remarks Classes wishing to emit events may either extend this class, compose over it, or expose it as a property of type {@link @fluidframework/core-interfaces#Listenable}.\n *\n * @example Extending this class\n *\n * ```typescript\n * interface MyEvents {\n * \tloaded: () => void;\n * \tcomputed: () => number;\n * }\n *\n * class MyInheritanceClass extends EventEmitter<MyEvents> {\n * \tprivate load() {\n * \t\tthis.emit(\"loaded\");\n * \t\tconst results: number[] = this.emitAndCollect(\"computed\");\n * \t}\n * }\n * ```\n *\n * @example Composing over this class\n *\n * ```typescript\n * class MyCompositionClass implements Listenable<MyEvents> {\n * \tprivate readonly events = createEmitter<MyEvents>();\n *\n * \tprivate load() {\n * \t\tthis.events.emit(\"loaded\");\n * \t\tconst results: number[] = this.events.emitAndCollect(\"computed\");\n * \t}\n *\n * \tpublic on<K extends keyof MyEvents>(eventName: K, listener: MyEvents[K]): () => void {\n * \t\treturn this.events.on(eventName, listener);\n * \t}\n * }\n * ```\n *\n * @example Exposing this class as a property\n *\n * ```typescript\n * class MyExposingClass {\n * \tprivate readonly _events = createEmitter<MyEvents>();\n * \tpublic readonly events: Listenable<MyEvents> = this._events;\n *\n * \tprivate load() {\n * \t\tthis._events.emit(\"loaded\");\n * \t\tconst results: number[] = this._events.emitAndCollect(\"computed\");\n * \t}\n * }\n * ```\n * @internal\n */\nexport class CustomEventEmitter<TListeners extends Listeners<TListeners>>\n\timplements Listenable<TListeners>, HasListeners<TListeners>\n{\n\t/**\n\t * The listeners of each event with listeners: the listener itself while it is the only one,\n\t * and a set of them once a second is added.\n\t * @remarks\n\t * Most emitters have at most one listener per event, so this saves a set for each of their events.\n\t * A set is kept until the event has no listeners, so that listeners added or removed by another listener\n\t * during an emit are treated the same whether or not the event had a set.\n\t */\n\tprotected readonly listeners = new Map<\n\t\tkeyof TListeners,\n\t\t| ((...args: any[]) => TListeners[keyof TListeners])\n\t\t| Set<(...args: any[]) => TListeners[keyof TListeners]>\n\t>();\n\n\t// Because this is protected and not public, calling this externally (not from a subclass) makes sending events to the constructed instance impossible.\n\t// Instead, use the static `create` function to get an instance which allows emitting events.\n\tprotected constructor(private readonly noListeners?: NoListenersCallback<TListeners>) {}\n\n\tprotected emit<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): void {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\t// Current tsc (5.4.5) cannot spread `args` into `listener()`.\n\t\tconst argArray: unknown[] = args;\n\t\tif (typeof listeners === \"function\") {\n\t\t\tlisteners(...argArray);\n\t\t} else if (listeners !== undefined) {\n\t\t\t// This explicitly copies listeners so that new listeners added during this call to emit will not receive this event.\n\t\t\tfor (const listener of [...listeners]) {\n\t\t\t\t// If listener has been unsubscribed while invoking other listeners, skip it.\n\t\t\t\tif (listeners.has(listener)) {\n\t\t\t\t\tlistener(...argArray);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected emitAndCollect<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): ReturnType<TListeners[K]>[] {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\tconst argArray: unknown[] = args;\n\t\tif (typeof listeners === \"function\") {\n\t\t\treturn [listeners(...argArray) as ReturnType<TListeners[K]>];\n\t\t}\n\t\tif (listeners !== undefined) {\n\t\t\tconst resultArray: ReturnType<TListeners[K]>[] = [];\n\t\t\tfor (const listener of [...listeners.values()]) {\n\t\t\t\tresultArray.push(listener(...argArray));\n\t\t\t}\n\t\t\treturn resultArray;\n\t\t}\n\t\treturn [];\n\t}\n\n\tpublic on<K extends keyof Listeners<TListeners>>(\n\t\teventName: K,\n\t\tlistener: TListeners[K],\n\t): Off {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\tif (listeners === undefined) {\n\t\t\tthis.listeners.set(eventName, listener);\n\t\t} else if (\n\t\t\ttypeof listeners === \"function\" ? listeners === listener : listeners.has(listener)\n\t\t) {\n\t\t\tconst eventDescription =\n\t\t\t\ttypeof eventName === \"symbol\" ? eventName.description : String(eventName.toString());\n\n\t\t\tthrow new Error(\n\t\t\t\t`Attempted to register the same listener object twice for event ${eventDescription}`,\n\t\t\t);\n\t\t} else if (typeof listeners === \"function\") {\n\t\t\t// Added one at a time: a set built from an array is allocated with a larger table.\n\t\t\tconst set = new Set<(...args: any[]) => TListeners[keyof TListeners]>();\n\t\t\tset.add(listeners);\n\t\t\tset.add(listener);\n\t\t\tthis.listeners.set(eventName, set);\n\t\t} else {\n\t\t\tlisteners.add(listener);\n\t\t}\n\t\treturn () => this.off(eventName, listener);\n\t}\n\n\tpublic off<K extends keyof Listeners<TListeners>>(\n\t\teventName: K,\n\t\tlistener: TListeners[K],\n\t): void {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\tif (\n\t\t\ttypeof listeners === \"function\"\n\t\t\t\t? listeners === listener\n\t\t\t\t: listeners?.delete(listener) === true && listeners.size === 0\n\t\t) {\n\t\t\tthis.listeners.delete(eventName);\n\t\t\tthis.noListeners?.(eventName);\n\t\t}\n\t}\n\n\tpublic hasListeners(eventName?: keyof TListeners): boolean {\n\t\tif (eventName === undefined) {\n\t\t\treturn this.listeners.size > 0;\n\t\t}\n\t\treturn this.listeners.has(eventName);\n\t}\n}\n\n/**\n * This class exposes the constructor and the `emit` method of `EventEmitter`, elevating them from protected to public\n * @internal\n */\nclass ComposableEventEmitter<TListeners extends Listeners<TListeners>>\n\textends CustomEventEmitter<TListeners>\n\timplements IEmitter<TListeners>\n{\n\tpublic constructor(noListeners?: NoListenersCallback<TListeners>) {\n\t\tsuper(noListeners);\n\t}\n\n\tpublic override emit<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): void {\n\t\treturn super.emit(eventName, ...args);\n\t}\n\n\tpublic override emitAndCollect<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): ReturnType<TListeners[K]>[] {\n\t\treturn super.emitAndCollect(eventName, ...args);\n\t}\n}\n\n/**\n * Create a {@link @fluidframework/core-interfaces#Listenable} that can be instructed to emit events via the {@link @fluidframework/core-interfaces#IEmitter} interface.\n *\n * A class can delegate handling {@link @fluidframework/core-interfaces#Listenable} to the returned value while using it to emit the events.\n * See also CustomEventEmitter which be used as a base class to implement {@link @fluidframework/core-interfaces#Listenable} via extension.\n * @example Forwarding events to the emitter\n * ```typescript\n * interface MyEvents {\n * \tloaded(): void;\n * }\n *\n * class MyClass implements Listenable<MyEvents> {\n * \tprivate readonly events = createEmitter<MyEvents>();\n *\n * \tprivate load(): void {\n * \t\tthis.events.emit(\"loaded\");\n * \t}\n *\n * \tpublic on<K extends keyof MyEvents>(eventName: K, listener: MyEvents[K]): Off {\n * \t\treturn this.events.on(eventName, listener);\n * \t}\n *\n * \tpublic off<K extends keyof MyEvents>(eventName: K, listener: MyEvents[K]): void {\n * \t\treturn this.events.off(eventName, listener);\n * \t}\n * }\n * ```\n * @internal\n */\nexport function createEmitter<TListeners extends object>(\n\tnoListeners?: NoListenersCallback<TListeners>,\n): Listenable<TListeners> & IEmitter<TListeners> & HasListeners<TListeners> {\n\treturn new ComposableEventEmitter<TListeners>(noListeners);\n}\n"]}
@@ -58,7 +58,15 @@ import type { HasListeners, IEmitter, Listenable, Listeners, NoListenersCallback
58
58
  */
59
59
  export declare class CustomEventEmitter<TListeners extends Listeners<TListeners>> implements Listenable<TListeners>, HasListeners<TListeners> {
60
60
  private readonly noListeners?;
61
- protected readonly listeners: Map<keyof TListeners, Set<(...args: any[]) => TListeners[keyof TListeners]>>;
61
+ /**
62
+ * The listeners of each event with listeners: the listener itself while it is the only one,
63
+ * and a set of them once a second is added.
64
+ * @remarks
65
+ * Most emitters have at most one listener per event, so this saves a set for each of their events.
66
+ * A set is kept until the event has no listeners, so that listeners added or removed by another listener
67
+ * during an emit are treated the same whether or not the event had a set.
68
+ */
69
+ protected readonly listeners: Map<keyof TListeners, Set<(...args: any[]) => TListeners[keyof TListeners]> | ((...args: any[]) => TListeners[keyof TListeners])>;
62
70
  protected constructor(noListeners?: NoListenersCallback<TListeners> | undefined);
63
71
  protected emit<K extends keyof TListeners>(eventName: K, ...args: Parameters<TListeners[K]>): void;
64
72
  protected emitAndCollect<K extends keyof TListeners>(eventName: K, ...args: Parameters<TListeners[K]>): ReturnType<TListeners[K]>[];
@@ -1 +1 @@
1
- {"version":3,"file":"emitter.d.ts","sourceRoot":"","sources":["../../src/events/emitter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EACX,YAAY,EACZ,QAAQ,EACR,UAAU,EACV,SAAS,EAET,mBAAmB,EACnB,GAAG,EACH,MAAM,0CAA0C,CAAC;AAmBlD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AACH,qBAAa,kBAAkB,CAAC,UAAU,SAAS,SAAS,CAAC,UAAU,CAAC,CACvE,YAAW,UAAU,CAAC,UAAU,CAAC,EAAE,YAAY,CAAC,UAAU,CAAC;IASrC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC;IAPnD,SAAS,CAAC,QAAQ,CAAC,SAAS,sCAEb,GAAG,EAAE,KAAK,UAAU,CAAC,MAAM,UAAU,CAAC,GACjD;IAIJ,SAAS,aAA8B,WAAW,CAAC,EAAE,mBAAmB,CAAC,UAAU,CAAC,YAAA;IAEpF,SAAS,CAAC,IAAI,CAAC,CAAC,SAAS,MAAM,UAAU,EACxC,SAAS,EAAE,CAAC,EACZ,GAAG,IAAI,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAChC,IAAI;IAeP,SAAS,CAAC,cAAc,CAAC,CAAC,SAAS,MAAM,UAAU,EAClD,SAAS,EAAE,CAAC,EACZ,GAAG,IAAI,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAChC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE;IAavB,EAAE,CAAC,CAAC,SAAS,MAAM,SAAS,CAAC,UAAU,CAAC,EAC9C,SAAS,EAAE,CAAC,EACZ,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC,GACrB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C,EACZ,GAAG,IAAI,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAChC,IAAI;IAiBP,SAAS,CAAC,cAAc,CAAC,CAAC,SAAS,MAAM,UAAU,EAClD,SAAS,EAAE,CAAC,EACZ,GAAG,IAAI,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,GAChC,UAAU,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE;IAgBvB,EAAE,CAAC,CAAC,SAAS,MAAM,SAAS,CAAC,UAAU,CAAC,EAC9C,SAAS,EAAE,CAAC,EACZ,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC,GACrB,GAAG;IAyBC,GAAG,CAAC,CAAC,SAAS,MAAM,SAAS,CAAC,UAAU,CAAC,EAC/C,SAAS,EAAE,CAAC,EACZ,QAAQ,EAAE,UAAU,CAAC,CAAC,CAAC,GACrB,IAAI;IAYA,YAAY,CAAC,SAAS,CAAC,EAAE,MAAM,UAAU,GAAG,OAAO;CAM1D;AA6BD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,aAAa,CAAC,UAAU,SAAS,MAAM,EACtD,WAAW,CAAC,EAAE,mBAAmB,CAAC,UAAU,CAAC,GAC3C,UAAU,CAAC,UAAU,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,YAAY,CAAC,UAAU,CAAC,CAE1E"}
@@ -2,22 +2,6 @@
2
2
  * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
3
  * Licensed under the MIT License.
4
4
  */
5
- /**
6
- * Retrieve a value from a map with the given key, or create a new entry if the key is not in the map.
7
- * @param map - The map to query/update
8
- * @param key - The key to lookup in the map
9
- * @param defaultValue - a function which returns a default value. This is called and used to set an initial value for the given key in the map if none exists
10
- * @returns either the existing value for the given key, or the newly-created value (the result of `defaultValue`)
11
- * @internal
12
- */
13
- function getOrCreate(map, key, defaultValue) {
14
- let value = map.get(key);
15
- if (value === undefined) {
16
- value = defaultValue(key);
17
- map.set(key, value);
18
- }
19
- return value;
20
- }
21
5
  /**
22
6
  * Provides an API for subscribing to and listening to events.
23
7
  *
@@ -73,6 +57,14 @@ function getOrCreate(map, key, defaultValue) {
73
57
  */
74
58
  export class CustomEventEmitter {
75
59
  noListeners;
60
+ /**
61
+ * The listeners of each event with listeners: the listener itself while it is the only one,
62
+ * and a set of them once a second is added.
63
+ * @remarks
64
+ * Most emitters have at most one listener per event, so this saves a set for each of their events.
65
+ * A set is kept until the event has no listeners, so that listeners added or removed by another listener
66
+ * during an emit are treated the same whether or not the event had a set.
67
+ */
76
68
  listeners = new Map();
77
69
  // Because this is protected and not public, calling this externally (not from a subclass) makes sending events to the constructed instance impossible.
78
70
  // Instead, use the static `create` function to get an instance which allows emitting events.
@@ -81,9 +73,12 @@ export class CustomEventEmitter {
81
73
  }
82
74
  emit(eventName, ...args) {
83
75
  const listeners = this.listeners.get(eventName);
84
- if (listeners !== undefined) {
85
- // Current tsc (5.4.5) cannot spread `args` into `listener()`.
86
- const argArray = args;
76
+ // Current tsc (5.4.5) cannot spread `args` into `listener()`.
77
+ const argArray = args;
78
+ if (typeof listeners === "function") {
79
+ listeners(...argArray);
80
+ }
81
+ else if (listeners !== undefined) {
87
82
  // This explicitly copies listeners so that new listeners added during this call to emit will not receive this event.
88
83
  for (const listener of [...listeners]) {
89
84
  // If listener has been unsubscribed while invoking other listeners, skip it.
@@ -95,8 +90,11 @@ export class CustomEventEmitter {
95
90
  }
96
91
  emitAndCollect(eventName, ...args) {
97
92
  const listeners = this.listeners.get(eventName);
93
+ const argArray = args;
94
+ if (typeof listeners === "function") {
95
+ return [listeners(...argArray)];
96
+ }
98
97
  if (listeners !== undefined) {
99
- const argArray = args;
100
98
  const resultArray = [];
101
99
  for (const listener of [...listeners.values()]) {
102
100
  resultArray.push(listener(...argArray));
@@ -106,17 +104,31 @@ export class CustomEventEmitter {
106
104
  return [];
107
105
  }
108
106
  on(eventName, listener) {
109
- const listeners = getOrCreate(this.listeners, eventName, () => new Set());
110
- if (listeners.has(listener)) {
107
+ const listeners = this.listeners.get(eventName);
108
+ if (listeners === undefined) {
109
+ this.listeners.set(eventName, listener);
110
+ }
111
+ else if (typeof listeners === "function" ? listeners === listener : listeners.has(listener)) {
111
112
  const eventDescription = typeof eventName === "symbol" ? eventName.description : String(eventName.toString());
112
113
  throw new Error(`Attempted to register the same listener object twice for event ${eventDescription}`);
113
114
  }
114
- listeners.add(listener);
115
+ else if (typeof listeners === "function") {
116
+ // Added one at a time: a set built from an array is allocated with a larger table.
117
+ const set = new Set();
118
+ set.add(listeners);
119
+ set.add(listener);
120
+ this.listeners.set(eventName, set);
121
+ }
122
+ else {
123
+ listeners.add(listener);
124
+ }
115
125
  return () => this.off(eventName, listener);
116
126
  }
117
127
  off(eventName, listener) {
118
128
  const listeners = this.listeners.get(eventName);
119
- if (listeners?.delete(listener) === true && listeners.size === 0) {
129
+ if (typeof listeners === "function"
130
+ ? listeners === listener
131
+ : listeners?.delete(listener) === true && listeners.size === 0) {
120
132
  this.listeners.delete(eventName);
121
133
  this.noListeners?.(eventName);
122
134
  }
@@ -1 +1 @@
1
- {"version":3,"file":"emitter.js","sourceRoot":"","sources":["../../src/events/emitter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAYH;;;;;;;GAOG;AACH,SAAS,WAAW,CAAO,GAAoB,EAAE,GAAM,EAAE,YAA2B;IACnF,IAAI,KAAK,GAAG,GAAG,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACzB,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;QACzB,KAAK,GAAG,YAAY,CAAC,GAAG,CAAC,CAAC;QAC1B,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACrB,CAAC;IACD,OAAO,KAAK,CAAC;AACd,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AACH,MAAM,OAAO,kBAAkB;IAUS;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C,IAAI,CAAC,SAAS,EAAE,GAAG,IAAI,CAAC,CAAC;IACvC,CAAC;IAEe,cAAc,CAC7B,SAAY,EACZ,GAAG,IAA+B;QAElC,OAAO,KAAK,CAAC,cAAc,CAAC,SAAS,EAAE,GAAG,IAAI,CAAC,CAAC;IACjD,CAAC;CACD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,UAAU,aAAa,CAC5B,WAA6C;IAE7C,OAAO,IAAI,sBAAsB,CAAa,WAAW,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type {\n\tHasListeners,\n\tIEmitter,\n\tListenable,\n\tListeners,\n\tMapGetSet,\n\tNoListenersCallback,\n\tOff,\n} from \"@fluidframework/core-interfaces/internal\";\n\n/**\n * Retrieve a value from a map with the given key, or create a new entry if the key is not in the map.\n * @param map - The map to query/update\n * @param key - The key to lookup in the map\n * @param defaultValue - a function which returns a default value. This is called and used to set an initial value for the given key in the map if none exists\n * @returns either the existing value for the given key, or the newly-created value (the result of `defaultValue`)\n * @internal\n */\nfunction getOrCreate<K, V>(map: MapGetSet<K, V>, key: K, defaultValue: (key: K) => V): V {\n\tlet value = map.get(key);\n\tif (value === undefined) {\n\t\tvalue = defaultValue(key);\n\t\tmap.set(key, value);\n\t}\n\treturn value;\n}\n\n/**\n * Provides an API for subscribing to and listening to events.\n *\n * @remarks Classes wishing to emit events may either extend this class, compose over it, or expose it as a property of type {@link @fluidframework/core-interfaces#Listenable}.\n *\n * @example Extending this class\n *\n * ```typescript\n * interface MyEvents {\n * \tloaded: () => void;\n * \tcomputed: () => number;\n * }\n *\n * class MyInheritanceClass extends EventEmitter<MyEvents> {\n * \tprivate load() {\n * \t\tthis.emit(\"loaded\");\n * \t\tconst results: number[] = this.emitAndCollect(\"computed\");\n * \t}\n * }\n * ```\n *\n * @example Composing over this class\n *\n * ```typescript\n * class MyCompositionClass implements Listenable<MyEvents> {\n * \tprivate readonly events = createEmitter<MyEvents>();\n *\n * \tprivate load() {\n * \t\tthis.events.emit(\"loaded\");\n * \t\tconst results: number[] = this.events.emitAndCollect(\"computed\");\n * \t}\n *\n * \tpublic on<K extends keyof MyEvents>(eventName: K, listener: MyEvents[K]): () => void {\n * \t\treturn this.events.on(eventName, listener);\n * \t}\n * }\n * ```\n *\n * @example Exposing this class as a property\n *\n * ```typescript\n * class MyExposingClass {\n * \tprivate readonly _events = createEmitter<MyEvents>();\n * \tpublic readonly events: Listenable<MyEvents> = this._events;\n *\n * \tprivate load() {\n * \t\tthis._events.emit(\"loaded\");\n * \t\tconst results: number[] = this._events.emitAndCollect(\"computed\");\n * \t}\n * }\n * ```\n * @internal\n */\nexport class CustomEventEmitter<TListeners extends Listeners<TListeners>>\n\timplements Listenable<TListeners>, HasListeners<TListeners>\n{\n\tprotected readonly listeners = new Map<\n\t\tkeyof TListeners,\n\t\tSet<(...args: any[]) => TListeners[keyof TListeners]>\n\t>();\n\n\t// Because this is protected and not public, calling this externally (not from a subclass) makes sending events to the constructed instance impossible.\n\t// Instead, use the static `create` function to get an instance which allows emitting events.\n\tprotected constructor(private readonly noListeners?: NoListenersCallback<TListeners>) {}\n\n\tprotected emit<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): void {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\tif (listeners !== undefined) {\n\t\t\t// Current tsc (5.4.5) cannot spread `args` into `listener()`.\n\t\t\tconst argArray: unknown[] = args;\n\t\t\t// This explicitly copies listeners so that new listeners added during this call to emit will not receive this event.\n\t\t\tfor (const listener of [...listeners]) {\n\t\t\t\t// If listener has been unsubscribed while invoking other listeners, skip it.\n\t\t\t\tif (listeners.has(listener)) {\n\t\t\t\t\tlistener(...argArray);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected emitAndCollect<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): ReturnType<TListeners[K]>[] {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\tif (listeners !== undefined) {\n\t\t\tconst argArray: unknown[] = args;\n\t\t\tconst resultArray: ReturnType<TListeners[K]>[] = [];\n\t\t\tfor (const listener of [...listeners.values()]) {\n\t\t\t\tresultArray.push(listener(...argArray));\n\t\t\t}\n\t\t\treturn resultArray;\n\t\t}\n\t\treturn [];\n\t}\n\n\tpublic on<K extends keyof Listeners<TListeners>>(\n\t\teventName: K,\n\t\tlistener: TListeners[K],\n\t): Off {\n\t\tconst listeners = getOrCreate(this.listeners, eventName, () => new Set());\n\t\tif (listeners.has(listener)) {\n\t\t\tconst eventDescription =\n\t\t\t\ttypeof eventName === \"symbol\" ? eventName.description : String(eventName.toString());\n\n\t\t\tthrow new Error(\n\t\t\t\t`Attempted to register the same listener object twice for event ${eventDescription}`,\n\t\t\t);\n\t\t}\n\t\tlisteners.add(listener);\n\t\treturn () => this.off(eventName, listener);\n\t}\n\n\tpublic off<K extends keyof Listeners<TListeners>>(\n\t\teventName: K,\n\t\tlistener: TListeners[K],\n\t): void {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\tif (listeners?.delete(listener) === true && listeners.size === 0) {\n\t\t\tthis.listeners.delete(eventName);\n\t\t\tthis.noListeners?.(eventName);\n\t\t}\n\t}\n\n\tpublic hasListeners(eventName?: keyof TListeners): boolean {\n\t\tif (eventName === undefined) {\n\t\t\treturn this.listeners.size > 0;\n\t\t}\n\t\treturn this.listeners.has(eventName);\n\t}\n}\n\n/**\n * This class exposes the constructor and the `emit` method of `EventEmitter`, elevating them from protected to public\n * @internal\n */\nclass ComposableEventEmitter<TListeners extends Listeners<TListeners>>\n\textends CustomEventEmitter<TListeners>\n\timplements IEmitter<TListeners>\n{\n\tpublic constructor(noListeners?: NoListenersCallback<TListeners>) {\n\t\tsuper(noListeners);\n\t}\n\n\tpublic override emit<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): void {\n\t\treturn super.emit(eventName, ...args);\n\t}\n\n\tpublic override emitAndCollect<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): ReturnType<TListeners[K]>[] {\n\t\treturn super.emitAndCollect(eventName, ...args);\n\t}\n}\n\n/**\n * Create a {@link @fluidframework/core-interfaces#Listenable} that can be instructed to emit events via the {@link @fluidframework/core-interfaces#IEmitter} interface.\n *\n * A class can delegate handling {@link @fluidframework/core-interfaces#Listenable} to the returned value while using it to emit the events.\n * See also CustomEventEmitter which be used as a base class to implement {@link @fluidframework/core-interfaces#Listenable} via extension.\n * @example Forwarding events to the emitter\n * ```typescript\n * interface MyEvents {\n * \tloaded(): void;\n * }\n *\n * class MyClass implements Listenable<MyEvents> {\n * \tprivate readonly events = createEmitter<MyEvents>();\n *\n * \tprivate load(): void {\n * \t\tthis.events.emit(\"loaded\");\n * \t}\n *\n * \tpublic on<K extends keyof MyEvents>(eventName: K, listener: MyEvents[K]): Off {\n * \t\treturn this.events.on(eventName, listener);\n * \t}\n *\n * \tpublic off<K extends keyof MyEvents>(eventName: K, listener: MyEvents[K]): void {\n * \t\treturn this.events.off(eventName, listener);\n * \t}\n * }\n * ```\n * @internal\n */\nexport function createEmitter<TListeners extends object>(\n\tnoListeners?: NoListenersCallback<TListeners>,\n): Listenable<TListeners> & IEmitter<TListeners> & HasListeners<TListeners> {\n\treturn new ComposableEventEmitter<TListeners>(noListeners);\n}\n"]}
1
+ {"version":3,"file":"emitter.js","sourceRoot":"","sources":["../../src/events/emitter.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAWH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AACH,MAAM,OAAO,kBAAkB;IAmBS;IAhBvC;;;;;;;OAOG;IACgB,SAAS,GAAG,IAAI,GAAG,EAInC,CAAC;IAEJ,uJAAuJ;IACvJ,6FAA6F;IAC7F,YAAuC,WAA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AC,CAAC,SAAS,KAAK,QAAQ;YACxB,CAAC,CAAC,SAAS,EAAE,MAAM,CAAC,QAAQ,CAAC,KAAK,IAAI,IAAI,SAAS,CAAC,IAAI,KAAK,CAAC,EAC9D,CAAC;YACF,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;YACjC,IAAI,CAAC,WAAW,EAAE,CAAC,SAAS,CAAC,CAAC;QAC/B,CAAC;IACF,CAAC;IAEM,YAAY,CAAC,SAA4B;QAC/C,IAAI,SAAS,KAAK,SAAS,EAAE,CAAC;YAC7B,OAAO,IAAI,CAAC,SAAS,CAAC,IAAI,GAAG,CAAC,CAAC;QAChC,CAAC;QACD,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACtC,CAAC;CACD;AAED;;;GAGG;AACH,MAAM,sBACL,SAAQ,kBAA8B;IAGtC,YAAmB,WAA6C;QAC/D,KAAK,CAAC,WAAW,CAAC,CAAC;IACpB,CAAC;IAEe,IAAI,CACnB,SAAY,EACZ,GAAG,IAA+B;QAElC,OAAO,KAAK,CAAC,IAAI,CAAC,SAAS,EAAE,GAAG,IAAI,CAAC,CAAC;IACvC,CAAC;IAEe,cAAc,CAC7B,SAAY,EACZ,GAAG,IAA+B;QAElC,OAAO,KAAK,CAAC,cAAc,CAAC,SAAS,EAAE,GAAG,IAAI,CAAC,CAAC;IACjD,CAAC;CACD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,MAAM,UAAU,aAAa,CAC5B,WAA6C;IAE7C,OAAO,IAAI,sBAAsB,CAAa,WAAW,CAAC,CAAC;AAC5D,CAAC","sourcesContent":["/*!\n * Copyright (c) Microsoft Corporation and contributors. All rights reserved.\n * Licensed under the MIT License.\n */\n\nimport type {\n\tHasListeners,\n\tIEmitter,\n\tListenable,\n\tListeners,\n\tNoListenersCallback,\n\tOff,\n} from \"@fluidframework/core-interfaces/internal\";\n\n/**\n * Provides an API for subscribing to and listening to events.\n *\n * @remarks Classes wishing to emit events may either extend this class, compose over it, or expose it as a property of type {@link @fluidframework/core-interfaces#Listenable}.\n *\n * @example Extending this class\n *\n * ```typescript\n * interface MyEvents {\n * \tloaded: () => void;\n * \tcomputed: () => number;\n * }\n *\n * class MyInheritanceClass extends EventEmitter<MyEvents> {\n * \tprivate load() {\n * \t\tthis.emit(\"loaded\");\n * \t\tconst results: number[] = this.emitAndCollect(\"computed\");\n * \t}\n * }\n * ```\n *\n * @example Composing over this class\n *\n * ```typescript\n * class MyCompositionClass implements Listenable<MyEvents> {\n * \tprivate readonly events = createEmitter<MyEvents>();\n *\n * \tprivate load() {\n * \t\tthis.events.emit(\"loaded\");\n * \t\tconst results: number[] = this.events.emitAndCollect(\"computed\");\n * \t}\n *\n * \tpublic on<K extends keyof MyEvents>(eventName: K, listener: MyEvents[K]): () => void {\n * \t\treturn this.events.on(eventName, listener);\n * \t}\n * }\n * ```\n *\n * @example Exposing this class as a property\n *\n * ```typescript\n * class MyExposingClass {\n * \tprivate readonly _events = createEmitter<MyEvents>();\n * \tpublic readonly events: Listenable<MyEvents> = this._events;\n *\n * \tprivate load() {\n * \t\tthis._events.emit(\"loaded\");\n * \t\tconst results: number[] = this._events.emitAndCollect(\"computed\");\n * \t}\n * }\n * ```\n * @internal\n */\nexport class CustomEventEmitter<TListeners extends Listeners<TListeners>>\n\timplements Listenable<TListeners>, HasListeners<TListeners>\n{\n\t/**\n\t * The listeners of each event with listeners: the listener itself while it is the only one,\n\t * and a set of them once a second is added.\n\t * @remarks\n\t * Most emitters have at most one listener per event, so this saves a set for each of their events.\n\t * A set is kept until the event has no listeners, so that listeners added or removed by another listener\n\t * during an emit are treated the same whether or not the event had a set.\n\t */\n\tprotected readonly listeners = new Map<\n\t\tkeyof TListeners,\n\t\t| ((...args: any[]) => TListeners[keyof TListeners])\n\t\t| Set<(...args: any[]) => TListeners[keyof TListeners]>\n\t>();\n\n\t// Because this is protected and not public, calling this externally (not from a subclass) makes sending events to the constructed instance impossible.\n\t// Instead, use the static `create` function to get an instance which allows emitting events.\n\tprotected constructor(private readonly noListeners?: NoListenersCallback<TListeners>) {}\n\n\tprotected emit<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): void {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\t// Current tsc (5.4.5) cannot spread `args` into `listener()`.\n\t\tconst argArray: unknown[] = args;\n\t\tif (typeof listeners === \"function\") {\n\t\t\tlisteners(...argArray);\n\t\t} else if (listeners !== undefined) {\n\t\t\t// This explicitly copies listeners so that new listeners added during this call to emit will not receive this event.\n\t\t\tfor (const listener of [...listeners]) {\n\t\t\t\t// If listener has been unsubscribed while invoking other listeners, skip it.\n\t\t\t\tif (listeners.has(listener)) {\n\t\t\t\t\tlistener(...argArray);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprotected emitAndCollect<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): ReturnType<TListeners[K]>[] {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\tconst argArray: unknown[] = args;\n\t\tif (typeof listeners === \"function\") {\n\t\t\treturn [listeners(...argArray) as ReturnType<TListeners[K]>];\n\t\t}\n\t\tif (listeners !== undefined) {\n\t\t\tconst resultArray: ReturnType<TListeners[K]>[] = [];\n\t\t\tfor (const listener of [...listeners.values()]) {\n\t\t\t\tresultArray.push(listener(...argArray));\n\t\t\t}\n\t\t\treturn resultArray;\n\t\t}\n\t\treturn [];\n\t}\n\n\tpublic on<K extends keyof Listeners<TListeners>>(\n\t\teventName: K,\n\t\tlistener: TListeners[K],\n\t): Off {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\tif (listeners === undefined) {\n\t\t\tthis.listeners.set(eventName, listener);\n\t\t} else if (\n\t\t\ttypeof listeners === \"function\" ? listeners === listener : listeners.has(listener)\n\t\t) {\n\t\t\tconst eventDescription =\n\t\t\t\ttypeof eventName === \"symbol\" ? eventName.description : String(eventName.toString());\n\n\t\t\tthrow new Error(\n\t\t\t\t`Attempted to register the same listener object twice for event ${eventDescription}`,\n\t\t\t);\n\t\t} else if (typeof listeners === \"function\") {\n\t\t\t// Added one at a time: a set built from an array is allocated with a larger table.\n\t\t\tconst set = new Set<(...args: any[]) => TListeners[keyof TListeners]>();\n\t\t\tset.add(listeners);\n\t\t\tset.add(listener);\n\t\t\tthis.listeners.set(eventName, set);\n\t\t} else {\n\t\t\tlisteners.add(listener);\n\t\t}\n\t\treturn () => this.off(eventName, listener);\n\t}\n\n\tpublic off<K extends keyof Listeners<TListeners>>(\n\t\teventName: K,\n\t\tlistener: TListeners[K],\n\t): void {\n\t\tconst listeners = this.listeners.get(eventName);\n\t\tif (\n\t\t\ttypeof listeners === \"function\"\n\t\t\t\t? listeners === listener\n\t\t\t\t: listeners?.delete(listener) === true && listeners.size === 0\n\t\t) {\n\t\t\tthis.listeners.delete(eventName);\n\t\t\tthis.noListeners?.(eventName);\n\t\t}\n\t}\n\n\tpublic hasListeners(eventName?: keyof TListeners): boolean {\n\t\tif (eventName === undefined) {\n\t\t\treturn this.listeners.size > 0;\n\t\t}\n\t\treturn this.listeners.has(eventName);\n\t}\n}\n\n/**\n * This class exposes the constructor and the `emit` method of `EventEmitter`, elevating them from protected to public\n * @internal\n */\nclass ComposableEventEmitter<TListeners extends Listeners<TListeners>>\n\textends CustomEventEmitter<TListeners>\n\timplements IEmitter<TListeners>\n{\n\tpublic constructor(noListeners?: NoListenersCallback<TListeners>) {\n\t\tsuper(noListeners);\n\t}\n\n\tpublic override emit<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): void {\n\t\treturn super.emit(eventName, ...args);\n\t}\n\n\tpublic override emitAndCollect<K extends keyof TListeners>(\n\t\teventName: K,\n\t\t...args: Parameters<TListeners[K]>\n\t): ReturnType<TListeners[K]>[] {\n\t\treturn super.emitAndCollect(eventName, ...args);\n\t}\n}\n\n/**\n * Create a {@link @fluidframework/core-interfaces#Listenable} that can be instructed to emit events via the {@link @fluidframework/core-interfaces#IEmitter} interface.\n *\n * A class can delegate handling {@link @fluidframework/core-interfaces#Listenable} to the returned value while using it to emit the events.\n * See also CustomEventEmitter which be used as a base class to implement {@link @fluidframework/core-interfaces#Listenable} via extension.\n * @example Forwarding events to the emitter\n * ```typescript\n * interface MyEvents {\n * \tloaded(): void;\n * }\n *\n * class MyClass implements Listenable<MyEvents> {\n * \tprivate readonly events = createEmitter<MyEvents>();\n *\n * \tprivate load(): void {\n * \t\tthis.events.emit(\"loaded\");\n * \t}\n *\n * \tpublic on<K extends keyof MyEvents>(eventName: K, listener: MyEvents[K]): Off {\n * \t\treturn this.events.on(eventName, listener);\n * \t}\n *\n * \tpublic off<K extends keyof MyEvents>(eventName: K, listener: MyEvents[K]): void {\n * \t\treturn this.events.off(eventName, listener);\n * \t}\n * }\n * ```\n * @internal\n */\nexport function createEmitter<TListeners extends object>(\n\tnoListeners?: NoListenersCallback<TListeners>,\n): Listenable<TListeners> & IEmitter<TListeners> & HasListeners<TListeners> {\n\treturn new ComposableEventEmitter<TListeners>(noListeners);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fluid-internal/client-utils",
3
- "version": "3.12.0",
3
+ "version": "3.13.0",
4
4
  "description": "Not intended for use outside the Fluid Framework.",
5
5
  "homepage": "https://fluidframework.com",
6
6
  "repository": {
@@ -63,7 +63,7 @@
63
63
  "temp-directory": "nyc/.nyc_output"
64
64
  },
65
65
  "dependencies": {
66
- "@fluidframework/core-interfaces": "~3.12.0",
66
+ "@fluidframework/core-interfaces": "~3.13.0",
67
67
  "@types/events_pkg": "npm:@types/events@^3.0.0",
68
68
  "base64-js": "^1.5.1",
69
69
  "buffer": "^6.0.3",
@@ -73,8 +73,8 @@
73
73
  "devDependencies": {
74
74
  "@arethetypeswrong/cli": "^0.18.5",
75
75
  "@biomejs/biome": "~2.4.5",
76
- "@fluid-internal/client-utils-previous": "npm:@fluid-internal/client-utils@3.11.0",
77
- "@fluid-internal/mocha-test-setup": "~3.12.0",
76
+ "@fluid-internal/client-utils-previous": "npm:@fluid-internal/client-utils@3.12.0",
77
+ "@fluid-internal/mocha-test-setup": "~3.13.0",
78
78
  "@fluid-tools/build-cli": "^0.68.0",
79
79
  "@fluidframework/build-common": "^2.0.3",
80
80
  "@fluidframework/build-tools": "^0.68.0",
@@ -8,28 +8,10 @@ import type {
8
8
  IEmitter,
9
9
  Listenable,
10
10
  Listeners,
11
- MapGetSet,
12
11
  NoListenersCallback,
13
12
  Off,
14
13
  } from "@fluidframework/core-interfaces/internal";
15
14
 
16
- /**
17
- * Retrieve a value from a map with the given key, or create a new entry if the key is not in the map.
18
- * @param map - The map to query/update
19
- * @param key - The key to lookup in the map
20
- * @param defaultValue - a function which returns a default value. This is called and used to set an initial value for the given key in the map if none exists
21
- * @returns either the existing value for the given key, or the newly-created value (the result of `defaultValue`)
22
- * @internal
23
- */
24
- function getOrCreate<K, V>(map: MapGetSet<K, V>, key: K, defaultValue: (key: K) => V): V {
25
- let value = map.get(key);
26
- if (value === undefined) {
27
- value = defaultValue(key);
28
- map.set(key, value);
29
- }
30
- return value;
31
- }
32
-
33
15
  /**
34
16
  * Provides an API for subscribing to and listening to events.
35
17
  *
@@ -86,9 +68,18 @@ function getOrCreate<K, V>(map: MapGetSet<K, V>, key: K, defaultValue: (key: K)
86
68
  export class CustomEventEmitter<TListeners extends Listeners<TListeners>>
87
69
  implements Listenable<TListeners>, HasListeners<TListeners>
88
70
  {
71
+ /**
72
+ * The listeners of each event with listeners: the listener itself while it is the only one,
73
+ * and a set of them once a second is added.
74
+ * @remarks
75
+ * Most emitters have at most one listener per event, so this saves a set for each of their events.
76
+ * A set is kept until the event has no listeners, so that listeners added or removed by another listener
77
+ * during an emit are treated the same whether or not the event had a set.
78
+ */
89
79
  protected readonly listeners = new Map<
90
80
  keyof TListeners,
91
- Set<(...args: any[]) => TListeners[keyof TListeners]>
81
+ | ((...args: any[]) => TListeners[keyof TListeners])
82
+ | Set<(...args: any[]) => TListeners[keyof TListeners]>
92
83
  >();
93
84
 
94
85
  // Because this is protected and not public, calling this externally (not from a subclass) makes sending events to the constructed instance impossible.
@@ -100,9 +91,11 @@ export class CustomEventEmitter<TListeners extends Listeners<TListeners>>
100
91
  ...args: Parameters<TListeners[K]>
101
92
  ): void {
102
93
  const listeners = this.listeners.get(eventName);
103
- if (listeners !== undefined) {
104
- // Current tsc (5.4.5) cannot spread `args` into `listener()`.
105
- const argArray: unknown[] = args;
94
+ // Current tsc (5.4.5) cannot spread `args` into `listener()`.
95
+ const argArray: unknown[] = args;
96
+ if (typeof listeners === "function") {
97
+ listeners(...argArray);
98
+ } else if (listeners !== undefined) {
106
99
  // This explicitly copies listeners so that new listeners added during this call to emit will not receive this event.
107
100
  for (const listener of [...listeners]) {
108
101
  // If listener has been unsubscribed while invoking other listeners, skip it.
@@ -118,8 +111,11 @@ export class CustomEventEmitter<TListeners extends Listeners<TListeners>>
118
111
  ...args: Parameters<TListeners[K]>
119
112
  ): ReturnType<TListeners[K]>[] {
120
113
  const listeners = this.listeners.get(eventName);
114
+ const argArray: unknown[] = args;
115
+ if (typeof listeners === "function") {
116
+ return [listeners(...argArray) as ReturnType<TListeners[K]>];
117
+ }
121
118
  if (listeners !== undefined) {
122
- const argArray: unknown[] = args;
123
119
  const resultArray: ReturnType<TListeners[K]>[] = [];
124
120
  for (const listener of [...listeners.values()]) {
125
121
  resultArray.push(listener(...argArray));
@@ -133,16 +129,27 @@ export class CustomEventEmitter<TListeners extends Listeners<TListeners>>
133
129
  eventName: K,
134
130
  listener: TListeners[K],
135
131
  ): Off {
136
- const listeners = getOrCreate(this.listeners, eventName, () => new Set());
137
- if (listeners.has(listener)) {
132
+ const listeners = this.listeners.get(eventName);
133
+ if (listeners === undefined) {
134
+ this.listeners.set(eventName, listener);
135
+ } else if (
136
+ typeof listeners === "function" ? listeners === listener : listeners.has(listener)
137
+ ) {
138
138
  const eventDescription =
139
139
  typeof eventName === "symbol" ? eventName.description : String(eventName.toString());
140
140
 
141
141
  throw new Error(
142
142
  `Attempted to register the same listener object twice for event ${eventDescription}`,
143
143
  );
144
+ } else if (typeof listeners === "function") {
145
+ // Added one at a time: a set built from an array is allocated with a larger table.
146
+ const set = new Set<(...args: any[]) => TListeners[keyof TListeners]>();
147
+ set.add(listeners);
148
+ set.add(listener);
149
+ this.listeners.set(eventName, set);
150
+ } else {
151
+ listeners.add(listener);
144
152
  }
145
- listeners.add(listener);
146
153
  return () => this.off(eventName, listener);
147
154
  }
148
155
 
@@ -151,7 +158,11 @@ export class CustomEventEmitter<TListeners extends Listeners<TListeners>>
151
158
  listener: TListeners[K],
152
159
  ): void {
153
160
  const listeners = this.listeners.get(eventName);
154
- if (listeners?.delete(listener) === true && listeners.size === 0) {
161
+ if (
162
+ typeof listeners === "function"
163
+ ? listeners === listener
164
+ : listeners?.delete(listener) === true && listeners.size === 0
165
+ ) {
155
166
  this.listeners.delete(eventName);
156
167
  this.noListeners?.(eventName);
157
168
  }