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 | 8x 8x 1016x 1016x 8x 55x 14x 14x 14x 14x 154x 154x 154x 154x 6x 6x 14x 14x 20x 20x 20x 6x 14x 14x 14x 14x 14x 32x 32x 32x 32x 32x 698x 674x 698x 32x 32x 32x 32x 32x 32x 32x 18x 18x 18x 14x 20x 14x 32x 14x 32x 32x 16x 24x 24x 24x 24x 24x 24x 24x 8x 24x 24x 21x 3x 3x 3x 3x 3x 3x 3x 1x 3x 2x 3x 1x 3x 1x 1x 1x 1x 2099x 2099x 2099x 2099x 8x 2099x 2x 2099x 2070x 2070x 29x 29x 32x 16x 24x 24x 24x 8x 16x 8x 32x 8x 32x 32x 8x 24x 24x 24x 8x 16x 16x 16x 8x 16x 24x 8x 8x 8x 21x 11x 1x 3x 10x 24043x 24043x 72069x 55x 55x 1x 55x | /**
* Coherent.js - Object-Based Rendering Framework
* A pure JavaScript framework for server-side rendering using natural object syntax
*
* @author Coherent Framework Team
* @license MIT
*/
// Performance monitoring
import { readFileSync } from 'node:fs';
import { performanceMonitor } from './performance/monitor.js';
import { escapeHtml, createTrustedContent } from './core/html-utils.js';
// Unified HTML renderer
import {
render as renderWithHtmlRenderer,
renderToStream as streamWithHtmlRenderer
} from './rendering/html-renderer.js';
// Component system imports
import {
withState,
withStateUtils,
createStateManager,
createComponent,
defineComponent,
registerComponent,
getComponent,
getRegisteredComponents,
lazy,
isLazy,
evaluateLazy,
memo as memoWithOptions
} from './components/component-system.js';
// Component lifecycle imports
import {
ComponentLifecycle,
LIFECYCLE_PHASES,
withLifecycle,
createLifecycleHooks,
useHooks,
componentUtils as lifecycleUtils
} from './components/lifecycle.js';
// Object factory imports
import {
createElement,
createTextNode,
h
} from './core/object-factory.js';
// Component cache imports
import {
ComponentCache,
createComponentCache,
memoize
} from './performance/component-cache.js';
// Error boundary imports
import {
createErrorBoundary,
createErrorFallback,
withErrorBoundary,
createAsyncErrorBoundary,
GlobalErrorHandler,
createGlobalErrorHandler
} from './components/error-boundary.js';
// CSS Scoping System (similar to Angular View Encapsulation)
/**
* Scope id derived from the component's CSS (FNV-1a), so the same component
* renders the same HTML every time. A global counter used to give it coh-0,
* then coh-1..., which broke HTML caching and hydration comparisons. Two
* components with identical CSS may share an id; their rules are the same.
*/
function generateScopeId(cssText) {
let hash = 0x811c9dc5;
for (let i = 0; i < cssText.length; i++) {
hash ^= cssText.charCodeAt(i);
hash = Math.imul(hash, 0x01000193);
}
return `coh-${(hash >>> 0).toString(36)}`;
}
// At-rules whose blocks contain style rules; others (@keyframes,
// @font-face, @page, @property...) contain declarations or keyframe
// selectors and are left untouched.
const GROUPING_AT_RULES = new Set(['media', 'supports', 'container', 'layer', 'document', 'scope']);
function splitSelectorList(prelude) {
const parts = [];
let depth = 0;
let start = 0;
for (let i = 0; i < prelude.length; i++) {
const ch = prelude[i];
Iif (ch === '(' || ch === '[') depth++;
else Iif (ch === ')' || ch === ']') depth--;
else if (ch === ',' && depth === 0) {
parts.push(prelude.slice(start, i));
start = i + 1;
}
}
parts.push(prelude.slice(start));
return parts;
}
function scopeSelector(selector, scopeId) {
const trimmed = selector.trim();
Iif (!trimmed) return selector;
// Handle pseudo-selectors and complex selectors
if (trimmed.includes(':')) {
return trimmed.replace(/([^:]+)(:.*)?/, `$1[${scopeId}]$2`);
}
// Simple selector scoping
return `${trimmed}[${scopeId}]`;
}
/**
* Add the scope attribute to every selector in a stylesheet, recursing into
* grouping at-rules. The previous regex treated `@media (max-width: 600px)`
* and keyframe selectors (`from`, `50%`) as selectors and corrupted them.
*/
function scopeCSS(css, scopeId) {
Iif (!css || typeof css !== 'string') return css;
let result = '';
let i = 0;
while (i < css.length) {
const open = css.indexOf('{', i);
Iif (open === -1) {
result += css.slice(i);
break;
}
let depth = 1;
let j = open + 1;
while (j < css.length && depth > 0) {
if (css[j] === '{') depth++;
else if (css[j] === '}') depth--;
j++;
}
const body = css.slice(open + 1, depth === 0 ? j - 1 : j);
// Statements before the rule (`@import ...;`) pass through verbatim.
const rawPrelude = css.slice(i, open);
const semicolon = rawPrelude.lastIndexOf(';');
const lead = semicolon === -1 ? '' : rawPrelude.slice(0, semicolon + 1);
const prelude = semicolon === -1 ? rawPrelude : rawPrelude.slice(semicolon + 1);
const trimmed = prelude.trim();
if (trimmed.startsWith('@')) {
const name = trimmed.slice(1).split(/[\s({]/)[0].toLowerCase();
const inner = GROUPING_AT_RULES.has(name) ? scopeCSS(body, scopeId) : body;
result += `${lead}${prelude}{${inner}}`;
} else {
const leading = prelude.match(/^\s*/)[0];
const scoped = splitSelectorList(prelude).map((part) => scopeSelector(part, scopeId)).join(', ');
result += `${lead}${leading}${scoped} {${body}}`;
}
i = j;
}
return result;
}
function applyScopeToElement(element, scopeId) {
Iif (typeof element === 'string' || typeof element === 'number' || !element) {
return element;
}
if (Array.isArray(element)) {
return element.map(item => applyScopeToElement(item, scopeId));
}
Eif (typeof element === 'object') {
const scoped = {};
for (const [tagName, props] of Object.entries(element)) {
if (typeof props === 'object' && props !== null) {
const scopedProps = { ...props };
// Add scope attribute to the element
scopedProps[scopeId] = '';
// Recursively scope children
if (scopedProps.children) {
scopedProps.children = applyScopeToElement(scopedProps.children, scopeId);
}
scoped[tagName] = scopedProps;
} else E{
// For simple text content elements, keep them as is
// Don't add scope attributes to text-only elements
scoped[tagName] = props;
}
}
return scoped;
}
return element;
}
/**
* Mark content as safe/trusted to skip HTML escaping
* USE WITH EXTREME CAUTION - only for developer-controlled content
* NEVER use with user input!
*
* @param {string} content - Trusted content (e.g., inline scripts/styles)
* @returns {Object} Marked safe content
*/
export function dangerouslySetInnerContent(content) {
return createTrustedContent(content);
}
export { isTrustedContent, isValidAttributeName } from './core/html-utils.js';
// Hydration attribute injection
function injectHydrationAttributes(component, options) {
Iif (!component || typeof component !== 'object' || Array.isArray(component)) {
return component;
}
const tagName = Object.keys(component)[0];
Iif (!tagName) return component;
const props = component[tagName];
Iif (typeof props !== 'object' || props === null) return component;
const injected = { ...props };
if (options.hydratable) {
injected['data-hydratable'] = 'true';
}
if (options.island) {
injected['data-coherent-island'] = 'true';
}
if (options._islandComponentName) {
injected['data-coherent-island-component'] = options._islandComponentName;
}
return { [tagName]: injected };
}
/**
* Island wrapper - marks a component for island-based hydration
* @param {Function} componentFn - A function component to wrap as an island
* @returns {Function} Wrapped component that renders with island attributes
*/
export function Island(componentFn) {
const componentName = componentFn.name || 'Anonymous';
return function IslandComponent(props) {
const result = componentFn(props);
return injectHydrationAttributes(result, {
island: true,
_islandComponentName: componentName
});
};
}
// Shared by render() and renderToStream(): top-level function, scoping and
// hydration attributes, then the options the renderer itself takes.
function prepareRender(obj, options) {
const scoped = options.scoped ?? options.encapsulate ?? false;
const { scoped: _scoped, encapsulate: _encapsulate, hydratable: _hydratable, island: _island, ...rendererOptions } = options;
// Handle function components passed directly to render. Called before
// scoping: scoping a function was a no-op, so render(Fn, { scoped: true })
// came out unscoped.
let component = typeof obj === 'function' ? obj(options) : obj;
if (scoped) {
component = renderScopedComponent(component);
}
// Inject hydration attributes if needed
if (_hydratable || _island) {
component = injectHydrationAttributes(component, { hydratable: _hydratable, island: _island });
}
return { component, rendererOptions };
}
// Main rendering function
export function render(obj, options = {}) {
const { component, rendererOptions } = prepareRender(obj, options);
return renderWithHtmlRenderer(component, rendererOptions);
}
/**
* Stream a component as HTML chunks (an async generator of strings) with
* the same output as render(). The event loop gets a turn after each chunk.
*
* @example
* import { Readable } from 'node:stream';
* Readable.from(renderToStream(Page(), { chunkSize: 16384 })).pipe(res);
*
* @param {*} obj - Component to render
* @param {Object} [options] - render() options plus `chunkSize` (default 8192)
* @returns {AsyncGenerator<string>}
*/
export function renderToStream(obj, options = {}) {
const { component, rendererOptions } = prepareRender(obj, options);
return streamWithHtmlRenderer(component, rendererOptions);
}
export { streamingUtils } from './rendering/html-renderer.js';
function collectStyleText(element, out = []) {
if (Array.isArray(element)) {
element.forEach((item) => collectStyleText(item, out));
} else Eif (element && typeof element === 'object') {
for (const [tagName, props] of Object.entries(element)) {
if (tagName === 'style' && props && typeof props === 'object' && typeof props.text === 'string') {
out.push(props.text);
} else if (props && typeof props === 'object' && props.children) {
collectStyleText(props.children, out);
}
}
}
return out;
}
// Internal: Scoped rendering with CSS encapsulation
function renderScopedComponent(component) {
const scopeId = generateScopeId(collectStyleText(component).join('\n'));
// Handle style elements specially
function processScopedElement(element) {
Iif (!element || typeof element !== 'object') {
return element;
}
if (Array.isArray(element)) {
return element.map(processScopedElement);
}
const result = {};
for (const [tagName, props] of Object.entries(element)) {
if (tagName === 'style' && typeof props === 'object' && props.text) {
// Scope CSS within style tags
result[tagName] = {
...props,
text: scopeCSS(props.text, scopeId)
};
} else if (typeof props === 'object' && props !== null) {
// Recursively process children
const scopedProps = { ...props };
if (scopedProps.children) {
scopedProps.children = processScopedElement(scopedProps.children);
}
result[tagName] = scopedProps;
} else E{
result[tagName] = props;
}
}
return result;
}
// First process styles, then apply scope attributes
const processedComponent = processScopedElement(component);
const scopedComponent = applyScopeToElement(processedComponent, scopeId);
return scopedComponent;
}
// Component system - Re-export from component-system for unified API
export {
Component,
withState,
withStateUtils,
createStateManager,
createComponent,
createHOC,
defineComponent,
memoComponent,
registerComponent,
getComponent,
getRegisteredComponents,
lazy,
isLazy,
evaluateLazy
} from './components/component-system.js';
// HTML utilities. escapeHtml is also imported below for the default export;
// index.js used to carry a second copy that escaped ' as ' instead of
// ', so the package shipped two different escapers.
export {
escapeHtml,
isVoidElement,
formatAttributes
} from './core/html-utils.js';
// Cache management
export {
cacheManager,
createCacheManager
} from './performance/cache-manager.js';
// Component lifecycle exports
export {
ComponentLifecycle,
LIFECYCLE_PHASES,
withLifecycle,
createLifecycleHooks,
useHooks,
componentUtils as lifecycleUtils
} from './components/lifecycle.js';
// Object factory exports
export {
createElement,
createTextNode,
h
} from './core/object-factory.js';
// Component cache exports
export {
ComponentCache,
createComponentCache,
memoize
} from './performance/component-cache.js';
// Error boundaries
export {
createErrorBoundary,
createErrorFallback,
withErrorBoundary,
createAsyncErrorBoundary,
GlobalErrorHandler,
createGlobalErrorHandler
};
export {
renderWithMonitoring,
renderWithTemplate,
renderComponentFactory,
isCoherentComponent,
createErrorResponse
} from './utils/render-utils.js';
export {
isPeerDependencyAvailable,
importPeerDependency,
createLazyIntegration,
checkPeerDependencies
} from './utils/dependency-utils.js';
export {
hasChildren,
normalizeChildren
} from './core/object-utils.js';
// HTML nesting validation exports
export {
validateNesting,
FORBIDDEN_CHILDREN,
HTMLNestingError
} from './core/html-nesting-rules.js';
/**
* Memoize a component (or any function). Each memoized function has its own
* cache: this used to be one module-level Map keyed only by props, so two
* components called with the same props returned each other's output.
*
* @param {Function} component - Component or function to memoize
* @param {Function|Object} [options] - Key function `(props) => key`, or
* options `{ keyFn, maxSize, strategy, ttl, stats, onHit, onMiss, onEvict }`
* @returns {Function} Memoized function with `clear()`, `has()`, `size()`...
*/
export function memo(component, options = {}) {
// Components receive `{}` when called without props, as they always have.
const withDefaultProps = (props = {}, ...rest) => component(props, ...rest);
if (typeof options === 'function') {
const keyGenerator = options;
return memoWithOptions(withDefaultProps, { keyFn: (props = {}, ...rest) => keyGenerator(props, ...rest) });
}
return memoWithOptions(withDefaultProps, options);
}
export function validateComponent(obj) {
Iif (!obj || typeof obj !== 'object') {
throw new Error('Component must be an object');
}
return true;
}
export function isCoherentObject(obj) {
return obj && typeof obj === 'object' && !Array.isArray(obj);
}
export function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (obj instanceof Date) return new Date(obj);
if (Array.isArray(obj)) return obj.map(deepClone);
const cloned = {};
for (const [key, value] of Object.entries(obj)) {
cloned[key] = deepClone(value);
}
return cloned;
}
/* global __COHERENT_VERSION__ */
// Substituted with the manifest version by esbuild `define` at build time
// (a literal, so it works in both the ESM and CJS bundles); the fallback
// covers running from source inside the monorepo.
export const VERSION = typeof __COHERENT_VERSION__ !== 'undefined'
? __COHERENT_VERSION__
: JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
// Performance monitoring export
export { performanceMonitor };
// Shadow DOM exports
export { shadowDOM };
// Import Shadow DOM functionality
import * as shadowDOM from './shadow-dom.js';
// Event system imports and exports
import eventSystemDefault, {
EventBus,
createEventBus,
globalEventBus,
emit,
emitSync,
on,
once,
off,
registerAction,
handleAction,
DOMEventIntegration,
globalDOMIntegration,
initializeDOMIntegration,
withEventBus,
withEventState,
createActionHandlers,
createEventHandlers,
createEventComponent
} from './events/index.js';
export {
eventSystemDefault as eventSystem,
EventBus,
createEventBus,
globalEventBus,
emit,
emitSync,
on,
once,
off,
registerAction,
handleAction,
DOMEventIntegration,
globalDOMIntegration,
initializeDOMIntegration,
withEventBus,
withEventState,
createActionHandlers,
createEventHandlers,
createEventComponent
};
// Enhanced FP composition tools
export { hoc, compose } from './components/enhanced-composition.js';
/**
* Functional programming utilities
*/
export const fp = {
/**
* Curried map: fp.map(fn)(array)
*/
map(fn) {
return (array) => array.map(fn);
}
};
// Note: Forms have been moved to @coherent.js/forms package
// Default export
const coherent = {
// Core rendering
render,
renderToStream,
// Shadow DOM (client-side only)
shadowDOM,
// Component system
createComponent,
defineComponent,
registerComponent,
getComponent,
getRegisteredComponents,
lazy,
isLazy,
evaluateLazy,
// Component lifecycle
ComponentLifecycle,
LIFECYCLE_PHASES,
withLifecycle,
createLifecycleHooks,
useHooks,
lifecycleUtils,
// Object factory
createElement,
createTextNode,
h,
// Component cache
ComponentCache,
createComponentCache,
memoize,
// State management
withState,
withStateUtils,
createStateManager,
memo,
// Error boundaries
createErrorBoundary,
createErrorFallback,
withErrorBoundary,
createAsyncErrorBoundary,
GlobalErrorHandler,
createGlobalErrorHandler,
// Event system
eventSystem: eventSystemDefault,
emit,
emitSync,
on,
once,
off,
registerAction,
handleAction,
withEventBus,
withEventState,
// Utilities
validateComponent,
isCoherentObject,
deepClone,
escapeHtml,
performanceMonitor,
VERSION
};
export default coherent;
|