@jasonshimmy/custom-elements-runtime 3.3.0 → 3.5.0

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.
Files changed (106) hide show
  1. package/README.md +28 -7
  2. package/dist/css-utils-Bn-dO44e.js +203 -0
  3. package/dist/{css-utils-CC43BbEy.js.map → css-utils-Bn-dO44e.js.map} +1 -1
  4. package/dist/{css-utils-CC43BbEy.js → css-utils-CFeP8SK1.cjs} +5 -71
  5. package/dist/{css-utils-mgjmH8qX.cjs.map → css-utils-CFeP8SK1.cjs.map} +1 -1
  6. package/dist/custom-elements-runtime.cjs.js +3 -4
  7. package/dist/custom-elements-runtime.cjs.js.map +1 -1
  8. package/dist/custom-elements-runtime.colors.cjs.js +1 -2
  9. package/dist/custom-elements-runtime.colors.cjs.js.map +1 -1
  10. package/dist/custom-elements-runtime.colors.es.js +277 -277
  11. package/dist/custom-elements-runtime.colors.es.js.map +1 -1
  12. package/dist/custom-elements-runtime.directive-enhancements.cjs.js +1 -2
  13. package/dist/custom-elements-runtime.directive-enhancements.cjs.js.map +1 -1
  14. package/dist/custom-elements-runtime.directive-enhancements.es.js +106 -122
  15. package/dist/custom-elements-runtime.directive-enhancements.es.js.map +1 -1
  16. package/dist/custom-elements-runtime.directives.cjs.js +1 -2
  17. package/dist/custom-elements-runtime.directives.cjs.js.map +1 -1
  18. package/dist/custom-elements-runtime.directives.es.js +60 -65
  19. package/dist/custom-elements-runtime.directives.es.js.map +1 -1
  20. package/dist/custom-elements-runtime.dom-jit-css.cjs.js +1 -7
  21. package/dist/custom-elements-runtime.dom-jit-css.cjs.js.map +1 -1
  22. package/dist/custom-elements-runtime.dom-jit-css.es.js +103 -115
  23. package/dist/custom-elements-runtime.dom-jit-css.es.js.map +1 -1
  24. package/dist/custom-elements-runtime.es.js +206 -253
  25. package/dist/custom-elements-runtime.es.js.map +1 -1
  26. package/dist/custom-elements-runtime.event-bus.cjs.js +1 -2
  27. package/dist/custom-elements-runtime.event-bus.cjs.js.map +1 -1
  28. package/dist/custom-elements-runtime.event-bus.es.js +102 -108
  29. package/dist/custom-elements-runtime.event-bus.es.js.map +1 -1
  30. package/dist/custom-elements-runtime.jit-css.cjs.js +1 -2
  31. package/dist/custom-elements-runtime.jit-css.cjs.js.map +1 -1
  32. package/dist/custom-elements-runtime.jit-css.es.js +14 -32
  33. package/dist/custom-elements-runtime.jit-css.es.js.map +1 -1
  34. package/dist/custom-elements-runtime.router.cjs.js +20 -21
  35. package/dist/custom-elements-runtime.router.cjs.js.map +1 -1
  36. package/dist/custom-elements-runtime.router.es.js +866 -926
  37. package/dist/custom-elements-runtime.router.es.js.map +1 -1
  38. package/dist/custom-elements-runtime.ssr-middleware.cjs.js +3 -4
  39. package/dist/custom-elements-runtime.ssr-middleware.cjs.js.map +1 -1
  40. package/dist/custom-elements-runtime.ssr-middleware.es.js +67 -73
  41. package/dist/custom-elements-runtime.ssr-middleware.es.js.map +1 -1
  42. package/dist/custom-elements-runtime.ssr.cjs.js +1 -1
  43. package/dist/custom-elements-runtime.ssr.es.js +3 -13
  44. package/dist/custom-elements-runtime.store.cjs.js +1 -2
  45. package/dist/custom-elements-runtime.store.cjs.js.map +1 -1
  46. package/dist/custom-elements-runtime.store.es.js +32 -33
  47. package/dist/custom-elements-runtime.store.es.js.map +1 -1
  48. package/dist/custom-elements-runtime.transitions.cjs.js +1 -2
  49. package/dist/custom-elements-runtime.transitions.cjs.js.map +1 -1
  50. package/dist/custom-elements-runtime.transitions.es.js +200 -210
  51. package/dist/custom-elements-runtime.transitions.es.js.map +1 -1
  52. package/dist/custom-elements-runtime.vite-plugin.cjs.js +4 -2
  53. package/dist/custom-elements-runtime.vite-plugin.cjs.js.map +1 -1
  54. package/dist/custom-elements-runtime.vite-plugin.es.js +155 -78
  55. package/dist/custom-elements-runtime.vite-plugin.es.js.map +1 -1
  56. package/dist/helpers-DcEpRwq5.cjs +5 -0
  57. package/dist/helpers-DcEpRwq5.cjs.map +1 -0
  58. package/dist/helpers-tJgb4Qve.js +693 -0
  59. package/dist/helpers-tJgb4Qve.js.map +1 -0
  60. package/dist/hooks-CEUnvtsA.js +407 -0
  61. package/dist/hooks-CEUnvtsA.js.map +1 -0
  62. package/dist/hooks-CNfugc95.cjs +2 -0
  63. package/dist/hooks-CNfugc95.cjs.map +1 -0
  64. package/dist/logger-DIJ0UH3R.js +36 -0
  65. package/dist/{logger-L25axmB-.js.map → logger-DIJ0UH3R.js.map} +1 -1
  66. package/dist/logger-Dkht1dCX.cjs +2 -0
  67. package/dist/{logger-BYIN7ysT.cjs.map → logger-Dkht1dCX.cjs.map} +1 -1
  68. package/dist/namespace-helpers-CIUkG8Mn.js +56 -0
  69. package/dist/{namespace-helpers-BucDdgz_.js.map → namespace-helpers-CIUkG8Mn.js.map} +1 -1
  70. package/dist/namespace-helpers-yYIb7INq.cjs +2 -0
  71. package/dist/{namespace-helpers-Bf7rm9JV.cjs.map → namespace-helpers-yYIb7INq.cjs.map} +1 -1
  72. package/dist/runtime/tag-utils.d.ts +11 -0
  73. package/dist/ssr-BpYy9XlW.js +170 -0
  74. package/dist/{ssr-B3lxl1vr.js.map → ssr-BpYy9XlW.js.map} +1 -1
  75. package/dist/ssr-CFabTOyi.cjs +4 -0
  76. package/dist/{ssr-DtD9e5iA.cjs.map → ssr-CFabTOyi.cjs.map} +1 -1
  77. package/dist/ssr.d.ts +33 -0
  78. package/dist/style-A8l3aQ52.cjs +55 -0
  79. package/dist/{style-Bjn8zDiZ.cjs.map → style-A8l3aQ52.cjs.map} +1 -1
  80. package/dist/style-DSSoCbC9.js +1877 -0
  81. package/dist/{style-DuDoj_xK.js.map → style-DSSoCbC9.js.map} +1 -1
  82. package/dist/tag-utils-CoSXTr1F.js +10 -0
  83. package/dist/tag-utils-CoSXTr1F.js.map +1 -0
  84. package/dist/tag-utils-XJ3dkcPQ.cjs +2 -0
  85. package/dist/tag-utils-XJ3dkcPQ.cjs.map +1 -0
  86. package/dist/template-compiler-B4B_jAPN.cjs +19 -0
  87. package/dist/{template-compiler-BB4JJdqk.cjs.map → template-compiler-B4B_jAPN.cjs.map} +1 -1
  88. package/dist/template-compiler-C3h8_vbE.js +3044 -0
  89. package/dist/{template-compiler-Cs5axmn4.js.map → template-compiler-C3h8_vbE.js.map} +1 -1
  90. package/dist/vite-plugin.d.ts +96 -2
  91. package/package.json +8 -8
  92. package/dist/css-utils-mgjmH8qX.cjs +0 -577
  93. package/dist/hooks-_3xP4G2N.js +0 -1189
  94. package/dist/hooks-_3xP4G2N.js.map +0 -1
  95. package/dist/hooks-fYQgZk2g.cjs +0 -7
  96. package/dist/hooks-fYQgZk2g.cjs.map +0 -1
  97. package/dist/logger-BYIN7ysT.cjs +0 -3
  98. package/dist/logger-L25axmB-.js +0 -41
  99. package/dist/namespace-helpers-Bf7rm9JV.cjs +0 -3
  100. package/dist/namespace-helpers-BucDdgz_.js +0 -61
  101. package/dist/ssr-B3lxl1vr.js +0 -165
  102. package/dist/ssr-DtD9e5iA.cjs +0 -5
  103. package/dist/style-Bjn8zDiZ.cjs +0 -56
  104. package/dist/style-DuDoj_xK.js +0 -1972
  105. package/dist/template-compiler-BB4JJdqk.cjs +0 -23
  106. package/dist/template-compiler-Cs5axmn4.js +0 -3236
