eleva 1.0.1 → 1.1.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.
Files changed (97) hide show
  1. package/README.md +21 -10
  2. package/dist/{eleva-plugins.cjs.js → eleva-plugins.cjs} +1002 -292
  3. package/dist/eleva-plugins.cjs.map +1 -0
  4. package/dist/eleva-plugins.d.cts +1352 -0
  5. package/dist/eleva-plugins.d.cts.map +1 -0
  6. package/dist/eleva-plugins.d.ts +1352 -0
  7. package/dist/eleva-plugins.d.ts.map +1 -0
  8. package/dist/{eleva-plugins.esm.js → eleva-plugins.js} +1002 -292
  9. package/dist/eleva-plugins.js.map +1 -0
  10. package/dist/eleva-plugins.umd.js +1001 -291
  11. package/dist/eleva-plugins.umd.js.map +1 -1
  12. package/dist/eleva-plugins.umd.min.js +1 -1
  13. package/dist/eleva-plugins.umd.min.js.map +1 -1
  14. package/dist/{eleva.cjs.js → eleva.cjs} +421 -191
  15. package/dist/eleva.cjs.map +1 -0
  16. package/dist/eleva.d.cts +1329 -0
  17. package/dist/eleva.d.cts.map +1 -0
  18. package/dist/eleva.d.ts +473 -226
  19. package/dist/eleva.d.ts.map +1 -0
  20. package/dist/{eleva.esm.js → eleva.js} +422 -192
  21. package/dist/eleva.js.map +1 -0
  22. package/dist/eleva.umd.js +420 -190
  23. package/dist/eleva.umd.js.map +1 -1
  24. package/dist/eleva.umd.min.js +1 -1
  25. package/dist/eleva.umd.min.js.map +1 -1
  26. package/dist/plugins/attr.cjs +279 -0
  27. package/dist/plugins/attr.cjs.map +1 -0
  28. package/dist/plugins/attr.d.cts +101 -0
  29. package/dist/plugins/attr.d.cts.map +1 -0
  30. package/dist/plugins/attr.d.ts +101 -0
  31. package/dist/plugins/attr.d.ts.map +1 -0
  32. package/dist/plugins/attr.js +276 -0
  33. package/dist/plugins/attr.js.map +1 -0
  34. package/dist/plugins/attr.umd.js +111 -22
  35. package/dist/plugins/attr.umd.js.map +1 -1
  36. package/dist/plugins/attr.umd.min.js +1 -1
  37. package/dist/plugins/attr.umd.min.js.map +1 -1
  38. package/dist/plugins/router.cjs +1873 -0
  39. package/dist/plugins/router.cjs.map +1 -0
  40. package/dist/plugins/router.d.cts +1296 -0
  41. package/dist/plugins/router.d.cts.map +1 -0
  42. package/dist/plugins/router.d.ts +1296 -0
  43. package/dist/plugins/router.d.ts.map +1 -0
  44. package/dist/plugins/router.js +1870 -0
  45. package/dist/plugins/router.js.map +1 -0
  46. package/dist/plugins/router.umd.js +482 -186
  47. package/dist/plugins/router.umd.js.map +1 -1
  48. package/dist/plugins/router.umd.min.js +1 -1
  49. package/dist/plugins/router.umd.min.js.map +1 -1
  50. package/dist/plugins/store.cjs +920 -0
  51. package/dist/plugins/store.cjs.map +1 -0
  52. package/dist/plugins/store.d.cts +266 -0
  53. package/dist/plugins/store.d.cts.map +1 -0
  54. package/dist/plugins/store.d.ts +266 -0
  55. package/dist/plugins/store.d.ts.map +1 -0
  56. package/dist/plugins/store.js +917 -0
  57. package/dist/plugins/store.js.map +1 -0
  58. package/dist/plugins/store.umd.js +410 -85
  59. package/dist/plugins/store.umd.js.map +1 -1
  60. package/dist/plugins/store.umd.min.js +1 -1
  61. package/dist/plugins/store.umd.min.js.map +1 -1
  62. package/package.json +112 -68
  63. package/src/core/Eleva.js +195 -115
  64. package/src/index.cjs +10 -0
  65. package/src/index.js +11 -0
  66. package/src/modules/Emitter.js +68 -20
  67. package/src/modules/Renderer.js +82 -20
  68. package/src/modules/Signal.js +43 -15
  69. package/src/modules/TemplateEngine.js +50 -9
  70. package/src/plugins/Attr.js +121 -19
  71. package/src/plugins/Router.js +526 -181
  72. package/src/plugins/Store.js +448 -69
  73. package/src/plugins/index.js +1 -0
  74. package/types/core/Eleva.d.ts +263 -169
  75. package/types/core/Eleva.d.ts.map +1 -1
  76. package/types/index.d.cts +3 -0
  77. package/types/index.d.cts.map +1 -0
  78. package/types/index.d.ts +5 -0
  79. package/types/index.d.ts.map +1 -1
  80. package/types/modules/Emitter.d.ts +73 -30
  81. package/types/modules/Emitter.d.ts.map +1 -1
  82. package/types/modules/Renderer.d.ts +48 -18
  83. package/types/modules/Renderer.d.ts.map +1 -1
  84. package/types/modules/Signal.d.ts +44 -16
  85. package/types/modules/Signal.d.ts.map +1 -1
  86. package/types/modules/TemplateEngine.d.ts +46 -11
  87. package/types/modules/TemplateEngine.d.ts.map +1 -1
  88. package/types/plugins/Attr.d.ts +83 -16
  89. package/types/plugins/Attr.d.ts.map +1 -1
  90. package/types/plugins/Router.d.ts +498 -207
  91. package/types/plugins/Router.d.ts.map +1 -1
  92. package/types/plugins/Store.d.ts +211 -37
  93. package/types/plugins/Store.d.ts.map +1 -1
  94. package/dist/eleva-plugins.cjs.js.map +0 -1
  95. package/dist/eleva-plugins.esm.js.map +0 -1
  96. package/dist/eleva.cjs.js.map +0 -1
  97. package/dist/eleva.esm.js.map +0 -1
