wu-framework 2.1.2 → 2.6.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 (72) hide show
  1. package/README.md +6 -1
  2. package/dist/adapters/alpine/index.d.ts +1 -1
  3. package/dist/adapters/angular/index.d.ts +1 -1
  4. package/dist/adapters/htmx/index.d.ts +1 -1
  5. package/dist/adapters/lit/index.d.ts +1 -1
  6. package/dist/adapters/lit/index.js +2 -2
  7. package/dist/adapters/lit/index.js.map +1 -1
  8. package/dist/adapters/preact/index.d.ts +1 -1
  9. package/dist/adapters/preact/index.js +1 -1
  10. package/dist/adapters/preact/index.js.map +1 -1
  11. package/dist/adapters/qwik/index.d.ts +3 -10
  12. package/dist/adapters/qwik/index.js +1 -1
  13. package/dist/adapters/qwik/index.js.map +1 -1
  14. package/dist/adapters/react/index.js +1 -1
  15. package/dist/adapters/react/index.js.map +1 -1
  16. package/dist/adapters/shared.d.ts +44 -0
  17. package/dist/adapters/shared.js +1 -1
  18. package/dist/adapters/shared.js.map +1 -1
  19. package/dist/adapters/solid/index.d.ts +1 -1
  20. package/dist/adapters/solid/index.js +1 -1
  21. package/dist/adapters/solid/index.js.map +1 -1
  22. package/dist/adapters/stencil/index.d.ts +1 -1
  23. package/dist/adapters/stimulus/index.d.ts +1 -1
  24. package/dist/adapters/svelte/index.d.ts +1 -1
  25. package/dist/adapters/svelte/index.js +1 -1
  26. package/dist/adapters/svelte/index.js.map +1 -1
  27. package/dist/adapters/vanilla/index.d.ts +1 -1
  28. package/dist/adapters/vanilla/index.js +1 -1
  29. package/dist/adapters/vanilla/index.js.map +1 -1
  30. package/dist/adapters/vue/index.js +1 -1
  31. package/dist/adapters/vue/index.js.map +1 -1
  32. package/dist/ai/wu-ai.js +1 -1
  33. package/dist/ai/wu-ai.js.map +1 -1
  34. package/dist/core/wu-devtools.js +2 -0
  35. package/dist/core/wu-devtools.js.map +1 -0
  36. package/dist/core/wu-html-parser.js +1 -1
  37. package/dist/core/wu-html-parser.js.map +1 -1
  38. package/dist/core/wu-iframe-sandbox.js +1 -1
  39. package/dist/core/wu-iframe-sandbox.js.map +1 -1
  40. package/dist/core/wu-loader.js +1 -1
  41. package/dist/core/wu-loader.js.map +1 -1
  42. package/dist/core/wu-logger.js +2 -0
  43. package/dist/core/wu-logger.js.map +1 -0
  44. package/dist/core/wu-mcp-bridge.js +1 -1
  45. package/dist/core/wu-mcp-bridge.js.map +1 -1
  46. package/dist/core/wu-script-executor.js +1 -1
  47. package/dist/core/wu-script-executor.js.map +1 -1
  48. package/dist/core/wu-store-sync.js +2 -0
  49. package/dist/core/wu-store-sync.js.map +1 -0
  50. package/dist/core/wu-timeline.js +2 -0
  51. package/dist/core/wu-timeline.js.map +1 -0
  52. package/dist/index.d.cts +759 -0
  53. package/dist/index.d.ts +315 -1
  54. package/dist/wu-ai-browser-primitives-CaUCk1Xl.js +2 -0
  55. package/dist/wu-ai-browser-primitives-CaUCk1Xl.js.map +1 -0
  56. package/dist/wu-framework.cjs +3 -0
  57. package/dist/wu-framework.cjs.map +1 -0
  58. package/dist/wu-framework.dev.js +1296 -275
  59. package/dist/wu-framework.dev.js.map +1 -1
  60. package/dist/wu-framework.esm.js +2 -2
  61. package/dist/wu-framework.esm.js.map +1 -1
  62. package/dist/wu-framework.umd.js +2 -2
  63. package/dist/wu-framework.umd.js.map +1 -1
  64. package/integrations/astro/WuApp.astro +16 -11
  65. package/integrations/astro/WuShell.astro +11 -3
  66. package/package.json +14 -6
  67. package/dist/wu-ai-browser-primitives-BDKXJlwc.js +0 -2
  68. package/dist/wu-ai-browser-primitives-BDKXJlwc.js.map +0 -1
  69. package/dist/wu-framework.cjs.js +0 -3
  70. package/dist/wu-framework.cjs.js.map +0 -1
  71. package/dist/wu-logger-fJfUHBGA.js +0 -2
  72. package/dist/wu-logger-fJfUHBGA.js.map +0 -1
