@coherent.js/express 1.0.0-beta.2 → 1.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,2371 +1,3 @@
1
- // ../core/src/performance/monitor.js
2
- function createPerformanceMonitor(options = {}) {
3
- const opts = {
4
- enabled: true,
5
- metrics: {
6
- custom: {}
7
- },
8
- sampling: {
9
- enabled: false,
10
- rate: 1,
11
- strategy: "random"
12
- },
13
- reporting: {
14
- enabled: false,
15
- interval: 6e4,
16
- format: "json",
17
- batch: {
18
- enabled: false,
19
- maxSize: 100,
20
- flushInterval: 5e3
21
- },
22
- onReport: null
23
- },
24
- alerts: {
25
- enabled: true,
26
- rules: []
27
- },
28
- resources: {
29
- enabled: false,
30
- track: ["memory"],
31
- interval: 1e3
32
- },
33
- profiling: {
34
- enabled: false,
35
- mode: "production",
36
- flamegraph: false,
37
- tracing: {
38
- enabled: false,
39
- sampleRate: 0.01
40
- }
41
- },
42
- ...options
43
- };
44
- opts.reporting.batch = {
45
- enabled: false,
46
- maxSize: 100,
47
- flushInterval: 5e3,
48
- ...options.reporting?.batch || {}
49
- };
50
- const metrics = {
51
- builtin: {
52
- renderTime: { type: "histogram", unit: "ms", values: [] },
53
- componentCount: { type: "counter", unit: "renders", value: 0 },
54
- errorCount: { type: "counter", unit: "errors", value: 0 },
55
- memoryUsage: { type: "gauge", unit: "MB", values: [] }
56
- },
57
- custom: {}
58
- };
59
- Object.entries(opts.metrics.custom).forEach(([name, config]) => {
60
- metrics.custom[name] = {
61
- type: config.type || "counter",
62
- unit: config.unit || "",
63
- threshold: config.threshold,
64
- values: config.type === "histogram" ? [] : void 0,
65
- value: config.type === "counter" || config.type === "gauge" ? 0 : void 0
66
- };
67
- });
68
- const samplingState = {
69
- count: 0,
70
- sampled: 0,
71
- adaptiveRate: opts.sampling.rate
72
- };
73
- const reportingState = {
74
- batch: [],
75
- lastReport: Date.now(),
76
- reportTimer: null,
77
- flushTimer: null
78
- };
79
- const alertState = {
80
- triggered: /* @__PURE__ */ new Map(),
81
- history: []
82
- };
83
- const resourceState = {
84
- samples: [],
85
- timer: null
86
- };
87
- const profilingState = {
88
- traces: [],
89
- flamegraphData: []
90
- };
91
- const stats = {
92
- metricsRecorded: 0,
93
- sampleRate: opts.sampling.rate,
94
- reportsGenerated: 0,
95
- alertsTriggered: 0
96
- };
97
- function shouldSample() {
98
- if (!opts.sampling.enabled) return true;
99
- samplingState.count++;
100
- if (opts.sampling.strategy === "random") {
101
- return Math.random() < samplingState.adaptiveRate;
102
- } else if (opts.sampling.strategy === "deterministic") {
103
- return samplingState.count % Math.ceil(1 / samplingState.adaptiveRate) === 0;
104
- } else if (opts.sampling.strategy === "adaptive") {
105
- const recentRenderTimes = metrics.builtin.renderTime.values.slice(-10);
106
- if (recentRenderTimes.length > 0) {
107
- const avgTime = recentRenderTimes.reduce((a, b) => a + b, 0) / recentRenderTimes.length;
108
- samplingState.adaptiveRate = avgTime > 16 ? Math.min(1, opts.sampling.rate * 2) : opts.sampling.rate;
109
- }
110
- return Math.random() < samplingState.adaptiveRate;
111
- }
112
- return true;
113
- }
114
- function recordMetric(name, value, metadata = {}) {
115
- if (!opts.enabled) return;
116
- if (!shouldSample()) return;
117
- stats.metricsRecorded++;
118
- const builtinMetric = metrics.builtin[name];
119
- if (builtinMetric) {
120
- if (builtinMetric.type === "histogram") {
121
- builtinMetric.values.push(value);
122
- if (builtinMetric.values.length > 1e3) {
123
- builtinMetric.values = builtinMetric.values.slice(-1e3);
124
- }
125
- } else if (builtinMetric.type === "counter") {
126
- builtinMetric.value += value;
127
- } else if (builtinMetric.type === "gauge") {
128
- builtinMetric.values.push(value);
129
- if (builtinMetric.values.length > 100) {
130
- builtinMetric.values = builtinMetric.values.slice(-100);
131
- }
132
- }
133
- }
134
- const customMetric = metrics.custom[name];
135
- if (customMetric) {
136
- if (customMetric.type === "histogram") {
137
- customMetric.values = customMetric.values || [];
138
- customMetric.values.push(value);
139
- if (customMetric.values.length > 1e3) {
140
- customMetric.values = customMetric.values.slice(-1e3);
141
- }
142
- } else if (customMetric.type === "counter") {
143
- customMetric.value = (customMetric.value || 0) + value;
144
- } else if (customMetric.type === "gauge") {
145
- customMetric.values = customMetric.values || [];
146
- customMetric.values.push(value);
147
- if (customMetric.values.length > 100) {
148
- customMetric.values = customMetric.values.slice(-100);
149
- }
150
- }
151
- if (customMetric.threshold) {
152
- const currentValue = customMetric.type === "histogram" || customMetric.type === "gauge" ? customMetric.values[customMetric.values.length - 1] : customMetric.value;
153
- if (currentValue > customMetric.threshold) {
154
- checkAlerts(name, currentValue);
155
- }
156
- }
157
- }
158
- if (opts.reporting.enabled && opts.reporting.batch.enabled) {
159
- reportingState.batch.push({
160
- metric: name,
161
- value,
162
- metadata,
163
- timestamp: Date.now()
164
- });
165
- if (reportingState.batch.length >= opts.reporting.batch.maxSize) {
166
- flushBatch();
167
- }
168
- }
169
- checkAlerts(name, value);
170
- }
171
- function checkAlerts(metric, value) {
172
- if (!opts.alerts.enabled) return;
173
- opts.alerts.rules.forEach((rule) => {
174
- if (rule.metric !== metric) return;
175
- let triggered = false;
176
- if (rule.condition === "exceeds" && value > rule.threshold) {
177
- triggered = true;
178
- } else if (rule.condition === "below" && value < rule.threshold) {
179
- triggered = true;
180
- } else if (rule.condition === "equals" && value === rule.threshold) {
181
- triggered = true;
182
- }
183
- if (triggered) {
184
- const alertKey = `${rule.metric}-${rule.condition}-${rule.threshold}`;
185
- const lastTriggered = alertState.triggered.get(alertKey);
186
- const now = Date.now();
187
- if (!lastTriggered || now - lastTriggered > 5e3) {
188
- alertState.triggered.set(alertKey, now);
189
- alertState.history.push({
190
- rule,
191
- value,
192
- timestamp: now
193
- });
194
- stats.alertsTriggered++;
195
- if (rule.action) {
196
- rule.action(value, rule);
197
- }
198
- }
199
- }
200
- });
201
- }
202
- function flushBatch() {
203
- if (reportingState.batch.length === 0) return;
204
- const batch = [...reportingState.batch];
205
- reportingState.batch = [];
206
- if (opts.reporting.onReport) {
207
- opts.reporting.onReport({ type: "batch", data: batch });
208
- }
209
- }
210
- function generateReport() {
211
- const report = {
212
- timestamp: Date.now(),
213
- statistics: { ...stats },
214
- metrics: {}
215
- };
216
- Object.entries(metrics.builtin).forEach(([name, metric]) => {
217
- if (metric.type === "histogram") {
218
- report.metrics[name] = {
219
- type: "histogram",
220
- unit: metric.unit,
221
- count: metric.values.length,
222
- min: metric.values.length > 0 ? Math.min(...metric.values) : 0,
223
- max: metric.values.length > 0 ? Math.max(...metric.values) : 0,
224
- avg: metric.values.length > 0 ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length : 0,
225
- p50: percentile(metric.values, 0.5),
226
- p95: percentile(metric.values, 0.95),
227
- p99: percentile(metric.values, 0.99)
228
- };
229
- } else if (metric.type === "counter") {
230
- report.metrics[name] = {
231
- type: "counter",
232
- unit: metric.unit,
233
- value: metric.value
234
- };
235
- } else if (metric.type === "gauge") {
236
- report.metrics[name] = {
237
- type: "gauge",
238
- unit: metric.unit,
239
- current: metric.values.length > 0 ? metric.values[metric.values.length - 1] : 0,
240
- avg: metric.values.length > 0 ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length : 0
241
- };
242
- }
243
- });
244
- Object.entries(metrics.custom).forEach(([name, metric]) => {
245
- if (metric.type === "histogram") {
246
- report.metrics[name] = {
247
- type: "histogram",
248
- unit: metric.unit,
249
- count: metric.values?.length || 0,
250
- min: metric.values?.length > 0 ? Math.min(...metric.values) : 0,
251
- max: metric.values?.length > 0 ? Math.max(...metric.values) : 0,
252
- avg: metric.values?.length > 0 ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length : 0,
253
- p95: percentile(metric.values || [], 0.95),
254
- p99: percentile(metric.values || [], 0.99)
255
- };
256
- } else if (metric.type === "counter") {
257
- report.metrics[name] = {
258
- type: "counter",
259
- unit: metric.unit,
260
- value: metric.value || 0
261
- };
262
- } else if (metric.type === "gauge") {
263
- report.metrics[name] = {
264
- type: "gauge",
265
- unit: metric.unit,
266
- current: metric.values?.length > 0 ? metric.values[metric.values.length - 1] : 0,
267
- avg: metric.values?.length > 0 ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length : 0
268
- };
269
- }
270
- });
271
- report.alerts = {
272
- total: alertState.history.length,
273
- recent: alertState.history.slice(-10)
274
- };
275
- if (opts.resources.enabled) {
276
- report.resources = {
277
- samples: resourceState.samples.slice(-20)
278
- };
279
- }
280
- stats.reportsGenerated++;
281
- if (opts.reporting.onReport) {
282
- opts.reporting.onReport({ type: "report", data: report });
283
- }
284
- return report;
285
- }
286
- function percentile(values, p) {
287
- if (values.length === 0) return 0;
288
- const sorted = [...values].sort((a, b) => a - b);
289
- const index = Math.ceil(sorted.length * p) - 1;
290
- return sorted[Math.max(0, index)];
291
- }
292
- function startResourceMonitoring() {
293
- if (!opts.resources.enabled) return;
294
- const collectResources = () => {
295
- const sample = {
296
- timestamp: Date.now()
297
- };
298
- if (opts.resources.track.includes("memory")) {
299
- if (typeof process !== "undefined" && process.memoryUsage) {
300
- const mem = process.memoryUsage();
301
- sample.memory = {
302
- heapUsed: mem.heapUsed / 1024 / 1024,
303
- heapTotal: mem.heapTotal / 1024 / 1024,
304
- external: mem.external / 1024 / 1024,
305
- rss: mem.rss / 1024 / 1024
306
- };
307
- } else if (typeof performance !== "undefined" && performance.memory) {
308
- sample.memory = {
309
- heapUsed: performance.memory.usedJSHeapSize / 1024 / 1024,
310
- heapTotal: performance.memory.totalJSHeapSize / 1024 / 1024
311
- };
312
- }
313
- }
314
- resourceState.samples.push(sample);
315
- if (resourceState.samples.length > 100) {
316
- resourceState.samples = resourceState.samples.slice(-100);
317
- }
318
- resourceState.timer = setTimeout(collectResources, opts.resources.interval);
319
- };
320
- collectResources();
321
- }
322
- function stopResourceMonitoring() {
323
- if (resourceState.timer) {
324
- clearTimeout(resourceState.timer);
325
- resourceState.timer = null;
326
- }
327
- }
328
- function startReporting() {
329
- if (!opts.reporting.enabled) return;
330
- reportingState.reportTimer = setInterval(() => {
331
- generateReport();
332
- }, opts.reporting.interval);
333
- if (opts.reporting.batch.enabled) {
334
- reportingState.flushTimer = setInterval(() => {
335
- flushBatch();
336
- }, opts.reporting.batch.flushInterval);
337
- }
338
- }
339
- function stopReporting() {
340
- if (reportingState.reportTimer) {
341
- clearInterval(reportingState.reportTimer);
342
- reportingState.reportTimer = null;
343
- }
344
- if (reportingState.flushTimer) {
345
- clearInterval(reportingState.flushTimer);
346
- reportingState.flushTimer = null;
347
- }
348
- flushBatch();
349
- }
350
- function startProfiling() {
351
- if (!opts.profiling.enabled) return;
352
- }
353
- function recordTrace(name, duration, metadata = {}) {
354
- if (!opts.profiling.enabled || !opts.profiling.tracing.enabled) return;
355
- if (Math.random() < opts.profiling.tracing.sampleRate) {
356
- profilingState.traces.push({
357
- name,
358
- duration,
359
- metadata,
360
- timestamp: Date.now()
361
- });
362
- if (profilingState.traces.length > 1e3) {
363
- profilingState.traces = profilingState.traces.slice(-1e3);
364
- }
365
- }
366
- }
367
- function measure(name, fn, metadata = {}) {
368
- if (!opts.enabled) return fn();
369
- const start = performance.now();
370
- try {
371
- const result = fn();
372
- const duration = performance.now() - start;
373
- recordMetric("renderTime", duration, { name, ...metadata });
374
- recordTrace(name, duration, metadata);
375
- return result;
376
- } catch (error) {
377
- recordMetric("errorCount", 1, { name, error: error.message });
378
- throw error;
379
- }
380
- }
381
- async function measureAsync(name, fn, metadata = {}) {
382
- if (!opts.enabled) return fn();
383
- const start = performance.now();
384
- try {
385
- const result = await fn();
386
- const duration = performance.now() - start;
387
- recordMetric("renderTime", duration, { name, ...metadata });
388
- recordTrace(name, duration, metadata);
389
- return result;
390
- } catch (error) {
391
- recordMetric("errorCount", 1, { name, error: error.message });
392
- throw error;
393
- }
394
- }
395
- function addMetric(name, config) {
396
- metrics.custom[name] = {
397
- type: config.type || "counter",
398
- unit: config.unit || "",
399
- threshold: config.threshold,
400
- values: config.type === "histogram" ? [] : void 0,
401
- value: config.type === "counter" || config.type === "gauge" ? 0 : void 0
402
- };
403
- }
404
- function addAlertRule(rule) {
405
- opts.alerts.rules.push(rule);
406
- }
407
- function getStats() {
408
- return {
409
- ...stats,
410
- sampleRate: samplingState.adaptiveRate,
411
- batchSize: reportingState.batch.length,
412
- resourceSamples: resourceState.samples.length,
413
- traces: profilingState.traces.length,
414
- alerts: {
415
- total: alertState.history.length,
416
- unique: alertState.triggered.size
417
- }
418
- };
419
- }
420
- function reset() {
421
- Object.values(metrics.builtin).forEach((metric) => {
422
- if (metric.type === "histogram" || metric.type === "gauge") {
423
- metric.values = [];
424
- } else if (metric.type === "counter") {
425
- metric.value = 0;
426
- }
427
- });
428
- Object.values(metrics.custom).forEach((metric) => {
429
- if (metric.type === "histogram" || metric.type === "gauge") {
430
- metric.values = [];
431
- } else if (metric.type === "counter") {
432
- metric.value = 0;
433
- }
434
- });
435
- samplingState.count = 0;
436
- samplingState.sampled = 0;
437
- reportingState.batch = [];
438
- alertState.history = [];
439
- alertState.triggered.clear();
440
- resourceState.samples = [];
441
- profilingState.traces = [];
442
- stats.metricsRecorded = 0;
443
- stats.reportsGenerated = 0;
444
- stats.alertsTriggered = 0;
445
- }
446
- if (opts.enabled) {
447
- startResourceMonitoring();
448
- startReporting();
449
- startProfiling();
450
- }
451
- return {
452
- recordMetric,
453
- measure,
454
- measureAsync,
455
- addMetric,
456
- addAlertRule,
457
- generateReport,
458
- getStats,
459
- reset,
460
- start() {
461
- opts.enabled = true;
462
- startResourceMonitoring();
463
- startReporting();
464
- startProfiling();
465
- },
466
- stop() {
467
- opts.enabled = false;
468
- stopResourceMonitoring();
469
- stopReporting();
470
- return generateReport();
471
- }
472
- };
473
- }
474
- var performanceMonitor = createPerformanceMonitor();
475
-
476
- // ../core/src/core/object-utils.js
477
- function deepClone(obj, seen = /* @__PURE__ */ new WeakMap()) {
478
- if (obj === null || typeof obj !== "object") {
479
- return obj;
480
- }
481
- if (seen.has(obj)) {
482
- return seen.get(obj);
483
- }
484
- if (obj instanceof Date) {
485
- return new Date(obj.getTime());
486
- }
487
- if (obj instanceof RegExp) {
488
- return new RegExp(obj.source, obj.flags);
489
- }
490
- if (Array.isArray(obj)) {
491
- const clonedArray = [];
492
- seen.set(obj, clonedArray);
493
- for (let i = 0; i < obj.length; i++) {
494
- clonedArray[i] = deepClone(obj[i], seen);
495
- }
496
- return clonedArray;
497
- }
498
- if (typeof obj === "function") {
499
- return obj;
500
- }
501
- if (obj instanceof Map) {
502
- const clonedMap = /* @__PURE__ */ new Map();
503
- seen.set(obj, clonedMap);
504
- for (const [key, value] of obj) {
505
- clonedMap.set(deepClone(key, seen), deepClone(value, seen));
506
- }
507
- return clonedMap;
508
- }
509
- if (obj instanceof Set) {
510
- const clonedSet = /* @__PURE__ */ new Set();
511
- seen.set(obj, clonedSet);
512
- for (const value of obj) {
513
- clonedSet.add(deepClone(value, seen));
514
- }
515
- return clonedSet;
516
- }
517
- if (obj instanceof WeakMap) {
518
- return /* @__PURE__ */ new WeakMap();
519
- }
520
- if (obj instanceof WeakSet) {
521
- return /* @__PURE__ */ new WeakSet();
522
- }
523
- const clonedObj = {};
524
- seen.set(obj, clonedObj);
525
- if (obj.constructor && obj.constructor !== Object) {
526
- try {
527
- clonedObj.__proto__ = obj.__proto__;
528
- } catch {
529
- Object.setPrototypeOf(clonedObj, Object.getPrototypeOf(obj));
530
- }
531
- }
532
- for (const key in obj) {
533
- if (obj.hasOwnProperty(key)) {
534
- clonedObj[key] = deepClone(obj[key], seen);
535
- }
536
- }
537
- const descriptors = Object.getOwnPropertyDescriptors(obj);
538
- for (const key of Object.keys(descriptors)) {
539
- if (!descriptors[key].enumerable && descriptors[key].configurable) {
540
- try {
541
- Object.defineProperty(clonedObj, key, {
542
- ...descriptors[key],
543
- value: deepClone(descriptors[key].value, seen)
544
- });
545
- } catch {
546
- }
547
- }
548
- }
549
- return clonedObj;
550
- }
551
- function validateComponent(component, path = "root") {
552
- if (component === null || component === void 0) {
553
- throw new Error(`Invalid component at ${path}: null or undefined`);
554
- }
555
- if (["string", "number", "boolean"].includes(typeof component)) {
556
- return true;
557
- }
558
- if (typeof component === "function") {
559
- return true;
560
- }
561
- if (Array.isArray(component)) {
562
- component.forEach((child, index) => {
563
- validateComponent(child, `${path}[${index}]`);
564
- });
565
- return true;
566
- }
567
- if (typeof component === "object") {
568
- const keys = Object.keys(component);
569
- if (keys.length === 0) {
570
- throw new Error(`Empty object at ${path}`);
571
- }
572
- keys.forEach((key) => {
573
- const value = component[key];
574
- if (!/^[a-zA-Z][a-zA-Z0-9-]*$/.test(key) && key !== "text") {
575
- console.warn(`Potentially invalid tag name at ${path}: ${key}`);
576
- }
577
- if (value && typeof value === "object" && !Array.isArray(value)) {
578
- if (value.children) {
579
- validateComponent(value.children, `${path}.${key}.children`);
580
- }
581
- } else if (value && typeof value !== "string" && typeof value !== "number" && typeof value !== "function") {
582
- throw new Error(`Invalid value type at ${path}.${key}: ${typeof value}`);
583
- }
584
- });
585
- return true;
586
- }
587
- throw new Error(`Invalid component type at ${path}: ${typeof component}`);
588
- }
589
-
590
- // ../core/src/components/component-system.js
591
- var COMPONENT_METADATA = /* @__PURE__ */ new WeakMap();
592
- var ComponentState = class {
593
- constructor(initialState = {}) {
594
- this.state = { ...initialState };
595
- this.listeners = /* @__PURE__ */ new Set();
596
- this.isUpdating = false;
597
- }
598
- /**
599
- * Get state value by key or entire state
600
- *
601
- * @param {string} [key] - State key to retrieve
602
- * @returns {*} State value or entire state object
603
- */
604
- get(key) {
605
- return key ? this.state[key] : { ...this.state };
606
- }
607
- /**
608
- * Update state with new values
609
- *
610
- * @param {Object} updates - State updates to apply
611
- * @returns {ComponentState} This instance for chaining
612
- */
613
- set(updates) {
614
- if (this.isUpdating) return this;
615
- const oldState = { ...this.state };
616
- if (typeof updates === "function") {
617
- updates = updates(oldState);
618
- }
619
- this.state = { ...this.state, ...updates };
620
- this.notifyListeners(oldState, this.state);
621
- return this;
622
- }
623
- subscribe(listener) {
624
- this.listeners.add(listener);
625
- return () => this.listeners.delete(listener);
626
- }
627
- notifyListeners(oldState, newState) {
628
- if (this.listeners.size === 0) return;
629
- this.isUpdating = true;
630
- this.listeners.forEach((listener) => {
631
- try {
632
- listener(newState, oldState);
633
- } catch (_error) {
634
- console.error("State listener _error:", _error);
635
- }
636
- });
637
- this.isUpdating = false;
638
- }
639
- };
640
- var Component = class _Component {
641
- constructor(definition = {}) {
642
- this.definition = definition;
643
- this.name = definition.name || "AnonymousComponent";
644
- this.props = {};
645
- this.state = new ComponentState(definition.state || {});
646
- this.children = [];
647
- this.parent = null;
648
- this.rendered = null;
649
- this.isMounted = false;
650
- this.isDestroyed = false;
651
- this.hooks = {
652
- beforeCreate: definition.beforeCreate || (() => {
653
- }),
654
- created: definition.created || (() => {
655
- }),
656
- beforeMount: definition.beforeMount || (() => {
657
- }),
658
- mounted: definition.mounted || (() => {
659
- }),
660
- beforeUpdate: definition.beforeUpdate || (() => {
661
- }),
662
- updated: definition.updated || (() => {
663
- }),
664
- beforeDestroy: definition.beforeDestroy || (() => {
665
- }),
666
- destroyed: definition.destroyed || (() => {
667
- }),
668
- errorCaptured: definition.errorCaptured || (() => {
669
- })
670
- };
671
- this.methods = definition.methods || {};
672
- Object.keys(this.methods).forEach((methodName) => {
673
- if (typeof this.methods[methodName] === "function") {
674
- this[methodName] = this.methods[methodName].bind(this);
675
- }
676
- });
677
- this.computed = definition.computed || {};
678
- this.computedCache = /* @__PURE__ */ new Map();
679
- this.watchers = definition.watch || {};
680
- this.setupWatchers();
681
- COMPONENT_METADATA.set(this, {
682
- createdAt: Date.now(),
683
- updateCount: 0,
684
- renderCount: 0
685
- });
686
- this.callHook("beforeCreate");
687
- this.initialize();
688
- this.callHook("created");
689
- }
690
- /**
691
- * Initialize component
692
- */
693
- initialize() {
694
- this.unsubscribeState = this.state.subscribe((newState, oldState) => {
695
- this.onStateChange(newState, oldState);
696
- });
697
- this.initializeComputed();
698
- }
699
- /**
700
- * Set up watchers for reactive data
701
- */
702
- setupWatchers() {
703
- Object.keys(this.watchers).forEach((key) => {
704
- const handler = this.watchers[key];
705
- this.state.subscribe((newState, oldState) => {
706
- if (newState[key] !== oldState[key]) {
707
- handler.call(this, newState[key], oldState[key]);
708
- }
709
- });
710
- });
711
- }
712
- /**
713
- * Initialize computed properties
714
- */
715
- initializeComputed() {
716
- Object.keys(this.computed).forEach((key) => {
717
- Object.defineProperty(this, key, {
718
- get: () => {
719
- if (!this.computedCache.has(key)) {
720
- const value = this.computed[key].call(this);
721
- this.computedCache.set(key, value);
722
- }
723
- return this.computedCache.get(key);
724
- },
725
- enumerable: true
726
- });
727
- });
728
- }
729
- /**
730
- * Handle state changes
731
- */
732
- onStateChange() {
733
- if (this.isDestroyed) return;
734
- this.computedCache.clear();
735
- if (this.isMounted) {
736
- this.update();
737
- }
738
- }
739
- /**
740
- * Call lifecycle hook
741
- */
742
- callHook(hookName, ...args) {
743
- try {
744
- if (this.hooks[hookName]) {
745
- return this.hooks[hookName].call(this, ...args);
746
- }
747
- } catch (_error) {
748
- this.handleError(_error, `${hookName} hook`);
749
- }
750
- }
751
- /**
752
- * Handle component errors
753
- */
754
- handleError(_error) {
755
- console.error(`Component Error in ${this.name}:`, _error);
756
- this.callHook("errorCaptured", _error);
757
- if (this.parent && this.parent.handleError) {
758
- this.parent.handleError(_error, `${this.name} -> ${context}`);
759
- }
760
- }
761
- /**
762
- * Render the component
763
- */
764
- render(props = {}) {
765
- if (this.isDestroyed) {
766
- console.warn(`Attempting to render destroyed component: ${this.name}`);
767
- return null;
768
- }
769
- try {
770
- const metadata = COMPONENT_METADATA.get(this);
771
- if (metadata) {
772
- metadata.renderCount++;
773
- }
774
- this.props = { ...props };
775
- if (typeof this.definition.render === "function") {
776
- this.rendered = this.definition.render.call(this, this.props, this.state.get());
777
- } else if (typeof this.definition.template !== "undefined") {
778
- this.rendered = this.processTemplate(this.definition.template, this.props, this.state.get());
779
- } else {
780
- throw new Error(`Component ${this.name} must have either render method or template`);
781
- }
782
- if (this.rendered !== null) {
783
- validateComponent(this.rendered, this.name);
784
- }
785
- return this.rendered;
786
- } catch (_error) {
787
- this.handleError(_error);
788
- return { div: { className: "component-_error", text: `Error in ${this.name}` } };
789
- }
790
- }
791
- /**
792
- * Process template with data
793
- */
794
- processTemplate(template, props, state) {
795
- if (typeof template === "function") {
796
- return template.call(this, props, state);
797
- }
798
- if (typeof template === "string") {
799
- return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
800
- return props[key] || state[key] || "";
801
- });
802
- }
803
- const processed = deepClone(template);
804
- this.interpolateObject(processed, { ...props, ...state });
805
- return processed;
806
- }
807
- /**
808
- * Interpolate object with data
809
- */
810
- interpolateObject(obj, data) {
811
- if (typeof obj === "string") {
812
- return obj.replace(/\{\{(\w+)\}\}/g, (match, key) => data[key] || "");
813
- }
814
- if (Array.isArray(obj)) {
815
- return obj.map((item) => this.interpolateObject(item, data));
816
- }
817
- if (obj && typeof obj === "object") {
818
- Object.keys(obj).forEach((key) => {
819
- obj[key] = this.interpolateObject(obj[key], data);
820
- });
821
- }
822
- return obj;
823
- }
824
- /**
825
- * Mount the component
826
- */
827
- mount() {
828
- if (this.isMounted || this.isDestroyed) return this;
829
- this.callHook("beforeMount");
830
- this.isMounted = true;
831
- this.callHook("mounted");
832
- return this;
833
- }
834
- /**
835
- * Update the component
836
- */
837
- update() {
838
- if (!this.isMounted || this.isDestroyed) return this;
839
- const metadata = COMPONENT_METADATA.get(this);
840
- if (metadata) {
841
- metadata.updateCount++;
842
- }
843
- this.callHook("beforeUpdate");
844
- this.callHook("updated");
845
- return this;
846
- }
847
- /**
848
- * Destroy the component
849
- */
850
- destroy() {
851
- if (this.isDestroyed) return this;
852
- this.callHook("beforeDestroy");
853
- if (this.unsubscribeState) {
854
- this.unsubscribeState();
855
- }
856
- this.children.forEach((child) => {
857
- if (child.destroy) {
858
- child.destroy();
859
- }
860
- });
861
- this.isMounted = false;
862
- this.isDestroyed = true;
863
- this.children = [];
864
- this.parent = null;
865
- this.callHook("destroyed");
866
- return this;
867
- }
868
- /**
869
- * Get component metadata
870
- */
871
- getMetadata() {
872
- return COMPONENT_METADATA.get(this) || {};
873
- }
874
- /**
875
- * Clone component with new props/state
876
- */
877
- clone(overrides = {}) {
878
- const newDefinition = { ...this.definition, ...overrides };
879
- return new _Component(newDefinition);
880
- }
881
- };
882
- if (performanceMonitor) {
883
- const originalRender = Component.prototype.render;
884
- Component.prototype.render = function(...args) {
885
- const start = performance.now();
886
- const result = originalRender.apply(this, args);
887
- const duration = performance.now() - start;
888
- performanceMonitor.recordMetric("renderTime", duration, {
889
- type: "component",
890
- name: this.name,
891
- propsSize: JSON.stringify(this.props || {}).length,
892
- hasState: Object.keys(this.state?.get() || {}).length > 0
893
- });
894
- return result;
895
- };
896
- }
897
-
898
- // ../core/src/utils/error-handler.js
899
- var CoherentError = class _CoherentError extends Error {
900
- constructor(message, options = {}) {
901
- super(message);
902
- this.name = "CoherentError";
903
- this.type = options.type || "generic";
904
- this.component = options.component;
905
- this.context = options.context;
906
- this.suggestions = options.suggestions || [];
907
- this.timestamp = Date.now();
908
- if (Error.captureStackTrace) {
909
- Error.captureStackTrace(this, _CoherentError);
910
- }
911
- }
912
- toJSON() {
913
- return {
914
- name: this.name,
915
- message: this.message,
916
- type: this.type,
917
- component: this.component,
918
- context: this.context,
919
- suggestions: this.suggestions,
920
- timestamp: this.timestamp,
921
- stack: this.stack
922
- };
923
- }
924
- };
925
- var ComponentValidationError = class extends CoherentError {
926
- constructor(message, component, suggestions = []) {
927
- super(message, {
928
- type: "validation",
929
- component,
930
- suggestions: [
931
- "Check component structure and syntax",
932
- "Ensure all required properties are present",
933
- "Validate prop types and values",
934
- ...suggestions
935
- ]
936
- });
937
- this.name = "ComponentValidationError";
938
- }
939
- };
940
- var RenderingError = class extends CoherentError {
941
- constructor(message, component, context2, suggestions = []) {
942
- super(message, {
943
- type: "rendering",
944
- component,
945
- context: context2,
946
- suggestions: [
947
- "Check for circular references",
948
- "Validate component depth",
949
- "Ensure all functions return valid components",
950
- ...suggestions
951
- ]
952
- });
953
- this.name = "RenderingError";
954
- }
955
- };
956
- var PerformanceError = class extends CoherentError {
957
- constructor(message, metrics, suggestions = []) {
958
- super(message, {
959
- type: "performance",
960
- context: metrics,
961
- suggestions: [
962
- "Consider component memoization",
963
- "Reduce component complexity",
964
- "Enable caching",
965
- ...suggestions
966
- ]
967
- });
968
- this.name = "PerformanceError";
969
- }
970
- };
971
- var StateError = class extends CoherentError {
972
- constructor(message, state, suggestions = []) {
973
- super(message, {
974
- type: "state",
975
- context: state,
976
- suggestions: [
977
- "Check state mutations",
978
- "Ensure proper state initialization",
979
- "Validate state transitions",
980
- ...suggestions
981
- ]
982
- });
983
- this.name = "StateError";
984
- }
985
- };
986
- var ErrorHandler = class {
987
- constructor(options = {}) {
988
- this.options = {
989
- enableStackTrace: options.enableStackTrace !== false,
990
- enableSuggestions: options.enableSuggestions !== false,
991
- enableLogging: options.enableLogging !== false,
992
- logLevel: options.logLevel || "_error",
993
- maxErrorHistory: options.maxErrorHistory || 100,
994
- ...options
995
- };
996
- this.errorHistory = [];
997
- this.errorCounts = /* @__PURE__ */ new Map();
998
- this.suppressedErrors = /* @__PURE__ */ new Set();
999
- }
1000
- /**
1001
- * Handle and report errors with detailed context
1002
- */
1003
- handle(_error, context2 = {}) {
1004
- const enhancedError = this.enhanceError(_error, context2);
1005
- this.addToHistory(enhancedError);
1006
- if (this.options.enableLogging) {
1007
- this.logError(enhancedError);
1008
- }
1009
- return enhancedError;
1010
- }
1011
- /**
1012
- * Enhance existing errors with more context
1013
- */
1014
- enhanceError(_error, context2 = {}) {
1015
- if (_error instanceof CoherentError) {
1016
- return _error;
1017
- }
1018
- const errorType = this.classifyError(_error, context2);
1019
- switch (errorType) {
1020
- case "validation":
1021
- return new ComponentValidationError(
1022
- _error.message,
1023
- context2.component,
1024
- this.generateSuggestions(_error, context2)
1025
- );
1026
- case "rendering":
1027
- return new RenderingError(
1028
- _error.message,
1029
- context2.component,
1030
- context2.renderContext,
1031
- this.generateSuggestions(_error, context2)
1032
- );
1033
- case "performance":
1034
- return new PerformanceError(
1035
- _error.message,
1036
- context2.metrics,
1037
- this.generateSuggestions(_error, context2)
1038
- );
1039
- case "state":
1040
- return new StateError(
1041
- _error.message,
1042
- context2.state,
1043
- this.generateSuggestions(_error, context2)
1044
- );
1045
- default:
1046
- return new CoherentError(_error.message, {
1047
- type: errorType,
1048
- component: context2.component,
1049
- context: context2.context,
1050
- suggestions: this.generateSuggestions(_error, context2)
1051
- });
1052
- }
1053
- }
1054
- /**
1055
- * Classify _error type based on message and context
1056
- */
1057
- classifyError(_error, context2) {
1058
- const message = _error.message.toLowerCase();
1059
- if (message.includes("invalid") || message.includes("validation") || message.includes("required") || message.includes("type")) {
1060
- return "validation";
1061
- }
1062
- if (message.includes("render") || message.includes("circular") || message.includes("depth") || message.includes("cannot render")) {
1063
- return "rendering";
1064
- }
1065
- if (message.includes("slow") || message.includes("memory") || message.includes("performance") || message.includes("timeout")) {
1066
- return "performance";
1067
- }
1068
- if (message.includes("state") || message.includes("mutation") || message.includes("store") || context2.state) {
1069
- return "state";
1070
- }
1071
- if (context2.component) return "validation";
1072
- if (context2.renderContext) return "rendering";
1073
- if (context2.metrics) return "performance";
1074
- return "generic";
1075
- }
1076
- /**
1077
- * Generate helpful suggestions based on _error
1078
- */
1079
- generateSuggestions(_error, context2 = {}) {
1080
- const suggestions = [];
1081
- const message = _error.message.toLowerCase();
1082
- const patterns = [
1083
- {
1084
- pattern: /cannot render|render.*failed/,
1085
- suggestions: [
1086
- "Check if component returns a valid object structure",
1087
- "Ensure all properties are properly defined",
1088
- "Look for undefined variables or null references"
1089
- ]
1090
- },
1091
- {
1092
- pattern: /circular.*reference/,
1093
- suggestions: [
1094
- "Remove circular references between components",
1095
- "Use lazy loading or memoization to break cycles",
1096
- "Check for self-referencing components"
1097
- ]
1098
- },
1099
- {
1100
- pattern: /maximum.*depth/,
1101
- suggestions: [
1102
- "Reduce component nesting depth",
1103
- "Break complex components into smaller parts",
1104
- "Check for infinite recursion in component functions"
1105
- ]
1106
- },
1107
- {
1108
- pattern: /invalid.*component/,
1109
- suggestions: [
1110
- "Ensure component follows the expected object structure",
1111
- "Check property names and values for typos",
1112
- "Verify component is not null or undefined"
1113
- ]
1114
- },
1115
- {
1116
- pattern: /performance|slow|timeout/,
1117
- suggestions: [
1118
- "Enable component caching",
1119
- "Use memoization for expensive operations",
1120
- "Reduce component complexity",
1121
- "Consider lazy loading for large components"
1122
- ]
1123
- }
1124
- ];
1125
- patterns.forEach(({ pattern, suggestions: patternSuggestions }) => {
1126
- if (pattern.test(message)) {
1127
- suggestions.push(...patternSuggestions);
1128
- }
1129
- });
1130
- if (context2.component) {
1131
- const componentType = typeof context2.component;
1132
- if (componentType === "function") {
1133
- suggestions.push("Check function component return value");
1134
- } else if (componentType === "object" && context2.component === null) {
1135
- suggestions.push("Component is null - ensure proper initialization");
1136
- } else if (Array.isArray(context2.component)) {
1137
- suggestions.push("Arrays should contain valid component objects");
1138
- }
1139
- }
1140
- if (suggestions.length === 0) {
1141
- suggestions.push(
1142
- "Enable development tools for more detailed debugging",
1143
- "Check browser console for additional _error details",
1144
- "Use component validation tools to identify issues"
1145
- );
1146
- }
1147
- return [...new Set(suggestions)];
1148
- }
1149
- /**
1150
- * Add _error to history with deduplication
1151
- */
1152
- addToHistory(_error) {
1153
- const errorKey = `${_error.name}:${_error.message}`;
1154
- this.errorCounts.set(errorKey, (this.errorCounts.get(errorKey) || 0) + 1);
1155
- const historyEntry = {
1156
- ..._error.toJSON(),
1157
- count: this.errorCounts.get(errorKey),
1158
- firstSeen: this.errorHistory.find((e) => e.key === errorKey)?.firstSeen || _error.timestamp,
1159
- key: errorKey
1160
- };
1161
- this.errorHistory = this.errorHistory.filter((e) => e.key !== errorKey);
1162
- this.errorHistory.unshift(historyEntry);
1163
- if (this.errorHistory.length > this.options.maxErrorHistory) {
1164
- this.errorHistory = this.errorHistory.slice(0, this.options.maxErrorHistory);
1165
- }
1166
- }
1167
- /**
1168
- * Log _error with enhanced formatting
1169
- */
1170
- logError(_error) {
1171
- if (this.suppressedErrors.has(`${_error.name}:${_error.message}`)) {
1172
- return;
1173
- }
1174
- const isRepeated = this.errorCounts.get(`${_error.name}:${_error.message}`) > 1;
1175
- const errorGroup = `\u{1F6A8} ${_error.name}${isRepeated ? ` (\xD7${this.errorCounts.get(`${_error.name}:${_error.message}`)})` : ""}`;
1176
- console.group(errorGroup);
1177
- console.error(`\u274C ${_error.message}`);
1178
- if (_error.component) {
1179
- console.log("\u{1F50D} Component:", this.formatComponent(_error.component));
1180
- }
1181
- if (_error.context) {
1182
- console.log("\u{1F4CB} Context:", _error.context);
1183
- }
1184
- if (this.options.enableSuggestions && _error.suggestions.length > 0) {
1185
- console.group("\u{1F4A1} Suggestions:");
1186
- _error.suggestions.forEach((suggestion, index) => {
1187
- console.log(`${index + 1}. ${suggestion}`);
1188
- });
1189
- console.groupEnd();
1190
- }
1191
- if (this.options.enableStackTrace && _error.stack) {
1192
- console.log("\u{1F4DA} Stack trace:", _error.stack);
1193
- }
1194
- console.groupEnd();
1195
- }
1196
- /**
1197
- * Format component for logging
1198
- */
1199
- formatComponent(component, maxDepth = 2, currentDepth = 0) {
1200
- if (currentDepth > maxDepth) {
1201
- return "[...deep]";
1202
- }
1203
- if (typeof component === "function") {
1204
- return `[Function: ${component.name || "anonymous"}]`;
1205
- }
1206
- if (Array.isArray(component)) {
1207
- return component.slice(0, 3).map(
1208
- (item) => this.formatComponent(item, maxDepth, currentDepth + 1)
1209
- );
1210
- }
1211
- if (component && typeof component === "object") {
1212
- const formatted = {};
1213
- const keys = Object.keys(component).slice(0, 5);
1214
- for (const key of keys) {
1215
- if (key === "children" && component[key]) {
1216
- formatted[key] = this.formatComponent(component[key], maxDepth, currentDepth + 1);
1217
- } else {
1218
- formatted[key] = component[key];
1219
- }
1220
- }
1221
- if (Object.keys(component).length > 5) {
1222
- formatted["..."] = `(${Object.keys(component).length - 5} more)`;
1223
- }
1224
- return formatted;
1225
- }
1226
- return component;
1227
- }
1228
- /**
1229
- * Suppress specific _error types
1230
- */
1231
- suppress(errorPattern) {
1232
- this.suppressedErrors.add(errorPattern);
1233
- }
1234
- /**
1235
- * Clear _error history
1236
- */
1237
- clearHistory() {
1238
- this.errorHistory = [];
1239
- this.errorCounts.clear();
1240
- }
1241
- /**
1242
- * Get _error statistics
1243
- */
1244
- getStats() {
1245
- const errorsByType = {};
1246
- const errorsByTime = {};
1247
- this.errorHistory.forEach((_error) => {
1248
- errorsByType[_error.type] = (errorsByType[_error.type] || 0) + _error.count;
1249
- const hour = new Date(_error.timestamp).toISOString().slice(0, 13);
1250
- errorsByTime[hour] = (errorsByTime[hour] || 0) + _error.count;
1251
- });
1252
- return {
1253
- totalErrors: this.errorHistory.reduce((sum, e) => sum + e.count, 0),
1254
- uniqueErrors: this.errorHistory.length,
1255
- errorsByType,
1256
- errorsByTime,
1257
- mostCommonErrors: this.getMostCommonErrors(5),
1258
- recentErrors: this.errorHistory.slice(0, 10)
1259
- };
1260
- }
1261
- /**
1262
- * Get most common errors
1263
- */
1264
- getMostCommonErrors(limit = 10) {
1265
- return this.errorHistory.sort((a, b) => b.count - a.count).slice(0, limit).map(({ name, message, count, type }) => ({
1266
- name,
1267
- message,
1268
- count,
1269
- type
1270
- }));
1271
- }
1272
- };
1273
- var globalErrorHandler = new ErrorHandler();
1274
-
1275
- // ../core/src/components/lifecycle.js
1276
- var LIFECYCLE_PHASES = {
1277
- BEFORE_CREATE: "beforeCreate",
1278
- CREATED: "created",
1279
- BEFORE_MOUNT: "beforeMount",
1280
- MOUNTED: "mounted",
1281
- BEFORE_UPDATE: "beforeUpdate",
1282
- UPDATED: "updated",
1283
- BEFORE_UNMOUNT: "beforeUnmount",
1284
- UNMOUNTED: "unmounted",
1285
- ERROR: "_error"
1286
- };
1287
- var componentInstances = /* @__PURE__ */ new WeakMap();
1288
- var ComponentEventSystem = class {
1289
- constructor() {
1290
- this.events = /* @__PURE__ */ new Map();
1291
- this.globalHandlers = /* @__PURE__ */ new Map();
1292
- }
1293
- /**
1294
- * Emit event to component or globally
1295
- */
1296
- emit(eventName, data = {}, target = null) {
1297
- const event = {
1298
- name: eventName,
1299
- data,
1300
- target,
1301
- timestamp: Date.now(),
1302
- stopped: false,
1303
- preventDefault: false
1304
- };
1305
- if (target) {
1306
- const instance = componentInstances.get(target);
1307
- if (instance) {
1308
- this._notifyHandlers(instance.id, event);
1309
- }
1310
- } else {
1311
- this._notifyGlobalHandlers(event);
1312
- }
1313
- return event;
1314
- }
1315
- /**
1316
- * Listen for events on component or globally
1317
- */
1318
- on(eventName, handler, componentId = null) {
1319
- if (componentId) {
1320
- if (!this.events.has(componentId)) {
1321
- this.events.set(componentId, /* @__PURE__ */ new Map());
1322
- }
1323
- const componentEvents = this.events.get(componentId);
1324
- if (!componentEvents.has(eventName)) {
1325
- componentEvents.set(eventName, /* @__PURE__ */ new Set());
1326
- }
1327
- componentEvents.get(eventName).add(handler);
1328
- } else {
1329
- if (!this.globalHandlers.has(eventName)) {
1330
- this.globalHandlers.set(eventName, /* @__PURE__ */ new Set());
1331
- }
1332
- this.globalHandlers.get(eventName).add(handler);
1333
- }
1334
- return () => this.off(eventName, handler, componentId);
1335
- }
1336
- /**
1337
- * Remove event handler
1338
- */
1339
- off(eventName, handler, componentId = null) {
1340
- if (componentId) {
1341
- const componentEvents = this.events.get(componentId);
1342
- if (componentEvents && componentEvents.has(eventName)) {
1343
- componentEvents.get(eventName).delete(handler);
1344
- if (componentEvents.get(eventName).size === 0) {
1345
- componentEvents.delete(eventName);
1346
- if (componentEvents.size === 0) {
1347
- this.events.delete(componentId);
1348
- }
1349
- }
1350
- }
1351
- } else {
1352
- const handlers = this.globalHandlers.get(eventName);
1353
- if (handlers) {
1354
- handlers.delete(handler);
1355
- if (handlers.size === 0) {
1356
- this.globalHandlers.delete(eventName);
1357
- }
1358
- }
1359
- }
1360
- }
1361
- /**
1362
- * Listen once
1363
- */
1364
- once(eventName, handler, componentId = null) {
1365
- const onceHandler = (event) => {
1366
- handler(event);
1367
- this.off(eventName, onceHandler, componentId);
1368
- };
1369
- return this.on(eventName, onceHandler, componentId);
1370
- }
1371
- /**
1372
- * Notify component handlers
1373
- */
1374
- _notifyHandlers(componentId, event) {
1375
- const componentEvents = this.events.get(componentId);
1376
- if (componentEvents && componentEvents.has(event.name)) {
1377
- const handlers = componentEvents.get(event.name);
1378
- for (const handler of handlers) {
1379
- if (event.stopped) break;
1380
- try {
1381
- handler(event);
1382
- } catch (_error) {
1383
- globalErrorHandler.handle(_error, {
1384
- type: "event-handler-_error",
1385
- context: { event, handler: handler.toString() }
1386
- });
1387
- }
1388
- }
1389
- }
1390
- }
1391
- /**
1392
- * Notify global handlers
1393
- */
1394
- _notifyGlobalHandlers(event) {
1395
- const handlers = this.globalHandlers.get(event.name);
1396
- if (handlers) {
1397
- for (const handler of handlers) {
1398
- if (event.stopped) break;
1399
- try {
1400
- handler(event);
1401
- } catch (_error) {
1402
- globalErrorHandler.handle(_error, {
1403
- type: "global-event-handler-_error",
1404
- context: { event, handler: handler.toString() }
1405
- });
1406
- }
1407
- }
1408
- }
1409
- }
1410
- /**
1411
- * Clean up events for a component
1412
- */
1413
- cleanup(componentId) {
1414
- this.events.delete(componentId);
1415
- }
1416
- /**
1417
- * Get event statistics
1418
- */
1419
- getStats() {
1420
- return {
1421
- componentEvents: this.events.size,
1422
- globalEvents: this.globalHandlers.size,
1423
- totalHandlers: Array.from(this.events.values()).reduce((sum, events) => {
1424
- return sum + Array.from(events.values()).reduce((eventSum, handlers) => {
1425
- return eventSum + handlers.size;
1426
- }, 0);
1427
- }, 0) + Array.from(this.globalHandlers.values()).reduce((sum, handlers) => {
1428
- return sum + handlers.size;
1429
- }, 0)
1430
- };
1431
- }
1432
- };
1433
- var eventSystem = new ComponentEventSystem();
1434
- function createLifecycleHooks() {
1435
- const hooks = {};
1436
- Object.values(LIFECYCLE_PHASES).forEach((phase) => {
1437
- hooks[phase] = (callback) => {
1438
- const instance = getCurrentInstance();
1439
- if (instance) {
1440
- instance.hook(phase, callback);
1441
- }
1442
- };
1443
- });
1444
- return hooks;
1445
- }
1446
- var currentInstance = null;
1447
- function getCurrentInstance() {
1448
- return currentInstance;
1449
- }
1450
- var useHooks = createLifecycleHooks();
1451
-
1452
- // ../core/src/events/event-bus.js
1453
- function throttle(func, delay) {
1454
- let lastCall = 0;
1455
- let timeoutId = null;
1456
- return function throttled(...args) {
1457
- const now = Date.now();
1458
- const timeSinceLastCall = now - lastCall;
1459
- if (timeSinceLastCall >= delay) {
1460
- lastCall = now;
1461
- return func.apply(this, args);
1462
- } else {
1463
- if (timeoutId) clearTimeout(timeoutId);
1464
- timeoutId = setTimeout(() => {
1465
- lastCall = Date.now();
1466
- func.apply(this, args);
1467
- }, delay - timeSinceLastCall);
1468
- }
1469
- };
1470
- }
1471
- var EventBus = class {
1472
- constructor(options = {}) {
1473
- this.listeners = /* @__PURE__ */ new Map();
1474
- this.handlers = /* @__PURE__ */ new Map();
1475
- this.actionHandlers = /* @__PURE__ */ new Map();
1476
- this.middleware = [];
1477
- this.throttledEmitters = /* @__PURE__ */ new Map();
1478
- this.debouncedEmitters = /* @__PURE__ */ new Map();
1479
- this.options = {
1480
- debug: false,
1481
- performance: true,
1482
- maxListeners: 100,
1483
- enableWildcards: true,
1484
- enableAsync: true,
1485
- wildcardSeparator: ":",
1486
- enablePriority: true,
1487
- defaultPriority: 0,
1488
- errorHandler: null,
1489
- filters: {
1490
- allowList: null,
1491
- // null means allow all
1492
- blockList: []
1493
- },
1494
- throttle: {
1495
- enabled: false,
1496
- defaultDelay: 100,
1497
- events: {}
1498
- },
1499
- batching: {
1500
- enabled: false,
1501
- maxBatchSize: 10,
1502
- flushInterval: 16
1503
- },
1504
- ...options
1505
- };
1506
- this.stats = {
1507
- eventsEmitted: 0,
1508
- listenersExecuted: 0,
1509
- errorsOccurred: 0,
1510
- averageEmitTime: 0,
1511
- throttledEvents: 0,
1512
- filteredEvents: 0
1513
- };
1514
- if (this.options.batching.enabled) {
1515
- this.batchQueue = [];
1516
- this.batchTimer = null;
1517
- }
1518
- if (this.options.debug) {
1519
- this.use((event, data, next) => {
1520
- console.log(`[EventBus] ${event}:`, data);
1521
- next();
1522
- });
1523
- }
1524
- }
1525
- /**
1526
- * Add middleware
1527
- */
1528
- use(middleware) {
1529
- if (typeof middleware !== "function") {
1530
- throw new Error("Middleware must be a function");
1531
- }
1532
- this.middleware.push(middleware);
1533
- return this;
1534
- }
1535
- /**
1536
- * Check if event passes filters
1537
- */
1538
- passesFilters(event) {
1539
- const { allowList, blockList } = this.options.filters;
1540
- if (blockList && blockList.length > 0) {
1541
- for (const pattern of blockList) {
1542
- if (this.matchPattern(pattern, event)) {
1543
- this.stats.filteredEvents++;
1544
- return false;
1545
- }
1546
- }
1547
- }
1548
- if (allowList && allowList.length > 0) {
1549
- for (const pattern of allowList) {
1550
- if (this.matchPattern(pattern, event)) {
1551
- return true;
1552
- }
1553
- }
1554
- this.stats.filteredEvents++;
1555
- return false;
1556
- }
1557
- return true;
1558
- }
1559
- /**
1560
- * Match event against pattern
1561
- */
1562
- matchPattern(pattern, event) {
1563
- const sep = this.options.wildcardSeparator;
1564
- const patternParts = pattern.split(sep);
1565
- const eventParts = event.split(sep);
1566
- if (pattern.includes("*")) {
1567
- if (patternParts.length !== eventParts.length) {
1568
- return false;
1569
- }
1570
- return patternParts.every((part, i) => part === "*" || part === eventParts[i]);
1571
- }
1572
- return pattern === event;
1573
- }
1574
- /**
1575
- * Emit an event
1576
- */
1577
- async emit(event, data = null) {
1578
- if (!this.passesFilters(event)) {
1579
- if (this.options.debug) {
1580
- console.warn(`[EventBus] Event filtered: ${event}`);
1581
- }
1582
- return;
1583
- }
1584
- if (this.options.batching.enabled) {
1585
- return this.addToBatch(event, data);
1586
- }
1587
- if (this.options.throttle.enabled) {
1588
- const throttleDelay = this.options.throttle.events && this.options.throttle.events[event] || this.options.throttle.defaultDelay;
1589
- if (throttleDelay > 0) {
1590
- return this.emitThrottled(event, data, throttleDelay);
1591
- }
1592
- }
1593
- return this.emitImmediate(event, data);
1594
- }
1595
- /**
1596
- * Emit immediately without throttling
1597
- */
1598
- async emitImmediate(event, data = null) {
1599
- const startTime = this.options.performance ? performance.now() : 0;
1600
- try {
1601
- await this.runMiddleware(event, data);
1602
- const listeners = this.getEventListeners(event);
1603
- if (listeners.length === 0) {
1604
- if (this.options.debug) {
1605
- console.warn(`[EventBus] No listeners for event: ${event}`);
1606
- }
1607
- return;
1608
- }
1609
- const promises = listeners.map(
1610
- (listenerObj) => this.executeListener(listenerObj.listener, event, data, listenerObj.options)
1611
- );
1612
- if (this.options.enableAsync) {
1613
- await Promise.allSettled(promises);
1614
- } else {
1615
- for (const promise of promises) {
1616
- await promise;
1617
- }
1618
- }
1619
- this.stats.eventsEmitted++;
1620
- this.stats.listenersExecuted += listeners.length;
1621
- } catch (error) {
1622
- this.stats.errorsOccurred++;
1623
- this.handleError(error, event, data);
1624
- } finally {
1625
- if (this.options.performance) {
1626
- const duration = performance.now() - startTime;
1627
- this.updatePerformanceStats(duration);
1628
- }
1629
- }
1630
- }
1631
- /**
1632
- * Emit with throttling
1633
- */
1634
- emitThrottled(event, data, delay) {
1635
- if (!this.throttledEmitters.has(event)) {
1636
- const throttled = throttle((evt, d) => this.emitImmediate(evt, d), delay);
1637
- this.throttledEmitters.set(event, throttled);
1638
- }
1639
- this.stats.throttledEvents++;
1640
- return this.throttledEmitters.get(event)(event, data);
1641
- }
1642
- /**
1643
- * Add event to batch queue
1644
- */
1645
- addToBatch(event, data) {
1646
- this.batchQueue.push({ event, data, timestamp: Date.now() });
1647
- if (this.batchQueue.length >= this.options.batching.maxBatchSize) {
1648
- this.flushBatch();
1649
- } else if (!this.batchTimer) {
1650
- this.batchTimer = setTimeout(() => {
1651
- this.flushBatch();
1652
- }, this.options.batching.flushInterval);
1653
- }
1654
- }
1655
- /**
1656
- * Flush batch queue
1657
- */
1658
- async flushBatch() {
1659
- if (this.batchTimer) {
1660
- clearTimeout(this.batchTimer);
1661
- this.batchTimer = null;
1662
- }
1663
- const batch = this.batchQueue.splice(0);
1664
- for (const { event, data } of batch) {
1665
- await this.emitImmediate(event, data);
1666
- }
1667
- }
1668
- /**
1669
- * Register event listener with options
1670
- */
1671
- on(event, listener, options = {}) {
1672
- if (typeof listener !== "function") {
1673
- throw new Error("Listener must be a function");
1674
- }
1675
- if (!this.listeners.has(event)) {
1676
- this.listeners.set(event, []);
1677
- }
1678
- const listeners = this.listeners.get(event);
1679
- if (listeners.length >= this.options.maxListeners) {
1680
- console.warn(`[EventBus] Max listeners (${this.options.maxListeners}) reached for event: ${event}`);
1681
- }
1682
- const listenerId = this.generateListenerId(event);
1683
- const listenerObj = {
1684
- listener,
1685
- listenerId,
1686
- priority: options.priority !== void 0 ? options.priority : this.options.defaultPriority,
1687
- condition: options.condition || null,
1688
- timeout: options.timeout || null,
1689
- options
1690
- };
1691
- listener.__listenerId = listenerId;
1692
- listener.__event = event;
1693
- if (this.options.enablePriority) {
1694
- const insertIndex = listeners.findIndex((l) => l.priority < listenerObj.priority);
1695
- if (insertIndex === -1) {
1696
- listeners.push(listenerObj);
1697
- } else {
1698
- listeners.splice(insertIndex, 0, listenerObj);
1699
- }
1700
- } else {
1701
- listeners.push(listenerObj);
1702
- }
1703
- return listenerId;
1704
- }
1705
- /**
1706
- * Register one-time listener
1707
- */
1708
- once(event, listener, options = {}) {
1709
- const onceListener = (...args) => {
1710
- this.off(event, onceListener.__listenerId);
1711
- return listener.call(this, ...args);
1712
- };
1713
- if (options.timeout) {
1714
- const timeoutId = setTimeout(() => {
1715
- this.off(event, onceListener.__listenerId);
1716
- if (this.options.debug) {
1717
- console.warn(`[EventBus] Listener timeout for event: ${event}`);
1718
- }
1719
- }, options.timeout);
1720
- onceListener.__cleanup = () => clearTimeout(timeoutId);
1721
- }
1722
- return this.on(event, onceListener, options);
1723
- }
1724
- /**
1725
- * Remove listener
1726
- */
1727
- off(event, listenerId) {
1728
- if (!this.listeners.has(event)) {
1729
- return false;
1730
- }
1731
- const listeners = this.listeners.get(event);
1732
- const index = listeners.findIndex((l) => l.listenerId === listenerId);
1733
- if (index !== -1) {
1734
- const listenerObj = listeners[index];
1735
- if (listenerObj.listener.__cleanup) {
1736
- listenerObj.listener.__cleanup();
1737
- }
1738
- listeners.splice(index, 1);
1739
- if (listeners.length === 0) {
1740
- this.listeners.delete(event);
1741
- }
1742
- return true;
1743
- }
1744
- return false;
1745
- }
1746
- /**
1747
- * Remove all listeners for an event
1748
- */
1749
- removeAllListeners(event) {
1750
- if (event) {
1751
- this.listeners.delete(event);
1752
- } else {
1753
- this.listeners.clear();
1754
- }
1755
- }
1756
- /**
1757
- * Get event listeners with wildcard support
1758
- */
1759
- getEventListeners(event) {
1760
- const listeners = [];
1761
- if (this.listeners.has(event)) {
1762
- listeners.push(...this.listeners.get(event));
1763
- }
1764
- if (this.options.enableWildcards) {
1765
- for (const [pattern, patternListeners] of this.listeners) {
1766
- if (pattern.includes("*") && this.matchPattern(pattern, event)) {
1767
- listeners.push(...patternListeners);
1768
- }
1769
- }
1770
- }
1771
- if (this.options.enablePriority) {
1772
- listeners.sort((a, b) => b.priority - a.priority);
1773
- }
1774
- return listeners;
1775
- }
1776
- /**
1777
- * Execute listener with options
1778
- */
1779
- async executeListener(listener, event, data, options = {}) {
1780
- try {
1781
- if (options.condition && !options.condition(data)) {
1782
- return;
1783
- }
1784
- const result = listener.call(this, data, event);
1785
- if (result && typeof result.then === "function") {
1786
- await result;
1787
- }
1788
- return result;
1789
- } catch (error) {
1790
- this.handleError(error, event, data);
1791
- }
1792
- }
1793
- /**
1794
- * Run middleware chain
1795
- */
1796
- async runMiddleware(event, data) {
1797
- if (this.middleware.length === 0) return;
1798
- let index = 0;
1799
- const next = async () => {
1800
- if (index < this.middleware.length) {
1801
- const middleware = this.middleware[index++];
1802
- await middleware(event, data, next);
1803
- }
1804
- };
1805
- await next();
1806
- }
1807
- /**
1808
- * Handle errors
1809
- */
1810
- handleError(error, event, data) {
1811
- if (this.options.errorHandler) {
1812
- this.options.errorHandler(error, event, data);
1813
- } else if (this.options.debug) {
1814
- console.error(`[EventBus] Error in event ${event}:`, error, data);
1815
- }
1816
- this.emitSync("eventbus:error", { error, event, data });
1817
- }
1818
- /**
1819
- * Synchronous emit
1820
- */
1821
- emitSync(event, data = null) {
1822
- try {
1823
- const listeners = this.getEventListeners(event);
1824
- listeners.forEach((listenerObj) => {
1825
- try {
1826
- if (!listenerObj.options.condition || listenerObj.options.condition(data)) {
1827
- listenerObj.listener.call(this, data, event);
1828
- }
1829
- } catch (error) {
1830
- this.handleError(error, event, data);
1831
- }
1832
- });
1833
- this.stats.eventsEmitted++;
1834
- this.stats.listenersExecuted += listeners.length;
1835
- } catch (error) {
1836
- this.stats.errorsOccurred++;
1837
- this.handleError(error, event, data);
1838
- }
1839
- }
1840
- /**
1841
- * Register action handler
1842
- */
1843
- registerAction(action, handler) {
1844
- if (typeof handler !== "function") {
1845
- throw new Error("Action handler must be a function");
1846
- }
1847
- this.actionHandlers.set(action, handler);
1848
- if (this.options.debug) {
1849
- console.log(`[EventBus] Registered action: ${action}`);
1850
- }
1851
- }
1852
- /**
1853
- * Register multiple actions
1854
- */
1855
- registerActions(actions) {
1856
- Object.entries(actions).forEach(([action, handler]) => {
1857
- this.registerAction(action, handler);
1858
- });
1859
- }
1860
- /**
1861
- * Get registered actions
1862
- */
1863
- getRegisteredActions() {
1864
- return Array.from(this.actionHandlers.keys());
1865
- }
1866
- /**
1867
- * Handle action event (called by DOM integration)
1868
- */
1869
- handleAction(action, element, event, data) {
1870
- const handler = this.actionHandlers.get(action);
1871
- if (!handler) {
1872
- if (this.options.debug) {
1873
- console.warn(`[EventBus] No handler registered for action: ${action}`);
1874
- }
1875
- return;
1876
- }
1877
- try {
1878
- handler.call(element, {
1879
- element,
1880
- event,
1881
- data,
1882
- emit: this.emit.bind(this),
1883
- emitSync: this.emitSync.bind(this)
1884
- });
1885
- } catch (error) {
1886
- this.handleError(error, `action:${action}`, { element, event, data });
1887
- }
1888
- }
1889
- /**
1890
- * Generate unique listener ID
1891
- */
1892
- generateListenerId(event) {
1893
- return `${event}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1894
- }
1895
- /**
1896
- * Update performance stats
1897
- */
1898
- updatePerformanceStats(duration) {
1899
- const count = this.stats.eventsEmitted;
1900
- this.stats.averageEmitTime = (this.stats.averageEmitTime * (count - 1) + duration) / count;
1901
- }
1902
- /**
1903
- * Get statistics
1904
- */
1905
- getStats() {
1906
- return { ...this.stats };
1907
- }
1908
- /**
1909
- * Reset statistics
1910
- */
1911
- resetStats() {
1912
- this.stats = {
1913
- eventsEmitted: 0,
1914
- listenersExecuted: 0,
1915
- errorsOccurred: 0,
1916
- averageEmitTime: 0,
1917
- throttledEvents: 0,
1918
- filteredEvents: 0
1919
- };
1920
- }
1921
- /**
1922
- * Destroy event bus
1923
- */
1924
- destroy() {
1925
- this.removeAllListeners();
1926
- this.actionHandlers.clear();
1927
- this.handlers.clear();
1928
- this.middleware = [];
1929
- this.throttledEmitters.clear();
1930
- this.debouncedEmitters.clear();
1931
- if (this.batchTimer) {
1932
- clearTimeout(this.batchTimer);
1933
- }
1934
- }
1935
- };
1936
- function createEventBus(options = {}) {
1937
- return new EventBus(options);
1938
- }
1939
- var globalEventBus = createEventBus();
1940
- var emit = globalEventBus.emit.bind(globalEventBus);
1941
- var emitSync = globalEventBus.emitSync.bind(globalEventBus);
1942
- var on = globalEventBus.on.bind(globalEventBus);
1943
- var once = globalEventBus.once.bind(globalEventBus);
1944
- var off = globalEventBus.off.bind(globalEventBus);
1945
- var registerAction = globalEventBus.registerAction.bind(globalEventBus);
1946
- var handleAction = globalEventBus.handleAction.bind(globalEventBus);
1947
-
1948
- // ../core/src/events/dom-integration.js
1949
- var DOMEventIntegration = class {
1950
- constructor(eventBus = globalEventBus, options = {}) {
1951
- this.eventBus = eventBus;
1952
- this.options = {
1953
- debug: false,
1954
- debounceDelay: 150,
1955
- throttleDelay: 100,
1956
- enableDelegation: true,
1957
- enableDebounce: true,
1958
- enableThrottle: false,
1959
- ...options
1960
- };
1961
- this.boundHandlers = /* @__PURE__ */ new Map();
1962
- this.activeElement = null;
1963
- this.isInitialized = false;
1964
- this.handleClick = this.handleClick.bind(this);
1965
- this.handleChange = this.handleChange.bind(this);
1966
- this.handleInput = this.handleInput.bind(this);
1967
- this.handleSubmit = this.handleSubmit.bind(this);
1968
- this.handleKeydown = this.handleKeydown.bind(this);
1969
- this.handleFocus = this.handleFocus.bind(this);
1970
- this.handleBlur = this.handleBlur.bind(this);
1971
- }
1972
- /**
1973
- * Initialize DOM event listeners
1974
- * @param {HTMLElement} rootElement - Root element to attach listeners to (default: document)
1975
- */
1976
- initialize(rootElement = document) {
1977
- if (this.isInitialized) {
1978
- console.warn("[DOMEventIntegration] Already initialized");
1979
- return;
1980
- }
1981
- if (typeof window === "undefined" || !rootElement) {
1982
- console.warn("[DOMEventIntegration] Cannot initialize: no DOM environment");
1983
- return;
1984
- }
1985
- this.rootElement = rootElement;
1986
- this.setupDOMEventListeners();
1987
- this.isInitialized = true;
1988
- if (this.options.debug) {
1989
- console.log("[DOMEventIntegration] Initialized with options:", this.options);
1990
- }
1991
- }
1992
- /**
1993
- * Set up delegated DOM event listeners
1994
- * @private
1995
- */
1996
- setupDOMEventListeners() {
1997
- const clickHandler = this.createDelegatedHandler("click", this.handleClick);
1998
- this.rootElement.addEventListener("click", clickHandler, { passive: false });
1999
- this.boundHandlers.set("click", clickHandler);
2000
- const changeHandler = this.options.enableDebounce ? this.debounce(this.createDelegatedHandler("change", this.handleChange), this.options.debounceDelay) : this.createDelegatedHandler("change", this.handleChange);
2001
- this.rootElement.addEventListener("change", changeHandler, { passive: true });
2002
- this.boundHandlers.set("change", changeHandler);
2003
- const inputHandler = this.options.enableDebounce ? this.debounce(this.createDelegatedHandler("input", this.handleInput), this.options.debounceDelay) : this.createDelegatedHandler("input", this.handleInput);
2004
- this.rootElement.addEventListener("input", inputHandler, { passive: true });
2005
- this.boundHandlers.set("input", inputHandler);
2006
- const submitHandler = this.createDelegatedHandler("submit", this.handleSubmit);
2007
- this.rootElement.addEventListener("submit", submitHandler, { passive: false });
2008
- this.boundHandlers.set("submit", submitHandler);
2009
- const keydownHandler = this.createDelegatedHandler("keydown", this.handleKeydown);
2010
- this.rootElement.addEventListener("keydown", keydownHandler, { passive: false });
2011
- this.boundHandlers.set("keydown", keydownHandler);
2012
- const focusHandler = this.createDelegatedHandler("focus", this.handleFocus);
2013
- this.rootElement.addEventListener("focus", focusHandler, { passive: true, capture: true });
2014
- this.boundHandlers.set("focus", focusHandler);
2015
- const blurHandler = this.createDelegatedHandler("blur", this.handleBlur);
2016
- this.rootElement.addEventListener("blur", blurHandler, { passive: true, capture: true });
2017
- this.boundHandlers.set("blur", blurHandler);
2018
- }
2019
- /**
2020
- * Create a delegated event handler
2021
- * @private
2022
- */
2023
- createDelegatedHandler(eventType, handler) {
2024
- return (event) => {
2025
- const target = event.target;
2026
- if (!target) return;
2027
- const actionElement = this.options.enableDelegation ? target.closest("[data-action]") : target.hasAttribute?.("data-action") ? target : null;
2028
- if (actionElement) {
2029
- handler(actionElement, event);
2030
- } else {
2031
- handler(target, event);
2032
- }
2033
- };
2034
- }
2035
- /**
2036
- * Handle click events
2037
- * @private
2038
- */
2039
- handleClick(element, event) {
2040
- const action = element.getAttribute?.("data-action");
2041
- if (action) {
2042
- this.handleDataAction(element, event, action);
2043
- }
2044
- this.eventBus.emitSync("dom:click", {
2045
- element,
2046
- event,
2047
- action,
2048
- data: this.parseDataAttributes(element)
2049
- });
2050
- }
2051
- /**
2052
- * Handle change events
2053
- * @private
2054
- */
2055
- handleChange(element, event) {
2056
- const action = element.getAttribute?.("data-action");
2057
- if (action) {
2058
- this.handleDataAction(element, event, action);
2059
- }
2060
- this.eventBus.emitSync("dom:change", {
2061
- element,
2062
- event,
2063
- value: element.value,
2064
- action,
2065
- data: this.parseDataAttributes(element)
2066
- });
2067
- }
2068
- /**
2069
- * Handle input events
2070
- * @private
2071
- */
2072
- handleInput(element, event) {
2073
- const action = element.getAttribute?.("data-action");
2074
- if (action) {
2075
- this.handleDataAction(element, event, action);
2076
- }
2077
- this.eventBus.emitSync("dom:input", {
2078
- element,
2079
- event,
2080
- value: element.value,
2081
- action,
2082
- data: this.parseDataAttributes(element)
2083
- });
2084
- }
2085
- /**
2086
- * Handle submit events
2087
- * @private
2088
- */
2089
- handleSubmit(element, event) {
2090
- const action = element.getAttribute?.("data-action");
2091
- if (action) {
2092
- event.preventDefault();
2093
- this.handleDataAction(element, event, action);
2094
- }
2095
- this.eventBus.emitSync("dom:submit", {
2096
- element,
2097
- event,
2098
- action,
2099
- formData: this.extractFormData(element),
2100
- data: this.parseDataAttributes(element)
2101
- });
2102
- }
2103
- /**
2104
- * Handle keydown events
2105
- * @private
2106
- */
2107
- handleKeydown(element, event) {
2108
- const action = element.getAttribute?.("data-action");
2109
- const keyAction = element.getAttribute?.(`data-key-${event.key.toLowerCase()}`);
2110
- if (action && this.shouldTriggerKeyAction(event)) {
2111
- this.handleDataAction(element, event, action);
2112
- }
2113
- if (keyAction) {
2114
- this.handleDataAction(element, event, keyAction);
2115
- }
2116
- this.eventBus.emitSync("dom:keydown", {
2117
- element,
2118
- event,
2119
- key: event.key,
2120
- code: event.code,
2121
- action,
2122
- keyAction,
2123
- data: this.parseDataAttributes(element)
2124
- });
2125
- }
2126
- /**
2127
- * Handle focus events
2128
- * @private
2129
- */
2130
- handleFocus(element, event) {
2131
- this.activeElement = element;
2132
- this.eventBus.emitSync("dom:focus", {
2133
- element,
2134
- event,
2135
- data: this.parseDataAttributes(element)
2136
- });
2137
- }
2138
- /**
2139
- * Handle blur events
2140
- * @private
2141
- */
2142
- handleBlur(element, event) {
2143
- if (this.activeElement === element) {
2144
- this.activeElement = null;
2145
- }
2146
- this.eventBus.emitSync("dom:blur", {
2147
- element,
2148
- event,
2149
- data: this.parseDataAttributes(element)
2150
- });
2151
- }
2152
- /**
2153
- * Handle data-action attributes
2154
- * @private
2155
- */
2156
- handleDataAction(element, event, action) {
2157
- if (!action) return;
2158
- const data = this.parseDataAttributes(element);
2159
- this.eventBus.emitSync("dom:action", {
2160
- action,
2161
- element,
2162
- event,
2163
- data
2164
- });
2165
- this.eventBus.handleAction(action, element, event, data);
2166
- if (this.options.debug) {
2167
- console.log(`[DOMEventIntegration] Action triggered: ${action}`, {
2168
- element,
2169
- event: event.type,
2170
- data
2171
- });
2172
- }
2173
- }
2174
- /**
2175
- * Parse data attributes from an element
2176
- * @private
2177
- */
2178
- parseDataAttributes(element) {
2179
- if (!element?.attributes) return {};
2180
- const data = {};
2181
- Array.from(element.attributes).forEach((attr) => {
2182
- if (attr.name.startsWith("data-") && attr.name !== "data-action") {
2183
- const key = attr.name.slice(5).replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
2184
- let value = attr.value;
2185
- try {
2186
- if (value === "true") value = true;
2187
- else if (value === "false") value = false;
2188
- else if (value === "null") value = null;
2189
- else if (value === "undefined") value = void 0;
2190
- else if (/^\d+$/.test(value)) value = parseInt(value, 10);
2191
- else if (/^\d*\.\d+$/.test(value)) value = parseFloat(value);
2192
- else if (value.startsWith("{") && value.endsWith("}") || value.startsWith("[") && value.endsWith("]")) {
2193
- value = JSON.parse(value);
2194
- }
2195
- } catch {
2196
- }
2197
- data[key] = value;
2198
- }
2199
- });
2200
- return data;
2201
- }
2202
- /**
2203
- * Extract form data from a form element
2204
- * @private
2205
- */
2206
- extractFormData(formElement) {
2207
- if (!formElement || formElement.tagName !== "FORM") {
2208
- return {};
2209
- }
2210
- const formData = new FormData(formElement);
2211
- const data = {};
2212
- for (const [key, value] of formData.entries()) {
2213
- if (data[key]) {
2214
- if (Array.isArray(data[key])) {
2215
- data[key].push(value);
2216
- } else {
2217
- data[key] = [data[key], value];
2218
- }
2219
- } else {
2220
- data[key] = value;
2221
- }
2222
- }
2223
- return data;
2224
- }
2225
- /**
2226
- * Check if a key event should trigger an action
2227
- * @private
2228
- */
2229
- shouldTriggerKeyAction(event) {
2230
- const triggerKeys = ["Enter", "Space", "Escape"];
2231
- return triggerKeys.includes(event.key);
2232
- }
2233
- /**
2234
- * Debounce utility function
2235
- * @private
2236
- */
2237
- debounce(func, wait) {
2238
- let timeout;
2239
- return function executedFunction(...args) {
2240
- const later = () => {
2241
- clearTimeout(timeout);
2242
- func.apply(this, args);
2243
- };
2244
- clearTimeout(timeout);
2245
- timeout = setTimeout(later, wait);
2246
- };
2247
- }
2248
- /**
2249
- * Throttle utility function
2250
- * @private
2251
- */
2252
- throttle(func, limit) {
2253
- let inThrottle;
2254
- return function executedFunction(...args) {
2255
- if (!inThrottle) {
2256
- func.apply(this, args);
2257
- inThrottle = true;
2258
- setTimeout(() => inThrottle = false, limit);
2259
- }
2260
- };
2261
- }
2262
- /**
2263
- * Add custom event listener
2264
- * @param {string} eventType - Event type
2265
- * @param {Function} handler - Event handler
2266
- * @param {Object} options - Event listener options
2267
- */
2268
- addCustomListener(eventType, handler, options = {}) {
2269
- const wrappedHandler = this.createDelegatedHandler(eventType, handler);
2270
- this.rootElement.addEventListener(eventType, wrappedHandler, options);
2271
- this.boundHandlers.set(`custom:${eventType}`, wrappedHandler);
2272
- }
2273
- /**
2274
- * Remove custom event listener
2275
- * @param {string} eventType - Event type
2276
- */
2277
- removeCustomListener(eventType) {
2278
- const handler = this.boundHandlers.get(`custom:${eventType}`);
2279
- if (handler) {
2280
- this.rootElement.removeEventListener(eventType, handler);
2281
- this.boundHandlers.delete(`custom:${eventType}`);
2282
- }
2283
- }
2284
- /**
2285
- * Register action handlers in bulk
2286
- * @param {Object} actions - Object mapping action names to handlers
2287
- */
2288
- registerActions(actions) {
2289
- this.eventBus.registerActions(actions);
2290
- }
2291
- /**
2292
- * Get the currently active (focused) element
2293
- * @returns {HTMLElement|null}
2294
- */
2295
- getActiveElement() {
2296
- return this.activeElement;
2297
- }
2298
- /**
2299
- * Trigger an action programmatically
2300
- * @param {string} action - Action name
2301
- * @param {HTMLElement} element - Target element
2302
- * @param {Object} data - Additional data
2303
- */
2304
- triggerAction(action, element, data = {}) {
2305
- const syntheticEvent = new CustomEvent("synthetic", {
2306
- bubbles: true,
2307
- cancelable: true,
2308
- detail: data
2309
- });
2310
- this.eventBus.handleAction(action, element, syntheticEvent, data);
2311
- }
2312
- /**
2313
- * Clean up event listeners
2314
- */
2315
- destroy() {
2316
- if (!this.isInitialized) return;
2317
- this.boundHandlers.forEach((handler, eventType) => {
2318
- this.rootElement.removeEventListener(
2319
- eventType.replace("custom:", ""),
2320
- handler
2321
- );
2322
- });
2323
- this.boundHandlers.clear();
2324
- this.activeElement = null;
2325
- this.isInitialized = false;
2326
- if (this.options.debug) {
2327
- console.log("[DOMEventIntegration] Destroyed");
2328
- }
2329
- }
2330
- };
2331
- var globalDOMIntegration = new DOMEventIntegration(globalEventBus, {
2332
- debug: typeof process !== "undefined" && true
2333
- });
2334
- if (typeof window !== "undefined") {
2335
- if (document.readyState === "loading") {
2336
- document.addEventListener("DOMContentLoaded", () => {
2337
- globalDOMIntegration.initialize();
2338
- });
2339
- } else {
2340
- globalDOMIntegration.initialize();
2341
- }
2342
- }
2343
-
2344
- // ../core/src/events/index.js
2345
- var eventSystem2 = {
2346
- // Core bus
2347
- bus: globalEventBus,
2348
- dom: globalDOMIntegration,
2349
- // Quick access methods
2350
- emit: globalEventBus.emit.bind(globalEventBus),
2351
- emitSync: globalEventBus.emitSync.bind(globalEventBus),
2352
- on: globalEventBus.on.bind(globalEventBus),
2353
- once: globalEventBus.once.bind(globalEventBus),
2354
- off: globalEventBus.off.bind(globalEventBus),
2355
- // Action methods
2356
- registerAction: globalEventBus.registerAction.bind(globalEventBus),
2357
- registerActions: globalEventBus.registerActions.bind(globalEventBus),
2358
- handleAction: globalEventBus.handleAction.bind(globalEventBus),
2359
- // Statistics and debugging
2360
- getStats: globalEventBus.getStats.bind(globalEventBus),
2361
- resetStats: globalEventBus.resetStats.bind(globalEventBus),
2362
- // Lifecycle
2363
- destroy() {
2364
- globalEventBus.destroy();
2365
- globalDOMIntegration.destroy();
2366
- }
2367
- };
2368
-
2369
1
  // ../core/src/index.js
2370
2
  var scopeCounter = { value: 0 };
2371
3
  function generateScopeId() {