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

52.35% Statements 89/170
51.78% Branches 87/168
50% Functions 16/32
54% Lines 81/150

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                                        62x                                                                                             2217x 2217x                     2217x     2217x 1x   2216x 2x     2214x 1x   2213x 2x     2211x 1x   2210x 2x       2208x                       2208x                                                                                                       2518x 2513x 10x 2503x 2498x     312x 309x 316x     2186x 3x             49578x 5x                     49370x 2x       49368x 27x         49341x 6x       49335x 7x       49328x 19x       49309x 109x       49200x 49193x       7x                   29x         29x     29x       16x   13x     13x                                                                   51271x 7x                         36x                 4270x 4270x                 2146x             2117x                                                                                       62x                               520x 520x   3x           1601x   526x   1x   3x       1069x 1068x 1067x   1067x 1067x 1061x 1061x     1066x 1066x 12x       1069x     1069x 1069x       2x             62x                                                                                                                                                                                                                            
/**
 * Base Renderer Class
 * Provides common functionality shared across all Coherent.js renderers
 * Reduces code duplication and ensures consistent behavior
 */
 
import {
  validateComponent,
  isCoherentObject,
  hasChildren,
  normalizeChildren,
} from '../core/object-utils.js';
import { isTrustedContent } from '../core/html-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
  // Off by default: keying a render on its content costs a full walk of
  // the tree, which only pays off when identical trees are re-rendered.
  enableCache: false,
  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
    Iif (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 === true,
          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, depth = 0) {
    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)) {
      // Past maxDepth the renderer reports the depth error; recursing
      // further overflowed the stack on deeply nested arrays first.
      if (depth >= this.config.maxDepth) return true;
      return component.every((child) =>
        this.isValidComponent(child, depth + 1)
      );
    }
    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 };
    }
 
    // Booleans render nothing, so `cond && { li: ... }` can sit in a
    // children array (it used to print "false").
    if (typeof component === 'boolean') {
      return { type: 'empty', value: '' };
    }
 
    // Number
    if (typeof component === 'number') {
      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. Errors propagate: they used to be
   * swallowed here (the component rendered as nothing, logged only when
   * NODE_ENV=development), so a broken component produced a partial page
   * with a 200 and error boundaries never saw nested failures.
   */
  executeFunctionComponent(func, depth = 0) {
    try {
      // Always called without arguments. Functions declaring a parameter
      // used to receive a render callback returning an HTML string,
      // which then got escaped (double-escaped context providers), and a
      // `({ name }) => ...` child destructured its props from it.
      const result = func();
 
      // Handle case where function returns another function
      Iif (typeof result === 'function') {
        return this.executeFunctionComponent(result, depth);
      }
 
      return result;
    } catch (error) {
      Iif (this.config.enableMonitoring) {
        performanceMonitor.recordError('functionComponent', error);
      }
      throw error;
    }
  }
 
  /**
   * 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 = {}) {
    Iif (this.config.enableMonitoring) {
      performanceMonitor.recordError(operation, _error, metadata);
    }
  }
 
  /**
   * Get current timestamp with fallback
   */
  getCurrentTime() {
    Eif (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');
  }
}
 
const UNCACHEABLE = Symbol('uncacheable');
 
/**
 * Serialize a component tree into a string that identifies its rendered
 * output: two trees with the same key always render the same HTML.
 *
 * JSON.stringify can't be used for this. It drops functions and undefined,
 * turns NaN into null and Dates into ISO strings, and ignores the brand on
 * trusted content, so different trees (rendering different HTML) collided.
 * Values whose output isn't a pure function of their content — functions,
 * class instances, Dates — make the tree uncacheable instead.
 *
 * @param {*} value - Component tree
 * @returns {string|null} Cache key, or null when the tree can't be cached
 */
export function serializeForCache(value) {
  try {
    return serialize(value, new Set());
  } catch (error) {
    Eif (error === UNCACHEABLE) return null;
    throw error;
  }
}
 
function serialize(value, ancestors) {
  switch (typeof value) {
    case 'string':
      return JSON.stringify(value);
    case 'number':
      return `n${value}`;
    case 'boolean':
      return value ? 't' : 'f';
    case 'undefined':
      return 'u';
    case 'object': {
      if (value === null) return 'z';
      if (isTrustedContent(value)) return `T${JSON.stringify(value.__html)}`;
      Iif (ancestors.has(value)) throw UNCACHEABLE;
 
      const isArray = Array.isArray(value);
      if (!isArray) {
        const proto = Object.getPrototypeOf(value);
        if (proto !== Object.prototype && proto !== null) throw UNCACHEABLE;
      }
 
      ancestors.add(value);
      const body = isArray
        ? value.map((item) => serialize(item, ancestors)).join(',')
        : Object.keys(value)
            .map(
              (key) =>
                `${JSON.stringify(key)}:${serialize(value[key], ancestors)}`
            )
            .join(',');
      ancestors.delete(value);
      return isArray ? `[${body}]` : `{${body}}`;
    }
    default:
      // functions, symbols, bigints
      throw UNCACHEABLE;
  }
}
 
/**
 * Utility functions for renderer implementations
 */
export const RendererUtils = {
  /**
   * Check if element is static (no functions or circular references)
   */
  isStaticElement(element, visited = new WeakSet()) {
    if (!element || typeof element !== 'object') {
      return typeof element === 'string' || typeof element === 'number';
    }
 
    // Handle circular references - treat as non-static (will be caught during render)
    if (visited.has(element)) {
      return false;
    }
    visited.add(element);
 
    // Check if element has any dynamic content
    for (const [_key, value] of Object.entries(element)) {
      if (typeof value === 'function') return false;
 
      // Recursively check arrays (including children)
      if (Array.isArray(value)) {
        const allStatic = value.every((child) =>
          RendererUtils.isStaticElement(child, visited)
        );
        if (!allStatic) return false;
      }
      // Recursively check nested objects
      else if (typeof value === 'object' && value !== null) {
        if (!RendererUtils.isStaticElement(value, visited)) return false;
      }
    }
 
    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) {
    // The whole element, not a summary of it: a key that leaves out any
    // part of the content lets two different elements share an entry.
    const serialized = serializeForCache(element);
    return serialized === null
      ? null
      : `element:${JSON.stringify(tagName)}:${serialized}`;
  },
 
  /**
   * 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;