@remyxjs/core 1.0.0-beta

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 (105) hide show
  1. package/README.md +2454 -0
  2. package/dist/convertCsv-B8RVtdcs.cjs +2 -0
  3. package/dist/convertCsv-B8RVtdcs.cjs.map +1 -0
  4. package/dist/convertCsv-CKzZjzLJ.js +2 -0
  5. package/dist/convertCsv-CKzZjzLJ.js.map +1 -0
  6. package/dist/convertDocx-4q89XLLv.cjs +2 -0
  7. package/dist/convertDocx-4q89XLLv.cjs.map +1 -0
  8. package/dist/convertDocx-Dmx88twM.js +2 -0
  9. package/dist/convertDocx-Dmx88twM.js.map +1 -0
  10. package/dist/convertHtml-CtYVhiTh.js +2 -0
  11. package/dist/convertHtml-CtYVhiTh.js.map +1 -0
  12. package/dist/convertHtml-DbHrdrD3.cjs +2 -0
  13. package/dist/convertHtml-DbHrdrD3.cjs.map +1 -0
  14. package/dist/convertMarkdown-Di239Gtn.js +2 -0
  15. package/dist/convertMarkdown-Di239Gtn.js.map +1 -0
  16. package/dist/convertMarkdown-eJ9Nkoid.cjs +2 -0
  17. package/dist/convertMarkdown-eJ9Nkoid.cjs.map +1 -0
  18. package/dist/convertPdf-CFA1eNNH.js +2 -0
  19. package/dist/convertPdf-CFA1eNNH.js.map +1 -0
  20. package/dist/convertPdf-CSLmTrB8.cjs +2 -0
  21. package/dist/convertPdf-CSLmTrB8.cjs.map +1 -0
  22. package/dist/convertRtf-08CoScGD.js +2 -0
  23. package/dist/convertRtf-08CoScGD.js.map +1 -0
  24. package/dist/convertRtf-BfiBLMig.cjs +2 -0
  25. package/dist/convertRtf-BfiBLMig.cjs.map +1 -0
  26. package/dist/convertText-BpgzHRuh.cjs +2 -0
  27. package/dist/convertText-BpgzHRuh.cjs.map +1 -0
  28. package/dist/convertText-sa7PxKTe.js +2 -0
  29. package/dist/convertText-sa7PxKTe.js.map +1 -0
  30. package/dist/index-4syk9eEO.js +2 -0
  31. package/dist/index-4syk9eEO.js.map +1 -0
  32. package/dist/index-B25zSs0W.js +2 -0
  33. package/dist/index-B25zSs0W.js.map +1 -0
  34. package/dist/index-B7VT6ZLa.cjs +2 -0
  35. package/dist/index-B7VT6ZLa.cjs.map +1 -0
  36. package/dist/index-BCpytFKJ.js +2 -0
  37. package/dist/index-BCpytFKJ.js.map +1 -0
  38. package/dist/index-BNKANY5i.cjs +2 -0
  39. package/dist/index-BNKANY5i.cjs.map +1 -0
  40. package/dist/index-B_g_579T.cjs +2 -0
  41. package/dist/index-B_g_579T.cjs.map +1 -0
  42. package/dist/index-BvwyeoMb.js +3 -0
  43. package/dist/index-BvwyeoMb.js.map +1 -0
  44. package/dist/index-Bw7mlUQo.js +2 -0
  45. package/dist/index-Bw7mlUQo.js.map +1 -0
  46. package/dist/index-Byatzd-A.js +2 -0
  47. package/dist/index-Byatzd-A.js.map +1 -0
  48. package/dist/index-C0z9eZLm.cjs +2 -0
  49. package/dist/index-C0z9eZLm.cjs.map +1 -0
  50. package/dist/index-C88XPqjX.js +2 -0
  51. package/dist/index-C88XPqjX.js.map +1 -0
  52. package/dist/index-CI6FPF49.cjs +2 -0
  53. package/dist/index-CI6FPF49.cjs.map +1 -0
  54. package/dist/index-CLZF5_GB.cjs +2 -0
  55. package/dist/index-CLZF5_GB.cjs.map +1 -0
  56. package/dist/index-CXSwYlG4.cjs +2 -0
  57. package/dist/index-CXSwYlG4.cjs.map +1 -0
  58. package/dist/index-Ch9gotLk.js +2 -0
  59. package/dist/index-Ch9gotLk.js.map +1 -0
  60. package/dist/index-CifDpN1Y.js +2 -0
  61. package/dist/index-CifDpN1Y.js.map +1 -0
  62. package/dist/index-D5o8VpWJ.cjs +2 -0
  63. package/dist/index-D5o8VpWJ.cjs.map +1 -0
  64. package/dist/index-DKT1bABL.js +2 -0
  65. package/dist/index-DKT1bABL.js.map +1 -0
  66. package/dist/index-DWcn72PW.js +2 -0
  67. package/dist/index-DWcn72PW.js.map +1 -0
  68. package/dist/index-DjCGzPEv.cjs +2 -0
  69. package/dist/index-DjCGzPEv.cjs.map +1 -0
  70. package/dist/index-Dq0Jr1Ae.js +2 -0
  71. package/dist/index-Dq0Jr1Ae.js.map +1 -0
  72. package/dist/index-Dw0MVypb.cjs +2 -0
  73. package/dist/index-Dw0MVypb.cjs.map +1 -0
  74. package/dist/index-FEo3LShh.cjs +2 -0
  75. package/dist/index-FEo3LShh.cjs.map +1 -0
  76. package/dist/index-O1hzAUzi.cjs +2 -0
  77. package/dist/index-O1hzAUzi.cjs.map +1 -0
  78. package/dist/index-T1ZyLzeF.cjs +2 -0
  79. package/dist/index-T1ZyLzeF.cjs.map +1 -0
  80. package/dist/index-iRikoCdK.cjs +2 -0
  81. package/dist/index-iRikoCdK.cjs.map +1 -0
  82. package/dist/index-l6Yddj6x.js +2 -0
  83. package/dist/index-l6Yddj6x.js.map +1 -0
  84. package/dist/index-rD8LZENp.js +2 -0
  85. package/dist/index-rD8LZENp.js.map +1 -0
  86. package/dist/remyx-core.cjs +2 -0
  87. package/dist/remyx-core.cjs.map +1 -0
  88. package/dist/remyx-core.css +1 -0
  89. package/dist/remyx-core.js +2 -0
  90. package/dist/remyx-core.js.map +1 -0
  91. package/dist/themes/callouts.css +79 -0
  92. package/dist/themes/collaboration.css +117 -0
  93. package/dist/themes/comments.css +198 -0
  94. package/dist/themes/dark.css +109 -0
  95. package/dist/themes/forest.css +109 -0
  96. package/dist/themes/light.css +4 -0
  97. package/dist/themes/links.css +115 -0
  98. package/dist/themes/math-toc-analytics.css +129 -0
  99. package/dist/themes/ocean.css +109 -0
  100. package/dist/themes/rose.css +109 -0
  101. package/dist/themes/spellcheck.css +173 -0
  102. package/dist/themes/sunset.css +109 -0
  103. package/dist/themes/templates.css +87 -0
  104. package/dist/themes/variables.css +3222 -0
  105. package/package.json +80 -0
@@ -0,0 +1,3 @@
1
+ import e from"turndown";import{gfm as t}from"turndown-plugin-gfm";import{marked as n}from"marked";class o{constructor(){this._listeners=/* @__PURE__ */new Map,this._keyedHandlers=/* @__PURE__ */new Map,this._emitDepth=0}on(e,t,n){if(this._listeners.has(e)||this._listeners.set(e,/* @__PURE__ */new Set),n?.key){const o=`${e}:${n.key}`,r=this._keyedHandlers.get(o);r&&this.off(e,r),this._keyedHandlers.set(o,t)}return this._listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){const n=this._listeners.get(e);n&&(n.delete(t),0===n.size&&this._listeners.delete(e))}once(e,t){const n=(...o)=>{this.off(e,n),t(...o)};return this.on(e,n)}emit(e,t){const n=this._listeners.get(e);if(n){this._emitDepth++;try{n.forEach((n=>{try{n(t)}catch(o){"error"!==e&&this._emitDepth<3&&this.emit("error",{event:e,error:o,data:t})}}))}finally{this._emitDepth--}}}removeAllListeners(e){e?this._listeners.delete(e):this._listeners.clear()}}const r=/* @__PURE__ */new Set(["P","H1","H2","H3","H4","H5","H6","DIV","BLOCKQUOTE","PRE","LI","TD","TH"]);function s(e,t){let n=e.nodeType===Node.TEXT_NODE?e.parentElement:e;for(;n&&n!==t;){if(r.has(n.tagName))return n;n=n.parentElement}return null}function i(e,t){return s(e,t)}function a(e,t,n){const o=t.toUpperCase();let r=e.nodeType===Node.TEXT_NODE?e.parentElement:e;for(;r&&r!==n;){if(r.tagName===o)return r;r=r.parentElement}return null}function l(e,t,n={}){const o=document.createElement(t);Object.entries(n).forEach((([e,t])=>o.setAttribute(e,t)));try{e.surroundContents(o)}catch{const t=e.extractContents();o.appendChild(t),e.insertNode(o)}return o}function c(e){const t=e.parentNode;for(;e.firstChild;)t.insertBefore(e.firstChild,e);t.removeChild(e)}function d(){return"rmx-"+Math.random().toString(36).substr(2,9)}function u(e){if(!e)return!0;return""===e.textContent.trim()&&!e.querySelector("img, iframe, hr, input")}const m=/^h[1-6]$/,h={bold:/* @__PURE__ */new Set(["STRONG","B"]),italic:/* @__PURE__ */new Set(["EM","I"]),underline:/* @__PURE__ */new Set(["U"]),strikethrough:/* @__PURE__ */new Set(["S","DEL"]),subscript:/* @__PURE__ */new Set(["SUB"]),superscript:/* @__PURE__ */new Set(["SUP"])};class g{constructor(e){this.editor=e,this._cachedRange=null,this._cacheGeneration=0}invalidateCache(){this._cacheGeneration++,this._cachedRange=null}getSelection(){return window.getSelection()}getRange(){if(null!==this._cachedRange)return this._cachedRange;const e=this.getSelection();if(!e||0===e.rangeCount)return this._cachedRange=null,null;const t=e.getRangeAt(0);if(!this.isWithinEditor(t.commonAncestorContainer))return this._cachedRange=null,null;this._cachedRange=t;const n=++this._cacheGeneration;return Promise.resolve().then((()=>{this._cacheGeneration===n&&(this._cachedRange=null)})),t}setRange(e){this._cachedRange=null;try{const t=this.getSelection();t.removeAllRanges(),t.addRange(e)}catch{}}isWithinEditor(e){if(!e)return!1;const t=e.nodeType===Node.TEXT_NODE?e.parentElement:e;return this.editor.contains(t)}isCollapsed(){const e=this.getSelection();return!e||e.isCollapsed}getSelectedText(){const e=this.getSelection();return e?e.toString():""}getSelectedHTML(){const e=this.getRange();if(!e)return"";const t=e.cloneContents(),n=document.createElement("div");return n.appendChild(t),n.innerHTML}save(){const e=this.getRange();if(!e)return null;const t=document.createRange();t.selectNodeContents(this.editor),t.setEnd(e.startContainer,e.startOffset);const n=t.toString().length;return{startOffset:n,endOffset:n+e.toString().length,collapsed:e.collapsed}}restore(e){if(!e)return;const t=document.createTreeWalker(this.editor,NodeFilter.SHOW_TEXT,null);let n=0,o=null,r=0,s=null,i=0;for(;t.nextNode();){const a=t.currentNode,l=n+a.textContent.length;if(!o&&l>=e.startOffset&&(o=a,r=e.startOffset-n),!s&&l>=e.endOffset){s=a,i=e.endOffset-n;break}n=l}if(o)try{const e=document.createRange();e.setStart(o,Math.min(r,o.textContent.length)),s?e.setEnd(s,Math.min(i,s.textContent.length)):e.collapse(!0),this.setRange(e)}catch{try{const e=document.createRange();e.selectNodeContents(this.editor),e.collapse(!1),this.setRange(e)}catch{}}}collapse(e=!1){const t=this.getSelection();t&&t.rangeCount>0&&(e?t.collapseToEnd():t.collapseToStart())}getParentElement(){const e=this.getRange();if(!e)return null;const t=e.commonAncestorContainer;return t.nodeType===Node.TEXT_NODE?t.parentElement:t}getParentBlock(){const e=this.getParentElement();return e?s(e,this.editor):null}getClosestElement(e){let t=this.getParentElement();const n=e.toUpperCase();for(;t&&t!==this.editor;){if(t.tagName===n)return t;t=t.parentElement}return null}insertHTML(e){const t=this._sanitizer?this._sanitizer.sanitize(e):e,n=this.getSelection();if(!n||0===n.rangeCount)return;const o=n.getRangeAt(0);o.deleteContents();const r=document.createElement("template");r.innerHTML=t;const s=r.content,i=s.lastChild;if(o.insertNode(s),i){const e=document.createRange();e.setStartAfter(i),e.collapse(!0),n.removeAllRanges(),n.addRange(e)}}setSanitizer(e){this._sanitizer=e}insertNode(e){const t=this.getRange();t&&(t.deleteContents(),t.insertNode(e),t.setStartAfter(e),t.collapse(!0),this.setRange(t))}wrapWith(e,t={}){const n=this.getRange();if(!n||n.collapsed)return null;const o=document.createElement(e);Object.entries(t).forEach((([e,t])=>{o.setAttribute(e,t)}));try{n.surroundContents(o)}catch{const e=n.extractContents();o.appendChild(e),n.insertNode(o)}return this.setRange(n),o}unwrap(e){const t=this.getClosestElement(e);if(!t)return;const n=t.parentNode;for(;t.firstChild;)n.insertBefore(t.firstChild,t);n.removeChild(t)}getActiveFormats(){const e={bold:!1,italic:!1,underline:!1,strikethrough:!1,subscript:!1,superscript:!1,heading:null,alignment:"left",orderedList:!1,unorderedList:!1,blockquote:!1,codeBlock:!1,link:null,fontFamily:null,fontSize:null,foreColor:null,backColor:null};try{const t=window.getSelection();if(t&&t.rangeCount>0){let n=t.anchorNode;for(;n&&n!==this.editor;){if(n.nodeType===Node.ELEMENT_NODE){const t=n.tagName;for(const n in h)!e[n]&&h[n].has(t)&&(e[n]=!0)}n=n.parentNode}}}catch{}const t=this.getParentBlock();if(t){const n=t.tagName.toLowerCase();m.test(n)&&(e.heading=n);const o=t.style.textAlign||window.getComputedStyle(t).textAlign;o&&(e.alignment="start"===o?"left":"end"===o?"right":o)}let n=this.getParentElement();for(;n&&n!==this.editor;){const t=n.tagName;"OL"===t&&(e.orderedList=!0),"UL"===t&&(e.unorderedList=!0),"BLOCKQUOTE"===t&&(e.blockquote=!0),"PRE"===t&&(e.codeBlock=!0),"A"===t&&(e.link={href:n.href,text:n.textContent,target:n.target}),n=n.parentElement}try{e.fontFamily=document.queryCommandValue("fontName")||null,e.fontSize=document.queryCommandValue("fontSize")||null,e.foreColor=document.queryCommandValue("foreColor")||null,e.backColor=document.queryCommandValue("backColor")||null}catch{}return e}getBoundingRect(){const e=this.getRange();return e?e.getBoundingClientRect():null}}class p{constructor(e){this.engine=e,this._commands=/* @__PURE__ */new Map}register(e,t){if(this._commands.set(e,{name:e,execute:t.execute,isActive:t.isActive||(()=>!1),isEnabled:t.isEnabled||(()=>!0),shortcut:t.shortcut||null,meta:t.meta||{},skipSnapshot:t.skipSnapshot||!1}),t.shortcut&&this.engine.keyboard.register(t.shortcut,e),t.alternateShortcuts)for(const n of t.alternateShortcuts)this.engine.keyboard.register(n,e)}execute(e,...t){const n=this._commands.get(e);if(!n)return!1;if(!n.isEnabled(this.engine))return!1;n.skipSnapshot||this.engine.history.snapshot();const o=n.execute(this.engine,...t);return this.engine.eventBus.emit("command:executed",{name:e,args:t,result:o}),this.engine.eventBus.emit("content:change"),o}isActive(e){const t=this._commands.get(e);return!!t&&t.isActive(this.engine)}isEnabled(e){const t=this._commands.get(e);return!!t&&t.isEnabled(this.engine)}get(e){return this._commands.get(e)}getAll(){return Array.from(this._commands.keys())}has(e){return this._commands.has(e)}}function f(e){let t=5381;for(let n=0,o=e.length;n<o;n++)t=(t<<5)+t+e.charCodeAt(n)|0;return t}function b(e,t){const{prefixLen:n,suffixLen:o,insert:r}=t;return e.slice(0,n)+r+(o>0?e.slice(e.length-o):"")}class y{constructor(e,t={}){this.engine=e,this.maxSize=t.maxSize||100,this.debounceMs=t.debounceMs||300,this.coalesceMs=t.coalesceMs||1e3,this._undoStack=[],this._redoStack=[],this._observer=null,this._debounceTimer=null,this._coalesceTimer=null,this._isPerformingUndoRedo=!1,this._isCoalescing=!1,this._lastSnapshot=null,this._lastHash=null}init(){this._takeSnapshot(),this._observer=new MutationObserver((()=>{this._isPerformingUndoRedo||this._debouncedSnapshot()})),this._observer.observe(this.engine.element,{childList:!0,characterData:!0,subtree:!0})}destroy(){this._observer&&(this._observer.disconnect(),this._observer=null),this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._coalesceTimer&&(clearTimeout(this._coalesceTimer),this._coalesceTimer=null),this._isCoalescing=!1}snapshot(){this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._takeSnapshot()}_debouncedSnapshot(){this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout((()=>{this._isCoalescing?this._updateTopSnapshot():(this._isCoalescing=!0,this._takeSnapshot(),this._coalesceTimer&&clearTimeout(this._coalesceTimer),this._coalesceTimer=setTimeout((()=>{this._isCoalescing=!1}),this.coalesceMs))}),this.debounceMs)}_createEntry(e,t){if(e.length<5e3||!this._lastSnapshot)return{type:"full",html:e,bookmark:t};const n=function(e,t){const n=Math.min(e.length,t.length);let o=0;for(;o<n&&e[o]===t[o];)o++;let r=0;const s=n-o;for(;r<s&&e[e.length-1-r]===t[t.length-1-r];)r++;return{prefixLen:o,suffixLen:r,insert:t.slice(o,t.length-r||void 0)}}(this._lastSnapshot,e);return n.insert.length>=.8*e.length?{type:"full",html:e,bookmark:t}:{type:"diff",patch:n,bookmark:t}}_resolveEntry(e,t){const n=e[t];if("full"===n.type)return n.html;let o,r=t-1;for(;r>=0&&"full"!==e[r].type;)r--;o=r>=0?e[r].html:this._lastSnapshot||"";for(let s=r+1;s<=t;s++)o="diff"===e[s].type?b(o,e[s].patch):e[s].html;return o}_updateTopSnapshot(){const e=this.engine.element.innerHTML,t=f(e);if(t===this._lastHash&&e===this._lastSnapshot)return;const n=this.engine.selection.save();this._undoStack.length>0?this._undoStack[this._undoStack.length-1]=this._createEntry(e,n):this._undoStack.push({type:"full",html:e,bookmark:n}),this._lastSnapshot=e,this._lastHash=t}_takeSnapshot(){const e=this.engine.element.innerHTML,t=f(e);if(t===this._lastHash&&e===this._lastSnapshot)return;const n=this.engine.selection.save(),o=this._createEntry(e,n);this._undoStack.push(o),this._undoStack.length>this.maxSize&&this._undoStack.shift(),this._redoStack=[],this._lastSnapshot=e,this._lastHash=t}_disconnectObserver(){this._observer&&this._observer.disconnect()}_reconnectObserver(){this._observer&&this._observer.observe(this.engine.element,{childList:!0,characterData:!0,subtree:!0})}undo(){if(!this.canUndo())return;this._isPerformingUndoRedo=!0,this._disconnectObserver();const e=this.engine.element.innerHTML,t=this.engine.selection.save();this._redoStack.push({type:"full",html:e,bookmark:t});const n=this._undoStack.length-1,o=this._resolveEntry(this._undoStack,n),r=this._undoStack[n].bookmark;this._undoStack.pop(),this.engine.element.innerHTML=o,this._lastSnapshot=o,this._lastHash=f(o),r&&this.engine.selection.restore(r),this._reconnectObserver(),this._isPerformingUndoRedo=!1,this.engine.eventBus.emit("history:undo"),this.engine.eventBus.emit("content:change")}redo(){if(!this.canRedo())return;this._isPerformingUndoRedo=!0,this._disconnectObserver();const e=this.engine.element.innerHTML,t=this.engine.selection.save();this._undoStack.push({type:"full",html:e,bookmark:t});const n=this._redoStack.length-1,o=this._resolveEntry(this._redoStack,n),r=this._redoStack[n].bookmark;this._redoStack.pop(),this.engine.element.innerHTML=o,this._lastSnapshot=o,this._lastHash=f(o),r&&this.engine.selection.restore(r),this._reconnectObserver(),this._isPerformingUndoRedo=!1,this.engine.eventBus.emit("history:redo"),this.engine.eventBus.emit("content:change")}canUndo(){return this._undoStack.length>0}canRedo(){return this._redoStack.length>0}clear(){this._undoStack=[],this._redoStack=[],this._lastSnapshot=null,this._lastHash=null}}let v=null;function x(){return null===v&&(v="undefined"!=typeof navigator&&/Mac|iPod|iPhone|iPad/.test(navigator.platform)),v}function C(){return x()?"⌘":"Ctrl"}class w{constructor(e){this.engine=e,this._shortcuts=/* @__PURE__ */new Map,this._normalizeCache=/* @__PURE__ */new Map,this._handleKeyDown=this._handleKeyDown.bind(this)}init(){this.engine.element.addEventListener("keydown",this._handleKeyDown)}destroy(){this.engine.element.removeEventListener("keydown",this._handleKeyDown)}register(e,t){const n=this._normalizeShortcut(e);this._shortcuts.set(n,t)}unregister(e){const t=this._normalizeShortcut(e);this._shortcuts.delete(t)}getShortcutForCommand(e){for(const[t,n]of this._shortcuts)if(n===e)return t;return null}getShortcutLabel(e){if(!e)return"";return e.split("+").map((e=>"mod"===e?x()?"⌘":"Ctrl":"shift"===e?x()?"⇧":"Shift":"alt"===e?x()?"⌥":"Alt":e.toUpperCase())).join(x()?"":"+")}_normalizeShortcut(e){if(this._normalizeCache.has(e))return this._normalizeCache.get(e);const t=e.toLowerCase().split("+").sort().join("+");return this._normalizeCache.set(e,t),t}_handleKeyDown(e){const t=[];(x()?e.metaKey:e.ctrlKey)&&t.push("mod"),e.shiftKey&&t.push("shift"),e.altKey&&t.push("alt");const n=e.key.toLowerCase();["control","meta","shift","alt"].includes(n)||t.push(n);const o=t.sort().join("+"),r=this._shortcuts.get(o);r&&(e.preventDefault(),e.stopPropagation(),this.engine.commands.execute(r))}}const k={p:["class","style"],h1:["class"],h2:["class"],h3:["class"],h4:["class"],h5:["class"],h6:["class"],strong:[],b:[],em:[],i:[],u:[],s:[],del:[],sub:[],sup:[],a:["href","target","rel","title","class","data-attachment","data-filename","data-filesize"],img:["src","alt","width","height","style","class"],ul:["class"],ol:["class","start","type"],li:["class"],table:["class","data-sort-state"],thead:[],tbody:[],tr:["class"],th:["colspan","rowspan","class","style","data-sort-dir","data-sort-priority","data-filter-value","data-cell-format","data-raw-value","data-formula"],td:["colspan","rowspan","class","style","data-cell-format","data-raw-value","data-formula","data-col-width"],blockquote:["class"],pre:["class","data-language"],code:["class","data-language"],hr:[],br:[],div:["class","style","data-embed-url"],span:["style","class"],input:["type","checked","disabled","class"],label:["class"],mark:["class"],iframe:["src","width","height","frameborder","allowfullscreen","sandbox","class","style"]},_=["color","background-color","font-family","font-size","text-align","text-decoration","font-weight","font-style","width","height","max-width","float","margin","margin-left","margin-right","display","padding","border","min-width"],S=/^\s*javascript\s*:/i,A=/expression\s*\(|@import|behavior\s*:|javascript\s*:/i,E=/* @__PURE__ */new Set(["script","style","svg","math","form","object","embed","applet","template"]),L=["www.youtube.com","youtube.com","www.youtube-nocookie.com","player.vimeo.com","www.dailymotion.com","geo.dailymotion.com"];function T(e,t){if(!e)return!1;try{const n=new URL(e);if("https:"!==n.protocol)return!1;const o=n.hostname.toLowerCase();return t.some((e=>{const t=e.toLowerCase();return o===t||o.endsWith("."+t)}))}catch{return!1}}class I{constructor(e={}){this.allowedTags=e.allowedTags||k,this.allowedStyles=e.allowedStyles||_,this.iframeAllowedDomains=e.iframeAllowedDomains||L,this._cache=/* @__PURE__ */new Map,this._parser=new DOMParser}sanitize(e){if(!e)return"";const t=f(e);if(this._cache.has(t)){const n=this._cache.get(t);if(n.input===e)return this._cache.delete(t),this._cache.set(t,n),n.output}const n=this._parser.parseFromString(`<body>${e}</body>`,"text/html");this._cleanNode(n.body);const o=n.body.innerHTML;if(this._cache.size>=50){const e=this._cache.keys().next().value;this._cache.delete(e)}return this._cache.set(t,{input:e,output:o}),o}_cleanNode(e){for(let t=e.childNodes.length-1;t>=0;t--){const n=e.childNodes[t];if(n.nodeType===Node.TEXT_NODE)continue;if(n.nodeType===Node.COMMENT_NODE){e.removeChild(n);continue}if(n.nodeType!==Node.ELEMENT_NODE){e.removeChild(n);continue}const o=n.tagName.toLowerCase(),r=this.allowedTags[o];if(!r){if(E.has(o))e.removeChild(n);else{for(;n.firstChild;)e.insertBefore(n.firstChild,n);e.removeChild(n)}continue}const s=Array.from(n.attributes);for(const e of s)e.name.startsWith("on")?n.removeAttribute(e.name):"style"===e.name?r.includes("style")?this._cleanStyles(n):n.removeAttribute("style"):r.includes(e.name)||n.removeAttribute(e.name);if(n.hasAttribute("href")){const e=n.getAttribute("href");e&&S.test(e)&&n.setAttribute("href","#")}if("input"===o){if("checkbox"!==(n.getAttribute("type")||"").toLowerCase()){e.removeChild(n);continue}}if("iframe"===o){if(!T(n.getAttribute("src"),this.iframeAllowedDomains)){e.removeChild(n);continue}}this._cleanNode(n)}}_cleanStyles(e){const t=e.style,n=[];for(const o of this.allowedStyles){const e=t.getPropertyValue(o);if(e){if(A.test(e))continue;n.push(`${o}: ${e}`)}}n.length>0?e.setAttribute("style",n.join("; ")):e.removeAttribute("style")}}const B="undefined"!=typeof DOMParser?new DOMParser:null,N=/^[\s]*[·•●○◦▪▫–—-]\s*/,R=/^[\s]*\d+[.)]\s*/,M=/^[\s]*[a-zA-Z][.)]\s*/,D=/margin-left|padding-left|text-indent/i,H=/^[\s]*(?:[·•●○◦▪▫–—-]|\d+[.)]|[a-zA-Z][.)])\s*/;function F(e){if(!e)return"";let t=e;t=t.replace(/<meta[^>]*>/gi,""),t=t.replace(/<\/?html[^>]*>/gi,""),t=t.replace(/<head[\s\S]*?<\/head>/gi,""),t=t.replace(/<\/?body[^>]*>/gi,""),t=t.replace(/<style[\s\S]*?<\/style>/gi,""),t=t.replace(/<title[\s\S]*?<\/title>/gi,""),t=t.replace(/<svg[\s\S]*?<\/svg>/gi,""),t=t.replace(/<math[\s\S]*?<\/math>/gi,""),t=t.replace(/<object[\s\S]*?<\/object>/gi,""),t=t.replace(/<link[^>]*>/gi,"");const n=/mso-|class="Mso|<o:p|<w:/.test(e),o=/docs-internal|id="h\.[a-z0-9]+"/.test(e),r=/google-sheets-html-origin/.test(e),s=/<text:|<office:|class="P\d+"/.test(e),i=/apple-content-edited|class="[sp]\d+"/.test(e);return n&&(t=t.replace(/<!--\[if[\s\S]*?endif\]-->/gi,""),t=t.replace(/<!--[\s\S]*?-->/g,""),t=t.replace(/<o:p[\s\S]*?<\/o:p>/gi,""),t=t.replace(/<w:[\s\S]*?<\/w:[\s\S]*?>/gi,""),t=t.replace(/<m:[\s\S]*?<\/m:[\s\S]*?>/gi,""),t=t.replace(/<\/?(xml|st1|v:|o:)[^>]*>/gi,""),t=t.replace(/\s*mso-[^:]+:[^;"]+;?/gi,""),t=t.replace(/\s*class="Mso[^"]*"/gi,""),t=t.replace(/\s*lang="[^"]*"/gi,"")),o&&(t=t.replace(/<b\s+id="docs-internal[^"]*"[^>]*>([\s\S]*?)<\/b>/gi,"$1"),t=t.replace(/\s*id="docs-internal[^"]*"/gi,""),t=t.replace(/\s*id="h\.[a-z0-9]+"/gi,""),t=t.replace(/\s*class="c\d+"/gi,""),t=t.replace(/\s*dir="ltr"/gi,""),t=t.replace(/\s*role="presentation"/gi,""),t=t.replace(/<span\s+style="[^"]*font-weight:\s*(700|bold)[^"]*">([\s\S]*?)<\/span>/gi,"<strong>$2</strong>"),t=t.replace(/<span\s+style="[^"]*font-style:\s*italic[^"]*">([\s\S]*?)<\/span>/gi,"<em>$2</em>"),t=t.replace(/<span\s+style="[^"]*text-decoration:\s*line-through[^"]*">([\s\S]*?)<\/span>/gi,"<s>$2</s>")),s&&(t=t.replace(/<\/?(text|office|table|draw|style|number|fo|svg):[^>]*>/gi,""),t=t.replace(/\s*class="P\d+"/gi,""),t=t.replace(/\s*class="T\d+"/gi,""),t=t.replace(/\s*class="Table\d+"/gi,"")),r&&(t=t.replace(/<google-sheets-html-origin[\s\S]*?\/>/gi,""),t=t.replace(/<\/?google-sheets-html-origin[^>]*>/gi,""),t=t.replace(/<col[^>]*>/gi,""),t=t.replace(/<\/?colgroup[^>]*>/gi,"")),n&&/<table/i.test(e)&&(t=t.replace(/\s*xmlns:[a-z]="[^"]*"/gi,""),t=t.replace(/<col[^>]*>/gi,""),t=t.replace(/<\/?colgroup[^>]*>/gi,"")),i&&(t=t.replace(/\s*class="(s|p)\d+"/gi,""),t=t.replace(/<div\s+apple-content-edited="true"[^>]*>/gi,"<div>")),t=t.replace(/@font-face\s*\{[^}]*\}/gi,""),t=t.replace(/\s*style="\s*"/gi,""),t=t.replace(/\s*class="\s*"/gi,""),t=t.replace(/<span\s*>([\s\S]*?)<\/span>/gi,"$1"),t=t.replace(/<(\w+)\s+>/g,"<$1>"),t=t.replace(/<p[^>]*>\s*<\/p>/gi,""),t=t.replace(/<div[^>]*>\s*<\/div>/gi,""),t=t.replace(/<font\s[^>]*?face="([^"]*)"[^>]*>([\s\S]*?)<\/font>/gi,'<span style="font-family: $1">$2</span>'),t=t.replace(/<font\s[^>]*?color="([^"]*)"[^>]*>([\s\S]*?)<\/font>/gi,'<span style="color: $1">$2</span>'),t=t.replace(/<font\s[^>]*?size="([^"]*)"[^>]*>([\s\S]*?)<\/font>/gi,"$2"),t=t.replace(/<\/?font[^>]*>/gi,""),t=t.replace(/<b(\s|>)/gi,"<strong$1"),t=t.replace(/<\/b>/gi,"</strong>"),t=t.replace(/<i(\s|>)/gi,"<em$1"),t=t.replace(/<\/i>/gi,"</em>"),n&&(t=function(e){if(!B)return e;const t=B.parseFromString(`<body>${e}</body>`,"text/html"),n=t.querySelectorAll("p");let o=!1,r=null,s=null;for(const i of n){const e=i.textContent.trim(),n=i.getAttribute("style")||"",a=D.test(n),l=N.test(e),c=R.test(e)||M.test(e);if((l||c)&&a){const e=l?"ul":"ol";o&&r===e||(s=t.createElement(e),i.parentNode.insertBefore(s,i),o=!0,r=e);const n=t.createElement("li");n.innerHTML=i.innerHTML.replace(H,""),s.appendChild(n),i.parentNode.removeChild(i)}else o=!1,r=null,s=null}return t.body.innerHTML}(t)),t=t.replace(/(<br\s*\/?\s*>){3,}/gi,"<br><br>"),t.trim()}const P=/^#{1,6}\s+\S/,z=/^[-*+]\s+\S/,O=/^\d+[.)]\s+\S/,G=/^[-*+]\s+\[[ xX]\]\s/,q=/^>\s/,W=/^([-*_])\1{2,}$/,$=/^```/,Z=/\*\*[^*]+\*\*/,U=/__[^_]+__/,V=new RegExp("(?<!\\w)\\*[^*\\s][^*]*\\*(?!\\w)"),j=/\[.+\]\(.+\)/,K=/!\[.*\]\(.+\)/,X=/^\|.+\|/,J=/^\|[\s-:|]+\|$/,Y=/`[^`]+`/;function Q(e){if(!e||e.length<3)return!1;const t=e.split("\n");let n=0,o=0;for(const r of t){const e=r.trim();e&&(o++,P.test(e)?n+=2:z.test(e)||O.test(e)?n++:G.test(e)?n+=2:q.test(e)||W.test(e)?n++:$.test(e)?n+=2:Z.test(e)||U.test(e)||V.test(e)||j.test(e)?n++:K.test(e)?n+=2:(X.test(e)||J.test(e)||Y.test(e))&&n++)}if(0===o)return!1;return n/o>=.3||n>=2}function ee(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function te(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function ne(e){const t=e.lastIndexOf(".");return t>=0?e.slice(t).toLowerCase():""}function oe(e){return new Promise(((t,n)=>{const o=new FileReader;o.onload=e=>t(e.target.result),o.onerror=()=>n(new Error(`Failed to read file: ${e.name}`)),o.readAsText(e)}))}function re(e){return new Promise(((t,n)=>{const o=new FileReader;o.onload=e=>t(e.target.result),o.onerror=()=>n(new Error(`Failed to read file: ${e.name}`)),o.readAsArrayBuffer(e)}))}function se(e){return te(e)}const ie={"application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/pdf":"pdf","text/markdown":"markdown","text/x-markdown":"markdown","text/html":"html","text/plain":"text","text/csv":"csv","application/csv":"csv","text/rtf":"rtf","application/rtf":"rtf"},ae={".docx":"docx",".pdf":"pdf",".md":"markdown",".markdown":"markdown",".html":"html",".htm":"html",".txt":"text",".csv":"csv",".tsv":"csv",".rtf":"rtf"};function le(e){if(e.type&&ie[e.type])return ie[e.type];const t=ne(e.name||"");return ae[t]||null}function ce(e){return null!==le(e)}function de(){return Object.keys(ae).join(",")}function ue(){return["PDF","DOCX","Markdown","HTML","TXT","CSV","TSV","RTF"]}async function me(e){const t=le(e);if(!t)throw new Error(`Unsupported file format: ${e.name}`);const n={docx:()=>import("./convertDocx-Dmx88twM.js"),pdf:()=>import("./convertPdf-CFA1eNNH.js"),markdown:()=>import("./convertMarkdown-Di239Gtn.js"),html:()=>import("./convertHtml-CtYVhiTh.js"),text:()=>import("./convertText-sa7PxKTe.js"),csv:()=>import("./convertCsv-CKzZjzLJ.js"),rtf:()=>import("./convertRtf-08CoScGD.js")},o=await n[t](),r=await o.default(e);return"string"==typeof r?F(r):r}const he=[["undo","redo"],["headings","fontFamily","fontSize"],["bold","italic","underline","strikethrough"],["foreColor","backColor"],["alignLeft","alignCenter","alignRight","alignJustify"],["orderedList","unorderedList","taskList"],["outdent","indent"],["link","image","attachment","importDocument","table","embedMedia","blockquote","codeBlock","horizontalRule"],["subscript","superscript","removeFormat"],["insertCallout","insertMath","insertToc","insertBookmark","insertMergeTag"],["findReplace","toggleMarkdown","sourceMode","toggleAnalytics","toggleSpellcheck","distractionFree","toggleSplitView","export","commandPalette","fullscreen"]],ge=["Arial","Arial Black","Courier New","Georgia","Helvetica","Impact","Lucida Console","Palatino Linotype","Tahoma","Times New Roman","Trebuchet MS","Verdana","Comic Sans MS","Segoe UI","Roboto","Open Sans"],pe=[{label:"8px",value:"8px"},{label:"10px",value:"10px"},{label:"12px",value:"12px"},{label:"14px",value:"14px"},{label:"16px",value:"16px"},{label:"18px",value:"18px"},{label:"20px",value:"20px"},{label:"24px",value:"24px"},{label:"28px",value:"28px"},{label:"32px",value:"32px"},{label:"36px",value:"36px"},{label:"48px",value:"48px"},{label:"64px",value:"64px"},{label:"72px",value:"72px"}],fe=["#000000","#434343","#666666","#999999","#b7b7b7","#cccccc","#d9d9d9","#efefef","#f3f3f3","#ffffff","#980000","#ff0000","#ff9900","#ffff00","#00ff00","#00ffff","#4a86e8","#0000ff","#9900ff","#ff00ff","#e6b8af","#f4cccc","#fce5cd","#fff2cc","#d9ead3","#d0e0e3","#c9daf8","#cfe2f3","#d9d2e9","#ead1dc","#dd7e6b","#ea9999","#f9cb9c","#ffe599","#b6d7a8","#a2c4c9","#a4c2f4","#9fc5e8","#b4a7d6","#d5a6bd","#cc4125","#e06666","#f6b26b","#ffd966","#93c47d","#76a5af","#6d9eeb","#6fa8dc","#8e7cc3","#c27ba0","#a61c00","#cc0000","#e69138","#f1c232","#6aa84f","#45818e","#3c78d8","#3d85c6","#674ea7","#a64d79","#85200c","#990000","#b45f06","#bf9000","#38761d","#134f5c","#1155cc","#0b5394","#351c75","#741b47","#5b0f00","#660000","#783f04","#7f6000","#274e13","#0c343d","#1c4587","#073763","#20124d","#4c1130"],be=[{label:"File",items:["importDocument","export"]},{label:"Edit",items:["undo","redo","---","findReplace"]},{label:"View",items:["fullscreen","distractionFree","toggleSplitView","---","toggleMarkdown","sourceMode","---","toggleAnalytics","toggleSpellcheck"]},{label:"Insert",items:["link","image","table","attachment","embedMedia","---","blockquote","codeBlock","horizontalRule","---","insertCallout","insertMath","insertToc","insertBookmark","insertMergeTag","---","addComment"]},{label:"Format",items:["bold","italic","underline","strikethrough","---","subscript","superscript","---",{label:"Alignment",items:["alignLeft","alignCenter","alignRight","alignJustify"]},"---","orderedList","unorderedList","taskList","---","foreColor","backColor","---",{label:"Typography",items:["lineHeight","letterSpacing","paragraphSpacing"]},"---","removeFormat"]}],ye=[{label:"Normal",value:"p",tag:"p"},{label:"Heading 1",value:"h1",tag:"h1"},{label:"Heading 2",value:"h2",tag:"h2"},{label:"Heading 3",value:"h3",tag:"h3"},{label:"Heading 4",value:"h4",tag:"h4"},{label:"Heading 5",value:"h5",tag:"h5"},{label:"Heading 6",value:"h6",tag:"h6"}];function ve(e,t,n){const o=t??10485760;if(o>0&&e.size>o){(e.size/1048576).toFixed(1),(o/1048576).toFixed(0);return n?.eventBus&&n.eventBus.emit("file:too-large",{file:e,maxSize:o}),!0}return!1}let xe=null,Ce=!1;const we=/* @__PURE__ */new Set(["http:","https:","mailto:","tel:"]);function ke(e){if(!e)return!1;if(/^(\/|#)/.test(e))return!0;try{const t=decodeURIComponent(e),n=new URL(t,"https://placeholder.invalid");return we.has(n.protocol)}catch{return!1}}function _e(n){return n&&"<p><br></p>"!==n?(xe||(xe=new e({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",fence:"```",emDelimiter:"*",strongDelimiter:"**",linkStyle:"inlined"}),xe.use(t),xe.addRule("lineBreak",{filter:"br",replacement:()=>" \n"}),xe.addRule("taskCheckbox",{filter:e=>"INPUT"===e.nodeName&&"checkbox"===e.type&&e.classList.contains("rmx-task-checkbox"),replacement:(e,t)=>t.checked?"[x] ":"[ ] "}),xe.addRule("fencedCodeBlockWithLanguage",{filter:e=>"PRE"===e.nodeName&&e.firstChild&&"CODE"===e.firstChild.nodeName,replacement(e,t){const n=t.firstChild;return`\n\n\`\`\`${n.getAttribute("data-language")||""}\n${n.textContent}\n\`\`\`\n\n`}}),xe.addRule("underline",{filter:["u"],replacement:e=>`<u>${e}</u>`})),xe).turndown(n):""}function Se(e){return e?(function(){if(!Ce){n.setOptions({gfm:!0,breaks:!1});const e=new n.Renderer;e.link=({href:e,title:t,tokens:o})=>{const r=n.Parser.parseInline(o);return e&&!ke(e)?r:`<a href="${e}"${t?` title="${t.replace(/"/g,"&quot;")}"`:""}>${r}</a>`},e.image=({href:e,title:t,text:n})=>!e||ke(e)||e.startsWith("data:image/")?`<img src="${e}" alt="${n||""}"${t?` title="${t.replace(/"/g,"&quot;")}"`:""} />`:n||"",e.code=({text:e,lang:t})=>{const n=t?` data-language="${t.replace(/"/g,"&quot;")}"`:"";return`<pre${n}><code${n}>${ee(e)}</code></pre>\n`},n.use({renderer:e}),Ce=!0}}(),n.parse(e)):""}function Ae(e,t){if("markdown"===e.outputFormat||Q(t)){let n=Se(t);n=e.sanitizer.sanitize(n),e.selection.insertHTML(n)}else{const n=ee(t).split(/\n\n+/).map((e=>`<p>${e.replace(/\n/g,"<br>")}</p>`)).join("");e.selection.insertHTML(n||"<p><br></p>")}}class Ee{constructor(e){this.engine=e,this._handlePaste=this._handlePaste.bind(this),this._handleCopy=this._handleCopy.bind(this),this._handleCut=this._handleCut.bind(this)}init(){this.engine.element.addEventListener("paste",this._handlePaste),this.engine.element.addEventListener("copy",this._handleCopy),this.engine.element.addEventListener("cut",this._handleCut)}destroy(){this.engine.element.removeEventListener("paste",this._handlePaste),this.engine.element.removeEventListener("copy",this._handleCopy),this.engine.element.removeEventListener("cut",this._handleCut)}_handlePaste(e){e.preventDefault(),this.engine.history.snapshot();const t=e.clipboardData||window.clipboardData;let n=t.getData("text/html");const o=t.getData("text/plain"),r=Array.from(t.files||[]),s=r.find((e=>e.type.startsWith("image/")));if(s)return void this._handleImagePaste(s);const i=r.filter((e=>!e.type.startsWith("image/")&&ce(e)));if(i.length>0){const e=i.filter((e=>!this._exceedsMaxFileSize(e)));let t=Promise.resolve();for(const n of e)t=t.then((()=>me(n).then((e=>{const t=this.engine.sanitizer.sanitize(e);this.engine.selection.insertHTML(t),this.engine.eventBus.emit("content:change")})).catch((e=>{}))));return}const a=r.filter((e=>!e.type.startsWith("image/")));if(a.length>0&&this.engine.options.uploadHandler){let e=Promise.resolve();for(const t of a)e=e.then((()=>this.engine.options.uploadHandler(t).then((e=>{this.engine.commands.execute("insertAttachment",{url:e,filename:t.name,filesize:t.size})})).catch((e=>{this.engine.eventBus.emit("upload:error",{file:t,error:e})}))));return}const l=this._getCaretCell();if(l){const e=l.closest("table");if(e){if(o&&this._looksLikeTSV(o))return this._pasteIntoTable(e,l,o),this.engine.eventBus.emit("paste",{html:n,text:o}),void this.engine.eventBus.emit("content:change");if(n&&/<table/i.test(n)){const t=F(n),r=this._htmlTableToTSV(t);if(r)return this._pasteIntoTable(e,l,r),this.engine.eventBus.emit("paste",{html:n,text:o}),void this.engine.eventBus.emit("content:change")}}}n?(n=F(n),n=this.engine.sanitizer.sanitize(n),this.engine.selection.insertHTML(n)):o&&this._handleTextPaste(o),this.engine.eventBus.emit("paste",{html:n,text:o}),this.engine.eventBus.emit("content:change")}_handleTextPaste(e){Ae(this.engine,e)}_handleCopy(e){const t=window.getSelection();if(!t||0===t.rangeCount)return;const n=t.anchorNode?.nodeType===Node.TEXT_NODE?t.anchorNode.parentElement:t.anchorNode,o=t.focusNode?.nodeType===Node.TEXT_NODE?t.focusNode.parentElement:t.focusNode,r=n?.closest?.("table.rmx-table"),s=o?.closest?.("table.rmx-table");if(r&&s&&r===s){const t=r.querySelectorAll("thead tr, tbody tr"),n=[];let o="";for(const e of t){if(e.classList.contains("rmx-row-hidden"))continue;const t=e.querySelectorAll("td, th"),r=[];let s="";for(const e of t){const t=e.textContent.trim();t.includes("\t")||t.includes("\n")||t.includes('"')?r.push('"'+t.replace(/"/g,'""')+'"'):r.push(t);const n=e.tagName.toLowerCase();s+=`<${n}>${e.innerHTML}</${n}>`}n.push(r.join("\t")),o+=`<tr>${s}</tr>`}const s=n.join("\n"),i=`<table><tbody>${o}</tbody></table>`;e.preventDefault(),e.clipboardData.setData("text/plain",s),e.clipboardData.setData("text/html",i)}}_handleCut(){this.engine.history.snapshot(),setTimeout((()=>{this.engine.eventBus.emit("content:change")}),0)}_exceedsMaxFileSize(e){return ve(e,this.engine.options.maxFileSize,{eventBus:this.engine.eventBus})}_getCaretCell(){const e=window.getSelection();if(!e||!e.anchorNode)return null;const t=e.anchorNode.nodeType===Node.TEXT_NODE?e.anchorNode.parentElement:e.anchorNode;return t?.closest?.("td, th")||null}_looksLikeTSV(e){if(!e.includes("\t"))return!1;const t=e.trim().split("\n");return!(t.length<1)&&t[0].includes("\t")}_htmlTableToTSV(e){const t=(new DOMParser).parseFromString(e,"text/html").querySelector("table");if(!t)return null;const n=[],o=t.querySelectorAll("tr");for(const r of o){const e=r.querySelectorAll("td, th");n.push(Array.from(e).map((e=>e.textContent.trim())).join("\t"))}return n.join("\n")}_pasteIntoTable(e,t,n){const o=e.querySelector("tbody")||e,r=n.trim().split("\n").map((e=>e.split("\t"))),s=Array.from(e.querySelectorAll("tbody tr")),i=t.closest("tr");let a=s.indexOf(i);a<0&&(a=0);let l=0,c=t.previousElementSibling;for(;c;)l+=c.colSpan||1,c=c.previousElementSibling;for(let d=0;d<r.length;d++){const e=a+d;for(;s.length<=e;){const e=s[0]||i,t=e?e.cells.length:r[0].length,n=document.createElement("tr");for(let o=0;o<t;o++){const e=document.createElement("td");e.innerHTML="<br>",n.appendChild(e)}o.appendChild(n),s.push(n)}const t=s[e];for(let n=0;n<r[d].length;n++){const o=l+n;for(;t.cells.length<=o;){const n=document.createElement("td");n.innerHTML="<br>",t.appendChild(n),s.forEach(((t,n)=>{if(n!==e&&t.cells.length<=o){const e=document.createElement("td");e.innerHTML="<br>",t.appendChild(e)}}))}const i=t.cells[o];i&&(i.textContent=r[d][n])}}}_handleImagePaste(e){if(!this._exceedsMaxFileSize(e))if(this.engine.options.uploadHandler)this.engine.options.uploadHandler(e).then((t=>{this.engine.commands.execute("insertImage",{src:t,alt:e.name})})).catch((t=>{this.engine.eventBus.emit("upload:error",{file:e,error:t})}));else{const t=new FileReader;t.onprogress=e=>{e.lengthComputable&&this.engine.eventBus.emit("upload:progress",{loaded:e.loaded,total:e.total,percent:Math.round(e.loaded/e.total*100)})},t.onload=t=>{const n=t.target.result;this.engine.commands.execute("insertImage",{src:n,alt:e.name})},t.readAsDataURL(e)}}}const Le="application/x-remyx-content",Te=/* @__PURE__ */new Set(["P","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","UL","OL","TABLE","HR","DIV"]),Ie=/* @__PURE__ */new Set(["UL","OL","TBODY","TABLE"]),Be=/* @__PURE__ */new WeakMap,Ne=/* @__PURE__ */new Set;class Re{constructor(e){this.engine=e,this._dragSource=null,this._dragSourceEditor=null,this._dropTarget=null,this._dropPosition=null,this._ghostEl=null,this._dropIndicator=null,this._isExternalDrag=!1,this._enterCount=0,this._blockRects=null,this._scrollHandler=null,this._handleDragOver=this._handleDragOver.bind(this),this._handleDrop=this._handleDrop.bind(this),this._handleDragEnter=this._handleDragEnter.bind(this),this._handleDragLeave=this._handleDragLeave.bind(this),this._handleDragStart=this._handleDragStart.bind(this),this._handleDragEnd=this._handleDragEnd.bind(this)}init(){const e=this.engine.element;e.addEventListener("dragover",this._handleDragOver),e.addEventListener("drop",this._handleDrop),e.addEventListener("dragenter",this._handleDragEnter),e.addEventListener("dragleave",this._handleDragLeave),e.addEventListener("dragstart",this._handleDragStart),e.addEventListener("dragend",this._handleDragEnd),Be.set(e,this),Ne.add(this)}destroy(){const e=this.engine.element;e.removeEventListener("dragover",this._handleDragOver),e.removeEventListener("drop",this._handleDrop),e.removeEventListener("dragenter",this._handleDragEnter),e.removeEventListener("dragleave",this._handleDragLeave),e.removeEventListener("dragstart",this._handleDragStart),e.removeEventListener("dragend",this._handleDragEnd),Be.delete(e),Ne.delete(this),this._cleanupDrag()}getDraggableBlock(e){return this._closestDraggableBlock(e)}makeBlockDraggable(e){e&&!e.hasAttribute("draggable")&&e.setAttribute("draggable","true")}unmakeBlockDraggable(e){e&&e.removeAttribute("draggable")}isDragging(){return!!this._dragSource}getDragState(){return{isDragging:!!this._dragSource||this._isExternalDrag,isExternalDrag:this._isExternalDrag,dropTarget:this._dropTarget,dropPosition:this._dropPosition}}_handleDragStart(e){const t=this._getReorderableItem(e.target)||this._closestDraggableBlock(e.target);if(!t)return;this._dragSource=t,this._dragSourceEditor=this;const n=t.outerHTML,o=t.textContent;e.dataTransfer.setData(Le,n),e.dataTransfer.setData("text/html",n),e.dataTransfer.setData("text/plain",o),e.dataTransfer.effectAllowed="move",this._createGhostPreview(t,e),this._cacheBlockRects(),t.classList.add("rmx-block-dragging");for(const r of Ne)r._dragSourceEditor=this,r._dragSource=t;this.engine.eventBus.emit("drag:start",{block:t})}_handleDragEnd(e){this._dragSource&&this._dragSource.classList.remove("rmx-block-dragging");for(const t of Ne)t._cleanupDrag();this.engine.eventBus.emit("drag:end")}_handleDragOver(e){e.preventDefault(),this._dragSource?e.dataTransfer.dropEffect="move":e.dataTransfer.dropEffect="copy",(this._dragSource||this._isExternalDrag)&&this._updateDropTarget(e)}_handleDragEnter(e){e.preventDefault(),this._enterCount++,1===this._enterCount&&(this._dragSource||(this._isExternalDrag=!0),this.engine.element.classList.add("rmx-drag-over"),this.engine.eventBus.emit("drag:enter",{isExternal:this._isExternalDrag,types:Array.from(e.dataTransfer.types||[])}))}_handleDragLeave(e){this._enterCount--,this._enterCount<=0&&(this._enterCount=0,this.engine.element.classList.remove("rmx-drag-over"),this._removeDropIndicator(),this._dropTarget=null,this._dropPosition=null,this._isExternalDrag&&!this._dragSource&&(this._isExternalDrag=!1),this.engine.eventBus.emit("drag:leave"))}_handleDrop(e){if(e.preventDefault(),this._enterCount=0,this.engine.element.classList.remove("rmx-drag-over"),this._removeDropIndicator(),this._dragSource&&this._dropTarget)return this._handleBlockDrop(e),void this._cleanupDrag();const t=Array.from(e.dataTransfer.files),n=t.filter((e=>e.type.startsWith("image/")));if(n.length>0)return this._handleImageDrop(e,n),void this._cleanupDrag();const o=t.filter((e=>!e.type.startsWith("image/")&&ce(e)));if(o.length>0)return this._handleDocumentDrop(e,o),void this._cleanupDrag();const r=t.filter((e=>!e.type.startsWith("image/")));if(r.length>0&&this.engine.options.uploadHandler)return this._handleFileDrop(e,r),void this._cleanupDrag();const s=e.dataTransfer.getData(Le);if(s&&!this._dragSource)return this._handleInterEditorDrop(e,s),void this._cleanupDrag();this._setCursorAtDropPoint(e),this.engine.history.snapshot();const i=e.dataTransfer.getData("text/html");if(i){let e=F(i);e=this.engine.sanitizer.sanitize(e),this.engine.selection.insertHTML(e),this.engine.eventBus.emit("content:change")}else{const t=e.dataTransfer.getData("text/plain");t&&(this._handleTextDrop(t),this.engine.eventBus.emit("content:change"))}this.engine.eventBus.emit("drop",{files:t,html:i}),this._cleanupDrag()}_handleBlockDrop(e){const t=this._dragSource,n=this._dropTarget,o=this._dropPosition,r=this._dragSourceEditor;if(!t||!n||!o)return;if(t===n)return;this.engine.history.snapshot(),r&&r!==this&&r.engine.history.snapshot();const s=this._getReorderableItem(t),i=this._getReorderableItem(n);if(s&&i&&s.parentElement===i.parentElement)"before"===o?i.parentElement.insertBefore(s,i):i.parentElement.insertBefore(s,i.nextSibling);else{const e=n.parentElement;if(!e)return;"before"===o?e.insertBefore(t,n):e.insertBefore(t,n.nextSibling)}r&&r!==this&&r.engine.eventBus.emit("content:change"),this.engine.eventBus.emit("content:change"),this.engine.eventBus.emit("drag:reorder",{source:t,target:n,position:o})}_handleInterEditorDrop(e,t){this._setCursorAtDropPoint(e),this.engine.history.snapshot();const n=this.engine.sanitizer.sanitize(t);this.engine.selection.insertHTML(n),this.engine.eventBus.emit("content:change"),this.engine.eventBus.emit("drag:inter-editor",{html:n})}_cacheBlockRects(){this._blockRects=/* @__PURE__ */new Map;const e=this._getTopLevelBlocks();for(const t of e)this._blockRects.set(t,t.getBoundingClientRect());this._scrollHandler=()=>{this._blockRects=null},this.engine.element.addEventListener("scroll",this._scrollHandler,{passive:!0})}_getBlockRect(e){return this._blockRects&&this._blockRects.has(e)?this._blockRects.get(e):e.getBoundingClientRect()}_updateDropTarget(e){this.engine.element;const t=this._dragSource?this._getReorderableItem(this._dragSource):null,n=t&&t.parentElement?Array.from(t.parentElement.children).filter((e=>e.tagName===t.tagName)):this._getTopLevelBlocks();if(0===n.length)return this._dropTarget=null,this._dropPosition=null,void this._removeDropIndicator();const o=e.clientY;let r=null,s=null,i=1/0;for(const a of n){if(a===this._dragSource)continue;const e=this._getBlockRect(a),t=e.top+e.height/2,n=Math.abs(o-e.top),l=Math.abs(o-e.bottom);if(n<i&&(i=n,r=a,s="before"),l<i&&(i=l,r=a,s="after"),o>=e.top&&o<=e.bottom){r=a,s=o<t?"before":"after",i=0;break}}r===this._dropTarget&&s===this._dropPosition||(this._dropTarget=r,this._dropPosition=s,r?this._showDropIndicator(r,s):this._removeDropIndicator())}_getTopLevelBlocks(){const e=[],t=this.engine.element;for(let n=0;n<t.children.length;n++){const o=t.children[n];o.nodeType!==Node.ELEMENT_NODE||o.classList.contains("rmx-drop-indicator")||o.classList.contains("rmx-drag-ghost")||e.push(o)}return e}_showDropIndicator(e,t){this._dropIndicator||(this._dropIndicator=document.createElement("div"),this._dropIndicator.className="rmx-drop-indicator",this._dropIndicator.setAttribute("aria-hidden","true"));const n=this.engine.element,o=n.getBoundingClientRect(),r=e.getBoundingClientRect(),s="before"===t?r.top-o.top+n.scrollTop:r.bottom-o.top+n.scrollTop;this._dropIndicator.style.top=`${s}px`,this._dropIndicator.parentElement||n.appendChild(this._dropIndicator),this.engine.eventBus.emit("drag:indicator",{target:e,position:t,top:s})}_removeDropIndicator(){this._dropIndicator&&this._dropIndicator.parentElement&&this._dropIndicator.parentElement.removeChild(this._dropIndicator),this._dropIndicator=null}_createGhostPreview(e,t){const n=e.cloneNode(!0);n.className="rmx-drag-ghost",n.style.position="absolute",n.style.top="-9999px",n.style.left="-9999px",n.style.width=`${e.offsetWidth}px`,n.style.pointerEvents="none",document.body.appendChild(n),this._ghostEl=n;const o=e.getBoundingClientRect(),r=t.clientX-o.left,s=t.clientY-o.top;t.dataTransfer.setDragImage(n,r,s)}_removeGhostPreview(){this._ghostEl&&this._ghostEl.parentElement&&this._ghostEl.parentElement.removeChild(this._ghostEl),this._ghostEl=null}_closestDraggableBlock(e){let t=e.nodeType===Node.TEXT_NODE?e.parentElement:e;const n=this.engine.element;for(;t&&t!==n;){if(t.parentElement===n&&Te.has(t.tagName))return t;t=t.parentElement}return null}_getReorderableItem(e){let t=e.nodeType===Node.TEXT_NODE?e.parentElement:e;const n=this.engine.element;for(;t&&t!==n;){if(("LI"===t.tagName||"TR"===t.tagName)&&t.parentElement&&Ie.has(t.parentElement.tagName))return t;t=t.parentElement}return null}_cleanupDrag(){this._dragSource&&this._dragSource.classList.remove("rmx-block-dragging"),this._dragSource=null,this._dragSourceEditor=null,this._dropTarget=null,this._dropPosition=null,this._isExternalDrag=!1,this._enterCount=0,this._blockRects=null,this._scrollHandler&&(this.engine.element.removeEventListener("scroll",this._scrollHandler),this._scrollHandler=null),this._removeDropIndicator(),this._removeGhostPreview(),this.engine.element.classList.remove("rmx-drag-over")}_exceedsMaxFileSize(e){return ve(e,this.engine.options.maxFileSize,{eventBus:this.engine.eventBus})}_handleImageDrop(e,t){this._setCursorAtDropPoint(e),this.engine.history.snapshot();const n=t.filter((e=>!this._exceedsMaxFileSize(e)));let o=Promise.resolve();for(const r of n)o=o.then((()=>this.engine.options.uploadHandler?this.engine.options.uploadHandler(r).then((e=>{this.engine.commands.execute("insertImage",{src:e,alt:r.name})})).catch((e=>{this.engine.eventBus.emit("upload:error",{file:r,error:e})})):new Promise((e=>{const t=new FileReader;t.onprogress=e=>{e.lengthComputable&&this.engine.eventBus.emit("upload:progress",{loaded:e.loaded,total:e.total,percent:Math.round(e.loaded/e.total*100)})},t.onload=t=>{this.engine.commands.execute("insertImage",{src:t.target.result,alt:r.name}),e()},t.onerror=()=>e(),t.readAsDataURL(r)}))))}_handleDocumentDrop(e,t){this._setCursorAtDropPoint(e),this.engine.history.snapshot(),t.filter((e=>!this._exceedsMaxFileSize(e))).forEach((e=>{me(e).then((e=>{const t=this.engine.sanitizer.sanitize(e);this.engine.selection.insertHTML(t),this.engine.eventBus.emit("content:change")})).catch((e=>{}))}))}_handleFileDrop(e,t){this._setCursorAtDropPoint(e),this.engine.history.snapshot();let n=Promise.resolve();for(const o of t)n=n.then((()=>this.engine.options.uploadHandler(o).then((e=>{this.engine.commands.execute("insertAttachment",{url:e,filename:o.name,filesize:o.size})})).catch((e=>{this.engine.eventBus.emit("upload:error",{file:o,error:e})}))))}_setCursorAtDropPoint(e){const t=document.caretRangeFromPoint?document.caretRangeFromPoint(e.clientX,e.clientY):null;if(t){const e=window.getSelection();e.removeAllRanges(),e.addRange(t)}}_handleTextDrop(e){Ae(this.engine,e)}}function Me(e,t,n){return{get element(){return e.element},executeCommand:(t,...n)=>e.commands.execute(t,...n),on:(t,n)=>e.eventBus.on(t,n),off(t,n){e.eventBus.off(t,n)},getSelection:()=>e.selection.getSelection(),getRange:()=>e.selection.getRange(),getActiveFormats:()=>e.selection.getActiveFormats(),getHTML:()=>e.getHTML(),getText:()=>e.getText(),isEmpty:()=>e.isEmpty(),get options(){return{...e.options}},getSetting:e=>n.getPluginSetting(t,e),setSetting(e,o){n.setPluginSetting(t,e,o)}}}Re._getRegistry=()=>Be,Re._getActiveInstances=()=>Ne;const De=/* @__PURE__ */new Map;function He(e){e&&e.name&&De.set(e.name,e)}function Fe(e){return De.delete(e)}function Pe(){return Array.from(De.values())}function ze(e){if(!e)return Pe();const t=e.toLowerCase();return Pe().filter((e=>e.name.toLowerCase().includes(t)||(e.description||"").toLowerCase().includes(t)||(e.tags||[]).some((e=>e.toLowerCase().includes(t)))))}class Oe{constructor(e){this.engine=e,this._plugins=/* @__PURE__ */new Map,this._initialized=/* @__PURE__ */new Set,this._commandPluginMap=/* @__PURE__ */new Map,this._settings=/* @__PURE__ */new Map,this._lifecycleUnsubs=/* @__PURE__ */new Map}getPluginSetting(e,t){const n=this._settings.get(e);if(n&&n.has(t))return n.get(t);const o=this._plugins.get(e);return o?.defaultSettings&&t in o.defaultSettings?o.defaultSettings[t]:void 0}setPluginSetting(e,t,n){const o=this._plugins.get(e);if(!o)return!1;if(o.settingsSchema&&o.settingsSchema.length>0){const e=o.settingsSchema.find((e=>e.key===t));if(e){if("boolean"===e.type&&"boolean"!=typeof n)return!1;if("number"===e.type&&"number"!=typeof n)return!1;if("string"===e.type&&"string"!=typeof n)return!1;if("select"===e.type){if(!(e.options||[]).map((e=>e.value)).includes(n))return!1}if(e.validate&&!e.validate(n))return!1}}return this._settings.has(e)||this._settings.set(e,/* @__PURE__ */new Map),this._settings.get(e).set(t,n),this.engine.eventBus.emit("plugin:settingChanged",{pluginName:e,key:t,value:n}),!0}getPluginSettings(e){const t=this._plugins.get(e),n={...t?.defaultSettings||{}},o=this._settings.get(e);if(o)for(const[r,s]of o)n[r]=s;return n}_resolveDependencyOrder(e){const t=new Set(e.map((e=>e.name))),n=/* @__PURE__ */new Map,o=/* @__PURE__ */new Map;for(const l of e){const e=(l.dependencies||[]).filter((e=>t.has(e)));n.set(l.name,e),o.set(l.name,e.length)}const r=[];for(const[l,c]of o)0===c&&r.push(l);const s=[];for(;r.length>0;){const e=r.shift();s.push(e);for(const[t,s]of n)s.includes(e)&&(o.set(t,o.get(t)-1),0===o.get(t)&&r.push(t))}const i=[];if(s.length<e.length){const t=e.filter((e=>!s.includes(e.name))).map((e=>e.name));i.push(t)}const a=new Map(e.map((e=>[e.name,e])));return{sorted:s.map((e=>a.get(e))),circular:i}}register(e){e&&e.name&&(this._plugins.has(e.name)||(this._plugins.set(e.name,e),e.defaultSettings&&(this._settings.has(e.name)||this._settings.set(e.name,/* @__PURE__ */new Map)),e.commands&&e.commands.forEach((t=>{if(e.lazy){this._commandPluginMap.set(t.name,e.name);const n=t.execute,o=this,r={...t,execute(...r){return o.activatePlugin(e.name),o.engine.commands.register(t.name,{...t,execute:n}),n.apply(this,r)}};this.engine.commands.register(t.name,r)}else this.engine.commands.register(t.name,t)})),this.engine.eventBus.emit("plugin:registered",{name:e.name})))}_initPlugin(e){if(!this._initialized.has(e.name))try{const t=e.requiresFullAccess?this.engine:Me(this.engine,e.name,this);e.init&&e.init(t);const n=[];if("function"==typeof e.onContentChange){const o=()=>{try{e.onContentChange(t)}catch(n){this.engine.eventBus.emit("plugin:error",{name:e.name,error:n,hook:"onContentChange"})}};n.push(this.engine.eventBus.on("content:change",o))}if("function"==typeof e.onSelectionChange){const o=()=>{try{e.onSelectionChange(t)}catch(n){this.engine.eventBus.emit("plugin:error",{name:e.name,error:n,hook:"onSelectionChange"})}};n.push(this.engine.eventBus.on("selection:change",o))}n.length>0&&this._lifecycleUnsubs.set(e.name,n),this._initialized.add(e.name),this.engine.eventBus.emit("plugin:initialized",{name:e.name})}catch(t){this.engine.eventBus.emit("plugin:error",{name:e.name,error:t})}}activatePlugin(e){const t=this._plugins.get(e);if(t&&!this._initialized.has(e)){for(const e of t.dependencies||[])this._plugins.has(e)&&!this._initialized.has(e)&&this.activatePlugin(e);this._initPlugin(t)}}initAll(){const e=[];this._plugins.forEach((t=>{t.lazy||e.push(t)}));const{sorted:t,circular:n}=this._resolveDependencyOrder(e);if(n.length>0)for(const o of n)this.engine.eventBus.emit("plugin:circularDependency",{plugins:o});for(const o of t)this._initPlugin(o);for(const o of e)this._initialized.has(o.name)||this._initPlugin(o)}destroyAll(){this._plugins.forEach((e=>{try{if((!e.lazy||this._initialized.has(e.name))&&e.destroy){const t=e.requiresFullAccess?this.engine:Me(this.engine,e.name,this);e.destroy(t)}const t=this._lifecycleUnsubs.get(e.name);if(t)for(const e of t)e?.()}catch(t){this.engine.eventBus.emit("plugin:error",{name:e.name,error:t})}})),this._plugins.clear(),this._initialized.clear(),this._commandPluginMap.clear(),this._settings.clear(),this._lifecycleUnsubs.clear()}get(e){return this._plugins.get(e)}getAll(){return Array.from(this._plugins.values())}has(e){return this._plugins.has(e)}isInitialized(e){return this._initialized.has(e)}}const Ge=/* @__PURE__ */new WeakMap;let qe=!1;function We(){const e=document.activeElement;if(e){let t=e;for(;t;){const e=Ge.get(t);if(e)return void e._handleSelectionChange();t=t.parentElement}}const t=window.getSelection();if(t&&t.anchorNode){let e=t.anchorNode;for(;e;){const t=Ge.get(e);if(t)return void t._handleSelectionChange();e=e.parentNode}}}class $e{constructor(e,t={}){this.element=e,this.options=t,this.outputFormat=t.outputFormat||"html",this.isSourceMode=!1,this.isMarkdownMode=!1,this._isDestroyed=!1,this._htmlDirty=!0,this._lastHTML="",this._textCache=null,this._textCacheDirty=!0,this.eventBus=new o,this.selection=new g(e),this.keyboard=new w(this),this.commands=new p(this),this.history=new y(this,t.history),this.sanitizer=new I(t.sanitize),this.selection.setSanitizer(this.sanitizer),this.clipboard=new Ee(this),this.dragDrop=new Re(this),this.plugins=new Oe(this),this._handleInput=this._handleInput.bind(this),this._handleSelectionChange=this._handleSelectionChange.bind(this),this._handleFocus=this._handleFocus.bind(this),this._handleBlur=this._handleBlur.bind(this),this._handleClick=this._handleClick.bind(this)}init(){try{this.element.setAttribute("contenteditable","true"),this.element.setAttribute("role","textbox"),this.element.setAttribute("aria-multiline","true"),this.element.setAttribute("spellcheck","true"),this.element.innerHTML.trim()||(this.element.innerHTML="<p><br></p>"),this.element.addEventListener("input",this._handleInput),this.element.addEventListener("focus",this._handleFocus),this.element.addEventListener("blur",this._handleBlur),this.element.addEventListener("click",this._handleClick),Ge.set(this.element,this),qe||(document.addEventListener("selectionchange",We),qe=!0),this.keyboard.init(),this.history.init(),this.clipboard.init(),this.dragDrop.init(),this.plugins.initAll()}catch(e){throw this.eventBus.emit("editor:error",{phase:"init",error:e}),e}}destroy(){this._isDestroyed||(this._isDestroyed=!0,this.element.removeEventListener("input",this._handleInput),this.element.removeEventListener("focus",this._handleFocus),this.element.removeEventListener("blur",this._handleBlur),this.element.removeEventListener("click",this._handleClick),Ge.delete(this.element),this.eventBus.emit("destroy"),this.keyboard.destroy(),this.history.destroy(),this.clipboard.destroy(),this.dragDrop.destroy(),this.plugins.destroyAll(),this.eventBus.removeAllListeners(),this.element.removeAttribute("contenteditable"))}getHTML(){return this._htmlDirty?(this._lastHTML=this.sanitizer.sanitize(this.element.innerHTML),this._htmlDirty=!1,this._lastHTML):this._lastHTML}setHTML(e){const t=this.sanitizer.sanitize(e);this.element.innerHTML=t||"<p><br></p>",this._htmlDirty=!0,this._textCacheDirty=!0}getText(){return this._textCacheDirty||null===this._textCache?(this._textCache=this.element.textContent||"",this._textCacheDirty=!1,this._textCache):this._textCache}isEmpty(){const e=this.getText().trim();return""===e||"\n"===e}focus(){this.element.focus()}blur(){this.element.blur()}executeCommand(e,...t){return this.commands.execute(e,...t)}on(e,t){return this.eventBus.on(e,t)}off(e,t){this.eventBus.off(e,t)}getWordCount(){const e=this.getText().trim();return e?e.split(/\s+/).length:0}getCharCount(){return this.getText().length}_handleInput(){if(this._htmlDirty=!0,this._textCacheDirty=!0,""===this.element.innerHTML||"<br>"===this.element.innerHTML){this.element.innerHTML="<p><br></p>";const e=document.createRange();e.setStart(this.element.firstChild,0),e.collapse(!0),this.selection.setRange(e)}this.eventBus.emit("content:change")}_handleSelectionChange(){if(!this.selection.isWithinEditor(document.activeElement))return;if(!this.selection.getRange())return;const e=this.selection.getActiveFormats();this.eventBus.emit("selection:change",e)}_handleFocus(){this.eventBus.emit("focus")}_handleBlur(){this.eventBus.emit("blur")}_handleClick(e){"checkbox"===e.target.type&&e.target.classList.contains("rmx-task-checkbox")&&(e.target.checked=!e.target.checked,this._htmlDirty=!0,this._textCacheDirty=!0,this.eventBus.emit("content:change"))}}const Ze=new class{constructor(){this._bus=new o,this._registry=/* @__PURE__ */new Map}register(e,t){this._registry.set(e,t),this._bus.emit("editor:registered",{id:e,engine:t})}unregister(e){this._registry.delete(e),this._bus.emit("editor:unregistered",{id:e})}getEditor(e){return this._registry.get(e)}getEditorIds(){return[...this._registry.keys()]}get editorCount(){return this._registry.size}on(e,t,n){return this._bus.on(e,t,n)}off(e,t){this._bus.off(e,t)}once(e,t){return this._bus.once(e,t)}emit(e,t){this._bus.emit(e,t)}broadcast(e,t,n){for(const[o,r]of this._registry)n?.exclude&&o===n.exclude||r.eventBus.emit(e,t)}reset(){this._bus.removeAllListeners(),this._registry.clear()}},Ue={full:he,standard:[["undo","redo"],["headings","fontFamily","fontSize"],["bold","italic","underline","strikethrough"],["foreColor","backColor"],["alignLeft","alignCenter","alignRight","alignJustify"],["orderedList","unorderedList","taskList"],["outdent","indent"],["link","image","table","blockquote","codeBlock","horizontalRule"],["fullscreen"]],minimal:[["headings"],["bold","italic","underline"],["orderedList","unorderedList"],["link","image","blockquote"]],bare:[["bold","italic","underline"]],rich:[["undo","redo"],["headings","fontFamily","fontSize","typography"],["bold","italic","underline","strikethrough"],["foreColor","backColor"],["alignLeft","alignCenter","alignRight"],["orderedList","unorderedList","taskList"],["outdent","indent"],["link","image","attachment","table","embedMedia","blockquote","codeBlock","horizontalRule"],["insertCallout","insertMath","insertToc","insertBookmark","insertMergeTag"],["subscript","superscript","removeFormat"],["findReplace","toggleMarkdown","sourceMode","toggleAnalytics","distractionFree","toggleSplitView","export","commandPalette","fullscreen"]]};function Ve(e,t){const n=new Set(t);return e.map((e=>e.filter((e=>!n.has(e))))).filter((e=>e.length>0))}function je(e,t,n={}){const o=Array.isArray(t)?t:[t],r=e.map((e=>[...e]));if(n.after||n.before){const e=n.after||n.before;for(let t=0;t<r.length;t++){const s=r[t].indexOf(e);if(-1!==s){const e=n.after?s+1:s;return r[t].splice(e,0,...o),r}}}if(void 0!==n.group){const e=n.group<0?r.length+n.group:n.group;if(e>=0&&e<r.length)return r[e].push(...o),r}return r.push(o),r}function Ke(e){const t=[{commands:["undo","redo"]},{commands:["headings","fontFamily","fontSize"]},{commands:["bold","italic","underline","strikethrough"]},{commands:["foreColor","backColor"]},{commands:["alignLeft","alignCenter","alignRight","alignJustify"]},{commands:["orderedList","unorderedList","taskList"]},{commands:["outdent","indent"]},{commands:["link","image","attachment","importDocument","table","embedMedia","blockquote","codeBlock","horizontalRule"]},{commands:["subscript","superscript"]},{commands:["findReplace","toggleMarkdown","sourceMode","export","fullscreen"]}],n=new Set(e),o=[];for(const r of t){const e=r.commands.filter((e=>n.has(e)));e.length>0&&(o.push(e),e.forEach((e=>n.delete(e))))}return n.size>0&&o.push([...n]),o}const Xe=/* @__PURE__ */new Set(["bold","italic","underline","strikethrough","subscript","superscript","alignLeft","alignCenter","alignRight","alignJustify","orderedList","unorderedList","taskList","blockquote","codeBlock","horizontalRule","undo","redo","removeFormat","indent","outdent","fullscreen","sourceMode","toggleMarkdown","distractionFree","toggleSplitView","insertCallout","insertMath","insertToc","insertBookmark","insertMergeTag","toggleAnalytics","toggleSpellcheck","checkGrammar","startCollaboration","stopCollaboration","addComment","removeFormat","lineHeight","letterSpacing","paragraphSpacing"]),Je={bold:"Bold",italic:"Italic",underline:"Underline",strikethrough:"Strikethrough",subscript:"Subscript",superscript:"Superscript",alignLeft:"Align Left",alignCenter:"Align Center",alignRight:"Align Right",alignJustify:"Justify",orderedList:"Numbered List",unorderedList:"Bulleted List",taskList:"Task List",blockquote:"Blockquote",codeBlock:"Code Block",horizontalRule:"Horizontal Rule",undo:"Undo",redo:"Redo",removeFormat:"Remove Formatting",indent:"Indent",outdent:"Outdent",link:"Insert Link",image:"Insert Image",attachment:"Attach File",table:"Insert Table",importDocument:"Import Document",embedMedia:"Embed Media",findReplace:"Find & Replace",fullscreen:"Fullscreen",sourceMode:"Source Code",toggleMarkdown:"Toggle Markdown",export:"Export Document",distractionFree:"Distraction-Free Mode",toggleSplitView:"Split View",lineHeight:"Line Height",letterSpacing:"Letter Spacing",paragraphSpacing:"Paragraph Spacing",saveColorPreset:"Save Color Preset",typography:"Typography",foreColor:"Text Color",backColor:"Background Color",headings:"Block Type",fontFamily:"Font Family",fontSize:"Font Size",commandPalette:"Command Palette",insertCallout:"Insert Callout",insertMath:"Insert Math",insertToc:"Insert Table of Contents",insertBookmark:"Insert Bookmark",insertMergeTag:"Insert Merge Tag",addComment:"Add Comment",scanBrokenLinks:"Scan Broken Links",getAnalytics:"Content Analytics",toggleAnalytics:"Toggle Analytics",toggleSpellcheck:"Toggle Spellcheck",checkGrammar:"Check Grammar",startCollaboration:"Start Collaboration",stopCollaboration:"Stop Collaboration"},Ye={bold:"mod+B",italic:"mod+I",underline:"mod+U",strikethrough:"mod+Shift+X",undo:"mod+Z",redo:"mod+Shift+Z",insertLink:"mod+K",findReplace:"mod+F",fullscreen:"mod+Shift+F",sourceMode:"mod+Shift+U",commandPalette:"mod+Shift+P",distractionFree:"mod+Shift+D",toggleSplitView:"mod+Shift+V"},Qe={link:"link",image:"image",attachment:"attachment",importDocument:"importDocument",table:"table",embedMedia:"embed",findReplace:"findReplace",export:"export"};function et(e){const t=Ye[e];return t?t.replace(/mod/g,x()?"⌘":"Ctrl"):""}function tt(e,t,n){switch(e){case"bold":return t.bold;case"italic":return t.italic;case"underline":return t.underline;case"strikethrough":return t.strikethrough;case"subscript":return t.subscript;case"superscript":return t.superscript;case"alignLeft":return"left"===t.alignment;case"alignCenter":return"center"===t.alignment;case"alignRight":return"right"===t.alignment;case"alignJustify":return"justify"===t.alignment;case"orderedList":return t.orderedList;case"unorderedList":return t.unorderedList;case"blockquote":return t.blockquote;case"codeBlock":return t.codeBlock;case"sourceMode":return n?.isSourceMode;case"toggleMarkdown":return n?.isMarkdownMode;case"fullscreen":return n?.element?.closest(".rmx-editor")?.classList.contains("rmx-fullscreen");case"distractionFree":return n?.element?.closest(".rmx-editor")?.classList.contains("rmx-distraction-free");case"toggleSplitView":return n?.element?.closest(".rmx-editor")?.classList.contains("rmx-split-view");default:return!1}}const nt={bold:"mod+b",italic:"mod+i",underline:"mod+u",strikethrough:"mod+shift+x",undo:"mod+z",redo:"mod+shift+z",selectAll:"mod+a",insertLink:"mod+k",findReplace:"mod+f",orderedList:"mod+shift+7",unorderedList:"mod+shift+8",blockquote:"mod+shift+9",codeBlock:"mod+shift+c",indent:"tab",outdent:"shift+tab",fullscreen:"mod+shift+f",sourceMode:"mod+shift+u",subscript:"mod+,",superscript:"mod+."};const ot=new class{constructor(){this._initialized=!1,this._sanitizerSchema=null,this._toolbarPresets=null,this._defaults=null,this._keybindings=null,this._commands=null,this._icons=/* @__PURE__ */new Map}_ensureInit(){this._initialized||(this._initialized=!0,this._sanitizerSchema=Object.freeze({allowedTags:Object.freeze(Object.fromEntries(Object.entries(k).map((([e,t])=>[e,Object.freeze([...t])])))),allowedStyles:Object.freeze([..._])}),this._toolbarPresets=Object.freeze(Object.fromEntries(Object.entries(Ue).map((([e,t])=>[e,Object.freeze(t.map((e=>Object.freeze([...e]))))])))),this._defaults=Object.freeze({toolbar:Object.freeze(he.map((e=>Object.freeze([...e])))),menuBar:Object.freeze(be),fonts:Object.freeze([...ge]),fontSizes:Object.freeze([...pe]),colors:Object.freeze([...fe]),headingOptions:Object.freeze([...ye])}),this._keybindings=Object.freeze({...nt}),this._commands=Object.freeze({buttons:Object.freeze({...Xe}),tooltips:Object.freeze({...Je}),shortcuts:Object.freeze({...Ye}),modals:Object.freeze({...Qe})}))}get sanitizerSchema(){return this._ensureInit(),this._sanitizerSchema}get toolbarPresets(){return this._ensureInit(),this._toolbarPresets}get defaults(){return this._ensureInit(),this._defaults}get keybindings(){return this._ensureInit(),this._keybindings}get commands(){return this._ensureInit(),this._commands}registerIcon(e,t){this._icons.set(e,t)}unregisterIcon(e){this._icons.delete(e)}getIcon(e){return this._icons.get(e)}getIconNames(){return[...this._icons.keys()]}get stats(){return this._ensureInit(),{registeredIcons:this._icons.size,frozenSchemas:!0}}};function rt(e,t){const n=e.selection.getSelection();if(!n||0===n.rangeCount)return;const o=n.getRangeAt(0);if(o.collapsed)return;const r=e.selection.getParentElement();if(r&&r.tagName===t.toUpperCase()){const e=document.createDocumentFragment();for(;r.firstChild;)e.appendChild(r.firstChild);return void r.parentNode.replaceChild(e,r)}let s=r;for(;s&&s!==e.element;){if(s.tagName===t.toUpperCase()){const e=document.createDocumentFragment();for(;s.firstChild;)e.appendChild(s.firstChild);return void s.parentNode.replaceChild(e,s)}s=s.parentNode}const i=document.createElement(t);try{o.surroundContents(i)}catch{const e=o.extractContents();i.appendChild(e),o.insertNode(i)}}function st(e,t){const n=e.selection.getParentElement();if(!n)return!1;let o=n;for(;o&&o!==e.element;){if(o.tagName===t.toUpperCase())return!0;o=o.parentNode}return!1}function it(e){e.commands.register("bold",{execute(e){rt(e,"strong")},isActive:e=>st(e,"STRONG")||st(e,"B"),shortcut:"mod+b",meta:{icon:"bold",tooltip:"Bold"}}),e.commands.register("italic",{execute(e){rt(e,"em")},isActive:e=>st(e,"EM")||st(e,"I"),shortcut:"mod+i",meta:{icon:"italic",tooltip:"Italic"}}),e.commands.register("underline",{execute(e){rt(e,"u")},isActive:e=>st(e,"U"),shortcut:"mod+u",meta:{icon:"underline",tooltip:"Underline"}}),e.commands.register("strikethrough",{execute(e){rt(e,"s")},isActive:e=>st(e,"S")||st(e,"DEL"),shortcut:"mod+shift+x",meta:{icon:"strikethrough",tooltip:"Strikethrough"}}),e.commands.register("subscript",{execute(e){rt(e,"sub")},isActive:e=>st(e,"SUB"),shortcut:"mod+,",alternateShortcuts:["mod+shift+,"],meta:{icon:"subscript",tooltip:"Subscript"}}),e.commands.register("superscript",{execute(e){rt(e,"sup")},isActive:e=>st(e,"SUP"),shortcut:"mod+.",alternateShortcuts:["mod+shift+."],meta:{icon:"superscript",tooltip:"Superscript"}}),e.commands.register("highlight",{execute(e,{color:t="yellow"}={}){const n=e.selection.getSelection();if(!n||0===n.rangeCount)return;const o=n.getRangeAt(0);if(o.collapsed)return;let r=e.selection.getParentElement();for(;r&&r!==e.element;){if("MARK"===r.tagName){const e=document.createDocumentFragment();for(;r.firstChild;)e.appendChild(r.firstChild);return void r.parentNode.replaceChild(e,r)}r=r.parentNode}const s={yellow:"rgba(255, 235, 59, 0.4)",green:"rgba(76, 175, 80, 0.3)",blue:"rgba(33, 150, 243, 0.3)",pink:"rgba(233, 30, 99, 0.3)",orange:"rgba(255, 152, 0, 0.3)",purple:"rgba(156, 39, 176, 0.3)"},i=s[t]||s.yellow,a=document.createElement("mark");a.style.backgroundColor=i,a.setAttribute("data-highlight-color",t);try{o.surroundContents(a)}catch{const e=o.extractContents();a.appendChild(e),o.insertNode(a)}},isActive:e=>st(e,"MARK"),meta:{icon:"highlight",tooltip:"Highlight"}}),e.commands.register("removeFormat",{execute(e){const t=e.selection.getSelection();if(!t||0===t.rangeCount)return;const n=t.getRangeAt(0);if(n.collapsed)return;const o=/* @__PURE__ */new Set(["STRONG","B","EM","I","U","S","DEL","SUB","SUP","MARK","SPAN"]),r=n.commonAncestorContainer,s=r.nodeType===Node.TEXT_NODE?r.parentElement:r,i=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT),a=[];let l;for(;l=i.nextNode();)o.has(l.tagName)&&n.intersectsNode(l)&&a.push(l);for(let c=a.length-1;c>=0;c--){const e=a[c],t=e.parentNode;for(;e.firstChild;)t.insertBefore(e.firstChild,e);t.removeChild(e)}},shortcut:"mod+\\",meta:{icon:"removeFormat",tooltip:"Remove Formatting"}})}function at(e,t){if(t<=1)return e;const n=t-1;return Math.min(e+n,6)}function lt(e,t){const n=e.selection.getParentBlock();if(!n)return;if(n.tagName===t.toUpperCase())return;const o=document.createElement(t);for(;n.firstChild;)o.appendChild(n.firstChild);n.className&&(o.className=n.className),n.parentNode.replaceChild(o,n);const r=document.createRange();r.selectNodeContents(o),r.collapse(!1),e.selection.setRange(r)}function ct(e){const t=e.options.baseHeadingLevel||1;e.commands.register("heading",{execute(e,n){if("p"===n)lt(e,"p");else{lt(e,`h${at(Number(n),t)}`)}},isActive(e){const t=e.selection.getParentBlock();return!!t&&(!!/^H[1-6]$/.test(t.tagName)&&t.tagName.toLowerCase())},meta:{icon:"heading",tooltip:"Heading"}});for(let n=1;n<=6;n++){const o=at(n,t);e.commands.register(`h${n}`,{execute(e){lt(e,`h${o}`)},isActive(e){const t=e.selection.getParentBlock();return t&&t.tagName===`H${o}`},meta:{tooltip:`Heading ${n}`}})}e.commands.register("paragraph",{execute(e){lt(e,"p")},isActive(e){const t=e.selection.getParentBlock();return t&&"P"===t.tagName},meta:{tooltip:"Normal text"}})}function dt(e){e.commands.register("alignLeft",{execute(e){const t=e.selection.getParentBlock();t&&(t.style.textAlign="left")},isActive(e){const t=e.selection.getParentBlock();if(!t)return!1;const n=t.style.textAlign;return!n||"left"===n||"start"===n},meta:{icon:"alignLeft",tooltip:"Align Left"}}),e.commands.register("alignCenter",{execute(e){const t=e.selection.getParentBlock();t&&(t.style.textAlign="center")},isActive(e){const t=e.selection.getParentBlock();if(!t)return!1;return"center"===t.style.textAlign},meta:{icon:"alignCenter",tooltip:"Align Center"}}),e.commands.register("alignRight",{execute(e){const t=e.selection.getParentBlock();t&&(t.style.textAlign="right")},isActive(e){const t=e.selection.getParentBlock();if(!t)return!1;const n=t.style.textAlign;return"right"===n||"end"===n},meta:{icon:"alignRight",tooltip:"Align Right"}}),e.commands.register("alignJustify",{execute(e){const t=e.selection.getParentBlock();t&&(t.style.textAlign="justify")},isActive(e){const t=e.selection.getParentBlock();if(!t)return!1;return"justify"===t.style.textAlign},meta:{icon:"alignJustify",tooltip:"Justify"}})}function ut(e){e.commands.register("orderedList",{execute(e){const t=e.selection.getClosestElement("ol");if(t)return void ht(t);const n=e.selection.getClosestElement("ul");n?gt(n,"ol"):mt(e,"ol")},isActive:e=>!!e.selection.getClosestElement("ol"),shortcut:"mod+shift+7",meta:{icon:"orderedList",tooltip:"Numbered List"}}),e.commands.register("unorderedList",{execute(e){const t=e.selection.getClosestElement("ul");if(t&&!t.classList.contains("rmx-task-list"))return void ht(t);const n=e.selection.getClosestElement("ol");n?gt(n,"ul"):mt(e,"ul")},isActive(e){const t=e.selection.getClosestElement("ul");return!!t&&!t.classList.contains("rmx-task-list")},shortcut:"mod+shift+8",meta:{icon:"unorderedList",tooltip:"Bulleted List"}}),e.commands.register("taskList",{execute(e){const t=e.selection.getClosestElement("ul");if(t&&t.classList.contains("rmx-task-list"))return t.classList.remove("rmx-task-list"),void t.querySelectorAll(".rmx-task-checkbox").forEach((e=>e.remove()));t||mt(e,"ul");const n=e.selection.getClosestElement("ul");n&&(n.classList.add("rmx-task-list"),n.querySelectorAll("li").forEach((e=>{if(!e.querySelector(".rmx-task-checkbox")){const t=document.createElement("input");t.type="checkbox",t.className="rmx-task-checkbox",t.setAttribute("contenteditable","false"),e.insertBefore(t,e.firstChild)}})))},isActive(e){const t=e.selection.getClosestElement("ul");return t&&t.classList.contains("rmx-task-list")},meta:{icon:"taskList",tooltip:"Task List"}}),e.commands.register("indent",{execute(e){const t=e.selection.getClosestElement("li");if(!t)return;const n=t.previousElementSibling;if(!n)return;const o=e.options?.maxListNestingDepth??5;let r=0,s=t.parentElement;for(;s&&s!==e.element;)"UL"!==s.tagName&&"OL"!==s.tagName||r++,s=s.parentElement;if(r>=o)return;const i=t.parentElement.tagName.toLowerCase();let a=n.querySelector(i);a||(a=document.createElement(i),n.appendChild(a)),a.appendChild(t)},meta:{icon:"indent",tooltip:"Increase Indent"}}),e.commands.register("outdent",{execute(e){const t=e.selection.getClosestElement("li");if(!t)return;const n=t.parentElement;if(!n)return;const o=n.parentElement;if(!o||"LI"!==o.tagName)return;o.parentElement.insertBefore(t,o.nextSibling),0===n.children.length&&n.remove()},meta:{icon:"outdent",tooltip:"Decrease Indent"}})}function mt(e,t){const n=e.selection.getParentBlock();if(!n)return;const o=document.createElement(t),r=document.createElement("li");for(;n.firstChild;)r.appendChild(n.firstChild);o.appendChild(r),n.parentNode.replaceChild(o,n);const s=document.createRange();s.selectNodeContents(r),s.collapse(!1),e.selection.setRange(s)}function ht(e){const t=e.parentNode,n=Array.from(e.querySelectorAll(":scope > li"));for(const o of n){const n=document.createElement("p");for(;o.firstChild;)n.appendChild(o.firstChild);t.insertBefore(n,e)}t.removeChild(e)}function gt(e,t){const n=document.createElement(t);for(const o of e.attributes)n.setAttribute(o.name,o.value);for(;e.firstChild;)n.appendChild(e.firstChild);e.parentNode.replaceChild(n,e)}const pt=/^\s*(javascript|vbscript|data\s*:\s*text\/html)\s*:/i;function ft(e){return e&&pt.test(e)?"#":e}function bt(e){e.commands.register("insertLink",{execute(e,{href:t,text:n,target:o="_blank"}){if(!t)return;const r=e.selection,s=r.getSelectedText();if(s){const e=r.wrapWith("a",{href:t,target:o,rel:"_blank"===o?"noopener noreferrer":void 0});e&&n&&n!==s&&(e.textContent=n)}else{const e=n||t,s=`<a href="${yt(ft(t))}" target="${yt(o)}"${"_blank"===o?' rel="noopener noreferrer"':""}>${te(e)}</a>`;r.insertHTML(s)}},shortcut:"mod+k",meta:{icon:"link",tooltip:"Insert Link"}}),e.commands.register("editLink",{execute(e,{href:t,text:n,target:o}){const r=e.selection.getClosestElement("a");r&&(void 0!==t&&(r.href=ft(t)),void 0!==n&&(r.textContent=n),void 0!==o&&(r.target=o,"_blank"===o?r.rel="noopener noreferrer":r.removeAttribute("rel")))},meta:{tooltip:"Edit Link"}}),e.commands.register("removeLink",{execute(e){e.selection.unwrap("a")},meta:{icon:"unlink",tooltip:"Remove Link"}})}function yt(e){return e.replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function vt(e){e.commands.register("insertImage",{execute(e,{src:t,alt:n="",width:o,height:r}){if(!t)return;if(/^data:image\/svg/i.test(t))return;try{if(new URL(t,window.location.href).pathname.toLowerCase().endsWith(".svg"))return}catch{if(/\.svg(\?|#|$)/i.test(t))return}if(e.element.focus(),!e.selection.getRange()){const t=document.createRange();t.selectNodeContents(e.element),t.collapse(!1),e.selection.setRange(t)}const s=document.createElement("img");if(s.src=t,s.alt=n,o&&(s.style.width="number"==typeof o?`${o}px`:o),r&&(s.style.height="number"==typeof r?`${r}px`:r),s.style.maxWidth="100%",s.className="rmx-image",e.selection.insertNode(s),!s.nextSibling||s.parentElement===e.element){const e=document.createElement("p");e.innerHTML="<br>",s.parentElement.insertBefore(e,s.nextSibling)}},meta:{icon:"image",tooltip:"Insert Image"}}),e.commands.register("resizeImage",{execute(e,{element:t,width:n,height:o}){t&&"IMG"===t.tagName&&(t.style.width="number"==typeof n?`${n}px`:n,t.style.height=o?"number"==typeof o?`${o}px`:o:"auto")},meta:{tooltip:"Resize Image"}}),e.commands.register("alignImage",{execute(e,{element:t,alignment:n}){if(t&&"IMG"===t.tagName)switch(t.style.float="",t.style.margin="",t.style.display="",n){case"left":t.style.float="left",t.style.margin="0 16px 16px 0";break;case"right":t.style.float="right",t.style.margin="0 0 16px 16px";break;case"center":t.style.display="block",t.style.margin="16px auto"}},meta:{tooltip:"Align Image"}}),e.commands.register("removeImage",{execute(e,{element:t}){t&&"IMG"===t.tagName&&t.parentNode.removeChild(t)},meta:{tooltip:"Remove Image"}})}function xt(e){e.commands.register("insertTable",{execute(e,{rows:t=3,cols:n=3}={}){let o='<table class="rmx-table"><thead><tr>';for(let r=0;r<n;r++)o+="<th><br></th>";o+="</tr></thead><tbody>";for(let r=1;r<t;r++){o+="<tr>";for(let e=0;e<n;e++)o+="<td><br></td>";o+="</tr>"}o+="</tbody></table><p><br></p>",e.selection.insertHTML(o)},meta:{icon:"table",tooltip:"Insert Table"}}),e.commands.register("toggleHeaderRow",{execute(e){const t=e.selection.getClosestElement("table");if(!t)return;const n=t.querySelector("thead");if(n){const e=n.querySelector("tr");if(!e)return;const o=document.createElement("tr");for(const t of Array.from(e.cells)){const e=document.createElement("td");e.innerHTML=t.innerHTML,t.colSpan>1&&(e.colSpan=t.colSpan),t.rowSpan>1&&(e.rowSpan=t.rowSpan),o.appendChild(e)}let r=t.querySelector("tbody");r||(r=document.createElement("tbody"),t.appendChild(r)),r.insertBefore(o,r.firstChild),n.remove()}else{let e=t.querySelector("tbody");if(!e)return;const n=e.querySelector("tr");if(!n)return;const o=document.createElement("thead"),r=document.createElement("tr");for(const t of Array.from(n.cells)){const e=document.createElement("th");e.innerHTML=t.innerHTML,t.colSpan>1&&(e.colSpan=t.colSpan),t.rowSpan>1&&(e.rowSpan=t.rowSpan),r.appendChild(e)}o.appendChild(r),t.insertBefore(o,t.firstChild),n.remove()}},meta:{tooltip:"Toggle Header Row"}}),e.commands.register("alignCell",{execute(e,{direction:t="left"}={}){const n=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");n&&["left","center","right"].includes(t)&&(n.style.textAlign=t)},meta:{tooltip:"Align Cell Content"}}),e.commands.register("addRowBefore",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=t.parentElement,o=kt(Ct(n));n.parentElement.insertBefore(o,n)},meta:{tooltip:"Insert Row Before"}}),e.commands.register("addRowAfter",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=t.parentElement,o=kt(Ct(n));n.parentElement.insertBefore(o,n.nextSibling)},meta:{tooltip:"Insert Row After"}}),e.commands.register("addColBefore",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=wt(t),o=e.selection.getClosestElement("table");o&&o.querySelectorAll("tr").forEach((e=>{const t=document.createElement("THEAD"===e.parentElement.tagName?"th":"td");t.innerHTML="<br>";const o=e.cells[n];e.insertBefore(t,o)}))},meta:{tooltip:"Insert Column Before"}}),e.commands.register("addColAfter",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=wt(t),o=e.selection.getClosestElement("table");o&&o.querySelectorAll("tr").forEach((e=>{const t=document.createElement("THEAD"===e.parentElement.tagName?"th":"td");t.innerHTML="<br>";const o=e.cells[n];e.insertBefore(t,o?o.nextSibling:null)}))},meta:{tooltip:"Insert Column After"}}),e.commands.register("deleteRow",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=t.parentElement;if(n.parentElement.rows.length<=1){const t=e.selection.getClosestElement("table");if(t){const e=document.createElement("p");e.innerHTML="<br>",t.parentElement.replaceChild(e,t)}}else n.remove()},meta:{tooltip:"Delete Row"}}),e.commands.register("deleteCol",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=wt(t),o=e.selection.getClosestElement("table");if(!o)return;const r=o.querySelector("tr");if(r&&r.cells.length<=1){const e=document.createElement("p");e.innerHTML="<br>",o.parentElement.replaceChild(e,o)}else o.querySelectorAll("tr").forEach((e=>{e.cells[n]&&e.cells[n].remove()}))},meta:{tooltip:"Delete Column"}}),e.commands.register("deleteTable",{execute(e){const t=e.selection.getClosestElement("table");if(!t)return;const n=document.createElement("p");n.innerHTML="<br>",t.parentElement.replaceChild(n,t)},meta:{tooltip:"Delete Table"}}),e.commands.register("mergeCells",{execute(e,{cells:t}){if(!t||t.length<2)return;const n=t[0],o=/* @__PURE__ */new Set,r=/* @__PURE__ */new Set;t.forEach((e=>{o.add(e.parentElement.rowIndex),r.add(wt(e))}));const s=o.size,i=r.size,a=[];t.slice(1).forEach((e=>{e.textContent.trim()&&a.push(e.innerHTML),e.remove()})),a.length>0&&(n.innerHTML+="<br>"+a.join("<br>")),s>1&&(n.rowSpan=s),i>1&&(n.colSpan=i)},meta:{tooltip:"Merge Cells"}}),e.commands.register("sortTable",{execute(e,{columnIndex:t,direction:n,dataType:o,keys:r,comparator:s}={}){const i=e.selection.getClosestElement("table");if(!i)return;const a=i.querySelector("tbody");if(!a)return;const l=Array.from(a.querySelectorAll("tr"));if(0===l.length)return;const c=r||[{columnIndex:t,direction:n||"asc",dataType:o}],d=(e,t)=>{const n=e.querySelectorAll("td, th");return n[t]?.textContent?.trim()||""},u=s||e.options?.tableSortComparator;l.sort(((e,t)=>{for(const n of c){const o=d(e,n.columnIndex),r=d(t,n.columnIndex),s=n.dataType||_t(l,n.columnIndex);let i=0;if(u)i=u(o,r,s,n.columnIndex);else if("numeric"===s){i=(parseFloat(o)||0)-(parseFloat(r)||0)}else if("date"===s){i=(new Date(o).getTime()||0)-(new Date(r).getTime()||0)}else i=o.localeCompare(r,void 0,{sensitivity:"base"});if("desc"===n.direction&&(i=-i),0!==i)return i}return 0})),l.forEach((e=>a.appendChild(e)));const m=i.querySelector("thead");if(m){const e=m.querySelectorAll("th");e.forEach((e=>{e.removeAttribute("data-sort-dir"),e.removeAttribute("data-sort-priority")})),c.forEach(((t,n)=>{e[t.columnIndex]&&(e[t.columnIndex].setAttribute("data-sort-dir",t.direction||"asc"),c.length>1&&e[t.columnIndex].setAttribute("data-sort-priority",String(n+1)))}))}},meta:{tooltip:"Sort Table"}}),e.commands.register("filterTable",{execute(e,{columnIndex:t,filterValue:n}={}){const o=e.selection.getClosestElement("table");if(!o)return;const r=o.querySelector("thead"),s=o.querySelector("tbody");if(!s)return;if(r){const e=r.querySelectorAll("th");e[t]&&(n?e[t].setAttribute("data-filter-value",n):e[t].removeAttribute("data-filter-value"))}const i=[];r&&r.querySelectorAll("th").forEach(((e,t)=>{const n=e.getAttribute("data-filter-value");n&&i.push({columnIndex:t,value:n.toLowerCase()})}));s.querySelectorAll("tr").forEach((e=>{const t=e.querySelectorAll("td, th");i.some((e=>!(t[e.columnIndex]?.textContent||"").toLowerCase().includes(e.value)))?e.classList.add("rmx-row-hidden"):e.classList.remove("rmx-row-hidden")}))},meta:{tooltip:"Filter Table"}}),e.commands.register("clearTableFilters",{execute(e){const t=e.selection.getClosestElement("table");if(!t)return;const n=t.querySelector("thead");n&&n.querySelectorAll("th").forEach((e=>{e.removeAttribute("data-filter-value")}));const o=t.querySelector("tbody");o&&o.querySelectorAll("tr.rmx-row-hidden").forEach((e=>{e.classList.remove("rmx-row-hidden")}))},meta:{tooltip:"Clear Table Filters"}}),e.commands.register("formatCell",{execute(e,{format:t,options:n={}}={}){const o=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!o||!t)return;const r=o.getAttribute("data-raw-value")||o.textContent.trim();o.setAttribute("data-raw-value",r),o.setAttribute("data-cell-format",t);const s=parseFloat(r);if("number"!==t||isNaN(s))if("currency"!==t||isNaN(s))if("percentage"!==t||isNaN(s)){if("date"===t){const e=new Date(r);isNaN(e.getTime())||(o.textContent=new Intl.DateTimeFormat(void 0,{dateStyle:n.dateStyle||"short"}).format(e))}}else{const e=n.decimals??1;o.textContent=(100*s).toFixed(e)+"%"}else o.textContent=new Intl.NumberFormat(void 0,{style:"currency",currency:n.currency||"USD",minimumFractionDigits:n.decimals??2,maximumFractionDigits:n.decimals??2}).format(s);else o.textContent=new Intl.NumberFormat(void 0,{minimumFractionDigits:n.decimals??2,maximumFractionDigits:n.decimals??2}).format(s)},meta:{tooltip:"Format Cell"}}),e.commands.register("evaluateFormulas",{execute(e){const t=e.selection.getClosestElement("table");t&&Tt(t)},meta:{tooltip:"Evaluate Formulas"}}),e.commands.register("splitCell",{execute(e){const t=e.selection.getClosestElement("td")||e.selection.getClosestElement("th");if(!t)return;const n=t.colSpan||1,o=t.rowSpan||1;if(n<=1&&o<=1)return;t.colSpan=1,t.rowSpan=1;const r=t.parentElement,s=r.closest("thead")?"th":t.tagName.toLowerCase();for(let i=1;i<n;i++){const e=document.createElement(s);e.innerHTML="<br>",r.insertBefore(e,t.nextSibling)}if(o>1){const e=wt(t);let s=r.nextElementSibling;for(let t=1;t<o&&s;t++){const t=s.closest("thead")?"th":"td";let o=null,r=0;for(const n of s.cells){if(r>=e){o=n;break}r+=n.colSpan||1}for(let e=0;e<n;e++){const e=document.createElement(t);e.innerHTML="<br>",s.insertBefore(e,o)}s=s.nextElementSibling}}},meta:{tooltip:"Split Cell"}})}function Ct(e){let t=0;for(const n of e.cells)t+=n.colSpan||1;return t}function wt(e){let t=0,n=e.previousElementSibling;for(;n;)t+=n.colSpan||1,n=n.previousElementSibling;return t}function kt(e){const t=document.createElement("tr");for(let n=0;n<e;n++){const e=document.createElement("td");e.innerHTML="<br>",t.appendChild(e)}return t}function _t(e,t){let n=0,o=0,r=0;for(const s of e){const e=s.querySelectorAll("td, th"),i=(e[t]?.textContent||"").trim();i&&(r++,!isNaN(parseFloat(i))&&isFinite(i)?n++:!isNaN(new Date(i).getTime())&&i.length>4&&o++)}return 0===r?"alphabetical":n/r>.7?"numeric":o/r>.7?"date":"alphabetical"}const St={SUM:e=>e.flat().reduce(((e,t)=>e+(parseFloat(t)||0)),0),AVERAGE:e=>{const t=e.flat().map((e=>parseFloat(e))).filter((e=>!isNaN(e)));return t.length?t.reduce(((e,t)=>e+t),0)/t.length:0},COUNT:e=>e.flat().filter((e=>""!==e&&null!=e)).length,MIN:e=>Math.min(...e.flat().map((e=>parseFloat(e))).filter((e=>!isNaN(e)))),MAX:e=>Math.max(...e.flat().map((e=>parseFloat(e))).filter((e=>!isNaN(e)))),IF:e=>e[0]?e[1]:e[2]??"",CONCAT:e=>e.flat().join("")};function At(e){const t=e.match(/^([A-Z]+)(\d+)$/);if(!t)return null;let n=0;for(let o=0;o<t[1].length;o++)n=26*n+(t[1].charCodeAt(o)-64);return{col:n-1,row:parseInt(t[2],10)-1}}function Et(e,t,n){const o=e.querySelectorAll("thead tr, tbody tr")[n];if(!o)return"";const r=o.querySelectorAll("td, th");return r[t]?r[t].getAttribute("data-raw-value")||r[t].textContent.trim():""}function Lt(e,t,n=/* @__PURE__ */new Set){const o=function(e){const t=[];let n=0;for(;n<e.length;){const o=e[n];if(/\s/.test(o))n++;else if("+-*/(),".includes(o))t.push({type:"op",value:o}),n++;else if(">"!==o&&"<"!==o&&"="!==o)if(/\d/.test(o)||"."===o&&/\d/.test(e[n+1])){let o="";for(;n<e.length&&(/\d/.test(e[n])||"."===e[n]);)o+=e[n++];t.push({type:"number",value:parseFloat(o)})}else if('"'!==o)if(/[A-Z]/i.test(o)){let o="";for(;n<e.length&&/[A-Z0-9]/i.test(e[n]);)o+=e[n++];if(":"===e[n]){n++;let r="";for(;n<e.length&&/[A-Z0-9]/i.test(e[n]);)r+=e[n++];t.push({type:"range",value:o.toUpperCase()+":"+r.toUpperCase()})}else/^[A-Z]+\d+$/i.test(o)?t.push({type:"cellref",value:o.toUpperCase()}):t.push({type:"func",value:o.toUpperCase()})}else n++;else{let o="";for(n++;n<e.length&&'"'!==e[n];)o+=e[n++];n++,t.push({type:"string",value:o})}else"="===e[n+1]?(t.push({type:"op",value:o+"="}),n+=2):(t.push({type:"op",value:o}),n++)}return t}(e.startsWith("=")?e.slice(1):e);let r=0;const s=()=>o[r]||null,i=()=>o[r++];function a(){let e=l();for(;s()&&("+"===s().value||"-"===s().value);){const t=i().value,n=l();e="+"===t?e+n:e-n}return e}function l(){let e=c();for(;s()&&("*"===s().value||"/"===s().value);){const t=i().value,n=c();e="*"===t?e*n:0!==n?e/n:NaN}return e}function c(){let e=d();if(s()&&[">","<",">=","<=","=="].includes(s().value)){const t=i().value,n=d();if(">"===t)return e>n?1:0;if("<"===t)return e<n?1:0;if(">="===t)return e>=n?1:0;if("<="===t)return e<=n?1:0;if("=="===t)return e===n?1:0}return e}function d(){const e=s();if(!e)return 0;if("number"===e.type)return i(),e.value;if("string"===e.type)return i(),e.value;if("cellref"===e.type){i();const o=At(e.value);if(!o)return 0;const r=e.value;if(n.has(r))return"#CIRC!";n.add(r);const s=Et(t,o.col,o.row),a=t.querySelectorAll("thead tr, tbody tr"),l=a[o.row]?.querySelectorAll("td, th")[o.col],c=l?.getAttribute("data-formula");let d;return c?d=Lt(c,t,n):(d=parseFloat(s),isNaN(d)&&(d=s)),n.delete(r),d}if("range"===e.type){i();const n=function(e){const t=e.split(":");if(2!==t.length)return null;const n=At(t[0]),o=At(t[1]);if(!n||!o)return null;const r=[];for(let s=n.row;s<=o.row;s++)for(let e=n.col;e<=o.col;e++)r.push({col:e,row:s});return r}(e.value);return n?n.map((e=>{const n=Et(t,e.col,e.row),o=parseFloat(n);return isNaN(o)?n:o})):[]}if("func"===e.type){const e=i().value,t=St[e];if(!t)return"#NAME!";"("===s()?.value&&i();const n=[];for(;s()&&")"!==s().value;){if(","===s().value){i();continue}const e="range"===s()?.type?d():a();n.push(e)}return")"===s()?.value&&i(),t(n)}if("("===e.value){i();const e=a();return")"===s()?.value&&i(),e}return"-"===e.value?(i(),-d()):(i(),0)}return a()}function Tt(e){const t=e.querySelectorAll("td[data-formula], th[data-formula]");for(const n of t){const t=n.getAttribute("data-formula");if(!t)continue;const o=Lt(t,e);"string"==typeof o&&o.startsWith("#")?n.textContent=o:n.textContent="number"==typeof o?String(Math.round(1e10*o)/1e10):o}}const It=/* @__PURE__ */new Set(["P","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","UL","OL","TABLE","HR","DIV","DETAILS"]);function Bt(e){const t=e.selection.getParentBlock();if(!t)return null;let n=t;for(;n&&n.parentElement!==e.element;)n=n.parentElement;return n&&It.has(n.tagName)?n:null}function Nt(e){e.commands.register("blockquote",{execute(e){const t=e.selection.getClosestElement("blockquote");if(t){const e=t.parentNode;for(;t.firstChild;)e.insertBefore(t.firstChild,t);e.removeChild(t)}else{const t=e.selection.getParentBlock();if(!t)return;const n=document.createElement("blockquote");t.parentNode.replaceChild(n,t),n.appendChild(t)}},isActive:e=>!!e.selection.getClosestElement("blockquote"),shortcut:"mod+shift+9",meta:{icon:"blockquote",tooltip:"Blockquote"}}),e.commands.register("codeBlock",{execute(e,{language:t}={}){const n=e.selection.getClosestElement("pre");if(n){const t=n.textContent,o=document.createElement("p");o.textContent=t,n.parentNode.replaceChild(o,n);const r=document.createRange();r.selectNodeContents(o),r.collapse(!1),e.selection.setRange(r)}else{const n=e.selection.getRange();if(!n)return;const o=n.collapsed?"\n":n.toString(),r=document.createElement("pre"),s=document.createElement("code");if(s.textContent=o,t&&(s.setAttribute("data-language",t),r.setAttribute("data-language",t)),r.appendChild(s),n.collapsed||n.deleteContents(),n.insertNode(r),!r.nextSibling){const e=document.createElement("p");e.innerHTML="<br>",r.parentNode.insertBefore(e,r.nextSibling)}const i=document.createRange();i.selectNodeContents(s),i.collapse(!1),e.selection.setRange(i),e.eventBus.emit("codeblock:created",{element:r,language:t})}},isActive:e=>!!e.selection.getClosestElement("pre"),shortcut:"mod+shift+c",meta:{icon:"codeBlock",tooltip:"Code Block"}}),e.commands.register("horizontalRule",{execute(e){const t=e.selection.getRange();if(!t)return;const n=document.createElement("hr");if(t.deleteContents(),t.insertNode(n),!n.nextSibling||"P"!==n.nextSibling.tagName){const e=document.createElement("p");e.innerHTML="<br>",n.parentNode.insertBefore(e,n.nextSibling)}const o=document.createRange();o.setStartAfter(n),o.collapse(!0),e.selection.setRange(o)},meta:{icon:"horizontalRule",tooltip:"Horizontal Rule"}}),e.commands.register("moveBlockUp",{execute(e){const t=Bt(e);t&&t.previousElementSibling&&(e.history.snapshot(),t.parentNode.insertBefore(t,t.previousElementSibling),e.eventBus.emit("content:change"))},meta:{tooltip:"Move Block Up"}}),e.commands.register("moveBlockDown",{execute(e){const t=Bt(e);t&&t.nextElementSibling&&(e.history.snapshot(),t.parentNode.insertBefore(t,t.nextElementSibling.nextSibling),e.eventBus.emit("content:change"))},meta:{tooltip:"Move Block Down"}}),e.commands.register("duplicateBlock",{execute(e){const t=Bt(e);if(!t)return;e.history.snapshot();const n=t.cloneNode(!0);t.parentNode.insertBefore(n,t.nextSibling);const o=document.createRange();o.selectNodeContents(n),o.collapse(!1),e.selection.setRange(o),e.eventBus.emit("content:change")},meta:{tooltip:"Duplicate Block"}}),e.commands.register("deleteBlock",{execute(e){const t=Bt(e);if(!t)return;e.history.snapshot();const n=t.nextElementSibling,o=t.previousElementSibling;t.parentNode.removeChild(t),function(e){if(0===e.element.children.length){const t=document.createElement("p");t.innerHTML="<br>",e.element.appendChild(t);const n=document.createRange();n.selectNodeContents(t),n.collapse(!0),e.selection.setRange(n)}}(e);const r=n||o||e.element.firstElementChild;if(r){const t=document.createRange();t.selectNodeContents(r),t.collapse(!0),e.selection.setRange(t)}e.eventBus.emit("content:change")},meta:{tooltip:"Delete Block"}}),e.commands.register("selectBlocks",{execute(e,{blocks:t}={}){t&&Array.isArray(t)&&t.forEach((e=>{e&&e.classList&&e.classList.add("rmx-block-selected")}))},meta:{tooltip:"Select Blocks"}}),e.commands.register("clearBlockSelection",{execute(e){e.element.querySelectorAll(".rmx-block-selected").forEach((e=>e.classList.remove("rmx-block-selected")))},meta:{tooltip:"Clear Block Selection"}}),e.commands.register("toggleCollapse",{execute(e){const t=Bt(e);if(t){if(e.history.snapshot(),"DETAILS"===t.tagName){const e=t.parentNode,n=t.querySelector("summary");Array.from(t.childNodes).filter((e=>e!==n)).forEach((n=>e.insertBefore(n,t))),e.removeChild(t)}else{const e=document.createElement("details");e.className="rmx-collapsible",e.setAttribute("open","");const n=document.createElement("summary");n.textContent=t.textContent.slice(0,50)||"Section",t.parentNode.replaceChild(e,t),e.appendChild(n),e.appendChild(t)}e.eventBus.emit("content:change")}},meta:{tooltip:"Toggle Collapsible Section"}}),e.commands.register("groupBlocks",{execute(e){const t=Array.from(e.element.querySelectorAll(".rmx-block-selected"));if(0===t.length)return;e.history.snapshot();const n=document.createElement("div");n.className="rmx-block-group",t[0].parentNode.insertBefore(n,t[0]),t.forEach((e=>{e.classList.remove("rmx-block-selected"),n.appendChild(e)})),e.eventBus.emit("content:change")},meta:{tooltip:"Group Selected Blocks"}}),e.commands.register("ungroupBlocks",{execute(e){const t=Bt(e);if(!t)return;let n=t;if(n.classList.contains("rmx-block-group")||(n=t.closest(".rmx-block-group")),!n||!n.classList.contains("rmx-block-group"))return;e.history.snapshot();const o=n.parentNode;for(;n.firstChild;)o.insertBefore(n.firstChild,n);o.removeChild(n),e.eventBus.emit("content:change")},meta:{tooltip:"Ungroup Blocks"}}),e.commands.register("moveGroup",{execute(e,{direction:t}={}){const n=Bt(e);if(!n)return;let o=n.classList.contains("rmx-block-group")?n:n.closest(".rmx-block-group");if(o&&o.classList.contains("rmx-block-group")){for(;o.parentElement!==e.element;)if(o=o.parentElement,!o)return;e.history.snapshot(),"up"===t&&o.previousElementSibling?o.parentNode.insertBefore(o,o.previousElementSibling):"down"===t&&o.nextElementSibling&&o.parentNode.insertBefore(o,o.nextElementSibling.nextSibling),e.eventBus.emit("content:change")}},meta:{tooltip:"Move Group"}}),e.commands.register("duplicateGroup",{execute(e){const t=Bt(e);if(!t)return;let n=t.classList.contains("rmx-block-group")?t:t.closest(".rmx-block-group");if(!n||!n.classList.contains("rmx-block-group"))return;for(;n.parentElement!==e.element;)if(n=n.parentElement,!n)return;e.history.snapshot();const o=n.cloneNode(!0);n.parentNode.insertBefore(o,n.nextSibling),e.eventBus.emit("content:change")},meta:{tooltip:"Duplicate Group"}})}const Rt={paragraph:{tag:"P"},heading1:{tag:"H1"},heading2:{tag:"H2"},heading3:{tag:"H3"},heading4:{tag:"H4"},heading5:{tag:"H5"},heading6:{tag:"H6"},blockquote:{tag:"BLOCKQUOTE"},codeBlock:{tag:"PRE"},unorderedList:{tag:"UL"},orderedList:{tag:"OL"}};function Mt(e){e.commands.register("convertBlock",{execute(e,{to:t}={}){if(!t||!Rt[t])return;const n=function(e){const t=e.selection.getParentBlock();if(!t)return null;let n=t;for(;n&&n.parentElement!==e.element;)n=n.parentElement;return n||null}(e);if(!n)return;const o=Rt[t].tag;if(n.tagName===o)return;e.history.snapshot();const r=function(e){const t=e.tagName;if("UL"===t||"OL"===t){const t=Array.from(e.querySelectorAll("li"));return 1===t.length?t[0].innerHTML:t.map((e=>e.innerHTML)).join("<br>")}if("PRE"===t){const t=e.querySelector("code");return t?t.textContent:e.textContent}return"BLOCKQUOTE"===t&&1===e.children.length?e.children[0].innerHTML:e.innerHTML}(n),s=function(e,t){const n=Rt[e];if(!n)return null;if("unorderedList"===e||"orderedList"===e){const e=document.createElement(n.tag),o=document.createElement("li");return o.innerHTML=t||"<br>",e.appendChild(o),e}if("codeBlock"===e){const e=document.createElement("pre"),n=document.createElement("code"),o=document.createElement("div");return o.innerHTML=t,n.textContent=o.textContent||"\n",e.appendChild(n),e}if("blockquote"===e){const e=document.createElement("blockquote"),n=document.createElement("p");return n.innerHTML=t||"<br>",e.appendChild(n),e}const o=document.createElement(n.tag);return o.innerHTML=t||"<br>",o}(t,r);if(!s)return;n.parentNode.replaceChild(s,n);const i=document.createRange();let a=s;"unorderedList"===t||"orderedList"===t?a=s.querySelector("li")||s:"codeBlock"===t?a=s.querySelector("code")||s:"blockquote"===t&&(a=s.querySelector("p")||s),i.selectNodeContents(a),i.collapse(!1),e.selection.setRange(i),e.eventBus.emit("content:change")},meta:{tooltip:"Convert Block Type"}})}function Dt(e,t,n){if(!n)return;const o=e.selection.getSelection();if(!o||0===o.rangeCount)return;const r=o.getRangeAt(0);if(r.collapsed)return;const s=e.selection.getParentElement();if(s&&"SPAN"===s.tagName&&s.style[t])return void(s.style[t]=n);const i=document.createElement("span");i.style[t]=n;try{r.surroundContents(i)}catch{const e=r.extractContents();i.appendChild(e),r.insertNode(i)}}function Ht(e,t){const n=e.selection.getParentElement();if(!n)return!1;try{return window.getComputedStyle(n)[t]||!1}catch{return!1}}function Ft(e){e.commands.register("fontFamily",{execute(e,t){Dt(e,"fontFamily",t)},isActive:e=>Ht(e,"fontFamily"),meta:{icon:"fontFamily",tooltip:"Font Family"}}),e.commands.register("fontSize",{execute(e,t){t&&/^\d+(\.\d+)?(px|pt|em|rem|%)$/.test(t)&&Dt(e,"fontSize",t)},meta:{icon:"fontSize",tooltip:"Font Size"}}),e.commands.register("foreColor",{execute(e,t){Dt(e,"color",t)},isActive:e=>Ht(e,"color"),meta:{icon:"foreColor",tooltip:"Text Color"}}),e.commands.register("backColor",{execute(e,t){Dt(e,"backgroundColor",t)},isActive:e=>Ht(e,"backgroundColor"),meta:{icon:"backColor",tooltip:"Background Color"}}),e.commands.register("lineHeight",{execute(e,t){t&&Dt(e,"lineHeight",t)},isActive:e=>Ht(e,"lineHeight"),meta:{icon:"lineHeight",tooltip:"Line Height"}}),e.commands.register("letterSpacing",{execute(e,t){t&&Dt(e,"letterSpacing",t)},isActive:e=>Ht(e,"letterSpacing"),meta:{icon:"letterSpacing",tooltip:"Letter Spacing"}}),e.commands.register("paragraphSpacing",{execute(e,t){if(!t)return;const n=e.selection.getParentElement();if(!n)return;const o=n.closest("p, h1, h2, h3, h4, h5, h6, li, blockquote, pre, div");o&&(o.style.marginBottom=t)},isActive(e){const t=e.selection.getParentElement();if(!t)return!1;const n=t.closest("p, h1, h2, h3, h4, h5, h6, li, blockquote, pre, div");return n&&n.style.marginBottom||!1},meta:{icon:"paragraphSpacing",tooltip:"Paragraph Spacing"}})}function Pt(e){e.commands.register("embedMedia",{execute(e,{url:t}){if(!t)return;const n=function(e){let t=e.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(t)return`https://www.youtube.com/embed/${t[1]}`;if(t=e.match(/(?:vimeo\.com\/)(\d+)/),t)return`https://player.vimeo.com/video/${t[1]}`;if(t=e.match(/dailymotion\.com\/video\/([a-zA-Z0-9]+)/),t)return`https://www.dailymotion.com/embed/video/${t[1]}`;return null}(t);if(!n)return;const o=document.createElement("div");o.className="rmx-embed-wrapper",o.setAttribute("contenteditable","false"),o.setAttribute("data-embed-url",t);const r=document.createElement("iframe");r.src=n,r.setAttribute("frameborder","0"),r.setAttribute("allowfullscreen","true"),r.setAttribute("sandbox","allow-scripts allow-same-origin allow-presentation allow-popups"),r.setAttribute("allow","autoplay; picture-in-picture"),r.style.width="100%",r.style.height="100%",o.appendChild(r),e.selection.insertNode(o);const s=document.createElement("p");s.innerHTML="<br>",o.parentNode.insertBefore(s,o.nextSibling)},meta:{icon:"embedMedia",tooltip:"Embed Media"}}),e.commands.register("removeEmbed",{execute(e,{element:t}){if(!t)return;const n=t.closest(".rmx-embed-wrapper")||t,o=document.createElement("p");o.innerHTML="<br>",n.parentNode.replaceChild(o,n)},meta:{tooltip:"Remove Embed"}})}function zt(e){let t=[],n=-1;function o(e){e.querySelectorAll("mark.rmx-find-highlight").forEach((e=>{const t=e.parentNode;t.replaceChild(document.createTextNode(e.textContent),e),t.normalize()}))}function r(){t=t.filter((e=>e.isConnected)),n>=t.length&&(n=t.length>0?t.length-1:-1)}function s(){r(),t.forEach(((e,t)=>{e.className=t===n?"rmx-find-highlight rmx-find-current":"rmx-find-highlight"})),t[n]&&t[n].scrollIntoView({block:"center",behavior:"smooth"})}e.commands.register("find",{execute:(e,{text:r,caseSensitive:i})=>(t=function(e,t,n=!1){if(o(e),!t)return[];const r=[],s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null),i=[];for(;s.nextNode();)i.push(s.currentNode);const a=n?"g":"gi",l=new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),a);for(let o=i.length-1;o>=0;o--){const e=i[o],t=e.textContent,n=[];let s;for(;null!==(s=l.exec(t));)n.push({index:s.index,length:s[0].length});for(let o=n.length-1;o>=0;o--){const t=n[o],s=document.createRange();s.setStart(e,t.index),s.setEnd(e,t.index+t.length);const i=document.createElement("mark");i.className="rmx-find-highlight",s.surroundContents(i),r.push(i)}}return r.reverse(),r}(e.element,r,i),n=t.length>0?0:-1,n>=0&&s(),e.eventBus.emit("find:results",{total:t.length,current:n+1}),{total:t.length,current:n+1}),shortcut:"mod+f",meta:{icon:"findReplace",tooltip:"Find & Replace"}}),e.commands.register("findNext",{execute(e){0!==t.length&&(n=(n+1)%t.length,s(),e.eventBus.emit("find:results",{total:t.length,current:n+1}))},meta:{tooltip:"Find Next"}}),e.commands.register("findPrev",{execute(e){0!==t.length&&(n=(n-1+t.length)%t.length,s(),e.eventBus.emit("find:results",{total:t.length,current:n+1}))},meta:{tooltip:"Find Previous"}}),e.commands.register("replace",{execute(e,{replaceText:o}){if(r(),0===t.length||n<0||n>=t.length)return;const i=t[n],a=document.createTextNode(o);i.parentNode.replaceChild(a,i),t.splice(n,1),t.length>0?(n=Math.min(n,t.length-1),s()):n=-1,e.eventBus.emit("find:results",{total:t.length,current:n+1}),e.eventBus.emit("content:change")},meta:{tooltip:"Replace"}}),e.commands.register("replaceAll",{execute(e,{replaceText:o}){r(),t.forEach((e=>{const t=document.createTextNode(o);e.parentNode.replaceChild(t,e)}));const s=t.length;return t=[],n=-1,e.eventBus.emit("find:results",{total:0,current:0}),e.eventBus.emit("content:change"),s},meta:{tooltip:"Replace All"}}),e.commands.register("clearFind",{execute(e){o(e.element),t=[],n=-1},meta:{tooltip:"Clear Find"}})}function Ot(e){e.commands.register("sourceMode",{execute(e){e.isSourceMode=!e.isSourceMode,e.eventBus.emit("mode:change",{sourceMode:e.isSourceMode})},isActive:e=>e.isSourceMode,shortcut:"mod+shift+u",meta:{icon:"sourceMode",tooltip:"Source Code"}})}let Gt=0;function qt(e){e.commands.register("fullscreen",{execute(e){const t=e.element.closest(".rmx-editor");if(!t)return;const n=t.classList.contains("rmx-fullscreen");n?(t.classList.remove("rmx-fullscreen"),Gt=Math.max(0,Gt-1),0===Gt&&(document.body.style.overflow="")):(t.classList.add("rmx-fullscreen"),Gt++,document.body.style.overflow="hidden"),e.eventBus.emit("fullscreen:toggle",{fullscreen:!n})},isActive(e){const t=e.element.closest(".rmx-editor");return!!t&&t.classList.contains("rmx-fullscreen")},shortcut:"mod+shift+f",meta:{icon:"fullscreen",tooltip:"Fullscreen"}})}let Wt=null;function $t(e){e.commands.register("distractionFree",{execute(e){const t=e.element.closest(".rmx-editor");if(!t)return;const n=t.classList.contains("rmx-distraction-free");n?(t.classList.remove("rmx-distraction-free"),t.classList.remove("rmx-df-show-chrome"),t.removeEventListener("mousemove",Zt),clearTimeout(Wt)):(t.classList.add("rmx-distraction-free"),t.addEventListener("mousemove",Zt)),e.eventBus.emit("distractionFree:toggle",{active:!n})},isActive(e){const t=e.element.closest(".rmx-editor");return!!t&&t.classList.contains("rmx-distraction-free")},shortcut:"mod+shift+d",meta:{icon:"distractionFree",tooltip:"Distraction-Free Mode"}})}function Zt(e){const t=e.currentTarget;t.classList.contains("rmx-distraction-free")&&(t.classList.add("rmx-df-show-chrome"),clearTimeout(Wt),Wt=setTimeout((()=>{t.classList.remove("rmx-df-show-chrome")}),3e3))}function Ut(e){e.commands.register("toggleSplitView",{execute(e){const t=e.element.closest(".rmx-editor");if(!t)return;const n=t.classList.contains("rmx-split-view");n?t.classList.remove("rmx-split-view"):t.classList.add("rmx-split-view"),e.eventBus.emit("splitView:toggle",{active:!n})},isActive(e){const t=e.element.closest(".rmx-editor");return!!t&&t.classList.contains("rmx-split-view")},shortcut:"mod+shift+v",meta:{icon:"splitView",tooltip:"Split View"}})}const Vt="rmx-color-presets";function jt(){try{const e=localStorage.getItem(Vt);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Kt(e,t){if(e&&Array.isArray(t))try{const n=jt().filter((t=>t.name!==e));n.push({name:e,colors:t}),localStorage.setItem(Vt,JSON.stringify(n))}catch{}}function Xt(e){try{const t=jt().filter((t=>t.name!==e));localStorage.setItem(Vt,JSON.stringify(t))}catch{}}function Jt(e){e.commands.register("saveColorPreset",{execute(t,n,o){Kt(n,o),e.eventBus.emit("colorPresets:change",{presets:jt()})},meta:{icon:"colorPreset",tooltip:"Save Color Preset"}}),e.commands.register("loadColorPresets",{execute:()=>jt(),meta:{icon:"colorPreset",tooltip:"Load Color Presets"}}),e.commands.register("deleteColorPreset",{execute(t,n){Xt(n),e.eventBus.emit("colorPresets:change",{presets:jt()})},meta:{icon:"colorPreset",tooltip:"Delete Color Preset"}})}function Yt(e){e.commands.register("toggleMarkdown",{execute(e){if(e.history.snapshot(),e.isMarkdownMode){const t=Se(e.element.textContent);e.setHTML(t),e.isMarkdownMode=!1}else{const t=_e(e.getHTML());e.element.textContent=t,e.isMarkdownMode=!0}e.element.classList.toggle("rmx-markdown-mode",e.isMarkdownMode),e.eventBus.emit("mode:change:markdown",{markdownMode:e.isMarkdownMode}),e.eventBus.emit("content:change")},isActive:e=>e.isMarkdownMode,meta:{icon:"toggleMarkdown",tooltip:"Toggle Markdown"}})}const Qt=/^\s*(javascript|vbscript|data\s*:\s*text\/html)\s*:/i;function en(e){e.commands.register("insertAttachment",{execute(e,{url:t,filename:n="file",filesize:o}){if(!t)return;if(e.element.focus(),!e.selection.getRange()){const t=document.createRange();t.selectNodeContents(e.element),t.collapse(!1),e.selection.setRange(t)}const r=document.createElement("a");r.href=Qt.test(t)?"#":t,r.className="rmx-attachment",r.setAttribute("data-attachment","true"),r.setAttribute("data-filename",n),o&&r.setAttribute("data-filesize",String(o)),r.target="_blank",r.rel="noopener noreferrer";const s=o?` (${function(e){if(!e||0===e)return"";const t=["B","KB","MB","GB"];let n=e,o=0;for(;n>=1024&&o<t.length-1;)n/=1024,o++;return`${n%1==0?n:n.toFixed(1)} ${t[o]}`}(o)})`:"";if(r.textContent=`📎 ${n}${s}`,e.selection.insertNode(r),!r.nextSibling||r.parentElement===e.element){const e=document.createElement("p");e.innerHTML="<br>",r.parentElement.insertBefore(e,r.nextSibling)}},meta:{icon:"attachment",tooltip:"Insert Attachment"}}),e.commands.register("removeAttachment",{execute(e,{element:t}){t&&t.classList?.contains("rmx-attachment")&&t.parentNode.removeChild(t)},meta:{tooltip:"Remove Attachment"}})}function tn(e){e.commands.register("importDocument",{execute(e,{html:t,mode:n="insert"}){if(t){if(e.element.focus(),"replace"===n)e.setHTML(t);else{if(!e.selection.getRange()){const t=document.createRange();t.selectNodeContents(e.element),t.collapse(!1),e.selection.setRange(t)}e.selection.insertHTML(e.sanitizer.sanitize(t))}e.eventBus.emit("content:change")}},meta:{icon:"importDocument",tooltip:"Import Document"}})}const nn="rmx-recent-commands";function on(){try{const e=localStorage.getItem(nn);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.slice(0,5):[]}catch{return[]}}function rn(e){try{const t=on().filter((t=>t!==e));t.unshift(e),localStorage.setItem(nn,JSON.stringify(t.slice(0,5)))}catch{}}function sn(){try{localStorage.removeItem(nn)}catch{}}const an=[];function ln(e){const t=Array.isArray(e)?e:[e];for(const n of t){const e=an.findIndex((e=>e.id===n.id));e>=0?an[e]=n:an.push(n)}}function cn(e){const t=an.findIndex((t=>t.id===e));return t>=0&&(an.splice(t,1),!0)}function dn(){return[...an]}const un=[{id:"heading1",label:"Heading 1",description:"Large section heading",icon:"H1",keywords:["h1","title","heading","large"],category:"Text",action:e=>e.executeCommand("heading",1)},{id:"heading2",label:"Heading 2",description:"Medium section heading",icon:"H2",keywords:["h2","subtitle","heading","medium"],category:"Text",action:e=>e.executeCommand("heading",2)},{id:"heading3",label:"Heading 3",description:"Small section heading",icon:"H3",keywords:["h3","heading","small"],category:"Text",action:e=>e.executeCommand("heading",3)},{id:"paragraph",label:"Paragraph",description:"Plain text block",icon:"¶",keywords:["text","normal","body","plain"],category:"Text",action:e=>e.executeCommand("heading","p")},{id:"blockquote",label:"Blockquote",description:"Indented quote block",icon:"“",keywords:["quote","citation","indent"],category:"Text",action:e=>e.executeCommand("blockquote")},{id:"codeBlock",label:"Code Block",description:"Monospace code snippet",icon:"<>",keywords:["code","pre","monospace","snippet","programming"],category:"Text",action:e=>e.executeCommand("codeBlock")},{id:"unorderedList",label:"Bulleted List",description:"Unordered bullet list",icon:"•",keywords:["bullet","ul","list","unordered"],category:"Lists",action:e=>e.executeCommand("unorderedList")},{id:"orderedList",label:"Numbered List",description:"Ordered numbered list",icon:"1.",keywords:["number","ol","list","ordered"],category:"Lists",action:e=>e.executeCommand("orderedList")},{id:"taskList",label:"Task List",description:"Checklist with toggleable items",icon:"☑",keywords:["todo","checkbox","checklist","task"],category:"Lists",action:e=>e.executeCommand("taskList")},{id:"image",label:"Image",description:"Insert an image",icon:"🖼",keywords:["img","photo","picture","upload"],category:"Media",action:(e,t)=>t?.("image")},{id:"attachment",label:"Attachment",description:"Attach a file",icon:"📎",keywords:["file","attach","upload","document"],category:"Media",action:(e,t)=>t?.("attachment")},{id:"embedMedia",label:"Embed Media",description:"Embed a YouTube or Vimeo video",icon:"▶",keywords:["video","youtube","vimeo","embed","media"],category:"Media",action:(e,t)=>t?.("embed")},{id:"horizontalRule",label:"Horizontal Rule",description:"Visual divider line",icon:"―",keywords:["hr","divider","line","separator","rule"],category:"Layout",action:e=>e.executeCommand("horizontalRule")},{id:"table",label:"Table",description:"Insert a data table",icon:"☷",keywords:["table","grid","spreadsheet","cells"],category:"Layout",action:(e,t)=>t?.("table")},{id:"insertCallout",label:"Callout",description:"Insert a styled callout block",icon:"ℹ️",keywords:["callout","alert","admonition","info","warning","tip","note"],category:"Insert",action:e=>e.commands.has("insertCallout")&&e.executeCommand("insertCallout")},{id:"insertMath",label:"Math Equation",description:"Insert a LaTeX math expression",icon:"𝑓",keywords:["math","equation","latex","formula","katex"],category:"Insert",action:e=>e.commands.has("insertMath")&&e.executeCommand("insertMath",{latex:"",displayMode:!0})},{id:"insertToc",label:"Table of Contents",description:"Insert an auto-generated table of contents",icon:"📜",keywords:["toc","contents","outline","navigation","index"],category:"Insert",action:e=>e.commands.has("insertToc")&&e.executeCommand("insertToc")},{id:"insertBookmark",label:"Bookmark",description:"Insert a bookmark anchor for linking",icon:"🔖",keywords:["bookmark","anchor","link","target","reference"],category:"Insert",action:e=>e.commands.has("insertBookmark")&&e.executeCommand("insertBookmark",{name:"bookmark"})},{id:"insertMergeTag",label:"Merge Tag",description:"Insert a template merge tag",icon:"🏷️",keywords:["merge","tag","template","variable","placeholder","dynamic"],category:"Insert",action:e=>e.commands.has("insertMergeTag")&&e.executeCommand("insertMergeTag",{tag:"name"})},{id:"addComment",label:"Comment",description:"Add a comment to the selected text",icon:"💬",keywords:["comment","annotate","annotation","note","review","feedback"],category:"Insert",action:e=>e.commands.has("addComment")&&e.executeCommand("addComment")},{id:"findReplace",label:"Find & Replace",description:"Search and replace text",icon:"🔍",keywords:["find","search","replace"],category:"Advanced",action:(e,t)=>t?.("findReplace")},{id:"sourceMode",label:"Source Code",description:"View and edit raw HTML",icon:"</>",keywords:["html","source","code","raw"],category:"Advanced",action:e=>e.executeCommand("sourceMode")},{id:"export",label:"Export",description:"Export as PDF, DOCX, or Markdown",icon:"📤",keywords:["export","download","pdf","docx","save"],category:"Advanced",action:(e,t)=>t?.("export")},{id:"importDocument",label:"Import Document",description:"Import from file",icon:"📥",keywords:["import","upload","open","file"],category:"Advanced",action:(e,t)=>t?.("importDocument")},{id:"toggleAnalytics",label:"Toggle Analytics",description:"Show or hide content analytics panel",icon:"📊",keywords:["analytics","readability","stats","word count","reading time"],category:"Advanced",action:e=>e.commands.has("toggleAnalytics")&&e.executeCommand("toggleAnalytics")},{id:"toggleSpellcheck",label:"Toggle Spellcheck",description:"Enable or disable spelling and grammar checking",icon:"✓",keywords:["spellcheck","spelling","grammar","proofread","writing"],category:"Advanced",action:e=>e.commands.has("toggleSpellcheck")&&e.executeCommand("toggleSpellcheck")},{id:"checkGrammar",label:"Check Grammar",description:"Run grammar and style analysis on content",icon:"Aa",keywords:["grammar","check","proofread","style","writing","passive"],category:"Advanced",action:e=>e.commands.has("checkGrammar")&&e.executeCommand("checkGrammar")},{id:"startCollaboration",label:"Start Collaboration",description:"Connect to collaboration server and start co-editing",icon:"👥",keywords:["collaborate","realtime","share","multiplayer","co-edit"],category:"Advanced",action:e=>e.commands.has("startCollaboration")&&e.executeCommand("startCollaboration")},{id:"stopCollaboration",label:"Stop Collaboration",description:"Disconnect from collaboration session",icon:"🚫",keywords:["disconnect","leave","stop","collaboration"],category:"Advanced",action:e=>e.commands.has("stopCollaboration")&&e.executeCommand("stopCollaboration")},{id:"toggleMarkdown",label:"Toggle Markdown",description:"Switch between WYSIWYG and Markdown editing",icon:"M↓",keywords:["markdown","toggle","wysiwyg","mode"],category:"Advanced",action:e=>e.executeCommand("toggleMarkdown")},{id:"fullscreen",label:"Fullscreen",description:"Enter distraction-free fullscreen mode",icon:"⛶",keywords:["fullscreen","expand","zen","focus","distraction"],category:"Advanced",action:e=>e.executeCommand("fullscreen")},{id:"removeFormat",label:"Clear Formatting",description:"Remove all formatting from selection",icon:"🚫",keywords:["clear","remove","format","plain","reset"],category:"Advanced",action:e=>e.executeCommand("removeFormat")},{id:"distractionFree",label:"Distraction-Free",description:"Hide toolbar and status bar, show on mouse move",icon:"🧘",keywords:["distraction","zen","focus","minimal","clean"],category:"Advanced",action:e=>e.executeCommand("distractionFree")},{id:"toggleSplitView",label:"Split View",description:"Side-by-side edit and preview pane",icon:"◫",keywords:["split","preview","side","dual","pane"],category:"Advanced",action:e=>e.executeCommand("toggleSplitView")}];function mn(e,t,n={}){const{pinRecent:o=!0}=n;if(!t){if(!o)return e;const t=on();if(0===t.length)return e;const n=[];for(const o of t){const t=e.find((e=>e.id===o));t&&n.push({...t,category:"Recent"})}return 0===n.length?e:[...n,...e]}const r=t.toLowerCase(),s=[],i=[];for(const a of e)a.label.toLowerCase().includes(r)?s.push(a):(a.description.toLowerCase().includes(r)||a.keywords.some((e=>e.includes(r))))&&i.push(a);return[...s,...i]}function hn(e){try{const t=new URL(e);if("https:"!==t.protocol&&"http:"!==t.protocol)throw new Error("URL must use http or https protocol");return e}catch(t){throw new Error(`Invalid URL from callback: ${t.message}`)}}function gn(e,t={}){return JSON.stringify({content:e,timestamp:Date.now(),version:1,...t})}function pn(e){if(!e)return null;try{const t=JSON.parse(e);return t&&"string"==typeof t.content?t:null}catch{return null}}class fn{constructor({prefix:e="rmx-autosave"}={}){this.prefix=e}_key(e){return`${this.prefix}:${e}`}async save(e,t,n){try{localStorage.setItem(this._key(e),gn(t,n))}catch(o){throw new Error(`LocalStorage save failed: ${o.message}`)}}async load(e){try{return pn(localStorage.getItem(this._key(e)))}catch{return null}}async clear(e){try{localStorage.removeItem(this._key(e))}catch{}}saveSync(e,t,n){try{return localStorage.setItem(this._key(e),gn(t,n)),!0}catch{return!1}}}class bn{constructor({prefix:e="rmx-autosave"}={}){this.prefix=e}_key(e){return`${this.prefix}:${e}`}async save(e,t,n){try{sessionStorage.setItem(this._key(e),gn(t,n))}catch(o){throw new Error(`SessionStorage save failed: ${o.message}`)}}async load(e){try{return pn(sessionStorage.getItem(this._key(e)))}catch{return null}}async clear(e){try{sessionStorage.removeItem(this._key(e))}catch{}}saveSync(e,t,n){try{return sessionStorage.setItem(this._key(e),gn(t,n)),!0}catch{return!1}}}class yn{constructor({writeFn:e,readFn:t,deleteFn:n}){if("function"!=typeof e)throw new Error("FileSystemProvider requires a writeFn");if("function"!=typeof t)throw new Error("FileSystemProvider requires a readFn");if("function"!=typeof n)throw new Error("FileSystemProvider requires a deleteFn");this.writeFn=e,this.readFn=t,this.deleteFn=n}async save(e,t,n){const o=gn(t,n);await this.writeFn(e,o)}async load(e){return pn(await this.readFn(e))}async clear(e){await this.deleteFn(e)}}class vn{constructor({endpoint:e,headers:t={},method:n="PUT",fetchFn:o,buildUrl:r,buildBody:s,buildLoadUrl:i,buildDeleteUrl:a}){if(!e&&!r)throw new Error("CloudProvider requires an endpoint or buildUrl");if(e)try{const t=new URL(e);if("https:"!==t.protocol&&"http:"!==t.protocol)throw new Error("CloudProvider endpoint must use http or https protocol")}catch(l){if(l.message.includes("protocol"))throw l;throw new Error(`CloudProvider endpoint is not a valid URL: ${e}`)}if(this.endpoint=e,this.headers=t,this.method=n,this._fetch=o||("undefined"!=typeof fetch?fetch.bind(globalThis):null),this.buildUrl=r,this.buildBody=s,this.buildLoadUrl=i||r,this.buildDeleteUrl=a||r,!this._fetch)throw new Error("CloudProvider requires fetch or a custom fetchFn")}_saveUrl(e){return this.buildUrl?hn(this.buildUrl(e)):this.endpoint}_loadUrl(e){if(this.buildLoadUrl)return hn(this.buildLoadUrl(e));const t=this.endpoint.includes("?")?"&":"?";return`${this.endpoint}${t}key=${encodeURIComponent(e)}`}_deleteUrl(e){return this.buildDeleteUrl?hn(this.buildDeleteUrl(e)):this._loadUrl(e)}async _fetchWithRetry(e,t,n=1){try{const n=await this._fetch(e,t);if(!n.ok)throw new Error(`HTTP ${n.status}: ${n.statusText}`);return n}catch(o){if(n>0)return await new Promise((e=>setTimeout(e,1e3))),this._fetchWithRetry(e,t,n-1);throw o}}async save(e,t,n){const o=this.buildBody?this.buildBody(e,t):gn(t,n),r={...this.headers};this.buildBody||r["Content-Type"]||(r["Content-Type"]="application/json"),await this._fetchWithRetry(this._saveUrl(e),{method:this.method,headers:r,body:o})}async load(e){try{const t=await this._fetch(this._loadUrl(e),{method:"GET",headers:this.headers});if(!t.ok){if(404===t.status)return null;throw new Error(`HTTP ${t.status}`)}return pn(await t.text())}catch{return null}}async clear(e){try{await this._fetch(this._deleteUrl(e),{method:"DELETE",headers:this.headers})}catch{}}}class xn{constructor({save:e,load:t,clear:n}){if("function"!=typeof e)throw new Error("CustomProvider requires a save function");if("function"!=typeof t)throw new Error("CustomProvider requires a load function");if("function"!=typeof n)throw new Error("CustomProvider requires a clear function");this._save=e,this._load=t,this._clear=n}async save(e,t,n){await this._save(e,t,n)}async load(e){return this._load(e)}async clear(e){await this._clear(e)}}function Cn(e){if(!e||"localStorage"===e)return new fn;if("sessionStorage"===e)return new bn;if("object"!=typeof e)throw new Error(`Unknown storage provider: ${e}`);if("function"==typeof e.save&&"function"==typeof e.load&&"function"==typeof e.clear)return e.constructor===Object?new xn(e):e;if(e.endpoint||e.buildUrl)return new vn(e);if(e.writeFn)return new yn(e);if(e.prefix)return new fn(e);throw new Error("Unable to resolve storage provider from config")}const wn=/* @__PURE__ */new Map;class kn{constructor(e,t={}){this.engine=e,this.provider=Cn(t.provider),this.key=t.key||"rmx-default";const n=wn.get(this.key);n&&n.destroy(),wn.set(this.key,this),this.interval=t.interval??3e4,this.debounceMs=t.debounce??2e3,this.enabled=!1!==t.enabled,this._debounceTimer=null,this._intervalTimer=null,this._isSaving=!1,this._pendingSave=!1,this._lastSavedContent=null,this._contentChangeHandler=null,this._beforeUnloadHandler=null,this._destroyed=!1,this._consecutiveErrors=0,this._maxRetries=t.maxRetries??5}init(){this.enabled&&!this._destroyed&&(this._contentChangeHandler=()=>{this._scheduleDebouncedSave()},this._unsubContentChange=this.engine.eventBus.on("content:change",this._contentChangeHandler),this.interval>0&&(this._intervalTimer=setInterval((()=>{this.save()}),this.interval)),"undefined"!=typeof window&&(this._beforeUnloadHandler=()=>{this._attemptSyncSave()},window.addEventListener("beforeunload",this._beforeUnloadHandler)))}destroy(){this._debounceTimer&&(clearTimeout(this._debounceTimer),this._debounceTimer=null),this._intervalTimer&&(clearInterval(this._intervalTimer),this._intervalTimer=null),this._unsubContentChange&&(this._unsubContentChange(),this._unsubContentChange=null),this._beforeUnloadHandler&&"undefined"!=typeof window&&(window.removeEventListener("beforeunload",this._beforeUnloadHandler),this._beforeUnloadHandler=null),wn.get(this.key)===this&&wn.delete(this.key),this.save().catch((()=>{})).finally((()=>{this._destroyed=!0}))}async save(){if(!this.engine||this._destroyed)return;const e=this.engine.getHTML();if(e!==this._lastSavedContent)if(this._isSaving)this._pendingSave=!0;else{this._isSaving=!0,this.engine.eventBus.emit("autosave:saving");try{await this.provider.save(this.key,e),this._lastSavedContent=e,this._consecutiveErrors=0;const t=Date.now();this.engine.eventBus.emit("autosave:saved",{timestamp:t})}catch(t){this._consecutiveErrors++,this.engine.eventBus.emit("autosave:error",{error:t,retryCount:this._consecutiveErrors})}finally{if(this._isSaving=!1,this._pendingSave)if(this._pendingSave=!1,this._consecutiveErrors>=this._maxRetries)this.engine.eventBus.emit("autosave:error",{error:new Error(`Autosave failed after ${this._maxRetries} consecutive attempts`),fatal:!0});else if(this._consecutiveErrors>0){const e=Math.min(1e3*Math.pow(2,this._consecutiveErrors-1),3e4);setTimeout((()=>this.save()),e)}else this.save()}}}async checkRecovery(e){try{const t=await this.provider.load(this.key);if(!t||!t.content)return null;const n=t.content.trim(),o=(e||"").trim();return n&&n!==o?{recoveredContent:t.content,timestamp:t.timestamp||Date.now()}:null}catch{return null}}async clearRecovery(){try{await this.provider.clear(this.key)}catch{}}_scheduleDebouncedSave(){this._debounceTimer&&clearTimeout(this._debounceTimer),this._debounceTimer=setTimeout((()=>{this._debounceTimer=null,this.save()}),this.debounceMs)}_attemptSyncSave(){if(!this.engine||this._destroyed)return;const e=this.engine.getHTML();if(e!==this._lastSavedContent)if("function"!=typeof this.provider.saveSync){if("undefined"!=typeof navigator&&navigator.sendBeacon&&this.provider.endpoint)try{const t=JSON.stringify({key:this.key,content:e,timestamp:Date.now(),version:1});navigator.sendBeacon(this.provider.endpoint,t)}catch{}}else this.provider.saveSync(this.key,e)}}function _n(e){return{name:e.name,version:e.version||"0.0.0",description:e.description||"",author:e.author||"",dependencies:e.dependencies||[],requiresFullAccess:e.requiresFullAccess||!1,lazy:e.lazy||!1,init:e.init||(()=>{}),destroy:e.destroy||(()=>{}),onContentChange:e.onContentChange||null,onSelectionChange:e.onSelectionChange||null,commands:e.commands||[],toolbarItems:e.toolbarItems||[],statusBarItems:e.statusBarItems||[],contextMenuItems:e.contextMenuItems||[],settingsSchema:e.settingsSchema||[],defaultSettings:e.defaultSettings||{}}}function Sn(){let e=null,t=null;return _n({name:"wordCount",requiresFullAccess:!0,init(n){const o=()=>{const e=n.getText().trim(),t={wordCount:e?e.split(/\s+/).length:0,charCount:n.getText().length};n._wordCount=t,n.eventBus.emit("wordcount:update",t)};t=n.eventBus.on("content:change",(()=>{clearTimeout(e),e=setTimeout(o,100)})),o()},destroy(){clearTimeout(e),t&&(t(),t=null)}})}const An=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,WordCountPlugin:Sn},Symbol.toStringTag,{value:"Module"})),En=new RegExp("(?:https?:\\/\\/[^\\s<]{1,2000}[^\\s<.,:;\"')\\]!?])|(?:www\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,62}[a-zA-Z0-9])?(?:\\.[a-zA-Z]{2,20})+(?:\\/[^\\s<]{0,2000}[^\\s<.,:;\"')\\]!?])?)|(?:(?<![a-zA-Z0-9@/:.])(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,62}[a-zA-Z0-9])?\\.){1,10}[a-zA-Z]{2,20}(?:\\/[^\\s<]{0,2000}[^\\s<.,:;\"')\\]!?])?)","g"),Ln=/https?:\/\/$/,Tn=/https?:\/\/[^\s]*$/,In=/* @__PURE__ */new Set(["com","org","net","edu","gov","mil","int","io","co","us","uk","ca","au","de","fr","es","it","nl","be","at","ch","jp","cn","kr","in","br","mx","ru","za","nz","se","no","fi","dk","pl","dev","app","ai","me","tv","cc","info","biz","pro","name","museum","xyz","online","site","tech","store","blog","cloud","design","agency"]);function Bn(e){const t=e.split("/")[0].split(".");return t[t.length-1].toLowerCase()}function Nn(){let e=null;return _n({name:"autolink",requiresFullAccess:!0,init(t){e=e=>{if(" "!==e.key&&"Enter"!==e.key)return;const t=window.getSelection();if(!t||!t.focusNode)return;const n=t.focusNode;if(n.nodeType!==Node.TEXT_NODE)return;if(n.parentElement.closest("a"))return;const o=function(e){if(!e||e.length>4096)return null;const t=Math.max(0,e.length-200);t>0&&(e=e.slice(t));let n=null;for(const o of e.matchAll(En)){const t=o[0],r=t.startsWith("http://")||t.startsWith("https://"),s=!r&&t.startsWith("www."),i=!r&&!s;let a=null;if(r)a={url:t,href:t,startIdx:o.index,endIdx:o.index+t.length};else if(s){const n=e.slice(Math.max(0,o.index-8),o.index);if(Ln.test(n))continue;a={url:t,href:"https://"+t,startIdx:o.index,endIdx:o.index+t.length}}else if(i){const n=Bn(t);if(!In.has(n))continue;const r=e.slice(Math.max(0,o.index-12),o.index);if(Tn.test(r)||/www\.$/.test(r))continue;a={url:t,href:"https://"+t,startIdx:o.index,endIdx:o.index+t.length}}a&&(!n||a.startIdx>=n.startIdx)&&(n=a)}n&&t>0&&(n.startIdx+=t,n.endIdx+=t);return n}(n.textContent);if(!o)return;const{href:r,startIdx:s,endIdx:i}=o;if(i>t.focusOffset)return;const a=document.createRange();a.setStart(n,s),a.setEnd(n,i);const l=document.createElement("a");l.href=r,l.target="_blank",l.rel="noopener noreferrer",a.surroundContents(l);const c=document.createRange();c.setStartAfter(l),c.collapse(!0),t.removeAllRanges(),t.addRange(c)},t.element.addEventListener("keydown",e)},destroy(t){e&&(t.element.removeEventListener("keydown",e),e=null)}})}const Rn=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,AutolinkPlugin:Nn},Symbol.toStringTag,{value:"Module"}));function Mn(e="Start typing..."){return _n({name:"placeholder",requiresFullAccess:!0,init(t){const n=()=>{t.isEmpty()?(t.element.setAttribute("data-placeholder",e),t.element.classList.add("rmx-empty")):t.element.classList.remove("rmx-empty")};t.eventBus.on("content:change",n),t.eventBus.on("focus",n),t.eventBus.on("blur",n),n()}})}const Dn=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,PlaceholderPlugin:Mn},Symbol.toStringTag,{value:"Module"}));function Hn(e,t){const n=[];let o=0,r="";const s=()=>{r&&(n.push({text:r,className:null}),r="")};for(;o<e.length;){let i=!1;for(const[r,a]of t){r.lastIndex=o;const t=r.exec(e);if(t&&t.index===o){s(),n.push({text:t[0],className:a}),o+=t[0].length,i=!0;break}}i||(r+=e[o],o++)}return s(),n}function Fn(e){return new RegExp(`\\b(?:${e.join("|")})\\b`,"g")}function Pn(e){const t=new Set(e);return e=>t.has(e)}function zn(e){const t=new Set(e.map((e=>e.toLowerCase())));return e=>t.has(e.toLowerCase())}function On(e,t){const n=[],o=/\b[a-zA-Z_$]\w*\b/g;for(const r of e){if(null!==r.className){n.push(r);continue}let e,s=0;for(o.lastIndex=0;null!==(e=o.exec(r.text));){e.index>s&&n.push({text:r.text.slice(s,e.index),className:null});let i=null;for(const{match:n,className:o}of t)if(n(e[0])){i=o;break}n.push({text:e[0],className:i}),s=o.lastIndex}s<r.text.length&&n.push({text:r.text.slice(s),className:null})}return n}const Gn=[{match:Pn(["any","boolean","never","number","string","unknown","void","type","keyof","readonly","infer"]),className:"rmx-syn-type"},{match:Pn(["await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","finally","for","from","function","if","implements","import","in","instanceof","interface","let","new","of","package","return","static","super","switch","this","throw","try","typeof","var","void","while","with","yield","async"]),className:"rmx-syn-keyword"},{match:Pn(["Array","Boolean","console","Date","Error","JSON","Map","Math","Number","Object","Promise","Proxy","RegExp","Set","String","Symbol","WeakMap","WeakSet","parseInt","parseFloat","undefined","null","true","false","NaN","Infinity"]),className:"rmx-syn-builtin"}],qn=[[/\/\/[^\n]{0,500}/g,"rmx-syn-comment"],[/\/\*[^]*?(?:\*\/|$)/g,"rmx-syn-comment"],[/\/(?:[^/\\*\n]|\\.){1,200}\/[gimsuy]{0,6}/g,"rmx-syn-regex"],[/`(?:[^`\\]|\\.|\$\{[^}]{0,200}\}){0,2000}`/g,"rmx-syn-string"],[/"(?:[^"\\]|\\.){0,1000}"/g,"rmx-syn-string"],[/'(?:[^'\\]|\\.){0,1000}'/g,"rmx-syn-string"],[/@\w{1,50}/g,"rmx-syn-decorator"],[/\b\d[\d_]{0,30}(?:\.\d[\d_]{0,30})?(?:[eE][+-]?\d{1,10})?\b/g,"rmx-syn-number"],[/0[xX][\da-fA-F_]{1,20}/g,"rmx-syn-number"],[/0[bB][01_]{1,64}/g,"rmx-syn-number"],[/\b[a-zA-Z_$]\w{0,50}(?=\s{0,5}\()/g,"rmx-syn-function"],[new RegExp("(?<=\\.)[a-zA-Z_$]\\w{0,50}","g"),"rmx-syn-property"],[/=>|[+\-*/%=!<>&|^~?:]{1,3}/g,"rmx-syn-operator"],[/[{}()[\];,.]/g,"rmx-syn-punctuation"]];function Wn(e){return On(Hn(e,qn),Gn)}const $n=[{match:Pn(["False","None","True","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield"]),className:"rmx-syn-keyword"},{match:Pn(["abs","all","any","bin","bool","bytes","callable","chr","dict","dir","enumerate","eval","filter","float","format","frozenset","getattr","hasattr","hash","hex","id","input","int","isinstance","issubclass","iter","len","list","map","max","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","set","setattr","slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"]),className:"rmx-syn-builtin"}],Zn=[[/#[^\n]{0,500}/g,"rmx-syn-comment"],[/"""[^]*?(?:"""|$)/g,"rmx-syn-string"],[/'''[^]*?(?:'''|$)/g,"rmx-syn-string"],[/f"(?:[^"\\]|\\.|\{[^}]{0,200}\}){0,1000}"/g,"rmx-syn-string"],[/f'(?:[^'\\]|\\.|\{[^}]{0,200}\}){0,1000}'/g,"rmx-syn-string"],[/"(?:[^"\\]|\\.){0,1000}"/g,"rmx-syn-string"],[/'(?:[^'\\]|\\.){0,1000}'/g,"rmx-syn-string"],[/@\w{1,50}/g,"rmx-syn-decorator"],[/\b\d[\d_]{0,30}(?:\.\d[\d_]{0,30})?(?:[eE][+-]?\d{1,10})?\b/g,"rmx-syn-number"],[/0[xX][\da-fA-F_]{1,20}/g,"rmx-syn-number"],[/0[bBoO][\d_]{1,64}/g,"rmx-syn-number"],[/\b[a-zA-Z_]\w{0,50}(?=\s{0,5}\()/g,"rmx-syn-function"],[new RegExp("(?<=\\.)[a-zA-Z_]\\w{0,50}","g"),"rmx-syn-property"],[/[+\-*/%=!<>&|^~@:]{1,3}/g,"rmx-syn-operator"],[/[{}()[\];,.]/g,"rmx-syn-punctuation"]];function Un(e){return On(Hn(e,Zn),$n)}const Vn=[[/\/\*[^]*?(?:\*\/|$)/g,"rmx-syn-comment"],[new RegExp(`@(?:${["charset","import","namespace","media","supports","keyframes","font-face","layer","container","property","scope"].join("|")})\\b`,"g"),"rmx-syn-keyword"],[/"(?:[^"\\]|\\.){0,1000}"/g,"rmx-syn-string"],[/'(?:[^'\\]|\\.){0,1000}'/g,"rmx-syn-string"],[/#[\da-fA-F]{3,8}\b/g,"rmx-syn-number"],[/\b\d[\d.]{0,20}(?:%|px|rem|em|vh|vw|ch|ex|s|ms|deg|fr|vmin|vmax)?\b/g,"rmx-syn-number"],[/(?:^|\s|[{;])\s{0,10}[a-zA-Z-]{1,40}(?=\s{0,5}:)/gm,"rmx-syn-attr-name"],[/[.#][\w-]{1,60}/g,"rmx-syn-tag"],[/::?[\w-]{1,40}/g,"rmx-syn-entity"],[/\b(?:rgb|rgba|hsl|hsla|var|calc|min|max|clamp)(?=\()/g,"rmx-syn-builtin"],[/!important\b/g,"rmx-syn-keyword"],[/[{}();:,]/g,"rmx-syn-punctuation"]];const jn=[{match:zn(["INT","INTEGER","BIGINT","SMALLINT","TINYINT","FLOAT","DOUBLE","DECIMAL","NUMERIC","CHAR","VARCHAR","TEXT","BLOB","BOOLEAN","DATE","TIMESTAMP","SERIAL"]),className:"rmx-syn-type"},{match:zn(["SELECT","FROM","WHERE","INSERT","INTO","UPDATE","DELETE","CREATE","DROP","ALTER","TABLE","INDEX","VIEW","JOIN","INNER","LEFT","RIGHT","OUTER","FULL","CROSS","ON","AS","AND","OR","NOT","IN","BETWEEN","LIKE","IS","NULL","ORDER","BY","GROUP","HAVING","LIMIT","OFFSET","UNION","ALL","DISTINCT","SET","VALUES","EXISTS","CASE","WHEN","THEN","ELSE","END","ASC","DESC","PRIMARY","KEY","FOREIGN","REFERENCES","CONSTRAINT","DEFAULT","WITH","RECURSIVE","RETURNING","BEGIN","COMMIT","ROLLBACK","TRANSACTION","GRANT","REVOKE","TRUNCATE"]),className:"rmx-syn-keyword"},{match:zn(["COUNT","SUM","AVG","MIN","MAX","COALESCE","IFNULL","NULLIF","CAST","CONVERT","SUBSTRING","TRIM","UPPER","LOWER","LENGTH","CONCAT","NOW","CURRENT_TIMESTAMP","TRUE","FALSE"]),className:"rmx-syn-builtin"}],Kn=[[/--[^\n]{0,500}/g,"rmx-syn-comment"],[/\/\*[^]*?(?:\*\/|$)/g,"rmx-syn-comment"],[/'(?:[^'\\]|\\.){0,1000}'/g,"rmx-syn-string"],[/"(?:[^"\\]|\\.){0,1000}"/g,"rmx-syn-string"],[/\b\d[\d.]{0,20}\b/g,"rmx-syn-number"],[/[+\-*/%=!<>]{1,3}/g,"rmx-syn-operator"],[/[{}()[\];,.]/g,"rmx-syn-punctuation"]];const Xn=[[/"(?:[^"\\]|\\.){0,1000}"(?=\s{0,10}:)/g,"rmx-syn-attr-name"],[/"(?:[^"\\]|\\.){0,1000}"/g,"rmx-syn-string"],[/\b(?:true|false)\b/g,"rmx-syn-builtin"],[/\bnull\b/g,"rmx-syn-builtin"],[/-?\b\d[\d.]{0,20}(?:[eE][+-]?\d{1,10})?\b/g,"rmx-syn-number"],[/[{}[\]:,]/g,"rmx-syn-punctuation"]];const Jn=[[/#[^\n]{0,500}/g,"rmx-syn-comment"],[/"(?:[^"\\]|\\.|\$\{[^}]{0,200}\}|\$\w{1,50}){0,1000}"/g,"rmx-syn-string"],[/'[^']{0,2000}'/g,"rmx-syn-string"],[/\$\{[^}]{0,200}\}/g,"rmx-syn-entity"],[/\$[\w?!#@*]{1,50}/g,"rmx-syn-entity"],[Fn(["if","then","else","elif","fi","for","while","until","do","done","case","esac","in","function","select","return","exit","break","continue","local","export","declare","readonly","unset","shift","source","trap"]),"rmx-syn-keyword"],[Fn(["echo","printf","cd","pwd","ls","cp","mv","rm","mkdir","cat","grep","sed","awk","find","sort","uniq","wc","head","tail","chmod","chown","curl","wget","tar","git","docker","npm","yarn","pip","sudo","apt","brew","test","read","eval","exec","set"]),"rmx-syn-builtin"],[/\b\d[\d.]{0,20}\b/g,"rmx-syn-number"],[/[|&;<>]{1,3}/g,"rmx-syn-operator"],[/[{}()[\]]/g,"rmx-syn-punctuation"]];function Yn(e){return Hn(e,Jn)}const Qn=[{match:Pn(["bool","char","f32","f64","i8","i16","i32","i64","i128","isize","str","u8","u16","u32","u64","u128","usize","Self","Box","Vec","String","Option","Result","Rc","Arc","HashMap","HashSet","BTreeMap","BTreeSet","Cow"]),className:"rmx-syn-type"},{match:Pn(["as","async","await","break","const","continue","crate","dyn","else","enum","extern","fn","for","if","impl","in","let","loop","match","mod","move","mut","pub","ref","return","self","static","struct","super","trait","type","unsafe","use","where","while","yield"]),className:"rmx-syn-keyword"},{match:Pn(["Some","None","Ok","Err","true","false","println","eprintln","format","panic","assert","assert_eq","assert_ne","todo","unimplemented","unreachable","dbg","cfg","derive"]),className:"rmx-syn-builtin"}],eo=[[/\/\/[^\n]{0,500}/g,"rmx-syn-comment"],[/\/\*[^]*?(?:\*\/|$)/g,"rmx-syn-comment"],[/"(?:[^"\\]|\\.){0,1000}"/g,"rmx-syn-string"],[/r#*"[^]*?"#*/g,"rmx-syn-string"],[/'[a-zA-Z_]\w{0,30}/g,"rmx-syn-entity"],[/b?'(?:[^'\\]|\\.){1,4}'/g,"rmx-syn-string"],[/#!\[[\w:]{1,50}/g,"rmx-syn-decorator"],[/#\[[\w:]{1,50}/g,"rmx-syn-decorator"],[/\b\w{1,30}!/g,"rmx-syn-builtin"],[/\b\d[\d_]{0,30}(?:\.\d[\d_]{0,30})?(?:[eE][+-]?\d{1,10})?(?:_?(?:f32|f64|i8|i16|i32|i64|i128|u8|u16|u32|u64|u128|isize|usize))?\b/g,"rmx-syn-number"],[/0[xX][\da-fA-F_]{1,20}/g,"rmx-syn-number"],[/0[bB][01_]{1,64}/g,"rmx-syn-number"],[/\b[a-zA-Z_]\w{0,50}(?=\s{0,5}\()/g,"rmx-syn-function"],[new RegExp("(?<=\\.)[a-zA-Z_]\\w{0,50}","g"),"rmx-syn-property"],[/[+\-*/%=!<>&|^]{1,3}|::|=>/g,"rmx-syn-operator"],[/[{}()[\];,.]/g,"rmx-syn-punctuation"]];function to(e){return On(Hn(e,eo),Qn)}const no=[[/\/\/[^\n]{0,500}/g,"rmx-syn-comment"],[/\/\*[^]*?(?:\*\/|$)/g,"rmx-syn-comment"],[/`[^`]{0,5000}`/g,"rmx-syn-string"],[/"(?:[^"\\]|\\.){0,1000}"/g,"rmx-syn-string"],[Fn(["bool","byte","complex64","complex128","error","float32","float64","int","int8","int16","int32","int64","rune","string","uint","uint8","uint16","uint32","uint64","uintptr"]),"rmx-syn-type"],[Fn(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"]),"rmx-syn-keyword"],[Fn(["append","cap","close","complex","copy","delete","imag","len","make","new","panic","print","println","real","recover","true","false","nil","iota"]),"rmx-syn-builtin"],[/\b\d[\d_]{0,30}(?:\.\d[\d_]{0,30})?(?:[eE][+-]?\d{1,10})?\b/g,"rmx-syn-number"],[/0[xX][\da-fA-F_]{1,20}/g,"rmx-syn-number"],[/\b[a-zA-Z_]\w{0,50}(?=\s{0,5}\()/g,"rmx-syn-function"],[new RegExp("(?<=\\.)[a-zA-Z_]\\w{0,50}","g"),"rmx-syn-property"],[/:=|[+\-*/%=!<>&|^]{1,3}/g,"rmx-syn-operator"],[/[{}()[\];,.]/g,"rmx-syn-punctuation"]];function oo(e){return Hn(e,no)}const ro=[{match:Pn(["String","Integer","Long","Double","Float","Boolean","Byte","Character","Short","Object","List","Map","Set","Collection","ArrayList","HashMap","HashSet","Optional","Stream"]),className:"rmx-syn-type"},{match:Pn(["abstract","assert","boolean","break","byte","case","catch","char","class","const","continue","default","do","double","else","enum","extends","final","finally","float","for","goto","if","implements","import","instanceof","int","interface","long","native","new","package","private","protected","public","return","short","static","strictfp","super","switch","synchronized","this","throw","throws","transient","try","void","volatile","while","var","record","sealed","permits","yield"]),className:"rmx-syn-keyword"},{match:Pn(["true","false","null","System","Math","Arrays","Collections"]),className:"rmx-syn-builtin"}],so=[[/\/\/[^\n]{0,500}/g,"rmx-syn-comment"],[/\/\*[^]*?(?:\*\/|$)/g,"rmx-syn-comment"],[/"(?:[^"\\]|\\.){0,1000}"/g,"rmx-syn-string"],[/'(?:[^'\\]|\\.){1,4}'/g,"rmx-syn-string"],[/@\w{1,50}/g,"rmx-syn-decorator"],[/\b\d[\d_]{0,30}(?:\.\d[\d_]{0,30})?(?:[eE][+-]?\d{1,10})?[lLfFdD]?\b/g,"rmx-syn-number"],[/0[xX][\da-fA-F_]{1,20}[lL]?/g,"rmx-syn-number"],[/0[bB][01_]{1,64}[lL]?/g,"rmx-syn-number"],[/\b[a-zA-Z_]\w{0,50}(?=\s{0,5}\()/g,"rmx-syn-function"],[new RegExp("(?<=\\.)[a-zA-Z_]\\w{0,50}","g"),"rmx-syn-property"],[/[+\-*/%=!<>&|^~?:]{1,3}|->/g,"rmx-syn-operator"],[/[{}()[\];,.]/g,"rmx-syn-punctuation"]];const io=[[/<!--[^]*?(?:-->|$)/g,"rmx-syn-comment"],[/<!DOCTYPE[^>]{0,200}>/gi,"rmx-syn-entity"],[/<\/?[a-zA-Z][\w.-]{0,50}/g,"rmx-syn-tag"],[/\/?>/g,"rmx-syn-tag"],[/\b[a-zA-Z_:][\w:.-]{0,50}(?=\s{0,5}=)/g,"rmx-syn-attr-name"],[/=\s{0,5}"[^"]{0,1000}"/g,"rmx-syn-attr-value"],[/=\s{0,5}'[^']{0,1000}'/g,"rmx-syn-attr-value"],[/&\w{1,20};/g,"rmx-syn-entity"]];function ao(e){return Hn(e,io)}function lo(e){return[{text:e,className:null}]}const co={javascript:Wn,js:Wn,jsx:Wn,typescript:Wn,ts:Wn,tsx:Wn,python:Un,py:Un,css:function(e){return Hn(e,Vn)},sql:function(e){return On(Hn(e,Kn),jn)},json:function(e){return Hn(e,Xn)},bash:Yn,sh:Yn,shell:Yn,zsh:Yn,rust:to,rs:to,go:oo,golang:oo,java:function(e){return On(Hn(e,so),ro)},html:ao,htm:ao,xml:ao,svg:ao,plaintext:lo,text:lo,txt:lo},uo=[{id:"javascript",label:"JavaScript"},{id:"typescript",label:"TypeScript"},{id:"python",label:"Python"},{id:"css",label:"CSS"},{id:"sql",label:"SQL"},{id:"json",label:"JSON"},{id:"bash",label:"Bash"},{id:"rust",label:"Rust"},{id:"go",label:"Go"},{id:"java",label:"Java"},{id:"html",label:"HTML"},{id:"plaintext",label:"Plain Text"}];function mo(e,t,n,o=[]){if(!e||"string"!=typeof e)throw new Error("registerLanguage: id is required");if(!t||"string"!=typeof t)throw new Error("registerLanguage: label is required");if("function"!=typeof n)throw new Error("registerLanguage: tokenizer must be a function");co[e.toLowerCase()]=n;for(const r of o)co[r.toLowerCase()]=n;uo.find((t=>t.id===e))||uo.push({id:e,label:t})}function ho(e,t=[]){delete co[e.toLowerCase()];for(const o of t)delete co[o.toLowerCase()];const n=uo.findIndex((t=>t.id===e));-1!==n&&uo.splice(n,1)}function go(e,t){const n=co[t?.toLowerCase()];if(!n||n===lo)return null;return n(e).map((({text:e,className:t})=>({type:t?t.replace("rmx-syn-",""):"plain",value:e})))}function po(e){if(!e||"string"!=typeof e)return"plaintext";const t=e.trimStart(),n=t.slice(0,200);if(n.toLowerCase(),/^\s*[{\[]/.test(t))try{return JSON.parse(t),"json"}catch{}return/^\s*<!doctype\s+html/i.test(t)||/^\s*<(?:html|head|body|div|span|p|a|img|ul|ol|li|table|form|section|header|footer|nav|main|article)\b/i.test(t)?"html":/^\s*(?:SELECT|INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|WITH|GRANT|EXPLAIN)\b/i.test(t)?"sql":/^#!.*python/i.test(t)||/^\s*(?:def |class \w+[:(]|from \w+ import|import (?:os|sys|re|json|math|typing|collections|pathlib|django|flask|numpy|pandas))\b/.test(t)?"python":/^\s*(?:fn |use std|pub fn|impl |#\[derive|mod \w+;|extern crate)/.test(t)?"rust":/^\s*(?:package \w+|func (?:main|\w+)\(|import \()/.test(t)?"go":/^\s*(?:(?:public|private|protected)\s+(?:class|interface|enum|abstract)|import java|@Override|package [a-z]+\.)/.test(t)?"java":/^#!\/(?:bin\/(?:ba)?sh|usr\/bin\/env (?:ba)?sh)/.test(t)||/^\s*(?:export |alias |source |if \[)/.test(t)?"bash":/^\s*(?:@(?:media|import|charset|keyframes|font-face)|[.#][\w-]+\s*\{|:root\s*\{|\*\s*\{|body\s*\{)/.test(t)?"css":/^\s*(?:import |export |const |let |var |function |class |async |'use strict')/.test(t)||/=>/.test(n)||/(?:React|require\(|module\.exports)/.test(n)?"javascript":"plaintext"}function fo(e){const t=e.selection.getSelection();if(!t||!t.anchorNode)return null;const n=t.anchorNode.nodeType===Node.TEXT_NODE?t.anchorNode.parentElement:t.anchorNode;return n?.closest?.("pre")??null}function bo(){let e=null,t=null,n=null,o=null,r=null;function s(e,t){const n=e.closest("pre");if(!n)return;let o=e.getAttribute("data-language");o||(o=po(e.textContent),o&&e.setAttribute("data-language",o));const r=go(e.textContent,o);if(!r)return void n.classList.add("rmx-highlighted");let s="";for(const a of r)"plain"===a.type?s+=te(a.value):s+=`<span class="rmx-syn-${a.type}">${te(a.value)}</span>`;const i=t.selection.save();e.innerHTML=s,n.classList.add("rmx-highlighted"),i&&t.selection.restore(i)}function i(e){const t=e.hasAttribute("data-line-numbers");let n=e.querySelector(".rmx-line-numbers");if(!t)return n&&n.remove(),void e.classList.remove("rmx-has-line-numbers");const o=e.querySelector("code");if(!o)return;const r=(o.textContent.match(/\n/g)||[]).length+1;n||(n=document.createElement("span"),n.className="rmx-line-numbers",n.setAttribute("aria-hidden","true"),n.contentEditable="false",e.insertBefore(n,e.firstChild));let s="";for(let i=1;i<=r;i++)s+=`<span class="rmx-line-number">${i}</span>`;n.innerHTML=s,e.classList.add("rmx-has-line-numbers")}function a(e){if(e.querySelector(".rmx-code-copy-btn"))return;const t=document.createElement("button");t.className="rmx-code-copy-btn",t.type="button",t.setAttribute("aria-label","Copy code"),t.contentEditable="false",t.textContent="⧉",e.appendChild(t)}function l(e){const t=function(){if(!document.activeElement)return null;const e=window.getSelection();if(!e||!e.focusNode)return null;const t=e.focusNode.nodeType===Node.TEXT_NODE?e.focusNode.parentElement:e.focusNode;return t?.closest?.("pre")??null}(),n=e.element.querySelectorAll("pre");for(const o of n){if(a(o),i(o),o===t)continue;if(o.classList.contains("rmx-highlighted"))continue;const n=o.querySelector("code");n&&s(n,e)}!function(e){const t=e.element.querySelectorAll("code[data-language]:not(pre code)");for(const n of t){if(n.classList.contains("rmx-inline-highlighted"))continue;const e=n.getAttribute("data-language"),t=go(n.textContent,e);if(!t)continue;let o="";for(const n of t)"plain"===n.type?o+=te(n.value):o+=`<span class="rmx-syn-${n.type}">${te(n.value)}</span>`;n.innerHTML=o,n.classList.add("rmx-inline-highlighted")}}(e)}return _n({name:"syntaxHighlight",requiresFullAccess:!0,commands:[{name:"setCodeLanguage",execute(e,{language:t}={}){if(!t)return!1;const n=fo(e);if(!n)return!1;const o=n.querySelector("code");return!!o&&(o.setAttribute("data-language",t),n.classList.remove("rmx-highlighted"),s(o,e),e.eventBus.emit("codeblock:language-change",{language:t,element:o}),!0)}},{name:"getCodeLanguage",execute(e){const t=fo(e);if(!t)return null;const n=t.querySelector("code");return n&&n.getAttribute("data-language")||null}},{name:"toggleLineNumbers",execute(e,{element:t}={}){const n=t||fo(e);return!!n&&(n.hasAttribute("data-line-numbers")?n.removeAttribute("data-line-numbers"):n.setAttribute("data-line-numbers",""),i(n),!0)},meta:{icon:"lineNumbers",tooltip:"Toggle Line Numbers"}}],init(a){l(a),e=new MutationObserver((e=>{let n=!1;for(const t of e){if("childList"===t.type)for(const e of t.addedNodes)if(e.nodeType===Node.ELEMENT_NODE&&(e.matches?.("pre")||e.querySelector?.("pre"))){n=!0;break}if("characterData"===t.type){const e=t.target.parentElement?.closest?.("pre");e&&(e.classList.remove("rmx-highlighted"),n=!0)}if("attributes"===t.type){const e=t.target;if(e.matches?.("code")&&"data-language"===t.attributeName){const t=e.closest("pre");t&&(t.classList.remove("rmx-highlighted"),n=!0)}}if(n)break}n&&function(e){clearTimeout(t),t=setTimeout((()=>l(e)),150)}(a)})),e.observe(a.element,{childList:!0,subtree:!0,characterData:!0,attributes:!0,attributeFilter:["data-language"]}),r=async e=>{const t=e.target.closest(".rmx-code-copy-btn");if(!t)return;const n=t.closest("pre");if(!n)return;const o=n.querySelector("code");if(o){e.preventDefault(),e.stopPropagation();try{await navigator.clipboard.writeText(o.textContent),t.textContent="✓",t.classList.add("rmx-code-copy-success"),setTimeout((()=>{t.textContent="⧉",t.classList.remove("rmx-code-copy-success")}),1500)}catch{const e=document.createElement("textarea");e.value=o.textContent,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),t.textContent="✓",t.classList.add("rmx-code-copy-success"),setTimeout((()=>{t.textContent="⧉",t.classList.remove("rmx-code-copy-success")}),1500)}}},a.element.addEventListener("click",r,!0),n=e=>{const t=e.target?.closest?.("pre");if(t&&a.element.contains(t)){t.classList.remove("rmx-highlighted");const e=t.querySelector("code");e&&s(e,a),i(t)}},a.element.addEventListener("focusout",n,!0),o=a.eventBus.on("codeblock:language-change",(({language:e,element:t})=>{if(!t)return;const n=t.closest("pre");n&&a.element.contains(n)&&(n.classList.remove("rmx-highlighted"),s(t,a))}))},destroy(s){clearTimeout(t),t=null,e&&(e.disconnect(),e=null),n&&(s.element.removeEventListener("focusout",n,!0),n=null),r&&(s.element.removeEventListener("click",r,!0),r=null),o&&(o(),o=null)}})}function yo(e,t){const n=[];let o=null,r=null;function s(){l();const t=e.querySelector("thead");if(!t)return;t.querySelectorAll("th").forEach(((e,t)=>{const s=document.createElement("span");s.className="rmx-filter-btn",s.textContent="▽",s.title="Filter column",s.setAttribute("data-col-index",String(t)),s.addEventListener("mousedown",(n=>{n.preventDefault(),n.stopPropagation(),function(e,t){if(o&&o.parentElement===e)return void a();a();const n=document.createElement("div");n.className="rmx-filter-dropdown",n.addEventListener("mousedown",(e=>e.stopPropagation()));const s=document.createElement("input");s.type="text",s.className="rmx-filter-input",s.placeholder="Filter...",s.value=e.getAttribute("data-filter-value")||"",s.addEventListener("input",(()=>{clearTimeout(r),r=setTimeout((()=>{i(t,s.value)}),200)}));const l=document.createElement("button");l.className="rmx-filter-clear-btn",l.textContent="Clear",l.type="button",l.addEventListener("click",(e=>{e.stopPropagation(),s.value="",i(t,""),a()})),n.appendChild(s),n.appendChild(l),e.appendChild(n),o=n,setTimeout((()=>s.focus()),0);const c=t=>{n.contains(t.target)||t.target===e.querySelector(".rmx-filter-btn")||(a(),document.removeEventListener("mousedown",c))};setTimeout((()=>document.addEventListener("mousedown",c)),0)}(e,t)})),e.style.position="relative",e.appendChild(s),n.push(s),e.getAttribute("data-filter-value")&&s.classList.add("rmx-filter-active")}))}function i(n,o){const r=e.querySelector("thead"),s=e.querySelector("tbody");if(!s)return;if(r){const e=r.querySelectorAll("th");if(e[n])if(o){e[n].setAttribute("data-filter-value",o);const t=e[n].querySelector(".rmx-filter-btn");t&&t.classList.add("rmx-filter-active")}else{e[n].removeAttribute("data-filter-value");const t=e[n].querySelector(".rmx-filter-btn");t&&t.classList.remove("rmx-filter-active")}}const i=[];r&&r.querySelectorAll("th").forEach(((e,t)=>{const n=e.getAttribute("data-filter-value");n&&i.push({columnIndex:t,value:n.toLowerCase()})}));s.querySelectorAll("tr").forEach((e=>{const t=e.querySelectorAll("td, th");i.some((e=>!(t[e.columnIndex]?.textContent||"").toLowerCase().includes(e.value)))?e.classList.add("rmx-row-hidden"):e.classList.remove("rmx-row-hidden")})),t?.eventBus&&t.eventBus.emit("table:filter-change",{table:e,filters:i})}function a(){o&&(o.remove(),o=null)}function l(){n.forEach((e=>e.remove())),n.length=0,a()}return s(),{update:s,destroy:()=>{clearTimeout(r),l()}}}function vo(){let e=null,t=/* @__PURE__ */new Map,n=null,o=null,r=null,s=null,i=null;function a(e,n){if(t.has(e))return;const o={};o.resize=function(e,t){const n=[];let o=0,r=0,s=0,i=0,a=-1,l=null;function c(){const t=e.getBoundingClientRect(),o=e.querySelector("thead"),r=o?.querySelector("tr")||e.querySelector("tr");if(!r)return;const s=r.querySelectorAll("th, td");n.forEach((n=>{if(n.classList.contains("rmx-col-resize-handle")){const o=parseInt(n.getAttribute("data-col-index")),r=s[o];if(!r)return;const i=r.getBoundingClientRect();n.style.position="absolute",n.style.top="0",n.style.left=i.right-t.left-3+"px",n.style.width="6px",n.style.height=e.offsetHeight+"px"}else if(n.classList.contains("rmx-row-resize-handle")){const o=parseInt(n.getAttribute("data-row-index")),r=e.querySelectorAll("tbody tr")[o];if(!r)return;const s=r.getBoundingClientRect();n.style.position="absolute",n.style.left="0",n.style.top=s.bottom-t.top-3+"px",n.style.width=e.offsetWidth+"px",n.style.height="6px"}}))}function d(t){t.preventDefault(),t.stopPropagation(),a=parseInt(t.target.getAttribute("data-col-index"));const n=e.querySelector("thead"),r=n?.querySelector("tr")||e.querySelector("tr"),i=r?.querySelectorAll("th, td")[a];i&&(o=t.clientX,s=i.offsetWidth,t.target,e.classList.add("rmx-table-resizing"),document.addEventListener("mousemove",u),document.addEventListener("mouseup",m))}function u(t){if(a<0)return;const n=t.clientX-o,r=Math.max(40,s+n);e.querySelectorAll("tr").forEach((e=>{const t=e.cells[a];t&&t.colSpan<=1&&(t.style.width=r+"px")}))}function m(){document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",m),e.classList.remove("rmx-table-resizing"),a=-1,t?.history&&t.history.snapshot(),c()}function h(t){t.preventDefault(),t.stopPropagation();const n=parseInt(t.target.getAttribute("data-row-index")),o=e.querySelectorAll("tbody tr");l=o[n],l&&(r=t.clientY,i=l.offsetHeight,e.classList.add("rmx-table-resizing"),document.addEventListener("mousemove",g),document.addEventListener("mouseup",p))}function g(e){if(!l)return;const t=e.clientY-r,n=Math.max(24,i+t);l.style.height=n+"px"}function p(){document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",p),e.classList.remove("rmx-table-resizing"),l=null,t?.history&&t.history.snapshot(),c()}function f(){n.forEach((e=>e.remove())),n.length=0}return"static"===getComputedStyle(e).position&&(e.style.position="relative"),function(){f();const t=e.querySelector("thead"),o=t?.querySelector("tr")||e.querySelector("tr");if(!o)return;const r=o.querySelectorAll("th, td");r.forEach(((t,o)=>{if(o===r.length-1)return;const s=document.createElement("div");s.className="rmx-col-resize-handle",s.setAttribute("data-col-index",String(o)),s.addEventListener("mousedown",d),e.appendChild(s),n.push(s)}));const s=e.querySelectorAll("tbody tr");s.forEach(((t,o)=>{if(o===s.length-1)return;const r=document.createElement("div");r.className="rmx-row-resize-handle",r.setAttribute("data-row-index",String(o)),r.addEventListener("mousedown",h),e.appendChild(r),n.push(r)})),c()}(),{update:c,destroy:()=>{f(),document.removeEventListener("mousemove",u),document.removeEventListener("mouseup",m),document.removeEventListener("mousemove",g),document.removeEventListener("mouseup",p)}}}(e,n),e.querySelector("thead")&&(o.filter=yo(e,n));const r=e.querySelector("thead");r&&r.querySelectorAll("th").forEach((e=>{e.classList.add("rmx-sortable")})),e.querySelectorAll("td, th").forEach((e=>{const t=e.textContent.trim();t.startsWith("=")&&!e.hasAttribute("data-formula")&&e.setAttribute("data-formula",t)})),Tt(e),t.set(e,o)}function l(e){const n=t.get(e);n&&(n.resize?.destroy(),n.filter?.destroy(),t.delete(e))}function c(e){e.element.querySelectorAll("table.rmx-table").forEach((t=>a(t,e)))}return _n({name:"tableFeatures",requiresFullAccess:!0,init(t){c(t),e=new MutationObserver((e=>{let n=!1;for(const t of e){if("childList"===t.type){for(const e of t.addedNodes)if(e.nodeType===Node.ELEMENT_NODE&&(e.matches?.("table.rmx-table")||e.querySelector?.("table.rmx-table"))){n=!0;break}for(const e of t.removedNodes)e.nodeType===Node.ELEMENT_NODE&&e.matches?.("table.rmx-table")&&l(e)}if(n)break}n&&c(t)})),e.observe(t.element,{childList:!0,subtree:!0}),o=e=>{const n=e.target.closest("th");if(!n)return;const o=n.closest("thead");if(!o)return;const r=o.closest("table.rmx-table");if(!r||!t.element.contains(r))return;if(e.target.closest(".rmx-filter-btn")||e.target.closest(".rmx-filter-dropdown"))return;const s=Array.from(o.querySelectorAll("th")),i=s.indexOf(n);if(i<0)return;const a=n.getAttribute("data-sort-dir");let l;if(l=a?"asc"===a?"desc":null:"asc",e.shiftKey){const e=[];s.forEach(((t,n)=>{const o=t.getAttribute("data-sort-dir");o&&n!==i&&e.push({columnIndex:n,direction:o})})),l&&e.push({columnIndex:i,direction:l}),e.length>0?t.executeCommand("sortTable",{keys:e}):s.forEach((e=>{e.removeAttribute("data-sort-dir"),e.removeAttribute("data-sort-priority")}))}else l?t.executeCommand("sortTable",{columnIndex:i,direction:l}):s.forEach((e=>{e.removeAttribute("data-sort-dir"),e.removeAttribute("data-sort-priority")}))},t.element.addEventListener("click",o),r=e=>{const n=e.target.closest("td, th");if(!n||!t.element.contains(n))return;const o=n.getAttribute("data-formula");o&&(n.textContent="="+o)},s=e=>{const n=e.target.closest("td, th");if(!n||!t.element.contains(n))return;const o=n.textContent.trim();if(o.startsWith("=")&&o.length>1){const e=o.slice(1);n.setAttribute("data-formula",e);const t=n.closest("table.rmx-table");t&&Tt(t)}else n.hasAttribute("data-formula")&&!o.startsWith("=")&&n.removeAttribute("data-formula")},t.element.addEventListener("focusin",r,!0),t.element.addEventListener("focusout",s,!0),i=t.eventBus.on("content:change",(()=>{clearTimeout(n),n=setTimeout((()=>{t.element.querySelectorAll("table.rmx-table").forEach((e=>Tt(e)))}),200)}))},destroy(a){clearTimeout(n),n=null,i?.(),i=null,e&&(e.disconnect(),e=null),o&&(a.element.removeEventListener("click",o),o=null),r&&(a.element.removeEventListener("focusin",r,!0),r=null),s&&(a.element.removeEventListener("focusout",s,!0),s=null);for(const e of t.keys())l(e);t.clear()}})}const xo={"Feature Card":'<div class="rmx-template-feature-card" style="border:1px solid #e2e8f0;border-radius:8px;padding:16px;margin:8px 0;">\n <img src="" alt="Feature image" style="width:100%;height:auto;border-radius:4px;margin-bottom:12px;" />\n <h3>Feature Title</h3>\n <p>Describe the feature here. Highlight key benefits and value propositions.</p>\n</div>',"Two-Column":'<div class="rmx-template-two-column" style="display:flex;gap:16px;margin:8px 0;">\n <div style="flex:1;padding:12px;border:1px solid #e2e8f0;border-radius:4px;">\n <p>Left column content</p>\n </div>\n <div style="flex:1;padding:12px;border:1px solid #e2e8f0;border-radius:4px;">\n <p>Right column content</p>\n </div>\n</div>',"Call to Action":'<div class="rmx-template-cta" style="text-align:center;padding:24px;margin:8px 0;background:#f8fafc;border-radius:8px;">\n <h2>Ready to Get Started?</h2>\n <p>Take the next step and join thousands of satisfied users today.</p>\n <p><span style="display:inline-block;padding:10px 24px;background:#6366f1;color:#fff;border-radius:6px;font-weight:600;">Get Started</span></p>\n</div>'};function Co(){const e=/* @__PURE__ */new Map;return _n({name:"blockTemplates",requiresFullAccess:!0,init(t){for(const[n,o]of Object.entries(xo))e.set(n,o);t._blockTemplates={registerTemplate:function(t,n){t&&"string"==typeof n&&e.set(t,n)},insertTemplate:function(n){const o=e.get(n);if(!o)return;t.history.snapshot();const r=t.selection.getRange();if(!r)return;const s=document.createElement("div");s.innerHTML=t.sanitizer.sanitize(o);const i=document.createDocumentFragment();for(;s.firstChild;)i.appendChild(s.firstChild);r.collapsed||r.deleteContents(),r.insertNode(i);const a=t.element;if(!a.lastElementChild||"P"!==a.lastElementChild.tagName){const e=document.createElement("p");e.innerHTML="<br>",a.appendChild(e)}t.eventBus.emit("content:change")},getTemplates:function(){return Array.from(e.entries()).map((([e,t])=>({name:e,html:t})))},removeTemplate:function(t){return e.delete(t)}}},destroy(){e.clear()}})}const wo=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,BlockTemplatePlugin:Co},Symbol.toStringTag,{value:"Module"}));let ko=1;function _o(){return`rmx-comment-${Date.now()}-${ko++}`}function So(e){if(!e)return[];const t=e.match(/@([\w.-]+)/g);return t?t.map((e=>e.slice(1))):[]}function Ao(e={}){const{onComment:t,onResolve:n,onDelete:o,onReply:r,mentionUsers:s=[],commentOnly:i=!1}=e,a=/* @__PURE__ */new Map;let l=null,c=null,d=null,u=null;function m(){return Array.from(a.values()).sort(((e,t)=>t.createdAt-e.createdAt))}function h(e){return a.get(e)}function g(){return m().filter((e=>!e.resolved))}function p(){return m().filter((e=>e.resolved))}function f({author:e="Anonymous",body:n=""}={}){if(!l)return null;const o=window.getSelection();if(!o||o.isCollapsed||0===o.rangeCount)return null;const r=o.getRangeAt(0);if(!l.element.contains(r.commonAncestorContainer))return null;const s=_o(),i=Date.now(),c={id:s,author:e,body:n,mentions:So(n),resolved:!1,createdAt:i,updatedAt:i,replies:[]};l.history.snapshot();const d=document.createElement("mark");d.className="rmx-comment",d.setAttribute("data-comment-id",s),d.setAttribute("data-comment-resolved","false"),d.setAttribute("title",`${e}: ${n}`);try{r.surroundContents(d)}catch{const e=r.extractContents();d.appendChild(e),r.insertNode(d)}return o.removeAllRanges(),a.set(s,c),l.eventBus.emit("comment:created",{thread:c}),l.eventBus.emit("content:change"),t?.(c),c}function b(e,{author:t="Anonymous",body:n=""}={}){const o=a.get(e);if(!o)return null;const s={id:_o(),author:t,body:n,mentions:So(n),createdAt:Date.now()};return o.replies.push(s),o.updatedAt=Date.now(),l?.eventBus.emit("comment:replied",{thread:o,reply:s}),r?.({thread:o,reply:s}),s}function y(e,t=!0){const o=a.get(e);if(!o)return;o.resolved=t,o.updatedAt=Date.now();const r=l?.element.querySelector(`[data-comment-id="${e}"]`);r&&(r.setAttribute("data-comment-resolved",String(t)),t?r.classList.add("rmx-comment-resolved"):r.classList.remove("rmx-comment-resolved")),l?.eventBus.emit("comment:resolved",{thread:o,resolved:t}),n?.({thread:o,resolved:t})}function v(e){const t=a.get(e);if(!t)return;const n=l?.element.querySelector(`[data-comment-id="${e}"]`);if(n){l.history.snapshot();const e=n.parentNode;for(;n.firstChild;)e.insertBefore(n.firstChild,n);e.removeChild(n),e.normalize(),l.eventBus.emit("content:change")}a.delete(e),l?.eventBus.emit("comment:deleted",{thread:t}),o?.(t)}function x(e,t){const n=a.get(e);if(!n)return;n.body=t,n.mentions=So(t),n.updatedAt=Date.now();const o=l?.element.querySelector(`[data-comment-id="${e}"]`);o&&o.setAttribute("title",`${n.author}: ${t}`),l?.eventBus.emit("comment:updated",{thread:n})}function C(e){const t=l?.element.querySelector(`[data-comment-id="${e}"]`);if(!t)return;t.scrollIntoView?.({behavior:"smooth",block:"center"});const n=window.getSelection(),o=document.createRange();o.selectNodeContents(t),n.removeAllRanges(),n.addRange(o),l?.eventBus.emit("comment:navigated",{threadId:e})}function w(e){for(const t of e)a.set(t.id,{...t});l?.eventBus.emit("comment:imported",{count:e.length})}function k(){return m().map((e=>({...e,replies:[...e.replies]})))}function _(){if(l)for(const[e]of a){l.element.querySelector(`[data-comment-id="${e}"]`)||a.delete(e)}}function S(){return[...s]}return _n({name:"comments",requiresFullAccess:!0,commands:[{name:"addComment",execute:(e,t)=>f(t),isEnabled(e){const t=window.getSelection();return t&&!t.isCollapsed&&e.element.contains(t.anchorNode)},meta:{icon:"comment",tooltip:"Add Comment"}},{name:"deleteComment",execute(e,t){v(t)},meta:{icon:"trash",tooltip:"Delete Comment"}},{name:"resolveComment",execute(e,t,n){y(t,n)},meta:{icon:"check",tooltip:"Resolve Comment"}},{name:"replyToComment",execute:(e,t,n)=>b(t,n),meta:{icon:"reply",tooltip:"Reply to Comment"}},{name:"editComment",execute(e,t,n){x(t,n)},meta:{icon:"edit",tooltip:"Edit Comment"}},{name:"navigateToComment",execute(e,t){C(t)},meta:{icon:"navigate",tooltip:"Go to Comment"}}],contextMenuItems:[{label:"Add Comment",command:"addComment",when:e=>{const t=window.getSelection();return t&&!t.isCollapsed}}],init(e){l=e,l._comments={addComment:f,deleteComment:v,resolveComment:y,replyToComment:b,editComment:x,navigateToComment:C,getAllThreads:m,getThread:h,getUnresolvedThreads:g,getResolvedThreads:p,importThreads:w,exportThreads:k,syncWithDOM:_,getMentionUsers:S},i&&(l.element.setAttribute("contenteditable","false"),l.element.classList.add("rmx-comment-only"));const t=l.element.querySelectorAll("[data-comment-id]");for(const n of t){const e=n.getAttribute("data-comment-id");a.has(e)||a.set(e,{id:e,author:"Imported",body:n.getAttribute("title")||"",mentions:[],resolved:"true"===n.getAttribute("data-comment-resolved"),createdAt:Date.now(),updatedAt:Date.now(),replies:[]})}c=l.eventBus.on("content:change",(()=>{clearTimeout(u),u=setTimeout(_,100)})),l.element.addEventListener("click",A),d=l.eventBus.on("destroy",E)},destroy(){E()}});function A(e){const t=e.target.closest?.("[data-comment-id]");if(t){const e=t.getAttribute("data-comment-id"),n=a.get(e);n&&l.eventBus.emit("comment:clicked",{thread:n,element:t})}}function E(){clearTimeout(u),u=null,c?.(),d?.(),l?.element?.removeEventListener("click",A),i&&l?.element&&(l.element.removeAttribute("contenteditable"),l.element.classList.remove("rmx-comment-only")),l=null}}const Eo=/* @__PURE__ */new Map,Lo=[{type:"info",label:"Info",icon:"ℹ️",color:"#3b82f6"},{type:"warning",label:"Warning",icon:"⚠️",color:"#f59e0b"},{type:"error",label:"Error",icon:"❌",color:"#ef4444"},{type:"success",label:"Success",icon:"✅",color:"#22c55e"},{type:"tip",label:"Tip",icon:"💡",color:"#8b5cf6"},{type:"note",label:"Note",icon:"📝",color:"#6366f1"},{type:"question",label:"Question",icon:"❓",color:"#ec4899"}];for(const Li of Lo)Eo.set(Li.type,Li);function To(e){e&&e.type&&Eo.set(e.type,e)}function Io(e){return Eo.delete(e)}function Bo(){return Array.from(Eo.values())}function No(e){return Eo.get(e)}const Ro={NOTE:"note",TIP:"tip",IMPORTANT:"info",WARNING:"warning",CAUTION:"error"};function Mo(e){if(!e)return null;const t=e.match(/^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]\s*\n?([\s\S]*)/);if(!t)return null;const n=t[1];return{type:Ro[n]||n.toLowerCase(),body:t[2].trim()}}function Do(e,t="",n={}){const{collapsible:o=!1,collapsed:r=!1,title:s}=n,i=Eo.get(e)||{label:e,icon:"📌"},a=document.createElement("div");a.className=`rmx-callout rmx-callout-${e}`,a.setAttribute("data-callout",e),o&&(a.setAttribute("data-callout-collapsible",""),r&&a.setAttribute("data-callout-collapsed",""));const l=document.createElement("div");l.className="rmx-callout-header",l.contentEditable="false";const c=document.createElement("span");c.className="rmx-callout-icon",c.textContent=i.icon,l.appendChild(c);const d=document.createElement("span");if(d.className="rmx-callout-title",d.textContent=s||i.label,l.appendChild(d),o){const e=document.createElement("button");e.className="rmx-callout-toggle",e.type="button",e.setAttribute("aria-label",r?"Expand":"Collapse"),e.textContent=r?"▶":"▼",l.appendChild(e)}a.appendChild(l);const u=document.createElement("div");if(u.className="rmx-callout-body",t)u.innerHTML=t;else{const e=document.createElement("p");e.innerHTML="<br>",u.appendChild(e)}return o&&r&&(u.style.display="none"),a.appendChild(u),a}function Ho(){let e=null,t=null,n=null;function o(e){const t=e.target.closest?.(".rmx-callout-toggle");if(!t)return;const n=t.closest(".rmx-callout");if(!n)return;e.preventDefault(),e.stopPropagation();const o=n.querySelector(".rmx-callout-body");if(!o)return;n.hasAttribute("data-callout-collapsed")?(n.removeAttribute("data-callout-collapsed"),o.style.display="",t.textContent="▼",t.setAttribute("aria-label","Collapse")):(n.setAttribute("data-callout-collapsed",""),o.style.display="none",t.textContent="▶",t.setAttribute("aria-label","Expand"))}function r(){if(!e)return;const t=e.element.querySelectorAll("blockquote");for(const n of t){const t=Mo(n.textContent);if(t){e.history.snapshot();const o=Do(t.type,`<p>${t.body||"<br>"}</p>`);n.parentNode.replaceChild(o,n),e.eventBus.emit("content:change")}}}return _n({name:"callouts",requiresFullAccess:!0,version:"1.0.0",description:"Styled callout blocks with 7 built-in types, custom types, collapsible toggle, and GFM alert syntax",commands:[{name:"insertCallout",execute(e,t={}){const{type:n="info",content:o="",collapsible:r=!1,collapsed:s=!1,title:i}=t;e.history.snapshot();const a=Do(n,o,{collapsible:r,collapsed:s,title:i}),l=window.getSelection();if(l&&l.rangeCount>0&&e.element.contains(l.anchorNode)){let t=l.getRangeAt(0).startContainer;for(;t&&t.parentNode!==e.element;)t=t.parentNode;t?t.parentNode.insertBefore(a,t.nextSibling):e.element.appendChild(a)}else e.element.appendChild(a);const c=a.querySelector(".rmx-callout-body p");if(c){const e=document.createRange();e.selectNodeContents(c),e.collapse(!0),l?.removeAllRanges(),l?.addRange(e)}return e.eventBus.emit("content:change"),a},meta:{icon:"callout",tooltip:"Insert Callout"}},{name:"removeCallout",execute(e){const t=e.selection.getClosestElement?.(".rmx-callout")||Fo(e,"rmx-callout");if(!t)return;e.history.snapshot();const n=t.querySelector(".rmx-callout-body"),o=t.parentNode;if(n)for(;n.firstChild;)o.insertBefore(n.firstChild,t);o.removeChild(t),o.normalize(),e.eventBus.emit("content:change")},meta:{icon:"remove",tooltip:"Remove Callout"}},{name:"changeCalloutType",execute(e,t){const n=Fo(e,"rmx-callout");if(!n||!t)return;const o=Eo.get(t);if(!o)return;e.history.snapshot();const r=n.getAttribute("data-callout");n.classList.remove(`rmx-callout-${r}`),n.classList.add(`rmx-callout-${t}`),n.setAttribute("data-callout",t);const s=n.querySelector(".rmx-callout-icon"),i=n.querySelector(".rmx-callout-title");s&&(s.textContent=o.icon),i&&(i.textContent=o.label),e.eventBus.emit("content:change")},meta:{icon:"swap",tooltip:"Change Callout Type"}},{name:"toggleCalloutCollapse",execute(e){const t=Fo(e,"rmx-callout");if(!t)return;const n=t.querySelector(".rmx-callout-body"),o=t.querySelector(".rmx-callout-toggle");if(n){if(t.hasAttribute("data-callout-collapsible")){t.hasAttribute("data-callout-collapsed")?(t.removeAttribute("data-callout-collapsed"),n.style.display="",o&&(o.textContent="▼",o.setAttribute("aria-label","Collapse"))):(t.setAttribute("data-callout-collapsed",""),n.style.display="none",o&&(o.textContent="▶",o.setAttribute("aria-label","Expand")))}else if(t.setAttribute("data-callout-collapsible",""),!o){const e=document.createElement("button");e.className="rmx-callout-toggle",e.type="button",e.textContent="▼",e.setAttribute("aria-label","Collapse"),t.querySelector(".rmx-callout-header")?.appendChild(e)}e.eventBus.emit("content:change")}},meta:{icon:"collapse",tooltip:"Toggle Callout Collapse"}}],contextMenuItems:[{label:"Insert Callout",command:"insertCallout"},{label:"Remove Callout",command:"removeCallout",when:e=>!!Fo(e,"rmx-callout")}],init(s){e=s,e._callouts={getCalloutTypes:Bo,getCalloutType:No,registerCalloutType:To,unregisterCalloutType:Io,parseGFMAlert:Mo},e.element.addEventListener("click",o);let i=null;n=e.eventBus.on("content:change",(()=>{clearTimeout(i),i=setTimeout(r,300)})),r(),t=new MutationObserver((()=>{const t=e.element.querySelectorAll(".rmx-callout-body");for(const e of t)e.hasAttribute("contenteditable")})),t.observe(e.element,{childList:!0,subtree:!0})},destroy(){t?.disconnect(),t=null,n?.(),e?.element?.removeEventListener("click",o),e=null}})}function Fo(e,t){const n=window.getSelection();if(!n||0===n.rangeCount)return null;let o=n.anchorNode;for(3===o.nodeType&&(o=o.parentNode);o&&o!==e.element;){if(o.classList?.contains(t))return o;o=o.parentNode}return null}const Po=/(?:https?:\/\/|www\.)[^\s<>"']+/gi,zo=/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g,Oo=/(?:\+?1[-.\s]?)?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}/g;function Go(e){const t=[];let n;for(Po.lastIndex=0;null!==(n=Po.exec(e));)t.push({type:"url",value:n[0],index:n.index});for(zo.lastIndex=0;null!==(n=zo.exec(e));){const e=n.index;t.some((t=>e>=t.index&&e<t.index+t.value.length))||t.push({type:"email",value:n[0],index:n.index})}for(Oo.lastIndex=0;null!==(n=Oo.exec(e));)t.push({type:"phone",value:n[0],index:n.index});return t.sort(((e,t)=>e.index-t.index))}function qo(e){return e.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||"anchor"}let Wo=null;function $o(){Wo&&(Wo.remove(),Wo=null)}function Zo(e){return e?te(e):""}function Uo(e={}){const{onLinkClick:t,onUnfurl:n,onSuggest:o,onBrokenLink:r,validateLink:s,scanInterval:i=6e4,autoLink:a=!0,showPreviews:l=!0}=e;let c=null,d=null,u=null,m=null;const h=/* @__PURE__ */new Map,g=/* @__PURE__ */new Set;function p(e){if(!a||!c)return;if(" "!==e.key&&"Enter"!==e.key)return;const t=window.getSelection();if(!t||0===t.rangeCount||!t.isCollapsed)return;const n=t.getRangeAt(0),o=n.startContainer;if(3!==o.nodeType)return;if(o.parentElement?.closest("a"))return;if(!c.element.contains(o))return;const r=Go(o.textContent.substring(0,n.startOffset));if(0===r.length)return;const s=r[r.length-1],i=s.index+s.value.length;if(i!==n.startOffset)return;e.preventDefault(),c.history.snapshot();const l="email"===(d=s).type?`mailto:${d.value}`:"phone"===d.type?`tel:${d.value.replace(/[^\d+]/g,"")}`:d.value.startsWith("www.")?`https://${d.value}`:d.value;var d;const u=document.createRange();u.setStart(o,s.index),u.setEnd(o,i);const m=document.createElement("a");m.href=l,m.target="_blank",m.rel="noopener noreferrer",m.textContent=s.value,u.deleteContents(),u.insertNode(m);const h=document.createTextNode(" "===e.key?" ":"");if(m.after(h),"Enter"===e.key){const e=document.createElement("br");m.after(e);const n=document.createTextNode("");e.after(n);const o=document.createRange();o.setStart(n,0),o.collapse(!0),t.removeAllRanges(),t.addRange(o)}else{const e=document.createRange();e.setStartAfter(h),e.collapse(!0),t.removeAllRanges(),t.addRange(e)}o.parentNode?.normalize(),c.eventBus.emit("content:change")}function f(e){const n=e.target.closest?.("a[href]");n&&c?.element.contains(n)&&t&&t({href:n.href,text:n.textContent,target:n.target,timestamp:Date.now(),element:n})}function b(e){if(!l||!n)return;const t=e.target.closest?.("a[href]");t&&c?.element.contains(t)&&(clearTimeout(u),u=setTimeout((async()=>{const e=t.href;try{let o=h.get(e);o||(o=await n(e),o&&h.set(e,o)),o&&function(e,t,n){$o();const o=e.getBoundingClientRect(),r=n.getBoundingClientRect();Wo=document.createElement("div"),Wo.className="rmx-link-preview",Wo.innerHTML=`\n ${t.image?`<img class="rmx-link-preview-img" src="${t.image}" alt="" />`:""}\n <div class="rmx-link-preview-text">\n <div class="rmx-link-preview-title">${Zo(t.title||e.href)}</div>\n ${t.description?`<div class="rmx-link-preview-desc">${Zo(t.description)}</div>`:""}\n <div class="rmx-link-preview-url">${Zo(e.href)}</div>\n </div>\n `,Wo.style.position="absolute",Wo.style.left=o.left-r.left+"px",Wo.style.top=o.bottom-r.top+4+"px",n.style.position="relative",n.appendChild(Wo)}(t,o,c.element)}catch{}}),400))}function y(e){const t=e.target.closest?.("a[href]");t&&(clearTimeout(u),$o())}async function v(){if(!c||!s)return;const e=c.element.querySelectorAll("a[href]"),t=/* @__PURE__ */new Set,n=[];for(const o of e){const e=o.href;t.has(e)||e.startsWith("mailto:")||e.startsWith("tel:")||e.startsWith("#")||(t.add(e),n.push({url:e,anchor:o}))}for(let o=0;o<n.length;o+=5){const e=n.slice(o,o+5);await Promise.all(e.map((async({url:e,anchor:t})=>{try{await s(e)?(g.delete(e),t.classList.remove("rmx-link-broken"),t.removeAttribute("data-link-broken")):(g.add(e),t.classList.add("rmx-link-broken"),t.setAttribute("data-link-broken","true"),r?.(e,t))}catch{g.add(e),t.classList.add("rmx-link-broken"),t.setAttribute("data-link-broken","true"),r?.(e,t)}})))}c.eventBus.emit("link:scanComplete",{total:t.size,broken:g.size})}function x(){if(!c||0===g.size)return;const e=c.element.querySelectorAll("a[href]");for(const t of e)g.has(t.href)&&(t.classList.add("rmx-link-broken"),t.setAttribute("data-link-broken","true"))}return _n({name:"advancedLinks",requiresFullAccess:!0,version:"1.0.0",description:"Link previews, broken link detection, auto-linking, analytics, bookmarks",commands:[{name:"insertBookmark",execute(e,t={}){const{name:n,id:o}=t,r=o||qo(n||"bookmark");e.history.snapshot();const s=window.getSelection();if(!s||0===s.rangeCount)return;const i=s.getRangeAt(0),a=document.createElement("a");a.id=r,a.className="rmx-bookmark",a.setAttribute("data-bookmark",r),a.textContent=n?`📌 ${n}`:`📌 ${r}`,a.contentEditable="false",i.collapse(!0),i.insertNode(a);const l=document.createTextNode(" ");return a.after(l),e.eventBus.emit("content:change"),e.eventBus.emit("bookmark:created",{id:r,name:n}),a},meta:{icon:"bookmark",tooltip:"Insert Bookmark Anchor"}},{name:"linkToBookmark",execute(e,t){if(!t)return;const n=e.selection;if(!n.getSelectedText())return;e.history.snapshot();const o=n.wrapWith("a",{href:`#${t}`});o&&o.classList.add("rmx-internal-link"),e.eventBus.emit("content:change")},meta:{icon:"link",tooltip:"Link to Bookmark"}},{name:"getBookmarks",execute(e){const t=e.element.querySelectorAll("[data-bookmark]");return Array.from(t).map((e=>({id:e.getAttribute("data-bookmark"),name:e.textContent.replace(/^\u{1F4CC}\s*/u,""),element:e})))},meta:{tooltip:"List Bookmarks"}},{name:"removeBookmark",execute(e,t){const n=e.element.querySelector(`[data-bookmark="${t}"]`);n&&(e.history.snapshot(),n.remove(),e.eventBus.emit("content:change"),e.eventBus.emit("bookmark:deleted",{id:t}))},meta:{icon:"trash",tooltip:"Remove Bookmark"}},{name:"scanBrokenLinks",execute(){v()},meta:{icon:"scan",tooltip:"Scan for Broken Links"}},{name:"getBrokenLinks",execute:()=>Array.from(g),meta:{tooltip:"Get Broken Links"}}],contextMenuItems:[{label:"Insert Bookmark Here",command:"insertBookmark"}],init(e){c=e,c._links={detectLinks:Go,slugify:qo,getBrokenLinks:()=>Array.from(g),getBookmarks:()=>{const e=c.element.querySelectorAll("[data-bookmark]");return Array.from(e).map((e=>({id:e.getAttribute("data-bookmark"),name:e.textContent.replace(/^\u{1F4CC}\s*/u,"")})))},scanForBrokenLinks:v,clearUnfurlCache:()=>h.clear()},a&&c.element.addEventListener("keydown",p),c.element.addEventListener("click",f),l&&n&&(c.element.addEventListener("mouseover",b),c.element.addEventListener("mouseout",y)),s&&i>0&&(d=setInterval(v,i),setTimeout(v,2e3)),m=c.eventBus.on("content:change",x)},destroy(){a&&c?.element?.removeEventListener("keydown",p),c?.element?.removeEventListener("click",f),c?.element?.removeEventListener("mouseover",b),c?.element?.removeEventListener("mouseout",y),$o(),clearTimeout(u),clearInterval(d),m?.(),h.clear(),g.clear(),c=null}})}const Vo=/\{\{([^{}]+)\}\}/g,jo=/\{\{#if\s+(\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g,Ko=/\{\{#each\s+(\w+)\}\}([\s\S]*?)\{\{\/each\}\}/g;function Xo(e,t){if(!e||!t)return e||"";let n=e;return n=n.replace(Ko,((e,n,o)=>{const r=t[n];return Array.isArray(r)?r.map((e=>{let n=o;return n="object"==typeof e&&null!==e?Xo(o,{...t,...e}):n.replace(/\{\{this\}\}/g,String(e)),n})).join(""):""})),n=n.replace(jo,((e,n,o)=>t[n]?Xo(o,t):"")),n=n.replace(Vo,((e,n)=>{const o=n.trim();return o in t?String(t[o]):`{{${o}}}`})),n}function Jo(e){if(!e)return[];const t=/* @__PURE__ */new Set,n=e.matchAll(/\{\{(?:#(?:if|each)\s+)?(\w+)\}\}/g);for(const o of n)t.add(o[1]);return Array.from(t)}const Yo=/* @__PURE__ */new Map,Qo=[{id:"email",name:"Email",category:"Communication",html:"<p>Dear {{recipient_name}},</p><p>{{body}}</p><p>Best regards,<br>{{sender_name}}<br>{{sender_title}}</p>",sampleData:{recipient_name:"John Doe",body:"Thank you for your interest in our product.",sender_name:"Jane Smith",sender_title:"Sales Manager"}},{id:"invoice",name:"Invoice",category:"Business",html:'<h2>Invoice #{{invoice_number}}</h2><p>Date: {{date}}</p><p>Bill to: <strong>{{client_name}}</strong></p><p>{{client_address}}</p><table class="rmx-table"><thead><tr><th>Item</th><th>Qty</th><th>Price</th></tr></thead><tbody><tr><td>{{item_1}}</td><td>{{qty_1}}</td><td>{{price_1}}</td></tr></tbody></table><p><strong>Total: {{total}}</strong></p>',sampleData:{invoice_number:"INV-001",date:"2026-03-19",client_name:"Acme Corp",client_address:"123 Main St",item_1:"Widget",qty_1:"10",price_1:"$29.99",total:"$299.90"}},{id:"letter",name:"Letter",category:"Communication",html:"<p>{{date}}</p><p>{{recipient_name}}<br>{{recipient_address}}</p><p>Dear {{recipient_name}},</p><p>{{body}}</p><p>Sincerely,<br>{{sender_name}}</p>",sampleData:{date:"March 19, 2026",recipient_name:"John Doe",recipient_address:"456 Oak Ave",body:"I am writing to inform you...",sender_name:"Jane Smith"}},{id:"report",name:"Report",category:"Business",html:"<h1>{{title}}</h1><p><em>Prepared by {{author}} | {{date}}</em></p><h2>Executive Summary</h2><p>{{summary}}</p><h2>Findings</h2><p>{{findings}}</p><h2>Recommendations</h2><p>{{recommendations}}</p>",sampleData:{title:"Q1 2026 Report",author:"Analytics Team",date:"March 2026",summary:"Key findings from Q1...",findings:"Revenue increased by 15%...",recommendations:"Continue investing in..."}},{id:"newsletter",name:"Newsletter",category:"Marketing",html:'<h1>{{newsletter_name}}</h1><p><em>{{edition}} | {{date}}</em></p><hr><h2>{{headline}}</h2><p>{{lead_story}}</p>{{#if has_coupon}}<div class="rmx-callout rmx-callout-success" data-callout="success"><div class="rmx-callout-header" contenteditable="false"><span class="rmx-callout-icon">✅</span><span class="rmx-callout-title">Special Offer</span></div><div class="rmx-callout-body"><p>Use code <strong>{{coupon_code}}</strong> for {{discount}} off!</p></div></div>{{/if}}<p>{{closing}}</p>',sampleData:{newsletter_name:"The Weekly Digest",edition:"Vol. 12",date:"March 19, 2026",headline:"Big News This Week",lead_story:"We are excited to announce...",has_coupon:!0,coupon_code:"SAVE20",discount:"20%",closing:"Thanks for reading!"}}];for(const Li of Qo)Yo.set(Li.id,Li);function er(e){e?.id&&Yo.set(e.id,e)}function tr(e){return Yo.delete(e)}function nr(){return Array.from(Yo.values())}function or(e){return Yo.get(e)}function rr(e){return e.replace(Vo,((e,t)=>{const n=t.trim();return n.startsWith("#")||n.startsWith("/")?e:`<span class="rmx-merge-tag" data-tag="${n}" contenteditable="false">{{${n}}}</span>`}))}function sr(e){return e.replace(/<span[^>]*class="rmx-merge-tag"[^>]*data-tag="([^"]*)"[^>]*>.*?<\/span>/g,((e,t)=>`{{${t}}}`))}function ir(e={}){let t=null,n=!1,o={};return _n({name:"templates",requiresFullAccess:!0,version:"1.0.0",description:"Merge tags, conditional blocks, repeatable sections, live preview, template library",commands:[{name:"insertMergeTag",execute(e,t){if(!t)return;e.history.snapshot();const n=window.getSelection();if(!n||0===n.rangeCount)return;const o=n.getRangeAt(0),r=document.createElement("span");r.className="rmx-merge-tag",r.setAttribute("data-tag",t),r.contentEditable="false",r.textContent=`{{${t}}}`,o.deleteContents(),o.insertNode(r);const s=document.createTextNode(" ");r.after(s),o.setStartAfter(s),o.collapse(!0),n.removeAllRanges(),n.addRange(o),e.eventBus.emit("content:change")},meta:{icon:"tag",tooltip:"Insert Merge Tag"}},{name:"loadTemplate",execute(e,t){const n=Yo.get(t);return n?(e.history.snapshot(),e.element.innerHTML=rr(n.html),o={...n.sampleData||{}},e.eventBus.emit("content:change"),e.eventBus.emit("template:loaded",{id:t,template:n}),n):null},meta:{icon:"template",tooltip:"Load Template"}},{name:"previewTemplate",execute(e,t){if(!t&&0===Object.keys(o).length)return;const r=t||o;o=r;const s=Xo(sr(e.getHTML()),r);n=!0,e._templateBackup=e.element.innerHTML,e.element.innerHTML=s,e.element.contentEditable="false",e.element.classList.add("rmx-template-preview"),e.eventBus.emit("template:preview",{data:r})},meta:{icon:"preview",tooltip:"Preview Template"}},{name:"exitPreview",execute(e){n&&(n=!1,e._templateBackup&&(e.element.innerHTML=e._templateBackup,delete e._templateBackup),e.element.contentEditable="true",e.element.classList.remove("rmx-template-preview"),e.eventBus.emit("template:exitPreview"))},meta:{icon:"edit",tooltip:"Exit Preview"}},{name:"exportTemplate",execute(e){const t=sr(e.getHTML());return{html:t,tags:Jo(t),sampleData:{...o}}},meta:{icon:"export",tooltip:"Export Template"}},{name:"getTemplateTags",execute:e=>Jo(sr(e.getHTML())),meta:{tooltip:"Get Template Tags"}}],contextMenuItems:[{label:"Insert Merge Tag",command:"insertMergeTag"}],init(e){t=e,t._templates={renderTemplate:Xo,extractTags:Jo,getTemplateLibrary:nr,getTemplate:or,registerTemplate:er,unregisterTemplate:tr,textToChips:rr,chipsToText:sr,setPreviewData:e=>{o={...e}},getPreviewData:()=>({...o}),isPreviewMode:()=>n}},destroy(){n&&t&&(t.element.contentEditable="true",t.element.classList.remove("rmx-template-preview")),t=null}})}const ar={"(":")","[":"]","{":"}",'"':'"',"'":"'","`":"`"},lr=new Set(Object.values(ar)),cr="normal",dr="insert",ur="visual";function mr(){return{mode:cr,pending:""}}const hr={"ctrl+a":"moveToLineStart","ctrl+e":"moveToLineEnd","ctrl+k":"killToLineEnd","ctrl+y":"yank","ctrl+w":"killWord","ctrl+f":"moveForward","ctrl+b":"moveBackward","ctrl+n":"moveDown","ctrl+p":"moveUp","ctrl+d":"deleteForward","ctrl+h":"deleteBackward","ctrl+space":"setMark"};function gr(e){const t=e.querySelectorAll("h1, h2, h3, h4, h5, h6");return Array.from(t).map((e=>({level:parseInt(e.tagName.charAt(1),10),text:e.textContent,element:e})))}function pr(e){const t=window.getSelection();if(!t||0===t.rangeCount)return 0;const n=t.toString();if(!n)return 0;const o=t.getRangeAt(t.rangeCount-1).endOffset,r=e.textContent,s=r.indexOf(n,-1===r.indexOf(n,o)?0:o+1);if(-1===s)return t.rangeCount;const i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT);let a=0;for(;i.nextNode();){const e=i.currentNode,o=e.textContent.length;if(a+o>s){const r=s-a,i=document.createRange();i.setStart(e,r),i.setEnd(e,Math.min(r+n.length,o)),t.addRange(i);break}a+=o}return t.rangeCount}function fr(e={}){const{mode:t="default",keyBindings:n={},autoPair:o=!0,jumpToHeading:r=!0}=e;let s=null,i=null,a="";function l(e){if(!s)return;if("vim"===t&&i)return void function(e){if(i.mode===dr)return"Escape"===e.key?(e.preventDefault(),i.mode=cr,s.element.classList.remove("rmx-vim-insert"),s.element.classList.add("rmx-vim-normal"),void s.eventBus.emit("vim:modeChange",{mode:cr})):void(o&&c(e));e.preventDefault();const t=window.getSelection();switch(e.key){case"i":i.mode=dr,s.element.classList.remove("rmx-vim-normal"),s.element.classList.add("rmx-vim-insert"),s.eventBus.emit("vim:modeChange",{mode:dr});break;case"a":if(i.mode=dr,t&&t.rangeCount>0){t.getRangeAt(0).collapse(!1)}s.element.classList.remove("rmx-vim-normal"),s.element.classList.add("rmx-vim-insert"),s.eventBus.emit("vim:modeChange",{mode:dr});break;case"v":i.mode=ur,s.element.classList.add("rmx-vim-visual"),s.eventBus.emit("vim:modeChange",{mode:ur});break;case"Escape":i.mode===ur&&(i.mode=cr,s.element.classList.remove("rmx-vim-visual"),t?.collapseToStart(),s.eventBus.emit("vim:modeChange",{mode:cr}));break;case"h":t?.modify("move","backward","character");break;case"l":t?.modify("move","forward","character");break;case"j":t?.modify("move","forward","line");break;case"k":t?.modify("move","backward","line");break;case"w":t?.modify("move","forward","word");break;case"b":t?.modify("move","backward","word");break;case"0":t?.modify("move","backward","lineboundary");break;case"$":t?.modify("move","forward","lineboundary");break;case"G":if(t&&s.element.lastChild){const e=document.createRange();e.selectNodeContents(s.element.lastChild),e.collapse(!1),t.removeAllRanges(),t.addRange(e)}break;case"u":s.executeCommand("undo");break;case"x":s.history.snapshot(),document.execCommand("delete");break;case"d":if("d"===i.pending){i.pending="",s.history.snapshot();const e=s.selection?.getParentBlock?.();e&&e.remove(),s.eventBus.emit("content:change")}else i.pending="d";break;case"o":s.history.snapshot();{const e=s.selection?.getParentBlock?.()||s.element.lastChild,n=document.createElement("p");n.innerHTML="<br>",e?.after(n);const o=document.createRange();o.selectNodeContents(n),o.collapse(!0),t?.removeAllRanges(),t?.addRange(o)}i.mode=dr,s.element.classList.remove("rmx-vim-normal"),s.element.classList.add("rmx-vim-insert"),s.eventBus.emit("vim:modeChange",{mode:dr}),s.eventBus.emit("content:change");break;default:i.pending=""}}(e);"emacs"===t&&function(e){if(!e.ctrlKey)return;const t=`ctrl+${e.key}`,n=hr[t];if(!n)return;e.preventDefault();const o=window.getSelection(),r=o?.rangeCount>0?o.getRangeAt(0):null;switch(n){case"moveToLineStart":o?.modify("move","backward","lineboundary");break;case"moveToLineEnd":o?.modify("move","forward","lineboundary");break;case"moveForward":o?.modify("move","forward","character");break;case"moveBackward":o?.modify("move","backward","character");break;case"moveDown":o?.modify("move","forward","line");break;case"moveUp":o?.modify("move","backward","line");break;case"deleteForward":document.execCommand("forwardDelete");break;case"deleteBackward":document.execCommand("delete");break;case"killToLineEnd":r&&(s.history.snapshot(),o.modify("extend","forward","lineboundary"),a=o.toString(),r.deleteContents(),s.eventBus.emit("content:change"));break;case"yank":a&&r&&(s.history.snapshot(),r.insertNode(document.createTextNode(a)),r.collapse(!1),s.eventBus.emit("content:change"));break;case"killWord":r&&(s.history.snapshot(),o.modify("extend","backward","word"),a=o.toString(),r.deleteContents(),s.eventBus.emit("content:change"))}}(e);const l=function(e){const t=[];e.ctrlKey&&t.push("ctrl");e.metaKey&&t.push("cmd");e.altKey&&t.push("alt");e.shiftKey&&t.push("shift");1===e.key.length?t.push(e.key.toLowerCase()):t.push(e.key);return t.join("+")}(e);if(!n[l]){if(o&&"vim"!==t&&c(e),r){if((e.metaKey||e.ctrlKey)&&e.shiftKey&&"g"===e.key)return e.preventDefault(),void s.eventBus.emit("keyboard:jumpToHeading")}return!e.metaKey&&!e.ctrlKey||"d"!==e.key||e.shiftKey?void 0:(e.preventDefault(),void pr(s.element))}{e.preventDefault();const t=n[l];"function"==typeof t?t(s):"string"==typeof t&&s.executeCommand(t)}}function c(e){if(1!==e.key.length||e.metaKey||e.ctrlKey||e.altKey)return;const t=window.getSelection();if(!t||0===t.rangeCount)return;const n=t.getRangeAt(0);if(ar[e.key]){const o=ar[e.key];if(!n.collapsed){e.preventDefault();const t=n.toString();return n.deleteContents(),void n.insertNode(document.createTextNode(e.key+t+o))}e.preventDefault();const r=document.createTextNode(e.key+o);return n.insertNode(r),n.setStart(r,1),n.setEnd(r,1),t.removeAllRanges(),t.addRange(n),void s.eventBus.emit("content:change")}if(lr.has(e.key)&&n.collapsed){const o=n.startContainer;if(3===o.nodeType&&o.textContent.charAt(n.startOffset)===e.key)return e.preventDefault(),n.setStart(o,n.startOffset+1),n.collapse(!0),t.removeAllRanges(),void t.addRange(n)}}return _n({name:"keyboard",requiresFullAccess:!0,version:"1.0.0",description:"Vim/Emacs modes, auto-pairing, multi-cursor, jump-to-heading",commands:[{name:"setKeyboardMode",execute(e,t){"vim"===t?(i=mr(),e.element.classList.add("rmx-vim-normal"),e.eventBus.emit("vim:modeChange",{mode:cr})):(i=null,e.element.classList.remove("rmx-vim-normal","rmx-vim-insert","rmx-vim-visual")),e.eventBus.emit("keyboard:modeChange",{mode:t})},meta:{tooltip:"Set Keyboard Mode"}},{name:"getVimMode",execute:()=>i?.mode||null,meta:{tooltip:"Get Vim Mode"}},{name:"jumpToHeading",execute(e,t){!function(e,t){const n=gr(e);if(t<0||t>=n.length)return;const o=n[t];o.element.scrollIntoView?.({behavior:"smooth",block:"center"});const r=window.getSelection(),s=document.createRange();s.selectNodeContents(o.element),s.collapse(!0),r.removeAllRanges(),r.addRange(s)}(e.element,t)},meta:{icon:"heading",tooltip:"Jump to Heading"}},{name:"getHeadings",execute:e=>gr(e.element),meta:{tooltip:"Get Headings"}},{name:"selectNextOccurrence",execute:e=>pr(e.element),shortcut:"mod+d",meta:{tooltip:"Select Next Occurrence"}}],init(e){s=e,"vim"===t&&(i=mr(),s.element.classList.add("rmx-vim-normal")),s.element.addEventListener("keydown",l,!0),s._keyboard={getHeadings:()=>gr(s.element),getVimMode:()=>i?.mode||null,selectNextOccurrence:()=>pr(s.element)}},destroy(){s?.element?.removeEventListener("keydown",l,!0),s?.element?.classList.remove("rmx-vim-normal","rmx-vim-insert","rmx-vim-visual"),i=null,s=null}})}const br="rmx-drop-zone",yr="rmx-drop-zone-active",vr="rmx-drop-indicator",xr="rmx-dragging";function Cr(e,t){const n=Array.from(e.children).filter((e=>!e.classList.contains(vr)&&!e.classList.contains(br)));let o=null,r=1/0,s="after";for(const i of n){const e=i.getBoundingClientRect(),n=e.top+e.height/2,a=Math.abs(t-n);a<r&&(r=a,o=i,s=t<n?"before":"after")}return{element:o,position:s}}function wr(e,t){let n=e;for(;n&&n!==t&&n.parentNode!==t;)n=n.parentNode;return n!==t?n:null}function kr(e={}){const{onDrop:t,onFileDrop:n,allowExternalDrop:o=!0,showDropZone:r=!0,enableReorder:s=!0}=e;let i=null,a=null,l=null,c=null;function d(e){if(!i||!s)return;const t=wr(e.target,i.element);t&&(l=t,t.classList.add(xr),c=t.cloneNode(!0),c.style.cssText="position:fixed;top:-9999px;left:-9999px;opacity:0.6;pointer-events:none;max-width:400px;",document.body.appendChild(c),e.dataTransfer.setDragImage(c,20,20),e.dataTransfer.effectAllowed="move",e.dataTransfer.setData("text/x-remyx-block","true"),e.dataTransfer.setData("text/html",t.outerHTML))}function u(e){if(i&&(e.preventDefault(),e.dataTransfer.dropEffect="move",r&&i.element.classList.add(yr),s&&a)){const{element:t,position:n}=Cr(i.element,e.clientY);if(t){const e=t.getBoundingClientRect(),o=i.element.getBoundingClientRect(),r="before"===n?e.top-o.top-2:e.bottom-o.top+1;a.style.top=`${r}px`,a.style.display="block"}}}function m(e){i&&(i.element.contains(e.relatedTarget)||(i.element.classList.remove(yr),a&&(a.style.display="none")))}function h(e){if(!i)return;if(e.preventDefault(),i.element.classList.remove(yr),a&&(a.style.display="none"),i.history.snapshot(),l&&i.element.contains(l)){const{element:n,position:o}=Cr(i.element,e.clientY);return n&&n!==l&&("before"===o?n.before(l):n.after(l),i.eventBus.emit("content:change"),i.eventBus.emit("dragdrop:reorder",{block:l})),p(),void t?.(e,{type:"reorder"})}if(e.dataTransfer.getData("text/x-remyx-block")){const n=e.dataTransfer.getData("text/html");if(n){const{element:o,position:r}=Cr(i.element,e.clientY),s=document.createElement("div");s.innerHTML=n;const a=document.createDocumentFragment();for(;s.firstChild;)a.appendChild(s.firstChild);o?"before"===r?o.before(a):o.after(a):i.element.appendChild(a),i.eventBus.emit("content:change"),i.eventBus.emit("dragdrop:crossEditor",{}),t?.(e,{type:"crossEditor",html:n})}p()}else{if(o&&e.dataTransfer.files.length>0){const o=Array.from(e.dataTransfer.files);n?.(o),i.eventBus.emit("dragdrop:fileDrop",{files:o});for(const t of o)if(t.type.startsWith("image/")){const n=new FileReader;n.onload=()=>{const t=document.createElement("img");t.src=n.result,t.style.maxWidth="100%";const{element:o,position:r}=Cr(i.element,e.clientY);o?"before"===r?o.before(t):o.after(t):i.element.appendChild(t),i.eventBus.emit("content:change")},n.readAsDataURL(t)}return p(),void t?.(e,{type:"file",files:o})}if(o){const n=e.dataTransfer.getData("text/html"),o=e.dataTransfer.getData("text/plain"),r=n||(o?`<p>${o.replace(/\n/g,"</p><p>")}</p>`:"");if(r){const{element:n,position:o}=Cr(i.element,e.clientY),s=document.createElement("div");s.innerHTML=r;const a=document.createDocumentFragment();for(;s.firstChild;)a.appendChild(s.firstChild);n?"before"===o?n.before(a):n.after(a):i.element.appendChild(a),i.eventBus.emit("content:change"),i.eventBus.emit("dragdrop:externalDrop",{html:r}),t?.(e,{type:"external",html:r})}}p()}}function g(){p()}function p(){l&&(l.classList.remove(xr),l=null),c&&(c.remove(),c=null),i?.element?.classList.remove(yr),a&&(a.style.display="none")}function f(e){if(!i||!s)return;const t=wr(e.target,i.element);if(!t)return;const n=t.getBoundingClientRect();e.clientX-n.left<30&&(t.draggable=!0,t.addEventListener("dragend",(()=>{t.draggable=!1}),{once:!0}))}return _n({name:"dragDrop",requiresFullAccess:!0,version:"1.0.0",description:"Drop zones, cross-editor drag, file drops, block reorder, ghost previews",commands:[{name:"moveBlockUp",execute(e){const t=e.selection?.getParentBlock?.();if(!t)return;let n=t;for(;n.parentNode!==e.element;)n=n.parentNode;const o=n.previousElementSibling;o&&(e.history.snapshot(),o.before(n),e.eventBus.emit("content:change"))},shortcut:"mod+shift+ArrowUp",meta:{icon:"arrow-up",tooltip:"Move Block Up"}},{name:"moveBlockDown",execute(e){const t=e.selection?.getParentBlock?.();if(!t)return;let n=t;for(;n.parentNode!==e.element;)n=n.parentNode;const o=n.nextElementSibling;o&&(e.history.snapshot(),o.after(n),e.eventBus.emit("content:change"))},shortcut:"mod+shift+ArrowDown",meta:{icon:"arrow-down",tooltip:"Move Block Down"}}],init(e){i=e,s&&(a=function(){const e=document.createElement("div");return e.className=vr,e.style.cssText="position:absolute;left:0;right:0;height:3px;background:var(--rmx-primary,#6366f1);border-radius:2px;pointer-events:none;z-index:100;transition:top 0.1s ease;",e}(),a.style.display="none",i.element.style.position="relative",i.element.appendChild(a)),i.element.addEventListener("dragstart",d),i.element.addEventListener("dragover",u),i.element.addEventListener("dragleave",m),i.element.addEventListener("drop",h),i.element.addEventListener("dragend",g),i.element.addEventListener("mousedown",f),r&&i.element.classList.add(br),i._dragDrop={getDropTarget:e=>Cr(i.element,e)}},destroy(){i?.element?.removeEventListener("dragstart",d),i?.element?.removeEventListener("dragover",u),i?.element?.removeEventListener("dragleave",m),i?.element?.removeEventListener("drop",h),i?.element?.removeEventListener("dragend",g),i?.element?.removeEventListener("mousedown",f),a?.remove(),p(),i?.element?.classList.remove(br,yr),i=null}})}const _r=[{category:"Greek",symbols:[{label:"α",latex:"\\alpha"},{label:"β",latex:"\\beta"},{label:"γ",latex:"\\gamma"},{label:"δ",latex:"\\delta"},{label:"ε",latex:"\\epsilon"},{label:"θ",latex:"\\theta"},{label:"λ",latex:"\\lambda"},{label:"μ",latex:"\\mu"},{label:"π",latex:"\\pi"},{label:"σ",latex:"\\sigma"},{label:"φ",latex:"\\phi"},{label:"ω",latex:"\\omega"},{label:"Δ",latex:"\\Delta"},{label:"Σ",latex:"\\Sigma"},{label:"Ω",latex:"\\Omega"}]},{category:"Operators",symbols:[{label:"±",latex:"\\pm"},{label:"×",latex:"\\times"},{label:"÷",latex:"\\div"},{label:"≠",latex:"\\neq"},{label:"≤",latex:"\\leq"},{label:"≥",latex:"\\geq"},{label:"∞",latex:"\\infty"},{label:"≈",latex:"\\approx"},{label:"√",latex:"\\sqrt{}"},{label:"∑",latex:"\\sum"},{label:"∏",latex:"\\prod"},{label:"∫",latex:"\\int"}]},{category:"Arrows",symbols:[{label:"←",latex:"\\leftarrow"},{label:"→",latex:"\\rightarrow"},{label:"↔",latex:"\\leftrightarrow"},{label:"⇒",latex:"\\Rightarrow"},{label:"⇔",latex:"\\Leftrightarrow"},{label:"↑",latex:"\\uparrow"},{label:"↓",latex:"\\downarrow"}]},{category:"Common",symbols:[{label:"²",latex:"^{2}"},{label:"³",latex:"^{3}"},{label:"xⁿ",latex:"^{n}"},{label:"x₁",latex:"_{1}"},{label:"∀",latex:"\\forall"},{label:"∃",latex:"\\exists"},{label:"∈",latex:"\\in"},{label:"⊂",latex:"\\subset"},{label:"∪",latex:"\\cup"},{label:"∩",latex:"\\cap"},{label:"frac",latex:"\\frac{}{}"},{label:"∂",latex:"\\partial"}]}];function Sr(){return _r}const Ar=new RegExp("(?<!\\$)\\$(?!\\$)(.+?)(?<!\\$)\\$(?!\\$)","g"),Er=/\$\$([\s\S]+?)\$\$/g;function Lr(e){if(!e)return[];const t=[];let n;for(Er.lastIndex=0;null!==(n=Er.exec(e));)t.push({type:"block",src:n[1].trim(),index:n.index,length:n[0].length});for(Ar.lastIndex=0;null!==(n=Ar.exec(e));)t.some((e=>n.index>=e.index&&n.index<e.index+e.length))||t.push({type:"inline",src:n[1].trim(),index:n.index,length:n[0].length});return t.sort(((e,t)=>e.index-t.index))}function Tr(e){return`<math xmlns="http://www.w3.org/1998/Math/MathML">${e.replace(/\\frac\{([^}]*)\}\{([^}]*)\}/g,"<mfrac><mrow>$1</mrow><mrow>$2</mrow></mfrac>").replace(/\\sqrt\{([^}]*)\}/g,"<msqrt><mrow>$1</mrow></msqrt>").replace(/\^{([^}]*)}/g,"<msup><mo></mo><mn>$1</mn></msup>").replace(/_{([^}]*)}/g,"<msub><mo></mo><mn>$1</mn></msub>").replace(/\\sum/g,"<mo>&sum;</mo>").replace(/\\prod/g,"<mo>&prod;</mo>").replace(/\\int/g,"<mo>&int;</mo>").replace(/\\infty/g,"<mo>&infin;</mo>").replace(/\\alpha/g,"<mi>&alpha;</mi>").replace(/\\beta/g,"<mi>&beta;</mi>").replace(/\\pi/g,"<mi>&pi;</mi>")}</math>`}function Ir(e,t){return`<code class="rmx-math-latex">${ee(e)}</code>`}function Br(e={}){const{renderMath:t=Ir,autoRender:n=!0,numbering:o=!0}=e;let r=null,s=null,i=0;function a(e){const n=e.getAttribute("data-math-src");if(!n)return;const r=e.classList.contains("rmx-math-block"),s=t(n,r);if(e.innerHTML=s,r&&o){const t=e.getAttribute("data-equation-number");if(t){const n=document.createElement("span");n.className="rmx-equation-number",n.textContent=`(${t})`,e.appendChild(n)}}}function l(){if(!r)return;r.element.querySelectorAll("[data-math-src]").forEach(a)}return _n({name:"math",requiresFullAccess:!0,version:"1.0.0",description:"LaTeX/KaTeX math rendering, symbol palette, equation numbering",commands:[{name:"insertMath",execute(e,n={}){const{latex:r="",displayMode:s=!1}=n;e.history.snapshot(),i++;const a=function(e,n,r){const s=n?"div":"span",i=document.createElement(s);if(i.className="rmx-math "+(n?"rmx-math-block":"rmx-math-inline"),i.setAttribute("data-math","latex"),i.setAttribute("data-math-src",e),i.contentEditable="false",n&&o&&r&&i.setAttribute("data-equation-number",String(r)),i.innerHTML=t(e,n),n&&o&&r){const e=document.createElement("span");e.className="rmx-equation-number",e.textContent=`(${r})`,i.appendChild(e)}return i}(r,s,s?i:null),l=window.getSelection();if(l&&l.rangeCount>0){const e=l.getRangeAt(0);e.deleteContents(),e.insertNode(a);const t=document.createTextNode(" ");a.after(t),e.setStartAfter(t),e.collapse(!0),l.removeAllRanges(),l.addRange(e)}return e.eventBus.emit("content:change"),a},meta:{icon:"math",tooltip:"Insert Math Equation"}},{name:"editMath",execute(e,{element:t,latex:n}){t&&n&&(e.history.snapshot(),t.setAttribute("data-math-src",n),a(t),e.eventBus.emit("content:change"))},meta:{tooltip:"Edit Math Equation"}},{name:"insertSymbol",execute(e,t){if(!t)return;const n=window.getSelection();if(!n||0===n.rangeCount)return;const o=n.getRangeAt(0);o.deleteContents(),o.insertNode(document.createTextNode(t)),o.collapse(!1),e.eventBus.emit("content:change")},meta:{icon:"symbol",tooltip:"Insert Symbol"}},{name:"getSymbolPalette",execute:()=>Sr(),meta:{tooltip:"Get Symbol Palette"}},{name:"getMathElements",execute(e){const t=e.element.querySelectorAll("[data-math-src]");return Array.from(t).map(((e,t)=>({index:t,src:e.getAttribute("data-math-src"),displayMode:e.classList.contains("rmx-math-block"),equationNumber:e.getAttribute("data-equation-number"),element:e})))},meta:{tooltip:"Get Math Elements"}},{name:"copyMathAs",execute(e,{element:t,format:n="latex"}){if(!t)return null;const o=t.getAttribute("data-math-src");return o?"latex"===n?o:"mathml"===n?Tr(o):o:null},meta:{tooltip:"Copy Math As Format"}}],contextMenuItems:[{label:"Insert Inline Math",command:"insertMath"}],init(e){r=e,r._math={getSymbolPalette:Sr,parseMathExpressions:Lr,latexToMathML:Tr,renderAllMath:l,getEquationCount:()=>i},r.element.addEventListener("dblclick",(e=>{const t=e.target.closest("[data-math-src]");t&&r.eventBus.emit("math:edit",{element:t,src:t.getAttribute("data-math-src"),displayMode:t.classList.contains("rmx-math-block")})})),s=new MutationObserver((()=>l())),s.observe(r.element,{childList:!0,subtree:!0}),l()},destroy(){s?.disconnect(),r=null}})}let Nr=0;function Rr(e,t={}){const{numbering:n=!0}=t,o=e.querySelectorAll("h1, h2, h3, h4, h5, h6"),r=[];for(const a of o){if(!a.id){const e=a.textContent.toLowerCase().replace(/[^\w\s-]/g,"").replace(/\s+/g,"-").replace(/-+/g,"-")||"heading-"+ ++Nr;a.id=e}r.push({id:a.id,text:a.textContent,level:parseInt(a.tagName.charAt(1),10),element:a,children:[],number:""})}const s=[],i=[];for(const a of r){for(;i.length>0&&i[i.length-1].level>=a.level;)i.pop();0===i.length?s.push(a):i[i.length-1].item.children.push(a),i.push({item:a,level:a.level})}return n&&Mr(s,""),s}function Mr(e,t){e.forEach(((e,n)=>{e.number=t?`${t}.${n+1}`:String(n+1),Mr(e.children,e.number)}))}function Dr(e){const t=[];return function e(n){for(const o of n)t.push(o),e(o.children)}(e),t}function Hr(e,t={}){const{numbering:n=!0,linkPrefix:o="#"}=t;return`<nav class="rmx-toc" role="navigation" aria-label="Table of Contents"><ul>${function e(t){return 0===t.length?"":t.map((t=>{const r=n&&t.number?`<span class="rmx-toc-number">${t.number}</span> `:"",s=t.children.length>0?`<ul>${e(t.children)}</ul>`:"";return`<li><a href="${o}${t.id}" class="rmx-toc-link">${r}${ee(t.text)}</a>${s}</li>`})).join("")}(e)}</ul></nav>`}function Fr(e){const t=[];for(let n=1;n<e.length;n++){const o=e[n-1].level,r=e[n].level;r>o+1&&t.push({message:`Heading level skipped: H${o} → H${r} (expected H${o+1})`,element:e[n].element})}return t}function Pr(e={}){const{onOutlineChange:t,numbering:n=!0,collapsible:o=!0}=e;let r=null,s=null,i=[],a=null;function l(){r&&(i=Rr(r.element,{numbering:n}),r.eventBus.emit("toc:change",{outline:i}),t?.(i))}return _n({name:"toc",requiresFullAccess:!0,version:"1.0.0",description:"Auto-generated table of contents, document outline, heading validation",commands:[{name:"getOutline",execute:e=>Rr(e.element,{numbering:n}),meta:{tooltip:"Get Document Outline"}},{name:"insertToc",execute(e){e.history.snapshot();const t=Hr(Rr(e.element,{numbering:n}),{numbering:n}),o=window.getSelection();if(o&&o.rangeCount>0){const e=o.getRangeAt(0),n=document.createElement("div");n.innerHTML=t;const r=document.createDocumentFragment();for(;n.firstChild;)r.appendChild(n.firstChild);e.deleteContents(),e.insertNode(r)}e.eventBus.emit("content:change")},meta:{icon:"toc",tooltip:"Insert Table of Contents"}},{name:"scrollToHeading",execute(e,t){const n=e.element.querySelector(`#${CSS.escape(t)}`);if(n){n.scrollIntoView?.({behavior:"smooth",block:"start"});const e=window.getSelection(),t=document.createRange();t.selectNodeContents(n),t.collapse(!0),e.removeAllRanges(),e.addRange(t)}},meta:{icon:"scroll",tooltip:"Scroll to Heading"}},{name:"validateHeadings",execute:e=>Fr(Dr(Rr(e.element,{numbering:!1}))),meta:{tooltip:"Validate Heading Hierarchy"}}],init(e){r=e,r._toc={buildOutline:()=>Rr(r.element,{numbering:n}),flattenOutline:Dr,renderTocHTML:Hr,validateHeadingHierarchy:Fr,getOutline:()=>i},s=r.eventBus.on("content:change",(()=>{clearTimeout(a),a=setTimeout(l,200)})),r.element.addEventListener("click",(e=>{const t=e.target.closest(".rmx-toc-link");if(t){e.preventDefault();const n=t.getAttribute("href")?.replace("#","");if(n){const e=r.element.querySelector(`#${CSS.escape(n)}`);e?.scrollIntoView?.({behavior:"smooth",block:"start"})}}})),l()},destroy(){clearTimeout(a),s?.(),r=null}})}function zr(e){if(!(e=e.toLowerCase().replace(/[^a-z]/g,"")))return 0;if(e.length<=3)return 1;const t=(e=(e=e.replace(/(?:[^laeiouy]es|ed|[^laeiouy]e)$/,"")).replace(/^y/,"")).match(/[aeiouy]{1,2}/g);return t?t.length:1}function Or(e){return e?e.split(new RegExp("(?<=[.!?])\\s+")).map((e=>e.trim())).filter((e=>e.length>0)):[]}function Gr(e){return e.trim().split(/\s+/).filter((e=>e.length>0))}function qr(e){return 0===e.sentences||0===e.words?0:e.words/e.sentences*.39+e.syllables/e.words*11.8-15.59}function Wr(e){return 0===e.sentences||0===e.words?0:206.835-e.words/e.sentences*1.015-e.syllables/e.words*84.6}function $r(e){return 0===e.sentences||0===e.words?0:.4*(e.words/e.sentences+e.complexWords/e.words*100)}function Zr(e){if(0===e.words)return 0;return.0588*(e.chars/e.words*100)-.296*(e.sentences/e.words*100)-15.8}function Ur(e){return e<=6?"basic":e<=12?"intermediate":"advanced"}function Vr(e,t={}){const{wordsPerMinute:n=200,targetWordCount:o=0,maxSentenceLength:r=30,maxParagraphLength:s=150}=t,i=Gr(e),a=Or(e),l=function(e){return e.split(/\n\s*\n/).map((e=>e.trim())).filter((e=>e.length>0))}(e),c=e.replace(/\s/g,"").length;let d=0,u=0;for(const k of i){const e=zr(k);d+=e,e>=3&&u++}const m={words:i.length,sentences:a.length,syllables:d,complexWords:u,chars:c},h=qr(m),g=Wr(m),p=$r(m),f=Zr(m),b=Ur(h),y=i.length/n,v=Math.round(60*y),x=a.map(((e,t)=>({index:t,text:e,wordCount:Gr(e).length}))).filter((e=>e.wordCount>r)),C=l.map(((e,t)=>({index:t,text:e.substring(0,100)+(e.length>100?"...":""),wordCount:Gr(e).length}))).filter((e=>e.wordCount>s)),w=o>0?{target:o,current:i.length,percentage:Math.round(i.length/o*100)}:null;return{wordCount:i.length,charCount:c,sentenceCount:a.length,paragraphCount:l.length,syllableCount:d,complexWordCount:u,readability:{fleschKincaid:Math.round(10*h)/10,fleschReadingEase:Math.round(10*g)/10,gunningFog:Math.round(10*p)/10,colemanLiau:Math.round(10*f)/10,vocabularyLevel:b},readingTime:{minutes:Math.ceil(y),seconds:v,wordsPerMinute:n},warnings:{longSentences:x,longParagraphs:C},goalProgress:w}}function jr(e,t){if(!e||!t)return{count:0,density:0,positions:[]};const n=Gr(e),o=t.toLowerCase(),r=[];let s=0;return n.forEach(((e,t)=>{e.toLowerCase()===o&&(s++,r.push(t))})),{count:s,density:n.length>0?Math.round(s/n.length*1e4)/100:0,positions:r}}function Kr(e,t,n){const o=Gr(e),r=t.querySelectorAll("h1, h2, h3, h4, h5, h6"),s=t.querySelectorAll("h1").length,i=[];0===s&&i.push("Missing H1 heading"),s>1&&i.push("Multiple H1 headings — consider using only one"),o.length<300&&i.push("Content is short — aim for 300+ words for SEO"),0===r.length&&i.push("No headings — add headings to improve content structure");let a=null;return n&&(a=jr(e,n),a.density<.5&&i.push(`Keyword "${n}" density is low (${a.density}%) — aim for 1-3%`),a.density>3&&i.push(`Keyword "${n}" density is high (${a.density}%) — may be over-optimized`)),{wordCount:o.length,headingCount:r.length,h1Count:s,keywordInfo:a,hints:i}}function Xr(e={}){const{wordsPerMinute:t=200,targetWordCount:n=0,onAnalytics:o,maxSentenceLength:r=30,maxParagraphLength:s=150}=e;let i=null,a=null,l=null,c=null,d=null;function u(){if(!i)return;const e=i.getText();e===d&&c||(d=e,c=Vr(e,{wordsPerMinute:t,targetWordCount:n,maxSentenceLength:r,maxParagraphLength:s}),i.eventBus.emit("analytics:update",c),o?.(c))}return _n({name:"analytics",requiresFullAccess:!0,version:"1.0.0",description:"Readability scores, reading time, vocabulary level, SEO hints",commands:[{name:"toggleAnalytics",execute:e=>(e._analyticsVisible=!e._analyticsVisible,e.eventBus.emit("analytics:toggle",{visible:e._analyticsVisible}),e._analyticsVisible),meta:{icon:"analytics",tooltip:"Toggle Analytics Panel"}},{name:"getAnalytics",execute:e=>Vr(e.getText(),{wordsPerMinute:t,targetWordCount:n,maxSentenceLength:r,maxParagraphLength:s}),meta:{tooltip:"Get Content Analytics"}},{name:"getSeoAnalysis",execute:(e,t)=>Kr(e.getText(),e.element,t),meta:{tooltip:"Get SEO Analysis"}},{name:"getKeywordDensity",execute:(e,t)=>jr(e.getText(),t),meta:{tooltip:"Get Keyword Density"}}],init(e){i=e,i._analytics={analyzeContent:()=>Vr(i.getText(),{wordsPerMinute:t,targetWordCount:n,maxSentenceLength:r,maxParagraphLength:s}),seoAnalysis:e=>Kr(i.getText(),i.element,e),keywordDensity:e=>jr(i.getText(),e),getStats:()=>c,countSyllables:zr,fleschKincaid:qr,gunningFog:$r,colemanLiau:Zr},a=i.eventBus.on("content:change",(()=>{clearTimeout(l),l=setTimeout(u,300)})),u()},destroy(){clearTimeout(l),a?.(),i=null}})}const Jr=/\b(was|were|been|being|is|are|am|get|gets|got|gotten)\b/i,Yr=/\b\w+(ed|en|wn|nt|ht|lt)\b/i;function Qr(e){const t=[],n=e.split(/(\s+)/);let o=0;for(let r=0;r<n.length;r++){const s=n[r];if(/^\s+$/.test(s))o+=s.length;else{if(Jr.test(s)){let i=r+1;for(;i<n.length&&/^\s+$/.test(n[i]);)i++;if(i<n.length&&Yr.test(n[i])){const a=o;let l=o+s.length;for(let e=r+1;e<=i;e++)l+=n[e].length;const c=e.slice(a,l);t.push({offset:a,length:l-a,message:`Passive voice detected: "${c}". Consider using active voice.`,suggestions:[],type:"grammar",rule:"passive-voice"})}}o+=s.length}}return t}const es=[{pattern:/\bin order to\b/gi,replacement:"to",message:'"in order to" can be simplified to "to"'},{pattern:/\bat this point in time\b/gi,replacement:"now",message:'"at this point in time" can be simplified to "now"'},{pattern:/\bdue to the fact that\b/gi,replacement:"because",message:'"due to the fact that" can be simplified to "because"'},{pattern:/\bin the event that\b/gi,replacement:"if",message:'"in the event that" can be simplified to "if"'},{pattern:/\bfor the purpose of\b/gi,replacement:"to",message:'"for the purpose of" can be simplified to "to"'},{pattern:/\bin the near future\b/gi,replacement:"soon",message:'"in the near future" can be simplified to "soon"'},{pattern:/\bat the present time\b/gi,replacement:"now",message:'"at the present time" can be simplified to "now"'},{pattern:/\bin spite of the fact that\b/gi,replacement:"although",message:'"in spite of the fact that" can be simplified to "although"'},{pattern:/\bwith regard to\b/gi,replacement:"about",message:'"with regard to" can be simplified to "about"'},{pattern:/\bin close proximity\b/gi,replacement:"near",message:'"in close proximity" can be simplified to "near"'},{pattern:/\ba large number of\b/gi,replacement:"many",message:'"a large number of" can be simplified to "many"'},{pattern:/\bhas the ability to\b/gi,replacement:"can",message:'"has the ability to" can be simplified to "can"'},{pattern:/\bis able to\b/gi,replacement:"can",message:'"is able to" can be simplified to "can"'},{pattern:/\bit is important to note that\b/gi,replacement:"(remove)",message:'"it is important to note that" is unnecessary filler'},{pattern:/\bneedless to say\b/gi,replacement:"(remove)",message:'"needless to say" is unnecessary — just say it'},{pattern:/\beach and every\b/gi,replacement:"each",message:'"each and every" can be simplified to "each" or "every"'},{pattern:/\bfirst and foremost\b/gi,replacement:"first",message:'"first and foremost" can be simplified to "first"'},{pattern:/\bbasically\b/gi,replacement:"(remove)",message:'"basically" is often unnecessary filler'},{pattern:/\bvery unique\b/gi,replacement:"unique",message:'"unique" is absolute — "very" is redundant'},{pattern:/\bcompletely eliminate\b/gi,replacement:"eliminate",message:'"eliminate" is absolute — "completely" is redundant'}];function ts(e){const t=[];for(const n of es){let o;const r=new RegExp(n.pattern.source,n.pattern.flags);for(;null!==(o=r.exec(e));)t.push({offset:o.index,length:o[0].length,message:n.message,suggestions:"(remove)"===n.replacement?[]:[n.replacement],type:"style",rule:"wordiness"})}return t}const ns=["at the end of the day","think outside the box","low-hanging fruit","move the needle","take it to the next level","game changer","paradigm shift","synergy","it goes without saying","avoid it like the plague","better late than never","the bottom line","by the same token","crystal clear","few and far between","hit the ground running","in a nutshell","level playing field","read between the lines","reinvent the wheel","tip of the iceberg","win-win situation","back to the drawing board","bite the bullet","cutting edge","pushing the envelope","raise the bar","on the same page","circle back","deep dive","best practice","leverage","ecosystem","robust","scalable solution"];function os(e){const t=[],n=e.toLowerCase();for(const o of ns){let r=n.indexOf(o);for(;-1!==r;)t.push({offset:r,length:o.length,message:`Cliche detected: "${e.slice(r,r+o.length)}". Consider using more original phrasing.`,suggestions:[],type:"style",rule:"cliche"}),r=n.indexOf(o,r+o.length)}return t}function rs(e){const t=[];let n;const o=/ +/g;for(;null!==(n=o.exec(e));)0!==n.index&&"\n"!==e[n.index-1]&&t.push({offset:n.index,length:n[0].length,message:"Multiple consecutive spaces detected.",suggestions:[" "],type:"grammar",rule:"double-space"});const r=/([.,!?;:])\1+/g;for(;null!==(n=r.exec(e));)"..."!==n[0]&&".."!==n[0]&&t.push({offset:n.index,length:n[0].length,message:`Repeated punctuation: "${n[0]}"`,suggestions:[n[1]],type:"grammar",rule:"repeated-punctuation"});const s=/[.!?,;:](?=[A-Za-z])/g;for(;null!==(n=s.exec(e));){const o=e.slice(Math.max(0,n.index-4),n.index+1);/\b[A-Z]\.$/.test(o)||/[a-z]\.[a-z]/.test(o)||/https?:/.test(o)||t.push({offset:n.index,length:2,message:"Missing space after punctuation.",suggestions:[e[n.index]+" "+e[n.index+1]],type:"grammar",rule:"missing-space"})}return t}const ss={formal:{passiveVoice:!0,wordiness:!0,cliches:!0,punctuation:!0},casual:{passiveVoice:!1,wordiness:!1,cliches:!0,punctuation:!0},technical:{passiveVoice:!0,wordiness:!1,cliches:!1,punctuation:!0},academic:{passiveVoice:!0,wordiness:!0,cliches:!1,punctuation:!0}};function is(e,t={}){if(!e)return[];const n=ss[t.stylePreset]||ss.formal,o=t.passiveVoice??n.passiveVoice,r=t.wordiness??n.wordiness,s=t.cliches??n.cliches,i=t.punctuation??n.punctuation,a=[];return o&&a.push(...Qr(e)),r&&a.push(...ts(e)),s&&a.push(...os(e)),i&&a.push(...rs(e)),a.sort(((e,t)=>e.offset-t.offset)),a}function as(e){const t={total:e.length,grammar:0,style:0,byRule:{}};for(const n of e)"grammar"===n.type?t.grammar++:t.style++,t.byRule[n.rule]=(t.byRule[n.rule]||0)+1;return t}const ls="rmx-spellcheck-dictionary",cs="rmx-spellcheck-ignored";function ds(){try{const e=localStorage.getItem(ls);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function us(e){try{localStorage.setItem(ls,JSON.stringify(e))}catch{}}function ms(e={}){const{language:t="en-US",enabled:n=!0,grammarRules:o=!0,stylePreset:r="formal",customService:s=null,dictionary:i=[],persistent:a=!0,onError:l,onCorrection:c}=e;let d=null,u=n,m=r,h=t,g=null,p=[],f=null,b=null;const y=/* @__PURE__ */new Set([...i,...a?ds():[]]),v=a?function(){try{const e=localStorage.getItem(cs);if(!e)/* @__PURE__ */return new Set;const t=JSON.parse(e);return new Set(Array.isArray(t)?t:[])}catch{/* @__PURE__ */
2
+ return new Set}}():/* @__PURE__ */new Set;function x(){if(!d)return;const e=d.element.querySelectorAll(".rmx-spelling-error, .rmx-grammar-error, .rmx-style-suggestion");for(const t of e){const e=t.parentNode;for(;t.firstChild;)e.insertBefore(t.firstChild,t);e.removeChild(t),e.normalize()}}async function C(){if(!d||!u)return[];const e=d.getText();if(!e.trim())return p=[],d.eventBus.emit("spellcheck:update",{errors:[],stats:as([])}),[];let t=[];if(o){const n=is(e,{stylePreset:m});t.push(...n)}if(s?.check)try{const n=await s.check(e);Array.isArray(n)&&t.push(...n)}catch(r){d.eventBus.emit("spellcheck:error",{error:r})}t=t.filter((t=>{const n=e.slice(t.offset,t.offset+t.length).toLowerCase();return!y.has(n)&&!v.has(n)})),t.sort(((e,t)=>e.offset-t.offset)),p=t,x(),function(e){if(!d||0===e.length)return;d.getText();const t=document.createTreeWalker(d.element,NodeFilter.SHOW_TEXT,null),n=[];let o,r=0;for(;o=t.nextNode();)n.push({node:o,start:r,end:r+o.textContent.length}),r+=o.textContent.length;const s=[...e].sort(((e,t)=>t.offset-e.offset));for(const i of s){const e=i.offset+i.length;let t=null,o=null,r=0,s=0;for(const a of n)if(!t&&a.end>i.offset&&(t=a,r=i.offset-a.start),a.end>=e){o=a,s=e-a.start;break}if(t&&o&&t.node===o.node)try{const e=document.createRange();e.setStart(t.node,r),e.setEnd(o.node,s);const n="spelling"===i.type?"rmx-spelling-error":"grammar"===i.type?"rmx-grammar-error":"rmx-style-suggestion",a=document.createElement("span");a.className=n,a.setAttribute("data-spellcheck-message",i.message),a.setAttribute("data-spellcheck-suggestions",JSON.stringify(i.suggestions||[])),a.setAttribute("data-spellcheck-type",i.type),a.setAttribute("title",i.message),e.surroundContents(a)}catch{}}}(t);const n=as(t);return d.eventBus.emit("spellcheck:update",{errors:t,stats:n}),d.eventBus.emit("grammar:check",{errors:t,stats:n}),l?.(t),t}function w(){clearTimeout(g),g=setTimeout(C,500)}function k(e){if(!e)return;const t=e.toLowerCase();y.add(t),a&&us([...y]),d?.eventBus.emit("spellcheck:dictionary:add",{word:t}),w()}function _(e){y.delete(e.toLowerCase()),a&&us([...y]),w()}function S(){return[...y]}function A(e){if(!e)return;const t=e.toLowerCase();v.add(t),a&&function(e){try{localStorage.setItem(cs,JSON.stringify([...e]))}catch{}}(v),d?.eventBus.emit("spellcheck:ignored:add",{word:t}),w()}function E(){return[...v]}function L(e,t){if(!d||!e)return;const n=e.textContent;d.history.snapshot();const o=document.createTextNode(t);e.parentNode.replaceChild(o,e),o.parentNode.normalize(),d.eventBus.emit("content:change"),d.eventBus.emit("spellcheck:correction",{original:n,replacement:t}),c?.({original:n,replacement:t}),w()}function T(e){ss[e]&&(m=e,d?.eventBus.emit("spellcheck:style:change",{preset:e}),w())}function I(){return m}function B(e){h=e,d?.element&&d.element.setAttribute("lang",e),d?.eventBus.emit("spellcheck:language:change",{language:e}),w()}function N(){return h}function R(){return{...as(p),enabled:u,stylePreset:m,language:h,dictionarySize:y.size,ignoredCount:v.size}}function M(e){const t=e.target.closest?.(".rmx-spelling-error, .rmx-grammar-error, .rmx-style-suggestion");if(!t)return;e.preventDefault();const n=t.getAttribute("data-spellcheck-message")||"",o=t.getAttribute("data-spellcheck-suggestions")||"[]",r=t.getAttribute("data-spellcheck-type")||"grammar";let s=[];try{s=JSON.parse(o)}catch{}const i=t.textContent,a=t.getBoundingClientRect();d.eventBus.emit("spellcheck:contextmenu",{word:i,message:n,suggestions:s,type:r,rect:a,mark:t,applyCorrection:e=>L(t,e),ignoreWord:()=>A(i),addToDictionary:()=>k(i)})}return _n({name:"spellcheck",requiresFullAccess:!0,version:"1.0.0",description:"Spelling & grammar checking with inline underlines, writing-style presets, and custom service integration",commands:[{name:"toggleSpellcheck",execute:e=>(u=!u,u?(e.element.setAttribute("spellcheck","true"),w()):(e.element.setAttribute("spellcheck","false"),x(),p=[],e.eventBus.emit("spellcheck:update",{errors:[],stats:as([])})),e.eventBus.emit("spellcheck:toggle",{enabled:u}),u),meta:{icon:"spellcheck",tooltip:"Toggle Spellcheck"}},{name:"checkGrammar",execute:async e=>C(),meta:{icon:"spellcheck",tooltip:"Check Grammar"}},{name:"addToDictionary",execute(e,t){k(t)},meta:{tooltip:"Add to Dictionary"}},{name:"ignoreWord",execute(e,t){A(t)},meta:{tooltip:"Ignore Word"}},{name:"setWritingStyle",execute:(e,t)=>(T(t),t),meta:{tooltip:"Set Writing Style"}},{name:"getSpellcheckStats",execute:e=>R(),meta:{tooltip:"Get Spellcheck Stats"}}],contextMenuItems:[{label:"Check Grammar",command:"checkGrammar",when:()=>u}],init(e){d=e,d._spellcheck={runCheck:C,clearMarks:x,addToDictionary:k,removeFromDictionary:_,getDictionary:S,ignoreWord:A,getIgnoredWords:E,applyCorrection:L,setWritingStyle:T,getWritingStyle:I,setLanguage:B,getLanguage:N,getErrors:()=>[...p],getStats:R,isEnabled:()=>u},d.element.setAttribute("spellcheck",u?"true":"false"),d.element.setAttribute("lang",h),f=d.eventBus.on("content:change",w),d.element.addEventListener("contextmenu",M),b=d.eventBus.on("destroy",D),u&&w()},destroy(){D()}});function D(){clearTimeout(g),x(),f?.(),b?.(),d?.element?.removeEventListener("contextmenu",M),d=null}}function hs(e,t,n=0){const o=document.createRange(),r=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,null);let s=0,i=!1;for(;r.nextNode();){const e=r.currentNode,a=e.textContent.length;if(!i&&s+a>=t&&(o.setStart(e,t-s),i=!0,0===n))return o.setEnd(e,t-s),o;if(i&&s+a>=t+n)return o.setEnd(e,t+n-s),o;s+=a}return i||(o.selectNodeContents(e),o.collapse(!1)),o}function gs(e,t){const n=document.createRange();n.selectNodeContents(e),n.setEnd(t.startContainer,t.startOffset);return{offset:n.toString().length,length:t.toString().length}}class ps{constructor(e){this.userId=e,this._clock={[e]:0},this._pendingOps=[],this._seenOps=/* @__PURE__ */new Set,this._maxSeenOps=1e4,this._suppressRemote=!1,this._lastTextContent=null}_trackOp(e){if(this._seenOps.add(e),this._seenOps.size>this._maxSeenOps){const e=this._seenOps.size-this._maxSeenOps,t=this._seenOps.values();for(let n=0;n<e;n++)this._seenOps.delete(t.next().value)}}_tickLocal(){return this._clock[this.userId]=(this._clock[this.userId]||0)+1,{...this._clock}}_merge(e){for(const[t,n]of Object.entries(e))this._clock[t]=Math.max(this._clock[t]||0,n)}captureOperations(e,t){if(this._suppressRemote)return[];const n=t.textContent,o=this._lastTextContent;if(null===o||n===o)return this._lastTextContent=n,[];const r=[],s=this._tickLocal(),i=`${this.userId}-${this._clock[this.userId]}`;if(n.length>o.length){const{position:e,content:t}=this._findInsert(o,n),a={id:i,type:"insert",userId:this.userId,clock:s,timestamp:Date.now(),position:e,content:t};r.push(a),this._trackOp(i)}else if(n.length<o.length){const{position:e,length:t}=this._findDelete(o,n),a={id:i,type:"delete",userId:this.userId,clock:s,timestamp:Date.now(),position:e,length:t};r.push(a),this._trackOp(i)}else{const{position:e,length:t,content:a}=this._findReplace(o,n);if(void 0!==a){const n={id:i,type:"replace",userId:this.userId,clock:s,timestamp:Date.now(),position:e,length:t,content:a};r.push(n),this._trackOp(i)}}return this._lastTextContent=n,r}_findInsert(e,t){let n=0;for(;n<e.length&&e[n]===t[n];)n++;const o=t.length-e.length;return{position:n,content:t.substring(n,n+o)}}_findDelete(e,t){let n=0;for(;n<t.length&&e[n]===t[n];)n++;return{position:n,length:e.length-t.length}}_findReplace(e,t){let n=0;for(;n<e.length&&e[n]===t[n];)n++;if(n>=e.length)return{};let o=e.length-1,r=t.length-1;for(;o>n&&e[o]===t[r];)o--,r--;return{position:n,length:o-n+1,content:t.substring(n,r+1)}}_transformPosition(e,t){if("insert"===t.type){if(t.position<=e)return e+t.content.length}else if("delete"===t.type){if(t.position+t.length<=e)return e-t.length;if(t.position<e)return t.position}else if("replace"===t.type){if(t.position+t.length<=e)return e+(t.content.length-t.length);if(t.position<e)return t.position+t.content.length}return e}applyRemoteOperations(e,t){const n=e.filter((e=>!this._seenOps.has(e.id)));if(0!==n.length){n.sort(((e,t)=>{const n=Object.values(e.clock).reduce(((e,t)=>e+t),0),o=Object.values(t.clock).reduce(((e,t)=>e+t),0);return n!==o?n-o:e.timestamp!==t.timestamp?e.timestamp-t.timestamp:e.userId.localeCompare(t.userId)})),this._suppressRemote=!0;for(const e of n)this._trackOp(e.id),this._applyOp(e,t);this._lastTextContent=t.textContent,this._suppressRemote=!1}}_applyOp(e,t){try{if("insert"===e.type){const n=hs(t,e.position);n&&(n.collapse(!0),n.insertNode(document.createTextNode(e.content)),t.normalize())}else if("delete"===e.type){const n=hs(t,e.position,e.length);n&&(n.deleteContents(),t.normalize())}else if("replace"===e.type){const n=hs(t,e.position,e.length);n&&(n.deleteContents(),n.insertNode(document.createTextNode(e.content)),t.normalize())}}catch(n){}}queueOperation(e){this._pendingOps.push(e)}flushQueue(){const e=[...this._pendingOps];return this._pendingOps=[],e}hasPendingOps(){return this._pendingOps.length>0}initTextContent(e){this._lastTextContent=e.textContent}getState(){return{clock:{...this._clock},pendingOps:this._pendingOps.length,seenOps:this._seenOps.size}}destroy(){this._pendingOps=[],this._seenOps.clear(),this._lastTextContent=null}}class fs{constructor(e,t,n){this.userId=e,this._localState={cursor:null,userName:t,userColor:n,status:"active",lastActive:Date.now()},this._remoteStates=/* @__PURE__ */new Map,this._broadcastInterval=null,this._idleTimer=null,this._cursorsContainer=null,this._renderRafId=null}updateLocalCursor(e,t){try{const t=window.getSelection();if(!t||0===t.rangeCount||!e.contains(t.anchorNode))return void(this._localState.cursor=null);const n=t.getRangeAt(0);this._localState.cursor=gs(e,n),this._localState.lastActive=Date.now()}catch{this._localState.cursor=null}}setStatus(e){this._localState.status=e}resetIdleTimer(){this._localState.status="active",this._localState.lastActive=Date.now(),clearTimeout(this._idleTimer),this._idleTimer=setTimeout((()=>{this._localState.status="idle"}),3e4)}applyRemoteAwareness(e,t){e!==this.userId&&this._remoteStates.set(e,{...t})}removeUser(e){this._remoteStates.delete(e)}getCollaborators(){return Array.from(this._remoteStates.entries()).map((([e,t])=>({userId:e,userName:t.userName,userColor:t.userColor,cursor:t.cursor,status:t.status})))}renderRemoteCursors(e){this._renderRafId&&cancelAnimationFrame(this._renderRafId),this._renderRafId=requestAnimationFrame((()=>{this._doRender(e)}))}_doRender(e){this._cursorsContainer||(this._cursorsContainer=document.createElement("div"),this._cursorsContainer.className="rmx-collab-cursors-container",this._cursorsContainer.setAttribute("aria-hidden","true"),e.parentNode?.insertBefore(this._cursorsContainer,e.nextSibling)),this._cursorsContainer.innerHTML="";const t=e.getBoundingClientRect();let n=0;for(const[o,r]of this._remoteStates)if(r.cursor&&"offline"!==r.status){if(n>=20)break;n++;try{const n=hs(e,r.cursor.offset,r.cursor.length);if(!n)continue;const o=n.getClientRects();if(0===o.length)continue;const s=o[0],i=document.createElement("div");i.className="rmx-collab-cursor",i.style.cssText=`\n left: ${s.left-t.left}px;\n top: ${s.top-t.top}px;\n height: ${s.height}px;\n background-color: ${r.userColor};\n `;const a=document.createElement("span");if(a.className="rmx-collab-cursor-label",a.textContent=r.userName,a.style.backgroundColor=r.userColor,i.appendChild(a),this._cursorsContainer.appendChild(i),r.cursor.length>0)for(const e of o){const n=document.createElement("div");n.className="rmx-collab-selection",n.style.cssText=`\n left: ${e.left-t.left}px;\n top: ${e.top-t.top}px;\n width: ${e.width}px;\n height: ${e.height}px;\n background-color: ${r.userColor};\n `,this._cursorsContainer.appendChild(n)}}catch{}}}clearRemoteCursors(e){this._cursorsContainer&&(this._cursorsContainer.innerHTML="")}getLocalState(){return{...this._localState}}startBroadcasting(e,t=1e3){this.stopBroadcasting(),this._broadcastInterval=setInterval((()=>{e(this.getLocalState())}),t)}stopBroadcasting(){this._broadcastInterval&&(clearInterval(this._broadcastInterval),this._broadcastInterval=null)}destroy(){this.stopBroadcasting(),clearTimeout(this._idleTimer),this._renderRafId&&cancelAnimationFrame(this._renderRafId),this._cursorsContainer&&(this._cursorsContainer.remove(),this._cursorsContainer=null),this._remoteStates.clear()}}class bs{constructor(e,t={}){this._url=e,this._reconnect=!1!==t.reconnect,this._reconnectInterval=t.reconnectInterval||2e3,this._maxAttempts=t.maxReconnectAttempts||10,this._maxDelay=t.maxReconnectDelay||3e4,this._ws=null,this._messageHandler=null,this._connectHandler=null,this._disconnectHandler=null,this._reconnectTimer=null,this._reconnectAttempts=0,this._intentionalClose=!1}connect(){if(!this._ws||this._ws.readyState!==WebSocket.OPEN){this._intentionalClose=!1,this._reconnectAttempts=0;try{this._ws=new WebSocket(this._url)}catch(e){return void this._scheduleReconnect()}this._ws.onopen=()=>{this._reconnectAttempts=0,this._connectHandler?.()},this._ws.onmessage=t=>{try{const e=JSON.parse(t.data);this._messageHandler?.(e)}catch(e){}},this._ws.onclose=()=>{this._disconnectHandler?.(),!this._intentionalClose&&this._reconnect&&this._scheduleReconnect()},this._ws.onerror=()=>{}}}disconnect(){this._intentionalClose=!0,clearTimeout(this._reconnectTimer),this._reconnectTimer=null,this._ws&&(this._ws.onclose=null,this._ws.onerror=null,this._ws.onmessage=null,this._ws.onopen=null,this._ws.readyState!==WebSocket.OPEN&&this._ws.readyState!==WebSocket.CONNECTING||this._ws.close(),this._ws=null)}send(e){this._ws&&this._ws.readyState===WebSocket.OPEN&&this._ws.send(JSON.stringify(e))}onMessage(e){this._messageHandler=e}onConnect(e){this._connectHandler=e}onDisconnect(e){this._disconnectHandler=e}isConnected(){return this._ws?.readyState===WebSocket.OPEN}_scheduleReconnect(){if(this._reconnectAttempts>=this._maxAttempts)return;const e=Math.min(this._reconnectInterval*Math.pow(2,this._reconnectAttempts),this._maxDelay);this._reconnectAttempts++,this._reconnectTimer=setTimeout((()=>{this.connect()}),e)}destroy(){this.disconnect(),this._messageHandler=null,this._connectHandler=null,this._disconnectHandler=null}}function ys(e={}){const{signalingServer:t,transport:n,userId:o=`user-${Date.now()}-${Math.random().toString(36).slice(2,6)}`,userName:r="Anonymous",userColor:s="#6366f1",roomId:i="default",autoConnect:a=!0,broadcastInterval:l=1e3,onUserJoin:c,onUserLeave:d,onSync:u,onConflict:m}=e;let h=null,g=null,p=null,f=null,b=null,y=[],v=!1;function x(e){if(h)switch(e.type){case"op":{if(e.userId===o)return;const t=window.getSelection();let n=null;if(t&&t.rangeCount>0&&h.element.contains(t.anchorNode))try{const e=t.getRangeAt(0);n={startOffset:e.startOffset,startContainer:e.startContainer}}catch{}if(h._isRemoteOperation=!0,p.applyRemoteOperations(e.operations,h.element),p._merge(e.clock),h._isRemoteOperation=!1,n)try{const e=document.createRange();e.setStart(n.startContainer,Math.min(n.startOffset,n.startContainer.length||0)),e.collapse(!0),t.removeAllRanges(),t.addRange(e)}catch{}h.eventBus.emit("collab:sync",{userId:e.userId,opCount:e.operations.length}),h.eventBus.emit("content:change"),u?.({userId:e.userId,operations:e.operations});break}case"awareness":if(e.userId===o)return;f.applyRemoteAwareness(e.userId,e.state),f.renderRemoteCursors(h.element);break;case"join":if(e.userId===o)return;f.applyRemoteAwareness(e.userId,{userName:e.userName,userColor:e.userColor,status:"active",cursor:null,lastActive:Date.now()}),h.eventBus.emit("collab:userJoin",{userId:e.userId,userName:e.userName}),c?.({userId:e.userId,userName:e.userName});break;case"leave":if(e.userId===o)return;f.removeUser(e.userId),f.renderRemoteCursors(h.element),h.eventBus.emit("collab:userLeave",{userId:e.userId}),d?.({userId:e.userId});break;case"sync-request":if(e.userId===o)return;g?.send({type:"sync-response",roomId:i,userId:o,html:h.getHTML(),clock:p._clock});break;case"sync-response":if(e.userId===o)return;Object.entries(e.clock).some((([e,t])=>(p._clock[e]||0)<t))&&(h._isRemoteOperation=!0,h.setHTML(e.html),p._merge(e.clock),p.initTextContent(h.element),h._isRemoteOperation=!1,h.eventBus.emit("content:change"));break}}function C(){g&&!v&&(g.onMessage(x),g.onConnect((()=>{v=!0,g.send({type:"join",roomId:i,userId:o,userName:r,userColor:s}),g.send({type:"sync-request",roomId:i,userId:o,clock:p._clock});const e=p.flushQueue();e.length>0&&g.send({type:"op",roomId:i,userId:o,clock:p._clock,operations:e,timestamp:Date.now()}),f.setStatus("active"),f.startBroadcasting((e=>{g.send({type:"awareness",roomId:i,userId:o,state:e})}),l),h?.eventBus.emit("collab:connected")})),g.onDisconnect((()=>{v=!1,f.setStatus("offline"),f.stopBroadcasting(),h&&(f.clearRemoteCursors(h.element),h.eventBus.emit("collab:disconnected"))})),g.connect())}function w(){g&&(v&&g.send({type:"leave",roomId:i,userId:o}),f.stopBroadcasting(),h&&f.clearRemoteCursors(h.element),g.disconnect(),v=!1)}function k(){return g?g.isConnected()?"connected":"disconnected":"unconfigured"}function _(e){e.userName&&(f._localState.userName=e.userName),e.userColor&&(f._localState.userColor=e.userColor)}return _n({name:"collaboration",version:"1.0.0",description:"Real-time collaborative editing with CRDT-inspired conflict resolution, live cursors, and configurable transport",requiresFullAccess:!0,commands:[{name:"startCollaboration",execute(){C()},meta:{icon:"collaboration",tooltip:"Start Collaboration"}},{name:"stopCollaboration",execute(){w()},meta:{icon:"collaboration",tooltip:"Stop Collaboration"}},{name:"getCollaborators",execute:()=>f?.getCollaborators()??[],meta:{tooltip:"Get Collaborators"}},{name:"setUserInfo",execute(e,t){_(t)},meta:{tooltip:"Set User Info"}}],init(e){h=e,p=new ps(o),f=new fs(o,r,s),n?g=n:t&&(g=new bs(t)),p.initTextContent(h.element),h._collaboration={startCollaboration:C,stopCollaboration:w,getCollaborators:()=>f.getCollaborators(),isConnected:()=>g?.isConnected()??!1,getConnectionStatus:k,setUserInfo:_,getCrdtState:()=>p.getState(),userId:o,userName:r,userColor:s},b=new MutationObserver((e=>{if(p._suppressRemote||h._isRemoteOperation)return;const t=p.captureOperations(e,h.element);t.length>0&&(g?.isConnected()?g.send({type:"op",roomId:i,userId:o,clock:{...p._clock},operations:t,timestamp:Date.now()}):t.forEach((e=>p.queueOperation(e))))})),b.observe(h.element,{childList:!0,subtree:!0,characterData:!0,characterDataOldValue:!0});const l=h.eventBus.on("selection:change",(()=>{f.updateLocalCursor(h.element,h.selection),f.resetIdleTimer()}));y.push(l);const c=h.eventBus.on("content:change",(()=>{f.renderRemoteCursors(h.element)}));y.push(c),a&&g&&C()},destroy(){w(),b?.disconnect(),b=null;for(const e of y)e?.();y=[],p?.destroy(),f?.destroy(),g&&!n&&g.destroy?.(),h=null,g=null,p=null,f=null}})}class vs{constructor(e={}){this._maxWorkers=e.maxWorkers||("undefined"!=typeof navigator?navigator.hardwareConcurrency:2)||2,this._workers=[],this._queue=[],this._nextId=1,this._pending=/* @__PURE__ */new Map,this._roundRobin=0,this._enabled="undefined"!=typeof Worker&&!1!==e.enabled,this._workerURL=e.workerURL||null}async execute(e,t){if(!this._enabled)return this._executeFallback(e,t);this._workers.length<this._maxWorkers&&this._spawnWorker();const n=this._nextId++,o=this._workers[this._roundRobin%this._workers.length];return this._roundRobin++,new Promise(((r,s)=>{this._pending.set(n,{resolve:r,reject:s}),o.postMessage({id:n,type:e,data:t})}))}_executeFallback(e,t){switch(e){case"sanitize":return t.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/\s+on\w+\s*=\s*(?:"[^"]*"|'[^']*'|[^\s>]+)/gi,"");case"markdown":return t;case"convert":return{format:t.format,html:null,fallback:!0};default:throw new Error(`Unknown task type: ${e}`)}}_spawnWorker(){try{const e=this._workerURL||new URL("data:text/javascript;base64,LyoqCiAqIFdlYiBXb3JrZXIgbW9kdWxlIGZvciBvZmZsb2FkaW5nIGV4cGVuc2l2ZSBlZGl0b3Igb3BlcmF0aW9ucy4KICoKICogSGFuZGxlcyBIVE1MIHNhbml0aXphdGlvbiwgTWFya2Rvd24gcGFyc2luZywgYW5kIGRvY3VtZW50IGNvbnZlcnNpb24KICogZGlzcGF0Y2ggb2ZmIHRoZSBtYWluIHRocmVhZCB0byBrZWVwIHRoZSBlZGl0b3IgcmVzcG9uc2l2ZS4KICoKICogTWVzc2FnZSBwcm90b2NvbDoKICogICBSZXF1ZXN0OiAgeyBpZCwgdHlwZSwgZGF0YSB9CiAqICAgUmVzcG9uc2U6IHsgaWQsIHJlc3VsdCB9IHwgeyBpZCwgZXJyb3IgfQogKi8KCi8qIGVzbGludC1lbnYgd29ya2VyICovCgovKioKICogTWluaW1hbCBIVE1MIHNhbml0aXplciBmb3IgdXNlIGluc2lkZSB0aGUgd29ya2VyLgogKiBTdHJpcHMgc2NyaXB0IHRhZ3MsIGV2ZW50IGhhbmRsZXJzLCBhbmQgZGFuZ2Vyb3VzIGF0dHJpYnV0ZXMuCiAqIEZvciBmdWxsIHNhbml0aXphdGlvbiB0aGUgbWFpbi10aHJlYWQgU2FuaXRpemVyIHNob3VsZCBiZSB1c2VkOwogKiB0aGlzIHByb3ZpZGVzIGEgZmFzdCBmaXJzdCBwYXNzLgogKgogKiBAcGFyYW0ge3N0cmluZ30gaHRtbCAtIFJhdyBIVE1MIHN0cmluZwogKiBAcmV0dXJucyB7c3RyaW5nfSBTYW5pdGl6ZWQgSFRNTCBzdHJpbmcKICovCmZ1bmN0aW9uIHNhbml0aXplSFRNTChodG1sKSB7CiAgLy8gUmVtb3ZlIDxzY3JpcHQ+IGJsb2NrcyAoaW5jbHVkaW5nIGNvbnRlbnQpCiAgbGV0IHJlc3VsdCA9IGh0bWwucmVwbGFjZSgvPHNjcmlwdFxiW148XSooPzooPyE8XC9zY3JpcHQ+KTxbXjxdKikqPFwvc2NyaXB0Pi9naSwgJycpCiAgLy8gUmVtb3ZlIGV2ZW50LWhhbmRsZXIgYXR0cmlidXRlcyAob25jbGljaywgb25sb2FkLCBvbmVycm9yLCBldGMuKQogIHJlc3VsdCA9IHJlc3VsdC5yZXBsYWNlKC9ccytvblx3K1xzKj1ccyooPzoiW14iXSoifCdbXiddKid8W15ccz5dKykvZ2ksICcnKQogIC8vIFJlbW92ZSBqYXZhc2NyaXB0OiBVUkxzCiAgcmVzdWx0ID0gcmVzdWx0LnJlcGxhY2UoL2hyZWZccyo9XHMqWyInXT9ccypqYXZhc2NyaXB0OlteIic+XHNdKi9naSwgJ2hyZWY9IiMiJykKICAvLyBSZW1vdmUgPGlmcmFtZT4sIDxvYmplY3Q+LCA8ZW1iZWQ+IHRhZ3MKICByZXN1bHQgPSByZXN1bHQucmVwbGFjZSgvPChpZnJhbWV8b2JqZWN0fGVtYmVkKVxiW14+XSo+W1xzXFNdKj88XC9cMT4vZ2ksICcnKQogIHJlc3VsdCA9IHJlc3VsdC5yZXBsYWNlKC88KGlmcmFtZXxvYmplY3R8ZW1iZWQpXGJbXj5dKlwvPz4vZ2ksICcnKQogIHJldHVybiByZXN1bHQKfQoKLyoqCiAqIFNpbXBsZSBNYXJrZG93bi10by1IVE1MIGNvbnZlcnRlciBmb3IgdXNlIGluc2lkZSB0aGUgd29ya2VyLgogKiBIYW5kbGVzIGNvbW1vbiBjb25zdHJ1Y3RzOiBoZWFkaW5ncywgYm9sZCwgaXRhbGljLCBjb2RlLCBsaW5rcywKICogdW5vcmRlcmVkL29yZGVyZWQgbGlzdHMsIGJsb2NrcXVvdGVzLCBhbmQgcGFyYWdyYXBocy4KICoKICogQHBhcmFtIHtzdHJpbmd9IG1kIC0gTWFya2Rvd24gc291cmNlCiAqIEByZXR1cm5zIHtzdHJpbmd9IEhUTUwgc3RyaW5nCiAqLwpmdW5jdGlvbiBwYXJzZU1hcmtkb3duKG1kKSB7CiAgY29uc3QgbGluZXMgPSBtZC5zcGxpdCgnXG4nKQogIGNvbnN0IG91dCA9IFtdCiAgbGV0IGluTGlzdCA9IG51bGwgLy8gJ3VsJyB8ICdvbCcgfCBudWxsCgogIGZvciAobGV0IGkgPSAwOyBpIDwgbGluZXMubGVuZ3RoOyBpKyspIHsKICAgIGxldCBsaW5lID0gbGluZXNbaV0KCiAgICAvLyBDbG9zZSBvcGVuIGxpc3QgaWYgdGhlIGN1cnJlbnQgbGluZSBpcyBub3QgYSBsaXN0IGl0ZW0KICAgIGlmIChpbkxpc3QgJiYgIS9eXHMqWy0qXVxzLy50ZXN0KGxpbmUpICYmICEvXlxzKlxkK1wuXHMvLnRlc3QobGluZSkpIHsKICAgICAgb3V0LnB1c2goYDwvJHtpbkxpc3R9PmApCiAgICAgIGluTGlzdCA9IG51bGwKICAgIH0KCiAgICAvLyBIZWFkaW5ncwogICAgY29uc3QgaGVhZGluZ01hdGNoID0gbGluZS5tYXRjaCgvXigjezEsNn0pXHMrKC4qKSQvKQogICAgaWYgKGhlYWRpbmdNYXRjaCkgewogICAgICBjb25zdCBsZXZlbCA9IGhlYWRpbmdNYXRjaFsxXS5sZW5ndGgKICAgICAgb3V0LnB1c2goYDxoJHtsZXZlbH0+JHtpbmxpbmVNYXJrZG93bihoZWFkaW5nTWF0Y2hbMl0pfTwvaCR7bGV2ZWx9PmApCiAgICAgIGNvbnRpbnVlCiAgICB9CgogICAgLy8gQmxvY2txdW90ZQogICAgaWYgKC9ePlxzPy8udGVzdChsaW5lKSkgewogICAgICBvdXQucHVzaChgPGJsb2NrcXVvdGU+JHtpbmxpbmVNYXJrZG93bihsaW5lLnJlcGxhY2UoL14+XHM/LywgJycpKX08L2Jsb2NrcXVvdGU+YCkKICAgICAgY29udGludWUKICAgIH0KCiAgICAvLyBVbm9yZGVyZWQgbGlzdAogICAgY29uc3QgdWxNYXRjaCA9IGxpbmUubWF0Y2goL15ccypbLSpdXHMrKC4qKSQvKQogICAgaWYgKHVsTWF0Y2gpIHsKICAgICAgaWYgKGluTGlzdCAhPT0gJ3VsJykgewogICAgICAgIGlmIChpbkxpc3QpIG91dC5wdXNoKGA8LyR7aW5MaXN0fT5gKQogICAgICAgIG91dC5wdXNoKCc8dWw+JykKICAgICAgICBpbkxpc3QgPSAndWwnCiAgICAgIH0KICAgICAgb3V0LnB1c2goYDxsaT4ke2lubGluZU1hcmtkb3duKHVsTWF0Y2hbMV0pfTwvbGk+YCkKICAgICAgY29udGludWUKICAgIH0KCiAgICAvLyBPcmRlcmVkIGxpc3QKICAgIGNvbnN0IG9sTWF0Y2ggPSBsaW5lLm1hdGNoKC9eXHMqXGQrXC5ccysoLiopJC8pCiAgICBpZiAob2xNYXRjaCkgewogICAgICBpZiAoaW5MaXN0ICE9PSAnb2wnKSB7CiAgICAgICAgaWYgKGluTGlzdCkgb3V0LnB1c2goYDwvJHtpbkxpc3R9PmApCiAgICAgICAgb3V0LnB1c2goJzxvbD4nKQogICAgICAgIGluTGlzdCA9ICdvbCcKICAgICAgfQogICAgICBvdXQucHVzaChgPGxpPiR7aW5saW5lTWFya2Rvd24ob2xNYXRjaFsxXSl9PC9saT5gKQogICAgICBjb250aW51ZQogICAgfQoKICAgIC8vIEJsYW5rIGxpbmUKICAgIGlmIChsaW5lLnRyaW0oKSA9PT0gJycpIHsKICAgICAgY29udGludWUKICAgIH0KCiAgICAvLyBQYXJhZ3JhcGgKICAgIG91dC5wdXNoKGA8cD4ke2lubGluZU1hcmtkb3duKGxpbmUpfTwvcD5gKQogIH0KCiAgaWYgKGluTGlzdCkgb3V0LnB1c2goYDwvJHtpbkxpc3R9PmApCiAgcmV0dXJuIG91dC5qb2luKCdcbicpCn0KCi8qKgogKiBDb252ZXJ0IGlubGluZSBNYXJrZG93biBzeW50YXggdG8gSFRNTC4KICogQHBhcmFtIHtzdHJpbmd9IHRleHQKICogQHJldHVybnMge3N0cmluZ30KICovCmZ1bmN0aW9uIGlubGluZU1hcmtkb3duKHRleHQpIHsKICAvLyBDb2RlIChiYWNrdGljaykKICB0ZXh0ID0gdGV4dC5yZXBsYWNlKC9gKFteYF0rKWAvZywgJzxjb2RlPiQxPC9jb2RlPicpCiAgLy8gQm9sZAogIHRleHQgPSB0ZXh0LnJlcGxhY2UoL1wqXCooLis/KVwqXCovZywgJzxzdHJvbmc+JDE8L3N0cm9uZz4nKQogIHRleHQgPSB0ZXh0LnJlcGxhY2UoL19fKC4rPylfXy9nLCAnPHN0cm9uZz4kMTwvc3Ryb25nPicpCiAgLy8gSXRhbGljCiAgdGV4dCA9IHRleHQucmVwbGFjZSgvXCooLis/KVwqL2csICc8ZW0+JDE8L2VtPicpCiAgdGV4dCA9IHRleHQucmVwbGFjZSgvXyguKz8pXy9nLCAnPGVtPiQxPC9lbT4nKQogIC8vIExpbmtzCiAgdGV4dCA9IHRleHQucmVwbGFjZSgvXFsoW15cXV0rKVxdXCgoW14pXSspXCkvZywgJzxhIGhyZWY9IiQyIj4kMTwvYT4nKQogIHJldHVybiB0ZXh0Cn0KCi8qKgogKiBEaXNwYXRjaCBoYW5kbGVyIGZvciBkb2N1bWVudCBjb252ZXJzaW9uLgogKiBDdXJyZW50bHkgYWN0cyBhcyBhIHBhc3MtdGhyb3VnaCB0aGF0IHZhbGlkYXRlcyB0aGUgcmVxdWVzdDsKICogaGVhdnkgY29udmVyc2lvbiBsb2dpYyBydW5zIG9uIHRoZSBtYWluIHRocmVhZCB3aXRoIGFjY2VzcyB0bwogKiB0aGUgZnVsbCBkb2N1bWVudENvbnZlcnRlciB1dGlsaXRpZXMuCiAqCiAqIEBwYXJhbSB7eyBmb3JtYXQ6IHN0cmluZywgY29udGVudDogc3RyaW5nIH19IGRhdGEKICogQHJldHVybnMge3sgZm9ybWF0OiBzdHJpbmcsIGh0bWw6IHN0cmluZyB9fQogKi8KZnVuY3Rpb24gZGlzcGF0Y2hDb252ZXJzaW9uKGRhdGEpIHsKICBjb25zdCB7IGZvcm1hdCwgY29udGVudCB9ID0gZGF0YQogIC8vIEZvciBmb3JtYXRzIHdlIGNhbiBoYW5kbGUgaW4gdGhlIHdvcmtlciwgZG8gc28gaGVyZS4KICAvLyBPdGhlcndpc2UgcmV0dXJuIGEgbWFya2VyIHRlbGxpbmcgdGhlIG1haW4gdGhyZWFkIHRvIGhhbmRsZSBpdC4KICBpZiAoZm9ybWF0ID09PSAnbWFya2Rvd24nIHx8IGZvcm1hdCA9PT0gJ21kJykgewogICAgcmV0dXJuIHsgZm9ybWF0LCBodG1sOiBwYXJzZU1hcmtkb3duKGNvbnRlbnQpIH0KICB9CiAgcmV0dXJuIHsgZm9ybWF0LCBodG1sOiBudWxsLCBmYWxsYmFjazogdHJ1ZSB9Cn0KCi8vIC0tLSBNZXNzYWdlIGhhbmRsZXIgLS0tCnNlbGYub25tZXNzYWdlID0gZnVuY3Rpb24gKGUpIHsKICBjb25zdCB7IGlkLCB0eXBlLCBkYXRhIH0gPSBlLmRhdGEKICB0cnkgewogICAgbGV0IHJlc3VsdAogICAgc3dpdGNoICh0eXBlKSB7CiAgICAgIGNhc2UgJ3Nhbml0aXplJzoKICAgICAgICByZXN1bHQgPSBzYW5pdGl6ZUhUTUwoZGF0YSkKICAgICAgICBicmVhawogICAgICBjYXNlICdtYXJrZG93bic6CiAgICAgICAgcmVzdWx0ID0gcGFyc2VNYXJrZG93bihkYXRhKQogICAgICAgIGJyZWFrCiAgICAgIGNhc2UgJ2NvbnZlcnQnOgogICAgICAgIHJlc3VsdCA9IGRpc3BhdGNoQ29udmVyc2lvbihkYXRhKQogICAgICAgIGJyZWFrCiAgICAgIGRlZmF1bHQ6CiAgICAgICAgdGhyb3cgbmV3IEVycm9yKGBVbmtub3duIHRhc2sgdHlwZTogJHt0eXBlfWApCiAgICB9CiAgICBzZWxmLnBvc3RNZXNzYWdlKHsgaWQsIHJlc3VsdCB9KQogIH0gY2F0Y2ggKGVycikgewogICAgc2VsZi5wb3N0TWVzc2FnZSh7IGlkLCBlcnJvcjogZXJyLm1lc3NhZ2UgfSkKICB9Cn0K",import.meta.url).href,t=new Worker(e,{type:"module"});t.onmessage=e=>{const{id:t,result:n,error:o}=e.data,r=this._pending.get(t);r&&(this._pending.delete(t),o?r.reject(new Error(o)):r.resolve(n))},t.onerror=e=>{},this._workers.push(t)}catch(e){this._enabled=!1}}get isEnabled(){return this._enabled}get workerCount(){return this._workers.length}destroy(){this._workers.forEach((e=>e.terminate())),this._workers=[],this._pending.forEach((({reject:e})=>{e(new Error("WorkerPool destroyed"))})),this._pending.clear(),this._queue=[]}}const xs=/* @__PURE__ */new Set(["P","DIV","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","PRE","UL","OL","LI","TABLE","FIGURE","SECTION","ARTICLE","ASIDE","HR","DL","DD","DT","DETAILS","SUMMARY"]);class Cs{constructor(e,t={}){this._container=e,this._threshold=t.threshold??200,this._rootMargin=t.rootMargin||"500px",this._observer=null,this._active=!1,this._collapsed=/* @__PURE__ */new Map,this._placeholders=/* @__PURE__ */new Set}init(){0!==this._threshold&&"undefined"!=typeof IntersectionObserver&&(this._observer=new IntersectionObserver((e=>this._handleIntersection(e)),{root:null,rootMargin:this._rootMargin,threshold:0}),this._scan())}_scan(){const e=this._getBlockElements();e.length<this._threshold?this._active=!1:(this._active=!0,e.forEach((e=>{this._observer.observe(e)})))}_getBlockElements(){const e=[],t=this._container.children;for(let n=0;n<t.length;n++){const o=t[n];1===o.nodeType&&xs.has(o.tagName)&&e.push(o)}return e}_handleIntersection(e){for(const t of e){const e=t.target;t.isIntersecting?this._restore(e):this._collapse(e)}}_collapse(e){if(this._placeholders.has(e))return;if(this._collapsed.has(e))return;const t=e.getBoundingClientRect().height;if(0===t)return;const n=e.innerHTML,o=e.tagName;this._collapsed.set(e,{html:n,height:t,tagName:o}),e.innerHTML="",e.style.minHeight=`${t}px`,e.setAttribute("data-virtualized","true"),this._placeholders.add(e)}_restore(e){const t=this._collapsed.get(e);t&&(e.innerHTML=t.html,e.style.minHeight="",e.removeAttribute("data-virtualized"),this._collapsed.delete(e),this._placeholders.delete(e))}restoreAll(){this._collapsed.forEach(((e,t)=>{this._restore(t)}))}refresh(){this._observer&&(this._observer.disconnect(),this.restoreAll(),this._scan())}get isActive(){return this._active}get collapsedCount(){return this._collapsed.size}destroy(){this.restoreAll(),this._observer&&(this._observer.disconnect(),this._observer=null),this._collapsed.clear(),this._placeholders.clear(),this._active=!1}}const ws=new I;function ks(e,t){const n=URL.createObjectURL(e),o=document.createElement("a");o.href=n,o.download=t,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(n)}function _s(e,t="document.md"){const n=_e(e);ks(new Blob([n],{type:"text/markdown;charset=utf-8"}),t)}function Ss(e,t="Document"){const n=document.createElement("iframe");n.style.cssText="position:fixed;left:-9999px;top:-9999px;width:0;height:0;",n.setAttribute("sandbox","allow-same-origin allow-modals"),document.body.appendChild(n);const o=ws.sanitize(e),r=`<!DOCTYPE html>\n<html>\n<head>\n <title>${t.replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}</title>\n <style>\n body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; line-height: 1.6; color: #1a1a1a; max-width: 800px; margin: 0 auto; padding: 20px; }\n h1, h2, h3, h4, h5, h6 { margin-top: 1.2em; margin-bottom: 0.4em; }\n img { max-width: 100%; height: auto; }\n table { border-collapse: collapse; width: 100%; }\n th, td { border: 1px solid #ccc; padding: 8px; text-align: left; }\n pre { background: #f5f5f5; padding: 12px; border-radius: 4px; overflow-x: auto; }\n code { font-family: 'SFMono-Regular', Consolas, monospace; font-size: 0.9em; }\n blockquote { border-left: 3px solid #ccc; margin-left: 0; padding-left: 16px; color: #555; }\n @media print { body { padding: 0; } }\n </style>\n</head>\n<body>${o}</body>\n</html>`;n.srcdoc=r;let s=!1;const i=()=>{s||(s=!0,clearTimeout(a),n.parentNode&&document.body.removeChild(n))};n.contentWindow.onafterprint=i;let a=setTimeout(i,6e4);n.onload=()=>{n.contentWindow.focus(),n.contentWindow.print(),clearTimeout(a),a=setTimeout(i,1e3)}}function As(e,t="document.doc"){ks(new Blob(["\ufeff",`<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">\n<head><meta charset="utf-8"><style>\nbody { font-family: Calibri, sans-serif; line-height: 1.5; color: #1a1a1a; }\nh1, h2, h3, h4, h5, h6 { margin-top: 1em; margin-bottom: 0.4em; }\ntable { border-collapse: collapse; width: 100%; }\nth, td { border: 1px solid #999; padding: 6px 10px; }\npre { background: #f5f5f5; padding: 10px; font-family: Consolas, monospace; font-size: 0.9em; }\ncode { font-family: Consolas, monospace; font-size: 0.9em; }\nblockquote { border-left: 3px solid #ccc; margin-left: 0; padding-left: 14px; color: #555; }\nimg { max-width: 100%; }\n</style></head>\n<body>${e}</body></html>`],{type:"application/msword"}),t)}function Es(e,t){const n=new Set(t.map((e=>e.toLowerCase())));return e.filter((e=>!n.has(e.toLowerCase())))}function Ls(e,t,n={}){const o=new Set(e.map((e=>e.toLowerCase()))),r=t.filter((e=>!o.has(e.toLowerCase())));return"start"===n.position?[...r,...e]:[...e,...r]}function Ts(e,t={}){if(!e||0===e.length)return null;if("undefined"==typeof document)return null;const n=`https://fonts.googleapis.com/css2?${e.map((e=>(e.includes(":"),`family=${e.replace(/ /g,"+")}`))).join("&")}&display=swap`,o=document.querySelector(`link[href="${n}"]`);if(o)return o;const r=document.createElement("link");return r.rel="stylesheet",r.href=n,r.dataset.remyxFonts="true",t.integrity?(r.integrity=t.integrity,r.crossOrigin=t.crossOrigin||"anonymous"):r.crossOrigin=t.crossOrigin||"anonymous",document.head.appendChild(r),r}const Is=/* @__PURE__ */new Set(["html","head","body","div","section","article","aside","nav","header","footer","main","p","h1","h2","h3","h4","h5","h6","ul","ol","li","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","blockquote","pre","figure","figcaption","form","fieldset","legend","details","summary","hr","br","iframe","video","audio","canvas"]),Bs=/* @__PURE__ */new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),Ns=/* @__PURE__ */new Set(["pre","code","script","style","textarea"]);function Rs(e){if(!e||!e.trim())return"";const t=[];return Ms((new DOMParser).parseFromString(`<body>${e}</body>`,"text/html").body,0,t," "),t.join("\n").trim()}function Ms(e,t,n,o){const r=Array.from(e.childNodes);for(const s of r){if(s.nodeType===Node.COMMENT_NODE){n.push(`${o.repeat(Math.max(0,t))}\x3c!--${s.textContent}--\x3e`);continue}if(s.nodeType===Node.TEXT_NODE){const e=s.textContent;if(!e.trim())continue;const r=e.replace(/\s+/g," ").trim();r&&n.push(`${o.repeat(Math.max(0,t))}${r}`);continue}if(s.nodeType!==Node.ELEMENT_NODE)continue;const e=s.tagName.toLowerCase();if(Ns.has(e)){n.push(`${o.repeat(Math.max(0,t))}${s.outerHTML}`);continue}const r=Bs.has(e),i=o.repeat(Math.max(0,t)),a=Ds(s,e);if(r){n.push(`${i}${a}`);continue}if(Hs(s)){const t=Fs(s);n.push(`${i}${a}${t}</${e}>`)}else n.push(`${i}${a}`),Ms(s,t+1,n,o),n.push(`${i}</${e}>`)}}function Ds(e,t){const n=Array.from(e.attributes);if(0===n.length)return`<${t}>`;return`<${t} ${n.map((e=>{return""===e.value?e.name:`${e.name}="${t=e.value,te(t)}"`;var t})).join(" ")}>`}function Hs(e){for(const t of e.childNodes)if(t.nodeType!==Node.TEXT_NODE&&t.nodeType===Node.ELEMENT_NODE){const e=t.tagName.toLowerCase();if(Is.has(e))return!1;if(!Hs(t))return!1}return!0}function Fs(e){let t="";for(const n of e.childNodes)if(n.nodeType===Node.TEXT_NODE)t+=n.textContent.replace(/\s+/g," ");else if(n.nodeType===Node.ELEMENT_NODE){const e=n.tagName.toLowerCase(),o=Ds(n,e);Bs.has(e)?t+=o:t+=`${o}${Fs(n)}</${e}>`}return t}const Ps=/[\u0591-\u07FF\u200F\u202B\u202E\uFB1D-\uFDFD\uFE70-\uFEFC]/,zs=/[A-Za-z\u00C0-\u00FF\u0100-\u024F\u0400-\u04FF\u1100-\u11FF\u3040-\u309F\u30A0-\u30FF\u3400-\u4DBF\u4E00-\u9FFF]/;function Os(e){if(!e||"string"!=typeof e)return"auto";let t=0,n=0;for(let o=0;o<e.length;o++){const r=e[o];Ps.test(r)?t++:zs.test(r)&&n++}return 0===t&&0===n?"auto":t>n?"rtl":"ltr"}function Gs(e){if(!e||!e.textContent)return;const t=Os(e.textContent);"auto"===t?e.removeAttribute("dir"):e.setAttribute("dir",t)}function qs(e){if(!e)return;const t=e.querySelectorAll("p, h1, h2, h3, h4, h5, h6, li, blockquote, td, th");for(const n of t)Gs(n)}const Ws={marginStart:"margin-inline-start",marginEnd:"margin-inline-end",paddingStart:"padding-inline-start",paddingEnd:"padding-inline-end",borderStart:"border-inline-start",borderEnd:"border-inline-end",insetStart:"inset-inline-start",insetEnd:"inset-inline-end"},$s={"toolbar.bold":"Bold","toolbar.italic":"Italic","toolbar.underline":"Underline","toolbar.strikethrough":"Strikethrough","toolbar.subscript":"Subscript","toolbar.superscript":"Superscript","toolbar.removeFormat":"Remove Formatting","toolbar.heading":"Heading","toolbar.paragraph":"Normal text","toolbar.orderedList":"Numbered List","toolbar.unorderedList":"Bulleted List","toolbar.taskList":"Task List","toolbar.indent":"Increase Indent","toolbar.outdent":"Decrease Indent","toolbar.alignLeft":"Align Left","toolbar.alignCenter":"Align Center","toolbar.alignRight":"Align Right","toolbar.alignJustify":"Justify","toolbar.blockquote":"Blockquote","toolbar.codeBlock":"Code Block","toolbar.horizontalRule":"Horizontal Rule","toolbar.link":"Insert Link","toolbar.image":"Insert Image","toolbar.table":"Insert Table","toolbar.fontFamily":"Font Family","toolbar.fontSize":"Font Size","toolbar.foreColor":"Text Color","toolbar.backColor":"Background Color","toolbar.undo":"Undo","toolbar.redo":"Redo","toolbar.source":"Source Code","toolbar.markdown":"Markdown","toolbar.fullscreen":"Fullscreen","toolbar.commandPalette":"Command Palette","toolbar.print":"Print","toolbar.findReplace":"Find & Replace","toolbar.lineNumbers":"Toggle Line Numbers","toolbar.copyCode":"Copy Code","menu.file":"File","menu.edit":"Edit","menu.view":"View","menu.insert":"Insert","menu.format":"Format","context.cut":"Cut","context.copy":"Copy","context.paste":"Paste","context.selectAll":"Select All","context.toggleHeaderRow":"Toggle Header Row","context.formatCell":"Format Cell","context.clearFilters":"Clear Filters","modal.link.title":"Insert Link","modal.link.url":"URL","modal.link.text":"Link Text","modal.link.newTab":"Open in new tab","modal.link.insert":"Insert","modal.link.cancel":"Cancel","modal.image.title":"Insert Image","modal.image.url":"Image URL","modal.image.alt":"Alt Text","modal.image.insert":"Insert","modal.image.cancel":"Cancel","modal.source.title":"Edit Source","modal.source.apply":"Apply","modal.source.cancel":"Cancel","modal.table.title":"Insert Table","modal.table.rows":"Rows","modal.table.cols":"Columns","modal.table.insert":"Insert","modal.table.cancel":"Cancel","find.placeholder":"Find...","find.replace":"Replace...","find.replaceAll":"Replace All","find.matchCase":"Match Case","find.noResults":"No results","find.results":"{{current}} of {{total}}","palette.placeholder":"Type a command...","palette.noResults":"No matching commands","autosave.saved":"Saved","autosave.saving":"Saving...","autosave.unsaved":"Unsaved changes","autosave.error":"Save failed","autosave.recovery":"Unsaved content was recovered.","autosave.restore":"Restore","autosave.dismiss":"Dismiss","a11y.skipToEditor":"Skip to editor","a11y.toolbar":"Editor toolbar","a11y.menuBar":"Editor menu bar","a11y.editor":"Rich text editor","heading.h1":"Heading 1","heading.h2":"Heading 2","heading.h3":"Heading 3","heading.h4":"Heading 4","heading.h5":"Heading 5","heading.h6":"Heading 6","heading.paragraph":"Normal text","format.number":"Number","format.currency":"Currency","format.percentage":"Percentage","format.date":"Date","status.words":"{{count}} words","status.chars":"{{count}} characters"};let Zs={...$s};const Us={en:$s};let Vs="en";function js(e,t){let n=Zs[e];if(void 0===n)return e;if(t)for(const[o,r]of Object.entries(t))n=n.replace(new RegExp(`\\{\\{${o}\\}\\}`,"g"),String(r));return n}function Ks(e){const t=Us[e];if(!t)throw new Error(`Locale "${e}" is not registered. Use registerLocale() first.`);Vs=e,Zs={...$s,...t}}function Xs(){return Vs}function Js(e,t){if(!e||"string"!=typeof e)throw new Error("registerLocale: lang is required");if(!t||"object"!=typeof t)throw new Error("registerLocale: strings object is required");Us[e]=t}function Ys(e){"en"!==e&&(delete Us[e],Vs===e&&Ks("en"))}function Qs(){return Object.keys(Us)}function ei(e){return new Promise((t=>{requestAnimationFrame((()=>{for(const t of e)t();t()}))}))}function ti(e,t={}){const n=t.timeout||2e3;return"function"==typeof requestIdleCallback?requestIdleCallback(e,{timeout:n}):setTimeout(e,16)}function ni(e){"function"==typeof cancelIdleCallback?cancelIdleCallback(e):clearTimeout(e)}function oi(e){let t=null;return function(...n){null===t&&(t=requestAnimationFrame((()=>{e.apply(this,n),t=null})))}}function ri(e,t){const n=performance.now(),o=t();performance.now();return"undefined"!=typeof console&&console.debug,o}function si(e,t,n=100){const o=[];for(let r=0;r<n;r++){const e=performance.now();t(),o.push(performance.now()-e)}o.sort(((e,t)=>e-t));return{label:e,mean:o.reduce(((e,t)=>e+t),0)/o.length,median:o[Math.floor(o.length/2)],min:o[0],max:o[o.length-1],p95:o[Math.floor(.95*o.length)]}}function ii(e,t={}){const n=t.flushMs||16;let o=[],r=null;return{queue(t){o.push(t),r||(r="function"==typeof requestAnimationFrame?requestAnimationFrame((()=>{const t=o;o=[],r=null,e(t)})):setTimeout((()=>{const t=o;o=[],r=null,e(t)}),n))},flush(){if(r&&("function"==typeof cancelAnimationFrame?cancelAnimationFrame(r):clearTimeout(r),r=null),o.length){const t=o;o=[],e(t)}},destroy(){r&&("function"==typeof cancelAnimationFrame?cancelAnimationFrame(r):clearTimeout(r)),o=[],r=null}}}const ai={bg:{var:"--rmx-bg",description:"Editor background color"},text:{var:"--rmx-text",description:"Primary text color"},textSecondary:{var:"--rmx-text-secondary",description:"Secondary/muted text color"},border:{var:"--rmx-border",description:"Border color"},borderSubtle:{var:"--rmx-border-subtle",description:"Subtle/light border color"},toolbarBg:{var:"--rmx-toolbar-bg",description:"Toolbar background color"},toolbarBorder:{var:"--rmx-toolbar-border",description:"Toolbar border color"},toolbarButtonHover:{var:"--rmx-toolbar-button-hover",description:"Toolbar button hover background"},toolbarButtonActive:{var:"--rmx-toolbar-button-active",description:"Toolbar button active background"},toolbarIcon:{var:"--rmx-toolbar-icon",description:"Toolbar icon color"},toolbarIconActive:{var:"--rmx-toolbar-icon-active",description:"Toolbar icon active color"},primary:{var:"--rmx-primary",description:"Primary accent color"},primaryHover:{var:"--rmx-primary-hover",description:"Primary color on hover"},primaryLight:{var:"--rmx-primary-light",description:"Light variant of primary (backgrounds)"},focusRing:{var:"--rmx-focus-ring",description:"Focus ring outline color"},selection:{var:"--rmx-selection",description:"Text selection highlight color"},danger:{var:"--rmx-danger",description:"Error/danger color"},dangerLight:{var:"--rmx-danger-light",description:"Light variant of danger"},placeholder:{var:"--rmx-placeholder",description:"Placeholder text color"},modalBg:{var:"--rmx-modal-bg",description:"Modal background color"},modalOverlay:{var:"--rmx-modal-overlay",description:"Modal overlay background"},statusbarBg:{var:"--rmx-statusbar-bg",description:"Status bar background"},statusbarText:{var:"--rmx-statusbar-text",description:"Status bar text color"},hoverBg:{var:"--rmx-hover-bg",description:"Generic hover background"},shadowSm:{var:"--rmx-shadow-sm",description:"Small shadow"},shadowMd:{var:"--rmx-shadow-md",description:"Medium shadow"},shadowLg:{var:"--rmx-shadow-lg",description:"Large shadow"},shadowFloat:{var:"--rmx-shadow-float",description:"Floating element shadow"},fontFamily:{var:"--rmx-font-family",description:"UI font stack"},fontSize:{var:"--rmx-font-size",description:"UI font size"},contentFontSize:{var:"--rmx-content-font-size",description:"Content area font size"},contentLineHeight:{var:"--rmx-content-line-height",description:"Content area line height"},radius:{var:"--rmx-radius",description:"Standard border radius"},radiusSm:{var:"--rmx-radius-sm",description:"Small border radius"},radiusInner:{var:"--rmx-radius-inner",description:"Inner element border radius"},spacingXs:{var:"--rmx-spacing-xs",description:"Extra small spacing (4px)"},spacingSm:{var:"--rmx-spacing-sm",description:"Small spacing (8px)"},spacingMd:{var:"--rmx-spacing-md",description:"Medium spacing (12px)"},transitionFast:{var:"--rmx-transition-fast",description:"Fast transition duration"},transitionNormal:{var:"--rmx-transition-normal",description:"Normal transition duration"}},li={};for(const[Li,Ti]of Object.entries(ai))li[Li]=Ti.var;function ci(e){const t={};for(const[n,o]of Object.entries(e))n.startsWith("--rmx-")?t[n]=o:li[n]?t[li[n]]=o:t[`--rmx-${n.replace(/([A-Z])/g,"-$1").toLowerCase()}`]=o;return t}const di={ocean:ci({bg:"#0f172a",text:"#e2e8f0",textSecondary:"#94a3b8",border:"#1e3a5f",borderSubtle:"#1e3a5f",toolbarBg:"#0c1426",toolbarBorder:"#1e3a5f",toolbarButtonHover:"#1e3a5f",toolbarButtonActive:"#1e4976",toolbarIcon:"#94a3b8",toolbarIconActive:"#38bdf8",primary:"#0ea5e9",primaryHover:"#0284c7",primaryLight:"rgba(14, 165, 233, 0.15)",focusRing:"#0ea5e9",selection:"#0c4a6e",placeholder:"#475569",modalBg:"#0c1426",modalOverlay:"rgba(0, 0, 0, 0.6)",statusbarBg:"#0c1426",statusbarText:"#64748b"}),forest:ci({bg:"#14201a",text:"#d1e7dd",textSecondary:"#8fbc8f",border:"#2d4a3e",borderSubtle:"#2d4a3e",toolbarBg:"#0f1a14",toolbarBorder:"#2d4a3e",toolbarButtonHover:"#2d4a3e",toolbarButtonActive:"#1a5c3a",toolbarIcon:"#8fbc8f",toolbarIconActive:"#4ade80",primary:"#22c55e",primaryHover:"#16a34a",primaryLight:"rgba(34, 197, 94, 0.15)",focusRing:"#22c55e",selection:"#14532d",placeholder:"#4a7c5f",modalBg:"#0f1a14",modalOverlay:"rgba(0, 0, 0, 0.6)",statusbarBg:"#0f1a14",statusbarText:"#4a7c5f"}),sunset:ci({bg:"#1c1210",text:"#fde8d0",textSecondary:"#d4a574",border:"#5c3a28",borderSubtle:"#5c3a28",toolbarBg:"#181010",toolbarBorder:"#5c3a28",toolbarButtonHover:"#5c3a28",toolbarButtonActive:"#7c4a2a",toolbarIcon:"#d4a574",toolbarIconActive:"#fb923c",primary:"#f97316",primaryHover:"#ea580c",primaryLight:"rgba(249, 115, 22, 0.15)",focusRing:"#f97316",selection:"#7c2d12",placeholder:"#8b6f47",modalBg:"#181010",modalOverlay:"rgba(0, 0, 0, 0.6)",statusbarBg:"#181010",statusbarText:"#8b6f47"}),rose:ci({bg:"#1c1018",text:"#fde2ee",textSecondary:"#d4809f",border:"#5c2848",borderSubtle:"#5c2848",toolbarBg:"#18101a",toolbarBorder:"#5c2848",toolbarButtonHover:"#5c2848",toolbarButtonActive:"#7c2858",toolbarIcon:"#d4809f",toolbarIconActive:"#fb7185",primary:"#f43f5e",primaryHover:"#e11d48",primaryLight:"rgba(244, 63, 94, 0.15)",focusRing:"#f43f5e",selection:"#881337",placeholder:"#8b4766",modalBg:"#18101a",modalOverlay:"rgba(0, 0, 0, 0.6)",statusbarBg:"#18101a",statusbarText:"#8b4766"})},ui={color:{var:"--rmx-tb-color",description:"Icon / text color"},background:{var:"--rmx-tb-bg",description:"Default background"},hoverColor:{var:"--rmx-tb-hover-color",description:"Color on hover"},hoverBackground:{var:"--rmx-tb-hover-bg",description:"Background on hover"},activeColor:{var:"--rmx-tb-active-color",description:"Color when active / pressed"},activeBackground:{var:"--rmx-tb-active-bg",description:"Background when active"},border:{var:"--rmx-tb-border",description:"Border shorthand"},borderRadius:{var:"--rmx-tb-radius",description:"Border radius"},size:{var:"--rmx-tb-size",description:"Button width & height"},iconSize:{var:"--rmx-tb-icon-size",description:"Icon size inside button"},padding:{var:"--rmx-tb-padding",description:"Button padding"},opacity:{var:"--rmx-tb-opacity",description:"Button opacity"}},mi={};for(const[Li,Ti]of Object.entries(ui))mi[Li]=Ti.var;const hi={color:"--rmx-tb-sep-color",width:"--rmx-tb-sep-width",height:"--rmx-tb-sep-height",margin:"--rmx-tb-sep-margin"};function gi(e){if(!e||"object"!=typeof e)return null;const t={};let n=!1;for(const[o,r]of Object.entries(e))o.startsWith("--rmx-")?(t[o]=r,n=!0):mi[o]&&(t[mi[o]]=r,n=!0);return n?t:null}function pi(e){if(!e||"object"!=typeof e)return null;const t={};let n=!1;for(const[o,r]of Object.entries(e))o.startsWith("--rmx-")?(t[o]=r,n=!0):hi[o]&&(t[hi[o]]=r,n=!0);return n?t:null}function fi(e){if(!e||"object"!=typeof e)return{};const t={};for(const[n,o]of Object.entries(e))if("_separator"===n)t._separator=pi(o);else{const e=gi(o);e&&(t[n]=e)}return t}function bi(e){if(!e||"object"!=typeof e)throw new Error("defineConfig expects a configuration object");if(e.editors&&"object"!=typeof e.editors)throw new Error('defineConfig: "editors" must be an object mapping names to editor configurations');return e}async function yi(e,t={}){const{env:n,headers:o,signal:r}=t,s=await fetch(e,{headers:{Accept:"application/json, text/yaml, text/plain",...o},signal:r});if(!s.ok)throw new Error(`loadConfig: Failed to fetch "${e}" (HTTP ${s.status})`);const i=await s.text();let a;if(/\.ya?ml(\?.*)?$/i.test(e))a=xi(i);else try{a=JSON.parse(i)}catch{a=xi(i)}if(!a||"object"!=typeof a)throw new Error("loadConfig: Configuration must be a JSON/YAML object");if(n&&a.env&&"object"==typeof a.env){const e=a.env[n];if(e&&"object"==typeof e){const{env:t,...n}=a;a=vi(n,e)}else{const{env:e,...t}=a;a=t}}else if(a.env){const{env:e,...t}=a;a=t}return a}function vi(e,t){const n={...e};for(const o of Object.keys(t))t[o]&&"object"==typeof t[o]&&!Array.isArray(t[o])&&e[o]&&"object"==typeof e[o]&&!Array.isArray(e[o])?n[o]=vi(e[o],t[o]):n[o]=t[o];return n}function xi(e){const t=e.split("\n"),n={},o=[{obj:n,indent:-1}];for(let r=0;r<t.length;r++){const e=t[r];if(/^\s*(#.*)?$/.test(e))continue;const n=e.match(/^(\s*)(.+)$/);if(!n)continue;const s=n[1].length,i=n[2];for(;o.length>1&&o[o.length-1].indent>=s;)o.pop();const a=o[o.length-1].obj,l=i.match(/^-\s+(.*)$/);if(l){const e=Ci(l[1]);Array.isArray(a)&&a.push(e);continue}const c=i.match(/^([^:]+?):\s*(.*)$/);if(c){const e=c[1].trim(),n=c[2].trim();if(""===n||"|"===n||">"===n){const n=t[r+1];if(n&&/^\s+-\s/.test(n)){const t=[];a[e]=t,o.push({obj:t,indent:s})}else{const t={};a[e]=t,o.push({obj:t,indent:s})}}else a[e]=Ci(n)}}return n}function Ci(e){if("true"===e)return!0;if("false"===e)return!1;if("null"===e||"~"===e)return null;if(e.startsWith("[")&&e.endsWith("]"))return e.slice(1,-1).split(",").map((e=>Ci(e.trim())));if(e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'"))return e.slice(1,-1);const t=Number(e);return isNaN(t)||""===e?e:t}const wi=/* @__PURE__ */new Map([["WordCountPlugin",async()=>{const{WordCountPlugin:e}=await Promise.resolve().then((()=>An));return e}],["AutolinkPlugin",async()=>{const{AutolinkPlugin:e}=await Promise.resolve().then((()=>Rn));return e}],["PlaceholderPlugin",async e=>{const{PlaceholderPlugin:t}=await Promise.resolve().then((()=>Dn));return t(e?.placeholder)}],["SyntaxHighlightPlugin",async e=>{const{SyntaxHighlightPlugin:t}=await import("./index-C88XPqjX.js");return t(e)}],["TablePlugin",async e=>{const{TablePlugin:t}=await import("./index-CifDpN1Y.js");return t(e)}],["BlockTemplatePlugin",async e=>{const{BlockTemplatePlugin:t}=await Promise.resolve().then((()=>wo));return t(e)}],["CommentsPlugin",async e=>{const{CommentsPlugin:t}=await import("./index-DKT1bABL.js");return t(e)}],["CalloutPlugin",async e=>{const{CalloutPlugin:t}=await import("./index-rD8LZENp.js");return t(e)}],["LinkPlugin",async e=>{const{LinkPlugin:t}=await import("./index-4syk9eEO.js");return t(e)}],["TemplatePlugin",async e=>{const{TemplatePlugin:t}=await import("./index-Byatzd-A.js");return t(e)}],["KeyboardPlugin",async e=>{const{KeyboardPlugin:t}=await import("./index-Ch9gotLk.js");return t(e)}],["DragDropPlugin",async e=>{const{DragDropPlugin:t}=await import("./index-Dq0Jr1Ae.js");return t(e)}],["MathPlugin",async e=>{const{MathPlugin:t}=await import("./index-B25zSs0W.js");return t(e)}],["TocPlugin",async e=>{const{TocPlugin:t}=await import("./index-Bw7mlUQo.js");return t(e)}],["AnalyticsPlugin",async e=>{const{AnalyticsPlugin:t}=await import("./index-DWcn72PW.js");return t(e)}],["SpellcheckPlugin",async e=>{const{SpellcheckPlugin:t}=await import("./index-l6Yddj6x.js");return t(e)}],["CollaborationPlugin",async e=>{const{CollaborationPlugin:t}=await import("./index-BCpytFKJ.js");return t(e)}]]),ki=/* @__PURE__ */new Map;function _i(e,t){if("string"!=typeof e||!e)throw new Error("registerPluginFactory: name must be a non-empty string");if("function"!=typeof t)throw new Error("registerPluginFactory: factory must be a function");ki.set(e,t)}function Si(e){ki.delete(e)}function Ai(e){if(e&&Array.isArray(e))return Promise.all(e.map(((e,t)=>{if("function"==typeof e||"object"==typeof e&&null!==e&&"function"==typeof e.init)return e;if("string"==typeof e)return Ei(e);if("object"==typeof e&&null!==e&&"string"==typeof e.name)return Ei(e.name,e.options);throw new Error(`resolvePlugins: invalid plugin entry at index ${t} -- expected string, { name, options }, or plugin instance`)})))}async function Ei(e,t){const n=ki.get(e);if(n)return n(t);const o=wi.get(e);if(o)return o(t);throw new Error(`resolvePlugins: unknown plugin "${e}". Register it with registerPluginFactory() or import it directly.`)}export{is as $,Tr as A,Lr as B,Ao as C,kr as D,Pr as E,Rr as F,Dr as G,Hr as H,Fr as I,Xr as J,fr as K,co as L,Br as M,Vr as N,Zr as O,zr as P,qr as Q,Wr as R,bo as S,vo as T,$r as U,jr as V,Kr as W,Or as X,Ur as Y,ms as Z,ss as _,uo as a,ei as a$,os as a0,Qr as a1,rs as a2,ts as a3,as as a4,ys as a5,fs as a6,ps as a7,bs as a8,hs as a9,yn as aA,ye as aB,y as aC,w as aD,Ws as aE,fn as aF,Qe as aG,Mn as aH,Oe as aI,Ye as aJ,un as aK,I as aL,g as aM,bn as aN,ot as aO,di as aP,ai as aQ,ui as aR,Ue as aS,Je as aT,Cs as aU,Sn as aV,vs as aW,Ls as aX,je as aY,Gs as aZ,qs as a_,gs as aa,re as ab,se as ac,oe as ad,Se as ae,ne as af,_ as ag,k as ah,Nn as ai,kn as aj,Xe as ak,Co as al,Ee as am,vn as an,p as ao,xn as ap,fe as aq,ge as ar,pe as as,nt as at,be as au,he as av,Re as aw,Ze as ax,$e as ay,o as az,Hn as b,Js as b$,si as b0,ni as b1,F as b2,sn as b3,i as b4,a as b5,me as b6,ii as b7,_n as b8,Cn as b9,u as bA,ce as bB,x as bC,Pe as bD,jt as bE,yi as bF,Ts as bG,Q as bH,ri as bI,oi as bJ,rn as bK,dt as bL,en as bM,Nt as bN,Mt as bO,Jt as bP,ln as bQ,$t as bR,zt as bS,Ft as bT,it as bU,qt as bV,ct as bW,vt as bX,tn as bY,bt as bZ,ut as b_,ci as ba,Ke as bb,fi as bc,bi as bd,Xt as be,Os as bf,ee as bg,te as bh,Tt as bi,As as bj,_s as bk,Ss as bl,mn as bm,Rs as bn,d as bo,tt as bp,dn as bq,Xs as br,C as bs,on as bt,Qs as bu,et as bv,de as bw,ue as bx,_e as by,Ae as bz,Ho as c,Yt as c0,Pt as c1,_i as c2,He as c3,Ot as c4,Ut as c5,xt as c6,Es as c7,Ve as c8,Ai as c9,pi as ca,gi as cb,Kt as cc,ti as cd,ze as ce,Ks as cf,js as cg,cn as ch,Ys as ci,Si as cj,Fe as ck,c as cl,l as cm,po as d,Bo as e,Mo as f,No as g,To as h,Io as i,Uo as j,Go as k,ir as l,Jo as m,or as n,nr as o,So as p,er as q,mo as r,qo as s,go as t,ho as u,Xo as v,tr as w,gr as x,pr as y,Sr as z};
3
+ //# sourceMappingURL=index-BvwyeoMb.js.map