All files / src/rendering base-renderer.js

59.36% Statements 168/283
60.49% Branches 49/81
66.66% Functions 16/24
59.36% Lines 168/283

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 4791x                                       1x   1x 1x 1x 1x     1x 1x 1x 1x     1x 1x 1x 1x 1x     1x 1x     1x 1x     1x 1x     1x 1x 1x         1x 1x 15x 15x 15x 15x 15x 15x 15x         1x 15x     15x     15x       15x     15x       15x     15x         15x                   15x 15x         1x                                                                     1x                   1x 9x 9x 9x 9x 9x   9x         1x 40x     40x         1x   30x         30x 2x 2x     30x         30x 2x 2x     30x         26x 26x 26x       30x         1x 2x   2x   2x 2x   2x 2x 2x 2x           2x       2x 2x                       2x         1x                           1x                       1x 35x               35x         1x                 1x 18x 18x 18x   18x         1x 9x 9x         1x 9x 9x         1x                             1x 7x 7x 7x 7x 7x 7x         1x             1x     1x         1x       1x 42x 2x 2x     40x 47x   47x   8x 8x   47x     47x   29x 42x         1x 72x 72x   72x 90x 90x 7x 7x 90x 59x 72x         1x 30x   30x   30x 5x 5x 5x 5x 5x   30x 30x         1x 66x   66x 66x 66x 66x 66x 66x   66x 66x               66x         1x   26x     26x     26x     26x 26x   20x 26x 1x   1x  
/**
 * Base Renderer Class
 * Provides common functionality shared across all Coherent.js renderers
 * Reduces code duplication and ensures consistent behavior
 */
 
import {
    validateComponent,
    isCoherentObject,
    extractProps,
    hasChildren,
    normalizeChildren,
} from '../core/object-utils.js';
 
import { performanceMonitor } from '../performance/monitor.js';
 
/**
 * Unified configuration for all Coherent.js renderers
 * Includes options for HTML, Streaming, and DOM renderers
 */
export const DEFAULT_RENDERER_CONFIG = {
    // Core rendering options
    maxDepth: 100,
    enableValidation: true,
    enableMonitoring: false,
    validateInput: true,
 
    // HTML Renderer specific options
    enableCache: true,
    minify: false,
    cacheSize: 1000,
    cacheTTL: 300000, // 5 minutes
 
    // Streaming Renderer specific options
    chunkSize: 1024,           // Size of each chunk in bytes
    bufferSize: 4096,          // Internal buffer size
    enableMetrics: false,      // Track streaming metrics
    yieldThreshold: 100,       // Yield control after N elements
    encoding: 'utf8',          // Output encoding
 
    // DOM Renderer specific options
    enableHydration: true,     // Enable hydration support
    namespace: null,           // SVG namespace support
 
    // Performance options
    enablePerformanceTracking: false,
    performanceThreshold: 10,  // ms threshold for slow renders
 
    // Development options
    enableDevWarnings: typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development',
    enableDebugLogging: false,
 
    // Error handling options
    errorFallback: '',         // Fallback content on errors
    throwOnError: true,        // Whether to throw or return fallback
};
 
/**
 * Base renderer class with common functionality
 */
export class BaseRenderer {
    constructor(options = {}) {
        this.config = this.validateAndMergeConfig(options);
        this.metrics = {
            startTime: null,
            endTime: null,
            elementsProcessed: 0
        };
    }
 
    /**
     * Validate and merge configuration options
     */
    validateAndMergeConfig(options) {
        const config = { ...DEFAULT_RENDERER_CONFIG, ...options };
        
        // Validate critical options
        if (typeof config.maxDepth !== 'number') {
            throw new Error('maxDepth must be a number');
        }
        if (config.maxDepth <= 0) {
            throw new Error('maxDepth must be a positive number');
        }
        
        if (typeof config.chunkSize !== 'number') {
            throw new Error('chunkSize must be a number');
        }
        if (config.chunkSize <= 0) {
            throw new Error('chunkSize must be a positive number');
        }
        
        if (typeof config.yieldThreshold !== 'number') {
            throw new Error('yieldThreshold must be a number');
        }
        if (config.yieldThreshold <= 0) {
            throw new Error('yieldThreshold must be a positive number');
        }
        
        // Warn about potentially problematic configurations
        if (config.enableDevWarnings) {
            if (config.maxDepth > 1000) {
                console.warn('Coherent.js: maxDepth > 1000 may cause performance issues');
            }
            
            if (config.chunkSize > 16384) {
                console.warn('Coherent.js: Large chunkSize may increase memory usage');
            }
        }
        
        return config;
    }
 