@@ -1 +1 @@
1
- {"version":3,"file":"custom-elements-runtime.es.js","names":[],"sources":["../src/lib/runtime/hydration.ts","../src/lib/runtime/monitoring/health-monitor.ts","../src/lib/keep-alive.ts","../src/lib/runtime/builtin-components.ts","../src/lib/teleport.ts"],"sourcesContent":["/**\n * Client-side hydration helpers.\n *\n * When the server renders with `dsd: true`, each custom element's shadow DOM\n * is already present in the HTML via a Declarative Shadow DOM template. The\n * browser parses that template and attaches the shadow root before any\n * JavaScript runs. When the JS bundle loads, the custom element constructors\n * detect the existing shadow root and skip the `attachShadow()` call, then\n * hydrate (attach reactivity to) the existing DOM on `connectedCallback`.\n *\n * `hydrateApp` is a signal/entry point for this process. In most cases custom\n * elements self-hydrate automatically on connection — this function is useful\n * when you need to explicitly trigger or defer the hydration of a subtree.\n */\n\n/**\n * Trigger hydration for all registered custom elements within `root`.\n *\n * In practice, custom elements self-hydrate as soon as their class definition\n * is registered and the element is connected to the DOM. Call `hydrateApp`\n * after importing and calling `component()` for all your components to signal\n * that the page is ready for reactive activation.\n *\n * @param root - The root element to hydrate. Defaults to `document`.\n *\n * @example\n * ```ts\n * import { component, hydrateApp } from '@jasonshimmy/custom-elements-runtime';\n * import './components'; // registers all components via component()\n *\n * hydrateApp(); // activate all DSD-rendered components on the page\n * ```\n */\nexport function hydrateApp(root: Element | Document = document): void {\n if (typeof CustomEvent === 'undefined') return;\n const target =\n root instanceof Document ? root.documentElement : (root as Element);\n target.dispatchEvent(\n new CustomEvent('cer:hydrate', { bubbles: true, composed: true }),\n );\n}\n","/**\n * Runtime Health Monitoring System\n * Tracks framework health metrics and provides early warning for potential issues\n */\n\nimport { devWarn, devError } from '../logger';\n\ninterface HealthMetric {\n name: string;\n value: number;\n threshold: number;\n status: 'healthy' | 'warning' | 'critical';\n lastUpdated: number;\n history: number[];\n}\n\ninterface HealthReport {\n overall: 'healthy' | 'warning' | 'critical';\n metrics: Record<string, HealthMetric>;\n timestamp: number;\n recommendations: string[];\n}\nexport type { HealthReport };\n\n/**\n * Public interface for a health monitor instance.\n * All state is managed internally via closures — no class syntax.\n */\nexport interface HealthMonitorInstance {\n /** Update a specific health metric value */\n updateMetric(name: string, value: number): void;\n /** Get the current health report */\n getHealthReport(): HealthReport;\n /** Add a listener to be notified when a health check runs */\n addListener(listener: (report: HealthReport) => void): void;\n /** Remove a previously registered listener */\n removeListener(listener: (report: HealthReport) => void): void;\n /** Stop the periodic health monitoring timer */\n stop(): void;\n /** Get historical values for a specific metric */\n getMetricHistory(name: string): number[];\n /** Clear all metric history */\n clearHistory(): void;\n}\n\nconst MAX_HISTORY_SIZE = 100;\nconst CHECK_INTERVAL = 30_000; // 30 seconds\n\nfunction calcStatus(\n value: number,\n threshold: number,\n metricName: string,\n): 'healthy' | 'warning' | 'critical' {\n if (metricName === 'jitCacheHitRate') {\n if (value < threshold * 0.5) return 'critical';\n if (value < threshold) return 'warning';\n return 'healthy';\n }\n if (value > threshold * 2) return 'critical';\n if (value > threshold) return 'warning';\n return 'healthy';\n}\n\nfunction buildRecommendations(metrics: Record<string, HealthMetric>): string[] {\n const out: string[] = [];\n if (metrics.memoryUsage?.status !== 'healthy')\n out.push(\n 'Consider reducing component complexity or implementing better memory cleanup',\n );\n if (metrics.averageRenderTime?.status !== 'healthy')\n out.push(\n 'Optimize component render functions - consider lazy loading or virtualization',\n );\n if (metrics.jitCacheHitRate?.status !== 'healthy')\n out.push(\n 'JIT CSS cache performance is poor - review CSS patterns for optimization',\n );\n if (metrics.componentErrorRate?.status !== 'healthy')\n out.push(\n 'High component error rate detected - review error handling and component logic',\n );\n if (metrics.activeReactiveStates?.status !== 'healthy')\n out.push(\n 'High number of reactive states - consider state consolidation or cleanup',\n );\n if (metrics.memoryLeakIndicator?.status !== 'healthy')\n out.push(\n 'Potential memory leak detected - review component cleanup and event listener management',\n );\n return out;\n}\n\n/**\n * Create a new health monitor instance.\n * All mutable state lives in closures — no `class` or `this`.\n */\nexport function createHealthMonitor(): HealthMonitorInstance {\n const metricsMap = new Map<string, HealthMetric>();\n const listeners = new Set<(report: HealthReport) => void>();\n let intervalId: ReturnType<typeof setInterval> | null = null;\n\n function addMetric(name: string, value: number, threshold: number): void {\n metricsMap.set(name, {\n name,\n value,\n threshold,\n status: 'healthy',\n lastUpdated: Date.now(),\n history: [],\n });\n }\n\n function initializeMetrics(): void {\n addMetric('activeComponents', 0, 1000);\n addMetric('componentCreateRate', 0, 50);\n addMetric('componentErrorRate', 0, 0.1);\n addMetric('memoryUsage', 0, 50 * 1024 * 1024);\n addMetric('memoryGrowthRate', 0, 1024 * 1024);\n addMetric('averageRenderTime', 0, 16);\n addMetric('slowRenderCount', 0, 10);\n addMetric('jitCacheHitRate', 100, 80);\n addMetric('activeReactiveStates', 0, 5000);\n addMetric('dependencyUpdates', 0, 100);\n addMetric('memoryLeakIndicator', 0, 0.1);\n }\n\n function updateMetric(name: string, value: number): void {\n const metric = metricsMap.get(name);\n if (!metric) return;\n metric.value = value;\n metric.lastUpdated = Date.now();\n metric.history.push(value);\n if (metric.history.length > MAX_HISTORY_SIZE) metric.history.shift();\n metric.status = calcStatus(value, metric.threshold, name);\n }\n\n function getHealthReport(): HealthReport {\n const snapshot: Record<string, HealthMetric> = {};\n let overall: 'healthy' | 'warning' | 'critical' = 'healthy';\n for (const [name, metric] of metricsMap) {\n snapshot[name] = { ...metric };\n if (metric.status === 'critical') overall = 'critical';\n else if (metric.status === 'warning' && overall === 'healthy')\n overall = 'warning';\n }\n return {\n overall,\n metrics: snapshot,\n timestamp: Date.now(),\n recommendations: buildRecommendations(snapshot),\n };\n }\n\n function updateMemoryMetrics(): void {\n if (\n 'memory' in performance &&\n (performance as Record<string, unknown>).memory\n ) {\n const mem = (performance as Record<string, unknown>).memory as {\n usedJSHeapSize: number;\n };\n updateMetric('memoryUsage', mem.usedJSHeapSize);\n const m = metricsMap.get('memoryUsage');\n if (m && m.history.length > 1) {\n const prev = m.history[m.history.length - 2];\n const curr = m.history[m.history.length - 1];\n updateMetric('memoryGrowthRate', Math.max(0, curr - prev));\n }\n }\n }\n\n function notifyListeners(report: HealthReport): void {\n for (const listener of listeners) {\n try {\n listener(report);\n } catch (e) {\n devError('Error in health monitor listener:', e);\n }\n }\n }\n\n function performHealthCheck(): void {\n updateMemoryMetrics();\n const report = getHealthReport();\n notifyListeners(report);\n if (report.overall === 'critical')\n devError(\n '🚨 Runtime Health: Critical issues detected',\n report.recommendations,\n );\n else if (report.overall === 'warning')\n devWarn(\n '⚠️ Runtime Health: Performance warnings',\n report.recommendations,\n );\n }\n\n function startMonitoring(): void {\n if (typeof window === 'undefined') return;\n intervalId = setInterval(performHealthCheck, CHECK_INTERVAL);\n }\n\n function stop(): void {\n if (intervalId !== null) {\n clearInterval(intervalId);\n intervalId = null;\n }\n }\n\n function addListener(listener: (report: HealthReport) => void): void {\n listeners.add(listener);\n }\n function removeListener(listener: (report: HealthReport) => void): void {\n listeners.delete(listener);\n }\n function getMetricHistory(name: string): number[] {\n const m = metricsMap.get(name);\n return m ? [...m.history] : [];\n }\n function clearHistory(): void {\n for (const m of metricsMap.values()) m.history = [];\n }\n\n initializeMetrics();\n startMonitoring();\n\n return {\n updateMetric,\n getHealthReport,\n addListener,\n removeListener,\n stop,\n getMetricHistory,\n clearHistory,\n };\n}\n\n// Global singleton\nlet _monitor: HealthMonitorInstance | null = null;\n\n/**\n * Get the global health monitor singleton instance.\n */\nexport function getHealthMonitor(): HealthMonitorInstance {\n if (!_monitor) _monitor = createHealthMonitor();\n return _monitor;\n}\n\n/**\n * Update a health metric from anywhere in the framework.\n */\nexport function updateHealthMetric(name: string, value: number): void {\n getHealthMonitor().updateMetric(name, value);\n}\n\n/**\n * Get the current health status report.\n */\nexport function getHealthStatus(): HealthReport {\n return getHealthMonitor().getHealthReport();\n}\n","/**\n * keep-alive.ts\n *\n * Preserves component state when a component is removed from and later\n * re-inserted into the DOM. By default, custom elements lose all JavaScript\n * state when `disconnectedCallback` fires. `cer-keep-alive` intercepts\n * that lifecycle and keeps the child element alive in memory, re-attaching\n * it when a matching component is re-inserted.\n *\n * ## Usage\n *\n * Wrap any custom element with `<cer-keep-alive>`:\n * ```html\n * <cer-keep-alive>\n * <my-counter></my-counter>\n * </cer-keep-alive>\n * ```\n *\n * Or register it programmatically:\n * ```ts\n * import { registerKeepAlive } from '@jasonshimmy/custom-elements-runtime';\n * registerKeepAlive(); // registers <cer-keep-alive> globally\n * ```\n *\n * ## How it works\n *\n * `cer-keep-alive` uses a slotted layout. When a slotted child component is\n * about to leave the DOM (via a re-render of a parent), KeepAlive intercepts\n * `slotchange` events and preserves the detached child element in an internal\n * cache keyed by tag name. When the same tag re-appears in the slot, the\n * cached element is re-inserted, restoring all JavaScript state.\n *\n * ## Limitations\n *\n * - The first slot child per tag name is cached. Multiple children with the\n * same tag use separate cache entries keyed by their `id` attribute.\n * - Only components registered with the same tag name are matched.\n * - Cache entries can be manually evicted with `clearCache()`.\n */\n\n/** Cache key = tagName[:id] */\ntype CacheKey = string;\n\n/**\n * Register the `<cer-keep-alive>` custom element.\n * Safe to call multiple times — subsequent calls are no-ops.\n *\n * @example\n * ```ts\n * import { registerKeepAlive } from '@jasonshimmy/custom-elements-runtime';\n * registerKeepAlive();\n * ```\n */\nexport function registerKeepAlive(): void {\n if (\n typeof window === 'undefined' ||\n typeof customElements === 'undefined' ||\n customElements.get('cer-keep-alive')\n ) {\n return;\n }\n\n customElements.define('cer-keep-alive', createKeepAliveClass());\n}\n\nfunction createKeepAliveClass(): CustomElementConstructor {\n return class CerKeepAlive extends HTMLElement {\n /** Preserved component instances keyed by tag[:id]. */\n private _cache = new Map<CacheKey, Element>();\n private _slot: HTMLSlotElement | null = null;\n private _slotListener: (() => void) | null = null;\n\n connectedCallback(): void {\n if (!this.shadowRoot) {\n this.attachShadow({ mode: 'open' });\n }\n\n if (!this.shadowRoot!.querySelector('slot')) {\n this.shadowRoot!.innerHTML = '<slot></slot>';\n }\n\n this._slot = this.shadowRoot!.querySelector('slot');\n if (this._slot) {\n this._slotListener = () => this._handleSlotChange();\n this._slot.addEventListener('slotchange', this._slotListener);\n // Process current slotted content\n this._handleSlotChange();\n }\n }\n\n disconnectedCallback(): void {\n if (this._slot && this._slotListener) {\n this._slot.removeEventListener('slotchange', this._slotListener);\n }\n this._slotListener = null;\n }\n\n /**\n * Evict a cached element by its cache key (`tagName` or `tagName:id`).\n * The evicted element is disconnected and removed from the cache.\n */\n clearCache(key?: CacheKey): void {\n if (key) {\n this._cache.delete(key);\n } else {\n this._cache.clear();\n }\n }\n\n private _handleSlotChange(): void {\n if (!this._slot) return;\n\n const slottedElements = this._slot.assignedElements({ flatten: true });\n\n for (const child of slottedElements) {\n const cacheKey = this._buildCacheKey(child);\n\n if (!this._cache.has(cacheKey)) {\n // New element — cache it so we can restore it later\n this._cache.set(cacheKey, child);\n } else {\n const cached = this._cache.get(cacheKey)!;\n if (cached !== child) {\n // A different instance appeared for the same slot.\n // Replace it with the cached instance to restore state.\n try {\n child.parentNode?.replaceChild(cached, child);\n } catch {\n // If replacement fails, update the cache with the new element\n this._cache.set(cacheKey, child);\n }\n }\n }\n }\n }\n\n private _buildCacheKey(el: Element): CacheKey {\n const tag = el.tagName.toLowerCase();\n const id = el.getAttribute('id');\n return id ? `${tag}:${id}` : tag;\n }\n };\n}\n","/**\n * Built-in utility components provided by the custom-elements runtime.\n *\n * These components are registered automatically when this module is imported.\n * They are designed to be minimal, tree-shakeable, and zero-dependency.\n *\n * Included components:\n * - `<cer-suspense>` — Shows a fallback while async work is pending\n * - `<cer-error-boundary>` — Catches render errors and shows a fallback UI\n * - `<cer-keep-alive>` — Preserves component state across DOM removal/re-insertion\n */\n\nimport { component } from './component';\nimport { html } from './template-compiler';\nimport { ref } from './reactive';\nimport { useProps, useOnError, useExpose } from './hooks';\nimport { registerKeepAlive } from '../keep-alive';\n\n// ── cer-suspense ──────────────────────────────────────────────────────────────\n\n/**\n * A built-in component that conditionally renders either the default slot\n * content or the `fallback` slot content, controlled by the `pending` prop.\n *\n * Use the `pending` attribute/property to signal that async work is in\n * progress; the component will swap to the `fallback` slot until `pending`\n * becomes falsy.\n *\n * @example\n * ```html\n * <cer-suspense pending>\n * <!-- shown when pending=false -->\n * <my-async-content></my-async-content>\n *\n * <!-- shown while pending=true -->\n * <div slot=\"fallback\">Loading…</div>\n * </cer-suspense>\n * ```\n *\n * @example Programmatic usage\n * ```ts\n * component('my-data-loader', () => {\n * const pending = ref(true);\n * useOnConnected(async () => {\n * await fetchData();\n * pending.value = false;\n * });\n * return html`\n * <cer-suspense pending=\"${pending.value}\">\n * <my-data-view></my-data-view>\n * <div slot=\"fallback\">Loading data…</div>\n * </cer-suspense>\n * `;\n * });\n * ```\n */\nexport function registerSuspense(): void {\n if (typeof customElements !== 'undefined' && customElements.get('cer-suspense')) return;\n\n component('cer-suspense', () => {\n const { pending } = useProps({ pending: false });\n\n return pending\n ? html`<slot name=\"fallback\"><span>Loading…</span></slot>`\n : html`<slot></slot>`;\n });\n}\n\n// ── cer-error-boundary ────────────────────────────────────────────────────────\n\n/**\n * A built-in component that catches errors thrown during child component\n * rendering and displays a fallback UI instead of crashing the page.\n *\n * Errors are caught via the `useOnError` lifecycle hook. Once an error is\n * caught the component switches to showing the `fallback` named slot (or a\n * default \"Something went wrong\" message if no fallback slot is provided).\n *\n * Call the custom `reset()` method on the element to clear the error and\n * attempt re-rendering the default slot.\n *\n * @example\n * ```html\n * <cer-error-boundary>\n * <my-risky-component></my-risky-component>\n *\n * <div slot=\"fallback\">\n * <p>Something went wrong. <button onclick=\"this.closest('cer-error-boundary').reset()\">Retry</button></p>\n * </div>\n * </cer-error-boundary>\n * ```\n */\nexport function registerErrorBoundary(): void {\n if (typeof customElements !== 'undefined' && customElements.get('cer-error-boundary')) return;\n\n component('cer-error-boundary', () => {\n const hasError = ref(false);\n const errorMessage = ref('');\n\n useOnError((err: Error) => {\n hasError.value = true;\n errorMessage.value = err.message;\n });\n\n // Expose a reset() method so parent templates can call\n // `errorBoundaryRef.value.reset()` to clear the error and retry.\n // Also expose an internal `_cerHandleChildError` receiver so that the\n // component runtime can propagate uncaught errors from slotted child\n // components up to the nearest ancestor <cer-error-boundary>.\n useExpose({\n _cerHandleChildError: (err: unknown) => {\n // Use peek() to read the current value without registering a reactive\n // dependency — the child component's render context may be active when\n // this handler runs, and we must not accidentally subscribe the child\n // to this boundary's internal state.\n if (!hasError.peek()) {\n hasError.value = true;\n errorMessage.value = err instanceof Error ? err.message : String(err);\n }\n },\n reset: () => {\n hasError.value = false;\n errorMessage.value = '';\n },\n });\n\n return hasError.value\n ? html`<slot name=\"fallback\"\n ><div role=\"alert\">\n <strong>Something went wrong.</strong>\n ${errorMessage.value ? html`<p>${errorMessage.value}</p>` : html``}\n </div></slot\n >`\n : html`<slot></slot>`;\n });\n}\n\n// ── Auto-register all components ─────────────────────────────────────────────\n\n/**\n * Register all built-in components (`cer-suspense`, `cer-error-boundary`,\n * `cer-keep-alive`).\n * Safe to call multiple times — each registration is guarded by a\n * `customElements.get()` check.\n */\nexport function registerBuiltinComponents(): void {\n registerSuspense();\n registerErrorBoundary();\n registerKeepAlive();\n}\n","/**\n * teleport.ts\n *\n * Renders virtual DOM content into an arbitrary DOM target located outside\n * the current component's Shadow Root. Useful for modals, tooltips, popovers,\n * and any UI that must visually escape the component boundary.\n *\n * @example\n * ```ts\n * import { component, html, ref, useOnDisconnected, useTeleport } from '@jasonshimmy/custom-elements-runtime';\n *\n * component('modal-trigger', () => {\n * const isOpen = ref(false);\n *\n * // Render modal content into <body> outside the shadow root\n * const { portal, destroy } = useTeleport('#modal-root');\n * useOnDisconnected(destroy);\n *\n * // Call portal() to update the teleported content on each render\n * if (isOpen.value) {\n * portal(html`<div class=\"modal\">\n * <h2>Hello</h2>\n * <button @click=\"${() => (isOpen.value = false)}\">Close</button>\n * </div>`);\n * } else {\n * portal(null);\n * }\n *\n * return html`\n * <button @click=\"${() => (isOpen.value = true)}\">Open modal</button>\n * `;\n * });\n * ```\n */\n\nimport type { VNode, VDomRefs } from './runtime/types';\nimport { vdomRenderer } from './runtime/vdom';\nimport { reactiveSystem } from './runtime/reactive';\nimport { getCurrentComponentContext, isDiscoveryRender } from './runtime/hooks';\n\n/** Handle returned by {@link useTeleport} for managing a portal. */\nexport interface TeleportHandle {\n /**\n * Render (or clear) content at the teleport target.\n * Pass `null` or `undefined` to remove previously rendered content.\n */\n portal(content: VNode | VNode[] | null | undefined): void;\n\n /**\n * Destroy the teleport container and clean up all rendered content.\n * Call this in `useOnDisconnected` to prevent memory leaks.\n */\n destroy(): void;\n}\n\n/**\n * Create a teleport portal that renders content outside the current Shadow Root.\n *\n * @param target - A CSS selector string or an `Element` reference to render into.\n * @returns A {@link TeleportHandle} with `portal()` (update content) and `destroy()` (cleanup).\n *\n * @example\n * ```ts\n * import { component, html, useOnDisconnected, useTeleport } from '@jasonshimmy/custom-elements-runtime';\n *\n * component('my-tooltip', () => {\n * const { portal, destroy } = useTeleport('body');\n * useOnDisconnected(destroy);\n *\n * portal(html`<div class=\"tooltip\">Tooltip content</div>`);\n * return html`<span>Hover me</span>`;\n * });\n * ```\n */\nexport function useTeleport(target: string | Element): TeleportHandle {\n // SSR guard\n if (typeof document === 'undefined') {\n return { portal: () => {}, destroy: () => {} };\n }\n\n // During discovery render the component is not yet mounted — return a no-op\n // handle so the library can detect props/hooks without side-effects.\n if (isDiscoveryRender()) {\n return { portal: () => {}, destroy: () => {} };\n }\n\n // If called inside a component render, use the reactive state-index slot\n // mechanism to ensure the same handle is returned on every re-render of the\n // same component instance. Without this, each re-render would create a new\n // <cer-teleport> container in the target, leaking all but the last one.\n const ctx = getCurrentComponentContext();\n if (ctx) {\n // getOrCreateState uses an incrementing stateIndex that is reset to 0 at\n // the start of each render, so the same call site always gets the same slot.\n const slot = reactiveSystem.getOrCreateState<TeleportHandle | null>(null);\n const existing = slot.peek();\n if (existing !== null) {\n return existing;\n }\n // First render: create the handle and store it without triggering a\n // reactive update (initSilent bypasses triggerUpdate).\n // Pass a slot-invalidation callback so that destroy() clears the slot,\n // allowing a reconnected component to create a fresh container.\n const handle = _createTeleportHandle(target, () => slot.initSilent(null));\n slot.initSilent(handle);\n return handle;\n }\n\n // Outside a component context (e.g. called directly in tests or scripts):\n // fall through to a non-cached, non-stable handle.\n return _createTeleportHandle(target);\n}\n\n/** Internal: create a fresh teleport handle pointing at `target`.\n * @param onDestroy - Optional callback invoked after cleanup in destroy(), used\n * to invalidate a cached slot so the next render creates a fresh handle.\n */\nfunction _createTeleportHandle(\n target: string | Element,\n onDestroy?: () => void,\n): TeleportHandle {\n const targetEl =\n typeof target === 'string'\n ? (document.querySelector(target) as Element | null)\n : target;\n\n if (!targetEl) {\n console.warn(\n `[useTeleport] Target \"${String(target)}\" not found in the document. ` +\n 'Teleported content will not be rendered.',\n );\n return { portal: () => {}, destroy: () => {} };\n }\n\n // Create a dedicated container so we never clobber sibling content.\n const container = document.createElement('cer-teleport');\n container.dataset.cerTeleport = '';\n targetEl.appendChild(container);\n\n // Shared refs bag — passed consistently so ref directives work across updates.\n const refs: VDomRefs = {};\n\n const handle: TeleportHandle = {\n portal(content: VNode | VNode[] | null | undefined): void {\n const nodes: VNode[] =\n content == null ? [] : Array.isArray(content) ? content : [content];\n // vdomRenderer stores _prevVNode/_prevDom on the root object for diffing.\n // Casting to ShadowRoot is safe: we only access properties that exist on\n // HTMLElement (firstChild, appendChild, replaceChild, childNodes).\n vdomRenderer(container as unknown as ShadowRoot, nodes, undefined, refs);\n },\n\n destroy(): void {\n // Render empty nodes to clean up event listeners and refs.\n try {\n vdomRenderer(container as unknown as ShadowRoot, [], undefined, refs);\n } catch {\n /* best-effort cleanup */\n }\n if (container.parentNode) {\n container.parentNode.removeChild(container);\n }\n // Invalidate the cached slot so that if the component reconnects and\n // re-renders, useTeleport() creates a fresh container rather than\n // reusing this destroyed one.\n onDestroy?.();\n },\n };\n\n return handle;\n}\n"],"mappings":";;;;AAiCA,SAAgB,GAAW,IAA2B,UAAgB;AACpE,EAAI,OAAO,cAAgB,QAEzB,aAAgB,WAAW,EAAK,kBAAmB,GAC9C,cACL,IAAI,YAAY,eAAe;AAAA,IAAE,SAAS;AAAA,IAAM,UAAU;AAAA,GAAM,CAAC;;ACOrE,IAAM,IAAmB,KACnB,IAAiB;AAEvB,SAAS,EACP,GACA,GACA,GACoC;AACpC,SAAI,MAAe,oBACb,IAAQ,IAAY,MAAY,aAChC,IAAQ,IAAkB,YACvB,YAEL,IAAQ,IAAY,IAAU,aAC9B,IAAQ,IAAkB,YACvB;;AAGT,SAAS,EAAqB,GAAiD;AAC7E,QAAM,IAAgB,CAAA;AACtB,SAAI,EAAQ,aAAa,WAAW,aAClC,EAAI,KACF,8EAAA,GAEA,EAAQ,mBAAmB,WAAW,aACxC,EAAI,KACF,+EAAA,GAEA,EAAQ,iBAAiB,WAAW,aACtC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7B,OAAO,GAAmD;AAMxD,MAAA,EAAa,GAJX,KAAW,OAAO,CAAA,IAAK,MAAM,QAAQ,CAAA,IAAW,IAAU,CAAC,CAAA,GAIL,QAAW,CAAA;AAAA;IAGrE,UAAgB;AAEd,UAAI;AACF,QAAA,EAAa,GAAoC,CAAA,GAAI,QAAW,CAAA;AAAA,cAC1D;AAAA,MAAA;AAGR,MAAI,EAAU,cACZ,EAAU,WAAW,YAAY,CAAA,GAKnC,IAAA;AAAA"}
1
+ {"version":3,"file":"custom-elements-runtime.es.js","names":[],"sources":["../src/lib/runtime/hydration.ts","../src/lib/runtime/monitoring/health-monitor.ts","../src/lib/keep-alive.ts","../src/lib/runtime/builtin-components.ts","../src/lib/teleport.ts"],"sourcesContent":["/**\n * Client-side hydration helpers.\n *\n * When the server renders with `dsd: true`, each custom element's shadow DOM\n * is already present in the HTML via a Declarative Shadow DOM template. The\n * browser parses that template and attaches the shadow root before any\n * JavaScript runs. When the JS bundle loads, the custom element constructors\n * detect the existing shadow root and skip the `attachShadow()` call, then\n * hydrate (attach reactivity to) the existing DOM on `connectedCallback`.\n *\n * `hydrateApp` is a signal/entry point for this process. In most cases custom\n * elements self-hydrate automatically on connection — this function is useful\n * when you need to explicitly trigger or defer the hydration of a subtree.\n */\n\n/**\n * Trigger hydration for all registered custom elements within `root`.\n *\n * In practice, custom elements self-hydrate as soon as their class definition\n * is registered and the element is connected to the DOM. Call `hydrateApp`\n * after importing and calling `component()` for all your components to signal\n * that the page is ready for reactive activation.\n *\n * @param root - The root element to hydrate. Defaults to `document`.\n *\n * @example\n * ```ts\n * import { component, hydrateApp } from '@jasonshimmy/custom-elements-runtime';\n * import './components'; // registers all components via component()\n *\n * hydrateApp(); // activate all DSD-rendered components on the page\n * ```\n */\nexport function hydrateApp(root: Element | Document = document): void {\n if (typeof CustomEvent === 'undefined') return;\n const target =\n root instanceof Document ? root.documentElement : (root as Element);\n target.dispatchEvent(\n new CustomEvent('cer:hydrate', { bubbles: true, composed: true }),\n );\n}\n","/**\n * Runtime Health Monitoring System\n * Tracks framework health metrics and provides early warning for potential issues\n */\n\nimport { devWarn, devError } from '../logger';\n\ninterface HealthMetric {\n name: string;\n value: number;\n threshold: number;\n status: 'healthy' | 'warning' | 'critical';\n lastUpdated: number;\n history: number[];\n}\n\ninterface HealthReport {\n overall: 'healthy' | 'warning' | 'critical';\n metrics: Record<string, HealthMetric>;\n timestamp: number;\n recommendations: string[];\n}\nexport type { HealthReport };\n\n/**\n * Public interface for a health monitor instance.\n * All state is managed internally via closures — no class syntax.\n */\nexport interface HealthMonitorInstance {\n /** Update a specific health metric value */\n updateMetric(name: string, value: number): void;\n /** Get the current health report */\n getHealthReport(): HealthReport;\n /** Add a listener to be notified when a health check runs */\n addListener(listener: (report: HealthReport) => void): void;\n /** Remove a previously registered listener */\n removeListener(listener: (report: HealthReport) => void): void;\n /** Stop the periodic health monitoring timer */\n stop(): void;\n /** Get historical values for a specific metric */\n getMetricHistory(name: string): number[];\n /** Clear all metric history */\n clearHistory(): void;\n}\n\nconst MAX_HISTORY_SIZE = 100;\nconst CHECK_INTERVAL = 30_000; // 30 seconds\n\nfunction calcStatus(\n value: number,\n threshold: number,\n metricName: string,\n): 'healthy' | 'warning' | 'critical' {\n if (metricName === 'jitCacheHitRate') {\n if (value < threshold * 0.5) return 'critical';\n if (value < threshold) return 'warning';\n return 'healthy';\n }\n if (value > threshold * 2) return 'critical';\n if (value > threshold) return 'warning';\n return 'healthy';\n}\n\nfunction buildRecommendations(metrics: Record<string, HealthMetric>): string[] {\n const out: string[] = [];\n if (metrics.memoryUsage?.status !== 'healthy')\n out.push(\n 'Consider reducing component complexity or implementing better memory cleanup',\n );\n if (metrics.averageRenderTime?.status !== 'healthy')\n out.push(\n 'Optimize component render functions - consider lazy loading or virtualization',\n );\n if (metrics.jitCacheHitRate?.status !== 'healthy')\n out.push(\n 'JIT CSS cache performance is poor - review CSS patterns for optimization',\n );\n if (metrics.componentErrorRate?.status !== 'healthy')\n out.push(\n 'High component error rate detected - review error handling and component logic',\n );\n if (metrics.activeReactiveStates?.status !== 'healthy')\n out.push(\n 'High number of reactive states - consider state consolidation or cleanup',\n );\n if (metrics.memoryLeakIndicator?.status !== 'healthy')\n out.push(\n 'Potential memory leak detected - review component cleanup and event listener management',\n );\n return out;\n}\n\n/**\n * Create a new health monitor instance.\n * All mutable state lives in closures — no `class` or `this`.\n */\nexport function createHealthMonitor(): HealthMonitorInstance {\n const metricsMap = new Map<string, HealthMetric>();\n const listeners = new Set<(report: HealthReport) => void>();\n let intervalId: ReturnType<typeof setInterval> | null = null;\n\n function addMetric(name: string, value: number, threshold: number): void {\n metricsMap.set(name, {\n name,\n value,\n threshold,\n status: 'healthy',\n lastUpdated: Date.now(),\n history: [],\n });\n }\n\n function initializeMetrics(): void {\n addMetric('activeComponents', 0, 1000);\n addMetric('componentCreateRate', 0, 50);\n addMetric('componentErrorRate', 0, 0.1);\n addMetric('memoryUsage', 0, 50 * 1024 * 1024);\n addMetric('memoryGrowthRate', 0, 1024 * 1024);\n addMetric('averageRenderTime', 0, 16);\n addMetric('slowRenderCount', 0, 10);\n addMetric('jitCacheHitRate', 100, 80);\n addMetric('activeReactiveStates', 0, 5000);\n addMetric('dependencyUpdates', 0, 100);\n addMetric('memoryLeakIndicator', 0, 0.1);\n }\n\n function updateMetric(name: string, value: number): void {\n const metric = metricsMap.get(name);\n if (!metric) return;\n metric.value = value;\n metric.lastUpdated = Date.now();\n metric.history.push(value);\n if (metric.history.length > MAX_HISTORY_SIZE) metric.history.shift();\n metric.status = calcStatus(value, metric.threshold, name);\n }\n\n function getHealthReport(): HealthReport {\n const snapshot: Record<string, HealthMetric> = {};\n let overall: 'healthy' | 'warning' | 'critical' = 'healthy';\n for (const [name, metric] of metricsMap) {\n snapshot[name] = { ...metric };\n if (metric.status === 'critical') overall = 'critical';\n else if (metric.status === 'warning' && overall === 'healthy')\n overall = 'warning';\n }\n return {\n overall,\n metrics: snapshot,\n timestamp: Date.now(),\n recommendations: buildRecommendations(snapshot),\n };\n }\n\n function updateMemoryMetrics(): void {\n if (\n 'memory' in performance &&\n (performance as Record<string, unknown>).memory\n ) {\n const mem = (performance as Record<string, unknown>).memory as {\n usedJSHeapSize: number;\n };\n updateMetric('memoryUsage', mem.usedJSHeapSize);\n const m = metricsMap.get('memoryUsage');\n if (m && m.history.length > 1) {\n const prev = m.history[m.history.length - 2];\n const curr = m.history[m.history.length - 1];\n updateMetric('memoryGrowthRate', Math.max(0, curr - prev));\n }\n }\n }\n\n function notifyListeners(report: HealthReport): void {\n for (const listener of listeners) {\n try {\n listener(report);\n } catch (e) {\n devError('Error in health monitor listener:', e);\n }\n }\n }\n\n function performHealthCheck(): void {\n updateMemoryMetrics();\n const report = getHealthReport();\n notifyListeners(report);\n if (report.overall === 'critical')\n devError(\n '🚨 Runtime Health: Critical issues detected',\n report.recommendations,\n );\n else if (report.overall === 'warning')\n devWarn(\n '⚠️ Runtime Health: Performance warnings',\n report.recommendations,\n );\n }\n\n function startMonitoring(): void {\n if (typeof window === 'undefined') return;\n intervalId = setInterval(performHealthCheck, CHECK_INTERVAL);\n }\n\n function stop(): void {\n if (intervalId !== null) {\n clearInterval(intervalId);\n intervalId = null;\n }\n }\n\n function addListener(listener: (report: HealthReport) => void): void {\n listeners.add(listener);\n }\n function removeListener(listener: (report: HealthReport) => void): void {\n listeners.delete(listener);\n }\n function getMetricHistory(name: string): number[] {\n const m = metricsMap.get(name);\n return m ? [...m.history] : [];\n }\n function clearHistory(): void {\n for (const m of metricsMap.values()) m.history = [];\n }\n\n initializeMetrics();\n startMonitoring();\n\n return {\n updateMetric,\n getHealthReport,\n addListener,\n removeListener,\n stop,\n getMetricHistory,\n clearHistory,\n };\n}\n\n// Global singleton\nlet _monitor: HealthMonitorInstance | null = null;\n\n/**\n * Get the global health monitor singleton instance.\n */\nexport function getHealthMonitor(): HealthMonitorInstance {\n if (!_monitor) _monitor = createHealthMonitor();\n return _monitor;\n}\n\n/**\n * Update a health metric from anywhere in the framework.\n */\nexport function updateHealthMetric(name: string, value: number): void {\n getHealthMonitor().updateMetric(name, value);\n}\n\n/**\n * Get the current health status report.\n */\nexport function getHealthStatus(): HealthReport {\n return getHealthMonitor().getHealthReport();\n}\n","/**\n * keep-alive.ts\n *\n * Preserves component state when a component is removed from and later\n * re-inserted into the DOM. By default, custom elements lose all JavaScript\n * state when `disconnectedCallback` fires. `cer-keep-alive` intercepts\n * that lifecycle and keeps the child element alive in memory, re-attaching\n * it when a matching component is re-inserted.\n *\n * ## Usage\n *\n * Wrap any custom element with `<cer-keep-alive>`:\n * ```html\n * <cer-keep-alive>\n * <my-counter></my-counter>\n * </cer-keep-alive>\n * ```\n *\n * Or register it programmatically:\n * ```ts\n * import { registerKeepAlive } from '@jasonshimmy/custom-elements-runtime';\n * registerKeepAlive(); // registers <cer-keep-alive> globally\n * ```\n *\n * ## How it works\n *\n * `cer-keep-alive` uses a slotted layout. When a slotted child component is\n * about to leave the DOM (via a re-render of a parent), KeepAlive intercepts\n * `slotchange` events and preserves the detached child element in an internal\n * cache keyed by tag name. When the same tag re-appears in the slot, the\n * cached element is re-inserted, restoring all JavaScript state.\n *\n * ## Limitations\n *\n * - The first slot child per tag name is cached. Multiple children with the\n * same tag use separate cache entries keyed by their `id` attribute.\n * - Only components registered with the same tag name are matched.\n * - Cache entries can be manually evicted with `clearCache()`.\n */\n\n/** Cache key = tagName[:id] */\ntype CacheKey = string;\n\n/**\n * Register the `<cer-keep-alive>` custom element.\n * Safe to call multiple times — subsequent calls are no-ops.\n *\n * @example\n * ```ts\n * import { registerKeepAlive } from '@jasonshimmy/custom-elements-runtime';\n * registerKeepAlive();\n * ```\n */\nexport function registerKeepAlive(): void {\n if (\n typeof window === 'undefined' ||\n typeof customElements === 'undefined' ||\n customElements.get('cer-keep-alive')\n ) {\n return;\n }\n\n customElements.define('cer-keep-alive', createKeepAliveClass());\n}\n\nfunction createKeepAliveClass(): CustomElementConstructor {\n return class CerKeepAlive extends HTMLElement {\n /** Preserved component instances keyed by tag[:id]. */\n private _cache = new Map<CacheKey, Element>();\n private _slot: HTMLSlotElement | null = null;\n private _slotListener: (() => void) | null = null;\n\n connectedCallback(): void {\n if (!this.shadowRoot) {\n this.attachShadow({ mode: 'open' });\n }\n\n if (!this.shadowRoot!.querySelector('slot')) {\n this.shadowRoot!.innerHTML = '<slot></slot>';\n }\n\n this._slot = this.shadowRoot!.querySelector('slot');\n if (this._slot) {\n this._slotListener = () => this._handleSlotChange();\n this._slot.addEventListener('slotchange', this._slotListener);\n // Process current slotted content\n this._handleSlotChange();\n }\n }\n\n disconnectedCallback(): void {\n if (this._slot && this._slotListener) {\n this._slot.removeEventListener('slotchange', this._slotListener);\n }\n this._slotListener = null;\n }\n\n /**\n * Evict a cached element by its cache key (`tagName` or `tagName:id`).\n * The evicted element is disconnected and removed from the cache.\n */\n clearCache(key?: CacheKey): void {\n if (key) {\n this._cache.delete(key);\n } else {\n this._cache.clear();\n }\n }\n\n private _handleSlotChange(): void {\n if (!this._slot) return;\n\n const slottedElements = this._slot.assignedElements({ flatten: true });\n\n for (const child of slottedElements) {\n const cacheKey = this._buildCacheKey(child);\n\n if (!this._cache.has(cacheKey)) {\n // New element — cache it so we can restore it later\n this._cache.set(cacheKey, child);\n } else {\n const cached = this._cache.get(cacheKey)!;\n if (cached !== child) {\n // A different instance appeared for the same slot.\n // Replace it with the cached instance to restore state.\n try {\n child.parentNode?.replaceChild(cached, child);\n } catch {\n // If replacement fails, update the cache with the new element\n this._cache.set(cacheKey, child);\n }\n }\n }\n }\n }\n\n private _buildCacheKey(el: Element): CacheKey {\n const tag = el.tagName.toLowerCase();\n const id = el.getAttribute('id');\n return id ? `${tag}:${id}` : tag;\n }\n };\n}\n","/**\n * Built-in utility components provided by the custom-elements runtime.\n *\n * These components are registered automatically when this module is imported.\n * They are designed to be minimal, tree-shakeable, and zero-dependency.\n *\n * Included components:\n * - `<cer-suspense>` — Shows a fallback while async work is pending\n * - `<cer-error-boundary>` — Catches render errors and shows a fallback UI\n * - `<cer-keep-alive>` — Preserves component state across DOM removal/re-insertion\n */\n\nimport { component } from './component';\nimport { html } from './template-compiler';\nimport { ref } from './reactive';\nimport { useProps, useOnError, useExpose } from './hooks';\nimport { registerKeepAlive } from '../keep-alive';\n\n// ── cer-suspense ──────────────────────────────────────────────────────────────\n\n/**\n * A built-in component that conditionally renders either the default slot\n * content or the `fallback` slot content, controlled by the `pending` prop.\n *\n * Use the `pending` attribute/property to signal that async work is in\n * progress; the component will swap to the `fallback` slot until `pending`\n * becomes falsy.\n *\n * @example\n * ```html\n * <cer-suspense pending>\n * <!-- shown when pending=false -->\n * <my-async-content></my-async-content>\n *\n * <!-- shown while pending=true -->\n * <div slot=\"fallback\">Loading…</div>\n * </cer-suspense>\n * ```\n *\n * @example Programmatic usage\n * ```ts\n * component('my-data-loader', () => {\n * const pending = ref(true);\n * useOnConnected(async () => {\n * await fetchData();\n * pending.value = false;\n * });\n * return html`\n * <cer-suspense pending=\"${pending.value}\">\n * <my-data-view></my-data-view>\n * <div slot=\"fallback\">Loading data…</div>\n * </cer-suspense>\n * `;\n * });\n * ```\n */\nexport function registerSuspense(): void {\n if (typeof customElements !== 'undefined' && customElements.get('cer-suspense')) return;\n\n component('cer-suspense', () => {\n const { pending } = useProps({ pending: false });\n\n return pending\n ? html`<slot name=\"fallback\"><span>Loading…</span></slot>`\n : html`<slot></slot>`;\n });\n}\n\n// ── cer-error-boundary ────────────────────────────────────────────────────────\n\n/**\n * A built-in component that catches errors thrown during child component\n * rendering and displays a fallback UI instead of crashing the page.\n *\n * Errors are caught via the `useOnError` lifecycle hook. Once an error is\n * caught the component switches to showing the `fallback` named slot (or a\n * default \"Something went wrong\" message if no fallback slot is provided).\n *\n * Call the custom `reset()` method on the element to clear the error and\n * attempt re-rendering the default slot.\n *\n * @example\n * ```html\n * <cer-error-boundary>\n * <my-risky-component></my-risky-component>\n *\n * <div slot=\"fallback\">\n * <p>Something went wrong. <button onclick=\"this.closest('cer-error-boundary').reset()\">Retry</button></p>\n * </div>\n * </cer-error-boundary>\n * ```\n */\nexport function registerErrorBoundary(): void {\n if (typeof customElements !== 'undefined' && customElements.get('cer-error-boundary')) return;\n\n component('cer-error-boundary', () => {\n const hasError = ref(false);\n const errorMessage = ref('');\n\n useOnError((err: Error) => {\n hasError.value = true;\n errorMessage.value = err.message;\n });\n\n // Expose a reset() method so parent templates can call\n // `errorBoundaryRef.value.reset()` to clear the error and retry.\n // Also expose an internal `_cerHandleChildError` receiver so that the\n // component runtime can propagate uncaught errors from slotted child\n // components up to the nearest ancestor <cer-error-boundary>.\n useExpose({\n _cerHandleChildError: (err: unknown) => {\n // Use peek() to read the current value without registering a reactive\n // dependency — the child component's render context may be active when\n // this handler runs, and we must not accidentally subscribe the child\n // to this boundary's internal state.\n if (!hasError.peek()) {\n hasError.value = true;\n errorMessage.value = err instanceof Error ? err.message : String(err);\n }\n },\n reset: () => {\n hasError.value = false;\n errorMessage.value = '';\n },\n });\n\n return hasError.value\n ? html`<slot name=\"fallback\"\n ><div role=\"alert\">\n <strong>Something went wrong.</strong>\n ${errorMessage.value ? html`<p>${errorMessage.value}</p>` : html``}\n </div></slot\n >`\n : html`<slot></slot>`;\n });\n}\n\n// ── Auto-register all components ─────────────────────────────────────────────\n\n/**\n * Register all built-in components (`cer-suspense`, `cer-error-boundary`,\n * `cer-keep-alive`).\n * Safe to call multiple times — each registration is guarded by a\n * `customElements.get()` check.\n */\nexport function registerBuiltinComponents(): void {\n registerSuspense();\n registerErrorBoundary();\n registerKeepAlive();\n}\n","/**\n * teleport.ts\n *\n * Renders virtual DOM content into an arbitrary DOM target located outside\n * the current component's Shadow Root. Useful for modals, tooltips, popovers,\n * and any UI that must visually escape the component boundary.\n *\n * @example\n * ```ts\n * import { component, html, ref, useOnDisconnected, useTeleport } from '@jasonshimmy/custom-elements-runtime';\n *\n * component('modal-trigger', () => {\n * const isOpen = ref(false);\n *\n * // Render modal content into <body> outside the shadow root\n * const { portal, destroy } = useTeleport('#modal-root');\n * useOnDisconnected(destroy);\n *\n * // Call portal() to update the teleported content on each render\n * if (isOpen.value) {\n * portal(html`<div class=\"modal\">\n * <h2>Hello</h2>\n * <button @click=\"${() => (isOpen.value = false)}\">Close</button>\n * </div>`);\n * } else {\n * portal(null);\n * }\n *\n * return html`\n * <button @click=\"${() => (isOpen.value = true)}\">Open modal</button>\n * `;\n * });\n * ```\n */\n\nimport type { VNode, VDomRefs } from './runtime/types';\nimport { vdomRenderer } from './runtime/vdom';\nimport { reactiveSystem } from './runtime/reactive';\nimport { getCurrentComponentContext, isDiscoveryRender } from './runtime/hooks';\n\n/** Handle returned by {@link useTeleport} for managing a portal. */\nexport interface TeleportHandle {\n /**\n * Render (or clear) content at the teleport target.\n * Pass `null` or `undefined` to remove previously rendered content.\n */\n portal(content: VNode | VNode[] | null | undefined): void;\n\n /**\n * Destroy the teleport container and clean up all rendered content.\n * Call this in `useOnDisconnected` to prevent memory leaks.\n */\n destroy(): void;\n}\n\n/**\n * Create a teleport portal that renders content outside the current Shadow Root.\n *\n * @param target - A CSS selector string or an `Element` reference to render into.\n * @returns A {@link TeleportHandle} with `portal()` (update content) and `destroy()` (cleanup).\n *\n * @example\n * ```ts\n * import { component, html, useOnDisconnected, useTeleport } from '@jasonshimmy/custom-elements-runtime';\n *\n * component('my-tooltip', () => {\n * const { portal, destroy } = useTeleport('body');\n * useOnDisconnected(destroy);\n *\n * portal(html`<div class=\"tooltip\">Tooltip content</div>`);\n * return html`<span>Hover me</span>`;\n * });\n * ```\n */\nexport function useTeleport(target: string | Element): TeleportHandle {\n // SSR guard\n if (typeof document === 'undefined') {\n return { portal: () => {}, destroy: () => {} };\n }\n\n // During discovery render the component is not yet mounted — return a no-op\n // handle so the library can detect props/hooks without side-effects.\n if (isDiscoveryRender()) {\n return { portal: () => {}, destroy: () => {} };\n }\n\n // If called inside a component render, use the reactive state-index slot\n // mechanism to ensure the same handle is returned on every re-render of the\n // same component instance. Without this, each re-render would create a new\n // <cer-teleport> container in the target, leaking all but the last one.\n const ctx = getCurrentComponentContext();\n if (ctx) {\n // getOrCreateState uses an incrementing stateIndex that is reset to 0 at\n // the start of each render, so the same call site always gets the same slot.\n const slot = reactiveSystem.getOrCreateState<TeleportHandle | null>(null);\n const existing = slot.peek();\n if (existing !== null) {\n return existing;\n }\n // First render: create the handle and store it without triggering a\n // reactive update (initSilent bypasses triggerUpdate).\n // Pass a slot-invalidation callback so that destroy() clears the slot,\n // allowing a reconnected component to create a fresh container.\n const handle = _createTeleportHandle(target, () => slot.initSilent(null));\n slot.initSilent(handle);\n return handle;\n }\n\n // Outside a component context (e.g. called directly in tests or scripts):\n // fall through to a non-cached, non-stable handle.\n return _createTeleportHandle(target);\n}\n\n/** Internal: create a fresh teleport handle pointing at `target`.\n * @param onDestroy - Optional callback invoked after cleanup in destroy(), used\n * to invalidate a cached slot so the next render creates a fresh handle.\n */\nfunction _createTeleportHandle(\n target: string | Element,\n onDestroy?: () => void,\n): TeleportHandle {\n const targetEl =\n typeof target === 'string'\n ? (document.querySelector(target) as Element | null)\n : target;\n\n if (!targetEl) {\n console.warn(\n `[useTeleport] Target \"${String(target)}\" not found in the document. ` +\n 'Teleported content will not be rendered.',\n );\n return { portal: () => {}, destroy: () => {} };\n }\n\n // Create a dedicated container so we never clobber sibling content.\n const container = document.createElement('cer-teleport');\n container.dataset.cerTeleport = '';\n targetEl.appendChild(container);\n\n // Shared refs bag — passed consistently so ref directives work across updates.\n const refs: VDomRefs = {};\n\n const handle: TeleportHandle = {\n portal(content: VNode | VNode[] | null | undefined): void {\n const nodes: VNode[] =\n content == null ? [] : Array.isArray(content) ? content : [content];\n // vdomRenderer stores _prevVNode/_prevDom on the root object for diffing.\n // Casting to ShadowRoot is safe: we only access properties that exist on\n // HTMLElement (firstChild, appendChild, replaceChild, childNodes).\n vdomRenderer(container as unknown as ShadowRoot, nodes, undefined, refs);\n },\n\n destroy(): void {\n // Render empty nodes to clean up event listeners and refs.\n try {\n vdomRenderer(container as unknown as ShadowRoot, [], undefined, refs);\n } catch {\n /* best-effort cleanup */\n }\n if (container.parentNode) {\n container.parentNode.removeChild(container);\n }\n // Invalidate the cached slot so that if the component reconnects and\n // re-renders, useTeleport() creates a fresh container rather than\n // reusing this destroyed one.\n onDestroy?.();\n },\n };\n\n return handle;\n}\n"],"mappings":";;;;;;AAiCA,SAAgB,EAAW,IAA2B,UAAgB;AAChE,QAAO,cAAgB,QAEzB,aAAgB,WAAW,EAAK,kBAAmB,GAC9C,cACL,IAAI,YAAY,eAAe;EAAE,SAAS;EAAM,UAAU;EAAM,CAAC,CAClE;;;;ACMH,IAAM,IAAmB,KACnB,IAAiB;AAEvB,SAAS,EACP,GACA,GACA,GACoC;AAQpC,QAPI,MAAe,oBACb,IAAQ,IAAY,KAAY,aAChC,IAAQ,IAAkB,YACvB,YAEL,IAAQ,IAAY,IAAU,aAC9B,IAAQ,IAAkB,YACvB;;AAGT,SAAS,EAAqB,GAAiD;CAC7E,IAAM,IAAgB,EAAE;AAyBxB,QAxBI,EAAQ,aAAa,WAAW,aAClC,EAAI,KACF,+EACD,EACC,EAAQ,mBAAmB,WAAW,aACxC,EAAI,KACF,gFACD,EACC,EAAQ,iBAAiB,WAAW,aACtC,EAAI,KACF,2EACD,EACC,EAAQ,oBAAoB,WAAW,aACzC,EAAI,KACF,iFACD,EACC,EAAQ,sBAAsB,WAAW,aAC3C,EAAI,KACF,2EACD,EACC,EAAQ,qBAAqB,WAAW,aAC1C,EAAI,KACF,0FACD,EACI;;AAOT,SAAgB,IAA6C;CAC3D,IAAM,oBAAa,IAAI,KAA2B,EAC5C,oBAAY,IAAI,KAAqC,EACvD,IAAoD;CAExD,SAAS,EAAU,GAAc,GAAe,GAAyB;AACvE,IAAW,IAAI,GAAM;GACnB;GACA;GACA;GACA,QAAQ;GACR,aAAa,KAAK,KAAK;GACvB,SAAS,EAAE;GACZ,CAAC;;CAGJ,SAAS,IAA0B;AAWjC,EAVA,EAAU,oBAAoB,GAAG,IAAK,EACtC,EAAU,uBAAuB,G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AS,cAAc,eAAe;AAExD,CADA,EAAU,QAAQ,cAAc,IAChC,EAAS,YAAY,EAAU;CAG/B,IAAM,IAAiB,EAAE;AA6BzB,QA3B+B;EAC7B,OAAO,GAAmD;AAMxD,KAAa,GAJX,KAAW,OAAO,EAAE,GAAG,MAAM,QAAQ,EAAQ,GAAG,IAAU,CAAC,EAAQ,EAIb,KAAA,GAAW,EAAK;;EAG1E,UAAgB;AAEd,OAAI;AACF,MAAa,GAAoC,EAAE,EAAE,KAAA,GAAW,EAAK;WAC/D;AASR,GANI,EAAU,cACZ,EAAU,WAAW,YAAY,EAAU,EAK7C,KAAa;;EAEhB"}
@@ -1,3 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const a=require("./logger-BYIN7ysT.cjs");var l=class o extends EventTarget{handlers={};static instance;eventCounters=new Map;nativeUnsubscribers=new Map;MAX_EVENT_COUNTERS=1e3;static getInstance(){return o.instance||(o.instance=new o),o.instance}emit(e,t){const n=Date.now(),s=this.eventCounters.get(e);if(!s||n-s.window>1e3){if(!s&&this.eventCounters.size>=this.MAX_EVENT_COUNTERS){const c=this.eventCounters.keys().next().value;c!==void 0&&this.eventCounters.delete(c)}this.eventCounters.set(e,{count:1,window:n})}else if(s.count++,s.count===51&&a.devError(`[EventBus] Event "${e}" is firing too frequently (>${s.count-1}/s). Emissions above 50/s are throttled and above 100/s are dropped to prevent event storms. Consider debouncing the emitter.`),s.count>100)return;this.dispatchEvent(new CustomEvent(e,{detail:t,bubbles:!1,cancelable:!0}));const u=this.handlers[e];u&&u.forEach(c=>{try{c(t)}catch(h){a.devError(`Error in global event handler for "${e}":`,h)}})}on(e,t){return this.handlers[e]||(this.handlers[e]=new Set),this.handlers[e].add(t),()=>this.off(e,t)}off(e,t){const n=this.handlers[e];n&&(n.delete(t),n.size===0&&delete this.handlers[e])}offAll(e){delete this.handlers[e]}listen(e,t,n){this.addEventListener(e,t,n);const s=()=>{this.removeEventListener(e,t),this.nativeUnsubscribers.delete(s)};return this.nativeUnsubscribers.set(s,!0),s}once(e,t){if(t!==void 0){const n=this.on(e,s=>{n(),t(s)})}else return new Promise(n=>{const s=this.on(e,u=>{s(),n(u)})})}getActiveEvents(){return Object.keys(this.handlers).filter(e=>this.handlers[e]&&this.handlers[e].size>0)}clear(){this.handlers={};const e=Array.from(this.nativeUnsubscribers.keys());this.nativeUnsubscribers.clear();for(const t of e)t()}getHandlerCount(e){return this.handlers[e]?.size||0}getEventStats(){const e={};for(const[t,n]of this.eventCounters.entries())e[t]={count:n.count,handlersCount:this.getHandlerCount(t)};return e}resetEventCounters(){this.eventCounters.clear()}},i=new Proxy({},{get(r,e){const t=l.getInstance(),n=t[e];return typeof n=="function"?n.bind(t):n},apply(){throw new TypeError("eventBus is not a callable function")}}),d=(r,e)=>i.emit(r,e),f=(r,e)=>i.on(r,e),v=(r,e)=>i.off(r,e);function b(r,e){return e!==void 0?i.once(r,e):i.once(r)}var E=(r,e,t)=>i.listen(r,e,t);exports.GlobalEventBus=l;exports.emit=d;exports.eventBus=i;exports.listen=E;exports.off=v;exports.on=f;exports.once=b;
2
-
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./logger-Dkht1dCX.cjs`);var t=class t extends EventTarget{handlers={};static instance;eventCounters=new Map;nativeUnsubscribers=new Map;MAX_EVENT_COUNTERS=1e3;static getInstance(){return t.instance||=new t,t.instance}emit(t,n){let r=Date.now(),i=this.eventCounters.get(t);if(!i||r-i.window>1e3){if(!i&&this.eventCounters.size>=this.MAX_EVENT_COUNTERS){let e=this.eventCounters.keys().next().value;e!==void 0&&this.eventCounters.delete(e)}this.eventCounters.set(t,{count:1,window:r})}else if(i.count++,i.count===51&&e.t(`[EventBus] Event "${t}" is firing too frequently (>${i.count-1}/s). Emissions above 50/s are throttled and above 100/s are dropped to prevent event storms. Consider debouncing the emitter.`),i.count>100)return;this.dispatchEvent(new CustomEvent(t,{detail:n,bubbles:!1,cancelable:!0}));let a=this.handlers[t];a&&a.forEach(r=>{try{r(n)}catch(n){e.t(`Error in global event handler for "${t}":`,n)}})}on(e,t){return this.handlers[e]||(this.handlers[e]=new Set),this.handlers[e].add(t),()=>this.off(e,t)}off(e,t){let n=this.handlers[e];n&&(n.delete(t),n.size===0&&delete this.handlers[e])}offAll(e){delete this.handlers[e]}listen(e,t,n){this.addEventListener(e,t,n);let r=()=>{this.removeEventListener(e,t),this.nativeUnsubscribers.delete(r)};return this.nativeUnsubscribers.set(r,!0),r}once(e,t){if(t!==void 0){let n=this.on(e,e=>{n(),t(e)})}else return new Promise(t=>{let n=this.on(e,e=>{n(),t(e)})})}getActiveEvents(){return Object.keys(this.handlers).filter(e=>this.handlers[e]&&this.handlers[e].size>0)}clear(){this.handlers={};let e=Array.from(this.nativeUnsubscribers.keys());this.nativeUnsubscribers.clear();for(let t of e)t()}getHandlerCount(e){return this.handlers[e]?.size||0}getEventStats(){let e={};for(let[t,n]of this.eventCounters.entries())e[t]={count:n.count,handlersCount:this.getHandlerCount(t)};return e}resetEventCounters(){this.eventCounters.clear()}},n=new Proxy({},{get(e,n){let r=t.getInstance(),i=r[n];return typeof i==`function`?i.bind(r):i},apply(){throw TypeError(`eventBus is not a callable function`)}}),r=(e,t)=>n.emit(e,t),i=(e,t)=>n.on(e,t),a=(e,t)=>n.off(e,t);function o(e,t){return t===void 0?n.once(e):n.once(e,t)}var s=(e,t,r)=>n.listen(e,t,r);exports.GlobalEventBus=t,exports.emit=r,exports.eventBus=n,exports.listen=s,exports.off=a,exports.on=i,exports.once=o;
3
2
  //# sourceMappingURL=custom-elements-runtime.event-bus.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"custom-elements-runtime.event-bus.cjs.js","names":[],"sources":["../src/lib/event-bus.ts"],"sourcesContent":["/**\n * Event handler type for global event bus\n */\nexport type EventHandler<T> = (data: T) => void;\n\nimport { devError } from './runtime/logger';\n\n/**\n * Event map type using Set for efficient handler management\n */\ntype EventMap<Events extends Record<string, unknown>> = {\n [K in keyof Events]: Set<EventHandler<Events[K]>>;\n};\n\n/**\n * GlobalEventBus provides a singleton event bus for cross-component communication.\n * Uses Set for handler storage to optimize add/remove operations and prevent duplicates.\n */\nexport class GlobalEventBus extends EventTarget {\n private handlers: EventMap<Record<string, unknown>> = {};\n private static instance: GlobalEventBus;\n private eventCounters: Map<string, { count: number; window: number }> =\n new Map();\n private nativeUnsubscribers: Map<() => void, true> = new Map();\n private readonly MAX_EVENT_COUNTERS = 1000;\n\n /**\n * Returns the singleton instance of GlobalEventBus\n */\n static getInstance(): GlobalEventBus {\n if (!GlobalEventBus.instance) {\n GlobalEventBus.instance = new GlobalEventBus();\n }\n return GlobalEventBus.instance;\n }\n\n /**\n * Emit a global event with optional data. Includes event storm protection.\n * @param eventName - Name of the event\n * @param data - Optional event payload\n */\n emit<T = unknown>(eventName: string, data?: T): void {\n // Event storm protection\n const now = Date.now();\n const counter = this.eventCounters.get(eventName);\n\n if (!counter || now - counter.window > 1000) {\n // Evict oldest entry if the map is at capacity to prevent unbounded growth.\n if (!counter && this.eventCounters.size >= this.MAX_EVENT_COUNTERS) {\n const firstKey = this.eventCounters.keys().next().value;\n if (firstKey !== undefined) this.eventCounters.delete(firstKey);\n }\n // Reset counter every second\n this.eventCounters.set(eventName, { count: 1, window: now });\n } else {\n counter.count++;\n\n if (counter.count === 51) {\n // Warn once at the throttle threshold so developers know emissions are being dropped.\n devError(\n `[EventBus] Event \"${eventName}\" is firing too frequently (>${counter.count - 1}/s). ` +\n 'Emissions above 50/s are throttled and above 100/s are dropped to prevent event storms. ' +\n 'Consider debouncing the emitter.',\n );\n }\n if (counter.count > 100) {\n // Drop the event to protect against runaway event storms.\n return;\n }\n }\n\n // Use native CustomEvent for better browser integration\n this.dispatchEvent(\n new CustomEvent(eventName, {\n detail: data,\n bubbles: false, // Global events don't need to bubble\n cancelable: true,\n }),\n );\n\n // Also trigger registered handlers\n const eventHandlers = this.handlers[eventName];\n if (eventHandlers) {\n eventHandlers.forEach((handler) => {\n try {\n handler(data);\n } catch (error) {\n devError(`Error in global event handler for \"${eventName}\":`, error);\n }\n });\n }\n }\n\n /**\n * Register a handler for a global event. Returns an unsubscribe function.\n * @param eventName - Name of the event\n * @param handler - Handler function\n */\n on<T = unknown>(eventName: string, handler: EventHandler<T>): () => void {\n if (!this.handlers[eventName]) {\n this.handlers[eventName] = new Set<EventHandler<unknown>>();\n }\n this.handlers[eventName].add(handler as EventHandler<unknown>);\n return () => this.off(eventName, handler);\n }\n\n /**\n * Remove a specific handler for a global event.\n * @param eventName - Name of the event\n * @param handler - Handler function to remove\n */\n off<T = unknown>(eventName: string, handler: EventHandler<T>): void {\n const eventHandlers = this.handlers[eventName];\n if (eventHandlers) {\n eventHandlers.delete(handler as EventHandler<unknown>);\n // Remove the entry entirely once it is empty so stale keys don't\n // accumulate indefinitely in long-lived apps.\n if (eventHandlers.size === 0) {\n delete this.handlers[eventName];\n }\n }\n }\n\n /**\n * Remove all handlers for a specific event.\n * @param eventName - Name of the event\n */\n offAll(eventName: string): void {\n delete this.handlers[eventName];\n }\n\n /**\n * Listen for a native CustomEvent. Returns an unsubscribe function.\n * @param eventName - Name of the event\n * @param handler - CustomEvent handler\n * @param options - AddEventListener options\n */\n listen<T = unknown>(\n eventName: string,\n handler: (event: CustomEvent<T>) => void,\n options?: AddEventListenerOptions,\n ): () => void {\n this.addEventListener(eventName, handler as EventListener, options);\n // Use a wrapper so calling unsubscribe also removes it from nativeUnsubscribers,\n // preventing indefinite accumulation in long-lived apps.\n const unsubscribe: () => void = () => {\n this.removeEventListener(eventName, handler as EventListener);\n this.nativeUnsubscribers.delete(unsubscribe);\n };\n this.nativeUnsubscribers.set(unsubscribe, true);\n return unsubscribe;\n }\n\n /**\n * Register a one-time event handler (callback form).\n * The handler is invoked exactly once, then automatically unsubscribed.\n * @param eventName - Name of the event\n * @param handler - Handler function\n */\n once<T = unknown>(eventName: string, handler: EventHandler<T>): void;\n /**\n * Returns a Promise that resolves with the first emission of the event\n * (Promise form — no handler argument).\n * @param eventName - Name of the event\n */\n once<T = unknown>(eventName: string): Promise<T>;\n once<T = unknown>(\n eventName: string,\n handler?: EventHandler<T>,\n ): void | Promise<T> {\n if (handler !== undefined) {\n // Callback form: fire-and-forget, returns void\n const unsubscribe = this.on(eventName, (data: T) => {\n unsubscribe();\n handler(data);\n });\n } else {\n // Promise form: resolves on first emission\n return new Promise<T>((resolve) => {\n const unsubscribe = this.on(eventName, (data: T) => {\n unsubscribe();\n resolve(data);\n });\n });\n }\n }\n\n /**\n * Get a list of all active event names with registered handlers.\n */\n getActiveEvents(): string[] {\n return Object.keys(this.handlers).filter(\n (eventName) =>\n this.handlers[eventName] && this.handlers[eventName].size > 0,\n );\n }\n\n /**\n * Clear all event handlers and native EventTarget listeners (useful for testing or cleanup).\n */\n clear(): void {\n this.handlers = {};\n const toCleanup = Array.from(this.nativeUnsubscribers.keys());\n this.nativeUnsubscribers.clear();\n for (const unsubscribe of toCleanup) {\n unsubscribe();\n }\n }\n\n /**\n * Get the number of handlers registered for a specific event.\n * @param eventName - Name of the event\n */\n getHandlerCount(eventName: string): number {\n return this.handlers[eventName]?.size || 0;\n }\n\n /**\n * Get event statistics for debugging.\n */\n getEventStats(): Record<string, { count: number; handlersCount: number }> {\n const stats: Record<string, { count: number; handlersCount: number }> = {};\n for (const [eventName, counter] of this.eventCounters.entries()) {\n stats[eventName] = {\n count: counter.count,\n handlersCount: this.getHandlerCount(eventName),\n };\n }\n return stats;\n }\n\n /**\n * Reset event counters (useful for testing or after resolving issues).\n */\n resetEventCounters(): void {\n this.eventCounters.clear();\n }\n}\n\n/**\n * Singleton instance of the global event bus\n */\n/**\n * Lazily-instantiated event bus.\n *\n * We preserve the `eventBus` export for backward compatibility but avoid\n * creating the underlying GlobalEventBus instance at module import time.\n * A small proxy defers the call to `GlobalEventBus.getInstance()` until a\n * property is accessed. This reduces import-time side-effects and helps\n * bundlers tree-shake unused entrypoints.\n */\nexport const eventBus = new Proxy(\n {},\n {\n get(_target, prop: PropertyKey) {\n const inst = GlobalEventBus.getInstance();\n const val = (inst as unknown as Record<PropertyKey, unknown>)[prop];\n // If the property is a function (method), bind it to the instance\n // so callers using `eventBus.method(...)` get the correct `this`.\n if (typeof val === 'function')\n return (val as (...args: unknown[]) => unknown).bind(inst);\n return val;\n },\n apply() {\n throw new TypeError('eventBus is not a callable function');\n },\n },\n) as unknown as GlobalEventBus;\n\n/**\n * Emit a global event\n */\nexport const emit = <T = unknown>(eventName: string, data?: T) =>\n eventBus.emit(eventName, data);\n\n/**\n * Register a handler for a global event\n */\nexport const on = <T = unknown>(eventName: string, handler: EventHandler<T>) =>\n eventBus.on(eventName, handler);\n\n/**\n * Remove a handler for a global event\n */\nexport const off = <T = unknown>(eventName: string, handler: EventHandler<T>) =>\n eventBus.off(eventName, handler);\n\n/**\n * Register a one-time handler for a global event (callback form).\n * The handler fires once then auto-unsubscribes.\n */\nexport function once<T = unknown>(\n eventName: string,\n handler: EventHandler<T>,\n): void;\n/**\n * Returns a Promise that resolves with the next emission of the event\n * (Promise form — no handler argument needed).\n */\nexport function once<T = unknown>(eventName: string): Promise<T>;\nexport function once<T = unknown>(\n eventName: string,\n handler?: EventHandler<T>,\n): void | Promise<T> {\n if (handler !== undefined) {\n return eventBus.once(eventName, handler);\n }\n return eventBus.once<T>(eventName);\n}\n\n/**\n * Listen for a native CustomEvent\n */\nexport const listen = <T = unknown>(\n eventName: string,\n handler: (event: CustomEvent<T>) => void,\n options?: AddEventListenerOptions,\n) => eventBus.listen(eventName, handler, options);\n"],"mappings":"4GAkBA,IAAa,EAAb,MAAa,UAAuB,WAAY,CAC9C,SAAsD,CAAA,EACtD,OAAe,SACf,cACE,IAAI,IACN,oBAAqD,IAAI,IACzD,mBAAsC,IAKtC,OAAO,aAA8B,CACnC,OAAK,EAAe,WAClB,EAAe,SAAW,IAAI,GAEzB,EAAe,SAQxB,KAAkB,EAAmB,EAAgB,CAEnD,MAAM,EAAM,KAAK,IAAA,EACX,EAAU,KAAK,cAAc,IAAI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EAAW,CAAA,EAE3B,EAAS,KAAQ,CAAA,EAM1B,IAAa,EAAA,CACX,EACA,EACA,IACG,EAAS,OAAO,EAAW,EAAS,CAAA"}
