All files / core/src/rendering html-renderer.js

61.2% Statements 172/281
68.56% Branches 181/264
60% Functions 18/30
62.04% Lines 170/274

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823                                                    16x           68x   61x 61x 231x 231x     231x     61x                                                             62x                   62x 62x                                                   62x 62x   62x   62x 1x       61x           61x 61x     62x 62x       62x     5x 5x       5x       5x                 136x 3x   133x 1x       132x 119x 3x             116x 109x         129x   129x   129x   129x       5x     2x 2x       6x         5x 12x 9x 9x 9x   3x     5x 3x               13x       116x 116x 116x             5x   5x 5x   5x     5x                     116x     116x 109x 1x             108x 101x         115x         115x 100x 100x 100x 100x                     115x 7x       7x 7x 7x       108x           108x 108x                                           7x 6x 6x 6x                           108x     108x 108x 108x 104x 104x 1x 1x                 107x     108x 108x         108x             107x 107x 65x 65x 65x 65x 65x                   65x         107x 107x 38x 38x     58x 56x 56x 56x     58x           103x     103x 97x 97x 97x       103x 103x                     62x           62x 62x                                                                                                                                                                                                                                                         11x               11x 11x       56x 11x 10x 10x             45x 45x         24x         24x     24x           24x 4x 6x     6x       4x       20x 3x 3x 3x       17x 17x 17x 16x 16x 16x   16x           16x   16x 12x 4x 4x     16x 16x 1x   1x     1x   1x                             11x 11x 11x                   16x                                                                                                                                               2x             16x 16x               2x                                                                              
/**
 * High-performance HTML renderer with caching, monitoring, and streaming support
 * Converts object-based components to HTML strings with advanced optimizations
 */
 
import { BaseRenderer, RendererUtils } from './base-renderer.js';
import {
    hasChildren,
    normalizeChildren,
} from '../core/object-utils.js';
 
import { validateNesting } from '../core/html-nesting-rules.js';
 
import {
    escapeHtml,
    isVoidElement,
    formatAttributes,
    minifyHtml
} from '../core/html-utils.js';
 
import { performanceMonitor } from '../performance/monitor.js';
import { createCacheManager } from '../performance/cache-manager.js';
import { cssUtils, defaultCSSManager } from './css-manager.js';
import { CoherentError, RenderingError, globalErrorHandler } from '../utils/error-handler.js';
 
// Create a global cache instance for the renderer
const rendererCache = createCacheManager({
    maxSize: 1000,
    ttlMs: 300000 // 5 minutes
});
 
function formatRenderPath(path) {
    if (!path || path.length === 0) return 'root';
 
    let rendered = 'root';
    for (const segment of path) {
        Iif (typeof segment !== 'string' || segment.length === 0) continue;
        Iif (segment.startsWith('[')) {
            rendered += segment;
        } else {
            rendered += `.${segment}`;
        }
    }
    return rendered;
}
 
/**
 * HTML Renderer Class extending BaseRenderer
 *
 * @class HTMLRenderer
 * @extends BaseRenderer
 * @description High-performance HTML renderer with caching, monitoring, and streaming support.
 * Converts object-based components to HTML strings with advanced optimizations.
 *
 * @param {Object} [options={}] - Renderer configuration options
 * @param {boolean} [options.enableCache=true] - Enable component caching
 * @param {boolean} [options.enableMonitoring=true] - Enable performance monitoring
 * @param {boolean} [options.minify=false] - Enable HTML minification
 * @param {boolean} [options.streaming=false] - Enable streaming mode
 * @param {number} [options.maxDepth=100] - Maximum rendering depth
 * @param {number} [options.cacheSize=1000] - Cache size limit
 * @param {number} [options.cacheTTL=300000] - Cache TTL in milliseconds
 *
 * @example
 * const renderer = new HTMLRenderer({
 *   enableCache: true,
 *   enableMonitoring: true,
 *   minify: true
 * });
 *
 * const html = renderer.render({ div: { text: 'Hello World' } });
 */
