@coherent.js/fastify 1.0.0-beta.5 → 1.0.0-beta.6

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,1492 +1,8 @@
1
- // ../core/src/core/object-utils.js
2
- function validateComponent(component, path = "root") {
3
- if (component === null || component === void 0) {
4
- throw new Error(`Invalid component at ${path}: null or undefined`);
5
- }
6
- if (["string", "number", "boolean"].includes(typeof component)) {
7
- return true;
8
- }
9
- if (typeof component === "function") {
10
- return true;
11
- }
12
- if (Array.isArray(component)) {
13
- component.forEach((child, index) => {
14
- validateComponent(child, `${path}[${index}]`);
15
- });
16
- return true;
17
- }
18
- if (typeof component === "object") {
19
- const keys = Object.keys(component);
20
- if (keys.length === 0) {
21
- throw new Error(`Empty object at ${path}`);
22
- }
23
- keys.forEach((key) => {
24
- const value = component[key];
25
- if (!/^[a-zA-Z][a-zA-Z0-9-]*$/.test(key) && key !== "text") {
26
- console.warn(`Potentially invalid tag name at ${path}: ${key}`);
27
- }
28
- if (value && typeof value === "object" && !Array.isArray(value)) {
29
- if (value.children) {
30
- validateComponent(value.children, `${path}.${key}.children`);
31
- }
32
- } else if (value && typeof value !== "string" && typeof value !== "number" && typeof value !== "function") {
33
- throw new Error(`Invalid value type at ${path}.${key}: ${typeof value}`);
34
- }
35
- });
36
- return true;
37
- }
38
- throw new Error(`Invalid component type at ${path}: ${typeof component}`);
39
- }
40
- function isCoherentObject(obj) {
41
- if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
42
- return false;
43
- }
44
- const keys = Object.keys(obj);
45
- if (keys.length === 0) {
46
- return false;
47
- }
48
- return keys.every((key) => {
49
- if (key === "text") return true;
50
- return /^[a-zA-Z][a-zA-Z0-9-]*$/.test(key);
51
- });
52
- }
53
- function extractProps(coherentObj) {
54
- if (!isCoherentObject(coherentObj)) {
55
- return {};
56
- }
57
- const props = {};
58
- const keys = Object.keys(coherentObj);
59
- keys.forEach((tag) => {
60
- const value = coherentObj[tag];
61
- if (value && typeof value === "object" && !Array.isArray(value)) {
62
- props[tag] = { ...value };
63
- } else {
64
- props[tag] = { text: value };
65
- }
66
- });
67
- return props;
68
- }
69
- function hasChildren(component) {
70
- if (Array.isArray(component)) {
71
- return component.length > 0;
72
- }
73
- if (isCoherentObject(component)) {
74
- if (component.children !== void 0 && component.children !== null) {
75
- return Array.isArray(component.children) ? component.children.length > 0 : true;
76
- }
77
- const keys = Object.keys(component);
78
- return keys.some((key) => {
79
- const value = component[key];
80
- return value && typeof value === "object" && value.children;
81
- });
82
- }
83
- return false;
84
- }
85
- function normalizeChildren(children) {
86
- if (children === null || children === void 0) {
87
- return [];
88
- }
89
- if (Array.isArray(children)) {
90
- return children.flat().filter((child) => child !== null && child !== void 0);
91
- }
92
- return [children];
93
- }
94
-
95
- // ../core/src/performance/monitor.js
96
- function createPerformanceMonitor(options = {}) {
97
- const opts = {
98
- enabled: true,
99
- metrics: {
100
- custom: {}
101
- },
102
- sampling: {
103
- enabled: false,
104
- rate: 1,
105
- strategy: "random"
106
- },
107
- reporting: {
108
- enabled: false,
109
- interval: 6e4,
110
- format: "json",
111
- batch: {
112
- enabled: false,
113
- maxSize: 100,
114
- flushInterval: 5e3
115
- },
116
- onReport: null
117
- },
118
- alerts: {
119
- enabled: true,
120
- debounceMs: 5e3,
121
- rules: []
122
- },
123
- resources: {
124
- enabled: false,
125
- track: ["memory"],
126
- interval: 1e3
127
- },
128
- profiling: {
129
- enabled: false,
130
- mode: "production",
131
- flamegraph: false,
132
- tracing: {
133
- enabled: false,
134
- sampleRate: 0.01
135
- }
136
- },
137
- ...options
138
- };
139
- opts.reporting.batch = {
140
- enabled: false,
141
- maxSize: 100,
142
- flushInterval: 5e3,
143
- ...options.reporting?.batch || {}
144
- };
145
- const metrics = {
146
- builtin: {
147
- renderTime: { type: "histogram", unit: "ms", values: [] },
148
- componentCount: { type: "counter", unit: "renders", value: 0 },
149
- errorCount: { type: "counter", unit: "errors", value: 0 },
150
- memoryUsage: { type: "gauge", unit: "MB", values: [] }
151
- },
152
- custom: {}
153
- };
154
- Object.entries(opts.metrics.custom).forEach(([name, config]) => {
155
- metrics.custom[name] = {
156
- type: config.type || "counter",
157
- unit: config.unit || "",
158
- threshold: config.threshold,
159
- values: config.type === "histogram" ? [] : void 0,
160
- value: config.type === "counter" || config.type === "gauge" ? 0 : void 0
161
- };
162
- });
163
- const samplingState = {
164
- count: 0,
165
- sampled: 0,
166
- adaptiveRate: opts.sampling.rate
167
- };
168
- const reportingState = {
169
- batch: [],
170
- lastReport: Date.now(),
171
- reportTimer: null,
172
- flushTimer: null
173
- };
174
- const alertState = {
175
- triggered: /* @__PURE__ */ new Map(),
176
- history: []
177
- };
178
- const resourceState = {
179
- samples: [],
180
- timer: null
181
- };
182
- const profilingState = {
183
- traces: [],
184
- flamegraphData: []
185
- };
186
- const stats = {
187
- metricsRecorded: 0,
188
- sampleRate: opts.sampling.rate,
189
- reportsGenerated: 0,
190
- alertsTriggered: 0
191
- };
192
- function shouldSample() {
193
- if (!opts.sampling.enabled) return true;
194
- samplingState.count++;
195
- if (opts.sampling.strategy === "random") {
196
- return Math.random() < samplingState.adaptiveRate;
197
- } else if (opts.sampling.strategy === "deterministic") {
198
- return samplingState.count % Math.ceil(1 / samplingState.adaptiveRate) === 0;
199
- } else if (opts.sampling.strategy === "adaptive") {
200
- const recentRenderTimes = metrics.builtin.renderTime.values.slice(-10);
201
- if (recentRenderTimes.length > 0) {
202
- const avgTime = recentRenderTimes.reduce((a, b) => a + b, 0) / recentRenderTimes.length;
203
- samplingState.adaptiveRate = avgTime > 16 ? Math.min(1, opts.sampling.rate * 2) : opts.sampling.rate;
204
- }
205
- return Math.random() < samplingState.adaptiveRate;
206
- }
207
- return true;
208
- }
209
- function recordMetric(name, value, metadata = {}) {
210
- if (!opts.enabled) return;
211
- if (!shouldSample()) return;
212
- stats.metricsRecorded++;
213
- const builtinMetric = metrics.builtin[name];
214
- if (builtinMetric) {
215
- if (builtinMetric.type === "histogram") {
216
- builtinMetric.values.push(value);
217
- if (builtinMetric.values.length > 1e3) {
218
- builtinMetric.values = builtinMetric.values.slice(-1e3);
219
- }
220
- } else if (builtinMetric.type === "counter") {
221
- builtinMetric.value += value;
222
- } else if (builtinMetric.type === "gauge") {
223
- builtinMetric.values.push(value);
224
- if (builtinMetric.values.length > 100) {
225
- builtinMetric.values = builtinMetric.values.slice(-100);
226
- }
227
- }
228
- }
229
- const customMetric = metrics.custom[name];
230
- if (customMetric) {
231
- if (customMetric.type === "histogram") {
232
- customMetric.values = customMetric.values || [];
233
- customMetric.values.push(value);
234
- if (customMetric.values.length > 1e3) {
235
- customMetric.values = customMetric.values.slice(-1e3);
236
- }
237
- } else if (customMetric.type === "counter") {
238
- customMetric.value = (customMetric.value || 0) + value;
239
- } else if (customMetric.type === "gauge") {
240
- customMetric.values = customMetric.values || [];
241
- customMetric.values.push(value);
242
- if (customMetric.values.length > 100) {
243
- customMetric.values = customMetric.values.slice(-100);
244
- }
245
- }
246
- if (customMetric.threshold) {
247
- const currentValue = customMetric.type === "histogram" || customMetric.type === "gauge" ? customMetric.values[customMetric.values.length - 1] : customMetric.value;
248
- if (currentValue > customMetric.threshold) {
249
- checkAlerts(name, currentValue);
250
- }
251
- }
252
- }
253
- if (opts.reporting.enabled && opts.reporting.batch.enabled) {
254
- reportingState.batch.push({
255
- metric: name,
256
- value,
257
- metadata,
258
- timestamp: Date.now()
259
- });
260
- if (reportingState.batch.length >= opts.reporting.batch.maxSize) {
261
- flushBatch();
262
- }
263
- }
264
- checkAlerts(name, value);
265
- }
266
- function checkAlerts(metric, value) {
267
- if (!opts.alerts.enabled) return;
268
- opts.alerts.rules.forEach((rule) => {
269
- if (rule.metric !== metric) return;
270
- let triggered = false;
271
- if (rule.condition === "exceeds" && value > rule.threshold) {
272
- triggered = true;
273
- } else if (rule.condition === "below" && value < rule.threshold) {
274
- triggered = true;
275
- } else if (rule.condition === "equals" && value === rule.threshold) {
276
- triggered = true;
277
- }
278
- if (triggered) {
279
- const alertKey = `${rule.metric}-${rule.condition}-${rule.threshold}`;
280
- const lastTriggered = alertState.triggered.get(alertKey);
281
- const now = Date.now();
282
- if (!lastTriggered || now - lastTriggered > opts.alerts.debounceMs) {
283
- alertState.triggered.set(alertKey, now);
284
- alertState.history.push({
285
- rule,
286
- value,
287
- timestamp: now
288
- });
289
- stats.alertsTriggered++;
290
- if (rule.action) {
291
- rule.action(value, rule);
292
- }
293
- }
294
- }
295
- });
296
- }
297
- function flushBatch() {
298
- if (reportingState.batch.length === 0) return;
299
- const batch = [...reportingState.batch];
300
- reportingState.batch = [];
301
- if (opts.reporting.onReport) {
302
- opts.reporting.onReport({ type: "batch", data: batch });
303
- }
304
- }
305
- function generateReport() {
306
- const report = {
307
- timestamp: Date.now(),
308
- statistics: { ...stats },
309
- metrics: {}
310
- };
311
- Object.entries(metrics.builtin).forEach(([name, metric]) => {
312
- if (metric.type === "histogram") {
313
- report.metrics[name] = {
314
- type: "histogram",
315
- unit: metric.unit,
316
- count: metric.values.length,
317
- min: metric.values.length > 0 ? Math.min(...metric.values) : 0,
318
- max: metric.values.length > 0 ? Math.max(...metric.values) : 0,
319
- avg: metric.values.length > 0 ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length : 0,
320
- p50: percentile(metric.values, 0.5),
321
- p95: percentile(metric.values, 0.95),
322
- p99: percentile(metric.values, 0.99)
323
- };
324
- } else if (metric.type === "counter") {
325
- report.metrics[name] = {
326
- type: "counter",
327
- unit: metric.unit,
328
- value: metric.value
329
- };
330
- } else if (metric.type === "gauge") {
331
- report.metrics[name] = {
332
- type: "gauge",
333
- unit: metric.unit,
334
- current: metric.values.length > 0 ? metric.values[metric.values.length - 1] : 0,
335
- avg: metric.values.length > 0 ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length : 0
336
- };
337
- }
338
- });
339
- Object.entries(metrics.custom).forEach(([name, metric]) => {
340
- if (metric.type === "histogram") {
341
- report.metrics[name] = {
342
- type: "histogram",
343
- unit: metric.unit,
344
- count: metric.values?.length || 0,
345
- min: metric.values?.length > 0 ? Math.min(...metric.values) : 0,
346
- max: metric.values?.length > 0 ? Math.max(...metric.values) : 0,
347
- avg: metric.values?.length > 0 ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length : 0,
348
- p95: percentile(metric.values || [], 0.95),
349
- p99: percentile(metric.values || [], 0.99)
350
- };
351
- } else if (metric.type === "counter") {
352
- report.metrics[name] = {
353
- type: "counter",
354
- unit: metric.unit,
355
- value: metric.value || 0
356
- };
357
- } else if (metric.type === "gauge") {
358
- report.metrics[name] = {
359
- type: "gauge",
360
- unit: metric.unit,
361
- current: metric.values?.length > 0 ? metric.values[metric.values.length - 1] : 0,
362
- avg: metric.values?.length > 0 ? metric.values.reduce((a, b) => a + b, 0) / metric.values.length : 0
363
- };
364
- }
365
- });
366
- report.alerts = {
367
- total: alertState.history.length,
368
- recent: alertState.history.slice(-10)
369
- };
370
- if (opts.resources.enabled) {
371
- report.resources = {
372
- samples: resourceState.samples.slice(-20)
373
- };
374
- }
375
- stats.reportsGenerated++;
376
- if (opts.reporting.onReport) {
377
- opts.reporting.onReport({ type: "report", data: report });
378
- }
379
- return report;
380
- }
381
- function percentile(values, p) {
382
- if (values.length === 0) return 0;
383
- const sorted = [...values].sort((a, b) => a - b);
384
- const index = Math.ceil(sorted.length * p) - 1;
385
- return sorted[Math.max(0, index)];
386
- }
387
- function startResourceMonitoring() {
388
- if (!opts.resources.enabled) return;
389
- const collectResources = () => {
390
- const sample = {
391
- timestamp: Date.now()
392
- };
393
- if (opts.resources.track.includes("memory")) {
394
- if (typeof process !== "undefined" && process.memoryUsage) {
395
- const mem = process.memoryUsage();
396
- sample.memory = {
397
- heapUsed: mem.heapUsed / 1024 / 1024,
398
- heapTotal: mem.heapTotal / 1024 / 1024,
399
- external: mem.external / 1024 / 1024,
400
- rss: mem.rss / 1024 / 1024
401
- };
402
- } else if (typeof performance !== "undefined" && performance.memory) {
403
- sample.memory = {
404
- heapUsed: performance.memory.usedJSHeapSize / 1024 / 1024,
405
- heapTotal: performance.memory.totalJSHeapSize / 1024 / 1024
406
- };
407
- }
408
- }
409
- resourceState.samples.push(sample);
410
- if (resourceState.samples.length > 100) {
411
- resourceState.samples = resourceState.samples.slice(-100);
412
- }
413
- resourceState.timer = setTimeout(collectResources, opts.resources.interval);
414
- };
415
- collectResources();
416
- }
417
- function stopResourceMonitoring() {
418
- if (resourceState.timer) {
419
- clearTimeout(resourceState.timer);
420
- resourceState.timer = null;
421
- }
422
- }
423
- function startReporting() {
424
- if (!opts.reporting.enabled) return;
425
- reportingState.reportTimer = setInterval(() => {
426
- generateReport();
427
- }, opts.reporting.interval);
428
- if (opts.reporting.batch.enabled) {
429
- reportingState.flushTimer = setInterval(() => {
430
- flushBatch();
431
- }, opts.reporting.batch.flushInterval);
432
- }
433
- }
434
- function stopReporting() {
435
- if (reportingState.reportTimer) {
436
- clearInterval(reportingState.reportTimer);
437
- reportingState.reportTimer = null;
438
- }
439
- if (reportingState.flushTimer) {
440
- clearInterval(reportingState.flushTimer);
441
- reportingState.flushTimer = null;
442
- }
443
- flushBatch();
444
- }
445
- function startProfiling() {
446
- if (!opts.profiling.enabled) return;
447
- }
448
- function recordTrace(name, duration, metadata = {}) {
449
- if (!opts.profiling.enabled || !opts.profiling.tracing.enabled) return;
450
- if (Math.random() < opts.profiling.tracing.sampleRate) {
451
- profilingState.traces.push({
452
- name,
453
- duration,
454
- metadata,
455
- timestamp: Date.now()
456
- });
457
- if (profilingState.traces.length > 1e3) {
458
- profilingState.traces = profilingState.traces.slice(-1e3);
459
- }
460
- }
461
- }
462
- function measure(name, fn, metadata = {}) {
463
- if (!opts.enabled) return fn();
464
- const start = performance.now();
465
- try {
466
- const result = fn();
467
- const duration = performance.now() - start;
468
- recordMetric("renderTime", duration, { name, ...metadata });
469
- recordTrace(name, duration, metadata);
470
- return result;
471
- } catch (error) {
472
- recordMetric("errorCount", 1, { name, error: error.message });
473
- throw error;
474
- }
475
- }
476
- async function measureAsync(name, fn, metadata = {}) {
477
- if (!opts.enabled) return fn();
478
- const start = performance.now();
479
- try {
480
- const result = await fn();
481
- const duration = performance.now() - start;
482
- recordMetric("renderTime", duration, { name, ...metadata });
483
- recordTrace(name, duration, metadata);
484
- return result;
485
- } catch (error) {
486
- recordMetric("errorCount", 1, { name, error: error.message });
487
- throw error;
488
- }
489
- }
490
- function addMetric(name, config) {
491
- metrics.custom[name] = {
492
- type: config.type || "counter",
493
- unit: config.unit || "",
494
- threshold: config.threshold,
495
- values: config.type === "histogram" ? [] : void 0,
496
- value: config.type === "counter" || config.type === "gauge" ? 0 : void 0
497
- };
498
- }
499
- function addAlertRule(rule) {
500
- opts.alerts.rules.push(rule);
501
- }
502
- function getStats() {
503
- return {
504
- ...stats,
505
- sampleRate: samplingState.adaptiveRate,
506
- batchSize: reportingState.batch.length,
507
- resourceSamples: resourceState.samples.length,
508
- traces: profilingState.traces.length,
509
- alerts: {
510
- total: alertState.history.length,
511
- unique: alertState.triggered.size
512
- }
513
- };
514
- }
515
- function reset() {
516
- Object.values(metrics.builtin).forEach((metric) => {
517
- if (metric.type === "histogram" || metric.type === "gauge") {
518
- metric.values = [];
519
- } else if (metric.type === "counter") {
520
- metric.value = 0;
521
- }
522
- });
523
- Object.values(metrics.custom).forEach((metric) => {
524
- if (metric.type === "histogram" || metric.type === "gauge") {
525
- metric.values = [];
526
- } else if (metric.type === "counter") {
527
- metric.value = 0;
528
- }
529
- });
530
- samplingState.count = 0;
531
- samplingState.sampled = 0;
532
- reportingState.batch = [];
533
- alertState.history = [];
534
- alertState.triggered.clear();
535
- resourceState.samples = [];
536
- profilingState.traces = [];
537
- stats.metricsRecorded = 0;
538
- stats.reportsGenerated = 0;
539
- stats.alertsTriggered = 0;
540
- }
541
- if (opts.enabled) {
542
- startResourceMonitoring();
543
- startReporting();
544
- startProfiling();
545
- }
546
- return {
547
- recordMetric,
548
- measure,
549
- measureAsync,
550
- addMetric,
551
- addAlertRule,
552
- generateReport,
553
- getStats,
554
- reset,
555
- start() {
556
- opts.enabled = true;
557
- startResourceMonitoring();
558
- startReporting();
559
- startProfiling();
560
- },
561
- stop() {
562
- opts.enabled = false;
563
- stopResourceMonitoring();
564
- stopReporting();
565
- return generateReport();
566
- }
567
- };
568
- }
569
- var performanceMonitor = createPerformanceMonitor();
570
-
571
- // ../core/src/rendering/base-renderer.js
572
- var DEFAULT_RENDERER_CONFIG = {
573
- // Core rendering options
574
- maxDepth: 100,
575
- enableValidation: true,
576
- enableMonitoring: false,
577
- validateInput: true,
578
- // HTML Renderer specific options
579
- enableCache: true,
580
- minify: false,
581
- cacheSize: 1e3,
582
- cacheTTL: 3e5,
583
- // 5 minutes
584
- // Streaming Renderer specific options
585
- chunkSize: 1024,
586
- // Size of each chunk in bytes
587
- bufferSize: 4096,
588
- // Internal buffer size
589
- enableMetrics: false,
590
- // Track streaming metrics
591
- yieldThreshold: 100,
592
- // Yield control after N elements
593
- encoding: "utf8",
594
- // Output encoding
595
- // DOM Renderer specific options
596
- enableHydration: true,
597
- // Enable hydration support
598
- namespace: null,
599
- // SVG namespace support
600
- // Performance options
601
- enablePerformanceTracking: false,
602
- performanceThreshold: 10,
603
- // ms threshold for slow renders
604
- // Development options
605
- enableDevWarnings: typeof process !== "undefined" && process.env && true,
606
- enableDebugLogging: false,
607
- // Error handling options
608
- errorFallback: "",
609
- // Fallback content on errors
610
- throwOnError: true
611
- // Whether to throw or return fallback
612
- };
613
- var BaseRenderer = class {
614
- constructor(options = {}) {
615
- this.config = this.validateAndMergeConfig(options);
616
- this.metrics = {
617
- startTime: null,
618
- endTime: null,
619
- elementsProcessed: 0
620
- };
621
- }
622
- /**
623
- * Validate and merge configuration options
624
- */
625
- validateAndMergeConfig(options) {
626
- const config = { ...DEFAULT_RENDERER_CONFIG, ...options };
627
- if (typeof config.maxDepth !== "number") {
628
- throw new Error("maxDepth must be a number");
629
- }
630
- if (config.maxDepth <= 0) {
631
- throw new Error("maxDepth must be a positive number");
632
- }
633
- if (typeof config.chunkSize !== "number") {
634
- throw new Error("chunkSize must be a number");
635
- }
636
- if (config.chunkSize <= 0) {
637
- throw new Error("chunkSize must be a positive number");
638
- }
639
- if (typeof config.yieldThreshold !== "number") {
640
- throw new Error("yieldThreshold must be a number");
641
- }
642
- if (config.yieldThreshold <= 0) {
643
- throw new Error("yieldThreshold must be a positive number");
644
- }
645
- if (config.enableDevWarnings) {
646
- if (config.maxDepth > 1e3) {
647
- console.warn("Coherent.js: maxDepth > 1000 may cause performance issues");
648
- }
649
- if (config.chunkSize > 16384) {
650
- console.warn("Coherent.js: Large chunkSize may increase memory usage");
651
- }
652
- }
653
- return config;
654
- }
655
- /**
656
- * Get configuration for specific renderer type
657
- */
658
- getRendererConfig(rendererType) {
659
- const baseConfig = { ...this.config };
660
- switch (rendererType) {
661
- case "html":
662
- return {
663
- ...baseConfig,
664
- // HTML-specific defaults
665
- enableCache: baseConfig.enableCache !== false,
666
- enableMonitoring: baseConfig.enableMonitoring !== false
667
- };
668
- case "streaming":
669
- return {
670
- ...baseConfig,
671
- // Streaming-specific defaults
672
- enableMetrics: baseConfig.enableMetrics ?? false,
673
- maxDepth: baseConfig.maxDepth ?? 1e3
674
- // Higher default for streaming
675
- };
676
- case "dom":
677
- return {
678
- ...baseConfig,
679
- // DOM-specific defaults
680
- enableHydration: baseConfig.enableHydration !== false
681
- };
682
- default:
683
- return baseConfig;
684
- }
685
- }
686
- /**
687
- * Validate component structure
688
- */
689
- validateComponent(component) {
690
- if (this.config.validateInput !== false) {
691
- return validateComponent(component);
692
- }
693
- return true;
694
- }
695
- /**
696
- * Check if component is valid for rendering
697
- */
698
- isValidComponent(component) {
699
- if (component === null || component === void 0) return true;
700
- if (typeof component === "string" || typeof component === "number") return true;
701
- if (typeof component === "function") return true;
702
- if (Array.isArray(component)) return component.every((child) => this.isValidComponent(child));
703
- if (isCoherentObject(component)) return true;
704
- return false;
705
- }
706
- /**
707
- * Validate rendering depth to prevent stack overflow
708
- */
709
- validateDepth(depth) {
710
- if (depth > this.config.maxDepth) {
711
- throw new Error(`Maximum render depth (${this.config.maxDepth}) exceeded`);
712
- }
713
- }
714
- /**
715
- * Handle different component types with consistent logic
716
- */
717
- processComponentType(component) {
718
- if (component === null || component === void 0) {
719
- return { type: "empty", value: "" };
720
- }
721
- if (typeof component === "string") {
722
- return { type: "text", value: component };
723
- }
724
- if (typeof component === "number" || typeof component === "boolean") {
725
- return { type: "text", value: String(component) };
726
- }
727
- if (typeof component === "function") {
728
- return { type: "function", value: component };
729
- }
730
- if (Array.isArray(component)) {
731
- return { type: "array", value: component };
732
- }
733
- if (isCoherentObject(component)) {
734
- return { type: "element", value: component };
735
- }
736
- return { type: "unknown", value: component };
737
- }
738
- /**
739
- * Execute function components with _error handling
740
- */
741
- executeFunctionComponent(func, depth = 0) {
742
- try {
743
- const isContextProvider = func.length > 0 || func.isContextProvider;
744
- let result;
745
- if (isContextProvider) {
746
- result = func((children) => {
747
- return this.renderComponent(children, this.config, depth + 1);
748
- });
749
- } else {
750
- result = func();
751
- }
752
- if (typeof result === "function") {
753
- return this.executeFunctionComponent(result, depth);
754
- }
755
- return result;
756
- } catch (_error) {
757
- if (this.config.enableMonitoring) {
758
- performanceMonitor.recordError("functionComponent", _error);
759
- }
760
- if (typeof process !== "undefined" && process.env && true) {
761
- console.warn("Coherent.js Function Component Error:", _error.message);
762
- }
763
- return null;
764
- }
765
- }
766
- /**
767
- * Process element children consistently
768
- */
769
- processChildren(children, options, depth) {
770
- if (!hasChildren({ children })) {
771
- return [];
772
- }
773
- const normalizedChildren = normalizeChildren(children);
774
- return normalizedChildren.map(
775
- (child) => this.renderComponent(child, options, depth + 1)
776
- );
777
- }
778
- /**
779
- * Extract and process element attributes
780
- */
781
- extractElementAttributes(props) {
782
- if (!props || typeof props !== "object") return {};
783
- const attributes = { ...props };
784
- delete attributes.children;
785
- delete attributes.text;
786
- return attributes;
787
- }
788
- /**
789
- * Record performance metrics
790
- */
791
- recordPerformance(operation, startTime, fromCache = false, metadata = {}) {
792
- if (this.config.enableMonitoring) {
793
- performanceMonitor.recordRender(
794
- operation,
795
- this.getCurrentTime() - startTime,
796
- fromCache,
797
- metadata
798
- );
799
- }
800
- }
801
- /**
802
- * Record _error for monitoring
803
- */
804
- recordError(operation, _error, metadata = {}) {
805
- if (this.config.enableMonitoring) {
806
- performanceMonitor.recordError(operation, _error, metadata);
807
- }
808
- }
809
- /**
810
- * Get current timestamp with fallback
811
- */
812
- getCurrentTime() {
813
- if (typeof performance !== "undefined" && performance.now) {
814
- return performance.now();
815
- }
816
- return Date.now();
817
- }
818
- /**
819
- * Start performance timing
820
- */
821
- startTiming() {
822
- this.metrics.startTime = this.getCurrentTime();
823
- }
824
- /**
825
- * End performance timing
826
- */
827
- endTiming() {
828
- this.metrics.endTime = this.getCurrentTime();
829
- }
830
- /**
831
- * Get performance metrics
832
- */
833
- getMetrics() {
834
- const duration = this.metrics.endTime ? this.metrics.endTime - this.metrics.startTime : this.getCurrentTime() - this.metrics.startTime;
835
- return {
836
- ...this.metrics,
837
- duration,
838
- elementsPerSecond: this.metrics.elementsProcessed / (duration / 1e3)
839
- };
840
- }
841
- /**
842
- * Reset metrics for new render
843
- */
844
- resetMetrics() {
845
- this.metrics = {
846
- startTime: null,
847
- endTime: null,
848
- elementsProcessed: 0
849
- };
850
- }
851
- /**
852
- * Abstract method - must be implemented by subclasses
853
- */
854
- renderComponent() {
855
- throw new Error("renderComponent must be implemented by subclass");
856
- }
857
- /**
858
- * Abstract method - must be implemented by subclasses
859
- */
860
- render() {
861
- throw new Error("render must be implemented by subclass");
862
- }
863
- };
864
- var RendererUtils = {
865
- /**
866
- * Check if element is static (no functions)
867
- */
868
- isStaticElement(element) {
869
- if (!element || typeof element !== "object") {
870
- return typeof element === "string" || typeof element === "number";
871
- }
872
- for (const [key, value] of Object.entries(element)) {
873
- if (typeof value === "function") return false;
874
- if (key === "children" && Array.isArray(value)) {
875
- return value.every((child) => RendererUtils.isStaticElement(child));
876
- }
877
- if (key === "children" && typeof value === "object" && value !== null) {
878
- return RendererUtils.isStaticElement(value);
879
- }
880
- }
881
- return true;
882
- },
883
- /**
884
- * Check if object has functions (for caching decisions)
885
- */
886
- hasFunctions(obj, visited = /* @__PURE__ */ new WeakSet()) {
887
- if (visited.has(obj)) return false;
888
- visited.add(obj);
889
- for (const value of Object.values(obj)) {
890
- if (typeof value === "function") return true;
891
- if (typeof value === "object" && value !== null && RendererUtils.hasFunctions(value, visited)) {
892
- return true;
893
- }
894
- }
895
- return false;
896
- },
897
- /**
898
- * Get element complexity score
899
- */
900
- getElementComplexity(element) {
901
- if (!element || typeof element !== "object") return 1;
902
- let complexity = Object.keys(element).length;
903
- if (element.children && Array.isArray(element.children)) {
904
- complexity += element.children.reduce(
905
- (sum, child) => sum + RendererUtils.getElementComplexity(child),
906
- 0
907
- );
908
- }
909
- return complexity;
910
- },
911
- /**
912
- * Generate cache key for element
913
- */
914
- generateCacheKey(tagName, element) {
915
- try {
916
- const keyData = {
917
- tag: tagName,
918
- props: extractProps(element),
919
- hasChildren: hasChildren(element),
920
- childrenType: Array.isArray(element.children) ? "array" : typeof element.children
921
- };
922
- return `element:${JSON.stringify(keyData)}`;
923
- } catch (_error) {
924
- if (typeof process !== "undefined" && process.env && true) {
925
- console.warn("Failed to generate cache key:", _error);
926
- }
927
- return null;
928
- }
929
- },
930
- /**
931
- * Check if element is cacheable
932
- */
933
- isCacheable(element, options) {
934
- if (!options.enableCache) return false;
935
- if (RendererUtils.hasFunctions(element)) return false;
936
- if (RendererUtils.getElementComplexity(element) > 1e3) return false;
937
- const cacheKey = RendererUtils.generateCacheKey(element.tagName || "unknown", element);
938
- if (!cacheKey) return false;
939
- return true;
940
- }
941
- };
942
-
943
- // ../core/src/core/html-utils.js
944
- function escapeHtml(text) {
945
- if (typeof text !== "string") return text;
946
- return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
947
- }
948
- function isVoidElement(tagName) {
949
- if (typeof tagName !== "string") {
950
- return false;
951
- }
952
- const voidElements = /* @__PURE__ */ new Set([
953
- "area",
954
- "base",
955
- "br",
956
- "col",
957
- "embed",
958
- "hr",
959
- "img",
960
- "input",
961
- "link",
962
- "meta",
963
- "param",
964
- "source",
965
- "track",
966
- "wbr"
967
- ]);
968
- return voidElements.has(tagName.toLowerCase());
969
- }
970
- function formatAttributes(props) {
971
- let formatted = "";
972
- for (const key in props) {
973
- if (props.hasOwnProperty(key)) {
974
- let value = props[key];
975
- const attributeName = key === "className" ? "class" : key;
976
- if (typeof value === "function") {
977
- if (attributeName.startsWith("on")) {
978
- const actionId = `__coherent_action_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
979
- const DEBUG = typeof process !== "undefined" && process && process.env && (process.env.COHERENT_DEBUG === "1" || true) || typeof window !== "undefined" && window && window.COHERENT_DEBUG === true;
980
- if (typeof global !== "undefined") {
981
- if (!global.__coherentActionRegistry) {
982
- global.__coherentActionRegistry = {};
983
- if (DEBUG) console.log("Initialized global action registry");
984
- }
985
- global.__coherentActionRegistry[actionId] = value;
986
- if (DEBUG) console.log(`Added action ${actionId} to global registry, total: ${Object.keys(global.__coherentActionRegistry).length}`);
987
- if (DEBUG) console.log(`Global registry keys: ${Object.keys(global.__coherentActionRegistry).join(", ")}`);
988
- if (DEBUG) {
989
- if (typeof global.__coherentActionRegistryLog === "undefined") {
990
- global.__coherentActionRegistryLog = [];
991
- }
992
- global.__coherentActionRegistryLog.push({
993
- action: "add",
994
- actionId,
995
- timestamp: Date.now(),
996
- registrySize: Object.keys(global.__coherentActionRegistry).length
997
- });
998
- }
999
- } else if (typeof window !== "undefined") {
1000
- if (!window.__coherentActionRegistry) {
1001
- window.__coherentActionRegistry = {};
1002
- if (DEBUG) console.log("Initialized window action registry");
1003
- }
1004
- window.__coherentActionRegistry[actionId] = value;
1005
- if (DEBUG) console.log(`Added action ${actionId} to window registry, total: ${Object.keys(window.__coherentActionRegistry).length}`);
1006
- if (DEBUG) console.log(`Window registry keys: ${Object.keys(window.__coherentActionRegistry).join(", ")}`);
1007
- }
1008
- const eventType = attributeName.substring(2);
1009
- formatted += ` data-action="${actionId}" data-event="${eventType}"`;
1010
- continue;
1011
- } else {
1012
- try {
1013
- value = value();
1014
- } catch (_error) {
1015
- console.warn(`Error executing function for attribute '${key}':`, {
1016
- _error: _error.message,
1017
- stack: _error.stack,
1018
- attributeKey: key
1019
- });
1020
- value = "";
1021
- }
1022
- }
1023
- }
1024
- if (value === true) {
1025
- formatted += ` ${attributeName}`;
1026
- } else if (value !== false && value !== null && value !== void 0) {
1027
- formatted += ` ${attributeName}="${escapeHtml(String(value))}"`;
1028
- }
1029
- }
1030
- }
1031
- return formatted.trim();
1032
- }
1033
- function minifyHtml(html, options = {}) {
1034
- if (!options.minify) return html;
1035
- return html.replace(/<!--[\s\S]*?-->/g, "").replace(/\s+/g, " ").replace(/>\s+</g, "><").trim();
1036
- }
1037
-
1038
- // ../core/src/performance/cache-manager.js
1039
- function createCacheManager(options = {}) {
1040
- const {
1041
- maxCacheSize = 1e3,
1042
- maxMemoryMB = 100,
1043
- ttlMs = 1e3 * 60 * 5,
1044
- // 5 minutes
1045
- enableStatistics = true
1046
- } = options;
1047
- const caches = {
1048
- static: /* @__PURE__ */ new Map(),
1049
- // Never-changing components
1050
- component: /* @__PURE__ */ new Map(),
1051
- // Component results with deps
1052
- template: /* @__PURE__ */ new Map(),
1053
- // Template strings
1054
- data: /* @__PURE__ */ new Map()
1055
- // General purpose data
1056
- };
1057
- let memoryUsage = 0;
1058
- const stats = {
1059
- hits: 0,
1060
- misses: 0,
1061
- hitRate: {
1062
- static: 0,
1063
- component: 0,
1064
- template: 0,
1065
- data: 0
1066
- },
1067
- accessCount: {
1068
- static: 0,
1069
- component: 0,
1070
- template: 0,
1071
- data: 0
1072
- }
1073
- };
1074
- let cleanupInterval;
1075
- if (typeof setInterval === "function") {
1076
- cleanupInterval = setInterval(() => cleanup(), 3e4);
1077
- if (cleanupInterval.unref) {
1078
- cleanupInterval.unref();
1079
- }
1080
- }
1081
- function generateCacheKey(component, props = {}, context = {}) {
1082
- const componentStr = typeof component === "function" ? component.name || component.toString() : JSON.stringify(component);
1083
- const propsStr = JSON.stringify(props, Object.keys(props).sort());
1084
- const contextStr = JSON.stringify(context);
1085
- const hash = simpleHash(componentStr + propsStr + contextStr);
1086
- return `${extractComponentName(component)}_${hash}`;
1087
- }
1088
- function get(key, type = "component") {
1089
- const cache = caches[type] || caches.component;
1090
- const entry = cache.get(key);
1091
- if (!entry) {
1092
- stats.misses++;
1093
- if (enableStatistics) stats.accessCount[type]++;
1094
- return null;
1095
- }
1096
- if (Date.now() - entry.timestamp > ttlMs) {
1097
- cache.delete(key);
1098
- updateMemoryUsage(-entry.size);
1099
- stats.misses++;
1100
- if (enableStatistics) stats.accessCount[type]++;
1101
- return null;
1102
- }
1103
- entry.lastAccess = Date.now();
1104
- entry.accessCount++;
1105
- stats.hits++;
1106
- if (enableStatistics) {
1107
- stats.accessCount[type]++;
1108
- stats.hitRate[type] = stats.hits / (stats.hits + stats.misses) * 100;
1109
- }
1110
- return entry.value;
1111
- }
1112
- function set(key, value, type = "component", metadata = {}) {
1113
- const cache = caches[type] || caches.component;
1114
- const size = calculateSize(value);
1115
- if (memoryUsage + size > maxMemoryMB * 1024 * 1024) {
1116
- optimize(type, size);
1117
- }
1118
- const entry = {
1119
- value,
1120
- timestamp: Date.now(),
1121
- lastAccess: Date.now(),
1122
- size,
1123
- metadata,
1124
- accessCount: 0
1125
- };
1126
- const existing = cache.get(key);
1127
- if (existing) {
1128
- updateMemoryUsage(-existing.size);
1129
- }
1130
- cache.set(key, entry);
1131
- updateMemoryUsage(size);
1132
- if (cache.size > maxCacheSize) {
1133
- optimize(type);
1134
- }
1135
- }
1136
- function remove(key, type) {
1137
- if (type) {
1138
- const cache = caches[type];
1139
- if (!cache) return false;
1140
- const entry = cache.get(key);
1141
- if (entry) {
1142
- updateMemoryUsage(-entry.size);
1143
- return cache.delete(key);
1144
- }
1145
- return false;
1146
- }
1147
- for (const [, cache] of Object.entries(caches)) {
1148
- const entry = cache.get(key);
1149
- if (entry) {
1150
- updateMemoryUsage(-entry.size);
1151
- return cache.delete(key);
1152
- }
1153
- }
1154
- return false;
1155
- }
1156
- function clear(type) {
1157
- if (type) {
1158
- const cache = caches[type];
1159
- if (cache) {
1160
- cache.clear();
1161
- }
1162
- } else {
1163
- Object.values(caches).forEach((cache) => cache.clear());
1164
- }
1165
- memoryUsage = 0;
1166
- }
1167
- function getStats() {
1168
- const entries = Object.values(caches).reduce((sum, cache) => sum + cache.size, 0);
1169
- return {
1170
- hits: stats.hits,
1171
- misses: stats.misses,
1172
- size: memoryUsage,
1173
- entries,
1174
- hitRate: stats.hitRate,
1175
- accessCount: stats.accessCount
1176
- };
1177
- }
1178
- function cleanup() {
1179
- const now = Date.now();
1180
- let freed = 0;
1181
- for (const [, cache] of Object.entries(caches)) {
1182
- for (const [key, entry] of cache.entries()) {
1183
- if (now - entry.timestamp > ttlMs) {
1184
- cache.delete(key);
1185
- updateMemoryUsage(-entry.size);
1186
- freed++;
1187
- }
1188
- }
1189
- }
1190
- return { freed };
1191
- }
1192
- function calculateSize(value) {
1193
- if (value === null || value === void 0) return 0;
1194
- if (typeof value === "string") return value.length * 2;
1195
- if (typeof value === "number") return 8;
1196
- if (typeof value === "boolean") return 4;
1197
- if (Array.isArray(value)) {
1198
- return value.reduce((sum, item) => sum + calculateSize(item), 0);
1199
- }
1200
- if (typeof value === "object") {
1201
- return Object.values(value).reduce((sum, val) => sum + calculateSize(val), 0);
1202
- }
1203
- return 0;
1204
- }
1205
- function updateMemoryUsage(delta) {
1206
- memoryUsage = Math.max(0, memoryUsage + delta);
1207
- }
1208
- function optimize(type, requiredSpace = 0) {
1209
- const cache = caches[type] || caches.component;
1210
- const entries = Array.from(cache.entries()).sort(([, a], [, b]) => a.lastAccess - b.lastAccess);
1211
- let freed = 0;
1212
- for (const [key, entry] of entries) {
1213
- if (freed >= requiredSpace) break;
1214
- cache.delete(key);
1215
- updateMemoryUsage(-entry.size);
1216
- freed += entry.size;
1217
- }
1218
- return { freed };
1219
- }
1220
- function simpleHash(str) {
1221
- let hash = 0;
1222
- for (let i = 0; i < str.length; i++) {
1223
- const char = str.charCodeAt(i);
1224
- hash = (hash << 5) - hash + char;
1225
- hash = hash & hash;
1226
- }
1227
- return Math.abs(hash).toString(36);
1228
- }
1229
- function extractComponentName(component) {
1230
- if (typeof component === "function") {
1231
- return component.name || "AnonymousComponent";
1232
- }
1233
- if (component && typeof component === "object") {
1234
- const keys = Object.keys(component);
1235
- return keys.length > 0 ? keys[0] : "ObjectComponent";
1236
- }
1237
- return "UnknownComponent";
1238
- }
1239
- function destroy() {
1240
- if (cleanupInterval) {
1241
- clearInterval(cleanupInterval);
1242
- }
1243
- clear();
1244
- }
1245
- return {
1246
- get,
1247
- set,
1248
- remove,
1249
- clear,
1250
- getStats,
1251
- cleanup,
1252
- destroy,
1253
- generateCacheKey,
1254
- get memoryUsage() {
1255
- return memoryUsage;
1256
- },
1257
- get maxMemory() {
1258
- return maxMemoryMB * 1024 * 1024;
1259
- }
1260
- };
1261
- }
1262
- var cacheManager = createCacheManager();
1263
-
1264
- // ../core/src/rendering/html-renderer.js
1265
- var rendererCache = createCacheManager({
1266
- maxSize: 1e3,
1267
- ttlMs: 3e5
1268
- // 5 minutes
1269
- });
1270
- var HTMLRenderer = class extends BaseRenderer {
1271
- constructor(options = {}) {
1272
- super({
1273
- enableCache: options.enableCache !== false,
1274
- enableMonitoring: options.enableMonitoring !== false,
1275
- minify: options.minify || false,
1276
- streaming: options.streaming || false,
1277
- maxDepth: options.maxDepth || 100,
1278
- ...options
1279
- });
1280
- if (this.config.enableCache && !this.cache) {
1281
- this.cache = rendererCache;
1282
- }
1283
- }
1284
- /**
1285
- * Main render method - converts components to HTML string
1286
- *
1287
- * @param {Object|Array|string|Function} component - Component to render
1288
- * @param {Object} [options={}] - Rendering options
1289
- * @param {Object} [options.context] - Rendering context
1290
- * @param {boolean} [options.enableCache] - Override cache setting
1291
- * @param {number} [options.depth=0] - Current rendering depth
1292
- * @returns {string} Rendered HTML string
1293
- *
1294
- * @example
1295
- * const html = renderer.render({
1296
- * div: {
1297
- * className: 'container',
1298
- * children: [
1299
- * { h1: { text: 'Title' } },
1300
- * { p: { text: 'Content' } }
1301
- * ]
1302
- * }
1303
- * });
1304
- */
1305
- render(component, options = {}) {
1306
- const config = { ...this.config, ...options };
1307
- this.startTiming();
1308
- try {
1309
- if (config.validateInput && !this.isValidComponent(component)) {
1310
- throw new Error("Invalid component structure");
1311
- }
1312
- const html = this.renderComponent(component, config, 0);
1313
- const finalHtml = config.minify ? minifyHtml(html, config) : html;
1314
- this.endTiming();
1315
- this.recordPerformance("render", this.metrics.startTime, false, {
1316
- cacheEnabled: config.enableCache
1317
- });
1318
- return finalHtml;
1319
- } catch (_error) {
1320
- this.recordError("render", _error);
1321
- throw _error;
1322
- }
1323
- }
1324
- /**
1325
- * Render a single component with full optimization pipeline
1326
- */
1327
- renderComponent(component, options, depth = 0) {
1328
- this.validateDepth(depth);
1329
- const { type, value } = this.processComponentType(component);
1330
- switch (type) {
1331
- case "empty":
1332
- return "";
1333
- case "text":
1334
- return escapeHtml(value);
1335
- case "function":
1336
- const result = this.executeFunctionComponent(value, depth);
1337
- return this.renderComponent(result, options, depth + 1);
1338
- case "array":
1339
- return value.map((child) => this.renderComponent(child, options, depth + 1)).join("");
1340
- case "element":
1341
- const tagName = Object.keys(value)[0];
1342
- const elementContent = value[tagName];
1343
- return this.renderElement(tagName, elementContent, options, depth);
1344
- default:
1345
- this.recordError("renderComponent", new Error(`Unknown component type: ${type}`));
1346
- return "";
1347
- }
1348
- }
1349
- /**
1350
- * Render an HTML element with advanced caching and optimization
1351
- */
1352
- renderElement(tagName, element, options, depth = 0) {
1353
- const startTime = performance.now();
1354
- if (options.enableMonitoring && this.cache) {
1355
- }
1356
- if (options.enableCache && this.cache && RendererUtils.isStaticElement(element)) {
1357
- const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;
1358
- const cached = this.cache.get("static", cacheKey);
1359
- if (cached) {
1360
- this.recordPerformance(tagName, startTime, true);
1361
- return cached.value;
1362
- }
1363
- }
1364
- if (typeof element === "string" || typeof element === "number" || typeof element === "boolean") {
1365
- const html2 = isVoidElement(tagName) ? `<${tagName}>` : `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;
1366
- this.cacheIfStatic(tagName, element, html2, options);
1367
- this.recordPerformance(tagName, startTime, false);
1368
- return html2;
1369
- }
1370
- if (typeof element === "function") {
1371
- const result = this.executeFunctionComponent(element, depth);
1372
- return this.renderElement(tagName, result, options, depth);
1373
- }
1374
- if (element && typeof element === "object") {
1375
- return this.renderObjectElement(tagName, element, options, depth);
1376
- }
1377
- if (element === null || element === void 0) {
1378
- const html2 = isVoidElement(tagName) ? `<${tagName}>` : `<${tagName}></${tagName}>`;
1379
- this.recordPerformance(tagName, startTime, false);
1380
- return html2;
1381
- }
1382
- const html = `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;
1383
- this.recordPerformance(tagName, startTime, false);
1384
- return html;
1385
- }
1386
- /**
1387
- * Cache element if it's static
1388
- */
1389
- cacheIfStatic(tagName, element, html) {
1390
- if (this.config.enableCache && this.cache && RendererUtils.isStaticElement(element)) {
1391
- const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;
1392
- this.cache.set("static", cacheKey, html, {
1393
- ttlMs: this.config.cacheTTL || 5 * 60 * 1e3,
1394
- // 5 minutes default
1395
- size: html.length
1396
- // Approximate size
1397
- });
1398
- }
1399
- }
1400
- /**
1401
- * Render complex object elements with attributes and children
1402
- */
1403
- renderObjectElement(tagName, element, options, depth = 0) {
1404
- const startTime = performance.now();
1405
- if (options.enableCache && this.cache) {
1406
- const cacheKey = RendererUtils.generateCacheKey(tagName, element);
1407
- if (cacheKey) {
1408
- const cached = this.cache.get(cacheKey);
1409
- if (cached) {
1410
- this.recordPerformance(tagName, startTime, true);
1411
- return cached;
1412
- }
1413
- }
1414
- }
1415
- const { children, text, ...attributes } = element || {};
1416
- const attributeString = formatAttributes(attributes);
1417
- const openingTag = attributeString ? `<${tagName} ${attributeString}>` : `<${tagName}>`;
1418
- let textContent = "";
1419
- if (text !== void 0) {
1420
- const isScript = tagName === "script";
1421
- const isStyle = tagName === "style";
1422
- const isRawTag = isScript || isStyle;
1423
- const raw = typeof text === "function" ? String(text()) : String(text);
1424
- if (isRawTag) {
1425
- const safe = raw.replace(/<\/(script)/gi, "<\\/$1").replace(/<\/(style)/gi, "<\\/$1").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
1426
- textContent = safe;
1427
- } else {
1428
- textContent = escapeHtml(raw);
1429
- }
1430
- }
1431
- let childrenHtml = "";
1432
- if (hasChildren(element)) {
1433
- const normalizedChildren = normalizeChildren(children);
1434
- childrenHtml = normalizedChildren.map((child) => this.renderComponent(child, options, depth + 1)).join("");
1435
- }
1436
- const html = `${openingTag}${textContent}${childrenHtml}</${tagName}>`;
1437
- if (options.enableCache && this.cache && RendererUtils.isCacheable(element, options)) {
1438
- const cacheKey = RendererUtils.generateCacheKey(tagName, element);
1439
- if (cacheKey) {
1440
- this.cache.set(cacheKey, html);
1441
- }
1442
- }
1443
- this.recordPerformance(tagName, startTime, false);
1444
- return html;
1445
- }
1446
- };
1447
- function render(component, options = {}) {
1448
- const mergedOptions = {
1449
- enableCache: true,
1450
- enableMonitoring: false,
1451
- ...options
1452
- };
1453
- const renderer = new HTMLRenderer(mergedOptions);
1454
- return renderer.render(component, mergedOptions);
1455
- }
1456
-
1457
- // ../core/src/utils/render-utils.js
1458
- function renderWithMonitoring(component, options = {}) {
1459
- const {
1460
- enablePerformanceMonitoring = false
1461
- } = options;
1462
- let html;
1463
- if (enablePerformanceMonitoring) {
1464
- const renderId = performanceMonitor.startRender();
1465
- html = render(component);
1466
- performanceMonitor.endRender(renderId);
1467
- } else {
1468
- html = render(component);
1469
- }
1470
- return html;
1471
- }
1472
- function renderWithTemplate(component, options = {}) {
1473
- const {
1474
- template = "<!DOCTYPE html>\n{{content}}"
1475
- } = options;
1476
- const html = renderWithMonitoring(component, options);
1477
- return template.replace("{{content}}", html);
1478
- }
1479
- async function renderComponentFactory(componentFactory, factoryArgs, options = {}) {
1480
- const component = await Promise.resolve(
1481
- componentFactory(...factoryArgs)
1482
- );
1483
- if (!component) {
1484
- throw new Error("Component factory returned null/undefined");
1485
- }
1486
- return renderWithTemplate(component, options);
1487
- }
1488
-
1489
1
  // src/coherent-fastify.js
2
+ import {
3
+ renderWithTemplate,
4
+ renderComponentFactory
5
+ } from "@coherent.js/core";
1490
6
  function coherentFastify(fastify, options, done) {
1491
7
  const {
1492
8
  enablePerformanceMonitoring = false,
@@ -1560,10 +76,4 @@ export {
1560
76
  coherent_fastify_default as default,
1561
77
  setupCoherent
1562
78
  };
1563
- /**
1564
- * Advanced caching system with memory management and smart invalidation for Coherent.js
1565
- *
1566
- * @module @coherent/performance/cache-manager
1567
- * @license MIT
1568
- */
1569
79
  //# sourceMappingURL=index.js.map