@@ -0,0 +1,3 @@
1
+ /*! wu-framework v2.6.0 | MIT License */
2
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});class e{constructor(){this.isDevelopment=this.detectEnvironment(),this.logLevel=this.isDevelopment?"warn":"error",this.levels={debug:0,info:1,warn:2,error:3,silent:4}}detectEnvironment(){if("undefined"!=typeof window&&!0===window.WU_DEBUG)return!0;if("undefined"!=typeof window&&!1===window.WU_DEBUG)return!1;if("undefined"!=typeof process&&"production"===process.env?.NODE_ENV)return!1;if("undefined"!=typeof process&&"development"===process.env?.NODE_ENV)return!0;if("undefined"!=typeof window&&window.location){const e=window.location.hostname;if("localhost"===e||"127.0.0.1"===e||"[::1]"===e)return!0;try{if(new URLSearchParams(window.location.search).has("wu-debug"))return!0}catch{}}return!1}setLevel(e){return this.logLevel=e,this}setDevelopment(e){return this.isDevelopment=e,this.logLevel=e?"debug":"error",this}shouldLog(e){return this.levels[e]>=this.levels[this.logLevel]}debug(...e){this.shouldLog("debug")&&console.log(...e)}info(...e){this.shouldLog("info")&&console.info(...e)}warn(...e){this.shouldLog("warn")&&console.warn(...e)}error(...e){this.shouldLog("error")&&console.error(...e)}wu(e,...t){if(this.shouldLog(e)){console["debug"===e?"log":e]("[Wu]",...t)}}wuDebug(...e){this.wu("debug",...e)}wuInfo(...e){this.wu("info",...e)}wuWarn(...e){this.wu("warn",...e)}wuError(...e){this.wu("error",...e)}}const t=new e;function s(){t.setLevel("silent")}function r(){t.setLevel("debug")}var n=Object.freeze({__proto__:null,WuLogger:e,enableAllLogs:r,logger:t,silenceAllLogs:s});class i{constructor(){this.styleObserver=null,this.fullyIsolatedApps=new Map,this.config={autoShareLibraries:["element-plus","vue-flow","@vue-flow","vueuse","@vueuse","normalize.css","reset.css"],sharePatterns:[/\/node_modules\//,/\/@vite\/client/,/\/dist\/index\.css$/,/\/dist\/style\.css$/],mode:"auto",cacheEnabled:!0},t.debug("[WuStyleBridge] 🎨 Style sharing system initialized")}registerFullyIsolatedApp(e,s){this.fullyIsolatedApps.set(e,s),t.debug(`[WuStyleBridge] 🛡️ Registered fully-isolated app: ${e} (${s})`)}unregisterFullyIsolatedApp(e){this.fullyIsolatedApps.delete(e)&&t.debug(`[WuStyleBridge] 🛡️ Unregistered fully-isolated app: ${e}`)}isStyleFromFullyIsolatedApp(e){let t="",s=null;if("string"==typeof e?t=e:e&&"function"==typeof e.getAttribute?(s=e,t=e.getAttribute("data-vite-dev-id")||e.href||""):e&&(e.href?t=e.href:e.viteId?t=e.viteId:e.element&&(s=e.element,"function"==typeof e.element.getAttribute?t=e.element.getAttribute("data-vite-dev-id")||e.element.href||"":e.element.href&&(t=e.element.href))),s){const e=s.getAttribute("data-wu-app");if(e&&this.fullyIsolatedApps.has(e))return!0}if(!t||""===t.trim())return!1;const r=t.replace(/\\/g,"/").toLowerCase();for(const[e,t]of this.fullyIsolatedApps.entries()){const s=t.replace(/\\/g,"/").toLowerCase(),n=e.toLowerCase();if(s&&r.includes(s))return!0;if(new RegExp(`[/\\\\]${n}[/\\\\]`,"i").test(r))return!0}return!1}detectDocumentStyles(){const e=[];document.querySelectorAll('link[rel="stylesheet"]').forEach(t=>{this.isStyleFromFullyIsolatedApp(t)||e.push({type:"link",href:t.href,element:t,library:this.extractLibraryName(t.href)})});return document.querySelectorAll("style").forEach((s,r)=>{if("true"===s.getAttribute("data-wu-shared"))return;const n=s.getAttribute("data-vite-dev-id"),i=s.textContent;this.isStyleFromFullyIsolatedApp(s)||n&&this.isStyleFromFullyIsolatedApp(n)?t.debug(`[WuStyleBridge] 🛡️ Filtered out style from fully-isolated app: ${n||"unknown"}`):i&&i.trim().length>0&&e.push({type:"inline",content:i,element:s,viteId:n,library:this.extractLibraryName(n||""),index:r})}),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&document.adoptedStyleSheets.forEach((t,s)=>{e.push({type:"adoptedStyleSheet",sheet:t,index:s})}),t.debug(`[WuStyleBridge] 🔍 Detected ${e.length} shareable styles`),e}shouldShareStyle(e){if(!e)return!1;if("all"===this.config.mode)return!0;for(const t of this.config.sharePatterns)if(t.test(e))return!0;for(const t of this.config.autoShareLibraries)if(e.includes(t))return!0;return!1}extractLibraryName(e){if(!e)return null;const t=e.match(/\/node_modules\/(@?[^/]+\/[^/]+|@?[^/]+)/);if(t)return t[1];const s=e.match(/\/node_modules\/(.+?)\/.*?\.css/);return s?s[1]:null}async injectStylesIntoShadow(e,s,r){if(!e)return t.warn("[WuStyleBridge] ⚠️ No shadow root provided"),0;if("fully-isolated"===r)return t.debug(`[WuStyleBridge] 🛡️ Style mode "fully-isolated" for ${s}, skipping shared style injection`),0;if("isolated"===r)return t.debug(`[WuStyleBridge] 🔒 Style mode "isolated" for ${s}, using native Shadow DOM encapsulation (no external styles)`),0;t.debug(`[WuStyleBridge] 🌐 Style mode "shared" for ${s}, injecting all shared styles...`);const n=this.detectDocumentStyles();let i=0;for(const s of n)try{switch(s.type){case"link":await this.injectLinkStyle(e,s),i++;break;case"inline":this.injectInlineStyle(e,s),i++;break;case"adoptedStyleSheet":this.injectAdoptedStyleSheet(e,s),i++}}catch(e){t.warn("[WuStyleBridge] ⚠️ Failed to inject style:",e)}return t.debug(`[WuStyleBridge] ✅ Injected ${i} shared styles into ${s}`),i}async injectLinkStyle(e,s){if(e.querySelector(`link[href="${s.href}"]`))return void t.debug(`[WuStyleBridge] ⏭️ Style already exists: ${s.library||s.href}`);const r=document.createElement("link");r.rel="stylesheet",r.href=s.href,r.setAttribute("data-wu-shared","true"),r.setAttribute("data-wu-library",s.library||"unknown"),e.insertBefore(r,e.firstChild),t.debug(`[WuStyleBridge] 🔗 Injected link: ${s.library||s.href}`)}injectInlineStyle(e,s){const r=s.viteId,n=r?null:this._hashStyleContent(s.content);if(r){if(e.querySelector(`style[data-wu-vite-id="${r}"]`))return void t.debug(`[WuStyleBridge] ⏭️ Inline style already exists: ${r}`)}else{if(e.querySelector(`style[data-wu-content-hash="${n}"]`))return void t.debug(`[WuStyleBridge] ⏭️ Inline style already exists (content hash: ${n})`)}const i=document.createElement("style");i.textContent=s.content,i.setAttribute("data-wu-shared","true"),i.setAttribute("data-wu-library",s.library||"unknown"),r?i.setAttribute("data-wu-vite-id",r):i.setAttribute("data-wu-content-hash",n),e.insertBefore(i,e.firstChild),t.debug(`[WuStyleBridge] 📝 Injected inline style: ${s.library||r}`)}_hashStyleContent(e){let t=5381;for(let s=0;s<e.length;s++)t=(t<<5)+t+e.charCodeAt(s)|0;return`${e.length}_${(t>>>0).toString(36)}`}injectAdoptedStyleSheet(e,s){try{if(e.adoptedStyleSheets||(e.adoptedStyleSheets=[]),e.adoptedStyleSheets.includes(s.sheet))return void t.debug("[WuStyleBridge] ⏭️ Adopted stylesheet already exists");e.adoptedStyleSheets=[...e.adoptedStyleSheets,s.sheet],t.debug("[WuStyleBridge] 📋 Injected adopted stylesheet")}catch(e){t.warn("[WuStyleBridge] ⚠️ Failed to inject adopted stylesheet:",e)}}observeStyleChanges(e){return"function"!=typeof e?()=>{}:(this._styleCallbacks||(this._styleCallbacks=new Set),this._styleCallbacks.add(e),this.styleObserver||(this.styleObserver=new MutationObserver(e=>{let s=!1;for(const t of e)if("childList"===t.type){if(Array.from(t.addedNodes).some(e=>"LINK"===e.tagName||"STYLE"===e.tagName)){s=!0;break}}if(s){t.debug("[WuStyleBridge] 🔄 Style changes detected");for(const e of this._styleCallbacks)try{e()}catch(e){t.warn("[WuStyleBridge] callback threw:",e)}}}),this.styleObserver.observe(document.head,{childList:!0,subtree:!0}),t.debug("[WuStyleBridge] 👀 Observing style changes (shared observer)")),()=>{this._styleCallbacks&&(this._styleCallbacks.delete(e),0===this._styleCallbacks.size&&this.styleObserver&&(this.styleObserver.disconnect(),this.styleObserver=null))})}configure(e){this.config={...this.config,...e},t.debug("[WuStyleBridge] ⚙️ Configuration updated:",this.config)}cleanup(){this.styleObserver&&(this.styleObserver.disconnect(),this.styleObserver=null),t.debug("[WuStyleBridge] 🧹 StyleBridge cleaned up")}getStats(){const e=this.detectDocumentStyles();return{totalStyles:e.length,linkStyles:e.filter(e=>"link"===e.type).length,inlineStyles:e.filter(e=>"inline"===e.type).length,adoptedStyleSheets:e.filter(e=>"adoptedStyleSheet"===e.type).length,libraries:[...new Set(e.map(e=>e.library).filter(Boolean))],config:this.config}}}class o{constructor(e,t={}){this.appName=e,this.options=t,this.proxy=null,this.fakeWindow=Object.create(null),this.active=!1,this.modifiedKeys=new Set,this._timers=new Set,this._intervals=new Set,this._rafs=new Set,this._eventListeners=[],this._container=null,this._shadowRoot=null,this._scopedDocument=null,this._scopedLocalStorage=null,this._scopedSessionStorage=null,this._patched=!1,this._originals=null}setContainer(e,t){this._container=e,this._shadowRoot=t}activate(){if(this.active)return this.proxy;const e=this;return this.proxy=new Proxy(window,{get(t,s){if(s in e.fakeWindow)return e.fakeWindow[s];const r=e._intercept(s,t);if(void 0!==r)return r;const n=t[s];return"function"!=typeof n||e._isConstructor(n)?n:n.bind(t)},set:(t,s,r)=>(e.fakeWindow[s]=r,e.modifiedKeys.add(s),!0),has:(t,s)=>s in e.fakeWindow||s in t,deleteProperty:(t,s)=>s in e.fakeWindow&&(delete e.fakeWindow[s],e.modifiedKeys.delete(s),!0)}),this.active=!0,t.wuDebug(`[ProxySandbox] Activated for ${this.appName}`),this.proxy}deactivate(){if(!this.active)return;this.unpatchWindow();for(const e of this._timers)try{clearTimeout(e)}catch{}for(const e of this._intervals)try{clearInterval(e)}catch{}for(const e of this._rafs)try{cancelAnimationFrame(e)}catch{}const e=this._timers.size+this._intervals.size+this._rafs.size;this._timers.clear(),this._intervals.clear(),this._rafs.clear();const s=this._eventListeners.length;for(const{target:e,event:t,handler:s,options:r}of this._eventListeners)try{e.removeEventListener(t,s,r)}catch{}this._eventListeners=[],this.fakeWindow=Object.create(null),this.modifiedKeys.clear(),this._scopedDocument=null,this._scopedLocalStorage=null,this._scopedSessionStorage=null,this.proxy=null,this.active=!1,(e>0||s>0)&&t.wuDebug(`[ProxySandbox] ${this.appName} cleanup: ${e} timers, ${s} listeners`),t.wuDebug(`[ProxySandbox] Deactivated for ${this.appName}`)}patchWindow(){if(this._patched)return;const e=this,s={setTimeout:window.setTimeout,clearTimeout:window.clearTimeout,setInterval:window.setInterval,clearInterval:window.clearInterval,requestAnimationFrame:window.requestAnimationFrame,cancelAnimationFrame:window.cancelAnimationFrame,addEventListener:window.addEventListener,removeEventListener:window.removeEventListener};this._originals=s,window.setTimeout=function(t,r,...n){const i=s.setTimeout.call(window,t,r,...n);return e._patched&&e._timers.add(i),i},window.clearTimeout=function(t){return e._timers.delete(t),s.clearTimeout.call(window,t)},window.setInterval=function(t,r,...n){const i=s.setInterval.call(window,t,r,...n);return e._patched&&e._intervals.add(i),i},window.clearInterval=function(t){return e._intervals.delete(t),s.clearInterval.call(window,t)},window.requestAnimationFrame=function(t){const r=s.requestAnimationFrame.call(window,t);return e._patched&&e._rafs.add(r),r},window.cancelAnimationFrame=function(t){return e._rafs.delete(t),s.cancelAnimationFrame.call(window,t)},window.addEventListener=function(t,r,n){return e._patched&&e._eventListeners.push({target:window,event:t,handler:r,options:n}),s.addEventListener.call(window,t,r,n)},window.removeEventListener=function(t,r,n){return e._eventListeners=e._eventListeners.filter(e=>!(e.target===window&&e.event===t&&e.handler===r)),s.removeEventListener.call(window,t,r,n)},this._patched=!0,t.wuDebug(`[ProxySandbox] Window patched for ${this.appName}`)}unpatchWindow(){this._patched&&this._originals&&(window.setTimeout=this._originals.setTimeout,window.clearTimeout=this._originals.clearTimeout,window.setInterval=this._originals.setInterval,window.clearInterval=this._originals.clearInterval,window.requestAnimationFrame=this._originals.requestAnimationFrame,window.cancelAnimationFrame=this._originals.cancelAnimationFrame,window.addEventListener=this._originals.addEventListener,window.removeEventListener=this._originals.removeEventListener,this._patched=!1,t.wuDebug(`[ProxySandbox] Window unpatched for ${this.appName}`))}_intercept(e,t){const s=this;switch(e){case"setTimeout":return function(e,r,...n){const i=t.setTimeout(e,r,...n);return s._timers.add(i),i};case"clearTimeout":return function(e){s._timers.delete(e),t.clearTimeout(e)};case"setInterval":return function(e,r,...n){const i=t.setInterval(e,r,...n);return s._intervals.add(i),i};case"clearInterval":return function(e){s._intervals.delete(e),t.clearInterval(e)};case"requestAnimationFrame":return function(e){const r=t.requestAnimationFrame(e);return s._rafs.add(r),r};case"cancelAnimationFrame":return function(e){s._rafs.delete(e),t.cancelAnimationFrame(e)};case"addEventListener":return function(e,r,n){s._eventListeners.push({target:t,event:e,handler:r,options:n}),t.addEventListener(e,r,n)};case"removeEventListener":return function(e,r,n){s._eventListeners=s._eventListeners.filter(s=>!(s.target===t&&s.event===e&&s.handler===r)),t.removeEventListener(e,r,n)};case"document":return this._getScopedDocument();case"localStorage":return this._getScopedStorage("local");case"sessionStorage":return this._getScopedStorage("session")}}_getScopedDocument(){if(this._scopedDocument)return this._scopedDocument;const e=this._shadowRoot||this._container;if(!e)return document;const t=this;return this._scopedDocument=new Proxy(document,{get(s,r){switch(r){case"querySelector":return t=>e.querySelector(t);case"querySelectorAll":return t=>e.querySelectorAll(t);case"getElementById":return t=>e.querySelector(`#${CSS.escape(t)}`);case"getElementsByClassName":return t=>e.querySelectorAll(`.${CSS.escape(t)}`);case"getElementsByTagName":return t=>e.querySelectorAll(t);case"addEventListener":return function(e,r,n){t._eventListeners.push({target:s,event:e,handler:r,options:n}),s.addEventListener(e,r,n)};case"removeEventListener":return function(e,r,n){t._eventListeners=t._eventListeners.filter(t=>!(t.target===s&&t.event===e&&t.handler===r)),s.removeEventListener(e,r,n)};default:{const e=s[r];return"function"==typeof e?e.bind(s):e}}}}),this._scopedDocument}_getScopedStorage(e){const t="local"===e?"_scopedLocalStorage":"_scopedSessionStorage";if(this[t])return this[t];const s="local"===e?window.localStorage:window.sessionStorage;if(!s)return s;const r=`wu_${this.appName}_`;return this[t]={getItem:e=>s.getItem(r+e),setItem(e,t){s.setItem(r+e,String(t))},removeItem(e){s.removeItem(r+e)},clear(){const e=[];for(let t=0;t<s.length;t++){const n=s.key(t);n&&n.startsWith(r)&&e.push(n)}e.forEach(e=>s.removeItem(e))},key(e){let t=0;for(let n=0;n<s.length;n++){const i=s.key(n);if(i&&i.startsWith(r)){if(t===e)return i.slice(r.length);t++}}return null},get length(){let e=0;for(let t=0;t<s.length;t++)s.key(t)?.startsWith(r)&&e++;return e}},this[t]}_isConstructor(e){try{return e.prototype&&e.prototype.constructor===e}catch{return!1}}getProxy(){return this.active?this.proxy:null}isActive(){return this.active}getStats(){return{appName:this.appName,active:this.active,patched:this._patched,modifiedKeys:Array.from(this.modifiedKeys),isolatedPropsCount:Object.keys(this.fakeWindow).length,trackedTimers:this._timers.size,trackedIntervals:this._intervals.size,trackedRAFs:this._rafs.size,trackedEventListeners:this._eventListeners.length,hasContainer:!!this._container,hasShadowRoot:!!this._shadowRoot}}}function a(e){return"none"===e?"isolated":"own-only"===e?"fully-isolated":e}class c{constructor(){this.sandboxes=new Map,this.styleBridge=new i,this.jsSandboxes=new Map,this.sandboxStrategy=this.detectSandboxStrategy(),t.wuDebug(`Advanced isolation system initialized (strategy: ${this.sandboxStrategy})`)}detectSandboxStrategy(){return"proxy"}create(e,s,r={}){t.wuDebug(`Creating sandbox for: ${e}`);try{if(!s.attachShadow)throw new Error("Shadow DOM not supported in this browser");let n;s.shadowRoot?(t.wuDebug(`Existing shadow root detected for ${e}, performing cleanup...`),s.shadowRoot.innerHTML="",n=s.shadowRoot,t.wuDebug(`Existing shadow root cleaned and reused for ${e}`)):(n=s.attachShadow({mode:"open",delegatesFocus:!0}),t.wuDebug(`New shadow root created for ${e}`));const i=document.createElement("div");i.id=`wu-app-${e}`,i.className="wu-app-root",i.setAttribute("data-wu-enhanced","true"),i.setAttribute("data-wu-timestamp",Date.now().toString());const o=document.createElement("style");o.textContent=this.generateSandboxStyles(e),n.appendChild(o),n.appendChild(i);const c=this.createAdvancedJSSandbox(e);c.setContainer&&c.setContainer(i,n);const l=c.activate(),u=a(r.styleMode||r.manifest?.styleMode),d={appName:e,shadowRoot:n,container:i,hostContainer:s,jsSandbox:c,jsProxy:l,styles:o,styleMode:u,manifest:r.manifest,created:Date.now(),sandbox_state:"stable",recovery_count:0};if("isolated"===u)t.wuDebug(`Style mode "isolated" for ${e}, using native Shadow DOM encapsulation`),d.stylesReady=Promise.resolve(0);else if("fully-isolated"===u){t.wuDebug(`Style mode "fully-isolated" detected for ${e}, using enhanced style injection`);const s=r.appUrl||(r.manifest?.name?`/${r.manifest.name}/`:`/${e}/`);this.styleBridge.registerFullyIsolatedApp(e,s),d.appUrl=s;const i=this;d.stylesReady=new Promise(r=>{let o=!1;const a=async()=>{const a=await i.injectOwnStylesToShadow(n,e,s);return a>0&&(t.wuDebug(`Injected ${a} own styles for ${e} (fully-isolated)`),o||(o=!0,r(a))),a};t.wuDebug(`Setting up style observer for ${e} (fully-isolated)`);const c=new MutationObserver(s=>{let r=0;for(const n of s)if("childList"===n.type)for(const s of n.addedNodes)if("STYLE"===s.nodeName||"LINK"===s.nodeName){if(r++,!s.getAttribute)continue;const n=s.getAttribute("data-wu-app"),i=s.getAttribute("data-vite-dev-id");n===e?t.wuDebug(`New ${e} style (data-wu-app)`):i&&i.toLowerCase().includes(e.toLowerCase())&&t.wuDebug(`New ${e} style (vite): ${i.split("/").pop()}`)}r>0&&(t.wuDebug(`${r} new styles detected in head, checking for ${e}...`),a())});c.observe(document.head,{childList:!0,subtree:!0}),d.styleObserver=c,setTimeout(async()=>{await a();o||setTimeout(()=>{if(!o){t.wuWarn(`No own styles found for ${e} after timeout, using FALLBACK`);const s=i.injectAllStylesToShadow(n,e);t.wuDebug(`FALLBACK: Injected ${s} styles for ${e}`),o=!0,r(s)}},3e3)},50)})}else t.wuDebug(`Style mode "shared" for ${e}, injecting all shared styles...`),d.stylesReady=this.styleBridge.injectStylesIntoShadow(n,e,u).then(s=>(t.wuDebug(`Shared ${s} styles with ${e}`),d.unsubscribeStyleChanges=this.styleBridge.observeStyleChanges(()=>{t.wuDebug(`Reinjecting styles for ${e} due to changes`),this.styleBridge.injectStylesIntoShadow(n,e,u).catch(e=>{t.wuWarn(`Failed to reinject styles: ${e}`)})}),s)).catch(e=>(t.wuWarn(`Failed to inject styles: ${e}`),0));return this.sandboxes.set(e,d),t.wuDebug(`Enhanced sandbox created for ${e}`),d}catch(r){if(t.wuError(`Failed to create sandbox for ${e}: ${r}`),r.message.includes("Shadow root cannot be created"))return this.createFallbackSandbox(e,s);throw r}}createFallbackSandbox(e,s){t.wuDebug(`Creating fallback sandbox for ${e}...`);try{s.shadowRoot&&(s.shadowRoot.innerHTML="");const r=document.createElement("div");r.id=`wu-app-${e}`,r.className="wu-app-root wu-fallback",r.style.cssText="\n width: 100%;\n height: 100%;\n isolation: isolate;\n contain: layout style paint;\n ",s.innerHTML="",s.appendChild(r);const n={appName:e,shadowRoot:null,container:r,hostContainer:s,styles:null,created:Date.now(),sandbox_state:"fallback_mode",recovery_count:1,fallback_mode:!0};return this.sandboxes.set(e,n),t.wuDebug(`Fallback sandbox created successfully for ${e}`),n}catch(e){throw t.wuError(`Fallback sandbox creation failed: ${e}`),e}}generateSandboxStyles(e){return`\n /* Wu Framework - Shadow DOM Isolation Styles */\n :host {\n display: block;\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n contain: layout style paint;\n --wu-sandbox-active: true;\n --wu-isolation-state: stable;\n }\n\n .wu-app-root {\n width: 100%;\n height: 100%;\n box-sizing: border-box;\n isolation: isolate;\n position: relative;\n overflow: hidden;\n }\n\n /* Loading animation for sandbox initialization */\n .wu-app-root[data-wu-loading="true"] {\n background: linear-gradient(45deg,\n rgba(74, 144, 226, 0.1) 0%,\n rgba(80, 227, 194, 0.1) 100%);\n animation: sandboxPulse 2s ease-in-out infinite;\n }\n\n @keyframes sandboxPulse {\n 0%, 100% { opacity: 0.8; }\n 50% { opacity: 1; }\n }\n\n /* CSS reset for shadow DOM stability */\n * {\n box-sizing: border-box;\n }\n\n /* CSS custom properties for sandbox */\n :host {\n --wu-app-name: "${e}";\n --wu-isolation: true;\n --wu-creation-timestamp: ${Date.now()};\n }\n\n /* 🛡️ Debug mode enhancements */\n :host([wu-debug]) {\n border: 2px dashed #4a90e2;\n background: rgba(74, 144, 226, 0.05);\n box-shadow: 0 0 10px rgba(74, 144, 226, 0.3);\n }\n\n :host([wu-debug])::before {\n content: "Wu Framework: " attr(wu-app);\n position: absolute;\n top: 0;\n left: 0;\n background: linear-gradient(45deg, #4a90e2, #50e3c2);\n color: white;\n padding: 4px 8px;\n font-size: 11px;\n font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;\n z-index: 10000;\n border-radius: 0 0 4px 0;\n font-weight: 600;\n }\n\n /* Sandbox state indicators */\n :host([data-sandbox-state="stable"]) {\n --wu-isolation-state: stable;\n }\n\n :host([data-sandbox-state="healing"]) {\n --wu-dimensional-stability: healing;\n animation: sandboxHealing 1s ease-in-out infinite;\n }\n\n @keyframes sandboxHealing {\n 0%, 100% { filter: hue-rotate(0deg); }\n 50% { filter: hue-rotate(180deg); }\n }\n `}createAdvancedJSSandbox(e){const s=new o(e);return t.wuDebug(`Created ProxySandbox for ${e}`),this.jsSandboxes.set(e,s),s}addStyles(e,s){const r=this.sandboxes.get(e);if(!r)return void t.wuWarn(`Sandbox not found for: ${e}`);const n=document.createElement("style");n.textContent=s,n.setAttribute("wu-custom-styles",""),r.shadowRoot.appendChild(n),t.wuDebug(`Custom styles added to ${e}`)}loadExternalStyles(e,s){const r=this.sandboxes.get(e);if(!r)return void t.wuWarn(`Sandbox not found for: ${e}`);const n=document.createElement("link");n.rel="stylesheet",n.href=s,n.setAttribute("wu-external-styles",""),r.shadowRoot.appendChild(n),t.wuDebug(`External styles loaded in ${e}: ${s}`)}setDebugMode(e,s=!0){const r=this.sandboxes.get(e);r?(s?(r.hostContainer.setAttribute("wu-debug",""),r.hostContainer.setAttribute("wu-app",e)):(r.hostContainer.removeAttribute("wu-debug"),r.hostContainer.removeAttribute("wu-app")),t.wuDebug(`Debug mode ${s?"enabled":"disabled"} for ${e}`)):t.wuWarn(`Sandbox not found for: ${e}`)}cleanup(e){if(!e)return;const{appName:s,shadowRoot:r,hostContainer:n,jsSandbox:i}=e;t.wuDebug(`Cleaning up sandbox for: ${s}`);try{if(i&&i.isActive()&&(i.deactivate(),t.wuDebug(`JS Sandbox deactivated for ${s}`)),e.styleObserver){try{e.styleObserver.disconnect()}catch(e){t.wuWarn(`Failed to disconnect styleObserver for ${s}: ${e}`)}e.styleObserver=null}if("function"==typeof e.unsubscribeStyleChanges){try{e.unsubscribeStyleChanges()}catch(e){t.wuWarn(`Failed to unsubscribe style changes for ${s}: ${e}`)}e.unsubscribeStyleChanges=null}this.styleBridge?.unregisterFullyIsolatedApp&&this.styleBridge.unregisterFullyIsolatedApp(s),this.cleanupEventListeners(e),r&&(r.innerHTML=""),n&&(n.removeAttribute("wu-debug"),n.removeAttribute("wu-app"),n.removeAttribute("wu-no-scroll")),this.sandboxes.delete(s),this.jsSandboxes.delete(s),t.wuDebug(`Sandbox cleaned up: ${s}`)}catch(e){t.wuError(`Error cleaning up sandbox ${s}: ${e}`)}}cleanupEventListeners(e){const{shadowRoot:t}=e;if(!t)return;t.querySelectorAll("*").forEach(e=>{if(e.cloneNode){const t=e.cloneNode(!0);e.parentNode?.replaceChild(t,e)}})}getSandboxInfo(e){const t=this.sandboxes.get(e);return t?{appName:t.appName,created:t.created,hasContainer:!!t.container,hasShadowRoot:!!t.shadowRoot,elementCount:t.shadowRoot?.children?.length||0,uptime:Date.now()-t.created}:null}getStats(){return{strategy:this.sandboxStrategy,total:this.sandboxes.size,sandboxes:Array.from(this.sandboxes.keys()),jsSandboxes:Array.from(this.jsSandboxes.keys()),details:Array.from(this.sandboxes.entries()).map(([e,t])=>({name:e,uptime:Date.now()-t.created,elements:t.shadowRoot?.children?.length||0,hasJsSandbox:!!t.jsSandbox,jsSandboxActive:t.jsSandbox?.isActive()||!1}))}}cleanupAll(){t.wuDebug(`Cleaning up all ${this.sandboxes.size} sandboxes...`);for(const[e,t]of this.sandboxes)this.cleanup(t);this.styleBridge&&this.styleBridge.cleanup(),t.wuDebug("All sandboxes cleaned up")}configureStyleSharing(e){this.styleBridge&&(this.styleBridge.configure(e),t.wuDebug("StyleBridge configured"))}getStyleStats(){return this.styleBridge?this.styleBridge.getStats():null}async reinjectStyles(e){const s=this.sandboxes.get(e);if(!s||!s.shadowRoot)return void t.wuWarn(`Cannot reinject styles for ${e}`);const r=s.styleMode;if("isolated"===r)return void t.wuDebug(`Skipping reinject for ${e} (isolated mode - app manages own styles)`);if("fully-isolated"===r){t.wuDebug(`Reinjecting OWN styles for ${e} (fully-isolated)...`);const r=s.appUrl||s.manifest?.name?`/${s.manifest.name}/`:`/${e}/`,n=await this.injectOwnStylesToShadow(s.shadowRoot,e,r);return void t.wuDebug(`Reinjected ${n} own styles for ${e}`)}t.wuDebug(`Reinjecting shared styles for ${e}...`);const n=await this.styleBridge.injectStylesIntoShadow(s.shadowRoot,e,r);t.wuDebug(`Reinjected ${n} shared styles`)}async injectOwnStylesToShadow(e,s,r){if(!e)return 0;let n=0;const i=document.querySelectorAll("style"),o=s.toLowerCase(),a=[new RegExp(`packages[/\\\\]${o}[/\\\\]src[/\\\\]`,"i")];t.wuDebug(`Searching own styles for ${s}, found ${i.length} style tags in head`);let c=0;for(const e of i){(e.getAttribute("data-vite-dev-id")||"").toLowerCase().includes(o)&&c++}c>0&&t.wuDebug(`Found ${c} styles potentially matching ${s}`);for(const r of i){const i=r.getAttribute("data-vite-dev-id")||"",o=i.replace(/\\/g,"/").toLowerCase();let c=!1;if(i)for(const e of a)if(e instanceof RegExp){if(e.test(i)){c=!0;break}}else if(o.includes(e.toLowerCase())){c=!0;break}if(c){if(!e.querySelector(`style[data-vite-dev-id="${i}"]`)){const o=r.cloneNode(!0);o.setAttribute("data-wu-injected","true"),e.insertBefore(o,e.firstChild),n++;const a=i.substring(i.lastIndexOf("/")+1)||i.substring(i.lastIndexOf("\\")+1);t.wuDebug(`Injected own style for ${s}: ${a}`)}}}return t.wuDebug(`Total own styles injected for ${s}: ${n}`),n}injectAllStylesToShadow(e,s){if(!e)return 0;let r=0;const n=s.toLowerCase(),i=document.querySelectorAll("style");for(const s of i){const i=s.getAttribute("data-vite-dev-id")||"";if(!i.toLowerCase().includes(n))continue;if(e.querySelector(`style[data-vite-dev-id="${i}"]`))continue;const o=s.cloneNode(!0);o.setAttribute("data-wu-fallback","true"),e.insertBefore(o,e.firstChild),r++;const a=i.split("/").pop()||i.split("\\").pop();t.wuDebug(`FALLBACK injected: ${a}`)}return t.wuDebug(`FALLBACK: Total ${r} styles injected for ${s}`),r}}class l{constructor(){this.cache=new Map,this.schemas=new Map,this.security={maxManifestSize:102400,maxNameLength:50,maxEntryLength:200,maxExports:100,maxImports:50,maxRoutes:100,dangerousPatterns:[/\.\./,/^\/etc\//,/^\/proc\//,/^file:\/\//,/javascript:/i,/data:/i,/<script/i,/on\w+\s*=/i],blockedDomains:["evil.com","malware.com"]},this.defineSchema()}defineSchema(){this.schemas.set("wu.json",{required:["name","entry"],optional:["wu"],wu:{optional:["exports","imports","routes","permissions"],exports:"object",imports:"array",routes:"array",permissions:"array"}})}async load(e){const s=`${e}/wu.json`;t.debug(`[WuManifest] 📥 Loading manifest: ${s}`);try{if(this.cache.has(s))return t.debug(`[WuManifest] ⚡ Cache hit: ${s}`),this.cache.get(s);const r=await fetch(s,{cache:"no-cache",headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)});if(!r.ok){if(404===r.status)return t.debug(`[WuManifest] 📄 No manifest found, creating default for: ${e}`),this.createDefaultManifest(e);throw new Error(`HTTP ${r.status}: ${r.statusText}`)}const n=await r.text();if(n.length>this.security.maxManifestSize)throw new Error(`Manifest too large (${n.length} bytes, max ${this.security.maxManifestSize})`);let i;try{i=JSON.parse(n)}catch(e){throw new Error(`Invalid JSON in manifest: ${e.message}`)}const o=this.validate(i);return this.cache.set(s,o),t.debug(`[WuManifest] ✅ Manifest loaded: ${i.name}`),o}catch(t){console.error(`[WuManifest] ❌ Failed to load manifest: ${s}`,t);try{return this.createDefaultManifest(e)}catch(e){throw new Error(`Failed to load manifest from ${s}: ${t.message}`)}}}createDefaultManifest(e){const s=this.extractAppNameFromUrl(e),r={name:s,entry:"index.js",wu:{exports:{},imports:[],routes:[],permissions:[]}};return t.debug(`[WuManifest] 🔧 Created default manifest for: ${s}`),r}extractAppNameFromUrl(e){try{const t=new URL(e).pathname.split("/").filter(Boolean);return t[t.length-1]||"unknown-app"}catch{return e.replace(/[^a-zA-Z0-9-]/g,"")||"unknown-app"}}_sanitizeString(e){return"string"!=typeof e?"":e.replace(/[<>'"]/g,"").replace(/[\x00-\x1F\x7F]/g,"").trim()}_hasDangerousPatterns(e){return"string"==typeof e&&this.security.dangerousPatterns.some(t=>t.test(e))}_isUrlSafe(e){if("string"!=typeof e)return!1;if(this._hasDangerousPatterns(e))return!1;try{const t=new URL(e,"http://localhost");if(this.security.blockedDomains.some(e=>t.hostname.includes(e)))return!1}catch{if(this._hasDangerousPatterns(e))return!1}return!0}validate(e){const s=this.schemas.get("wu.json");if(!e||"object"!=typeof e||Array.isArray(e))throw new Error("Manifest must be a valid object");for(const t of s.required)if(!e[t])throw new Error(`Required field missing: ${t}`);if("string"!=typeof e.name)throw new Error("name must be a string");if(e.name.length>this.security.maxNameLength)throw new Error(`name too long (max ${this.security.maxNameLength} chars)`);if(this._hasDangerousPatterns(e.name))throw new Error("name contains dangerous patterns");if("string"!=typeof e.entry)throw new Error("entry must be a string");if(e.entry.length>this.security.maxEntryLength)throw new Error(`entry too long (max ${this.security.maxEntryLength} chars)`);if(!this._isUrlSafe(e.entry))throw new Error("entry contains dangerous patterns");if(e.wu){const t=e.wu;if(t.exports&&"object"!=typeof t.exports)throw new Error("wu.exports must be an object");if(t.exports&&Object.keys(t.exports).length>this.security.maxExports)throw new Error(`Too many exports (max ${this.security.maxExports})`);if(t.exports)for(const[e,s]of Object.entries(t.exports))if(!this._isUrlSafe(s))throw new Error(`Dangerous export path: ${e}`);if(t.imports&&!Array.isArray(t.imports))throw new Error("wu.imports must be an array");if(t.imports&&t.imports.length>this.security.maxImports)throw new Error(`Too many imports (max ${this.security.maxImports})`);if(t.routes&&!Array.isArray(t.routes))throw new Error("wu.routes must be an array");if(t.routes&&t.routes.length>this.security.maxRoutes)throw new Error(`Too many routes (max ${this.security.maxRoutes})`);if(t.permissions&&!Array.isArray(t.permissions))throw new Error("wu.permissions must be an array")}if(void 0!==e.styleMode){const s=["shared","isolated","fully-isolated","none","own-only"];s.includes(e.styleMode)||(t.warn(`[WuManifest] Invalid styleMode "${e.styleMode}", defaulting to "shared". Valid: ${s.join(", ")}`),e.styleMode="shared")}if(void 0!==e.version&&"string"!=typeof e.version&&(t.warn("[WuManifest] version must be a string, ignoring"),delete e.version),void 0!==e.folder)if("string"!=typeof e.folder)t.warn("[WuManifest] folder must be a string, ignoring"),delete e.folder;else if(this._hasDangerousPatterns(e.folder))throw new Error("folder contains dangerous patterns");return this.normalize(e)}normalize(e){const s={name:e.name.trim(),entry:this.normalizeEntry(e.entry),wu:{exports:e.wu?.exports||{},imports:e.wu?.imports||[],routes:e.wu?.routes||[],permissions:e.wu?.permissions||[]}};if(e.styleMode&&(s.styleMode=e.styleMode),e.version&&(s.version=e.version),e.folder&&(s.folder=e.folder),s.wu.exports){const e={};for(const[t,r]of Object.entries(s.wu.exports))e[t]=this.normalizeComponentPath(r);s.wu.exports=e}return s.wu.imports=s.wu.imports.filter(e=>!("string"!=typeof e||!e.includes("."))||(t.warn(`[WuManifest] Invalid import format: ${e}`),!1)),s}normalizeEntry(e){if(!e)return"index.js";let t=e.trim();return t.startsWith("./")&&(t=t.substring(2)),t.includes(".")||(t+=".js"),t}normalizeComponentPath(e){if(!e)return"";let t=e.trim();return t.startsWith("./")&&(t=t.substring(2)),t.includes(".")||(t+=".js"),t}validateDependencies(e,t){const s={valid:[],invalid:[],missing:[]};for(const r of e){const[e,n]=r.split(".");if(!e||!n){s.invalid.push({import:r,reason:'Invalid format. Use "app.component"'});continue}const i=t.get(e);if(!i){s.missing.push({import:r,app:e,reason:"App not registered"});continue}const o=i.manifest,a=o?.wu?.exports?.[n];a?s.valid.push({import:r,app:e,component:n,path:a}):s.invalid.push({import:r,reason:`Component ${n} not exported by ${e}`})}return s}create(e,t={}){const s={name:e,entry:t.entry||"index.js",wu:{exports:t.exports||{},imports:t.imports||[],routes:t.routes||[],permissions:t.permissions||[]}};return this.normalize(s)}clearCache(e){if(e){let s;try{s=new RegExp(e)}catch(s){return void t.warn(`[WuManifest] Invalid clearCache pattern: ${e} (${s.message})`)}for(const[e]of this.cache)s.test(e)&&(this.cache.delete(e),t.debug(`[WuManifest] 🗑️ Cleared cache for: ${e}`))}else this.cache.clear(),t.debug("[WuManifest] 🗑️ Manifest cache cleared completely")}getStats(){return{cached:this.cache.size,schemas:this.schemas.size,cacheKeys:Array.from(this.cache.keys())}}}class u{constructor(e=256){this.bufferSize=this.nextPowerOfTwo(e),this.mask=this.bufferSize-1,this.buffer=new Array(this.bufferSize),this.cursor=0,this.state={},this.listeners=new Map,this.patternListeners=new Map,this._taps=null,this.metrics={reads:0,writes:0,notifications:0};for(let e=0;e<this.bufferSize;e++)this.buffer[e]={path:null,value:null,timestamp:0}}get(e){if(this.metrics.reads++,!e)return this.state;const t=e.split(".");return t.every(u._isSafeKey)?t.reduce((e,t)=>e?.[t],this.state):void 0}set(e,t){if(this.metrics.writes++,e){const t=e.split(".");for(const s of t)if(!u._isSafeKey(s))throw new Error(`[WuStore] Unsafe key in path: "${s}" (path: "${e}")`)}const s=this.cursor;this.cursor=this.cursor+1;const r=s&this.mask,n=this.buffer[r];if(n.path=e,n.value=t,n.timestamp=performance.now(),this.updateState(e,t),this._taps&&this._taps.size)for(const r of this._taps)try{r(s,e,t)}catch(e){console.error("[WuStore] Tap error:",e)}return queueMicrotask(()=>{this.notify(e,t),this.notifyPatterns(e,t)}),s}tap(e){return"function"!=typeof e?()=>{}:(this._taps||(this._taps=new Set),this._taps.add(e),()=>{this._taps?.delete(e)})}hydrate(e,{notifyPaths:t}={}){this.state=e&&"object"==typeof e?e:{};const s=t||Object.keys(this.state);for(const e of s){const t=this.get(e);this.notify(e,t),this.notifyPatterns(e,t)}}on(e,t){return e.includes("*")?(this.patternListeners.has(e)||this.patternListeners.set(e,new Set),this.patternListeners.get(e).add(t),()=>{const s=this.patternListeners.get(e);s&&(s.delete(t),0===s.size&&this.patternListeners.delete(e))}):(this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>{const s=this.listeners.get(e);s&&(s.delete(t),0===s.size&&this.listeners.delete(e))})}batch(e){const t=[];for(const[s,r]of Object.entries(e))t.push(this.set(s,r));return t}getMetrics(){const e=Math.min(1,this.cursor/this.bufferSize);return{...this.metrics,bufferUtilization:e,sequenceNumber:this.cursor,bufferSize:this.bufferSize,listenerCount:this.listeners.size+this.patternListeners.size}}static _isSafeKey(e){return"__proto__"!==e&&"constructor"!==e&&"prototype"!==e}nextPowerOfTwo(e){return Math.pow(2,Math.ceil(Math.log2(e)))}updateState(e,t){if(!e)return void(this.state=t);const s=e.split(".");if(!s.every(u._isSafeKey))return;const r=s.pop();let n=this.state;for(const e of s)Object.prototype.hasOwnProperty.call(n,e)&&"object"==typeof n[e]&&null!==n[e]||(n[e]={}),n=n[e];n[r]=t}notify(e,t){this.metrics.notifications++;const s=this.listeners.get(e);s&&s.forEach(s=>{try{s(t,e)}catch(e){console.error("[WuStore] Listener error:",e)}});const r=e.split(".");for(let e=r.length-1;e>0;e--){const t=r.slice(0,e).join("."),s=this.listeners.get(t);if(s){const e=this.get(t);s.forEach(s=>{try{s(e,t)}catch(e){console.error("[WuStore] Parent listener error:",e)}})}}}notifyPatterns(e,t){for(const[s,r]of this.patternListeners)this.matchesPattern(e,s)&&r.forEach(s=>{try{s({path:e,value:t})}catch(e){console.error("[WuStore] Pattern listener error:",e)}})}matchesPattern(e,t){if("*"===t)return!0;const s=t.split(".").map(e=>"*"===e?"[^.]+":e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\.");return new RegExp(`^${s}$`).test(e)}sync(e={}){if(this._syncHandle&&!this._syncHandle._stopped)return console.warn("[WuStore] sync() already active — returning the existing handle. stop() it first to reconfigure."),this._syncHandle;const t=this;let s=null,r=null,n=!1,i=null;const o=()=>s?Promise.resolve(s):(r||(r=Promise.resolve().then(function(){return z}).then(({WuStoreSync:r})=>{if(n)return null;const i=new r(t);return i.connect(e),s=i,s}).catch(e=>(i=e,t._syncHandle===a&&(t._syncHandle=null),console.warn("[WuStore] sync() failed to connect:",e?.message||e),null))),r),a={stop(){n=!0,this._stopped=!0,t._syncHandle===a&&(t._syncHandle=null),s&&s.stop()},status:()=>s?s.status():{connected:!1,site:null,lamport:0,peers:0,tracked:0,sent:0,received:0,applied:0,ignored:0,dropped:0,loading:!n&&!i,stopped:n,error:i?String(i.message||i):null},ready:()=>o(),get connected(){return!!s&&s.status().connected},get instance(){return s},_stopped:!1};return this._syncHandle=a,o(),a}clear(){this.state={},this.listeners.clear(),this.patternListeners.clear(),this.cursor=0;for(let e=0;e<this.bufferSize;e++)this.buffer[e].path=null,this.buffer[e].value=null,this.buffer[e].timestamp=0}getRecentEvents(e=10){const t=[];for(let s=Math.max(0,this.cursor-e);s<this.cursor&&t.length<e;s++){const e=s&this.mask,r=this.buffer[e];r.path&&t.push({path:r.path,value:r.value,timestamp:r.timestamp})}return t.reverse()}}const d=new u;class h{constructor(e,t,s){this.name=e,this.url=t.url,this.container=t.container,this.keepAlive=t.keepAlive||!1,this._wu=s,this._mounted=!1,this._autoInit=!1!==t.autoInit,this._autoInit&&this._registerApp()}_registerApp(){this._wu.apps.has(this.name)||(this._wu.apps.set(this.name,{name:this.name,url:this.url,keepAlive:this.keepAlive,status:"registered"}),t.debug(`📦 App registered: ${this.name} at ${this.url}`))}async mount(e){const t=e||this.container;if(!t)throw new Error(`Container not specified for app: ${this.name}`);return this._wu.isInitialized?this._wu.apps.get(this.name)?.manifest||await this._wu.registerApp({name:this.name,url:this.url,keepAlive:this.keepAlive}):await this._wu.init({apps:[{name:this.name,url:this.url}]}),await this._wu.mount(this.name,t),this._mounted=!0,this}async unmount(e={}){return this._mounted||this._wu.isHidden(this.name)?(await this._wu.unmount(this.name,e),this._mounted=!1,this):(t.warn(`⚠️ App ${this.name} is not mounted`),this)}async hide(){return this._mounted?(await this._wu.hide(this.name),this._mounted=!1,this):(t.warn(`⚠️ App ${this.name} is not mounted`),this)}async show(){return this._wu.isHidden(this.name)?(await this._wu.show(this.name),this._mounted=!0,this):(t.warn(`⚠️ App ${this.name} is not in keep-alive state`),this)}async remount(e){return await this.unmount({force:!0}),await this.mount(e),this}get isMounted(){return this._mounted&&this._wu.mounted?.has(this.name)}get isHidden(){return this._wu.isHidden(this.name)}get info(){return{name:this.name,url:this.url,container:this.container,mounted:this.isMounted,status:this._wu.apps.get(this.name)?.status||"unknown"}}async reload(){return t.debug(`🔄 Reloading app: ${this.name}`),await this.unmount(),this._wu.loader?.clearCache&&this._wu.loader.clearCache(this.name),this._wu.manifest?.clearCache&&this._wu.manifest.clearCache(this.name),await this.mount(),t.debug(`✅ App reloaded: ${this.name}`),this}async verify(){const e=document.querySelector(this.container),t=null!==e?.shadowRoot,s=(e?.shadowRoot?.children?.length||0)>0;return{name:this.name,mounted:this.isMounted,container:{found:!!e,selector:this.container,hasShadowDOM:t,hasContent:s},wu:{registered:this._wu.apps.has(this.name),mountedInWu:this._wu.mounted?.has(this.name)}}}async start(e){return await this.mount(e)}async stop(){return await this.unmount()}async destroy(){await this.unmount({force:!0}),this._wu.apps.delete(this.name),this._mounted=!1,t.debug(`🗑️ App destroyed: ${this.name}`)}}class p{constructor(e={}){this.config={maxSize:e.maxSize||50,maxItems:e.maxItems||100,defaultTTL:e.defaultTTL||36e5,persistent:!1!==e.persistent,storage:e.storage||"memory"};("localStorage"===this.config.storage||"sessionStorage"===this.config.storage)&&this.config.persistent&&this.config.maxSize>5&&t.wuWarn(`[WuCache] maxSize=${this.config.maxSize}MB configured with ${this.config.storage}, but browsers typically cap that backing at ~5MB per origin. In-memory LRU will evict before storage fills. Consider maxSize ≤ 5 or storage: 'memory' for a large in-memory cache.`),this.rateLimiting={enabled:!1!==e.rateLimiting,maxOpsPerSecond:e.maxOpsPerSecond||100,windowMs:1e3,cooldownMs:e.cooldownMs||5e3,operations:[],inCooldown:!1,cooldownUntil:0},this._rateLimitNotified=!1,this.memoryCache=new Map,this.accessOrder=new Map,this.stats={hits:0,misses:0,sets:0,evictions:0,size:0,rateLimited:0}}_checkRateLimit(){if(!this.rateLimiting.enabled)return!0;const e=Date.now();if(this.rateLimiting.inCooldown){if(e<this.rateLimiting.cooldownUntil)return this.stats.rateLimited++,!1;this.rateLimiting.inCooldown=!1,this._rateLimitNotified=!1,this.rateLimiting.operations=[]}const s=e-this.rateLimiting.windowMs;return this.rateLimiting.operations=this.rateLimiting.operations.filter(e=>e>s),this.rateLimiting.operations.length>=this.rateLimiting.maxOpsPerSecond?(this.rateLimiting.inCooldown=!0,this.rateLimiting.cooldownUntil=e+this.rateLimiting.cooldownMs,this.stats.rateLimited++,t.warn(`[WuCache] 🚫 Rate limit exceeded. Cooldown for ${this.rateLimiting.cooldownMs}ms`),!1):(this.rateLimiting.operations.push(e),!0)}_onRateLimited(e,s){if(!this._rateLimitNotified){const r=Math.max(0,this.rateLimiting.cooldownUntil-Date.now());t.warn(`[WuCache] Rate limited: ${e} for key "${s}" rejected. ${r}ms remaining in cooldown.`),this._rateLimitNotified=!0}return{rateLimited:!0,operation:e,key:s}}getRateLimitStatus(){const e=Date.now();return{enabled:this.rateLimiting.enabled,inCooldown:this.rateLimiting.inCooldown,cooldownRemaining:this.rateLimiting.inCooldown?Math.max(0,this.rateLimiting.cooldownUntil-e):0,currentOps:this.rateLimiting.operations.length,maxOps:this.rateLimiting.maxOpsPerSecond,rateLimited:this.stats.rateLimited}}get(e){if(!this._checkRateLimit())return this._onRateLimited("get",e),null;if(this.memoryCache.has(e)){const t=this.memoryCache.get(e);return this.isExpired(t)?(this.delete(e),this.stats.misses++,null):(this.accessOrder.set(e,Date.now()),this.stats.hits++,t.value)}if(this.config.persistent){const t=this.getFromStorage(e);if(t)return this.isExpired(t)?(this.delete(e),this.stats.misses++,null):(!1!==this.ensureSpace(t.size||0,{demoteOnly:!0})&&(this.memoryCache.set(e,t),this.accessOrder.set(e,Date.now()),this.stats.size+=t.size||0),this.stats.hits++,t.value)}return this.stats.misses++,null}set(e,s,r){if(!this._checkRateLimit())return this._onRateLimited("set",e),!1;try{const n={key:e,value:s,timestamp:Date.now(),ttl:r||this.config.defaultTTL,size:this.estimateSize(s)};if(!1===this.ensureSpace(n.size))return t.warn(`[WuCache] ⚠️ Cannot cache item: ${e} (too large)`),!1;const i=this.memoryCache.get(e);return i&&(this.stats.size-=i.size),this.memoryCache.set(e,n),this.accessOrder.set(e,Date.now()),this.config.persistent&&this.saveToStorage(e,n),this.stats.sets++,this.stats.size+=n.size,!0}catch(e){return t.warn("[WuCache] ⚠️ Failed to set cache:",e),!1}}delete(e){const t=this.memoryCache.get(e);t&&(this.stats.size-=t.size),this.memoryCache.delete(e),this.accessOrder.delete(e),this.config.persistent&&this.deleteFromStorage(e)}clear(){this.memoryCache.clear(),this.accessOrder.clear(),this.stats.size=0,this.config.persistent&&this.clearStorage(),t.debug("[WuCache] 🧹 Cache cleared")}isExpired(e){return!!e.ttl&&Date.now()-e.timestamp>e.ttl}estimateSize(e){if("string"==typeof e)return 2*e.length;if("object"==typeof e)try{return 2*JSON.stringify(e).length}catch{return 1e3}return 100}ensureSpace(e,{demoteOnly:s=!1}={}){const r=1024*this.config.maxSize*1024;if(e>r)return t.warn(`[WuCache] ⚠️ Item size (${e}) exceeds max cache size (${r}). Skipping.`),!1;const n=this.config.maxItems+10;let i=0;for(;(this.stats.size+e>r||this.memoryCache.size>=this.config.maxItems)&&i<n;){if(i++,0===this.memoryCache.size){t.warn("[WuCache] ⚠️ Cache empty but still no space. Breaking loop.");break}let e=null,r=1/0;for(const[t,s]of this.accessOrder)s<r&&(r=s,e=t);if(!e)break;if(t.debug(`[WuCache] 🗑️ Evicting LRU entry: ${e}`),s){const t=this.memoryCache.get(e);t&&(this.stats.size-=t.size),this.memoryCache.delete(e),this.accessOrder.delete(e)}else this.delete(e);this.stats.evictions++}return i>=n&&console.error(`[WuCache] 🚨 Max eviction iterations reached (${n}). Possible infinite loop prevented.`),!0}getFromStorage(e){try{const t=this.getStorage().getItem(`wu_cache_${e}`);if(t)return JSON.parse(t)}catch(e){t.warn("[WuCache] ⚠️ Failed to get from storage:",e)}return null}saveToStorage(e,s){const r=this.getStorage();try{r.setItem(`wu_cache_${e}`,JSON.stringify(s))}catch(n){t.warn("[WuCache] ⚠️ Storage full, cleaning old entries"),this.cleanOldStorageEntries();try{r.setItem(`wu_cache_${e}`,JSON.stringify(s))}catch{t.warn("[WuCache] ⚠️ Failed to save to storage after cleanup")}}}deleteFromStorage(e){try{this.getStorage().removeItem(`wu_cache_${e}`)}catch(e){t.warn("[WuCache] ⚠️ Failed to delete from storage:",e)}}clearStorage(){try{const e=this.getStorage();Object.keys(e).forEach(t=>{t.startsWith("wu_cache_")&&e.removeItem(t)})}catch(e){t.warn("[WuCache] ⚠️ Failed to clear storage:",e)}}cleanOldStorageEntries(){try{const e=this.getStorage(),s=Object.keys(e),r=[];s.forEach(t=>{if(t.startsWith("wu_cache_"))try{const s=JSON.parse(e.getItem(t));r.push({key:t,timestamp:s.timestamp})}catch{}}),r.sort((e,t)=>e.timestamp-t.timestamp);const n=Math.ceil(.25*r.length);for(let t=0;t<n;t++)e.removeItem(r[t].key);t.debug(`[WuCache] 🧹 Cleaned ${n} old storage entries`)}catch(e){t.warn("[WuCache] ⚠️ Failed to clean old storage entries:",e)}}getStorage(){return"localStorage"===this.config.storage?window.localStorage:"sessionStorage"===this.config.storage?window.sessionStorage:{getItem:()=>null,setItem:()=>{},removeItem:()=>{},clear:()=>{}}}getStats(){const e=this.stats.hits+this.stats.misses>0?(this.stats.hits/(this.stats.hits+this.stats.misses)*100).toFixed(2):0;return{...this.stats,hitRate:`${e}%`,items:this.memoryCache.size,sizeMB:(this.stats.size/1024/1024).toFixed(2)}}configure(e){this.config={...this.config,...e}}}class m{constructor(){this.listeners=new Map,this.history=[],this._taps=null,this._wildcardCache=new Map,this.authorizedApps=new Map,this.trustedEvents=new Set(["wu:*","system:*"]),this.trustedApps=new Set(["wu-ai","wu-mcp-bridge","wu-core","plugin"]),this._internalTokens=new Map;for(const e of this.trustedApps)this._internalTokens.set(e,this._mintInternalToken());const e="undefined"!=typeof process&&"production"===process.env?.NODE_ENV;this.config={maxHistory:100,enableReplay:!0,enableWildcards:!0,logEvents:!1,strictMode:e,validateOrigin:!0},this._permissiveWarned=!1,this.stats={emitted:0,subscriptions:0,rejected:0}}registerApp(e,t={}){const s=t.token||this._generateToken();return this.authorizedApps.set(e,{token:s,permissions:t.permissions||["*"],registeredAt:Date.now()}),s}unregisterApp(e){this.authorizedApps.delete(e)}_validateOrigin(e,t,s){if(this._isSystemEvent(e))return!0;if(!this.config.strictMode)return!0;if(this.trustedApps.has(t)){return s===this._internalTokens.get(t)}const r=this.authorizedApps.get(t);return!!r&&((!s||r.token===s)&&this._hasPermission(r.permissions,e))}_hasPermission(e,t){return!!e.includes("*")||e.some(e=>e===t||!!e.includes("*")&&this.matchesWildcard(t,e))}_isSystemEvent(e){return e.startsWith("wu:")||e.startsWith("system:")||e.startsWith("app:")}getInternalToken(e){return this.trustedApps.has(e)&&this._internalTokens.get(e)||null}_mintInternalToken(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return`wu-int-${crypto.randomUUID()}`;const e=()=>Math.random().toString(36).slice(2,11);return`wu-int-${Date.now().toString(36)}-${e()}${e()}`}_generateToken(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return`wu_${crypto.randomUUID()}`;const e=()=>Math.random().toString(36).slice(2,11);return`wu_${Date.now().toString(36)}_${e()}${e()}`}_warnPermissiveMode(){this._permissiveWarned||(this._permissiveWarned=!0,t.warn("[WuEventBus] strictMode is disabled. Events are emitted without authorization checks. Enable strictMode for production by calling enableStrictMode() or setting NODE_ENV=production."))}emit(e,s,r={}){const n=r.appName||"unknown";if(this.config.strictMode||this._warnPermissiveMode(),this.config.validateOrigin&&this.config.strictMode&&!this._validateOrigin(e,n,r.token))return this.stats.rejected++,t.warn(`[WuEventBus] 🚫 Event rejected: ${e} from ${n} (unauthorized)`),!1;const i={name:e,data:s,timestamp:r.timestamp||Date.now(),appName:n,meta:r.meta||{},verified:this.authorizedApps.has(n)};if(this.config.enableReplay&&!1!==r.history&&this.addToHistory(i),this._taps&&this._taps.size)for(const e of this._taps)try{e(i)}catch(e){console.error("[WuEventBus] Tap error:",e)}this.config.logEvents&&t.debug(`[WuEventBus] 📢 ${e}`,s);const o=this.listeners.get(e);return o&&o.forEach(t=>{try{t(i)}catch(t){console.error(`[WuEventBus] ❌ Error in listener for ${e}:`,t)}}),this.config.enableWildcards&&this.notifyWildcardListeners(e,i),this.stats.emitted++,!0}tap(e){return"function"!=typeof e?()=>{}:(this._taps||(this._taps=new Set),this._taps.add(e),()=>{this._taps?.delete(e)})}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),this.stats.subscriptions++,()=>this.off(e,t)}off(e,t){const s=this.listeners.get(e);s&&(s.delete(t),0===s.size&&this.listeners.delete(e),this.stats.subscriptions--)}once(e,t){const s=r=>{this.off(e,s),t(r)};return this.on(e,s)}notifyWildcardListeners(e,t){for(const[s,r]of this.listeners)this.matchesWildcard(e,s)&&r.forEach(e=>{try{e(t)}catch(e){console.error(`[WuEventBus] ❌ Error in wildcard listener for ${s}:`,e)}})}matchesWildcard(e,t){if(!t.includes("*"))return!1;let s=this._wildcardCache.get(t);if(!s){const e=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");s=new RegExp(`^${e}$`),this._wildcardCache.set(t,s)}return s.test(e)}addToHistory(e){this.history.push(e),this.history.length>this.config.maxHistory&&this.history.shift()}replay(e,t){this.history.filter(t=>e.includes("*")?this.matchesWildcard(t.name,e):t.name===e).forEach(e=>{try{t(e)}catch(e){console.error("[WuEventBus] ❌ Error replaying event:",e)}})}clearHistory(e){this.history=e?this.history.filter(t=>e.includes("*")?!this.matchesWildcard(t.name,e):t.name!==e):[]}getStats(){return{...this.stats,activeListeners:this.listeners.size,historySize:this.history.length,authorizedApps:this.authorizedApps.size,listenersByEvent:Array.from(this.listeners.entries()).map(([e,t])=>({event:e,listeners:t.size}))}}configure(e){this.config={...this.config,...e}}enableStrictMode(){this.config.strictMode=!0}disableStrictMode(){this.config.strictMode=!1}removeAll(){this.listeners.clear(),this.stats.subscriptions=0}}const f="wu:",g="undefined"!=typeof performance&&"function"==typeof performance.mark&&"function"==typeof performance.measure;class w{constructor(){this.metrics=new Map,this.measurements=[],this.marks=new Map,this.config={enabled:!0,maxMeasurements:1e3,devtoolsTimeline:g},this.thresholds={mount:3e3,unmount:1e3,load:5e3},t.debug("[WuPerformance] ⚡ Framework performance monitoring initialized")}_entryName(e,t,s=""){return`${f}${e}:${t}${s}`}startMeasure(e,s="global"){const r=`${s}:${e}:start`;if(this.marks.set(r,performance.now()),this.config.devtoolsTimeline)try{performance.mark(this._entryName(s,e,":start"),{detail:{appName:s,name:e,source:"wu-framework",phase:"start"}})}catch{try{performance.mark(this._entryName(s,e,":start"))}catch{}}t.debug(`[WuPerformance] 📊 Measure started: ${r}`)}endMeasure(e,s="global"){const r=`${s}:${e}:start`,n=this.marks.get(r);if(!n)return 0;const i=performance.now(),o=i-n;if(this.marks.delete(r),this.config.devtoolsTimeline){const t=this._entryName(s,e),r=this._entryName(s,e,":start"),a=this._entryName(s,e,":end");try{performance.mark(a,{detail:{appName:s,name:e,source:"wu-framework",phase:"end",duration:o}}),performance.measure(t,{start:n,end:i,detail:{appName:s,name:e,source:"wu-framework",duration:o}})}catch{try{performance.mark(a),performance.measure(t,r,a)}catch{}}}return this.recordMeasurement({name:e,appName:s,duration:o,timestamp:Date.now(),type:"duration"}),this.checkThreshold(e,o)&&t.warn(`[WuPerformance] ⚠️ Threshold exceeded for ${e}: ${o.toFixed(2)}ms`),t.debug(`[WuPerformance] ⏹️ Measure ended: ${r} (${o.toFixed(2)}ms)`),o}recordMeasurement(e){this.measurements.push(e),this.measurements.length>this.config.maxMeasurements&&this.measurements.shift(),this.metrics.has(e.appName)||this.metrics.set(e.appName,{appName:e.appName,measurements:[],stats:{}});const t=this.metrics.get(e.appName);t.measurements.push(e),t.measurements.length>this.config.maxMeasurements&&t.measurements.shift(),this.calculateStats(e.appName)}calculateStats(e){const t=this.metrics.get(e);if(!t)return;const s=t.measurements;if(0===s.length)return;const r={};s.forEach(e=>{r[e.name]||(r[e.name]=[]),r[e.name].push(e.duration)}),t.stats={},Object.entries(r).forEach(([e,s])=>{t.stats[e]={count:s.length,avg:s.reduce((e,t)=>e+t,0)/s.length,min:Math.min(...s),max:Math.max(...s),last:s[s.length-1]}})}checkThreshold(e,t){const s=this.thresholds[e];return s&&t>s}generateReport(){const e={timestamp:Date.now(),totalMeasurements:this.measurements.length,apps:{}};for(const[t,s]of this.metrics)e.apps[t]={measurementCount:s.measurements.length,stats:s.stats};return e}getDevToolsEntries(e={}){if(!g)return[];const{type:t="all",appName:s}=e,r=s?`${f}${s}:`:f,n=e=>e.name.startsWith(r),i=[];if("all"===t||"mark"===t)try{i.push(...performance.getEntriesByType("mark").filter(n))}catch{}if("all"===t||"measure"===t)try{i.push(...performance.getEntriesByType("measure").filter(n))}catch{}return i}observe(e,s={}){if("undefined"==typeof PerformanceObserver||"function"!=typeof e)return()=>{};const{type:r="measure"}=s,n="all"===r?["mark","measure"]:[r];let i;try{i=new PerformanceObserver(s=>{for(const r of s.getEntries())if(r.name.startsWith(f))try{e(r)}catch(e){t.warn(`[WuPerformance] observe callback threw: ${e?.message}`)}}),i.observe({entryTypes:n})}catch(e){return t.warn(`[WuPerformance] observe() unavailable: ${e?.message}`),()=>{}}return()=>{try{i.disconnect()}catch{}}}getMetrics(e){return this.metrics.get(e)||null}getAllMetrics(){const e={};for(const[t,s]of this.metrics)e[t]=s;return e}clearMetrics(e){e?(this.metrics.delete(e),this.measurements=this.measurements.filter(t=>t.appName!==e)):(this.metrics.clear(),this.measurements=[]),this._clearTimelineEntries(e),t.debug("[WuPerformance] 🧹 Metrics cleared"+(e?` for ${e}`:""))}_clearTimelineEntries(e){if(!g)return;const t=e?`${f}${e}:`:f;try{for(const e of performance.getEntriesByType("mark"))e.name.startsWith(t)&&performance.clearMarks(e.name);for(const e of performance.getEntriesByType("measure"))e.name.startsWith(t)&&performance.clearMeasures(e.name)}catch{}}configure(e){this.config={...this.config,...e},e.thresholds&&(this.thresholds={...this.thresholds,...e.thresholds})}}class y{constructor(e,t={}){this._core=e,this.plugins=new Map,this.hooks=new Map,this.availableHooks=["beforeInit","afterInit","beforeMount","afterMount","beforeUnmount","afterUnmount","onError","onDestroy"],this.availablePermissions=["mount","events","store","apps","config","unsafe"],this.hookTimeout=t.hookTimeout||5e3,this.availableHooks.forEach(e=>{this.hooks.set(e,[])})}_createSandboxedApi(e){const s={version:this._core.version,info:this._core.info,getAppInfo:e=>{const t=this._core.mounted.get(e);return t?{name:e,state:t.state,timestamp:t.timestamp}:null},getMountedApps:()=>Array.from(this._core.mounted.keys()),getStats:()=>this._core.getStats()};if(e.includes("events")||e.includes("unsafe")){const e=this._core.eventBus.getInternalToken?.("plugin")||null;s.emit=(t,s)=>this._core.eventBus.emit(t,s,{appName:"plugin",token:e}),s.on=(e,t)=>this._core.eventBus.on(e,t),s.off=(e,t)=>this._core.eventBus.off(e,t)}return(e.includes("store")||e.includes("unsafe"))&&(s.getState=e=>this._core.store.get(e),s.setState=(e,t)=>this._core.store.set(e,t)),(e.includes("mount")||e.includes("unsafe"))&&(s.mount=(e,t)=>this._core.mount(e,t),s.unmount=e=>this._core.unmount(e)),(e.includes("config")||e.includes("unsafe"))&&(s.configure=e=>{const t=["debug","logLevel"],s={};for(const r of t)r in e&&(s[r]=e[r]);Object.assign(this._core,s)}),e.includes("unsafe")&&(s._unsafeCore=this._core,t.warn("[WuPlugin] ⚠️ Plugin has unsafe access to core!")),y._deepFreeze(s)}static _deepFreeze(e,t){if(null==e)return e;if(!("object"==typeof e))return e;const s=Object.getPrototypeOf(e)===Object.prototype||null===Object.getPrototypeOf(e),r=Array.isArray(e);if(!s&&!r)return e;if(t||(t=new WeakSet),t.has(e))return e;t.add(e);const n=Object.keys(e);for(let s=0;s<n.length;s++){const r=e[n[s]];null!=r&&"object"==typeof r&&y._deepFreeze(r,t)}return Object.freeze(e)}_validatePlugin(e){if(!e||"object"!=typeof e)throw new Error("[WuPlugin] Invalid plugin: must be an object");if(!e.name||"string"!=typeof e.name)throw new Error("[WuPlugin] Invalid plugin: must have a name (string)");if(e.name.length>50)throw new Error("[WuPlugin] Invalid plugin: name too long (max 50 chars)");for(const t of this.availableHooks)if(e[t]&&"function"!=typeof e[t])throw new Error(`[WuPlugin] Invalid plugin: ${t} must be a function`);if(e.permissions){if(!Array.isArray(e.permissions))throw new Error("[WuPlugin] Invalid plugin: permissions must be an array");for(const t of e.permissions)if(!this.availablePermissions.includes(t))throw new Error(`[WuPlugin] Invalid permission: ${t}`)}return!0}use(e,s={}){if("function"==typeof e&&(e=e(s)),this._validatePlugin(e),this.plugins.has(e.name))return void t.warn(`[WuPlugin] Plugin "${e.name}" already installed`);const r=e.permissions||["events"],n=this._createSandboxedApi(r);if(e.install)try{e.install(n,s)}catch(t){throw console.error(`[WuPlugin] Error installing "${e.name}":`,t),t}const i=[];this.availableHooks.forEach(t=>{if("function"==typeof e[t]){const s=this._wrapHook(e[t].bind(e),e.name,t);this.registerHook(t,s),i.push({hookName:t,callback:s})}}),this.plugins.set(e.name,{plugin:e,options:s,permissions:r,sandboxedApi:n,registeredHooks:i,installedAt:Date.now()}),t.debug(`[WuPlugin] ✅ Plugin "${e.name}" installed (permissions: ${r.join(", ")})`)}_wrapHook(e,t,s){return async r=>{const n=new Promise((e,r)=>{setTimeout(()=>{r(new Error(`Plugin "${t}" hook "${s}" timed out after ${this.hookTimeout}ms`))},this.hookTimeout)});try{return await Promise.race([e(r),n])}catch(e){return void console.error(`[WuPlugin] Error in ${t}.${s}:`,e)}}}registerHook(e,s){this.hooks.has(e)?this.hooks.get(e).push(s):t.warn(`[WuPlugin] Unknown hook: ${e}`)}async callHook(e,t){const s=[...this.hooks.get(e)||[]];for(const r of s)try{if(!1===await r(t))return!1}catch(t){console.error(`[WuPlugin] Error in hook ${e}:`,t)}return!0}uninstall(e){const s=this.plugins.get(e);if(!s)return void t.warn(`[WuPlugin] Plugin "${e}" not found`);const{plugin:r,sandboxedApi:n,registeredHooks:i}=s;if(r.uninstall)try{r.uninstall(n)}catch(t){console.error(`[WuPlugin] Error uninstalling "${e}":`,t)}if(i)for(const{hookName:e,callback:t}of i){const s=this.hooks.get(e);if(s){const e=s.indexOf(t);e>-1&&s.splice(e,1)}}this.plugins.delete(e),t.debug(`[WuPlugin] ✅ Plugin "${e}" uninstalled`)}getPlugin(e){return this.plugins.get(e)?.plugin}getStats(){return{totalPlugins:this.plugins.size,plugins:Array.from(this.plugins.entries()).map(([e,t])=>({name:e,permissions:t.permissions,installedAt:t.installedAt})),hooks:Array.from(this.hooks.entries()).map(([e,t])=>({name:e,callbacks:t.length}))}}cleanup(){for(const[e]of this.plugins)this.uninstall(e)}}class _{constructor(e){this.core=e,this.strategies=new Map,this.loadingQueue=[],this.isIdle=!1,this._idleHandle=null,this._idleFallback=null,this._destroyed=!1,this.registerDefaultStrategies(),this.setupIdleCallback(),t.debug("[WuStrategies] 🎯 Loading strategies initialized")}registerDefaultStrategies(){this.register("lazy",{shouldPreload:!1,load:async(e,s)=>{t.debug(`[Strategy:Lazy] Loading ${e} on demand (no preload)`)}}),this.register("eager",{shouldPreload:!0,priority:"high",load:async(e,s)=>{t.debug(`[Strategy:Eager] Preloading ${e} immediately`);const r=this.core.apps.get(e);if(r){const s=await this.core.resolveModulePath(r);await import(s),t.debug(`[Strategy:Eager] ✅ ${e} preloaded`)}}}),this.register("preload",{shouldPreload:!0,priority:"medium",load:async(e,s)=>{t.debug(`[Strategy:Preload] Using resource hints for ${e}`);const r=this.core.apps.get(e);if(r){const s=await this.core.resolveModulePath(r),n=document.createElement("link");n.rel="prefetch",n.href=s,n.as="script",document.head.appendChild(n),t.debug(`[Strategy:Preload] ✅ Resource hint added for ${e}`)}}}),this.register("speculate",{shouldPreload:!0,priority:"medium",load:async(e,t)=>{this.core.prefetcher&&await this.core.prefetcher.prefetch(e,{eagerness:t.eagerness||"moderate"})}}),this.register("idle",{shouldPreload:!1,load:async(e,s)=>(t.debug(`[Strategy:Idle] Queueing ${e} for idle loading`),new Promise(t=>{this.loadingQueue.push({appName:e,config:s,resolve:t}),this.isIdle&&this.processIdleQueue()}))})}register(e,s){if(!s.load||"function"!=typeof s.load)throw new Error("[WuStrategies] Strategy must have a load function");this.strategies.set(e,{name:e,shouldPreload:s.shouldPreload||!1,priority:s.priority||"low",load:s.load}),t.debug(`[WuStrategies] Strategy "${e}" registered`)}async load(e,s){const r=s.strategy||"lazy",n=this.strategies.get(r);return n?await n.load(e,s):(t.warn(`[WuStrategies] Strategy "${r}" not found, using lazy`),await this.strategies.get("lazy").load(e,s))}async preload(e){const s=e.filter(e=>{const s=this.strategies.get(e.strategy||"lazy");return s?s.shouldPreload:(t.warn(`[WuStrategies] Strategy "${e.strategy}" not found, using lazy`),!1)});s.sort((e,t)=>{const s={high:0,medium:1,low:2},r=this.strategies.get(e.strategy)?.priority||"low",n=this.strategies.get(t.strategy)?.priority||"low";return s[r]-s[n]}),t.debug(`[WuStrategies] Preloading ${s.length} apps`);for(const e of s)try{await this.load(e.name,e)}catch(t){console.error(`[WuStrategies] Failed to preload ${e.name}:`,t)}}setupIdleCallback(){if("undefined"!=typeof window)if("requestIdleCallback"in window){const e=t=>{this._destroyed||(this.isIdle=!0,this.processIdleQueue(t),this._idleHandle=requestIdleCallback(e))};this._idleHandle=requestIdleCallback(e)}else this._idleFallback=setTimeout(()=>{this._destroyed||(this.isIdle=!0,this.processIdleQueue())},2e3)}async processIdleQueue(e){for(;this.loadingQueue.length>0&&!(e&&e.timeRemaining()<=0);){const e=this.loadingQueue.shift();try{const s=this.core.apps.get(e.appName);if(s){const r=await this.core.resolveModulePath(s);await import(r),t.debug(`[Strategy:Idle] ✅ ${e.appName} loaded during idle time`),e.resolve(!0)}else e.resolve(null)}catch(t){console.error(`[Strategy:Idle] Failed to load ${e.appName}:`,t),e.resolve(null)}}}getStats(){return{totalStrategies:this.strategies.size,strategies:Array.from(this.strategies.keys()),idleQueueSize:this.loadingQueue.length,isIdle:this.isIdle}}cleanup(){this._destroyed=!0,null!=this._idleHandle&&"function"==typeof cancelIdleCallback&&(cancelIdleCallback(this._idleHandle),this._idleHandle=null),null!=this._idleFallback&&(clearTimeout(this._idleFallback),this._idleFallback=null);for(const e of this.loadingQueue)try{e.resolve(null)}catch{}this.loadingQueue=[],t.debug("[WuStrategies] 🧹 Strategies cleaned up")}}class b{constructor(e){this.core=e,this.handlers=[],this.errorLog=[],this.maxErrorLog=100,this.config={maxRetries:3,retryDelay:1e3,showErrorUI:!0},this.registerDefaultHandlers(),t.debug("[WuErrorBoundary] 🛡️ Error boundary initialized")}registerDefaultHandlers(){this.register({name:"network",canHandle:e=>"TypeError"===e.name&&(e.message.includes("fetch")||e.message.includes("network")),handle:async(e,s)=>{if(t.debug("[ErrorHandler:Network] Handling network error"),s.retryCount<this.config.maxRetries){const e=this.config.retryDelay*Math.pow(2,s.retryCount);return t.debug(`[ErrorHandler:Network] Retrying in ${e}ms...`),await new Promise(t=>setTimeout(t,e)),{recovered:!0,action:"retry",retryCount:s.retryCount+1}}return{recovered:!1,action:"fallback",message:"Network error: Please check your connection"}}}),this.register({name:"script-load",canHandle:e=>"Error"===e.name&&(e.message.includes("Loading")||e.message.includes("Failed to fetch")),handle:async(e,s)=>(t.debug("[ErrorHandler:ScriptLoad] Handling script load error"),s.fallbackUrl?(t.debug("[ErrorHandler:ScriptLoad] Trying fallback URL"),{recovered:!0,action:"use-fallback-url",url:s.fallbackUrl}):{recovered:!1,action:"fallback",message:"Failed to load microfrontend"})}),this.register({name:"mount",canHandle:e=>e.message&&e.message.includes("mount"),handle:async(e,s)=>{if(t.debug("[ErrorHandler:Mount] Handling mount error"),s.retryCount<2){t.debug("[ErrorHandler:Mount] Cleaning up and retrying...");try{await this.core.unmount(s.appName)}catch(e){t.warn("[ErrorHandler:Mount] Cleanup failed:",e)}return await new Promise(e=>setTimeout(e,500)),{recovered:!0,action:"retry",retryCount:s.retryCount+1}}return{recovered:!1,action:"fallback",message:"Failed to mount application"}}}),this.register({name:"timeout",canHandle:e=>"TimeoutError"===e.name||e.message.includes("timeout"),handle:async(e,s)=>(t.debug("[ErrorHandler:Timeout] Handling timeout error"),s.retryCount<2?{recovered:!0,action:"retry-with-longer-timeout",timeout:2*(s.timeout||5e3),retryCount:s.retryCount+1}:{recovered:!1,action:"fallback",message:"Operation timed out"})}),this.register({name:"generic",canHandle:()=>!0,handle:async(e,s)=>(t.debug("[ErrorHandler:Generic] Handling generic error"),{recovered:!1,action:"fallback",message:e.message||"An unexpected error occurred"})})}register(e){if(!e.name||!e.canHandle||!e.handle)throw new Error("[WuErrorBoundary] Handler must have name, canHandle, and handle");this.handlers.push(e),t.debug(`[WuErrorBoundary] Handler "${e.name}" registered`)}async handle(e,s={}){s={retryCount:0,timestamp:Date.now(),...s},this.logError(e,s);for(const r of this.handlers)try{if(r.canHandle(e,s)){t.debug(`[WuErrorBoundary] Using handler: ${r.name}`);const n=await r.handle(e,s);return n.recovered?(t.debug(`[WuErrorBoundary] ✅ Error recovered by ${r.name}`),n):("fallback"===n.action&&this.config.showErrorUI&&this.renderFallback(s,n),n)}}catch(e){console.error(`[WuErrorBoundary] Handler "${r.name}" failed:`,e)}return console.error("[WuErrorBoundary] ❌ No handler could handle the error"),{recovered:!1,action:"unhandled",message:"Unhandled error"}}renderFallback(e,s){if(!e.container)return void t.warn("[WuErrorBoundary] No container to render fallback");const r="string"==typeof e.container?document.querySelector(e.container):e.container;if(!r)return;r.innerHTML="";const n=document.createElement("div");n.className="wu-error-boundary",Object.assign(n.style,{padding:"2rem",borderRadius:"8px",background:"#fff3cd",border:"1px solid #ffc107",color:"#856404",fontFamily:"system-ui, -apple-system, sans-serif",textAlign:"center"});const i=document.createElement("div");i.textContent="⚠️",i.style.fontSize="3rem",i.style.marginBottom="1rem";const o=document.createElement("h3");o.textContent="Application Error",o.style.margin="0 0 0.5rem 0";const a=document.createElement("p");a.textContent=s.message||"An error occurred",a.style.margin="0 0 1rem 0";const c=document.createElement("button");c.textContent="🔄 Reload",Object.assign(c.style,{padding:"0.5rem 1rem",background:"#ffc107",border:"none",borderRadius:"4px",cursor:"pointer",fontWeight:"bold",color:"#000"}),c.addEventListener("click",()=>window.location.reload()),n.appendChild(i),n.appendChild(o),n.appendChild(a),n.appendChild(c),r.appendChild(n)}logError(e,t){const s=e.stack?e.stack.split("\n").slice(0,5).join("\n"):"",r={};for(const e of Object.keys(t)){const s=t[e];r[e]="string"==typeof s||"number"==typeof s||"boolean"==typeof s||null===s?s:String(s)}const n={error:{name:e.name,message:e.message,stack:s},context:r,timestamp:Date.now()};this.errorLog.push(n),this.errorLog.length>this.maxErrorLog&&this.errorLog.shift()}getErrorLog(e=10){return this.errorLog.slice(-e)}getStats(){const e={};return this.errorLog.forEach(t=>{const s=t.error.name||"Unknown";e[s]=(e[s]||0)+1}),{totalErrors:this.errorLog.length,handlers:this.handlers.length,errorsByType:e,recentErrors:this.getErrorLog(5)}}configure(e){this.config={...this.config,...e}}cleanup(){this.errorLog=[],this.handlers=[],t.debug("[WuErrorBoundary] 🧹 Error boundary cleaned up")}}class v{constructor(e){this.core=e,this.hooks=new Map,this.executionLog=[],this.maxLogSize=100,this.lifecyclePhases=["beforeInit","afterInit","beforeLoad","afterLoad","beforeMount","afterMount","beforeUpdate","afterUpdate","beforeUnmount","afterUnmount","beforeDestroy","afterDestroy"],this.lifecyclePhases.forEach(e=>{this.hooks.set(e,[])}),t.debug("[WuHooks] 🪝 Lifecycle hooks initialized")}use(e,s,r={}){if(!this.hooks.has(e))throw new Error(`[WuHooks] Unknown lifecycle phase: ${e}`);if("function"!=typeof s)throw new Error("[WuHooks] Middleware must be a function");const n={middleware:s,name:r.name||`hook_${Date.now()}`,priority:r.priority||0,registeredAt:Date.now()},i=this.hooks.get(e);return i.push(n),i.sort((e,t)=>t.priority-e.priority),t.debug(`[WuHooks] Hook "${n.name}" registered for ${e} (priority: ${n.priority})`),()=>this.remove(e,n.name)}remove(e,s){if(!this.hooks.has(e))return;const r=this.hooks.get(e),n=r.findIndex(e=>e.name===s);n>-1&&(r.splice(n,1),t.debug(`[WuHooks] Hook "${s}" removed from ${e}`))}async execute(e,s={}){const r=this.hooks.get(e);if(!r||0===r.length)return s;t.debug(`[WuHooks] Executing ${r.length} hooks for ${e}`);const n={phase:e,timestamp:Date.now(),hooksCount:r.length,hookNames:r.map(e=>e.name)};let i={...s},o=!1;const a=async e=>{if(e>=r.length)return i;const s=r[e],n=Date.now();let c=!1;try{const r=async t=>(c=!0,void 0!==t&&(i={...i,...t}),await a(e+1));if(await s.middleware(i,r),!c)return t.debug(`[WuHooks] Hook "${s.name}" cancelled execution`),o=!0,{cancelled:!0};const l=Date.now()-n;t.debug(`[WuHooks] Hook "${s.name}" executed in ${l}ms`)}catch(t){if(console.error(`[WuHooks] Error in hook "${s.name}":`,t),!c)return await a(e+1)}return o?{cancelled:!0}:i},c=await a(0);return n.duration=Date.now()-n.timestamp,n.cancelled=o,n.success=!o,this.executionLog.push(n),this.executionLog.length>this.maxLogSize&&this.executionLog.shift(),c}useMultiple(e,t,s={}){const r=e.map(e=>this.use(e,t,{...s,name:`${s.name}_${e}`}));return()=>r.forEach(e=>e())}getHooks(e){if(e)return this.hooks.get(e)||[];const t={};return this.hooks.forEach((e,s)=>{t[s]=e.map(e=>({name:e.name,priority:e.priority,registeredAt:e.registeredAt}))}),t}getStats(){const e=Array.from(this.hooks.values()).reduce((e,t)=>e+t.length,0),t={};this.executionLog.forEach(e=>{t[e.phase]=(t[e.phase]||0)+1});const s=this.executionLog.length>0?this.executionLog.reduce((e,t)=>e+t.duration,0)/this.executionLog.length:0,r=this.executionLog.filter(e=>e.cancelled).length;return{totalHooks:e,totalExecutions:this.executionLog.length,executionsByPhase:t,avgDuration:Math.round(s),cancelledCount:r,recentExecutions:this.executionLog.slice(-10)}}cleanup(e){e?(this.hooks.set(e,[]),t.debug(`[WuHooks] Hooks cleaned for ${e}`)):(this.lifecyclePhases.forEach(e=>{this.hooks.set(e,[])}),this.executionLog=[],t.debug("[WuHooks] 🧹 All hooks cleaned"))}}class x{constructor(e){this.core=e,this.prefetched=new Set,this._observers=new Map,this._listeners=[],this._speculationScript=null,this._speculationRules={prefetch:[],prerender:[]},this.supportsSpeculationRules=this._detectSpeculationRules(),this.supportsModulePreload=this._detectModulePreload(),t.wuDebug(`[WuPrefetch] Initialized — Speculation Rules: ${this.supportsSpeculationRules?"yes":"no"}, Module Preload: `+(this.supportsModulePreload?"yes":"no"))}_detectSpeculationRules(){return"undefined"!=typeof HTMLScriptElement&&(HTMLScriptElement.supports?.("speculationrules")??!1)}_detectModulePreload(){if("undefined"==typeof document)return!1;const e=document.createElement("link");return e.relList?.supports?.("modulepreload")??!1}async prefetch(e,s={}){const r=Array.isArray(e)?e:[e],n=s.on||"immediate";switch(n){case"immediate":return this._prefetchImmediate(r,s);case"hover":return this._prefetchOnHover(r,s);case"visible":return this._prefetchOnVisible(r,s);case"idle":return this._prefetchOnIdle(r,s);default:return t.wuWarn(`[WuPrefetch] Unknown trigger "${n}", using immediate`),this._prefetchImmediate(r,s)}}async _prefetchImmediate(e,t){const s=await this._resolveAppUrls(e);0!==s.length&&(this.supportsSpeculationRules?this._addSpeculationRules(s,t.eagerness||"moderate"):(s.forEach(({name:e})=>this.prefetched.add(e)),this.supportsModulePreload?s.forEach(({url:e})=>this._injectModulePreload(e)):s.forEach(({url:e})=>this._injectPrefetch(e))))}_prefetchOnHover(e,s){const r=this._resolveTarget(s.target);if(!r)return t.wuWarn("[WuPrefetch] hover trigger requires a target element or selector"),()=>{};let n=!1;const i=()=>{r.removeEventListener("mouseenter",o),r.removeEventListener("focusin",o);const e=this._listeners.indexOf(i);-1!==e&&this._listeners.splice(e,1)},o=()=>{n||(n=!0,this._prefetchImmediate(e,s),i())};return r.addEventListener("mouseenter",o,{passive:!0}),r.addEventListener("focusin",o,{passive:!0}),this._listeners.push(i),i}_prefetchOnVisible(e,s){const r=this._resolveTarget(s.target);if(!r)return t.wuWarn("[WuPrefetch] visible trigger requires a target element or selector"),()=>{};if("undefined"==typeof IntersectionObserver)return this._prefetchImmediate(e,s),()=>{};const n=new IntersectionObserver(t=>{for(const r of t)if(r.isIntersecting){this._prefetchImmediate(e,s),i();break}},{rootMargin:"200px"});n.observe(r),this._observers.set(r,n);const i=()=>{n.disconnect(),this._observers.delete(r)};return i}_prefetchOnIdle(e,t){let s;const r=()=>{if(!s)return;const e=this._listeners.indexOf(s);-1!==e&&this._listeners.splice(e,1)},n=()=>{this._prefetchImmediate(e,t),r()};if("requestIdleCallback"in window){const e=requestIdleCallback(n,{timeout:3e3});s=()=>{cancelIdleCallback(e),r()}}else{const e=setTimeout(n,2e3);s=()=>{clearTimeout(e),r()}}return this._listeners.push(s),s}_addSpeculationRules(e,s){const r=e.filter(({name:e})=>!this.prefetched.has(e));if(0===r.length)return;r.forEach(({name:e})=>this.prefetched.add(e));const n=r.map(({url:e})=>e);this._speculationRules.prefetch.push({source:"list",urls:n,eagerness:s}),this._updateSpeculationScript(),t.wuDebug(`[WuPrefetch] Speculation Rules: prefetch ${r.map(e=>e.name).join(", ")} (eagerness: ${s})`)}_updateSpeculationScript(){this._speculationScript&&this._speculationScript.remove();const e=document.createElement("script");e.type="speculationrules",e.textContent=JSON.stringify(this._speculationRules),document.head.appendChild(e),this._speculationScript=e}_injectModulePreload(e){if(this.prefetched.has(e))return;this.prefetched.add(e);const s=document.createElement("link");s.rel="modulepreload",s.href=e,document.head.appendChild(s),t.wuDebug(`[WuPrefetch] modulepreload: ${e}`)}_injectPrefetch(e){if(this.prefetched.has(e))return;this.prefetched.add(e);const s=document.createElement("link");s.rel="prefetch",s.href=e,s.as="script",document.head.appendChild(s),t.wuDebug(`[WuPrefetch] prefetch: ${e}`)}async _resolveAppUrls(e){const s=[];for(const r of e){if(this.prefetched.has(r)){t.wuDebug(`[WuPrefetch] ${r} already prefetched, skipping`);continue}if(this.core.mounted.has(r)){t.wuDebug(`[WuPrefetch] ${r} already mounted, skipping`);continue}if(this.core.definitions.has(r)){t.wuDebug(`[WuPrefetch] ${r} already defined, skipping`);continue}const e=this.core.apps.get(r);if(e)try{const t=await this.core.resolveModulePath(e);s.push({name:r,url:t})}catch(e){t.wuWarn(`[WuPrefetch] Failed to resolve URL for "${r}":`,e.message)}else t.wuWarn(`[WuPrefetch] App "${r}" not registered, cannot prefetch`)}return s}_resolveTarget(e){return e?"string"==typeof e?document.querySelector(e):e instanceof Element?e:null:null}async prefetchAll(e={}){const s=[];for(const[e]of this.core.apps)this.core.mounted.has(e)||this.prefetched.has(e)||s.push(e);if(0!==s.length)return t.wuDebug(`[WuPrefetch] Prefetching all: ${s.join(", ")}`),this.prefetch(s,e);t.wuDebug("[WuPrefetch] No apps to prefetch")}getStats(){return{prefetched:[...this.prefetched],activeObservers:this._observers.size,activeListeners:this._listeners.length,speculationRulesSupported:this.supportsSpeculationRules,modulePreloadSupported:this.supportsModulePreload,speculationRules:this._speculationRules}}cleanup(){for(const[,e]of this._observers)e.disconnect();this._observers.clear();for(const e of this._listeners)e();this._listeners=[],this._speculationScript&&(this._speculationScript.remove(),this._speculationScript=null),this._speculationRules={prefetch:[],prerender:[]},this.prefetched.clear(),t.wuDebug("[WuPrefetch] Cleaned up")}}const S="wu-override:";class ${constructor(e={}){this._overrides=new Map,this._allowedDomains=e.allowedDomains||[],this._showIndicator=e.showIndicator??!0,this._indicatorElement=null,void 0!==e.enabled?this._enabled=e.enabled:this._enabled=this._isDevEnvironment(),this._enabled&&this._parseFromCookies()}_isDevEnvironment(){if("undefined"==typeof window)return!1;const e=window.location?.hostname||"",t=window.location?.port||"";return"localhost"===e||"127.0.0.1"===e||"0.0.0.0"===e||e.endsWith(".local")||""!==t&&"80"!==t&&"443"!==t}_isDomainAllowed(e){if(0===this._allowedDomains.length)return!0;const t=this._extractHostname(e);if(!t)return!1;for(const e of this._allowedDomains)if(this._matchDomain(t,e))return!0;return!1}_extractHostname(e){try{if(/^localhost(:\d+)?/.test(e))return"localhost";const t=e.startsWith("//")?`https:${e}`:e;return new URL(t).hostname}catch{return null}}_matchDomain(e,t){if(e===t)return!0;if(t.startsWith("*.")){const s=t.substring(2);return e===s||e.endsWith("."+s)}return!1}_parseFromCookies(){if(this._overrides.clear(),"undefined"==typeof document)return this._overrides;if(!this._enabled)return t.wuDebug("[WuOverrides] Overrides disabled — skipping cookie parse"),this._overrides;const e=document.cookie;if(!e)return this._overrides;const s=e.split(";");for(const e of s){const s=e.trim();if(!s.startsWith(S))continue;const r=s.indexOf("=");if(-1===r)continue;const n=s.substring(12,r).trim(),i=s.substring(r+1).trim();n&&i&&(this._isValidUrl(i)?this._isDomainAllowed(i)?(this._overrides.set(n,i),t.wuDebug(`[WuOverrides] Parsed override: ${n} → ${i}`)):t.wuWarn(`[WuOverrides] BLOCKED: "${n}" override to "${i}" — domain not in allowedDomains. Allowed: [${this._allowedDomains.join(", ")}]`):t.wuWarn(`[WuOverrides] Invalid override URL for "${n}": ${i}`))}return this._overrides.size>0&&t.wuInfo(`[WuOverrides] ${this._overrides.size} active override(s): `+[...this._overrides.keys()].join(", ")),this._overrides}applyToApps(e){if(!this._enabled||0===this._overrides.size)return e;for(const s of e){const e=this._overrides.get(s.name);e&&(s._originalUrl=s.url,s.url=e,t.wuInfo(`[WuOverrides] "${s.name}" overridden: ${s._originalUrl} → ${e}`))}return this._showIndicator&&this._overrides.size>0&&this._showOverrideIndicator(),e}getOverrideFor(e){return this._overrides.get(e)||null}set(e,s,r={}){if(!e||!s)throw new Error("[WuOverrides] appName and url are required");if(!this._enabled)throw new Error("[WuOverrides] Overrides are disabled in this environment. Enable with wu.init({ overrides: { enabled: true } })");if(!this._isValidUrl(s))throw new Error(`[WuOverrides] Invalid URL: ${s}`);if(!this._isDomainAllowed(s))throw new Error(`[WuOverrides] Domain not allowed: "${this._extractHostname(s)}". Allowed: [${this._allowedDomains.join(", ")}]`);const n=r.maxAge??86400,i=r.path??"/";"undefined"!=typeof document&&(document.cookie=`${S}${e}=${s}; path=${i}; max-age=${n}; SameSite=Lax`),this._overrides.set(e,s),this._showIndicator&&this._showOverrideIndicator(),t.wuInfo(`[WuOverrides] Override set: ${e} → ${s} (expires in ${n}s)`)}remove(e){"undefined"!=typeof document&&(document.cookie=`${S}${e}=; path=/; max-age=0`),this._overrides.delete(e),this._showIndicator&&(0===this._overrides.size?this._removeOverrideIndicator():this._showOverrideIndicator()),t.wuInfo(`[WuOverrides] Override removed: ${e}`)}clearAll(){for(const e of[...this._overrides.keys()])this.remove(e);this._removeOverrideIndicator(),t.wuInfo("[WuOverrides] All overrides cleared")}getAll(){return Object.fromEntries(this._overrides)}hasOverrides(){return this._overrides.size>0}isEnabled(){return this._enabled}configure(e={}){void 0!==e.enabled&&(this._enabled=e.enabled),e.allowedDomains&&(this._allowedDomains=e.allowedDomains),void 0!==e.showIndicator&&(this._showIndicator=e.showIndicator),this._enabled&&this._parseFromCookies()}refresh(){this._parseFromCookies()}_showOverrideIndicator(){if("undefined"==typeof document)return;this._removeOverrideIndicator();const e=document.createElement("div");e.id="wu-override-indicator";const t=[...this._overrides.entries()].map(([e,t])=>`${e} → ${t}`).join(" | ");e.textContent=`WU OVERRIDE ACTIVE: ${t}`,e.style.cssText=["position: fixed","bottom: 0","left: 0","right: 0","z-index: 2147483647","background: #f59e0b","color: #000","font-family: monospace","font-size: 12px","font-weight: bold","padding: 6px 12px","text-align: center","cursor: pointer","user-select: none","box-shadow: 0 -2px 8px rgba(0,0,0,0.2)"].join(";"),e.addEventListener("click",()=>{e.style.display="none"}),e.addEventListener("dblclick",e=>{e.preventDefault(),this.clearAll()}),e.title="Click to hide | Double-click to clear all overrides",document.body.appendChild(e),this._indicatorElement=e}_removeOverrideIndicator(){if(this._indicatorElement&&(this._indicatorElement.remove(),this._indicatorElement=null),"undefined"!=typeof document){const e=document.getElementById("wu-override-indicator");e&&e.remove()}}_isValidUrl(e){return!!(e.startsWith("http://")||e.startsWith("https://")||e.startsWith("//"))||!!/^localhost(:\d+)?/.test(e)}getStats(){return{enabled:this._enabled,activeOverrides:this._overrides.size,overrides:this.getAll(),allowedDomains:this._allowedDomains,showIndicator:this._showIndicator,environment:this._isDevEnvironment()?"development":"production"}}}function k(e){const t=parseInt(e,10);return Number.isNaN(t)?0:t}function E(e){const t=String(e).trim().replace(/^[v=\s]+/,"").split("+")[0].split("-")[0].split(".");return[k(t[0]),k(t[1]),k(t[2])]}function A(e,t){const s=Array.isArray(e)?e:E(e),r=Array.isArray(t)?t:E(t);for(let e=0;e<3;e++)if(s[e]!==r[e])return s[e]<r[e]?-1:1;return 0}function W(e,t){return null==t||""===t||"*"===t||String(t).split("||").some(t=>t.trim().split(/\s+/).filter(Boolean).every(t=>function(e,t){const s=t.trim();if(""===s||"*"===s||"x"===s||"X"===s)return!0;if("^"===s[0]||"~"===s[0]){const t="^"===s[0],r=s.slice(1).trim(),n=E(r);if(A(e,n)<0)return!1;const i=r.replace(/^[v=]+/,"").split("+")[0].split("-")[0].split(".").filter(e=>""!==e&&"x"!==e&&"X"!==e&&"*"!==e).length;let o;return o=t?n[0]>0?[n[0]+1,0,0]:i<2?[1,0,0]:n[1]>0?[0,n[1]+1,0]:i<3?[0,1,0]:[0,0,n[2]+1]:i>=2?[n[0],n[1]+1,0]:[n[0]+1,0,0],A(E(e),o)<0}const r=s.match(/^(>=|<=|>|<|=)\s*(.+)$/);if(r){const t=A(e,E(r[2]));switch(r[1]){case">":return t>0;case">=":return t>=0;case"<":return t<0;case"<=":return t<=0;default:return 0===t}}const n=s.replace(/^[v=]+/,"").split("+")[0].split("-")[0].split("."),i=n.some(e=>"x"===e||"X"===e||"*"===e);if(n.length<3||i){const t=E(e);for(let e=0;e<3;e++){const s=n[e];if(void 0!==s&&""!==s&&"x"!==s&&"X"!==s&&"*"!==s&&t[e]!==k(s))return!1}return!0}return 0===A(e,E(s))}(e,t)))}class C{constructor(e){this.core=e,this._providers=new Map,this._waiters=new Map}provide(e,s,r={}){if(!e||"string"!=typeof e)throw new Error("[WuContracts] provide() requires a capability name (string).");if(null==s||"object"!=typeof s&&"function"!=typeof s)throw new Error(`[WuContracts] provide('${e}') requires an implementation object or function.`);const n=r.version||"0.0.0";r.shape&&this._verifyShape(e,s,r.shape,n);const i=this._providers.get(e);i&&i.version!==n&&t.wuDebug?.(`[WuContracts] '${e}' re-provided: ${i.version} → ${n}`);const o={impl:s,version:n,app:r.app||null,shape:r.shape||null,providedAt:Date.now()};return this._providers.set(e,o),this._emit("wu:capability:provided",{name:e,version:n,app:o.app}),this._resolveWaiters(e,o),t.wuDebug?.(`[WuContracts] provided '${e}@${n}'`),{revoke:()=>this._providers.get(e)===o&&this.revoke(e)}}consume(e,t="*",s={}){if(!s.wait)return this._proxy(e,t);const r=this._providers.get(e);return r&&W(r.version,t)?Promise.resolve(this._proxy(e,t)):new Promise((r,n)=>{const i={range:t,resolve:()=>r(this._proxy(e,t)),reject:n,timer:null};s.timeout&&(i.timer=setTimeout(()=>{this._removeWaiter(e,i),n(new Error(`[WuContracts] timed out after ${s.timeout}ms waiting for '${e}' satisfying '${t}'.`))},s.timeout)),this._addWaiter(e,i)})}has(e,t="*"){const s=this._providers.get(e);return!!s&&W(s.version,t)}revoke(e){return!!this._providers.delete(e)&&(this._emit("wu:capability:revoked",{name:e}),t.wuDebug?.(`[WuContracts] revoked '${e}'`),!0)}revokeByApp(e){if(e)for(const[t,s]of[...this._providers])s.app===e&&this.revoke(t)}list(){const e=[];for(const[t,s]of this._providers)e.push({name:t,version:s.version,app:s.app});return e}cleanup(){for(const e of this._waiters.values())for(const t of e){t.timer&&clearTimeout(t.timer);try{t.reject(new Error("[WuContracts] framework destroyed"))}catch{}}this._waiters.clear(),this._providers.clear()}_proxy(e,s){const r=this,n=new WeakMap,i=(e,t)=>{let s=n.get(t);return s||(s=t.bind(e),n.set(t,s)),s};return new Proxy(Object.create(null),{get(t,n){if("__wuCapability"===n)return e;if("__wuRange"===n)return s;if("__wuAvailable"===n)return r.has(e,s);if("then"===n)return;if("symbol"==typeof n){if(!r.has(e,s))return;const t=r._providers.get(e),o=t.impl[n];return"function"==typeof o?i(t.impl,o):o}const o=(()=>{const t=r._providers.get(e);if(!t)throw new Error(`[WuContracts] no provider for capability '${e}'. Did the providing app mount and call wu.provide('${e}', …)?`);if(!W(t.version,s))throw new Error(`[WuContracts] capability '${e}@${t.version}' does not satisfy '${s}'.`);return t})(),a=o.impl[n];return"function"==typeof a?i(o.impl,a):a},set:(s,r)=>(t.wuWarn?.(`[WuContracts] ignored write to '${String(r)}' on consumed capability '${e}': consumed capabilities are read-only.`),!0),has(t,s){const n=r._providers.get(e);return!!n&&s in n.impl}})}_verifyShape(e,t,s,r){const n=[];if(Array.isArray(s))for(const e of s)C._provides(t,e)||n.push(`${e} (missing)`);else if(s&&"object"==typeof s)for(const[e,r]of Object.entries(s))C._provides(t,e)?r&&typeof t[e]!==r&&n.push(`${e} (expected ${r}, got ${typeof t[e]})`):n.push(`${e} (missing)`);if(n.length)throw new Error(`[WuContracts] provide('${e}@${r}') violates its declared shape — ${n.join(", ")}.`)}static _provides(e,t){let s=e;for(;s&&s!==Object.prototype&&s!==Function.prototype;){if(Object.prototype.hasOwnProperty.call(s,t))return!0;s=Object.getPrototypeOf(s)}return!1}_addWaiter(e,t){this._waiters.has(e)||this._waiters.set(e,new Set),this._waiters.get(e).add(t)}_removeWaiter(e,t){const s=this._waiters.get(e);s&&(s.delete(t),s.size||this._waiters.delete(e))}_resolveWaiters(e,t){const s=this._waiters.get(e);if(s){for(const e of[...s])W(t.version,e.range)&&(e.timer&&clearTimeout(e.timer),s.delete(e),e.resolve());s.size||this._waiters.delete(e)}}_emit(e,t){try{this.core.eventBus?.emit(e,t,{appName:"wu-core"})}catch{}}}class D{constructor(e={}){this.apps=new Map,this.definitions=new Map,this.manifests=new Map,this.mounted=new Map,this.hidden=new Map,this._pendingUnmounts=new Map,this._mountingPromises=new Map,this._unmountingPromises=new Map,this._defineWaiters=new Map,this._resolvedPaths=new Map,this._mountRefs=new Map,this.sandbox=new c,this.manifest=new l,this.store=d,this.htmlParser=null,this.scriptExecutor=null,this._WuIframeSandbox=null,this.loader=null,this._timeline=null,this.cache=new p({storage:"localStorage",maxSize:4}),this.eventBus=new m,this.performance=new w,this.pluginSystem=new y(this),this.strategies=new _(this),this.errorBoundary=new b(this),this.hooks=new v(this),this.prefetcher=new x(this),this.overrides=new $,this.contracts=new C(this),this.isInitialized=!1,this._principal=null,t.wuInfo("Wu Framework initialized - Universal Microfrontends")}async init(e){if(this.isInitialized)t.wuWarn("Framework already initialized");else{this._sandboxMode=e.sandbox||"module",this._strictFallback=!1!==e.strictFallback,t.wuDebug(`Initializing (sandbox: ${this._sandboxMode}) with apps:`,e.apps?.map(e=>e.name));try{if((await this.hooks.execute("beforeInit",{config:e})).cancelled)return void t.wuWarn("Initialization cancelled by beforeInit hook");await this.pluginSystem.callHook("beforeInit",{config:e}),e.overrides&&this.overrides.configure(e.overrides);const s=e.apps||[];this.overrides.refresh(),this.overrides.applyToApps(s);for(const e of s)await this.registerApp(e);await this.strategies.preload(e.apps||[]),this.isInitialized=!0,await this.hooks.execute("afterInit",{config:e}),await this.pluginSystem.callHook("afterInit",{config:e}),t.wuInfo("Framework initialized successfully")}catch(e){throw t.wuError("Initialization failed:",e),await this.pluginSystem.callHook("onError",{phase:"init",error:e}),e}}}async registerApp(e){const{name:s,url:r}=e;try{t.wuDebug(`Registering app: ${s} from ${r}`);const n=await this.manifest.load(r);this.manifests.set(s,n),this.apps.set(s,{...e,manifest:n,status:"registered"}),t.wuDebug(`App ${s} registered successfully`)}catch(e){throw t.wuError(`Failed to register app ${s}:`,e),e}}setPrincipal(e){this._principal=e||null;try{this.store.set("auth.principal",this._principal)}catch{}return this.eventBus.emit("principal:changed",{principal:this._principal}),this._principal}getPrincipal(){return this._principal}_requiredRoles(e){const t=this.apps.get(e),s=this.manifests.get(e),r=t?.roles??s?.wu?.roles??s?.roles??null;return Array.isArray(r)&&r.length?r:null}_principalRoles(){const e=this._principal;if(!e)return[];const t=[];return"string"==typeof e.role&&t.push(e.role),Array.isArray(e.roles)&&t.push(...e.roles),t}can(e){const t=this._requiredRoles(e);if(!t)return!0;const s=this._principal;if(!s)return!1;const r=Array.isArray(s.permissions)?s.permissions:[];if(r.includes("mount:*")||r.includes(`mount:${e}`))return!0;return this._principalRoles().some(e=>t.includes(e))}define(e,s){if(!s.mount)throw new Error(`[Wu] Mount function required for app: ${e}`);this.definitions.set(e,s);const r=this._defineWaiters.get(e);r&&(clearTimeout(r.timer),this._defineWaiters.delete(e),r.resolve());const n=new CustomEvent("wu:app:ready",{detail:{appName:e,timestamp:Date.now()}});window.dispatchEvent(n),t.wuDebug(`Lifecycle defined for: ${e}`)}async mount(e,s){if(!this.can(e)){const t=this._requiredRoles(e)||[],s=this._principal?.role??null;this.eventBus.emit("access:denied",{appName:e,role:s,required:t},{appName:e});try{window.dispatchEvent(new CustomEvent("wu:access:denied",{detail:{appName:e,role:s,required:t}}))}catch{}const r=new Error(`[Wu] Access denied: el rol '${s??"ninguno"}' no puede montar '${e}' (requiere: ${t.join(", ")||"un principal"})`);throw r.code="WU_ACCESS_DENIED",r.appName=e,r.required=t,r}const r=this._mountRefs.get(e)||0;this._mountRefs.set(e,r+1),t.wuDebug(`${e} mount refs: ${r} → ${r+1}`),this._pendingUnmounts.has(e)&&(clearTimeout(this._pendingUnmounts.get(e)),this._pendingUnmounts.delete(e),t.wuDebug(`${e} deferred unmount cancelled by remount`));let n=!1;const i=()=>{n||(n=!0,this._releaseMountRef(e))},o=()=>{n||0!==(this._mountRefs.get(e)||0)||this._mountRefs.set(e,1)};try{if(this._unmountingPromises.has(e)&&(await Promise.race([this._unmountingPromises.get(e),new Promise(e=>setTimeout(e,5e3))]),o()),this.mounted.has(e)){if(this.mounted.get(e).containerSelector===s)return void t.wuDebug(`${e} already mounted in ${s}`);await this.unmount(e,{force:!0}),o()}const r=this._mountingPromises.get(e);if(r)return r.containerSelector===s?(t.wuDebug(`${e} mount already in progress, deduplicating`),await r.promise):(i(),await r.promise.catch(()=>{}),await this.mount(e,s));const n=this.hidden.get(e);if(n){if(n.containerSelector===s)return await this.show(e);await this._destroyHidden(e)}const a=this.mountWithRecovery(e,s,0);this._mountingPromises.set(e,{promise:a,containerSelector:s});try{return await a}finally{this._mountingPromises.delete(e)}}catch(e){throw i(),e}}async update(e,s={}){if(this._unmountingPromises.has(e)&&await Promise.race([this._unmountingPromises.get(e),new Promise(e=>setTimeout(e,5e3))]),this._unmountingPromises.has(e))return t.wuWarn(`[Wu] update('${e}') ignored: app is being unmounted`),!1;const r=this.mounted.get(e)||this.hidden.get(e);if(!r)return t.wuWarn(`[Wu] update('${e}') ignored: app is not mounted`),!1;const n=r.lifecycle;if(!n||"function"!=typeof n.update)return t.wuWarn(`[Wu] update('${e}') is a no-op: this app's adapter does not support live props (no update() slot). Re-mount to change props, or use the event bus / store for cross-app state.`),!1;try{return(await this.hooks.execute("beforeUpdate",{appName:e,props:s,mounted:r})).cancelled?(t.wuWarn(`[Wu] update('${e}') cancelled by beforeUpdate hook`),!1):(await n.update(r.container,s),r.props={...r.props||{},...s},await this.hooks.execute("afterUpdate",{appName:e,props:s}),this.eventBus.emit("app:updated",{appName:e,props:s},{appName:e}),t.wuDebug(`${e} props updated`),!0)}catch(s){return t.wuError(`[Wu] update('${e}') failed:`,s),this.errorBoundary.handle(s,{appName:e,phase:"update"}),!1}}_releaseMountRef(e){const s=this._mountRefs.get(e)||0,r=s-1;r>0?this._mountRefs.set(e,r):this._mountRefs.delete(e),t.wuDebug(`${e} mount ref released: ${s} → ${Math.max(0,r)}`)}async mountWithRecovery(e,s,r=0){try{this.performance.startMeasure("mount",e),t.wuDebug(`Mounting ${e} in ${s} (attempt ${r+1})`);if((await this.hooks.execute("beforeLoad",{appName:e,containerSelector:s,attempt:r})).cancelled)return t.wuWarn("Mount cancelled by beforeLoad hook"),void this._releaseMountRef(e);if(!1===await this.pluginSystem.callHook("beforeMount",{appName:e,containerSelector:s}))return t.wuWarn("Mount cancelled by plugin beforeMount hook"),void this._releaseMountRef(e);const n=this.apps.get(e);if(!n)throw new Error(`App ${e} not registered. Call wu.init() first.`);const i=document.querySelector(s);if(!i)throw new Error(`Container not found: ${s}`);const o=this.sandbox.create(e,i,{manifest:n.manifest,styleMode:n.manifest?.styleMode,appUrl:n.url});await this.hooks.execute("afterLoad",{appName:e,containerSelector:s,sandbox:o});let a=this.definitions.get(e);if(!a&&(await this.loadAndMountRemoteApp(n,o),a=this.definitions.get(e),!a))throw new Error(`App ${e} did not register with wu.define()`);if((await this.hooks.execute("beforeMount",{appName:e,containerSelector:s,sandbox:o,lifecycle:a})).cancelled)return t.wuWarn("Mount cancelled by beforeMount hook"),o.iframeSandbox&&(o.iframeSandbox.destroy(),o.iframeSandbox=null),this.sandbox.cleanup(o),void this._releaseMountRef(e);o.stylesReady&&(t.wuDebug(`Waiting for styles to be ready for ${e}...`),await o.stylesReady,t.wuDebug(`Styles ready for ${e}`)),await a.mount(o.container),this.mounted.set(e,{app:n,sandbox:o,lifecycle:a,container:o.container,hostContainer:i,containerSelector:s,timestamp:Date.now(),state:"stable"});const c=this.performance.endMeasure("mount",e);await this.hooks.execute("afterMount",{appName:e,containerSelector:s,sandbox:o,mountTime:c}),await this.pluginSystem.callHook("afterMount",{appName:e,containerSelector:s,mountTime:c}),this.eventBus.emit("app:mounted",{appName:e,mountTime:c,attempt:r},{appName:e}),t.wuInfo(`${e} mounted successfully in ${c.toFixed(2)}ms`)}catch(n){t.wuError(`Mount attempt ${r+1} failed for ${e}:`,n);try{if(this.sandbox&&this.sandbox.sandboxes&&this.sandbox.sandboxes.has(e)){const s=this.sandbox.sandboxes.get(e);s&&s.iframeSandbox&&(s.iframeSandbox.destroy(),s.iframeSandbox=null),s&&s.jsSandbox&&s.jsSandbox.isActive()&&s.jsSandbox.deactivate(),this.sandbox.sandboxes.delete(e),t.wuDebug(`Sandbox cleaned up after mount failure for ${e}`)}}catch(s){t.wuWarn(`Sandbox cleanup failed for ${e}:`,s)}const i=await this.errorBoundary.handle(n,{appName:e,containerSelector:s,retryCount:r,container:s}),o="retry"===i.action||"retry-with-longer-timeout"===i.action;if(o&&r<2)return t.wuDebug("Initiating recovery protocol..."),await this.appStateCleanup(e,s,{preserveDefinition:!0}),0===(this._mountRefs.get(e)||0)&&this._mountRefs.set(e,1),await new Promise(e=>setTimeout(e,1e3*(r+1))),await this.mountWithRecovery(e,s,r+1);if(i.recovered&&!o)return t.wuDebug("Error recovered by error boundary"),void this._releaseMountRef(e);throw await this.pluginSystem.callHook("onError",{phase:"mount",error:n,appName:e}),n}}async appStateCleanup(e,s,{preserveDefinition:r=!1}={}){try{if(t.wuDebug(`Starting app state cleanup for ${e}...`),this.hidden.has(e))try{await this._destroyHidden(e)}catch(e){t.wuWarn("Hidden app cleanup failed:",e)}if(this.mounted.has(e))try{await this.unmount(e,{force:!0})}catch(e){t.wuWarn("Unmount failed during cleanup:",e)}const n=document.querySelector(s);if(n){if(n.shadowRoot)try{Array.from(n.shadowRoot.children).forEach(e=>{try{e.remove()}catch(e){t.wuWarn("Failed to remove shadow child:",e)}})}catch(e){t.wuWarn("Shadow root cleanup failed:",e)}if(!n.shadowRoot&&n.children.length>0)try{n.innerHTML=""}catch(e){t.wuWarn("Container innerHTML cleanup failed:",e)}n.removeAttribute("data-wu-app"),n.removeAttribute("data-quantum-state"),n.removeAttribute("wu-debug")}r||this.definitions.delete(e),this.sandbox&&this.sandbox.sandboxes&&this.sandbox.sandboxes.delete(e),t.wuDebug(`App state cleaned successfully for ${e}`)}catch(r){t.wuWarn(`App cleanup partial failure for ${e}:`,r);try{const e=document.querySelector(s);e&&(e.style.display="none",setTimeout(()=>{e&&(e.style.display="")},100))}catch(e){t.wuError("Emergency cleanup failed:",e)}}}async loadAndMountRemoteApp(e,t){const s=e.sandbox||this._sandboxMode||"module";t._requestedMode=s,t._actualMode=s,"strict"===s?await this._loadStrict(e,t):"eval"===s?await this._loadEval(e,t):await this._loadModule(e,t)}tagStyleAsApp(e,t){e&&"function"==typeof e.setAttribute&&t&&e.setAttribute("data-wu-app",t)}getSandboxInfo(e){const t=this.mounted.get(e)||this.hidden.get(e);if(!t)return null;const s=t.sandbox,r=s._actualMode||s._requestedMode||"module",n="strict"===r?"iframe":"eval"===r?"proxy-trap":"none";return{requestedMode:s._requestedMode||"module",actualMode:r,isolationLevel:n,mounted:this.mounted.has(e)}}async _ensureIframeSandboxClass(){if(this._WuIframeSandbox)return this._WuIframeSandbox;const e=await Promise.resolve().then(function(){return U});return this._WuIframeSandbox=e.WuIframeSandbox,this._WuIframeSandbox}async _ensureEvalDeps(){if(!this.htmlParser){const{WuHtmlParser:e}=await Promise.resolve().then(function(){return q});this.htmlParser=new e}if(!this.scriptExecutor){const{WuScriptExecutor:e}=await Promise.resolve().then(function(){return G});this.scriptExecutor=new e}}async _ensureLoader(){if(!this.loader){const{WuLoader:e}=await Promise.resolve().then(function(){return M});this.loader=new e}}async _loadModule(e,s){const r=await this.resolveModulePath(e);t.wuDebug(`[module] Loading ES module: ${r}`);const n=s.jsSandbox;n?.patchWindow&&n.patchWindow();try{await this.moduleLoader(r,e.name),t.wuDebug(`[module] ES module loaded: ${e.name}`)}catch(e){throw t.wuError(`[module] Failed to load ${r}:`,e),e}finally{n?.unpatchWindow&&n.unpatchWindow()}}async _loadStrict(e,s){t.wuDebug(`[strict] Loading ${e.name} via iframe sandbox`);const r=new(await this._ensureIframeSandboxClass())(e.name);r.activate(e.url,s.container,s.shadowRoot),s.iframeSandbox=r;try{const s=await this.resolveModulePath(e);t.wuDebug(`[strict] Importing module in iframe: ${s}`),await r.importModule(s),t.wuDebug(`[strict] Module imported for ${e.name}`)}catch(n){const i=e.strictFallback??this._strictFallback??!0;if(r.destroy(),s.iframeSandbox=null,!i)throw new Error(`[strict] iframe import failed for '${e.name}' and strictFallback is disabled.\nOriginal error: ${n.message}\nFix: ensure the app's dev server sets Access-Control-Allow-Origin headers,\nor explicitly allow degrade with { strictFallback: true } or sandbox: 'eval'.`);return t.wuWarn(`[strict] iframe import failed for ${e.name}: ${n.message}\nFalling back to eval mode (fetch + parse + execute with proxy).\nTo fix: ensure the app's dev server sets Access-Control-Allow-Origin: * headers,\nor use sandbox: 'eval' explicitly for UMD/IIFE bundles.\nTo make this an error instead of a warning, set { strictFallback: false }.`),s._actualMode="eval",s._fellBackFromStrict=!0,void await this._loadEval(e,s)}try{await this._waitForDefine(e.name,"strict")}catch(e){throw r.destroy(),s.iframeSandbox=null,e}t.wuDebug(`[strict] ${e.name} loaded and registered via iframe`)}async _loadEval(e,s){t.wuDebug(`[eval] Loading ${e.name} from ${e.url}`);const r=s.jsSandbox.getProxy();if(!r)throw new Error(`[eval] No active proxy for ${e.name}. Sandbox must be activated first.`);await this._ensureEvalDeps();const n=await this.htmlParser.fetchAndParse(e.url,e.name);n.dom&&(s.container.innerHTML=n.dom);const i=s.shadowRoot||s.container;for(const e of n.styles.inline){const t=document.createElement("style");t.textContent=e,i.appendChild(t)}for(const e of n.styles.external){const t=document.createElement("link");t.rel="stylesheet",t.href=e,i.appendChild(t)}const o=[];for(const e of n.scripts.inline)o.push({content:e});for(const e of n.scripts.external)o.push({src:e});await this.scriptExecutor.executeAll(o,e.name,r),t.wuDebug(`[eval] Scripts executed for ${e.name}`),await this._waitForDefine(e.name,"eval"),t.wuDebug(`[eval] ${e.name} loaded and registered`)}_waitForDefine(e,t,s=1e4){if(this.definitions.has(e))return Promise.resolve();const r=this._defineWaiters.get(e);if(r)return r.promise;let n,i;const o=new Promise((e,t)=>{n=e,i=t}),a=setTimeout(()=>{this._defineWaiters.delete(e)&&i(new Error(`[${t}] App '${e}' loaded but wu.define() was not called within ${s}ms.\nMake sure your app calls: window.wu.define('${e}', { mount, unmount })`))},s);return this._defineWaiters.set(e,{resolve:n,reject:i,timer:a,promise:o}),o}_cancelDefineWaiter(e){const t=this._defineWaiters.get(e);t&&(clearTimeout(t.timer),this._defineWaiters.delete(e))}async resolveModulePath(e){const s=e.manifest?.entry||"main.js",r=e.url.replace(/\/$/,"");if(/^(src|dist|public|build|assets|lib|es)\//.test(s)){t.wuDebug(`Entry already has folder prefix: ${s}`);const e=`${r}/${s}`;return t.wuDebug(`Using direct path: ${e}`),e}const n=`${r}::${s}`,i=this._resolvedPaths.get(n);if(i)return t.wuDebug(`Using cached resolved path for ${e.name}: ${i}`),i;const o=[`${r}/src/${s}`,`${r}/${s}`,`${r}/dist/${s}`,`${r}/public/${s}`,`${r}/build/${s}`,`${r}/assets/${s}`,`${r}/lib/${s}`,`${r}/es/${s}`];t.wuDebug(`Resolving path for ${e.name} (parallel HEAD probe)...`);const a=(await Promise.all(o.map(e=>this.validatePath(e).then(t=>t?e:null).catch(()=>null)))).find(e=>null!==e);if(a)return t.wuDebug(`Path resolved successfully: ${a}`),this._resolvedPaths.set(n,a),a;const c=o[0];return t.wuWarn(`All path candidates failed, using fallback: ${c}`),c}async validatePath(e){try{t.wuDebug(`Probing path: ${e}`);let s=await fetch(e,{method:"HEAD",cache:"no-cache",signal:AbortSignal.timeout(2e3)});if(405!==s.status&&501!==s.status||(t.wuDebug(`HEAD not supported (${s.status}), falling back to ranged GET: ${e}`),s=await fetch(e,{method:"GET",cache:"no-cache",headers:{Range:"bytes=0-255"},signal:AbortSignal.timeout(2e3)})),!s.ok&&206!==s.status)return t.wuDebug(`Path validation failed - HTTP ${s.status}: ${e}`),!1;const r=(s.headers.get("content-type")||"").toLowerCase();if(r.startsWith("text/html"))return t.wuDebug(`Path validation failed - HTML fallback detected: ${e}`),!1;return r.includes("javascript")||r.includes("module")||r.includes("text/plain")||""===r||e.endsWith(".js")||e.endsWith(".mjs")?(t.wuDebug(`Path validation successful: ${e}`),!0):(t.wuDebug(`Path validation failed - non-JS content-type '${r}': ${e}`),!1)}catch(s){return t.wuDebug(`Path validation failed for ${e}: ${s.message}`),!1}}async moduleLoader(e,s){if(this.definitions.has(s))return void t.wuDebug(`App ${s} already registered`);t.wuDebug(`Using event-based registration for ${s}`);const r=this._waitForDefine(s,"module");try{await import(e)}catch(r){throw this._cancelDefineWaiter(s),t.wuError(`Failed to import module ${e}:`,r),r}await r,t.wuDebug(`App ${s} loaded and registered (verified in definitions)`)}async unmount(e,s={}){t.wuDebug(`Unmounting ${e}`);const r=this.mounted.get(e);if(!r)return s.force&&this.hidden.has(e)?(this._mountRefs.delete(e),await this._destroyHidden(e)):void t.wuWarn(`App ${e} not mounted`);if(!s.force&&(s.keepAlive??r.app?.keepAlive??!1))return await this.hide(e);if(s.force)return this._mountRefs.delete(e),this._pendingUnmounts.has(e)&&(clearTimeout(this._pendingUnmounts.get(e)),this._pendingUnmounts.delete(e)),await this._executeUnmount(e,r);const n=this._mountRefs.get(e)||1,i=n-1;this._mountRefs.set(e,Math.max(0,i)),t.wuDebug(`${e} unmount refs: ${n} → ${i}`),i>0?t.wuDebug(`${e} unmount skipped: ${i} ref(s) still active`):(this._pendingUnmounts.has(e)&&clearTimeout(this._pendingUnmounts.get(e)),this._pendingUnmounts.set(e,setTimeout(()=>{if(this._pendingUnmounts.delete(e),!((this._mountRefs.get(e)||0)>0)&&this.mounted.has(e)&&this.mounted.get(e)===r){const s=(async()=>{try{await this._executeUnmount(e,r),this._mountRefs.delete(e)}catch(s){t.wuError(`Deferred unmount failed for ${e}:`,s)}finally{this._unmountingPromises.delete(e)}})();this._unmountingPromises.set(e,s)}},60)))}async _executeUnmount(e,s){try{if((await this.hooks.execute("beforeUnmount",{appName:e,mounted:s})).cancelled)return void t.wuWarn("Unmount cancelled by beforeUnmount hook");if(!1===await this.pluginSystem.callHook("beforeUnmount",{appName:e}))return void t.wuWarn("Unmount cancelled by plugin beforeUnmount hook");s.lifecycle?.unmount&&await s.lifecycle.unmount(s.container),s.sandbox.iframeSandbox&&(s.sandbox.iframeSandbox.destroy(),s.sandbox.iframeSandbox=null),this.sandbox.cleanup(s.sandbox),this.mounted.delete(e),await this.hooks.execute("afterUnmount",{appName:e}),await this.pluginSystem.callHook("afterUnmount",{appName:e});try{this.contracts.revokeByApp(e)}catch{}this.eventBus.emit("app:unmounted",{appName:e},{appName:e}),t.wuDebug(`${e} unmounted successfully`)}catch(s){throw t.wuError(`Failed to unmount ${e}:`,s),await this.pluginSystem.callHook("onError",{phase:"unmount",error:s,appName:e}),this.eventBus.emit("app:error",{appName:e,error:s.message},{appName:e}),s}}async hide(e){const s=this.mounted.get(e);if(s){if(t.wuDebug(`Hiding ${e} (keep-alive)`),s.lifecycle?.deactivate)try{await s.lifecycle.deactivate(s.container)}catch(s){t.wuWarn(`deactivate() failed for ${e}:`,s)}await this.hooks.execute("beforeUnmount",{appName:e,mounted:s,keepAlive:!0}),await this.pluginSystem.callHook("beforeUnmount",{appName:e,keepAlive:!0}),s.hostContainer.style.display="none",s.state="hidden",s.hiddenAt=Date.now(),this.hidden.set(e,s),this.mounted.delete(e),await this.hooks.execute("afterUnmount",{appName:e,keepAlive:!0}),await this.pluginSystem.callHook("afterUnmount",{appName:e,keepAlive:!0}),this.eventBus.emit("app:hidden",{appName:e},{appName:e}),t.wuInfo(`${e} hidden (keep-alive) — state preserved`)}else t.wuWarn(`Cannot hide ${e}: not mounted`)}async show(e){const s=this.hidden.get(e);if(!s)return void t.wuWarn(`Cannot show ${e}: not in keep-alive state`);if(this.performance.startMeasure("show",e),t.wuDebug(`Showing ${e} from keep-alive`),await this.hooks.execute("beforeMount",{appName:e,containerSelector:s.containerSelector,sandbox:s.sandbox,lifecycle:s.lifecycle,keepAlive:!0}),await this.pluginSystem.callHook("beforeMount",{appName:e,containerSelector:s.containerSelector,keepAlive:!0}),s.hostContainer.style.display="",s.state="stable",delete s.hiddenAt,this.mounted.set(e,s),this.hidden.delete(e),s.lifecycle?.activate)try{await s.lifecycle.activate(s.container)}catch(s){t.wuWarn(`activate() failed for ${e}:`,s)}const r=this.performance.endMeasure("show",e);await this.hooks.execute("afterMount",{appName:e,containerSelector:s.containerSelector,sandbox:s.sandbox,mountTime:r,keepAlive:!0}),await this.pluginSystem.callHook("afterMount",{appName:e,containerSelector:s.containerSelector,mountTime:r,keepAlive:!0}),this.eventBus.emit("app:shown",{appName:e,showTime:r},{appName:e}),t.wuInfo(`${e} shown from keep-alive in ${r.toFixed(2)}ms`)}async _destroyHidden(e){const s=this.hidden.get(e);s&&(t.wuDebug(`Force-destroying hidden app: ${e}`),s.hostContainer.style.display="",s.state="stable",this.mounted.set(e,s),this.hidden.delete(e),await this.unmount(e,{force:!0}))}isHidden(e){return this.hidden.has(e)}async use(e){const[t,s]=e.split(".");if(!t||!s)throw new Error(`Invalid component path: ${e}. Use format "app.component"`);const r=this.apps.get(t);if(!r)throw new Error(`App ${t} not registered`);const n=this.manifests.get(t),i=n?.wu?.exports?.[s];if(!i)throw new Error(`Component ${s} not exported by ${t}`);return await this._ensureLoader(),await this.loader.loadComponent(r.url,i)}getAppInfo(e){return{registered:this.apps.get(e),manifest:this.manifests.get(e),mounted:this.mounted.get(e),definition:this.definitions.get(e)}}getStats(){return{registered:this.apps.size,defined:this.definitions.size,mounted:this.mounted.size,hidden:this.hidden.size,apps:Array.from(this.apps.keys())}}provide(e,t,s){return this.contracts.provide(e,t,s)}consume(e,t,s){return this.contracts.consume(e,t,s)}inspect(e={}){const{events:t=25}=e,s=(e,t,s)=>{const r=t.lifecycle||this.definitions.get(e);return{name:e,status:s,framework:t.app?.framework||t.app?.config?.framework||null,containerSelector:t.containerSelector||null,mountedAt:t.timestamp||null,liveProps:"function"==typeof r?.update,props:t.props||null,sandbox:this.getSandboxInfo(e)}},r=[];for(const[e,t]of this.mounted)r.push(s(e,t,"mounted"));for(const[e,t]of this.hidden)r.push(s(e,t,"hidden"));let n=[];try{n=(this.eventBus.history||[]).slice(-t).map(e=>({type:e.name||e.type||e.event,appName:e.appName,timestamp:e.timestamp}))}catch{}let i=null;try{i=this.store.get()}catch{}return{version:this.version||null,timestamp:Date.now(),summary:{registered:this.apps.size,defined:this.definitions.size,mounted:this.mounted.size,hidden:this.hidden.size},apps:r,defined:Array.from(this.definitions.keys()),registered:Array.from(this.apps.keys()),capabilities:(()=>{try{return this.contracts.list()}catch{return[]}})(),events:{recent:n,stats:(()=>{try{return this.eventBus.getStats()}catch{return null}})()},store:{snapshot:i,metrics:(()=>{try{return this.store.getMetrics()}catch{return null}})()}}}async showInspector(){if("undefined"==typeof window)return null;const{mountInspector:e}=await Promise.resolve().then(function(){return se});return e(this)}async _ensureTimeline(){if(this._timeline)return this._timeline;const{WuTimeline:e}=await Promise.resolve().then(function(){return ce});return this._timeline=new e(this),this._timeline}async hideInspector(){if("undefined"!=typeof window)try{const{unmountInspector:e}=await Promise.resolve().then(function(){return se});e()}catch{}}getState(e){return this.store.get(e)}setState(e,t){return this.store.set(e,t)}onStateChange(e,t){return this.store.on(e,t)}batchState(e){return this.store.batch(e)}getStoreMetrics(){return this.store.getMetrics()}clearState(){this.store.clear()}override(e,t,s){this.overrides.set(e,t,s)}removeOverride(e){this.overrides.remove(e)}getOverrides(){return this.overrides.getAll()}clearOverrides(){this.overrides.clearAll()}prefetch(e,t){return this.prefetcher.prefetch(e,t)}prefetchAll(e){return this.prefetcher.prefetchAll(e)}app(e,t){return new h(e,t,this)}async destroy(){t.wuDebug("Destroying framework...");try{if(await this.hideInspector(),this._timeline)try{this._timeline.stop()}catch{}await this.hooks.execute("beforeDestroy",{}),await this.pluginSystem.callHook("onDestroy",{});for(const e of this._pendingUnmounts.values())clearTimeout(e);this._pendingUnmounts.clear(),this._mountingPromises.clear(),this._unmountingPromises.clear();for(const[,e]of this._defineWaiters)clearTimeout(e.timer),e.reject(new Error("Framework destroyed"));this._defineWaiters.clear(),this._resolvedPaths.clear(),this._mountRefs.clear();for(const e of[...this.hidden.keys()])await this._destroyHidden(e);for(const e of[...this.mounted.keys()])await this.unmount(e,{force:!0});this.cache.clear(),this.eventBus.removeAll(),this.eventBus.clearHistory(),this.performance.clearMetrics(),this.pluginSystem.cleanup(),this.strategies.cleanup(),this.errorBoundary.cleanup(),this.hooks.cleanup(),this.prefetcher.cleanup(),this.contracts.cleanup(),this.apps.clear(),this.definitions.clear(),this.manifests.clear(),this.mounted.clear(),this.hidden.clear(),this.store.clear(),this.isInitialized=!1,await this.hooks.execute("afterDestroy",{}),t.wuDebug("Framework destroyed")}catch(e){throw t.wuError("Error during destroy:",e),e}}}class P{constructor(e={}){this.maxCacheSize=e.maxCacheSize??50,this.cacheTTL=e.cacheTTL??18e5,this.cache=new Map,this.loadingPromises=new Map,t.debug("[WuLoader] Dynamic loader initialized")}_cacheGet(e){if(!this.cache.has(e))return;const s=this.cache.get(e),r=Date.now();return r-s.timestamp>this.cacheTTL?(this.cache.delete(e),void t.debug(`[WuLoader] Cache expired for: ${e}`)):(this.cache.delete(e),s.lastAccess=r,this.cache.set(e,s),s.code)}_cacheSet(e,t){this.cache.has(e)&&this.cache.delete(e),this._evictIfNeeded();const s=Date.now();this.cache.set(e,{code:t,timestamp:s,lastAccess:s})}_evictIfNeeded(){const e=Date.now();for(const[s,r]of this.cache)e-r.timestamp>this.cacheTTL&&(this.cache.delete(s),t.debug(`[WuLoader] Evicted expired entry: ${s}`));for(;this.cache.size>=this.maxCacheSize;){const e=this.cache.keys().next().value;this.cache.delete(e),t.debug(`[WuLoader] Evicted LRU entry: ${e}`)}}async loadApp(e,s){await this._ensureSentinelVerified();const r=`${e}/${s?.entry||"index.js"}`;t.debug(`[WuLoader] Loading app from: ${r}`);try{const e=this._cacheGet(r);if(void 0!==e)return t.debug(`[WuLoader] Cache hit for: ${r}`),e;if(this.loadingPromises.has(r))return t.debug(`[WuLoader] Loading in progress for: ${r}`),await this.loadingPromises.get(r);const s=this.fetchCode(r);this.loadingPromises.set(r,s);const n=await s;return this.loadingPromises.delete(r),this._cacheSet(r,n),t.debug(`[WuLoader] App loaded successfully: ${r}`),n}catch(e){throw this.loadingPromises.delete(r),console.error(`[WuLoader] Failed to load app: ${r}`,e),new Error(`Failed to load app from ${r}: ${e.message}`)}}async loadComponent(e,s){await this._ensureSentinelVerified();let r=s;r.startsWith("./")&&(r=r.substring(2)),r.endsWith(".js")||r.endsWith(".jsx")||(r+=".js");const n=`${e}/${r}`;t.debug(`[WuLoader] Loading component from: ${n}`);try{const e=await this.loadCode(n),r=new Function("require","module","exports",`\n ${e}\n return typeof module.exports === 'function' ? module.exports :\n typeof module.exports === 'object' && module.exports.default ? module.exports.default :\n exports.default || exports;\n `),i={exports:{}},o=r(e=>(t.warn(`[WuLoader] Component ${s} requires ${e} - not supported yet`),{}),i,i.exports);return t.debug(`[WuLoader] Component loaded: ${s}`),o}catch(e){throw console.error(`[WuLoader] Failed to load component: ${s}`,e),new Error(`Failed to load component ${s}: ${e.message}`)}}async loadCode(e){const t=this._cacheGet(e);if(void 0!==t)return t;if(this.loadingPromises.has(e))return await this.loadingPromises.get(e);const s=this.fetchCode(e);this.loadingPromises.set(e,s);try{const t=await s;return this.loadingPromises.delete(e),this._cacheSet(e,t),t}catch(t){throw this.loadingPromises.delete(e),t}}async fetchCode(e,t=3e4){const s=await fetch(e,{cache:"no-cache",headers:{Accept:"application/javascript, text/javascript, */*"},signal:AbortSignal.timeout(t)});if(!s.ok)throw new Error(`HTTP ${s.status}: ${s.statusText}`);const r=await s.text();if(!r.trim())throw new Error("Empty response");return r}async preload(e){t.debug(`[WuLoader] Preloading ${e.length} apps...`);const s=e.map(async e=>{try{await this.loadApp(e.url,e.manifest),t.debug(`[WuLoader] Preloaded: ${e.name}`)}catch(s){t.warn(`[WuLoader] Failed to preload ${e.name}:`,s.message)}});await Promise.allSettled(s),t.debug("[WuLoader] Preload completed")}async isAvailable(e){try{return(await fetch(e,{method:"HEAD",signal:AbortSignal.timeout(5e3)})).ok}catch{return!1}}async resolveDependencies(e,s){const r=new Map;for(const n of e||[]){const[e,i]=n.split(".");if(!e||!i){t.warn(`[WuLoader] Invalid import format: ${n}`);continue}const o=s.get(e);if(!o){t.warn(`[WuLoader] Import app not found: ${e}`);continue}const a=o.manifest,c=a?.wu?.exports?.[i];if(c)try{const e=await this.loadComponent(o.url,c);r.set(n,e),t.debug(`[WuLoader] Resolved dependency: ${n}`)}catch(e){console.error(`[WuLoader] Failed to resolve: ${n}`,e)}else t.warn(`[WuLoader] Export not found: ${n}`)}return r}clearCache(e){if(e){let s;try{s=new RegExp(e)}catch(s){return void t.warn(`[WuLoader] Invalid clearCache pattern: ${e} (${s.message})`)}for(const[e]of this.cache)s.test(e)&&(this.cache.delete(e),t.debug(`[WuLoader] Cleared cache for: ${e}`))}else this.cache.clear(),t.debug("[WuLoader] Cache cleared completely")}getStats(){return{cached:this.cache.size,maxCacheSize:this.maxCacheSize,cacheTTL:this.cacheTTL,loading:this.loadingPromises.size,cacheKeys:Array.from(this.cache.keys())}}async _ensureSentinelVerified(){if("undefined"==typeof window)return;const e=window.location?.hostname||"";"localhost"!==e&&"127.0.0.1"!==e&&"0.0.0.0"!==e&&window.__wu_sentinel&&(window.__wu_sentinel.isVerified()||await new Promise((e,t)=>{if(window.__wu_sentinel.isVerified())return void e();const s=setTimeout(()=>{n(),t(new Error("[WuLoader] Sentinel verification timeout — content blocked"))},1e4),r=()=>{n(),e()};function n(){clearTimeout(s),window.removeEventListener("wu:sentinel:verified",r)}window.addEventListener("wu:sentinel:verified",r);const i=setInterval(()=>{window.__wu_sentinel.isVerified()&&(clearInterval(i),n(),e())},100),o=n;n=function(){clearInterval(i),o()}}))}}var M=Object.freeze({__proto__:null,WuLoader:P});const L=new Set(["provider","action","trigger","capability","workflow","removeApp","init"]),T=new Set(["context","conversation","permissions"]),I={tools:()=>[],expose:()=>!1,getStats:()=>({initialized:!1,lazy:!0})},N=new Set(["abort","destroy","confirmTool","rejectTool","fireTrigger"]),O=new Set(["stream","agent","runWorkflow"]);if(exports.wu=void 0,"undefined"!=typeof window&&window.wu&&window.wu._isWuFramework)exports.wu=window.wu;else if(exports.wu=new D,exports.wu._isWuFramework=!0,"undefined"!=typeof window){const e=Symbol.for("wu-framework");window[e]=exports.wu}if("undefined"!=typeof window&&(window.wu&&!window.wu._isWuFramework&&console.warn('[Wu Framework] window.wu already exists and is not a Wu Framework instance. Overwriting. Use Symbol.for("wu-framework") for collision-safe access.'),window.wu=exports.wu),exports.wu.version||(exports.wu.version="2.6.0",exports.wu.info={name:"Wu Framework",description:"Universal Microfrontends",features:["Framework Agnostic","Zero Config","Shadow DOM Isolation","Runtime Loading"]}),exports.wu.emit||(exports.wu.emit=(e,t,s)=>exports.wu.eventBus.emit(e,t,s),exports.wu.on=(e,t)=>exports.wu.eventBus.on(e,t),exports.wu.once=(e,t)=>exports.wu.eventBus.once(e,t),exports.wu.off=(e,t)=>exports.wu.eventBus.off(e,t)),exports.wu.prefetch||(exports.wu.prefetch=(e,t)=>exports.wu.prefetcher.prefetch(e,t),exports.wu.prefetchAll=e=>exports.wu.prefetcher.prefetchAll(e)),exports.wu.override||(exports.wu.override=(e,t,s)=>exports.wu.overrides.set(e,t,s),exports.wu.removeOverride=e=>exports.wu.overrides.remove(e),exports.wu.getOverrides=()=>exports.wu.overrides.getAll(),exports.wu.clearOverrides=()=>exports.wu.overrides.clearAll()),exports.wu.provide||(exports.wu.provide=(e,t,s)=>exports.wu.contracts.provide(e,t,s),exports.wu.consume=(e,t,s)=>exports.wu.contracts.consume(e,t,s)),exports.wu.silence||(exports.wu.silence=async()=>{const{silenceAllLogs:e}=await Promise.resolve().then(function(){return n});e()},exports.wu.verbose=async()=>{const{enableAllLogs:e}=await Promise.resolve().then(function(){return n});e()}),exports.wu.ai||function(e){let t=null,s=null;const r=[],n=()=>t?Promise.resolve(t):s||(s=Promise.resolve().then(function(){return Ze}).then(({WuAI:s})=>{t=new s({eventBus:e.eventBus,store:e.store,core:e,token:e.eventBus.getInternalToken?.("wu-ai")||null});for(const e of r)try{if("method"===e.kind)t[e.prop](...e.args);else if("sub"===e.kind){const s=t[e.parent];s&&"function"==typeof s[e.prop]&&s[e.prop](...e.args)}}catch(e){setTimeout(()=>{throw e},0)}return r.length=0,t}),s),i=new Proxy({},{get(e,s){if(t){const e=Reflect.get(t,s);return"function"==typeof e?e.bind(t):e}return"isLazy"===s||"isLoaded"!==s&&(T.has(s)?(o=s,new Proxy({},{get(e,s){if(t){const e=t[o],r=e?.[s];return"function"==typeof r?r.bind(e):r}return(...e)=>{r.push({kind:"sub",parent:o,prop:s,args:e}),n()}}})):L.has(s)?(...e)=>(r.push({kind:"method",prop:s,args:e}),n(),i):N.has(s)?(...e)=>{r.push({kind:"method",prop:s,args:e}),n()}:s in I?I[s]:O.has(s)?async function*(...e){const t=await n();yield*t[s](...e)}:(...e)=>n().then(t=>{const r=t[s];return"function"==typeof r?r.apply(t,e):r}));var o}});Object.defineProperty(e,"ai",{get:()=>t||i,configurable:!0}),e.aiReady=n}(exports.wu),"undefined"==typeof window||window.__WU_DEVTOOLS__||(window.__WU_DEVTOOLS__={version:exports.wu.version,isWu:!0,inspect:e=>exports.wu.inspect(e),show:()=>exports.wu.showInspector(),hide:()=>exports.wu.hideInspector(),subscribe:e=>exports.wu.eventBus.on("*",e)}),!exports.wu.mcp){let e=null;exports.wu.mcp={async connect(t="ws://localhost:19100",s={}){if(!e){const{createMcpBridge:t}=await Promise.resolve().then(function(){return et});e=t(exports.wu)}e.connect(t,s)},disconnect(){e?.disconnect()},isConnected:()=>e?.isConnected()||!1}}if(!exports.wu.timeline){let e,t=null,s=null,r=!1;const n=()=>t?Promise.resolve(t):(s||(s=exports.wu._ensureTimeline().then(s=>(t=s,r&&!s.status().recording&&s.record(e),s))),s),i=Object.freeze({loaded:!1,recording:!1,live:!0,position:0,length:0,site:null,lamport:0,snapshots:0}),o={record:s=>(r=!0,e=s,t?t.status().recording||t.record(s):n(),o),stop:()=>(r=!1,t&&t.stop(),o),clear:()=>(n().then(e=>e.clear()),o),seek:(e,t)=>n().then(s=>s.seek(e,t)),live:()=>n().then(e=>e.live()),stepBack:()=>n().then(e=>e.stepBack()),stepForward:()=>n().then(e=>e.stepForward()),export:()=>n().then(e=>e.export()),import:e=>n().then(t=>t.import(e)),ingest:e=>n().then(t=>t.ingest(e)),entries:()=>t?t.entries():[],status:()=>t?t.status():{...i},get loaded(){return!!t},get instance(){return t}};exports.wu.timeline=o,exports.wu.timelineReady=n}var R=exports.wu;function j(e){if(null===e||"object"!=typeof e)return e;if("function"==typeof structuredClone)try{return structuredClone(e)}catch{}try{return JSON.parse(JSON.stringify(e))}catch{return e}}function B(e){let s=null,r=[];const n=()=>{for(;r.length&&1===e.readyState;)e.send(r.shift())},i=e=>{try{s&&s("string"==typeof e.data?JSON.parse(e.data):e.data)}catch{}};return e.addEventListener("open",n),e.addEventListener("message",i),{send(s){let n;try{n=JSON.stringify(s)}catch(e){return void t.wuWarn(`[WuStoreSync] message not JSON-serializable, dropped: ${e?.message||e}`)}1!==e.readyState?e.readyState>=2||(r.length>=1e3&&r.shift(),r.push(n)):e.send(n)},onMessage(e){s=e},close(){try{e.removeEventListener("open",n),e.removeEventListener("message",i)}catch{}s=null,r=[];try{e.close()}catch{}}}}function F(e){const t=e.transport;if(t&&"function"==typeof t.send&&"function"==typeof t.onMessage)return t;if(void 0===t||"broadcast"===t)return function(e){if("undefined"==typeof BroadcastChannel)throw new Error("[WuStoreSync] BroadcastChannel is not available in this environment.");const t=new BroadcastChannel(`wu-store:${e}`);let s=null;const r=e=>{s&&s(e.data)};return t.addEventListener("message",r),{send(e){t.postMessage(e)},onMessage(e){s=e},close(){try{t.removeEventListener("message",r)}catch{}s=null;try{t.close()}catch{}}}}(e.room||"default");if("undefined"!=typeof WebSocket&&t instanceof WebSocket)return B(t);if("string"==typeof t&&/^wss?:\/\//.test(t)){if("undefined"==typeof WebSocket)throw new Error("[WuStoreSync] WebSocket not available.");return B(new WebSocket(t))}throw new Error('[WuStoreSync] Unknown transport. Use "broadcast", a WebSocket/URL, or { send, onMessage, close }.')}var z=Object.freeze({__proto__:null,WuStoreSync:class{constructor(e){this.store=e,this.site=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();const e=()=>Math.random().toString(36).slice(2,10);return`${Date.now().toString(36)}-${e()}${e()}`}(),this._lamport=0,this._clocks=new Map,this._transport=null,this._untap=null,this._applyingRemote=!1,this._outbox=[],this._flushScheduled=!1,this._connected=!1,this._peers=new Set,this.stats={sent:0,received:0,applied:0,ignored:0,dropped:0}}connect(e={}){return this._connected||(this._transport=F(e),this._transport.onMessage(e=>this._receive(e)),this._untap=this.store.tap((e,s,r)=>{if(!this._applyingRemote&&s){if(!function(e){const t=typeof e;return!("bigint"===t||"function"===t||"symbol"===t)}(r))return t.wuWarn(`[WuStoreSync] '${s}' not synced: value type '${typeof r}' is not serializable.`),void(this.stats.dropped+=1);this._pruneDescendants(s),this._lamport+=1,this._clocks.set(s,{l:this._lamport,site:this.site}),this._outbox.push({path:s,value:j(r),l:this._lamport,site:this.site}),this._scheduleFlush()}}),this._connected=!0,this._send({t:"hello"})),this}stop(){return this._untap&&(this._untap(),this._untap=null),this._outbox.length=0,this._flushScheduled=!1,this._connected=!1,this._transport&&(this._transport.close(),this._transport=null),this}status(){return{connected:this._connected,site:this.site,lamport:this._lamport,peers:this._peers.size,tracked:this._clocks.size,...this.stats}}_scheduleFlush(){this._flushScheduled||(this._flushScheduled=!0,queueMicrotask(()=>{this._flushScheduled=!1,this._connected&&this._outbox.length&&this._send({t:"op",ops:this._outbox.splice(0)})}))}_send(e){if(this._transport){e.from=this.site;try{this._transport.send(e),this.stats.sent+=1}catch{}}}_receive(e){if(this._connected&&e&&e.from!==this.site)if(this.stats.received+=1,e.from&&this._peers.size<1024&&this._peers.add(e.from),"op"===e.t)for(const t of e.ops||[])this._applyOp(t);else if("hello"===e.t){const t=this._snapshotOps();t.length&&this._send({t:"op",ops:t,to:e.from})}}_applyOp(e){if(!e||"string"!=typeof e.path||!e.path||"number"!=typeof e.l)return;this._lamport=Math.max(this._lamport,e.l);const t=this._clocks.get(e.path);if(!t||this._isNewer(e,t)){this._pruneDescendants(e.path),this._clocks.set(e.path,{l:e.l,site:e.site}),this._applyingRemote=!0;try{this.store.set(e.path,e.value),this.stats.applied+=1}catch{this._clocks.delete(e.path),this.stats.ignored+=1}finally{this._applyingRemote=!1}}else this.stats.ignored+=1}_isNewer(e,t){return e.l!==t.l?e.l>t.l:String(e.site)>String(t.site)}_pruneDescendants(e){const t=`${e}.`;for(const e of this._clocks.keys())e.startsWith(t)&&this._clocks.delete(e)}_snapshotOps(){const e=[];for(const[t,s]of this._clocks){const r=this.store.get(t);void 0!==r&&e.push({path:t,value:j(r),l:s.l,site:s.site})}return e.sort((e,t)=>e.path.split(".").length-t.path.split(".").length),e}}});const H=e=>{const t=String(e);return"undefined"!=typeof CSS&&"function"==typeof CSS.escape?CSS.escape(t):t.replace(/[^a-zA-Z0-9_\u00A0-\uFFFF-]/g,"\\$&").replace(/^(\d)/,(e,t)=>`\\3${t} `)};var U=Object.freeze({__proto__:null,WuIframeSandbox:class{constructor(e){this.appName=e,this.iframe=null,this._active=!1,this._timers=new Set,this._intervals=new Set,this._rafs=new Set,this._listeners=[]}activate(e,s,r){if(this._active)return this.iframe.contentWindow;const n=document.createElement("iframe");n.setAttribute("data-wu-sandbox",this.appName),n.style.cssText="display:none !important;position:absolute;width:0;height:0;border:0;",document.body.appendChild(n),this.iframe=n;const i=e.replace(/\/$/,""),o=n.contentWindow,a=o.document;return a.open(),a.write(`<!DOCTYPE html><html><head><base href="${i}/"></head><body></body></html>`),a.close(),o.wu=this._buildRestrictedWu(window.wu),o.__wuHostPostMessage=e=>window.postMessage(e,"*"),this._confineParentAccess(o),this._patchDocument(o,s,r),this._patchTimers(o),this._active=!0,t.wuDebug(`[IframeSandbox] Activated for ${this.appName} (base: ${i})`),o}_buildRestrictedWu(e){if(!e)return;const t=t=>"function"==typeof t?t.bind(e):t,s=e.store?Object.freeze({get:t(e.store.get),set:t(e.store.set),on:t(e.store.on),batch:t(e.store.batch)}):null,r=e.eventBus?Object.freeze({emit:t(e.eventBus.emit),on:t(e.eventBus.on),off:t(e.eventBus.off),once:t(e.eventBus.once),registerApp:t(e.eventBus.registerApp),unregisterApp:t(e.eventBus.unregisterApp)}):null,n={version:e.version,info:e.info,_isWuFramework:!0,define:t(e.define),mount:t(e.mount),unmount:t(e.unmount),app:t(e.app),hide:t(e.hide),show:t(e.show),isHidden:t(e.isHidden),store:s,eventBus:r,emit:t(e.emit),on:t(e.on),off:t(e.off),once:t(e.once),getState:t(e.getState),setState:t(e.setState),onStateChange:t(e.onStateChange),ai:e.ai,aiReady:t(e.aiReady),getStats:t(e.getStats),getSandboxInfo:t(e.getSandboxInfo),silence:t(e.silence),verbose:t(e.verbose)};return Object.freeze(n)}_confineParentAccess(e){const s=window,r=new Proxy(e,{get(e,t){if("postMessage"===t)return(...e)=>s.postMessage(...e);const r=Reflect.get(e,t);return"function"==typeof r?r.bind(e):r}});for(const s of["parent","top"])try{Object.defineProperty(e,s,{get:()=>r,configurable:!0})}catch{t.wuDebug(`[IframeSandbox] Could not confine window.${s}`)}try{Object.defineProperty(e,"frameElement",{get:()=>null,configurable:!0})}catch{t.wuDebug("[IframeSandbox] Could not confine window.frameElement")}}importModule(e,s=3e4){if(!this._active)throw new Error(`[IframeSandbox] Not active for ${this.appName}`);return new Promise((r,n)=>{const i=`wu_${this.appName}_${Date.now()}`,o=e=>{e.data?.channelId===i&&(c(),e.data.error?n(new Error(e.data.error)):r())},a=setTimeout(()=>{c(),n(new Error(`[IframeSandbox] import() timed out for ${this.appName}: ${e}`))},s),c=()=>{window.removeEventListener("message",o),clearTimeout(a)};window.addEventListener("message",o);const l=this.iframe.contentWindow.document,u=l.createElement("script");u.type="module",u.textContent=`import("${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}").then(() => __wuHostPostMessage({ channelId: "${i}", success: true })).catch(e => __wuHostPostMessage({ channelId: "${i}", error: e.message || String(e) }));`,l.head.appendChild(u),t.wuDebug(`[IframeSandbox] Importing module: ${e}`)})}_patchDocument(e,s,r){const n=e.document,i=r||s,o=document;n.createElement=(e,t)=>o.createElement(e,t),n.createElementNS=(e,t,s)=>o.createElementNS(e,t,s),n.createTextNode=e=>o.createTextNode(e),n.createComment=e=>o.createComment(e),n.createDocumentFragment=()=>o.createDocumentFragment(),n.querySelector=e=>i.querySelector(e),n.querySelectorAll=e=>i.querySelectorAll(e),n.getElementById=e=>i.querySelector(`#${H(e)}`),n.getElementsByClassName=e=>i.querySelectorAll(`.${H(e)}`),n.getElementsByTagName=e=>i.querySelectorAll(e);try{Object.defineProperty(n,"body",{get:()=>s,configurable:!0})}catch{t.wuDebug("[IframeSandbox] Could not redefine document.body")}const a=n.addEventListener.bind(n),c=n.removeEventListener.bind(n);n.addEventListener=(e,t,s)=>{this._listeners.push({target:n,event:e,handler:t,options:s}),a(e,t,s)},n.removeEventListener=(e,t,s)=>{this._listeners=this._listeners.filter(s=>!(s.target===n&&s.event===e&&s.handler===t)),c(e,t,s)},t.wuDebug(`[IframeSandbox] Document patched for ${this.appName}`)}_patchTimers(e){const s=e.setTimeout.bind(e),r=e.clearTimeout.bind(e),n=e.setInterval.bind(e),i=e.clearInterval.bind(e);if(e.setTimeout=(e,t,...r)=>{const n=s((...t)=>{this._timers.delete(n),"function"==typeof e&&e(...t)},t,...r);return this._timers.add(n),n},e.clearTimeout=e=>{this._timers.delete(e),r(e)},e.setInterval=(e,t,...s)=>{const r=n(e,t,...s);return this._intervals.add(r),r},e.clearInterval=e=>{this._intervals.delete(e),i(e)},e.requestAnimationFrame){const t=e.requestAnimationFrame.bind(e),s=e.cancelAnimationFrame.bind(e);e.requestAnimationFrame=e=>{const s=t((...t)=>{this._rafs.delete(s),e(...t)});return this._rafs.add(s),s},e.cancelAnimationFrame=e=>{this._rafs.delete(e),s(e)}}t.wuDebug(`[IframeSandbox] Timer tracking active for ${this.appName}`)}destroy(){if(this._active){this._active=!1;for(const e of this._timers)try{clearTimeout(e)}catch{}for(const e of this._intervals)try{clearInterval(e)}catch{}for(const e of this._rafs)try{cancelAnimationFrame(e)}catch{}this._timers.clear(),this._intervals.clear(),this._rafs.clear();for(const{target:e,event:t,handler:s,options:r}of this._listeners)try{e.removeEventListener(t,s,r)}catch{}if(this._listeners=[],this.iframe){try{const e=this.iframe.contentDocument;e&&(e.open(),e.write(""),e.close())}catch{}this.iframe.parentNode&&this.iframe.parentNode.removeChild(this.iframe),this.iframe=null}t.wuDebug(`[IframeSandbox] Destroyed for ${this.appName}`)}}isActive(){return this._active}}});var q=Object.freeze({__proto__:null,WuHtmlParser:class{constructor(){this._cache=new Map}async fetchHtml(e,s){t.wuDebug(`[HtmlParser] Fetching HTML for ${s} from ${e}`);const r=await fetch(e,{method:"GET",headers:{Accept:"text/html,application/xhtml+xml,*/*"}});if(!r.ok)throw new Error(`[HtmlParser] Failed to fetch ${e}: HTTP ${r.status}`);const n=await r.text();if(!n||!n.trim())throw new Error(`[HtmlParser] Empty HTML response from ${e}`);return t.wuDebug(`[HtmlParser] Fetched ${n.length} chars for ${s}`),n}parse(e,s,r){const n=`${s}:${e.length}`;if(this._cache.has(n))return this._cache.get(n);const i=(new DOMParser).parseFromString(e,"text/html"),o=[],a=[],c=[],l=[],u={inlineScripts:o,externalScripts:a,inlineStyles:c,externalStyles:l,baseUrl:r};i.head&&this._extractResources(i.head,u);const d=i.body||i.documentElement;this._extractResources(d,u);const h={dom:d.innerHTML,scripts:{inline:o,external:a},styles:{inline:c,external:l}};return this._cache.set(n,h),t.wuDebug(`[HtmlParser] ${s}: ${o.length} inline scripts, ${a.length} external scripts, ${c.length+l.length} styles`),h}async fetchAndParse(e,t){const s=await this.fetchHtml(e,t);return this.parse(s,t,e)}_extractResources(e,t){const s=Array.from(e.children);for(const e of s){const s=e.nodeName.toLowerCase();if("script"!==s){if("style"===s){const s=e.textContent?.trim();s&&t.inlineStyles.push(s),e.replaceWith(document.createComment("wu:style"));continue}if("link"===s){const s=e.getAttribute("rel"),r=e.getAttribute("href");if("stylesheet"===s&&r){t.externalStyles.push(this._resolveUrl(r,t.baseUrl)),e.replaceWith(document.createComment("wu:link"));continue}}e.children.length>0&&this._extractResources(e,t)}else this._extractScript(e,t),e.replaceWith(document.createComment("wu:script"))}}_extractScript(e,s){const r=e.getAttribute("type")||"",n=e.getAttribute("src");if("module"!==r)if(n)s.externalScripts.push(this._resolveUrl(n,s.baseUrl));else{const t=e.textContent?.trim();t&&s.inlineScripts.push(t)}else t.wuDebug('[HtmlParser] Skipping type="module" script (use sandbox: "module" for ES modules)')}_resolveUrl(e,t){if(e.startsWith("http://")||e.startsWith("https://"))return e;if(e.startsWith("//"))return`https:${e}`;try{return new URL(e,t).href}catch{const s=t.replace(/\/$/,"");return e.startsWith("/")?s+e:`${s}/${e}`}}clearCache(){this._cache.clear()}}});class J{static DANGEROUS_PATTERNS=[{pattern:/constructor\s*\[\s*['"`]constructor['"`]\s*\]/,label:"constructor chain access (sandbox escape)"},{pattern:/__proto__/,label:"__proto__ access (prototype pollution)"},{pattern:/Object\s*\.\s*getPrototypeOf\s*\(\s*proxy\s*\)/,label:"Object.getPrototypeOf(proxy) (sandbox escape)"},{pattern:/Function\s*\(\s*['"`]/,label:"Function() constructor (dynamic code generation)"},{pattern:/\beval\s*\(/,label:"eval() (dynamic code execution)"},{pattern:/\bimport\s*\(/,label:"import() (dynamic import escapes sandbox)"},{pattern:/document\s*\.\s*cookie/,label:"document.cookie (direct cookie access)"}];_validateScript(e,s){for(const{pattern:r,label:n}of J.DANGEROUS_PATTERNS)if(r.test(e)){const e=`[ScriptExecutor] Blocked dangerous pattern in "${s}": ${n}`;throw t.wuError(e),new Error(e)}}execute(e,s,r,n={}){const{strictGlobal:i=!0,sourceUrl:o=""}=n;if(!e||!e.trim())return;this._validateScript(e,s);const a=o?`\n//# sourceURL=wu-sandbox:///${s}/${o}\n`:"";let c,l;c=i?`;(function(window, self, globalThis, top, parent) {\n with(window) {\n ;${e}${a}\n }\n}).call(proxy, proxy, proxy, proxy, proxy, proxy);`:`;(function(window, self, globalThis, top, parent) {\n ;${e}${a}\n}).call(proxy, proxy, proxy, proxy, proxy, proxy);`;try{l=new Function("proxy",c)}catch(o){if(i)return t.wuWarn(`[ScriptExecutor] strictGlobal failed for ${s}, retrying without with(): ${o.message}`),this.execute(e,s,r,{...n,strictGlobal:!1});throw t.wuError(`[ScriptExecutor] Execution failed for ${s}:`,o),o}try{return l(r)}catch(e){throw t.wuError(`[ScriptExecutor] Execution failed for ${s}:`,e),e}}async fetchScript(e){const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch script ${e}: HTTP ${t.status}`);return t.text()}async executeAll(e,s,r,n={}){for(const i of e){let e=i.content;!e&&i.src&&(t.wuDebug(`[ScriptExecutor] Fetching external script: ${i.src}`),e=await this.fetchScript(i.src)),e&&e.trim()&&this.execute(e,s,r,{...n,sourceUrl:i.src||n.sourceUrl||""})}t.wuDebug(`[ScriptExecutor] Executed ${e.length} scripts for ${s}`)}}var G=Object.freeze({__proto__:null,WuScriptExecutor:J});let V=null,K=null,Q=null,Y=!1;function X(e){return String(e).replace(/[&<>]/g,e=>({"&":"&amp;","<":"&lt;",">":"&gt;"}[e]))}function Z(e,t){const s=t.inspect(),r=s.apps.length?s.apps.map(e=>`\n <div class="app">\n <div><span class="name">${X(e.name)}</span>\n <span class="badge ${"mounted"===e.status?"b-mounted":"b-hidden"}">${e.status}</span>\n <span class="badge ${e.liveProps?"b-live":"b-static"}">${e.liveProps?"live props":"static props"}</span>\n </div>\n <div class="row"><span class="k">container</span> ${X(e.containerSelector||"—")}</div>\n <div class="row"><span class="k">sandbox</span> ${X(e.sandbox?.isolationLevel||e.sandbox?.styleMode||"—")}</div>\n </div>`).join(""):'<div class="empty">No apps mounted</div>',n=s.events.recent.length?s.events.recent.slice().reverse().map(e=>`<div class="ev"><span class="t">${X(e.type||"?")}</span> ${X(e.appName||"")}</div>`).join(""):'<div class="empty">No events yet</div>',i=s.capabilities&&s.capabilities.length?s.capabilities.map(e=>`\n <div class="app">\n <div><span class="name">${X(e.name)}</span>\n <span class="badge b-live">v${X(e.version)}</span>\n ${e.app?`<span class="badge b-static">${X(e.app)}</span>`:""}\n </div>\n </div>`).join(""):'<div class="empty">No capabilities provided</div>';e.querySelector(".body").innerHTML=`\n <div class="row"><span class="k">apps</span>\n ${s.summary.mounted} mounted · ${s.summary.hidden} hidden · ${s.summary.registered} registered</div>\n <h4>Apps</h4>${r}\n <h4>Capabilities</h4>${i}\n <h4>Recent events</h4>${n}\n <h4>Store</h4>\n <pre>${X(JSON.stringify(s.store.snapshot??{},null,2)).slice(0,2e3)}</pre>\n `}function ee(e){const t=e.querySelector(".tl-range"),s=e.querySelector(".tl-rec"),r=e.querySelector(".tl-pos"),n=e.querySelector(".tl-state"),i=e.querySelector(".tl-live");if(!t)return;const o=Q?Q.status():{recording:!1,live:!0,position:0,length:0};t.max=String(o.length),Y||(t.value=String(Math.min(o.position,o.length))),t.disabled=!Q||0===o.length&&!o.recording,s.textContent=o.recording?"■ Stop":"● Rec",s.classList.toggle("on",!!o.recording),s.disabled=!Q,r.textContent=o.length?`${o.position}/${o.length}`:"—",n.textContent=Q?o.recording&&o.live?"rec ● live":o.recording?"rec ⏸ past":o.live?"stopped":"⏪ past":"idle",i.style.display=Q&&!o.live?"":"none"}function te(){K&&(clearInterval(K),K=null),V&&(V.remove(),V=null),Q=null,Y=!1}var se=Object.freeze({__proto__:null,mountInspector:function(e){if(V){if(V.isConnected)return{close:te};te()}Y=!1,V=document.createElement("div"),V.id="wu-devtools-overlay";const t=V.attachShadow({mode:"open"});t.innerHTML=`\n <style>\n :host { all: initial; }\n .panel {\n position: fixed; bottom: 16px; right: 16px; z-index: 2147483647;\n width: 360px; max-height: 70vh; display: flex; flex-direction: column;\n font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace;\n color: #e5e7eb; background: #0b1020; border: 1px solid #2a3350;\n border-radius: 10px; box-shadow: 0 12px 40px rgba(0,0,0,.5); overflow: hidden;\n }\n .head {\n display: flex; align-items: center; gap: 8px; padding: 8px 12px;\n background: linear-gradient(90deg,#6366f1,#14b8a6); color: #fff; font-weight: 600;\n }\n .head .ver { opacity: .85; font-weight: 400; }\n .head .x { margin-left: auto; cursor: pointer; background: rgba(255,255,255,.15);\n border: none; color: #fff; border-radius: 6px; width: 22px; height: 22px; }\n .tl { display: flex; align-items: center; gap: 8px; padding: 6px 12px;\n background: #0e1428; border-bottom: 1px solid #1c2540; }\n .tl button { cursor: pointer; border: 1px solid #2a3350; background: #141b33;\n color: #e5e7eb; border-radius: 6px; padding: 2px 8px; font: inherit; white-space: nowrap; }\n .tl button.on { background: #7f1d1d; border-color: #b91c1c; color: #fecaca; }\n .tl .tl-range { flex: 1; min-width: 40px; accent-color: #6366f1; }\n .tl .tl-pos { color: #93c5fd; min-width: 44px; text-align: right; }\n .tl .tl-state { color: #fbbf24; min-width: 56px; font-size: 10px; }\n .body { overflow: auto; padding: 8px 12px; }\n .row { display: flex; gap: 6px; padding: 2px 0; }\n .k { color: #93c5fd; }\n h4 { margin: 12px 0 4px; color: #a5b4fc; font-size: 11px; text-transform: uppercase; letter-spacing: .04em; }\n .app { border: 1px solid #232c47; border-radius: 7px; padding: 6px 8px; margin: 5px 0; background: #0e1428; }\n .app .name { font-weight: 700; color: #fff; }\n .badge { display: inline-block; padding: 0 6px; border-radius: 999px; font-size: 10px; margin-left: 4px; }\n .b-mounted { background: #064e3b; color: #6ee7b7; }\n .b-hidden { background: #4c1d95; color: #ddd6fe; }\n .b-live { background: #1e3a8a; color: #bfdbfe; }\n .b-static { background: #3f3f46; color: #d4d4d8; }\n .ev { color: #cbd5e1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n .ev .t { color: #fbbf24; }\n pre { margin: 4px 0 0; padding: 6px; background: #060a16; border-radius: 6px; overflow: auto;\n max-height: 120px; color: #a7f3d0; }\n .empty { opacity: .5; }\n</style>\n <div class="panel">\n <div class="head">Wu Inspector <span class="ver">v${X(e.version||"")}</span>\n <button class="x" title="Close">×</button>\n </div>\n <div class="tl">\n <button class="tl-rec" title="Record / stop time travel">● Rec</button>\n <input class="tl-range" type="range" min="0" max="0" value="0" step="1" title="Scrub the page through time" />\n <span class="tl-pos">—</span>\n <span class="tl-state">idle</span>\n <button class="tl-live" title="Return to the present" style="display:none">⏭ Live</button>\n </div>\n <div class="body"></div>\n </div>\n `,document.body.appendChild(V),t.querySelector(".x").addEventListener("click",()=>te());const s=t.querySelector(".tl-range");return t.querySelector(".tl-rec").addEventListener("click",()=>{Q&&(Q.status().recording?Q.stop():Q.record(),setTimeout(()=>V&&ee(t),30))}),s.addEventListener("input",()=>{Y=!0,Q&&Q.seek(Number(s.value))}),s.addEventListener("change",()=>{Y=!1}),t.querySelector(".tl-live").addEventListener("click",()=>{Y=!1,Q&&Q.live(),setTimeout(()=>V&&ee(t),30)}),"function"==typeof e._ensureTimeline&&e._ensureTimeline().then(e=>{Q=e,V&&ee(t)}).catch(()=>{}),Z(t,e),ee(t),K=setInterval(()=>{V&&V.isConnected?(Z(t,e),ee(t)):te()},1e3),{close:te}},unmountInspector:te});const re="wu-timeline/1";function ne(e){return"__proto__"!==e&&"constructor"!==e&&"prototype"!==e}function ie(e){if(null===e||"object"!=typeof e)return e;if("function"==typeof structuredClone)try{return structuredClone(e)}catch{}try{return JSON.parse(JSON.stringify(e))}catch{return e}}function oe(e,t,s){if(!t)return s;const r=String(t).split(".");if(!r.every(ne))return e;let n=e;for(let e=0;e<r.length-1;e++){const t=r[e];Object.prototype.hasOwnProperty.call(n,t)&&"object"==typeof n[t]&&null!==n[t]||(n[t]={}),n=n[t]}return n[r[r.length-1]]=s,e}function ae(e=[],t=[]){const s=new Set,r=[];for(const n of[...e,...t]){if(!n||"number"!=typeof n.l||!n.site)continue;const e=`${n.l}|${n.site}`;s.has(e)||(s.add(e),r.push(n))}return r.sort((e,t)=>e.l-t.l||(e.site<t.site?-1:e.site>t.site?1:0)),r}var ce=Object.freeze({__proto__:null,TIMELINE_FORMAT:re,WuTimeline:class{constructor(e){this.wu=e,this.site=function(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();const e=()=>Math.random().toString(36).slice(2,10);return`${Date.now().toString(36)}-${e()}${e()}`}(),this._entries=[],this._snapshots=[],this._baselineApps=[],this._lamport=0,this._position=0,this._recording=!1,this._applying=!1,this._storeWritesSinceSnap=0,this._untapStore=null,this._untapBus=null,this._seekChain=Promise.resolve(),this._pastWarned=!1,this._opts={snapshotEvery:64,maxEntries:5e3}}record(e={}){return this._recording||(this._opts={...this._opts,...e},this._entries=[],this._snapshots=[{at:0,state:ie(this.wu.store.get())||{}}],this._baselineApps=this._captureApps(),this._position=0,this._storeWritesSinceSnap=0,this._pastWarned=!1,this._recording=!0,this._untapStore=this.wu.store.tap((e,t,s)=>{this._shouldJournal()&&this._push({kind:"store",seq:e,path:t,value:ie(s)})}),this._untapBus=this.wu.eventBus.tap(e=>{if(!this._shouldJournal())return;if("string"==typeof e.name&&e.name.startsWith("timeline:"))return;const t={kind:"event",name:e.name,appName:e.appName};if("app:mounted"===e.name)t.container=this.wu.mounted.get(e.data?.appName)?.containerSelector||null;else if("app:updated"===e.name){const s=this.wu.mounted.get(e.data?.appName)||this.wu.hidden.get(e.data?.appName);t.props=ie(s?.props??e.data?.props??null)}this._push(t)}),this._emit("timeline:record",{site:this.site}),t.wuInfo("[WuTimeline] Recording started")),this.status()}stop(){return this._untapStore&&(this._untapStore(),this._untapStore=null),this._untapBus&&(this._untapBus(),this._untapBus=null),this._recording&&(this._recording=!1,this._emit("timeline:stop",{length:this._entries.length}),t.wuInfo(`[WuTimeline] Recording stopped (${this._entries.length} entries)`)),this.status()}clear(){return this._entries=[],this._snapshots=[{at:0,state:ie(this.wu.store.get())||{}}],this._baselineApps=this._captureApps(),this._position=0,this._storeWritesSinceSnap=0,this.status()}_shouldJournal(){return!(this._applying||!this._recording)&&(!(this._position<this._entries.length)||(this._pastWarned||(this._pastWarned=!0,t.wuWarn("[WuTimeline] Writes while positioned in the past are not journaled — they will be discarded when you return to live().")),!1))}_push(e){this._lamport+=1,this._entries.push({l:this._lamport,site:this.site,t:Date.now(),...e}),"store"===e.kind&&(this._storeWritesSinceSnap+=1,this._storeWritesSinceSnap>=this._opts.snapshotEvery&&(this._storeWritesSinceSnap=0,this._snapshots.push({at:this._entries.length,state:ie(this.wu.store.get())||{}}))),this._entries.length>this._opts.maxEntries&&this._trim(),this._position=this._entries.length}_trim(){const e=this._entries.length-this._opts.maxEntries;if(e<=0)return;const t=this._stateAt(e),s=this._appsAt(e);this._entries.splice(0,e),this._baselineApps=[...s].map(([e,t])=>({name:e,container:t.container,props:t.props})),this._snapshots=this._snapshots.map(t=>({at:t.at-e,state:t.state})).filter(e=>e.at>0),this._snapshots.unshift({at:0,state:t}),this._position>0&&(this._position=Math.max(0,this._position-e))}seek(e,s={}){return this._seekChain=this._seekChain.then(()=>this._doSeek("function"==typeof e?e():e,s)).catch(e=>(t.wuError("[WuTimeline] seek failed:",e),this.status())),this._seekChain}live(){return this.seek(()=>this._entries.length)}stepBack(){return this.seek(()=>this._position-1)}stepForward(){return this.seek(()=>this._position+1)}async _doSeek(e,{store:s=!0,apps:r=!0,props:n=!0}={}){const i=this._entries.length;e=Math.max(0,Math.min(i,Math.floor(Number(e)||0))),this._applying=!0;try{if(s){const t=this._stateAt(e);this.wu.store.hydrate(t,{notifyPaths:this._touchedPaths(t)})}if(r||n){const s=this._appsAt(e);if(r){for(const e of[...this.wu.mounted.keys()])if(!s.has(e))try{await this.wu.unmount(e,{force:!0})}catch(s){t.wuWarn(`[WuTimeline] seek unmount('${e}') failed:`,s)}for(const[e,r]of s)if(!this.wu.mounted.has(e)&&r.container)try{await this.wu.mount(e,r.container)}catch(s){t.wuWarn(`[WuTimeline] seek mount('${e}') failed:`,s)}}if(n)for(const[e,r]of s){if(!this.wu.mounted.has(e))continue;const s=r.props||{},n=this.wu.mounted.get(e).props||{},i={...s};for(const e of Object.keys(n))e in s||(i[e]=void 0);if(Object.keys(i).length)try{await this.wu.update(e,i)}catch(s){t.wuWarn(`[WuTimeline] seek update('${e}') failed:`,s)}}}this._position=e,this._emit("timeline:seek",{position:e,length:i,live:e===i})}finally{this._applying=!1}return this.status()}_stateAt(e){let t=this._snapshots[0]||{at:0,state:{}};for(const s of this._snapshots)s.at<=e&&s.at>=t.at&&(t=s);let s=ie(t.state);null!==s&&"object"==typeof s||(s={});for(let r=t.at;r<e;r++){const e=this._entries[r];"store"===e.kind&&(s=oe(s,e.path,ie(e.value)))}return s}_appsAt(e){const t=new Map;for(const e of this._baselineApps)t.set(e.name,{container:e.container,props:e.props??null});for(let s=0;s<e;s++){const e=this._entries[s];"event"===e.kind&&e.appName&&("app:mounted"===e.name?t.set(e.appName,{container:e.container||t.get(e.appName)?.container||null,props:t.get(e.appName)?.props??null}):"app:unmounted"===e.name?t.delete(e.appName):"app:updated"===e.name&&t.has(e.appName)&&(t.get(e.appName).props=e.props??null))}return t}_touchedPaths(e){const t=new Set;let s=!1;for(const e of this._entries)if("store"===e.kind)if(e.path)t.add(e.path);else if(s=!0,e.value&&"object"==typeof e.value)for(const s of Object.keys(e.value))t.add(s);if(s){const s=this._snapshots[0]?.state;if(s&&"object"==typeof s)for(const e of Object.keys(s))t.add(e);if(e&&"object"==typeof e)for(const s of Object.keys(e))t.add(s)}return[...t]}export(){return{format:re,wu:this.wu.version||null,site:this.site,exportedAt:Date.now(),baselineApps:ie(this._baselineApps),entries:ie(this._entries),snapshots:ie(this._snapshots)}}import(e){if(!e||e.format!==re)throw new Error(`[WuTimeline] Unsupported journal format: ${e?.format??typeof e}`);this.stop(),this._entries=Array.isArray(e.entries)?e.entries.filter(Boolean):[],this._baselineApps=Array.isArray(e.baselineApps)?e.baselineApps:[];const t=(Array.isArray(e.snapshots)?e.snapshots:[]).filter(e=>e&&"number"==typeof e.at&&e.at>=0&&e.at<=this._entries.length).sort((e,t)=>e.at-t.at);return t.length&&0===t[0].at||t.unshift({at:0,state:{}}),this._snapshots=t,this._lamport=this._entries.reduce((e,t)=>Math.max(e,t.l||0),this._lamport),this._position=this._entries.length,this._storeWritesSinceSnap=0,this._emit("timeline:import",{length:this._entries.length,site:e.site}),this.status()}ingest(e=[]){return this._entries=ae(this._entries,e),this._lamport=this._entries.reduce((e,t)=>Math.max(e,t.l||0),this._lamport),this._snapshots=[{at:0,state:{}}],this._position=this._entries.length,this._storeWritesSinceSnap=0,this._entries.length>this._opts.maxEntries&&this._trim(),this.status()}entries(){return this._entries.slice()}status(){return{loaded:!0,recording:this._recording,live:this._position===this._entries.length,position:this._position,length:this._entries.length,site:this.site,lamport:this._lamport,snapshots:this._snapshots.length}}_captureApps(){const e=[];for(const[t,s]of this.wu.mounted)e.push({name:t,container:s.containerSelector||null,props:ie(s.props??null)});return e}_emit(e,t){try{this.wu.eventBus.emit(e,t,{appName:"wu-core",token:this.wu.eventBus.getInternalToken?.("wu-core")||void 0,history:!1})}catch{}}},mergeJournals:ae,safeClone:ie,setPath:oe});class le{constructor(e={}){this.model=e.model||""}formatRequest(){throw new Error("Adapter must implement formatRequest()")}parseResponse(){throw new Error("Adapter must implement parseResponse()")}parseStreamChunk(){throw new Error("Adapter must implement parseStreamChunk()")}getHeaders(){return{"Content-Type":"application/json"}}}class ue extends le{constructor(e){super(e),this.model=e.model||"claude-sonnet-4-5-20250929"}getHeaders(e){const t={"Content-Type":"application/json"};return e.apiKey&&(t["x-api-key"]=e.apiKey,t["anthropic-version"]="2023-06-01"),t}formatRequest(e,t={}){const s=e.filter(e=>"system"===e.role),r=e.filter(e=>"system"!==e.role),n={model:t.model||this.model,max_tokens:t.maxTokens||4096,messages:r.map(e=>"tool"===e.role?{role:"user",content:[{type:"tool_result",tool_use_id:e.tool_call_id,content:e.content}]}:e.tool_calls?{role:"assistant",content:e.tool_calls.map(e=>({type:"tool_use",id:e.id,name:e.name,input:e.arguments}))}:{role:e.role,content:e.content})};if(s.length&&(n.system=s.map(e=>e.content).join("\n\n")),t.responseFormat){const e=t.responseFormat,s="\n\nYou MUST respond with valid JSON only. No markdown, no explanation.";if("json"===e||"json_object"===e?.type)n.system=(n.system||"")+s;else if("json_schema"===e?.type){const t=JSON.stringify(e.schema,null,2);n.system=(n.system||"")+s+`\n\nYour response MUST conform to this JSON schema:\n${t}`}n.messages.push({role:"assistant",content:"{"})}return t.tools?.length&&(n.tools=t.tools.map(e=>({name:e.name,description:e.description,input_schema:e.parameters}))),void 0!==t.temperature&&(n.temperature=t.temperature),t.stream&&(n.stream=!0),n}parseResponse(e){const t=(e.content||[]).filter(e=>"text"===e.type),s=(e.content||[]).filter(e=>"tool_use"===e.type),r=t.map(e=>e.text).join(""),n=s.map(e=>({id:e.id,name:e.name,arguments:e.input||{}}));return{content:r,tool_calls:n.length>0?n:void 0,usage:e.usage?{prompt_tokens:e.usage.input_tokens,completion_tokens:e.usage.output_tokens}:void 0}}parseStreamChunk(e){if(!e.startsWith("data: "))return null;const t=e.slice(6).trim();try{const e=JSON.parse(t);if("content_block_delta"===e.type){if("text_delta"===e.delta?.type)return{type:"text",content:e.delta.text};if("input_json_delta"===e.delta?.type)return{type:"tool_call_delta",argumentsDelta:e.delta.partial_json||""}}return"content_block_start"===e.type&&"tool_use"===e.content_block?.type?{type:"tool_call_start",id:e.content_block.id,name:e.content_block.name}:"message_delta"===e.type&&e.usage?{type:"usage",usage:{prompt_tokens:e.usage.input_tokens,completion_tokens:e.usage.output_tokens}}:"message_stop"===e.type?{type:"done"}:null}catch{return null}}}class de extends le{constructor(e){super(e),this._sendFn=e.send||null,this._streamFn=e.stream||null}get isCustom(){return!0}}const he={openai:class extends le{constructor(e){super(e),this.model=e.model||"gpt-4o"}getHeaders(e){const t={"Content-Type":"application/json"};return e.apiKey&&(t.Authorization=`Bearer ${e.apiKey}`),t}formatRequest(e,t={}){const s={model:t.model||this.model,messages:e.map(e=>{const t={role:e.role,content:e.content};return e.tool_call_id&&(t.tool_call_id=e.tool_call_id),e.tool_calls&&(t.tool_calls=e.tool_calls.map(e=>({id:e.id,type:"function",function:{name:e.name,arguments:JSON.stringify(e.arguments)}}))),t})};if(t.tools?.length&&(s.tools=t.tools.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}}))),void 0!==t.temperature&&(s.temperature=t.temperature),t.maxTokens&&(s.max_tokens=t.maxTokens),t.stream&&(s.stream=!0),t.responseFormat){const e=t.responseFormat;"json"===e||"json_object"===e?.type?s.response_format={type:"json_object"}:"json_schema"===e?.type&&(s.response_format={type:"json_schema",json_schema:{name:e.name||"response",schema:e.schema,strict:!1!==e.strict}})}return s}parseResponse(e){const t=e.choices?.[0];if(!t)return{content:"",tool_calls:[],usage:e.usage};const s=t.message||{},r=(s.tool_calls||[]).map(e=>({id:e.id,name:e.function?.name,arguments:this._safeParseArgs(e.function?.arguments)}));return{content:s.content||"",tool_calls:r.length>0?r:void 0,usage:e.usage?{prompt_tokens:e.usage.prompt_tokens,completion_tokens:e.usage.completion_tokens}:void 0}}parseStreamChunk(e){if(!e.startsWith("data: "))return null;const t=e.slice(6).trim();if("[DONE]"===t)return{type:"done"};try{const e=JSON.parse(t),s=e.choices?.[0]?.delta;if(!s)return null;if(s.tool_calls?.length){const e=s.tool_calls[0];return{type:"tool_call_delta",index:e.index,id:e.id,name:e.function?.name,argumentsDelta:e.function?.arguments||""}}return s.content?{type:"text",content:s.content}:e.usage?{type:"usage",usage:e.usage}:null}catch{return null}}_safeParseArgs(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}},anthropic:ue,ollama:class extends le{constructor(e){super(e),this.model=e.model||"llama3"}getHeaders(){return{"Content-Type":"application/json"}}formatRequest(e,t={}){const s={model:t.model||this.model,messages:e.map(e=>({role:e.role,content:e.content}))};if(t.tools?.length&&(s.tools=t.tools.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters}}))),void 0!==t.temperature&&(s.options={temperature:t.temperature}),void 0!==t.stream&&(s.stream=t.stream),t.responseFormat){const e=t.responseFormat;"json"===e||"json_object"===e?.type?s.format="json":"json_schema"===e?.type&&(s.format=e.schema)}return s}parseResponse(e){const t=e.message||{},s=(t.tool_calls||[]).map((e,t)=>({id:`ollama_${t}_${Date.now()}`,name:e.function?.name,arguments:e.function?.arguments||{}}));return{content:t.content||"",tool_calls:s.length>0?s:void 0,usage:e.eval_count?{prompt_tokens:e.prompt_eval_count||0,completion_tokens:e.eval_count||0}:void 0}}parseStreamChunk(e){try{const t=JSON.parse(e);return t.done?{type:"done"}:t.message?.content?{type:"text",content:t.message.content}:null}catch{return null}}}};class pe{constructor(){this._providers=new Map,this._active=null,this._activeName=null,this._activeConfig={},this._retryConfig={maxRetries:3,baseDelayMs:1e3}}register(e,s={}){s.apiKey&&!0!==s.unsafeAllowDirectKey&&this._isProduction()&&(t.wuWarn(`[wu-ai] Direct API key for provider '${e}' BLOCKED in production. Use a server-side proxy endpoint instead.`),s={...s,apiKey:void 0});const r=s.adapter||e,n=he[r];let i;if(s.send||s.stream)i=new de(s);else{if(!n)throw new Error(`[wu-ai] Unknown adapter '${r}'. Available: ${Object.keys(he).join(", ")}, or provide custom send/stream.`);i=new n(s)}this._providers.set(e,{adapter:i,config:s}),this._active&&!1===s.active||(this._active=i,this._activeName=e,this._activeConfig=s),t.wuInfo(`[wu-ai] Provider registered: '${e}' (adapter: ${r})`)}use(e){const t=this._providers.get(e);if(!t)throw new Error(`[wu-ai] Provider '${e}' not registered`);this._active=t.adapter,this._activeName=e,this._activeConfig=t.config}async send(e,s={}){const{adapter:r,config:n}=this._resolveProvider(s.provider);if(r.isCustom&&r._sendFn)return r._sendFn(e,s);const i=n.endpoint||n.baseUrl;if(!i)throw new Error("[wu-ai] No endpoint configured. Set config.endpoint or config.baseUrl.");const o=this._resolveUrl(i),a=r.formatRequest(e,{...s,stream:!1}),c=r.getHeaders(n),l=await this._fetchWithRetry(o,{method:"POST",headers:c,body:JSON.stringify(a),signal:s.signal}),u=await l.json(),d=r.parseResponse(u);if(r instanceof ue&&s.responseFormat&&d.content&&(d.content="{"+d.content),s.responseFormat&&d.content)try{d.parsed=JSON.parse(d.content)}catch{d.parseError="Response is not valid JSON",t.wuDebug("[wu-ai] responseFormat requested but LLM returned invalid JSON")}return d}async*stream(e,t={}){const{adapter:s,config:r}=this._resolveProvider(t.provider);if(s.isCustom&&s._streamFn)return void(yield*s._streamFn(e,t));const n=r.endpoint||r.baseUrl;if(!n)throw new Error("[wu-ai] No endpoint configured. Set config.endpoint or config.baseUrl.");const i=this._resolveUrl(n),o=s.formatRequest(e,{...t,stream:!0}),a=s.getHeaders(r),c=await fetch(i,{method:"POST",headers:a,body:JSON.stringify(o),signal:t.signal});if(!c.ok)throw new Error(`[wu-ai] Stream request failed: ${c.status} ${c.statusText}`);const l=c.body.getReader(),u=new TextDecoder;let d="",h=s instanceof ue&&!!t.responseFormat;try{for(;;){const{done:e,value:t}=await l.read();if(e)break;d+=u.decode(t,{stream:!0});const r=d.split("\n");d=r.pop()||"";for(const e of r){const t=e.trim();if(!t)continue;const r=s.parseStreamChunk(t);if(r&&(h&&"text"===r.type&&(r.content="{"+r.content,h=!1),yield r),"done"===r?.type)return}}if(d.trim()){const e=s.parseStreamChunk(d.trim());e&&(yield e)}}finally{l.releaseLock()}}async _fetchWithRetry(e,s){let r;for(let n=0;n<=this._retryConfig.maxRetries;n++)try{const i=await fetch(e,s);if(i.ok)return i;if((429===i.status||i.status>=500)&&(r=new Error(`HTTP ${i.status}: ${i.statusText}`),n<this._retryConfig.maxRetries)){const e=this._retryConfig.baseDelayMs*Math.pow(2,n);t.wuDebug(`[wu-ai] Retry ${n+1}/${this._retryConfig.maxRetries} in ${e}ms (${i.status})`),await new Promise(t=>setTimeout(t,e));continue}const o=new Error(`[wu-ai] Request failed: ${i.status} ${i.statusText}`);throw o._noRetry=!0,o}catch(e){if("AbortError"===e.name)throw e;if(e._noRetry)throw e;if(r=e,n<this._retryConfig.maxRetries){const e=this._retryConfig.baseDelayMs*Math.pow(2,n);await new Promise(t=>setTimeout(t,e));continue}}throw r}_isProduction(){if("undefined"!=typeof process&&process.env?.NODE_ENV)return!0;if("undefined"!=typeof window){const e=window.location?.hostname||"";return"localhost"!==e&&"127.0.0.1"!==e&&"0.0.0.0"!==e&&"[::1]"!==e&&"::1"!==e&&"host.docker.internal"!==e&&(!(e.endsWith(".local")||e.endsWith(".localhost")||e.endsWith(".test"))&&!/^10\.|^192\.168\.|^172\.(1[6-9]|2\d|3[01])\./.test(e))}return!1}_resolveUrl(e){return e.startsWith("/")&&"undefined"!=typeof window?`${window.location.origin}${e}`:e}_resolveProvider(e){if(e){const t=this._providers.get(e);if(!t)throw new Error(`[wu-ai] Provider '${e}' not registered. Available: ${[...this._providers.keys()].join(", ")}`);return{adapter:t.adapter,config:t.config}}return this._ensureActive(),{adapter:this._active,config:this._activeConfig}}_ensureActive(){if(!this._active)throw new Error('[wu-ai] No provider configured. Call wu.ai.provider("name", { endpoint, adapter }) first.')}configureRetry(e){void 0!==e.maxRetries&&(this._retryConfig.maxRetries=e.maxRetries),void 0!==e.baseDelayMs&&(this._retryConfig.baseDelayMs=e.baseDelayMs)}getActiveProvider(){return this._activeName}getStats(){return{activeProvider:this._activeName,registeredProviders:[...this._providers.keys()]}}}const me={readStore:!0,writeStore:!1,emitEvents:!0,readDOM:!1,modifyDOM:!1,executeActions:!0,allowDirectKey:!1},fe="closed",ge="open",we="half-open";class ye{constructor(e={}){this._maxPerMinute=e.requestsPerMinute??20,this._maxPerMinutePerNs=e.requestsPerMinutePerNs??10,this._maxConcurrent=e.maxConcurrent??3,this._globalTimestamps=[],this._nsTimestamps=new Map,this._concurrent=0}configure(e){void 0!==e.requestsPerMinute&&(this._maxPerMinute=e.requestsPerMinute),void 0!==e.requestsPerMinutePerNs&&(this._maxPerMinutePerNs=e.requestsPerMinutePerNs),void 0!==e.maxConcurrent&&(this._maxConcurrent=e.maxConcurrent)}canSend(e="default"){if(this._pruneOld(),this._concurrent>=this._maxConcurrent)return{allowed:!1,reason:`Max concurrent (${this._maxConcurrent}) reached`};if(this._globalTimestamps.length>=this._maxPerMinute)return{allowed:!1,reason:`Global rate limit (${this._maxPerMinute}/min) exceeded`};return(this._nsTimestamps.get(e)||[]).length>=this._maxPerMinutePerNs?{allowed:!1,reason:`Namespace '${e}' rate limit (${this._maxPerMinutePerNs}/min) exceeded`}:{allowed:!0}}recordStart(e="default"){const t=Date.now();this._globalTimestamps.push(t),this._nsTimestamps.has(e)||this._nsTimestamps.set(e,[]),this._nsTimestamps.get(e).push(t),this._concurrent++}recordEnd(){this._concurrent=Math.max(0,this._concurrent-1)}_pruneOld(){const e=Date.now()-6e4;this._globalTimestamps=this._globalTimestamps.filter(t=>t>e);for(const[t,s]of this._nsTimestamps){const r=s.filter(t=>t>e);0===r.length?this._nsTimestamps.delete(t):this._nsTimestamps.set(t,r)}}getStats(){return this._pruneOld(),{globalRequestsLastMinute:this._globalTimestamps.length,concurrent:this._concurrent,maxPerMinute:this._maxPerMinute,maxConcurrent:this._maxConcurrent}}}class _e{constructor(e={}){this._state=fe,this._failureCount=0,this._maxFailures=e.maxFailures??3,this._cooldownMs=e.cooldownMs??3e4,this._openedAt=0,this._rapidFireThreshold=e.rapidFireThreshold??5,this._rapidFireWindowMs=e.rapidFireWindowMs??2e3,this._recentRequests=[]}configure(e){void 0!==e.maxFailures&&(this._maxFailures=e.maxFailures),void 0!==e.cooldownMs&&(this._cooldownMs=e.cooldownMs)}canPass(){if(this._state===fe)return{allowed:!0};if(this._state===ge){if(Date.now()-this._openedAt>=this._cooldownMs)return this._state=we,t.wuDebug("[wu-ai] Circuit breaker → HALF-OPEN (testing)"),{allowed:!0};const e=this._cooldownMs-(Date.now()-this._openedAt);return{allowed:!1,reason:`Circuit breaker OPEN (${Math.ceil(e/1e3)}s remaining)`}}return{allowed:!0}}recordSuccess(){this._state===we?(this._state=fe,this._failureCount=0,t.wuInfo("[wu-ai] Circuit breaker → CLOSED (recovered)")):this._failureCount=0}recordFailure(){this._failureCount++,this._recordRequest(),this._state!==we?this._failureCount>=this._maxFailures&&this._tripOpen(`${this._failureCount} consecutive failures`):this._tripOpen("Failed during half-open test")}_recordRequest(){const e=Date.now();this._recentRequests.push(e),this._recentRequests=this._recentRequests.filter(t=>e-t<this._rapidFireWindowMs),this._state===fe&&this._recentRequests.length>=this._rapidFireThreshold&&this._tripOpen(`${this._recentRequests.length} requests in ${this._rapidFireWindowMs}ms (rapid fire)`)}_tripOpen(e){this._state=ge,this._openedAt=Date.now(),t.wuWarn(`[wu-ai] Circuit breaker → OPEN: ${e}. Cooldown: ${this._cooldownMs/1e3}s`)}getState(){return this._state}getStats(){return{state:this._state,failureCount:this._failureCount,maxFailures:this._maxFailures,cooldownMs:this._cooldownMs,openedAt:this._openedAt}}reset(){this._state=fe,this._failureCount=0,this._openedAt=0,this._recentRequests=[]}}class be{constructor(e={}){this._maxDepth=e.maxDepth??3,this._activeTraces=new Map,this._traceLog=[],this._maxTraceLog=50}configure(e){void 0!==e.maxDepth&&(this._maxDepth=e.maxDepth)}canProceed(e,t){if(e>this._maxDepth)return{allowed:!1,reason:`Max AI depth (${this._maxDepth}) exceeded at depth ${e}`};if(t){const e=(this._activeTraces.get(t)||0)+1;if(e>this._maxDepth)return{allowed:!1,reason:`Causal chain '${t}' looped ${e} times (max ${this._maxDepth})`}}return{allowed:!0}}enter(e){if(!e)return;const t=(this._activeTraces.get(e)||0)+1;this._activeTraces.set(e,t),this._traceLog.push({traceId:e,count:t,timestamp:Date.now()}),this._traceLog.length>this._maxTraceLog&&this._traceLog.shift()}exit(e){if(!e)return;const t=(this._activeTraces.get(e)||0)-1;t<=0?this._activeTraces.delete(e):this._activeTraces.set(e,t)}createTraceId(){return`t_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}getTraces(){return[...this._traceLog]}getStats(){return{maxDepth:this._maxDepth,activeTraces:this._activeTraces.size,traceLogSize:this._traceLog.length}}}class ve{constructor(e={}){this._permissions={...me},this.rateLimiter=new ye(e.rateLimit),this.circuitBreaker=new _e(e.circuitBreaker),this.loopProtection=new be(e.loopProtection),this._allowedDomains=e.allowedDomains||[],e.permissions&&this.configure(e.permissions)}configure(e){Object.assign(this._permissions,e),this._isProduction()&&this._permissions.allowDirectKey&&(t.wuWarn("[wu-ai] allowDirectKey FORCED to false in production"),this._permissions.allowDirectKey=!1)}check(e){return!0===this._permissions[e]}getPermissions(){return{...this._permissions}}setAllowedDomains(e){this._allowedDomains=e}isDomainAllowed(e){if(0===this._allowedDomains.length)return!0;try{const t=new URL(e).hostname;return this._allowedDomains.some(e=>{if(e.startsWith("*.")){const s=e.slice(2);return t===s||t.endsWith("."+s)}return t===e})}catch{return!1}}preflight(e={}){const t=this.circuitBreaker.canPass();if(!t.allowed)return t;const s=this.rateLimiter.canSend(e.namespace);if(!s.allowed)return s;const r=this.loopProtection.canProceed(e.depth||0,e.traceId);return r.allowed?{allowed:!0}:r}getStats(){return{permissions:{...this._permissions},rateLimiter:this.rateLimiter.getStats(),circuitBreaker:this.circuitBreaker.getStats(),loopProtection:this.loopProtection.getStats(),allowedDomains:[...this._allowedDomains]}}_isProduction(){if("undefined"!=typeof process&&"production"===process.env?.NODE_ENV)return!0;if("undefined"!=typeof window){const e=window.location?.hostname||"";return"localhost"!==e&&"127.0.0.1"!==e&&"0.0.0.0"!==e&&!e.endsWith(".local")}return!1}}const xe=["password","token","apiKey","secret","credential","authorization","cookie","session"];function Se(e,t=0){if(t>10)return"[MAX_DEPTH]";if(null==e)return e;if("object"!=typeof e)return e;if(Array.isArray(e))return e.map(e=>Se(e,t+1));const s={};for(const[r,n]of Object.entries(e)){const e=r.toLowerCase();xe.some(t=>e.includes(t.toLowerCase()))?s[r]="[REDACTED]":s[r]=Se(n,t+1)}return s}function $e(e,t){return e.replace(/\{\{(\w+(?:\.\w+)*)\}\}/g,(e,s)=>{const r=s.split(".").reduce((e,t)=>e?.[t],t);return null==r?"":"object"==typeof r?function(e,t=2e3){if(null==e)return"null";if("function"==typeof e)return"[Function]";if("symbol"==typeof e)return"[Symbol]";if("string"==typeof e)return`<user_data>${e.length>t?e.slice(0,t)+"...[truncated]":e}</user_data>`;if("number"==typeof e||"boolean"==typeof e)return String(e);if("object"==typeof e){const s=Se(e),r=JSON.stringify(s);return r.length>t?`<user_data>${r.slice(0,t)}...[truncated]</user_data>`:`<user_data>${r}</user_data>`}return String(e).slice(0,t)}(r):String(r)})}function ke(e){if(!e||"object"!=typeof e)return{type:"object",properties:{},required:[]};if("object"===e.type&&e.properties)return e;const t={},s=[];for(const[r,n]of Object.entries(e))if("string"==typeof n)t[r]={type:n};else if("object"==typeof n){const{required:e,...i}=n;t[r]=i.type?i:{type:"string",...i},e&&s.push(r)}return{type:"object",properties:t,required:s}}class Ee{constructor({store:e,eventBus:t,core:s}){this._store=e,this._eventBus=t,this._core=s,this._config={budget:4e3,charRatio:4,sources:{store:{include:[],priority:"high"},events:{include:[],lastN:10,priority:"medium"},custom:[]}},this._collectors=new Map,this._lastSnapshot=null}configure(e){void 0!==e.budget&&(this._config.budget=e.budget),void 0!==e.charRatio&&(this._config.charRatio=e.charRatio),e.sources&&(e.sources.store&&Object.assign(this._config.sources.store,e.sources.store),e.sources.events&&Object.assign(this._config.sources.events,e.sources.events),e.sources.custom&&(this._config.sources.custom=e.sources.custom))}register(e,s){this._collectors.set(e,{collector:s.collector,priority:s.priority||"medium"}),t.wuDebug(`[wu-ai] Context collector registered: '${e}' (${s.priority||"medium"})`)}async collect(){const e={_timestamp:Date.now(),_mountedApps:this._getMountedApps()},s=this._collectStore();s&&Object.keys(s).length>0&&(e._store=s);const r=this._collectEvents();r.length>0&&(e._events=r);for(const s of this._config.sources.custom)try{const t="function"==typeof s.value?await s.value():s.value;e[s.key]=t}catch(e){t.wuDebug(`[wu-ai] Custom collector '${s.key}' failed: ${e.message}`)}for(const[s,r]of this._collectors)try{const t=await r.collector();e[s]=t}catch(e){t.wuDebug(`[wu-ai] Collector '${s}' failed: ${e.message}`)}return this._lastSnapshot=e,e}toSystemPrompt(e={}){const t=this._lastSnapshot;if(!t)return this._baseSystemPrompt(e);const s=[];s.push("You are an AI assistant connected to a live web application via Wu Framework.","You can observe application state and execute actions when appropriate.",""),t._mountedApps?.length&&s.push(`MOUNTED APPS: ${t._mountedApps.join(", ")}`,"");const r=this._config.budget*this._config.charRatio;let n=s.join("\n").length;const i=this._prioritizeSections(t);for(const e of i){const t=e.text;if(n+t.length>r){if("high"===e.priority){const e=r-n;e>100&&(s.push(t.slice(0,e)+"\n...[truncated]"),n+=e)}}else s.push(t),n+=t.length}if(e.tools?.length){s.push("","AVAILABLE TOOLS:");for(const t of e.tools)s.push(`- ${t.name}: ${t.description}`)}return s.join("\n")}getSnapshot(){return this._lastSnapshot}getInterpolationContext(){if(!this._lastSnapshot)return{};const{_timestamp:e,_mountedApps:t,_store:s,_events:r,...n}=this._lastSnapshot;return{apps:t,store:s,events:r,...n}}_collectStore(){if(!this._store)return{};const{include:e}=this._config.sources.store;if(!e||0===e.length)return{};const t={};for(const s of e)try{const e=this._store.get(s);void 0!==e&&(t[s]=Se(e))}catch{}return t}_collectEvents(){if(!this._eventBus)return[];const{include:e,lastN:t}=this._config.sources.events;if(!e||0===e.length)return[];return(this._eventBus.history||[]).filter(t=>e.some(e=>this._matchPattern(t.name||t.event,e))).slice(-(t||10)).map(e=>({event:e.name||e.event,data:Se(e.data),timestamp:e.timestamp}))}_getMountedApps(){if(!this._core)return[];try{if(this._core.mounted instanceof Map)return[...this._core.mounted.keys()];const e=this._core.getStats?.();return e?.apps||e?.mounted||[]}catch{return[]}}_prioritizeSections(e){const t=[],s=this._config.sources.store.priority||"high",r=this._config.sources.events.priority||"medium";if(e._store&&Object.keys(e._store).length>0&&t.push({priority:s,text:`APPLICATION STATE:\n${JSON.stringify(e._store,null,2)}`}),e._events?.length){const s=e._events.map(e=>` [${e.event}] ${JSON.stringify(e.data)}`).join("\n");t.push({priority:r,text:`RECENT EVENTS:\n${s}`})}for(const[s,r]of this._collectors)void 0!==e[s]&&t.push({priority:r.priority,text:`${s.toUpperCase()}:\n${JSON.stringify(e[s],null,2)}`});for(const s of this._config.sources.custom)void 0!==e[s.key]&&t.push({priority:s.priority||"low",text:`${s.key}: ${JSON.stringify(e[s.key])}`});const n={high:0,medium:1,low:2};return t.sort((e,t)=>(n[e.priority]??1)-(n[t.priority]??1)),t}_baseSystemPrompt(e={}){let t="You are an AI assistant connected to a web application via Wu Framework.";return e.tools?.length&&(t+="\n\nAVAILABLE TOOLS:\n"+e.tools.map(e=>`- ${e.name}: ${e.description}`).join("\n")),t}_matchPattern(e,t){if(!e||!t)return!1;if("*"===t)return!0;if(!t.includes("*"))return e===t;return new RegExp("^"+t.replace(/\*/g,"[^:]*")+"$").test(e)}getStats(){return{budget:this._config.budget,collectors:[...this._collectors.keys()],storePaths:this._config.sources.store.include,eventPatterns:this._config.sources.events.include,lastCollected:this._lastSnapshot?._timestamp||null}}}class Ae{constructor({eventBus:e,store:t,permissions:s}){this._eventBus=e,this._store=t,this._permissions=s,this._actions=new Map,this._executionLog=[],this._maxLogSize=100,this._pendingConfirms=new Map}register(e,s){if(!s.handler||"function"!=typeof s.handler)throw new Error(`[wu-ai] Action '${e}' must have a handler function`);this._actions.set(e,{description:s.description||`Execute: ${e}`,parameters:ke(s.parameters),handler:s.handler,confirm:s.confirm||!1,permissions:s.permissions||[],dangerous:s.dangerous||!1}),t.wuDebug(`[wu-ai] Action registered: '${e}'${s.dangerous?" [DANGEROUS]":""}`)}unregister(e){this._actions.delete(e)}async execute(e,s,r={}){const n=this._actions.get(e);if(!n)return{success:!1,reason:`Action '${e}' not registered`};for(const t of n.permissions)if(!this._permissions.check(t))return this._emitDenied(e,s,`Missing permission: ${t}`),{success:!1,reason:`Permission denied: ${t}`};const i=function(e,t){const s=[];if(!t||!t.properties)return{valid:!0,errors:s};for(const r of t.required||[])void 0!==e[r]&&null!==e[r]||s.push(`'${r}' is required`);for(const[r,n]of Object.entries(t.properties)){const t=e[r];if(null!=t){if(n.type&&"any"!==n.type){const e=Array.isArray(t)?"array":typeof t;"integer"===n.type?"number"==typeof t&&Number.isInteger(t)||s.push(`'${r}' must be integer, got ${e}`):n.type!==e&&s.push(`'${r}' must be ${n.type}, got ${e}`)}n.enum&&!n.enum.includes(t)&&s.push(`'${r}' must be one of [${n.enum.join(", ")}], got '${t}'`)}}return{valid:0===s.length,errors:s}}(s||{},n.parameters);if(!i.valid)return{success:!1,reason:`Invalid params: ${i.errors.join(", ")}`};if(n.confirm){if(!await this._requestConfirmation(e,s,r.callId))return{success:!1,reason:"User denied action"}}try{n.dangerous&&t.wuWarn(`[wu-ai] Executing DANGEROUS action: '${e}' with params: ${JSON.stringify(s)}`);const i=this._createSandboxedApi(n.permissions),o=await n.handler(s,i);return this._log(e,s,o,r),this._eventBus.emit("ai:action:executed",{action:e,params:s,result:o,traceId:r.traceId},{appName:"wu-ai"}),{success:!0,result:o}}catch(t){return this._eventBus.emit("ai:action:error",{action:e,params:s,error:t.message,traceId:r.traceId},{appName:"wu-ai"}),{success:!1,reason:t.message}}}getToolSchemas(){return function(e){const t=[];for(const[s,r]of e)t.push({name:s,description:r.description||`Execute action: ${s}`,parameters:ke(r.parameters)});return t}(this._actions)}has(e){return this._actions.has(e)}getNames(){return[...this._actions.keys()]}getLog(){return[...this._executionLog]}confirmTool(e){const t=this._pendingConfirms.get(e);t&&(clearTimeout(t.timeout),this._pendingConfirms.delete(e),t.resolve(!0))}rejectTool(e){const t=this._pendingConfirms.get(e);t&&(clearTimeout(t.timeout),this._pendingConfirms.delete(e),t.resolve(!1))}_createSandboxedApi(e){const t={},s=new Set(e);return this._permissions.check("readStore")&&(t.getState=e=>this._store.get(e)),this._permissions.check("writeStore")&&s.has("writeStore")&&(t.setState=(e,t)=>this._store.set(e,t)),this._permissions.check("emitEvents")&&(t.emit=(e,t)=>this._eventBus.emit(e,t,{appName:"wu-ai"})),t}_requestConfirmation(e,s,r){const n=r||`confirm_${Date.now()}_${Math.random().toString(36).slice(2,6)}`;return new Promise(r=>{const i=setTimeout(()=>{this._pendingConfirms.delete(n),r(!1),t.wuDebug(`[wu-ai] Confirmation timeout for action '${e}'`)},3e4);this._pendingConfirms.set(n,{resolve:r,timeout:i}),this._eventBus.emit("ai:tool:confirm",{callId:n,action:e,params:s,message:`AI wants to execute: ${e}`},{appName:"wu-ai"})})}_log(e,t,s,r){this._executionLog.push({action:e,params:t,result:"object"==typeof s?{...s}:s,timestamp:Date.now(),traceId:r.traceId}),this._executionLog.length>this._maxLogSize&&this._executionLog.shift()}_emitDenied(e,s,r){this._eventBus.emit("ai:action:denied",{action:e,params:s,reason:r},{appName:"wu-ai"}),t.wuWarn(`[wu-ai] Action denied: '${e}' — ${r}`)}getStats(){return{registeredActions:[...this._actions.keys()],executionLogSize:this._executionLog.length,pendingConfirmations:this._pendingConfirms.size}}}const We={maxHistoryMessages:50,maxToolRounds:5,defaultNamespace:"default",systemPrompt:null,temperature:void 0,maxTokens:void 0,namespaceTTL:18e5,gcInterval:3e5};class Ce{constructor(e){this.name=e,this.messages=[],this.createdAt=Date.now(),this.lastActivity=Date.now(),this._abortController=null}addMessage(e){this.messages.push({...e,_ts:Date.now()}),this.lastActivity=Date.now()}getMessages(){return this.messages.map(({_ts:e,...t})=>t)}truncate(e){if(this.messages.length<=e)return;const t=this.messages.filter(e=>"system"===e.role),s=this.messages.filter(e=>"system"!==e.role).slice(-e);for(;s.length>0&&"tool"===s[0].role;)s.shift();this.messages=[...t,...s]}clear(){this.messages=[],this.lastActivity=Date.now()}abort(){this._abortController&&(this._abortController.abort(),this._abortController=null)}createAbortController(){return this.abort(),this._abortController=new AbortController,this._abortController}}class De{constructor({provider:e,actions:t,context:s,permissions:r,eventBus:n}){this._provider=e,this._actions=t,this._context=s,this._permissions=r,this._eventBus=n,this._config={...We},this._namespaces=new Map,this._activeRequests=new Map,this._lastGcRun=Date.now()}configure(e){Object.assign(this._config,e)}async send(e,s={}){const r=this._getOrCreateNamespace(s.namespace),n=this._permissions.loopProtection.createTraceId(),i={namespace:r.name,depth:0,traceId:n},o=await this._buildSystemPrompt(s),a=this._permissions.preflight(i);if(!a.allowed)return{content:`[blocked] ${a.reason}`,namespace:r.name};this._permissions.rateLimiter.recordStart(r.name);try{this._setSystemMessage(r,o);const i=this._processMessage(e,s.templateVars);r.addMessage({role:"user",content:i}),r.truncate(this._config.maxHistoryMessages);const a=r.createAbortController(),c=this._mergeSignals(a.signal,s.signal),l=[];let u=0;const d=this._config.maxToolRounds;for(;u<=d;){const e=this._actions.getToolSchemas(),i=await this._provider.send(r.getMessages(),{tools:e.length>0?e:void 0,temperature:s.temperature??this._config.temperature,maxTokens:s.maxTokens??this._config.maxTokens,responseFormat:s.responseFormat,provider:s.provider,signal:c}),o={role:"assistant",content:i.content||""};if(i.tool_calls&&(o.tool_calls=i.tool_calls),r.addMessage(o),!i.tool_calls||0===i.tool_calls.length)return this._permissions.circuitBreaker.recordSuccess(),this._eventBus.emit("ai:response",{namespace:r.name,content:i.content,toolResults:l.length>0?l:void 0,usage:i.usage,traceId:n},{appName:"wu-ai"}),{content:i.content||"",tool_results:l.length>0?l:void 0,usage:i.usage,namespace:r.name};if(u++,u>d){const e=`[wu-ai] Tool call loop limit (${d}) reached in namespace '${r.name}'`;return t.wuWarn(e),r.addMessage({role:"assistant",content:e}),{content:e,tool_results:l,namespace:r.name}}this._permissions.loopProtection.enter(n);for(const e of i.tool_calls){const t=await this._actions.execute(e.name,e.arguments,{traceId:n,depth:u,callId:e.id});l.push({tool:e.name,params:e.arguments,result:t.result,success:t.success}),r.addMessage({role:"tool",content:JSON.stringify(t.success?t.result:{error:t.reason}),tool_call_id:e.id})}this._permissions.loopProtection.exit(n)}return{content:"",tool_results:l,namespace:r.name}}catch(e){if("AbortError"===e.name)return{content:"[aborted]",namespace:r.name};throw this._permissions.circuitBreaker.recordFailure(),this._eventBus.emit("ai:error",{namespace:r.name,error:e.message,traceId:n},{appName:"wu-ai"}),e}finally{this._permissions.rateLimiter.recordEnd(),r._abortController=null}}async*stream(e,s={}){const r=this._getOrCreateNamespace(s.namespace),n=this._permissions.loopProtection.createTraceId(),i={namespace:r.name,depth:0,traceId:n},o=await this._buildSystemPrompt(s),a=this._permissions.preflight(i);if(a.allowed){this._permissions.rateLimiter.recordStart(r.name);try{this._setSystemMessage(r,o);const i=this._processMessage(e,s.templateVars);r.addMessage({role:"user",content:i}),r.truncate(this._config.maxHistoryMessages);const a=r.createAbortController(),c=this._mergeSignals(a.signal,s.signal);let l=0;const u=this._config.maxToolRounds;for(;l<=u;){const e=this._actions.getToolSchemas();let i="";const o=new Map;let a=!1;for await(const t of this._provider.stream(r.getMessages(),{tools:e.length>0?e:void 0,temperature:s.temperature??this._config.temperature,maxTokens:s.maxTokens??this._config.maxTokens,responseFormat:s.responseFormat,provider:s.provider,signal:c}))if("text"===t.type)i+=t.content,yield t;else if("tool_call_start"===t.type)o.set(o.size,{id:t.id,name:t.name,args:""});else if("tool_call_delta"===t.type){const e=t.index??o.size-1,s=o.get(e);s?(t.id&&(s.id=t.id),t.name&&(s.name=t.name),s.args+=t.argumentsDelta||""):o.set(e,{id:t.id||`tc_${e}`,name:t.name||"",args:t.argumentsDelta||""})}else{if("done"===t.type){a=!0;break}("usage"===t.type||"error"===t.type)&&(yield t)}if(0===o.size)return i&&r.addMessage({role:"assistant",content:i}),this._permissions.circuitBreaker.recordSuccess(),void(yield{type:"done"});if(l++,l>u){const e=`[wu-ai] Tool call loop limit (${u}) reached in streaming namespace '${r.name}'`;return t.wuWarn(e),yield{type:"error",error:e},void(yield{type:"done"})}const d=[];for(const[,e]of o){let t={};try{t=JSON.parse(e.args)}catch{}d.push({id:e.id,name:e.name,arguments:t})}r.addMessage({role:"assistant",content:i,tool_calls:d}),this._permissions.loopProtection.enter(n);for(const e of d){const t=await this._actions.execute(e.name,e.arguments,{traceId:n,depth:l,callId:e.id});yield{type:"tool_result",tool:e.name,result:t.success?t.result:{error:t.reason},success:t.success},r.addMessage({role:"tool",content:JSON.stringify(t.success?t.result:{error:t.reason}),tool_call_id:e.id})}this._permissions.loopProtection.exit(n),yield{type:"tool_calls_done",count:d.length}}}catch(e){if("AbortError"===e.name)return void(yield{type:"error",error:"aborted"});this._permissions.circuitBreaker.recordFailure(),yield{type:"error",error:e.message},this._eventBus.emit("ai:error",{namespace:r.name,error:e.message,traceId:n},{appName:"wu-ai"})}finally{this._permissions.rateLimiter.recordEnd(),r._abortController=null}}else yield{type:"error",error:a.reason}}inject(e,t,s={}){this._getOrCreateNamespace(s.namespace).addMessage({role:e,content:t})}getHistory(e){const t=this._namespaces.get(e||this._config.defaultNamespace);return t?t.getMessages():[]}clear(e){const t=this._namespaces.get(e||this._config.defaultNamespace);t&&t.clear()}clearAll(){for(const e of this._namespaces.values())e.clear()}abort(e){const t=this._namespaces.get(e||this._config.defaultNamespace);t&&t.abort()}abortAll(){for(const e of this._namespaces.values())e.abort()}getNamespaces(){return[...this._namespaces.keys()]}deleteNamespace(e){const t=this._namespaces.get(e);t&&(t.abort(),this._namespaces.delete(e))}_getOrCreateNamespace(e){const t=e||this._config.defaultNamespace;this._maybeGcSweep(),this._namespaces.has(t)||this._namespaces.set(t,new Ce(t));const s=this._namespaces.get(t);return s.lastActivity=Date.now(),s}_maybeGcSweep(){const e=this._config.namespaceTTL,s=this._config.gcInterval;if(!e||e<=0)return;const r=Date.now();if(r-this._lastGcRun<s)return;this._lastGcRun=r;const n=r-e,i=[];for(const[e,t]of this._namespaces)e!==this._config.defaultNamespace&&(t._abortController||t.lastActivity<n&&i.push(e));for(const e of i)this._namespaces.delete(e);i.length>0&&t.wuDebug(`[wu-ai] GC sweep: removed ${i.length} expired namespace(s): ${i.join(", ")}`)}async _buildSystemPrompt(e){if(e.systemPrompt)return"function"==typeof e.systemPrompt?await e.systemPrompt():e.systemPrompt;if(this._config.systemPrompt)return"function"==typeof this._config.systemPrompt?await this._config.systemPrompt():this._config.systemPrompt;if(this._context){await this._context.collect();const e=this._actions.getToolSchemas();return this._context.toSystemPrompt({tools:e})}return"You are an AI assistant connected to a web application via Wu Framework."}_setSystemMessage(e,t){e.messages.length>0&&"system"===e.messages[0].role?(e.messages[0].content=t,e.messages[0]._ts=Date.now()):e.messages.unshift({role:"system",content:t,_ts:Date.now()})}_processMessage(e,t){if(!t)return e;try{return $e(e,{...this._context?.getInterpolationContext()||{},...t})}catch{return e}}_mergeSignals(e,t){if(!t)return e;if("undefined"!=typeof AbortSignal&&AbortSignal.any)return AbortSignal.any([e,t]);const s=new AbortController,r=()=>s.abort();return e.addEventListener("abort",r,{once:!0}),t.addEventListener("abort",r,{once:!0}),s.signal}getStats(){const e={};for(const[t,s]of this._namespaces)e[t]={messageCount:s.messages.length,lastActivity:s.lastActivity,hasActiveRequest:!!s._abortController};return{namespaces:e,config:{...this._config}}}}const Pe={enabled:!0,maxActiveTriggers:20,defaultDebounceMs:1e3,batchIntervalMs:2e3};class Me{constructor(e,t){this.name=e,this.pattern=t.pattern,this.prompt=t.prompt,this.condition=t.condition||null,this.debounceMs=t.debounce??Pe.defaultDebounceMs,this.priority=t.priority||"medium",this.namespace=t.namespace||`trigger:${e}`,this.systemPrompt=t.systemPrompt||null,this.onResult=t.onResult||null,this.enabled=!1!==t.enabled,this.maxTokens=t.maxTokens||void 0,this.temperature=t.temperature||void 0,this._debounceTimer=null,this._lastFired=0,this._fireCount=0,this._pendingEvent=null}matches(e){if(!this.pattern)return!1;if("*"===this.pattern)return!0;if(!this.pattern.includes("*"))return e===this.pattern;return new RegExp("^"+this.pattern.replace(/\*/g,"[^:]*")+"$").test(e)}buildPrompt(e){return"function"==typeof this.prompt?this.prompt(e):$e(this.prompt,{event:e,data:e?.data,timestamp:Date.now()})}async checkCondition(e){if(!this.condition)return!0;try{const t=this.condition(e);return t instanceof Promise?await t:t}catch(e){return t.wuDebug(`[wu-ai] Trigger '${this.name}' condition error: ${e.message}`),!1}}}class Le{constructor({eventBus:e,conversation:t,permissions:s}){this._eventBus=e,this._conversation=t,this._permissions=s,this._config={...Pe},this._triggers=new Map,this._listeners=new Map,this._batchQueue=[],this._batchTimer=null,this._stats={totalFired:0,totalSkipped:0,totalErrors:0}}configure(e){Object.assign(this._config,e)}register(e,s){if(this._triggers.size>=this._config.maxActiveTriggers)return void t.wuWarn(`[wu-ai] Max triggers (${this._config.maxActiveTriggers}) reached. Cannot register '${e}'.`);this._triggers.has(e)&&this.unregister(e);const r=new Me(e,s);this._triggers.set(e,r);const n=this._eventBus.on(r.pattern,t=>this._handleEvent(e,t));this._listeners.set(e,n),t.wuDebug(`[wu-ai] Trigger registered: '${e}' → pattern '${r.pattern}' (${r.priority})`)}unregister(e){const t=this._triggers.get(e);t&&t._debounceTimer&&clearTimeout(t._debounceTimer);const s=this._listeners.get(e);"function"==typeof s&&s(),this._triggers.delete(e),this._listeners.delete(e)}setEnabled(e,t){const s=this._triggers.get(e);s&&(s.enabled=t)}setAllEnabled(e){this._config.enabled=e;for(const t of this._triggers.values())t.enabled=e}async fire(e,s={}){const r=this._triggers.get(e);return r?this._executeTrigger(r,s):(t.wuWarn(`[wu-ai] Trigger '${e}' not found`),null)}getNames(){return[...this._triggers.keys()]}getTrigger(e){const t=this._triggers.get(e);return t?{name:t.name,pattern:t.pattern,priority:t.priority,namespace:t.namespace,enabled:t.enabled,fireCount:t._fireCount,lastFired:t._lastFired}:null}destroy(){for(const e of[...this._triggers.keys()])this.unregister(e);this._batchTimer&&(clearTimeout(this._batchTimer),this._batchTimer=null),this._batchQueue=[]}async _handleEvent(e,t){if(!this._config.enabled)return;const s=this._triggers.get(e);if(!s||!s.enabled)return;await s.checkCondition(t)?"high"===s.priority?this._debouncedFire(s,t):"low"===s.priority?(this._batchQueue.push({trigger:s,eventData:t}),this._scheduleBatch()):this._debouncedFire(s,t):this._stats.totalSkipped++}_debouncedFire(e,t){e._pendingEvent=t,e._debounceTimer&&clearTimeout(e._debounceTimer),e.debounceMs<=0?this._executeTrigger(e,t):e._debounceTimer=setTimeout(()=>{e._debounceTimer=null;const t=e._pendingEvent;e._pendingEvent=null,t&&this._executeTrigger(e,t)},e.debounceMs)}_scheduleBatch(){this._batchTimer||(this._batchTimer=setTimeout(()=>{this._batchTimer=null,this._processBatch()},this._config.batchIntervalMs))}async _processBatch(){const e=[...this._batchQueue];this._batchQueue=[];const t=new Map;for(const{trigger:s,eventData:r}of e)t.set(s.name,{trigger:s,eventData:r});for(const{trigger:e,eventData:s}of t.values())await this._executeTrigger(e,s)}async _executeTrigger(e,s){try{const r=e.buildPrompt(s);if(!r)return this._stats.totalSkipped++,null;t.wuDebug(`[wu-ai] Trigger '${e.name}' firing with prompt: ${r.slice(0,100)}...`);const n=await this._conversation.send(r,{namespace:e.namespace,systemPrompt:e.systemPrompt,temperature:e.temperature,maxTokens:e.maxTokens});if(e._fireCount++,e._lastFired=Date.now(),this._stats.totalFired++,this._eventBus.emit("ai:trigger:result",{trigger:e.name,pattern:e.pattern,result:n},{appName:"wu-ai"}),e.onResult)try{await e.onResult(n,s)}catch(s){t.wuDebug(`[wu-ai] Trigger '${e.name}' onResult error: ${s.message}`)}return n}catch(s){return this._stats.totalErrors++,t.wuWarn(`[wu-ai] Trigger '${e.name}' error: ${s.message}`),this._eventBus.emit("ai:trigger:error",{trigger:e.name,error:s.message},{appName:"wu-ai"}),null}}getStats(){const e={};for(const[t,s]of this._triggers)e[t]={pattern:s.pattern,priority:s.priority,enabled:s.enabled,fireCount:s._fireCount,lastFired:s._lastFired};return{...this._stats,triggerCount:this._triggers.size,batchQueueSize:this._batchQueue.length,triggers:e}}}const Te="[DONE]",Ie="agent:";class Ne{constructor({conversation:e,actions:t,context:s,permissions:r,eventBus:n}){this._conversation=e,this._actions=t,this._context=s,this._permissions=r,this._eventBus=n,this._config={maxSteps:10,systemPrompt:null},this._activeRuns=new Map,this._stats={totalRuns:0,totalSteps:0,completedRuns:0,abortedRuns:0,errorRuns:0}}configure(e){void 0!==e.maxSteps&&(this._config.maxSteps=e.maxSteps),void 0!==e.systemPrompt&&(this._config.systemPrompt=e.systemPrompt)}async*run(e,s={}){const r=s.maxSteps??this._config.maxSteps,n=s.namespace||this._generateNamespace(),i=this._generateRunId(),o=new AbortController;this._activeRuns.set(i,o),s.signal&&(s.signal.aborted?o.abort():s.signal.addEventListener("abort",()=>o.abort(),{once:!0})),this._stats.totalRuns++;const a=await this._buildAgentSystemPrompt(e,s);this._eventBus.emit("ai:agent:start",{runId:i,goal:e,namespace:n,maxSteps:r},{appName:"wu-ai"}),t.wuInfo(`[wu-ai] Agent run started: "${e.slice(0,80)}${e.length>80?"...":""}" (max ${r} steps)`);let c=0,l=!1,u="max_steps";try{for(;c<r;){c++;const t=Date.now();if(o.signal.aborted){const e=this._buildStepResult(c,"aborted",{reason:"Aborted by caller",elapsed:Date.now()-t});return this._stats.abortedRuns++,u="aborted",this._emitStep(i,e),void(yield e)}const r=this._permissions.loopProtection.createTraceId(),d=this._permissions.preflight({namespace:n,depth:0,traceId:r});if(!d.allowed){const e=this._buildStepResult(c,"blocked",{reason:d.reason,elapsed:Date.now()-t});return u="blocked",this._emitStep(i,e),void(yield e)}const h=1===c?e:"Continue working toward the goal. If you are done, include [DONE] in your response.";let p;try{p=await this._conversation.send(h,{namespace:n,systemPrompt:a,provider:s.provider,temperature:s.temperature,maxTokens:s.maxTokens,signal:o.signal})}catch(e){if("AbortError"===e.name||o.signal.aborted){const e=this._buildStepResult(c,"aborted",{reason:"Aborted during LLM call",elapsed:Date.now()-t});return this._stats.abortedRuns++,u="aborted",this._emitStep(i,e),void(yield e)}throw e}const m=Date.now()-t;this._stats.totalSteps++;const f=p.tool_results&&p.tool_results.length>0,g=p.content||"";if(g.includes(Te)){const e=this._buildStepResult(c,"done",{content:g.replace(Te,"").trim(),toolResults:p.tool_results,usage:p.usage,reason:"Goal completed (DONE marker)",elapsed:m});return u="done",this._stats.completedRuns++,this._emitStep(i,e),s.onStep&&await this._safeCallback(s.onStep,e),void(yield e)}const w=f;if(l&&!w){const e=this._buildStepResult(c,"done",{content:g,toolResults:p.tool_results,usage:p.usage,reason:"Goal completed (no further tool calls)",elapsed:m});return u="done",this._stats.completedRuns++,this._emitStep(i,e),s.onStep&&await this._safeCallback(s.onStep,e),void(yield e)}l=w;const y=f?"tool_call":"thinking",_=this._buildStepResult(c,y,{content:g,toolResults:p.tool_results,usage:p.usage,elapsed:m});if(this._emitStep(i,_),s.onStep&&await this._safeCallback(s.onStep,_),yield _,s.shouldContinue){let e;try{e=await s.shouldContinue(_)}catch{e=!1}if(!e){const e=this._buildStepResult(c,"interrupted",{content:g,reason:"Stopped by shouldContinue callback",elapsed:0});return u="interrupted",this._emitStep(i,e),void(yield e)}}}const t=this._buildStepResult(c,"done",{reason:`Max steps (${r}) reached`,elapsed:0});u="max_steps",yield t}catch(s){throw this._stats.errorRuns++,u="error",t.wuWarn(`[wu-ai] Agent run error: ${s.message}`),this._eventBus.emit("ai:agent:error",{runId:i,goal:e,namespace:n,step:c,error:s.message},{appName:"wu-ai"}),s}finally{this._activeRuns.delete(i),!s.namespace&&n.startsWith(Ie)&&this._conversation.deleteNamespace(n),this._eventBus.emit("ai:agent:done",{runId:i,goal:e,namespace:n,totalSteps:c,reason:u},{appName:"wu-ai"}),t.wuDebug(`[wu-ai] Agent run finished: ${u} after ${c} step(s)`)}}abort(e){const s=this._activeRuns.get(e);s&&(s.abort(),t.wuDebug(`[wu-ai] Agent run aborted: ${e}`))}abortAll(){for(const[e,t]of this._activeRuns)t.abort();this._activeRuns.clear()}getActiveRuns(){return[...this._activeRuns.keys()]}getStats(){return{...this._stats,activeRuns:this._activeRuns.size,config:{...this._config}}}destroy(){this.abortAll(),this._stats={totalRuns:0,totalSteps:0,completedRuns:0,abortedRuns:0,errorRuns:0}}async _buildAgentSystemPrompt(e,t){const s=t.systemPrompt??this._config.systemPrompt??null;if(s){return"function"==typeof s?await s(e):s}const r=[];if(r.push("You are an autonomous AI agent connected to a live web application via Wu Framework.","You have been given a goal and must work step-by-step to achieve it.","","PROTOCOL:",'- Each message you send is one "step" in your execution.',"- You may call tools to read or modify application state.","- After each step, you will be prompted to continue.","- When the goal is fully achieved, include the marker [DONE] in your response.","- If you determine the goal cannot be achieved, include [DONE] and explain why.","- Be concise. Each step should make meaningful progress.",""),this._context)try{await this._context.collect();const e=this._context.getSnapshot();e?._mountedApps?.length&&r.push(`MOUNTED APPS: ${e._mountedApps.join(", ")}`,""),e?._store&&Object.keys(e._store).length>0&&r.push(`APPLICATION STATE:\n${JSON.stringify(e._store,null,2)}`,"")}catch{}const n=this._actions.getToolSchemas();if(n.length>0){r.push("AVAILABLE TOOLS:");for(const e of n){const t=e.parameters?.properties?Object.keys(e.parameters.properties).join(", "):"none";r.push(`- ${e.name}(${t}): ${e.description}`)}r.push("")}return r.push(`GOAL: ${e}`),r.join("\n")}_buildStepResult(e,t,s={}){return{step:e,type:t,content:s.content??null,toolResults:s.toolResults??null,usage:s.usage??null,reason:s.reason??null,elapsed:s.elapsed??0}}_emitStep(e,t){this._eventBus.emit("ai:agent:step",{runId:e,...t},{appName:"wu-ai"})}async _safeCallback(e,...s){try{const t=e(...s);t&&"function"==typeof t.then&&await t}catch(e){t.wuDebug(`[wu-ai] Agent callback error: ${e.message}`)}}_generateNamespace(){return Ie+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,6)}_generateRunId(){return"run_"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,8)}}const Oe=[],Re=300,je=[];let Be=!1;function Fe(){Be||(!function(){const e=window.fetch;window.fetch=async function(...t){const s=Date.now(),r=t[0],n="string"==typeof r?r:r?.url||"",i=(t[1]?.method||r?.method||"GET").toUpperCase();try{const r=await e.apply(window,t),o=parseInt(r.headers?.get("content-length")||"0",10);return Oe.push({type:"fetch",method:i,url:n,status:r.status,statusText:r.statusText,duration:Date.now()-s,size:o,timestamp:s}),Oe.length>Re&&Oe.shift(),r}catch(e){throw Oe.push({type:"fetch",method:i,url:n,status:0,error:e.message,duration:Date.now()-s,timestamp:s}),Oe.length>Re&&Oe.shift(),e}};const t=XMLHttpRequest.prototype.open,s=XMLHttpRequest.prototype.send;XMLHttpRequest.prototype.open=function(e,s,...r){return this._wuAi={method:(e||"GET").toUpperCase(),url:String(s)},t.call(this,e,s,...r)},XMLHttpRequest.prototype.send=function(...e){return this._wuAi&&(this._wuAi.start=Date.now(),this.addEventListener("loadend",()=>{Oe.push({type:"xhr",method:this._wuAi.method,url:this._wuAi.url,status:this.status,statusText:this.statusText,duration:Date.now()-this._wuAi.start,size:parseInt(this.getResponseHeader("content-length")||"0",10),timestamp:this._wuAi.start}),Oe.length>Re&&Oe.shift()})),s.apply(this,e)}}(),function(){const e=["log","warn","error"];for(const t of e){const e=console[t];console[t]=(...s)=>{je.push({level:t,message:s.map(e=>{if("object"!=typeof e)return String(e);try{return JSON.stringify(e)}catch(t){return String(e)}}).join(" "),timestamp:Date.now()}),je.length>500&&je.shift(),e.apply(console,s)}}}(),Be=!0)}function ze(e,t=0,s=5){if(t>s||!e)return"";const r=" ".repeat(t),n=e.tagName?.toLowerCase()||"",i=e.getAttribute?.("role")||"",o=e.getAttribute?.("aria-label")||"",a=1===e.childNodes?.length&&3===e.childNodes[0].nodeType?e.textContent?.trim().slice(0,80):"";let c=`${r}<${n}`;if(e.id&&(c+=` id="${e.id}"`),i&&(c+=` role="${i}"`),o&&(c+=` aria-label="${o}"`),e.className&&"string"==typeof e.className){const t=e.className.trim().slice(0,60);t&&(c+=` class="${t}"`)}c+=">",a&&(c+=` "${a}"`);let l=c+"\n";const u=(e.shadowRoot||e).children||[];for(let e=0;e<u.length&&e<50;e++)l+=ze(u[e],t+1,s);return l}function He(e,t){const s=["color","background","background-color","font-family","font-size","font-weight","border","border-radius","padding","margin","display","flex-direction","align-items","justify-content","gap","width","height","max-width","max-height","overflow","opacity","box-shadow","text-align","line-height","position","top","left","right","bottom","z-index","transform","visibility"];try{const r=window.getComputedStyle(e);for(const e of s){const s=r.getPropertyValue(e);s&&t.style?.setProperty(e,s)}}catch(e){}const r=e.children||[],n=t.children||[],i=Math.min(r.length,n.length,200);for(let e=0;e<i;e++)He(r[e],n[e])}async function Ue(e,t=.8){const s=e?document.querySelector(e):document.documentElement;if(!s)return{error:`Element not found: ${e}`};const r=s.getBoundingClientRect(),n=Math.ceil(Math.min(r.width||window.innerWidth,1920)),i=Math.ceil(Math.min(r.height||window.innerHeight,1080)),o=s.cloneNode(!0);He(s,o);const a=(new XMLSerializer).serializeToString(o),c=[`<svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${i}">`,'<foreignObject width="100%" height="100%">',`<div xmlns="http://www.w3.org/1999/xhtml" style="width:${n}px;height:${i}px;overflow:hidden;">`,a,"</div>","</foreignObject>","</svg>"].join(""),l=new Blob([c],{type:"image/svg+xml;charset=utf-8"}),u=URL.createObjectURL(l),d=await new Promise(e=>{const s=new Image;s.onload=()=>{try{const r=document.createElement("canvas");r.width=n,r.height=i;r.getContext("2d").drawImage(s,0,0),e(r.toDataURL("image/png",t))}catch(t){e(null)}finally{URL.revokeObjectURL(u)}},s.onerror=()=>{URL.revokeObjectURL(u),e(null)},s.src=u});if(!d)return{error:"Canvas rendering failed"};const h=d.split(",")[1];return{width:n,height:i,format:"png",base64:h,sizeKB:Math.round(3*h.length/4/1024)}}function qe(e,t){let s=null;if(e&&(s=document.querySelector(e)),!s&&t){const e=document.querySelectorAll('button, a, [role="button"], input[type="submit"], input[type="button"], [data-click], label, [onclick]'),r=t.toLowerCase();for(const t of e)if(t.textContent?.trim().toLowerCase().includes(r)){s=t;break}}if(!s)return{error:`Element not found: ${e||`text="${t}"`}`};s.scrollIntoView({behavior:"instant",block:"center"}),s.click();const r=s.tagName?.toLowerCase();return{clicked:`${r}${s.id?`#${s.id}`:""}`,text:s.textContent?.trim().slice(0,100)||"",rect:s.getBoundingClientRect().toJSON?.()||null}}function Je(e,t,{clear:s=!1,submit:r=!1}={}){if(!e)return{error:"selector is required"};if(void 0===t)return{error:"text is required"};const n=document.querySelector(e);if(!n)return{error:`Element not found: ${e}`};n.focus(),s&&(n.value="",n.dispatchEvent(new Event("input",{bubbles:!0})));const i=Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype,"value")?.set||Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype,"value")?.set,o=s?t:(n.value||"")+t;if(i?i.call(n,o):n.value=o,n.dispatchEvent(new Event("input",{bubbles:!0})),n.dispatchEvent(new Event("change",{bubbles:!0})),r){const e=n.closest("form");e?e.dispatchEvent(new Event("submit",{bubbles:!0,cancelable:!0})):n.dispatchEvent(new KeyboardEvent("keydown",{key:"Enter",code:"Enter",bubbles:!0}))}return{selector:e,typed:t,currentValue:n.value?.slice(0,200),submitted:!!r}}function Ge(e,t,s=30){let r=Oe;return e&&(r=r.filter(t=>t.method===e.toUpperCase())),t&&(r="error"===t?r.filter(e=>0===e.status||e.status>=400):r.filter(e=>String(e.status).startsWith(String(t)))),{requests:r.slice(-s),total:Oe.length,showing:Math.min(r.length,s)}}function Ve(e,t=30){const s=e&&"all"!==e?je.filter(t=>t.level===e):je;return{messages:s.slice(-t),total:je.length,showing:Math.min(s.length,t)}}function Ke(e,t,s){switch(e.action){case"click":{const t=qe(e.selector,e.text);return t.error?{success:!1,error:t.error}:{success:!0,detail:`Clicked: ${e.selector||e.text}`}}case"type":{const t=Je(e.selector,e.value,{clear:e.clear??!0,submit:e.submit??!1});return t.error?{success:!1,error:t.error}:{success:!0,detail:`Typed "${e.value}" into ${e.selector}`}}case"navigate":if(t&&e.section)return t.emit("nav:section",{section:e.section},{appName:"wu-ai"}),{success:!0,detail:`Navigated to section: ${e.section}`};if(e.selector){const t=qe(e.selector,e.text);return t.error?{success:!1,error:t.error}:{success:!0,detail:`Navigated via click: ${e.selector}`}}return{success:!1,error:'navigate requires "section" or "selector"'};case"wait":return{success:!0,detail:`Wait: ${e.ms||0}ms`};case"emit":return t?(t.emit(e.event,e.data||{},{appName:"wu-ai"}),{success:!0,detail:`Emitted: ${e.event}`}):{success:!1,error:"eventBus not available"};case"setState":return s?(s.set(e.path,e.value),{success:!0,detail:`Set state: ${e.path}`}):{success:!1,error:"store not available"};default:return{success:!1,error:`Unknown action: ${e.action}`}}}function Qe(e,t=5e3){return new Promise(s=>{if(document.querySelector(e))return void s(!0);let r=0;const n=setInterval(()=>{r+=100,document.querySelector(e)?(clearInterval(n),s(!0)):r>=t&&(clearInterval(n),s(!1))},100)})}function Ye(e){return new Promise(t=>setTimeout(t,e))}class Xe{constructor({actions:e,conversation:t,context:s,permissions:r,eventBus:n,agent:i,store:o}){this._actions=e,this._conversation=t,this._context=s,this._permissions=r,this._eventBus=n,this._agent=i,this._store=o,this._capabilities=new Map,this._workflows=new Map,this._config={defaultProvider:null,defaultTemperature:.3},this._stats={totalIntents:0,resolvedIntents:0,failedIntents:0,workflowsRegistered:0,workflowsExecuted:0}}configure(e){void 0!==e.defaultProvider&&(this._config.defaultProvider=e.defaultProvider),void 0!==e.defaultTemperature&&(this._config.defaultTemperature=e.defaultTemperature)}register(e,s,r){if(!e||!s)throw new Error("[wu-ai] capability() requires both appName and actionName");if(!r||"function"!=typeof r.handler)throw new Error(`[wu-ai] capability '${e}:${s}' must have a handler function`);const n=`${e}:${s}`;this._capabilities.has(e)||this._capabilities.set(e,new Map),this._capabilities.get(e).set(s,{description:r.description||s,qualifiedName:n}),this._actions.register(n,{...r,description:`[${e}] ${r.description||s}`}),t.wuDebug(`[wu-ai] Capability registered: ${n}`)}unregister(e,t){const s=this._capabilities.get(e);if(!s)return;const r=`${e}:${t}`;s.delete(t),this._actions.unregister(r),0===s.size&&this._capabilities.delete(e)}removeApp(e){const s=this._capabilities.get(e);if(!s)return 0;let r=0;for(const[t]of s){const s=`${e}:${t}`;this._actions.unregister(s),r++}return this._capabilities.delete(e),t.wuDebug(`[wu-ai] All capabilities removed for app '${e}' (${r})`),this._eventBus.emit("ai:app:removed",{appName:e,capabilitiesRemoved:r},{appName:"wu-ai"}),r}getCapabilityMap(){const e={};for(const[t,s]of this._capabilities){e[t]=[];for(const[,r]of s)e[t].push({action:r.qualifiedName,description:r.description})}return e}getRegisteredApps(){return[...this._capabilities.keys()]}hasApp(e){return this._capabilities.has(e)}getTotalCapabilities(){let e=0;for(const t of this._capabilities.values())e+=t.size;return e}async resolve(e,t={}){if(!e||"string"!=typeof e)throw new Error("[wu-ai] intent() requires a description string");this._stats.totalIntents++;const s=this._generateNamespace();if(this._context)try{await this._context.collect()}catch{}const r=this._buildOrchestratorPrompt(t);this._eventBus.emit("ai:intent:start",{description:e.slice(0,200),namespace:s,capabilities:this.getTotalCapabilities()},{appName:"wu-ai"});try{const n=await this._conversation.send(e,{namespace:s,systemPrompt:r,provider:t.provider||this._config.defaultProvider,temperature:t.temperature??this._config.defaultTemperature,maxTokens:t.maxTokens,signal:t.signal,responseFormat:t.responseFormat}),i=n.tool_results||[],o=this._extractInvolvedApps(i),a=!!n.content;a?this._stats.resolvedIntents++:this._stats.failedIntents++;const c={content:n.content||"",tool_results:i,usage:n.usage||null,resolved:a,appsInvolved:o};return this._eventBus.emit("ai:intent:resolved",{description:e.slice(0,200),resolved:a,appsInvolved:o},{appName:"wu-ai"}),c}catch(t){throw this._stats.failedIntents++,this._eventBus.emit("ai:intent:error",{description:e.slice(0,200),error:t.message},{appName:"wu-ai"}),t}finally{this._conversation.deleteNamespace(s)}}buildOrchestratorPrompt(e={}){return this._buildOrchestratorPrompt(e)}_buildOrchestratorPrompt(e={}){const t=[];t.push("You are an AI orchestrator for a microfrontend application.","Multiple independent apps are mounted, each with specific capabilities.","Resolve cross-app requests by calling the right capabilities in the right order.","","RULES:","- Call capabilities (tools) to gather data or trigger actions.","- You may call multiple capabilities from different apps if needed.","- Synthesize results into a clear, actionable response.","- If a required app is not available or lacks a capability, explain what is missing.","");const s=this.getCapabilityMap(),r=Object.keys(s);if(r.length>0){t.push("CAPABILITY MAP:");for(const e of r){t.push(` ${e}:`);for(const r of s[e])t.push(` - ${r.action}: ${r.description}`)}t.push("")}else t.push("NOTE: No app capabilities are registered. Answer based on available context only.","");if(e.plan&&e.plan.length>0){t.push("SUGGESTED PLAN (follow this unless a better approach is evident):");for(let s=0;s<e.plan.length;s++)t.push(` ${s+1}. ${e.plan[s]}`);t.push("")}const n=this._context?.getSnapshot();return n?._mountedApps?.length&&t.push(`MOUNTED APPS: ${n._mountedApps.join(", ")}`,""),n?._store&&Object.keys(n._store).length>0&&t.push("CURRENT STATE:",JSON.stringify(n._store,null,2),""),t.join("\n")}registerWorkflow(e,s){if(!e)throw new Error("[wu-ai] workflow() requires a name");if(!s||!s.steps||!Array.isArray(s.steps)||0===s.steps.length)throw new Error(`[wu-ai] workflow '${e}' must have a non-empty steps array`);const r=s.mode||(s.steps.length>0&&"object"==typeof s.steps[0]&&s.steps[0].action?"deterministic":"ai");this._workflows.set(e,{description:s.description||e,steps:s.steps,mode:r,parameters:s.parameters||{},maxSteps:s.maxSteps??15,provider:s.provider||null,temperature:s.temperature??.2}),this._stats.workflowsRegistered++,t.wuDebug(`[wu-ai] Workflow registered: '${e}' (${s.steps.length} steps)`)}async*executeWorkflow(e,t={},s={}){const r=this._workflows.get(e);if(!r)throw new Error(`[wu-ai] Workflow '${e}' is not registered`);for(const[s,n]of Object.entries(r.parameters))if(n.required&&(void 0===t[s]||null===t[s]))throw new Error(`[wu-ai] Workflow '${e}' requires parameter '${s}'`);this._stats.workflowsExecuted++,"deterministic"===r.mode?yield*this._executeDeterministic(e,r,t,s):yield*this._executeWithAgent(e,r,t,s)}async*_executeWithAgent(e,t,s,r){if(!this._agent)throw new Error("[wu-ai] Agent module not available for workflow execution");const n=t.steps.map(e=>{let t=e;for(const[e,r]of Object.entries(s))t=t.replace(new RegExp(`\\{\\{${e}\\}\\}`,"g"),String(r));return t}),i=this._buildWorkflowGoal(t,n,s);this._eventBus.emit("ai:workflow:start",{workflow:e,mode:"ai",params:s,steps:n.length},{appName:"wu-ai"});let o=null;try{yield*this._agent.run(i,{maxSteps:t.maxSteps,provider:r.provider||t.provider||this._config.defaultProvider,temperature:t.temperature??.2,onStep:e=>{o=e,r.onStep&&r.onStep(e)},shouldContinue:r.shouldContinue,signal:r.signal})}finally{this._eventBus.emit("ai:workflow:done",{workflow:e,params:s,totalSteps:o?.step||0,result:o?.type||"unknown"},{appName:"wu-ai"})}}async*_executeDeterministic(e,t,s,r){const n=t.steps.map(e=>{const t={...e};for(const[e,r]of Object.entries(s)){const s=new RegExp(`\\{\\{${e}\\}\\}`,"g");for(const e of["value","selector","text","section","event","path"])"string"==typeof t[e]&&(t[e]=t[e].replace(s,String(r)))}return t});this._eventBus?.emit("ai:workflow:start",{workflow:e,mode:"deterministic",params:s,steps:n.length},{appName:"wu-ai"});let i=null;try{for(let e=0;e<n.length;e++){const t=n[e],s=e+1,o=Date.now();if(r.signal?.aborted){const e={step:s,type:"aborted",content:"Workflow aborted",reason:"Aborted by caller",elapsed:0};return i=e,void(yield e)}if("wait"===t.action){if(t.selector){const e=await Qe(t.selector,t.timeout||5e3),n=Date.now()-o,a={step:s,type:e?"action":"error",content:e?`Waited for "${t.selector}" — found`:`Timeout waiting for "${t.selector}"`,elapsed:n};if(i=a,r.onStep&&r.onStep(a),yield a,!e)return}else if(t.ms){await Ye(t.ms);const e={step:s,type:"action",content:`Waited ${t.ms}ms`,elapsed:t.ms};i=e,r.onStep&&r.onStep(e),yield e}continue}const a=Ke(t,this._eventBus,this._store),c=Date.now()-o,l={step:s,type:a.success?"action":"error",content:a.success?a.detail:a.error,elapsed:c};if(i=l,r.onStep&&r.onStep(l),yield l,r.shouldContinue){let e;try{e=await r.shouldContinue(l)}catch{e=!1}if(!e){const e={step:s,type:"interrupted",content:"Stopped by user",reason:"shouldContinue returned false",elapsed:0};return i=e,void(yield e)}}if(!a.success)return;e<n.length-1&&await Ye(t.delay??200)}const t={step:n.length,type:"done",content:`Workflow "${e}" completed (${n.length} steps)`,reason:"All steps executed",elapsed:0};i=t,r.onStep&&r.onStep(t),yield t}finally{this._eventBus?.emit("ai:workflow:done",{workflow:e,mode:"deterministic",params:s,totalSteps:i?.step||0,result:i?.type||"unknown"},{appName:"wu-ai"})}}hasWorkflow(e){return this._workflows.has(e)}getWorkflow(e){const t=this._workflows.get(e);return t?{description:t.description,steps:[...t.steps],mode:t.mode,parameters:{...t.parameters},maxSteps:t.maxSteps}:null}removeWorkflow(e){this._workflows.delete(e)}getWorkflowNames(){return[...this._workflows.keys()]}_buildWorkflowGoal(e,t,s){const r=[];r.push(`WORKFLOW: ${e.description}`,"","You must follow these steps IN ORDER. Use browser tools (screenshot, click, type)","to interact with the application. After each step, take a screenshot to verify.","","STEPS:");for(let e=0;e<t.length;e++)r.push(` ${e+1}. ${t[e]}`);r.push("","After completing all steps successfully, respond with [DONE].","If a step fails, explain what went wrong.");const n=this.getCapabilityMap(),i=Object.keys(n);if(i.length>0){r.push("","AVAILABLE APP CAPABILITIES:");for(const e of i)for(const t of n[e])r.push(` - ${t.action}: ${t.description}`)}return r.join("\n")}getStats(){return{...this._stats,registeredApps:this.getRegisteredApps(),totalCapabilities:this.getTotalCapabilities(),capabilityMap:this.getCapabilityMap(),workflows:this.getWorkflowNames(),config:{...this._config}}}destroy(){for(const[e,t]of this._capabilities)for(const[s]of t)this._actions.unregister(`${e}:${s}`);this._capabilities.clear(),this._workflows.clear(),this._stats={totalIntents:0,resolvedIntents:0,failedIntents:0,workflowsRegistered:0,workflowsExecuted:0}}_extractInvolvedApps(e){if(!e||!Array.isArray(e))return[];const t=new Set;for(const s of e){const e=s.name||s.tool||"",r=e.indexOf(":");r>0&&t.add(e.slice(0,r))}return[...t]}_generateNamespace(){return"intent:"+Date.now().toString(36)+"_"+Math.random().toString(36).slice(2,6)}}var Ze=Object.freeze({__proto__:null,WuAI:class{constructor({eventBus:e,store:t,core:s,token:r}){this._store=t,this._core=s,this._initialized=!1,this._modules={},this._token=r||null,this._eventBus=this._wrapEventBus(e)}_wrapEventBus(e){if(!this._token)return e;const t=this._token;return new Proxy(e,{get(e,s){if("emit"===s)return function(s,r,n={}){return e.emit(s,r,{...n,appName:n.appName||"wu-ai",token:n.token||t})};const r=Reflect.get(e,s);return"function"==typeof r?r.bind(e):r}})}init(e={}){return this._initialized?(this._reconfigure(e),this):(this._modules.permissions=new ve({permissions:e.permissions,rateLimit:e.rateLimit,circuitBreaker:e.circuitBreaker,loopProtection:e.loopProtection,allowedDomains:e.allowedDomains}),this._modules.provider=new pe,this._modules.context=new Ee({store:this._store,eventBus:this._eventBus,core:this._core}),e.context&&this._modules.context.configure(e.context),this._modules.actions=new Ae({eventBus:this._eventBus,store:this._store,permissions:this._modules.permissions}),this._modules.conversation=new De({provider:this._modules.provider,actions:this._modules.actions,context:this._modules.context,permissions:this._modules.permissions,eventBus:this._eventBus}),e.conversation&&this._modules.conversation.configure(e.conversation),this._modules.triggers=new Le({eventBus:this._eventBus,conversation:this._modules.conversation,permissions:this._modules.permissions}),e.triggers&&this._modules.triggers.configure(e.triggers),this._modules.agent=new Ne({conversation:this._modules.conversation,actions:this._modules.actions,context:this._modules.context,permissions:this._modules.permissions,eventBus:this._eventBus}),e.agent&&this._modules.agent.configure(e.agent),this._modules.orchestrate=new Xe({actions:this._modules.actions,conversation:this._modules.conversation,context:this._modules.context,permissions:this._modules.permissions,eventBus:this._eventBus,agent:this._modules.agent,store:this._store}),e.orchestrate&&this._modules.orchestrate.configure(e.orchestrate),this._initialized=!0,t.wuInfo("[wu-ai] Initialized"),"undefined"!=typeof window&&(s=this,r=this._core,Fe(),s.action("browser_screenshot",{description:"Take a screenshot of the current page or a specific element. Returns a base64 PNG image. Use this to SEE what the user sees.",parameters:{selector:{type:"string",description:"CSS selector of the element to capture. Empty = full visible page.",required:!1}},handler:async e=>Ue(e.selector),permissions:[]}),s.action("browser_click",{description:"Click an element on the page. Find by CSS selector or by visible text content. Use this to interact with buttons, links, tabs, etc.",parameters:{selector:{type:"string",description:'CSS selector (e.g. "#submit-btn", ".nav-link", "button[type=submit]")',required:!1},text:{type:"string",description:'Visible text to find and click (e.g. "Submit", "Next", "Guardar"). Searches buttons, links, and clickable elements.',required:!1}},handler:async(e,t)=>{const s=qe(e.selector,e.text);return s.error||t.emit?.("browser:clicked",{selector:e.selector,text:e.text}),s},permissions:["emitEvents"]}),s.action("browser_type",{description:"Type text into an input, textarea, or contenteditable element. Works with React, Vue, Angular, and other frameworks. Can optionally clear existing text first and submit the form.",parameters:{selector:{type:"string",description:'CSS selector of the input (e.g. "#email", "input[name=search]", "textarea.comment")',required:!0},text:{type:"string",description:"Text to type into the element",required:!0},clear:{type:"boolean",description:"Clear existing value before typing (default: false)",required:!1},submit:{type:"boolean",description:"Submit the form or press Enter after typing (default: false)",required:!1}},handler:async(e,t)=>{const s=Je(e.selector,e.text,{clear:e.clear,submit:e.submit});return s.error||t.emit?.("browser:typed",{selector:e.selector,length:e.text.length}),s},permissions:["emitEvents"]}),s.action("browser_select",{description:"Select an option in a <select> dropdown or a custom dropdown component.",parameters:{selector:{type:"string",description:"CSS selector of the <select> element",required:!0},value:{type:"string",description:'The value attribute of the option to select. Use "text:" prefix to match by visible text (e.g. "text:Mexico")',required:!0}},handler:async(e,t)=>{const s=document.querySelector(e.selector);if(!s)return{error:`Element not found: ${e.selector}`};if("select"===s.tagName?.toLowerCase()){const r=Array.from(s.options);let n;if(e.value.startsWith("text:")){const t=e.value.slice(5).toLowerCase();n=r.find(e=>e.textContent.trim().toLowerCase().includes(t))}else n=r.find(t=>t.value===e.value);return n?(s.value=n.value,s.dispatchEvent(new Event("change",{bubbles:!0})),s.dispatchEvent(new Event("input",{bubbles:!0})),t.emit?.("browser:selected",{selector:e.selector,value:n.value}),{selected:n.value,text:n.textContent.trim()}):{error:`Option not found: ${e.value}`}}return s.click(),{clicked:e.selector,note:"Custom dropdown — clicked trigger. Use browser_click to select an option from the opened menu."}},permissions:["emitEvents"]}),s.action("browser_scroll",{description:"Scroll the page or a specific element. Use to reveal content that is not visible.",parameters:{direction:{type:"string",description:'Direction: "up", "down", "top", "bottom"',required:!0},selector:{type:"string",description:"CSS selector of scrollable container (empty = page)",required:!1},amount:{type:"number",description:'Pixels to scroll (default: 500). Ignored for "top"/"bottom".',required:!1}},handler:async e=>{const t=e.selector?document.querySelector(e.selector):window,s=e.amount||500;if(e.selector&&!t)return{error:`Element not found: ${e.selector}`};const r=t===window?document.documentElement:t;switch(e.direction){case"up":r.scrollBy({top:-s,behavior:"smooth"});break;case"down":r.scrollBy({top:s,behavior:"smooth"});break;case"top":r.scrollTo({top:0,behavior:"smooth"});break;case"bottom":r.scrollTo({top:r.scrollHeight,behavior:"smooth"});break;default:return{error:`Invalid direction: ${e.direction}`}}return{scrolled:e.direction,amount:"top"===e.direction||"bottom"===e.direction?"max":s,currentScroll:r.scrollTop}},permissions:[]}),s.action("browser_snapshot",{description:"Get a text representation of the visible DOM structure (accessibility tree). Use this to understand what elements are on the page, their roles, IDs, and text content. Cheaper and faster than a screenshot.",parameters:{selector:{type:"string",description:'CSS selector to snapshot (empty = full page). Use "[data-wu-app=appName]" for a specific micro-app.',required:!1},depth:{type:"number",description:"Max depth to traverse (default: 5)",required:!1}},handler:async e=>{const t=e.selector?document.querySelector(e.selector):document.body;return t?{snapshot:ze(t,0,e.depth||5)}:{error:`Element not found: ${e.selector}`}},permissions:[]}),s.action("browser_navigate",{description:"Navigate to a route within the SPA application. Emits a shell:navigate event and updates the store.",parameters:{route:{type:"string",description:'Route path (e.g. "/dashboard", "/users", "/pos/cotizador")',required:!0}},handler:async(e,t)=>(t.emit?.("shell:navigate",{route:e.route}),t.setState?.("currentPath",e.route),{navigated:e.route}),permissions:["emitEvents","writeStore"]}),s.action("browser_network",{description:"View captured HTTP network requests (fetch and XHR). Shows URL, method, status code, duration, and size. Use to debug API calls, check for errors, or monitor performance.",parameters:{method:{type:"string",description:"Filter by HTTP method: GET, POST, PUT, DELETE (empty = all)",required:!1},status:{type:"string",description:'Filter: "2" (2xx success), "4" (4xx errors), "5" (5xx errors), "error" (all failures)',required:!1},limit:{type:"number",description:"Max requests to return (default: 30)",required:!1}},handler:async e=>Ge(e.method,e.status,e.limit),permissions:[]}),s.action("browser_console",{description:"View captured browser console messages (log, warn, error). Use to check for errors, warnings, or debug output.",parameters:{level:{type:"string",description:'Filter by level: "log", "warn", "error" (empty = all)',required:!1},limit:{type:"number",description:"Max messages to return (default: 30)",required:!1}},handler:async e=>Ve(e.level,e.limit),permissions:[]}),s.action("browser_info",{description:"Get an overview of the current page state: URL, viewport size, mounted micro-apps, store keys, visible elements summary. Use this FIRST to understand the page before taking actions.",parameters:{},handler:async(e,t)=>{const s=[];if(r._apps)for(const[e,t]of Object.entries(r._apps))s.push({name:e,mounted:t.mounted||t.isMounted||!1,status:t.status||"unknown"});0===s.length&&document.querySelectorAll("[data-wu-app]").forEach(e=>{s.push({name:e.getAttribute("data-wu-app"),mounted:!0})});const n=t.getState?.("")||{},i="object"==typeof n?Object.keys(n):[];return{url:window.location.href,title:document.title,viewport:{width:window.innerWidth,height:window.innerHeight},apps:s,storeKeys:i,networkRequests:Oe.length,consoleMessages:je.length,consoleErrors:je.filter(e=>"error"===e.level).length}},permissions:["readStore"]}),t.wuInfo("[wu-ai] Browser actions registered (10 tools)")),this._eventBus.emit("ai:initialized",{},{appName:"wu-ai"}),this);var s,r}provider(e,t){return this._ensureInit(),this._modules.provider.register(e,t),this}async send(e,t={}){return this._ensureInit(),this._modules.conversation.send(e,t)}async*stream(e,t={}){this._ensureInit(),yield*this._modules.conversation.stream(e,t)}async json(e,t={}){this._ensureInit();const{schema:s,schemaName:r,...n}=t;let i;i=s?{type:"json_schema",schema:s,name:r||"response"}:t.responseFormat||"json";const o=await this._modules.conversation.send(e,{...n,responseFormat:i});let a,c=null;if(void 0!==o.parsed)c=o.parsed;else if(o.content)try{c=JSON.parse(o.content)}catch{a="LLM response is not valid JSON"}return{data:c,raw:o.content||"",error:a||o.parseError,usage:o.usage,namespace:o.namespace}}abort(e){this._initialized&&(e?this._modules.conversation.abort(e):this._modules.conversation.abortAll())}action(e,t){return this._ensureInit(),this._modules.actions.register(e,t),this}async execute(e,t){this._ensureInit();const s=this._modules.permissions.loopProtection.createTraceId();return this._modules.actions.execute(e,t,{traceId:s,depth:0})}trigger(e,t){return this._ensureInit(),this._modules.triggers.register(e,t),this}async fireTrigger(e,t){return this._ensureInit(),this._modules.triggers.fire(e,t)}async*agent(e,t={}){this._ensureInit(),yield*this._modules.agent.run(e,t)}capability(e,t,s){return this._ensureInit(),this._modules.orchestrate.register(e,t,s),this}async intent(e,t={}){return this._ensureInit(),this._modules.orchestrate.resolve(e,t)}removeApp(e){return this._ensureInit(),this._modules.orchestrate.removeApp(e),this}workflow(e,t){return this._ensureInit(),this._modules.orchestrate.registerWorkflow(e,t),this}async*runWorkflow(e,t={},s={}){this._ensureInit(),yield*this._modules.orchestrate.executeWorkflow(e,t,s)}get context(){return this._ensureInit(),{configure:e=>this._modules.context.configure(e),register:(e,t)=>this._modules.context.register(e,t),collect:()=>this._modules.context.collect(),getSnapshot:()=>this._modules.context.getSnapshot()}}get conversation(){return this._ensureInit(),{getHistory:e=>this._modules.conversation.getHistory(e),clear:e=>this._modules.conversation.clear(e),clearAll:()=>this._modules.conversation.clearAll(),inject:(e,t,s)=>this._modules.conversation.inject(e,t,s),getNamespaces:()=>this._modules.conversation.getNamespaces(),deleteNamespace:e=>this._modules.conversation.deleteNamespace(e)}}get permissions(){return this._ensureInit(),{configure:e=>this._modules.permissions.configure(e),check:e=>this._modules.permissions.check(e),getPermissions:()=>this._modules.permissions.getPermissions(),setAllowedDomains:e=>this._modules.permissions.setAllowedDomains(e)}}tools(){return this._ensureInit(),this._modules.actions.getToolSchemas()}expose(){if(this._ensureInit(),"undefined"==typeof navigator||!navigator.modelContext)return t.wuDebug("[wu-ai] WebMCP not available (navigator.modelContext missing)"),!1;const e=this._modules.actions.getToolSchemas(),s=this._modules.actions.getNames();for(let r=0;r<e.length;r++){const n=e[r],i=s[r];try{navigator.modelContext.registerTool({name:n.name,description:n.description,inputSchema:n.parameters,handler:async e=>{const t=await this.execute(i,e);return t.success?t.result:{error:t.reason}}})}catch(e){t.wuDebug(`[wu-ai] WebMCP register failed for '${n.name}': ${e.message}`)}}return t.wuInfo(`[wu-ai] Exposed ${e.length} tools via WebMCP`),this._eventBus.emit("ai:webmcp:exposed",{toolCount:e.length,tools:e.map(e=>e.name)},{appName:"wu-ai"}),!0}confirmTool(e){this._initialized&&this._modules.actions.confirmTool(e)}rejectTool(e){this._initialized&&this._modules.actions.rejectTool(e)}getStats(){return this._initialized?{initialized:!0,provider:this._modules.provider.getStats(),permissions:this._modules.permissions.getStats(),context:this._modules.context.getStats(),actions:this._modules.actions.getStats(),conversation:this._modules.conversation.getStats(),triggers:this._modules.triggers.getStats(),agent:this._modules.agent.getStats(),orchestrate:this._modules.orchestrate.getStats()}:{initialized:!1}}destroy(){this._initialized&&(this._modules.orchestrate.destroy(),this._modules.agent.destroy(),this._modules.conversation.abortAll(),this._modules.triggers.destroy(),this._modules={},this._initialized=!1,t.wuInfo("[wu-ai] Destroyed"),this._eventBus.emit("ai:destroyed",{},{appName:"wu-ai"}))}_ensureInit(){this._initialized||this.init()}_reconfigure(e){e.permissions&&this._modules.permissions.configure(e.permissions),e.rateLimit&&this._modules.permissions.rateLimiter.configure(e.rateLimit),e.circuitBreaker&&this._modules.permissions.circuitBreaker.configure(e.circuitBreaker),e.loopProtection&&this._modules.permissions.loopProtection.configure(e.loopProtection),e.context&&this._modules.context.configure(e.context),e.conversation&&this._modules.conversation.configure(e.conversation),e.triggers&&this._modules.triggers.configure(e.triggers),e.agent&&this._modules.agent.configure(e.agent),e.orchestrate&&this._modules.orchestrate.configure(e.orchestrate)}}});var et=Object.freeze({__proto__:null,createMcpBridge:function(e){let s=null,r=null,n=0,i=!1,o=null;const a=e.eventBus?.getInternalToken?.("wu-mcp-bridge")||null,c=(t,s)=>e.eventBus?.emit(t,s,{appName:"wu-mcp-bridge",token:a}),l=[];function u(t){if(e.ai&&e.ai.permissions)return e.ai.permissions.check(t);return["readStore","executeActions"].includes(t)}function d(t,s,r){e.eventBus&&c("mcp:bridge:operation",{operation:t,params:s,result:r?.error?{error:r.error}:{success:!0},timestamp:Date.now()})}e.eventBus&&e.eventBus.on("*",e=>{l.push({name:e.name,data:e.data,timestamp:e.timestamp||Date.now(),source:e.source||"unknown"}),l.length>200&&l.shift()}),Fe();const h={status:()=>({connected:!0,framework:"wu-framework",apps:w(),storeKeys:e.store?Object.keys(e.store.get("")||{}):[],actionsCount:e.ai?e.ai.tools().length:0,eventLogSize:l.length}),list_apps:()=>w(),list_events:({limit:e=20})=>l.slice(-e),list_actions(){if(!e.ai)return{actions:[],note:"wu.ai not initialized"};const t=e.ai.tools();return{actions:t,count:t.length}},snapshot({appName:e}){try{const t=e?document.querySelector(`[data-wu-app="${e}"]`)||document.querySelector(`#wu-app-${e}`):document.body;return t?{app:e||"(page)",snapshot:ze(t,0,5),timestamp:Date.now()}:{error:`App "${e}" not found in DOM`}}catch(e){return{error:e.message}}},console:({level:e="all",limit:t=50})=>Ve(e,t),async screenshot({selector:e,quality:t=.8}){const s=await Ue(e,t);return s.error||(s.timestamp=Date.now()),s},network:({method:e,status:t,limit:s=50})=>Ge(e,t,s),get_state({path:t}){if(!e.store)return{error:"wu.store not available"};if(!u("readStore"))return{error:"Permission denied: readStore is disabled"};return{path:t||"(root)",value:e.store.get(t||"")}},set_state:({path:t,value:s})=>e.store?t?u("writeStore")?(e.store.set(t,s),d("set_state",{path:t,value:s},{}),{path:t,value:s,updated:!0}):(d("set_state",{path:t},{error:"Permission denied"}),{error:"Permission denied: writeStore is disabled"}):{error:"path is required"}:{error:"wu.store not available"},emit_event:({event:t,data:s})=>e.eventBus?t?u("emitEvents")?(c(t,s),d("emit_event",{event:t,data:s},{}),{emitted:t,data:s}):(d("emit_event",{event:t},{error:"Permission denied"}),{error:"Permission denied: emitEvents is disabled"}):{error:"event name is required"}:{error:"wu.eventBus not available"},navigate:({route:t})=>t?u("emitEvents")?(c("shell:navigate",{route:t}),e.store&&u("writeStore")&&e.store.set("currentPath",t),d("navigate",{route:t},{}),{navigated:t}):(d("navigate",{route:t},{error:"Permission denied: emitEvents"}),{error:"Permission denied: emitEvents is disabled"}):{error:"Route is required"},mount_app({appName:t,container:s}){if(!t)return{error:"appName is required"};if(!u("modifyDOM"))return d("mount_app",{appName:t},{error:"Permission denied"}),{error:"Permission denied: modifyDOM is disabled"};try{return e.mount?(e.mount(t,s),d("mount_app",{appName:t,container:s},{success:!0}),{mounted:t,container:s}):{error:"wu.mount not available"}}catch(e){return{error:e.message}}},unmount_app({appName:t}){if(!t)return{error:"appName is required"};if(!u("modifyDOM"))return d("unmount_app",{appName:t},{error:"Permission denied"}),{error:"Permission denied: modifyDOM is disabled"};try{return e.unmount?(e.unmount(t),d("unmount_app",{appName:t},{success:!0}),{unmounted:t}):{error:"wu.unmount not available"}}catch(e){return{error:e.message}}},click({selector:e,text:t}){if(!u("modifyDOM"))return{error:"Permission denied: modifyDOM is disabled"};const s=qe(e,t);return d("click",{selector:e,text:t},s),s},type({selector:e,text:t,clear:s=!1,submit:r=!1}){if(!u("modifyDOM"))return{error:"Permission denied: modifyDOM is disabled"};const n=Je(e,t,{clear:s,submit:r});return d("type",{selector:e,textLength:t?.length},n),n},async execute_action({action:t,params:s}){if(!e.ai)return{error:"wu.ai not available"};if(!t)return{error:"action name is required"};try{return{action:t,...await e.ai.execute(t,s||{})}}catch(e){return{error:e.message}}}};function p(e="ws://localhost:19100",r={}){if(s&&s.readyState<=1)t.warn("[wu-mcp-bridge] Already connected or connecting");else{o=r.token||null,i=!o;try{s=new WebSocket(e),s.onopen=()=>{t.debug("[wu-mcp-bridge] Connected to wu-mcp-server"),n=0,o&&s.send(JSON.stringify({type:"auth",token:o}))},s.onmessage=async e=>{try{const s=JSON.parse(e.data);if("auth_result"===s.type)return i=!0===s.success,void(i?t.debug("[wu-mcp-bridge] Authenticated successfully"):(console.error("[wu-mcp-bridge] Authentication failed:",s.reason||"Invalid token"),m()));if(!i)return void(s.id&&f(s.id,null,"Not authenticated. Send auth token first."));const{id:r,command:n,params:o}=s;if(!r||!n)return void t.warn("[wu-mcp-bridge] Invalid message:",s);const a=h[n];if(!a)return void f(r,null,`Unknown command: ${n}`);try{f(r,await a(o||{}))}catch(e){f(r,null,e.message)}}catch(e){console.error("[wu-mcp-bridge] Failed to handle message:",e)}},s.onclose=()=>{t.debug("[wu-mcp-bridge] Disconnected"),s=null,i=!1,g(e,r)},s.onerror=()=>{}}catch(t){console.error("[wu-mcp-bridge] Connection failed:",t.message),g(e,r)}}}function m(){r&&(clearTimeout(r),r=null),n=10,s&&(s.close(),s=null),i=!1}function f(e,t,r){if(!s||1!==s.readyState)return;const n=r?{id:e,error:r}:{id:e,result:t};s.send(JSON.stringify(n))}function g(e,t){if(n>=10)return;n++;const s=2e3*Math.min(n,5);r=setTimeout(()=>p(e,t),s)}function w(){const t=[];if(e._apps)for(const[s,r]of Object.entries(e._apps))t.push({name:s,mounted:r.mounted||r.isMounted||!1,url:r.url||r.info?.url||"",status:r.status||r.info?.status||"unknown"});return 0===t.length&&document.querySelectorAll("[data-wu-app]").forEach(e=>{t.push({name:e.getAttribute("data-wu-app"),mounted:!0,container:`#${e.id||"(no-id)"}`})}),t}return{connect:p,disconnect:m,isConnected:function(){return null!==s&&1===s.readyState&&i}}}});exports.WuApp=h,exports.WuCache=p,exports.WuContracts=C,exports.WuCore=D,exports.WuErrorBoundary=b,exports.WuEventBus=m,exports.WuLifecycleHooks=v,exports.WuLoader=P,exports.WuLoadingStrategy=_,exports.WuManifest=l,exports.WuOverrides=$,exports.WuPerformance=w,exports.WuPluginSystem=y,exports.WuPrefetch=x,exports.WuProxySandbox=o,exports.WuSandbox=c,exports.WuStore=u,exports.WuStyleBridge=i,exports.app=(e,t)=>exports.wu.app(e,t),exports.can=e=>exports.wu.can(e),exports.clearOverrides=()=>exports.wu.clearOverrides(),exports.compareVersions=A,exports.consume=(e,t,s)=>exports.wu.contracts.consume(e,t,s),exports.createConditionalHook=(e,t)=>async(s,r)=>{await e(s)&&await t(s),await r()},exports.createGuardHook=e=>async(t,s)=>{await e(t)&&await s()},exports.createPlugin=e=>({name:e.name,permissions:e.permissions||["events"],install:e.install,uninstall:e.uninstall,beforeInit:e.beforeInit,afterInit:e.afterInit,beforeMount:e.beforeMount,afterMount:e.afterMount,beforeUnmount:e.beforeUnmount,afterUnmount:e.afterUnmount,onError:e.onError,onDestroy:e.onDestroy}),exports.createSimpleHook=e=>async(t,s)=>{await e(t),await s()},exports.createTimedHook=(e,t=5e3)=>async(s,r)=>{const n=new Promise((e,s)=>setTimeout(()=>s(new Error("Hook timeout")),t));try{await Promise.race([e(s),n]),await r()}catch(e){console.error("[WuHooks] Timed hook failed:",e),await r()}},exports.createTransformHook=e=>async(t,s)=>{const r=await e(t);await s(r)},exports.default=R,exports.define=(e,t)=>exports.wu.define(e,t),exports.destroy=()=>exports.wu.destroy(),exports.emit=(e,t,s)=>exports.wu.eventBus.emit(e,t,s),exports.enableAllLogs=r,exports.endMeasure=(e,t)=>exports.wu.performance.endMeasure(e,t),exports.generatePerformanceReport=()=>exports.wu.performance.generateReport(),exports.getOverrides=()=>exports.wu.getOverrides(),exports.getPrincipal=()=>exports.wu.getPrincipal(),exports.getState=e=>exports.wu.store.get(e),exports.hide=e=>exports.wu.hide(e),exports.init=e=>exports.wu.init({apps:e}),exports.isHidden=e=>exports.wu.isHidden(e),exports.mount=(e,t)=>exports.wu.mount(e,t),exports.normalizeStyleMode=a,exports.off=(e,t)=>exports.wu.eventBus.off(e,t),exports.on=(e,t)=>exports.wu.eventBus.on(e,t),exports.onStateChange=(e,t)=>exports.wu.store.on(e,t),exports.once=(e,t)=>exports.wu.eventBus.once(e,t),exports.override=(e,t,s)=>exports.wu.override(e,t,s),exports.parseVersion=E,exports.prefetch=(e,t)=>exports.wu.prefetch(e,t),exports.prefetchAll=e=>exports.wu.prefetchAll(e),exports.provide=(e,t,s)=>exports.wu.contracts.provide(e,t,s),exports.removeOverride=e=>exports.wu.removeOverride(e),exports.satisfies=W,exports.setPrincipal=e=>exports.wu.setPrincipal(e),exports.setState=(e,t)=>exports.wu.store.set(e,t),exports.show=e=>exports.wu.show(e),exports.silenceAllLogs=s,exports.startMeasure=(e,t)=>exports.wu.performance.startMeasure(e,t),exports.store=d,exports.syncStore=e=>exports.wu.store.sync(e),exports.unmount=(e,t)=>exports.wu.unmount(e,t),exports.useHook=(e,t,s)=>exports.wu.hooks.use(e,t,s),exports.usePlugin=(e,t)=>exports.wu.pluginSystem.use(e,t);
3
+ //# sourceMappingURL=wu-framework.cjs.map