class HTMLRenderer extends BaseRenderer {
    constructor(options = {}) {
        super({
            enableCache: options.enableCache !== false,
            enableMonitoring: options.enableMonitoring !== false,
            minify: options.minify || false,
            streaming: options.streaming || false,
            maxDepth: options.maxDepth || 100,
            ...options
        });
 
        // Initialize cache if enabled
        Eif (this.config.enableCache && !this.cache) {
            this.cache = rendererCache;
        }
    }
 
    /**
     * Main render method - converts components to HTML string
     *
     * @param {Object|Array|string|Function} component - Component to render
     * @param {Object} [options={}] - Rendering options
     * @param {Object} [options.context] - Rendering context
     * @param {boolean} [options.enableCache] - Override cache setting
     * @param {number} [options.depth=0] - Current rendering depth
     * @returns {string} Rendered HTML string
     *
     * @example
     * const html = renderer.render({
     *   div: {
     *     className: 'container',
     *     children: [
     *       { h1: { text: 'Title' } },
     *       { p: { text: 'Content' } }
     *     ]
     *   }
     * });
     */
    render(component, options = {}) {
        const config = { ...this.config, ...options };
        this.startTiming();
 
        try {
            // Input validation
            if (config.validateInput && !this.isValidComponent(component)) {
                throw new Error('Invalid component structure');
            }
 
            // Initialize seenObjects for circular reference detection
            const renderOptions = {
                ...config,
                seenObjects: new WeakSet()
            };
 
            // Main rendering logic
            const html = this.renderComponent(component, renderOptions, 0, []);
            const finalHtml = config.minify ? minifyHtml(html, config) : html;
 
            // Performance monitoring
            this.endTiming();
            this.recordPerformance('render', this.metrics.startTime, false, {
                cacheEnabled: config.enableCache
            });
 
            return finalHtml;
 
        } catch (_error) {
            this.recordError('render', _error);
            const enhancedError = globalErrorHandler.handle(_error, {
                renderContext: { path: 'root', renderer: 'html' }
            });
 
            Iif (config.throwOnError === false) {
                return config.errorFallback;
            }
 
            throw enhancedError;
        }
    }
 
    /**
     * Render a single component with full optimization pipeline
     */
    renderComponent(component, options, depth = 0, path = []) {
        // Handle nullish and empty inputs immediately
        if (component === null || component === undefined) {
            return '';
        }
        if (Array.isArray(component) && component.length === 0) {
            return '';
        }
 
        // Detect circular references (objects only)
        if (typeof component === 'object' && component !== null && !Array.isArray(component)) {
            if (options.seenObjects && options.seenObjects.has(component)) {
                throw new RenderingError(
                    'Circular reference detected in component tree',
                    component,
                    { path: formatRenderPath(path) },
                    ['Remove the circular reference', 'Use lazy loading to break the cycle']
                );
            }
            if (options.seenObjects) {
                options.seenObjects.add(component);
            }
        }
 
        // Use base class depth validation
        this.validateDepth(depth);
 
        try {
            // Use base class component type processing
            const { type, value } = this.processComponentType(component);
 
            switch (type) {
                case 'empty':
                    return '';
                case 'text':
                    return escapeHtml(value);
                case 'function':
                    {
                        const result = this.executeFunctionComponent(value, depth);
                        return this.renderComponent(result, options, depth + 1, [...path, '()']);
                    }
                case 'array':
                    // Development mode warning for missing keys
                    if (typeof process !== 'undefined' &&
                        process.env &&
                        process.env.NODE_ENV !== 'production' &&
                        value.length > 1) {
 
                        const missingKeyCount = value.filter((child) => {
                            if (child && typeof child === 'object' && !Array.isArray(child)) {
                                const tagName = Object.keys(child)[0];
                                const props = child[tagName];
                                return props && typeof props === 'object' && props.key === undefined;
                            }
                            return false;  // primitives don't need keys
                        }).length;
 
                        if (missingKeyCount > 0) {
                            console.warn(
                                `[Coherent.js] Array of ${value.length} elements at ${formatRenderPath(path)} ` +
                                `has ${missingKeyCount} items missing "key" props. ` +
                                `Keys help identify which items changed for efficient updates. ` +
                                `Add unique key props like: { div: { key: 'unique-id', ... } }`
                            );
                        }
                    }
                    return value.map((child, index) => this.renderComponent(child, options, depth + 1, [...path, `[${index}]`])).join('');
                case 'element':
                    {
                        // Process object-based component
                        const tagName = Object.keys(value)[0];
                        const elementContent = value[tagName];
                        return this.renderElement(tagName, elementContent, options, depth, [...path, tagName]);
                    }
                default:
                    this.recordError('renderComponent', new Error(`Unknown component type: ${type}`));
                    return '';
            }
        } catch (_error) {
            const renderPath = formatRenderPath(path);
 
            Eif (_error instanceof CoherentError) {
                Iif (!_error.context || typeof _error.context !== 'object') {
                    _error.context = { path: renderPath };
                } else if (I!_error.context.path) {
                    _error.context = { ..._error.context, path: renderPath };
                }
                throw _error;
            }
 
            throw new RenderingError(_error.message, undefined, { path: renderPath, renderer: 'html' });
        }
    }
 
