@xylabs/events 4.9.17

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/LICENSE ADDED
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
package/README.md ADDED
@@ -0,0 +1,69 @@
1
+ [![logo][]](https://xylabs.com)
2
+
3
+ # @xylabs/events
4
+
5
+ [![npm-badge][]][npm-link]
6
+ [![npm-downloads-badge][]][npm-link]
7
+ [![jsdelivr-badge][]][jsdelivr-link]
8
+ [![npm-license-badge][]](LICENSE)
9
+ [![socket-badge][]][socket-link]
10
+
11
+ > XY Labs generalized Javascript library
12
+
13
+ ## Table of Contents
14
+
15
+ - [Description](#description)
16
+ - [Install](#install)
17
+ - [Maintainers](#maintainers)
18
+ - [License](#license)
19
+ - [Credits](#credits)
20
+
21
+ ## Description
22
+
23
+ Common Javascript code that is used throughout XYO projects that use React.
24
+
25
+ ## Install
26
+
27
+ Using npm:
28
+
29
+ ```sh
30
+ npm i --save @xylabs/events
31
+ ```
32
+
33
+ Using yarn:
34
+
35
+ ```sh
36
+ yarn add @xylabs/events
37
+ ```
38
+
39
+ ## Documentation
40
+ [Developer Reference](https://xylabs.github.io/sdk-js)
41
+
42
+ ## Maintainers
43
+
44
+ - [Arie Trouw](https://github.com/arietrouw) ([arietrouw.com](https://arietrouw.com))
45
+ - [Joel Carter](https://github.com/JoelBCarter)
46
+ - [Matt Jones](https://github.com/jonesmac)
47
+ - [Jordan Trouw](https://github.com/jordantrouw)
48
+
49
+ ## License
50
+
51
+ See the [LICENSE](LICENSE) file for license details
52
+
53
+ ## Credits
54
+
55
+ [Made with 🔥and ❄️ by XY Labs](https://xylabs.com)
56
+
57
+ [logo]: https://cdn.xy.company/img/brand/XYPersistentCompany_Logo_Icon_Colored.svg
58
+
59
+ [npm-badge]: https://img.shields.io/npm/v/@xylabs/events.svg
60
+ [npm-link]: https://www.npmjs.com/package/@xylabs/events
61
+
62
+ [npm-downloads-badge]: https://img.shields.io/npm/dw/@xylabs/events
63
+ [npm-license-badge]: https://img.shields.io/npm/l/@xylabs/events
64
+
65
+ [jsdelivr-badge]: https://data.jsdelivr.com/v1/package/npm/@xylabs/events/badge
66
+ [jsdelivr-link]: https://www.jsdelivr.com/package/npm/@xylabs/events
67
+
68
+ [socket-badge]: https://socket.dev/api/badge/npm/package/@xylabs/events
69
+ [socket-link]: https://socket.dev/npm/package/@xylabs/events
@@ -0,0 +1,258 @@
1
+ // src/Events/Events.ts
2
+ import { assertEx } from "@xylabs/assert";
3
+ import { Base } from "@xylabs/base";
4
+ import { handleError } from "@xylabs/error";
5
+ import { forget } from "@xylabs/forget";
6
+ import { isDefined } from "@xylabs/typeof";
7
+ var NO_META_EVENT_ERROR_MESSAGE = "`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`";
8
+ var resolvedPromise = Promise.resolve();
9
+ var isMetaEvent = (eventName) => eventName === "listenerAdded" || eventName === "listenerRemoved";
10
+ var Events = class _Events extends Base {
11
+ static anyMap = /* @__PURE__ */ new WeakMap();
12
+ static eventsMap = /* @__PURE__ */ new WeakMap();
13
+ static canEmitMetaEvents = false;
14
+ static isGlobalDebugEnabled = false;
15
+ // this is here to be able to query the type, not use
16
+ eventData = {};
17
+ constructor(params = {}) {
18
+ const mutatedParams = { ...params };
19
+ if (mutatedParams.debug) {
20
+ mutatedParams.debug.logger = mutatedParams.debug.logger ?? ((type, debugName, eventName, eventData) => {
21
+ let eventDataString;
22
+ try {
23
+ eventDataString = JSON.stringify(eventData);
24
+ } catch {
25
+ eventDataString = `Object with the following keys failed to stringify: ${Object.keys(eventData ?? {}).join(",")}`;
26
+ }
27
+ const eventNameString = typeof eventName === "symbol" || typeof eventName === "number" ? eventName.toString() : eventName;
28
+ const currentTime = /* @__PURE__ */ new Date();
29
+ const logTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}.${currentTime.getMilliseconds()}`;
30
+ this.logger?.log(`[${logTime}][events:${type}][${debugName}] Event Name: ${eventNameString}
31
+ data: ${eventDataString}`);
32
+ });
33
+ }
34
+ super(mutatedParams);
35
+ _Events.anyMap.set(this, /* @__PURE__ */ new Set());
36
+ _Events.eventsMap.set(this, /* @__PURE__ */ new Map());
37
+ }
38
+ static get isDebugEnabled() {
39
+ if (typeof globalThis.process?.env !== "object") {
40
+ return _Events.isGlobalDebugEnabled;
41
+ }
42
+ const { env } = globalThis.process ?? { env: {} };
43
+ return env.DEBUG === "events" || env.DEBUG === "*" || _Events.isGlobalDebugEnabled;
44
+ }
45
+ static set isDebugEnabled(newValue) {
46
+ _Events.isGlobalDebugEnabled = newValue;
47
+ }
48
+ get debug() {
49
+ return this.params.debug;
50
+ }
51
+ clearListeners(eventNames) {
52
+ const eventNamesArray = Array.isArray(eventNames) ? eventNames : [eventNames];
53
+ for (const eventName of eventNamesArray) {
54
+ this.logIfDebugEnabled("clear", eventName);
55
+ if (typeof eventName === "string" || typeof eventName === "symbol" || typeof eventName === "number") {
56
+ const set = this.getListeners(eventName);
57
+ if (set) {
58
+ set.clear();
59
+ }
60
+ } else {
61
+ _Events.anyMap.get(this)?.clear();
62
+ for (const [eventName2, listeners] of assertEx(_Events.eventsMap.get(this)).entries()) {
63
+ listeners.clear();
64
+ _Events.eventsMap.get(this)?.delete(eventName2);
65
+ }
66
+ }
67
+ }
68
+ }
69
+ async emit(eventName, eventArgs) {
70
+ await this.emitInternal(eventName, eventArgs);
71
+ }
72
+ async emitMetaEvent(eventName, eventArgs) {
73
+ if (isMetaEvent(eventName)) {
74
+ try {
75
+ _Events.canEmitMetaEvents = true;
76
+ await this.emitMetaEventInternal(eventName, eventArgs);
77
+ } finally {
78
+ _Events.canEmitMetaEvents = false;
79
+ }
80
+ }
81
+ }
82
+ async emitSerial(eventName, eventArgs) {
83
+ if (isMetaEvent(eventName) && !_Events.canEmitMetaEvents) {
84
+ throw new TypeError(NO_META_EVENT_ERROR_MESSAGE);
85
+ }
86
+ const filterMatch = (args, filter) => {
87
+ switch (typeof filter) {
88
+ case "object": {
89
+ return Object.entries(args).reduce((prev, [key, value]) => filter[key] === value ? true : prev, false);
90
+ }
91
+ default: {
92
+ return args === filter;
93
+ }
94
+ }
95
+ };
96
+ this.logIfDebugEnabled("emitSerial", eventName, eventArgs);
97
+ const listeners = this.getListeners(eventName) ?? /* @__PURE__ */ new Set();
98
+ const filteredListeners = [...listeners.values()].filter((value) => isDefined(value.filter) ? filterMatch(eventArgs, value.filter) : true).map((info) => info.listener);
99
+ const anyListeners = assertEx(_Events.anyMap.get(this));
100
+ const staticListeners = [...filteredListeners];
101
+ const staticAnyListeners = [...anyListeners];
102
+ await resolvedPromise;
103
+ for (const listener of staticListeners) {
104
+ await this.safeCallListener(eventName, eventArgs, listener);
105
+ }
106
+ for (const listener of staticAnyListeners) {
107
+ await this.safeCallAnyListener(eventName, eventArgs, listener);
108
+ }
109
+ }
110
+ // TODO: Make test for this
111
+ listenerCount(eventNames) {
112
+ const eventNamesArray = Array.isArray(eventNames) ? eventNames : [eventNames];
113
+ let count = 0;
114
+ for (const eventName of eventNamesArray) {
115
+ if (typeof eventName === "string") {
116
+ count += assertEx(_Events.anyMap.get(this)).size + (this.getListeners(eventName)?.size ?? 0);
117
+ continue;
118
+ }
119
+ count += assertEx(_Events.anyMap.get(this)).size;
120
+ for (const value of assertEx(_Events.eventsMap.get(this)).values()) {
121
+ count += value.size;
122
+ }
123
+ }
124
+ return count;
125
+ }
126
+ logIfDebugEnabled(type, eventName, eventArgs) {
127
+ if (_Events.isDebugEnabled || this.debug?.enabled) {
128
+ this.debug?.logger?.(type, this.debug.name, eventName, eventArgs);
129
+ }
130
+ }
131
+ off(eventNames, listener) {
132
+ const eventNamesArray = Array.isArray(eventNames) ? eventNames : [eventNames];
133
+ for (const eventName of eventNamesArray) {
134
+ const set = this.getListeners(eventName);
135
+ if (set) {
136
+ set.delete(listener);
137
+ if (set.size === 0) {
138
+ const events = _Events.eventsMap.get(this);
139
+ events?.delete(eventName);
140
+ }
141
+ }
142
+ this.logIfDebugEnabled("unsubscribe", eventName);
143
+ if (!isMetaEvent(eventName)) {
144
+ forget(this.emitMetaEvent("listenerRemoved", { eventName, listener }));
145
+ }
146
+ }
147
+ }
148
+ offAny(listener) {
149
+ this.logIfDebugEnabled("unsubscribeAny");
150
+ const typedMap = _Events.anyMap.get(this);
151
+ typedMap?.delete(listener);
152
+ forget(this.emitMetaEvent("listenerRemoved", { listener }));
153
+ }
154
+ on(eventNames, listener, filter) {
155
+ const eventNamesArray = Array.isArray(eventNames) ? eventNames : [eventNames];
156
+ for (const eventName of eventNamesArray) {
157
+ let set = this.getListeners(eventName);
158
+ if (!set) {
159
+ set = /* @__PURE__ */ new Set();
160
+ const events = _Events.eventsMap.get(this);
161
+ events?.set(eventName, set);
162
+ }
163
+ set.add({ filter, listener });
164
+ this.logIfDebugEnabled("subscribe", eventName);
165
+ if (!isMetaEvent(eventName)) {
166
+ forget(this.emitMetaEvent("listenerAdded", { eventName, listener }));
167
+ }
168
+ }
169
+ return this.off.bind(this, eventNames, listener);
170
+ }
171
+ onAny(listener) {
172
+ this.logIfDebugEnabled("subscribeAny");
173
+ _Events.anyMap.get(this)?.add(listener);
174
+ forget(this.emitMetaEvent("listenerAdded", { listener }));
175
+ return this.offAny.bind(this, listener);
176
+ }
177
+ once(eventName, listener) {
178
+ const subListener = async (args) => {
179
+ this.off(eventName, subListener);
180
+ await this.safeCallListener(eventName, args, listener);
181
+ };
182
+ this.on(eventName, subListener);
183
+ return this.off.bind(this, eventName, subListener);
184
+ }
185
+ async emitInternal(eventName, eventArgs, filter) {
186
+ if (isMetaEvent(eventName) && !_Events.canEmitMetaEvents) {
187
+ throw new TypeError(NO_META_EVENT_ERROR_MESSAGE);
188
+ }
189
+ this.logIfDebugEnabled("emit", eventName, eventArgs);
190
+ const listeners = this.getListeners(eventName) ?? /* @__PURE__ */ new Set();
191
+ const filteredListeners = [...listeners.values()].filter((value) => isDefined(filter) ? isDefined(value.listener) : true).map((info) => info.listener);
192
+ const anyListeners = assertEx(_Events.anyMap.get(this));
193
+ const staticListeners = [...filteredListeners];
194
+ const staticAnyListeners = isMetaEvent(eventName) ? [] : [...anyListeners];
195
+ await resolvedPromise;
196
+ await Promise.all([
197
+ ...staticListeners.map(async (listener) => {
198
+ await this.safeCallListener(eventName, eventArgs, listener);
199
+ }),
200
+ ...staticAnyListeners.map(async (listener) => {
201
+ if (anyListeners.has(listener)) {
202
+ await this.safeCallAnyListener(eventName, eventArgs, listener);
203
+ }
204
+ })
205
+ ]);
206
+ }
207
+ async emitMetaEventInternal(eventName, eventArgs) {
208
+ if (isMetaEvent(eventName) && !_Events.canEmitMetaEvents) {
209
+ throw new TypeError("`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`");
210
+ }
211
+ this.logIfDebugEnabled("emit", eventName, eventArgs);
212
+ const listeners = this.getListeners(eventName) ?? /* @__PURE__ */ new Set();
213
+ const filteredListeners = [...listeners.values()].map((info) => info.listener);
214
+ const anyListeners = assertEx(_Events.anyMap.get(this));
215
+ const staticListeners = [...filteredListeners];
216
+ const staticAnyListeners = isMetaEvent(eventName) ? [] : [...anyListeners];
217
+ await resolvedPromise;
218
+ await Promise.all([
219
+ ...staticListeners.map(async (listener) => {
220
+ await this.safeCallListener(eventName, eventArgs, listener);
221
+ }),
222
+ ...staticAnyListeners.map(async (listener) => {
223
+ if (anyListeners.has(listener)) {
224
+ await this.safeCallAnyListener(eventName, eventArgs, listener);
225
+ }
226
+ })
227
+ ]);
228
+ }
229
+ getListeners(eventName) {
230
+ const events = assertEx(_Events.eventsMap.get(this));
231
+ if (!events.has(eventName)) {
232
+ return;
233
+ }
234
+ return events.get(eventName);
235
+ }
236
+ async safeCallAnyListener(eventName, eventArgs, listener) {
237
+ try {
238
+ return await listener(eventName, eventArgs);
239
+ } catch (ex) {
240
+ handleError(ex, (error) => {
241
+ this.logger?.error(`Listener[${String(eventName)}] Excepted: ${error.message}`);
242
+ });
243
+ }
244
+ }
245
+ async safeCallListener(eventName, eventArgs, listener) {
246
+ try {
247
+ return await listener(eventArgs);
248
+ } catch (ex) {
249
+ handleError(ex, (error) => {
250
+ this.logger?.error(`Listener[${String(eventName)}] Excepted: ${error.message}`);
251
+ });
252
+ }
253
+ }
254
+ };
255
+ export {
256
+ Events
257
+ };
258
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/Events/Events.ts"],"sourcesContent":["import { assertEx } from '@xylabs/assert'\nimport type { BaseParams } from '@xylabs/base'\nimport { Base } from '@xylabs/base'\nimport { handleError } from '@xylabs/error'\nimport { forget } from '@xylabs/forget'\nimport { isDefined } from '@xylabs/typeof'\n\nimport type {\n EventAnyListener, EventArgs, EventData, EventFunctions, EventListener, EventName,\n} from '../model/index.ts'\n\n/**\nEmittery can collect and log debug information.\n\nTo enable this feature set the `DEBUG` environment variable to `emittery` or `*`. Additionally, you can set the static `isDebugEnabled` variable to true\non the Emittery class, or `myEmitter.debug.enabled` on an instance of it for debugging a single instance.\n\nSee API for more information on how debugging works.\n*/\nexport type DebugLogger = (type: string, debugName: string, eventName?: EventName, eventData?: EventArgs) => void\n\nexport type EventListenerInfo<TEventArgs extends EventArgs = EventArgs> = {\n filter?: TEventArgs\n listener: EventListener<TEventArgs>\n}\n\nconst NO_META_EVENT_ERROR_MESSAGE = '`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`'\n\n/**\nConfigure debug options of an instance.\n*/\nexport type DebugOptions = {\n enabled?: boolean\n logger?: DebugLogger\n readonly name: string\n}\n\nconst resolvedPromise = Promise.resolve()\n\nexport type MetaEventData<TEventData extends EventData> = {\n listenerAdded: {\n eventName?: keyof TEventData\n listener: EventListener<TEventData[keyof TEventData]> | EventAnyListener<TEventData[keyof TEventData]>\n }\n listenerRemoved: {\n eventName?: keyof TEventData\n listener: EventListener<TEventData[keyof TEventData]> | EventAnyListener<TEventData[keyof TEventData]>\n }\n}\n\nconst isMetaEvent = (eventName: EventName) => eventName === 'listenerAdded' || eventName === 'listenerRemoved'\n\nexport type EventsParams = BaseParams<{ readonly debug?: DebugOptions }>\n\nexport class Events<TEventData extends EventData = EventData> extends Base<EventsParams> implements EventFunctions<TEventData> {\n protected static anyMap = new WeakMap<object, Set<EventAnyListener>>()\n protected static eventsMap = new WeakMap<object, Map<EventName, Set<EventListenerInfo>>>()\n\n private static canEmitMetaEvents = false\n private static isGlobalDebugEnabled = false\n\n // this is here to be able to query the type, not use\n eventData = {} as TEventData\n\n constructor(params: EventsParams = {}) {\n const mutatedParams = { ...params }\n if (mutatedParams.debug) {\n mutatedParams.debug.logger\n = mutatedParams.debug.logger\n ?? ((type: string, debugName: string, eventName?: EventName, eventData?: EventArgs) => {\n let eventDataString: string\n try {\n eventDataString = JSON.stringify(eventData)\n } catch {\n eventDataString = `Object with the following keys failed to stringify: ${Object.keys(eventData ?? {}).join(',')}`\n }\n\n const eventNameString = typeof eventName === 'symbol' || typeof eventName === 'number' ? eventName.toString() : eventName\n\n const currentTime = new Date()\n const logTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}.${currentTime.getMilliseconds()}`\n this.logger?.log(`[${logTime}][events:${type}][${debugName}] Event Name: ${eventNameString}\\n\\tdata: ${eventDataString}`)\n })\n }\n super(mutatedParams)\n Events.anyMap.set(this, new Set<EventAnyListener>())\n Events.eventsMap.set(this, new Map<keyof TEventData, Set<EventListenerInfo>>())\n }\n\n static get isDebugEnabled() {\n // In a browser environment, `globalThis.process` can potentially reference a DOM Element with a `#process` ID,\n // so instead of just type checking `globalThis.process`, we need to make sure that `globalThis.process.env` exists.\n\n if (typeof globalThis.process?.env !== 'object') {\n return Events.isGlobalDebugEnabled\n }\n\n const { env } = globalThis.process ?? { env: {} }\n return env.DEBUG === 'events' || env.DEBUG === '*' || Events.isGlobalDebugEnabled\n }\n\n static set isDebugEnabled(newValue) {\n Events.isGlobalDebugEnabled = newValue\n }\n\n get debug() {\n return this.params.debug\n }\n\n clearListeners(eventNames: keyof TEventData | (keyof TEventData)[]) {\n const eventNamesArray = Array.isArray(eventNames) ? eventNames : [eventNames]\n\n for (const eventName of eventNamesArray) {\n this.logIfDebugEnabled('clear', eventName)\n\n if (typeof eventName === 'string' || typeof eventName === 'symbol' || typeof eventName === 'number') {\n const set = this.getListeners(eventName)\n if (set) {\n set.clear()\n }\n } else {\n Events.anyMap.get(this)?.clear()\n\n for (const [eventName, listeners] of assertEx(Events.eventsMap.get(this)).entries()) {\n listeners.clear()\n Events.eventsMap.get(this)?.delete(eventName)\n }\n }\n }\n }\n\n async emit<TEventName extends keyof TEventData>(eventName: TEventName, eventArgs: TEventData[TEventName]) {\n await this.emitInternal(eventName, eventArgs)\n }\n\n async emitMetaEvent<TEventName extends keyof MetaEventData<TEventData>>(eventName: TEventName, eventArgs: MetaEventData<TEventData>[TEventName]) {\n if (isMetaEvent(eventName)) {\n try {\n Events.canEmitMetaEvents = true\n await this.emitMetaEventInternal(eventName, eventArgs)\n } finally {\n Events.canEmitMetaEvents = false\n }\n }\n }\n\n async emitSerial<TEventName extends keyof TEventData>(eventName: TEventName, eventArgs: TEventData[TEventName]) {\n if (isMetaEvent(eventName) && !Events.canEmitMetaEvents) {\n throw new TypeError(NO_META_EVENT_ERROR_MESSAGE)\n }\n\n const filterMatch = (args: TEventData[TEventName], filter: TEventData[TEventName]) => {\n switch (typeof filter) {\n case 'object': {\n // eslint-disable-next-line unicorn/no-array-reduce\n return Object.entries(args).reduce((prev, [key, value]) => ((filter as Record<PropertyKey, unknown>)[key] === value ? true : prev), false)\n }\n default: {\n return args === filter\n }\n }\n }\n\n this.logIfDebugEnabled('emitSerial', eventName, eventArgs)\n\n const listeners = this.getListeners(eventName) ?? new Set()\n const filteredListeners = [...listeners.values()]\n .filter(value => (isDefined(value.filter) ? filterMatch(eventArgs, value.filter as TEventData[TEventName]) : true))\n .map(info => info.listener)\n const anyListeners = assertEx(Events.anyMap.get(this))\n const staticListeners = [...filteredListeners]\n const staticAnyListeners = [...anyListeners]\n\n await resolvedPromise\n\n for (const listener of staticListeners) {\n await this.safeCallListener(eventName, eventArgs, listener)\n }\n\n for (const listener of staticAnyListeners) {\n await this.safeCallAnyListener(eventName, eventArgs, listener)\n }\n }\n\n // TODO: Make test for this\n listenerCount(eventNames?: keyof TEventData | (keyof TEventData)[]) {\n const eventNamesArray = Array.isArray(eventNames) ? eventNames : [eventNames]\n let count = 0\n\n for (const eventName of eventNamesArray) {\n if (typeof eventName === 'string') {\n count += assertEx(Events.anyMap.get(this)).size + (this.getListeners(eventName)?.size ?? 0)\n\n continue\n }\n\n count += assertEx(Events.anyMap.get(this)).size\n\n for (const value of assertEx(Events.eventsMap.get(this)).values()) {\n count += value.size\n }\n }\n\n return count\n }\n\n logIfDebugEnabled<TEventName extends EventName>(type: string, eventName?: TEventName, eventArgs?: EventArgs) {\n if (Events.isDebugEnabled || this.debug?.enabled) {\n this.debug?.logger?.(type, this.debug.name, eventName, eventArgs)\n }\n }\n\n off<TEventName extends keyof TEventData, TEventListener = EventListener<TEventData[TEventName]>>(\n eventNames: TEventName | TEventName[],\n listener: TEventListener,\n ) {\n const eventNamesArray = Array.isArray(eventNames) ? eventNames : [eventNames]\n for (const eventName of eventNamesArray) {\n const set = this.getListeners(eventName) as Set<TEventListener> | undefined\n if (set) {\n set.delete(listener)\n if (set.size === 0) {\n const events = Events.eventsMap.get(this)\n events?.delete(eventName)\n }\n }\n\n this.logIfDebugEnabled('unsubscribe', eventName)\n\n if (!isMetaEvent(eventName)) {\n forget(this.emitMetaEvent('listenerRemoved', { eventName, listener: listener as EventListener }))\n }\n }\n }\n\n offAny(listener: EventAnyListener) {\n this.logIfDebugEnabled('unsubscribeAny')\n\n const typedMap = Events.anyMap.get(this) as Set<EventAnyListener<TEventData[keyof TEventData]>>\n typedMap?.delete(listener)\n forget(this.emitMetaEvent('listenerRemoved', { listener: listener as EventAnyListener }))\n }\n\n on<TEventName extends keyof TEventData = keyof TEventData>(\n eventNames: TEventName | TEventName[],\n listener: EventListener<TEventData[TEventName]>,\n filter?: TEventData[TEventName],\n ) {\n const eventNamesArray = Array.isArray(eventNames) ? eventNames : [eventNames]\n for (const eventName of eventNamesArray) {\n let set = this.getListeners(eventName)\n if (!set) {\n set = new Set()\n const events = Events.eventsMap.get(this)\n events?.set(eventName, set)\n }\n\n set.add({ filter, listener: listener as EventListener })\n\n this.logIfDebugEnabled('subscribe', eventName)\n\n if (!isMetaEvent(eventName)) {\n forget(this.emitMetaEvent('listenerAdded', { eventName, listener: listener as EventListener }))\n }\n }\n\n return this.off.bind(this, eventNames, listener as EventListener)\n }\n\n onAny(listener: EventAnyListener) {\n this.logIfDebugEnabled('subscribeAny')\n\n Events.anyMap.get(this)?.add(listener as EventAnyListener)\n forget(this.emitMetaEvent('listenerAdded', { listener: listener as EventAnyListener }))\n return this.offAny.bind(this, listener as EventAnyListener)\n }\n\n once<TEventName extends keyof TEventData>(eventName: TEventName, listener: EventListener<TEventData[TEventName]>) {\n const subListener = async (args: TEventData[TEventName]) => {\n this.off(eventName, subListener)\n await this.safeCallListener(eventName, args, listener)\n }\n this.on(eventName, subListener)\n return this.off.bind(this, eventName, subListener as EventListener)\n }\n\n private async emitInternal<TEventName extends keyof TEventData, TEventArgs extends TEventData[TEventName]>(\n eventName: TEventName,\n eventArgs: TEventArgs,\n filter?: TEventArgs,\n ) {\n if (isMetaEvent(eventName) && !Events.canEmitMetaEvents) {\n throw new TypeError(NO_META_EVENT_ERROR_MESSAGE)\n }\n\n this.logIfDebugEnabled('emit', eventName, eventArgs)\n\n const listeners = this.getListeners(eventName) ?? new Set()\n const filteredListeners = [...listeners.values()].filter(value => (isDefined(filter) ? isDefined(value.listener) : true)).map(info => info.listener)\n const anyListeners = assertEx(Events.anyMap.get(this))\n const staticListeners = [...filteredListeners]\n const staticAnyListeners = isMetaEvent(eventName) ? [] : [...anyListeners]\n\n await resolvedPromise\n await Promise.all([\n ...staticListeners.map(async (listener) => {\n await this.safeCallListener(eventName, eventArgs, listener)\n }),\n ...staticAnyListeners.map(async (listener) => {\n if (anyListeners.has(listener)) {\n await this.safeCallAnyListener(eventName, eventArgs, listener)\n }\n }),\n ])\n }\n\n private async emitMetaEventInternal<TEventName extends keyof MetaEventData<TEventData>>(\n eventName: TEventName,\n eventArgs: MetaEventData<TEventData>[TEventName],\n ) {\n if (isMetaEvent(eventName) && !Events.canEmitMetaEvents) {\n throw new TypeError('`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`')\n }\n\n this.logIfDebugEnabled('emit', eventName, eventArgs)\n\n const listeners = this.getListeners(eventName) ?? new Set()\n const filteredListeners = [...listeners.values()].map(info => info.listener)\n const anyListeners = assertEx(Events.anyMap.get(this))\n const staticListeners = [...filteredListeners]\n const staticAnyListeners = isMetaEvent(eventName) ? [] : [...anyListeners]\n\n await resolvedPromise\n await Promise.all([\n ...staticListeners.map(async (listener) => {\n await this.safeCallListener(eventName, eventArgs, listener)\n }),\n ...staticAnyListeners.map(async (listener) => {\n if (anyListeners.has(listener)) {\n await this.safeCallAnyListener(eventName, eventArgs, listener)\n }\n }),\n ])\n }\n\n private getListeners<TEventName extends keyof TEventData>(eventName: TEventName) {\n const events = assertEx(Events.eventsMap.get(this))\n if (!events.has(eventName)) {\n return\n }\n\n return events.get(eventName)\n }\n\n private async safeCallAnyListener<TEventData extends EventData, TEventName extends keyof EventData>(\n eventName: TEventName,\n eventArgs: TEventData[TEventName],\n listener: EventAnyListener<TEventData[TEventName]>,\n ) {\n try {\n return await listener(eventName, eventArgs)\n } catch (ex) {\n handleError(ex, (error) => {\n this.logger?.error(`Listener[${String(eventName)}] Excepted: ${error.message}`)\n })\n }\n }\n\n private async safeCallListener<TEventData extends EventData, TEventName extends keyof EventData>(\n eventName: TEventName,\n eventArgs: TEventData[TEventName],\n listener: EventListener<TEventData[TEventName]>,\n ) {\n try {\n return await listener(eventArgs)\n } catch (ex) {\n handleError(ex, (error) => {\n this.logger?.error(`Listener[${String(eventName)}] Excepted: ${error.message}`)\n })\n }\n }\n}\n"],"mappings":";AAAA,SAAS,gBAAgB;AAEzB,SAAS,YAAY;AACrB,SAAS,mBAAmB;AAC5B,SAAS,cAAc;AACvB,SAAS,iBAAiB;AAqB1B,IAAM,8BAA8B;AAWpC,IAAM,kBAAkB,QAAQ,QAAQ;AAaxC,IAAM,cAAc,CAAC,cAAyB,cAAc,mBAAmB,cAAc;AAItF,IAAM,SAAN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D,QAAI,CAAC,OAAO,IAAI,SAAS,GAAG;AAC1B;AAAA,IACF;AAEA,WAAO,OAAO,IAAI,SAAS;AAAA,EAC7B;AAAA,EAEA,MAAc,oBACZ,WACA,WACA,UACA;AACA,QAAI;AACF,aAAO,MAAM,SAAS,WAAW,SAAS;AAAA,IAC5C,SAAS,IAAI;AACX,kBAAY,IAAI,CAAC,UAAU;AACzB,aAAK,QAAQ,MAAM,YAAY,OAAO,SAAS,CAAC,eAAe,MAAM,OAAO,EAAE;AAAA,MAChF,CAAC;AAAA,IACH;AAAA,EACF;AAAA,EAEA,MAAc,iBACZ,WACA,WACA,UACA;AACA,QAAI;AACF,aAAO,MAAM,SAAS,SAAS;AAAA,IACjC,SAAS,IAAI;AACX,kBAAY,IAAI,CAAC,UAAU;AACzB,aAAK,QAAQ,MAAM,YAAY,OAAO,SAAS,CAAC,eAAe,MAAM,OAAO,EAAE;AAAA,MAChF,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["eventName"]}
@@ -0,0 +1,65 @@
1
+ import type { BaseParams } from '@xylabs/base';
2
+ import { Base } from '@xylabs/base';
3
+ import type { EventAnyListener, EventArgs, EventData, EventFunctions, EventListener, EventName } from '../model/index.ts';
4
+ /**
5
+ Emittery can collect and log debug information.
6
+
7
+ To enable this feature set the `DEBUG` environment variable to `emittery` or `*`. Additionally, you can set the static `isDebugEnabled` variable to true
8
+ on the Emittery class, or `myEmitter.debug.enabled` on an instance of it for debugging a single instance.
9
+
10
+ See API for more information on how debugging works.
11
+ */
12
+ export type DebugLogger = (type: string, debugName: string, eventName?: EventName, eventData?: EventArgs) => void;
13
+ export type EventListenerInfo<TEventArgs extends EventArgs = EventArgs> = {
14
+ filter?: TEventArgs;
15
+ listener: EventListener<TEventArgs>;
16
+ };
17
+ /**
18
+ Configure debug options of an instance.
19
+ */
20
+ export type DebugOptions = {
21
+ enabled?: boolean;
22
+ logger?: DebugLogger;
23
+ readonly name: string;
24
+ };
25
+ export type MetaEventData<TEventData extends EventData> = {
26
+ listenerAdded: {
27
+ eventName?: keyof TEventData;
28
+ listener: EventListener<TEventData[keyof TEventData]> | EventAnyListener<TEventData[keyof TEventData]>;
29
+ };
30
+ listenerRemoved: {
31
+ eventName?: keyof TEventData;
32
+ listener: EventListener<TEventData[keyof TEventData]> | EventAnyListener<TEventData[keyof TEventData]>;
33
+ };
34
+ };
35
+ export type EventsParams = BaseParams<{
36
+ readonly debug?: DebugOptions;
37
+ }>;
38
+ export declare class Events<TEventData extends EventData = EventData> extends Base<EventsParams> implements EventFunctions<TEventData> {
39
+ protected static anyMap: WeakMap<object, Set<EventAnyListener>>;
40
+ protected static eventsMap: WeakMap<object, Map<PropertyKey, Set<EventListenerInfo<EventArgs>>>>;
41
+ private static canEmitMetaEvents;
42
+ private static isGlobalDebugEnabled;
43
+ eventData: TEventData;
44
+ constructor(params?: EventsParams);
45
+ static get isDebugEnabled(): boolean;
46
+ static set isDebugEnabled(newValue: boolean);
47
+ get debug(): DebugOptions | undefined;
48
+ clearListeners(eventNames: keyof TEventData | (keyof TEventData)[]): void;
49
+ emit<TEventName extends keyof TEventData>(eventName: TEventName, eventArgs: TEventData[TEventName]): Promise<void>;
50
+ emitMetaEvent<TEventName extends keyof MetaEventData<TEventData>>(eventName: TEventName, eventArgs: MetaEventData<TEventData>[TEventName]): Promise<void>;
51
+ emitSerial<TEventName extends keyof TEventData>(eventName: TEventName, eventArgs: TEventData[TEventName]): Promise<void>;
52
+ listenerCount(eventNames?: keyof TEventData | (keyof TEventData)[]): number;
53
+ logIfDebugEnabled<TEventName extends EventName>(type: string, eventName?: TEventName, eventArgs?: EventArgs): void;
54
+ off<TEventName extends keyof TEventData, TEventListener = EventListener<TEventData[TEventName]>>(eventNames: TEventName | TEventName[], listener: TEventListener): void;
55
+ offAny(listener: EventAnyListener): void;
56
+ on<TEventName extends keyof TEventData = keyof TEventData>(eventNames: TEventName | TEventName[], listener: EventListener<TEventData[TEventName]>, filter?: TEventData[TEventName]): () => void;
57
+ onAny(listener: EventAnyListener): () => void;
58
+ once<TEventName extends keyof TEventData>(eventName: TEventName, listener: EventListener<TEventData[TEventName]>): () => void;
59
+ private emitInternal;
60
+ private emitMetaEventInternal;
61
+ private getListeners;
62
+ private safeCallAnyListener;
63
+ private safeCallListener;
64
+ }
65
+ //# sourceMappingURL=Events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Events.d.ts","sourceRoot":"","sources":["../../../src/Events/Events.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAA;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,cAAc,CAAA;AAKnC,OAAO,KAAK,EACV,gBAAgB,EAAE,SAAS,EAAE,SAAS,EAAE,cAAc,EAAE,aAAa,EAAE,SAAS,EACjF,MAAM,mBAAmB,CAAA;AAE1B;;;;;;;EAOE;AACF,MAAM,MAAM,WAAW,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,SAAS,EAAE,SAAS,CAAC,EAAE,SAAS,KAAK,IAAI,CAAA;AAEjH,MAAM,MAAM,iBAAiB,CAAC,UAAU,SAAS,SAAS,GAAG,SAAS,IAAI;IACxE,MAAM,CAAC,EAAE,UAAU,CAAA;IACnB,QAAQ,EAAE,aAAa,CAAC,UAAU,CAAC,CAAA;CACpC,CAAA;AAID;;EAEE;AACF,MAAM,MAAM,YAAY,GAAG;IACzB,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,MAAM,CAAC,EAAE,WAAW,CAAA;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CACtB,CAAA;AAID,MAAM,MAAM,aAAa,CAAC,UAAU,SAAS,SAAS,IAAI;IACxD,aAAa,EAAE;QACb,SAAS,CAAC,EAAE,MAAM,UAAU,CAAA;QAC5B,QAAQ,EAAE,aAAa,CAAC,UAAU,CAAC,MAAM,UAAU,CAAC,CAAC,GAAG,gBAAgB,CAAC,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,EAAE,UAAU,EAAE,SAAS,EAAE,UAAU,CAAC,UAAU,CAAC;IAuC9G,aAAa,CAAC,UAAU,CAAC,EAAE,MAAM,UAAU,GAAG,CAAC,MAAM,UAAU,CAAC,EAAE;IAqBlE,iBAAiB,CAAC,UAAU,SAAS,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,UAAU,EAAE,SAAS,CAAC,EAAE,SAAS;IAM3G,GAAG,CAAC,UAAU,SAAS,MAAM,UAAU,EAAE,cAAc,GAAG,aAAa,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,EAC7F,UAAU,EAAE,UAAU,GAAG,UAAU,EAAE,EACrC,QAAQ,EAAE,cAAc;IAqB1B,MAAM,CAAC,QAAQ,EAAE,gBAAgB;IAQjC,EAAE,CAAC,UAAU,SAAS,MAAM,UAAU,GAAG,MAAM,UAAU,EACvD,UAAU,EAAE,UAAU,GAAG,UAAU,EAAE,EACrC,QAAQ,EAAE,aAAa,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,EAC/C,MAAM,CAAC,EAAE,UAAU,CAAC,UAAU,CAAC;IAuBjC,KAAK,CAAC,QAAQ,EAAE,gBAAgB;IAQhC,IAAI,CAAC,UAAU,SAAS,MAAM,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,aAAa,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;YASlG,YAAY;YA8BZ,qBAAqB;IA6BnC,OAAO,CAAC,YAAY;YASN,mBAAmB;YAcnB,gBAAgB;CAa/B"}
@@ -0,0 +1,2 @@
1
+ export * from './Events.ts';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/Events/index.ts"],"names":[],"mappings":"AAAA,cAAc,aAAa,CAAA"}
@@ -0,0 +1,3 @@
1
+ export * from './Events/index.ts';
2
+ export * from './model/index.ts';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,mBAAmB,CAAA;AACjC,cAAc,kBAAkB,CAAA"}
@@ -0,0 +1,22 @@
1
+ import type { Promisable } from '@xylabs/promise';
2
+ export type EventName = PropertyKey;
3
+ export type EventArgs = string | number | object;
4
+ export type EventData = {
5
+ [key: EventName]: EventArgs;
6
+ };
7
+ export type EventUnsubscribeFunction = () => void;
8
+ export type EventAnyListener<TEventArgs extends EventArgs = EventArgs> = (eventName: EventName, eventData: TEventArgs) => Promisable<void>;
9
+ export type EventListener<TEventArgs extends EventArgs = EventArgs> = (eventData: TEventArgs) => Promisable<void>;
10
+ export interface EventFunctions<TEventData extends EventData> {
11
+ eventData: TEventData;
12
+ clearListeners(eventNames: keyof TEventData | (keyof TEventData)[]): void;
13
+ emit<TEventName extends keyof TEventData>(eventName: TEventName, eventArgs: TEventData[TEventName]): Promise<void>;
14
+ emitSerial<TEventName extends keyof TEventData>(eventName: TEventName, eventArgs: TEventData[TEventName]): Promise<void>;
15
+ listenerCount(eventNames: keyof TEventData | (keyof TEventData)[]): number;
16
+ off<TEventName extends keyof TEventData>(eventNames: TEventName | TEventName[], listener: EventListener<TEventData[TEventName]>): void;
17
+ offAny(listener: EventAnyListener | Promise<void>): void;
18
+ on<TEventName extends keyof TEventData>(eventNames: TEventName | TEventName[], listener: EventListener<TEventData[TEventName]>): EventUnsubscribeFunction;
19
+ onAny(listener: EventAnyListener): EventUnsubscribeFunction;
20
+ once<TEventName extends keyof TEventData>(eventName: TEventName, listener: EventListener<TEventData[TEventName]>): EventUnsubscribeFunction;
21
+ }
22
+ //# sourceMappingURL=Event.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Event.d.ts","sourceRoot":"","sources":["../../../src/model/Event.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAA;AAEjD,MAAM,MAAM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,CAAA;IACtI,MAAM,CAAC,QAAQ,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAA;IACxD,EAAE,CAAC,UAAU,SAAS,MAAM,UAAU,EACpC,UAAU,EAAE,UAAU,GAAG,UAAU,EAAE,EACrC,QAAQ,EAAE,aAAa,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,GAC9C,wBAAwB,CAAA;IAC3B,KAAK,CAAC,QAAQ,EAAE,gBAAgB,GAAG,wBAAwB,CAAA;IAC3D,IAAI,CAAC,UAAU,SAAS,MAAM,UAAU,EAAE,SAAS,EAAE,UAAU,EAAE,QAAQ,EAAE,aAAa,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC,GAAG,wBAAwB,CAAA;CAC5I"}
@@ -0,0 +1,2 @@
1
+ export * from './Event.ts';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/model/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAA"}
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@xylabs/events",
3
+ "version": "4.9.17",
4
+ "description": "Primary SDK for using XYO Protocol 2.0",
5
+ "homepage": "https://xyo.network",
6
+ "bugs": {
7
+ "url": "git+https://github.com/XYOracleNetwork/sdk-xyo-client-js/issues",
8
+ "email": "support@xyo.network"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/XYOracleNetwork/sdk-xyo-client-js.git"
13
+ },
14
+ "license": "LGPL-3.0-only",
15
+ "author": {
16
+ "name": "XYO Development Team",
17
+ "email": "support@xyo.network",
18
+ "url": "https://xyo.network"
19
+ },
20
+ "sideEffects": false,
21
+ "type": "module",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/types/index.d.ts",
25
+ "default": "./dist/neutral/index.mjs"
26
+ },
27
+ "./package.json": "./package.json"
28
+ },
29
+ "module": "dist/neutral/index.mjs",
30
+ "types": "dist/types/index.d.ts",
31
+ "dependencies": {
32
+ "@xylabs/assert": "^4.9.17",
33
+ "@xylabs/base": "^4.9.17",
34
+ "@xylabs/error": "^4.9.17",
35
+ "@xylabs/forget": "^4.9.17",
36
+ "@xylabs/promise": "^4.9.17",
37
+ "@xylabs/typeof": "^4.9.17"
38
+ },
39
+ "devDependencies": {
40
+ "@xylabs/delay": "^4.9.17",
41
+ "@xylabs/ts-scripts-yarn3": "^6.5.5",
42
+ "@xylabs/tsconfig": "^6.5.5",
43
+ "@xylabs/vitest-extended": "^4.9.17",
44
+ "typescript": "^5.8.3",
45
+ "vitest": "^3.1.3"
46
+ },
47
+ "publishConfig": {
48
+ "access": "public"
49
+ }
50
+ }
@@ -0,0 +1,382 @@
1
+ import { assertEx } from '@xylabs/assert'
2
+ import type { BaseParams } from '@xylabs/base'
3
+ import { Base } from '@xylabs/base'
4
+ import { handleError } from '@xylabs/error'
5
+ import { forget } from '@xylabs/forget'
6
+ import { isDefined } from '@xylabs/typeof'
7
+
8
+ import type {
9
+ EventAnyListener, EventArgs, EventData, EventFunctions, EventListener, EventName,
10
+ } from '../model/index.ts'
11
+
12
+ /**
13
+ Emittery can collect and log debug information.
14
+
15
+ To enable this feature set the `DEBUG` environment variable to `emittery` or `*`. Additionally, you can set the static `isDebugEnabled` variable to true
16
+ on the Emittery class, or `myEmitter.debug.enabled` on an instance of it for debugging a single instance.
17
+
18
+ See API for more information on how debugging works.
19
+ */
20
+ export type DebugLogger = (type: string, debugName: string, eventName?: EventName, eventData?: EventArgs) => void
21
+
22
+ export type EventListenerInfo<TEventArgs extends EventArgs = EventArgs> = {
23
+ filter?: TEventArgs
24
+ listener: EventListener<TEventArgs>
25
+ }
26
+
27
+ const NO_META_EVENT_ERROR_MESSAGE = '`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`'
28
+
29
+ /**
30
+ Configure debug options of an instance.
31
+ */
32
+ export type DebugOptions = {
33
+ enabled?: boolean
34
+ logger?: DebugLogger
35
+ readonly name: string
36
+ }
37
+
38
+ const resolvedPromise = Promise.resolve()
39
+
40
+ export type MetaEventData<TEventData extends EventData> = {
41
+ listenerAdded: {
42
+ eventName?: keyof TEventData
43
+ listener: EventListener<TEventData[keyof TEventData]> | EventAnyListener<TEventData[keyof TEventData]>
44
+ }
45
+ listenerRemoved: {
46
+ eventName?: keyof TEventData
47
+ listener: EventListener<TEventData[keyof TEventData]> | EventAnyListener<TEventData[keyof TEventData]>
48
+ }
49
+ }
50
+
51
+ const isMetaEvent = (eventName: EventName) => eventName === 'listenerAdded' || eventName === 'listenerRemoved'
52
+
53
+ export type EventsParams = BaseParams<{ readonly debug?: DebugOptions }>
54
+
55
+ export class Events<TEventData extends EventData = EventData> extends Base<EventsParams> implements EventFunctions<TEventData> {
56
+ protected static anyMap = new WeakMap<object, Set<EventAnyListener>>()
57
+ protected static eventsMap = new WeakMap<object, Map<EventName, Set<EventListenerInfo>>>()
58
+
59
+ private static canEmitMetaEvents = false
60
+ private static isGlobalDebugEnabled = false
61
+
62
+ // this is here to be able to query the type, not use
63
+ eventData = {} as TEventData
64
+
65
+ constructor(params: EventsParams = {}) {
66
+ const mutatedParams = { ...params }
67
+ if (mutatedParams.debug) {
68
+ mutatedParams.debug.logger
69
+ = mutatedParams.debug.logger
70
+ ?? ((type: string, debugName: string, eventName?: EventName, eventData?: EventArgs) => {
71
+ let eventDataString: string
72
+ try {
73
+ eventDataString = JSON.stringify(eventData)
74
+ } catch {
75
+ eventDataString = `Object with the following keys failed to stringify: ${Object.keys(eventData ?? {}).join(',')}`
76
+ }
77
+
78
+ const eventNameString = typeof eventName === 'symbol' || typeof eventName === 'number' ? eventName.toString() : eventName
79
+
80
+ const currentTime = new Date()
81
+ const logTime = `${currentTime.getHours()}:${currentTime.getMinutes()}:${currentTime.getSeconds()}.${currentTime.getMilliseconds()}`
82
+ this.logger?.log(`[${logTime}][events:${type}][${debugName}] Event Name: ${eventNameString}\n\tdata: ${eventDataString}`)
83
+ })
84
+ }
85
+ super(mutatedParams)
86
+ Events.anyMap.set(this, new Set<EventAnyListener>())
87
+ Events.eventsMap.set(this, new Map<keyof TEventData, Set<EventListenerInfo>>())
88
+ }
89
+
90
+ static get isDebugEnabled() {
91
+ // In a browser environment, `globalThis.process` can potentially reference a DOM Element with a `#process` ID,
92
+ // so instead of just type checking `globalThis.process`, we need to make sure that `globalThis.process.env` exists.
93
+
94
+ if (typeof globalThis.process?.env !== 'object') {
95
+ return Events.isGlobalDebugEnabled
96
+ }
97
+
98
+ const { env } = globalThis.process ?? { env: {} }
99
+ return env.DEBUG === 'events' || env.DEBUG === '*' || Events.isGlobalDebugEnabled
100
+ }
101
+
102
+ static set isDebugEnabled(newValue) {
103
+ Events.isGlobalDebugEnabled = newValue
104
+ }
105
+
106
+ get debug() {
107
+ return this.params.debug
108
+ }
109
+
110
+ clearListeners(eventNames: keyof TEventData | (keyof TEventData)[]) {
111
+ const eventNamesArray = Array.isArray(eventNames) ? eventNames : [eventNames]
112
+
113
+ for (const eventName of eventNamesArray) {
114
+ this.logIfDebugEnabled('clear', eventName)
115
+
116
+ if (typeof eventName === 'string' || typeof eventName === 'symbol' || typeof eventName === 'number') {
117
+ const set = this.getListeners(eventName)
118
+ if (set) {
119
+ set.clear()
120
+ }
121
+ } else {
122
+ Events.anyMap.get(this)?.clear()
123
+
124
+ for (const [eventName, listeners] of assertEx(Events.eventsMap.get(this)).entries()) {
125
+ listeners.clear()
126
+ Events.eventsMap.get(this)?.delete(eventName)
127
+ }
128
+ }
129
+ }
130
+ }
131
+
132
+ async emit<TEventName extends keyof TEventData>(eventName: TEventName, eventArgs: TEventData[TEventName]) {
133
+ await this.emitInternal(eventName, eventArgs)
134
+ }
135
+
136
+ async emitMetaEvent<TEventName extends keyof MetaEventData<TEventData>>(eventName: TEventName, eventArgs: MetaEventData<TEventData>[TEventName]) {
137
+ if (isMetaEvent(eventName)) {
138
+ try {
139
+ Events.canEmitMetaEvents = true
140
+ await this.emitMetaEventInternal(eventName, eventArgs)
141
+ } finally {
142
+ Events.canEmitMetaEvents = false
143
+ }
144
+ }
145
+ }
146
+
147
+ async emitSerial<TEventName extends keyof TEventData>(eventName: TEventName, eventArgs: TEventData[TEventName]) {
148
+ if (isMetaEvent(eventName) && !Events.canEmitMetaEvents) {
149
+ throw new TypeError(NO_META_EVENT_ERROR_MESSAGE)
150
+ }
151
+
152
+ const filterMatch = (args: TEventData[TEventName], filter: TEventData[TEventName]) => {
153
+ switch (typeof filter) {
154
+ case 'object': {
155
+ // eslint-disable-next-line unicorn/no-array-reduce
156
+ return Object.entries(args).reduce((prev, [key, value]) => ((filter as Record<PropertyKey, unknown>)[key] === value ? true : prev), false)
157
+ }
158
+ default: {
159
+ return args === filter
160
+ }
161
+ }
162
+ }
163
+
164
+ this.logIfDebugEnabled('emitSerial', eventName, eventArgs)
165
+
166
+ const listeners = this.getListeners(eventName) ?? new Set()
167
+ const filteredListeners = [...listeners.values()]
168
+ .filter(value => (isDefined(value.filter) ? filterMatch(eventArgs, value.filter as TEventData[TEventName]) : true))
169
+ .map(info => info.listener)
170
+ const anyListeners = assertEx(Events.anyMap.get(this))
171
+ const staticListeners = [...filteredListeners]
172
+ const staticAnyListeners = [...anyListeners]
173
+
174
+ await resolvedPromise
175
+
176
+ for (const listener of staticListeners) {
177
+ await this.safeCallListener(eventName, eventArgs, listener)
178
+ }
179
+
180
+ for (const listener of staticAnyListeners) {
181
+ await this.safeCallAnyListener(eventName, eventArgs, listener)
182
+ }
183
+ }
184
+
185
+ // TODO: Make test for this
186
+ listenerCount(eventNames?: keyof TEventData | (keyof TEventData)[]) {
187
+ const eventNamesArray = Array.isArray(eventNames) ? eventNames : [eventNames]
188
+ let count = 0
189
+
190
+ for (const eventName of eventNamesArray) {
191
+ if (typeof eventName === 'string') {
192
+ count += assertEx(Events.anyMap.get(this)).size + (this.getListeners(eventName)?.size ?? 0)
193
+
194
+ continue
195
+ }
196
+
197
+ count += assertEx(Events.anyMap.get(this)).size
198
+
199
+ for (const value of assertEx(Events.eventsMap.get(this)).values()) {
200
+ count += value.size
201
+ }
202
+ }
203
+
204
+ return count
205
+ }
206
+
207
+ logIfDebugEnabled<TEventName extends EventName>(type: string, eventName?: TEventName, eventArgs?: EventArgs) {
208
+ if (Events.isDebugEnabled || this.debug?.enabled) {
209
+ this.debug?.logger?.(type, this.debug.name, eventName, eventArgs)
210
+ }
211
+ }
212
+
213
+ off<TEventName extends keyof TEventData, TEventListener = EventListener<TEventData[TEventName]>>(
214
+ eventNames: TEventName | TEventName[],
215
+ listener: TEventListener,
216
+ ) {
217
+ const eventNamesArray = Array.isArray(eventNames) ? eventNames : [eventNames]
218
+ for (const eventName of eventNamesArray) {
219
+ const set = this.getListeners(eventName) as Set<TEventListener> | undefined
220
+ if (set) {
221
+ set.delete(listener)
222
+ if (set.size === 0) {
223
+ const events = Events.eventsMap.get(this)
224
+ events?.delete(eventName)
225
+ }
226
+ }
227
+
228
+ this.logIfDebugEnabled('unsubscribe', eventName)
229
+
230
+ if (!isMetaEvent(eventName)) {
231
+ forget(this.emitMetaEvent('listenerRemoved', { eventName, listener: listener as EventListener }))
232
+ }
233
+ }
234
+ }
235
+
236
+ offAny(listener: EventAnyListener) {
237
+ this.logIfDebugEnabled('unsubscribeAny')
238
+
239
+ const typedMap = Events.anyMap.get(this) as Set<EventAnyListener<TEventData[keyof TEventData]>>
240
+ typedMap?.delete(listener)
241
+ forget(this.emitMetaEvent('listenerRemoved', { listener: listener as EventAnyListener }))
242
+ }
243
+
244
+ on<TEventName extends keyof TEventData = keyof TEventData>(
245
+ eventNames: TEventName | TEventName[],
246
+ listener: EventListener<TEventData[TEventName]>,
247
+ filter?: TEventData[TEventName],
248
+ ) {
249
+ const eventNamesArray = Array.isArray(eventNames) ? eventNames : [eventNames]
250
+ for (const eventName of eventNamesArray) {
251
+ let set = this.getListeners(eventName)
252
+ if (!set) {
253
+ set = new Set()
254
+ const events = Events.eventsMap.get(this)
255
+ events?.set(eventName, set)
256
+ }
257
+
258
+ set.add({ filter, listener: listener as EventListener })
259
+
260
+ this.logIfDebugEnabled('subscribe', eventName)
261
+
262
+ if (!isMetaEvent(eventName)) {
263
+ forget(this.emitMetaEvent('listenerAdded', { eventName, listener: listener as EventListener }))
264
+ }
265
+ }
266
+
267
+ return this.off.bind(this, eventNames, listener as EventListener)
268
+ }
269
+
270
+ onAny(listener: EventAnyListener) {
271
+ this.logIfDebugEnabled('subscribeAny')
272
+
273
+ Events.anyMap.get(this)?.add(listener as EventAnyListener)
274
+ forget(this.emitMetaEvent('listenerAdded', { listener: listener as EventAnyListener }))
275
+ return this.offAny.bind(this, listener as EventAnyListener)
276
+ }
277
+
278
+ once<TEventName extends keyof TEventData>(eventName: TEventName, listener: EventListener<TEventData[TEventName]>) {
279
+ const subListener = async (args: TEventData[TEventName]) => {
280
+ this.off(eventName, subListener)
281
+ await this.safeCallListener(eventName, args, listener)
282
+ }
283
+ this.on(eventName, subListener)
284
+ return this.off.bind(this, eventName, subListener as EventListener)
285
+ }
286
+
287
+ private async emitInternal<TEventName extends keyof TEventData, TEventArgs extends TEventData[TEventName]>(
288
+ eventName: TEventName,
289
+ eventArgs: TEventArgs,
290
+ filter?: TEventArgs,
291
+ ) {
292
+ if (isMetaEvent(eventName) && !Events.canEmitMetaEvents) {
293
+ throw new TypeError(NO_META_EVENT_ERROR_MESSAGE)
294
+ }
295
+
296
+ this.logIfDebugEnabled('emit', eventName, eventArgs)
297
+
298
+ const listeners = this.getListeners(eventName) ?? new Set()
299
+ const filteredListeners = [...listeners.values()].filter(value => (isDefined(filter) ? isDefined(value.listener) : true)).map(info => info.listener)
300
+ const anyListeners = assertEx(Events.anyMap.get(this))
301
+ const staticListeners = [...filteredListeners]
302
+ const staticAnyListeners = isMetaEvent(eventName) ? [] : [...anyListeners]
303
+
304
+ await resolvedPromise
305
+ await Promise.all([
306
+ ...staticListeners.map(async (listener) => {
307
+ await this.safeCallListener(eventName, eventArgs, listener)
308
+ }),
309
+ ...staticAnyListeners.map(async (listener) => {
310
+ if (anyListeners.has(listener)) {
311
+ await this.safeCallAnyListener(eventName, eventArgs, listener)
312
+ }
313
+ }),
314
+ ])
315
+ }
316
+
317
+ private async emitMetaEventInternal<TEventName extends keyof MetaEventData<TEventData>>(
318
+ eventName: TEventName,
319
+ eventArgs: MetaEventData<TEventData>[TEventName],
320
+ ) {
321
+ if (isMetaEvent(eventName) && !Events.canEmitMetaEvents) {
322
+ throw new TypeError('`eventName` cannot be meta event `listenerAdded` or `listenerRemoved`')
323
+ }
324
+
325
+ this.logIfDebugEnabled('emit', eventName, eventArgs)
326
+
327
+ const listeners = this.getListeners(eventName) ?? new Set()
328
+ const filteredListeners = [...listeners.values()].map(info => info.listener)
329
+ const anyListeners = assertEx(Events.anyMap.get(this))
330
+ const staticListeners = [...filteredListeners]
331
+ const staticAnyListeners = isMetaEvent(eventName) ? [] : [...anyListeners]
332
+
333
+ await resolvedPromise
334
+ await Promise.all([
335
+ ...staticListeners.map(async (listener) => {
336
+ await this.safeCallListener(eventName, eventArgs, listener)
337
+ }),
338
+ ...staticAnyListeners.map(async (listener) => {
339
+ if (anyListeners.has(listener)) {
340
+ await this.safeCallAnyListener(eventName, eventArgs, listener)
341
+ }
342
+ }),
343
+ ])
344
+ }
345
+
346
+ private getListeners<TEventName extends keyof TEventData>(eventName: TEventName) {
347
+ const events = assertEx(Events.eventsMap.get(this))
348
+ if (!events.has(eventName)) {
349
+ return
350
+ }
351
+
352
+ return events.get(eventName)
353
+ }
354
+
355
+ private async safeCallAnyListener<TEventData extends EventData, TEventName extends keyof EventData>(
356
+ eventName: TEventName,
357
+ eventArgs: TEventData[TEventName],
358
+ listener: EventAnyListener<TEventData[TEventName]>,
359
+ ) {
360
+ try {
361
+ return await listener(eventName, eventArgs)
362
+ } catch (ex) {
363
+ handleError(ex, (error) => {
364
+ this.logger?.error(`Listener[${String(eventName)}] Excepted: ${error.message}`)
365
+ })
366
+ }
367
+ }
368
+
369
+ private async safeCallListener<TEventData extends EventData, TEventName extends keyof EventData>(
370
+ eventName: TEventName,
371
+ eventArgs: TEventData[TEventName],
372
+ listener: EventListener<TEventData[TEventName]>,
373
+ ) {
374
+ try {
375
+ return await listener(eventArgs)
376
+ } catch (ex) {
377
+ handleError(ex, (error) => {
378
+ this.logger?.error(`Listener[${String(eventName)}] Excepted: ${error.message}`)
379
+ })
380
+ }
381
+ }
382
+ }
@@ -0,0 +1 @@
1
+ export * from './Events.ts'
package/src/index.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './Events/index.ts'
2
+ export * from './model/index.ts'
@@ -0,0 +1,24 @@
1
+ import type { Promisable } from '@xylabs/promise'
2
+
3
+ export type EventName = PropertyKey
4
+ export type EventArgs = string | number | object
5
+ export type EventData = { [key: EventName]: EventArgs }
6
+ export type EventUnsubscribeFunction = () => void
7
+ export type EventAnyListener<TEventArgs extends EventArgs = EventArgs> = (eventName: EventName, eventData: TEventArgs) => Promisable<void>
8
+ export type EventListener<TEventArgs extends EventArgs = EventArgs> = (eventData: TEventArgs) => Promisable<void>
9
+
10
+ export interface EventFunctions<TEventData extends EventData> {
11
+ eventData: TEventData
12
+ clearListeners(eventNames: keyof TEventData | (keyof TEventData)[]): void
13
+ emit<TEventName extends keyof TEventData>(eventName: TEventName, eventArgs: TEventData[TEventName]): Promise<void>
14
+ emitSerial<TEventName extends keyof TEventData>(eventName: TEventName, eventArgs: TEventData[TEventName]): Promise<void>
15
+ listenerCount(eventNames: keyof TEventData | (keyof TEventData)[]): number
16
+ off<TEventName extends keyof TEventData>(eventNames: TEventName | TEventName[], listener: EventListener<TEventData[TEventName]>): void
17
+ offAny(listener: EventAnyListener | Promise<void>): void
18
+ on<TEventName extends keyof TEventData>(
19
+ eventNames: TEventName | TEventName[],
20
+ listener: EventListener<TEventData[TEventName]>,
21
+ ): EventUnsubscribeFunction
22
+ onAny(listener: EventAnyListener): EventUnsubscribeFunction
23
+ once<TEventName extends keyof TEventData>(eventName: TEventName, listener: EventListener<TEventData[TEventName]>): EventUnsubscribeFunction
24
+ }
@@ -0,0 +1 @@
1
+ export * from './Event.ts'
package/xy.config.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { XyTsupConfig } from '@xylabs/ts-scripts-yarn3'
2
+ const config: XyTsupConfig = {
3
+ compile: {
4
+ browser: {},
5
+ neutral: { src: true },
6
+ node: {},
7
+ },
8
+ }
9
+
10
+ export default config