eleva 1.0.0-alpha → 1.0.0-rc.2

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.
@@ -1,46 +1,64 @@
1
1
  "use strict";
2
2
 
3
3
  /**
4
- * 🔒 TemplateEngine: Secure interpolation & dynamic attribute parsing.
4
+ * @class 🔒 TemplateEngine
5
+ * @classdesc A secure template engine that handles interpolation and dynamic attribute parsing.
6
+ * Provides a safe way to evaluate expressions in templates while preventing XSS attacks.
7
+ * All methods are static and can be called directly on the class.
5
8
  *
6
- * This class provides methods to parse template strings by replacing
7
- * interpolation expressions with dynamic data values and to evaluate expressions
8
- * within a given data context.
9
+ * @example
10
+ * const template = "Hello, {{name}}!";
11
+ * const data = { name: "World" };
12
+ * const result = TemplateEngine.parse(template, data); // Returns: "Hello, World!"
9
13
  */
10
14
  export class TemplateEngine {
11
15
  /**
12
- * Parses a template string and replaces interpolation expressions with corresponding values.
16
+ * @private {RegExp} Regular expression for matching template expressions in the format {{ expression }}
17
+ * @type {RegExp}
18
+ */
19
+ static expressionPattern = /\{\{\s*(.*?)\s*\}\}/g;
20
+
21
+ /**
22
+ * Parses a template string, replacing expressions with their evaluated values.
23
+ * Expressions are evaluated in the provided data context.
13
24
  *
14
- * @param {string} template - The template string containing expressions in the format {{ expression }}.
15
- * @param {object} data - The data object to use for evaluating expressions.
16
- * @returns {string} The resulting string with evaluated values.
25
+ * @public
26
+ * @static
27
+ * @param {string} template - The template string to parse.
28
+ * @param {Record<string, unknown>} data - The data context for evaluating expressions.
29
+ * @returns {string} The parsed template with expressions replaced by their values.
30
+ * @example
31
+ * const result = TemplateEngine.parse("{{user.name}} is {{user.age}} years old", {
32
+ * user: { name: "John", age: 30 }
33
+ * }); // Returns: "John is 30 years old"
17
34
  */
18
35
  static parse(template, data) {
19
- return template.replace(/\{\{\s*(.*?)\s*\}\}/g, (_, expr) => {
20
- const value = this.evaluate(expr, data);
21
- return value === undefined ? "" : value;
22
- });
36
+ if (typeof template !== "string") return template;
37
+ return template.replace(this.expressionPattern, (_, expression) =>
38
+ this.evaluate(expression, data)
39
+ );
23
40
  }
24
41
 
25
42
  /**
26
- * Evaluates an expression using the provided data context.
43
+ * Evaluates an expression in the context of the provided data object.
44
+ * Note: This does not provide a true sandbox and evaluated expressions may access global scope.
45
+ * The use of the `with` statement is necessary for expression evaluation but has security implications.
46
+ * Expressions should be carefully validated before evaluation.
27
47
  *
28
- * @param {string} expr - The JavaScript expression to evaluate.
29
- * @param {object} data - The data context for evaluating the expression.
30
- * @returns {*} The result of the evaluated expression, or an empty string if undefined or on error.
48
+ * @public
49
+ * @static
50
+ * @param {string} expression - The expression to evaluate.
51
+ * @param {Record<string, unknown>} data - The data context for evaluation.
52
+ * @returns {unknown} The result of the evaluation, or an empty string if evaluation fails.
53
+ * @example
54
+ * const result = TemplateEngine.evaluate("user.name", { user: { name: "John" } }); // Returns: "John"
55
+ * const age = TemplateEngine.evaluate("user.age", { user: { age: 30 } }); // Returns: 30
31
56
  */
32
- static evaluate(expr, data) {
57
+ static evaluate(expression, data) {
58
+ if (typeof expression !== "string") return expression;
33
59
  try {
34
- const keys = Object.keys(data);
35
- const values = keys.map((k) => data[k]);
36
- const result = new Function(...keys, `return ${expr}`)(...values);
37
- return result === undefined ? "" : result;
38
- } catch (error) {
39
- console.error(`Template evaluation error:`, {
40
- expression: expr,
41
- data,
42
- error: error.message,
43
- });
60
+ return new Function("data", `with(data) { return ${expression}; }`)(data);
61
+ } catch {
44
62
  return "";
45
63
  }
46
64
  }
@@ -1,86 +1,355 @@
1
1
  /**
2
- * 🧩 Eleva Core: Signal-based component runtime framework with lifecycle, scoped styles, and plugins.
2
+ * @typedef {Object} ComponentDefinition
3
+ * @property {function(ComponentContext): (Record<string, unknown>|Promise<Record<string, unknown>>)} [setup]
4
+ * Optional setup function that initializes the component's state and returns reactive data
5
+ * @property {(function(ComponentContext): string|Promise<string>)} template
6
+ * Required function that defines the component's HTML structure
7
+ * @property {(function(ComponentContext): string)|string} [style]
8
+ * Optional function or string that provides component-scoped CSS styles
9
+ * @property {Record<string, ComponentDefinition>} [children]
10
+ * Optional object defining nested child components
11
+ */
12
+ /**
13
+ * @typedef {Object} ComponentContext
14
+ * @property {Record<string, unknown>} props
15
+ * Component properties passed during mounting
16
+ * @property {Emitter} emitter
17
+ * Event emitter instance for component event handling
18
+ * @property {function<T>(value: T): Signal<T>} signal
19
+ * Factory function to create reactive Signal instances
20
+ * @property {function(LifecycleHookContext): Promise<void>} [onBeforeMount]
21
+ * Hook called before component mounting
22
+ * @property {function(LifecycleHookContext): Promise<void>} [onMount]
23
+ * Hook called after component mounting
24
+ * @property {function(LifecycleHookContext): Promise<void>} [onBeforeUpdate]
25
+ * Hook called before component update
26
+ * @property {function(LifecycleHookContext): Promise<void>} [onUpdate]
27
+ * Hook called after component update
28
+ * @property {function(UnmountHookContext): Promise<void>} [onUnmount]
29
+ * Hook called during component unmounting
30
+ */
31
+ /**
32
+ * @typedef {Object} LifecycleHookContext
33
+ * @property {HTMLElement} container
34
+ * The DOM element where the component is mounted
35
+ * @property {ComponentContext} context
36
+ * The component's reactive state and context data
37
+ */
38
+ /**
39
+ * @typedef {Object} UnmountHookContext
40
+ * @property {HTMLElement} container
41
+ * The DOM element where the component is mounted
42
+ * @property {ComponentContext} context
43
+ * The component's reactive state and context data
44
+ * @property {{
45
+ * watchers: Array<() => void>, // Signal watcher cleanup functions
46
+ * listeners: Array<() => void>, // Event listener cleanup functions
47
+ * children: Array<MountResult> // Child component instances
48
+ * }} cleanup
49
+ * Object containing cleanup functions and instances
50
+ */
51
+ /**
52
+ * @typedef {Object} MountResult
53
+ * @property {HTMLElement} container
54
+ * The DOM element where the component is mounted
55
+ * @property {ComponentContext} data
56
+ * The component's reactive state and context data
57
+ * @property {function(): Promise<void>} unmount
58
+ * Function to clean up and unmount the component
59
+ */
60
+ /**
61
+ * @typedef {Object} ElevaPlugin
62
+ * @property {function(Eleva, Record<string, unknown>): void} install
63
+ * Function that installs the plugin into the Eleva instance
64
+ * @property {string} name
65
+ * Unique identifier name for the plugin
66
+ */
67
+ /**
68
+ * @class 🧩 Eleva
69
+ * @classdesc A modern, signal-based component runtime framework that provides lifecycle hooks,
70
+ * scoped styles, and plugin support. Eleva manages component registration, plugin integration,
71
+ * event handling, and DOM rendering with a focus on performance and developer experience.
72
+ *
73
+ * @example
74
+ * // Basic component creation and mounting
75
+ * const app = new Eleva("myApp");
76
+ * app.component("myComponent", {
77
+ * setup: (ctx) => ({ count: ctx.signal(0) }),
78
+ * template: (ctx) => `<div>Hello ${ctx.props.name}</div>`
79
+ * });
80
+ * app.mount(document.getElementById("app"), "myComponent", { name: "World" });
3
81
  *
4
- * The Eleva class is the core of the framework. It manages component registration,
5
- * plugin integration, lifecycle hooks, event handling, and DOM rendering.
82
+ * @example
83
+ * // Using lifecycle hooks
84
+ * app.component("lifecycleDemo", {
85
+ * setup: () => {
86
+ * return {
87
+ * onMount: ({ container, context }) => {
88
+ * console.log('Component mounted!');
89
+ * }
90
+ * };
91
+ * },
92
+ * template: `<div>Lifecycle Demo</div>`
93
+ * });
6
94
  */
7
95
  export class Eleva {
8
96
  /**
9
- * Creates a new Eleva instance.
97
+ * Creates a new Eleva instance with the specified name and configuration.
98
+ *
99
+ * @public
100
+ * @param {string} name - The unique identifier name for this Eleva instance.
101
+ * @param {Record<string, unknown>} [config={}] - Optional configuration object for the instance.
102
+ * May include framework-wide settings and default behaviors.
103
+ * @throws {Error} If the name is not provided or is not a string.
104
+ * @returns {Eleva} A new Eleva instance.
105
+ *
106
+ * @example
107
+ * const app = new Eleva("myApp");
108
+ * app.component("myComponent", {
109
+ * setup: (ctx) => ({ count: ctx.signal(0) }),
110
+ * template: (ctx) => `<div>Hello ${ctx.props.name}!</div>`
111
+ * });
112
+ * app.mount(document.getElementById("app"), "myComponent", { name: "World" });
10
113
  *
11
- * @param {string} name - The name of the Eleva instance.
12
- * @param {object} [config={}] - Optional configuration for the instance.
13
114
  */
14
- constructor(name: string, config?: object);
15
- name: string;
16
- config: object;
17
- _components: {};
18
- _plugins: any[];
19
- _lifecycleHooks: string[];
20
- _isMounted: boolean;
21
- emitter: Emitter;
22
- renderer: Renderer;
115
+ constructor(name: string, config?: Record<string, unknown>);
116
+ /** @public {string} The unique identifier name for this Eleva instance */
117
+ public name: string;
118
+ /** @public {Object<string, unknown>} Optional configuration object for the Eleva instance */
119
+ public config: Record<string, unknown>;
120
+ /** @public {Emitter} Instance of the event emitter for handling component events */
121
+ public emitter: Emitter;
122
+ /** @public {typeof Signal} Static reference to the Signal class for creating reactive state */
123
+ public signal: typeof Signal;
124
+ /** @public {Renderer} Instance of the renderer for handling DOM updates and patching */
125
+ public renderer: Renderer;
126
+ /** @private {Map<string, ComponentDefinition>} Registry of all component definitions by name */
127
+ private _components;
128
+ /** @private {Map<string, ElevaPlugin>} Collection of installed plugin instances by name */
129
+ private _plugins;
130
+ /** @private {boolean} Flag indicating if the root component is currently mounted */
131
+ private _isMounted;
132
+ /** @private {number} Counter for generating unique component IDs */
133
+ private _componentCounter;
23
134
  /**
24
135
  * Integrates a plugin with the Eleva framework.
136
+ * The plugin's install function will be called with the Eleva instance and provided options.
137
+ * After installation, the plugin will be available for use by components.
25
138
  *
26
- * @param {object} [plugin] - The plugin object which should have an install function.
27
- * @param {object} [options={}] - Optional options to pass to the plugin.
28
- * @returns {Eleva} The Eleva instance (for chaining).
139
+ * @public
140
+ * @param {ElevaPlugin} plugin - The plugin object which must have an `install` function.
141
+ * @param {Object<string, unknown>} [options={}] - Optional configuration options for the plugin.
142
+ * @returns {Eleva} The Eleva instance (for method chaining).
143
+ * @example
144
+ * app.use(myPlugin, { option1: "value1" });
29
145
  */
30
- use(plugin?: object, options?: object): Eleva;
146
+ public use(plugin: ElevaPlugin, options?: {
147
+ [x: string]: unknown;
148
+ }): Eleva;
31
149
  /**
32
- * Registers a component with the Eleva instance.
150
+ * Registers a new component with the Eleva instance.
151
+ * The component will be available for mounting using its registered name.
33
152
  *
34
- * @param {string} name - The name of the component.
35
- * @param {object} definition - The component definition including setup, template, style, and children.
36
- * @returns {Eleva} The Eleva instance (for chaining).
153
+ * @public
154
+ * @param {string} name - The unique name of the component to register.
155
+ * @param {ComponentDefinition} definition - The component definition including setup, template, style, and children.
156
+ * @returns {Eleva} The Eleva instance (for method chaining).
157
+ * @throws {Error} If the component name is already registered.
158
+ * @example
159
+ * app.component("myButton", {
160
+ * template: (ctx) => `<button>${ctx.props.text}</button>`,
161
+ * style: `button { color: blue; }`
162
+ * });
37
163
  */
38
- component(name: string, definition: object): Eleva;
164
+ public component(name: string, definition: ComponentDefinition): Eleva;
39
165
  /**
40
166
  * Mounts a registered component to a DOM element.
167
+ * This will initialize the component, set up its reactive state, and render it to the DOM.
41
168
  *
42
- * @param {string|HTMLElement} selectorOrElement - A CSS selector string or DOM element where the component will be mounted.
43
- * @param {string} compName - The name of the component to mount.
44
- * @param {object} [props={}] - Optional properties to pass to the component.
45
- * @returns {object|Promise<object>} An object representing the mounted component instance, or a Promise that resolves to it for asynchronous setups.
46
- * @throws Will throw an error if the container or component is not found.
169
+ * @public
170
+ * @param {HTMLElement} container - The DOM element where the component will be mounted.
171
+ * @param {string|ComponentDefinition} compName - The name of the registered component or a direct component definition.
172
+ * @param {Object<string, unknown>} [props={}] - Optional properties to pass to the component.
173
+ * @returns {Promise<MountResult>}
174
+ * A Promise that resolves to an object containing:
175
+ * - container: The mounted component's container element
176
+ * - data: The component's reactive state and context
177
+ * - unmount: Function to clean up and unmount the component
178
+ * @throws {Error} If the container is not found, or component is not registered.
179
+ * @example
180
+ * const instance = await app.mount(document.getElementById("app"), "myComponent", { text: "Click me" });
181
+ * // Later...
182
+ * instance.unmount();
47
183
  */
48
- mount(selectorOrElement: string | HTMLElement, compName: string, props?: object): object | Promise<object>;
49
- /**
50
- * Prepares default no-operation lifecycle hook functions.
51
- *
52
- * @returns {object} An object with keys for lifecycle hooks mapped to empty functions.
53
- * @private
54
- */
55
- private _prepareLifecycleHooks;
184
+ public mount(container: HTMLElement, compName: string | ComponentDefinition, props?: {
185
+ [x: string]: unknown;
186
+ }): Promise<MountResult>;
56
187
  /**
57
188
  * Processes DOM elements for event binding based on attributes starting with "@".
189
+ * This method handles the event delegation system and ensures proper cleanup of event listeners.
58
190
  *
59
- * @param {HTMLElement} container - The container element in which to search for events.
60
- * @param {object} context - The current context containing event handler definitions.
61
191
  * @private
192
+ * @param {HTMLElement} container - The container element in which to search for event attributes.
193
+ * @param {ComponentContext} context - The current component context containing event handler definitions.
194
+ * @param {Array<() => void>} listeners - Array to collect cleanup functions for each event listener.
195
+ * @returns {void}
62
196
  */
63
197
  private _processEvents;
64
198
  /**
65
199
  * Injects scoped styles into the component's container.
200
+ * The styles are automatically prefixed to prevent style leakage to other components.
66
201
  *
67
- * @param {HTMLElement} container - The container element.
68
- * @param {string} compName - The component name used to identify the style element.
69
- * @param {Function} styleFn - A function that returns CSS styles as a string.
70
- * @param {object} context - The current context for style interpolation.
71
202
  * @private
203
+ * @param {HTMLElement} container - The container element where styles should be injected.
204
+ * @param {string} compId - The component ID used to identify the style element.
205
+ * @param {(function(ComponentContext): string)|string} styleDef - The component's style definition (function or string).
206
+ * @param {ComponentContext} context - The current component context for style interpolation.
207
+ * @returns {void}
72
208
  */
73
209
  private _injectStyles;
74
210
  /**
75
- * Mounts child components within the parent component's container.
211
+ * Extracts props from an element's attributes that start with the specified prefix.
212
+ * This method is used to collect component properties from DOM elements.
76
213
  *
77
- * @param {HTMLElement} container - The parent container element.
78
- * @param {object} children - An object mapping child component selectors to their definitions.
79
- * @param {Array} childInstances - An array to store the mounted child component instances.
80
214
  * @private
215
+ * @param {HTMLElement} element - The DOM element to extract props from
216
+ * @param {string} prefix - The prefix to look for in attributes
217
+ * @returns {Record<string, string>} An object containing the extracted props
218
+ * @example
219
+ * // For an element with attributes:
220
+ * // <div :name="John" :age="25">
221
+ * // Returns: { name: "John", age: "25" }
81
222
  */
82
- private _mountChildren;
223
+ private _extractProps;
224
+ /**
225
+ * Mounts all components within the parent component's container.
226
+ * This method handles mounting of explicitly defined children components.
227
+ *
228
+ * The mounting process follows these steps:
229
+ * 1. Cleans up any existing component instances
230
+ * 2. Mounts explicitly defined children components
231
+ *
232
+ * @private
233
+ * @param {HTMLElement} container - The container element to mount components in
234
+ * @param {Object<string, ComponentDefinition>} children - Map of selectors to component definitions for explicit children
235
+ * @param {Array<MountResult>} childInstances - Array to store all mounted component instances
236
+ * @returns {Promise<void>}
237
+ *
238
+ * @example
239
+ * // Explicit children mounting:
240
+ * const children = {
241
+ * 'UserProfile': UserProfileComponent,
242
+ * '#settings-panel': "settings-panel"
243
+ * };
244
+ */
245
+ private _mountComponents;
83
246
  }
247
+ export type ComponentDefinition = {
248
+ /**
249
+ * Optional setup function that initializes the component's state and returns reactive data
250
+ */
251
+ setup?: ((arg0: ComponentContext) => (Record<string, unknown> | Promise<Record<string, unknown>>)) | undefined;
252
+ /**
253
+ * Required function that defines the component's HTML structure
254
+ */
255
+ template: ((arg0: ComponentContext) => string | Promise<string>);
256
+ /**
257
+ * Optional function or string that provides component-scoped CSS styles
258
+ */
259
+ style?: string | ((arg0: ComponentContext) => string) | undefined;
260
+ /**
261
+ * Optional object defining nested child components
262
+ */
263
+ children?: Record<string, ComponentDefinition> | undefined;
264
+ };
265
+ export type ComponentContext = {
266
+ /**
267
+ * Component properties passed during mounting
268
+ */
269
+ props: Record<string, unknown>;
270
+ /**
271
+ * Event emitter instance for component event handling
272
+ */
273
+ emitter: Emitter;
274
+ /**
275
+ * <T>(value: T): Signal<T>} signal
276
+ * Factory function to create reactive Signal instances
277
+ */
278
+ "": Function;
279
+ /**
280
+ * Hook called before component mounting
281
+ */
282
+ onBeforeMount?: ((arg0: LifecycleHookContext) => Promise<void>) | undefined;
283
+ /**
284
+ * Hook called after component mounting
285
+ */
286
+ onMount?: ((arg0: LifecycleHookContext) => Promise<void>) | undefined;
287
+ /**
288
+ * Hook called before component update
289
+ */
290
+ onBeforeUpdate?: ((arg0: LifecycleHookContext) => Promise<void>) | undefined;
291
+ /**
292
+ * Hook called after component update
293
+ */
294
+ onUpdate?: ((arg0: LifecycleHookContext) => Promise<void>) | undefined;
295
+ /**
296
+ * Hook called during component unmounting
297
+ */
298
+ onUnmount?: ((arg0: UnmountHookContext) => Promise<void>) | undefined;
299
+ };
300
+ export type LifecycleHookContext = {
301
+ /**
302
+ * The DOM element where the component is mounted
303
+ */
304
+ container: HTMLElement;
305
+ /**
306
+ * The component's reactive state and context data
307
+ */
308
+ context: ComponentContext;
309
+ };
310
+ export type UnmountHookContext = {
311
+ /**
312
+ * The DOM element where the component is mounted
313
+ */
314
+ container: HTMLElement;
315
+ /**
316
+ * The component's reactive state and context data
317
+ */
318
+ context: ComponentContext;
319
+ /**
320
+ * Object containing cleanup functions and instances
321
+ */
322
+ cleanup: {
323
+ watchers: Array<() => void>;
324
+ listeners: Array<() => void>;
325
+ children: Array<MountResult>;
326
+ };
327
+ };
328
+ export type MountResult = {
329
+ /**
330
+ * The DOM element where the component is mounted
331
+ */
332
+ container: HTMLElement;
333
+ /**
334
+ * The component's reactive state and context data
335
+ */
336
+ data: ComponentContext;
337
+ /**
338
+ * Function to clean up and unmount the component
339
+ */
340
+ unmount: () => Promise<void>;
341
+ };
342
+ export type ElevaPlugin = {
343
+ /**
344
+ * Function that installs the plugin into the Eleva instance
345
+ */
346
+ install: (arg0: Eleva, arg1: Record<string, unknown>) => void;
347
+ /**
348
+ * Unique identifier name for the plugin
349
+ */
350
+ name: string;
351
+ };
84
352
  import { Emitter } from "../modules/Emitter.js";
353
+ import { Signal } from "../modules/Signal.js";
85
354
  import { Renderer } from "../modules/Renderer.js";
86
355
  //# sourceMappingURL=Eleva.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Eleva.d.ts","sourceRoot":"","sources":["../../src/core/Eleva.js"],"names":[],"mappings":"AAOA;;;;;GAKG;AACH;IACE;;;;;OAKG;IACH,kBAHW,MAAM,WACN,MAAM,EAiBhB;IAdC,aAAgB;IAChB,e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;;;;aAMzB,CAAS,IAAK,EAAL,KAAK,EAAE,IAAuB,EAAvB,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KAAG,IAAI;;;;UAE9C,MAAM;;wBAvEI,uBAAuB;uBADxB,sBAAsB;yBAEpB,wBAAwB"}
@@ -1,34 +1,66 @@
1
1
  /**
2
- * 🎙️ Emitter: Robust inter-component communication with event bubbling.
2
+ * @class 📡 Emitter
3
+ * @classdesc A robust event emitter that enables inter-component communication through a publish-subscribe pattern.
4
+ * Components can emit events and listen for events from other components, facilitating loose coupling
5
+ * and reactive updates across the application.
6
+ * Events are handled synchronously in the order they were registered, with proper cleanup
7
+ * of unsubscribed handlers.
8
+ * Event names should follow the format 'namespace:action' (e.g., 'user:login', 'cart:update').
3
9
  *
4
- * Implements a basic publish-subscribe pattern for event handling,
5
- * allowing components to communicate through custom events.
10
+ * @example
11
+ * const emitter = new Emitter();
12
+ * emitter.on('user:login', (user) => console.log(`User logged in: ${user.name}`));
13
+ * emitter.emit('user:login', { name: 'John' }); // Logs: "User logged in: John"
6
14
  */
7
15
  export class Emitter {
8
- /** @type {Object.<string, Function[]>} */
9
- events: {
10
- [x: string]: Function[];
11
- };
16
+ /** @private {Map<string, Set<(data: unknown) => void>>} Map of event names to their registered handler functions */
17
+ private _events;
12
18
  /**
13
- * Registers an event handler for the specified event.
19
+ * Registers an event handler for the specified event name.
20
+ * The handler will be called with the event data when the event is emitted.
21
+ * Event names should follow the format 'namespace:action' for consistency.
14
22
  *
15
- * @param {string} event - The name of the event.
16
- * @param {Function} handler - The function to call when the event is emitted.
23
+ * @public
24
+ * @param {string} event - The name of the event to listen for (e.g., 'user:login').
25
+ * @param {(data: unknown) => void} handler - The callback function to invoke when the event occurs.
26
+ * @returns {() => void} A function to unsubscribe the event handler.
27
+ * @example
28
+ * const unsubscribe = emitter.on('user:login', (user) => console.log(user));
29
+ * // Later...
30
+ * unsubscribe(); // Stops listening for the event
17
31
  */
18
- on(event: string, handler: Function): void;
32
+ public on(event: string, handler: (data: unknown) => void): () => void;
19
33
  /**
20
- * Removes a previously registered event handler.
34
+ * Removes an event handler for the specified event name.
35
+ * If no handler is provided, all handlers for the event are removed.
36
+ * Automatically cleans up empty event sets to prevent memory leaks.
21
37
  *
22
- * @param {string} event - The name of the event.
23
- * @param {Function} handler - The handler function to remove.
38
+ * @public
39
+ * @param {string} event - The name of the event to remove handlers from.
40
+ * @param {(data: unknown) => void} [handler] - The specific handler function to remove.
41
+ * @returns {void}
42
+ * @example
43
+ * // Remove a specific handler
44
+ * emitter.off('user:login', loginHandler);
45
+ * // Remove all handlers for an event
46
+ * emitter.off('user:login');
24
47
  */
25
- off(event: string, handler: Function): void;
48
+ public off(event: string, handler?: (data: unknown) => void): void;
26
49
  /**
27
- * Emits an event, invoking all handlers registered for that event.
50
+ * Emits an event with the specified data to all registered handlers.
51
+ * Handlers are called synchronously in the order they were registered.
52
+ * If no handlers are registered for the event, the emission is silently ignored.
28
53
  *
29
- * @param {string} event - The event name.
30
- * @param {...*} args - Additional arguments to pass to the event handlers.
54
+ * @public
55
+ * @param {string} event - The name of the event to emit.
56
+ * @param {...unknown} args - Optional arguments to pass to the event handlers.
57
+ * @returns {void}
58
+ * @example
59
+ * // Emit an event with data
60
+ * emitter.emit('user:login', { name: 'John', role: 'admin' });
61
+ * // Emit an event with multiple arguments
62
+ * emitter.emit('cart:update', { items: [] }, { total: 0 });
31
63
  */
32
- emit(event: string, ...args: any[]): void;
64
+ public emit(event: string, ...args: unknown[]): void;
33
65
  }
34
66
  //# sourceMappingURL=Emitter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Emitter.d.ts","sourceRoot":"","sources":["../../src/modules/Emitter.js"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH;IAKI,0CAA0C;IAC1C;;MAAgB;IAGlB;;;;;OAKG;IACH,UAHW,MAAM,2BAKhB;IAED;;;;;OAKG;IACH,WAHW,MAAM,2BAOhB;IAED;;;;;OAKG;IACH,YAHW,MAAM,WACH,GAAC,EAAA,QAId;CACF"}
1
+ {"version":3,"file":"Emitter.d.ts","sourceRoot":"","sources":["../../src/modules/Emitter.js"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AACH;IAOI,oHAAoH;IACpH,gBAAwB;IAG1B;;;;;;;;;;;;;OAaG;IACH,iBARW,MAAM,WACN,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,GACrB,MAAM,IAAI,CAWtB;IAED;;;;;;;;;;;;;;OAcG;IACH,kBATW,MAAM,YACN,CAAC,IAAI,EAAE,OAAO,KAAK,IAAI,GACrB,IAAI,CAiBhB;IAED;;;;;;;;;;;;;;OAcG;IACH,mBATW,MAAM,WACH,OAAO,EAAA,GACR,IAAI,CAUhB;CACF"}