    /**
     * Get configuration for specific renderer type
     */
    getRendererConfig(rendererType) {
        const baseConfig = { ...this.config };
        
        switch (rendererType) {
            case 'html':
                return {
                    ...baseConfig,
                    // HTML-specific defaults
                    enableCache: baseConfig.enableCache !== false,
                    enableMonitoring: baseConfig.enableMonitoring !== false
                };
                
            case 'streaming':
                return {
                    ...baseConfig,
                    // Streaming-specific defaults
                    enableMetrics: baseConfig.enableMetrics ?? false,
                    maxDepth: baseConfig.maxDepth ?? 1000 // Higher default for streaming
                };
                
            case 'dom':
                return {
                    ...baseConfig,
                    // DOM-specific defaults
                    enableHydration: baseConfig.enableHydration !== false
                };
                
            default:
                return baseConfig;
        }
    }
 
    /**
     * Validate component structure
     */
    validateComponent(component) {
        if (this.config.validateInput !== false) {
            return validateComponent(component);
        }
        return true;
    }
 
    /**
     * Check if component is valid for rendering
     */
    isValidComponent(component) {
        if (component === null || component === undefined) return true;
        if (typeof component === 'string' || typeof component === 'number') return true;
        if (typeof component === 'function') return true;
        if (Array.isArray(component)) return component.every(child => this.isValidComponent(child));
        if (isCoherentObject(component)) return true;
        return false;
    }
 
    /**
     * Validate rendering depth to prevent stack overflow
     */
    validateDepth(depth) {
        if (depth > this.config.maxDepth) {
            throw new Error(`Maximum render depth (${this.config.maxDepth}) exceeded`);
        }
    }
 
    /**
     * Handle different component types with consistent logic
     */
    processComponentType(component) {
        // Null/undefined
        if (component === null || component === undefined) {
            return { type: 'empty', value: '' };
        }
 
        // String
        if (typeof component === 'string') {
            return { type: 'text', value: component };
        }
 
        // Number/Boolean
        if (typeof component === 'number' || typeof component === 'boolean') {
            return { type: 'text', value: String(component) };
        }
 
        // Function
        if (typeof component === 'function') {
            return { type: 'function', value: component };
        }
 
        // Array
        if (Array.isArray(component)) {
            return { type: 'array', value: component };
        }
 
        // Object (Coherent element)
        if (isCoherentObject(component)) {
            return { type: 'element', value: component };
        }
 
        // Unknown type
        return { type: 'unknown', value: component };
    }
 
    /**
     * Execute function components with error handling
     */
    executeFunctionComponent(func, depth = 0) {
        try {
            // Check if this is a context provider by checking function arity or a marker
            const isContextProvider = func.length > 0 || func.isContextProvider;
            
            let result;
            if (isContextProvider) {
                // Call with render function for context providers
                result = func((children) => {
                    return this.renderComponent(children, this.config, depth + 1);
                });
            } else {
                // Regular function component
                result = func();
            }
            
            // Handle case where function returns another function
            if (typeof result === 'function') {
                return this.executeFunctionComponent(result, depth);
            }
            
            return result;
        } catch (error) {
            if (this.config.enableMonitoring) {
                performanceMonitor.recordError('functionComponent', error);
            }
            
            // In development, provide detailed error info
            if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development') {
                console.warn('Coherent.js Function Component Error:', error.message);
            }
            
            return null;
        }
    }
 
    /**
     * Process element children consistently
     */
    processChildren(children, options, depth) {
        if (!hasChildren({ children })) {
            return [];
        }
 
        const normalizedChildren = normalizeChildren(children);
        return normalizedChildren.map(child => 
            this.renderComponent(child, options, depth + 1)
        );
    }
 
    /**
     * Extract and process element attributes
     */
    extractElementAttributes(props) {
        if (!props || typeof props !== 'object') return {};
 
        const attributes = { ...props };
        delete attributes.children;
        delete attributes.text;
        return attributes;
    }
 
    /**
     * Record performance metrics
     */
    recordPerformance(operation, startTime, fromCache = false, metadata = {}) {
        if (this.config.enableMonitoring) {
            performanceMonitor.recordRender(
                operation,
                this.getCurrentTime() - startTime,
                fromCache,
                metadata
            );
        }
    }
 
    /**
     * Record error for monitoring
     */
    recordError(operation, error, metadata = {}) {
        if (this.config.enableMonitoring) {
            performanceMonitor.recordError(operation, error, metadata);
        }
    }
 
    /**
     * Get current timestamp with fallback
     */
    getCurrentTime() {
        if (typeof performance !== 'undefined' && performance.now) {
            return performance.now();
        }
        return Date.now();
    }
 
    /**
     * Start performance timing
     */
    startTiming() {
        this.metrics.startTime = this.getCurrentTime();
    }
 
    /**
     * End performance timing
     */
    endTiming() {
        this.metrics.endTime = this.getCurrentTime();
    }
 
    /**
     * Get performance metrics
     */
    getMetrics() {
        const duration = this.metrics.endTime ? 
            this.metrics.endTime - this.metrics.startTime :
            this.getCurrentTime() - this.metrics.startTime;
 
        return {
            ...this.metrics,
            duration,
            elementsPerSecond: this.metrics.elementsProcessed / (duration / 1000)
        };
    }
 
    /**
     * Reset metrics for new render
     */
    resetMetrics() {
        this.metrics = {
            startTime: null,
            endTime: null,
            elementsProcessed: 0
        };
    }
 
    /**
     * Abstract method - must be implemented by subclasses
     */
    renderComponent() {
        throw new Error('renderComponent must be implemented by subclass');
    }
 
    /**
     * Abstract method - must be implemented by subclasses
     */
    render() {
        throw new Error('render must be implemented by subclass');
    }
}
 