    /**
     * Render an HTML element with advanced caching and optimization
     */
    renderElement(tagName, element, options, depth = 0, path = []) {
        const startTime = performance.now();
 
        // Check for circular references in element props
        if (element && typeof element === 'object' && !Array.isArray(element)) {
            if (options.seenObjects && options.seenObjects.has(element)) {
                throw new RenderingError(
                    'Circular reference detected in component tree',
                    element,
                    { path: formatRenderPath(path) },
                    ['Remove the circular reference', 'Use lazy loading to break the cycle']
                );
            }
            if (options.seenObjects) {
                options.seenObjects.add(element);
            }
        }
 
        // Track element usage for performance analysis (via stats in the new cache manager)
        if (options.enableMonitoring && this.cache) {
            // The new cache manager tracks usage automatically via get/set operations
        }
 
        // Check cache first for static elements
        if (options.enableCache && this.cache && RendererUtils.isStaticElement(element)) {
            try {
                const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;
                const cached = this.cache.get('static', cacheKey);
                Iif (cached) {
                    this.recordPerformance(tagName, startTime, true);
                    return cached.value; // Return the cached HTML
                }
            } catch {
                // Circular reference in element - skip caching and continue with rendering
                // The circular reference will be detected and properly reported during render
            }
        }
 
        // Handle text-only elements including booleans
        if (typeof element === 'string' || typeof element === 'number' || typeof element === 'boolean') {
            const html = isVoidElement(tagName)
                ? `<${tagName}>`
                : `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;
 
            this.cacheIfStatic(tagName, element, html, options);
            this.recordPerformance(tagName, startTime, false);
            return html;
        }
 
        // Handle function elements
        Iif (typeof element === 'function') {
            const result = this.executeFunctionComponent(element, depth);
            return this.renderElement(tagName, result, options, depth, [...path, '()']);
        }
 
        // Handle object elements (complex elements with props and children)
        Eif (element && typeof element === 'object') {
            return this.renderObjectElement(tagName, element, options, depth, path);
        }
 
        // Handle null and undefined by returning empty tags
        if (element === null || element === undefined) {
            const html = isVoidElement(tagName)
                ? `<${tagName}>`
                : `<${tagName}></${tagName}>`;
            this.recordPerformance(tagName, startTime, false);
            return html;
        }
 
        // Fallback for any other types
        const html = `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;
        this.recordPerformance(tagName, startTime, false);
        return html;
    }
 
    /**
     * Cache element if it's static
     */
    cacheIfStatic(tagName, element, html) {
        if (this.config.enableCache && this.cache && RendererUtils.isStaticElement(element)) {
            try {
                const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;
                this.cache.set('static', cacheKey, html, {
                    ttlMs: this.config.cacheTTL || 5 * 60 * 1000, // 5 minutes default
                    size: html.length // Approximate size
                });
            } catch {
                // Circular reference - skip caching
            }
        }
    }
 
    /**
     * Render complex object elements with attributes and children
     */
    renderObjectElement(tagName, element, options, depth = 0, path = []) {
        const startTime = performance.now();
 
        // Check component-level cache
        Eif (options.enableCache && this.cache) {
            const cacheKey = RendererUtils.generateCacheKey(tagName, element);
            if (cacheKey) {
                const cached = this.cache.get(cacheKey);
                if (cached) {
                    this.recordPerformance(tagName, startTime, true);
                    return cached;
                }
            }
        }
 
        // Extract props and children directly from element content
        // Note: key is extracted but NOT rendered as an HTML attribute
        // It's used for reconciliation identity, not DOM output
        // html prop is extracted to prevent it from being rendered as an attribute
        const { children, text, key: _key, html: _rawHtml, ...attributes } = element || {};
 
        // Build opening tag with attributes
        const attributeString = formatAttributes(attributes);
        const openingTag = attributeString
            ? `<${tagName} ${attributeString}>`
            : `<${tagName}>`;
 
        // Handle raw HTML injection (unescaped) — for SSR use cases like syntax highlighting
        Iif (_rawHtml !== undefined) {
            const rawContent = typeof _rawHtml === 'function' ? String(_rawHtml()) : String(_rawHtml);
            const result = `${openingTag}${rawContent}</${tagName}>`;
            return result;
        }
 
        // Handle text content
        let textContent = '';
        if (text !== undefined) {
            const isScript = tagName === 'script';
            const isStyle = tagName === 'style';
            const isRawTag = isScript || isStyle;
            const raw = typeof text === 'function' ? String(text()) : String(text);
            Iif (isRawTag) {
                // Prevent </script> or </style> early-terminating the tag
                const safe = raw
                  .replace(/<\/(script)/gi, '<\\/$1')
                  .replace(/<\/(style)/gi, '<\\/$1')
                  // Escape problematic Unicode line separators in JS
                  .replace(/\u2028/g, '\\u2028')
                  .replace(/\u2029/g, '\\u2029');
                textContent = safe;
            } else {
                textContent = escapeHtml(raw);
            }
        }
 
        // Handle children
        let childrenHtml = '';
        if (hasChildren(element)) {
            const normalizedChildren = normalizeChildren(children);
            childrenHtml = normalizedChildren
                .map((child, index) => {
                    // Validate HTML nesting before rendering child
                    if (child && typeof child === 'object' && !Array.isArray(child)) {
                        const childTagName = Object.keys(child)[0];
                        Eif (childTagName) {
                            validateNesting(tagName, childTagName, formatRenderPath([...path, `children[${index}]`]));
                        }
                    }
                    return this.renderComponent(child, options, depth + 1, [...path, `children[${index}]`]);
                })
                .join('');
        }
 
        // Build complete HTML
        const html = `${openingTag}${textContent}${childrenHtml}</${tagName}>`;
 
        // Cache the result if appropriate
        if (options.enableCache && this.cache && RendererUtils.isCacheable(element, options)) {
            const cacheKey = RendererUtils.generateCacheKey(tagName, element);
            Eif (cacheKey) {
                this.cache.set(cacheKey, html);
            }
        }
 
        this.recordPerformance(tagName, startTime, false);
        return html;
    }
}
 
// Note: globalCache is now imported from cache-manager.js
 
/**
 * Main render function - converts object components to HTML
 */
export function render(component, options = {}) {
    // Merge default options with provided options
    const mergedOptions = {
        enableCache: true,
        enableMonitoring: false,
        ...options
    };
 
    const renderer = new HTMLRenderer(mergedOptions);
    return renderer.render(component, mergedOptions);
}
 
/**
 * Renders component to complete HTML document with DOCTYPE
 * Better alternative to manual DOCTYPE concatenation
 * Supports CSS file inclusion and inline styles
 */
export async function renderHTML(component, options = {}) {
    const htmlContent = render(component, options);
 
    // Process CSS options
    const cssOptions = cssUtils.processCSSOptions(options);
 
    // Generate CSS HTML if any CSS is specified
    let cssHtml = '';
    if (cssOptions.files.length > 0 || cssOptions.links.length > 0 || cssOptions.inline) {
        cssHtml = await cssUtils.generateCSSHtml(cssOptions, defaultCSSManager);
    }
 
    // If the component includes a head tag, inject CSS into it
    if (cssHtml && htmlContent.includes('<head>')) {
        const htmlWithCSS = htmlContent.replace(
            '</head>',
            `${cssHtml}\n</head>`
        );
        return `<!DOCTYPE html>\n${htmlWithCSS}`;
    }
 
    // If there's CSS but no head tag, wrap the component with a basic HTML structure
    if (cssHtml) {
        return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
${cssHtml}
</head>
<body>
${htmlContent}
</body>
</html>`;
    }
 
    return `<!DOCTYPE html>\n${htmlContent}`;
}
 
/**
 * Synchronous version of render for cases without CSS files
 * Falls back to async if CSS files are detected
 */
export function renderHTMLSync(component, options = {}) {
    const cssOptions = cssUtils.processCSSOptions(options);
 
    // If CSS files are specified, return a promise
    if (cssOptions.files.length > 0) {
        console.warn('CSS files detected, use render() (async) instead of renderSync()');
        return render(component, options);
    }
 
    const htmlContent = render(component, options);
 
    // Handle inline CSS and external links only
    let cssHtml = '';
    if (cssOptions.links.length > 0) {
        cssHtml += defaultCSSManager.generateCSSLinks(cssOptions.links);
    }
    if (cssOptions.inline) {
        cssHtml += `\n${  defaultCSSManager.generateInlineStyles(cssOptions.inline)}`;
    }
 
    if (cssHtml && htmlContent.includes('<head>')) {
        const htmlWithCSS = htmlContent.replace(
            '</head>',
            `${cssHtml}\n</head>`
        );
        return `<!DOCTYPE html>\n${htmlWithCSS}`;
    }
 
    if (cssHtml) {
        return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
${cssHtml}
</head>
<body>
${htmlContent}
</body>
</html>`;
    }
 
    return `<!DOCTYPE html>\n${htmlContent}`;
}
 
 
// Old functions removed - now part of HTMLRenderer class
 
// Old helper functions removed - now available in RendererUtils from BaseRenderer
 
/**
 * Batch rendering for multiple components
 */
export function renderBatch(components, options = {}) {
    if (!Array.isArray(components)) {
        throw new Error('renderBatch expects an array of components');
    }
 
    // Merge default options with provided options
    const mergedOptions = {
        enableCache: true,
        enableMonitoring: false,
        ...options
    };
 
    const renderer = new HTMLRenderer(mergedOptions);
    return components.map(component => renderer.render(component, mergedOptions));
}
 
/**
 * Real streaming render - yields chunks progressively as HTML is generated
 * Ideal for large component trees or memory-constrained environments
 */
export async function* renderToStream(component, options = {}) {
    const config = {
        chunkSize: 8192, // 8KB default chunk size
        maxDepth: 1000,
        yieldThreshold: 100, // Yield control every 100 elements
        encoding: 'utf8',
        ...options
    };
 
    let buffer = '';
    let elementCount = 0;
 
    // Helper to flush buffer when it reaches chunk size
    async function* flushBuffer(force = false) {
        if (force || buffer.length >= config.chunkSize) {
            if (buffer.length > 0) {
                yield buffer;
                buffer = '';
            }
        }
    }
 
    // Helper to add to buffer
    async function* write(text) {
        buffer += text;
        yield* flushBuffer();
    }
 
    // Recursive streaming component renderer
    async function* streamComponent(comp, depth = 0) {
        Iif (depth > config.maxDepth) {
            throw new Error(`Maximum nesting depth exceeded: ${config.maxDepth}`);
        }
 
        // Handle null/undefined
        Iif (comp === null || comp === undefined) return;
 
        // Handle primitives
        Iif (typeof comp === 'string' || typeof comp === 'number') {
            yield* write(escapeHtml(String(comp)));
            return;
        }
 
        // Handle arrays
        if (Array.isArray(comp)) {
            for (const child of comp) {
                yield* streamComponent(child, depth);
 
                // Yield control periodically
                Iif (elementCount++ % config.yieldThreshold === 0) {
                    await new Promise(resolve => setImmediate(resolve));
                }
            }
            return;
        }
 
        // Handle functions
        if (typeof comp === 'function') {
            const result = comp();
            yield* streamComponent(result, depth);
            return;
        }
 
        // Handle objects (HTML elements)
        Eif (typeof comp === 'object') {
            for (const [tagName, props] of Object.entries(comp)) {
                if (typeof props === 'object' && props !== null) {
                    const { children, text, ...attributes } = props;
                    const attrsStr = formatAttributes(attributes);
                    const openTag = attrsStr ? `<${tagName} ${attrsStr}>` : `<${tagName}>`;
 
                    Iif (isVoidElement(tagName)) {
                        yield* write(openTag.replace('>', ' />'));
                        elementCount++;
                        return;
                    }
 
                    yield* write(openTag);
 
                    if (text !== undefined) {
                        yield* write(escapeHtml(String(text)));
                    } else if (Echildren) {
                        yield* streamComponent(children, depth + 1);
                    }
 
                    yield* write(`</${tagName}>`);
                    elementCount++;
                } else if (props === null || props === undefined) {
                    // Handle null/undefined props - render empty element
                    Iif (isVoidElement(tagName)) {
                        yield* write(`<${tagName} />`);
                    } else {
                        yield* write(`<${tagName}></${tagName}>`);
                    }
                    elementCount++;
                } else if (Etypeof props === 'string') {
                    const content = escapeHtml(props);
                    if (isVoidElement(tagName)) {
                        yield* write(`<${tagName} />`);
                    } else {
                        yield* write(`<${tagName}>${content}</${tagName}>`);
                    }
                    elementCount++;
                }
            }
        }
    }
 
    // Start streaming
    try {
        yield* streamComponent(component);
        yield* flushBuffer(true); // Force flush remaining buffer
    } catch (error) {
        // Stream error as HTML comment
        yield `<!-- Streaming Error: ${error.message} -->`;
    }
}
 
/**
 * Streaming utilities for common use cases
 */
export const streamingUtils = {
    /**
     * Collect all chunks into a single string
     */
    async collectChunks(chunkGenerator) {
        let html = '';
        for await (const chunk of chunkGenerator) {
            html += chunk;
        }
        return html;
    },
 
    /**
     * Stream directly to a Node.js response
     */
    async streamToResponse(chunkGenerator, response) {
        let totalBytes = 0;
        response.setHeader('Content-Type', 'text/html; charset=utf-8');
        response.setHeader('Transfer-Encoding', 'chunked');
 
        for await (const chunk of chunkGenerator) {
            response.write(chunk);
            totalBytes += Buffer.byteLength(chunk);
        }
 
        response.end();
        return totalBytes;
    },
 
    /**
     * Stream with progress callback
     */
    async* streamWithProgress(chunkGenerator, onProgress) {
        let totalBytes = 0;
        let chunkCount = 0;
 
        for await (const chunk of chunkGenerator) {
            totalBytes += Buffer.byteLength(chunk);
            chunkCount++;
 
            if (onProgress) {
                onProgress({ chunkCount, totalBytes, chunk });
            }
 
            yield chunk;
        }
    }
};
 
/**
 * Render to chunks (legacy - kept for backward compatibility)
 * For true streaming, use renderToStream() instead
 */
export function* renderToChunks(component, options = {}) {
    const mergedOptions = {
        enableCache: true,
        enableMonitoring: false,
        ...options,
        chunkSize: options.chunkSize || 1024 // Default 1KB chunks
    };
 
    const html = render(component, mergedOptions);
 
    for (let i = 0; i < html.length; i += mergedOptions.chunkSize) {
        yield html.slice(i, i + mergedOptions.chunkSize);
    }
}
 
/**
 * Get global cache instance for external access
 */
export function getCache() {
    return rendererCache;
}
 
/**
 * Reset cache (useful for testing)
 */
export function resetCache() {
    Eif (rendererCache) {
        rendererCache.clear();
    }
}
 
/**
 * Get rendering statistics
 */
export function getRenderingStats() {
    return {
        cache: rendererCache ? rendererCache.getStats() : null,
        performance: performanceMonitor.getStats()
    };
}
 
/**
 * Precompile static components for maximum performance
 */
export function precompileComponent(component, options = {}) {
    if (!isStaticElement(component)) {
        throw new Error('Can only precompile static components');
    }
 
    const html = render(component, { ...options, enableCache: false });
 
    return {
        html,
        isPrecompiled: true,
        render: () => html
    };
}
 
/**
 * Development helper - render with detailed timing
 */
export function renderWithTiming(component, options = {}) {
    const start = performance.now();
    const html = render(component, { ...options, enableMonitoring: true });
    const end = performance.now();
 
    return {
        html,
        timing: {
            total: end - start,
            breakdown: performanceMonitor.getStats()
        }
    };
}