1
+ {"version":3,"file":"custom-elements-runtime.event-bus.cjs.js","names":[],"sources":["../src/lib/event-bus.ts"],"sourcesContent":["/**\n * Event handler type for global event bus\n */\nexport type EventHandler<T> = (data: T) => void;\n\nimport { devError } from './runtime/logger';\n\n/**\n * Event map type using Set for efficient handler management\n */\ntype EventMap<Events extends Record<string, unknown>> = {\n [K in keyof Events]: Set<EventHandler<Events[K]>>;\n};\n\n/**\n * GlobalEventBus provides a singleton event bus for cross-component communication.\n * Uses Set for handler storage to optimize add/remove operations and prevent duplicates.\n */\nexport class GlobalEventBus extends EventTarget {\n private handlers: EventMap<Record<string, unknown>> = {};\n private static instance: GlobalEventBus;\n private eventCounters: Map<string, { count: number; window: number }> =\n new Map();\n private nativeUnsubscribers: Map<() => void, true> = new Map();\n private readonly MAX_EVENT_COUNTERS = 1000;\n\n /**\n * Returns the singleton instance of GlobalEventBus\n */\n static getInstance(): GlobalEventBus {\n if (!GlobalEventBus.instance) {\n GlobalEventBus.instance = new GlobalEventBus();\n }\n return GlobalEventBus.instance;\n }\n\n /**\n * Emit a global event with optional data. Includes event storm protection.\n * @param eventName - Name of the event\n * @param data - Optional event payload\n */\n emit<T = unknown>(eventName: string, data?: T): void {\n // Event storm protection\n const now = Date.now();\n const counter = this.eventCounters.get(eventName);\n\n if (!counter || now - counter.window > 1000) {\n // Evict oldest entry if the map is at capacity to prevent unbounded growth.\n if (!counter && this.eventCounters.size >= this.MAX_EVENT_COUNTERS) {\n const firstKey = this.eventCounters.keys().next().value;\n if (firstKey !== undefined) this.eventCounters.delete(firstKey);\n }\n // Reset counter every second\n this.eventCounters.set(eventName, { count: 1, window: now });\n } else {\n counter.count++;\n\n if (counter.count === 51) {\n // Warn once at the throttle threshold so developers know emissions are being dropped.\n devError(\n `[EventBus] Event \"${eventName}\" is firing too frequently (>${counter.count - 1}/s). ` +\n 'Emissions above 50/s are throttled and above 100/s are dropped to prevent event storms. ' +\n 'Consider debouncing the emitter.',\n );\n }\n if (counter.count > 100) {\n // Drop the event to protect against runaway event storms.\n return;\n }\n }\n\n // Use native CustomEvent for better browser integration\n this.dispatchEvent(\n new CustomEvent(eventName, {\n detail: data,\n bubbles: false, // Global events don't need to bubble\n cancelable: true,\n }),\n );\n\n // Also trigger registered handlers\n const eventHandlers = this.handlers[eventName];\n if (eventHandlers) {\n eventHandlers.forEach((handler) => {\n try {\n handler(data);\n } catch (error) {\n devError(`Error in global event handler for \"${eventName}\":`, error);\n }\n });\n }\n }\n\n /**\n * Register a handler for a global event. Returns an unsubscribe function.\n * @param eventName - Name of the event\n * @param handler - Handler function\n */\n on<T = unknown>(eventName: string, handler: EventHandler<T>): () => void {\n if (!this.handlers[eventName]) {\n this.handlers[eventName] = new Set<EventHandler<unknown>>();\n }\n this.handlers[eventName].add(handler as EventHandler<unknown>);\n return () => this.off(eventName, handler);\n }\n\n /**\n * Remove a specific handler for a global event.\n * @param eventName - Name of the event\n * @param handler - Handler function to remove\n */\n off<T = unknown>(eventName: string, handler: EventHandler<T>): void {\n const eventHandlers = this.handlers[eventName];\n if (eventHandlers) {\n eventHandlers.delete(handler as EventHandler<unknown>);\n // Remove the entry entirely once it is empty so stale keys don't\n // accumulate indefinitely in long-lived apps.\n if (eventHandlers.size === 0) {\n delete this.handlers[eventName];\n }\n }\n }\n\n /**\n * Remove all handlers for a specific event.\n * @param eventName - Name of the event\n */\n offAll(eventName: string): void {\n delete this.handlers[eventName];\n }\n\n /**\n * Listen for a native CustomEvent. Returns an unsubscribe function.\n * @param eventName - Name of the event\n * @param handler - CustomEvent handler\n * @param options - AddEventListener options\n */\n listen<T = unknown>(\n eventName: string,\n handler: (event: CustomEvent<T>) => void,\n options?: AddEventListenerOptions,\n ): () => void {\n this.addEventListener(eventName, handler as EventListener, options);\n // Use a wrapper so calling unsubscribe also removes it from nativeUnsubscribers,\n // preventing indefinite accumulation in long-lived apps.\n const unsubscribe: () => void = () => {\n this.removeEventListener(eventName, handler as EventListener);\n this.nativeUnsubscribers.delete(unsubscribe);\n };\n this.nativeUnsubscribers.set(unsubscribe, true);\n return unsubscribe;\n }\n\n /**\n * Register a one-time event handler (callback form).\n * The handler is invoked exactly once, then automatically unsubscribed.\n * @param eventName - Name of the event\n * @param handler - Handler function\n */\n once<T = unknown>(eventName: string, handler: EventHandler<T>): void;\n /**\n * Returns a Promise that resolves with the first emission of the event\n * (Promise form — no handler argument).\n * @param eventName - Name of the event\n */\n once<T = unknown>(eventName: string): Promise<T>;\n once<T = unknown>(\n eventName: string,\n handler?: EventHandler<T>,\n ): void | Promise<T> {\n if (handler !== undefined) {\n // Callback form: fire-and-forget, returns void\n const unsubscribe = this.on(eventName, (data: T) => {\n unsubscribe();\n handler(data);\n });\n } else {\n // Promise form: resolves on first emission\n return new Promise<T>((resolve) => {\n const unsubscribe = this.on(eventName, (data: T) => {\n unsubscribe();\n resolve(data);\n });\n });\n }\n }\n\n /**\n * Get a list of all active event names with registered handlers.\n */\n getActiveEvents(): string[] {\n return Object.keys(this.handlers).filter(\n (eventName) =>\n this.handlers[eventName] && this.handlers[eventName].size > 0,\n );\n }\n\n /**\n * Clear all event handlers and native EventTarget listeners (useful for testing or cleanup).\n */\n clear(): void {\n this.handlers = {};\n const toCleanup = Array.from(this.nativeUnsubscribers.keys());\n this.nativeUnsubscribers.clear();\n for (const unsubscribe of toCleanup) {\n unsubscribe();\n }\n }\n\n /**\n * Get the number of handlers registered for a specific event.\n * @param eventName - Name of the event\n */\n getHandlerCount(eventName: string): number {\n return this.handlers[eventName]?.size || 0;\n }\n\n /**\n * Get event statistics for debugging.\n */\n getEventStats(): Record<string, { count: number; handlersCount: number }> {\n const stats: Record<string, { count: number; handlersCount: number }> = {};\n for (const [eventName, counter] of this.eventCounters.entries()) {\n stats[eventName] = {\n count: counter.count,\n handlersCount: this.getHandlerCount(eventName),\n };\n }\n return stats;\n }\n\n /**\n * Reset event counters (useful for testing or after resolving issues).\n */\n resetEventCounters(): void {\n this.eventCounters.clear();\n }\n}\n\n/**\n * Singleton instance of the global event bus\n */\n/**\n * Lazily-instantiated event bus.\n *\n * We preserve the `eventBus` export for backward compatibility but avoid\n * creating the underlying GlobalEventBus instance at module import time.\n * A small proxy defers the call to `GlobalEventBus.getInstance()` until a\n * property is accessed. This reduces import-time side-effects and helps\n * bundlers tree-shake unused entrypoints.\n */\nexport const eventBus = new Proxy(\n {},\n {\n get(_target, prop: PropertyKey) {\n const inst = GlobalEventBus.getInstance();\n const val = (inst as unknown as Record<PropertyKey, unknown>)[prop];\n // If the property is a function (method), bind it to the instance\n // so callers using `eventBus.method(...)` get the correct `this`.\n if (typeof val === 'function')\n return (val as (...args: unknown[]) => unknown).bind(inst);\n return val;\n },\n apply() {\n throw new TypeError('eventBus is not a callable function');\n },\n },\n) as unknown as GlobalEventBus;\n\n/**\n * Emit a global event\n */\nexport const emit = <T = unknown>(eventName: string, data?: T) =>\n eventBus.emit(eventName, data);\n\n/**\n * Register a handler for a global event\n */\nexport const on = <T = unknown>(eventName: string, handler: EventHandler<T>) =>\n eventBus.on(eventName, handler);\n\n/**\n * Remove a handler for a global event\n */\nexport const off = <T = unknown>(eventName: string, handler: EventHandler<T>) =>\n eventBus.off(eventName, handler);\n\n/**\n * Register a one-time handler for a global event (callback form).\n * The handler fires once then auto-unsubscribes.\n */\nexport function once<T = unknown>(\n eventName: string,\n handler: EventHandler<T>,\n): void;\n/**\n * Returns a Promise that resolves with the next emission of the event\n * (Promise form — no handler argument needed).\n */\nexport function once<T = unknown>(eventName: string): Promise<T>;\nexport function once<T = unknown>(\n eventName: string,\n handler?: EventHandler<T>,\n): void | Promise<T> {\n if (handler !== undefined) {\n return eventBus.once(eventName, handler);\n }\n return eventBus.once<T>(eventName);\n}\n\n/**\n * Listen for a native CustomEvent\n */\nexport const listen = <T = unknown>(\n eventName: string,\n handler: (event: CustomEvent<T>) => void,\n options?: Add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T,EAAwC,KAAK,EAAK,CACrD,GAET,OAAQ,CACN,MAAU,UAAU,sCAAsC,EAE7D,CACF,CAKY,GAAqB,EAAmB,IACnD,EAAS,KAAK,EAAW,EAAK,CAKnB,GAAmB,EAAmB,IACjD,EAAS,GAAG,EAAW,EAAQ,CAKpB,GAAoB,EAAmB,IAClD,EAAS,IAAI,EAAW,EAAQ,CAelC,SAAgB,EACd,EACA,EACmB,CAInB,OAHI,IAAY,IAAA,GAGT,EAAS,KAAQ,EAAU,CAFzB,EAAS,KAAK,EAAW,EAAQ,CAQ5C,IAAa,GACX,EACA,EACA,IACG,EAAS,OAAO,EAAW,EAAS,EAAQ"}
@@ -1,111 +1,105 @@
1
- import { t as a } from "./logger-L25axmB-.js";
2
- var h = class o extends EventTarget {
3
- handlers = {};
4
- static instance;
5
- eventCounters = /* @__PURE__ */ new Map();
6
- nativeUnsubscribers = /* @__PURE__ */ new Map();
7
- MAX_EVENT_COUNTERS = 1e3;
8
- static getInstance() {
9
- return o.instance || (o.instance = new o()), o.instance;
10
- }
11
- emit(t, e) {
12
- const n = Date.now(), s = this.eventCounters.get(t);
13
- if (!s || n - s.window > 1e3) {
14
- if (!s && this.eventCounters.size >= this.MAX_EVENT_COUNTERS) {
15
- const c = this.eventCounters.keys().next().value;
16
- c !== void 0 && this.eventCounters.delete(c);
17
- }
18
- this.eventCounters.set(t, {
19
- count: 1,
20
- window: n
21
- });
22
- } else if (s.count++, s.count === 51 && a(`[EventBus] Event "${t}" is firing too frequently (>${s.count - 1}/s). Emissions above 50/s are throttled and above 100/s are dropped to prevent event storms. Consider debouncing the emitter.`), s.count > 100) return;
23
- this.dispatchEvent(new CustomEvent(t, {
24
- detail: e,
25
- bubbles: !1,
26
- cancelable: !0
27
- }));
28
- const u = this.handlers[t];
29
- u && u.forEach((c) => {
30
- try {
31
- c(e);
32
- } catch (l) {
33
- a(`Error in global event handler for "${t}":`, l);
34
- }
35
- });
36
- }
37
- on(t, e) {
38
- return this.handlers[t] || (this.handlers[t] = /* @__PURE__ */ new Set()), this.handlers[t].add(e), () => this.off(t, e);
39
- }
40
- off(t, e) {
41
- const n = this.handlers[t];
42
- n && (n.delete(e), n.size === 0 && delete this.handlers[t]);
43
- }
44
- offAll(t) {
45
- delete this.handlers[t];
46
- }
47
- listen(t, e, n) {
48
- this.addEventListener(t, e, n);
49
- const s = () => {
50
- this.removeEventListener(t, e), this.nativeUnsubscribers.delete(s);
51
- };
52
- return this.nativeUnsubscribers.set(s, !0), s;
53
- }
54
- once(t, e) {
55
- if (e !== void 0) {
56
- const n = this.on(t, (s) => {
57
- n(), e(s);
58
- });
59
- } else return new Promise((n) => {
60
- const s = this.on(t, (u) => {
61
- s(), n(u);
62
- });
63
- });
64
- }
65
- getActiveEvents() {
66
- return Object.keys(this.handlers).filter((t) => this.handlers[t] && this.handlers[t].size > 0);
67
- }
68
- clear() {
69
- this.handlers = {};
70
- const t = Array.from(this.nativeUnsubscribers.keys());
71
- this.nativeUnsubscribers.clear();
72
- for (const e of t) e();
73
- }
74
- getHandlerCount(t) {
75
- return this.handlers[t]?.size || 0;
76
- }
77
- getEventStats() {
78
- const t = {};
79
- for (const [e, n] of this.eventCounters.entries()) t[e] = {
80
- count: n.count,
81
- handlersCount: this.getHandlerCount(e)
82
- };
83
- return t;
84
- }
85
- resetEventCounters() {
86
- this.eventCounters.clear();
87
- }
88
- }, i = new Proxy({}, {
89
- get(r, t) {
90
- const e = h.getInstance(), n = e[t];
91
- return typeof n == "function" ? n.bind(e) : n;
92
- },
93
- apply() {
94
- throw new TypeError("eventBus is not a callable function");
95
- }
96
- }), d = (r, t) => i.emit(r, t), v = (r, t) => i.on(r, t), b = (r, t) => i.off(r, t);
97
- function E(r, t) {
98
- return t !== void 0 ? i.once(r, t) : i.once(r);
1
+ import { t as e } from "./logger-DIJ0UH3R.js";
2
+ //#region src/lib/event-bus.ts
3
+ var t = class t extends EventTarget {
4
+ handlers = {};
5
+ static instance;
6
+ eventCounters = /* @__PURE__ */ new Map();
7
+ nativeUnsubscribers = /* @__PURE__ */ new Map();
8
+ MAX_EVENT_COUNTERS = 1e3;
9
+ static getInstance() {
10
+ return t.instance ||= new t(), t.instance;
11
+ }
12
+ emit(t, n) {
13
+ let r = Date.now(), i = this.eventCounters.get(t);
14
+ if (!i || r - i.window > 1e3) {
15
+ if (!i && this.eventCounters.size >= this.MAX_EVENT_COUNTERS) {
16
+ let e = this.eventCounters.keys().next().value;
17
+ e !== void 0 && this.eventCounters.delete(e);
18
+ }
19
+ this.eventCounters.set(t, {
20
+ count: 1,
21
+ window: r
22
+ });
23
+ } else if (i.count++, i.count === 51 && e(`[EventBus] Event "${t}" is firing too frequently (>${i.count - 1}/s). Emissions above 50/s are throttled and above 100/s are dropped to prevent event storms. Consider debouncing the emitter.`), i.count > 100) return;
24
+ this.dispatchEvent(new CustomEvent(t, {
25
+ detail: n,
26
+ bubbles: !1,
27
+ cancelable: !0
28
+ }));
29
+ let a = this.handlers[t];
30
+ a && a.forEach((r) => {
31
+ try {
32
+ r(n);
33
+ } catch (n) {
34
+ e(`Error in global event handler for "${t}":`, n);
35
+ }
36
+ });
37
+ }
38
+ on(e, t) {
39
+ return this.handlers[e] || (this.handlers[e] = /* @__PURE__ */ new Set()), this.handlers[e].add(t), () => this.off(e, t);
40
+ }
41
+ off(e, t) {
42
+ let n = this.handlers[e];
43
+ n && (n.delete(t), n.size === 0 && delete this.handlers[e]);
44
+ }
45
+ offAll(e) {
46
+ delete this.handlers[e];
47
+ }
48
+ listen(e, t, n) {
49
+ this.addEventListener(e, t, n);
50
+ let r = () => {
51
+ this.removeEventListener(e, t), this.nativeUnsubscribers.delete(r);
52
+ };
53
+ return this.nativeUnsubscribers.set(r, !0), r;
54
+ }
55
+ once(e, t) {
56
+ if (t !== void 0) {
57
+ let n = this.on(e, (e) => {
58
+ n(), t(e);
59
+ });
60
+ } else return new Promise((t) => {
61
+ let n = this.on(e, (e) => {
62
+ n(), t(e);
63
+ });
64
+ });
65
+ }
66
+ getActiveEvents() {
67
+ return Object.keys(this.handlers).filter((e) => this.handlers[e] && this.handlers[e].size > 0);
68
+ }
69
+ clear() {
70
+ this.handlers = {};
71
+ let e = Array.from(this.nativeUnsubscribers.keys());
72
+ this.nativeUnsubscribers.clear();
73
+ for (let t of e) t();
74
+ }
75
+ getHandlerCount(e) {
76
+ return this.handlers[e]?.size || 0;
77
+ }
78
+ getEventStats() {
79
+ let e = {};
80
+ for (let [t, n] of this.eventCounters.entries()) e[t] = {
81
+ count: n.count,
82
+ handlersCount: this.getHandlerCount(t)
83
+ };
84
+ return e;
85
+ }
86
+ resetEventCounters() {
87
+ this.eventCounters.clear();
88
+ }
89
+ }, n = new Proxy({}, {
90
+ get(e, n) {
91
+ let r = t.getInstance(), i = r[n];
92
+ return typeof i == "function" ? i.bind(r) : i;
93
+ },
94
+ apply() {
95
+ throw TypeError("eventBus is not a callable function");
96
+ }
97
+ }), r = (e, t) => n.emit(e, t), i = (e, t) => n.on(e, t), a = (e, t) => n.off(e, t);
98
+ function o(e, t) {
99
+ return t === void 0 ? n.once(e) : n.once(e, t);
99
100
  }
100
- var C = (r, t, e) => i.listen(r, t, e);
101
- export {
102
- h as GlobalEventBus,
103
- d as emit,
104
- i as eventBus,
105
- C as listen,
106
- b as off,
107
- v as on,
108
- E as once
109
- };
101
+ var s = (e, t, r) => n.listen(e, t, r);
102
+ //#endregion
103
+ export { t as GlobalEventBus, r as emit, n as eventBus, s as listen, a as off, i as on, o as once };
110
104
 
111
105
  //# sourceMappingURL=custom-elements-runtime.event-bus.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"custom-elements-runtime.event-bus.es.js","names":[],"sources":["../src/lib/event-bus.ts"],"sourcesContent":["/**\n * Event handler type for global event bus\n */\nexport type EventHandler<T> = (data: T) => void;\n\nimport { devError } from './runtime/logger';\n\n/**\n * Event map type using Set for efficient handler management\n */\ntype EventMap<Events extends Record<string, unknown>> = {\n [K in keyof Events]: Set<EventHandler<Events[K]>>;\n};\n\n/**\n * GlobalEventBus provides a singleton event bus for cross-component communication.\n * Uses Set for handler storage to optimize add/remove operations and prevent duplicates.\n */\nexport class GlobalEventBus extends EventTarget {\n private handlers: EventMap<Record<string, unknown>> = {};\n private static instance: GlobalEventBus;\n private eventCounters: Map<string, { count: number; window: number }> =\n new Map();\n private nativeUnsubscribers: Map<() => void, true> = new Map();\n private readonly MAX_EVENT_COUNTERS = 1000;\n\n /**\n * Returns the singleton instance of GlobalEventBus\n */\n static getInstance(): GlobalEventBus {\n if (!GlobalEventBus.instance) {\n GlobalEventBus.instance = new GlobalEventBus();\n }\n return GlobalEventBus.instance;\n }\n\n /**\n * Emit a global event with optional data. Includes event storm protection.\n * @param eventName - Name of the event\n * @param data - Optional event payload\n */\n emit<T = unknown>(eventName: string, data?: T): void {\n // Event storm protection\n const now = Date.now();\n const counter = this.eventCounters.get(eventName);\n\n if (!counter || now - counter.window > 1000) {\n // Evict oldest entry if the map is at capacity to prevent unbounded growth.\n if (!counter && this.eventCounters.size >= this.MAX_EVENT_COUNTERS) {\n const firstKey = this.eventCounters.keys().next().value;\n if (firstKey !== undefined) this.eventCounters.delete(firstKey);\n }\n // Reset counter every second\n this.eventCounters.set(eventName, { count: 1, window: now });\n } else {\n counter.count++;\n\n if (counter.count === 51) {\n // Warn once at the throttle threshold so developers know emissions are being dropped.\n devError(\n `[EventBus] Event \"${eventName}\" is firing too frequently (>${counter.count - 1}/s). ` +\n 'Emissions above 50/s are throttled and above 100/s are dropped to prevent event storms. ' +\n 'Consider debouncing the emitter.',\n );\n }\n if (counter.count > 100) {\n // Drop the event to protect against runaway event storms.\n return;\n }\n }\n\n // Use native CustomEvent for better browser integration\n this.dispatchEvent(\n new CustomEvent(eventName, {\n detail: data,\n bubbles: false, // Global events don't need to bubble\n cancelable: true,\n }),\n );\n\n // Also trigger registered handlers\n const eventHandlers = this.handlers[eventName];\n if (eventHandlers) {\n eventHandlers.forEach((handler) => {\n try {\n handler(data);\n } catch (error) {\n devError(`Error in global event handler for \"${eventName}\":`, error);\n }\n });\n }\n }\n\n /**\n * Register a handler for a global event. Returns an unsubscribe function.\n * @param eventName - Name of the event\n * @param handler - Handler function\n */\n on<T = unknown>(eventName: string, handler: EventHandler<T>): () => void {\n if (!this.handlers[eventName]) {\n this.handlers[eventName] = new Set<EventHandler<unknown>>();\n }\n this.handlers[eventName].add(handler as EventHandler<unknown>);\n return () => this.off(eventName, handler);\n }\n\n /**\n * Remove a specific handler for a global event.\n * @param eventName - Name of the event\n * @param handler - Handler function to remove\n */\n off<T = unknown>(eventName: string, handler: EventHandler<T>): void {\n const eventHandlers = this.handlers[eventName];\n if (eventHandlers) {\n eventHandlers.delete(handler as EventHandler<unknown>);\n // Remove the entry entirely once it is empty so stale keys don't\n // accumulate indefinitely in long-lived apps.\n if (eventHandlers.size === 0) {\n delete this.handlers[eventName];\n }\n }\n }\n\n /**\n * Remove all handlers for a specific event.\n * @param eventName - Name of the event\n */\n offAll(eventName: string): void {\n delete this.handlers[eventName];\n }\n\n /**\n * Listen for a native CustomEvent. Returns an unsubscribe function.\n * @param eventName - Name of the event\n * @param handler - CustomEvent handler\n * @param options - AddEventListener options\n */\n listen<T = unknown>(\n eventName: string,\n handler: (event: CustomEvent<T>) => void,\n options?: AddEventListenerOptions,\n ): () => void {\n this.addEventListener(eventName, handler as EventListener, options);\n // Use a wrapper so calling unsubscribe also removes it from nativeUnsubscribers,\n // preventing indefinite accumulation in long-lived apps.\n const unsubscribe: () => void = () => {\n this.removeEventListener(eventName, handler as EventListener);\n this.nativeUnsubscribers.delete(unsubscribe);\n };\n this.nativeUnsubscribers.set(unsubscribe, true);\n return unsubscribe;\n }\n\n /**\n * Register a one-time event handler (callback form).\n * The handler is invoked exactly once, then automatically unsubscribed.\n * @param eventName - Name of the event\n * @param handler - Handler function\n */\n once<T = unknown>(eventName: string, handler: EventHandler<T>): void;\n /**\n * Returns a Promise that resolves with the first emission of the event\n * (Promise form — no handler argument).\n * @param eventName - Name of the event\n */\n once<T = unknown>(eventName: string): Promise<T>;\n once<T = unknown>(\n eventName: string,\n handler?: EventHandler<T>,\n ): void | Promise<T> {\n if (handler !== undefined) {\n // Callback form: fire-and-forget, returns void\n const unsubscribe = this.on(eventName, (data: T) => {\n unsubscribe();\n handler(data);\n });\n } else {\n // Promise form: resolves on first emission\n return new Promise<T>((resolve) => {\n const unsubscribe = this.on(eventName, (data: T) => {\n unsubscribe();\n resolve(data);\n });\n });\n }\n }\n\n /**\n * Get a list of all active event names with registered handlers.\n */\n getActiveEvents(): string[] {\n return Object.keys(this.handlers).filter(\n (eventName) =>\n this.handlers[eventName] && this.handlers[eventName].size > 0,\n );\n }\n\n /**\n * Clear all event handlers and native EventTarget listeners (useful for testing or cleanup).\n */\n clear(): void {\n this.handlers = {};\n const toCleanup = Array.from(this.nativeUnsubscribers.keys());\n this.nativeUnsubscribers.clear();\n for (const unsubscribe of toCleanup) {\n unsubscribe();\n }\n }\n\n /**\n * Get the number of handlers registered for a specific event.\n * @param eventName - Name of the event\n */\n getHandlerCount(eventName: string): number {\n return this.handlers[eventName]?.size || 0;\n }\n\n /**\n * Get event statistics for debugging.\n */\n getEventStats(): Record<string, { count: number; handlersCount: number }> {\n const stats: Record<string, { count: number; handlersCount: number }> = {};\n for (const [eventName, counter] of this.eventCounters.entries()) {\n stats[eventName] = {\n count: counter.count,\n handlersCount: this.getHandlerCount(eventName),\n };\n }\n return stats;\n }\n\n /**\n * Reset event counters (useful for testing or after resolving issues).\n */\n resetEventCounters(): void {\n this.eventCounters.clear();\n }\n}\n\n/**\n * Singleton instance of the global event bus\n */\n/**\n * Lazily-instantiated event bus.\n *\n * We preserve the `eventBus` export for backward compatibility but avoid\n * creating the underlying GlobalEventBus instance at module import time.\n * A small proxy defers the call to `GlobalEventBus.getInstance()` until a\n * property is accessed. This reduces import-time side-effects and helps\n * bundlers tree-shake unused entrypoints.\n */\nexport const eventBus = new Proxy(\n {},\n {\n get(_target, prop: PropertyKey) {\n const inst = GlobalEventBus.getInstance();\n const val = (inst as unknown as Record<PropertyKey, unknown>)[prop];\n // If the property is a function (method), bind it to the instance\n // so callers using `eventBus.method(...)` get the correct `this`.\n if (typeof val === 'function')\n return (val as (...args: unknown[]) => unknown).bind(inst);\n return val;\n },\n apply() {\n throw new TypeError('eventBus is not a callable function');\n },\n },\n) as unknown as GlobalEventBus;\n\n/**\n * Emit a global event\n */\nexport const emit = <T = unknown>(eventName: string, data?: T) =>\n eventBus.emit(eventName, data);\n\n/**\n * Register a handler for a global event\n */\nexport const on = <T = unknown>(eventName: string, handler: EventHandler<T>) =>\n eventBus.on(eventName, handler);\n\n/**\n * Remove a handler for a global event\n */\nexport const off = <T = unknown>(eventName: string, handler: EventHandler<T>) =>\n eventBus.off(eventName, handler);\n\n/**\n * Register a one-time handler for a global event (callback form).\n * The handler fires once then auto-unsubscribes.\n */\nexport function once<T = unknown>(\n eventName: string,\n handler: EventHandler<T>,\n): void;\n/**\n * Returns a Promise that resolves with the next emission of the event\n * (Promise form — no handler argument needed).\n */\nexport function once<T = unknown>(eventName: string): Promise<T>;\nexport function once<T = unknown>(\n eventName: string,\n handler?: EventHandler<T>,\n): void | Promise<T> {\n if (handler !== undefined) {\n return eventBus.once(eventName, handler);\n }\n return eventBus.once<T>(eventName);\n}\n\n/**\n * Listen for a native CustomEvent\n */\nexport const listen = <T = unknown>(\n eventName: string,\n handler: (event: CustomEvent<T>) => void,\n options?: AddEventListenerOptions,\n) => eventBus.listen(eventName, handler, options);\n"],"mappings":";AAkBA,IAAa,IAAb,MAAa,UAAuB,YAAY;AAAA,EAC9C,WAAsD,CAAA;AAAA,EACtD,OAAe;AAAA,EACf,gBACE,oBAAI,IAAA;AAAA,EACN,sBAAqD,oBAAI,IAAA;AAAA,EACzD,qBAAsC;AAAA,EAKtC,OAAO,cAA8B;AACnC,WAAK,EAAe,aAClB,EAAe,WAAW,IAAI,EAAA,IAEzB,EAAe;AAAA;EAQxB,KAAkB,GAAmB,GAAgB;AAEnD,UAAM,IAAM,KAAK,IAAA,GACX,IAA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AACN,UAAM,IAAI,UAAU,qCAAA;AAAA;CAEvB,GAMU,IAAA,CAAqB,GAAmB,MACnD,EAAS,KAAK,GAAW,CAAA,GAKd,IAAA,CAAmB,GAAmB,MACjD,EAAS,GAAG,GAAW,CAAA,GAKZ,IAAA,CAAoB,GAAmB,MAClD,EAAS,IAAI,GAAW,CAAA;AAe1B,SAAgB,EACd,GACA,GACmB;AACnB,SAAI,MAAY,SACP,EAAS,KAAK,GAAW,CAAA,IAE3B,EAAS,KAAQ,CAAA;;AAM1B,IAAa,IAAA,CACX,GACA,GACA,MACG,EAAS,OAAO,GAAW,GAAS,CAAA"}
1
+ {"version":3,"file":"custom-elements-runtime.event-bus.es.js","names":[],"sources":["../src/lib/event-bus.ts"],"sourcesContent":["/**\n * Event handler type for global event bus\n */\nexport type EventHandler<T> = (data: T) => void;\n\nimport { devError } from './runtime/logger';\n\n/**\n * Event map type using Set for efficient handler management\n */\ntype EventMap<Events extends Record<string, unknown>> = {\n [K in keyof Events]: Set<EventHandler<Events[K]>>;\n};\n\n/**\n * GlobalEventBus provides a singleton event bus for cross-component communication.\n * Uses Set for handler storage to optimize add/remove operations and prevent duplicates.\n */\nexport class GlobalEventBus extends EventTarget {\n private handlers: EventMap<Record<string, unknown>> = {};\n private static instance: GlobalEventBus;\n private eventCounters: Map<string, { count: number; window: number }> =\n new Map();\n private nativeUnsubscribers: Map<() => void, true> = new Map();\n private readonly MAX_EVENT_COUNTERS = 1000;\n\n /**\n * Returns the singleton instance of GlobalEventBus\n */\n static getInstance(): GlobalEventBus {\n if (!GlobalEventBus.instance) {\n GlobalEventBus.instance = new GlobalEventBus();\n }\n return GlobalEventBus.instance;\n }\n\n /**\n * Emit a global event with optional data. Includes event storm protection.\n * @param eventName - Name of the event\n * @param data - Optional event payload\n */\n emit<T = unknown>(eventName: string, data?: T): void {\n // Event storm protection\n const now = Date.now();\n const counter = this.eventCounters.get(eventName);\n\n if (!counter || now - counter.window > 1000) {\n // Evict oldest entry if the map is at capacity to prevent unbounded growth.\n if (!counter && this.eventCounters.size >= this.MAX_EVENT_COUNTERS) {\n const firstKey = this.eventCounters.keys().next().value;\n if (firstKey !== undefined) this.eventCounters.delete(firstKey);\n }\n // Reset counter every second\n this.eventCounters.set(eventName, { count: 1, window: now });\n } else {\n counter.count++;\n\n if (counter.count === 51) {\n // Warn once at the throttle threshold so developers know emissions are being dropped.\n devError(\n `[EventBus] Event \"${eventName}\" is firing too frequently (>${counter.count - 1}/s). ` +\n 'Emissions above 50/s are throttled and above 100/s are dropped to prevent event storms. ' +\n 'Consider debouncing the emitter.',\n );\n }\n if (counter.count > 100) {\n // Drop the event to protect against runaway event storms.\n return;\n }\n }\n\n // Use native CustomEvent for better browser integration\n this.dispatchEvent(\n new CustomEvent(eventName, {\n detail: data,\n bubbles: false, // Global events don't need to bubble\n cancelable: true,\n }),\n );\n\n // Also trigger registered handlers\n const eventHandlers = this.handlers[eventName];\n if (eventHandlers) {\n eventHandlers.forEach((handler) => {\n try {\n handler(data);\n } catch (error) {\n devError(`Error in global event handler for \"${eventName}\":`, error);\n }\n });\n }\n }\n\n /**\n * Register a handler for a global event. Returns an unsubscribe function.\n * @param eventName - Name of the event\n * @param handler - Handler function\n */\n on<T = unknown>(eventName: string, handler: EventHandler<T>): () => void {\n if (!this.handlers[eventName]) {\n this.handlers[eventName] = new Set<EventHandler<unknown>>();\n }\n this.handlers[eventName].add(handler as EventHandler<unknown>);\n return () => this.off(eventName, handler);\n }\n\n /**\n * Remove a specific handler for a global event.\n * @param eventName - Name of the event\n * @param handler - Handler function to remove\n */\n off<T = unknown>(eventName: string, handler: EventHandler<T>): void {\n const eventHandlers = this.handlers[eventName];\n if (eventHandlers) {\n eventHandlers.delete(handler as EventHandler<unknown>);\n // Remove the entry entirely once it is empty so stale keys don't\n // accumulate indefinitely in long-lived apps.\n if (eventHandlers.size === 0) {\n delete this.handlers[eventName];\n }\n }\n }\n\n /**\n * Remove all handlers for a specific event.\n * @param eventName - Name of the event\n */\n offAll(eventName: string): void {\n delete this.handlers[eventName];\n }\n\n /**\n * Listen for a native CustomEvent. Returns an unsubscribe function.\n * @param eventName - Name of the event\n * @param handler - CustomEvent handler\n * @param options - AddEventListener options\n */\n listen<T = unknown>(\n eventName: string,\n handler: (event: CustomEvent<T>) => void,\n options?: AddEventListenerOptions,\n ): () => void {\n this.addEventListener(eventName, handler as EventListener, options);\n // Use a wrapper so calling unsubscribe also removes it from nativeUnsubscribers,\n // preventing indefinite accumulation in long-lived apps.\n const unsubscribe: () => void = () => {\n this.removeEventListener(eventName, handler as EventListener);\n this.nativeUnsubscribers.delete(unsubscribe);\n };\n this.nativeUnsubscribers.set(unsubscribe, true);\n return unsubscribe;\n }\n\n /**\n * Register a one-time event handler (callback form).\n * The handler is invoked exactly once, then automatically unsubscribed.\n * @param eventName - Name of the event\n * @param handler - Handler function\n */\n once<T = unknown>(eventName: string, handler: EventHandler<T>): void;\n /**\n * Returns a Promise that resolves with the first emission of the event\n * (Promise form — no handler argument).\n * @param eventName - Name of the event\n */\n once<T = unknown>(eventName: string): Promise<T>;\n once<T = unknown>(\n eventName: string,\n handler?: EventHandler<T>,\n ): void | Promise<T> {\n if (handler !== undefined) {\n // Callback form: fire-and-forget, returns void\n const unsubscribe = this.on(eventName, (data: T) => {\n unsubscribe();\n handler(data);\n });\n } else {\n // Promise form: resolves on first emission\n return new Promise<T>((resolve) => {\n const unsubscribe = this.on(eventName, (data: T) => {\n unsubscribe();\n resolve(data);\n });\n });\n }\n }\n\n /**\n * Get a list of all active event names with registered handlers.\n */\n getActiveEvents(): string[] {\n return Object.keys(this.handlers).filter(\n (eventName) =>\n this.handlers[eventName] && this.handlers[eventName].size > 0,\n );\n }\n\n /**\n * Clear all event handlers and native EventTarget listeners (useful for testing or cleanup).\n */\n clear(): void {\n this.handlers = {};\n const toCleanup = Array.from(this.nativeUnsubscribers.keys());\n this.nativeUnsubscribers.clear();\n for (const unsubscribe of toCleanup) {\n unsubscribe();\n }\n }\n\n /**\n * Get the number of handlers registered for a specific event.\n * @param eventName - Name of the event\n */\n getHandlerCount(eventName: string): number {\n return this.handlers[eventName]?.size || 0;\n }\n\n /**\n * Get event statistics for debugging.\n */\n getEventStats(): Record<string, { count: number; handlersCount: number }> {\n const stats: Record<string, { count: number; handlersCount: number }> = {};\n for (const [eventName, counter] of this.eventCounters.entries()) {\n stats[eventName] = {\n count: counter.count,\n handlersCount: this.getHandlerCount(eventName),\n };\n }\n return stats;\n }\n\n /**\n * Reset event counters (useful for testing or after resolving issues).\n */\n resetEventCounters(): void {\n this.eventCounters.clear();\n }\n}\n\n/**\n * Singleton instance of the global event bus\n */\n/**\n * Lazily-instantiated event bus.\n *\n * We preserve the `eventBus` export for backward compatibility but avoid\n * creating the underlying GlobalEventBus instance at module import time.\n * A small proxy defers the call to `GlobalEventBus.getInstance()` until a\n * property is accessed. This reduces import-time side-effects and helps\n * bundlers tree-shake unused entrypoints.\n */\nexport const eventBus = new Proxy(\n {},\n {\n get(_target, prop: PropertyKey) {\n const inst = GlobalEventBus.getInstance();\n const val = (inst as unknown as Record<PropertyKey, unknown>)[prop];\n // If the property is a function (method), bind it to the instance\n // so callers using `eventBus.method(...)` get the correct `this`.\n if (typeof val === 'function')\n return (val as (...args: unknown[]) => unknown).bind(inst);\n return val;\n },\n apply() {\n throw new TypeError('eventBus is not a callable function');\n },\n },\n) as unknown as GlobalEventBus;\n\n/**\n * Emit a global event\n */\nexport const emit = <T = unknown>(eventName: string, data?: T) =>\n eventBus.emit(eventName, data);\n\n/**\n * Register a handler for a global event\n */\nexport const on = <T = unknown>(eventName: string, handler: EventHandler<T>) =>\n eventBus.on(eventName, handler);\n\n/**\n * Remove a handler for a global event\n */\nexport const off = <T = unknown>(eventName: string, handler: EventHandler<T>) =>\n eventBus.off(eventName, handler);\n\n/**\n * Register a one-time handler for a global event (callback form).\n * The handler fires once then auto-unsubscribes.\n */\nexport function once<T = unknown>(\n eventName: string,\n handler: EventHandler<T>,\n): void;\n/**\n * Returns a Promise that resolves with the next emission of the event\n * (Promise form — no handler argument needed).\n */\nexport function once<T = unknown>(eventName: string): Promise<T>;\nexport function once<T = unknown>(\n eventName: string,\n handler?: EventHandler<T>,\n): void | Promise<T> {\n if (handler !== undefined) {\n return eventBus.once(eventName, handler);\n }\n return eventBus.once<T>(eventName);\n}\n\n/**\n * Listen for a native CustomEvent\n */\nexport const listen = <T = unknown>(\n eventName: string,\n handler: (event: CustomEvent<T>) => void,\n options?: AddEventListenerOptions,\n) => eventBus.listen(eventName, handler, options);\n"],"mappings":";;AAkBA,IAAa,IAAb,MAAa,UAAuB,YAAY;CAC9C,WAAsD,EAAE;CACxD,OAAe;CACf,gCACE,IAAI,KAAK;CACX,sCAAqD,IAAI,KAAK;CAC9D,qBAAsC;CAKtC,OAAO,cAA8B;AAInC,SAHA,AACE,EAAe,aAAW,IAAI,GAAgB,EAEzC,EAAe;;CAQxB,KAAkB,GAAmB,GAAgB;EAEnD,IAAM,IAAM,KAAK,KAAK,EAChB,IAAU,KAAK,cAAc,IAAI,EAAU;AAEjD,MAAI,CAAC,KAAW,IAAM,EAAQ,SAAS,KAAM;AAE3C,OAAI,CAAC,KAAW,KAAK,cAAc,QAAQ,KAAK,oBAAoB;IAClE,IAAM,IAAW,KAAK,cAAc,MAAM,CAAC,MAAM,CAAC;AAClD,IAAI,MAAa,KAAA,KAAW,KAAK,cAAc,OAAO,EAAS;;AAGjE,QAAK,cAAc,IAAI,GAAW;IAAE,OAAO;IAAG,QAAQ;IAAK,CAAC;aAE5D,EAAQ,SAEJ,EAAQ,UAAU,MAEpB,EACE,qBAAqB,EAAU,+BAA+B,EAAQ,QAAQ,EAAE,+HAGjF,EAEC,EAAQ,QAAQ,IAElB;AAKJ,OAAK,cACH,IAAI,YAAY,GAAW;GACzB,QAAQ;GACR,SAAS;GACT,YAAY;GACb,CAAC,CACH;EAGD,IAAM,IAAgB,KAAK,SAAS;AACpC,EAAI,KACF,EAAc,SAAS,MAAY;AACjC,OAAI;AACF,MAAQ,EAAK;Y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,IAAM,IAAkE,EAAE;AAC1E,OAAK,IAAM,CAAC,GAAW,MAAY,KAAK,cAAc,SAAS,CAC7D,GAAM,KAAa;GACjB,OAAO,EAAQ;GACf,eAAe,KAAK,gBAAgB,EAAU;GAC/C;AAEH,SAAO;;CAMT,qBAA2B;AACzB,OAAK,cAAc,OAAO;;GAgBjB,IAAW,IAAI,MAC1B,EAAE,EACF;CACE,IAAI,GAAS,GAAmB;EAC9B,IAAM,IAAO,EAAe,aAAa,EACnC,IAAO,EAAiD;AAK9D,SAFI,OAAO,KAAQ,aACT,EAAwC,KAAK,EAAK,GACrD;;CAET,QAAQ;AACN,QAAU,UAAU,sCAAsC;;CAE7D,CACF,EAKY,KAAqB,GAAmB,MACnD,EAAS,KAAK,GAAW,EAAK,EAKnB,KAAmB,GAAmB,MACjD,EAAS,GAAG,GAAW,EAAQ,EAKpB,KAAoB,GAAmB,MAClD,EAAS,IAAI,GAAW,EAAQ;AAelC,SAAgB,EACd,GACA,GACmB;AAInB,QAHI,MAAY,KAAA,IAGT,EAAS,KAAQ,EAAU,GAFzB,EAAS,KAAK,GAAW,EAAQ;;AAQ5C,IAAa,KACX,GACA,GACA,MACG,EAAS,OAAO,GAAW,GAAS,EAAQ"}
@@ -1,3 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("./hooks-fYQgZk2g.cjs"),e=require("./style-Bjn8zDiZ.cjs");function o(r){if(s.isDiscoveryRender$1())return;const t=s.getCurrentComponentContext()?._host?.shadowRoot??null;t?e.registerJITCSSComponent(t,r):e.enableJITCSS(r)}function a(r){return r}exports.cls=a;exports.colors=e.colors;exports.containerVariants=e.containerVariants;exports.disableJITCSS=e.disableJITCSS;exports.enableJITCSS=e.enableJITCSS;exports.extractClassesFromHTML=e.extractClassesFromHTML;exports.getJITCSSOptions=e.getJITCSSOptions;exports.isJITCSSEnabled=e.isJITCSSEnabled;exports.isJITCSSEnabledFor=e.isJITCSSEnabledFor;exports.jitCSS=e.jitCSS;exports.mediaVariants=e.mediaVariants;exports.parseArbitrary=e.parseArbitrary;exports.parseColorClass=e.parseColorClass;exports.parseColorWithOpacity=e.parseColorWithOpacity;exports.parseGradientColorStop=e.parseGradientColorStop;exports.parseSpacing=e.parseSpacing;exports.registerJITCSSComponent=e.registerJITCSSComponent;exports.selectorVariants=e.selectorVariants;exports.useDesignTokens=s.useDesignTokens;exports.useGlobalStyle=s.useGlobalStyle;exports.useJITCSS=o;exports.utilityMap=e.utilityMap;
2
-
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./helpers-DcEpRwq5.cjs`),t=require(`./hooks-CNfugc95.cjs`),n=require(`./style-A8l3aQ52.cjs`);function r(r){if(e.w())return;let i=t.i()?._host?.shadowRoot??null;i?n.g(i,r):n.i(r)}function i(e){return e}exports.cls=i,exports.colors=n.t,exports.containerVariants=n.n,exports.disableJITCSS=n.r,exports.enableJITCSS=n.i,exports.extractClassesFromHTML=n.a,exports.getJITCSSOptions=n.o,exports.isJITCSSEnabled=n.s,exports.isJITCSSEnabledFor=n.c,exports.jitCSS=n.l,exports.mediaVariants=n.u,exports.parseArbitrary=n.d,exports.parseColorClass=n.f,exports.parseColorWithOpacity=n.p,exports.parseGradientColorStop=n.m,exports.parseSpacing=n.h,exports.registerJITCSSComponent=n.g,exports.selectorVariants=n._,exports.useDesignTokens=t.l,exports.useGlobalStyle=t.f,exports.useJITCSS=r,exports.utilityMap=n.v;
3
2
  //# sourceMappingURL=custom-elements-runtime.jit-css.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"custom-elements-runtime.jit-css.cjs.js","names":[],"sources":["../src/lib/runtime/jit-hooks.ts","../src/lib/jit-css.ts"],"sourcesContent":["/**\n * JIT CSS hooks — lives in a separate module so that hooks.ts does not\n * statically import style.ts. Consumers who never call `useJITCSS` will\n * have the entire JIT engine tree-shaken out of their bundle.\n */\n\nimport { isDiscoveryRender as _isDiscoveryRenderFn } from './discovery-state';\nimport { getCurrentComponentContext } from './hooks';\nimport {\n enableJITCSS,\n registerJITCSSComponent,\n type JITCSSOptions,\n} from './style';\n\n/**\n * Configure the JIT CSS engine for the current session.\n * This is a convenience wrapper around `enableJITCSS()` that can be called\n * inside a component render function or at module initialisation time.\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * // Enable extended Tailwind colors so bg-blue-500, text-violet-700, etc. generate CSS\n * useJITCSS({ extendedColors: true });\n * return html`<div class=\"bg-blue-500 text-white\">Hello</div>`;\n * });\n * ```\n *\n * @example\n * ```ts\n * // At app entry – enable once for all components\n * useJITCSS({ extendedColors: true, customColors: { brand: { '500': '#e63946' } } });\n * ```\n */\nexport function useJITCSS(options?: JITCSSOptions): void {\n // During discovery renders (component registration phase) there is no real\n // shadow root. Without this guard, useJITCSS() falls through to\n // enableJITCSS() and globally enables JIT CSS for every component — exactly\n // the opt-in behaviour we are trying to prevent.\n if (_isDiscoveryRenderFn()) return;\n\n // When called inside a component render function, register this component's\n // shadow root for per-component JIT CSS opt-in. Context is always set during\n // a real render; it may be absent (null) or missing _host when called at app\n // startup level (outside any component context).\n const host = (getCurrentComponentContext() as { _host?: Element } | null)\n ?._host;\n const shadowRoot = host?.shadowRoot ?? null;\n\n if (shadowRoot) {\n // Per-component opt-in: register this shadow root only.\n registerJITCSSComponent(shadowRoot, options);\n } else {\n // App-level call (outside component context) — enable for all components\n // globally, preserving v2 behaviour when called at the entry point.\n enableJITCSS(options);\n }\n}\n\nexport type { JITCSSOptions };\n","/**\n * JIT CSS entry point — opt-in import for the full JIT CSS engine.\n *\n * @example\n * ```ts\n * import {\n * useJITCSS,\n * enableJITCSS,\n * } from '@jasonshimmy/custom-elements-runtime/jit-css';\n * ```\n */\n\n// Hooks\nexport { useJITCSS } from './runtime/jit-hooks';\nexport { useDesignTokens, useGlobalStyle } from './runtime/hooks';\nexport type { JITCSSOptions, DesignTokens } from './runtime/hooks';\n\n// Global configuration\nexport {\n enableJITCSS,\n disableJITCSS,\n isJITCSSEnabled,\n isJITCSSEnabledFor,\n registerJITCSSComponent,\n getJITCSSOptions,\n jitCSS,\n extractClassesFromHTML,\n parseColorClass,\n parseColorWithOpacity,\n parseGradientColorStop,\n parseSpacing,\n parseArbitrary,\n utilityMap,\n selectorVariants,\n mediaVariants,\n containerVariants,\n colors,\n} from './runtime/style';\n\n/**\n * A no-op identity function that signals to development tools (IDE\n * autocomplete, linters, PurgeCSS-style scanners) that the string contains\n * JIT CSS utility class names.\n *\n * At runtime this is simply `return className` — zero overhead.\n *\n * @example\n * ```ts\n * import { cls } from '@jasonshimmy/custom-elements-runtime/jit-css';\n *\n * const containerClasses = cls('flex items-center gap-4 bg-primary-500 text-white');\n * ```\n */\nexport function cls(className: string): string {\n return className;\n}\n"],"mappings":"6IAkCA,SAAgB,EAAU,EAA+B,CAKvD,GAAI,EAAA,oBAAA,EAAwB,OAQ5B,MAAM,EAFQ,EAAA,2BAAA,GACV,OACqB,YAAc,KAEnC,EAEF,EAAA,wBAAwB,EAAY,CAAA,EAIpC,EAAA,aAAa,CAAA,ECFjB,SAAgB,EAAI,EAA2B,CAC7C,OAAO"}