/**
 * Utility functions for renderer implementations
 */
export const RendererUtils = {
    /**
     * Check if element is static (no functions)
     */
    isStaticElement(element) {
        if (!element || typeof element !== 'object') {
            return typeof element === 'string' || typeof element === 'number';
        }
 
        // Check if element has any dynamic content
        for (const [key, value] of Object.entries(element)) {
            if (typeof value === 'function') return false;
 
            if (key === 'children' && Array.isArray(value)) {
                // Recursively check children for dynamic content
                return value.every(child => RendererUtils.isStaticElement(child));
            }
 
            if (key === 'children' && typeof value === 'object' && value !== null) {
                return RendererUtils.isStaticElement(value);
            }
        }
 
        return true;
    },
 
    /**
     * Check if object has functions (for caching decisions)
     */
    hasFunctions(obj, visited = new WeakSet()) {
        if (visited.has(obj)) return false;
        visited.add(obj);
 
        for (const value of Object.values(obj)) {
            if (typeof value === 'function') return true;
            if (typeof value === 'object' && value !== null && RendererUtils.hasFunctions(value, visited)) {
                return true;
            }
        }
        return false;
    },
 
    /**
     * Get element complexity score
     */
    getElementComplexity(element) {
        if (!element || typeof element !== 'object') return 1;
 
        let complexity = Object.keys(element).length;
 
        if (element.children && Array.isArray(element.children)) {
            complexity += element.children.reduce(
                (sum, child) => sum + RendererUtils.getElementComplexity(child),
                0
            );
        }
 
        return complexity;
    },
 
    /**
     * Generate cache key for element
     */
    generateCacheKey(tagName, element) {
        try {
            // Create a stable cache key for the element
            const keyData = {
                tag: tagName,
                props: extractProps(element),
                hasChildren: hasChildren(element),
                childrenType: Array.isArray(element.children) ? 'array' : typeof element.children
            };
 
            return `element:${JSON.stringify(keyData)}`;
        } catch (error) {
            // Log error in development mode
            if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'development') {
                console.warn('Failed to generate cache key:', error);
            }
            // Return null to indicate uncacheable element
            return null;
        }
    },
 
    /**
     * Check if element is cacheable
     */
    isCacheable(element, options) {
        // Don't cache if caching is disabled
        if (!options.enableCache) return false;
 
        // Don't cache elements with functions (dynamic content)
        if (RendererUtils.hasFunctions(element)) return false;
 
        // Don't cache very large elements (memory consideration)
        if (RendererUtils.getElementComplexity(element) > 1000) return false;
 
        // Don't cache if we can't generate a stable cache key
        const cacheKey = RendererUtils.generateCacheKey(element.tagName || 'unknown', element);
        if (!cacheKey) return false;
 
        return true;
    }
};
 
export default BaseRenderer;