@@ -0,0 +1,917 @@
1
+ /*! Eleva Store Plugin v1.1.0 | MIT License | https://elevajs.com */
2
+ /**
3
+ * @module eleva/plugins/store
4
+ * @fileoverview Reactive state management plugin with namespaced modules,
5
+ * persistence, and subscription system.
6
+ */ // ============================================================================
7
+ // TYPE DEFINITIONS
8
+ // ============================================================================
9
+ // -----------------------------------------------------------------------------
10
+ // External Type Imports
11
+ // -----------------------------------------------------------------------------
12
+ /**
13
+ * Type imports from the Eleva core library.
14
+ * @typedef {import('eleva').Eleva} Eleva
15
+ * @typedef {import('eleva').ComponentDefinition} ComponentDefinition
16
+ * @typedef {import('eleva').ComponentContext} ComponentContext
17
+ * @typedef {import('eleva').SetupResult} SetupResult
18
+ * @typedef {import('eleva').ComponentProps} ComponentProps
19
+ * @typedef {import('eleva').ChildrenMap} ChildrenMap
20
+ * @typedef {import('eleva').MountResult} MountResult
21
+ */ /**
22
+ * Generic type import.
23
+ * @template T
24
+ * @typedef {import('eleva').Signal<T>} Signal
25
+ */ // -----------------------------------------------------------------------------
26
+ // Store Type Definitions
27
+ // -----------------------------------------------------------------------------
28
+ /**
29
+ * Mutation record emitted to subscribers.
30
+ * @typedef {Object} StoreMutation
31
+ * @property {string} type
32
+ * The action name that was dispatched.
33
+ * @property {unknown} payload
34
+ * The payload passed to the action.
35
+ * @property {number} timestamp
36
+ * Unix timestamp of when the mutation occurred.
37
+ * @description Record passed to subscribers when state changes via dispatch.
38
+ * @example
39
+ * store.subscribe((mutation, state) => {
40
+ * console.log(`Action: ${mutation.type}`);
41
+ * console.log(`Payload: ${mutation.payload}`);
42
+ * console.log(`Time: ${new Date(mutation.timestamp)}`);
43
+ * });
44
+ */ /**
45
+ * Store configuration options.
46
+ * @typedef {Object} StoreOptions
47
+ * @property {Record<string, unknown>} [state]
48
+ * Initial state object.
49
+ * @property {Record<string, ActionFunction>} [actions]
50
+ * Action functions for state mutations.
51
+ * @property {Record<string, StoreModule>} [namespaces]
52
+ * Namespaced modules for organizing store.
53
+ * @property {StorePersistenceOptions} [persistence]
54
+ * Persistence configuration.
55
+ * @property {boolean} [devTools]
56
+ * Enable development tools integration.
57
+ * @property {StoreErrorHandler} [onError]
58
+ * Error handler function.
59
+ * @description Configuration options passed to StorePlugin.install().
60
+ * @example
61
+ * app.use(StorePlugin, {
62
+ * state: { count: 0, user: null },
63
+ * actions: {
64
+ * increment: (state) => state.count.value++,
65
+ * setUser: (state, user) => state.user.value = user
66
+ * },
67
+ * persistence: { enabled: true, key: 'my-app' }
68
+ * });
69
+ */ /**
70
+ * Namespaced store module definition.
71
+ * @typedef {Object} StoreModule
72
+ * @property {Record<string, unknown>} state
73
+ * Module state.
74
+ * @property {Record<string, ActionFunction>} [actions]
75
+ * Module actions.
76
+ * @description Defines a namespaced module for organizing related state and actions.
77
+ * @example
78
+ * // Define a module
79
+ * const authModule = {
80
+ * state: { user: null, token: null },
81
+ * actions: {
82
+ * login: (state, { user, token }) => {
83
+ * state.auth.user.value = user;
84
+ * state.auth.token.value = token;
85
+ * }
86
+ * }
87
+ * };
88
+ *
89
+ * // Register dynamically
90
+ * store.registerModule('auth', authModule);
91
+ */ /**
92
+ * Store persistence configuration.
93
+ * @typedef {Object} StorePersistenceOptions
94
+ * @property {boolean} [enabled]
95
+ * Enable state persistence.
96
+ * @property {string} [key]
97
+ * Storage key (default: "eleva-store").
98
+ * @property {'localStorage' | 'sessionStorage'} [storage]
99
+ * Storage type.
100
+ * @property {string[]} [include]
101
+ * Dot-path prefixes to persist (e.g., "auth.user").
102
+ * @property {string[]} [exclude]
103
+ * Dot-path prefixes to exclude.
104
+ * @description Configuration for persisting store state to localStorage or sessionStorage.
105
+ * @example
106
+ * // Persist only specific state paths
107
+ * persistence: {
108
+ * enabled: true,
109
+ * key: 'my-app-store',
110
+ * storage: 'localStorage',
111
+ * include: ['user', 'settings.theme']
112
+ * }
113
+ *
114
+ * @example
115
+ * // Exclude sensitive data
116
+ * persistence: {
117
+ * enabled: true,
118
+ * exclude: ['auth.token', 'temp']
119
+ * }
120
+ */ /**
121
+ * Store error handler callback.
122
+ * @typedef {(error: Error, context: string) => void} StoreErrorHandler
123
+ * @description Custom error handler for store operations.
124
+ * @example
125
+ * app.use(StorePlugin, {
126
+ * onError: (error, context) => {
127
+ * console.error(`Store error in ${context}:`, error);
128
+ * // Send to error tracking service
129
+ * errorTracker.capture(error, { context });
130
+ * }
131
+ * });
132
+ */ /**
133
+ * Reactive state tree containing signals and nested namespaces.
134
+ * @typedef {Record<string, Signal<unknown> | Record<string, unknown>>} StoreState
135
+ * @description Represents the store's reactive state structure with support for nested modules.
136
+ */ /**
137
+ * Action function signature for store actions.
138
+ * @typedef {(state: StoreState, payload?: unknown) => unknown} ActionFunction
139
+ * @description Function that receives state and optional payload, returns action result.
140
+ */ /**
141
+ * Dispatch function signature for triggering actions.
142
+ * @typedef {(actionName: string, payload?: unknown) => Promise<unknown>} DispatchFunction
143
+ * @description Dispatches an action by name with optional payload, returns action result.
144
+ */ /**
145
+ * Subscribe callback signature for mutation listeners.
146
+ * @typedef {(mutation: StoreMutation, state: StoreState) => void} SubscribeCallback
147
+ * @description Called after each successful action dispatch with mutation details and current state.
148
+ */ /**
149
+ * Store API exposed to components via ctx.store.
150
+ * @typedef {Object} StoreApi
151
+ * @property {StoreState} state
152
+ * Reactive state signals (supports nested modules).
153
+ * @property {DispatchFunction} dispatch
154
+ * Dispatch an action by name with optional payload.
155
+ * @property {(callback: SubscribeCallback) => () => void} subscribe
156
+ * Subscribe to state mutations. Returns unsubscribe function.
157
+ * @property {() => Record<string, unknown>} getState
158
+ * Get a snapshot of current state values.
159
+ * @property {(namespace: string, module: StoreModule) => void} registerModule
160
+ * Register a namespaced module dynamically.
161
+ * @property {(namespace: string) => void} unregisterModule
162
+ * Unregister a namespaced module.
163
+ * @property {(key: string, initialValue: unknown) => Signal<unknown>} createState
164
+ * Create a new state signal dynamically.
165
+ * @property {(name: string, actionFn: ActionFunction) => void} createAction
166
+ * Register a new action dynamically.
167
+ * @property {new <T>(value: T) => Signal<T>} signal
168
+ * Signal class constructor for manual state creation.
169
+ * @description The store API injected into component setup as `ctx.store`.
170
+ * @example
171
+ * app.component('Counter', {
172
+ * setup({ store }) {
173
+ * // Access reactive state
174
+ * const count = store.state.count;
175
+ *
176
+ * // Dispatch actions
177
+ * const increment = () => store.dispatch('increment');
178
+ *
179
+ * // Subscribe to changes
180
+ * const unsub = store.subscribe((mutation) => {
181
+ * console.log('State changed:', mutation.type);
182
+ * });
183
+ *
184
+ * return { count, increment, onUnmount: () => unsub() };
185
+ * },
186
+ * template: (ctx) => `<button @click="increment">${ctx.count.value}</button>`
187
+ * });
188
+ * @see StoreMutation - Mutation record structure.
189
+ * @see StoreModule - Module definition for namespaces.
190
+ */ /**
191
+ * @class 🏪 StorePlugin
192
+ * @classdesc A powerful reactive state management plugin for Eleva that enables sharing
193
+ * reactive data across the entire application. The Store plugin provides a centralized,
194
+ * reactive data store that can be accessed from any component's setup function.
195
+ *
196
+ * Core Features:
197
+ * - Centralized reactive state management using Eleva's signal system
198
+ * - Global state accessibility through component setup functions
199
+ * - Namespace support for organizing store modules
200
+ * - Built-in persistence with localStorage/sessionStorage support
201
+ * - Action-based state mutations with validation
202
+ * - Subscription system for reactive updates
203
+ * - DevTools integration for debugging
204
+ * - Plugin architecture for extensibility
205
+ *
206
+ * @example
207
+ * // Install the plugin
208
+ * const app = new Eleva("myApp");
209
+ * app.use(StorePlugin, {
210
+ * state: {
211
+ * user: { name: "John", email: "john@example.com" },
212
+ * counter: 0,
213
+ * todos: []
214
+ * },
215
+ * actions: {
216
+ * increment: (state) => state.counter.value++,
217
+ * addTodo: (state, todo) => state.todos.value = [...state.todos.value, todo],
218
+ * setUser: (state, user) => state.user.value = user
219
+ * },
220
+ * persistence: {
221
+ * enabled: true,
222
+ * key: "myApp-store",
223
+ * storage: "localStorage"
224
+ * }
225
+ * });
226
+ *
227
+ * // Use store in components
228
+ * app.component("Counter", {
229
+ * setup({ store }) {
230
+ * return {
231
+ * count: store.state.counter,
232
+ * increment: () => store.dispatch("increment"),
233
+ * user: store.state.user
234
+ * };
235
+ * },
236
+ * template: (ctx) => `
237
+ * <div>
238
+ * <p>Hello ${ctx.user.value.name}!</p>
239
+ * <p>Count: ${ctx.count.value}</p>
240
+ * <button @click="increment">+</button>
241
+ * </div>
242
+ * `
243
+ * });
244
+ */ const StorePlugin = {
245
+ /**
246
+ * Unique identifier for the plugin
247
+ * @type {string}
248
+ */ name: "store",
249
+ /**
250
+ * Plugin version
251
+ * @type {string}
252
+ */ version: "1.1.0",
253
+ /**
254
+ * Plugin description
255
+ * @type {string}
256
+ */ description: "Reactive state management for sharing data across the entire Eleva application",
257
+ /**
258
+ * Installs the plugin into the Eleva instance.
259
+ *
260
+ * @public
261
+ * @param {Eleva} eleva - The Eleva instance.
262
+ * @param {StoreOptions} options - Plugin configuration options.
263
+ * @param {Record<string, unknown>} [options.state={}] - Initial state object.
264
+ * @param {Record<string, ActionFunction>} [options.actions={}] - Action functions for state mutations.
265
+ * @param {Record<string, StoreModule>} [options.namespaces={}] - Namespaced modules for organizing store.
266
+ * @param {StorePersistenceOptions} [options.persistence] - Persistence configuration.
267
+ * @param {boolean} [options.persistence.enabled=false] - Enable state persistence.
268
+ * @param {string} [options.persistence.key="eleva-store"] - Storage key.
269
+ * @param {'localStorage' | 'sessionStorage'} [options.persistence.storage="localStorage"] - Storage type.
270
+ * @param {string[]} [options.persistence.include] - Dot-path prefixes to persist (e.g., "auth.user")
271
+ * @param {string[]} [options.persistence.exclude] - Dot-path prefixes to exclude (applies when include is empty).
272
+ * @param {boolean} [options.devTools=false] - Enable development tools integration.
273
+ * @param {(error: Error, context: string) => void} [options.onError=null] - Error handler function.
274
+ * @returns {void}
275
+ * @description
276
+ * Installs the store and injects `store` into component setup context by wrapping
277
+ * `eleva.mount` and `eleva._mountComponents`. Also exposes `eleva.store` and
278
+ * helper methods (`eleva.dispatch`, `eleva.getState`, `eleva.subscribe`, `eleva.createAction`).
279
+ * Uninstall restores the originals.
280
+ *
281
+ * @example
282
+ * // Basic installation
283
+ * app.use(StorePlugin, {
284
+ * state: { count: 0, user: null },
285
+ * actions: {
286
+ * increment: (state) => state.count.value++,
287
+ * setUser: (state, user) => state.user.value = user
288
+ * }
289
+ * });
290
+ *
291
+ * // Advanced installation with persistence and namespaces
292
+ * app.use(StorePlugin, {
293
+ * state: { theme: "light" },
294
+ * namespaces: {
295
+ * auth: {
296
+ * state: { user: null, token: null },
297
+ * actions: {
298
+ * login: (state, { user, token }) => {
299
+ * state.auth.user.value = user;
300
+ * state.auth.token.value = token;
301
+ * },
302
+ * logout: (state) => {
303
+ * state.auth.user.value = null;
304
+ * state.auth.token.value = null;
305
+ * }
306
+ * }
307
+ * }
308
+ * },
309
+ * persistence: {
310
+ * enabled: true,
311
+ * include: ["theme", "auth.user"]
312
+ * }
313
+ * });
314
+ */ install (eleva, options = {}) {
315
+ const { state = {}, actions = {}, namespaces = {}, persistence = {}, devTools = false, onError = null } = options;
316
+ /**
317
+ * @class Store
318
+ * @classdesc Store instance that manages all state and provides the API.
319
+ * @private
320
+ */ class Store {
321
+ /**
322
+ * Initializes the root state and actions.
323
+ * Creates reactive signals for each state property and copies actions.
324
+ *
325
+ * @private
326
+ * @param {Record<string, unknown>} initialState - The initial state key-value pairs.
327
+ * @param {Record<string, ActionFunction>} initialActions - The action functions to register.
328
+ * @returns {void}
329
+ */ _initializeState(initialState, initialActions) {
330
+ // Create reactive signals for each state property
331
+ Object.entries(initialState).forEach(([key, value])=>{
332
+ this.state[key] = new eleva.signal(value);
333
+ });
334
+ // Set up actions
335
+ this.actions = {
336
+ ...initialActions
337
+ };
338
+ }
339
+ /**
340
+ * Initializes namespaced modules.
341
+ * Creates namespace objects and populates them with state signals and actions.
342
+ *
343
+ * @private
344
+ * @param {Record<string, StoreModule>} namespaces - Map of namespace names to module definitions.
345
+ * @returns {void}
346
+ */ _initializeNamespaces(namespaces) {
347
+ Object.entries(namespaces).forEach(([namespace, module])=>{
348
+ const { state: moduleState = {}, actions: moduleActions = {} } = module;
349
+ // Create namespace object if it doesn't exist
350
+ if (!this.state[namespace]) {
351
+ this.state[namespace] = {};
352
+ }
353
+ if (!this.actions[namespace]) {
354
+ this.actions[namespace] = {};
355
+ }
356
+ // Initialize namespaced state
357
+ Object.entries(moduleState).forEach(([key, value])=>{
358
+ this.state[namespace][key] = new eleva.signal(value);
359
+ });
360
+ // Set up namespaced actions
361
+ this.actions[namespace] = {
362
+ ...moduleActions
363
+ };
364
+ });
365
+ }
366
+ /**
367
+ * Loads persisted state from storage.
368
+ * Reads from localStorage/sessionStorage and applies values to state signals.
369
+ * Does nothing if persistence is disabled or running in SSR environment.
370
+ *
371
+ * @private
372
+ * @returns {void}
373
+ */ _loadPersistedState() {
374
+ if (!this.persistence.enabled || typeof window === "undefined") {
375
+ return;
376
+ }
377
+ try {
378
+ const storage = window[this.persistence.storage];
379
+ const persistedData = storage.getItem(this.persistence.key);
380
+ if (persistedData) {
381
+ const data = JSON.parse(persistedData);
382
+ this._applyPersistedData(data);
383
+ }
384
+ } catch (error) {
385
+ if (this.onError) {
386
+ this.onError(error, "Failed to load persisted state");
387
+ } else {
388
+ console.warn("[StorePlugin] Failed to load persisted state:", error);
389
+ }
390
+ }
391
+ }
392
+ /**
393
+ * Applies persisted data to the current state.
394
+ * Recursively updates signal values for paths that should be persisted.
395
+ *
396
+ * @private
397
+ * @param {Record<string, unknown>} data - The persisted data object to apply.
398
+ * @param {Record<string, unknown>} [currentState=this.state] - The current state object to update.
399
+ * @param {string} [path=""] - The current dot-notation path (for include/exclude filtering).
400
+ * @returns {void}
401
+ */ _applyPersistedData(data, currentState = this.state, path = "") {
402
+ Object.entries(data).forEach(([key, value])=>{
403
+ const fullPath = path ? `${path}.${key}` : key;
404
+ if (this._shouldPersist(fullPath)) {
405
+ if (currentState[key] && typeof currentState[key] === "object" && "value" in currentState[key]) {
406
+ // This is a signal, update its value
407
+ currentState[key].value = value;
408
+ } else if (typeof value === "object" && value !== null && currentState[key]) {
409
+ // This is a nested object, recurse
410
+ this._applyPersistedData(value, currentState[key], fullPath);
411
+ }
412
+ }
413
+ });
414
+ }
415
+ /**
416
+ * Determines if a state path should be persisted.
417
+ * Checks against include/exclude filters configured in persistence options.
418
+ *
419
+ * @private
420
+ * @param {string} path - The dot-notation path to check (e.g., "auth.user").
421
+ * @returns {boolean} True if the path should be persisted, false otherwise.
422
+ */ _shouldPersist(path) {
423
+ const { include, exclude } = this.persistence;
424
+ if (include && include.length > 0) {
425
+ return include.some((includePath)=>path.startsWith(includePath));
426
+ }
427
+ if (exclude && exclude.length > 0) {
428
+ return !exclude.some((excludePath)=>path.startsWith(excludePath));
429
+ }
430
+ return true;
431
+ }
432
+ /**
433
+ * Saves current state to storage.
434
+ * Extracts persistable data and writes to localStorage/sessionStorage.
435
+ * Does nothing if persistence is disabled or running in SSR environment.
436
+ *
437
+ * @private
438
+ * @returns {void}
439
+ */ _saveState() {
440
+ if (!this.persistence.enabled || typeof window === "undefined") {
441
+ return;
442
+ }
443
+ try {
444
+ const storage = window[this.persistence.storage];
445
+ const dataToSave = this._extractPersistedData();
446
+ storage.setItem(this.persistence.key, JSON.stringify(dataToSave));
447
+ } catch (error) {
448
+ if (this.onError) {
449
+ this.onError(error, "Failed to save state");
450
+ } else {
451
+ console.warn("[StorePlugin] Failed to save state:", error);
452
+ }
453
+ }
454
+ }
455
+ /**
456
+ * Extracts data that should be persisted.
457
+ * Recursively extracts signal values for paths that pass persistence filters.
458
+ *
459
+ * @private
460
+ * @param {Record<string, unknown>} [currentState=this.state] - The state object to extract from.
461
+ * @param {string} [path=""] - The current dot-notation path (for include/exclude filtering).
462
+ * @returns {Record<string, unknown>} The extracted data object with raw values (not signals).
463
+ */ _extractPersistedData(currentState = this.state, path = "") {
464
+ const result = {};
465
+ Object.entries(currentState).forEach(([key, value])=>{
466
+ const fullPath = path ? `${path}.${key}` : key;
467
+ if (this._shouldPersist(fullPath)) {
468
+ if (value && typeof value === "object" && "value" in value) {
469
+ // This is a signal, extract its value
470
+ result[key] = value.value;
471
+ } else if (typeof value === "object" && value !== null) {
472
+ // This is a nested object, recurse
473
+ const nestedData = this._extractPersistedData(value, fullPath);
474
+ if (Object.keys(nestedData).length > 0) {
475
+ result[key] = nestedData;
476
+ }
477
+ }
478
+ }
479
+ });
480
+ return result;
481
+ }
482
+ /**
483
+ * Sets up development tools integration.
484
+ * Registers the store with Eleva DevTools if available and enabled.
485
+ * Does nothing if devTools is disabled, running in SSR, or DevTools not installed.
486
+ *
487
+ * @private
488
+ * @returns {void}
489
+ */ _setupDevTools() {
490
+ if (!this.devTools || typeof window === "undefined" || !window.__ELEVA_DEVTOOLS__) {
491
+ return;
492
+ }
493
+ window.__ELEVA_DEVTOOLS__.registerStore(this);
494
+ }
495
+ /**
496
+ * Dispatches an action to mutate the state.
497
+ *
498
+ * Execution flow:
499
+ * 1. Retrieves the action function (supports namespaced actions like "auth.login")
500
+ * 2. Records mutation for devtools/history (keeps last 100 mutations)
501
+ * 3. Executes action with await (actions can be sync or async)
502
+ * 4. Saves state if persistence is enabled
503
+ * 5. Notifies all subscribers with (mutation, state)
504
+ * 6. Notifies devtools if enabled
505
+ *
506
+ * @note Always returns a Promise regardless of whether the action is sync or async.
507
+ * Subscriber callbacks that throw are caught and passed to onError handler.
508
+ *
509
+ * @async
510
+ * @param {string} actionName - The name of the action to dispatch (supports dot notation for namespaces).
511
+ * @param {unknown} payload - The payload to pass to the action.
512
+ * @returns {Promise<unknown>} The result of the action (undefined if action returns nothing).
513
+ * @throws {Error} If action is not found or action function throws.
514
+ * @see subscribe - Listen for mutations triggered by dispatch.
515
+ * @see getState - Get current state values.
516
+ */ async dispatch(actionName, payload) {
517
+ try {
518
+ const action = this._getAction(actionName);
519
+ if (!action) {
520
+ const error = new Error(`Action "${actionName}" not found`);
521
+ if (this.onError) {
522
+ this.onError(error, actionName);
523
+ }
524
+ throw error;
525
+ }
526
+ const mutation = {
527
+ type: actionName,
528
+ payload,
529
+ timestamp: Date.now()
530
+ };
531
+ // Record mutation for devtools
532
+ this.mutations.push(mutation);
533
+ if (this.mutations.length > 100) {
534
+ this.mutations.shift(); // Keep only last 100 mutations
535
+ }
536
+ // Execute the action
537
+ const result = await action.call(null, this.state, payload);
538
+ // Save state if persistence is enabled
539
+ this._saveState();
540
+ // Notify subscribers
541
+ this.subscribers.forEach((callback)=>{
542
+ try {
543
+ callback(mutation, this.state);
544
+ } catch (error) {
545
+ if (this.onError) {
546
+ this.onError(error, "Subscriber callback failed");
547
+ }
548
+ }
549
+ });
550
+ // Notify devtools
551
+ if (this.devTools && typeof window !== "undefined" && window.__ELEVA_DEVTOOLS__) {
552
+ window.__ELEVA_DEVTOOLS__.notifyMutation(mutation, this.state);
553
+ }
554
+ return result;
555
+ } catch (error) {
556
+ if (this.onError) {
557
+ this.onError(error, `Action dispatch failed: ${actionName}`);
558
+ }
559
+ throw error;
560
+ }
561
+ }
562
+ /**
563
+ * Gets an action by name (supports namespaced actions).
564
+ * Traverses the actions object using dot-notation path segments.
565
+ *
566
+ * @private
567
+ * @param {string} actionName - The action name, supports dot notation for namespaces (e.g., "auth.login").
568
+ * @returns {ActionFunction | null} The action function if found and is a function, null otherwise.
569
+ */ _getAction(actionName) {
570
+ const parts = actionName.split(".");
571
+ let current = this.actions;
572
+ for (const part of parts){
573
+ if (current[part] === undefined) {
574
+ return null;
575
+ }
576
+ current = current[part];
577
+ }
578
+ return typeof current === "function" ? current : null;
579
+ }
580
+ /**
581
+ * Subscribes to store mutations.
582
+ * Callback is invoked after every successful action dispatch.
583
+ *
584
+ * @param {SubscribeCallback} callback
585
+ * Called after each mutation with:
586
+ * - mutation.type: The action name that was dispatched
587
+ * - mutation.payload: The payload passed to the action
588
+ * - mutation.timestamp: When the mutation occurred (Date.now())
589
+ * - state: The current state object (contains Signals)
590
+ * @returns {() => void} Unsubscribe function. Call to stop receiving notifications.
591
+ * @throws {Error} If callback is not a function.
592
+ * @see dispatch - Triggers mutations that notify subscribers.
593
+ */ subscribe(callback) {
594
+ if (typeof callback !== "function") {
595
+ throw new Error("Subscribe callback must be a function");
596
+ }
597
+ this.subscribers.add(callback);
598
+ // Return unsubscribe function
599
+ return ()=>{
600
+ this.subscribers.delete(callback);
601
+ };
602
+ }
603
+ /**
604
+ * Gets current state values (not signals).
605
+ *
606
+ * @note When persistence include/exclude filters are configured,
607
+ * this returns only the filtered subset of state.
608
+ * @returns {Record<string, unknown>} The current state values (filtered by persistence config if set).
609
+ * @see replaceState - Set state values.
610
+ * @see subscribe - Listen for state changes.
611
+ */ getState() {
612
+ return this._extractPersistedData();
613
+ }
614
+ /**
615
+ * Replaces state values (useful for testing or state hydration).
616
+ *
617
+ * @note When persistence include/exclude filters are configured,
618
+ * this only updates the filtered subset of state.
619
+ * @param {Record<string, unknown>} newState - The new state object.
620
+ * @returns {void}
621
+ * @see getState - Get current state values.
622
+ */ replaceState(newState) {
623
+ this._applyPersistedData(newState);
624
+ this._saveState();
625
+ }
626
+ /**
627
+ * Clears persisted state from storage.
628
+ * Does nothing if persistence is disabled or running in SSR.
629
+ * @returns {void}
630
+ */ clearPersistedState() {
631
+ if (!this.persistence.enabled || typeof window === "undefined") {
632
+ return;
633
+ }
634
+ try {
635
+ const storage = window[this.persistence.storage];
636
+ storage.removeItem(this.persistence.key);
637
+ } catch (error) {
638
+ if (this.onError) {
639
+ this.onError(error, "Failed to clear persisted state");
640
+ }
641
+ }
642
+ }
643
+ /**
644
+ * Registers a new namespaced module at runtime.
645
+ * Logs a warning if the namespace already exists.
646
+ * Module state is nested under `state[namespace]` and actions under `actions[namespace]`.
647
+ * @param {string} namespace - The namespace for the module.
648
+ * @param {StoreModule} module - The module definition.
649
+ * @param {Record<string, unknown>} module.state - The module's initial state.
650
+ * @param {Record<string, ActionFunction>} module.actions - The module's actions.
651
+ * @returns {void}
652
+ */ registerModule(namespace, module) {
653
+ if (this.state[namespace] || this.actions[namespace]) {
654
+ console.warn(`[StorePlugin] Module "${namespace}" already exists`);
655
+ return;
656
+ }
657
+ // Initialize the module
658
+ this.state[namespace] = {};
659
+ this.actions[namespace] = {};
660
+ const namespaces = {
661
+ [namespace]: module
662
+ };
663
+ this._initializeNamespaces(namespaces);
664
+ this._saveState();
665
+ }
666
+ /**
667
+ * Unregisters a namespaced module.
668
+ * Logs a warning if the namespace doesn't exist.
669
+ * Removes both state and actions under the namespace.
670
+ * @param {string} namespace - The namespace to unregister.
671
+ * @returns {void}
672
+ */ unregisterModule(namespace) {
673
+ if (!this.state[namespace] && !this.actions[namespace]) {
674
+ console.warn(`[StorePlugin] Module "${namespace}" does not exist`);
675
+ return;
676
+ }
677
+ delete this.state[namespace];
678
+ delete this.actions[namespace];
679
+ this._saveState();
680
+ }
681
+ /**
682
+ * Creates a new reactive state property at runtime.
683
+ *
684
+ * @param {string} key - The state key.
685
+ * @param {*} initialValue - The initial value.
686
+ * @returns {Signal} The created signal, or existing signal if key exists.
687
+ */ createState(key, initialValue) {
688
+ if (this.state[key]) {
689
+ return this.state[key]; // Return existing state
690
+ }
691
+ this.state[key] = new eleva.signal(initialValue);
692
+ this._saveState();
693
+ return this.state[key];
694
+ }
695
+ /**
696
+ * Creates a new action at runtime.
697
+ * Overwrites existing action if name already exists.
698
+ * Supports dot-notation for namespaced actions (e.g., "auth.login").
699
+ * @param {string} name - The action name (supports dot notation for namespaces).
700
+ * @param {ActionFunction} actionFn - The action function (receives state and payload).
701
+ * @returns {void}
702
+ * @throws {Error} If actionFn is not a function.
703
+ * @example
704
+ * // Root-level action
705
+ * store.createAction("increment", (state) => state.count.value++);
706
+ *
707
+ * // Namespaced action
708
+ * store.createAction("auth.login", async (state, credentials) => {
709
+ * // ... login logic
710
+ * });
711
+ */ createAction(name, actionFn) {
712
+ if (typeof actionFn !== "function") {
713
+ throw new Error("Action must be a function");
714
+ }
715
+ // Fast path: no dot means simple action (avoids array allocation)
716
+ if (name.indexOf(".") === -1) {
717
+ this.actions[name] = actionFn;
718
+ return;
719
+ }
720
+ // Namespaced action, traverse/create nested structure
721
+ const parts = name.split(".");
722
+ const lastIndex = parts.length - 1;
723
+ let current = this.actions;
724
+ for(let i = 0; i < lastIndex; i++){
725
+ current = current[parts[i]] || (current[parts[i]] = {});
726
+ }
727
+ current[parts[lastIndex]] = actionFn;
728
+ }
729
+ /**
730
+ * Creates a new Store instance.
731
+ * Initializes state signals, actions, persistence, and devtools integration.
732
+ *
733
+ * @constructor
734
+ */ constructor(){
735
+ /** @type {Record<string, Signal | Record<string, unknown>>} */ this.state = {};
736
+ /** @type {Record<string, ActionFunction | Record<string, ActionFunction>>} */ this.actions = {};
737
+ /** @type {Set<SubscribeCallback>} */ this.subscribers = new Set();
738
+ /** @type {StoreMutation[]} */ this.mutations = [];
739
+ /** @type {{enabled: boolean, key: string, storage: string, include: string[]|null, exclude: string[]|null}} */ this.persistence = {
740
+ enabled: false,
741
+ key: "eleva-store",
742
+ storage: "localStorage",
743
+ include: null,
744
+ exclude: null,
745
+ ...persistence
746
+ };
747
+ /** @type {boolean} */ this.devTools = devTools;
748
+ /** @type {((error: Error, context: string) => void)|null} */ this.onError = onError;
749
+ this._initializeState(state, actions);
750
+ this._initializeNamespaces(namespaces);
751
+ this._loadPersistedState();
752
+ this._setupDevTools();
753
+ }
754
+ }
755
+ // Create the store instance
756
+ const store = new Store();
757
+ // Store the original mount method to override it
758
+ const originalMount = eleva.mount;
759
+ /**
760
+ * Overridden mount method that injects store context into components.
761
+ * Wraps the original mount to add `ctx.store` to the component's setup context.
762
+ *
763
+ * @param {HTMLElement} container - The DOM element where the component will be mounted.
764
+ * @param {string | ComponentDefinition} compName - Component name or definition.
765
+ * @param {ComponentProps} [props={}] - Optional properties to pass to the component.
766
+ * @returns {Promise<MountResult>} The mount result.
767
+ */ eleva.mount = async (container, compName, props = {})=>{
768
+ // Get the component definition
769
+ const componentDef = typeof compName === "string" ? eleva._components.get(compName) || compName : compName;
770
+ if (!componentDef) {
771
+ return await originalMount.call(eleva, container, compName, props);
772
+ }
773
+ // Create a wrapped component that injects store into setup
774
+ const wrappedComponent = {
775
+ ...componentDef,
776
+ async setup (ctx) {
777
+ /** @type {StoreApi} */ ctx.store = {
778
+ // Core store functionality
779
+ state: store.state,
780
+ dispatch: store.dispatch.bind(store),
781
+ subscribe: store.subscribe.bind(store),
782
+ getState: store.getState.bind(store),
783
+ // Module management
784
+ registerModule: store.registerModule.bind(store),
785
+ unregisterModule: store.unregisterModule.bind(store),
786
+ // Utilities for dynamic state/action creation
787
+ createState: store.createState.bind(store),
788
+ createAction: store.createAction.bind(store),
789
+ // Access to signal constructor for manual state creation
790
+ signal: eleva.signal
791
+ };
792
+ // Call original setup if it exists
793
+ const originalSetup = componentDef.setup;
794
+ const result = originalSetup ? await originalSetup(ctx) : {};
795
+ return result;
796
+ }
797
+ };
798
+ // Call original mount with wrapped component
799
+ return await originalMount.call(eleva, container, wrappedComponent, props);
800
+ };
801
+ // Override _mountComponents to ensure child components also get store context
802
+ const originalMountComponents = eleva._mountComponents;
803
+ /**
804
+ * Overridden _mountComponents method that injects store context into child components.
805
+ * Wraps each child component's setup function to add `ctx.store` before mounting.
806
+ *
807
+ * @param {HTMLElement} container - The parent container element.
808
+ * @param {ChildrenMap} children - Map of selectors to component definitions.
809
+ * @param {MountResult[]} childInstances - Array to store mounted instances.
810
+ * @param {ComponentContext & SetupResult} context - Parent component context.
811
+ * @returns {Promise<void>}
812
+ */ eleva._mountComponents = async (container, children, childInstances, context)=>{
813
+ // Create wrapped children with store injection
814
+ const wrappedChildren = {};
815
+ for (const [selector, childComponent] of Object.entries(children)){
816
+ const componentDef = typeof childComponent === "string" ? eleva._components.get(childComponent) || childComponent : childComponent;
817
+ if (componentDef && typeof componentDef === "object") {
818
+ wrappedChildren[selector] = {
819
+ ...componentDef,
820
+ async setup (ctx) {
821
+ /** @type {StoreApi} */ ctx.store = {
822
+ // Core store functionality
823
+ state: store.state,
824
+ dispatch: store.dispatch.bind(store),
825
+ subscribe: store.subscribe.bind(store),
826
+ getState: store.getState.bind(store),
827
+ // Module management
828
+ registerModule: store.registerModule.bind(store),
829
+ unregisterModule: store.unregisterModule.bind(store),
830
+ // Utilities for dynamic state/action creation
831
+ createState: store.createState.bind(store),
832
+ createAction: store.createAction.bind(store),
833
+ // Access to signal constructor for manual state creation
834
+ signal: eleva.signal
835
+ };
836
+ // Call original setup if it exists
837
+ const originalSetup = componentDef.setup;
838
+ const result = originalSetup ? await originalSetup(ctx) : {};
839
+ return result;
840
+ }
841
+ };
842
+ } else {
843
+ wrappedChildren[selector] = childComponent;
844
+ }
845
+ }
846
+ // Call original _mountComponents with wrapped children
847
+ return await originalMountComponents.call(eleva, container, wrappedChildren, childInstances, context);
848
+ };
849
+ // Expose store instance and utilities on the Eleva instance
850
+ /** @type {StoreApi} */ eleva.store = store;
851
+ /**
852
+ * Expose utility methods on the Eleva instance.
853
+ * These are top-level helpers (e.g., `eleva.dispatch`) in addition to `eleva.store`.
854
+ */ /** @type {(name: string, actionFn: ActionFunction) => void} */ eleva.createAction = (name, actionFn)=>{
855
+ store.createAction(name, actionFn);
856
+ };
857
+ /** @type {DispatchFunction} */ eleva.dispatch = (actionName, payload)=>{
858
+ return store.dispatch(actionName, payload);
859
+ };
860
+ /** @type {() => Record<string, unknown>} */ eleva.getState = ()=>{
861
+ return store.getState();
862
+ };
863
+ /** @type {(callback: SubscribeCallback) => () => void} */ eleva.subscribe = (callback)=>{
864
+ return store.subscribe(callback);
865
+ };
866
+ // Store original methods for cleanup
867
+ eleva._originalMount = originalMount;
868
+ eleva._originalMountComponents = originalMountComponents;
869
+ },
870
+ /**
871
+ * Uninstalls the plugin from the Eleva instance.
872
+ *
873
+ * @public
874
+ * @param {Eleva} eleva - The Eleva instance.
875
+ * @returns {void}
876
+ * @description
877
+ * Restores the original Eleva methods and removes all plugin-specific
878
+ * functionality. This method should be called when the plugin is no
879
+ * longer needed.
880
+ * Also removes `eleva.store` and top-level helpers (`eleva.dispatch`,
881
+ * `eleva.getState`, `eleva.subscribe`, `eleva.createAction`).
882
+ *
883
+ * @example
884
+ * // Uninstall the plugin
885
+ * StorePlugin.uninstall(app);
886
+ */ uninstall (eleva) {
887
+ // Restore original mount method
888
+ if (eleva._originalMount) {
889
+ eleva.mount = eleva._originalMount;
890
+ delete eleva._originalMount;
891
+ }
892
+ // Restore original _mountComponents method
893
+ if (eleva._originalMountComponents) {
894
+ eleva._mountComponents = eleva._originalMountComponents;
895
+ delete eleva._originalMountComponents;
896
+ }
897
+ // Remove store instance and utility methods
898
+ if (eleva.store) {
899
+ delete eleva.store;
900
+ }
901
+ if (eleva.createAction) {
902
+ delete eleva.createAction;
903
+ }
904
+ if (eleva.dispatch) {
905
+ delete eleva.dispatch;
906
+ }
907
+ if (eleva.getState) {
908
+ delete eleva.getState;
909
+ }
910
+ if (eleva.subscribe) {
911
+ delete eleva.subscribe;
912
+ }
913
+ }
914
+ };
915
+
916
+ export { StorePlugin as Store, StorePlugin };
917
+ //# sourceMappingURL=store.js.map