1
+ {"version":3,"file":"custom-elements-runtime.jit-css.cjs.js","names":[],"sources":["../src/lib/runtime/jit-hooks.ts","../src/lib/jit-css.ts"],"sourcesContent":["/**\n * JIT CSS hooks — lives in a separate module so that hooks.ts does not\n * statically import style.ts. Consumers who never call `useJITCSS` will\n * have the entire JIT engine tree-shaken out of their bundle.\n */\n\nimport { isDiscoveryRender as _isDiscoveryRenderFn } from './discovery-state';\nimport { getCurrentComponentContext } from './hooks';\nimport {\n enableJITCSS,\n registerJITCSSComponent,\n type JITCSSOptions,\n} from './style';\n\n/**\n * Configure the JIT CSS engine for the current session.\n * This is a convenience wrapper around `enableJITCSS()` that can be called\n * inside a component render function or at module initialisation time.\n *\n * @example\n * ```ts\n * component('my-component', () => {\n * // Enable extended Tailwind colors so bg-blue-500, text-violet-700, etc. generate CSS\n * useJITCSS({ extendedColors: true });\n * return html`<div class=\"bg-blue-500 text-white\">Hello</div>`;\n * });\n * ```\n *\n * @example\n * ```ts\n * // At app entry – enable once for all components\n * useJITCSS({ extendedColors: true, customColors: { brand: { '500': '#e63946' } } });\n * ```\n */\nexport function useJITCSS(options?: JITCSSOptions): void {\n // During discovery renders (component registration phase) there is no real\n // shadow root. Without this guard, useJITCSS() falls through to\n // enableJITCSS() and globally enables JIT CSS for every component — exactly\n // the opt-in behaviour we are trying to prevent.\n if (_isDiscoveryRenderFn()) return;\n\n // When called inside a component render function, register this component's\n // shadow root for per-component JIT CSS opt-in. Context is always set during\n // a real render; it may be absent (null) or missing _host when called at app\n // startup level (outside any component context).\n const host = (getCurrentComponentContext() as { _host?: Element } | null)\n ?._host;\n const shadowRoot = host?.shadowRoot ?? null;\n\n if (shadowRoot) {\n // Per-component opt-in: register this shadow root only.\n registerJITCSSComponent(shadowRoot, options);\n } else {\n // App-level call (outside component context) — enable for all components\n // globally, preserving v2 behaviour when called at the entry point.\n enableJITCSS(options);\n }\n}\n\nexport type { JITCSSOptions };\n","/**\n * JIT CSS entry point — opt-in import for the full JIT CSS engine.\n *\n * @example\n * ```ts\n * import {\n * useJITCSS,\n * enableJITCSS,\n * } from '@jasonshimmy/custom-elements-runtime/jit-css';\n * ```\n */\n\n// Hooks\nexport { useJITCSS } from './runtime/jit-hooks';\nexport { useDesignTokens, useGlobalStyle } from './runtime/hooks';\nexport type { JITCSSOptions, DesignTokens } from './runtime/hooks';\n\n// Global configuration\nexport {\n enableJITCSS,\n disableJITCSS,\n isJITCSSEnabled,\n isJITCSSEnabledFor,\n registerJITCSSComponent,\n getJITCSSOptions,\n jitCSS,\n extractClassesFromHTML,\n parseColorClass,\n parseColorWithOpacity,\n parseGradientColorStop,\n parseSpacing,\n parseArbitrary,\n utilityMap,\n selectorVariants,\n mediaVariants,\n containerVariants,\n colors,\n} from './runtime/style';\n\n/**\n * A no-op identity function that signals to development tools (IDE\n * autocomplete, linters, PurgeCSS-style scanners) that the string contains\n * JIT CSS utility class names.\n *\n * At runtime this is simply `return className` — zero overhead.\n *\n * @example\n * ```ts\n * import { cls } from '@jasonshimmy/custom-elements-runtime/jit-css';\n *\n * const containerClasses = cls('flex items-center gap-4 bg-primary-500 text-white');\n * ```\n */\nexport function cls(className: string): string {\n return className;\n}\n"],"mappings":"iLAkCA,SAAgB,EAAU,EAA+B,CAKvD,GAAI,EAAA,GAAsB,CAAE,OAQ5B,IAAM,EAFQ,EAAA,GAA4B,EACtC,OACqB,YAAc,KAEnC,EAEF,EAAA,EAAwB,EAAY,EAAQ,CAI5C,EAAA,EAAa,EAAQ,CCFzB,SAAgB,EAAI,EAA2B,CAC7C,OAAO"}