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