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