@coherent.js/core 1.0.0-beta.3 → 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,9 +1,18 @@
1
1
  var __defProp = Object.defineProperty;
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
2
8
  var __export = (target, all) => {
3
9
  for (var name in all)
4
10
  __defProp(target, name, { get: all[name], enumerable: true });
5
11
  };
6
12
 
13
+ // src/index.js
14
+ import { readFileSync } from "node:fs";
15
+
7
16
  // src/performance/monitor.js
8
17
  function createPerformanceMonitor(options = {}) {
9
18
  const opts = {
@@ -29,6 +38,7 @@ function createPerformanceMonitor(options = {}) {
29
38
  },
30
39
  alerts: {
31
40
  enabled: true,
41
+ debounceMs: 5e3,
32
42
  rules: []
33
43
  },
34
44
  resources: {
@@ -190,7 +200,7 @@ function createPerformanceMonitor(options = {}) {
190
200
  const alertKey = `${rule.metric}-${rule.condition}-${rule.threshold}`;
191
201
  const lastTriggered = alertState.triggered.get(alertKey);
192
202
  const now = Date.now();
193
- if (!lastTriggered || now - lastTriggered > 5e3) {
203
+ if (!lastTriggered || now - lastTriggered > opts.alerts.debounceMs) {
194
204
  alertState.triggered.set(alertKey, now);
195
205
  alertState.history.push({
196
206
  rule,
@@ -592,737 +602,2256 @@ function validateComponent(component, path = "root") {
592
602
  }
593
603
  throw new Error(`Invalid component type at ${path}: ${typeof component}`);
594
604
  }
595
-
596
- // src/components/component-system.js
597
- var COMPONENT_REGISTRY = /* @__PURE__ */ new Map();
598
- var COMPONENT_METADATA = /* @__PURE__ */ new WeakMap();
599
- var ComponentState = class {
600
- constructor(initialState = {}) {
601
- this.state = { ...initialState };
602
- this.listeners = /* @__PURE__ */ new Set();
603
- this.isUpdating = false;
605
+ function isCoherentObject(obj) {
606
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
607
+ return false;
604
608
  }
605
- /**
606
- * Get state value by key or entire state
607
- *
608
- * @param {string} [key] - State key to retrieve
609
- * @returns {*} State value or entire state object
610
- */
611
- get(key) {
612
- return key ? this.state[key] : { ...this.state };
609
+ const keys = Object.keys(obj);
610
+ if (keys.length === 0) {
611
+ return false;
613
612
  }
614
- /**
615
- * Update state with new values
616
- *
617
- * @param {Object} updates - State updates to apply
618
- * @returns {ComponentState} This instance for chaining
619
- */
620
- set(updates) {
621
- if (this.isUpdating) return this;
622
- const oldState = { ...this.state };
623
- if (typeof updates === "function") {
624
- updates = updates(oldState);
613
+ return keys.every((key) => {
614
+ if (key === "text") return true;
615
+ return /^[a-zA-Z][a-zA-Z0-9-]*$/.test(key);
616
+ });
617
+ }
618
+ function extractProps(coherentObj) {
619
+ if (!isCoherentObject(coherentObj)) {
620
+ return {};
621
+ }
622
+ const props = {};
623
+ const keys = Object.keys(coherentObj);
624
+ keys.forEach((tag) => {
625
+ const value = coherentObj[tag];
626
+ if (value && typeof value === "object" && !Array.isArray(value)) {
627
+ props[tag] = { ...value };
628
+ } else {
629
+ props[tag] = { text: value };
625
630
  }
626
- this.state = { ...this.state, ...updates };
627
- this.notifyListeners(oldState, this.state);
628
- return this;
629
- }
630
- subscribe(listener) {
631
- this.listeners.add(listener);
632
- return () => this.listeners.delete(listener);
631
+ });
632
+ return props;
633
+ }
634
+ function hasChildren(component) {
635
+ if (Array.isArray(component)) {
636
+ return component.length > 0;
633
637
  }
634
- notifyListeners(oldState, newState) {
635
- if (this.listeners.size === 0) return;
636
- this.isUpdating = true;
637
- this.listeners.forEach((listener) => {
638
- try {
639
- listener(newState, oldState);
640
- } catch (_error) {
641
- console.error("State listener _error:", _error);
642
- }
638
+ if (isCoherentObject(component)) {
639
+ if (component.children !== void 0 && component.children !== null) {
640
+ return Array.isArray(component.children) ? component.children.length > 0 : true;
641
+ }
642
+ const keys = Object.keys(component);
643
+ return keys.some((key) => {
644
+ const value = component[key];
645
+ return value && typeof value === "object" && value.children;
643
646
  });
644
- this.isUpdating = false;
645
647
  }
648
+ return false;
649
+ }
650
+ function normalizeChildren(children) {
651
+ if (children === null || children === void 0) {
652
+ return [];
653
+ }
654
+ if (Array.isArray(children)) {
655
+ return children.flat().filter((child) => child !== null && child !== void 0);
656
+ }
657
+ return [children];
658
+ }
659
+
660
+ // src/rendering/base-renderer.js
661
+ var DEFAULT_RENDERER_CONFIG = {
662
+ // Core rendering options
663
+ maxDepth: 100,
664
+ enableValidation: true,
665
+ enableMonitoring: false,
666
+ validateInput: true,
667
+ // HTML Renderer specific options
668
+ enableCache: true,
669
+ minify: false,
670
+ cacheSize: 1e3,
671
+ cacheTTL: 3e5,
672
+ // 5 minutes
673
+ // Streaming Renderer specific options
674
+ chunkSize: 1024,
675
+ // Size of each chunk in bytes
676
+ bufferSize: 4096,
677
+ // Internal buffer size
678
+ enableMetrics: false,
679
+ // Track streaming metrics
680
+ yieldThreshold: 100,
681
+ // Yield control after N elements
682
+ encoding: "utf8",
683
+ // Output encoding
684
+ // DOM Renderer specific options
685
+ enableHydration: true,
686
+ // Enable hydration support
687
+ namespace: null,
688
+ // SVG namespace support
689
+ // Performance options
690
+ enablePerformanceTracking: false,
691
+ performanceThreshold: 10,
692
+ // ms threshold for slow renders
693
+ // Development options
694
+ enableDevWarnings: typeof process !== "undefined" && process.env && true,
695
+ enableDebugLogging: false,
696
+ // Error handling options
697
+ errorFallback: "",
698
+ // Fallback content on errors
699
+ throwOnError: true
700
+ // Whether to throw or return fallback
646
701
  };
647
- var Component = class _Component {
648
- constructor(definition = {}) {
649
- this.definition = definition;
650
- this.name = definition.name || "AnonymousComponent";
651
- this.props = {};
652
- this.state = new ComponentState(definition.state || {});
653
- this.children = [];
654
- this.parent = null;
655
- this.rendered = null;
656
- this.isMounted = false;
657
- this.isDestroyed = false;
658
- this.hooks = {
659
- beforeCreate: definition.beforeCreate || (() => {
660
- }),
661
- created: definition.created || (() => {
662
- }),
663
- beforeMount: definition.beforeMount || (() => {
664
- }),
665
- mounted: definition.mounted || (() => {
666
- }),
667
- beforeUpdate: definition.beforeUpdate || (() => {
668
- }),
669
- updated: definition.updated || (() => {
670
- }),
671
- beforeDestroy: definition.beforeDestroy || (() => {
672
- }),
673
- destroyed: definition.destroyed || (() => {
674
- }),
675
- errorCaptured: definition.errorCaptured || (() => {
676
- })
702
+ var BaseRenderer = class {
703
+ constructor(options = {}) {
704
+ this.config = this.validateAndMergeConfig(options);
705
+ this.metrics = {
706
+ startTime: null,
707
+ endTime: null,
708
+ elementsProcessed: 0
677
709
  };
678
- this.methods = definition.methods || {};
679
- Object.keys(this.methods).forEach((methodName) => {
680
- if (typeof this.methods[methodName] === "function") {
681
- this[methodName] = this.methods[methodName].bind(this);
682
- }
683
- });
684
- this.computed = definition.computed || {};
685
- this.computedCache = /* @__PURE__ */ new Map();
686
- this.watchers = definition.watch || {};
687
- this.setupWatchers();
688
- COMPONENT_METADATA.set(this, {
689
- createdAt: Date.now(),
690
- updateCount: 0,
691
- renderCount: 0
692
- });
693
- this.callHook("beforeCreate");
694
- this.initialize();
695
- this.callHook("created");
696
710
  }
697
711
  /**
698
- * Initialize component
712
+ * Validate and merge configuration options
699
713
  */
700
- initialize() {
701
- this.unsubscribeState = this.state.subscribe((newState, oldState) => {
702
- this.onStateChange(newState, oldState);
703
- });
704
- this.initializeComputed();
714
+ validateAndMergeConfig(options) {
715
+ const config = { ...DEFAULT_RENDERER_CONFIG, ...options };
716
+ if (typeof config.maxDepth !== "number") {
717
+ throw new Error("maxDepth must be a number");
718
+ }
719
+ if (config.maxDepth <= 0) {
720
+ throw new Error("maxDepth must be a positive number");
721
+ }
722
+ if (typeof config.chunkSize !== "number") {
723
+ throw new Error("chunkSize must be a number");
724
+ }
725
+ if (config.chunkSize <= 0) {
726
+ throw new Error("chunkSize must be a positive number");
727
+ }
728
+ if (typeof config.yieldThreshold !== "number") {
729
+ throw new Error("yieldThreshold must be a number");
730
+ }
731
+ if (config.yieldThreshold <= 0) {
732
+ throw new Error("yieldThreshold must be a positive number");
733
+ }
734
+ if (config.enableDevWarnings) {
735
+ if (config.maxDepth > 1e3) {
736
+ console.warn("Coherent.js: maxDepth > 1000 may cause performance issues");
737
+ }
738
+ if (config.chunkSize > 16384) {
739
+ console.warn("Coherent.js: Large chunkSize may increase memory usage");
740
+ }
741
+ }
742
+ return config;
705
743
  }
706
744
  /**
707
- * Set up watchers for reactive data
745
+ * Get configuration for specific renderer type
708
746
  */
709
- setupWatchers() {
710
- Object.keys(this.watchers).forEach((key) => {
711
- const handler = this.watchers[key];
712
- this.state.subscribe((newState, oldState) => {
713
- if (newState[key] !== oldState[key]) {
714
- handler.call(this, newState[key], oldState[key]);
715
- }
716
- });
717
- });
747
+ getRendererConfig(rendererType) {
748
+ const baseConfig = { ...this.config };
749
+ switch (rendererType) {
750
+ case "html":
751
+ return {
752
+ ...baseConfig,
753
+ // HTML-specific defaults
754
+ enableCache: baseConfig.enableCache !== false,
755
+ enableMonitoring: baseConfig.enableMonitoring !== false
756
+ };
757
+ case "streaming":
758
+ return {
759
+ ...baseConfig,
760
+ // Streaming-specific defaults
761
+ enableMetrics: baseConfig.enableMetrics ?? false,
762
+ maxDepth: baseConfig.maxDepth ?? 1e3
763
+ // Higher default for streaming
764
+ };
765
+ case "dom":
766
+ return {
767
+ ...baseConfig,
768
+ // DOM-specific defaults
769
+ enableHydration: baseConfig.enableHydration !== false
770
+ };
771
+ default:
772
+ return baseConfig;
773
+ }
718
774
  }
719
775
  /**
720
- * Initialize computed properties
776
+ * Validate component structure
721
777
  */
722
- initializeComputed() {
723
- Object.keys(this.computed).forEach((key) => {
724
- Object.defineProperty(this, key, {
725
- get: () => {
726
- if (!this.computedCache.has(key)) {
727
- const value = this.computed[key].call(this);
728
- this.computedCache.set(key, value);
729
- }
730
- return this.computedCache.get(key);
731
- },
732
- enumerable: true
733
- });
734
- });
778
+ validateComponent(component) {
779
+ if (this.config.validateInput !== false) {
780
+ return validateComponent(component);
781
+ }
782
+ return true;
735
783
  }
736
784
  /**
737
- * Handle state changes
785
+ * Check if component is valid for rendering
738
786
  */
739
- onStateChange() {
740
- if (this.isDestroyed) return;
741
- this.computedCache.clear();
742
- if (this.isMounted) {
743
- this.update();
744
- }
787
+ isValidComponent(component) {
788
+ if (component === null || component === void 0) return true;
789
+ if (typeof component === "string" || typeof component === "number") return true;
790
+ if (typeof component === "function") return true;
791
+ if (Array.isArray(component)) return component.every((child) => this.isValidComponent(child));
792
+ if (isCoherentObject(component)) return true;
793
+ return false;
745
794
  }
746
795
  /**
747
- * Call lifecycle hook
796
+ * Validate rendering depth to prevent stack overflow
748
797
  */
749
- callHook(hookName, ...args) {
750
- try {
751
- if (this.hooks[hookName]) {
752
- return this.hooks[hookName].call(this, ...args);
753
- }
754
- } catch (_error) {
755
- this.handleError(_error, `${hookName} hook`);
798
+ validateDepth(depth) {
799
+ if (depth > this.config.maxDepth) {
800
+ throw new Error(`Maximum render depth (${this.config.maxDepth}) exceeded`);
756
801
  }
757
802
  }
758
803
  /**
759
- * Handle component errors
804
+ * Handle different component types with consistent logic
760
805
  */
761
- handleError(_error) {
762
- console.error(`Component Error in ${this.name}:`, _error);
763
- this.callHook("errorCaptured", _error);
764
- if (this.parent && this.parent.handleError) {
765
- this.parent.handleError(_error, `${this.name} -> ${context}`);
806
+ processComponentType(component) {
807
+ if (component === null || component === void 0) {
808
+ return { type: "empty", value: "" };
809
+ }
810
+ if (typeof component === "string") {
811
+ return { type: "text", value: component };
812
+ }
813
+ if (typeof component === "number" || typeof component === "boolean") {
814
+ return { type: "text", value: String(component) };
815
+ }
816
+ if (typeof component === "function") {
817
+ return { type: "function", value: component };
818
+ }
819
+ if (Array.isArray(component)) {
820
+ return { type: "array", value: component };
821
+ }
822
+ if (isCoherentObject(component)) {
823
+ return { type: "element", value: component };
766
824
  }
825
+ return { type: "unknown", value: component };
767
826
  }
768
827
  /**
769
- * Render the component
828
+ * Execute function components with _error handling
770
829
  */
771
- render(props = {}) {
772
- if (this.isDestroyed) {
773
- console.warn(`Attempting to render destroyed component: ${this.name}`);
774
- return null;
775
- }
830
+ executeFunctionComponent(func, depth = 0) {
776
831
  try {
777
- const metadata = COMPONENT_METADATA.get(this);
778
- if (metadata) {
779
- metadata.renderCount++;
780
- }
781
- this.props = { ...props };
782
- if (typeof this.definition.render === "function") {
783
- this.rendered = this.definition.render.call(this, this.props, this.state.get());
784
- } else if (typeof this.definition.template !== "undefined") {
785
- this.rendered = this.processTemplate(this.definition.template, this.props, this.state.get());
832
+ const isContextProvider = func.length > 0 || func.isContextProvider;
833
+ let result;
834
+ if (isContextProvider) {
835
+ result = func((children) => {
836
+ return this.renderComponent(children, this.config, depth + 1);
837
+ });
786
838
  } else {
787
- throw new Error(`Component ${this.name} must have either render method or template`);
839
+ result = func();
788
840
  }
789
- if (this.rendered !== null) {
790
- validateComponent(this.rendered, this.name);
841
+ if (typeof result === "function") {
842
+ return this.executeFunctionComponent(result, depth);
791
843
  }
792
- return this.rendered;
844
+ return result;
793
845
  } catch (_error) {
794
- this.handleError(_error);
795
- return { div: { className: "component-_error", text: `Error in ${this.name}` } };
846
+ if (this.config.enableMonitoring) {
847
+ performanceMonitor.recordError("functionComponent", _error);
848
+ }
849
+ if (typeof process !== "undefined" && process.env && true) {
850
+ console.warn("Coherent.js Function Component Error:", _error.message);
851
+ }
852
+ return null;
796
853
  }
797
854
  }
798
855
  /**
799
- * Process template with data
856
+ * Process element children consistently
800
857
  */
801
- processTemplate(template, props, state) {
802
- if (typeof template === "function") {
803
- return template.call(this, props, state);
804
- }
805
- if (typeof template === "string") {
806
- return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
807
- return props[key] || state[key] || "";
808
- });
858
+ processChildren(children, options, depth) {
859
+ if (!hasChildren({ children })) {
860
+ return [];
809
861
  }
810
- const processed = deepClone(template);
811
- this.interpolateObject(processed, { ...props, ...state });
812
- return processed;
862
+ const normalizedChildren = normalizeChildren(children);
863
+ return normalizedChildren.map(
864
+ (child) => this.renderComponent(child, options, depth + 1)
865
+ );
813
866
  }
814
867
  /**
815
- * Interpolate object with data
868
+ * Extract and process element attributes
816
869
  */
817
- interpolateObject(obj, data) {
818
- if (typeof obj === "string") {
819
- return obj.replace(/\{\{(\w+)\}\}/g, (match, key) => data[key] || "");
870
+ extractElementAttributes(props) {
871
+ if (!props || typeof props !== "object") return {};
872
+ const attributes = { ...props };
873
+ delete attributes.children;
874
+ delete attributes.text;
875
+ return attributes;
876
+ }
877
+ /**
878
+ * Record performance metrics
879
+ */
880
+ recordPerformance(operation, startTime, fromCache = false, metadata = {}) {
881
+ if (this.config.enableMonitoring) {
882
+ performanceMonitor.recordRender(
883
+ operation,
884
+ this.getCurrentTime() - startTime,
885
+ fromCache,
886
+ metadata
887
+ );
820
888
  }
821
- if (Array.isArray(obj)) {
822
- return obj.map((item) => this.interpolateObject(item, data));
889
+ }
890
+ /**
891
+ * Record _error for monitoring
892
+ */
893
+ recordError(operation, _error, metadata = {}) {
894
+ if (this.config.enableMonitoring) {
895
+ performanceMonitor.recordError(operation, _error, metadata);
823
896
  }
824
- if (obj && typeof obj === "object") {
825
- Object.keys(obj).forEach((key) => {
826
- obj[key] = this.interpolateObject(obj[key], data);
827
- });
897
+ }
898
+ /**
899
+ * Get current timestamp with fallback
900
+ */
901
+ getCurrentTime() {
902
+ if (typeof performance !== "undefined" && performance.now) {
903
+ return performance.now();
828
904
  }
829
- return obj;
905
+ return Date.now();
830
906
  }
831
907
  /**
832
- * Mount the component
908
+ * Start performance timing
833
909
  */
834
- mount() {
835
- if (this.isMounted || this.isDestroyed) return this;
836
- this.callHook("beforeMount");
837
- this.isMounted = true;
838
- this.callHook("mounted");
839
- return this;
910
+ startTiming() {
911
+ this.metrics.startTime = this.getCurrentTime();
840
912
  }
841
913
  /**
842
- * Update the component
914
+ * End performance timing
843
915
  */
844
- update() {
845
- if (!this.isMounted || this.isDestroyed) return this;
846
- const metadata = COMPONENT_METADATA.get(this);
847
- if (metadata) {
848
- metadata.updateCount++;
849
- }
850
- this.callHook("beforeUpdate");
851
- this.callHook("updated");
852
- return this;
916
+ endTiming() {
917
+ this.metrics.endTime = this.getCurrentTime();
853
918
  }
854
919
  /**
855
- * Destroy the component
920
+ * Get performance metrics
856
921
  */
857
- destroy() {
858
- if (this.isDestroyed) return this;
859
- this.callHook("beforeDestroy");
860
- if (this.unsubscribeState) {
861
- this.unsubscribeState();
862
- }
863
- this.children.forEach((child) => {
864
- if (child.destroy) {
865
- child.destroy();
866
- }
867
- });
868
- this.isMounted = false;
869
- this.isDestroyed = true;
870
- this.children = [];
871
- this.parent = null;
872
- this.callHook("destroyed");
873
- return this;
922
+ getMetrics() {
923
+ const duration = this.metrics.endTime ? this.metrics.endTime - this.metrics.startTime : this.getCurrentTime() - this.metrics.startTime;
924
+ return {
925
+ ...this.metrics,
926
+ duration,
927
+ elementsPerSecond: this.metrics.elementsProcessed / (duration / 1e3)
928
+ };
874
929
  }
875
930
  /**
876
- * Get component metadata
931
+ * Reset metrics for new render
877
932
  */
878
- getMetadata() {
879
- return COMPONENT_METADATA.get(this) || {};
933
+ resetMetrics() {
934
+ this.metrics = {
935
+ startTime: null,
936
+ endTime: null,
937
+ elementsProcessed: 0
938
+ };
880
939
  }
881
940
  /**
882
- * Clone component with new props/state
941
+ * Abstract method - must be implemented by subclasses
883
942
  */
884
- clone(overrides = {}) {
885
- const newDefinition = { ...this.definition, ...overrides };
886
- return new _Component(newDefinition);
943
+ renderComponent() {
944
+ throw new Error("renderComponent must be implemented by subclass");
945
+ }
946
+ /**
947
+ * Abstract method - must be implemented by subclasses
948
+ */
949
+ render() {
950
+ throw new Error("render must be implemented by subclass");
887
951
  }
888
952
  };
889
- function createComponent(definition) {
890
- if (typeof definition === "function") {
891
- definition = {
892
- name: definition.name || "FunctionalComponent",
893
- render: definition
894
- };
953
+ var RendererUtils = {
954
+ /**
955
+ * Check if element is static (no functions or circular references)
956
+ */
957
+ isStaticElement(element, visited = /* @__PURE__ */ new WeakSet()) {
958
+ if (!element || typeof element !== "object") {
959
+ return typeof element === "string" || typeof element === "number";
960
+ }
961
+ if (visited.has(element)) {
962
+ return false;
963
+ }
964
+ visited.add(element);
965
+ for (const [_key, value] of Object.entries(element)) {
966
+ if (typeof value === "function") return false;
967
+ if (Array.isArray(value)) {
968
+ const allStatic = value.every((child) => RendererUtils.isStaticElement(child, visited));
969
+ if (!allStatic) return false;
970
+ } else if (typeof value === "object" && value !== null) {
971
+ if (!RendererUtils.isStaticElement(value, visited)) return false;
972
+ }
973
+ }
974
+ return true;
975
+ },
976
+ /**
977
+ * Check if object has functions (for caching decisions)
978
+ */
979
+ hasFunctions(obj, visited = /* @__PURE__ */ new WeakSet()) {
980
+ if (visited.has(obj)) return false;
981
+ visited.add(obj);
982
+ for (const value of Object.values(obj)) {
983
+ if (typeof value === "function") return true;
984
+ if (typeof value === "object" && value !== null && RendererUtils.hasFunctions(value, visited)) {
985
+ return true;
986
+ }
987
+ }
988
+ return false;
989
+ },
990
+ /**
991
+ * Get element complexity score
992
+ */
993
+ getElementComplexity(element) {
994
+ if (!element || typeof element !== "object") return 1;
995
+ let complexity = Object.keys(element).length;
996
+ if (element.children && Array.isArray(element.children)) {
997
+ complexity += element.children.reduce(
998
+ (sum, child) => sum + RendererUtils.getElementComplexity(child),
999
+ 0
1000
+ );
1001
+ }
1002
+ return complexity;
1003
+ },
1004
+ /**
1005
+ * Generate cache key for element
1006
+ */
1007
+ generateCacheKey(tagName, element) {
1008
+ try {
1009
+ const keyData = {
1010
+ tag: tagName,
1011
+ props: extractProps(element),
1012
+ hasChildren: hasChildren(element),
1013
+ childrenType: Array.isArray(element.children) ? "array" : typeof element.children
1014
+ };
1015
+ return `element:${JSON.stringify(keyData)}`;
1016
+ } catch (_error) {
1017
+ if (typeof process !== "undefined" && process.env && true) {
1018
+ console.warn("Failed to generate cache key:", _error);
1019
+ }
1020
+ return null;
1021
+ }
1022
+ },
1023
+ /**
1024
+ * Check if element is cacheable
1025
+ */
1026
+ isCacheable(element, options) {
1027
+ if (!options.enableCache) return false;
1028
+ if (RendererUtils.hasFunctions(element)) return false;
1029
+ if (RendererUtils.getElementComplexity(element) > 1e3) return false;
1030
+ const cacheKey = RendererUtils.generateCacheKey(element.tagName || "unknown", element);
1031
+ if (!cacheKey) return false;
1032
+ return true;
895
1033
  }
896
- return new Component(definition);
897
- }
898
- function defineComponent(definition) {
899
- const componentFactory = (props) => {
900
- const component = new Component(definition);
901
- return component.render(props);
902
- };
903
- componentFactory.componentName = definition.name || "Component";
904
- componentFactory.definition = definition;
905
- return componentFactory;
1034
+ };
1035
+
1036
+ // src/core/html-nesting-rules.js
1037
+ var FORBIDDEN_CHILDREN = {
1038
+ // Phrasing content only - cannot contain flow content
1039
+ p: /* @__PURE__ */ new Set([
1040
+ "address",
1041
+ "article",
1042
+ "aside",
1043
+ "blockquote",
1044
+ "div",
1045
+ "dl",
1046
+ "fieldset",
1047
+ "footer",
1048
+ "form",
1049
+ "h1",
1050
+ "h2",
1051
+ "h3",
1052
+ "h4",
1053
+ "h5",
1054
+ "h6",
1055
+ "header",
1056
+ "hr",
1057
+ "main",
1058
+ "nav",
1059
+ "ol",
1060
+ "p",
1061
+ "pre",
1062
+ "section",
1063
+ "table",
1064
+ "ul",
1065
+ "figure",
1066
+ "figcaption"
1067
+ ]),
1068
+ // Interactive content restrictions
1069
+ a: /* @__PURE__ */ new Set(["a"]),
1070
+ // Links cannot nest
1071
+ button: /* @__PURE__ */ new Set(["button", "a", "input", "select", "textarea", "label"]),
1072
+ label: /* @__PURE__ */ new Set(["label"]),
1073
+ // Table structure restrictions
1074
+ thead: /* @__PURE__ */ new Set(["thead", "tbody", "tfoot", "caption", "colgroup", "tr"]),
1075
+ tbody: /* @__PURE__ */ new Set(["thead", "tbody", "tfoot", "caption", "colgroup"]),
1076
+ tfoot: /* @__PURE__ */ new Set(["thead", "tbody", "tfoot", "caption", "colgroup"]),
1077
+ tr: /* @__PURE__ */ new Set(["tr", "thead", "tbody", "tfoot", "table"]),
1078
+ td: /* @__PURE__ */ new Set(["td", "th", "tr", "thead", "tbody", "tfoot", "table"]),
1079
+ th: /* @__PURE__ */ new Set(["td", "th", "tr", "thead", "tbody", "tfoot", "table"]),
1080
+ // Other common restrictions
1081
+ select: /* @__PURE__ */ new Set(["select", "input", "textarea"]),
1082
+ option: /* @__PURE__ */ new Set(["option", "optgroup"])
1083
+ };
1084
+ function validateNesting(parentTag, childTag, path = "", options = {}) {
1085
+ if (!parentTag || !childTag) {
1086
+ return true;
1087
+ }
1088
+ const parent = parentTag.toLowerCase();
1089
+ const child = childTag.toLowerCase();
1090
+ const forbidden = FORBIDDEN_CHILDREN[parent];
1091
+ if (!forbidden || !forbidden.has(child)) {
1092
+ return true;
1093
+ }
1094
+ const pathSuffix = path ? ` at ${path}` : "";
1095
+ const message = `Invalid HTML nesting: <${child}> cannot be a child of <${parent}>${pathSuffix}. Browsers will auto-correct this, causing potential hydration mismatches.`;
1096
+ if (options.throwOnError) {
1097
+ throw new HTMLNestingError(message, { parent, child, path });
1098
+ }
1099
+ const shouldWarn = options.warn !== false && (typeof process === "undefined" || !process.env || true);
1100
+ if (shouldWarn) {
1101
+ console.warn(`[Coherent.js] ${message}`);
1102
+ }
1103
+ return false;
906
1104
  }
907
- function registerComponent(name, definition) {
908
- if (COMPONENT_REGISTRY.has(name)) {
909
- console.warn(`Component ${name} is already registered. Overriding.`);
1105
+ var HTMLNestingError = class extends Error {
1106
+ constructor(message, context2 = {}) {
1107
+ super(message);
1108
+ this.name = "HTMLNestingError";
1109
+ this.parent = context2.parent;
1110
+ this.child = context2.child;
1111
+ this.path = context2.path;
910
1112
  }
911
- const component = typeof definition === "function" ? defineComponent({ name, render: definition }) : defineComponent(definition);
912
- COMPONENT_REGISTRY.set(name, component);
913
- return component;
1113
+ };
1114
+
1115
+ // src/core/html-utils.js
1116
+ function escapeHtml(text) {
1117
+ if (typeof text !== "string") return text;
1118
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
914
1119
  }
915
- function getComponent(name) {
916
- return COMPONENT_REGISTRY.get(name);
1120
+ function isVoidElement(tagName) {
1121
+ if (typeof tagName !== "string") {
1122
+ return false;
1123
+ }
1124
+ const voidElements = /* @__PURE__ */ new Set([
1125
+ "area",
1126
+ "base",
1127
+ "br",
1128
+ "col",
1129
+ "embed",
1130
+ "hr",
1131
+ "img",
1132
+ "input",
1133
+ "link",
1134
+ "meta",
1135
+ "param",
1136
+ "source",
1137
+ "track",
1138
+ "wbr"
1139
+ ]);
1140
+ return voidElements.has(tagName.toLowerCase());
917
1141
  }
918
- function getRegisteredComponents() {
919
- return new Map(COMPONENT_REGISTRY);
1142
+ function formatAttributes(props) {
1143
+ let formatted = "";
1144
+ for (const key in props) {
1145
+ if (props.hasOwnProperty(key)) {
1146
+ let value = props[key];
1147
+ const attributeName = key === "className" ? "class" : key;
1148
+ if (typeof value === "function") {
1149
+ if (attributeName.startsWith("on")) {
1150
+ const actionId = `__coherent_action_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
1151
+ const DEBUG = typeof process !== "undefined" && process && process.env && (process.env.COHERENT_DEBUG === "1" || true) || typeof window !== "undefined" && window && window.COHERENT_DEBUG === true;
1152
+ if (typeof global !== "undefined") {
1153
+ if (!global.__coherentActionRegistry) {
1154
+ global.__coherentActionRegistry = {};
1155
+ if (DEBUG) console.log("Initialized global action registry");
1156
+ }
1157
+ global.__coherentActionRegistry[actionId] = value;
1158
+ if (DEBUG) console.log(`Added action ${actionId} to global registry, total: ${Object.keys(global.__coherentActionRegistry).length}`);
1159
+ if (DEBUG) console.log(`Global registry keys: ${Object.keys(global.__coherentActionRegistry).join(", ")}`);
1160
+ if (DEBUG) {
1161
+ if (typeof global.__coherentActionRegistryLog === "undefined") {
1162
+ global.__coherentActionRegistryLog = [];
1163
+ }
1164
+ global.__coherentActionRegistryLog.push({
1165
+ action: "add",
1166
+ actionId,
1167
+ timestamp: Date.now(),
1168
+ registrySize: Object.keys(global.__coherentActionRegistry).length
1169
+ });
1170
+ }
1171
+ } else if (typeof window !== "undefined") {
1172
+ if (!window.__coherentActionRegistry) {
1173
+ window.__coherentActionRegistry = {};
1174
+ if (DEBUG) console.log("Initialized window action registry");
1175
+ }
1176
+ window.__coherentActionRegistry[actionId] = value;
1177
+ if (DEBUG) console.log(`Added action ${actionId} to window registry, total: ${Object.keys(window.__coherentActionRegistry).length}`);
1178
+ if (DEBUG) console.log(`Window registry keys: ${Object.keys(window.__coherentActionRegistry).join(", ")}`);
1179
+ }
1180
+ const eventType = attributeName.substring(2);
1181
+ formatted += ` data-action="${actionId}" data-event="${eventType}"`;
1182
+ continue;
1183
+ } else {
1184
+ try {
1185
+ value = value();
1186
+ } catch (_error) {
1187
+ console.warn(`Error executing function for attribute '${key}':`, {
1188
+ _error: _error.message,
1189
+ stack: _error.stack,
1190
+ attributeKey: key
1191
+ });
1192
+ value = "";
1193
+ }
1194
+ }
1195
+ }
1196
+ if (value === true) {
1197
+ formatted += ` ${attributeName}`;
1198
+ } else if (value !== false && value !== null && value !== void 0) {
1199
+ formatted += ` ${attributeName}="${escapeHtml(String(value))}"`;
1200
+ }
1201
+ }
1202
+ }
1203
+ return formatted.trim();
920
1204
  }
921
- if (performanceMonitor) {
922
- const originalRender = Component.prototype.render;
923
- Component.prototype.render = function(...args) {
924
- const start = performance.now();
925
- const result = originalRender.apply(this, args);
926
- const duration = performance.now() - start;
927
- performanceMonitor.recordMetric("renderTime", duration, {
928
- type: "component",
929
- name: this.name,
930
- propsSize: JSON.stringify(this.props || {}).length,
931
- hasState: Object.keys(this.state?.get() || {}).length > 0
932
- });
933
- return result;
934
- };
1205
+ function minifyHtml(html, options = {}) {
1206
+ if (!options.minify) return html;
1207
+ return html.replace(/<!--[\s\S]*?-->/g, "").replace(/\s+/g, " ").replace(/>\s+</g, "><").trim();
935
1208
  }
936
- function lazy(factory, options = {}) {
1209
+
1210
+ // src/performance/cache-manager.js
1211
+ function createCacheManager(options = {}) {
937
1212
  const {
938
- cache = true,
939
- // Cache the result after first evaluation
940
- timeout = null,
941
- // Optional timeout for evaluation
942
- fallback = null,
943
- // Fallback value if evaluation fails
944
- onError = null,
945
- // Error handler
946
- dependencies = []
947
- // Dependencies that invalidate cache
1213
+ maxCacheSize = 1e3,
1214
+ maxMemoryMB = 100,
1215
+ ttlMs = 1e3 * 60 * 5,
1216
+ // 5 minutes
1217
+ enableStatistics = true
948
1218
  } = options;
949
- let cached = false;
950
- let cachedValue = null;
951
- let isEvaluating = false;
952
- let lastDependencyHash = null;
953
- const lazyWrapper = {
954
- // Mark as lazy for identification
955
- __isLazy: true,
956
- __factory: factory,
957
- __options: options,
958
- // Evaluation method
959
- evaluate(...args) {
960
- if (isEvaluating) {
961
- console.warn("Lazy evaluation cycle detected, returning fallback");
962
- return fallback;
1219
+ const caches = {
1220
+ static: /* @__PURE__ */ new Map(),
1221
+ // Never-changing components
1222
+ component: /* @__PURE__ */ new Map(),
1223
+ // Component results with deps
1224
+ template: /* @__PURE__ */ new Map(),
1225
+ // Template strings
1226
+ data: /* @__PURE__ */ new Map()
1227
+ // General purpose data
1228
+ };
1229
+ let memoryUsage = 0;
1230
+ const stats = {
1231
+ hits: 0,
1232
+ misses: 0,
1233
+ hitRate: {
1234
+ static: 0,
1235
+ component: 0,
1236
+ template: 0,
1237
+ data: 0
1238
+ },
1239
+ accessCount: {
1240
+ static: 0,
1241
+ component: 0,
1242
+ template: 0,
1243
+ data: 0
1244
+ }
1245
+ };
1246
+ let cleanupInterval;
1247
+ if (typeof setInterval === "function") {
1248
+ cleanupInterval = setInterval(() => cleanup(), 3e4);
1249
+ if (cleanupInterval.unref) {
1250
+ cleanupInterval.unref();
1251
+ }
1252
+ }
1253
+ function generateCacheKey(component, props = {}, context2 = {}) {
1254
+ const componentStr = typeof component === "function" ? component.name || component.toString() : JSON.stringify(component);
1255
+ const propsStr = JSON.stringify(props, Object.keys(props).sort());
1256
+ const contextStr = JSON.stringify(context2);
1257
+ const hash = simpleHash(componentStr + propsStr + contextStr);
1258
+ return `${extractComponentName(component)}_${hash}`;
1259
+ }
1260
+ function get(key, type = "component") {
1261
+ const cache = caches[type] || caches.component;
1262
+ const entry = cache.get(key);
1263
+ if (!entry) {
1264
+ stats.misses++;
1265
+ if (enableStatistics) stats.accessCount[type]++;
1266
+ return null;
1267
+ }
1268
+ if (Date.now() - entry.timestamp > ttlMs) {
1269
+ cache.delete(key);
1270
+ updateMemoryUsage(-entry.size);
1271
+ stats.misses++;
1272
+ if (enableStatistics) stats.accessCount[type]++;
1273
+ return null;
1274
+ }
1275
+ entry.lastAccess = Date.now();
1276
+ entry.accessCount++;
1277
+ stats.hits++;
1278
+ if (enableStatistics) {
1279
+ stats.accessCount[type]++;
1280
+ stats.hitRate[type] = stats.hits / (stats.hits + stats.misses) * 100;
1281
+ }
1282
+ return entry.value;
1283
+ }
1284
+ function set(key, value, type = "component", metadata = {}) {
1285
+ const cache = caches[type] || caches.component;
1286
+ const size = calculateSize(value);
1287
+ if (memoryUsage + size > maxMemoryMB * 1024 * 1024) {
1288
+ optimize(type, size);
1289
+ }
1290
+ const entry = {
1291
+ value,
1292
+ timestamp: Date.now(),
1293
+ lastAccess: Date.now(),
1294
+ size,
1295
+ metadata,
1296
+ accessCount: 0
1297
+ };
1298
+ const existing = cache.get(key);
1299
+ if (existing) {
1300
+ updateMemoryUsage(-existing.size);
1301
+ }
1302
+ cache.set(key, entry);
1303
+ updateMemoryUsage(size);
1304
+ if (cache.size > maxCacheSize) {
1305
+ optimize(type);
1306
+ }
1307
+ }
1308
+ function remove(key, type) {
1309
+ if (type) {
1310
+ const cache = caches[type];
1311
+ if (!cache) return false;
1312
+ const entry = cache.get(key);
1313
+ if (entry) {
1314
+ updateMemoryUsage(-entry.size);
1315
+ return cache.delete(key);
963
1316
  }
964
- if (cache && dependencies.length > 0) {
965
- const currentHash = hashDependencies(dependencies);
966
- if (lastDependencyHash !== null && lastDependencyHash !== currentHash) {
967
- cached = false;
968
- cachedValue = null;
969
- }
970
- lastDependencyHash = currentHash;
1317
+ return false;
1318
+ }
1319
+ for (const [, cache] of Object.entries(caches)) {
1320
+ const entry = cache.get(key);
1321
+ if (entry) {
1322
+ updateMemoryUsage(-entry.size);
1323
+ return cache.delete(key);
971
1324
  }
972
- if (cache && cached) {
973
- return cachedValue;
1325
+ }
1326
+ return false;
1327
+ }
1328
+ function clear(type) {
1329
+ if (type) {
1330
+ const cache = caches[type];
1331
+ if (cache) {
1332
+ cache.clear();
974
1333
  }
975
- isEvaluating = true;
976
- try {
977
- let result;
978
- if (timeout) {
979
- result = evaluateWithTimeout(factory, timeout, args, fallback);
980
- } else {
981
- result = typeof factory === "function" ? factory(...args) : factory;
982
- }
983
- if (result && typeof result.then === "function") {
984
- return result.catch((_error) => {
985
- if (onError) onError(_error);
986
- return fallback;
987
- });
988
- }
989
- if (cache) {
990
- cached = true;
991
- cachedValue = result;
992
- }
993
- return result;
994
- } catch (_error) {
995
- if (onError) {
996
- onError(_error);
997
- } else {
998
- console.error("Lazy evaluation _error:", _error);
1334
+ } else {
1335
+ Object.values(caches).forEach((cache) => cache.clear());
1336
+ }
1337
+ memoryUsage = 0;
1338
+ }
1339
+ function getStats() {
1340
+ const entries = Object.values(caches).reduce((sum, cache) => sum + cache.size, 0);
1341
+ return {
1342
+ hits: stats.hits,
1343
+ misses: stats.misses,
1344
+ size: memoryUsage,
1345
+ entries,
1346
+ hitRate: stats.hitRate,
1347
+ accessCount: stats.accessCount
1348
+ };
1349
+ }
1350
+ function cleanup() {
1351
+ const now = Date.now();
1352
+ let freed = 0;
1353
+ for (const [, cache] of Object.entries(caches)) {
1354
+ for (const [key, entry] of cache.entries()) {
1355
+ if (now - entry.timestamp > ttlMs) {
1356
+ cache.delete(key);
1357
+ updateMemoryUsage(-entry.size);
1358
+ freed++;
999
1359
  }
1000
- return fallback;
1001
- } finally {
1002
- isEvaluating = false;
1003
1360
  }
1004
- },
1005
- // Force re-evaluation
1006
- invalidate() {
1007
- cached = false;
1008
- cachedValue = null;
1009
- lastDependencyHash = null;
1010
- return this;
1011
- },
1012
- // Check if evaluated
1013
- isEvaluated() {
1014
- return cached;
1015
- },
1016
- // Get cached value without evaluation
1017
- getCachedValue() {
1018
- return cachedValue;
1019
- },
1020
- // Transform the lazy value
1021
- map(transform) {
1022
- return lazy((...args) => {
1023
- const value = this.evaluate(...args);
1024
- return transform(value);
1025
- }, { ...options, cache: false });
1026
- },
1027
- // Chain lazy evaluations
1028
- flatMap(transform) {
1029
- return lazy((...args) => {
1030
- const value = this.evaluate(...args);
1031
- const transformed = transform(value);
1032
- if (isLazy(transformed)) {
1033
- return transformed.evaluate(...args);
1034
- }
1035
- return transformed;
1036
- }, { ...options, cache: false });
1037
- },
1038
- // Convert to string for debugging
1039
- toString() {
1040
- return `[Lazy${cached ? " (cached)" : ""}]`;
1041
- },
1042
- // JSON serialization
1043
- toJSON() {
1044
- return this.evaluate();
1045
1361
  }
1046
- };
1047
- return lazyWrapper;
1048
- }
1049
- function isLazy(value) {
1050
- return value && typeof value === "object" && value.__isLazy === true;
1051
- }
1052
- function evaluateLazy(obj, ...args) {
1053
- if (isLazy(obj)) {
1054
- return obj.evaluate(...args);
1362
+ return { freed };
1055
1363
  }
1056
- if (Array.isArray(obj)) {
1057
- return obj.map((item) => evaluateLazy(item, ...args));
1364
+ function calculateSize(value) {
1365
+ if (value === null || value === void 0) return 0;
1366
+ if (typeof value === "string") return value.length * 2;
1367
+ if (typeof value === "number") return 8;
1368
+ if (typeof value === "boolean") return 4;
1369
+ if (Array.isArray(value)) {
1370
+ return value.reduce((sum, item) => sum + calculateSize(item), 0);
1371
+ }
1372
+ if (typeof value === "object") {
1373
+ return Object.values(value).reduce((sum, val) => sum + calculateSize(val), 0);
1374
+ }
1375
+ return 0;
1058
1376
  }
1059
- if (obj && typeof obj === "object") {
1060
- const result = {};
1061
- for (const [key, value] of Object.entries(obj)) {
1062
- result[key] = evaluateLazy(value, ...args);
1377
+ function updateMemoryUsage(delta) {
1378
+ memoryUsage = Math.max(0, memoryUsage + delta);
1379
+ }
1380
+ function optimize(type, requiredSpace = 0) {
1381
+ const cache = caches[type] || caches.component;
1382
+ const entries = Array.from(cache.entries()).sort(([, a], [, b]) => a.lastAccess - b.lastAccess);
1383
+ let freed = 0;
1384
+ for (const [key, entry] of entries) {
1385
+ if (freed >= requiredSpace) break;
1386
+ cache.delete(key);
1387
+ updateMemoryUsage(-entry.size);
1388
+ freed += entry.size;
1063
1389
  }
1064
- return result;
1390
+ return { freed };
1065
1391
  }
1066
- return obj;
1067
- }
1068
- function hashDependencies(dependencies) {
1069
- return dependencies.map((dep) => {
1070
- if (typeof dep === "function") {
1071
- return dep.toString();
1392
+ function simpleHash(str) {
1393
+ let hash = 0;
1394
+ for (let i = 0; i < str.length; i++) {
1395
+ const char = str.charCodeAt(i);
1396
+ hash = (hash << 5) - hash + char;
1397
+ hash = hash & hash;
1072
1398
  }
1073
- return JSON.stringify(dep);
1074
- }).join("|");
1075
- }
1076
- function evaluateWithTimeout(factory, timeout, args, fallback) {
1077
- return new Promise((resolve, reject) => {
1078
- const timer = setTimeout(() => {
1079
- reject(new Error(`Lazy evaluation timeout after ${timeout}ms`));
1080
- }, timeout);
1081
- try {
1082
- const result = factory(...args);
1083
- if (result && typeof result.then === "function") {
1084
- result.then((value) => {
1085
- clearTimeout(timer);
1086
- resolve(value);
1087
- }).catch((_error) => {
1088
- clearTimeout(timer);
1089
- reject(_error);
1090
- });
1091
- } else {
1092
- clearTimeout(timer);
1093
- resolve(result);
1094
- }
1095
- } catch (_error) {
1096
- clearTimeout(timer);
1097
- reject(_error);
1399
+ return Math.abs(hash).toString(36);
1400
+ }
1401
+ function extractComponentName(component) {
1402
+ if (typeof component === "function") {
1403
+ return component.name || "AnonymousComponent";
1098
1404
  }
1099
- }).catch(() => fallback);
1100
- }
1101
- function memo(fn, options = {}) {
1102
- const {
1103
- // Caching strategy
1104
- strategy = "lru",
1105
- // 'lru', 'ttl', 'weak', 'simple'
1106
- maxSize = 100,
1107
- // Maximum cache entries
1108
- ttl = null,
1109
- // Time to live in milliseconds
1110
- // Key generation
1111
- keyFn = null,
1112
- // Custom key function
1113
- keySerializer = JSON.stringify,
1114
- // Default serialization
1115
- // Comparison
1116
- // eslint-disable-next-line no-unused-vars
1117
- compareFn = null,
1118
- // Custom equality comparison
1119
- // eslint-disable-next-line no-unused-vars
1120
- shallow = false,
1121
- // Shallow comparison for objects
1122
- // Lifecycle hooks
1123
- onHit = null,
1124
- // Called on cache hit
1125
- onMiss = null,
1126
- // Called on cache miss
1127
- onEvict = null,
1128
- // Called when item evicted
1129
- // Performance
1130
- stats = false,
1131
- // Track hit/miss statistics
1132
- // Development
1133
- debug = false
1134
- // Debug logging
1135
- } = options;
1136
- let cache;
1137
- const stats_data = stats ? { hits: 0, misses: 0, evictions: 0 } : null;
1138
- switch (strategy) {
1139
- case "lru":
1140
- cache = new LRUCache(maxSize, { onEvict });
1141
- break;
1142
- case "ttl":
1143
- cache = new TTLCache(ttl, { onEvict });
1144
- break;
1145
- case "weak":
1146
- cache = /* @__PURE__ */ new WeakMap();
1147
- break;
1148
- default:
1149
- cache = /* @__PURE__ */ new Map();
1405
+ if (component && typeof component === "object") {
1406
+ const keys = Object.keys(component);
1407
+ return keys.length > 0 ? keys[0] : "ObjectComponent";
1408
+ }
1409
+ return "UnknownComponent";
1150
1410
  }
1151
- const generateKey = keyFn || ((...args) => {
1152
- if (args.length === 0) return "__empty__";
1153
- if (args.length === 1) return keySerializer(args[0]);
1154
- return keySerializer(args);
1155
- });
1156
- const memoizedFn = (...args) => {
1157
- const key = generateKey(...args);
1158
- if (cache.has(key)) {
1159
- const cached = cache.get(key);
1160
- if (cached && (!cached.expires || Date.now() < cached.expires)) {
1161
- if (debug) console.log(`Memo cache hit for key: ${key}`);
1162
- if (onHit) onHit(key, cached.value, args);
1163
- if (stats_data) stats_data.hits++;
1164
- return cached.value || cached;
1165
- } else {
1166
- cache.delete(key);
1167
- }
1411
+ function destroy() {
1412
+ if (cleanupInterval) {
1413
+ clearInterval(cleanupInterval);
1168
1414
  }
1169
- if (debug) console.log(`Memo cache miss for key: ${key}`);
1170
- if (onMiss) onMiss(key, args);
1171
- if (stats_data) stats_data.misses++;
1172
- const result = fn(...args);
1173
- const cacheEntry = ttl ? { value: result, expires: Date.now() + ttl } : result;
1174
- cache.set(key, cacheEntry);
1175
- return result;
1176
- };
1177
- memoizedFn.cache = cache;
1178
- memoizedFn.clear = () => cache.clear();
1179
- memoizedFn.delete = (key) => cache.delete(key);
1180
- memoizedFn.has = (key) => cache.has(key);
1181
- memoizedFn.size = () => cache.size;
1182
- if (stats_data) {
1183
- memoizedFn.stats = () => ({ ...stats_data });
1184
- memoizedFn.resetStats = () => {
1185
- stats_data.hits = 0;
1186
- stats_data.misses = 0;
1187
- stats_data.evictions = 0;
1188
- };
1415
+ clear();
1189
1416
  }
1190
- memoizedFn.refresh = (...args) => {
1191
- const key = generateKey(...args);
1192
- cache.delete(key);
1193
- return memoizedFn(...args);
1417
+ return {
1418
+ get,
1419
+ set,
1420
+ remove,
1421
+ clear,
1422
+ getStats,
1423
+ cleanup,
1424
+ destroy,
1425
+ generateCacheKey,
1426
+ get memoryUsage() {
1427
+ return memoryUsage;
1428
+ },
1429
+ get maxMemory() {
1430
+ return maxMemoryMB * 1024 * 1024;
1431
+ }
1194
1432
  };
1195
- return memoizedFn;
1196
1433
  }
1197
- var LRUCache = class {
1198
- constructor(maxSize = 100, options = {}) {
1199
- this.maxSize = maxSize;
1200
- this.cache = /* @__PURE__ */ new Map();
1201
- this.onEvict = options.onEvict;
1202
- }
1203
- get(key) {
1204
- if (this.cache.has(key)) {
1205
- const value = this.cache.get(key);
1206
- this.cache.delete(key);
1207
- this.cache.set(key, value);
1208
- return value;
1209
- }
1210
- return void 0;
1211
- }
1212
- set(key, value) {
1213
- if (this.cache.has(key)) {
1214
- this.cache.delete(key);
1215
- } else if (this.cache.size >= this.maxSize) {
1216
- const firstKey = this.cache.keys().next().value;
1217
- const evicted = this.cache.get(firstKey);
1218
- this.cache.delete(firstKey);
1219
- if (this.onEvict) {
1220
- this.onEvict(firstKey, evicted);
1221
- }
1434
+ var cacheManager = createCacheManager();
1435
+
1436
+ // src/utils/error-handler.js
1437
+ var CoherentError = class _CoherentError extends Error {
1438
+ constructor(message, options = {}) {
1439
+ super(message);
1440
+ this.name = "CoherentError";
1441
+ this.type = options.type || "generic";
1442
+ this.code = options.code || `COHERENT_${String(this.type).toUpperCase()}`;
1443
+ this.docsUrl = options.docsUrl || `/docs/core/errors#${this.code}`;
1444
+ this.component = options.component;
1445
+ this.context = options.context;
1446
+ this.suggestions = options.suggestions || [];
1447
+ this.timestamp = Date.now();
1448
+ if (Error.captureStackTrace) {
1449
+ Error.captureStackTrace(this, _CoherentError);
1222
1450
  }
1223
- this.cache.set(key, value);
1224
- }
1225
- has(key) {
1226
- return this.cache.has(key);
1227
- }
1228
- delete(key) {
1229
- return this.cache.delete(key);
1230
- }
1231
- clear() {
1232
- this.cache.clear();
1233
1451
  }
1234
- get size() {
1235
- return this.cache.size;
1452
+ toJSON() {
1453
+ return {
1454
+ name: this.name,
1455
+ message: this.message,
1456
+ type: this.type,
1457
+ code: this.code,
1458
+ docsUrl: this.docsUrl,
1459
+ component: this.component,
1460
+ context: this.context,
1461
+ suggestions: this.suggestions,
1462
+ timestamp: this.timestamp,
1463
+ stack: this.stack
1464
+ };
1236
1465
  }
1237
1466
  };
1238
- var TTLCache = class {
1239
- constructor(ttl, options = {}) {
1240
- this.ttl = ttl;
1241
- this.cache = /* @__PURE__ */ new Map();
1242
- this.timers = /* @__PURE__ */ new Map();
1243
- this.onEvict = options.onEvict;
1244
- }
1245
- get(key) {
1246
- if (this.cache.has(key)) {
1247
- const entry = this.cache.get(key);
1248
- if (Date.now() < entry.expires) {
1249
- return entry.value;
1250
- } else {
1251
- this.delete(key);
1252
- }
1253
- }
1254
- return void 0;
1467
+ var ComponentValidationError = class extends CoherentError {
1468
+ constructor(message, component, suggestions = []) {
1469
+ super(message, {
1470
+ type: "validation",
1471
+ component,
1472
+ suggestions: [
1473
+ "Check component structure and syntax",
1474
+ "Ensure all required properties are present",
1475
+ "Validate prop types and values",
1476
+ ...suggestions
1477
+ ]
1478
+ });
1479
+ this.name = "ComponentValidationError";
1255
1480
  }
1256
- set(key, value) {
1257
- if (this.timers.has(key)) {
1258
- clearTimeout(this.timers.get(key));
1481
+ };
1482
+ var RenderingError = class extends CoherentError {
1483
+ constructor(message, component, context2, suggestions = []) {
1484
+ super(message, {
1485
+ type: "rendering",
1486
+ component,
1487
+ context: context2,
1488
+ suggestions: [
1489
+ "Check for circular references",
1490
+ "Validate component depth",
1491
+ "Ensure all functions return valid components",
1492
+ ...suggestions
1493
+ ]
1494
+ });
1495
+ this.name = "RenderingError";
1496
+ if (context2 && context2.path) {
1497
+ this.renderPath = context2.path;
1259
1498
  }
1260
- const expires = Date.now() + this.ttl;
1261
- this.cache.set(key, { value, expires });
1262
- const timer = setTimeout(() => {
1263
- this.delete(key);
1264
- }, this.ttl);
1265
- this.timers.set(key, timer);
1266
1499
  }
1267
- has(key) {
1268
- if (this.cache.has(key)) {
1269
- const entry = this.cache.get(key);
1270
- return Date.now() < entry.expires;
1271
- }
1272
- return false;
1500
+ };
1501
+ var PerformanceError = class extends CoherentError {
1502
+ constructor(message, metrics, suggestions = []) {
1503
+ super(message, {
1504
+ type: "performance",
1505
+ context: metrics,
1506
+ suggestions: [
1507
+ "Consider component memoization",
1508
+ "Reduce component complexity",
1509
+ "Enable caching",
1510
+ ...suggestions
1511
+ ]
1512
+ });
1513
+ this.name = "PerformanceError";
1273
1514
  }
1274
- delete(key) {
1275
- const had = this.cache.has(key);
1276
- if (had) {
1277
- const entry = this.cache.get(key);
1278
- this.cache.delete(key);
1279
- if (this.timers.has(key)) {
1280
- clearTimeout(this.timers.get(key));
1281
- this.timers.delete(key);
1282
- }
1283
- if (this.onEvict) {
1284
- this.onEvict(key, entry.value);
1285
- }
1515
+ };
1516
+ var StateError = class extends CoherentError {
1517
+ constructor(message, state, suggestions = []) {
1518
+ super(message, {
1519
+ type: "state",
1520
+ context: state,
1521
+ suggestions: [
1522
+ "Check state mutations",
1523
+ "Ensure proper state initialization",
1524
+ "Validate state transitions",
1525
+ ...suggestions
1526
+ ]
1527
+ });
1528
+ this.name = "StateError";
1529
+ }
1530
+ };
1531
+ var ErrorHandler = class {
1532
+ constructor(options = {}) {
1533
+ const isDev = typeof process !== "undefined" && process.env && true;
1534
+ const envForceSilent = typeof process !== "undefined" && process.env && process.env.COHERENT_SILENT === "1";
1535
+ const envForceDebug = typeof process !== "undefined" && process.env && process.env.COHERENT_DEBUG === "1";
1536
+ const defaultEnableLogging = envForceSilent ? false : envForceDebug ? true : isDev;
1537
+ this.options = {
1538
+ enableStackTrace: options.enableStackTrace !== false,
1539
+ enableSuggestions: options.enableSuggestions !== false,
1540
+ enableLogging: options.enableLogging ?? defaultEnableLogging,
1541
+ logLevel: options.logLevel || "_error",
1542
+ maxErrorHistory: options.maxErrorHistory || 100,
1543
+ ...options
1544
+ };
1545
+ this.errorHistory = [];
1546
+ this.errorCounts = /* @__PURE__ */ new Map();
1547
+ this.suppressedErrors = /* @__PURE__ */ new Set();
1548
+ }
1549
+ /**
1550
+ * Handle and report errors with detailed context
1551
+ */
1552
+ handle(_error, context2 = {}) {
1553
+ const enhancedError = this.enhanceError(_error, context2);
1554
+ this.addToHistory(enhancedError);
1555
+ if (this.options.enableLogging) {
1556
+ this.logError(enhancedError);
1286
1557
  }
1287
- return had;
1558
+ return enhancedError;
1288
1559
  }
1289
- clear() {
1290
- this.timers.forEach((timer) => clearTimeout(timer));
1291
- this.timers.clear();
1292
- this.cache.clear();
1560
+ /**
1561
+ * Enhance existing errors with more context
1562
+ */
1563
+ enhanceError(_error, context2 = {}) {
1564
+ if (_error instanceof CoherentError) {
1565
+ return _error;
1566
+ }
1567
+ const errorType = this.classifyError(_error, context2);
1568
+ switch (errorType) {
1569
+ case "validation":
1570
+ return new ComponentValidationError(
1571
+ _error.message,
1572
+ context2.component,
1573
+ this.generateSuggestions(_error, context2)
1574
+ );
1575
+ case "rendering":
1576
+ return new RenderingError(
1577
+ _error.message,
1578
+ context2.component,
1579
+ context2.renderContext,
1580
+ this.generateSuggestions(_error, context2)
1581
+ );
1582
+ case "performance":
1583
+ return new PerformanceError(
1584
+ _error.message,
1585
+ context2.metrics,
1586
+ this.generateSuggestions(_error, context2)
1587
+ );
1588
+ case "state":
1589
+ return new StateError(
1590
+ _error.message,
1591
+ context2.state,
1592
+ this.generateSuggestions(_error, context2)
1593
+ );
1594
+ default:
1595
+ return new CoherentError(_error.message, {
1596
+ type: errorType,
1597
+ component: context2.component,
1598
+ context: context2.context,
1599
+ suggestions: this.generateSuggestions(_error, context2)
1600
+ });
1601
+ }
1293
1602
  }
1294
- get size() {
1295
- return this.cache.size;
1603
+ /**
1604
+ * Classify _error type based on message and context
1605
+ */
1606
+ classifyError(_error, context2) {
1607
+ const message = _error.message.toLowerCase();
1608
+ if (message.includes("invalid") || message.includes("validation") || message.includes("required") || message.includes("type")) {
1609
+ return "validation";
1610
+ }
1611
+ if (message.includes("render") || message.includes("circular") || message.includes("depth") || message.includes("cannot render")) {
1612
+ return "rendering";
1613
+ }
1614
+ if (message.includes("slow") || message.includes("memory") || message.includes("performance") || message.includes("timeout")) {
1615
+ return "performance";
1616
+ }
1617
+ if (message.includes("state") || message.includes("mutation") || message.includes("store") || context2.state) {
1618
+ return "state";
1619
+ }
1620
+ if (context2.component) return "validation";
1621
+ if (context2.renderContext) return "rendering";
1622
+ if (context2.metrics) return "performance";
1623
+ return "generic";
1296
1624
  }
1297
- };
1298
- function withState(initialState = {}, options = {}) {
1299
- const {
1300
- // State options
1301
- persistent = false,
1302
- // Persist state across component unmounts
1303
- storageKey = null,
1304
- // Key for persistent storage
1305
- storage = typeof window !== "undefined" && typeof window.localStorage !== "undefined" ? window.localStorage : {
1306
- // Fallback storage for Node.js environments
1307
- _data: /* @__PURE__ */ new Map(),
1308
- setItem(key, value) {
1309
- this._data.set(key, value);
1625
+ /**
1626
+ * Generate helpful suggestions based on _error
1627
+ */
1628
+ generateSuggestions(_error, context2 = {}) {
1629
+ const suggestions = [];
1630
+ const message = _error.message.toLowerCase();
1631
+ const patterns = [
1632
+ {
1633
+ pattern: /cannot render|render.*failed/,
1634
+ suggestions: [
1635
+ "Check if component returns a valid object structure",
1636
+ "Ensure all properties are properly defined",
1637
+ "Look for undefined variables or null references"
1638
+ ]
1310
1639
  },
1311
- getItem(key) {
1312
- return this._data.get(key) || null;
1640
+ {
1641
+ pattern: /circular.*reference/,
1642
+ suggestions: [
1643
+ "Remove circular references between components",
1644
+ "Use lazy loading or memoization to break cycles",
1645
+ "Check for self-referencing components"
1646
+ ]
1313
1647
  },
1314
- removeItem(key) {
1315
- this._data.delete(key);
1648
+ {
1649
+ pattern: /maximum.*depth/,
1650
+ suggestions: [
1651
+ "Reduce component nesting depth",
1652
+ "Break complex components into smaller parts",
1653
+ "Check for infinite recursion in component functions"
1654
+ ]
1316
1655
  },
1317
- clear() {
1318
- this._data.clear();
1656
+ {
1657
+ pattern: /invalid.*component/,
1658
+ suggestions: [
1659
+ "Ensure component follows the expected object structure",
1660
+ "Check property names and values for typos",
1661
+ "Verify component is not null or undefined"
1662
+ ]
1663
+ },
1664
+ {
1665
+ pattern: /performance|slow|timeout/,
1666
+ suggestions: [
1667
+ "Enable component caching",
1668
+ "Use memoization for expensive operations",
1669
+ "Reduce component complexity",
1670
+ "Consider lazy loading for large components"
1671
+ ]
1319
1672
  }
1320
- },
1321
- // Storage mechanism
1322
- // State transformation
1323
- stateTransform = null,
1324
- // Transform state before injection
1325
- propName = "state",
1673
+ ];
1674
+ patterns.forEach(({ pattern, suggestions: patternSuggestions }) => {
1675
+ if (pattern.test(message)) {
1676
+ suggestions.push(...patternSuggestions);
1677
+ }
1678
+ });
1679
+ if (context2.component) {
1680
+ const componentType = typeof context2.component;
1681
+ if (componentType === "function") {
1682
+ suggestions.push("Check function component return value");
1683
+ } else if (componentType === "object" && context2.component === null) {
1684
+ suggestions.push("Component is null - ensure proper initialization");
1685
+ } else if (Array.isArray(context2.component)) {
1686
+ suggestions.push("Arrays should contain valid component objects");
1687
+ }
1688
+ }
1689
+ if (suggestions.length === 0) {
1690
+ suggestions.push(
1691
+ "Enable development tools for more detailed debugging",
1692
+ "Check browser console for additional _error details",
1693
+ "Use component validation tools to identify issues"
1694
+ );
1695
+ }
1696
+ return [...new Set(suggestions)];
1697
+ }
1698
+ /**
1699
+ * Add _error to history with deduplication
1700
+ */
1701
+ addToHistory(_error) {
1702
+ const errorKey = `${_error.name}:${_error.message}`;
1703
+ this.errorCounts.set(errorKey, (this.errorCounts.get(errorKey) || 0) + 1);
1704
+ const historyEntry = {
1705
+ ..._error.toJSON(),
1706
+ count: this.errorCounts.get(errorKey),
1707
+ firstSeen: this.errorHistory.find((e) => e.key === errorKey)?.firstSeen || _error.timestamp,
1708
+ key: errorKey
1709
+ };
1710
+ this.errorHistory = this.errorHistory.filter((e) => e.key !== errorKey);
1711
+ this.errorHistory.unshift(historyEntry);
1712
+ if (this.errorHistory.length > this.options.maxErrorHistory) {
1713
+ this.errorHistory = this.errorHistory.slice(0, this.options.maxErrorHistory);
1714
+ }
1715
+ }
1716
+ /**
1717
+ * Log _error with enhanced formatting
1718
+ */
1719
+ logError(_error) {
1720
+ if (this.suppressedErrors.has(`${_error.name}:${_error.message}`)) {
1721
+ return;
1722
+ }
1723
+ const isRepeated = this.errorCounts.get(`${_error.name}:${_error.message}`) > 1;
1724
+ const errorGroup = `\u{1F6A8} ${_error.name}${isRepeated ? ` (\xD7${this.errorCounts.get(`${_error.name}:${_error.message}`)})` : ""}`;
1725
+ console.group(errorGroup);
1726
+ console.error(`\u274C ${_error.message}`);
1727
+ if (_error.code) {
1728
+ console.log("\u{1F3F7}\uFE0F Code:", _error.code);
1729
+ }
1730
+ if (_error.docsUrl) {
1731
+ console.log("\u{1F4D6} Docs:", _error.docsUrl);
1732
+ }
1733
+ if (_error.component) {
1734
+ console.log("\u{1F50D} Component:", this.formatComponent(_error.component));
1735
+ }
1736
+ if (_error.context) {
1737
+ console.log("\u{1F4CB} Context:", _error.context);
1738
+ }
1739
+ if (_error.context && typeof _error.context === "object" && _error.context.path) {
1740
+ console.log("\u{1F4CD} Path:", _error.context.path);
1741
+ }
1742
+ if (this.options.enableSuggestions && _error.suggestions.length > 0) {
1743
+ console.group("\u{1F4A1} Suggestions:");
1744
+ _error.suggestions.forEach((suggestion, index) => {
1745
+ console.log(`${index + 1}. ${suggestion}`);
1746
+ });
1747
+ console.groupEnd();
1748
+ }
1749
+ if (this.options.enableStackTrace && _error.stack) {
1750
+ console.log("\u{1F4DA} Stack trace:", _error.stack);
1751
+ }
1752
+ console.groupEnd();
1753
+ }
1754
+ /**
1755
+ * Format component for logging
1756
+ */
1757
+ formatComponent(component, maxDepth = 2, currentDepth = 0) {
1758
+ if (currentDepth > maxDepth) {
1759
+ return "[...deep]";
1760
+ }
1761
+ if (typeof component === "function") {
1762
+ return `[Function: ${component.name || "anonymous"}]`;
1763
+ }
1764
+ if (Array.isArray(component)) {
1765
+ return component.slice(0, 3).map(
1766
+ (item) => this.formatComponent(item, maxDepth, currentDepth + 1)
1767
+ );
1768
+ }
1769
+ if (component && typeof component === "object") {
1770
+ const formatted = {};
1771
+ const keys = Object.keys(component).slice(0, 5);
1772
+ for (const key of keys) {
1773
+ if (key === "children" && component[key]) {
1774
+ formatted[key] = this.formatComponent(component[key], maxDepth, currentDepth + 1);
1775
+ } else {
1776
+ formatted[key] = component[key];
1777
+ }
1778
+ }
1779
+ if (Object.keys(component).length > 5) {
1780
+ formatted["..."] = `(${Object.keys(component).length - 5} more)`;
1781
+ }
1782
+ return formatted;
1783
+ }
1784
+ return component;
1785
+ }
1786
+ /**
1787
+ * Suppress specific _error types
1788
+ */
1789
+ suppress(errorPattern) {
1790
+ this.suppressedErrors.add(errorPattern);
1791
+ }
1792
+ /**
1793
+ * Clear _error history
1794
+ */
1795
+ clearHistory() {
1796
+ this.errorHistory = [];
1797
+ this.errorCounts.clear();
1798
+ }
1799
+ /**
1800
+ * Get _error statistics
1801
+ */
1802
+ getStats() {
1803
+ const errorsByType = {};
1804
+ const errorsByTime = {};
1805
+ this.errorHistory.forEach((_error) => {
1806
+ errorsByType[_error.type] = (errorsByType[_error.type] || 0) + _error.count;
1807
+ const hour = new Date(_error.timestamp).toISOString().slice(0, 13);
1808
+ errorsByTime[hour] = (errorsByTime[hour] || 0) + _error.count;
1809
+ });
1810
+ return {
1811
+ totalErrors: this.errorHistory.reduce((sum, e) => sum + e.count, 0),
1812
+ uniqueErrors: this.errorHistory.length,
1813
+ errorsByType,
1814
+ errorsByTime,
1815
+ mostCommonErrors: this.getMostCommonErrors(5),
1816
+ recentErrors: this.errorHistory.slice(0, 10)
1817
+ };
1818
+ }
1819
+ /**
1820
+ * Get most common errors
1821
+ */
1822
+ getMostCommonErrors(limit = 10) {
1823
+ return this.errorHistory.sort((a, b) => b.count - a.count).slice(0, limit).map(({ name, message, count, type }) => ({
1824
+ name,
1825
+ message,
1826
+ count,
1827
+ type
1828
+ }));
1829
+ }
1830
+ };
1831
+ var globalErrorHandler = new ErrorHandler();
1832
+
1833
+ // src/rendering/html-renderer.js
1834
+ var rendererCache = createCacheManager({
1835
+ maxSize: 1e3,
1836
+ ttlMs: 3e5
1837
+ // 5 minutes
1838
+ });
1839
+ function formatRenderPath(path) {
1840
+ if (!path || path.length === 0) return "root";
1841
+ let rendered = "root";
1842
+ for (const segment of path) {
1843
+ if (typeof segment !== "string" || segment.length === 0) continue;
1844
+ if (segment.startsWith("[")) {
1845
+ rendered += segment;
1846
+ } else {
1847
+ rendered += `.${segment}`;
1848
+ }
1849
+ }
1850
+ return rendered;
1851
+ }
1852
+ var HTMLRenderer = class extends BaseRenderer {
1853
+ constructor(options = {}) {
1854
+ super({
1855
+ enableCache: options.enableCache !== false,
1856
+ enableMonitoring: options.enableMonitoring !== false,
1857
+ minify: options.minify || false,
1858
+ streaming: options.streaming || false,
1859
+ maxDepth: options.maxDepth || 100,
1860
+ ...options
1861
+ });
1862
+ if (this.config.enableCache && !this.cache) {
1863
+ this.cache = rendererCache;
1864
+ }
1865
+ }
1866
+ /**
1867
+ * Main render method - converts components to HTML string
1868
+ *
1869
+ * @param {Object|Array|string|Function} component - Component to render
1870
+ * @param {Object} [options={}] - Rendering options
1871
+ * @param {Object} [options.context] - Rendering context
1872
+ * @param {boolean} [options.enableCache] - Override cache setting
1873
+ * @param {number} [options.depth=0] - Current rendering depth
1874
+ * @returns {string} Rendered HTML string
1875
+ *
1876
+ * @example
1877
+ * const html = renderer.render({
1878
+ * div: {
1879
+ * className: 'container',
1880
+ * children: [
1881
+ * { h1: { text: 'Title' } },
1882
+ * { p: { text: 'Content' } }
1883
+ * ]
1884
+ * }
1885
+ * });
1886
+ */
1887
+ render(component, options = {}) {
1888
+ const config = { ...this.config, ...options };
1889
+ this.startTiming();
1890
+ try {
1891
+ if (config.validateInput && !this.isValidComponent(component)) {
1892
+ throw new Error("Invalid component structure");
1893
+ }
1894
+ const renderOptions = {
1895
+ ...config,
1896
+ seenObjects: /* @__PURE__ */ new WeakSet()
1897
+ };
1898
+ const html = this.renderComponent(component, renderOptions, 0, []);
1899
+ const finalHtml = config.minify ? minifyHtml(html, config) : html;
1900
+ this.endTiming();
1901
+ this.recordPerformance("render", this.metrics.startTime, false, {
1902
+ cacheEnabled: config.enableCache
1903
+ });
1904
+ return finalHtml;
1905
+ } catch (_error) {
1906
+ this.recordError("render", _error);
1907
+ const enhancedError = globalErrorHandler.handle(_error, {
1908
+ renderContext: { path: "root", renderer: "html" }
1909
+ });
1910
+ if (config.throwOnError === false) {
1911
+ return config.errorFallback;
1912
+ }
1913
+ throw enhancedError;
1914
+ }
1915
+ }
1916
+ /**
1917
+ * Render a single component with full optimization pipeline
1918
+ */
1919
+ renderComponent(component, options, depth = 0, path = []) {
1920
+ if (component === null || component === void 0) {
1921
+ return "";
1922
+ }
1923
+ if (Array.isArray(component) && component.length === 0) {
1924
+ return "";
1925
+ }
1926
+ if (typeof component === "object" && component !== null && !Array.isArray(component)) {
1927
+ if (options.seenObjects && options.seenObjects.has(component)) {
1928
+ throw new RenderingError(
1929
+ "Circular reference detected in component tree",
1930
+ component,
1931
+ { path: formatRenderPath(path) },
1932
+ ["Remove the circular reference", "Use lazy loading to break the cycle"]
1933
+ );
1934
+ }
1935
+ if (options.seenObjects) {
1936
+ options.seenObjects.add(component);
1937
+ }
1938
+ }
1939
+ this.validateDepth(depth);
1940
+ try {
1941
+ const { type, value } = this.processComponentType(component);
1942
+ switch (type) {
1943
+ case "empty":
1944
+ return "";
1945
+ case "text":
1946
+ return escapeHtml(value);
1947
+ case "function": {
1948
+ const result = this.executeFunctionComponent(value, depth);
1949
+ return this.renderComponent(result, options, depth + 1, [...path, "()"]);
1950
+ }
1951
+ case "array":
1952
+ if (typeof process !== "undefined" && process.env && true && value.length > 1) {
1953
+ const missingKeyCount = value.filter((child) => {
1954
+ if (child && typeof child === "object" && !Array.isArray(child)) {
1955
+ const tagName = Object.keys(child)[0];
1956
+ const props = child[tagName];
1957
+ return props && typeof props === "object" && props.key === void 0;
1958
+ }
1959
+ return false;
1960
+ }).length;
1961
+ if (missingKeyCount > 0) {
1962
+ console.warn(
1963
+ `[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', ... } }`
1964
+ );
1965
+ }
1966
+ }
1967
+ return value.map((child, index) => this.renderComponent(child, options, depth + 1, [...path, `[${index}]`])).join("");
1968
+ case "element": {
1969
+ const tagName = Object.keys(value)[0];
1970
+ const elementContent = value[tagName];
1971
+ return this.renderElement(tagName, elementContent, options, depth, [...path, tagName]);
1972
+ }
1973
+ default:
1974
+ this.recordError("renderComponent", new Error(`Unknown component type: ${type}`));
1975
+ return "";
1976
+ }
1977
+ } catch (_error) {
1978
+ const renderPath = formatRenderPath(path);
1979
+ if (_error instanceof CoherentError) {
1980
+ if (!_error.context || typeof _error.context !== "object") {
1981
+ _error.context = { path: renderPath };
1982
+ } else if (!_error.context.path) {
1983
+ _error.context = { ..._error.context, path: renderPath };
1984
+ }
1985
+ throw _error;
1986
+ }
1987
+ throw new RenderingError(_error.message, void 0, { path: renderPath, renderer: "html" });
1988
+ }
1989
+ }
1990
+ /**
1991
+ * Render an HTML element with advanced caching and optimization
1992
+ */
1993
+ renderElement(tagName, element, options, depth = 0, path = []) {
1994
+ const startTime = performance.now();
1995
+ if (element && typeof element === "object" && !Array.isArray(element)) {
1996
+ if (options.seenObjects && options.seenObjects.has(element)) {
1997
+ throw new RenderingError(
1998
+ "Circular reference detected in component tree",
1999
+ element,
2000
+ { path: formatRenderPath(path) },
2001
+ ["Remove the circular reference", "Use lazy loading to break the cycle"]
2002
+ );
2003
+ }
2004
+ if (options.seenObjects) {
2005
+ options.seenObjects.add(element);
2006
+ }
2007
+ }
2008
+ if (options.enableMonitoring && this.cache) {
2009
+ }
2010
+ if (options.enableCache && this.cache && RendererUtils.isStaticElement(element)) {
2011
+ try {
2012
+ const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;
2013
+ const cached = this.cache.get("static", cacheKey);
2014
+ if (cached) {
2015
+ this.recordPerformance(tagName, startTime, true);
2016
+ return cached.value;
2017
+ }
2018
+ } catch {
2019
+ }
2020
+ }
2021
+ if (typeof element === "string" || typeof element === "number" || typeof element === "boolean") {
2022
+ const html2 = isVoidElement(tagName) ? `<${tagName}>` : `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;
2023
+ this.cacheIfStatic(tagName, element, html2, options);
2024
+ this.recordPerformance(tagName, startTime, false);
2025
+ return html2;
2026
+ }
2027
+ if (typeof element === "function") {
2028
+ const result = this.executeFunctionComponent(element, depth);
2029
+ return this.renderElement(tagName, result, options, depth, [...path, "()"]);
2030
+ }
2031
+ if (element && typeof element === "object") {
2032
+ return this.renderObjectElement(tagName, element, options, depth, path);
2033
+ }
2034
+ if (element === null || element === void 0) {
2035
+ const html2 = isVoidElement(tagName) ? `<${tagName}>` : `<${tagName}></${tagName}>`;
2036
+ this.recordPerformance(tagName, startTime, false);
2037
+ return html2;
2038
+ }
2039
+ const html = `<${tagName}>${escapeHtml(String(element))}</${tagName}>`;
2040
+ this.recordPerformance(tagName, startTime, false);
2041
+ return html;
2042
+ }
2043
+ /**
2044
+ * Cache element if it's static
2045
+ */
2046
+ cacheIfStatic(tagName, element, html) {
2047
+ if (this.config.enableCache && this.cache && RendererUtils.isStaticElement(element)) {
2048
+ try {
2049
+ const cacheKey = `static:${tagName}:${JSON.stringify(element)}`;
2050
+ this.cache.set("static", cacheKey, html, {
2051
+ ttlMs: this.config.cacheTTL || 5 * 60 * 1e3,
2052
+ // 5 minutes default
2053
+ size: html.length
2054
+ // Approximate size
2055
+ });
2056
+ } catch {
2057
+ }
2058
+ }
2059
+ }
2060
+ /**
2061
+ * Render complex object elements with attributes and children
2062
+ */
2063
+ renderObjectElement(tagName, element, options, depth = 0, path = []) {
2064
+ const startTime = performance.now();
2065
+ if (options.enableCache && this.cache) {
2066
+ const cacheKey = RendererUtils.generateCacheKey(tagName, element);
2067
+ if (cacheKey) {
2068
+ const cached = this.cache.get(cacheKey);
2069
+ if (cached) {
2070
+ this.recordPerformance(tagName, startTime, true);
2071
+ return cached;
2072
+ }
2073
+ }
2074
+ }
2075
+ const { children, text, key: _key, html: _rawHtml, ...attributes } = element || {};
2076
+ const attributeString = formatAttributes(attributes);
2077
+ const openingTag = attributeString ? `<${tagName} ${attributeString}>` : `<${tagName}>`;
2078
+ let textContent = "";
2079
+ if (text !== void 0) {
2080
+ const isScript = tagName === "script";
2081
+ const isStyle = tagName === "style";
2082
+ const isRawTag = isScript || isStyle;
2083
+ const raw = typeof text === "function" ? String(text()) : String(text);
2084
+ if (isRawTag) {
2085
+ const safe = raw.replace(/<\/(script)/gi, "<\\/$1").replace(/<\/(style)/gi, "<\\/$1").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
2086
+ textContent = safe;
2087
+ } else {
2088
+ textContent = escapeHtml(raw);
2089
+ }
2090
+ }
2091
+ let childrenHtml = "";
2092
+ if (hasChildren(element)) {
2093
+ const normalizedChildren = normalizeChildren(children);
2094
+ childrenHtml = normalizedChildren.map((child, index) => {
2095
+ if (child && typeof child === "object" && !Array.isArray(child)) {
2096
+ const childTagName = Object.keys(child)[0];
2097
+ if (childTagName) {
2098
+ validateNesting(tagName, childTagName, formatRenderPath([...path, `children[${index}]`]));
2099
+ }
2100
+ }
2101
+ return this.renderComponent(child, options, depth + 1, [...path, `children[${index}]`]);
2102
+ }).join("");
2103
+ }
2104
+ const html = `${openingTag}${textContent}${childrenHtml}</${tagName}>`;
2105
+ if (options.enableCache && this.cache && RendererUtils.isCacheable(element, options)) {
2106
+ const cacheKey = RendererUtils.generateCacheKey(tagName, element);
2107
+ if (cacheKey) {
2108
+ this.cache.set(cacheKey, html);
2109
+ }
2110
+ }
2111
+ this.recordPerformance(tagName, startTime, false);
2112
+ return html;
2113
+ }
2114
+ };
2115
+ function render(component, options = {}) {
2116
+ const mergedOptions = {
2117
+ enableCache: true,
2118
+ enableMonitoring: false,
2119
+ ...options
2120
+ };
2121
+ const renderer = new HTMLRenderer(mergedOptions);
2122
+ return renderer.render(component, mergedOptions);
2123
+ }
2124
+
2125
+ // src/components/component-system.js
2126
+ var COMPONENT_REGISTRY = /* @__PURE__ */ new Map();
2127
+ var COMPONENT_METADATA = /* @__PURE__ */ new WeakMap();
2128
+ var ComponentState = class {
2129
+ constructor(initialState = {}) {
2130
+ this.state = { ...initialState };
2131
+ this.listeners = /* @__PURE__ */ new Set();
2132
+ this.isUpdating = false;
2133
+ }
2134
+ /**
2135
+ * Get state value by key or entire state
2136
+ *
2137
+ * @param {string} [key] - State key to retrieve
2138
+ * @returns {*} State value or entire state object
2139
+ */
2140
+ get(key) {
2141
+ return key ? this.state[key] : { ...this.state };
2142
+ }
2143
+ /**
2144
+ * Update state with new values
2145
+ *
2146
+ * @param {Object} updates - State updates to apply
2147
+ * @returns {ComponentState} This instance for chaining
2148
+ */
2149
+ set(updates) {
2150
+ if (this.isUpdating) return this;
2151
+ const oldState = { ...this.state };
2152
+ if (typeof updates === "function") {
2153
+ updates = updates(oldState);
2154
+ }
2155
+ this.state = { ...this.state, ...updates };
2156
+ this.notifyListeners(oldState, this.state);
2157
+ return this;
2158
+ }
2159
+ subscribe(listener) {
2160
+ this.listeners.add(listener);
2161
+ return () => this.listeners.delete(listener);
2162
+ }
2163
+ notifyListeners(oldState, newState) {
2164
+ if (this.listeners.size === 0) return;
2165
+ this.isUpdating = true;
2166
+ this.listeners.forEach((listener) => {
2167
+ try {
2168
+ listener(newState, oldState);
2169
+ } catch (_error) {
2170
+ console.error("State listener _error:", _error);
2171
+ }
2172
+ });
2173
+ this.isUpdating = false;
2174
+ }
2175
+ };
2176
+ var Component = class _Component {
2177
+ constructor(definition = {}) {
2178
+ this.definition = definition;
2179
+ this.name = definition.name || "AnonymousComponent";
2180
+ this.props = {};
2181
+ this.state = new ComponentState(definition.state || {});
2182
+ this.children = [];
2183
+ this.parent = null;
2184
+ this.rendered = null;
2185
+ this.isMounted = false;
2186
+ this.isDestroyed = false;
2187
+ this.hooks = {
2188
+ beforeCreate: definition.beforeCreate || (() => {
2189
+ }),
2190
+ created: definition.created || (() => {
2191
+ }),
2192
+ beforeMount: definition.beforeMount || (() => {
2193
+ }),
2194
+ mounted: definition.mounted || (() => {
2195
+ }),
2196
+ beforeUpdate: definition.beforeUpdate || (() => {
2197
+ }),
2198
+ updated: definition.updated || (() => {
2199
+ }),
2200
+ beforeDestroy: definition.beforeDestroy || (() => {
2201
+ }),
2202
+ destroyed: definition.destroyed || (() => {
2203
+ }),
2204
+ errorCaptured: definition.errorCaptured || (() => {
2205
+ })
2206
+ };
2207
+ this.methods = definition.methods || {};
2208
+ Object.keys(this.methods).forEach((methodName) => {
2209
+ if (typeof this.methods[methodName] === "function") {
2210
+ this[methodName] = this.methods[methodName].bind(this);
2211
+ }
2212
+ });
2213
+ this.computed = definition.computed || {};
2214
+ this.computedCache = /* @__PURE__ */ new Map();
2215
+ this.watchers = definition.watch || {};
2216
+ this.setupWatchers();
2217
+ COMPONENT_METADATA.set(this, {
2218
+ createdAt: Date.now(),
2219
+ updateCount: 0,
2220
+ renderCount: 0
2221
+ });
2222
+ this.callHook("beforeCreate");
2223
+ this.initialize();
2224
+ this.callHook("created");
2225
+ }
2226
+ /**
2227
+ * Initialize component
2228
+ */
2229
+ initialize() {
2230
+ this.unsubscribeState = this.state.subscribe((newState, oldState) => {
2231
+ this.onStateChange(newState, oldState);
2232
+ });
2233
+ this.initializeComputed();
2234
+ }
2235
+ /**
2236
+ * Set up watchers for reactive data
2237
+ */
2238
+ setupWatchers() {
2239
+ Object.keys(this.watchers).forEach((key) => {
2240
+ const handler = this.watchers[key];
2241
+ this.state.subscribe((newState, oldState) => {
2242
+ if (newState[key] !== oldState[key]) {
2243
+ handler.call(this, newState[key], oldState[key]);
2244
+ }
2245
+ });
2246
+ });
2247
+ }
2248
+ /**
2249
+ * Initialize computed properties
2250
+ */
2251
+ initializeComputed() {
2252
+ Object.keys(this.computed).forEach((key) => {
2253
+ Object.defineProperty(this, key, {
2254
+ get: () => {
2255
+ if (!this.computedCache.has(key)) {
2256
+ const value = this.computed[key].call(this);
2257
+ this.computedCache.set(key, value);
2258
+ }
2259
+ return this.computedCache.get(key);
2260
+ },
2261
+ enumerable: true
2262
+ });
2263
+ });
2264
+ }
2265
+ /**
2266
+ * Handle state changes
2267
+ */
2268
+ onStateChange() {
2269
+ if (this.isDestroyed) return;
2270
+ this.computedCache.clear();
2271
+ if (this.isMounted) {
2272
+ this.update();
2273
+ }
2274
+ }
2275
+ /**
2276
+ * Call lifecycle hook
2277
+ */
2278
+ callHook(hookName, ...args) {
2279
+ try {
2280
+ if (this.hooks[hookName]) {
2281
+ return this.hooks[hookName].call(this, ...args);
2282
+ }
2283
+ } catch (_error) {
2284
+ this.handleError(_error, `${hookName} hook`);
2285
+ }
2286
+ }
2287
+ /**
2288
+ * Handle component errors
2289
+ */
2290
+ handleError(_error) {
2291
+ console.error(`Component Error in ${this.name}:`, _error);
2292
+ this.callHook("errorCaptured", _error);
2293
+ if (this.parent && this.parent.handleError) {
2294
+ this.parent.handleError(_error, `${this.name} -> ${context}`);
2295
+ }
2296
+ }
2297
+ /**
2298
+ * Render the component
2299
+ */
2300
+ render(props = {}) {
2301
+ if (this.isDestroyed) {
2302
+ console.warn(`Attempting to render destroyed component: ${this.name}`);
2303
+ return null;
2304
+ }
2305
+ try {
2306
+ const metadata = COMPONENT_METADATA.get(this);
2307
+ if (metadata) {
2308
+ metadata.renderCount++;
2309
+ }
2310
+ this.props = { ...props };
2311
+ if (typeof this.definition.render === "function") {
2312
+ this.rendered = this.definition.render.call(this, this.props, this.state.get());
2313
+ } else if (typeof this.definition.template !== "undefined") {
2314
+ this.rendered = this.processTemplate(this.definition.template, this.props, this.state.get());
2315
+ } else {
2316
+ throw new Error(`Component ${this.name} must have either render method or template`);
2317
+ }
2318
+ if (this.rendered !== null) {
2319
+ validateComponent(this.rendered, this.name);
2320
+ }
2321
+ return this.rendered;
2322
+ } catch (_error) {
2323
+ this.handleError(_error);
2324
+ return { div: { className: "component-_error", text: `Error in ${this.name}` } };
2325
+ }
2326
+ }
2327
+ /**
2328
+ * Process template with data
2329
+ */
2330
+ processTemplate(template, props, state) {
2331
+ if (typeof template === "function") {
2332
+ return template.call(this, props, state);
2333
+ }
2334
+ if (typeof template === "string") {
2335
+ return template.replace(/\{\{(\w+)\}\}/g, (match, key) => {
2336
+ return props[key] || state[key] || "";
2337
+ });
2338
+ }
2339
+ const processed = deepClone(template);
2340
+ this.interpolateObject(processed, { ...props, ...state });
2341
+ return processed;
2342
+ }
2343
+ /**
2344
+ * Interpolate object with data
2345
+ */
2346
+ interpolateObject(obj, data) {
2347
+ if (typeof obj === "string") {
2348
+ return obj.replace(/\{\{(\w+)\}\}/g, (match, key) => data[key] || "");
2349
+ }
2350
+ if (Array.isArray(obj)) {
2351
+ return obj.map((item) => this.interpolateObject(item, data));
2352
+ }
2353
+ if (obj && typeof obj === "object") {
2354
+ Object.keys(obj).forEach((key) => {
2355
+ obj[key] = this.interpolateObject(obj[key], data);
2356
+ });
2357
+ }
2358
+ return obj;
2359
+ }
2360
+ /**
2361
+ * Mount the component
2362
+ */
2363
+ mount() {
2364
+ if (this.isMounted || this.isDestroyed) return this;
2365
+ this.callHook("beforeMount");
2366
+ this.isMounted = true;
2367
+ this.callHook("mounted");
2368
+ return this;
2369
+ }
2370
+ /**
2371
+ * Update the component
2372
+ */
2373
+ update() {
2374
+ if (!this.isMounted || this.isDestroyed) return this;
2375
+ const metadata = COMPONENT_METADATA.get(this);
2376
+ if (metadata) {
2377
+ metadata.updateCount++;
2378
+ }
2379
+ this.callHook("beforeUpdate");
2380
+ this.callHook("updated");
2381
+ return this;
2382
+ }
2383
+ /**
2384
+ * Destroy the component
2385
+ */
2386
+ destroy() {
2387
+ if (this.isDestroyed) return this;
2388
+ this.callHook("beforeDestroy");
2389
+ if (this.unsubscribeState) {
2390
+ this.unsubscribeState();
2391
+ }
2392
+ this.children.forEach((child) => {
2393
+ if (child.destroy) {
2394
+ child.destroy();
2395
+ }
2396
+ });
2397
+ this.isMounted = false;
2398
+ this.isDestroyed = true;
2399
+ this.children = [];
2400
+ this.parent = null;
2401
+ this.callHook("destroyed");
2402
+ return this;
2403
+ }
2404
+ /**
2405
+ * Get component metadata
2406
+ */
2407
+ getMetadata() {
2408
+ return COMPONENT_METADATA.get(this) || {};
2409
+ }
2410
+ /**
2411
+ * Clone component with new props/state
2412
+ */
2413
+ clone(overrides = {}) {
2414
+ const newDefinition = { ...this.definition, ...overrides };
2415
+ return new _Component(newDefinition);
2416
+ }
2417
+ };
2418
+ function createComponent(definition) {
2419
+ if (typeof definition === "function") {
2420
+ definition = {
2421
+ name: definition.name || "FunctionalComponent",
2422
+ render: definition
2423
+ };
2424
+ }
2425
+ return new Component(definition);
2426
+ }
2427
+ function defineComponent(definition) {
2428
+ const componentFactory = (props) => {
2429
+ const component = new Component(definition);
2430
+ return component.render(props);
2431
+ };
2432
+ componentFactory.componentName = definition.name || "Component";
2433
+ componentFactory.definition = definition;
2434
+ return componentFactory;
2435
+ }
2436
+ function registerComponent(name, definition) {
2437
+ if (COMPONENT_REGISTRY.has(name)) {
2438
+ console.warn(`Component ${name} is already registered. Overriding.`);
2439
+ }
2440
+ const component = typeof definition === "function" ? defineComponent({ name, render: definition }) : defineComponent(definition);
2441
+ COMPONENT_REGISTRY.set(name, component);
2442
+ return component;
2443
+ }
2444
+ function getComponent(name) {
2445
+ return COMPONENT_REGISTRY.get(name);
2446
+ }
2447
+ function getRegisteredComponents() {
2448
+ return new Map(COMPONENT_REGISTRY);
2449
+ }
2450
+ if (performanceMonitor) {
2451
+ const originalRender = Component.prototype.render;
2452
+ Component.prototype.render = function(...args) {
2453
+ const start = performance.now();
2454
+ const result = originalRender.apply(this, args);
2455
+ const duration = performance.now() - start;
2456
+ performanceMonitor.recordMetric("renderTime", duration, {
2457
+ type: "component",
2458
+ name: this.name,
2459
+ propsSize: JSON.stringify(this.props || {}).length,
2460
+ hasState: Object.keys(this.state?.get() || {}).length > 0
2461
+ });
2462
+ return result;
2463
+ };
2464
+ }
2465
+ function lazy(factory, options = {}) {
2466
+ const {
2467
+ cache = true,
2468
+ // Cache the result after first evaluation
2469
+ timeout = null,
2470
+ // Optional timeout for evaluation
2471
+ fallback = null,
2472
+ // Fallback value if evaluation fails
2473
+ onError = null,
2474
+ // Error handler
2475
+ dependencies = []
2476
+ // Dependencies that invalidate cache
2477
+ } = options;
2478
+ let cached = false;
2479
+ let cachedValue = null;
2480
+ let isEvaluating = false;
2481
+ let lastDependencyHash = null;
2482
+ const lazyWrapper = {
2483
+ // Mark as lazy for identification
2484
+ __isLazy: true,
2485
+ __factory: factory,
2486
+ __options: options,
2487
+ // Evaluation method
2488
+ evaluate(...args) {
2489
+ if (isEvaluating) {
2490
+ console.warn("Lazy evaluation cycle detected, returning fallback");
2491
+ return fallback;
2492
+ }
2493
+ if (cache && dependencies.length > 0) {
2494
+ const currentHash = hashDependencies(dependencies);
2495
+ if (lastDependencyHash !== null && lastDependencyHash !== currentHash) {
2496
+ cached = false;
2497
+ cachedValue = null;
2498
+ }
2499
+ lastDependencyHash = currentHash;
2500
+ }
2501
+ if (cache && cached) {
2502
+ return cachedValue;
2503
+ }
2504
+ isEvaluating = true;
2505
+ try {
2506
+ let result;
2507
+ if (timeout) {
2508
+ result = evaluateWithTimeout(factory, timeout, args, fallback);
2509
+ } else {
2510
+ result = typeof factory === "function" ? factory(...args) : factory;
2511
+ }
2512
+ if (result && typeof result.then === "function") {
2513
+ return result.catch((_error) => {
2514
+ if (onError) onError(_error);
2515
+ return fallback;
2516
+ });
2517
+ }
2518
+ if (cache) {
2519
+ cached = true;
2520
+ cachedValue = result;
2521
+ }
2522
+ return result;
2523
+ } catch (_error) {
2524
+ if (onError) {
2525
+ onError(_error);
2526
+ } else {
2527
+ console.error("Lazy evaluation _error:", _error);
2528
+ }
2529
+ return fallback;
2530
+ } finally {
2531
+ isEvaluating = false;
2532
+ }
2533
+ },
2534
+ // Force re-evaluation
2535
+ invalidate() {
2536
+ cached = false;
2537
+ cachedValue = null;
2538
+ lastDependencyHash = null;
2539
+ return this;
2540
+ },
2541
+ // Check if evaluated
2542
+ isEvaluated() {
2543
+ return cached;
2544
+ },
2545
+ // Get cached value without evaluation
2546
+ getCachedValue() {
2547
+ return cachedValue;
2548
+ },
2549
+ // Transform the lazy value
2550
+ map(transform) {
2551
+ return lazy((...args) => {
2552
+ const value = this.evaluate(...args);
2553
+ return transform(value);
2554
+ }, { ...options, cache: false });
2555
+ },
2556
+ // Chain lazy evaluations
2557
+ flatMap(transform) {
2558
+ return lazy((...args) => {
2559
+ const value = this.evaluate(...args);
2560
+ const transformed = transform(value);
2561
+ if (isLazy(transformed)) {
2562
+ return transformed.evaluate(...args);
2563
+ }
2564
+ return transformed;
2565
+ }, { ...options, cache: false });
2566
+ },
2567
+ // Convert to string for debugging
2568
+ toString() {
2569
+ return `[Lazy${cached ? " (cached)" : ""}]`;
2570
+ },
2571
+ // JSON serialization
2572
+ toJSON() {
2573
+ return this.evaluate();
2574
+ }
2575
+ };
2576
+ return lazyWrapper;
2577
+ }
2578
+ function isLazy(value) {
2579
+ return value && typeof value === "object" && value.__isLazy === true;
2580
+ }
2581
+ function evaluateLazy(obj, ...args) {
2582
+ if (isLazy(obj)) {
2583
+ return obj.evaluate(...args);
2584
+ }
2585
+ if (Array.isArray(obj)) {
2586
+ return obj.map((item) => evaluateLazy(item, ...args));
2587
+ }
2588
+ if (obj && typeof obj === "object") {
2589
+ const result = {};
2590
+ for (const [key, value] of Object.entries(obj)) {
2591
+ result[key] = evaluateLazy(value, ...args);
2592
+ }
2593
+ return result;
2594
+ }
2595
+ return obj;
2596
+ }
2597
+ function hashDependencies(dependencies) {
2598
+ return dependencies.map((dep) => {
2599
+ if (typeof dep === "function") {
2600
+ return dep.toString();
2601
+ }
2602
+ return JSON.stringify(dep);
2603
+ }).join("|");
2604
+ }
2605
+ function evaluateWithTimeout(factory, timeout, args, fallback) {
2606
+ return new Promise((resolve, reject) => {
2607
+ const timer = setTimeout(() => {
2608
+ reject(new Error(`Lazy evaluation timeout after ${timeout}ms`));
2609
+ }, timeout);
2610
+ try {
2611
+ const result = factory(...args);
2612
+ if (result && typeof result.then === "function") {
2613
+ result.then((value) => {
2614
+ clearTimeout(timer);
2615
+ resolve(value);
2616
+ }).catch((_error) => {
2617
+ clearTimeout(timer);
2618
+ reject(_error);
2619
+ });
2620
+ } else {
2621
+ clearTimeout(timer);
2622
+ resolve(result);
2623
+ }
2624
+ } catch (_error) {
2625
+ clearTimeout(timer);
2626
+ reject(_error);
2627
+ }
2628
+ }).catch(() => fallback);
2629
+ }
2630
+ function memo(fn, options = {}) {
2631
+ const {
2632
+ // Caching strategy
2633
+ strategy = "lru",
2634
+ // 'lru', 'ttl', 'weak', 'simple'
2635
+ maxSize = 100,
2636
+ // Maximum cache entries
2637
+ ttl = null,
2638
+ // Time to live in milliseconds
2639
+ // Key generation
2640
+ keyFn = null,
2641
+ // Custom key function
2642
+ keySerializer = JSON.stringify,
2643
+ // Default serialization
2644
+ // Comparison
2645
+ // eslint-disable-next-line no-unused-vars
2646
+ compareFn = null,
2647
+ // Custom equality comparison
2648
+ // eslint-disable-next-line no-unused-vars
2649
+ shallow = false,
2650
+ // Shallow comparison for objects
2651
+ // Lifecycle hooks
2652
+ onHit = null,
2653
+ // Called on cache hit
2654
+ onMiss = null,
2655
+ // Called on cache miss
2656
+ onEvict = null,
2657
+ // Called when item evicted
2658
+ // Performance
2659
+ stats = false,
2660
+ // Track hit/miss statistics
2661
+ // Development
2662
+ debug = false
2663
+ // Debug logging
2664
+ } = options;
2665
+ let cache;
2666
+ const stats_data = stats ? { hits: 0, misses: 0, evictions: 0 } : null;
2667
+ switch (strategy) {
2668
+ case "lru":
2669
+ cache = new LRUCache(maxSize, { onEvict });
2670
+ break;
2671
+ case "ttl":
2672
+ cache = new TTLCache(ttl, { onEvict });
2673
+ break;
2674
+ case "weak":
2675
+ cache = /* @__PURE__ */ new WeakMap();
2676
+ break;
2677
+ default:
2678
+ cache = /* @__PURE__ */ new Map();
2679
+ }
2680
+ const generateKey = keyFn || ((...args) => {
2681
+ if (args.length === 0) return "__empty__";
2682
+ if (args.length === 1) return keySerializer(args[0]);
2683
+ return keySerializer(args);
2684
+ });
2685
+ const memoizedFn = (...args) => {
2686
+ const key = generateKey(...args);
2687
+ if (cache.has(key)) {
2688
+ const cached = cache.get(key);
2689
+ if (cached && (!cached.expires || Date.now() < cached.expires)) {
2690
+ if (debug) console.log(`Memo cache hit for key: ${key}`);
2691
+ if (onHit) onHit(key, cached.value, args);
2692
+ if (stats_data) stats_data.hits++;
2693
+ return cached.value || cached;
2694
+ } else {
2695
+ cache.delete(key);
2696
+ }
2697
+ }
2698
+ if (debug) console.log(`Memo cache miss for key: ${key}`);
2699
+ if (onMiss) onMiss(key, args);
2700
+ if (stats_data) stats_data.misses++;
2701
+ const result = fn(...args);
2702
+ const cacheEntry = ttl ? { value: result, expires: Date.now() + ttl } : result;
2703
+ cache.set(key, cacheEntry);
2704
+ return result;
2705
+ };
2706
+ memoizedFn.cache = cache;
2707
+ memoizedFn.clear = () => cache.clear();
2708
+ memoizedFn.delete = (key) => cache.delete(key);
2709
+ memoizedFn.has = (key) => cache.has(key);
2710
+ memoizedFn.size = () => cache.size;
2711
+ if (stats_data) {
2712
+ memoizedFn.stats = () => ({ ...stats_data });
2713
+ memoizedFn.resetStats = () => {
2714
+ stats_data.hits = 0;
2715
+ stats_data.misses = 0;
2716
+ stats_data.evictions = 0;
2717
+ };
2718
+ }
2719
+ memoizedFn.refresh = (...args) => {
2720
+ const key = generateKey(...args);
2721
+ cache.delete(key);
2722
+ return memoizedFn(...args);
2723
+ };
2724
+ return memoizedFn;
2725
+ }
2726
+ var LRUCache = class {
2727
+ constructor(maxSize = 100, options = {}) {
2728
+ this.maxSize = maxSize;
2729
+ this.cache = /* @__PURE__ */ new Map();
2730
+ this.onEvict = options.onEvict;
2731
+ }
2732
+ get(key) {
2733
+ if (this.cache.has(key)) {
2734
+ const value = this.cache.get(key);
2735
+ this.cache.delete(key);
2736
+ this.cache.set(key, value);
2737
+ return value;
2738
+ }
2739
+ return void 0;
2740
+ }
2741
+ set(key, value) {
2742
+ if (this.cache.has(key)) {
2743
+ this.cache.delete(key);
2744
+ } else if (this.cache.size >= this.maxSize) {
2745
+ const firstKey = this.cache.keys().next().value;
2746
+ const evicted = this.cache.get(firstKey);
2747
+ this.cache.delete(firstKey);
2748
+ if (this.onEvict) {
2749
+ this.onEvict(firstKey, evicted);
2750
+ }
2751
+ }
2752
+ this.cache.set(key, value);
2753
+ }
2754
+ has(key) {
2755
+ return this.cache.has(key);
2756
+ }
2757
+ delete(key) {
2758
+ return this.cache.delete(key);
2759
+ }
2760
+ clear() {
2761
+ this.cache.clear();
2762
+ }
2763
+ get size() {
2764
+ return this.cache.size;
2765
+ }
2766
+ };
2767
+ var TTLCache = class {
2768
+ constructor(ttl, options = {}) {
2769
+ this.ttl = ttl;
2770
+ this.cache = /* @__PURE__ */ new Map();
2771
+ this.timers = /* @__PURE__ */ new Map();
2772
+ this.onEvict = options.onEvict;
2773
+ }
2774
+ get(key) {
2775
+ if (this.cache.has(key)) {
2776
+ const entry = this.cache.get(key);
2777
+ if (Date.now() < entry.expires) {
2778
+ return entry.value;
2779
+ } else {
2780
+ this.delete(key);
2781
+ }
2782
+ }
2783
+ return void 0;
2784
+ }
2785
+ set(key, value) {
2786
+ if (this.timers.has(key)) {
2787
+ clearTimeout(this.timers.get(key));
2788
+ }
2789
+ const expires = Date.now() + this.ttl;
2790
+ this.cache.set(key, { value, expires });
2791
+ const timer = setTimeout(() => {
2792
+ this.delete(key);
2793
+ }, this.ttl);
2794
+ this.timers.set(key, timer);
2795
+ }
2796
+ has(key) {
2797
+ if (this.cache.has(key)) {
2798
+ const entry = this.cache.get(key);
2799
+ return Date.now() < entry.expires;
2800
+ }
2801
+ return false;
2802
+ }
2803
+ delete(key) {
2804
+ const had = this.cache.has(key);
2805
+ if (had) {
2806
+ const entry = this.cache.get(key);
2807
+ this.cache.delete(key);
2808
+ if (this.timers.has(key)) {
2809
+ clearTimeout(this.timers.get(key));
2810
+ this.timers.delete(key);
2811
+ }
2812
+ if (this.onEvict) {
2813
+ this.onEvict(key, entry.value);
2814
+ }
2815
+ }
2816
+ return had;
2817
+ }
2818
+ clear() {
2819
+ this.timers.forEach((timer) => clearTimeout(timer));
2820
+ this.timers.clear();
2821
+ this.cache.clear();
2822
+ }
2823
+ get size() {
2824
+ return this.cache.size;
2825
+ }
2826
+ };
2827
+ function withState(initialState = {}, options = {}) {
2828
+ const {
2829
+ // State options
2830
+ persistent = false,
2831
+ // Persist state across component unmounts
2832
+ storageKey = null,
2833
+ // Key for persistent storage
2834
+ storage = typeof window !== "undefined" && typeof window.localStorage !== "undefined" ? window.localStorage : {
2835
+ // Fallback storage for Node.js environments
2836
+ _data: /* @__PURE__ */ new Map(),
2837
+ setItem(key, value) {
2838
+ this._data.set(key, value);
2839
+ },
2840
+ getItem(key) {
2841
+ return this._data.get(key) || null;
2842
+ },
2843
+ removeItem(key) {
2844
+ this._data.delete(key);
2845
+ },
2846
+ clear() {
2847
+ this._data.clear();
2848
+ }
2849
+ },
2850
+ // Storage mechanism
2851
+ // State transformation
2852
+ stateTransform = null,
2853
+ // Transform state before injection
2854
+ propName = "state",
1326
2855
  // Prop name for state injection
1327
2856
  actionsName = "actions",
1328
2857
  // Prop name for action injection
@@ -1437,6 +2966,8 @@ function withState(initialState = {}, options = {}) {
1437
2966
  ...props,
1438
2967
  [propName]: transformedState,
1439
2968
  [actionsName]: boundActions,
2969
+ setState: stateUtils.setState,
2970
+ getState: stateUtils.getState,
1440
2971
  stateUtils
1441
2972
  };
1442
2973
  if (debug) {
@@ -1541,631 +3072,254 @@ function createStateContainer(initialState, options) {
1541
3072
  unsubscribe(listener) {
1542
3073
  return listeners.delete(listener);
1543
3074
  },
1544
- batch(batchFn) {
1545
- const originalListeners = listeners;
1546
- listeners = /* @__PURE__ */ new Set();
1547
- try {
1548
- batchFn();
1549
- } finally {
1550
- listeners = originalListeners;
1551
- listeners.forEach((listener) => listener(state));
1552
- }
1553
- },
1554
- destroy() {
1555
- listeners.clear();
1556
- if (persistent && storageKey) {
1557
- try {
1558
- storage.removeItem(storageKey);
1559
- } catch (_error) {
1560
- if (debug) console.warn("Failed to remove persisted state:", _error);
1561
- }
1562
- }
1563
- }
1564
- };
1565
- return container;
1566
- }
1567
- function createBoundActions(actions, stateContainer, options) {
1568
- const { props, context: context2, supportAsync, debug } = options;
1569
- const boundActions = {};
1570
- Object.entries(actions).forEach(([actionName, actionCreator]) => {
1571
- boundActions[actionName] = (...args) => {
1572
- try {
1573
- const result = actionCreator(
1574
- stateContainer.getState(),
1575
- stateContainer.setState.bind(stateContainer),
1576
- { props, context: context2, args }
1577
- );
1578
- if (supportAsync && result && typeof result.then === "function") {
1579
- return result.catch((_error) => {
1580
- if (debug) console.error(`Async action ${actionName} failed:`, _error);
1581
- throw _error;
1582
- });
1583
- }
1584
- return result;
1585
- } catch (_error) {
1586
- if (debug) console.error(`Action ${actionName} failed:`, _error);
1587
- throw _error;
1588
- }
1589
- };
1590
- });
1591
- return boundActions;
1592
- }
1593
- var withStateUtils = {
1594
- /**
1595
- * Simple local state
1596
- */
1597
- local: (initialState) => withState(initialState),
1598
- /**
1599
- * Persistent state with localStorage
1600
- */
1601
- persistent: (initialState, key) => withState(initialState, {
1602
- persistent: true,
1603
- storageKey: key
1604
- }),
1605
- /**
1606
- * State with reducer pattern
1607
- */
1608
- reducer: (initialState, reducer, actions = {}) => withState(initialState, {
1609
- reducer,
1610
- actions
1611
- }),
1612
- /**
1613
- * Async state management
1614
- */
1615
- async: (initialState, asyncActions = {}) => withState(initialState, {
1616
- supportAsync: true,
1617
- actions: asyncActions
1618
- }),
1619
- /**
1620
- * State with validation
1621
- */
1622
- validated: (initialState, validator) => withState(initialState, {
1623
- validator,
1624
- debug: true
1625
- }),
1626
- /**
1627
- * Shared state across components
1628
- */
1629
- shared: (initialState, sharedKey) => {
1630
- const sharedStates = withStateUtils._shared || (withStateUtils._shared = /* @__PURE__ */ new Map());
1631
- if (!sharedStates.has(sharedKey)) {
1632
- sharedStates.set(sharedKey, createStateContainer(initialState, {}));
1633
- }
1634
- return (WrappedComponent) => {
1635
- const sharedContainer = sharedStates.get(sharedKey);
1636
- function SharedStateComponent(props, globalState, context2) {
1637
- const currentState = sharedContainer.getState();
1638
- const enhancedProps = {
1639
- ...props,
1640
- state: currentState,
1641
- setState: sharedContainer.setState.bind(sharedContainer),
1642
- subscribe: sharedContainer.subscribe.bind(sharedContainer)
1643
- };
1644
- return typeof WrappedComponent === "function" ? WrappedComponent(enhancedProps, globalState, context2) : WrappedComponent;
1645
- }
1646
- SharedStateComponent.displayName = `withSharedState(${getComponentName(WrappedComponent)})`;
1647
- return SharedStateComponent;
1648
- };
1649
- },
1650
- /**
1651
- * State with form utilities
1652
- */
1653
- form: (initialFormState) => withState(initialFormState, {
1654
- actions: {
1655
- updateField: (state, setState, { args: [field, value] }) => {
1656
- setState({ [field]: value });
1657
- },
1658
- updateMultiple: (state, setState, { args: [updates] }) => {
1659
- setState(updates);
1660
- },
1661
- resetForm: (state, setState) => {
1662
- setState(initialFormState);
1663
- },
1664
- validateForm: (state, setState, { args: [validator] }) => {
1665
- const errors = validator(state);
1666
- setState({ _errors: errors });
1667
- return Object.keys(errors).length === 0;
3075
+ batch(batchFn) {
3076
+ const originalListeners = listeners;
3077
+ listeners = /* @__PURE__ */ new Set();
3078
+ try {
3079
+ batchFn();
3080
+ } finally {
3081
+ listeners = originalListeners;
3082
+ listeners.forEach((listener) => listener(state));
1668
3083
  }
1669
- }
1670
- }),
1671
- /**
1672
- * State with loading/_error handling
1673
- */
1674
- withLoading: async (initialState) => withState({
1675
- ...initialState,
1676
- _loading: false,
1677
- _error: null
1678
- }, {
1679
- supportAsync: true,
1680
- actions: {
1681
- setLoading: (state, setState, { args: [loading] }) => {
1682
- setState({ _loading: loading });
1683
- },
1684
- setError: (state, setState, { args: [_error] }) => {
1685
- setState({ _error, _loading: false });
1686
- },
1687
- clearError: (state, setState) => {
1688
- setState({ _error: null });
1689
- },
1690
- asyncAction: async (state, setState, { args: [asyncFn] }) => {
1691
- setState({ _loading: true, _error: null });
3084
+ },
3085
+ destroy() {
3086
+ listeners.clear();
3087
+ if (persistent && storageKey) {
1692
3088
  try {
1693
- const result = await asyncFn(state);
1694
- setState({ _loading: false });
1695
- return result;
3089
+ storage.removeItem(storageKey);
1696
3090
  } catch (_error) {
1697
- setState({ _loading: false, _error });
1698
- throw _error;
3091
+ if (debug) console.warn("Failed to remove persisted state:", _error);
1699
3092
  }
1700
3093
  }
1701
3094
  }
1702
- }),
1703
- /**
1704
- * State with undo/redo functionality
1705
- */
1706
- withHistory: (initialState, maxHistory = 10) => {
1707
- const historyState = {
1708
- present: initialState,
1709
- past: [],
1710
- future: []
1711
- };
1712
- return withState(historyState, {
1713
- actions: {
1714
- undo: (state, setState) => {
1715
- if (state.past.length === 0) return;
1716
- const previous = state.past[state.past.length - 1];
1717
- const newPast = state.past.slice(0, state.past.length - 1);
1718
- setState({
1719
- past: newPast,
1720
- present: previous,
1721
- future: [state.present, ...state.future]
1722
- });
1723
- },
1724
- redo: (state, setState) => {
1725
- if (state.future.length === 0) return;
1726
- const next = state.future[0];
1727
- const newFuture = state.future.slice(1);
1728
- setState({
1729
- past: [...state.past, state.present],
1730
- present: next,
1731
- future: newFuture
1732
- });
1733
- },
1734
- updatePresent: (state, setState, { args: [newPresent] }) => {
1735
- setState({
1736
- past: [...state.past, state.present].slice(-maxHistory),
1737
- present: newPresent,
1738
- future: []
1739
- });
1740
- },
1741
- canUndo: (state) => state.past.length > 0,
1742
- canRedo: (state) => state.future.length > 0
1743
- }
1744
- });
1745
- },
1746
- /**
1747
- * Computed state properties
1748
- */
1749
- computed: (initialState, computedProps) => withState(initialState, {
1750
- stateTransform: (state) => {
1751
- const computed = {};
1752
- Object.entries(computedProps).forEach(([key, computeFn]) => {
1753
- computed[key] = computeFn(state);
1754
- });
1755
- return { ...state, ...computed };
1756
- },
1757
- memoizeState: true
1758
- })
1759
- };
1760
- function createStateManager(config) {
1761
- const {
1762
- initialState = {},
1763
- reducers = {},
1764
- actions = {},
1765
- middleware = [],
1766
- plugins = []
1767
- } = config;
1768
- const rootReducer = (state, action) => {
1769
- let nextState = state;
1770
- Object.entries(reducers).forEach(([key, reducer]) => {
1771
- nextState = {
1772
- ...nextState,
1773
- [key]: reducer(nextState[key], action)
1774
- };
1775
- });
1776
- return nextState;
1777
3095
  };
1778
- const enhancedConfig = plugins.reduce(
1779
- (acc, plugin) => plugin(acc),
1780
- { initialState, reducer: rootReducer, actions, middleware }
1781
- );
1782
- return withState(enhancedConfig.initialState, {
1783
- reducer: enhancedConfig.reducer,
1784
- actions: enhancedConfig.actions,
1785
- middleware: enhancedConfig.middleware
1786
- });
1787
- }
1788
- function getComponentName(component) {
1789
- if (!component) return "Component";
1790
- return component.displayName || component.name || component.constructor?.name || "Component";
3096
+ return container;
1791
3097
  }
1792
-
1793
- // src/utils/error-handler.js
1794
- var CoherentError = class _CoherentError extends Error {
1795
- constructor(message, options = {}) {
1796
- super(message);
1797
- this.name = "CoherentError";
1798
- this.type = options.type || "generic";
1799
- this.component = options.component;
1800
- this.context = options.context;
1801
- this.suggestions = options.suggestions || [];
1802
- this.timestamp = Date.now();
1803
- if (Error.captureStackTrace) {
1804
- Error.captureStackTrace(this, _CoherentError);
1805
- }
1806
- }
1807
- toJSON() {
1808
- return {
1809
- name: this.name,
1810
- message: this.message,
1811
- type: this.type,
1812
- component: this.component,
1813
- context: this.context,
1814
- suggestions: this.suggestions,
1815
- timestamp: this.timestamp,
1816
- stack: this.stack
1817
- };
1818
- }
1819
- };
1820
- var ComponentValidationError = class extends CoherentError {
1821
- constructor(message, component, suggestions = []) {
1822
- super(message, {
1823
- type: "validation",
1824
- component,
1825
- suggestions: [
1826
- "Check component structure and syntax",
1827
- "Ensure all required properties are present",
1828
- "Validate prop types and values",
1829
- ...suggestions
1830
- ]
1831
- });
1832
- this.name = "ComponentValidationError";
1833
- }
1834
- };
1835
- var RenderingError = class extends CoherentError {
1836
- constructor(message, component, context2, suggestions = []) {
1837
- super(message, {
1838
- type: "rendering",
1839
- component,
1840
- context: context2,
1841
- suggestions: [
1842
- "Check for circular references",
1843
- "Validate component depth",
1844
- "Ensure all functions return valid components",
1845
- ...suggestions
1846
- ]
1847
- });
1848
- this.name = "RenderingError";
1849
- }
1850
- };
1851
- var PerformanceError = class extends CoherentError {
1852
- constructor(message, metrics, suggestions = []) {
1853
- super(message, {
1854
- type: "performance",
1855
- context: metrics,
1856
- suggestions: [
1857
- "Consider component memoization",
1858
- "Reduce component complexity",
1859
- "Enable caching",
1860
- ...suggestions
1861
- ]
1862
- });
1863
- this.name = "PerformanceError";
1864
- }
1865
- };
1866
- var StateError = class extends CoherentError {
1867
- constructor(message, state, suggestions = []) {
1868
- super(message, {
1869
- type: "state",
1870
- context: state,
1871
- suggestions: [
1872
- "Check state mutations",
1873
- "Ensure proper state initialization",
1874
- "Validate state transitions",
1875
- ...suggestions
1876
- ]
1877
- });
1878
- this.name = "StateError";
1879
- }
1880
- };
1881
- var ErrorHandler = class {
1882
- constructor(options = {}) {
1883
- this.options = {
1884
- enableStackTrace: options.enableStackTrace !== false,
1885
- enableSuggestions: options.enableSuggestions !== false,
1886
- enableLogging: options.enableLogging !== false,
1887
- logLevel: options.logLevel || "_error",
1888
- maxErrorHistory: options.maxErrorHistory || 100,
1889
- ...options
1890
- };
1891
- this.errorHistory = [];
1892
- this.errorCounts = /* @__PURE__ */ new Map();
1893
- this.suppressedErrors = /* @__PURE__ */ new Set();
1894
- }
1895
- /**
1896
- * Handle and report errors with detailed context
1897
- */
1898
- handle(_error, context2 = {}) {
1899
- const enhancedError = this.enhanceError(_error, context2);
1900
- this.addToHistory(enhancedError);
1901
- if (this.options.enableLogging) {
1902
- this.logError(enhancedError);
1903
- }
1904
- return enhancedError;
1905
- }
3098
+ function createBoundActions(actions, stateContainer, options) {
3099
+ const { props, context: context2, supportAsync, debug } = options;
3100
+ const boundActions = {};
3101
+ Object.entries(actions).forEach(([actionName, actionCreator]) => {
3102
+ boundActions[actionName] = (...args) => {
3103
+ try {
3104
+ const result = actionCreator(
3105
+ stateContainer.getState(),
3106
+ stateContainer.setState.bind(stateContainer),
3107
+ { props, context: context2, args }
3108
+ );
3109
+ if (supportAsync && result && typeof result.then === "function") {
3110
+ return result.catch((_error) => {
3111
+ if (debug) console.error(`Async action ${actionName} failed:`, _error);
3112
+ throw _error;
3113
+ });
3114
+ }
3115
+ return result;
3116
+ } catch (_error) {
3117
+ if (debug) console.error(`Action ${actionName} failed:`, _error);
3118
+ throw _error;
3119
+ }
3120
+ };
3121
+ });
3122
+ return boundActions;
3123
+ }
3124
+ var withStateUtils = {
1906
3125
  /**
1907
- * Enhance existing errors with more context
3126
+ * Simple local state
1908
3127
  */
1909
- enhanceError(_error, context2 = {}) {
1910
- if (_error instanceof CoherentError) {
1911
- return _error;
1912
- }
1913
- const errorType = this.classifyError(_error, context2);
1914
- switch (errorType) {
1915
- case "validation":
1916
- return new ComponentValidationError(
1917
- _error.message,
1918
- context2.component,
1919
- this.generateSuggestions(_error, context2)
1920
- );
1921
- case "rendering":
1922
- return new RenderingError(
1923
- _error.message,
1924
- context2.component,
1925
- context2.renderContext,
1926
- this.generateSuggestions(_error, context2)
1927
- );
1928
- case "performance":
1929
- return new PerformanceError(
1930
- _error.message,
1931
- context2.metrics,
1932
- this.generateSuggestions(_error, context2)
1933
- );
1934
- case "state":
1935
- return new StateError(
1936
- _error.message,
1937
- context2.state,
1938
- this.generateSuggestions(_error, context2)
1939
- );
1940
- default:
1941
- return new CoherentError(_error.message, {
1942
- type: errorType,
1943
- component: context2.component,
1944
- context: context2.context,
1945
- suggestions: this.generateSuggestions(_error, context2)
1946
- });
1947
- }
1948
- }
3128
+ local: (initialState) => withState(initialState),
1949
3129
  /**
1950
- * Classify _error type based on message and context
3130
+ * Persistent state with localStorage
1951
3131
  */
1952
- classifyError(_error, context2) {
1953
- const message = _error.message.toLowerCase();
1954
- if (message.includes("invalid") || message.includes("validation") || message.includes("required") || message.includes("type")) {
1955
- return "validation";
1956
- }
1957
- if (message.includes("render") || message.includes("circular") || message.includes("depth") || message.includes("cannot render")) {
1958
- return "rendering";
1959
- }
1960
- if (message.includes("slow") || message.includes("memory") || message.includes("performance") || message.includes("timeout")) {
1961
- return "performance";
1962
- }
1963
- if (message.includes("state") || message.includes("mutation") || message.includes("store") || context2.state) {
1964
- return "state";
1965
- }
1966
- if (context2.component) return "validation";
1967
- if (context2.renderContext) return "rendering";
1968
- if (context2.metrics) return "performance";
1969
- return "generic";
1970
- }
3132
+ persistent: (initialState, key) => withState(initialState, {
3133
+ persistent: true,
3134
+ storageKey: key
3135
+ }),
1971
3136
  /**
1972
- * Generate helpful suggestions based on _error
3137
+ * State with reducer pattern
1973
3138
  */
1974
- generateSuggestions(_error, context2 = {}) {
1975
- const suggestions = [];
1976
- const message = _error.message.toLowerCase();
1977
- const patterns = [
1978
- {
1979
- pattern: /cannot render|render.*failed/,
1980
- suggestions: [
1981
- "Check if component returns a valid object structure",
1982
- "Ensure all properties are properly defined",
1983
- "Look for undefined variables or null references"
1984
- ]
1985
- },
1986
- {
1987
- pattern: /circular.*reference/,
1988
- suggestions: [
1989
- "Remove circular references between components",
1990
- "Use lazy loading or memoization to break cycles",
1991
- "Check for self-referencing components"
1992
- ]
1993
- },
1994
- {
1995
- pattern: /maximum.*depth/,
1996
- suggestions: [
1997
- "Reduce component nesting depth",
1998
- "Break complex components into smaller parts",
1999
- "Check for infinite recursion in component functions"
2000
- ]
2001
- },
2002
- {
2003
- pattern: /invalid.*component/,
2004
- suggestions: [
2005
- "Ensure component follows the expected object structure",
2006
- "Check property names and values for typos",
2007
- "Verify component is not null or undefined"
2008
- ]
2009
- },
2010
- {
2011
- pattern: /performance|slow|timeout/,
2012
- suggestions: [
2013
- "Enable component caching",
2014
- "Use memoization for expensive operations",
2015
- "Reduce component complexity",
2016
- "Consider lazy loading for large components"
2017
- ]
2018
- }
2019
- ];
2020
- patterns.forEach(({ pattern, suggestions: patternSuggestions }) => {
2021
- if (pattern.test(message)) {
2022
- suggestions.push(...patternSuggestions);
2023
- }
2024
- });
2025
- if (context2.component) {
2026
- const componentType = typeof context2.component;
2027
- if (componentType === "function") {
2028
- suggestions.push("Check function component return value");
2029
- } else if (componentType === "object" && context2.component === null) {
2030
- suggestions.push("Component is null - ensure proper initialization");
2031
- } else if (Array.isArray(context2.component)) {
2032
- suggestions.push("Arrays should contain valid component objects");
2033
- }
2034
- }
2035
- if (suggestions.length === 0) {
2036
- suggestions.push(
2037
- "Enable development tools for more detailed debugging",
2038
- "Check browser console for additional _error details",
2039
- "Use component validation tools to identify issues"
2040
- );
2041
- }
2042
- return [...new Set(suggestions)];
2043
- }
3139
+ reducer: (initialState, reducer, actions = {}) => withState(initialState, {
3140
+ reducer,
3141
+ actions
3142
+ }),
2044
3143
  /**
2045
- * Add _error to history with deduplication
3144
+ * Async state management
2046
3145
  */
2047
- addToHistory(_error) {
2048
- const errorKey = `${_error.name}:${_error.message}`;
2049
- this.errorCounts.set(errorKey, (this.errorCounts.get(errorKey) || 0) + 1);
2050
- const historyEntry = {
2051
- ..._error.toJSON(),
2052
- count: this.errorCounts.get(errorKey),
2053
- firstSeen: this.errorHistory.find((e) => e.key === errorKey)?.firstSeen || _error.timestamp,
2054
- key: errorKey
2055
- };
2056
- this.errorHistory = this.errorHistory.filter((e) => e.key !== errorKey);
2057
- this.errorHistory.unshift(historyEntry);
2058
- if (this.errorHistory.length > this.options.maxErrorHistory) {
2059
- this.errorHistory = this.errorHistory.slice(0, this.options.maxErrorHistory);
2060
- }
2061
- }
3146
+ async: (initialState, asyncActions = {}) => withState(initialState, {
3147
+ supportAsync: true,
3148
+ actions: asyncActions
3149
+ }),
2062
3150
  /**
2063
- * Log _error with enhanced formatting
3151
+ * State with validation
2064
3152
  */
2065
- logError(_error) {
2066
- if (this.suppressedErrors.has(`${_error.name}:${_error.message}`)) {
2067
- return;
2068
- }
2069
- const isRepeated = this.errorCounts.get(`${_error.name}:${_error.message}`) > 1;
2070
- const errorGroup = `\u{1F6A8} ${_error.name}${isRepeated ? ` (\xD7${this.errorCounts.get(`${_error.name}:${_error.message}`)})` : ""}`;
2071
- console.group(errorGroup);
2072
- console.error(`\u274C ${_error.message}`);
2073
- if (_error.component) {
2074
- console.log("\u{1F50D} Component:", this.formatComponent(_error.component));
2075
- }
2076
- if (_error.context) {
2077
- console.log("\u{1F4CB} Context:", _error.context);
2078
- }
2079
- if (this.options.enableSuggestions && _error.suggestions.length > 0) {
2080
- console.group("\u{1F4A1} Suggestions:");
2081
- _error.suggestions.forEach((suggestion, index) => {
2082
- console.log(`${index + 1}. ${suggestion}`);
2083
- });
2084
- console.groupEnd();
2085
- }
2086
- if (this.options.enableStackTrace && _error.stack) {
2087
- console.log("\u{1F4DA} Stack trace:", _error.stack);
2088
- }
2089
- console.groupEnd();
2090
- }
3153
+ validated: (initialState, validator) => withState(initialState, {
3154
+ validator,
3155
+ debug: true
3156
+ }),
2091
3157
  /**
2092
- * Format component for logging
3158
+ * Shared state across components
2093
3159
  */
2094
- formatComponent(component, maxDepth = 2, currentDepth = 0) {
2095
- if (currentDepth > maxDepth) {
2096
- return "[...deep]";
2097
- }
2098
- if (typeof component === "function") {
2099
- return `[Function: ${component.name || "anonymous"}]`;
2100
- }
2101
- if (Array.isArray(component)) {
2102
- return component.slice(0, 3).map(
2103
- (item) => this.formatComponent(item, maxDepth, currentDepth + 1)
2104
- );
2105
- }
2106
- if (component && typeof component === "object") {
2107
- const formatted = {};
2108
- const keys = Object.keys(component).slice(0, 5);
2109
- for (const key of keys) {
2110
- if (key === "children" && component[key]) {
2111
- formatted[key] = this.formatComponent(component[key], maxDepth, currentDepth + 1);
2112
- } else {
2113
- formatted[key] = component[key];
2114
- }
2115
- }
2116
- if (Object.keys(component).length > 5) {
2117
- formatted["..."] = `(${Object.keys(component).length - 5} more)`;
2118
- }
2119
- return formatted;
3160
+ shared: (initialState, sharedKey) => {
3161
+ const sharedStates = withStateUtils._shared || (withStateUtils._shared = /* @__PURE__ */ new Map());
3162
+ if (!sharedStates.has(sharedKey)) {
3163
+ sharedStates.set(sharedKey, createStateContainer(initialState, {}));
2120
3164
  }
2121
- return component;
2122
- }
3165
+ return (WrappedComponent) => {
3166
+ const sharedContainer = sharedStates.get(sharedKey);
3167
+ function SharedStateComponent(props, globalState, context2) {
3168
+ const currentState = sharedContainer.getState();
3169
+ const enhancedProps = {
3170
+ ...props,
3171
+ state: currentState,
3172
+ setState: sharedContainer.setState.bind(sharedContainer),
3173
+ subscribe: sharedContainer.subscribe.bind(sharedContainer)
3174
+ };
3175
+ return typeof WrappedComponent === "function" ? WrappedComponent(enhancedProps, globalState, context2) : WrappedComponent;
3176
+ }
3177
+ SharedStateComponent.displayName = `withSharedState(${getComponentName(WrappedComponent)})`;
3178
+ return SharedStateComponent;
3179
+ };
3180
+ },
2123
3181
  /**
2124
- * Suppress specific _error types
3182
+ * State with form utilities
2125
3183
  */
2126
- suppress(errorPattern) {
2127
- this.suppressedErrors.add(errorPattern);
2128
- }
3184
+ form: (initialFormState) => withState(initialFormState, {
3185
+ actions: {
3186
+ updateField: (state, setState, { args: [field, value] }) => {
3187
+ setState({ [field]: value });
3188
+ },
3189
+ updateMultiple: (state, setState, { args: [updates] }) => {
3190
+ setState(updates);
3191
+ },
3192
+ resetForm: (state, setState) => {
3193
+ setState(initialFormState);
3194
+ },
3195
+ validateForm: (state, setState, { args: [validator] }) => {
3196
+ const errors = validator(state);
3197
+ setState({ _errors: errors });
3198
+ return Object.keys(errors).length === 0;
3199
+ }
3200
+ }
3201
+ }),
2129
3202
  /**
2130
- * Clear _error history
3203
+ * State with loading/_error handling
2131
3204
  */
2132
- clearHistory() {
2133
- this.errorHistory = [];
2134
- this.errorCounts.clear();
2135
- }
3205
+ withLoading: async (initialState) => withState({
3206
+ ...initialState,
3207
+ _loading: false,
3208
+ _error: null
3209
+ }, {
3210
+ supportAsync: true,
3211
+ actions: {
3212
+ setLoading: (state, setState, { args: [loading] }) => {
3213
+ setState({ _loading: loading });
3214
+ },
3215
+ setError: (state, setState, { args: [_error] }) => {
3216
+ setState({ _error, _loading: false });
3217
+ },
3218
+ clearError: (state, setState) => {
3219
+ setState({ _error: null });
3220
+ },
3221
+ asyncAction: async (state, setState, { args: [asyncFn] }) => {
3222
+ setState({ _loading: true, _error: null });
3223
+ try {
3224
+ const result = await asyncFn(state);
3225
+ setState({ _loading: false });
3226
+ return result;
3227
+ } catch (_error) {
3228
+ setState({ _loading: false, _error });
3229
+ throw _error;
3230
+ }
3231
+ }
3232
+ }
3233
+ }),
2136
3234
  /**
2137
- * Get _error statistics
3235
+ * State with undo/redo functionality
2138
3236
  */
2139
- getStats() {
2140
- const errorsByType = {};
2141
- const errorsByTime = {};
2142
- this.errorHistory.forEach((_error) => {
2143
- errorsByType[_error.type] = (errorsByType[_error.type] || 0) + _error.count;
2144
- const hour = new Date(_error.timestamp).toISOString().slice(0, 13);
2145
- errorsByTime[hour] = (errorsByTime[hour] || 0) + _error.count;
2146
- });
2147
- return {
2148
- totalErrors: this.errorHistory.reduce((sum, e) => sum + e.count, 0),
2149
- uniqueErrors: this.errorHistory.length,
2150
- errorsByType,
2151
- errorsByTime,
2152
- mostCommonErrors: this.getMostCommonErrors(5),
2153
- recentErrors: this.errorHistory.slice(0, 10)
3237
+ withHistory: (initialState, maxHistory = 10) => {
3238
+ const historyState = {
3239
+ present: initialState,
3240
+ past: [],
3241
+ future: []
2154
3242
  };
2155
- }
3243
+ return withState(historyState, {
3244
+ actions: {
3245
+ undo: (state, setState) => {
3246
+ if (state.past.length === 0) return;
3247
+ const previous = state.past[state.past.length - 1];
3248
+ const newPast = state.past.slice(0, state.past.length - 1);
3249
+ setState({
3250
+ past: newPast,
3251
+ present: previous,
3252
+ future: [state.present, ...state.future]
3253
+ });
3254
+ },
3255
+ redo: (state, setState) => {
3256
+ if (state.future.length === 0) return;
3257
+ const next = state.future[0];
3258
+ const newFuture = state.future.slice(1);
3259
+ setState({
3260
+ past: [...state.past, state.present],
3261
+ present: next,
3262
+ future: newFuture
3263
+ });
3264
+ },
3265
+ updatePresent: (state, setState, { args: [newPresent] }) => {
3266
+ setState({
3267
+ past: [...state.past, state.present].slice(-maxHistory),
3268
+ present: newPresent,
3269
+ future: []
3270
+ });
3271
+ },
3272
+ canUndo: (state) => state.past.length > 0,
3273
+ canRedo: (state) => state.future.length > 0
3274
+ }
3275
+ });
3276
+ },
2156
3277
  /**
2157
- * Get most common errors
3278
+ * Computed state properties
2158
3279
  */
2159
- getMostCommonErrors(limit = 10) {
2160
- return this.errorHistory.sort((a, b) => b.count - a.count).slice(0, limit).map(({ name, message, count, type }) => ({
2161
- name,
2162
- message,
2163
- count,
2164
- type
2165
- }));
2166
- }
3280
+ computed: (initialState, computedProps) => withState(initialState, {
3281
+ stateTransform: (state) => {
3282
+ const computed = {};
3283
+ Object.entries(computedProps).forEach(([key, computeFn]) => {
3284
+ computed[key] = computeFn(state);
3285
+ });
3286
+ return { ...state, ...computed };
3287
+ },
3288
+ memoizeState: true
3289
+ })
2167
3290
  };
2168
- var globalErrorHandler = new ErrorHandler();
3291
+ function createStateManager(config) {
3292
+ const {
3293
+ initialState = {},
3294
+ reducers = {},
3295
+ actions = {},
3296
+ middleware = [],
3297
+ plugins = []
3298
+ } = config;
3299
+ const rootReducer = (state, action) => {
3300
+ let nextState = state;
3301
+ Object.entries(reducers).forEach(([key, reducer]) => {
3302
+ nextState = {
3303
+ ...nextState,
3304
+ [key]: reducer(nextState[key], action)
3305
+ };
3306
+ });
3307
+ return nextState;
3308
+ };
3309
+ const enhancedConfig = plugins.reduce(
3310
+ (acc, plugin) => plugin(acc),
3311
+ { initialState, reducer: rootReducer, actions, middleware }
3312
+ );
3313
+ return withState(enhancedConfig.initialState, {
3314
+ reducer: enhancedConfig.reducer,
3315
+ actions: enhancedConfig.actions,
3316
+ middleware: enhancedConfig.middleware
3317
+ });
3318
+ }
3319
+ function getComponentName(component) {
3320
+ if (!component) return "Component";
3321
+ return component.displayName || component.name || component.constructor?.name || "Component";
3322
+ }
2169
3323
 
2170
3324
  // src/components/lifecycle.js
2171
3325
  var LIFECYCLE_PHASES = {
@@ -3407,6 +4561,117 @@ function createGlobalErrorHandler(options = {}) {
3407
4561
  return new GlobalErrorHandler(options);
3408
4562
  }
3409
4563
 
4564
+ // src/utils/render-utils.js
4565
+ function renderWithMonitoring(component, options = {}) {
4566
+ const {
4567
+ enablePerformanceMonitoring = false
4568
+ } = options;
4569
+ let html;
4570
+ if (enablePerformanceMonitoring) {
4571
+ const renderId = performanceMonitor.startRender();
4572
+ html = render(component);
4573
+ performanceMonitor.endRender(renderId);
4574
+ } else {
4575
+ html = render(component);
4576
+ }
4577
+ return html;
4578
+ }
4579
+ function renderWithTemplate(component, options = {}) {
4580
+ const {
4581
+ template = "<!DOCTYPE html>\n{{content}}"
4582
+ } = options;
4583
+ const html = renderWithMonitoring(component, options);
4584
+ return template.replace("{{content}}", html);
4585
+ }
4586
+ async function renderComponentFactory(componentFactory, factoryArgs, options = {}) {
4587
+ const component = await Promise.resolve(
4588
+ componentFactory(...factoryArgs)
4589
+ );
4590
+ if (!component) {
4591
+ throw new Error("Component factory returned null/undefined");
4592
+ }
4593
+ return renderWithTemplate(component, options);
4594
+ }
4595
+ function isCoherentComponent(obj) {
4596
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
4597
+ return false;
4598
+ }
4599
+ const keys = Object.keys(obj);
4600
+ return keys.length === 1;
4601
+ }
4602
+ function createErrorResponse(error, context2 = "rendering") {
4603
+ return {
4604
+ error: "Internal Server Error",
4605
+ message: error.message,
4606
+ context: context2,
4607
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
4608
+ };
4609
+ }
4610
+
4611
+ // src/utils/dependency-utils.js
4612
+ function isPeerDependencyAvailable(packageName) {
4613
+ try {
4614
+ if (typeof __require !== "undefined" && __require.resolve) {
4615
+ __require.resolve(packageName);
4616
+ return true;
4617
+ }
4618
+ return false;
4619
+ } catch {
4620
+ return false;
4621
+ }
4622
+ }
4623
+ async function importPeerDependency(packageName, integrationName) {
4624
+ try {
4625
+ return await import(packageName);
4626
+ } catch {
4627
+ throw new Error(
4628
+ `${integrationName} integration requires the '${packageName}' package to be installed.
4629
+ Please install it with: npm install ${packageName}
4630
+ Or with pnpm: pnpm add ${packageName}
4631
+ Or with yarn: yarn add ${packageName}`
4632
+ );
4633
+ }
4634
+ }
4635
+ function createLazyIntegration(packageName, integrationName, createIntegration) {
4636
+ let cachedIntegration = null;
4637
+ let importPromise = null;
4638
+ return async function(...args) {
4639
+ if (cachedIntegration) {
4640
+ return cachedIntegration(...args);
4641
+ }
4642
+ if (!importPromise) {
4643
+ importPromise = importPeerDependency(packageName, integrationName).then((module) => {
4644
+ cachedIntegration = createIntegration(module);
4645
+ return cachedIntegration;
4646
+ });
4647
+ }
4648
+ const integration = await importPromise;
4649
+ return integration(...args);
4650
+ };
4651
+ }
4652
+ function checkPeerDependencies(dependencies) {
4653
+ const results = {};
4654
+ const missing = [];
4655
+ for (const { package: packageName, integration } of dependencies) {
4656
+ const available = isPeerDependencyAvailable(packageName);
4657
+ results[packageName] = available;
4658
+ if (!available) {
4659
+ missing.push({ package: packageName, integration });
4660
+ }
4661
+ }
4662
+ if (missing.length > 0) {
4663
+ const installCommands = missing.map(({ package: pkg }) => pkg).join(" ");
4664
+ const integrationsList = missing.map(({ integration }) => integration).join(", ");
4665
+ console.warn(
4666
+ `Optional dependencies missing for ${integrationsList} integration(s).
4667
+ To use these integrations, install: npm install ${installCommands}
4668
+ Or with pnpm: pnpm add ${installCommands}
4669
+ Or with yarn: yarn add ${installCommands}`
4670
+ );
4671
+ }
4672
+ return results;
4673
+ }
4674
+
3410
4675
  // src/shadow-dom.js
3411
4676
  var shadow_dom_exports = {};
3412
4677
  __export(shadow_dom_exports, {
@@ -4916,7 +6181,7 @@ function applyScopeToElement(element, scopeId) {
4916
6181
  }
4917
6182
  return element;
4918
6183
  }
4919
- function escapeHtml(text) {
6184
+ function escapeHtml2(text) {
4920
6185
  if (typeof text !== "string") return text;
4921
6186
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#x27;");
4922
6187
  }
@@ -4926,83 +6191,11 @@ function dangerouslySetInnerContent(content) {
4926
6191
  __trusted: true
4927
6192
  };
4928
6193
  }
4929
- function isTrustedContent(value) {
4930
- return value && typeof value === "object" && value.__trusted === true && typeof value.__html === "string";
4931
- }
4932
- function isVoidElement(tagName) {
4933
- const voidElements = /* @__PURE__ */ new Set([
4934
- "area",
4935
- "base",
4936
- "br",
4937
- "col",
4938
- "embed",
4939
- "hr",
4940
- "img",
4941
- "input",
4942
- "link",
4943
- "meta",
4944
- "param",
4945
- "source",
4946
- "track",
4947
- "wbr"
4948
- ]);
4949
- return voidElements.has(tagName.toLowerCase());
4950
- }
4951
- function formatAttributes(attrs) {
4952
- if (!attrs || typeof attrs !== "object") return "";
4953
- return Object.entries(attrs).filter(([, value]) => value !== null && value !== void 0 && value !== false).map(([key, value]) => {
4954
- if (typeof value === "function") {
4955
- value = value();
4956
- }
4957
- const attrName = key === "className" ? "class" : key;
4958
- if (value === true) return attrName;
4959
- return `${attrName}="${escapeHtml(String(value))}"`;
4960
- }).join(" ");
4961
- }
4962
- function renderRaw(obj) {
4963
- if (obj === null || obj === void 0) return "";
4964
- if (typeof obj === "string" || typeof obj === "number") return escapeHtml(String(obj));
4965
- if (Array.isArray(obj)) return obj.map(renderRaw).join("");
4966
- if (typeof obj === "function") {
4967
- const result = obj(renderRaw);
4968
- return renderRaw(result);
4969
- }
4970
- if (typeof obj !== "object") return escapeHtml(String(obj));
4971
- if (obj.text !== void 0) {
4972
- return escapeHtml(String(obj.text));
4973
- }
4974
- for (const [tagName, props] of Object.entries(obj)) {
4975
- if (typeof props === "object" && props !== null) {
4976
- const { children, text, ...attributes } = props;
4977
- const attrsStr = formatAttributes(attributes);
4978
- const openTag = attrsStr ? `<${tagName} ${attrsStr}>` : `<${tagName}>`;
4979
- if (isVoidElement(tagName)) {
4980
- return openTag.replace(">", " />");
4981
- }
4982
- let content = "";
4983
- if (text !== void 0) {
4984
- if (isTrustedContent(text)) {
4985
- content = text.__html;
4986
- } else {
4987
- content = escapeHtml(String(text));
4988
- }
4989
- } else if (children) {
4990
- content = renderRaw(children);
4991
- }
4992
- return `${openTag}${content}</${tagName}>`;
4993
- } else if (typeof props === "string") {
4994
- const content = isTrustedContent(props) ? props.__html : escapeHtml(props);
4995
- return isVoidElement(tagName) ? `<${tagName} />` : `<${tagName}>${content}</${tagName}>`;
4996
- }
4997
- }
4998
- return "";
4999
- }
5000
- function render(obj, options = {}) {
5001
- const { scoped = false } = options;
5002
- if (scoped) {
5003
- return renderScopedComponent(obj);
5004
- }
5005
- return renderRaw(obj);
6194
+ function render2(obj, options = {}) {
6195
+ const scoped = options.scoped ?? options.encapsulate ?? false;
6196
+ const { scoped: _scoped, encapsulate: _encapsulate, ...rendererOptions } = options;
6197
+ const component = scoped ? renderScopedComponent(obj) : obj;
6198
+ return render(component, rendererOptions);
5006
6199
  }
5007
6200
  function renderScopedComponent(component) {
5008
6201
  const scopeId = generateScopeId();
@@ -5034,7 +6227,7 @@ function renderScopedComponent(component) {
5034
6227
  }
5035
6228
  const processedComponent = processScopedElement(component);
5036
6229
  const scopedComponent = applyScopeToElement(processedComponent, scopeId);
5037
- return renderRaw(scopedComponent);
6230
+ return scopedComponent;
5038
6231
  }
5039
6232
  var memoCache = /* @__PURE__ */ new Map();
5040
6233
  function memo2(component, keyGenerator) {
@@ -5058,7 +6251,7 @@ function validateComponent2(obj) {
5058
6251
  }
5059
6252
  return true;
5060
6253
  }
5061
- function isCoherentObject(obj) {
6254
+ function isCoherentObject2(obj) {
5062
6255
  return obj && typeof obj === "object" && !Array.isArray(obj);
5063
6256
  }
5064
6257
  function deepClone2(obj) {
@@ -5071,10 +6264,13 @@ function deepClone2(obj) {
5071
6264
  }
5072
6265
  return cloned;
5073
6266
  }
5074
- var VERSION = "2.0.0";
6267
+ var _corePackageJson = JSON.parse(
6268
+ readFileSync(new URL("../package.json", import.meta.url), "utf-8")
6269
+ );
6270
+ var VERSION = _corePackageJson.version;
5075
6271
  var coherent = {
5076
6272
  // Core rendering
5077
- render,
6273
+ render: render2,
5078
6274
  // Shadow DOM (client-side only)
5079
6275
  shadowDOM: shadow_dom_exports,
5080
6276
  // Component system
@@ -5126,9 +6322,9 @@ var coherent = {
5126
6322
  withEventState,
5127
6323
  // Utilities
5128
6324
  validateComponent: validateComponent2,
5129
- isCoherentObject,
6325
+ isCoherentObject: isCoherentObject2,
5130
6326
  deepClone: deepClone2,
5131
- escapeHtml,
6327
+ escapeHtml: escapeHtml2,
5132
6328
  performanceMonitor,
5133
6329
  VERSION
5134
6330
  };
@@ -5138,9 +6334,12 @@ export {
5138
6334
  ComponentLifecycle,
5139
6335
  DOMEventIntegration,
5140
6336
  EventBus,
6337
+ FORBIDDEN_CHILDREN,
5141
6338
  GlobalErrorHandler,
6339
+ HTMLNestingError,
5142
6340
  LIFECYCLE_PHASES,
5143
6341
  VERSION,
6342
+ checkPeerDependencies,
5144
6343
  createActionHandlers,
5145
6344
  createAsyncErrorBoundary,
5146
6345
  createComponent,
@@ -5148,10 +6347,12 @@ export {
5148
6347
  createElement,
5149
6348
  createErrorBoundary,
5150
6349
  createErrorFallback,
6350
+ createErrorResponse,
5151
6351
  createEventBus,
5152
6352
  createEventComponent,
5153
6353
  createEventHandlers,
5154
6354
  createGlobalErrorHandler,
6355
+ createLazyIntegration,
5155
6356
  createLifecycleHooks,
5156
6357
  createStateManager,
5157
6358
  createTextNode,
@@ -5169,23 +6370,32 @@ export {
5169
6370
  globalEventBus,
5170
6371
  h,
5171
6372
  handleAction,
6373
+ hasChildren,
6374
+ importPeerDependency,
5172
6375
  initializeDOMIntegration,
5173
- isCoherentObject,
6376
+ isCoherentComponent,
6377
+ isCoherentObject2 as isCoherentObject,
5174
6378
  isLazy,
6379
+ isPeerDependencyAvailable,
5175
6380
  lazy,
5176
6381
  componentUtils as lifecycleUtils,
5177
6382
  memo2 as memo,
5178
6383
  memoize,
6384
+ normalizeChildren,
5179
6385
  off,
5180
6386
  on,
5181
6387
  once,
5182
6388
  performanceMonitor,
5183
6389
  registerAction,
5184
6390
  registerComponent,
5185
- render,
6391
+ render2 as render,
6392
+ renderComponentFactory,
6393
+ renderWithMonitoring,
6394
+ renderWithTemplate,
5186
6395
  shadow_dom_exports as shadowDOM,
5187
6396
  useHooks,
5188
6397
  validateComponent2 as validateComponent,
6398
+ validateNesting,
5189
6399
  withErrorBoundary,
5190
6400
  withEventBus,
5191
6401
  withEventState,
@@ -5193,11 +6403,17 @@ export {
5193
6403
  withState,
5194
6404
  withStateUtils
5195
6405
  };
6406
+ /**
6407
+ * Advanced caching system with memory management and smart invalidation for Coherent.js
6408
+ *
6409
+ * @module @coherent/performance/cache-manager
6410
+ * @license MIT
6411
+ */
5196
6412
  /**
5197
6413
  * Coherent.js - Object-Based Rendering Framework
5198
6414
  * A pure JavaScript framework for server-side rendering using natural object syntax
5199
6415
  *
5200
- * @version 2.0.0
6416
+ * @version 1.0.0-beta.6
5201
6417
  * @author Coherent Framework Team
5202
6418
  * @license MIT
5203
6419
  */