@decido/shell 4.0.2 → 4.0.4

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 (37) hide show
  1. package/dist/CenterComposite-V3LL23PG.mjs +64 -0
  2. package/dist/DebugPanel-NFXQOZQ6.mjs +1 -0
  3. package/dist/MorphShell-4JGDAN46.mjs +1 -0
  4. package/dist/PlaygroundAppSidebar-QI73PNRI.mjs +1 -0
  5. package/dist/PlaygroundChat-CBIIQMWU.mjs +1 -0
  6. package/dist/PlaygroundTerminal-MVZKXTYW.mjs +1 -0
  7. package/dist/PluginSandbox-MUNBFWGH.mjs +1 -0
  8. package/dist/ReactFlowEditor-2ALQWCHQ.mjs +6 -0
  9. package/dist/ReactFlowEditor-ROZ6RF3K.css +1 -0
  10. package/dist/TimelineEditor-UPRRXXVM.mjs +3 -0
  11. package/dist/WidgetSlotPanel-YX2VBQAP.mjs +1 -0
  12. package/dist/chunk-3YEFIKFH.mjs +1 -0
  13. package/dist/chunk-53FADIUX.mjs +1 -0
  14. package/dist/chunk-5FWJFDER.mjs +285 -0
  15. package/dist/chunk-6K3AFDP5.mjs +1 -0
  16. package/dist/chunk-AGAAZ2MU.mjs +1 -0
  17. package/dist/chunk-BCP43BRV.mjs +2 -0
  18. package/dist/chunk-BSJBW64M.mjs +1 -0
  19. package/dist/chunk-C5FD536O.mjs +1 -0
  20. package/dist/chunk-DTH34ILQ.mjs +1 -0
  21. package/dist/chunk-DWP77YZU.mjs +1 -0
  22. package/dist/chunk-O3OWL3Q2.mjs +1 -0
  23. package/dist/chunk-POBZMHZ5.mjs +7 -0
  24. package/dist/chunk-S3AQ4QDD.mjs +42 -0
  25. package/dist/chunk-XDA6ZRIQ.mjs +1 -0
  26. package/dist/chunk-XTDMHHMW.mjs +5 -0
  27. package/dist/chunk-YAYNNUEX.mjs +12 -0
  28. package/dist/chunk-YEKQJ4YC.mjs +1 -0
  29. package/dist/chunk-YHFKY5MB.mjs +1 -0
  30. package/dist/chunk-ZKD74U4X.mjs +1 -0
  31. package/dist/index.css +1 -0
  32. package/dist/index.js +506 -0
  33. package/dist/index.mjs +89 -0
  34. package/dist/useIntentLens-OCAUBNOQ.mjs +1 -0
  35. package/dist/useSuggestionsStore-Q4KVPU7L.mjs +1 -0
  36. package/dist/wasm-A4BTVJWV.mjs +1 -0
  37. package/package.json +18 -19
package/dist/index.mjs ADDED
@@ -0,0 +1,89 @@
1
+ import{a as dp,b as Zw,c as Qw,d as qc}from"./chunk-5FWJFDER.mjs";import{b as Dr,c as nr,d as up,e as hp,f as fp,g as pp,i as ir,j as mp,k as Zi,l as pa,m as ma,n as gp,o as Qi,p as es,q as ts,r as bp}from"./chunk-POBZMHZ5.mjs";import{a as Kr}from"./chunk-DWP77YZU.mjs";import{a as jc}from"./chunk-XTDMHHMW.mjs";import{a as np,b as ip,c as Xi,d as Gc,e as Jw,f as Xw,g as lp,h as fa,i as cp}from"./chunk-53FADIUX.mjs";import{a as _w,b as zw,c as $w,d as op,e as ap}from"./chunk-S3AQ4QDD.mjs";import{a as Hw,b as Ww,c as Vw,d as jw,e as Uw,f as Gw,g as qw}from"./chunk-C5FD536O.mjs";import"./chunk-6K3AFDP5.mjs";import{d as Kw}from"./chunk-DTH34ILQ.mjs";import{a as Yw}from"./chunk-YAYNNUEX.mjs";import{a as wI,b as SI,c as CI,d as kI,e as NI,f as EI,g as AI,h as Vc}from"./chunk-BCP43BRV.mjs";import{a as Ks,b as MI,c as DI,d as OI}from"./chunk-O3OWL3Q2.mjs";import{a as Uc}from"./chunk-ZKD74U4X.mjs";import{a as TI}from"./chunk-BSJBW64M.mjs";import{a as sp,b as ce}from"./chunk-AGAAZ2MU.mjs";import{a as qn}from"./chunk-YHFKY5MB.mjs";import{a as ne}from"./chunk-XDA6ZRIQ.mjs";import{a as tp,b as rp}from"./chunk-YEKQJ4YC.mjs";var t0=tp(($8,Pn)=>{"use strict";function qd(){return Pn.exports=qd=Object.assign?Object.assign.bind():function(r){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var n in t)({}).hasOwnProperty.call(t,n)&&(r[n]=t[n])}return r},Pn.exports.__esModule=!0,Pn.exports.default=Pn.exports,qd.apply(null,arguments)}Pn.exports=qd,Pn.exports.__esModule=!0,Pn.exports.default=Pn.exports});var r0=tp((H8,mo)=>{"use strict";function bE(r,e){if(r==null)return{};var t={};for(var n in r)if({}.hasOwnProperty.call(r,n)){if(e.indexOf(n)!==-1)continue;t[n]=r[n]}return t}mo.exports=bE,mo.exports.__esModule=!0,mo.exports.default=mo.exports});import{create as e1}from"zustand";import{kernel as xp}from"@decido/kernel-bridge";import{sentinelMiddleware as t1}from"@decido/sentinel-browser";var rt=e1()(t1("shell_store",r=>({plugins:new Map,widgets:new Map,activeShellMode:"workbench",setShellMode:e=>r({activeShellMode:e}),rootLayout:null,activeWidgetId:null,workspaces:[],activeWorkspaceId:null,transientOverlays:[],isCommandPaletteOpen:!1,isForgeTerminalOpen:!1,isGodModePanelOpen:!1,isMarketplaceOpen:!1,isShortcutSettingsOpen:!1,savedScenes:{},widgetDataBus:{},setWidgetData:(e,t)=>r(n=>({widgetDataBus:{...n.widgetDataBus,[e]:t}})),isThinClient:!1,initializeEnvironment:async()=>{try{if(!(typeof window<"u"&&"__TAURI_INTERNALS__"in window)){console.log("[OS] Web Environment Detected (No Tauri). Running in standard browser mode."),r({isThinClient:!1});return}let n=await(await import("@tauri-apps/plugin-os")).type(),i=n==="android"||n==="ios";r({isThinClient:i}),console.log(`[OS] Entorno detectado: ${i?"M\xF3vil (Thin Client)":"Desktop (Node)"}`),i&&xp.execute("broadcast_message",{intent:"node_announcement",payload:JSON.stringify({tier:"Satellite",capabilities:["voice","display"]})}),xp.onEvent(async s=>{if(s.event_type==="broadcast_event"&&s.data?.intent==="push_notification"){let{title:o,body:a,urgency:l}=s.data.payload;try{let c=await import("@tauri-apps/plugin-notification"),d=await c.isPermissionGranted();d||(d=await c.requestPermission()==="granted"),d&&(c.sendNotification({title:o,body:a,icon:"notification_icon",sound:l==="critical"?"alarm":"default"}),console.log(`[Satellite] \u{1F514} Alerta recibida de ${s.agent_id}: ${o}`))}catch(c){console.warn("Failed to send tauri notification",c)}}})}catch(e){console.warn("[OS] No se pudo detectar el entorno Tauri, asumiendo Desktop",e)}},registerPlugin:e=>r(t=>{let n=e.id||e.manifest?.id;if(!n)return t;let i=new Map(t.plugins);i.set(n,e);let s=new Map(t.widgets);if((e.widgets||e.manifest?.widgets||[]).forEach(a=>{let l={...a,pluginId:n};s.set(l.id,l)}),e.onRegister)try{Promise.resolve(e.onRegister()).catch(a=>console.error(`[OS] Failed to async-register plugin ${n}:`,a))}catch(a){console.error(`[OS] Failed to sync-register plugin ${n}:`,a)}if(e.mount&&e.manifest&&typeof window<"u")try{e.mount({})}catch(a){console.error(`[OS] Failed to mount plugin ${n}`,a)}return{plugins:i,widgets:s}}),unregisterPlugin:e=>r(t=>{let n=new Map(t.plugins),i=n.get(e);if(i){let s=new Map(t.widgets);if((i.widgets||i.manifest?.widgets||[]).forEach(a=>s.delete(a.id)),i.onUnregister)try{Promise.resolve(i.onUnregister()).catch(a=>console.error(`[OS] Failed to async-unregister plugin ${e}:`,a))}catch(a){console.error(`[OS] Failed to sync-unregister plugin ${e}:`,a)}return n.delete(e),{plugins:n,widgets:s}}return t}),openTransientOverlay:e=>{let t=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Date.now().toString()+Math.random().toString(36).substring(2);return r(n=>({transientOverlays:[...n.transientOverlays,{...e,id:t}]})),t},closeTransientOverlay:e=>{r(t=>({transientOverlays:t.transientOverlays.filter(n=>n.id!==e)}))},setCommandPaletteOpen:e=>{r({isCommandPaletteOpen:e})},setForgeTerminalOpen:e=>{r({isForgeTerminalOpen:e})},setGodModePanelOpen:e=>{r({isGodModePanelOpen:e})},setMarketplaceOpen:e=>{r({isMarketplaceOpen:e})},setShortcutSettingsOpen:e=>{r({isShortcutSettingsOpen:e})},setLayout:e=>{if(typeof document<"u"&&"startViewTransition"in document){let t=document.startViewTransition(()=>{r({rootLayout:e})});t.ready&&t.ready.catch(()=>{}),t.finished&&t.finished.catch(()=>{}),t.updateCallbackDone&&t.updateCallbackDone.catch(()=>{})}else r({rootLayout:e})},addWorkspace:e=>{r(t=>t.workspaces.find(i=>i.id===e.id)?t:{workspaces:[...t.workspaces,e]})},setActiveWorkspace:e=>{r(t=>{let n=t.workspaces.find(i=>i.id===e);if(!n)return t;if(typeof document<"u"&&"startViewTransition"in document){let i=document.startViewTransition(()=>{r({rootLayout:n.layout,activeWorkspaceId:e})});return i.ready&&i.ready.catch(()=>{}),i.finished&&i.finished.catch(()=>{}),i.updateCallbackDone&&i.updateCallbackDone.catch(()=>{}),t}else return{rootLayout:n.layout,activeWorkspaceId:e}})},saveScene:e=>{r(t=>{if(!t.rootLayout)return t;let n=JSON.parse(JSON.stringify(t.rootLayout));return{savedScenes:{...t.savedScenes,[e]:n}}})},loadScene:e=>{r(t=>{let n=t.savedScenes[e];if(!n)return t;if(typeof document<"u"&&"startViewTransition"in document){let i=document.startViewTransition(()=>{r({rootLayout:JSON.parse(JSON.stringify(n))})});return i.ready&&i.ready.catch(()=>{}),i.finished&&i.finished.catch(()=>{}),i.updateCallbackDone&&i.updateCallbackDone.catch(()=>{}),t}else return{rootLayout:JSON.parse(JSON.stringify(n))}})},requestCapability:e=>{let t=[];return rt.getState().widgets.forEach(n=>{n.capabilities?.includes(e)&&t.push(n)}),t},openWidgetByCapability:(e,t)=>{let n=rt.getState(),i=n.requestCapability(e);if(i.length===0)return!1;let s=i[0],o=s.layoutConfig?.preferredZone||"overlay";return o==="overlay"?(n.openTransientOverlay({widgetId:s.id,position:{x:typeof window<"u"?window.innerWidth/2-200:100,y:typeof window<"u"?window.innerHeight/2-150:100,width:s.layoutConfig?.initialSize?.w||400,height:s.layoutConfig?.initialSize?.h||300},props:{context:{renderMode:t?.renderMode||"expanded",data:t?.data}}}),!0):(console.warn(`[Shell OS] Morphological view requested for capability ${e} in zone ${o}, but only 'overlay' is currently implemented for Intent-Based Registry.`),!1)}})));export*from"@decido/shell-auth";export*from"@decido/plugin-engine";import{create as r1}from"zustand";var yp="macia_mcp_servers",n1=()=>{try{let r=localStorage.getItem(yp);if(r){let e=JSON.parse(r);if(Array.isArray(e))return e}}catch(r){console.error("[McpStore] Failed to parse persisted MCP servers",r)}return[]},vp=r=>{try{localStorage.setItem(yp,JSON.stringify(r))}catch(e){console.error("[McpStore] Failed to persist MCP servers",e)}},wp=r1()(r=>({mcpServers:n1(),addMcpServer:e=>r(t=>{let n=[...t.mcpServers.filter(i=>i.name!==e.name),{...e,isConnected:!1}];return vp(n),{mcpServers:n}}),removeMcpServer:e=>r(t=>{let n=t.mcpServers.filter(i=>i.name!==e||i.isDefault);return vp(n),{mcpServers:n}}),setMcpServerStatus:(e,t)=>r(n=>({mcpServers:n.mcpServers.map(i=>i.name===e?{...i,isConnected:t}:i)}))}));import{create as i1}from"zustand";var Sp=i1((r,e)=>({isUpdating:!1,status:"idle",progress:0,downloadedBytes:0,totalBytes:0,version:null,error:null,setChecking:()=>r({status:"checking",error:null}),setDownloading:(t,n)=>r({isUpdating:!0,status:"downloading",version:t,totalBytes:n,downloadedBytes:0,progress:0}),updateProgress:t=>{let n=e().totalBytes,i=e().downloadedBytes+t,s=n>0?Math.min(Math.round(i/n*100),100):0;r({downloadedBytes:i,progress:s})},setInstalling:()=>r({status:"installing",progress:100}),setRebooting:()=>r({status:"rebooting"}),setError:t=>r({status:"error",error:t,isUpdating:!1}),reset:()=>r({isUpdating:!1,status:"idle",progress:0,downloadedBytes:0,totalBytes:0,version:null,error:null})}));import{createContext as s1,useContext as o1,useSyncExternalStore as a1}from"react";import{jsx as c1}from"react/jsx-runtime";var Kc=class{state={};listeners=new Set;set(e,t){this.state={...this.state,[e]:t},this.listeners.forEach(n=>n())}get(e,t){return e in this.state?this.state[e]:t}getSnapshot(){return this.state}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}},ga=new Map,Cp=s1(null);function kp({pluginId:r,children:e}){let t=rt(d=>d.plugins),n=rt(d=>d.openTransientOverlay),i=rt(d=>d.closeTransientOverlay);ga.has(r)||ga.set(r,new Kc);let s=ga.get(r),o=(d,u)=>{s.set(d,u)},a=(d,u)=>s.get(d,u),l=(d,u)=>{n({widgetId:d,position:u})},c={pluginId:r,pluginDetails:t.get(r),setContextState:o,getContextState:a,openOverlay:l,closeOverlay:i};return c1(Cp.Provider,{value:c,children:e})}function l1(){let r=o1(Cp);if(!r)throw new Error("usePluginContext must be used within a ShellPluginProvider. Only call this inside MaciaWidgets components.");return r}function VI(r,e){let t=l1(),n=ga.get(t.pluginId);if(!n)throw new Error("Plugin store not initialized");let i=a1(a=>n.subscribe(a),()=>n.getSnapshot()),s=r in i?i[r]:e;return[s,a=>{if(typeof a=="function"){let l=a;t.setContextState(r,l(s))}else t.setContextState(r,a)}]}import{probe as Np}from"@decido/logger";var qI={listeners:new Map,emit(r,e){let t=this.listeners.get(r)?.size??0;Np("eventbus.emit",{event:r,listenerCount:t},{level:"debug",context:{module:"shell",component:"EventBus"}}),this.listeners.get(r)?.forEach(n=>n(e))},subscribe(r,e){return this.listeners.has(r)||this.listeners.set(r,new Set),this.listeners.get(r).add(e),Np("eventbus.subscribe",{event:r,totalListeners:this.listeners.get(r).size},{level:"debug",context:{module:"shell",component:"EventBus"}}),()=>{let t=this.listeners.get(r);t&&t.delete(e)}}};var Ep=class{static async processQuery(e){let{plugins:t}=rt.getState(),n=[];t.forEach(i=>{i.intents&&n.push(...i.intents)});for(let i of n){let s=e.match(i.match.pattern);if(s){console.log(`[AIDirector] Intent Matched: ${i.name}`);try{return await i.handler(s),!0}catch(o){throw console.error(`[AIDirector] Error handling intent ${i.name}:`,o),o}}}return console.log(`[AIDirector] No specific intent matched for: "${e}". Delegating to general AI layer.`),await this.delegateToGeneralAI(e),!1}static getSuggestedIntents(){let{plugins:e}=rt.getState(),t=[];return e.forEach(n=>{n.intents&&n.intents.forEach(i=>{t.push({pluginName:n.name||n.manifest?.name||"Unknown Plugin",intentName:i.name,description:i.match.description,examples:i.match.examples||[]})})}),t}static async delegateToGeneralAI(e){console.log(`[AIDirector Fallback] Processing general request: ${e}`)}};import f1 from"react";import d1 from"react";import{AlertTriangle as u1,RefreshCw as h1}from"lucide-react";import{jsx as pi,jsxs as Yc}from"react/jsx-runtime";var rs=class extends d1.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error(`\u{1F6A8} [Plugin Error Boundary] Plugin ${this.props.pluginName||this.props.pluginId||"Unknown"} crashed:`,e,t)}resetBoundary=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError?Yc("div",{className:"w-full h-full flex flex-col items-center justify-center p-6 bg-red-950/10 border border-red-500/20 rounded-xl m-2 backdrop-blur-xs relative overflow-hidden",children:[pi("div",{className:"absolute top-0 left-0 w-full h-1 bg-linear-to-r from-red-500/50 to-orange-500/50"}),pi(u1,{className:"w-12 h-12 text-red-400 mb-4 opacity-80"}),pi("h3",{className:"text-lg font-bold text-red-200 mb-2 text-center text-balance",children:"Plugin Crashed"}),Yc("p",{className:"text-sm text-red-300/70 text-center mb-6 max-w-sm",children:["The plugin ",pi("span",{className:"text-red-200 font-mono bg-red-900/40 px-1 py-0.5 rounded",children:this.props.pluginName||this.props.pluginId||"unknown"})," encountered an unexpected runtime error. The core OS remains stable."]}),this.state.error&&pi("div",{className:"w-full bg-surface-overlay p-3 rounded-lg border border-red-900/30 mb-6 overflow-auto max-h-24",children:pi("code",{className:"text-xs text-red-400 font-mono whitespace-pre-wrap break-all",children:this.state.error.toString()})}),Yc("button",{onClick:this.resetBoundary,className:"flex items-center gap-2 px-4 py-2 bg-red-500/10 hover:bg-red-500/20 active:bg-red-500/30 text-red-300 border border-red-500/30 rounded-lg transition-colors text-sm font-medium",children:[pi(h1,{className:"w-4 h-4"}),"Reload Plugin"]})]}):this.props.children}};import{jsx as fr,jsxs as Ap}from"react/jsx-runtime";var p1=({node:r,isRoot:e=!1})=>{let t=rt(o=>o.rootLayout),n=rt(o=>o.widgets),i=r||(e?t:void 0);if(!i)return fr("div",{className:"flex-1 flex items-center justify-center text-text-primary/30 text-sm italic h-full w-full",children:"No active layout topology"});if(i.type==="widget"&&i.widgetId){let o=n.get(i.widgetId);if(!o)return Ap("div",{className:"text-red-500 p-4 bg-surface-glass",children:["Widget '",i.widgetId,"' not found."]});let a=o.component;return Ap("div",{className:"w-full h-full relative overflow-hidden bg-surface-overlay backdrop-blur-md border border-border-subtle rounded-2xl shadow-xl flex flex-col",children:[fr("div",{className:"flex-none px-4 py-2 border-b border-border-default bg-linear-to-r from-white/5 to-transparent",children:fr("span",{className:"text-xs font-semibold text-text-primary/70 uppercase tracking-wider",children:o.name})}),fr("div",{className:"flex-1 overflow-auto relative",children:fr(kp,{pluginId:o.pluginId,children:a?fr(rs,{pluginName:o.name,pluginId:o.pluginId,children:fr(f1.Suspense,{fallback:fr("div",{className:"text-text-primary/50 p-4 text-center",children:"Loading Remote Plugin..."}),children:fr(a,{...o.defaultProps||{}})})}):fr("div",{className:"text-text-primary/50 p-4 text-center",children:"Component Not Renderable"})})})]})}let s=i.type==="split-vertical";return fr("div",{className:`flex w-full h-full gap-4 ${s?"flex-col":"flex-row"}`,children:i.children?.map((o,a)=>fr("div",{className:"shrink grow",style:{flexBasis:o.size?`${o.size}%`:"auto"},children:fr(p1,{node:o})},o.id||a))})};import m1 from"react";import{jsx as Rn,jsxs as Tp}from"react/jsx-runtime";var hP=()=>{let r=rt(n=>n.transientOverlays),e=rt(n=>n.widgets),t=rt(n=>n.closeTransientOverlay);return r.length===0?null:Rn("div",{className:"fixed inset-0 z-100 pointer-events-none",children:r.map(n=>{let i=e.get(n.widgetId);if(!i)return null;let s=i.component,o=16,a=72,l=n.position.width||400,c=n.position.height||300,d=n.position.x,u=n.position.y;if(typeof window<"u"){let h=window.innerWidth-a-o,f=window.innerHeight-o*2;l>h&&(l=h),c>f&&(c=f);let p=window.innerWidth-l-o,m=window.innerHeight-c-o;d<a&&(d=a),d>p&&(d=p),u<o&&(u=o),u>m&&(u=m)}return Tp("div",{className:"absolute shadow-2xl rounded-2xl overflow-hidden glass-panel border border-border-default pointer-events-auto animate-in fade-in zoom-in-95 duration-200",style:{left:d,top:u,width:l,height:c},children:[Tp("div",{className:"flex justify-between items-center px-4 py-2 bg-surface-overlay border-b border-border-subtle backdrop-blur-md",children:[Rn("span",{className:"text-xs font-semibold text-text-primary/70",children:i.name}),Rn("button",{onClick:()=>t(n.id),className:"w-4 h-4 rounded-full bg-red-500/80 hover:bg-red-500 flex items-center justify-center transition-colors"})]}),Rn("div",{className:"p-4 bg-surface-overlay backdrop-blur-xl h-full w-full",children:s?Rn(rs,{pluginName:i.name,pluginId:i.pluginId,children:Rn(m1.Suspense,{fallback:Rn("div",{className:"text-text-primary/50 p-4 text-center",children:"Loading Floating Plugin..."}),children:Rn(s,{...i.defaultProps||{},...n.props||{}})})}):Rn("div",{className:"text-text-primary/50 text-center w-full h-full flex items-center justify-center",children:"No Component"})})]},n.id)})})};import g1,{useMemo as b1}from"react";import{kernel as Mp}from"@decido/kernel-bridge";import x1 from"clsx";import{twMerge as v1}from"tailwind-merge";import{jsx as Dp}from"react/jsx-runtime";var y1=["div","span","p","button","input","h1","h2","h3","h4","h5","h6","img","a","ul","ol","li","section","article","aside","header","footer","nav","main","figure","figcaption","blockquote","hr","br","b","i","u","s","em","strong","small","sub","sup","mark","del","ins","kbd","samp","var","code","pre","q","cite","dfn","abbr","time","address","ruby","rt","rp","bdi","bdo","wbr","table","caption","colgroup","col","tbody","thead","tfoot","tr","td","th"],w1=(...r)=>v1(x1(r)),vP=({uiSchema:r,missionData:e,tenantId:t})=>{let n=b1(()=>{if(!r)return null;if(typeof r=="object")return r;try{return JSON.parse(r)}catch(o){return console.error("[Server-Driven UI] Failed to parse schema:",o),null}},[r]),i=async(o,a)=>{try{await Mp.execute(t,o,{...a,__missionContext:e})}catch(l){console.error("[Server-Driven UI] RPC Execution Failed:",l),Mp.injectEvent({type:"system_alert",source:"SafeLiquidUI",payload:{level:"error",title:"Action Failed",message:String(l)}})}},s=(o,a)=>{if(typeof o=="string")return o;if(!o||!o.type)return null;let l=y1.includes(o.type)?o.type:"div",c={...o.props,key:a};if(c.className&&(c.className=w1(c.className)),o.onAction&&o.onAction.command){let u=l==="input"?"onChange":"onClick";c[u]=h=>{h&&typeof h.preventDefault=="function"&&(h.preventDefault(),h.stopPropagation());let f=h?.target?.value,p=f!==void 0?{...o.onAction?.payload,value:f}:o.onAction?.payload;i(o.onAction.command,p)}}let d=null;return Array.isArray(o.children)?d=o.children.map((u,h)=>s(u,h)):typeof o.children=="string"&&(d=o.children.replace(/\{\{\s*([a-zA-Z0-9_.]+)\s*\}\}/g,(u,h)=>{let f=h.split("."),p={missionData:e};for(let m of f)if(p&&typeof p=="object"&&m in p)p=p[m];else return u;return String(p)})),g1.createElement(l,c,d)};return n?Dp("div",{className:"w-full h-full overflow-y-auto custom-scrollbar",children:s(n)}):Dp("div",{className:"w-full h-full flex items-center justify-center bg-surface-primary/50 backdrop-blur border border-border-subtle rounded-xl p-8 text-text-muted font-mono text-xs",children:"Waiting for Server-Driven UI Schema..."})};import{useEffect as S1}from"react";import{useCommandRegistry as C1,useShortcutManager as k1}from"@decido/commands";var NP=()=>{let r=C1(t=>t.registerCommand),e=k1(t=>t.registerDefaultShortcut);S1(()=>{r({id:"shell.toggleCommandPalette",title:"Toggle Command Palette",category:"Shell",handler:()=>{let t=rt.getState();t.setCommandPaletteOpen(!t.isCommandPaletteOpen)}}),e("shell.toggleCommandPalette","$mod+k"),r({id:"shell.openShortcutSettings",title:"Configurar Atajos",category:"Shell",handler:()=>{let t=rt.getState();t.setShortcutSettingsOpen(!t.isShortcutSettingsOpen)}}),e("shell.openShortcutSettings","$mod+Shift+K"),r({id:"shell.toggleForgeTerminal",title:"Toggle Forge Terminal",category:"Shell",handler:()=>{let t=rt.getState();t.setForgeTerminalOpen(!t.isForgeTerminalOpen)}}),e("shell.toggleForgeTerminal","$mod+j"),r({id:"shell.toggleGodMode",title:"Toggle God Mode",category:"Shell",handler:()=>{let t=rt.getState();t.setGodModePanelOpen(!t.isGodModePanelOpen)}}),e("shell.toggleGodMode","$mod+Shift+D"),r({id:"shell.closePanels",title:"Close Active Panels",category:"Shell",handler:()=>{let t=rt.getState();t.isCommandPaletteOpen&&t.setCommandPaletteOpen(!1),t.isForgeTerminalOpen&&t.setForgeTerminalOpen(!1),t.isGodModePanelOpen&&t.setGodModePanelOpen(!1)}}),e("shell.closePanels","Escape")},[r,e])};import{useEffect as N1}from"react";import{ed25519 as E1}from"@noble/curves/ed25519.js";var MP=({setRemote:r,getRemote:e,registry:t,publicKeyB64:n,onPluginLoaded:i,onMCPServerDiscovered:s,onSecurityAlert:o,onSidebarItemsRegistered:a})=>{N1(()=>{let l=async(c,d,u,h)=>{try{if(h&&h!=="offline_or_invalid_signature"){console.info(`\u{1F512} [Security] Verifying Cryptographic Signature for ${c}...`);try{let g=await fetch(d);if(!g.ok)throw new Error("Could not fetch remote bundle for verification");let b=await g.text();if(!n){console.error(`\u{1F6A8} [Security Breach] No public key provided to verify ${c}. Halting execution.`),o&&o(c,"El host no provey\xF3 una llave p\xFAblica para verificar la firma criptogr\xE1fica.");return}let y=Uint8Array.from(atob(n),w=>w.charCodeAt(0)).slice(12),x=Uint8Array.from(atob(h),w=>w.charCodeAt(0)),N=new TextEncoder().encode(b);if(!E1.verify(x,N,y)){console.error(`\u{1F6A8} [Security Breach] Invalid signature for ${c}. Halting execution.`),o&&o(c,"El plugin ha sido modificado en tr\xE1nsito o no tiene firma v\xE1lida.");return}console.info(`\u2705 [Security] Signature verified for ${c}. Secure to execute.`)}catch(g){console.error(`\u{1F6A8} [Security] Failed to verify signature for ${c}:`,g),o&&o(c,"Fallo al verificar firma criptogr\xE1fica.");return}}else console.debug(`[Security] Loaded ${c} without a cryptographic signature (Local Dev Mode).`);r(c,{url:()=>Promise.resolve(`${d}?t=${Date.now()}`),format:"esm",from:"vite"});let f=async g=>g&&typeof g=="object"&&"default"in g?g.default:g,p=(g,b)=>{g&&g.widgets?(console.info(`\u{1F525} [Federation Marketplace] Registering Cortex: ${b} with ${g.widgets.length} widgets`),g.widgets=g.widgets.map(y=>{let x=y.component;if(x&&typeof x=="object"&&!x.$$typeof)try{let N=Object.keys(x);N.length>0&&typeof x[N[0]]=="function"?x=x[N[0]]:x.default&&(x=x.default)}catch(N){console.warn(`[Federation Marketplace] TDZ / Getter Exception unpacking component for ${y.name}:`,N)}return{...y,component:x}}),i(g,b),g.mcp_servers&&Array.isArray(g.mcp_servers)&&(console.info(`\u{1F50C} [Dynamic MCP] Discovered ${g.mcp_servers.length} MCP Servers in ${b}.`),s&&g.mcp_servers.forEach(y=>{s(y)})),g.sidebarItems&&Array.isArray(g.sidebarItems)&&a&&(console.info(`\u{1F4CC} [Sidebar] ${b} registered ${g.sidebarItems.length} sidebar items`),a(g.id||b,g.sidebarItems))):console.warn(`\u26A0\uFE0F [Federation Marketplace] Manifest ${b} is invalid or has no widgets`,g)},m=async g=>{try{let b=await e(c,u),y=await f(b);y.id&&y.widgets?(console.log(`[Plugin Injector] Setup Root Cortex: ${y.name}`),p(y,y.name)):y.default&&y.default.id&&y.default.widgets?(console.log(`[Plugin Injector] Setup Default Cortex: ${y.default.name}`),p(y.default,y.default.name)):(console.warn("[Plugin Injector] No raw CORTEX structure found at root, checking legacy namespaces..."),y.PlantaErpPlugin&&p(y.PlantaErpPlugin,"PlantaErpPlugin"),y.FrubealaUiPlugin&&p(y.FrubealaUiPlugin,"FrubealaUiPlugin"),y.ForgeCortex&&p(y.ForgeCortex,"ForgeCortex"),y.CommanderCortex&&p(y.CommanderCortex,"CommanderCortex"),y.BridgeCortex&&p(y.BridgeCortex,"BridgeCortex"))}catch(b){b instanceof ReferenceError&&g>0?(console.warn(`\u23F3 [Plugin Engine] TDZ ReferenceError dynamically loading ${c}, waiting 100ms... (${g} left)`),await new Promise(y=>setTimeout(y,100)),await m(g-1)):console.error(`\u274C [Federation Marketplace] Could not load Remote ${c} from ${d}:`,b)}};await m(10)}catch(f){console.error(`\u274C [Federation Marketplace] execution error resolving Remote ${c} from ${d}:`,f)}};for(let c of t)c.enabled&&c.url&&c.exposedModule&&l(c.name,c.url,c.exposedModule,c.signature)},[t,r,e,n,i,s,o,a])};import{useEffect as T1,useState as Jc}from"react";import{kernel as Xc,StateRehydrationManager as M1}from"@decido/kernel-bridge";import{initPluginSecurityManager as D1}from"@decido/plugin-engine";import{useEffect as A1}from"react";import{kernel as Op}from"@decido/kernel-bridge";var Rp=()=>{A1(()=>{if(import.meta.env?.VITE_DECIDO_SAFE_MODE==="1"){console.log("\u{1F6E1}\uFE0F [Telemetry] Performance tracking disabled in Safe Mode");return}try{if("PerformanceObserver"in window){let r=new PerformanceObserver(t=>{for(let n of t.getEntries())n.duration>250&&(console.warn(`\u26A0\uFE0F [Telemetry] Long task detected! UI blocked for ${n.duration.toFixed(0)}ms`,n),Op.injectEvent({type:"system_alert",source:"telemetry_engine",payload:{level:"warning",title:"Performance Degradation",message:`A plugin or core component blocked the main thread for ${n.duration.toFixed(0)}ms.`,duration:n.duration}}))});r.observe({entryTypes:["longtask"]});let e=setInterval(()=>{let t=performance.memory;t&&t.usedJSHeapSize>t.jsHeapSizeLimit*.9&&(console.error("\u{1F6A8} [Telemetry] Critical Memory Warning! Heap > 90%"),Op.injectEvent({type:"system_alert",source:"telemetry_engine",payload:{level:"error",title:"Critical Memory Exhaustion",message:`V8 JS Heap is critically high (${(t.usedJSHeapSize/1024/1024).toFixed(0)}MB). The application might crash soon. Consider restarting plugins.`}}))},3e4);return()=>{r.disconnect(),clearInterval(e)}}}catch(r){console.warn("[Telemetry] PerformanceObserver not fully supported on this platform",r)}},[])};var _P=({availableInstances:r=[],onAutoConnect:e})=>{let[t,n]=Jc(!1),[i,s]=Jc(!1),[o,a]=Jc(null);return Rp(),T1(()=>{let l=D1();return(async()=>{try{let d=await Xc.execute("get_settings").catch(()=>({})),u=import.meta.env?.VITE_APP_VERSION||"1.0.0",h=localStorage.getItem("decido_app_version");if(h!==u&&(console.warn(`[Boot] Version mismatch detected (${h} -> ${u}). Purgando cach\xE9 para UI Refresh.`),await Xc.execute("save_settings",{config:{gemini_api_key:d?.gemini_api_key||"",qdrant_url:d?.qdrant_url||"http://localhost:6334",qdrant_api_key:d?.qdrant_api_key||"",swarm_key:d?.swarm_key||null,setup_completed:!1,selected_instance_id:null}}),localStorage.setItem("decido_app_version",u),d.setup_completed=!1,d.selected_instance_id=null),d.setup_completed&&d.swarm_key&&await M1.rehydrate(d.swarm_key),d.setup_completed&&d.selected_instance_id){let f=r.find(p=>p.id===d.selected_instance_id);f&&(a(f),s(!0),e?e(f):Xc.execute("connect_to_swarm",{redisUrl:f.ip}).catch(p=>{console.error("[Boot] Failed to auto-reconnect swarm:",p)}))}}catch(d){console.error("[Boot] Error during rehydration:",d)}finally{n(!0)}})(),()=>{l()}},[r,e]),{isRehydrated:t,setupComplete:i,setSetupComplete:s,selectedInstance:o,setSelectedInstance:a}};import{useEffect as O1}from"react";import{kernel as R1}from"@decido/kernel-bridge";var VP=({appName:r="Decido OS",onUpdateAvailable:e,onUpdateFinished:t,delayMs:n=4e3}={})=>{let i=Sp();O1(()=>{setTimeout(async()=>{if(!("__TAURI_INTERNALS__"in window)){console.info("[Updater] Ejecuci\xF3n en navegador detectada. Saltando buscar OTA de Tauri.");return}try{i.setChecking();let a=await(await import("@tauri-apps/plugin-updater")).check();if(a){console.info(`[Updater] Nueva versi\xF3n encontrada: ${a.version} (${a.date})`),e?e(a.version,a.date):R1.notify("\u{1F680} Actualizaci\xF3n Disponible",`Descargando silenci\xF3samente la versi\xF3n ${a.version}...`);let l=0,c=0;await a.downloadAndInstall(d=>{switch(d.event){case"Started":c=d.data.contentLength,i.setDownloading(a.version,c);break;case"Progress":i.updateProgress(d.data.chunkLength);break;case"Finished":console.info("[Updater] Descarga completada. Preparando reinicio."),i.setInstalling();break}}),t?t():(i.setRebooting(),setTimeout(async()=>{(await import("@tauri-apps/plugin-process")).relaunch()},3e3))}else i.reset()}catch(o){let a=o?.toString()||"";a.includes("url")||a.includes("404")||a.includes("offline")||a.includes("Could not fetch")||a.includes("fetch")||a.includes("network")||a.includes("ECONNREFUSED")?(console.info("[Updater] OTA no disponible \u2014 modo local/offline."),i.reset()):(console.error("[Updater] Fall\xF3 el escaneo de actualizaciones:",o),i.setError(a))}},n)},[r,e,t,n])};var mi=[];function Ip(r,e){mi.find(t=>t.name===r)||mi.push({name:r,store:e}),typeof window<"u"&&(window.__ZUSTAND_STORES__=window.__ZUSTAND_STORES__||{},window.__ZUSTAND_STORES__[r]=e)}function I1(){if(typeof window>"u"||window.__BRIDGE_AGENT__)return;console.log("[BridgeAgent] Initializing postMessage bridge v1.0...");let r=(l,c,d,u)=>{if(!(!c||!l))try{l.postMessage({jsonrpc:"2.0",id:c,result:d,error:u||null},"*")}catch{}},e=(l,c,d)=>{try{l.postMessage({jsonrpc:"2.0",method:c,params:d},"*")}catch{}},t=(l,c=0)=>{if(c>4)return"[max depth]";if(l==null)return l;if(typeof l=="function")return"[Function]";if(typeof l!="object")return l;if(Array.isArray(l))return l.slice(0,50).map(u=>t(u,c+1));if(l instanceof Map)return Object.fromEntries(Array.from(l.entries()).slice(0,50).map(([u,h])=>[String(u),t(h,c+1)]));if(l instanceof Set)return Array.from(l).slice(0,50).map(u=>t(u,c+1));let d={};for(let u of Object.keys(l).slice(0,100))d[u]=t(l[u],c+1);return d},n=l=>{if(l.id)return`#${l.id}`;let c=[],d=l;for(;d&&d!==document.body;){let u=d.tagName.toLowerCase();if(d.id){c.unshift(`#${d.id}`);break}if(d.className&&typeof d.className=="string"){let f=d.className.trim().split(/\s+/).filter(p=>!p.includes("/")).slice(0,2).join(".");f&&(u+=`.${f}`)}let h=d.parentElement;if(h){let f=Array.from(h.children).filter(p=>p.tagName===d.tagName);f.length>1&&(u+=`:nth-of-type(${f.indexOf(d)+1})`)}c.unshift(u),d=d.parentElement}return c.join(" > ")},i=!1,s=null,o=null,a=async l=>{let c=l.data;if(!c||c.jsonrpc!=="2.0"||!c.method)return;let{method:d,params:u,id:h}=c,f=l.source;try{switch(d){case"PING":case"HANDSHAKE":{r(f,h,{success:!0,version:"1.0.0",stores:mi.map(p=>p.name),url:window.location.href,title:document.title});break}case"CLICK":{let p=document.querySelector(u.selector);if(!p)throw new Error(`Element not found: ${u.selector}`);p.click(),p.focus?.(),r(f,h,{success:!0});break}case"DBLCLICK":{let p=document.querySelector(u.selector);if(!p)throw new Error(`Element not found: ${u.selector}`);p.dispatchEvent(new MouseEvent("dblclick",{bubbles:!0})),r(f,h,{success:!0});break}case"TYPE":{let p=document.querySelector(u.selector);if(!p)throw new Error(`Element not found: ${u.selector}`);p.focus();let m=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value")?.set||Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value")?.set;m?m.call(p,u.value||""):p.value=u.value||"",p.dispatchEvent(new Event("input",{bubbles:!0})),p.dispatchEvent(new Event("change",{bubbles:!0})),r(f,h,{success:!0});break}case"CLEAR":{let p=document.querySelector(u.selector);if(!p)throw new Error(`Element not found: ${u.selector}`);p.value="",p.dispatchEvent(new Event("input",{bubbles:!0})),r(f,h,{success:!0});break}case"SELECT":{let p=document.querySelector(u.selector);if(!p)throw new Error(`Element not found: ${u.selector}`);p.value=u.value||"",p.dispatchEvent(new Event("change",{bubbles:!0})),r(f,h,{success:!0});break}case"HOVER":{let p=document.querySelector(u.selector);if(!p)throw new Error(`Element not found: ${u.selector}`);p.dispatchEvent(new MouseEvent("mouseenter",{bubbles:!0})),p.dispatchEvent(new MouseEvent("mouseover",{bubbles:!0})),r(f,h,{success:!0});break}case"FOCUS":{let p=document.querySelector(u.selector);if(!p)throw new Error(`Element not found: ${u.selector}`);p.focus(),r(f,h,{success:!0});break}case"SCROLL":{u.selector?document.querySelector(u.selector)?.scrollIntoView({behavior:"smooth",block:"center"}):window.scrollTo({top:u.y||0,left:u.x||0,behavior:"smooth"}),r(f,h,{success:!0});break}case"KEYDOWN":case"KEYUP":case"KEYPRESS":{(u.selector?document.querySelector(u.selector):document.activeElement||document.body)?.dispatchEvent(new KeyboardEvent(d.toLowerCase(),{key:u.key,bubbles:!0})),r(f,h,{success:!0});break}case"NAVIGATE":{window.location.href=u.url||u.value||"/",r(f,h,{success:!0});break}case"RELOAD":{window.location.reload(),r(f,h,{success:!0});break}case"BACK":{window.history.back(),r(f,h,{success:!0});break}case"WAIT_FOR":{let p=u.timeout||5e3,m=Date.now(),g=()=>{document.querySelector(u.selector)?r(f,h,{success:!0}):Date.now()-m>p?r(f,h,null,{code:408,message:`Timeout waiting for: ${u.selector}`}):setTimeout(g,100)};g();break}case"ASSERT_EXISTS":{if(!document.querySelector(u.selector))throw new Error(`Assert failed: ${u.selector} not found`);r(f,h,{success:!0});break}case"ASSERT_TEXT":{let p=document.querySelector(u.selector);if(!p)throw new Error(`Assert failed: ${u.selector} not found`);let m=p.textContent?.trim();if(m!==u.expected&&m!==u.value)throw new Error(`Assert failed: expected "${u.expected||u.value}", got "${m}"`);r(f,h,{success:!0,text:m});break}case"ASSERT_VISIBLE":{let p=document.querySelector(u.selector);if(!p)throw new Error(`Assert failed: ${u.selector} not found`);let m=window.getComputedStyle(p);if(m.display==="none"||m.visibility==="hidden"||m.opacity==="0")throw new Error(`Assert failed: ${u.selector} not visible`);r(f,h,{success:!0});break}case"STORE_LIST":{let p=mi.map(m=>{let g=m.store.getState(),b=Object.keys(g).filter(y=>typeof g[y]=="function");return{name:m.name,keys:Object.keys(g).length,methods:b.length}});r(f,h,{success:!0,stores:p});break}case"STORE_READ":{let p=mi.find(y=>y.name===u.store||y.name===u.storeName);if(!p)throw new Error(`Store not found: ${u.store||u.storeName}`);let m=p.store.getState(),g=Object.keys(m).filter(y=>typeof m[y]=="function"),b=m;u.path&&(b=u.path.split(".").reduce((y,x)=>y?.[x],m)),r(f,h,{success:!0,name:p.name,state:t(m),methods:g,value:u.path?t(b):void 0});break}case"STORE_WRITE":{let p=mi.find(g=>g.name===u.store||g.name===u.storeName);if(!p)throw new Error(`Store not found: ${u.store||u.storeName}`);let m=(u.path||"").split(".").filter(Boolean);if(m.length===0)throw new Error("Store path required");if(m.length===1)p.store.setState({[m[0]]:JSON.parse(u.value)});else{let g={...p.store.getState()},b=g;for(let y=0;y<m.length-1;y++)b=b[m[y]];b[m[m.length-1]]=JSON.parse(u.value),p.store.setState(g)}r(f,h,{success:!0});break}case"GET_HTML":{let p=document.querySelector(u.selector);r(f,h,{success:!0,html:p?.outerHTML||""});break}case"GET_COMPUTED_STYLE":{let p=document.querySelector(u.selector);if(!p)throw new Error(`Element not found: ${u.selector}`);let m=window.getComputedStyle(p),g=u.property||u.key?m.getPropertyValue(u.property||u.key):void 0;r(f,h,{success:!0,value:g});break}case"GET_INFO":{r(f,h,{success:!0,title:document.title,url:window.location.href,buttons:document.querySelectorAll("button").length,inputs:document.querySelectorAll("input").length,links:document.querySelectorAll("a").length});break}case"EVAL":{let p=window.eval(u.code);r(f,h,{success:!0,result:t(p)});break}case"RECORD_START":{if(i){r(f,h,{success:!1,error:"Already recording"});break}i=!0,o=f;let p=y=>{let x=y.target;x&&e(o,"bridge.recorded",{type:"click",selector:n(x),tagName:x.tagName,id:x.id,textContent:(x.textContent||"").slice(0,50),timestamp:Date.now()})},m=y=>{let x=y.target;!x||!["INPUT","TEXTAREA","SELECT"].includes(x.tagName)||e(o,"bridge.recorded",{type:x.tagName==="SELECT"?"select":"type",selector:n(x),value:x.value,tagName:x.tagName,timestamp:Date.now()})},g,b=()=>{clearTimeout(g),g=setTimeout(()=>{e(o,"bridge.recorded",{type:"scroll",x:window.scrollX,y:window.scrollY,timestamp:Date.now()})},300)};document.addEventListener("click",p,!0),document.addEventListener("input",m,!0),document.addEventListener("change",m,!0),window.addEventListener("scroll",b,!0),s=()=>{document.removeEventListener("click",p,!0),document.removeEventListener("input",m,!0),document.removeEventListener("change",m,!0),window.removeEventListener("scroll",b,!0)},r(f,h,{success:!0});break}case"RECORD_STOP":{s&&s(),i=!1,s=null,o=null,r(f,h,{success:!0});break}default:r(f,h,null,{code:-32601,message:`Unknown method: ${d}`})}}catch(p){r(f,h,null,{code:500,message:p.message||String(p)})}};window.addEventListener("message",a),window.__BRIDGE_AGENT__={version:"1.0.0",storeRegistry:mi,registerStore:Ip,destroy:()=>window.removeEventListener("message",a)},console.log("[BridgeAgent] Ready \u2014 listening for postMessage commands")}import{useState as Ys,useEffect as P1}from"react";import{usePluginStore as Js}from"@decido/plugin-engine";import{Trash2 as L1,Power as B1,Puzzle as Pp,Code as Lp,RefreshCcw as F1,DownloadCloud as _1,AlertCircle as z1,LayoutDashboard as $1,ChevronLeft as H1,Info as W1,Box as Zc}from"lucide-react";import{jsx as pe,jsxs as de}from"react/jsx-runtime";var JP=()=>{let r=Js(b=>b.registry),e=Js(b=>b.availablePlugins),t=Js(b=>b.addRegistryEntry),n=Js(b=>b.removeRegistryEntry),i=Js(b=>b.toggleRegistryEntry),[s,o]=Ys([]),[a,l]=Ys(!0),[c,d]=Ys(null),[u,h]=Ys(!1),[f,p]=Ys(null);P1(()=>{(async()=>{try{l(!0);let y=import.meta.env?.VITE_MARKETPLACE_URL||"http://localhost:5010/api/marketplace",x=await fetch(`${y}/catalog`);if(!x.ok)throw new Error("Catalog request failed");let N=await x.json();o(N),d(null)}catch(y){d(y.message||"Failed to connect to Decido Hub")}finally{l(!1)}})()},[]);let m=b=>{t({name:b.name,url:b.url,exposedModule:b.exposedModule,signature:b.signature})},g=b=>r.some(y=>y.name===b);return de("div",{className:"w-full h-full flex flex-col bg-surface-primary text-text-primary font-sans overflow-hidden border-r border-border-subtle",children:[de("div",{className:"p-4 border-b border-border-subtle bg-surface-secondary/50 flex justify-between items-center shrink-0",children:[de("div",{className:"flex items-center gap-2",children:[pe(Pp,{className:"w-5 h-5 text-cyan-400"}),pe("h2",{className:"font-bold text-sm tracking-wide",children:"Decido Hub"})]}),de("div",{className:"flex bg-surface-primary p-1 rounded-lg border border-border-subtle",children:[pe("button",{onClick:()=>{h(!1),p(null)},className:`px-3 py-1 text-xs rounded-md transition-colors ${u?"text-text-muted hover:text-text-primary":"bg-cyan-500/20 text-cyan-400"}`,children:"Installed"}),de("button",{onClick:()=>{h(!0),p(null)},className:`px-3 py-1 flex items-center gap-1 text-xs rounded-md transition-colors ${u?"bg-cyan-500/20 text-cyan-400":"text-text-muted hover:text-text-primary"}`,children:[pe(_1,{className:"w-3 h-3"})," Catalog"]})]})]}),de("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[!f&&!u&&de("div",{className:"bg-cyan-500/10 border border-cyan-500/20 p-3 rounded-lg flex items-start gap-3",children:[pe(F1,{className:"w-4 h-4 text-cyan-400 shrink-0 mt-0.5"}),pe("p",{className:"text-xs text-cyan-200/70 leading-relaxed",children:"Changes to the Federation Registry require a hard reload to apply securely to the OS Kernel context. (cmd+R)"})]}),f&&de("div",{className:"space-y-4 animate-in fade-in slide-in-from-right-4 duration-300",children:[de("button",{onClick:()=>p(null),className:"flex items-center gap-1 text-xs text-text-secondary hover:text-text-primary transition-colors mb-2",children:[pe(H1,{className:"w-4 h-4"})," Volver"]}),de("div",{className:"flex items-start gap-4 pb-4 border-b border-border-subtle",children:[pe("div",{className:"w-16 h-16 rounded-2xl bg-linear-to-br from-cyan-500/20 to-blue-500/20 border border-cyan-500/30 flex items-center justify-center shrink-0",children:pe(Zc,{className:"w-8 h-8 text-cyan-400"})}),de("div",{className:"flex-1",children:[pe("h2",{className:"text-xl font-bold text-text-primary mb-1",children:f.title||f.name}),de("p",{className:"text-sm text-cyan-400 font-mono mb-2",children:[f.author||"Decido Publisher"," \u2022 v",f.version||"1.0.0"]}),g(f.name)?de("div",{className:"flex items-center gap-2",children:[de("span",{className:"bg-emerald-500/10 text-emerald-400 text-xs px-3 py-1.5 rounded-full font-medium flex items-center gap-1",children:[pe("div",{className:"w-2 h-2 rounded-full bg-emerald-400 animate-pulse"}),"Installed"]}),pe("button",{onClick:()=>n(f.name),className:"bg-surface-tertiary hover:bg-red-500/20 hover:text-red-400 text-text-primary text-xs px-3 py-1.5 rounded transition-colors",children:"Uninstall"})]}):pe("button",{onClick:()=>m(f),className:"bg-cyan-600 hover:bg-cyan-500 text-text-primary text-sm px-6 py-2 rounded-lg transition-colors shadow-lg shadow-cyan-500/20 font-medium",children:"Install Plugin"})]})]}),de("div",{className:"space-y-6 pt-2",children:[de("div",{children:[de("h3",{className:"text-sm font-semibold text-text-primary mb-2 flex items-center gap-2",children:[pe(W1,{className:"w-4 h-4 text-text-muted"})," General Description"]}),pe("p",{className:"text-sm text-text-secondary leading-relaxed bg-surface-glass p-4 rounded-xl border border-border-subtle/50",children:f.description||"No README.md currently available for this plugin. This is a technical expansion module for Decido OS."})]}),(()=>{let b=e.find(y=>y.id===f.name||y.name===f.name);return b?de("div",{className:"space-y-4",children:[b.widgets&&b.widgets.length>0&&de("div",{children:[de("h3",{className:"text-sm font-semibold text-text-primary mb-2 flex items-center gap-2",children:[pe($1,{className:"w-4 h-4 text-cyan-400"})," Provisioned Widgets"]}),pe("div",{className:"grid gap-2",children:b.widgets.map(y=>de("div",{className:"bg-surface-secondary border border-border-subtle p-3 rounded-lg flex items-center justify-between",children:[de("div",{className:"flex flex-col",children:[pe("span",{className:"text-sm font-medium text-text-primary",children:y.name}),de("span",{className:"text-xs text-text-muted font-mono",children:["ID: ",y.id]})]}),de("span",{className:"text-xs bg-surface-primary text-emerald-400/80 border border-emerald-500/20 px-2 py-1 rounded",children:["Zone: ",y.defaultZone]})]},y.id))})]}),b.intents&&b.intents.length>0&&de("div",{children:[de("h3",{className:"text-sm font-semibold text-text-primary mb-2 flex items-center gap-2",children:[pe(Lp,{className:"w-4 h-4 text-purple-400"})," Registered AI Intents"]}),pe("div",{className:"bg-surface-secondary border border-border-subtle rounded-lg p-3 flex flex-wrap gap-2",children:b.intents.map(y=>de("span",{className:"bg-surface-primary text-purple-400/90 text-xs px-2 py-1 rounded border border-purple-500/20 font-mono",children:['"',y,'"']},y))})]})]}):pe("div",{className:"text-xs text-text-muted italic bg-surface-glass p-4 rounded-xl border border-border-subtle/30 text-center",children:"Install and activate this plugin to view its provided Architecture bounds (Widgets & Intents)."})})()]})]}),!f&&u&&de("div",{className:"space-y-4",children:[a&&pe("div",{className:"text-xs text-text-muted text-center py-8 animate-pulse",children:"Connecting to Decido Hub..."}),c&&de("div",{className:"bg-red-500/10 border border-red-500/20 p-4 rounded-xl flex items-center gap-3 text-red-400 text-xs",children:[pe(z1,{className:"w-4 h-4"})," ",c]}),!a&&!c&&s.map(b=>{let y=g(b.name);return de("div",{onClick:()=>p(b),className:"bg-surface-secondary border border-border-subtle hover:border-cyan-500/30 focus:border-cyan-500/30 cursor-pointer p-4 rounded-xl flex flex-col gap-3 transition-colors group",children:[de("div",{className:"flex justify-between items-start",children:[de("div",{className:"flex gap-3 items-center",children:[pe("div",{className:"w-10 h-10 rounded-lg bg-surface-primary border border-border-subtle flex items-center justify-center group-hover:border-cyan-500/30 transition-colors",children:pe(Zc,{className:"w-5 h-5 text-text-muted group-hover:text-cyan-400 transition-colors"})}),de("div",{children:[pe("h3",{className:"font-bold text-sm text-text-primary group-hover:text-cyan-300 transition-colors",children:b.title}),de("p",{className:"text-xs text-text-muted font-mono mt-0.5",children:[b.author," \u2022 v",b.version]})]})]}),y&&pe("span",{className:"bg-emerald-500/10 text-emerald-400 text-[10px] px-2 py-1 rounded-full uppercase font-bold tracking-wider",children:"Installed"})]}),pe("p",{className:"text-xs text-text-secondary leading-relaxed border-l-2 border-border-subtle pl-2 line-clamp-2",children:b.description}),de("div",{className:"flex gap-2 mt-1",children:[pe("button",{className:"text-[10px] text-text-secondary hover:text-text-primary bg-surface-glass px-2 py-1 rounded uppercase font-bold tracking-wide",children:"Details"}),b.tags?.map(x=>pe("span",{className:"text-[10px] bg-surface-primary text-text-muted px-2 py-1 rounded-full border border-border-subtle",children:x},x))]})]},b.id)})]}),!f&&!u&&de("div",{className:"space-y-3",children:[r.map(b=>de("div",{onClick:()=>p(b),className:`bg-surface-secondary border ${b.enabled?"border-border-default/50":"border-border-subtle opacity-60"} hover:border-cyan-500/30 cursor-pointer p-4 rounded-xl transition-all group`,children:[de("div",{className:"flex justify-between items-start mb-2",children:[de("div",{className:"flex items-center gap-3",children:[pe("div",{className:"w-10 h-10 rounded-lg bg-surface-primary border border-border-subtle flex items-center justify-center group-hover:border-cyan-500/30 transition-colors",children:pe(Zc,{className:"w-5 h-5 text-text-muted group-hover:text-cyan-400 transition-colors"})}),de("div",{children:[de("div",{className:"flex items-center gap-2",children:[pe("div",{className:`w-2 h-2 rounded-full ${b.enabled?"bg-emerald-400 shadow-[0_0_8px_rgba(52,211,153,0.5)]":"bg-surface-elevated"}`}),pe("h3",{className:"font-bold text-sm tracking-wide text-text-primary group-hover:text-cyan-300 transition-colors",children:b.name})]}),de("div",{className:"text-xs font-mono text-text-muted mt-1",children:["module: ",pe("span",{className:"text-cyan-300/80",children:b.exposedModule})]})]})]}),de("div",{className:"flex items-center gap-1",onClick:y=>y.stopPropagation(),children:[pe("button",{onClick:()=>i(b.name),className:`w-7 h-7 flex items-center justify-center rounded transition-colors ${b.enabled?"text-emerald-400 hover:bg-emerald-400/10":"text-text-muted hover:bg-surface-tertiary"}`,title:b.enabled?"Disable Plugin":"Enable Plugin",children:pe(B1,{className:"w-4 h-4"})}),pe("button",{onClick:()=>n(b.name),className:"w-7 h-7 flex items-center justify-center rounded transition-colors text-text-muted hover:bg-red-500/20 hover:text-red-400",title:"Uninstall Plugin",children:pe(L1,{className:"w-4 h-4"})})]})]}),de("div",{className:"bg-surface-glass p-2 border border-border-subtle/50 rounded flex gap-2 items-center mt-3",children:[pe(Lp,{className:"w-3.5 h-3.5 text-text-muted shrink-0"}),pe("span",{className:"font-mono text-[10px] text-text-secondary truncate",title:b.url,children:b.url})]})]},b.name)),r.length===0&&de("div",{className:"text-center py-12 text-text-muted text-sm",children:[pe(Pp,{className:"w-8 h-8 mx-auto text-text-muted mb-3"}),"No local modules installed.",pe("br",{}),pe("button",{onClick:()=>h(!0),className:"mt-3 text-cyan-400 hover:text-cyan-300 underline underline-offset-4 decoration-zinc-800",children:"Browse Decido Hub"})]})]})]})]})};import{useState as ba}from"react";import{Send as V1,Megaphone as j1}from"lucide-react";import{Fragment as U1,jsx as Yt,jsxs as mn}from"react/jsx-runtime";var Bp=()=>{let[r,e]=ba(""),[t,n]=ba("INFO"),[i,s]=ba("NONE"),[o,a]=ba(!1);return mn("div",{className:"bg-surface-tertiary rounded-xl border border-border-default p-6 shadow-lg",children:[mn("h3",{className:"text-lg font-bold text-text-primary mb-4 flex items-center gap-2",children:[Yt(j1,{size:20,className:"text-purple-400"})," Broadcast Center"]}),mn("div",{className:"space-y-4",children:[mn("div",{children:[Yt("label",{className:"block text-xs font-bold text-text-secondary mb-1",children:"Message"}),Yt("input",{type:"text",value:r,onChange:c=>e(c.target.value),placeholder:"e.g. System maintenance in 5 minutes",className:"w-full bg-surface-secondary border border-border-default rounded-lg p-3 text-text-primary focus:border-purple-500 outline-hidden"})]}),mn("div",{className:"grid grid-cols-2 gap-4",children:[mn("div",{children:[Yt("label",{className:"block text-xs font-bold text-text-secondary mb-1",children:"Alert Type"}),mn("select",{value:t,onChange:c=>n(c.target.value),className:"w-full bg-surface-secondary border border-border-default rounded-lg p-3 text-text-primary outline-hidden",children:[Yt("option",{value:"INFO",children:"Info (Blue)"}),Yt("option",{value:"WARNING",children:"Warning (Orange)"}),Yt("option",{value:"CRITICAL",children:"Critical (Red)"}),Yt("option",{value:"SUCCESS",children:"Success (Green)"})]})]}),mn("div",{children:[Yt("label",{className:"block text-xs font-bold text-text-secondary mb-1",children:"Forced Action"}),mn("select",{value:i,onChange:c=>s(c.target.value),className:"w-full bg-surface-secondary border border-border-default rounded-lg p-3 text-text-primary outline-hidden",children:[Yt("option",{value:"NONE",children:"None"}),Yt("option",{value:"RELOAD",children:"Force Reload"}),Yt("option",{value:"LINK",children:"Open Link"})]})]})]}),Yt("div",{className:"pt-2",children:Yt("button",{onClick:async()=>{if(r){a(!0);try{let c=import.meta.env?.VITE_API_URL||"http://localhost:3001/api";await fetch(`${c}/admin/broadcast`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:r,type:t,action:i==="NONE"?void 0:i})}),alert("Broadcast Sent!"),e("")}catch(c){console.error(c),alert("Error sending broadcast")}finally{a(!1)}}},disabled:o||!r,className:"w-full py-3 bg-purple-600 hover:bg-purple-500 disabled:opacity-50 disabled:bg-surface-elevated text-text-primary font-bold rounded-lg transition-colors flex items-center justify-center gap-2",children:o?"Sending...":mn(U1,{children:[Yt(V1,{size:18})," Broadcast Now"]})})})]})]})};import{RefreshCw as G1,Zap as q1,ShieldAlert as K1}from"lucide-react";import{jsx as Xs,jsxs as Zs}from"react/jsx-runtime";var Fp=()=>{let r=async e=>{if(confirm("Are you sure you want to execute this global action?"))try{let t=import.meta.env?.VITE_API_URL||"http://localhost:3001/api";e==="FORCE_RELOAD"?await fetch(`${t}/admin/broadcast`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:"System Integrity Check: Reloading...",type:"WARNING",action:"RELOAD"})}):e==="CLEAR_ALERTS"&&await fetch(`${t}/admin/broadcast`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({message:"System Normal",type:"SUCCESS"})})}catch{alert("Action Failed")}};return Zs("div",{className:"bg-surface-tertiary rounded-xl border border-border-default p-6 shadow-lg",children:[Zs("h3",{className:"text-lg font-bold text-text-primary mb-4 flex items-center gap-2",children:[Xs(K1,{size:20,className:"text-red-400"})," Panic Room"]}),Zs("div",{className:"grid grid-cols-2 gap-3",children:[Zs("button",{onClick:()=>r("FORCE_RELOAD"),className:"flex flex-col items-center justify-center p-4 bg-red-900/20 hover:bg-red-900/40 border border-red-800/50 rounded-lg transition-colors group",children:[Xs(G1,{size:24,className:"text-red-500 mb-2 group-hover:rotate-180 transition-transform duration-500"}),Xs("span",{className:"text-xs font-bold text-red-400",children:"Force Reload All"})]}),Zs("button",{onClick:()=>r("CLEAR_ALERTS"),className:"flex flex-col items-center justify-center p-4 bg-emerald-900/20 hover:bg-emerald-900/40 border border-emerald-800/50 rounded-lg transition-colors",children:[Xs(q1,{size:24,className:"text-emerald-500 mb-2"}),Xs("span",{className:"text-xs font-bold text-emerald-400",children:"System Normal"})]})]})]})};import{useEffect as Y1,useState as xa}from"react";import{BarChart as J1,Bar as X1,XAxis as Z1,YAxis as Q1,CartesianGrid as eS,Tooltip as tS,Legend as rS,ResponsiveContainer as nS}from"recharts";import{AlertCircle as iS}from"lucide-react";import{jsx as sr,jsxs as Qs}from"react/jsx-runtime";var _p=()=>{let[r,e]=xa([]),[t,n]=xa(!0),[i,s]=xa(null),[o,a]=xa(!1),l=5e4;Y1(()=>{(async()=>{try{n(!0);let h=import.meta.env?.VITE_API_URL||"http://localhost:3001/api",f=await fetch(`${h}/billing/usage`);if(!f.ok)throw new Error("Failed to fetch billing usage");let p=await f.json();e(p);let m=0;p.forEach(g=>{Object.keys(g).forEach(b=>{b!=="date"&&(m+=Number(g[b]))})}),m>=l*.8&&a(!0)}catch(h){console.error("Failed to fetch billing usage:",h),s(h.message||"Failed to load usage data")}finally{n(!1)}})()},[]);let c=()=>{let u=new Set;return r.forEach(h=>{Object.keys(h).forEach(f=>{f!=="date"&&u.add(f)})}),Array.from(u)},d=["#8884d8","#82ca9d","#ffc658","#ff8042","#00C49F"];return Qs("div",{className:"w-full flex-1 bg-surface-overlay border border-border-default rounded-xl backdrop-blur-xl overflow-hidden shadow-2xl",children:[sr("div",{className:"p-4 border-b border-border-subtle",children:sr("h3",{className:"text-emerald-400 font-semibold flex items-center gap-2",children:"Portal del Cliente - Consumo de IA (Gas)"})}),Qs("div",{className:"p-4",children:[o&&Qs("div",{className:"mb-4 flex items-center gap-2 text-rose-400 bg-rose-500/10 p-3 rounded-lg border border-rose-500/20",children:[sr(iS,{className:"w-5 h-5"}),Qs("span",{children:["Atenci\xF3n: Has superado el 80% de tu cuota mensual (",l," Gas)."]})]}),t?sr("div",{className:"h-64 flex items-center justify-center text-text-primary/50",children:"Cargando consumo..."}):i?sr("div",{className:"h-64 flex items-center justify-center text-rose-400",children:i}):r.length===0?sr("div",{className:"h-64 flex items-center justify-center text-text-primary/50",children:"No hay datos de consumo registrados a\xFAn."}):sr("div",{className:"h-64 w-full",children:sr(nS,{width:"100%",height:"100%",children:Qs(J1,{data:r,children:[sr(eS,{strokeDasharray:"3 3",stroke:"#ffffff10",vertical:!1}),sr(Z1,{dataKey:"date",stroke:"#ffffff50",tickFormatter:u=>new Date(u).toLocaleDateString()}),sr(Q1,{stroke:"#ffffff50"}),sr(tS,{contentStyle:{backgroundColor:"#1a1a1a",border:"1px solid #333"},itemStyle:{color:"#fff"}}),sr(rS,{}),c().map((u,h)=>sr(X1,{dataKey:u,stackId:"a",fill:d[h%d.length]},u))]})})})]})]})};import{Activity as sS,Server as oS,Users as aS}from"lucide-react";import{jsx as At,jsxs as Jt}from"react/jsx-runtime";var g4=()=>Jt("div",{className:"min-h-screen bg-surface-primary p-8 text-text-primary",children:[Jt("header",{className:"mb-8 flex items-center justify-between",children:[Jt("div",{children:[At("h1",{className:"text-3xl font-black text-transparent bg-clip-text bg-linear-to-r from-purple-400 to-pink-600",children:"MISSION CONTROL"}),At("p",{className:"text-text-muted font-mono text-sm mt-1",children:"System Operations & Real-time Command"})]}),Jt("div",{className:"flex gap-4",children:[Jt("div",{className:"bg-surface-secondary px-4 py-2 rounded-lg border border-border-subtle flex items-center gap-3",children:[At(aS,{size:16,className:"text-blue-400"}),At("span",{className:"font-mono font-bold",children:"12 Active"})]}),Jt("div",{className:"bg-surface-secondary px-4 py-2 rounded-lg border border-border-subtle flex items-center gap-3",children:[At(oS,{size:16,className:"text-emerald-400"}),At("span",{className:"font-mono font-bold",children:"Healthy"}),At("div",{className:"w-2 h-2 rounded-full bg-emerald-500 animate-pulse"})]})]})]}),Jt("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[At("div",{className:"space-y-6",children:At(Bp,{})}),Jt("div",{className:"space-y-6",children:[At(Fp,{}),At(_p,{})]}),Jt("div",{className:"bg-surface-secondary rounded-xl border border-border-subtle p-6 font-mono text-xs h-[500px] flex flex-col",children:[Jt("h3",{className:"font-bold text-text-secondary mb-4 flex items-center gap-2",children:[At(sS,{size:16})," Live Event Stream"]}),Jt("div",{className:"flex-1 overflow-y-auto space-y-2 text-text-muted",children:[Jt("p",{children:[At("span",{className:"text-emerald-500",children:"[10:00:01]"})," System Init"]}),Jt("p",{children:[At("span",{className:"text-blue-500",children:"[10:05:23]"})," User 'Julio' connected"]}),Jt("p",{children:[At("span",{className:"text-yellow-500",children:"[10:12:45]"})," AI Graph Analysis triggered"]}),Jt("p",{children:[At("span",{className:"text-purple-500",children:"[10:15:00]"})," Order #1234 staged to PRODUCTION"]}),At("div",{className:"opacity-30 italic mt-4",children:"Listening for events..."})]})]})]})]});import{useState as ns,useEffect as lS}from"react";import{kernel as Kn}from"@decido/kernel-bridge";import{jsx as $t,jsxs as Or}from"react/jsx-runtime";var C4=()=>{let{mcpServers:r,setMcpServerStatus:e}=wp(),[t,n]=ns([]),[i,s]=ns(null),[o,a]=ns(null),[l,c]=ns("{}"),[d,u]=ns(null),[h,f]=ns(!1),p=async()=>{try{let x=await Kn.execute("list_mcp_tools");n(x||[])}catch(x){console.error("Failed to fetch MCP tools",x)}};lS(()=>{p();let x=setInterval(p,1e4);return()=>clearInterval(x)},[]);let m=async(x,N,C)=>{s(x);try{let w=C.split(" ").filter(k=>k.trim()!=="");await Kn.execute("connect_mcp_server",{name:x,command:N,args:w}),Kn.notify("MCP Connected",`Server ${x} connected successfully.`),e(x,!0),await p()}catch(w){Kn.notify("MCP Connection Failed",w.toString())}finally{s(null)}},g=async x=>{s(x);try{await Kn.execute("disconnect_mcp_server",{name:x}),Kn.notify("MCP Disconnected",`Server ${x} disconnected.`),e(x,!1),await p()}catch(N){Kn.notify("Disconnect Failed",N.toString())}finally{s(null)}},b=x=>{if(o===x.name){a(null);return}a(x.name),u(null);let N={};x.inputSchema?.properties&&Object.keys(x.inputSchema.properties).forEach(C=>{let w=x.inputSchema.properties[C];w.type==="string"?N[C]="":w.type==="number"?N[C]=0:w.type==="boolean"?N[C]=!1:w.type==="object"?N[C]={}:w.type==="array"&&(N[C]=[])}),c(JSON.stringify(N,null,2))},y=async x=>{f(!0),u(null);try{let N={};try{let S=l.replace(/[\u2018\u2019]/g,"'").replace(/[\u201C\u201D]/g,'"');N=JSON.parse(S)}catch{u("Invalid JSON format in arguments."),f(!1);return}let C=x.split(":"),w="",k=x;C.length>=3&&C[0]==="mcp"?(w=C[1],k=C.slice(2).join(":")):C.length===2&&C[0]!=="mcp"?(w=C[0],k=C[1]):w=C[0]||"frubeala-mcp";let A=await Kn.execute("call_mcp_tool",{serverName:w,toolName:k,arguments:N});if(A&&A.content){let S=A.content.filter(M=>M.type==="text").map(M=>M.text).join("\\n");u(S)}else u(JSON.stringify(A,null,2))}catch(N){u(`Error: ${N.toString()}`)}finally{f(!1)}};return Or("div",{className:"space-y-4",children:[Or("div",{className:"space-y-2",children:[$t("h4",{className:"text-xs font-bold text-text-secondary uppercase tracking-widest mb-3",children:"Conexiones Activas"}),r.length===0&&$t("div",{className:"text-text-muted text-xs text-center py-4 bg-surface-glass rounded-xl border border-border-subtle",children:"Sin servidores conectados."}),r.map((x,N)=>Or("div",{className:"flex flex-col p-3 bg-surface-glass rounded-xl border border-border-subtle",children:[Or("div",{className:"flex items-center justify-between",children:[$t("span",{className:"text-sm font-medium text-text-primary",children:x.name}),x.isConnected?$t("button",{onClick:()=>g(x.name),disabled:i===x.name,className:"px-2 py-1 bg-red-900/30 hover:bg-red-900/60 text-red-400 border border-red-500/30 rounded text-xs transition-colors",children:i===x.name?"Disconnecting...":"Disconnect"}):$t("button",{onClick:()=>m(x.name,x.command,x.args),disabled:i===x.name,className:"px-2 py-1 bg-emerald-900/30 hover:bg-emerald-900/60 text-emerald-400 border border-emerald-500/30 rounded text-xs transition-colors",children:i===x.name?"Connecting...":"Connect"})]}),Or("div",{className:"text-[10px] text-text-muted font-mono mt-1",children:[x.command," ",x.args]})]},N))]}),Or("div",{className:"space-y-2 mt-6",children:[$t("h4",{className:"text-xs font-bold text-text-secondary uppercase tracking-widest mb-3 border-t border-border-subtle pt-4",children:"Tools Playground"}),t.length===0&&$t("div",{className:"text-text-muted text-xs text-center py-4 bg-surface-glass rounded-xl border border-border-subtle",children:"No hay herramientas disponibles. Aseg\xFArate de que un servidor MCP est\xE9 online."}),$t("div",{className:"space-y-2 pb-10",children:t.map(x=>Or("div",{className:"bg-surface-overlay border border-border-subtle rounded-xl p-3 overflow-hidden",children:[Or("div",{className:"flex items-center justify-between",children:[Or("div",{children:[$t("h4",{className:"text-cyan-400 font-bold text-sm",children:x.name.split(":").pop()||x.name}),$t("p",{className:"text-xs text-text-muted line-clamp-1",children:x.description})]}),$t("button",{onClick:()=>b(x),className:"px-3 py-1 bg-cyan-900/30 hover:bg-cyan-900/60 text-cyan-400 border border-cyan-500/30 rounded text-xs transition-colors",children:"Test"})]}),o===x.name&&Or("div",{className:"mt-4 border-t border-border-default pt-4 flex flex-col gap-3 animate-in slide-in-from-top-4 duration-200",children:[Or("div",{children:[$t("label",{className:"text-[10px] text-text-muted font-bold uppercase tracking-wider mb-1 block",children:"Arguments (JSON)"}),$t("textarea",{value:l,onChange:N=>c(N.target.value),className:"w-full h-24 bg-surface-overlay border border-border-default rounded p-2 text-cyan-300 font-mono text-xs focus:border-cyan-400 outline-hidden resize-none"})]}),$t("button",{onClick:()=>y(x.name),disabled:h,className:"w-full py-2 bg-linear-to-r from-cyan-600 to-indigo-600 text-text-primary rounded font-bold text-xs hover:from-cyan-500 hover:to-indigo-500 transition-all shadow-[0_0_15px_rgba(6,182,212,0.3)] disabled:opacity-50",children:h?"Executing...":"Execute Tool"}),d&&Or("div",{className:"mt-2",children:[$t("label",{className:"text-[10px] text-text-muted font-bold uppercase tracking-wider mb-1 block",children:"Output"}),$t("div",{className:"w-full max-h-48 overflow-y-auto bg-surface-primary border border-border-default rounded p-2 text-emerald-400 font-mono text-xs whitespace-pre-wrap",children:d})]})]})]},x.name))})]})]})};import Xf,{useEffect as Bc,useMemo as TR,useCallback as MR}from"react";import vS from"react";import{PanelLeftClose as yS,PanelLeftOpen as wS,Plus as SS,Share2 as CS,Bug as kS,Sun as NS,Moon as ES,MessageSquare as AS,MessageSquareOff as TS}from"lucide-react";import cS from"react";import{motion as Qc,AnimatePresence as zp}from"motion/react";import{Network as dS}from"lucide-react";import{jsx as Yn,jsxs as va}from"react/jsx-runtime";var $p=cS.memo(function({isSpeaking:e,isCreatorMode:t,creatorViewMode:n,modelLabel:i,onModelClick:s,onSyncCreatorMode:o,onSetCreatorViewMode:a}){return va("div",{"data-tauri-drag-region":!0,className:"flex-1 flex items-center justify-center gap-2 min-w-0",children:[Yn(zp,{children:e&&Yn(Qc.div,{initial:{opacity:0,width:0},animate:{opacity:1,width:"auto"},exit:{opacity:0,width:0},className:"flex items-center gap-0.5 mr-2 overflow-hidden",children:[1,2,3,4,5].map(l=>Yn(Qc.div,{animate:{height:[6,Math.random()*16+8,6]},transition:{repeat:1/0,duration:.5,delay:l*.08},className:"w-1 bg-accent-cyan rounded-full"},l))})}),va("div",{className:"flex bg-surface-tertiary border border-border-default rounded-lg p-0.5 shadow-sm",children:[Yn("button",{onClick:()=>{t&&o(!1)},className:`px-3 py-1 text-[11px] font-semibold rounded-md transition-all duration-200 ${t?"text-text-muted hover:text-text-secondary border border-transparent":"bg-surface-elevated text-text-primary shadow-sm border border-border-default"}`,children:"Player"}),Yn("button",{onClick:()=>{t||o(!0)},className:`px-3 py-1 text-[11px] font-semibold rounded-md transition-all duration-200 flex items-center gap-1 ${t?"bg-surface-elevated text-accent-purple shadow-sm border border-accent-purple":"text-text-muted hover:text-text-secondary border border-transparent"}`,children:"Creator"})]}),Yn(zp,{children:t&&va(Qc.div,{initial:{opacity:0,scale:.9,width:0},animate:{opacity:1,scale:1,width:"auto"},exit:{opacity:0,scale:.9,width:0},className:"hidden lg:flex bg-surface-tertiary border border-border-default rounded-lg p-0.5 overflow-hidden shadow-sm",children:[Yn("button",{onClick:()=>a("timeline"),className:`px-2.5 py-1 text-[10px] font-bold tracking-wider rounded-md transition-all duration-200 ${n==="timeline"?"bg-surface-elevated text-text-primary shadow-sm border border-border-default":"text-text-muted hover:text-text-secondary border border-transparent"}`,children:"TIMELINE"}),va("button",{onClick:()=>a("graph"),className:`px-2.5 py-1 text-[10px] font-bold tracking-wider rounded-md transition-all duration-200 flex items-center gap-1 ${n==="graph"?"bg-surface-elevated text-text-primary shadow-sm border border-border-default":"text-text-muted hover:text-text-secondary border border-transparent"}`,children:[Yn(dS,{size:10})," GRAPH"]})]})})]})});import{useState as td,useCallback as uS}from"react";import{motion as rd,AnimatePresence as Wp}from"motion/react";import{Settings as hS,Grid3X3 as fS,Save as pS,RotateCcw as mS,Trash2 as gS,ChevronDown as Vp,SlidersHorizontal as bS}from"lucide-react";var ed={R1:"Left Top",R2:"Left Bottom",R3:"Right Top",R4:"Right Bottom",R5:"Top Edge",R6:"Status Bar"};var Hp=[{id:null,label:"\u2014 Vac\xEDo \u2014"},{id:"chat",label:"Chat"},{id:"debug",label:"Debug Panel"},{id:"terminal",label:"Terminal"},{id:"canvas",label:"Canvas / MorphShell"},{id:"graph-editor",label:"Graph Editor"},{id:"timeline-editor",label:"Timeline Editor"},{id:"app-sidebar",label:"App Sidebar"}];import{Fragment as xS,jsx as Le,jsxs as Ht}from"react/jsx-runtime";function nd(){let[r,e]=td(!1),[t,n]=td(!1),[i,s]=td(""),o=ce(p=>p.slots),a=ce(p=>p.setSlot),l=ce(p=>p.resetLayout),c=ce(p=>p.savedPresets),d=ce(p=>p.savePreset),u=ce(p=>p.loadPreset),h=ce(p=>p.deletePreset),f=uS(()=>{i.trim()&&(d(i.trim()),s(""))},[i,d]);return Ht("div",{className:"relative",children:[Le("button",{onClick:()=>e(!r),className:`p-2 rounded-lg transition-all ${r?"bg-cyan-500/20 text-cyan-400 shadow-[0_0_10px_rgba(6,182,212,0.2)]":"text-text-muted hover:text-text-primary hover:bg-surface-glass"}`,title:"Layout Configurator",children:Le(fS,{size:16})}),Le(Wp,{children:r&&Ht(xS,{children:[Le("div",{className:"fixed inset-0 z-800",style:{position:"fixed",inset:0,zIndex:800},onClick:()=>e(!1)}),Ht(rd.div,{initial:{opacity:0,y:-8,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-8,scale:.95},transition:{type:"spring",damping:25,stiffness:300},className:`absolute top-full right-0 mt-2 w-[calc(100vw-2rem)] sm:w-[380px] z-801
2
+ bg-surface-tertiary border border-border-default rounded-xl sm:rounded-2xl shadow-2xl overflow-hidden`,children:[Ht("div",{className:"px-4 py-3 border-b border-border-subtle flex items-center justify-between",children:[Ht("div",{className:"flex items-center gap-2",children:[Le(hS,{size:14,className:"text-cyan-400"}),Le("h3",{className:"text-sm font-bold text-text-primary",children:"Layout Configurator"})]}),Le("div",{className:"flex items-center gap-1",children:Object.keys(sp).map(p=>Le("button",{onClick:()=>l(p),className:`px-2.5 py-1 text-[10px] font-bold uppercase tracking-wider
3
+ rounded-full bg-surface-glass text-text-muted hover:text-text-primary hover:bg-surface-glass
4
+ transition-colors border border-border-subtle`,children:p},p))})]}),Ht("div",{children:[Ht("button",{onClick:()=>n(!t),className:"w-full px-4 py-2.5 flex items-center justify-between hover:bg-surface-glass transition-colors group",children:[Ht("div",{className:"flex items-center gap-2 text-xs font-medium text-text-secondary group-hover:text-text-primary",children:[Le(bS,{size:14,className:"text-cyan-500/50"}),Le("span",{children:"Configuraci\xF3n de Slots"}),Le("span",{className:"text-[9px] px-1.5 rounded-full bg-cyan-500/10 text-cyan-400",children:"6 REGIONES"})]}),Le(rd.div,{animate:{rotate:t?180:0},children:Le(Vp,{size:14,className:"text-text-muted"})})]}),Le(Wp,{initial:!1,children:t&&Le(rd.div,{initial:{height:0,opacity:0},animate:{height:"auto",opacity:1},exit:{height:0,opacity:0},transition:{duration:.2,ease:"easeInOut"},className:"overflow-hidden",children:Le("div",{className:"px-4 pb-4 pt-1 space-y-2 bg-black/10",children:Object.keys(ed).map(p=>Ht("div",{className:"flex items-center gap-3",children:[Ht("div",{className:"w-20 flex items-center gap-1.5",children:[Le("span",{className:`w-5 h-5 rounded bg-surface-glass flex items-center justify-center
5
+ text-[9px] font-bold font-mono text-cyan-400/60 shadow-inner`,children:p}),Le("span",{className:"text-[10px] text-text-muted truncate",children:ed[p]})]}),Ht("div",{className:"flex-1 relative",children:[Le("select",{value:o[p]||"",onChange:m=>a(p,m.target.value||null),className:`w-full bg-surface-secondary border border-border-default rounded-lg px-3 py-1.5
6
+ text-xs text-text-primary appearance-none cursor-pointer
7
+ hover:border-border-strong transition-colors
8
+ focus:outline-hidden focus:border-cyan-500/40`,children:Hp.map(m=>Le("option",{value:m.id||"",children:m.label},m.id||"null"))}),Le(Vp,{size:12,className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-text-muted pointer-events-none"})]})]},p))})})})]}),Ht("div",{className:"px-4 pb-3 border-t border-border-subtle pt-3",children:[Ht("div",{className:"flex items-center gap-2 mb-2",children:[Le("input",{value:i,onChange:p=>s(p.target.value),onKeyDown:p=>p.key==="Enter"&&f(),placeholder:"Nombre del preset...",className:`flex-1 bg-surface-glass border border-border-default rounded-lg px-3 py-1.5
9
+ text-xs text-text-primary placeholder:text-text-muted outline-hidden
10
+ focus:border-cyan-500/40`}),Le("button",{onClick:f,disabled:!i.trim(),className:`p-1.5 rounded-lg bg-cyan-500/10 text-cyan-400 hover:bg-cyan-500/20
11
+ disabled:opacity-30 disabled:cursor-not-allowed transition-colors`,title:"Guardar Preset",children:Le(pS,{size:14})})]}),c.length>0&&Le("div",{className:"space-y-1 max-h-[120px] overflow-y-auto",children:c.map(p=>Ht("div",{className:"flex items-center gap-2 group",children:[Le("button",{onClick:()=>u(p.id),className:`flex-1 text-left px-2 py-1 text-[11px] text-text-secondary
12
+ hover:text-text-primary hover:bg-surface-glass rounded-lg transition-colors`,children:p.name}),Le("button",{onClick:()=>h(p.id),className:`p-1 rounded text-text-muted hover:text-red-400
13
+ opacity-0 group-hover:opacity-100 transition-all`,children:Le(gS,{size:12})})]},p.id))})]}),Ht("div",{className:"px-4 py-2 border-t border-border-subtle flex items-center justify-between text-[10px] text-text-muted",children:[Le("span",{children:"\u2318K \u2192 buscar slots"}),Ht("button",{onClick:()=>l("player"),className:"flex items-center gap-1 hover:text-text-secondary transition-colors",children:[Le(mS,{size:10}),"Reset"]})]})]})]})})]})}import{useEngineStore as MS}from"@decido/engine";import{jsx as at,jsxs as is}from"react/jsx-runtime";function DS(){let r=Vc(n=>n.currentThemeId),e=Vc(n=>n.setTheme),t=r!=="decido-light";return at("button",{onClick:()=>e(t?"decido-light":"decido-dark"),className:"w-8 h-8 rounded-lg flex items-center justify-center transition-all duration-200 border text-text-secondary hover:text-text-primary hover:bg-surface-glass border-transparent",title:t?"Cambiar a Decido Light":"Cambiar a Decido Dark","aria-label":t?"Cambiar a tema claro":"Cambiar a tema oscuro",children:is("div",{className:"relative w-4 h-4",children:[at(NS,{size:16,className:"absolute inset-0 transition-all duration-300",style:{opacity:t?0:1,transform:t?"rotate(-90deg) scale(0.5)":"rotate(0deg) scale(1)",color:t?void 0:"#f59e0b"}}),at(ES,{size:16,className:"absolute inset-0 transition-all duration-300",style:{opacity:t?1:0,transform:t?"rotate(0deg) scale(1)":"rotate(90deg) scale(0.5)",color:t?"#a78bfa":void 0}})]})})}var ya=vS.memo(function({extraActions:e=[],modelLabel:t,onModelClick:n}){let i=ne(S=>S.isSidebarOpen),s=ne(S=>S.setIsSidebarOpen),o=ne(S=>S.prototypeBrand),a=ne(S=>S.isCreatorMode),l=ne(S=>S.setIsCreatorMode),c=ne(S=>S.creatorViewMode),d=ne(S=>S.setCreatorViewMode),u=ne(S=>S.isVoiceActive),{isSpeaking:h}=MS(),f=qn(S=>S.isOpen),p=qn(S=>S.errorCount),m=qn(S=>S.togglePanel),g=ce(S=>S.showChat),b=ce(S=>S.setShowChat),y=ne(S=>S.setShowChat),x=()=>{let S=!g;b(S),y(S)},N=S=>{l(S),ce.getState().setIsCreatorMode(S)},k=[...[{id:"toggle-chat",icon:g?at(TS,{size:16}):at(AS,{size:16}),label:g?"Ocultar chat":"Mostrar chat",onClick:x,variant:g?"ghost":"outline",visibleIn:"both",className:g?"text-text-secondary":"text-accent-cyan bg-surface-glass border-accent-cyan/30"},{id:"debug-panel",icon:at(kS,{size:16}),onClick:m,variant:f?"accent":"ghost",showIndicator:p>0,indicatorColor:"bg-status-error",visibleIn:"both"}],...e].filter(S=>!S.visibleIn||S.visibleIn==="both"||S.visibleIn==="creator"&&a||S.visibleIn==="player"&&!a),A=(S="ghost")=>{switch(S){case"accent":return"bg-surface-glass text-accent-cyan hover:bg-surface-elevated border border-accent-cyan";case"outline":return"bg-transparent text-text-primary hover:bg-surface-glass border-border-default";default:return"bg-transparent text-text-secondary hover:text-text-primary hover:bg-surface-glass border-transparent"}};return is("header",{"data-tauri-drag-region":!0,className:"flex-none h-12 px-3 flex items-center justify-between bg-surface-secondary backdrop-blur-md border-b border-border-default shadow-[0_1px_3px_0_rgba(0,0,0,0.08)] z-30 select-none",children:[is("div",{className:"flex items-center gap-1.5 min-w-0",children:[at("button",{onClick:()=>s(!i),className:"w-8 h-8 rounded-lg text-text-secondary hover:text-text-primary hover:bg-surface-glass flex items-center justify-center transition-all duration-150 shrink-0",title:i?"Cerrar panel":"Abrir panel",children:i?at(yS,{size:18}):at(wS,{size:18})}),at("button",{className:"w-8 h-8 rounded-lg text-text-secondary hover:text-text-primary hover:bg-surface-glass flex items-center justify-center transition-all duration-150 shrink-0",title:"Nueva Conversaci\xF3n",children:at(SS,{size:18})}),at("div",{className:"h-4 w-px bg-border-subtle mx-1 hidden sm:block"}),at("div",{"data-tauri-drag-region":!0,className:"flex items-center gap-2 min-w-0 cursor-default",children:at("span",{className:"text-sm font-semibold text-text-primary/80 tracking-tight truncate hidden sm:inline",children:is("span",{className:"text-accent-cyan capitalize",children:[o||"Decido"," OS"]})})})]}),at($p,{isSpeaking:!!h,isCreatorMode:a,creatorViewMode:c,modelLabel:t,onModelClick:n,onSyncCreatorMode:N,onSetCreatorViewMode:d}),is("div",{className:"flex items-center gap-1",children:[k.map(S=>is("button",{onClick:S.onClick,className:`relative h-8 rounded-lg flex items-center justify-center transition-all duration-150 border text-xs font-medium ${S.className||""} ${A(S.variant)} ${S.label?"px-3 gap-1.5":"w-8"}`,title:S.label,children:[S.icon,S.label&&at("span",{className:"hidden sm:inline",children:S.label}),S.showIndicator&&at("span",{className:`absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full ${S.indicatorColor||"bg-accent-cyan"} shadow-[0_0_6px] animate-pulse`})]},S.id)),at(DS,{}),at(nd,{}),at("button",{className:"w-8 h-8 rounded-lg text-text-secondary hover:text-text-primary hover:bg-surface-glass flex items-center justify-center transition-all duration-150",title:"Compartir",children:at(CS,{size:16})})]})]})});import{useTriggerRouter as DR}from"@decido/engine";import{useEffect as OS}from"react";import{useEngineStore as eo}from"@decido/engine";var RS=()=>{let{isConnected:r,isNativeOS:e,emitEvent:t}=np(),n=eo(s=>s.lastEvent),i=ne(s=>s.addLog);OS(()=>{if(n?.type==="MCP_EXECUTION_REQUESTED"){let{intent:s,tool:o,context:a,parameters:l}=n.payload||{},c=n.targetNodeId,d=s||o;if(e||r){i(`\u{1F980} [OS Kernel] Solicitando ejecuci\xF3n nativa: ${d}`,"system"),fetch("http://localhost:3101/api/explorer/execute_tool",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({tool_name:d,args:a||l})}).then(u=>u.json()).then(u=>{if(u.success||u.result)i(`\u2705 [Daemon REST] Herramienta completada: ${d}`,"success"),eo.getState().dispatchEvent({type:"NODE_COMPLETED",targetNodeId:c,routeHandle:"success",variables:{result:u.result,...u}});else throw new Error(u.error||"Server error")}).catch(u=>{i(`\u274C [Daemon REST] Error en la herramienta ${d}: ${u.message}`,"error"),eo.getState().dispatchEvent({type:"NODE_COMPLETED",targetNodeId:c,routeHandle:"error",variables:{error:u.message,mcp_error:u.message}})});return}else{i(`[Local Mock] Simulando callback resolutivo para: ${d}`,"system");let u=setTimeout(()=>{eo.getState().dispatchEvent({type:"NODE_COMPLETED",targetNodeId:c,routeHandle:"success",variables:{mockValue:Math.floor(Math.random()*100),mocked_intent:d}})},1500);return()=>clearTimeout(u)}}},[n,r,e,t,i]),ip("mcp:response",s=>{let{targetNodeId:o,status:a,data:l,error:c}=s;if(!o){i(`\u26A0\uFE0F [OS Kernel] Respuesta hu\xE9rfana (sin targetNodeId): ${a}`,"error");return}i(`\u2705 [OS Kernel] Respuesta recibida para nodo ${o}: ${a}`,a==="success"?"success":"error");let d=a==="success"?"success":"error";eo.getState().dispatchEvent({type:"NODE_COMPLETED",targetNodeId:o,routeHandle:d,variables:{...l,mcp_error:c}})})},jp=()=>(RS(),null);import{Panel as gi,Group as od,Separator as wa}from"react-resizable-panels";import Yr from"react";import{jsx as ss,jsxs as US}from"react/jsx-runtime";var IS=Yr.lazy(()=>import("./CenterComposite-V3LL23PG.mjs").then(r=>({default:r.CenterComposite}))),PS=Yr.lazy(()=>import("./PlaygroundChat-CBIIQMWU.mjs").then(r=>({default:r.PlaygroundChat}))),LS=Yr.lazy(()=>import("./DebugPanel-NFXQOZQ6.mjs").then(r=>({default:r.DebugPanel}))),BS=Yr.lazy(()=>import("./PlaygroundTerminal-MVZKXTYW.mjs").then(r=>({default:r.PlaygroundTerminal}))),FS=Yr.lazy(()=>import("./MorphShell-4JGDAN46.mjs").then(r=>({default:r.MorphShell}))),_S=Yr.lazy(()=>import("./ReactFlowEditor-2ALQWCHQ.mjs").then(r=>({default:r.ReactFlowEditor}))),zS=Yr.lazy(()=>import("./TimelineEditor-UPRRXXVM.mjs").then(r=>({default:r.TimelineEditor}))),$S=Yr.lazy(()=>import("./PlaygroundAppSidebar-QI73PNRI.mjs").then(r=>({default:r.PlaygroundAppSidebar}))),HS=Yr.lazy(()=>import("./WidgetSlotPanel-YX2VBQAP.mjs").then(r=>({default:r.WidgetSlotPanel}))),WS=()=>ss("div",{className:"w-full h-full flex items-center justify-center",children:ss("div",{className:"w-6 h-6 border-2 border-cyan-500 border-t-transparent rounded-full animate-spin"})}),id={"workspace-chat":IS,chat:PS,debug:LS,terminal:BS,canvas:FS,"graph-editor":_S,"timeline-editor":zS,"app-sidebar":$S,"widget-panel":HS},gn=Yr.memo(function({componentId:e,slotProps:t={},className:n=""}){if(!e)return null;let i=id[e];return i?ss(Yr.Suspense,{fallback:ss(WS,{}),children:ss("div",{className:`w-full h-full overflow-hidden ${n}`,children:ss(i,{...t})})}):US("div",{className:`w-full h-full flex items-center justify-center text-text-muted text-xs font-mono ${n}`,children:["Unknown slot: ",e]})});function VS(r,e){id[r]=e}function jS(){return Object.keys(id)}import GS from"react";import{motion as Up,AnimatePresence as qS}from"motion/react";import{X as KS}from"lucide-react";import{jsx as os,jsxs as YS}from"react/jsx-runtime";function sd({className:r=""}){let e=ce(o=>o.tabs),t=ce(o=>o.activeTabId),n=ce(o=>o.setActiveTab),i=ce(o=>o.removeTab),s=GS.useCallback(o=>{if(n(o),o.startsWith("morph-")){let a=o.replace("morph-","");Uc.getState().setActiveInstance(a);let l=Uc.getState().instances.get(a);l?.sourceChatId&&ne.getState().setActiveChatId(l.sourceChatId)}},[n]);return e.length===0?null:os("div",{className:`flex items-center gap-0.5 px-2 py-1 bg-surface-primary border-b border-border-subtle overflow-x-auto scrollbar-hide ${r}`,children:os(qS,{mode:"popLayout",children:e.map(o=>YS(Up.button,{layout:!0,initial:{opacity:0,scale:.9,width:0},animate:{opacity:1,scale:1,width:"auto"},exit:{opacity:0,scale:.9,width:0},onClick:()=>s(o.id),className:`
14
+ flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-medium
15
+ transition-colors whitespace-nowrap group relative shrink-0
16
+ ${t===o.id?"bg-surface-glass text-text-primary shadow-xs border border-border-default":"text-text-muted hover:text-text-primary hover:bg-surface-glass border border-transparent"}
17
+ `,children:[os("span",{className:"truncate max-w-[120px]",children:o.label}),o.closeable!==!1&&os("span",{onClick:a=>{a.stopPropagation(),i(o.id)},className:`w-4 h-4 rounded-md flex items-center justify-center
18
+ opacity-0 group-hover:opacity-100 hover:bg-surface-glass hover:text-red-400
19
+ transition-all ml-0.5`,children:os(KS,{size:10})}),t===o.id&&os(Up.div,{layoutId:"tab-indicator",className:"absolute bottom-0 left-1 right-1 h-[2px] bg-cyan-500/60 rounded-full"})]},o.id))})})}import{jsx as Re,jsxs as Sa}from"react/jsx-runtime";var Gp="w-1.5 hover:bg-cyan-500/20 active:bg-cyan-500/30 transition-colors cursor-col-resize z-40 relative group flex items-center justify-center",qp=Re("div",{className:"w-[2px] h-10 bg-white/5 rounded-full group-hover:bg-cyan-500/60 transition-colors"}),Kp="h-1.5 hover:bg-cyan-500/20 active:bg-cyan-500/30 transition-colors cursor-row-resize z-40 relative group flex items-center justify-center",Yp=Re("div",{className:"h-[2px] w-10 bg-white/5 rounded-full group-hover:bg-cyan-500/60 transition-colors"}),ad="h-full overflow-hidden flex flex-col min-w-0 min-h-0 bg-surface-secondary border-r border-border-subtle shadow-[inset_-6px_0_20px_rgba(0,0,0,0.15)]",ld="h-full overflow-hidden flex flex-col min-w-0 min-h-0 bg-surface-secondary border-l border-border-subtle shadow-[inset_6px_0_20px_rgba(0,0,0,0.15)]";function cd({children:r,slotProps:e={}}){let t=ce(b=>b.slots),n=ce(b=>b.tabs),i=ce(b=>b.showCanvas),o=ce(b=>b.showChat)?t.R1:null,a=!!(o||t.R2),l=!!(t.R3||t.R4),c=!!t.R6,d=n.length>0,u=`${a?"L":""}${i?"C":""}${l?"R":""}`,h=i?l?20:25:l?50:100,f=i?35:l?70:100,p=i?a?25:40:a?50:100,m=i?60:a?70:100,g=a&&l?40:a?60:l?50:100;return Sa("div",{className:"flex-1 flex flex-col h-full overflow-hidden min-w-0 min-h-0",children:[t.R5&&Re("div",{className:"flex-none",children:Re(gn,{componentId:t.R5,slotProps:e})}),d&&Re(sd,{}),Sa(od,{orientation:"horizontal",className:"flex-1 min-w-0 min-h-0",children:[a&&Re(gi,{id:"left-column",defaultSize:h,minSize:15,className:"h-full overflow-hidden flex flex-col min-w-0 min-h-0",children:o&&t.R2?Sa(od,{orientation:"vertical",className:"h-full min-w-0 min-h-0",children:[Re(gi,{id:"R1",defaultSize:65,minSize:20,className:"flex flex-col min-w-0 min-h-0",children:Re("div",{className:ad,children:Re(gn,{componentId:o,slotProps:e})})}),Re(wa,{className:Kp,children:Yp}),Re(gi,{id:"R2",defaultSize:35,minSize:15,className:"flex flex-col min-w-0 min-h-0",children:Re("div",{className:ad,children:Re(gn,{componentId:t.R2,slotProps:e})})})]}):Re("div",{className:ad,children:Re(gn,{componentId:o||t.R2,slotProps:e})})}),a&&i&&Re(wa,{id:"h-left",className:Gp,children:qp}),i&&Re(gi,{id:"center",defaultSize:g,minSize:20,className:"h-full overflow-hidden flex flex-col min-w-0 min-h-0",children:Re("div",{className:"h-full flex flex-col overflow-hidden bg-surface-secondary min-w-0 min-h-0",children:r})}),l&&(i||a)&&Re(wa,{id:"h-right",className:Gp,children:qp}),l&&Re(gi,{id:"right-column",defaultSize:p,minSize:15,className:"h-full overflow-hidden flex flex-col min-w-0 min-h-0",children:t.R3&&t.R4?Sa(od,{orientation:"vertical",className:"h-full min-w-0 min-h-0",children:[Re(gi,{id:"R3",defaultSize:65,minSize:20,className:"flex flex-col min-w-0 min-h-0",children:Re("div",{className:ld,children:Re(gn,{componentId:t.R3,slotProps:e})})}),Re(wa,{className:Kp,children:Yp}),Re(gi,{id:"R4",defaultSize:35,minSize:15,className:"flex flex-col min-w-0 min-h-0",children:Re("div",{className:ld,children:Re(gn,{componentId:t.R4,slotProps:e})})})]}):Re("div",{className:ld,children:Re(gn,{componentId:t.R3||t.R4,slotProps:e})})})]},u),c&&Re("div",{className:"flex-none border-t border-border-subtle",children:Re(gn,{componentId:t.R6,slotProps:e})})]})}import{motion as dd}from"motion/react";import{jsx as Ca,jsxs as Jp}from"react/jsx-runtime";function Xp(){return Jp("div",{className:"h-dvh w-full bg-surface-primary flex flex-col items-center justify-center font-mono text-cyan-400 relative overflow-hidden",children:[Ca("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E')] opacity-[0.15] mix-blend-overlay pointer-events-none z-0"}),Jp(dd.div,{initial:{opacity:0},animate:{opacity:1},className:"z-10 flex flex-col items-center",children:[Ca("div",{className:"w-16 h-16 rounded-full border-[3px] border-cyan-500/30 border-t-cyan-400 animate-spin mb-6 shadow-[0_0_30px_rgba(34,211,238,0.2)]"}),Ca(dd.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.5},className:"text-sm tracking-widest uppercase mb-2 font-bold",children:"Inicializando yo.decido"}),Ca(dd.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1},className:"text-xs text-text-muted",children:"Cargando m\xF3dulos de IA y telemetr\xEDa..."})]})]})}import{useEffect as JS}from"react";import{logger as XS}from"@decido/logger";function Zp(){let r=ne(t=>t.addLog),e=qn(t=>t.addLogEntry);JS(()=>{let t=XS.subscribe(n=>{let i=n.categories.length>0?`[${n.categories.join(",")}] `:"";r(`${i}${n.message}`,n.level),e({timestamp:n.timestamp,level:n.level,categories:n.categories,message:n.message,data:n.data,source:n.source})});return()=>t()},[r,e])}import{useEffect as ZS}from"react";function Qp(){let r=ne(t=>t.setIsBooting),e=ne(t=>t.isMuted);ZS(()=>{let t=setTimeout(()=>{r(!1),lp("success",e)},2500);return()=>clearTimeout(t)},[e,r])}import{useEffect as QS,useRef as eC}from"react";import{io as tC}from"socket.io-client";var rC=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",em=()=>{let{addChatMessage:r,isMuted:e}=ne(),t=eC(new Set);QS(()=>{let n=tC(rC,{reconnectionAttempts:5,reconnectionDelay:2e3}),i=s=>{if(s){let{wamid:o,from:a,type:l,timestamp:c,name:d,content:u}=s;if(o&&t.current.has(o))return;o&&t.current.add(o);let h=parseInt(c),f=new Date(h>1e10?h:h*1e3),p={type:"div",props:{className:"w-full outline-hidden bg-transparent flex flex-col p-4 gap-3 border-l-4 border-l-[#25D366]"},children:[{type:"div",props:{className:"flex items-center gap-3 border-b border-white/5 pb-3"},children:[{type:"div",props:{className:"flex items-center justify-center p-2 bg-[#25D366]/20 rounded-full text-[#25D366] w-8 h-8 font-bold text-xs"},children:"WA"},{type:"div",props:{className:"flex flex-col"},children:[{type:"span",props:{className:"font-semibold text-text-primary text-xs"},children:d?`${d}`:`${a}`},{type:"span",props:{className:"text-[#25D366] text-[10px] uppercase font-mono tracking-wider"},children:`Recibido a las ${f.toLocaleTimeString()}`}]}]},{type:"p",props:{className:"text-text-secondary leading-relaxed bg-black/20 p-3 rounded-lg border border-white/5"},children:u||"Mensaje interactivo o multimedia (Abrir WhatsApp Studio para ver)"},{type:"button",props:{className:"mt-2 w-full py-2 bg-[#25D366]/20 hover:bg-[#25D366]/30 text-[#25D366] rounded-lg transition-colors text-xs font-bold border border-[#25D366]/20 flex items-center justify-center gap-2"},children:"Abrir WhatsApp Studio",onAction:{command:"studio:openPlugin",payload:{pluginId:"chameleon",view:"discovery_admin"}}},{type:"button",props:{className:"mt-1 w-full py-2 bg-surface-secondary hover:bg-surface-tertiary text-text-secondary rounded-lg transition-colors text-xs font-medium border border-border-default flex items-center justify-center gap-2"},children:"Ver Kanban de Pedidos",onAction:{command:"studio:openPlugin",payload:{pluginId:"chameleon",view:"enterprise_kanban"}}}]};r({type:"ui-artifact",sender:"agent",text:`Nuevo mensaje de WhatsApp de ${d||a}`,actorId:"whatsapp",actorName:"WhatsApp Gateway",uiSchema:JSON.stringify(p)})}};return n.on("wa:message_received",i),n.on("connect",()=>{console.log("[WhatsApp Listener] Conectado al backend para mensajes globales:",n.id)}),()=>{n.off("wa:message_received",i),n.disconnect()}},[r,e])};import{useManifestRegistry as Fc,registerManifestLoader as ww}from"@decido/plugin-engine";var ud="http://localhost:3333",tm={id:"sentinel-ui",name:"Sentinel AI",description:"Observability suite: telemetry, error tracking, and session replay for Decido OS",author:"Decido Engineering",version:"2.0.0",icon:"Shield",color:"#3b82f6",engines:{},permissions:["events:read","sessions:read","errors:read"],intents:["sentinel:openTelemetry","sentinel:openErrors","sentinel:openReplays"],widgets:[{id:"sentinel-telemetry",name:"Telemetry Dashboard",icon:"Activity",defaultZone:"main-canvas",schema:{type:"div",props:{className:"p-4 space-y-5 bg-zinc-950 min-h-full"},children:[{type:"div",props:{className:"flex items-center justify-between"},children:[{type:"h2",props:{className:"text-lg font-bold text-white flex items-center gap-2"},children:["\u{1F6E1}\uFE0F Sentinel \u2014 Telemetry"]},{type:"StatusBadge",props:{status:"online",label:"Live"}}]},{type:"div",props:{className:"grid grid-cols-3 gap-3"},children:[{type:"MetricCard",props:{label:"Events/min",value:1247,color:"emerald",trend:"up"}},{type:"MetricCard",props:{label:"Avg Latency",value:"23ms",color:"amber",trend:"down"}},{type:"MetricCard",props:{label:"Uptime",value:"99.7%",color:"cyan",trend:"stable"}}]},{type:"div",props:{className:"grid grid-cols-2 gap-3"},children:[{type:"div",props:{className:"p-3 bg-zinc-900/50 rounded-lg border border-white/5 space-y-2"},children:[{type:"div",props:{className:"flex items-center justify-between"},children:[{type:"span",props:{className:"text-[10px] text-zinc-500 uppercase tracking-wider"},children:["Event Rate (60s)"]},{type:"Sparkline",props:{color:"cyan",height:28}}]}]},{type:"div",props:{className:"p-3 bg-zinc-900/50 rounded-lg border border-white/5 space-y-2"},children:[{type:"ProgressBar",props:{label:"Memory",value:67,color:"emerald"}},{type:"ProgressBar",props:{label:"CPU",value:34,color:"cyan"}}]}]},{type:"div",props:{className:"p-3 bg-zinc-900/50 rounded-lg border border-white/5 space-y-2"},children:[{type:"h3",props:{className:"text-xs font-semibold text-zinc-400 uppercase tracking-wider"},children:["Recent Events"]},{type:"EventList",dataSource:"sentinel.events",props:{maxItems:5}}]}]}},{id:"sentinel-errors",name:"Error Tracking",icon:"AlertTriangle",defaultZone:"main-canvas",schema:{type:"div",props:{className:"p-4 space-y-4 bg-zinc-950 min-h-full"},children:[{type:"div",props:{className:"flex items-center justify-between"},children:[{type:"h2",props:{className:"text-lg font-bold text-white flex items-center gap-2"},children:["\u{1F534} Error Tracking"]},{type:"MetricCard",props:{label:"Total Errors",value:2,color:"red"}}]},{type:"ErrorList",dataSource:"sentinel.errors",props:{}},{type:"button",props:{className:"w-full px-4 py-2.5 bg-red-600/20 hover:bg-red-600/30 text-red-400 text-sm rounded-lg font-medium transition-colors border border-red-500/20"},children:["\u{1F5D1}\uFE0F Clear All Errors"],onAction:{command:"sentinel:clearErrors"}}]}},{id:"sentinel-replays",name:"Session Replay",icon:"Film",defaultZone:"main-canvas",schema:{type:"div",props:{className:"p-4 space-y-4 bg-zinc-950 min-h-full"},children:[{type:"div",props:{className:"flex items-center justify-between"},children:[{type:"h2",props:{className:"text-lg font-bold text-white flex items-center gap-2"},children:["\u{1F3AC} Session Replay"]},{type:"StatusBadge",props:{status:"online",label:"Recording"}}]},{type:"div",props:{className:"grid grid-cols-2 gap-3"},children:[{type:"MetricCard",props:{label:"Sessions Today",value:3,color:"blue"}},{type:"MetricCard",props:{label:"Avg Duration",value:"4:30",color:"cyan"}}]},{type:"div",props:{className:"p-4 bg-zinc-900/50 rounded-lg border border-white/5 text-center space-y-3"},children:[{type:"div",props:{className:"text-4xl"},children:["\u{1F4F9}"]},{type:"p",props:{className:"text-sm text-zinc-300"},children:["Latest session: 4 min 32s"]},{type:"ProgressBar",props:{label:"Playback",value:72,color:"blue"}},{type:"button",props:{className:"px-4 py-2 bg-indigo-600 hover:bg-indigo-500 text-white text-sm rounded-lg font-medium transition-colors"},children:["\u25B6 Play Latest Session"],onAction:{command:"sentinel:openReplay",payload:{sessionId:"latest"}}}]}]}}],sidebarItems:[{id:"telemetry",label:"Telemetry Dashboard",icon:"Activity",section:"sentinel",sectionTitle:"\u{1F6E1}\uFE0F Sentinel AI",targetWidget:"sentinel-telemetry"},{id:"errors",label:"Error Tracking",icon:"AlertTriangle",section:"sentinel",sectionTitle:"\u{1F6E1}\uFE0F Sentinel AI",targetWidget:"sentinel-errors"},{id:"replays",label:"Session Replay",icon:"Film",section:"sentinel",sectionTitle:"\u{1F6E1}\uFE0F Sentinel AI",targetWidget:"sentinel-replays"}]},rm={"sentinel-telemetry":`${ud}/`,"sentinel-errors":`${ud}/errors`,"sentinel-replays":`${ud}/replays`};import{definePlugin as AR}from"@decido/sdk";import{useState as wN,useEffect as SN}from"react";import{create as IC}from"zustand";import{persist as PC}from"zustand/middleware";var nm=r=>r<5?24:72,im=(r,e)=>{let t=r.toLowerCase();return t.includes("perforacion")||t.includes("dise\xF1o")||t.includes("cnc")?"HOMAG":e>10||t.includes("grueso")||t.includes("18mm")?"GABBIANI":"SIGMA"},sm=r=>{let e=r.replace(/\D/g,"");return e.startsWith("57")?`+${e}`:`+57 ${e}`};var nC={DISE\u00D1O:["OPTIMIZACION","CAJA"],OPTIMIZACION:["CAJA","PRODUCCION"],CAJA:["PRODUCCION"],PRODUCCION:["DESPACHO"],DESPACHO:["ENTREGADO"],ENTREGADO:[]},om=(r,e)=>{let t=r.status;return(nC[t]||[]).includes(e)?e==="PRODUCCION"&&!r.isPaid?{allowed:!1,reason:"Bloqueo de Caja: El pedido debe estar pagado para entrar a Planta."}:e==="DESPACHO"&&r.status!=="PRODUCCION"?{allowed:!1,reason:"El pedido debe salir de producci\xF3n antes de despacharse."}:{allowed:!0}:{allowed:!1,reason:`Flujo inv\xE1lido: No se puede pasar de ${t} a ${e}.`}};import Q,{forwardRef as iC,isValidElement as hd}from"react";import sC from"react-dom";import ar from"react";import am from"react";import mC from"react";var oC=r=>{switch(r){case"success":return cC;case"info":return uC;case"warning":return dC;case"error":return hC;default:return null}},aC=Array(12).fill(0),lC=({visible:r,className:e})=>ar.createElement("div",{className:["sonner-loading-wrapper",e].filter(Boolean).join(" "),"data-visible":r},ar.createElement("div",{className:"sonner-spinner"},aC.map((t,n)=>ar.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${n}`})))),cC=ar.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ar.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),dC=ar.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ar.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),uC=ar.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ar.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),hC=ar.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ar.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),fC=ar.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ar.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ar.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),pC=()=>{let[r,e]=am.useState(document.hidden);return am.useEffect(()=>{let t=()=>{e(document.hidden)};return document.addEventListener("visibilitychange",t),()=>window.removeEventListener("visibilitychange",t)},[]),r},fd=1,gC=class{constructor(){this.subscribe=r=>(this.subscribers.push(r),()=>{let e=this.subscribers.indexOf(r);this.subscribers.splice(e,1)}),this.publish=r=>{this.subscribers.forEach(e=>e(r))},this.addToast=r=>{this.publish(r),this.toasts=[...this.toasts,r]},this.create=r=>{var e;let{message:t,...n}=r,i=typeof r?.id=="number"||((e=r.id)==null?void 0:e.length)>0?r.id:fd++,s=this.toasts.find(a=>a.id===i),o=r.dismissible===void 0?!0:r.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),s?this.toasts=this.toasts.map(a=>a.id===i?(this.publish({...a,...r,id:i,title:t}),{...a,...r,id:i,dismissible:o,title:t}):a):this.addToast({title:t,...n,dismissible:o,id:i}),i},this.dismiss=r=>(this.dismissedToasts.add(r),r||this.toasts.forEach(e=>{this.subscribers.forEach(t=>t({id:e.id,dismiss:!0}))}),this.subscribers.forEach(e=>e({id:r,dismiss:!0})),r),this.message=(r,e)=>this.create({...e,message:r}),this.error=(r,e)=>this.create({...e,message:r,type:"error"}),this.success=(r,e)=>this.create({...e,type:"success",message:r}),this.info=(r,e)=>this.create({...e,type:"info",message:r}),this.warning=(r,e)=>this.create({...e,type:"warning",message:r}),this.loading=(r,e)=>this.create({...e,type:"loading",message:r}),this.promise=(r,e)=>{if(!e)return;let t;e.loading!==void 0&&(t=this.create({...e,promise:r,type:"loading",message:e.loading,description:typeof e.description!="function"?e.description:void 0}));let n=r instanceof Promise?r:r(),i=t!==void 0,s,o=n.then(async l=>{if(s=["resolve",l],mC.isValidElement(l))i=!1,this.create({id:t,type:"default",message:l});else if(xC(l)&&!l.ok){i=!1;let c=typeof e.error=="function"?await e.error(`HTTP error! status: ${l.status}`):e.error,d=typeof e.description=="function"?await e.description(`HTTP error! status: ${l.status}`):e.description;this.create({id:t,type:"error",message:c,description:d})}else if(e.success!==void 0){i=!1;let c=typeof e.success=="function"?await e.success(l):e.success,d=typeof e.description=="function"?await e.description(l):e.description;this.create({id:t,type:"success",message:c,description:d})}}).catch(async l=>{if(s=["reject",l],e.error!==void 0){i=!1;let c=typeof e.error=="function"?await e.error(l):e.error,d=typeof e.description=="function"?await e.description(l):e.description;this.create({id:t,type:"error",message:c,description:d})}}).finally(()=>{var l;i&&(this.dismiss(t),t=void 0),(l=e.finally)==null||l.call(e)}),a=()=>new Promise((l,c)=>o.then(()=>s[0]==="reject"?c(s[1]):l(s[1])).catch(c));return typeof t!="string"&&typeof t!="number"?{unwrap:a}:Object.assign(t,{unwrap:a})},this.custom=(r,e)=>{let t=e?.id||fd++;return this.create({jsx:r(t),id:t,...e}),t},this.getActiveToasts=()=>this.toasts.filter(r=>!this.dismissedToasts.has(r.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},or=new gC,bC=(r,e)=>{let t=e?.id||fd++;return or.addToast({title:r,...e,id:t}),t},xC=r=>r&&typeof r=="object"&&"ok"in r&&typeof r.ok=="boolean"&&"status"in r&&typeof r.status=="number",vC=bC,yC=()=>or.toasts,wC=()=>or.getActiveToasts(),Te=Object.assign(vC,{success:or.success,info:or.info,warning:or.warning,error:or.error,custom:or.custom,message:or.message,promise:or.promise,dismiss:or.dismiss,loading:or.loading},{getHistory:yC,getToasts:wC});function SC(r,{insertAt:e}={}){if(!r||typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",e==="top"&&t.firstChild?t.insertBefore(n,t.firstChild):t.appendChild(n),n.styleSheet?n.styleSheet.cssText=r:n.appendChild(document.createTextNode(r))}SC(`:where(html[dir="ltr"]),:where([data-sonner-toaster][dir="ltr"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][dir="rtl"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted="true"]){transform:translateY(-10px)}@media (hover: none) and (pointer: coarse){:where([data-sonner-toaster][data-lifted="true"]){transform:none}}:where([data-sonner-toaster][data-x-position="right"]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position="left"]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:var(--offset-bottom)}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast] [data-close-button]{background:var(--gray1)}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:-50%;right:-50%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y, 0px)) translate(var(--swipe-amount-x, 0px));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-bg-hover: hsl(0, 0%, 12%);--normal-border: hsl(0, 0%, 20%);--normal-border-hover: hsl(0, 0%, 25%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);--error-text: hsl(358, 100%, 81%)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}
20
+ `);function ka(r){return r.label!==void 0}var CC=3,kC="32px",NC="16px",lm=4e3,EC=356,AC=14,TC=20,MC=200;function Jr(...r){return r.filter(Boolean).join(" ")}function DC(r){let[e,t]=r.split("-"),n=[];return e&&n.push(e),t&&n.push(t),n}var OC=r=>{var e,t,n,i,s,o,a,l,c,d,u;let{invert:h,toast:f,unstyled:p,interacting:m,setHeights:g,visibleToasts:b,heights:y,index:x,toasts:N,expanded:C,removeToast:w,defaultRichColors:k,closeButton:A,style:S,cancelButtonStyle:M,actionButtonStyle:D,className:O="",descriptionClassName:H="",duration:E,position:$,gap:G,loadingIcon:W,expandByDefault:he,classNames:_,icons:ie,closeButtonAriaLabel:Se="Close toast",pauseWhenPageIsHidden:J}=r,[ae,fe]=Q.useState(null),[Oe,_e]=Q.useState(null),[ke,B]=Q.useState(!1),[re,X]=Q.useState(!1),[me,Ae]=Q.useState(!1),[bt,xt]=Q.useState(!1),[Ur,qt]=Q.useState(!1),[Ji,hr]=Q.useState(0),[Er,rr]=Q.useState(0),Ar=Q.useRef(f.duration||E||lm),fn=Q.useRef(null),Gr=Q.useRef(null),Tr=x===0,js=x+1<=b,_t=f.type,Ce=f.dismissible!==!1,ct=f.className||"",Dn=f.descriptionClassName||"",On=Q.useMemo(()=>y.findIndex(se=>se.toastId===f.id)||0,[y,f.id]),Mr=Q.useMemo(()=>{var se;return(se=f.closeButton)!=null?se:A},[f.closeButton,A]),Un=Q.useMemo(()=>f.duration||E||lm,[f.duration,E]),pn=Q.useRef(0),vt=Q.useRef(0),I=Q.useRef(0),j=Q.useRef(null),[V,z]=$.split("-"),be=Q.useMemo(()=>y.reduce((se,ge,ve)=>ve>=On?se:se+ge.height,0),[y,On]),He=pC(),qr=f.invert||h,We=_t==="loading";vt.current=Q.useMemo(()=>On*G+be,[On,be]),Q.useEffect(()=>{Ar.current=Un},[Un]),Q.useEffect(()=>{B(!0)},[]),Q.useEffect(()=>{let se=Gr.current;if(se){let ge=se.getBoundingClientRect().height;return rr(ge),g(ve=>[{toastId:f.id,height:ge,position:f.position},...ve]),()=>g(ve=>ve.filter(et=>et.toastId!==f.id))}},[g,f.id]),Q.useLayoutEffect(()=>{if(!ke)return;let se=Gr.current,ge=se.style.height;se.style.height="auto";let ve=se.getBoundingClientRect().height;se.style.height=ge,rr(ve),g(et=>et.find(yt=>yt.toastId===f.id)?et.map(yt=>yt.toastId===f.id?{...yt,height:ve}:yt):[{toastId:f.id,height:ve,position:f.position},...et])},[ke,f.title,f.description,g,f.id]);let ze=Q.useCallback(()=>{X(!0),hr(vt.current),g(se=>se.filter(ge=>ge.toastId!==f.id)),setTimeout(()=>{w(f)},MC)},[f,w,g,vt]);Q.useEffect(()=>{if(f.promise&&_t==="loading"||f.duration===1/0||f.type==="loading")return;let se;return C||m||J&&He?(()=>{if(I.current<pn.current){let ge=new Date().getTime()-pn.current;Ar.current=Ar.current-ge}I.current=new Date().getTime()})():Ar.current!==1/0&&(pn.current=new Date().getTime(),se=setTimeout(()=>{var ge;(ge=f.onAutoClose)==null||ge.call(f,f),ze()},Ar.current)),()=>clearTimeout(se)},[C,m,f,_t,J,He,ze]),Q.useEffect(()=>{f.delete&&ze()},[ze,f.delete]);function Kt(){var se,ge,ve;return ie!=null&&ie.loading?Q.createElement("div",{className:Jr(_?.loader,(se=f?.classNames)==null?void 0:se.loader,"sonner-loader"),"data-visible":_t==="loading"},ie.loading):W?Q.createElement("div",{className:Jr(_?.loader,(ge=f?.classNames)==null?void 0:ge.loader,"sonner-loader"),"data-visible":_t==="loading"},W):Q.createElement(lC,{className:Jr(_?.loader,(ve=f?.classNames)==null?void 0:ve.loader),visible:_t==="loading"})}return Q.createElement("li",{tabIndex:0,ref:Gr,className:Jr(O,ct,_?.toast,(e=f?.classNames)==null?void 0:e.toast,_?.default,_?.[_t],(t=f?.classNames)==null?void 0:t[_t]),"data-sonner-toast":"","data-rich-colors":(n=f.richColors)!=null?n:k,"data-styled":!(f.jsx||f.unstyled||p),"data-mounted":ke,"data-promise":!!f.promise,"data-swiped":Ur,"data-removed":re,"data-visible":js,"data-y-position":V,"data-x-position":z,"data-index":x,"data-front":Tr,"data-swiping":me,"data-dismissible":Ce,"data-type":_t,"data-invert":qr,"data-swipe-out":bt,"data-swipe-direction":Oe,"data-expanded":!!(C||he&&ke),style:{"--index":x,"--toasts-before":x,"--z-index":N.length-x,"--offset":`${re?Ji:vt.current}px`,"--initial-height":he?"auto":`${Er}px`,...S,...f.style},onDragEnd:()=>{Ae(!1),fe(null),j.current=null},onPointerDown:se=>{We||!Ce||(fn.current=new Date,hr(vt.current),se.target.setPointerCapture(se.pointerId),se.target.tagName!=="BUTTON"&&(Ae(!0),j.current={x:se.clientX,y:se.clientY}))},onPointerUp:()=>{var se,ge,ve,et;if(bt||!Ce)return;j.current=null;let yt=Number(((se=Gr.current)==null?void 0:se.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Ue=Number(((ge=Gr.current)==null?void 0:ge.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),zt=new Date().getTime()-((ve=fn.current)==null?void 0:ve.getTime()),tt=ae==="x"?yt:Ue,wt=Math.abs(tt)/zt;if(Math.abs(tt)>=TC||wt>.11){hr(vt.current),(et=f.onDismiss)==null||et.call(f,f),_e(ae==="x"?yt>0?"right":"left":Ue>0?"down":"up"),ze(),xt(!0),qt(!1);return}Ae(!1),fe(null)},onPointerMove:se=>{var ge,ve,et,yt;if(!j.current||!Ce||((ge=window.getSelection())==null?void 0:ge.toString().length)>0)return;let Ue=se.clientY-j.current.y,zt=se.clientX-j.current.x,tt=(ve=r.swipeDirections)!=null?ve:DC($);!ae&&(Math.abs(zt)>1||Math.abs(Ue)>1)&&fe(Math.abs(zt)>Math.abs(Ue)?"x":"y");let wt={x:0,y:0};ae==="y"?(tt.includes("top")||tt.includes("bottom"))&&(tt.includes("top")&&Ue<0||tt.includes("bottom")&&Ue>0)&&(wt.y=Ue):ae==="x"&&(tt.includes("left")||tt.includes("right"))&&(tt.includes("left")&&zt<0||tt.includes("right")&&zt>0)&&(wt.x=zt),(Math.abs(wt.x)>0||Math.abs(wt.y)>0)&&qt(!0),(et=Gr.current)==null||et.style.setProperty("--swipe-amount-x",`${wt.x}px`),(yt=Gr.current)==null||yt.style.setProperty("--swipe-amount-y",`${wt.y}px`)}},Mr&&!f.jsx?Q.createElement("button",{"aria-label":Se,"data-disabled":We,"data-close-button":!0,onClick:We||!Ce?()=>{}:()=>{var se;ze(),(se=f.onDismiss)==null||se.call(f,f)},className:Jr(_?.closeButton,(i=f?.classNames)==null?void 0:i.closeButton)},(s=ie?.close)!=null?s:fC):null,f.jsx||hd(f.title)?f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title:Q.createElement(Q.Fragment,null,_t||f.icon||f.promise?Q.createElement("div",{"data-icon":"",className:Jr(_?.icon,(o=f?.classNames)==null?void 0:o.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||Kt():null,f.type!=="loading"?f.icon||ie?.[_t]||oC(_t):null):null,Q.createElement("div",{"data-content":"",className:Jr(_?.content,(a=f?.classNames)==null?void 0:a.content)},Q.createElement("div",{"data-title":"",className:Jr(_?.title,(l=f?.classNames)==null?void 0:l.title)},typeof f.title=="function"?f.title():f.title),f.description?Q.createElement("div",{"data-description":"",className:Jr(H,Dn,_?.description,(c=f?.classNames)==null?void 0:c.description)},typeof f.description=="function"?f.description():f.description):null),hd(f.cancel)?f.cancel:f.cancel&&ka(f.cancel)?Q.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||M,onClick:se=>{var ge,ve;ka(f.cancel)&&Ce&&((ve=(ge=f.cancel).onClick)==null||ve.call(ge,se),ze())},className:Jr(_?.cancelButton,(d=f?.classNames)==null?void 0:d.cancelButton)},f.cancel.label):null,hd(f.action)?f.action:f.action&&ka(f.action)?Q.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||D,onClick:se=>{var ge,ve;ka(f.action)&&((ve=(ge=f.action).onClick)==null||ve.call(ge,se),!se.defaultPrevented&&ze())},className:Jr(_?.actionButton,(u=f?.classNames)==null?void 0:u.actionButton)},f.action.label):null))};function cm(){if(typeof window>"u"||typeof document>"u")return"ltr";let r=document.documentElement.getAttribute("dir");return r==="auto"||!r?window.getComputedStyle(document.documentElement).direction:r}function RC(r,e){let t={};return[r,e].forEach((n,i)=>{let s=i===1,o=s?"--mobile-offset":"--offset",a=s?NC:kC;function l(c){["top","right","bottom","left"].forEach(d=>{t[`${o}-${d}`]=typeof c=="number"?`${c}px`:c})}typeof n=="number"||typeof n=="string"?l(n):typeof n=="object"?["top","right","bottom","left"].forEach(c=>{n[c]===void 0?t[`${o}-${c}`]=a:t[`${o}-${c}`]=typeof n[c]=="number"?`${n[c]}px`:n[c]}):l(a)}),t}var KL=iC(function(r,e){let{invert:t,position:n="bottom-right",hotkey:i=["altKey","KeyT"],expand:s,closeButton:o,className:a,offset:l,mobileOffset:c,theme:d="light",richColors:u,duration:h,style:f,visibleToasts:p=CC,toastOptions:m,dir:g=cm(),gap:b=AC,loadingIcon:y,icons:x,containerAriaLabel:N="Notifications",pauseWhenPageIsHidden:C}=r,[w,k]=Q.useState([]),A=Q.useMemo(()=>Array.from(new Set([n].concat(w.filter(J=>J.position).map(J=>J.position)))),[w,n]),[S,M]=Q.useState([]),[D,O]=Q.useState(!1),[H,E]=Q.useState(!1),[$,G]=Q.useState(d!=="system"?d:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),W=Q.useRef(null),he=i.join("+").replace(/Key/g,"").replace(/Digit/g,""),_=Q.useRef(null),ie=Q.useRef(!1),Se=Q.useCallback(J=>{k(ae=>{var fe;return(fe=ae.find(Oe=>Oe.id===J.id))!=null&&fe.delete||or.dismiss(J.id),ae.filter(({id:Oe})=>Oe!==J.id)})},[]);return Q.useEffect(()=>or.subscribe(J=>{if(J.dismiss){k(ae=>ae.map(fe=>fe.id===J.id?{...fe,delete:!0}:fe));return}setTimeout(()=>{sC.flushSync(()=>{k(ae=>{let fe=ae.findIndex(Oe=>Oe.id===J.id);return fe!==-1?[...ae.slice(0,fe),{...ae[fe],...J},...ae.slice(fe+1)]:[J,...ae]})})})}),[]),Q.useEffect(()=>{if(d!=="system"){G(d);return}if(d==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?G("dark"):G("light")),typeof window>"u")return;let J=window.matchMedia("(prefers-color-scheme: dark)");try{J.addEventListener("change",({matches:ae})=>{G(ae?"dark":"light")})}catch{J.addListener(({matches:fe})=>{try{G(fe?"dark":"light")}catch(Oe){console.error(Oe)}})}},[d]),Q.useEffect(()=>{w.length<=1&&O(!1)},[w]),Q.useEffect(()=>{let J=ae=>{var fe,Oe;i.every(_e=>ae[_e]||ae.code===_e)&&(O(!0),(fe=W.current)==null||fe.focus()),ae.code==="Escape"&&(document.activeElement===W.current||(Oe=W.current)!=null&&Oe.contains(document.activeElement))&&O(!1)};return document.addEventListener("keydown",J),()=>document.removeEventListener("keydown",J)},[i]),Q.useEffect(()=>{if(W.current)return()=>{_.current&&(_.current.focus({preventScroll:!0}),_.current=null,ie.current=!1)}},[W.current]),Q.createElement("section",{ref:e,"aria-label":`${N} ${he}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},A.map((J,ae)=>{var fe;let[Oe,_e]=J.split("-");return w.length?Q.createElement("ol",{key:J,dir:g==="auto"?cm():g,tabIndex:-1,ref:W,className:a,"data-sonner-toaster":!0,"data-theme":$,"data-y-position":Oe,"data-lifted":D&&w.length>1&&!s,"data-x-position":_e,style:{"--front-toast-height":`${((fe=S[0])==null?void 0:fe.height)||0}px`,"--width":`${EC}px`,"--gap":`${b}px`,...f,...RC(l,c)},onBlur:ke=>{ie.current&&!ke.currentTarget.contains(ke.relatedTarget)&&(ie.current=!1,_.current&&(_.current.focus({preventScroll:!0}),_.current=null))},onFocus:ke=>{ke.target instanceof HTMLElement&&ke.target.dataset.dismissible==="false"||ie.current||(ie.current=!0,_.current=ke.relatedTarget)},onMouseEnter:()=>O(!0),onMouseMove:()=>O(!0),onMouseLeave:()=>{H||O(!1)},onDragEnd:()=>O(!1),onPointerDown:ke=>{ke.target instanceof HTMLElement&&ke.target.dataset.dismissible==="false"||E(!0)},onPointerUp:()=>E(!1)},w.filter(ke=>!ke.position&&ae===0||ke.position===J).map((ke,B)=>{var re,X;return Q.createElement(OC,{key:ke.id,icons:x,index:B,toast:ke,defaultRichColors:u,duration:(re=m?.duration)!=null?re:h,className:m?.className,descriptionClassName:m?.descriptionClassName,invert:t,visibleToasts:p,closeButton:(X=m?.closeButton)!=null?X:o,interacting:H,position:J,style:m?.style,unstyled:m?.unstyled,classNames:m?.classNames,cancelButtonStyle:m?.cancelButtonStyle,actionButtonStyle:m?.actionButtonStyle,removeToast:Se,toasts:w.filter(me=>me.position==ke.position),heights:S.filter(me=>me.position==ke.position),setHeights:M,expandByDefault:s,gap:b,loadingIcon:y,expanded:D,pauseWhenPageIsHidden:C,swipeDirections:r.swipeDirections})})):null}))});import{kernel as Na}from"@decido/kernel-bridge";import*as dm from"yjs";import{WebsocketProvider as LC}from"y-websocket";var pd=new dm.Doc,lr=pd.getMap("orders"),BC=()=>(import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001").replace(/^https?/,e=>e==="https"?"wss":"ws")+"/api/collaboration",i3=new LC(BC(),"madefront-kanban-room",pd,{connect:!0});Na.onEvent(r=>{r&&(r.type==="MadefrontOrderUpdated"||r.event_type==="MadefrontOrderUpdated"||r.message?.includes("MadefrontOrderUpdated"))&&pr.getState().fetchOrders()});var pr=IC()(PC((r,e)=>(lr.observe(()=>{r({orders:Array.from(lr.values())})}),{orders:Array.from(lr.values()),setOrders:t=>r({orders:t}),fetchOrders:async()=>{try{let t=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",n=await fetch(`${t}/api/orders`,{headers:{"x-api-key":"dev_ak_chameleon_studio_99x"}});if(!n.ok)throw new Error(`Error HTTP: ${n.status}`);let i=await n.json();if(i.error)throw new Error(i.error);let s=o=>{switch(o?.toUpperCase()){case"NEW":case"DESIGN":return"DISE\xD1O";case"OPTIMIZATION":case"IN_CUTTING":case"IN_EDGEBANDING":case"IN_ASSEMBLY":return"OPTIMIZACION";case"AUTHORIZED_FOR_PRODUCTION":return"CAJA";case"PRODUCTION":return"PRODUCCION";case"DISPATCH":case"IN_DISPATCH":case"READY_FOR_DISPATCH":return"DESPACHO";case"COMPLETED":case"DELIVERED":return"ENTREGADO";default:return"DISE\xD1O"}};pd.transact(()=>{let o=new Set(i.map(a=>a.legacyId||a.id));Array.from(lr.keys()).forEach(a=>{o.has(a)||lr.delete(a)}),i.forEach(a=>{let l=a.legacyId||a.id,c=s(a.stage);lr.set(l,{id:l,client:a.clientName||a.clientId||"Desconocido",whatsapp:a.clientPhone?String(a.clientPhone):a.whatsapp?String(a.whatsapp):"+57 000 000 0000",material:a.salesObservation||a.material||a.items?.[0]?.woodType||"Desconocido",measurements:a.items?.[0]?.dimensions||"Ver O.T.",sheets:a.items?.[0]?.quantity||1,status:c,rawStage:a.stage,machine:a.machine||"Sin Asignar",slaHours:a.is24Hours?24:72,isUrgent:a.isUrgent||!1,isPaid:a.isPaid||!1,createdAt:new Date(a.createdAt).toLocaleDateString(),logs:lr.get(l)?.logs||[]})})})}catch(t){console.error("[Chameleon Store] Error fetching orders:",t),Te.error(`SysError: ${t.message}`)}},createOrder:t=>{let n=nm(t.sheets),i=im(t.material,t.sheets),s=sm(t.whatsapp),o=`MF-${Math.floor(1e3+Math.random()*9e3)}`,a={id:o,client:t.client,whatsapp:s,material:t.material,measurements:t.measurements,sheets:parseInt(t.sheets),status:"DISE\xD1O",machine:i,slaHours:n,isPaid:!1,createdAt:new Date().toISOString(),logs:[`Pedido creado. SLA calculado: ${n}h. M\xE1quina sugerida: ${i}`]};lr.set(o,a),Na.execute("broadcast_message",{message:JSON.stringify({type:"ORDER_CREATED",payload:a})}).catch(l=>console.error("Sync Error",l))},updateStatus:async(t,n)=>{let i=lr.get(t);if(!i)return;let s=om(i,n);if(!s.allowed){console.warn(`[Workflow Engine] Bloqueo: ${s.reason}`),setTimeout(()=>Te.error("Transici\xF3n Bloqueada",{description:s.reason}),0);return}let o="DESIGN";switch(n){case"CAJA":o="AUTHORIZED_FOR_PRODUCTION";break;case"PRODUCCION":o="PRODUCTION";break;case"DESPACHO":o="DISPATCH";break;case"ENTREGADO":o="DELIVERED";break;case"OPTIMIZACION":o="IN_CUTTING";break}try{let a=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",l=await fetch(`${a}/api/orders/${i.id}/dynamic-move`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":"dev_ak_chameleon_studio_99x"},body:JSON.stringify({newStage:o})});if(!l.ok){let u=await l.json().catch(()=>({}));throw new Error(u.error||`Error HTTP: ${l.status}`)}let c=`[${new Date().toLocaleTimeString()}] Movido a ${n}`,d={...i,status:n,logs:[...i.logs,c]};lr.set(t,d),await Na.execute("broadcast_message",{message:JSON.stringify({type:"MadefrontOrderUpdated",data:d})})}catch(a){Te.error(`Error persistiendo estado: ${a.message}`)}},updateOrder:t=>{lr.has(t.id)&&lr.set(t.id,t)},approvePayment:async t=>{let n=lr.get(t);if(!n)return;let i={...n,isPaid:!0,status:"PRODUCCION",logs:[...n.logs,"\u{1F4B0} Pago Aprobado por Caja -> Enviado a Planta"]};lr.set(t,i);try{let s=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001";await fetch(`${s}/api/orders/${n.id}/dynamic-move`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":"dev_ak_chameleon_studio_99x"},body:JSON.stringify({newStage:"PRODUCTION"})}),await Na.execute("broadcast_message",{message:JSON.stringify({type:"MadefrontOrderUpdated",data:i})})}catch{}},getOrdersByStage:t=>e().orders.filter(n=>n.status===t),getPendingPayments:()=>e().orders.filter(t=>t.status==="CAJA"&&!t.isPaid)}),{name:"madefront-db-v2"}));import{create as FC}from"zustand";var Jn=FC(r=>({currentRole:"NONE",currentUser:"",activeContext:void 0,setRole:(e,t,n)=>r({currentRole:e,currentUser:t,activeContext:n}),logout:()=>r({currentRole:"NONE",currentUser:"",activeContext:void 0})}));import{create as _C}from"zustand";var Ea=_C(r=>({currentView:"login",searchTerm:"",setCurrentView:e=>r({currentView:e}),setSearchTerm:e=>r({searchTerm:e})}));import{Plus as CN,LogOut as kN,Package as NN,FileSpreadsheet as EN}from"lucide-react";import{useState as Md,useEffect as hg}from"react";import bn,{createContext as lo,useContext as us,useEffect as dt,useState as Xr,useCallback as Zr,useMemo as ft,useRef as Tt,memo as UC,useReducer as GC,cloneElement as m3,forwardRef as g3}from"react";import{createPortal as qC,unstable_batchedUpdates as Ia}from"react-dom";import{useMemo as gd,useLayoutEffect as zC,useEffect as hm,useRef as as,useCallback as Aa}from"react";function fm(){for(var r=arguments.length,e=new Array(r),t=0;t<r;t++)e[t]=arguments[t];return gd(()=>n=>{e.forEach(i=>i(n))},e)}var to=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function bi(r){let e=Object.prototype.toString.call(r);return e==="[object Window]"||e==="[object global]"}function Ta(r){return"nodeType"in r}function Xt(r){var e,t;return r?bi(r)?r:Ta(r)&&(e=(t=r.ownerDocument)==null?void 0:t.defaultView)!=null?e:window:window}function Ma(r){let{Document:e}=Xt(r);return r instanceof e}function ls(r){return bi(r)?!1:r instanceof Xt(r).HTMLElement}function bd(r){return r instanceof Xt(r).SVGElement}function xi(r){return r?bi(r)?r.document:Ta(r)?Ma(r)?r:ls(r)||bd(r)?r.ownerDocument:document:document:document}var Rr=to?zC:hm;function Da(r){let e=as(r);return Rr(()=>{e.current=r}),Aa(function(){for(var t=arguments.length,n=new Array(t),i=0;i<t;i++)n[i]=arguments[i];return e.current==null?void 0:e.current(...n)},[])}function pm(){let r=as(null),e=Aa((n,i)=>{r.current=setInterval(n,i)},[]),t=Aa(()=>{r.current!==null&&(clearInterval(r.current),r.current=null)},[]);return[e,t]}function cs(r,e){e===void 0&&(e=[r]);let t=as(r);return Rr(()=>{t.current!==r&&(t.current=r)},e),t}function ds(r,e){let t=as();return gd(()=>{let n=r(t.current);return t.current=n,n},[...e])}function ro(r){let e=Da(r),t=as(null),n=Aa(i=>{i!==t.current&&e?.(i,t.current),t.current=i},[]);return[t,n]}function Oa(r){let e=as();return hm(()=>{e.current=r},[r]),e.current}var md={};function vi(r,e){return gd(()=>{if(e)return e;let t=md[r]==null?0:md[r]+1;return md[r]=t,r+"-"+t},[r,e])}function mm(r){return function(e){for(var t=arguments.length,n=new Array(t>1?t-1:0),i=1;i<t;i++)n[i-1]=arguments[i];return n.reduce((s,o)=>{let a=Object.entries(o);for(let[l,c]of a){let d=s[l];d!=null&&(s[l]=d+r*c)}return s},{...e})}}var yi=mm(1),wi=mm(-1);function $C(r){return"clientX"in r&&"clientY"in r}function no(r){if(!r)return!1;let{KeyboardEvent:e}=Xt(r.target);return e&&r instanceof e}function HC(r){if(!r)return!1;let{TouchEvent:e}=Xt(r.target);return e&&r instanceof e}function Ra(r){if(HC(r)){if(r.touches&&r.touches.length){let{clientX:e,clientY:t}=r.touches[0];return{x:e,y:t}}else if(r.changedTouches&&r.changedTouches.length){let{clientX:e,clientY:t}=r.changedTouches[0];return{x:e,y:t}}}return $C(r)?{x:r.clientX,y:r.clientY}:null}var Xn=Object.freeze({Translate:{toString(r){if(!r)return;let{x:e,y:t}=r;return"translate3d("+(e?Math.round(e):0)+"px, "+(t?Math.round(t):0)+"px, 0)"}},Scale:{toString(r){if(!r)return;let{scaleX:e,scaleY:t}=r;return"scaleX("+e+") scaleY("+t+")"}},Transform:{toString(r){if(r)return[Xn.Translate.toString(r),Xn.Scale.toString(r)].join(" ")}},Transition:{toString(r){let{property:e,duration:t,easing:n}=r;return e+" "+t+"ms "+n}}}),um="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function gm(r){return r.matches(um)?r:r.querySelector(um)}import bm,{useState as WC,useCallback as VC}from"react";var jC={display:"none"};function xm(r){let{id:e,value:t}=r;return bm.createElement("div",{id:e,style:jC},t)}function vm(r){let{id:e,announcement:t,ariaLiveType:n="assertive"}=r,i={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return bm.createElement("div",{id:e,style:i,role:"status","aria-live":n,"aria-atomic":!0},t)}function ym(){let[r,e]=WC("");return{announce:VC(n=>{n!=null&&e(n)},[]),announcement:r}}var Im=lo(null);function KC(r){let e=us(Im);dt(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of <DndContext>");return e(r)},[r,e])}function YC(){let[r]=Xr(()=>new Set),e=Zr(n=>(r.add(n),()=>r.delete(n)),[r]);return[Zr(n=>{let{type:i,event:s}=n;r.forEach(o=>{var a;return(a=o[i])==null?void 0:a.call(o,s)})},[r]),e]}var JC={draggable:`
21
+ To pick up a draggable item, press the space bar.
22
+ While dragging, use the arrow keys to move the item.
23
+ Press space again to drop the item in its new position, or press escape to cancel.
24
+ `},XC={onDragStart(r){let{active:e}=r;return"Picked up draggable item "+e.id+"."},onDragOver(r){let{active:e,over:t}=r;return t?"Draggable item "+e.id+" was moved over droppable area "+t.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(r){let{active:e,over:t}=r;return t?"Draggable item "+e.id+" was dropped over droppable area "+t.id:"Draggable item "+e.id+" was dropped."},onDragCancel(r){let{active:e}=r;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function ZC(r){let{announcements:e=XC,container:t,hiddenTextDescribedById:n,screenReaderInstructions:i=JC}=r,{announce:s,announcement:o}=ym(),a=vi("DndLiveRegion"),[l,c]=Xr(!1);if(dt(()=>{c(!0)},[]),KC(ft(()=>({onDragStart(u){let{active:h}=u;s(e.onDragStart({active:h}))},onDragMove(u){let{active:h,over:f}=u;e.onDragMove&&s(e.onDragMove({active:h,over:f}))},onDragOver(u){let{active:h,over:f}=u;s(e.onDragOver({active:h,over:f}))},onDragEnd(u){let{active:h,over:f}=u;s(e.onDragEnd({active:h,over:f}))},onDragCancel(u){let{active:h,over:f}=u;s(e.onDragCancel({active:h,over:f}))}}),[s,e])),!l)return null;let d=bn.createElement(bn.Fragment,null,bn.createElement(xm,{id:n,value:i.draggable}),bn.createElement(vm,{id:a,announcement:o}));return t?qC(d,t):d}var ht;(function(r){r.DragStart="dragStart",r.DragMove="dragMove",r.DragEnd="dragEnd",r.DragCancel="dragCancel",r.DragOver="dragOver",r.RegisterDroppable="registerDroppable",r.SetDroppableDisabled="setDroppableDisabled",r.UnregisterDroppable="unregisterDroppable"})(ht||(ht={}));function La(){}function Ed(r,e){return ft(()=>({sensor:r,options:e??{}}),[r,e])}function Pm(){for(var r=arguments.length,e=new Array(r),t=0;t<r;t++)e[t]=arguments[t];return ft(()=>[...e].filter(n=>n!=null),[...e])}var Qr=Object.freeze({x:0,y:0});function Lm(r,e){return Math.sqrt(Math.pow(r.x-e.x,2)+Math.pow(r.y-e.y,2))}function Bm(r,e){let{data:{value:t}}=r,{data:{value:n}}=e;return t-n}function QC(r,e){let{data:{value:t}}=r,{data:{value:n}}=e;return n-t}function wm(r){let{left:e,top:t,height:n,width:i}=r;return[{x:e,y:t},{x:e+i,y:t},{x:e,y:t+n},{x:e+i,y:t+n}]}function Ad(r,e){if(!r||r.length===0)return null;let[t]=r;return e?t[e]:t}function Sm(r,e,t){return e===void 0&&(e=r.left),t===void 0&&(t=r.top),{x:e+r.width*.5,y:t+r.height*.5}}var Fm=r=>{let{collisionRect:e,droppableRects:t,droppableContainers:n}=r,i=Sm(e,e.left,e.top),s=[];for(let o of n){let{id:a}=o,l=t.get(a);if(l){let c=Lm(Sm(l),i);s.push({id:a,data:{droppableContainer:o,value:c}})}}return s.sort(Bm)},_m=r=>{let{collisionRect:e,droppableRects:t,droppableContainers:n}=r,i=wm(e),s=[];for(let o of n){let{id:a}=o,l=t.get(a);if(l){let c=wm(l),d=i.reduce((h,f,p)=>h+Lm(c[p],f),0),u=Number((d/4).toFixed(4));s.push({id:a,data:{droppableContainer:o,value:u}})}}return s.sort(Bm)};function ek(r,e){let t=Math.max(e.top,r.top),n=Math.max(e.left,r.left),i=Math.min(e.left+e.width,r.left+r.width),s=Math.min(e.top+e.height,r.top+r.height),o=i-n,a=s-t;if(n<i&&t<s){let l=e.width*e.height,c=r.width*r.height,d=o*a,u=d/(l+c-d);return Number(u.toFixed(4))}return 0}var tk=r=>{let{collisionRect:e,droppableRects:t,droppableContainers:n}=r,i=[];for(let s of n){let{id:o}=s,a=t.get(o);if(a){let l=ek(a,e);l>0&&i.push({id:o,data:{droppableContainer:s,value:l}})}}return i.sort(QC)};function rk(r,e,t){return{...r,scaleX:e&&t?e.width/t.width:1,scaleY:e&&t?e.height/t.height:1}}function zm(r,e){return r&&e?{x:r.left-e.left,y:r.top-e.top}:Qr}function nk(r){return function(t){for(var n=arguments.length,i=new Array(n>1?n-1:0),s=1;s<n;s++)i[s-1]=arguments[s];return i.reduce((o,a)=>({...o,top:o.top+r*a.y,bottom:o.bottom+r*a.y,left:o.left+r*a.x,right:o.right+r*a.x}),{...t})}}var ik=nk(1);function sk(r){if(r.startsWith("matrix3d(")){let e=r.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(r.startsWith("matrix(")){let e=r.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function ok(r,e,t){let n=sk(e);if(!n)return r;let{scaleX:i,scaleY:s,x:o,y:a}=n,l=r.left-o-(1-i)*parseFloat(t),c=r.top-a-(1-s)*parseFloat(t.slice(t.indexOf(" ")+1)),d=i?r.width/i:r.width,u=s?r.height/s:r.height;return{width:d,height:u,top:c,right:l+d,bottom:c+u,left:l}}var ak={ignoreTransform:!1};function ki(r,e){e===void 0&&(e=ak);let t=r.getBoundingClientRect();if(e.ignoreTransform){let{transform:c,transformOrigin:d}=Xt(r).getComputedStyle(r);c&&(t=ok(t,c,d))}let{top:n,left:i,width:s,height:o,bottom:a,right:l}=t;return{top:n,left:i,width:s,height:o,bottom:a,right:l}}function Cm(r){return ki(r,{ignoreTransform:!0})}function lk(r){let e=r.innerWidth,t=r.innerHeight;return{top:0,left:0,right:e,bottom:t,width:e,height:t}}function ck(r,e){return e===void 0&&(e=Xt(r).getComputedStyle(r)),e.position==="fixed"}function dk(r,e){e===void 0&&(e=Xt(r).getComputedStyle(r));let t=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{let s=e[i];return typeof s=="string"?t.test(s):!1})}function co(r,e){let t=[];function n(i){if(e!=null&&t.length>=e||!i)return t;if(Ma(i)&&i.scrollingElement!=null&&!t.includes(i.scrollingElement))return t.push(i.scrollingElement),t;if(!ls(i)||bd(i)||t.includes(i))return t;let s=Xt(r).getComputedStyle(i);return i!==r&&dk(i,s)&&t.push(i),ck(i,s)?t:n(i.parentNode)}return r?n(r):t}function $m(r){let[e]=co(r,1);return e??null}function xd(r){return!to||!r?null:bi(r)?r:Ta(r)?Ma(r)||r===xi(r).scrollingElement?window:ls(r)?r:null:null}function Hm(r){return bi(r)?r.scrollX:r.scrollLeft}function Wm(r){return bi(r)?r.scrollY:r.scrollTop}function wd(r){return{x:Hm(r),y:Wm(r)}}var St;(function(r){r[r.Forward=1]="Forward",r[r.Backward=-1]="Backward"})(St||(St={}));function Vm(r){return!to||!r?!1:r===document.scrollingElement}function jm(r){let e={x:0,y:0},t=Vm(r)?{height:window.innerHeight,width:window.innerWidth}:{height:r.clientHeight,width:r.clientWidth},n={x:r.scrollWidth-t.width,y:r.scrollHeight-t.height},i=r.scrollTop<=e.y,s=r.scrollLeft<=e.x,o=r.scrollTop>=n.y,a=r.scrollLeft>=n.x;return{isTop:i,isLeft:s,isBottom:o,isRight:a,maxScroll:n,minScroll:e}}var uk={x:.2,y:.2};function hk(r,e,t,n,i){let{top:s,left:o,right:a,bottom:l}=t;n===void 0&&(n=10),i===void 0&&(i=uk);let{isTop:c,isBottom:d,isLeft:u,isRight:h}=jm(r),f={x:0,y:0},p={x:0,y:0},m={height:e.height*i.y,width:e.width*i.x};return!c&&s<=e.top+m.height?(f.y=St.Backward,p.y=n*Math.abs((e.top+m.height-s)/m.height)):!d&&l>=e.bottom-m.height&&(f.y=St.Forward,p.y=n*Math.abs((e.bottom-m.height-l)/m.height)),!h&&a>=e.right-m.width?(f.x=St.Forward,p.x=n*Math.abs((e.right-m.width-a)/m.width)):!u&&o<=e.left+m.width&&(f.x=St.Backward,p.x=n*Math.abs((e.left+m.width-o)/m.width)),{direction:f,speed:p}}function fk(r){if(r===document.scrollingElement){let{innerWidth:s,innerHeight:o}=window;return{top:0,left:0,right:s,bottom:o,width:s,height:o}}let{top:e,left:t,right:n,bottom:i}=r.getBoundingClientRect();return{top:e,left:t,right:n,bottom:i,width:r.clientWidth,height:r.clientHeight}}function Um(r){return r.reduce((e,t)=>yi(e,wd(t)),Qr)}function pk(r){return r.reduce((e,t)=>e+Hm(t),0)}function mk(r){return r.reduce((e,t)=>e+Wm(t),0)}function gk(r,e){if(e===void 0&&(e=ki),!r)return;let{top:t,left:n,bottom:i,right:s}=e(r);$m(r)&&(i<=0||s<=0||t>=window.innerHeight||n>=window.innerWidth)&&r.scrollIntoView({block:"center",inline:"center"})}var bk=[["x",["left","right"],pk],["y",["top","bottom"],mk]],so=class{constructor(e,t){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;let n=co(t),i=Um(n);this.rect={...e},this.width=e.width,this.height=e.height;for(let[s,o,a]of bk)for(let l of o)Object.defineProperty(this,l,{get:()=>{let c=a(n),d=i[s]-c;return this.rect[l]+d},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}},Si=class{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(t=>{var n;return(n=this.target)==null?void 0:n.removeEventListener(...t)})},this.target=e}add(e,t,n){var i;(i=this.target)==null||i.addEventListener(e,t,n),this.listeners.push([e,t,n])}};function xk(r){let{EventTarget:e}=Xt(r);return r instanceof e?r:xi(r)}function vd(r,e){let t=Math.abs(r.x),n=Math.abs(r.y);return typeof e=="number"?Math.sqrt(t**2+n**2)>e:"x"in e&&"y"in e?t>e.x&&n>e.y:"x"in e?t>e.x:"y"in e?n>e.y:!1}var Ir;(function(r){r.Click="click",r.DragStart="dragstart",r.Keydown="keydown",r.ContextMenu="contextmenu",r.Resize="resize",r.SelectionChange="selectionchange",r.VisibilityChange="visibilitychange"})(Ir||(Ir={}));function km(r){r.preventDefault()}function vk(r){r.stopPropagation()}var ye;(function(r){r.Space="Space",r.Down="ArrowDown",r.Right="ArrowRight",r.Left="ArrowLeft",r.Up="ArrowUp",r.Esc="Escape",r.Enter="Enter",r.Tab="Tab"})(ye||(ye={}));var Gm={start:[ye.Space,ye.Enter],cancel:[ye.Esc],end:[ye.Space,ye.Enter,ye.Tab]},yk=(r,e)=>{let{currentCoordinates:t}=e;switch(r.code){case ye.Right:return{...t,x:t.x+25};case ye.Left:return{...t,x:t.x-25};case ye.Down:return{...t,y:t.y+25};case ye.Up:return{...t,y:t.y-25}}},hs=class{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;let{event:{target:t}}=e;this.props=e,this.listeners=new Si(xi(t)),this.windowListeners=new Si(Xt(t)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Ir.Resize,this.handleCancel),this.windowListeners.add(Ir.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Ir.Keydown,this.handleKeyDown))}handleStart(){let{activeNode:e,onStart:t}=this.props,n=e.node.current;n&&gk(n),t(Qr)}handleKeyDown(e){if(no(e)){let{active:t,context:n,options:i}=this.props,{keyboardCodes:s=Gm,coordinateGetter:o=yk,scrollBehavior:a="smooth"}=i,{code:l}=e;if(s.end.includes(l)){this.handleEnd(e);return}if(s.cancel.includes(l)){this.handleCancel(e);return}let{collisionRect:c}=n.current,d=c?{x:c.left,y:c.top}:Qr;this.referenceCoordinates||(this.referenceCoordinates=d);let u=o(e,{active:t,context:n.current,currentCoordinates:d});if(u){let h=wi(u,d),f={x:0,y:0},{scrollableAncestors:p}=n.current;for(let m of p){let g=e.code,{isTop:b,isRight:y,isLeft:x,isBottom:N,maxScroll:C,minScroll:w}=jm(m),k=fk(m),A={x:Math.min(g===ye.Right?k.right-k.width/2:k.right,Math.max(g===ye.Right?k.left:k.left+k.width/2,u.x)),y:Math.min(g===ye.Down?k.bottom-k.height/2:k.bottom,Math.max(g===ye.Down?k.top:k.top+k.height/2,u.y))},S=g===ye.Right&&!y||g===ye.Left&&!x,M=g===ye.Down&&!N||g===ye.Up&&!b;if(S&&A.x!==u.x){let D=m.scrollLeft+h.x,O=g===ye.Right&&D<=C.x||g===ye.Left&&D>=w.x;if(O&&!h.y){m.scrollTo({left:D,behavior:a});return}O?f.x=m.scrollLeft-D:f.x=g===ye.Right?m.scrollLeft-C.x:m.scrollLeft-w.x,f.x&&m.scrollBy({left:-f.x,behavior:a});break}else if(M&&A.y!==u.y){let D=m.scrollTop+h.y,O=g===ye.Down&&D<=C.y||g===ye.Up&&D>=w.y;if(O&&!h.x){m.scrollTo({top:D,behavior:a});return}O?f.y=m.scrollTop-D:f.y=g===ye.Down?m.scrollTop-C.y:m.scrollTop-w.y,f.y&&m.scrollBy({top:-f.y,behavior:a});break}}this.handleMove(e,yi(wi(u,this.referenceCoordinates),f))}}}handleMove(e,t){let{onMove:n}=this.props;e.preventDefault(),n(t)}handleEnd(e){let{onEnd:t}=this.props;e.preventDefault(),this.detach(),t()}handleCancel(e){let{onCancel:t}=this.props;e.preventDefault(),this.detach(),t()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}};hs.activators=[{eventName:"onKeyDown",handler:(r,e,t)=>{let{keyboardCodes:n=Gm,onActivation:i}=e,{active:s}=t,{code:o}=r.nativeEvent;if(n.start.includes(o)){let a=s.activatorNode.current;return a&&r.target!==a?!1:(r.preventDefault(),i?.({event:r.nativeEvent}),!0)}return!1}}];function Nm(r){return!!(r&&"distance"in r)}function Em(r){return!!(r&&"delay"in r)}var oo=class{constructor(e,t,n){var i;n===void 0&&(n=xk(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=t;let{event:s}=e,{target:o}=s;this.props=e,this.events=t,this.document=xi(o),this.documentListeners=new Si(this.document),this.listeners=new Si(n),this.windowListeners=new Si(Xt(o)),this.initialCoordinates=(i=Ra(s))!=null?i:Qr,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){let{events:e,props:{options:{activationConstraint:t,bypassActivationConstraint:n}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(Ir.Resize,this.handleCancel),this.windowListeners.add(Ir.DragStart,km),this.windowListeners.add(Ir.VisibilityChange,this.handleCancel),this.windowListeners.add(Ir.ContextMenu,km),this.documentListeners.add(Ir.Keydown,this.handleKeydown),t){if(n!=null&&n({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Em(t)){this.timeoutId=setTimeout(this.handleStart,t.delay),this.handlePending(t);return}if(Nm(t)){this.handlePending(t);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,t){let{active:n,onPending:i}=this.props;i(n,e,this.initialCoordinates,t)}handleStart(){let{initialCoordinates:e}=this,{onStart:t}=this.props;e&&(this.activated=!0,this.documentListeners.add(Ir.Click,vk,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Ir.SelectionChange,this.removeTextSelection),t(e))}handleMove(e){var t;let{activated:n,initialCoordinates:i,props:s}=this,{onMove:o,options:{activationConstraint:a}}=s;if(!i)return;let l=(t=Ra(e))!=null?t:Qr,c=wi(i,l);if(!n&&a){if(Nm(a)){if(a.tolerance!=null&&vd(c,a.tolerance))return this.handleCancel();if(vd(c,a.distance))return this.handleStart()}if(Em(a)&&vd(c,a.tolerance))return this.handleCancel();this.handlePending(a,c);return}e.cancelable&&e.preventDefault(),o(l)}handleEnd(){let{onAbort:e,onEnd:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleCancel(){let{onAbort:e,onCancel:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleKeydown(e){e.code===ye.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}},wk={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}},fs=class extends oo{constructor(e){let{event:t}=e,n=xi(t.target);super(e,wk,n)}};fs.activators=[{eventName:"onPointerDown",handler:(r,e)=>{let{nativeEvent:t}=r,{onActivation:n}=e;return!t.isPrimary||t.button!==0?!1:(n?.({event:t}),!0)}}];var Sk={move:{name:"mousemove"},end:{name:"mouseup"}},Sd;(function(r){r[r.RightClick=2]="RightClick"})(Sd||(Sd={}));var Cd=class extends oo{constructor(e){super(e,Sk,xi(e.event.target))}};Cd.activators=[{eventName:"onMouseDown",handler:(r,e)=>{let{nativeEvent:t}=r,{onActivation:n}=e;return t.button===Sd.RightClick?!1:(n?.({event:t}),!0)}}];var yd={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}},kd=class extends oo{constructor(e){super(e,yd)}static setup(){return window.addEventListener(yd.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(yd.move.name,e)};function e(){}}};kd.activators=[{eventName:"onTouchStart",handler:(r,e)=>{let{nativeEvent:t}=r,{onActivation:n}=e,{touches:i}=t;return i.length>1?!1:(n?.({event:t}),!0)}}];var io;(function(r){r[r.Pointer=0]="Pointer",r[r.DraggableRect=1]="DraggableRect"})(io||(io={}));var Ba;(function(r){r[r.TreeOrder=0]="TreeOrder",r[r.ReversedTreeOrder=1]="ReversedTreeOrder"})(Ba||(Ba={}));function Ck(r){let{acceleration:e,activator:t=io.Pointer,canScroll:n,draggingRect:i,enabled:s,interval:o=5,order:a=Ba.TreeOrder,pointerCoordinates:l,scrollableAncestors:c,scrollableAncestorRects:d,delta:u,threshold:h}=r,f=Nk({delta:u,disabled:!s}),[p,m]=pm(),g=Tt({x:0,y:0}),b=Tt({x:0,y:0}),y=ft(()=>{switch(t){case io.Pointer:return l?{top:l.y,bottom:l.y,left:l.x,right:l.x}:null;case io.DraggableRect:return i}},[t,i,l]),x=Tt(null),N=Zr(()=>{let w=x.current;if(!w)return;let k=g.current.x*b.current.x,A=g.current.y*b.current.y;w.scrollBy(k,A)},[]),C=ft(()=>a===Ba.TreeOrder?[...c].reverse():c,[a,c]);dt(()=>{if(!s||!c.length||!y){m();return}for(let w of C){if(n?.(w)===!1)continue;let k=c.indexOf(w),A=d[k];if(!A)continue;let{direction:S,speed:M}=hk(w,A,y,e,h);for(let D of["x","y"])f[D][S[D]]||(M[D]=0,S[D]=0);if(M.x>0||M.y>0){m(),x.current=w,p(N,o),g.current=M,b.current=S;return}}g.current={x:0,y:0},b.current={x:0,y:0},m()},[e,N,n,m,s,o,JSON.stringify(y),JSON.stringify(f),p,c,C,d,JSON.stringify(h)])}var kk={x:{[St.Backward]:!1,[St.Forward]:!1},y:{[St.Backward]:!1,[St.Forward]:!1}};function Nk(r){let{delta:e,disabled:t}=r,n=Oa(e);return ds(i=>{if(t||!n||!i)return kk;let s={x:Math.sign(e.x-n.x),y:Math.sign(e.y-n.y)};return{x:{[St.Backward]:i.x[St.Backward]||s.x===-1,[St.Forward]:i.x[St.Forward]||s.x===1},y:{[St.Backward]:i.y[St.Backward]||s.y===-1,[St.Forward]:i.y[St.Forward]||s.y===1}}},[t,e,n])}function Ek(r,e){let t=e!=null?r.get(e):void 0,n=t?t.node.current:null;return ds(i=>{var s;return e==null?null:(s=n??i)!=null?s:null},[n,e])}function Ak(r,e){return ft(()=>r.reduce((t,n)=>{let{sensor:i}=n,s=i.activators.map(o=>({eventName:o.eventName,handler:e(o.handler,n)}));return[...t,...s]},[]),[r,e])}var ao;(function(r){r[r.Always=0]="Always",r[r.BeforeDragging=1]="BeforeDragging",r[r.WhileDragging=2]="WhileDragging"})(ao||(ao={}));var Nd;(function(r){r.Optimized="optimized"})(Nd||(Nd={}));var Am=new Map;function Tk(r,e){let{dragging:t,dependencies:n,config:i}=e,[s,o]=Xr(null),{frequency:a,measure:l,strategy:c}=i,d=Tt(r),u=g(),h=cs(u),f=Zr(function(b){b===void 0&&(b=[]),!h.current&&o(y=>y===null?b:y.concat(b.filter(x=>!y.includes(x))))},[h]),p=Tt(null),m=ds(b=>{if(u&&!t)return Am;if(!b||b===Am||d.current!==r||s!=null){let y=new Map;for(let x of r){if(!x)continue;if(s&&s.length>0&&!s.includes(x.id)&&x.rect.current){y.set(x.id,x.rect.current);continue}let N=x.node.current,C=N?new so(l(N),N):null;x.rect.current=C,C&&y.set(x.id,C)}return y}return b},[r,s,t,u,l]);return dt(()=>{d.current=r},[r]),dt(()=>{u||f()},[t,u]),dt(()=>{s&&s.length>0&&o(null)},[JSON.stringify(s)]),dt(()=>{u||typeof a!="number"||p.current!==null||(p.current=setTimeout(()=>{f(),p.current=null},a))},[a,u,f,...n]),{droppableRects:m,measureDroppableContainers:f,measuringScheduled:s!=null};function g(){switch(c){case ao.Always:return!1;case ao.BeforeDragging:return t;default:return!t}}}function qm(r,e){return ds(t=>r?t||(typeof e=="function"?e(r):r):null,[e,r])}function Mk(r,e){return qm(r,e)}function Dk(r){let{callback:e,disabled:t}=r,n=Da(e),i=ft(()=>{if(t||typeof window>"u"||typeof window.MutationObserver>"u")return;let{MutationObserver:s}=window;return new s(n)},[n,t]);return dt(()=>()=>i?.disconnect(),[i]),i}function Fa(r){let{callback:e,disabled:t}=r,n=Da(e),i=ft(()=>{if(t||typeof window>"u"||typeof window.ResizeObserver>"u")return;let{ResizeObserver:s}=window;return new s(n)},[t]);return dt(()=>()=>i?.disconnect(),[i]),i}function Ok(r){return new so(ki(r),r)}function Tm(r,e,t){e===void 0&&(e=Ok);let[n,i]=Xr(null);function s(){i(l=>{if(!r)return null;if(r.isConnected===!1){var c;return(c=l??t)!=null?c:null}let d=e(r);return JSON.stringify(l)===JSON.stringify(d)?l:d})}let o=Dk({callback(l){if(r)for(let c of l){let{type:d,target:u}=c;if(d==="childList"&&u instanceof HTMLElement&&u.contains(r)){s();break}}}}),a=Fa({callback:s});return Rr(()=>{s(),r?(a?.observe(r),o?.observe(document.body,{childList:!0,subtree:!0})):(a?.disconnect(),o?.disconnect())},[r]),n}function Rk(r){let e=qm(r);return zm(r,e)}var Mm=[];function Ik(r){let e=Tt(r),t=ds(n=>r?n&&n!==Mm&&r&&e.current&&r.parentNode===e.current.parentNode?n:co(r):Mm,[r]);return dt(()=>{e.current=r},[r]),t}function Pk(r){let[e,t]=Xr(null),n=Tt(r),i=Zr(s=>{let o=xd(s.target);o&&t(a=>a?(a.set(o,wd(o)),new Map(a)):null)},[]);return dt(()=>{let s=n.current;if(r!==s){o(s);let a=r.map(l=>{let c=xd(l);return c?(c.addEventListener("scroll",i,{passive:!0}),[c,wd(c)]):null}).filter(l=>l!=null);t(a.length?new Map(a):null),n.current=r}return()=>{o(r),o(s)};function o(a){a.forEach(l=>{let c=xd(l);c?.removeEventListener("scroll",i)})}},[i,r]),ft(()=>r.length?e?Array.from(e.values()).reduce((s,o)=>yi(s,o),Qr):Um(r):Qr,[r,e])}function Dm(r,e){e===void 0&&(e=[]);let t=Tt(null);return dt(()=>{t.current=null},e),dt(()=>{let n=r!==Qr;n&&!t.current&&(t.current=r),!n&&t.current&&(t.current=null)},[r]),t.current?wi(r,t.current):Qr}function Lk(r){dt(()=>{if(!to)return;let e=r.map(t=>{let{sensor:n}=t;return n.setup==null?void 0:n.setup()});return()=>{for(let t of e)t?.()}},r.map(e=>{let{sensor:t}=e;return t}))}function Bk(r,e){return ft(()=>r.reduce((t,n)=>{let{eventName:i,handler:s}=n;return t[i]=o=>{s(o,e)},t},{}),[r,e])}function Km(r){return ft(()=>r?lk(r):null,[r])}var Om=[];function Fk(r,e){e===void 0&&(e=ki);let[t]=r,n=Km(t?Xt(t):null),[i,s]=Xr(Om);function o(){s(()=>r.length?r.map(l=>Vm(l)?n:new so(e(l),l)):Om)}let a=Fa({callback:o});return Rr(()=>{a?.disconnect(),o(),r.forEach(l=>a?.observe(l))},[r]),i}function _k(r){if(!r)return null;if(r.children.length>1)return r;let e=r.children[0];return ls(e)?e:r}function zk(r){let{measure:e}=r,[t,n]=Xr(null),i=Zr(c=>{for(let{target:d}of c)if(ls(d)){n(u=>{let h=e(d);return u?{...u,width:h.width,height:h.height}:h});break}},[e]),s=Fa({callback:i}),o=Zr(c=>{let d=_k(c);s?.disconnect(),d&&s?.observe(d),n(d?e(d):null)},[e,s]),[a,l]=ro(o);return ft(()=>({nodeRef:a,rect:t,setRef:l}),[t,a,l])}var $k=[{sensor:fs,options:{}},{sensor:hs,options:{}}],Hk={current:{}},Pa={draggable:{measure:Cm},droppable:{measure:Cm,strategy:ao.WhileDragging,frequency:Nd.Optimized},dragOverlay:{measure:ki}},Ci=class extends Map{get(e){var t;return e!=null&&(t=super.get(e))!=null?t:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:t}=e;return!t})}getNodeFor(e){var t,n;return(t=(n=this.get(e))==null?void 0:n.node.current)!=null?t:void 0}},Wk={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ci,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:La},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Pa,measureDroppableContainers:La,windowRect:null,measuringScheduled:!1},Vk={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:La,draggableNodes:new Map,over:null,measureDroppableContainers:La},_a=lo(Vk),Ym=lo(Wk);function jk(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ci}}}function Uk(r,e){switch(e.type){case ht.DragStart:return{...r,draggable:{...r.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case ht.DragMove:return r.draggable.active==null?r:{...r,draggable:{...r.draggable,translate:{x:e.coordinates.x-r.draggable.initialCoordinates.x,y:e.coordinates.y-r.draggable.initialCoordinates.y}}};case ht.DragEnd:case ht.DragCancel:return{...r,draggable:{...r.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ht.RegisterDroppable:{let{element:t}=e,{id:n}=t,i=new Ci(r.droppable.containers);return i.set(n,t),{...r,droppable:{...r.droppable,containers:i}}}case ht.SetDroppableDisabled:{let{id:t,key:n,disabled:i}=e,s=r.droppable.containers.get(t);if(!s||n!==s.key)return r;let o=new Ci(r.droppable.containers);return o.set(t,{...s,disabled:i}),{...r,droppable:{...r.droppable,containers:o}}}case ht.UnregisterDroppable:{let{id:t,key:n}=e,i=r.droppable.containers.get(t);if(!i||n!==i.key)return r;let s=new Ci(r.droppable.containers);return s.delete(t),{...r,droppable:{...r.droppable,containers:s}}}default:return r}}function Gk(r){let{disabled:e}=r,{active:t,activatorEvent:n,draggableNodes:i}=us(_a),s=Oa(n),o=Oa(t?.id);return dt(()=>{if(!e&&!n&&s&&o!=null){if(!no(s)||document.activeElement===s.target)return;let a=i.get(o);if(!a)return;let{activatorNode:l,node:c}=a;if(!l.current&&!c.current)return;requestAnimationFrame(()=>{for(let d of[l.current,c.current]){if(!d)continue;let u=gm(d);if(u){u.focus();break}}})}},[n,e,i,o,s]),null}function qk(r,e){let{transform:t,...n}=e;return r!=null&&r.length?r.reduce((i,s)=>s({transform:i,...n}),t):t}function Kk(r){return ft(()=>({draggable:{...Pa.draggable,...r?.draggable},droppable:{...Pa.droppable,...r?.droppable},dragOverlay:{...Pa.dragOverlay,...r?.dragOverlay}}),[r?.draggable,r?.droppable,r?.dragOverlay])}function Yk(r){let{activeNode:e,measure:t,initialRect:n,config:i=!0}=r,s=Tt(!1),{x:o,y:a}=typeof i=="boolean"?{x:i,y:i}:i;Rr(()=>{if(!o&&!a||!e){s.current=!1;return}if(s.current||!n)return;let c=e?.node.current;if(!c||c.isConnected===!1)return;let d=t(c),u=zm(d,n);if(o||(u.x=0),a||(u.y=0),s.current=!0,Math.abs(u.x)>0||Math.abs(u.y)>0){let h=$m(c);h&&h.scrollBy({top:u.y,left:u.x})}},[e,o,a,n,t])}var Jm=lo({...Qr,scaleX:1,scaleY:1}),Zn;(function(r){r[r.Uninitialized=0]="Uninitialized",r[r.Initializing=1]="Initializing",r[r.Initialized=2]="Initialized"})(Zn||(Zn={}));var Xm=UC(function(e){var t,n,i,s;let{id:o,accessibility:a,autoScroll:l=!0,children:c,sensors:d=$k,collisionDetection:u=tk,measuring:h,modifiers:f,...p}=e,m=GC(Uk,void 0,jk),[g,b]=m,[y,x]=YC(),[N,C]=Xr(Zn.Uninitialized),w=N===Zn.Initialized,{draggable:{active:k,nodes:A,translate:S},droppable:{containers:M}}=g,D=k!=null?A.get(k):null,O=Tt({initial:null,translated:null}),H=ft(()=>{var We;return k!=null?{id:k,data:(We=D?.data)!=null?We:Hk,rect:O}:null},[k,D]),E=Tt(null),[$,G]=Xr(null),[W,he]=Xr(null),_=cs(p,Object.values(p)),ie=vi("DndDescribedBy",o),Se=ft(()=>M.getEnabled(),[M]),J=Kk(h),{droppableRects:ae,measureDroppableContainers:fe,measuringScheduled:Oe}=Tk(Se,{dragging:w,dependencies:[S.x,S.y],config:J.droppable}),_e=Ek(A,k),ke=ft(()=>W?Ra(W):null,[W]),B=qr(),re=Mk(_e,J.draggable.measure);Yk({activeNode:k!=null?A.get(k):null,config:B.layoutShiftCompensation,initialRect:re,measure:J.draggable.measure});let X=Tm(_e,J.draggable.measure,re),me=Tm(_e?_e.parentElement:null),Ae=Tt({activatorEvent:null,active:null,activeNode:_e,collisionRect:null,collisions:null,droppableRects:ae,draggableNodes:A,draggingNode:null,draggingNodeRect:null,droppableContainers:M,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),bt=M.getNodeFor((t=Ae.current.over)==null?void 0:t.id),xt=zk({measure:J.dragOverlay.measure}),Ur=(n=xt.nodeRef.current)!=null?n:_e,qt=w?(i=xt.rect)!=null?i:X:null,Ji=!!(xt.nodeRef.current&&xt.rect),hr=Rk(Ji?null:X),Er=Km(Ur?Xt(Ur):null),rr=Ik(w?bt??_e:null),Ar=Fk(rr),fn=qk(f,{transform:{x:S.x-hr.x,y:S.y-hr.y,scaleX:1,scaleY:1},activatorEvent:W,active:H,activeNodeRect:X,containerNodeRect:me,draggingNodeRect:qt,over:Ae.current.over,overlayNodeRect:xt.rect,scrollableAncestors:rr,scrollableAncestorRects:Ar,windowRect:Er}),Gr=ke?yi(ke,S):null,Tr=Pk(rr),js=Dm(Tr),_t=Dm(Tr,[X]),Ce=yi(fn,js),ct=qt?ik(qt,fn):null,Dn=H&&ct?u({active:H,collisionRect:ct,droppableRects:ae,droppableContainers:Se,pointerCoordinates:Gr}):null,On=Ad(Dn,"id"),[Mr,Un]=Xr(null),pn=Ji?fn:yi(fn,_t),vt=rk(pn,(s=Mr?.rect)!=null?s:null,X),I=Tt(null),j=Zr((We,ze)=>{let{sensor:Kt,options:se}=ze;if(E.current==null)return;let ge=A.get(E.current);if(!ge)return;let ve=We.nativeEvent,et=new Kt({active:E.current,activeNode:ge,event:ve,options:se,context:Ae,onAbort(Ue){if(!A.get(Ue))return;let{onDragAbort:tt}=_.current,wt={id:Ue};tt?.(wt),y({type:"onDragAbort",event:wt})},onPending(Ue,zt,tt,wt){if(!A.get(Ue))return;let{onDragPending:Gs}=_.current,Gn={id:Ue,constraint:zt,initialCoordinates:tt,offset:wt};Gs?.(Gn),y({type:"onDragPending",event:Gn})},onStart(Ue){let zt=E.current;if(zt==null)return;let tt=A.get(zt);if(!tt)return;let{onDragStart:wt}=_.current,Us={activatorEvent:ve,active:{id:zt,data:tt.data,rect:O}};Ia(()=>{wt?.(Us),C(Zn.Initializing),b({type:ht.DragStart,initialCoordinates:Ue,active:zt}),y({type:"onDragStart",event:Us}),G(I.current),he(ve)})},onMove(Ue){b({type:ht.DragMove,coordinates:Ue})},onEnd:yt(ht.DragEnd),onCancel:yt(ht.DragCancel)});I.current=et;function yt(Ue){return async function(){let{active:tt,collisions:wt,over:Us,scrollAdjustedTranslate:Gs}=Ae.current,Gn=null;if(tt&&Gs){let{cancelDrop:qs}=_.current;Gn={activatorEvent:ve,active:tt,collisions:wt,delta:Gs,over:Us},Ue===ht.DragEnd&&typeof qs=="function"&&await Promise.resolve(qs(Gn))&&(Ue=ht.DragCancel)}E.current=null,Ia(()=>{b({type:Ue}),C(Zn.Uninitialized),Un(null),G(null),he(null),I.current=null;let qs=Ue===ht.DragEnd?"onDragEnd":"onDragCancel";if(Gn){let Wc=_.current[qs];Wc?.(Gn),y({type:qs,event:Gn})}})}}},[A]),V=Zr((We,ze)=>(Kt,se)=>{let ge=Kt.nativeEvent,ve=A.get(se);if(E.current!==null||!ve||ge.dndKit||ge.defaultPrevented)return;let et={active:ve};We(Kt,ze.options,et)===!0&&(ge.dndKit={capturedBy:ze.sensor},E.current=se,j(Kt,ze))},[A,j]),z=Ak(d,V);Lk(d),Rr(()=>{X&&N===Zn.Initializing&&C(Zn.Initialized)},[X,N]),dt(()=>{let{onDragMove:We}=_.current,{active:ze,activatorEvent:Kt,collisions:se,over:ge}=Ae.current;if(!ze||!Kt)return;let ve={active:ze,activatorEvent:Kt,collisions:se,delta:{x:Ce.x,y:Ce.y},over:ge};Ia(()=>{We?.(ve),y({type:"onDragMove",event:ve})})},[Ce.x,Ce.y]),dt(()=>{let{active:We,activatorEvent:ze,collisions:Kt,droppableContainers:se,scrollAdjustedTranslate:ge}=Ae.current;if(!We||E.current==null||!ze||!ge)return;let{onDragOver:ve}=_.current,et=se.get(On),yt=et&&et.rect.current?{id:et.id,rect:et.rect.current,data:et.data,disabled:et.disabled}:null,Ue={active:We,activatorEvent:ze,collisions:Kt,delta:{x:ge.x,y:ge.y},over:yt};Ia(()=>{Un(yt),ve?.(Ue),y({type:"onDragOver",event:Ue})})},[On]),Rr(()=>{Ae.current={activatorEvent:W,active:H,activeNode:_e,collisionRect:ct,collisions:Dn,droppableRects:ae,draggableNodes:A,draggingNode:Ur,draggingNodeRect:qt,droppableContainers:M,over:Mr,scrollableAncestors:rr,scrollAdjustedTranslate:Ce},O.current={initial:qt,translated:ct}},[H,_e,Dn,ct,A,Ur,qt,ae,M,Mr,rr,Ce]),Ck({...B,delta:S,draggingRect:ct,pointerCoordinates:Gr,scrollableAncestors:rr,scrollableAncestorRects:Ar});let be=ft(()=>({active:H,activeNode:_e,activeNodeRect:X,activatorEvent:W,collisions:Dn,containerNodeRect:me,dragOverlay:xt,draggableNodes:A,droppableContainers:M,droppableRects:ae,over:Mr,measureDroppableContainers:fe,scrollableAncestors:rr,scrollableAncestorRects:Ar,measuringConfiguration:J,measuringScheduled:Oe,windowRect:Er}),[H,_e,X,W,Dn,me,xt,A,M,ae,Mr,fe,rr,Ar,J,Oe,Er]),He=ft(()=>({activatorEvent:W,activators:z,active:H,activeNodeRect:X,ariaDescribedById:{draggable:ie},dispatch:b,draggableNodes:A,over:Mr,measureDroppableContainers:fe}),[W,z,H,X,b,ie,A,Mr,fe]);return bn.createElement(Im.Provider,{value:x},bn.createElement(_a.Provider,{value:He},bn.createElement(Ym.Provider,{value:be},bn.createElement(Jm.Provider,{value:vt},c)),bn.createElement(Gk,{disabled:a?.restoreFocus===!1})),bn.createElement(ZC,{...a,hiddenTextDescribedById:ie}));function qr(){let We=$?.autoScrollEnabled===!1,ze=typeof l=="object"?l.enabled===!1:l===!1,Kt=w&&!We&&!ze;return typeof l=="object"?{...l,enabled:Kt}:{enabled:Kt}}}),Jk=lo(null),Rm="button",Xk="Draggable";function Zm(r){let{id:e,data:t,disabled:n=!1,attributes:i}=r,s=vi(Xk),{activators:o,activatorEvent:a,active:l,activeNodeRect:c,ariaDescribedById:d,draggableNodes:u,over:h}=us(_a),{role:f=Rm,roleDescription:p="draggable",tabIndex:m=0}=i??{},g=l?.id===e,b=us(g?Jm:Jk),[y,x]=ro(),[N,C]=ro(),w=Bk(o,e),k=cs(t);Rr(()=>(u.set(e,{id:e,key:s,node:y,activatorNode:N,data:k}),()=>{let S=u.get(e);S&&S.key===s&&u.delete(e)}),[u,e]);let A=ft(()=>({role:f,tabIndex:m,"aria-disabled":n,"aria-pressed":g&&f===Rm?!0:void 0,"aria-roledescription":p,"aria-describedby":d.draggable}),[n,f,m,g,p,d.draggable]);return{active:l,activatorEvent:a,activeNodeRect:c,attributes:A,isDragging:g,listeners:n?void 0:w,node:y,over:h,setNodeRef:x,setActivatorNodeRef:C,transform:b}}function Qm(){return us(Ym)}var Zk="Droppable",Qk={timeout:25};function eg(r){let{data:e,disabled:t=!1,id:n,resizeObserverConfig:i}=r,s=vi(Zk),{active:o,dispatch:a,over:l,measureDroppableContainers:c}=us(_a),d=Tt({disabled:t}),u=Tt(!1),h=Tt(null),f=Tt(null),{disabled:p,updateMeasurementsFor:m,timeout:g}={...Qk,...i},b=cs(m??n),y=Zr(()=>{if(!u.current){u.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{c(Array.isArray(b.current)?b.current:[b.current]),f.current=null},g)},[g]),x=Fa({callback:y,disabled:p||!o}),N=Zr((A,S)=>{x&&(S&&(x.unobserve(S),u.current=!1),A&&x.observe(A))},[x]),[C,w]=ro(N),k=cs(e);return dt(()=>{!x||!C.current||(x.disconnect(),u.current=!1,x.observe(C.current))},[C,x]),dt(()=>(a({type:ht.RegisterDroppable,element:{id:n,key:s,disabled:t,node:C,rect:h,data:k}}),()=>a({type:ht.UnregisterDroppable,key:s,id:n})),[n]),dt(()=>{t!==d.current.disabled&&(a({type:ht.SetDroppableDisabled,id:n,key:s,disabled:t}),d.current.disabled=t)},[n,s,t,a]),{active:o,rect:h,isOver:l?.id===n,node:C,over:l,setNodeRef:w}}import tg,{useMemo as Ha,useRef as Td,useEffect as Wa,useState as eN,useContext as tN}from"react";function rg(r,e,t){let n=r.slice();return n.splice(t<0?n.length+t:t,0,n.splice(e,1)[0]),n}function rN(r,e){return r.reduce((t,n,i)=>{let s=e.get(n);return s&&(t[i]=s),t},Array(r.length))}function za(r){return r!==null&&r>=0}function nN(r,e){if(r===e)return!0;if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function iN(r){return typeof r=="boolean"?{draggable:r,droppable:r}:r}var ng=r=>{let{rects:e,activeIndex:t,overIndex:n,index:i}=r,s=rg(e,n,t),o=e[i],a=s[i];return!a||!o?null:{x:a.left-o.left,y:a.top-o.top,scaleX:a.width/o.width,scaleY:a.height/o.height}};var $a={scaleX:1,scaleY:1},ig=r=>{var e;let{activeIndex:t,activeNodeRect:n,index:i,rects:s,overIndex:o}=r,a=(e=s[t])!=null?e:n;if(!a)return null;if(i===t){let c=s[o];return c?{x:0,y:t<o?c.top+c.height-(a.top+a.height):c.top-a.top,...$a}:null}let l=sN(s,i,t);return i>t&&i<=o?{x:0,y:-a.height-l,...$a}:i<t&&i>=o?{x:0,y:a.height+l,...$a}:{x:0,y:0,...$a}};function sN(r,e,t){let n=r[e],i=r[e-1],s=r[e+1];return n?t<e?i?n.top-(i.top+i.height):s?s.top-(n.top+n.height):0:s?s.top-(n.top+n.height):i?n.top-(i.top+i.height):0:0}var sg="Sortable",og=tg.createContext({activeIndex:-1,containerId:sg,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:ng,disabled:{draggable:!1,droppable:!1}});function ag(r){let{children:e,id:t,items:n,strategy:i=ng,disabled:s=!1}=r,{active:o,dragOverlay:a,droppableRects:l,over:c,measureDroppableContainers:d}=Qm(),u=vi(sg,t),h=a.rect!==null,f=Ha(()=>n.map(w=>typeof w=="object"&&"id"in w?w.id:w),[n]),p=o!=null,m=o?f.indexOf(o.id):-1,g=c?f.indexOf(c.id):-1,b=Td(f),y=!nN(f,b.current),x=g!==-1&&m===-1||y,N=iN(s);Rr(()=>{y&&p&&d(f)},[y,f,p,d]),Wa(()=>{b.current=f},[f]);let C=Ha(()=>({activeIndex:m,containerId:u,disabled:N,disableTransforms:x,items:f,overIndex:g,useDragOverlay:h,sortedRects:rN(f,l),strategy:i}),[m,u,N.draggable,N.droppable,x,f,g,l,h,i]);return tg.createElement(og.Provider,{value:C},e)}var oN=r=>{let{id:e,items:t,activeIndex:n,overIndex:i}=r;return rg(t,n,i).indexOf(e)},aN=r=>{let{containerId:e,isSorting:t,wasDragging:n,index:i,items:s,newIndex:o,previousItems:a,previousContainerId:l,transition:c}=r;return!c||!n||a!==s&&i===o?!1:t?!0:o!==i&&e===l},lN={duration:200,easing:"ease"},lg="transform",cN=Xn.Transition.toString({property:lg,duration:0,easing:"linear"}),dN={roleDescription:"sortable"};function uN(r){let{disabled:e,index:t,node:n,rect:i}=r,[s,o]=eN(null),a=Td(t);return Rr(()=>{if(!e&&t!==a.current&&n.current){let l=i.current;if(l){let c=ki(n.current,{ignoreTransform:!0}),d={x:l.left-c.left,y:l.top-c.top,scaleX:l.width/c.width,scaleY:l.height/c.height};(d.x||d.y)&&o(d)}}t!==a.current&&(a.current=t)},[e,t,n,i]),Wa(()=>{s&&o(null)},[s]),s}function cg(r){let{animateLayoutChanges:e=aN,attributes:t,disabled:n,data:i,getNewIndex:s=oN,id:o,strategy:a,resizeObserverConfig:l,transition:c=lN}=r,{items:d,containerId:u,activeIndex:h,disabled:f,disableTransforms:p,sortedRects:m,overIndex:g,useDragOverlay:b,strategy:y}=tN(og),x=hN(n,f),N=d.indexOf(o),C=Ha(()=>({sortable:{containerId:u,index:N,items:d},...i}),[u,i,N,d]),w=Ha(()=>d.slice(d.indexOf(o)),[d,o]),{rect:k,node:A,isOver:S,setNodeRef:M}=eg({id:o,data:C,disabled:x.droppable,resizeObserverConfig:{updateMeasurementsFor:w,...l}}),{active:D,activatorEvent:O,activeNodeRect:H,attributes:E,setNodeRef:$,listeners:G,isDragging:W,over:he,setActivatorNodeRef:_,transform:ie}=Zm({id:o,data:C,attributes:{...dN,...t},disabled:x.draggable}),Se=fm(M,$),J=!!D,ae=J&&!p&&za(h)&&za(g),fe=!b&&W,Oe=fe&&ae?ie:null,ke=ae?Oe??(a??y)({rects:m,activeNodeRect:H,activeIndex:h,overIndex:g,index:N}):null,B=za(h)&&za(g)?s({id:o,items:d,activeIndex:h,overIndex:g}):N,re=D?.id,X=Td({activeId:re,items:d,newIndex:B,containerId:u}),me=d!==X.current.items,Ae=e({active:D,containerId:u,isDragging:W,isSorting:J,id:o,index:N,items:d,newIndex:X.current.newIndex,previousItems:X.current.items,previousContainerId:X.current.containerId,transition:c,wasDragging:X.current.activeId!=null}),bt=uN({disabled:!Ae,index:N,node:A,rect:k});return Wa(()=>{J&&X.current.newIndex!==B&&(X.current.newIndex=B),u!==X.current.containerId&&(X.current.containerId=u),d!==X.current.items&&(X.current.items=d)},[J,B,u,d]),Wa(()=>{if(re===X.current.activeId)return;if(re&&!X.current.activeId){X.current.activeId=re;return}let Ur=setTimeout(()=>{X.current.activeId=re},50);return()=>clearTimeout(Ur)},[re]),{active:D,activeIndex:h,attributes:E,data:C,rect:k,index:N,newIndex:B,items:d,isOver:S,isSorting:J,isDragging:W,listeners:G,node:A,overIndex:g,over:he,setNodeRef:Se,setActivatorNodeRef:_,setDroppableNodeRef:M,setDraggableNodeRef:$,transform:bt??ke,transition:xt()};function xt(){if(bt||me&&X.current.newIndex===N)return cN;if(!(fe&&!no(O)||!c)&&(J||Ae))return Xn.Transition.toString({...c,property:lg})}}function hN(r,e){var t,n;return typeof r=="boolean"?{draggable:r,droppable:!1}:{draggable:(t=r?.draggable)!=null?t:e.draggable,droppable:(n=r?.droppable)!=null?n:e.droppable}}function Va(r){if(!r)return!1;let e=r.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}var fN=[ye.Down,ye.Right,ye.Up,ye.Left],dg=(r,e)=>{let{context:{active:t,collisionRect:n,droppableRects:i,droppableContainers:s,over:o,scrollableAncestors:a}}=e;if(fN.includes(r.code)){if(r.preventDefault(),!t||!n)return;let l=[];s.getEnabled().forEach(u=>{if(!u||u!=null&&u.disabled)return;let h=i.get(u.id);if(h)switch(r.code){case ye.Down:n.top<h.top&&l.push(u);break;case ye.Up:n.top>h.top&&l.push(u);break;case ye.Left:n.left>h.left&&l.push(u);break;case ye.Right:n.left<h.left&&l.push(u);break}});let c=_m({active:t,collisionRect:n,droppableRects:i,droppableContainers:l,pointerCoordinates:null}),d=Ad(c,"id");if(d===o?.id&&c.length>1&&(d=c[1].id),d!=null){let u=s.get(t.id),h=s.get(d),f=h?i.get(h.id):null,p=h?.node.current;if(p&&f&&u&&h){let g=co(p).some((w,k)=>a[k]!==w),b=ug(u,h),y=pN(u,h),x=g||!b?{x:0,y:0}:{x:y?n.width-f.width:0,y:y?n.height-f.height:0},N={x:f.left,y:f.top};return x.x&&x.y?N:wi(N,x)}}}};function ug(r,e){return!Va(r)||!Va(e)?!1:r.data.current.sortable.containerId===e.data.current.sortable.containerId}function pN(r,e){return!Va(r)||!Va(e)||!ug(r,e)?!1:r.data.current.sortable.index<e.data.current.sortable.index}import{Phone as mN,Calendar as gN,Ruler as bN,User as fg}from"lucide-react";import{jsx as Ke,jsxs as Je}from"react/jsx-runtime";var Dd=[{id:"DISE\xD1O",title:"Dise\xF1o",color:"bg-blue-500/10 border-blue-500/20 text-blue-700 dark:text-blue-400",coordinator:"Paola"},{id:"OPTIMIZACION",title:"Optimizaci\xF3n y Fact.",color:"bg-purple-500/10 border-purple-500/20 text-purple-700 dark:text-purple-400",coordinator:"Diego"},{id:"CAJA",title:"Caja",color:"bg-yellow-500/10 border-yellow-500/20 text-yellow-700 dark:text-yellow-400",coordinator:"Gloria"},{id:"PRODUCCION",title:"Producci\xF3n",color:"bg-orange-500/10 border-orange-500/20 text-orange-700 dark:text-orange-400",coordinator:"Gabriel, Diego"},{id:"DESPACHO",title:"Despacho",color:"bg-green-500/10 border-green-500/20 text-green-700 dark:text-green-400",coordinator:"Manuel"},{id:"ENTREGADO",title:"Entregado",color:"bg-teal-500/10 border-teal-500/20 text-teal-700 dark:text-teal-400",coordinator:"Local"}];function xN({order:r}){let{attributes:e,listeners:t,setNodeRef:n,transform:i,transition:s,isDragging:o}=cg({id:r.id}),a={transform:Xn.Transform.toString(i),transition:s,zIndex:o?10:1,opacity:o?.5:1};return Je("div",{ref:n,style:a,...e,...t,className:"bg-surface-secondary p-3 rounded-xl shadow-sm lg:shadow border border-border-default mb-3 cursor-grab active:cursor-grabbing hover:border-border-hover hover:shadow-md transition-all group",children:[Je("div",{className:"flex justify-between items-start mb-2",children:[Je("div",{className:"flex flex-col",children:[Ke("span",{className:"font-bold text-text-primary text-sm",children:r.id}),r.rawStage&&Ke("span",{className:"text-[9px] uppercase tracking-wider text-text-tertiary mt-0.5 font-bold",children:r.rawStage.replace(/_/g," ")})]}),Je("span",{className:"text-[10px] font-medium px-2 py-0.5 bg-surface-tertiary rounded-full text-text-secondary border border-border-default",children:[r.material.substring(0,15),"..."]})]}),Je("div",{className:"space-y-1.5 text-xs text-text-secondary",children:[Je("div",{className:"flex items-center gap-2",children:[Ke(fg,{size:13,className:"text-text-tertiary"}),Ke("span",{className:"truncate",children:r.client})]}),Je("div",{className:"flex items-center gap-2",children:[Ke(bN,{size:13,className:"text-text-tertiary"}),Ke("span",{children:r.measurements})]}),Je("div",{className:"flex items-center gap-2",children:[Ke(gN,{size:13,className:"text-text-tertiary"}),Ke("span",{children:r.createdAt})]}),Je("div",{className:"flex items-center gap-2 cursor-pointer hover:bg-surface-tertiary p-1 -ml-1 rounded transition-colors group/phone mt-1",onClick:l=>{l.stopPropagation(),typeof window<"u"&&window.dispatchEvent(new CustomEvent("studio:open-plugin",{detail:{pluginId:"chameleon"}}))},title:"Abrir WhatsApp Studio",children:[Ke(mN,{size:13,className:"text-green-500 group-hover/phone:animate-pulse"}),Ke("span",{className:"text-green-600 dark:text-green-400 font-medium group-hover/phone:underline",children:r.whatsapp})]})]})]})}function ja(){let{orders:r,updateStatus:e}=pr(),[t,n]=Md(!1),[i,s]=Md(""),o=["DISE\xD1O","OPTIMIZACION","CAJA","PRODUCCION","DESPACHO"],[a,l]=Md(()=>{if(typeof window<"u"){let h=localStorage.getItem("mf_kanban_cols");if(h)return JSON.parse(h)}return o});hg(()=>{localStorage.setItem("mf_kanban_cols",JSON.stringify(a))},[a]),hg(()=>{let h=f=>{f.detail?.query&&(s(f.detail.query),window.dispatchEvent(new CustomEvent("studio:open-plugin",{detail:{pluginId:"chameleon",viewId:"chameleon-kanban-view"}})))};return window.addEventListener("studio:search-order",h),()=>window.removeEventListener("studio:search-order",h)},[]);let c=h=>{l(f=>f.includes(h)?f.filter(p=>p!==h):[...f,h])},d=Pm(Ed(fs,{activationConstraint:{distance:5}}),Ed(hs,{coordinateGetter:dg})),u=async h=>{let{active:f,over:p}=h;if(!p)return;let m=f.id,g=p.id,b=r.find(N=>N.id===m);if(!b)return;let y=null,x=Dd.find(N=>N.id===g);if(x)y=x.id;else{let N=r.find(C=>C.id===g);N&&(y=N.status)}y&&b.status!==y&&e(b.id,y)};return Je("div",{className:"h-full w-full bg-transparent p-4 flex flex-col overflow-hidden min-h-0 relative",children:[Je("div",{className:"flex justify-between items-center mb-4 shrink-0",children:[Je("h2",{className:"text-lg font-bold text-text-primary flex items-center gap-2",children:["Kanban de Pedidos",Je("span",{className:"text-xs bg-brand-primary/10 text-brand-primary px-2 py-0.5 rounded-full border border-brand-primary/20",children:[r.length," Totales"]})]}),Je("div",{className:"flex items-center gap-3 relative",children:[Je("div",{className:"relative flex items-center",children:[Ke("input",{type:"text",placeholder:"Buscar pedido, cliente...",value:i,onChange:h=>s(h.target.value),className:"pl-3 pr-8 py-1.5 w-64 bg-surface-secondary border border-border-default rounded-lg text-sm text-text-primary placeholder:text-text-muted focus:outline-none focus:border-brand-primary/50 transition-colors"}),i&&Ke("button",{onClick:()=>s(""),className:"absolute right-2 text-text-muted hover:text-text-primary",children:"\u2715"})]}),Je("button",{onClick:()=>n(!t),className:"flex items-center gap-2 px-3 py-1.5 bg-surface-secondary border border-border-default rounded-lg text-sm font-medium text-text-secondary hover:text-text-primary transition-colors",children:["Filtros ",Ke("span",{className:"opacity-50",children:"\u25BE"})]}),t&&Je("div",{className:"absolute right-0 top-full mt-2 w-56 bg-surface-elevated border border-border-default shadow-xl rounded-xl p-3 z-50",children:[Ke("h3",{className:"text-xs font-bold text-text-secondary uppercase mb-2",children:"Columnas Visibles"}),Ke("div",{className:"flex flex-col gap-1.5",children:Dd.map(h=>Je("label",{className:"flex items-center gap-2 text-sm text-text-primary cursor-pointer hover:bg-surface-tertiary p-1.5 rounded-md transition-colors",children:[Ke("input",{type:"checkbox",className:"rounded border-border-default bg-surface-secondary text-brand-primary focus:ring-brand-primary/50",checked:a.includes(h.id),onChange:()=>c(h.id)}),h.title]},h.id))})]})]})]}),Ke(Xm,{sensors:d,collisionDetection:Fm,onDragEnd:u,children:Ke("div",{className:"flex-1 min-h-0 flex gap-6 overflow-x-auto pb-4 pr-4 scrollbar-thin",children:Dd.filter(h=>a.includes(h.id)).map(h=>{let f=r.filter(g=>{if(g.status!==h.id)return!1;if(i){let b=i.toLowerCase();return g.id.toLowerCase().includes(b)||g.client.toLowerCase().includes(b)||g.whatsapp.toLowerCase().includes(b)||g.material.toLowerCase().includes(b)}return!0}),p=100,m=f.slice(0,p);return Je("div",{className:"flex flex-col shrink-0 w-[280px] bg-surface-primary/30 rounded-2xl border border-border-default overflow-hidden",children:[Je("div",{className:`p-3 border-b border-border-default ${h.color}`,children:[Ke("h2",{className:"font-bold text-base",children:h.title}),Je("p",{className:"text-[10px] opacity-80 mt-0.5 flex items-center gap-1 uppercase tracking-wider font-semibold",children:[Ke(fg,{size:10})," ",h.coordinator]}),Je("div",{className:"mt-2 text-xs font-medium bg-black/5 dark:bg-white/10 px-2 py-0.5 rounded-md inline-block",children:[f.length," pedidos"]})]}),Ke("div",{className:"flex-1 p-4 overflow-y-auto min-h-0",children:Ke(ag,{id:h.id,items:m.map(g=>g.id),strategy:ig,children:Je("div",{className:"min-h-[100px] h-full flex flex-col gap-0 pb-10",children:[m.map(g=>Ke(xN,{order:g},g.id)),f.length>p&&Je("div",{className:"p-3 mt-2 text-center text-xs font-medium text-text-tertiary bg-surface-tertiary/50 rounded-xl border border-border-subtle border-dashed",children:["+ ",f.length-p," pedidos ocultos",Ke("br",{}),Ke("span",{className:"text-[10px] text-brand-primary opacity-80 mt-1 inline-block",children:"Usa el buscador para filtrar"})]})]})})})]},h.id)})})})]})}import{Download as vN,FileSpreadsheet as yN}from"lucide-react";import{jsx as ps,jsxs as uo}from"react/jsx-runtime";function Ua(){let{orders:r}=pr(),{searchTerm:e,setSearchTerm:t}=Ea(),n=a=>a.normalize("NFD").replace(/[\u0300-\u036f]/g,"").toLowerCase(),i=n(e),s=r.filter(a=>n(a.id).includes(i)||n(a.client).includes(i)||n(a.status).includes(i));return uo("div",{className:"h-full w-full bg-white p-8 flex flex-col",children:[uo("div",{className:"flex items-center justify-between mb-8",children:[uo("div",{children:[uo("h1",{className:"text-3xl font-bold text-gray-800 flex items-center gap-3",children:[ps(yN,{className:"text-green-600",size:32}),"Historial de Pedidos"]}),ps("p",{className:"text-gray-500 mt-2",children:"Registro completo de operaciones Madefront."})]}),ps("div",{className:"flex items-center gap-4",children:uo("button",{onClick:()=>{if(r.length===0)return;let a=["N\xBA Pedido","Urgente","Cliente","WhatsApp","Material","L\xE1minas","M\xE1quina","Estado","Pagado","SLA (Horas)","Fecha Creaci\xF3n"],l=r.map(f=>[f.id,f.isUrgent?"SI":"NO",`"${f.client}"`,f.whatsapp,`"${f.material}"`,f.sheets.toString(),f.machine,f.status,f.isPaid?"SI":"NO",f.slaHours.toString(),f.createdAt]),c=[a.join(","),...l.map(f=>f.join(","))].join(`
25
+ `),d=new Blob([c],{type:"text/csv;charset=utf-8;"}),u=URL.createObjectURL(d),h=document.createElement("a");h.setAttribute("href",u),h.setAttribute("download",`Madefront_Historial_${new Date().toISOString().split("T")[0]}.csv`),document.body.appendChild(h),h.click(),document.body.removeChild(h)},className:"flex items-center gap-2 px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 font-medium transition-colors shadow-sm active:scale-95",children:[ps(vN,{size:18}),"Descargar CSV"]})})]}),ps("div",{className:"flex-1 bg-white border border-gray-200 rounded-xl shadow-sm overflow-hidden flex flex-col",children:ps("iframe",{src:`https://docs.google.com/spreadsheets/d/${import.meta.env?.VITE_GOOGLE_SHEETS_ID||"1tu_YDOYiYeyWlw5_xqC5DHIsVB2bQdu1vCV3tCNoAYI"}/edit?rm=minimal`,className:"w-full h-full border-0",title:"Google Sheets Viewer",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]})}import{jsx as Mt,jsxs as mr}from"react/jsx-runtime";var pg=()=>{let{createOrder:r}=pr(),{logout:e}=Jn(),{currentView:t,setCurrentView:n}=Ea(),[i,s]=wN({client:"",whatsapp:"",material:"",sheets:"1",measurements:"Adjunto"});SN(()=>{t!=="madefront_kanban"&&t!=="madefront_excel"&&n("madefront_kanban")},[t,n]);let o=a=>{a.preventDefault(),r(i),Te.success("Pedido Creado",{description:`El pedido para ${i.client} fue enviado a Dise\xF1o/Caja.`}),s({client:"",whatsapp:"",material:"",sheets:"1",measurements:"Adjunto"})};return mr("div",{className:"h-screen w-full bg-blue-50/50 font-sans text-slate-800 flex flex-col",children:[mr("header",{className:"bg-white px-8 py-4 border-b border-blue-100 flex justify-between items-center z-10 shadow-sm shrink-0",children:[mr("h1",{className:"text-xl font-bold text-blue-900 flex items-center gap-2",children:[Mt(NN,{className:"text-blue-500"})," Gerencia & Ventas"]}),mr("div",{className:"flex bg-slate-100 p-1 rounded-xl",children:[Mt("button",{onClick:()=>n("madefront_kanban"),className:`px-4 py-2 rounded-lg text-sm font-bold transition-all ${t==="madefront_kanban"?"bg-white shadow-sm text-blue-600":"text-slate-500 hover:text-slate-700"}`,children:"Kanban Operativo"}),mr("button",{onClick:()=>n("madefront_excel"),className:`px-4 py-2 rounded-lg text-sm font-bold transition-all flex items-center gap-2 ${t==="madefront_excel"?"bg-white shadow-sm text-green-600":"text-slate-500 hover:text-slate-700"}`,children:[Mt(EN,{size:16})," Datos"]})]}),mr("button",{onClick:e,className:"text-sm text-slate-500 hover:text-blue-600 flex items-center gap-2 bg-slate-100 px-4 py-2 rounded-lg",children:[Mt(kN,{size:16})," Salir"]})]}),Mt("main",{className:"flex-1 overflow-hidden flex flex-col w-full relative",children:t==="madefront_kanban"?mr("div",{className:"flex-1 flex flex-col p-4 md:p-6 overflow-hidden",children:[mr("div",{className:"mb-4 bg-white p-4 rounded-2xl shadow-sm border border-blue-100 flex gap-4 items-end shrink-0 overflow-x-auto",children:[mr("div",{className:"flex-1 min-w-[200px]",children:[Mt("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:"Cliente Nuevo"}),Mt("input",{className:"w-full bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 text-sm",value:i.client,onChange:a=>s({...i,client:a.target.value}),placeholder:"Ej: Arq. Juan..."})]}),mr("div",{className:"w-40 shrink-0",children:[Mt("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:"Tel\xE9fono"}),Mt("input",{className:"w-full bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 text-sm",value:i.whatsapp,onChange:a=>s({...i,whatsapp:a.target.value}),placeholder:"300..."})]}),mr("div",{className:"w-24 shrink-0",children:[Mt("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:"L\xE1minas"}),Mt("input",{type:"number",className:"w-full bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 text-sm",value:i.sheets,onChange:a=>s({...i,sheets:a.target.value})})]}),mr("div",{className:"w-48 shrink-0",children:[Mt("label",{className:"text-[10px] font-bold text-slate-400 uppercase",children:"Material"}),Mt("input",{className:"w-full bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 text-sm",value:i.material,onChange:a=>s({...i,material:a.target.value}),placeholder:"Ej: RH 15mm"})]}),mr("button",{onClick:o,className:"bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-6 rounded-lg shadow-md transition-all flex items-center gap-2 shrink-0 h-[38px]",children:[Mt(CN,{size:16})," Crear"]})]}),Mt("div",{className:"flex-1 min-h-0 border border-slate-200 rounded-2xl overflow-hidden shadow-xl bg-white flex flex-col",children:Mt(ja,{})})]}):Mt(Ua,{})})]})};import{CheckCircle as mg,DollarSign as AN,LogOut as TN}from"lucide-react";import{jsx as en,jsxs as nt}from"react/jsx-runtime";var gg=()=>{let{getPendingPayments:r,approvePayment:e}=pr(),{logout:t,currentUser:n}=Jn(),i=r();return nt("div",{className:"min-h-screen bg-slate-50 text-slate-900 font-sans",children:[nt("header",{className:"bg-white border-b border-emerald-100 px-8 py-4 flex justify-between items-center sticky top-0 z-10",children:[nt("div",{className:"flex items-center gap-3",children:[en("div",{className:"p-2 bg-emerald-100 text-emerald-600 rounded-lg",children:en(AN,{size:24})}),nt("div",{children:[en("h1",{className:"text-xl font-bold text-emerald-950",children:"Terminal de Caja"}),nt("p",{className:"text-xs text-emerald-600 font-medium uppercase tracking-wider",children:["Operador: ",n]})]})]}),nt("button",{onClick:t,className:"text-sm text-slate-400 hover:text-red-500 flex items-center gap-2 font-medium",children:[en(TN,{size:16})," Salir"]})]}),nt("main",{className:"p-8 max-w-5xl mx-auto",children:[nt("div",{className:"flex justify-between items-end mb-6",children:[en("h2",{className:"text-2xl font-bold text-slate-800",children:"Pendientes de Aprobaci\xF3n"}),nt("span",{className:"text-sm bg-slate-200 px-3 py-1 rounded-full text-slate-600 font-bold",children:[i.length," PEDIDOS"]})]}),nt("div",{className:"grid gap-4",children:[i.map(s=>nt("div",{className:"bg-white p-6 rounded-2xl shadow-sm border border-slate-100 flex justify-between items-center hover:shadow-md transition-shadow",children:[nt("div",{children:[nt("div",{className:"flex items-center gap-3 mb-1",children:[en("span",{className:"text-lg font-black text-slate-800",children:s.id}),en("span",{className:"px-2 py-0.5 bg-blue-50 text-blue-600 text-xs font-bold rounded uppercase",children:s.client})]}),nt("div",{className:"text-sm text-slate-500 flex gap-4",children:[nt("span",{children:["\u{1F4C5} SLA: ",s.slaHours,"h"]}),nt("span",{children:["\u{1FAB5} ",s.material]}),nt("span",{children:["\u{1F4CF} ",s.sheets," L\xE1minas"]})]})]}),nt("div",{className:"flex items-center gap-6",children:[nt("div",{className:"text-right",children:[en("p",{className:"text-xs text-slate-400 uppercase font-bold",children:"Total a Pagar"}),nt("p",{className:"text-xl font-bold text-slate-900",children:["$ ",(s.sheets*25e4+5e4).toLocaleString()]})]}),nt("button",{onClick:()=>e(s.id),className:"bg-emerald-500 hover:bg-emerald-600 text-white px-6 py-3 rounded-xl font-bold flex items-center gap-2 shadow-lg shadow-emerald-200 transition-all active:scale-95",children:[en(mg,{size:20}),"CONFIRMAR PAGO"]})]})]},s.id)),i.length===0&&nt("div",{className:"text-center py-20 bg-white rounded-3xl border border-dashed border-slate-200",children:[en(mg,{size:48,className:"mx-auto text-slate-200 mb-4"}),en("p",{className:"text-slate-400",children:"Todo al d\xEDa. No hay pagos pendientes."})]})]})]})]})};import{Hammer as MN,LogOut as DN,AlertTriangle as ON,CheckSquare as RN}from"lucide-react";import{jsx as Wt,jsxs as Pr}from"react/jsx-runtime";var bg=()=>{let{getOrdersByStage:r,updateStatus:e}=pr(),{logout:t}=Jn(),n=r("PRODUCCION"),i=s=>{e(s,"DESPACHO"),Te.success(`Enviando WhatsApp a +57...: El pedido ${s} pas\xF3 a Despacho`,{description:"Notificaci\xF3n de Producci\xF3n",icon:"\u{1F4F1}"})};return Pr("div",{className:"min-h-screen bg-neutral-900 text-white font-sans selection:bg-orange-500 selection:text-white",children:[Pr("header",{className:"bg-black border-b border-orange-600/30 px-6 py-4 flex justify-between items-center",children:[Pr("div",{className:"flex items-center gap-4",children:[Wt("div",{className:"w-3 h-3 rounded-full bg-green-500 animate-pulse shadow-[0_0_10px_#22c55e]"}),Wt("h1",{className:"text-2xl font-black tracking-tighter text-orange-500",children:"KIOSCO DE PLANTA"})]}),Wt("button",{onClick:t,className:"bg-neutral-800 p-3 rounded-lg hover:bg-neutral-700",children:Wt(DN,{size:24})})]}),Wt("main",{className:"p-6",children:n.length===0?Pr("div",{className:"h-[60vh] flex flex-col items-center justify-center text-neutral-600",children:[Wt(MN,{size:80,className:"mb-6 opacity-20"}),Wt("h2",{className:"text-3xl font-black uppercase",children:"M\xE1quinas Libres"}),Wt("p",{className:"mt-2",children:"Esperando asignaci\xF3n desde Caja..."})]}):Wt("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:n.map(s=>Pr("div",{className:"bg-neutral-800 border-l-8 border-orange-500 rounded-r-2xl p-6 relative overflow-hidden group",children:[Pr("div",{className:"absolute top-0 right-0 bg-neutral-700 px-4 py-2 rounded-bl-xl text-xs font-bold text-neutral-400",children:["MAQUINA: ",Wt("span",{className:"text-orange-400 text-base",children:s.machine})]}),Pr("div",{className:"mb-6 mt-2",children:[Wt("h2",{className:"text-5xl font-black text-white mb-2",children:s.id}),Wt("p",{className:"text-xl text-neutral-300 font-medium truncate",children:s.material}),Pr("div",{className:"mt-4 flex gap-2",children:[Pr("span",{className:"px-3 py-1 bg-neutral-700 rounded text-sm font-mono text-orange-200",children:[s.sheets," L\xC1MINAS"]}),Wt("span",{className:"px-3 py-1 bg-neutral-700 rounded text-sm font-mono text-orange-200",children:s.measurements})]})]}),Pr("div",{className:"grid grid-cols-2 gap-3",children:[Pr("button",{className:"bg-neutral-700 hover:bg-neutral-600 text-neutral-300 py-4 rounded-xl font-bold flex flex-col items-center justify-center gap-1",children:[Wt(ON,{size:24}),Wt("span",{className:"text-xs",children:"REPORTAR"})]}),Pr("button",{onClick:()=>i(s.id),className:"bg-orange-600 hover:bg-orange-500 text-white py-4 rounded-xl font-black text-lg flex flex-col items-center justify-center gap-1 shadow-[0_0_20px_rgba(234,88,12,0.3)] active:scale-95 transition-all",children:[Wt(RN,{size:28}),"TERMINADO"]})]})]},s.id))})})]})};import{Truck as xg,LogOut as IN,CheckCircle as PN,Navigation as LN}from"lucide-react";import{jsx as pt,jsxs as it}from"react/jsx-runtime";var vg=()=>{let{getOrdersByStage:r,updateStatus:e}=pr(),{logout:t,currentUser:n}=Jn(),i=r("DESPACHO"),s=(o,a)=>{e(o,"ENTREGADO"),Te.success(`Mensaje enviado a ${a}`,{description:`\u{1F4E6} \xA1Tu pedido ${o} ha sido entregado exitosamente!`,icon:"\u2705"})};return it("div",{className:"min-h-screen bg-slate-900 text-slate-100 font-sans",children:[it("header",{className:"bg-slate-950 border-b border-purple-500/30 px-6 py-4 flex justify-between items-center sticky top-0 z-10 shadow-lg shadow-purple-500/10",children:[it("div",{className:"flex items-center gap-3",children:[pt("div",{className:"p-2 bg-purple-500/20 text-purple-400 rounded-lg",children:pt(xg,{size:24})}),it("div",{children:[pt("h1",{className:"text-xl font-bold text-white",children:"Log\xEDstica & Despacho"}),it("p",{className:"text-xs text-purple-400 font-medium uppercase tracking-wider",children:["Operador: ",n]})]})]}),it("button",{onClick:t,className:"text-sm text-slate-400 hover:text-red-400 flex items-center gap-2 font-medium bg-slate-800 px-4 py-2 rounded-lg transition-colors",children:[pt(IN,{size:16})," Salir"]})]}),it("main",{className:"p-8 max-w-6xl mx-auto",children:[it("div",{className:"flex justify-between items-end mb-8",children:[it("div",{children:[pt("h2",{className:"text-3xl font-bold text-white mb-2",children:"Pedidos Listos para Entrega"}),pt("p",{className:"text-slate-400",children:"Verifica la identidad antes de entregar el paquete."})]}),it("span",{className:"text-sm bg-purple-500/20 border border-purple-500/30 px-4 py-2 rounded-full text-purple-300 font-bold tracking-widest",children:[i.length," PAQUETES"]})]}),it("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[i.map(o=>it("div",{className:"bg-slate-800 border border-slate-700/50 rounded-2xl p-6 relative group overflow-hidden hover:border-purple-500/30 transition-colors",children:[pt("div",{className:"flex justify-between items-start mb-6",children:it("div",{children:[it("h3",{className:"text-2xl font-black text-white mb-1 flex items-center gap-2",children:[o.id,pt("span",{className:"bg-green-500/20 text-green-400 text-[10px] px-2 py-1 rounded-full uppercase tracking-widest font-bold",children:"PAGADO"})]}),it("p",{className:"text-slate-400 flex items-center gap-2",children:[pt(LN,{size:14,className:"text-purple-400"}),"Destino: ",pt("strong",{className:"text-white",children:o.client})]})]})}),it("div",{className:"grid grid-cols-2 gap-4 mb-6 text-sm bg-slate-900/50 p-4 rounded-xl",children:[it("div",{children:[pt("span",{className:"block text-slate-500 text-xs mb-1 uppercase font-bold tracking-wider",children:"Material"}),pt("span",{className:"font-medium text-slate-200",children:o.material})]}),it("div",{children:[pt("span",{className:"block text-slate-500 text-xs mb-1 uppercase font-bold tracking-wider",children:"L\xE1minas (Volumen)"}),it("span",{className:"font-medium text-slate-200",children:[o.sheets," unid."]})]}),it("div",{className:"col-span-2 border-t border-slate-700/50 pt-3 mt-1",children:[pt("span",{className:"block text-slate-500 text-xs mb-1 uppercase font-bold tracking-wider",children:"Contacto WhatsApp"}),pt("span",{className:"font-mono text-purple-300",children:o.whatsapp})]})]}),it("button",{onClick:()=>s(o.id,o.whatsapp),className:"w-full bg-purple-600 hover:bg-purple-500 text-white py-4 rounded-xl font-bold flex items-center justify-center gap-2 shadow-lg shadow-purple-900/50 transition-all active:scale-95",children:[pt(PN,{size:20}),"CONFIRMAR ENTREGA"]})]},o.id)),i.length===0&&it("div",{className:"col-span-full h-[40vh] flex flex-col items-center justify-center text-slate-500 border-2 border-dashed border-slate-700 rounded-3xl",children:[pt(xg,{size:64,className:"mb-4 opacity-20"}),pt("p",{className:"text-lg font-medium",children:"Bandeja de salida vac\xEDa"}),pt("p",{className:"text-sm",children:"Todo ha sido despachado a los clientes."})]})]})]})]})};import{useEffect as G2,useState as zg}from"react";import{io as q2}from"socket.io-client";import Ka,{memo as Ig,useState as oe,useEffect as yn,useRef as jd,useCallback as po}from"react";import{io as Pg}from"socket.io-client";import{jsx as v,jsxs as T}from"react/jsx-runtime";import{kernel as Eg}from"@decido/kernel-bridge";var Od=class r{static instance;templates=new Map;constructor(){}static getInstance(){return r.instance||(r.instance=new r),r.instance}register(e){this.templates.set(e.id,e)}get(e){return this.templates.get(e)}getAll(){return Array.from(this.templates.values())}},Rd=Od.getInstance();var Id=`
26
+ You are an AI Graph Architect for react-flow.
27
+ Your goal is to parse natural language requests and return a JSON schema of operations to modify the graph.
28
+
29
+ # Output Format
30
+ Return ONLY a JSON object with this structure:
31
+ {
32
+ "operations": [
33
+ { "type": "addNode", "id": "generated-id", "position": { "x": 0, "y": 0 }, "data": { "label": "Node Label", "type": "default" } },
34
+ { "type": "addEdge", "source": "source-id", "target": "target-id", "animated": true }
35
+ ],
36
+ "thought": "Brief explanation of your architectural decision."
37
+ }
38
+
39
+ # Rules
40
+ 1. Assign unique IDs to new nodes (e.g., "node-timestamp-random").
41
+ 2. Prefer "default" or "input/output" types unless specified.
42
+ 3. Space nodes out reasonably (x+=200).
43
+ `;var Pd=class r{static instance;constructor(){this.registerPrompts()}static getInstance(){return r.instance||(r.instance=new r),r.instance}registerPrompts(){Rd.register({id:"flow-generation",description:"Generate Flow Graph",system:Id,user:"Request: {{input}}",requiredContext:["activeView"]})}executor=null;setExecutor(e){this.executor=e}async generateGraphOps(e){if(console.log("[FlowOrchestrator] Generating ops for:",e),this.executor)try{let t=`${Id}
44
+
45
+ User Prompt: ${e}`,n=await this.executor(t);return this.parseResponse(n)}catch(t){return console.error("[FlowOrchestrator] AI Execution Failed:",t),{operations:[],thought:"Failed to generate flow via AI."}}return e.toLowerCase().includes("server")?{thought:"Adding a server node as requested.",operations:[{type:"addNode",id:`server-${Date.now()}`,position:{x:Math.random()*500,y:Math.random()*500},data:{label:"Server Node",type:"default"}}]}:{operations:[],thought:"No relevant graph operations found (Mock)."}}parseResponse(e){try{let t=e.replace(/```json/g,"").replace(/```/g,"").trim();return JSON.parse(t)}catch{return console.error("[FlowOrchestrator] Failed to parse JSON:",e),{operations:[],thought:"Invalid JSON response from AI."}}}},wB=Pd.getInstance();import MB,{useState as DB,useEffect as OB}from"react";import{Cpu as IB,Activity as PB,ChevronDown as LB,ChevronUp as BB,Plus as FB,Terminal as _B,Play as zB}from"lucide-react";import ho from"react";import NB from"react-dom";function BN(r){if(!r||typeof document>"u")return;let e=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.type="text/css",e.appendChild(t),t.styleSheet?t.styleSheet.cssText=r:t.appendChild(document.createTextNode(r))}var EB=Array(12).fill(0);var Ld=1,Bd=class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{var t;let{message:n,...i}=e,s=typeof e?.id=="number"||((t=e.id)==null?void 0:t.length)>0?e.id:Ld++,o=this.toasts.find(l=>l.id===s),a=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(s)&&this.dismissedToasts.delete(s),o?this.toasts=this.toasts.map(l=>l.id===s?(this.publish({...l,...e,id:s,title:n}),{...l,...e,id:s,dismissible:a,title:n}):l):this.addToast({title:n,...i,dismissible:a,id:s}),s},this.dismiss=e=>(e?(this.dismissedToasts.add(e),requestAnimationFrame(()=>this.subscribers.forEach(t=>t({id:e,dismiss:!0})))):this.toasts.forEach(t=>{this.subscribers.forEach(n=>n({id:t.id,dismiss:!0}))}),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:"error"}),this.success=(e,t)=>this.create({...t,type:"success",message:e}),this.info=(e,t)=>this.create({...t,type:"info",message:e}),this.warning=(e,t)=>this.create({...t,type:"warning",message:e}),this.loading=(e,t)=>this.create({...t,type:"loading",message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:"loading",message:t.loading,description:typeof t.description!="function"?t.description:void 0}));let i=Promise.resolve(e instanceof Function?e():e),s=n!==void 0,o,a=i.then(async c=>{if(o=["resolve",c],ho.isValidElement(c))s=!1,this.create({id:n,type:"default",message:c});else if(_N(c)&&!c.ok){s=!1;let u=typeof t.error=="function"?await t.error(`HTTP error! status: ${c.status}`):t.error,h=typeof t.description=="function"?await t.description(`HTTP error! status: ${c.status}`):t.description,p=typeof u=="object"&&!ho.isValidElement(u)?u:{message:u};this.create({id:n,type:"error",description:h,...p})}else if(c instanceof Error){s=!1;let u=typeof t.error=="function"?await t.error(c):t.error,h=typeof t.description=="function"?await t.description(c):t.description,p=typeof u=="object"&&!ho.isValidElement(u)?u:{message:u};this.create({id:n,type:"error",description:h,...p})}else if(t.success!==void 0){s=!1;let u=typeof t.success=="function"?await t.success(c):t.success,h=typeof t.description=="function"?await t.description(c):t.description,p=typeof u=="object"&&!ho.isValidElement(u)?u:{message:u};this.create({id:n,type:"success",description:h,...p})}}).catch(async c=>{if(o=["reject",c],t.error!==void 0){s=!1;let d=typeof t.error=="function"?await t.error(c):t.error,u=typeof t.description=="function"?await t.description(c):t.description,f=typeof d=="object"&&!ho.isValidElement(d)?d:{message:d};this.create({id:n,type:"error",description:u,...f})}}).finally(()=>{s&&(this.dismiss(n),n=void 0),t.finally==null||t.finally.call(t)}),l=()=>new Promise((c,d)=>a.then(()=>o[0]==="reject"?d(o[1]):c(o[1])).catch(d));return typeof n!="string"&&typeof n!="number"?{unwrap:l}:Object.assign(n,{unwrap:l})},this.custom=(e,t)=>{let n=t?.id||Ld++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},Lr=new Bd,FN=(r,e)=>{let t=e?.id||Ld++;return Lr.addToast({title:r,...e,id:t}),t},_N=r=>r&&typeof r=="object"&&"ok"in r&&typeof r.ok=="boolean"&&"status"in r&&typeof r.status=="number",zN=FN,$N=()=>Lr.toasts,HN=()=>Lr.getActiveToasts(),xn=Object.assign(zN,{success:Lr.success,info:Lr.info,warning:Lr.warning,error:Lr.error,custom:Lr.custom,message:Lr.message,promise:Lr.promise,dismiss:Lr.dismiss,loading:Lr.loading},{getHistory:$N,getToasts:HN});BN("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");import{jsx as WB,jsxs as VB}from"react/jsx-runtime";import{memo as WN,useState as Ga}from"react";import{Play as VN,Activity as jN,Terminal as UN}from"lucide-react";import{jsx as vn,jsxs as Ni}from"react/jsx-runtime";var KB=WN(({data:r})=>{let e=r.label||"UNKNOWN_SKILL",[t,n]=Ga(!1),[i,s]=Ga(["> READY_TO_EXECUTE"]),[o,a]=Ga("idle"),[l,c]=Ga(r.config||{target:"127.0.0.1"});return Ni("div",{className:"h-full bg-slate-900 border border-slate-700 rounded-lg overflow-hidden flex flex-col shadow-lg",style:{minWidth:200,minHeight:180},children:[Ni("div",{className:"flex items-center justify-between p-2 bg-slate-800 border-b border-slate-700",children:[vn("div",{className:`p-1 rounded ${o==="running"?"bg-amber-500 text-white animate-pulse":"text-slate-500"}`,children:vn(UN,{size:14})}),vn("span",{className:"text-[9px] font-bold text-slate-400 uppercase tracking-wider",children:o}),Ni("button",{onClick:()=>{n(!0),a("running"),s(u=>[...u,`> EXECUTING: ${e}`,"> INITIATING_PROCESS..."]),setTimeout(()=>{s(u=>[...u,`> TARGET_ACQUIRED: ${l.target||"LOCALHOST"}`,"> RUNNING_DIAGNOSTICS..."])},800),setTimeout(()=>{s(u=>[...u,"> PROCESS_COMPLETE","> EXIT_CODE: 0"]),n(!1),a("success")},2200)},disabled:t,className:`flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-bold transition-all
46
+ ${t?"text-slate-500 cursor-not-allowed":"bg-emerald-600 hover:bg-emerald-500 text-white shadow-lg shadow-emerald-900/50"}
47
+ `,children:[t?vn(jN,{size:10,className:"animate-spin"}):vn(VN,{size:10}),"RUN"]})]}),Ni("div",{className:"px-3 py-2 bg-slate-900 border-b border-slate-800 flex items-center gap-2",children:[vn("span",{className:"text-[9px] font-bold text-slate-500 uppercase",children:"Target"}),vn("input",{type:"text",value:l.target,onChange:u=>c({...l,target:u.target.value}),className:"flex-1 bg-transparent border-none text-[11px] text-blue-400 font-mono outline-none placeholder-slate-700",placeholder:"ENTER_TARGET"})]}),Ni("div",{className:"flex-1 p-2 bg-black/40 font-mono text-[9px] overflow-y-auto custom-scrollbar",children:[i.map((u,h)=>vn("div",{className:"text-emerald-500/80 mb-0.5 whitespace-pre-wrap break-all border-l-2 border-transparent pl-1 hover:border-emerald-500/30",children:u},h)),t&&vn("div",{className:"text-emerald-500 animate-pulse",children:"_"})]}),Ni("div",{className:"flex justify-between px-2 py-1 bg-slate-950 text-[8px] text-slate-600 font-mono",children:[Ni("span",{children:["PID: ",Math.floor(Math.random()*9999)]}),vn("span",{children:"MEM: 14MB"})]})]})});import{memo as GN,useState as Ei,useEffect as qN}from"react";import{Zap as KN,Terminal as YN,ShieldAlert as JN,Search as XN,ChevronRight as ZN,ChevronDown as QN}from"lucide-react";import{jsx as Ie,jsxs as Ze}from"react/jsx-runtime";var yg=({value:r,label:e,onChange:t,depth:n=0})=>{let[i,s]=Ei(!1),[o,a]=Ei(10),l=Array.isArray(r)?"array":r===null?"null":typeof r;if(r===null)return Ie("div",{style:{color:"var(--text-dim)",fontStyle:"italic"},children:"null"});if(l==="boolean")return Ze("div",{style:{display:"flex",alignItems:"center",gap:"8px"},children:[e&&Ze("span",{style:{color:"var(--accent-primary)",fontWeight:700,marginRight:"8px"},children:[e,":"]}),Ie("button",{onClick:()=>t(!r),style:{width:32,height:16,borderRadius:"8px",position:"relative",background:r?"var(--accent-primary)":"var(--border-light)",border:"none",cursor:"pointer",transition:"background 0.15s"},children:Ie("div",{style:{position:"absolute",top:2,width:12,height:12,background:"white",borderRadius:"50%",left:r?18:2,transition:"left 0.15s"}})}),Ie("span",{style:{color:"var(--text-dim)",fontSize:"9px"},children:r?"TRUE":"FALSE"})]});let c={flex:1,background:"var(--node-bg)",border:"1px solid var(--border-light)",borderRadius:"var(--radius-sm)",padding:"2px 8px",fontSize:"10px",outline:"none",fontFamily:"var(--font-mono)",minWidth:0};if(l==="string")return Ze("div",{style:{display:"flex",alignItems:"center",gap:"8px",width:"100%"},children:[e&&Ze("span",{style:{color:"var(--accent-primary)",fontWeight:700,whiteSpace:"nowrap"},children:[e,":"]}),Ie("input",{style:{...c,color:"var(--status-ok)"},value:r,onChange:d=>t(d.target.value)})]});if(l==="number")return Ze("div",{style:{display:"flex",alignItems:"center",gap:"8px",width:"100%"},children:[e&&Ze("span",{style:{color:"var(--accent-primary)",fontWeight:700,whiteSpace:"nowrap"},children:[e,":"]}),Ie("input",{type:"number",style:{...c,color:"var(--accent-primary)"},value:r,onChange:d=>t(Number(d.target.value))})]});if(l==="array"||l==="object"){let d=Object.keys(r),u=d.length,h=u===0;return Ze("div",{style:{width:"100%"},children:[Ze("div",{style:{display:"flex",alignItems:"center",gap:"8px",marginBottom:"4px"},children:[Ie("button",{onClick:()=>s(!i),disabled:h,style:{background:"none",border:"none",color:"var(--text-dim)",cursor:h?"default":"pointer",opacity:h?.3:1,padding:0},children:i?Ie(QN,{size:12}):Ie(ZN,{size:12})}),e&&Ze("span",{style:{color:"var(--accent-primary)",fontWeight:700},children:[e,":"]}),Ie("span",{style:{fontSize:"9px",color:"var(--text-dim)",textTransform:"uppercase"},children:l==="array"?`Array(${u})`:"Object"}),!i&&!h&&Ze("span",{style:{fontSize:"9px",color:"var(--text-dim)",maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",opacity:.5},children:[JSON.stringify(r).slice(0,30),"..."]})]}),i&&Ze("div",{style:{paddingLeft:"16px",marginLeft:"4px",borderLeft:"1px solid var(--border-light)",display:"flex",flexDirection:"column",gap:"4px",marginTop:"4px"},children:[d.slice(0,o).map(f=>{let p=r[f],m=g=>{let b;Array.isArray(r)?(b=[...r],b[Number(f)]=g):b={...r,[f]:g},t(b)};return Ie("div",{style:{paddingTop:"2px",paddingBottom:"2px"},children:Ie(yg,{label:Array.isArray(r)?`${f}`:f,value:p,onChange:m,depth:n+1})},f)}),u>o&&Ze("button",{onClick:()=>a(f=>f+20),className:"text-[9px] text-blue-400 hover:text-blue-300 w-full text-center py-1 bg-slate-800/50 rounded",children:["Show ",u-o," more..."]})]})]})}return Ie("div",{style:{color:"var(--status-crit)"},children:"Unknown Type"})},e2=({data:r,selected:e})=>{let[t,n]=Ei("mission"),[i,s]=Ei(""),[o,a]=Ei(""),[l,c]=Ei(!1),[d,u]=Ei({});qN(()=>{r.getDebugState&&u(r.getDebugState(t))},[t,r.getDebugState]);let h=d,f=r.availableActions||[],p=async b=>{try{if(r.onRunAction){let y=r.onRunAction(b);y instanceof Promise?xn.promise(y,{loading:`Running ${b}...`,success:`${b} completed`,error:`${b} failed`}):xn.success(`Executed: ${b}`)}else xn.warning("No action runner provided")}catch(y){xn.error(`Error executing ${b}`),console.error(y)}},m=()=>{try{r.onInjectState?(r.onInjectState(o),xn.success("State injected into Core"),c(!1)):xn.error("Injection not supported")}catch{xn.error("Invalid JSON")}},g={mission:"var(--accent-primary, #3b82f6)",ui:"var(--status-warn, #f59e0b)",system:"var(--status-ok, #10b981)"};return Ze("div",{className:`bg-slate-900 border-2 rounded-xl overflow-hidden flex flex-col font-mono text-[10px] ${e?"border-blue-500 shadow-xl":"border-slate-800"}`,style:{width:"100%",height:"100%",minWidth:"350px",minHeight:"500px"},children:[Ie(bp,{minWidth:350,minHeight:500,isVisible:e,color:"var(--accent-primary)"}),Ze("div",{className:"h-8 flex items-center px-2 border-b border-red-500/30 bg-linear-to-r from-red-900/20 to-blue-900/20 drag-handle",children:[Ze("div",{className:"flex items-center gap-2 text-red-500 font-bold uppercase tracking-widest text-[10px]",children:[Ie(JN,{size:14}),Ie("span",{children:"GOD_MODE // KERNEL"})]}),Ze("div",{className:"ml-auto flex items-center gap-2",children:[Ie("div",{className:"w-2 h-2 rounded-full bg-green-500 animate-pulse"}),Ie("span",{className:"text-slate-500",children:"v2.0"})]})]}),Ie("div",{className:"flex border-b border-slate-700 bg-slate-900",children:["mission","ui","system"].map(b=>Ie("button",{onClick:()=>n(b),className:`flex-1 py-2 text-[10px] uppercase font-bold transition-colors border-b-2 ${t===b?"text-"+b+" border-"+b:"text-slate-500 border-transparent hover:text-slate-300"}`,style:{color:t===b?g[b]:void 0,borderColor:t===b?g[b]:void 0},children:b},b))}),Ze("div",{className:"flex-1 flex flex-col overflow-hidden bg-slate-950",children:[Ze("div",{className:"p-2 border-b border-slate-800 bg-slate-900 flex items-center gap-2",children:[Ze("div",{className:"flex items-center bg-slate-950 rounded border border-slate-800 flex-1 px-2 h-7 gap-2",children:[Ie(XN,{size:12,className:"text-slate-500"}),Ie("input",{className:"bg-transparent border-none text-slate-200 w-full outline-none font-mono text-[10px]",placeholder:"Filter keys...",value:i,onChange:b=>s(b.target.value)})]}),Ie("button",{onClick:()=>c(!l),className:`p-1.5 rounded border ${l?"border-blue-500 bg-blue-500/10 text-blue-500":"border-slate-800 bg-transparent text-slate-500"}`,title:"Inject State",children:Ie(YN,{size:14})})]}),Ie("div",{className:"flex-1 overflow-y-auto p-2 custom-scrollbar",children:l?Ze("div",{className:"h-full flex flex-col gap-2",children:[Ie("textarea",{className:"flex-1 bg-slate-900 border border-slate-700 rounded p-2 text-green-400 font-mono text-[10px] outline-none resize-none",placeholder:"// Paste JSON State here to hydrate...",value:o,onChange:b=>a(b.target.value)}),Ie("button",{onClick:m,className:"w-full py-2 bg-blue-600 hover:bg-blue-500 text-white rounded font-bold uppercase tracking-wider text-[10px]",children:"HYDRATE REALITY"})]}):Ie("div",{className:"flex flex-col gap-1 pb-10",children:Ie(yg,{value:h,onChange:b=>{xn.info("Visual editing is read-only for deep structures. Use Injection for major changes.")}})})}),Ze("div",{className:"h-[150px] border-t border-slate-800 bg-slate-900 p-2 overflow-y-auto custom-scrollbar",children:[Ze("div",{className:"text-[9px] text-slate-500 uppercase font-bold mb-2 flex items-center gap-2",children:[Ie(KN,{size:10})," OVERRIDE COMMANDS"]}),Ie("div",{className:"grid grid-cols-2 gap-1",children:f.filter(b=>b.toLowerCase().includes(i.toLowerCase())).slice(0,10).map(b=>Ze("button",{onClick:()=>p(b),className:"text-left px-2 py-1 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white rounded text-[9px] truncate transition-colors",title:b,children:[b,"()"]},b))})]})]})]})},hF=GN(e2);import{useState as NF}from"react";import{Sparkles as AF,Zap as TF,ChevronDown as MF}from"lucide-react";import gF,{createContext as t2,useContext as bF}from"react";import{jsx as wF}from"react/jsx-runtime";var vF=t2(null);import{jsx as IF,jsxs as PF}from"react/jsx-runtime";import{useState as FF}from"react";var Fd=new Date,$F=[`[${Fd.toLocaleTimeString()}] System initialized.`,`[${Fd.toLocaleTimeString()}] Connected to Cortex Telemetry.`,`[${Fd.toLocaleTimeString()}] Monitoring active nodes...`];import{useMemo as UF}from"react";import{useEffect as ZF}from"react";import{logger as In}from"@decido/logger";var _d=class{tools=new Map;modules=new Map;register(e){this.tools.has(e.name)&&In.warn(`[ToolRegistry] Overwriting tool: ${e.name}`),this.tools.set(e.name,e),In.info(`[ToolRegistry] Registered tool: ${e.name}`)}unregister(e){this.tools.delete(e),In.info(`[ToolRegistry] Unregistered tool: ${e}`)}registerModule(e){this.modules.has(e.id)&&(In.warn(`[ToolRegistry] Module already registered: ${e.id}, updating...`),this.modules.get(e.id).tools.forEach(n=>this.tools.delete(n.name))),this.modules.set(e.id,e),e.tools.forEach(t=>this.register(t)),In.info(`[ToolRegistry] \u{1F4E6} Module registered: ${e.name} (${e.tools.length} tools)`)}unregisterModule(e){let t=this.modules.get(e);t&&(t.tools.forEach(n=>this.tools.delete(n.name)),this.modules.delete(e),In.info(`[ToolRegistry] \u{1F4E6} Module unregistered: ${t.name}`))}getModule(e){return this.modules.get(e)}getAllModules(){return Array.from(this.modules.values())}get(e){return this.tools.get(e)}getAll(){return Array.from(this.tools.values())}async execute(e,t){let n=this.tools.get(e);if(!n)throw new Error(`Tool not found: ${e}`);try{return In.info(`[ToolRegistry] Executing ${e}`,t),await n.handler(t)}catch(i){throw In.error(`[ToolRegistry] Execution failed for ${e}`,i),i}}},n2=new _d;import{useEffect as i_,useState as s_}from"react";var zd=class{channels=new Map;lastValues=new Map;subscribe(e,t){if(this.channels.has(e)||this.channels.set(e,new Set),this.channels.get(e).add(t),this.lastValues.has(e))try{t(this.lastValues.get(e))}catch(n){console.error(`[Synapse] Error in callback for ${e}:`,n)}return()=>this.unsubscribe(e,t)}unsubscribe(e,t){this.channels.get(e)?.delete(t),this.channels.get(e)?.size===0&&this.channels.delete(e)}broadcast(e,t){this.lastValues.set(e,t);let n=this.channels.get(e);n&&n.forEach(i=>{try{i(t)}catch(s){console.error(`[Synapse] Broadcast failed for listener on ${e}`,s)}})}getValue(e){return this.lastValues.get(e)}getActiveChannels(){return Array.from(this.channels.keys())}},i2=new zd;import{Timer as s2,Globe as o2,Zap as wg,Split as a2}from"lucide-react";var $d=class{definitions=new Map;constructor(){this.registerDefaults()}register(e){this.definitions.set(e.id,e)}get(e){return this.definitions.get(e)}getAll(){return Array.from(this.definitions.values())}getByType(e){return this.getAll().filter(t=>t.type===e)}registerDefaults(){this.register({id:"cron",label:"Interval Timer",type:"trigger",icon:s2,description:"Dispara un evento repetidamente.",fields:[{key:"interval",label:"Intervalo (ms)",type:"number",defaultValue:5e3},{key:"emitTimestamp",label:"Incluir Timestamp",type:"boolean",defaultValue:!0}],execute:async()=>({}),setup:(e,{trigger:t})=>{let n=Number(e.interval)||5e3,i=setInterval(()=>{t({timestamp:Date.now(),type:"cron"})},n);return()=>clearInterval(i)}}),this.register({id:"event",label:"Event Listener",type:"trigger",icon:wg,description:"Escucha eventos globales (window.postMessage).",fields:[{key:"eventName",label:"Nombre del Evento",type:"text",placeholder:"mindframe.event"}],execute:async()=>({}),setup:(e,{trigger:t})=>{if(!e.eventName)return;let n=i=>{(i.data?.type===e.eventName||i.data?.name===e.eventName)&&t(i.data)};return window.addEventListener("message",n),()=>window.removeEventListener("message",n)}}),this.register({id:"bridge",label:"Broadcast Message",type:"action",icon:wg,description:"Env\xEDa un mensaje global a la ventana.",fields:[{key:"method",label:"Method / Event Name",type:"text",defaultValue:"custom_event"},{key:"payload",label:"Payload (JSON)",type:"json"}],execute:async(e,t)=>{let n=e.payload?JSON.parse(e.payload):t;return window.postMessage({type:e.method,payload:n,timestamp:Date.now()},"*"),{sent:!0,method:e.method}}}),this.register({id:"http",label:"HTTP Request",type:"action",icon:o2,description:"Realiza una petici\xF3n API externa.",fields:[{key:"url",label:"URL",type:"text",placeholder:"https://api.xyz"},{key:"method",label:"M\xE9todo",type:"select",defaultValue:"GET",options:[{label:"GET",value:"GET"},{label:"POST",value:"POST"},{label:"PUT",value:"PUT"}]},{key:"body",label:"Body (JSON)",type:"json"}],execute:async(e,t)=>await(await fetch(e.url,{method:e.method,headers:{"Content-Type":"application/json"},body:e.method!=="GET"?e.body||JSON.stringify(t):void 0})).json()}),this.register({id:"check_value",label:"Check Value",type:"condition",icon:a2,description:"Compara un valor del payload.",fields:[{key:"field",label:"Campo (ej: data.id)",type:"text"},{key:"operator",label:"Operador",type:"select",defaultValue:"equals",options:[{label:"Igual a (==)",value:"equals"},{label:"Contiene",value:"contains"},{label:"Mayor que (>)",value:"gt"}]},{key:"value",label:"Valor a comparar",type:"text"}],execute:async(e,t)=>{let i=((o,a)=>a.split(".").reduce((l,c)=>l?.[c],o))(t,e.field),s=e.value;return e.operator==="equals"?String(i)===String(s):e.operator==="contains"?String(i).includes(String(s)):e.operator==="gt"?Number(i)>Number(s):!1}})}},h_=new $d;import{probe as g_,probeStart as b_}from"@decido/logger";import{create as l2}from"zustand";var Sg=(r=[],e=[])=>l2((t,n)=>({nodes:r,edges:e,onNodesChange:i=>{t({nodes:fp(i,n().nodes)})},onEdgesChange:i=>{t({edges:pp(i,n().edges)})},onConnect:i=>{t({edges:up(i,n().edges)})},setNodes:i=>{t({nodes:i})},setEdges:i=>{t({edges:i})},addNode:i=>{t({nodes:[...n().nodes,i]})},updateNodeConfig:(i,s)=>{t({nodes:n().nodes.map(o=>o.id===i?{...o,data:{...o.data,config:s}}:o)})}}));import Hd,{useMemo as c2}from"react";import*as Cg from"yjs";import{WebsocketProvider as d2}from"y-websocket";import{Fragment as p2,jsx as gr,jsxs as Ng}from"react/jsx-runtime";var qa=null,Qn=null;function u2(r){if(!qa){qa=new Cg.Doc;let e=import.meta.env?.VITE_WS_URL||"ws://localhost:3001";Qn=new d2(`${e}/api/collaboration`,r,qa),Qn.awareness.setLocalStateField("user",{name:`Usuario ${Math.floor(Math.random()*1e3)}`,color:`hsl(${Math.floor(Math.random()*360)}, 70%, 50%)`})}return{ydoc:qa,wsProvider:Qn}}function h2(){let[r,e]=Hd.useState(new Map);Hd.useEffect(()=>{if(!Qn)return;let n=Qn.awareness,i=()=>{e(new Map(n.getStates()))};return n.on("change",i),i(),()=>n.off("change",i)},[]);let t=Array.from(r.entries()).filter(([n,i])=>n!==Qn?.awareness.clientID&&i.cursor).map(([n,i])=>Ng("div",{style:{position:"absolute",left:i.cursor.x,top:i.cursor.y,pointerEvents:"none",zIndex:9999},className:"flex flex-col items-start transition-all duration-75 ease-out",children:[gr("svg",{width:"24",height:"36",viewBox:"0 0 24 36",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"absolute -left-1 -top-1",style:{transform:"rotate(-25deg)"},children:gr("path",{d:"M5.65376 2.15376C5.40821 1.66266 4.70732 1.63738 4.43265 2.1098L0.165287 9.44917C-0.0827293 9.87574 0.224673 10.4285 0.730302 10.4285H10.1506C10.7437 10.4285 11.0182 9.69176 10.5513 9.303L5.65376 2.15376Z",fill:i.user?.color||"red"})}),gr("span",{style:{backgroundColor:i.user?.color||"red"},className:"text-[10px] font-bold text-white px-2 py-0.5 rounded-md whitespace-nowrap shadow-sm mt-3 ml-2",children:i.user?.name||"Anon"})]},n));return gr(p2,{children:t})}var f2=({initialNodes:r=[],initialEdges:e=[],nodes:t,edges:n,onNodesChange:i,onEdgesChange:s,onConnect:o,nodeTypes:a,edgeTypes:l,onSave:c,readOnly:d=!1,onNodeClick:u,onEdgeClick:h,onPaneClick:f,flowId:p="default-flow"})=>{Hd.useEffect(()=>{u2(`madefront-flow-${p}`)},[p]);let m=c2(()=>Sg(r,e),[]),g=m(M=>M.nodes),b=m(M=>M.edges),y=m(M=>M.onNodesChange),x=m(M=>M.onEdgesChange),N=m(M=>M.onConnect),C=t!==void 0?t:g,w=n!==void 0?n:b;return gr("div",{className:"w-full h-full min-h-[500px] border border-white/10 rounded-xl overflow-hidden bg-macia-bg relative",children:Ng(Zi,{nodes:C,edges:w,onNodesChange:d?void 0:i!==void 0?i:y,onEdgesChange:d?void 0:s!==void 0?s:x,onConnect:d?void 0:o!==void 0?o:N,nodeTypes:a,edgeTypes:l,fitView:!0,proOptions:{hideAttribution:!0},className:"bg-transparent",nodesDraggable:!d,nodesConnectable:!d,elementsSelectable:!0,onNodeClick:u,onEdgeClick:h,onPaneClick:f,onPointerMove:M=>{let D=M.currentTarget.getBoundingClientRect();Qn?.awareness.setLocalStateField("cursor",{x:M.clientX-D.left,y:M.clientY-D.top})},onPointerLeave:()=>{Qn?.awareness.setLocalStateField("cursor",null)},children:[gr(h2,{}),gr(Qi,{variant:gp.Dots,gap:24,size:2,color:"rgba(255,255,255,0.05)"}),gr(es,{className:"bg-macia-bg border border-white/10 fill-white text-white"}),gr(ts,{nodeColor:"rgba(6, 182, 212, 0.5)",maskColor:"rgba(0, 0, 0, 0.7)",className:"bg-macia-bg border border-white/10"}),c&&!d&&gr(hp,{position:"top-right",className:"m-4",children:gr("button",{onClick:()=>c(C,w),className:"px-4 py-2 bg-emerald-500/20 hover:bg-emerald-500/30 text-emerald-400 border border-emerald-500/50 rounded-lg text-sm font-bold transition-colors shadow-[0_0_15px_rgba(16,185,129,0.2)]",children:"Guardar Pipeline"})})]})})},kg=r=>gr(mp,{children:gr(f2,{...r})});import{useState as D_,useEffect as O_}from"react";import{jsx as I_,jsxs as P_}from"react/jsx-runtime";import{BaseNode as Lg}from"@decido/macia-core";import{Info as m2,Reply as g2,MessageCircle as b2,GitBranch as x2,Brain as v2,Headphones as y2,ShoppingCart as w2,Bot as S2}from"lucide-react";var Ag=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",Tg=[{id:"t1",label:"Confirmaci\xF3n Pedido",icon:"fas fa-check-circle"},{id:"t2",label:"Estado de Env\xEDo",icon:"fas fa-truck"},{id:"t3",label:"Cotizaci\xF3n",icon:"fas fa-file-invoice"},{id:"t4",label:"Bienvenida",icon:"fas fa-hand-wave"}],Mg=[{id:"a1",label:"Auto-respuesta horario",active:!0},{id:"a2",label:"Crear pedido autom\xE1tico",active:!0},{id:"a3",label:"Escalamiento a asesor",active:!1},{id:"a4",label:"Encuesta satisfacci\xF3n",active:!0}],Wd=({title:r,icon:e,count:t,defaultOpen:n=!0,children:i})=>{let[s,o]=oe(n);return T("div",{className:"border-b",style:{borderColor:"var(--border-color)"},children:[T("button",{onClick:()=>o(a=>!a),className:"w-full flex items-center gap-2 px-3 py-2 text-[10px] font-black uppercase tracking-widest transition-all hover:bg-white/5",style:{color:"var(--text-secondary)"},children:[v("i",{className:`fas fa-chevron-${s?"down":"right"} text-[8px] w-3`}),v("i",{className:`${e} text-[10px]`}),v("span",{className:"flex-1 text-left",children:r}),t!==void 0&&v("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-bold",style:{background:"var(--bg-muted)",color:"var(--text-secondary)"},children:t})]}),s&&v("div",{className:"pb-1",children:i})]})},C2=({selectedContact:r,onSelectContact:e})=>{let[t,n]=oe(""),[i,s]=oe([]);yn(()=>{let a=async()=>{try{let c=await(await fetch(`${Ag}/api/whatsapp/conversations`)).json();s(c.map(d=>({...d,last_activity:new Date(d.last_activity)})))}catch{}};a();let l=Pg(Ag,{transports:["websocket","polling"]});return l.on("wa:message_received",a),l.on("wa:message_sent",a),()=>{l.disconnect()}},[]);let o=i.filter(a=>a.phone.includes(t));return T("div",{className:"flex flex-col h-full overflow-hidden",children:[v("div",{className:"p-2 shrink-0",children:T("div",{className:"flex items-center gap-2 px-2.5 py-1.5 rounded-lg text-xs",style:{background:"var(--bg-muted)",border:"1px solid var(--border-color)"},children:[v("i",{className:"fas fa-search text-[10px]",style:{color:"var(--text-secondary)"}}),v("input",{type:"text",placeholder:"Filtrar...",className:"flex-1 bg-transparent outline-none text-xs",style:{color:"var(--text-primary)"},value:t,onChange:a=>n(a.target.value)})]})}),T("div",{className:"flex-1 overflow-y-auto scrollbar-thin",children:[T(Wd,{title:"Conversaciones",icon:"fas fa-comments",count:o.length,children:[o.map(a=>T("button",{onClick:()=>e(a.phone),className:"w-full flex items-start gap-2.5 px-3 py-2 text-left transition-all rounded-md mx-1",style:{background:r===a.phone?"var(--bg-muted)":"transparent",width:"calc(100% - 8px)"},onMouseEnter:l=>{r!==a.phone&&(l.currentTarget.style.background="var(--bg-muted)")},onMouseLeave:l=>{r!==a.phone&&(l.currentTarget.style.background="transparent")},children:[v("div",{className:"w-8 h-8 rounded-full flex items-center justify-center shrink-0 text-white text-[10px] font-bold",style:{background:"var(--brand-primary)"},children:v("i",{className:"fab fa-whatsapp text-sm"})}),T("div",{className:"flex-1 min-w-0",children:[T("div",{className:"flex items-center justify-between",children:[v("span",{className:"text-xs font-bold truncate",style:{color:"var(--text-primary)"},children:a.profile_name||"+"+a.phone}),v("span",{className:"text-[9px] shrink-0 ml-1",style:{color:"var(--text-secondary)"},children:a.last_activity.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}),v("p",{className:"text-[10px] truncate mt-0.5",style:{color:"var(--text-secondary)"},children:a.last_message||"Media"})]})]},a.phone)),o.length===0&&T("div",{className:"px-4 py-3 pb-4 text-center",children:[v("i",{className:"fab fa-whatsapp text-2xl mb-2",style:{color:"#25D366"}}),v("p",{className:"text-xs",style:{color:"var(--text-secondary)"},children:"No hay chats activos. Manda un WhatsApp al n\xFAmero Business para empezar."})]})]}),v(Wd,{title:"Plantillas",icon:"fas fa-file-alt",count:Tg.length,defaultOpen:!1,children:Tg.map(a=>T("div",{className:"flex items-center gap-2 px-3 py-1.5 mx-1 rounded-md cursor-pointer transition-all",style:{width:"calc(100% - 8px)"},onMouseEnter:l=>l.currentTarget.style.background="var(--bg-muted)",onMouseLeave:l=>l.currentTarget.style.background="transparent",children:[v("i",{className:`${a.icon} text-[10px]`,style:{color:"var(--brand-primary)"}}),v("span",{className:"text-xs",style:{color:"var(--text-primary)"},children:a.label})]},a.id))}),v(Wd,{title:"Automatizaciones",icon:"fas fa-robot",count:Mg.filter(a=>a.active).length,defaultOpen:!1,children:Mg.map(a=>T("div",{className:"flex items-center gap-2 px-3 py-1.5 mx-1 rounded-md",style:{width:"calc(100% - 8px)"},children:[v("span",{className:`w-1.5 h-1.5 rounded-full ${a.active?"bg-green-500":"bg-slate-400"}`}),v("span",{className:"text-xs flex-1",style:{color:"var(--text-primary)"},children:a.label}),v("span",{className:"text-[9px] font-bold",style:{color:a.active?"#22c55e":"var(--text-secondary)"},children:a.active?"ON":"OFF"})]},a.id))})]})]})},k2={c1:{name:"Mar\xEDa Garc\xEDa",phone:"+57 301 234 5678",email:"maria@gmail.com",city:"Bogot\xE1",totalOrders:8,totalSpent:"$4,250,000",lastOrder:"PED-1847",sentiment:"neutral",tags:["VIP","Frecuente","Muebler\xEDa"],timeline:[{time:"2m",event:"Pregunt\xF3 por estado de pedido",icon:"fas fa-comment"},{time:"1d",event:"Pedido PED-1847 en PRODUCTION",icon:"fas fa-industry"},{time:"3d",event:"Transici\xF3n a IN_CUTTING (Control)",icon:"fas fa-check-circle"},{time:"1w",event:"Tracking Link Generado",icon:"fas fa-link"}]},c2:{name:"Carlos Ruiz",phone:"+57 310 987 6543",email:"cruiz@empresa.co",city:"Medell\xEDn",totalOrders:3,totalSpent:"$1,890,000",lastOrder:"PED-1832",sentiment:"positive",tags:["Empresa","Nuevo"],timeline:[{time:"15m",event:"Solicit\xF3 cotizaci\xF3n de mesa",icon:"fas fa-comment"},{time:"2d",event:"RuleEngine Trigger: NEW Order",icon:"fas fa-bolt"}]}},N2={positive:{icon:"fas fa-smile",color:"#22c55e",label:"Positivo"},neutral:{icon:"fas fa-meh",color:"#f59e0b",label:"Neutral"},negative:{icon:"fas fa-frown",color:"#ef4444",label:"Negativo"}},fo=({label:r,value:e})=>T("div",{className:"flex justify-between items-center py-1.5",children:[v("span",{className:"text-[10px] font-bold uppercase tracking-wider",style:{color:"var(--text-secondary)"},children:r}),v("span",{className:"text-xs font-semibold",style:{color:"var(--text-primary)"},children:e})]}),E2=({selectedContact:r})=>{let e=r?k2[r]:null;if(!e)return T("div",{className:"flex-1 flex flex-col items-center justify-center gap-3 p-6",children:[v("div",{className:"w-16 h-16 rounded-2xl flex items-center justify-center",style:{background:"var(--bg-muted)"},children:v("i",{className:"fas fa-user-slash text-xl",style:{color:"var(--text-secondary)"}})}),T("p",{className:"text-xs text-center font-medium",style:{color:"var(--text-secondary)"},children:["Selecciona un contacto",v("br",{}),"para ver detalles"]})]});let t=N2[e.sentiment];return T("div",{className:"flex flex-col h-full overflow-y-auto scrollbar-thin",children:[T("div",{className:"p-4 text-center border-b",style:{borderColor:"var(--border-color)"},children:[v("div",{className:"w-14 h-14 rounded-full mx-auto flex items-center justify-center text-white font-bold text-lg mb-3",style:{background:"var(--brand-primary)"},children:e.name.split(" ").map(n=>n[0]).join("")}),v("h3",{className:"font-bold text-sm",style:{color:"var(--text-primary)"},children:e.name}),v("p",{className:"text-[10px] mt-0.5",style:{color:"var(--text-secondary)"},children:e.phone}),v("div",{className:"flex flex-wrap justify-center gap-1 mt-3",children:e.tags.map(n=>v("span",{className:"px-2 py-0.5 rounded-full text-[9px] font-bold",style:{background:"var(--bg-muted)",color:"var(--brand-primary)",border:"1px solid var(--border-color)"},children:n},n))})]}),T("div",{className:"px-4 py-3 border-b",style:{borderColor:"var(--border-color)"},children:[v("div",{className:"text-[10px] font-black uppercase tracking-widest mb-2",style:{color:"var(--text-secondary)"},children:"Sentimiento IA"}),T("div",{className:"flex items-center gap-2 p-2 rounded-lg",style:{background:"var(--bg-muted)"},children:[v("i",{className:`${t.icon} text-lg`,style:{color:t.color}}),T("div",{children:[v("span",{className:"text-xs font-bold",style:{color:t.color},children:t.label}),v("div",{className:"w-full h-1.5 rounded-full mt-1",style:{background:"var(--border-color)"},children:v("div",{className:"h-full rounded-full transition-all",style:{width:e.sentiment==="positive"?"80%":e.sentiment==="neutral"?"50%":"25%",background:t.color}})})]})]})]}),T("div",{className:"px-4 py-3 border-b",style:{borderColor:"var(--border-color)"},children:[v("div",{className:"text-[10px] font-black uppercase tracking-widest mb-2",style:{color:"var(--text-secondary)"},children:"Resumen Cliente"}),v(fo,{label:"Pedidos",value:String(e.totalOrders)}),v(fo,{label:"Total",value:e.totalSpent}),v(fo,{label:"\xDAltimo",value:e.lastOrder}),v(fo,{label:"Ciudad",value:e.city}),v(fo,{label:"Email",value:e.email})]}),T("div",{className:"px-4 py-3",children:[v("div",{className:"text-[10px] font-black uppercase tracking-widest mb-3",style:{color:"var(--text-secondary)"},children:"Actividad Reciente"}),v("div",{className:"space-y-0",children:e.timeline.map((n,i)=>T("div",{className:"flex gap-3 relative",children:[i<e.timeline.length-1&&v("div",{className:"absolute left-[9px] top-5 w-px h-full",style:{background:"var(--border-color)"}}),v("div",{className:"w-5 h-5 rounded-full flex items-center justify-center shrink-0 z-10",style:{background:"var(--bg-muted)",border:"1px solid var(--border-color)"},children:v("i",{className:`${n.icon} text-[8px]`,style:{color:"var(--brand-primary)"}})}),T("div",{className:"pb-4 min-w-0",children:[v("p",{className:"text-[11px] font-medium leading-tight",style:{color:"var(--text-primary)"},children:n.event}),T("span",{className:"text-[9px]",style:{color:"var(--text-secondary)"},children:["Hace ",n.time]})]})]},i))})]})]})},A2=()=>{let[r,e]=oe([{id:"1",text:"Soy tu Agente Vocal asignado. \xBFEn qu\xE9 te ayudo con tus flujos?",type:"system"}]),[t,n]=oe(""),[i,s]=oe(!1),o=jd(null);yn(()=>{o.current&&(o.current.scrollTop=o.current.scrollHeight)},[r]),yn(()=>{let l=Eg.onEvent(d=>{d.event_type==="message_sent"&&d.data?.target==="vocal_domain_agent"||d.event_type==="message_sent"&&d.data?.intent==="vocal_response"&&(e(u=>[...u,{id:Date.now().toString(),text:d.data.payload,type:"agent"}]),s(!1))}),c=null;try{c=new EventSource("http://localhost:3001/api/events"),c.addEventListener("whatsapp:message_received",d=>{try{let u=JSON.parse(d.data);e(h=>[...h,{id:Date.now().toString(),text:`\u{1F4F1} [WA] ${u.profileName||u.from}: ${u.text||"Archivo Adjunto"}`,type:"user"}]),s(!0),setTimeout(()=>{e(h=>[...h,{id:Date.now().toString(),text:"Regla disparada: Mensaje recibido. Evaluando intenci\xF3n...",type:"system"}]),s(!1)},1e3)}catch{}}),c.addEventListener("whatsapp:status_update",d=>{try{let u=JSON.parse(d.data);e(h=>[...h,{id:Date.now().toString(),text:`\u2714\uFE0F [Estado WA] ${u.status} a ${u.recipient_id}`,type:"system"}])}catch{}}),c.onerror=()=>{c?.close()}}catch{console.log("SSE Error, falling back to local kernel")}return()=>{l(),c&&c.close()}},[]);let a=async()=>{if(!t.trim())return;let l=t;n(""),e(c=>[...c,{id:Date.now().toString(),text:l,type:"user"}]),s(!0);try{await Eg.execute("spawn_task",{target_id:"vocal_domain_agent",role:"vocal_domain",intent:"user_prompt",payload:l}),setTimeout(()=>{s(!1),e(c=>c.some(d=>d.type==="agent"&&parseInt(d.id)>Date.now()-2e3)?c:[...c,{id:Date.now().toString(),text:"Evaluando el dise\xF1o de tu flujo actual... Parece \xF3ptimo para WhatsApp Business.",type:"agent"}])},1500)}catch(c){console.error("Error contacting agent:",c),s(!1)}};return T("div",{className:"h-full flex flex-col font-sans",style:{background:"var(--bg-elevated)",color:"var(--text-primary)"},children:[T("div",{className:"h-11 shrink-0 flex items-center px-3 border-b gap-2",style:{borderColor:"var(--border-color)"},children:[v("div",{className:"w-6 h-6 rounded-full bg-emerald-500/20 flex items-center justify-center border border-emerald-500/50",children:v("i",{className:"fas fa-robot text-emerald-400 text-xs text-brand animate-pulse"})}),v("span",{className:"font-bold text-xs",children:"Agente Decido"}),v("span",{className:"ml-auto px-1.5 py-0.5 rounded text-[9px] font-bold bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:"VOCAL DOMAIN"})]}),T("div",{ref:o,className:"flex-1 min-h-0 overflow-y-auto p-3 space-y-3",children:[r.map(l=>T("div",{className:`flex flex-col max-w-[90%] ${l.type==="user"?"ml-auto items-end":"mr-auto items-start"}`,children:[l.type==="system"&&v("div",{className:"text-[10px] text-center w-full my-2 italic",style:{color:"var(--text-secondary)"},children:l.text}),l.type!=="system"&&v("div",{className:`text-xs px-3 py-2 rounded-xl leading-relaxed ${l.type==="user"?"bg-brand text-white rounded-br-sm":"bg-white/5 border border-white/10 rounded-bl-sm"}`,children:l.text})]},l.id)),i&&T("div",{className:"flex items-center gap-1.5 p-2 bg-white/5 w-fit rounded-lg border border-white/10 rounded-bl-sm",children:[v("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500/50 animate-bounce",style:{animationDelay:"0ms"}}),v("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500/50 animate-bounce",style:{animationDelay:"150ms"}}),v("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500/50 animate-bounce",style:{animationDelay:"300ms"}})]})]}),v("div",{className:"p-2 shrink-0 border-t",style:{borderColor:"var(--border-color)"},children:T("div",{className:"flex items-end gap-2 bg-white/5 border border-white/10 rounded-lg p-1.5 focus-within:border-emerald-500/50 transition-colors",children:[v("textarea",{value:t,onChange:l=>n(l.target.value),onKeyDown:l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),a())},placeholder:"Preg\xFAntale al Agente...",className:"flex-1 bg-transparent resize-none text-xs outline-none p-1.5 min-h-[32px] max-h-[100px]",rows:t.split(`
48
+ `).length>1?Math.min(t.split(`
49
+ `).length,4):1}),v("button",{onClick:a,disabled:!t.trim()||i,className:"w-8 h-8 shrink-0 rounded-md bg-white/10 hover:bg-white/20 text-emerald-400 flex items-center justify-center transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:v("i",{className:"fas fa-paper-plane text-xs"})})]})})]})},Vd=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",T2=({selectedContact:r})=>{let[e,t]=oe([]),[n,i]=oe(""),[s,o]=oe("COPILOT"),[a,l]=oe(null),c=jd(null),d=po(async()=>{if(!r){t([]);return}try{let h=(await(await fetch(`${Vd}/api/whatsapp/messages?phone=${r}&limit=50`)).json()).reverse().map(f=>({id:f.id.toString(),text:f.body||(f.message_type==="image"?"\u{1F4F8} [Imagen]":"\u{1F4CE} [Archivo]"),sender:f.direction==="INBOUND"?"user":"bot",timestamp:new Date(f.created_at),isIncoming:f.direction==="INBOUND",status:f.direction==="OUTBOUND"?"sent":void 0}));t(h)}catch(h){console.error("Failed to fetch messages:",h)}},[r]);yn(()=>{d();let h=Pg(Vd,{transports:["websocket","polling"]});return h.on("connect",()=>console.log("[ChatTab] Connected to WebSocket")),h.on("wa:message_received",f=>{r&&f.from===r&&d()}),h.on("wa:message_sent",f=>{r&&f.to===r&&d()}),h.on("wa:status_update",f=>{r&&d()}),l(h),()=>{h.disconnect()}},[r,d]),yn(()=>{c.current?.scrollIntoView({behavior:"smooth"})},[e]);let u=async()=>{if(!n.trim()||!r)return;let h=n;i("");let f={id:`temp-${Date.now()}`,text:h,sender:"bot",timestamp:new Date,isIncoming:!1,status:"sent"};t(p=>[...p,f]);try{await fetch(`${Vd}/api/whatsapp/send-chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({to:r,text:h})})}catch(p){console.error("Send failed:",p)}};return T("div",{className:"flex-1 flex flex-col min-h-0 overflow-hidden relative",children:[T("div",{className:"h-12 shrink-0 flex items-center justify-between px-4 border-b",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},children:[T("div",{className:"flex items-center gap-3",children:[v("div",{className:"w-8 h-8 rounded-full flex items-center justify-center text-white text-[10px] font-bold",style:{background:"#25D366"},children:v("i",{className:"fab fa-whatsapp text-sm"})}),T("div",{children:[v("span",{className:"text-xs font-bold",style:{color:"var(--text-primary)"},children:r?"+"+r:"Seleccionar contacto"}),v("span",{className:"text-[10px] block",style:{color:"var(--text-secondary)"},children:r?"en l\xEDnea":"\u2014"})]})]}),v("div",{className:"flex items-center gap-1 p-0.5 rounded-lg",style:{background:"var(--bg-muted)"},children:["MANUAL","COPILOT","AUTO"].map(h=>T("button",{onClick:()=>o(h),className:"px-2.5 py-1 rounded-md text-[9px] font-black tracking-wide transition-all",style:{background:s===h?"var(--brand-primary)":"transparent",color:s===h?"white":"var(--text-secondary)"},children:[h==="COPILOT"&&v("i",{className:"fas fa-wand-sparkles mr-1 text-[8px]"}),h]},h))})]}),T("div",{className:"flex-1 overflow-y-auto p-4 space-y-3 scrollbar-thin",style:{background:"var(--bg-primary)"},children:[v("div",{className:"absolute inset-0 opacity-[0.02] pointer-events-none",style:{backgroundImage:`url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23888' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`}}),T("div",{className:"relative z-10 space-y-3",children:[e.map(h=>v("div",{className:`flex ${h.sender==="system"?"justify-center":h.isIncoming?"justify-start":"justify-end"}`,children:h.sender==="system"?T("span",{className:"px-3 py-1 rounded-full text-[9px] font-bold uppercase tracking-widest",style:{background:"var(--bg-muted)",color:"var(--text-secondary)",border:"1px solid var(--border-color)"},children:[v("i",{className:"fas fa-info-circle mr-1"}),h.text]}):h.sender==="copilot"?T("div",{className:"max-w-[75%] p-3 rounded-xl rounded-bl-none shadow-lg border",style:{background:"linear-gradient(135deg, rgba(99,102,241,0.15), rgba(168,85,247,0.15))",borderColor:"rgba(139,92,246,0.3)"},children:[T("div",{className:"flex items-center gap-1.5 mb-1.5",children:[v("i",{className:"fas fa-wand-sparkles text-[10px]",style:{color:"#a855f7"}}),v("span",{className:"text-[9px] font-black uppercase tracking-wide",style:{color:"#a855f7"},children:"CoPilot IA"})]}),v("p",{className:"text-xs italic leading-relaxed",style:{color:"var(--text-primary)"},children:h.text}),T("div",{className:"mt-2 flex gap-1.5",children:[v("button",{className:"flex-1 px-2 py-1 rounded-md text-[9px] font-bold transition-all",style:{background:"var(--bg-muted)",color:"var(--text-secondary)",border:"1px solid var(--border-color)"},children:"Ignorar"}),v("button",{className:"flex-1 px-2 py-1 rounded-md text-[9px] font-bold transition-all text-white",style:{background:"#8b5cf6"},children:"Aplicar"})]})]}):T("div",{className:`max-w-[70%] p-3 rounded-xl shadow-sm text-xs leading-relaxed ${h.isIncoming?"rounded-tl-none":"rounded-tr-none"}`,style:{background:h.isIncoming?"var(--bg-elevated)":"rgba(37,211,102,0.15)",color:"var(--text-primary)",border:h.isIncoming?"1px solid var(--border-color)":"1px solid rgba(37,211,102,0.2)"},children:[v("p",{className:"whitespace-pre-wrap",children:h.text}),T("div",{className:"flex items-center justify-end gap-1 mt-1.5",children:[v("span",{className:"text-[9px]",style:{color:"var(--text-secondary)"},children:h.timestamp.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})}),!h.isIncoming&&h.status&&v("i",{className:`fas fa-check-double text-[9px] ${h.status==="read"?"text-blue-400":""}`,style:{color:h.status==="read"?"#38bdf8":"var(--text-secondary)"}})]})]})},h.id)),v("div",{ref:c})]})]}),T("div",{className:"shrink-0 p-3 border-t",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},children:[T("div",{className:"flex items-center gap-2",children:[v("button",{className:"w-8 h-8 rounded-lg flex items-center justify-center transition-all",style:{color:"var(--text-secondary)"},onMouseEnter:h=>h.currentTarget.style.background="var(--bg-muted)",onMouseLeave:h=>h.currentTarget.style.background="transparent",children:v("i",{className:"fas fa-paperclip text-sm"})}),T("div",{className:"flex-1 flex items-center gap-2 px-3 py-2 rounded-xl",style:{background:"var(--bg-muted)",border:"1px solid var(--border-color)"},children:[v("input",{type:"text",placeholder:"Escribe un mensaje...",className:"flex-1 bg-transparent outline-none text-xs",style:{color:"var(--text-primary)"},value:n,onChange:h=>i(h.target.value),onKeyDown:h=>h.key==="Enter"&&u()}),v("button",{className:"text-xs",style:{color:"var(--text-secondary)"},children:v("i",{className:"fas fa-face-smile"})})]}),v("button",{onClick:u,className:"w-9 h-9 rounded-xl flex items-center justify-center text-white transition-all shadow-md",style:{background:"#25D366"},children:v("i",{className:`fas ${n.trim()?"fa-paper-plane":"fa-microphone"} text-sm`})})]}),s==="COPILOT"&&T("div",{className:"flex items-center gap-2 mt-2 px-2",children:[v("i",{className:"fas fa-wand-sparkles text-[9px]",style:{color:"#a855f7"}}),v("span",{className:"text-[9px]",style:{color:"var(--text-secondary)"},children:"CoPilot activo \u2014 sugerencias autom\xE1ticas"})]})]})]})},Dg={incoming:{icon:v(b2,{size:14}),colorClass:"text-emerald-400",bgClass:"from-emerald-500/10 to-transparent"},outgoing:{icon:v(g2,{size:14}),colorClass:"text-blue-400",bgClass:"from-blue-500/10 to-transparent"},system:{icon:v(m2,{size:14}),colorClass:"text-purple-400",bgClass:"from-purple-500/10 to-transparent"}},Bg=Ig(({id:r,data:e,selected:t})=>{let n=e||{},i=Dg[n.type]||Dg.incoming,s=T("div",{className:"flex justify-between items-center w-full min-w-[140px]",children:[T("div",{className:"flex items-center gap-2",children:[v("span",{className:i.colorClass,children:i.icon}),v("span",{children:n.label})]}),n.time&&v("span",{className:"text-[9px] text-zinc-500 font-mono tracking-wider ml-4",children:n.time})]});return T(Lg,{id:r,selected:t,title:s,className:`border border-white/5 bg-linear-to-br ${i.bgClass} backdrop-blur-md`,children:[v(ir,{type:"target",position:nr.Left,className:"!w-2 !h-2 !bg-zinc-800 !border-[1.5px] !border-zinc-400"}),v("div",{className:"p-3 text-xs leading-relaxed text-zinc-300 font-light break-words max-w-[240px]",children:n.text}),v(ir,{type:"source",position:nr.Right,className:`!w-2 !h-2 !bg-zinc-800 !border-[1.5px] ${i.colorClass.replace("text-","border-")}`})]})});Bg.displayName="MessageNode";var Og={reply:{icon:v(S2,{size:14}),colorClass:"text-emerald-400",bgClass:"from-emerald-500/10 to-transparent"},create_order:{icon:v(w2,{size:14}),colorClass:"text-amber-400",bgClass:"from-amber-500/10 to-transparent"},escalate:{icon:v(y2,{size:14}),colorClass:"text-rose-400",bgClass:"from-rose-500/10 to-transparent"},analyze:{icon:v(v2,{size:14}),colorClass:"text-violet-400",bgClass:"from-violet-500/10 to-transparent"},decision:{icon:v(x2,{size:14}),colorClass:"text-cyan-400",bgClass:"from-cyan-500/10 to-transparent"}},Fg=Ig(({id:r,data:e,selected:t})=>{let n=e||{},i=Og[n?.actionType]||Og.reply,s=T("div",{className:"flex items-center gap-2",children:[v("span",{className:i.colorClass,children:i.icon}),v("span",{children:n?.label||"Action"})]});return T(Lg,{id:r,selected:t,title:s,hideTarget:!0,hideSource:!0,className:`min-w-[200px] border border-white/5 bg-linear-to-br ${i.bgClass} backdrop-blur-md`,children:[v(ir,{type:"target",position:nr.Left,className:"!w-2 !h-2 !bg-zinc-800 !border-[1.5px] !border-zinc-400"}),n.description&&v("div",{className:"px-3 py-2 text-xs text-zinc-400 font-light leading-relaxed",children:n.description}),v(ir,{type:"source",position:nr.Right,className:`!w-2 !h-2 !bg-zinc-800 !border-[1.5px] ${i.colorClass.replace("text-","border-")}`}),n.actionType==="decision"&&v(ir,{type:"source",position:nr.Bottom,id:"no",className:"!w-2 !h-2 !bg-zinc-800 !border-[1.5px] border-rose-500"})]})});Fg.displayName="BotActionNode";var M2=({token:r="demo-token-123",onClose:e})=>{let t=`http://localhost:3001/track/${r}`,[n,i]=oe(!0);return v("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4 animate-in fade-in",children:T("div",{className:"w-full max-w-[400px] bg-[#0E1525] rounded-[24px] overflow-hidden border border-white/10 shadow-2xl flex flex-col h-[700px] max-h-[90vh] relative animate-in zoom-in-95",children:[T("div",{className:"absolute top-4 right-4 z-10 flex gap-2",children:[v("button",{onClick:()=>window.open(t,"_blank"),className:"w-8 h-8 rounded-full bg-white/10 backdrop-blur-md flex items-center justify-center text-white/70 hover:text-white hover:bg-white/20 transition-colors",title:"Abrir en nueva pesta\xF1a",children:v("i",{className:"fas fa-external-link-alt text-xs"})}),v("button",{onClick:e,className:"w-8 h-8 rounded-full bg-white/10 backdrop-blur-md flex items-center justify-center text-white/70 hover:text-white hover:bg-white/20 transition-colors",title:"Cerrar vista previa",children:v("i",{className:"fas fa-times text-xs"})})]}),v("div",{className:"h-7 w-full bg-black flex justify-center items-start shrink-0",children:v("div",{className:"w-[120px] h-5 bg-black rounded-b-xl"})}),v("div",{className:"px-4 py-2 bg-black/50 border-b border-white/5 flex items-center justify-center shrink-0",children:T("div",{className:"bg-white/5 rounded-lg px-3 py-1 flex items-center gap-2 text-[10px] text-white/40 w-fit",children:[v("i",{className:"fas fa-lock text-[8px]"}),T("span",{children:["decido.com/track/",r]})]})}),T("div",{className:"flex-1 relative bg-black",children:[n&&T("div",{className:"absolute inset-0 flex flex-col items-center justify-center bg-[#0E1525] text-white/50",children:[v("i",{className:"fas fa-circle-notch fa-spin text-2xl text-emerald-500 mb-3"}),v("span",{className:"text-xs font-medium",children:"Cargando vista m\xF3vil..."})]}),v("iframe",{src:t,className:`w-full h-full border-none transition-opacity duration-300 ${n?"opacity-0":"opacity-100"}`,onLoad:()=>i(!1),title:"Tracking Portal Preview"})]}),v("div",{className:"h-6 w-full bg-black flex justify-center items-center shrink-0",children:v("div",{className:"w-[120px] h-1 bg-white/20 rounded-full"})})]})})},D2={messageNode:Bg,botAction:Fg},O2=[{id:"trigger",type:"messageNode",position:{x:50,y:300},data:{label:"Mensaje Entrante de WhatsApp",type:"incoming",text:"Hola, \xBFc\xF3mo va mi pedido XJ-901?",time:"10:05 AM"}},{id:"ai-intent",type:"botAction",position:{x:400,y:280},data:{label:"Reconocimiento Intenci\xF3n IA",actionType:"analyze",description:'Detectar Intenci\xF3n: "Estado de Pedido"'}},{id:"db-check",type:"botAction",position:{x:750,y:150},data:{label:"Acci\xF3n Ejecutada",actionType:"decision",description:"Action: GENERATE_TRACKING_LINK"}},{id:"escalate-human",type:"botAction",position:{x:750,y:400},data:{label:"Evaluar Sentimiento (Frustrado)",actionType:"escalate",description:"Ruteo Inmediato a Humano"}},{id:"reply-status",type:"messageNode",position:{x:1050,y:150},data:{label:"Regla: SEND_WA_TEMPLATE",type:"outgoing",text:`Template: pedido_produccion
50
+ Par\xE1metros: [legacyId, trackUrl]`,time:"10:06 AM"}},{id:"assign-agent",type:"messageNode",position:{x:1050,y:400},data:{label:"Soporte Asignado",type:"system",text:"Asignando Chat #3421 (Humano en la ruta)"}}],R2=[{id:"e1",source:"trigger",target:"ai-intent",animated:!0,style:{stroke:"#22c55e"},markerEnd:{type:Dr.ArrowClosed,color:"#22c55e"}},{id:"e2",source:"ai-intent",target:"db-check",label:"Intent: Query Order",animated:!0,style:{stroke:"#3b82f6"},markerEnd:{type:Dr.ArrowClosed,color:"#3b82f6"}},{id:"e3",source:"db-check",target:"reply-status",label:"Pedido Encontrado",style:{stroke:"#22c55e"},markerEnd:{type:Dr.ArrowClosed,color:"#22c55e"}},{id:"e4",source:"ai-intent",target:"escalate-human",label:"Intent: Queja/Reclamo",style:{stroke:"#ef4444"},markerEnd:{type:Dr.ArrowClosed,color:"#ef4444"}},{id:"e5",source:"db-check",sourceHandle:"no",target:"escalate-human",label:"Pedido No Encontrado",style:{stroke:"#ef4444",strokeDasharray:"5 5"},markerEnd:{type:Dr.ArrowClosed,color:"#ef4444"}},{id:"e6",source:"escalate-human",target:"assign-agent",style:{stroke:"#f59e0b"},markerEnd:{type:Dr.ArrowClosed,color:"#f59e0b"}}],I2=()=>{let[r,e]=oe(O2),[t,n]=oe(R2),[i,s]=oe(!1),o=po(d=>{},[]),a=po(d=>{},[]),l=po(d=>{n(u=>[...u,{...d,id:`e-${Date.now()}`,animated:!0}])},[n]),c=po((d,u)=>{(u.data?.description?.includes("GENERATE_TRACKING_LINK")||u.data?.text?.includes("trackUrl"))&&s(!0)},[]);return T("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden",children:[T("div",{className:"h-9 shrink-0 flex items-center gap-2 px-3 border-b",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},children:[T("span",{className:"text-[10px] font-black uppercase tracking-widest",style:{color:"var(--text-secondary)"},children:[v("i",{className:"fas fa-project-diagram mr-1.5"}),"Flujo de Conversaci\xF3n"]}),v("div",{className:"flex-1"}),v("div",{className:"flex items-center gap-1",children:[{icon:"fas fa-comment-dots",label:"Mensaje",color:"#25D366"},{icon:"fas fa-brain",label:"IA",color:"#8b5cf6"},{icon:"fas fa-code-branch",label:"Decisi\xF3n",color:"#06b6d4"},{icon:"fas fa-cart-plus",label:"Pedido",color:"#f59e0b"}].map(d=>T("div",{className:"flex items-center gap-1 px-2 py-1 rounded-md text-[9px] font-bold cursor-grab transition-all",style:{border:"1px dashed var(--border-color)",color:d.color},title:`Arrastra para agregar: ${d.label}`,children:[v("i",{className:d.icon}),v("span",{children:d.label})]},d.label))}),v("div",{className:"h-5 w-px mx-1",style:{background:"var(--border-color)"}}),v("button",{className:"px-2 py-1 rounded-md text-[9px] font-bold transition-all",style:{color:"var(--text-secondary)"},title:"Fit view",children:v("i",{className:"fas fa-compress-arrows-alt"})})]}),v("div",{className:"flex-1 min-h-0 relative",children:v(kg,{nodes:r,edges:t,onNodesChange:o,onEdgesChange:a,onConnect:l,onNodeClick:c,nodeTypes:D2})}),i&&v(M2,{onClose:()=>s(!1)})]})},P2=[{hour:"6AM",sent:2,received:5},{hour:"7AM",sent:8,received:12},{hour:"8AM",sent:15,received:22},{hour:"9AM",sent:28,received:35},{hour:"10AM",sent:42,received:48},{hour:"11AM",sent:38,received:41},{hour:"12PM",sent:20,received:25},{hour:"1PM",sent:15,received:18},{hour:"2PM",sent:30,received:33},{hour:"3PM",sent:45,received:52},{hour:"4PM",sent:35,received:40},{hour:"5PM",sent:22,received:28},{hour:"6PM",sent:10,received:15}],L2=[{label:"Mensajes Hoy",value:"347",change:"+12%",icon:"fas fa-paper-plane",color:"#22c55e",positive:!0},{label:"Tiempo Respuesta",value:"2.4s",change:"-18%",icon:"fas fa-clock",color:"#3b82f6",positive:!0},{label:"Tasa Conversi\xF3n",value:"24.5%",change:"+3.2%",icon:"fas fa-funnel-dollar",color:"#f59e0b",positive:!0},{label:"Chats Activos",value:"12",change:"+2",icon:"fas fa-comments",color:"#8b5cf6",positive:!0},{label:"Pedidos v\xEDa WA",value:"8",change:"+1",icon:"fas fa-cart-plus",color:"#06b6d4",positive:!0},{label:"Escalamientos",value:"3",change:"+1",icon:"fas fa-exclamation-triangle",color:"#ef4444",positive:!1}],Rg=[{intent:"Estado de Pedido",count:156,pct:45},{intent:"Cotizaci\xF3n",count:89,pct:26},{intent:"Cat\xE1logo",count:52,pct:15},{intent:"Reclamo",count:28,pct:8},{intent:"Otro",count:22,pct:6}],B2=["#22c55e","#3b82f6","#f59e0b","#ef4444","#6b7280"],F2=({data:r})=>{let e=Math.max(...r.map(t=>Math.max(t.sent,t.received)));return v("div",{className:"flex items-end gap-1 h-32",children:r.map((t,n)=>T("div",{className:"flex-1 flex flex-col items-center gap-0.5",children:[T("div",{className:"w-full flex items-end gap-px",style:{height:"100px"},children:[v("div",{className:"flex-1 rounded-t-sm transition-all duration-500",style:{height:`${t.received/e*100}%`,background:"rgba(37,211,102,0.6)"},title:`Recibidos: ${t.received}`}),v("div",{className:"flex-1 rounded-t-sm transition-all duration-500",style:{height:`${t.sent/e*100}%`,background:"rgba(59,130,246,0.6)"},title:`Enviados: ${t.sent}`})]}),v("span",{className:"text-[7px] font-bold",style:{color:"var(--text-secondary)"},children:t.hour})]},n))})},_2=()=>{let[r,e]=oe({});return yn(()=>{let t=setTimeout(()=>{let n={};Rg.forEach(i=>{n[i.intent]=i.pct}),e(n)},200);return()=>clearTimeout(t)},[]),T("div",{className:"flex-1 overflow-y-auto p-4 space-y-4 scrollbar-thin",style:{background:"var(--bg-primary)"},children:[v("div",{className:"grid grid-cols-3 gap-3",children:L2.map((t,n)=>T("div",{className:"p-3 rounded-xl border transition-all hover:shadow-lg",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)",animationDelay:`${n*80}ms`},children:[T("div",{className:"flex items-center justify-between mb-2",children:[v("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center",style:{background:`${t.color}15`},children:v("i",{className:`${t.icon} text-xs`,style:{color:t.color}})}),v("span",{className:`text-[10px] font-bold px-1.5 py-0.5 rounded ${t.positive?"text-green-500":"text-red-500"}`,style:{background:t.positive?"rgba(34,197,94,0.1)":"rgba(239,68,68,0.1)"},children:t.change})]}),v("div",{className:"text-xl font-black",style:{color:"var(--text-primary)"},children:t.value}),v("div",{className:"text-[10px] font-medium mt-0.5",style:{color:"var(--text-secondary)"},children:t.label})]},t.label))}),T("div",{className:"grid grid-cols-2 gap-3",children:[T("div",{className:"p-4 rounded-xl border",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},children:[T("div",{className:"flex items-center justify-between mb-4",children:[T("h3",{className:"text-xs font-bold",style:{color:"var(--text-primary)"},children:[v("i",{className:"fas fa-chart-bar mr-2",style:{color:"var(--brand-primary)"}}),"Actividad por Hora"]}),T("div",{className:"flex items-center gap-3 text-[9px]",children:[T("span",{className:"flex items-center gap-1",children:[v("span",{className:"w-2 h-2 rounded-sm",style:{background:"rgba(37,211,102,0.6)"}}),v("span",{style:{color:"var(--text-secondary)"},children:"Recibidos"})]}),T("span",{className:"flex items-center gap-1",children:[v("span",{className:"w-2 h-2 rounded-sm",style:{background:"rgba(59,130,246,0.6)"}}),v("span",{style:{color:"var(--text-secondary)"},children:"Enviados"})]})]})]}),v(F2,{data:P2})]}),T("div",{className:"p-4 rounded-xl border",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},children:[T("h3",{className:"text-xs font-bold mb-4",style:{color:"var(--text-primary)"},children:[v("i",{className:"fas fa-brain mr-2",style:{color:"var(--brand-primary)"}}),"Intenciones Detectadas"]}),v("div",{className:"space-y-3",children:Rg.map((t,n)=>T("div",{children:[T("div",{className:"flex items-center justify-between mb-1",children:[v("span",{className:"text-[11px] font-semibold",style:{color:"var(--text-primary)"},children:t.intent}),T("span",{className:"text-[10px] font-bold",style:{color:"var(--text-secondary)"},children:[t.count," (",t.pct,"%)"]})]}),v("div",{className:"h-2 rounded-full overflow-hidden",style:{background:"var(--bg-muted)"},children:v("div",{className:"h-full rounded-full transition-all duration-1000 ease-out",style:{width:`${r[t.intent]||0}%`,background:B2[n]}})})]},t.intent))})]})]}),T("div",{className:"p-4 rounded-xl border",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},children:[T("h3",{className:"text-xs font-bold mb-4",style:{color:"var(--text-primary)"},children:[v("i",{className:"fas fa-fire-alt mr-2",style:{color:"var(--brand-primary)"}}),"Heatmap Semanal"]}),T("div",{className:"grid gap-1",style:{gridTemplateColumns:"auto repeat(24, 1fr)"},children:[v("div",{}),Array.from({length:24},(t,n)=>v("div",{className:"text-[7px] text-center font-bold",style:{color:"var(--text-secondary)"},children:n},n)),["Lun","Mar","Mi\xE9","Jue","Vie","S\xE1b","Dom"].map((t,n)=>T(Ka.Fragment,{children:[v("div",{className:"text-[9px] font-bold pr-2 flex items-center",style:{color:"var(--text-secondary)"},children:t}),Array.from({length:24},(i,s)=>{let o=Math.random(),a=n>=5,l=s>=7&&s<=18,c=(a?.3:1)*(l?1:.4)*o;return v("div",{className:"aspect-square rounded-sm transition-all hover:ring-1 hover:ring-white/30 cursor-pointer",style:{background:c>.6?"#22c55e":c>.3?"rgba(34,197,94,0.4)":c>.1?"rgba(34,197,94,0.15)":"var(--bg-muted)"},title:`${t} ${s}:00 \u2014 ${Math.floor(c*50)} mensajes`},s)})]},t))]})]})]})},z2=()=>{let[r,e]=oe(""),[t,n]=oe("text"),[i,s]=oe("Hola desde Decido OS \u{1F680}"),[o,a]=oe("hello_world"),[l,c]=oe("en_US"),[d,u]=oe(!1),[h,f]=oe(null),[p,m]=oe([]),[g,b]=oe(""),[y,x]=oe(!1),[N,C]=oe([]),[w,k]=oe([]),[A,S]=oe(!1);Ka.useEffect(()=>{let E=localStorage.getItem("wa_api_tester_phones");if(E)try{m(JSON.parse(E))}catch{}M()},[]),Ka.useEffect(()=>{let E=w.find($=>$.name===o&&$.language===l);if(E){let $=E.components?.find(G=>G.type==="BODY"||G.type==="body");if($&&$.text){let G=$.text.match(/\{\{\d+\}\}/g);if(G){let W=Math.max(...G.map(he=>parseInt(he.replace(/\{|\}/g,""))));C(he=>{let _=[...he];for(;_.length<W;)_.push("");return _.slice(0,W)});return}}}C([])},[o,l,w]);let M=async()=>{S(!0);try{let E=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",$=await fetch(`${E}/api/whatsapp/templates`);if($.ok){let G=await $.json();!G.error&&Array.isArray(G)&&(k(G),G.length>0&&(a(G[0].name),c(G[0].language)))}}catch(E){console.error("Failed to fetch templates",E)}finally{S(!1)}},D=()=>{if(!r||!g)return;let E=[...p,{name:g,number:r}];m(E),localStorage.setItem("wa_api_tester_phones",JSON.stringify(E)),b(""),x(!1)},O=E=>{let $=p.filter(G=>G.number!==E);m($),localStorage.setItem("wa_api_tester_phones",JSON.stringify($)),r===E&&e("")},H=async()=>{if(!r){f({error:"Ingresa un n\xFAmero de tel\xE9fono v\xE1lido (ej. 52155...)"});return}u(!0),f(null);try{let E={};t==="text"?E.text=i:t==="template"?(E.templateName=o,E.language=l,E.components=[],N.length>0&&E.components.push({type:"body",parameters:N.map(W=>({type:"text",text:W||"n/a"}))})):t==="interactive"&&(E.bodyText=i,E.buttons=[{id:"opt_1",title:"S\xED, me interesa"},{id:"opt_2",title:"No, gracias"}]);let $=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",G=await(await fetch(`${$}/api/whatsapp/send-test`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({to:r,type:t,payload:E})})).json();f(G)}catch(E){f({error:E.message})}finally{u(!1)}};return v("div",{className:"flex-1 flex flex-col min-h-0 overflow-y-auto p-6",style:{background:"var(--bg-primary)",color:"var(--text-primary)"},children:T("div",{className:"max-w-2xl mx-auto w-full space-y-6",children:[T("div",{children:[v("h2",{className:"text-xl font-bold mb-1",children:"WhatsApp API Tester"}),v("p",{className:"text-sm",style:{color:"var(--text-secondary)"},children:"Prueba el env\xEDo de diferentes formatos soportados por Meta Cloud API directamente."})]}),T("div",{className:"p-5 rounded-xl border space-y-4",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},children:[T("div",{children:[T("div",{className:"flex items-center justify-between mb-2",children:[v("label",{className:"block text-xs font-bold uppercase tracking-wider",style:{color:"var(--text-secondary)"},children:"Tel\xE9fono Destino (Sandbox)"}),r&&!p.find(E=>E.number===r)&&v("button",{onClick:()=>x(!y),className:"text-[10px] font-bold text-indigo-400 hover:text-indigo-300 transition-colors",children:"+ Guardar N\xFAmero"})]}),y&&T("div",{className:"flex gap-2 mb-2 p-2 rounded-lg bg-indigo-500/10 border border-indigo-500/30",children:[v("input",{type:"text",placeholder:"Nombre (ej. Mi Celular)",className:"flex-1 px-3 py-1.5 text-xs rounded border outline-none bg-black/20 text-white border-transparent focus:border-indigo-500",value:g,onChange:E=>b(E.target.value)}),v("button",{onClick:D,className:"px-3 py-1.5 bg-indigo-500 text-white rounded text-xs font-bold hover:bg-indigo-600",children:"Guardar"}),v("button",{onClick:()=>x(!1),className:"px-3 py-1.5 bg-white/10 text-white rounded text-xs hover:bg-white/20",children:"Cancelar"})]}),T("div",{className:"flex flex-col gap-2",children:[p.length>0&&v("div",{className:"flex flex-wrap gap-2 mb-1",children:p.map((E,$)=>T("div",{className:`flex items-center gap-2 px-3 py-1.5 rounded-full border border-indigo-500/30 text-xs cursor-pointer transition-colors ${r===E.number?"bg-indigo-500 text-white":"bg-transparent text-indigo-300 hover:bg-indigo-500/10"}`,onClick:()=>e(E.number),children:[v("i",{className:"fas fa-user-circle"}),v("span",{className:"font-bold",children:E.name}),v("button",{onClick:G=>{G.stopPropagation(),O(E.number)},className:"w-4 h-4 rounded-full flex items-center justify-center hover:bg-red-500/50 hover:text-white text-indigo-300 transition-colors",children:v("i",{className:"fas fa-times text-[8px]"})})]},$))}),v("input",{type:"text",placeholder:"Ej. 52155... (Incluye c\xF3digo de pa\xEDs)",className:"w-full px-4 py-2 text-sm rounded-lg border outline-none transition-all focus:border-indigo-500 font-mono",style:{background:"var(--bg-primary)",borderColor:"var(--border-color)",color:"var(--text-primary)"},value:r,onChange:E=>e(E.target.value)}),T("p",{className:"text-[10px] mt-1 text-amber-500/80",children:[v("i",{className:"fas fa-exclamation-triangle mr-1"}),"Aseg\xFArate de que este n\xFAmero est\xE9 registrado en Meta for Developers si tu app est\xE1 en modo desarrollo."]})]})]}),T("div",{children:[v("label",{className:"block text-xs font-bold uppercase tracking-wider mb-2",style:{color:"var(--text-secondary)"},children:"Tipo de Mensaje"}),v("div",{className:"flex gap-2",children:["text","template","interactive"].map(E=>v("button",{onClick:()=>n(E),className:`px-4 py-2 text-sm font-medium rounded-lg transition-all capitalize border ${t===E?"border-indigo-500 bg-indigo-500/10 text-indigo-400":"hover:bg-white/5 opacity-70"}`,style:{borderColor:t===E?"":"var(--border-color)"},children:E},E))})]}),T("div",{className:"pt-2",children:[t==="text"&&T("div",{children:[v("label",{className:"block text-xs font-bold uppercase tracking-wider mb-2",style:{color:"var(--text-secondary)"},children:"Mensaje de Texto"}),v("textarea",{className:"w-full px-4 py-2 text-sm rounded-lg border outline-none min-h-[100px]",style:{background:"var(--bg-primary)",borderColor:"var(--border-color)",color:"var(--text-primary)"},value:i,onChange:E=>s(E.target.value)})]}),t==="template"&&T("div",{children:[v("label",{className:"block text-xs font-bold uppercase tracking-wider mb-2",style:{color:"var(--text-secondary)"},children:"Seleccionar Template (Aprobado)"}),A?v("div",{className:"text-xs p-2 text-indigo-400",children:"Cargando plantillas de Meta..."}):w.length>0?v("select",{className:"w-full px-4 py-2 text-sm rounded-lg border outline-none font-mono",style:{background:"var(--bg-primary)",borderColor:"var(--border-color)",color:"var(--text-primary)"},value:`${o}::${l}`,onChange:E=>{let[$,G]=E.target.value.split("::");a($),c(G)},children:w.filter(E=>E.status==="APPROVED").map(E=>T("option",{value:`${E.name}::${E.language}`,children:[E.name," (",E.language,") [",E.category,"]"]},`${E.id||E.name}_${E.language}`))}):v("input",{type:"text",placeholder:"No se pudieron cargar, ingresa el nombre manual (ej. hello_world)",className:"w-full px-4 py-2 text-sm rounded-lg border outline-none",style:{background:"var(--bg-primary)",borderColor:"var(--border-color)",color:"var(--text-primary)"},value:o,onChange:E=>a(E.target.value)}),N.length>0&&T("div",{className:"mt-4 p-3 rounded bg-black/20 border border-white/5 space-y-3",children:[v("label",{className:"block text-xs font-bold text-indigo-300",children:"Variables Requeridas (Cuerpo)"}),N.map((E,$)=>T("div",{className:"flex items-center gap-2",children:[v("span",{className:"text-xs font-mono text-white/50 w-8",children:`{{${$+1}}}`}),v("input",{type:"text",placeholder:"Valor para la variable (opcional)",className:"flex-1 px-3 py-1.5 text-xs rounded border outline-none bg-black/40 text-white border-transparent focus:border-indigo-500",value:E,onChange:G=>{let W=[...N];W[$]=G.target.value,C(W)}})]},$))]}),v("p",{className:"text-[10px] mt-2",style:{color:"var(--text-secondary)"},children:"Si la plantilla usa variables din\xE1micas en encabezados o links, la API intentar\xE1 autocompletarlos si no se incluyen aqu\xED."})]}),t==="interactive"&&T("div",{children:[v("label",{className:"block text-xs font-bold uppercase tracking-wider mb-2",style:{color:"var(--text-secondary)"},children:"Texto Principal (Con Botones)"}),v("textarea",{className:"w-full px-4 py-2 text-sm rounded-lg border outline-none min-h-[80px]",style:{background:"var(--bg-primary)",borderColor:"var(--border-color)",color:"var(--text-primary)"},value:i,onChange:E=>s(E.target.value)}),T("div",{className:"mt-3 flex gap-2",children:[v("div",{className:"px-3 py-1.5 rounded bg-indigo-500/20 text-indigo-400 text-xs font-bold border border-indigo-500/30",children:"Bot\xF3n: S\xED, me interesa"}),v("div",{className:"px-3 py-1.5 rounded bg-indigo-500/20 text-indigo-400 text-xs font-bold border border-indigo-500/30",children:"Bot\xF3n: No, gracias"})]})]})]}),v("div",{className:"pt-4 border-t flex justify-end",style:{borderColor:"var(--border-color)"},children:T("button",{onClick:H,disabled:d,className:`px-6 py-2 rounded-lg font-bold text-sm text-white flex items-center gap-2 ${d?"opacity-50 cursor-not-allowed":"hover:bg-indigo-600"} bg-indigo-500 transition-colors`,children:[d?v("i",{className:"fas fa-spinner fa-spin"}):v("i",{className:"fab fa-whatsapp"}),d?"Enviando...":"Enviar Prueba"]})})]}),h&&T("div",{className:`p-4 rounded-xl border ${h.error||!h.success?"bg-red-500/10 border-red-500/30":"bg-green-500/10 border-green-500/30"}`,children:[v("h3",{className:`text-sm font-bold mb-2 ${h.error||!h.success?"text-red-400":"text-green-400"}`,children:h.error||!h.success?"Error en el env\xEDo":"\xA1Mensaje enviado con \xE9xito!"}),v("pre",{className:"text-[10px] overflow-x-auto p-3 rounded bg-black/50 text-slate-300",children:JSON.stringify(h,null,2)})]})]})})},$2=()=>{let[r,e]=oe([]),[t,n]=oe(!0),[i,s]=oe(null),[o,a]=oe(!1),[l,c]=oe(""),[d,u]=oe("UTILITY"),[h,f]=oe("es"),[p,m]=oe(""),[g,b]=oe("Hola {{1}}, tu pedido est\xE1 listo."),[y,x]=oe(""),[N,C]=oe([]);yn(()=>{w()},[]);let w=async()=>{n(!0),s(null);try{let S=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",M=await fetch(`${S}/api/whatsapp/templates`);if(!M.ok)throw new Error(`HTTP ${M.status}`);let D=await M.json();if(D.error)throw new Error(D.error);e(D||[])}catch(S){s(S.message)}finally{n(!1)}},k=async()=>{if(!l||!g){s("Por favor completa el nombre y el texto.");return}n(!0);try{let S=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",M=[];p.trim()&&M.push({type:"HEADER",format:"TEXT",text:p});let D=g.match(/\{\{\d+\}\}/g),O;D&&D.length>0&&(O={body_text:[D.map((G,W)=>`Variable${W+1}`)]}),M.push({type:"BODY",text:g,...O?{example:O}:{}}),y.trim()&&M.push({type:"FOOTER",text:y}),N.length>0&&M.push({type:"BUTTONS",buttons:N.map(G=>G.type==="URL"?{type:"URL",text:G.text,url:G.url}:{type:"QUICK_REPLY",text:G.text})});let H={name:l.toLowerCase().replace(/[^a-z0-9_]/g,"_"),language:h,category:d,components:M},E=await fetch(`${S}/api/whatsapp/templates`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(H)}),$=await E.json();if(!E.ok||$.error)throw new Error($.error||"Error al crear la plantilla");a(!1),c(""),m(""),x(""),C([]),b("Hola {{1}}, tu pedido est\xE1 listo."),await w()}catch(S){s(S.message),n(!1)}},A=async S=>{if(window.confirm(`\xBFSeguro que deseas eliminar la plantilla '${S}' permanentemente de Meta?`)){n(!0);try{let M=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",D=await fetch(`${M}/api/whatsapp/templates/${S}`,{method:"DELETE"}),O=await D.json();if(!D.ok||O.error)throw new Error(O.error||"Error al eliminar");await w()}catch(M){s(M.message),n(!1)}}};return v("div",{className:"flex-1 flex flex-col min-h-0 overflow-y-auto p-6",style:{background:"var(--bg-primary)",color:"var(--text-primary)"},children:T("div",{className:"max-w-4xl mx-auto w-full space-y-6",children:[T("div",{className:"flex items-center justify-between",children:[T("div",{children:[v("h2",{className:"text-xl font-bold mb-1",children:"Gestor de Plantillas (Meta)"}),v("p",{className:"text-sm",style:{color:"var(--text-secondary)"},children:"Crea y administra tus plantillas oficiales de WhatsApp sin salir de Decido OS."})]}),v("button",{onClick:()=>a(!o),className:"px-4 py-2 bg-indigo-500 hover:bg-indigo-600 text-white text-sm font-bold rounded-lg transition-colors",children:o?"Ver Lista":"+ Nueva Plantilla"})]}),i&&T("div",{className:"p-4 rounded-lg bg-red-500/10 border border-red-500/30 text-red-400 text-sm font-medium",children:[v("i",{className:"fas fa-exclamation-triangle mr-2"})," ",i]}),o?T("div",{className:"p-6 rounded-xl border space-y-4",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},children:[v("h3",{className:"font-bold text-lg border-b pb-2 mb-4",style:{borderColor:"var(--border-color)"},children:"Crear Nueva Plantilla"}),T("div",{className:"grid grid-cols-2 gap-4",children:[T("div",{children:[v("label",{className:"block text-xs font-bold uppercase tracking-wider mb-2",style:{color:"var(--text-secondary)"},children:"Nombre de la Plantilla"}),v("input",{type:"text",placeholder:"ej. welcome_message_01",className:"w-full px-4 py-2 text-sm rounded-lg border outline-none font-mono",style:{background:"var(--bg-primary)",borderColor:"var(--border-color)",color:"var(--text-primary)"},value:l,onChange:S=>c(S.target.value.toLowerCase().replace(/[^a-z0-9_]/g,"_"))}),v("p",{className:"text-[10px] mt-1",style:{color:"var(--text-secondary)"},children:"Solo min\xFAsculas y guiones bajos (_)"})]}),T("div",{children:[v("label",{className:"block text-xs font-bold uppercase tracking-wider mb-2",style:{color:"var(--text-secondary)"},children:"Categor\xEDa"}),T("select",{className:"w-full px-4 py-2 text-sm rounded-lg border outline-none",style:{background:"var(--bg-primary)",borderColor:"var(--border-color)",color:"var(--text-primary)"},value:d,onChange:S=>u(S.target.value),children:[v("option",{value:"UTILITY",children:"Utilidad (Avisos, tracking, alertas)"}),v("option",{value:"MARKETING",children:"Marketing (Promociones, ventas)"}),v("option",{value:"AUTHENTICATION",children:"Autenticaci\xF3n (OTPs)"})]})]})]}),T("div",{children:[v("label",{className:"block text-xs font-bold uppercase tracking-wider mb-2",style:{color:"var(--text-secondary)"},children:"Idioma (Locale)"}),T("select",{className:"w-full px-4 py-2 text-sm rounded-lg border outline-none max-w-xs",style:{background:"var(--bg-primary)",borderColor:"var(--border-color)",color:"var(--text-primary)"},value:h,onChange:S=>f(S.target.value),children:[v("option",{value:"es",children:"Espa\xF1ol (es)"}),v("option",{value:"es_LA",children:"Espa\xF1ol Latino (es_LA)"}),v("option",{value:"en_US",children:"Ingl\xE9s (en_US)"})]})]}),T("div",{className:"pt-4 border-t space-y-4",style:{borderColor:"var(--border-color)"},children:[v("h4",{className:"text-xs font-bold uppercase tracking-wider",style:{color:"var(--text-secondary)"},children:"Estructura del Mensaje"}),T("div",{children:[v("label",{className:"block text-xs font-bold mb-2",children:"Encabezado (Opcional)"}),v("input",{type:"text",placeholder:"Ej. \xA1Alerta de Promoci\xF3n!",className:"w-full px-4 py-2 text-sm rounded-lg border outline-none",style:{background:"var(--bg-primary)",borderColor:"var(--border-color)",color:"var(--text-primary)"},value:p,onChange:S=>m(S.target.value)})]}),T("div",{children:[v("label",{className:"block text-xs font-bold mb-2",children:"Cuerpo (Obligatorio)"}),v("textarea",{className:"w-full px-4 py-2 text-sm rounded-lg border outline-none min-h-[100px]",style:{background:"var(--bg-primary)",borderColor:"var(--border-color)",color:"var(--text-primary)"},value:g,onChange:S=>b(S.target.value)}),T("p",{className:"text-[10px] mt-1",style:{color:"var(--text-secondary)"},children:["Usa ","{{","1","}}",", ","{{","2","}}"," para variables que se llenar\xE1n din\xE1micamente."]})]}),T("div",{children:[v("label",{className:"block text-xs font-bold mb-2",children:"Pie de p\xE1gina (Opcional)"}),v("input",{type:"text",placeholder:"Ej. Responde STOP para cancelar",className:"w-full px-4 py-2 text-sm rounded-lg border outline-none",style:{background:"var(--bg-primary)",borderColor:"var(--border-color)",color:"var(--text-primary)"},value:y,onChange:S=>x(S.target.value)})]}),T("div",{children:[T("div",{className:"flex items-center justify-between mb-2",children:[v("label",{className:"block text-xs font-bold",children:"Botones (M\xE1x 3)"}),T("div",{className:"flex gap-2",children:[v("button",{onClick:()=>{N.length<3&&C([...N,{type:"QUICK_REPLY",text:"Nuevo Bot\xF3n"}])},className:"px-2 py-1 text-[10px] bg-white/10 hover:bg-white/20 rounded font-bold transition-colors",disabled:N.length>=3,children:"+ Respuesta R\xE1pida"}),v("button",{onClick:()=>{N.length<3&&C([...N,{type:"URL",text:"Saber M\xE1s",url:"https://"}])},className:"px-2 py-1 text-[10px] bg-white/10 hover:bg-white/20 rounded font-bold transition-colors",disabled:N.length>=3,children:"+ Enlace Web (URL)"})]})]}),N.length>0&&v("div",{className:"space-y-2",children:N.map((S,M)=>T("div",{className:"flex gap-2 items-start bg-black/20 p-2 rounded-lg border",style:{borderColor:"var(--border-color)"},children:[T("div",{className:"flex-1 space-y-2",children:[T("div",{className:"flex items-center gap-2",children:[v("span",{className:"text-[10px] font-bold px-2 py-1 bg-white/10 rounded",children:S.type==="URL"?"\u{1F310} URL":"\u21AA\uFE0F RESPUESTA"}),v("input",{type:"text",placeholder:"Texto del bot\xF3n (ej. Comprar)",className:"flex-1 px-3 py-1.5 text-xs rounded border outline-none",style:{background:"var(--bg-primary)",borderColor:"var(--border-color)",color:"var(--text-primary)"},value:S.text,onChange:D=>{let O=[...N];O[M].text=D.target.value,C(O)}})]}),S.type==="URL"&&v("input",{type:"text",placeholder:"https://tulink.com",className:"w-full px-3 py-1.5 text-xs rounded border outline-none",style:{background:"var(--bg-primary)",borderColor:"var(--border-color)",color:"var(--text-primary)"},value:S.url||"",onChange:D=>{let O=[...N];O[M].url=D.target.value,C(O)}})]}),v("button",{onClick:()=>C(N.filter((D,O)=>O!==M)),className:"w-8 h-8 flex items-center justify-center text-red-400 hover:bg-red-500/20 rounded",children:v("i",{className:"fas fa-times"})})]},M))})]})]}),v("div",{className:"pt-4 border-t flex justify-end",style:{borderColor:"var(--border-color)"},children:T("button",{onClick:k,disabled:t||!l||!g,className:`px-6 py-2 rounded-lg font-bold text-sm text-white flex items-center gap-2 ${t?"opacity-50 cursor-not-allowed":"hover:bg-green-600"} bg-green-500 transition-colors`,children:[t?v("i",{className:"fas fa-spinner fa-spin"}):v("i",{className:"fas fa-paper-plane"}),"Enviar a Meta para Aprobaci\xF3n"]})})]}):T("div",{className:"rounded-xl border overflow-hidden",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},children:[T("div",{className:"flex bg-black/20 p-4 border-b text-xs font-bold uppercase tracking-wider",style:{borderColor:"var(--border-color)",color:"var(--text-secondary)"},children:[v("div",{className:"flex-[2]",children:"Nombre"}),v("div",{className:"flex-1",children:"Categor\xEDa"}),v("div",{className:"flex-1",children:"Idioma"}),v("div",{className:"flex-1",children:"Estado"}),v("div",{className:"flex-1 text-right",children:"Acci\xF3n"})]}),t?T("div",{className:"p-8 text-center text-sm",style:{color:"var(--text-secondary)"},children:[v("i",{className:"fas fa-spinner fa-spin mr-2"})," Cargando plantillas desde Meta..."]}):r.length===0?v("div",{className:"p-8 text-center text-sm",style:{color:"var(--text-secondary)"},children:"No hay plantillas creadas en esta WABA (WhatsApp Business Account)."}):v("div",{className:"divide-y",style:{borderColor:"var(--border-color)"},children:r.map(S=>T("div",{className:"flex items-center p-4 hover:bg-white/5 transition-colors text-sm",children:[v("div",{className:"flex-[2] font-mono font-bold",children:S.name}),v("div",{className:"flex-1 text-[11px] font-bold",children:v("span",{className:"px-2 py-1 rounded-md bg-white/5",children:S.category})}),v("div",{className:"flex-1",children:S.language}),T("div",{className:"flex-1 flex items-center gap-2",children:[S.status==="APPROVED"&&v("span",{className:"w-2 h-2 rounded-full bg-green-500"}),S.status==="PENDING"&&v("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),S.status==="REJECTED"&&v("span",{className:"w-2 h-2 rounded-full bg-red-500"}),v("span",{className:"text-xs font-bold",children:S.status})]}),v("div",{className:"flex-1 text-right",children:v("button",{onClick:()=>A(S.name),className:"w-8 h-8 rounded-full hover:bg-red-500/20 text-red-400 transition-colors",title:"Eliminar Plantilla",children:v("i",{className:"fas fa-trash"})})})]},S.id))})]})]})})},H2=[{icon:"fas fa-comment-dots",color:"text-indigo-400",bg:"bg-indigo-500/10",text:"Saluda al cliente cuando se cree un pedido"},{icon:"fas fa-camera",color:"text-amber-400",bg:"bg-amber-500/10",text:"Detecta pagos en fotos de comprobante"},{icon:"fas fa-industry",color:"text-emerald-400",bg:"bg-emerald-500/10",text:"Avisa por WhatsApp al pasar a Producci\xF3n"},{icon:"fas fa-truck",color:"text-cyan-400",bg:"bg-cyan-500/10",text:"Pedido listo: avisa si >$1M"}],W2=()=>{let[r,e]=oe(""),[t,n]=oe(!1),[i,s]=oe(null),[o,a]=oe(null),l=async c=>{let d=c||r;if(d.trim()){n(!0),a(null),s(null);try{let u=await fetch("http://localhost:3001/api/whatsapp/rules/generate",{method:"POST",headers:{"Content-Type":"application/json","x-tenant-id":"dev-tenant"},body:JSON.stringify({prompt:d})});if(!u.ok)throw new Error("Error al generar regla IA");let h=await u.json();s(JSON.stringify(h.rule||h,null,2))}catch(u){a(u.message||"Error de conexi\xF3n con el AI Service")}finally{n(!1)}}};return v("div",{className:"flex-1 h-full flex flex-col items-center justify-center p-8 bg-black/20 overflow-y-auto",children:T("div",{className:"w-full max-w-3xl",children:[T("div",{className:"text-center mb-10 text-white",children:[v("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-2xl bg-indigo-500/20 text-indigo-400 mb-6 border border-indigo-500/30 shadow-[0_0_30px_rgba(99,102,241,0.2)]",children:v("i",{className:"fas fa-wand-magic-sparkles text-2xl"})}),v("h2",{className:"text-3xl font-black tracking-tight mb-3",children:"Workflow Architect"}),v("p",{className:"text-zinc-400 max-w-lg mx-auto leading-relaxed",children:"Escribe una instrucci\xF3n en lenguaje natural y Sentinal AI generar\xE1 la regla JSON requerida para la automatizaci\xF3n de WhatsApp."})]}),v("div",{className:"grid grid-cols-2 gap-3 mb-8",children:H2.map((c,d)=>T("button",{onClick:()=>{e(c.text),l(c.text)},className:"flex items-center gap-3 p-4 text-left rounded-xl transition-all border border-white/5 bg-zinc-900/50 hover:bg-zinc-800/80 hover:border-white/10 group",children:[v("div",{className:`w-8 h-8 shrink-0 flex items-center justify-center rounded-lg ${c.bg} ${c.color}`,children:v("i",{className:c.icon})}),v("span",{className:"text-sm font-medium text-zinc-300 group-hover:text-white leading-tight",children:c.text})]},d))}),T("div",{className:"flex flex-col gap-4",children:[T("div",{className:"relative group",children:[v("div",{className:"absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none",children:v("i",{className:"fas fa-terminal text-zinc-500"})}),v("input",{type:"text",value:r,onChange:c=>e(c.target.value),onKeyDown:c=>c.key==="Enter"&&l(),placeholder:"Ej: Cuando un pedido pase de Producci\xF3n a Dispatch, env\xEDa una plantilla...",className:"block w-full pl-11 pr-32 py-4 bg-zinc-950/80 border-2 border-zinc-800 rounded-xl text-sm outline-none text-zinc-200 placeholder-zinc-600 focus:border-indigo-500/50 focus:bg-zinc-950 transition-all shadow-inner"}),v("button",{onClick:()=>l(),disabled:t||!r.trim(),className:"absolute right-2 top-2 bottom-2 px-6 bg-indigo-600 hover:bg-indigo-500 disabled:bg-zinc-800 disabled:text-zinc-600 text-white font-bold rounded-lg text-sm transition-all shadow-lg active:scale-95 flex items-center gap-2",children:t?v("i",{className:"fas fa-circle-notch fa-spin"}):"Generar"})]}),o&&T("div",{className:"p-4 rounded-xl bg-rose-500/10 border border-rose-500/20 text-rose-400 text-sm flex items-start gap-3 animate-in fade-in slide-in-from-top-2",children:[v("i",{className:"fas fa-exclamation-circle mt-0.5"}),v("div",{children:o})]}),i&&T("div",{className:"rounded-xl overflow-hidden border border-zinc-800 bg-[#0d1117] relative animate-in zoom-in-95 fade-in duration-300 shadow-2xl",children:[T("div",{className:"px-4 py-2 border-b border-zinc-800 bg-[#161b22] flex items-center gap-2",children:[v("i",{className:"fab fa-js text-yellow-400/80 text-xs"}),v("span",{className:"text-xs font-mono text-zinc-400",children:"generated_rule.json"}),v("div",{className:"flex-1"}),v("span",{className:"text-[10px] uppercase font-bold text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded",children:"V\xE1lido"})]}),v("pre",{className:"p-5 text-xs font-mono leading-relaxed text-[#c9d1d9] overflow-x-auto whitespace-pre-wrap max-h-[300px] overflow-y-auto custom-scrollbar",children:i})]})]})]})})},V2=()=>{let[r,e]=oe({activeChats:12,avgResponse:"2.4s",todayMessages:347,botUptime:"99.8%",queuedMessages:3});return yn(()=>{let t=setInterval(()=>{e(n=>({...n,activeChats:n.activeChats+Math.floor(Math.random()*3)-1,todayMessages:n.todayMessages+Math.floor(Math.random()*5),queuedMessages:Math.max(0,n.queuedMessages+Math.floor(Math.random()*3)-1)}))},8e3);return()=>clearInterval(t)},[]),r},j2=Ka.memo(()=>{let r=V2();return T("div",{className:"h-6 shrink-0 flex items-center justify-between px-3 text-[10px] font-medium border-t",style:{background:"var(--brand-primary)",borderColor:"transparent",color:"white"},children:[T("div",{className:"flex items-center gap-4",children:[T("span",{className:"flex items-center gap-1",children:[v("i",{className:"fas fa-comments"})," ",r.activeChats," chats activos"]}),T("span",{className:"flex items-center gap-1",children:[v("i",{className:"fas fa-clock"})," Resp: ",r.avgResponse]}),T("span",{className:"flex items-center gap-1",children:[v("i",{className:"fas fa-paper-plane"})," ",r.todayMessages," hoy"]})]}),T("div",{className:"flex items-center gap-4",children:[T("span",{className:"flex items-center gap-1",children:[v("i",{className:"fas fa-inbox"})," ",r.queuedMessages," en cola"]}),T("span",{className:"flex items-center gap-1",children:[v("i",{className:"fas fa-robot"})," Uptime: ",r.botUptime]}),v("span",{className:"opacity-70",children:"WhatsApp Business API"})]})]})}),U2=[{id:"chat",label:"Live Chat",icon:"fas fa-comments"},{id:"flow",label:"Flow Canvas",icon:"fas fa-project-diagram"},{id:"architect",label:"Workflow Architect",icon:"fas fa-wand-magic-sparkles"},{id:"analytics",label:"Analytics",icon:"fas fa-chart-bar"},{id:"api_tester",label:"API Tester",icon:"fas fa-vial"},{id:"templates",label:"Templates",icon:"fas fa-layer-group"}],_g=({gatewayStatus:r="connected",activeProvider:e="Meta Cloud API"})=>{let[t,n]=oe("chat"),[i,s]=oe(!0),[o,a]=oe(!1),[l,c]=oe(!0),[d,u]=oe(null),[h,f]=oe(!1),[p,m]=oe(""),g=jd(null);yn(()=>{let x=N=>{(N.metaKey||N.ctrlKey)&&N.key==="k"&&(N.preventDefault(),f(C=>!C),m("")),N.key==="Escape"&&f(!1)};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[]),yn(()=>{h&&g.current&&g.current.focus()},[h]);let b=[{id:"chat",label:"Abrir Chat en Vivo",icon:"fas fa-comments",action:()=>n("chat")},{id:"flow",label:"Abrir Flow Canvas",icon:"fas fa-project-diagram",action:()=>n("flow")},{id:"architect",label:"Abrir Workflow Architect (IA)",icon:"fas fa-wand-magic-sparkles",action:()=>n("architect")},{id:"analytics",label:"Abrir Analytics",icon:"fas fa-chart-bar",action:()=>n("analytics")},{id:"explorer",label:i?"Cerrar Explorer":"Abrir Explorer",icon:"fas fa-folder-tree",action:()=>s(x=>!x)},{id:"inspector",label:o?"Cerrar Inspector":"Abrir Inspector",icon:"fas fa-info-circle",action:()=>a(x=>!x)},{id:"agent",label:l?"Ocultar Copiloto":"Mostrar Copiloto",icon:"fas fa-robot",action:()=>c(x=>!x)},{id:"demo",label:"Activar Modo Demo",icon:"fas fa-play-circle",action:()=>{}}].filter(x=>x.label.toLowerCase().includes(p.toLowerCase())),y=x=>{x.action(),f(!1)};return T("div",{className:"h-full w-full flex flex-col overflow-hidden relative font-sans",style:{background:"var(--bg-primary)"},children:[T("div",{className:"h-11 shrink-0 flex items-center justify-between px-3 gap-2 border-b",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},children:[T("div",{className:"flex items-center gap-2",children:[T("div",{className:"flex items-center gap-2 px-2 py-1 rounded-lg",style:{background:"var(--bg-muted)"},children:[v("i",{className:"fab fa-whatsapp text-green-500 text-lg"}),v("span",{className:"font-black text-xs uppercase tracking-widest",style:{color:"var(--text-primary)"},children:"Discovery Studio"})]}),v("div",{className:"h-5 w-px mx-1",style:{background:"var(--border-color)"}}),v("button",{onClick:()=>s(x=>!x),className:`w-7 h-7 rounded-md flex items-center justify-center text-xs transition-all ${i?"text-brand":""}`,style:{background:i?"var(--bg-muted)":"transparent",color:i?"var(--brand-primary)":"var(--text-secondary)"},title:"Toggle Explorer",children:v("i",{className:"fas fa-folder-tree"})}),v("button",{onClick:()=>a(x=>!x),className:"w-7 h-7 rounded-md flex items-center justify-center text-xs transition-all",style:{background:o?"var(--bg-muted)":"transparent",color:o?"var(--text-primary)":"var(--text-secondary)"},title:"Toggle Inspector",children:v("i",{className:"fas fa-columns"})}),v("button",{onClick:()=>c(x=>!x),className:"w-7 h-7 rounded-md flex items-center justify-center text-xs transition-all border border-emerald-500/20",style:{background:l?"rgba(16, 185, 129, 0.1)":"transparent",color:l?"#10b981":"var(--text-secondary)"},title:"Toggle Agent Copilot",children:v("i",{className:"fas fa-robot"})})]}),T("button",{onClick:()=>f(!0),className:"flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs transition-all hover:border-brand-primary",style:{background:"var(--bg-muted)",border:"1px solid var(--border-color)",color:"var(--text-secondary)"},children:[v("i",{className:"fas fa-search text-[10px]"}),v("span",{children:"Buscar comandos..."}),v("kbd",{className:"ml-4 px-1.5 py-0.5 rounded text-[9px] font-mono font-bold",style:{background:"var(--bg-elevated)",border:"1px solid var(--border-color)"},children:"\u2318K"})]}),T("div",{className:"flex items-center gap-2",children:[T("div",{className:"flex items-center gap-1.5 px-2 py-1 rounded-lg text-[10px] font-bold",style:{background:r==="connected"?"rgba(34,197,94,0.1)":"rgba(239,68,68,0.1)",color:r==="connected"?"#22c55e":"#ef4444"},children:[v("span",{className:`w-1.5 h-1.5 rounded-full ${r==="connected"?"bg-green-500 animate-pulse":"bg-red-500"}`}),r==="connected"?`CONNECTED: ${e}`:"DISCONNECTED"]}),v("button",{className:"w-7 h-7 rounded-md flex items-center justify-center text-xs transition-all",style:{color:"var(--text-secondary)"},title:"Settings",children:v("i",{className:"fas fa-cog"})})]})]}),T("div",{className:"h-9 shrink-0 flex items-end px-1 gap-px border-b",style:{background:"var(--bg-muted)",borderColor:"var(--border-color)"},children:[U2.map(x=>T("button",{onClick:()=>n(x.id),className:`flex items-center gap-2 px-4 py-1.5 text-xs font-semibold rounded-t-lg transition-all relative ${t===x.id?"font-bold":"opacity-60 hover:opacity-80"}`,style:{background:t===x.id?"var(--bg-primary)":"transparent",color:t===x.id?"var(--text-primary)":"var(--text-secondary)",borderBottom:t===x.id?"2px solid var(--brand-primary)":"2px solid transparent"},children:[v("i",{className:`${x.icon} text-[10px]`}),x.label]},x.id)),v("div",{className:"flex-1"}),v("div",{className:"flex items-center gap-1 px-2 pb-1",children:v("button",{className:"w-6 h-6 rounded flex items-center justify-center text-[10px] transition-all hover:bg-white/10",style:{color:"var(--text-secondary)"},title:"Split view",children:v("i",{className:"fas fa-columns"})})})]}),T("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[i&&v("div",{className:"w-60 shrink-0 flex flex-col border-r overflow-hidden animate-fade-in",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},children:v(C2,{selectedContact:d,onSelectContact:u})}),T("div",{className:"flex-1 min-w-0 flex flex-col overflow-hidden",children:[t==="chat"&&v(T2,{selectedContact:d}),t==="flow"&&v(I2,{}),t==="architect"&&v(W2,{}),t==="analytics"&&v(_2,{}),t==="api_tester"&&v(z2,{}),t==="templates"&&v($2,{})]}),o&&v("div",{className:"w-72 shrink-0 flex flex-col border-l overflow-hidden animate-fade-in",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},children:v(E2,{selectedContact:d})}),l&&v("div",{className:"w-80 shrink-0 flex flex-col border-l overflow-hidden animate-fade-in relative shadow-[-10px_0_30px_rgba(0,0,0,0.1)]",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},children:v(A2,{})})]}),v(j2,{}),h&&T("div",{className:"absolute inset-0 z-50 flex items-start justify-center pt-[15%]",onClick:()=>f(!1),children:[v("div",{className:"absolute inset-0 bg-black/40 backdrop-blur-sm"}),T("div",{className:"relative w-[520px] max-h-[400px] rounded-xl overflow-hidden shadow-2xl border animate-scale-up",style:{background:"var(--bg-elevated)",borderColor:"var(--border-color)"},onClick:x=>x.stopPropagation(),children:[T("div",{className:"flex items-center gap-3 px-4 py-3 border-b",style:{borderColor:"var(--border-color)"},children:[v("i",{className:"fas fa-search text-xs",style:{color:"var(--text-secondary)"}}),v("input",{ref:g,type:"text",placeholder:"Escribe un comando...",className:"flex-1 bg-transparent outline-none text-sm font-medium",style:{color:"var(--text-primary)"},value:p,onChange:x=>m(x.target.value)}),v("kbd",{className:"px-1.5 py-0.5 rounded text-[9px] font-mono",style:{background:"var(--bg-muted)",color:"var(--text-secondary)"},children:"ESC"})]}),T("div",{className:"max-h-[320px] overflow-y-auto p-1",children:[b.map((x,N)=>T("button",{onClick:()=>y(x),className:"w-full flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm transition-all text-left",style:{color:"var(--text-primary)"},onMouseEnter:C=>C.currentTarget.style.background="var(--bg-muted)",onMouseLeave:C=>C.currentTarget.style.background="transparent",children:[v("i",{className:`${x.icon} w-5 text-center text-xs`,style:{color:"var(--brand-primary)"}}),v("span",{className:"font-medium",children:x.label})]},x.id)),b.length===0&&T("div",{className:"py-8 text-center text-xs",style:{color:"var(--text-secondary)"},children:[v("i",{className:"fas fa-search-minus text-lg mb-2 block opacity-30"}),"No se encontraron comandos"]})]})]})]})]})};import{jsx as Ud}from"react/jsx-runtime";var K2=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",$g=()=>{let[r,e]=zg("disconnected"),[t,n]=zg("Meta Cloud API");return G2(()=>{let i=q2(K2,{reconnectionDelay:2e3,reconnectionAttempts:1/0});return i.on("connect",()=>{console.log("[Discovery Admin] Conectado al backend de monitoreo:",i.id),e("connected")}),i.on("disconnect",()=>{console.warn("[Discovery Admin] Desconectado del backend"),e("disconnected")}),i.on("wa:status_update",s=>{console.log("[Discovery Admin] Estado del WA Gateway actualizado:",s),s?.status}),()=>{i.disconnect()}},[]),Ud("div",{className:"w-full h-full flex flex-col transition-colors",style:{"--bg-primary":"var(--ds-surface-primary, #ffffff)","--bg-elevated":"var(--ds-surface-secondary, #f8fafc)","--bg-muted":"var(--ds-surface-tertiary, #f1f5f9)","--border-color":"var(--ds-border-default, #e2e8f0)","--text-primary":"var(--ds-text-primary, #0f172a)","--text-secondary":"var(--ds-text-secondary, #64748b)","--brand-primary":"var(--ds-accent-blue, #3b82f6)"},children:Ud("div",{className:"flex-1 w-full h-full min-h-0 relative",children:Ud(_g,{gatewayStatus:r,activeProvider:t})})})};import{useState as Dt,useEffect as Hg,useMemo as Y2}from"react";import{motion as Ya,AnimatePresence as J2}from"framer-motion";import{Database as X2,TableProperties as Z2,RefreshCw as Wg,Plus as Q2,Edit2 as eE,Trash2 as tE,X as rE,Check as nE,Search as iE,ServerCrash as sE,DatabaseZap as oE,LayoutGrid as aE,ChevronRight as lE,Loader2 as Ja,ArrowUpDown as cE,Server as dE}from"lucide-react";import{jsx as F,jsxs as ue}from"react/jsx-runtime";var ms=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",Vg=()=>{let[r]=Dt([{id:"postgres",name:"PostgreSQL Core"},{id:"google_sheets",name:"Google Sheets MCP"}]),[e,t]=Dt("postgres"),[n,i]=Dt([]),[s,o]=Dt(null),[a,l]=Dt(!0),[c,d]=Dt(!1),[u,h]=Dt([]),[f,p]=Dt(""),[m,g]=Dt(null),[b,y]=Dt(null),[x,N]=Dt("data"),[C,w]=Dt([]),[k,A]=Dt(!1),[S,M]=Dt(!1),[D,O]=Dt(null),[H,E]=Dt(!1),[$,G]=Dt(!1),W=async()=>{l(!0),y(null);try{let B=await fetch(`${ms}/api/dataway/resources?connectorId=${e}`,{headers:{"x-api-key":"dev_ak_chameleon_studio_99x"}});if(!B.ok)throw new Error("API Endpoint /api/dataway/resources no disponible");let re=await B.json(),X=Array.isArray(re.resources)?re.resources:[];i(X),X.length>0?o(X[0]):o(null)}catch(B){console.error("[DB Admin] Failed to load schema:",B),y(B.message)}finally{l(!1)}};Hg(()=>{W()},[e]);let he=async(B,re=!1)=>{re||d(!0),p(""),g(null);try{let X=await fetch(`${ms}/api/dataway/query`,{method:"POST",headers:{"x-api-key":"dev_ak_chameleon_studio_99x","Content-Type":"application/json"},body:JSON.stringify({connectorId:e,resource:B,type:e==="postgres"?"table":"range"})});if(!X.ok)throw new Error(`El backend Dataway rechaz\xF3 la lectura de la tabla ${B}`);let me=await X.json();h(Array.isArray(me.data)?me.data:[])}catch(X){Te.error(`Acceso Denegado a ${B}`,{description:X.message}),h([])}finally{d(!1)}},_=async B=>{A(!0);try{let re=await fetch(`${ms}/api/dataway/schema?connectorId=${e}&resource=${B}`,{headers:{"x-api-key":"dev_ak_chameleon_studio_99x"}});if(!re.ok)throw new Error(`El Dataway backend rechaz\xF3 el esquema de ${B}`);let X=await re.json();w(X.schema||[])}catch(re){Te.error("Error de Esquema Dataway",{description:re.message}),w([])}finally{A(!1)}};Hg(()=>{s&&(he(s),_(s),N("data"))},[s]);let ie=B=>{let re="asc";m&&m.key===B&&m.direction==="asc"&&(re="desc"),g({key:B,direction:re})},Se=Y2(()=>{let B=[...u];if(f){let re=f.toLowerCase();B=B.filter(X=>Object.keys(X).some(me=>String(X[me]).toLowerCase().includes(re)))}return m!==null&&B.sort((re,X)=>{let me=re[m.key],Ae=X[m.key];return me<Ae?m.direction==="asc"?-1:1:me>Ae?m.direction==="asc"?1:-1:0}),B},[u,f,m]),J=u.length>0?Object.keys(u[0]):[],ae=async B=>{if(!s)return;G(!0);let re=H,X=re?"POST":"PUT",me=re?`${ms}/api/db/${s}`:`${ms}/api/db/${s}/${B.id}`;try{let Ae={...B};re&&delete Ae.id;let bt=await fetch(me,{method:X,headers:{"Content-Type":"application/json","x-api-key":"dev_ak_chameleon_studio_99x"},body:JSON.stringify(Ae)});if(!bt.ok){let xt=await bt.json().catch(()=>({}));throw new Error(xt.message||xt.error||"Error desconocido al guardar en base de datos")}Te.success(`Registro ${re?"creado":"actualizado"} en la tabla ${s}`),M(!1),he(s,!0)}catch(Ae){Te.error("Error de Integridad",{description:Ae.message})}finally{G(!1)}},fe=async B=>{if(s&&confirm("\xBFAtenci\xF3n: Esta acci\xF3n es destructiva y permanente. \xBFConfirmar eliminaci\xF3n?"))try{if(!(await fetch(`${ms}/api/db/${s}/${B}`,{method:"DELETE",headers:{"x-api-key":"dev_ak_chameleon_studio_99x"}})).ok)throw new Error("No se pudo eliminar el registro (violaci\xF3n de Foreign Key o ruta no implementada)");Te.success("Registro eliminado exitosamente"),h(X=>X.filter(me=>me.id!==B))}catch(re){Te.error("Fallo al Eliminar",{description:re.message})}},Oe=B=>{O({...B}),E(!1),M(!0)},_e=()=>{let B={};J.length>0&&J.forEach(re=>{re!=="id"&&re!=="created_at"&&re!=="updated_at"&&(B[re]="")}),O(B),E(!0),M(!0)},ke=B=>typeof B=="boolean"?"checkbox":typeof B=="number"?"number":"text";return ue("div",{className:"w-full h-full flex flex-row overflow-hidden",style:{"--bg-primary":"var(--ds-surface-primary, #ffffff)","--bg-elevated":"var(--ds-surface-secondary, #f8fafc)","--bg-surface":"var(--ds-surface-tertiary, #f1f5f9)","--border-color":"var(--ds-border-default, #e2e8f0)","--text-primary":"var(--ds-text-primary, #0f172a)","--text-secondary":"var(--ds-text-secondary, #64748b)","--brand-primary":"var(--ds-accent-blue, #3b82f6)","--brand-primary-hover":"var(--ds-accent-blue-hover, #2563eb)"},children:[ue("div",{className:"w-72 border-r border-[var(--border-color)] bg-[var(--bg-elevated)] flex flex-col h-full z-10 shadow-[2px_0_10px_rgba(0,0,0,0.02)]",children:[ue("div",{className:"p-6 border-b border-[var(--border-color)] flex flex-col gap-4 bg-[var(--bg-primary)]",children:[ue("div",{className:"flex items-center gap-3",children:[F("div",{className:"p-2 bg-[var(--brand-primary)]/10 rounded-xl",children:F(oE,{className:"w-6 h-6 text-[var(--brand-primary)]"})}),ue("div",{children:[F("h2",{className:"font-extrabold text-[var(--text-primary)] tracking-tight text-lg leading-none",children:"Data Studio"}),F("p",{className:"text-[11px] font-medium text-[var(--text-secondary)] uppercase tracking-wider mt-1",children:"Dataway Core"})]})]}),F("select",{value:e,onChange:B=>t(B.target.value),className:"w-full bg-[var(--bg-surface)] border border-[var(--border-color)] text-[var(--text-primary)] text-sm font-bold rounded-lg px-3 py-2 outline-none cursor-pointer hover:border-[var(--brand-primary)]/50 focus:border-[var(--brand-primary)] focus:ring-2 focus:ring-[var(--brand-primary)]/20 transition-all shadow-sm",children:r.map(B=>F("option",{value:B.id,children:B.name},B.id))})]}),ue("div",{className:"p-4 flex-1 overflow-y-auto w-full space-y-1.5 custom-scrollbar",children:[ue("h3",{className:"text-xs font-bold text-[var(--text-secondary)] tracking-wider uppercase mb-3 px-2 flex items-center justify-between",children:["Esquema P\xFAbico",F("button",{onClick:W,className:"hover:text-[var(--text-primary)] transition-colors p-1 rounded-md hover:bg-[var(--bg-surface)]",children:F(Wg,{className:"w-3 h-3"})})]}),a?F("div",{className:"space-y-2 px-2",children:[1,2,3,4].map(B=>F("div",{className:"h-10 bg-[var(--bg-surface)] rounded-lg animate-pulse w-full"},B))}):b?ue("div",{className:"p-4 mx-2 bg-red-50 text-red-600 rounded-xl border border-red-100 flex flex-col items-center text-center gap-2",children:[F(sE,{className:"w-6 h-6"}),F("p",{className:"text-sm font-semibold",children:"Backend Offline"}),F("p",{className:"text-xs opacity-80",children:b})]}):n.length===0?F("div",{className:"p-4 text-center text-[var(--text-secondary)] text-sm",children:"No se descubrieron tablas v\xEDa /api/db/tables."}):n.map(B=>ue("button",{onClick:()=>o(B),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-sm font-semibold transition-all duration-200 group ${s===B?"bg-gradient-to-r from-[var(--brand-primary)] to-[var(--brand-primary-hover)] text-white shadow-md shadow-blue-500/20":"text-[var(--text-secondary)] hover:bg-[var(--bg-surface)] hover:text-[var(--text-primary)]"}`,children:[ue("div",{className:"flex items-center gap-3",children:[F(Z2,{className:`w-4 h-4 ${s===B?"text-blue-100":"text-slate-400 group-hover:text-slate-600"}`}),F("span",{className:"capitalize",children:B})]}),s===B&&F(lE,{className:"w-4 h-4 opacity-70"})]},B))]})]}),ue("div",{className:"flex-1 bg-[var(--bg-surface)] flex flex-col h-full min-w-0 relative",children:[ue("header",{className:"px-8 py-6 bg-[var(--bg-primary)] border-b border-[var(--border-color)] flex items-center justify-between sticky top-0 z-20 shadow-sm",children:[ue("div",{className:"flex flex-col",children:[ue("div",{className:"flex items-center gap-2 text-[var(--text-secondary)] text-xs font-bold uppercase tracking-wider mb-1",children:[F(dE,{className:"w-3.5 h-3.5"}),ue("span",{children:[r.find(B=>B.id===e)?.name," / ",s||"..."]})]}),ue("h1",{className:"text-3xl font-extrabold text-[var(--text-primary)] capitalize tracking-tight flex items-center gap-3",children:[s||"Selecciona un Recurso",c&&F(Ja,{className:"w-5 h-5 animate-spin text-[var(--brand-primary)]"})]})]}),s&&ue("div",{className:"flex gap-4 items-center",children:[ue("div",{className:"flex bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded-lg p-1 shadow-sm h-[42px] items-center mr-2",children:[F("button",{onClick:()=>N("data"),className:`px-4 py-1.5 text-xs font-bold rounded-md transition-all duration-200 ${x==="data"?"bg-[var(--bg-primary)] text-[var(--text-primary)] shadow-sm border border-[var(--border-color)]":"text-[var(--text-secondary)] hover:text-[var(--text-primary)] border border-transparent"}`,children:"Registros"}),F("button",{onClick:()=>N("schema"),className:`px-4 py-1.5 text-xs font-bold rounded-md transition-all duration-200 ${x==="schema"?"bg-[var(--bg-primary)] text-[var(--brand-primary)] shadow-sm border border-[var(--brand-primary)]/30":"text-[var(--text-secondary)] hover:text-[var(--text-primary)] border border-transparent"}`,children:"Estructura"})]}),ue("div",{className:"relative group",children:[F(iE,{className:"w-4 h-4 text-[var(--text-secondary)] absolute left-3.5 top-1/2 -translate-y-1/2 group-focus-within:text-[var(--brand-primary)] transition-colors"}),F("input",{type:"text",placeholder:`Buscar en ${s}...`,value:f,onChange:B=>p(B.target.value),className:"pl-10 pr-4 py-2.5 rounded-xl border border-[var(--border-color)] bg-[var(--bg-elevated)] text-[var(--text-primary)] text-sm font-medium outline-none focus:ring-2 focus:ring-[var(--brand-primary)]/20 focus:border-[var(--brand-primary)] transition-all w-72 shadow-inner"})]}),F("div",{className:"h-8 w-px bg-[var(--border-color)] mx-2"}),F("button",{onClick:()=>he(s),disabled:c,className:"p-2.5 text-[var(--text-secondary)] hover:bg-[var(--bg-surface)] hover:text-[var(--text-primary)] rounded-xl transition-all disabled:opacity-50 border border-transparent hover:border-[var(--border-color)]",title:"Recargar Data",children:F(Wg,{className:`w-[18px] h-[18px] ${c?"animate-spin":""}`})}),ue("button",{onClick:_e,disabled:n.length===0,className:"flex items-center gap-2 bg-[var(--brand-primary)] hover:bg-[var(--brand-primary-hover)] text-white px-5 py-2.5 rounded-xl font-bold text-sm shadow-lg shadow-[var(--brand-primary)]/25 transition-all active:scale-95 disabled:opacity-50 disabled:grayscale",children:[F(Q2,{className:"w-[18px] h-[18px]"}),"Insertar Fila"]})]})]}),F("div",{className:"flex-1 overflow-hidden p-6 relative flex flex-col",children:s?ue("div",{className:"flex-1 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-2xl shadow-sm overflow-hidden flex flex-col relative",children:[F("div",{className:"overflow-auto flex-1 custom-scrollbar",children:x==="schema"?ue("table",{className:"w-full text-left text-sm whitespace-nowrap",children:[F("thead",{className:"bg-[var(--bg-elevated)] sticky top-0 z-10 shadow-[0_1px_2px_rgba(0,0,0,0.05)]",children:ue("tr",{children:[F("th",{className:"px-6 py-4 text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider",children:"Columna"}),F("th",{className:"px-6 py-4 text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider",children:"Tipo de Dato"}),F("th",{className:"px-6 py-4 text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider",children:"Nulabilidad"}),F("th",{className:"px-6 py-4 text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider",children:"Valor por Defecto"})]})}),F("tbody",{className:"divide-y divide-[var(--border-color)] text-[var(--text-primary)] font-medium",children:k?F("tr",{children:F("td",{colSpan:4,className:"h-48 text-center text-[var(--text-secondary)]",children:ue("div",{className:"flex flex-col items-center gap-3",children:[F(Ja,{className:"w-8 h-8 animate-spin text-[var(--brand-primary)]"}),F("span",{children:"Cargando esquema estructural..."})]})})}):C.map(B=>ue(Ya.tr,{initial:{opacity:0},animate:{opacity:1},className:"hover:bg-[var(--bg-surface)]/70 transition-colors",children:[F("td",{className:"px-6 py-3",children:F("span",{className:"font-bold text-[var(--text-primary)]",children:B.name})}),F("td",{className:"px-6 py-3",children:F("span",{className:"font-mono text-[11px] text-blue-600 bg-blue-50 px-2 py-1 rounded-md",children:B.type})}),F("td",{className:"px-6 py-3",children:B.is_nullable==="YES"?F("span",{className:"opacity-60 text-[11px] font-bold uppercase",children:"Nullable"}):F("span",{className:"text-red-600 bg-red-50 px-2 py-0.5 rounded text-[10px] font-bold uppercase",children:"Not Null"})}),F("td",{className:"px-6 py-3",children:B.default_value?F("span",{className:"font-mono text-[11px] text-purple-600 bg-purple-50 px-2 py-1 rounded-md",children:B.default_value}):F("span",{className:"text-gray-400 italic",children:"None"})})]},B.name))})]}):ue("table",{className:"w-full text-left text-sm whitespace-nowrap",children:[F("thead",{className:"bg-[var(--bg-elevated)] sticky top-0 z-10 shadow-[0_1px_2px_rgba(0,0,0,0.05)]",children:ue("tr",{children:[J.map(B=>F("th",{onClick:()=>ie(B),className:"px-6 py-4 cursor-pointer hover:bg-[var(--bg-surface)] transition-colors group select-none",children:ue("div",{className:"flex items-center gap-2 text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider",children:[B,F(cE,{className:`w-3.5 h-3.5 ${m?.key===B?"text-[var(--brand-primary)]":"opacity-0 group-hover:opacity-50 transition-opacity"}`})]})},B)),F("th",{className:"px-6 py-4 w-24 sticky right-0 bg-[var(--bg-elevated)] backdrop-blur-md shadow-[-4px_0_10px_rgba(0,0,0,0.02)]",children:F("span",{className:"sr-only",children:"Actions"})})]})}),F("tbody",{className:"divide-y divide-[var(--border-color)] text-[var(--text-primary)] font-medium",children:Se.length===0?F("tr",{children:F("td",{colSpan:J.length+1,className:"h-48 text-center text-[var(--text-secondary)]",children:c?ue("div",{className:"flex flex-col items-center gap-3",children:[F(Ja,{className:"w-8 h-8 animate-spin text-[var(--brand-primary)]"}),ue("span",{children:["Consultando ",s,"..."]})]}):ue("div",{className:"flex flex-col items-center gap-3 opacity-60",children:[F(X2,{className:"w-10 h-10"}),F("span",{children:"La consulta retorn\xF3 0 filas."})]})})}):Se.map((B,re)=>ue(Ya.tr,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.2,delay:Math.min(re*.02,.5)},className:"hover:bg-[var(--bg-surface)]/70 transition-colors group",children:[J.map(X=>{let me=B[X];return F("td",{className:"px-6 py-3 max-w-[250px] truncate text-ellipsis",children:typeof me=="boolean"?F("span",{className:`px-2 py-1 rounded-md text-[10px] font-bold uppercase tracking-wider ${me?"bg-green-100 text-green-700":"bg-red-100 text-red-700"}`,children:me?"TRUE":"FALSE"}):typeof me=="object"&&me!==null?F("span",{className:"font-mono text-[11px] text-emerald-600 bg-emerald-50 px-2 py-1 rounded-md",children:JSON.stringify(me)}):F("span",{title:String(me),children:me!=null?String(me):F("span",{className:"text-gray-400 italic",children:"null"})})},X)}),F("td",{className:"px-6 py-3 text-right sticky right-0 bg-[var(--bg-primary)] group-hover:bg-[#f8fafc] transition-colors shadow-[-4px_0_10px_rgba(0,0,0,0.02)] border-l border-transparent group-hover:border-[var(--border-color)]",children:ue("div",{className:"flex items-center justify-end gap-1 opacity-10 md:opacity-0 group-hover:opacity-100 transition-opacity",children:[F("button",{onClick:()=>Oe(B),className:"p-1.5 hover:bg-blue-100 text-blue-600 rounded-md transition-colors tooltip-trigger",title:"Editar Registro",children:F(eE,{className:"w-4 h-4"})}),F("button",{onClick:()=>fe(B.id),className:"p-1.5 hover:bg-red-100 text-red-600 rounded-md transition-colors tooltip-trigger",title:"Eliminar Permanente",children:F(tE,{className:"w-4 h-4"})})]})})]},B.id||re))})]})}),ue("div",{className:"px-6 py-3 border-t border-[var(--border-color)] bg-[var(--bg-elevated)] text-xs font-semibold text-[var(--text-secondary)] flex justify-between items-center z-10",children:[ue("span",{children:["Total Records: ",Se.length]}),F("span",{className:"uppercase tracking-wider",children:"Macia Platform v2.0 - Core Gateway"})]})]}):ue("div",{className:"m-auto flex flex-col items-center justify-center opacity-40",children:[F(aE,{className:"w-16 h-16 mb-4"}),F("h2",{className:"text-xl font-bold",children:"Sin Datos Activos"}),F("p",{className:"text-sm",children:"Selecciona una tabla en el panel lateral."})]})})]}),F(J2,{children:S&&F(Ya.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},className:"fixed inset-0 z-50 flex items-center justify-center p-4 bg-[var(--text-primary)]/40 backdrop-blur-md",children:ue(Ya.div,{initial:{scale:.95,opacity:0,y:20},animate:{scale:1,opacity:1,y:0},exit:{scale:.95,opacity:0,y:-20},transition:{type:"spring",bounce:0,duration:.3},className:"bg-[var(--bg-primary)] border border-white/20 rounded-3xl shadow-[0_20px_60px_-10px_rgba(0,0,0,0.3)] w-full max-w-2xl overflow-hidden flex flex-col relative",children:[F("div",{className:"absolute top-0 left-0 w-full h-32 bg-gradient-to-br from-blue-500/10 to-purple-500/5 pointer-events-none"}),ue("div",{className:"px-8 py-5 border-b border-[var(--border-color)] flex justify-between items-center relative z-10 bg-[var(--bg-primary)]/80 backdrop-blur-lg",children:[ue("div",{children:[F("h3",{className:"font-extrabold text-xl text-[var(--text-primary)] tracking-tight",children:H?"Insertar Documento":"Modificar Documento"}),ue("p",{className:"text-xs text-[var(--text-secondary)] font-medium mt-0.5",children:["Tabla destino: ",F("span",{className:"uppercase tracking-wider bg-[var(--bg-surface)] px-1.5 py-0.5 rounded text-[var(--brand-primary)]",children:s})]})]}),F("button",{onClick:()=>M(!1),className:"p-2 bg-[var(--bg-surface)] text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--border-color)] rounded-xl transition-all",children:F(rE,{className:"w-5 h-5"})})]}),F("div",{className:"p-8 space-y-5 max-h-[65vh] overflow-y-auto custom-scrollbar relative z-10",children:D&&Object.keys(D).map(B=>{let re=!H&&B==="id"||B==="created_at"||B==="updated_at",X=D[B],me=ke(X);return ue("div",{className:"flex flex-col gap-1.5",children:[ue("label",{className:"text-[11px] font-bold text-[var(--text-secondary)] uppercase tracking-wider pl-1 flex justify-between",children:[B,re&&F("span",{className:"opacity-50 font-mono lowercase",children:"auto-generated"})]}),re?F("input",{disabled:!0,value:X||"Depende del Motor DB",className:"w-full px-4 py-3 rounded-xl border border-[var(--border-color)] bg-[var(--bg-surface)] text-[var(--text-secondary)] font-mono text-xs cursor-not-allowed opacity-70"}):typeof X=="boolean"?ue("select",{value:String(X),onChange:Ae=>O({...D,[B]:Ae.target.value==="true"}),className:"w-full px-4 py-3 rounded-xl border border-[var(--border-color)] bg-[var(--bg-primary)] text-[var(--text-primary)] focus:ring-2 focus:ring-[var(--brand-primary)]/20 focus:border-[var(--brand-primary)] text-sm font-medium outline-none transition-all cursor-pointer shadow-sm",children:[F("option",{value:"true",children:"Verdadero (TRUE)"}),F("option",{value:"false",children:"Falso (FALSE)"})]}):typeof X=="object"&&X!==null?F("textarea",{rows:4,value:JSON.stringify(X,null,2),onChange:Ae=>{try{let bt=JSON.parse(Ae.target.value);O({...D,[B]:bt})}catch{O({...D,[B]:Ae.target.value})}},className:"w-full px-4 py-3 rounded-xl border border-[var(--border-color)] bg-[var(--bg-primary)] font-mono text-xs focus:ring-2 focus:ring-[var(--brand-primary)]/20 focus:border-[var(--brand-primary)] outline-none transition-all shadow-sm"}):F("input",{type:me,value:X!==null?X:"",onChange:Ae=>O({...D,[B]:me==="number"?Number(Ae.target.value):Ae.target.value}),className:"w-full px-4 py-3 rounded-xl border border-[var(--border-color)] bg-[var(--bg-primary)] text-[var(--text-primary)] focus:ring-2 focus:ring-[var(--brand-primary)]/20 focus:border-[var(--brand-primary)] text-sm font-medium outline-none transition-all shadow-sm",placeholder:`Ingresar ${B}...`})]},B)})}),ue("div",{className:"px-8 py-5 border-t border-[var(--border-color)] bg-[var(--bg-surface)] flex justify-end gap-3 rounded-b-3xl relative z-10",children:[F("button",{onClick:()=>M(!1),className:"px-5 py-2.5 rounded-xl text-sm font-bold text-[var(--text-secondary)] hover:text-[var(--text-primary)] hover:bg-[var(--border-color)] transition-all",children:"Descartar"}),ue("button",{onClick:()=>ae(D),disabled:$,className:"flex items-center gap-2 px-6 py-2.5 rounded-xl text-sm font-extrabold text-white bg-gradient-to-r from-[var(--brand-primary)] to-[var(--brand-primary-hover)] shadow-lg shadow-[var(--brand-primary)]/30 transition-all active:scale-95 disabled:opacity-70",children:[$?F(Ja,{className:"w-[18px] h-[18px] animate-spin"}):F(nE,{className:"w-[18px] h-[18px]"}),$?"Sincronizando...":"Confirmar Cambios"]})]})]})})}),F("style",{children:`
51
+ .custom-scrollbar::-webkit-scrollbar {
52
+ width: 6px;
53
+ height: 6px;
54
+ }
55
+ .custom-scrollbar::-webkit-scrollbar-track {
56
+ background: transparent;
57
+ }
58
+ .custom-scrollbar::-webkit-scrollbar-thumb {
59
+ background: var(--border-color);
60
+ border-radius: 10px;
61
+ }
62
+ .custom-scrollbar::-webkit-scrollbar-thumb:hover {
63
+ background: var(--text-secondary);
64
+ }
65
+ `})]})};import{useState as qe,useEffect as Gf,useMemo as uw,useRef as hR}from"react";import{motion as hw,AnimatePresence as fw}from"framer-motion";import*as ei from"react";import{flushSync as mE}from"react-dom";function Ai(r,e,t){let n=t.initialDeps??[],i,s=!0;function o(){var a,l,c;let d;t.key&&((a=t.debug)!=null&&a.call(t))&&(d=Date.now());let u=r();if(!(u.length!==n.length||u.some((p,m)=>n[m]!==p)))return i;n=u;let f;if(t.key&&((l=t.debug)!=null&&l.call(t))&&(f=Date.now()),i=e(...u),t.key&&((c=t.debug)!=null&&c.call(t))){let p=Math.round((Date.now()-d)*100)/100,m=Math.round((Date.now()-f)*100)/100,g=m/16,b=(y,x)=>{for(y=String(y);y.length<x;)y=" "+y;return y};console.info(`%c\u23F1 ${b(m,5)} /${b(p,5)} ms`,`
66
+ font-size: .6rem;
67
+ font-weight: bold;
68
+ color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,t?.key)}return t?.onChange&&!(s&&t.skipInitialOnChange)&&t.onChange(i),s=!1,i}return o.updateDeps=a=>{n=a},o}function Gd(r,e){if(r===void 0)throw new Error(`Unexpected undefined${e?`: ${e}`:""}`);return r}var jg=(r,e)=>Math.abs(r-e)<1.01,Ug=(r,e,t)=>{let n;return function(...i){r.clearTimeout(n),n=r.setTimeout(()=>e.apply(this,i),t)}};var Gg=r=>{let{offsetWidth:e,offsetHeight:t}=r;return{width:e,height:t}},uE=r=>r,hE=r=>{let e=Math.max(r.startIndex-r.overscan,0),t=Math.min(r.endIndex+r.overscan,r.count-1),n=[];for(let i=e;i<=t;i++)n.push(i);return n},Yg=(r,e)=>{let t=r.scrollElement;if(!t)return;let n=r.targetWindow;if(!n)return;let i=o=>{let{width:a,height:l}=o;e({width:Math.round(a),height:Math.round(l)})};if(i(Gg(t)),!n.ResizeObserver)return()=>{};let s=new n.ResizeObserver(o=>{let a=()=>{let l=o[0];if(l?.borderBoxSize){let c=l.borderBoxSize[0];if(c){i({width:c.inlineSize,height:c.blockSize});return}}i(Gg(t))};r.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()});return s.observe(t,{box:"border-box"}),()=>{s.unobserve(t)}},qg={passive:!0};var Kg=typeof window>"u"?!0:"onscrollend"in window,Jg=(r,e)=>{let t=r.scrollElement;if(!t)return;let n=r.targetWindow;if(!n)return;let i=0,s=r.options.useScrollendEvent&&Kg?()=>{}:Ug(n,()=>{e(i,!1)},r.options.isScrollingResetDelay),o=d=>()=>{let{horizontal:u,isRtl:h}=r.options;i=u?t.scrollLeft*(h&&-1||1):t.scrollTop,s(),e(i,d)},a=o(!0),l=o(!1);t.addEventListener("scroll",a,qg);let c=r.options.useScrollendEvent&&Kg;return c&&t.addEventListener("scrollend",l,qg),()=>{t.removeEventListener("scroll",a),c&&t.removeEventListener("scrollend",l)}};var fE=(r,e,t)=>{if(e?.borderBoxSize){let n=e.borderBoxSize[0];if(n)return Math.round(n[t.options.horizontal?"inlineSize":"blockSize"])}return r[t.options.horizontal?"offsetWidth":"offsetHeight"]};var Xg=(r,{adjustments:e=0,behavior:t},n)=>{var i,s;let o=r+e;(s=(i=n.scrollElement)==null?void 0:i.scrollTo)==null||s.call(i,{[n.options.horizontal?"left":"top"]:o,behavior:t})},Xa=class{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,n,i;return((i=(n=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:n.now)==null?void 0:i.call(n))??Date.now()},this.observer=(()=>{let t=null,n=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(i=>{i.forEach(s=>{let o=()=>{let a=s.target,l=this.indexFromElement(a);if(!a.isConnected){this.observer.unobserve(a);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(a,s,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()})}));return{disconnect:()=>{var i;(i=n())==null||i.disconnect(),t=null},observe:i=>{var s;return(s=n())==null?void 0:s.observe(i,{box:"border-box"})},unobserve:i=>{var s;return(s=n())==null?void 0:s.unobserve(i)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([n,i])=>{typeof i>"u"&&delete t[n]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:uE,rangeExtractor:hE,onChange:()=>{},measureElement:fE,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,...t}},this.notify=t=>{var n,i;(i=(n=this.options).onChange)==null||i.call(n,this,t)},this.maybeNotify=Ai(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:process.env.NODE_ENV!=="production"&&"maybeNotify",debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;let n=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==n){if(this.cleanup(),!n){this.maybeNotify();return}this.scrollElement=n,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(i=>{this.observer.observe(i)}),this.unsubs.push(this.options.observeElementRect(this,i=>{this.scrollRect=i,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(i,s)=>{this.scrollAdjustments=0,this.scrollDirection=s?this.getScrollOffset()<i?"forward":"backward":null,this.scrollOffset=i,this.isScrolling=s,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,n)=>{let i=new Map,s=new Map;for(let o=n-1;o>=0;o--){let a=t[o];if(i.has(a.lane))continue;let l=s.get(a.lane);if(l==null||a.end>l.end?s.set(a.lane,a):a.end<l.end&&i.set(a.lane,!0),i.size===this.options.lanes)break}return s.size===this.options.lanes?Array.from(s.values()).sort((o,a)=>o.end===a.end?o.index-a.index:o.end-a.end)[0]:void 0},this.getMeasurementOptions=Ai(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes],(t,n,i,s,o,a)=>(this.prevLanes!==void 0&&this.prevLanes!==a&&(this.lanesChangedFlag=!0),this.prevLanes=a,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:n,scrollMargin:i,getItemKey:s,enabled:o,lanes:a}),{key:!1}),this.getMeasurements=Ai(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:n,scrollMargin:i,getItemKey:s,enabled:o,lanes:a},l)=>{if(!o)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(let h of this.laneAssignments.keys())h>=t&&this.laneAssignments.delete(h);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(h=>{this.itemSizeCache.set(h.key,h.size)}));let c=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===t&&(this.lanesSettling=!1);let d=this.measurementsCache.slice(0,c),u=new Array(a).fill(void 0);for(let h=0;h<c;h++){let f=d[h];f&&(u[f.lane]=h)}for(let h=c;h<t;h++){let f=s(h),p=this.laneAssignments.get(h),m,g;if(p!==void 0&&this.options.lanes>1){m=p;let N=u[m],C=N!==void 0?d[N]:void 0;g=C?C.end+this.options.gap:n+i}else{let N=this.options.lanes===1?d[h-1]:this.getFurthestMeasurement(d,h);g=N?N.end+this.options.gap:n+i,m=N?N.lane:h%this.options.lanes,this.options.lanes>1&&this.laneAssignments.set(h,m)}let b=l.get(f),y=typeof b=="number"?b:this.options.estimateSize(h),x=g+y;d[h]={index:h,start:g,size:y,end:x,key:f,lane:m},u[m]=h}return this.measurementsCache=d,d},{key:process.env.NODE_ENV!=="production"&&"getMeasurements",debug:()=>this.options.debug}),this.calculateRange=Ai(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,n,i,s)=>this.range=t.length>0&&n>0?pE({measurements:t,outerSize:n,scrollOffset:i,lanes:s}):null,{key:process.env.NODE_ENV!=="production"&&"calculateRange",debug:()=>this.options.debug}),this.getVirtualIndexes=Ai(()=>{let t=null,n=null,i=this.calculateRange();return i&&(t=i.startIndex,n=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,n]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,n]},(t,n,i,s,o)=>s===null||o===null?[]:t({startIndex:s,endIndex:o,overscan:n,count:i}),{key:process.env.NODE_ENV!=="production"&&"getVirtualIndexes",debug:()=>this.options.debug}),this.indexFromElement=t=>{let n=this.options.indexAttribute,i=t.getAttribute(n);return i?parseInt(i,10):(console.warn(`Missing attribute name '${n}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var n;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;let i=this.scrollState.index??((n=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:n.index);if(i!==void 0&&this.range){let s=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),o=Math.max(0,i-s),a=Math.min(this.options.count-1,i+s);return t>=o&&t<=a}return!0},this.measureElement=t=>{if(!t){this.elementsCache.forEach((o,a)=>{o.isConnected||(this.observer.unobserve(o),this.elementsCache.delete(a))});return}let n=this.indexFromElement(t),i=this.options.getItemKey(n),s=this.elementsCache.get(i);s!==t&&(s&&this.observer.unobserve(s),this.observer.observe(t),this.elementsCache.set(i,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(n)&&this.resizeItem(n,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,n)=>{var i;let s=this.measurementsCache[t];if(!s)return;let o=this.itemSizeCache.get(s.key)??s.size,a=n-o;a!==0&&(((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(s,a,this):s.start<this.getScrollOffset()+this.scrollAdjustments)&&(process.env.NODE_ENV!=="production"&&this.options.debug&&console.info("correction",a),this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=a,behavior:void 0})),this.pendingMeasuredCacheIndexes.push(s.index),this.itemSizeCache=new Map(this.itemSizeCache.set(s.key,n)),this.notify(!1))},this.getVirtualItems=Ai(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,n)=>{let i=[];for(let s=0,o=t.length;s<o;s++){let a=t[s],l=n[a];i.push(l)}return i},{key:process.env.NODE_ENV!=="production"&&"getVirtualItems",debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{let n=this.getMeasurements();if(n.length!==0)return Gd(n[Zg(0,n.length-1,i=>Gd(n[i]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{let t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,n,i=0)=>{if(!this.scrollElement)return 0;let s=this.getSize(),o=this.getScrollOffset();n==="auto"&&(n=t>=o+s?"end":"start"),n==="center"?t+=(i-s)/2:n==="end"&&(t-=s);let a=this.getMaxScrollOffset();return Math.max(Math.min(a,t),0)},this.getOffsetForIndex=(t,n="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));let i=this.getSize(),s=this.getScrollOffset(),o=this.measurementsCache[t];if(!o)return;if(n==="auto")if(o.end>=s+i-this.options.scrollPaddingEnd)n="end";else if(o.start<=s+this.options.scrollPaddingStart)n="start";else return[s,n];if(n==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),n];let a=n==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(a,n,o.size),n]},this.scrollToOffset=(t,{align:n="start",behavior:i="auto"}={})=>{let s=this.getOffsetForAlignment(t,n),o=this.now();this.scrollState={index:null,align:n,behavior:i,startedAt:o,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:n="auto",behavior:i="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));let s=this.getOffsetForIndex(t,n);if(!s)return;let[o,a]=s,l=this.now();this.scrollState={index:t,align:a,behavior:i,startedAt:l,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:n="auto"}={})=>{let i=this.getScrollOffset()+t,s=this.now();this.scrollState={index:null,align:"start",behavior:n,startedAt:s,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:n}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;let n=this.getMeasurements(),i;if(n.length===0)i=this.options.paddingStart;else if(this.options.lanes===1)i=((t=n[n.length-1])==null?void 0:t.end)??0;else{let s=Array(this.options.lanes).fill(null),o=n.length-1;for(;o>=0&&s.some(a=>a===null);){let a=n[o];s[a.lane]===null&&(s[a.lane]=a.end),o--}i=Math.max(...s.filter(a=>a!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:n,behavior:i})=>{this.options.scrollToFn(t,{behavior:i,adjustments:n},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}let n=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=n?n[0]:this.scrollState.lastTargetOffset,s=1,o=i!==this.scrollState.lastTargetOffset;if(!o&&jg(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=s){this.scrollState=null;return}}else this.scrollState.stableFrames=0,o&&(this.scrollState.lastTargetOffset=i,this.scrollState.behavior="auto",this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}},Zg=(r,e,t,n)=>{for(;r<=e;){let i=(r+e)/2|0,s=t(i);if(s<n)r=i+1;else if(s>n)e=i-1;else return i}return r>0?r-1:0};function pE({measurements:r,outerSize:e,scrollOffset:t,lanes:n}){let i=r.length-1,s=l=>r[l].start;if(r.length<=n)return{startIndex:0,endIndex:i};let o=Zg(0,i,s,t),a=o;if(n===1)for(;a<i&&r[a].end<t+e;)a++;else if(n>1){let l=Array(n).fill(0);for(;a<i&&l.some(d=>d<t+e);){let d=r[a];l[d.lane]=d.end,a++}let c=Array(n).fill(t+e);for(;o>=0&&c.some(d=>d>=t);){let d=r[o];c[d.lane]=d.start,o--}o=Math.max(0,o-o%n),a=Math.min(i,a+(n-1-a%n))}return{startIndex:o,endIndex:a}}var Qg=typeof document<"u"?ei.useLayoutEffect:ei.useEffect;function gE({useFlushSync:r=!0,...e}){let t=ei.useReducer(()=>({}),{})[1],n={...e,onChange:(s,o)=>{var a;r&&o?mE(t):t(),(a=e.onChange)==null||a.call(e,s,o)}},[i]=ei.useState(()=>new Xa(n));return i.setOptions(n),Qg(()=>i._didMount(),[]),Qg(()=>i._willUpdate()),i}function e0(r){return gE({observeElementRect:Yg,observeElementOffset:Jg,scrollToFn:Xg,...r})}import{Database as Lc,TableProperties as fR,RefreshCw as pR,X as pw,FunctionSquare as mR,LayoutGrid as gR,ChevronRight as bR,Loader2 as mw,ArrowUpDown as xR,Server as vR,Download as yR,Layers as qf,Plus as gw,Trash2 as Kf,BarChart3 as wR,Table2 as SR,ChevronDown as CR,Filter as kR,Edit2 as bw,Network as NR,Clock as ER}from"lucide-react";import{useState as ua,useCallback as vO}from"react";import{Play as yO,FunctionSquare as wO,XCircle as Jy,History as SO,Sparkles as CO,Loader2 as kO}from"lucide-react";var Uy=rp(t0(),1),Gy=rp(r0(),1);import{useRef as hO,forwardRef as fO,useImperativeHandle as pO,useCallback as mO}from"react";import{useEffect as ca,useLayoutEffect as lO,useState as da}from"react";var Yd=[],o0=[];(()=>{let r="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e<r.length;e++)(e%2?o0:Yd).push(t=t+r[e])})();function xE(r){if(r<768)return!1;for(let e=0,t=Yd.length;;){let n=e+t>>1;if(r<Yd[n])t=n;else if(r>=o0[n])e=n+1;else return!0;if(e==t)return!1}}function n0(r){return r>=127462&&r<=127487}var i0=8205;function a0(r,e,t=!0,n=!0){return(t?l0:vE)(r,e,n)}function l0(r,e,t){if(e==r.length)return e;e&&c0(r.charCodeAt(e))&&d0(r.charCodeAt(e-1))&&e--;let n=Kd(r,e);for(e+=s0(n);e<r.length;){let i=Kd(r,e);if(n==i0||i==i0||t&&xE(i))e+=s0(i),n=i;else if(n0(i)){let s=0,o=e-2;for(;o>=0&&n0(Kd(r,o));)s++,o-=2;if(s%2==0)break;e+=2}else break}return e}function vE(r,e,t){for(;e>0;){let n=l0(r,e-2,t);if(n<e)return n;e--}return 0}function Kd(r,e){let t=r.charCodeAt(e);if(!d0(t)||e+1==r.length)return t;let n=r.charCodeAt(e+1);return c0(n)?(t-55296<<10)+(n-56320)+65536:t}function c0(r){return r>=56320&&r<57344}function d0(r){return r>=55296&&r<56320}function s0(r){return r<65536?1:2}var we=class r{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,n){[e,t]=ys(this,e,t);let i=[];return this.decompose(0,e,i,2),n.length&&n.decompose(0,n.length,i,3),this.decompose(t,this.length,i,1),bs.from(i,this.length-(t-e)+n.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=ys(this,e,t);let n=[];return this.decompose(e,t,n,0),bs.from(n,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),n=this.length-this.scanIdentical(e,-1),i=new Di(this),s=new Di(e);for(let o=t,a=t;;){if(i.next(o),s.next(o),o=0,i.lineBreak!=s.lineBreak||i.done!=s.done||i.value!=s.value)return!1;if(a+=i.value.length,i.done||a>=n)return!0}}iter(e=1){return new Di(this,e)}iterRange(e,t=this.length){return new rl(this,e,t)}iterLines(e,t){let n;if(e==null)n=this.iter();else{t==null&&(t=this.lines+1);let i=this.line(e).from;n=this.iterRange(i,Math.max(i,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new nl(n)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?r.empty:e.length<=32?new br(e):bs.from(br.split(e,[]))}},br=class r extends we{constructor(e,t=yE(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,n,i){for(let s=0;;s++){let o=this.text[s],a=i+o.length;if((t?n:a)>=e)return new Xd(i,a,n,o);i=a+1,n++}}decompose(e,t,n,i){let s=e<=0&&t>=this.length?this:new r(u0(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(i&1){let o=n.pop(),a=tl(s.text,o.text.slice(),0,s.length);if(a.length<=32)n.push(new r(a,o.length+s.length));else{let l=a.length>>1;n.push(new r(a.slice(0,l)),new r(a.slice(l)))}}else n.push(s)}replace(e,t,n){if(!(n instanceof r))return super.replace(e,t,n);[e,t]=ys(this,e,t);let i=tl(this.text,tl(n.text,u0(this.text,0,e)),t),s=this.length+n.length-(t-e);return i.length<=32?new r(i,s):bs.from(r.split(i,[]),s)}sliceString(e,t=this.length,n=`
69
+ `){[e,t]=ys(this,e,t);let i="";for(let s=0,o=0;s<=t&&o<this.text.length;o++){let a=this.text[o],l=s+a.length;s>e&&o&&(i+=n),e<l&&t>s&&(i+=a.slice(Math.max(0,e-s),t-s)),s=l+1}return i}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let n=[],i=-1;for(let s of e)n.push(s),i+=s.length+1,n.length==32&&(t.push(new r(n,i)),n=[],i=-1);return i>-1&&t.push(new r(n,i)),t}},bs=class r extends we{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let n of e)this.lines+=n.lines}lineInner(e,t,n,i){for(let s=0;;s++){let o=this.children[s],a=i+o.length,l=n+o.lines-1;if((t?l:a)>=e)return o.lineInner(e,t,n,i);i=a+1,n=l+1}}decompose(e,t,n,i){for(let s=0,o=0;o<=t&&s<this.children.length;s++){let a=this.children[s],l=o+a.length;if(e<=l&&t>=o){let c=i&((o<=e?1:0)|(l>=t?2:0));o>=e&&l<=t&&!c?n.push(a):a.decompose(e-o,t-o,n,c)}o=l+1}}replace(e,t,n){if([e,t]=ys(this,e,t),n.lines<this.lines)for(let i=0,s=0;i<this.children.length;i++){let o=this.children[i],a=s+o.length;if(e>=s&&t<=a){let l=o.replace(e-s,t-s,n),c=this.lines-o.lines+l.lines;if(l.lines<c>>4&&l.lines>c>>6){let d=this.children.slice();return d[i]=l,new r(d,this.length-(t-e)+n.length)}return super.replace(s,a,l)}s=a+1}return super.replace(e,t,n)}sliceString(e,t=this.length,n=`
70
+ `){[e,t]=ys(this,e,t);let i="";for(let s=0,o=0;s<this.children.length&&o<=t;s++){let a=this.children[s],l=o+a.length;o>e&&s&&(i+=n),e<l&&t>o&&(i+=a.sliceString(e-o,t-o,n)),o=l+1}return i}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof r))return 0;let n=0,[i,s,o,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;i+=t,s+=t){if(i==o||s==a)return n;let l=this.children[i],c=e.children[s];if(l!=c)return n+l.scanIdentical(c,t);n+=l.length+1}}static from(e,t=e.reduce((n,i)=>n+i.length+1,-1)){let n=0;for(let f of e)n+=f.lines;if(n<32){let f=[];for(let p of e)p.flatten(f);return new br(f,t)}let i=Math.max(32,n>>5),s=i<<1,o=i>>1,a=[],l=0,c=-1,d=[];function u(f){let p;if(f.lines>s&&f instanceof r)for(let m of f.children)u(m);else f.lines>o&&(l>o||!l)?(h(),a.push(f)):f instanceof br&&l&&(p=d[d.length-1])instanceof br&&f.lines+p.lines<=32?(l+=f.lines,c+=f.length+1,d[d.length-1]=new br(p.text.concat(f.text),p.length+1+f.length)):(l+f.lines>i&&h(),l+=f.lines,c+=f.length+1,d.push(f))}function h(){l!=0&&(a.push(d.length==1?d[0]:r.from(d,c)),c=-1,l=d.length=0)}for(let f of e)u(f);return h(),a.length==1?a[0]:new r(a,t)}};we.empty=new br([""],0);function yE(r){let e=-1;for(let t of r)e+=t.length+1;return e}function tl(r,e,t=0,n=1e9){for(let i=0,s=0,o=!0;s<r.length&&i<=n;s++){let a=r[s],l=i+a.length;l>=t&&(l>n&&(a=a.slice(0,n-i)),i<t&&(a=a.slice(t-i)),o?(e[e.length-1]+=a,o=!1):e.push(a)),i=l+1}return e}function u0(r,e,t){return tl(r,[""],e,t)}var Di=class{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[e],this.offsets=[t>0?1:(e instanceof br?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,i=this.nodes[n],s=this.offsets[n],o=s>>1,a=i instanceof br?i.text.length:i.children.length;if(o==(t>0?a:0)){if(n==0)return this.done=!0,this.value="",this;t>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((s&1)==(t>0?0:1)){if(this.offsets[n]+=t,e==0)return this.lineBreak=!0,this.value=`
71
+ `,this;e--}else if(i instanceof br){let l=i.text[o+(t<0?-1:0)];if(this.offsets[n]+=t,l.length>Math.max(0,e))return this.value=e==0?l:t>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=i.children[o+(t<0?-1:0)];e>l.length?(e-=l.length,this.offsets[n]+=t):(t<0&&this.offsets[n]--,this.nodes.push(l),this.offsets.push(t>0?1:(l instanceof br?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}},rl=class{constructor(e,t,n){this.value="",this.done=!1,this.cursor=new Di(e,t>n?-1:1),this.pos=t>n?e.length:0,this.from=Math.min(t,n),this.to=Math.max(t,n)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let n=t<0?this.pos-this.from:this.to-this.pos;e>n&&(e=n),n-=e;let{value:i}=this.cursor.next(e);return this.pos+=(i.length+e)*t,this.value=i.length<=n?i:t<0?i.slice(i.length-n):i.slice(0,n),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}},nl=class{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:n,value:i}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):n?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=i,this.afterBreak=!1),this}get lineBreak(){return!1}};typeof Symbol<"u"&&(we.prototype[Symbol.iterator]=function(){return this.iter()},Di.prototype[Symbol.iterator]=rl.prototype[Symbol.iterator]=nl.prototype[Symbol.iterator]=function(){return this});var Xd=class{constructor(e,t,n,i){this.from=e,this.to=t,this.number=n,this.text=i}get length(){return this.to-this.from}};function ys(r,e,t){return e=Math.max(0,Math.min(r.length,e)),[e,Math.max(e,Math.min(r.length,t))]}function lt(r,e,t=!0,n=!0){return a0(r,e,t,n)}function wE(r){return r>=56320&&r<57344}function SE(r){return r>=55296&&r<56320}function Rt(r,e){let t=r.charCodeAt(e);if(!SE(t)||e+1==r.length)return t;let n=r.charCodeAt(e+1);return wE(n)?(t-55296<<10)+(n-56320)+65536:t}function wo(r){return r<=65535?String.fromCharCode(r):(r-=65536,String.fromCharCode((r>>10)+55296,(r&1023)+56320))}function vr(r){return r<65536?1:2}var Zd=/\r\n?|\n/,Ot=(function(r){return r[r.Simple=0]="Simple",r[r.TrackDel=1]="TrackDel",r[r.TrackBefore=2]="TrackBefore",r[r.TrackAfter=3]="TrackAfter",r})(Ot||(Ot={})),Ln=class r{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let n=this.sections[t+1];e+=n<0?this.sections[t]:n}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,n=0,i=0;t<this.sections.length;){let s=this.sections[t++],o=this.sections[t++];o<0?(e(n,i,s),i+=s):i+=o,n+=s}}iterChangedRanges(e,t=!1){Qd(this,e,t)}get invertedDesc(){let e=[];for(let t=0;t<this.sections.length;){let n=this.sections[t++],i=this.sections[t++];i<0?e.push(n,i):e.push(i,n)}return new r(e)}composeDesc(e){return this.empty?e:e.empty?this:g0(this,e)}mapDesc(e,t=!1){return e.empty?this:eu(this,e,t)}mapPos(e,t=-1,n=Ot.Simple){let i=0,s=0;for(let o=0;o<this.sections.length;){let a=this.sections[o++],l=this.sections[o++],c=i+a;if(l<0){if(c>e)return s+(e-i);s+=a}else{if(n!=Ot.Simple&&c>=e&&(n==Ot.TrackDel&&i<e&&c>e||n==Ot.TrackBefore&&i<e||n==Ot.TrackAfter&&c>e))return null;if(c>e||c==e&&t<0&&!a)return e==i||t<0?s:s+l;s+=l}i=c}if(e>i)throw new RangeError(`Position ${e} is out of range for changeset of length ${i}`);return s}touchesRange(e,t=e){for(let n=0,i=0;n<this.sections.length&&i<=t;){let s=this.sections[n++],o=this.sections[n++],a=i+s;if(o>=0&&i<=t&&a>=e)return i<e&&a>t?"cover":!0;i=a}return!1}toString(){let e="";for(let t=0;t<this.sections.length;){let n=this.sections[t++],i=this.sections[t++];e+=(e?" ":"")+n+(i>=0?":"+i:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new r(e)}static create(e){return new r(e)}},Zt=class r extends Ln{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Qd(this,(t,n,i,s,o)=>e=e.replace(i,i+(n-t),o),!1),e}mapDesc(e,t=!1){return eu(this,e,t,!0)}invert(e){let t=this.sections.slice(),n=[];for(let i=0,s=0;i<t.length;i+=2){let o=t[i],a=t[i+1];if(a>=0){t[i]=a,t[i+1]=o;let l=i>>1;for(;n.length<l;)n.push(we.empty);n.push(o?e.slice(s,s+o):we.empty)}s+=o}return new r(t,n)}compose(e){return this.empty?e:e.empty?this:g0(this,e,!0)}map(e,t=!1){return e.empty?this:eu(this,e,t,!0)}iterChanges(e,t=!1){Qd(this,e,t)}get desc(){return Ln.create(this.sections)}filter(e){let t=[],n=[],i=[],s=new Oi(this);e:for(let o=0,a=0;;){let l=o==e.length?1e9:e[o++];for(;a<l||a==l&&s.len==0;){if(s.done)break e;let d=Math.min(s.len,l-a);Vt(i,d,-1);let u=s.ins==-1?-1:s.off==0?s.ins:0;Vt(t,d,u),u>0&&ti(n,t,s.text),s.forward(d),a+=d}let c=e[o++];for(;a<c;){if(s.done)break e;let d=Math.min(s.len,c-a);Vt(t,d,-1),Vt(i,d,s.ins==-1?-1:s.off==0?s.ins:0),s.forward(d),a+=d}}return{changes:new r(t,n),filtered:Ln.create(i)}}toJSON(){let e=[];for(let t=0;t<this.sections.length;t+=2){let n=this.sections[t],i=this.sections[t+1];i<0?e.push(n):i==0?e.push([n]):e.push([n].concat(this.inserted[t>>1].toJSON()))}return e}static of(e,t,n){let i=[],s=[],o=0,a=null;function l(d=!1){if(!d&&!i.length)return;o<t&&Vt(i,t-o,-1);let u=new r(i,s);a=a?a.compose(u.map(a)):u,i=[],s=[],o=0}function c(d){if(Array.isArray(d))for(let u of d)c(u);else if(d instanceof r){if(d.length!=t)throw new RangeError(`Mismatched change set length (got ${d.length}, expected ${t})`);l(),a=a?a.compose(d.map(a)):d}else{let{from:u,to:h=u,insert:f}=d;if(u>h||u<0||h>t)throw new RangeError(`Invalid change range ${u} to ${h} (in doc of length ${t})`);let p=f?typeof f=="string"?we.of(f.split(n||Zd)):f:we.empty,m=p.length;if(u==h&&m==0)return;u<o&&l(),u>o&&Vt(i,u-o,-1),Vt(i,h-u,m),ti(s,i,p),o=h}}return c(e),l(!a),a}static empty(e){return new r(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],n=[];for(let i=0;i<e.length;i++){let s=e[i];if(typeof s=="number")t.push(s,-1);else{if(!Array.isArray(s)||typeof s[0]!="number"||s.some((o,a)=>a&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(s.length==1)t.push(s[0],0);else{for(;n.length<i;)n.push(we.empty);n[i]=we.of(s.slice(1)),t.push(s[0],n[i].length)}}}return new r(t,n)}static createSet(e,t){return new r(e,t)}};function Vt(r,e,t,n=!1){if(e==0&&t<=0)return;let i=r.length-2;i>=0&&t<=0&&t==r[i+1]?r[i]+=e:i>=0&&e==0&&r[i]==0?r[i+1]+=t:n?(r[i]+=e,r[i+1]+=t):r.push(e,t)}function ti(r,e,t){if(t.length==0)return;let n=e.length-2>>1;if(n<r.length)r[r.length-1]=r[r.length-1].append(t);else{for(;r.length<n;)r.push(we.empty);r.push(t)}}function Qd(r,e,t){let n=r.inserted;for(let i=0,s=0,o=0;o<r.sections.length;){let a=r.sections[o++],l=r.sections[o++];if(l<0)i+=a,s+=a;else{let c=i,d=s,u=we.empty;for(;c+=a,d+=l,l&&n&&(u=u.append(n[o-2>>1])),!(t||o==r.sections.length||r.sections[o+1]<0);)a=r.sections[o++],l=r.sections[o++];e(i,c,s,d,u),i=c,s=d}}}function eu(r,e,t,n=!1){let i=[],s=n?[]:null,o=new Oi(r),a=new Oi(e);for(let l=-1;;){if(o.done&&a.len||a.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&a.ins==-1){let c=Math.min(o.len,a.len);Vt(i,c,-1),o.forward(c),a.forward(c)}else if(a.ins>=0&&(o.ins<0||l==o.i||o.off==0&&(a.len<o.len||a.len==o.len&&!t))){let c=a.len;for(Vt(i,a.ins,-1);c;){let d=Math.min(o.len,c);o.ins>=0&&l<o.i&&o.len<=d&&(Vt(i,0,o.ins),s&&ti(s,i,o.text),l=o.i),o.forward(d),c-=d}a.next()}else if(o.ins>=0){let c=0,d=o.len;for(;d;)if(a.ins==-1){let u=Math.min(d,a.len);c+=u,d-=u,a.forward(u)}else if(a.ins==0&&a.len<d)d-=a.len,a.next();else break;Vt(i,c,l<o.i?o.ins:0),s&&l<o.i&&ti(s,i,o.text),l=o.i,o.forward(o.len-d)}else{if(o.done&&a.done)return s?Zt.createSet(i,s):Ln.create(i);throw new Error("Mismatched change set lengths")}}}function g0(r,e,t=!1){let n=[],i=t?[]:null,s=new Oi(r),o=new Oi(e);for(let a=!1;;){if(s.done&&o.done)return i?Zt.createSet(n,i):Ln.create(n);if(s.ins==0)Vt(n,s.len,0,a),s.next();else if(o.len==0&&!o.done)Vt(n,0,o.ins,a),i&&ti(i,n,o.text),o.next();else{if(s.done||o.done)throw new Error("Mismatched change set lengths");{let l=Math.min(s.len2,o.len),c=n.length;if(s.ins==-1){let d=o.ins==-1?-1:o.off?0:o.ins;Vt(n,l,d,a),i&&d&&ti(i,n,o.text)}else o.ins==-1?(Vt(n,s.off?0:s.len,l,a),i&&ti(i,n,s.textBit(l))):(Vt(n,s.off?0:s.len,o.off?0:o.ins,a),i&&!o.off&&ti(i,n,o.text));a=(s.ins>l||o.ins>=0&&o.len>l)&&(a||n.length>c),s.forward2(l),o.forward(l)}}}}var Oi=class{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i<e.length?(this.len=e[this.i++],this.ins=e[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:e}=this.set,t=this.i-2>>1;return t>=e.length?we.empty:e[t]}textBit(e){let{inserted:t}=this.set,n=this.i-2>>1;return n>=t.length&&!e?we.empty:t[n].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}},gs=class r{constructor(e,t,n){this.from=e,this.to=t,this.flags=n}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}get goalColumn(){let e=this.flags>>6;return e==16777215?void 0:e}map(e,t=-1){let n,i;return this.empty?n=i=e.mapPos(this.from,t):(n=e.mapPos(this.from,1),i=e.mapPos(this.to,-1)),n==this.from&&i==this.to?this:new r(n,i,this.flags)}extend(e,t=e,n=0){if(e<=this.anchor&&t>=this.anchor)return P.range(e,t,void 0,void 0,n);let i=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return P.range(this.anchor,i,void 0,void 0,n)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return P.range(e.anchor,e.head)}static create(e,t,n){return new r(e,t,n)}},P=class r{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:r.create(this.ranges.map(n=>n.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let n=0;n<this.ranges.length;n++)if(!this.ranges[n].eq(e.ranges[n],t))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new r([this.main],0)}addRange(e,t=!0){return r.create([e].concat(this.ranges),t?0:this.mainIndex+1)}replaceRange(e,t=this.mainIndex){let n=this.ranges.slice();return n[t]=e,r.create(n,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(e=>e.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new r(e.ranges.map(t=>gs.fromJSON(t)),e.main)}static single(e,t=e){return new r([r.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let n=0,i=0;i<e.length;i++){let s=e[i];if(s.empty?s.from<=n:s.from<n)return r.normalized(e.slice(),t);n=s.to}return new r(e,t)}static cursor(e,t=0,n,i){return gs.create(e,e,(t==0?0:t<0?8:16)|(n==null?7:Math.min(6,n))|(i??16777215)<<6)}static range(e,t,n,i,s){let o=(n??16777215)<<6|(i==null?7:Math.min(6,i));return!s&&e!=t&&(s=t<e?1:-1),t<e?gs.create(t,e,48|o):gs.create(e,t,(s?s<0?8:16:0)|o)}static normalized(e,t=0){let n=e[t];e.sort((i,s)=>i.from-s.from),t=e.indexOf(n);for(let i=1;i<e.length;i++){let s=e[i],o=e[i-1];if(s.empty?s.from<=o.to:s.from<o.to){let a=o.from,l=Math.max(s.to,o.to);i<=t&&t--,e.splice(--i,2,s.anchor>s.head?r.range(l,a):r.range(a,l))}}return new r(e,t)}};function b0(r,e){for(let t of r.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}var du=0,K=class r{constructor(e,t,n,i,s){this.combine=e,this.compareInput=t,this.compare=n,this.isStatic=i,this.id=du++,this.default=e([]),this.extensions=typeof s=="function"?s(this):s}get reader(){return this}static define(e={}){return new r(e.combine||(t=>t),e.compareInput||((t,n)=>t===n),e.compare||(e.combine?(t,n)=>t===n:uu),!!e.static,e.enables)}of(e){return new xs([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new xs(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new xs(e,this,2,t)}from(e,t){return t||(t=n=>n),this.compute([e],n=>t(n.field(e)))}};function uu(r,e){return r==e||r.length==e.length&&r.every((t,n)=>t===e[n])}var xs=class{constructor(e,t,n,i){this.dependencies=e,this.facet=t,this.type=n,this.value=i,this.id=du++}dynamicSlot(e){var t;let n=this.value,i=this.facet.compareInput,s=this.id,o=e[s]>>1,a=this.type==2,l=!1,c=!1,d=[];for(let u of this.dependencies)u=="doc"?l=!0:u=="selection"?c=!0:(((t=e[u.id])!==null&&t!==void 0?t:1)&1)==0&&d.push(e[u.id]);return{create(u){return u.values[o]=n(u),1},update(u,h){if(l&&h.docChanged||c&&(h.docChanged||h.selection)||tu(u,d)){let f=n(u);if(a?!h0(f,u.values[o],i):!i(f,u.values[o]))return u.values[o]=f,1}return 0},reconfigure:(u,h)=>{let f,p=h.config.address[s];if(p!=null){let m=al(h,p);if(this.dependencies.every(g=>g instanceof K?h.facet(g)===u.facet(g):g instanceof st?h.field(g,!1)==u.field(g,!1):!0)||(a?h0(f=n(u),m,i):i(f=n(u),m)))return u.values[o]=m,0}else f=n(u);return u.values[o]=f,1}}}};function h0(r,e,t){if(r.length!=e.length)return!1;for(let n=0;n<r.length;n++)if(!t(r[n],e[n]))return!1;return!0}function tu(r,e){let t=!1;for(let n of e)bo(r,n)&1&&(t=!0);return t}function CE(r,e,t){let n=t.map(l=>r[l.id]),i=t.map(l=>l.type),s=n.filter(l=>!(l&1)),o=r[e.id]>>1;function a(l){let c=[];for(let d=0;d<n.length;d++){let u=al(l,n[d]);if(i[d]==2)for(let h of u)c.push(h);else c.push(u)}return e.combine(c)}return{create(l){for(let c of n)bo(l,c);return l.values[o]=a(l),1},update(l,c){if(!tu(l,s))return 0;let d=a(l);return e.compare(d,l.values[o])?0:(l.values[o]=d,1)},reconfigure(l,c){let d=tu(l,n),u=c.config.facets[e.id],h=c.facet(e);if(u&&!d&&uu(t,u))return l.values[o]=h,0;let f=a(l);return e.compare(f,h)?(l.values[o]=h,0):(l.values[o]=f,1)}}}var Za=K.define({static:!0}),st=class r{constructor(e,t,n,i,s){this.id=e,this.createF=t,this.updateF=n,this.compareF=i,this.spec=s,this.provides=void 0}static define(e){let t=new r(du++,e.create,e.update,e.compare||((n,i)=>n===i),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(Za).find(n=>n.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:n=>(n.values[t]=this.create(n),1),update:(n,i)=>{let s=n.values[t],o=this.updateF(s,i);return this.compareF(s,o)?0:(n.values[t]=o,1)},reconfigure:(n,i)=>{let s=n.facet(Za),o=i.facet(Za),a;return(a=s.find(l=>l.field==this))&&a!=o.find(l=>l.field==this)?(n.values[t]=a.create(n),1):i.config.address[this.id]!=null?(n.values[t]=i.field(this),0):(n.values[t]=this.create(n),1)}}}init(e){return[this,Za.of({field:this,create:e})]}get extension(){return this}},Ti={lowest:4,low:3,default:2,high:1,highest:0};function go(r){return e=>new il(e,r)}var tn={highest:go(Ti.highest),high:go(Ti.high),default:go(Ti.default),low:go(Ti.low),lowest:go(Ti.lowest)},il=class{constructor(e,t){this.inner=e,this.prec=t}},sl=class r{of(e){return new xo(this,e)}reconfigure(e){return r.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}},xo=class{constructor(e,t){this.compartment=e,this.inner=t}},ol=class r{constructor(e,t,n,i,s,o){for(this.base=e,this.compartments=t,this.dynamicSlots=n,this.address=i,this.staticValues=s,this.facets=o,this.statusTemplate=[];this.statusTemplate.length<n.length;)this.statusTemplate.push(0)}staticFacet(e){let t=this.address[e.id];return t==null?e.default:this.staticValues[t>>1]}static resolve(e,t,n){let i=[],s=Object.create(null),o=new Map;for(let h of kE(e,t,o))h instanceof st?i.push(h):(s[h.facet.id]||(s[h.facet.id]=[])).push(h);let a=Object.create(null),l=[],c=[];for(let h of i)a[h.id]=c.length<<1,c.push(f=>h.slot(f));let d=n?.config.facets;for(let h in s){let f=s[h],p=f[0].facet,m=d&&d[h]||[];if(f.every(g=>g.type==0))if(a[p.id]=l.length<<1|1,uu(m,f))l.push(n.facet(p));else{let g=p.combine(f.map(b=>b.value));l.push(n&&p.compare(g,n.facet(p))?n.facet(p):g)}else{for(let g of f)g.type==0?(a[g.id]=l.length<<1|1,l.push(g.value)):(a[g.id]=c.length<<1,c.push(b=>g.dynamicSlot(b)));a[p.id]=c.length<<1,c.push(g=>CE(g,p,f))}}let u=c.map(h=>h(a));return new r(e,o,u,a,l,s)}};function kE(r,e,t){let n=[[],[],[],[],[]],i=new Map;function s(o,a){let l=i.get(o);if(l!=null){if(l<=a)return;let c=n[l].indexOf(o);c>-1&&n[l].splice(c,1),o instanceof xo&&t.delete(o.compartment)}if(i.set(o,a),Array.isArray(o))for(let c of o)s(c,a);else if(o instanceof xo){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let c=e.get(o.compartment)||o.inner;t.set(o.compartment,c),s(c,a)}else if(o instanceof il)s(o.inner,o.prec);else if(o instanceof st)n[a].push(o),o.provides&&s(o.provides,a);else if(o instanceof xs)n[a].push(o),o.facet.extensions&&s(o.facet.extensions,Ti.default);else{let c=o.extension;if(!c)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);s(c,a)}}return s(r,Ti.default),n.reduce((o,a)=>o.concat(a))}function bo(r,e){if(e&1)return 2;let t=e>>1,n=r.status[t];if(n==4)throw new Error("Cyclic dependency between fields and/or facets");if(n&2)return n;r.status[t]=4;let i=r.computeSlot(r,r.config.dynamicSlots[t]);return r.status[t]=2|i}function al(r,e){return e&1?r.config.staticValues[e>>1]:r.values[e>>1]}var x0=K.define(),ru=K.define({combine:r=>r.some(e=>e),static:!0}),v0=K.define({combine:r=>r.length?r[0]:void 0,static:!0}),y0=K.define(),w0=K.define(),S0=K.define(),C0=K.define({combine:r=>r.length?r[0]:!1}),jt=class{constructor(e,t){this.type=e,this.value=t}static define(){return new nu}},nu=class{of(e){return new jt(this,e)}},iu=class{constructor(e){this.map=e}of(e){return new le(this,e)}},le=class r{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new r(this.type,t)}is(e){return this.type==e}static define(e={}){return new iu(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let n=[];for(let i of e){let s=i.map(t);s&&n.push(s)}return n}};le.reconfigure=le.define();le.appendConfig=le.define();var mt=class r{constructor(e,t,n,i,s,o){this.startState=e,this.changes=t,this.selection=n,this.effects=i,this.annotations=s,this.scrollIntoView=o,this._doc=null,this._state=null,n&&b0(n,t.newLength),s.some(a=>a.type==r.time)||(this.annotations=s.concat(r.time.of(Date.now())))}static create(e,t,n,i,s,o){return new r(e,t,n,i,s,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(r.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}};mt.time=jt.define();mt.userEvent=jt.define();mt.addToHistory=jt.define();mt.remote=jt.define();function NE(r,e){let t=[];for(let n=0,i=0;;){let s,o;if(n<r.length&&(i==e.length||e[i]>=r[n]))s=r[n++],o=r[n++];else if(i<e.length)s=e[i++],o=e[i++];else return t;!t.length||t[t.length-1]<s?t.push(s,o):t[t.length-1]<o&&(t[t.length-1]=o)}}function k0(r,e,t){var n;let i,s,o;return t?(i=e.changes,s=Zt.empty(e.changes.length),o=r.changes.compose(e.changes)):(i=e.changes.map(r.changes),s=r.changes.mapDesc(e.changes,!0),o=r.changes.compose(i)),{changes:o,selection:e.selection?e.selection.map(s):(n=r.selection)===null||n===void 0?void 0:n.map(i),effects:le.mapEffects(r.effects,i).concat(le.mapEffects(e.effects,s)),annotations:r.annotations.length?r.annotations.concat(e.annotations):e.annotations,scrollIntoView:r.scrollIntoView||e.scrollIntoView}}function su(r,e,t){let n=e.selection,i=vs(e.annotations);return e.userEvent&&(i=i.concat(mt.userEvent.of(e.userEvent))),{changes:e.changes instanceof Zt?e.changes:Zt.of(e.changes||[],t,r.facet(v0)),selection:n&&(n instanceof P?n:P.single(n.anchor,n.head)),effects:vs(e.effects),annotations:i,scrollIntoView:!!e.scrollIntoView}}function N0(r,e,t){let n=su(r,e.length?e[0]:{},r.doc.length);e.length&&e[0].filter===!1&&(t=!1);for(let s=1;s<e.length;s++){e[s].filter===!1&&(t=!1);let o=!!e[s].sequential;n=k0(n,su(r,e[s],o?n.changes.newLength:r.doc.length),o)}let i=mt.create(r,n.changes,n.selection,n.effects,n.annotations,n.scrollIntoView);return AE(t?EE(i):i)}function EE(r){let e=r.startState,t=!0;for(let i of e.facet(y0)){let s=i(r);if(s===!1){t=!1;break}Array.isArray(s)&&(t=t===!0?s:NE(t,s))}if(t!==!0){let i,s;if(t===!1)s=r.changes.invertedDesc,i=Zt.empty(e.doc.length);else{let o=r.changes.filter(t);i=o.changes,s=o.filtered.mapDesc(o.changes).invertedDesc}r=mt.create(e,i,r.selection&&r.selection.map(s),le.mapEffects(r.effects,s),r.annotations,r.scrollIntoView)}let n=e.facet(w0);for(let i=n.length-1;i>=0;i--){let s=n[i](r);s instanceof mt?r=s:Array.isArray(s)&&s.length==1&&s[0]instanceof mt?r=s[0]:r=N0(e,vs(s),!1)}return r}function AE(r){let e=r.startState,t=e.facet(S0),n=r;for(let i=t.length-1;i>=0;i--){let s=t[i](r);s&&Object.keys(s).length&&(n=k0(n,su(e,s,r.changes.newLength),!0))}return n==r?r:mt.create(e,r.changes,r.selection,n.effects,n.annotations,n.scrollIntoView)}var TE=[];function vs(r){return r==null?TE:Array.isArray(r)?r:[r]}var $e=(function(r){return r[r.Word=0]="Word",r[r.Space=1]="Space",r[r.Other=2]="Other",r})($e||($e={})),ME=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,ou;try{ou=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function DE(r){if(ou)return ou.test(r);for(let e=0;e<r.length;e++){let t=r[e];if(/\w/.test(t)||t>"\x80"&&(t.toUpperCase()!=t.toLowerCase()||ME.test(t)))return!0}return!1}function OE(r){return e=>{if(!/\S/.test(e))return $e.Space;if(DE(e))return $e.Word;for(let t=0;t<r.length;t++)if(e.indexOf(r[t])>-1)return $e.Word;return $e.Other}}var Me=class r{constructor(e,t,n,i,s,o){this.config=e,this.doc=t,this.selection=n,this.values=i,this.status=e.statusTemplate.slice(),this.computeSlot=s,o&&(o._state=this);for(let a=0;a<this.config.dynamicSlots.length;a++)bo(this,a<<1);this.computeSlot=null}field(e,t=!0){let n=this.config.address[e.id];if(n==null){if(t)throw new RangeError("Field is not present in this state");return}return bo(this,n),al(this,n)}update(...e){return N0(this,e,!0)}applyTransaction(e){let t=this.config,{base:n,compartments:i}=t;for(let a of e.effects)a.is(sl.reconfigure)?(t&&(i=new Map,t.compartments.forEach((l,c)=>i.set(c,l)),t=null),i.set(a.value.compartment,a.value.extension)):a.is(le.reconfigure)?(t=null,n=a.value):a.is(le.appendConfig)&&(t=null,n=vs(n).concat(a.value));let s;t?s=e.startState.values.slice():(t=ol.resolve(n,i,this),s=new r(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,c)=>c.reconfigure(l,this),null).values);let o=e.startState.facet(ru)?e.newSelection:e.newSelection.asSingle();new r(t,e.newDoc,o,s,(a,l)=>l.update(a,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:P.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,n=e(t.ranges[0]),i=this.changes(n.changes),s=[n.range],o=vs(n.effects);for(let a=1;a<t.ranges.length;a++){let l=e(t.ranges[a]),c=this.changes(l.changes),d=c.map(i);for(let h=0;h<a;h++)s[h]=s[h].map(d);let u=i.mapDesc(c,!0);s.push(l.range.map(u)),i=i.compose(d),o=le.mapEffects(o,d).concat(le.mapEffects(vs(l.effects),u))}return{changes:i,selection:P.create(s,t.mainIndex),effects:o}}changes(e=[]){return e instanceof Zt?e:Zt.of(e,this.doc.length,this.facet(r.lineSeparator))}toText(e){return we.of(e.split(this.facet(r.lineSeparator)||Zd))}sliceDoc(e=0,t=this.doc.length){return this.doc.sliceString(e,t,this.lineBreak)}facet(e){let t=this.config.address[e.id];return t==null?e.default:(bo(this,t),al(this,t))}toJSON(e){let t={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(e)for(let n in e){let i=e[n];i instanceof st&&this.config.address[i.id]!=null&&(t[n]=i.spec.toJSON(this.field(e[n]),this))}return t}static fromJSON(e,t={},n){if(!e||typeof e.doc!="string")throw new RangeError("Invalid JSON representation for EditorState");let i=[];if(n){for(let s in n)if(Object.prototype.hasOwnProperty.call(e,s)){let o=n[s],a=e[s];i.push(o.init(l=>o.spec.fromJSON(a,l)))}}return r.create({doc:e.doc,selection:P.fromJSON(e.selection),extensions:t.extensions?i.concat([t.extensions]):i})}static create(e={}){let t=ol.resolve(e.extensions||[],new Map),n=e.doc instanceof we?e.doc:we.of((e.doc||"").split(t.staticFacet(r.lineSeparator)||Zd)),i=e.selection?e.selection instanceof P?e.selection:P.single(e.selection.anchor,e.selection.head):P.single(0);return b0(i,n.length),t.staticFacet(ru)||(i=i.asSingle()),new r(t,n,i,t.dynamicSlots.map(()=>null),(s,o)=>o.create(s),null)}get tabSize(){return this.facet(r.tabSize)}get lineBreak(){return this.facet(r.lineSeparator)||`
72
+ `}get readOnly(){return this.facet(C0)}phrase(e,...t){for(let n of this.facet(r.phrases))if(Object.prototype.hasOwnProperty.call(n,e)){e=n[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(n,i)=>{if(i=="$")return"$";let s=+(i||1);return!s||s>t.length?n:t[s-1]})),e}languageDataAt(e,t,n=-1){let i=[];for(let s of this.facet(x0))for(let o of s(this,t,n))Object.prototype.hasOwnProperty.call(o,e)&&i.push(o[e]);return i}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return OE(t.length?t[0]:"")}wordAt(e){let{text:t,from:n,length:i}=this.doc.lineAt(e),s=this.charCategorizer(e),o=e-n,a=e-n;for(;o>0;){let l=lt(t,o,!1);if(s(t.slice(l,o))!=$e.Word)break;o=l}for(;a<i;){let l=lt(t,a);if(s(t.slice(a,l))!=$e.Word)break;a=l}return o==a?null:P.range(o+n,a+n)}};Me.allowMultipleSelections=ru;Me.tabSize=K.define({combine:r=>r.length?r[0]:4});Me.lineSeparator=v0;Me.readOnly=C0;Me.phrases=K.define({compare(r,e){let t=Object.keys(r),n=Object.keys(e);return t.length==n.length&&t.every(i=>r[i]==e[i])}});Me.languageData=x0;Me.changeFilter=y0;Me.transactionFilter=w0;Me.transactionExtender=S0;sl.reconfigure=le.define();function Ut(r,e,t={}){let n={};for(let i of r)for(let s of Object.keys(i)){let o=i[s],a=n[s];if(a===void 0)n[s]=o;else if(!(a===o||o===void 0))if(Object.hasOwnProperty.call(t,s))n[s]=t[s](a,o);else throw new Error("Config merge conflict for field "+s)}for(let i in e)n[i]===void 0&&(n[i]=e[i]);return n}var Br=class{eq(e){return this==e}range(e,t=e){return vo.create(e,t,this)}};Br.prototype.startSide=Br.prototype.endSide=0;Br.prototype.point=!1;Br.prototype.mapMode=Ot.TrackDel;function hu(r,e){return r==e||r.constructor==e.constructor&&r.eq(e)}var vo=class r{constructor(e,t,n){this.from=e,this.to=t,this.value=n}static create(e,t,n){return new r(e,t,n)}};function au(r,e){return r.from-e.from||r.value.startSide-e.value.startSide}var lu=class r{constructor(e,t,n,i){this.from=e,this.to=t,this.value=n,this.maxPoint=i}get length(){return this.to[this.to.length-1]}findIndex(e,t,n,i=0){let s=n?this.to:this.from;for(let o=i,a=s.length;;){if(o==a)return o;let l=o+a>>1,c=s[l]-e||(n?this.value[l].endSide:this.value[l].startSide)-t;if(l==o)return c>=0?o:a;c>=0?a=l:o=l+1}}between(e,t,n,i){for(let s=this.findIndex(t,-1e9,!0),o=this.findIndex(n,1e9,!1,s);s<o;s++)if(i(this.from[s]+e,this.to[s]+e,this.value[s])===!1)return!1}map(e,t){let n=[],i=[],s=[],o=-1,a=-1;for(let l=0;l<this.value.length;l++){let c=this.value[l],d=this.from[l]+e,u=this.to[l]+e,h,f;if(d==u){let p=t.mapPos(d,c.startSide,c.mapMode);if(p==null||(h=f=p,c.startSide!=c.endSide&&(f=t.mapPos(d,c.endSide),f<h)))continue}else if(h=t.mapPos(d,c.startSide),f=t.mapPos(u,c.endSide),h>f||h==f&&c.startSide>0&&c.endSide<=0)continue;(f-h||c.endSide-c.startSide)<0||(o<0&&(o=h),c.point&&(a=Math.max(a,f-h)),n.push(c),i.push(h-o),s.push(f-o))}return{mapped:n.length?new r(i,s,n,a):null,pos:o}}},Ne=class r{constructor(e,t,n,i){this.chunkPos=e,this.chunk=t,this.nextLayer=n,this.maxPoint=i}static create(e,t,n,i){return new r(e,t,n,i)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:n=!1,filterFrom:i=0,filterTo:s=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(n&&(t=t.slice().sort(au)),this.isEmpty)return t.length?r.of(t):this;let a=new ll(this,null,-1).goto(0),l=0,c=[],d=new xr;for(;a.value||l<t.length;)if(l<t.length&&(a.from-t[l].from||a.startSide-t[l].value.startSide)>=0){let u=t[l++];d.addInner(u.from,u.to,u.value)||c.push(u)}else a.rangeIndex==1&&a.chunkIndex<this.chunk.length&&(l==t.length||this.chunkEnd(a.chunkIndex)<t[l].from)&&(!o||i>this.chunkEnd(a.chunkIndex)||s<this.chunkPos[a.chunkIndex])&&d.addChunk(this.chunkPos[a.chunkIndex],this.chunk[a.chunkIndex])?a.nextChunk():((!o||i>a.to||s<a.from||o(a.from,a.to,a.value))&&(d.addInner(a.from,a.to,a.value)||c.push(vo.create(a.from,a.to,a.value))),a.next());return d.finishInner(this.nextLayer.isEmpty&&!c.length?r.empty:this.nextLayer.update({add:c,filter:o,filterFrom:i,filterTo:s}))}map(e){if(e.empty||this.isEmpty)return this;let t=[],n=[],i=-1;for(let o=0;o<this.chunk.length;o++){let a=this.chunkPos[o],l=this.chunk[o],c=e.touchesRange(a,a+l.length);if(c===!1)i=Math.max(i,l.maxPoint),t.push(l),n.push(e.mapPos(a));else if(c===!0){let{mapped:d,pos:u}=l.map(a,e);d&&(i=Math.max(i,d.maxPoint),t.push(d),n.push(u))}}let s=this.nextLayer.map(e);return t.length==0?s:new r(n,t,s||r.empty,i)}between(e,t,n){if(!this.isEmpty){for(let i=0;i<this.chunk.length;i++){let s=this.chunkPos[i],o=this.chunk[i];if(t>=s&&e<=s+o.length&&o.between(s,e-s,t-s,n)===!1)return}this.nextLayer.between(e,t,n)}}iter(e=0){return yo.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return yo.from(e).goto(t)}static compare(e,t,n,i,s=-1){let o=e.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=s),a=t.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=s),l=f0(o,a,n),c=new Mi(o,l,s),d=new Mi(a,l,s);n.iterGaps((u,h,f)=>p0(c,u,d,h,f,i)),n.empty&&n.length==0&&p0(c,0,d,0,0,i)}static eq(e,t,n=0,i){i==null&&(i=999999999);let s=e.filter(d=>!d.isEmpty&&t.indexOf(d)<0),o=t.filter(d=>!d.isEmpty&&e.indexOf(d)<0);if(s.length!=o.length)return!1;if(!s.length)return!0;let a=f0(s,o),l=new Mi(s,a,0).goto(n),c=new Mi(o,a,0).goto(n);for(;;){if(l.to!=c.to||!cu(l.active,c.active)||l.point&&(!c.point||!hu(l.point,c.point)))return!1;if(l.to>i)return!0;l.next(),c.next()}}static spans(e,t,n,i,s=-1){let o=new Mi(e,null,s).goto(t),a=t,l=o.openStart;for(;;){let c=Math.min(o.to,n);if(o.point){let d=o.activeForPoint(o.to),u=o.pointFrom<t?d.length+1:o.point.startSide<0?d.length:Math.min(d.length,l);i.point(a,c,o.point,d,u,o.pointRank),l=Math.min(o.openEnd(c),d.length)}else c>a&&(i.span(a,c,o.active,l),l=o.openEnd(c));if(o.to>n)return l+(o.point&&o.to>n?1:0);a=o.to,o.next()}}static of(e,t=!1){let n=new xr;for(let i of e instanceof vo?[e]:t?RE(e):e)n.add(i.from,i.to,i.value);return n.finish()}static join(e){if(!e.length)return r.empty;let t=e[e.length-1];for(let n=e.length-2;n>=0;n--)for(let i=e[n];i!=r.empty;i=i.nextLayer)t=new r(i.chunkPos,i.chunk,t,Math.max(i.maxPoint,t.maxPoint));return t}};Ne.empty=new Ne([],[],null,-1);function RE(r){if(r.length>1)for(let e=r[0],t=1;t<r.length;t++){let n=r[t];if(au(e,n)>0)return r.slice().sort(au);e=n}return r}Ne.empty.nextLayer=Ne.empty;var xr=class r{finishChunk(e){this.chunks.push(new lu(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,n){this.addInner(e,t,n)||(this.nextLayer||(this.nextLayer=new r)).add(e,t,n)}addInner(e,t,n){let i=e-this.lastTo||n.startSide-this.last.endSide;if(i<=0&&(e-this.lastFrom||n.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return i<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=n,this.lastFrom=e,this.lastTo=t,this.value.push(n),n.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let n=t.value.length-1;return this.last=t.value[n],this.lastFrom=t.from[n]+e,this.lastTo=t.to[n]+e,!0}finish(){return this.finishInner(Ne.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=Ne.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}};function f0(r,e,t){let n=new Map;for(let s of r)for(let o=0;o<s.chunk.length;o++)s.chunk[o].maxPoint<=0&&n.set(s.chunk[o],s.chunkPos[o]);let i=new Set;for(let s of e)for(let o=0;o<s.chunk.length;o++){let a=n.get(s.chunk[o]);a!=null&&(t?t.mapPos(a):a)==s.chunkPos[o]&&!t?.touchesRange(a,a+s.chunk[o].length)&&i.add(s.chunk[o])}return i}var ll=class{constructor(e,t,n,i=0){this.layer=e,this.skip=t,this.minPoint=n,this.rank=i}get startSide(){return this.value?this.value.startSide:0}get endSide(){return this.value?this.value.endSide:0}goto(e,t=-1e9){return this.chunkIndex=this.rangeIndex=0,this.gotoInner(e,t,!1),this}gotoInner(e,t,n){for(;this.chunkIndex<this.layer.chunk.length;){let i=this.layer.chunk[this.chunkIndex];if(!(this.skip&&this.skip.has(i)||this.layer.chunkEnd(this.chunkIndex)<e||i.maxPoint<this.minPoint))break;this.chunkIndex++,n=!1}if(this.chunkIndex<this.layer.chunk.length){let i=this.layer.chunk[this.chunkIndex].findIndex(e-this.layer.chunkPos[this.chunkIndex],t,!0);(!n||this.rangeIndex<i)&&this.setRangeIndex(i)}this.next()}forward(e,t){(this.to-e||this.endSide-t)<0&&this.gotoInner(e,t,!0)}next(){for(;;)if(this.chunkIndex==this.layer.chunk.length){this.from=this.to=1e9,this.value=null;break}else{let e=this.layer.chunkPos[this.chunkIndex],t=this.layer.chunk[this.chunkIndex],n=e+t.from[this.rangeIndex];if(this.from=n,this.to=e+t.to[this.rangeIndex],this.value=t.value[this.rangeIndex],this.setRangeIndex(this.rangeIndex+1),this.minPoint<0||this.value.point&&this.to-this.from>=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex<this.layer.chunk.length&&this.skip.has(this.layer.chunk[this.chunkIndex]);)this.chunkIndex++;this.rangeIndex=0}else this.rangeIndex=e}nextChunk(){this.chunkIndex++,this.rangeIndex=0,this.next()}compare(e){return this.from-e.from||this.startSide-e.startSide||this.rank-e.rank||this.to-e.to||this.endSide-e.endSide}},yo=class r{constructor(e){this.heap=e}static from(e,t=null,n=-1){let i=[];for(let s=0;s<e.length;s++)for(let o=e[s];!o.isEmpty;o=o.nextLayer)o.maxPoint>=n&&i.push(new ll(o,t,n,s));return i.length==1?i[0]:new r(i)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let n of this.heap)n.goto(e,t);for(let n=this.heap.length>>1;n>=0;n--)Jd(this.heap,n);return this.next(),this}forward(e,t){for(let n of this.heap)n.forward(e,t);for(let n=this.heap.length>>1;n>=0;n--)Jd(this.heap,n);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Jd(this.heap,0)}}};function Jd(r,e){for(let t=r[e];;){let n=(e<<1)+1;if(n>=r.length)break;let i=r[n];if(n+1<r.length&&i.compare(r[n+1])>=0&&(i=r[n+1],n++),t.compare(i)<0)break;r[n]=t,r[e]=i,e=n}}var Mi=class{constructor(e,t,n){this.minPoint=n,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=yo.from(e,t,n)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){Qa(this.active,e),Qa(this.activeTo,e),Qa(this.activeRank,e),this.minActive=m0(this.active,this.activeTo)}addActive(e){let t=0,{value:n,to:i,rank:s}=this.cursor;for(;t<this.activeRank.length&&(s-this.activeRank[t]||i-this.activeTo[t])>0;)t++;el(this.active,t,n),el(this.activeTo,t,i),el(this.activeRank,t,s),e&&el(e,t,this.cursor.from),this.minActive=m0(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let n=this.openStart<0?[]:null;for(;;){let i=this.minActive;if(i>-1&&(this.activeTo[i]-this.cursor.from||this.active[i].endSide-this.cursor.startSide)<0){if(this.activeTo[i]>e){this.to=this.activeTo[i],this.endSide=this.active[i].endSide;break}this.removeActive(i),n&&Qa(n,i)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let s=this.cursor.value;if(!s.point)this.addActive(n),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from<this.cursor.to)this.cursor.next();else{this.point=s,this.pointFrom=this.cursor.from,this.pointRank=this.cursor.rank,this.to=this.cursor.to,this.endSide=s.endSide,this.cursor.next(),this.forward(this.to,this.endSide);break}}else{this.to=this.endSide=1e9;break}}if(n){this.openStart=0;for(let i=n.length-1;i>=0&&n[i]<e;i--)this.openStart++}}activeForPoint(e){if(!this.active.length)return this.active;let t=[];for(let n=this.active.length-1;n>=0&&!(this.activeRank[n]<this.pointRank);n--)(this.activeTo[n]>e||this.activeTo[n]==e&&this.active[n].endSide>=this.point.endSide)&&t.push(this.active[n]);return t.reverse()}openEnd(e){let t=0;for(let n=this.activeTo.length-1;n>=0&&this.activeTo[n]>e;n--)t++;return t}};function p0(r,e,t,n,i,s){r.goto(e),t.goto(n);let o=n+i,a=n,l=n-e,c=!!s.boundChange;for(let d=!1;;){let u=r.to+l-t.to,h=u||r.endSide-t.endSide,f=h<0?r.to+l:t.to,p=Math.min(f,o);if(r.point||t.point?(r.point&&t.point&&hu(r.point,t.point)&&cu(r.activeForPoint(r.to),t.activeForPoint(t.to))||s.comparePoint(a,p,r.point,t.point),d=!1):(d&&s.boundChange(a),p>a&&!cu(r.active,t.active)&&s.compareRange(a,p,r.active,t.active),c&&p<o&&(u||r.openEnd(f)!=t.openEnd(f))&&(d=!0)),f>o)break;a=f,h<=0&&r.next(),h>=0&&t.next()}}function cu(r,e){if(r.length!=e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!=e[t]&&!hu(r[t],e[t]))return!1;return!0}function Qa(r,e){for(let t=e,n=r.length-1;t<n;t++)r[t]=r[t+1];r.pop()}function el(r,e,t){for(let n=r.length-1;n>=e;n--)r[n+1]=r[n];r[e]=t}function m0(r,e){let t=-1,n=1e9;for(let i=0;i<e.length;i++)(e[i]-n||r[i].endSide-r[t].endSide)<0&&(t=i,n=e[i]);return t}function Bn(r,e,t=r.length){let n=0;for(let i=0;i<t&&i<r.length;)r.charCodeAt(i)==9?(n+=e-n%e,i++):(n++,i=lt(r,i));return n}function cl(r,e,t,n){for(let i=0,s=0;;){if(s>=e)return i;if(i==r.length)break;s+=r.charCodeAt(i)==9?t-s%t:1,i=lt(r,i)}return n===!0?-1:r.length}var E0=typeof Symbol>"u"?"__\u037C":Symbol.for("\u037C"),fu=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),A0=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{},Fr=class{constructor(e,t){this.rules=[];let{finish:n}=t||{};function i(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function s(o,a,l,c){let d=[],u=/^@(\w+)\b/.exec(o[0]),h=u&&u[1]=="keyframes";if(u&&a==null)return l.push(o[0]+";");for(let f in a){let p=a[f];if(/&/.test(f))s(f.split(/,\s*/).map(m=>o.map(g=>m.replace(/&/,g))).reduce((m,g)=>m.concat(g)),p,l);else if(p&&typeof p=="object"){if(!u)throw new RangeError("The value of a property ("+f+") should be a primitive value.");s(i(f),p,d,h)}else p!=null&&d.push(f.replace(/_.*/,"").replace(/[A-Z]/g,m=>"-"+m.toLowerCase())+": "+p+";")}(d.length||h)&&l.push((n&&!u&&!c?o.map(n):o).join(", ")+" {"+d.join(" ")+"}")}for(let o in e)s(i(o),e[o],this.rules)}getRules(){return this.rules.join(`
73
+ `)}static newName(){let e=A0[E0]||1;return A0[E0]=e+1,"\u037C"+e.toString(36)}static mount(e,t,n){let i=e[fu],s=n&&n.nonce;i?s&&i.setNonce(s):i=new pu(e,s),i.mount(Array.isArray(t)?t:[t],e)}},T0=new Map,pu=class{constructor(e,t){let n=e.ownerDocument||e,i=n.defaultView;if(!e.head&&e.adoptedStyleSheets&&i.CSSStyleSheet){let s=T0.get(n);if(s)return e[fu]=s;this.sheet=new i.CSSStyleSheet,T0.set(n,this)}else this.styleTag=n.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[fu]=this}mount(e,t){let n=this.sheet,i=0,s=0;for(let o=0;o<e.length;o++){let a=e[o],l=this.modules.indexOf(a);if(l<s&&l>-1&&(this.modules.splice(l,1),s--,l=-1),l==-1){if(this.modules.splice(s++,0,a),n)for(let c=0;c<a.rules.length;c++)n.insertRule(a.rules[c],i++)}else{for(;s<l;)i+=this.modules[s++].rules.length;i+=a.rules.length,s++}}if(n)t.adoptedStyleSheets.indexOf(this.sheet)<0&&(t.adoptedStyleSheets=[this.sheet,...t.adoptedStyleSheets]);else{let o="";for(let l=0;l<this.modules.length;l++)o+=this.modules[l].getRules()+`
74
+ `;this.styleTag.textContent=o;let a=t.head||t;this.styleTag.parentNode!=a&&a.insertBefore(this.styleTag,a.firstChild)}}setNonce(e){this.styleTag&&this.styleTag.getAttribute("nonce")!=e&&this.styleTag.setAttribute("nonce",e)}};var Fn={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},ws={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},IE=typeof navigator<"u"&&/Mac/.test(navigator.platform),PE=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(ut=0;ut<10;ut++)Fn[48+ut]=Fn[96+ut]=String(ut);var ut;for(ut=1;ut<=24;ut++)Fn[ut+111]="F"+ut;var ut;for(ut=65;ut<=90;ut++)Fn[ut]=String.fromCharCode(ut+32),ws[ut]=String.fromCharCode(ut);var ut;for(dl in Fn)ws.hasOwnProperty(dl)||(ws[dl]=Fn[dl]);var dl;function M0(r){var e=IE&&r.metaKey&&r.shiftKey&&!r.ctrlKey&&!r.altKey||PE&&r.shiftKey&&r.key&&r.key.length==1||r.key=="Unidentified",t=!e&&r.key||(r.shiftKey?ws:Fn)[r.keyCode]||r.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function De(){var r=arguments[0];typeof r=="string"&&(r=document.createElement(r));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){var i=t[n];typeof i=="string"?r.setAttribute(n,i):i!=null&&(r[n]=i)}e++}for(;e<arguments.length;e++)D0(r,arguments[e]);return r}function D0(r,e){if(typeof e=="string")r.appendChild(document.createTextNode(e));else if(e!=null)if(e.nodeType!=null)r.appendChild(e);else if(Array.isArray(e))for(var t=0;t<e.length;t++)D0(r,e[t]);else throw new RangeError("Unsupported child node: "+e)}var Qt=typeof navigator<"u"?navigator:{userAgent:"",vendor:"",platform:""},ku=typeof document<"u"?document:{documentElement:{style:{}}},Nu=/Edge\/(\d+)/.exec(Qt.userAgent),mb=/MSIE \d/.test(Qt.userAgent),Eu=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(Qt.userAgent),Hl=!!(mb||Eu||Nu),O0=!Hl&&/gecko\/(\d+)/i.test(Qt.userAgent),mu=!Hl&&/Chrome\/(\d+)/.exec(Qt.userAgent),R0="webkitFontSmoothing"in ku.documentElement.style,Au=!Hl&&/Apple Computer/.test(Qt.vendor),I0=Au&&(/Mobile\/\w+/.test(Qt.userAgent)||Qt.maxTouchPoints>2),Y={mac:I0||/Mac/.test(Qt.platform),windows:/Win/.test(Qt.platform),linux:/Linux|X11/.test(Qt.platform),ie:Hl,ie_version:mb?ku.documentMode||6:Eu?+Eu[1]:Nu?+Nu[1]:0,gecko:O0,gecko_version:O0?+(/Firefox\/(\d+)/.exec(Qt.userAgent)||[0,0])[1]:0,chrome:!!mu,chrome_version:mu?+mu[1]:0,ios:I0,android:/Android\b/.test(Qt.userAgent),webkit:R0,webkit_version:R0?+(/\bAppleWebKit\/(\d+)/.exec(Qt.userAgent)||[0,0])[1]:0,safari:Au,safari_version:Au?+(/\bVersion\/(\d+(\.\d+)?)/.exec(Qt.userAgent)||[0,0])[1]:0,tabSize:ku.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function yh(r,e){for(let t in r)t=="class"&&e.class?e.class+=" "+r.class:t=="style"&&e.style?e.style+=";"+r.style:e[t]=r[t];return e}var kl=Object.create(null);function wh(r,e,t){if(r==e)return!0;r||(r=kl),e||(e=kl);let n=Object.keys(r),i=Object.keys(e);if(n.length-(t&&n.indexOf(t)>-1?1:0)!=i.length-(t&&i.indexOf(t)>-1?1:0))return!1;for(let s of n)if(s!=t&&(i.indexOf(s)==-1||r[s]!==e[s]))return!1;return!0}function LE(r,e){for(let t=r.attributes.length-1;t>=0;t--){let n=r.attributes[t].name;e[n]==null&&r.removeAttribute(n)}for(let t in e){let n=e[t];t=="style"?r.style.cssText=n:r.getAttribute(t)!=n&&r.setAttribute(t,n)}}function P0(r,e,t){let n=!1;if(e)for(let i in e)t&&i in t||(n=!0,i=="style"?r.style.cssText="":r.removeAttribute(i));if(t)for(let i in t)e&&e[i]==t[i]||(n=!0,i=="style"?r.style.cssText=t[i]:r.setAttribute(i,t[i]));return n}function BE(r){let e=Object.create(null);for(let t=0;t<r.attributes.length;t++){let n=r.attributes[t];e[n.name]=n.value}return e}var er=class{eq(e){return!1}updateDOM(e,t,n){return!1}compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(e){return!0}coordsAt(e,t,n){return null}get isHidden(){return!1}get editable(){return!1}destroy(e){}},Pt=(function(r){return r[r.Text=0]="Text",r[r.WidgetBefore=1]="WidgetBefore",r[r.WidgetAfter=2]="WidgetAfter",r[r.WidgetRange=3]="WidgetRange",r})(Pt||(Pt={})),Z=class extends Br{constructor(e,t,n,i){super(),this.startSide=e,this.endSide=t,this.widget=n,this.spec=i}get heightRelevant(){return!1}static mark(e){return new Lo(e)}static widget(e){let t=Math.max(-1e4,Math.min(1e4,e.side||0)),n=!!e.block;return t+=n&&!e.inlineOrder?t>0?3e8:-4e8:t>0?1e8:-1e8,new Li(e,t,t,n,e.widget||null,!1)}static replace(e){let t=!!e.block,n,i;if(e.isBlockGap)n=-5e8,i=4e8;else{let{start:s,end:o}=gb(e,t);n=(s?t?-3e8:-1:5e8)-1,i=(o?t?2e8:1:-6e8)+1}return new Li(e,n,i,t,e.widget||null,!0)}static line(e){return new Bo(e)}static set(e,t=!1){return Ne.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}};Z.none=Ne.empty;var Lo=class r extends Z{constructor(e){let{start:t,end:n}=gb(e);super(t?-1:5e8,n?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?yh(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||kl}eq(e){return this==e||e instanceof r&&this.tagName==e.tagName&&wh(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}};Lo.prototype.point=!1;var Bo=class r extends Z{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof r&&this.spec.class==e.spec.class&&wh(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}};Bo.prototype.mapMode=Ot.TrackBefore;Bo.prototype.point=!0;var Li=class r extends Z{constructor(e,t,n,i,s,o){super(t,n,s,e),this.block=i,this.isReplace=o,this.mapMode=i?t<=0?Ot.TrackBefore:Ot.TrackAfter:Ot.TrackDel}get type(){return this.startSide!=this.endSide?Pt.WidgetRange:this.startSide<=0?Pt.WidgetBefore:Pt.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof r&&FE(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}};Li.prototype.point=!0;function gb(r,e=!1){let{inclusiveStart:t,inclusiveEnd:n}=r;return t==null&&(t=r.inclusive),n==null&&(n=r.inclusive),{start:t??e,end:n??e}}function FE(r,e){return r==e||!!(r&&e&&r.compare(e))}function As(r,e,t,n=0){let i=t.length-1;i>=0&&t[i]+n>=r?t[i]=Math.max(t[i],e):t.push(r,e)}var Nl=class r extends Br{constructor(e,t){super(),this.tagName=e,this.attributes=t}eq(e){return e==this||e instanceof r&&this.tagName==e.tagName&&wh(this.attributes,e.attributes)}static create(e){return new r(e.tagName,e.attributes||kl)}static set(e,t=!1){return Ne.of(e,t)}};Nl.prototype.startSide=Nl.prototype.endSide=-1;function Fo(r){let e;return r.nodeType==11?e=r.getSelection?r:r.ownerDocument:e=r,e.getSelection()}function Tu(r,e){return e?r==e||r.contains(e.nodeType!=1?e.parentNode:e):!1}function No(r,e){if(!e.anchorNode)return!1;try{return Tu(r,e.anchorNode)}catch{return!1}}function Eo(r){return r.nodeType==3?zo(r,0,r.nodeValue.length).getClientRects():r.nodeType==1?r.getClientRects():[]}function Ao(r,e,t,n){return t?L0(r,e,t,n,-1)||L0(r,e,t,n,1):!1}function ii(r){for(var e=0;;e++)if(r=r.previousSibling,!r)return e}function El(r){return r.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(r.nodeName)}function L0(r,e,t,n,i){for(;;){if(r==t&&e==n)return!0;if(e==(i<0?0:$n(r))){if(r.nodeName=="DIV")return!1;let s=r.parentNode;if(!s||s.nodeType!=1)return!1;e=ii(r)+(i<0?0:1),r=s}else if(r.nodeType==1){if(r=r.childNodes[e+(i<0?-1:0)],r.nodeType==1&&r.contentEditable=="false")return!1;e=i<0?$n(r):0}else return!1}}function $n(r){return r.nodeType==3?r.nodeValue.length:r.childNodes.length}function _o(r,e){let t=e?r.left:r.right;return{left:t,right:t,top:r.top,bottom:r.bottom}}function _E(r){let e=r.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:r.innerWidth,top:0,bottom:r.innerHeight}}function bb(r,e){let t=e.width/r.offsetWidth,n=e.height/r.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-r.offsetWidth)<1)&&(t=1),(n>.995&&n<1.005||!isFinite(n)||Math.abs(e.height-r.offsetHeight)<1)&&(n=1),{scaleX:t,scaleY:n}}function zE(r,e,t,n,i,s,o,a){let l=r.ownerDocument,c=l.defaultView||window;for(let d=r,u=!1;d&&!u;)if(d.nodeType==1){let h,f=d==l.body,p=1,m=1;if(f)h=_E(c);else{if(/^(fixed|sticky)$/.test(getComputedStyle(d).position)&&(u=!0),d.scrollHeight<=d.clientHeight&&d.scrollWidth<=d.clientWidth){d=d.assignedSlot||d.parentNode;continue}let y=d.getBoundingClientRect();({scaleX:p,scaleY:m}=bb(d,y)),h={left:y.left,right:y.left+d.clientWidth*p,top:y.top,bottom:y.top+d.clientHeight*m}}let g=0,b=0;if(i=="nearest")e.top<h.top?(b=e.top-(h.top+o),t>0&&e.bottom>h.bottom+b&&(b=e.bottom-h.bottom+o)):e.bottom>h.bottom&&(b=e.bottom-h.bottom+o,t<0&&e.top-b<h.top&&(b=e.top-(h.top+o)));else{let y=e.bottom-e.top,x=h.bottom-h.top;b=(i=="center"&&y<=x?e.top+y/2-x/2:i=="start"||i=="center"&&t<0?e.top-o:e.bottom-x+o)-h.top}if(n=="nearest"?e.left<h.left?(g=e.left-(h.left+s),t>0&&e.right>h.right+g&&(g=e.right-h.right+s)):e.right>h.right&&(g=e.right-h.right+s,t<0&&e.left<h.left+g&&(g=e.left-(h.left+s))):g=(n=="center"?e.left+(e.right-e.left)/2-(h.right-h.left)/2:n=="start"==a?e.left-s:e.right-(h.right-h.left)+s)-h.left,g||b)if(f)c.scrollBy(g,b);else{let y=0,x=0;if(b){let N=d.scrollTop;d.scrollTop+=b/m,x=(d.scrollTop-N)*m}if(g){let N=d.scrollLeft;d.scrollLeft+=g/p,y=(d.scrollLeft-N)*p}e={left:e.left-y,top:e.top-x,right:e.right-y,bottom:e.bottom-x},y&&Math.abs(y-g)<1&&(n="nearest"),x&&Math.abs(x-b)<1&&(i="nearest")}if(f)break;(e.top<h.top||e.bottom>h.bottom||e.left<h.left||e.right>h.right)&&(e={left:Math.max(e.left,h.left),right:Math.min(e.right,h.right),top:Math.max(e.top,h.top),bottom:Math.min(e.bottom,h.bottom)}),d=d.assignedSlot||d.parentNode}else if(d.nodeType==11)d=d.host;else break}function xb(r,e=!0){let t=r.ownerDocument,n=null,i=null;for(let s=r.parentNode;s&&!(s==t.body||(!e||n)&&i);)if(s.nodeType==1)!i&&s.scrollHeight>s.clientHeight&&(i=s),e&&!n&&s.scrollWidth>s.clientWidth&&(n=s),s=s.assignedSlot||s.parentNode;else if(s.nodeType==11)s=s.host;else break;return{x:n,y:i}}var Mu=class{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:n}=e;this.set(t,Math.min(e.anchorOffset,t?$n(t):0),n,Math.min(e.focusOffset,n?$n(n):0))}set(e,t,n,i){this.anchorNode=e,this.anchorOffset=t,this.focusNode=n,this.focusOffset=i}},Ri=null;Y.safari&&Y.safari_version>=26&&(Ri=!1);function vb(r){if(r.setActive)return r.setActive();if(Ri)return r.focus(Ri);let e=[];for(let t=r;t&&(e.push(t,t.scrollTop,t.scrollLeft),t!=t.ownerDocument);t=t.parentNode);if(r.focus(Ri==null?{get preventScroll(){return Ri={preventScroll:!0},!0}}:void 0),!Ri){Ri=!1;for(let t=0;t<e.length;){let n=e[t++],i=e[t++],s=e[t++];n.scrollTop!=i&&(n.scrollTop=i),n.scrollLeft!=s&&(n.scrollLeft=s)}}}var B0;function zo(r,e,t=e){let n=B0||(B0=document.createRange());return n.setEnd(r,t),n.setStart(r,e),n}function Ts(r,e,t,n){let i={key:e,code:e,keyCode:t,which:t,cancelable:!0};n&&({altKey:i.altKey,ctrlKey:i.ctrlKey,shiftKey:i.shiftKey,metaKey:i.metaKey}=n);let s=new KeyboardEvent("keydown",i);s.synthetic=!0,r.dispatchEvent(s);let o=new KeyboardEvent("keyup",i);return o.synthetic=!0,r.dispatchEvent(o),s.defaultPrevented||o.defaultPrevented}function $E(r){for(;r;){if(r&&(r.nodeType==9||r.nodeType==11&&r.host))return r;r=r.assignedSlot||r.parentNode}return null}function HE(r,e){let t=e.focusNode,n=e.focusOffset;if(!t||e.anchorNode!=t||e.anchorOffset!=n)return!1;for(n=Math.min(n,$n(t));;)if(n){if(t.nodeType!=1)return!1;let i=t.childNodes[n-1];i.contentEditable=="false"?n--:(t=i,n=$n(t))}else{if(t==r)return!0;n=ii(t),t=t.parentNode}}function yb(r){return r instanceof Window?r.pageYOffset>Math.max(0,r.document.documentElement.scrollHeight-r.innerHeight-4):r.scrollTop>Math.max(1,r.scrollHeight-r.clientHeight-4)}function wb(r,e){for(let t=r,n=e;;){if(t.nodeType==3&&n>0)return{node:t,offset:n};if(t.nodeType==1&&n>0){if(t.contentEditable=="false")return null;t=t.childNodes[n-1],n=$n(t)}else if(t.parentNode&&!El(t))n=ii(t),t=t.parentNode;else return null}}function Sb(r,e){for(let t=r,n=e;;){if(t.nodeType==3&&n<t.nodeValue.length)return{node:t,offset:n};if(t.nodeType==1&&n<t.childNodes.length){if(t.contentEditable=="false")return null;t=t.childNodes[n],n=0}else if(t.parentNode&&!El(t))n=ii(t)+1,t=t.parentNode;else return null}}var Sn=class r{constructor(e,t,n=!0){this.node=e,this.offset=t,this.precise=n}static before(e,t){return new r(e.parentNode,ii(e),t)}static after(e,t){return new r(e.parentNode,ii(e)+1,t)}},Be=(function(r){return r[r.LTR=0]="LTR",r[r.RTL=1]="RTL",r})(Be||(Be={})),Bi=Be.LTR,Sh=Be.RTL;function Cb(r){let e=[];for(let t=0;t<r.length;t++)e.push(1<<+r[t]);return e}var WE=Cb("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"),VE=Cb("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"),Du=Object.create(null),wn=[];for(let r of["()","[]","{}"]){let e=r.charCodeAt(0),t=r.charCodeAt(1);Du[e]=t,Du[t]=-e}function kb(r){return r<=247?WE[r]:1424<=r&&r<=1524?2:1536<=r&&r<=1785?VE[r-1536]:1774<=r&&r<=2220?4:8192<=r&&r<=8204?256:64336<=r&&r<=65023?4:1}var jE=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/,$r=class{get dir(){return this.level%2?Sh:Bi}constructor(e,t,n){this.from=e,this.to=t,this.level=n}side(e,t){return this.dir==t==e?this.to:this.from}forward(e,t){return e==(this.dir==t)}static find(e,t,n,i){let s=-1;for(let o=0;o<e.length;o++){let a=e[o];if(a.from<=t&&a.to>=t){if(a.level==n)return o;(s<0||(i!=0?i<0?a.from<t:a.to>t:e[s].level>a.level))&&(s=o)}}if(s<0)throw new RangeError("Index out of range");return s}};function Nb(r,e){if(r.length!=e.length)return!1;for(let t=0;t<r.length;t++){let n=r[t],i=e[t];if(n.from!=i.from||n.to!=i.to||n.direction!=i.direction||!Nb(n.inner,i.inner))return!1}return!0}var Ve=[];function UE(r,e,t,n,i){for(let s=0;s<=n.length;s++){let o=s?n[s-1].to:e,a=s<n.length?n[s].from:t,l=s?256:i;for(let c=o,d=l,u=l;c<a;c++){let h=kb(r.charCodeAt(c));h==512?h=d:h==8&&u==4&&(h=16),Ve[c]=h==4?2:h,h&7&&(u=h),d=h}for(let c=o,d=l,u=l;c<a;c++){let h=Ve[c];if(h==128)c<a-1&&d==Ve[c+1]&&d&24?h=Ve[c]=d:Ve[c]=256;else if(h==64){let f=c+1;for(;f<a&&Ve[f]==64;)f++;let p=c&&d==8||f<t&&Ve[f]==8?u==1?1:8:256;for(let m=c;m<f;m++)Ve[m]=p;c=f-1}else h==8&&u==1&&(Ve[c]=1);d=h,h&7&&(u=h)}}}function GE(r,e,t,n,i){let s=i==1?2:1;for(let o=0,a=0,l=0;o<=n.length;o++){let c=o?n[o-1].to:e,d=o<n.length?n[o].from:t;for(let u=c,h,f,p;u<d;u++)if(f=Du[h=r.charCodeAt(u)])if(f<0){for(let m=a-3;m>=0;m-=3)if(wn[m+1]==-f){let g=wn[m+2],b=g&2?i:g&4?g&1?s:i:0;b&&(Ve[u]=Ve[wn[m]]=b),a=m;break}}else{if(wn.length==189)break;wn[a++]=u,wn[a++]=h,wn[a++]=l}else if((p=Ve[u])==2||p==1){let m=p==i;l=m?0:1;for(let g=a-3;g>=0;g-=3){let b=wn[g+2];if(b&2)break;if(m)wn[g+2]|=2;else{if(b&4)break;wn[g+2]|=4}}}}}function qE(r,e,t,n){for(let i=0,s=n;i<=t.length;i++){let o=i?t[i-1].to:r,a=i<t.length?t[i].from:e;for(let l=o;l<a;){let c=Ve[l];if(c==256){let d=l+1;for(;;)if(d==a){if(i==t.length)break;d=t[i++].to,a=i<t.length?t[i].from:e}else if(Ve[d]==256)d++;else break;let u=s==1,h=(d<e?Ve[d]:n)==1,f=u==h?u?1:2:n;for(let p=d,m=i,g=m?t[m-1].to:r;p>l;)p==g&&(p=t[--m].from,g=m?t[m-1].to:r),Ve[--p]=f;l=d}else s=c,l++}}}function Ou(r,e,t,n,i,s,o){let a=n%2?2:1;if(n%2==i%2)for(let l=e,c=0;l<t;){let d=!0,u=!1;if(c==s.length||l<s[c].from){let m=Ve[l];m!=a&&(d=!1,u=m==16)}let h=!d&&a==1?[]:null,f=d?n:n+1,p=l;e:for(;;)if(c<s.length&&p==s[c].from){if(u)break e;let m=s[c];if(!d)for(let g=m.to,b=c+1;;){if(g==t)break e;if(b<s.length&&s[b].from==g)g=s[b++].to;else{if(Ve[g]==a)break e;break}}if(c++,h)h.push(m);else{m.from>l&&o.push(new $r(l,m.from,f));let g=m.direction==Bi!=!(f%2);Ru(r,g?n+1:n,i,m.inner,m.from,m.to,o),l=m.to}p=m.to}else{if(p==t||(d?Ve[p]!=a:Ve[p]==a))break;p++}h?Ou(r,l,p,n+1,i,h,o):l<p&&o.push(new $r(l,p,f)),l=p}else for(let l=t,c=s.length;l>e;){let d=!0,u=!1;if(!c||l>s[c-1].to){let m=Ve[l-1];m!=a&&(d=!1,u=m==16)}let h=!d&&a==1?[]:null,f=d?n:n+1,p=l;e:for(;;)if(c&&p==s[c-1].to){if(u)break e;let m=s[--c];if(!d)for(let g=m.from,b=c;;){if(g==e)break e;if(b&&s[b-1].to==g)g=s[--b].from;else{if(Ve[g-1]==a)break e;break}}if(h)h.push(m);else{m.to<l&&o.push(new $r(m.to,l,f));let g=m.direction==Bi!=!(f%2);Ru(r,g?n+1:n,i,m.inner,m.from,m.to,o),l=m.from}p=m.from}else{if(p==e||(d?Ve[p-1]!=a:Ve[p-1]==a))break;p--}h?Ou(r,p,l,n+1,i,h,o):p<l&&o.push(new $r(p,l,f)),l=p}}function Ru(r,e,t,n,i,s,o){let a=e%2?2:1;UE(r,i,s,n,a),GE(r,i,s,n,a),qE(i,s,n,a),Ou(r,i,s,e,t,n,o)}function KE(r,e,t){if(!r)return[new $r(0,0,e==Sh?1:0)];if(e==Bi&&!t.length&&!jE.test(r))return Eb(r.length);if(t.length)for(;r.length>Ve.length;)Ve[Ve.length]=256;let n=[],i=e==Bi?0:1;return Ru(r,i,i,t,0,r.length,n),n}function Eb(r){return[new $r(0,r,0)]}var Ab="";function YE(r,e,t,n,i){var s;let o=n.head-r.from,a=$r.find(e,o,(s=n.bidiLevel)!==null&&s!==void 0?s:-1,n.assoc),l=e[a],c=l.side(i,t);if(o==c){let h=a+=i?1:-1;if(h<0||h>=e.length)return null;l=e[a=h],o=l.side(!i,t),c=l.side(i,t)}let d=lt(r.text,o,l.forward(i,t));(d<l.from||d>l.to)&&(d=c),Ab=r.text.slice(Math.min(o,d),Math.max(o,d));let u=a==(i?e.length-1:0)?null:e[a+(i?1:-1)];return u&&d==c&&u.level+(i?0:1)<l.level?P.cursor(u.side(!i,t)+r.from,u.forward(i,t)?1:-1,u.level):P.cursor(d+r.from,l.forward(i,t)?-1:1,l.level)}function JE(r,e,t){for(let n=e;n<t;n++){let i=kb(r.charCodeAt(n));if(i==1)return Bi;if(i==2||i==4)return Sh}return Bi}var Tb=K.define(),Mb=K.define(),Db=K.define(),Ob=K.define(),Iu=K.define(),Rb=K.define(),Ib=K.define(),Ch=K.define(),kh=K.define(),Pb=K.define({combine:r=>r.some(e=>e)}),Lb=K.define({combine:r=>r.some(e=>e)}),Bb=K.define(),To=class r{constructor(e,t="nearest",n="nearest",i=5,s=5,o=!1){this.range=e,this.y=t,this.x=n,this.yMargin=i,this.xMargin=s,this.isSnapshot=o}map(e){return e.empty?this:new r(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new r(P.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}},ul=le.define({map:(r,e)=>r.map(e)}),Fb=le.define();function It(r,e,t){let n=r.facet(Ob);n.length?n[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}var _n=K.define({combine:r=>r.length?r[0]:!0}),XE=0,Cs=K.define({combine(r){return r.filter((e,t)=>{for(let n=0;n<t;n++)if(r[n].plugin==e.plugin)return!1;return!0})}}),Ye=class r{constructor(e,t,n,i,s){this.id=e,this.create=t,this.domEventHandlers=n,this.domEventObservers=i,this.baseExtensions=s(this),this.extension=this.baseExtensions.concat(Cs.of({plugin:this,arg:void 0}))}of(e){return this.baseExtensions.concat(Cs.of({plugin:this,arg:e}))}static define(e,t){let{eventHandlers:n,eventObservers:i,provide:s,decorations:o}=t||{};return new r(XE++,e,n,i,a=>{let l=[];return o&&l.push(Wl.of(c=>{let d=c.plugin(a);return d?o(d):Z.none})),s&&l.push(s(a)),l})}static fromClass(e,t){return r.define((n,i)=>new e(n,i),t)}},Mo=class{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(n){if(It(t.state,n,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){It(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(n){It(e.state,n,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}},_b=K.define(),Nh=K.define(),Wl=K.define(),zb=K.define(),Eh=K.define(),$o=K.define(),$b=K.define();function F0(r,e){let t=r.state.facet($b);if(!t.length)return t;let n=t.map(s=>s instanceof Function?s(r):s),i=[];return Ne.spans(n,e.from,e.to,{point(){},span(s,o,a,l){let c=s-e.from,d=o-e.from,u=i;for(let h=a.length-1;h>=0;h--,l--){let f=a[h].spec.bidiIsolate,p;if(f==null&&(f=JE(e.text,c,d)),l>0&&u.length&&(p=u[u.length-1]).to==c&&p.direction==f)p.to=d,u=p.inner;else{let m={from:c,to:d,direction:f,inner:[]};u.push(m),u=m.inner}}}}),i}var Hb=K.define();function Ah(r){let e=0,t=0,n=0,i=0;for(let s of r.state.facet(Hb)){let o=s(r);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(n=Math.max(n,o.top)),o.bottom!=null&&(i=Math.max(i,o.bottom)))}return{left:e,right:t,top:n,bottom:i}}var So=K.define(),nn=class r{constructor(e,t,n,i){this.fromA=e,this.toA=t,this.fromB=n,this.toB=i}join(e){return new r(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,n=this;for(;t>0;t--){let i=e[t-1];if(!(i.fromA>n.toA)){if(i.toA<n.fromA)break;n=n.join(i),e.splice(t-1,1)}}return e.splice(t,0,n),e}static extendWithRanges(e,t){if(t.length==0)return e;let n=[];for(let i=0,s=0,o=0;;){let a=i<e.length?e[i].fromB:1e9,l=s<t.length?t[s]:1e9,c=Math.min(a,l);if(c==1e9)break;let d=c+o,u=c,h=d;for(;;)if(s<t.length&&t[s]<=u){let f=t[s+1];s+=2,u=Math.max(u,f);for(let p=i;p<e.length&&e[p].fromB<=u;p++)o=e[p].toA-e[p].toB;h=Math.max(h,f+o)}else if(i<e.length&&e[i].fromB<=u){let f=e[i++];u=Math.max(u,f.toB),h=Math.max(h,f.toA),o=f.toA-f.toB}else break;n.push(new r(d,h,c,u))}return n}},Al=class r{constructor(e,t,n){this.view=e,this.state=t,this.transactions=n,this.flags=0,this.startState=e.state,this.changes=Zt.empty(this.startState.doc.length);for(let s of n)this.changes=this.changes.compose(s.changes);let i=[];this.changes.iterChangedRanges((s,o,a,l)=>i.push(new nn(s,o,a,l))),this.changedRanges=i}static create(e,t,n){return new r(e,t,n)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}},ZE=[],Xe=class{constructor(e,t,n=0){this.dom=e,this.length=t,this.flags=n,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return ZE}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&LE(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let n=t;for(let i of this.children){if(i==e)return n;n+=i.length+i.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t){return null}domPosFor(e,t){let n=ii(this.dom),i=this.length?e>0:t>0;return new Sn(this.parent.dom,n+(i?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof Ds)return e;return null}static get(e){return e.cmTile}},Ms=class extends Xe{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,n=null,i,s=e?.node==t?e:null,o=0;for(let a of this.children){if(a.sync(e),o+=a.length+a.breakAfter,i=n?n.nextSibling:t.firstChild,s&&i!=a.dom&&(s.written=!0),a.dom.parentNode==t)for(;i&&i!=a.dom;)i=_0(i);else t.insertBefore(a.dom,i);n=a.dom}for(i=n?n.nextSibling:t.firstChild,s&&i&&(s.written=!0);i;)i=_0(i);this.length=o}};function _0(r){let e=r.nextSibling;return r.parentNode.removeChild(r),e}var Ds=class extends Ms{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=Xe.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],n=this,i=0,s=0;;)if(i==n.children.length){if(!t.length)return;n=n.parent,n.breakAfter&&s++,i=t.pop()}else{let o=n.children[i++];if(o instanceof zn)t.push(i),n=o,i=0;else{let a=s+o.length,l=e(o,s);if(l!==void 0)return l;s=a+o.breakAfter}}}resolveBlock(e,t){let n,i=-1,s,o=-1;if(this.blockTiles((a,l)=>{let c=l+a.length;if(e>=l&&e<=c){if(a.isWidget()&&t>=-1&&t<=1){if(a.flags&32)return!0;a.flags&16&&(n=void 0)}(l<e||e==c&&(t<-1?a.length:a.covers(1)))&&(!n||!a.isWidget()&&n.isWidget())&&(n=a,i=e-l),(c>e||e==l&&(t>1?a.length:a.covers(-1)))&&(!s||!a.isWidget()&&s.isWidget())&&(s=a,o=e-l)}}),!n&&!s)throw new Error("No tile at position "+e);return n&&t<0||!s?{tile:n,offset:i}:{tile:s,offset:o}}},zn=class r extends Ms{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,t){let n=new r(t||document.createElement(e.tagName),e);return t||(n.flags|=4),n}},Os=class r extends Ms{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(e,t,n){let i=new r(t||document.createElement("div"),e);return(!t||!n)&&(i.flags|=4),i}get domAttrs(){return this.attrs}resolveInline(e,t,n){let i=null,s=-1,o=null,a=-1;function l(d,u){for(let h=0,f=0;h<d.children.length&&f<=u;h++){let p=d.children[h],m=f+p.length;m>=u&&(p.isComposite()?l(p,u-f):(!o||o.isHidden&&(t>0||n&&eA(o,p)))&&(m>u||p.flags&32)?(o=p,a=u-f):(f<u||p.flags&16&&!p.isHidden)&&(i=p,s=u-f)),f=m}}l(this,e);let c=(t<0?i:o)||i||o;return c?{tile:c,offset:c==i?s:a}:null}coordsIn(e,t){let n=this.resolveInline(e,t,!0);return n?n.tile.coordsIn(Math.max(0,n.offset),t):QE(this)}domIn(e,t){let n=this.resolveInline(e,t);if(n){let{tile:i,offset:s}=n;if(this.dom.contains(i.dom))return i.isText()?new Sn(i.dom,Math.min(i.dom.nodeValue.length,s)):i.domPosFor(s,i.flags&16?1:i.flags&32?-1:t);let o=n.tile.parent,a=!1;for(let l of o.children){if(a)return new Sn(l.dom,0);l==n.tile&&(a=!0)}}return new Sn(this.dom,0)}};function QE(r){let e=r.dom.lastChild;if(!e)return r.dom.getBoundingClientRect();let t=Eo(e);return t[t.length-1]||null}function eA(r,e){let t=r.coordsIn(0,1),n=e.coordsIn(0,1);return t&&n&&n.top<t.bottom}var cr=class r extends Ms{constructor(e,t){super(e),this.mark=t}get domAttrs(){return this.mark.attrs}static of(e,t){let n=new r(t||document.createElement(e.tagName),e);return t||(n.flags|=4),n}},Ii=class r extends Xe{constructor(e,t){super(e,t.length),this.text=t}sync(e){this.flags&2||(super.sync(e),this.dom.nodeValue!=this.text&&(e&&e.node==this.dom&&(e.written=!0),this.dom.nodeValue=this.text))}isText(){return!0}toString(){return JSON.stringify(this.text)}coordsIn(e,t){let n=this.dom.nodeValue.length;e>n&&(e=n);let i=e,s=e,o=0;e==0&&t<0||e==n&&t>=0?Y.chrome||Y.gecko||(e?(i--,o=1):s<n&&(s++,o=-1)):t<0?i--:s<n&&s++;let a=zo(this.dom,i,s).getClientRects();if(!a.length)return null;let l=a[(o?o<0:t>=0)?0:a.length-1];return Y.safari&&!o&&l.width==0&&(l=Array.prototype.find.call(a,c=>c.width)||l),o?_o(l,o<0):l||null}static of(e,t){let n=new r(t||document.createTextNode(e),e);return t||(n.flags|=2),n}},Fi=class r extends Xe{constructor(e,t,n,i){super(e,t,i),this.widget=n}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,n){let i=this.widget.coordsAt(this.dom,e,t);if(i)return i;if(n)return _o(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let s=this.dom.getClientRects(),o=null;if(!s.length)return null;let a=this.flags&16?!0:this.flags&32?!1:e>0;for(let l=a?s.length-1:0;o=s[l],!(e>0?l==0:l==s.length-1||o.top<o.bottom);l+=a?-1:1);return _o(o,!a)}}get overrideDOMText(){if(!this.length)return we.empty;let{root:e}=this;if(!e)return we.empty;let t=this.posAtStart;return e.view.state.doc.slice(t,t+this.length)}destroy(){super.destroy(),this.widget.destroy(this.dom)}static of(e,t,n,i,s){return s||(s=e.toDOM(t),e.editable||(s.contentEditable="false")),new r(s,n,e,i)}},Rs=class extends Xe{constructor(e){let t=document.createElement("img");t.className="cm-widgetBuffer",t.setAttribute("aria-hidden","true"),super(t,0,e)}get isHidden(){return!0}get overrideDOMText(){return we.empty}coordsIn(e){return this.dom.getBoundingClientRect()}},Pu=class{constructor(e){this.index=0,this.beforeBreak=!1,this.parents=[],this.tile=e}advance(e,t,n){let{tile:i,index:s,beforeBreak:o,parents:a}=this;for(;e||t>0;)if(i.isComposite())if(o){if(!e)break;n&&n.break(),e--,o=!1}else if(s==i.children.length){if(!e&&!a.length)break;n&&n.leave(i),o=!!i.breakAfter,{tile:i,index:s}=a.pop(),s++}else{let l=i.children[s],c=l.breakAfter;(t>0?l.length<=e:l.length<e)&&(!n||n.skip(l,0,l.length)!==!1||!l.isComposite)?(o=!!c,s++,e-=l.length):(a.push({tile:i,index:s}),i=l,s=0,n&&l.isComposite()&&n.enter(l))}else if(s==i.length)o=!!i.breakAfter,{tile:i,index:s}=a.pop(),s++;else if(e){let l=Math.min(e,i.length-s);n&&n.skip(i,s,s+l),e-=l,s+=l}else break;return this.tile=i,this.index=s,this.beforeBreak=o,this}get root(){return this.parents.length?this.parents[0].tile:this.tile}},Lu=class{constructor(e,t,n,i){this.from=e,this.to=t,this.wrapper=n,this.rank=i}},Bu=class{constructor(e,t,n){this.cache=e,this.root=t,this.blockWrappers=n,this.curLine=null,this.lastBlock=null,this.afterWidget=null,this.pos=0,this.wrappers=[],this.wrapperPos=0}addText(e,t,n,i){var s;this.flushBuffer();let o=this.ensureMarks(t,n),a=o.lastChild;if(a&&a.isText()&&!(a.flags&8)&&a.length+e.length<512){this.cache.reused.set(a,2);let l=o.children[o.children.length-1]=new Ii(a.dom,a.text+e);l.parent=o}else o.append(i||Ii.of(e,(s=this.cache.find(Ii))===null||s===void 0?void 0:s.dom));this.pos+=e.length,this.afterWidget=null}addComposition(e,t){let n=this.curLine;n.dom!=t.line.dom&&(n.setDOM(this.cache.reused.has(t.line)?gu(t.line.dom):t.line.dom),this.cache.reused.set(t.line,2));let i=n;for(let a=t.marks.length-1;a>=0;a--){let l=t.marks[a],c=i.lastChild;if(c instanceof cr&&c.mark.eq(l.mark))c.dom!=l.dom&&c.setDOM(gu(l.dom)),i=c;else{if(this.cache.reused.get(l)){let u=Xe.get(l.dom);u&&u.setDOM(gu(l.dom))}let d=cr.of(l.mark,l.dom);i.append(d),i=d}this.cache.reused.set(l,2)}let s=Xe.get(e.text);s&&this.cache.reused.set(s,2);let o=new Ii(e.text,e.text.nodeValue);o.flags|=8,i.append(o)}addInlineWidget(e,t,n){let i=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);i||this.flushBuffer();let s=this.ensureMarks(t,n);!i&&!(e.flags&16)&&s.append(this.getBuffer(1)),s.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,n){this.flushBuffer(),this.ensureMarks(t,n).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){var n;e||(e=Wb);let i=Os.start(e,t||((n=this.cache.find(Os))===null||n===void 0?void 0:n.dom),!!t);this.getBlockPos().append(this.lastBlock=this.curLine=i)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){var n;let i=this.curLine;for(let s=e.length-1;s>=0;s--){let o=e[s],a;if(t>0&&(a=i.lastChild)&&a instanceof cr&&a.mark.eq(o))i=a,t--;else{let l=cr.of(o,(n=this.cache.find(cr,c=>c.mark.eq(o)))===null||n===void 0?void 0:n.dom);i.append(l),i=l,t=0}}return i}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!z0(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(Y.ios&&z0(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(bu,0,32)||new Fi(bu.toDOM(),0,bu,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to<this.pos&&this.wrappers.splice(e,1);for(let e=this.blockWrappers;e.value&&e.from<=this.pos;e.next())if(e.to>=this.pos){let t=new Lu(e.from,e.to,e.value,e.rank),n=this.wrappers.length;for(;n>0&&(this.wrappers[n-1].rank-t.rank||this.wrappers[n-1].to-t.to)<0;)n--;this.wrappers.splice(n,0,t)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let t=this.root;for(let n of this.wrappers){let i=t.lastChild;if(n.from<this.pos&&i instanceof zn&&i.wrapper.eq(n.wrapper))t=i;else{let s=zn.of(n.wrapper,(e=this.cache.find(zn,o=>o.wrapper.eq(n.wrapper)))===null||e===void 0?void 0:e.dom);t.append(s),t=s}}return t}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),n=this.cache.find(Rs,void 0,1);return n&&(n.flags=t),n||new Rs(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}},Fu=class{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:i,lineBreak:s,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=i;let a=this.textOff=Math.min(e,i.length);return s?null:i.slice(0,a)}let t=Math.min(this.text.length,this.textOff+e),n=this.text.slice(this.textOff,t);return this.textOff=t,n}},Tl=[Fi,Os,Ii,cr,Rs,zn,Ds];for(let r=0;r<Tl.length;r++)Tl[r].bucket=r;var _u=class{constructor(e){this.view=e,this.buckets=Tl.map(()=>[]),this.index=Tl.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,n=this.buckets[t];n.length<6?n.push(e):n[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,n=2){let i=e.bucket,s=this.buckets[i],o=this.index[i];for(let a=s.length-1;a>=0;a--){let l=(a+o)%s.length,c=s[l];if((!t||t(c))&&!this.reused.has(c))return s.splice(l,1),l<o&&this.index[i]--,this.reused.set(c,n),c}return null}findWidget(e,t,n){let i=this.buckets[0];if(i.length)for(let s=0,o=0;;s++){if(s==i.length){if(o)return null;o=1,s=0}let a=i[s];if(!this.reused.has(a)&&(o==0?a.widget.compare(e):a.widget.constructor==e.constructor&&e.updateDOM(a.dom,this.view,a.widget)))return i.splice(s,1),s<this.index[0]&&this.index[0]--,a.widget==e&&a.length==t&&(a.flags&497)==n?(this.reused.set(a,1),a):(this.reused.set(a,2),new Fi(a.dom,t,e,a.flags&-498|n))}}reuse(e){return this.reused.set(e,1),e}maybeReuse(e,t=2){if(!this.reused.has(e))return this.reused.set(e,t),e.dom}clear(){for(let e=0;e<this.buckets.length;e++)this.buckets[e].length=this.index[e]=0}},zu=class{constructor(e,t,n,i,s){this.view=e,this.decorations=i,this.disallowBlockEffectsFor=s,this.openWidget=!1,this.openMarks=0,this.cache=new _u(e),this.text=new Fu(e.state.doc),this.builder=new Bu(this.cache,new Ds(e,e.contentDOM),Ne.iter(n)),this.cache.reused.set(t,2),this.old=new Pu(t),this.reuseWalker={skip:(o,a,l)=>{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,t){let n=t&&this.getCompositionContext(t.text);for(let i=0,s=0,o=0;;){let a=o<e.length?e[o++]:null,l=a?a.fromA:this.old.root.length;if(l>i){let c=l-i;this.preserve(c,!o,!a),i=l,s+=c}if(!a)break;t&&a.fromA<=t.range.fromA&&a.toA>=t.range.toA?(this.forward(a.fromA,t.range.fromA,t.range.fromA<t.range.toA?1:-1),this.emit(s,t.range.fromB),this.cache.clear(),this.builder.addComposition(t,n),this.text.skip(t.range.toB-t.range.fromB),this.forward(t.range.fromA,a.toA),this.emit(t.range.toB,a.toB)):(this.forward(a.fromA,a.toA),this.emit(s,a.toB)),s=a.toB,i=a.toA}return this.builder.curLine&&this.builder.endLine(),this.builder.root}preserve(e,t,n){let i=nA(this.old),s=this.openMarks;this.old.advance(e,n?1:-1,{skip:(o,a,l)=>{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(l-a);else{let c=l>0||a<o.length?Fi.of(o.widget,this.view,l-a,o.flags&496,this.cache.maybeReuse(o)):this.cache.reuse(o);c.flags&256?(c.flags&=-2,this.builder.addBlockWidget(c)):(this.builder.ensureLine(null),this.builder.addInlineWidget(c,i,s),s=i.length)}else if(o.isText())this.builder.ensureLine(null),!a&&l==o.length&&!this.cache.reused.has(o)?this.builder.addText(o.text,i,s,this.cache.reuse(o)):(this.cache.add(o),this.builder.addText(o.text.slice(a,l),i,s)),s=i.length;else if(o.isLine())o.flags&=-2,this.cache.reused.set(o,1),this.builder.addLine(o);else if(o instanceof Rs)this.cache.add(o);else if(o instanceof cr)this.builder.ensureLine(null),this.builder.addMark(o,i,s),this.cache.reused.set(o,1),s=i.length;else return!1;this.openWidget=!1},enter:o=>{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof cr&&i.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?i.length&&(i.length=s=0):o instanceof cr&&(i.shift(),s=Math.min(s,i.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let n=null,i=this.builder,s=0,o=Ne.spans(this.decorations,e,t,{point:(a,l,c,d,u,h)=>{if(c instanceof Li){if(this.disallowBlockEffectsFor[h]){if(c.block)throw new RangeError("Block decorations may not be specified via plugins");if(l>this.view.state.doc.lineAt(a).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(s=d.length,u>d.length)i.continueWidget(l-a);else{let f=c.widget||(c.block?si.block:si.inline),p=tA(c),m=this.cache.findWidget(f,l-a,p)||Fi.of(f,this.view,l-a,p);c.block?(c.startSide>0&&i.addLineStartIfNotCovered(n),i.addBlockWidget(m)):(i.ensureLine(n),i.addInlineWidget(m,d,u))}n=null}else n=rA(n,c);l>a&&this.text.skip(l-a)},span:(a,l,c,d)=>{for(let u=a;u<l;){let h=this.text.next(Math.min(512,l-u));h==null?(i.addLineStartIfNotCovered(n),i.addBreak(),u++):(i.ensureLine(n),i.addText(h,c,u==a?d:c.length),u+=h.length),n=null}}});i.addLineStartIfNotCovered(n),this.openWidget=o>s,this.openMarks=o}forward(e,t,n=1){t-e<=10?this.old.advance(t-e,n,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,n,this.reuseWalker))}getCompositionContext(e){let t=[],n=null;for(let i=e.parentNode;;i=i.parentNode){let s=Xe.get(i);if(i==this.view.contentDOM)break;s instanceof cr?t.push(s):s?.isLine()?n=s:s instanceof zn||(i.nodeName=="DIV"&&!n&&i!=this.view.contentDOM?n=new Os(i,Wb):n||t.push(cr.of(new Lo({tagName:i.nodeName.toLowerCase(),attributes:BE(i)}),i)))}return{line:n,marks:t}}};function z0(r,e){let t=n=>{for(let i of n.children)if((e?i.isText():i.length)||t(i))return!0;return!1};return t(r)}function tA(r){let e=r.isReplace?(r.startSide<0?64:0)|(r.endSide>0?128:0):r.startSide>0?32:16;return r.block&&(e|=256),e}var Wb={class:"cm-line"};function rA(r,e){let t=e.spec.attributes,n=e.spec.class;return!t&&!n||(r||(r={class:"cm-line"}),t&&yh(t,r),n&&(r.class+=" "+n)),r}function nA(r){let e=[];for(let t=r.parents.length;t>1;t--){let n=t==r.parents.length?r.tile:r.parents[t].tile;n instanceof cr&&e.push(n.mark)}return e}function gu(r){let e=Xe.get(r);return e&&e.setDOM(r.cloneNode()),r}var si=class extends er{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}};si.inline=new si("span");si.block=new si("div");var bu=new class extends er{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}},Ml=class{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=Z.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new Ds(e,e.contentDOM),this.updateInner([new nn(0,0,0,e.state.doc.length)],null)}update(e){var t;let n=e.changedRanges;this.minWidth>0&&n.length&&(n.every(({fromA:d,toA:u})=>u<this.minWidthFrom||d>this.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let i=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?i=this.domChanged.newSel.head:!uA(e.changes,this.hasComposition)&&!e.selectionSet&&(i=e.state.selection.main.head));let s=i>-1?sA(this.view,e.changes,i):null;if(this.domChanged=null,this.hasComposition){let{from:d,to:u}=this.hasComposition;n=new nn(d,u,e.changes.mapPos(d,-1),e.changes.mapPos(u,1)).addToSet(n.slice())}this.hasComposition=s?{from:s.range.fromB,to:s.range.toB}:null,(Y.ie||Y.chrome)&&!s&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,a=this.blockWrappers;this.updateDeco();let l=lA(o,this.decorations,e.changes);l.length&&(n=nn.extendWithRanges(n,l));let c=cA(a,this.blockWrappers,e.changes);return c.length&&(n=nn.extendWithRanges(n,c)),s&&!n.some(d=>d.fromA<=s.range.fromA&&d.toA>=s.range.toA)&&(n=s.range.addToSet(n.slice())),this.tile.flags&2&&n.length==0?!1:(this.updateInner(n,s),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:n}=this.view;n.ignore(()=>{if(t||e.length){let o=this.tile,a=new zu(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&Xe.get(t.text)&&a.cache.reused.set(Xe.get(t.text),2),this.tile=a.run(e,t),$u(o,a.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let s=Y.chrome||Y.ios?{node:n.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(s),s&&(s.written||n.selectionRange.focusNode!=s.node||!this.tile.dom.contains(s.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let i=[];if(this.view.viewport.from||this.view.viewport.to<this.view.state.doc.length)for(let s of this.tile.children)s.isWidget()&&s.widget instanceof Do&&i.push(s.dom);n.updateGaps(i)}updateEditContextFormatting(e){this.editContextFormatting=this.editContextFormatting.map(e.changes);for(let t of e.transactions)for(let n of t.effects)n.is(Fb)&&(this.editContextFormatting=n.value)}updateSelection(e=!1,t=!1){(e||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange();let{dom:n}=this.tile,i=this.view.root.activeElement,s=i==n,o=!s&&!(this.view.state.facet(_n)||n.tabIndex>-1)&&No(n,this.view.observer.selectionRange)&&!(i&&n.contains(i));if(!(s||t||o))return;let a=this.forceSelection;this.forceSelection=!1;let l=this.view.state.selection.main,c,d;if(l.empty?d=c=this.inlineDOMNearPos(l.anchor,l.assoc||1):(d=this.inlineDOMNearPos(l.head,l.head==l.from?1:-1),c=this.inlineDOMNearPos(l.anchor,l.anchor==l.from?1:-1)),Y.gecko&&l.empty&&!this.hasComposition&&iA(c)){let h=document.createTextNode("");this.view.observer.ignore(()=>c.node.insertBefore(h,c.node.childNodes[c.offset]||null)),c=d=new Sn(h,0),a=!0}let u=this.view.observer.selectionRange;(a||!u.focusNode||(!Ao(c.node,c.offset,u.anchorNode,u.anchorOffset)||!Ao(d.node,d.offset,u.focusNode,u.focusOffset))&&!this.suppressWidgetCursorChange(u,l))&&(this.view.observer.ignore(()=>{Y.android&&Y.chrome&&n.contains(u.focusNode)&&dA(u.focusNode,n)&&(n.blur(),n.focus({preventScroll:!0}));let h=Fo(this.view.root);if(h)if(l.empty){if(Y.gecko){let f=oA(c.node,c.offset);if(f&&f!=3){let p=(f==1?wb:Sb)(c.node,c.offset);p&&(c=new Sn(p.node,p.offset))}}h.collapse(c.node,c.offset),l.bidiLevel!=null&&h.caretBidiLevel!==void 0&&(h.caretBidiLevel=l.bidiLevel)}else if(h.extend){h.collapse(c.node,c.offset);try{h.extend(d.node,d.offset)}catch{}}else{let f=document.createRange();l.anchor>l.head&&([c,d]=[d,c]),f.setEnd(d.node,d.offset),f.setStart(c.node,c.offset),h.removeAllRanges(),h.addRange(f)}o&&this.view.root.activeElement==n&&(n.blur(),i&&i.focus())}),this.view.observer.setSelectionRange(c,d)),this.impreciseAnchor=c.precise?null:new Sn(u.anchorNode,u.anchorOffset),this.impreciseHead=d.precise?null:new Sn(u.focusNode,u.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&Ao(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,n=Fo(e.root),{anchorNode:i,anchorOffset:s}=e.observer.selectionRange;if(!n||!t.empty||!t.assoc||!n.modify)return;let o=this.lineAt(t.head,t.assoc);if(!o)return;let a=o.posAtStart;if(t.head==a||t.head==a+o.length)return;let l=this.coordsAt(t.head,-1),c=this.coordsAt(t.head,1);if(!l||!c||l.bottom>c.top)return;let d=this.domAtPos(t.head+t.assoc,t.assoc);n.collapse(d.node,d.offset),n.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let u=e.observer.selectionRange;e.docView.posFromDOM(u.anchorNode,u.anchorOffset)!=t.from&&n.collapse(i,s)}posFromDOM(e,t){let n=this.tile.nearest(e);if(!n)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let i=n.posAtStart;if(n.isComposite()){let s;if(e==n.dom)s=n.dom.childNodes[t];else{let o=$n(e)==0?0:t==0?-1:1;for(;;){let a=e.parentNode;if(a==n.dom)break;o==0&&a.firstChild!=a.lastChild&&(e==a.firstChild?o=-1:o=1),e=a}o<0?s=e:s=e.nextSibling}if(s==n.dom.firstChild)return i;for(;s&&!Xe.get(s);)s=s.nextSibling;if(!s)return i+n.length;for(let o=0,a=i;;o++){let l=n.children[o];if(l.dom==s)return a;a+=l.length+l.breakAfter}}else return n.isText()?e==n.dom?i+t:i+(t?n.length:0):i}domAtPos(e,t){let{tile:n,offset:i}=this.tile.resolveBlock(e,t);return n.isWidget()?n.domPosFor(e,t):n.domIn(i,t)}inlineDOMNearPos(e,t){let n,i=-1,s=!1,o,a=-1,l=!1;return this.tile.blockTiles((c,d)=>{if(c.isWidget()){if(c.flags&32&&d>=e)return!0;c.flags&16&&(s=!0)}else{let u=d+c.length;if(d<=e&&(n=c,i=e-d,s=u<e),u>=e&&!o&&(o=c,a=e-d,l=d>e),d>e&&o)return!0}}),!n&&!o?this.domAtPos(e,t):(s&&o?n=null:l&&n&&(o=null),n&&t<0||!o?n.domIn(i,t):o.domIn(a,t))}coordsAt(e,t){let{tile:n,offset:i}=this.tile.resolveBlock(e,t);return n.isWidget()?n.widget instanceof Do?null:n.coordsInWidget(i,t,!0):n.coordsIn(i,t)}lineAt(e,t){let{tile:n}=this.tile.resolveBlock(e,t);return n.isLine()?n:null}coordsForChar(e){let{tile:t,offset:n}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function i(s,o){if(s.isComposite())for(let a of s.children){if(a.length>=o){let l=i(a,o);if(l)return l}if(o-=a.length,o<0)break}else if(s.isText()&&o<s.length){let a=lt(s.text,o);if(a==o)return null;let l=zo(s.dom,o,a).getClientRects();for(let c=0;c<l.length;c++){let d=l[c];if(c==l.length-1||d.top<d.bottom&&d.left<d.right)return d}}return null}return i(t,n)}measureVisibleLineHeights(e){let t=[],{from:n,to:i}=e,s=this.view.contentDOM.clientWidth,o=s>Math.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,a=-1,l=this.view.textDirection==Be.LTR,c=0,d=(u,h,f)=>{for(let p=0;p<u.children.length&&!(h>i);p++){let m=u.children[p],g=h+m.length,b=m.dom.getBoundingClientRect(),{height:y}=b;if(f&&!p&&(c+=b.top-f.top),m instanceof zn)g>n&&d(m,h,b);else if(h>=n&&(c>0&&t.push(-c),t.push(y+c),c=0,o)){let x=m.dom.lastChild,N=x?Eo(x):[];if(N.length){let C=N[N.length-1],w=l?C.right-b.left:b.right-C.left;w>a&&(a=w,this.minWidth=s,this.minWidthFrom=h,this.minWidthTo=g)}}f&&p==u.children.length-1&&(c+=f.bottom-b.bottom),h=g+m.breakAfter}};return d(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?Be.RTL:Be.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let a=0,l;for(let c of o.children){if(!c.isText()||/[^ -~]/.test(c.text))return;let d=Eo(c.dom);if(d.length!=1)return;a+=d[0].width,l=d[0].height}if(a)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:a/o.length,textHeight:l}}});if(e)return e;let t=document.createElement("div"),n,i,s;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let o=Eo(t.firstChild)[0];n=t.getBoundingClientRect().height,i=o&&o.width?o.width/27:7,s=o&&o.height?o.height:n,t.remove()}),{lineHeight:n,charWidth:i,textHeight:s}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let n=0,i=0;;i++){let s=i==t.viewports.length?null:t.viewports[i],o=s?s.from-1:this.view.state.doc.length;if(o>n){let a=(t.lineBlockAt(o).bottom-t.lineBlockAt(n).top)/this.view.scaleY;e.push(Z.replace({widget:new Do(a),block:!0,inclusive:!0,isBlockGap:!0}).range(n,o))}if(!s)break;n=s.to+1}return Z.set(e)}updateDeco(){let e=1,t=this.view.state.facet(Wl).map(s=>(this.dynamicDecorationMap[e++]=typeof s=="function")?s(this.view):s),n=!1,i=this.view.state.facet(Eh).map((s,o)=>{let a=typeof s=="function";return a&&(n=!0),a?s(this.view):s});for(i.length&&(this.dynamicDecorationMap[e++]=n,t.push(Ne.join(i))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];e<this.decorations.length;)this.dynamicDecorationMap[e++]=!1;this.blockWrappers=this.view.state.facet(zb).map(s=>typeof s=="function"?s(this.view):s)}scrollIntoView(e){var t;if(e.isSnapshot){let d=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=d.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let d of this.view.state.facet(Bb))try{if(d(this.view,e.range,e))return!0}catch(u){It(this.view.state,u,"scroll handler")}let{range:n}=e,i=this.coordsAt(n.head,(t=n.assoc)!==null&&t!==void 0?t:n.empty?0:n.head>n.anchor?-1:1),s;if(!i)return;!n.empty&&(s=this.coordsAt(n.anchor,n.anchor>n.head?-1:1))&&(i={left:Math.min(i.left,s.left),top:Math.min(i.top,s.top),right:Math.max(i.right,s.right),bottom:Math.max(i.bottom,s.bottom)});let o=Ah(this.view),a={left:i.left-o.left,top:i.top-o.top,right:i.right+o.right,bottom:i.bottom+o.bottom},{offsetWidth:l,offsetHeight:c}=this.view.scrollDOM;if(zE(this.view.scrollDOM,a,n.head<n.anchor?-1:1,e.x,e.y,Math.max(Math.min(e.xMargin,l),-l),Math.max(Math.min(e.yMargin,c),-c),this.view.textDirection==Be.LTR),window.visualViewport&&window.innerHeight-window.visualViewport.height>1&&(i.top>window.pageYOffset+window.visualViewport.offsetTop+window.visualViewport.height||i.bottom<window.pageYOffset+window.visualViewport.offsetTop)){let d=this.view.docView.lineAt(n.head,1);d&&d.dom.scrollIntoView({block:"nearest"})}}lineHasWidget(e){let t=n=>n.isWidget()||n.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){$u(this.tile)}};function $u(r,e){let t=e?.get(r);if(t!=1){t==null&&r.destroy();for(let n of r.children)$u(n,e)}}function iA(r){return r.node.nodeType==1&&r.node.firstChild&&(r.offset==0||r.node.childNodes[r.offset-1].contentEditable=="false")&&(r.offset==r.node.childNodes.length||r.node.childNodes[r.offset].contentEditable=="false")}function Vb(r,e){let t=r.observer.selectionRange;if(!t.focusNode)return null;let n=wb(t.focusNode,t.focusOffset),i=Sb(t.focusNode,t.focusOffset),s=n||i;if(i&&n&&i.node!=n.node){let a=Xe.get(i.node);if(!a||a.isText()&&a.text!=i.node.nodeValue)s=i;else if(r.docView.lastCompositionAfterCursor){let l=Xe.get(n.node);!l||l.isText()&&l.text!=n.node.nodeValue||(s=i)}}if(r.docView.lastCompositionAfterCursor=s!=n,!s)return null;let o=e-s.offset;return{from:o,to:o+s.node.nodeValue.length,node:s.node}}function sA(r,e,t){let n=Vb(r,t);if(!n)return null;let{node:i,from:s,to:o}=n,a=i.nodeValue;if(/[\n\r]/.test(a)||r.state.doc.sliceString(n.from,n.to)!=a)return null;let l=e.invertedDesc;return{range:new nn(l.mapPos(s),l.mapPos(o),s,o),text:i}}function oA(r,e){return r.nodeType!=1?0:(e&&r.childNodes[e-1].contentEditable=="false"?1:0)|(e<r.childNodes.length&&r.childNodes[e].contentEditable=="false"?2:0)}var aA=class{constructor(){this.changes=[]}compareRange(e,t){As(e,t,this.changes)}comparePoint(e,t){As(e,t,this.changes)}boundChange(e){As(e,e,this.changes)}};function lA(r,e,t){let n=new aA;return Ne.compare(r,e,t,n),n.changes}var Hu=class{constructor(){this.changes=[]}compareRange(e,t){As(e,t,this.changes)}comparePoint(){}boundChange(e){As(e,e,this.changes)}};function cA(r,e,t){let n=new Hu;return Ne.compare(r,e,t,n),n.changes}function dA(r,e){for(let t=r;t&&t!=e;t=t.assignedSlot||t.parentNode)if(t.nodeType==1&&t.contentEditable=="false")return!0;return!1}function uA(r,e){let t=!1;return e&&r.iterChangedRanges((n,i)=>{n<e.to&&i>e.from&&(t=!0)}),t}var Do=class extends er{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}};function hA(r,e,t=1){let n=r.charCategorizer(e),i=r.doc.lineAt(e),s=e-i.from;if(i.length==0)return P.cursor(e);s==0?t=1:s==i.length&&(t=-1);let o=s,a=s;t<0?o=lt(i.text,s,!1):a=lt(i.text,s);let l=n(i.text.slice(o,a));for(;o>0;){let c=lt(i.text,o,!1);if(n(i.text.slice(c,o))!=l)break;o=c}for(;a<i.length;){let c=lt(i.text,a);if(n(i.text.slice(a,c))!=l)break;a=c}return P.range(o+i.from,a+i.from)}function fA(r,e,t,n,i){let s=Math.round((n-e.left)*r.defaultCharacterWidth);if(r.lineWrapping&&t.height>r.defaultLineHeight*1.5){let a=r.viewState.heightOracle.textHeight,l=Math.floor((i-t.top-(r.defaultLineHeight-a)*.5)/a);s+=l*r.viewState.heightOracle.lineLength}let o=r.state.sliceDoc(t.from,t.to);return t.from+cl(o,s,r.state.tabSize)}function Wu(r,e,t){let n=r.lineBlockAt(e);if(Array.isArray(n.type)){let i;for(let s of n.type){if(s.from>e)break;if(!(s.to<e)){if(s.from<e&&s.to>e)return s;(!i||s.type==Pt.Text&&(i.type!=s.type||(t<0?s.from<e:s.to>e)))&&(i=s)}}return i||n}return n}function pA(r,e,t,n){let i=Wu(r,e.head,e.assoc||-1),s=!n||i.type!=Pt.Text||!(r.lineWrapping||i.widgetLineBreaks)?null:r.coordsAtPos(e.assoc<0&&e.head>i.from?e.head-1:e.head);if(s){let o=r.dom.getBoundingClientRect(),a=r.textDirectionAt(i.from),l=r.posAtCoords({x:t==(a==Be.LTR)?o.right-1:o.left+1,y:(s.top+s.bottom)/2});if(l!=null)return P.cursor(l,t?-1:1)}return P.cursor(t?i.to:i.from,t?-1:1)}function $0(r,e,t,n){let i=r.state.doc.lineAt(e.head),s=r.bidiSpans(i),o=r.textDirectionAt(i.from);for(let a=e,l=null;;){let c=YE(i,s,o,a,t),d=Ab;if(!c){if(i.number==(t?r.state.doc.lines:1))return a;d=`
75
+ `,i=r.state.doc.line(i.number+(t?1:-1)),s=r.bidiSpans(i),c=r.visualLineSide(i,!t)}if(l){if(!l(d))return a}else{if(!n)return c;l=n(d)}a=c}}function mA(r,e,t){let n=r.state.charCategorizer(e),i=n(t);return s=>{let o=n(s);return i==$e.Space&&(i=o),i==o}}function gA(r,e,t,n){let i=e.head,s=t?1:-1;if(i==(t?r.state.doc.length:0))return P.cursor(i,e.assoc);let o=e.goalColumn,a,l=r.contentDOM.getBoundingClientRect(),c=r.coordsAtPos(i,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),d=r.documentTop;if(c)o==null&&(o=c.left-l.left),a=s<0?c.top:c.bottom;else{let p=r.viewState.lineBlockAt(i);o==null&&(o=Math.min(l.right-l.left,r.defaultCharacterWidth*(i-p.from))),a=(s<0?p.top:p.bottom)+d}let u=l.left+o,h=r.viewState.heightOracle.textHeight>>1,f=n??h;for(let p=0;;p+=h){let m=a+(f+p)*s,g=Vu(r,{x:u,y:m},!1,s);if(t?m>l.bottom:m<l.top)return P.cursor(g.pos,g.assoc);let b=r.coordsAtPos(g.pos,g.assoc),y=b?(b.top+b.bottom)/2:0;if(!b||(t?y>a:y<a))return P.cursor(g.pos,g.assoc,void 0,o)}}function Oo(r,e,t){for(;;){let n=0;for(let i of r)i.between(e-1,e+1,(s,o,a)=>{if(e>s&&e<o){let l=n||t||(e-s<o-e?-1:1);e=l<0?s:o,n=l}});if(!n)return e}}function jb(r,e){let t=null;for(let n=0;n<e.ranges.length;n++){let i=e.ranges[n],s=null;if(i.empty){let o=Oo(r,i.from,0);o!=i.from&&(s=P.cursor(o,-1))}else{let o=Oo(r,i.from,-1),a=Oo(r,i.to,1);(o!=i.from||a!=i.to)&&(s=P.range(i.from==i.anchor?o:a,i.from==i.head?o:a))}s&&(t||(t=e.ranges.slice()),t[n]=s)}return t?P.create(t,e.mainIndex):e}function xu(r,e,t){let n=Oo(r.state.facet($o).map(i=>i(r)),t.from,e.head>t.from?-1:1);return n==t.from?t:P.cursor(n,n<t.from?1:-1)}var zr=class{constructor(e,t){this.pos=e,this.assoc=t}};function Vu(r,e,t,n){let i=r.contentDOM.getBoundingClientRect(),s=i.top+r.viewState.paddingTop,{x:o,y:a}=e,l=a-s,c;for(;;){if(l<0)return new zr(0,1);if(l>r.viewState.docHeight)return new zr(r.state.doc.length,-1);if(c=r.elementAtHeight(l),n==null)break;if(c.type==Pt.Text){if(n<0?c.to<r.viewport.from:c.from>r.viewport.to)break;let h=r.docView.coordsAt(n<0?c.from:c.to,n>0?-1:1);if(h&&(n<0?h.top<=l+s:h.bottom>=l+s))break}let u=r.viewState.heightOracle.textHeight/2;l=n>0?c.bottom+u:c.top-u}if(r.viewport.from>=c.to||r.viewport.to<=c.from){if(t)return null;if(c.type==Pt.Text){let u=fA(r,i,c,o,a);return new zr(u,u==c.from?1:-1)}}if(c.type!=Pt.Text)return l<(c.top+c.bottom)/2?new zr(c.from,1):new zr(c.to,-1);let d=r.docView.lineAt(c.from,2);return(!d||d.length!=c.length)&&(d=r.docView.lineAt(c.from,-2)),new ju(r,o,a,r.textDirectionAt(c.from)).scanTile(d,c.from)}var ju=class{constructor(e,t,n,i){this.view=e,this.x=t,this.y=n,this.baseDir=i,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to<e)&&(this.line=this.view.state.doc.lineAt(e),this.spans=this.view.bidiSpans(this.line)),this}baseDirAt(e,t){let{line:n,spans:i}=this.bidiSpansAt(e);return i[$r.find(i,e-n.from,-1,t)].level==this.baseDir}dirAt(e,t){let{line:n,spans:i}=this.bidiSpansAt(e);return i[$r.find(i,e-n.from,-1,t)].dir}bidiIn(e,t){let{spans:n,line:i}=this.bidiSpansAt(e);return n.length>1||n.length&&(n[0].level!=this.baseDir||n[0].to+i.from<t)}scan(e,t){let n=0,i=e.length-1,s=new Set,o=this.bidiIn(e[0],e[i]),a,l,c=-1,d=1e9,u;e:for(;n<i;){let f=i-n,p=n+i>>1;t:if(s.has(p)){let g=n+Math.floor(Math.random()*f);for(let b=0;b<f;b++){if(!s.has(g)){p=g;break t}g++,g==i&&(g=n)}break e}s.add(p);let m=t(p);if(m)for(let g=0;g<m.length;g++){let b=m[g],y=0;if(!(b.width==0&&m.length>1)){if(b.bottom<this.y)(!a||a.bottom<b.bottom)&&(a=b),y=1;else if(b.top>this.y)(!l||l.top>b.top)&&(l=b),y=-1;else{let x=b.left>this.x?this.x-b.left:b.right<this.x?this.x-b.right:0,N=Math.abs(x);N<d&&(c=p,d=N,u=b),x&&(y=x<0==(this.baseDir==Be.LTR)?-1:1)}y==-1&&(!o||this.baseDirAt(e[p],1))?i=p:y==1&&(!o||this.baseDirAt(e[p+1],-1))&&(n=p+1)}}}if(!u){let f=a&&(!l||this.y-a.bottom<l.top-this.y)?a:l;return this.y=(f.top+f.bottom)/2,this.scan(e,t)}let h=(o?this.dirAt(e[c],1):this.baseDir)==Be.LTR;return{i:c,after:this.x>(u.left+u.right)/2==h}}scanText(e,t){let n=[];for(let s=0;s<e.length;s=lt(e.text,s))n.push(t+s);n.push(t+e.length);let i=this.scan(n,s=>{let o=n[s]-t,a=n[s+1]-t;return zo(e.dom,o,a).getClientRects()});return i.after?new zr(n[i.i+1],-1):new zr(n[i.i],1)}scanTile(e,t){if(!e.length)return new zr(t,1);if(e.children.length==1){let a=e.children[0];if(a.isText())return this.scanText(a,t);if(a.isComposite())return this.scanTile(a,t)}let n=[t];for(let a=0,l=t;a<e.children.length;a++)n.push(l+=e.children[a].length);let i=this.scan(n,a=>{let l=e.children[a];return l.flags&48?null:(l.dom.nodeType==1?l.dom:zo(l.dom,0,l.length)).getClientRects()}),s=e.children[i.i],o=n[i.i];return s.isText()?this.scanText(s,o):s.isComposite()?this.scanTile(s,o):i.after?new zr(n[i.i+1],-1):new zr(o,1)}},Ss="\uFFFF",Uu=class{constructor(e,t){this.points=e,this.view=t,this.text="",this.lineSeparator=t.state.facet(Me.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=Ss}readRange(e,t){if(!e)return this;let n=e.parentNode;for(let i=e;;){this.findPointBefore(n,i);let s=this.text.length;this.readNode(i);let o=Xe.get(i),a=i.nextSibling;if(a==t){o?.breakAfter&&!a&&n!=this.view.contentDOM&&this.lineBreak();break}let l=Xe.get(a);(o&&l?o.breakAfter:(o?o.breakAfter:El(i))||El(a)&&(i.nodeName!="BR"||o?.isWidget())&&this.text.length>s)&&!xA(a,t)&&this.lineBreak(),i=a}return this.findPointBefore(n,t),this}readTextNode(e){let t=e.nodeValue;for(let n of this.points)n.node==e&&(n.pos=this.text.length+Math.min(n.offset,t.length));for(let n=0,i=this.lineSeparator?null:/\r\n?|\n/g;;){let s=-1,o=1,a;if(this.lineSeparator?(s=t.indexOf(this.lineSeparator,n),o=this.lineSeparator.length):(a=i.exec(t))&&(s=a.index,o=a[0].length),this.append(t.slice(n,s<0?t.length:s)),s<0)break;if(this.lineBreak(),o>1)for(let l of this.points)l.node==e&&l.pos>this.text.length&&(l.pos-=o-1);n=s+o}}readNode(e){let t=Xe.get(e),n=t&&t.overrideDOMText;if(n!=null){this.findPointInside(e,n.length);for(let i=n.iter();!i.next().done;)i.lineBreak?this.lineBreak():this.append(i.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let n of this.points)n.node==e&&e.childNodes[n.offset]==t&&(n.pos=this.text.length)}findPointInside(e,t){for(let n of this.points)(e.nodeType==3?n.node==e:e.contains(n.node))&&(n.pos=this.text.length+(bA(e,n.node,n.offset)?t:0))}};function bA(r,e,t){for(;;){if(!e||t<$n(e))return!1;if(e==r)return!0;t=ii(e)+1,e=e.parentNode}}function xA(r,e){let t;for(;!(r==e||!r);r=r.nextSibling){let n=Xe.get(r);if(!n?.isWidget())return!1;n&&(t||(t=[])).push(n)}if(t)for(let n of t){let i=n.overrideDOMText;if(i?.length)return!1}return!0}var Dl=class{constructor(e,t){this.node=e,this.offset=t,this.pos=-1}},Gu=class{constructor(e,t,n,i){this.typeOver=i,this.bounds=null,this.text="",this.domChanged=t>-1;let{impreciseHead:s,impreciseAnchor:o}=e.docView,a=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=Ub(e.docView.tile,t,n,0))){let l=s||o?[]:yA(e),c=new Uu(l,e);c.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=c.text,this.newSel=wA(l,this.bounds.from)}else{let l=e.observer.selectionRange,c=s&&s.node==l.focusNode&&s.offset==l.focusOffset||!Tu(e.contentDOM,l.focusNode)?a.main.head:e.docView.posFromDOM(l.focusNode,l.focusOffset),d=o&&o.node==l.anchorNode&&o.offset==l.anchorOffset||!Tu(e.contentDOM,l.anchorNode)?a.main.anchor:e.docView.posFromDOM(l.anchorNode,l.anchorOffset),u=e.viewport;if((Y.ios||Y.chrome)&&a.main.empty&&c!=d&&(u.from>0||u.to<e.state.doc.length)){let h=Math.min(c,d),f=Math.max(c,d),p=u.from-h,m=u.to-f;(p==0||p==1||h==0)&&(m==0||m==-1||f==e.state.doc.length)&&(c=0,d=e.state.doc.length)}if(e.inputState.composing>-1&&a.ranges.length>1)this.newSel=a.replaceRange(P.range(d,c));else if(e.lineWrapping&&d==c&&!(a.main.empty&&a.main.head==c)&&e.inputState.lastTouchTime>Date.now()-100){let h=e.coordsAtPos(c,-1),f=0;h&&(f=e.inputState.lastTouchY<=h.bottom?-1:1),this.newSel=P.create([P.cursor(c,f)])}else this.newSel=P.single(d,c)}}};function Ub(r,e,t,n){if(r.isComposite()){let i=-1,s=-1,o=-1,a=-1;for(let l=0,c=n,d=n;l<r.children.length;l++){let u=r.children[l],h=c+u.length;if(c<e&&h>t)return Ub(u,e,t,c);if(h>=e&&i==-1&&(i=l,s=c),c>t&&u.dom.parentNode==r.dom){o=l,a=d;break}d=h,c=h+u.breakAfter}return{from:s,to:a<0?n+r.length:a,startDOM:(i?r.children[i-1].dom.nextSibling:null)||r.dom.firstChild,endDOM:o<r.children.length&&o>=0?r.children[o].dom:null}}else return r.isText()?{from:n,to:n+r.length,startDOM:r.dom,endDOM:r.dom.nextSibling}:null}function Gb(r,e){let t,{newSel:n}=e,{state:i}=r,s=i.selection.main,o=r.inputState.lastKeyTime>Date.now()-100?r.inputState.lastKeyCode:-1;if(e.bounds){let{from:a,to:l}=e.bounds,c=s.from,d=null;(o===8||Y.android&&e.text.length<l-a)&&(c=s.to,d="end");let u=i.doc.sliceString(a,l,Ss),h,f;!s.empty&&s.from>=a&&s.to<=l&&(e.typeOver||u!=e.text)&&u.slice(0,s.from-a)==e.text.slice(0,s.from-a)&&u.slice(s.to-a)==e.text.slice(h=e.text.length-(u.length-(s.to-a)))?t={from:s.from,to:s.to,insert:we.of(e.text.slice(s.from-a,h).split(Ss))}:(f=qb(u,e.text,c-a,d))&&(Y.chrome&&o==13&&f.toB==f.from+2&&e.text.slice(f.from,f.toB)==Ss+Ss&&f.toB--,t={from:a+f.from,to:a+f.toA,insert:we.of(e.text.slice(f.from,f.toB).split(Ss))})}else n&&(!r.hasFocus&&i.facet(_n)||Ol(n,s))&&(n=null);if(!t&&!n)return!1;if((Y.mac||Y.android)&&t&&t.from==t.to&&t.from==s.head-1&&/^\. ?$/.test(t.insert.toString())&&r.contentDOM.getAttribute("autocorrect")=="off"?(n&&t.insert.length==2&&(n=P.single(n.main.anchor-1,n.main.head-1)),t={from:t.from,to:t.to,insert:we.of([t.insert.toString().replace("."," ")])}):i.doc.lineAt(s.from).to<s.to&&r.docView.lineHasWidget(s.to)&&r.inputState.insertingTextAt>Date.now()-50?t={from:s.from,to:s.to,insert:i.toText(r.inputState.insertingText)}:Y.chrome&&t&&t.from==t.to&&t.from==s.head&&t.insert.toString()==`
76
+ `&&r.lineWrapping&&(n&&(n=P.single(n.main.anchor-1,n.main.head-1)),t={from:s.from,to:s.to,insert:we.of([" "])}),t)return Th(r,t,n,o);if(n&&!Ol(n,s)){let a=!1,l="select";return r.inputState.lastSelectionTime>Date.now()-50&&(r.inputState.lastSelectionOrigin=="select"&&(a=!0),l=r.inputState.lastSelectionOrigin,l=="select.pointer"&&(n=jb(i.facet($o).map(c=>c(r)),n))),r.dispatch({selection:n,scrollIntoView:a,userEvent:l}),!0}else return!1}function Th(r,e,t,n=-1){if(Y.ios&&r.inputState.flushIOSKey(e))return!0;let i=r.state.selection.main;if(Y.android&&(e.to==i.to&&(e.from==i.from||e.from==i.from-1&&r.state.sliceDoc(e.from,i.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&Ts(r.contentDOM,"Enter",13)||(e.from==i.from-1&&e.to==i.to&&e.insert.length==0||n==8&&e.insert.length<e.to-e.from&&e.to>i.head)&&Ts(r.contentDOM,"Backspace",8)||e.from==i.from&&e.to==i.to+1&&e.insert.length==0&&Ts(r.contentDOM,"Delete",46)))return!0;let s=e.insert.toString();r.inputState.composing>=0&&r.inputState.composing++;let o,a=()=>o||(o=vA(r,e,t));return r.state.facet(Rb).some(l=>l(r,e.from,e.to,s,a))||r.dispatch(a()),!0}function vA(r,e,t){let n,i=r.state,s=i.selection.main,o=-1;if(e.from==e.to&&e.from<s.from||e.from>s.to){let l=e.from<s.from?-1:1,c=l<0?s.from:s.to,d=Oo(i.facet($o).map(u=>u(r)),c,l);e.from==d&&(o=d)}if(o>-1)n={changes:e,selection:P.cursor(e.from+e.insert.length,-1)};else if(e.from>=s.from&&e.to<=s.to&&e.to-e.from>=(s.to-s.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&r.inputState.composing<0){let l=s.from<e.from?i.sliceDoc(s.from,e.from):"",c=s.to>e.to?i.sliceDoc(e.to,s.to):"";n=i.replaceSelection(r.state.toText(l+e.insert.sliceString(0,void 0,r.state.lineBreak)+c))}else{let l=i.changes(e),c=t&&t.main.to<=l.newLength?t.main:void 0;if(i.selection.ranges.length>1&&(r.inputState.composing>=0||r.inputState.compositionPendingChange)&&e.to<=s.to+10&&e.to>=s.to-10){let d=r.state.sliceDoc(e.from,e.to),u,h=t&&Vb(r,t.main.head);if(h){let p=e.insert.length-(e.to-e.from);u={from:h.from,to:h.to-p}}else u=r.state.doc.lineAt(s.head);let f=s.to-e.to;n=i.changeByRange(p=>{if(p.from==s.from&&p.to==s.to)return{changes:l,range:c||p.map(l)};let m=p.to-f,g=m-d.length;if(r.state.sliceDoc(g,m)!=d||m>=u.from&&g<=u.to)return{range:p};let b=i.changes({from:g,to:m,insert:e.insert}),y=p.to-s.to;return{changes:b,range:c?P.range(Math.max(0,c.anchor+y),Math.max(0,c.head+y)):p.map(b)}})}else n={changes:l,selection:c&&i.selection.replaceRange(c)}}let a="input.type";return(r.composing||r.inputState.compositionPendingChange&&r.inputState.compositionEndedAt>Date.now()-50)&&(r.inputState.compositionPendingChange=!1,a+=".compose",r.inputState.compositionFirstChange&&(a+=".start",r.inputState.compositionFirstChange=!1)),i.update(n,{userEvent:a,scrollIntoView:!0})}function qb(r,e,t,n){let i=Math.min(r.length,e.length),s=0;for(;s<i&&r.charCodeAt(s)==e.charCodeAt(s);)s++;if(s==i&&r.length==e.length)return null;let o=r.length,a=e.length;for(;o>0&&a>0&&r.charCodeAt(o-1)==e.charCodeAt(a-1);)o--,a--;if(n=="end"){let l=Math.max(0,s-Math.min(o,a));t-=o+l-s}if(o<s&&r.length<e.length){let l=t<=s&&t>=o?s-t:0;s-=l,a=s+(a-o),o=s}else if(a<s){let l=t<=s&&t>=a?s-t:0;s-=l,o=s+(o-a),a=s}return{from:s,toA:o,toB:a}}function yA(r){let e=[];if(r.root.activeElement!=r.contentDOM)return e;let{anchorNode:t,anchorOffset:n,focusNode:i,focusOffset:s}=r.observer.selectionRange;return t&&(e.push(new Dl(t,n)),(i!=t||s!=n)&&e.push(new Dl(i,s))),e}function wA(r,e){if(r.length==0)return null;let t=r[0].pos,n=r.length==2?r[1].pos:t;return t>-1&&n>-1?P.single(t+e,n+e):null}function Ol(r,e){return e.head==r.main.head&&e.anchor==r.main.anchor}var qu=class{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,Y.safari&&e.contentDOM.addEventListener("input",()=>null),Y.gecko&&LA(e.contentDOM.ownerDocument)}handleEvent(e){!TA(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let n=this.handlers[e];if(n){for(let i of n.observers)i(this.view,t);for(let i of n.handlers){if(t.defaultPrevented)break;if(i(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=SA(e),n=this.handlers,i=this.view.contentDOM;for(let s in t)if(s!="scroll"){let o=!t[s].handlers.length,a=n[s];a&&o!=!a.handlers.length&&(i.removeEventListener(s,this.handleEvent),a=null),a||i.addEventListener(s,this.handleEvent,{passive:o})}for(let s in n)s!="scroll"&&!t[s]&&i.removeEventListener(s,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&Yb.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),Y.android&&Y.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;let t;return Y.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&!e.shiftKey&&((t=Kb.find(n=>n.keyCode==e.keyCode))&&!e.ctrlKey||CA.indexOf(e.key)>-1&&e.ctrlKey)?(this.pendingIOSKey=t||e,setTimeout(()=>this.flushIOSKey(),250),!0):(e.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key=="Enter"&&e&&e.from<e.to&&/^\S+$/.test(e.insert.toString())?!1:(this.pendingIOSKey=void 0,Ts(this.view.contentDOM,t.key,t.keyCode,t instanceof KeyboardEvent?t:void 0))}ignoreDuringComposition(e){return!/^key/.test(e.type)||e.synthetic?!1:this.composing>0?!0:Y.safari&&!Y.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}};function H0(r,e){return(t,n)=>{try{return e.call(r,n,t)}catch(i){It(t.state,i)}}}function SA(r){let e=Object.create(null);function t(n){return e[n]||(e[n]={observers:[],handlers:[]})}for(let n of r){let i=n.spec,s=i&&i.plugin.domEventHandlers,o=i&&i.plugin.domEventObservers;if(s)for(let a in s){let l=s[a];l&&t(a).handlers.push(H0(n.value,l))}if(o)for(let a in o){let l=o[a];l&&t(a).observers.push(H0(n.value,l))}}for(let n in sn)t(n).handlers.push(sn[n]);for(let n in dr)t(n).observers.push(dr[n]);return e}var Kb=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],CA="dthko",Yb=[16,17,18,20,91,92,224,225],hl=6;function fl(r){return Math.max(0,r)*.7+8}function kA(r,e){return Math.max(Math.abs(r.clientX-e.clientX),Math.abs(r.clientY-e.clientY))}var Ku=class{constructor(e,t,n,i){this.view=e,this.startEvent=t,this.style=n,this.mustSelect=i,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=xb(e.contentDOM),this.atoms=e.state.facet($o).map(o=>o(e));let s=e.contentDOM.ownerDocument;s.addEventListener("mousemove",this.move=this.move.bind(this)),s.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(Me.allowMultipleSelections)&&NA(e,t),this.dragging=AA(e,t)&&Zb(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&kA(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,n=0,i=0,s=0,o=this.view.win.innerWidth,a=this.view.win.innerHeight;this.scrollParents.x&&({left:i,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:s,bottom:a}=this.scrollParents.y.getBoundingClientRect());let l=Ah(this.view);e.clientX-l.left<=i+hl?t=-fl(i-e.clientX):e.clientX+l.right>=o-hl&&(t=fl(e.clientX-o)),e.clientY-l.top<=s+hl?n=-fl(s-e.clientY):e.clientY+l.bottom>=a-hl&&(n=fl(e.clientY-a)),this.setScrollSpeed(t,n)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,n=jb(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!n.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:n,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}};function NA(r,e){let t=r.state.facet(Tb);return t.length?t[0](e):Y.mac?e.metaKey:e.ctrlKey}function EA(r,e){let t=r.state.facet(Mb);return t.length?t[0](e):Y.mac?!e.altKey:!e.ctrlKey}function AA(r,e){let{main:t}=r.state.selection;if(t.empty)return!1;let n=Fo(r.root);if(!n||n.rangeCount==0)return!0;let i=n.getRangeAt(0).getClientRects();for(let s=0;s<i.length;s++){let o=i[s];if(o.left<=e.clientX&&o.right>=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function TA(r,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,n;t!=r.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(n=Xe.get(t))&&n.isWidget()&&!n.isHidden&&n.widget.ignoreEvent(e))return!1;return!0}var sn=Object.create(null),dr=Object.create(null),Jb=Y.ie&&Y.ie_version<15||Y.ios&&Y.webkit_version<604;function MA(r){let e=r.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{r.focus(),t.remove(),Xb(r,t.value)},50)}function Vl(r,e,t){for(let n of r.facet(e))t=n(t,r);return t}function Xb(r,e){e=Vl(r.state,Ch,e);let{state:t}=r,n,i=1,s=t.toText(e),o=s.lines==t.selection.ranges.length;if(Yu!=null&&t.selection.ranges.every(l=>l.empty)&&Yu==s.toString()){let l=-1;n=t.changeByRange(c=>{let d=t.doc.lineAt(c.from);if(d.from==l)return{range:c};l=d.from;let u=t.toText((o?s.line(i++).text:e)+t.lineBreak);return{changes:{from:d.from,insert:u},range:P.cursor(c.from+u.length)}})}else o?n=t.changeByRange(l=>{let c=s.line(i++);return{changes:{from:l.from,to:l.to,insert:c.text},range:P.cursor(l.from+c.length)}}):n=t.replaceSelection(s);r.dispatch(n,{userEvent:"input.paste",scrollIntoView:!0})}dr.scroll=r=>{r.inputState.lastScrollTop=r.scrollDOM.scrollTop,r.inputState.lastScrollLeft=r.scrollDOM.scrollLeft};dr.wheel=dr.mousewheel=r=>{r.inputState.lastWheelEvent=Date.now()};sn.keydown=(r,e)=>(r.inputState.setSelectionOrigin("select"),e.keyCode==27&&r.inputState.tabFocusMode!=0&&(r.inputState.tabFocusMode=Date.now()+2e3),!1);dr.touchstart=(r,e)=>{let t=r.inputState,n=e.targetTouches[0];t.lastTouchTime=Date.now(),n&&(t.lastTouchX=n.clientX,t.lastTouchY=n.clientY),t.setSelectionOrigin("select.pointer")};dr.touchmove=r=>{r.inputState.setSelectionOrigin("select.pointer")};sn.mousedown=(r,e)=>{if(r.observer.flush(),r.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let n of r.state.facet(Db))if(t=n(r,e),t)break;if(!t&&e.button==0&&(t=OA(r,e)),t){let n=!r.hasFocus;r.inputState.startMouseSelection(new Ku(r,e,t,n)),n&&r.observer.ignore(()=>{vb(r.contentDOM);let s=r.root.activeElement;s&&!s.contains(r.contentDOM)&&s.blur()});let i=r.inputState.mouseSelection;if(i)return i.start(e),i.dragging===!1}else r.inputState.setSelectionOrigin("select.pointer");return!1};function W0(r,e,t,n){if(n==1)return P.cursor(e,t);if(n==2)return hA(r.state,e,t);{let i=r.docView.lineAt(e,t),s=r.state.doc.lineAt(i?i.posAtEnd:e),o=i?i.posAtStart:s.from,a=i?i.posAtEnd:s.to;return a<r.state.doc.length&&a==s.to&&a++,P.range(o,a)}}var DA=Y.ie&&Y.ie_version<=11,V0=null,j0=0,U0=0;function Zb(r){if(!DA)return r.detail;let e=V0,t=U0;return V0=r,U0=Date.now(),j0=!e||t>Date.now()-400&&Math.abs(e.clientX-r.clientX)<2&&Math.abs(e.clientY-r.clientY)<2?(j0+1)%3:1}function OA(r,e){let t=r.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),n=Zb(e),i=r.state.selection;return{update(s){s.docChanged&&(t.pos=s.changes.mapPos(t.pos),i=i.map(s.changes))},get(s,o,a){let l=r.posAndSideAtCoords({x:s.clientX,y:s.clientY},!1),c,d=W0(r,l.pos,l.assoc,n);if(t.pos!=l.pos&&!o){let u=W0(r,t.pos,t.assoc,n),h=Math.min(u.from,d.from),f=Math.max(u.to,d.to);d=h<d.from?P.range(h,f,d.assoc):P.range(f,h,d.assoc)}return o?i.replaceRange(i.main.extend(d.from,d.to,d.assoc)):a&&n==1&&i.ranges.length>1&&(c=RA(i,l.pos))?c:a?i.addRange(d):P.create([d])}}}function RA(r,e){for(let t=0;t<r.ranges.length;t++){let{from:n,to:i}=r.ranges[t];if(n<=e&&i>=e)return P.create(r.ranges.slice(0,t).concat(r.ranges.slice(t+1)),r.mainIndex==t?0:r.mainIndex-(r.mainIndex>t?1:0))}return null}sn.dragstart=(r,e)=>{let{selection:{main:t}}=r.state;if(e.target.draggable){let i=r.docView.tile.nearest(e.target);if(i&&i.isWidget()){let s=i.posAtStart,o=s+i.length;(s>=t.to||o<=t.from)&&(t=P.range(s,o))}}let{inputState:n}=r;return n.mouseSelection&&(n.mouseSelection.dragging=!0),n.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",Vl(r.state,kh,r.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};sn.dragend=r=>(r.inputState.draggedContent=null,!1);function G0(r,e,t,n){if(t=Vl(r.state,Ch,t),!t)return;let i=r.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:s}=r.inputState,o=n&&s&&EA(r,e)?{from:s.from,to:s.to}:null,a={from:i,insert:t},l=r.state.changes(o?[o,a]:a);r.focus(),r.dispatch({changes:l,selection:{anchor:l.mapPos(i,-1),head:l.mapPos(i,1)},userEvent:o?"move.drop":"input.drop"}),r.inputState.draggedContent=null}sn.drop=(r,e)=>{if(!e.dataTransfer)return!1;if(r.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let n=Array(t.length),i=0,s=()=>{++i==t.length&&G0(r,e,n.filter(o=>o!=null).join(r.state.lineBreak),!1)};for(let o=0;o<t.length;o++){let a=new FileReader;a.onerror=s,a.onload=()=>{/[\x00-\x08\x0e-\x1f]{2}/.test(a.result)||(n[o]=a.result),s()},a.readAsText(t[o])}return!0}else{let n=e.dataTransfer.getData("Text");if(n)return G0(r,e,n,!0),!0}return!1};sn.paste=(r,e)=>{if(r.state.readOnly)return!0;r.observer.flush();let t=Jb?null:e.clipboardData;return t?(Xb(r,t.getData("text/plain")||t.getData("text/uri-list")),!0):(MA(r),!1)};function IA(r,e){let t=r.dom.parentNode;if(!t)return;let n=t.appendChild(document.createElement("textarea"));n.style.cssText="position: fixed; left: -10000px; top: 10px",n.value=e,n.focus(),n.selectionEnd=e.length,n.selectionStart=0,setTimeout(()=>{n.remove(),r.focus()},50)}function PA(r){let e=[],t=[],n=!1;for(let i of r.selection.ranges)i.empty||(e.push(r.sliceDoc(i.from,i.to)),t.push(i));if(!e.length){let i=-1;for(let{from:s}of r.selection.ranges){let o=r.doc.lineAt(s);o.number>i&&(e.push(o.text),t.push({from:o.from,to:Math.min(r.doc.length,o.to+1)})),i=o.number}n=!0}return{text:Vl(r,kh,e.join(r.lineBreak)),ranges:t,linewise:n}}var Yu=null;sn.copy=sn.cut=(r,e)=>{if(!No(r.contentDOM,r.observer.selectionRange))return!1;let{text:t,ranges:n,linewise:i}=PA(r.state);if(!t&&!i)return!1;Yu=i?t:null,e.type=="cut"&&!r.state.readOnly&&r.dispatch({changes:n,scrollIntoView:!0,userEvent:"delete.cut"});let s=Jb?null:e.clipboardData;return s?(s.clearData(),s.setData("text/plain",t),!0):(IA(r,t),!1)};var Qb=jt.define();function ex(r,e){let t=[];for(let n of r.facet(Ib)){let i=n(r,e);i&&t.push(i)}return t.length?r.update({effects:t,annotations:Qb.of(!0)}):null}function tx(r){setTimeout(()=>{let e=r.hasFocus;if(e!=r.inputState.notifiedFocused){let t=ex(r.state,e);t?r.dispatch(t):r.update([])}},10)}dr.focus=r=>{r.inputState.lastFocusTime=Date.now(),!r.scrollDOM.scrollTop&&(r.inputState.lastScrollTop||r.inputState.lastScrollLeft)&&(r.scrollDOM.scrollTop=r.inputState.lastScrollTop,r.scrollDOM.scrollLeft=r.inputState.lastScrollLeft),tx(r)};dr.blur=r=>{r.observer.clearSelectionRange(),tx(r)};dr.compositionstart=dr.compositionupdate=r=>{r.observer.editContext||(r.inputState.compositionFirstChange==null&&(r.inputState.compositionFirstChange=!0),r.inputState.composing<0&&(r.inputState.composing=0))};dr.compositionend=r=>{r.observer.editContext||(r.inputState.composing=-1,r.inputState.compositionEndedAt=Date.now(),r.inputState.compositionPendingKey=!0,r.inputState.compositionPendingChange=r.observer.pendingRecords().length>0,r.inputState.compositionFirstChange=null,Y.chrome&&Y.android?r.observer.flushSoon():r.inputState.compositionPendingChange?Promise.resolve().then(()=>r.observer.flush()):setTimeout(()=>{r.inputState.composing<0&&r.docView.hasComposition&&r.update([])},50))};dr.contextmenu=r=>{r.inputState.lastContextMenu=Date.now()};sn.beforeinput=(r,e)=>{var t,n;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(r.inputState.insertingText=e.data,r.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&r.observer.editContext){let s=(t=e.dataTransfer)===null||t===void 0?void 0:t.getData("text/plain"),o=e.getTargetRanges();if(s&&o.length){let a=o[0],l=r.posAtDOM(a.startContainer,a.startOffset),c=r.posAtDOM(a.endContainer,a.endOffset);return Th(r,{from:l,to:c,insert:r.state.toText(s)},null),!0}}let i;if(Y.chrome&&Y.android&&(i=Kb.find(s=>s.inputType==e.inputType))&&(r.observer.delayAndroidKey(i.key,i.keyCode),i.key=="Backspace"||i.key=="Delete")){let s=((n=window.visualViewport)===null||n===void 0?void 0:n.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>s+10&&r.hasFocus&&(r.contentDOM.blur(),r.focus())},100)}return Y.ios&&e.inputType=="deleteContentForward"&&r.observer.flushSoon(),Y.safari&&e.inputType=="insertText"&&r.inputState.composing>=0&&setTimeout(()=>dr.compositionend(r,e),20),!1};var q0=new Set;function LA(r){q0.has(r)||(q0.add(r),r.addEventListener("copy",()=>{}),r.addEventListener("cut",()=>{}))}var K0=["pre-wrap","normal","pre-line","break-spaces"],Is=!1;function Y0(){Is=!1}var Ju=class{constructor(e){this.lineWrapping=e,this.doc=we.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let n=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(n+=Math.max(0,Math.ceil((t-e-n*this.lineLength*.5)/this.lineLength))),this.lineHeight*n}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return K0.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let n=0;n<e.length;n++){let i=e[n];i<0?n++:this.heightSamples[Math.floor(i*10)]||(t=!0,this.heightSamples[Math.floor(i*10)]=!0)}return t}refresh(e,t,n,i,s,o){let a=K0.indexOf(e)>-1,l=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=a||Math.abs(n-this.charWidth)>.1;if(this.lineWrapping=a,this.lineHeight=t,this.charWidth=n,this.textHeight=i,this.lineLength=s,l){this.heightSamples={};for(let c=0;c<o.length;c++){let d=o[c];d<0?c++:this.heightSamples[Math.floor(d*10)]=!0}}return l}},Xu=class{constructor(e,t){this.from=e,this.heights=t,this.index=0}get more(){return this.index<this.heights.length}},rn=class r{constructor(e,t,n,i,s){this.from=e,this.length=t,this.top=n,this.height=i,this._content=s}get type(){return typeof this._content=="number"?Pt.Text:Array.isArray(this._content)?this._content:this._content.type}get to(){return this.from+this.length}get bottom(){return this.top+this.height}get widget(){return this._content instanceof Li?this._content.widget:null}get widgetLineBreaks(){return typeof this._content=="number"?this._content:0}join(e){let t=(Array.isArray(this._content)?this._content:[this]).concat(Array.isArray(e._content)?e._content:[e]);return new r(this.from,this.length+e.length,this.top,this.height+e.height,t)}},Ge=(function(r){return r[r.ByPos=0]="ByPos",r[r.ByHeight=1]="ByHeight",r[r.ByPosNoHeight=2]="ByPosNoHeight",r})(Ge||(Ge={})),yl=.001,yr=class r{constructor(e,t,n=2){this.length=e,this.height=t,this.flags=n}get outdated(){return(this.flags&2)>0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>yl&&(Is=!0),this.height=e)}replace(e,t,n){return r.of(n)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,n,i){let s=this,o=n.doc;for(let a=i.length-1;a>=0;a--){let{fromA:l,toA:c,fromB:d,toB:u}=i[a],h=s.lineAt(l,Ge.ByPosNoHeight,n.setDoc(t),0,0),f=h.to>=c?h:s.lineAt(c,Ge.ByPosNoHeight,n,0,0);for(u+=f.to-c,c=f.to;a>0&&h.from<=i[a-1].toA;)l=i[a-1].fromA,d=i[a-1].fromB,a--,l<h.from&&(h=s.lineAt(l,Ge.ByPosNoHeight,n,0,0));d+=h.from-l,l=h.from;let p=Qu.build(n.setDoc(o),e,d,u);s=Rl(s,s.replace(l,c,p))}return s.updateHeight(n,0)}static empty(){return new _r(0,0,0)}static of(e){if(e.length==1)return e[0];let t=0,n=e.length,i=0,s=0;for(;;)if(t==n)if(i>s*2){let a=e[t-1];a.break?e.splice(--t,1,a.left,null,a.right):e.splice(--t,1,a.left,a.right),n+=1+a.break,i-=a.size}else if(s>i*2){let a=e[n];a.break?e.splice(n,1,a.left,null,a.right):e.splice(n,1,a.left,a.right),n+=2+a.break,s-=a.size}else break;else if(i<s){let a=e[t++];a&&(i+=a.size)}else{let a=e[--n];a&&(s+=a.size)}let o=0;return e[t-1]==null?(o=1,t--):e[t]==null&&(o=1,n++),new Zu(r.of(e.slice(0,t)),o,r.of(e.slice(n)))}};function Rl(r,e){return r==e?r:(r.constructor!=e.constructor&&(Is=!0),e)}yr.prototype.size=1;var BA=Z.replace({}),Il=class extends yr{constructor(e,t,n){super(e,t),this.deco=n,this.spaceAbove=0}mainBlock(e,t){return new rn(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.deco||0)}blockAt(e,t,n,i){return this.spaceAbove&&e<n+this.spaceAbove?new rn(i,0,n,this.spaceAbove,BA):this.mainBlock(n,i)}lineAt(e,t,n,i,s){let o=this.mainBlock(i,s);return this.spaceAbove?this.blockAt(0,n,i,s).join(o):o}forEachLine(e,t,n,i,s,o){e<=s+this.length&&t>=s&&o(this.lineAt(0,Ge.ByPos,n,i,s))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,n=!1,i){return i&&i.from<=t&&i.more&&this.setMeasuredHeight(i),this.outdated=!1,this}toString(){return`block(${this.length})`}},_r=class r extends Il{constructor(e,t,n){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=n}mainBlock(e,t){return new rn(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,t,n){let i=n[0];return n.length==1&&(i instanceof r||i instanceof ni&&i.flags&4)&&Math.abs(this.length-i.length)<10?(i instanceof ni?i=new r(i.length,this.height,this.spaceAbove):i.height=this.height,this.outdated||(i.outdated=!1),i):yr.of(n)}updateHeight(e,t=0,n=!1,i){return i&&i.from<=t&&i.more?this.setMeasuredHeight(i):(n||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}},ni=class r extends yr{constructor(e){super(e,0)}heightMetrics(e,t){let n=e.doc.lineAt(t).number,i=e.doc.lineAt(t+this.length).number,s=i-n+1,o,a=0;if(e.lineWrapping){let l=Math.min(this.height,e.lineHeight*s);o=l/s,this.length>s+1&&(a=(this.height-l)/(this.length-s-1))}else o=this.height/s;return{firstLine:n,lastLine:i,perLine:o,perChar:a}}blockAt(e,t,n,i){let{firstLine:s,lastLine:o,perLine:a,perChar:l}=this.heightMetrics(t,i);if(t.lineWrapping){let c=i+(e<t.lineHeight?0:Math.round(Math.max(0,Math.min(1,(e-n)/this.height))*this.length)),d=t.doc.lineAt(c),u=a+d.length*l,h=Math.max(n,e-u/2);return new rn(d.from,d.length,h,u,0)}else{let c=Math.max(0,Math.min(o-s,Math.floor((e-n)/a))),{from:d,length:u}=t.doc.line(s+c);return new rn(d,u,n+a*c,a,0)}}lineAt(e,t,n,i,s){if(t==Ge.ByHeight)return this.blockAt(e,n,i,s);if(t==Ge.ByPosNoHeight){let{from:f,to:p}=n.doc.lineAt(e);return new rn(f,p-f,0,0,0)}let{firstLine:o,perLine:a,perChar:l}=this.heightMetrics(n,s),c=n.doc.lineAt(e),d=a+c.length*l,u=c.number-o,h=i+a*u+l*(c.from-s-u);return new rn(c.from,c.length,Math.max(i,Math.min(h,i+this.height-d)),d,0)}forEachLine(e,t,n,i,s,o){e=Math.max(e,s),t=Math.min(t,s+this.length);let{firstLine:a,perLine:l,perChar:c}=this.heightMetrics(n,s);for(let d=e,u=i;d<=t;){let h=n.doc.lineAt(d);if(d==e){let p=h.number-a;u+=l*p+c*(e-s-p)}let f=l+c*h.length;o(new rn(h.from,h.length,u,f,0)),u+=f,d=h.to+1}}replace(e,t,n){let i=this.length-t;if(i>0){let s=n[n.length-1];s instanceof r?n[n.length-1]=new r(s.length+i):n.push(null,new r(i-1))}if(e>0){let s=n[0];s instanceof r?n[0]=new r(e+s.length):n.unshift(new r(e-1),null)}return yr.of(n)}decomposeLeft(e,t){t.push(new r(e-1),null)}decomposeRight(e,t){t.push(null,new r(this.length-e-1))}updateHeight(e,t=0,n=!1,i){let s=t+this.length;if(i&&i.from<=t+this.length&&i.more){let o=[],a=Math.max(t,i.from),l=-1;for(i.from>t&&o.push(new r(i.from-t-1).updateHeight(e,t));a<=s&&i.more;){let d=e.doc.lineAt(a).length;o.length&&o.push(null);let u=i.heights[i.index++],h=0;u<0&&(h=-u,u=i.heights[i.index++]),l==-1?l=u:Math.abs(u-l)>=yl&&(l=-2);let f=new _r(d,u,h);f.outdated=!1,o.push(f),a+=d+1}a<=s&&o.push(null,new r(s-a).updateHeight(e,a));let c=yr.of(o);return(l<0||Math.abs(c.height-this.height)>=yl||Math.abs(l-this.heightMetrics(e,t).perLine)>=yl)&&(Is=!0),Rl(this,c)}else(n||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}},Zu=class extends yr{constructor(e,t,n){super(e.length+t+n.length,e.height+n.height,t|(e.outdated||n.outdated?2:0)),this.left=e,this.right=n,this.size=e.size+n.size}get break(){return this.flags&1}blockAt(e,t,n,i){let s=n+this.left.height;return e<s?this.left.blockAt(e,t,n,i):this.right.blockAt(e,t,s,i+this.left.length+this.break)}lineAt(e,t,n,i,s){let o=i+this.left.height,a=s+this.left.length+this.break,l=t==Ge.ByHeight?e<o:e<a,c=l?this.left.lineAt(e,t,n,i,s):this.right.lineAt(e,t,n,o,a);if(this.break||(l?c.to<a:c.from>a))return c;let d=t==Ge.ByPosNoHeight?Ge.ByPosNoHeight:Ge.ByPos;return l?c.join(this.right.lineAt(a,d,n,o,a)):this.left.lineAt(a,d,n,i,s).join(c)}forEachLine(e,t,n,i,s,o){let a=i+this.left.height,l=s+this.left.length+this.break;if(this.break)e<l&&this.left.forEachLine(e,t,n,i,s,o),t>=l&&this.right.forEachLine(e,t,n,a,l,o);else{let c=this.lineAt(l,Ge.ByPos,n,i,s);e<c.from&&this.left.forEachLine(e,c.from-1,n,i,s,o),c.to>=e&&c.from<=t&&o(c),t>c.to&&this.right.forEachLine(c.to+1,t,n,a,l,o)}}replace(e,t,n){let i=this.left.length+this.break;if(t<i)return this.balanced(this.left.replace(e,t,n),this.right);if(e>this.left.length)return this.balanced(this.left,this.right.replace(e-i,t-i,n));let s=[];e>0&&this.decomposeLeft(e,s);let o=s.length;for(let a of n)s.push(a);if(e>0&&J0(s,o-1),t<this.length){let a=s.length;this.decomposeRight(t,s),J0(s,a)}return yr.of(s)}decomposeLeft(e,t){let n=this.left.length;if(e<=n)return this.left.decomposeLeft(e,t);t.push(this.left),this.break&&(n++,e>=n&&t.push(null)),e>n&&this.right.decomposeLeft(e-n,t)}decomposeRight(e,t){let n=this.left.length,i=n+this.break;if(e>=i)return this.right.decomposeRight(e-i,t);e<n&&this.left.decomposeRight(e,t),this.break&&e<i&&t.push(null),t.push(this.right)}balanced(e,t){return e.size>2*t.size||t.size>2*e.size?yr.of(this.break?[e,null,t]:[e,t]):(this.left=Rl(this.left,e),this.right=Rl(this.right,t),this.setHeight(e.height+t.height),this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,n=!1,i){let{left:s,right:o}=this,a=t+s.length+this.break,l=null;return i&&i.from<=t+s.length&&i.more?l=s=s.updateHeight(e,t,n,i):s.updateHeight(e,t,n),i&&i.from<=a+o.length&&i.more?l=o=o.updateHeight(e,a,n,i):o.updateHeight(e,a,n),l?this.balanced(s,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}};function J0(r,e){let t,n;r[e]==null&&(t=r[e-1])instanceof ni&&(n=r[e+1])instanceof ni&&r.splice(e-1,3,new ni(t.length+1+n.length))}var FA=5,Qu=class r{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let n=Math.min(t,this.lineEnd),i=this.nodes[this.nodes.length-1];i instanceof _r?i.length+=n-this.pos:(n>this.pos||!this.isCovered)&&this.nodes.push(new _r(n-this.pos,-1,0)),this.writtenTo=n,t>n&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,n){if(e<t||n.heightRelevant){let i=n.widget?n.widget.estimatedHeight:0,s=n.widget?n.widget.lineBreaks:0;i<0&&(i=this.oracle.lineHeight);let o=t-e;n.block?this.addBlock(new Il(o,i,n)):(o||s||i>=FA)&&this.addLineDeco(i,s,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd<this.pos&&(this.lineEnd=this.oracle.doc.lineAt(this.pos).to)}enterLine(){if(this.lineStart>-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenTo<e&&((this.writtenTo<e-1||this.nodes[this.nodes.length-1]==null)&&this.nodes.push(this.blankContent(this.writtenTo,e-1)),this.nodes.push(null)),this.pos>e&&this.nodes.push(new _r(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let n=new ni(t-e);return this.oracle.doc.lineAt(e).to==t&&(n.flags|=4),n}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof _r)return e;let t=new _r(0,-1,0);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,n){let i=this.ensureLine();i.length+=n,i.collapsed+=n,i.widgetHeight=Math.max(i.widgetHeight,e),i.breaks+=t,this.writtenTo=this.pos=this.pos+n}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof _r)&&!this.isCovered?this.nodes.push(new _r(0,-1,0)):(this.writtenTo<this.pos||t==null)&&this.nodes.push(this.blankContent(this.writtenTo,this.pos));let n=e;for(let i of this.nodes)i instanceof _r&&i.updateHeight(this.oracle,n),n+=i?i.length:1;return this.nodes}static build(e,t,n,i){let s=new r(n,e);return Ne.spans(t,n,i,s,0),s.finish(n)}};function _A(r,e,t){let n=new eh;return Ne.compare(r,e,t,n,0),n.changes}var eh=class{constructor(){this.changes=[]}compareRange(){}comparePoint(e,t,n,i){(e<t||n&&n.heightRelevant||i&&i.heightRelevant)&&As(e,t,this.changes,5)}};function zA(r,e){let t=r.getBoundingClientRect(),n=r.ownerDocument,i=n.defaultView||window,s=Math.max(0,t.left),o=Math.min(i.innerWidth,t.right),a=Math.max(0,t.top),l=Math.min(i.innerHeight,t.bottom);for(let c=r.parentNode;c&&c!=n.body;)if(c.nodeType==1){let d=c,u=window.getComputedStyle(d);if((d.scrollHeight>d.clientHeight||d.scrollWidth>d.clientWidth)&&u.overflow!="visible"){let h=d.getBoundingClientRect();s=Math.max(s,h.left),o=Math.min(o,h.right),a=Math.max(a,h.top),l=Math.min(c==r.parentNode?i.innerHeight:l,h.bottom)}c=u.position=="absolute"||u.position=="fixed"?d.offsetParent:d.parentNode}else if(c.nodeType==11)c=c.host;else break;return{left:s-t.left,right:Math.max(s,o)-t.left,top:a-(t.top+e),bottom:Math.max(a,l)-(t.top+e)}}function $A(r){let e=r.getBoundingClientRect(),t=r.ownerDocument.defaultView||window;return e.left<t.innerWidth&&e.right>0&&e.top<t.innerHeight&&e.bottom>0}function HA(r,e){let t=r.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}var Ro=class{constructor(e,t,n,i){this.from=e,this.to=t,this.size=n,this.displaySize=i}static same(e,t){if(e.length!=t.length)return!1;for(let n=0;n<e.length;n++){let i=e[n],s=t[n];if(i.from!=s.from||i.to!=s.to||i.size!=s.size)return!1}return!0}draw(e,t){return Z.replace({widget:new th(this.displaySize*(t?e.scaleY:e.scaleX),t)}).range(this.from,this.to)}},th=class extends er{constructor(e,t){super(),this.size=e,this.vertical=t}eq(e){return e.size==this.size&&e.vertical==this.vertical}toDOM(){let e=document.createElement("div");return this.vertical?e.style.height=this.size+"px":(e.style.width=this.size+"px",e.style.height="2px",e.style.display="inline-block"),e}get estimatedHeight(){return this.vertical?this.size:-1}},Pl=class{constructor(e,t){this.view=e,this.state=t,this.pixelViewport={left:0,right:window.innerWidth,top:0,bottom:0},this.inView=!0,this.paddingTop=0,this.paddingBottom=0,this.contentDOMWidth=0,this.contentDOMHeight=0,this.editorHeight=0,this.editorWidth=0,this.scaleX=1,this.scaleY=1,this.scrollOffset=0,this.scrolledToBottom=!1,this.scrollAnchorPos=0,this.scrollAnchorHeight=-1,this.scaler=X0,this.scrollTarget=null,this.printing=!1,this.mustMeasureContent=!0,this.defaultTextDirection=Be.LTR,this.visibleRanges=[],this.mustEnforceCursorAssoc=!1;let n=t.facet(Nh).some(i=>typeof i!="function"&&i.class=="cm-lineWrapping");this.heightOracle=new Ju(n),this.stateDeco=Z0(t),this.heightMap=yr.empty().applyChanges(this.stateDeco,we.empty,this.heightOracle.setDoc(t.doc),[new nn(0,0,0,t.doc.length)]);for(let i=0;i<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());i++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=Z.set(this.lineGaps.map(i=>i.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let n=0;n<=1;n++){let i=n?t.head:t.anchor;if(!e.some(({from:s,to:o})=>i>=s&&i<=o)){let{from:s,to:o}=this.lineBlockAt(i);e.push(new ks(s,o))}}return this.viewports=e.sort((n,i)=>n.from-i.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?X0:new rh(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(Co(e,this.scaler))})}update(e,t=null){this.state=e.state;let n=this.stateDeco;this.stateDeco=Z0(this.state);let i=e.changedRanges,s=nn.extendWithRanges(i,_A(n,this.stateDeco,e?e.changes:Zt.empty(this.state.doc.length))),o=this.heightMap.height,a=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);Y0(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),s),(this.heightMap.height!=o||Is)&&(e.flags|=2),a?(this.scrollAnchorPos=e.changes.mapPos(a.from,-1),this.scrollAnchorHeight=a.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let l=s.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.head<l.from||t.range.head>l.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,t));let c=l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,e.flags|=this.updateForViewport(),(c||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(Lb)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,n=window.getComputedStyle(t),i=this.heightOracle,s=n.whiteSpace;this.defaultTextDirection=n.direction=="rtl"?Be.RTL:Be.LTR;let o=this.heightOracle.mustRefreshForWrapping(s)||this.mustMeasureContent==="refresh",a=t.getBoundingClientRect(),l=o||this.mustMeasureContent||this.contentDOMHeight!=a.height;this.contentDOMHeight=a.height,this.mustMeasureContent=!1;let c=0,d=0;if(a.width&&a.height){let{scaleX:C,scaleY:w}=bb(t,a);(C>.005&&Math.abs(this.scaleX-C)>.005||w>.005&&Math.abs(this.scaleY-w)>.005)&&(this.scaleX=C,this.scaleY=w,c|=16,o=l=!0)}let u=(parseInt(n.paddingTop)||0)*this.scaleY,h=(parseInt(n.paddingBottom)||0)*this.scaleY;(this.paddingTop!=u||this.paddingBottom!=h)&&(this.paddingTop=u,this.paddingBottom=h,c|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(i.lineWrapping&&(l=!0),this.editorWidth=e.scrollDOM.clientWidth,c|=16);let f=xb(this.view.contentDOM,!1).y;f!=this.scrollParent&&(this.scrollParent=f,this.scrollAnchorHeight=-1,this.scrollOffset=0);let p=this.getScrollOffset();this.scrollOffset!=p&&(this.scrollAnchorHeight=-1,this.scrollOffset=p),this.scrolledToBottom=yb(this.scrollParent||e.win);let m=(this.printing?HA:zA)(t,this.paddingTop),g=m.top-this.pixelViewport.top,b=m.bottom-this.pixelViewport.bottom;this.pixelViewport=m;let y=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(y!=this.inView&&(this.inView=y,y&&(l=!0)),!this.inView&&!this.scrollTarget&&!$A(e.dom))return 0;let x=a.width;if((this.contentDOMWidth!=x||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=a.width,this.editorHeight=e.scrollDOM.clientHeight,c|=16),l){let C=e.docView.measureVisibleLineHeights(this.viewport);if(i.mustRefreshForHeights(C)&&(o=!0),o||i.lineWrapping&&Math.abs(x-this.contentDOMWidth)>i.charWidth){let{lineHeight:w,charWidth:k,textHeight:A}=e.docView.measureTextSize();o=w>0&&i.refresh(s,w,k,A,Math.max(5,x/k),C),o&&(e.docView.minWidth=0,c|=16)}g>0&&b>0?d=Math.max(g,b):g<0&&b<0&&(d=Math.min(g,b)),Y0();for(let w of this.viewports){let k=w.from==this.viewport.from?C:e.docView.measureVisibleLineHeights(w);this.heightMap=(o?yr.empty().applyChanges(this.stateDeco,we.empty,this.heightOracle,[new nn(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(i,0,o,new Xu(w.from,k))}Is&&(c|=2)}let N=!this.viewportIsAppropriate(this.viewport,d)||this.scrollTarget&&(this.scrollTarget.range.head<this.viewport.from||this.scrollTarget.range.head>this.viewport.to);return N&&(c&2&&(c|=this.updateScaler()),this.viewport=this.getViewport(d,this.scrollTarget),c|=this.updateForViewport()),(c&2||N)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),c|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),c}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let n=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),i=this.heightMap,s=this.heightOracle,{visibleTop:o,visibleBottom:a}=this,l=new ks(i.lineAt(o-n*1e3,Ge.ByHeight,s,0,0).from,i.lineAt(a+(1-n)*1e3,Ge.ByHeight,s,0,0).to);if(t){let{head:c}=t.range;if(c<l.from||c>l.to){let d=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),u=i.lineAt(c,Ge.ByPos,s,0,0),h;t.y=="center"?h=(u.top+u.bottom)/2-d/2:t.y=="start"||t.y=="nearest"&&c<l.from?h=u.top:h=u.bottom-d,l=new ks(i.lineAt(h-1e3/2,Ge.ByHeight,s,0,0).from,i.lineAt(h+d+1e3/2,Ge.ByHeight,s,0,0).to)}}return l}mapViewport(e,t){let n=t.mapPos(e.from,-1),i=t.mapPos(e.to,1);return new ks(this.heightMap.lineAt(n,Ge.ByPos,this.heightOracle,0,0).from,this.heightMap.lineAt(i,Ge.ByPos,this.heightOracle,0,0).to)}viewportIsAppropriate({from:e,to:t},n=0){if(!this.inView)return!0;let{top:i}=this.heightMap.lineAt(e,Ge.ByPos,this.heightOracle,0,0),{bottom:s}=this.heightMap.lineAt(t,Ge.ByPos,this.heightOracle,0,0),{visibleTop:o,visibleBottom:a}=this;return(e==0||i<=o-Math.max(10,Math.min(-n,250)))&&(t==this.state.doc.length||s>=a+Math.max(10,Math.min(n,250)))&&i>o-2*1e3&&s<a+2*1e3}mapLineGaps(e,t){if(!e.length||t.empty)return e;let n=[];for(let i of e)t.touchesRange(i.from,i.to)||n.push(new Ro(t.mapPos(i.from),t.mapPos(i.to),i.size,i.displaySize));return n}ensureLineGaps(e,t){let n=this.heightOracle.lineWrapping,i=n?1e4:2e3,s=i>>1,o=i<<1;if(this.defaultTextDirection!=Be.LTR&&!n)return[];let a=[],l=(d,u,h,f)=>{if(u-d<s)return;let p=this.state.selection.main,m=[p.from];p.empty||m.push(p.to);for(let b of m)if(b>d&&b<u){l(d,b-10,h,f),l(b+10,u,h,f);return}let g=VA(e,b=>b.from>=h.from&&b.to<=h.to&&Math.abs(b.from-d)<s&&Math.abs(b.to-u)<s&&!m.some(y=>b.from<y&&b.to>y));if(!g){if(u<h.to&&t&&n&&t.visibleRanges.some(x=>x.from<=u&&x.to>=u)){let x=t.moveToLineBoundary(P.cursor(u),!1,!0).head;x>d&&(u=x)}let b=this.gapSize(h,d,u,f),y=n||b<2e6?b:2e6;g=new Ro(d,u,b,y)}a.push(g)},c=d=>{if(d.length<o||d.type!=Pt.Text)return;let u=WA(d.from,d.to,this.stateDeco);if(u.total<o)return;let h=this.scrollTarget?this.scrollTarget.range.head:null,f,p;if(n){let m=i/this.heightOracle.lineLength*this.heightOracle.lineHeight,g,b;if(h!=null){let y=ml(u,h),x=((this.visibleBottom-this.visibleTop)/2+m)/d.height;g=y-x,b=y+x}else g=(this.visibleTop-d.top-m)/d.height,b=(this.visibleBottom-d.top+m)/d.height;f=pl(u,g),p=pl(u,b)}else{let m=u.total*this.heightOracle.charWidth,g=i*this.heightOracle.charWidth,b=0;if(m>2e6)for(let w of e)w.from>=d.from&&w.from<d.to&&w.size!=w.displaySize&&w.from*this.heightOracle.charWidth+b<this.pixelViewport.left&&(b=w.size-w.displaySize);let y=this.pixelViewport.left+b,x=this.pixelViewport.right+b,N,C;if(h!=null){let w=ml(u,h),k=((x-y)/2+g)/m;N=w-k,C=w+k}else N=(y-g)/m,C=(x+g)/m;f=pl(u,N),p=pl(u,C)}f>d.from&&l(d.from,f,d,u),p<d.to&&l(p,d.to,d,u)};for(let d of this.viewportLines)Array.isArray(d.type)?d.type.forEach(c):c(d);return a}gapSize(e,t,n,i){let s=ml(i,n)-ml(i,t);return this.heightOracle.lineWrapping?e.height*s:i.total*this.heightOracle.charWidth*s}updateLineGaps(e){Ro.same(e,this.lineGaps)||(this.lineGaps=e,this.lineGapDeco=Z.set(e.map(t=>t.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let n=[];Ne.spans(t,this.viewport.from,this.viewport.to,{span(s,o){n.push({from:s,to:o})},point(){}},20);let i=0;if(n.length!=this.visibleRanges.length)i=12;else for(let s=0;s<n.length&&!(i&8);s++){let o=this.visibleRanges[s],a=n[s];(o.from!=a.from||o.to!=a.to)&&(i|=4,e&&e.mapPos(o.from,-1)==a.from&&e.mapPos(o.to,1)==a.to||(i|=8))}return this.visibleRanges=n,i}lineBlockAt(e){return e>=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||Co(this.heightMap.lineAt(e,Ge.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||Co(this.heightMap.lineAt(this.scaler.fromDOM(e),Ge.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return(this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top)*this.scaleY}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return Co(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}},ks=class{constructor(e,t){this.from=e,this.to=t}};function WA(r,e,t){let n=[],i=r,s=0;return Ne.spans(t,r,e,{span(){},point(o,a){o>i&&(n.push({from:i,to:o}),s+=o-i),i=a}},20),i<e&&(n.push({from:i,to:e}),s+=e-i),{total:s,ranges:n}}function pl({total:r,ranges:e},t){if(t<=0)return e[0].from;if(t>=1)return e[e.length-1].to;let n=Math.floor(r*t);for(let i=0;;i++){let{from:s,to:o}=e[i],a=o-s;if(n<=a)return s+n;n-=a}}function ml(r,e){let t=0;for(let{from:n,to:i}of r.ranges){if(e<=i){t+=e-n;break}t+=i-n}return t/r.total}function VA(r,e){for(let t of r)if(e(t))return t}var X0={toDOM(r){return r},fromDOM(r){return r},scale:1,eq(r){return r==this}};function Z0(r){let e=r.facet(Wl).filter(n=>typeof n!="function"),t=r.facet(Eh).filter(n=>typeof n!="function");return t.length&&e.push(Ne.join(t)),e}var rh=class r{constructor(e,t,n){let i=0,s=0,o=0;this.viewports=n.map(({from:a,to:l})=>{let c=t.lineAt(a,Ge.ByPos,e,0,0).top,d=t.lineAt(l,Ge.ByPos,e,0,0).bottom;return i+=d-c,{from:a,to:l,top:c,bottom:d,domTop:0,domBottom:0}}),this.scale=(7e6-i)/(t.height-i);for(let a of this.viewports)a.domTop=o+(a.top-s)*this.scale,o=a.domBottom=a.domTop+(a.bottom-a.top),s=a.bottom}toDOM(e){for(let t=0,n=0,i=0;;t++){let s=t<this.viewports.length?this.viewports[t]:null;if(!s||e<s.top)return i+(e-n)*this.scale;if(e<=s.bottom)return s.domTop+(e-s.top);n=s.bottom,i=s.domBottom}}fromDOM(e){for(let t=0,n=0,i=0;;t++){let s=t<this.viewports.length?this.viewports[t]:null;if(!s||e<s.domTop)return n+(e-i)/this.scale;if(e<=s.domBottom)return s.top+(e-s.domTop);n=s.bottom,i=s.domBottom}}eq(e){return e instanceof r?this.scale==e.scale&&this.viewports.length==e.viewports.length&&this.viewports.every((t,n)=>t.from==e.viewports[n].from&&t.to==e.viewports[n].to):!1}};function Co(r,e){if(e.scale==1)return r;let t=e.toDOM(r.top),n=e.toDOM(r.bottom);return new rn(r.from,r.length,t,n-t,Array.isArray(r._content)?r._content.map(i=>Co(i,e)):r._content)}var gl=K.define({combine:r=>r.join(" ")}),nh=K.define({combine:r=>r.indexOf(!0)>-1}),ih=Fr.newName(),rx=Fr.newName(),nx=Fr.newName(),ix={"&light":"."+rx,"&dark":"."+nx};function sh(r,e,t){return new Fr(e,{finish(n){return/&/.test(n)?n.replace(/&\w*/,i=>{if(i=="&")return r;if(!t||!t[i])throw new RangeError(`Unsupported selector: ${i}`);return t[i]}):r+" "+n}})}var jA=sh("."+ih,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{backgroundImage:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",backgroundPosition:"center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},ix),UA={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},vu=Y.ie&&Y.ie_version<=11,oh=class{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new Mu,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let n of t)this.queue.push(n);(Y.ie&&Y.ie_version<=11||Y.ios&&e.composing)&&t.some(n=>n.type=="childList"&&n.removedNodes.length||n.type=="characterData"&&n.oldValue.length>n.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&Y.android&&e.constructor.EDIT_CONTEXT!==!1&&!(Y.chrome&&Y.chrome_version<126)&&(this.editContext=new ah(e),e.state.facet(_n)&&(e.contentDOM.editContext=this.editContext.editContext)),vu&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate)<Date.now()-75&&this.onResize()}),this.resizeScroll.observe(e.scrollDOM)),this.addWindowListeners(this.win=e.win),this.start(),typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(t=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,n)=>t!=e[n]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:n}=this,i=this.selectionRange;if(n.state.facet(_n)?n.root.activeElement!=this.dom:!No(this.dom,i))return;let s=i.anchorNode&&n.docView.tile.nearest(i.anchorNode);if(s&&s.isWidget()&&s.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(Y.ie&&Y.ie_version<=11||Y.android&&Y.chrome)&&!n.state.selection.main.empty&&i.focusNode&&Ao(i.focusNode,i.focusOffset,i.anchorNode,i.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=Fo(e.root);if(!t)return!1;let n=Y.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&GA(this.view,t)||t;if(!n||this.selectionRange.eq(n))return!1;let i=No(this.dom,n);return i&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime<Date.now()-300&&HE(this.dom,n)?(this.view.inputState.lastFocusTime=0,e.docView.updateSelection(),!1):(this.selectionRange.setRange(n),i&&(this.selectionChanged=!0),!0)}setSelectionRange(e,t){this.selectionRange.set(e.node,e.offset,t.node,t.offset),this.selectionChanged=!1}clearSelectionRange(){this.selectionRange.set(null,0,null,0)}listenForScroll(){this.parentCheck=-1;let e=0,t=null;for(let n=this.dom;n;)if(n.nodeType==1)!t&&e<this.scrollTargets.length&&this.scrollTargets[e]==n?e++:t||(t=this.scrollTargets.slice(0,e)),t&&t.push(n),n=n.assignedSlot||n.parentNode;else if(n.nodeType==11)n=n.host;else break;if(e<this.scrollTargets.length&&!t&&(t=this.scrollTargets.slice(0,e)),t){for(let n of this.scrollTargets)n.removeEventListener("scroll",this.onScroll);for(let n of this.scrollTargets=t)n.addEventListener("scroll",this.onScroll)}}ignore(e){if(!this.active)return e();try{return this.stop(),e()}finally{this.start(),this.clear()}}start(){this.active||(this.observer.observe(this.dom,UA),vu&&this.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.active=!0)}stop(){this.active&&(this.active=!1,this.observer.disconnect(),vu&&this.dom.removeEventListener("DOMCharacterDataModified",this.onCharData))}clear(){this.processRecords(),this.queue.length=0,this.selectionChanged=!1}delayAndroidKey(e,t){var n;if(!this.delayedAndroidKey){let i=()=>{let s=this.delayedAndroidKey;s&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=s.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&s.force&&Ts(this.dom,s.key,s.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(i)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange<Date.now()-50||!!(!((n=this.delayedAndroidKey)===null||n===void 0)&&n.force)})}clearDelayedAndroidKey(){this.win.cancelAnimationFrame(this.flushingAndroidKey),this.delayedAndroidKey=null,this.flushingAndroidKey=-1}flushSoon(){this.delayedFlush<0&&(this.delayedFlush=this.view.win.requestAnimationFrame(()=>{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,n=-1,i=!1;for(let s of e){let o=this.readMutation(s);o&&(o.typeOver&&(i=!0),t==-1?{from:t,to:n}=o:(t=Math.min(o.from,t),n=Math.max(o.to,n)))}return{from:t,to:n,typeOver:i}}readChange(){let{from:e,to:t,typeOver:n}=this.processRecords(),i=this.selectionChanged&&No(this.dom,this.selectionRange);if(e<0&&!i)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let s=new Gu(this.view,e,t,n);return this.view.docView.domChanged={newSel:s.newSel?s.newSel.main:null},s}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let n=this.view.state,i=Gb(this.view,t);return this.view.state==n&&(t.domChanged||t.newSel&&!Ol(this.view.state.selection,t.newSel.main))&&this.view.update([]),i}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let n=Q0(t,e.previousSibling||e.target.previousSibling,-1),i=Q0(t,e.nextSibling||e.target.nextSibling,1);return{from:n?t.posAfter(n):t.posAtStart,to:i?t.posBefore(i):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(_n)!=e.state.facet(_n)&&(e.view.contentDOM.editContext=e.state.facet(_n)?this.editContext.editContext:null))}destroy(){var e,t,n;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(n=this.resizeScroll)===null||n===void 0||n.disconnect();for(let i of this.scrollTargets)i.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}};function Q0(r,e,t){for(;e;){let n=Xe.get(e);if(n&&n.parent==r)return n;let i=e.parentNode;e=i!=r.dom?i:t>0?e.nextSibling:e.previousSibling}return null}function eb(r,e){let t=e.startContainer,n=e.startOffset,i=e.endContainer,s=e.endOffset,o=r.docView.domAtPos(r.state.selection.main.anchor,1);return Ao(o.node,o.offset,i,s)&&([t,n,i,s]=[i,s,t,n]),{anchorNode:t,anchorOffset:n,focusNode:i,focusOffset:s}}function GA(r,e){if(e.getComposedRanges){let i=e.getComposedRanges(r.root)[0];if(i)return eb(r,i)}let t=null;function n(i){i.preventDefault(),i.stopImmediatePropagation(),t=i.getTargetRanges()[0]}return r.contentDOM.addEventListener("beforeinput",n,!0),r.dom.ownerDocument.execCommand("indent"),r.contentDOM.removeEventListener("beforeinput",n,!0),t?eb(r,t):null}var ah=class{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=n=>{let i=e.state.selection.main,{anchor:s,head:o}=i,a=this.toEditorPos(n.updateRangeStart),l=this.toEditorPos(n.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:n.updateRangeStart,editorBase:a,drifted:!1});let c=l-a>n.text.length;a==this.from&&s<this.from?a=s:l==this.to&&s>this.to&&(l=s);let d=qb(e.state.sliceDoc(a,l),n.text,(c?i.from:i.to)-a,c?"end":null);if(!d){let h=P.single(this.toEditorPos(n.selectionStart),this.toEditorPos(n.selectionEnd));Ol(h,i)||e.dispatch({selection:h,userEvent:"select"});return}let u={from:d.from+a,to:d.toA+a,insert:we.of(n.text.slice(d.from,d.toB).split(`
77
+ `))};if((Y.mac||Y.android)&&u.from==o-1&&/^\. ?$/.test(n.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(u={from:a,to:l,insert:we.of([n.text.replace("."," ")])}),this.pendingContextChange=u,!e.state.readOnly){let h=this.to-this.from+(u.to-u.from+u.insert.length);Th(e,u,P.single(this.toEditorPos(n.selectionStart,h),this.toEditorPos(n.selectionEnd,h)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),u.from<u.to&&!u.insert.length&&e.inputState.composing>=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,n.updateRangeStart-1),Math.min(t.text.length,n.updateRangeStart+1)))&&this.handlers.compositionend(n)},this.handlers.characterboundsupdate=n=>{let i=[],s=null;for(let o=this.toEditorPos(n.rangeStart),a=this.toEditorPos(n.rangeEnd);o<a;o++){let l=e.coordsForChar(o);s=l&&new DOMRect(l.left,l.top,l.right-l.left,l.bottom-l.top)||s||new DOMRect,i.push(s)}t.updateCharacterBounds(n.rangeStart,i)},this.handlers.textformatupdate=n=>{let i=[];for(let s of n.getTextFormats()){let o=s.underlineStyle,a=s.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(a)){let l=this.toEditorPos(s.rangeStart),c=this.toEditorPos(s.rangeEnd);if(l<c){let d=`text-decoration: underline ${/^[a-z]/.test(o)?o+" ":o=="Dashed"?"dashed ":o=="Squiggle"?"wavy ":""}${/thin/i.test(a)?1:2}px`;i.push(Z.mark({attributes:{style:d}}).range(l,c))}}}e.dispatch({effects:Fb.of(Z.set(i))})},this.handlers.compositionstart=()=>{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:n}=this.composing;this.composing=null,n&&this.reset(e.state)}};for(let n in this.handlers)t.addEventListener(n,this.handlers[n]);this.measureReq={read:n=>{this.editContext.updateControlBounds(n.contentDOM.getBoundingClientRect());let i=Fo(n.root);i&&i.rangeCount&&this.editContext.updateSelectionBounds(i.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,n=!1,i=this.pendingContextChange;return e.changes.iterChanges((s,o,a,l,c)=>{if(n)return;let d=c.length-(o-s);if(i&&o>=i.to)if(i.from==s&&i.to==o&&i.insert.eq(c)){i=this.pendingContextChange=null,t+=d,this.to+=d;return}else i=null,this.revertPending(e.state);if(s+=t,o+=t,o<=this.from)this.from+=d,this.to+=d;else if(s<this.to){if(s<this.from||o>this.to||this.to-this.from+c.length>3e4){n=!0;return}this.editContext.updateText(this.toContextPos(s),this.toContextPos(o),c.toString()),this.to+=d}t+=d}),i&&!n&&this.revertPending(e.state),!n}update(e){let t=this.pendingContextChange,n=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(n.from,n.to)&&e.transactions.some(i=>!i.isUserEvent("input.type")&&i.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,n=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),i=this.toContextPos(t.head);(this.editContext.selectionStart!=n||this.editContext.selectionEnd!=i)&&this.editContext.updateSelection(n,i)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to<e.doc.length&&this.to-t<500||this.to-this.from>1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let n=this.composing;return n&&n.drifted?n.editorBase+(e-n.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}},U=class r{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:n}=e;this.dispatchTransactions=e.dispatchTransactions||n&&(i=>i.forEach(s=>n(s,this)))||(i=>this.update(i)),this.dispatch=this.dispatch.bind(this),this._root=e.root||$E(e.parent)||document,this.viewState=new Pl(this,e.state||Me.create(e)),e.scrollTo&&e.scrollTo.is(ul)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Cs).map(i=>new Mo(i));for(let i of this.plugins)i.update(this);this.observer=new oh(this),this.inputState=new qu(this),this.inputState.ensureHandlers(this.plugins),this.docView=new Ml(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((t=document.fonts)===null||t===void 0)&&t.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof mt?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,n=!1,i,s=this.state;for(let h of e){if(h.startState!=s)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");s=h.state}if(this.destroyed){this.viewState.state=s;return}let o=this.hasFocus,a=0,l=null;e.some(h=>h.annotation(Qb))?(this.inputState.notifiedFocused=o,a=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,l=ex(s,o),l||(a=1));let c=this.observer.delayedAndroidKey,d=null;if(c?(this.observer.clearDelayedAndroidKey(),d=this.observer.readChange(),(d&&!this.state.doc.eq(s.doc)||!this.state.selection.eq(s.selection))&&(d=null)):this.observer.clear(),s.facet(Me.phrases)!=this.state.facet(Me.phrases))return this.setState(s);i=Al.create(this,s,e),i.flags|=a;let u=this.viewState.scrollTarget;try{this.updateState=2;for(let h of e){if(u&&(u=u.map(h.changes)),h.scrollIntoView){let{main:f}=h.state.selection;u=new To(f.empty?f:P.cursor(f.head,f.head>f.anchor?-1:1))}for(let f of h.effects)f.is(ul)&&(u=f.value.clip(this.state))}this.viewState.update(i,u),this.bidiCache=Ll.update(this.bidiCache,i.changes),i.empty||(this.updatePlugins(i),this.inputState.update(i)),t=this.docView.update(i),this.state.facet(So)!=this.styleModules&&this.mountStyles(),n=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(h=>h.isUserEvent("select.pointer")))}finally{this.updateState=0}if(i.startState.facet(gl)!=i.state.facet(gl)&&(this.viewState.mustMeasureContent=!0),(t||n||u||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!i.empty)for(let h of this.state.facet(Iu))try{h(i)}catch(f){It(this.state,f,"update listener")}(l||d)&&Promise.resolve().then(()=>{l&&this.state==l.startState&&this.dispatch(l),d&&!Gb(this,d)&&c.force&&Ts(this.contentDOM,c.key,c.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let n of this.plugins)n.destroy(this);this.viewState=new Pl(this,e),this.plugins=e.facet(Cs).map(n=>new Mo(n)),this.pluginMap.clear();for(let n of this.plugins)n.update(this);this.docView.destroy(),this.docView=new Ml(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(Cs),n=e.state.facet(Cs);if(t!=n){let i=[];for(let s of n){let o=t.indexOf(s);if(o<0)i.push(new Mo(s));else{let a=this.plugins[o];a.mustUpdate=e,i.push(a)}}for(let s of this.plugins)s.mustUpdate!=e&&s.destroy(this);this.plugins=i,this.pluginMap.clear()}else for(let i of this.plugins)i.mustUpdate=e;for(let i=0;i<this.plugins.length;i++)this.plugins[i].update(this);t!=n&&this.inputState.ensureHandlers(this.plugins)}docViewUpdate(){for(let e of this.plugins){let t=e.value;if(t&&t.docViewUpdate)try{t.docViewUpdate(this)}catch(n){It(this.state,n,"doc view update listener")}}}measure(e=!0){if(this.destroyed)return;if(this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,n=this.viewState.scrollParent,i=this.viewState.getScrollOffset(),{scrollAnchorPos:s,scrollAnchorHeight:o}=this.viewState;Math.abs(i-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let a=0;;a++){if(o<0)if(yb(n||this.win))s=-1,o=this.viewState.heightMap.height;else{let f=this.viewState.scrollAnchorAt(i);s=f.from,o=f.top}this.updateState=1;let l=this.viewState.measure();if(!l&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(a>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let c=[];l&4||([this.measureRequests,c]=[c,this.measureRequests]);let d=c.map(f=>{try{return f.read(this)}catch(p){return It(this.state,p),tb}}),u=Al.create(this,this.state,[]),h=!1;u.flags|=l,t?t.flags|=l:t=u,this.updateState=2,u.empty||(this.updatePlugins(u),this.inputState.update(u),this.updateAttrs(),h=this.docView.update(u),h&&this.docViewUpdate());for(let f=0;f<c.length;f++)if(d[f]!=tb)try{let p=c[f];p.write&&p.write(d[f],this)}catch(p){It(this.state,p)}if(h&&this.docView.updateSelection(!0),!u.viewportChanged&&this.measureRequests.length==0){if(this.viewState.editorHeight)if(this.viewState.scrollTarget){this.docView.scrollIntoView(this.viewState.scrollTarget),this.viewState.scrollTarget=null,o=-1;continue}else{let p=((s<0?this.viewState.heightMap.height:this.viewState.lineBlockAt(s).top)-o)/this.scaleY;if((p>1||p<-1)&&(n==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){i=i+p,n?n.scrollTop+=p:this.win.scrollBy(0,p),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let a of this.state.facet(Iu))a(t)}get themeClasses(){return ih+" "+(this.state.facet(nh)?nx:rx)+" "+this.state.facet(gl)}updateAttrs(){let e=rb(this,_b,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(_n)?"true":"false",class:"cm-content",style:`${Y.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),rb(this,Nh,t);let n=this.observer.ignore(()=>{let i=P0(this.contentDOM,this.contentAttrs,t),s=P0(this.dom,this.editorAttrs,e);return i||s});return this.editorAttrs=e,this.contentAttrs=t,n}showAnnouncements(e){let t=!0;for(let n of e)for(let i of n.effects)if(i.is(r.announce)){t&&(this.announceDOM.textContent=""),t=!1;let s=this.announceDOM.appendChild(document.createElement("div"));s.textContent=i.value}}mountStyles(){this.styleModules=this.state.facet(So);let e=this.state.facet(r.cspNonce);Fr.mount(this.root,this.styleModules.concat(jA).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;t<this.measureRequests.length;t++)if(this.measureRequests[t].key===e.key){this.measureRequests[t]=e;return}}this.measureRequests.push(e)}}plugin(e){let t=this.pluginMap.get(e);return(t===void 0||t&&t.plugin!=e)&&this.pluginMap.set(e,t=this.plugins.find(n=>n.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,n){return xu(this,e,$0(this,e,t,n))}moveByGroup(e,t){return xu(this,e,$0(this,e,t,n=>mA(this,e.head,n)))}visualLineSide(e,t){let n=this.bidiSpans(e),i=this.textDirectionAt(e.from),s=n[t?n.length-1:0];return P.cursor(s.side(t,i)+e.from,s.forward(!t,i)?1:-1)}moveToLineBoundary(e,t,n=!0){return pA(this,e,t,n)}moveVertically(e,t,n){return xu(this,e,gA(this,e,t,n))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let n=Vu(this,e,t);return n&&n.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),Vu(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let n=this.docView.coordsAt(e,t);if(!n||n.left==n.right)return n;let i=this.state.doc.lineAt(e),s=this.bidiSpans(i),o=s[$r.find(s,e-i.from,-1,t)];return _o(n,o.dir==Be.LTR==t>0)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(Pb)||e<this.viewport.from||e>this.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>qA)return Eb(e.length);let t=this.textDirectionAt(e.from),n;for(let s of this.bidiCache)if(s.from==e.from&&s.dir==t&&(s.fresh||Nb(s.isolates,n=F0(this,e))))return s.order;n||(n=F0(this,e));let i=KE(e.text,t,n);return this.bidiCache.push(new Ll(e.from,e.to,t,n,!0,i)),i}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||Y.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{vb(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){return ul.of(new To(typeof e=="number"?P.cursor(e):e,t.y,t.x,t.yMargin,t.xMargin))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,n=this.viewState.scrollAnchorAt(e);return ul.of(new To(P.cursor(n.from),"start","start",n.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return Ye.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return Ye.define(()=>({}),{eventObservers:e})}static theme(e,t){let n=Fr.newName(),i=[gl.of(n),So.of(sh(`.${n}`,e))];return t&&t.dark&&i.push(nh.of(!0)),i}static baseTheme(e){return tn.lowest(So.of(sh("."+ih,e,ix)))}static findFromDOM(e){var t;let n=e.querySelector(".cm-content"),i=n&&Xe.get(n)||Xe.get(e);return((t=i?.root)===null||t===void 0?void 0:t.view)||null}};U.styleModule=So;U.inputHandler=Rb;U.clipboardInputFilter=Ch;U.clipboardOutputFilter=kh;U.scrollHandler=Bb;U.focusChangeEffect=Ib;U.perLineTextDirection=Pb;U.exceptionSink=Ob;U.updateListener=Iu;U.editable=_n;U.mouseSelectionStyle=Db;U.dragMovesSelection=Mb;U.clickAddsSelectionRange=Tb;U.decorations=Wl;U.blockWrappers=zb;U.outerDecorations=Eh;U.atomicRanges=$o;U.bidiIsolatedRanges=$b;U.scrollMargins=Hb;U.darkTheme=nh;U.cspNonce=K.define({combine:r=>r.length?r[0]:""});U.contentAttributes=Nh;U.editorAttributes=_b;U.lineWrapping=U.contentAttributes.of({class:"cm-lineWrapping"});U.announce=le.define();var qA=4096,tb={},Ll=class r{constructor(e,t,n,i,s,o){this.from=e,this.to=t,this.dir=n,this.isolates=i,this.fresh=s,this.order=o}static update(e,t){if(t.empty&&!e.some(s=>s.fresh))return e;let n=[],i=e.length?e[e.length-1].dir:Be.LTR;for(let s=Math.max(0,e.length-10);s<e.length;s++){let o=e[s];o.dir==i&&!t.touchesRange(o.from,o.to)&&n.push(new r(t.mapPos(o.from,1),t.mapPos(o.to,-1),o.dir,o.isolates,!1,o.order))}return n}};function rb(r,e,t){for(let n=r.state.facet(e),i=n.length-1;i>=0;i--){let s=n[i],o=typeof s=="function"?s(r):s;o&&yh(o,t)}return t}var KA=Y.mac?"mac":Y.windows?"win":Y.linux?"linux":"key";function YA(r,e){let t=r.split(/-(?!$)/),n=t[t.length-1];n=="Space"&&(n=" ");let i,s,o,a;for(let l=0;l<t.length-1;++l){let c=t[l];if(/^(cmd|meta|m)$/i.test(c))a=!0;else if(/^a(lt)?$/i.test(c))i=!0;else if(/^(c|ctrl|control)$/i.test(c))s=!0;else if(/^s(hift)?$/i.test(c))o=!0;else if(/^mod$/i.test(c))e=="mac"?a=!0:s=!0;else throw new Error("Unrecognized modifier name: "+c)}return i&&(n="Alt-"+n),s&&(n="Ctrl-"+n),a&&(n="Meta-"+n),o&&(n="Shift-"+n),n}function bl(r,e,t){return e.altKey&&(r="Alt-"+r),e.ctrlKey&&(r="Ctrl-"+r),e.metaKey&&(r="Meta-"+r),t!==!1&&e.shiftKey&&(r="Shift-"+r),r}var JA=tn.default(U.domEventHandlers({keydown(r,e){return ax(sx(e.state),r,e,"editor")}})),Hn=K.define({enables:JA}),nb=new WeakMap;function sx(r){let e=r.facet(Hn),t=nb.get(e);return t||nb.set(e,t=ZA(e.reduce((n,i)=>n.concat(i),[]))),t}function ox(r,e,t){return ax(sx(r.state),e,r,t)}var ri=null,XA=4e3;function ZA(r,e=KA){let t=Object.create(null),n=Object.create(null),i=(o,a)=>{let l=n[o];if(l==null)n[o]=a;else if(l!=a)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},s=(o,a,l,c,d)=>{var u,h;let f=t[o]||(t[o]=Object.create(null)),p=a.split(/ (?!$)/).map(b=>YA(b,e));for(let b=1;b<p.length;b++){let y=p.slice(0,b).join(" ");i(y,!0),f[y]||(f[y]={preventDefault:!0,stopPropagation:!1,run:[x=>{let N=ri={view:x,prefix:y,scope:o};return setTimeout(()=>{ri==N&&(ri=null)},XA),!0}]})}let m=p.join(" ");i(m,!1);let g=f[m]||(f[m]={preventDefault:!1,stopPropagation:!1,run:((h=(u=f._any)===null||u===void 0?void 0:u.run)===null||h===void 0?void 0:h.slice())||[]});l&&g.run.push(l),c&&(g.preventDefault=!0),d&&(g.stopPropagation=!0)};for(let o of r){let a=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let c of a){let d=t[c]||(t[c]=Object.create(null));d._any||(d._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:u}=o;for(let h in d)d[h].run.push(f=>u(f,lh))}let l=o[e]||o.key;if(l)for(let c of a)s(c,l,o.run,o.preventDefault,o.stopPropagation),o.shift&&s(c,"Shift-"+l,o.shift,o.preventDefault,o.stopPropagation)}return t}var lh=null;function ax(r,e,t,n){lh=e;let i=M0(e),s=Rt(i,0),o=vr(s)==i.length&&i!=" ",a="",l=!1,c=!1,d=!1;ri&&ri.view==t&&ri.scope==n&&(a=ri.prefix+" ",Yb.indexOf(e.keyCode)<0&&(c=!0,ri=null));let u=new Set,h=g=>{if(g){for(let b of g.run)if(!u.has(b)&&(u.add(b),b(t)))return g.stopPropagation&&(d=!0),!0;g.preventDefault&&(g.stopPropagation&&(d=!0),c=!0)}return!1},f=r[n],p,m;return f&&(h(f[a+bl(i,e,!o)])?l=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(Y.windows&&e.ctrlKey&&e.altKey)&&!(Y.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(p=Fn[e.keyCode])&&p!=i?(h(f[a+bl(p,e,!0)])||e.shiftKey&&(m=ws[e.keyCode])!=i&&m!=p&&h(f[a+bl(m,e,!1)]))&&(l=!0):o&&e.shiftKey&&h(f[a+bl(i,e,!0)])&&(l=!0),!l&&h(f._any)&&(l=!0)),c&&(l=!0),l&&d&&e.stopPropagation(),lh=null,l}var Pi=class r{constructor(e,t,n,i,s){this.className=e,this.left=t,this.top=n,this.width=i,this.height=s}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,n){if(n.empty){let i=e.coordsAtPos(n.head,n.assoc||1);if(!i)return[];let s=lx(e);return[new r(t,i.left-s.left,i.top-s.top,null,i.bottom-i.top)]}else return QA(e,t,n)}};function lx(r){let e=r.scrollDOM.getBoundingClientRect();return{left:(r.textDirection==Be.LTR?e.left:e.right-r.scrollDOM.clientWidth*r.scaleX)-r.scrollDOM.scrollLeft*r.scaleX,top:e.top-r.scrollDOM.scrollTop*r.scaleY}}function ib(r,e,t,n){let i=r.coordsAtPos(e,t*2);if(!i)return n;let s=r.dom.getBoundingClientRect(),o=(i.top+i.bottom)/2,a=r.posAtCoords({x:s.left+1,y:o}),l=r.posAtCoords({x:s.right-1,y:o});return a==null||l==null?n:{from:Math.max(n.from,Math.min(a,l)),to:Math.min(n.to,Math.max(a,l))}}function QA(r,e,t){if(t.to<=r.viewport.from||t.from>=r.viewport.to)return[];let n=Math.max(t.from,r.viewport.from),i=Math.min(t.to,r.viewport.to),s=r.textDirection==Be.LTR,o=r.contentDOM,a=o.getBoundingClientRect(),l=lx(r),c=o.querySelector(".cm-line"),d=c&&window.getComputedStyle(c),u=a.left+(d?parseInt(d.paddingLeft)+Math.min(0,parseInt(d.textIndent)):0),h=a.right-(d?parseInt(d.paddingRight):0),f=Wu(r,n,1),p=Wu(r,i,-1),m=f.type==Pt.Text?f:null,g=p.type==Pt.Text?p:null;if(m&&(r.lineWrapping||f.widgetLineBreaks)&&(m=ib(r,n,1,m)),g&&(r.lineWrapping||p.widgetLineBreaks)&&(g=ib(r,i,-1,g)),m&&g&&m.from==g.from&&m.to==g.to)return y(x(t.from,t.to,m));{let C=m?x(t.from,null,m):N(f,!1),w=g?x(null,t.to,g):N(p,!0),k=[];return(m||f).to<(g||p).from-(m&&g?1:0)||f.widgetLineBreaks>1&&C.bottom+r.defaultLineHeight/2<w.top?k.push(b(u,C.bottom,h,w.top)):C.bottom<w.top&&r.elementAtHeight((C.bottom+w.top)/2).type==Pt.Text&&(C.bottom=w.top=(C.bottom+w.top)/2),y(C).concat(k).concat(y(w))}function b(C,w,k,A){return new Pi(e,C-l.left,w-l.top,Math.max(0,k-C),A-w)}function y({top:C,bottom:w,horizontal:k}){let A=[];for(let S=0;S<k.length;S+=2)A.push(b(k[S],C,k[S+1],w));return A}function x(C,w,k){let A=1e9,S=-1e9,M=[];function D(E,$,G,W,he){let _=r.coordsAtPos(E,E==k.to?-2:2),ie=r.coordsAtPos(G,G==k.from?2:-2);!_||!ie||(A=Math.min(_.top,ie.top,A),S=Math.max(_.bottom,ie.bottom,S),he==Be.LTR?M.push(s&&$?u:_.left,s&&W?h:ie.right):M.push(!s&&W?u:ie.left,!s&&$?h:_.right))}let O=C??k.from,H=w??k.to;for(let E of r.visibleRanges)if(E.to>O&&E.from<H)for(let $=Math.max(E.from,O),G=Math.min(E.to,H);;){let W=r.state.doc.lineAt($);for(let he of r.bidiSpans(W)){let _=he.from+W.from,ie=he.to+W.from;if(_>=G)break;ie>$&&D(Math.max(_,$),C==null&&_<=O,Math.min(ie,G),w==null&&ie>=H,he.dir)}if($=W.to+1,$>=G)break}return M.length==0&&D(O,C==null,H,w==null,r.textDirection),{top:A,bottom:S,horizontal:M}}function N(C,w){let k=a.top+(w?C.top:C.bottom);return{top:k,bottom:k,horizontal:[]}}}function eT(r,e){return r.constructor==e.constructor&&r.eq(e)}var ch=class{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(wl)!=e.state.facet(wl)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let t=0,n=e.facet(wl);for(;t<n.length&&n[t]!=this.layer;)t++;this.dom.style.zIndex=String((this.layer.above?150:-1)-t)}measure(){return this.layer.markers(this.view)}scale(){let{scaleX:e,scaleY:t}=this.view;(e!=this.scaleX||t!=this.scaleY)&&(this.scaleX=e,this.scaleY=t,this.dom.style.transform=`scale(${1/e}, ${1/t})`)}draw(e){if(e.length!=this.drawn.length||e.some((t,n)=>!eT(t,this.drawn[n]))){let t=this.dom.firstChild,n=0;for(let i of e)i.update&&t&&i.constructor&&this.drawn[n].constructor&&i.update(t,this.drawn[n])?(t=t.nextSibling,n++):this.dom.insertBefore(i.draw(),t);for(;t;){let i=t.nextSibling;t.remove(),t=i}this.drawn=e,Y.safari&&Y.safari_version>=26&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}},wl=K.define();function cx(r){return[Ye.define(e=>new ch(e,r)),wl.of(r)]}var Ps=K.define({combine(r){return Ut(r,{cursorBlinkRate:1200,drawRangeCursor:!0,iosSelectionHandles:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function dx(r={}){return[Ps.of(r),tT,rT,nT,Lb.of(!0)]}function ux(r){return r.startState.facet(Ps)!=r.state.facet(Ps)}var tT=cx({above:!0,markers(r){let{state:e}=r,t=e.facet(Ps),n=[];for(let i of e.selection.ranges){let s=i==e.selection.main;if(i.empty||t.drawRangeCursor&&!(s&&Y.ios&&t.iosSelectionHandles)){let o=s?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",a=i.empty?i:P.cursor(i.head,i.assoc);for(let l of Pi.forRange(r,o,a))n.push(l)}}return n},update(r,e){r.transactions.some(n=>n.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=ux(r);return t&&sb(r.state,e),r.docChanged||r.selectionSet||t},mount(r,e){sb(e.state,r)},class:"cm-cursorLayer"});function sb(r,e){e.style.animationDuration=r.facet(Ps).cursorBlinkRate+"ms"}var rT=cx({above:!1,markers(r){let e=[],{main:t,ranges:n}=r.state.selection;for(let i of n)if(!i.empty)for(let s of Pi.forRange(r,"cm-selectionBackground",i))e.push(s);if(Y.ios&&!t.empty&&r.state.facet(Ps).iosSelectionHandles){for(let i of Pi.forRange(r,"cm-selectionHandle cm-selectionHandle-start",P.cursor(t.from,1)))e.push(i);for(let i of Pi.forRange(r,"cm-selectionHandle cm-selectionHandle-end",P.cursor(t.to,1)))e.push(i)}return e},update(r,e){return r.docChanged||r.selectionSet||r.viewportChanged||ux(r)},class:"cm-selectionLayer"}),nT=tn.highest(U.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:"transparent !important"},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}})),hx=le.define({map(r,e){return r==null?null:e.mapPos(r)}}),ko=st.define({create(){return null},update(r,e){return r!=null&&(r=e.changes.mapPos(r)),e.effects.reduce((t,n)=>n.is(hx)?n.value:t,r)}}),iT=Ye.fromClass(class{constructor(r){this.view=r,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(r){var e;let t=r.state.field(ko);t==null?this.cursor!=null&&((e=this.cursor)===null||e===void 0||e.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(r.startState.field(ko)!=t||r.docChanged||r.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:r}=this,e=r.state.field(ko),t=e!=null&&r.coordsAtPos(e);if(!t)return null;let n=r.scrollDOM.getBoundingClientRect();return{left:t.left-n.left+r.scrollDOM.scrollLeft*r.scaleX,top:t.top-n.top+r.scrollDOM.scrollTop*r.scaleY,height:t.bottom-t.top}}drawCursor(r){if(this.cursor){let{scaleX:e,scaleY:t}=this.view;r?(this.cursor.style.left=r.left/e+"px",this.cursor.style.top=r.top/t+"px",this.cursor.style.height=r.height/t+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(r){this.view.state.field(ko)!=r&&this.view.dispatch({effects:hx.of(r)})}},{eventObservers:{dragover(r){this.setDropPos(this.view.posAtCoords({x:r.clientX,y:r.clientY}))},dragleave(r){(r.target==this.view.contentDOM||!this.view.contentDOM.contains(r.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function fx(){return[ko,iT]}function ob(r,e,t,n,i){e.lastIndex=0;for(let s=r.iterRange(t,n),o=t,a;!s.next().done;o+=s.value.length)if(!s.lineBreak)for(;a=e.exec(s.value);)i(o+a.index,a)}function sT(r,e){let t=r.visibleRanges;if(t.length==1&&t[0].from==r.viewport.from&&t[0].to==r.viewport.to)return t;let n=[];for(let{from:i,to:s}of t)i=Math.max(r.state.doc.lineAt(i).from,i-e),s=Math.min(r.state.doc.lineAt(s).to,s+e),n.length&&n[n.length-1].to>=i?n[n.length-1].to=s:n.push({from:i,to:s});return n}var dh=class{constructor(e){let{regexp:t,decoration:n,decorate:i,boundary:s,maxLength:o=1e3}=e;if(!t.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=t,i)this.addMatch=(a,l,c,d)=>i(d,c,c+a[0].length,a,l);else if(typeof n=="function")this.addMatch=(a,l,c,d)=>{let u=n(a,l,c);u&&d(c,c+a[0].length,u)};else if(n)this.addMatch=(a,l,c,d)=>d(c,c+a[0].length,n);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=s,this.maxLength=o}createDeco(e){let t=new xr,n=t.add.bind(t);for(let{from:i,to:s}of sT(e,this.maxLength))ob(e.state.doc,this.regexp,i,s,(o,a)=>this.addMatch(a,e,o,n));return t.finish()}updateDeco(e,t){let n=1e9,i=-1;return e.docChanged&&e.changes.iterChanges((s,o,a,l)=>{l>=e.view.viewport.from&&a<=e.view.viewport.to&&(n=Math.min(a,n),i=Math.max(l,i))}),e.viewportMoved||i-n>1e3?this.createDeco(e.view):i>-1?this.updateRange(e.view,t.map(e.changes),n,i):t}updateRange(e,t,n,i){for(let s of e.visibleRanges){let o=Math.max(s.from,n),a=Math.min(s.to,i);if(a>=o){let l=e.state.doc.lineAt(o),c=l.to<a?e.state.doc.lineAt(a):l,d=Math.max(s.from,l.from),u=Math.min(s.to,c.to);if(this.boundary){for(;o>l.from;o--)if(this.boundary.test(l.text[o-1-l.from])){d=o;break}for(;a<c.to;a++)if(this.boundary.test(c.text[a-c.from])){u=a;break}}let h=[],f,p=(m,g,b)=>h.push(b.range(m,g));if(l==c)for(this.regexp.lastIndex=d-l.from;(f=this.regexp.exec(l.text))&&f.index<u-l.from;)this.addMatch(f,e,f.index+l.from,p);else ob(e.state.doc,this.regexp,d,u,(m,g)=>this.addMatch(g,e,m,p));t=t.update({filterFrom:d,filterTo:u,filter:(m,g)=>m<d||g>u,add:h})}}return t}},uh=/x/.unicode!=null?"gu":"g",oT=new RegExp(`[\0-\b
78
+ -\x7F-\x9F\xAD\u061C\u200B\u200E\u200F\u2028\u2029\u202D\u202E\u2066\u2067\u2069\uFEFF\uFFF9-\uFFFC]`,uh),aT={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"},yu=null;function lT(){var r;if(yu==null&&typeof document<"u"&&document.body){let e=document.body.style;yu=((r=e.tabSize)!==null&&r!==void 0?r:e.MozTabSize)!=null}return yu||!1}var Sl=K.define({combine(r){let e=Ut(r,{render:null,specialChars:oT,addSpecialChars:null});return(e.replaceTabs=!lT())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,uh)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,uh)),e}});function px(r={}){return[Sl.of(r),cT()]}var ab=null;function cT(){return ab||(ab=Ye.fromClass(class{constructor(r){this.view=r,this.decorations=Z.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(r.state.facet(Sl)),this.decorations=this.decorator.createDeco(r)}makeDecorator(r){return new dh({regexp:r.specialChars,decoration:(e,t,n)=>{let{doc:i}=t.state,s=Rt(e[0],0);if(s==9){let o=i.lineAt(n),a=t.state.tabSize,l=Bn(o.text,a,n-o.from);return Z.replace({widget:new fh((a-l%a)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[s]||(this.decorationCache[s]=Z.replace({widget:new hh(r,s)}))},boundary:r.replaceTabs?void 0:/[^]/})}update(r){let e=r.state.facet(Sl);r.startState.facet(Sl)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(r.view)):this.decorations=this.decorator.updateDeco(r,this.decorations)}},{decorations:r=>r.decorations}))}var dT="\u2022";function uT(r){return r>=32?dT:r==10?"\u2424":String.fromCharCode(9216+r)}var hh=class extends er{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=uT(this.code),n=e.state.phrase("Control character")+" "+(aT[this.code]||"0x"+this.code.toString(16)),i=this.options.render&&this.options.render(this.code,n,t);if(i)return i;let s=document.createElement("span");return s.textContent=t,s.title=n,s.setAttribute("aria-label",n),s.className="cm-specialChar",s}ignoreEvent(){return!1}},fh=class extends er{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}};function mx(){return fT}var hT=Z.line({class:"cm-activeLine"}),fT=Ye.fromClass(class{constructor(r){this.decorations=this.getDeco(r)}update(r){(r.docChanged||r.selectionSet)&&(this.decorations=this.getDeco(r.view))}getDeco(r){let e=-1,t=[];for(let n of r.state.selection.ranges){let i=r.lineBlockAt(n.head);i.from>e&&(t.push(hT.range(i.from)),e=i.from)}return Z.set(t)}},{decorations:r=>r.decorations}),ph=class extends er{constructor(e){super(),this.content=e}toDOM(e){let t=document.createElement("span");return t.className="cm-placeholder",t.style.pointerEvents="none",t.appendChild(typeof this.content=="string"?document.createTextNode(this.content):typeof this.content=="function"?this.content(e):this.content.cloneNode(!0)),t.setAttribute("aria-hidden","true"),t}coordsAt(e){let t=e.firstChild?Eo(e.firstChild):[];if(!t.length)return null;let n=window.getComputedStyle(e.parentNode),i=_o(t[0],n.direction!="rtl"),s=parseInt(n.lineHeight);return i.bottom-i.top>s*1.5?{left:i.left,right:i.right,top:i.top,bottom:i.top+s}:i}ignoreEvent(){return!1}};function gx(r){let e=Ye.fromClass(class{constructor(t){this.view=t,this.placeholder=r?Z.set([Z.widget({widget:new ph(r),side:1}).range(0)]):Z.none}get decorations(){return this.view.state.doc.length?Z.none:this.placeholder}},{decorations:t=>t.decorations});return typeof r=="string"?[e,U.contentAttributes.of({"aria-placeholder":r})]:e}var mh=2e3;function pT(r,e,t){let n=Math.min(e.line,t.line),i=Math.max(e.line,t.line),s=[];if(e.off>mh||t.off>mh||e.col<0||t.col<0){let o=Math.min(e.off,t.off),a=Math.max(e.off,t.off);for(let l=n;l<=i;l++){let c=r.doc.line(l);c.length<=a&&s.push(P.range(c.from+o,c.to+a))}}else{let o=Math.min(e.col,t.col),a=Math.max(e.col,t.col);for(let l=n;l<=i;l++){let c=r.doc.line(l),d=cl(c.text,o,r.tabSize,!0);if(d<0)s.push(P.cursor(c.to));else{let u=cl(c.text,a,r.tabSize);s.push(P.range(c.from+d,c.from+u))}}}return s}function mT(r,e){let t=r.coordsAtPos(r.viewport.from);return t?Math.round(Math.abs((t.left-e)/r.defaultCharacterWidth)):-1}function lb(r,e){let t=r.posAtCoords({x:e.clientX,y:e.clientY},!1),n=r.state.doc.lineAt(t),i=t-n.from,s=i>mh?-1:i==n.length?mT(r,e.clientX):Bn(n.text,r.state.tabSize,t-n.from);return{line:n.number,col:s,off:i}}function gT(r,e){let t=lb(r,e),n=r.state.selection;return t?{update(i){if(i.docChanged){let s=i.changes.mapPos(i.startState.doc.line(t.line).from),o=i.state.doc.lineAt(s);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},n=n.map(i.changes)}},get(i,s,o){let a=lb(r,i);if(!a)return n;let l=pT(r.state,t,a);return l.length?o?P.create(l.concat(n.ranges)):P.create(l):n}}:null}function bx(r){let e=r?.eventFilter||(t=>t.altKey&&t.button==0);return U.mouseSelectionStyle.of((t,n)=>e(n)?gT(t,n):null)}var bT={Alt:[18,r=>!!r.altKey],Control:[17,r=>!!r.ctrlKey],Shift:[16,r=>!!r.shiftKey],Meta:[91,r=>!!r.metaKey]},xT={style:"cursor: crosshair"};function xx(r={}){let[e,t]=bT[r.key||"Alt"],n=Ye.fromClass(class{constructor(i){this.view=i,this.isDown=!1}set(i){this.isDown!=i&&(this.isDown=i,this.view.update([]))}},{eventObservers:{keydown(i){this.set(i.keyCode==e||t(i))},keyup(i){(i.keyCode==e||!t(i))&&this.set(!1)},mousemove(i){this.set(t(i))}}});return[n,U.contentAttributes.of(i=>{var s;return!((s=i.plugin(n))===null||s===void 0)&&s.isDown?xT:null})]}var xl="-10000px",Bl=class{constructor(e,t,n,i){this.facet=t,this.createTooltipView=n,this.removeTooltipView=i,this.input=e.state.facet(t),this.tooltips=this.input.filter(o=>o);let s=null;this.tooltipViews=this.tooltips.map(o=>s=n(o,s))}update(e,t){var n;let i=e.state.facet(this.facet),s=i.filter(l=>l);if(i===this.input){for(let l of this.tooltipViews)l.update&&l.update(e);return!1}let o=[],a=t?[]:null;for(let l=0;l<s.length;l++){let c=s[l],d=-1;if(c){for(let u=0;u<this.tooltips.length;u++){let h=this.tooltips[u];h&&h.create==c.create&&(d=u)}if(d<0)o[l]=this.createTooltipView(c,l?o[l-1]:null),a&&(a[l]=!!c.above);else{let u=o[l]=this.tooltipViews[d];a&&(a[l]=t[d]),u.update&&u.update(e)}}}for(let l of this.tooltipViews)o.indexOf(l)<0&&(this.removeTooltipView(l),(n=l.destroy)===null||n===void 0||n.call(l));return t&&(a.forEach((l,c)=>t[c]=l),t.length=a.length),this.input=i,this.tooltips=s,this.tooltipViews=o,!0}};function vT(r){let e=r.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:e.clientHeight,right:e.clientWidth}}var wu=K.define({combine:r=>{var e,t,n;return{position:Y.ios?"absolute":((e=r.find(i=>i.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=r.find(i=>i.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((n=r.find(i=>i.tooltipSpace))===null||n===void 0?void 0:n.tooltipSpace)||vT}}}),cb=new WeakMap,Mh=Ye.fromClass(class{constructor(r){this.view=r,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=r.state.facet(wu);this.position=e.position,this.parent=e.parent,this.classes=r.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new Bl(r,Ho,(t,n)=>this.createTooltip(t,n),t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()}),this.above=this.manager.tooltips.map(t=>!!t.above),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(t=>{Date.now()>this.lastTransaction-50&&t.length>0&&t[t.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),r.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let r of this.manager.tooltipViews)this.intersectionObserver.observe(r.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(r){r.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(r,this.above);e&&this.observeIntersection();let t=e||r.geometryChanged,n=r.state.facet(wu);if(n.position!=this.position&&!this.madeAbsolute){this.position=n.position;for(let i of this.manager.tooltipViews)i.dom.style.position=this.position;t=!0}if(n.parent!=this.parent){this.parent&&this.container.remove(),this.parent=n.parent,this.createContainer();for(let i of this.manager.tooltipViews)this.container.appendChild(i.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(r,e){let t=r.create(this.view),n=e?e.dom:null;if(t.dom.classList.add("cm-tooltip"),r.arrow&&!t.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let i=document.createElement("div");i.className="cm-tooltip-arrow",t.dom.appendChild(i)}return t.dom.style.position=this.position,t.dom.style.top=xl,t.dom.style.left="0px",this.container.insertBefore(t.dom,n),t.mount&&t.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(t.dom),t}destroy(){var r,e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let n of this.manager.tooltipViews)n.dom.remove(),(r=n.destroy)===null||r===void 0||r.call(n);this.parent&&this.container.remove(),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),(t=this.intersectionObserver)===null||t===void 0||t.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let r=1,e=1,t=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:s}=this.manager.tooltipViews[0];if(Y.safari){let o=s.getBoundingClientRect();t=Math.abs(o.top+1e4)>1||Math.abs(o.left)>1}else t=!!s.offsetParent&&s.offsetParent!=this.container.ownerDocument.body}if(t||this.position=="absolute")if(this.parent){let s=this.parent.getBoundingClientRect();s.width&&s.height&&(r=s.width/this.parent.offsetWidth,e=s.height/this.parent.offsetHeight)}else({scaleX:r,scaleY:e}=this.view.viewState);let n=this.view.scrollDOM.getBoundingClientRect(),i=Ah(this.view);return{visible:{left:n.left+i.left,top:n.top+i.top,right:n.right-i.right,bottom:n.bottom-i.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((s,o)=>{let a=this.manager.tooltipViews[o];return a.getCoords?a.getCoords(s.pos):this.view.coordsAtPos(s.pos)}),size:this.manager.tooltipViews.map(({dom:s})=>s.getBoundingClientRect()),space:this.view.state.facet(wu).tooltipSpace(this.view),scaleX:r,scaleY:e,makeAbsolute:t}}writeMeasure(r){var e;if(r.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let a of this.manager.tooltipViews)a.dom.style.position="absolute"}let{visible:t,space:n,scaleX:i,scaleY:s}=r,o=[];for(let a=0;a<this.manager.tooltips.length;a++){let l=this.manager.tooltips[a],c=this.manager.tooltipViews[a],{dom:d}=c,u=r.pos[a],h=r.size[a];if(!u||l.clip!==!1&&(u.bottom<=Math.max(t.top,n.top)||u.top>=Math.min(t.bottom,n.bottom)||u.right<Math.max(t.left,n.left)-.1||u.left>Math.min(t.right,n.right)+.1)){d.style.top=xl;continue}let f=l.arrow?c.dom.querySelector(".cm-tooltip-arrow"):null,p=f?7:0,m=h.right-h.left,g=(e=cb.get(c))!==null&&e!==void 0?e:h.bottom-h.top,b=c.offset||wT,y=this.view.textDirection==Be.LTR,x=h.width>n.right-n.left?y?n.left:n.right-h.width:y?Math.max(n.left,Math.min(u.left-(f?14:0)+b.x,n.right-m)):Math.min(Math.max(n.left,u.left-m+(f?14:0)-b.x),n.right-m),N=this.above[a];!l.strictSide&&(N?u.top-g-p-b.y<n.top:u.bottom+g+p+b.y>n.bottom)&&N==n.bottom-u.bottom>u.top-n.top&&(N=this.above[a]=!N);let C=(N?u.top-n.top:n.bottom-u.bottom)-p;if(C<g&&c.resize!==!1){if(C<this.view.defaultLineHeight){d.style.top=xl;continue}cb.set(c,g),d.style.height=(g=C)/s+"px"}else d.style.height&&(d.style.height="");let w=N?u.top-g-p-b.y:u.bottom+p+b.y,k=x+m;if(c.overlap!==!0)for(let A of o)A.left<k&&A.right>x&&A.top<w+g&&A.bottom>w&&(w=N?A.top-g-2-p:A.bottom+p+2);if(this.position=="absolute"?(d.style.top=(w-r.parent.top)/s+"px",db(d,(x-r.parent.left)/i)):(d.style.top=w/s+"px",db(d,x/i)),f){let A=u.left+(y?b.x:-b.x)-(x+14-7);f.style.left=A/i+"px"}c.overlap!==!0&&o.push({left:x,top:w,right:k,bottom:w+g}),d.classList.toggle("cm-tooltip-above",N),d.classList.toggle("cm-tooltip-below",!N),c.positioned&&c.positioned(r.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let r of this.manager.tooltipViews)r.dom.style.top=xl}},{eventObservers:{scroll(){this.maybeMeasure()}}});function db(r,e){let t=parseInt(r.style.left,10);(isNaN(t)||Math.abs(e-t)>1)&&(r.style.left=e+"px")}var yT=U.baseTheme({".cm-tooltip":{zIndex:500,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:"14px",position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),wT={x:0,y:0},Ho=K.define({enables:[Mh,yT]}),Fl=K.define({combine:r=>r.reduce((e,t)=>e.concat(t),[])}),_l=class r{static create(e){return new r(e)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new Bl(e,Fl,(t,n)=>this.createHostedView(t,n),t=>t.dom.remove())}createHostedView(e,t){let n=e.create(this.view);return n.dom.classList.add("cm-tooltip-section"),this.dom.insertBefore(n.dom,t?t.dom.nextSibling:this.dom.firstChild),this.mounted&&n.mount&&n.mount(this.view),n}mount(e){for(let t of this.manager.tooltipViews)t.mount&&t.mount(e);this.mounted=!0}positioned(e){for(let t of this.manager.tooltipViews)t.positioned&&t.positioned(e)}update(e){this.manager.update(e)}destroy(){var e;for(let t of this.manager.tooltipViews)(e=t.destroy)===null||e===void 0||e.call(t)}passProp(e){let t;for(let n of this.manager.tooltipViews){let i=n[e];if(i!==void 0){if(t===void 0)t=i;else if(t!==i)return}}return t}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}},ST=Ho.compute([Fl],r=>{let e=r.facet(Fl);return e.length===0?null:{pos:Math.min(...e.map(t=>t.pos)),end:Math.max(...e.map(t=>{var n;return(n=t.end)!==null&&n!==void 0?n:t.pos})),create:_l.create,above:e[0].above,arrow:e.some(t=>t.arrow)}}),gh=class{constructor(e,t,n,i,s){this.view=e,this.source=t,this.field=n,this.setHover=i,this.hoverTime=s,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:e.dom,time:0},this.checkHover=this.checkHover.bind(this),e.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),e.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active.length)return;let e=Date.now()-this.lastMove.time;e<this.hoverTime?this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime-e):this.startHover()}startHover(){clearTimeout(this.restartTimeout);let{view:e,lastMove:t}=this,n=e.docView.tile.nearest(t.target);if(!n)return;let i,s=1;if(n.isWidget())i=n.posAtStart;else{if(i=e.posAtCoords(t),i==null)return;let a=e.coordsAtPos(i);if(!a||t.y<a.top||t.y>a.bottom||t.x<a.left-e.defaultCharacterWidth||t.x>a.right+e.defaultCharacterWidth)return;let l=e.bidiSpans(e.state.doc.lineAt(i)).find(d=>d.from<=i&&d.to>=i),c=l&&l.dir==Be.RTL?-1:1;s=t.x<a.left?-c:c}let o=this.source(e,i,s);if(o?.then){let a=this.pending={pos:i};o.then(l=>{this.pending==a&&(this.pending=null,l&&!(Array.isArray(l)&&!l.length)&&e.dispatch({effects:this.setHover.of(Array.isArray(l)?l:[l])}))},l=>It(e.state,l,"hover tooltip"))}else o&&!(Array.isArray(o)&&!o.length)&&e.dispatch({effects:this.setHover.of(Array.isArray(o)?o:[o])})}get tooltip(){let e=this.view.plugin(Mh),t=e?e.manager.tooltips.findIndex(n=>n.create==_l.create):-1;return t>-1?e.manager.tooltipViews[t]:null}mousemove(e){var t,n;this.lastMove={x:e.clientX,y:e.clientY,target:e.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:i,tooltip:s}=this;if(i.length&&s&&!CT(s.dom,e)||this.pending){let{pos:o}=i[0]||this.pending,a=(n=(t=i[0])===null||t===void 0?void 0:t.end)!==null&&n!==void 0?n:o;(o==a?this.view.posAtCoords(this.lastMove)!=o:!kT(this.view,o,a,e.clientX,e.clientY))&&(this.view.dispatch({effects:this.setHover.of([])}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:t}=this;if(t.length){let{tooltip:n}=this;n&&n.dom.contains(e.relatedTarget)?this.watchTooltipLeave(n.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(e){let t=n=>{e.removeEventListener("mouseleave",t),this.active.length&&!this.view.dom.contains(n.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};e.addEventListener("mouseleave",t)}destroy(){clearTimeout(this.hoverTimeout),clearTimeout(this.restartTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}},vl=4;function CT(r,e){let{left:t,right:n,top:i,bottom:s}=r.getBoundingClientRect(),o;if(o=r.querySelector(".cm-tooltip-arrow")){let a=o.getBoundingClientRect();i=Math.min(a.top,i),s=Math.max(a.bottom,s)}return e.clientX>=t-vl&&e.clientX<=n+vl&&e.clientY>=i-vl&&e.clientY<=s+vl}function kT(r,e,t,n,i,s){let o=r.scrollDOM.getBoundingClientRect(),a=r.documentTop+r.documentPadding.top+r.contentHeight;if(o.left>n||o.right<n||o.top>i||Math.min(o.bottom,a)<i)return!1;let l=r.posAtCoords({x:n,y:i},!1);return l>=e&&l<=t}function vx(r,e={}){let t=le.define(),n=st.define({create(){return[]},update(i,s){if(i.length&&(e.hideOnChange&&(s.docChanged||s.selection)?i=[]:e.hideOn&&(i=i.filter(o=>!e.hideOn(s,o))),s.docChanged)){let o=[];for(let a of i){let l=s.changes.mapPos(a.pos,-1,Ot.TrackDel);if(l!=null){let c=Object.assign(Object.create(null),a);c.pos=l,c.end!=null&&(c.end=s.changes.mapPos(c.end)),o.push(c)}}i=o}for(let o of s.effects)o.is(t)&&(i=o.value),o.is(NT)&&(i=[]);return i},provide:i=>Fl.from(i)});return{active:n,extension:[n,Ye.define(i=>new gh(i,r,n,t,e.hoverTime||300)),ST]}}function Dh(r,e){let t=r.plugin(Mh);if(!t)return null;let n=t.manager.tooltips.indexOf(e);return n<0?null:t.manager.tooltipViews[n]}var NT=le.define();var ub=K.define({combine(r){let e,t;for(let n of r)e=e||n.topContainer,t=t||n.bottomContainer;return{topContainer:e,bottomContainer:t}}});function Wo(r,e){let t=r.plugin(yx),n=t?t.specs.indexOf(e):-1;return n>-1?t.panels[n]:null}var yx=Ye.fromClass(class{constructor(r){this.input=r.state.facet(_i),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(r));let e=r.state.facet(ub);this.top=new Ns(r,!0,e.topContainer),this.bottom=new Ns(r,!1,e.bottomContainer),this.top.sync(this.panels.filter(t=>t.top)),this.bottom.sync(this.panels.filter(t=>!t.top));for(let t of this.panels)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}update(r){let e=r.state.facet(ub);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new Ns(r.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new Ns(r.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=r.state.facet(_i);if(t!=this.input){let n=t.filter(l=>l),i=[],s=[],o=[],a=[];for(let l of n){let c=this.specs.indexOf(l),d;c<0?(d=l(r.view),a.push(d)):(d=this.panels[c],d.update&&d.update(r)),i.push(d),(d.top?s:o).push(d)}this.specs=n,this.panels=i,this.top.sync(s),this.bottom.sync(o);for(let l of a)l.dom.classList.add("cm-panel"),l.mount&&l.mount()}else for(let n of this.panels)n.update&&n.update(r)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:r=>U.scrollMargins.of(e=>{let t=e.plugin(r);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})}),Ns=class{constructor(e,t,n){this.view=e,this.top=t,this.container=n,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let t of this.panels)t.destroy&&e.indexOf(t)<0&&t.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let t=this.container||this.view.dom;t.insertBefore(this.dom,this.top?t.firstChild:null)}let e=this.dom.firstChild;for(let t of this.panels)if(t.dom.parentNode==this.dom){for(;e!=t.dom;)e=hb(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=hb(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}};function hb(r){let e=r.nextSibling;return r.remove(),e}var _i=K.define({enables:yx});function wx(r,e){let t,n=new Promise(o=>t=o),i=o=>ET(o,e,t);r.state.field(Su,!1)?r.dispatch({effects:Sx.of(i)}):r.dispatch({effects:le.appendConfig.of(Su.init(()=>[i]))});let s=Cx.of(i);return{close:s,result:n.then(o=>((r.win.queueMicrotask||(l=>r.win.setTimeout(l,10)))(()=>{r.state.field(Su).indexOf(i)>-1&&r.dispatch({effects:s})}),o))}}var Su=st.define({create(){return[]},update(r,e){for(let t of e.effects)t.is(Sx)?r=[t.value].concat(r):t.is(Cx)&&(r=r.filter(n=>n!=t.value));return r},provide:r=>_i.computeN([r],e=>e.field(r))}),Sx=le.define(),Cx=le.define();function ET(r,e,t){let n=e.content?e.content(r,()=>o(null)):null;if(!n){if(n=De("form"),e.input){let a=De("input",e.input);/^(text|password|number|email|tel|url)$/.test(a.type)&&a.classList.add("cm-textfield"),a.name||(a.name="input"),n.appendChild(De("label",(e.label||"")+": ",a))}else n.appendChild(document.createTextNode(e.label||""));n.appendChild(document.createTextNode(" ")),n.appendChild(De("button",{class:"cm-button",type:"submit"},e.submitLabel||"OK"))}let i=n.nodeName=="FORM"?[n]:n.querySelectorAll("form");for(let a=0;a<i.length;a++){let l=i[a];l.addEventListener("keydown",c=>{c.keyCode==27?(c.preventDefault(),o(null)):c.keyCode==13&&(c.preventDefault(),o(l))}),l.addEventListener("submit",c=>{c.preventDefault(),o(l)})}let s=De("div",n,De("button",{onclick:()=>o(null),"aria-label":r.state.phrase("close"),class:"cm-dialog-close",type:"button"},["\xD7"]));e.class&&(s.className=e.class),s.classList.add("cm-dialog");function o(a){s.contains(s.ownerDocument.activeElement)&&r.focus(),t(a)}return{dom:s,top:e.top,mount:()=>{if(e.focus){let a;typeof e.focus=="string"?a=n.querySelector(e.focus):a=n.querySelector("input")||n.querySelector("button"),a&&"select"in a?a.select():a&&"focus"in a&&a.focus()}}}}var wr=class extends Br{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}};wr.prototype.elementClass="";wr.prototype.toDOM=void 0;wr.prototype.mapMode=Ot.TrackBefore;wr.prototype.startSide=wr.prototype.endSide=-1;wr.prototype.point=!0;var Cl=K.define(),AT=K.define(),TT={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>Ne.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{},side:"before"},Io=K.define();function Oh(r){return[kx(),Io.of({...TT,...r})]}var bh=K.define({combine:r=>r.some(e=>e)});function kx(r){let e=[MT];return r&&r.fixed===!1&&e.push(bh.of(!0)),e}var MT=Ye.fromClass(class{constructor(r){this.view=r,this.domAfter=null,this.prevViewport=r.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=r.state.facet(Io).map(e=>new zl(r,e)),this.fixed=!r.state.facet(bh);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),r.scrollDOM.insertBefore(this.dom,r.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(r){if(this.updateGutters(r)){let e=this.prevViewport,t=r.view.viewport,n=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(n<(t.to-t.from)*.8)}if(r.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(bh)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=r.view.viewport}syncGutters(r){let e=this.dom.nextSibling;r&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let t=Ne.iter(this.view.state.facet(Cl),this.view.viewport.from),n=[],i=this.gutters.map(s=>new vh(s,this.view.viewport,-this.view.documentPadding.top));for(let s of this.view.viewportLineBlocks)if(n.length&&(n=[]),Array.isArray(s.type)){let o=!0;for(let a of s.type)if(a.type==Pt.Text&&o){xh(t,n,a.from);for(let l of i)l.line(this.view,a,n);o=!1}else if(a.widget)for(let l of i)l.widget(this.view,a)}else if(s.type==Pt.Text){xh(t,n,s.from);for(let o of i)o.line(this.view,s,n)}else if(s.widget)for(let o of i)o.widget(this.view,s);for(let s of i)s.finish();r&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(r){let e=r.startState.facet(Io),t=r.state.facet(Io),n=r.docChanged||r.heightChanged||r.viewportChanged||!Ne.eq(r.startState.facet(Cl),r.state.facet(Cl),r.view.viewport.from,r.view.viewport.to);if(e==t)for(let i of this.gutters)i.update(r)&&(n=!0);else{n=!0;let i=[];for(let s of t){let o=e.indexOf(s);o<0?i.push(new zl(this.view,s)):(this.gutters[o].update(r),i.push(this.gutters[o]))}for(let s of this.gutters)s.dom.remove(),i.indexOf(s)<0&&s.destroy();for(let s of i)s.config.side=="after"?this.getDOMAfter().appendChild(s.dom):this.dom.appendChild(s.dom);this.gutters=i}return n}destroy(){for(let r of this.gutters)r.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:r=>U.scrollMargins.of(e=>{let t=e.plugin(r);if(!t||t.gutters.length==0||!t.fixed)return null;let n=t.dom.offsetWidth*e.scaleX,i=t.domAfter?t.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==Be.LTR?{left:n,right:i}:{right:n,left:i}})});function fb(r){return Array.isArray(r)?r:[r]}function xh(r,e,t){for(;r.value&&r.from<=t;)r.from==t&&e.push(r.value),r.next()}var vh=class{constructor(e,t,n){this.gutter=e,this.height=n,this.i=0,this.cursor=Ne.iter(e.markers,t.from)}addElement(e,t,n){let{gutter:i}=this,s=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==i.elements.length){let a=new $l(e,o,s,n);i.elements.push(a),i.dom.appendChild(a.dom)}else i.elements[this.i].update(e,o,s,n);this.height=t.bottom,this.i++}line(e,t,n){let i=[];xh(this.cursor,i,t.from),n.length&&(i=i.concat(n));let s=this.gutter.config.lineMarker(e,t,i);s&&i.unshift(s);let o=this.gutter;i.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,i)}widget(e,t){let n=this.gutter.config.widgetMarker(e,t.widget,t),i=n?[n]:null;for(let s of e.state.facet(AT)){let o=s(e,t.widget,t);o&&(i||(i=[])).push(o)}i&&this.addElement(e,t,i)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}},zl=class{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let n in t.domEventHandlers)this.dom.addEventListener(n,i=>{let s=i.target,o;if(s!=this.dom&&this.dom.contains(s)){for(;s.parentNode!=this.dom;)s=s.parentNode;let l=s.getBoundingClientRect();o=(l.top+l.bottom)/2}else o=i.clientY;let a=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[n](e,a,i)&&i.preventDefault()});this.markers=fb(t.markers(e)),t.initialSpacer&&(this.spacer=new $l(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=fb(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let i=this.config.updateSpacer(this.spacer.markers[0],e);i!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[i])}let n=e.view.viewport;return!Ne.eq(this.markers,t,n.from,n.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}},$l=class{constructor(e,t,n,i){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,n,i)}update(e,t,n,i){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=n&&(this.dom.style.marginTop=(this.above=n)?n+"px":""),DT(this.markers,i)||this.setMarkers(e,i)}setMarkers(e,t){let n="cm-gutterElement",i=this.dom.firstChild;for(let s=0,o=0;;){let a=o,l=s<t.length?t[s++]:null,c=!1;if(l){let d=l.elementClass;d&&(n+=" "+d);for(let u=o;u<this.markers.length;u++)if(this.markers[u].compare(l)){a=u,c=!0;break}}else a=this.markers.length;for(;o<a;){let d=this.markers[o++];if(d.toDOM){d.destroy(i);let u=i.nextSibling;i.remove(),i=u}}if(!l)break;l.toDOM&&(c?i=i.nextSibling:this.dom.insertBefore(l.toDOM(e),i)),c&&o++}this.dom.className=n,this.markers=t}destroy(){this.setMarkers(null,[])}};function DT(r,e){if(r.length!=e.length)return!1;for(let t=0;t<r.length;t++)if(!r[t].compare(e[t]))return!1;return!0}var OT=K.define(),RT=K.define(),Es=K.define({combine(r){return Ut(r,{formatNumber:String,domEventHandlers:{}},{domEventHandlers(e,t){let n=Object.assign({},e);for(let i in t){let s=n[i],o=t[i];n[i]=s?(a,l,c)=>s(a,l,c)||o(a,l,c):o}return n}})}}),Po=class extends wr{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}};function Cu(r,e){return r.state.facet(Es).formatNumber(e,r.state)}var IT=Io.compute([Es],r=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(OT)},lineMarker(e,t,n){return n.some(i=>i.toDOM)?null:new Po(Cu(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,n)=>{for(let i of e.state.facet(RT)){let s=i(e,t,n);if(s)return s}return null},lineMarkerChange:e=>e.startState.facet(Es)!=e.state.facet(Es),initialSpacer(e){return new Po(Cu(e,pb(e.state.doc.lines)))},updateSpacer(e,t){let n=Cu(t.view,pb(t.view.state.doc.lines));return n==e.number?e:new Po(n)},domEventHandlers:r.facet(Es).domEventHandlers,side:"before"}));function Nx(r={}){return[Es.of(r),kx(),IT]}function pb(r){let e=9;for(;e<r;)e=e*10+9;return e}var PT=new class extends wr{constructor(){super(...arguments),this.elementClass="cm-activeLineGutter"}},LT=Cl.compute(["selection"],r=>{let e=[],t=-1;for(let n of r.selection.ranges){let i=r.doc.lineAt(n.head).from;i>t&&(t=i,e.push(PT.range(i)))}return Ne.of(e)});function Ex(){return LT}var BT=0,Vo=class{constructor(e,t){this.from=e,this.to=t}},xe=class{constructor(e={}){this.id=BT++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=Sr.match(e)),t=>{let n=e(t);return n===void 0?null:[this,n]}}};xe.closedBy=new xe({deserialize:r=>r.split(" ")});xe.openedBy=new xe({deserialize:r=>r.split(" ")});xe.group=new xe({deserialize:r=>r.split(" ")});xe.isolate=new xe({deserialize:r=>{if(r&&r!="rtl"&&r!="ltr"&&r!="auto")throw new RangeError("Invalid value for isolate: "+r);return r||"auto"}});xe.contextHash=new xe({perNode:!0});xe.lookAhead=new xe({perNode:!0});xe.mounted=new xe({perNode:!0});var zi=class{constructor(e,t,n,i=!1){this.tree=e,this.overlay=t,this.parser=n,this.bracketed=i}static get(e){return e&&e.props&&e.props[xe.mounted.id]}},FT=Object.create(null),Sr=class r{constructor(e,t,n,i=0){this.name=e,this.props=t,this.id=n,this.flags=i}static define(e){let t=e.props&&e.props.length?Object.create(null):FT,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),i=new r(e.name||"",t,e.id,n);if(e.props){for(let s of e.props)if(Array.isArray(s)||(s=s(i)),s){if(s[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[s[0].id]=s[1]}}return i}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(xe.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let i of n.split(" "))t[i]=e[n];return n=>{for(let i=n.prop(xe.group),s=-1;s<(i?i.length:0);s++){let o=t[s<0?n.name:i[s]];if(o)return o}}}};Sr.none=new Sr("",Object.create(null),0,8);var jl=new WeakMap,Ax=new WeakMap,ot;(function(r){r[r.ExcludeBuffers=1]="ExcludeBuffers",r[r.IncludeAnonymous=2]="IncludeAnonymous",r[r.IgnoreMounts=4]="IgnoreMounts",r[r.IgnoreOverlays=8]="IgnoreOverlays",r[r.EnterBracketed=16]="EnterBracketed"})(ot||(ot={}));var Lt=class r{constructor(e,t,n,i,s){if(this.type=e,this.children=t,this.positions=n,this.length=i,this.props=null,s&&s.length){this.props=Object.create(null);for(let[o,a]of s)this.props[typeof o=="number"?o:o.id]=a}}toString(){let e=zi.get(this);if(e&&!e.overlay)return e.tree.toString();let t="";for(let n of this.children){let i=n.toString();i&&(t&&(t+=","),t+=i)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(t.length?"("+t+")":""):t}cursor(e=0){return new Go(this.topNode,e)}cursorAt(e,t=0,n=0){let i=jl.get(this)||this.topNode,s=new Go(i);return s.moveTo(e,t),jl.set(this,s._tree),s}get topNode(){return new Cn(this,0,0,null)}resolve(e,t=0){let n=jo(jl.get(this)||this.topNode,e,t,!1);return jl.set(this,n),n}resolveInner(e,t=0){let n=jo(Ax.get(this)||this.topNode,e,t,!0);return Ax.set(this,n),n}resolveStack(e,t=0){return _T(this,e,t)}iterate(e){let{enter:t,leave:n,from:i=0,to:s=this.length}=e,o=e.mode||0,a=(o&ot.IncludeAnonymous)>0;for(let l=this.cursor(o|ot.IncludeAnonymous);;){let c=!1;if(l.from<=s&&l.to>=i&&(!a&&l.type.isAnonymous||t(l)!==!1)){if(l.firstChild())continue;c=!0}for(;c&&n&&(a||!l.type.isAnonymous)&&n(l),!l.nextSibling();){if(!l.parent())return;c=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:_h(Sr.none,this.children,this.positions,0,this.children.length,0,this.length,(t,n,i)=>new r(this.type,t,n,i,this.propValues),e.makeTree||((t,n,i)=>new r(Sr.none,t,n,i)))}static build(e){return zT(e)}};Lt.empty=new Lt(Sr.none,[],[],0);var Rh=class r{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new r(this.buffer,this.index)}},oi=class r{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return Sr.none}toString(){let e=[];for(let t=0;t<this.buffer.length;)e.push(this.childString(t)),t=this.buffer[t+3];return e.join(",")}childString(e){let t=this.buffer[e],n=this.buffer[e+3],i=this.set.types[t],s=i.name;if(/\W/.test(s)&&!i.isError&&(s=JSON.stringify(s)),e+=4,n==e)return s;let o=[];for(;e<n;)o.push(this.childString(e)),e=this.buffer[e+3];return s+"("+o.join(",")+")"}findChild(e,t,n,i,s){let{buffer:o}=this,a=-1;for(let l=e;l!=t&&!(Dx(s,i,o[l+1],o[l+2])&&(a=l,n>0));l=o[l+3]);return a}slice(e,t,n){let i=this.buffer,s=new Uint16Array(t-e),o=0;for(let a=e,l=0;a<t;){s[l++]=i[a++],s[l++]=i[a++]-n;let c=s[l++]=i[a++]-n;s[l++]=i[a++]-e,o=Math.max(o,c)}return new r(s,o,this.set)}};function Dx(r,e,t,n){switch(r){case-2:return t<e;case-1:return n>=e&&t<e;case 0:return t<e&&n>e;case 1:return t<=e&&n>e;case 2:return n>e;case 4:return!0}}function jo(r,e,t,n){for(var i;r.from==r.to||(t<1?r.from>=e:r.from>e)||(t>-1?r.to<=e:r.to<e);){let o=!n&&r instanceof Cn&&r.index<0?null:r.parent;if(!o)return r;r=o}let s=n?0:ot.IgnoreOverlays;if(n)for(let o=r,a=o.parent;a;o=a,a=o.parent)o instanceof Cn&&o.index<0&&((i=a.enter(e,t,s))===null||i===void 0?void 0:i.from)!=o.from&&(r=a);for(;;){let o=r.enter(e,t,s);if(!o)return r;r=o}}var Gl=class{cursor(e=0){return new Go(this,e)}getChild(e,t=null,n=null){let i=Tx(this,e,t,n);return i.length?i[0]:null}getChildren(e,t=null,n=null){return Tx(this,e,t,n)}resolve(e,t=0){return jo(this,e,t,!1)}resolveInner(e,t=0){return jo(this,e,t,!0)}matchContext(e){return Ih(this.parent,e)}enterUnfinishedNodesBefore(e){let t=this.childBefore(e),n=this;for(;t;){let i=t.lastChild;if(!i||i.to!=t.to)break;i.type.isError&&i.from==i.to?(n=t,t=i.prevSibling):t=i}return n}get node(){return this}get next(){return this.parent}},Cn=class r extends Gl{constructor(e,t,n,i){super(),this._tree=e,this.from=t,this.index=n,this._parent=i}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(e,t,n,i,s=0){for(let o=this;;){for(let{children:a,positions:l}=o._tree,c=t>0?a.length:-1;e!=c;e+=t){let d=a[e],u=l[e]+o.from,h;if(!(!(s&ot.EnterBracketed&&d instanceof Lt&&(h=zi.get(d))&&!h.overlay&&h.bracketed&&n>=u&&n<=u+d.length)&&!Dx(i,n,u,u+d.length))){if(d instanceof oi){if(s&ot.ExcludeBuffers)continue;let f=d.findChild(0,d.buffer.length,t,n-u,i);if(f>-1)return new Uo(new Ph(o,d,e,u),null,f)}else if(s&ot.IncludeAnonymous||!d.type.isAnonymous||Fh(d)){let f;if(!(s&ot.IgnoreMounts)&&(f=zi.get(d))&&!f.overlay)return new r(f.tree,u,e,o);let p=new r(d,u,e,o);return s&ot.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?d.children.length-1:0,t,n,i,s)}}}if(s&ot.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,t,n=0){let i;if(!(n&ot.IgnoreOverlays)&&(i=zi.get(this._tree))&&i.overlay){let s=e-this.from,o=n&ot.EnterBracketed&&i.bracketed;for(let{from:a,to:l}of i.overlay)if((t>0||o?a<=s:a<s)&&(t<0||o?l>=s:l>s))return new r(i.tree,i.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,n)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}};function Tx(r,e,t,n){let i=r.cursor(),s=[];if(!i.firstChild())return s;if(t!=null){for(let o=!1;!o;)if(o=i.type.is(t),!i.nextSibling())return s}for(;;){if(n!=null&&i.type.is(n))return s;if(i.type.is(e)&&s.push(i.node),!i.nextSibling())return n==null?s:[]}}function Ih(r,e,t=e.length-1){for(let n=r;t>=0;n=n.parent){if(!n)return!1;if(!n.type.isAnonymous){if(e[t]&&e[t]!=n.name)return!1;t--}}return!0}var Ph=class{constructor(e,t,n,i){this.parent=e,this.buffer=t,this.index=n,this.start=i}},Uo=class r extends Gl{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,n){super(),this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}child(e,t,n){let{buffer:i}=this.context,s=i.findChild(this.index+4,i.buffer[this.index+3],e,t-this.context.start,n);return s<0?null:new r(this.context,this,s)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,t,n=0){if(n&ot.ExcludeBuffers)return null;let{buffer:i}=this.context,s=i.findChild(this.index+4,i.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return s<0?null:new r(this.context,this,s)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new r(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new r(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,i=this.index+4,s=n.buffer[this.index+3];if(s>i){let o=n.buffer[this.index+1];e.push(n.slice(i,s,o)),t.push(0)}return new Lt(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}};function Ox(r){if(!r.length)return null;let e=0,t=r[0];for(let s=1;s<r.length;s++){let o=r[s];(o.from>t.from||o.to<t.to)&&(t=o,e=s)}let n=t instanceof Cn&&t.index<0?null:t.parent,i=r.slice();return n?i[e]=n:i.splice(e,1),new Lh(i,t)}var Lh=class{constructor(e,t){this.heads=e,this.node=t}get next(){return Ox(this.heads)}};function _T(r,e,t){let n=r.resolveInner(e,t),i=null;for(let s=n instanceof Cn?n:n.context.parent;s;s=s.parent)if(s.index<0){let o=s.parent;(i||(i=[n])).push(o.resolve(e,t)),s=o}else{let o=zi.get(s.tree);if(o&&o.overlay&&o.overlay[0].from<=e&&o.overlay[o.overlay.length-1].to>=e){let a=new Cn(o.tree,o.overlay[0].from+s.from,-1,s);(i||(i=[n])).push(jo(a,e,t,!1))}}return i?Ox(i):n}var Go=class{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~ot.EnterBracketed,e instanceof Cn)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let n=e._parent;n;n=n._parent)this.stack.unshift(n.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:n,buffer:i}=this.buffer;return this.type=t||i.set.types[i.buffer[e]],this.from=n+i.buffer[e+1],this.to=n+i.buffer[e+2],!0}yield(e){return e?e instanceof Cn?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,n,this.mode));let{buffer:i}=this.buffer,s=i.findChild(this.index+4,i.buffer[this.index+3],e,t-this.buffer.start,n);return s<0?!1:(this.stack.push(this.index),this.yieldBuf(s))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=this.mode){return this.buffer?n&ot.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n))}parent(){if(!this.buffer)return this.yieldNode(this.mode&ot.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&ot.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let i=n<0?0:this.stack[n]+4;if(this.index!=i)return this.yieldBuf(t.findChild(i,this.index,-1,0,4))}else{let i=t.buffer[this.index+3];if(i<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(i)}return n<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:i}=this;if(i){if(e>0){if(this.index<i.buffer.buffer.length)return!1}else for(let s=0;s<this.index;s++)if(i.buffer.buffer[s+3]<this.index)return!1;({index:t,parent:n}=i)}else({index:t,_parent:n}=this._tree);for(;n;{index:t,_parent:n}=n)if(t>-1)for(let s=t+e,o=e<0?-1:n._tree.children.length;s!=o;s+=e){let a=n._tree.children[s];if(this.mode&ot.IncludeAnonymous||a instanceof oi||!a.type.isAnonymous||Fh(a))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to<e))&&this.parent(););for(;this.enterChild(1,e,t););return this}get node(){if(!this.buffer)return this._tree;let e=this.bufferNode,t=null,n=0;if(e&&e.context==this.buffer)e:for(let i=this.index,s=this.stack.length;s>=0;){for(let o=e;o;o=o._parent)if(o.index==i){if(i==this.index)return o;t=o,n=s+1;break e}i=this.stack[--s]}for(let i=n;i<this.stack.length;i++)t=new Uo(this.buffer,t,this.stack[i]);return this.bufferNode=new Uo(this.buffer,t,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(e,t){for(let n=0;;){let i=!1;if(this.type.isAnonymous||e(this)!==!1){if(this.firstChild()){n++;continue}this.type.isAnonymous||(i=!0)}for(;;){if(i&&t&&t(this),i=this.type.isAnonymous,!n)return;if(this.nextSibling())break;this.parent(),n--,i=!0}}}matchContext(e){if(!this.buffer)return Ih(this.node.parent,e);let{buffer:t}=this.buffer,{types:n}=t.set;for(let i=e.length-1,s=this.stack.length-1;i>=0;s--){if(s<0)return Ih(this._tree,e,i);let o=n[t.buffer[this.stack[s]]];if(!o.isAnonymous){if(e[i]&&e[i]!=o.name)return!1;i--}}return!0}};function Fh(r){return r.children.some(e=>e instanceof oi||!e.type.isAnonymous||Fh(e))}function zT(r){var e;let{buffer:t,nodeSet:n,maxBufferLength:i=1024,reused:s=[],minRepeatType:o=n.types.length}=r,a=Array.isArray(t)?new Rh(t,t.length):t,l=n.types,c=0,d=0;function u(C,w,k,A,S,M){let{id:D,start:O,end:H,size:E}=a,$=d,G=c;if(E<0)if(a.next(),E==-1){let Se=s[D];k.push(Se),A.push(O-C);return}else if(E==-3){c=D;return}else if(E==-4){d=D;return}else throw new RangeError(`Unrecognized record size: ${E}`);let W=l[D],he,_,ie=O-C;if(H-O<=i&&(_=g(a.pos-w,S))){let Se=new Uint16Array(_.size-_.skip),J=a.pos-_.size,ae=Se.length;for(;a.pos>J;)ae=b(_.start,Se,ae);he=new oi(Se,H-_.start,n),ie=_.start-C}else{let Se=a.pos-E;a.next();let J=[],ae=[],fe=D>=o?D:-1,Oe=0,_e=H;for(;a.pos>Se;)fe>=0&&a.id==fe&&a.size>=0?(a.end<=_e-i&&(p(J,ae,O,Oe,a.end,_e,fe,$,G),Oe=J.length,_e=a.end),a.next()):M>2500?h(O,Se,J,ae):u(O,Se,J,ae,fe,M+1);if(fe>=0&&Oe>0&&Oe<J.length&&p(J,ae,O,Oe,O,_e,fe,$,G),J.reverse(),ae.reverse(),fe>-1&&Oe>0){let ke=f(W,G);he=_h(W,J,ae,0,J.length,0,H-O,ke,ke)}else he=m(W,J,ae,H-O,$-H,G)}k.push(he),A.push(ie)}function h(C,w,k,A){let S=[],M=0,D=-1;for(;a.pos>w;){let{id:O,start:H,end:E,size:$}=a;if($>4)a.next();else{if(D>-1&&H<D)break;D<0&&(D=E-i),S.push(O,H,E),M++,a.next()}}if(M){let O=new Uint16Array(M*4),H=S[S.length-2];for(let E=S.length-3,$=0;E>=0;E-=3)O[$++]=S[E],O[$++]=S[E+1]-H,O[$++]=S[E+2]-H,O[$++]=$;k.push(new oi(O,S[2]-H,n)),A.push(H-C)}}function f(C,w){return(k,A,S)=>{let M=0,D=k.length-1,O,H;if(D>=0&&(O=k[D])instanceof Lt){if(!D&&O.type==C&&O.length==S)return O;(H=O.prop(xe.lookAhead))&&(M=A[D]+O.length+H)}return m(C,k,A,S,M,w)}}function p(C,w,k,A,S,M,D,O,H){let E=[],$=[];for(;C.length>A;)E.push(C.pop()),$.push(w.pop()+k-S);C.push(m(n.types[D],E,$,M-S,O-M,H)),w.push(S-k)}function m(C,w,k,A,S,M,D){if(M){let O=[xe.contextHash,M];D=D?[O].concat(D):[O]}if(S>25){let O=[xe.lookAhead,S];D=D?[O].concat(D):[O]}return new Lt(C,w,k,A,D)}function g(C,w){let k=a.fork(),A=0,S=0,M=0,D=k.end-i,O={size:0,start:0,skip:0};e:for(let H=k.pos-C;k.pos>H;){let E=k.size;if(k.id==w&&E>=0){O.size=A,O.start=S,O.skip=M,M+=4,A+=4,k.next();continue}let $=k.pos-E;if(E<0||$<H||k.start<D)break;let G=k.id>=o?4:0,W=k.start;for(k.next();k.pos>$;){if(k.size<0)if(k.size==-3||k.size==-4)G+=4;else break e;else k.id>=o&&(G+=4);k.next()}S=W,A+=E,M+=G}return(w<0||A==C)&&(O.size=A,O.start=S,O.skip=M),O.size>4?O:void 0}function b(C,w,k){let{id:A,start:S,end:M,size:D}=a;if(a.next(),D>=0&&A<o){let O=k;if(D>4){let H=a.pos-(D-4);for(;a.pos>H;)k=b(C,w,k)}w[--k]=O,w[--k]=M-C,w[--k]=S-C,w[--k]=A}else D==-3?c=A:D==-4&&(d=A);return k}let y=[],x=[];for(;a.pos>0;)u(r.start||0,r.bufferStart||0,y,x,-1,0);let N=(e=r.length)!==null&&e!==void 0?e:y.length?x[0]+y[0].length:0;return new Lt(l[r.topID],y.reverse(),x.reverse(),N)}var Mx=new WeakMap;function Ul(r,e){if(!r.isAnonymous||e instanceof oi||e.type!=r)return 1;let t=Mx.get(e);if(t==null){t=1;for(let n of e.children){if(n.type!=r||!(n instanceof Lt)){t=1;break}t+=Ul(r,n)}Mx.set(e,t)}return t}function _h(r,e,t,n,i,s,o,a,l){let c=0;for(let p=n;p<i;p++)c+=Ul(r,e[p]);let d=Math.ceil(c*1.5/8),u=[],h=[];function f(p,m,g,b,y){for(let x=g;x<b;){let N=x,C=m[x],w=Ul(r,p[x]);for(x++;x<b;x++){let k=Ul(r,p[x]);if(w+k>=d)break;w+=k}if(x==N+1){if(w>d){let k=p[N];f(k.children,k.positions,0,k.children.length,m[N]+y);continue}u.push(p[N])}else{let k=m[x-1]+p[x-1].length-C;u.push(_h(r,p,m,N,x,C,k,null,l))}h.push(C+y-s)}}return f(e,t,n,i,0),(a||l)(u,h,o)}var $i=class r{constructor(e,t,n,i,s=!1,o=!1){this.from=e,this.to=t,this.tree=n,this.offset=i,this.open=(s?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],n=!1){let i=[new r(0,e.length,e,0,!1,n)];for(let s of t)s.to>e.length&&i.push(s);return i}static applyChanges(e,t,n=128){if(!t.length)return e;let i=[],s=1,o=e.length?e[0]:null;for(let a=0,l=0,c=0;;a++){let d=a<t.length?t[a]:null,u=d?d.fromA:1e9;if(u-l>=n)for(;o&&o.from<u;){let h=o;if(l>=h.from||u<=h.to||c){let f=Math.max(h.from,l)-c,p=Math.min(h.to,u)-c;h=f>=p?null:new r(f,p,h.tree,h.offset+c,a>0,!!d)}if(h&&i.push(h),o.to>u)break;o=s<e.length?e[s++]:null}if(!d)break;l=d.toA,c=d.toA-d.toB}return i}},ql=class{startParse(e,t,n){return typeof e=="string"&&(e=new Bh(e)),n=n?n.length?n.map(i=>new Vo(i.from,i.to)):[new Vo(0,0)]:[new Vo(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let i=this.startParse(e,t,n);for(;;){let s=i.advance();if(s)return s}}},Bh=class{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}};var dz=new xe({perNode:!0});var $T=0,on=class r{constructor(e,t,n,i){this.name=e,this.set=t,this.base=n,this.modified=i,this.id=$T++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(e,t){let n=typeof e=="string"?e:"?";if(e instanceof r&&(t=e),t?.base)throw new Error("Can not derive from a modified tag");let i=new r(n,[],null,[]);if(i.set.push(i),t)for(let s of t.set)i.set.push(s);return i}static defineModifier(e){let t=new Xl(e);return n=>n.modified.indexOf(t)>-1?n:Xl.get(n.base||n,n.modified.concat(t).sort((i,s)=>i.id-s.id))}},HT=0,Xl=class r{constructor(e){this.name=e,this.instances=[],this.id=HT++}static get(e,t){if(!t.length)return e;let n=t[0].instances.find(a=>a.base==e&&WT(t,a.modified));if(n)return n;let i=[],s=new on(e.name,i,e,t);for(let a of t)a.instances.push(s);let o=VT(t);for(let a of e.set)if(!a.modified.length)for(let l of o)i.push(r.get(a,l));return s}};function WT(r,e){return r.length==e.length&&r.every((t,n)=>t==e[n])}function VT(r){let e=[[]];for(let t=0;t<r.length;t++)for(let n=0,i=e.length;n<i;n++)e.push(e[n].concat(r[t]));return e.sort((t,n)=>n.length-t.length)}function Px(r){let e=Object.create(null);for(let t in r){let n=r[t];Array.isArray(n)||(n=[n]);for(let i of t.split(" "))if(i){let s=[],o=2,a=i;for(let u=0;;){if(a=="..."&&u>0&&u+3==i.length){o=1;break}let h=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(a);if(!h)throw new RangeError("Invalid path: "+i);if(s.push(h[0]=="*"?"":h[0][0]=='"'?JSON.parse(h[0]):h[0]),u+=h[0].length,u==i.length)break;let f=i[u++];if(u==i.length&&f=="!"){o=0;break}if(f!="/")throw new RangeError("Invalid path: "+i);a=i.slice(u)}let l=s.length-1,c=s[l];if(!c)throw new RangeError("Invalid path: "+i);let d=new Wi(n,o,l>0?s.slice(0,l):null);e[c]=d.sort(e[c])}}return Lx.add(e)}var Lx=new xe({combine(r,e){let t,n,i;for(;r||e;){if(!r||e&&r.depth>=e.depth?(i=e,e=e.next):(i=r,r=r.next),t&&t.mode==i.mode&&!i.context&&!t.context)continue;let s=new Wi(i.tags,i.mode,i.context);t?t.next=s:n=s,t=s}return n}}),Wi=class{constructor(e,t,n,i){this.tags=e,this.mode=t,this.context=n,this.next=i}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth<this.depth?(this.next=e,this):(e.next=this.sort(e.next),e)}get depth(){return this.context?this.context.length:0}};Wi.empty=new Wi([],2,null);function Wh(r,e){let t=Object.create(null);for(let s of r)if(!Array.isArray(s.tag))t[s.tag.id]=s.class;else for(let o of s.tag)t[o.id]=s.class;let{scope:n,all:i=null}=e||{};return{style:s=>{let o=i;for(let a of s)for(let l of a.set){let c=t[l.id];if(c){o=o?o+" "+c:c;break}}return o},scope:n}}function jT(r,e){let t=null;for(let n of r){let i=n.style(e);i&&(t=t?t+" "+i:i)}return t}function Bx(r,e,t,n=0,i=r.length){let s=new $h(n,Array.isArray(e)?e:[e],t);s.highlightRange(r.cursor(),n,i,"",s.highlighters),s.flush(i)}var $h=class{constructor(e,t,n){this.at=e,this.highlighters=t,this.span=n,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,n,i,s){let{type:o,from:a,to:l}=e;if(a>=n||l<=t)return;o.isTop&&(s=this.highlighters.filter(f=>!f.scope||f.scope(o)));let c=i,d=UT(e)||Wi.empty,u=jT(s,d.tags);if(u&&(c&&(c+=" "),c+=u,d.mode==1&&(i+=(i?" ":"")+u)),this.startSpan(Math.max(t,a),c),d.opaque)return;let h=e.tree&&e.tree.prop(xe.mounted);if(h&&h.overlay){let f=e.node.enter(h.overlay[0].from+a,1),p=this.highlighters.filter(g=>!g.scope||g.scope(h.tree.type)),m=e.firstChild();for(let g=0,b=a;;g++){let y=g<h.overlay.length?h.overlay[g]:null,x=y?y.from+a:l,N=Math.max(t,b),C=Math.min(n,x);if(N<C&&m)for(;e.from<C&&(this.highlightRange(e,N,C,i,s),this.startSpan(Math.min(C,e.to),c),!(e.to>=x||!e.nextSibling())););if(!y||x>n)break;b=y.to+a,b>t&&(this.highlightRange(f.cursor(),Math.max(t,y.from+a),Math.min(n,b),"",p),this.startSpan(Math.min(n,b),c))}m&&e.parent()}else if(e.firstChild()){h&&(i="");do if(!(e.to<=t)){if(e.from>=n)break;this.highlightRange(e,t,n,i,s),this.startSpan(Math.min(n,e.to),c)}while(e.nextSibling());e.parent()}}};function UT(r){let e=r.type.prop(Lx);for(;e&&e.context&&!r.matchContext(e.context);)e=e.next;return e||null}var q=on.define,Kl=q(),ai=q(),Rx=q(ai),Ix=q(ai),li=q(),Yl=q(li),zh=q(li),En=q(),Hi=q(En),kn=q(),Nn=q(),Hh=q(),qo=q(Hh),Jl=q(),R={comment:Kl,lineComment:q(Kl),blockComment:q(Kl),docComment:q(Kl),name:ai,variableName:q(ai),typeName:Rx,tagName:q(Rx),propertyName:Ix,attributeName:q(Ix),className:q(ai),labelName:q(ai),namespace:q(ai),macroName:q(ai),literal:li,string:Yl,docString:q(Yl),character:q(Yl),attributeValue:q(Yl),number:zh,integer:q(zh),float:q(zh),bool:q(li),regexp:q(li),escape:q(li),color:q(li),url:q(li),keyword:kn,self:q(kn),null:q(kn),atom:q(kn),unit:q(kn),modifier:q(kn),operatorKeyword:q(kn),controlKeyword:q(kn),definitionKeyword:q(kn),moduleKeyword:q(kn),operator:Nn,derefOperator:q(Nn),arithmeticOperator:q(Nn),logicOperator:q(Nn),bitwiseOperator:q(Nn),compareOperator:q(Nn),updateOperator:q(Nn),definitionOperator:q(Nn),typeOperator:q(Nn),controlOperator:q(Nn),punctuation:Hh,separator:q(Hh),bracket:qo,angleBracket:q(qo),squareBracket:q(qo),paren:q(qo),brace:q(qo),content:En,heading:Hi,heading1:q(Hi),heading2:q(Hi),heading3:q(Hi),heading4:q(Hi),heading5:q(Hi),heading6:q(Hi),contentSeparator:q(En),list:q(En),quote:q(En),emphasis:q(En),strong:q(En),link:q(En),monospace:q(En),strikethrough:q(En),inserted:q(),deleted:q(),changed:q(),invalid:q(),meta:Jl,documentMeta:q(Jl),annotation:q(Jl),processingInstruction:q(Jl),definition:on.defineModifier("definition"),constant:on.defineModifier("constant"),function:on.defineModifier("function"),standard:on.defineModifier("standard"),local:on.defineModifier("local"),special:on.defineModifier("special")};for(let r in R){let e=R[r];e instanceof on&&(e.name=r)}var fz=Wh([{tag:R.link,class:"tok-link"},{tag:R.heading,class:"tok-heading"},{tag:R.emphasis,class:"tok-emphasis"},{tag:R.strong,class:"tok-strong"},{tag:R.keyword,class:"tok-keyword"},{tag:R.atom,class:"tok-atom"},{tag:R.bool,class:"tok-bool"},{tag:R.url,class:"tok-url"},{tag:R.labelName,class:"tok-labelName"},{tag:R.inserted,class:"tok-inserted"},{tag:R.deleted,class:"tok-deleted"},{tag:R.literal,class:"tok-literal"},{tag:R.string,class:"tok-string"},{tag:R.number,class:"tok-number"},{tag:[R.regexp,R.escape,R.special(R.string)],class:"tok-string2"},{tag:R.variableName,class:"tok-variableName"},{tag:R.local(R.variableName),class:"tok-variableName tok-local"},{tag:R.definition(R.variableName),class:"tok-variableName tok-definition"},{tag:R.special(R.variableName),class:"tok-variableName2"},{tag:R.definition(R.propertyName),class:"tok-propertyName tok-definition"},{tag:R.typeName,class:"tok-typeName"},{tag:R.namespace,class:"tok-namespace"},{tag:R.className,class:"tok-className"},{tag:R.macroName,class:"tok-macroName"},{tag:R.propertyName,class:"tok-propertyName"},{tag:R.operator,class:"tok-operator"},{tag:R.comment,class:"tok-comment"},{tag:R.meta,class:"tok-meta"},{tag:R.invalid,class:"tok-invalid"},{tag:R.punctuation,class:"tok-punctuation"}]);var Vh,Yo=new xe;var GT=new xe,Hr=class{constructor(e,t,n=[],i=""){this.data=e,this.name=i,Me.prototype.hasOwnProperty("tree")||Object.defineProperty(Me.prototype,"tree",{get(){return Ct(this)}}),this.parser=t,this.extension=[ci.of(this),Me.languageData.of((s,o,a)=>{let l=Fx(s,o,a),c=l.type.prop(Yo);if(!c)return[];let d=s.facet(c),u=l.type.prop(GT);if(u){let h=l.resolve(o-l.from,a);for(let f of u)if(f.test(h,s)){let p=s.facet(f.facet);return f.type=="replace"?p:p.concat(d)}}return d})].concat(n)}isActiveAt(e,t,n=-1){return Fx(e,t,n).type.prop(Yo)==this.data}findRegions(e){let t=e.facet(ci);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let n=[],i=(s,o)=>{if(s.prop(Yo)==this.data){n.push({from:o,to:o+s.length});return}let a=s.prop(xe.mounted);if(a){if(a.tree.prop(Yo)==this.data){if(a.overlay)for(let l of a.overlay)n.push({from:l.from+o,to:l.to+o});else n.push({from:o,to:o+s.length});return}else if(a.overlay){let l=n.length;if(i(a.tree,a.overlay[0].from+o),n.length>l)return}}for(let l=0;l<s.children.length;l++){let c=s.children[l];c instanceof Lt&&i(c,s.positions[l]+o)}};return i(Ct(e),0),n}get allowsNesting(){return!0}};Hr.setState=le.define();function Fx(r,e,t){let n=r.facet(ci),i=Ct(r).topNode;if(!n||n.allowsNesting)for(let s=i;s;s=s.enter(e,t,ot.ExcludeBuffers|ot.EnterBracketed))s.type.isTop&&(i=s);return i}function Ct(r){let e=r.field(Hr.state,!1);return e?e.tree:Lt.empty}var qh=class{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let n=this.cursorPos-this.string.length;return e<n||t>=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-n,t-n)}},Ko=null,Kh=class r{constructor(e,t,n=[],i,s,o,a,l){this.parser=e,this.state=t,this.fragments=n,this.tree=i,this.treeLen=s,this.viewport=o,this.skipped=a,this.scheduleOn=l,this.parse=null,this.tempSkipped=[]}static create(e,t,n){return new r(e,t,[],Lt.empty,0,n,[],null)}startParse(){return this.parser.startParse(new qh(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=Lt.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var n;if(typeof e=="number"){let i=Date.now()+e;e=()=>Date.now()>i}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t<this.state.doc.length&&this.parse.stopAt(t);;){let i=this.parse.advance();if(i)if(this.fragments=this.withoutTempSkipped($i.addTree(i,this.fragments,this.parse.stoppedAt!=null)),this.treeLen=(n=this.parse.stoppedAt)!==null&&n!==void 0?n:this.state.doc.length,this.tree=i,this.parse=null,this.treeLen<(t??this.state.doc.length))this.parse=this.startParse();else return!0;if(e())return!1}})}takeTree(){let e,t;this.parse&&(e=this.parse.parsedPos)>=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped($i.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=Ko;Ko=this;try{return e()}finally{Ko=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=_x(e,t.from,t.to);return e}changes(e,t){let{fragments:n,tree:i,treeLen:s,viewport:o,skipped:a}=this;if(this.takeTree(),!e.empty){let l=[];if(e.iterChangedRanges((c,d,u,h)=>l.push({fromA:c,toA:d,fromB:u,toB:h})),n=$i.applyChanges(n,l),i=Lt.empty,s=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){a=[];for(let c of this.skipped){let d=e.mapPos(c.from,1),u=e.mapPos(c.to,-1);d<u&&a.push({from:d,to:u})}}}return new r(this.parser,t,n,i,s,o,a,this.scheduleOn)}updateViewport(e){if(this.viewport.from==e.from&&this.viewport.to==e.to)return!1;this.viewport=e;let t=this.skipped.length;for(let n=0;n<this.skipped.length;n++){let{from:i,to:s}=this.skipped[n];i<e.to&&s>e.from&&(this.fragments=_x(this.fragments,i,s),this.skipped.splice(n--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends ql{createParse(t,n,i){let s=i[0].from,o=i[i.length-1].to;return{parsedPos:s,advance(){let l=Ko;if(l){for(let c of i)l.tempSkipped.push(c);e&&(l.scheduleOn=l.scheduleOn?Promise.all([l.scheduleOn,e]):e)}return this.parsedPos=o,new Lt(Sr.none,[],[],o-s)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return Ko}};function _x(r,e,t){return $i.applyChanges(r,[{fromA:e,toA:t,fromB:e,toB:t}])}var Xo=class r{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),n=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,n)||t.takeTree(),new r(t)}static init(e){let t=Math.min(3e3,e.doc.length),n=Kh.create(e.facet(ci).parser,e,{from:0,to:t});return n.work(20,t)||n.takeTree(),new r(n)}};Hr.state=st.define({create:Xo.init,update(r,e){for(let t of e.effects)if(t.is(Hr.setState))return t.value;return e.startState.facet(ci)!=e.state.facet(ci)?Xo.init(e.state):r.apply(e)}});var Ux=r=>{let e=setTimeout(()=>r(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(Ux=r=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(r,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});var jh=typeof navigator<"u"&&(!((Vh=navigator.scheduling)===null||Vh===void 0)&&Vh.isInputPending)?()=>navigator.scheduling.isInputPending():null,qT=Ye.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(Hr.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(Hr.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=Ux(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnd<t&&(this.chunkEnd<0||this.view.hasFocus)&&(this.chunkEnd=t+3e4,this.chunkBudget=3e3),this.chunkBudget<=0)return;let{state:n,viewport:{to:i}}=this.view,s=n.field(Hr.state);if(s.tree==s.context.tree&&s.context.isDone(i+1e5))return;let o=Date.now()+Math.min(this.chunkBudget,100,e&&!jh?Math.max(25,e.timeRemaining()-5):1e9),a=s.context.treeLen<i&&n.doc.length>i+1e3,l=s.context.work(()=>jh&&jh()||Date.now()>o,i+(a?0:1e5));this.chunkBudget-=Date.now()-t,(l||this.chunkBudget<=0)&&(s.context.takeTree(),this.view.dispatch({effects:Hr.setState.of(new Xo(s.context))})),this.chunkBudget>0&&!(l&&!a)&&this.scheduleWork(),this.checkAsyncSchedule(s.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>It(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),ci=K.define({combine(r){return r.length?r[0]:null},enables:r=>[Hr.state,qT,U.contentAttributes.compute([r],e=>{let t=e.facet(r);return t&&t.name?{"data-language":t.name}:{}})]});var KT=K.define(),Ui=K.define({combine:r=>{if(!r.length)return" ";let e=r[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(r[0]));return e}});function Zo(r){let e=r.facet(Ui);return e.charCodeAt(0)==9?r.tabSize*e.length:e.length}function Bs(r,e){let t="",n=r.tabSize,i=r.facet(Ui)[0];if(i==" "){for(;e>=n;)t+=" ",e-=n;i=" "}for(let s=0;s<e;s++)t+=i;return t}function ec(r,e){r instanceof Me&&(r=new Vi(r));for(let n of r.state.facet(KT)){let i=n(r,e);if(i!==void 0)return i}let t=Ct(r.state);return t.length>=e?JT(r,t,e):null}var Vi=class{constructor(e,t={}){this.state=e,this.options=t,this.unit=Zo(e)}lineAt(e,t=1){let n=this.state.doc.lineAt(e),{simulateBreak:i,simulateDoubleBreak:s}=this.options;return i!=null&&i>=n.from&&i<=n.to?s&&i==e?{text:"",from:e}:(t<0?i<e:i<=e)?{text:n.text.slice(i-n.from),from:i}:{text:n.text.slice(0,i-n.from),from:n.from}:n}textAfterPos(e,t=1){if(this.options.simulateDoubleBreak&&e==this.options.simulateBreak)return"";let{text:n,from:i}=this.lineAt(e,t);return n.slice(e-i,Math.min(n.length,e+100-i))}column(e,t=1){let{text:n,from:i}=this.lineAt(e,t),s=this.countColumn(n,e-i),o=this.options.overrideIndentation?this.options.overrideIndentation(i):-1;return o>-1&&(s+=o-this.countColumn(n,n.search(/\S|$/))),s}countColumn(e,t=e.length){return Bn(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:n,from:i}=this.lineAt(e,t),s=this.options.overrideIndentation;if(s){let o=s(i);if(o>-1)return o}return this.countColumn(n,n.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}},YT=new xe;function JT(r,e,t){let n=e.resolveStack(t),i=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(i!=n.node){let s=[];for(let o=i;o&&!(o.from<n.node.from||o.to>n.node.to||o.from==n.node.from&&o.type==n.node.type);o=o.parent)s.push(o);for(let o=s.length-1;o>=0;o--)n={node:s[o],next:n}}return Gx(n,r,t)}function Gx(r,e,t){for(let n=r;n;n=n.next){let i=ZT(n.node);if(i)return i(Yh.create(e,t,n))}return 0}function XT(r){return r.pos==r.options.simulateBreak&&r.options.simulateDoubleBreak}function ZT(r){let e=r.type.prop(YT);if(e)return e;let t=r.firstChild,n;if(t&&(n=t.type.prop(xe.closedBy))){let i=r.lastChild,s=i&&n.indexOf(i.name)>-1;return o=>rM(o,!0,1,void 0,s&&!XT(o)?i.from:void 0)}return r.parent==null?QT:null}function QT(){return 0}var Yh=class r extends Vi{constructor(e,t,n){super(e.state,e.options),this.base=e,this.pos=t,this.context=n}get node(){return this.context.node}static create(e,t,n){return new r(e,t,n)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let n=e.resolve(t.from);for(;n.parent&&n.parent.from==n.from;)n=n.parent;if(eM(n,e))break;t=this.state.doc.lineAt(n.from)}return this.lineIndent(t.from)}continue(){return Gx(this.context.next,this.base,this.pos)}};function eM(r,e){for(let t=e;t;t=t.parent)if(r==t)return!0;return!1}function tM(r){let e=r.node,t=e.childAfter(e.from),n=e.lastChild;if(!t)return null;let i=r.options.simulateBreak,s=r.state.doc.lineAt(t.from),o=i==null||i<=s.from?s.to:Math.min(s.to,i);for(let a=t.to;;){let l=e.childAfter(a);if(!l||l==n)return null;if(!l.type.isSkipped){if(l.from>=o)return null;let c=/^ */.exec(s.text.slice(t.to-s.from))[0].length;return{from:t.from,to:t.to+c}}a=l.to}}function rM(r,e,t,n,i){let s=r.textAfter,o=s.match(/^\s*/)[0].length,a=n&&s.slice(o,o+n.length)==n||i==r.pos+o,l=e?tM(r):null;return l?a?r.column(l.from):r.column(l.to):r.baseIndent+(a?0:r.unit*t)}var nM=200;function qx(){return Me.transactionFilter.of(r=>{if(!r.docChanged||!r.isUserEvent("input.type")&&!r.isUserEvent("input.complete"))return r;let e=r.startState.languageDataAt("indentOnInput",r.startState.selection.main.head);if(!e.length)return r;let t=r.newDoc,{head:n}=r.newSelection.main,i=t.lineAt(n);if(n>i.from+nM)return r;let s=t.sliceString(i.from,n);if(!e.some(c=>c.test(s)))return r;let{state:o}=r,a=-1,l=[];for(let{head:c}of o.selection.ranges){let d=o.doc.lineAt(c);if(d.from==a)continue;a=d.from;let u=ec(o,d.from);if(u==null)continue;let h=/^\s*/.exec(d.text)[0],f=Bs(o,u);h!=f&&l.push({from:d.from,to:d.from+h.length,insert:f})}return l.length?[r,{changes:l,sequential:!0}]:r})}var iM=K.define(),sM=new xe;function oM(r,e,t){let n=Ct(r);if(n.length<t)return null;let i=n.resolveStack(t,1),s=null;for(let o=i;o;o=o.next){let a=o.node;if(a.to<=t||a.from>t)continue;if(s&&a.from<e)break;let l=a.type.prop(sM);if(l&&(a.to<n.length-50||n.length==r.doc.length||!aM(a))){let c=l(a,r);c&&c.from<=t&&c.from>=e&&c.to>t&&(s=c)}}return s}function aM(r){let e=r.lastChild;return e&&e.to==r.to&&e.type.isError}function Zl(r,e,t){for(let n of r.facet(iM)){let i=n(r,e,t);if(i)return i}return oM(r,e,t)}function Kx(r,e){let t=e.mapPos(r.from,1),n=e.mapPos(r.to,-1);return t>=n?void 0:{from:t,to:n}}var tc=le.define({map:Kx}),Qo=le.define({map:Kx});function Yx(r){let e=[];for(let{head:t}of r.state.selection.ranges)e.some(n=>n.from<=t&&n.to>=t)||e.push(r.lineBlockAt(t));return e}var ji=st.define({create(){return Z.none},update(r,e){e.isUserEvent("delete")&&e.changes.iterChangedRanges((t,n)=>r=zx(r,t,n)),r=r.map(e.changes);for(let t of e.effects)if(t.is(tc)&&!lM(r,t.value.from,t.value.to)){let{preparePlaceholder:n}=e.state.facet(tf),i=n?Z.replace({widget:new Jh(n(e.state,t.value))}):$x;r=r.update({add:[i.range(t.value.from,t.value.to)]})}else t.is(Qo)&&(r=r.update({filter:(n,i)=>t.value.from!=n||t.value.to!=i,filterFrom:t.value.from,filterTo:t.value.to}));return e.selection&&(r=zx(r,e.selection.main.head)),r},provide:r=>U.decorations.from(r),toJSON(r,e){let t=[];return r.between(0,e.doc.length,(n,i)=>{t.push(n,i)}),t},fromJSON(r){if(!Array.isArray(r)||r.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let t=0;t<r.length;){let n=r[t++],i=r[t++];if(typeof n!="number"||typeof i!="number")throw new RangeError("Invalid JSON for fold state");e.push($x.range(n,i))}return Z.set(e,!0)}});function zx(r,e,t=e){let n=!1;return r.between(e,t,(i,s)=>{i<t&&s>e&&(n=!0)}),n?r.update({filterFrom:e,filterTo:t,filter:(i,s)=>i>=t||s<=e}):r}function Ql(r,e,t){var n;let i=null;return(n=r.field(ji,!1))===null||n===void 0||n.between(e,t,(s,o)=>{(!i||i.from>s)&&(i={from:s,to:o})}),i}function lM(r,e,t){let n=!1;return r.between(e,e,(i,s)=>{i==e&&s==t&&(n=!0)}),n}function Jx(r,e){return r.field(ji,!1)?e:e.concat(le.appendConfig.of(Qx()))}var cM=r=>{for(let e of Yx(r)){let t=Zl(r.state,e.from,e.to);if(t)return r.dispatch({effects:Jx(r.state,[tc.of(t),Xx(r,t)])}),!0}return!1},dM=r=>{if(!r.state.field(ji,!1))return!1;let e=[];for(let t of Yx(r)){let n=Ql(r.state,t.from,t.to);n&&e.push(Qo.of(n),Xx(r,n,!1))}return e.length&&r.dispatch({effects:e}),e.length>0};function Xx(r,e,t=!0){let n=r.state.doc.lineAt(e.from).number,i=r.state.doc.lineAt(e.to).number;return U.announce.of(`${r.state.phrase(t?"Folded lines":"Unfolded lines")} ${n} ${r.state.phrase("to")} ${i}.`)}var uM=r=>{let{state:e}=r,t=[];for(let n=0;n<e.doc.length;){let i=r.lineBlockAt(n),s=Zl(e,i.from,i.to);s&&t.push(tc.of(s)),n=(s?r.lineBlockAt(s.to):i).to+1}return t.length&&r.dispatch({effects:Jx(r.state,t)}),!!t.length},hM=r=>{let e=r.state.field(ji,!1);if(!e||!e.size)return!1;let t=[];return e.between(0,r.state.doc.length,(n,i)=>{t.push(Qo.of({from:n,to:i}))}),r.dispatch({effects:t}),!0};var Zx=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:cM},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:dM},{key:"Ctrl-Alt-[",run:uM},{key:"Ctrl-Alt-]",run:hM}],fM={placeholderDOM:null,preparePlaceholder:null,placeholderText:"\u2026"},tf=K.define({combine(r){return Ut(r,fM)}});function Qx(r){let e=[ji,mM];return r&&e.push(tf.of(r)),e}function ev(r,e){let{state:t}=r,n=t.facet(tf),i=o=>{let a=r.lineBlockAt(r.posAtDOM(o.target)),l=Ql(r.state,a.from,a.to);l&&r.dispatch({effects:Qo.of(l)}),o.preventDefault()};if(n.placeholderDOM)return n.placeholderDOM(r,i,e);let s=document.createElement("span");return s.textContent=n.placeholderText,s.setAttribute("aria-label",t.phrase("folded code")),s.title=t.phrase("unfold"),s.className="cm-foldPlaceholder",s.onclick=i,s}var $x=Z.replace({widget:new class extends er{toDOM(r){return ev(r,null)}}}),Jh=class extends er{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return ev(e,this.value)}},pM={openText:"\u2304",closedText:"\u203A",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1},Jo=class extends wr{constructor(e,t){super(),this.config=e,this.open=t}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let t=document.createElement("span");return t.textContent=this.open?this.config.openText:this.config.closedText,t.title=e.state.phrase(this.open?"Fold line":"Unfold line"),t}};function tv(r={}){let e={...pM,...r},t=new Jo(e,!0),n=new Jo(e,!1),i=Ye.fromClass(class{constructor(o){this.from=o.viewport.from,this.markers=this.buildMarkers(o)}update(o){(o.docChanged||o.viewportChanged||o.startState.facet(ci)!=o.state.facet(ci)||o.startState.field(ji,!1)!=o.state.field(ji,!1)||Ct(o.startState)!=Ct(o.state)||e.foldingChanged(o))&&(this.markers=this.buildMarkers(o.view))}buildMarkers(o){let a=new xr;for(let l of o.viewportLineBlocks){let c=Ql(o.state,l.from,l.to)?n:Zl(o.state,l.from,l.to)?t:null;c&&a.add(l.from,l.from,c)}return a.finish()}}),{domEventHandlers:s}=e;return[i,Oh({class:"cm-foldGutter",markers(o){var a;return((a=o.plugin(i))===null||a===void 0?void 0:a.markers)||Ne.empty},initialSpacer(){return new Jo(e,!1)},domEventHandlers:{...s,click:(o,a,l)=>{if(s.click&&s.click(o,a,l))return!0;let c=Ql(o.state,a.from,a.to);if(c)return o.dispatch({effects:Qo.of(c)}),!0;let d=Zl(o.state,a.from,a.to);return d?(o.dispatch({effects:tc.of(d)}),!0):!1}}}),Qx()]}var mM=U.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}}),Ls=class r{constructor(e,t){this.specs=e;let n;function i(a){let l=Fr.newName();return(n||(n=Object.create(null)))["."+l]=a,l}let s=typeof t.all=="string"?t.all:t.all?i(t.all):void 0,o=t.scope;this.scope=o instanceof Hr?a=>a.prop(Yo)==o.data:o?a=>a==o:void 0,this.style=Wh(e.map(a=>({tag:a.tag,class:a.class||i(Object.assign({},a,{tag:null}))})),{all:s}).style,this.module=n?new Fr(n):null,this.themeType=t.themeType}static define(e,t){return new r(e,t||{})}},Xh=K.define(),rv=K.define({combine(r){return r.length?[r[0]]:null}});function Uh(r){let e=r.facet(Xh);return e.length?e:r.facet(rv)}function rc(r,e){let t=[gM],n;return r instanceof Ls&&(r.module&&t.push(U.styleModule.of(r.module)),n=r.themeType),e?.fallback?t.push(rv.of(r)):n?t.push(Xh.computeN([U.darkTheme],i=>i.facet(U.darkTheme)==(n=="dark")?[r]:[])):t.push(Xh.of(r)),t}var Zh=class{constructor(e){this.markCache=Object.create(null),this.tree=Ct(e.state),this.decorations=this.buildDeco(e,Uh(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=Ct(e.state),n=Uh(e.state),i=n!=Uh(e.startState),{viewport:s}=e.view,o=e.changes.mapPos(this.decoratedTo,1);t.length<s.to&&!i&&t.type==this.tree.type&&o>=s.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=o):(t!=this.tree||e.viewportChanged||i)&&(this.tree=t,this.decorations=this.buildDeco(e.view,n),this.decoratedTo=s.to)}buildDeco(e,t){if(!t||!this.tree.length)return Z.none;let n=new xr;for(let{from:i,to:s}of e.visibleRanges)Bx(this.tree,t,(o,a,l)=>{n.add(o,a,this.markCache[l]||(this.markCache[l]=Z.mark({class:l})))},i,s);return n.finish()}},gM=tn.high(Ye.fromClass(Zh,{decorations:r=>r.decorations})),nv=Ls.define([{tag:R.meta,color:"#404740"},{tag:R.link,textDecoration:"underline"},{tag:R.heading,textDecoration:"underline",fontWeight:"bold"},{tag:R.emphasis,fontStyle:"italic"},{tag:R.strong,fontWeight:"bold"},{tag:R.strikethrough,textDecoration:"line-through"},{tag:R.keyword,color:"#708"},{tag:[R.atom,R.bool,R.url,R.contentSeparator,R.labelName],color:"#219"},{tag:[R.literal,R.inserted],color:"#164"},{tag:[R.string,R.deleted],color:"#a11"},{tag:[R.regexp,R.escape,R.special(R.string)],color:"#e40"},{tag:R.definition(R.variableName),color:"#00f"},{tag:R.local(R.variableName),color:"#30a"},{tag:[R.typeName,R.namespace],color:"#085"},{tag:R.className,color:"#167"},{tag:[R.special(R.variableName),R.macroName],color:"#256"},{tag:R.definition(R.propertyName),color:"#00c"},{tag:R.comment,color:"#940"},{tag:R.invalid,color:"#f00"}]),bM=U.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),iv=1e4,sv="()[]{}",ov=K.define({combine(r){return Ut(r,{afterCursor:!0,brackets:sv,maxScanDistance:iv,renderMatch:yM})}}),xM=Z.mark({class:"cm-matchingBracket"}),vM=Z.mark({class:"cm-nonmatchingBracket"});function yM(r){let e=[],t=r.matched?xM:vM;return e.push(t.range(r.start.from,r.start.to)),r.end&&e.push(t.range(r.end.from,r.end.to)),e}function Hx(r){let e=[],t=r.facet(ov);for(let n of r.selection.ranges){if(!n.empty)continue;let i=an(r,n.head,-1,t)||n.head>0&&an(r,n.head-1,1,t)||t.afterCursor&&(an(r,n.head,1,t)||n.head<r.doc.length&&an(r,n.head+1,-1,t));i&&(e=e.concat(t.renderMatch(i,r)))}return Z.set(e,!0)}var wM=Ye.fromClass(class{constructor(r){this.paused=!1,this.decorations=Hx(r.state)}update(r){(r.docChanged||r.selectionSet||this.paused)&&(r.view.composing?(this.decorations=this.decorations.map(r.changes),this.paused=!0):(this.decorations=Hx(r.state),this.paused=!1))}},{decorations:r=>r.decorations}),SM=[wM,bM];function av(r={}){return[ov.of(r),SM]}var CM=new xe;function Qh(r,e,t){let n=r.prop(e<0?xe.openedBy:xe.closedBy);if(n)return n;if(r.name.length==1){let i=t.indexOf(r.name);if(i>-1&&i%2==(e<0?1:0))return[t[i+e]]}return null}function ef(r){let e=r.type.prop(CM);return e?e(r.node):r}function an(r,e,t,n={}){let i=n.maxScanDistance||iv,s=n.brackets||sv,o=Ct(r),a=o.resolveInner(e,t);for(let l=a;l;l=l.parent){let c=Qh(l.type,t,s);if(c&&l.from<l.to){let d=ef(l);if(d&&(t>0?e>=d.from&&e<d.to:e>d.from&&e<=d.to))return kM(r,e,t,l,d,c,s)}}return NM(r,e,t,o,a.type,i,s)}function kM(r,e,t,n,i,s,o){let a=n.parent,l={from:i.from,to:i.to},c=0,d=a?.cursor();if(d&&(t<0?d.childBefore(n.from):d.childAfter(n.to)))do if(t<0?d.to<=n.from:d.from>=n.to){if(c==0&&s.indexOf(d.type.name)>-1&&d.from<d.to){let u=ef(d);return{start:l,end:u?{from:u.from,to:u.to}:void 0,matched:!0}}else if(Qh(d.type,t,o))c++;else if(Qh(d.type,-t,o)){if(c==0){let u=ef(d);return{start:l,end:u&&u.from<u.to?{from:u.from,to:u.to}:void 0,matched:!1}}c--}}while(t<0?d.prevSibling():d.nextSibling());return{start:l,matched:!1}}function NM(r,e,t,n,i,s,o){if(t<0?!e:e==r.doc.length)return null;let a=t<0?r.sliceDoc(e-1,e):r.sliceDoc(e,e+1),l=o.indexOf(a);if(l<0||l%2==0!=t>0)return null;let c={from:t<0?e-1:e,to:t>0?e+1:e},d=r.doc.iterRange(e,t>0?r.doc.length:0),u=0;for(let h=0;!d.next().done&&h<=s;){let f=d.value;t<0&&(h+=f.length);let p=e+h*t;for(let m=t>0?0:f.length-1,g=t>0?f.length:-1;m!=g;m+=t){let b=o.indexOf(f[m]);if(!(b<0||n.resolveInner(p+m,1).type!=i))if(b%2==0==t>0)u++;else{if(u==1)return{start:c,end:{from:p+m,to:p+m+1},matched:b>>1==l>>1};u--}}t>0&&(h+=f.length)}return d.done?{start:c,matched:!1}:null}var EM=Object.create(null),Wx=[Sr.none];var Vx=[],jx=Object.create(null),AM=Object.create(null);for(let[r,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])AM[r]=TM(EM,e);function Gh(r,e){Vx.indexOf(r)>-1||(Vx.push(r),console.warn(e))}function TM(r,e){let t=[];for(let a of e.split(" ")){let l=[];for(let c of a.split(".")){let d=r[c]||R[c];d?typeof d=="function"?l.length?l=l.map(d):Gh(c,`Modifier ${c} used at start of tag`):l.length?Gh(c,`Tag ${c} used as modifier`):l=Array.isArray(d)?d:[d]:Gh(c,`Unknown highlighting tag ${c}`)}for(let c of l)t.push(c)}if(!t.length)return 0;let n=e.replace(/ /g,"_"),i=n+" "+t.map(a=>a.id),s=jx[i];if(s)return s.id;let o=jx[i]=Sr.define({id:Wx.length,name:n,props:[Px({[n]:t})]});return Wx.push(o),o.id}var Sz={rtl:Z.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"rtl"},bidiIsolate:Be.RTL}),ltr:Z.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"ltr"},bidiIsolate:Be.LTR}),auto:Z.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"auto"},bidiIsolate:null})};var MM=r=>{let{state:e}=r,t=e.doc.lineAt(e.selection.main.from),n=cf(r.state,t.from);return n.line?DM(r):n.block?RM(r):!1};function lf(r,e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let i=r(e,t);return i?(n(t.update(i)),!0):!1}}var DM=lf(LM,0);var OM=lf(gv,0);var RM=lf((r,e)=>gv(r,e,PM(e)),0);function cf(r,e){let t=r.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}var ea=50;function IM(r,{open:e,close:t},n,i){let s=r.sliceDoc(n-ea,n),o=r.sliceDoc(i,i+ea),a=/\s*$/.exec(s)[0].length,l=/^\s*/.exec(o)[0].length,c=s.length-a;if(s.slice(c-e.length,c)==e&&o.slice(l,l+t.length)==t)return{open:{pos:n-a,margin:a&&1},close:{pos:i+l,margin:l&&1}};let d,u;i-n<=2*ea?d=u=r.sliceDoc(n,i):(d=r.sliceDoc(n,n+ea),u=r.sliceDoc(i-ea,i));let h=/^\s*/.exec(d)[0].length,f=/\s*$/.exec(u)[0].length,p=u.length-f-t.length;return d.slice(h,h+e.length)==e&&u.slice(p,p+t.length)==t?{open:{pos:n+h+e.length,margin:/\s/.test(d.charAt(h+e.length))?1:0},close:{pos:i-f-t.length,margin:/\s/.test(u.charAt(p-1))?1:0}}:null}function PM(r){let e=[];for(let t of r.selection.ranges){let n=r.doc.lineAt(t.from),i=t.to<=n.to?n:r.doc.lineAt(t.to);i.from>n.from&&i.from==t.to&&(i=t.to==n.to+1?n:r.doc.lineAt(t.to-1));let s=e.length-1;s>=0&&e[s].to>n.from?e[s].to=i.to:e.push({from:n.from+/^\s*/.exec(n.text)[0].length,to:i.to})}return e}function gv(r,e,t=e.selection.ranges){let n=t.map(s=>cf(e,s.from).block);if(!n.every(s=>s))return null;let i=t.map((s,o)=>IM(e,n[o],s.from,s.to));if(r!=2&&!i.every(s=>s))return{changes:e.changes(t.map((s,o)=>i[o]?[]:[{from:s.from,insert:n[o].open+" "},{from:s.to,insert:" "+n[o].close}]))};if(r!=1&&i.some(s=>s)){let s=[];for(let o=0,a;o<i.length;o++)if(a=i[o]){let l=n[o],{open:c,close:d}=a;s.push({from:c.pos-l.open.length,to:c.pos+c.margin},{from:d.pos-d.margin,to:d.pos+l.close.length})}return{changes:s}}return null}function LM(r,e,t=e.selection.ranges){let n=[],i=-1;e:for(let{from:s,to:o}of t){let a=n.length,l=1e9,c;for(let d=s;d<=o;){let u=e.doc.lineAt(d);if(c==null&&(c=cf(e,u.from).line,!c))continue e;if(u.from>i&&(s==o||o>u.from)){i=u.from;let h=/^\s*/.exec(u.text)[0].length,f=h==u.length,p=u.text.slice(h,h+c.length)==c?h:-1;h<u.text.length&&h<l&&(l=h),n.push({line:u,comment:p,token:c,indent:h,empty:f,single:!1})}d=u.to+1}if(l<1e9)for(let d=a;d<n.length;d++)n[d].indent<n[d].line.text.length&&(n[d].indent=l);n.length==a+1&&(n[a].single=!0)}if(r!=2&&n.some(s=>s.comment<0&&(!s.empty||s.single))){let s=[];for(let{line:a,token:l,indent:c,empty:d,single:u}of n)(u||!d)&&s.push({from:a.from+c,insert:l+" "});let o=e.changes(s);return{changes:o,selection:e.selection.map(o,1)}}else if(r!=1&&n.some(s=>s.comment>=0)){let s=[];for(let{line:o,comment:a,token:l}of n)if(a>=0){let c=o.from+a,d=c+l.length;o.text[d-o.from]==" "&&d++,s.push({from:c,to:d})}return{changes:s}}return null}var nf=jt.define(),BM=jt.define(),FM=K.define(),bv=K.define({combine(r){return Ut(r,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(n,i)=>e(n,i)||t(n,i)})}}),xv=st.define({create(){return Gi.empty},update(r,e){let t=e.state.facet(bv),n=e.annotation(nf);if(n){let l=ln.fromTransaction(e,n.selection),c=n.side,d=c==0?r.undone:r.done;return l?d=ic(d,d.length,t.minDepth,l):d=Sv(d,e.startState.selection),new Gi(c==0?n.rest:d,c==0?d:n.rest)}let i=e.annotation(BM);if((i=="full"||i=="before")&&(r=r.isolate()),e.annotation(mt.addToHistory)===!1)return e.changes.empty?r:r.addMapping(e.changes.desc);let s=ln.fromTransaction(e),o=e.annotation(mt.time),a=e.annotation(mt.userEvent);return s?r=r.addChanges(s,o,a,t,e):e.selection&&(r=r.addSelection(e.startState.selection,o,a,t.newGroupDelay)),(i=="full"||i=="after")&&(r=r.isolate()),r},toJSON(r){return{done:r.done.map(e=>e.toJSON()),undone:r.undone.map(e=>e.toJSON())}},fromJSON(r){return new Gi(r.done.map(ln.fromJSON),r.undone.map(ln.fromJSON))}});function vv(r={}){return[xv,bv.of(r),U.domEventHandlers({beforeinput(e,t){let n=e.inputType=="historyUndo"?yv:e.inputType=="historyRedo"?sf:null;return n?(e.preventDefault(),n(t)):!1}})]}function sc(r,e){return function({state:t,dispatch:n}){if(!e&&t.readOnly)return!1;let i=t.field(xv,!1);if(!i)return!1;let s=i.pop(r,t,e);return s?(n(s),!0):!1}}var yv=sc(0,!1),sf=sc(1,!1),_M=sc(0,!0),zM=sc(1,!0);var ln=class r{constructor(e,t,n,i,s){this.changes=e,this.effects=t,this.mapped=n,this.startSelection=i,this.selectionsAfter=s}setSelAfter(e){return new r(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,n;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(n=this.startSelection)===null||n===void 0?void 0:n.toJSON(),selectionsAfter:this.selectionsAfter.map(i=>i.toJSON())}}static fromJSON(e){return new r(e.changes&&Zt.fromJSON(e.changes),[],e.mapped&&Ln.fromJSON(e.mapped),e.startSelection&&P.fromJSON(e.startSelection),e.selectionsAfter.map(P.fromJSON))}static fromTransaction(e,t){let n=Wr;for(let i of e.startState.facet(FM)){let s=i(e);s.length&&(n=n.concat(s))}return!n.length&&e.changes.empty?null:new r(e.changes.invert(e.startState.doc),n,void 0,t||e.startState.selection,Wr)}static selection(e){return new r(void 0,Wr,void 0,void 0,e)}};function ic(r,e,t,n){let i=e+1>t+20?e-t-1:0,s=r.slice(i,e);return s.push(n),s}function $M(r,e){let t=[],n=!1;return r.iterChangedRanges((i,s)=>t.push(i,s)),e.iterChangedRanges((i,s,o,a)=>{for(let l=0;l<t.length;){let c=t[l++],d=t[l++];a>=c&&o<=d&&(n=!0)}}),n}function HM(r,e){return r.ranges.length==e.ranges.length&&r.ranges.filter((t,n)=>t.empty!=e.ranges[n].empty).length===0}function wv(r,e){return r.length?e.length?r.concat(e):r:e}var Wr=[],WM=200;function Sv(r,e){if(r.length){let t=r[r.length-1],n=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-WM));return n.length&&n[n.length-1].eq(e)?r:(n.push(e),ic(r,r.length-1,1e9,t.setSelAfter(n)))}else return[ln.selection([e])]}function VM(r){let e=r[r.length-1],t=r.slice();return t[r.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function rf(r,e){if(!r.length)return r;let t=r.length,n=Wr;for(;t;){let i=jM(r[t-1],e,n);if(i.changes&&!i.changes.empty||i.effects.length){let s=r.slice(0,t);return s[t-1]=i,s}else e=i.mapped,t--,n=i.selectionsAfter}return n.length?[ln.selection(n)]:Wr}function jM(r,e,t){let n=wv(r.selectionsAfter.length?r.selectionsAfter.map(a=>a.map(e)):Wr,t);if(!r.changes)return ln.selection(n);let i=r.changes.map(e),s=e.mapDesc(r.changes,!0),o=r.mapped?r.mapped.composeDesc(s):s;return new ln(i,le.mapEffects(r.effects,e),o,r.startSelection.map(s),n)}var UM=/^(input\.type|delete)($|\.)/,Gi=class r{constructor(e,t,n=0,i=void 0){this.done=e,this.undone=t,this.prevTime=n,this.prevUserEvent=i}isolate(){return this.prevTime?new r(this.done,this.undone):this}addChanges(e,t,n,i,s){let o=this.done,a=o[o.length-1];return a&&a.changes&&!a.changes.empty&&e.changes&&(!n||UM.test(n))&&(!a.selectionsAfter.length&&t-this.prevTime<i.newGroupDelay&&i.joinToEvent(s,$M(a.changes,e.changes))||n=="input.type.compose")?o=ic(o,o.length-1,i.minDepth,new ln(e.changes.compose(a.changes),wv(le.mapEffects(e.effects,a.changes),a.effects),a.mapped,a.startSelection,Wr)):o=ic(o,o.length,i.minDepth,e),new r(o,Wr,t,n)}addSelection(e,t,n,i){let s=this.done.length?this.done[this.done.length-1].selectionsAfter:Wr;return s.length>0&&t-this.prevTime<i&&n==this.prevUserEvent&&n&&/^select($|\.)/.test(n)&&HM(s[s.length-1],e)?this:new r(Sv(this.done,e),this.undone,t,n)}addMapping(e){return new r(rf(this.done,e),rf(this.undone,e),this.prevTime,this.prevUserEvent)}pop(e,t,n){let i=e==0?this.done:this.undone;if(i.length==0)return null;let s=i[i.length-1],o=s.selectionsAfter[0]||(s.startSelection?s.startSelection.map(s.changes.invertedDesc,1):t.selection);if(n&&s.selectionsAfter.length)return t.update({selection:s.selectionsAfter[s.selectionsAfter.length-1],annotations:nf.of({side:e,rest:VM(i),selection:o}),userEvent:e==0?"select.undo":"select.redo",scrollIntoView:!0});if(s.changes){let a=i.length==1?Wr:i.slice(0,i.length-1);return s.mapped&&(a=rf(a,s.mapped)),t.update({changes:s.changes,selection:s.startSelection,effects:s.effects,annotations:nf.of({side:e,rest:a,selection:o}),filter:!1,userEvent:e==0?"undo":"redo",scrollIntoView:!0})}else return null}};Gi.empty=new Gi(Wr,Wr);var Cv=[{key:"Mod-z",run:yv,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:sf,preventDefault:!0},{linux:"Ctrl-Shift-z",run:sf,preventDefault:!0},{key:"Mod-u",run:_M,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:zM,preventDefault:!0}];function Fs(r,e){return P.create(r.ranges.map(e),r.mainIndex)}function cn(r,e){return r.update({selection:e,scrollIntoView:!0,userEvent:"select"})}function dn({state:r,dispatch:e},t){let n=Fs(r.selection,t);return n.eq(r.selection,!0)?!1:(e(cn(r,n)),!0)}function oc(r,e){return P.cursor(e?r.to:r.from)}function kv(r,e){return dn(r,t=>t.empty?r.moveByChar(t,e):oc(t,e))}function Gt(r){return r.textDirectionAt(r.state.selection.main.head)==Be.LTR}var Nv=r=>kv(r,!Gt(r)),Ev=r=>kv(r,Gt(r));function Av(r,e){return dn(r,t=>t.empty?r.moveByGroup(t,e):oc(t,e))}var GM=r=>Av(r,!Gt(r)),qM=r=>Av(r,Gt(r));var Rz=typeof Intl<"u"&&Intl.Segmenter?new Intl.Segmenter(void 0,{granularity:"word"}):null;function KM(r,e,t){if(e.type.prop(t))return!0;let n=e.to-e.from;return n&&(n>2||/[^\s,.;:]/.test(r.sliceDoc(e.from,e.to)))||e.firstChild}function ac(r,e,t){let n=Ct(r).resolveInner(e.head),i=t?xe.closedBy:xe.openedBy;for(let l=e.head;;){let c=t?n.childAfter(l):n.childBefore(l);if(!c)break;KM(r,c,i)?n=c:l=t?c.to:c.from}let s=n.type.prop(i),o,a;return s&&(o=t?an(r,n.from,1):an(r,n.to,-1))&&o.matched?a=t?o.end.to:o.end.from:a=t?n.to:n.from,P.cursor(a,t?-1:1)}var YM=r=>dn(r,e=>ac(r.state,e,!Gt(r))),JM=r=>dn(r,e=>ac(r.state,e,Gt(r)));function Tv(r,e){return dn(r,t=>{if(!t.empty)return oc(t,e);let n=r.moveVertically(t,e);return n.head!=t.head?n:r.moveToLineBoundary(t,e)})}var Mv=r=>Tv(r,!1),Dv=r=>Tv(r,!0);function Ov(r){let e=r.scrollDOM.clientHeight<r.scrollDOM.scrollHeight-2,t=0,n=0,i;if(e){for(let s of r.state.facet(U.scrollMargins)){let o=s(r);o?.top&&(t=Math.max(o?.top,t)),o?.bottom&&(n=Math.max(o?.bottom,n))}i=r.scrollDOM.clientHeight-t-n}else i=(r.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:t,marginBottom:n,selfScroll:e,height:Math.max(r.defaultLineHeight,i-5)}}function Rv(r,e){let t=Ov(r),{state:n}=r,i=Fs(n.selection,o=>o.empty?r.moveVertically(o,e,t.height):oc(o,e));if(i.eq(n.selection))return!1;let s;if(t.selfScroll){let o=r.coordsAtPos(n.selection.main.head),a=r.scrollDOM.getBoundingClientRect(),l=a.top+t.marginTop,c=a.bottom-t.marginBottom;o&&o.top>l&&o.bottom<c&&(s=U.scrollIntoView(i.main.head,{y:"start",yMargin:o.top-l}))}return r.dispatch(cn(n,i),{effects:s}),!0}var lv=r=>Rv(r,!1),of=r=>Rv(r,!0);function di(r,e,t){let n=r.lineBlockAt(e.head),i=r.moveToLineBoundary(e,t);if(i.head==e.head&&i.head!=(t?n.to:n.from)&&(i=r.moveToLineBoundary(e,t,!1)),!t&&i.head==n.from&&n.length){let s=/^\s*/.exec(r.state.sliceDoc(n.from,Math.min(n.from+100,n.to)))[0].length;s&&e.head!=n.from+s&&(i=P.cursor(n.from+s))}return i}var XM=r=>dn(r,e=>di(r,e,!0)),ZM=r=>dn(r,e=>di(r,e,!1)),QM=r=>dn(r,e=>di(r,e,!Gt(r))),eD=r=>dn(r,e=>di(r,e,Gt(r))),tD=r=>dn(r,e=>P.cursor(r.lineBlockAt(e.head).from,1)),rD=r=>dn(r,e=>P.cursor(r.lineBlockAt(e.head).to,-1));function nD(r,e,t){let n=!1,i=Fs(r.selection,s=>{let o=an(r,s.head,-1)||an(r,s.head,1)||s.head>0&&an(r,s.head-1,1)||s.head<r.doc.length&&an(r,s.head+1,-1);if(!o||!o.end)return s;n=!0;let a=o.start.from==s.head?o.end.to:o.end.from;return t?P.range(s.anchor,a):P.cursor(a)});return n?(e(cn(r,i)),!0):!1}var iD=({state:r,dispatch:e})=>nD(r,e,!1);function Vr(r,e){let t=Fs(r.state.selection,n=>{let i=e(n);return P.range(n.anchor,i.head,i.goalColumn,i.bidiLevel||void 0,i.assoc)});return t.eq(r.state.selection)?!1:(r.dispatch(cn(r.state,t)),!0)}function Iv(r,e){return Vr(r,t=>r.moveByChar(t,e))}var Pv=r=>Iv(r,!Gt(r)),Lv=r=>Iv(r,Gt(r));function Bv(r,e){return Vr(r,t=>r.moveByGroup(t,e))}var sD=r=>Bv(r,!Gt(r)),oD=r=>Bv(r,Gt(r));var aD=r=>Vr(r,e=>ac(r.state,e,!Gt(r))),lD=r=>Vr(r,e=>ac(r.state,e,Gt(r)));function Fv(r,e){return Vr(r,t=>r.moveVertically(t,e))}var _v=r=>Fv(r,!1),zv=r=>Fv(r,!0);function $v(r,e){return Vr(r,t=>r.moveVertically(t,e,Ov(r).height))}var cv=r=>$v(r,!1),dv=r=>$v(r,!0),cD=r=>Vr(r,e=>di(r,e,!0)),dD=r=>Vr(r,e=>di(r,e,!1)),uD=r=>Vr(r,e=>di(r,e,!Gt(r))),hD=r=>Vr(r,e=>di(r,e,Gt(r))),fD=r=>Vr(r,e=>P.cursor(r.lineBlockAt(e.head).from)),pD=r=>Vr(r,e=>P.cursor(r.lineBlockAt(e.head).to)),uv=({state:r,dispatch:e})=>(e(cn(r,{anchor:0})),!0),hv=({state:r,dispatch:e})=>(e(cn(r,{anchor:r.doc.length})),!0),fv=({state:r,dispatch:e})=>(e(cn(r,{anchor:r.selection.main.anchor,head:0})),!0),pv=({state:r,dispatch:e})=>(e(cn(r,{anchor:r.selection.main.anchor,head:r.doc.length})),!0),mD=({state:r,dispatch:e})=>(e(r.update({selection:{anchor:0,head:r.doc.length},userEvent:"select"})),!0),gD=({state:r,dispatch:e})=>{let t=lc(r).map(({from:n,to:i})=>P.range(n,Math.min(i+1,r.doc.length)));return e(r.update({selection:P.create(t),userEvent:"select"})),!0},bD=({state:r,dispatch:e})=>{let t=Fs(r.selection,n=>{let i=Ct(r),s=i.resolveStack(n.from,1);if(n.empty){let o=i.resolveStack(n.from,-1);o.node.from>=s.node.from&&o.node.to<=s.node.to&&(s=o)}for(let o=s;o;o=o.next){let{node:a}=o;if((a.from<n.from&&a.to>=n.to||a.to>n.to&&a.from<=n.from)&&o.next)return P.range(a.to,a.from)}return n});return t.eq(r.selection)?!1:(e(cn(r,t)),!0)};function Hv(r,e){let{state:t}=r,n=t.selection,i=t.selection.ranges.slice();for(let s of t.selection.ranges){let o=t.doc.lineAt(s.head);if(e?o.to<r.state.doc.length:o.from>0)for(let a=s;;){let l=r.moveVertically(a,e);if(l.head<o.from||l.head>o.to){i.some(c=>c.head==l.head)||i.push(l);break}else{if(l.head==a.head)break;a=l}}}return i.length==n.ranges.length?!1:(r.dispatch(cn(t,P.create(i,i.length-1))),!0)}var xD=r=>Hv(r,!1),vD=r=>Hv(r,!0),yD=({state:r,dispatch:e})=>{let t=r.selection,n=null;return t.ranges.length>1?n=P.create([t.main]):t.main.empty||(n=P.create([P.cursor(t.main.head)])),n?(e(cn(r,n)),!0):!1};function ta(r,e){if(r.state.readOnly)return!1;let t="delete.selection",{state:n}=r,i=n.changeByRange(s=>{let{from:o,to:a}=s;if(o==a){let l=e(s);l<o?(t="delete.backward",l=nc(r,l,!1)):l>o&&(t="delete.forward",l=nc(r,l,!0)),o=Math.min(o,l),a=Math.max(a,l)}else o=nc(r,o,!1),a=nc(r,a,!0);return o==a?{range:s}:{changes:{from:o,to:a},range:P.cursor(o,o<s.head?-1:1)}});return i.changes.empty?!1:(r.dispatch(n.update(i,{scrollIntoView:!0,userEvent:t,effects:t=="delete.selection"?U.announce.of(n.phrase("Selection deleted")):void 0})),!0)}function nc(r,e,t){if(r instanceof U)for(let n of r.state.facet(U.atomicRanges).map(i=>i(r)))n.between(e,e,(i,s)=>{i<e&&s>e&&(e=t?s:i)});return e}var Wv=(r,e,t)=>ta(r,n=>{let i=n.from,{state:s}=r,o=s.doc.lineAt(i),a,l;if(t&&!e&&i>o.from&&i<o.from+200&&!/[^ \t]/.test(a=o.text.slice(0,i-o.from))){if(a[a.length-1]==" ")return i-1;let c=Bn(a,s.tabSize),d=c%Zo(s)||Zo(s);for(let u=0;u<d&&a[a.length-1-u]==" ";u++)i--;l=i}else l=lt(o.text,i-o.from,e,e)+o.from,l==i&&o.number!=(e?s.doc.lines:1)?l+=e?1:-1:!e&&/[\ufe00-\ufe0f]/.test(o.text.slice(l-o.from,i-o.from))&&(l=lt(o.text,l-o.from,!1,!1)+o.from);return l}),af=r=>Wv(r,!1,!0);var Vv=r=>Wv(r,!0,!1),jv=(r,e)=>ta(r,t=>{let n=t.head,{state:i}=r,s=i.doc.lineAt(n),o=i.charCategorizer(n);for(let a=null;;){if(n==(e?s.to:s.from)){n==t.head&&s.number!=(e?i.doc.lines:1)&&(n+=e?1:-1);break}let l=lt(s.text,n-s.from,e)+s.from,c=s.text.slice(Math.min(n,l)-s.from,Math.max(n,l)-s.from),d=o(c);if(a!=null&&d!=a)break;(c!=" "||n!=t.head)&&(a=d),n=l}return n}),Uv=r=>jv(r,!1),wD=r=>jv(r,!0);var SD=r=>ta(r,e=>{let t=r.lineBlockAt(e.head).to;return e.head<t?t:Math.min(r.state.doc.length,e.head+1)});var CD=r=>ta(r,e=>{let t=r.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),kD=r=>ta(r,e=>{let t=r.moveToLineBoundary(e,!0).head;return e.head<t?t:Math.min(r.state.doc.length,e.head+1)});var ND=({state:r,dispatch:e})=>{if(r.readOnly)return!1;let t=r.changeByRange(n=>({changes:{from:n.from,to:n.to,insert:we.of(["",""])},range:P.cursor(n.from)}));return e(r.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},ED=({state:r,dispatch:e})=>{if(r.readOnly)return!1;let t=r.changeByRange(n=>{if(!n.empty||n.from==0||n.from==r.doc.length)return{range:n};let i=n.from,s=r.doc.lineAt(i),o=i==s.from?i-1:lt(s.text,i-s.from,!1)+s.from,a=i==s.to?i+1:lt(s.text,i-s.from,!0)+s.from;return{changes:{from:o,to:a,insert:r.doc.slice(i,a).append(r.doc.slice(o,i))},range:P.cursor(a)}});return t.changes.empty?!1:(e(r.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function lc(r){let e=[],t=-1;for(let n of r.selection.ranges){let i=r.doc.lineAt(n.from),s=r.doc.lineAt(n.to);if(!n.empty&&n.to==s.from&&(s=r.doc.lineAt(n.to-1)),t>=i.number){let o=e[e.length-1];o.to=s.to,o.ranges.push(n)}else e.push({from:i.from,to:s.to,ranges:[n]});t=s.number+1}return e}function Gv(r,e,t){if(r.readOnly)return!1;let n=[],i=[];for(let s of lc(r)){if(t?s.to==r.doc.length:s.from==0)continue;let o=r.doc.lineAt(t?s.to+1:s.from-1),a=o.length+1;if(t){n.push({from:s.to,to:o.to},{from:s.from,insert:o.text+r.lineBreak});for(let l of s.ranges)i.push(P.range(Math.min(r.doc.length,l.anchor+a),Math.min(r.doc.length,l.head+a)))}else{n.push({from:o.from,to:s.from},{from:s.to,insert:r.lineBreak+o.text});for(let l of s.ranges)i.push(P.range(l.anchor-a,l.head-a))}}return n.length?(e(r.update({changes:n,scrollIntoView:!0,selection:P.create(i,r.selection.mainIndex),userEvent:"move.line"})),!0):!1}var AD=({state:r,dispatch:e})=>Gv(r,e,!1),TD=({state:r,dispatch:e})=>Gv(r,e,!0);function qv(r,e,t){if(r.readOnly)return!1;let n=[];for(let s of lc(r))t?n.push({from:s.from,insert:r.doc.slice(s.from,s.to)+r.lineBreak}):n.push({from:s.to,insert:r.lineBreak+r.doc.slice(s.from,s.to)});let i=r.changes(n);return e(r.update({changes:i,selection:r.selection.map(i,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}var MD=({state:r,dispatch:e})=>qv(r,e,!1),DD=({state:r,dispatch:e})=>qv(r,e,!0),OD=r=>{if(r.state.readOnly)return!1;let{state:e}=r,t=e.changes(lc(e).map(({from:i,to:s})=>(i>0?i--:s<e.doc.length&&s++,{from:i,to:s}))),n=Fs(e.selection,i=>{let s;if(r.lineWrapping){let o=r.lineBlockAt(i.head),a=r.coordsAtPos(i.head,i.assoc||1);a&&(s=o.bottom+r.documentTop-a.bottom+r.defaultLineHeight/2)}return r.moveVertically(i,!0,s)}).map(t);return r.dispatch({changes:t,selection:n,scrollIntoView:!0,userEvent:"delete.line"}),!0};function RD(r,e){if(/\(\)|\[\]|\{\}/.test(r.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=Ct(r).resolveInner(e),n=t.childBefore(e),i=t.childAfter(e),s;return n&&i&&n.to<=e&&i.from>=e&&(s=n.type.prop(xe.closedBy))&&s.indexOf(i.name)>-1&&r.doc.lineAt(n.to).from==r.doc.lineAt(i.from).from&&!/\S/.test(r.sliceDoc(n.to,i.from))?{from:n.to,to:i.from}:null}var mv=Kv(!1),ID=Kv(!0);function Kv(r){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(i=>{let{from:s,to:o}=i,a=e.doc.lineAt(s),l=!r&&s==o&&RD(e,s);r&&(s=o=(o<=a.to?a:e.doc.lineAt(o)).to);let c=new Vi(e,{simulateBreak:s,simulateDoubleBreak:!!l}),d=ec(c,s);for(d==null&&(d=Bn(/^\s*/.exec(e.doc.lineAt(s).text)[0],e.tabSize));o<a.to&&/\s/.test(a.text[o-a.from]);)o++;l?{from:s,to:o}=l:s>a.from&&s<a.from+100&&!/\S/.test(a.text.slice(0,s))&&(s=a.from);let u=["",Bs(e,d)];return l&&u.push(Bs(e,c.lineIndent(a.from,-1))),{changes:{from:s,to:o,insert:we.of(u)},range:P.cursor(s+1+u[1].length)}});return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0}}function df(r,e){let t=-1;return r.changeByRange(n=>{let i=[];for(let o=n.from;o<=n.to;){let a=r.doc.lineAt(o);a.number>t&&(n.empty||n.to>a.from)&&(e(a,i,n),t=a.number),o=a.to+1}let s=r.changes(i);return{changes:i,range:P.range(s.mapPos(n.anchor,1),s.mapPos(n.head,1))}})}var PD=({state:r,dispatch:e})=>{if(r.readOnly)return!1;let t=Object.create(null),n=new Vi(r,{overrideIndentation:s=>{let o=t[s];return o??-1}}),i=df(r,(s,o,a)=>{let l=ec(n,s.from);if(l==null)return;/\S/.test(s.text)||(l=0);let c=/^\s*/.exec(s.text)[0],d=Bs(r,l);(c!=d||a.from<s.from+c.length)&&(t[s.from]=l,o.push({from:s.from,to:s.from+c.length,insert:d}))});return i.changes.empty||e(r.update(i,{userEvent:"indent"})),!0},Yv=({state:r,dispatch:e})=>r.readOnly?!1:(e(r.update(df(r,(t,n)=>{n.push({from:t.from,insert:r.facet(Ui)})}),{userEvent:"input.indent"})),!0),Jv=({state:r,dispatch:e})=>r.readOnly?!1:(e(r.update(df(r,(t,n)=>{let i=/^\s*/.exec(t.text)[0];if(!i)return;let s=Bn(i,r.tabSize),o=0,a=Bs(r,Math.max(0,s-Zo(r)));for(;o<i.length&&o<a.length&&i.charCodeAt(o)==a.charCodeAt(o);)o++;n.push({from:t.from+o,to:t.from+i.length,insert:a.slice(o)})}),{userEvent:"delete.dedent"})),!0),LD=r=>(r.setTabFocusMode(),!0);var BD=[{key:"Ctrl-b",run:Nv,shift:Pv,preventDefault:!0},{key:"Ctrl-f",run:Ev,shift:Lv},{key:"Ctrl-p",run:Mv,shift:_v},{key:"Ctrl-n",run:Dv,shift:zv},{key:"Ctrl-a",run:tD,shift:fD},{key:"Ctrl-e",run:rD,shift:pD},{key:"Ctrl-d",run:Vv},{key:"Ctrl-h",run:af},{key:"Ctrl-k",run:SD},{key:"Ctrl-Alt-h",run:Uv},{key:"Ctrl-o",run:ND},{key:"Ctrl-t",run:ED},{key:"Ctrl-v",run:of}],FD=[{key:"ArrowLeft",run:Nv,shift:Pv,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:GM,shift:sD,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:QM,shift:uD,preventDefault:!0},{key:"ArrowRight",run:Ev,shift:Lv,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:qM,shift:oD,preventDefault:!0},{mac:"Cmd-ArrowRight",run:eD,shift:hD,preventDefault:!0},{key:"ArrowUp",run:Mv,shift:_v,preventDefault:!0},{mac:"Cmd-ArrowUp",run:uv,shift:fv},{mac:"Ctrl-ArrowUp",run:lv,shift:cv},{key:"ArrowDown",run:Dv,shift:zv,preventDefault:!0},{mac:"Cmd-ArrowDown",run:hv,shift:pv},{mac:"Ctrl-ArrowDown",run:of,shift:dv},{key:"PageUp",run:lv,shift:cv},{key:"PageDown",run:of,shift:dv},{key:"Home",run:ZM,shift:dD,preventDefault:!0},{key:"Mod-Home",run:uv,shift:fv},{key:"End",run:XM,shift:cD,preventDefault:!0},{key:"Mod-End",run:hv,shift:pv},{key:"Enter",run:mv,shift:mv},{key:"Mod-a",run:mD},{key:"Backspace",run:af,shift:af,preventDefault:!0},{key:"Delete",run:Vv,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:Uv,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:wD,preventDefault:!0},{mac:"Mod-Backspace",run:CD,preventDefault:!0},{mac:"Mod-Delete",run:kD,preventDefault:!0}].concat(BD.map(r=>({mac:r.key,run:r.run,shift:r.shift}))),Xv=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:YM,shift:aD},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:JM,shift:lD},{key:"Alt-ArrowUp",run:AD},{key:"Shift-Alt-ArrowUp",run:MD},{key:"Alt-ArrowDown",run:TD},{key:"Shift-Alt-ArrowDown",run:DD},{key:"Mod-Alt-ArrowUp",run:xD},{key:"Mod-Alt-ArrowDown",run:vD},{key:"Escape",run:yD},{key:"Mod-Enter",run:ID},{key:"Alt-l",mac:"Ctrl-l",run:gD},{key:"Mod-i",run:bD,preventDefault:!0},{key:"Mod-[",run:Jv},{key:"Mod-]",run:Yv},{key:"Mod-Alt-\\",run:PD},{key:"Shift-Mod-k",run:OD},{key:"Shift-Mod-\\",run:iD},{key:"Mod-/",run:MM},{key:"Alt-A",run:OM},{key:"Ctrl-m",mac:"Shift-Alt-m",run:LD}].concat(FD),Zv={key:"Tab",run:Yv,shift:Jv};var Qv=typeof String.prototype.normalize=="function"?r=>r.normalize("NFKD"):r=>r,hi=class{constructor(e,t,n=0,i=e.length,s,o){this.test=o,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(n,i),this.bufferStart=n,this.normalize=s?a=>s(Qv(a)):Qv,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return Rt(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=wo(e),n=this.bufferStart+this.bufferPos;this.bufferPos+=vr(e);let i=this.normalize(t);if(i.length)for(let s=0,o=n;;s++){let a=i.charCodeAt(s),l=this.match(a,o,this.bufferPos+this.bufferStart);if(s==i.length-1){if(l)return this.value=l,this;break}o==n&&s<t.length&&t.charCodeAt(s)==a&&o++}}}match(e,t,n){let i=null;for(let s=0;s<this.matches.length;s+=2){let o=this.matches[s],a=!1;this.query.charCodeAt(o)==e&&(o==this.query.length-1?i={from:this.matches[s+1],to:n}:(this.matches[s]++,a=!0)),a||(this.matches.splice(s,2),s-=2)}return this.query.charCodeAt(0)==e&&(this.query.length==1?i={from:t,to:n}:this.matches.push(1,t)),i&&this.test&&!this.test(i.from,i.to,this.buffer,this.bufferStart)&&(i=null),i}};typeof Symbol<"u"&&(hi.prototype[Symbol.iterator]=function(){return this});var ry={from:-1,to:-1,match:/.*/.exec("")},gf="gm"+(/x/.unicode==null?"":"u"),uc=class{constructor(e,t,n,i=0,s=e.length){if(this.text=e,this.to=s,this.curLine="",this.done=!1,this.value=ry,/\\[sWDnr]|\n|\r|\[\^/.test(t))return new fc(e,t,n,i,s);this.re=new RegExp(t,gf+(n?.ignoreCase?"i":"")),this.test=n?.test,this.iter=e.iter();let o=e.lineAt(i);this.curLineStart=o.from,this.matchPos=pc(e,i),this.getLine(this.curLineStart)}getLine(e){this.iter.next(e),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let n=this.curLineStart+t.index,i=n+t[0].length;if(this.matchPos=pc(this.text,i+(n==i?1:0)),n==this.curLineStart+this.curLine.length&&this.nextLine(),(n<i||n>this.value.to)&&(!this.test||this.test(n,i,t)))return this.value={from:n,to:i,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),e=0;else return this.done=!0,this}}},uf=new WeakMap,hc=class r{constructor(e,t){this.from=e,this.text=t}get to(){return this.from+this.text.length}static get(e,t,n){let i=uf.get(e);if(!i||i.from>=n||i.to<=t){let a=new r(t,e.sliceString(t,n));return uf.set(e,a),a}if(i.from==t&&i.to==n)return i;let{text:s,from:o}=i;return o>t&&(s=e.sliceString(t,o)+s,o=t),i.to<n&&(s+=e.sliceString(i.to,n)),uf.set(e,new r(o,s)),new r(t,s.slice(t-o,n-o))}},fc=class{constructor(e,t,n,i,s){this.text=e,this.to=s,this.done=!1,this.value=ry,this.matchPos=pc(e,i),this.re=new RegExp(t,gf+(n?.ignoreCase?"i":"")),this.test=n?.test,this.flat=hc.get(e,i,this.chunkEnd(i+5e3))}chunkEnd(e){return e>=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let n=this.flat.from+t.index,i=n+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(n,i,t)))return this.value={from:n,to:i,match:t},this.matchPos=pc(this.text,i+(n==i?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=hc.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}};typeof Symbol<"u"&&(uc.prototype[Symbol.iterator]=fc.prototype[Symbol.iterator]=function(){return this});function _D(r){try{return new RegExp(r,gf),!0}catch{return!1}}function pc(r,e){if(e>=r.length)return e;let t=r.lineAt(e),n;for(;e<t.to&&(n=t.text.charCodeAt(e-t.from))>=56320&&n<57344;)e++;return e}var zD=r=>{let{state:e}=r,t=String(e.doc.lineAt(r.state.selection.main.head).number),{close:n,result:i}=wx(r,{label:e.phrase("Go to line"),input:{type:"text",name:"line",value:t},focus:!0,submitLabel:e.phrase("go")});return i.then(s=>{let o=s&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(s.elements.line.value);if(!o){r.dispatch({effects:n});return}let a=e.doc.lineAt(e.selection.main.head),[,l,c,d,u]=o,h=d?+d.slice(1):0,f=c?+c:a.number;if(c&&u){let g=f/100;l&&(g=g*(l=="-"?-1:1)+a.number/e.doc.lines),f=Math.round(e.doc.lines*g)}else c&&l&&(f=f*(l=="-"?-1:1)+a.number);let p=e.doc.line(Math.max(1,Math.min(e.doc.lines,f))),m=P.cursor(p.from+Math.max(0,Math.min(h,p.length)));r.dispatch({effects:[n,U.scrollIntoView(m.from,{y:"center"})],selection:m})}),!0},$D={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},ny=K.define({combine(r){return Ut(r,$D,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function iy(r){let e=[UD,jD];return r&&e.push(ny.of(r)),e}var HD=Z.mark({class:"cm-selectionMatch"}),WD=Z.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function ey(r,e,t,n){return(t==0||r(e.sliceDoc(t-1,t))!=$e.Word)&&(n==e.doc.length||r(e.sliceDoc(n,n+1))!=$e.Word)}function VD(r,e,t,n){return r(e.sliceDoc(t,t+1))==$e.Word&&r(e.sliceDoc(n-1,n))==$e.Word}var jD=Ye.fromClass(class{constructor(r){this.decorations=this.getDeco(r)}update(r){(r.selectionSet||r.docChanged||r.viewportChanged)&&(this.decorations=this.getDeco(r.view))}getDeco(r){let e=r.state.facet(ny),{state:t}=r,n=t.selection;if(n.ranges.length>1)return Z.none;let i=n.main,s,o=null;if(i.empty){if(!e.highlightWordAroundCursor)return Z.none;let l=t.wordAt(i.head);if(!l)return Z.none;o=t.charCategorizer(i.head),s=t.sliceDoc(l.from,l.to)}else{let l=i.to-i.from;if(l<e.minSelectionLength||l>200)return Z.none;if(e.wholeWords){if(s=t.sliceDoc(i.from,i.to),o=t.charCategorizer(i.head),!(ey(o,t,i.from,i.to)&&VD(o,t,i.from,i.to)))return Z.none}else if(s=t.sliceDoc(i.from,i.to),!s)return Z.none}let a=[];for(let l of r.visibleRanges){let c=new hi(t.doc,s,l.from,l.to);for(;!c.next().done;){let{from:d,to:u}=c.value;if((!o||ey(o,t,d,u))&&(i.empty&&d<=i.from&&u>=i.to?a.push(WD.range(d,u)):(d>=i.to||u<=i.from)&&a.push(HD.range(d,u)),a.length>e.maxMatches))return Z.none}}return Z.set(a)}},{decorations:r=>r.decorations}),UD=U.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),GD=({state:r,dispatch:e})=>{let{selection:t}=r,n=P.create(t.ranges.map(i=>r.wordAt(i.head)||P.cursor(i.head)),t.mainIndex);return n.eq(t)?!1:(e(r.update({selection:n})),!0)};function qD(r,e){let{main:t,ranges:n}=r.selection,i=r.wordAt(t.head),s=i&&i.from==t.from&&i.to==t.to;for(let o=!1,a=new hi(r.doc,e,n[n.length-1].to);;)if(a.next(),a.done){if(o)return null;a=new hi(r.doc,e,0,Math.max(0,n[n.length-1].from-1)),o=!0}else{if(o&&n.some(l=>l.from==a.value.from))continue;if(s){let l=r.wordAt(a.value.from);if(!l||l.from!=a.value.from||l.to!=a.value.to)continue}return a.value}}var KD=({state:r,dispatch:e})=>{let{ranges:t}=r.selection;if(t.some(s=>s.from===s.to))return GD({state:r,dispatch:e});let n=r.sliceDoc(t[0].from,t[0].to);if(r.selection.ranges.some(s=>r.sliceDoc(s.from,s.to)!=n))return!1;let i=qD(r,n);return i?(e(r.update({selection:r.selection.addRange(P.range(i.from,i.to),!1),effects:U.scrollIntoView(i.to)})),!0):!1},$s=K.define({combine(r){return Ut(r,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new mf(e),scrollToMatch:e=>U.scrollIntoView(e)})}});var mc=class{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||_D(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,n)=>n=="n"?`
79
+ `:n=="r"?"\r":n=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new ff(this):new hf(this)}getCursor(e,t=0,n){let i=e.doc?e:Me.create({doc:e});return n==null&&(n=i.doc.length),this.regexp?zs(this,i,t,n):_s(this,i,t,n)}},gc=class{constructor(e){this.spec=e}};function YD(r,e,t){return(n,i,s,o)=>{if(t&&!t(n,i,s,o))return!1;let a=n>=o&&i<=o+s.length?s.slice(n-o,i-o):e.doc.sliceString(n,i);return r(a,e,n,i)}}function _s(r,e,t,n){let i;return r.wholeWord&&(i=JD(e.doc,e.charCategorizer(e.selection.main.head))),r.test&&(i=YD(r.test,e,i)),new hi(e.doc,r.unquoted,t,n,r.caseSensitive?void 0:s=>s.toLowerCase(),i)}function JD(r,e){return(t,n,i,s)=>((s>t||s+i.length<n)&&(s=Math.max(0,t-2),i=r.sliceString(s,Math.min(r.length,n+2))),(e(bc(i,t-s))!=$e.Word||e(xc(i,t-s))!=$e.Word)&&(e(xc(i,n-s))!=$e.Word||e(bc(i,n-s))!=$e.Word))}var hf=class extends gc{constructor(e){super(e)}nextMatch(e,t,n){let i=_s(this.spec,e,n,e.doc.length).nextOverlapping();if(i.done){let s=Math.min(e.doc.length,t+this.spec.unquoted.length);i=_s(this.spec,e,0,s).nextOverlapping()}return i.done||i.value.from==t&&i.value.to==n?null:i.value}prevMatchInRange(e,t,n){for(let i=n;;){let s=Math.max(t,i-1e4-this.spec.unquoted.length),o=_s(this.spec,e,s,i),a=null;for(;!o.nextOverlapping().done;)a=o.value;if(a)return a;if(s==t)return null;i-=1e4}}prevMatch(e,t,n){let i=this.prevMatchInRange(e,0,t);return i||(i=this.prevMatchInRange(e,Math.max(0,n-this.spec.unquoted.length),e.doc.length)),i&&(i.from!=t||i.to!=n)?i:null}getReplacement(e){return this.spec.unquote(this.spec.replace)}matchAll(e,t){let n=_s(this.spec,e,0,e.doc.length),i=[];for(;!n.next().done;){if(i.length>=t)return null;i.push(n.value)}return i}highlight(e,t,n,i){let s=_s(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(n+this.spec.unquoted.length,e.doc.length));for(;!s.next().done;)i(s.value.from,s.value.to)}};function XD(r,e,t){return(n,i,s)=>(!t||t(n,i,s))&&r(s[0],e,n,i)}function zs(r,e,t,n){let i;return r.wholeWord&&(i=ZD(e.charCategorizer(e.selection.main.head))),r.test&&(i=XD(r.test,e,i)),new uc(e.doc,r.search,{ignoreCase:!r.caseSensitive,test:i},t,n)}function bc(r,e){return r.slice(lt(r,e,!1),e)}function xc(r,e){return r.slice(e,lt(r,e))}function ZD(r){return(e,t,n)=>!n[0].length||(r(bc(n.input,n.index))!=$e.Word||r(xc(n.input,n.index))!=$e.Word)&&(r(xc(n.input,n.index+n[0].length))!=$e.Word||r(bc(n.input,n.index+n[0].length))!=$e.Word)}var ff=class extends gc{nextMatch(e,t,n){let i=zs(this.spec,e,n,e.doc.length).next();return i.done&&(i=zs(this.spec,e,0,t).next()),i.done?null:i.value}prevMatchInRange(e,t,n){for(let i=1;;i++){let s=Math.max(t,n-i*1e4),o=zs(this.spec,e,s,n),a=null;for(;!o.next().done;)a=o.value;if(a&&(s==t||a.from>s+10))return a;if(s==t)return null}}prevMatch(e,t,n){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,n,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(t,n)=>{if(n=="&")return e.match[0];if(n=="$")return"$";for(let i=n.length;i>0;i--){let s=+n.slice(0,i);if(s>0&&s<e.match.length)return e.match[s]+n.slice(i)}return t})}matchAll(e,t){let n=zs(this.spec,e,0,e.doc.length),i=[];for(;!n.next().done;){if(i.length>=t)return null;i.push(n.value)}return i}highlight(e,t,n,i){let s=zs(this.spec,e,Math.max(0,t-250),Math.min(n+250,e.doc.length));for(;!s.next().done;)i(s.value.from,s.value.to)}},na=le.define(),bf=le.define(),ui=st.define({create(r){return new ra(pf(r).create(),null)},update(r,e){for(let t of e.effects)t.is(na)?r=new ra(t.value.create(),r.panel):t.is(bf)&&(r=new ra(r.query,t.value?xf:null));return r},provide:r=>_i.from(r,e=>e.panel)});var ra=class{constructor(e,t){this.query=e,this.panel=t}},QD=Z.mark({class:"cm-searchMatch"}),e5=Z.mark({class:"cm-searchMatch cm-searchMatch-selected"}),t5=Ye.fromClass(class{constructor(r){this.view=r,this.decorations=this.highlight(r.state.field(ui))}update(r){let e=r.state.field(ui);(e!=r.startState.field(ui)||r.docChanged||r.selectionSet||r.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:r,panel:e}){if(!e||!r.spec.valid)return Z.none;let{view:t}=this,n=new xr;for(let i=0,s=t.visibleRanges,o=s.length;i<o;i++){let{from:a,to:l}=s[i];for(;i<o-1&&l>s[i+1].from-500;)l=s[++i].to;r.highlight(t.state,a,l,(c,d)=>{let u=t.state.selection.ranges.some(h=>h.from==c&&h.to==d);n.add(c,d,u?e5:QD)})}return n.finish()}},{decorations:r=>r.decorations});function ia(r){return e=>{let t=e.state.field(ui,!1);return t&&t.query.spec.valid?r(e,t):ay(e)}}var vc=ia((r,{query:e})=>{let{to:t}=r.state.selection.main,n=e.nextMatch(r.state,t,t);if(!n)return!1;let i=P.single(n.from,n.to),s=r.state.facet($s);return r.dispatch({selection:i,effects:[vf(r,n),s.scrollToMatch(i.main,r)],userEvent:"select.search"}),oy(r),!0}),yc=ia((r,{query:e})=>{let{state:t}=r,{from:n}=t.selection.main,i=e.prevMatch(t,n,n);if(!i)return!1;let s=P.single(i.from,i.to),o=r.state.facet($s);return r.dispatch({selection:s,effects:[vf(r,i),o.scrollToMatch(s.main,r)],userEvent:"select.search"}),oy(r),!0}),r5=ia((r,{query:e})=>{let t=e.matchAll(r.state,1e3);return!t||!t.length?!1:(r.dispatch({selection:P.create(t.map(n=>P.range(n.from,n.to))),userEvent:"select.search.matches"}),!0)}),n5=({state:r,dispatch:e})=>{let t=r.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:n,to:i}=t.main,s=[],o=0;for(let a=new hi(r.doc,r.sliceDoc(n,i));!a.next().done;){if(s.length>1e3)return!1;a.value.from==n&&(o=s.length),s.push(P.range(a.value.from,a.value.to))}return e(r.update({selection:P.create(s,o),userEvent:"select.search.matches"})),!0},ty=ia((r,{query:e})=>{let{state:t}=r,{from:n,to:i}=t.selection.main;if(t.readOnly)return!1;let s=e.nextMatch(t,n,n);if(!s)return!1;let o=s,a=[],l,c,d=[];o.from==n&&o.to==i&&(c=t.toText(e.getReplacement(o)),a.push({from:o.from,to:o.to,insert:c}),o=e.nextMatch(t,o.from,o.to),d.push(U.announce.of(t.phrase("replaced match on line $",t.doc.lineAt(n).number)+".")));let u=r.state.changes(a);return o&&(l=P.single(o.from,o.to).map(u),d.push(vf(r,o)),d.push(t.facet($s).scrollToMatch(l.main,r))),r.dispatch({changes:u,selection:l,effects:d,userEvent:"input.replace"}),!0}),i5=ia((r,{query:e})=>{if(r.state.readOnly)return!1;let t=e.matchAll(r.state,1e9).map(i=>{let{from:s,to:o}=i;return{from:s,to:o,insert:e.getReplacement(i)}});if(!t.length)return!1;let n=r.state.phrase("replaced $ matches",t.length)+".";return r.dispatch({changes:t,effects:U.announce.of(n),userEvent:"input.replace.all"}),!0});function xf(r){return r.state.facet($s).createPanel(r)}function pf(r,e){var t,n,i,s,o;let a=r.selection.main,l=a.empty||a.to>a.from+100?"":r.sliceDoc(a.from,a.to);if(e&&!l)return e;let c=r.facet($s);return new mc({search:((t=e?.literal)!==null&&t!==void 0?t:c.literal)?l:l.replace(/\n/g,"\\n"),caseSensitive:(n=e?.caseSensitive)!==null&&n!==void 0?n:c.caseSensitive,literal:(i=e?.literal)!==null&&i!==void 0?i:c.literal,regexp:(s=e?.regexp)!==null&&s!==void 0?s:c.regexp,wholeWord:(o=e?.wholeWord)!==null&&o!==void 0?o:c.wholeWord})}function sy(r){let e=Wo(r,xf);return e&&e.dom.querySelector("[main-field]")}function oy(r){let e=sy(r);e&&e==r.root.activeElement&&e.select()}var ay=r=>{let e=r.state.field(ui,!1);if(e&&e.panel){let t=sy(r);if(t&&t!=r.root.activeElement){let n=pf(r.state,e.query.spec);n.valid&&r.dispatch({effects:na.of(n)}),t.focus(),t.select()}}else r.dispatch({effects:[bf.of(!0),e?na.of(pf(r.state,e.query.spec)):le.appendConfig.of(o5)]});return!0},ly=r=>{let e=r.state.field(ui,!1);if(!e||!e.panel)return!1;let t=Wo(r,xf);return t&&t.dom.contains(r.root.activeElement)&&r.focus(),r.dispatch({effects:bf.of(!1)}),!0},cy=[{key:"Mod-f",run:ay,scope:"editor search-panel"},{key:"F3",run:vc,shift:yc,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:vc,shift:yc,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:ly,scope:"editor search-panel"},{key:"Mod-Shift-l",run:n5},{key:"Mod-Alt-g",run:zD},{key:"Mod-d",run:KD,preventDefault:!0}],mf=class{constructor(e){this.view=e;let t=this.query=e.state.field(ui).query.spec;this.commit=this.commit.bind(this),this.searchField=De("input",{value:t.search,placeholder:Cr(e,"Find"),"aria-label":Cr(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=De("input",{value:t.replace,placeholder:Cr(e,"Replace"),"aria-label":Cr(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=De("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=De("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=De("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit});function n(i,s,o){return De("button",{class:"cm-button",name:i,onclick:s,type:"button"},o)}this.dom=De("div",{onkeydown:i=>this.keydown(i),class:"cm-search"},[this.searchField,n("next",()=>vc(e),[Cr(e,"next")]),n("prev",()=>yc(e),[Cr(e,"previous")]),n("select",()=>r5(e),[Cr(e,"all")]),De("label",null,[this.caseField,Cr(e,"match case")]),De("label",null,[this.reField,Cr(e,"regexp")]),De("label",null,[this.wordField,Cr(e,"by word")]),...e.state.readOnly?[]:[De("br"),this.replaceField,n("replace",()=>ty(e),[Cr(e,"replace")]),n("replaceAll",()=>i5(e),[Cr(e,"replace all")])],De("button",{name:"close",onclick:()=>ly(e),"aria-label":Cr(e,"close"),type:"button"},["\xD7"])])}commit(){let e=new mc({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:na.of(e)}))}keydown(e){ox(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?yc:vc)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),ty(this.view))}update(e){for(let t of e.transactions)for(let n of t.effects)n.is(na)&&!n.value.eq(this.query)&&this.setQuery(n.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet($s).top}};function Cr(r,e){return r.state.phrase(e)}var cc=30,dc=/[\s\.,:;?!]/;function vf(r,{from:e,to:t}){let n=r.state.doc.lineAt(e),i=r.state.doc.lineAt(t).to,s=Math.max(n.from,e-cc),o=Math.min(i,t+cc),a=r.state.sliceDoc(s,o);if(s!=n.from){for(let l=0;l<cc;l++)if(!dc.test(a[l+1])&&dc.test(a[l])){a=a.slice(l);break}}if(o!=i){for(let l=a.length-1;l>a.length-cc;l--)if(!dc.test(a[l-1])&&dc.test(a[l])){a=a.slice(0,l);break}}return U.announce.of(`${r.state.phrase("current match")}. ${a} ${r.state.phrase("on line")} ${n.number}.`)}var s5=U.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),o5=[ui,tn.low(t5),s5];var Sc=class{constructor(e,t,n,i){this.state=e,this.pos=t,this.explicit=n,this.view=i,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let t=Ct(this.state).resolveInner(this.pos,-1);for(;t&&e.indexOf(t.name)<0;)t=t.parent;return t?{from:t.from,to:this.pos,text:this.state.sliceDoc(t.from,this.pos),type:t.type}:null}matchBefore(e){let t=this.state.doc.lineAt(this.pos),n=Math.max(t.from,this.pos-250),i=t.text.slice(n-t.from,this.pos-t.from),s=i.search(by(e,!1));return s<0?null:{from:n+s,to:this.pos,text:i.slice(s)}}get aborted(){return this.abortListeners==null}addEventListener(e,t,n){e=="abort"&&this.abortListeners&&(this.abortListeners.push(t),n&&n.onDocChange&&(this.abortOnDocChange=!0))}};function dy(r){let e=Object.keys(r).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function a5(r){let e=Object.create(null),t=Object.create(null);for(let{label:i}of r){e[i[0]]=!0;for(let s=1;s<i.length;s++)t[i[s]]=!0}let n=dy(e)+dy(t)+"*$";return[new RegExp("^"+n),new RegExp(n)]}function l5(r){let e=r.map(i=>typeof i=="string"?{label:i}:i),[t,n]=e.every(i=>/^\w+$/.test(i.label))?[/\w*$/,/\w+$/]:a5(e);return i=>{let s=i.matchBefore(n);return s||i.explicit?{from:s?s.from:i.pos,options:e,validFor:t}:null}}var Cc=class{constructor(e,t,n,i){this.completion=e,this.source=t,this.match=n,this.score=i}};function Ki(r){return r.selection.main.from}function by(r,e){var t;let{source:n}=r,i=e&&n[0]!="^",s=n[n.length-1]!="$";return!i&&!s?r:new RegExp(`${i?"^":""}(?:${n})${s?"$":""}`,(t=r.flags)!==null&&t!==void 0?t:r.ignoreCase?"i":"")}var xy=jt.define();function c5(r,e,t,n){let{main:i}=r.selection,s=t-i.from,o=n-i.from;return{...r.changeByRange(a=>{if(a!=i&&t!=n&&r.sliceDoc(a.from+s,a.from+o)!=r.sliceDoc(t,n))return{range:a};let l=r.toText(e);return{changes:{from:a.from+s,to:n==i.from?a.to:a.from+o,insert:l},range:P.cursor(a.from+s+l.length)}}),scrollIntoView:!0,userEvent:"input.complete"}}var uy=new WeakMap;function d5(r){if(!Array.isArray(r))return r;let e=uy.get(r);return e||uy.set(r,e=l5(r)),e}var kc=le.define(),sa=le.define(),Cf=class{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let t=0;t<e.length;){let n=Rt(e,t),i=vr(n);this.chars.push(n);let s=e.slice(t,t+i),o=s.toUpperCase();this.folded.push(Rt(o==s?s.toLowerCase():o,0)),t+=i}this.astral=e.length!=this.chars.length}ret(e,t){return this.score=e,this.matched=t,this}match(e){if(this.pattern.length==0)return this.ret(-100,[]);if(e.length<this.pattern.length)return null;let{chars:t,folded:n,any:i,precise:s,byWord:o}=this;if(t.length==1){let y=Rt(e,0),x=vr(y),N=x==e.length?0:-100;if(y!=t[0])if(y==n[0])N+=-200;else return null;return this.ret(N,[0,x])}let a=e.indexOf(this.pattern);if(a==0)return this.ret(e.length==this.pattern.length?0:-100,[0,this.pattern.length]);let l=t.length,c=0;if(a<0){for(let y=0,x=Math.min(e.length,200);y<x&&c<l;){let N=Rt(e,y);(N==t[c]||N==n[c])&&(i[c++]=y),y+=vr(N)}if(c<l)return null}let d=0,u=0,h=!1,f=0,p=-1,m=-1,g=/[a-z]/.test(e),b=!0;for(let y=0,x=Math.min(e.length,200),N=0;y<x&&u<l;){let C=Rt(e,y);a<0&&(d<l&&C==t[d]&&(s[d++]=y),f<l&&(C==t[f]||C==n[f]?(f==0&&(p=y),m=y+1,f++):f=0));let w,k=C<255?C>=48&&C<=57||C>=97&&C<=122?2:C>=65&&C<=90?1:0:(w=wo(C))!=w.toLowerCase()?1:w!=w.toUpperCase()?2:0;(!y||k==1&&g||N==0&&k!=0)&&(t[u]==C||n[u]==C&&(h=!0)?o[u++]=y:o.length&&(b=!1)),N=k,y+=vr(C)}return u==l&&o[0]==0&&b?this.result(-100+(h?-200:0),o,e):f==l&&p==0?this.ret(-200-e.length+(m==e.length?0:-100),[0,m]):a>-1?this.ret(-700-e.length,[a,a+this.pattern.length]):f==l?this.ret(-900-e.length,[p,m]):u==l?this.result(-100+(h?-200:0)+-700+(b?0:-1100),o,e):t.length==2?null:this.result((i[0]?-700:0)+-200+-1100,i,e)}result(e,t,n){let i=[],s=0;for(let o of t){let a=o+(this.astral?vr(Rt(n,o)):1);s&&i[s-1]==o?i[s-1]=a:(i[s++]=o,i[s++]=a)}return this.ret(e-n.length,i)}},kf=class{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length<this.pattern.length)return null;let t=e.slice(0,this.pattern.length),n=t==this.pattern?0:t.toLowerCase()==this.folded?-200:null;return n==null?null:(this.matched=[0,t.length],this.score=n+(e.length==this.pattern.length?0:-100),this)}},kt=K.define({combine(r){return Ut(r,{activateOnTyping:!0,activateOnCompletion:()=>!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:u5,filterStrict:!1,compareCompletions:(e,t)=>(e.sortText||e.label).localeCompare(t.sortText||t.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,tooltipClass:(e,t)=>n=>hy(e(n),t(n)),optionClass:(e,t)=>n=>hy(e(n),t(n)),addToOptions:(e,t)=>e.concat(t),filterStrict:(e,t)=>e||t})}});function hy(r,e){return r?e?r+" "+e:r:e}function u5(r,e,t,n,i,s){let o=r.textDirection==Be.RTL,a=o,l=!1,c="top",d,u,h=e.left-i.left,f=i.right-e.right,p=n.right-n.left,m=n.bottom-n.top;if(a&&h<Math.min(p,f)?a=!1:!a&&f<Math.min(p,h)&&(a=!0),p<=(a?h:f))d=Math.max(i.top,Math.min(t.top,i.bottom-m))-e.top,u=Math.min(400,a?h:f);else{l=!0,u=Math.min(400,(o?e.right:i.right-e.left)-30);let y=i.bottom-e.bottom;y>=m||y>e.top?d=t.bottom-e.top:(c="bottom",d=e.bottom-t.top)}let g=(e.bottom-e.top)/s.offsetHeight,b=(e.right-e.left)/s.offsetWidth;return{style:`${c}: ${d/g}px; max-width: ${u/b}px`,class:"cm-completionInfo-"+(l?o?"left-narrow":"right-narrow":a?"left":"right")}}var Mf=le.define();function h5(r){let e=r.addToOptions.slice();return r.icons&&e.push({render(t){let n=document.createElement("div");return n.classList.add("cm-completionIcon"),t.type&&n.classList.add(...t.type.split(/\s+/g).map(i=>"cm-completionIcon-"+i)),n.setAttribute("aria-hidden","true"),n},position:20}),e.push({render(t,n,i,s){let o=document.createElement("span");o.className="cm-completionLabel";let a=t.displayLabel||t.label,l=0;for(let c=0;c<s.length;){let d=s[c++],u=s[c++];d>l&&o.appendChild(document.createTextNode(a.slice(l,d)));let h=o.appendChild(document.createElement("span"));h.appendChild(document.createTextNode(a.slice(d,u))),h.className="cm-completionMatchedText",l=u}return l<a.length&&o.appendChild(document.createTextNode(a.slice(l))),o},position:50},{render(t){if(!t.detail)return null;let n=document.createElement("span");return n.className="cm-completionDetail",n.textContent=t.detail,n},position:80}),e.sort((t,n)=>t.position-n.position).map(t=>t.render)}function yf(r,e,t){if(r<=t)return{from:0,to:r};if(e<0&&(e=0),e<=r>>1){let i=Math.floor(e/t);return{from:i*t,to:(i+1)*t}}let n=Math.floor((r-e)/t);return{from:r-(n+1)*t,to:r-n*t}}var Nf=class{constructor(e,t,n){this.view=e,this.stateField=t,this.applyCompletion=n,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:l=>this.placeInfo(l),key:this},this.space=null,this.currentClass="";let i=e.state.field(t),{options:s,selected:o}=i.open,a=e.state.facet(kt);this.optionContent=h5(a),this.optionClass=a.optionClass,this.tooltipClass=a.tooltipClass,this.range=yf(s.length,o,a.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",l=>{let{options:c}=e.state.field(t).open;for(let d=l.target,u;d&&d!=this.dom;d=d.parentNode)if(d.nodeName=="LI"&&(u=/-(\d+)$/.exec(d.id))&&+u[1]<c.length){this.applyCompletion(e,c[+u[1]]),l.preventDefault();return}if(l.target==this.list){let d=this.list.classList.contains("cm-completionListIncompleteTop")&&l.clientY<this.list.firstChild.getBoundingClientRect().top?this.range.from-1:this.list.classList.contains("cm-completionListIncompleteBottom")&&l.clientY>this.list.lastChild.getBoundingClientRect().bottom?this.range.to:null;d!=null&&(e.dispatch({effects:Mf.of(d)}),l.preventDefault())}}),this.dom.addEventListener("focusout",l=>{let c=e.state.field(this.stateField,!1);c&&c.tooltip&&e.state.facet(kt).closeOnBlur&&l.relatedTarget!=e.contentDOM&&e.dispatch({effects:sa.of(null)})}),this.showOptions(s,i.id)}mount(){this.updateSel()}showOptions(e,t){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,t,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){var t;let n=e.state.field(this.stateField),i=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),n!=i){let{options:s,selected:o,disabled:a}=n.open;(!i.open||i.open.options!=s)&&(this.range=yf(s.length,o,e.state.facet(kt).maxRenderedOptions),this.showOptions(s,n.id)),this.updateSel(),a!=((t=i.open)===null||t===void 0?void 0:t.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!a)}}updateTooltipClass(e){let t=this.tooltipClass(e);if(t!=this.currentClass){for(let n of this.currentClass.split(" "))n&&this.dom.classList.remove(n);for(let n of t.split(" "))n&&this.dom.classList.add(n);this.currentClass=t}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),t=e.open;(t.selected>-1&&t.selected<this.range.from||t.selected>=this.range.to)&&(this.range=yf(t.options.length,t.selected,this.view.state.facet(kt).maxRenderedOptions),this.showOptions(t.options,e.id));let n=this.updateSelectedOption(t.selected);if(n){this.destroyInfo();let{completion:i}=t.options[t.selected],{info:s}=i;if(!s)return;let o=typeof s=="string"?document.createTextNode(s):s(i);if(!o)return;"then"in o?o.then(a=>{a&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(a,i)}).catch(a=>It(this.view.state,a,"completion info")):(this.addInfoPane(o,i),n.setAttribute("aria-describedby",this.info.id))}}addInfoPane(e,t){this.destroyInfo();let n=this.info=document.createElement("div");if(n.className="cm-tooltip cm-completionInfo",n.id="cm-completionInfo-"+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)n.appendChild(e),this.infoDestroy=null;else{let{dom:i,destroy:s}=e;n.appendChild(i),this.infoDestroy=s||null}this.dom.appendChild(n),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let t=null;for(let n=this.list.firstChild,i=this.range.from;n;n=n.nextSibling,i++)n.nodeName!="LI"||!n.id?i--:i==e?n.hasAttribute("aria-selected")||(n.setAttribute("aria-selected","true"),t=n):n.hasAttribute("aria-selected")&&(n.removeAttribute("aria-selected"),n.removeAttribute("aria-describedby"));return t&&p5(this.list,t),t}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),n=this.info.getBoundingClientRect(),i=e.getBoundingClientRect(),s=this.space;if(!s){let o=this.dom.ownerDocument.documentElement;s={left:0,top:0,right:o.clientWidth,bottom:o.clientHeight}}return i.top>Math.min(s.bottom,t.bottom)-10||i.bottom<Math.max(s.top,t.top)+10?null:this.view.state.facet(kt).positionInfo(this.view,t,i,n,s,this.dom)}placeInfo(e){this.info&&(e?(e.style&&(this.info.style.cssText=e.style),this.info.className="cm-tooltip cm-completionInfo "+(e.class||"")):this.info.style.cssText="top: -1e6px")}createListBox(e,t,n){let i=document.createElement("ul");i.id=t,i.setAttribute("role","listbox"),i.setAttribute("aria-expanded","true"),i.setAttribute("aria-label",this.view.state.phrase("Completions")),i.addEventListener("mousedown",o=>{o.target==i&&o.preventDefault()});let s=null;for(let o=n.from;o<n.to;o++){let{completion:a,match:l}=e[o],{section:c}=a;if(c){let h=typeof c=="string"?c:c.name;if(h!=s&&(o>n.from||n.from==0))if(s=h,typeof c!="string"&&c.header)i.appendChild(c.header(c));else{let f=i.appendChild(document.createElement("completion-section"));f.textContent=h}}let d=i.appendChild(document.createElement("li"));d.id=t+"-"+o,d.setAttribute("role","option");let u=this.optionClass(a);u&&(d.className=u);for(let h of this.optionContent){let f=h(a,this.view.state,this.view,l);f&&d.appendChild(f)}}return n.from&&i.classList.add("cm-completionListIncompleteTop"),n.to<e.length&&i.classList.add("cm-completionListIncompleteBottom"),i}destroyInfo(){this.info&&(this.infoDestroy&&this.infoDestroy(),this.info.remove(),this.info=null)}destroy(){this.destroyInfo()}};function f5(r,e){return t=>new Nf(t,r,e)}function p5(r,e){let t=r.getBoundingClientRect(),n=e.getBoundingClientRect(),i=t.height/r.offsetHeight;n.top<t.top?r.scrollTop-=(t.top-n.top)/i:n.bottom>t.bottom&&(r.scrollTop+=(n.bottom-t.bottom)/i)}function fy(r){return(r.boost||0)*100+(r.apply?10:0)+(r.info?5:0)+(r.type?1:0)}function m5(r,e){let t=[],n=null,i=null,s=d=>{t.push(d);let{section:u}=d.completion;if(u){n||(n=[]);let h=typeof u=="string"?u:u.name;n.some(f=>f.name==h)||n.push(typeof u=="string"?{name:h}:u)}},o=e.facet(kt);for(let d of r)if(d.hasResult()){let u=d.result.getMatch;if(d.result.filter===!1)for(let h of d.result.options)s(new Cc(h,d.source,u?u(h):[],1e9-t.length));else{let h=e.sliceDoc(d.from,d.to),f,p=o.filterStrict?new kf(h):new Cf(h);for(let m of d.result.options)if(f=p.match(m.label)){let g=m.displayLabel?u?u(m,f.matched):[]:f.matched,b=f.score+(m.boost||0);if(s(new Cc(m,d.source,g,b)),typeof m.section=="object"&&m.section.rank==="dynamic"){let{name:y}=m.section;i||(i=Object.create(null)),i[y]=Math.max(b,i[y]||-1e9)}}}}if(n){let d=Object.create(null),u=0,h=(f,p)=>(f.rank==="dynamic"&&p.rank==="dynamic"?i[p.name]-i[f.name]:0)||(typeof f.rank=="number"?f.rank:1e9)-(typeof p.rank=="number"?p.rank:1e9)||(f.name<p.name?-1:1);for(let f of n.sort(h))u-=1e5,d[f.name]=u;for(let f of t){let{section:p}=f.completion;p&&(f.score+=d[typeof p=="string"?p:p.name])}}let a=[],l=null,c=o.compareCompletions;for(let d of t.sort((u,h)=>h.score-u.score||c(u.completion,h.completion))){let u=d.completion;!l||l.label!=u.label||l.detail!=u.detail||l.type!=null&&u.type!=null&&l.type!=u.type||l.apply!=u.apply||l.boost!=u.boost?a.push(d):fy(d.completion)>fy(l)&&(a[a.length-1]=d),l=d.completion}return a}var Ef=class r{constructor(e,t,n,i,s,o){this.options=e,this.attrs=t,this.tooltip=n,this.timestamp=i,this.selected=s,this.disabled=o}setSelected(e,t){return e==this.selected||e>=this.options.length?this:new r(this.options,py(t,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,t,n,i,s,o){if(i&&!o&&e.some(c=>c.isPending))return i.setDisabled();let a=m5(e,t);if(!a.length)return i&&e.some(c=>c.isPending)?i.setDisabled():null;let l=t.facet(kt).selectOnOpen?0:-1;if(i&&i.selected!=l&&i.selected!=-1){let c=i.options[i.selected].completion;for(let d=0;d<a.length;d++)if(a[d].completion==c){l=d;break}}return new r(a,py(n,l),{pos:e.reduce((c,d)=>d.hasResult()?Math.min(c,d.from):c,1e8),create:w5,above:s.aboveCursor},i?i.timestamp:Date.now(),l,!1)}map(e){return new r(this.options,this.attrs,{...this.tooltip,pos:e.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new r(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}},Af=class r{constructor(e,t,n){this.active=e,this.id=t,this.open=n}static start(){return new r(v5,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:t}=e,n=t.facet(kt),s=(n.override||t.languageDataAt("autocomplete",Ki(t)).map(d5)).map(l=>(this.active.find(d=>d.source==l)||new Wn(l,this.active.some(d=>d.state!=0)?1:0)).update(e,n));s.length==this.active.length&&s.every((l,c)=>l==this.active[c])&&(s=this.active);let o=this.open,a=e.effects.some(l=>l.is(Df));o&&e.docChanged&&(o=o.map(e.changes)),e.selection||s.some(l=>l.hasResult()&&e.changes.touchesRange(l.from,l.to))||!g5(s,this.active)||a?o=Ef.build(s,t,this.id,o,n,a):o&&o.disabled&&!s.some(l=>l.isPending)&&(o=null),!o&&s.every(l=>!l.isPending)&&s.some(l=>l.hasResult())&&(s=s.map(l=>l.hasResult()?new Wn(l.source,0):l));for(let l of e.effects)l.is(Mf)&&(o=o&&o.setSelected(l.value,this.id));return s==this.active&&o==this.open?this:new r(s,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?b5:x5}};function g5(r,e){if(r==e)return!0;for(let t=0,n=0;;){for(;t<r.length&&!r[t].hasResult();)t++;for(;n<e.length&&!e[n].hasResult();)n++;let i=t==r.length,s=n==e.length;if(i||s)return i==s;if(r[t++].result!=e[n++].result)return!1}}var b5={"aria-autocomplete":"list"},x5={};function py(r,e){let t={"aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":r};return e>-1&&(t["aria-activedescendant"]=r+"-"+e),t}var v5=[];function vy(r,e){if(r.isUserEvent("input.complete")){let n=r.annotation(xy);if(n&&e.activateOnCompletion(n))return 12}let t=r.isUserEvent("input.type");return t&&e.activateOnTyping?5:t?1:r.isUserEvent("delete.backward")?2:r.selection?8:r.docChanged?16:0}var Wn=class r{constructor(e,t,n=!1){this.source=e,this.state=t,this.explicit=n}hasResult(){return!1}get isPending(){return this.state==1}update(e,t){let n=vy(e,t),i=this;(n&8||n&16&&this.touches(e))&&(i=new r(i.source,0)),n&4&&i.state==0&&(i=new r(this.source,1)),i=i.updateFor(e,n);for(let s of e.effects)if(s.is(kc))i=new r(i.source,1,s.value);else if(s.is(sa))i=new r(i.source,0);else if(s.is(Df))for(let o of s.value)o.source==i.source&&(i=o);return i}updateFor(e,t){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(Ki(e.state))}},Nc=class r extends Wn{constructor(e,t,n,i,s,o){super(e,3,t),this.limit=n,this.result=i,this.from=s,this.to=o}hasResult(){return!0}updateFor(e,t){var n;if(!(t&3))return this.map(e.changes);let i=this.result;i.map&&!e.changes.empty&&(i=i.map(i,e.changes));let s=e.changes.mapPos(this.from),o=e.changes.mapPos(this.to,1),a=Ki(e.state);if(a>o||!i||t&2&&(Ki(e.startState)==this.from||a<this.limit))return new Wn(this.source,t&4?1:0);let l=e.changes.mapPos(this.limit);return y5(i.validFor,e.state,s,o)?new r(this.source,this.explicit,l,i,s,o):i.update&&(i=i.update(i,s,o,new Sc(e.state,a,!1)))?new r(this.source,this.explicit,l,i,i.from,(n=i.to)!==null&&n!==void 0?n:Ki(e.state)):new Wn(this.source,1,this.explicit)}map(e){return e.empty?this:(this.result.map?this.result.map(this.result,e):this.result)?new r(this.source,this.explicit,e.mapPos(this.limit),this.result,e.mapPos(this.from),e.mapPos(this.to,1)):new Wn(this.source,0)}touches(e){return e.changes.touchesRange(this.from,this.to)}};function y5(r,e,t,n){if(!r)return!1;let i=e.sliceDoc(t,n);return typeof r=="function"?r(i,t,n,e):by(r,!0).test(i)}var Df=le.define({map(r,e){return r.map(t=>t.map(e))}}),ur=st.define({create(){return Af.start()},update(r,e){return r.update(e)},provide:r=>[Ho.from(r,e=>e.tooltip),U.contentAttributes.from(r,e=>e.attrs)]});function Of(r,e){let t=e.completion.apply||e.completion.label,n=r.state.field(ur).active.find(i=>i.source==e.source);return n instanceof Nc?(typeof t=="string"?r.dispatch({...c5(r.state,t,n.from,n.to),annotations:xy.of(e.completion)}):t(r,e.completion,n.from,n.to),!0):!1}var w5=f5(ur,Of);function wc(r,e="option"){return t=>{let n=t.state.field(ur,!1);if(!n||!n.open||n.open.disabled||Date.now()-n.open.timestamp<t.state.facet(kt).interactionDelay)return!1;let i=1,s;e=="page"&&(s=Dh(t,n.open.tooltip))&&(i=Math.max(2,Math.floor(s.dom.offsetHeight/s.dom.querySelector("li").offsetHeight)-1));let{length:o}=n.open.options,a=n.open.selected>-1?n.open.selected+i*(r?1:-1):r?0:o-1;return a<0?a=e=="page"?0:o-1:a>=o&&(a=e=="page"?o-1:0),t.dispatch({effects:Mf.of(a)}),!0}}var S5=r=>{let e=r.state.field(ur,!1);return r.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestamp<r.state.facet(kt).interactionDelay?!1:Of(r,e.open.options[e.open.selected])},wf=r=>r.state.field(ur,!1)?(r.dispatch({effects:kc.of(!0)}),!0):!1,C5=r=>{let e=r.state.field(ur,!1);return!e||!e.active.some(t=>t.state!=0)?!1:(r.dispatch({effects:sa.of(null)}),!0)},Tf=class{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}},k5=50,N5=1e3,E5=Ye.fromClass(class{constructor(r){this.view=r,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of r.state.field(ur).active)e.isPending&&this.startQuery(e)}update(r){let e=r.state.field(ur),t=r.state.facet(kt);if(!r.selectionSet&&!r.docChanged&&r.startState.field(ur)==e)return;let n=r.transactions.some(s=>{let o=vy(s,t);return o&8||(s.selection||s.docChanged)&&!(o&3)});for(let s=0;s<this.running.length;s++){let o=this.running[s];if(n||o.context.abortOnDocChange&&r.docChanged||o.updates.length+r.transactions.length>k5&&Date.now()-o.time>N5){for(let a of o.context.abortListeners)try{a()}catch(l){It(this.view.state,l)}o.context.abortListeners=null,this.running.splice(s--,1)}else o.updates.push(...r.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),r.transactions.some(s=>s.effects.some(o=>o.is(kc)))&&(this.pendingStart=!0);let i=this.pendingStart?50:t.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(s=>s.isPending&&!this.running.some(o=>o.active.source==s.source))?setTimeout(()=>this.startUpdate(),i):-1,this.composing!=0)for(let s of r.transactions)s.isUserEvent("input.type")?this.composing=2:this.composing==2&&s.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:r}=this.view,e=r.field(ur);for(let t of e.active)t.isPending&&!this.running.some(n=>n.active.source==t.source)&&this.startQuery(t);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(kt).updateSyncTime))}startQuery(r){let{state:e}=this.view,t=Ki(e),n=new Sc(e,t,r.explicit,this.view),i=new Tf(r,n);this.running.push(i),Promise.resolve(r.source(n)).then(s=>{i.context.aborted||(i.done=s||null,this.scheduleAccept())},s=>{this.view.dispatch({effects:sa.of(null)}),It(this.view.state,s)})}scheduleAccept(){this.running.every(r=>r.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(kt).updateSyncTime))}accept(){var r;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(kt),n=this.view.state.field(ur);for(let i=0;i<this.running.length;i++){let s=this.running[i];if(s.done===void 0)continue;if(this.running.splice(i--,1),s.done){let a=Ki(s.updates.length?s.updates[0].startState:this.view.state),l=Math.min(a,s.done.from+(s.active.explicit?0:1)),c=new Nc(s.active.source,s.active.explicit,l,s.done,s.done.from,(r=s.done.to)!==null&&r!==void 0?r:a);for(let d of s.updates)c=c.update(d,t);if(c.hasResult()){e.push(c);continue}}let o=n.active.find(a=>a.source==s.active.source);if(o&&o.isPending)if(s.done==null){let a=new Wn(s.active.source,0);for(let l of s.updates)a=a.update(l,t);a.isPending||e.push(a)}else this.startQuery(o)}(e.length||n.open&&n.open.disabled)&&this.view.dispatch({effects:Df.of(e)})}},{eventHandlers:{blur(r){let e=this.view.state.field(ur,!1);if(e&&e.tooltip&&this.view.state.facet(kt).closeOnBlur){let t=e.open&&Dh(this.view,e.open.tooltip);(!t||!t.dom.contains(r.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:sa.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:kc.of(!1)}),20),this.composing=0}}}),A5=typeof navigator=="object"&&/Win/.test(navigator.platform),T5=tn.highest(U.domEventHandlers({keydown(r,e){let t=e.state.field(ur,!1);if(!t||!t.open||t.open.disabled||t.open.selected<0||r.key.length>1||r.ctrlKey&&!(A5&&r.altKey)||r.metaKey)return!1;let n=t.open.options[t.open.selected],i=t.active.find(o=>o.source==n.source),s=n.completion.commitCharacters||i.result.commitCharacters;return s&&s.indexOf(r.key)>-1&&Of(e,n),!1}})),M5=U.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"\xB7\xB7\xB7"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'\u0192'"}},".cm-completionIcon-class":{"&:after":{content:"'\u25CB'"}},".cm-completionIcon-interface":{"&:after":{content:"'\u25CC'"}},".cm-completionIcon-variable":{"&:after":{content:"'\u{1D465}'"}},".cm-completionIcon-constant":{"&:after":{content:"'\u{1D436}'"}},".cm-completionIcon-type":{"&:after":{content:"'\u{1D461}'"}},".cm-completionIcon-enum":{"&:after":{content:"'\u222A'"}},".cm-completionIcon-property":{"&:after":{content:"'\u25A1'"}},".cm-completionIcon-keyword":{"&:after":{content:"'\u{1F511}\uFE0E'"}},".cm-completionIcon-namespace":{"&:after":{content:"'\u25A2'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});var oa={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},qi=le.define({map(r,e){let t=e.mapPos(r,-1,Ot.TrackAfter);return t??void 0}}),Rf=new class extends Br{};Rf.startSide=1;Rf.endSide=-1;var yy=st.define({create(){return Ne.empty},update(r,e){if(r=r.map(e.changes),e.selection){let t=e.state.doc.lineAt(e.selection.main.head);r=r.update({filter:n=>n>=t.from&&n<=t.to})}for(let t of e.effects)t.is(qi)&&(r=r.update({add:[Rf.range(t.value,t.value+1)]}));return r}});function wy(){return[O5,yy]}var Sf="()[]{}<>\xAB\xBB\xBB\xAB\uFF3B\uFF3D\uFF5B\uFF5D";function Sy(r){for(let e=0;e<Sf.length;e+=2)if(Sf.charCodeAt(e)==r)return Sf.charAt(e+1);return wo(r<128?r:r+1)}function Cy(r,e){return r.languageDataAt("closeBrackets",e)[0]||oa}var D5=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),O5=U.inputHandler.of((r,e,t,n)=>{if((D5?r.composing:r.compositionStarted)||r.state.readOnly)return!1;let i=r.state.selection.main;if(n.length>2||n.length==2&&vr(Rt(n,0))==1||e!=i.from||t!=i.to)return!1;let s=I5(r.state,n);return s?(r.dispatch(s),!0):!1}),R5=({state:r,dispatch:e})=>{if(r.readOnly)return!1;let n=Cy(r,r.selection.main.head).brackets||oa.brackets,i=null,s=r.changeByRange(o=>{if(o.empty){let a=P5(r.doc,o.head);for(let l of n)if(l==a&&Ec(r.doc,o.head)==Sy(Rt(l,0)))return{changes:{from:o.head-l.length,to:o.head+l.length},range:P.cursor(o.head-l.length)}}return{range:i=o}});return i||e(r.update(s,{scrollIntoView:!0,userEvent:"delete.backward"})),!i},ky=[{key:"Backspace",run:R5}];function I5(r,e){let t=Cy(r,r.selection.main.head),n=t.brackets||oa.brackets;for(let i of n){let s=Sy(Rt(i,0));if(e==i)return s==i?F5(r,i,n.indexOf(i+i+i)>-1,t):L5(r,i,s,t.before||oa.before);if(e==s&&Ny(r,r.selection.main.from))return B5(r,i,s)}return null}function Ny(r,e){let t=!1;return r.field(yy).between(0,r.doc.length,n=>{n==e&&(t=!0)}),t}function Ec(r,e){let t=r.sliceString(e,e+2);return t.slice(0,vr(Rt(t,0)))}function P5(r,e){let t=r.sliceString(e-2,e);return vr(Rt(t,0))==t.length?t:t.slice(1)}function L5(r,e,t,n){let i=null,s=r.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:qi.of(o.to+e.length),range:P.range(o.anchor+e.length,o.head+e.length)};let a=Ec(r.doc,o.head);return!a||/\s/.test(a)||n.indexOf(a)>-1?{changes:{insert:e+t,from:o.head},effects:qi.of(o.head+e.length),range:P.cursor(o.head+e.length)}:{range:i=o}});return i?null:r.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function B5(r,e,t){let n=null,i=r.changeByRange(s=>s.empty&&Ec(r.doc,s.head)==t?{changes:{from:s.head,to:s.head+t.length,insert:t},range:P.cursor(s.head+t.length)}:n={range:s});return n?null:r.update(i,{scrollIntoView:!0,userEvent:"input.type"})}function F5(r,e,t,n){let i=n.stringPrefixes||oa.stringPrefixes,s=null,o=r.changeByRange(a=>{if(!a.empty)return{changes:[{insert:e,from:a.from},{insert:e,from:a.to}],effects:qi.of(a.to+e.length),range:P.range(a.anchor+e.length,a.head+e.length)};let l=a.head,c=Ec(r.doc,l),d;if(c==e){if(my(r,l))return{changes:{insert:e+e,from:l},effects:qi.of(l+e.length),range:P.cursor(l+e.length)};if(Ny(r,l)){let h=t&&r.sliceDoc(l,l+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:l,to:l+h.length,insert:h},range:P.cursor(l+h.length)}}}else{if(t&&r.sliceDoc(l-2*e.length,l)==e+e&&(d=gy(r,l-2*e.length,i))>-1&&my(r,d))return{changes:{insert:e+e+e+e,from:l},effects:qi.of(l+e.length),range:P.cursor(l+e.length)};if(r.charCategorizer(l)(c)!=$e.Word&&gy(r,l,i)>-1&&!_5(r,l,e,i))return{changes:{insert:e+e,from:l},effects:qi.of(l+e.length),range:P.cursor(l+e.length)}}return{range:s=a}});return s?null:r.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function my(r,e){let t=Ct(r).resolveInner(e+1);return t.parent&&t.from==e}function _5(r,e,t,n){let i=Ct(r).resolveInner(e,-1),s=n.reduce((o,a)=>Math.max(o,a.length),0);for(let o=0;o<5;o++){let a=r.sliceDoc(i.from,Math.min(i.to,i.from+t.length+s)),l=a.indexOf(t);if(!l||l>-1&&n.indexOf(a.slice(0,l))>-1){let d=i.firstChild;for(;d&&d.from==i.from&&d.to-d.from>t.length+l;){if(r.sliceDoc(d.to-t.length,d.to)==t)return!1;d=d.firstChild}return!0}let c=i.to==e&&i.parent;if(!c)break;i=c}return!1}function gy(r,e,t){let n=r.charCategorizer(e);if(n(r.sliceDoc(e-1,e))!=$e.Word)return e;for(let i of t){let s=e-i.length;if(r.sliceDoc(s,e)==i&&n(r.sliceDoc(s-1,s))!=$e.Word)return s}return-1}function Ac(r={}){return[T5,ur,kt.of(r),E5,z5,M5]}var If=[{key:"Ctrl-Space",run:wf},{mac:"Alt-`",run:wf},{mac:"Alt-i",run:wf},{key:"Escape",run:C5},{key:"ArrowDown",run:wc(!0)},{key:"ArrowUp",run:wc(!1)},{key:"PageDown",run:wc(!0,"page")},{key:"PageUp",run:wc(!1,"page")},{key:"Enter",run:S5}],z5=tn.highest(Hn.computeN([kt],r=>r.facet(kt).defaultKeymap?[If]:[]));var Mc=class{constructor(e,t,n){this.from=e,this.to=t,this.diagnostic=n}},Yi=class r{constructor(e,t,n){this.diagnostics=e,this.panel=t,this.selected=n}static init(e,t,n){let i=n.facet(aa).markerFilter;i&&(e=i(e,n));let s=e.slice().sort((f,p)=>f.from-p.from||f.to-p.to),o=new xr,a=[],l=0,c=n.doc.iter(),d=0,u=n.doc.length;for(let f=0;;){let p=f==s.length?null:s[f];if(!p&&!a.length)break;let m,g;if(a.length)m=l,g=a.reduce((x,N)=>Math.min(x,N.to),p&&p.from>m?p.from:1e8);else{if(m=p.from,m>u)break;g=p.to,a.push(p),f++}for(;f<s.length;){let x=s[f];if(x.from==m&&(x.to>x.from||x.to==m))a.push(x),f++,g=Math.min(x.to,g);else{g=Math.min(x.from,g);break}}g=Math.min(g,u);let b=!1;if(a.some(x=>x.from==m&&(x.to==g||g==u))&&(b=m==g,!b&&g-m<10)){let x=m-(d+c.value.length);x>0&&(c.next(x),d=m);for(let N=m;;){if(N>=g){b=!0;break}if(!c.lineBreak&&d+c.value.length>N)break;N=d+c.value.length,d+=c.value.length,c.next()}}let y=J5(a);if(b)o.add(m,m,Z.widget({widget:new Pf(y),diagnostics:a.slice()}));else{let x=a.reduce((N,C)=>C.markClass?N+" "+C.markClass:N,"");o.add(m,g,Z.mark({class:"cm-lintRange cm-lintRange-"+y+x,diagnostics:a.slice(),inclusiveEnd:a.some(N=>N.to>g)}))}if(l=g,l==u)break;for(let x=0;x<a.length;x++)a[x].to<=l&&a.splice(x--,1)}let h=o.finish();return new r(h,t,fi(h))}};function fi(r,e=null,t=0){let n=null;return r.between(t,1e9,(i,s,{spec:o})=>{if(!(e&&o.diagnostics.indexOf(e)<0))if(!n)n=new Mc(i,s,e||o.diagnostics[0]);else{if(o.diagnostics.indexOf(n.diagnostic)<0)return!1;n=new Mc(n.from,s,n.diagnostic)}}),n}function $5(r,e){let t=e.pos,n=e.end||t,i=r.state.facet(aa).hideOn(r,t,n);if(i!=null)return i;let s=r.startState.doc.lineAt(e.pos);return!!(r.effects.some(o=>o.is(Ty))||r.changes.touchesRange(s.from,Math.max(s.to,n)))}function H5(r,e){return r.field(kr,!1)?e:e.concat(le.appendConfig.of(X5))}var Ty=le.define(),Lf=le.define(),My=le.define(),kr=st.define({create(){return new Yi(Z.none,null,null)},update(r,e){if(e.docChanged&&r.diagnostics.size){let t=r.diagnostics.map(e.changes),n=null,i=r.panel;if(r.selected){let s=e.changes.mapPos(r.selected.from,1);n=fi(t,r.selected.diagnostic,s)||fi(t,null,s)}!t.size&&i&&e.state.facet(aa).autoPanel&&(i=null),r=new Yi(t,i,n)}for(let t of e.effects)if(t.is(Ty)){let n=e.state.facet(aa).autoPanel?t.value.length?la.open:null:r.panel;r=Yi.init(t.value,n,e.state)}else t.is(Lf)?r=new Yi(r.diagnostics,t.value?la.open:null,r.selected):t.is(My)&&(r=new Yi(r.diagnostics,r.panel,t.value));return r},provide:r=>[_i.from(r,e=>e.panel),U.decorations.from(r,e=>e.diagnostics)]});var W5=Z.mark({class:"cm-lintRange cm-lintRange-active"});function V5(r,e,t){let{diagnostics:n}=r.state.field(kr),i,s=-1,o=-1;n.between(e-(t<0?1:0),e+(t>0?1:0),(l,c,{spec:d})=>{if(e>=l&&e<=c&&(l==c||(e>l||t>0)&&(e<c||t<0)))return i=d.diagnostics,s=l,o=c,!1});let a=r.state.facet(aa).tooltipFilter;return i&&a&&(i=a(i,r.state)),i?{pos:s,end:o,above:r.state.doc.lineAt(s).to<o,create(){return{dom:j5(r,i)}}}:null}function j5(r,e){return De("ul",{class:"cm-tooltip-lint"},e.map(t=>Ry(r,t,!1)))}var U5=r=>{let e=r.state.field(kr,!1);(!e||!e.panel)&&r.dispatch({effects:H5(r.state,[Lf.of(!0)])});let t=Wo(r,la.open);return t&&t.dom.querySelector(".cm-panel-lint ul").focus(),!0},Ey=r=>{let e=r.state.field(kr,!1);return!e||!e.panel?!1:(r.dispatch({effects:Lf.of(!1)}),!0)},G5=r=>{let e=r.state.field(kr,!1);if(!e)return!1;let t=r.state.selection.main,n=fi(e.diagnostics,null,t.to+1);return!n&&(n=fi(e.diagnostics,null,0),!n||n.from==t.from&&n.to==t.to)?!1:(r.dispatch({selection:{anchor:n.from,head:n.to},scrollIntoView:!0}),!0)};var Dy=[{key:"Mod-Shift-m",run:U5,preventDefault:!0},{key:"F8",run:G5}];var aa=K.define({combine(r){return{sources:r.map(e=>e.source).filter(e=>e!=null),...Ut(r.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:Ay,tooltipFilter:Ay,needsRefresh:(e,t)=>e?t?n=>e(n)||t(n):e:t,hideOn:(e,t)=>e?t?(n,i,s)=>e(n,i,s)||t(n,i,s):e:t,autoPanel:(e,t)=>e||t})}}});function Ay(r,e){return r?e?(t,n)=>e(r(t,n),n):r:e}function Oy(r){let e=[];if(r)e:for(let{name:t}of r){for(let n=0;n<t.length;n++){let i=t[n];if(/[a-zA-Z]/.test(i)&&!e.some(s=>s.toLowerCase()==i.toLowerCase())){e.push(i);continue e}}e.push("")}return e}function Ry(r,e,t){var n;let i=t?Oy(e.actions):[];return De("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},De("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage(r):e.message),(n=e.actions)===null||n===void 0?void 0:n.map((s,o)=>{let a=!1,l=f=>{if(f.preventDefault(),a)return;a=!0;let p=fi(r.state.field(kr).diagnostics,e);p&&s.apply(r,p.from,p.to)},{name:c}=s,d=i[o]?c.indexOf(i[o]):-1,u=d<0?c:[c.slice(0,d),De("u",c.slice(d,d+1)),c.slice(d+1)],h=s.markClass?" "+s.markClass:"";return De("button",{type:"button",class:"cm-diagnosticAction"+h,onclick:l,onmousedown:l,"aria-label":` Action: ${c}${d<0?"":` (access key "${i[o]})"`}.`},u)}),e.source&&De("div",{class:"cm-diagnosticSource"},e.source))}var Pf=class extends er{constructor(e){super(),this.sev=e}eq(e){return e.sev==this.sev}toDOM(){return De("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}},Dc=class{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Ry(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}},la=class r{constructor(e){this.view=e,this.items=[];let t=i=>{if(!(i.ctrlKey||i.altKey||i.metaKey)){if(i.keyCode==27)Ey(this.view),this.view.focus();else if(i.keyCode==38||i.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(i.keyCode==40||i.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(i.keyCode==36)this.moveSelection(0);else if(i.keyCode==35)this.moveSelection(this.items.length-1);else if(i.keyCode==13)this.view.focus();else if(i.keyCode>=65&&i.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:s}=this.items[this.selectedIndex],o=Oy(s.actions);for(let a=0;a<o.length;a++)if(o[a].toUpperCase().charCodeAt(0)==i.keyCode){let l=fi(this.view.state.field(kr).diagnostics,s);l&&s.actions[a].apply(e,l.from,l.to)}}else return;i.preventDefault()}},n=i=>{for(let s=0;s<this.items.length;s++)this.items[s].dom.contains(i.target)&&this.moveSelection(s)};this.list=De("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:t,onclick:n}),this.dom=De("div",{class:"cm-panel-lint"},this.list,De("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>Ey(this.view)},"\xD7")),this.update()}get selectedIndex(){let e=this.view.state.field(kr).selected;if(!e)return-1;for(let t=0;t<this.items.length;t++)if(this.items[t].diagnostic==e.diagnostic)return t;return-1}update(){let{diagnostics:e,selected:t}=this.view.state.field(kr),n=0,i=!1,s=null,o=new Set;for(e.between(0,this.view.state.doc.length,(a,l,{spec:c})=>{for(let d of c.diagnostics){if(o.has(d))continue;o.add(d);let u=-1,h;for(let f=n;f<this.items.length;f++)if(this.items[f].diagnostic==d){u=f;break}u<0?(h=new Dc(this.view,d),this.items.splice(n,0,h),i=!0):(h=this.items[u],u>n&&(this.items.splice(n,u-n),i=!0)),t&&h.diagnostic==t.diagnostic?h.dom.hasAttribute("aria-selected")||(h.dom.setAttribute("aria-selected","true"),s=h):h.dom.hasAttribute("aria-selected")&&h.dom.removeAttribute("aria-selected"),n++}});n<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)i=!0,this.items.pop();this.items.length==0&&(this.items.push(new Dc(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),i=!0),s?(this.list.setAttribute("aria-activedescendant",s.id),this.view.requestMeasure({key:this,read:()=>({sel:s.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:a,panel:l})=>{let c=l.height/this.list.offsetHeight;a.top<l.top?this.list.scrollTop-=(l.top-a.top)/c:a.bottom>l.bottom&&(this.list.scrollTop+=(a.bottom-l.bottom)/c)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),i&&this.sync()}sync(){let e=this.list.firstChild;function t(){let n=e;e=n.nextSibling,n.remove()}for(let n of this.items)if(n.dom.parentNode==this.list){for(;e!=n.dom;)t();e=n.dom.nextSibling}else this.list.insertBefore(n.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=this.view.state.field(kr),n=fi(t.diagnostics,this.items[e].diagnostic);n&&this.view.dispatch({selection:{anchor:n.from,head:n.to},scrollIntoView:!0,effects:My.of(n)})}static open(e){return new r(e)}};function q5(r,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${e}>${encodeURIComponent(r)}</svg>')`}function Tc(r){return q5(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${r}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}var K5=U.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:Tc("#d11")},".cm-lintRange-warning":{backgroundImage:Tc("orange")},".cm-lintRange-info":{backgroundImage:Tc("#999")},".cm-lintRange-hint":{backgroundImage:Tc("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}},"&dark .cm-lintRange-active":{backgroundColor:"#86714a80"},"&dark .cm-panel.cm-panel-lint ul":{"& [aria-selected]":{backgroundColor:"#2e343e"}}});function Y5(r){return r=="error"?4:r=="warning"?3:r=="info"?2:1}function J5(r){let e="hint",t=1;for(let n of r){let i=Y5(n.severity);i>t&&(t=i,e=n.severity)}return e}var X5=[kr,U.decorations.compute([kr],r=>{let{selected:e,panel:t}=r.field(kr);return!e||!t||e.from==e.to?Z.none:Z.set([W5.range(e.from,e.to)])}),vx(V5,{hideOn:$5}),K5];var Bf=function(e){e===void 0&&(e={});var{crosshairCursor:t=!1}=e,n=[];e.closeBracketsKeymap!==!1&&(n=n.concat(ky)),e.defaultKeymap!==!1&&(n=n.concat(Xv)),e.searchKeymap!==!1&&(n=n.concat(cy)),e.historyKeymap!==!1&&(n=n.concat(Cv)),e.foldKeymap!==!1&&(n=n.concat(Zx)),e.completionKeymap!==!1&&(n=n.concat(If)),e.lintKeymap!==!1&&(n=n.concat(Dy));var i=[];return e.lineNumbers!==!1&&i.push(Nx()),e.highlightActiveLineGutter!==!1&&i.push(Ex()),e.highlightSpecialChars!==!1&&i.push(px()),e.history!==!1&&i.push(vv()),e.foldGutter!==!1&&i.push(tv()),e.drawSelection!==!1&&i.push(dx()),e.dropCursor!==!1&&i.push(fx()),e.allowMultipleSelections!==!1&&i.push(Me.allowMultipleSelections.of(!0)),e.indentOnInput!==!1&&i.push(qx()),e.syntaxHighlighting!==!1&&i.push(rc(nv,{fallback:!0})),e.bracketMatching!==!1&&i.push(av()),e.closeBrackets!==!1&&i.push(wy()),e.autocompletion!==!1&&i.push(Ac()),e.rectangularSelection!==!1&&i.push(bx()),t!==!1&&i.push(xx()),e.highlightActiveLine!==!1&&i.push(mx()),e.highlightSelectionMatches!==!1&&i.push(iy()),e.tabSize&&typeof e.tabSize=="number"&&i.push(Ui.of(" ".repeat(e.tabSize))),i.concat([Hn.of(n.flat())]).filter(Boolean)};var Z5="#e5c07b",Iy="#e06c75",Q5="#56b6c2",eO="#ffffff",Oc="#abb2bf",_f="#7d8799",tO="#61afef",rO="#98c379",Py="#d19a66",nO="#c678dd",iO="#21252b",Ly="#2c313a",By="#282c34",Ff="#353a42",sO="#3E4451",Fy="#528bff";var oO=U.theme({"&":{color:Oc,backgroundColor:By},".cm-content":{caretColor:Fy},".cm-cursor, .cm-dropCursor":{borderLeftColor:Fy},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:sO},".cm-panels":{backgroundColor:iO,color:Oc},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#6699ff0b"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847"},".cm-gutters":{backgroundColor:By,color:_f,border:"none"},".cm-activeLineGutter":{backgroundColor:Ly},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Ff},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Ff,borderBottomColor:Ff},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:Ly,color:Oc}}},{dark:!0}),aO=Ls.define([{tag:R.keyword,color:nO},{tag:[R.name,R.deleted,R.character,R.propertyName,R.macroName],color:Iy},{tag:[R.function(R.variableName),R.labelName],color:tO},{tag:[R.color,R.constant(R.name),R.standard(R.name)],color:Py},{tag:[R.definition(R.name),R.separator],color:Oc},{tag:[R.typeName,R.className,R.number,R.changed,R.annotation,R.modifier,R.self,R.namespace],color:Z5},{tag:[R.operator,R.operatorKeyword,R.url,R.escape,R.regexp,R.link,R.special(R.string)],color:Q5},{tag:[R.meta,R.comment],color:_f},{tag:R.strong,fontWeight:"bold"},{tag:R.emphasis,fontStyle:"italic"},{tag:R.strikethrough,textDecoration:"line-through"},{tag:R.link,color:_f,textDecoration:"underline"},{tag:R.heading,fontWeight:"bold",color:Iy},{tag:[R.atom,R.bool,R.special(R.variableName)],color:Py},{tag:[R.processingInstruction,R.string,R.inserted],color:rO},{tag:R.invalid,color:eO}]),_y=[oO,rc(aO)];var zy=U.theme({"&":{backgroundColor:"#fff"}},{dark:!1});var $y=function(e){e===void 0&&(e={});var{indentWithTab:t=!0,editable:n=!0,readOnly:i=!1,theme:s="light",placeholder:o="",basicSetup:a=!0}=e,l=[];switch(t&&l.unshift(Hn.of([Zv])),a&&(typeof a=="boolean"?l.unshift(Bf()):l.unshift(Bf(a))),o&&l.unshift(gx(o)),s){case"light":l.push(zy);break;case"dark":l.push(_y);break;case"none":break;default:l.push(s);break}return n===!1&&l.push(U.editable.of(!1)),i&&l.push(Me.readOnly.of(!0)),[...l]};var Hy=r=>({line:r.state.doc.lineAt(r.state.selection.main.from),lineCount:r.state.doc.lines,lineBreak:r.state.lineBreak,length:r.state.doc.length,readOnly:r.state.readOnly,tabSize:r.state.tabSize,selection:r.state.selection,selectionAsSingle:r.state.selection.asSingle().main,ranges:r.state.selection.ranges,selectionCode:r.state.sliceDoc(r.state.selection.main.from,r.state.selection.main.to),selections:r.state.selection.ranges.map(e=>r.state.sliceDoc(e.from,e.to)),selectedText:r.state.selection.ranges.some(e=>!e.empty)});var Rc=class{constructor(e,t){this.timeLeftMS=void 0,this.timeoutMS=void 0,this.isCancelled=!1,this.isTimeExhausted=!1,this.callbacks=[],this.timeLeftMS=t,this.timeoutMS=t,this.callbacks.push(e)}tick(){if(!this.isCancelled&&!this.isTimeExhausted&&(this.timeLeftMS--,this.timeLeftMS<=0)){this.isTimeExhausted=!0;var e=this.callbacks.slice();this.callbacks.length=0,e.forEach(t=>{try{t()}catch(n){console.error("TimeoutLatch callback error:",n)}})}}cancel(){this.isCancelled=!0,this.callbacks.length=0}reset(){this.timeLeftMS=this.timeoutMS,this.isCancelled=!1,this.isTimeExhausted=!1}get isDone(){return this.isCancelled||this.isTimeExhausted}},Ic=class{constructor(){this.interval=null,this.latches=new Set}add(e){this.latches.add(e),this.start()}remove(e){this.latches.delete(e),this.latches.size===0&&this.stop()}start(){this.interval===null&&(this.interval=setInterval(()=>{this.latches.forEach(e=>{e.tick(),e.isDone&&this.remove(e)})},1))}stop(){this.interval!==null&&(clearInterval(this.interval),this.interval=null)}},zf=null,Wy=()=>typeof window>"u"?new Ic:(zf||(zf=new Ic),zf);var Vy=jt.define(),cO=200,dO=[];function jy(r){var{value:e,selection:t,onChange:n,onStatistics:i,onCreateEditor:s,onUpdate:o,extensions:a=dO,autoFocus:l,theme:c="light",height:d=null,minHeight:u=null,maxHeight:h=null,width:f=null,minWidth:p=null,maxWidth:m=null,placeholder:g="",editable:b=!0,readOnly:y=!1,indentWithTab:x=!0,basicSetup:N=!0,root:C,initialState:w}=r,[k,A]=da(),[S,M]=da(),[D,O]=da(),H=da(()=>({current:null}))[0],E=da(()=>({current:null}))[0],$=U.theme({"&":{height:d,minHeight:u,maxHeight:h,width:f,minWidth:p,maxWidth:m},"& .cm-scroller":{height:"100% !important"}}),G=U.updateListener.of(_=>{if(_.docChanged&&typeof n=="function"&&!_.transactions.some(J=>J.annotation(Vy))){H.current?H.current.reset():(H.current=new Rc(()=>{if(E.current){var J=E.current;E.current=null,J()}H.current=null},cO),Wy().add(H.current));var ie=_.state.doc,Se=ie.toString();n(Se,_)}i&&i(Hy(_))}),W=$y({theme:c,editable:b,readOnly:y,placeholder:g,indentWithTab:x,basicSetup:N}),he=[G,$,...W];return o&&typeof o=="function"&&he.push(U.updateListener.of(o)),he=he.concat(a),lO(()=>{if(k&&!D){var _={doc:e,selection:t,extensions:he},ie=w?Me.fromJSON(w.json,_,w.fields):Me.create(_);if(O(ie),!S){var Se=new U({state:ie,parent:k,root:C});M(Se),s&&s(Se,ie)}}return()=>{S&&(O(void 0),M(void 0))}},[k,D]),ca(()=>{r.container&&A(r.container)},[r.container]),ca(()=>()=>{S&&(S.destroy(),M(void 0)),H.current&&(H.current.cancel(),H.current=null)},[S]),ca(()=>{l&&S&&S.focus()},[l,S]),ca(()=>{S&&S.dispatch({effects:le.reconfigure.of(he)})},[c,a,d,u,h,f,p,m,g,b,y,x,N,n,o]),ca(()=>{if(e!==void 0){var _=S?S.state.doc.toString():"";if(S&&e!==_){var ie=H.current&&!H.current.isDone,Se=()=>{S&&e!==S.state.doc.toString()&&S.dispatch({changes:{from:0,to:S.state.doc.toString().length,insert:e||""},annotations:[Vy.of(!0)]})};ie?E.current=Se:Se()}}},[e,S]),{state:D,setState:O,view:S,setView:M,container:k,setContainer:A}}import{jsx as gO}from"react/jsx-runtime";var uO=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],qy=fO((r,e)=>{var{className:t,value:n="",selection:i,extensions:s=[],onChange:o,onStatistics:a,onCreateEditor:l,onUpdate:c,autoFocus:d,theme:u="light",height:h,minHeight:f,maxHeight:p,width:m,minWidth:g,maxWidth:b,basicSetup:y,placeholder:x,indentWithTab:N,editable:C,readOnly:w,root:k,initialState:A}=r,S=(0,Gy.default)(r,uO),M=hO(null),{state:D,view:O,container:H,setContainer:E}=jy({root:k,value:n,autoFocus:d,theme:u,height:h,minHeight:f,maxHeight:p,width:m,minWidth:g,maxWidth:b,basicSetup:y,placeholder:x,indentWithTab:N,editable:C,readOnly:w,selection:i,onChange:o,onStatistics:a,onCreateEditor:l,onUpdate:c,extensions:s,initialState:A});pO(e,()=>({editor:M.current,state:D,view:O}),[M,H,D,O]);var $=mO(W=>{M.current=W,E(W)},[E]);if(typeof n!="string")throw new Error("value must be typeof string but got "+typeof n);var G=typeof u=="string"?"cm-theme-"+u:"cm-theme";return gO("div",(0,Uy.default)({ref:$,className:""+G+(t?" "+t:"")},S))});qy.displayName="CodeMirror";var Ky=qy;import{create as bO}from"zustand";import{persist as xO}from"zustand/middleware";var Yy=bO()(xO(r=>({commandHistory:[],addCommand:e=>r(t=>{let n=e.trim();return!n||t.commandHistory[t.commandHistory.length-1]===n?t:{commandHistory:[...t.commandHistory,n].slice(-50)}}),clearHistory:()=>r({commandHistory:[]})}),{name:"decido-dataway-history-v1"}));import{jsx as Bt,jsxs as ha}from"react/jsx-runtime";var Xy=({onExecute:r,onClear:e,activeResource:t,activeConnector:n,isLoading:i,schemaColumns:s=[]})=>{let[o,a]=ua(""),[l,c]=ua(!1),[d,u]=ua(""),[h,f]=ua(!1),{commandHistory:p,addCommand:m}=Yy(),[g,b]=ua(-1),y=()=>{o.trim()?(m(o),b(-1),r(o)):e()},x=()=>{a(""),b(-1),e()},N=vO(k=>{if(k.key==="ArrowUp"&&(k.ctrlKey||k.metaKey)){if(k.preventDefault(),p.length>0){let A=g===-1?p.length-1:Math.max(0,g-1);b(A),a(p[A])}}else if(k.key==="ArrowDown"&&(k.ctrlKey||k.metaKey)&&(k.preventDefault(),g!==-1)){let A=g+1;A>=p.length?(b(-1),a("")):(b(A),a(p[A]))}},[p,g]),C=async()=>{if(!(!d.trim()||!t)){f(!0);try{let k=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",A=await fetch(`${k}/api/dataway/copilot`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({prompt:d,connectorId:n,resource:t})});if(!A.ok)throw new Error("Fall\xF3 la generaci\xF3n IA");let S=await A.json();a(S.script),c(!1),u(""),Te.success("M-Script Generado por Inteligencia Artificial")}catch(k){Te.error("Error del Copilot",{description:k.message})}finally{f(!1)}}},w=[Hn.of([{key:"Enter",run:()=>(y(),!0),shift:()=>!1}]),Ac({override:[k=>{let A=k.matchBefore(/["\w.]+/);if(!A||A.from===A.to&&!k.explicit)return null;let S=[{label:"Table.SelectRows",type:"function",info:"Table.SelectRows(table, column, value)"},{label:"Table.AddColumn",type:"function",info:"Table.AddColumn(table, newColumn, value)"},{label:"Table.RenameColumns",type:"function",info:'Table.RenameColumns(table, {{"old", "new"}})'},{label:"Table.SelectColumns",type:"function",info:'Table.SelectColumns(table, {"col1", "col2"})'},{label:"Table.RemoveColumns",type:"function",info:'Table.RemoveColumns(table, {"col1", "col2"})'},{label:"Table.FirstN",type:"function",info:"Table.FirstN(table, count)"},{label:"Table.LastN",type:"function",info:"Table.LastN(table, count)"},{label:"Table.Distinct",type:"function",info:"Table.Distinct(table)"},{label:"Table.Sort",type:"function",info:'Table.Sort(table, {{"col", Order.Descending}})'},{label:"Order.Ascending",type:"variable"},{label:"Order.Descending",type:"variable"},{label:"Source",type:"variable",info:"The active resource dataset"}],M=s.map(D=>({label:`"${D}"`,type:"property",info:`Column in ${t}`}));return{from:A.from,options:[...S,...M]}}]})];return ha("div",{className:"w-full bg-[var(--bg-primary)] border-b border-[var(--border-color)] px-6 py-3 flex items-center gap-3 shadow-sm z-30",onKeyDown:N,children:[Bt("div",{className:"bg-[var(--brand-primary)]/10 p-1.5 rounded-lg text-[var(--brand-primary)]",children:Bt(wO,{className:"w-5 h-5"})}),l?ha("div",{className:"flex-1 relative group border border-purple-400 ring-2 ring-purple-400/20 rounded-xl overflow-hidden shadow-inner bg-purple-50/50 flex items-center transition-all",children:[Bt("input",{type:"text",autoFocus:!0,value:d,onChange:k=>u(k.target.value),placeholder:"Dile a Gemini qu\xE9 necesitas... (Ej: filtra los urgentes y ordena por fecha)",className:"w-full bg-transparent border-none outline-none py-2.5 px-4 text-sm font-medium text-purple-900 placeholder:text-purple-400/70",onKeyDown:k=>{k.key==="Enter"&&C(),k.key==="Escape"&&c(!1)},disabled:h}),Bt("button",{onClick:()=>c(!1),className:"pr-3 text-purple-400 hover:text-purple-600 transition-colors",children:Bt(Jy,{className:"w-4 h-4"})})]}):ha("div",{className:"flex-1 relative group border border-[var(--border-color)] rounded-xl overflow-hidden shadow-inner focus-within:ring-2 focus-within:ring-[var(--brand-primary)]/30 focus-within:border-[var(--brand-primary)] transition-all bg-[var(--bg-surface)] flex items-center",children:[Bt("div",{className:"flex-1",children:Bt(Ky,{value:o,height:"auto",placeholder:t?`Ej: Table.SelectRows(Source, "${t}_id", "==", "10") (Ctrl+\u2191 Hist\xF3rico)`:"Selecciona un recurso para escribir una f\xF3rmula M-Script...",extensions:w,onChange:k=>a(k),editable:!!t&&!i,basicSetup:{lineNumbers:!1,foldGutter:!1,dropCursor:!1,allowMultipleSelections:!1,indentOnInput:!1,bracketMatching:!0,closeBrackets:!0,autocompletion:!0,highlightActiveLine:!1,highlightActiveLineGutter:!1},className:"text-sm font-mono text-[var(--text-primary)] w-full [&_.cm-editor]:bg-transparent [&_.cm-scroller]:p-2.5",theme:"none"})}),o&&Bt("button",{onClick:x,className:"absolute right-3 top-1/2 -translate-y-1/2 text-[var(--text-secondary)] hover:text-red-500 transition-colors bg-[var(--bg-surface)] pl-2 h-full flex items-center",title:"Limpiar F\xF3rmula",style:{zIndex:10},children:Bt(Jy,{className:"w-4 h-4"})})]}),Bt("button",{onClick:()=>l?C():c(!0),disabled:!t||i||h,className:`flex items-center justify-center w-10 h-10 rounded-xl transition-all ${l?"bg-gradient-to-r from-purple-500 to-indigo-600 text-white shadow-md shadow-purple-500/20":"bg-[var(--bg-surface)] text-[var(--text-secondary)] hover:text-purple-600 hover:bg-purple-50"}`,title:"AI Copilot (M-Script Maker)",children:h?Bt(kO,{className:"w-5 h-5 animate-spin"}):Bt(CO,{className:"w-5 h-5"})}),p.length>0&&ha("div",{className:"text-[10px] text-[var(--text-secondary)] font-medium flex items-center gap-1 cursor-help relative",title:"Consultas en el historial (Ctrl+\u2191 / Ctrl+\u2193)",children:[Bt(SO,{className:"w-3 h-3 opacity-60"}),Bt("span",{className:"opacity-60",children:p.length})]}),ha("button",{onClick:y,disabled:!t||i||!o.trim(),className:"flex items-center gap-2 bg-[var(--brand-primary)] hover:bg-[var(--brand-primary-hover)] text-white px-5 py-2.5 rounded-xl text-sm font-bold shadow-md shadow-[var(--brand-primary)]/20 transition-all active:scale-95 disabled:opacity-50 disabled:grayscale ml-2",children:[i?Bt("div",{className:"w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin"}):Bt(yO,{className:"w-4 h-4 fill-current"}),Bt("span",{children:"Ejecutar"})]})]})};import NO,{useMemo as EO}from"react";import{ResponsiveContainer as AO,BarChart as TO,Bar as MO,XAxis as $f,YAxis as Hf,CartesianGrid as Wf,Tooltip as Vf,Legend as jf,LineChart as DO,Line as OO,AreaChart as RO,Area as IO}from"recharts";import{BarChart3 as Zy,LineChart as PO,PieChart as LO,Activity as BO}from"lucide-react";import{jsx as Ee,jsxs as An}from"react/jsx-runtime";var Qy=({data:r,columns:e})=>{let[t,n]=NO.useState("bar"),{dimension:i,metrics:s}=EO(()=>{if(r.length===0||e.length===0)return{dimension:"",metrics:[]};let a=e.find(c=>{let d=r.find(u=>u[c]!==null&&u[c]!==void 0)?.[c];return d!==void 0&&(typeof d=="string"||isNaN(Number(d)))});a=a||e[0];let l=e.filter(c=>{if(c===a)return!1;let d=r.find(u=>u[c]!==null&&u[c]!==void 0)?.[c];return d!==void 0&&!isNaN(Number(d))&&String(d).trim()!==""});return{dimension:a,metrics:l}},[r,e]);if(r.length===0)return An("div",{className:"flex-1 flex flex-col items-center justify-center opacity-40",children:[Ee(BO,{className:"w-16 h-16 mb-4"}),Ee("h2",{className:"text-xl font-bold",children:"Sin Datos para Graficar"}),Ee("p",{className:"text-sm",children:"La tabla procesada est\xE1 vac\xEDa."})]});if(s.length===0)return An("div",{className:"flex-1 flex flex-col items-center justify-center opacity-60",children:[Ee(Zy,{className:"w-16 h-16 mb-4"}),Ee("h2",{className:"text-lg font-bold",children:"Sin Columnas Num\xE9ricas"}),Ee("p",{className:"text-sm text-center max-w-sm mt-2",children:"El motor de gr\xE1ficos necesita al menos una m\xE9trica num\xE9rica para generar la visualizaci\xF3n. (Usa M-Script para castear o generar n\xFAmeros)."})]});let o=["#6366f1","#ec4899","#14b8a6","#f59e0b","#8b5cf6","#10b981"];return An("div",{className:"flex-1 flex flex-col h-full bg-[var(--bg-primary)] p-6",children:[An("div",{className:"flex justify-between items-center mb-6",children:[An("div",{children:[Ee("h2",{className:"text-lg font-bold text-[var(--text-primary)]",children:"Analytics Auto-Dashboard"}),An("p",{className:"text-[11px] font-medium text-[var(--text-secondary)] uppercase tracking-wider",children:["Dimensi\xF3n: ",Ee("span",{className:"text-[var(--brand-primary)]",children:i})," | M\xE9tricas: ",s.join(", ")]})]}),An("div",{className:"flex bg-[var(--bg-elevated)] p-1 rounded-lg border border-[var(--border-color)]",children:[Ee("button",{onClick:()=>n("bar"),className:`p-2 rounded-md transition-all ${t==="bar"?"bg-white shadow-sm text-[var(--brand-primary)]":"text-[var(--text-secondary)] hover:bg-[var(--bg-surface)]"}`,title:"Gr\xE1fico de Barras",children:Ee(Zy,{className:"w-4 h-4"})}),Ee("button",{onClick:()=>n("line"),className:`p-2 rounded-md transition-all ${t==="line"?"bg-white shadow-sm text-[var(--brand-primary)]":"text-[var(--text-secondary)] hover:bg-[var(--bg-surface)]"}`,title:"Gr\xE1fico de L\xEDneas",children:Ee(PO,{className:"w-4 h-4"})}),Ee("button",{onClick:()=>n("area"),className:`p-2 rounded-md transition-all ${t==="area"?"bg-white shadow-sm text-[var(--brand-primary)]":"text-[var(--text-secondary)] hover:bg-[var(--bg-surface)]"}`,title:"Gr\xE1fico de \xC1rea",children:Ee(LO,{className:"w-4 h-4"})})]})]}),Ee("div",{className:"flex-1 min-h-0 bg-white border border-[var(--border-color)] rounded-xl p-4 shadow-inner",children:Ee(AO,{width:"100%",height:"100%",children:t==="bar"?An(TO,{data:r,margin:{top:20,right:30,left:20,bottom:20},children:[Ee(Wf,{strokeDasharray:"3 3",vertical:!1,stroke:"#e2e8f0"}),Ee($f,{dataKey:i,tick:{fontSize:12,fill:"#64748b"},axisLine:{stroke:"#cbd5e1"},tickLine:!1}),Ee(Hf,{tick:{fontSize:12,fill:"#64748b"},axisLine:!1,tickLine:!1}),Ee(Vf,{contentStyle:{borderRadius:"8px",border:"none",boxShadow:"0 4px 6px -1px rgb(0 0 0 / 0.1)"},cursor:{fill:"#f1f5f9"}}),Ee(jf,{wrapperStyle:{paddingTop:"20px"}}),s.map((a,l)=>Ee(MO,{dataKey:a,fill:o[l%o.length],radius:[4,4,0,0]},a))]}):t==="line"?An(DO,{data:r,margin:{top:20,right:30,left:20,bottom:20},children:[Ee(Wf,{strokeDasharray:"3 3",vertical:!1,stroke:"#e2e8f0"}),Ee($f,{dataKey:i,tick:{fontSize:12,fill:"#64748b"},axisLine:{stroke:"#cbd5e1"},tickLine:!1}),Ee(Hf,{tick:{fontSize:12,fill:"#64748b"},axisLine:!1,tickLine:!1}),Ee(Vf,{contentStyle:{borderRadius:"8px",border:"none",boxShadow:"0 4px 6px -1px rgb(0 0 0 / 0.1)"}}),Ee(jf,{wrapperStyle:{paddingTop:"20px"}}),s.map((a,l)=>Ee(OO,{type:"monotone",dataKey:a,stroke:o[l%o.length],strokeWidth:3,dot:{r:4},activeDot:{r:6}},a))]}):An(RO,{data:r,margin:{top:20,right:30,left:20,bottom:20},children:[Ee(Wf,{strokeDasharray:"3 3",vertical:!1,stroke:"#e2e8f0"}),Ee($f,{dataKey:i,tick:{fontSize:12,fill:"#64748b"},axisLine:{stroke:"#cbd5e1"},tickLine:!1}),Ee(Hf,{tick:{fontSize:12,fill:"#64748b"},axisLine:!1,tickLine:!1}),Ee(Vf,{contentStyle:{borderRadius:"8px",border:"none",boxShadow:"0 4px 6px -1px rgb(0 0 0 / 0.1)"}}),Ee(jf,{wrapperStyle:{paddingTop:"20px"}}),s.map((a,l)=>Ee(IO,{type:"monotone",dataKey:a,fill:o[l%o.length],stroke:o[l%o.length],fillOpacity:.3,strokeWidth:2},a))]})})})]})};import{useState as ew,useEffect as FO}from"react";import{X as _O,Filter as zO,Calendar as $O,Type as HO,Hash as WO}from"lucide-react";import{jsx as tr,jsxs as Tn}from"react/jsx-runtime";var tw=({isOpen:r,column:e,colType:t,onClose:n,onApply:i})=>{let[s,o]=ew("="),[a,l]=ew("");if(FO(()=>{r&&(o("="),l(""))},[r]),!r)return null;let d={text:[{val:"=",label:"Es igual a"},{val:"contains",label:"Contiene"},{val:"starts_with",label:"Empieza con"}],number:[{val:"=",label:"Es igual a"},{val:">",label:"Es mayor que"},{val:"<",label:"Es menor que"},{val:">=",label:"Mayor o igual"},{val:"<=",label:"Menor o igual"}],date:[{val:"=",label:"Es exactamente"},{val:"<",label:"Antes de"},{val:">",label:"Despu\xE9s de"}]}[t];return tr("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/50 backdrop-blur-sm p-4 animate-in fade-in duration-200",children:Tn("div",{className:"bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-2xl shadow-2xl w-full max-w-sm overflow-hidden animate-in zoom-in-95 duration-200",children:[Tn("div",{className:"flex items-center justify-between p-4 border-b border-[var(--border-color)] bg-[var(--bg-elevated)]",children:[Tn("h3",{className:"font-bold flex items-center gap-2 text-[var(--text-primary)]",children:[tr(zO,{className:"w-4 h-4 text-[var(--brand-primary)]"}),"Filtro Inteligente"]}),tr("button",{onClick:n,className:"p-1 hover:bg-[var(--bg-surface)] rounded-md transition-colors text-[var(--text-secondary)]",children:tr(_O,{className:"w-4 h-4"})})]}),Tn("form",{onSubmit:h=>{h.preventDefault(),a.trim()&&i(e,s,a.trim())},className:"p-5 space-y-4",children:[Tn("div",{className:"flex flex-col gap-1",children:[Tn("label",{className:"text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider flex items-center gap-1.5",children:[t==="text"&&tr(HO,{className:"w-3.5 h-3.5"}),t==="number"&&tr(WO,{className:"w-3.5 h-3.5"}),t==="date"&&tr($O,{className:"w-3.5 h-3.5"}),"Columna Objetivo"]}),Tn("div",{className:"px-3 py-2 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-lg text-sm font-semibold text-[var(--text-primary)]",children:[e,tr("span",{className:"ml-2 text-[10px] bg-[var(--brand-primary)]/10 text-[var(--brand-primary)] px-2 py-0.5 rounded-full uppercase",children:t})]})]}),Tn("div",{className:"flex flex-col gap-1",children:[tr("label",{className:"text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider",children:"Condici\xF3n"}),tr("select",{value:s,onChange:h=>o(h.target.value),className:"w-full px-3 py-2 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-lg text-sm outline-none focus:ring-2 focus:ring-[var(--brand-primary)]/50 transition-shadow appearance-none",children:d.map(h=>tr("option",{value:h.val,children:h.label},h.val))})]}),Tn("div",{className:"flex flex-col gap-1",children:[tr("label",{className:"text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider",children:"Valor"}),tr("input",{type:t==="date"?"date":t==="number"?"number":"text",step:"any",autoFocus:!0,value:a,onChange:h=>l(h.target.value),placeholder:"Escribe el valor...",className:"w-full px-3 py-2 bg-transparent border border-[var(--border-color)] rounded-lg text-sm outline-none focus:ring-2 focus:ring-[var(--brand-primary)]/50 transition-shadow"})]}),Tn("div",{className:"pt-2 flex gap-3",children:[tr("button",{type:"button",onClick:n,className:"flex-1 px-4 py-2 border border-[var(--border-color)] rounded-xl text-sm font-medium hover:bg-[var(--bg-surface)] transition-colors",children:"Cancelar"}),tr("button",{type:"submit",disabled:!a.trim(),className:"flex-1 px-4 py-2 bg-[var(--brand-primary)] hover:opacity-90 text-white rounded-xl text-sm font-medium transition-all disabled:opacity-50 disabled:cursor-not-allowed",children:"Aplicar Filtro"})]})]})]})})};import{useState as Pc,useEffect as VO}from"react";import{X as jO,Calculator as rw,Edit3 as UO}from"lucide-react";import{jsx as Nt,jsxs as Nr}from"react/jsx-runtime";var nw=({isOpen:r,columns:e,onClose:t,onApply:n})=>{let[i,s]=Pc(""),[o,a]=Pc(e[0]||""),[l,c]=Pc("+"),[d,u]=Pc("");return VO(()=>{r&&(s(""),a(e[0]||""),c("+"),u(""))},[r,e]),r?Nt("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/50 backdrop-blur-sm p-4 animate-in fade-in duration-200",children:Nr("div",{className:"bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-2xl shadow-2xl w-full max-w-sm overflow-hidden animate-in zoom-in-95 duration-200",children:[Nr("div",{className:"flex items-center justify-between p-4 border-b border-[var(--border-color)] bg-[var(--bg-elevated)]",children:[Nr("h3",{className:"font-bold flex items-center gap-2 text-[var(--text-primary)]",children:[Nt(rw,{className:"w-4 h-4 text-purple-600"}),"Columna Calculada"]}),Nt("button",{onClick:t,className:"p-1 hover:bg-[var(--bg-surface)] rounded-md transition-colors text-[var(--text-secondary)]",children:Nt(jO,{className:"w-4 h-4"})})]}),Nr("form",{onSubmit:f=>{f.preventDefault(),!(!i.trim()||!d.trim())&&n(i.trim(),o,l,d.trim())},className:"p-5 space-y-4",children:[Nr("div",{className:"flex flex-col gap-1",children:[Nr("label",{className:"text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider flex items-center gap-1.5",children:[Nt(UO,{className:"w-3.5 h-3.5"})," Nombre Nueva Columna"]}),Nt("input",{type:"text",autoFocus:!0,value:i,onChange:f=>s(f.target.value),placeholder:"Ej. Ingresos Netos",className:"w-full px-3 py-2 bg-transparent border border-[var(--border-color)] rounded-lg text-sm outline-none focus:ring-2 focus:ring-purple-600/50 transition-shadow"})]}),Nr("div",{className:"flex bg-[var(--bg-surface)] p-3 rounded-xl border border-[var(--border-color)] gap-3 items-center",children:[Nr("div",{className:"flex-1 flex flex-col gap-1",children:[Nt("label",{className:"text-[10px] font-bold text-[var(--text-secondary)] uppercase",children:"Columna (A)"}),Nt("select",{value:o,onChange:f=>a(f.target.value),className:"w-full px-2 py-1.5 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-md text-sm outline-none",children:e.map(f=>Nt("option",{value:f,children:f},f))})]}),Nr("div",{className:"w-12 flex flex-col gap-1",children:[Nt("label",{className:"text-[10px] font-bold text-[var(--text-secondary)] uppercase text-center",children:"Op"}),Nr("select",{value:l,onChange:f=>c(f.target.value),className:"w-full px-1 py-1.5 bg-purple-50 text-purple-700 border border-purple-200 rounded-md text-sm outline-none text-center font-bold font-mono",children:[Nt("option",{value:"+",children:"+"}),Nt("option",{value:"-",children:"-"}),Nt("option",{value:"*",children:"*"}),Nt("option",{value:"/",children:"/"})]})]}),Nr("div",{className:"flex-1 flex flex-col gap-1",children:[Nt("label",{className:"text-[10px] font-bold text-[var(--text-secondary)] uppercase",title:"Puede ser otra columna o un n\xFAmero fijo",children:"Columna o # (B)"}),Nt("input",{type:"text",value:d,onChange:f=>u(f.target.value),placeholder:"Col o #...",className:"w-full px-2 py-1.5 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-md text-sm outline-none"})]})]}),Nr("div",{className:"pt-2 flex gap-3",children:[Nt("button",{type:"button",onClick:t,className:"flex-1 px-4 py-2 border border-[var(--border-color)] rounded-xl text-sm font-medium hover:bg-[var(--bg-surface)] transition-colors",children:"Cancelar"}),Nr("button",{type:"submit",disabled:!i.trim()||!d.trim(),className:"flex-1 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-xl text-sm font-medium transition-all disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2",children:[Nt(rw,{className:"w-4 h-4"})," Calcular"]})]})]})]})}):null};import{useState as Hs,useEffect as GO}from"react";import{X as qO,Save as KO,Play as YO,Trash2 as JO,Database as iw,Code2 as XO,Loader2 as sw}from"lucide-react";import{Fragment as ZO,jsx as Fe,jsxs as gt}from"react/jsx-runtime";var ow=({isOpen:r,onClose:e,currentScript:t,activeConnector:n,activeResource:i,onLoadPipeline:s})=>{let[o,a]=Hs("list"),[l,c]=Hs([]),[d,u]=Hs(!1),[h,f]=Hs(""),[p,m]=Hs(""),[g,b]=Hs(!1);GO(()=>{r&&(a("list"),y())},[r]);let y=async()=>{u(!0);try{let w=await(await fetch("http://localhost:3000/api/dataway/pipelines")).json();w.pipelines&&c(w.pipelines)}catch(C){console.error("Failed to fetch pipelines",C)}finally{u(!1)}},x=async C=>{if(C.preventDefault(),!(!h.trim()||!n||!i||!t)){b(!0);try{(await fetch("http://localhost:3000/api/dataway/pipelines",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:h,description:p,connectorId:n,resource:i,mScript:t})})).ok&&(f(""),m(""),a("list"),y())}catch(w){console.error("Failed to save pipeline",w)}finally{b(!1)}}},N=async C=>{if(confirm("\xBFSeguro que deseas borrar esta plantilla?"))try{await fetch(`http://localhost:3000/api/dataway/pipelines/${C}`,{method:"DELETE"}),y()}catch(w){console.error("Failed to delete",w)}};return r?Fe("div",{className:"fixed inset-0 z-[100] flex items-center justify-center bg-black/50 backdrop-blur-sm p-4 animate-in fade-in duration-200",children:gt("div",{className:"bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-2xl shadow-2xl w-full max-w-2xl overflow-hidden flex flex-col max-h-[85vh]",children:[gt("div",{className:"flex items-center justify-between p-4 border-b border-[var(--border-color)] bg-[var(--bg-elevated)]",children:[gt("h3",{className:"font-bold flex items-center gap-2 text-[var(--text-primary)]",children:[Fe(iw,{className:"w-4 h-4 text-[var(--brand-primary)]"}),"Librer\xEDa de Pipelines ETL"]}),gt("div",{className:"flex items-center gap-2",children:[gt("div",{className:"flex bg-[var(--bg-surface)] p-1 rounded-lg border border-[var(--border-color)]",children:[Fe("button",{onClick:()=>a("list"),className:`px-3 py-1 rounded-md text-xs font-semibold transition-colors ${o==="list"?"bg-white shadow text-[var(--brand-primary)]":"text-[var(--text-secondary)] hover:text-[var(--text-primary)]"}`,children:"Cat\xE1logo"}),Fe("button",{onClick:()=>a("save"),className:`px-3 py-1 rounded-md text-xs font-semibold transition-colors ${o==="save"?"bg-white shadow text-[var(--brand-primary)]":"text-[var(--text-secondary)] hover:text-[var(--text-primary)]"}`,children:"Nueva Plantilla"})]}),Fe("div",{className:"w-px h-6 bg-[var(--border-color)] mx-2"}),Fe("button",{onClick:e,className:"p-1.5 hover:bg-[var(--bg-surface)] rounded-md transition-colors text-[var(--text-secondary)]",children:Fe(qO,{className:"w-4 h-4"})})]})]}),Fe("div",{className:"flex-1 overflow-y-auto p-4 bg-[var(--bg-primary)]",children:o==="list"?Fe("div",{className:"space-y-3",children:d?Fe("div",{className:"flex justify-center p-8",children:Fe(sw,{className:"w-6 h-6 animate-spin text-[var(--brand-primary)]"})}):l.length===0?gt("div",{className:"text-center p-8 text-[var(--text-secondary)]",children:[Fe(iw,{className:"w-12 h-12 mx-auto mb-3 opacity-20"}),Fe("p",{children:"No tienes pipelines guardados."})]}):l.map(C=>gt("div",{className:"border border-[var(--border-color)] rounded-xl p-4 hover:border-[var(--brand-primary)]/50 transition-colors bg-[var(--bg-surface)]/30 group",children:[gt("div",{className:"flex justify-between items-start mb-2",children:[gt("div",{children:[Fe("h4",{className:"font-bold text-[var(--text-primary)]",children:C.name}),Fe("p",{className:"text-xs text-[var(--text-secondary)] mt-0.5",children:C.description||"Sin descripci\xF3n"})]}),gt("div",{className:"flex items-center gap-2 opacity-0 group-hover:opacity-100 transition-opacity",children:[gt("button",{onClick:()=>{s(C.m_script),e()},className:"flex items-center gap-1.5 bg-[var(--brand-primary)] hover:opacity-90 text-white px-3 py-1.5 rounded-lg text-xs font-bold transition-opacity",children:[Fe(YO,{className:"w-3.5 h-3.5"})," Cargar & Ejecutar"]}),Fe("button",{onClick:()=>N(C.id),className:"p-1.5 text-red-400 hover:text-red-600 hover:bg-red-50 rounded-lg transition-colors",children:Fe(JO,{className:"w-4 h-4"})})]})]}),gt("div",{className:"mt-3 flex items-center gap-3 text-[10px] font-mono font-medium text-[var(--text-secondary)]",children:[gt("span",{className:"bg-[var(--bg-elevated)] px-2 py-1 rounded border border-[var(--border-color)]",children:[C.connector_id," : ",C.resource]}),gt("span",{className:"truncate flex-1 flex items-center gap-1.5",children:[Fe(XO,{className:"w-3 h-3"}),C.m_script.substring(0,50),"..."]}),Fe("span",{children:new Date(C.created_at).toLocaleDateString()})]})]},C.id))}):Fe("form",{onSubmit:x,className:"max-w-md mx-auto space-y-4 py-4",children:t?gt(ZO,{children:[gt("div",{className:"flex flex-col gap-1.5",children:[Fe("label",{className:"text-xs font-bold text-[var(--text-secondary)] uppercase",children:"Nombre del Pipeline"}),Fe("input",{type:"text",autoFocus:!0,required:!0,value:h,onChange:C=>f(C.target.value),placeholder:"Ej. Limpieza de Ventas Mensuales",className:"w-full px-3 py-2 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-lg text-sm outline-none focus:ring-2 focus:ring-[var(--brand-primary)]/50"})]}),gt("div",{className:"flex flex-col gap-1.5",children:[Fe("label",{className:"text-xs font-bold text-[var(--text-secondary)] uppercase",children:"Descripci\xF3n (Opcional)"}),Fe("textarea",{value:p,onChange:C=>m(C.target.value),placeholder:"\xBFQu\xE9 hace esta transformaci\xF3n?",rows:3,className:"w-full px-3 py-2 bg-[var(--bg-surface)] border border-[var(--border-color)] rounded-lg text-sm outline-none focus:ring-2 focus:ring-[var(--brand-primary)]/50 resize-none"})]}),gt("div",{className:"p-3 bg-[var(--bg-elevated)] border border-[var(--border-color)] rounded-lg",children:[Fe("div",{className:"text-[10px] font-bold text-[var(--text-secondary)] uppercase mb-1",children:"M-Script a Guardar"}),Fe("pre",{className:"text-xs font-mono text-[var(--text-primary)] whitespace-pre-wrap truncate max-h-24 overflow-hidden",children:t})]}),gt("button",{type:"submit",disabled:g||!h.trim(),className:"w-full py-2.5 bg-[var(--brand-primary)] hover:opacity-90 text-white rounded-xl text-sm font-bold shadow-sm transition-all disabled:opacity-50 flex items-center justify-center gap-2 mt-4",children:[g?Fe(sw,{className:"w-4 h-4 animate-spin"}):Fe(KO,{className:"w-4 h-4"}),"Guardar en Postgres"]})]}):Fe("div",{className:"p-4 bg-orange-50 border border-orange-200 text-orange-800 rounded-lg text-sm text-center",children:"No hay un script activo en el editor para guardar."})})})]})}):null};import{useState as aw,useEffect as QO}from"react";import{jsx as Qe,jsxs as Et}from"react/jsx-runtime";var eR=({data:r})=>Et("div",{className:"bg-slate-900 border border-slate-700 rounded-lg shadow-xl w-72 text-sm overflow-hidden font-mono",children:[Et("div",{className:`px-4 py-2 font-bold text-white uppercase tracking-wider flex items-center justify-between ${r.side==="source"?"bg-indigo-600":"bg-emerald-600"}`,children:[Qe("span",{children:r.title}),Et("span",{className:"text-xs opacity-75",children:[r.columns.length," cols"]})]}),Qe("div",{className:"flex flex-col",children:r.columns.map((e,t)=>Et("div",{className:"relative px-4 py-2 border-b border-slate-800 flex items-center justify-between hover:bg-slate-800 transition-colors group",children:[r.side==="source"&&Qe(ir,{type:"source",position:nr.Right,id:`src-${e.name}`,className:"w-3 h-3 bg-indigo-400 !border-2 !border-slate-900 right-[-6px]"}),r.side==="target"&&Qe(ir,{type:"target",position:nr.Left,id:`tgt-${e.name}`,className:"w-3 h-3 bg-emerald-400 !border-2 !border-slate-900 left-[-6px]"}),Et("div",{className:"flex items-center gap-2 overflow-hidden",children:[Qe("span",{className:`w-2 h-2 rounded-full flex-shrink-0 ${r.side==="source"?"bg-indigo-500":"bg-emerald-500"}`}),Qe("span",{className:"text-slate-200 truncate font-semibold",title:e.name,children:e.name})]}),Et("div",{className:"flex flex-col items-end",children:[Qe("span",{className:"text-xs text-slate-500",children:e.type}),e.formula&&Qe("span",{className:"text-[10px] text-cyan-400 opacity-0 group-hover:opacity-100 transition-opacity absolute right-6 bg-slate-900 px-1 rounded z-10",title:e.formula,children:e.formula})]})]},e.name))})]}),tR={tableNode:eR},lw=({sourceConnector:r,sourceResource:e,targetConnector:t,targetResource:n,onClose:i})=>{let[s,o,a]=pa([]),[l,c,d]=ma([]),[u,h]=aw(!0),[f,p]=aw({mapped:0,missingSource:0,missingTarget:0}),m=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001";return QO(()=>{(async()=>{try{let b=await fetch(`${m}/api/dataway/schema/mapper?sourceConnector=${r}&sourceResource=${e}&targetConnector=${t}&targetResource=${n}`);if(!b.ok)throw new Error("Failed to fetch schema mapping");let y=await b.json(),x=[{id:"source-table",type:"tableNode",position:{x:100,y:100},data:{title:e,columns:y.sourceSchema.columns,side:"source"}},{id:"target-table",type:"tableNode",position:{x:700,y:100},data:{title:n,columns:y.targetSchema.columns,side:"target"}}];y.sourceSchema.inferences&&y.sourceSchema.inferences.length>0&&y.sourceSchema.inferences.forEach((k,A)=>{x.push({id:`inf-${k}`,type:"default",position:{x:100+A*150,y:-100},data:{label:`\u{1F4CE} Ref: ${k}`},style:{background:"#1e293b",color:"#94a3b8",border:"1px solid #334155",borderRadius:"8px",padding:"10px"}})}),o(x);let N=[],C=0,w=y.targetSchema.columns.map(k=>k.name.toLowerCase());y.sourceSchema.columns.forEach(k=>{let A=k.name.toLowerCase(),S=w.findIndex(M=>{let D=A.replace(/[^a-z0-9]/g,""),O=M.replace(/[^a-z0-9]/g,"");return D===O});if(S!==-1){let M=y.targetSchema.columns[S];N.push({id:`e-${k.name}-${M.name}`,source:"source-table",target:"target-table",sourceHandle:`src-${k.name}`,targetHandle:`tgt-${M.name}`,animated:!0,style:{stroke:"#10b981",strokeWidth:2},markerEnd:{type:Dr.ArrowClosed,color:"#10b981"}}),C++}k.formula&&y.sourceSchema.inferences.forEach(M=>{k.formula?.includes(M)&&N.push({id:`infe-${k.name}-${M}`,source:`inf-${M}`,target:"source-table",targetHandle:`src-${k.name}`,animated:!0,style:{stroke:"#cbd5e1",strokeWidth:1,strokeDasharray:"5,5"}})})}),c(N),p({mapped:C,missingSource:y.sourceSchema.columns.length-C,missingTarget:y.targetSchema.columns.length-C})}catch(b){console.error("Schema Map error:",b)}finally{h(!1)}})()},[r,e,t,n]),Qe("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-sm p-4 text-white",children:Et("div",{className:"bg-[#0b0e14] w-[95vw] h-[90vh] rounded-2xl border border-slate-700 shadow-2xl flex flex-col overflow-hidden relative",children:[Et("div",{className:"flex items-center justify-between px-6 py-4 border-b border-slate-800 bg-slate-900/50 backdrop-blur-md",children:[Et("div",{children:[Et("h2",{className:"text-xl font-bold bg-gradient-to-r from-blue-400 to-indigo-400 bg-clip-text text-transparent flex items-center gap-2",children:[Qe("span",{className:"material-symbols-outlined text-indigo-400",children:"schema"}),"Dataway ERD Mapper"]}),Et("p",{className:"text-slate-400 text-sm mt-1",children:["Analyzed Source ",Et("b",{children:["(",e,")"]})," against Target ",Et("b",{children:["(",n,")"]})]})]}),Et("div",{className:"flex gap-6 items-center",children:[Et("div",{className:"flex gap-4 text-sm font-mono bg-black/40 px-4 py-2 rounded-lg border border-slate-800",children:[Et("div",{className:"flex flex-col items-center px-2",children:[Qe("span",{className:"text-emerald-400 text-lg font-bold",children:f.mapped}),Qe("span",{className:"text-slate-500 text-[10px] uppercase",children:"Mapped"})]}),Qe("div",{className:"w-px bg-slate-800"}),Et("div",{className:"flex flex-col items-center px-2",children:[Qe("span",{className:"text-rose-400 text-lg font-bold",children:f.missingTarget}),Qe("span",{className:"text-slate-500 text-[10px] uppercase",children:"Orphans"})]})]}),Qe("button",{onClick:i,className:"w-10 h-10 rounded-xl bg-slate-800 hover:bg-rose-500/20 hover:text-rose-400 flex items-center justify-center transition-all",children:Qe("span",{className:"material-symbols-outlined",children:"close"})})]})]}),Qe("div",{className:"flex-1 w-full h-full bg-[#0a0a0a]",children:u?Qe("div",{className:"w-full h-full flex items-center justify-center",children:Qe("div",{className:"animate-spin rounded-full h-12 w-12 border-b-2 border-indigo-500"})}):Et(Zi,{nodes:s,edges:l,onNodesChange:a,onEdgesChange:d,nodeTypes:tR,fitView:!0,attributionPosition:"bottom-left",className:"bg-[#050505]",children:[Qe(Qi,{color:"#334155",gap:20,size:1}),Qe(es,{className:"!bg-slate-900 !border-slate-700 !fill-slate-400"}),Qe(ts,{className:"!bg-slate-900 !border-slate-700 rounded-lg",maskColor:"rgba(0,0,0,0.5)",nodeColor:g=>g.id.includes("source")?"#4f46e5":"#10b981"})]})})]})})};import{useState as Vn,useEffect as rR}from"react";import{Clock as Uf,Database as nR,FastForward as cw,CheckCircle2 as iR,Play as sR,Pause as oR,Trash2 as aR}from"lucide-react";import{jsx as te,jsxs as Pe}from"react/jsx-runtime";var lR=({data:r})=>Pe("div",{className:"bg-slate-900 border border-amber-500/50 rounded-xl shadow-2xl p-4 w-64 text-slate-200",children:[Pe("div",{className:"flex items-center gap-2 mb-3 text-amber-400",children:[te(Uf,{size:18}),te("span",{className:"font-bold text-sm tracking-wide",children:"CRON TRIGGER"})]}),te("div",{className:"bg-black/50 p-2 rounded-lg font-mono text-center text-lg text-emerald-400 border border-slate-700",children:r.cron}),te("div",{className:"text-xs text-slate-500 mt-2 text-center uppercase",children:"Schedule Expression"}),te(ir,{type:"source",position:nr.Right,className:"w-3 h-3 bg-amber-500"})]}),cR=({data:r})=>Pe("div",{className:"bg-indigo-950 border border-indigo-500/50 rounded-xl shadow-2xl p-4 w-72 text-slate-200",children:[te(ir,{type:"target",position:nr.Left,className:"w-3 h-3 bg-indigo-500"}),Pe("div",{className:"flex items-center gap-2 mb-3 text-indigo-400",children:[te(cw,{size:18}),te("span",{className:"font-bold text-sm tracking-wide",children:"ETL PIPELINE"})]}),te("div",{className:"font-semibold text-white bg-indigo-900/50 p-2 rounded-lg border border-indigo-500/30 truncate",children:r.name}),te(ir,{type:"source",position:nr.Right,className:"w-3 h-3 bg-indigo-500"})]}),dR=({data:r})=>Pe("div",{className:"bg-emerald-950 border border-emerald-500/50 rounded-xl shadow-2xl p-4 w-64 text-slate-200 relative overflow-hidden",children:[r.isActive?te("div",{className:"absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-emerald-400 to-teal-400 animate-pulse"}):te("div",{className:"absolute top-0 left-0 w-full h-1 bg-slate-700"}),te(ir,{type:"target",position:nr.Left,className:"w-3 h-3 bg-emerald-500"}),Pe("div",{className:"flex items-center gap-2 mb-3 text-emerald-400",children:[te(nR,{size:18}),te("span",{className:"font-bold text-sm tracking-wide",children:"TARGET DB"})]}),Pe("div",{className:"text-sm font-mono text-slate-300",children:[te("span",{className:"opacity-50",children:"Conn:"})," ",r.connector,te("br",{}),te("span",{className:"opacity-50",children:"Table:"})," ",r.resource]}),r.lastStatus&&Pe("div",{className:"mt-3 text-[10px] text-slate-400 bg-black/40 p-1.5 rounded flex items-center gap-1.5",children:[te(iR,{size:12,className:r.lastStatus.includes("Failed")?"text-rose-400":"text-emerald-400"}),te("span",{className:"truncate",children:r.lastStatus})]})]}),uR={trigger:lR,pipeline:cR,destination:dR},dw=({onClose:r})=>{let[e,t,n]=pa([]),[i,s,o]=ma([]),[a,l]=Vn([]),[c,d]=Vn([]),[u,h]=Vn(""),[f,p]=Vn("0 3 * * *"),[m,g]=Vn(""),[b,y]=Vn("googlesheets"),[x,N]=Vn(""),[C,w]=Vn("postgres"),[k,A]=Vn("ventas"),S=async()=>{try{let[E,$]=await Promise.all([fetch("/api/dataway/crons").then(G=>G.json()),fetch("/api/dataway/pipelines").then(G=>G.json())]);l(E.crons||[]),d($.pipelines||[]),M(E.crons||[])}catch(E){console.error("Failed to load orchestrator data",E)}},M=E=>{let $=[],G=[];E.forEach((W,he)=>{let _=he*250+50;$.push({id:`trigger-${W.id}`,type:"trigger",position:{x:50,y:_},data:{cron:W.cron_expression}}),$.push({id:`pipe-${W.id}`,type:"pipeline",position:{x:400,y:_+10},data:{name:W.pipeline_name||`Pipeline #${W.pipeline_id}`}}),$.push({id:`dest-${W.id}`,type:"destination",position:{x:800,y:_},data:{connector:W.target_connector,resource:W.target_resource,lastStatus:W.last_status,isActive:W.is_active}}),G.push({id:`e1-${W.id}`,source:`trigger-${W.id}`,target:`pipe-${W.id}`,animated:W.is_active,style:{stroke:W.is_active?"#f59e0b":"#334155",strokeWidth:2},markerEnd:{type:Dr.ArrowClosed,color:W.is_active?"#f59e0b":"#334155"}}),G.push({id:`e2-${W.id}`,source:`pipe-${W.id}`,target:`dest-${W.id}`,animated:W.is_active,style:{stroke:W.is_active?"#10b981":"#334155",strokeWidth:2},markerEnd:{type:Dr.ArrowClosed,color:W.is_active?"#10b981":"#334155"}})}),t($),s(G)};rR(()=>{S()},[]);let D=async()=>{if(!u||!m||!x||!k)return alert("Faltan campos (Origen, Destino, Plantilla)");await fetch("/api/dataway/crons",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:u,cron_expression:f,pipeline_id:parseInt(m),source_connector:b,source_resource:x,target_connector:C,target_resource:k,is_active:!1})}),S()},O=async(E,$)=>{await fetch(`/api/dataway/crons/${E}/toggle`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({is_active:!$})}),S()},H=async E=>{confirm("Are you sure?")&&(await fetch(`/api/dataway/crons/${E}`,{method:"DELETE"}),S())};return te("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-md p-4 flex-col text-slate-200",children:Pe("div",{className:"w-[98vw] h-[95vh] bg-[#090b11] rounded-2xl border border-slate-700 shadow-2xl flex overflow-hidden",children:[Pe("div",{className:"flex-1 relative",children:[Pe(Zi,{nodes:e,edges:i,onNodesChange:n,onEdgesChange:o,nodeTypes:uR,fitView:!0,className:"bg-[#050505]",children:[te(Qi,{color:"#334155",gap:20,size:1}),te(es,{className:"!bg-slate-900 !border-slate-700 !fill-slate-400"}),te(ts,{className:"!bg-slate-900 !border-slate-700",maskColor:"rgba(0,0,0,0.6)"})]}),Pe("div",{className:"absolute top-4 left-4 bg-slate-900/60 backdrop-blur p-4 rounded-xl border border-slate-700 shadow-xl",children:[Pe("h2",{className:"text-xl font-bold bg-gradient-to-r from-teal-400 to-indigo-400 bg-clip-text text-transparent flex items-center gap-2",children:[te(Uf,{className:"text-teal-400"}),"Dataway Orchestrator (Level 14) \u{1F680}"]}),te("p",{className:"text-sm text-slate-400 mt-1",children:"Autonomous ETL Cron Engine linked to Postgres Templates"})]}),te("button",{onClick:r,className:"absolute top-4 right-4 bg-slate-800 p-2 rounded-lg hover:bg-rose-500/20 text-slate-400 transition-colors",children:"Cerrar Orchestrator"})]}),Pe("div",{className:"w-[400px] border-l border-slate-800 bg-slate-900 flex flex-col",children:[te("div",{className:"p-4 border-b border-slate-800 font-bold bg-slate-950 uppercase tracking-widest text-xs text-slate-500",children:"Create Auto-Job"}),Pe("div",{className:"p-4 space-y-4 border-b border-slate-800",children:[Pe("div",{children:[te("label",{className:"text-xs text-slate-400 mb-1 block",children:"Job Name"}),te("input",{value:u,onChange:E=>h(E.target.value),className:"w-full bg-black/40 border border-slate-700 rounded-md px-3 py-2 text-sm",placeholder:"Sincronizaci\xF3n Nocturna"})]}),te("div",{className:"flex gap-2",children:Pe("div",{className:"flex-1",children:[te("label",{className:"text-xs text-slate-400 mb-1 block",children:"Cron Format"}),te("input",{value:f,onChange:E=>p(E.target.value),className:"w-full bg-black/40 border border-slate-700 rounded-md px-3 py-2 text-sm font-mono text-amber-400"})]})}),Pe("div",{children:[te("label",{className:"text-xs text-slate-400 mb-1 block",children:"Pipeline Template"}),Pe("select",{value:m,onChange:E=>g(E.target.value),className:"w-full bg-black/40 border border-slate-700 rounded-md px-3 py-2 text-sm text-indigo-300",children:[te("option",{value:"",children:"Select Pipeline..."}),c.map(E=>te("option",{value:E.id,children:E.name},E.id))]})]}),Pe("div",{className:"grid grid-cols-2 gap-2 p-3 bg-black/30 rounded-lg border border-slate-800",children:[Pe("div",{children:[te("label",{className:"text-xs text-slate-500 mb-1 block",children:"Source Conn"}),te("input",{value:b,onChange:E=>y(E.target.value),className:"w-full bg-transparent border-b border-slate-700 text-xs py-1"})]}),Pe("div",{children:[te("label",{className:"text-xs text-slate-500 mb-1 block",children:"Source Table/Sheet"}),te("input",{value:x,onChange:E=>N(E.target.value),className:"w-full bg-transparent border-b border-slate-700 text-xs py-1"})]}),Pe("div",{children:[te("label",{className:"text-xs text-slate-500 mb-1 block mt-2",children:"Target Conn"}),te("input",{value:C,onChange:E=>w(E.target.value),className:"w-full bg-transparent border-b border-slate-700 text-xs py-1"})]}),Pe("div",{children:[te("label",{className:"text-xs text-slate-500 mb-1 block mt-2",children:"Target Table"}),te("input",{value:k,onChange:E=>A(E.target.value),className:"w-full bg-transparent border-b border-slate-700 text-xs py-1 text-emerald-400"})]})]}),Pe("button",{onClick:D,className:"w-full bg-indigo-600 hover:bg-indigo-500 text-white font-bold py-2 rounded-lg transition-colors flex justify-center items-center gap-2 text-sm",children:[te(cw,{size:16})," Deploy to Engine"]})]}),Pe("div",{className:"flex-1 overflow-y-auto p-4 space-y-3",children:[te("h3",{className:"text-xs font-bold text-slate-500 uppercase tracking-widest mb-4",children:"Deployed Engine Jobs"}),a.map(E=>Pe("div",{className:`p-3 rounded-xl border transition-all ${E.is_active?"bg-indigo-950/30 border-indigo-500/50":"bg-slate-800/50 border-slate-700"}`,children:[Pe("div",{className:"flex justify-between items-start mb-2",children:[te("div",{className:"font-bold text-sm truncate pr-2",children:E.name}),Pe("div",{className:"flex gap-2",children:[te("button",{onClick:()=>O(E.id,E.is_active),className:`p-1.5 rounded-md ${E.is_active?"bg-amber-500/20 text-amber-500":"bg-emerald-500/20 text-emerald-500"}`,children:E.is_active?te(oR,{size:14}):te(sR,{size:14})}),te("button",{onClick:()=>H(E.id),className:"p-1.5 bg-rose-500/10 text-rose-500 rounded-md hover:bg-rose-500/20",children:te(aR,{size:14})})]})]}),Pe("div",{className:"flex items-center gap-2 text-xs font-mono mb-2",children:[te(Uf,{size:12,className:"text-slate-500"}),te("span",{className:"text-amber-400",children:E.cron_expression}),te("span",{className:`px-2 py-0.5 rounded-full text-[10px] ${E.is_active?"bg-emerald-500/20 text-emerald-400":"bg-slate-700 text-slate-400"}`,children:E.is_active?"RUNNING IN BACKGROUND":"PAUSED"})]}),E.last_status&&Pe("div",{className:"text-[10px] bg-black/30 p-1.5 rounded text-amber-100/70 border border-slate-800 truncate",children:["Status: ",E.last_status]})]},E.id)),a.length===0&&te("div",{className:"text-center text-slate-500 text-sm mt-10",children:"No cron jobs scheduled via Orchestrator."})]})]})]})})};import{Fragment as xw,jsx as L,jsxs as ee}from"react/jsx-runtime";var Yf=import.meta.env?.VITE_API_BASE_URL||"http://localhost:3001",vw=()=>{let[r]=qe([{id:"postgres",name:"PostgreSQL Core"},{id:"google_sheets",name:"Google Sheets MCP"}]),[e,t]=qe("google_sheets"),[n,i]=qe([]),[s,o]=qe({}),[a,l]=qe([]),[c,d]=qe(null),[u,h]=qe(null),[f,p]=qe("grid"),[m,g]=qe(!0),[b,y]=qe(!1),[x,N]=qe(!1),[C,w]=qe([]),[k,A]=qe([]),[S,M]=qe(""),[D,O]=qe(null),[H,E]=qe(null),[$,G]=qe(null),[W,he]=qe(null),[_,ie]=qe(null),[Se,J]=qe(!1),[ae,fe]=qe(!1),[Oe,_e]=qe(!1),[ke,B]=qe(!1),[re,X]=qe(!1),[me,Ae]=qe(!1),[bt,xt]=qe(""),Ur=async()=>{g(!0),E(null);try{let I=await fetch(`${Yf}/api/dataway/resources?connectorId=${e}`,{headers:{"x-api-key":"dev_ak_chameleon_studio_99x"}});if(!I.ok)throw new Error("API Endpoint no disponible");let j=await I.json(),V=Array.isArray(j.resources)?j.resources:[];i(V),V.length>0?h(V[0]):h(null)}catch(I){E(I.message)}finally{g(!1)}};Gf(()=>{Ur(),localStorage.setItem("dataway_active_connector",e)},[e]);let qt=(I,j)=>{let V="";for(let z of I)if(V?V=z.script.replace(/\bSource\b/g,V):V=z.script,j&&z.id===j)break;return V},Ji=I=>{let j={id:Date.now().toString(),name:"Plantilla ETL",script:I,isValidData:!0,isComputed:!1};l([j]),d(j.id),xt(I),u&&hr(u,I)},hr=async(I,j)=>{y(!0),M(""),O(null),G(null);try{let V=await fetch(`${Yf}/api/dataway/query`,{method:"POST",headers:{"x-api-key":"dev_ak_chameleon_studio_99x","Content-Type":"application/json"},body:JSON.stringify({connectorId:e,resource:I,type:e==="postgres"?"table":"range",m_script:j||void 0,secondaryResources:k.length>0?k:void 0})});if(!V.ok){let be=await V.json().catch(()=>({}));throw new Error(be.error||`El backend Dataway rechaz\xF3 la solicitud (HTTP ${V.status})`)}let z=await V.json();w(Array.isArray(z.data)?z.data:[]),j!==void 0&&xt(j)}catch(V){G(V.message),Te.error("Error en la consulta",{description:V.message}),w([])}finally{y(!1)}};Gf(()=>{if(u){localStorage.setItem("dataway_active_resource",u);let I=qt(a,c||void 0);hr(u,I)}else localStorage.removeItem("dataway_active_resource")},[u]);let Er=(I,j)=>{if(!I.trim())return;let V=[...a],z=j&&j!==u;z&&(V=[]);let be=z?-1:V.findIndex(ze=>ze.id===c);if(be===V.length-1||c===null||be===-1){let ze={id:Math.random().toString(36).substr(2,9),name:`Paso ${V.length+1}`,script:I};V.push(ze),l(V),d(ze.id)}else V[be].script=I,l(V);let He=z?V[0].id:c||void 0,qr=qt(V,He),We=j||u;We&&hr(We,qr)};Gf(()=>{let I=j=>{let V=j.detail?.script,z=j.detail?.resource;V&&typeof V=="string"&&(z&&z!==u?(h(z),Er(V,z),Te.success(`Cambiando de forma aut\xF3noma a la tabla ${z}`)):(Er(V),Te.success("Recibido desde Agente AI")))};return window.addEventListener("intent:dataway-generate-script",I),()=>window.removeEventListener("intent:dataway-generate-script",I)},[a,c,u]);let rr=I=>{d(I);let j=qt(a,I);u&&hr(u,j)},Ar=(I,j)=>{I.stopPropagation();let V=a.filter(He=>He.id!==j);l(V);let z=V.length>0?V[V.length-1].id:null;d(z);let be=qt(V,z||void 0);u?hr(u,be):w([])},fn=()=>{l([]),d(null),xt(""),u&&hr(u,"")},Gr=I=>{let j="asc";D&&D.key===I&&D.direction==="asc"&&(j="desc"),O({key:I,direction:j})},Tr=(I,j)=>{he(null);let V="";if(I==="rename"){let z=prompt(`Renombrar columna '${j}':`,j);if(!z||z===j)return;V=`Table.RenameColumns(Source, {{"${j}", "${z}"}})`}else if(I==="remove"){if(!confirm(`\xBFEst\xE1s seguro de eliminar la columna '${j}'?`))return;V=`Table.RemoveColumns(Source, "${j}")`}else if(I==="sort")V=`Table.Sort(Source, "${j}")`;else if(I==="filter"){let z=Ce.find(He=>He[j]!==null&&He[j]!==void 0)?.[j],be="text";z!=null&&(!isNaN(Number(z))&&String(z).trim()!==""?be="number":isNaN(Number(z))&&!isNaN(Date.parse(String(z)))&&(be="date")),ie({isOpen:!0,col:j,type:be});return}else if(I==="group_sum"){let z=prompt(`Vas a agrupar por '${j}'. \xBFQu\xE9 columna deseas SUMAR para totalizar?`,"");if(!z)return;V=`Table.GroupSum(Source, "${j}", "${z}", "Total_${z}")`}else if(I==="drop_nulls")V=`Table.DropNulls(Source, "${j}")`;else if(I==="fill_nulls"){let z=prompt(`\xBFCon qu\xE9 valor (ej. 0 o "N/A") deseas rellenar los datos vac\xEDos en '${j}'?`,"0");if(z===null||z==="")return;let He=!isNaN(Number(z))&&z.trim()!==""?z:`"${z}"`;V=`Table.FillNulls(Source, "${j}", ${He})`}V&&(Er(V),Te.success("Paso generado exitosamente"))},js=(I,j,V)=>{ie(null);let z=`"${V}"`;!isNaN(Number(V))&&V.trim()!==""&&(z=V);let He=`Table.Filter(Source, "${I}", "${j}", ${z})`;Er(He),Te.success("Filtro Inteligente aplicado")},_t=(I,j,V,z)=>{J(!1);let be=`"${z}"`,He=`Table.MathColumn(Source, "${I}", "${j}", "${V}", ${be})`;Er(He),Te.success("Columna Calculada agregada")},Ce=uw(()=>{let I=[...C];if(S){let j=S.toLowerCase();I=I.filter(V=>Object.keys(V).some(z=>String(V[z]).toLowerCase().includes(j)))}return D!==null&&I.sort((j,V)=>{let z=j[D.key],be=V[D.key];return z<be?D.direction==="asc"?-1:1:z>be?D.direction==="asc"?1:-1:0}),I},[C,S,D]),ct=C.length>0?Object.keys(C[0]):[],Dn=uw(()=>{if(Ce.length===0)return{};let I={};return ct.forEach(j=>{let V=0,z=0,be=Ce.length;for(let He=0;He<be;He++){let qr=Ce[He][j];qr==null||qr===""?z++:V++}I[j]={valid:V,empty:z,total:be}}),I},[Ce,ct]),On=()=>{if(Ce.length===0)return;let I=[];I.push(ct.join(","));for(let be of Ce){let He=ct.map(qr=>{let We=be[qr];return We==null?"":`"${String(We).replace(/"/g,'""')}"`});I.push(He.join(","))}let j=new Blob([I.join(`
80
+ `)],{type:"text/csv;charset=utf-8;"}),V=URL.createObjectURL(j),z=document.createElement("a");z.setAttribute("href",V),z.setAttribute("download",`dataway_${u}_${new Date().getTime()}.csv`),document.body.appendChild(z),z.click(),document.body.removeChild(z),Te.success(`Exportados ${Ce.length} registros exitosamente`)},Mr=async()=>{if(Ce.length===0)return;let I=prompt("Ingrese el nombre de la tabla de destino en PostgreSQL:");if(I){N(!0),Te.loading(`Sincronizando ${Ce.length} registros hacia ${I}...`,{id:"sync-db"});try{let j={connectorId:"postgres",destinationTable:I,data:Ce},V=await fetch(`${Yf}/api/dataway/sync`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":"dev_ak_chameleon_studio_99x"},body:JSON.stringify(j)});if(!V.ok){let be=await V.json();throw new Error(be.error||"Error en sincronizaci\xF3n")}let z=await V.json();Te.success(`Sincronizaci\xF3n Exitosa: ${z.rowsInserted} filas insertadas en ${z.destination}`,{id:"sync-db"})}catch(j){Te.error("Error de Sincronizaci\xF3n",{description:j.message,id:"sync-db"})}finally{N(!1)}}},Un=hR(null),pn=e0({count:Ce.length,getScrollElement:()=>Un.current,estimateSize:()=>45,overscan:10}),vt=pn.getVirtualItems();return ee("div",{className:"w-full h-full flex flex-row overflow-hidden",style:{"--bg-primary":"var(--ds-surface-primary, #ffffff)","--bg-elevated":"var(--ds-surface-secondary, #f8fafc)","--bg-surface":"var(--ds-surface-tertiary, #f1f5f9)","--border-color":"var(--ds-border-default, #e2e8f0)","--text-primary":"var(--ds-text-primary, #0f172a)","--text-secondary":"var(--ds-text-secondary, #64748b)","--brand-primary":"var(--ds-accent-blue, #6366f1)","--brand-primary-hover":"var(--ds-accent-blue-hover, #4f46e5)"},children:[L(fw,{children:re&&L(hw.div,{initial:{width:0,opacity:0},animate:{width:288,opacity:1},exit:{width:0,opacity:0},transition:{duration:.2},className:"border-r border-[var(--border-color)] bg-[var(--bg-elevated)] flex flex-col h-full z-10 shrink-0 overflow-hidden",children:ee("div",{className:"w-72 flex flex-col h-full",children:[ee("div",{className:"p-6 border-b border-[var(--border-color)] flex flex-col gap-4 bg-[var(--bg-primary)]",children:[ee("div",{className:"flex items-center gap-3",children:[L("div",{className:"p-2 bg-[var(--brand-primary)]/10 rounded-xl",children:L(mR,{className:"w-6 h-6 text-[var(--brand-primary)]"})}),ee("div",{children:[L("h2",{className:"font-extrabold text-[var(--text-primary)] tracking-tight text-lg leading-none",children:"Dataway Studio"}),L("p",{className:"text-[11px] font-medium text-[var(--text-secondary)] uppercase tracking-wider mt-1",children:"M-Script Engine"})]})]}),L("select",{value:e,onChange:I=>t(I.target.value),className:"w-full bg-[var(--bg-surface)] border border-[var(--border-color)] text-[var(--text-primary)] text-sm font-bold rounded-lg px-3 py-2 outline-none cursor-pointer",children:r.map(I=>L("option",{value:I.id,children:I.name},I.id))})]}),ee("div",{className:"p-4 flex-1 overflow-y-auto w-full space-y-1.5 custom-scrollbar",children:[ee("h3",{className:"text-xs font-bold text-[var(--text-secondary)] tracking-wider uppercase mb-3 px-2 flex items-center justify-between",children:["Recursos",L("button",{onClick:Ur,className:"hover:text-[var(--text-primary)] transition-colors p-1 rounded-md",children:L(pR,{className:"w-3 h-3"})})]}),m?L("div",{className:"space-y-2 px-2",children:[1,2,3].map(I=>L("div",{className:"h-10 bg-[var(--bg-surface)] rounded-lg animate-pulse w-full"},I))}):n.map((I,j)=>ee("button",{onClick:()=>h(I),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-xl text-sm font-semibold transition-all group ${u===I?"bg-[var(--brand-primary)] text-white shadow-md":"text-[var(--text-secondary)] hover:bg-[var(--bg-surface)] hover:text-[var(--text-primary)]"}`,children:[ee("div",{className:"flex items-center gap-3",children:[L(fR,{className:`w-4 h-4 ${u===I?"text-[var(--bg-surface)]":""}`}),L("span",{className:"capitalize",children:I})]}),ee("div",{className:"flex items-center gap-2",children:[L("div",{onClick:V=>{V.stopPropagation();let z=`${e}_${I}`.replace(/[^a-zA-Z0-9_]/g,""),be=prompt("Asignar nombre de variable local (ej. Clientes) para el JOIN:",z);if(be){if(k.some(He=>He.boundName===be)){Te.error("El nombre de la variable ya existe.");return}A(He=>[...He,{connectorId:e,resource:I,boundName:be}]),Te.success(`Referencia: ${be} agregada al contexto.`)}},className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-black/10 rounded transition-colors",title:"Inyectar en Contexto Secundario (Federated Join)",children:L(gw,{className:"w-3.5 h-3.5"})}),u===I&&L(bR,{className:"w-4 h-4 opacity-70"})]})]},`${I}-${j}`))]})]})})}),ee("div",{className:"flex-1 bg-[var(--bg-surface)] flex flex-col h-full min-w-0",children:[L(Xy,{activeResource:u,activeConnector:e,isLoading:b,schemaColumns:ct,onExecute:Er,onClear:fn}),ee("div",{className:"bg-[var(--bg-primary)] border-b border-[var(--border-color)] px-4 py-2 flex items-center justify-between z-10 overflow-x-auto custom-scrollbar",children:[ee("div",{className:"flex items-center gap-2",children:[L("button",{onClick:()=>X(!re),className:`p-1.5 rounded-md border transition-colors flex items-center justify-center ${re?"bg-slate-800 text-white border-slate-700 dark:bg-indigo-500/20 dark:text-indigo-300":"bg-[var(--bg-surface)] text-[var(--text-secondary)] border-[var(--border-color)] hover:bg-[var(--bg-elevated)]"}`,title:"Alternar panel de Recursos",children:L(Lc,{className:"w-4 h-4"})}),L("button",{onClick:()=>Ae(!me),className:`p-1.5 rounded-md border transition-colors flex items-center justify-center ${me?"bg-slate-800 text-white border-slate-700 dark:bg-indigo-500/20 dark:text-indigo-300":"bg-[var(--bg-surface)] text-[var(--text-secondary)] border-[var(--border-color)] hover:bg-[var(--bg-elevated)]"}`,title:"Alternar panel de Pasos Aplicados",children:L(qf,{className:"w-4 h-4"})}),L("div",{className:"w-px h-4 bg-[var(--border-color)] mx-1"}),ee("button",{onClick:()=>J(!0),disabled:ct.length===0,className:"text-xs font-semibold px-3 py-1.5 rounded-md bg-purple-50 text-purple-700 border border-purple-200 hover:bg-purple-100 transition-colors flex items-center gap-2 disabled:opacity-50",children:[L(gw,{className:"w-3.5 h-3.5"}),"Columna Calculada"]})]}),L("div",{children:ee("button",{onClick:()=>fe(!0),className:"text-xs font-semibold px-3 py-1.5 rounded-md bg-[var(--bg-surface)] border border-[var(--border-color)] hover:bg-[var(--bg-elevated)] transition-colors flex items-center gap-2 text-[var(--text-primary)]",children:[L(Lc,{className:"w-3.5 h-3.5"}),"Gestor de Plantillas"]})}),L("div",{children:ee("button",{onClick:()=>B(!0),className:"text-xs font-semibold px-3 py-1.5 rounded-md bg-amber-50 text-amber-700 border border-amber-200 hover:bg-amber-100 transition-colors flex items-center gap-2",children:[L(ER,{className:"w-3.5 h-3.5"}),"Dataway Cron (Orchestrator)"]})}),L("div",{children:ee("button",{onClick:()=>_e(!0),disabled:!u,className:"text-xs font-semibold px-3 py-1.5 rounded-md bg-indigo-50 text-indigo-700 border border-indigo-200 hover:bg-indigo-100 transition-colors flex items-center gap-2 disabled:opacity-50",children:[L(NR,{className:"w-3.5 h-3.5"}),"Mapa Relacional (ERD)"]})})]}),ee("div",{className:"flex-1 flex min-w-0 min-h-0 bg-[var(--bg-primary)]",children:[L(fw,{children:me&&L(hw.div,{initial:{width:0,opacity:0},animate:{width:256,opacity:1},exit:{width:0,opacity:0},transition:{duration:.2},className:"border-r border-[var(--border-color)] bg-[var(--bg-elevated)] flex flex-col min-h-0 shrink-0 overflow-hidden",children:ee("div",{className:"w-64 flex flex-col h-full",children:[ee("div",{className:"p-4 border-b border-[var(--border-color)] flex items-center justify-between",children:[ee("h3",{className:"text-xs font-bold text-[var(--text-primary)] uppercase tracking-wider flex items-center gap-2",children:[L(qf,{className:"w-4 h-4 text-[var(--brand-primary)]"}),"Pasos Aplicados"]}),a.length>0&&L("button",{onClick:fn,className:"text-[var(--text-secondary)] hover:text-red-500 transition-colors",title:"Limpiar Pipeline",children:L(Kf,{className:"w-4 h-4"})})]}),ee("div",{className:"flex-1 overflow-y-auto p-3 space-y-2",children:[ee("div",{className:`p-3 rounded-lg border cursor-pointer transition-all text-sm mb-2 ${c===null?"border-[var(--brand-primary)] bg-[var(--brand-primary)]/10 text-[var(--brand-primary)]":"border-[var(--border-color)] hover:border-[var(--brand-primary)]/50 text-[var(--text-secondary)]"}`,onClick:()=>rr("source"),children:[ee("div",{className:"font-semibold flex items-center gap-2",children:[L(Lc,{className:"w-4 h-4"}),"Origen de Datos"]}),L("div",{className:"text-[10px] opacity-70 mt-1 truncate",children:u||"Seleccione una tabla"})]}),a.map((I,j)=>ee("div",{className:"flex flex-col relative",children:[L("div",{className:"absolute -top-3 left-4 h-3 w-px bg-[var(--border-color)]"}),ee("div",{className:`flex items-start justify-between p-3 rounded-lg border group cursor-pointer transition-all text-sm ${c===I.id?"border-purple-500 bg-purple-50/50 text-purple-900 shadow-sm":"border-[var(--border-color)] hover:border-purple-300 text-[var(--text-secondary)] bg-[var(--bg-primary)]"}`,onClick:()=>rr(I.id),children:[ee("div",{className:"min-w-0 pr-2",children:[L("div",{className:"font-semibold",children:I.name}),L("div",{className:"text-[10px] opacity-70 mt-1 truncate font-mono",children:I.script.length>30?I.script.substring(0,30)+"...":I.script})]}),L("button",{className:"opacity-0 group-hover:opacity-100 text-red-400 hover:text-red-600 transition-opacity p-1",onClick:V=>Ar(V,I.id),title:"Eliminar Paso",children:L(pw,{className:"w-3.5 h-3.5"})})]})]},I.id)),L("div",{className:"text-center pt-2",children:L("span",{className:"text-[10px] text-[var(--text-secondary)] font-medium",children:"Ejecuta c\xF3digo para a\xF1adir pasos"})}),k.length>0&&ee("div",{className:"mt-6 border-t border-[var(--border-color)] pt-4",children:[ee("h4",{className:"text-[10px] font-bold text-[var(--text-secondary)] uppercase tracking-wider mb-2 flex items-center justify-between",children:[L("span",{children:"Recursos Vinculados"}),L("span",{className:"bg-[var(--brand-primary)]/20 text-[var(--brand-primary)] px-1.5 py-0.5 rounded text-[9px]",children:k.length})]}),L("div",{className:"space-y-1.5",children:k.map((I,j)=>ee("div",{className:"flex flex-col p-2 rounded-lg bg-[var(--bg-primary)] border border-[var(--border-color)] group",children:[ee("div",{className:"flex items-center justify-between",children:[L("span",{className:"text-xs font-bold text-[var(--text-primary)]",children:I.boundName}),L("button",{onClick:()=>A(V=>V.filter(z=>z.boundName!==I.boundName)),className:"opacity-0 group-hover:opacity-100 text-red-400 hover:text-red-600 transition-opacity p-0.5",title:"Remover Binding",children:L(pw,{className:"w-3 h-3"})})]}),ee("div",{className:"text-[9px] text-[var(--text-secondary)] truncate flex items-center gap-1 mt-0.5",children:[L(Lc,{className:"w-2.5 h-2.5"}),I.connectorId," : ",I.resource]})]},j))}),L("div",{className:"text-[9px] text-[var(--text-secondary)] mt-2 text-center opacity-70",children:"Utilizalos en Table.NestedJoin(...)"})]})]})]})})}),L("div",{className:"flex-1 min-w-0 overflow-hidden p-6 flex flex-col relative",children:u?f==="dashboard"?L(Qy,{data:Ce,columns:ct}):ee("div",{className:"flex-1 min-w-0 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-2xl shadow-sm overflow-hidden flex flex-col relative",children:[L("div",{ref:Un,className:"overflow-auto flex-1 custom-scrollbar relative",children:ee("table",{className:"w-full text-left text-sm whitespace-nowrap",children:[L("thead",{className:"bg-[var(--bg-elevated)] sticky top-0 shadow-[0_1px_2px_rgba(0,0,0,0.05)]",style:{zIndex:10},children:L("tr",{children:ct.map(I=>{let j=Ce.length>0?Ce.find(be=>be[I]!==null&&be[I]!==void 0)?.[I]:null,V=j!=null&&!isNaN(Number(j))&&String(j).trim()!=="",z=Dn[I];return ee("th",{className:"px-6 py-4 hover:bg-[var(--bg-surface)] transition-colors select-none relative group",children:[ee("div",{className:"flex flex-col gap-1 w-full",children:[ee("div",{className:`flex items-center gap-2 text-xs font-bold text-[var(--text-secondary)] uppercase tracking-wider cursor-pointer ${V?"justify-end":""}`,onClick:()=>he(W===I?null:I),children:[I,L(CR,{className:`w-3.5 h-3.5 transition-transform ${W===I?"rotate-180 text-[var(--brand-primary)]":"opacity-0 group-hover:opacity-100"}`})]}),z&&ee("div",{className:"h-[3px] w-full bg-red-400 mt-0.5 flex overflow-hidden rounded-full opacity-70",title:`V\xE1lidos: ${z.valid} | Vac\xEDos: ${z.empty}`,children:[L("div",{className:"bg-green-500 h-full",style:{width:`${z.valid/z.total*100}%`}}),L("div",{className:"bg-gray-300 h-full",style:{width:`${z.empty/z.total*100}%`}})]})]}),W===I&&ee(xw,{children:[L("div",{className:"fixed inset-0 z-40",onClick:()=>he(null)}),ee("div",{className:"absolute top-full left-4 mt-1 w-48 bg-[var(--bg-primary)] border border-[var(--border-color)] rounded-xl shadow-xl z-50 overflow-hidden flex flex-col py-1 animate-in fade-in zoom-in-95 duration-150",children:[ee("button",{onClick:()=>Tr("sort",I),className:"px-3 py-2 text-xs font-medium text-left hover:bg-[var(--bg-surface)] flex items-center gap-2 text-[var(--text-primary)]",children:[L(xR,{className:"w-3.5 h-3.5 opacity-70"})," Ordenar Ascendente"]}),ee("button",{onClick:()=>Tr("filter",I),className:"px-3 py-2 text-xs font-medium text-left hover:bg-[var(--bg-surface)] flex items-center gap-2 text-[var(--text-primary)]",children:[L(kR,{className:"w-3.5 h-3.5 opacity-70"})," Filtrar Valor Exacto"]}),L("div",{className:"h-px bg-[var(--border-color)] my-1 w-full"}),ee("button",{onClick:()=>Tr("group_sum",I),className:"px-3 py-2 text-xs font-medium text-left hover:bg-[var(--bg-surface)] flex items-center gap-2 text-purple-600",children:[L(qf,{className:"w-3.5 h-3.5 opacity-70"})," Agrupar y Sumar"]}),L("div",{className:"h-px bg-[var(--border-color)] my-1 w-full"}),ee("button",{onClick:()=>Tr("rename",I),className:"px-3 py-2 text-xs font-medium text-left hover:bg-[var(--bg-surface)] flex items-center gap-2 text-[var(--text-primary)]",children:[L(bw,{className:"w-3.5 h-3.5 opacity-70"})," Renombrar Columna"]}),ee("button",{onClick:()=>Tr("remove",I),className:"px-3 py-2 text-xs font-medium text-left hover:bg-red-50 text-red-600 flex items-center gap-2",children:[L(Kf,{className:"w-3.5 h-3.5 opacity-70"})," Remover Columna"]}),L("div",{className:"h-px bg-[var(--border-color)] my-1 w-full"}),ee("button",{onClick:()=>Tr("drop_nulls",I),className:"px-3 py-2 text-xs font-medium text-left hover:bg-orange-50 text-orange-600 flex items-center gap-2",children:[L(Kf,{className:"w-3.5 h-3.5 opacity-70"})," Eliminar filas vac\xEDas"]}),ee("button",{onClick:()=>Tr("fill_nulls",I),className:"px-3 py-2 text-xs font-medium text-left hover:bg-orange-50 text-orange-600 flex items-center gap-2",children:[L(bw,{className:"w-3.5 h-3.5 opacity-70"})," Rellenar vac\xEDos"]})]})]})]},I)})})}),L("tbody",{className:"divide-y divide-[var(--border-color)] text-[var(--text-primary)] font-medium",children:Ce.length===0?L("tr",{children:L("td",{colSpan:ct.length,className:"h-48 text-center text-[var(--text-secondary)]",children:b?L(mw,{className:"w-8 h-8 animate-spin mx-auto mb-2 text-[var(--brand-primary)]"}):ee("span",{children:["Genera una consulta o ajusta tu filtro (",bt||"Vac\xEDo",")."]})})}):ee(xw,{children:[vt.length>0&&vt[0].start>0&&L("tr",{children:L("td",{style:{height:`${vt[0].start}px`}})}),vt.map(I=>{let j=Ce[I.index];return L("tr",{"data-index":I.index,ref:pn.measureElement,className:"hover:bg-[var(--bg-surface)]/70 transition-colors",children:ct.map(V=>{let z=j[V],be=z!=null&&!isNaN(Number(z))&&String(z).trim()!=="";return L("td",{className:`px-6 py-3 max-w-[250px] truncate text-ellipsis ${be?"text-right font-mono text-purple-700 font-semibold bg-purple-50/20":""}`,children:L("span",{title:String(z),children:z!=null?String(z):L("span",{className:"text-gray-400 italic",children:"null"})})},V)})},I.key)}),vt.length>0&&vt[vt.length-1].end<pn.getTotalSize()&&L("tr",{children:L("td",{style:{height:`${pn.getTotalSize()-vt[vt.length-1].end}px`}})})]})})]})}),ee("div",{className:"px-6 py-3 border-t border-[var(--border-color)] bg-[var(--bg-elevated)] text-xs font-semibold text-[var(--text-secondary)] flex justify-between items-center z-10",children:[ee("div",{className:"flex items-center gap-4",children:[ee("span",{children:["Total Records: ",Ce.length]}),L("div",{className:"h-4 w-px bg-[var(--border-color)]"}),ee("div",{className:"flex bg-[var(--bg-surface)] p-0.5 rounded-md border border-[var(--border-color)]",children:[ee("button",{onClick:()=>p("grid"),className:`px-3 py-1 flex items-center gap-1.5 rounded-md transition-colors ${f==="grid"?"bg-white shadow-sm text-[var(--brand-primary)]":"hover:text-[var(--text-primary)]"}`,children:[L(SR,{className:"w-3.5 h-3.5"})," DataGrid"]}),ee("button",{onClick:()=>p("dashboard"),className:`px-3 py-1 flex items-center gap-1.5 rounded-md transition-colors ${f==="dashboard"?"bg-white shadow-sm text-[var(--brand-primary)]":"hover:text-[var(--text-primary)]"}`,disabled:Ce.length===0,children:[L(wR,{className:"w-3.5 h-3.5"})," Graficar"]})]})]}),ee("div",{className:"flex items-center gap-4",children:[L("span",{className:"opacity-70",children:"Powered by Polars & Rust"}),ee("button",{onClick:On,disabled:Ce.length===0,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-md hover:bg-[var(--border-color)] transition-colors text-[var(--text-primary)] disabled:opacity-50",title:"Descargar datos en pantalla como CSV",children:[L(yR,{className:"w-3.5 h-3.5"}),L("span",{children:"Exportar CSV"})]}),ee("button",{onClick:Mr,disabled:Ce.length===0||x,className:"flex items-center gap-1.5 px-4 py-1.5 rounded-lg bg-[var(--brand-primary)] hover:bg-[var(--brand-primary-hover)] transition-colors text-white font-bold disabled:opacity-50",title:"Empujar datos transformados a una tabla en Postgres",children:[x?L(mw,{className:"w-4 h-4 animate-spin"}):L(vR,{className:"w-4 h-4"}),L("span",{children:"Sync (Push)"})]})]})]}),_&&L(tw,{isOpen:_.isOpen,column:_.col,colType:_.type,onClose:()=>ie(null),onApply:js}),L(nw,{isOpen:Se,columns:ct,onClose:()=>J(!1),onApply:_t}),L(ow,{isOpen:ae,onClose:()=>fe(!1),currentScript:qt(a),activeConnector:e,activeResource:u,onLoadPipeline:Ji}),Oe&&u&&L(lw,{sourceConnector:e,sourceResource:u,targetConnector:"postgres",targetResource:"ventas",onClose:()=>_e(!1)}),ke&&L(dw,{onClose:()=>B(!1)})]}):ee("div",{className:"m-auto flex flex-col items-center justify-center opacity-40",children:[L(gR,{className:"w-16 h-16 mb-4"}),L("h2",{className:"text-xl font-bold",children:"Sin Datos Activos"}),L("p",{className:"text-sm",children:"Selecciona o crea un Dataway."})]})})]})]}),L("style",{children:`
81
+ .custom-scrollbar::-webkit-scrollbar { width: 6px; height: 6px; }
82
+ .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
83
+ .custom-scrollbar::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 10px; }
84
+ .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: var(--text-secondary); }
85
+ `})]})};var Jf=[],yw=AR({manifest:{id:"macia-chameleon-agent",version:"2.1.0",name:"Madefront",description:"Proactive Intelligence & Liquid UI Engine",author:"Decido AI",permissions:["cortex:view","os:capture_screen"],intents:["chameleon-change-view"],widgets:[{id:"chameleon-kanban-view",name:"Madefront Kanban",defaultZone:"ide-editor",component:ja},{id:"chameleon-ventas-view",name:"Ventas & Dise\xF1o",defaultZone:"ide-editor",component:pg},{id:"chameleon-caja-view",name:"Caja & Pagos",defaultZone:"ide-editor",component:gg},{id:"chameleon-planta-view",name:"Producci\xF3n",defaultZone:"ide-editor",component:bg},{id:"chameleon-despacho-view",name:"Log\xEDstica",defaultZone:"ide-editor",component:vg},{id:"chameleon-discovery-view",name:"Studio Admin",defaultZone:"ide-editor",component:$g},{id:"chameleon-sheet-view",name:"Vista Excel (Datos)",defaultZone:"ide-editor",component:Ua},{id:"chameleon-database-admin",name:"Database Admin (CRUD)",defaultZone:"ide-editor",component:Vg},{id:"chameleon-dataway-studio",name:"Dataway M-Script Studio",defaultZone:"ide-editor",component:vw}],blueprints:[]},onMount:r=>{r.logger.log("Chameleon AI mounting..."),Jf=[r.subscribeToEvent("intent:chameleon-change-view",t=>{let n=t?.matches;if(!n||!n[0])return;let i=n[0].toLowerCase(),s=o=>{r.callKernel("activate_plugin",{pluginId:o}).catch(a=>{r.logger.warn(`Failed to activate ${o}:`,a)})};i.includes("venta")&&s("cortex-omnichannel"),i.includes("caja")&&s("cortex-commander"),i.includes("planta")&&s("cortex-forge"),i.includes("admin")&&s("cortex-admin")})]},onUnmount:()=>{Jf.forEach(r=>r()),Jf=[],console.log("[Chameleon] Cleaned up \u2014 all subscriptions removed.")},onError:(r,e)=>{console.error(`[Chameleon] Error during ${e}:`,r)}});import{Fragment as OR,jsx as un,jsxs as _c}from"react/jsx-runtime";ww("sentinel-ui",async()=>({manifest:{...tm,baseUrl:"http://localhost:3333",iframeUrls:{"sentinel-telemetry":"/","sentinel-errors":"/errors","sentinel-replays":"/replays"}},iframeUrls:rm}));ww("macia-chameleon-agent",async()=>({manifest:yw.manifest}));function zc({aiProvider:r,VoiceWidget:e,config:t}={}){let n=ne(w=>w.isBooting),i=ne(w=>w.isSidebarOpen),s=ne(w=>w.setIsSidebarOpen),o=ne(w=>w.isCreatorMode),a=ne(w=>w.creatorViewMode),l=ne(w=>w.prototypeBrand),c=ce(w=>w.isImmersive),d=ce(w=>w.setIsImmersive);Zp(),Qp(),DR();let{activeConfig:u}=cp(t,l),{showCanvas:h}=fa();em();let f=Fc(w=>w.manifests),p=Fc(w=>w.loading),m=Fc(w=>w.syncWithRegistry),g=Fc(w=>w.getManifest);Xf.useEffect(()=>{let w=Object.values(f);if(w.length===0)return;Kr.restoreFromPersistence(A=>{if(A.startsWith("sdui-")){let S=A.replace("sdui-","");for(let M of w){let D=M.widgets?.find(O=>O.id===S);if(D?.schema)return D.schema}}})&&Kr.size>0&&ce.getState().setSlot("R3","widget-panel")},[f]);let b=MR((w,k,A)=>{let S=g(w);if(!S){console.warn(`[Plugin] No manifest loaded for ${w}`);return}console.log(`[Plugin] Opening widgets for ${w}:${k}`);let M=S.widgets?.find(O=>O.id===k);M?.schema&&Kr.register({id:`sdui-${k}`,pluginId:w,title:`${A} (SDUI)`,icon:"\u{1F7E2}",slot:"tab",schema:M.schema,order:1});let D=S.iframeUrls?.[k];if(D!==void 0){let O=D.startsWith("http")?D:`${S.baseUrl||""}${D}`;Kr.register({id:`iframe-${k}`,pluginId:w,title:`${A} (iframe)`,icon:"\u{1F535}",slot:"tab",url:O,order:2})}M?.component&&Kr.register({id:`react-${k}`,pluginId:w,title:`${A}`,icon:"\u26A1",slot:"tab",component:M.component,order:3}),M?.schema?Kr.setActive(`sdui-${k}`):M?.component?Kr.setActive(`react-${k}`):Kr.setActive(`iframe-${k}`),ce.getState().setSlot("R3","widget-panel")},[g]);Bc(()=>{let w=A=>{let S=A.detail?.pluginId,M=A.detail?.view;if(S==="chameleon"){let D=A.detail?.viewId;D||(M==="discovery_admin"||M==="whatsapp_studio"?D="chameleon-discovery-view":M==="enterprise_kanban"?D="chameleon-kanban-view":D="chameleon-discovery-view"),b("macia-chameleon-agent",D,M||"WhatsApp Studio"),M&&setTimeout(()=>window.dispatchEvent(new CustomEvent("chameleon:set-view",{detail:{view:M}})),100)}},k=A=>{let S=A.detail?.view?.toLowerCase();S&&(S.includes("kanban")||S.includes("producci\xF3n")||S.includes("produccion")?b("macia-chameleon-agent","chameleon-kanban-view","Kanban de Producci\xF3n"):S.includes("excel")||S.includes("ventas")||S.includes("datos")?b("macia-chameleon-agent","chameleon-sheet-view","Google Sheets"):(S.includes("chat")||S.includes("whatsapp")||S.includes("studio")||S.includes("discovery"))&&b("macia-chameleon-agent","chameleon-discovery-view","WhatsApp Studio"))};return window.addEventListener("studio:open-plugin",w),window.addEventListener("studio:change-view",k),()=>{window.removeEventListener("studio:open-plugin",w),window.removeEventListener("studio:change-view",k)}},[b]);let y=Xf.useCallback(()=>{try{let w=localStorage.getItem("decido-plugin-registry-v10"),k=localStorage.getItem("decido-plugin-registry-v9"),A=w||k,S=[];A&&(S=JSON.parse(A)?.state?.registry||[]);let M=S.filter(D=>D.enabled).map(D=>({name:D.name,url:D.url||""}));return M.some(D=>D.name==="macia-chameleon-agent")||M.push({name:"macia-chameleon-agent",url:""}),M}catch(w){console.error("[ManifestRegistry] Error reading plugin registry:",w)}return[{name:"macia-chameleon-agent",url:""}]},[]),[x,N]=Xf.useState(y);Bc(()=>{N(y());let w=()=>{let A=y();N(S=>JSON.stringify(S)===JSON.stringify(A)?S:A)};window.addEventListener("storage",w),window.addEventListener("focus",w);let k=setInterval(w,5e3);return()=>{window.removeEventListener("storage",w),window.removeEventListener("focus",w),clearInterval(k)}},[y]),Bc(()=>{x.length>0&&m(x)},[x,m]);let C=TR(()=>{let w=[],k=Object.values(f);for(let A of k)if(x.some(M=>M.name===A.id||M.name.includes(A.id)||A.id.includes(M.name)))if(A.sidebarItems?.length){let M=new Map;for(let D of A.sidebarItems){let O=D.section||"default";M.has(O)||M.set(O,{title:D.sectionTitle||A.name,items:[]}),M.get(O).items.push(D)}for(let[D,O]of M)w.push({id:`plugin-${A.id}-${D}`,title:O.title,collapsible:!0,items:O.items.map(H=>({id:`${A.id}-${H.id}`,label:H.label,onClick:()=>{b(A.id,H.targetWidget||"",H.label)}}))})}else w.push({id:`plugin-${A.id}`,title:`\u{1F9E9} ${A.name}`,collapsible:!0,items:A.widgets.map(M=>({id:`${A.id}-${M.id}`,label:M.name,onClick:()=>b(A.id,M.id,M.name)}))});for(let A of p)w.push({id:`loading-${A}`,title:"\u23F3 Loading...",collapsible:!1,items:[{id:"loading",label:A,onClick:()=>{}}]});if(typeof window<"u"&&"__TAURI_INTERNALS__"in window&&w.push({id:"wasm-plugins",title:"\u26A1 WASM Plugins",collapsible:!0,items:[{id:"wasm-demo-math",label:"demo-math-plugin",onClick:()=>{Kr.register({id:"wasm-demo-math",pluginId:"wasm-native",title:"Demo Math (WASM)",icon:"\u26A1",slot:"tab",scriptUrl:"wasm://demo-math-plugin/run",order:10}),Kr.setActive("wasm-demo-math"),ce.getState().setSlot("R3","widget-panel")}}]}),w.length===0&&x.length>0)for(let A of x)!A.url&&!f[A.name]&&w.push({id:`plugin-${A.name}`,title:"\u{1F50C} Plugin Instalado",collapsible:!0,items:[{id:"info",label:A.name.substring(0,24),onClick:()=>{}}]});return console.log("[ManifestRegistry] Sidebar sections:",w.length,w.map(A=>A.title)),w},[f,x,b,p]);return Bc(()=>{let w=ce.getState();w.slots?.R3!=="widget-panel"&&(o?w.setSlot("R3",a==="timeline"?"timeline-editor":"graph-editor"):w.setSlot("R3",null))},[o,a]),n?un(Xp,{}):_c(OR,{children:[un(jp,{}),_c("div",{className:"h-full w-full bg-surface-primary flex font-sans relative overflow-hidden text-text-primary",children:[un("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E')] opacity-[0.15] mix-blend-overlay pointer-events-none z-0"}),un("div",{className:"md:hidden",children:un(jc,{isOpen:i,onClose:()=>s(!1),menuSections:C})}),_c("div",{className:"flex-1 flex h-full relative z-20",children:[un("div",{className:`hidden md:flex shrink-0 h-full transition-all duration-300 ease-in-out overflow-hidden bg-surface-secondary ${i&&!c?"w-[280px] min-w-[280px]":"w-0 min-w-0"}`,children:un(jc,{isOpen:i&&!c,onClose:()=>s(!1),menuSections:C})}),_c("div",{className:"flex-1 flex flex-col h-full min-w-0 overflow-hidden relative",children:[!c&&un(ya,{modelLabel:u?.greetingText||"yo.decido"}),c&&un("button",{onClick:()=>d(!1),className:"fixed top-3 right-3 z-900 px-3 py-1.5 rounded-full bg-surface-overlay backdrop-blur-md border border-border-default text-[10px] text-text-secondary hover:text-text-primary hover:bg-surface-overlay transition-all opacity-0 hover:opacity-100 focus:opacity-100",title:"Salir de modo inmersivo (\u2318\u21E7F)",children:"ESC \xB7 Salir inmersivo"}),un(cd,{slotProps:{aiProvider:r,VoiceWidget:e,config:t},children:un(qc,{})})]})]})]})]})}import{useEffect as Sw,useState as RR,useMemo as IR}from"react";import{Panel as Cw,Group as PR,Separator as LR}from"react-resizable-panels";import{useEngineStore as BR}from"@decido/engine";import{useTimelineStore as FR}from"@decido/engine";import{usePlaybackSimulator as _R}from"@decido/engine";import{useRef as zR}from"react";import{Fragment as $R,jsx as Mn,jsxs as kw}from"react/jsx-runtime";function Nw({aiProvider:r,VoiceWidget:e,config:t,socketInstance:n,width:i="100%",height:s="100%"}){let{step:o,selectedProfile:a,isBooting:l,prototypeBrand:c,setInputValue:d}=ne(),{resetEngine:u}=BR(),h=FR(S=>S.setActiveTimeline),{demoState:f,showCanvas:p,setShowCanvas:m}=fa(),g=zR(null),b=IR(()=>({id:`tape-${c}`,events:[{t:.1,event:{type:"SYSTEM_START"},description:"Arranque Autom\xE1tico (Player)"}]}),[c]),{isPlaying:y,setIsPlaying:x,resetSimulation:N}=_R(b);Sw(()=>{h(c),u(),N();let S=setTimeout(()=>x(!0),100);return()=>clearTimeout(S)},[c]);let C=t||{environments:{},voices:[]},w=C.environments[c]||Object.values(C.environments)[0]||{},[k,A]=RR([]);return Sw(()=>{A(S=>{let M=w.suggestions||[];return JSON.stringify(S)===JSON.stringify(M)?S:M})},[w.suggestions]),Mn(Xi,{socketInstance:n,isConnected:!!n?.connected,children:Mn("div",{style:{width:i,height:s},className:"bg-surface-primary flex font-sans relative overflow-hidden text-text-primary rounded-xl border border-border-default shadow-lg",children:kw(PR,{orientation:"horizontal",className:"flex-1 w-full h-full relative z-20",children:[Mn(Cw,{id:"player-chat",defaultSize:p?60:100,minSize:30,className:"flex flex-col relative h-full bg-surface-primary",children:Mn("div",{className:"flex-1 w-full relative z-20 overflow-hidden flex flex-col",children:Mn(Gc,{fallbackName:"Motor de Chat (Player)",children:Mn(ap,{step:o,selectedProfile:a,authAvailableLicenses:[],handleProfileSelect:()=>{},activeConfig:w,demoState:f,suggestions:k,setInputValue:d,isGenerating:!1,config:C,isCreatorMode:!1,handleGeneratePlayground:async()=>{}})})})}),p&&kw($R,{children:[Mn(LR,{className:"w-1.5 hover:bg-cyan-500/20 active:bg-cyan-500/30 transition-colors cursor-col-resize z-40 relative group flex items-center justify-center border-l-2 border-border-subtle"}),Mn(Cw,{id:"player-canvas",defaultSize:40,minSize:20,className:"bg-surface-secondary h-full relative z-30 overflow-hidden",children:Mn(Gc,{fallbackName:"Lienzo 3D (Player)",children:Mn(dp,{showCanvas:p,setShowCanvas:m,activeConfig:w,prototypeBrand:c,activeState:f,chartData:[],dragConstraintsRef:g})})})]})]})})})}import{useState as Aw,useEffect as qR}from"react";import{Panel as KR,Group as YR}from"react-resizable-panels";import{useRef as HR,useEffect as WR}from"react";import{motion as VR,AnimatePresence as jR}from"motion/react";import{Sparkles as UR,Terminal as GR}from"lucide-react";import{jsx as Ft,jsxs as hn}from"react/jsx-runtime";var Ew=({messages:r,onSendMessage:e,isGenerating:t,agentName:n="Decido OS",themeBrand:i="decido"})=>{let s=HR(null);return WR(()=>{s.current&&s.current.scrollTo({top:s.current.scrollHeight,behavior:"smooth"})},[r,t]),hn("div",{className:"flex flex-col h-full overflow-hidden w-full max-w-4xl mx-auto pb-4 relative",children:[hn("div",{ref:s,className:"flex-1 overflow-y-auto pr-4 custom-scrollbar scroll-smooth flex flex-col gap-6 pb-20 mt-8",children:[r.length===0&&hn("div",{className:"flex flex-col gap-4",children:[hn("h1",{className:"text-3xl font-semibold leading-tight text-text-primary/50",children:[Ft("span",{className:"bg-gradient-to-r from-cyan-400 to-blue-500 text-transparent bg-clip-text",children:"Modo Agente Aut\xF3nomo"}),Ft("br",{}),"\xBFQu\xE9 vamos a construir en el Sandbox?"]}),hn("p",{className:"text-sm text-text-muted font-mono",children:["// ",n," conectado al demonio Rust (core-rust) con ejecuci\xF3n nativa."]})]}),r.map(o=>hn("div",{className:`flex flex-col gap-2 ${o.role==="user"?"items-end":"items-start"}`,children:[o.text&&Ft("div",{className:`p-4 rounded-2xl max-w-[85%] ${o.role==="user"?"bg-cyan-500/10 border border-cyan-500/20 text-cyan-50":o.role==="system"?"bg-orange-500/10 border border-orange-500/20 text-orange-200 font-mono text-xs":"bg-surface-tertiary border border-border-subtle text-text-primary"}`,children:o.text}),o.toolCalls&&o.toolCalls.map((a,l)=>hn("div",{className:"w-full max-w-[85%] bg-[#0d1117] border border-border-strong rounded-lg overflow-hidden my-2",children:[hn("div",{className:"flex items-center gap-2 bg-[#161b22] px-3 py-2 border-b border-border-strong",children:[Ft(GR,{size:14,className:"text-slate-400"}),Ft("span",{className:"text-xs font-mono text-cyan-400 font-bold",children:a.name}),Ft("span",{className:"flex-1"}),Ft("span",{className:`text-[10px] uppercase font-bold px-2 py-0.5 rounded-full ${a.status==="running"?"bg-amber-500/20 text-amber-500 animate-pulse":a.status==="success"?"bg-emerald-500/20 text-emerald-500":a.status==="error"?"bg-red-500/20 text-red-500":"bg-slate-500/20 text-slate-500"}`,children:a.status})]}),hn("div",{className:"p-3",children:[hn("pre",{className:"text-[10px] font-mono text-slate-300 whitespace-pre-wrap break-words",children:[Ft("span",{className:"text-slate-500",children:"// Argumentos:"}),Ft("br",{}),JSON.stringify(a.args,null,2)]}),a.output&&Ft("div",{className:"mt-2 pt-2 border-t border-slate-800",children:Ft("pre",{className:"text-[10px] font-mono whitespace-pre-wrap break-words text-emerald-400/80",children:a.output.length>500?a.output.substring(0,500)+"... [TRUNCADO]":a.output})})]})]},l))]},o.id)),Ft(jR,{children:t&&hn(VR.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},exit:{opacity:0},className:"flex gap-4 items-center",children:[Ft("div",{className:"w-8 h-8 rounded-full border border-cyan-500/30 flex items-center justify-center bg-cyan-500/10",children:Ft(UR,{size:14,className:"text-cyan-400 animate-pulse"})}),Ft("span",{className:"text-xs text-cyan-400/70 font-mono animate-pulse",children:"Razonando siguiente acci\xF3n..."})]})})]}),Ft("div",{className:"shrink-0 w-full px-4 pb-2 z-50",children:Ft(op,{isGenerating:t,onSend:e,isVoiceActive:!1,setIsVoiceActive:()=>{},showCanvas:!1,setShowCanvas:()=>{},prototypeBrand:i,setPrototypeBrand:()=>{}})})]})};import{jsx as Ws}from"react/jsx-runtime";function Tw({socketInstance:r}){let[e,t]=Aw([]),[n,i]=Aw(!1);qR(()=>{if(!r)return;let o=a=>{if(console.log("[AgentPlayer] Recibido orchestrator-event:",a),a.event_type==="AgentStreamEvent"&&a.data){let l=a.data,c=a.agent_id||"decido-agent";t(d=>{let u=d[d.length-1],h=u&&u.role==="agent"&&u.id===c,f=h?[...u.toolCalls||[]]:[],p=h?u.text:"";if(l.type==="Think"?p+=l.content:l.type==="ToolCall"?f.push({name:l.tool_name||"unknown_tool",args:l.tool_args||{},status:"running"}):l.type==="ToolResult"?f.length>0&&(f[f.length-1].status="success",f[f.length-1].output=l.content):l.type==="Message"&&(p+=l.content,i(!1)),h){let m=[...d];return m[m.length-1]={...u,text:p,toolCalls:f},m}else return[...d,{id:c,role:"agent",text:p,toolCalls:f}]})}else a.event_type==="SpawnAgentRequest"&&i(!0)};return r.on("orchestrator-event",o),()=>{r.off("orchestrator-event",o)}},[r]);let s=o=>{if(!o.trim()||!r)return;let a={id:Date.now().toString(),role:"user",text:o};t(l=>[...l,a]),i(!0),r.emit("rpc_call",{cmd:"send_message",args:{from:"AgentPlayerUI",to:"dev-master",intent:"chat_request",payload:o,priority:"High"}})};return Ws(Xi,{socketInstance:r,isConnected:!!r?.connected,children:Ws("div",{className:"bg-surface-primary flex font-sans relative overflow-hidden text-text-primary rounded-xl border border-border-default shadow-lg w-full h-[800px]",children:Ws(YR,{orientation:"horizontal",className:"flex-1 w-full h-full relative z-20",children:Ws(KR,{id:"agent-chat",defaultSize:100,minSize:30,className:"flex flex-col relative h-full bg-surface-primary",children:Ws("div",{className:"flex-1 w-full relative z-20 overflow-hidden flex flex-col pt-4",children:Ws(Ew,{messages:e,onSendMessage:s,isGenerating:n})})})})})})}import{useState as Mw,useCallback as Zf,useRef as JR}from"react";var Qf={maxAttempts:3,initialDelay:500,maxDelay:3e4,retryableStatusCodes:[429,500,502,503]};function XR(r={}){let{model:e="gemini-flash-lite-latest",systemInstruction:t,maxRetries:n=Qf.maxAttempts,initialRetryDelay:i=Qf.initialDelay}=r,[s,o]=Mw(!1),[a,l]=Mw(null),c=JR(null),d=ne(p=>p.addChatMessage),u=Zf(()=>localStorage.getItem("google_gemini_api_key")||import.meta.env?.VITE_GEMINI_API_KEY||"",[]),h=Zf(async p=>{let m=u();if(!m){l('No Gemini API key found. Set it in localStorage "google_gemini_api_key" or VITE_GEMINI_API_KEY.'),d({type:"error",sender:"system",text:'\u26A0\uFE0F No se encontr\xF3 API key de Gemini. Config\xFArala en localStorage como "google_gemini_api_key".'});return}o(!0),l(null),d({type:"text",sender:"user",text:p});let g=[],b=Date.now();g.push({type:"thinking",label:"Processing",startTime:b});let y=new AbortController;c.current=y;let x={...Qf,maxAttempts:n,initialDelay:i};try{let N=`https://generativelanguage.googleapis.com/v1beta/models/${e}:streamGenerateContent?alt=sse&key=${m}`,C={contents:[{role:"user",parts:[{text:p}]}],generationConfig:{temperature:.7,maxOutputTokens:4096}};t&&(C.systemInstruction={parts:[{text:t}]});let w=null,k=x.initialDelay;for(let H=1;H<=x.maxAttempts&&!y.signal.aborted;H++)try{if(w=await fetch(N,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(C),signal:y.signal}),w.ok)break;if(x.retryableStatusCodes.includes(w.status)&&H<x.maxAttempts){g.push({type:"retry",label:`Retry ${H}/${x.maxAttempts} (HTTP ${w.status})`,startTime:Date.now()});let $=`retry-${Date.now()}`;ne.getState().upsertChatMessage($,{id:$,type:"alert",sender:"system",text:`\u{1F504} Reintentando (${H}/${x.maxAttempts})... HTTP ${w.status}`,timestamp:Date.now()}),await new Promise(G=>setTimeout(G,k)),k=Math.min(k*2,x.maxDelay),w=null;continue}let E=await w.text();throw new Error(`Gemini API error ${w.status}: ${E.slice(0,200)}`)}catch(E){if(E.name==="AbortError"||H>=x.maxAttempts)throw E;g.push({type:"retry",label:`Retry ${H}/${x.maxAttempts} (network)`,startTime:Date.now()}),await new Promise($=>setTimeout($,k)),k=Math.min(k*2,x.maxDelay)}if(!w||!w.ok)throw new Error("All retry attempts exhausted");g[0].endTime=Date.now();let A=Date.now();g.push({type:"text_delta",label:"Streaming",startTime:A});let S=w.body?.getReader();if(!S)throw new Error("No response body reader");let M=new TextDecoder,D="",O=`gemini-${Date.now()}`;for(;;){let{done:H,value:E}=await S.read();if(H)break;let G=M.decode(E,{stream:!0}).split(`
86
+ `);for(let W of G){if(!W.startsWith("data: "))continue;let he=W.slice(6).trim();if(!(!he||he==="[DONE]"))try{let ie=JSON.parse(he)?.candidates?.[0];if(!ie)continue;let Se=ie?.content?.parts?.[0]?.text;Se&&(D+=Se,ne.getState().upsertChatMessage(O,{id:O,type:"text",sender:"agent",text:D,timestamp:Date.now(),executionSteps:[...g]})),ie.finishReason&&ie.finishReason!=="STOP"&&g.push({type:"text_complete",label:`Finished: ${ie.finishReason}`,startTime:Date.now(),endTime:Date.now()})}catch{}}}if(!D.trim()&&!y.signal.aborted)return g.push({type:"retry",label:"Content retry (empty response)",startTime:Date.now()}),d({type:"alert",sender:"system",text:"\u{1F504} Respuesta vac\xEDa, reintentando..."}),o(!1),c.current=null,h(p);g[g.length-1].endTime??=Date.now(),g.push({type:"text_complete",label:"Complete",startTime:Date.now(),endTime:Date.now()}),ne.getState().upsertChatMessage(O,{id:O,type:"text",sender:"agent",text:D,timestamp:Date.now(),executionSteps:g})}catch(N){N.name==="AbortError"?d({type:"alert",sender:"system",text:"\u23F9\uFE0F Generaci\xF3n cancelada por el usuario."}):(l(N.message),d({type:"error",sender:"system",text:`\u274C Error: ${N.message}`}))}finally{o(!1),c.current=null}},[e,t,n,i,u,d]),f=Zf(()=>{c.current?.abort()},[]);return{sendMessage:h,abort:f,isStreaming:s,error:a}}import{useEffect as cI}from"react";import{registerUIBridge as dI}from"@decido/engine";import{PluginRegistry as jr}from"@decido/core";import{DialoguePlugin as uI,LogicPlugin as hI,UIStatePlugin as fI,SubflowPlugin as pI,EndSubflowPlugin as mI,UIRendererPlugin as gI}from"@decido/engine";import $c,{useEffect as Dw,useCallback as ZR}from"react";import{AnimatePresence as QR,motion as Ow}from"motion/react";import{Search as eI,Command as tI,Package as rI,ArrowRight as nI,Grid3X3 as Vs,Maximize2 as iI,RotateCcw as sI,Layout as Hc,MessageSquare as oI}from"lucide-react";import{useManifestRegistry as aI}from"@decido/plugin-engine";import{Fragment as Rw,jsx as je,jsxs as jn}from"react/jsx-runtime";function ep(){let[r,e]=$c.useState(!1),[t,n]=$c.useState(""),i=$c.useRef(null),s=aI(d=>d.manifests),o=$c.useMemo(()=>{let d=[];return Object.values(s).forEach(u=>{u.widgets&&u.widgets.forEach(h=>{h.defaultZone==="overlay"&&h.component&&d.push({id:h.id,component:h.component})})}),d},[s]);Dw(()=>{let d=u=>{(u.metaKey||u.ctrlKey)&&u.key==="k"&&(u.preventDefault(),e(h=>!h)),u.key==="Escape"&&r&&e(!1)};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[r]),Dw(()=>{r&&i.current&&setTimeout(()=>i.current?.focus(),100)},[r]);let a=ZR(d=>{e(!1),n("");let u=ce.getState();if(d.startsWith("slot:")){let[h,f,p]=d.split(":");u.setSlot(f,p||null);return}if(d.startsWith("preset:")){let h=d.split(":")[1];u.resetLayout(h);return}if(d==="open:omnichannel"){Ks.getState().pushStage({id:`omni-${Date.now()}`,name:"Bandeja Omnicanal",shellType:"shell-omnichannel",data:{}});return}switch(d){case"toggle-creator":u.setIsCreatorMode(!u.isCreatorMode);break;case"toggle-sidebar":u.setIsSidebarOpen(!u.isSidebarOpen);break;case"toggle-canvas":u.setShowCanvas(!u.showCanvas);break;case"toggle-immersive":u.setIsImmersive(!u.isImmersive);break;case"reset-layout":u.resetLayout("player");break;default:break}},[]),l=[{id:"toggle-creator",label:"Toggle Creator Mode",shortcut:"\u2318\u21E7C",icon:je(tI,{size:14}),category:"Modo"},{id:"toggle-sidebar",label:"Toggle Sidebar",shortcut:"\u2318B",icon:je(nI,{size:14}),category:"Modo"},{id:"toggle-canvas",label:"Toggle Canvas",shortcut:"\u2318\u21E7V",icon:je(rI,{size:14}),category:"Modo"},{id:"toggle-immersive",label:"Modo Inmersivo",shortcut:"\u2318\u21E7F",icon:je(iI,{size:14}),category:"Modo"},{id:"preset:creator",label:"Preset: Creator",shortcut:"",icon:je(Hc,{size:14}),category:"Layout"},{id:"preset:player",label:"Preset: Player",shortcut:"",icon:je(Hc,{size:14}),category:"Layout"},{id:"preset:minimal",label:"Preset: Minimal",shortcut:"",icon:je(Hc,{size:14}),category:"Layout"},{id:"preset:studio",label:"Preset: Studio",shortcut:"",icon:je(Hc,{size:14}),category:"Layout"},{id:"reset-layout",label:"Reset Layout",shortcut:"",icon:je(sI,{size:14}),category:"Layout"},{id:"slot:R1:chat",label:"R1 \u2192 Chat",shortcut:"",icon:je(Vs,{size:14}),category:"Slots"},{id:"slot:R1:debug",label:"R1 \u2192 Debug",shortcut:"",icon:je(Vs,{size:14}),category:"Slots"},{id:"slot:R3:graph-editor",label:"R3 \u2192 Graph Editor",shortcut:"",icon:je(Vs,{size:14}),category:"Slots"},{id:"slot:R3:canvas",label:"R3 \u2192 Canvas",shortcut:"",icon:je(Vs,{size:14}),category:"Slots"},{id:"slot:R4:terminal",label:"R4 \u2192 Terminal",shortcut:"",icon:je(Vs,{size:14}),category:"Slots"},{id:"slot:R4:debug",label:"R4 \u2192 Debug",shortcut:"",icon:je(Vs,{size:14}),category:"Slots"},{id:"open:omnichannel",label:"Abrir Bandeja Omnicanal (WhatsApp)",shortcut:"",icon:je(oI,{size:14}),category:"Herramientas"}],c=t?l.filter(d=>d.label.toLowerCase().includes(t.toLowerCase())):l;return jn(Rw,{children:[je(QR,{children:r&&jn(Rw,{children:[je(Ow.div,{initial:{opacity:0},animate:{opacity:1},exit:{opacity:0},onClick:()=>e(!1),className:"fixed inset-0 bg-surface-overlay backdrop-blur-xs z-9998"}),jn(Ow.div,{initial:{opacity:0,y:-20,scale:.95},animate:{opacity:1,y:0,scale:1},exit:{opacity:0,y:-20,scale:.95},transition:{type:"spring",damping:25,stiffness:300},className:`fixed top-[15%] left-1/2 -translate-x-1/2 w-[540px] max-w-[90vw] z-9999
87
+ bg-surface-tertiary border border-border-default rounded-2xl shadow-2xl overflow-hidden`,children:[jn("div",{className:"flex items-center gap-3 px-4 py-3 border-b border-border-subtle",children:[je(eI,{size:18,className:"text-text-muted shrink-0"}),je("input",{ref:i,value:t,onChange:d=>n(d.target.value),placeholder:"Buscar comandos, slots, plugins...",className:"flex-1 bg-transparent text-text-primary text-sm outline-hidden placeholder:text-text-muted"}),je("kbd",{className:"text-[10px] text-text-muted bg-surface-glass px-1.5 py-0.5 rounded border border-border-default font-mono",children:"ESC"})]}),jn("div",{className:"max-h-[300px] overflow-y-auto p-2",children:[c.map(d=>jn("button",{onClick:()=>a(d.id),className:`w-full flex items-center gap-3 px-3 py-2.5 rounded-xl text-sm
88
+ text-text-secondary hover:text-text-primary hover:bg-surface-glass transition-colors group`,children:[je("span",{className:`w-6 h-6 rounded-lg bg-surface-glass flex items-center justify-center
89
+ group-hover:bg-cyan-500/10 group-hover:text-cyan-400 transition-colors`,children:d.icon}),je("span",{className:"flex-1 text-left",children:d.label}),d.shortcut&&je("kbd",{className:"text-[10px] text-text-muted font-mono",children:d.shortcut})]},d.id)),c.length===0&&jn("div",{className:"text-center py-8 text-text-muted text-sm",children:['No se encontraron comandos para "',t,'"']})]}),jn("div",{className:"flex items-center justify-between px-4 py-2 border-t border-border-subtle text-[10px] text-text-muted",children:[je("span",{children:"\u2318K para abrir \xB7 ESC para cerrar"}),jn("span",{className:"flex items-center gap-1",children:[je("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500/60"}),"Decido OS"]})]})]})]})}),o.map(d=>{let u=d.component;return je(u,{},d.id)})]})}import{useEffect as lI}from"react";import{useTimelineStore as Iw}from"@decido/engine";function Pw(){lI(()=>{let r=e=>{if(e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement)return;let t=e.metaKey||e.ctrlKey;if(t&&e.shiftKey&&e.code==="KeyC"){e.preventDefault();let n=ce.getState(),i=ne.getState(),s=!n.isCreatorMode;n.setIsCreatorMode(s),i.setIsCreatorMode(s);return}if(t&&!e.shiftKey&&e.code==="KeyB"){e.preventDefault();let n=ce.getState(),i=ne.getState(),s=!n.isSidebarOpen;n.setIsSidebarOpen(s),i.setIsSidebarOpen(s);return}if(t&&e.shiftKey&&e.code==="KeyV"){e.preventDefault();let n=ce.getState(),i=ne.getState(),s=!n.showCanvas;n.setShowCanvas(s),i.setShowCanvas(s);return}if(t&&e.shiftKey&&e.code==="KeyX"){e.preventDefault();let n=ce.getState(),i=ne.getState(),s=!n.showChat;n.setShowChat(s),i.setShowChat(s);return}if(t&&e.shiftKey&&e.code==="KeyF"){e.preventDefault();let n=ce.getState();n.setIsImmersive(!n.isImmersive);return}if(t&&e.shiftKey&&e.code==="KeyP"){e.preventDefault(),ce.getState().resetLayout("player");return}if(e.code==="Escape"&&ce.getState().isImmersive){e.preventDefault(),ce.getState().setIsImmersive(!1);return}if(t&&e.shiftKey&&e.code==="KeyD"){e.preventDefault(),qn.getState().togglePanel();return}if(t&&e.key==="z"&&ne.getState().isCreatorMode){e.preventDefault(),e.shiftKey?(Iw.getState().redo(),ne.getState().addLog("Topolog\xEDa: Acci\xF3n Rehecha","info")):(Iw.getState().undo(),ne.getState().addLog("Topolog\xEDa: Acci\xF3n Deshecha","info"));return}};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[])}import{jsx as Fw,jsxs as yI}from"react/jsx-runtime";var Lw=!1;function bI(){Lw||(Lw=!0,dI({addLog:(r,e)=>ne.getState().addLog(r,e),pushMorphStage:r=>{Ks.getState().pushStage(r),ce.getState().pushStage(r)},clearMorphStages:()=>{Ks.getState().clearStages(),ce.getState().clearStages()},showCanvas:r=>{ne.getState().setShowCanvas(r),ce.getState().setShowCanvas(r)},setSidebarOpen:r=>{ne.getState().setIsSidebarOpen(r),ce.getState().setIsSidebarOpen(r)},setDemoState:r=>ne.getState().setDemoState(r),getActiveBrand:()=>ne.getState().prototypeBrand,setActiveBrand:r=>ne.getState().setPrototypeBrand(r),addChatMessage:r=>ne.getState().addChatMessage(r),isMuted:()=>ne.getState().isMuted,getSelectedVoice:()=>ne.getState().selectedVoice}))}var Bw=!1;function xI(){Bw||(Bw=!0,jr.get("ai:dialogue")||jr.register(uI),jr.get("mcp:execute")||jr.register(hI),jr.get("ui:state")||jr.register(fI),jr.get("core:subflow")||jr.register(pI),jr.get("core:return")||jr.register(mI),jr.get("ui:render")||jr.register(gI))}function vI({aiProvider:r,VoiceWidget:e,config:t,socketInstance:n,children:i,renderOverlays:s}){return bI(),xI(),Pw(),cI(()=>ne.subscribe(a=>{let l=ce.getState();a.isCreatorMode!==l.isCreatorMode&&l.setIsCreatorMode(a.isCreatorMode),a.showCanvas!==l.showCanvas&&l.setShowCanvas(a.showCanvas),a.isSidebarOpen!==l.isSidebarOpen&&l.setIsSidebarOpen(a.isSidebarOpen)}),[]),yI(Xi,{socketInstance:n,isConnected:!!n?.connected,children:[s?.(),Fw(ep,{}),Fw(zc,{aiProvider:r,VoiceWidget:e,config:t,socketInstance:n}),i]})}export{Ep as AIDirector,Tw as AgentPlayer,ya as AppHeader,vI as AppShell,Zw as ArtifactBar,sp as BUILT_IN_PRESETS,Yw as DebugPanel,Nw as DecidoPlayer,zc as DecidoShell,qI as EventBus,ep as GlobalOverlays,nd as LayoutConfigurator,cd as LayoutGrid,JP as MarketplaceWidget,C4 as McpToolsWidget,qc as MorphShell,Xi as NetworkProvider,g4 as OpsDashboard,p1 as PanelSplitter,rs as PluginErrorBoundary,vP as SafeLiquidUI,kp as ShellPluginProvider,gn as SlotRenderer,wI as THEME_DECIDO_DARK,EI as THEME_DECIDO_LIGHT,CI as THEME_EMERALD_NOIR,SI as THEME_MIDNIGHT_BLUE,NI as THEME_OLED_PURE,AI as THEME_PRESETS,kI as THEME_ROSE_GOLD,sd as TabBar,hP as TransientLayer,Jw as bridgeToMorph,Xw as detectShellType,jS as getAvailableSlotComponents,DI as getMorphComponent,qw as getMorphComponentCompat,OI as getRegisteredMorphComponents,jw as getRegisteredShellTypes,Uw as getShellMeta,I1 as initBridgeAgent,Vw as isShellRegistered,MI as registerMorphComponent,Gw as registerMorphComponentCompat,Hw as registerShell,VS as registerSlotComponent,Ip as registerStore,zw as resolveColor,$w as resolveColorClasses,_w as resolveIcon,Ww as resolveShell,VP as useAutoUpdater,qn as useDebugPanelStore,XR as useGeminiStream,Kw as useIntentLens,NP as useKeyboardShortcuts,ce as useLayoutStore,wp as useMcpStore,Uc as useMorphInstanceStore,Ks as useMorphologyStore,np as useNetwork,ip as useNetworkEvent,ne as usePlaygroundStore,l1 as usePluginContext,MP as usePluginEngine,VI as usePluginState,Qw as useShellKeyboard,rt as useShellStore,_P as useSystemBoot,Vc as useTheme,TI as useUIComponentStore,Sp as useUpdaterStore};