revise 2.2.0 → 3.0.1

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 (134) hide show
  1. package/CHANGELOG.md +56 -1182
  2. package/LICENSE +24 -41
  3. package/README.md +103 -26
  4. package/agent.d.ts +139 -0
  5. package/chunks/chunk-U5X47PZ6.js +135 -0
  6. package/chunks/chunk-U6YKQBKL.js +15 -0
  7. package/chunks/chunk-ZLQVPMBN.js +1650 -0
  8. package/chunks/package-5SHL5FOJ.js +14 -0
  9. package/chunks/render-QD5VWKSV.js +109 -0
  10. package/cli-output.schema.json +1984 -0
  11. package/cli.js +3609 -0
  12. package/document.d.ts +320 -0
  13. package/docx.d.ts +73 -0
  14. package/errors.d.ts +14 -0
  15. package/index.d.ts +13 -975
  16. package/index.js +31 -1
  17. package/legacy/editor.d.ts +19 -0
  18. package/legacy/editor.js +16 -0
  19. package/legacy/server.d.ts +37 -0
  20. package/legacy/server.js +25 -0
  21. package/legacy/style.css +2 -0
  22. package/package.d.ts +23 -0
  23. package/package.json +49 -55
  24. package/render.d.ts +27 -0
  25. package/FONT-LICENSE-HAN-EXT-B.txt +0 -91
  26. package/FONT-LICENSE-KATEX.txt +0 -95
  27. package/FONT-LICENSE-LIBERATION.txt +0 -102
  28. package/FONT-LICENSE-NOTO-MULTILINGUAL.txt +0 -93
  29. package/FONT-LICENSE-NOTO-SANS-SC.txt +0 -93
  30. package/FONT-LICENSE-NOTO.txt +0 -94
  31. package/FONT-LICENSE-SOURCE-CODE-PRO.txt +0 -94
  32. package/FONT-LICENSE-SOURCE-SERIF-4.txt +0 -93
  33. package/THIRD-PARTY-NOTICES.md +0 -3376
  34. package/assets/historyMaterializeWorker-B51R08XN.js +0 -612
  35. package/backend.d.ts +0 -161
  36. package/backend.js +0 -3
  37. package/chunks/AgentPageRenderer-CH8kSTJn.js +0 -1
  38. package/chunks/AgentPageRenderer-P23XVguo.js +0 -1
  39. package/chunks/AttachmentDocumentImporter-B1WOaa7d.js +0 -1
  40. package/chunks/AttachmentDocumentImporter-CT_PJp_e.js +0 -1
  41. package/chunks/BidiText-Swm5fl9J.js +0 -160
  42. package/chunks/ColorParserFull-BKH72fK8.js +0 -446
  43. package/chunks/DocumentMutator-btiDK57e.js +0 -31
  44. package/chunks/DocumentScrubber-CMPfm_HF.js +0 -18
  45. package/chunks/DocumentScrubber-Cm2kH8op.js +0 -1
  46. package/chunks/DocumentScrubber-bJoKijol.js +0 -1
  47. package/chunks/DocumentStylesheet-DreoD7sD.js +0 -7
  48. package/chunks/DocxConverter-BcVG-p5K.js +0 -13
  49. package/chunks/DocxConverter-D2bO5RE-.js +0 -1125
  50. package/chunks/DocxConverter-haCfRuWb.js +0 -13
  51. package/chunks/DocxGraft-BRKh4mHQ.js +0 -1
  52. package/chunks/DocxGraft-BxSQtl12.js +0 -7
  53. package/chunks/DocxGraft-C9MBQCnf.js +0 -1
  54. package/chunks/FileImporter-CszqRfVU.js +0 -1
  55. package/chunks/FileImporter-DObFoCCn.js +0 -1
  56. package/chunks/HorizontalRuleOrnaments-gmUZ3R7Q.js +0 -3
  57. package/chunks/HtmlConverter-DwXB4IDh.js +0 -267
  58. package/chunks/ListNumbering-Qlu6AuRZ.js +0 -23
  59. package/chunks/MarkdownConverter-CUC8GgsS.js +0 -57
  60. package/chunks/MathRenderer-DT6GyJXb.js +0 -68
  61. package/chunks/OdtConverter-7h9HHMpL.js +0 -125
  62. package/chunks/OdtConverter-Ct4qypJk.js +0 -6
  63. package/chunks/OdtConverter-DFl__sJc.js +0 -6
  64. package/chunks/OfficeImportShared-BY6FdZ8d.js +0 -1
  65. package/chunks/OfficeImportShared-BrZoDM0j.js +0 -30
  66. package/chunks/OfficeImportShared-Bvm-mOyj.js +0 -1
  67. package/chunks/ParagraphDiffAnalysis-DrmStvmz.js +0 -36
  68. package/chunks/PdfConverter-1wyvoT7X.js +0 -21
  69. package/chunks/PdfConverter-BAoEHILo.js +0 -21
  70. package/chunks/PdfConverter-CKEvFj11.js +0 -448
  71. package/chunks/PdfImportService-BhLPp5uG.js +0 -2
  72. package/chunks/PdfImportService-xbzrN__L.js +0 -2
  73. package/chunks/RtfConverter-Bxn-enp8.js +0 -15
  74. package/chunks/RtfConverter-LZPzBDSr.js +0 -15
  75. package/chunks/RtfConverter-_bacXqr1.js +0 -186
  76. package/chunks/TableBorders-CwnF3jvH.js +0 -30
  77. package/chunks/TableGrid-DbroRucl.js +0 -12
  78. package/chunks/TextFileDecoder--rsVs3NR.js +0 -9
  79. package/chunks/TxtConverter-C7FOwHpH.js +0 -14
  80. package/chunks/UnicodeUtils-CXtusU4g.js +0 -10
  81. package/chunks/XmlConverter-7oo8oeQB.js +0 -2
  82. package/chunks/XmlConverter-DGORHJcZ.js +0 -96
  83. package/chunks/XmlConverter-DeLHReK_.js +0 -2
  84. package/chunks/__vite-browser-external-l0sNRNKZ.js +0 -0
  85. package/chunks/_commonjsHelpers-DaMA6jEr.js +0 -2
  86. package/chunks/_revise-sdk-lazy-harfbuzz-CDWdjF9f.js +0 -1
  87. package/chunks/_revise-sdk-lazy-harfbuzz-X8gnYTZL.js +0 -1
  88. package/chunks/ar-ComXvtmh.js +0 -13
  89. package/chunks/backend-DecaBz-I.js +0 -490
  90. package/chunks/base64-sSPOzq-u.js +0 -198
  91. package/chunks/browser-module-CFmqfGkE.js +0 -1791
  92. package/chunks/browser-module-Dj5o3kuL.js +0 -3
  93. package/chunks/browser-module-UuM_O36W.js +0 -3
  94. package/chunks/bundle.min-DRpfgV69.js +0 -782
  95. package/chunks/capture-1btcWcPF.js +0 -9
  96. package/chunks/carrier-DQeng6yq.js +0 -6
  97. package/chunks/de-BkbpIKxx.js +0 -13
  98. package/chunks/es-CKkXujOF.js +0 -13
  99. package/chunks/fil-piIHMc8F.js +0 -13
  100. package/chunks/footnoteFlatten-DUQticYy.js +0 -6
  101. package/chunks/fr-DuA8qLje.js +0 -13
  102. package/chunks/graftExport-CYnStOdU.js +0 -82
  103. package/chunks/html2canvas.esm-CntiHiYW.js +0 -997
  104. package/chunks/index-2TBhRkX7.js +0 -387
  105. package/chunks/index-BWdRWxoH.js +0 -1807
  106. package/chunks/index-Bf14eTEW.js +0 -1096
  107. package/chunks/index-BwcX_r62.js +0 -387
  108. package/chunks/index.es-CI0QPo8w.js +0 -780
  109. package/chunks/index.es-CI7cDExj.js +0 -5
  110. package/chunks/index.es-DHpGt6Y5.js +0 -5
  111. package/chunks/ja-DgrSs555.js +0 -13
  112. package/chunks/jspdf.es.min--GshOuIm.js +0 -77
  113. package/chunks/jspdf.es.min-DU74zN8b.js +0 -1792
  114. package/chunks/jspdf.es.min-DurJZ1zW.js +0 -77
  115. package/chunks/jszip.min-CPW0h1Kx.js +0 -476
  116. package/chunks/katex-DWj8TvwO.js +0 -1462
  117. package/chunks/pdf-BLWDCiFF.js +0 -1828
  118. package/chunks/persistInlineDocumentImages-DQj2iaqg.js +0 -1
  119. package/chunks/pseudoLocale-BoYTjmiK.js +0 -1
  120. package/chunks/pseudoLocale-DG2NnZmz.js +0 -1
  121. package/chunks/purify.es-BwLardii.js +0 -107
  122. package/chunks/serverDocumentSession-CJ1EH3Tp.js +0 -15
  123. package/chunks/signatures-Bwt_OGik.js +0 -17
  124. package/chunks/suggestionAuthorship-B-IuLQlE.js +0 -1
  125. package/chunks/tree-sitter-D6zWWUMP.js +0 -4
  126. package/chunks/wasmInline.generated-CBYFkdSM.js +0 -1
  127. package/chunks/web-tree-sitter-BXGZGnNj.js +0 -2
  128. package/chunks/zh-9OF3SWWO.js +0 -13
  129. package/full.js +0 -1
  130. package/root.d.ts +0 -5
  131. package/root.js +0 -2
  132. package/serverToolContract.d.ts +0 -391
  133. package/serverToolInputs.generated.d.ts +0 -250
  134. package/style.css +0 -1
@@ -1,31 +0,0 @@
1
- import{r as Ve,p as Pe,c as es,a as ts,e as hl,n as vi,f as fl,j as pl,H as xi,S as ml,k as Sn,l as ns,q as Ai,s as Re,u as is,v as De,w as Y,x as ee,z as bl,A as yl,B as kl,C as Sl,D as Il,E as rs,P as Ge,F as wi,G as Ti,I as ss,J as vl,K as os,L as J,M as Se,y as he,N as G,O as Z,Q as ne,T as dt,U as K,V as zt,W as ie,X as ae,Y as as,Z as ls,_ as xl,$ as cs,a0 as Ye,a1 as Ht,a2 as Al,a3 as wl,a4 as Tl,a5 as In,a6 as Cl,a7 as Pl,a8 as Bl,a9 as gt,aa as Ml,ab as ds,ac as El,ad as $l,ae as Fl,af as gs,ag as Nl,ah as ce,ai as Ci,aj as ut,ak as Tt,al as vn,am as Ct,an as us,ao as xn,ap as An,aq as Ll,ar as wn,as as Ol,at as Rl,d as Pi,au as hs,av as fs,aw as ps,ax as Dl,ay as Bi,az as _l,aA as jl,aB as Xl,aC as Ul,aD as Ue,aE as zl,aF as Mi,aG as Hl,aH as Wl,aI as Yl,aJ as ms,aK as ql,aL as Jl,aM as Kl,aN as Ei,aO as Vl,aP as Gl,aQ as bs}from"./backend-DecaBz-I.js";import{f as z,a as Wt,r as Ql,g as Zl,h as qe,t as Tn,i as Ie,d as Je,j as ys,k as $i,l as Fi,m as Qe,n as ht,o as ks,p as Pt,q as Ni,s as ec,u as tc,v as nc}from"./index-Bf14eTEW.js";import{b as Ze,e as ic}from"./TableGrid-DbroRucl.js";import{e as rc,r as Ss,s as sc,p as oc,i as ac}from"./ListNumbering-Qlu6AuRZ.js";import{i as Is}from"./HorizontalRuleOrnaments-gmUZ3R7Q.js";import{a as lc,s as vs,b as xs,c as Li,d as As}from"./DocumentStylesheet-DreoD7sD.js";import{p as Cn,a as ws,c as Ts,b as Oi,d as cc,e as dc,s as Pn,f as Cs,g as Ps,h as gc,i as uc,n as Bs}from"./TableBorders-CwnF3jvH.js";import{h as _e,H as Yt,D as hc,C as Ms,a as Es,b as $s,n as fc,g as pc,r as mc}from"./BidiText-Swm5fl9J.js";import*as S from"yjs";import{j as qt,i as bc}from"./signatures-Bwt_OGik.js";import{MarkdownConverter as Bn}from"./MarkdownConverter-CUC8GgsS.js";import{r as yc,w as kc,a as Ri}from"./ParagraphDiffAnalysis-DrmStvmz.js";import{R as ze,A as Fs}from"./suggestionAuthorship-B-IuLQlE.js";const Ns=/<!--[^]*?-->|<\/?[a-zA-Z][\w:-]*(?:\s+(?:[^"'<>]|"[^"]*"|'[^']*')*)?\s*\/?>/g,Ls={amp:"&",lt:"<",gt:">",quot:'"',AMP:"&",LT:"<",GT:">",QUOT:'"',apos:"'",nbsp:" ",lsquo:"‘",rsquo:"’",sbquo:"‚",ldquo:"“",rdquo:"”",bdquo:"„",laquo:"«",raquo:"»",lsaquo:"‹",rsaquo:"›",ensp:" ",emsp:" ",thinsp:" ",ndash:"–",mdash:"—",hellip:"…",copy:"©",reg:"®",trade:"™"};function Sc(s){return s.replace(/\\+(["'])/g,"$1")}function Jt(s){return Sc(s.replace(/&(#(?:\d+|x[0-9a-f]+)|[a-z]+);/gi,(e,t)=>{if(!t.startsWith("#"))return Object.prototype.hasOwnProperty.call(Ls,t)?Ls[t]:e;const n=t[1].toLowerCase()==="x",i=Number.parseInt(t.slice(n?2:1),n?16:10);return i>=0&&i<=1114111&&!(i>=55296&&i<=57343)?String.fromCodePoint(i):e}))}function et(s){return s.search(Ns)>=0}function Kt(s){return Jt(s.replace(Ns,e=>/^<br\b/i.test(e)?`
2
- `:""))}function Mn(s){const e=Jt(s);return[...new Set(et(s)?[s,e,Kt(s)]:[s,e])]}function En(s,e,t="prefer-exact",n){if(n&&t!=="normalized"){const i=Rs(s,n,e);if(i.length)return i}for(const i of Mn(e)){const r=Vt(s,i,t);if(r.length)return r}return[]}function Bt(s){return s.replace(/<\/?comment-thread\b[^>]*>/gi,"")}function Os(s,e){return _i(Bt(s),Bt(e))}function Rs(s,e,t){if(!et(t))return[];e=Bt(e);const n=Kt(e);return n.length!==s.length||tt(n)!==tt(s)?[]:Os(e,t).map(({start:i,end:r})=>({start:Kt(e.slice(0,i)).length,end:Kt(e.slice(0,r)).length})).filter(i=>i.end>i.start)}function Di(s){let e="";const t=[],n=[];for(let i=0;i<s.length;i++){const r=i;let o=Ds(s[i]);if(/[\s\u0085]/u.test(o)){for(;i+1<s.length&&/[\s\u0085]/u.test(s[i+1]);)i++;o=" "}e+=o,t.push(r),n.push(i+1)}return{text:e,starts:t,ends:n}}function Ds(s){return/[\s\u0085]/u.test(s)?" ":/[\u2018-\u201b\u2039\u203a\uff07]/u.test(s)?"'":/[\u201c-\u201f\u00ab\u00bb\uff02]/u.test(s)?'"':s}function tt(s){let e="";for(let t=0;t<s.length;t++){const n=Ds(s[t]);e+=/[\u2012-\u2014]/u.test(n)?"-":n}return e}function _i(s,e){if(!e)return[];const t=[];let n=0;for(;n<=s.length-e.length;){const i=s.indexOf(e,n);if(i<0)break;t.push({start:i,end:i+e.length}),n=i+1}return t}function Vt(s,e,t="prefer-exact"){if(t!=="normalized"){const r=_i(s,e);if(r.length>0||t==="exact")return r}const n=Di(s),i=Di(e).text;return i.trim()?_i(n.text,i).map(({start:r,end:o})=>({start:n.starts[r],end:n.ends[o-1]})):[]}function Ic(s,e,t,n,i){for(const r of["exact","normalized"]){const o=i?i(e,r):En(s,e,r,n),a=i?i(t,r):En(s,t,r,n),l=[];let c=0;for(const d of o){for(;c<a.length&&a[c].start<d.end;)c++;for(let g=c;g<a.length;g++)if(l.push({start:d.start,end:a[g].end}),l.length===2)return l}if(l.length)return l}return[]}function vc(s){const e=s.children.filter(t=>t.type==="text");return e.length===0?[{type:"text",text:""}]:e}function $n(s){return vc(s).reduce((e,t)=>e+t.text.length,0)}function xc(s,e){const t=z(s,e);if(!t||!t.id)return null;if(t.type==="paragraph"){let n=0;for(const i of t.children)i.type==="text"&&(n+=i.text.length);return{block:t.id,offset:n}}if(t.type==="list"){const n=t;let i=0;for(let r=0;r<n.children.length;r++)i+=$n(n.children[r]),r<n.children.length-1&&(i+=1);return{block:t.id,offset:i}}return{block:t.id,offset:0}}function ji(s){if(!s)return;const e=s.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(px|pt|in)?$/i);if(!e)return;const t=parseFloat(e[1]);if(Number.isFinite(t))switch(e[2]?.toLowerCase()){case"pt":return t*4/3;case"in":return t*96;default:return t}}function _s(s){const e=s.match(/(?:^|;)\s*margin:\s*([^;]+)/i)?.[1];if(!e)return;const t=e.trim().split(/\s+/);if(t.length<1||t.length>4)return;const[n,i=n,r=n,o=i]=t;return{top:n,right:i,bottom:r,left:o}}function Ac(s){const e={},t=_s(s),n=s.match(/(?:^|;)\s*margin-top:\s*([^;]+)/i)?.[1]??t?.top,i=s.match(/(?:^|;)\s*margin-bottom:\s*([^;]+)/i)?.[1]??t?.bottom,r=ji(n);r!==void 0&&(e.spaceBefore=Math.round(r*100)/100);const o=ji(i);o!==void 0&&(e.spaceAfter=Math.round(o*100)/100);const a=s.match(/(?:^|;)\s*line-height:\s*([\d.]+)\s*(?:;|$)/i);if(a){const l=parseFloat(a[1]);Number.isFinite(l)&&l>=.5&&l<=4&&(e.lineSpacing=l)}return e}class fe extends Error{constructor(e,t,n="validation",i=!1,r="unchanged",o){super(t),this.code=e,this.phase=n,this.retryable=i,this.mutationOutcome=r,this.details=o,this.name="SemanticToolError"}}function Mt(s){return s instanceof fe?{code:s.code,phase:s.phase,retryable:s.retryable,mutationOutcome:s.mutationOutcome,details:s.details}:void 0}const js=24e3,Xs=25;function wc(s,e,t){const n={type:"doc",children:s},i=s.findIndex(l=>!!z({...n,children:[l]},e)),r=s.findIndex(l=>!!z({...n,children:[l]},t)),o=s.flatMap((l,c)=>{if(l.type!=="table"||l.children.length<Xs)return[l];const d=l.children.findIndex(m=>m.children.some(y=>!!z(y,e))),g=l.children.findIndex(m=>m.children.some(y=>!!z(y,t)));if(!((i<0||c>=i)&&(r<0||c<=r))||d<0&&g<0&&i===r)return[];const u=Ze(l),p=ic(u,{top:d<0?0:d,bottom:g<0?u.rows-1:g,left:0,right:u.cols-1}),h=p.top,f=p.bottom;return[{...l,children:l.children.filter((m,y)=>l.hasHeader&&y===0||y>=h&&y<=f)}]});if(JSON.stringify(o).length<=js)return o;const a=[e,t].flatMap((l,c)=>{if(c&&l===e)return[];for(const d of s){const g=z({type:"doc",children:[d]},l);if(g)return[g]}return[]});return JSON.stringify(a).length<=js?a:[]}const Us=s=>s.replace(/\\+u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)));function zs(s,e){if(!s)return;const t=s.trim().toLowerCase();if(!t||t==="normal")return;const n=t.match(/^(-?\d+(?:\.\d+)?|-?\.\d+)(px|pt|em|rem|pc|in|cm|mm)?$/);if(!n)return;const i=parseFloat(n[1]);if(Number.isFinite(i))switch(n[2]??"px"){case"px":return i;case"pt":return i*(96/72);case"em":return i*(e??16);case"rem":return i*16;case"pc":return i*16;case"in":return i*96;case"cm":return i*(96/2.54);case"mm":return i*(96/25.4);default:return}}function Tc(s){const e=s?.trim().match(/^([\d.]+)(px|pt)?$/i);if(!e)return;const t=parseFloat(e[1]);if(Number.isFinite(t))return e[2]?.toLowerCase()==="pt"?t*4/3:t}function Cc(s){if(!s)return;const e=i=>s.match(new RegExp(`(?:^|;)\\s*${i}\\s*:\\s*([^;]+)`,"i"))?.[1]?.trim(),t=Cn(e("border")),n={};for(const i of["top","bottom","left","right"]){const r=s.match(new RegExp(`border-${i}:\\s*([\\d.]+)px\\s+(solid|double|dashed|dotted|none)\\s+(#[0-9a-fA-F]{3,8}|[a-zA-Z]+)`,"i"));let o;if(r){const l=r[2].toLowerCase();o={width:l==="none"?0:parseFloat(r[1]),style:l==="solid"?"single":l,color:r[3]}}else{const l=Cn(e(`border-${i}`))??t;l&&(o={...l})}if(!o)continue;const a=Tc(e(`padding-${i}`));a!==void 0&&a>0&&(o.space=Math.round(a*100)/100),n[i]=o}return Object.keys(n).length>0?JSON.stringify(n):void 0}const Pc=new Set(["p","center","h1","h2","h3","h4","h5","h6","ul","ol","div","table","pre","img","latex","page-break","section-break","toc","hr","docx-raw"]),Bc=/[&<>"']/,Mc=/[&<>"']/g,Ec={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#039;"};function $c(s){return Ec[s]??s}function Fc(s){const e=s.trim();if(e.length<2)return e;const t=[['"','"'],["'","'"],["“","”"],["‘","’"]];for(const[n,i]of t)if(e.startsWith(n)&&e.endsWith(i))return e.slice(n.length,e.length-i.length).trim();return e}let Fn=null;function Xi(s){return Fn||(Fn=new DOMParser().parseFromString("","text/html")),Fn.body.innerHTML=s.replace(/<!--[\s\S]*?-->|<\/?[a-z][a-z0-9-]*(?:[^<>"']|"[^"]*"|'[^']*')*>/gi,e=>{const t=e.match(/^<(page-break|section-break|docx-raw|toc)(?=[\s/>])/i);return t&&/\/\s*>$/.test(e)?e.replace(/\/\s*>$/,`></${t[1]}>`):e}),Fn}function Nc(s,e={}){return!s||e.code||e.latex?s:Us(s.replace(/\\+(["'])/g,"$1"))}function Hs(s){const e=new Set;function t(n){if("id"in n&&n.id&&e.add(n.id),n.type!=="paragraph"){if(n.type==="list")for(const i of n.children)i.id&&e.add(i.id);else if(n.type==="container")for(const i of n.children)t(i);else if(n.type==="table")for(const i of n.children){i.id&&e.add(i.id);for(const r of i.children){r.id&&e.add(r.id);for(const o of r.children)t(o)}}}}for(const n of s.children)t(n);return e}function pe(s,e){if(!e?.validIds)return s||Y();if(s&&e.validIds.has(s)&&!e.usedIds.has(s))return e.usedIds.add(s),s;let t=Y();for(;e.usedIds.has(t);)t=Y();return e.usedIds.add(t),t}const Nn=class{static createParsingContext(e){const t=new Map,n=i=>{i.type==="image"&&t.set(i.id,i),"children"in i&&i.children.forEach(n)};n(e);for(const i of e.notes??[])n(i);return{imagesById:t,validIds:Hs(e),indentStepPx:this.resolveIndentStepPx(e),documentFontFamily:this.findOmittableDocumentFontFamily(e)}}static toAgentHtml(e,t={}){const n=this.resolveOmittableDocumentFontFamily(e,t),i=this.pageLayoutToHtmlComment(e),r=[...e.children,...e.notes??[]].map(o=>this.blockToHtml(o,e,n,t)).filter(o=>o.length>0).join(`
3
- `);return i&&r.length>0?`${i}
4
- ${r}`:i||r}static toInternalImageHtml(e){return this.imageBlockToHtml(e,!0)}static toInternalHtml(e){return this.toAgentHtml(e,{scanDocumentFontFamily:!1,includeImageSources:!0,includeZeroListLevels:!0})}static pageLayoutToHtmlComment(e){const t=e.pageless===!0;if(!e.pageLayout&&!t)return null;const n=Ve(e.pageLayout),i=this.formatInchesForComment(Pe(n.marginTopPx)),r=this.formatInchesForComment(Pe(n.marginRightPx)),o=this.formatInchesForComment(Pe(n.marginBottomPx)),a=this.formatInchesForComment(Pe(n.marginLeftPx)),l=this.formatInchesForComment(Pe(n.indentStepPx)),c=this.formatInchesForComment(Pe(n.blockSpacingPx)),d=n.marginTopPx===n.marginRightPx&&n.marginTopPx===n.marginBottomPx&&n.marginTopPx===n.marginLeftPx?` margin-in="${i}"`:"",g=this.getEffectivePageNumberSettings(e,n),u=` show-page-numbers="${g.showPageNumbers?"true":"false"}" page-number-position="${g.pageNumberPosition}" page-number-start="${n.pageNumberStart}"${n.pageNumberFormat!=="decimal"?` page-number-format="${n.pageNumberFormat}"`:""}`,p=this.formatInchesForComment(es(n.columnGapTwips));return`<!--revise-page-layout${t?' pageless="true"':""} page-size="${n.pageSize}" orientation="${n.orientation}" margin-top-in="${i}" margin-right-in="${r}" margin-bottom-in="${o}" margin-left-in="${a}"${d} indent-in="${l}" block-spacing-in="${c}" column-count="${n.columnCount}" column-gap-in="${p}"${u}-->`}static formatInchesForComment(e){return Number.isFinite(e)?e.toFixed(2).replace(/\.00$/,"").replace(/(\.\d)0$/,"$1"):"0"}static toDocumentOverview(e,t){const n=e.children.length,i=t?.pendingChangeCounts,r=t?.measurements,o=b=>{if(!i)return 0;const k=i instanceof Map?i.get(b):i[b];return typeof k=="number"&&Number.isFinite(k)?Math.max(0,Math.floor(k)):0},a=[],l=[],c=[];for(let b=0;b<e.children.length;b++){const k=e.children[b];k.id&&o(k.id)>0&&c.push(b),k.type==="paragraph"&&k.heading!==void 0&&k.heading<=2?a.push(b):k.type!=="image"&&l.push(b)}const d=a.length>this.MAX_OVERVIEW_BLOCKS?Math.ceil(a.length/this.MAX_OVERVIEW_BLOCKS):1,g=d>1?a.filter((b,k)=>k%d===0):a,u=Math.max(0,this.MAX_OVERVIEW_BLOCKS-g.length),p=[];let h=1;if(u>0&&l.length>0){h=Math.max(1,Math.ceil(l.length/u));for(let b=0;b<l.length;b++)b%h===0&&p.push(l[b])}const f=Array.from(new Set([...g,...p,...c])).sort((b,k)=>b-k),m=n-1;m>=0&&!f.includes(m)&&f.push(m);const y=f.map(b=>{const k=this.getBlockId(e.children[b]),I=o(k),v=r?.blocks?.get(k);return{index:b,id:k,type:this.getBlockTypeLabel(e.children[b]),preview:this.getBlockPreview(e.children[b]),...v?.wordCount!==void 0?{wordCount:v.wordCount}:{},...v?.pageStart!==void 0?{pageStart:v.pageStart,pageEnd:v.pageEnd}:{},...I>0?{pendingChangeCount:I}:{},isLast:b===m}});return{title:e.title||"Untitled",totalBlocks:n,...r?{totalWords:r.wordCount,totalParagraphs:r.paragraphCount}:{},...r?.pageCount!==void 0?{pageCount:r.pageCount}:{},blockIds:y,samplingInterval:Math.max(d,h),...r?.sections&&r.sections.length>0?{sections:r.sections}:{}}}static toDocumentLayoutContext(e){const t=Ve(e.pageLayout),n=ts(t),i=this.getEffectivePageNumberSettings(e,t);return{pageless:e.pageless===!0,pageSize:t.pageSize,orientation:t.orientation,pageWidth:this.formatInchesLength(Pe(n.pageWidth)),pageHeight:this.formatInchesLength(Pe(n.pageHeight)),marginTop:this.formatInchesLength(Pe(t.marginTopPx)),marginRight:this.formatInchesLength(Pe(t.marginRightPx)),marginBottom:this.formatInchesLength(Pe(t.marginBottomPx)),marginLeft:this.formatInchesLength(Pe(t.marginLeftPx)),indentStep:this.formatInchesLength(Pe(t.indentStepPx)),blockSpacing:this.formatInchesLength(Pe(t.blockSpacingPx)),columnCount:t.columnCount,columnGap:this.formatInchesLength(es(t.columnGapTwips)),showPageNumbers:i.showPageNumbers,pageNumberPosition:i.pageNumberPosition,pageNumberStart:t.pageNumberStart,...t.pageNumberFormat!=="decimal"?{pageNumberFormat:t.pageNumberFormat}:{},pageBorders:t.pageBorders,...t.pageNumberRestart?{pageNumberRestart:!0}:{}}}static getEffectivePageNumberSettings(e,t){for(const n of e.chrome??[])for(let i=0;i<n.children.length;i+=1){const r=n.children[i],o=l=>{if(!l||typeof l!="object")return!1;if(Array.isArray(l))return l.some(o);const c=l;return c.marks?.field==="page"||o(c.children)};if(!o(r))continue;const a=i===0?"left":i===2?"right":null;return{showPageNumbers:!0,pageNumberPosition:a?`${n.side==="header"?"top":"bottom"}-${a}`:t.pageNumberPosition}}return{showPageNumbers:t.showPageNumbers,pageNumberPosition:t.pageNumberPosition}}static formatInchesLength(e){return`${this.formatInchesForComment(e)}in`}static formatOverview(e){const t=[];if(t.push(`Document: "${e.title}"`),t.push(`Total blocks: ${e.totalBlocks}`),e.totalWords!==void 0&&t.push(`Total words: ${e.totalWords}`),e.totalParagraphs!==void 0&&t.push(`Total paragraphs: ${e.totalParagraphs}`),e.pageCount!==void 0&&t.push(`Pages: ${e.pageCount}`),e.sections&&e.sections.length>0){t.push(""),t.push("Sections (inclusive ranges):");for(const n of e.sections){const i=this.formatOverviewPageRange(n.pageStart,n.pageEnd);t.push(`[${n.startIndex}-${n.endIndex} inclusive] [#${n.startBlockId}-#${n.endBlockId} inclusive] h${n.headingLevel} "${n.title}" words=${n.wordCount} paragraphs=${n.paragraphCount}${i?` pages=${i}`:""}`)}}e.samplingInterval>1&&t.push(`(Showing every ${e.samplingInterval}${this.ordinalSuffix(e.samplingInterval)} block ID)`),t.push(""),t.push("Block IDs:");for(const n of e.blockIds){const i=n.preview?` — ${n.preview}`:"",r=n.wordCount!==void 0?` words=${n.wordCount}`:"",o=this.formatOverviewPageRange(n.pageStart,n.pageEnd),a=o?` pages=${o}`:"",l=n.isLast?" [LAST BLOCK]":"",c=n.pendingChangeCount&&n.pendingChangeCount>0?` [${n.pendingChangeCount} pending ${n.pendingChangeCount===1?"change":"changes"}]`:"";t.push(`[${n.index}] ${n.id} (${n.type})${r}${a}${c}${i}${l}`)}return t.join(`
5
- `)}static formatOverviewPageRange(e,t){return e===void 0||t===void 0?"":e===t?`${e}`:`${e}-${t}`}static extractBlocksById(e,t,n){const i=Wt(e,t);return i===-1?null:this.extractBlocksByIndex(e,i,n)}static extractBlocksByIndex(e,t,n,i={}){const r=Math.max(0,Math.min(t,e.children.length)),o=Math.min(n,100),a=Math.min(r+o,e.children.length),l=this.resolveOmittableDocumentFontFamily(e,i);return{html:e.children.slice(r,a).map(c=>this.blockToHtml(c,e,l)).filter(c=>c.length>0).join(`
6
- `),startIndex:r,endIndex:a-1,totalBlocks:e.children.length}}static formatBlockRange(e){const t=[];return t.push(`Showing blocks ${e.startIndex}-${e.endIndex} of ${e.totalBlocks} total:`),t.push(""),t.push(e.html),t.join(`
7
- `)}static searchDocument(e,t){const n=[],i=t.map(o=>{if(o.startsWith("regex:")){const a=o.slice(6);try{const l=new RegExp(a,"i");return{query:o,match:c=>l.test(c)}}catch{return{query:o,match:l=>l.toLowerCase().includes(a.toLowerCase())}}}else{const a=Fc(o).toLowerCase();return{query:o,match:l=>l.toLowerCase().includes(a)}}}),r=[...e.children,...e.notes??[]];for(let o=0;o<r.length;o++){const a=r[o],l=this.getBlockPlainText(a),c=this.getBlockId(a),d=[];for(const g of i)g.match(l)&&d.push(g.query);d.length>0&&c&&n.push({blockId:c,blockIndex:o,matchedQueries:d})}return n}static findHighlights(e,t){const n=t?_e(t):void 0;if(t&&!n)return[];const i=[];for(let r=0;r<e.children.length;r++){const o=e.children[r],a=this.getBlockId(o);if(!a)continue;const l=Array.from(this.collectHighlightColors(o));l.length!==0&&(n&&!l.includes(n)||i.push({blockId:a,blockIndex:r,matchedColors:n?[n]:l}))}return i}static extractSpecificBlocks(e,t,n,i={}){const r=[],o=[],a=[],l=[],c=new Set,d=this.resolveOmittableDocumentFontFamily(e,i),g=[...e.children,...e.notes??[]],u=this.findTopLevelIndexesByBlockId(e,t),p=n&&n.length>0?this.buildSelectionInfoForBlocks(g,n):null;for(const h of t){const f=u.get(h);if(f===void 0){o.push(h);continue}const m=g[f],y=this.getBlockId(m);if(!y){o.push(h);continue}if(r.push(h),c.has(y))continue;c.add(y);const b=p?.get(y),k=this.blockToHtmlWithSelections(m,e,b,d,p??void 0);a.push(k),l.push({id:y,blockIndex:f,html:k})}return{html:a.filter(h=>h.length>0).join(`
8
- `),foundIds:r,missingIds:o,foundBlocks:l}}static renderSubtree(e,t){return this.blockToHtml(e,t,void 0,{scanDocumentFontFamily:!1})}static renderTableRow(e,t,n){const i=e.children.findIndex(o=>o.id===t.id),r=this.tableRowToHtml(e,t,i,Ze(e),n);return`<table_row table_id="${this.escapeAttribute(e.id)}" id="${this.escapeAttribute(t.id)}" row_index="${i}">
9
- ${r}
10
- </table_row>`}static renderTopLevelBlocks(e,t,n={}){const i=this.resolveOmittableDocumentFontFamily(e,n),r=[],o=new Set;for(const a of t){if(o.has(a)||a<0||a>=e.children.length)continue;o.add(a);const l=e.children[a],c=this.getBlockId(l);c&&r.push({id:c,blockIndex:a,html:this.blockToHtml(l,e,i)})}return r}static buildSelectionInfoForBlocks(e,t){const n=[],i=new Map,r=a=>{if(a.type==="paragraph"||a.type==="list"){if(n.push(a.id),a.type==="list"){let l=0;for(const c of a.children){const d=c.children.reduce((g,u)=>g+u.text.length,0);i.set(c.id,{listId:a.id,offset:l,length:d}),l+=d+1}}}else if("children"in a)for(const l of a.children)r(l)};e.forEach(r);const o=t.map(a=>{const l=i.get(a.startBlock),c=i.get(a.endBlock);return{...a,startBlock:l?.listId??a.startBlock,endBlock:c?.listId??a.endBlock,startOffset:l?l.offset+(a.startOffset??0):a.startOffset,endOffset:c?c.offset+(a.endOffset??c.length):a.endOffset}});return this.buildSelectionInfoForMultiple(n,o)}static buildSelectionInfoForMultiple(e,t){const n=new Map;for(const i of t){let r=i,o=e.indexOf(r.startBlock),a=e.indexOf(r.endBlock);if(!(o===-1||a===-1)){(o>a||o===a&&r.startOffset!==void 0&&r.endOffset!==void 0&&r.startOffset>r.endOffset)&&([o,a]=[a,o],r={...r,startOffset:r.endOffset,endOffset:r.startOffset});for(let l=o;l<=a;l++){const c=e[l],d={};l===o&&(d.startOffset=r.startOffset),l===a&&(d.endOffset=r.endOffset),n.has(c)||n.set(c,[]),n.get(c).push(d)}}}return n}static blockToHtmlWithSelections(e,t,n,i,r){if(e.type==="paragraph"&&n&&n.length>0)return this.paragraphToHtmlWithSelections(e,t,n,i);if(e.type==="list"&&n?.length)return this.listToHtml(e,i,t,{},n);const o=this.blockToHtml(e,t,i);if(!r?.size||!("children"in e))return o;const a=[],l=d=>{const g=r.get(d.id);(d.type==="paragraph"||d.type==="list")&&g?.length?a.push({block:d,ranges:g}):"children"in d&&d.type!=="list"&&d.children.forEach(u=>l(u))};if(e.children.forEach(d=>l(d)),!a.length)return o;const c=document.createElement("div");c.innerHTML=o;for(const d of a){const g=Array.from(c.querySelectorAll("[id]")).find(u=>u.id===d.block.id);g&&(g.outerHTML=this.blockToHtmlWithSelections(d.block,t,d.ranges,i))}return c.innerHTML}static paragraphToHtmlWithSelections(e,t,n,i){if(e.type!=="paragraph")return"";const r=e.heading?this.extractUniformTextFontSize(e.children):void 0,o=this.textNodesToHtmlWithSelections(e.children,t,n,i,e),a=[];e.align&&a.push(`text-align: ${e.align}`),this.appendParagraphIndentStyles(a,e,this.resolveIndentStepPx(t)),e.heading&&r!==void 0&&a.push(`font-size: ${r}px`);const l=a.length>0?` style="${a.join("; ")}"`:"",c=e.id?` id="${this.escapeHtml(e.id)}"`:"",d=e.styleId?` data-style-id="${this.escapeHtml(e.styleId)}"`:"",g=e.tabStops?` data-tab-stops="${this.escapeHtml(e.tabStops)}"`:"",u=e.direction?` dir="${e.direction}"`:"";return e.heading?`<h${e.heading}${c}${u}${d}${g}${l}>${o}</h${e.heading}>`:`<p${c}${u}${d}${g}${l}>${o}</p>`}static textNodesToHtmlWithSelections(e,t,n,i,r){const o=this.extractUniformTextFontFamily(e);let a=0;for(const h of e)h.type==="text"&&(a+=h.text.length);const l=[];n.forEach((h,f)=>{const m=h.startOffset??0,y=h.endOffset??a;l.push({pos:m,type:"open",idx:f}),l.push({pos:y,type:"close",idx:f})}),l.sort((h,f)=>h.pos!==f.pos?h.pos-f.pos:h.type==="open"&&f.type==="close"?-1:h.type==="close"&&f.type==="open"?1:0);let c=0,d=0;const g=[],u=r?.heading?this.extractUniformTextFontSize(e):void 0,p=this.coalesceAdjacentTextNodesForHtml(e,o,r?.heading?u:void 0,i);for(const h of p)if(h.type==="text"){const f=h.text,m=c,y=c+f.length;let b=0;for(;d<l.length&&l[d].pos<=y;){const k=l[d];if(k.pos>m+b){const I=f.slice(b,k.pos-m);g.push(this.textToHtmlWithMarks(I,h.marks,r,t,u,o,i)),b=k.pos-m}g.push(k.type==="open"?"<user-selection>":"</user-selection>"),d++}if(b<f.length){const k=f.slice(b);g.push(this.textToHtmlWithMarks(k,h.marks,r,t,u,o,i))}c=y}for(;d<l.length;){const h=l[d];g.push(h.type==="open"?"<user-selection>":"</user-selection>"),d++}return g.join("")}static textToHtmlWithMarks(e,t,n,i,r,o,a){let l=this.escapeHtml(e);if(l=l.replace(/\r\n|\r|\n/g,"<br>"),t){const c=[];if(t.fontFamily){const h=o??Ql(void 0,n,i,this.DEFAULT_FONT_FAMILY);t.fontFamily!==h&&t.fontFamily!==a&&c.push(`font-family: ${this.escapeHtml(t.fontFamily)}`)}if(t.bold&&(l=`<b>${l}</b>`),t.italic&&(l=`<i>${l}</i>`),t.underline&&(l=`<u>${l}</u>`),t.strikethrough&&(l=`<s>${l}</s>`),t.code&&(l=`<code>${l}</code>`),t.latex&&(l=`<latex-inline>${l}</latex-inline>`),t.superscript||t.footnoteRef||t.footnotePendingBody){const h=[];t.footnoteRef&&h.push(`data-footnote-ref="${this.escapeHtml(t.footnoteRef)}"`),t.footnotePendingBody!==void 0&&(h.push(`data-footnote="${this.escapeHtml(t.footnotePendingBody)}"`),t.footnotePendingKind==="endnote"&&h.push('data-note-kind="endnote"')),l=`<sup${h.length>0?` ${h.join(" ")}`:""}>${l}</sup>`}t.subscript&&(l=`<sub>${l}</sub>`),t.fontSize&&!(n?.heading&&r===t.fontSize)&&c.push(`font-size: ${t.fontSize}px`),t.color&&c.push(`color: ${this.escapeHtml(t.color)}`),t.doubleStrikethrough&&c.push("text-decoration: line-through double"),t.smallCaps&&c.push("font-variant: small-caps"),t.allCaps&&c.push("text-transform: uppercase"),typeof t.letterSpacing=="number"&&Number.isFinite(t.letterSpacing)&&c.push(`letter-spacing: ${t.letterSpacing}px`);const d=[];c.length>0&&d.push(`style="${c.join("; ")}"`);const g=hl(t);g.length>0&&d.push(`data-docx-explicit-false-marks="${g.join(",")}"`);const u=vi(t.docxRunPropertyResets);u&&d.push(`data-docx-run-property-resets="${u}"`),d.length>0&&(l=`<span ${d.join(" ")}>${l}</span>`),t.hidden&&(l=`<span data-word-hidden="true">${l}</span>`),t.bookmark&&(l=`<span data-bookmark="${this.escapeHtml(t.bookmark)}">${l}</span>`),t.fieldInstr&&(l=`<span data-field-instr="${this.escapeHtml(t.fieldInstr)}">${l}</span>`);const p=_e(t.backgroundColor);p&&(l=`<mark color="${this.escapeHtml(p)}">${l}</mark>`),t.link&&(l=`<a href="${this.escapeHtml(t.link)}">${l}</a>`),t.comment&&i&&(l=this.wrapWithCommentThreads(l,t.comment.split(","),i))}return l}static formatSpecificBlocks(e){const t=[],n=e.foundBlocks&&e.foundBlocks.length>0?e.foundBlocks.length:e.foundIds.length;if(e.missingIds.length>0&&(t.push(`Note: ${e.missingIds.length} block(s) not found: ${e.missingIds.join(", ")}`),t.push("")),t.push(`Showing ${n} block(s):`),t.push(""),e.foundBlocks&&e.foundBlocks.length>0)for(let i=0;i<e.foundBlocks.length;i++){const r=e.foundBlocks[i];if(i>0){const o=e.foundBlocks[i-1],a=r.blockIndex-o.blockIndex-1;if(a>0){const l=a===1?"block":"blocks";t.push(`(${a} ${l} omitted...)`)}}t.push(r.html)}else t.push(e.html);return t.join(`
11
- `)}static getBlockId(e){return"id"in e&&e.id?e.id:""}static getBlockTypeLabel(e){return e.type==="paragraph"&&e.heading!==void 0&&e.heading>=1&&e.heading<=6?`h${e.heading}`:e.type}static getBlockPreview(e){const t=this.getBlockPlainText(e).split(/\s+/).filter(i=>i.length>0),n=t.slice(0,10).join(" ");return t.length>10?n+"...":n}static getBlockPlainText(e){switch(e.type){case"paragraph":return e.children.map(t=>t.type==="text"?t.text:"").join("");case"list":return e.children.map(t=>t.children.map(n=>n.type==="text"?n.text:"").join("")).join(" ");case"code":return e.content||"";case"table":return"[table] "+e.children.flatMap(t=>t.children).map(t=>this.getBlockPlainText(t)).join(" ");case"table-cell":case"container":case"footnote":return e.children.map(t=>this.getBlockPlainText(t)).join(" ");case"image":return`[image${e.alt?`: ${e.alt}`:""}]`;case"math":return`[math: ${e.content||""}]`;case"docx-raw":return`[${e.tagName}${e.detail?`: ${e.detail}`:""}]`;case"page-break":return"[page break]";case"section-break":return"[section break]";case"toc":return"[table of contents]";default:return""}}static collectHighlightColors(e,t=new Set){switch(e.type){case"paragraph":for(const n of e.children){const i=_e(n.marks?.backgroundColor);i&&t.add(i)}break;case"list":for(const n of e.children)for(const i of n.children){const r=_e(i.marks?.backgroundColor);r&&t.add(r)}break;case"container":for(const n of e.children)this.collectHighlightColors(n,t);break;case"table":for(const n of e.children)for(const i of n.children)for(const r of i.children)this.collectHighlightColors(r,t);break}return t}static ordinalSuffix(e){const t=["th","st","nd","rd"],n=e%100;return t[(n-20)%10]||t[n]||t[0]}static blockToHtml(e,t,n,i={}){let r;switch(e.type){case"placeholder":r="";break;case"image":r=this.imageBlockToHtml(e,i.includeImageSources);break;case"list":r=this.listToHtml(e,n,t,i);break;case"container":r=this.containerToHtml(e,t,n,i);break;case"table":r=this.tableToHtml(e,t,n,i);break;case"table-cell":r=this.tableCellToHtml(e,t,n,i);break;case"paragraph":r=this.paragraphToHtml(e,t,n);break;case"code":r=this.codeBlockToHtml(e);break;case"math":r=this.mathBlockToHtml(e);break;case"page-break":r=this.pageBreakToHtml(e);break;case"docx-raw":r=this.docxRawToHtml(e);break;case"section-break":r=this.sectionBreakToHtml(e);break;case"toc":r=this.tocToHtml(e);break;case"header-footer":r="";break;case"footnote":r=this.footnoteToHtml(e,t,n,i);break;default:r="";break}if(!r||!t||!("id"in e)||!e.id)return r;const o=(t.comments??[]).filter(a=>!a.parentId&&a.anchorBlockId===e.id).map(a=>a.id);return this.wrapWithCommentThreads(r,o,t)}static footnoteToHtml(e,t,n,i={}){const r=e.children.map(o=>this.blockToHtml(o,t,n,i)).filter(Boolean).join("");return`<aside data-footnote data-note-kind="${e.noteKind==="endnote"?"endnote":"footnote"}" id="${e.id}">${r}</aside>`}static docxRawToHtml(e){const t=e.id?` id="${this.escapeAttribute(e.id)}"`:"",n=e.detail?` detail="${this.escapeAttribute(e.detail)}"`:"";return`<docx-raw${t} tag="${this.escapeAttribute(e.tagName)}"${n} />`}static pageBreakToHtml(e){return`<page-break${e.id?` id="${this.escapeAttribute(e.id)}"`:""} />`}static sectionBreakToHtml(e){const t=e.id?` id="${this.escapeAttribute(e.id)}"`:"",n=e.breakType?` break-type="${this.escapeAttribute(e.breakType)}"`:"",i=e.layout?` layout="${this.escapeAttribute(JSON.stringify(e.layout))}"`:"";return`<section-break${t}${n}${i} />`}static tocToHtml(e){const t=e.id?` id="${this.escapeAttribute(e.id)}"`:"",n=[];e.direction&&n.push(`direction: ${e.direction}`),e.align&&n.push(`text-align: ${e.align}`),e.fontFamily&&n.push(`font-family: ${e.fontFamily}`),e.fontSize&&n.push(`font-size: ${e.fontSize}px`),e.color&&n.push(`color: ${e.color}`);const i=n.length>0?` style="${this.escapeAttribute(n.join("; "))}"`:"";return`<toc${t} levels="${fl(e)}"${e.direction?` dir="${e.direction}"`:""}${i}></toc>`}static codeBlockToHtml(e){const t=e.language?.trim().toLowerCase();if(t==="latex"||t==="latex-inline"){const o=e.id?` id="${this.escapeAttribute(e.id)}"`:"",a=t==="latex-inline"?' display="inline"':"",l=this.escapeHtml(e.content||"");return`<latex${o}${a}>${l}</latex>`}const n=e.id?` id="${this.escapeAttribute(e.id)}"`:"",i=e.language?` language="${this.escapeAttribute(e.language)}"`:"",r=this.escapeHtml(e.content||"");return`<pre${n}${i}>${r}</pre>`}static mathBlockToHtml(e){const t=e.id?` id="${this.escapeAttribute(e.id)}"`:"",n=e.displayMode&&e.displayMode!=="block"?` display="${e.displayMode}"`:"",i=e.align&&e.align!=="center"?` align="${e.align}"`:"",r=this.escapeHtml(e.content||"");return`<latex${t}${n}${i}>${r}</latex>`}static paragraphToHtml(e,t,n){if(e.type!=="paragraph")return"";const i=this.paragraphCarriesNonRuleLayout(e)?null:pl(e);if(i){const h=e.id?` id="${this.escapeHtml(e.id)}"`:"",f=Is(i.style),m=i.width===xi.width&&i.color.toLowerCase()===xi.color.toLowerCase(),y=f?` data-rule="${i.style}"`:"";let b="";if(!m||!f&&i.style!==xi.style){const k=f||i.style==="single"?"solid":i.style;b=` style="border-bottom: ${i.width}px ${k} ${i.color}"`}return`<hr${h}${y}${b} />`}const r=this.extractUniformTextFontFamily(e.children),o=e.heading?this.extractUniformTextFontSize(e.children):void 0,a=this.coalesceAdjacentTextNodesForHtml(e.children,r,e.heading?o:void 0,n).map(h=>h.type==="text"?this.textNodeToHtml(h,e,t,o,r,n):"").join(""),l=[];e.align&&l.push(`text-align: ${e.align}`),this.appendParagraphIndentStyles(l,e,this.resolveIndentStepPx(t)),e.heading&&o!==void 0&&l.push(`font-size: ${o}px`),r&&r!==n&&l.push(`font-family: ${this.escapeAttribute(r)}`);const c=l.length>0?` style="${l.join("; ")}"`:"",d=e.id?` id="${this.escapeHtml(e.id)}"`:"",g=e.styleId?` data-style-id="${this.escapeHtml(e.styleId)}"`:"",u=e.tabStops?` data-tab-stops="${this.escapeHtml(e.tabStops)}"`:"",p=e.direction?` dir="${e.direction}"`:"";return e.heading?`<h${e.heading}${d}${p}${g}${u}${c}>${a}</h${e.heading}>`:`<p${d}${p}${g}${u}${c}>${a}</p>`}static paragraphCarriesNonRuleLayout(e){if(e.spaceBefore!==void 0||e.spaceAfter!==void 0||e.lineSpacing!==void 0||e.keepNext||e.keepLines||e.widowControl===!1)return!0;if(!e.borders)return!1;try{const t=JSON.parse(e.borders)?.bottom;return typeof t?.space=="number"&&t.space>0}catch{return!1}}static textNodeToHtml(e,t,n,i,r,o){return this.textToHtmlWithMarks(e.text,e.marks,t,n,i,r,o)}static coalesceAdjacentTextNodesForHtml(e,t,n,i){if(e.length<=1)return e;const r=[];let o=null;for(const a of e){const l=this.getTextSerializationKey(a.marks,t,n,i),c=r[r.length-1];if(c&&o===l){c.text+=a.text;continue}r.push({...a,marks:a.marks?{...a.marks}:void 0}),o=l}return r}static getTextSerializationKey(e,t,n,i){const r=e?.fontFamily&&e.fontFamily!==t&&e.fontFamily!==i?e.fontFamily:null,o=e?.fontSize!==void 0&&e.fontSize!==n?e.fontSize:null;return JSON.stringify([r,o,e?.bold,e?.italic,e?.underline,e?.strikethrough,e?.doubleStrikethrough,e?.code,e?.latex,e?.superscript,e?.subscript,e?.footnoteRef,e?.footnotePendingBody,e?.footnotePendingKind,e?.color,_e(e?.backgroundColor)??null,e?.smallCaps,e?.allCaps,e?.letterSpacing,e?.hidden,e?.bookmark,e?.fieldInstr,e?.link,e?.comment,vi(e?.docxRunPropertyResets)])}static wrapWithCommentThreads(e,t,n){const i=Array.from(new Set(t.map(r=>r.trim()).filter(Boolean))).sort();for(const r of i.reverse()){const o=(n.comments??[]).find(g=>g.id===r&&!g.parentId),a=o?this.collectCommentThreadRecords(o.id,n):[],l=this.serializeCommentTranscript(a),c=o?.resolved===!0?"true":"false",d=o?.suggestionId?` suggestion-id="${this.escapeAttribute(o.suggestionId)}"`:"";e=`<comment-thread id="${this.escapeAttribute(r)}" resolved="${c}"${d} transcript="${this.escapeAttribute(l)}">${e}</comment-thread>`}return e}static collectCommentThreadRecords(e,t){const n=t.comments??[],i=new Set([e]);let r=!0;for(;r;){r=!1;for(const o of n)o.parentId&&i.has(o.parentId)&&!i.has(o.id)&&(i.add(o.id),r=!0)}return n.filter(o=>i.has(o.id)).sort((o,a)=>(o.createdAt??"").localeCompare(a.createdAt??""))}static serializeCommentTranscript(e){const t=e.length<=20?e:[e[0],...e.slice(-19)],n=(l,c)=>{const d=l.agentName??l.author,g=(l.authorType??"human")==="ai"?" (AI)":"",u=(l.createdAt??"").slice(0,10),p=l.bodyMd.replace(/\s+/g," ").trim(),h=p.length>c?`${p.slice(0,c)}…`:p;return`${d}${g}${u?` on ${u}`:""}: ${h}`},i=(l,c)=>(c?["(older replies omitted)",...l]:l).join(" — "),r=e.length>t.length;let o=i(t.map(l=>n(l,2e3)),r);if(o.length<=4e3)return o;const a=Math.max(80,Math.floor(4e3/Math.max(1,t.length)-60));return o=i(t.map(l=>n(l,a)),!0),o.length<=4e3?o:i(t.slice(-5).map(l=>n(l,300)),!0)}static normalizeAgentHighlightColor(e){return _e(e)}static escapeHtml(e){return Bc.test(e)?e.replace(Mc,$c):e}static escapeAttribute(e){return this.escapeHtml(e)}static resolveFontToCss(e){if(this.isDisallowedFontFamilyValue(e))throw new Error('font-family does not support CSS-wide values like "inherit"; use a concrete font family such as "Arial, sans-serif".');if(e.includes(",")||e.includes("'")||e.includes('"'))return e;const t=ml.find(n=>n.value===e.toLowerCase());return t?t.cssValue:e}static isDisallowedFontFamilyValue(e){const t=e.trim().replace(/\s*!important\s*$/i,"").trim().toLowerCase();return["inherit","initial","unset","revert","revert-layer"].includes(t)}static extractFontSizeFromStyle(e){const t=e.match(/font-size:\s*(\d+(?:\.\d+)?)(px|pt)?/i);if(!t)return;const n=parseFloat(t[1]);if(Number.isFinite(n))return t[2]?.toLowerCase()==="pt"?n*4/3:n}static extractTextStyleMarksFromStyle(e){const t={},n=this.extractFontSizeFromStyle(e);n!==void 0&&n>0&&(t.fontSize=n),this.parseCssFontWeightToBold(e)&&(t.bold=!0),/(?:^|;)\s*font-style:\s*(italic|oblique)/i.test(e)&&(t.italic=!0);const i=e.match(/(?:^|;)\s*color:\s*([^;]+)/i);if(i){const a=Sn(i[1].trim());a&&!ns(a)&&(t.color=a)}const r=e.match(/(?:^|;)\s*letter-spacing:\s*([^;]+)/i);if(r){const a=zs(r[1].trim(),t.fontSize);a!==void 0&&(t.letterSpacing=a)}const o=e.match(/(?:^|;)\s*font-family:\s*([^;]+)/i);if(o){const a=o[1].trim();this.isDisallowedFontFamilyValue(a)||(t.fontFamily=this.resolveFontToCss(a))}return t}static parseCssFontWeightToBold(e){const t=e.match(/(?:^|;)\s*font-weight:\s*([^;]+)/i);if(!t)return;const n=t[1].trim().toLowerCase();if(n==="bold"||n==="bolder")return!0;if(n==="normal"||n==="lighter")return!1;const i=parseInt(n,10);if(Number.isFinite(i))return i>=600}static resolveIndentStepPx(e){return Ve(e?.pageLayout).indentStepPx}static applyParagraphElementAttributes(e,t,n){const i=t.getAttribute("style");if(i){const l=this.extractParagraphStyleAttributes(i,n);l.align&&(e.align=l.align),l.leftIndent!==void 0&&(e.leftIndent=l.leftIndent),l.firstLineIndent!==void 0&&(e.firstLineIndent=l.firstLineIndent),l.keepNext&&(e.keepNext=!0),l.keepLines&&(e.keepLines=!0),l.widowControl===!1&&(e.widowControl=!1);const c=l;c.borders&&(e.borders=c.borders),c.shading&&(e.shading=c.shading),this.applyParagraphSpacingAttributes(e,l)}const r=t.getAttribute("data-style-id");r&&(e.styleId=r);const o=t.getAttribute("data-tab-stops");o&&(e.tabStops=o);const a=t.getAttribute("dir")?.trim().toLowerCase();(a==="rtl"||a==="ltr")&&(e.direction=a)}static applyParagraphSpacingAttributes(e,t){t.spaceBefore!==void 0&&(e.spaceBefore=t.spaceBefore),t.spaceAfter!==void 0&&(e.spaceAfter=t.spaceAfter),t.lineSpacing!==void 0&&(e.lineSpacing=t.lineSpacing)}static cssLengthToPx(e){return ji(e)}static extractParagraphStyleAttributes(e,t=this.resolveIndentStepPx()){const n={};/break-after:\s*avoid/i.test(e)&&(n.keepNext=!0),/break-inside:\s*avoid/i.test(e)&&(n.keepLines=!0),/(?:^|;)\s*(?:widows|orphans):\s*1\b/i.test(e)&&(n.widowControl=!1);{const g=Cc(e);g&&(n.borders=g);const u=e.match(/(?:^|;)\s*background-color:\s*(#[0-9a-fA-F]{3,8}|transparent)/i);u&&(n.shading=u[1])}const i=e.match(/text-align:\s*([^;]+)/i);if(i){const g=i[1].trim().toLowerCase();(g==="left"||g==="center"||g==="right"||g==="justify")&&(n.align=g)}Object.assign(n,Ac(e));const r=_s(e)?.left,o=e.match(/margin-left:\s*([^;]+)/i),a=this.cssLengthToPx(r)?r:void 0,l=Ai(o?.[1]??a,{indentStepPx:t});l!==void 0&&(n.leftIndent=l);const c=e.match(/text-indent:\s*([^;]+)/i),d=Ai(c?.[1],{indentStepPx:t,firstLine:!0});return d!==void 0&&(n.firstLineIndent=d),n}static appendParagraphIndentStyles(e,t,n){const i=t.leftIndent===0?0:Re(t.leftIndent);i!==void 0&&e.push(`margin-left: ${is(i,n)}px`);const r=t.firstLineIndent===0?0:De(t.firstLineIndent);if(r!==void 0&&e.push(`text-indent: ${Math.sign(r)*is(Math.abs(r),n)}px`),typeof t.spaceBefore=="number"&&e.push(`margin-top: ${t.spaceBefore}px`),typeof t.spaceAfter=="number"&&e.push(`margin-bottom: ${t.spaceAfter}px`),typeof t.lineSpacing=="number"&&e.push(`line-height: ${t.lineSpacing}`),t.keepNext&&e.push("break-after: avoid"),t.keepLines&&e.push("break-inside: avoid"),t.widowControl===!1&&e.push("orphans: 1"),t.shading&&e.push(`background-color: ${t.shading}`),t.borders)try{const o=JSON.parse(t.borders);for(const a of["top","bottom","left","right"]){const l=o[a];if(!l)continue;const c=l.style==="none"?"none":l.style==="double"||l.style==="dashed"||l.style==="dotted"?l.style:"solid";e.push(`border-${a}: ${l.style==="none"?0:l.width??1}px ${c} ${l.color??"#000000"}`),typeof l.space=="number"&&l.space>0&&e.push(`padding-${a}: ${l.space}px`)}}catch{}}static extractUniformTextFontFamily(e){let t,n=!1;for(const i of e){if(i.type!=="text"||i.text.length===0)continue;const r=i.marks?.fontFamily;if(r===void 0)return;if(t===void 0)t=r;else if(t!==r)return;n=!0}return n?t:void 0}static extractUniformTextFontSize(e){let t,n=!1;for(const i of e){if(i.type!=="text"||i.text.length===0)continue;const r=i.marks?.fontSize;if(r===void 0)return;if(t===void 0)t=r;else if(t!==r)return;n=!0}return n?t:void 0}static findOmittableDocumentFontFamily(e){if(!e)return;const t=new Set,n=r=>{for(const o of r)if(!(o.type!=="text"||o.text.length===0)&&(t.add(o.marks?.fontFamily??this.DEFAULT_FONT_FAMILY),t.size>1))return},i=r=>{if(!(t.size>1))switch(r.type){case"paragraph":n(r.children);break;case"list":for(const o of r.children)if(n(o.children),t.size>1)return;break;case"container":for(const o of r.children)if(i(o),t.size>1)return;break;case"table":for(const o of r.children)for(const a of o.children)for(const l of a.children)if(i(l),t.size>1)return;break;case"table-cell":for(const o of r.children)if(i(o),t.size>1)return;break}};for(const r of e.children)if(i(r),t.size>1)return;return t.size===1?Array.from(t)[0]:void 0}static resolveOmittableDocumentFontFamily(e,t={}){if(t.scanDocumentFontFamily!==!1)return this.findOmittableDocumentFontFamily(e)}static findTopLevelIndexesByBlockId(e,t){const n=new Map,i=new Set(t);if(i.size===0)return n;const r=[...e.children,...e.notes??[]];for(let o=0;o<r.length;o++){const a=this.getBlockId(r[o]);if(a&&i.has(a)&&(n.set(a,o),i.delete(a),i.size===0))return n}for(let o=0;o<r.length&&(this.collectRequestedBlockIndexesForTopLevel(r[o],i,n,{topLevelIndex:o,includeRootBlock:!1}),i.size!==0);o++);return n}static collectRequestedBlockIndexesForTopLevel(e,t,n,i){if(t.size!==0&&!(i.includeRootBlock&&e.id&&t.has(e.id)&&(n.set(e.id,i.topLevelIndex),t.delete(e.id),t.size===0)))switch(e.type){case"list":for(const r of e.children)if(r.id&&t.has(r.id)&&(n.set(r.id,i.topLevelIndex),t.delete(r.id),t.size===0))return;break;case"container":case"table-cell":case"footnote":for(const r of e.children)if(this.collectRequestedBlockIndexesForTopLevel(r,t,n,{topLevelIndex:i.topLevelIndex,includeRootBlock:!0}),t.size===0)return;break;case"table":for(const r of e.children){if(r.id&&t.has(r.id)&&(n.set(r.id,i.topLevelIndex),t.delete(r.id),t.size===0))return;for(const o of r.children){if(o.id&&t.has(o.id)&&(n.set(o.id,i.topLevelIndex),t.delete(o.id),t.size===0))return;for(const a of o.children)if(this.collectRequestedBlockIndexesForTopLevel(a,t,n,{topLevelIndex:i.topLevelIndex,includeRootBlock:!0}),t.size===0)return}}break}}static imageBlockToHtml(e,t=!1){const n=e.alt?` alt="${this.escapeAttribute(e.alt)}"`:"",i=e.align?` align="${e.align}" data-align="${e.align}"`:"",r=this.getImageStyle(e),o=r?` style="${r}"`:"",a=Math.max(1,Math.round(e.width)),l=Math.max(1,Math.round(e.height)),c=e.sourceUrl?` data-source-url="${this.escapeAttribute(e.sourceUrl)}"`:"",d=t?` src="${this.escapeAttribute(e.src)}"`:' data-image-source="hidden"';return`<img id="${this.escapeAttribute(e.id)}"${d}${c} width="${a}" height="${l}"${n}${i}${o}>`}static listToHtml(e,t,n,i={},r){const o=e.variant==="ordered"?"ol":"ul",a=new Map;let l=0;for(const k of e.children){const I=k.children.reduce((x,A)=>x+A.text.length,0),v=(r??[]).flatMap(x=>{const A=Math.max(0,(x.startOffset??0)-l),C=Math.min(I,(x.endOffset??1/0)-l);return A<C?[{startOffset:A,endOffset:C}]:[]});v.length&&a.set(k,v),l+=I+1}const c=(k,I)=>{const v=[];let x=0;for(;x<k.length;){const A=k[x],C=A.indentLevel||0;if(C<I)break;if(C>=I){const F=this.extractUniformTextFontFamily(A.children),E=[...A.lineSpacing!==void 0?[`line-height: ${A.lineSpacing}`]:[],...A.spaceBefore!==void 0?[`margin-top: ${A.spaceBefore}px`]:[],...A.spaceAfter!==void 0?[`margin-bottom: ${A.spaceAfter}px`]:[]];F&&F!==t&&E.push(`font-family: ${this.escapeHtml(F)}`);const P=E.length>0?` style="${E.join("; ")}"`:"",B=A.id?` id="${this.escapeAttribute(A.id)}"`:"",w=A.direction?` dir="${A.direction}"`:"",T=C!==0||i.includeZeroListLevels?` data-indent-level="${C}"`:"",N=`${B}${P}${w}${T}`,L=a.get(A),_=L?this.textNodesToHtmlWithSelections(A.children,n,L,t):this.coalesceAdjacentTextNodesForHtml(A.children,F,void 0,t).map(O=>O.type==="text"?this.textNodeToHtml(O,void 0,n,void 0,F,t):"").join(""),$=[];let R=x+1;for(;R<k.length&&(k[R].indentLevel||0)>C;)$.push(k[R]),R++;let M=_;if($.length>0){const O=e.variant==="ordered"?"ol":"ul",D=`<${O}>${c($,C+1)}</${O}>`;M=_+D}if(e.variant==="todo"&&(M=`<input type="checkbox"${A.checked?" checked":""}>${M}`),n&&A.id){const O=(n.comments??[]).filter(D=>!D.parentId&&D.anchorBlockId===A.id).map(D=>D.id);M=this.wrapWithCommentThreads(M,O,n)}v.push(`<li${N}>${M}</li>`),x=R}else x++}return v.join("")},d=c(e.children,0),g=e.id?` id="${this.escapeAttribute(e.id)}"`:"",u=e.variant==="ordered"?rc((n?Ss(n).get(e.id):void 0)??sc(e)):1,p=e.variant==="ordered"&&u!==1?` start="${u}"`:"",h=[...e.lineSpacing!==void 0?[`line-height: ${e.lineSpacing}`]:[],...e.spaceBefore!==void 0?[`margin-top: ${e.spaceBefore}px`]:[],...e.spaceAfter!==void 0?[`margin-bottom: ${e.spaceAfter}px`]:[]],f=h.length?` style="${h.join("; ")}"`:"",m=e.contextualSpacing!==void 0?` data-contextual-spacing="${e.contextualSpacing}"`:"",y=e.numberingChainId?` data-numbering-chain-id="${this.escapeAttribute(e.numberingChainId)}" data-start-number="${e.startNumber??""}" data-effective-start="${u}"`:"",b=e.numberingFormat?` data-numbering-format="${this.escapeAttribute(e.numberingFormat)}"`:"";return`<${o}${g}${p}${f}${m}${y}${b}>${d}</${o}>`}static containerToHtml(e,t,n,i={}){const r=e.id?` id="${this.escapeAttribute(e.id)}"`:"",o=[];e.borderColor&&o.push(`border-color: ${this.escapeHtml(e.borderColor)}`),e.padding!==void 0&&o.push(`padding: ${e.padding}px`);const a=o.length>0?` style="${o.join("; ")}"`:"",l=e.children.map(c=>this.blockToHtml(c,t,n,i)).filter(c=>c.length>0).join(`
12
- `);return`<div class="container"${r}${a}>
13
- ${l}
14
- </div>`}static tableToHtml(e,t,n,i={}){const r=e.id?` id="${this.escapeAttribute(e.id)}"`:"",o=["border-collapse: collapse"];e.tableWidth!==void 0?o.push(`width: ${e.tableWidth}px`):o.push("width: 100%"),e.align&&e.align!=="left"&&(e.align==="center"?o.push("margin-left: auto","margin-right: auto"):e.align==="right"&&o.push("margin-left: auto","margin-right: 0")),e.borderColor&&o.push(`border-color: ${this.escapeHtml(e.borderColor)}`);const a=ws(e.borders);let l="";if(a){for(const u of["top","right","bottom","left"]){const p=a[u];p&&o.push(`border-${u}: ${Ts(p)}`)}l=` data-borders="${this.escapeAttribute(e.borders)}"`}const c=` style="${o.join("; ")}"`,d=Ze(e),g=e.children.map((u,p)=>this.tableRowToHtml(e,u,p,d,t,n,i)).join(`
15
- `);return`<table${r}${l}${c}>
16
- ${g}
17
- </table>`}static tableRowToHtml(e,t,n,i,r,o,a={}){const l=[];if(r){const h=f=>{const m=f;if(m.type==="list"){m.variant==="ordered"&&l.push([m.id,Ss(r).get(m.id??"")]);return}for(const y of m.children??[])h(y)};h(t)}const c=JSON.stringify([t,l,e.columnWidths,e.hasHeader&&n===0,o,r?.stylesheet,r?.comments,r?.pageLayout,a,t.children.map(h=>{const f=i.byId.get(h.id);return f?[f.col,f.rowSpan,f.colSpan]:null})]),d=this.tableRowHtmlCache.get(t);if(d?.key===c)return d.html;const g=e.hasHeader&&n===0?"th":"td",u=t.children.map((h,f)=>{const m=h.id?` id="${this.escapeAttribute(h.id)}"`:"",y=i.byId.get(h.id);let b="";y&&y.colSpan>1&&(b+=` colspan="${y.colSpan}"`),y&&y.rowSpan>1&&(b+=` rowspan="${y.rowSpan}"`);const k=y?` data-grid-column="${y.col}"`:' data-grid-unplaced="true"';let I;if(y){let P=0;for(let B=y.col;B<y.col+y.colSpan;B++)P+=e.columnWidths[B]||0;I=P>0?P:void 0}else I=e.columnWidths[f];const v=[];let x="";const A=Oi(h.borders);if(A){for(const P of["top","right","bottom","left"]){const B=A[P];B&&v.push(`border-${P}: ${Ts(B)}`)}x+=` data-borders="${this.escapeAttribute(h.borders)}"`}else v.push("border: 1px solid #ccc");const C=cc(h.padding);C?v.push(`padding: ${dc(C)}`):v.push("padding: 8px"),I!==void 0&&v.push(`width: ${I}%`),h.verticalAlign&&v.push(`vertical-align: ${h.verticalAlign}`),h.backgroundColor&&v.push(`background-color: ${this.escapeHtml(h.backgroundColor)}`);const F=` style="${v.join("; ")}"`,E=h.children.map(P=>this.blockToHtml(P,r,o,a)).filter(P=>P.length>0).join("");return`<${g}${m}${b}${x}${F}${k}>${E}</${g}>`}).join(""),p=`<tr${t.id?` id="${this.escapeAttribute(t.id)}"`:""}>${u}</tr>`;return this.tableRowHtmlCache.set(t,{key:c,html:p}),p}static tableCellToHtml(e,t,n,i={}){const r=e.id?` id="${this.escapeAttribute(e.id)}"`:"",o=["border: 1px solid #ccc","padding: 8px"];e.verticalAlign&&o.push(`vertical-align: ${e.verticalAlign}`),e.backgroundColor&&o.push(`background-color: ${this.escapeHtml(e.backgroundColor)}`);const a=` style="${o.join("; ")}"`,l=e.children.map(c=>this.blockToHtml(c,t,n,i)).filter(c=>c.length>0).join(`
18
- `);return`<div class="table-cell"${r}${a}>
19
- ${l}
20
- </div>`}static parsePositiveImageDimension(e,t){const n=e.getAttribute(t);if(!n)return;const i=Number.parseInt(n,10);return Number.isFinite(i)&&i>0?i:void 0}static parseImageSourceUrl(e){const t=e.getAttribute("data-source-url")?.trim();if(t)try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"?n.href:void 0}catch{return}}static parseSingleImageParagraph(e,t){if(e.textContent?.trim())return null;let n=e,i=null;for(;;){const d=Array.from(n.children);if(d.length!==1)return null;const g=d[0],u=g.tagName.toLowerCase();if(u==="img"){i=g;break}if(u!=="span")return null;n=g}const r=this.parsePositiveImageDimension(i,"data-revise-natural-width"),o=this.parsePositiveImageDimension(i,"data-revise-natural-height"),a=this.parseImageElement(i,t);if(!a)return null;if(!a.align){const d=e.getAttribute("style");if(d){const g=d.match(/text-align:\s*([^;]+)/);if(g){const u=g[1].trim();(u==="left"||u==="center"||u==="right")&&(a.align=u)}}}const l=d=>{const g=d.trim().match(/^(\d+(?:\.\d+)?)px$/i);if(!g)return;const u=Number(g[1]);return Number.isFinite(u)&&u>0?Math.round(u):void 0};let c=i.parentElement;for(;c&&c!==e;){const d=c.getAttribute("style")??"",g=d.match(/(?:^|;)\s*width\s*:\s*([^;]+)/i),u=d.match(/(?:^|;)\s*height\s*:\s*([^;]+)/i),p=g?l(g[1]):void 0,h=u?l(u[1]):void 0,f=i.getAttribute("style")??"";if(p!==void 0&&h!==void 0&&/(?:^|;)\s*transform\s*:/i.test(f))a.width=p,a.height=h;else if(p!==void 0){const m=r??a.width,y=o??a.height;a.width=p,a.height=Math.max(1,Math.round(p*y/m))}else if(h!==void 0){const m=r??a.width,y=o??a.height;a.height=h,a.width=Math.max(1,Math.round(h*m/y))}if(p!==void 0||h!==void 0)break;c=c.parentElement}return a}static parseImageElement(e,t){const n=t?.imageReferences?.get(e);if(n){t?.remainingImageReferences?.delete(e);const f={...n,id:t?.imageIdsToPreserve?.has(n.id)?pe(n.id,t):pe(null,t)};f.width=this.parsePositiveImageDimension(e,"width")??f.width,f.height=this.parsePositiveImageDimension(e,"height")??f.height,e.hasAttribute("alt")&&(f.alt=e.getAttribute("alt")||void 0);const m=this.parseImageAlign(e);return m&&(f.align=m),f}const i=e.getAttribute("src");if(!i)return null;t?.remainingImageReferences?.delete(e);const r=this.parsePositiveImageDimension(e,"width"),o=this.parsePositiveImageDimension(e,"height"),a=this.parsePositiveImageDimension(e,"data-revise-natural-width"),l=this.parsePositiveImageDimension(e,"data-revise-natural-height"),c=e.getAttribute("alt")||void 0,d=this.parseImageAlign(e),g=this.parseImageSourceUrl(e);let u=r??a??200,p=o??l??200;a&&l&&(r?p=Math.max(1,Math.round(r*l/a)):o&&(u=Math.max(1,Math.round(o*a/l))));const h={type:"image",id:Y(),src:i,width:u,height:p};return c&&(h.alt=c),d&&(h.align=d),g&&(h.sourceUrl=g),h}static parseListElement(e,t,n=0){const i=e.tagName.toLowerCase();if(i!=="ul"&&i!=="ol")return null;let r=i==="ol"?"ordered":"unordered";const o=(h,f,m={},y=Math.min(n+2,8))=>{const b=[],k=h.getAttribute("style"),I=k?{...m,...this.extractTextStyleMarksFromStyle(k)}:m;for(const v of Array.from(h.children))if(v.tagName.toLowerCase()==="li"){const x=document.createElement("div");let A=!1;const C=[];for(const R of Array.from(v.childNodes))if(R.nodeType===Node.ELEMENT_NODE){const M=R,O=M.tagName.toLowerCase();O==="ul"||O==="ol"?(A=!0,C.push(M)):x.appendChild(R.cloneNode(!0))}else x.appendChild(R.cloneNode(!0));const F=v.getAttribute("style"),E=F?{...I,...this.extractTextStyleMarksFromStyle(F)}:I,P=x.querySelector('input[type="checkbox"]');P&&(r="todo",P.remove());const B=this.parseHtmlElement(x,E),w={type:"list-item",id:pe(v.getAttribute("id"),t),children:B.length>0?B:[{type:"text",text:"",marks:{}}]};P&&(w.checked=P.hasAttribute("checked"));const T=v.getAttribute("dir")??F?.match(/(?:^|;)\s*direction:\s*(rtl|ltr)\s*(?:;|$)/i)?.[1];if((T==="rtl"||T==="ltr")&&(w.direction=T),F){const R=this.extractParagraphStyleAttributes(F);for(const M of["lineSpacing","spaceBefore","spaceAfter"])R[M]!==void 0&&(w[M]=R[M])}const N=v.getAttribute("data-indent-level"),L=N!==null?Number(N):NaN,_=Number.isInteger(L)&&L>=0&&L<=8,$=_?L:f;if($>0&&(w.indentLevel=$),b.push(w),A)for(const R of C){const M=_?Math.max(y,Math.min($+2,8)):y,O=o(R,Math.min($+1,M),E,M);b.push(...O)}}return b},a=o(e,n);if(a.length===0)return null;const l={type:"list",id:pe(e.getAttribute("id"),t),variant:r,children:a};if(r==="ordered"){const h=e.getAttribute("start");if(h){const f=parseInt(h,10);!isNaN(f)&&f!==1&&(l.startNumber=f)}}const c=e.getAttribute("style");if(c){const h=this.extractParagraphStyleAttributes(c);for(const m of["spaceBefore","spaceAfter"])h[m]!==void 0&&(l[m]=h[m]);const f=c.match(/(?:^|;)\s*line-height:\s*([\d.]+)\s*(?:;|$)/i);if(f){const m=parseFloat(f[1]);Number.isFinite(m)&&m>=.5&&m<=4&&(l.lineSpacing=m)}}const d=e.getAttribute("data-contextual-spacing");(d==="true"||d==="false")&&(l.contextualSpacing=d==="true");const g=e.getAttribute("data-numbering-chain-id");if(g&&r==="ordered"){l.numberingChainId=g;const h=e.getAttribute("data-start-number"),f=Number(e.getAttribute("data-effective-start")),m=Number(e.getAttribute("start")??1);e.hasAttribute("start")&&Number.isInteger(f)&&f>0&&Number.isInteger(m)&&m>0&&m!==f?l.startNumber=m:h===""?delete l.startNumber:h!==null&&Number.isInteger(Number(h))&&Number(h)>0&&(l.startNumber=Number(h))}const u=e.getAttribute("data-numbering-format");u&&oc(u)&&(l.numberingFormat=u);const p=e.getAttribute("style");if(p){const h=p.match(/font-family:\s*([^;]+)/);if(h){const f=this.resolveFontToCss(h[1].trim());for(const m of l.children)for(const y of m.children)y.type==="text"&&(y.marks||(y.marks={}),y.marks.fontFamily||(y.marks.fontFamily=f))}}return l}static parseContainerElement(e,t,n){const i=pe(e.getAttribute("id"),n),r=e.getAttribute("style");let o,a;if(r){const g=r.match(/border-color:\s*([^;]+)/);g&&(o=g[1].trim());const u=r.match(/padding:\s*(\d+)px/);u&&(a=parseInt(u[1],10))}const l=this.resolveIndentStepPx(t?.existingDocument),c=[];for(const g of Array.from(e.children)){const u=g.tagName.toLowerCase();if(u==="p"||u.match(/^h[1-6]$/)){const p=u.match(/^h([1-6])$/),h=g.getAttribute("style"),f=this.parseHtmlElement(g,h?this.extractTextStyleMarksFromStyle(h):{}),m={type:"paragraph",id:pe(g.getAttribute("id"),n),children:f.length>0?f:[{type:"text",text:"",marks:{}}]};p&&(m.heading=parseInt(p[1])),this.applyParagraphElementAttributes(m,g,l),c.push(m)}else if(u==="ul"||u==="ol"){const p=this.parseListElement(g,n);p&&c.push(p)}else if(u==="hr")c.push(this.parseHrElement(g,n));else if(u==="img"){const p=this.parseImageElement(g,n);p&&c.push(p)}else if(u==="div"&&g.classList.contains("container")){const p=this.parseContainerElement(g,t,n);p&&c.push(p)}}if(c.length===0)return null;const d={type:"container",id:i,children:c};return o&&(d.borderColor=o),a!==void 0&&(d.padding=a),d}static parseTableElement(e,t,n){const i=pe(e.getAttribute("id"),n),r=this.resolveIndentStepPx(t?.existingDocument),o=e.getAttribute("style");let a,l,c;if(o){const x=o.match(/width:\s*(\d+)px/);x&&(a=parseInt(x[1],10));const A=o.match(/border-color:\s*([^;]+)/);A&&(l=A[1].trim()),/margin-left:\s*auto/.test(o)&&/margin-right:\s*auto/.test(o)?c="center":/margin-left:\s*auto/.test(o)&&/margin-right:\s*0/.test(o)&&(c="right")}const d=[],g=new Map;let u=!1;const p=Array.from(e.rows);for(let x=0;x<p.length;x++){const A=p[x],C=[],F=A.querySelectorAll(":scope > td, :scope > th");x===0&&F.length>0&&F[0].tagName.toLowerCase()==="th"&&(u=!0);for(let P=0;P<F.length;P++){const B=F[P],w=B.getAttribute("style");let T,N;if(w){const j=w.match(/vertical-align:\s*([^;]+)/);if(j){const q=j[1].trim();(q==="top"||q==="middle"||q==="bottom")&&(T=q)}const U=w.match(/background-color:\s*([^;]+)/);U&&(N=U[1].trim())}const L=[],_=B.children;if(_.length===0){const j=B.textContent||"";L.push({type:"paragraph",id:pe(null,n),children:[{type:"text",text:j,marks:{}}]})}else for(const j of Array.from(_)){const U=j.tagName.toLowerCase(),q=U==="img"?this.parseImageElement(j,n):U==="p"?this.parseSingleImageParagraph(j,n):null;if(q){L.push(q);continue}if(U==="p"||U.match(/^h[1-6]$/)){const oe=U.match(/^h([1-6])$/),be=j.getAttribute("style"),Xe=this.parseHtmlElement(j,be?this.extractTextStyleMarksFromStyle(be):{}),Oe={type:"paragraph",id:pe(j.getAttribute("id"),n),children:Xe.length>0?Xe:[{type:"text",text:"",marks:{}}]};oe&&(Oe.heading=parseInt(oe[1])),this.applyParagraphElementAttributes(Oe,j,r),L.push(Oe)}else if(U==="ul"||U==="ol"){const oe=this.parseListElement(j,n);oe&&L.push(oe)}else if(U==="hr")L.push(this.parseHrElement(j,n));else if(U==="table"){const oe=this.parseTableElement(j,t,n);oe&&L.push(oe)}else{const oe=j.textContent||"";oe.trim()&&L.push({type:"paragraph",id:pe(null,n),children:[{type:"text",text:oe,marks:{}}]})}}L.length===0&&L.push({type:"paragraph",id:pe(null,n),children:[{type:"text",text:"",marks:{}}]});const $={type:"table-cell",id:pe(B.getAttribute("id"),n),children:L},R=w?.match(/width:\s*([\d.]+)%/);if(R){const j=parseFloat(R[1]);Number.isFinite(j)&&j>0&&g.set($,j)}T&&($.verticalAlign=T),N&&($.backgroundColor=N);const M=Oi(B.getAttribute("data-borders")),O=M?Pn(M):Cs(Ps(w));if(O&&($.borders=O),w){const j=w.match(/(?:^|;)\s*padding\s*:\s*([^;]+)/i),U=gc(j?.[1]);U&&!(U.top===8&&U.right===8&&U.bottom===8&&U.left===8)&&($.padding=uc(U))}const D=this.parseSpanAttribute(B.getAttribute("colspan")),X=this.parseSpanAttribute(B.getAttribute("rowspan"));D>1&&($.colSpan=D),X>1&&($.rowSpan=X),C.push($)}const E=pe(A.getAttribute("id"),n);d.push({type:"table-row",id:E,children:C})}if(!d.some(x=>x.children.length>0))return null;const h=Ze({children:d,columnWidths:[]}),f=h.cols||1,m=new Array(f).fill(0),y=new Array(f).fill(!1);for(const x of h.cells){if(x.colSpan!==1||y[x.col])continue;const A=g.get(x.cell);A!==void 0&&(m[x.col]=A,y[x.col]=!0)}const b=y.filter(x=>!x).length;if(b>0){const x=m.reduce((C,F)=>C+F,0),A=Math.max(1,(100-x)/b);for(let C=0;C<f;C++)y[C]||(m[C]=A)}const k={type:"table",id:i,columnWidths:m,children:d};a!==void 0&&(k.tableWidth=a),c&&(k.align=c),l&&(k.borderColor=l),u&&(k.hasHeader=u);const I=ws(e.getAttribute("data-borders")),v=I?Pn(I):Cs(Ps(o));return v&&(k.borders=v),k}static parseSpanAttribute(e){const t=parseInt(e||"1",10);return Number.isFinite(t)?Math.min(Math.max(1,t),1e3):1}static parseCodeBlockElement(e,t){const n=pe(e.getAttribute("id"),t);let i;const r=e.getAttribute("language"),o=e.getAttribute("data-language");if(r)i=r;else if(o)i=o;else{const c=e.className.split(" ");for(const d of c)if(d.startsWith("language-")){i=d.substring(9);break}}let a="";const l=e.querySelector("code");return l?a=l.textContent||"":a=e.textContent||"",{type:"code",id:n,content:a,language:i}}static parseMathElement(e,t){const n=pe(e.getAttribute("id"),t);let i="block";e.getAttribute("display")==="inline"&&(i="inline");const r=e.textContent||"",o=ee(e,"align"),a={type:"math",id:n,content:r,displayMode:i};return(o==="left"||o==="center"||o==="right")&&(a.align=o),a}static parseHrElement(e,t){let n;const i=e.getAttribute("style");if(i){const o=i.match(/border(?:-bottom)?:\s*([\d.]+)px\s+(solid|double|dashed|dotted)\s+(#[0-9a-fA-F]{3,8}|[a-zA-Z]+)/i);if(o){const a=o[2].toLowerCase();n={width:parseFloat(o[1]),style:a==="solid"?"single":a,color:o[3]}}}const r=e.getAttribute("data-rule");return Is(r??void 0)&&(n={...n,style:r}),{type:"paragraph",id:pe(e.getAttribute("id"),t),children:[{type:"text",text:"",marks:{}}],borders:bl(n)}}static parsePageBreakElement(e,t){return{type:"page-break",id:pe(e.getAttribute("id"),t)}}static parseDocxRawElement(e,t){const n=e.getAttribute("origin");return{type:"docx-raw",id:pe(e.getAttribute("id"),t),xml:"",tagName:e.getAttribute("tag")||"unknown",...e.getAttribute("detail")?{detail:e.getAttribute("detail")}:{},origin:n==="body"?"body":"run"}}static parseTocElement(e,t){const n={type:"toc",...yl(e),id:pe(e.getAttribute("id"),t)},i=e.getAttribute("levels");if(i){const r=parseInt(i,10);Number.isFinite(r)&&r>=1&&r<=6&&(n.levels=r)}return Object.assign(n,kl(e.getAttribute("style"))),n}static parseSectionBreakElement(e,t){const n={type:"section-break",id:pe(e.getAttribute("id"),t)},i=e.getAttribute("break-type");(i==="nextPage"||i==="continuous"||i==="evenPage"||i==="oddPage")&&(n.breakType=i);const r=e.getAttribute("layout");if(r)try{const o=JSON.parse(r);o&&typeof o=="object"&&!Array.isArray(o)&&(n.layout=o)}catch{}return n}static parseCenterElement(e,t,n){const i=[],r=Array.from(e.children);for(const a of r){const l=a.tagName.toLowerCase();if(l==="p"||l.match(/^h[1-6]$/)){const c=l.match(/^h([1-6])$/),d=this.parseHtmlElement(a),g={type:"paragraph",id:pe(a.getAttribute("id"),n),children:d.length>0?d:[{type:"text",text:"",marks:{}}],align:"center"};c&&(g.heading=parseInt(c[1])),i.push(g);continue}if(l==="img"){const c=this.parseImageElement(a,n);c&&(c.align=c.align??"center",i.push(c));continue}if(l==="table"){const c=this.parseTableElement(a,t,n);c&&(c.align=c.align??"center",i.push(c));continue}if(l==="pre"){const c=this.parseCodeBlockElement(a,n);c&&i.push(c);continue}if(l==="latex"){i.push(this.parseMathElement(a,n));continue}if(l==="page-break"){i.push(this.parsePageBreakElement(a,n));continue}if(l==="docx-raw"){i.push(this.parseDocxRawElement(a,n));continue}if(l==="section-break"){i.push(this.parseSectionBreakElement(a,n));continue}if(l==="toc"){i.push(this.parseTocElement(a,n));continue}if(l==="hr"){i.push(this.parseHrElement(a,n));continue}if(l==="ul"||l==="ol"){const c=this.parseListElement(a,n);c&&i.push(c);continue}}if(i.length>0)return i;const o=this.parseHtmlElement(e);return[{type:"paragraph",id:pe(e.getAttribute("id"),n),align:"center",children:o.length>0?o:[{type:"text",text:"",marks:{}}]}]}static parseImageAlign(e){const t=ee(e,"align");if(t==="left"||t==="center"||t==="right")return t;const n=e.getAttribute("data-align");if(n==="left"||n==="center"||n==="right")return n;const i=e.getAttribute("style")||"";if(i.includes("margin-left: auto")&&i.includes("margin-right: auto"))return"center";if(i.includes("margin-left: auto"))return"right";if(i.includes("margin-right: auto"))return"left"}static getImageStyle(e){const t=["display: block","max-width: 100%","height: auto"];switch(e.align){case"center":t.push("margin-left: auto","margin-right: auto");break;case"right":t.push("margin-left: auto");break;case"left":t.push("margin-right: auto");break}return t.join("; ")}static escapePreContent(e){return e.replace(/<pre(\s[^>]*)?>(([\s\S](?!<\/pre>))*[\s\S]?)<\/pre>/gi,(t,n,i)=>{if(!i)return t;const r=i.match(/^(\s*)<code(\s[^>]*)?>(([\s\S](?!<\/code>))*[\s\S]?)<\/code>(\s*)$/i);if(r){const[,a,l,c,,d]=r,g=this.escapeCodeContent(c||"");return`<pre${n||""}>${a||""}<code${l||""}>${g}</code>${d||""}</pre>`}const o=this.escapeCodeContent(i);return`<pre${n||""}>${o}</pre>`})}static escapeCodeContent(e){return e.replace(/&(?!(lt|gt|amp|quot|apos|nbsp|#\d+|#x[0-9a-fA-F]+);)/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}static coalesceAdjacentBareListFragments(e){if(e.length<2)return e;const t=[];let n=!1;for(const i of e){const r=Xi(i),o=Array.from(r.body.childNodes),a=o.filter(d=>d.nodeType===Node.ELEMENT_NODE||d.nodeType===Node.TEXT_NODE&&d.textContent?.trim()),l=d=>d?.nodeType===Node.ELEMENT_NODE&&d.tagName.toLowerCase()==="li",c=a.length===0&&o.some(d=>d.nodeType===Node.COMMENT_NODE);n&&(l(a[0])||c)?t[t.length-1]+=i:t.push(i),c||(n=l(a.at(-1)))}return t}static fromAgentHtml(e,t){e=this.escapePreContent(e);const n=t?.parsingContext??(t?.existingDocument?this.createParsingContext(t.existingDocument):void 0),i=n?.validIds,r=t?.preserveImageReferenceIds?i??new Set:t?.replacementBlock?Hs({children:[t.replacementBlock]}):new Set,o={validIds:i,usedIds:new Set,imageIdsToPreserve:r,imageReferences:new Map,remainingImageReferences:new Set};t={...t,parsingContext:n};let a=Xi(e),l;const c=Array.from(a.body.children).some(f=>f.tagName.toLowerCase()==="li");for(const f of Array.from(a.body.childNodes))if(f.nodeType!==Node.COMMENT_NODE){if(f.nodeType===Node.TEXT_NODE){if(c&&f.textContent?.trim()){l=void 0;const m=a.createElement("p");a.body.insertBefore(m,f),m.appendChild(f)}continue}if(f.nodeType!==Node.ELEMENT_NODE||f.tagName.toLowerCase()!=="li"){l=void 0;continue}l||(l=a.createElement("ul"),a.body.insertBefore(l,f)),l.appendChild(f)}Array.from(a.body.children).some(f=>Pc.has(f.tagName.toLowerCase()))||(a=Xi(`<p>${e}</p>`));const d=new Set,g=Array.from(a.body.querySelectorAll("img"));for(const f of g){o.remainingImageReferences.add(f);const m=f.getAttribute("id")??"",y=m?n?.imagesById?.get(m):void 0,b=f.getAttribute("data-image-id"),k=f.getAttribute("src")??"",I=k.startsWith("#")?k.slice(1):void 0;if(b!==null||I!==void 0){const x=b??I,A=n?.imagesById?.get(x);if(!A?.src||I!==void 0&&I!==x||y&&y.id!==x||k&&I===void 0&&k!==x&&k!==A.src)throw new fe("invalid_image_reference",`Image reference "${x}" is missing or contradicts the supplied source. Copy an existing image with <img src="IMAGE_ID"> using the exact id from the document.`);o.imageReferences.set(f,A);continue}const v=n?.imagesById?.get(f.getAttribute("src")??"");if(v){o.imageReferences.set(f,v);continue}if(k&&k!==y?.src&&!/^(?:https?:\/\/|data:image\/|blob:)/i.test(k))throw new fe("invalid_image_reference",`Image source "${k}" is not a known image id or an absolute image URL. Copy an existing image with <img src="IMAGE_ID"> using its exact document id, or provide an absolute image URL.`);if(!f.getAttribute("src")){const x=!m&&t?.replacementBlock?.type==="image"&&g.length===1?n?.imagesById?.get(t.replacementBlock.id):void 0,A=y??x;if(!A?.src)throw new fe("invalid_image_reference",`${f.getAttribute("data-image-source")==="hidden"?"Cannot resolve hidden image":"Image"} ${m?'"'+m+'"':"without an id"} has no valid source. Supply src, copy a verified existing image with <img src="IMAGE_ID"> using its exact document id, or resize an explicitly targeted image block.`);if(d.has(A.id))throw new fe("invalid_image_reference",`Image "${A.id}" is referenced more than once. Each existing image may appear only once in replacement HTML.`);d.add(A.id),o.imageReferences.set(f,A);continue}y?.src===f.getAttribute("src")&&o.imageReferences.set(f,y)}const u=Array.from(a.body.children),p=t?.parsingContext?.indentStepPx??this.resolveIndentStepPx(t?.existingDocument),h=[];u.length===0&&a.body.textContent&&h.push({type:"paragraph",id:pe(null,o),children:[{type:"text",text:a.body.textContent||"",marks:{}}]});for(const f of u){const m=f.tagName.toLowerCase();if(m==="img"){const A=this.parseImageElement(f,o);A&&h.push(A);continue}if(m==="ul"||m==="ol"){const A=this.parseListElement(f,o,t?.listItemBaseIndent);A&&h.push(A);continue}if(m==="div"&&f.classList.contains("container")){const A=this.parseContainerElement(f,t,o);A&&h.push(A);continue}if(m==="table"){const A=this.parseTableElement(f,t,o);A&&h.push(A);continue}if(m==="pre"){const A=this.parseCodeBlockElement(f,o);A&&h.push(A);continue}if(m==="p"){const A=this.parseSingleImageParagraph(f,o);if(A){h.push(A);continue}}if(m==="latex"){const A=this.parseMathElement(f,o);h.push(A);continue}if(m==="page-break"){h.push(this.parsePageBreakElement(f,o));continue}if(m==="docx-raw"){h.push(this.parseDocxRawElement(f,o));continue}if(m==="section-break"){h.push(this.parseSectionBreakElement(f,o));continue}if(m==="toc"){h.push(this.parseTocElement(f,o));continue}if(m==="center"){h.push(...this.parseCenterElement(f,t,o));continue}if(m==="hr"){h.push(this.parseHrElement(f,o));continue}const y=m.match(/^h([1-6])$/),b=f.getAttribute("style");let k,I;if(b){const A=b.match(/font-family:\s*([^;]+)/);A&&(k=this.resolveFontToCss(A[1].trim())),I=this.extractFontSizeFromStyle(b)}const v=pe(f.getAttribute("id"),o),x=b?this.extractTextStyleMarksFromStyle(b):{};if(y){const A=parseInt(y[1]),C=this.parseHtmlElement(f,x,t?.preserveExplicitMarkResets),F={type:"paragraph",id:v,heading:A,children:C.length>0?C:[{type:"text",text:"",marks:{}}]};if(k)for(const E of F.children)E.type==="text"&&(E.marks||(E.marks={}),E.marks.fontFamily||(E.marks.fontFamily=k));I!==void 0&&this.ensureTextNodesHaveFontSize(F.children,I),this.applyParagraphElementAttributes(F,f,p),h.push(F)}else{const A=this.parseHtmlElement(f,x,t?.preserveExplicitMarkResets),C={type:"paragraph",id:v,children:A.length>0?A:[{type:"text",text:"",marks:{}}]};if(k)for(const F of C.children)F.type==="text"&&(F.marks||(F.marks={}),F.marks.fontFamily||(F.marks.fontFamily=k));this.applyParagraphElementAttributes(C,f,p),h.push(C)}}if(o.remainingImageReferences.size>0){const f=Array.from(o.remainingImageReferences,m=>m.getAttribute("id")||"(new image)").join(", ");throw new fe("invalid_image_reference",`Image(s) ${f||"without ids"} are in unsupported HTML positions. Put each image directly in a table cell or as its own image block; mixed text/image paragraphs and list items are not supported.`)}return h.length===0&&h.push(Sl()),lc(h,t?.existingDocument?.stylesheet),this.applyInheritedFontStyling(h,t),ac(()=>pe(null,o),h),this.hydrateDocxRawPlaceholders(h,t?.existingDocument),{type:"doc",children:h}}static hydrateDocxRawPlaceholders(e,t){for(let n=e.length-1;n>=0;n--){const i=e[n];if(i.type==="docx-raw"){if(i.xml)continue;const o=i.id&&t?z(t,i.id):void 0;o&&o.type==="docx-raw"&&o.xml?(i.xml=o.xml,i.tagName=o.tagName,o.detail&&(i.detail=o.detail),i.origin=o.origin):e.splice(n,1);continue}const r=i.children;Array.isArray(r)&&r.length>0&&r.filter(o=>typeof o=="object"&&o!==null&&typeof o.type=="string"&&o.type!=="text").length>0&&this.hydrateDocxRawPlaceholders(r,t)}}static parseHtmlElement(e,t={},n=!1){const i=[];let r;const o=(a,l={})=>{if(a.nodeType===Node.TEXT_NODE){const c=Nc(a.textContent||"",l);c&&i.push({type:"text",text:c,marks:{...l}})}else if(a.nodeType===Node.ELEMENT_NODE){const c=a,d={...l};switch(c.tagName.toLowerCase()){case"b":case"strong":d.bold=!0;break;case"i":case"em":d.italic=!0;break;case"u":d.underline=!0;break;case"s":case"strike":d.strikethrough=!0;break;case"code":d.code=!0;break;case"l":case"latex-inline":d.latex=!0;break;case"sup":{d.superscript=!0;const p=c.getAttribute("data-footnote-ref");p&&(d.footnoteRef=p);const h=c.getAttribute("data-footnote");h!==null&&(d.footnoteRef=p??Y(),d.footnotePendingBody=h,c.getAttribute("data-note-kind")==="endnote"&&(d.footnotePendingKind="endnote"));break}case"sub":d.subscript=!0;break;case"mark":{const p=c.getAttribute("color"),h=this.normalizeAgentHighlightColor(p);if(p!==null&&!h)throw new Error(`Unsupported highlight color ${JSON.stringify(p)}. Use one of: ${Yt.join(", ")}.`);d.backgroundColor=h??hc}break;case"a":const g=c.getAttribute("href");g&&(d.link=g);break;case"comment-thread":{const p=c.getAttribute("id")?.trim();if(p){const h=d.comment?.split(",").map(f=>f.trim()).filter(Boolean);d.comment=[...h??[],p].join(",")}break}case"br":i.push({type:"text",text:`
21
- `,marks:{...l}});return;case"span":Il(d,c.getAttribute("data-docx-explicit-false-marks"),c.getAttribute("data-docx-run-property-resets")),c.getAttribute("data-word-hidden")==="true"&&(d.hidden=!0);{const p=c.getAttribute("data-bookmark");p&&(d.bookmark=p);const h=c.getAttribute("data-field-instr");h&&(d.fieldInstr=h);const f=c.getAttribute("data-word-lang");f&&(d.lang=f);const m=c.getAttribute("data-dynamic-field");(m==="page"||m==="numPages")&&(d.field=m);const y=c.getAttribute("data-sdt-inline");y&&(d.sdtInline=y),c.getAttribute("data-ai-generated")==="true"&&(d.aiGenerated=!0);const b=c.getAttribute("data-html-class");b&&(d.__htmlClassName=b)}const u=c.getAttribute("style");if(u){const p=u.match(/font-family:\s*([^;]+)/);p&&(d.fontFamily=this.resolveFontToCss(p[1].trim()));const h=this.extractFontSizeFromStyle(u);h!==void 0&&(d.fontSize=h);const f=this.parseCssFontWeightToBold(u);f===!0?d.bold=!0:f===!1&&(n?d.bold=!1:delete d.bold);const m=u.match(/(?:^|;)\s*font-style:\s*([^;]+)/i);if(m){const v=m[1].trim().toLowerCase();v==="italic"||v==="oblique"?d.italic=!0:v==="normal"&&(n?d.italic=!1:delete d.italic)}const y=u.match(/background-color:\s*([^;]+)/i);if(y){const v=this.normalizeAgentHighlightColor(y[1].trim());v&&(d.backgroundColor=v)}const b=u.match(/(?:^|;)\s*color:\s*([^;]+)/i);if(b){const v=Sn(b[1].trim());v&&!ns(v)&&(d.color=v)}const k=u.match(/text-decoration:\s*([^;]+)/i);if(k){const v=k[1].toLowerCase();if(v.trim()==="none")for(const x of["underline","strikethrough","doubleStrikethrough"])n?d[x]=!1:delete d[x];v.includes("line-through")&&(v.includes("double")?d.doubleStrikethrough=!0:d.strikethrough=!0)}/font-variant:\s*small-caps/i.test(u)&&(d.smallCaps=!0),/text-transform:\s*uppercase/i.test(u)&&(d.allCaps=!0);const I=u.match(/letter-spacing:\s*([^;]+)/i);if(I){const v=zs(I[1],d.fontSize);v!==void 0&&(d.letterSpacing=v)}}break}c.tagName.toLowerCase()!=="img"&&(r=d);for(const g of Array.from(a.childNodes))o(g,d)}};for(const a of Array.from(e.childNodes))o(a,{...t});if(i.length===0){const a=r??t;if(Object.keys(a).length>0)return[{type:"text",text:"",marks:{...a}}]}return i}static applyInheritedFontStyling(e,t){const n=this.extractBlockFontStyling(t?.replacementBlock),i=this.extractBlockFontStyling(t?.previousBlock);let r=n.fontFamily??i.fontFamily??(t?.parsingContext?t.parsingContext.documentFontFamily:this.findOmittableDocumentFontFamily(t?.existingDocument)),o=t?.replacementBlock?n.fontSize:i.fontSize;for(const a of e){if(a.type!=="paragraph"&&a.type!=="list")continue;if(a.type==="paragraph")this.ensureTextNodesHaveFontStyling(a.children,r,o);else if(a.type==="list")for(const c of a.children)this.ensureTextNodesHaveFontStyling(c.children,r,o);const l=this.extractBlockFontStyling(a);r=l.fontFamily??r,o=l.fontSize??o}}static extractBlockFontStyling(e){if(!e)return{};const t=[];if(e.type==="paragraph")for(const r of e.children)r.type==="text"&&!r.marks?.footnoteRef&&t.push(r);else if(e.type==="list")for(const r of e.children)for(const o of r.children)o.type==="text"&&!o.marks?.footnoteRef&&t.push(o);if(t.length===0)return{};const n=t[0].marks?.fontFamily,i=t[0].marks?.fontSize;return{fontFamily:t.every(r=>r.marks?.fontFamily===n)?n:void 0,fontSize:t.every(r=>r.marks?.fontSize===i)?i:void 0}}static ensureTextNodesHaveFontStyling(e,t,n){e.forEach(i=>{i.type==="text"?(i.marks=i.marks?{...i.marks}:{},!i.marks.fontFamily&&t&&(i.marks.fontFamily=t),i.marks.fontSize===void 0&&n!==void 0&&(i.marks.fontSize=n)):i.children&&this.ensureTextNodesHaveFontStyling(i.children,t,n)})}static ensureTextNodesHaveFontSize(e,t){for(const n of e)n.type==="text"&&(n.marks=n.marks?{...n.marks}:{},n.marks.fontSize||(n.marks.fontSize=t))}static formatLockedSelectionContext(e){if(!e||e.length===0)return null;const t=[];for(const n of e){const i=n.contextBlocks?wc(n.contextBlocks,n.startBlock,n.endBlock):void 0;if(!i||i.length===0){t.push(`<selection_context_omitted start_id="${this.escapeAttribute(n.startBlock)}" end_id="${this.escapeAttribute(n.endBlock)}">Selection context exceeds the size limit. Read the actual target before editing; this marker is not document content.</selection_context_omitted>`);continue}const r=this.buildSelectionInfoForBlocks(i,[n]);for(const o of i){const a=this.getBlockId(o),l=r?.get(a);t.push(this.blockToHtmlWithSelections(o,void 0,l,void 0,r))}}return t.length===0?null:t.filter(n=>n.length>0).join(`
22
- `)}};Nn.DEFAULT_FONT_FAMILY="Arial, sans-serif",Nn.MAX_OVERVIEW_BLOCKS=50,Nn.tableRowHtmlCache=new WeakMap;let te=Nn;function me(s){if(!s||typeof s!="object")return"";const e=s;if(e.type==="text"&&typeof e.text=="string")return e.text;if((e.type==="code"||e.type==="math")&&typeof e.content=="string")return e.content;if(Array.isArray(e.children)){const t=e.type==="list"?" ":"";return e.children.map(n=>me(n)).join(t)}return""}const Ws={P:"paragraph",LI:"list-item",TD:"table-cell",TH:"table-cell",TR:"table-row",TABLE:"table",UL:"list",OL:"list",H1:"paragraph",H2:"paragraph",H3:"paragraph",H4:"paragraph",H5:"paragraph",H6:"paragraph"};function Ys(s,e){if(!/<[^>]+\bid\s*=/i.test(e))return null;const t=me(s);if(t.includes(e)||t.includes(Jt(e)))return null;const n=document.createElement("template");n.innerHTML=e;const i=[...n.content.querySelectorAll("[id]")].filter(c=>Ws[c.tagName]);if(!i.length)return null;const r=new Map,o=(c,d=null)=>{if(!c||typeof c!="object")return;const g=c;g.id&&(d?d.add(g.id):r.set(g.id,[...r.get(g.id)??[],g])),g.children?.forEach(u=>o(u,d))};o(s);const a=new Set,l=new Set;for(const c of i){const d=r.get(c.id)??[];if(a.has(c.id)||d.length!==1||d[0].type!==Ws[c.tagName])throw new fe("target_stale",`HTML matcher id '${c.id}' is missing, contradictory, or outside the authorized target. Read the target again.`,"target_resolution");a.add(c.id);const g=d[0],u=me(g),p=c.textContent??"",h=Vt(u,p,"prefer-exact");if(u!==p&&!h.some(y=>y.start===0&&y.end===u.length))throw new fe("target_stale",`HTML matcher text for '${c.id}' no longer matches that block. Read it again before editing.`,"matching");const f=new Set;o(g,f);const m=i.filter(y=>y!==c&&c.contains(y));if(m.some(y=>!f.has(y.id)))throw new fe("target_stale",`HTML matcher ids contradict the document hierarchy inside '${c.id}'.`,"target_resolution");m.length||f.forEach(y=>l.add(y))}return l}function Et(s,e){const t=z(s,e);return t?.type==="list"&&t.id!==e?t.children.find(n=>n.id===e)??null:t}function Ui(s){if(!(!s||s.type!=="paragraph"&&s.type!=="list-item"))return te.toAgentHtml({type:"doc",children:[{...s,type:"paragraph"}]})}function Ln(s,e,t="prefer-exact"){const n=Ys(s,e),i=En(me(s),e,t,et(e)?Ui(s):void 0);if(!n)return i;const r=qs(s);return i.filter(o=>{const a=r.filter(l=>l.start<o.end&&o.start<l.end);return a.length>0&&a.every(l=>n.has(l.blockId))})}function qs(s){const e=[];let t=0;const n=i=>{if(!i||typeof i!="object")return;const r=i,o=Array.isArray(r.children)?r.children:[],a=r.type==="list"||r.type==="table"||r.type==="table-row"||r.type==="table-cell"||r.type==="container";if(r.id&&!a){const l=me(i);if(l.length>0){e.push({blockId:r.id,start:t,end:t+l.length,text:l}),t+=l.length;return}}o.forEach((l,c)=>{r.type==="list"&&c>0&&(t+=1),n(l)})};return n(s),e}function Lc(s,e,t){const n=[];for(const i of s){const r=Math.max(e,i.start),o=Math.min(t,i.end);o<=r||n.push({blockId:i.blockId,start:r-i.start,end:o-i.start})}return n}function Js(s){const e=new Map;let t=0;const n=i=>{if(!i||typeof i!="object")return;const r=i;if(r.type==="text"&&typeof r.text=="string"){const o=t;t+=r.text.length;for(const a of r.marks?.comment?.split(",")??[]){const l=a.trim();if(!l)continue;const c=e.get(l);e.set(l,{start:c?Math.min(c.start,o):o,end:c?Math.max(c.end,t):t})}return}if((r.type==="code"||r.type==="math")&&typeof r.content=="string"){t+=r.content.length;return}if(Array.isArray(r.children)){const o=r.type==="list"?1:0;r.children.forEach((a,l)=>{o&&l>0&&(t+=o),n(a)})}};return n(s),e}const Ks=300;function zi(s,e,t,n,i){const r=Js(e);return(s.comments??[]).filter(o=>!o.parentId&&o.resolved!==!0).filter(o=>!i.has(o.id)).filter(o=>{if(o.anchorBlockId===t)return!0;const a=r.get(o.id);return a?n?n.start<a.end&&a.start<n.end:!0:!1}).map(o=>({id:o.id,author:o.agentName??o.author,bodyMd:o.bodyMd.length>Ks?`${o.bodyMd.slice(0,Ks)}…`:o.bodyMd}))}function Vs(s,e){const t=e.length===1?"thread":"threads";return{success:!1,overlappingThreadIds:e.map(n=>n.id),errorCode:"comment_overlap",error:`That text in block ${s} already carries ${e.length} unresolved comment ${t}: ${e.map(n=>`${n.id} (${n.author}): "${n.bodyMd}"`).join("; ")}. If your point is already covered there, do not repeat it: reply with reply_to_comment_id="${e[0].id}". If you are raising a genuinely different point, retry with acknowledge_existing_thread_ids=[${e.map(n=>`"${n.id}"`).join(", ")}].`}}function Oc(s,e,t,n,i,r,o,a){const l=r&&typeof r=="object"?["text"in r,"start_text"in r||"end_text"in r,"whole_block"in r]:[],c=l.length>0&&("text"in r?typeof r.text=="string"&&r.text.length>0:"whole_block"in r?r.whole_block===!0:typeof r.start_text=="string"&&r.start_text.length>0&&typeof r.end_text=="string"&&r.end_text.length>0);if(l.filter(Boolean).length!==1||!c)return{success:!1,error:"Anchor must contain exactly one of: text, start_text/end_text, or whole_block=true.",errorCode:"invalid_anchor"};const d=new Set((a??[]).map(A=>A.trim()).filter(Boolean)),g=Et(s,n);if(!g)return{success:!1,error:`Block ${n} not found`,errorCode:"target_missing"};if("whole_block"in r){const A=zi(s,g,n,null,d);if(A.length>0)return Vs(n,A);const C=t.addBlockComment(n,i,o);return C?{success:!0,commentId:C}:{success:!1,error:`Could not attach a comment to block ${n}`}}const u=Et(e,n),p=me(u??g);let h=-1,f=-1;const m="text"in r?Ln(u??g,r.text):Ic(p,r.start_text,r.end_text,Ui(u??g),(A,C)=>Ln(u??g,A,C));if(m.length!==1)return{success:!1,error:m.length?`Anchor text matched ${m.length} locations in block '${n}'. Provide unique text or an HTML fragment that identifies the formatting, such as <b>claim</b> for bold or <i>claim</i> for italic. Start/end boundary text is included in the comment range; do not use surrounding separators unless they should also be commented on.`:`Anchor text was not found in block '${n}'.`,errorCode:m.length?"anchor_ambiguous":"anchor_not_found"};({start:h,end:f}=m[0]);const y=qs(u??g),b=Lc(y,h,f);if(b.length===0)return{success:!1,error:`The anchor range in block ${n} does not map to commentable text`};const k=[];for(const A of b){const C=Et(e,A.blockId),F=Et(s,A.blockId);if(!C||!F)return{success:!1,error:`The anchor range in block ${n} could not be mapped to its live text; read the block again and retry`};let E={start:A.start,end:A.end};if(me(F)!==me(C)){const P=t.mapAcceptedSuggestionRangeToLiveRange(A.blockId,A.start,A.end);if(!P)return{success:!1,error:`The anchor range in block ${n} could not be mapped across pending suggestions; read the block again and retry`};E=P}k.push({blockId:A.blockId,...E})}const I=new Map;for(const A of zi(s,g,n,{start:h,end:f},d))s.comments?.some(C=>C.id===A.id&&C.anchorBlockId===n)&&I.set(A.id,A);for(const A of k){const C=Et(s,A.blockId);if(C)for(const F of zi(s,C,A.blockId,{start:A.start,end:A.end},d))I.set(F.id,F)}const v=Array.from(I.values());if(v.length>0)return Vs(n,v);const x=t.addCommentToRanges(k,i,o);return x?{success:!0,commentId:x,range:{start:h,end:f}}:{success:!1,error:`Could not attach a comment to block ${n}`}}function Gs(s,e){const t=s.comments??[];let n=t.find(r=>r.id===e);if(!n)return null;const i=new Set([n.id]);for(;n.parentId&&!i.has(n.parentId);){i.add(n.parentId);const r=t.find(o=>o.id===n.parentId);if(!r)break;n=r}return n}function Rc(s,e,t,n,i){const r=Gs(s,t);if(!r)return{success:!1,error:`Comment ${t} not found`,errorCode:"target_not_found"};if(r.resolved)return{success:!1,error:`Comment thread ${r.id} is resolved; leave a new comment instead`,errorCode:"already_resolved"};const o=e.replyToComment(r.id,n,i);return o?{success:!0,commentId:o,threadId:r.id}:{success:!1,error:`Could not reply to comment ${t}`,errorCode:"comment_mutation_failed"}}function Dc(s,e,t){const n=z(s.getDocument(),e),i=z(s.getDocumentWithAcceptedSuggestions(),e);if(!n||!i)throw new fe("target_missing",`Footnote target '${e}' no longer exists. Read the document again.`,"target_resolution");if(n.type!=="paragraph"||i.type!=="paragraph")throw new fe("target_unsupported","Footnote references require a paragraph target. Read the paragraph inside this block and use its id.","target_resolution");const r=t?Ln(i,t):[];if(t&&r.length!==1)throw new fe(r.length?"anchor_ambiguous":"anchor_not_found",r.length?`Anchor text matched ${r.length} locations in block ${e}; include unique surrounding text.`:`Anchor text ${JSON.stringify(t)} not found in block ${e}. Read it again.`,"matching");let o=t?r[0].end:me(i).length;if(me(n)!==me(i)){const a=s.mapAcceptedSuggestionRangeToLiveRange(e,o,o);if(!a)throw new fe("target_stale","Anchor could not be mapped across pending suggestions. Read the block again.","target_resolution");o=a.end}return{block:e,offset:o}}function Hi(s,e){return{indentStepPx:Ve(e).indentStepPx,storedAsUnits:s.get(Ge.paragraphIndentStorageVersion)===wi}}const Qs=new WeakMap;function Wi(s){return s.getXmlFragment("content")}function Zs(s,e){let t=e,n=null;for(;t;){if(n=t.parent,n===s)return t instanceof S.XmlElement&&t.getAttribute("id")||null;t=n}return null}function _c(s){const e=Wi(s),t={nestedBlocks:new WeakMap,doc:null,blockCache:new Map,elementByBlockId:new Map,dirtyBlockIds:new Set,structuralChange:!1,observer:()=>{}},n=i=>{for(const r of i){let o=r.target;for(;o&&o!==e;)o instanceof S.XmlElement&&t.nestedBlocks.delete(o),o=o.parent;if(r.target===e&&r instanceof S.YXmlEvent&&r.childListChanged){t.structuralChange=!0;continue}if(r instanceof S.YXmlEvent&&r.childListChanged){const l=Zs(e,r.target);l!==null&&t.dirtyBlockIds.add(l);continue}const a=Zs(e,r.target);a!==null&&t.dirtyBlockIds.add(a)}};return t.observer=n,e.observeDeep(n),t}function eo(s){let e=Qs.get(s);return e||(e=_c(s),Qs.set(s,e)),e}function On(s,e){const t=eo(s);t.nestedBlocks=new WeakMap,t.doc=e,t.blockCache.clear(),t.elementByBlockId.clear();const n=Wi(s).toArray();for(const i of e.children)i.id&&t.blockCache.set(i.id,i);for(const i of n)if(i instanceof S.XmlElement){const r=i.getAttribute("id");r&&t.elementByBlockId.set(r,i)}t.dirtyBlockIds.clear(),t.structuralChange=!1}function Rn(s,e,t){const n=t.nestedBlocks.get(s);if(n)return n;const i=Ti(s,e,void 0,r=>Rn(r,e,t));return i&&t.nestedBlocks.set(s,i),i}const Dn=new WeakMap;function jc(s){let e=Dn.get(s);e||(e={blocks:[],dirty:!0,observing:!1},Dn.set(s,e));const t=s.getXmlFragment("chrome");if(e.observing||(e.observing=!0,t.observeDeep(()=>{const n=Dn.get(s);n&&(n.dirty=!0)})),e.dirty){const n=[];for(const i of t.toArray())if(i instanceof S.XmlElement||i?.constructor?.name==="YXmlElement"){const r=Ti(i,Hi(s.getMap("metadata"),void 0));r&&r.type==="header-footer"&&n.push(r)}e.blocks=n,e.dirty=!1}return e.blocks}const _n=new WeakMap;function Xc(s){let e=_n.get(s);e||(e={blocks:[],dirty:!0,observing:!1},_n.set(s,e));const t=s.getXmlFragment("notes");if(e.observing||(e.observing=!0,t.observeDeep(()=>{const n=_n.get(s);n&&(n.dirty=!0)})),e.dirty){const n=[];for(const i of t.toArray())if(i instanceof S.XmlElement||i?.constructor?.name==="YXmlElement"){const r=Ti(i,Hi(s.getMap("metadata"),void 0));r&&r.type==="footnote"&&n.push(r)}e.blocks=n,e.dirty=!1}return e.blocks}function Uc(s){return!!(Dn.get(s)?.dirty||_n.get(s)?.dirty)}function jn(s,e){const t=Xc(e);t.length>0?(s.notes=t,vl(s)):delete s.notes}function Xn(s,e){const t=e.getMap("comments"),n=[];t.forEach(i=>{i&&typeof i=="object"&&n.push(i)}),n.length>0?(n.sort((i,r)=>(i.createdAt??"").localeCompare(r.createdAt??"")),s.comments=n):delete s.comments}function Yi(s,e){const t=e.getMap("oxml-ranges"),n=[];t.forEach(i=>{i&&typeof i=="object"&&n.push(i)}),n.length>0?(n.sort((i,r)=>i.id.localeCompare(r.id)),s.oxmlRanges=n):delete s.oxmlRanges}function Un(s,e){const t=e.getMap("sdt-wrappers"),n=[];if(t.forEach(i=>{i&&typeof i=="object"&&n.push(i)}),n.length>0){const i=new Map;s.children.forEach((o,a)=>{o.id&&i.set(o.id,a)});const r=o=>o.blockIds?.[0]??o.startBlockId??"";n.sort((o,a)=>(i.get(r(o))??Number.MAX_SAFE_INTEGER)-(i.get(r(a))??Number.MAX_SAFE_INTEGER)||o.id.localeCompare(a.id)),s.sdtWrappers=n}else delete s.sdtWrappers}function zn(s,e){const t=jc(e);t.length>0?s.chrome=t:delete s.chrome;const n=ss(t);n.headers?s.headers=n.headers:delete s.headers,n.footers?s.footers=n.footers:delete s.footers}function He(s){const e=eo(s),t=Wi(s),n=s.getMap("metadata"),i=n?.get("title"),r=n?.get("pageless"),o=n?.get("watermark"),a=typeof o=="string"&&o.trim()!==""?o:void 0,l=n?.get("chromeImages"),c=Array.isArray(l)&&l.length>0?l:void 0,d=n?.get("stylesheet"),g=d&&typeof d=="object"&&Array.isArray(d.paragraphStyles)&&d.paragraphStyles.length>0?d:void 0,u=n?.get("stylesXml"),p=typeof u=="string"&&u.length>0?u:void 0,h=n?.get("docxSource"),f=h&&typeof h=="object"&&Array.isArray(h.spans)?h:void 0,m=n?.get("coreProperties"),y=m&&typeof m=="object"&&Object.keys(m).length>0?m:void 0,b=n?.get("fontSubstitutes"),k=b&&typeof b=="object"&&Object.keys(b).length>0?b:void 0,I=rs(n),v=Hi(n,I);if(e.indentContext&&(e.indentContext.indentStepPx!==v.indentStepPx||e.indentContext.storedAsUnits!==v.storedAsUnits)&&(e.nestedBlocks=new WeakMap,e.doc=null,e.blockCache.clear(),e.elementByBlockId.clear()),e.indentContext=v,!e.doc){const x=[],A=t.toArray();for(let C=0;C<A.length;C++){const F=A[C];if(F instanceof S.XmlElement){const E=Rn(F,v,e);E&&(x.push(E),e.blockCache.set(E.id,E),e.elementByBlockId.set(E.id,F))}}return e.doc={type:"doc",children:x},i&&(e.doc.title=i),r!==void 0&&(e.doc.pageless=r),I&&(e.doc.pageLayout=I),a&&(e.doc.watermark=a),c&&(e.doc.chromeImages=c),g&&(e.doc.stylesheet=g),p&&(e.doc.stylesXml=p),f&&(e.doc.docxSource=f),y&&(e.doc.coreProperties=y),k&&(e.doc.fontSubstitutes=k),zn(e.doc,s),jn(e.doc,s),Xn(e.doc,s),Un(e.doc,s),Yi(e.doc,s),e.dirtyBlockIds.clear(),e.structuralChange=!1,e.doc}if(t.length!==e.doc.children.length&&(e.structuralChange=!0),e.structuralChange){const x=[],A=new Map,C=new Map,F=t.toArray();for(let E=0;E<F.length;E++){const P=F[E];if(P instanceof S.XmlElement){const B=P.getAttribute("id"),w=B?e.dirtyBlockIds.has(B):!0,T=B?e.blockCache.get(B):void 0,N=B!==null&&e.elementByBlockId.get(B)===P;if(B&&!w&&T&&N)x.push(T),A.set(B,T),C.set(B,P);else{const L=Rn(P,v,e);L&&(x.push(L),A.set(L.id,L),C.set(L.id,P))}}}return e.doc={type:"doc",children:x},i&&(e.doc.title=i),r!==void 0&&(e.doc.pageless=r),I&&(e.doc.pageLayout=I),a&&(e.doc.watermark=a),c&&(e.doc.chromeImages=c),g&&(e.doc.stylesheet=g),p&&(e.doc.stylesXml=p),f&&(e.doc.docxSource=f),y&&(e.doc.coreProperties=y),k&&(e.doc.fontSubstitutes=k),zn(e.doc,s),jn(e.doc,s),Xn(e.doc,s),Un(e.doc,s),Yi(e.doc,s),e.blockCache=A,e.elementByBlockId=C,e.dirtyBlockIds.clear(),e.structuralChange=!1,e.doc}if(e.dirtyBlockIds.size>0){const x=[...e.doc.children],A=t.toArray();for(let C=0;C<x.length;C++){const F=x[C];if(F?.id&&e.dirtyBlockIds.has(F.id)&&C<A.length){const E=A[C];if(E instanceof S.XmlElement){const P=Rn(E,v,e);P&&(e.blockCache.delete(F.id),x[C]=P,e.blockCache.set(P.id,P),e.elementByBlockId.set(P.id,E))}}}e.doc={type:"doc",children:x},i&&(e.doc.title=i),r!==void 0&&(e.doc.pageless=r),I&&(e.doc.pageLayout=I),a&&(e.doc.watermark=a),c&&(e.doc.chromeImages=c),g&&(e.doc.stylesheet=g),p&&(e.doc.stylesXml=p),f&&(e.doc.docxSource=f),y&&(e.doc.coreProperties=y),k&&(e.doc.fontSubstitutes=k),zn(e.doc,s),jn(e.doc,s),Xn(e.doc,s),Un(e.doc,s),Yi(e.doc,s),e.dirtyBlockIds.clear()}return i!==void 0?e.doc.title=i:delete e.doc.title,r!==void 0?e.doc.pageless=r:delete e.doc.pageless,I?e.doc.pageLayout=I:delete e.doc.pageLayout,p?e.doc.stylesXml=p:delete e.doc.stylesXml,f?e.doc.docxSource=f:delete e.doc.docxSource,y?e.doc.coreProperties=y:delete e.doc.coreProperties,k?e.doc.fontSubstitutes=k:delete e.doc.fontSubstitutes,e.doc.chromeImages!==c&&(e.doc={...e.doc},c?e.doc.chromeImages=c:delete e.doc.chromeImages),e.doc.watermark!==a&&(e.doc={...e.doc},a!==void 0?e.doc.watermark=a:delete e.doc.watermark),e.doc.stylesheet!==g&&(e.doc={...e.doc},g!==void 0?e.doc.stylesheet=g:delete e.doc.stylesheet),Uc(s)&&(e.doc={...e.doc}),zn(e.doc,s),jn(e.doc,s),Xn(e.doc,s),Un(e.doc,s),e.doc}const qi=new WeakMap,Gt="__revise_end_of_document__";function ve(s,e){qi.set(s,{...qi.get(s),...e})}function Me(s){return qi.get(s)}function Hn(s){if(s.name==="insert_block")return Me(s)?.stableId}function zc(s){return!!Me(s)?.allowNoopContinuation}function Hc(s){if(s.name==="replace_block")return Me(s)?.multiBlockReplace}function to(s,e){if(et(e)){let t=null;for(const n of s){const i=n.html?Rs(n.text,n.html,e):[];if(i.length){if(i.length>1||t!==null)return null;t=n.blockId}}if(t!==null)return t}for(const t of["exact","normalized"]){let n=null;for(const i of s){const r=En(i.text,e,t);if(r.length){if(r.length>1||n!==null)return null;n=i.blockId}}if(n!==null)return n}return null}function Ji(s){const e=Mn(s).at(-1);return Di(tt(e)).text}function no(s){return s?.type==="paragraph"||s?.type==="list-item"||s?.type==="code"||s?.type==="math"}function io(s){const e=[],t=(n,i)=>{if(!(!n||typeof n!="object")&&(typeof n.id=="string"&&n.id.trim().length>0&&no(n)&&e.push({blockId:n.id,topLevelBlockId:i,text:me(n)}),Array.isArray(n.children)))for(const r of n.children)t(r,i)};for(const n of s.children)t(n,n.id??null);for(const n of s.notes??[])t(n,n.id);return e}function Ki(s,e){const t=n=>!n||typeof n!="object"?!1:n.id===e?!0:Array.isArray(n.children)&&n.children.some(t);for(const n of s.notes??[])if(t(n))return n.id;return null}function ro(s,e){const t=Ki(s,e);if(!t)return null;if(e!==t)return e;const n=s.notes?.find(o=>o.id===t);if(!n)return e;const i=[],r=o=>{!o||typeof o!="object"||(typeof o.id=="string"&&(o.type==="paragraph"||o.type==="list-item"||o.type==="code"||o.type==="math")&&i.push(o.id),Array.isArray(o.children)&&o.children.forEach(r))};return n.children.forEach(r),i.length===1?i[0]:e}function so(s,e){return e.has(s.blockId)||s.topLevelBlockId!==null&&e.has(s.topLevelBlockId)}function oo(s){if(!s.loadedBlockIds||s.loadedBlockIds.size===0)return null;const e=Ji(s.find);if(!e||/^\s*$/.test(e))return null;const t=z(s.doc,s.requestedBlockId);if(t&&Ji(me(t)).includes(e))return null;const n=Mn(s.find).at(-1),i=io(s.doc).filter(o=>o.blockId!==s.requestedBlockId&&so(o,s.loadedBlockIds));if(i.some(o=>Vt(o.text,n).length>0))return to(i,n);let r=null;for(const o of i)if(Ji(o.text).includes(e)){if(r!==null)return null;r=o.blockId}return r}function Wc(s){if(s.action.name!=="replace"&&s.action.name!=="replace_all")return{action:s.action};if(!s.action.arguments||typeof s.action.arguments!="object")return{action:s.action};const e=s.action.arguments,t=typeof e.id=="string"?e.id.trim():"",n=typeof e.find=="string"?e.find:"";if(!t||!n)return{action:s.action};const i=oo({doc:s.doc,requestedBlockId:t,find:n,loadedBlockIds:s.loadedBlockIds});if(!i)return{action:s.action};const r={...s.action,arguments:{...e,id:i}},o=Me(s.action);return o&&ve(r,o),{action:r,retarget:{fromBlockId:t,toBlockId:i}}}function Yc(s){const e=[],t=[];for(const n of s.actions){const i=Wc({action:n,doc:s.doc,loadedBlockIds:s.loadedBlockIds});e.push(i.action),i.retarget&&t.push(i.retarget)}return{actions:e,retargets:t}}function Vi(s){return s.children.map(e=>{const t={type:"doc",children:[e]};return te.toInternalHtml(t).trim()})}function qc(s,e=0){const t=Bn.fromMarkdown(s);if(e){for(const n of t.children)if(n.type==="list")for(const i of n.children)i.indentLevel=Math.min(8,e+(i.indentLevel??0))}return Vi(t)}function Jc(s){return s.replace(/<span\b([^>]*?)\sdir\s*=\s*["']?(ltr|rtl|auto)["']?([^>]*)>([\s\S]*?)<\/span>/gi,(e,t,n,i,r)=>{const o=n.toLowerCase(),a=o==="ltr"?"⁦":o==="rtl"?"⁧":"⁨",l=`${t}${i}`.trim(),c=l?`<span ${l}>${r}</span>`:r;return`${a}${c}⁩`})}function Kc(s,e,t,n){return Vi(te.fromAgentHtml(Jc(s),{existingDocument:e,replacementBlock:t,listItemBaseIndent:n,preserveImageReferenceIds:!0}))}const ft=/<\/?[a-z][^>]*>/i;function $t(s){return s.replace(/\s+/g," ").trim()}function ao(s){return $t(s).replace(/^>\s+/,"")}function Vc(s,e){if(s.replace==="")return null;const t=s.format==="html"||ft.test(s.replace),n=t?te.fromAgentHtml(s.replace,{replacementBlock:z(e,s.id)??void 0,existingDocument:e,preserveImageReferenceIds:!0}):Bn.fromMarkdown(s.replace);if(n.children.length!==1||n.children[0].type!=="list")return null;const i=n.children[0].children;if(i.length===0)return null;const r=z(e,s.id);if(!r||r.type!=="list")return null;const o=r,a=ft.test(s.find)?te.fromAgentHtml(s.find,{existingDocument:e,preserveImageReferenceIds:!0}):Bn.fromMarkdown(s.find),l=a.children.length===1&&a.children[0].type==="list"?a.children[0].children.map(y=>$t(me(y))):[$t(me(a))];if(l.length===0||l.some(y=>y===""))return null;const c=o.children.map(y=>$t(me(y))),d=[];for(let y=0;y+l.length<=c.length;y++)l.every((b,k)=>c[y+k]===b)&&(d.push(y),y+=l.length-1);if(d.length===0)throw new Error(`replace: the replacement contains ${i.length} list items, so "find" must match complete list item(s) in block '${s.id}' — it did not. Include each full item's text in "find" (or use insert_markdown to add items).`);if(d.length>1&&!s.all)throw new Error(`replace: "find" matches ${d.length} runs of list items in block '${s.id}'. Include more items in "find" so it matches exactly one location, or set all: true.`);const g=s.all?d:[d[0]],u=[];let p=0;for(const y of g)u.push(...o.children.slice(p,y)),u.push(...i),p=y+l.length;u.push(...o.children.slice(p));const h=g.length===1&&g[0]===0&&l.length===o.children.length,f=h?{...n.children[0],id:o.id}:{...o,children:u},m=h&&t?s.replace:Vi({children:[f]})[0];return{name:"replace_block",arguments:{id:o.id,content:[m]}}}function Gc(s,e){if(s.replace===""||s.all)return null;const t=z(e,s.id);if(!t)return null;const n=s.format==="html"||!s.format&&ft.test(s.find)?me(te.fromAgentHtml(s.find,{existingDocument:e,preserveImageReferenceIds:!0})):me(Bn.fromMarkdown(s.find)),i=me(t);if(ao(n)!==ao(i))return null;const r=s.format==="html"||!s.format&&ft.test(s.replace)?Kc(s.replace,e,t):qc(s.replace),o=r.length===1&&/^<p\b[^>]*>[\s\S]*<\/p>$/i.test(r[0]),a=(s.format==="html"||!s.format&&ft.test(s.replace))&&/^<p\s+[^>]+>/i.test(s.replace.trim()),l=t.type==="footnote"?ro(e,s.id):null,c=l!==null&&l!==s.id&&z(e,l)?.type==="paragraph",d=s.format!=="markdown"&&ft.test(s.find)&&!ft.test(s.find.replace(/<\/?(?:b|strong|i|em|u|s|strike|sup|sub|code|mark|span|a|br)\b[^>]*>/gi,""));return o&&!a&&(t.type==="table-cell"||c||t.type==="paragraph"&&(d||$t(s.find)===$t(i)))?null:{name:"replace_block",arguments:{id:s.id,content:r}}}function Qc(s,e){return Vc(s,e)??Gc(s,e)}function Gi(s,e){const t=z(s,e);return t?lo(t):null}function lo(s){const e=JSON.stringify(s);let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36)}function Zc(s,e){const t=new Map;for(const n of e){if(t.has(n))continue;const i=Gi(s,n);i!==null&&t.set(n,i)}return t}const co=50,go="document_state_changed",ed=new Set(["replace","replace_block","style_blocks","remove_block","remove_blocks"]);function Qi(s,e){const t=s.name==="replace"&&!!s.arguments&&typeof s.arguments=="object"&&Object.prototype.hasOwnProperty.call(s.arguments,"replacements"),n=s.name==="replace_many";if(!t&&!n)return{actions:[s]};const i=n?"replace_many":"replace";if(!s.arguments||typeof s.arguments!="object")return{actions:[],error:`${i} requires object arguments`};const r=s.arguments.id,o=s.arguments.replacements;if(!Array.isArray(o)||o.length===0)return{actions:[],error:`${i} requires a non-empty replacements array`};if(o.length>co)return{actions:[],error:`${i} supports at most ${co} replacements per call`};const a=[];for(let c=0;c<o.length;c++){const d=o[c];if(!d||typeof d!="object")return{actions:[],error:`${i} replacement #${c+1} must be an object`};if(typeof d.find!="string")return{actions:[],error:`${i} replacement #${c+1} is missing "find"`};if(d.find.length===0&&(n||typeof r!="string"||r.trim().length===0))return{actions:[],error:n?`${i} replacement #${c+1} has an empty "find"`:`${i} replacement #${c+1} has an empty "find" and therefore requires a direct block id`};if(typeof d.replace!="string")return{actions:[],error:`${i} replacement #${c+1} is missing "replace"`};if(d.occurrence!==void 0&&d.occurrence!==null&&d.occurrence!=="unique"&&d.occurrence!=="all")return{actions:[],error:`${i} replacement #${c+1} has invalid "occurrence"; use "unique" or "all"`};if(d.comment!==void 0&&d.comment!==null&&(typeof d.comment!="string"||d.comment.trim().length===0))return{actions:[],error:`${i} replacement #${c+1} comment must be a non-empty string when provided`};let g=typeof r=="string"?r.trim():"";if(!g&&d.find.length>0&&e&&(g=oo({doc:e.doc,requestedBlockId:"",find:d.find,loadedBlockIds:e.loadedBlockIds})??""),!g)return{actions:[],error:`${i} replacement #${c+1} requires a block id unless its find text uniquely identifies one loaded block`};if(e&&!d.comment)try{const u=Qc({type:"replace",id:g,find:d.find,replace:d.replace,format:"html",all:d.occurrence==="all"},e.doc);if(u){a.push({...u,id:`${s.id||i}-${c+1}`});continue}}catch(u){return{actions:[],error:u instanceof Error?u.message:String(u),failure:Mt(u)}}a.push({id:`${s.id||i}-${c+1}`,name:d.occurrence==="all"?"replace_all":"replace",arguments:{id:g,find:d.find,replace:d.replace,...typeof d.comment=="string"?{comment:d.comment.trim()}:{}}})}const l=Array.from(new Set(a.map(c=>c.arguments?.id).filter(c=>typeof c=="string"&&c.length>0)));return{actions:a,blockId:l.length===1?l[0]:void 0}}function td(s){const{toolCall:e,docBefore:t,resultSets:n}=s,i=e.arguments;if(!i||typeof i!="object")return null;const r=i.search_result_id;if(r==null)return null;if(typeof r!="string"||r.trim().length===0)return{actions:[],targetBlockIds:[],error:"search_result_id must be a non-empty string"};const o=r.trim();if(!ed.has(e.name))return{actions:[],targetBlockIds:[],error:`${e.name} does not support search_result_id`};if(typeof i.id=="string"&&String(i.id).trim().length>0||Array.isArray(i.ids))return{actions:[],targetBlockIds:[],error:`${e.name} accepts either search_result_id or direct id/ids targets, not both.`};const a=n.get(o);if(!a)return{actions:[],targetBlockIds:[],error:`Search result '${o}' is unavailable. Search result references are request-scoped; rerun search_document in this request, then retry.`,errorCode:go};for(const g of a.blockIds){if(Ki(t,g))return{actions:[],targetBlockIds:[],error:"Bulk search-result mutations cannot include footnote or endnote bodies. Target those note blocks individually."};const u=Gi(t,g);if(u===null||u!==a.blockHashes.get(g))return{actions:[],targetBlockIds:[],error:`Search result '${o}' is stale because block '${g}' changed or disappeared. Rerun search_document, then retry; no partial mutation was applied.`,errorCode:go}}const{search_result_id:l,...c}=i,d=[];if(e.name==="replace")for(let g=0;g<a.blockIds.length;g++){const u=Qi({...e,id:`${e.id||"replace"}-search-${g+1}`,arguments:{...c,id:a.blockIds[g]}});if(u.error)return{actions:[],targetBlockIds:[],error:u.error};d.push(...u.actions)}else if(e.name==="replace_block"){const g=i.count;if(g!=null&&g!==1)return{actions:[],targetBlockIds:[],error:"replace_block with search_result_id applies independently to each matched block, so count must be omitted or 1."};for(let u=0;u<a.blockIds.length;u++)d.push({...e,id:`${e.id||"replace_block"}-search-${u+1}`,arguments:{...c,id:a.blockIds[u],count:1}})}else if(e.name==="remove_block")for(let g=0;g<a.blockIds.length;g++)d.push({...e,id:`${e.id||"remove_block"}-search-${g+1}`,arguments:{id:a.blockIds[g],count:1}});else{const g=i.selectors,u=(Array.isArray(g)?g:typeof g=="string"?[g]:[]).flatMap(h=>typeof h=="string"?h.split(",").map(f=>f.trim()):[h]);if(u.length===0||u.some(h=>typeof h!="string"||h.trim().length===0))return{actions:[],targetBlockIds:[],error:"style_blocks requires one or more non-empty selectors"};const p=a.blockIds.flatMap(h=>u.map(f=>{const m=String(f).trim();return/^(?:\*|all|document|:root)$/i.test(m)?`#${h}`:`#${h} ${m}`}));d.push({...e,arguments:{...c,selectors:p}})}return{actions:d,targetBlockIds:[...a.blockIds],resultSet:a}}function uo(s,e){const t={...e};for(const n of["lang","oxmlRPr","oxmlRange","sdtInline","field","aiGenerated","__htmlClassName"])t[n]===void 0&&s?.[n]!==void 0&&Object.assign(t,{[n]:s[n]});for(const n of os)t[n]===void 0&&s?.[n]===!1&&(t[n]=!1);if(t.docxRunPropertyResets===void 0){const n=vi(s?.docxRunPropertyResets)?.split(",").filter(i=>i==="color"?t.color===void 0:t.backgroundColor===void 0);n?.length&&(t.docxRunPropertyResets=n.join(","))}return t}function Wn(s,e){const t=s.map(o=>o.text).join("");if(!t||t!==e.map(o=>o.text).join("")){const o=new Set(s.filter(l=>l.text.length>0).map(l=>l.marks?.lang)),a=o.size===1?[...o][0]:void 0;return a===void 0?e:e.map(l=>({...l,marks:{lang:a,...l.marks}}))}const n=[];let i=0,r=0;for(const o of e){if(o.text.length===0){n.push({...o,marks:o.marks?{...o.marks}:void 0});continue}let a=0;for(;a<o.text.length;){for(;r===s[i].text.length;)i++,r=0;const l=s[i],c=Math.min(o.text.length-a,l.text.length-r);n.push({...o,text:o.text.slice(a,a+c),marks:uo(l.marks,o.marks)}),a+=c,r+=c}}return n}function nd(s,e){const t=Ze(s),n=Array.from({length:t.cols},(l,c)=>Math.max(.001,s.columnWidths[c]||100/t.cols)),i=new Map;for(const l of e){const c=t.byId.get(l.cellId);if(!c)throw new fe("target_stale","The requested table cell no longer exists. Read the table again.","target_resolution");if(!Number.isFinite(l.percent)||l.percent<=0||l.percent>100)throw new fe("attribute_value_unsupported","Cell width must be greater than 0 and at most 100 percent.");const d=n.slice(c.col,c.col+c.colSpan).reduce((g,u)=>g+u,0);for(let g=c.col;g<c.col+c.colSpan;g++){const u=l.percent*n[g]/d;if(i.has(g)&&Math.abs(i.get(g)-u)>.001)throw new fe("attribute_conflict","Conflicting cell widths constrain the same table column. Set each column once, using one unmerged row.");i.set(g,u)}}const r=[...i.values()].reduce((l,c)=>l+c,0),o=n.map((l,c)=>c).filter(l=>!i.has(l));if(r>100.001||!o.length&&Math.abs(r-100)>.001||o.length&&r>=100)throw new fe("attribute_conflict","Requested column widths conflict: they must leave space for other columns and sum to 100 percent when all columns are specified.");const a=o.reduce((l,c)=>l+n[c],0);return n.map((l,c)=>i.get(c)??(100-r)*l/a)}function ho(s,e,t,n){if(!n?.length)return;const i=e==="row"?s.cols:s.rows;if(n.length>i)return{success:!1,error:`content[${i}] is outside the table's ${i} ${e==="row"?"columns":"rows"}. Supply at most ${i} entries for this insertion.`};for(const r of s.cells){const o=e==="row"?r.row:r.col,a=e==="row"?r.rowSpan:r.colSpan;if(o>=t||o+a<=t)continue;const l=e==="row"?r.col:r.row,c=e==="row"?r.colSpan:r.rowSpan;for(let d=l;d<l+c;d++)if(n[d]?.length)return{success:!1,error:`content[${d}] targets a position covered by a merged cell. Leave that slot empty or insert outside the merged span; the table was not changed.`}}}function id(s){return{type:"paragraph",id:Y(),children:[{type:"text",text:""}]}}function rd(s){return{type:"table-cell",id:Y(),children:[id()]}}function fo(s,e){return!s||s.length===0?rd():{type:"table-cell",id:Y(),children:s}}function Yn(s,e){const t=s.get("content",S.XmlFragment);function n(i){for(let r=0;r<i.length;r++){const o=i.get(r);if(o instanceof S.XmlElement){if(o.nodeName==="table"&&o.getAttribute("id")===e)return o;if(o.nodeName==="container"||o.nodeName==="footnote"||o.nodeName==="table"||o.nodeName==="table-row"||o.nodeName==="table-cell"){const a=n(o);if(a)return a}}}return null}return n(t)??n(s.getXmlFragment("notes"))}function Zi(s,e){const t=Number(ee(s,e));return Number.isFinite(t)&&t>1?Math.floor(t):1}function qn(s){const e=[];for(let a=0;a<s.length;a++){const l=s.get(a);l instanceof S.XmlElement&&l.nodeName==="table-row"&&e.push(l)}const t=s.getAttribute("columnWidths");let n=0;try{const a=t?JSON.parse(t):[];n=Array.isArray(a)?a.length:0}catch{n=0}for(const a of e){let l=0;for(let c=0;c<a.length;c++){const d=a.get(c);d instanceof S.XmlElement&&d.nodeName==="table-cell"&&(l+=Zi(d,"colSpan"))}n=Math.max(n,l)}n=Math.max(n,1);const i=e.length,r=Array.from({length:i},()=>new Array(n).fill(void 0)),o=[];for(let a=0;a<i;a++){const l=e[a];let c=0,d=0;for(let g=0;g<l.length;g++){const u=l.get(g);if(!(u instanceof S.XmlElement)||u.nodeName!=="table-cell")continue;for(;c<n&&r[a][c]!==void 0;)c++;if(c>=n)break;const p=Math.min(Zi(u,"colSpan"),n-c),h=Math.min(Zi(u,"rowSpan"),i-a),f={el:u,row:a,col:c,rowSpan:h,colSpan:p,physicalIndex:d};o.push(f);for(let m=a;m<a+h;m++)for(let y=c;y<c+p;y++)r[m][y]===void 0&&(r[m][y]=f);c+=p,d++}}return{rows:i,cols:n,cells:o,occupancy:r,rowEls:e}}function Qt(s,e,t){t>1?s.setAttribute(e,String(t)):J(s,e)}function po(s){return Se(s)}function sd(s){const e=new S.XmlElement("table-row");e.setAttribute("id",s.id);let t=0;for(const n of s.children){const i=po(n);e.insert(t++,[i])}return e}function od(s,e,t){const n=Yn(s,e);if(!n)return{success:!1,error:`Table with ID "${e}" not found.`};const i=qn(n);return i.rows===0?{success:!1,error:"Table has no rows."}:t<0||t>=i.cols?{success:!1,error:`Invalid column index ${t}. Table has ${i.cols} columns.`}:i.cols<=1?{success:!1,error:"Cannot remove the last column from a table."}:(s.transact(()=>{for(const o of i.cells)o.col<=t&&t<o.col+o.colSpan&&(o.colSpan>1?Qt(o.el,"colSpan",o.colSpan-1):i.rowEls[o.row].delete(o.physicalIndex,1));const r=n.getAttribute("columnWidths");if(r){const o=JSON.parse(r);if(t<o.length){const a=o[t];o.splice(t,1);const l=o.reduce((d,g)=>d+g,0),c=l>0?o.map(d=>d+a*d/l):o;n.setAttribute("columnWidths",JSON.stringify(c))}}}),{success:!0})}function ad(s,e){const t=qn(s);if(e<0||e>=t.rows)return;for(const r of t.cells)r.row<e&&r.row+r.rowSpan>e&&Qt(r.el,"rowSpan",r.rowSpan-1);const n=t.cells.filter(r=>r.row===e&&r.rowSpan>1).sort((r,o)=>r.col-o.col);if(n.length>0&&e+1<t.rows){const r=t.rowEls[e+1],o=t.cells.filter(l=>l.row===e+1);let a=0;for(const l of n){const c=l.el.clone();Qt(c,"rowSpan",l.rowSpan-1);const d=o.filter(g=>g.col<l.col).length+a;r.insert(d,[c]),a++}}const i=t.rowEls[e];for(let r=0;r<s.length;r++)if(s.get(r)===i){s.delete(r,1);break}}function ld(s,e,t){const n=Yn(s,e);return n?t<0||t>=n.length?{success:!1,error:`Invalid row index ${t}. Table has ${n.length} rows.`}:n.length<=1?{success:!1,error:"Cannot remove the last row from a table."}:(s.transact(()=>{ad(n,t)}),{success:!0}):{success:!1,error:`Table with ID "${e}" not found.`}}function cd(s,e,t,n,i){const r=Yn(s,e);if(!r)return{success:!1,error:`Table with ID "${e}" not found.`};const o=qn(r);if(o.rows===0)return{success:!1,error:"Table has no rows."};const a=o.cols;if(n<0||n>=a)return{success:!1,error:`Invalid reference column index ${n}. Table has ${a} columns.`};const l=t==="before"?n:n+1;return ho(o,"column",l,i)||(s.transact(()=>{for(let g=0;g<o.rows;g++){const u=l>0&&l<a&&o.occupancy[g][l-1]===o.occupancy[g][l]?o.occupancy[g][l]:void 0;if(u){u.row===g&&Qt(u.el,"colSpan",u.colSpan+1);continue}const p=i?.[g],h=fo(p),f=po(h),m=o.cells.filter(y=>y.row===g&&y.col<l).length;o.rowEls[g].insert(m,[f])}const d=r.getAttribute("columnWidths");if(d){const g=JSON.parse(d),u=100/(a+1),p=(100-u)/100,h=g.map(f=>f*p);h.splice(l,0,u),r.setAttribute("columnWidths",JSON.stringify(h))}}),{success:!0})}function dd(s,e,t,n){const i=qn(e);return ho(i,"row",t,n)||(s.transact(()=>{const o=i.cells.filter(u=>u.row<t&&u.row+u.rowSpan>t),a=new Set;for(const u of o){Qt(u.el,"rowSpan",u.rowSpan+1);for(let p=u.col;p<u.col+u.colSpan;p++)a.add(p)}const l=[];for(let u=0;u<i.cols;u++)a.has(u)||l.push(fo(n?.[u]));const c={id:Y(),children:l},d=sd(c);let g=e.length;if(t<i.rows){const u=i.rowEls[t];for(let p=0;p<e.length;p++)if(e.get(p)===u){g=p;break}}e.insert(g,[d])}),{success:!0})}function gd(s,e,t,n,i){const r=Yn(s,e);if(!r)return{success:!1,error:`Table with ID "${e}" not found.`};if(n<0||n>=r.length)return{success:!1,error:`Invalid reference row index ${n}. Table has ${r.length} rows.`};const o=r.get(0);if(!(o instanceof S.XmlElement)||o.nodeName!=="table-row")return{success:!1,error:"Table has no rows."};const a=t==="before"?n:n+1;return dd(s,r,a,i)}const mo=new Set(["com","org","net","edu","gov","mil","int","io","co","ai","app","dev","tech","cloud","software","digital","online","site","website","web","blog","biz","info","pro","company","agency","studio","media","news","shop","store","uk","de","fr","es","it","nl","be","at","ch","cx","pl","ru","cn","jp","kr","in","au","nz","ca","us","mx","br","ar","za","ie","se","no","dk","fi","pt","cz","gr","hu","ro","ua","il","ae","sg","hk","tw","id","my","ph","th","vn","tr","me","tv","cc","gg","fm","ly","to","is","im","ws","la","ac","sh","vc","xyz","top","live","space"]),bo=/^(?:mailto|tel):\S+$/i,yo=/^[^\s@/?#:]+@[^\s@/?#:]+\.[a-z]{2,}$/i;function ud(s){if(!s||s.length<4)return!1;if(bo.test(s)||yo.test(s))return!0;if(/^https?:\/\//i.test(s))try{return new URL(s),!0}catch{return!1}if(s.split(/[/?#]/,1)[0].includes("@"))return!1;if(/^www\./i.test(s))try{return new URL(`https://${s}`),!0}catch{return!1}if(!s.includes(".")||!/^[a-zA-Z0-9]/.test(s))return!1;try{const e=new URL(`https://${s}`).hostname.split(".").filter(n=>n.length>0);if(e.length<2)return!1;const t=e[e.length-1].toLowerCase();if(mo.has(t))return!0;if(e.length>=3){const n=e[e.length-2].toLowerCase();if(mo.has(n))return!0}return!1}catch{return!1}}function hd(s){return/^https?:\/\//i.test(s)||bo.test(s)?s:yo.test(s)?`mailto:${s}`:`https://${s}`}function ko(s){return s===" "||s===" "||s===`
23
- `||s==="\r"}function So(s){if(!s||s.length<4)return[];const e=[];let t=0;for(;t<s.length;){if(ko(s[t])){t++;continue}let n=t,i=t;for(;i<s.length&&!ko(s[i]);)i++;const r=s.slice(n,i);ud(r)&&e.push({url:hd(r),originalText:r,start:n,end:i}),t=i}return e}function ue(s){for(const e of s.toArray())if(e instanceof S.XmlText)return e;return null}function er(s){const e=String(s.getAttribute("id")??"");throw new fe("target_type_mismatch",`Target '${e}' is a ${s.nodeName}, not a directly editable text block. Read its contents and target a paragraph ID instead${s.nodeName==="table-cell"?", or use the table-cell editing tool":""}. No change was made.`,"target_resolution",!0,"unchanged",{targetId:e,targetType:s.nodeName})}function Ft(s){return s instanceof S.XmlElement&&s.nodeName==="header-footer"}function Nt(){throw new Error("Headers and footers have fixed left, center, and right paragraph slots. Edit or replace one existing paragraph; do not insert, remove, split, join, or change the block type of a slot.")}function fd(s,e){const t=ue(s),n=s.parent instanceof S.XmlElement&&s.parent.nodeName==="list"?s.parent.getAttribute("variant")??void 0:void 0;if(t)return[{blockId:e,yBlock:s,yText:t,blockText:pt(t),listVariant:s.nodeName==="list-item"?n:void 0}];if(s.nodeName==="list"){const o=[];for(const a of s.toArray()){if(!(a instanceof S.XmlElement)||a.nodeName!=="list-item")continue;const l=ue(a);if(!l)continue;const c=a.getAttribute("id")||e;o.push({blockId:c,yBlock:a,yText:l,blockText:pt(l),listVariant:s.getAttribute("variant")??void 0})}return o}const i=[],r=o=>{for(const a of o.toArray()){if(!(a instanceof S.XmlElement))continue;const l=ue(a);l?i.push({blockId:a.getAttribute("id")??e,yBlock:a,yText:l,blockText:pt(l)}):r(a)}};return r(s),i}function pd(s,e){const t=new Set,n=r=>{const o=r.getAttribute("id"),a=typeof o=="string"?o:"",l=ue(r);if(a&&l&&!t.has(a)){const c=e({blockId:a,yBlock:r,yText:l,blockText:pt(l)});if(t.add(a),c===!0)return!0}for(const c of r.toArray())if(c instanceof S.XmlElement&&n(c))return!0;return!1},i=zt(s);for(const r of i.toArray())if(r instanceof S.XmlElement&&n(r))return}function md(s,e,t,n=3){const i=et(t)?Kt(t):Jt(t);if(!i||/^\s*$/.test(i))return null;const r=tt(i);if(!r||/^\s*$/.test(r))return null;const o=[];let a=0,l=!1;return pd(s,c=>{if(!(c.blockId===e||!tt(c.blockText).includes(r))&&(a++,o.length<n&&o.push(c.blockId),a>n))return l=!0,!0}),a===0?null:{blockIds:o,totalMatches:a,truncated:l}}function bd(s,e,t){const n=md(s,e,t);if(!n||n.blockIds.length===0)return"";if(n.totalMatches===1)return` Did you mean block '${n.blockIds[0]}'?`;const i=n.blockIds.map(a=>`'${a}'`).join(", "),r=n.totalMatches-n.blockIds.length,o=r>0?n.truncated?` and at least ${r} more`:` and ${r} more`:"";return` This text appears in other blocks: ${i}${o}. Did you mean one of those block IDs?`}const tr=new WeakMap;function nr(s){return tr.get(s)}const ge=s=>({kind:"block",...s}),we=s=>({kind:"textMark",...s}),yd=new Set(["bold","italic","underline","strikethrough","doubleStrikethrough","smallCaps","allCaps","code","superscript","subscript"]),Io={fontSize:{integer:!0,min:1,max:512},letterSpacing:{min:-20,max:100}},kd=[ge({attr:"align",nodeNames:["paragraph","image","math","table","toc"],valueType:"string",enumValues:["left","center","right","justify"],aliases:["textAlign","text-align"]}),ge({attr:"heading",nodeNames:["paragraph"],valueType:"number",integer:!0,min:1,max:6}),ge({attr:"lineSpacing",nodeNames:["paragraph","list","list-item"],valueType:"number",min:.5,max:4,aliases:["lineHeight","line-height"]}),ge({attr:"leftIndent",nodeNames:["paragraph"],valueType:"number",integer:!0,min:0,max:20,aliases:["marginLeft","margin-left","left-indent","indent","indents"]}),ge({attr:"direction",nodeNames:["paragraph","list-item","toc"],valueType:"string",enumValues:["ltr","rtl"],aliases:["dir"]}),ge({attr:"firstLineIndent",nodeNames:["paragraph"],valueType:"number",integer:!0,min:-1,max:1,aliases:["textIndent","text-indent","first-line-indent"]}),ge({attr:"spaceBefore",nodeNames:["paragraph","list","list-item"],valueType:"number",min:0,aliases:["marginTop","margin-top"]}),ge({attr:"spaceAfter",nodeNames:["paragraph","list","list-item"],valueType:"number",min:0,aliases:["marginBottom","margin-bottom"]}),ge({attr:"width",nodeNames:["image"],valueType:"number",integer:!0,min:1}),ge({attr:"height",nodeNames:["image"],valueType:"number",integer:!0,min:1}),ge({attr:"alt",nodeNames:["image"],valueType:"string"}),ge({attr:"language",nodeNames:["code"],valueType:"string"}),ge({attr:"renderDiagram",nodeNames:["code"],valueType:"boolean"}),ge({attr:"showDiagramSource",nodeNames:["code"],valueType:"boolean"}),ge({attr:"displayMode",nodeNames:["math"],valueType:"string",enumValues:["inline","block"]}),ge({attr:"variant",nodeNames:["list"],valueType:"string",enumValues:["ordered","unordered","todo"],aliases:["listStyleType","list-style-type"]}),ge({attr:"startNumber",nodeNames:["list"],valueType:"number",integer:!0,min:1}),ge({attr:"numberingChainId",nodeNames:["list"],valueType:"string"}),ge({attr:"checked",nodeNames:["list-item"],valueType:"boolean"}),ge({attr:"indentLevel",nodeNames:["list-item"],valueType:"number",integer:!0,min:0,max:10}),ge({attr:"tableWidth",nodeNames:["table"],valueType:"number",integer:!0,min:1,aliases:["width"]}),ge({attr:"borderColor",nodeNames:["table","table-cell","container"],valueType:"string",aliases:["border-color"]}),ge({attr:"borderWidth",nodeNames:["table","table-cell"],valueType:"number",integer:!0,min:0,aliases:["border-width"]}),ge({attr:"borders",nodeNames:["table","table-cell"],valueType:"string",aliases:["border"]}),ge({attr:"cellPadding",nodeNames:["table"],valueType:"number",integer:!0,min:0,aliases:["cell-padding","padding"]}),ge({attr:"hasHeader",nodeNames:["table"],valueType:"boolean"}),ge({attr:"verticalAlign",nodeNames:["table-cell"],valueType:"string",enumValues:["top","middle","bottom"],aliases:["vertical-align"]}),ge({attr:"backgroundColor",nodeNames:["table-cell"],valueType:"string",aliases:["background-color","background","highlightColor","highlight-color"]}),ge({attr:"padding",nodeNames:["container","table-cell"],valueType:"number",integer:!0,min:0}),we({attr:"bold",valueType:"boolean",aliases:["fontWeight","font-weight"]}),we({attr:"italic",valueType:"boolean",aliases:["fontStyle","font-style"]}),we({attr:"underline",valueType:"boolean",aliases:["textDecoration","text-decoration"]}),we({attr:"strikethrough",valueType:"boolean",aliases:["strike","line-through"]}),we({attr:"doubleStrikethrough",valueType:"boolean",aliases:["double-strikethrough","double-strike","dstrike"]}),we({attr:"smallCaps",valueType:"boolean",aliases:["small-caps","fontVariant","font-variant"]}),we({attr:"allCaps",valueType:"boolean",aliases:["all-caps","caps"]}),we({attr:"letterSpacing",valueType:"number",min:-20,max:100,aliases:["letter-spacing","characterSpacing","character-spacing"]}),we({attr:"code",valueType:"boolean"}),we({attr:"superscript",valueType:"boolean"}),we({attr:"subscript",valueType:"boolean"}),we({attr:"fontSize",valueType:"number",integer:!0,min:1,max:512,aliases:["font-size"]}),we({attr:"fontFamily",valueType:"string",aliases:["font-family"]}),we({attr:"backgroundColor",valueType:"string",aliases:["background-color","background","highlightColor","highlight-color"]}),we({attr:"color",valueType:"string"}),we({attr:"link",valueType:"string",aliases:["href"]})],ir=new Map,vo=(s,e)=>{const t=s.toLowerCase(),n=ir.get(t)??[];n.push(e),ir.set(t,n)};for(const s of kd){vo(s.attr,s);for(const e of s.aliases??[])vo(e,s)}const xo={align:{nodeNames:["paragraph","image","math","table","toc"],valueType:"string",enumValues:["left","center","right","justify"]},heading:{nodeNames:["paragraph"],valueType:"number",integer:!0,min:1,max:6},lineSpacing:{nodeNames:["paragraph","list","list-item"],valueType:"number",min:.5,max:4},leftIndent:{nodeNames:["paragraph"],valueType:"number",integer:!0,min:0,max:20},direction:{nodeNames:["paragraph","list-item","toc"],valueType:"string",enumValues:["ltr","rtl"]},firstLineIndent:{nodeNames:["paragraph"],valueType:"number",integer:!0,min:-1,max:1},spaceBefore:{nodeNames:["paragraph","list","list-item"],valueType:"number",min:0},spaceAfter:{nodeNames:["paragraph","list","list-item"],valueType:"number",min:0},width:{nodeNames:["image"],valueType:"number",integer:!0,min:1},height:{nodeNames:["image"],valueType:"number",integer:!0,min:1},alt:{nodeNames:["image"],valueType:"string"},src:{nodeNames:["image"],valueType:"string"},language:{nodeNames:["code"],valueType:"string"},renderDiagram:{nodeNames:["code"],valueType:"boolean"},showDiagramSource:{nodeNames:["code"],valueType:"boolean"},displayMode:{nodeNames:["math"],valueType:"string",enumValues:["inline","block"]},variant:{nodeNames:["list"],valueType:"string",enumValues:["ordered","unordered","todo"]},startNumber:{nodeNames:["list"],valueType:"number",integer:!0,min:1},numberingChainId:{nodeNames:["list"],valueType:"string"},checked:{nodeNames:["list-item"],valueType:"boolean"},indentLevel:{nodeNames:["list-item"],valueType:"number",integer:!0,min:0,max:10},tableWidth:{nodeNames:["table"],valueType:"number",integer:!0,min:1},borderColor:{nodeNames:["table","table-cell","container"],valueType:"string"},borderWidth:{nodeNames:["table","table-cell"],valueType:"number",integer:!0,min:0},borders:{nodeNames:["table","table-cell"],valueType:"string"},cellPadding:{nodeNames:["table"],valueType:"number",integer:!0,min:0},hasHeader:{nodeNames:["table"],valueType:"boolean"},verticalAlign:{nodeNames:["table-cell"],valueType:"string",enumValues:["top","middle","bottom"]},backgroundColor:{nodeNames:["table-cell"],valueType:"string"},padding:{nodeNames:["container","table-cell"],valueType:"number",integer:!0,min:0}};function pt(s){const e=Z(s);let t="";for(const n of e)n.insert&&typeof n.insert=="string"&&(t+=n.insert);return t}function Ao(s,e,t){if(pt(e).length===0)return!!kt(s.getAttribute("_emptyTextMarks"))[t];const n=Z(e);for(const i of n)if(!(!i.insert||typeof i.insert!="string"||i.insert.length===0)&&(i.attributes||{})[t]!==!0)return!1;return!0}function Sd(s,e,t){const n=kt(s.getAttribute("_emptyTextMarks"));t?n[e]=!0:delete n[e],Object.keys(n).length===0?s.removeAttribute("_emptyTextMarks"):s.setAttribute("_emptyTextMarks",JSON.stringify(n))}function Jn(s,e,t){if(t>0)return;const n=e.children.find(i=>i.type==="text"&&i.text===""&&Object.keys(i.marks??{}).length>0);n?.marks&&s.setAttribute("_emptyTextMarks",JSON.stringify(n.marks))}function wo(s,e,t){const n=kt(s.getAttribute("_emptyTextMarks"));t==null?delete n[e]:n[e]=t,Object.keys(n).length===0?s.removeAttribute("_emptyTextMarks"):s.setAttribute("_emptyTextMarks",JSON.stringify(n))}function Id(s,e,t){const n=Lt(s,e);if(!Number.isFinite(n))throw new Error(`set_block_attribute "${s}" expects a number.`);if(t.integer&&!Number.isInteger(n))throw new Error(`set_block_attribute "${s}" expects an integer value.`);if(t.min!==void 0&&n<t.min)throw new Error(`set_block_attribute "${s}" must be >= ${t.min}.`);if(t.max!==void 0&&n>t.max)throw new Error(`set_block_attribute "${s}" must be <= ${t.max}.`);return n}function vd(s){if(s==null)return"set";if(s==="set"||s==="toggle"||s==="remove")return s;throw new Error('set_block_attribute operation must be one of "set", "toggle", or "remove".')}function To(s,e){let t=Array.isArray(e)?e:[e];if(typeof e=="string"){const r=e.trim();if(r.startsWith("[")&&r.endsWith("]"))try{const o=JSON.parse(r);Array.isArray(o)&&(t=o)}catch{}}const n=[],i=new Set;for(const r of t){if(typeof r!="string"||r.trim().length===0)throw new Error(`${s} requires a valid block ID or a non-empty list of block IDs.`);const o=r.trim();i.has(o)||(i.add(o),n.push(o))}if(n.length===0)throw new Error(`${s} requires a valid block ID or a non-empty list of block IDs.`);return n}function Co(s){if(s===!0||s===!1)return s;if(typeof s=="string"){const e=s.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return!1}function Po(s,e,t){if(t.valueType==="string"){if(typeof e!="string")throw new Error(`set_block_attribute "${s}" expects a string value.`);if(t.enumValues&&!t.enumValues.includes(e))throw new Error(`set_block_attribute "${s}" must be one of: ${t.enumValues.join(", ")}.`);return e}if(t.valueType==="boolean"){if(typeof e!="boolean")throw new Error(`set_block_attribute "${s}" expects a boolean value.`);return String(e)}const n=Lt(s,e);if(!Number.isFinite(n))throw new Error(`set_block_attribute "${s}" expects a number.`);if(t.integer&&!Number.isInteger(n))throw new Error(`set_block_attribute "${s}" expects an integer value.`);if(t.min!==void 0&&n<t.min)throw new Error(`set_block_attribute "${s}" must be >= ${t.min}.`);if(t.max!==void 0&&n>t.max)throw new Error(`set_block_attribute "${s}" must be <= ${t.max}.`);return String(n)}function rr(s,e,t){if(t===void 0){J(s,e);return}s.setAttribute(e,String(t))}function Bo(s,e,t){if(e==="toggle")throw new Error('set_block_attribute "indentLevel" does not support toggle. Use operation "set" with a numeric value or "remove".');const n=e==="remove"?0:Number(Po("indentLevel",t,{valueType:"number",integer:!0,min:0,max:20})),i=n>0?De(1):void 0,r=n>1?Re(n-1):void 0;rr(s,"firstLineIndent",i),rr(s,"leftIndent",r)}function Mo(s,e,t){if(t===null){J(s,e);return}const n=e==="leftIndent"?Re(t):De(t);rr(s,e,n)}function Lt(s,e){if(typeof e=="number")return e;if(typeof e!="string")return Number.NaN;const t=e.trim();if(!t)return Number.NaN;const n=t.toLowerCase();if(s==="leftIndent"||s==="firstLineIndent"){const o=Ai(t,{firstLine:s==="firstLineIndent"});if(o!==void 0)return o}const i=n.match(/^(-?\d+(?:\.\d+)?)(px|pt|in|cm|mm)$/);if(i){const o=Number(i[1]),a=i[2],l={px:1,pt:4/3,in:96,cm:96/2.54,mm:96/25.4};return o*l[a]}if(s==="heading"){const o=n.match(/^h([1-6])$/);if(o)return Number(o[1])}if(s==="lineSpacing"){const o={single:1,"1x":1,"1.0x":1,one:1,double:2,"2x":2,"2.0x":2,onehalf:1.5,"one-half":1.5,"one and a half":1.5,"one-and-a-half":1.5,"1.5x":1.5};if(o[n]!==void 0)return o[n]}const r=Number(t);return Number.isFinite(r)?r:Number.NaN}function nt(s,e,t){const n=pt(t);s.push({kind:"replace",paragraphId:e,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(t,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(t,n.length,0)),text:n,oldText:n})}function Te(s){const e=s.getAttribute("id");return typeof e=="string"&&e.length>0?e:s.nodeName}function Kn(s){return ir.get(s.trim().toLowerCase())??[]}function mt(s,e,t,n){if(typeof t!="string")throw new Error(`${s} "${e}" expects a string value.`);const i=t.trim();if(i.length===0)throw new Error(`${s} "${e}" expects a non-empty string.`);if(/[<>;]/.test(i))throw new Error(`${s} "${e}" contains unsupported characters.`);if(e==="fontFamily"&&xd(i))throw new Error(`${s} "fontFamily" does not support CSS-wide values like "inherit"; use a concrete font family such as "Arial, sans-serif".`);const r=i.toLowerCase();if(n&&!n.includes(r))throw new Error(`${s} "${e}" must be one of: ${n.join(", ")}.`);return n?r:i}function xd(s){const e=s.trim().replace(/\s*!important\s*$/i,"").trim().toLowerCase();return["inherit","initial","unset","revert","revert-layer"].includes(e)}function sr(s,e,t){if(typeof t=="boolean")return t;if(typeof t=="string"){const n=t.trim().toLowerCase();if(["true","yes","on","1"].includes(n))return!0;if(["false","no","off","0","none"].includes(n))return!1}if(t===1)return!0;if(t===0)return!1;throw new Error(`${s} "${e}" expects a boolean value.`)}function Eo(s,e,t){if(typeof t!="string"&&typeof t!="number")return t;const n=s.trim().toLowerCase(),i=typeof t=="number"?String(t):t.trim().toLowerCase();if(n==="fontstyle"||n==="font-style"){if(e==="italic"){if(i==="italic"||i==="oblique")return!0;if(i==="normal")return!1}return t}if(n==="fontweight"||n==="font-weight"){if(e==="bold"){if(i==="bold"||i==="bolder")return!0;if(i==="normal"||i==="lighter")return!1;const r=Number(i);if(Number.isFinite(r))return r>=600}return t}if(n==="textdecoration"||n==="text-decoration"){if(e==="underline"){if(i.includes("underline"))return!0;if(i==="none")return!1}return t}return(n==="line-through"||n==="strike")&&e==="strikethrough"?i!=="false"&&i!=="none":t}function Ot(s,e,t,n){const i=Lt(e,t);if(!Number.isFinite(i))throw new Error(`${s} "${e}" expects a number.`);const r=n.integer?Math.round(i):i;if(n.min!==void 0&&r<n.min)throw new Error(`${s} "${e}" must be >= ${n.min}.`);if(n.max!==void 0&&r>n.max)throw new Error(`${s} "${e}" must be <= ${n.max}.`);return r}function Be(s,e,t,n){const i=Te(e);if(t){nt(s,i,t);return}const r=`Updated ${n} on ${e.nodeName} block.`;s.push({kind:"replace",paragraphId:i,text:r,oldText:r})}function Vn(s,e){const t=s.parent;if(s.nodeName!=="paragraph"||!(t instanceof S.XmlElement)||t.nodeName!=="footnote"||!s.doc)return null;const n=He(s.doc).notes?.find(i=>i.id===t.getAttribute("id"))?.children.find(i=>i.id===s.getAttribute("id"));return!n||n.type!=="paragraph"||typeof e=="string"&&n.children.length>0&&n.children.every(i=>i.marks?.fontFamily===e)?null:"Note-body fontFamily is inherited from its reference numeral. Style the reference paragraph to change the note font."}function $o(s){const{toolName:e,yBlock:t,yText:n,attribute:i,operation:r,value:o,config:a,anchors:l}=s;if(!n||t.nodeName!=="paragraph"&&t.nodeName!=="list-item")throw new Error(`${e} "${i}" only supports paragraph or list-item text blocks.`);if(r==="toggle"&&a.valueType!=="boolean")throw new Error(`${e} "${i}" does not support toggle. Use operation "set" with a value or "remove".`);let c;if(r==="remove"||o===null)c=null;else if(r==="toggle")c=!Ao(t,n,i);else if(a.valueType==="boolean")c=o===void 0?!0:sr(e,i,o);else{if(o===void 0)throw new Error(`${e} "${i}" requires a value.`);a.valueType==="number"?c=Ot(e,i,o,a):c=mt(e,i,o)}if(i==="fontFamily"){const d=Vn(t,c);if(d)throw new Error(d)}if(n.length>0)ie(n,0,n.length,{[i]:c===null?null:c}),nt(l,Te(t),n);else{wo(t,i,c);const d=`Text mark "${i}" ${c===null?"removed":"set"}.`;l.push({kind:"replace",paragraphId:Te(t),text:d,oldText:d})}}const Fo=new Set(["fontSize","fontFamily","color"]);function No(s){const{toolName:e,yBlock:t,attribute:n,operation:i,value:r,config:o,anchors:a}=s;if(!Fo.has(n))throw new Error(`${e} "${n}" cannot style a table of contents: its entries are generated from the document's headings. A table of contents supports fontSize, fontFamily, color; style the headings themselves for other text formatting.`);if(i==="toggle")throw new Error(`${e} "${n}" does not support toggle. Use operation "set" with a value or "remove".`);if(i==="remove"||r===null)t.removeAttribute(n);else{if(r===void 0)throw new Error(`${e} "${n}" requires a value.`);if(n==="fontSize"){const l=Ot(e,n,r,o);if(!Al(l))throw new Error(`${e} "fontSize" on a table of contents must be between ${wl} and ${Tl} px.`);t.setAttribute(n,String(l))}else if(n==="color"){const l=typeof r=="string"?Sn(r):void 0;if(!l)throw new Error(`${e} "color" expects a CSS color string or null.`);t.setAttribute(n,l)}else t.setAttribute(n,mt(e,n,r))}Be(a,t,null,n)}function Ad(s){const{yBlock:e}=s;if(e.nodeName==="paragraph"||e.nodeName==="list-item"){$o({...s,yText:ue(e)});return}if(e.nodeName==="toc"){No(s);return}const t=[],n=[],i=l=>{for(let c=0;c<l.length;c++){const d=l.get(c);if(d instanceof S.XmlElement&&!s.independentlySelectedTargets?.has(d)){if(d.nodeName==="paragraph"||d.nodeName==="list-item"){t.push(d);continue}if(d.nodeName==="toc"){Fo.has(s.attribute)&&n.push(d);continue}i(d)}}};if(i(e),s.attribute==="fontFamily"&&s.operation!=="toggle"){const l=s.operation==="remove"||s.value===null?null:mt(s.toolName,s.attribute,s.value);for(const c of t){const d=Vn(c,l);if(d)throw new Error(d)}}let r=0;const o=[],a=l=>{try{$o({...s,yBlock:l,yText:ue(l)}),r++}catch(c){o.push(c instanceof Error?c.message:String(c))}};for(const l of t)a(l);for(const l of n)try{No({...s,yBlock:l}),r++}catch(c){o.push(c instanceof Error?c.message:String(c))}if(r===0)throw new Error(o[0]??`${s.toolName} "${s.attribute}" found no descendant text blocks to style.`)}function wd(s){const{toolName:e,yBlock:t,ranges:n,attribute:i,operation:r,value:o,config:a,anchors:l}=s,c=ue(t);if(!c)throw new Error(`${e} inline selector matched a block without text content.`);let d;if(r==="remove"||o===null?d=null:a.valueType==="boolean"?d=sr(e,i,o):a.valueType==="number"?d=Ot(e,i,o,a):d=mt(e,i,o),i==="fontFamily"){const g=Vn(t,d);if(g)throw new Error(g)}for(const g of n)ie(c,g.start,g.length,{[i]:d===null?null:d});nt(l,Te(t),c)}function Gn(s){const{toolName:e,yBlock:t,attribute:n,operation:i,value:r,config:o,anchors:a}=s;if(!o.nodeNames.includes(t.nodeName))throw new Error(`${e} "${n}" is not valid for ${t.nodeName} blocks.`);if(n==="indentLevel"&&t.nodeName==="paragraph"){Bo(t,i,r),Be(a,t,ue(t),n);return}if(n==="padding"&&t.nodeName==="table-cell"){if(i==="remove"||r===null)J(t,n);else{const l=Ot(e,n,r,o);t.setAttribute(n,JSON.stringify({top:l,right:l,bottom:l,left:l}))}Be(a,t,null,n);return}if(n==="borders"&&(t.nodeName==="table"||t.nodeName==="table-cell")){if(i==="remove"||r===null)J(t,"borders");else{const l=mt(e,n,r),c=Cn(l);if(!c)throw new Error(`${e} "border" expects a CSS border shorthand like "1px solid #cccccc" or "none".`);const d={top:c,right:c,bottom:c,left:c};t.nodeName==="table"&&(d.insideH=c,d.insideV=c);const g=Pn(d);g&&t.setAttribute("borders",g)}Be(a,t,null,"borders");return}if(t.nodeName==="table-cell"&&(n==="borderColor"||n==="borderWidth")){if(i==="remove"||r===null)J(t,"borders");else{const l=Oi(ee(t,"borders")),c=n==="borderColor"?mt(e,n,r):Ot(e,n,r,o),d=["top","right","bottom","left"],g={};for(const p of d){const h=l?.[p]??{style:"single",width:1,color:"#cccccc"};g[p]={...h,...n==="borderColor"?{color:c}:{width:c}}}const u=Pn(g);u&&t.setAttribute("borders",u)}Be(a,t,null,"borders");return}if(i==="remove"||r===null)J(t,n);else if(i==="toggle"){if(o.valueType!=="boolean")throw new Error(`${e} "${n}" only supports toggle for boolean attributes.`);const l=Co(ee(t,n));t.setAttribute(n,String(!l))}else{if(r===void 0)throw new Error(`${e} "${n}" requires "value" when operation is "set".`);let l;o.valueType==="string"?l=mt(e,n,r,o.enumValues):o.valueType==="boolean"?l=String(sr(e,n,r)):l=String(Ot(e,n,r,o)),t.nodeName==="paragraph"&&(n==="leftIndent"||n==="firstLineIndent")?Mo(t,n,Number(l)):t.setAttribute(n,l)}Be(a,t,ue(t),n)}function Td(s){if(s.config.nodeNames.includes(s.yBlock.nodeName)){Gn(s);return}if(!(s.config.nodeNames.includes("paragraph")||s.config.nodeNames.includes("list-item"))){Gn(s);return}let e=0;const t=[],n=i=>{for(let r=0;r<i.length;r++){const o=i.get(r);if(o instanceof S.XmlElement&&!s.independentlySelectedTargets.has(o)){if(o.nodeName==="paragraph"||o.nodeName==="list-item"){try{Gn({...s,yBlock:o}),e++}catch(a){t.push(a instanceof Error?a.message:String(a))}continue}n(o)}}};if(n(s.yBlock),e===0)throw new Error(t[0]??`${s.toolName} "${s.attribute}" found no descendant text blocks to style.`)}function Cd(s){const e=[],t=n=>{n.nodeName!=="footnote"&&n.nodeName!=="header-footer"&&e.push(n);for(let i=0;i<n.length;i++){const r=n.get(i);r instanceof S.XmlElement&&t(r)}};for(const n of[zt(s),s.getXmlFragment("notes")])for(const i of n.toArray())i instanceof S.XmlElement&&t(i);return e}function or(s){switch(s.nodeName){case"paragraph":{const e=s.getAttribute("heading");return typeof e=="string"&&/^[1-6]$/.test(e)?[`h${e}`]:["p"]}case"list":return s.getAttribute("variant")==="ordered"?["ol"]:["ul"];case"list-item":return["li"];case"code":return["pre"];case"math":return["latex"];case"image":return["img"];case"table":return["table"];case"table-row":return["tr"];case"table-cell":return["td"];case"container":return["div"];default:return[s.nodeName]}}function Pd(s,e){const t=[],n=i=>{for(let r=0;r<i.length;r++){const o=i.get(r);o instanceof S.XmlElement&&(or(o).includes(e)&&t.push(o),n(o))}};return n(s),t}function Bd(s){const e=s.match(/^#([A-Za-z0-9_-]+)\s+([a-zA-Z][a-zA-Z0-9-]*)$/);return e?{id:e[1],tag:e[2].toLowerCase()}:null}function Zt(s){return s.toLowerCase()==="th"?"td":s.toLowerCase()}function ar(s){const e=s.match(/^(\*|[a-zA-Z][a-zA-Z0-9-]*)(?::(?:(first-child)|(last-child)|nth-child\(\s*(\d+|odd|even)\s*\)))?$/);if(!e)return null;const t=e[2]?1:e[3]?"last":e[4]==="odd"||e[4]==="even"?e[4]:e[4]?Number(e[4]):void 0;return typeof t=="number"&&t<1?null:{tag:Zt(e[1]),nthChild:t}}function en(s,e){if(e.tag!=="*"&&!or(s).includes(e.tag))return!1;if(e.nthChild===void 0)return!0;const t=s.parent;if(!(t instanceof S.XmlElement)&&!(t instanceof S.XmlFragment))return!1;const n=t.toArray().filter(r=>r instanceof S.XmlElement),i=n.indexOf(s)+1;return i===0?!1:e.nthChild==="last"?i===n.length:e.nthChild==="odd"?i%2===1:e.nthChild==="even"?i%2===0:i===e.nthChild}function Lo(s,e){if(!en(s,e[e.length-1]))return!1;let t=s.parent;for(let n=e.length-2;n>=0;n--){for(;t instanceof S.XmlElement&&!en(t,e[n]);)t=t.parent;if(!(t instanceof S.XmlElement))return!1;t=t.parent}return!0}const lr={span:"*",b:"bold",strong:"bold",i:"italic",em:"italic",u:"underline",s:"strikethrough",strike:"strikethrough",del:"strikethrough",code:"code",sup:"superscript",sub:"subscript",mark:"backgroundColor",a:"link"};function Md(s){const e=s.split(/\s+/).filter(Boolean),t=e.findIndex(i=>lr[i.toLowerCase()]!==void 0);if(t<0)return null;const n=e.slice(t).map(i=>i.toLowerCase());return n.some(i=>!lr[i])?null:{scopeSelector:t===0?"*":e.slice(0,t).join(" "),markAttributes:Array.from(new Set(n.map(i=>lr[i])))}}function Ed(s){if(s.nodeName==="paragraph"||s.nodeName==="list-item")return[s];const e=[],t=n=>{for(let i=0;i<n.length;i++){const r=n.get(i);r instanceof S.XmlElement&&(r.nodeName==="paragraph"||r.nodeName==="list-item"?e.push(r):t(r))}};return t(s),e}function $d(s,e){if(e==="*")return!0;const t=s?.[e];return e==="link"||e==="backgroundColor"?typeof t=="string"&&t.length>0:t===!0}function Fd(s,e){const t=[];let n=0;for(const i of Z(s)){if(typeof i.insert!="string")continue;const r=i.insert.length,o=i.attributes;if(r>0&&e.every(a=>$d(o,a))){const a=t[t.length-1];a&&a.start+a.length===n?a.length+=r:t.push({start:n,length:r})}n+=r}return t}function Nd(s,e){const t=[...s,...e].sort((i,r)=>i.start-r.start),n=[];for(const i of t){const r=n[n.length-1];r&&i.start<=r.start+r.length?r.length=Math.max(r.length,i.start+i.length-r.start):n.push({...i})}return n}function Ld(s){const e=Array.isArray(s)?s:[s],t=[],n=new Set;for(const i of e){if(typeof i!="string")throw new Error("style_blocks selectors must be strings.");for(const r of i.split(",")){const o=r.trim(),a=["all","document",":root"].includes(o.toLowerCase())?"*":o.replace(/\s*>\s*/g," ");a&&(n.has(a)||(n.add(a),t.push(a)))}}if(t.length===0)throw new Error("style_blocks requires at least one selector.");return t}function Oo(s,e){const t=Cd(s),n=[],i=new Set,r=[],o=[],a=l=>{const c=Te(l),d=`${l.nodeName}:${c}`;i.has(d)||(i.add(d),n.push(l))};for(const l of e){if(l==="*"){for(const m of t)a(m);continue}const c=l.match(/^(p|h[1-6]|li)\[data-style-id=(?:"([^"]+)"|'([^']+)'|([^\]]+))\]$/i);if(c){const m=Zt(c[1]),y=(c[2]??c[3]??c[4]).trim(),b=t.filter(k=>en(k,{tag:m})&&k.getAttribute("styleId")===y);b.length===0&&r.push(l);for(const k of b)a(k);continue}const d=l.match(/^#([A-Za-z0-9_-]+)\s*~\s*(\*|[a-zA-Z][a-zA-Z0-9-]*)$/);if(d){const m=K(s,d[1]),y=m?.parent;if(!m||!(y instanceof S.XmlElement)&&!(y instanceof S.XmlFragment)){r.push(l);continue}const b=y.toArray(),k=b.indexOf(m),I=Zt(d[2]),v=t.filter(x=>x.parent===y&&b.indexOf(x)>k&&en(x,{tag:I}));v.length===0&&r.push(l);for(const x of v)a(x);continue}const g=l.match(/^#([A-Za-z0-9_-]+)\s+(.+)$/);if(g){const m=K(s,g[1]);if(!m){r.push(l);continue}const y=g[2].split(/\s+/).filter(Boolean).map(ar);if(y.some(v=>v===null)){o.push(`selector "${l}" is not supported; descendants may use block tags, :first-child, and :nth-child(n).`);continue}const b=y,k=v=>{let x=v;for(;x;){if(x===m)return!0;x=x.parent}return!1},I=t.filter(v=>k(v)&&(b.length!==1||b[0].tag!=="*"||v!==m)&&Lo(v,b));I.length===0&&r.push(l);for(const v of I)a(v);continue}const u=Bd(l);if(u){if(u.tag==="span"){o.push('selector "span" is inline, not a block selector; target containing blocks with p, li, h1-h6, or #blockId.');continue}const m=K(s,u.id);if(!m){r.push(l);continue}const y=Pd(m,Zt(u.tag));if(y.length===0){r.push(l);continue}for(const b of y)a(b);continue}if(l.includes(" ")&&!l.startsWith("#")){const m=l.split(/\s+/).filter(Boolean).map(ar);if(m.some(k=>k===null)){o.push(`selector "${l}" is not supported; descendant selectors may use block tags, :first-child, and :nth-child(n).`);continue}const y=m;if(y.some(k=>k.tag==="span")){o.push(`selector "${l}" contains an inline selector; target its containing block instead.`);continue}const b=t.filter(k=>Lo(k,y));b.length===0&&r.push(l);for(const k of b)a(k);continue}if(l.startsWith("#")){const m=l.slice(1).trim();if(!m||/[\s.#:[\]>+~]/.test(m)){o.push(`selector "${l}" is not supported; use #blockId with a plain block ID.`);continue}const y=K(s,m);y?a(y):r.push(l);continue}const p=ar(l);if(p){let m=0;for(const y of t)en(y,p)&&(a(y),m+=1);m===0&&r.push(l);continue}if(!/^[a-zA-Z][a-zA-Z0-9-]*$/.test(l)){o.push(`selector "${l}" is not supported; use *, #id, or tag selectors like p, h2, li, table.`);continue}const h=Zt(l);if(h==="span"){o.push('selector "span" is inline, not a block selector; target containing blocks with p, li, h1-h6, or #blockId.');continue}let f=0;for(const m of t)or(m).includes(h)&&(a(m),f++);f===0&&r.push(l)}return{targets:n,unmatchedSelectors:r,invalidSelectorErrors:o}}function Od(s,e){const t=Ld(e),n=[],i=[];for(const c of t){const d=Md(c);d?i.push({selector:c,parsed:d}):n.push(c)}const r=n.length>0?Oo(s,n):{targets:[],unmatchedSelectors:[],invalidSelectorErrors:[]},o=new Map,a=[...r.unmatchedSelectors],l=[...r.invalidSelectorErrors];for(const{selector:c,parsed:d}of i){const g=Oo(s,[d.scopeSelector]);if(g.invalidSelectorErrors.length>0){l.push(...g.invalidSelectorErrors.map(h=>`selector "${c}": ${h}`));continue}let u=0;const p=new Set;for(const h of g.targets)for(const f of Ed(h)){const m=Te(f);if(p.has(m))continue;p.add(m);const y=ue(f);if(!y)continue;const b=Fd(y,d.markAttributes);if(b.length===0)continue;u+=b.length;const k=o.get(m);k?k.ranges=Nd(k.ranges,b):o.set(m,{yBlock:f,ranges:b})}u===0&&a.push(c)}return{targets:r.targets,inlineTargets:Array.from(o.values()),unmatchedSelectors:a,invalidSelectorErrors:l}}function bt(s){return s.trim().toLowerCase().replace(/[-_\s]/g,"")}function Rd(s){let e;if(Array.isArray(s))e=s.map((t,n)=>{if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`style_blocks attrs[${n}] must be an object.`);const i=t;if(typeof i.name!="string"||i.name.trim().length===0)throw new Error(`style_blocks attrs[${n}].name must be a string.`);return[i.name,i.value]});else if(s&&typeof s=="object")e=Object.entries(s);else throw new Error("style_blocks requires an attrs array or object.");if(e.length===0)throw new Error("style_blocks requires at least one attr.");return e.map(([t,n])=>({rawName:t,canonicalName:bt(t),value:n}))}function Dd(s){const e=[],t=[],n=new Set,i=(r,o,a)=>{const l=`${o.kind}:${o.attr}`;let c=a;if(o.kind==="textMark"&&o.attr==="color"||o.kind==="block"&&(o.attr==="borderColor"||o.attr==="backgroundColor")){if(a!==null&&typeof a!="string")throw new Error(`style_blocks "${o.attr}" expects a CSS color string or null.`);if(typeof a=="string"&&(c=Sn(a),!c))throw new Error(`style_blocks "${o.attr}" does not support ${JSON.stringify(a)}. Use a CSS named color, hex color, or CSS color function.`)}if(o.attr==="variant"&&typeof a=="string"){const g=a.trim().toLowerCase();["decimal","number","numbered","numeric","ol"].includes(g)?c="ordered":["disc","circle","square","bullet","bulleted","ul"].includes(g)?c="unordered":["check","checklist","checkbox","task"].includes(g)&&(c="todo")}const d={rawName:r,entry:o,value:c};if(n.has(l)){const g=e.findIndex(u=>`${u.entry.kind}:${u.entry.attr}`===l);g>=0&&(e[g]=d);return}n.add(l),e.push(d)};for(const{rawName:r,value:o}of s){if(r.trim().toLowerCase()==="border"){if(typeof o=="string"&&Cn(o)){for(const d of Kn("borders"))i(r,d,o);continue}const l=Kn("borderWidth"),c=Kn("borderColor");if(o===null||typeof o=="number"){for(const d of l)i(r,d,o);if(o===null)for(const d of c)i(r,d,null);continue}if(typeof o=="string"){const d=o.match(/(?:^|\s)(\d+(?:\.\d+)?)(?:px|pt)?(?:\s|$)/i),g=Array.from(o.matchAll(/(?:^|\s)(#[0-9a-f]{3,8}|rgba?\([^)]*\)|hsla?\([^)]*\)|[a-z]+)(?=\s|$)/gi)).find(u=>!["solid","dashed","dotted","double","none"].includes(u[1].toLowerCase()));if(d)for(const u of l)i(r,u,d[1]);if(g)for(const u of c)i(r,u,g[1]);if(d||g)continue}t.push(r);continue}const a=Kn(r);if(a.length===0){t.push(r);continue}for(const l of a)i(r,l,o)}return Object.assign(e,{unsupportedAttrs:t})}function Ro(s,e,t){const n=new Map;for(const r of s){const o=bt(r.rawName),a=n.get(o)??[];a.push(r),n.set(o,a)}const i=[];for(const r of n.values()){const o=r.filter(c=>c.entry.kind==="textMark"),a=r.filter(c=>c.entry.kind==="block");if(o.length===0&&a.length>1){const c=a.filter(d=>d.entry.kind==="block"&&d.entry.nodeNames.some(g=>g===e.nodeName));i.push(...c.length?c:r);continue}if(o.length===0||a.length===0){i.push(...r);continue}if(t){i.push(...o);continue}const l=a.filter(c=>c.entry.kind==="block"&&c.entry.nodeNames.some(d=>d===e.nodeName));i.push(...l.length>0?l:o)}return i}function Do(s){const e=[];for(const t of s){if(t.entry.kind!=="textMark"||t.entry.attr!=="backgroundColor"||t.value===null)continue;if(typeof t.value!="string")throw new Error(`style_blocks "backgroundColor" expects one of: ${Yt.join(", ")}.`);const n=t.value.trim(),i=_e(n);if(!i)throw new Error(`style_blocks "backgroundColor" does not support ${JSON.stringify(n)} as a text highlight. Use one of: ${Yt.join(", ")}.`);t.value=i,n.toLowerCase()!==i&&e.push(`${t.rawName}: ${n} -> ${i}`)}return e}function Rt(s,e,t,n){s[t].push(n);const i=s.issuesByRawName.get(e.canonicalName)??[];i.push(n),s.issuesByRawName.set(e.canonicalName,i)}function Qn(s,e){for(let t=s.length-1;t>=0;t--)if(s[t].canonicalName===e)return s[t]}function je(s){return typeof s=="string"?s.trim().toLowerCase():void 0}function tn(s){if(typeof s!="string")return;const e=s.trim().match(/^(-?\d+(?:\.\d+)?)%$/);if(!e)return;const t=Number(e[1]);return Number.isFinite(t)&&t>0?t:void 0}function Zn(s){return s===0?!0:typeof s=="string"&&/^[-+]?0+(?:\.0+)?(?:px|pt|in|cm|mm|%)?$/i.test(s.trim())}function _d(s){let e=s;for(;e.parent instanceof S.XmlElement;)e=e.parent;return e}function cr(s,e){const t=Te(_d(e)),n=s.children.findIndex(c=>c.id===t),i=n>=0?s.children.slice(n).find(c=>c.type==="section-break"):void 0,r=ls(s.pageLayout,i?.type==="section-break"?i.layout:void 0),{pageWidth:o}=ts(r),a=Math.max(1,o-r.marginLeftPx-r.marginRightPx),l=r.columnGapTwips/15;return Math.max(1,Math.round(Zl(a,r.columnCount,l)))}function jd(s){if(s===null)return{remove:!0};if(typeof s=="number")return!Number.isFinite(s)||s<0?null:s===0?{remove:!0}:{remove:!1,style:"single",width:s};if(typeof s!="string")return null;const e=s.trim(),t=e.toLowerCase();if(t==="none"||Zn(t))return{remove:!0};const n=e.match(/(?:^|\s)(\d+(?:\.\d+)?)(px|pt)?(?=\s|$)/i),i=t.match(/(?:^|\s)(solid|double|dashed|dotted|none)(?=\s|$)/),r=Array.from(e.matchAll(/(?:^|\s)(#[0-9a-f]{3,8}|rgba?\([^)]*\)|hsla?\([^)]*\)|[a-z]+)(?=\s|$)/gi)).find(c=>!["solid","double","dashed","dotted","none"].includes(c[1].toLowerCase()));if(!n&&!i&&!r)return null;if(i?.[1]==="none")return{remove:!0};const o=n?Number(n[1]):void 0,a=o===void 0?void 0:n?.[2]?.toLowerCase()==="pt"?o*(4/3):o,l=i?.[1];return{remove:!1,style:l==="double"||l==="dashed"||l==="dotted"?l:"single",...a!==void 0?{width:a}:{},...r?{color:r[1]}:{}}}function Xd(s){if(s.yBlock.nodeName!=="paragraph")return;const e={bordertop:"top",borderright:"right",borderbottom:"bottom",borderleft:"left"};for(const t of s.rawAttrs){const n=e[t.canonicalName];if(t.canonicalName!=="border"&&!n)continue;s.result.handledRawNames.add(t.canonicalName);const i=jd(t.value);if(!i){Rt(s.result,t,"errors",`${Te(s.yBlock)}.borders: style_blocks "${t.rawName}" expects CSS border syntax such as "1px solid #cccccc".`);continue}let r={};try{const a=JSON.parse(String(ee(s.yBlock,"borders")??"{}"));a&&typeof a=="object"&&!Array.isArray(a)&&(r=a)}catch{r={}}const o=n?[n]:["top","right","bottom","left"];if(i.remove)for(const a of o)delete r[a];else for(const a of o){const l=r[a]??{style:"single",width:1,color:"#000000"};r[a]={style:i.style??l.style,width:i.width??l.width,color:i.color??l.color}}Object.keys(r).length>0?s.yBlock.setAttribute("borders",JSON.stringify(r)):J(s.yBlock,"borders"),Be(s.anchors,s.yBlock,ue(s.yBlock),"borders"),s.result.appliedAttrs.push(`${t.rawName} -> paragraph borders`),s.result.exactMappings.push(`${t.rawName} -> paragraph borders`)}}function Ud(s){if(s.yBlock.nodeName!=="image")return;const e=x=>Qn(s.rawAttrs,x),t=e("display");t&&je(t.value)==="block"&&(s.result.handledRawNames.add(t.canonicalName),Rt(s.result,t,"ignoredAttrs",`${t.rawName}: block`));const n=e("float"),i=je(n?.value);n&&(i==="left"||i==="right")&&(s.result.handledRawNames.add(n.canonicalName),s.yBlock.setAttribute("align",i),Be(s.anchors,s.yBlock,null,"align"),s.result.appliedAttrs.push(`${n.rawName} -> align`),s.result.approximateMappings.push(`${n.rawName}: ${i} -> align: ${i} without text wrapping`));const r=e("marginleft"),o=e("marginright"),a=je(r?.value),l=je(o?.value);let c;a==="auto"&&l==="auto"?c="center":a==="auto"&&(!o||Zn(o.value))?c="right":l==="auto"&&(!r||Zn(r.value))&&(c="left"),c&&(r&&s.result.handledRawNames.add(r.canonicalName),o&&s.result.handledRawNames.add(o.canonicalName),s.yBlock.setAttribute("align",c),Be(s.anchors,s.yBlock,null,"align"),s.result.appliedAttrs.push("auto margins -> align"),s.result.exactMappings.push(`margin-left/margin-right auto -> align: ${c}`));for(const x of["margintop","marginright","marginbottom","marginleft"]){const A=e(x);!A||s.result.handledRawNames.has(A.canonicalName)||(s.result.handledRawNames.add(A.canonicalName),Zn(A.value)?Rt(s.result,A,"ignoredAttrs",`${A.rawName}: ${String(A.value)}`):Rt(s.result,A,"unsupportedImageSpacing",`${A.rawName}: ${String(A.value)}`))}const d=e("width"),g=e("maxwidth"),u=e("height"),p=je(u?.value)==="auto",h=tn(d?.value),f=tn(g?.value),m=cr(s.doc,s.yBlock),y=Math.max(1,Number(s.yBlock.getAttribute("width"))||1),b=Math.max(1,Number(s.yBlock.getAttribute("height"))||1);let k=y,I=!1,v=!1;if(h!==void 0&&d)k=Math.max(1,Math.round(m*h/100)),s.result.handledRawNames.add(d.canonicalName),I=!0,v=!0;else if(p&&d){const x=Lt("width",d.value);Number.isFinite(x)&&x>0&&(k=Math.max(1,Math.round(x)),s.result.handledRawNames.add(d.canonicalName),I=!0,v=!0)}if(f!==void 0&&g){const x=Math.max(1,Math.round(m*f/100));k=Math.min(k,x),s.result.handledRawNames.add(g.canonicalName),I=!0,s.result.approximateMappings.push(`${g.rawName}: ${String(g.value)} -> fixed ${k}px snapshot`)}if(I){s.yBlock.setAttribute("width",String(k));const x=u&&!p?Lt("height",u.value):Number.NaN,A=p||!Number.isFinite(x);if(A){const C=Math.max(1,Math.round(b*k/y));s.yBlock.setAttribute("height",String(C))}p&&u&&s.result.handledRawNames.add(u.canonicalName),Be(s.anchors,s.yBlock,null,"width/height"),s.result.appliedAttrs.push("responsive image size -> fixed snapshot"),v&&d&&s.result.approximateMappings.push(`${d.rawName}: ${String(d.value)} -> fixed ${k}px snapshot${A?" with auto height":""}`)}else p&&u&&(s.result.handledRawNames.add(u.canonicalName),Rt(s.result,u,"ignoredAttrs",`${u.rawName}: auto`))}function zd(s){if(s.yBlock.nodeName!=="table")return;const e=o=>Qn(s.rawAttrs,o),t=e("width"),n=tn(t?.value);if(t&&n!==void 0){const o=cr(s.doc,s.yBlock),a=Math.max(1,Math.round(o*n/100));s.result.handledRawNames.add(t.canonicalName),s.yBlock.setAttribute("tableWidth",String(a)),Be(s.anchors,s.yBlock,null,"tableWidth"),s.result.appliedAttrs.push("responsive table width -> fixed snapshot"),s.result.approximateMappings.push(`${t.rawName}: ${String(t.value)} -> fixed ${a}px snapshot`)}const i=e("marginleft"),r=e("marginright");je(i?.value)==="auto"&&je(r?.value)==="auto"&&(s.result.handledRawNames.add(i.canonicalName),s.result.handledRawNames.add(r.canonicalName),s.yBlock.setAttribute("align","center"),Be(s.anchors,s.yBlock,null,"align"),s.result.appliedAttrs.push("auto margins -> align"),s.result.exactMappings.push("margin-left/margin-right auto -> align: center"))}function Hd(s){if(s.yBlock.nodeName!=="paragraph")return;const e=a=>Qn(s.rawAttrs,a),t=e("breakafter"),n=e("breakbefore"),i=e("breakinside");if(!t&&!n&&!i)return;const r=new Set(String(ee(s.yBlock,"pagination")??"").split(",").filter(Boolean));t&&(s.result.handledRawNames.add(t.canonicalName),t.value===null||je(t.value)==="auto"?r.delete("keepNext"):["avoid","avoid-page"].includes(je(t.value)??"")&&r.add("keepNext"),s.result.appliedAttrs.push(`${t.rawName} -> keepNext`)),i&&(s.result.handledRawNames.add(i.canonicalName),i.value===null||je(i.value)==="auto"?r.delete("keepLines"):["avoid","avoid-page"].includes(je(i.value)??"")&&r.add("keepLines"),s.result.appliedAttrs.push(`${i.rawName} -> keepLines`)),n&&(s.result.handledRawNames.add(n.canonicalName),Rt(s.result,n,"ignoredAttrs",`${n.rawName}: ${String(n.value)}`));const o=Array.from(r).join(",");o?s.yBlock.setAttribute("pagination",o):J(s.yBlock,"pagination"),Be(s.anchors,s.yBlock,ue(s.yBlock),"pagination")}function Wd(s){const e={issuesByRawName:new Map,handledRawNames:new Set,appliedAttrs:[],exactMappings:[],approximateMappings:[],ignoredAttrs:[],unsupportedImageSpacing:[],errors:[]};return Xd({yBlock:s.yBlock,rawAttrs:s.rawAttrs,anchors:s.anchors,result:e}),Hd({...s,result:e}),Ud({...s,result:e}),zd({...s,result:e}),e}function Yd(s){const{inlineRangeCount:e,unsupportedAttrs:t,unmatchedSelectors:n,invalidSelectorErrors:i,skippedTargetErrors:r,exactCompatibilityMappings:o,approximateCompatibilityMappings:a,ignoredCompatibilityAttrs:l,unsupportedImageSpacing:c}=s,d=s.styleEffects,g=[`style_blocks ${d.outcome==="partial"?"partially applied requested styling":d.outcome==="unchanged"?"verified requested styling unchanged":"applied requested styling"}. Matched ${d.targetBlockIds.length} blocks${e?` and ${e} inline ranges`:""}; changed ${d.changedBlockIds.length} blocks.`,...d.attributes.map(u=>`${u.name}: applied to ${u.appliedBlockIds.length} targets (including already-equal values), skipped on ${new Set(u.skipped.map(p=>p.blockId)).size}.`)];if(o.length>0&&g.push(`Compatibility mappings: ${Array.from(new Set(o)).join("; ")}.`),a.length>0&&g.push(`Approximate compatibility mappings: ${Array.from(new Set(a)).join("; ")}.`),l.length>0&&g.push(`Ignored compatibility attrs: ${Array.from(new Set(l)).join(", ")}.`),c.length>0&&g.push(`Unsupported image spacing ignored: ${Array.from(new Set(c)).join(", ")}.`),n.length>0&&g.push(`Unmatched selectors: ${n.join(", ")}.`),i.length>0&&g.push(`Invalid selectors ignored: ${i.join("; ")}.`),t.length>0&&g.push(`Unsupported attrs ignored: ${t.join(", ")}.`),r.length>0){const u=Array.from(new Set(r)),p=u.slice(0,12),h=u.length-p.length;g.push(`Skipped invalid target/style pairs: ${p.join("; ")}${h>0?`; and ${h} more`:""}.`)}return g.join(" ")}function qd(s){const e=kt(s.getAttribute("_emptyTextMarks"));for(const t of $s)delete e[t];Object.keys(e).length===0?s.removeAttribute("_emptyTextMarks"):s.setAttribute("_emptyTextMarks",JSON.stringify(e))}function Jd(s,e=1){if(typeof s!="number"||!Number.isFinite(s))return e;const t=Math.floor(s);return t>=1?t:e}function Kd(s){const e=ue(s);if(e){const n=Z(e);let i="";for(const r of n)r.insert&&typeof r.insert=="string"&&(i+=r.insert);return i}const t=s.nodeName;return t==="list"?"List removed":t==="table"?"Table removed":t==="code"?"Code block removed":t==="math"?"Math block removed":t==="image"?"Image removed":"Block removed"}function _o(s,e,t){const n=Kd(s),i=ue(s),r=e&&e.length>0?e:void 0;if(i&&n.length>0){t.push({kind:"delete",paragraphId:r,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(i,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(i,n.length,0)),text:n});return}t.push({kind:"delete",paragraphId:r,text:n})}function Vd(s,e){const t=s.parent;if(!(t instanceof S.XmlElement)&&!(t instanceof S.XmlFragment)||s.nodeName!=="list")return null;const n=t.toArray().indexOf(s);if(n<0)return null;const i=[];for(const r of s.toArray()){if(!(r instanceof S.XmlElement)||r.nodeName!=="list-item")continue;const o=new S.XmlElement("paragraph");o.setAttribute("id",r.getAttribute("id")||Y());const a=ee(r,"direction");(a==="ltr"||a==="rtl")&&o.setAttribute("direction",a);for(const g of["lineSpacing","spaceBefore","spaceAfter","contextualSpacing"]){const u=ee(r,g)??ee(s,g);u!==void 0&&o.setAttribute(g,String(u))}const l=r.getAttribute("_emptyTextMarks");l&&o.setAttribute("_emptyTextMarks",l);const c=ue(r),d=new S.XmlText;c&&xl(d,Z(c)),o.insert(0,[d]),i.push(o)}if(i.length===0)return null;_o(s,s.getAttribute("id"),e),t.delete(n,1),t.insert(n,i);for(const r of i){const o=ue(r);if(!o)continue;const a=pt(o);e.push({kind:"insert",paragraphId:r.getAttribute("id"),from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(o,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(o,a.length,0)),text:a})}return i}function jo(s,e){if(e.link)return[{text:s,marks:e}];const t=So(s);if(t.length===0)return[{text:s,marks:e}];const n=[];let i=0;for(const r of t)r.start>i&&n.push({text:s.slice(i,r.start),marks:e}),n.push({text:r.originalText,marks:{...e,link:r.url}}),i=r.end;return i<s.length&&n.push({text:s.slice(i),marks:e}),n}function ei(s){return Se(cs(s,e=>!e.text||e.marks?.link?e:jo(e.text,e.marks||{}).map(t=>({type:"text",text:t.text,marks:t.marks}))))}function Xo(s,e){return qt(bc(e==="todo"?{...s,checked:s.checked??!1}:s))}function Uo(s,e,t,n=!1){return s.flatMap(i=>{if(i.type==="list")return i.children.map(r=>({...r,indentLevel:(n?0:e)+(r.indentLevel??0)}));if(i.type==="paragraph")return[{type:"list-item",id:i.id,children:i.children,direction:i.direction,lineSpacing:i.lineSpacing,spaceBefore:i.spaceBefore,spaceAfter:i.spaceAfter,indentLevel:e}];throw new Error(`Cannot put a ${i.type} inside a list item. Insert it before or after the containing list instead.`)}).map((i,r)=>({...i,id:r===0?t:i.id||Y()}))}function it(s,e,t,n){const i=jo(t,n);let r=e;for(const o of i)ne(s,r,o.text,o.marks),r+=o.text.length;return r}function zo(s,e,t){const n=s.toString(),i=t??n.length,r=n.slice(e,i),o=So(r);for(const a of o){const l=e+a.start;ie(s,l,a.end-a.start,{link:a.url})}}function dr(s,e){if(!Ht(s,e)||s.children.length!==e.children.length)return!1;for(let t=0;t<s.children.length;t++){const n=s.children[t],i=e.children[t];if(n.type!==i.type||n.type!=="text"||i.type!=="text"||n.text!==i.text||JSON.stringify(n.marks||{})!==JSON.stringify(i.marks||{}))return!1}return!0}function ti(s,e){const t=["heading","align","leftIndent","firstLineIndent","spaceBefore","spaceAfter","lineSpacing","styleId","direction","borders","shading","tabStops"];for(const i of t){const r=e[i];r===void 0?J(s,i):s.setAttribute(i,String(r))}const n=Ye(e);n===void 0?J(s,"pagination"):s.setAttribute("pagination",n)}function Gd(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++){const n=s[t],i=e[t];if(n.type!==i.type||n.text!==i.text||JSON.stringify(n.marks||{})!==JSON.stringify(i.marks||{}))return!1}return!0}function Qd(s,e){return s.type!==e.type?!1:s.type==="paragraph"&&e.type==="paragraph"?dr(s,e):Gd(s.children,e.children)}function Ho(s){return s.map(e=>({...e,marks:e.marks?{...e.marks}:void 0}))}function Wo(s,e){const t=n=>{for(const i of n){if(i.type==="paragraph"&&i.id===e)return i;if(i.type==="list"){for(const r of i.children)if(r.id===e)return r;continue}if(i.type==="container"||i.type==="table-cell"){const r=t(i.children);if(r)return r;continue}if(i.type==="table")for(const r of i.children)for(const o of r.children){const a=t(o.children);if(a)return a}}return null};return t(s.children)}function Yo(s){return s.replace(/&#0?39;|&apos;/g,"'").trim()}function Zd(s,e,t){const n=s.indexOf(e);return n===-1?s:s.slice(0,n)+t+s.slice(n+e.length)}function eg(s,e){if(e.type==="paragraph")return Yo(te.toAgentHtml({type:"doc",children:[{...e,children:Ho(e.children)}]}));if(s.listVariant==="todo")return null;const t={type:"list",id:"__agent_html_replace__",variant:s.listVariant==="ordered"?"ordered":"unordered",children:[{...e,children:Ho(e.children),indentLevel:void 0}]},n=Yo(te.toAgentHtml({type:"doc",children:[t]})).match(/^<(?:ul|ol)(?:\s[^>]*)?>([\s\S]*)<\/(?:ul|ol)>$/);return n?n[1].trim():null}function tg(s,e,t,n){try{if(t.type==="paragraph"){const o=te.fromAgentHtml(e,{existingDocument:n,replacementBlock:t});return o.children.length!==1||o.children[0].type!=="paragraph"?null:o.children[0]}if(s.listVariant==="todo")return null;const i=s.listVariant==="ordered"?"ol":"ul",r=te.fromAgentHtml(`<${i}>${e}</${i}>`,{existingDocument:n});return r.children.length!==1||r.children[0].type!=="list"||r.children[0].children.length!==1?null:r.children[0].children[0]}catch{return null}}function ng(s,e){const t=/<mark\b[^>]*\bcolor=(?:"([^"]+)"|'([^']+)')[^>]*>/i,n=s.match(t),i=e.match(t),r=n?.[1]??n?.[2],o=i?.[1]??i?.[2];if(!r||!o||r===o)return null;const a=_e(r),l=_e(o);return!a||a!==l?null:`Highlight colors ${JSON.stringify(r)} and ${JSON.stringify(o)} both resolve to ${JSON.stringify(a)}, so this replacement is a no-op. Use a different canonical highlight color: ${Yt.join(", ")}.`}function ig(s){const e=/<mark\b[^>]*\bcolor=(?:"([^"]+)"|'([^']+)')[^>]*>/gi;for(const t of s.matchAll(e)){const n=t[1]??t[2];if(n&&!_e(n))throw new Error(`Unsupported highlight color ${JSON.stringify(n)}. Use one of: ${Yt.join(", ")}.`)}}function qo(s){const e=s?.comment;return typeof e!="string"||e.length===0?[]:Array.from(new Set(e.split(",").map(t=>t.trim()).filter(Boolean))).sort()}function rt(s,e={}){const t=Object.entries(s??{}).filter(([n,i])=>i!==void 0&&(n!=="comment"||!e.ignoreComment)).map(([n,i])=>n==="comment"?[n,qo(s).join(",")]:[n,i]).filter(([,n])=>n!=="").sort(([n],[i])=>n<i?-1:n>i?1:0);return JSON.stringify(t)}function rg(s){return Object.fromEntries(Object.entries(s).sort(([e],[t])=>e<t?-1:e>t?1:0))}function ni(s){return s.flatMap(e=>{const{comment:t,...n}=e.marks??{},i=qo(e.marks);return Array.from({length:e.text.length},(r,o)=>({value:e.text[o],marks:n,comment:i}))})}function sg(s){return s.length===0?[]:s.reduce((e,t)=>e.filter(n=>t.includes(n)))}const yt=-1,gr=0,nn=1;function og(s){const e=[];for(let t=0;t<s.length;t++){const[n,i]=s[t],r=s[t+1];if(!(r!==void 0&&(n===yt&&r[0]===nn||n===nn&&r[0]===yt))){e.push([n,i]);continue}const o=n===yt?i:r[1],a=n===nn?i:r[1];let l=0;const c=Math.min(o.length,a.length);for(;l<c&&o[l]===a[l];)l++;let d=0;const g=c-l;for(;d<g&&o[o.length-1-d]===a[a.length-1-d];)d++;l>0&&e.push([gr,o.slice(0,l)]);const u=o.slice(l,o.length-d),p=a.slice(l,a.length-d);u.length>0&&e.push([yt,u]),p.length>0&&e.push([nn,p]),d>0&&e.push([gr,o.slice(o.length-d)]),t++}return e}function ag(s,e){const t=ni(s),n=ni(e),i=og(yc([],t.map(d=>d.value).join(""),n.map(d=>d.value).join(""))),r=new Array(n.length),o=new Array(n.length);let a=0,l=0;for(let d=0;d<i.length;d++){const[g,u]=i[d];if(g===gr){for(let I=0;I<u.length;I++)r[l+I]=t[a+I].comment,o[l+I]=t[a+I].marks.lang;a+=u.length,l+=u.length;continue}if(g===yt){a+=u.length;continue}if(g!==nn)continue;const p=i[d-1],h=i[d+1],f=[];p?.[0]===yt&&f.push(...t.slice(a-p[1].length,a)),h?.[0]===yt&&f.push(...t.slice(a,a+h[1].length));const m=f.length>0?f:[t[a-1],t[a]].filter(I=>!!I),y=sg(m.map(I=>I.comment)),b=m[0]?.marks.lang,k=typeof b=="string"&&m.every(I=>I.marks.lang===b)?b:void 0;for(let I=0;I<u.length;I++)r[l+I]=y,o[l+I]=k;l+=u.length}const c=[];return n.forEach((d,g)=>{const u=r[g]??[],p=rg({...d.marks,...d.marks.lang===void 0&&o[g]!==void 0?{lang:o[g]}:{},...u.length>0?{comment:u.join(",")}:{}}),h=c[c.length-1];h&&rt(h.marks)===rt(p)?h.text+=d.value:c.push({type:"text",text:d.value,...Object.keys(p).length>0?{marks:p}:{}})}),c}function lg(s,e){const t=ni(s),n=ni(e);return t.length===n.length&&t.every((i,r)=>i.value===n[r].value&&rt(i.marks)===rt(n[r].marks)&&i.comment.join(",")===n[r].comment.join(","))}function Jo(s,e,t,n,i){if(t=Bt(t),n=Bt(n),t.length===0)return null;const r=Wo(e,s.blockId);if(!r)return null;const o=eg(s,r),a=o?Bt(o):null;if(!a||!a.includes(t))return null;const l=Os(a,t).length;if(!i&&l>1)throw new Error(`Found ${l} matches for ${JSON.stringify(t)} in block '${s.blockId}' once comment-thread tags are ignored (threads don't distinguish text). Include more surrounding text so it matches exactly one location, or use replace_all.`);ig(n);const c=i?a.split(t).join(n):Zd(a,t,n);if(c===a)return null;const d=tg(s,c,r,e);if(!d)throw new Error(`Matched AgentHtml in block '${s.blockId}', but the replacement is not a supported single-block text update.`);if(d.type!==r.type)throw new Error(`Matched AgentHtml in block '${s.blockId}', but the replacement changes the block structure. Keep replace() within a single compatible text block.`);const g={...d,children:ag(r.children,Wn(r.children,d.children))};if(Qd(r,g)||lg(r.children,g.children)&&(r.type!=="paragraph"||g.type!=="paragraph"||Ht(r,g)))throw new Error(ng(t,n)??`Matched AgentHtml in block '${s.blockId}', but the replacement would not change any supported text or formatting.`);return{blockId:s.blockId,yBlock:s.yBlock,currentBlock:r,replacementBlock:g}}function ii(s,e){const t=ue(s.yBlock);if(!t)throw new Error(`Target block '${s.blockId}' has no text content to replace.`);const n=h=>h.flatMap(f=>Array.from({length:f.text.length},(m,y)=>({value:f.text[y],marks:f.marks||{}}))),i=(h,f)=>h.value===f.value&&rt(h.marks)===rt(f.marks),r=n(s.currentBlock.children),o=n(s.replacementBlock.children);let a=0;for(;a<r.length&&a<o.length&&i(r[a],o[a]);)a++;let l=0;for(;l<r.length-a&&l<o.length-a&&i(r[r.length-l-1],o[o.length-l-1]);)l++;const c=r.length-a-l,d=o.slice(a,o.length-l),g=S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(t,a,-1));c>0&&t.delete(a,c);let u=a;const p=[];for(let h=0;h<d.length;){const f=d[h].marks;let m=d[h].value;for(h++;h<d.length&&rt(d[h].marks)===rt(f);)m+=d[h].value,h++;p.push({type:"text",text:m,marks:f}),u=it(t,u,m,f)}s.currentBlock.type==="paragraph"&&s.replacementBlock.type==="paragraph"&&(s.replacementBlock.heading?s.yBlock.setAttribute("heading",String(s.replacementBlock.heading)):s.yBlock.removeAttribute("heading"),s.replacementBlock.align?s.yBlock.setAttribute("align",s.replacementBlock.align):J(s.yBlock,"align")),e.push({kind:"replace",paragraphId:s.blockId,previewStartOffset:a,sourceFrom:g,previewTextNodes:p,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(t,a,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(t,u,0)),text:d.map(h=>h.value).join(""),oldText:r.slice(a,r.length-l).map(h=>h.value).join("")})}function We(s,e,t,n){const i=[];ve(e,{verifiedUnchanged:!1,styleEffects:void 0}),tr.delete(e);const r=e.name;n&&r!=="insert_block"&&(n.lastInsertedBlock=void 0);const o=e.arguments;if(r==="replace_many"||r==="replace"&&Array.isArray(o?.replacements)){const a=Qi({...e,id:t??"replacement-batch"},{doc:He(s),loadedBlockIds:null});if(a.error){const d=a.failure;throw new fe(d?.code??"invalid_arguments",a.error,d?.phase??"validation",d?.retryable,d?.mutationOutcome,d?.details)}let l=n,c=!0;for(const d of a.actions){const g=d,u=We(s,g,t,l);if(c=c&&!!Me(g)?.verifiedUnchanged,i.push(...u),!l){const p=He(s);l={document:p,htmlParsingContext:te.createParsingContext(p),refreshDocumentIncrementally:!0}}}return ve(e,{verifiedUnchanged:c}),i}switch(e.name){case"move_blocks":throw new fe("move_requires_live_session","move_blocks must execute through the tracked-move session operation, not the generic replacement planner.");case"insert_block":{const{referenceId:a,position:l,content:c}=e.arguments;if(typeof a!="string"||!a.trim())throw new Error("insert_block referenceId is required. Resolve blank-document anchors before applying the action.");const d=Hn(e),g=n?.document??he(s);if(!Array.isArray(c))throw new Error("insert_block content must be an array");if(c.length!==1)throw new Error("insert_block should only receive a single block after preprocessing. Got array with "+c.length+" items");const u=c[0];let p,h;if(a===Gt)p=zt(s),h=p.length;else if(n?.lastInsertedBlock&&n.lastInsertedBlock.id===a)p=n.lastInsertedBlock.yParent,h=l==="before"?n.lastInsertedBlock.index:n.lastInsertedBlock.index+1;else{const k=G(s,a);if(!k)throw new Error(`Reference block '${a}' not found in the current document. Read the document again and use a current block ID.`);p=k.yParent,h=l==="before"?k.index:k.index+1}if((Ft(p)||p===s.getXmlFragment("chrome"))&&Nt(),p instanceof S.XmlElement&&(p.nodeName==="table"||p.nodeName==="table-row"))throw new Error("insert_block cannot insert beside a table row or cell. Use a paragraph ID inside the cell to insert cell content, the table ID to insert beside the table, or insert_table_row / insert_table_column to change the table structure.");let f;const m=n?.lastInsertedBlock;if(m?.yParent===p&&m.index===h-1)f=m.block;else if(h>0){const k=p.get(h-1);if(k instanceof S.XmlElement){const I=k.getAttribute("id");I&&(f=n?.lastInsertedBlock?.id===I?n.lastInsertedBlock.block:z(g,I)??void 0)}}let y;if(u.includes("<")&&u.includes(">")?y=te.fromAgentHtml(u,{previousBlock:f,existingDocument:g,parsingContext:n?.htmlParsingContext,listItemBaseIndent:p instanceof S.XmlElement&&p.nodeName==="list"?Number(K(s,a)?.getAttribute("indentLevel")??0):void 0}):y=te.fromAgentHtml(`<p>${u}</p>`,{previousBlock:f,existingDocument:g,parsingContext:n?.htmlParsingContext,listItemBaseIndent:p instanceof S.XmlElement&&p.nodeName==="list"?Number(K(s,a)?.getAttribute("indentLevel")??0):void 0}),y.children.length!==1)throw new Error(`insert_block should produce exactly one block. Got ${y.children.length} blocks from content: ${u}`);const b=y.children[0];if(!d)throw new Error("insert_block must have stableId set by preprocessor");if(b.id=d,p instanceof S.XmlElement&&p.nodeName==="list"){const k=K(s,a),I=Uo([b],Number(k?.getAttribute("indentLevel")??0),d,!0);p.insert(h,I.map(v=>Se(v))),i.push({kind:"insert",paragraphId:p.getAttribute("id"),text:I.map(v=>v.children.map(x=>x.text).join("")).join(`
24
- `)});break}if(b.type==="paragraph"){const k=b,I=new S.XmlElement("paragraph");I.setAttribute("id",d),ti(I,k);const v=new S.XmlText;let x=0;k.children.forEach(C=>{if(C.type==="text"){const F=C;x=it(v,x,F.text,F.marks||{})}}),Jn(I,k,x),I.insert(0,[v]),p.insert(h,[I]);const A=k.children.filter(C=>C.type==="text").map(C=>C.text).join("");i.push({kind:"insert",paragraphId:d,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(v,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(v,A.length,0)),text:A})}else if(b.type==="list"){const k=ei(b);p.insert(h,[k]);const I=[];for(const v of k.toArray()){if(!(v instanceof S.XmlElement))continue;const x=ae(v);if(!x)continue;const A=Z(x).map(C=>typeof C.insert=="string"?C.insert:"").join("");A.length&&I.push({yText:x,plainText:A})}I.forEach(({yText:v,plainText:x})=>{i.push({kind:"insert",paragraphId:d,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(v,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(v,x.length,0)),text:x})})}else if(b.type==="table"){const k=ei({...b,id:d});p.insert(h,[k]),i.push({kind:"insert",paragraphId:d,text:"Table inserted"})}else if(b.type==="code"){const k=b,I=new S.XmlElement("code");I.setAttribute("id",d),k.language&&I.setAttribute("language",k.language),k.renderDiagram!==void 0&&I.setAttribute("renderDiagram",String(k.renderDiagram)),k.showDiagramSource!==void 0&&I.setAttribute("showDiagramSource",String(k.showDiagramSource));const v=new S.XmlText;I.insert(0,[v]),ne(v,0,k.content||""),p.insert(h,[I]),i.push({kind:"insert",paragraphId:d,text:"Code block inserted"})}else if(b.type==="math"){const k=b,I=new S.XmlElement("math");I.setAttribute("id",d),k.displayMode&&I.setAttribute("displayMode",k.displayMode),k.align&&I.setAttribute("align",k.align);const v=new S.XmlText;I.insert(0,[v]),ne(v,0,k.content||""),p.insert(h,[I]),i.push({kind:"insert",paragraphId:d,text:"Math block inserted"})}else if(b.type==="page-break"){const k=new S.XmlElement("page-break");k.setAttribute("id",d),p.insert(h,[k]),i.push({kind:"insert",paragraphId:d,text:"Page break inserted"})}else if(b.type==="toc"){const k=Se({...b,id:d});p.insert(h,[k]),i.push({kind:"insert",paragraphId:d,text:"Table of contents inserted"})}else if(b.type==="image"){const k=b,I=new S.XmlElement("image");I.setAttribute("id",d),I.setAttribute("src",k.src),k.sourceUrl&&I.setAttribute("sourceUrl",k.sourceUrl),I.setAttribute("width",String(k.width)),I.setAttribute("height",String(k.height)),k.alt&&I.setAttribute("alt",k.alt),k.align&&I.setAttribute("align",k.align),p.insert(h,[I]),i.push({kind:"insert",paragraphId:d,text:"Image inserted"})}else throw new Error(`insert_block expected a paragraph, list, table, code, math, image, table-of-contents, or page-break block but got ${b.type}`);n&&(n.lastInsertedBlock={id:d,yParent:p,index:h,block:b},p===s.getXmlFragment("content")?n.document.children.splice(h,0,b):(n.document=he(s),n.htmlParsingContext=te.createParsingContext(n.document)));break}case"replace":case"replace_all":{const{id:a}=e.arguments;let{find:l,replace:c}=e.arguments;const d=n?.document??he(s),g=K(s,a);if(!g)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);let u=fd(g,a);const p=Ys(Wo(d,a)??z(d,a),l);if(p&&(u=u.filter(y=>p.has(y.blockId))),p&&u.length===0)throw new fe("target_stale","HTML matcher identities no longer resolve to editable text within this target. Read the target again.","target_resolution");if(u.length===0)break;if(l.length===0){if(u.length!==1||u[0].blockText.length!==0)throw new Error(`An empty find may only fill one truly empty text block; block '${a}' is not an unambiguous empty target.`);const y=u[0];hr(y.yText,0,0,l,c,y.blockId,i,kt(y.yBlock.getAttribute("_emptyTextMarks")));break}const h=y=>u.map(b=>({...b,matches:ea(b.blockText,y)})).filter(b=>b.matches.length>0);if(et(l)){const y=u.map(b=>Jo(b,d,l,c,e.name==="replace_all")).filter(b=>b!==null);if(y.length>0){if(e.name==="replace"&&y.length>1)throw new Error(`Found ${y.length} exact AgentHtml matches for "${l}" in block '${a}'. Include more surrounding AgentHtml so it matches exactly one location, or use replace_all.`);if(e.name==="replace")ii(y[0],i);else for(const b of y)ii(b,i);break}}let f=h(l);if(f.length===0){const y=Qo(l);if(y!==l&&y.trim()!==""){const b=h(y);b.length>0&&(l=y,c=Qo(c),f=b)}}if(f.length===0){const y=u.map(x=>Jo(x,d,l,c,e.name==="replace_all")).filter(x=>x!==null);if(y.length>0){if(e.name==="replace")ii(y[0],i);else for(const x of y)ii(x,i);break}const b=u.map(x=>x.blockText).join(`
25
- `),k=b.length>100?b.slice(0,100)+"...":b,I=bd(s,a,l),v=/(?:\*\*|__|^>|^#{1,6}\s|^[-*+]\s|^\d+[.)]\s|\|)/m.test(l)?" The requested find contains Markdown syntax, while this preview is stored plain text; formatting markers are not literal characters.":"";throw l.includes("<")&&l.includes(">")?new fe("text_not_found",`No match found for "${l}" in block '${a}'. The block's stored plain text begins ${JSON.stringify(k)}. If you're matching AgentHtml from the document context, the snippet must match the exact block HTML.${I}`,"matching"):new fe("text_not_found",`No match found for "${l}" in block '${a}'. The block's stored plain text begins ${JSON.stringify(k)}.${v} Make sure the text you're searching for exists exactly as written (case-sensitive, including punctuation and spaces).${I}`,"matching")}const m=f.reduce((y,b)=>y+b.matches.length,0);if((e.name==="replace_all"||m===1)&&f.every(y=>y.matches.every(b=>Vo(y.yText,b.offset,b.length,l,c)))){ve(e,{verifiedUnchanged:!0});break}if(e.name==="replace"){const y=f.reduce((I,v)=>I+v.matches.length,0);if(y>1)throw new Error(`Found ${y} matches for "${l}" in block '${a}'. Include more surrounding context in "find" so it matches exactly one location, or use replace_all to change every occurrence.`);const b=f[0],k=b.matches[0];hr(b.yText,k.offset,k.length,l,c,b.blockId,i)}else for(const y of f){let b=-1;y.matches=y.matches.filter(k=>k.offset<b?!1:(b=k.offset+k.length,!0));for(let k=y.matches.length-1;k>=0;k--){const I=y.matches[k];hr(y.yText,I.offset,I.length,l,c,y.blockId,i)}}break}case"replace_block":{const{id:a,content:l,count:c}=e.arguments;if(c!==void 0&&(!Number.isFinite(c)||Math.floor(c)<1))throw new Error("replace_block count must be a positive integer.");const d=Jd(c,1),g=n?.document??he(s),u=z(g,a);if(!u){const I=g.children.map(v=>v.id).filter(v=>v).slice(0,10);throw console.error(`[ForkActionApplicator] Block with id '${a}' not found. Available IDs:`,I),new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`)}const p=G(s,a);if(!p)throw new Error(`Y.js block not found for id: ${a}`);const{yBlock:h,yParent:f,index:m}=p,y=Ft(f);if((h.nodeName==="header-footer"||y&&d!==1)&&Nt(),d>1){const I=Math.max(0,f.length-(m+1)),v=Math.min(d-1,I);for(let x=0;x<v;x++){const A=f.get(m+1);if(!(A instanceof S.XmlElement))break;const C=A.getAttribute("id");_o(A,C??void 0,i),f.delete(m+1,1)}}const b=Wt(g,a),k=b>0?g.children[b-1]:void 0;{const I=(Array.isArray(l)?l:[l]).join(""),v=te.fromAgentHtml(I,{previousBlock:k,replacementBlock:u,existingDocument:g,listItemBaseIndent:h.nodeName==="list-item"?Number(h.getAttribute("indentLevel")??0):void 0});if(y&&(v.children.length!==1||v.children[0].type!=="paragraph")&&Nt(),h.nodeName==="list-item"&&f instanceof S.XmlElement&&f.nodeName==="list"){const x=Uo(v.children,Number(h.getAttribute("indentLevel")??0),a,!0);if(d===1&&x.length===1&&u.type==="list"){const A=u.children.find(C=>C.id===a);if(u.variant==="todo"&&x[0].checked===void 0&&A?.checked!==void 0&&(x[0].checked=A.checked),x[0].children=Wn(A?.children??[],x[0].children),A&&Xo(A,u.variant)===Xo(x[0],u.variant)){ve(e,{verifiedUnchanged:!0});break}}f.delete(m,1),f.insert(m,x.map(A=>Se(A))),i.push({kind:"replace",paragraphId:f.getAttribute("id"),oldText:"List item",text:x.map(A=>A.children.map(C=>C.text).join("")).join(`
26
- `)});break}if(u.type==="paragraph"){const x=C=>C.children.filter(F=>!F.marks?.footnoteRef),A=te.extractUniformTextFontFamily(x(u));if(A){for(const C of v.children)if(C.type==="paragraph"&&te.extractUniformTextFontFamily(x(C)))for(const F of x(C))F.marks={...F.marks,fontFamily:A}}}if(v.children.length>0)if(v.children.length===1){const x=v.children[0];if(d===1&&(u.type==="paragraph"||u.type==="list")&&x.type===u.type){if(u.type==="paragraph"&&x.type==="paragraph")x.children=Wn(u.children,x.children);else if(u.type==="list"&&x.type==="list"){const L=new Map(u.children.map($=>[$.id,$])),_=u.children.length===x.children.length&&x.children.every(($,R)=>$.children.map(M=>M.text).join("")===u.children[R].children.map(M=>M.text).join(""));x.children=x.children.map(($,R)=>({...$,children:Wn((L.get($.id)??(_?u.children[R]:void 0))?.children??[],$.children)}))}const w=L=>Array.isArray(L)?L.map(w):L&&typeof L=="object"?Object.fromEntries(Object.entries(L).filter(([_,$])=>_!=="id"&&$!==void 0&&!(_==="marks"&&Object.keys($).length===0)).sort(([_],[$])=>_.localeCompare($)).map(([_,$])=>[_,w($)])):L,T=L=>JSON.stringify(w(L)),N=L=>te.toInternalHtml({type:"doc",children:[w(L)]});if(T(u)===T(x)||N(u)===N(x)){ve(e,{verifiedUnchanged:!0});break}}if(!(h instanceof S.XmlElement))break;if(x.type==="list"){f.delete(m,1);const w=ei({...x,id:a});f.insert(m,[w]);const T=u.type==="list"?"List":"Paragraph";i.push({kind:"replace",paragraphId:a,text:"List replaced",oldText:T});break}if(x.type==="table"){const w=x;f.delete(m,1);const T=ei({...w,id:a});f.insert(m,[T]);const N=u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";i.push({kind:"replace",paragraphId:a,text:"Table replaced",oldText:N});break}if(x.type==="code"){const w=x;f.delete(m,1);const T=new S.XmlElement("code");T.setAttribute("id",a),w.language&&T.setAttribute("language",w.language),w.renderDiagram!==void 0&&T.setAttribute("renderDiagram",String(w.renderDiagram)),w.showDiagramSource!==void 0&&T.setAttribute("showDiagramSource",String(w.showDiagramSource));const N=new S.XmlText;T.insert(0,[N]),ne(N,0,w.content||""),f.insert(m,[T]);const L=u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";i.push({kind:"replace",paragraphId:a,text:"Code block replaced",oldText:L});break}if(x.type==="math"){const w=x;f.delete(m,1);const T=new S.XmlElement("math");T.setAttribute("id",a),w.displayMode&&T.setAttribute("displayMode",w.displayMode),w.align&&T.setAttribute("align",w.align);const N=new S.XmlText;T.insert(0,[N]),ne(N,0,w.content||""),f.insert(m,[T]);const L=u.type==="math"?"Math block":u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";i.push({kind:"replace",paragraphId:a,text:"Math block replaced",oldText:L});break}if(x.type==="page-break"){f.delete(m,1);const w=new S.XmlElement("page-break");w.setAttribute("id",a),f.insert(m,[w]);const T=u.type==="image"?"Image":u.type==="math"?"Math block":u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";i.push({kind:"replace",paragraphId:a,text:"Page break replaced",oldText:T});break}if(x.type==="toc"){f.delete(m,1);const w=Se({...x,id:a});f.insert(m,[w]),i.push({kind:"replace",paragraphId:a,text:"Table of contents replaced",oldText:"Block"});break}if(x.type==="image"){const w=x;f.delete(m,1);const T=new S.XmlElement("image");T.setAttribute("id",a),T.setAttribute("src",w.src),w.sourceUrl&&T.setAttribute("sourceUrl",w.sourceUrl),T.setAttribute("width",String(w.width)),T.setAttribute("height",String(w.height)),w.alt&&T.setAttribute("alt",w.alt),w.align&&T.setAttribute("align",w.align),f.insert(m,[T]);const N=u.type==="image"?"Image":u.type==="math"?"Math block":u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";i.push({kind:"replace",paragraphId:a,text:"Image replaced",oldText:N});break}if((u.type==="math"||u.type==="code")&&x.type==="paragraph"){f.delete(m,1);const w=new S.XmlElement("paragraph");w.setAttribute("id",a),ti(w,x);const T=new S.XmlText;let N=0;for(const L of x.children)L.type==="text"&&(N=it(T,N,L.text,L.marks||{}));Jn(w,x,N),w.insert(0,[T]),f.insert(m,[w]),i.push({kind:"replace",paragraphId:a,text:x.children.filter(L=>L.type==="text").map(L=>L.text).join(""),oldText:u.type==="code"?"Code block":"Math block"});break}if((u.type==="list"||u.type==="table")&&x.type==="paragraph"){f.delete(m,1);const w=new S.XmlElement("paragraph");w.setAttribute("id",a),ti(w,x);const T=new S.XmlText;let N=0;for(const L of x.children)L.type==="text"&&(N=it(T,N,L.text,L.marks||{}));Jn(w,x,N),w.insert(0,[T]),f.insert(m,[w]),i.push({kind:"replace",paragraphId:a,text:x.children.filter(L=>L.type==="text").map(L=>L.text).join(""),oldText:u.type==="table"?"Table":"List"});break}const A=ue(h);A||er(h);const C=u.type==="paragraph"?u:null,F=A.length,E=v.children[0],P=C!==null&&dr(C,E);let B=0;if(!P){if(F>0&&A.delete(0,F),E.children.length>0){for(const w of E.children)if(w.type==="text"){const T=w;B=it(A,B,T.text,T.marks||{})}}ti(h,E)}if(!P){const w=u.type==="paragraph"?u.children.filter(T=>T.type==="text").map(T=>T.text).join(""):"";i.push({kind:"replace",paragraphId:a,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,B,0)),text:E.children.filter(T=>T.type==="text").map(T=>T.text).join(""),oldText:w})}}else{if(!(h instanceof S.XmlElement))throw new fe("target_type_mismatch","Target is not an editable block. Read the current document and target a paragraph ID.","target_resolution");const x=ue(h);x||er(h);const A=u.type==="paragraph"?u:null,C=x.length,F=u.type==="paragraph"?u.children.filter(T=>T.type==="text").map(T=>T.text).join(""):"",E=v.children[0],P=A!==null&&dr(A,E);let B=0;if(!P){if(C>0&&x.delete(0,C),E.children.length>0){for(const T of E.children)if(T.type==="text"){const N=T;B=it(x,B,N.text,N.marks||{})}}E.heading&&h.setAttribute("heading",String(E.heading)),E.align&&h.setAttribute("align",E.align)}P||i.push({kind:"replace",paragraphId:a,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(x,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(x,B,0)),text:E.children.filter(T=>T.type==="text").map(T=>T.text).join(""),oldText:F});let w=m+1;for(let T=1;T<v.children.length;T++){const N=v.children[T],L=new S.XmlElement("paragraph"),_=N.id||Y();L.setAttribute("id",_),N.heading&&L.setAttribute("heading",String(N.heading)),N.align&&L.setAttribute("align",N.align);const $=new S.XmlText;let R=0;N.children.forEach(O=>{if(O.type==="text"){const D=O;R=it($,R,D.text,D.marks||{})}}),Jn(L,N,R),L.insert(0,[$]),f.insert(w,[L]),w++;const M=N.children.filter(O=>O.type==="text").map(O=>O.text).join("");i.push({kind:"insert",paragraphId:_,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex($,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex($,M.length,0)),text:M})}}}break}case"style_blocks":{const{selectors:a,attrs:l}=e.arguments,{targets:c,inlineTargets:d,unmatchedSelectors:g,invalidSelectorErrors:u}=Od(s,a),p=Rd(l),h=Dd(p);if(c.length===0&&d.length===0)throw new Error(`style_blocks matched no blocks. Unmatched selectors: ${g.length>0?g.join(", "):"all"}. ${u.length>0?`Invalid selectors: ${u.join("; ")}.`:""}`);const f=[],m=new Map,y=(W,Q,se)=>{const V=bt(W);let de=m.get(V);de||(de={name:W,applied:new Set,skipped:new Map},m.set(V,de)),se?de.skipped.set(`${Q}\0${se}`,{blockId:Q,reason:se}):de.applied.add(Q)},b=i.length,k=new Set,I=new Set,v=new Set(c),x=new Set,A=[],C=[],F=[],E=[],P=He(s),B=new Set([...c,...d.map(W=>W.yBlock)].map(Te)),w=W=>"id"in W&&B.has(String(W.id))||"children"in W&&W.children.some(Q=>w(Q)),T=W=>[...W.children,...W.notes??[],...W.chrome??[]],N=new Set(T(P).filter(w).map(W=>W.id)),L=W=>qt({order:W.children.map(Q=>Q.id),noteOrder:(W.notes??[]).map(Q=>Q.id),chromeOrder:(W.chrome??[]).map(Q=>Q.id),targets:T(W).filter(Q=>N.has(Q.id))}),_=L(P),$=new Set,R=new Set,M=Qn(p,"width");if(M&&!(c.some(W=>W.nodeName==="image")&&tn(M.value)===void 0)){const W=new Map;for(const se of c){if(se.nodeName!=="table-cell")continue;let V=se.parent;for(;V instanceof S.XmlElement&&V.nodeName!=="table";)V=V.parent;if(!(V instanceof S.XmlElement))continue;const de=z(P,Te(V));if(!de||de.type!=="table")continue;const ye=tn(M.value),Le=Lt("width",M.value),re=de.tableWidth??cr(P,V),le=ye??(typeof Le=="number"&&Number.isFinite(Le)?Le/re*100:NaN);W.has(V)||W.set(V,[]),W.get(V).push({cellId:Te(se),percent:le}),$.add(se)}const Q=[...W].map(([se,V])=>({table:se,requests:V,widths:nd(z(P,Te(se)),V)}));for(const se of Q){const V=String(se.table.getAttribute("columnWidths")??""),de=JSON.stringify(se.widths),ye=z(P,Te(se.table)),Le=Ze(ye);for(const re of se.requests){const le=Le.byId.get(re.cellId),ke=Ae=>Ae.slice(le.col,le.col+le.colSpan).reduce((ct,kn)=>ct+kn,0);Math.abs(ke(ye.columnWidths)-ke(se.widths))>.001&&R.add(re.cellId)}V!==de&&(se.table.setAttribute("columnWidths",de),Be(i,se.table,null,"columnWidths"),k.add(Te(se.table))),x.add(M.canonicalName),I.add("columnWidths")}}for(const W of c){const Q=Te(W);let se=!1;const V=Wd({doc:P,yBlock:W,rawAttrs:p,anchors:i});$.has(W)&&M&&(V.handledRawNames.add(M.canonicalName),V.appliedAttrs.push("cell width -> table columns"));for(const re of V.handledRawNames){const le=p.find(Ae=>Ae.canonicalName===re),ke=V.issuesByRawName.get(re)??[];y(le?.rawName??re,Q,ke.length?ke.join("; "):void 0),x.add(re)}for(const re of V.appliedAttrs)I.add(re),k.add(Q);A.push(...V.exactMappings),C.push(...V.approximateMappings),F.push(...V.ignoredAttrs),E.push(...V.unsupportedImageSpacing),f.push(...V.errors);const de=Ro(h,W,!1);C.push(...Do(de));const ye=de.some(({rawName:re,value:le})=>["liststyletype","list-style-type"].includes(re.toLowerCase())&&typeof le=="string"&&le.toLowerCase()==="none"),Le=[];for(const{rawName:re,entry:le,value:ke}of de){if(ye&&W.nodeName==="list"&&le.kind!=="textMark"&&le.nodeNames.includes("paragraph")&&!le.nodeNames.includes("list-item")){Le.push({rawName:re,entry:le,value:ke});continue}if(!V.handledRawNames.has(bt(re)))try{if(le.attr==="variant"&&typeof ke=="string"&&ke.trim().toLowerCase()==="none"&&["liststyletype","list-style-type"].includes(re.trim().toLowerCase())){if(W.nodeName!=="list")throw new Error('style_blocks "listStyleType: none" only applies to list blocks.');se=!0;continue}if(le.kind==="textMark"){const Ae=Eo(re,le.attr,ke);Ad({toolName:"style_blocks",yBlock:W,attribute:le.attr,operation:Ae===null?"remove":"set",value:Ae,config:le,anchors:i,independentlySelectedTargets:v}),k.add(Q),I.add(`${re} -> ${le.attr}`),y(re,Q);continue}Td({toolName:"style_blocks",yBlock:W,attribute:le.attr,operation:ke===null?"remove":"set",value:ke,config:{nodeNames:le.nodeNames,valueType:le.valueType,integer:le.integer,min:le.min,max:le.max,enumValues:le.enumValues},anchors:i,independentlySelectedTargets:v}),k.add(Q),I.add(`${re} -> ${le.attr}`),y(re,Q)}catch(Ae){y(re,Q,Ae instanceof Error?Ae.message:String(Ae)),f.push(`${Q}.${le.attr}: ${Ae instanceof Error?Ae.message:String(Ae)}`)}}if(se){const re=Vd(W,i);if(re){for(const{rawName:le,entry:ke,value:Ae}of Le)if(ke.kind!=="textMark")try{for(const ct of re)Gn({toolName:"style_blocks",yBlock:ct,attribute:ke.attr,operation:Ae===null?"remove":"set",value:Ae,config:ke,anchors:i});I.add(`${le} -> ${ke.attr}`),y(le,Q)}catch(ct){const kn=ct instanceof Error?ct.message:String(ct);y(le,Q,kn),f.push(`${Q}.${ke.attr}: ${kn}`)}k.add(Q),I.add("listStyleType -> plain paragraphs"),y("listStyleType",Q)}else f.push(`${Q}.variant: could not convert the list to plain paragraphs.`)}}for(const{yBlock:W,ranges:Q}of d){const se=Te(W),V=Ro(h,W,!0);C.push(...Do(V));for(const{rawName:de,entry:ye,value:Le}of V){if(ye.kind!=="textMark"){const re="Block attributes cannot apply to an inline range; select its block instead.";y(de,se,re),f.push(`${se}.${ye.attr}: ${re}`);continue}try{const re=Eo(de,ye.attr,Le);wd({toolName:"style_blocks",yBlock:W,ranges:Q,attribute:ye.attr,operation:re===null?"remove":"set",value:re,config:ye,anchors:i}),k.add(se),I.add(`${de} -> ${ye.attr}`),y(de,se)}catch(re){y(de,se,re instanceof Error?re.message:String(re)),f.push(`${se}.${ye.attr}: ${re instanceof Error?re.message:String(re)}`)}}}for(const W of h.unsupportedAttrs??[]){const Q=m.get(bt(W)),se=new Set([...Q?.skipped.values()??[]].map(V=>V.blockId));for(const V of B)!Q?.applied.has(V)&&!se.has(V)&&y(W,V,"Unsupported attribute for this target.")}const O=He(s),D=W=>{const Q=new Map,se=V=>{"id"in V&&V.id&&Q.set(V.id,V),"children"in V&&V.children.forEach(de=>se(de))};return T(W).forEach(se),Q},X=D(P),j=D(O),U=W=>qt(X.get(W)??null)!==qt(j.get(W)??null),q=[...new Set([...B,...i.slice(b).map(W=>W.paragraphId).filter(W=>!!W)])].filter(U),oe=[...B].filter(W=>U(W)||R.has(W)),be=[...m.values()].map(W=>({name:W.name,appliedBlockIds:[...W.applied],skipped:[...W.skipped.values()]})),Xe=be.every(W=>W.skipped.length===0)&&I.size>0&&f.length===0&&g.length===0&&u.length===0&&F.length===0&&E.length===0&&(h.unsupportedAttrs??[]).every(W=>x.has(bt(W))),Oe={outcome:Xe?oe.length?"complete":"unchanged":"partial",targetBlockIds:[...B],changedBlockIds:oe,affectedBlockIds:q,attributes:be};if(ve(e,{styleEffects:Oe}),Xe&&_===L(O)&&ve(e,{verifiedUnchanged:!0}),i.length===b&&!Me(e)?.verifiedUnchanged){if(E.length||F.length)throw new fe("attribute_unsupported","These image layout attributes cannot be represented. Use width/height or align for image sizing/placement, and document blockGap or surrounding paragraph spacing for separation.","validation");if(h.length===0){const W=h.unsupportedAttrs??[];throw new Error(W.length>0?`style_blocks has no supported attrs. Unsupported attrs: ${W.join(", ")}.`:"style_blocks requires at least one attr.")}throw new Error(`style_blocks could not apply to any target. ${f.length>0?`Skipped target attrs: ${f.join("; ")}`:"No matching supported attributes."}`)}tr.set(e,Yd({styleEffects:Oe,matchedTargetCount:c.length+d.reduce((W,Q)=>W+Q.ranges.length,0),inlineRangeCount:d.reduce((W,Q)=>W+Q.ranges.length,0),unsupportedAttrs:(h.unsupportedAttrs??[]).filter(W=>!x.has(bt(W))),unmatchedSelectors:g,invalidSelectorErrors:u,skippedTargetErrors:f,exactCompatibilityMappings:A,approximateCompatibilityMappings:C,ignoredCompatibilityAttrs:F,unsupportedImageSpacing:E}));break}case"set_block_attribute":{const{id:a,attribute:l,operation:c,value:d}=e.arguments,g=To("set_block_attribute",a),u=()=>{const b=He(s);return g.map(k=>z(b,k))},p=JSON.stringify(u());if(typeof l!="string"||l.trim().length===0)throw new Error("set_block_attribute requires a non-empty attribute name.");const h=l.trim();if(h==="id")throw new Error("set_block_attribute cannot modify the reserved 'id' attribute.");const f=vd(c),m=[],y=(b,k)=>{if(g.length<=1)throw new Error(k);return m.push(`${b}: ${k}`),!0};for(const b of g){const k=G(s,b);if(!k){y(b,`Target block '${b}' not found in the document. Please only reference IDs you see inside <document_content>.`);continue}const{yBlock:I}=k,v=ue(I);if(h==="fontFamily"){const A=Vn(I);if(A){y(b,A);continue}}if(yd.has(h)){if(!v||I.nodeName!=="paragraph"&&I.nodeName!=="list-item"){y(b,`set_block_attribute "${h}" only supports paragraph or list-item text blocks.`);continue}let A;if(f==="remove")A=!1;else if(f==="toggle")A=!Ao(I,v,h);else if(d===void 0)A=!0;else if(typeof d=="boolean")A=d;else throw new Error(`set_block_attribute "${h}" expects a boolean value when operation is "set".`);if(v.length>0)ie(v,0,v.length,{[h]:A?!0:null}),nt(i,b,v);else{Sd(I,h,A);const C=`Text mark "${h}" ${A?"enabled":"removed"}.`;i.push({kind:"replace",paragraphId:b,text:C,oldText:C})}continue}if(h in Io){if(!v||I.nodeName!=="paragraph"&&I.nodeName!=="list-item"){y(b,`set_block_attribute "${h}" only supports paragraph or list-item text blocks.`);continue}if(f==="toggle")throw new Error(`set_block_attribute "${h}" does not support toggle. Use operation "set" with a numeric value or "remove".`);const A=Io[h],C=f==="remove"?null:Id(h,d,A);if(v.length>0)ie(v,0,v.length,{[h]:C===null?null:C}),nt(i,b,v);else{wo(I,h,C);const F=`Text mark "${h}" ${C===null?"removed":"set"}.`;i.push({kind:"replace",paragraphId:b,text:F,oldText:F})}continue}if(h==="indentLevel"&&I.nodeName==="paragraph"){Bo(I,f,d),v&&nt(i,b,v);continue}const x=xo[h];if(!x){const A=Object.keys(xo).sort().join(", ");throw new Error(`set_block_attribute "${h}" is not supported. Supported block attributes: ${A}.`)}if(!x.nodeNames.includes(I.nodeName)){y(b,`set_block_attribute "${h}" is not valid for ${I.nodeName} blocks.`);continue}if(f==="remove")J(I,h);else if(f==="toggle"){if(x.valueType!=="boolean")throw new Error(`set_block_attribute "${h}" only supports toggle for boolean attributes.`);const A=Co(ee(I,h));I.setAttribute(h,String(!A))}else{if(d===void 0)throw new Error(`set_block_attribute "${h}" requires "value" when operation is "set".`);const A=Po(h,d,x);I.nodeName==="paragraph"&&(h==="leftIndent"||h==="firstLineIndent")?Mo(I,h,Number(A)):I.setAttribute(h,A)}if(v)nt(i,b,v);else{const A=`Updated ${h} on ${I.nodeName} block.`;i.push({kind:"replace",paragraphId:b,text:A,oldText:A})}}if(i.length===0&&m.length>0)throw new Error(`set_block_attribute could not apply to any target. Skipped targets: ${m.join("; ")}`);m.length===0&&p===JSON.stringify(u())&&ve(e,{verifiedUnchanged:!0});break}case"clear_formatting":{const{id:a}=e.arguments,l=To("clear_formatting",a),c=()=>{const g=He(s);return l.map(u=>z(g,u))},d=JSON.stringify(c());for(const g of l){const u=G(s,g);if(!u)throw new Error(`Target block '${g}' not found in the document. Please only reference IDs you see inside <document_content>.`);const p=[];if(u.yBlock.nodeName==="list"){for(let h=0;h<u.yBlock.length;h++){const f=u.yBlock.get(h);if(f instanceof S.XmlElement&&f.nodeName==="list-item"){const m=f.getAttribute("id")||g;p.push({id:m,yBlock:f})}}if(p.length===0){const h=`Cleared formatting on list block ${g}.`;i.push({kind:"replace",paragraphId:g,text:h,oldText:h});continue}}else p.push({id:g,yBlock:u.yBlock});for(const h of p){if(h.yBlock.nodeName!=="paragraph"&&h.yBlock.nodeName!=="list-item")throw new Error("clear_formatting only supports paragraph, list, or list-item blocks.");const f=ue(h.yBlock);if(!f)throw new Error("clear_formatting only supports paragraph, list, or list-item text blocks.");if(h.yBlock.nodeName==="paragraph")for(const m of Ms)J(h.yBlock,m);if(qd(h.yBlock),f.length>0){let m=0;for(const y of Z(f)){const b=typeof y.insert=="string"?y.insert.length:1,k={...Es};typeof y.attributes?.footnoteRef=="string"&&y.attributes.footnoteRef.length>0&&delete k.superscript,ie(f,m,b,k),m+=b}nt(i,h.id,f)}else{const m="Formatting cleared.";i.push({kind:"replace",paragraphId:h.id,text:m,oldText:m})}}}d===JSON.stringify(c())&&ve(e,{verifiedUnchanged:!0});break}case"remove_block":{const{id:a,count:l=1}=e.arguments,c=G(s,a);if(!c)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);const{yParent:d,index:g}=c;Ft(d)&&Nt();const u=zt(s),p=d===u;for(let h=0;h<l;h++){const f=g;if(f>=d.length)break;const m=d.get(f);if(!(m instanceof S.XmlElement))break;const y=m.getAttribute("id"),b=m.nodeName;if(p&&d.length===1){if(b==="paragraph"){const k=ue(m);if(k&&k.length>0){const I=Z(k);let v="";for(const x of I)x.insert&&typeof x.insert=="string"&&(v+=x.insert);i.push({kind:"delete",paragraphId:y,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(k,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(k,v.length,0)),text:v}),k.delete(0,k.length)}}else{i.push({kind:"delete",paragraphId:y,text:b==="list"?"List removed":"Block removed"});const k=new S.XmlElement("paragraph");k.setAttribute("id",y);const I=new S.XmlText;k.insert(0,[I]),d.delete(f,1),d.insert(f,[k])}break}if(b==="list")i.push({kind:"delete",paragraphId:y,text:"List removed"});else{const k=ue(m);if(k){const I=Z(k);let v="";for(const x of I)x.insert&&typeof x.insert=="string"&&(v+=x.insert);i.push({kind:"delete",paragraphId:y,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(k,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(k,v.length,0)),text:v})}else i.push({kind:"delete",paragraphId:y,text:"Block removed"})}d.delete(f,1)}break}case"append_to_paragraph":{const{id:a,content:l}=e.arguments,c=K(s,a);if(!c)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);const d=ue(c);d||er(c);const g=d.length,u=dt(g>0?ri(d,g-1,1):kt(c.getAttribute("_emptyTextMarks"))),p=te.fromAgentHtml(l);if(p.children.length>0){const h=[];for(const y of p.children)y.type==="paragraph"&&y.children.forEach(b=>{b.type==="text"&&h.push(b)});let f=g,m="";for(const y of h)if(y.text){const b=it(d,f,y.text,{...u||{},...y.marks||{}});m+=y.text,f=b}m&&i.push({kind:"insert",paragraphId:a,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(d,g,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(d,f,0)),text:m})}break}case"break_paragraph":{const{id:a,substring:l}=e.arguments,c=typeof l=="string"?l:String(l??"");if(c.trim().length===0)throw new Error("break_paragraph requires a non-empty substring to split on.");const d=n?.document??he(s),g=z(d,a);if(!g)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);if(g.type!=="paragraph")throw new Error(`break_paragraph only works on paragraphs. Block '${a}' is type '${g.type}'.`);const u=hg(g,c);if(u.length===0){const j=g.children.filter(q=>q.type==="text").map(q=>q.text).join(""),U=j.length>100?j.slice(0,100)+"...":j;throw new Error(`No match found for "${c}" in block '${a}'. The block contains: "${U}".`)}const p=u[0].offset,h=G(s,a);if(!h)throw new Error(`Y.js block not found for id: ${a}`);const{yBlock:f,yParent:m,index:y}=h;if(Ft(m)&&Nt(),!(f instanceof S.XmlElement))throw new Error(`Target block '${a}' is not a valid Y.XmlElement.`);const b=ue(f);if(!b)throw new Error(`break_paragraph only works on text paragraphs. Block '${a}' has no text content.`);const{beforeOps:k,afterOps:I,formatAtSplit:v,originalText:x,beforeText:A,afterText:C}=cg(b,p);b.delete(0,b.length);let F=0;for(const j of k)ne(b,F,j.insert,j.attributes??{}),F+=j.insert.length;const E=Y(),P=new S.XmlElement("paragraph");P.setAttribute("id",E);const B=f.getAttribute("heading");B&&P.setAttribute("heading",B);const w=ee(f,"align");w&&P.setAttribute("align",w);const T=ee(f,"lineSpacing");T!=null&&P.setAttribute("lineSpacing",T);const N=ee(f,"pagination");N!=null&&P.setAttribute("pagination",N);const L=f.getAttribute("styleId");L!=null&&P.setAttribute("styleId",L);const _=ee(f,"direction");_!=null&&P.setAttribute("direction",_);const $=ee(f,"borders");$!=null&&P.setAttribute("borders",$);const R=ee(f,"shading");R!=null&&P.setAttribute("shading",R);const M=ee(f,"tabStops");M!=null&&P.setAttribute("tabStops",M);const O=f.getAttribute("oxmlPPr");O!=null&&P.setAttribute("oxmlPPr",O);const D=new S.XmlText;let X=0;for(const j of I)D.insert(X,j.insert,j.attributes??{}),X+=j.insert.length;if(I.length===0){const j=kt(f.getAttribute("_emptyTextMarks")),U=dt({...j,...v??{}});U&&Object.keys(U).length>0&&P.setAttribute("_emptyTextMarks",JSON.stringify(U))}P.insert(0,[D]),m.insert(y+1,[P]),A!==x&&i.push({kind:"replace",paragraphId:a,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(b,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(b,F,0)),text:A,oldText:x}),i.push({kind:"insert",paragraphId:E,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(D,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(D,X,0)),text:C||"Paragraph split"});break}case"join_paragraphs":{const{firstId:a,secondId:l,separator:c}=e.arguments;if(!a||!l||a===l)throw new Error("join_paragraphs requires two different paragraph IDs: firstId and secondId.");const d=G(s,a),g=G(s,l);if(!d)throw new Error(`Target block '${a}' not found in the document.`);if(!g)throw new Error(`Target block '${l}' not found in the document.`);if((Ft(d.yParent)||Ft(g.yParent))&&Nt(),d.yBlock.nodeName!=="paragraph"||g.yBlock.nodeName!=="paragraph")throw new Error("join_paragraphs only works on two paragraph blocks.");if(d.yParent!==g.yParent||g.index!==d.index+1)throw new Error(`join_paragraphs requires adjacent sibling paragraphs with secondId immediately after firstId. '${l}' does not immediately follow '${a}'.`);const u=ue(d.yBlock),p=ue(g.yBlock);if(!u||!p)throw new Error("join_paragraphs only works on text paragraph blocks.");const h=u.toString(),f=p.toString(),m=c!==void 0?String(c):/\S/.test(h)&&/\S/.test(f)?" ":"",y=h.match(/\s+$/)?.[0].length??0,b=f.match(/^\s+/)?.[0].length??0,k=m.length>0,I=k?h.slice(0,h.length-y):h,v=k?f.slice(b):f;k&&y>0&&u.delete(u.length-y,y);const x=Z(u),A=Z(p),C=x.length>0?x[x.length-1].attributes??{}:{},F=A.length>0?A[0].attributes??{}:{};let E=u.length;m.length>0&&(ne(u,E,m,Object.keys(C).length>0?C:F),E+=m.length);let P=k?b:0;for(const w of A){if(typeof w.insert!="string"||w.insert.length===0)continue;const T=w.insert.slice(P);P=Math.max(0,P-w.insert.length),T.length!==0&&(ne(u,E,T,w.attributes??{}),E+=T.length)}const B=`${I}${m}${v}`;i.push({kind:"replace",paragraphId:a,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(u,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(u,u.length,0)),text:B||"Paragraphs joined",oldText:h}),i.push({kind:"delete",paragraphId:l,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(p,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(p,p.length,0)),text:f||"Empty paragraph removed"}),g.yParent.delete(g.index,1);break}case"insert_table_row":{const a=he(s),l=te.createParsingContext(a),{tableId:c,referenceIndex:d,referenceRowId:g,position:u,content:p}=e.arguments,h=z(a,c);if(h?.type!=="table")throw new Error(`Table ${c} not found`);let f=d;if(g!==void 0){if(f=h.children.findIndex(k=>k.id===g),f<0)throw new Error(`Row ${g} not found in table ${c}. Read the table and use a current row ID.`);if(d!==void 0&&d!==f)throw new Error(`Row ${g} is at index ${f}, not ${d}. Use referenceRowId alone or reread the table.`)}if(f===void 0||!Number.isInteger(f)||f<0||f>=h.children.length)throw new Error("Invalid reference row index. Supply a current referenceRowId or a valid 0-based referenceIndex.");const m=h.children[f],y=p?.map(k=>{if(k==="")return;const I=te.fromAgentHtml(k,{existingDocument:a,parsingContext:l});return I.children.length>0?I.children:void 0}),b=gd(s,c,u,f,y);if(!b.success)throw new Error(b.error||"Failed to insert table row");i.push({kind:"insert",paragraphId:c,text:`Row inserted ${u} row ${m.id} (reference index ${f}; new row index ${f+(u==="after"?1:0)})`});break}case"remove_table_row":{const{tableId:a,rowIndex:l}=e.arguments,c=ld(s,a,l);if(!c.success)throw new Error(c.error||"Failed to remove table row");i.push({kind:"delete",paragraphId:a,text:`Row ${l} removed`});break}case"insert_table_column":{const a=he(s),l=te.createParsingContext(a),{tableId:c,referenceIndex:d,position:g,content:u}=e.arguments,p=u?.map(f=>{if(f==="")return;const m=te.fromAgentHtml(f,{existingDocument:a,parsingContext:l});return m.children.length>0?m.children:void 0}),h=cd(s,c,g,d,p);if(!h.success)throw new Error(h.error||"Failed to insert table column");i.push({kind:"insert",paragraphId:c,text:`Column inserted ${g} column ${d}`});break}case"remove_table_column":{const{tableId:a,columnIndex:l}=e.arguments,c=od(s,a,l);if(!c.success)throw new Error(c.error||"Failed to remove table column");i.push({kind:"delete",paragraphId:a,text:`Column ${l} removed`});break}}return n?.refreshDocumentIncrementally&&(n.document=He(s)),i}function kt(s){if(!s)return{};try{const e=JSON.parse(s);if(e&&typeof e=="object")return e}catch{}return{}}function cg(s,e){const t=[],n=[];let i={},r="",o="",a="",l=0;const c=Z(s);for(const d of c){if(!d.insert||typeof d.insert!="string")continue;const g=d.insert,u=d.attributes||{},p=l+g.length;if(r+=g,p<=e)t.push({insert:g,attributes:u}),o+=g,p===e&&(i=u);else if(l>=e)n.push({insert:g,attributes:u}),a+=g;else{const h=e-l,f=g.slice(0,h),m=g.slice(h);f.length>0&&(t.push({insert:f,attributes:u}),o+=f),m.length>0&&(n.push({insert:m,attributes:u}),a+=m),i=u}l=p}return{beforeOps:t,afterOps:n,formatAtSplit:i,originalText:r,beforeText:o,afterText:a}}function ri(s,e,t){const n=e+t;let i=0,r=null;for(const o of Z(s)){if(typeof o.insert!="string")continue;const a=i+o.insert.length;if(a>e&&i<n){const l=o.attributes||{},c={};for(const d of as){const g=l[d];g!=null&&g!==!1&&(c[d]=g)}if(r===null)r=c;else for(const d of Object.keys(r))r[d]!==c[d]&&delete r[d]}if(i=a,i>=n)break}return r??{}}function ur(s){const e=new Set;if(!s.includes("<")||!s.includes(">"))return e;try{const t=te.fromAgentHtml(s),n=i=>{if(i.type==="text"){for(const r of In)i.marks?.[r]!==void 0&&e.add(r);return}if("children"in i&&Array.isArray(i.children))for(const r of i.children)n(r)};for(const i of t.children)n(i)}catch{}return e}function Ko(s,e){const t=Jt(s);return e.code||e.latex?t:Us(t)}function Vo(s,e,t,n,i){if(i.includes("<")&&i.includes(">")||ur(n).size>0)return!1;const r=ri(s,e,t),o=Ko(i,r);return s.toString().slice(e,e+t)===o}function hr(s,e,t,n,i,r,o,a={}){if(!Vo(s,e,t,n,i))if(i.includes("<")&&i.includes(">")){const l={...a,...ri(s,e,t)};for(const p of ur(n))delete l[p];const c=i.trim(),d=/^<\s*(?:p|h[1-6])(?:\s|>|\/)/i.test(c)?c:`<p>${i}</p>`,g=te.fromAgentHtml(d,{preserveExplicitMarkResets:!0}),u=g.children.length>0?g.children[0]:null;if(u&&u.type==="paragraph"&&u.children.length>0){s.delete(e,t);const p=[];for(const b of u.children)if(b.type==="text"){const k=b,I={...l,...k.marks||{}};p.push({text:k.text,marks:I})}const h=s.doc;let f=e;const m=[];for(const b of p){const k=m[m.length-1],I=JSON.stringify(b.marks||{}),v=k?JSON.stringify(k.marks||{}):null;k&&I===v?k.text+=b.text:m.push({text:b.text,marks:b.marks||{}})}const y=m.map(b=>b.text).join("");h.transact(()=>{ne(s,e,y);let b=e;for(const k of m)k.marks&&Object.keys(k.marks).length>0&&ie(s,b,k.text.length,k.marks),b+=k.text.length;f=e+y.length},"performReplacement"),zo(s,e,f),o.push({kind:"replace",paragraphId:r,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(s,e,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(s,f,0)),text:i.replace(/<[^>]*>/g,""),oldText:n.replace(/<[^>]*>/g,"")})}}else{const l={...a,...ri(s,e,t)},c=Ko(i,l);for(const d of ur(n))delete l[d];s.delete(e,t),c.length>0&&ne(s,e,c,l),zo(s,e,e+c.length),o.push({kind:"replace",paragraphId:r,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(s,e,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(s,e+c.length,0)),text:c,oldText:n.replace(/<[^>]*>/g,"")})}}const si=/\\+u[0-9a-fA-F]{4}/;function Go(s){let e="";const t=[],n=[];for(let i=0;i<s.length;){const r=s.slice(i).match(/^(\\+u)([0-9a-fA-F]{4})/),o=r?i+r[0].length:i+1,a=r?String.fromCharCode(Number.parseInt(r[2],16)):s[i],l=tt(a);e+=l;for(let c=0;c<l.length;c++)t.push(i),n.push(o);i=o}return{text:e,sourceStarts:t,sourceEnds:n}}function fr(s,e){return s.flatMap(t=>{if(t.length<=0)return[];const n=e.sourceStarts[t.offset],i=e.sourceEnds[t.offset+t.length-1];return n===void 0||i===void 0||i<n?[]:[{offset:n,length:i-n}]})}function Qo(s){return s.replace(/^(?:#{1,6}|>|[-*+]|\d+[.)])[ \t]+/,"")}function dg(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Zo(s,e){const t=e.split(/(\s+)/),n=[];for(const l of t)/^\s+$/.test(l)?n.push("\\s+"):l.length>0&&n.push(dg(l));if(n.length===0)return[];const i=n.join(""),r=new RegExp(i,"g"),o=[];let a;for(;(a=r.exec(s))!==null;)o.push({offset:a.index,length:a[0].length});return o}function gg(s,e,t,n,i){const r=[];let o=s.indexOf(e);for(;o!==-1;){const a=o+n-t.length,l=Math.min(o+i-t.length+1,s.length);for(let c=a;c<l;c++)if(s.substring(c,c+t.length)===t){const d=c+t.length-o;d>=n&&d<=i&&r.push({offset:o,length:d})}o=s.indexOf(e,o+1)}return r}function ea(s,e){const t=Mn(e);if(t.length>1)for(const n of t){const i=Vt(s,n);if(i.length)return i.map(({start:r,end:o})=>({offset:r,length:o-r}))}for(const n of t){if(et(n))continue;const i=ug(s,n);if(i.length)return i}return[]}function ug(s,e){if(!e)return[];if(/^\s*$/.test(e))return pr(s,e);if(si.test(s)||si.test(e))return ta(s,e);const t=kc();return t!==null?t:ta(s,e)}function ta(s,e){const t=Vt(s,e);if(t.length)return t.map(({start:d,end:g})=>({offset:d,length:g-d}));const n=tt(s),i=tt(e),r=pr(n,i);if(r.length>0)return r;const o=Zo(n,i);if(o.length>0)return o;let a,l;if(si.test(s)||si.test(e)){a=Go(s),l=Go(e).text;const d=pr(a.text,l);if(d.length>0)return fr(d,a);const g=Zo(a.text,l);if(g.length>0)return fr(g,a)}const c=8;if(i.length>=c*2){const d=na(n,i,c);if(d!==null)return[d]}if(a&&l&&l.length>=c*2){const d=na(a.text,l,c);if(d!==null)return fr([d],a)}return[]}function hg(s,e){let t="";for(const n of s.children)n.type==="text"&&(t+=n.text);return ea(t,e)}function pr(s,e){const t=[];let n=s.indexOf(e);for(;n!==-1;)t.push({offset:n,length:e.length}),n=s.indexOf(e,n+e.length);return t}function na(s,e,t){const n=Math.floor(e.length/2);for(let i=n;i>=t;i--){const r=e.substring(0,i),o=e.substring(e.length-i),a=Math.max(5,Math.floor(e.length*.2)),l=Math.max(i*2,e.length-a),c=e.length+a,d=gg(s,r,o,l,c);if(d.length===1)return d[0]}return null}function fg(s,e,t,n,i={}){if(!e.length)return{anchorsByAction:[],failures:[],alreadySatisfied:!1};const r=e.every(h=>h.name==="insert_block"),o=r?n:i.canonicalDocument?.()??n;r||On(s,o);let a;const l={document:r?{...n,children:[...n.children]}:o,get htmlParsingContext(){return a??(a=te.createParsingContext(n))},set htmlParsingContext(h){a=h},refreshDocumentIncrementally:!r},c=[],d=[],g=new Set,u=[],p=(h,f,m,y)=>{const b=Me(h);d.push({actionIndex:f,actionName:h.name,error:m,failure:y,sourceEditIndex:b?.sourceEditIndex,sourceEditType:b?.sourceEditType})};for(let h=0;h<e.length;h++){const f=e[h];try{const m=()=>We(s,f,`${t}_${h}`,!i.skipContextForFirstAction||r||h>0?l:void 0),y=i.measure?i.measure(m):m();i.skipContextForFirstAction&&!r&&h===0&&e.length>1&&(l.document=He(s)),c.push(y);const b=Me(f);if(y.length&&b?.splitReplacementGroup&&g.add(b.splitReplacementGroup),!y.length&&i.rejectUnchangedAction&&!b?.verifiedUnchanged)if(zc(f)&&b?.splitReplacementGroup)u.push({action:f,index:h,group:b.splitReplacementGroup});else{p(f,h,nr(f)??`${JSON.stringify(f.arguments)} - no change made`);break}}catch(m){if(i.throwOnError)throw m;if(p(f,h,String(m),Mt(m)),!i.continueAfterError)break}}for(const{action:h,index:f,group:m}of u)g.has(m)||p(h,f,"Split replacement made no verified change");return{anchorsByAction:c,failures:d,alreadySatisfied:d.length===0&&e.every(h=>Me(h)?.verifiedUnchanged)}}const mr=()=>{},pg={count:mr,gauge:mr,distribution:mr},ia=new WeakSet;function br(s,e){try{pg.count("frontend.editor.yjs_observer_failure",1,{event:e})}catch{}console.error(`Yjs ${e} observer failed`,s)}function ra(s,e=br){if(ia.has(s))return;ia.add(s);const t=s.emit;let n=Number.NEGATIVE_INFINITY;s.emit=function(i,r){if(!["update","updateV2","afterTransactionCleanup"].includes(i))return t.call(this,i,r);const o=Array.from(this._observers.get(i)??[]);for(const a of o)try{a(...r)}catch(l){const c=Date.now();if(c-n>=3e4){n=c;try{e(l,i)}catch{}}}}}const sa="suggestion-id-repair";function mg(s){if(s.deleteSet.clients.size>0)return!0;for(const[e,t]of s.afterState){const n=s.beforeState.get(e)??0;if(n===t)continue;const i=s.doc.store.clients.get(e);for(let r=S.findIndexSS(i,n);r<i.length&&i[r].id.clock<t;r++){const o=i[r];if(o instanceof S.Item&&o.content instanceof S.ContentFormat&&["insertion","deletion","suggestionId","proposalId"].includes(o.content.key))return!0}}return!1}function bg(s,e,t="recover"){const n=new Set(["content","chrome","notes"].filter(l=>s.share.has(l)).map(l=>s.getXmlFragment(l))),i=new Set,r=l=>{l._item?.deleted||(l instanceof S.XmlText?i.add(l):l instanceof S.XmlFragment&&l.toArray().forEach(r))};if(e){const l=mg(e);for(const[c,d]of e.changed)c instanceof S.XmlText?l&&i.add(c):c instanceof S.XmlFragment&&(d.has("structuralSuggestionId")||d.has("suggestionId"))&&r(c);Cl(e,c=>{c.deleted||c.content instanceof S.ContentType&&r(c.content.type)})}else n.forEach(r);const o=l=>typeof l=="string"&&l.trim().length>0,a=[];for(const l of i){if(l._item?.deleted)continue;let c=l,d=!1;for(;c.parent;){c=c.parent;const h=c;if(h instanceof S.XmlElement&&["structuralSuggestionId","suggestionId","proposalId"].some(f=>o(h.getAttribute(f)))){d=!0;break}}if(d||!n.has(c))continue;let g=0,u,p;for(const h of Z(l)){const f=typeof h.insert=="string"?h.insert.length:1,m=h.attributes??{};if(typeof h.insert!="string"||f===0||!(m.insertion||m.deletion)||o(m.suggestionId)||o(m.proposalId)){u=void 0,p=void 0,g+=f;continue}const y=JSON.stringify(Object.entries(m).filter(([b])=>b==="insertion"||b==="deletion"||b==="layeredInsertion"||b.startsWith("suggestion")).sort(([b],[k])=>b.localeCompare(k)));if(p&&u===y)p.length+=f;else{const b=S.createRelativePositionFromTypeIndex(l,g).item;if(!b){g+=f;continue}p={text:l,start:g,length:f,id:`recovered-inline-${b.client.toString(36)}-${b.clock.toString(36)}`},u=y,a.push(p)}g+=f}}return a.length&&s.transact(()=>{for(const l of a)ie(l.text,l.start,l.length,t==="strip"?{insertion:null,deletion:null,layeredInsertion:null,formatChange:null}:{suggestionId:l.id})},sa),a.length}function oi(s,e){if(Array.isArray(s))return s.map(i=>oi(i,e));if(!s||typeof s!="object")return s;const t={};for(const[i,r]of Object.entries(s))if(!(e.regenerateIds&&i==="id")){if(e.regenerateIds&&i==="marks"&&r&&typeof r=="object"&&!Array.isArray(r)&&"comment"in r){const{comment:o,...a}=r;Object.keys(a).length>0&&(t[i]=oi(a,e));continue}t[i]=oi(r,e)}const n=t.type;return e.regenerateIds&&typeof n=="string"&&n!=="doc"&&n!=="text"&&(t.id=Y()),t}function yg(s){return s.map(e=>oi(e,{regenerateIds:!0}))}const kg=["borders","align","styleId","direction","_emptyTextMarks"],Sg=["id","heading","oxmlAttrs",...Bl],Ig=["pagination"],vg=[...Pl("paragraph"),...Ig].filter(s=>!kg.includes(s)&&!Sg.includes(s));function oa(s,e){for(const t of vg){const n=ee(s,t);n!=null&&e.setAttribute(t,n)}}const yr=new Set(["aiGenerated","insertion","deletion","formatChange","suggestionId","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","docxMove","proposalId","toolCallId","toolType","diffSegmentIndex","__htmlClassName"]),xg=["insertion","deletion","formatChange","suggestionId","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","docxMove"];function aa(s,e){if(!s)return[];const t=!!s.footnoteRef,n=[];for(const[i,r]of Object.entries(s))r===void 0||r===!1||r===null||yr.has(i)||i==="link"&&e.excludeLink||i==="comment"&&e.excludeComment||i!=="footnoteRef"&&(i==="superscript"&&t||n.push([i,r]));return n}function kr(s){const{explicitMarks:e,inheritedMarks:t,emptyParagraphMarks:n,exitingLink:i=!1,exitingComment:r=!1,noteBodyFontSize:o,suggestionMarks:a}=s,l={},c=[],d=p=>{c.includes(p)||c.push(p)},g=p=>l[p]!==void 0,u=p=>c.includes(p);if(e){for(const[p,h]of Object.entries(e))h===!1?d(p):h!=null&&(l[p]=h);l.footnoteRef&&(delete l.footnoteRef,t?.footnoteRef&&delete l.superscript)}for(const[p,h]of aa(t,{excludeLink:i,excludeComment:r}))!g(p)&&!u(p)&&(l[p]=h);t?.footnoteRef&&!l.footnoteRef&&(d("footnoteRef"),l.superscript||d("superscript"));for(const[p,h]of aa(n,{excludeLink:i,excludeComment:r}))!g(p)&&!u(p)&&(l[p]=h);if(o!=null&&l.fontSize===void 0&&!u("fontSize")&&(l.fontSize=o),i&&!l.link&&d("link"),r&&!l.comment&&d("comment"),a)Object.assign(l,a);else if(t){const p=t;for(const h of xg)p[h]!==void 0&&p[h]!==null&&d(h)}return{marksToApply:l,marksToRemove:c}}function la(s,e,t,n){if(ne(s,e,t),Object.keys(n.marksToApply).length>0&&ie(s,e,t.length,n.marksToApply),n.marksToRemove.length>0){const i={};for(const r of n.marksToRemove)i[r]=null;ie(s,e,t.length,i)}}function ai(s,e,t){const n=ds(e,t,gt(s.getDocument().children));s.transact(()=>{const i=s.getYChromeFragment();ca(i,o=>o.getAttribute("sectionIndex")===void 0);for(const o of n)i.push([s.blockToYjsElement(o)]);const r=s.ydoc.getMap("metadata");r.delete("headers"),r.delete("footers")})}function Sr(s){return ss(s.getDocument().chrome??[])}function ca(s,e){for(let t=s.length-1;t>=0;t--){const n=s.get(t);n instanceof S.XmlElement&&e(n)&&s.delete(t,1)}}function Ag(s,e,t,n){const i=gt(s.getDocument().children),r=ds(t,n,i).map(o=>({...o,sectionIndex:e}));s.transact(()=>{const o=s.getYChromeFragment();ca(o,a=>a.getAttribute("sectionIndex")===String(e));for(const a of r)o.push([s.blockToYjsElement(a)])})}function wg(s,e){return Fl(s.getDocument().chrome??[],e)}function da(s,e,t){const n=El(s.getDocument().chrome??[],e,t);if(n)return n;const i=$l(e,t,void 0,gt(s.getDocument().children));return s.transact(()=>{s.getYChromeFragment().push([s.blockToYjsElement(i)])}),i}function Tg(s){const e=s.getYContentFragment(),t=[];for(const r of e.toArray())r instanceof S.XmlElement&&r.nodeName==="header-footer"&&t.push(r);const n=s.getYChromeFragment();if(t.length===0&&n.length<=3){ga(s);return}const i=s.getYChromeFragment();s.transact(()=>{for(const o of t){const a=s.getDocument().children.find(l=>l.type==="header-footer"&&l.id===o.getAttribute("id"));a&&i.push([s.blockToYjsElement(a)])}const r=e.toArray();for(let o=r.length-1;o>=0;o--){const a=r[o];a instanceof S.XmlElement&&a.nodeName==="header-footer"&&e.delete(o,1)}}),ga(s)}function ga(s){const e=s.getYChromeFragment(),t=new Map,n=[],i=e.toArray(),r=s.getDocument().chrome??[],o=a=>{const l=r.find(c=>c.id===a);return!!(l&&Nl(l))};i.forEach((a,l)=>{if(!(a instanceof S.XmlElement)||a.nodeName!=="header-footer")return;const c=`${a.getAttribute("side")}:${a.getAttribute("slot")}:${a.getAttribute("sectionIndex")??""}`,d=t.get(c);if(d===void 0){t.set(c,l);return}const g=i[d];!o(g.getAttribute("id"))&&o(a.getAttribute("id"))?(n.push(d),t.set(c,l)):n.push(l)}),n.length!==0&&s.transact(()=>{for(const a of n.sort((l,c)=>c-l))e.delete(a,1)})}function Cg(s){const e=s.ydoc.getMap("metadata"),t=e.get("headers"),n=e.get("footers");!t&&!n||((s.getDocument().chrome?.length??0)>0?s.transact(()=>{e.delete("headers"),e.delete("footers")}):ai(s,t,n))}function Pg(s,e,t="bottom-right"){const{headers:n={},footers:i={}}=Sr(s),r=l=>!!(l&&l.length===1&&l[0].children.every(c=>c.type==="text"&&(c.marks?.field==="page"||c.text.trim()===""))),o={...n},a={...i};if(r(o.default)&&delete o.default,r(a.default)&&delete a.default,e){const l=gs(t),c=l.side==="headers"?o:a;c.default||(c.default=[l.paragraph])}ai(s,Object.keys(o).length>0?o:void 0,Object.keys(a).length>0?a:void 0)}function Bg(s){const e=s.ydoc.getMap("metadata");if(e.get(Ge.showPageNumbers)!==!0)return;const t=e.get(Ge.pageNumberPosition)??"bottom-right",{headers:n={},footers:i={}}=Sr(s),r=gs(t),o=r.side==="headers"?n:i;if(s.transact(()=>{e.set(Ge.showPageNumbers,!1)}),!o.default){const a={...o,default:[r.paragraph]};ai(s,r.side==="headers"?a:n,r.side==="footers"?a:i)}}function Mg(s,e){const t=e?{fontFamily:e}:{},n=[];for(const i of s.split(/(\{PAGE\}|\{PAGES\})/))i&&(i==="{PAGE}"?n.push({type:"text",text:"1",marks:{field:"page",...t}}):i==="{PAGES}"?n.push({type:"text",text:"1",marks:{field:"numPages",...t}}):n.push({type:"text",text:i,...e?{marks:{...t}}:{}}));return n.length===0&&n.push({type:"text",text:"",...e?{marks:{...t}}:{}}),n}function Eg(s,e,t,n,i){const r=s.getYChromeFragment(),o=()=>{for(const d of r.toArray())if(d instanceof S.XmlElement&&d.nodeName==="header-footer"&&d.getAttribute("side")===e&&d.getAttribute("slot")===t)return d;return null};if(i){const d=o();return d?(s.transact(()=>{const g=r.toArray().indexOf(d);g>=0&&r.delete(g,1)}),!0):!1}const a=[];if(typeof n.left=="string"&&a.push([0,n.left]),typeof n.center=="string"&&a.push([1,n.center]),typeof n.right=="string"&&a.push([2,n.right]),a.length===0)return!1;da(s,e,t);const l=o();if(!l)return!1;const c=gt(s.getDocument().children);return s.transact(()=>{for(const[d,g]of a){const u=(s.getDocument().chrome??[]).find(f=>f.side===e&&f.slot===t)?.children[d],p=Ml[d],h={type:"paragraph",id:u?.id??Y(),children:Mg(g,c),...u?.align??p?{align:u?.align??p}:{}};l.get(d)&&l.delete(d,1),l.insert(d,[s.blockToYjsElement(h)])}}),!0}function st(s){return s.ydoc?s.ydoc.getMap("comments"):null}function $g(s){const e=st(s);if(!e)return[];const t=[];return e.forEach(n=>{n&&typeof n=="object"&&t.push(n)}),t.sort((n,i)=>(n.createdAt??"").localeCompare(i.createdAt??"")),t}function ua(s){const e=s.getAttribute("structuralSuggestionKind")==="insert"?s.getAttribute("structuralSuggestionId"):s.getAttribute("diffState")==="insert"?s.getAttribute("suggestionId"):void 0;return typeof e=="string"?e:void 0}function Fg(s,e){if(!s.ydoc||e.length===0)return[];const t=new Set(e),n=[],i=(r,o)=>{for(const a of r.toArray()){if(a instanceof S.XmlElement){const g=ua(a);i(a,typeof g=="string"&&t.has(g)?g:o);continue}if(!(a instanceof S.XmlText)||!(r instanceof S.XmlElement))continue;const l=r.getAttribute("id");if(typeof l!="string")continue;let c=0,d=0;for(const g of Z(a)){if(typeof g.insert!="string")continue;const u=g.insert.length,p=d+(g.attributes?.deletion?0:u),h=g.attributes?.suggestionId??o,f=!g.attributes?.suggestionId&&!!o;if(u>0&&typeof h=="string"&&t.has(h)){const m=n[n.length-1];m?.blockId===l&&m.suggestionId===h&&!!m.structural===f&&m.end===c?(m.end+=u,m.projectedEnd=p):n.push({blockId:l,suggestionId:h,start:c,end:c+u,projectedStart:d,projectedEnd:p,...f?{structural:!0}:{}})}c+=u,d=p}c===0&&o&&n.push({blockId:l,suggestionId:o,start:0,end:0,projectedStart:0,projectedEnd:0,structural:!0})}};return i(s.getYContentFragment()),i(s.ydoc.getXmlFragment("notes")),i(s.ydoc.getXmlFragment("chrome")),n}function Ir(s,e,t,n){return{id:ce(),author:t?.author??"Anonymous",...t?.initials?{initials:t.initials}:{},...t?.authorId?{authorId:t.authorId}:{},...t?.authorImageUrl?{authorImageUrl:t.authorImageUrl}:{},...t?.authorType?{authorType:t.authorType}:{},...t?.agentName?{agentName:t.agentName}:{},...t?.agentModel?{agentModel:t.agentModel}:{},...t?.suggestionId?{suggestionId:t.suggestionId}:{},...t?.mentions?.length?{mentions:t.mentions}:{},...t?.citations?.length?{citations:t.citations.map(i=>({...i}))}:{},...t?.anchorBlockId?{anchorBlockId:t.anchorBlockId}:{},...t?.agentRequestId?{agentRequestId:t.agentRequestId}:{},...t?.agentConversationId?{agentConversationId:t.agentConversationId}:{},...t?.agentTriggerIds?.length?{agentTriggerIds:[...t.agentTriggerIds]}:{},...t?.relatedSuggestionIds?.length?{relatedSuggestionIds:[...t.relatedSuggestionIds]}:{},createdAt:new Date().toISOString(),bodyMd:e,...n?{parentId:n}:{}}}function ha(s,e,t,n){const i=st(s);if(!i||!K(s.ydoc,e))return null;const r=Ir(s,t,{...n,anchorBlockId:e});return s.transact(()=>{i.set(r.id,r)}),r.id}function Ng(s,e,t,n,i){const r=K(s.ydoc,e),o=r?ae(r):null;if(!o||n<=t||t>=o.length)return!1;const a=Math.min(n,o.length),l=Z(o);let c=0,d=!1;for(const g of l){if(typeof g.insert!="string")continue;const u=c,p=c+g.insert.length;c=p;const h=Math.max(u,t),f=Math.min(p,a);if(f<=h)continue;const m=g.attributes?.comment,y=m?m.split(","):[];y.includes(i)||y.push(i),ie(o,h,f-h,{comment:y.join(",")}),d=!0}return d}function Lg(s,e,t,n,i,r){return vr(s,[{blockId:e,start:t,end:n}],i,r)}function vr(s,e,t,n){const i=st(s);if(!i||e.length===0)return null;const r=Ir(s,t,n),o=r.id;let a=!1;return s.transact(()=>{for(const l of e)a=Ng(s,l.blockId,l.start,l.end,o)||a;a&&i.set(o,r)}),a?o:null}function Og(s,e,t,n){const i=st(s);if(!i||!i.has(e))return null;const r=Ir(s,t,n,e);return s.transact(()=>{i.set(r.id,r)}),r.id}function Rg(s,e,t){const n=st(s),i=n?.get(e);return!n||!i?!1:(s.transact(()=>{n.set(e,{...i,resolved:t})}),!0)}function Dg(s,e,t){const n=st(s);if(!n)return 0;const i=new Set(e);if(i.size===0)return 0;const r=[];return n.forEach(o=>{const a=o;if(!a||typeof a!="object"||a.parentId||a.resolved)return;const l=[];typeof a.suggestionId=="string"&&a.suggestionId.length>0&&l.push(a.suggestionId);for(const c of a.relatedSuggestionIds??[])l.includes(c)||l.push(c);l.length!==0&&l.some(c=>i.has(c))&&(l.some(c=>t(c))||r.push(a))}),r.length===0?0:(s.transact(()=>{for(const o of r)n.set(o.id,{...o,resolved:!0})}),r.length)}function _g(s,e){const t=st(s);if(!t)return 0;const n=[];if(t.forEach(l=>{const c=l;c&&typeof c=="object"&&!c.parentId&&!c.resolved&&typeof c.suggestionId=="string"&&c.suggestionId.length>0&&(!e(c.suggestionId)||c.relatedSuggestionIds?.some(d=>!e(d)))&&n.push(c)}),n.length===0)return 0;const i=new Map,r=(l,c)=>{for(const d of l.toArray()){if(d instanceof S.XmlElement){const g=ua(d);r(d,g&&e(g)?g:c);continue}if(d instanceof S.XmlText)for(const g of Z(d)){const u=g.attributes?.comment,p=g.attributes?.suggestionId??c;if(!(!u||!p))for(const h of u.split(",")){const f=i.get(h)??[];f.includes(p)||f.push(p),i.set(h,f)}}}};try{r(s.getYContentFragment()),r(s.ydoc.getXmlFragment("notes")),r(s.ydoc.getXmlFragment("chrome"))}catch{}const o=l=>{const c=Array.from(new Set([...l.suggestionId?[l.suggestionId]:[],...i.get(l.id)??[],...l.relatedSuggestionIds??[]])).filter(e);if(c.length>0)return c;if(l.anchorBlockId){let d=K(s.ydoc,l.anchorBlockId)??null;for(;d;){if(d instanceof S.XmlElement){const g=d.getAttribute("structuralSuggestionId");if(typeof g=="string"&&e(g))return[g];for(const u of["structuralSuggestionRecord","structuralSuggestionRecords"]){const p=d.getAttribute(u);if(typeof p=="string")try{const h=JSON.parse(p),f=(Array.isArray(h)?h:[h]).find(m=>typeof m?.id=="string"&&e(m.id));if(f)return[f.id]}catch{}}}d=d.parent}}return[]};let a=0;return s.transact(()=>{for(const l of n){const c=o(l);if(c.length===0)continue;const d={...l,suggestionId:c[0]};c.length>1?d.relatedSuggestionIds=c:delete d.relatedSuggestionIds,t.set(l.id,d),a+=1}}),a}function jg(s,e){const t=st(s);if(!t||!t.has(e))return!1;const n=new Set([e]);let i=!0;for(;i;)i=!1,t.forEach((r,o)=>{const a=r;a?.parentId&&n.has(a.parentId)&&!n.has(o)&&(n.add(o),i=!0)});return s.transact(()=>{for(const o of n)t.delete(o);const r=o=>{for(const a of o.toArray()){if(a instanceof S.XmlElement){r(a);continue}if(!(a instanceof S.XmlText))continue;let l=0;for(const c of Z(a)){if(typeof c.insert!="string")continue;const d=c.insert.length,g=c.attributes?.comment;if(g){const u=g.split(",").filter(p=>!n.has(p));u.length!==g.split(",").length&&ie(a,l,d,{comment:u.length>0?u.join(","):null})}l+=d}}};try{r(s.getYContentFragment()),r(s.ydoc.getXmlFragment("notes")),r(s.ydoc.getXmlFragment("chrome"))}catch{}}),!0}function fa(s,e){const t=d=>d.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&amp;/g,"&");if(!s.includes("<")||!s.includes(">"))return[{type:"text",text:t(s),marks:{...e}}];const n=[],i={},r=d=>{d&&n.push({type:"text",text:t(d),marks:{...i,...e}})},o=/<(\/?)(i|em|b|strong|u|a)((?:\s+[a-zA-Z-]+="[^"]*")*)\s*\/?>/g;let a=0,l;for(;(l=o.exec(s))!==null;){r(s.slice(a,l.index)),a=o.lastIndex;const d=l[1]==="/",g=l[2].toLowerCase();if(g==="i"||g==="em")d?delete i.italic:i.italic=!0;else if(g==="b"||g==="strong")d?delete i.bold:i.bold=!0;else if(g==="u")d?delete i.underline:i.underline=!0;else if(g==="a")if(d)delete i.link;else{const u=/href="([^"]*)"/.exec(l[3]??"");u?.[1]&&(i.link=t(u[1]))}}r(s.slice(a));const c=n.map(d=>({...d,text:d.text.replace(/<[^>]{1,80}>/g,"")})).filter(d=>d.text.length>0);return c.length>0?c:[{type:"text",text:t(s),marks:{...e}}]}function Dt(s){const e=[],t=n=>{for(const i of n.toArray()){if(i instanceof S.XmlElement){if(i.nodeName==="footnote")continue;t(i);continue}if(!(i instanceof S.XmlText))continue;let r=0;for(const o of Z(i)){if(typeof o.insert!="string")continue;const a=o.attributes??{};typeof a.footnoteRef=="string"&&a.footnoteRef&&e.push({yText:i,start:r,length:o.insert.length,text:o.insert,attributes:a,footnoteId:a.footnoteRef}),r+=o.insert.length}}};try{t(s.getYContentFragment())}catch{}return e}function St(s){const e=new Map,t=n=>{for(const i of n.toArray())if(i instanceof S.XmlElement&&i.nodeName==="footnote"){const r=i.getAttribute("id");typeof r=="string"&&r&&e.set(r,i)}};try{t(s.getYNotesFragment()),t(s.getYContentFragment())}catch{}return e}function Xg(s,e){const t=[...s.notes??[],...s.children.filter(n=>n.type==="footnote")];for(const n of t)if(n.id===e||z(n,e))return!0;return!1}function xr(s){const e=new Map;for(const[t,n]of St(s))e.set(t,n.getAttribute("noteKind")==="endnote"?"endnote":"footnote");return e}function Ug(s){const e=[];for(const a of Dt(s))e.includes(a.footnoteId)||e.push(a.footnoteId);const t=xr(s),n=new Map,i=s.getDocument();for(const a of[...i.notes??[],...i.children.filter(l=>l.type==="footnote")])n.set(a.id,a);const r={footnote:0,endnote:0},o=[];for(const a of e){const l=n.get(a);if(!l)continue;const c=t.get(a)??"footnote";r[c]+=1,o.push({footnote:l,number:r[c],display:Ci(r[c],c),kind:c})}return o}function It(s){const e=Dt(s);if(e.length===0)return!1;const t=xr(s),n=new Map,i={footnote:0,endnote:0};for(const o of e)if(!n.has(o.footnoteId)){const a=t.get(o.footnoteId)??"footnote";i[a]+=1,n.set(o.footnoteId,Ci(i[a],a))}const r=e.filter(o=>o.text!==n.get(o.footnoteId));return r.length===0?!1:(s.transact(()=>{for(const o of[...r].sort((a,l)=>l.start-a.start)){const a=n.get(o.footnoteId)??"";o.yText.delete(o.start,o.length),ne(o.yText,o.start,a,o.attributes)}}),!0)}function zg(s){pa(s);const e=Dt(s),t=St(s);if(e.length===0&&t.size===0)return;const n=new Set(e.map(i=>i.footnoteId));s.transact(()=>{for(const[i,r]of t)if(!n.has(i)&&!r.getAttribute("structuralSuggestionId")){const o=r.parent;if(o){const a=o.toArray().indexOf(r);a>=0&&o.delete(a,1)}}for(const i of[...e].sort((r,o)=>o.start-r.start))t.has(i.footnoteId)||i.yText.delete(i.start,i.length)}),It(s)}function pa(s){let e;try{e=s.getYContentFragment()}catch{return!1}const t=[],n=d=>{for(const g of d.toArray()){if(g instanceof S.XmlElement){n(g);continue}if(!(g instanceof S.XmlText))continue;let u=0;for(const p of Z(g)){if(typeof p.insert!="string")continue;const h=p.attributes??{};typeof h.footnotePendingBody=="string"&&t.push({yText:g,start:u,length:p.insert.length,footnoteId:typeof h.footnoteRef=="string"&&h.footnoteRef?h.footnoteRef:Y(),body:h.footnotePendingBody,kind:h.footnotePendingKind==="endnote"?"endnote":"footnote",fontFamily:typeof h.fontFamily=="string"?h.fontFamily:void 0,suggestionId:typeof h.suggestionId=="string"?h.suggestionId:void 0,suggested:h.insertion===!0}),u+=p.insert.length}}};if(n(e),t.length===0)return!1;const i=St(s),r=new Set(Dt(s).map(d=>d.footnoteId)),o=s.getDocument(),a=new Map;for(const d of[...o.notes??[],...o.children.filter(g=>g.type==="footnote")])a.set(d.id,d.children.flatMap(g=>g.type==="paragraph"?g.children:[]).map(g=>g.type==="text"?g.text:"").join(""));const l=new Set;for(const d of t)if(!i.has(d.footnoteId)){for(const[g,u]of a)if(u===d.body&&!r.has(g)&&!l.has(g)&&i.has(g)){d.footnoteId=g,l.add(g);break}}const c=gt(s.getDocument().children);return s.transact(()=>{for(const d of t){if(ie(d.yText,d.start,d.length,{footnotePendingBody:null,footnotePendingKind:null,footnoteRef:d.footnoteId,superscript:!0}),i.has(d.footnoteId)){if(a.get(d.footnoteId)!==d.body){const f=i.get(d.footnoteId);let m=null;for(const b of f.toArray())if(b instanceof S.XmlElement&&b.nodeName==="paragraph"){m=b;break}const y=m?ae(m):null;if(y){const b=d.fontFamily??c;y.length>0&&y.delete(0,y.length);let k=0;for(const I of fa(d.body,{fontSize:ut,...b?{fontFamily:b}:{}}))ne(y,k,I.text,I.marks),k+=I.text.length}}continue}const g=d.fontFamily??c,u={fontSize:ut,...g?{fontFamily:g}:{}},p={type:"footnote",id:d.footnoteId,...d.kind==="endnote"?{noteKind:"endnote"}:{},children:[{type:"paragraph",id:Y(),children:fa(d.body,u)}]},h=s.blockToYjsElement(p);h.setAttribute("id",d.footnoteId),d.kind==="endnote"&&h.setAttribute("noteKind","endnote"),d.suggested&&d.suggestionId&&s.suggestions.setElementStructuralSuggestion(h,"insert",void 0,d.suggestionId,"Insert footnote"),s.getYNotesFragment().push([h]),i.set(d.footnoteId,h)}}),It(s),!0}function Hg(s){let e;try{e=s.getYContentFragment()}catch{return}const t=[];for(const o of e.toArray())o instanceof S.XmlElement&&o.nodeName==="footnote"&&t.push(o);if(t.length===0)return;const n=s.getYNotesFragment(),i=s.getDocument(),r=new Map([...i.notes??[],...i.children.filter(o=>o.type==="footnote")].map(o=>[o.id,o]));s.transact(()=>{for(const a of t){const l=a.getAttribute("id"),c=typeof l=="string"?r.get(l):void 0;c&&n.push([s.blockToYjsElement(c)])}const o=e.toArray();for(let a=o.length-1;a>=0;a--){const l=o[a];l instanceof S.XmlElement&&l.nodeName==="footnote"&&e.delete(a,1)}}),It(s)}function Wg(s,e,t,n,i="footnote"){if(!s.ydoc)return null;const r=Y(),o=s.suggestions.isSuggesting(),a=o?ce():void 0,l=xr(s),c=new Set(Dt(s).map(m=>m.footnoteId).filter(m=>(l.get(m)??"footnote")===i)).size,d=Ci(c+1,i);let g,u;{const m=z(s.getDocument(),e.block);if(m&&m.type==="paragraph"){u=m.direction;let y=0;for(const b of m.children){if(b.type!=="text")continue;const k=y+b.text.length;if(e.offset<=k&&b.marks?.fontFamily){g=b.marks.fontFamily;break}y=k}}}const p={footnoteRef:r,superscript:!0,...g?{fontFamily:g}:{},...o&&a?{insertion:!0,...s.suggestions.buildInlineMetadataMarks(a,"Insert footnote")}:{}};if(!s.insertTextNodes(e,[{type:"text",text:d,marks:p}],n))return null;const h=g??gt(s.getDocument().children),f={fontSize:ut,...h?{fontFamily:h}:{}};return s.transact(()=>{const m={type:"footnote",id:r,...i==="endnote"?{noteKind:"endnote"}:{},children:[{type:"paragraph",id:Y(),...u?{direction:u}:{},children:[{type:"text",text:t||"",marks:f}]}]},y=s.blockToYjsElement(m);if(y.setAttribute("id",r),i==="endnote"&&y.setAttribute("noteKind","endnote"),o&&a&&s.suggestions.setElementStructuralSuggestion(y,"insert",void 0,a,"Insert footnote"),s.getYNotesFragment().push([y]),!t){const b=y.toArray()[0];b instanceof S.XmlElement&&b.setAttribute("_emptyTextMarks",JSON.stringify(f))}}),It(s),{footnoteId:r,...a?{suggestionId:a}:{}}}function Yg(s,e,t){const n=St(s).get(e);if(!n)return!1;let i=null;for(const c of n.toArray())if(c instanceof S.XmlElement&&c.nodeName==="paragraph"){i=c;break}if(!i)return!1;const r=ae(i);if(!r)return!1;const o=s.getDocument(),a=[...o.notes??[],...o.children.filter(c=>c.type==="footnote")].find(c=>c.id===e)?.children.flatMap(c=>c.type==="paragraph"?c.children:[]).find(c=>c.type==="text"&&c.marks?.fontFamily)?.marks?.fontFamily??gt(s.getDocument().children),l={fontSize:ut,...a?{fontFamily:a}:{}};return s.transact(()=>{r.length>0&&r.delete(0,r.length),t.length>0?ne(r,0,t,l):i.setAttribute("_emptyTextMarks",JSON.stringify(l))}),!0}function qg(s,e,t,n,i=!1){if(!t)return{success:!1,replacements:0,error:"The text to find must not be empty."};let r=null;const o=m=>{if(!r){for(const y of m.toArray())if(y instanceof S.XmlElement){if(y.getAttribute("id")===e){r=y;return}o(y)}}};for(const m of St(s).values()){if(m.getAttribute("id")===e){r=m;break}if(o(m),r)break}if(!r)return{success:!1,replacements:0,error:`Note block '${e}' was not found.`};const a=ae(r);if(!a)return{success:!1,replacements:0,error:`Note block '${e}' does not contain editable text.`};const l=Z(a).map(m=>typeof m.insert=="string"?m.insert:"").join(""),c=[];let d=0;for(;d<=l.length-t.length;){const m=l.indexOf(t,d);if(m<0)break;c.push(m),d=m+t.length}if(c.length===0)return{success:!1,replacements:0,error:`No match found for ${JSON.stringify(t)} in note block '${e}'.`};if(!i&&c.length>1)return{success:!1,replacements:0,error:`Found ${c.length} matches for ${JSON.stringify(t)} in note block '${e}'. Include more surrounding context so it matches exactly one location, or use replace_all.`};const g=i?c:c.slice(0,1),u=s.suggestions.isSuggesting()?ce():null,p=u?s.suggestions.buildInlineMetadataMarks(u,"Replace footnote text"):null,h=m=>{let y=0;for(const b of Z(a)){if(typeof b.insert!="string")continue;const k=y+b.insert.length;if(m<k){const I={...b.attributes??{}};return delete I.insertion,delete I.deletion,delete I.suggestionId,delete I.suggestionLabel,delete I.suggestionCreatedAt,I}y=k}return{fontSize:ut}},f=new Map(g.map(m=>[m,h(m)]));return s.transact(()=>{for(const m of[...g].reverse()){const y=f.get(m)??{fontSize:ut};u&&p?(ie(a,m,t.length,{deletion:!0,...p}),n&&ne(a,m,n,{...y,insertion:!0,deletion:null,formatChange:null,...p})):(a.delete(m,t.length),n&&ne(a,m,n,y))}}),{success:!0,replacements:g.length,...u?{suggestionId:u}:{}}}function Jg(s,e){const t=St(s);return t.size===0?!1:(s.transact(()=>{for(const n of t.values())e==="endnote"?n.setAttribute("noteKind","endnote"):n.removeAttribute("noteKind")}),It(s),!0)}function Kg(s,e){const t=Dt(s).filter(i=>i.footnoteId===e),n=St(s).get(e);if(t.length===0&&!n)return!1;if(s.suggestions.isSuggesting()){const i=ce();return s.transact(()=>{for(const r of t)ie(r.yText,r.start,r.length,{deletion:!0,...s.suggestions.buildInlineMetadataMarks(i,"Delete footnote")});n&&s.suggestions.setElementStructuralSuggestion(n,"delete",void 0,i,"Delete footnote")}),!0}return s.transact(()=>{for(const i of[...t].sort((r,o)=>o.start-r.start))i.yText.delete(i.start,i.length);if(n){const i=n.parent;if(i){const r=i.toArray().indexOf(n);r>=0&&i.delete(r,1)}}}),It(s),!0}function ma(s,e,t){const n=a=>{const l=new Map;for(const c of a)c.id&&l.set(c.id,(l.get(c.id)??0)+1);return l},i=n(s),r=n(e),o=a=>a.id&&i.get(a.id)===1&&r.get(a.id)===1?`id:${a.id}`:`content:${t(a)}`;return{beforeKeys:s.map(o),afterKeys:e.map(o)}}function Ar(s,e){const t=s.length,n=e.length,i=Array.from({length:t+1},()=>Array(n+1).fill(0));for(let l=1;l<=t;l++)for(let c=1;c<=n;c++)s[l-1]===e[c-1]?i[l][c]=i[l-1][c-1]+1:i[l][c]=Math.max(i[l-1][c],i[l][c-1]);const r=[];let o=t,a=n;for(;o>0&&a>0;)s[o-1]===e[a-1]?(r.unshift(s[o-1]),o-=1,a-=1):i[o-1][a]>i[o][a-1]?o-=1:a-=1;return r}function Vg(s){let e=s,t=null;for(;e;){if(e instanceof S.XmlElement){const n=e.nodeName,i=e.getAttribute("id");if(n==="paragraph"&&i)return{blockId:i,offset:0};if(n==="list-item"&&(t=e),n==="list"&&i&&t){let r=0;for(let o=0;o<e.length;o++){const a=e.get(o);if(a===t)return{blockId:i,offset:r};if(a instanceof S.XmlElement&&a.nodeName==="list-item"){for(let l=0;l<a.length;l++){const c=a.get(l);if(c instanceof S.XmlText){r+=c.length;break}}r+=1}}return{blockId:i,offset:0}}}e=e.parent}return null}function Gg(s,e,t,n){const i=s.getArray("paragraphs"),r=i.toArray().findIndex(a=>a?.get("id")===e);if(r<0)return null;const o=i.get(r);if(!o)return null;if(t==="paragraph")return o.get("content");if(t==="list"&&n!==void 0){const a=o.get("items");return!a||n>=a.length?null:a.get(n)?.get("content")}return null}function Qg(s,e,t,n){const i=K(s,e);if(!i)return null;if(t==="paragraph"||t==="list-item")return ae(i);if(t==="list"&&n!==void 0){let r=0;for(let o=0;o<i.length;o++){const a=i.get(o);if(a instanceof S.XmlElement&&a.nodeName==="list-item"){if(r===n)return ae(a);r++}}}return null}function ba(s,e,t,n){return Qg(s,e,t,n)||(Tt(s)?Gg(s,e,t,n):null)}function ot(s,e,t){const n=z(t,s.block);if(!n||!n.id)return null;if(n.type==="paragraph"){const i=n,r=ba(e,n.id,"paragraph");if(!r)return null;const o=i.children.filter(c=>c.type==="text").reduce((c,d)=>c+d.text.length,0),a=Math.max(0,Math.min(s.offset,o)),l=S.createRelativePositionFromTypeIndex(r,a);return{blockId:n.id,textOffset:l}}if(n.type==="list"){const i=n;let r=-1,o=s.offset;if(s.offset,s.block!==n.id){let d=0;for(let g=0;g<i.children.length;g++){if(i.children[g].id===s.block){r=g,d+s.offset;break}d+=$n(i.children[g]),g<i.children.length-1&&(d+=1)}}if(r===-1){let d=s.offset;for(let g=0;g<i.children.length;g++){const u=$n(i.children[g]),p=g<i.children.length-1?1:0;if(d<=u){r=g,o=d;break}d-=u+p,g===i.children.length-1&&(r=g,o=u)}}r===-1&&(r=0,o=0);const a=ba(e,n.id,"list",r);if(!a)return null;const l=Math.max(0,Math.min(o,a.length)),c=S.createRelativePositionFromTypeIndex(a,l);return{blockId:n.id,textOffset:c}}return null}function Zg(s,e,t){const n=s.getArray("paragraphs");for(let i=0;i<n.length;i++){const r=n.get(i);if(!r)continue;const o=r.get("id");if(!o)continue;const a=r.get("type");if(a==="paragraph"&&r.get("content")===e)return{blockId:o,offset:0,yTextOffset:0};if(a==="list"){const l=r.get("items");if(!l)continue;const c=z(t,o);if(!c||c.type!=="list")continue;const d=c;let g=0;for(let u=0;u<l.length;u++){if(l.get(u)?.get("content")===e)return{blockId:o,offset:g,yTextOffset:0};u<d.children.length&&(g+=$n(d.children[u]),u<d.children.length-1&&(g+=1))}}}return null}function li(s,e){const t=S.createAbsolutePositionFromRelativePosition(s.textOffset,e);if(!t||!(t.type instanceof S.XmlText))return K(e,s.blockId)?{block:s.blockId,offset:0}:null;const n=t.index,i=t.type,r=Vg(i);if(r)return{block:r.blockId,offset:r.offset+n};if(Tt(e)){const o=he(e),a=Zg(e,i,o);if(a)return{block:a.blockId,offset:a.offset+n}}return K(e,s.blockId)?{block:s.blockId,offset:n}:null}function H(s,e,t){return{anchor:s.anchor?ot(s.anchor,e,t):null,focus:s.focus?ot(s.focus,e,t):null}}function wr(s,e){return{anchor:s.anchor?li(s.anchor,e):null,focus:s.focus?li(s.focus,e):null}}function vt(s){if(typeof window>"u")return null;try{return window.localStorage??null}catch(e){return console.warn(`[${s}] localStorage unavailable:`,e),null}}function eu(s,e){if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(s[t]!==e[t])return!1;return!0}class Tr{constructor(e,t,n=!1,i){this.destroyed=!1,this.handleDocumentUpdate=()=>{this.cachedBaseUpdate=null,this.cachedBaseUpdateV2=null},this.cachedBaseUpdate=null,this.cachedBaseUpdateV2=null,this.proposals=new Map,this.suggestionMeta=new Map,this.paragraphSuggestions=new Map,this.tableCellSuggestions=new Map,this.undoStack=[],this.redoStack=[],this.listeners=new Set,this.conversationId=null,this.ydoc=e,this.ydoc.on("update",this.handleDocumentUpdate),this.documentId=t||"default",this.conversationId=i||null,this.disableLocalStorage=n,this.storageKey=this.computeStorageKey();const r=e.getXmlFragment("content");this.undoManager=new S.UndoManager(r,{trackedOrigins:new Set}),this.documentId,this.conversationId,this.storageKey,n?this.clearDocumentProposalCacheIfRemote():this.loadFromLocalStorage(),tu(this.documentId,this)}getBaseUpdate(){return this.cachedBaseUpdate||(this.cachedBaseUpdate=S.encodeStateAsUpdate(this.ydoc)),this.cachedBaseUpdate}seedForkFromBase(e){return this.cachedBaseUpdateV2||(this.cachedBaseUpdateV2=S.encodeStateAsUpdateV2(this.ydoc)),S.applyUpdateV2(e,this.cachedBaseUpdateV2),e}computeStorageKey(){return this.conversationId?`proposals_${this.documentId}_${this.conversationId}`:`proposals_${this.documentId}`}clearDocumentProposalCacheIfRemote(){if(!this.isLikelyRemoteDocumentId())return;const e=vt("DetachedSuggestionStore");if(!e)return;const t=`proposals_${this.documentId}`,n=[];for(let i=0;i<e.length;i++){const r=e.key(i);r&&(r===t||r.startsWith(`${t}_`))&&n.push(r)}for(const i of n)e.removeItem(i)}isLikelyRemoteDocumentId(){const e=this.documentId.replace(/-/g,"");return/^[a-z0-9]{16}$/i.test(e)?!0:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(this.documentId)}getYDoc(){return this.ydoc}getDocumentId(){return this.documentId}getConversationId(){return this.conversationId}setOnSuggestionsChanged(e){this.onProposalsChanged=e}setConversation(e,t){this.conversationId!==e&&(this.conversationId,this.conversationId=e,this.storageKey=this.computeStorageKey(),this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),this.tableCellSuggestions.clear(),t&&(Object.keys(t.proposals||{}).length>0||Object.keys(t.metadata||{}).length>0)?(Object.keys(t.proposals||{}).length,this.loadFromServerData(t)):this.disableLocalStorage||this.loadFromLocalStorage(),this.notifyListeners())}serializeForServer(){const e={proposals:{},metadata:{},paragraphSuggestions:{}},t=new Set;for(const[n,i]of this.suggestionMeta)i.status==="pending"&&t.add(n);for(const[n,i]of this.proposals)t.has(n)&&(e.proposals[n]=btoa(String.fromCharCode(...i)));for(const[n,i]of this.suggestionMeta){if(!t.has(n))continue;const r={...i};r.anchors&&(r.anchors=r.anchors.map(o=>({...o,from:o.from?btoa(String.fromCharCode(...o.from)):o.from,to:o.to?btoa(String.fromCharCode(...o.to)):o.to}))),e.metadata[n]=r}for(const[n,i]of this.paragraphSuggestions){const r=i.filter(o=>t.has(o));r.length>0&&(e.paragraphSuggestions[n]=r)}return e}loadFromServerData(e,t){if(this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),!!e){if(Object.keys(e.proposals||{}).length,Object.keys(e.metadata||{}).length,t?.persistAndNotify,e.proposals)for(const[n,i]of Object.entries(e.proposals)){const r=Uint8Array.from(atob(i),o=>o.charCodeAt(0));this.proposals.set(n,r)}if(e.metadata)for(const[n,i]of Object.entries(e.metadata)){const r={...i};r.anchors&&(r.anchors=r.anchors.map(o=>({...o,from:o.from?Uint8Array.from(atob(o.from),a=>a.charCodeAt(0)):o.from,to:o.to?Uint8Array.from(atob(o.to),a=>a.charCodeAt(0)):o.to}))),this.suggestionMeta.set(n,r)}if(e.paragraphSuggestions)for(const[n,i]of Object.entries(e.paragraphSuggestions))this.paragraphSuggestions.set(n,i);t?.persistAndNotify&&(this.saveToLocalStorage(),this.notifyListeners())}}static getOldFormatProposals(e){const t=vt("DetachedSuggestionStore");if(!t)return null;const n=`proposals_${e}`;try{const i=t.getItem(n);if(!i)return null;const r=JSON.parse(i);return!r.proposals||Object.keys(r.proposals).length===0?null:{proposals:r.proposals||{},metadata:r.metadata||{},paragraphSuggestions:r.paragraphSuggestions||{}}}catch(i){return console.error("[DetachedSuggestionStore] Failed to read old format proposals:",i),null}}static clearOldFormatProposals(e){const t=vt("DetachedSuggestionStore");if(!t)return;const n=`proposals_${e}`;try{t.removeItem(n)}catch(i){console.error("[DetachedSuggestionStore] Failed to clear old format proposals:",i)}}static clearAllStoredSuggestions(e){const t=vt("DetachedSuggestionStore");if(!t)return;const n=`proposals_${e}`,i=[];for(let r=0;r<t.length;r++){const o=t.key(r);o&&(o===n||o.startsWith(`${n}_`))&&i.push(o)}try{for(const r of i)t.removeItem(r)}catch(r){console.error("[DetachedSuggestionStore] Failed to clear stored proposals for document:",e,r)}}loadFromLocalStorage(){const e=vt("DetachedSuggestionStore");if(e)try{const t=e.getItem(this.storageKey);if(t){const n=JSON.parse(t);if(Object.keys(n.proposals||{}).length,Object.keys(n.metadata||{}).length,n.proposals)for(const[i,r]of Object.entries(n.proposals)){const o=Uint8Array.from(atob(r),a=>a.charCodeAt(0));this.proposals.set(i,o)}if(n.metadata)for(const[i,r]of Object.entries(n.metadata)){const o=r;o.anchors&&(o.anchors=o.anchors.map(a=>({...a,from:a.from?Uint8Array.from(atob(a.from),l=>l.charCodeAt(0)):a.from,to:a.to?Uint8Array.from(atob(a.to),l=>l.charCodeAt(0)):a.to}))),this.suggestionMeta.set(i,o)}if(n.paragraphSuggestions)for(const[i,r]of Object.entries(n.paragraphSuggestions))this.paragraphSuggestions.set(i,r);Array.from(this.proposals.keys()),Array.from(this.suggestionMeta.keys()),Array.from(this.suggestionMeta.values()).filter(i=>i.status==="pending").length,Array.from(this.suggestionMeta.values()).filter(i=>i.status==="accepted").length,Array.from(this.suggestionMeta.values()).filter(i=>i.status==="rejected").length,Array.from(this.suggestionMeta.values()).map(i=>({id:i.id,status:i.status}))}else this.storageKey}catch(t){console.error("[DetachedSuggestionStore] Failed to load from localStorage:",t)}}saveToLocalStorage(){if(this.disableLocalStorage){this.onProposalsChanged&&this.onProposalsChanged();return}const e=vt("DetachedSuggestionStore");if(!e){this.onProposalsChanged&&this.onProposalsChanged();return}try{const t={proposals:{},metadata:{},paragraphSuggestions:{}};for(const[n,i]of this.proposals)t.proposals[n]=btoa(String.fromCharCode(...i));for(const[n,i]of this.suggestionMeta){const r={...i};r.anchors&&(r.anchors=r.anchors.map(o=>({...o,from:o.from?btoa(String.fromCharCode(...o.from)):o.from,to:o.to?btoa(String.fromCharCode(...o.to)):o.to}))),t.metadata[n]=r}for(const[n,i]of this.paragraphSuggestions)t.paragraphSuggestions[n]=i;e.setItem(this.storageKey,JSON.stringify(t)),this.storageKey,Object.keys(t.proposals).length,Object.keys(t.metadata).length,Object.values(t.metadata).filter(n=>n.status==="pending").length,Object.values(t.metadata).filter(n=>n.status==="accepted").length,Object.values(t.metadata).filter(n=>n.status==="rejected").length,Object.keys(t.metadata),this.onProposalsChanged&&this.onProposalsChanged()}catch(t){console.error("[DetachedSuggestionStore] Failed to save to localStorage:",t)}}cleanupOldProposals(){const e=Date.now(),t=24*60*60*1e3;for(const[n,i]of this.suggestionMeta)e-i.createdAt>t&&(this.proposals.delete(n),this.suggestionMeta.delete(n),this.removeProposalFromParagraphs(n));this.saveToLocalStorage()}createSuggestion(e,t,n={}){const i=this.seedForkFromBase(new S.Doc),r=S.encodeStateVector(i);let o=[];i.transact(()=>{o=t(i)},"proposal-edit");const a=S.encodeStateAsUpdate(i,r);return this.proposals.set(e,a),this.suggestionMeta.set(e,{id:e,authorId:n.authorId||"system",authorType:n.authorType||"ai",createdAt:Date.now(),status:"pending",anchors:o,...n}),this.saveToLocalStorage(),this.notifyListeners(),o.length,e}createSuggestionFromToolCall(e,t){return this.createSuggestion(this.generateId(),n=>t(n,e),{authorType:"ai",toolCallAction:e,description:`AI: ${e.name}`})}createTextDeletion(e,t,n,i,r,o={}){return this.createSuggestion(e,a=>{const l=K(a,t);if(!l)return console.warn(`Paragraph ${t} not found for text deletion`),[];const c=ae(l);return c?(c.delete(n,i),[{kind:"delete",paragraphId:t,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(c,n,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(c,n+i,0)),text:r}]):(console.warn(`No text content found in paragraph ${t}`),[])},{...o,id:e})}createTextInsertion(e,t,n,i,r={},o={}){const a={...r,proposalId:e};return this.createSuggestion(e,l=>{const c=K(l,t);if(!c)return console.warn(`Paragraph ${t} not found for text insertion`),[];const d=ae(c);return d?(ne(d,n,i,a),[{kind:"insert",paragraphId:t,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(d,n,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(d,n+i.length,0)),text:i}]):(console.warn(`No text content found in paragraph ${t}`),[])},{...o,id:e})}createTextReplacement(e,t,n,i,r,o={},a,l={}){const c={...o,proposalId:e};return this.createSuggestion(e,d=>{const g=K(d,t);if(!g)return console.warn(`Paragraph ${t} not found for text replacement`),[];const u=ae(g);return u?(u.delete(n,i),ne(u,n,r,c),[{kind:"replace",paragraphId:t,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(u,n,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(u,n+r.length,0)),text:r,oldText:a}]):(console.warn(`No text content found in paragraph ${t}`),[])},{...l,id:e})}createPositionAwareInsertion(e,t,n,i,r={}){const o=this.generateId();return this.suggestionMeta.set(o,{id:o,authorId:r.authorId||"system",authorType:r.authorType||"ai",createdAt:Date.now(),status:"pending",insertionContext:{paragraphId:e,content:t,mustBeAfter:n,mustBeBefore:i},...r}),this.saveToLocalStorage(),this.notifyListeners(),n.length,i.length,o}materializeWithSuggestion(e){const t=this.proposals.get(e);if(!t)return null;const n=new S.Doc;return this.seedForkFromBase(n),S.applyUpdate(n,t),n}withMaterializedSuggestion(e,t){const n=this.materializeWithSuggestion(e);return n?t(n):null}expandPositionAwarePredecessors(e){const t=new Map;for(const r of this.suggestionMeta.values()){const o=r.insertionContext;o&&t.set(o.paragraphId,o)}const n=new Set,i=[...e.mustBeAfter];for(;i.length>0;){const r=i.pop();if(n.has(r))continue;n.add(r);const o=t.get(r);o&&i.push(...o.mustBeAfter)}return n}applyPositionAwareInsertionToDoc(e,t,n){const i=n.insertionContext;if(!i)return;const r=this.expandPositionAwarePredecessors(i),o=e.getXmlFragment("content");let a=0;for(let c=o.length-1;c>=0;c--){const d=o.get(c);if(!(d instanceof S.XmlElement))continue;const g=d.getAttribute("id");if(g&&r.has(g)){a=c+1;break}}const l=ya(i.content,i.paragraphId,t);o.insert(a,[l])}materializeWithSuggestions(e){const t=new S.Doc;this.seedForkFromBase(t);for(const n of e){const i=this.suggestionMeta.get(n);if(!(i&&i.status==="accepted"))if(i?.insertionContext)this.applyPositionAwareInsertionToDoc(t,n,i);else{const r=this.proposals.get(n);if(r){const o=S.encodeStateAsUpdate(t);he(t),S.applyUpdate(t,r);const a=S.encodeStateAsUpdate(t);if(he(t),!!eu(o,a)&&i&&i.status==="pending")if(i.toolCallAction?.name==="remove_block"){const l=i.toolCallAction.arguments.id,c=G(t,l);if(c){const{yParent:d,index:g}=c;d.delete(g,1)}}else i.anchors&&i.anchors.length>0?console.warn("[DetachedSuggestionStore] Anchor-based regeneration not yet implemented for:",n):console.warn("[DetachedSuggestionStore] Cannot regenerate proposal without sufficient metadata:",n)}}}return t}acceptProposal(e){const t=this.suggestionMeta.get(e);if(!t)return!1;if(t.insertionContext){const n=this.acceptPositionAwareInsertion(e,t);return n&&this.recordAction({type:"accept",suggestionId:e,timestamp:Date.now()}),this.notifyListeners(),n}else{const n=this.proposals.get(e);if(!n)return!1;const i=`proposal-${e}`;this.undoManager.trackedOrigins.add(i);const r=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{S.applyUpdate(this.ydoc,n),this.ensureTrailingParagraphInTransaction(r)},i),this.undoManager.stopCapturing(),t.status="accepted",this.suggestionMeta.set(e,t),this.saveToLocalStorage();const o={type:"accept",suggestionId:e,timestamp:Date.now()};return o.suggestionId,this.undoStack.length,this.recordAction(o),this.notifyListeners(),!0}}acceptPositionAwareInsertion(e,t){const n=t.insertionContext,i=this.ydoc.getXmlFragment("content"),r=this.expandPositionAwarePredecessors(n);let o=0;const a=new Set;for(let c=0;c<i.length;c++){const d=i.get(c);if(d instanceof S.XmlElement){const g=d.getAttribute("id");g&&a.add(g)}}for(let c=i.length-1;c>=0;c--){const d=i.get(c);if(d instanceof S.XmlElement){const g=d.getAttribute("id");if(g&&r.has(g)){o=c+1;break}}}for(let c=0;c<i.length;c++){const d=i.get(c);if(d instanceof S.XmlElement){const g=d.getAttribute("id");if(g&&n.mustBeBefore.includes(g)){c<o&&(o=c);break}}}const l=`proposal-${e}`;return this.undoManager.trackedOrigins.add(l),this.ydoc.transact(()=>{const c=ya(n.content,n.paragraphId,e);i.insert(o,[c]),this.ensureTrailingParagraphInTransaction(i)},l),t.status="accepted",this.suggestionMeta.set(e,t),this.saveToLocalStorage(),this.notifyListeners(),!0}ensureTrailingParagraph(){const e=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{this.ensureTrailingParagraphInTransaction(e)})}ensureTrailingParagraphInTransaction(e){if(e.length===0)return;const t=e.get(e.length-1);if(!(t instanceof S.XmlElement)||t.nodeName==="paragraph")return;const n=new S.XmlElement("paragraph");n.setAttribute("id",Y());const i=new S.XmlText;n.insert(0,[i]),e.insert(e.length,[n])}acceptSuggestions(e){let t=!0;const n=[],i=()=>{if(n.length===0)return;const r=[...n];n.length=0;const o=this.ydoc.getXmlFragment("content");this.ydoc.transact(()=>{for(const a of r){const l=this.proposals.get(a);l?S.applyUpdate(this.ydoc,l):t=!1}this.ensureTrailingParagraphInTransaction(o)},"accept-proposals");for(const a of r){const l=this.suggestionMeta.get(a);l&&(l.status="accepted",this.suggestionMeta.set(a,l))}};for(const r of e)this.suggestionMeta.get(r)?.insertionContext?(i(),this.acceptProposal(r)||(t=!1)):n.push(r);return i(),this.saveToLocalStorage(),this.notifyListeners(),t}deleteSuggestion(e){this.proposals.delete(e),this.suggestionMeta.delete(e),this.removeProposalFromParagraphs(e),this.saveToLocalStorage()}rejectProposal(e){const t=this.suggestionMeta.get(e);return t?(t.status="rejected",this.suggestionMeta.set(e,t),this.saveToLocalStorage(),this.notifyListeners(),this.recordAction({type:"reject",suggestionId:e,timestamp:Date.now()}),!0):!1}unrejectProposal(e){const t=this.suggestionMeta.get(e);return!t||t.status!=="rejected"?!1:(t.status="pending",this.suggestionMeta.set(e,t),this.saveToLocalStorage(),this.recordAction({type:"unreject",suggestionId:e,timestamp:Date.now()}),this.notifyListeners(),!0)}rejectSuggestions(e){let t=!0;for(const n of e)this.suggestionMeta.has(n)?(this.proposals.delete(n),this.suggestionMeta.delete(n),this.removeProposalFromParagraphs(n)):t=!1;return this.saveToLocalStorage(),this.notifyListeners(),t}resolveAnchors(e){return this.resolveAnchorsAgainstDoc(e,this.ydoc)}resolveAnchorsAgainstDoc(e,t){const n=this.suggestionMeta.get(e);if(!n||!n.anchors)return[];const i=[];for(const r of n.anchors){const o=r.from?S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(r.from),t):null,a=r.to?S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(r.to),t):null;i.push({kind:r.kind,paragraphId:r.paragraphId,fromIndex:o?.index??null,toIndex:a?.index??null,text:r.text})}return i}checkConflicts(e){const t=this.suggestionMeta.get(e);if(!t)return"stale";if(t.anchors&&t.anchors.length>0){const n=this.resolveAnchors(e);for(let i=0;i<t.anchors.length;i++){const r=t.anchors[i],o=n[i];if(r.paragraphId&&o.fromIndex===null)return"conflicted"}}try{const n=this.materializeWithSuggestion(e);if(!n)return"stale";const i=vn(this.ydoc),r=vn(n),o=t.anchors?.filter(a=>a.kind==="insert"&&!a.paragraphId).length||0;return Math.abs(r-i)>o+1?"conflicted":"clean"}catch{return"conflicted"}}getAllSuggestions(){return new Map(this.suggestionMeta)}getSuggestion(e){return this.suggestionMeta.get(e)}getSuggestionCount(){return this.suggestionMeta.size}getPendingSuggestions(){const e=new Map;for(const[t,n]of this.suggestionMeta)n.status==="pending"&&e.set(t,n);return e}getParagraphIdsWithPendingProposals(){const e=new Set;for(const[n,i]of this.suggestionMeta)i.status==="pending"&&e.add(n);if(e.size===0)return[];const t=[];for(const[n,i]of this.paragraphSuggestions)!n||i.length===0||i.some(r=>e.has(r))&&t.push(n);return t}clearAllProposals(){this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),this.disableLocalStorage||vt("DetachedSuggestionStore")?.removeItem(this.storageKey),this.notifyListeners()}destroy(){this.destroyed||(this.destroyed=!0,this.ydoc.off("update",this.handleDocumentUpdate),this.undoManager.destroy(),this.listeners.clear(),this.onProposalsChanged=void 0,this.cachedBaseUpdate=null,this.cachedBaseUpdateV2=null,this.proposals.clear(),this.suggestionMeta.clear(),this.paragraphSuggestions.clear(),this.tableCellSuggestions.clear(),this.undoStack.length=0,this.redoStack.length=0,Pr.get(this.documentId)===this&&Pr.delete(this.documentId))}setSuggestionsForParagraph(e,t){this.paragraphSuggestions.set(e,t),this.saveToLocalStorage(),`${t.length}${e}`}getSuggestionsForParagraph(e){return this.paragraphSuggestions.get(e)||[]}setTableCellSuggestionMap(e,t){this.tableCellSuggestions.set(e,t),`${e}`,t.size}getProposalForTableCell(e,t){return this.tableCellSuggestions.get(e)?.get(t)}getTableCellSuggestionMap(e){return this.tableCellSuggestions.get(e)}async recomputeProposalsForParagraph(e){const t=this.getSuggestionsForParagraph(e).filter(d=>this.suggestionMeta.get(d)?.status==="pending");if(t.length===0)return;const{createGranularSuggestionsForParagraph:n}=await Promise.resolve().then(()=>Su),{findBlockById:i}=await import("./index-Bf14eTEW.js").then(d=>d.a0),r=he(this.ydoc),o=i(r,e);if(!o){console.warn(`[DetachedSuggestionStore] Paragraph ${e} not found in document`);return}if(o.type!=="paragraph")return;const a=new S.Doc;this.seedForkFromBase(a);for(const d of t){const g=this.proposals.get(d);g&&S.applyUpdate(a,g)}const l=he(a),c=i(l,e);if(c&&c.type==="paragraph")for(const d of t)this.deleteSuggestion(d)}findParagraphForProposal(e){for(const[t,n]of this.paragraphSuggestions)if(n.includes(e))return t;return null}removeProposalFromParagraphs(e){for(const[t,n]of this.paragraphSuggestions){const i=n.filter(r=>r!==e);i.length!==n.length&&(i.length===0?this.paragraphSuggestions.delete(t):this.paragraphSuggestions.set(t,i))}}generateId(){return`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async regenerateProposalFromDiff(e,t,n){const i=this.suggestionMeta.get(e);if(!i){console.warn("[DetachedSuggestionStore] Cannot regenerate - no metadata for proposal:",e);return}if(i.insertionContext)return;if(i.toolCallAction?.name==="remove_block"){const d=i.toolCallAction.arguments.id;K(this.ydoc,d);const g=new S.Doc;this.seedForkFromBase(g);const u=S.encodeStateVector(g);vn(g),g.transact(()=>{if(Tt(g)){const h=g.getArray("paragraphs");for(let f=0;f<h.length;f++)if(h.get(f).get("id")===d){h.delete(f,1);break}}else{const h=G(g,d);if(h){const{yParent:f,index:m}=h;f.delete(m,1)}}}),vn(g);const p=S.encodeStateAsUpdate(g,u);this.proposals.set(e,p),p.length;return}const r=new S.Doc;S.applyUpdate(r,t);const o=new S.Doc;S.applyUpdate(o,n);const a=he(r),l=he(o);if(a.children.length===l.children.length)for(let d=0;d<a.children.length;d++){const g=a.children[d],u=l.children[d];if(g.type!=="paragraph"||u.type!=="paragraph")continue;const p=g,h=u,f=c(p),m=c(h);if(f!==m&&p.id===h.id){p.id;const y=new S.Doc;this.seedForkFromBase(y);const b=S.encodeStateVector(y),{analyzeParagraphDiff:k}=await import("./ParagraphDiffAnalysis-DrmStvmz.js").then(x=>x.P),I=k(f,m).diffs;y.transact(()=>{let x=null;if(Tt(y)){const A=y.getArray("paragraphs");for(let C=0;C<A.length;C++){const F=A.get(C);if(F.get("id")===p.id){x=F.get("content");break}}}else{const A=K(y,p.id);A&&(x=ae(A))}if(x){const A=[];for(const E of h.children)if(E.type==="text")for(let P=0;P<E.text.length;P++)A.push({node:E,indexInNode:P,marks:E.marks||{}});let C=0,F=0;for(const[E,P]of I)if(E===0)C+=P.length,F+=P.length;else if(E===-1)x.delete(C,P.length);else if(E===1){for(let B=0;B<P.length;B++){const w=A[F+B];if(w){const T={...w.marks,proposalId:e};ne(x,C+B,P[B],T)}}C+=P.length,F+=P.length}}});const v=S.encodeStateAsUpdate(y,b);this.proposals.set(e,v),this.saveToLocalStorage(),this.notifyListeners();return}}function c(d){return d.children.filter(g=>g.type==="text").map(g=>g.text).join("")}}recordAction(e){this.undoStack.push(e),e.type,e.suggestionId,this.undoStack.length,this.undoStack.map(t=>t.suggestionId),this.redoStack=[]}clearHistory(){this.undoStack=[],this.redoStack=[]}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}async undoLastAction(){if(this.undoStack.length===0)return!1;const e=this.undoStack.pop();switch(this.redoStack.push(e),e.type){case"accept":{if(this.undoManager.canUndo()){const t=this.getBaseUpdate();this.undoManager.undo();const n=this.getBaseUpdate();await this.regenerateProposalFromDiff(e.suggestionId,n,t);const i=this.suggestionMeta.get(e.suggestionId);return i&&(i.status="pending",this.suggestionMeta.set(e.suggestionId,i),this.saveToLocalStorage(),this.notifyListeners()),!0}return!1}case"reject":{const t=this.suggestionMeta.get(e.suggestionId);return t?(t.status="pending",this.suggestionMeta.set(e.suggestionId,t),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}case"unreject":{const t=this.suggestionMeta.get(e.suggestionId);return t?(t.status="rejected",this.suggestionMeta.set(e.suggestionId,t),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}}return!1}redoLastAction(){if(this.redoStack.length===0)return!1;const e=this.redoStack.pop();switch(this.undoStack.push(e),e.type){case"accept":{if(this.undoManager.canRedo()){this.undoManager.redo();const t=this.suggestionMeta.get(e.suggestionId);return t&&(t.status="accepted",this.suggestionMeta.set(e.suggestionId,t),this.saveToLocalStorage(),this.notifyListeners()),!0}return!1}case"reject":{const t=this.suggestionMeta.get(e.suggestionId);return t?(t.status="rejected",this.suggestionMeta.set(e.suggestionId,t),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}case"unreject":{const t=this.suggestionMeta.get(e.suggestionId);return t?(t.status="pending",this.suggestionMeta.set(e.suggestionId,t),this.saveToLocalStorage(),this.notifyListeners(),!0):!1}}return!1}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notifyListeners(){this.listeners.forEach(e=>e())}}function ya(s,e,t,n){if(s.type==="list"){const l=new S.XmlElement("list");return l.setAttribute("id",e),l.setAttribute("variant",s.variant??"unordered"),s.startNumber!==void 0&&l.setAttribute("startNumber",String(s.startNumber)),s.numberingChainId&&l.setAttribute("numberingChainId",s.numberingChainId),s.children.forEach(c=>{const d=new S.XmlElement("list-item");Ct(d,c),d.setAttribute("id",c.id||Y()),c.checked!==void 0&&d.setAttribute("checked",String(c.checked)),typeof c.indentLevel=="number"&&c.indentLevel>0&&d.setAttribute("indentLevel",String(c.indentLevel)),c.direction!==void 0&&d.setAttribute("direction",c.direction);const g=new S.XmlText;let u=0;c.children.forEach(p=>{if(p.type==="text"){const h=p,f=Cr(h.marks,t);g.insert(u,h.text,f),u+=h.text.length}}),d.insert(0,[g]),l.push([d])}),l}if(s.type==="table"){const l=s,c=new S.XmlElement("table");c.setAttribute("id",e),l.columnWidths&&c.setAttribute("columnWidths",JSON.stringify(l.columnWidths)),l.hasHeader&&c.setAttribute("hasHeader","true"),l.tableWidth!==void 0&&c.setAttribute("tableWidth",String(l.tableWidth)),l.align&&c.setAttribute("align",l.align),l.borderColor&&c.setAttribute("borderColor",l.borderColor),l.borderWidth!==void 0&&c.setAttribute("borderWidth",String(l.borderWidth)),l.cellPadding!==void 0&&c.setAttribute("cellPadding",String(l.cellPadding));for(const d of l.children){const g=new S.XmlElement("table-row");g.setAttribute("id",d.id||Y());for(const u of d.children){const p=new S.XmlElement("table-cell");p.setAttribute("id",u.id||Y()),u.verticalAlign&&p.setAttribute("verticalAlign",u.verticalAlign),u.backgroundColor&&p.setAttribute("backgroundColor",u.backgroundColor);for(const h of u.children)if(h.type==="paragraph"){const f=h,m=new S.XmlElement("paragraph");m.setAttribute("id",f.id||Y()),f.heading&&m.setAttribute("heading",String(f.heading)),f.align&&m.setAttribute("align",f.align);const y=new S.XmlText;let b=0;for(const k of f.children)if(k.type==="text"){const I=k,v=Cr(I.marks,t);ne(y,b,I.text,v),b+=I.text.length}m.insert(0,[y]),p.push([m])}g.push([p])}c.push([g])}return c}if(s.type==="code"){const l=s,c=new S.XmlElement("code");c.setAttribute("id",e),l.language&&c.setAttribute("language",l.language),l.renderDiagram!==void 0&&c.setAttribute("renderDiagram",String(l.renderDiagram)),l.showDiagramSource!==void 0&&c.setAttribute("showDiagramSource",String(l.showDiagramSource));const d=new S.XmlText;return c.insert(0,[d]),ne(d,0,l.content||""),c}if(s.type==="math"){const l=s,c=new S.XmlElement("math");c.setAttribute("id",e),l.displayMode&&c.setAttribute("displayMode",l.displayMode),l.align&&c.setAttribute("align",l.align);const d=new S.XmlText;return c.insert(0,[d]),ne(d,0,l.content||""),c}if(s.type==="image"){const l=s,c=new S.XmlElement("image");return c.setAttribute("id",e),c.setAttribute("src",l.src),l.sourceUrl&&c.setAttribute("sourceUrl",l.sourceUrl),c.setAttribute("width",String(l.width)),c.setAttribute("height",String(l.height)),l.alt&&c.setAttribute("alt",l.alt),l.align&&c.setAttribute("align",l.align),c}if(s.type==="page-break"){const l=new S.XmlElement("page-break");return l.setAttribute("id",e),l}if(s.type==="toc")return Se({...s,id:e});if(s.type==="section-break"){const l=new S.XmlElement("section-break");return l.setAttribute("id",e),s.layout&&l.setAttribute("layout",JSON.stringify(s.layout)),s.breakType&&l.setAttribute("breakType",s.breakType),l}const i=new S.XmlElement("paragraph"),r=s;i.setAttribute("id",e),r.heading&&i.setAttribute("heading",String(r.heading)),r.align&&i.setAttribute("align",r.align);const o=new S.XmlText;let a=0;return r.children.forEach(l=>{if(l.type==="text"){const c=l,d=Cr(c.marks,t);ne(o,a,c.text,d),a+=c.text.length}}),i.insert(0,[o]),i}function Cr(s,e,t){return{...s||{},proposalId:e}}const Pr=new Map;function tu(s,e){Pr.set(s,e)}const nu=new Set(["Arial","Arial, sans-serif"]);function Br(s){if(typeof s!="string")return;const e=s.trim();if(!(!e||nu.has(e)))return e}function ci(s){const e={};for(const t of In)if(s[t]!==void 0)if(t==="fontFamily"){const n=Br(s[t]);n&&(e[t]=n)}else(t==="color"||t==="backgroundColor")&&typeof s[t]=="string"&&/^#[0-9a-fA-F]{6}$/.test(s[t])?e[t]=s[t].toLowerCase():e[t]=s[t];return e}const ka=as.filter(s=>!In.includes(s));function _t(s){const e=ci(s);for(const t of ka)s[t]!==void 0&&(e[t]=s[t]);return e}function iu(s){const e=Sa(s);for(const t of ka)s[t]!==void 0&&(e[t]=s[t]);return e}function Mr(s,e){return JSON.stringify(_t(s||{}))===JSON.stringify(_t(e||{}))}function Sa(s){const e=ci(s);e.docxRunPropertyResets=s.docxRunPropertyResets??null;for(const t of In)t in e||(e[t]=null);return e}function Er(s,e){const t=ci(s||{}),n=ci(e||{});return JSON.stringify(t)===JSON.stringify(n)}function Ia(s,e){for(const t of An){const n=s[t],i=e[t];if(t==="link"||t==="backgroundColor"||t==="color"){const r=l=>typeof l=="string"&&/^#[0-9a-fA-F]{6}$/.test(l),o=r(n)?n.toLowerCase():n,a=r(i)?i.toLowerCase():i;if(o!==a)return!1}else if(t==="fontFamily"){if(Br(n)!==Br(i))return!1}else if(t==="fontSize"){if((typeof n=="number"?n:void 0)!==(typeof i=="number"?i:void 0))return!1}else if(!!n!=!!i)return!1}return!0}class va{constructor(){this.toolCalls=[]}addToolCalls(e,t){const n=Date.now();if(e.actions)for(const i of e.actions)this.toolCalls.push({toolCall:i,toolCallId:t,timestamp:n})}getAllToolCalls(){return this.toolCalls}clear(){this.toolCalls=[]}}function at(s,e){return{...s,id:e}}function ru(s,e,t){const n=new Set(s),i=r=>{if(r){if(r.block.type==="table"&&r.block.id){n.add(r.block.id);return}for(let o=r.containerPath.length-1;o>=0;o--){const a=r.containerPath[o];if((t.get(a)?.block??e.get(a)?.block)?.type==="table"){n.add(a);break}}}};for(const r of s)i(t.get(r)),i(e.get(r));return n}function xa(s){return JSON.stringify(s.children.map(e=>[e.id,e.children.map(t=>[t.id,t.rowSpan??1,t.colSpan??1])]))}function Aa(s){return JSON.stringify({...s,children:s.children.map(e=>({...e,children:e.children.map(t=>({...t,children:[]}))}))})}function su(s,e){return{...e,children:e.children.map((t,n)=>({...t,children:t.children.map((i,r)=>({...i,children:s.children[n].children[r].children}))}))}}function $r(s,e,t){const n=t?.affectedBlockIds?new Set(Array.from(t.affectedBlockIds).filter(N=>typeof N=="string"&&N.length>0)):null,i=e.getYDoc(),r=Array.from(e.getPendingSuggestions().keys()),o=r.length>0?e.materializeWithSuggestions(r):i,a=t?.precomputedLiveDocSchema??he(i),l=t?.precomputedCurrentDocSchema??(o===i?a:he(o)),c=t?.precomputedFinalDocSchema??he(s),d=qe(a),g=qe(l),u=qe(c),p=n?ru(n,g,u):null,h=new Set;for(const N of new Set([...d.keys(),...u.keys()])){const L=d.get(N)?.block,_=u.get(N)?.block;L?.type!=="table"&&_?.type!=="table"||(L?.type!=="table"||_?.type!=="table"||xa(L)!==xa(_)||Tn(L,_))&&h.add(N)}if(p)for(const[N,L]of new Map([...d,...u]))L.containerPath.some(_=>p.has(_))&&p.add(N);const f=new Set(Array.from(t?.atomicReplaceBlockIds??[]).filter(N=>typeof N=="string"&&N.length>0)),m=new Map;for(const N of t?.replacementBlockMatches??[])typeof N?.currentBlockId!="string"||N.currentBlockId.length===0||typeof N?.finalBlockId!="string"||N.finalBlockId.length===0||m.set(N.finalBlockId,N.currentBlockId);const y=N=>{const L=m.get(N);return L&&d.has(L)?L:N},b=!!p&&p.size>0,k=e.getPendingSuggestions();if(b){const N=new Set;for(const L of p){const _=e.getSuggestionsForParagraph(L);for(const $ of _)k.has($)&&N.add($)}for(const L of N)e.deleteSuggestion(L)}else for(const[N]of k)e.deleteSuggestion(N);const I=[],v=new Set,x=new Set,A=g;for(const[N,L]of d){const _=L.block;if(_.type!=="list"||u.has(N)||_.children.length===0||b&&!p.has(N)||L.containerPath.some(U=>h.has(U)))continue;const $=A.get(N)?.block,R=(t?.listUnwrapMemberIds?.get(N)??($?.type==="list"?$.children:_.children).map(U=>U.id)).map(U=>u.get(U)).filter(U=>!!U),M=R[0];if(!M||R.some((U,q)=>U.containerPath.join("/")!==L.containerPath.join("/")||q>0&&U.indexInParent<=R[q-1].indexInParent))continue;const O=M.containerPath.at(-1),D=O?u.get(O)?.block:null,X=(D&&"children"in D?D.children:c.children).slice(M.indexInParent,R.at(-1).indexInParent+1);if(X.some(U=>!U.id||d.has(U.id)))continue;const j=`prop_${Y()}`;e.createSuggestion(j,U=>{const q=G(U,N);return q?(q.yParent.delete(q.index,1),q.yParent.insert(q.index,X.map(oe=>Se(oe))),[{kind:"replace",paragraphId:N,text:"Remove list markers"}]):[]},{authorType:"ai",blockSequencePreview:{blockId:N,blocks:X},description:"AI: remove list markers"}),I.push(j),v.add(N),e.setSuggestionsForParagraph(N,[j]);for(const U of X)x.add(U.id),e.setSuggestionsForParagraph(U.id,[j])}const C=[],F=b?Array.from(p).filter(N=>u.has(N)):Array.from(u.keys());for(const N of F){const L=u.get(N);if(!L||x.has(N)||L.containerPath.some(O=>x.has(O)))continue;const _=L.block,$=m.get(N);if(_.type==="container"||_.type==="table-cell"||L.containerPath.some(O=>h.has(O)))continue;const R=$?d.get($)??d.get(N):d.get(N),M=$&&R?.block.id===$&&$!==N?$:null;if(R?.block.id&&v.add(R.block.id),_.type==="paragraph"){const O=M!==null?at(_,M):_;if(!R)C.push({location:L});else if(R.block.type==="paragraph"){const D=R.block,X=Or(D),j=Or(O);if(X!==j||ku(D,O)){if(f.has(N)){const q=Fr(e,O);q&&(I.push(q),O.id&&e.setSuggestionsForParagraph(O.id,[q]));continue}const U=wa(e,D,O);I.push(...U)}}else{const D=Fr(e,O);D&&(I.push(D),O.id&&e.setSuggestionsForParagraph(O.id,[D]))}}else if(_.type==="list"){const O=M!==null?at(_,M):_;if(!R)C.push({location:L});else if(R.block.type==="list"){const D=R.block;if(us(D,O)){if(!hu(D,O)){const X=ou(e,D,O);X.length>0&&D.id&&(I.push(...X),e.setSuggestionsForParagraph(D.id,X))}}else{const X=Lr(e,O);X&&D.id&&(I.push(X),e.setSuggestionsForParagraph(D.id,[X]))}}else{const D=Lr(e,O);D&&O.id&&(I.push(D),e.setSuggestionsForParagraph(O.id,[D]))}}else if(_.type==="table"){const O=M!==null?at(_,M):_;if(!R)C.push({location:L});else if(R.block.type==="table"){const D=R.block,X=h.has(O.id);if(X||Aa(D)!==Aa(O)){const j=Ta(e,X?O:su(D,O));j&&(I.push(j),e.setSuggestionsForParagraph(O.id,[j]))}}else{const D=Ta(e,O);D&&O.id&&(I.push(D),e.setSuggestionsForParagraph(O.id,[D]))}}else if(_.type==="code"){const O=M!==null?at(_,M):_;if(!R)C.push({location:L});else if(R.block.type==="code"){const D=R.block;if(D.content!==O.content||D.language!==O.language){const X=Ca(e,O);X&&O.id&&(I.push(X),e.setSuggestionsForParagraph(O.id,[X]))}}else{const D=Ca(e,O);D&&O.id&&(I.push(D),e.setSuggestionsForParagraph(O.id,[D]))}}else if(_.type==="math"){const O=M!==null?at(_,M):_;if(!R)C.push({location:L});else if(R.block.type==="math"){const D=R.block;if(D.content!==O.content||D.displayMode!==O.displayMode||D.align!==O.align){const X=Pa(e,O);X&&O.id&&(I.push(X),e.setSuggestionsForParagraph(O.id,[X]))}}else{const D=Pa(e,O);D&&O.id&&(I.push(D),e.setSuggestionsForParagraph(O.id,[D]))}}else if(_.type==="image"){const O=M!==null?at(_,M):_;if(!R)C.push({location:L});else if(R.block.type==="image"){const D=R.block;if(D.src!==O.src||D.width!==O.width||D.height!==O.height||D.alt!==O.alt||D.align!==O.align){const X=Ba(e,O);X&&O.id&&(I.push(X),e.setSuggestionsForParagraph(O.id,[X]))}}else{const D=Ba(e,O);D&&O.id&&(I.push(D),e.setSuggestionsForParagraph(O.id,[D]))}}else if(_.type==="page-break"){const O=M!==null?at(_,M):_;if(!R)C.push({location:L});else if(R.block.type!=="page-break"){const D=gu(e,O);D&&O.id&&(I.push(D),e.setSuggestionsForParagraph(O.id,[D]))}}else if(_.type==="toc"){const O=M!==null?at(_,M):_;if(!R)C.push({location:L});else if(R.block.type!=="toc"||R.block.levels!==O.levels||R.block.instr!==O.instr||R.block.fontFamily!==O.fontFamily||R.block.fontSize!==O.fontSize||R.block.color!==O.color||R.block.direction!==O.direction||R.block.align!==O.align){const D=uu(e,O);D&&O.id&&(I.push(D),e.setSuggestionsForParagraph(O.id,[D]))}}}C.sort((N,L)=>{const _=N.location.containerPath,$=L.location.containerPath,R=Math.min(_.length,$.length);for(let M=0;M<R;M++)if(_[M]!==$[M])return _[M].localeCompare($[M]);return _.length!==$.length?_.length-$.length:N.location.indexInParent-L.location.indexInParent});const E=N=>{const L=N.containerPath.at(-1),_=L?u.get(L)?.block:null;return _&&"children"in _?_.children:c.children},P=N=>{const L=E(N);for(let _=N.indexInParent-1;_>=0;_--){const $=L[_];if($.id)return y($.id)}return null},B=N=>{const L=E(N),_=(()=>{for(let R=N.indexInParent-1;R>=0;R--)if(L[R]?.id)return y(L[R].id);return null})(),$=(()=>{for(let R=N.indexInParent-1;R>=0;R--){const M=L[R]?.id;if(!M)continue;const O=y(M);if(d.has(O))return O}return null})();return Array.from(new Set([$,_].filter(R=>typeof R=="string"&&R.length>0)))},w=[];for(const N of C){const L=N.location,_=P(L),$=w[w.length-1];if($&&$.afterId===_&&$.containerPath.join("/")===L.containerPath.join("/")&&$.blocks[$.blocks.length-1].location.indexInParent===L.indexInParent-1){$.blocks.push(N);continue}w.push({afterId:_,containerPath:L.containerPath,blocks:[N]})}for(const N of w){const L=N.afterId&&d.has(N.afterId);if(N.blocks.length===1&&L){const{location:_}=N.blocks[0],$=_.block,R=mu(e,$,N.afterId,a);R&&(I.push(R),$.id&&e.setSuggestionsForParagraph($.id,[R]))}else for(let _=0;_<N.blocks.length;_++){const{location:$}=N.blocks[_],R=$.block;if(R.type!=="paragraph"&&R.type!=="list"&&R.type!=="table"&&R.type!=="code"&&R.type!=="math"&&R.type!=="image"&&R.type!=="page-break"&&R.type!=="toc"){console.warn("[SuggestionPlanner] Skipping unsupported block type for position-aware insertion:",R.type);continue}const M=B($),O=e.createPositionAwareInsertion(R.id,R,M,E($).slice($.indexInParent+1).map(D=>D.id).filter(D=>!!D&&d.has(D)).slice(0,1),{authorType:"ai",description:`AI: insert_${R.type} (position-aware)`});O&&(I.push(O),e.setSuggestionsForParagraph(R.id,[O]))}}const T=b?Array.from(p).filter(N=>d.has(N)):Array.from(d.keys());for(const N of T){const L=d.get(N);if(!L||v.has(N))continue;const _=L.block,$=_.type==="container"&&b&&!!p?.has(N);if(!(_.type==="container"&&!$)&&_.type!=="table-cell"&&!L.containerPath.some(R=>h.has(R))&&(_.type==="paragraph"||_.type==="list"||_.type==="table"||_.type==="code"||_.type==="math"||_.type==="image"||_.type==="docx-raw"||_.type==="page-break"||_.type==="section-break"||_.type==="toc"||$)){const R=pu(e,_);R&&(I.push(R),e.setSuggestionsForParagraph(N,[R]))}}return I}function wa(s,e,t){const n=[];if(!Ht(e,t)){const u=Fr(s,t);if(u)return s.setSuggestionsForParagraph(t.id,[u]),[u]}const i=u=>{const p=[];return u.children.forEach((h,f)=>{if(h.type==="text"){const m=h;for(let y=0;y<m.text.length;y++)p.push({char:m.text[y],marks:m.marks||{},nodeIndex:f,charIndexInNode:y})}}),p},r=i(e),o=i(t),a=r.map(u=>u.char).join(""),l=o.map(u=>u.char).join(""),c=Ri(a,l).diffs;let d=0,g=0;for(let u=0;u<c.length;u++){const[p,h]=c[u];if(p===0){const f=h.length;for(let m=0;m<f;m++){const y=r[d+m],b=o[g+m],k=y?.marks||{},I=b?.marks||{};if(!Ia(k,I)){const v=m;let x=m+1;for(;x<f;){const P=r[d+x]?.marks||{},B=o[g+x]?.marks||{};if(Ia(P,B)||!Mr(B,I))break;x++}const A=h.substring(v,x),C=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,F=iu(I),E=s.createTextReplacement(C,t.id,d+v,x-v,A,F,A,{authorType:"ai",description:"AI: apply formatting"});E&&n.push(E),m=x-1}}d+=h.length,g+=h.length}else if(p===-1){const f=h.length,m=u+1<c.length?c[u+1]:null;if(m&&m[0]===1){const y=m[1];let b=!0;if(y.length>1){const k=g<o.length?o[g].marks:{};for(let I=1;I<y.length;I++){const v=g+I<o.length?o[g+I].marks:{};if(!Er(k,v)){b=!1;break}}}if(b){const k=g<o.length?o[g].marks:{},{...I}=k,v=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,x=s.createTextReplacement(v,t.id,d,f,y,I,h,{authorType:"ai",description:"AI: replace text"});x&&n.push(x)}else{const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,I=s.createSuggestion(k,v=>{const x=K(v,t.id);let A=null;if(x)for(let E=0;E<x.length;E++){const P=x.get(E);if(P instanceof S.XmlText){A=P;break}}if(!A)return console.warn(`Paragraph ${t.id} not found for mixed formatting replacement`),[];A.delete(d,f);let C=d,F=0;for(;F<y.length;){const E=F,P=g+F,B=P<o.length?_t(o[P].marks):{};let w=F+1;for(;w<y.length;){const N=g+w,L=N<o.length?_t(o[N].marks):{};if(!Mr(B,L))break;w++}const T=y.substring(E,w);ne(A,C,T,{...B,suggestionId:k}),C+=T.length,F=w}return[{kind:"replace",paragraphId:t.id,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,d,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,d+y.length,0)),text:y,oldText:h}]},{authorType:"ai",description:"AI: replace text"});I&&n.push(I)}u++,d+=f,g+=y.length}else{const y=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,b=s.createTextDeletion(y,t.id,d,f,h,{authorType:"ai",description:"AI: delete text"});b&&n.push(b),d+=f}}else if(p===1){const f=h,m=u>0?c[u-1]:null;if(m&&m[0]===-1)continue;const y=[];let b=0;for(;b<f.length;){const k=b,I=g+b,v=I<o.length?o[I].marks:{},x=_t(v);let A=b+1;for(;A<f.length;){const F=g+A,E=F<o.length?o[F].marks:{};if(!Mr(x,E))break;A++}const C=f.substring(k,A);y.push({text:C,marks:x}),b=A}if(y.length===1&&Object.keys(y[0].marks).length===0){const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,I=s.createTextInsertion(k,t.id,d,f,{},{authorType:"ai",description:"AI: insert text"});I&&n.push(I)}else{const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,I=s.createSuggestion(k,v=>{const x=K(v,t.id);let A=null;if(x)for(let F=0;F<x.length;F++){const E=x.get(F);if(E instanceof S.XmlText){A=E;break}}if(!A)return console.warn(`Paragraph ${t.id} not found for mixed formatting insertion`),[];let C=d;for(const F of y){const E={...F.marks,suggestionId:k};ne(A,C,F.text,E),C+=F.text.length}return[{kind:"insert",paragraphId:t.id,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,d,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,d+f.length,0)),text:f}]},{authorType:"ai",description:"AI: insert text"});I&&n.push(I)}g+=f.length}}return t.id&&n.length>0&&s.setSuggestionsForParagraph(t.id,n),n}function Fr(s,e){const t={name:"replace_block",arguments:{id:e.id,content:te.toAgentHtml({type:"doc",children:[e]})}};if(s.createBlockReplacementSuggestion){const n=s.createBlockReplacementSuggestion(e,t);if(n)return n}return s.createSuggestionFromToolCall(t,(n,i)=>{const r=G(n,e.id);if(!r||r.yBlock.nodeName!=="paragraph")return We(n,i);const o=ae(r.yBlock)?.toDelta().map(c=>typeof c.insert=="string"?c.insert:"").join("")??"";r.yParent.delete(r.index,1);const a=Se(e);r.yParent.insert(r.index,[a]);const l=ae(a);return[{kind:"replace",paragraphId:e.id,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(l,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(l,l.length,0)),text:Or(e),oldText:o}]})}function ou(s,e,t){const n=[],i=e.children.map(b=>({item:b,text:xt(b),signature:Nr(b)})),r=t.children.map(b=>({item:b,text:xt(b),signature:Nr(b)})),{beforeKeys:o,afterKeys:a}=ma(e.children,t.children,Nr),l=Ar(o,a),c=[],d=(b,k,I)=>{const v=Math.min(b.length,k.length);for(let x=0;x<v;x++)c.push({kind:"replace",index:I+x,currentItem:b[x],finalItem:k[x]});for(let x=v;x<b.length;x++)c.push({kind:"delete",index:I+x,currentItem:b[x]});for(let x=k.length-1;x>=v;x--)c.push({kind:"insert",index:I+v,finalItem:k[x]})};let g=0,u=0;for(const b of l){let k=g;for(;k<i.length&&o[k]!==b;)k+=1;let I=u;for(;I<r.length&&a[I]!==b;)I+=1;d(i.slice(g,k),r.slice(u,I),g),g=k+1,u=I+1;const v=i[k],x=r[I];v&&x&&(v.signature!==x.signature||!Ma(v.item,x.item))&&c.push({kind:"replace",index:k,currentItem:v,finalItem:x})}d(i.slice(g),r.slice(u),g);const p=c.some(b=>b.kind!=="replace"?!0:b.currentItem.signature!==b.finalItem.signature||b.currentItem.text!==b.finalItem.text);if(c.length>0&&!p){const b=au(s,t);return b?[b]:[]}for(const b of c){if(b.kind==="insert"){const I=lu(s,e.id,b.finalItem.item,b.index,e.variant);I&&n.push(I);continue}if(b.kind==="delete"){const I=cu(s,e.id,b.index,b.currentItem.text);I&&n.push(I);continue}const k=du(s,e.id,b.index,b.currentItem.item,b.finalItem.item,e.variant);k&&n.push(k)}const h=c.filter(b=>b.kind==="replace").length,f=c.some(b=>b.kind!=="replace"?b.kind==="insert"||b.kind==="delete":b.currentItem.signature!==b.finalItem.signature||b.currentItem.text!==b.finalItem.text),m=Math.max(i.length,r.length),y=m>0?n.length/m:0;if(h>0&&y>.7&&f){const b=Lr(s,t);return b?[b]:[]}return n}function au(s,e){if(!e.id)return null;const t=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(t,n=>{const i=K(n,e.id);if(!i||i.nodeName!=="list")return[];for(let r=0;r<e.children.length;r++){const o=i.get(r),a=e.children[r];if(!(o instanceof S.XmlElement)||!a)continue;const l=ae(o);if(!l)continue;let c=0;for(const d of a.children)d.type!=="text"||d.text.length===0||(ie(l,c,d.text.length,Sa(d.marks||{})),c+=d.text.length)}return[{kind:"replace",paragraphId:e.id,text:e.children.map(xt).join(`
27
- `),oldText:e.children.map(xt).join(`
28
- `)}]},{authorType:"ai",description:"AI: apply list formatting"})}function lu(s,e,t,n,i){const r=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(r,o=>{const a=K(o,e);if(!a||a.nodeName!=="list")return console.warn(`List ${e} not found for item insertion`),[];const l=new S.XmlElement("list-item");Ct(l,t),l.setAttribute("id",t.id||Y()),t.checked!==void 0&&l.setAttribute("checked",String(t.checked)),t.indentLevel&&l.setAttribute("indentLevel",String(t.indentLevel)),t.direction!==void 0&&l.setAttribute("direction",t.direction);const c=new S.XmlText;let d=0;t.children.forEach(u=>{if(u.type==="text"){const p=u,h={...p.marks||{},suggestionId:r,toolType:"list_item_insert"};c.insert(d,p.text,h),d+=p.text.length}}),l.insert(0,[c]);const g=Math.min(n,a.length);return a.insert(g,[l]),[{kind:"insert",paragraphId:e,text:xt(t)}]},{authorType:"ai",description:"AI: insert list item"})}function cu(s,e,t,n){const i=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(i,r=>{const o=K(r,e);return!o||o.nodeName!=="list"?(console.warn(`List ${e} not found for item deletion`),[]):t>=o.length?(console.warn(`Item index ${t} out of bounds for list ${e}`),[]):(o.delete(t,1),[{kind:"delete",paragraphId:e,text:n}])},{authorType:"ai",description:"AI: delete list item"})}function du(s,e,t,n,i,r){const o=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(o,a=>{const l=K(a,e);if(!l||l.nodeName!=="list")return console.warn(`List ${e} not found for item replacement`),[];if(t>=l.length)return console.warn(`Item index ${t} out of bounds for list ${e}`),[];const c=l.get(t);if(!(c instanceof S.XmlElement))return console.warn(`Item at index ${t} is not an XmlElement`),[];Ct(c,i),i.direction!==n.direction&&(i.direction!==void 0?c.setAttribute("direction",i.direction):c.removeAttribute("direction")),i.checked!==n.checked&&(i.checked!==void 0?c.setAttribute("checked",String(i.checked)):c.removeAttribute("checked")),i.indentLevel!==n.indentLevel&&(i.indentLevel?c.setAttribute("indentLevel",String(i.indentLevel)):c.removeAttribute("indentLevel"));let d=null;for(let p=0;p<c.length;p++){const h=c.get(p);if(h instanceof S.XmlText){d=h;break}}if(!d)return console.warn(`No content found in list item at index ${t}`),[];const g=d.length;g>0&&d.delete(0,g);let u=0;return i.children.forEach(p=>{if(p.type==="text"){const h=p,f={..._t(h.marks||{}),suggestionId:o,toolType:"list_item_replace"};d.insert(u,h.text,f),u+=h.text.length}}),[{kind:"replace",paragraphId:e,text:xt(i),oldText:xt(n)}]},{authorType:"ai",description:"AI: replace list item"})}function xt(s){return s.children.filter(e=>e.type==="text").map(e=>e.text).join("")}function Nr(s){return JSON.stringify({...Object.fromEntries(xn.map(e=>[e,s[e]])),direction:s.direction,checked:s.checked??!1,indentLevel:s.indentLevel??0,children:s.children.map(e=>e.type==="text"?{type:"text",text:e.text}:{type:e.type})})}function Lr(s,e){const t={name:"replace_block",arguments:{id:e.id,content:fu(e)}};return s.createSuggestionFromToolCall(t,n=>{const i=G(n,e.id);return i?(i.yParent.delete(i.index,1),i.yParent.insert(i.index,[Se(e)]),[{kind:"replace",paragraphId:e.id,text:"List replaced",oldText:i.yBlock.nodeName==="list"?"List":"Paragraph"}]):[]})}function Ta(s,e){const t={name:"replace_block",arguments:{id:e.id,content:te.toInternalHtml({type:"doc",children:[e]})}};return s.createSuggestionFromToolCall(t,(n,i)=>We(n,i))}function Ca(s,e){const t={name:"replace_block",arguments:{id:e.id,content:te.toAgentHtml({type:"doc",children:[e]})}};return s.createSuggestionFromToolCall(t,(n,i)=>We(n,i))}function Pa(s,e){const t={name:"replace_block",arguments:{id:e.id,content:te.toAgentHtml({type:"doc",children:[e]})}};return s.createSuggestionFromToolCall(t,(n,i)=>We(n,i))}function Ba(s,e){const t={name:"replace_block",arguments:{id:e.id,content:te.toInternalImageHtml(e)}};return s.createSuggestionFromToolCall(t,(n,i)=>We(n,i))}function gu(s,e){const t={name:"replace_block",arguments:{id:e.id,content:te.toAgentHtml({type:"doc",children:[e]})}};return s.createSuggestionFromToolCall(t,(n,i)=>We(n,i))}function uu(s,e){const t={name:"replace_block",arguments:{id:e.id,content:te.toAgentHtml({type:"doc",children:[e]})}};return s.createSuggestionFromToolCall(t,(n,i)=>We(n,i))}function hu(s,e){if(s.children.length!==e.children.length)return!1;for(let t=0;t<s.children.length;t++){const n=s.children[t],i=e.children[t];if(xn.some(a=>n[a]!==i[a])||n.direction!==i.direction||n.checked!==i.checked||n.indentLevel!==i.indentLevel)return!1;const r=n.children.filter(a=>a.type==="text").map(a=>a.text).join(""),o=i.children.filter(a=>a.type==="text").map(a=>a.text).join("");if(r!==o||!Ma(n,i))return!1}return!0}function Ma(s,e){if(s.children.length!==e.children.length)return!1;for(let t=0;t<s.children.length;t++){const n=s.children[t],i=e.children[t];if(n.type!==i.type||n.type==="text"&&i.type==="text"&&(n.text!==i.text||!Er(n.marks||{},i.marks||{})))return!1}return!0}function fu(s){return te.toInternalHtml({type:"doc",children:[s]})}function pu(s,e){if(!e.id)return console.warn("[SuggestionPlanner] Cannot create remove_block proposal for block without id:",e.type),null;const t=e.id,n={name:"remove_block",arguments:{id:t,count:1}},i=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return s.createSuggestion(i,r=>{const o=G(r,t);if(!o)return console.warn(`[SuggestionPlanner] Block ${t} not found for removal`),[];const{yBlock:a,yParent:l,index:c}=o,d=a.nodeName;let g;if(d==="list")g={kind:"delete",paragraphId:t,text:"List removed"};else{let u="";for(let p=0;p<a.length;p++){const h=a.get(p);if(h instanceof S.XmlText){const f=Z(h);for(const m of f)m.insert&&typeof m.insert=="string"&&(u+=m.insert)}}g={kind:"delete",paragraphId:t,text:u||"Block removed"}}return l.delete(c,1),[g]},{authorType:"ai",toolCallAction:n,description:"AI: remove_block"})}function mu(s,e,t,n){let i,r;t===null?n.children.length>0?(i=n.children[0].id,r="before"):(i=Gt,r="after"):(i=t,r="after");const o={name:"insert_block",arguments:{referenceId:i,position:r,content:[bu(e)]}};return ve(o,{stableId:e.id||Y()}),s.createSuggestionFromToolCall(o,(a,l)=>We(a,l))}function bu(s){return s.type==="paragraph"?yu(s):s.type==="image"?te.toInternalImageHtml(s):s.type==="list"||s.type==="table"||s.type==="code"||s.type==="math"||s.type==="page-break"||s.type==="toc"?te.toInternalHtml({type:"doc",children:[s]}):""}function Ee(s){return s.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function yu(s,e){const t=s.heading?`h${s.heading}`:"p",n=[];s.align&&n.push(`text-align: ${s.align}`);const i=n.length>0?` style="${n.join("; ")}"`:"";let r=`<${t}${i}>`;for(const o of s.children)if(o.type==="text"){let a=o.text.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;");if(o.marks?.bold&&(a=`<b>${a}</b>`),o.marks?.italic&&(a=`<i>${a}</i>`),o.marks?.underline&&(a=`<u>${a}</u>`),o.marks?.strikethrough&&(a=`<s>${a}</s>`),o.marks?.code&&(a=`<code>${a}</code>`),o.marks?.latex&&(a=`<latex-inline>${a}</latex-inline>`),o.marks?.superscript||o.marks?.footnoteRef){const g=o.marks?.footnotePendingBody!==void 0?` data-footnote="${Ee(o.marks.footnotePendingBody)}"${o.marks?.footnotePendingKind==="endnote"?' data-note-kind="endnote"':""}`:"";a=o.marks?.footnoteRef?`<sup data-footnote-ref="${Ee(o.marks.footnoteRef)}"${g}>${a}</sup>`:`<sup>${a}</sup>`}else o.marks?.subscript&&(a=`<sub>${a}</sub>`);const l=o.marks?.fontFamily,c=o.marks?.fontSize;if(l||c||o.marks?.color||o.marks?.doubleStrikethrough||o.marks?.smallCaps||o.marks?.allCaps||o.marks?.letterSpacing){const g=[];l&&g.push(`font-family: ${Ee(l)}`),c&&g.push(`font-size: ${c}px`),o.marks?.color&&g.push(`color: ${Ee(o.marks.color)}`),o.marks?.doubleStrikethrough&&g.push("text-decoration: line-through double"),o.marks?.smallCaps&&g.push("font-variant: small-caps"),o.marks?.allCaps&&g.push("text-transform: uppercase"),typeof o.marks?.letterSpacing=="number"&&Number.isFinite(o.marks.letterSpacing)&&o.marks.letterSpacing!==0&&g.push(`letter-spacing: ${o.marks.letterSpacing}px`),a=`<span style="${g.join("; ")}">${a}</span>`}o.marks?.hidden&&(a=`<span data-word-hidden="true">${a}</span>`),o.marks?.lang&&(a=`<span data-word-lang="${Ee(o.marks.lang)}">${a}</span>`),o.marks?.bookmark&&(a=`<span data-bookmark="${Ee(o.marks.bookmark)}">${a}</span>`),o.marks?.fieldInstr&&(a=`<span data-field-instr="${Ee(o.marks.fieldInstr)}">${a}</span>`),o.marks?.field&&(a=`<span data-dynamic-field="${Ee(o.marks.field)}">${a}</span>`),o.marks?.sdtInline&&(a=`<span data-sdt-inline="${Ee(o.marks.sdtInline)}">${a}</span>`),o.marks?.aiGenerated&&(a=`<span data-ai-generated="true">${a}</span>`),o.marks?.__htmlClassName&&(a=`<span data-html-class="${Ee(o.marks.__htmlClassName)}">${a}</span>`);const d=_e(o.marks?.backgroundColor);if(d&&(a=`<mark color="${Ee(d)}">${a}</mark>`),o.marks?.link&&(a=`<a href="${Ee(o.marks.link)}">${a}</a>`),o.marks?.comment)for(const g of o.marks.comment.split(",").map(u=>u.trim()).filter(Boolean).reverse())a=`<comment-thread id="${Ee(g)}">${a}</comment-thread>`;r+=a}return r+=`</${t}>`,r}function Or(s){return s.children.filter(e=>e.type==="text").map(e=>e.type==="text"?e.text:"").join("")}function ku(s,e){if(!Ht(s,e)||s.children.length!==e.children.length)return!0;for(let t=0;t<s.children.length;t++){const n=s.children[t],i=e.children[t];if(n.type!==i.type||n.type==="text"&&i.type==="text"&&(n.text!==i.text||!Er(n.marks||{},i.marks||{})))return!0}return!1}const Su=Object.freeze(Object.defineProperty({__proto__:null,ToolCallHistory:va,createFlattenedSuggestions:$r,createGranularSuggestionsForParagraph:wa},Symbol.toStringTag,{value:"Module"}));class Rr{constructor(e,t=!1){this.allowDirectBlockReplacementPreviews=t,this.proposals=new Map,this.suggestionMeta=new Map,this.paragraphSuggestions=new Map,this.tableCellSuggestions=new Map,this.cachedBaseUpdate=null,this.invalidateBaseUpdate=()=>{this.cachedBaseUpdate=null,this.ydoc.off("update",this.invalidateBaseUpdate)},this.ydoc=e}getBaseUpdate(){return this.cachedBaseUpdate||(this.cachedBaseUpdate=S.encodeStateAsUpdateV2(this.ydoc),this.ydoc.on("update",this.invalidateBaseUpdate)),this.cachedBaseUpdate}seedFork(){const e=new S.Doc;return S.applyUpdateV2(e,this.getBaseUpdate()),e}createForklessTextSuggestion(e){const t=K(this.ydoc,e.paragraphId),n=t?ae(t):null;if(!n||e.startOffset+e.deleteLength>n.length)return null;const i=e.kind==="delete"?e.startOffset+e.deleteLength:e.startOffset,r=S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(n,i,0)),o=S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(n,e.kind==="delete"?i:e.startOffset+e.deleteLength,0));return this.proposals.set(e.id,new Uint8Array(0)),this.suggestionMeta.set(e.id,{id:e.id,authorId:e.metadata.authorId||"system",authorType:e.metadata.authorType||"ai",createdAt:Date.now(),status:"pending",anchors:[{kind:e.kind,paragraphId:e.paragraphId,from:r,to:o,text:e.anchorText,...e.oldText!==void 0?{oldText:e.oldText}:{}}],...e.metadata,inlinePreview:{startOffset:e.startOffset,newText:e.newText,marks:e.marks}}),e.id}getYDoc(){return this.ydoc}createSuggestion(e,t,n={}){const i=this.seedFork(),r=S.encodeStateVector(i);let o=[];i.transact(()=>{o=t(i)},"proposal-edit");const a=S.encodeStateAsUpdate(i,r);return this.proposals.set(e,a),this.suggestionMeta.set(e,{id:e,authorId:n.authorId||"system",authorType:n.authorType||"ai",createdAt:Date.now(),status:"pending",anchors:o,...n}),e}createSuggestionFromToolCall(e,t){return this.createSuggestion(this.generateId(),n=>t(n,e),{authorType:"ai",toolCallAction:e,description:`AI: ${e.name}`})}createBlockReplacementSuggestion(e,t){if(!this.allowDirectBlockReplacementPreviews)return null;const n=e.id?K(this.ydoc,e.id):null;if(!n||n.nodeName!=="paragraph")return null;const i=this.generateId();return this.suggestionMeta.set(i,{id:i,authorId:"system",authorType:"ai",createdAt:Date.now(),status:"pending",anchors:[{kind:"replace",paragraphId:e.id}],toolCallAction:t,description:`AI: ${t.name}`,blockPreview:e}),i}createTextDeletion(e,t,n,i,r,o={}){return this.createForklessTextSuggestion({id:e,kind:"delete",paragraphId:t,startOffset:n,deleteLength:i,newText:"",marks:{},anchorText:r,metadata:{...o,id:e}})||this.createSuggestion(e,l=>{const c=K(l,t);if(!c)return[];const d=ae(c);return d?(d.delete(n,i),[{kind:"delete",paragraphId:t,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(d,n,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(d,n+i,0)),text:r}]):[]},{...o,id:e,inlinePreview:{startOffset:n,newText:"",marks:{}}})}createTextInsertion(e,t,n,i,r={},o={}){const a={...r,suggestionId:e};return this.createSuggestion(e,l=>{const c=K(l,t);if(!c)return[];const d=ae(c);return d?(ne(d,n,i,a),[{kind:"insert",paragraphId:t,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(d,n,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(d,n+i.length,0)),text:i}]):[]},{...o,id:e})}createTextReplacement(e,t,n,i,r,o={},a,l={}){const c={...o,suggestionId:e};return this.createForklessTextSuggestion({id:e,kind:"replace",paragraphId:t,startOffset:n,deleteLength:i,newText:r,marks:c,anchorText:r,oldText:a,metadata:{...l,id:e}})||this.createSuggestion(e,g=>{const u=K(g,t);if(!u)return[];const p=ae(u);return p?(p.delete(n,i),ne(p,n,r,c),[{kind:"replace",paragraphId:t,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(p,n,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(p,n+r.length,0)),text:r,oldText:a}]):[]},{...l,id:e,inlinePreview:{startOffset:n,newText:r,marks:c}})}createPositionAwareInsertion(e,t,n,i,r={}){const o=this.generateId();return this.suggestionMeta.set(o,{id:o,authorId:r.authorId||"system",authorType:r.authorType||"ai",createdAt:Date.now(),status:"pending",insertionContext:{paragraphId:e,content:t,mustBeAfter:n,mustBeBefore:i},...r}),o}materializeWithSuggestion(e){const t=this.suggestionMeta.get(e);if(!t||t.status==="accepted")return null;const n=this.seedFork();if(t.blockPreview?.id){const r=G(n,t.blockPreview.id);return r?(r.yParent.delete(r.index,1),r.yParent.insert(r.index,[Se(t.blockPreview)]),n):null}if(t.insertionContext)return this.applyPositionAwareInsertion(n,e,t),n;const i=this.proposals.get(e);return i?(S.applyUpdate(n,i),n):null}withMaterializedSuggestion(e,t){const n=this.materializeWithSuggestion(e);return n?t(n):null}materializeWithSuggestions(e){const t=this.seedFork();for(const n of e){const i=this.suggestionMeta.get(n);if(!i||i.status==="accepted")continue;if(i.insertionContext){this.applyPositionAwareInsertion(t,n,i);continue}if(i.blockPreview?.id){const o=G(t,i.blockPreview.id);o&&(o.yParent.delete(o.index,1),o.yParent.insert(o.index,[Se(i.blockPreview)]));continue}const r=this.proposals.get(n);r&&S.applyUpdate(t,r)}return t}getSuggestion(e){return this.suggestionMeta.get(e)}getPendingSuggestions(){const e=new Map;for(const[t,n]of this.suggestionMeta)n.status==="pending"&&e.set(t,n);return e}deleteSuggestion(e){this.proposals.delete(e),this.suggestionMeta.delete(e),this.removeProposalFromParagraphs(e),this.removeProposalFromTableCellMaps(e)}resolveAnchorsAgainstDoc(e,t){const n=this.suggestionMeta.get(e);return n?.anchors?n.anchors.map(i=>{const r=i.from?S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(i.from),t):null,o=i.to?S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(i.to),t):null;return{kind:i.kind,paragraphId:i.paragraphId,fromIndex:r?.index??null,toIndex:o?.index??null,text:i.text}}):[]}setSuggestionsForParagraph(e,t){this.paragraphSuggestions.set(e,t)}getSuggestionsForParagraph(e){return this.paragraphSuggestions.get(e)||[]}setTableCellSuggestionMap(e,t){this.tableCellSuggestions.set(e,t)}applyPositionAwareInsertion(e,t,n){const i=n.insertionContext;if(!i)return;const r=e.getXmlFragment("content");let o=0;for(let l=r.length-1;l>=0;l--){const c=r.get(l);if(!(c instanceof S.XmlElement))continue;const d=c.getAttribute("id");if(d&&i.mustBeAfter.includes(d)){o=l+1;break}}const a=Iu(i.content,i.paragraphId,t);r.insert(o,[a])}removeProposalFromParagraphs(e){for(const[t,n]of this.paragraphSuggestions){const i=n.filter(r=>r!==e);i.length!==n.length&&(i.length===0?this.paragraphSuggestions.delete(t):this.paragraphSuggestions.set(t,i))}}removeProposalFromTableCellMaps(e){for(const[t,n]of this.tableCellSuggestions){let i=!1;for(const[r,o]of n)o===e&&(n.delete(r),i=!0);i&&n.size===0&&this.tableCellSuggestions.delete(t)}}generateId(){return`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}}function Iu(s,e,t,n){if(s.type==="list"){const a=new S.XmlElement("list");return a.setAttribute("id",e),a.setAttribute("variant",s.variant??"unordered"),s.startNumber!==void 0&&a.setAttribute("startNumber",String(s.startNumber)),s.numberingChainId&&a.setAttribute("numberingChainId",s.numberingChainId),s.children.forEach(l=>{const c=new S.XmlElement("list-item");Ct(c,l),c.setAttribute("id",l.id||Y()),l.checked!==void 0&&c.setAttribute("checked",String(l.checked)),typeof l.indentLevel=="number"&&l.indentLevel>0&&c.setAttribute("indentLevel",String(l.indentLevel)),l.direction!==void 0&&c.setAttribute("direction",l.direction);const d=new S.XmlText;let g=0;l.children.forEach(u=>{if(u.type!=="text")return;const p=Dr(u.marks,t);d.insert(g,u.text,p),g+=u.text.length}),c.insert(0,[d]),a.push([c])}),a}if(s.type==="table")return Se(cs({...s,id:e},a=>({...a,marks:Dr(a.marks,t)})));if(s.type==="code"){const a=new S.XmlElement("code");a.setAttribute("id",e),s.language&&a.setAttribute("language",s.language),s.renderDiagram!==void 0&&a.setAttribute("renderDiagram",String(s.renderDiagram)),s.showDiagramSource!==void 0&&a.setAttribute("showDiagramSource",String(s.showDiagramSource));const l=new S.XmlText;return a.insert(0,[l]),ne(l,0,s.content||""),a}if(s.type==="math"){const a=new S.XmlElement("math");a.setAttribute("id",e),s.displayMode&&a.setAttribute("displayMode",s.displayMode),s.align&&a.setAttribute("align",s.align);const l=new S.XmlText;return a.insert(0,[l]),ne(l,0,s.content||""),a}if(s.type==="image"){const a=new S.XmlElement("image");return a.setAttribute("id",e),a.setAttribute("src",s.src),s.sourceUrl&&a.setAttribute("sourceUrl",s.sourceUrl),a.setAttribute("width",String(s.width)),a.setAttribute("height",String(s.height)),s.alt&&a.setAttribute("alt",s.alt),s.align&&a.setAttribute("align",s.align),a}if(s.type==="page-break"){const a=new S.XmlElement("page-break");return a.setAttribute("id",e),a}if(s.type==="toc")return Se({...s,id:e});if(s.type==="section-break"){const a=new S.XmlElement("section-break");return a.setAttribute("id",e),s.layout&&a.setAttribute("layout",JSON.stringify(s.layout)),s.breakType&&a.setAttribute("breakType",s.breakType),a}const i=new S.XmlElement("paragraph");i.setAttribute("id",e),s.heading&&i.setAttribute("heading",String(s.heading)),s.align&&i.setAttribute("align",s.align);const r=new S.XmlText;let o=0;return s.children.forEach(a=>{if(a.type!=="text")return;const l=Dr(a.marks,t);ne(r,o,a.text,l),o+=a.text.length}),i.insert(0,[r]),i}function Dr(s,e,t){return{...s||{},suggestionId:e}}class yn{constructor(e){this.host=e,this.batchYBlockLocationsById=null,this.stampedIdRecorder=null}recordStampedSuggestionIds(e){const t=this.stampedIdRecorder,n={deletionIds:new Set,insertionIds:new Set,structuralInsertIds:new Set,structuralDeleteIds:new Set};this.stampedIdRecorder=n;try{return{result:e(),stamped:n}}finally{this.stampedIdRecorder=t}}recordStampedId(e,t){this.stampedIdRecorder&&t&&this.stampedIdRecorder[e].add(t)}buildInlinePreviewTextNodes(e){return e.newText?[{type:"text",text:e.newText,marks:{...e.marks}}]:[]}setSuggestingMode(e){this.host.suggestingMode=e}isSuggestingMode(){return this.host.suggestingMode}cloneSuggestionSnapshot(e){return JSON.parse(JSON.stringify(e))}getLiveSuggestionStore(){return this.host.ydoc.getMap("liveSuggestions")}setDefaultSuggestionAuthorName(e){const t=e?.trim();this.host.defaultHumanAuthorName=t||null}resolveSuggestionAuthorName(e,t){return t?.trim()||(e==="ai"?ze:this.host.defaultHumanAuthorName??Fs)}isOwnPendingSuggestionSpan(e){const t=typeof e.suggestionAuthorName=="string"?e.suggestionAuthorName.trim():"";if(!t)return!0;const n=this.host.liveSuggestionMetadataContext,i=this.resolveSuggestionAuthorName(n?.authorType??"human",n?.agentName);return t===i}withSuggestionMetadata(e,t){const n=this.host.liveSuggestionMetadataContext,i=new Set(this.getLiveSuggestionIds()),r={source:e.source,authorType:e.authorType,createdAt:e.createdAt??Date.now(),label:e.label,commentThreadId:e.commentThreadId,agentName:e.agentName,agentModel:e.agentModel,agentConversationId:e.agentConversationId,agentRequestId:e.agentRequestId,agentTurn:e.agentTurn},o=()=>{this.host.liveSuggestionMetadataContext=r;try{return t()}finally{this.host.liveSuggestionMetadataContext=n}},a=e.batchHistory===!1?o():this.host.runWithUndoGroup(e.historyOrigin??`live-suggestions:${r.createdAt}`,o),l=this.getLiveSuggestionIds().filter(c=>!i.has(c));return{result:a,suggestionIds:l}}normalizeLiveSuggestionRecord(e){const t=this.host.liveSuggestionMetadataContext,n=e.source??t?.source??"manual",i=e.authorType??t?.authorType??(n==="agent"?"ai":"human"),r=e.createdAt??t?.createdAt??Date.now(),o=e.label??t?.label,a=this.resolveSuggestionAuthorName(i,e.agentName??t?.agentName),l=e.agentModel??t?.agentModel,c=e.commentThreadId??t?.commentThreadId,d=e.agentConversationId??t?.agentConversationId,g=e.agentRequestId??t?.agentRequestId,u=e.agentTurn??t?.agentTurn;return{...e,source:n,authorType:i,createdAt:r,label:o,...c?{commentThreadId:c}:{},agentName:a,...l?{agentModel:l}:{},...d?{agentConversationId:d}:{},...g!==void 0?{agentRequestId:g}:{},...u!==void 0?{agentTurn:u}:{}}}saveLiveSuggestion(e,t){const n=this.normalizeLiveSuggestionRecord(e);this.getLiveSuggestionStore().set(n.id,this.cloneSuggestionSnapshot(n)),this.embedLiveSuggestionRecordInTree(n,t)}liveSuggestionRecordAnchorBlockId(e){switch(e.type){case"block-change":return e.sequenceBlockIds?this.getSequenceReplacementMembers(e)[0]?.yBlock.getAttribute("id")??null:e.blockId;case"block-insert":case"block-delete":case"paragraph-split":return e.blockId;case"table-change":return e.tableId;case"paragraph-merge":return e.firstBlockId;default:return null}}embedLiveSuggestionRecordInTree(e,t){const n=this.liveSuggestionRecordAnchorBlockId(e);if(!n||!this.host.ydoc)return;const i=t??K(this.host.ydoc,n);if(i instanceof S.XmlElement)try{if(e.type==="table-change"){let r=[];const o=i.getAttribute("structuralSuggestionRecords");if(typeof o=="string")try{const a=JSON.parse(o);Array.isArray(a)&&(r=a)}catch{}r=r.filter(a=>a?.id!==e.id),r.push(e),i.setAttribute("structuralSuggestionRecords",JSON.stringify(r))}else i.setAttribute("structuralSuggestionRecord",JSON.stringify(e));this.host.liveSuggestionTreeRecordCache.delete(e.id)}catch{}}backfillLiveSuggestionTreeRecords(){if(!this.host.ydoc)return;const e=[];try{for(const[,t]of this.getLiveSuggestionStore()){const n=this.liveSuggestionRecordAnchorBlockId(t);if(!n)continue;const i=K(this.host.ydoc,n);i instanceof S.XmlElement&&!i.getAttribute("structuralSuggestionRecord")&&e.push(t)}}catch{return}e.length!==0&&this.host.transact(()=>{for(const t of e)this.embedLiveSuggestionRecordInTree(this.normalizeLiveSuggestionRecord(t))})}findLiveSuggestionRecordInTree(e){if(this.host.liveSuggestionTreeRecordCacheReady)return this.host.liveSuggestionTreeRecordCache.get(e)??null;const t=this.host.liveSuggestionTreeRecordCache,n=r=>{r&&r.id&&r.type&&!t.has(r.id)&&t.set(r.id,r)},i=r=>{for(const o of r.toArray()){if(!(o instanceof S.XmlElement))continue;const a=o.getAttribute("structuralSuggestionRecord");if(typeof a=="string"&&a.length>0)try{n(JSON.parse(a))}catch{}const l=o.getAttribute("structuralSuggestionRecords");if(typeof l=="string"&&l.length>0)try{const c=JSON.parse(l);Array.isArray(c)&&c.forEach(n)}catch{}i(o)}};try{i(this.host.getYContentFragment()),i(this.host.getYNotesFragment())}catch{}return this.host.liveSuggestionTreeRecordCacheReady=!0,t.get(e)??null}getLiveSuggestion(e){const t=this.getLiveSuggestionStore().get(e);return t?this.cloneSuggestionSnapshot(t):this.findLiveSuggestionRecordInTree(e)??void 0}findInlineSuggestionMetadataInValue(e,t){if(!e||typeof e!="object")return null;if(Array.isArray(e)){for(const r of e){const o=this.findInlineSuggestionMetadataInValue(r,t);if(o)return o}return null}const n=e;if(n.marks?.suggestionId===t)return{id:t,source:n.marks.suggestionSource,authorType:n.marks.suggestionAuthorType,createdAt:n.marks.suggestionCreatedAt,label:n.marks.suggestionLabel,commentThreadId:n.marks.suggestionCommentThreadId,agentName:n.marks.suggestionAuthorName,agentModel:n.marks.suggestionAgentModel,agentConversationId:n.marks.suggestionAgentConversationId,agentRequestId:n.marks.suggestionAgentRequestId,agentTurn:n.marks.suggestionAgentTurn};const i=fn(n.marks?.layeredInsertion);return i&&i.id===t?{id:t,source:i.source,authorType:i.authorType,createdAt:i.createdAt,label:i.label,commentThreadId:i.commentThreadId,agentName:i.authorName,agentModel:i.agentModel,agentConversationId:i.agentConversationId,agentRequestId:i.agentRequestId,agentTurn:i.agentTurn}:n.children?this.findInlineSuggestionMetadataInValue(n.children,t):null}getInlineSuggestionMetadataFromDocument(e){return this.host.inlineSuggestionMetadataCache.has(e)?this.host.inlineSuggestionMetadataCache.get(e)??null:(this.getDocumentSuggestionIdsCache(),this.host.inlineSuggestionMetadataCache.has(e)?this.host.inlineSuggestionMetadataCache.get(e)??null:(this.host.inlineSuggestionMetadataCache.set(e,null),null))}getLiveSuggestionTooltipDescription(e){const t=this.getLiveSuggestion(e);if(!t)return null;switch(t.type){case"inline-text":return null;case"inline-format":return this.host.getInlineFormatDescription(t);case"paragraph-split":return"Split Paragraph";case"paragraph-merge":return"Join Paragraphs";case"block-insert":{const n=z(this.host.getDocument(),t.blockId)??void 0,i=this.host.getBlockDescription(n);return i?`Insert ${i}`:n?.type==="paragraph"?"Insert Paragraph":n?.type==="list"?"Insert List":null}case"block-delete":{const n=this.host.getBlockDescription(t.beforeBlock);return n?`Delete ${n}`:t.beforeBlock.type==="paragraph"?"Delete Paragraph":t.beforeBlock.type==="list"?"Delete List":t.label??null}case"table-change":return t.label??"Table change";case"block-change":{const n=t.acceptedBlock??z(this.host.getDocument(),t.blockId)??void 0,i=this.host.getTableDimensionDescription(t.label,t.beforeBlock,n);if(i)return i;if(t.label==="Format")return this.host.getBlockFormatDescription(t.beforeBlock,n);if(t.label==="Paragraph")return"Convert to Paragraph";if(t.beforeBlock.type==="list"&&n?.type==="list"&&(t.label==="Insert"||t.label==="Delete"||t.label==="Change"))return t.label==="Insert"?"Insert List Item":t.label==="Delete"?"Delete List Item":"Change List Item";if(t.label==="List")return t.beforeBlock.type==="paragraph"?"Convert to List":"List Change";if(t.label==="Indent"||t.label==="Outdent")return t.label;if(t.label==="Join")return"Join List Items";const r=this.host.getBlockDescription(n)??this.host.getBlockDescription(t.beforeBlock);if(r&&t.label)return`${t.label} ${r}`;if(t.label){if(t.beforeBlock.type==="paragraph")return`${t.label} Paragraph`;if(t.beforeBlock.type==="list")return`${t.label} List`}return t.label??null}default:return null}}deleteLiveSuggestion(e){this.getLiveSuggestionStore().delete(e),this.host.liveSuggestionTreeRecordCache.delete(e)}getLiveSuggestionIds(){if(this.host.liveSuggestionIdsCache)return this.host.liveSuggestionIdsCache.slice();const e=Array.from(new Set([...Array.from(this.getLiveSuggestionStore().keys()),...this.getResolvableSuggestionIdsFromDocument()]));return this.host.liveSuggestionIdsCache=e,e.slice()}getLiveSuggestionIdsBySource(e){const t=this.host.liveSuggestionIdsBySourceCache.get(e);if(t)return t.slice();const n=this.getLiveSuggestionIds().filter(i=>{const r=this.getInlineSuggestionMetadataFromDocument(i);if(r?.source)return r.source===e;if(e==="agent"&&r?.authorType==="ai")return!0;const o=this.getLiveSuggestion(i);return o?.source?o.source===e:e==="agent"&&o?.authorType==="ai"});return this.host.liveSuggestionIdsBySourceCache.set(e,n),n.slice()}getLiveSuggestionIdsByCommentThread(e){return e?this.getLiveSuggestionIds().filter(t=>{const n=this.getInlineSuggestionMetadataFromDocument(t);return n?.commentThreadId?n.commentThreadId===e:this.getLiveSuggestion(t)?.commentThreadId===e}):[]}getResolvableLiveSuggestionIdsBySource(e){return this.getLiveSuggestionIdsBySource(e).filter(t=>this.canResolveLiveSuggestion(t))}normalizeLiveSuggestionIds(e){return Array.from(new Set(e)).filter(t=>typeof t=="string"&&t.length>0)}getLiveSuggestionAuthorName(e){const t=this.getInlineSuggestionMetadataFromDocument(e),n=t?void 0:this.getLiveSuggestion(e),i=t?.agentName??n?.agentName;return i?.trim()?i.trim():(t?.authorType??n?.authorType)==="ai"?ze:Fs}getLiveSuggestionKind(e){const t=this.getLiveSuggestion(e);if(t)switch(t.type){case"inline-format":return"format";case"block-change":return"format";case"table-change":return t.tableRevision.suggestionKind;case"block-insert":case"paragraph-split":return"insert";case"block-delete":case"paragraph-merge":return"delete"}return this.getInlineSuggestionKindFromDocument(e)}getInlineSuggestionKindFromDocument(e){return this.host.inlineSuggestionKindCache.has(e)?this.host.inlineSuggestionKindCache.get(e)??null:(this.getDocumentSuggestionIdsCache(),this.host.inlineSuggestionKindCache.has(e)?this.host.inlineSuggestionKindCache.get(e)??null:(this.host.inlineSuggestionKindCache.set(e,null),null))}getResolvableSuggestionIdsForScope(e){switch(e.kind){case"source":return this.getResolvableLiveSuggestionIdsBySource(e.source);case"author":{const t=e.authorName.trim();return this.getLiveSuggestionIds().filter(n=>this.getLiveSuggestionAuthorName(n)===t).filter(n=>this.canResolveLiveSuggestion(n))}case"suggestion-kind":return this.getLiveSuggestionIds().filter(t=>this.getLiveSuggestionKind(t)===e.suggestionKind).filter(t=>this.canResolveLiveSuggestion(t))}}getInitialSuggestionIdsForDecisionScope(e){return e.kind==="ids"?this.normalizeLiveSuggestionIds(e.suggestionIds):this.getResolvableSuggestionIdsForScope(e)}getNextSuggestionIdsForDecisionScope(e,t){return e.kind==="ids"?t===0?this.normalizeLiveSuggestionIds(e.suggestionIds):[]:this.getResolvableSuggestionIdsForScope(e)}getResolvableSuggestionIdsFromDocument(){return this.getSuggestionIdsFromDocument()}getSuggestionIdsFromDocument(){return this.getDocumentSuggestionIdsCache().ids.slice()}documentContainsSuggestionId(e){return this.getDocumentSuggestionIdsCache().idSet.has(e)}getDocumentSuggestionIdsCache(){return this.host.documentSuggestionIdsCache&&this.host.documentSuggestionIdsCache.revision===this.host.derivedDocumentRevision?this.host.documentSuggestionIdsCache:(this.host.documentSuggestionIdsCache=this.createDocumentSuggestionIdsCache(this.host.getDocument()),this.host.documentSuggestionIdsCache)}createDocumentSuggestionIdsCache(e){const t=new Set;for(const i of this.blocksWithNotesAndChrome(e)){for(const r of this.getSuggestionIdsForBlock(i))t.add(r);this.indexInlineSuggestionFacts(i)}const n=Array.from(t);return{revision:this.host.derivedDocumentRevision,ids:n,idSet:new Set(n)}}indexInlineSuggestionFacts(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(const r of e)this.indexInlineSuggestionFacts(r);return}const t=e,n=t.marks?.suggestionId;if(typeof n=="string"&&n.length>0){this.host.inlineSuggestionMetadataCache.has(n)||this.host.inlineSuggestionMetadataCache.set(n,{id:n,source:t.marks?.suggestionSource,authorType:t.marks?.suggestionAuthorType,createdAt:t.marks?.suggestionCreatedAt,label:t.marks?.suggestionLabel,commentThreadId:t.marks?.suggestionCommentThreadId,agentName:t.marks?.suggestionAuthorName,agentModel:t.marks?.suggestionAgentModel,agentConversationId:t.marks?.suggestionAgentConversationId,agentRequestId:t.marks?.suggestionAgentRequestId,agentTurn:t.marks?.suggestionAgentTurn});const r=t.marks?.deletion?"delete":t.marks?.insertion?"insert":t.marks?.formatChange?"format":null;r&&!this.host.inlineSuggestionKindCache.has(n)&&this.host.inlineSuggestionKindCache.set(n,r)}const i=fn(t.marks?.layeredInsertion);if(i&&(this.host.inlineSuggestionMetadataCache.has(i.id)||this.host.inlineSuggestionMetadataCache.set(i.id,{id:i.id,source:i.source,authorType:i.authorType,createdAt:i.createdAt,label:i.label,commentThreadId:i.commentThreadId,agentName:i.authorName,agentModel:i.agentModel,agentConversationId:i.agentConversationId,agentRequestId:i.agentRequestId,agentTurn:i.agentTurn}),this.host.inlineSuggestionKindCache.set(i.id,"insert")),typeof t.structuralSuggestionId=="string"&&t.structuralSuggestionId.length>0){const r=t.structuralSuggestionKind==="insert"||t.structuralSuggestionKind==="split"?"insert":t.structuralSuggestionKind==="delete"||t.structuralSuggestionKind==="merge"?"delete":t.structuralSuggestionKind==="change"?"format":null;r&&this.host.inlineSuggestionKindCache.set(t.structuralSuggestionId,r)}if(typeof t.suggestionId=="string"&&t.suggestionId.length>0&&!this.host.inlineSuggestionKindCache.has(t.suggestionId)){const r=t.diffState==="insert"?"insert":t.diffState==="delete"?"delete":null;r&&this.host.inlineSuggestionKindCache.set(t.suggestionId,r)}t.children&&this.indexInlineSuggestionFacts(t.children)}getLiveSuggestionIdsForBlock(e){return this.getSuggestionIdsForBlock(e)}getSuggestionIdsForBlock(e){const t=this.host.suggestionIdsByBlockCache.get(e);if(t)return t;const n=new Set;this.collectSuggestionIdsFromBlockValue(e,n);const i=Array.from(n);return this.host.suggestionIdsByBlockCache.set(e,i),i}canResolveLiveSuggestion(e){if(this.host.canResolveLiveSuggestionCache.has(e))return this.host.canResolveLiveSuggestionCache.get(e)??!1;const t=this.computeCanResolveLiveSuggestion(e);return this.host.canResolveLiveSuggestionCache.set(e,t),t}computeCanResolveLiveSuggestion(e){const t=this.getLiveSuggestion(e);if(!t)return this.documentContainsSuggestionId(e);const n=this.host.getDocument();switch(t.type){case"inline-text":return this.documentContainsSuggestionId(t.id);case"inline-format":return this.host.inlineFormatRecordHasLiveMarker(t);case"block-change":{if(t.sequenceBlockIds)return this.getSequenceReplacementMembers(t).length>0;const i=z(n,t.blockId);return i?this.host.isListItemBlockChangeRecord(t)?i.type==="list"&&i.children.some(r=>r.structuralSuggestionId===t.id):t.acceptedBlock?this.blockChangeTargetIsOwned(t):this.blockContainsSuggestionMarker(i,t.id):!1}case"table-change":{const i=z(n,t.tableId);return i?.type!=="table"||!this.blockContainsSuggestionMarker(i,t.id)?!1:t.tableRevision.operations.some(r=>r.kind==="row"?i.children.some(o=>o.id===r.rowId):r.kind==="cell"?i.children.some(o=>o.id===r.rowId&&o.children.some(a=>a.id===r.cellId)):r.kind==="geometry"?r.pendingRows.some(o=>i.children.some(a=>a.id===o.id)):r.kind==="grid"||r.target==="table"?!0:r.target==="row"||r.target==="row-exception"?i.children.some(o=>o.id===r.rowId):i.children.some(o=>o.children.some(a=>a.id===r.cellId)))}case"block-insert":{const i=z(n,t.blockId);return i&&this.blockContainsSuggestionMarker(i,t.id)?!0:this.host.collectStructuralInsertBlockIds(n,t.id).length>0}case"block-delete":{const i=z(n,t.blockId);return!!(i&&this.blockContainsSuggestionMarker(i,t.id))}case"paragraph-split":{const i=z(n,t.blockId),r=z(n,t.insertedBlockId);return!!(i&&r&&(this.blockContainsSuggestionMarker(i,t.id)||this.blockContainsSuggestionMarker(r,t.id)))}case"paragraph-merge":{const i=z(n,t.firstBlockId),r=z(n,t.secondBlockId);return!r||r.type!=="paragraph"?!1:i&&i.type==="paragraph"?this.blockContainsSuggestionMarker(i,t.id)||this.blockContainsSuggestionMarker(r,t.id):this.blockContainsSuggestionMarker(r,t.id)}}}getUnresolvableLiveSuggestionRecords(){const e=[];for(const t of this.getLiveSuggestionIds()){if(this.canResolveLiveSuggestion(t))continue;const n=this.getLiveSuggestion(t);e.push({id:t,type:n?.type??"unknown",source:n?.source??"unknown",label:n?.label})}return e}pruneUnresolvableLiveSuggestionsInternal(){const e=this.getUnresolvableLiveSuggestionRecords();return e.length===0?[]:(this.host.transact(()=>{for(const t of e)this.deleteLiveSuggestion(t.id)}),e)}pruneUnresolvableLiveSuggestions(){const e=this.pruneUnresolvableLiveSuggestionsInternal();return this.host.lastPrunedUnresolvableLiveSuggestions=e,e}takeLastPrunedUnresolvableLiveSuggestions(){const e=this.host.lastPrunedUnresolvableLiveSuggestions;return this.host.lastPrunedUnresolvableLiveSuggestions=[],e}getDocumentWithAcceptedSuggestions(){return this.createLiveSuggestionProjection("accept").doc}getDocumentWithRejectedSuggestions(){return this.createLiveSuggestionProjection("reject").doc}getSelectionInRejectedSuggestionProjection(e){if(!e.anchor||!e.focus||this.getLiveSuggestionIds().length===0)return null;const t=this.host.getDocument(),n=H(e,this.host.ydoc,t),i=this.createLiveSuggestionProjection("reject"),r=wr(n,i.ydoc);if(!r.anchor||!r.focus)return null;const o=Ie(i.doc,r.anchor,r.focus)<=0;return{doc:i.doc,start:o?r.anchor:r.focus,end:o?r.focus:r.anchor}}createLiveSuggestionProjection(e){const t=this.getLiveSuggestionIds(),n=this.host.liveSuggestionProjectionCache.get(e);if(n&&n.revision===this.host.derivedDocumentRevision)return n.projection;const i=Ii.createSuggestionProjectionFromYDoc(this.host.ydoc,e,t);return this.host.liveSuggestionProjectionCache.set(e,{revision:this.host.derivedDocumentRevision,projection:i}),i}mapAcceptedSuggestionRangeToLiveRange(e,t,n){if(t<0||n<=t)return null;if(this.getLiveSuggestionIds().length===0)return{start:t,end:n};const i=this.createLiveSuggestionProjection("accept"),r=K(i.ydoc,e),o=r?ae(r):null,a=K(this.host.ydoc,e),l=a?ae(a):null;if(!o||!l||n>o.length)return null;const c=S.createRelativePositionFromTypeIndex(o,t,0),d=S.createRelativePositionFromTypeIndex(o,n,-1),g=S.createAbsolutePositionFromRelativePosition(c,this.host.ydoc),u=S.createAbsolutePositionFromRelativePosition(d,this.host.ydoc);return!g||!u||g.type!==l||u.type!==l||u.index<=g.index?null:{start:g.index,end:u.index}}blocksWithNotesAndChrome(e){return[...e.children,...e.notes??[],...e.chrome??[]]}collectSuggestionIdsFromBlockValue(e,t){yn.collectSuggestionIdsFromBlockValue(e,t)}static collectSuggestionIdsFromBlockValue(e,t){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(const r of e)yn.collectSuggestionIdsFromBlockValue(r,t);return}const n=e;typeof n.suggestionId=="string"&&n.suggestionId.length&&t.add(n.suggestionId);const i=fn(n.marks?.layeredInsertion);if(i&&t.add(i.id),typeof n.structuralSuggestionId=="string"&&n.structuralSuggestionId.length&&t.add(n.structuralSuggestionId),typeof n.structuralSuggestionRecords=="string"&&n.structuralSuggestionRecords.length)try{const r=JSON.parse(n.structuralSuggestionRecords);if(Array.isArray(r))for(const o of r)o&&typeof o.id=="string"&&o.id&&t.add(o.id)}catch{}n.marks&&typeof n.marks.suggestionId=="string"&&n.marks.suggestionId.length&&t.add(n.marks.suggestionId);for(const r of Object.values(n))r&&typeof r=="object"&&yn.collectSuggestionIdsFromBlockValue(r,t)}getSequenceReplacementMembers(e){const t=[],n=i=>{i.toArray().forEach((r,o)=>{r instanceof S.XmlElement&&(r.getAttribute("structuralSuggestionId")===e.id?t.push({yBlock:r,yParent:i,index:o}):n(r))})};for(const i of["content","notes"])this.host.ydoc.share.has(i)&&n(this.host.ydoc.getXmlFragment(i));return t}preserveSequenceAfterParagraphSplit(e,t){for(const r of t)this.setParagraphStructuralSuggestion(r,"change",void 0,e.id,"Paragraph");const n=this.getSequenceReplacementMembers(e),i={...e,blockId:n[0].yBlock.getAttribute("id"),sequenceBlockIds:n.map(({yBlock:r})=>r.getAttribute("id"))};this.saveLiveSuggestion(i,n[0].yBlock);for(const r of n.slice(1))this.embedLiveSuggestionRecordInTree(i,r.yBlock)}expandPendingSequenceBlockIds(e){for(const t of this.getLiveSuggestionIds()){const n=this.getLiveSuggestion(t);if(!(n?.type!=="block-change"||!n.sequenceBlockIds||!this.liveSuggestionRecordTouchesAnyBlock(n,e))){n.beforeBlock.id&&e.add(n.beforeBlock.id);for(const{yBlock:i}of this.getSequenceReplacementMembers(n)){const r=i.getAttribute("id");r&&e.add(r)}}}}resetLiveSuggestionsForBlocks(e,t){const n=new Set(e);this.expandPendingSequenceBlockIds(n);for(const g of this.getLiveSuggestionStore().values())if(g.type==="block-change"&&g.sequenceBlockIds&&this.liveSuggestionRecordTouchesAnyBlock(g,n)&&!this.applySuggestionRecordRejection(g))throw new Error("Could not restore the pending list conversion for replanning.");const i=this.host.collapseAffectedBlockIds(n,t);if(i.length===0)return;const r=new Set,o=this.host.getDocument(),a=qe(o),l=qe(t),c=new Set(i);for(const[g,u]of this.getLiveSuggestionStore())this.liveSuggestionRecordTouchesAnyBlock(u,c)&&r.add(g);for(const g of i){const u=a.get(g)?.block??z(o,g);u&&this.collectSuggestionIdsFromBlockValue(u,r)}const d=this.getSuggestionMutationSelection();for(const g of i){const u=a.get(g)?.block??z(o,g),p=l.get(g)?.block??z(t,g);if(p){if(!u||u.type==="paragraph"&&p.type==="paragraph"&&JSON.stringify(u)===JSON.stringify(p))continue;this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(g,this.cloneSuggestionSnapshot(p),d,d));continue}u&&this.runWithoutSuggesting(()=>this.host.deleteBlockById(g,d,d))}this.host.transact(()=>{for(const g of r)this.deleteLiveSuggestion(g)})}liveSuggestionRecordTouchesAnyBlock(e,t){const n=i=>t.has(i.getAttribute("id")??"")||i.toArray().some(r=>r instanceof S.XmlElement&&n(r));switch(e.type){case"block-change":return t.has(e.blockId)||!!e.sequenceBlockIds&&(!!e.beforeBlock.id&&t.has(e.beforeBlock.id)||this.getSequenceReplacementMembers(e).some(({yBlock:i})=>n(i)));case"block-insert":case"block-delete":case"paragraph-split":return t.has(e.blockId);case"table-change":return t.has(e.tableId);case"paragraph-merge":return t.has(e.firstBlockId)||t.has(e.secondBlockId);case"inline-format":return e.spans.some(i=>t.has(i.blockId));case"inline-text":return!1}}applyLiveSuggestionDecisionInternal(e,t){const n=this.normalizeLiveSuggestionIds(e);if(n.length===0)return 0;const i=n.filter(l=>{const c=this.getLiveSuggestion(l);return!c||c.type==="inline-text"||c.type==="inline-format"});if(i.length===n.length)return this.applyInlineSuggestionDecisions(new Set(i),t).size;let r=this.applyInlineSuggestionDecisions(new Set(i),t).size;const o=this.host.documentId==="live-suggestion-projection"?this.applySimpleProjectionBlockDecisions(n,t):new Set;r+=o.size;const a=new Set;for(const l of n){if(o.has(l))continue;const c=this.getLiveSuggestion(l);if(!c||c.type==="inline-text"||c.type==="inline-format")continue;const d=c?.type==="block-change"&&!this.host.isListItemBlockChangeRecord(c);if(d&&a.has(c.blockId)){this.deleteLiveSuggestion(l),r+=1;continue}(t==="accept"?this.acceptLiveSuggestionWithoutPruning(l):this.rejectLiveSuggestionWithoutPruning(l))&&(d&&a.add(c.blockId),r+=1)}return r}applySimpleProjectionBlockDecisions(e,t){const n=new Set,i=new Set,r=new Set,o=new Set;for(const l of e){const c=this.getLiveSuggestion(l);if(c){if(t==="accept"&&c.type==="block-delete"||t==="reject"&&c.type==="block-insert"){n.add(l),i.add(c.blockId),c.cleanupTrailingParagraphId&&i.add(c.cleanupTrailingParagraphId),o.add(l);continue}(t==="accept"&&(c.type==="block-insert"||c.type==="paragraph-split")||t==="reject"&&(c.type==="block-delete"||c.type==="paragraph-merge"))&&(r.add(l),o.add(l))}}if(o.size===0)return o;const a=l=>{const c=l.toArray();for(let d=c.length-1;d>=0;d-=1){const g=c[d];if(!(g instanceof S.XmlElement))continue;const u=g.getAttribute("id"),p=g.getAttribute("structuralSuggestionId"),h=g.getAttribute("suggestionId");if(typeof u=="string"&&i.has(u)||typeof p=="string"&&n.has(p)||typeof h=="string"&&n.has(h)){l.delete(d,1);continue}typeof p=="string"&&r.has(p)&&this.clearElementStructuralSuggestion(g),typeof h=="string"&&r.has(h)&&this.setDiffSuggestionAttributes(g,void 0,void 0),a(g)}};return this.host.transact(()=>{a(this.host.getYContentFragment()),a(this.host.getYNotesFragment());for(const l of o)this.deleteLiveSuggestion(l)}),o}applyLiveSuggestionDecisionScopeInternal(e){let t=0,n=[];const i=new Set,r=new Set,o=[];for(let a=0;a<el;a+=1){const l=this.getNextSuggestionIdsForDecisionScope(e.scope,a);if(a===0&&(n=l),l.length===0)break;const c=l.join("\0");if(r.has(c))break;r.add(c);for(const g of l)i.add(g);const d=this.applyLiveSuggestionDecisionInternal(l,e.decision);if(o.push(...this.pruneUnresolvableLiveSuggestionsInternal()),d<=0)break;t+=d}return{decision:e.decision,scope:e.scope,resolvedCount:t,initialSuggestionIds:n,attemptedSuggestionIds:Array.from(i),attemptedSuggestionIdCount:i.size,prunedSuggestions:o}}decideLiveSuggestions(e){this.host.lastPrunedUnresolvableLiveSuggestions=[];const t=this.getInitialSuggestionIdsForDecisionScope(e.scope),n={decision:e.decision,scope:e.scope,resolvedCount:0,initialSuggestionIds:t,attemptedSuggestionIds:[],attemptedSuggestionIdCount:0,prunedSuggestions:[]};if(t.length===0)return n;let i=n;const r=e.historyOrigin??this.getLiveSuggestionDecisionHistoryOrigin(e);return this.host.runWithUndoGroup(r,()=>{const o=this.applyLiveSuggestionDecisionScopeInternal(e),a=o.prunedSuggestions.concat(this.pruneUnresolvableLiveSuggestionsInternal());i={...o,prunedSuggestions:a},this.host.lastPrunedUnresolvableLiveSuggestions=a,this.host.reconcileFootnotes(),this.host.resolveCommentsForSettledSuggestions(i.attemptedSuggestionIds)}),i}getLiveSuggestionDecisionHistoryOrigin(e){if(e.scope.kind==="source")return`live-suggestion-${e.decision}-source:${e.scope.source}`;if(e.scope.kind==="author")return`live-suggestion-${e.decision}-author:${e.scope.authorName}`;if(e.scope.kind==="suggestion-kind")return`live-suggestion-${e.decision}-kind:${e.scope.suggestionKind}`;const t=this.normalizeLiveSuggestionIds(e.scope.suggestionIds);return`live-suggestion-${e.decision}-individual:${t.join(",")}`}acceptLiveSuggestions(e){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"ids",suggestionIds:e}}).resolvedCount}acceptLiveSuggestionsBySource(e){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"source",source:e}})}acceptLiveSuggestionsByAuthor(e){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"author",authorName:e}})}rejectLiveSuggestionsByAuthor(e){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"author",authorName:e}})}acceptLiveSuggestionsByKind(e){return this.decideLiveSuggestions({decision:"accept",scope:{kind:"suggestion-kind",suggestionKind:e}})}rejectLiveSuggestionsByKind(e){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"suggestion-kind",suggestionKind:e}})}rejectLiveSuggestions(e){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"ids",suggestionIds:e}}).resolvedCount}rejectLiveSuggestionsBySource(e){return this.decideLiveSuggestions({decision:"reject",scope:{kind:"source",source:e}})}runWithoutSuggesting(e){const t=this.host.suggestingMode;this.host.suggestingMode=!1;try{return e()}finally{this.host.suggestingMode=t}}getSuggestionIdFromInheritedMarks(e){return e?.insertion&&e.suggestionId&&this.isOwnPendingSuggestionSpan(e)?e.suggestionId:ce()}getSuggestionIdForSuggestedSelectionOverwrite(e,t,n){if(!this.host.suggestingMode||!n?.anchor||!n.focus||Ie(e,n.anchor,n.focus)===0)return null;const[i,r]=Ie(e,n.anchor,n.focus)<=0?[n.anchor,n.focus]:[n.focus,n.anchor];if(i.block!==t.block||r.block!==t.block)return null;const o=z(e,t.block);if(!o)return null;if(o.type==="paragraph")return r.offset>i.offset?ce():null;if(o.type!=="list")return null;const a=this.host.getListCursorInfo(o,i),l=this.host.getListCursorInfo(o,r);return!a||!l||a.itemIndex!==l.itemIndex?null:(o.children[a.itemIndex],l.offsetInItem>a.offsetInItem?ce():null)}getInlineInsertionSuggestionNodeInTextChildren(e,t){let n=0,i=null;for(const r of e){if(r.type!=="text")continue;const o=r.text.length,a=n+o,l=!!(r.marks?.insertion&&r.marks.suggestionId&&this.isOwnPendingSuggestionSpan(r.marks));if(t>=n&&t<=a&&l)return r;t===a&&l&&(i=r),n=a}return i}getInlineInsertionSuggestionIdInTextChildren(e,t){return this.getInlineInsertionSuggestionNodeInTextChildren(e,t)?.marks?.suggestionId??null}getInlineInsertionSuggestionNodeAtPosition(e,t){const n=z(e,t.block);if(!n)return null;if(n.type==="paragraph")return this.getInlineInsertionSuggestionNodeInTextChildren(n.children,t.offset);if(n.type!=="list")return null;const i=this.host.getListCursorInfo(n,t);if(!i)return null;const r=n.children[i.itemIndex];return r?this.getInlineInsertionSuggestionNodeInTextChildren(r.children,i.offsetInItem):null}getInlineInsertionSuggestionIdAtPosition(e,t){return this.getInlineInsertionSuggestionNodeAtPosition(e,t)?.marks?.suggestionId??null}getStructuralInsertSuggestionIdAtPosition(e,t){const n=z(e,t.block);if(!n)return null;if("structuralSuggestionKind"in n&&n.structuralSuggestionKind==="insert"&&"structuralSuggestionId"in n&&typeof n.structuralSuggestionId=="string")return n.structuralSuggestionId;if(n.type!=="list")return null;const i=this.host.getListCursorInfo(n,t);if(!i)return null;const r=n.children[i.itemIndex];return r?.structuralSuggestionKind==="insert"&&r.structuralSuggestionId?r.structuralSuggestionId:null}getBlockInsertSuggestionIdForBlock(e){return e?(e.type==="paragraph"||e.type==="list")&&e.structuralSuggestionKind==="insert"&&typeof e.structuralSuggestionId=="string"&&e.structuralSuggestionId.length>0?e.structuralSuggestionId:"diffState"in e&&e.diffState==="insert"&&"suggestionId"in e&&typeof e.suggestionId=="string"&&e.suggestionId.length>0?e.suggestionId:null:null}getEnclosingBlockInsertSuggestionIdForBlockId(e,t){let n=z(e,t);for(;n;){const i=this.getBlockInsertSuggestionIdForBlock(n);if(i)return i;if(typeof n.id!="string")break;const r=Je(e,n.id);if(!r||!("id"in r)||typeof r.id!="string")break;n=r}return null}stripSuggestionMarksFromTextMark(e){if(!e)return;const t={...e};return delete t.insertion,delete t.deletion,delete t.suggestionId,delete t.formatChange,delete t.suggestionSource,delete t.suggestionAuthorType,delete t.suggestionCreatedAt,delete t.suggestionLabel,delete t.suggestionCommentThreadId,delete t.suggestionAuthorName,delete t.suggestionAgentModel,delete t.suggestionAgentConversationId,delete t.suggestionAgentRequestId,delete t.suggestionAgentTurn,delete t.suggestionPriorAttributes,delete t.layeredInsertion,delete t.docxMove,Object.keys(t).length>0?t:void 0}buildInlineSuggestionMetadataMarks(e,t,n){const i=this.host.liveSuggestionMetadataContext,r=i?.source??"manual",o=i?.authorType??(r==="agent"?"ai":"human");return{suggestionId:e,suggestionSource:r,suggestionAuthorType:o,suggestionCreatedAt:n??i?.createdAt??Date.now(),suggestionLabel:t??i?.label,...i?.commentThreadId?{suggestionCommentThreadId:i.commentThreadId}:{},suggestionAuthorName:this.resolveSuggestionAuthorName(o,i?.agentName),...i?.agentModel?{suggestionAgentModel:i.agentModel}:{},...i?.agentConversationId?{suggestionAgentConversationId:i.agentConversationId}:{},...i?.agentRequestId!==void 0?{suggestionAgentRequestId:i.agentRequestId}:{},...i?.agentTurn!==void 0?{suggestionAgentTurn:i.agentTurn}:{}}}buildSuggestionInsertionMarks(e,t,n="Insert",i,r){const o=e?.suggestionId===t?e:r?.suggestionId===t?r:null;return this.recordStampedId("insertionIds",t),{...e||{},insertion:!0,...this.buildInlineSuggestionMetadataMarks(t,n,i),...this.pickInlineSuggestionMetadataMarks(o)}}pickInlineSuggestionMetadataMarks(e){return e?Object.fromEntries(Object.entries({suggestionSource:e.suggestionSource,suggestionAuthorType:e.suggestionAuthorType,suggestionCreatedAt:e.suggestionCreatedAt,suggestionLabel:e.suggestionLabel,suggestionCommentThreadId:e.suggestionCommentThreadId,suggestionAuthorName:e.suggestionAuthorName,suggestionAgentModel:e.suggestionAgentModel,suggestionAgentConversationId:e.suggestionAgentConversationId,suggestionAgentRequestId:e.suggestionAgentRequestId,suggestionAgentTurn:e.suggestionAgentTurn}).filter(([,t])=>t!==void 0)):{}}clearInheritedDeletionFromInsertedSuggestion(e,t,n){n<=0||ie(e,t,n,{deletion:null})}findAdjacentDeletionSuggestionAttrs(e,t,n){if(n<=0)return null;const i=t+n,r=Z(e);let o=0,a=null,l=null;for(const c of r){if(typeof c.insert!="string")continue;const d=o,g=o+c.insert.length,u=c.attributes||{},p=u.deletion&&typeof u.suggestionId=="string"&&this.isOwnPendingSuggestionSpan(u);if(p&&g===t&&(a=u),p&&d===i){l=u;break}if(o=g,o>i)break}return a??l}findAdjacentDeletionSuggestionId(e,t,n){return this.findAdjacentDeletionSuggestionAttrs(e,t,n)?.suggestionId??null}applySuggestedDeletionToTextRange(e,t,n,i){const r=this.host.collectOverlappingTextSpans(e,t,n);if(r.length===0)return{retainedLength:0,changed:!1};const o=i?null:this.findAdjacentDeletionSuggestionAttrs(e,t,n),a=i??o?.suggestionId??ce(),l={...this.buildInlineSuggestionMetadataMarks(a,"Delete"),...this.pickInlineSuggestionMetadataMarks(o?.suggestionId===a?o:null)};let c=0,d=!1;for(let g=r.length-1;g>=0;g--){const u=r[g],p=u.attributes||{};if(p.insertion){if(this.isOwnPendingSuggestionSpan(p)){e.delete(u.start,u.length),d=!0;continue}c+=u.length,this.recordStampedId("deletionIds",a),ie(e,u.start,u.length,{deletion:!0,...l,layeredInsertion:JSON.stringify({id:p.suggestionId,source:p.suggestionSource,authorType:p.suggestionAuthorType,createdAt:p.suggestionCreatedAt,label:p.suggestionLabel,authorName:p.suggestionAuthorName,commentThreadId:p.suggestionCommentThreadId,agentModel:p.suggestionAgentModel,agentConversationId:p.suggestionAgentConversationId,agentRequestId:p.suggestionAgentRequestId,agentTurn:p.suggestionAgentTurn}),formatChange:null,suggestionPriorAttributes:null}),d=!0;continue}if(c+=u.length,p.deletion){i&&p.suggestionId!==i&&(this.recordStampedId("deletionIds",a),ie(e,u.start,u.length,{...l,formatChange:null,suggestionPriorAttributes:null}),d=!0);continue}this.recordStampedId("deletionIds",a),ie(e,u.start,u.length,{deletion:!0,...l,formatChange:null,suggestionPriorAttributes:null}),d=!0}return{retainedLength:c,changed:d}}clearElementStructuralSuggestion(e){e.removeAttribute("structuralSuggestionId"),e.removeAttribute("structuralSuggestionKind"),e.removeAttribute("structuralSuggestionRole"),e.removeAttribute("structuralSuggestionLabel"),e.removeAttribute("structuralSuggestionRecord")}clearParagraphStructuralSuggestion(e){this.clearElementStructuralSuggestion(e)}setElementStructuralSuggestion(e,t,n,i,r){this.recordStampedId(t==="insert"||t==="split"?"structuralInsertIds":"structuralDeleteIds",i),e.setAttribute("structuralSuggestionId",i),e.setAttribute("structuralSuggestionKind",t),n?e.setAttribute("structuralSuggestionRole",n):e.removeAttribute("structuralSuggestionRole"),r?e.setAttribute("structuralSuggestionLabel",r):e.removeAttribute("structuralSuggestionLabel")}setParagraphStructuralSuggestion(e,t,n,i,r){this.setElementStructuralSuggestion(e,t,n,i,r)}setDiffSuggestionAttributes(e,t,n){t?e.setAttribute("diffState",t):e.removeAttribute("diffState"),n?e.setAttribute("suggestionId",n):e.removeAttribute("suggestionId")}markInsertedBlockElement(e,t,n="Insert"){if(e.nodeName==="paragraph"||e.nodeName==="list"||e.nodeName==="list-item"){this.clearElementStructuralSuggestion(e),this.setElementStructuralSuggestion(e,"insert",void 0,t,n);return}this.setDiffSuggestionAttributes(e,"insert",t)}markDeletedBlockElement(e,t,n="Delete"){if(e.nodeName==="paragraph"||e.nodeName==="list"||e.nodeName==="list-item"){this.clearElementStructuralSuggestion(e),this.setElementStructuralSuggestion(e,"delete",void 0,t,n);return}this.setDiffSuggestionAttributes(e,"delete",t)}markTableSuggestionRows(e,t,n,i){const r=this.cloneSuggestionSnapshot(e);return r.children=r.children.map(o=>t.has(o.id)?{...o,diffState:n,suggestionId:i,children:o.children.map(a=>({...a,diffState:n,suggestionId:i}))}:o),r}markTableSuggestionColumn(e,t,n,i){const r=this.cloneSuggestionSnapshot(e);return r.children=r.children.map(o=>({...o,children:o.children.map((a,l)=>l===t?{...a,diffState:n,suggestionId:i}:a)})),r}buildSuggestedTableChange(e,t,n){const i=(h,f,m)=>({id:n,type:"table-change",tableId:e.id,label:h,tableRevision:{version:1,suggestionKind:f,...m}}),r=e.children.map(h=>h.id),o=t.children.map(h=>h.id),a=h=>JSON.stringify(h,(f,m)=>{if(f!=="id"){if(f==="marks"&&m&&typeof m=="object"){const y={...m};return y.fontFamily===Fe&&delete y.fontFamily,Object.keys(y).length?y:void 0}return m}}),l=a({...e,children:[]})===a({...t,children:[]}),c=(h,f)=>{let m=0;for(const y of f)y===h[m]&&m++;return m===h.length};if(t.children.length>e.children.length&&c(r,o)&&l&&e.children.every(h=>a(h)===a(t.children.find(f=>f.id===h.id)))){const h=new Set(r),f=t.children.map((b,k)=>({row:b,rowIndex:k})).filter(({row:b})=>!h.has(b.id)),m=new Set(f.map(({row:b})=>b.id)),y=f.length===1?"Insert table row":"Insert table rows";return{liveBlock:this.markTableSuggestionRows(t,m,"insert",n),label:y,record:i(y,"insert",{markers:f.map(({row:b,rowIndex:k})=>({kind:"row-insert",rowId:b.id,rowIndex:k})),operations:f.map(({row:b,rowIndex:k})=>({kind:"row",action:"insert",rowId:b.id,rowIndex:k,row:this.cloneSuggestionSnapshot(b)}))})}}if(t.children.length<e.children.length&&c(o,r)&&l&&t.children.every(h=>a(h)===a(e.children.find(f=>f.id===h.id)))){const h=new Set(o),f=e.children.map((I,v)=>({row:I,rowIndex:v})).filter(({row:I})=>!h.has(I.id)),m=new Set(f.map(({row:I})=>I.id)),y=new Map(t.children.map(I=>[I.id,I])),b=this.cloneSuggestionSnapshot(t);b.children=e.children.map(I=>y.get(I.id)??I);const k=f.length===1?"Delete table row":"Delete table rows";return{liveBlock:this.markTableSuggestionRows(b,m,"delete",n),label:k,record:i(k,"delete",{markers:f.map(({row:I,rowIndex:v})=>({kind:"row-delete",rowId:I.id,rowIndex:v})),operations:f.map(({row:I,rowIndex:v})=>({kind:"row",action:"delete",rowId:I.id,rowIndex:v,row:this.cloneSuggestionSnapshot(I)}))})}}const d=this.host.findSingleTableColumnDelta(e,t);if(d&&(a({...e,children:[],columnWidths:[]})!==a({...t,children:[],columnWidths:[]})||e.children.some((h,f)=>{const m=t.children[f];return a({...h,children:[]})!==a({...m,children:[]})?!0:h.children.some(y=>{const b=m.children.find(k=>k.id===y.id);return b&&a(y)!==a(b)})})))return null;if(d?.kind==="insert"){const h=[],f=[];for(let m=0;m<t.children.length;m++){const y=t.children[m],b=y.children[d.index];b&&(h.push({kind:"cell",action:"insert",rowId:y.id,cellId:b.id,cellIndex:d.index,cell:this.cloneSuggestionSnapshot(b)}),f.push({kind:"cell-insert",rowId:y.id,cellId:b.id,rowIndex:m,cellIndex:d.index,gridColumn:d.index}))}return h.push({kind:"grid",currentColumnWidths:[...t.columnWidths],priorColumnWidths:[...e.columnWidths],currentGridXml:"",priorGridXml:""}),{liveBlock:this.markTableSuggestionColumn(t,d.index,"insert",n),label:"Insert table column",record:i("Insert table column","insert",{markers:f,operations:h})}}if(d?.kind==="delete"){const h=[],f=[];for(let m=0;m<e.children.length;m++){const y=e.children[m],b=y.children[d.index];b&&(h.push({kind:"cell",action:"delete",rowId:y.id,cellId:b.id,cellIndex:d.index,cell:this.cloneSuggestionSnapshot(b)}),f.push({kind:"cell-delete",rowId:y.id,cellId:b.id,rowIndex:m,cellIndex:d.index,gridColumn:d.index}))}return h.push({kind:"grid",currentColumnWidths:[...t.columnWidths],priorColumnWidths:[...e.columnWidths],currentGridXml:"",priorGridXml:""}),{liveBlock:this.markTableSuggestionColumn(e,d.index,"delete",n),label:"Delete table column",record:i("Delete table column","delete",{markers:f,operations:h})}}const g=Ze(e),u=Ze(t);if(e.children.length===t.children.length&&g.rows===u.rows&&g.cols===u.cols&&e.children.every((h,f)=>h.id===t.children[f]?.id)){const h=g.cells.map(f=>{const m=u.byId.get(f.cell.id);return m?{before:f,after:m}:null}).filter(f=>!!f&&(f.before.rowSpan!==f.after.rowSpan||f.before.colSpan!==f.after.colSpan));if(h.length===1&&h[0].before.col===h[0].after.col&&h[0].before.row===h[0].after.row&&h[0].before.colSpan===h[0].after.colSpan&&h[0].before.rowSpan!==h[0].after.rowSpan){const f=h[0].before,m=h[0].after,y=m.rowSpan>f.rowSpan,b=y?f.row+f.rowSpan:m.row+m.rowSpan,k=y?m.row+m.rowSpan:f.row+f.rowSpan,I=[],v=new Set([e.children[f.row].id]);for(let F=b;F<k;F++){const E=t.children[F];E&&(v.add(E.id),I.push({kind:"cell-merge",rowId:E.id,rowIndex:F,gridColumn:m.col,...y?{vMerge:"cont"}:{vMergeOrig:"cont"}}))}const x=t.children.filter(F=>v.has(F.id)).map(F=>this.cloneSuggestionSnapshot(F)),A=e.children.filter(F=>v.has(F.id)).map(F=>this.cloneSuggestionSnapshot(F));if(!l||e.children.some(F=>!v.has(F.id)&&a(F)!==a(t.children.find(E=>E.id===F.id))))return null;const C=y?"Merge table cells":"Split table cells";return{liveBlock:this.cloneSuggestionSnapshot(t),label:C,record:i(C,"format",{markers:I,operations:[{kind:"geometry",pendingRows:x,acceptedRows:this.cloneSuggestionSnapshot(x),rejectedRows:A}]})}}}const p=h=>JSON.stringify(h.children,(f,m)=>{if(f!=="marks"||!m||typeof m!="object")return m;const y={...m};return y.fontFamily===Fe&&delete y.fontFamily,Object.keys(y).length>0?y:void 0});if(e.children.length===t.children.length&&e.children.every((h,f)=>{const m=t.children[f];return m?.id===h.id&&h.children.length===m.children.length&&h.children.every((y,b)=>{const k=m.children[b];return k?.id===y.id&&y.colSpan===k.colSpan&&y.rowSpan===k.rowSpan&&p(y)===p(k)})})){const h=[],f=[],m=(b,k,I)=>{const v={},x={};for(const A of I){const C=b[A],F=k[A];JSON.stringify(C)!==JSON.stringify(F)&&(F!==void 0&&(v[A]=F),C!==void 0&&(x[A]=C))}return{current:v,prior:x}};JSON.stringify(e.columnWidths)!==JSON.stringify(t.columnWidths)&&h.push({kind:"grid",currentColumnWidths:[...t.columnWidths],priorColumnWidths:[...e.columnWidths],currentGridXml:"",priorGridXml:""});const y=m(e,t,["tableWidth","align","borderColor","borderWidth","borders","cellPadding"]);(Object.keys(y.current).length>0||Object.keys(y.prior).length>0)&&(f.push({kind:"table-properties"}),h.push({kind:"properties",target:"table",currentPropertiesXml:"",priorPropertiesXml:"",currentAttributes:y.current,priorAttributes:y.prior})),e.hasHeader!==t.hasHeader&&t.children[0]&&(f.push({kind:"row-properties",rowId:t.children[0].id,rowIndex:0}),h.push({kind:"properties",target:"row",rowId:t.children[0].id,currentPropertiesXml:"",priorPropertiesXml:"",currentTableAttributes:t.hasHeader===void 0?{}:{hasHeader:t.hasHeader},priorTableAttributes:e.hasHeader===void 0?{}:{hasHeader:e.hasHeader}}));for(let b=0;b<t.children.length;b++){const k=e.children[b],I=t.children[b];for(let v=0;v<I.children.length;v++){const x=k.children[v],A=I.children[v],C=m(x,A,["verticalAlign","backgroundColor","borders","padding"]);if(Object.keys(C.current).length===0&&Object.keys(C.prior).length===0)continue;const F=u.byId.get(A.id);f.push({kind:"cell-properties",rowId:I.id,cellId:A.id,rowIndex:b,cellIndex:v,gridColumn:F?.col}),h.push({kind:"properties",target:"cell",rowId:I.id,cellId:A.id,currentPropertiesXml:"",priorPropertiesXml:"",currentAttributes:C.current,priorAttributes:C.prior})}}if(h.length>0)return{liveBlock:this.cloneSuggestionSnapshot(t),label:"Change table formatting",record:i("Change table formatting","format",{markers:f,operations:h})}}return null}hasSameTableGeometry(e,t){return e.children.length===t.children.length&&e.children.every((n,i)=>{const r=t.children[i];return r?.id===n.id&&n.children.length===r.children.length&&n.children.every((o,a)=>{const l=r.children[a];return l?.id===o.id&&l.colSpan===o.colSpan&&l.rowSpan===o.rowSpan})})}reconcileTableDescendantIds(e,t){const n=this.cloneSuggestionSnapshot(t),i=new Set(["id","diffState","suggestionId","structuralSuggestionId","structuralSuggestionKind","structuralSuggestionRole","structuralSuggestionLabel","structuralSuggestionRecord","structuralSuggestionRecords"]),r=b=>qt(JSON.parse(JSON.stringify(b,(k,I)=>i.has(k)?void 0:I))),o=e.children,a=n.children,l=new Set(o.map(b=>b.id)),c=new Set(a.map(b=>b.id)),d=new Set(o.flatMap(b=>b.children.map(k=>k.id))),g=new Set(a.flatMap(b=>b.children.map(k=>k.id))),u=new Map([...o,...a].map(b=>[b,r(b)])),p=(b,k)=>b.id===k.id?0:l.has(k.id)||c.has(b.id)?2.25:u.get(b)===u.get(k)?0:b.children.length===k.children.length&&b.children.every((I,v)=>{const x=k.children[v];return x?.colSpan===I.colSpan&&x?.rowSpan===I.rowSpan})?.75:2.25,h=Array.from({length:o.length+1},()=>Array(a.length+1).fill(0));for(let b=0;b<=o.length;b++)h[b][0]=b;for(let b=0;b<=a.length;b++)h[0][b]=b;for(let b=1;b<=o.length;b++)for(let k=1;k<=a.length;k++)h[b][k]=Math.min(h[b-1][k]+1,h[b][k-1]+1,h[b-1][k-1]+p(o[b-1],a[k-1]));const f=[];let m=o.length,y=a.length;for(;m>0&&y>0;){const b=p(o[m-1],a[y-1]);b<2&&Math.abs(h[m][y]-(h[m-1][y-1]+b))<1e-4?(f.push([o[m-1],a[y-1]]),m--,y--):h[m][y]===h[m-1][y]+1?m--:y--}for(const[b,k]of f)if(k.id=b.id,b.children.length===k.children.length)for(let I=0;I<b.children.length;I++){const v=b.children[I],x=k.children[I];v.colSpan!==x.colSpan||v.rowSpan!==x.rowSpan||v.id!==x.id&&(d.has(x.id)||g.has(v.id))||(x.id=v.id)}return n}mergePendingTableRevisionState(e,t){const n=this.cloneSuggestionSnapshot(t);e.structuralSuggestionRecords&&(n.structuralSuggestionRecords=e.structuralSuggestionRecords),e.docxTablePropertyOverrides&&(n.docxTablePropertyOverrides=e.docxTablePropertyOverrides);const i=(r,o)=>{!o.diffState&&r.diffState&&(o.diffState=r.diffState),!o.suggestionId&&r.suggestionId&&(o.suggestionId=r.suggestionId)};for(let r=0;r<e.children.length;r++){const o=e.children[r];let a=n.children.find(l=>l.id===o.id);if(!a&&o.diffState==="delete"){const l=e.children.slice(r+1).map(d=>d.id).find(d=>n.children.some(g=>g.id===d)),c=l?n.children.findIndex(d=>d.id===l):n.children.length;a=this.cloneSuggestionSnapshot(o),n.children.splice(c,0,a)}if(a){i(o,a);for(let l=0;l<o.children.length;l++){const c=o.children[l];let d=a.children.find(g=>g.id===c.id);if(!d&&c.diffState==="delete"){const g=o.children.slice(l+1).map(p=>p.id).find(p=>a.children.some(h=>h.id===p)),u=g?a.children.findIndex(p=>p.id===g):a.children.length;d=this.cloneSuggestionSnapshot(c),a.children.splice(u,0,d)}d&&i(c,d)}}}return n}getYTextForSuggestionSpan(e){const t=K(this.host.ydoc,e.blockId);if(!(t instanceof S.XmlElement))return null;if(e.itemIndex===void 0)return ae(t);const n=[];for(let r=0;r<t.length;r++){const o=t.get(r);o instanceof S.XmlElement&&o.nodeName==="list-item"&&n.push(o)}const i=n[e.itemIndex];return i?ae(i):null}stripInlineSuggestionMarks(e,t,n){ie(e,t,n,{insertion:null,deletion:null,suggestionId:null,formatChange:null,suggestionSource:null,suggestionAuthorType:null,suggestionCreatedAt:null,suggestionLabel:null,suggestionCommentThreadId:null,suggestionAuthorName:null,suggestionAgentModel:null,suggestionAgentConversationId:null,suggestionAgentRequestId:null,suggestionAgentTurn:null,suggestionPriorAttributes:null,layeredInsertion:null,docxMove:null})}restoreInlineSuggestionFormatting(e,t,n,i){const r=this.host.collectOverlappingTextSpans(e,t,n),o=r.length>0?r:[{start:t,length:n,attributes:{}}];for(const a of o){const l={insertion:null,deletion:null,suggestionId:null,formatChange:null,suggestionSource:null,suggestionAuthorType:null,suggestionCreatedAt:null,suggestionLabel:null,suggestionCommentThreadId:null,suggestionAuthorName:null,suggestionAgentModel:null,suggestionAgentConversationId:null,suggestionAgentRequestId:null,suggestionAgentTurn:null,suggestionPriorAttributes:null,layeredInsertion:null,docxMove:null},c=yi(a.attributes?.suggestionPriorAttributes)??i,d=new Set([...Object.keys(a.attributes||{}),...Object.keys(c||{})]);d.delete("insertion"),d.delete("deletion"),d.delete("suggestionId"),d.delete("formatChange"),d.delete("suggestionSource"),d.delete("suggestionAuthorType"),d.delete("suggestionCreatedAt"),d.delete("suggestionLabel"),d.delete("suggestionCommentThreadId"),d.delete("suggestionAuthorName"),d.delete("suggestionAgentModel"),d.delete("suggestionAgentConversationId"),d.delete("suggestionAgentRequestId"),d.delete("suggestionAgentTurn"),d.delete("suggestionPriorAttributes"),d.delete("layeredInsertion"),d.delete("docxMove");for(const g of d)Object.prototype.hasOwnProperty.call(c,g)?l[g]=c[g]:l[g]=null;ie(e,a.start,a.length,l)}}clearStructuralSuggestionById(e,t){for(const n of e.toArray()){if(!(n instanceof S.XmlElement))continue;n.getAttribute("structuralSuggestionId")===t&&this.clearElementStructuralSuggestion(n);const i=n.getAttribute("structuralSuggestionRecords");if(typeof i=="string"&&i.length>0)try{const r=JSON.parse(i);if(Array.isArray(r)){const o=r.filter(a=>a?.id!==t);o.length!==r.length&&(o.length>0?n.setAttribute("structuralSuggestionRecords",JSON.stringify(o)):n.removeAttribute("structuralSuggestionRecords"))}}catch{}n.getAttribute("suggestionId")===t&&this.setDiffSuggestionAttributes(n,void 0,void 0),this.clearStructuralSuggestionById(n,t)}}blockChangeTargetIsOwned(e){if(e.sequenceBlockIds)return this.getSequenceReplacementMembers(e).length>0;const t=z(this.host.getDocument(),e.blockId);return t?this.blockContainsSuggestionMarker(t,e.id)?!0:t.structuralSuggestionId?!1:Ll(this.host.ydoc,e.blockId)===1:!1}blockContainsSuggestionMarker(e,t){if(!e||typeof e!="object")return!1;if(e.suggestionId===t||e.structuralSuggestionId===t)return!0;const n=e.structuralSuggestionRecords;if(typeof n=="string"&&n.length>0)try{const i=JSON.parse(n);if(Array.isArray(i)&&i.some(r=>r?.id===t))return!0}catch{}return Array.isArray(e.children)?e.children.some(i=>this.blockContainsSuggestionMarker(i,t)):!1}getSuggestionMutationSelection(){return this.host.afterOperationSelection??this.host.beforeOperationSelection??{anchor:null,focus:null}}collectNestedSuggestionIdsForBlock(e,t){const n=z(this.host.getDocument(),e);if(!n)return[];const i=new Set;return this.collectSuggestionIdsFromBlockValue(n,i),t&&i.delete(t),Array.from(i)}clearSuggestionMarkerFromValue(e,t){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(const i of e)this.clearSuggestionMarkerFromValue(i,t);return}const n=e;if(n.suggestionId===t&&(delete n.suggestionId,delete n.diffState),n.structuralSuggestionId===t&&(delete n.structuralSuggestionId,delete n.structuralSuggestionKind,delete n.structuralSuggestionRole,delete n.structuralSuggestionLabel,delete n.structuralSuggestionRecord),typeof n.structuralSuggestionRecords=="string")try{const i=JSON.parse(n.structuralSuggestionRecords);if(Array.isArray(i)){const r=i.filter(o=>o?.id!==t);r.length>0?n.structuralSuggestionRecords=JSON.stringify(r):delete n.structuralSuggestionRecords}}catch{}for(const i of Object.values(n))i&&typeof i=="object"&&this.clearSuggestionMarkerFromValue(i,t)}applyTableGeometryRows(e,t,n){const i=new Map(t.map(a=>[a.id,a])),r=new Map(n.map(a=>[a.id,a])),o=new Set([...i.keys(),...r.keys()]);for(const a of o){const l=e.children.find(p=>p.id===a),c=i.get(a),d=r.get(a);if(!l||!c||!d)continue;const g=new Set(c.children.map(p=>p.id)),u=new Set(d.children.map(p=>p.id));l.children=l.children.filter(p=>!g.has(p.id)||u.has(p.id));for(let p=0;p<d.children.length;p++){const h=d.children[p],f=c.children.find(y=>y.id===h.id);let m=l.children.find(y=>y.id===h.id);if(!m&&!f&&(m=this.cloneSuggestionSnapshot(h),l.children.splice(Math.min(p,l.children.length),0,m)),!(!m||!f)){JSON.stringify(f.children)!==JSON.stringify(h.children)&&JSON.stringify(m.children)===JSON.stringify(f.children)&&(m.children=this.cloneSuggestionSnapshot(h.children));for(const y of["rowSpan","colSpan"])f[y]!==h[y]&&(h[y]===void 0?delete m[y]:m[y]=h[y])}}}}applyTableRevisionDecision(e,t){const n=z(this.host.getDocument(),e.tableId);if(!n||n.type!=="table")return!1;const i=this.cloneSuggestionSnapshot(n);let r={version:1};if(i.docxTablePropertyOverrides)try{const l=JSON.parse(i.docxTablePropertyOverrides);l?.version===1&&(r=l)}catch{}for(const l of e.tableRevision.operations){if(l.kind==="row"){const f=l.action==="insert"?t==="accept":t==="reject",m=i.children.findIndex(y=>y.id===l.rowId);f&&m<0?i.children.splice(Math.min(l.rowIndex,i.children.length),0,this.cloneSuggestionSnapshot(l.row)):!f&&m>=0&&i.children.splice(m,1);continue}if(l.kind==="cell"){const f=i.children.find(b=>b.id===l.rowId);if(!f)continue;const m=l.action==="insert"?t==="accept":t==="reject",y=f.children.findIndex(b=>b.id===l.cellId);m&&y<0?f.children.splice(Math.min(l.cellIndex,f.children.length),0,this.cloneSuggestionSnapshot(l.cell)):!m&&y>=0&&f.children.splice(y,1);continue}if(l.kind==="geometry"){this.applyTableGeometryRows(i,l.pendingRows,t==="accept"?l.acceptedRows:l.rejectedRows);continue}if(l.kind==="grid"){const f=t==="accept"?l.currentColumnWidths:l.priorColumnWidths,m=t==="accept"?l.currentGridXml:l.priorGridXml;i.columnWidths=[...f],m&&(r.grid={xml:m,columnWidths:[...f]});continue}const c=t==="accept"?l.currentAttributes:l.priorAttributes,d=t==="accept"?l.priorAttributes:l.currentAttributes;let g;if(l.target==="table"?g=i:l.target==="row"||l.target==="row-exception"?g=i.children.find(f=>f.id===l.rowId):g=i.children.flatMap(f=>f.children).find(f=>f.id===l.cellId),g)for(const f of new Set([...Object.keys(d??{}),...Object.keys(c??{})]))c&&Object.prototype.hasOwnProperty.call(c,f)&&c[f]!==void 0?g[f]=this.cloneSuggestionSnapshot(c[f]):delete g[f];const u=t==="accept"?l.currentTableAttributes:l.priorTableAttributes,p=t==="accept"?l.priorTableAttributes:l.currentTableAttributes;for(const f of new Set([...Object.keys(p??{}),...Object.keys(u??{})]))u&&Object.prototype.hasOwnProperty.call(u,f)&&u[f]!==void 0?i[f]=this.cloneSuggestionSnapshot(u[f]):delete i[f];const h=t==="accept"?l.currentPropertiesXml:l.priorPropertiesXml;l.target==="table"?r.table=h:l.target==="row-exception"&&l.rowId?(r.rowExceptions=r.rowExceptions??{},r.rowExceptions[l.rowId]=h):l.target==="row"&&l.rowId?(r.rows=r.rows??{},r.rows[l.rowId]=h):l.target==="cell"&&l.cellId&&(r.cells=r.cells??{},r.cells[l.cellId]=h)}(r.table||r.grid||Object.keys(r.rows??{}).length>0||Object.keys(r.rowExceptions??{}).length>0||Object.keys(r.cells??{}).length>0)&&(i.docxTablePropertyOverrides=JSON.stringify(r)),this.clearSuggestionMarkerFromValue(i,e.id);const o=this.getSuggestionMutationSelection();if(n.children.length>0&&i.children.length===0){const l=this.runWithoutSuggesting(()=>this.host.deleteBlockById(e.tableId,o,o));return l&&this.deleteLiveSuggestion(e.id),l}const a=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(e.tableId,i,o,o));return a&&this.deleteLiveSuggestion(e.id),a}applySuggestionRecordAcceptance(e){const t=this.getSuggestionMutationSelection();switch(e.type){case"inline-text":return this.applyInlineSuggestionDecision(e.id,"accept");case"table-change":return this.applyTableRevisionDecision(e,"accept");case"block-change":{if(this.host.isListItemBlockChangeRecord(e)&&this.host.applyListItemBlockChangeDecision(e,"accept",t))return!0;if(e.acceptedBlock){if(!this.blockChangeTargetIsOwned(e))return!1;const i=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(e.blockId,e.acceptedBlock,t,t));return i&&(this.host.transact(()=>this.clearStructuralSuggestionById(this.host.getYNotesFragment(),e.id)),this.deleteLiveSuggestion(e.id)),i}const n=z(this.host.getDocument(),this.liveSuggestionRecordAnchorBlockId(e)??e.blockId);return n&&this.blockContainsSuggestionMarker(n,e.id)?(this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),e.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),e.id)}),this.host.setSelectionAfterOperation(t),this.host.afterOperationRelativeSelection=H(t,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(e.id),!0):!1}case"block-insert":{const n=this.collectNestedSuggestionIdsForBlock(e.blockId,e.id);for(const i of n)this.acceptLiveSuggestionWithoutPruning(i);return this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),e.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),e.id)}),this.host.setSelectionAfterOperation(t),this.host.afterOperationRelativeSelection=H(t,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(e.id),!0}case"block-delete":{const n=this.runWithoutSuggesting(()=>this.host.deleteBlockById(e.blockId,t,t));return n&&(e.cleanupTrailingParagraphId&&this.runWithoutSuggesting(()=>this.host.deleteBlockById(e.cleanupTrailingParagraphId,t,t)),this.deleteLiveSuggestion(e.id)),n}case"paragraph-split":return this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),e.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),e.id)}),this.host.setSelectionAfterOperation(t),this.host.afterOperationRelativeSelection=H(t,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(e.id),!0;case"paragraph-merge":{const n=this.host.getDocument(),i=z(n,e.secondBlockId);let r=z(n,e.firstBlockId),o=Je(n,e.firstBlockId);if(!r||r.type!=="paragraph"){const d=Je(n,e.secondBlockId),g=d?"children"in d?d.children:[]:n.children,u=g.findIndex(h=>h.id===e.secondBlockId),p=u>0?g[u-1]:null;p?.type==="paragraph"&&(r=p,o=d??n)}if(!r||!i||!o||r.type!=="paragraph"||i.type!=="paragraph")return!1;const a={block:r.id,offset:r.children.reduce((d,g)=>d+(g.type==="text"?g.text.length:0),0)},l={block:i.id,offset:0},c=this.runWithoutSuggesting(()=>this.host.mergeAdjacentParagraphs(r,i,a,l,o,t,t));return c&&this.deleteLiveSuggestion(e.id),c}case"inline-format":return this.host.transact(()=>{for(const n of e.spans){const i=this.getYTextForSuggestionSpan(n);i&&this.stripInlineSuggestionMarks(i,n.start,n.end-n.start)}}),this.host.setSelectionAfterOperation(t),this.host.afterOperationRelativeSelection=H(t,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(e.id),!0}}applySuggestionRecordRejection(e){const t=this.getSuggestionMutationSelection();switch(e.type){case"inline-text":return this.applyInlineSuggestionDecision(e.id,"reject");case"table-change":return this.applyTableRevisionDecision(e,"reject");case"block-change":{if(this.host.isListItemBlockChangeRecord(e)&&this.host.applyListItemBlockChangeDecision(e,"reject",t))return!0;if(!this.blockChangeTargetIsOwned(e))return!1;if(e.sequenceBlockIds){const i=this.getSequenceReplacementMembers(e),r=i[0];return!r||i.some(o=>o.yParent!==r.yParent)?!1:(this.host.transact(()=>{for(const o of[...i].sort((a,l)=>l.index-a.index))o.yParent.delete(o.index,1);r.yParent.insert(r.index,[this.host.blockToYjsElement(this.cloneSuggestionSnapshot(e.beforeBlock))]),this.deleteLiveSuggestion(e.id)}),this.host.setSelectionAfterOperation(t),this.host.afterOperationRelativeSelection=H(t,this.host.ydoc,this.host.getDocument()),!0)}const n=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(e.blockId,e.beforeBlock,t,t));return n&&(this.host.transact(()=>this.clearStructuralSuggestionById(this.host.getYNotesFragment(),e.id)),this.deleteLiveSuggestion(e.id)),n}case"block-insert":{const n=this.collectNestedSuggestionIdsForBlock(e.blockId,e.id),i=this.host.collectStructuralInsertBlockIds(this.host.getDocument(),e.id),r=i.length>0?Array.from(new Set(i)):[e.blockId];let o=!1;for(const a of[...r].reverse())o=this.runWithoutSuggesting(()=>this.host.deleteBlockById(a,t,t))||o;if(o){e.cleanupTrailingParagraphId&&this.runWithoutSuggesting(()=>this.host.deleteBlockById(e.cleanupTrailingParagraphId,t,t)),this.host.transact(()=>this.clearStructuralSuggestionById(this.host.getYContentFragment(),e.id));for(const a of n)this.deleteLiveSuggestion(a);this.deleteLiveSuggestion(e.id)}return o}case"block-delete":return this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),e.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),e.id)}),this.host.setSelectionAfterOperation(t),this.host.afterOperationRelativeSelection=H(t,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(e.id),!0;case"paragraph-split":{const n=this.host.getDocument();return!z(n,e.insertedBlockId)||!this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(e.blockId,e.beforeBlock,t,t))?!1:(this.runWithoutSuggesting(()=>this.host.deleteBlockById(e.insertedBlockId,t,t)),this.deleteLiveSuggestion(e.id),!0)}case"paragraph-merge":return this.host.transact(()=>{this.clearStructuralSuggestionById(this.host.getYContentFragment(),e.id),this.clearStructuralSuggestionById(this.host.getYNotesFragment(),e.id)}),this.host.setSelectionAfterOperation(t),this.host.afterOperationRelativeSelection=H(t,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(e.id),!0;case"inline-format":return this.host.transact(()=>{for(const n of e.spans){const i=this.getYTextForSuggestionSpan(n);i&&this.restoreInlineSuggestionFormatting(i,n.start,n.end-n.start,n.attributes)}}),this.host.setSelectionAfterOperation(t),this.host.afterOperationRelativeSelection=H(t,this.host.ydoc,this.host.getDocument()),this.deleteLiveSuggestion(e.id),!0}}applyInlineSuggestionDecision(e,t){return this.applyInlineSuggestionDecisions(new Set([e]),t).has(e)}applyInlineSuggestionDecisions(e,t){const n=new Set;if(e.size===0)return n;const i=new Set,r=(a,l)=>a instanceof S.XmlText?Z(a).some(c=>{if(c.attributes?.suggestionId!==l||!c.attributes.docxMove)return!1;try{return JSON.parse(c.attributes.docxMove).wholeBlocks===!0}catch{return!1}}):a.toArray().some(c=>(c instanceof S.XmlElement||c instanceof S.XmlText)&&r(c,l));for(const a of this.host.getYContentFragment().toArray()){if(!(a instanceof S.XmlElement))continue;const l=a.getAttribute("structuralSuggestionId")??a.getAttribute("suggestionId");l&&e.has(l)&&!i.has(l)&&r(a,l)&&i.add(l)}const o=(a,l,c)=>{if(a instanceof S.XmlText)return Z(a).every(g=>g.insert===""||g.attributes?.suggestionId===l&&(c==="delete"?g.attributes?.deletion:g.attributes?.insertion));const d=a.getAttribute("structuralSuggestionId")??a.getAttribute("suggestionId");return d&&d!==l?!1:a.toArray().every(g=>(g instanceof S.XmlElement||g instanceof S.XmlText)&&o(g,l,c))};if(this.host.transact(()=>{const a=l=>{for(const c of l.toArray()){if(c instanceof S.XmlElement){const p=c.getAttribute("structuralSuggestionId")??c.getAttribute("suggestionId"),h=c.getAttribute("structuralSuggestionKind")??c.getAttribute("diffState");if(l===this.host.getYContentFragment()&&typeof p=="string"&&typeof h=="string"&&i.has(p)&&o(c,p,h)&&(t==="accept"&&h==="delete"||t==="reject"&&h==="insert")){const y=l.toArray().indexOf(c);y>=0&&l.delete(y,1),n.add(p);continue}const f=c.getAttribute("structuralSuggestionId");typeof f=="string"&&e.has(f)&&(this.clearElementStructuralSuggestion(c),n.add(f));const m=c.getAttribute("suggestionId");typeof m=="string"&&e.has(m)&&(this.setDiffSuggestionAttributes(c,void 0,void 0),n.add(m)),a(c);continue}if(!(c instanceof S.XmlText))continue;const d=Z(c),g=[];let u=0;for(const p of d)typeof p.insert=="string"&&(g.push({start:u,length:p.insert.length,attributes:p.attributes||{}}),u+=p.insert.length);for(let p=g.length-1;p>=0;p--){const h=g[p],f=typeof h.attributes.suggestionId=="string"?h.attributes.suggestionId:null,m=fn(h.attributes.layeredInsertion);if(f&&e.has(f)){t==="accept"?h.attributes.deletion?c.delete(h.start,h.length):this.stripInlineSuggestionMarks(c,h.start,h.length):h.attributes.deletion&&m?ie(c,h.start,h.length,{deletion:null,layeredInsertion:null,insertion:!0,suggestionId:m.id,suggestionSource:m.source??null,suggestionAuthorType:m.authorType??null,suggestionCreatedAt:m.createdAt??null,suggestionLabel:m.label??"Insert",suggestionCommentThreadId:m.commentThreadId??null,suggestionAuthorName:m.authorName??null,suggestionAgentModel:m.agentModel??null,suggestionAgentConversationId:m.agentConversationId??null,suggestionAgentRequestId:m.agentRequestId??null,suggestionAgentTurn:m.agentTurn??null}):h.attributes.insertion?c.delete(h.start,h.length):h.attributes.formatChange&&yi(h.attributes.suggestionPriorAttributes)?this.restoreInlineSuggestionFormatting(c,h.start,h.length,yi(h.attributes.suggestionPriorAttributes)):this.stripInlineSuggestionMarks(c,h.start,h.length),n.add(f);continue}m&&e.has(m.id)&&(t==="accept"?ie(c,h.start,h.length,{insertion:null,layeredInsertion:null}):c.delete(h.start,h.length),n.add(m.id))}}};a(this.host.getYContentFragment()),i.size>0&&this.host.ensureTrailingParagraph(),a(this.host.getYNotesFragment()),a(this.host.ydoc.getXmlFragment("chrome"))}),n.size>0){const a=this.getSuggestionMutationSelection();this.host.setSelectionAfterOperation(a),this.host.afterOperationRelativeSelection=H(a,this.host.ydoc,this.host.getDocument());for(const l of n)this.deleteLiveSuggestion(l)}return n}acceptLiveSuggestionWithoutPruning(e){const t=this.getLiveSuggestion(e);return t?this.applySuggestionRecordAcceptance(t):this.applyInlineSuggestionDecision(e,"accept")}rejectLiveSuggestionWithoutPruning(e){const t=this.getLiveSuggestion(e);return t?this.applySuggestionRecordRejection(t):this.applyInlineSuggestionDecision(e,"reject")}acceptLiveSuggestion(e){this.host.lastPrunedUnresolvableLiveSuggestions=[];const t=this.acceptLiveSuggestionWithoutPruning(e);return this.host.lastPrunedUnresolvableLiveSuggestions=this.pruneUnresolvableLiveSuggestionsInternal(),t&&this.host.resolveCommentsForSettledSuggestions([e]),t}rejectLiveSuggestion(e){this.host.lastPrunedUnresolvableLiveSuggestions=[];const t=this.rejectLiveSuggestionWithoutPruning(e);return this.host.lastPrunedUnresolvableLiveSuggestions=this.pruneUnresolvableLiveSuggestionsInternal(),t&&this.host.resolveCommentsForSettledSuggestions([e]),t}deleteMultiParagraphSelectionAsSuggestion(e,t,n,i,r){const o=this.host.getDocument().children.slice(n,i+1);if(o.length<2||o.some(c=>c.type!=="paragraph"))return!1;const a=o.map((c,d)=>{const g=c,u=this.host.getParagraphTextLength(g),p=d===0?Math.min(e.offset,u):0,h=d===o.length-1?Math.min(t.offset,u):u;return{blockId:g.id,from:p,to:h}});if(!a.some(c=>c.to>c.from))return!1;const l=ce();return this.host.transact(()=>{for(const c of a){if(c.to<=c.from)continue;const d=K(this.host.ydoc,c.blockId);if(!(d instanceof S.XmlElement))continue;const g=ae(d);g&&(this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),c.blockId)?g.delete(c.from,c.to-c.from):this.applySuggestedDeletionToTextRange(g,c.from,c.to-c.from,l).retainedLength>0&&this.host.normalizeAdjacentManualReplacementOrder(g,c.from))}for(let c=0;c+1<o.length;c++){const d=o[c],g=o[c+1],u=K(this.host.ydoc,d.id),p=K(this.host.ydoc,g.id);if(!(u instanceof S.XmlElement)||!(p instanceof S.XmlElement)||this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),d.id)||this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),g.id))continue;const h=ce();this.setParagraphStructuralSuggestion(u,"merge","before",h),this.setParagraphStructuralSuggestion(p,"merge","after",h),this.saveLiveSuggestion({id:h,type:"paragraph-merge",firstBlockId:d.id,secondBlockId:g.id})}}),this.host.setSelectionAfterOperation(r),this.host.afterOperationRelativeSelection=H(r,this.host.ydoc,this.host.getDocument()),!0}sanitizePreviewMarks(e){let t=tl(e);for(const n of os)e?.[n]===!1&&(t??(t={}),t[n]=!1);return e?.footnoteRef?{...t,footnoteRef:e.footnoteRef,...e.superscript?{superscript:!0}:{}}:t}sanitizePreviewBlock(e){const t=i=>({...i,marks:this.sanitizePreviewMarks(i.marks)}),n=i=>{const r={...i};return delete r.diffState,delete r.suggestionId,delete r.proposalId,delete r.toolCallId,delete r.toolType,delete r.diffSegmentIndex,delete r.structuralSuggestionId,delete r.structuralSuggestionKind,delete r.structuralSuggestionRole,delete r.structuralSuggestionLabel,r};switch(e.type){case"paragraph":return n({...e,children:e.children.map(i=>t(i))});case"list":return n({...e,children:e.children.map(i=>n({...i,children:i.children.map(r=>t(r))}))});case"table":return n({...e,children:e.children.map(i=>n({...i,children:i.children.map(r=>n({...r,children:r.children.map(o=>this.sanitizePreviewBlock(o))}))}))});case"table-cell":return n({...e,children:e.children.map(i=>this.sanitizePreviewBlock(i))});case"container":case"footnote":return n({...e,children:e.children.map(i=>this.sanitizePreviewBlock(i))});default:return n({...e})}}markBlockForGenericSuggestionChange(e,t,n){const i=this.sanitizePreviewBlock(e);return i.type==="paragraph"||i.type==="list"?{...i,structuralSuggestionId:t,structuralSuggestionKind:"change",structuralSuggestionLabel:n}:{...i,diffState:"insert",suggestionId:t}}getListItemSignatureForSuggestionBridge(e){const t=n=>{const i=this.sanitizePreviewMarks(n);if(!i)return{};if(i.fontFamily===Fe||i.fontFamily==="Arial"){const r={...i};return delete r.fontFamily,r}return i};return JSON.stringify({...Object.fromEntries(xn.map(n=>[n,e[n]])),direction:e.direction,checked:e.checked??!1,indentLevel:e.indentLevel??0,children:e.children.map(n=>({text:n.text,marks:t(n.marks)}))})}computeListItemLcsForSuggestionBridge(e,t){const{beforeKeys:n,afterKeys:i}=this.getListItemAlignmentKeysForSuggestionBridge(e,t);return Ar(n,i)}getListItemAlignmentKeysForSuggestionBridge(e,t){return ma(e,t,n=>this.getListItemSignatureForSuggestionBridge(n))}computeListSuggestionBridgeOperations(e,t){const n=[],i=this.computeListItemLcsForSuggestionBridge(e.children,t.children),{beforeKeys:r,afterKeys:o}=this.getListItemAlignmentKeysForSuggestionBridge(e.children,t.children),a=e.children.map(u=>this.getListItemSignatureForSuggestionBridge(u)),l=t.children.map(u=>this.getListItemSignatureForSuggestionBridge(u)),c=(u,p,h,f)=>{const m=Math.min(u.length,p.length);for(let y=0;y<m;y++)n.push({kind:"change",index:h+y,beforeItem:u[y],afterItem:p[y]});for(let y=m;y<u.length;y++)n.push({kind:"delete",index:h+y,beforeItem:u[y]});for(let y=m;y<p.length;y++)n.push({kind:"insert",index:h+y,afterIndex:f+y,afterItem:p[y]})};let d=0,g=0;for(const u of i){let p=d;for(;p<r.length&&r[p]!==u;)p+=1;let h=g;for(;h<o.length&&o[h]!==u;)h+=1;c(e.children.slice(d,p),t.children.slice(g,h),d,g),a[p]!==l[h]&&n.push({kind:"change",index:p,beforeItem:e.children[p],afterItem:t.children[h]}),d=p+1,g=h+1}return c(e.children.slice(d),t.children.slice(g),d,g),n}findListItemIndexForSuggestionBridge(e,t){if(!t)return-1;if(t.id){const i=e.findIndex(r=>r.id===t.id);if(i!==-1)return i}const n=this.getListItemSignatureForSuggestionBridge(t);return e.findIndex(i=>this.getListItemSignatureForSuggestionBridge(i)===n)}buildListSuggestionChange(e,t,n,i,r){const o=this.sanitizePreviewBlock(e),a=this.sanitizePreviewBlock(t),l=r?this.cloneSuggestionSnapshot(r):null;if(i.kind==="insert"){const g=this.cloneSuggestionSnapshot(l??o),u=this.cloneSuggestionSnapshot(i.afterItem),p=this.findListItemIndexForSuggestionBridge(g.children,a.children[i.afterIndex-1]),h=this.findListItemIndexForSuggestionBridge(g.children,a.children[i.afterIndex+1]);let f=Math.min(i.afterIndex,g.children.length);return i.afterIndex===0?f=0:p!==-1?f=p+1:h!==-1&&(f=h),g.children.splice(f,0,{...u,structuralSuggestionId:n,structuralSuggestionKind:"insert",structuralSuggestionLabel:"Insert"}),{liveBlock:g,label:"Insert",listItemSuggestion:{kind:"insert",afterItem:this.cloneSuggestionSnapshot(u)}}}if(i.kind==="delete"){const g=this.cloneSuggestionSnapshot(l??o),u=this.findListItemIndexForSuggestionBridge(g.children,i.beforeItem);if(u!==-1){const p=g.children[u];return g.children[u]={...p,structuralSuggestionId:n,structuralSuggestionKind:"delete",structuralSuggestionLabel:"Delete"},{liveBlock:g,acceptedBlock:this.cloneSuggestionSnapshot(a),label:"Delete",listItemSuggestion:{kind:"delete",beforeItem:this.cloneSuggestionSnapshot(i.beforeItem)}}}}if(i.kind!=="change")return null;const c=this.cloneSuggestionSnapshot(l??o),d=this.findListItemIndexForSuggestionBridge(c.children,i.beforeItem);return d!==-1?(c.children[d]={...this.cloneSuggestionSnapshot(i.afterItem),structuralSuggestionId:n,structuralSuggestionKind:"change",structuralSuggestionLabel:"Change"},{liveBlock:c,label:"Change",listItemSuggestion:{kind:"change",beforeItem:this.cloneSuggestionSnapshot(i.beforeItem),afterItem:this.cloneSuggestionSnapshot(i.afterItem)}}):null}applyGranularListSuggestionChanges(e){const t=this.sanitizePreviewBlock(e.before),n=this.sanitizePreviewBlock(e.after);if(!us(t,n))return!1;const i=this.computeListSuggestionBridgeOperations(t,n);if(i.length===0)return!1;let r=this.cloneSuggestionSnapshot(e.currentLiveBlock??t),o=!1;const a=[],l=[];for(let c=0;c<i.length;c++){const d=c===0?e.suggestionId:ce(),g=i[c];if(g.kind==="change"&&this.host.canBridgeListItemChangeAsInline(g.beforeItem,g.afterItem)){const p=this.findListItemIndexForSuggestionBridge(r.children,g.beforeItem);if(p===-1)return!1;l.push({suggestionId:d,itemIndex:p,beforeItem:this.cloneSuggestionSnapshot(g.beforeItem),afterItem:this.cloneSuggestionSnapshot(g.afterItem),formatOnly:this.host.getListItemPlainText(g.beforeItem)===this.host.getListItemPlainText(g.afterItem)});continue}const u=this.buildListSuggestionChange(t,n,d,g,r);if(!u?.listItemSuggestion)return!1;r=u.liveBlock,o=!0,a.push({id:d,type:"block-change",blockId:e.blockId,beforeBlock:this.cloneSuggestionSnapshot(t),acceptedBlock:u.acceptedBlock?this.cloneSuggestionSnapshot(u.acceptedBlock):void 0,listItemSuggestion:{kind:u.listItemSuggestion.kind,beforeItem:u.listItemSuggestion.beforeItem?this.cloneSuggestionSnapshot(u.listItemSuggestion.beforeItem):void 0,afterItem:u.listItemSuggestion.afterItem?this.cloneSuggestionSnapshot(u.listItemSuggestion.afterItem):void 0},label:u.label,createdAt:e.createdAt})}if(o&&!this.host.replaceBlockByIdWithoutSelection(e.blockId,r))return!1;this.host.transact(()=>{for(const c of a)this.saveLiveSuggestion(c)});for(const c of l){const d=this.host.getListItemPlainText(c.afterItem);let g;if(c.formatOnly){const u=this.host.extractTextNodesForRange(c.afterItem,0,d.length);g=this.applyBridgeInlineFormatSuggestion({suggestionId:c.suggestionId,blockId:e.blockId,itemIndex:c.itemIndex,start:0,end:d.length,targetAttributes:{},targetTextNodes:u,createdAt:e.createdAt})}else{const u=this.host.getListItemPlainText(c.beforeItem),p=Ri(u,d).diffs;let h=0,f=0;g=!0;for(let m=0;m<p.length&&g;m++){const[y,b]=p[m];if(y===0){g=this.applyBridgeInlineFormatSuggestion({suggestionId:ce(),blockId:e.blockId,itemIndex:c.itemIndex,start:f,end:f+b.length,targetAttributes:{},targetTextNodes:this.host.extractTextNodesForRange(c.afterItem,h,h+b.length),createdAt:e.createdAt}),h+=b.length,f+=b.length;continue}if(y===-1){const k=p[m+1];if(k&&k[0]===1){const I=this.host.extractTextNodesForRange(c.afterItem,h,h+k[1].length);g=this.applyBridgeInlineTextSuggestion({suggestionId:c.suggestionId,blockId:e.blockId,itemIndex:c.itemIndex,start:f,deleteLength:b.length,insertNodes:I,label:"Replace",createdAt:e.createdAt}),f+=b.length+k[1].length,h+=k[1].length,m++}else g=this.applyBridgeInlineTextSuggestion({suggestionId:c.suggestionId,blockId:e.blockId,itemIndex:c.itemIndex,start:f,deleteLength:b.length,insertNodes:[],label:"Replace",createdAt:e.createdAt}),f+=b.length}else{const k=this.host.extractTextNodesForRange(c.afterItem,h,h+b.length);g=this.applyBridgeInlineTextSuggestion({suggestionId:c.suggestionId,blockId:e.blockId,itemIndex:c.itemIndex,start:f,deleteLength:0,insertNodes:k,label:"Replace",createdAt:e.createdAt}),f+=b.length,h+=b.length}}}if(!g)return!1}return a.length>0||l.length>0}applyBridgeInlineTextSuggestion(e){const t=this.getYTextForSuggestionSpan({blockId:e.blockId,itemIndex:e.itemIndex});if(!t)return!1;let n=!1;return this.host.transact(()=>{let i=e.start;if(e.deleteLength>0){const o=this.applySuggestedDeletionToTextRange(t,e.start,e.deleteLength,e.suggestionId);i=e.start+o.retainedLength,n=n||o.changed}let r=i;for(const o of e.insertNodes){if(!o.text)continue;const a=this.buildSuggestionInsertionMarks(this.sanitizePreviewMarks(o.marks),e.suggestionId,e.label,e.createdAt);ne(t,r,o.text,a),r+=o.text.length,n=!0}}),n}applyBridgeInlineFormatSuggestion(e){const t=this.getYTextForSuggestionSpan({blockId:e.blockId,itemIndex:e.itemIndex});if(!t||e.end<=e.start)return!1;const n=e.end-e.start,i=this.host.collectOverlappingTextSpans(t,e.start,n);if(i.length===0||e.targetTextNodes&&e.targetTextNodes.reduce((d,g)=>d+g.text.length,0)!==n)return!1;const r=[];let o=e.start;const a=e.targetTextNodes?e.targetTextNodes.map(d=>({length:d.text.length,marks:d.marks})):[{length:n,marks:e.targetAttributes}];let l=0;for(const d of a){const g=o+d.length;for(;l<i.length&&i[l].start+i[l].length<=o;)l++;for(let u=l;u<i.length&&i[u].start<g;u++){const p=i[u],h=Math.max(p.start,o),f=Math.min(p.start+p.length,g);if(f<=h)continue;const m=e.targetTextNodes?uo(p.attributes,d.marks):{...d.marks??{}};r.push({...p,start:h,length:f-h,targetAttributes:m})}o=g}const c=[];return this.host.transact(()=>{for(const d of r){const g={formatChange:!0,...this.buildInlineSuggestionMetadataMarks(e.suggestionId,"Format",e.createdAt)},u=new Set([...Object.keys(d.attributes||{}),...Object.keys(d.targetAttributes)]);if(u.delete("insertion"),u.delete("deletion"),u.delete("suggestionId"),u.delete("formatChange"),u.delete("suggestionSource"),u.delete("suggestionAuthorType"),u.delete("suggestionCreatedAt"),u.delete("suggestionLabel"),u.delete("suggestionCommentThreadId"),u.delete("suggestionAuthorName"),u.delete("suggestionAgentModel"),u.delete("suggestionAgentConversationId"),u.delete("suggestionAgentRequestId"),u.delete("suggestionAgentTurn"),u.delete("suggestionPriorAttributes"),u.delete("layeredInsertion"),u.delete("proposalId"),u.delete("toolCallId"),u.delete("toolType"),![...u].every(p=>(d.attributes?.[p]??null)===(d.targetAttributes[p]??null))){c.push(d);for(const p of u)Object.prototype.hasOwnProperty.call(d.targetAttributes,p)?g[p]=d.targetAttributes[p]:g[p]=null;ie(t,d.start,d.length,{...g,suggestionPriorAttributes:hn(d.attributes)})}}c.length!==0&&this.saveLiveSuggestion({id:e.suggestionId,type:"inline-format",spans:c.map(d=>({blockId:e.blockId,itemIndex:e.itemIndex,start:d.start,end:d.start+d.length,attributes:d.attributes})),label:"Format",createdAt:e.createdAt})}),!0}insertBlockRelativeWithSuggestion(e){const t=e.batchInsertedBlocks?.get(e.referenceId),n=t||G(this.host.ydoc,e.referenceId),i=e.referenceId===Gt;if(!n&&!i)return!1;const r=n?.yParent??this.host.getYContentFragment(),o=n?.index??0,a=this.sanitizePreviewBlock(e.block),l=a.id||Y();let c=null;this.host.transact(()=>{const g=this.host.blockToYjsElement({...a,id:l});c=g,g.setAttribute("id",l),this.markInsertedBlockElement(g,e.suggestionId,e.label);const u=i?r.length:e.position==="before"?o:o+1;r.insert(u,[g]),e.batchInsertedBlocks?.set(l,{yBlock:g,yParent:r,index:u})});const d=this.host.ensureTrailingParagraph();return this.host.transact(()=>{this.saveLiveSuggestion({id:e.suggestionId,type:"block-insert",blockId:l,label:e.label,createdAt:e.createdAt,cleanupTrailingParagraphId:d??void 0},c??void 0)}),!0}applyBridgeBlockDeleteSuggestion(e){const t=K(this.host.ydoc,e.blockId);if(!(t instanceof S.XmlElement))return!1;const n=this.host.getTrailingCleanupParagraphIdForTopLevelBlock(this.host.getDocument(),e.blockId);return this.host.transact(()=>{this.markDeletedBlockElement(t,e.suggestionId,e.label),this.saveLiveSuggestion({id:e.suggestionId,type:"block-delete",blockId:e.blockId,beforeBlock:this.cloneSuggestionSnapshot(e.beforeBlock),label:e.label,createdAt:e.createdAt,cleanupTrailingParagraphId:n??void 0})}),!0}applyBridgeBlockChangeSuggestion(e){const t=this.sanitizePreviewBlock(e.beforeBlock),n=this.sanitizePreviewBlock(e.afterBlock),i=t.type==="list"||t.type==="table"?z(this.host.getDocument(),e.blockId):null;let r=this.markBlockForGenericSuggestionChange(n,e.suggestionId,e.label),o,a,l=e.label;if(t.type==="paragraph"&&n.type==="paragraph"&&Ne(t)!==Ne(n))r=this.host.buildParagraphReplacementLiveBlock(t,n,e.suggestionId,e.label),o=n;else if(t.type==="paragraph"&&n.type==="paragraph")o=n;else if(t.type==="list"&&n.type==="list"){if(!e.optimizeFormatting&&this.applyGranularListSuggestionChanges({blockId:e.blockId,before:t,after:n,suggestionId:e.suggestionId,currentLiveBlock:i?.type==="list"?i:void 0,createdAt:e.createdAt}))return!0;r={...n,structuralSuggestionId:e.suggestionId,structuralSuggestionKind:"change",structuralSuggestionLabel:"List"},o=n,l="List"}else if(t.type==="table"&&n.type==="table"){const c=z(this.createLiveSuggestionProjection("accept").doc,e.blockId),d=c?.type==="table"?c:t,g=this.reconcileTableDescendantIds(d,n),u=Tn(t,g),p=u?null:this.buildSuggestedTableChange(d,g,e.suggestionId);if(p)r=i?.type==="table"?this.mergePendingTableRevisionState(i,p.liveBlock):p.liveBlock,a=p.record,l=p.label;else if(!this.hasSameTableGeometry(d,g)||u||Tn(d,g))r=this.markBlockForGenericSuggestionChange(g,e.suggestionId,"Table"),o=g,l="Change";else{if(i?.type==="table"&&this.collectNestedSuggestionIdsForBlock(e.blockId,e.suggestionId).length>0)return!0;r={...this.cloneSuggestionSnapshot(g),diffState:"insert",suggestionId:e.suggestionId}}}if(e.optimizeFormatting&&t.type==="paragraph"&&n.type==="paragraph"&&Ne(t)===Ne(n)){const c=this.batchYBlockLocationsById?.get(e.blockId)?.yBlock??K(this.host.ydoc,e.blockId),d=c?c._item:null,g=c?ae(c):null;if(c&&g&&!d?.deleted){const u=new Set(["insertion","deletion","suggestionId","formatChange","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","proposalId","toolCallId","toolType"]),p=[];let h=0,f=!1;for(const m of n.children){if(m.type!=="text"||m.text.length===0)continue;const y=this.sanitizePreviewMarks(m.marks)??{},b=this.host.collectOverlappingTextSpans(g,h,m.text.length);f||(f=b.some(k=>["insertion","deletion","suggestionId","formatChange"].some(I=>Object.prototype.hasOwnProperty.call(k.attributes,I)))),p.push({targetAttributes:y,spans:b}),h+=m.text.length}if(!f)return this.host.transact(()=>{wn(c,r);for(const{targetAttributes:m,spans:y}of p)for(const b of y){const k=new Set([...Object.keys(b.attributes??{}),...Object.keys(m)]),I={formatChange:!0,...this.buildInlineSuggestionMetadataMarks(e.suggestionId,"Format",e.createdAt)};for(const v of k)u.has(v)||(I[v]=Object.prototype.hasOwnProperty.call(m,v)?m[v]:null);I.suggestionPriorAttributes=hn(b.attributes),ie(g,b.start,b.length,I)}this.saveLiveSuggestion({id:e.suggestionId,type:"block-change",blockId:e.blockId,beforeBlock:this.cloneSuggestionSnapshot(t),acceptedBlock:this.cloneSuggestionSnapshot(n),label:l,createdAt:e.createdAt},c)}),!0}}if(t.type==="paragraph"&&n.type==="paragraph"&&JSON.stringify(t.children)===JSON.stringify(n.children)){const c=this.batchYBlockLocationsById?.get(e.blockId),d=c?c.yBlock._item:null;if(c&&!d?.deleted)return wn(c.yBlock,r),this.saveLiveSuggestion({id:e.suggestionId,type:"block-change",blockId:e.blockId,beforeBlock:this.cloneSuggestionSnapshot(t),acceptedBlock:this.cloneSuggestionSnapshot(n),label:l,createdAt:e.createdAt},c.yBlock),!0}return this.host.replaceBlockByIdWithoutSelection(e.blockId,r,t.type==="paragraph"?this.batchYBlockLocationsById?.get(e.blockId):void 0)?(this.host.transact(()=>{a?this.saveLiveSuggestion({...a,label:l,createdAt:e.createdAt}):this.saveLiveSuggestion({id:e.suggestionId,type:"block-change",blockId:e.blockId,beforeBlock:this.cloneSuggestionSnapshot(t),acceptedBlock:o?this.cloneSuggestionSnapshot(o):void 0,label:l,createdAt:e.createdAt})}),!0):!1}sortBlockSuggestionPlansByDependency(e){if(e.length<=1)return e;const t=[],n=new Set,i=[...e],r=new Set(i.flatMap(o=>[o.blockId,...o.producedBlockIds??[]]).filter(o=>!!o));for(;i.length>0;){let o=!1;for(let a=0;a<i.length;a++){const l=i[a],c=l.insertReferenceId;if(!(c&&r.has(c)&&!n.has(c))){t.push(l),l.blockId&&n.add(l.blockId),l.producedBlockIds?.forEach(d=>n.add(d)),i.splice(a,1),o=!0;break}}if(!o){t.push(...i);break}}return t}buildAgentSuggestionPlanFromProposal(e,t,n,i,r,o,a,l=!1,c=!1){const d=t.getSuggestion(e);if(!d)return null;const g=r??d.createdAt;if(d.blockSequencePreview){const{blockId:v,blocks:x}=d.blockSequencePreview,A=z(n,v);return!A||x.length===0?null:{proposalId:e,category:"block",blockId:v,producedBlockIds:x.map(C=>C.id),apply:()=>{const C=G(this.host.ydoc,v);if(!C)return!1;const F=x.map(E=>this.sanitizePreviewBlock(E));return this.host.transact(()=>{C.yParent.delete(C.index,1);const E=F.map(B=>this.host.blockToYjsElement(B));C.yParent.insert(C.index,E);for(const B of E)this.setElementStructuralSuggestion(B,"change",void 0,e,"Paragraph");const P=this.normalizeLiveSuggestionRecord({id:e,type:"block-change",blockId:F[0].id,beforeBlock:this.cloneSuggestionSnapshot(A),sequenceBlockIds:F.map(B=>B.id),label:"Paragraph",createdAt:g});this.saveLiveSuggestion(P,E[0]);for(const B of E.slice(1))this.embedLiveSuggestionRecordInTree(P,B)}),!0}}}if(d.blockPreview?.id){const v=z(n,d.blockPreview.id);if(!v)return null;const x=d.blockPreview;return{proposalId:e,category:"block",blockId:v.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:e,blockId:v.id,beforeBlock:v,afterBlock:x,optimizeFormatting:l,label:v.type==="paragraph"&&x.type==="paragraph"?Ne(v)===Ne(x)?"Format":"Replace":v.type==="table"?"Table":v.type==="list"?"List":"Change",createdAt:g})}}if(d.toolCallAction?.name==="insert_block"){const v=d.toolCallAction.arguments&&typeof d.toolCallAction.arguments=="object"?d.toolCallAction.arguments:null,x=typeof v?.referenceId=="string"?v.referenceId:null,A=v?.position==="before"||v?.position==="after"?v.position:null,C=typeof v?.content=="string"?v.content:Array.isArray(v?.content)&&typeof v?.content[0]=="string"?v?.content[0]:null;if(!x||!A||!C)return null;const F=Hn(d.toolCallAction),E=(F&&o?z(o,F):null)??te.fromAgentHtml(C,{existingDocument:n}).children[0];if(!E)return null;const P={...E,id:F||E.id||Y()};return{proposalId:e,category:"block",blockId:P.id,insertReferenceId:x,apply:()=>this.insertBlockRelativeWithSuggestion({block:P,referenceId:x,position:A,suggestionId:e,label:"Insert",createdAt:g,batchInsertedBlocks:a})}}if(d.insertionContext){const v=this.host.resolvePositionAwareInsertionReference({baseDoc:n,mustBeAfter:d.insertionContext.mustBeAfter,mustBeBefore:d.insertionContext.mustBeBefore});return v?{proposalId:e,category:"block",blockId:d.insertionContext.paragraphId,insertReferenceId:v.referenceId,apply:()=>this.insertBlockRelativeWithSuggestion({block:{...this.cloneSuggestionSnapshot(d.insertionContext.content),id:d.insertionContext.content.id||d.insertionContext.paragraphId||Y()},referenceId:v.referenceId,position:v.position,suggestionId:e,label:"Insert",createdAt:g,batchInsertedBlocks:a})}:null}const u=t.resolveAnchorsAgainstDoc(e,i),p=d.anchors?.[0]?.paragraphId??null,h=d.inlinePreview&&!d.toolCallAction?d.inlinePreview:null,f=h?{resolvedPreview:(d.anchors??[]).map(v=>({kind:v.kind,paragraphId:v.paragraphId,fromIndex:h.startOffset,toIndex:h.startOffset+h.newText.length,text:v.text})),previewAnchorBlock:null}:t.withMaterializedSuggestion(e,v=>({resolvedPreview:t.resolveAnchorsAgainstDoc(e,v),previewAnchorBlock:p?Ol(v,p):null}));if(!f)return null;const{resolvedPreview:m,previewAnchorBlock:y}=f;if(d.toolCallAction?.name==="remove_block"){const v=d.toolCallAction.arguments&&typeof d.toolCallAction.arguments=="object"?d.toolCallAction.arguments:null,x=typeof v?.id=="string"?v.id:null,A=x?z(n,x):null;return!x||!A?null:{proposalId:e,category:"block",blockId:x,apply:()=>this.applyBridgeBlockDeleteSuggestion({suggestionId:e,blockId:x,beforeBlock:A,label:"Delete",createdAt:g})}}const b=d.anchors?.[0],k=u[0],I=m[0];if(b?.paragraphId){const v=z(n,b.paragraphId);let x=v?.type==="table"&&o?z(o,v.id):null;v?.type==="table"&&x?.type==="table"&&this.hasSameTableGeometry(v,x)&&!Tn(v,x)&&(x={...x,children:x.children.map((E,P)=>({...E,children:E.children.map((B,w)=>({...B,children:v.children[P].children[w].children}))}))});const A=x??y;if(d.toolCallAction?.name==="replace_block"&&v&&A&&(v.type!=="paragraph"||A.type!=="paragraph"||this.host.paragraphReplaceShouldStayAtomic(v,A)))return{proposalId:e,category:"block",blockId:v.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:e,blockId:v.id,beforeBlock:v,afterBlock:A,optimizeFormatting:l,label:v.type==="paragraph"&&A.type==="paragraph"?Ne(v)===Ne(A)?"Format":"Replace":v.type==="table"?"Table":v.type==="list"?"List":"Change",createdAt:g})};if(v?.type==="paragraph"){const E=k?.fromIndex??k?.toIndex,P=b.previewStartOffset??I?.fromIndex??I?.toIndex;if(b.kind==="delete"){const B=E??P??0,w=b.text?.length??Math.max(0,(k?.toIndex??B)-B),T=Math.max(0,B-w);return{proposalId:e,category:"inline",blockId:v.id,start:T,inlinePriority:2,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:e,blockId:v.id,start:T,deleteLength:w,insertNodes:[],label:"Delete",createdAt:g})}}if(b.kind==="insert"&&(h||A?.type==="paragraph")){const B=P??E??0,w=P??B,T=b.previewStartOffset!==void 0?w+(b.text?.length??0):I?.toIndex??w+(b.text?.length??0),N=b.previewTextNodes?b.previewTextNodes.map(L=>({...L,marks:L.marks?{...L.marks}:void 0})):h?this.buildInlinePreviewTextNodes(h):this.host.extractTextNodesForRange(A,w,T);return{proposalId:e,category:"inline",blockId:v.id,start:B,inlinePriority:0,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:e,blockId:v.id,start:B,deleteLength:0,insertNodes:N,label:"Insert",createdAt:g})}}if(b.kind==="replace"&&(h||A?.type==="paragraph")){const B=P??E??0,w=P??B,T=b.previewStartOffset!==void 0?w+(b.text?.length??0):I?.toIndex??w+(b.text?.length??0),N=b.previewTextNodes?b.previewTextNodes.map(L=>({...L,marks:L.marks?{...L.marks}:void 0})):h?this.buildInlinePreviewTextNodes(h):this.host.extractTextNodesForRange(A,w,T);return b.oldText===b.text?{proposalId:e,category:"inline",blockId:v.id,start:B,inlinePriority:1,apply:()=>this.applyBridgeInlineFormatSuggestion({suggestionId:e,blockId:v.id,start:B,end:B+(b.text?.length??0),targetAttributes:{},targetTextNodes:N,createdAt:g})}:{proposalId:e,category:"inline",blockId:v.id,start:B,inlinePriority:2,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:e,blockId:v.id,start:B,deleteLength:b.oldText?.length??0,insertNodes:N,label:"Replace",createdAt:g})}}}if(v?.type==="list"&&A?.type==="list")return{proposalId:e,category:"block",blockId:v.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:e,blockId:v.id,beforeBlock:v,afterBlock:A,optimizeFormatting:!c&&(l||b.oldText===b.text),label:"List",createdAt:g})};const C=v?.type,F=A?.type;if(C==="list-item"&&F==="list-item"){const E=v,P=A,B=Je(n,E.id)?.children.find(w=>w?.type!=="list"?!1:w.children.some(T=>T.id===E.id));if(B?.id){const w=B.children.findIndex(T=>T.id===E.id);if(w!==-1){const T=this.cloneSuggestionSnapshot(B),N=this.cloneSuggestionSnapshot(B);return N.children[w]=this.cloneSuggestionSnapshot(P),{proposalId:e,category:"block",blockId:B.id,apply:()=>{const L=z(this.host.getDocument(),B.id);return this.applyGranularListSuggestionChanges({blockId:B.id,before:T,after:N,suggestionId:e,currentLiveBlock:L?.type==="list"?L:void 0,createdAt:g})}}}}}if(v&&A)return{proposalId:e,category:"block",blockId:v.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:e,blockId:v.id,beforeBlock:v,afterBlock:A,optimizeFormatting:l,label:v.type==="table"?"Table":v.type==="paragraph"?"Format":"Change",createdAt:g})}}return null}describeAgentSuggestionApplyFailure(e,t,n,i){const r=t.getSuggestion(e.proposalId),o=(I,v)=>{const x=z(I,v);if(!x||x.id===v)return x;if(x.type==="list"){const A=x.children.find(C=>C.id===v);if(A)return A}return x},a=r?.toolCallAction,l=a?.arguments&&typeof a.arguments=="object"?a.arguments:null,c=typeof l?.id=="string"&&l.id.length>0?l.id:e.blockId,d=i?.find(I=>{const v=I.arguments&&typeof I.arguments=="object"?I.arguments:null,x=typeof v?.id=="string"&&v.id.length>0?v.id:null,A=x?o(n,x):null;if(!A)return!1;if(x===c)return!0;const C=typeof v?.find=="string"?v.find:"";return C.length>0&&Ne(A).includes(C)})??a,g=d?.name??"agent change",u=d?.arguments&&typeof d.arguments=="object"?d.arguments:null,p=typeof u?.id=="string"&&u.id.length>0?u.id:e.blockId,h=this.host.getDocument(),f=p?o(h,p):null,m=p?o(n,p):null,y=f??m,b=y?y.type:null,k=p?`'${p}'${typeof b=="string"?` (${b})`:""}`:"the requested target";return!f&&m?`Could not apply ${e.category} suggestion for ${g} to block ${k}: the target was present when the action was planned but is no longer available at replay time. The attempted change was rolled back; re-read that block and retry.`:y?`Could not apply ${e.category} suggestion for ${g} to block ${k}: the requested edit is not compatible with the target's current structure. The attempted change was rolled back; re-read the target and retry with a narrower edit or the containing block.`:`Could not apply ${e.category} suggestion for ${g}: the target block is unavailable at replay time. The attempted change was rolled back; re-read the document and retry.`}applyValidatedAgentActionsAsSuggestions(e){const t=this.host.tryCancelInsertedBlockForRemoveAction(e.processedActions,e.docBeforeToolCall);if(t)return t;const n=!!e.processedActions?.length&&e.processedActions.every(P=>P.name==="style_blocks"),i=new Rr(e.baseFork,n),r=new Map;for(const{block:P}of qe(e.docBeforeToolCall).values())P.type==="list"&&P.id&&r.set(P.id,P.children.map(B=>B.id));for(const P of this.getLiveSuggestionIds()){const B=this.getLiveSuggestion(P);B?.type==="block-change"&&B.sequenceBlockIds&&B.beforeBlock.id&&r.set(B.beforeBlock.id,this.getSequenceReplacementMembers(B).map(({yBlock:w})=>w.getAttribute("id")))}const o=$r(e.validationFork,i,{...e.flattenOptions,precomputedLiveDocSchema:e.baseDocForSuggestions,precomputedCurrentDocSchema:e.baseDocForSuggestions,listUnwrapMemberIds:r,precomputedFinalDocSchema:e.docAfterToolCall}),a=e.validationAnchorsByAction.flat().filter(P=>P.kind==="replace"&&P.previewStartOffset!==void 0&&!!P.paragraphId);for(const P of a){const B=o.filter(w=>(i.getSuggestion(w)?.anchors??[]).some(T=>T.kind==="replace"&&T.paragraphId===P.paragraphId&&(T.oldText??"").includes(P.oldText??"")&&(T.text??"").includes(P.text??"")));if(B.length===1){const w=i.getSuggestion(B[0]),T=P.sourceFrom?S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(P.sourceFrom),e.baseFork):null,N=P.paragraphId?K(e.baseFork,P.paragraphId):null,L=N?ae(N):null,_=L?Z(L).map($=>typeof $.insert=="string"?$.insert:"").join(""):"";w&&T&&T.type===L&&_.slice(T.index,T.index+(P.oldText?.length??0))===(P.oldText??"")&&(w.anchors=[{...P,previewStartOffset:T.index}])}}const l=o.length>=100,c=Date.now(),d=P=>{l&&(`${o.length}${P}`,Date.now()-c)};if(d("flattened"),o.length===0)return this.tryRejectRevertedPendingSuggestions({actions:e.processedActions,baseDoc:e.baseDocForSuggestions,docAfterToolCall:e.docAfterToolCall})||{success:!1,error:"No changes detected - the document already has the content you specified. Make sure you are modifying the correct block and providing different content."};const g=e.baseDocForSuggestions,u=(e.processedActions??[]).map((P,B)=>{const w=P.arguments&&typeof P.arguments=="object"?P.arguments:null,T=typeof w?.comment=="string"?w.comment.trim():"";return{action:P,comment:T,anchors:e.validationAnchorsByAction[B]??[]}}).filter(({action:P,comment:B})=>(P.name==="replace"||P.name==="replace_all")&&B.length>0),p=new Map;for(const P of u){const B=P.anchors.flatMap(w=>{if(!w.from||!w.to||!w.paragraphId)return[];const T=S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(w.from),e.validationFork),N=S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(w.to),e.validationFork);if(!T||!N||T.type!==N.type)return[];const L=w.oldText??"",_=w.text??"";let $=0;for(;$<L.length&&$<_.length&&L[$]===_[$];)$++;let R=0;for(;R<L.length-$&&R<_.length-$&&L[L.length-1-R]===_[_.length-1-R];)R++;const M=L.length>_.length&&$+R===_.length?T.index+$:null;return[{paragraphId:w.paragraphId,start:T.index,end:N.index,deletionPoint:M}]});p.set(P,B)}const h=new Map,f=o.map(P=>this.buildAgentSuggestionPlanFromProposal(P,i,g,e.baseFork,void 0,e.docAfterToolCall,h,e.optimizeStyleFormatting===!0,u.length>0)).filter(P=>!!P);if(d("built plans"),f.length!==o.length)return{success:!1,error:"Could not translate one or more agent changes into live suggestions."};const m=this.sortBlockSuggestionPlansByDependency(f.filter(P=>P.category==="block")),y=new Map(o.map((P,B)=>[P,B])),b=f.filter(P=>P.category==="inline").sort((P,B)=>{if(P.blockId&&B.blockId&&P.blockId===B.blockId){const w=(B.start??0)-(P.start??0);if(w!==0)return w;const T=(B.inlinePriority??0)-(P.inlinePriority??0);if(T!==0)return T}return(y.get(P.proposalId)??0)-(y.get(B.proposalId)??0)});let k=[];const I=this.host.beginRollbackScope();let v=null;try{d("applying plans"),k=this.withSuggestionMetadata({source:"agent",authorType:"ai",label:`${e.agentName??ze} revision`,agentName:e.agentName??ze,agentModel:e.agentModel,commentThreadId:e.commentThreadId,agentConversationId:e.agentConversationId,agentRequestId:e.agentRequestId,agentTurn:e.agentTurn,historyOrigin:`live-suggestions:${e.toolCallId}`},()=>this.host.transact(()=>{const P=new Set(Array.from(e.flattenOptions?.affectedBlockIds??[]));for(const T of f)T.blockId&&P.add(T.blockId);v=m[0]??b[0]??null,this.resetLiveSuggestionsForBlocks(P,g),this.batchYBlockLocationsById=new Map;const B=new Map;for(const T of m){if(!T.blockId)continue;const N=K(this.host.ydoc,T.blockId);N&&B.set(N,T.blockId)}const w=new Map;for(const[T,N]of B){const L=T.parent;if(!(L instanceof S.XmlElement||L instanceof S.XmlFragment))continue;const _=w.get(L)??new Map;_.set(T,N),w.set(L,_)}for(const[T,N]of w)T.toArray().forEach((L,_)=>{if(!(L instanceof S.XmlElement))return;const $=N.get(L);$&&this.batchYBlockLocationsById.set($,{yBlock:L,yParent:T,index:_})});try{for(const T of m)if(v=T,!T.apply())throw new Error("suggestion application returned false");for(const T of b)if(v=T,!T.apply())throw new Error("suggestion application returned false")}finally{this.batchYBlockLocationsById=null}d("finished plan loop"),v=null})).suggestionIds,d("applied plans"),I.dispose()}catch(P){I.revert();const B=P instanceof Error?P.message:"suggestion application failed",w=B==="suggestion application returned false"?null:B,T=v?this.describeAgentSuggestionApplyFailure(v,i,g,e.originalActions):null;return{success:!1,error:T?`${T}${w?` Detail: ${w}`:""}`:w??"Could not apply the requested edit."}}this.host.relinkCommentSuggestionIds();const x=u.length?this.host.getSuggestionCommentRanges(k):[],A=[],C=[];let F=0;for(const[P,B]of p){const w=x.flatMap(_=>B.flatMap($=>{if(_.structural){if($.paragraphId!==_.blockId)return[];const R=Math.max(_.projectedStart,$.start),M=Math.min(_.projectedEnd,$.end);return M<R||M===R&&$.start!==$.end?[]:[{..._,start:_.start+R-_.projectedStart,end:_.start+M-_.projectedStart}]}return(()=>{if($.paragraphId!==_.blockId)return!1;const R=_.projectedStart,M=_.projectedEnd;return R===M&&$.start===$.end?R===$.start:R===M?$.deletionPoint===R||$.start<R&&R<$.end:$.start===$.end?R<$.start&&$.start<M:R<$.end&&$.start<M})()?[_]:[]})),T=Array.from(new Set(w.map(_=>_.suggestionId)));if(T.length===0){F++;for(const _ of k)A.includes(_)||A.push(_);continue}for(const _ of T)A.includes(_)||A.push(_);const N={author:e.agentName??ze,authorType:"ai",agentName:e.agentName??ze,agentModel:e.agentModel,suggestionId:T[0],...T.length>1?{relatedSuggestionIds:T}:{}},L=w.every(_=>_.structural&&_.start===_.end)?this.host.addBlockComment(w[0].blockId,P.comment,N):this.host.addCommentToRanges(w.map(({blockId:_,start:$,end:R})=>({blockId:_,start:$,end:R})),P.comment,N);L?C.push(L):F++}const E=dl(e.agentFeedback,e.originalActions,o,e.docBeforeToolCall,e.docAfterToolCall);return{success:k.length>0,planningSuggestionIds:o,suggestionIds:k,commentedSuggestionIds:A,attachedCommentIds:C,commentAttachmentFailureCount:F,agentFeedback:k.length>0?E:void 0,error:k.length===0?"No changes detected - the document already has the content you specified. Make sure you are modifying the correct block and providing different content.":void 0}}captureLiveSuggestionApplicationSnapshot(){return{doc:this.cloneSuggestionSnapshot(this.host.getDocument()),liveSuggestions:Array.from(this.getLiveSuggestionStore().entries()).map(([e,t])=>[e,this.cloneSuggestionSnapshot(t)])}}restoreLiveSuggestionApplicationSnapshot(e){const t=this.host.getYContentFragment(),n=this.host.getYNotesFragment();this.host.transact(()=>{t.length>0&&t.delete(0,t.length),n.length>0&&n.delete(0,n.length)}),Rl(this.host.ydoc,e.doc),this.host.transact(()=>{const i=this.getLiveSuggestionStore();for(const r of Array.from(i.keys()))i.delete(r);for(const[r,o]of e.liveSuggestions)i.set(r,this.cloneSuggestionSnapshot(o))}),this.host.cachedDoc=this.cloneSuggestionSnapshot(e.doc),On(this.host.ydoc,this.host.cachedDoc),this.host.invalidateDerivedDocumentState()}tryRejectRevertedPendingSuggestions(e){const t=this.host.getActionTargetBlockIds(e.actions,e.baseDoc);if(t.length===0)return null;const n=this.host.getDocument(),i=new Set,r=[];for(const a of t){const l=z(n,a);l&&this.collectSuggestionIdsFromBlockValue(l,i);const c=z(e.baseDoc,a),d=z(e.docAfterToolCall,a);c&&d&&JSON.stringify(c)===JSON.stringify(d)&&r.push(a)}if(i.size===0||r.length===0||this.rejectLiveSuggestions(Array.from(i))===0)return null;const o=r.length===1?`block ${r[0]}`:`${r.length} blocks`;return{success:!0,planningSuggestionIds:[],suggestionIds:[],agentFeedback:`Rejected pending suggestion changes for ${o}.`}}resetToolCallHistory(){this.host.toolCallHistory.clear()}getToolCallHistory(){return this.host.toolCallHistory.getAllToolCalls()}setToolCallHistory(e){this.host.toolCallHistory.clear();for(const t of e)this.host.toolCallHistory.getAllToolCalls().push(t)}getDetachedSuggestionStore(){return this.host.detachedSuggestionStore}hasSerializedDetachedSuggestions(e){return e?Object.keys(e.proposals||{}).length>0||Object.keys(e.metadata||{}).length>0:!1}rebuildDetachedSuggestionsFromSnapshot(e){const t=new Rr(this.host.cloneYDoc(this.host.ydoc));return this.rebuildDetachedSuggestionsFromSnapshotWithStore(e,t)}rebuildDetachedSuggestionsFromSnapshotWithStore(e,t){const n=Pi(e);return $r(n,t)}setDetachedSuggestionConversation(e,t){this.host.detachedSuggestionStore.setConversation(e,t)}clearLegacyDetachedSuggestionState(){const e=Array.from(this.host.detachedSuggestionStore.getAllSuggestions().keys());e.length>0&&this.host.detachedSuggestionStore.rejectSuggestions(e),Tr.clearAllStoredSuggestions(this.host.documentId)}migrateLegacyDetachedSuggestionsToLiveSuggestions(e){const t=this.host.cloneYDoc(this.host.ydoc),n=new Rr(t);if(this.hasSerializedDetachedSuggestions(e.serverDetachedSuggestions)){const d=this.host.cloneYDoc(this.host.ydoc),g=new Tr(d,`${this.host.documentId}-legacy-proposal-materialization`,!0,e.conversationId);g.loadFromServerData(e.serverDetachedSuggestions);const u=Array.from(g.getPendingSuggestions().keys());if(u.length>0){const p=he(g.materializeWithSuggestions(u));this.rebuildDetachedSuggestionsFromSnapshotWithStore(p,n)}}else e.legacyDetachedSuggestionSnapshot?.proposedDocument&&this.rebuildDetachedSuggestionsFromSnapshotWithStore(e.legacyDetachedSuggestionSnapshot.proposedDocument,n);const i=Array.from(n.getPendingSuggestions().keys());if(i.length===0)return{success:!1,migratedSuggestionCount:0,error:"No legacy proposals to migrate."};const r=he(t),o=i.map(d=>this.buildAgentSuggestionPlanFromProposal(d,n,r,t,e.legacyCreatedAt)).filter(d=>!!d);if(o.length!==i.length)return{success:!1,migratedSuggestionCount:0,error:"Could not translate one or more legacy proposals into live suggestions."};const a=this.sortBlockSuggestionPlansByDependency(o.filter(d=>d.category==="block")),l=o.filter(d=>d.category==="inline").sort((d,g)=>d.blockId&&g.blockId&&d.blockId===g.blockId?(g.start??0)-(d.start??0):i.indexOf(d.proposalId)-i.indexOf(g.proposalId));let c=[];try{c=this.withSuggestionMetadata({source:"agent",authorType:"ai",createdAt:e.legacyCreatedAt,label:"Agent revision",agentName:ze,historyOrigin:`migrated-legacy-proposals:${e.conversationId}`},()=>{for(const d of a)if(!d.apply())throw new Error(`Failed migrating block proposal ${d.proposalId}`);for(const d of l)if(!d.apply())throw new Error(`Failed migrating inline proposal ${d.proposalId}`)}).suggestionIds}catch(d){return{success:!1,migratedSuggestionCount:0,error:d instanceof Error?d.message:"Failed applying migrated live suggestions."}}return{success:c.length>0,suggestionIds:c,migratedSuggestionCount:i.length,error:c.length===0?"No legacy proposals were migrated.":void 0}}hydrateLegacyDetachedSuggestionSnapshotForConversation(e,t,n){if(!e||!t?.proposedDocument||this.host.detachedSuggestionStore.getConversationId()!==e||this.host.rebuiltMigrationSnapshotConversations.has(e))return 0;if(this.hasSerializedDetachedSuggestions(n))return this.host.rebuiltMigrationSnapshotConversations.add(e),0;const i=typeof t.pendingSuggestionCount=="number"?t.pendingSuggestionCount:0;try{const r=this.rebuildDetachedSuggestionsFromSnapshot(t.proposedDocument);return(r.length>0||i<=0)&&this.host.rebuiltMigrationSnapshotConversations.add(e),r.length}catch(r){return console.error("[DocumentMutator] Failed rebuilding detached changes from migration snapshot:",r),i<=0&&this.host.rebuiltMigrationSnapshotConversations.add(e),0}}setOnDetachedSuggestionsChanged(e){this.host.detachedSuggestionStore.setOnSuggestionsChanged(e)}}class vu{constructor(e){this.host=e}resolveListContext(e,t){const n=this.host.resolveEditableContext(e,t);if(!n||n.editable.block.type!=="list"||!n.yContext)return null;const i=[];for(let r=0;r<n.yContext.yBlock.length;r++){const o=n.yContext.yBlock.get(r);o instanceof S.XmlElement&&o.nodeName==="list-item"&&i.push(o)}return{doc:n.doc,list:n.editable.block,blockPath:n.editable.blockPath,yContext:n.yContext,yListItems:i}}convertParagraphToList(e,t,n){const i=this.host.getDocument().children[e];return i?.id?this.convertParagraphToListById(i.id,t,n):!1}convertParagraphToListById(e,t,n){const i=this.host.getDocument(),r=z(i,e);if(!r||r.type!=="paragraph")return!1;const o=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(r):null,a=this.host.suggestingMode?ce():null,l=G(this.host.ydoc,e);if(!l)return!1;const{yBlock:c,yParent:d,index:g}=l;this.host.transact(()=>{if(!(c instanceof S.XmlElement))return;const h=new S.XmlElement("list"),f=c.getAttribute("id")||Y();h.setAttribute("id",f),h.setAttribute("variant",t),a&&this.host.suggestionEngine.setElementStructuralSuggestion(h,"change",void 0,a,"List"),n&&t==="ordered"?(h.setAttribute("startNumber",String(n)),this.host.listStartNumberCache.set(f,n)):t==="ordered"?(h.setAttribute("startNumber",String(1)),this.host.listStartNumberCache.set(f,1)):this.host.listStartNumberCache.delete(f);let m,y;for(let x=0;x<c.length;x++){const A=c.get(x);if(A instanceof S.XmlText){y=A;break}}if(y&&y.length>0){const x=Z(y);for(const A of x)if(A.attributes?.fontFamily){m=A.attributes.fontFamily;break}}if(!m&&r.type==="paragraph"){for(const x of r.children)if(x.type==="text"&&x.marks?.fontFamily){m=x.marks.fontFamily;break}}const b=[],k=[],I=(x,A)=>{k.push({ops:x,plain:A})};if(y&&y.length>0){const x=Z(y);let A=[],C="";const F=()=>{I(A,C),A=[],C=""};x.forEach(E=>{if(typeof E.insert=="string"){let P=E.insert;for(;P.length>0;){const B=P.indexOf(`
29
- `);if(B===-1)P.length>0&&(A.push({insert:P,attributes:E.attributes&&Object.keys(E.attributes).length>0?{...E.attributes}:void 0}),C+=P),P="";else{const w=P.slice(0,B);w.length>0&&(A.push({insert:w,attributes:E.attributes&&Object.keys(E.attributes).length>0?{...E.attributes}:void 0}),C+=w),F(),P=P.slice(B+1)}}}else if(E.insert!==void 0&&E.insert!==null){let P=null;if(typeof E.insert=="string")P=E.insert;else try{P=JSON.stringify(E.insert)}catch{P=String(E.insert)}P&&P.length>0&&(A.push({insert:P,attributes:E.attributes&&Object.keys(E.attributes).length>0?{...E.attributes}:void 0}),C+=P)}}),F()}else k.push({ops:[],plain:""});k.length===0&&k.push({ops:[],plain:""});const v=ee(c,"direction");k.forEach(x=>{const A=new S.XmlElement("list-item");A.setAttribute("id",Y()),t==="todo"&&A.setAttribute("checked","false"),(v==="rtl"||v==="ltr")&&A.setAttribute("direction",v);const C=new S.XmlText;if(k.length===1&&(t==="unordered"&&(x.plain==="-"||x.plain==="*")||t==="ordered"&&/^\d+\.$/.test(x.plain.trim())||t==="todo"&&(x.plain==="[]"||x.plain.trim()==="[]"))){const F=[...x.ops].reverse().find(P=>P.insert.length>0)?.attributes,E={...dt(F)??{}};E.fontFamily||(E.fontFamily=m||Fe),A.setAttribute("_emptyTextMarks",JSON.stringify(E))}else{let F=0;x.ops.forEach(({insert:E,attributes:P})=>{if(E.length===0)return;const B=P?{...P}:{};B.fontFamily||(m||console.warn("[DocumentMutator] convertParagraphToList: No font found, defaulting to Arial. This may indicate a bug."),B.fontFamily=m||Fe),C.insert(F,E,B),F+=E.length})}A.insert(0,[C]),b.push(A)}),h.insert(0,b),d.delete(g,1),d.insert(g,[h]),this.host.suggestingMode&&a&&o&&this.host.suggestionEngine.saveLiveSuggestion({id:a,type:"block-change",blockId:e,beforeBlock:o,label:"List"})});const u={block:c.getAttribute("id")||e,offset:0};this.host.setSelectionAfterOperation({anchor:u,focus:u});const p=this.host.getDocument();return this.host.updateAfterOperationRelativeSelection(p),!0}setListDirectionById(e,t){const n=G(this.host.ydoc,e);if(!n)return!1;const{yBlock:i}=n;return!(i instanceof S.XmlElement)||i.nodeName!=="list"?!1:(this.host.transact(()=>{for(let r=0;r<i.length;r++){const o=i.get(r);!(o instanceof S.XmlElement)||o.nodeName!=="list-item"||(t===null?J(o,"direction"):o.setAttribute("direction",t))}}),!0)}getListItemPlainText(e){return e.children.filter(t=>t.type==="text").map(t=>t.text).join("")}convertParagraphRangeToList(e,t,n){e>t&&([e,t]=[t,e]);const i=this.host.getDocument();if(e<0||t>=i.children.length||e>=i.children.length)return!1;const r=[];for(let o=e;o<=t;o++){const a=i.children[o];if(!a)return!1;if(a.type==="paragraph")r.push({type:"paragraph",node:a});else if(a.type==="list")r.push({type:"list",node:a});else return!1}return r.length===0?!1:(this.host.transact(()=>{const o=this.host.getYContentFragment(),a=o.get(e),l=a instanceof S.XmlElement?a.getAttribute("id"):void 0,c=new S.XmlElement("list"),d=l||Y();c.setAttribute("id",d),c.setAttribute("variant",n),n==="ordered"?(c.setAttribute("startNumber",String(1)),this.host.listStartNumberCache.set(d,1)):this.host.listStartNumberCache.delete(d);const g=[];let u;for(const f of r){if(f.type==="paragraph"){for(const m of f.node.children)if(m.type==="text"&&m.marks?.fontFamily){u=m.marks.fontFamily;break}}else if(f.type==="list")for(const m of f.node.children){for(const y of m.children)if(y.type==="text"&&y.marks?.fontFamily){u=y.marks.fontFamily;break}if(u)break}if(u)break}let p=!1;const h=(f,m)=>{const y=new S.XmlElement("list-item");y.setAttribute("id",Y()),n==="todo"&&y.setAttribute("checked",String(m?.checked??!1)),(m?.direction==="rtl"||m?.direction==="ltr")&&y.setAttribute("direction",m.direction);const b=new S.XmlText;let k=f;if((n==="unordered"&&(f==="-"||f==="*")||n==="ordered"&&/^\d+\.$/.test(f)||n==="todo"&&f==="[]")&&(k=""),k){const v=m?.fontFamily||u;v||console.warn("[DocumentMutator] convertParagraphRangeToList: No font found for list item, defaulting to Arial. This may indicate a bug."),b.insert(0,k,{fontFamily:v||Fe})}const I=m?.indentLevel;typeof I=="number"&&I>0&&y.setAttribute("indentLevel",String(I)),y.insert(0,[b]),g.push(y),p=!0};r.forEach(f=>{if(f.type==="paragraph"){const m=f.node.children.filter(b=>b.type==="text").map(b=>b.text).join("");let y;for(const b of f.node.children)if(b.type==="text"&&b.marks?.fontFamily){y=b.marks.fontFamily;break}(m.length>0?m.split(`
30
- `):[""]).forEach(b=>{h(b,{fontFamily:y,direction:f.node.direction})})}else{const m=f.node;m.children.forEach(y=>{const b=this.getListItemPlainText(y),k=m.variant==="todo"?y.checked??!1:void 0;let I;for(const v of y.children)if(v.type==="text"&&v.marks?.fontFamily){I=v.marks.fontFamily;break}h(b,{checked:k,indentLevel:y.indentLevel,fontFamily:I,direction:y.direction})})}}),p||h(""),c.insert(0,g),o.delete(e,t-e+1),o.insert(e,[c])}),!0)}convertListToParagraph(e){const t=this.host.getDocument().children[e];if(!t||t.type!=="list")return!1;const n=t;this.host.suggestingMode&&this.host.suggestionEngine.cloneSuggestionSnapshot(n);const i=this.host.suggestingMode?ce():null;n.id&&this.host.listStartNumberCache.delete(n.id),this.host.transact(()=>{const a=this.host.getYContentFragment(),l=a.get(e);if(!(l instanceof S.XmlElement))return;const c=[];for(let p=0;p<l.length;p++){const h=l.get(p);if(h instanceof S.XmlElement&&h.nodeName==="list-item"){let f=null;for(let m=0;m<h.length;m++){const y=h.get(m);if(y instanceof S.XmlText){f=y;break}}f?c.push({delta:Z(f)}):c.push({delta:[]})}}const d=new S.XmlElement("paragraph");d.setAttribute("id",l.getAttribute("id")||Y());{const p=n.children[0]?.direction;(p==="rtl"||p==="ltr")&&d.setAttribute("direction",p)}i&&this.host.suggestionEngine.setParagraphStructuralSuggestion(d,"change",void 0,i,"Paragraph");const g=new S.XmlText;let u=0;c.forEach((p,h)=>{p.delta.forEach(f=>{typeof f.insert=="string"&&(f.attributes&&Object.keys(f.attributes).length>0?g.insert(u,f.insert,f.attributes):g.insert(u,f.insert),u+=f.insert.length)}),h<c.length-1&&(g.insert(u,`
31
- `),u+=1)}),d.insert(0,[g]),a.delete(e,1),a.insert(e,[d])});const r=this.host.getDocument(),o=r.children[e]?.id?this.host.cursorAtBlock(e,0,r):null;return o&&(this.host.setSelectionAfterOperation({anchor:o,focus:o}),this.host.updateAfterOperationRelativeSelection(r)),!0}updateListVariant(e,t,n){const i=this.host.getDocument().children[e];if(!i||i.type!=="list")return!1;const r=i,o=r.id||String(e),a=r.startNumber;return this.host.transact(()=>{const l=this.host.getYContentFragment().get(e);if(l instanceof S.XmlElement){if(l.setAttribute("variant",t),t==="ordered"){const c=l.getAttribute("startNumber"),d=c?parseInt(c,10):void 0,g=this.host.listStartNumberCache.get(o),u=n??a??d??g??1;l.setAttribute("startNumber",String(u)),this.host.listStartNumberCache.set(o,u)}else a!==void 0&&this.host.listStartNumberCache.set(o,a),l.removeAttribute("startNumber");for(let c=0;c<l.length;c++){const d=l.get(c);d instanceof S.XmlElement&&d.nodeName==="list-item"&&(t==="todo"?d.getAttribute("checked")===void 0&&d.setAttribute("checked","false"):d.removeAttribute("checked"))}}}),!0}convertListToParagraphById(e){const t=this.host.getDocument(),n=z(t,e);if(!n||n.type!=="list")return!1;const i=n,r=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(i):null,o=this.host.suggestingMode?ce():null;i.id&&this.host.listStartNumberCache.delete(i.id);const a=G(this.host.ydoc,e);if(!a)return!1;const{yBlock:l,yParent:c,index:d}=a;this.host.transact(()=>{if(!(l instanceof S.XmlElement))return;const p=[];for(let f=0;f<l.length;f++){const m=l.get(f);if(m instanceof S.XmlElement&&m.nodeName==="list-item"){let y=null;for(let k=0;k<m.length;k++){const I=m.get(k);if(I instanceof S.XmlText){y=I;break}}const b=m.getAttribute("direction");p.push({delta:y?Z(y):[],...b==="rtl"||b==="ltr"?{direction:b}:{}})}}p.length===0&&p.push({delta:[]});const h=p.map((f,m)=>{const y=new S.XmlElement("paragraph");y.setAttribute("id",m===0?l.getAttribute("id")||Y():Y()),f.direction&&y.setAttribute("direction",f.direction),o&&this.host.suggestionEngine.setParagraphStructuralSuggestion(y,"change",void 0,o,"Paragraph");const b=new S.XmlText;let k=0;return f.delta.forEach(I=>{typeof I.insert=="string"&&(I.attributes&&Object.keys(I.attributes).length>0?b.insert(k,I.insert,I.attributes):b.insert(k,I.insert),k+=I.insert.length)}),y.insert(0,[b]),y});if(c.delete(d,1),c.insert(d,h),this.host.suggestingMode&&o&&r){const f=h.map(y=>y.getAttribute("id")),m={id:o,type:"block-change",blockId:f[0],beforeBlock:r,...f.length>1?{sequenceBlockIds:f}:{},label:"Paragraph"};this.host.suggestionEngine.saveLiveSuggestion(m,h[0]);for(const y of h.slice(1))this.host.suggestionEngine.embedLiveSuggestionRecordInTree(this.host.suggestionEngine.getLiveSuggestion(o)??m,y)}});const g={block:l.getAttribute("id")||e,offset:0};this.host.setSelectionAfterOperation({anchor:g,focus:g});const u=this.host.getDocument();return this.host.updateAfterOperationRelativeSelection(u),!0}updateListVariantById(e,t,n){const i=this.host.getDocument(),r=z(i,e);if(!r||r.type!=="list")return!1;const o=r,a=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(o):null,l=o.id||e,c=o.startNumber,d=this.host.suggestingMode?ce():null,g=G(this.host.ydoc,e);if(!g)return!1;const{yBlock:u}=g;return this.host.transact(()=>{if(u instanceof S.XmlElement){if(u.setAttribute("variant",t),d&&(this.host.suggestionEngine.clearElementStructuralSuggestion(u),this.host.suggestionEngine.setElementStructuralSuggestion(u,"change",void 0,d,"List")),t==="ordered"){const p=u.getAttribute("startNumber"),h=p?parseInt(p,10):void 0,f=this.host.listStartNumberCache.get(l),m=n??c??h??f??1;u.setAttribute("startNumber",String(m)),this.host.listStartNumberCache.set(l,m)}else c!==void 0&&this.host.listStartNumberCache.set(l,c),u.removeAttribute("startNumber");for(let p=0;p<u.length;p++){const h=u.get(p);h instanceof S.XmlElement&&h.nodeName==="list-item"&&(t==="todo"?h.getAttribute("checked")===void 0&&h.setAttribute("checked","false"):h.removeAttribute("checked"))}this.host.suggestingMode&&d&&a&&this.host.suggestionEngine.saveLiveSuggestion({id:d,type:"block-change",blockId:e,beforeBlock:a,label:"List"})}}),!0}continueListFromPrevious(e){const t=this.host.getDocument(),n=z(t,e);if(!n||n.type!=="list"||n.variant!=="ordered")return!1;const i=[],r=g=>{for(const u of g)if(u.type==="list")i.push(u);else if(u.type==="container"||u.type==="footnote")r(u.children);else if(u.type==="table")for(const p of u.children)for(const h of p.children)r(h.children)};r(t.children);const o=i.findIndex(g=>g.id===e);let a;for(let g=o-1;g>=0;g--)if(i[g].variant==="ordered"){a=i[g];break}if(o<0||!a)return!1;const l=G(this.host.ydoc,e)?.yBlock,c=G(this.host.ydoc,a.id)?.yBlock;if(!(l instanceof S.XmlElement)||!(c instanceof S.XmlElement))return!1;const d=a.numberingChainId??Y();return this.host.transact(()=>{a.numberingChainId||c.setAttribute("numberingChainId",d),l.setAttribute("numberingChainId",d),l.removeAttribute("startNumber")}),!0}restartListNumberingAt(e,t,n=0){const i=this.host.getDocument(),r=z(i,e);if(!r||r.type!=="list"||r.variant!=="ordered"||!Number.isFinite(t)||t<1)return null;const o=r,a=Math.max(0,Math.min(Math.floor(n),o.children.length-1)),l=Math.floor(t),c=G(this.host.ydoc,e);if(!c)return null;const{yBlock:d,yParent:g,index:u}=c;if(!(d instanceof S.XmlElement))return null;if(a===0)return this.host.transact(()=>{d.setAttribute("startNumber",String(l))}),this.host.listStartNumberCache.set(o.id,l),o.id;const p=Y();return this.host.transact(()=>{const h=new S.XmlElement("list");h.setAttribute("id",p),h.setAttribute("variant",o.variant);const f=o.numberingChainId;f&&h.setAttribute("numberingChainId",f),o.numberingFormat&&h.setAttribute("numberingFormat",o.numberingFormat),h.setAttribute("startNumber",String(l)),o.lineSpacing!==void 0&&h.setAttribute("lineSpacing",String(o.lineSpacing)),h.insert(0,this.cloneYListItemRange(d,a)),d.delete(a,d.length-a),g.insert(u+1,[h])}),this.host.listStartNumberCache.set(p,l),p}cloneYListItemRange(e,t){const n=[];for(let i=t;i<e.length;i++){const r=e.get(i);if(!(r instanceof S.XmlElement)||r.nodeName!=="list-item")continue;const o=new S.XmlElement("list-item");o.setAttribute("id",r.getAttribute("id")||Y());const a=r.getAttribute("checked");a!==void 0&&o.setAttribute("checked",a);const l=r.getAttribute("indentLevel");l!==void 0&&o.setAttribute("indentLevel",l);const c=ee(r,"direction");c!==void 0&&o.setAttribute("direction",c);let d=null;for(let u=0;u<r.length;u++){const p=r.get(u);if(p instanceof S.XmlText){d=p;break}}const g=new S.XmlText;if(d&&d.length>0){const u=Z(d);let p=0;u.forEach(h=>{typeof h.insert=="string"&&(g.insert(p,h.insert,h.attributes||{}),p+=h.insert.length)})}o.insert(0,[g]),n.push(o)}return n}splitListItem(e,t){this.host.beforeOperationSelection=t;const n=this.host.getDocument(),i=z(n,e.block);if(!i||i.type!=="list")return null;const r=i,o=ot(e,this.host.ydoc,n);if(!o)return null;const a=S.createAbsolutePositionFromRelativePosition(o.textOffset,this.host.ydoc);if(!a||!(a.type instanceof S.XmlText))return null;const l=a.type,c=a.index,d=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(r):null,g=this.host.suggestingMode?ce():null;let u=null,p=null,h=!0;if(this.host.transact(()=>{const f=G(this.host.ydoc,r.id);if(!f)return;const{yBlock:m,yParent:y,index:b}=f;if(!(m instanceof S.XmlElement))return;const k=[];for(let $=0;$<m.length;$++){const R=m.get($);R instanceof S.XmlElement&&R.nodeName==="list-item"&&k.push(R)}let I=-1;for(let $=0;$<k.length;$++){const R=k[$];for(let M=0;M<R.length;M++){const O=R.get(M);if(O instanceof S.XmlText&&O===l){I=$;break}}if(I!==-1)break}if(I===-1||I>=r.children.length)return;const v=k[I],x=r.children[I],A=x.children.map($=>$.type==="text"?$.text:"").join(""),C=this.host.suggestingMode&&c<A.length&&(()=>{let $=0,R=!1;for(const M of x.children){if(M.type!=="text")continue;const O=$+M.text.length;if(O>c&&M.text.length>0&&(R=!0,!M.marks?.deletion))return!1;$=O}return R})();if(A.trim().length===0&&r.children.length===1){const $=new S.XmlElement("paragraph");u=Y(),$.setAttribute("id",u),(x.direction==="rtl"||x.direction==="ltr")&&$.setAttribute("direction",x.direction),h=!1;let R;for(const O of x.children)if(O.type==="text"&&O.marks?.fontFamily){R=O.marks.fontFamily;break}R||(R=this.host.resolveFontFamilyForList(r)),R&&$.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:R}));const M=new S.XmlText;$.insert(0,[M]),y.delete(b,1),y.insert(b,[$]);return}if(A.trim().length===0&&r.children.length>1){const $=I===r.children.length-1,R=I===0;if(R||$){m.delete(I,1);const M=new S.XmlElement("paragraph");u=Y(),M.setAttribute("id",u),(x.direction==="rtl"||x.direction==="ltr")&&M.setAttribute("direction",x.direction),h=!1;let O;for(const X of x.children)if(X.type==="text"&&X.marks?.fontFamily){O=X.marks.fontFamily;break}O||(O=this.host.resolveFontFamilyForList(r)),O&&M.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:O}));const D=new S.XmlText;M.insert(0,[D]),R?y.insert(b,[M]):y.insert(b+1,[M])}else{const M=r.children.length-I-1,O=new S.XmlElement("list");if(O.setAttribute("id",Y()),O.setAttribute("variant",r.variant),r.variant==="ordered"){const q=r.numberingChainId??Y();r.numberingChainId||m.setAttribute("numberingChainId",q),O.setAttribute("numberingChainId",q),r.numberingFormat&&O.setAttribute("numberingFormat",r.numberingFormat)}const D=new S.XmlElement("paragraph");u=Y(),D.setAttribute("id",u),(x.direction==="rtl"||x.direction==="ltr")&&D.setAttribute("direction",x.direction),h=!1;let X;for(const q of x.children)if(q.type==="text"&&q.marks?.fontFamily){X=q.marks.fontFamily;break}X||(X=this.host.resolveFontFamilyForList(r)),X&&D.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:X}));const j=new S.XmlText;D.insert(0,[j]);const U=[];for(let q=I+1;q<k.length;q++){const oe=k[q],be=new S.XmlElement("list-item");be.setAttribute("id",oe.getAttribute("id")||Y());const Xe=oe.getAttribute("checked");Xe!==void 0&&be.setAttribute("checked",Xe);const Oe=oe.getAttribute("indentLevel");Oe!==void 0&&be.setAttribute("indentLevel",Oe);const W=ee(oe,"direction");W!==void 0&&be.setAttribute("direction",W);let Q=null;for(let V=0;V<oe.length;V++){const de=oe.get(V);if(de instanceof S.XmlText){Q=de;break}}const se=new S.XmlText;if(Q&&Q.length>0){const V=Z(Q);let de=0;V.forEach(ye=>{if(typeof ye.insert=="string"){const Le=ye.attributes||{};se.insert(de,ye.insert,Le),de+=ye.insert.length}})}be.insert(0,[se]),U.push(be)}O.insert(0,U),m.delete(I,M+1),y.insert(b+1,[D,O])}return}if(c===0){const $=new S.XmlElement("list-item"),R=Y();$.setAttribute("id",R),u=R,r.variant==="todo"&&$.setAttribute("checked","false");const M=x.indentLevel??0;M>0&&$.setAttribute("indentLevel",String(M)),(x.direction==="rtl"||x.direction==="ltr")&&$.setAttribute("direction",x.direction);let O;for(const X of x.children)if(X.type==="text"&&X.marks?.fontFamily){O=X.marks.fontFamily;break}O||(O=this.host.resolveFontFamilyForList(r));const D=new S.XmlText;$.insert(0,[D]),O?$.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:O})):$.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:Fe})),g&&(this.host.suggestionEngine.clearElementStructuralSuggestion($),this.host.suggestionEngine.setElementStructuralSuggestion($,"insert",void 0,g,"Insert")),m.insert(I,[$]),u=x.id??null,p=I+1;return}if(c>=A.length||C){const $=new S.XmlElement("list-item");u=Y(),$.setAttribute("id",u),p=I+1,r.variant==="todo"&&$.setAttribute("checked","false");const R=x.indentLevel??0;R>0&&$.setAttribute("indentLevel",String(R)),(x.direction==="rtl"||x.direction==="ltr")&&$.setAttribute("direction",x.direction);let M=this.host.getFontAtOffsetInListItem(x,c);M||(M=this.host.resolveFontFamilyForList(r));const O=new S.XmlText;$.insert(0,[O]),M?$.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:M})):$.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:Fe})),g&&(this.host.suggestionEngine.clearElementStructuralSuggestion($),this.host.suggestionEngine.setElementStructuralSuggestion($,"insert",void 0,g,"Insert")),m.insert(I+1,[$]);return}let F=null;for(let $=0;$<v.length;$++){const R=v.get($);if(R instanceof S.XmlText){F=R;break}}if(!F)return;const E=Z(F);let P=0;const B=[];for(const $ of E)if($.insert&&typeof $.insert=="string"){const R=$.insert.length;if(P+R<=c)P+=R;else if(P>=c)B.push($);else{const M=c-P,O=$.insert.slice(M);O&&B.push({insert:O,...$.attributes&&{attributes:$.attributes}}),P=c}}c<F.length&&F.delete(c,F.length-c);const w=new S.XmlElement("list-item");u=Y(),w.setAttribute("id",u),p=I+1,r.variant==="todo"&&w.setAttribute("checked","false");const T=x.indentLevel??0;T>0&&w.setAttribute("indentLevel",String(T)),(x.direction==="rtl"||x.direction==="ltr")&&w.setAttribute("direction",x.direction);const N=this.host.getFontAtOffsetInListItem(x,c),L=new S.XmlText;let _=0;if(B.length>0){for(const $ of B)if($.insert&&typeof $.insert=="string"){const R=$.attributes&&Object.keys($.attributes).length>0?{...$.attributes}:{};R.fontFamily||(N||console.warn("[DocumentMutator] splitListItem: No font found for new list item, defaulting to Arial. This may indicate a bug."),R.fontFamily=N||Fe),L.insert(_,$.insert,R),_+=$.insert.length}}else{const $=N||this.host.resolveFontFamilyForList(r)||Fe;w.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:$}))}g&&(this.host.suggestionEngine.clearElementStructuralSuggestion(v),this.host.suggestionEngine.clearElementStructuralSuggestion(w),this.host.suggestionEngine.setElementStructuralSuggestion(v,"split","before",g,"Split"),this.host.suggestionEngine.setElementStructuralSuggestion(w,"split","after",g,"Split")),w.insert(0,[L]),m.insert(I+1,[w])}),h){const f=this.host.getDocument(),m=z(f,r.id);if(!m||m.type!=="list"||p===null)return null;const y=m;let b=0;for(let v=0;v<p;v++){const x=y.children[v];for(const A of x.children)A.type==="text"&&(b+=A.text.length);v<p-1&&(b+=1)}p>0&&(b+=1);const k={block:y.id,offset:b},I={anchor:k,focus:k};return this.host.suggestingMode&&g&&d&&this.host.suggestionEngine.saveLiveSuggestion({id:g,type:"block-change",blockId:r.id,beforeBlock:d,label:"List"}),this.host.setSelectionAfterOperation(I),this.host.afterOperationRelativeSelection=H(I,this.host.ydoc,f),k}else{if(!u)return null;const f={block:u,offset:0},m={anchor:f,focus:f};return this.host.setSelectionAfterOperation(m),this.host.afterOperationRelativeSelection=H(m,this.host.ydoc,this.host.getDocument()),f}}insertTextInListItem(e,t,n,i){const r=this.resolveListContext(e);if(!r)return null;const{doc:o}=r,a=ot(e,this.host.ydoc,o);if(!a)return null;const l=S.createAbsolutePositionFromRelativePosition(a.textOffset,this.host.ydoc);if(!l||!(l.type instanceof S.XmlText))return null;const c=l.type,d=l.index;let g=null;if(i?.anchor&&i.focus&&Ie(r.doc,i.anchor,i.focus)!==0){const A=ot(i.anchor,this.host.ydoc,r.doc),C=ot(i.focus,this.host.ydoc,r.doc),F=A?S.createAbsolutePositionFromRelativePosition(A.textOffset,this.host.ydoc):null,E=C?S.createAbsolutePositionFromRelativePosition(C.textOffset,this.host.ydoc):null;F?.type instanceof S.XmlText&&E?.type instanceof S.XmlText&&F.type===E.type&&F.type===c&&(g={yText:c,startOffset:Math.min(F.index,E.index),endOffset:Math.max(F.index,E.index)})}const u={},p=[],h=ys(o,e),f=$i(o,e),m=Fi(o,e),y=this.host.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(o,e.block),b=y?null:this.host.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(o,e),k=b?.marks?.suggestionId??null,I=this.host.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(o,e,i);{const A=!y&&this.host.suggestingMode&&t.length>0,C=kr({explicitMarks:n&&Object.keys(n).length>0?n:void 0,inheritedMarks:h?.marks,exitingLink:f,exitingComment:m,suggestionMarks:A?this.host.suggestionEngine.buildSuggestionInsertionMarks(void 0,I??k??this.host.suggestionEngine.getSuggestionIdFromInheritedMarks(h?.marks),void 0,void 0,b?.marks??h?.marks):void 0});Object.assign(u,C.marksToApply),p.push(...C.marksToRemove)}let v=g?.startOffset??d;this.host.transact(()=>{if(g&&g.endOffset>g.startOffset){const A=g.endOffset-g.startOffset;if(this.host.suggestingMode&&!y){const C=this.host.suggestionEngine.applySuggestedDeletionToTextRange(g.yText,g.startOffset,A,I??void 0);v=g.startOffset+C.retainedLength}else g.yText.delete(g.startOffset,A),v=g.startOffset}la(c,v,t,{marksToApply:u,marksToRemove:p}),!y&&this.host.suggestingMode&&t.length>0&&this.host.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(c,v,t.length)});const x=S.createRelativePositionFromTypeIndex(c,v+t.length);return li({blockId:a.blockId,textOffset:x},this.host.ydoc)}insertTextInList(e,t,n,i){this.host.beforeOperationSelection=n;const r=this.insertTextInListItem(e,t,null,n);if(r){const o={anchor:r,focus:r};return this.host.setSelectionAfterOperation(o),this.host.afterOperationRelativeSelection=H(o,this.host.ydoc,this.host.getDocument()),!0}return this.host.setSelectionAfterOperation(i),this.host.afterOperationRelativeSelection=H(i,this.host.ydoc,this.host.getDocument()),!0}insertFormattedTextInList(e,t,n,i,r){this.host.beforeOperationSelection=i;const o=this.insertTextInListItem(e,t,n,i);if(o){const a={anchor:o,focus:o};return this.host.setSelectionAfterOperation(a),this.host.afterOperationRelativeSelection=H(a,this.host.ydoc,this.host.getDocument()),!0}return this.host.setSelectionAfterOperation(r),this.host.afterOperationRelativeSelection=H(r,this.host.ydoc,this.host.getDocument()),!0}deleteTextInList(e,t,n,i){const r=this.resolveListContext(e);if(!r)return!1;const o=ot(e,this.host.ydoc,r.doc);if(!o)return!1;const a=S.createAbsolutePositionFromRelativePosition(o.textOffset,this.host.ydoc);if(!a||!(a.type instanceof S.XmlText))return!1;const l=a.type,c=a.index,d=this.host.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r.doc,e.block);return this.host.transact(()=>{const g=l.length,u=Math.min(t,g-c);if(u>0)if(this.host.suggestingMode&&!d){const p=this.host.suggestionEngine.applySuggestedDeletionToTextRange(l,c,u);u>1&&p.retainedLength>0&&this.host.normalizeAdjacentManualReplacementOrder(l,c)}else l.delete(c,u)}),this.host.setSelectionAfterOperation(i),this.host.afterOperationRelativeSelection=H(i,this.host.ydoc,this.host.getDocument()),!0}tryApplyParagraphListTrigger(e,t,n){if(n!==" "||!e.id)return null;const i=this.host.getParagraphPlainText(e);return t.offset!==i.length?null:i==="-"||i==="*"?this.convertParagraphToListById(e.id,"unordered"):/^\d+\.$/.test(i)?this.convertParagraphToListById(e.id,"ordered",parseInt(i,10)):i==="[]"?this.convertParagraphToListById(e.id,"todo"):null}mergeAdjacentListsOnDelete(e,t,n,i,r,o,a){if(i!==n+1||!this.isCursorAtEndOfList(e,r)||!this.isCursorAtStartOfList(t,o))return!1;const l=this.host.getYContentFragment(),c=l.get(n),d=l.get(i);if(!(c instanceof S.XmlElement)||!(d instanceof S.XmlElement))return!1;let g=!1;return this.host.transact(()=>{const u=[];for(let h=0;h<d.length;h++){const f=d.get(h);if(f instanceof S.XmlElement&&f.nodeName==="list-item"){const m=new S.XmlElement("list-item");m.setAttribute("id",Y());const y=f.getAttribute("checked");e.variant==="todo"&&m.setAttribute("checked",y??"false");const b=f.getAttribute("indentLevel");b!==void 0&&m.setAttribute("indentLevel",b);const k=ee(f,"direction");k!==void 0&&m.setAttribute("direction",k);const I=new S.XmlText;for(let v=0;v<f.length;v++){const x=f.get(v);if(x instanceof S.XmlText){const A=Z(x);let C=0;A.forEach(F=>{typeof F.insert=="string"&&(I.insert(C,F.insert,F.attributes||{}),C+=F.insert.length)});break}}m.insert(0,[I]),u.push(m)}}u.length>0&&c.insert(c.length,u),l.delete(i,1);const p=d.getAttribute("id")||t.id;p&&this.host.listStartNumberCache.delete(p),g=!0}),g?(this.host.setSelectionAfterOperation(a),!0):!1}isCursorAtStartOfList(e,t){return t.offset===0}isCursorAtEndOfList(e,t){if(e.children.length===0)return!0;let n=0;for(let i=0;i<e.children.length;i++){const r=e.children[i];n+=r.children.filter(o=>o.type==="text").reduce((o,a)=>o+a.text.length,0),i<e.children.length-1&&(n+=1)}return t.offset>=n}getListCursorInfo(e,t){const n=e;if(n.type!=="list")return null;let i=t.offset,r=0;for(let c=0;c<n.children.length;c++){const d=n.children[c].children.filter(g=>g.type==="text").reduce((g,u)=>g+u.text.length,0);if(i<=d){r=c;break}if(i-=d,c<n.children.length-1){if(i===0){r=c+1;break}i-=1}}if(r<0||r>=e.children.length)return null;const o=e.children[r],a=this.getListItemTextLength(o),l=Math.max(0,Math.min(i,a));return{itemIndex:r,offsetInItem:l,itemLength:a}}getListItemTextLength(e){return e.children.reduce((t,n)=>n.type==="text"?t+n.text.length:t,0)}setListItemIndent(e,t,n,i,r){const o=this.host.getDocument();if(!e||e.type!=="list"||t<0||t>=e.children.length)return!1;const a=e,l=a.children[t].indentLevel??0,c=Math.max(0,Math.min(2,Math.floor(n)));if(c===l)return!1;const d=c-l;if(d>0&&(t===0||(a.children[t-1].indentLevel??0)<c-1))return!1;const g=[],u=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(a):null,p=this.host.suggestingMode?ce():null;if(d!==0)for(let m=t+1;m<a.children.length;m++){const y=a.children[m].indentLevel??0;if(y<=l)break;if(d>0&&y+d>2)return!1;const b=Math.max(0,Math.min(2,y+d));g.push({index:m,newIndent:b})}this.host.beforeOperationSelection=i;const h=Qe().getHandlerForBlock(e);this.host.beforeOperationRelativeSelection=h?.allowsInternalCursor()?H(i,this.host.ydoc,o):null;const f=K(this.host.ydoc,e.id??"");return!f||!(f instanceof S.XmlElement)?!1:(this.host.transact(()=>{const m=[];for(let b=0;b<f.length;b++){const k=f.get(b);k instanceof S.XmlElement&&k.nodeName==="list-item"&&m.push(k)}const y=m[t];y&&(c>0?y.setAttribute("indentLevel",String(c)):y.removeAttribute("indentLevel"),p&&(this.host.suggestionEngine.clearElementStructuralSuggestion(y),this.host.suggestionEngine.setElementStructuralSuggestion(y,"change",void 0,p,d>0?"Indent":"Outdent")),g.forEach(({index:b,newIndent:k})=>{const I=m[b];I&&(k>0?I.setAttribute("indentLevel",String(k)):I.removeAttribute("indentLevel"),p&&(this.host.suggestionEngine.clearElementStructuralSuggestion(I),this.host.suggestionEngine.setElementStructuralSuggestion(I,"change",void 0,p,d>0?"Indent":"Outdent")))}),this.host.suggestingMode&&p&&u&&this.host.suggestionEngine.saveLiveSuggestion({id:p,type:"block-change",blockId:e.id,beforeBlock:u,label:d>0?"Indent":"Outdent"}))}),this.host.setSelectionAfterOperation(r),this.host.afterOperationRelativeSelection=h?.allowsInternalCursor()?H(r,this.host.ydoc,this.host.getDocument()):null,!0)}}function xu(s,e){const t=Z(s).map(l=>typeof l.insert=="string"?l.insert:"").join(""),n=e.map(l=>l.text).join("");let i=0;for(const[l,c]of t===n?[]:Ri(t,n).diffs)l===-1?s.delete(i,c.length):(l===1&&ne(s,i,c),i+=c.length);const r=Z(s);let o=0,a=0;i=0;for(const l of r){if(typeof l.insert!="string")continue;let c=l.insert.length;for(;c>0;){for(;o<e.length&&a===e[o].text.length;)o++,a=0;const d=e[o],g=Math.min(c,d.text.length-a),u=d.marks??{},p=l.attributes??{},h={};for(const f of new Set([...Object.keys(u),...Object.keys(p)])){const m=u[f];JSON.stringify(m)!==JSON.stringify(p[f])&&(h[f]=m??null)}Object.keys(h).length&&ie(s,i,g,h),i+=g,a+=g,c-=g}}}function _r(s,e){const t=s.toArray().filter(c=>c instanceof S.XmlElement),n=t.map(c=>String(c.getAttribute("id"))),i=e.children.map(c=>c.id),r=new Map;let o=0,a=0;for(const c of Ar(n,i)){for(;n[o]!==c;)o++;for(;i[a]!==c;)a++;r.set(a++,t[o++])}const l=new Set(r.values());wn(s,e);for(let c=s.length-1;c>=0;c--){const d=s.get(c);(!(d instanceof S.XmlElement)||!l.has(d))&&s.delete(c,1)}e.children.forEach((c,d)=>{const g=r.get(d);if(!g){s.insert(d,[Se(c)]);return}wn(g,c);const u=g.toArray().find(h=>h instanceof S.XmlText);u&&xu(u,c.children);const p=c.children.every(h=>h.text.length===0)?c.children.find(h=>h.marks&&Object.keys(h.marks).length)?.marks:void 0;if(p){const h=JSON.stringify(p);ee(g,"_emptyTextMarks")!==h&&g.setAttribute("_emptyTextMarks",h)}else J(g,"_emptyTextMarks")})}const Au=300;function wu(s){return Array.from(s).slice(0,Au).join("")}function Tu(s){return s.children.every(e=>e.type==="paragraph"&&e.children.every(t=>t.type==="text"&&t.text.trim().length===0))}class jr extends Error{constructor(e,t,n){super(n instanceof Error?n.message:String(n)),this.actionIndex=e,this.action=t,this.originalError=n,this.name="PreprocessActionError"}}class rn{constructor(){this.afterIdChain=new Map,this.currentTurnId=""}startNewTurn(){const e="turn_"+Date.now();this.afterIdChain.clear(),this.currentTurnId=e}getChainedAfterId(e){return e?this.afterIdChain.get(e)||e:null}updateChain(e,t){this.afterIdChain.set(e,t)}hasChain(e){return this.afterIdChain.has(e)}getCurrentTurnId(){return this.currentTurnId}reset(){this.afterIdChain.clear(),this.currentTurnId=""}}function Ea(s){return s.replace(/\s+id="[^"]*"/g,"")}function $a(s){const e=Ea(s),t=e.match(/^<p\b([^>]*)>([\s\S]*)<\/p>$/i);return t?t[1].trim().length>0?e:t[2]:e}function Fa(s){return te.toInternalHtml({type:"doc",children:[s]})}function Cu(s,e,t,n){if(!s.actions)return s;const i=s.actions.map((c,d)=>{const g=y=>{throw new jr(d,c,new Error(y))};if(c.name==="replace_block"&&(typeof c.arguments.id!="string"||!c.arguments.id.trim())&&g('replace_block id is required. Read the target block and use its current ID. To write into a blank document, use insert_block with referenceId="" and position="after".'),c.name!=="insert_block")return c;const{referenceId:u,position:p}=c.arguments;if(p!=="before"&&p!=="after"&&g("insert_block position must be before or after."),typeof u=="string"&&u.trim())return c;if(!n||!Tu(n))return g("insert_block referenceId is required for a document with content. Read the target location and use a current block ID. Use an empty referenceId only for a blank document.");const h=p==="before"?n.children[0]:n.children.at(-1),f={...c,arguments:{...c.arguments,referenceId:h?.id??Gt}},m=Me(c);return m&&ve(f,m),f}),r=t||new rn;`${s.actions.length}${e}${r.getCurrentTurnId()}`;const o=[],a=n?te.createParsingContext(n):void 0,l=(c,d,g)=>{try{const u=d.name==="insert_block"?d.arguments.referenceId:d.name==="replace_block"?d.arguments.id:void 0,p=typeof u=="string"&&n?z(n,u):null,h=p?.type==="list"?p.children.find(f=>f.id===u):void 0;return te.fromAgentHtml(c,{existingDocument:n,parsingContext:a,preserveImageReferenceIds:!0,listItemBaseIndent:h?h.indentLevel??0:void 0})}catch(u){throw new jr(g,d,u)}};for(const[c,d]of i.entries()){const g=Me(d);if(d.name==="insert_block"){const{referenceId:u,position:p,content:h}=d.arguments;let f=u;const m=p;if(p==="after"&&r.hasChain(u)){const k=r.getChainedAfterId(u);k&&(f=k)}const y=te.coalesceAdjacentBareListFragments(Array.isArray(h)?h:[h]),b=[];for(const k of y){const I=l(k,d,c);if(I.children.length!==0)if(I.children.length===1){const v=Y();ve(d,{stableId:v});const x=I.children[0];let A;x.type==="list"||x.type==="table"||x.type==="page-break"||x.type,A=Ea(te.toInternalHtml(I)),b.push({content:A,id:v})}else for(let v=0;v<I.children.length;v++){const x=I.children[v],A=Fa(x);let C;x.type==="list"||x.type==="table"||x.type==="page-break"||x.type==="toc"?C=A:C=$a(A);const F=Y();b.push({content:C,id:F})}}for(let k=0;k<b.length;k++){const{content:I,id:v}=b[k],x={name:"insert_block",arguments:{}};k===0?(x.arguments.referenceId=f,x.arguments.position=m,ve(x,{stableId:b[k].id})):(x.arguments.referenceId=b[k-1].id,x.arguments.position="after"),x.arguments.content=[I],ve(x,{...g,stableId:v}),o.push(x)}if(p==="after"&&b.length>0){const k=b[b.length-1].id;r.updateChain(u,k)}}else if(d.name==="replace_block"){const{id:u,content:p,count:h}=d.arguments,f=te.coalesceAdjacentBareListFragments(Array.isArray(p)?p:[p]),m=[];for(const y of f){const b=l(y,d,c);if(b.children.length===0)m.push({content:y,id:u,type:"paragraph"});else for(const k of b.children){const I=Fa(k),v=m.length===0?u:Y();m.push({content:I,id:v,type:k.type})}}if(m.length<=1){const y={...d,arguments:{...d.arguments,content:m.length>0?[m[0].content]:f}};g&&ve(y,g),o.push(y)}else{const y={name:"replace_block",arguments:{id:u,...typeof h=="number"?{count:h}:{},content:[m[0].content]}};ve(y,{...g,allowNoopContinuation:!0,splitReplacementGroup:m[0].id,multiBlockReplace:{replacementBlockIds:m.map(b=>b.id),replacedCount:typeof h=="number"?h:1}}),o.push(y);for(let b=1;b<m.length;b++){const{content:k,id:I,type:v}=m[b];let x;v==="list"||v==="table"||v==="code"||v==="page-break"||v==="toc"?x=k:x=$a(k);const A={name:"insert_block",arguments:{referenceId:b===1?u:m[b-1].id,position:"after",content:[x]}};ve(A,{...g,stableId:I,splitReplacementGroup:m[0].id}),o.push(A)}m.length>1&&r.updateChain(u,m[m.length-1].id)}}else o.push(d)}return{...s,actions:o}}const Pu=Math.floor,Bu=(s,e)=>s<e?s:e,Mu=(s,e)=>s>e?s:e,Na=128,di=127,Eu=Number.MAX_SAFE_INTEGER,$u=s=>{const e=unescape(encodeURIComponent(s)),t=e.length,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e.codePointAt(i);return n},sn=typeof TextEncoder<"u"?new TextEncoder:null,Fu=s=>sn.encode(s),Nu=sn?Fu:$u;let on=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});on&&on.decode(new Uint8Array).length===1&&(on=null);const gi=(s,e)=>{const t=s.cbuf.length;s.cpos===t&&(s.bufs.push(s.cbuf),s.cbuf=new Uint8Array(t*2),s.cpos=0),s.cbuf[s.cpos++]=e},ui=(s,e)=>{for(;e>di;)gi(s,Na|di&e),e=Pu(e/128);gi(s,di&e)},Xr=new Uint8Array(3e4),Lu=Xr.length/3,Ou=(s,e)=>{if(e.length<Lu){const t=sn.encodeInto(e,Xr).written||0;ui(s,t);for(let n=0;n<t;n++)gi(s,Xr[n])}else ju(s,Nu(e))},Ru=(s,e)=>{const t=unescape(encodeURIComponent(e)),n=t.length;ui(s,n);for(let i=0;i<n;i++)gi(s,t.codePointAt(i))},Du=sn&&sn.encodeInto?Ou:Ru,_u=(s,e)=>{const t=s.cbuf.length,n=s.cpos,i=Bu(t-n,e.length),r=e.length-i;s.cbuf.set(e.subarray(0,i),n),s.cpos+=i,r>0&&(s.bufs.push(s.cbuf),s.cbuf=new Uint8Array(Mu(t*2,r)),s.cbuf.set(e.subarray(i)),s.cpos=r)},ju=(s,e)=>{ui(s,e.byteLength),_u(s,e)},La=s=>new Error(s),Xu=La("Unexpected end of array"),Uu=La("Integer out of Range"),zu=(s,e)=>{const t=new Uint8Array(s.arr.buffer,s.pos+s.arr.byteOffset,e);return s.pos+=e,t},Hu=s=>zu(s,Ur(s)),Oa=s=>s.arr[s.pos++],Ur=s=>{let e=0,t=1;const n=s.arr.length;for(;s.pos<n;){const i=s.arr[s.pos++];if(e=e+(i&di)*t,t*=128,i<Na)return e;if(e>Eu)throw Uu}throw Xu},Wu=s=>{let e=Ur(s);if(e===0)return"";{let t=String.fromCodePoint(Oa(s));if(--e<100)for(;e--;)t+=String.fromCodePoint(Oa(s));else for(;e>0;){const n=e<1e4?e:1e4,i=s.arr.subarray(s.pos,s.pos+n);s.pos+=n,t+=String.fromCodePoint.apply(null,i),e-=n}return decodeURIComponent(escape(t))}},Yu=s=>on.decode(Hu(s)),Ra=on?Yu:Wu;var an;(function(s){s[s.Token=0]="Token",s[s.PermissionDenied=1]="PermissionDenied",s[s.Authenticated=2]="Authenticated"})(an||(an={}));const qu=(s,e)=>{ui(s,an.Token),Du(s,e)},Ju=(s,e,t)=>{switch(Ur(s)){case an.PermissionDenied:{e(Ra(s));break}case an.Authenticated:{t(Ra(s));break}}},Da=s=>Array.from(s.entries()).map(([e,t])=>({clientId:e,...t}));var zr;(function(s){s[s.Connecting=0]="Connecting",s[s.Open=1]="Open",s[s.Closing=2]="Closing",s[s.Closed=3]="Closed"})(zr||(zr={}));function Ku(s){return s||(s={}),{delay:s.delay===void 0?200:s.delay,initialDelay:s.initialDelay===void 0?0:s.initialDelay,minDelay:s.minDelay===void 0?0:s.minDelay,maxDelay:s.maxDelay===void 0?0:s.maxDelay,factor:s.factor===void 0?0:s.factor,maxAttempts:s.maxAttempts===void 0?3:s.maxAttempts,timeout:s.timeout===void 0?0:s.timeout,jitter:s.jitter===!0,initialJitter:s.initialJitter===!0,handleError:s.handleError===void 0?null:s.handleError,handleTimeout:s.handleTimeout===void 0?null:s.handleTimeout,beforeAttempt:s.beforeAttempt===void 0?null:s.beforeAttempt,calculateDelay:s.calculateDelay===void 0?null:s.calculateDelay}}async function Hr(s){return new Promise(e=>setTimeout(e,s))}function Vu(s,e){let t=e.delay;if(t===0)return 0;if(e.factor&&(t*=Math.pow(e.factor,s.attemptNum-1),e.maxDelay!==0&&(t=Math.min(t,e.maxDelay))),e.jitter){const n=Math.ceil(e.minDelay),i=Math.floor(t);t=Math.floor(Math.random()*(i-n+1))+n}return Math.round(t)}async function Gu(s,e){const t=Ku(e);for(const a of["delay","initialDelay","minDelay","maxDelay","maxAttempts","timeout"]){const l=t[a];if(!Number.isInteger(l)||l<0)throw new Error(`Value for ${a} must be an integer greater than or equal to 0`)}if(t.factor.constructor!==Number||t.factor<0)throw new Error("Value for factor must be a number greater than or equal to 0");if(t.delay<t.minDelay)throw new Error(`delay cannot be less than minDelay (delay: ${t.delay}, minDelay: ${t.minDelay}`);const n={attemptNum:0,attemptsRemaining:t.maxAttempts?t.maxAttempts:-1,aborted:!1,abort(){n.aborted=!0}},i=t.calculateDelay||Vu;async function r(){if(t.beforeAttempt&&t.beforeAttempt(n,t),n.aborted){const l=new Error("Attempt aborted");throw l.code="ATTEMPT_ABORTED",l}const a=async l=>{if(t.handleError&&await t.handleError(l,n,t),n.aborted||n.attemptsRemaining===0)throw l;n.attemptNum++;const c=i(n,t);return c&&await Hr(c),r()};return n.attemptsRemaining>0&&n.attemptsRemaining--,t.timeout?new Promise((l,c)=>{const d=setTimeout(()=>{if(t.handleTimeout)try{l(t.handleTimeout(n,t))}catch(g){c(g)}else{const g=new Error(`Retry timeout (attemptNum: ${n.attemptNum}, timeout: ${t.timeout})`);g.code="ATTEMPT_TIMEOUT",c(g)}},t.timeout);s(n,t).then(g=>{clearTimeout(d),l(g)}).catch(g=>{clearTimeout(d),a(g).then(l).catch(c)})}):s(n,t).catch(a)}const o=t.calculateDelay?t.calculateDelay(n,t):t.initialDelay;if(o&&await Hr(o),n.attemptNum<1&&t.initialJitter){const a=i(n,t);a&&await Hr(a)}return r()}const _a=Math.floor,Qu=(s,e)=>s<e?s:e,Zu=(s,e)=>s>e?s:e,eh=64,hi=128,th=63,ln=127,ja=Number.MAX_SAFE_INTEGER,nh=()=>new Set,ih=Array.from,rh=s=>{const e=unescape(encodeURIComponent(s)),t=e.length,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e.codePointAt(i);return n},cn=typeof TextEncoder<"u"?new TextEncoder:null,sh=s=>cn.encode(s),oh=cn?sh:rh;let dn=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});dn&&dn.decode(new Uint8Array).length===1&&(dn=null);class ah{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Wr=()=>new ah,Xa=s=>{let e=s.cpos;for(let t=0;t<s.bufs.length;t++)e+=s.bufs[t].length;return e},Yr=s=>{const e=new Uint8Array(Xa(s));let t=0;for(let n=0;n<s.bufs.length;n++){const i=s.bufs[n];e.set(i,t),t+=i.length}return e.set(new Uint8Array(s.cbuf.buffer,0,s.cpos),t),e},fi=(s,e)=>{const t=s.cbuf.length;s.cpos===t&&(s.bufs.push(s.cbuf),s.cbuf=new Uint8Array(t*2),s.cpos=0),s.cbuf[s.cpos++]=e},Ce=(s,e)=>{for(;e>ln;)fi(s,hi|ln&e),e=_a(e/128);fi(s,ln&e)},qr=new Uint8Array(3e4),lh=qr.length/3,ch=(s,e)=>{if(e.length<lh){const t=cn.encodeInto(e,qr).written||0;Ce(s,t);for(let n=0;n<t;n++)fi(s,qr[n])}else jt(s,oh(e))},dh=(s,e)=>{const t=unescape(encodeURIComponent(e)),n=t.length;Ce(s,n);for(let i=0;i<n;i++)fi(s,t.codePointAt(i))},Ke=cn&&cn.encodeInto?ch:dh,gh=(s,e)=>{const t=s.cbuf.length,n=s.cpos,i=Qu(t-n,e.length),r=e.length-i;s.cbuf.set(e.subarray(0,i),n),s.cpos+=i,r>0&&(s.bufs.push(s.cbuf),s.cbuf=new Uint8Array(Zu(t*2,r)),s.cbuf.set(e.subarray(i)),s.cpos=r)},jt=(s,e)=>{Ce(s,e.byteLength),gh(s,e)},Ua=s=>new Error(s),za=Ua("Unexpected end of array"),Ha=Ua("Integer out of Range");class uh{constructor(e){this.arr=e,this.pos=0}}const Wa=s=>new uh(s),hh=(s,e)=>{const t=new Uint8Array(s.arr.buffer,s.pos+s.arr.byteOffset,e);return s.pos+=e,t},pi=s=>hh(s,At(s)),Ya=s=>s.arr[s.pos++],At=s=>{let e=0,t=1;const n=s.arr.length;for(;s.pos<n;){const i=s.arr[s.pos++];if(e=e+(i&ln)*t,t*=128,i<hi)return e;if(e>ja)throw Ha}throw za},fh=s=>{let e=s.arr[s.pos++],t=e&th,n=64;const i=(e&eh)>0?-1:1;if((e&hi)===0)return i*t;const r=s.arr.length;for(;s.pos<r;){if(e=s.arr[s.pos++],t=t+(e&ln)*n,n*=128,e<hi)return i*t;if(t>ja)throw Ha}throw za},ph=s=>{let e=At(s);if(e===0)return"";{let t=String.fromCodePoint(Ya(s));if(--e<100)for(;e--;)t+=String.fromCodePoint(Ya(s));else for(;e>0;){const n=e<1e4?e:1e4,i=s.arr.subarray(s.pos,s.pos+n);s.pos+=n,t+=String.fromCodePoint.apply(null,i),e-=n}return decodeURIComponent(escape(t))}},mh=s=>dn.decode(pi(s)),gn=dn?mh:ph,bh=s=>{const e=s.pos,t=gn(s);return s.pos=e,t},Xt=Date.now,Jr=()=>new Map,yh=(s,e,t)=>{let n=s.get(e);return n===void 0&&s.set(e,n=t()),n};class kh{constructor(){this._observers=Jr()}on(e,t){yh(this._observers,e,nh).add(t)}once(e,t){const n=(...i)=>{this.off(e,n),t(...i)};this.on(e,n)}off(e,t){const n=this._observers.get(e);n!==void 0&&(n.delete(t),n.size===0&&this._observers.delete(e))}emit(e,t){return ih((this._observers.get(e)||Jr()).values()).forEach(n=>n(...t))}destroy(){this._observers=Jr()}}const Sh=Object.keys,qa=s=>Sh(s).length,Ih=(s,e)=>Object.prototype.hasOwnProperty.call(s,e),vh=(s,e)=>s===e,un=(s,e)=>{if(s==null||e==null)return vh(s,e);if(s.constructor!==e.constructor)return!1;if(s===e)return!0;switch(s.constructor){case ArrayBuffer:s=new Uint8Array(s),e=new Uint8Array(e);case Uint8Array:{if(s.byteLength!==e.byteLength)return!1;for(let t=0;t<s.length;t++)if(s[t]!==e[t])return!1;break}case Set:{if(s.size!==e.size)return!1;for(const t of s)if(!e.has(t))return!1;break}case Map:{if(s.size!==e.size)return!1;for(const t of s.keys())if(!e.has(t)||!un(s.get(t),e.get(t)))return!1;break}case Object:if(qa(s)!==qa(e))return!1;for(const t in s)if(!Ih(s,t)||!un(s[t],e[t]))return!1;break;case Array:if(s.length!==e.length)return!1;for(let t=0;t<s.length;t++)if(!un(s[t],e[t]))return!1;break;default:return!1}return!0},Kr=3e4;class xh extends kh{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const t=Xt();this.getLocalState()!==null&&Kr/2<=t-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const n=[];this.meta.forEach((i,r)=>{r!==this.clientID&&Kr<=t-i.lastUpdated&&this.states.has(r)&&n.push(r)}),n.length>0&&mi(this,n,"timeout")},_a(Kr/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,n=this.meta.get(t),i=n===void 0?0:n.clock+1,r=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:i,lastUpdated:Xt()});const o=[],a=[],l=[],c=[];e===null?c.push(t):r==null?e!=null&&o.push(t):(a.push(t),un(r,e)||l.push(t)),(o.length>0||l.length>0||c.length>0)&&this.emit("change",[{added:o,updated:l,removed:c},"local"]),this.emit("update",[{added:o,updated:a,removed:c},"local"])}setLocalStateField(e,t){const n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}}const mi=(s,e,t)=>{const n=[];for(let i=0;i<e.length;i++){const r=e[i];if(s.states.has(r)){if(s.states.delete(r),r===s.clientID){const o=s.meta.get(r);s.meta.set(r,{clock:o.clock+1,lastUpdated:Xt()})}n.push(r)}}n.length>0&&(s.emit("change",[{added:[],updated:[],removed:n},t]),s.emit("update",[{added:[],updated:[],removed:n},t]))},Vr=(s,e,t=s.states)=>{const n=e.length,i=Wr();Ce(i,n);for(let r=0;r<n;r++){const o=e[r],a=t.get(o)||null,l=s.meta.get(o).clock;Ce(i,o),Ce(i,l),Ke(i,JSON.stringify(a))}return Yr(i)},Ah=(s,e,t)=>{const n=Wa(e),i=Xt(),r=[],o=[],a=[],l=[],c=At(n);for(let d=0;d<c;d++){const g=At(n);let u=At(n);const p=JSON.parse(gn(n)),h=s.meta.get(g),f=s.states.get(g),m=h===void 0?0:h.clock;(m<u||m===u&&p===null&&s.states.has(g))&&(p===null?g===s.clientID&&s.getLocalState()!=null?u++:s.states.delete(g):s.states.set(g,p),s.meta.set(g,{clock:u,lastUpdated:i}),h===void 0&&p!==null?r.push(g):h!==void 0&&p===null?l.push(g):p!==null&&(un(p,f)||a.push(g),o.push(g)))}(r.length>0||a.length>0||l.length>0)&&s.emit("change",[{added:r,updated:a,removed:l},t]),(r.length>0||o.length>0||l.length>0)&&s.emit("update",[{added:r,updated:o,removed:l},t])};class Ja{constructor(){this.callbacks={}}on(e,t){return this.callbacks[e]||(this.callbacks[e]=[]),this.callbacks[e].push(t),this}emit(e,...t){const n=this.callbacks[e];return n&&n.forEach(i=>i.apply(this,t)),this}off(e,t){const n=this.callbacks[e];return n&&(t?this.callbacks[e]=n.filter(i=>i!==t):delete this.callbacks[e]),this}removeAllListeners(){this.callbacks={}}}class Gr{constructor(e){this.data=e,this.encoder=Wr(),this.decoder=Wa(new Uint8Array(this.data))}peekVarString(){return bh(this.decoder)}readVarUint(){return At(this.decoder)}readVarString(){return gn(this.decoder)}readVarUint8Array(){return pi(this.decoder)}writeVarUint(e){return Ce(this.encoder,e)}writeVarString(e){return Ke(this.encoder,e)}writeVarUint8Array(e){return jt(this.encoder,e)}length(){return Xa(this.encoder)}}var xe;(function(s){s[s.Sync=0]="Sync",s[s.Awareness=1]="Awareness",s[s.Auth=2]="Auth",s[s.QueryAwareness=3]="QueryAwareness",s[s.Stateless=5]="Stateless",s[s.CLOSE=7]="CLOSE",s[s.SyncStatus=8]="SyncStatus"})(xe||(xe={}));var $e;(function(s){s.Connecting="connecting",s.Connected="connected",s.Disconnected="disconnected"})($e||($e={}));class wt{constructor(){this.encoder=Wr()}get(e){return e.encoder}toUint8Array(){return Yr(this.encoder)}}class wh extends wt{constructor(){super(...arguments),this.type=xe.CLOSE,this.description="Ask the server to close the connection"}get(e){return Ke(this.encoder,e.documentName),Ce(this.encoder,this.type),this.encoder}}class Th extends Ja{constructor(e){super(),this.messageQueue=[],this.configuration={url:"",document:void 0,WebSocketPolyfill:void 0,messageReconnectTimeout:3e4,delay:1e3,initialDelay:0,factor:2,maxAttempts:0,minDelay:1e3,maxDelay:3e4,jitter:!0,timeout:0,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onStatus:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,providerMap:new Map},this.webSocket=null,this.webSocketHandlers={},this.shouldConnect=!0,this.status=$e.Disconnected,this.lastMessageReceived=0,this.identifier=0,this.intervals={connectionChecker:null},this.connectionAttempt=null,this.receivedOnOpenPayload=void 0,this.closeTries=0,this.setConfiguration(e),this.configuration.WebSocketPolyfill=e.WebSocketPolyfill?e.WebSocketPolyfill:WebSocket,this.on("open",this.configuration.onOpen),this.on("open",this.onOpen.bind(this)),this.on("connect",this.configuration.onConnect),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("status",this.configuration.onStatus),this.on("disconnect",this.configuration.onDisconnect),this.on("close",this.configuration.onClose),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("close",this.onClose.bind(this)),this.on("message",this.onMessage.bind(this)),this.intervals.connectionChecker=setInterval(this.checkConnection.bind(this),this.configuration.messageReconnectTimeout/10),this.shouldConnect&&this.connect()}async onOpen(e){this.cancelWebsocketRetry=void 0,this.receivedOnOpenPayload=e}attach(e){this.configuration.providerMap.set(e.configuration.name,e),this.status===$e.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===$e.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){this.configuration.providerMap.has(e.configuration.name)&&(e.send(wh,{documentName:e.configuration.name}),this.configuration.providerMap.delete(e.configuration.name))}setConfiguration(e={}){this.configuration={...this.configuration,...e}}async connect(){if(this.status===$e.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const e=()=>{let i=!1;return{retryPromise:Gu(this.createWebSocketConnection.bind(this),{delay:this.configuration.delay,initialDelay:this.configuration.initialDelay,factor:this.configuration.factor,maxAttempts:this.configuration.maxAttempts,minDelay:this.configuration.minDelay,maxDelay:this.configuration.maxDelay,jitter:this.configuration.jitter,timeout:this.configuration.timeout,beforeAttempt:r=>{(!this.shouldConnect||i)&&r.abort()}}).catch(r=>{if(r&&r.code!=="ATTEMPT_ABORTED")throw r}),cancelFunc:()=>{i=!0}}},{retryPromise:t,cancelFunc:n}=e();return this.cancelWebsocketRetry=n,t}attachWebSocketListeners(e,t){const{identifier:n}=e,i=c=>this.emit("message",c),r=c=>this.emit("close",{event:c}),o=c=>this.emit("open",c),a=c=>{t(c)};this.webSocketHandlers[n]={message:i,close:r,open:o,error:a};const l=this.webSocketHandlers[e.identifier];Object.keys(l).forEach(c=>{e.addEventListener(c,l[c])})}cleanupWebSocket(){if(!this.webSocket)return;const{identifier:e}=this.webSocket,t=this.webSocketHandlers[e];Object.keys(t).forEach(n=>{var i;(i=this.webSocket)===null||i===void 0||i.removeEventListener(n,t[n]),delete this.webSocketHandlers[e]}),this.webSocket.close(),this.webSocket=null}createWebSocketConnection(){return new Promise((e,t)=>{this.webSocket&&(this.messageQueue=[],this.cleanupWebSocket()),this.lastMessageReceived=0,this.identifier+=1;const n=new this.configuration.WebSocketPolyfill(this.url);n.binaryType="arraybuffer",n.identifier=this.identifier,this.attachWebSocketListeners(n,t),this.webSocket=n,this.status=$e.Connecting,this.emit("status",{status:$e.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){var t;this.resolveConnectionAttempt(),this.lastMessageReceived=Xt();const n=new Gr(e.data).peekVarString();(t=this.configuration.providerMap.get(n))===null||t===void 0||t.onMessage(e)}resolveConnectionAttempt(){this.connectionAttempt&&(this.connectionAttempt.resolve(),this.connectionAttempt=null,this.status=$e.Connected,this.emit("status",{status:$e.Connected}),this.emit("connect"),this.messageQueue.forEach(e=>this.send(e)),this.messageQueue=[])}stopConnectionAttempt(){this.connectionAttempt=null}rejectConnectionAttempt(){var e;(e=this.connectionAttempt)===null||e===void 0||e.reject(),this.connectionAttempt=null}checkConnection(){var e;this.status===$e.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=Xt()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):((e=this.webSocket)===null||e===void 0||e.close(),this.messageQueue=[])))}get serverUrl(){for(;this.configuration.url[this.configuration.url.length-1]==="/";)return this.configuration.url.slice(0,this.configuration.url.length-1);return this.configuration.url}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,this.webSocket!==null)try{this.webSocket.close(),this.messageQueue=[]}catch(e){console.error(e)}}send(e){var t;((t=this.webSocket)===null||t===void 0?void 0:t.readyState)===zr.Open?this.webSocket.send(e):this.messageQueue.push(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=$e.Disconnected,this.emit("status",{status:$e.Disconnected}),this.emit("disconnect",{event:e}),!this.cancelWebsocketRetry&&this.shouldConnect&&setTimeout(()=>{this.connect()},this.configuration.delay)}destroy(){this.emit("destroy"),clearInterval(this.intervals.connectionChecker),this.stopConnectionAttempt(),this.disconnect(),this.removeAllListeners(),this.cleanupWebSocket()}}const Ka=0,Qr=1,Va=2,Ch=(s,e)=>{Ce(s,Ka);const t=S.encodeStateVector(e);jt(s,t)},Ph=(s,e,t)=>{Ce(s,Qr),jt(s,S.encodeStateAsUpdate(e,t))},Bh=(s,e,t)=>Ph(e,t,pi(s)),Ga=(s,e,t)=>{try{S.applyUpdate(e,pi(s),t)}catch(n){console.error("Caught error while handling a Yjs update",n)}},Mh=(s,e)=>{Ce(s,Va),jt(s,e)},Eh=Ga,$h=(s,e,t,n)=>{const i=At(s);switch(i){case Ka:Bh(s,e,t);break;case Qr:Ga(s,t,n);break;case Va:Eh(s,t,n);break;default:throw new Error("Unknown message type")}return i};class Fh{constructor(e){this.message=e}apply(e,t){const{message:n}=this,i=n.readVarUint(),r=n.length();switch(i){case xe.Sync:this.applySyncMessage(e,t);break;case xe.Awareness:this.applyAwarenessMessage(e);break;case xe.Auth:this.applyAuthMessage(e);break;case xe.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case xe.Stateless:e.receiveStateless(gn(n.decoder));break;case xe.SyncStatus:this.applySyncStatusMessage(e,fh(n.decoder)===1);break;case xe.CLOSE:const o={code:1e3,reason:gn(n.decoder),target:e.configuration.websocketProvider.webSocket,type:"close"};e.onClose(),e.configuration.onClose({event:o}),e.forwardClose(o);break;default:throw new Error(`Can’t apply message of unknown type: ${i}`)}n.length()>r+1&&e.send(wt,{encoder:n.encoder})}applySyncMessage(e,t){const{message:n}=this;n.writeVarUint(xe.Sync);const i=$h(n.decoder,n.encoder,e.document,e);t&&i===Qr&&(e.synced=!0)}applySyncStatusMessage(e,t){t&&e.decrementUnsyncedChanges()}applyAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;Ah(e.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){const{message:t}=this;Ju(t.decoder,e.permissionDeniedHandler.bind(e),e.authenticatedHandler.bind(e))}applyQueryAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;t.writeVarUint(xe.Awareness),t.writeVarUint8Array(Vr(e.awareness,Array.from(e.awareness.getStates().keys())))}}class Nh{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return Yr(this.encoder)}send(e){e?.send(this.create())}}class Lh extends wt{constructor(){super(...arguments),this.type=xe.Auth,this.description="Authentication"}get(e){if(typeof e.token>"u")throw new Error("The authentication message requires `token` as an argument.");return Ke(this.encoder,e.documentName),Ce(this.encoder,this.type),qu(this.encoder,e.token),this.encoder}}class Qa extends wt{constructor(){super(...arguments),this.type=xe.Awareness,this.description="Awareness states update"}get(e){if(typeof e.awareness>"u")throw new Error("The awareness message requires awareness as an argument");if(typeof e.clients>"u")throw new Error("The awareness message requires clients as an argument");Ke(this.encoder,e.documentName),Ce(this.encoder,this.type);let t;return e.states===void 0?t=Vr(e.awareness,e.clients):t=Vr(e.awareness,e.clients,e.states),jt(this.encoder,t),this.encoder}}class Oh extends wt{constructor(){super(...arguments),this.type=xe.Stateless,this.description="A stateless message"}get(e){var t;return Ke(this.encoder,e.documentName),Ce(this.encoder,this.type),Ke(this.encoder,(t=e.payload)!==null&&t!==void 0?t:""),this.encoder}}class Za extends wt{constructor(){super(...arguments),this.type=xe.Sync,this.description="First sync step"}get(e){if(typeof e.document>"u")throw new Error("The sync step one message requires document as an argument");return Ke(this.encoder,e.documentName),Ce(this.encoder,this.type),Ch(this.encoder,e.document),this.encoder}}class Rh extends wt{constructor(){super(...arguments),this.type=xe.Sync,this.description="A document update"}get(e){return Ke(this.encoder,e.documentName),Ce(this.encoder,this.type),Mh(this.encoder,e.update),this.encoder}}class Dh extends Error{constructor(){super(...arguments),this.code=1001}}class _h extends Ja{constructor(e){var t,n,i;super(),this.configuration={name:"",document:void 0,awareness:void 0,token:null,forceSyncInterval:!1,onAuthenticated:()=>null,onAuthenticationFailed:()=>null,onOpen:()=>null,onConnect:()=>null,onMessage:()=>null,onOutgoingMessage:()=>null,onSynced:()=>null,onDisconnect:()=>null,onClose:()=>null,onDestroy:()=>null,onAwarenessUpdate:()=>null,onAwarenessChange:()=>null,onStateless:()=>null,onUnsyncedChanges:()=>null},this.isSynced=!1,this.unsyncedChanges=0,this.isAuthenticated=!1,this.authorizedScope=void 0,this.manageSocket=!1,this._isAttached=!1,this.intervals={forceSync:null},this.boundDocumentUpdateHandler=this.documentUpdateHandler.bind(this),this.boundAwarenessUpdateHandler=this.awarenessUpdateHandler.bind(this),this.boundPageHide=this.pageHide.bind(this),this.boundOnOpen=this.onOpen.bind(this),this.boundOnClose=this.onClose.bind(this),this.forwardConnect=r=>this.emit("connect",r),this.forwardClose=r=>this.emit("close",r),this.forwardDisconnect=r=>this.emit("disconnect",r),this.forwardDestroy=r=>this.emit("destroy",r),this.setConfiguration(e),this.configuration.document=e.document?e.document:new S.Doc,this.configuration.awareness=e.awareness!==void 0?e.awareness:new xh(this.document),this.on("open",this.configuration.onOpen),this.on("message",this.configuration.onMessage),this.on("outgoingMessage",this.configuration.onOutgoingMessage),this.on("synced",this.configuration.onSynced),this.on("destroy",this.configuration.onDestroy),this.on("awarenessUpdate",this.configuration.onAwarenessUpdate),this.on("awarenessChange",this.configuration.onAwarenessChange),this.on("stateless",this.configuration.onStateless),this.on("unsyncedChanges",this.configuration.onUnsyncedChanges),this.on("authenticated",this.configuration.onAuthenticated),this.on("authenticationFailed",this.configuration.onAuthenticationFailed),(t=this.awareness)===null||t===void 0||t.on("update",()=>{this.emit("awarenessUpdate",{states:Da(this.awareness.getStates())})}),(n=this.awareness)===null||n===void 0||n.on("change",()=>{this.emit("awarenessChange",{states:Da(this.awareness.getStates())})}),this.document.on("update",this.boundDocumentUpdateHandler),(i=this.awareness)===null||i===void 0||i.on("update",this.boundAwarenessUpdateHandler),this.registerEventListeners(),this.configuration.forceSyncInterval&&typeof this.configuration.forceSyncInterval=="number"&&(this.intervals.forceSync=setInterval(this.forceSync.bind(this),this.configuration.forceSyncInterval)),this.manageSocket&&this.attach()}setConfiguration(e={}){if(!e.websocketProvider){const t=e;this.manageSocket=!0,this.configuration.websocketProvider=new Th({url:t.url})}this.configuration={...this.configuration,...e}}get document(){return this.configuration.document}get isAttached(){return this._isAttached}get awareness(){return this.configuration.awareness}get hasUnsyncedChanges(){return this.unsyncedChanges>0}resetUnsyncedChanges(){this.unsyncedChanges=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}incrementUnsyncedChanges(){this.unsyncedChanges+=1,this.emit("unsyncedChanges",{number:this.unsyncedChanges})}decrementUnsyncedChanges(){this.unsyncedChanges>0&&(this.unsyncedChanges-=1),this.unsyncedChanges===0&&(this.synced=!0),this.emit("unsyncedChanges",{number:this.unsyncedChanges})}forceSync(){this.resetUnsyncedChanges(),this.send(Za,{document:this.document,documentName:this.configuration.name})}pageHide(){this.awareness&&mi(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){typeof window>"u"||!("addEventListener"in window)||window.addEventListener("pagehide",this.boundPageHide)}sendStateless(e){this.send(Oh,{documentName:this.configuration.name,payload:e})}documentUpdateHandler(e,t){t!==this&&(this.incrementUnsyncedChanges(),this.send(Rh,{update:e,documentName:this.configuration.name}))}awarenessUpdateHandler({added:e,updated:t,removed:n},i){const r=e.concat(t).concat(n);this.send(Qa,{awareness:this.awareness,clients:r,documentName:this.configuration.name})}get synced(){return this.isSynced}set synced(e){this.isSynced!==e&&(this.isSynced=e,e&&this.emit("synced",{state:e}))}receiveStateless(e){this.emit("stateless",{payload:e})}async connect(){if(this.manageSocket)return this.configuration.websocketProvider.connect();console.warn("HocuspocusProvider::connect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.")}disconnect(){if(this.manageSocket)return this.configuration.websocketProvider.disconnect();console.warn("HocuspocusProvider::disconnect() is deprecated and does not do anything. Please connect/disconnect on the websocketProvider, or attach/deattach providers.")}async onOpen(e){this.isAuthenticated=!1,this.emit("open",{event:e});let t;try{t=await this.getToken()}catch(n){this.permissionDeniedHandler(`Failed to get token: ${n}`);return}this.send(Lh,{token:t??"",documentName:this.configuration.name}),this.startSync()}async getToken(){return typeof this.configuration.token=="function"?await this.configuration.token():this.configuration.token}startSync(){this.resetUnsyncedChanges(),this.send(Za,{document:this.document,documentName:this.configuration.name}),this.awareness&&this.awareness.getLocalState()!==null&&this.send(Qa,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.configuration.name})}send(e,t){if(!this._isAttached)return;const n=new Nh(e,t);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){const t=new Gr(e.data),n=t.readVarString();t.writeVarString(n),this.emit("message",{event:e,message:new Gr(e.data)}),new Fh(t).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,this.awareness&&mi(this.awareness,Array.from(this.awareness.getStates().keys()).filter(e=>e!==this.document.clientID),this)}destroy(){this.emit("destroy"),this.intervals.forceSync&&clearInterval(this.intervals.forceSync),this.awareness&&(mi(this.awareness,[this.document.clientID],"provider destroy"),this.awareness.off("update",this.boundAwarenessUpdateHandler),this.awareness.destroy()),this.document.off("update",this.boundDocumentUpdateHandler),this.removeAllListeners(),this.detach(),this.manageSocket&&this.configuration.websocketProvider.destroy(),!(typeof window>"u"||!("removeEventListener"in window))&&window.removeEventListener("pagehide",this.boundPageHide)}detach(){this.configuration.websocketProvider.off("connect",this.configuration.onConnect),this.configuration.websocketProvider.off("connect",this.forwardConnect),this.configuration.websocketProvider.off("open",this.boundOnOpen),this.configuration.websocketProvider.off("close",this.boundOnClose),this.configuration.websocketProvider.off("close",this.configuration.onClose),this.configuration.websocketProvider.off("close",this.forwardClose),this.configuration.websocketProvider.off("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.off("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.off("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.off("destroy",this.forwardDestroy),this.configuration.websocketProvider.detach(this),this._isAttached=!1}attach(){this._isAttached||(this.configuration.websocketProvider.on("connect",this.configuration.onConnect),this.configuration.websocketProvider.on("connect",this.forwardConnect),this.configuration.websocketProvider.on("open",this.boundOnOpen),this.configuration.websocketProvider.on("close",this.boundOnClose),this.configuration.websocketProvider.on("close",this.configuration.onClose),this.configuration.websocketProvider.on("close",this.forwardClose),this.configuration.websocketProvider.on("disconnect",this.configuration.onDisconnect),this.configuration.websocketProvider.on("disconnect",this.forwardDisconnect),this.configuration.websocketProvider.on("destroy",this.configuration.onDestroy),this.configuration.websocketProvider.on("destroy",this.forwardDestroy),this.configuration.websocketProvider.attach(this),this._isAttached=!0)}permissionDeniedHandler(e){this.emit("authenticationFailed",{reason:e}),this.isAuthenticated=!1}authenticatedHandler(e){this.isAuthenticated=!0,this.authorizedScope=e,this.emit("authenticated",{scope:e})}setAwarenessField(e,t){if(!this.awareness)throw new Dh(`Cannot set awareness field "${e}" to ${JSON.stringify(t)}. You have disabled Awareness for this provider by explicitly passing awareness: null in the provider configuration.`);this.awareness.setLocalStateField(e,t)}}const el=10,bi=(s,e,t)=>Math.max(e,Math.min(t,s));function hn(s){const e={};for(const[t,n]of Object.entries(s??{}))yr.has(t)&&t!=="aiGenerated"&&t!=="__htmlClassName"||n==null||(e[t]=n);return JSON.stringify(e)}function fn(s){if(typeof s!="string"||s.length===0)return null;try{const e=JSON.parse(s);return e&&typeof e=="object"&&typeof e.id=="string"?e:null}catch{return null}}function yi(s){if(typeof s!="string"||s.length===0)return null;try{const e=JSON.parse(s);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function tl(s,e){if(!s)return;const t={},n=!!s.footnoteRef;for(const[i,r]of Object.entries(s))r===void 0||r===!1||r===null||yr.has(i)||i!=="footnoteRef"&&(i==="superscript"&&n||(t[i]=r));return Object.keys(t).length>0?t:void 0}const nl=["spaceBefore","spaceAfter","contextualSpacing"];function pn(s,e){e.spaceBefore!==void 0&&s.setAttribute("spaceBefore",String(e.spaceBefore)),e.spaceAfter!==void 0&&s.setAttribute("spaceAfter",String(e.spaceAfter)),e.contextualSpacing!==void 0&&s.setAttribute("contextualSpacing",String(e.contextualSpacing))}function jh(s,e,t=!1){for(const n of nl){const i=ee(s,n);i!=null?e.setAttribute(n,i):t&&J(e,n)}}function il(s){if(!s)return{};if(typeof s=="string")try{return JSON.parse(s)}catch{return{}}return typeof s=="object"?{...s}:{}}function rl(s){const e=il(s.getAttribute("_emptyTextMarks"));if(Object.keys(e).length===0)return!1;for(const t of $s)delete e[t];return Object.keys(e).length===0?s.removeAttribute("_emptyTextMarks"):s.setAttribute("_emptyTextMarks",JSON.stringify(e)),!0}function sl(s,e,t,n){const i=s.getAttribute("_emptyTextMarks"),r=i!=null,o=t==null||t===!1;if(!r&&!n&&!o)return!1;const a=il(i),l=Object.prototype.hasOwnProperty.call(a,e);if(o){if(!l)return!1;delete a[e]}else{if(a[e]===t)return!1;a[e]=t}return Object.keys(a).length===0?s.removeAttribute("_emptyTextMarks"):s.setAttribute("_emptyTextMarks",JSON.stringify(a)),!0}function ki(s,e){e&&Object.keys(e).length>0?s.setAttribute("_emptyTextMarks",JSON.stringify(e)):s.removeAttribute("_emptyTextMarks")}function Si(s){return s.children.some(e=>e.type==="text"&&e.text.length>0)}function mn(s,e,t,n){if(!Si(e))return dt(n);if(t.offset<=0){const r=e.children.find(o=>o.type==="text"&&o.text.length>0);return dt(r?.marks)}const i=ys(s,t);return dt(i?.marks)}const bn=s=>s?.type==="code"||s?.type==="math",Ut=s=>{if(!s||s.type!=="code")return!1;const e=s.language?.trim().toLowerCase();return e==="latex"||e==="latex-inline"},Fe="Arial, sans-serif";function ol(s){if(s==null)return;const e=Number.parseFloat(s);return Number.isFinite(e)?e:void 0}function al(s,e){for(const t of s.toArray())if(t instanceof S.XmlElement){if(t.nodeName==="paragraph"){e(t);continue}(t.nodeName==="container"||t.nodeName==="table"||t.nodeName==="table-row"||t.nodeName==="table-cell")&&al(t,e)}}const ll=s=>s.name==="set_title"||s.name==="set_notes"||s.name==="set_page_layout"||s.name==="set_header_footer",Xh=s=>`${s} ${s===1?"proposal":"proposals"}`;function Ne(s){if(!s||typeof s!="object")return"";if(s.type==="text"&&typeof s.text=="string")return s.text;if((s.type==="code"||s.type==="math")&&typeof s.content=="string")return s.content;if(Array.isArray(s.children)){const e=s.type==="paragraph"||s.type==="list-item"?"":" ";return s.children.map(t=>Ne(t)).filter(t=>t.length>0).join(e)}return""}function cl(s){const e=s.replace(/\s+/g," ").trim();return e.length===0?[]:e.split(" ")}function Uh(s,e){if(s.length===0||e.length===0)return 0;const t=new Array(e.length+1).fill(0),n=new Array(e.length+1).fill(0);for(let i=1;i<=s.length;i++){for(let r=1;r<=e.length;r++)n[r]=s[i-1]===e[r-1]?t[r-1]+1:Math.max(t[r],n[r-1]);for(let r=0;r<=e.length;r++)t[r]=n[r],n[r]=0}return t[e.length]}function zh(s,e){const t=cl(s),n=cl(e),i=Math.max(t.length,n.length);if(i===0)return null;const r=Uh(t,n),o=Math.max(0,i-r);return Math.round(o/i*100)}function Hh(s,e,t){const n=z(s,t),i=z(e,t);if(!n||!i)return null;const r=Ne(n),o=Ne(i);return zh(r,o)}function dl(s,e,t,n,i){if(!s||!e||t.length===0)return s;const r=e.filter(g=>!ll(g));if(r.length!==1||r[0].name!=="replace_block")return s;const o=r[0].arguments&&typeof r[0].arguments=="object"?r[0].arguments:void 0,a=typeof o?.id=="string"&&o.id.trim().length>0?o.id.trim():null;if(!a||(typeof o?.count=="number"&&Number.isFinite(o.count)?Math.max(1,Math.floor(o.count)):1)!==1)return s;const l=[Xh(t.length)],c=Hh(n,i,a);c!==null&&l.push(`~${c}% words changed`);const d=s.trim();return d.endsWith(".")?`${d.slice(0,-1)} (${l.join("; ")}).`:`${d} (${l.join("; ")}).`}function Wh(s,e,t){if(t<=0)return[];const n=qe(s).get(e);if(!n)return[];const i=n.parentContainer?n.parentContainer.children:s.children,r=[];for(let o=n.indexInParent;o<i.length&&r.length<t;o+=1){const a=i[o];if(!a?.id)break;r.push(a.id)}return r}function Yh(s,e){if(!e||e.length===0)return[];const t=[];for(const n of e){if(n.name!=="replace_block")continue;const i=Hc(n);if(!i||i.replacementBlockIds.length<=1||i.replacedCount<=1)continue;const r=n.arguments&&typeof n.arguments=="object"?n.arguments:void 0,o=typeof r?.id=="string"&&r.id.trim().length>0?r.id.trim():null;if(!o)continue;const a=Wh(s,o,i.replacedCount),l=a.length===i.replacedCount&&i.replacementBlockIds.length===i.replacedCount?i.replacedCount:1;for(let c=0;c<l;c+=1){const d=a[c],g=i.replacementBlockIds[c];!d||!g||t.push({currentBlockId:d,finalBlockId:g})}}return t}const gl=(s,e,t)=>{if(!s||!e)return;const n=s.filter(a=>!ll(a));if(n.length!==1){if(n.length===0){const a=s.some(g=>g.name==="set_title"),l=s.some(g=>g.name==="set_notes"),c=s.some(g=>g.name==="set_page_layout");if(a&&l&&c)return"Updated title, notes, and page layout.";if(a&&l)return"Updated title and notes.";if(c&&a)return"Updated page layout and title.";if(c&&l)return"Updated page layout and notes.";if(a){const g=s.find(u=>u.name==="set_title")?.arguments?.title;return g?`Title set to "${g}".`:"Title set."}if(l)return"Notes updated.";if(c)return"Page layout updated.";const d=s.find(g=>g.name==="set_header_footer");if(d){const g=d.arguments?.side==="footer"?"Footer":"Header";return d.arguments?.clear?`${g} removed.`:`${g} updated.`}}return}const i=n[0],r=t?.[0]??[],o=a=>{if(typeof a=="string"&&a.trim().length>0)return a.trim();if(Array.isArray(a)){const l=Array.from(new Set(a.filter(c=>typeof c=="string").map(c=>c.trim()).filter(c=>c.length>0)));return l.length===0?"the target blocks":l.length===1?l[0]:`${l.length} blocks (${l.join(", ")})`}return"the target blocks"};if(i.name==="insert_block"){const a=e.filter(g=>g.name==="insert_block").map(g=>Hn(g)).filter(g=>typeof g=="string"&&g.length>0);if(a.length===0)return;const l=a.length,c=a[0],d=a[a.length-1];return l===1?`Inserted block ${c}.`:`Inserted ${l} blocks; first inserted block ID was ${c}; last inserted block ID was ${d}.`}if(i.name==="replace_block"){const a=e.find(u=>u.name==="replace_block"),l=a&&"id"in a.arguments?a.arguments.id:void 0;if(!l)return;const c=e.filter(u=>u.name==="insert_block").map(u=>Hn(u)).filter(u=>typeof u=="string"&&u.length>0),d=1+c.length,g=c.length>0?c[c.length-1]:l;return d===1?`Replaced block ${l}.`:`Inserted ${d} blocks; first inserted block ID was ${l}; last inserted block ID was ${g}.`}if(i.name==="remove_block"){const{id:a,count:l=1}=i.arguments,c=r.length>0?r.length:l;return`Removed ${c} ${c===1?"block":"blocks"} starting at block ID ${a}.`}if(i.name==="set_block_attribute"){const{id:a,attribute:l,operation:c="set"}=i.arguments,d=o(a);return c==="toggle"?`Toggled ${l} on ${d}.`:c==="remove"?`Removed ${l} from ${d}.`:`Updated ${l} on ${d}.`}if(i.name==="clear_formatting"){const{id:a}=i.arguments;return`Cleared removable formatting on ${o(a)}. Font family, font size, text color, and paragraph attributes were intentionally preserved.`}if(i.name==="replace"||i.name==="replace_all"){const{id:a}=i.arguments,l=r.length>0?r.length:1;return`Replaced ${l} ${l===1?"occurrence":"occurrences"} in block ${a}.`}if(i.name==="append_to_paragraph"){const{id:a}=i.arguments,l=r.map(c=>c.text?.length??0).reduce((c,d)=>c+d,0);return l>0?`Appended ${l} characters to block ${a}.`:`Appended content to block ${a}.`}if(i.name==="break_paragraph"){const{id:a}=i.arguments,l=r.find(c=>c.kind==="insert"&&c.paragraphId!==a);return l?.paragraphId?`Split block ${a}; new block ID ${l.paragraphId}.`:`Split block ${a}.`}if(i.name==="join_paragraphs"){const{firstId:a,secondId:l}=i.arguments;return`Joined adjacent blocks ${a} and ${l}; preserved block ${a}.`}if(i.name==="insert_table_row"){const{tableId:a,referenceIndex:l,referenceRowId:c,position:d}=i.arguments,g=r.find(u=>u.kind==="insert"&&u.paragraphId===a);return g?.text?`${g.text} in table ${a}.`:`Inserted 1 row ${d} row ${c??l} in table ${a}.`}if(i.name==="remove_table_row"){const{tableId:a,rowIndex:l}=i.arguments;return`Removed row ${l} from table ${a}.`}if(i.name==="insert_table_column"){const{tableId:a,referenceIndex:l,position:c}=i.arguments;return`Inserted 1 column ${c} column ${l} in table ${a}.`}if(i.name==="remove_table_column"){const{tableId:a,columnIndex:l}=i.arguments;return`Removed column ${l} from table ${a}.`}},ul=class lt{constructor(e,t=()=>{},n,i,r,o,a,l){this.cachedDoc=null,this.incrementalRefreshPending=!1,this.derivedDocumentRevision=0,this.liveSuggestionIdsCache=null,this.liveSuggestionIdsBySourceCache=new Map,this.inlineSuggestionMetadataCache=new Map,this.inlineSuggestionKindCache=new Map,this.canResolveLiveSuggestionCache=new Map,this.liveSuggestionProjectionCache=new Map,this.suggestionIdsByBlockCache=new WeakMap,this.documentSuggestionIdsCache=null,this.afterOperationSelection=null,this.beforeOperationSelection=null,this.beforeOperationRelativeSelection=null,this.afterOperationRelativeSelection=null,this.origin="local-user",this.trackedUndoOrigins=new Set([null,"local-user"]),this.remoteOrigins=new Set,this.isRedoing=!1,this.currentSelectionBeforeRedo=null,this.afterSelectionForRedo=null,this.rebuiltMigrationSnapshotConversations=new Set,this.listStartNumberCache=new Map,this.batchingUpdates=!1,this.pendingUpdate=null,this.disposed=!1,this.handleYDocUpdate=(f,m,y,b)=>{if(this.disposed)return;m!==hs&&m!==sa&&this.canRepairIdentity()&&(this.classifyTransactionOrigin(m)==="local"?this.repairDocumentIdentity(b,m):this.scheduleDeferredIdentityRepair());const k=this.ydoc.share.get("agent-presence"),I=k&&b.changedParentTypes.size>0&&[...b.changedParentTypes.keys()].every(x=>x===k),v=this.classifyTransactionOrigin(m);I||(this.invalidateDerivedDocumentState(),this.cachedDoc=null,this.incrementalRefreshPending=!0),this.batchingUpdates?this.pendingUpdate=()=>this.onDocumentChange(this.getDocument(),{origin:v}):this.onDocumentChange(this.getDocument(),{origin:v})},this.suggestingMode=!1,this.liveSuggestionMetadataContext=null,this.defaultHumanAuthorName=null,this.liveSuggestionTreeRecordCache=new Map,this.liveSuggestionTreeRecordCacheReady=!1,this.lastPrunedUnresolvableLiveSuggestions=[],this.listOperations=new vu(this),this.suggestionEngine=new yn(this),this.cachedKernel=null,this.strandedObservers=!1,this.strandedCheck=null,this.identityRepairedOnConstruct=!1,this.deferredIdentityRepair=null,this.ydoc=i||Pi(e),ra(this.ydoc,br),this.canRepairIdentity=l?.canRepairIdentity??(()=>!0),!l?.deferIdentityRepair&&this.canRepairIdentity()&&this.repairDocumentIdentity()&&(this.identityRepairedOnConstruct=!0,e=he(this.ydoc)),this.documentId=r||"default",this.onDocumentChange=t,this.onTitleChange=n,this.detachedSuggestionStore=new Tr(this.ydoc,this.documentId,o),this.toolCallHistory=new va,this.preprocessorSession=a||new rn,this.ensureParagraphIndentStorageUsesUnits(),this.cachedDoc=e,On(this.ydoc,e),this.documentSuggestionIdsCache=this.suggestionEngine.createDocumentSuggestionIdsCache(e);const c=this.ydoc.getXmlFragment("content"),d=this.ydoc.getXmlFragment("chrome"),g=this.ydoc.getXmlFragment("notes"),u=this.ydoc.getArray("annotations"),p=this.suggestionEngine.getLiveSuggestionStore(),h=this.ydoc.getMap("comments");this.undoManager=new S.UndoManager([c,d,g,u,p,h],{captureTimeout:1e3,trackedOrigins:this.trackedUndoOrigins}),this.ydoc.on("update",this.handleYDocUpdate),this.undoManager.on("stack-item-added",f=>{this.isRedoing?(this.currentSelectionBeforeRedo&&f.stackItem.meta.set("beforeSelection",this.currentSelectionBeforeRedo),this.afterSelectionForRedo&&f.stackItem.meta.set("afterSelection",this.afterSelectionForRedo),this.currentSelectionBeforeRedo=null,this.afterSelectionForRedo=null,this.isRedoing=!1):(this.beforeOperationRelativeSelection?f.stackItem.meta.set("beforeSelection",this.beforeOperationRelativeSelection):this.beforeOperationSelection&&f.stackItem.meta.set("beforeSelectionAbsolute",this.beforeOperationSelection),this.afterOperationRelativeSelection&&f.stackItem.meta.set("afterSelection",this.afterOperationRelativeSelection),this.beforeOperationSelection&&f.stackItem.meta.set("beforeSelectionAbsolute",this.beforeOperationSelection)),this.beforeOperationRelativeSelection=null,this.afterOperationRelativeSelection=null}),this.undoManager.on("stack-item-popped",f=>{if(f.type==="undo"){const m=this.undoManager.redoStack;if(m.length>0&&f.stackItem.meta.size>0){const y=m[m.length-1];f.stackItem.meta.forEach((b,k)=>{y.meta.set(k,b)})}}})}invalidateDerivedDocumentState(){this.derivedDocumentRevision+=1,this.liveSuggestionIdsCache=null,this.liveSuggestionIdsBySourceCache.clear(),this.inlineSuggestionMetadataCache.clear(),this.inlineSuggestionKindCache.clear(),this.canResolveLiveSuggestionCache.clear();for(const e of this.liveSuggestionProjectionCache.values())e.projection.ydoc.destroy();this.liveSuggestionProjectionCache.clear(),this.documentSuggestionIdsCache=null,this.liveSuggestionTreeRecordCache.clear(),this.liveSuggestionTreeRecordCacheReady=!1}getTopLevelIndexFromPath(e){return!e||e.length===0?null:e.length>0?e[0]:0}getTopLevelIndexFromPosition(e){if(!e)return null;const t=this.getBlockContextById(this.getDocument(),e.block);return t?t.topLevelIndex:null}getBlockContextById(e,t){const n=z(e,t);if(!n)return null;const i=ht(e,t);if(!i||i.length===0)return fs(e,t)?{block:n,blockPath:[-1],topLevelIndex:-1}:null;const r=i[0];return{block:n,blockPath:i,topLevelIndex:r}}cursorAtBlock(e,t,n=this.getDocument()){const i=n.children[e];return i?.id?{block:i.id,offset:t}:null}resolveFontFamilyForList(e){for(const t of e.children)for(const n of t.children)if(n.type==="text"&&n.marks?.fontFamily)return n.marks.fontFamily}getFontAtOffsetInListItem(e,t){if(t<=0){for(const r of e.children)if(r.type==="text"&&r.marks?.fontFamily)return r.marks.fontFamily;return}let n=0,i;for(const r of e.children)if(r.type==="text"){const o=r.text.length;if(r.marks?.fontFamily&&(i=r.marks.fontFamily),n+o>=t)return r.marks?.fontFamily||i;n+=o}return i}registerTrackedUndoOrigin(e){e!==void 0&&this.trackedUndoOrigins.add(e)}registerRemoteOrigin(e){if(e==null)throw new Error("A collaboration provider must apply updates with a non-null transaction origin");this.remoteOrigins.add(e),this.trackedUndoOrigins.delete(e)}unregisterRemoteOrigin(e){this.remoteOrigins.delete(e)}classifyTransactionOrigin(e){return e===this.origin||this.trackedUndoOrigins.has(e)?"local":this.remoteOrigins.has(e)||e instanceof _h?"remote":"unknown"}runWithUndoGroup(e,t){const n=this.origin;this.registerTrackedUndoOrigin(e),this.undoManager.stopCapturing(),this.beginGroup(e),this.origin=e;try{return t()}finally{this.origin=n,this.endGroup()}}getTextMarksAtBlockOffset(e,t,n){const i=z(this.getDocument(),e);if(!i)return;const r=i.type==="paragraph"?i.children:i.type==="list"&&t!==void 0?i.children[t]?.children:void 0;if(!r)return;let o=0;for(const a of r){if(a.type!=="text")continue;const l=o+a.text.length;if(n<l||a.text.length===0&&n===o)return a.marks;o=l}return[...r].reverse().find(a=>a.type==="text")?.marks}getFormattingDescriptionFromMarkKey(e){switch(e){case"bold":return"Bold";case"italic":return"Italic";case"underline":return"Underline";case"strikethrough":return"Strikethrough";case"doubleStrikethrough":return"Double Strikethrough";case"smallCaps":return"Small Caps";case"allCaps":return"All Caps";case"letterSpacing":return"Letter Spacing";case"code":return"Code";case"latex":return"LaTeX";case"superscript":return"Superscript";case"subscript":return"Subscript";case"backgroundColor":return"Highlight";case"fontSize":return"Font Size";case"color":return"Text Color";case"fontFamily":return"Font";case"link":return"Link";default:return"Format"}}getNaturalFormatCategoryFromMarkKey(e){switch(e){case"bold":return"bold";case"italic":return"italic";case"underline":return"underline";case"strikethrough":return"strikethrough";case"doubleStrikethrough":return"double strikethrough";case"smallCaps":return"small caps";case"allCaps":return"all caps";case"letterSpacing":return"letter spacing";case"superscript":return"superscript";case"subscript":return"subscript";case"fontSize":return"font size";case"color":return"text color";case"fontFamily":return"font";case"backgroundColor":return"highlight";case"link":return"link";case"code":return"code style";case"latex":return"LaTeX";default:return"formatting"}}getNaturalFormatCategoryFromDescription(e){return e.trim().toLowerCase()||"formatting"}buildNaturalFormatChangeDescription(e){const t=e.filter((i,r)=>e.indexOf(i)===r);if(t.length===0)return"Formatting";const n=t.join(", ");return n.charAt(0).toUpperCase()+n.slice(1)}getInlineFormatDescription(e){const t=new Set,n=new Set,i=["bold","italic","underline","strikethrough","doubleStrikethrough","smallCaps","allCaps","letterSpacing","code","latex","superscript","subscript","fontFamily","fontSize","color","backgroundColor","link"];for(const r of e.spans){const o=this.getTextMarksAtBlockOffset(r.blockId,r.itemIndex,r.start);for(const a of i){const l=r.attributes[a],c=o?.[a];a==="fontFamily"&&(l??void 0)===void 0&&c===Fe||(l??void 0)!==(c??void 0)&&(t.add(a),(c??void 0)===void 0||c===!1?n.add(a):n.delete(a))}}if(t.size>0){const r=Array.from(t).map(o=>{const a=this.getNaturalFormatCategoryFromMarkKey(o);return n.has(o)?`remove ${a}`:a});return this.buildNaturalFormatChangeDescription(r)}return e.label&&e.label!=="Format"?this.buildNaturalFormatChangeDescription([this.getNaturalFormatCategoryFromDescription(e.label)]):null}getBlockDescription(e){if(!e)return null;switch(e.type){case"image":return"Image";case"table":return"Table";case"code":return e.language==="latex"?"LaTeX Block":e.renderDiagram?"Diagram":"Code Block";case"math":return"LaTeX Block";case"page-break":return"Page Break";case"section-break":return"Section Break";case"placeholder":return"Placeholder";case"toc":return"Table of Contents";case"container":return"Container";case"paragraph":case"list":return null;default:return null}}getTableDimensionDescription(e,t,n){if(!e||e!=="Row"&&e!=="Column"||t?.type!=="table"||n?.type!=="table")return null;const i=e==="Row"?t.children.length:t.columnWidths.length,r=e==="Row"?n.children.length:n.columnWidths.length;return r>i?`Insert Table ${e}`:r<i?`Delete Table ${e}`:`Change Table ${e}`}getTextFormattingChangeKeys(e,t){const n=new Set,i=e.map(a=>a.text).join(""),r=t.map(a=>a.text).join("");if(i!==r)return[];const o=Math.max(i.length,r.length);for(let a=0;a<o;a++){const l=this.getTextMarksAtOffset(e,a),c=this.getTextMarksAtOffset(t,a);for(const d of An)this.formattingMarkValuesEqual(l?.[d],c?.[d])||n.add(d)}if(o===0){const a=e[0]?.marks,l=t[0]?.marks;for(const c of An)this.formattingMarkValuesEqual(a?.[c],l?.[c])||n.add(c)}return An.filter(a=>n.has(a))}getTextMarksAtOffset(e,t){let n=0;for(const i of e){const r=n+i.text.length;if(t<r)return i.marks;n=r}return e[e.length-1]?.marks}formattingMarkValuesEqual(e,t){const n=e??void 0,i=t??void 0;return n===i?!0:typeof n=="string"&&typeof i=="string"&&/^#[0-9a-fA-F]{6}$/.test(n)&&/^#[0-9a-fA-F]{6}$/.test(i)?n.toLowerCase()===i.toLowerCase():!1}getBlockFormatDescription(e,t){const n=[],i=r=>{n.includes(r)||n.push(r)};if(e?.type==="paragraph"&&t?.type==="paragraph"&&(e.heading!==t.heading&&i("heading"),e.align!==t.align&&i("alignment"),e.lineSpacing!==t.lineSpacing&&i("line spacing"),(e.leftIndent!==t.leftIndent||e.firstLineIndent!==t.firstLineIndent)&&i("indent"),n.length===0))for(const r of this.getTextFormattingChangeKeys(e.children,t.children))i(this.getNaturalFormatCategoryFromMarkKey(r));if(e?.type==="list"&&t?.type==="list"){e.lineSpacing!==t.lineSpacing&&i("line spacing");const r=Math.max(e.children.length,t.children.length);if(n.length===0)for(let o=0;o<r;o++){const a=e.children[o],l=t.children[o];if(!(!a||!l))for(const c of this.getTextFormattingChangeKeys(a.children,l.children))i(this.getNaturalFormatCategoryFromMarkKey(c))}}return this.buildNaturalFormatChangeDescription(n)}inlineFormatRecordHasLiveMarker(e){return e.spans.some(t=>{const n=this.suggestionEngine.getYTextForSuggestionSpan(t);return n?this.collectOverlappingTextSpans(n,t.start,t.end-t.start).some(i=>i.attributes.suggestionId===e.id&&!!i.attributes.formatChange):!1})}cloneYDoc(e){const t=new S.Doc;return S.applyUpdate(t,S.encodeStateAsUpdate(e)),t}collapseAffectedBlockIds(e,t){const n=Array.from(new Set(Array.from(e).filter(d=>typeof d=="string"&&d.length>0))),i=new Set(n),r=this.getDocument(),o=qe(r),a=qe(t),l=new Map;for(const d of[o,a])for(const{block:g}of d.values())if(g.type==="list")for(const u of g.children)l.set(u.id,g.id);const c=(d,g)=>{let u=Je(d,g);for(;u&&u.type!=="doc";){if(u.id)return u.id;u=Je(d,u.id)}return null};return n.filter(d=>{const g=l.get(d);if(g&&i.has(g))return!1;const u=[o.get(d),a.get(d)];let p=!1;for(const f of u)if(f&&(p=!0,f.containerPath.some(m=>m!==d&&i.has(m))))return!1;if(p)return!0;let h=d;for(;h;){const f=c(r,h)??c(t,h);if(!f)break;if(i.has(f))return!1;h=f}return!0})}collectOverlappingTextSpans(e,t,n){if(n<=0)return[];const i=[],r=t+n,o=Z(e);let a=0;for(const l of o){if(typeof l.insert!="string")continue;const c=a,d=a+l.insert.length,g=Math.max(t,c),u=Math.min(r,d);if(g<u&&i.push({start:g,length:u-g,attributes:{...l.attributes||{}}}),a=d,a>=r)break}return i}normalizeAdjacentManualReplacementOrder(e,t){const n=[];let i=0;for(const h of Z(e)){if(typeof h.insert!="string"||h.insert.length===0){i+=typeof h.insert=="string"?h.insert.length:1;continue}const f=i,m=f+h.insert.length;n.push({start:f,end:m,text:h.insert,attributes:{...h.attributes||{}}}),i=m}const r=n.findIndex(h=>h.start===t&&h.attributes.deletion);if(r<=0)return null;let o=r-1;if(n[o].end!==t||!n[o].attributes.insertion)return null;for(;o>0&&n[o-1].end===n[o].start&&n[o-1].attributes.insertion;)o-=1;let a=r;for(;a+1<n.length&&n[a].end===n[a+1].start&&n[a+1].attributes.deletion;)a+=1;const l=n.slice(o,a+1);if(l.some(h=>!h.attributes.insertion&&!h.attributes.deletion||h.attributes.insertion&&h.attributes.deletion))return null;const c=l.filter(h=>h.attributes.insertion),d=l.filter(h=>h.attributes.deletion);if(c.length===0||d.length===0)return null;const g=l[0].start,u=l[l.length-1].end-g;e.delete(g,u);let p=g;for(const h of[...d,...c])ne(e,p,h.text,h.attributes),p+=h.text.length;return{regionStart:g,insertionLength:c.reduce((h,f)=>h+f.text.length,0),deletionLength:d.reduce((h,f)=>h+f.text.length,0)}}static remapOffsetAcrossReplacementNormalization(e,t){const{regionStart:n,insertionLength:i,deletionLength:r}=t,o=n+i+r;return e<=n||e>o?e:e<=n+i?e+r:e-i}findSingleTableColumnDelta(e,t){if(e.children.length===0||e.children.length!==t.children.length)return null;let n=null,i=null;for(let r=0;r<e.children.length;r++){const o=e.children[r].children,a=t.children[r].children,l=a.length-o.length;if(Math.abs(l)!==1)return null;const c=l>0?"insert":"delete",d=l>0?a:o,g=l>0?o:a;let u=0;for(;u<g.length&&d[u]?.id===g[u]?.id;)u++;for(let p=u;p<g.length;p++)if(d[p+1]?.id!==g[p]?.id)return null;if(n!==null&&n!==c||i!==null&&i!==u)return null;n=c,i=u}return n!==null&&i!==null?{kind:n,index:i}:null}getTrailingCleanupParagraphIdForTopLevelBlock(e,t){const n=e.children.findIndex(r=>r.id===t);if(n===-1||n!==e.children.length-2)return;const i=e.children[n+1];if(!(!i||i.type!=="paragraph"||i.children.some(r=>r.type!=="text"||r.text.length>0)))return i.id}collectStructuralInsertBlockIds(e,t,n=[]){if("id"in e&&typeof e.id=="string"&&"structuralSuggestionKind"in e&&e.structuralSuggestionKind==="insert"&&"structuralSuggestionId"in e&&e.structuralSuggestionId===t&&n.push(e.id),e.type==="doc"&&Array.isArray(e.notes))for(const i of e.notes)this.collectStructuralInsertBlockIds(i,t,n);if(!("children"in e)||!Array.isArray(e.children))return n;for(const i of e.children)i&&typeof i=="object"&&this.collectStructuralInsertBlockIds(i,t,n);return n}replaceAnyBlockById(e,t,n,i){this.beforeOperationSelection=n;const r=this.getDocument();if(!z(r,e))return!1;const o=G(this.ydoc,e);return o?(this.beforeOperationRelativeSelection=H(n,this.ydoc,r),this.transact(()=>{this.replaceBlockByIdWithoutSelection(e,t,o)}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0):!1}isListItemBlockChangeRecord(e){return!!(e.beforeBlock.type==="list"&&e.listItemSuggestion)}applyListItemBlockChangeDecision(e,t,n){const i=z(this.getDocument(),e.blockId);if(!i||i.type!=="list")return!1;const r=this.suggestionEngine.cloneSuggestionSnapshot(i),o=r.children.findIndex(u=>u.structuralSuggestionId===e.id);if(o===-1)return!1;const a=this.suggestionEngine.cloneSuggestionSnapshot(r);if(a.structuralSuggestionRecord)try{JSON.parse(a.structuralSuggestionRecord).id===e.id&&delete a.structuralSuggestionRecord}catch{}const{kind:l,beforeItem:c,afterItem:d}=e.listItemSuggestion;if(l==="insert")t==="accept"?a.children[o]=this.suggestionEngine.cloneSuggestionSnapshot(d??a.children[o]):a.children.splice(o,1);else if(l==="delete")t==="accept"?a.children.splice(o,1):a.children[o]=this.suggestionEngine.cloneSuggestionSnapshot(c??a.children[o]);else{const u=t==="accept"?d??a.children[o]:c;if(!u)return!1;a.children[o]=this.suggestionEngine.cloneSuggestionSnapshot(u)}const g=this.suggestionEngine.runWithoutSuggesting(()=>this.replaceAnyBlockById(e.blockId,a,n,n));return g&&this.suggestionEngine.deleteLiveSuggestion(e.id),g}arePathsEqual(e,t){return!e||!t||e.length!==t.length?!1:e.every((n,i)=>n===t[i])}getParagraphContextForPosition(e,t){const n=t??this.getDocument(),i=this.getBlockContextById(n,e.block);return!i||i.block.type!=="paragraph"?null:{paragraph:i.block,paragraphPath:i.blockPath,topLevelIndex:i.topLevelIndex}}getParagraphOffsetForPosition(e,t){const n=t??this.getDocument(),i=this.getParagraphContextForPosition(e,n);return i?{...i,offset:e.offset}:null}getParagraphTextLength(e){return e.children.reduce((t,n)=>t+(n.type==="text"?n.text.length:0),0)}getCancelableParagraphSplitRecord(e,t){const n=e.structuralSuggestionId;if(!n||n!==t.structuralSuggestionId||e.structuralSuggestionKind!=="split"||t.structuralSuggestionKind!=="split")return null;const i=this.suggestionEngine.getLiveSuggestion(n);if(!i||i.type!=="paragraph-split")return null;const r=new Set([i.blockId,i.insertedBlockId]);return!r.has(e.id)||!r.has(t.id)?null:i}getCancelableParagraphMergeRecord(e,t){const n=e.structuralSuggestionId;if(!n||e.structuralSuggestionKind!=="merge"||!e.structuralSuggestionRole)return null;const i=this.getParagraphTextLength(e);if(!(e.structuralSuggestionRole==="before"&&t===i||e.structuralSuggestionRole==="after"&&t===0))return null;const r=this.suggestionEngine.getLiveSuggestion(n);return!r||r.type!=="paragraph-merge"||r.firstBlockId!==e.id&&r.secondBlockId!==e.id?null:r}isPlainEmptyParagraph(e){return!e.structuralSuggestionId&&!e.structuralSuggestionKind&&this.getParagraphTextLength(e)===0}isInsertedParagraph(e){return e.structuralSuggestionKind==="insert"&&typeof e.structuralSuggestionId=="string"&&e.structuralSuggestionId.length>0}cursorFromParagraphOffset(e,t,n){let i=0;for(const o of t.children)o.type==="text"&&(i+=o.text.length);const r=Math.min(Math.max(0,n),i);return{block:t.id,offset:r}}arePositionsInSameEditableBlock(e,t,n){return t.block===n.block}getYContentFragment(){return zt(this.ydoc)}getYChromeFragment(){if(!this.ydoc)throw new Error("No Y.Doc");return this.ydoc.getXmlFragment("chrome")}getYNotesFragment(){if(!this.ydoc)throw new Error("No Y.Doc");return this.ydoc.getXmlFragment("notes")}getYBlockContext(e,t){if(!e.length)return null;const n=this.getYContentFragment(),i=e[0];if(i<0||i>=n.length)return null;const r=n.get(i);return r instanceof S.XmlElement?{parent:n,index:i,yBlock:r}:null}getYParagraphContext(e,t){const n=this.getYBlockContext(e,t);if(!n)return null;for(let i=0;i<n.yBlock.length;i++){const r=n.yBlock.get(i);if(r instanceof S.XmlText)return{yBlock:n.yBlock,yText:r}}return null}getEmptyTextMarksForParagraph(e){const t=this.getYBlockContext(e);if(!t)return;const n=t.yBlock.getAttribute("_emptyTextMarks");if(n)try{return typeof n=="string"?JSON.parse(n):n}catch(i){console.warn("Failed to parse _emptyTextMarks",i);return}}getEmptyTextMarksForBlockId(e){const t=K(this.ydoc,e);if(!t)return;const n=t.getAttribute("_emptyTextMarks");if(n)try{return typeof n=="string"?JSON.parse(n):n}catch(i){console.warn("Failed to parse _emptyTextMarks",i);return}}resolveEditableContext(e,t){const n=t??this.getDocument(),i=this.getBlockContextById(n,e.block);if(!i)return null;const r={block:i.block,blockPath:i.blockPath},o=G(this.ydoc,i.block.id),a=o?{parent:o.yParent,index:o.index,yBlock:o.yBlock}:null;return{doc:n,editable:r,yContext:a}}dispose(){this.disposed||(this.disposed=!0,this.ydoc.off("update",this.handleYDocUpdate),this.strandedCheck&&clearTimeout(this.strandedCheck),this.strandedCheck=null,this.deferredIdentityRepair&&clearTimeout(this.deferredIdentityRepair),this.deferredIdentityRepair=null,this.detachedSuggestionStore.destroy(),this.undoManager.destroy(),this.pendingUpdate=null,this.onDocumentChange=()=>{},this.onTitleChange=void 0,this.remoteOrigins.clear(),this.trackedUndoOrigins.clear(),this.toolCallHistory.clear(),this.invalidateDerivedDocumentState())}setSelectionAfterOperation(e){this.afterOperationSelection=e,this.updateAfterOperationRelativeSelection(this.getDocument())}updateAfterOperationRelativeSelection(e){const t=this.afterOperationSelection;this.afterOperationRelativeSelection=t?H(t,this.ydoc,e):null}getDocument(){return this.cachedDoc||(this.cachedDoc=this.incrementalRefreshPending?He(this.ydoc):he(this.ydoc),this.incrementalRefreshPending=!1),this.cachedDoc}mergeAdjacentListItemsSnapshot(e,t,n){if(t<0||t>=e.children.length-1)return null;const i=this.suggestionEngine.cloneSuggestionSnapshot(e),r=i.children[t],o=i.children[t+1];if(!r||!o)return null;const a=this.suggestionEngine.cloneSuggestionSnapshot(r.children),l=this.suggestionEngine.cloneSuggestionSnapshot(o.children),c=a[a.length-1],d=l[0];return c?.type==="text"&&d?.type==="text"&&JSON.stringify(c.marks||{})===JSON.stringify(d.marks||{})&&(c.text+=d.text,l.shift()),r.children=[...a,...l],n&&(r.structuralSuggestionId=n,r.structuralSuggestionKind="change",r.structuralSuggestionLabel="Join",delete r.structuralSuggestionRole),i.children.splice(t+1,1),i}collectInlineFormattingRanges(e,t,n,i){const r=[],o=Ie(i,e,t)<=0,a=o?e:t,l=o?t:e;if(a.block===l.block)return this.collectSingleBlockFormattingRange(a,l,i);{const u=fs(i,a.block)?.block??(i.notes??[]).find(p=>p.children.some(h=>h.id===a.block));if(u){const p=u.children.map(m=>m.id),h=p.indexOf(a.block),f=p.indexOf(l.block);if(h!==-1&&f!==-1){const[m,y]=h<=f?[h,f]:[f,h],b=[];for(let k=m;k<=y;k++){const I=u.children[k];if(!I.id)continue;const v=k===h?a:{block:I.id,offset:0},x=k===f?l:{block:I.id,offset:Number.MAX_SAFE_INTEGER};b.push(...this.collectSingleBlockFormattingRange({block:I.id,offset:k===h?v.offset:0},{block:I.id,offset:k===f?x.offset:Number.MAX_SAFE_INTEGER},i))}return b}}}const c=ht(i,a.block),d=ht(i,l.block);if(!c||!d){if(a.block===l.block)return this.collectSingleBlockFormattingRange(a,l,i);const u=this.collectSingleBlockFormattingRange(a,a,i),p=this.collectSingleBlockFormattingRange(l,l,i);return[...u,...p]}let g=!0;for(const{block:u,path:p}of ks(i)){const h=Pt(p,c),f=Pt(p,d);if(h<0)continue;if(f>0)break;const m=f===0,y=G(this.ydoc,u.id);if(!y){g=!1;continue}const b=y.yBlock;if(u.type==="paragraph"){const k=ae(b);if(!k){g=!1;continue}let I=0,v=k.length;g&&a.block===u.id&&(I=a.offset),m&&l.block===u.id&&(v=l.offset),I=bi(I,0,k.length),v=bi(v,0,k.length);const x=Math.min(I,v),A=Math.max(I,v);A>x&&r.push({yText:k,start:x,end:A,blockId:u.id}),g=!1;continue}if(u.type==="list"){const k=u,I=[];for(let E=0;E<b.length;E++){const P=b.get(E);P instanceof S.XmlElement&&P.nodeName==="list-item"&&I.push(P)}const v=Math.min(k.children.length,I.length);if(v===0){g=!1;continue}let x=0,A=v-1,C=0,F=Number.MAX_SAFE_INTEGER;if(g&&a.block===u.id){const E=this.listOperations.getListCursorInfo(k,a);E&&(x=Math.min(E.itemIndex,v-1),C=E.offsetInItem)}if(m&&l.block===u.id){const E=this.listOperations.getListCursorInfo(k,l);E&&(A=Math.min(E.itemIndex,v-1),F=E.offsetInItem)}for(let E=x;E<=A;E++){const P=I[E];if(!P)continue;const B=ae(P);if(!B||B.length===0)continue;let w=0,T=B.length;E===x&&(w=Math.min(C,B.length)),E===A&&(T=Math.min(F,B.length)),T>w&&r.push({yText:B,start:w,end:T})}g=!1}}return r}collectSingleBlockFormattingRange(e,t,n){const i=[],r=z(n,e.block);if(!r)return i;const o=G(this.ydoc,e.block);if(!o)return i;const a=o.yBlock;if(r.type==="paragraph"){const l=ae(a);if(!l)return i;let c=e.offset,d=t.offset;c=bi(c,0,l.length),d=bi(d,0,l.length);const g=Math.min(c,d),u=Math.max(c,d);u>g&&i.push({yText:l,start:g,end:u,blockId:r.id})}else if(r.type==="list"){const l=r,c=[];for(let y=0;y<a.length;y++){const b=a.get(y);b instanceof S.XmlElement&&b.nodeName==="list-item"&&c.push(b)}const d=Math.min(l.children.length,c.length);if(d===0)return i;const g=this.listOperations.getListCursorInfo(l,e),u=this.listOperations.getListCursorInfo(l,t);if(!g||!u)return i;let p=Math.min(g.itemIndex,d-1),h=Math.min(u.itemIndex,d-1),f=g.offsetInItem,m=u.offsetInItem;p>h&&([p,h]=[h,p],[f,m]=[m,f]);for(let y=p;y<=h;y++){const b=c[y];if(!b)continue;const k=ae(b);if(!k||k.length===0)continue;let I=0,v=k.length;y===p&&(I=Math.min(f,k.length)),y===h&&(v=Math.min(m,k.length)),v>I&&i.push({yText:k,start:I,end:v,blockId:r.id,itemIndex:y})}}return i}collectParagraphBlockIdsInRange(e,t,n){const i=[],r=new Set,o=u=>{const p=z(n,u);p?.type==="paragraph"&&p.id&&!r.has(p.id)&&(r.add(p.id),i.push(p.id))},a=Ie(n,e,t)<=0,l=a?e:t,c=a?t:e,d=ht(n,l.block),g=ht(n,c.block);if(!d||!g)return o(l.block),o(c.block),i;for(const{block:u,path:p}of ks(n)){const h=Pt(p,d),f=Pt(p,g);if(!(h<0)){if(f>0)break;u.type==="paragraph"&&u.id&&!r.has(u.id)&&(r.add(u.id),i.push(u.id))}}return i.length===0&&o(l.block),i}clearFormattingEmptyMarksAtPosition(e,t){const n=z(t,e.block);if(!n)return!1;if(n.type==="paragraph"){const c=G(this.ydoc,n.id);return c?rl(c.yBlock):!1}if(n.type!=="list")return!1;const i=n;this.suggestingMode&&this.suggestionEngine.cloneSuggestionSnapshot(i),this.suggestingMode&&ce();const r=G(this.ydoc,n.id);if(!r)return!1;const o=this.listOperations.getListCursorInfo(i,e);if(!o)return!1;const a=[];for(let c=0;c<r.yBlock.length;c++){const d=r.yBlock.get(c);d instanceof S.XmlElement&&d.nodeName==="list-item"&&a.push(d)}const l=a[o.itemIndex];return l?rl(l):!1}updateEmptyTextMarksAtPosition(e,t,n,i){const r=z(i,e.block);if(!r)return!1;if(r.type==="paragraph"){const g=G(this.ydoc,r.id);if(!g)return!1;const u=r.children.some(p=>p.type==="text"&&p.text.length>0);return sl(g.yBlock,t,n,!u)}if(r.type!=="list")return!1;const o=r,a=G(this.ydoc,r.id);if(!a)return!1;const l=this.listOperations.getListCursorInfo(o,e);if(!l)return!1;const c=[];for(let g=0;g<a.yBlock.length;g++){const u=a.yBlock.get(g);u instanceof S.XmlElement&&u.nodeName==="list-item"&&c.push(u)}const d=c[l.itemIndex];return d?sl(d,t,n,l.itemLength===0):!1}updateBackgroundColorEmptyMarksAtPosition(e,t,n){return this.updateEmptyTextMarksAtPosition(e,"backgroundColor",t,n)}insertTextInCodeBlock(e,t,n,i){this.beforeOperationSelection=n;const r=this.getDocument(),o=z(r,e.block);if(!bn(o))return!1;const a=K(this.ydoc,e.block);if(!a)return!1;let l=null;for(let u=0;u<a.length;u++){const p=a.get(u);if(p instanceof S.XmlText){l=p;break}}if(!l)return!1;const c=Math.min(e.offset,l.length);this.transact(()=>{l.insert(c,t)});const d={block:e.block,offset:c+t.length},g={anchor:d,focus:d};return this.setSelectionAfterOperation(g),this.afterOperationRelativeSelection=H(g,this.ydoc,this.getDocument()),!0}deleteTextInCodeBlock(e,t,n,i){this.beforeOperationSelection=n;const r=this.getDocument();this.beforeOperationRelativeSelection=H(n,this.ydoc,r);const o=z(r,e.block);if(!bn(o))return!1;const a=K(this.ydoc,e.block);if(!a)return!1;let l=null;for(let g=0;g<a.length;g++){const u=a.get(g);if(u instanceof S.XmlText){l=u;break}}if(!l)return!1;const c=l.length-e.offset,d=Math.min(t,c);return this.transact(()=>{l.delete(e.offset,d)}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0}getYDoc(){return this.ydoc}getAfterOperationSelection(){return this.afterOperationSelection}captureSelectionBeforeOperation(e){if(!e){this.beforeOperationSelection=null,this.beforeOperationRelativeSelection=null;return}const t=i=>i?{block:i.block,offset:i.offset}:null;this.beforeOperationSelection={anchor:t(e.anchor),focus:t(e.focus)};const n=this.getDocument();this.beforeOperationRelativeSelection=H(e,this.ydoc,n)}setAfterOperationSelectionFromEditor(e){if(e){const n=i=>i?{block:i.block,offset:i.offset}:null;this.setSelectionAfterOperation({anchor:n(e.anchor),focus:n(e.focus)})}else this.setSelectionAfterOperation(null);if(!e){this.afterOperationRelativeSelection=null;return}const t=this.getDocument();this.afterOperationRelativeSelection=H(e,this.ydoc,t)}ensureParagraphIndentStorageUsesUnits(){const e=this.ydoc.getMap("metadata");if(e.get(Ge.paragraphIndentStorageVersion)===wi)return;const t=this.ydoc.getXmlFragment("content");if(t.length===0&&Tt(this.ydoc))return;const n=e.get(Ge.indentStepPx),i=Ve({indentStepPx:typeof n=="number"?n:void 0}).indentStepPx;this.ydoc.transact(()=>{t.length>0&&al(t,r=>{const o=bs(ol(ee(r,"leftIndent")),{indentStepPx:i,storedAsUnits:!1}),a=bs(ol(ee(r,"firstLineIndent")),{indentStepPx:i,storedAsUnits:!1,firstLine:!0});o===void 0?J(r,"leftIndent"):r.setAttribute("leftIndent",String(o)),a===void 0?J(r,"firstLineIndent"):r.setAttribute("firstLineIndent",String(a))}),e.set(Ge.paragraphIndentStorageVersion,wi)},"indent-storage-migration")}setTitle(e){const t=wu(e);this.transact(()=>{this.ydoc.getMap("metadata").set("title",t)}),this.onTitleChange&&this.onTitleChange(t)}setNotes(e){const t=typeof e=="string"?e:String(e??"");this.transact(()=>{const n=this.ydoc.getMap("metadata");t.length===0?n.delete("notes"):n.set("notes",t)})}getDocumentNotes(){const e=this.ydoc.getMap("metadata").get("notes");return typeof e=="string"?e:""}updateSectionBreakLayout(e,t){const n=this.getYContentFragment();let i=null;for(const r of n.toArray())if(r instanceof S.XmlElement&&r.nodeName==="section-break"&&r.getAttribute("id")===e){i=r;break}return i?(this.transact(()=>{i.setAttribute("layout",JSON.stringify(t))}),!0):!1}pinInheritedPageNumbering(e){const t=Ve(this.getPageLayoutSettings()),n=this.getDocument().children.filter(o=>o.type==="section-break"),i=e.pageNumberFormat!==void 0&&e.pageNumberFormat!==t.pageNumberFormat,r=e.pageNumberStart!==void 0&&e.pageNumberStart!==t.pageNumberStart;n.forEach((o,a)=>{const l=o.layout,c={...i&&l?.pageNumberFormat===void 0?{pageNumberFormat:t.pageNumberFormat}:{},...r&&a===0&&l?.pageNumberStart===void 0?{pageNumberStart:t.pageNumberStart}:{}};Object.keys(c).length>0&&this.updateSectionBreakLayout(o.id,{...l??{},...c})})}applyLayoutToAllSectionBreaks(e){const t=this.getYContentFragment();this.transact(()=>{for(const n of t.toArray())if(n instanceof S.XmlElement&&n.nodeName==="section-break"){let i={};try{const o=n.getAttribute("layout");i=typeof o=="string"?JSON.parse(o):{}}catch{i={}}const r={...i.oxmlSectPr!==void 0?{oxmlSectPr:i.oxmlSectPr}:{},...i.pageBorders!==void 0?{pageBorders:i.pageBorders}:{},...i.pageNumberStart!==void 0?{pageNumberStart:i.pageNumberStart}:{},...i.pageNumberFormat!==void 0?{pageNumberFormat:i.pageNumberFormat}:{}};n.setAttribute("layout",JSON.stringify(ps(r,e)??e))}})}applySetHeaderFooterAction(e){const t=e.side==="footer"?"footer":"header",n=e.slot==="first"||e.slot==="even"?e.slot:"default";return{changed:Eg(this.kernel,t,n,{left:e.left,center:e.center,right:e.right},e.clear===!0),side:t,slot:n}}applySetPageLayoutAction(e){const t=e.clearPageBorders===!0?null:Dl(e.pageBorders);if(e.pageBorders!==void 0&&t===void 0)throw new Error("Invalid pageBorders: use supported side styles, #RRGGBB colors, widthPt 0.25–12 and spacePt 0–31, or null to remove.");const n=this.getPageLayoutSettings(),i=this.getDocument().children.filter(B=>B.type==="section-break"),r=i.length+1,o=typeof e.sectionIndex=="number"&&Number.isInteger(e.sectionIndex)&&e.sectionIndex>=1&&e.sectionIndex<=r?e.sectionIndex:void 0;if(e.sectionIndex!=null&&o===void 0){const B=typeof e.sectionIndex=="number"&&Number.isInteger(e.sectionIndex)?`sectionIndex ${e.sectionIndex} is out of range: document has ${r} section${r===1?"":"s"}`:`sectionIndex must be an integer between 1 and ${r}, got ${JSON.stringify(e.sectionIndex)}`;return{settings:n,pageless:this.getPagelessMode(),error:B}}if(e.pageNumberFormat!=null&&!Bi(e.pageNumberFormat))return{settings:n,pageless:this.getPagelessMode(),error:`pageNumberFormat must be one of ${_l.join(", ")}, got ${JSON.stringify(e.pageNumberFormat)}`};const a=o?i[o-1]:void 0,l=a?ls(n,a.layout):n,c=this.getPagelessMode(),d=jl(e.preset)?Xl(e.preset):void 0,g={...d?.pageLayout??{}},u={...l,...d?.pageLayout??{}};Ul(e.pageSize)&&(u.pageSize=e.pageSize,g.pageSize=e.pageSize),(e.orientation==="portrait"||e.orientation==="landscape")&&(u.orientation=e.orientation,g.orientation=e.orientation);const p=Ue(e.margin);p!==void 0&&(u.marginTopPx=p,u.marginRightPx=p,u.marginBottomPx=p,u.marginLeftPx=p,g.marginTopPx=p,g.marginRightPx=p,g.marginBottomPx=p,g.marginLeftPx=p);const h=Ue(e.marginTop);h!==void 0&&(u.marginTopPx=h,g.marginTopPx=h);const f=Ue(e.marginRight);f!==void 0&&(u.marginRightPx=f,g.marginRightPx=f);const m=Ue(e.marginBottom);m!==void 0&&(u.marginBottomPx=m,g.marginBottomPx=m);const y=Ue(e.marginLeft);y!==void 0&&(u.marginLeftPx=y,g.marginLeftPx=y);const b=Ue(e.indentStep);b!==void 0&&(u.indentStepPx=b,g.indentStepPx=b);const k=Ue(e.blockSpacing);k!==void 0&&(u.blockSpacingPx=k,g.blockSpacingPx=k),zl(e.columnCount)&&(u.columnCount=e.columnCount,g.columnCount=e.columnCount);const I=Ue(e.columnGap);if(I!==void 0){const B=Math.max(0,Gl(I));u.columnGapTwips=B,g.columnGapTwips=B}if((e.noteMode==="footnotes"||e.noteMode==="endnotes")&&this.convertAllNoteKinds(e.noteMode==="endnotes"?"endnote":"footnote"),typeof e.showPageNumbers=="boolean"||Mi(e.pageNumberPosition)){const B=Mi(e.pageNumberPosition)?e.pageNumberPosition:this.ydoc.getMap("metadata").get(Ge.pageNumberPosition)??"bottom-right",w=typeof e.showPageNumbers=="boolean"?e.showPageNumbers:!0;this.setPageNumberSlot(w,B)}if(typeof e.showPageNumbers=="boolean"&&(u.showPageNumbers=!1),Mi(e.pageNumberPosition)&&(u.pageNumberPosition=e.pageNumberPosition),typeof e.pageNumberStart=="number"?(u.pageNumberStart=e.pageNumberStart,g.pageNumberStart=e.pageNumberStart):e.pageNumberRestart===!0&&(g.pageNumberStart=a?.layout?.pageNumberStart??1),Bi(e.pageNumberFormat)&&(u.pageNumberFormat=e.pageNumberFormat,g.pageNumberFormat=e.pageNumberFormat),!a){const B=o===r&&r>1;e.pageNumberRestart===!0||B&&typeof e.pageNumberStart=="number"&&e.pageNumberRestart!==!1?u.pageNumberRestart=!0:e.pageNumberRestart===!1&&delete u.pageNumberRestart}if((e.pageBorders!==void 0||e.clearPageBorders===!0)&&(u.pageBorders=t,g.pageBorders=t),e.lineNumbering!==void 0){const B=Hl(e.lineNumbering);B?u.lineNumbering=B:delete u.lineNumbering,g.lineNumbering=Wl(B)??"",B&&e.pleadingGrid===void 0&&(delete u.pleadingGrid,g.pleadingGrid="")}if(e.pleadingGrid!==void 0){const B=Yl(e.pleadingGrid);B?u.pleadingGrid=ms(B):delete u.pleadingGrid,g.pleadingGrid=ms(B)??"",B&&(delete u.lineNumbering,g.lineNumbering="")}const v=Ue(e.pageWidth),x=Ue(e.pageHeight);if(v!==void 0&&x!==void 0){const B=ql(v,x);B&&(u.pageSize=B.pageSize,u.orientation=B.orientation,g.pageSize=B.pageSize,g.orientation=B.orientation)}if(e.watermark!==void 0){const B=Bs(e.watermark);this.transact(()=>{const w=this.ydoc.getMap("metadata");B?w.set("watermark",B):w.delete("watermark")})}const A=Ve(u),C=typeof e.pageless=="boolean"?e.pageless:d?.pageless??c,F=e.pageNumberRestart===!1&&typeof e.pageNumberStart!="number",E=B=>{const w=ps(B,g)??{...g};if(!F)return w;const{pageNumberStart:T,...N}=w;return N},P=Object.keys(g).length>0||F;if(o&&a)P&&this.updateSectionBreakLayout(a.id,E(a.layout));else if(o===r){if(e.pageBorders!==void 0||e.clearPageBorders===!0)for(const B of i)B.layout?.pageBorders!==void 0||/<w:pgBorders\b/.test(B.layout?.oxmlSectPr??"")||this.updateSectionBreakLayout(B.id,{...B.layout,pageBorders:n.pageBorders??null});this.pinInheritedPageNumbering({...Bi(e.pageNumberFormat)?{pageNumberFormat:e.pageNumberFormat}:{},...typeof e.pageNumberStart=="number"?{pageNumberStart:e.pageNumberStart}:{}}),this.setPageLayoutSettings(A)}else{if(P)for(const B of i)this.updateSectionBreakLayout(B.id,E(B.layout));this.setPageLayoutSettings(A)}return this.setPagelessMode(C),{settings:A,pageless:C}}setPagelessMode(e){this.transact(()=>{this.ydoc.getMap("metadata").set("pageless",e)})}getPagelessMode(){return!!this.ydoc.getMap("metadata").get("pageless")}convertParagraphToList(e,t,n){return this.listOperations.convertParagraphToList(e,t,n)}convertParagraphToListById(e,t,n){return this.listOperations.convertParagraphToListById(e,t,n)}getListItemPlainText(e){return this.listOperations.getListItemPlainText(e)}convertParagraphRangeToList(e,t,n){return this.listOperations.convertParagraphRangeToList(e,t,n)}updateListVariant(e,t,n){return this.listOperations.updateListVariant(e,t,n)}convertListToParagraphById(e){return this.listOperations.convertListToParagraphById(e)}updateListVariantById(e,t,n){return this.listOperations.updateListVariantById(e,t,n)}continueListFromPrevious(e){return this.listOperations.continueListFromPrevious(e)}restartListNumberingAt(e,t,n){return this.listOperations.restartListNumberingAt(e,t,n)}splitListItem(e,t){return this.listOperations.splitListItem(e,t)}insertTextInListItem(e,t,n,i){return this.listOperations.insertTextInListItem(e,t,n,i)}insertTextInList(e,t,n,i){return this.listOperations.insertTextInList(e,t,n,i)}insertFormattedTextInList(e,t,n,i,r){return this.listOperations.insertFormattedTextInList(e,t,n,i,r)}getListCursorInfo(e,t){return this.listOperations.getListCursorInfo(e,t)}getListItemTextLength(e){return this.listOperations.getListItemTextLength(e)}setListItemIndent(e,t,n,i,r){return this.listOperations.setListItemIndent(e,t,n,i,r)}setSuggestingMode(e){this.suggestionEngine.setSuggestingMode(e)}isSuggestingMode(){return this.suggestionEngine.isSuggestingMode()}getLiveSuggestionStore(){return this.suggestionEngine.getLiveSuggestionStore()}setDefaultSuggestionAuthorName(e){this.suggestionEngine.setDefaultSuggestionAuthorName(e)}withSuggestionMetadata(e,t){return this.suggestionEngine.withSuggestionMetadata(e,t)}saveLiveSuggestion(e){this.suggestionEngine.saveLiveSuggestion(e)}backfillLiveSuggestionTreeRecords(){this.suggestionEngine.backfillLiveSuggestionTreeRecords()}getLiveSuggestion(e){return this.suggestionEngine.getLiveSuggestion(e)}getInlineSuggestionMetadataFromDocument(e){return this.suggestionEngine.getInlineSuggestionMetadataFromDocument(e)}getLiveSuggestionTooltipDescription(e){return this.suggestionEngine.getLiveSuggestionTooltipDescription(e)}deleteLiveSuggestion(e){this.suggestionEngine.deleteLiveSuggestion(e)}getLiveSuggestionIds(){return this.suggestionEngine.getLiveSuggestionIds()}completeInternalTextMove(e,t,n,i){const r=new Set(e),o=new Set(t),a=[],l=[],c=[],d=h=>{if(h instanceof S.XmlText){let f=0;for(const m of Z(h)){const y=typeof m.insert=="string"?m.insert.length:1,b=m.attributes??{};b.deletion&&r.has(b.suggestionId)?a.push({text:h,start:f,length:y,attributes:b}):b.insertion&&o.has(b.suggestionId)&&l.push({text:h,start:f,length:y,attributes:b}),f+=y}}if(h instanceof S.XmlFragment||h instanceof S.XmlElement){h instanceof S.XmlElement&&(r.has(h.getAttribute("structuralSuggestionId"))||o.has(h.getAttribute("structuralSuggestionId")))&&c.push(h);for(let f=0;f<h.length;f++){const m=h.get(f);m instanceof S.AbstractType&&d(m)}}};if(d(this.getYContentFragment()),a.length===0||l.length===0)return!1;const g=1e7+Math.floor(Math.random()*9e7),u=`reviseMove-${n}`,p=(h,f,m)=>{const y=JSON.stringify({version:1,...i?.wholeBlocks?{wholeBlocks:!0}:{},name:u,role:f,rangeId:`${g}${m}`,wrapperId:`${g+1}${m}`,fallbackSuggestionId:h[0].attributes.suggestionId,...h[0].attributes.suggestionAuthorName?{rangeAuthor:h[0].attributes.suggestionAuthorName}:{},...typeof h[0].attributes.suggestionCreatedAt=="number"?{rangeCreatedAt:h[0].attributes.suggestionCreatedAt}:{}});for(const b of h)ie(b.text,b.start,b.length,{suggestionId:n,suggestionLabel:"Move",docxMove:y})};return this.transact(()=>{p(a,"from","1"),p(l,"to","2");for(const h of c)h.setAttribute("structuralSuggestionId",n)}),!0}recordStampedSuggestionIds(e){return this.suggestionEngine.recordStampedSuggestionIds(e)}runTrackedMovePaste(e,t,n,i){return this.runWithUndoGroup("tracked-move-paste",()=>{const{result:r,stamped:o}=this.recordStampedSuggestionIds(n);return i(r)&&this.completeInternalTextMove(t,[...o.insertionIds,...o.structuralInsertIds,e],e),r})}getLiveSuggestionIdsBySource(e){return this.suggestionEngine.getLiveSuggestionIdsBySource(e)}getLiveSuggestionIdsByCommentThread(e){return this.suggestionEngine.getLiveSuggestionIdsByCommentThread(e)}getLiveSuggestionAuthorName(e){return this.suggestionEngine.getLiveSuggestionAuthorName(e)}getLiveSuggestionKind(e){return this.suggestionEngine.getLiveSuggestionKind(e)}getLiveSuggestionIdsForBlock(e){return this.suggestionEngine.getLiveSuggestionIdsForBlock(e)}canResolveLiveSuggestion(e){return this.suggestionEngine.canResolveLiveSuggestion(e)}getUnresolvableLiveSuggestionRecords(){return this.suggestionEngine.getUnresolvableLiveSuggestionRecords()}takeLastPrunedUnresolvableLiveSuggestions(){return this.suggestionEngine.takeLastPrunedUnresolvableLiveSuggestions()}getDocumentWithAcceptedSuggestions(){return this.suggestionEngine.getDocumentWithAcceptedSuggestions()}mapAcceptedSuggestionRangeToLiveRange(e,t,n){return this.suggestionEngine.mapAcceptedSuggestionRangeToLiveRange(e,t,n)}getDocumentWithRejectedSuggestions(){return this.suggestionEngine.getDocumentWithRejectedSuggestions()}sanitizeBlocksForClipboard(e){return e.map(t=>this.suggestionEngine.sanitizePreviewBlock(t))}getSelectionInRejectedSuggestionProjection(e){return this.suggestionEngine.getSelectionInRejectedSuggestionProjection(e)}static materializeAcceptedSuggestions(e){const t=i=>{if(!i||typeof i!="object")return!1;if(Array.isArray(i))return i.some(t);const r=i;return typeof r.suggestionId=="string"&&r.suggestionId||typeof r.structuralSuggestionId=="string"&&r.structuralSuggestionId||r.marks&&typeof r.marks.suggestionId=="string"&&r.marks.suggestionId?!0:t(r.children)};if(!e.children.some(t))return e;const n=Pi(e);try{const i=lt.createSuggestionProjectionFromYDoc(n,"accept");try{return{...e,children:i.doc.children}}finally{i.ydoc.destroy()}}finally{n.destroy()}}static createSuggestionProjectionFromYDoc(e,t,n){const i=new S.Doc;S.applyUpdate(i,S.encodeStateAsUpdate(e));const r=new lt(he(i),()=>{},void 0,i,"live-suggestion-projection",!0,new rn,{canRepairIdentity:()=>!1}),o=n?Array.from(new Set(n.filter(a=>typeof a=="string"&&a.length>0))):r.getLiveSuggestionIds();try{return t==="accept"?r.suggestionEngine.applyLiveSuggestionDecisionInternal(o,"accept"):r.suggestionEngine.applyLiveSuggestionDecisionInternal(o,"reject"),e.getXmlFragment("notes").length>0&&r.reconcileFootnotes(),{ydoc:i,doc:r.getDocument()}}finally{r.dispose()}}decideLiveSuggestions(e){return this.suggestionEngine.decideLiveSuggestions(e)}acceptLiveSuggestions(e){return this.suggestionEngine.acceptLiveSuggestions(e)}acceptLiveSuggestionsBySource(e){return this.suggestionEngine.acceptLiveSuggestionsBySource(e)}acceptLiveSuggestionsByAuthor(e){return this.suggestionEngine.acceptLiveSuggestionsByAuthor(e)}rejectLiveSuggestionsByAuthor(e){return this.suggestionEngine.rejectLiveSuggestionsByAuthor(e)}acceptLiveSuggestionsByKind(e){return this.suggestionEngine.acceptLiveSuggestionsByKind(e)}rejectLiveSuggestionsByKind(e){return this.suggestionEngine.rejectLiveSuggestionsByKind(e)}rejectLiveSuggestions(e){return this.suggestionEngine.rejectLiveSuggestions(e)}rejectLiveSuggestionsBySource(e){return this.suggestionEngine.rejectLiveSuggestionsBySource(e)}setElementStructuralSuggestion(e,t,n,i,r){this.suggestionEngine.setElementStructuralSuggestion(e,t,n,i,r)}setDiffSuggestionAttributes(e,t,n){this.suggestionEngine.setDiffSuggestionAttributes(e,t,n)}acceptLiveSuggestion(e){return this.suggestionEngine.acceptLiveSuggestion(e)}rejectLiveSuggestion(e){return this.suggestionEngine.rejectLiveSuggestion(e)}applyBridgeBlockChangeSuggestion(e){return this.suggestionEngine.applyBridgeBlockChangeSuggestion(e)}resetToolCallHistory(){return this.suggestionEngine.resetToolCallHistory()}setToolCallHistory(e){return this.suggestionEngine.setToolCallHistory(e)}getDetachedSuggestionStore(){return this.suggestionEngine.getDetachedSuggestionStore()}setDetachedSuggestionConversation(e,t){this.suggestionEngine.setDetachedSuggestionConversation(e,t)}clearLegacyDetachedSuggestionState(){this.suggestionEngine.clearLegacyDetachedSuggestionState()}migrateLegacyDetachedSuggestionsToLiveSuggestions(e){return this.suggestionEngine.migrateLegacyDetachedSuggestionsToLiveSuggestions(e)}get kernel(){return this.cachedKernel||(this.cachedKernel={ydoc:this.ydoc,transact:e=>this.transact(e),getYContentFragment:()=>this.getYContentFragment(),getYChromeFragment:()=>this.getYChromeFragment(),getYNotesFragment:()=>this.getYNotesFragment(),blockToYjsElement:e=>this.blockToYjsElement(e),getDocument:()=>this.getDocument(),insertTextNodes:(e,t,n)=>this.insertTextNodes(e,t,n),suggestions:{isSuggesting:()=>this.suggestingMode,buildInlineMetadataMarks:(e,t,n)=>this.suggestionEngine.buildInlineSuggestionMetadataMarks(e,t,n),setElementStructuralSuggestion:(e,t,n,i,r)=>this.suggestionEngine.setElementStructuralSuggestion(e,t,n,i,r)}}),this.cachedKernel}setHeadersAndFooters(e,t){ai(this.kernel,e,t)}ensureHeaderFooterBlock(e,t){return da(this.kernel,e,t)}migrateLegacyHeaderFooterMetadata(){Cg(this.kernel)}migrateNotesOutOfContent(){Hg(this.kernel)}migrateChromeOutOfContent(){Tg(this.kernel)}getHeadersAndFooters(){return Sr(this.kernel)}setSectionHeadersAndFooters(e,t,n){Ag(this.kernel,e,t,n)}getSectionHeadersAndFooters(e){return wg(this.kernel,e)}setPageNumberSlot(e,t="bottom-right"){Pg(this.kernel,e,t)}migrateLegacyPageNumbers(){Bg(this.kernel)}setPageLayoutSettings(e){this.ensureParagraphIndentStorageUsesUnits(),this.transact(()=>{Jl(this.ydoc.getMap("metadata"),e)})}setWatermark(e){const t=Bs(e);this.transact(()=>{const n=this.ydoc.getMap("metadata");t?n.set("watermark",t):n.delete("watermark")})}getWatermarkRaw(){const e=this.ydoc.getMap("metadata").get("watermark");return typeof e=="string"&&e.trim()!==""?e:void 0}getPageLayoutSettings(){return rs(this.ydoc.getMap("metadata"))??Ve(void 0)}getIndentStepPx(){return this.getPageLayoutSettings().indentStepPx??0}getTitle(){return this.ydoc.getMap("metadata").get("title")}transact(e){return this.assertObserversNotStranded(),this.incrementalRefreshPending=!1,this.cachedDoc=null,this.invalidateDerivedDocumentState(),this.ydoc.transact(e,this.origin)}assertObserversNotStranded(){if(this.strandedObservers)throw new Error("The editor lost sync with the document. Reload the page to continue editing.");this.hasQueuedCleanupsOutsideTransaction()&&!this.strandedCheck&&(this.strandedCheck=setTimeout(()=>{this.strandedCheck=null,!(this.disposed||!this.hasQueuedCleanupsOutsideTransaction())&&(this.strandedObservers=!0,br(new Error(`Refusing further writes: ${this.ydoc._transactionCleanups.length} stranded transaction cleanups`),"transact"))},0))}hasQueuedCleanupsOutsideTransaction(){const e=this.ydoc;return e._transaction===null&&e._transactionCleanups.length>0}scheduleDeferredIdentityRepair(){this.deferredIdentityRepair||(this.deferredIdentityRepair=setTimeout(()=>{this.deferredIdentityRepair=null,!(this.disposed||!this.canRepairIdentity())&&this.repairDocumentIdentity()&&this.onDocumentChange(this.getDocument(),{origin:"local"})},lt.DEFERRED_IDENTITY_REPAIR_MS))}repairDocumentIdentity(e,t){const n=e!==void 0&&t===this.undoManager,i=this.ydoc.clientID,r=e?.beforeState.get(i)??0,o=n?c=>{const d=c._item?.id;return d!==void 0&&d.client===i&&d.clock>=r}:void 0,a=Kl(this.ydoc,{transaction:e,shouldDrop:o});if(n&&a.droppedIds.length>0){const c=new Set(a.droppedIds),d=this.suggestionEngine.getLiveSuggestionStore(),g=[];for(const[u,p]of d._map){if(p.deleted||p.id.client!==i||p.id.clock<r)continue;const h=d.get(u);h&&this.suggestionEngine.liveSuggestionRecordTouchesAnyBlock(h,c)&&g.push(u)}g.length>0&&this.ydoc.transact(()=>{for(const u of g)this.suggestionEngine.deleteLiveSuggestion(u)},hs)}const l=bg(this.ydoc,e,n?"strip":"recover");return a.duplicatesFound===0&&l===0?!1:(this.cachedDoc=null,this.incrementalRefreshPending=!1,On(this.ydoc,he(this.ydoc)),!0)}get localOrigin(){return this.origin}beginRollbackScope(){const e=new S.UndoManager([this.ydoc.getXmlFragment("content"),this.ydoc.getXmlFragment("chrome"),this.ydoc.getXmlFragment("notes"),this.ydoc.getArray("annotations"),this.suggestionEngine.getLiveSuggestionStore(),this.ydoc.getMap("comments")],{captureTimeout:0,trackedOrigins:this.trackedUndoOrigins}),t=this.undoManager.undoStack.length,n=this.undoManager.redoStack.length;let i=!1;const r=()=>{i||(i=!0,e.destroy())};return{revert:()=>{if(!i){for(;e.canUndo();)e.undo();this.undoManager.undoStack.length=Math.min(this.undoManager.undoStack.length,t),this.undoManager.redoStack.length=Math.min(this.undoManager.redoStack.length,n),this.cachedDoc=null,this.incrementalRefreshPending=!1,this.invalidateDerivedDocumentState(),r()}},dispose:r}}canUndo(){return this.undoManager.canUndo()}canRedo(){return this.undoManager.canRedo()}undo(){try{const e=this.undoManager.undoStack;if(e.length===0)return null;const t=e[e.length-1],n=t.meta.get("beforeSelection"),i=t.meta.get("beforeSelectionAbsolute");return this.undoManager.undo(),n?wr(n,this.ydoc):i||null}catch(e){return console.error("Error during undo:",e),e instanceof Error&&e.message.includes("forEach")&&(console.warn("Clearing undo history due to corrupted state"),this.undoManager.clear()),null}}redo(e){try{const t=this.undoManager.redoStack;if(t.length===0)return null;const n=t[t.length-1].meta.get("afterSelection"),i=this.getDocument();return this.currentSelectionBeforeRedo=e?H(e,this.ydoc,i):null,this.afterSelectionForRedo=n||null,this.isRedoing=!0,this.undoManager.redo(),n?wr(n,this.ydoc):null}catch(t){return console.error("Error during redo:",t),this.isRedoing=!1,this.currentSelectionBeforeRedo=null,this.afterSelectionForRedo=null,t instanceof Error&&t.message.includes("forEach")&&(console.warn("Clearing undo history due to corrupted state"),this.undoManager.clear()),null}}getParagraphPlainText(e){return e.children.map(t=>t.text).join("")}insertText(e,t,n,i){this.beforeOperationSelection=n;const r=this.getDocument();try{this.beforeOperationRelativeSelection=H(n,this.ydoc,r)}catch{this.beforeOperationRelativeSelection=null}const o=this.resolveEditableContext(e,r);if(!o)return!1;const{editable:a}=o,l=a.block;if(l.type==="list")return this.listOperations.insertTextInList(e,t,n,i);if(bn(l))return this.insertTextInCodeBlock(e,t,n,i);if(l.type!=="paragraph")return!1;const c=l,d=this.listOperations.tryApplyParagraphListTrigger(c,e,t);if(d!==null)return d;const g={type:"text",text:t},u={},p=$i(r,e),h=Fi(r,e),f=Ni(r,e,n),m=this.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(r,e),y=m?.marks?.suggestionId??null,b=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r,e.block),k=this.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(r,e,n),I=!b&&this.suggestingMode&&t.length>0,v=kr({inheritedMarks:f?.marks,emptyParagraphMarks:Si(c)?void 0:this.getEmptyTextMarksForBlockId(e.block),exitingLink:p,exitingComment:h,suggestionMarks:I?this.suggestionEngine.buildSuggestionInsertionMarks(void 0,k??y??this.suggestionEngine.getSuggestionIdFromInheritedMarks(f?.marks),void 0,void 0,m?.marks??f?.marks):void 0});Object.assign(u,v.marksToApply),Object.keys(u).length>0&&(g.marks=u);const x=this.insertTextNodes(e,[g],n,k??void 0);if(x){const A={anchor:x,focus:x};this.setSelectionAfterOperation(A),this.afterOperationRelativeSelection=H(A,this.ydoc,this.getDocument())}return x!==null}insertFormattedText(e,t,n,i,r,o){this.beforeOperationSelection=i;const a=this.getDocument();this.beforeOperationRelativeSelection=H(i,this.ydoc,a);const l=z(a,e.block);if(!l)return!1;if(l.type==="list")return this.listOperations.insertFormattedTextInList(e,t,n,i,r);if(bn(l))return this.insertTextInCodeBlock(e,t,i,r);if(l.type!=="paragraph")return!1;const c=l,d=this.listOperations.tryApplyParagraphListTrigger(c,e,t);if(d!==null)return d;const g=ot(e,this.ydoc,a);if(!g)return!1;const u=S.createAbsolutePositionFromRelativePosition(g.textOffset,this.ydoc);if(!u||!(u.type instanceof S.XmlText))return!1;const p=u.type,h=u.index,f=Ni(a,e,i),m=this.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(a,e),y=m?.marks?.suggestionId??null,b=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(a,e.block),k=this.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(a,e,i),I=$i(a,e),v=Fi(a,e),x=!b&&this.suggestingMode&&t.length>0,{marksToApply:A,marksToRemove:C}=kr({explicitMarks:n&&Object.keys(n).length>0?n:void 0,inheritedMarks:f?.marks,emptyParagraphMarks:Si(c)?void 0:this.getEmptyTextMarksForBlockId(e.block),exitingLink:I,exitingComment:v,noteBodyFontSize:this.isBlockInsideFootnote(a,e.block)?ut:void 0,suggestionMarks:x?this.suggestionEngine.buildSuggestionInsertionMarks(void 0,o??k??y??this.suggestionEngine.getSuggestionIdFromInheritedMarks(f?.marks),void 0,void 0,m?.marks??f?.marks):void 0});let F=h;this.transact(()=>{if(i&&i.anchor&&i.focus&&Ie(a,i.anchor,i.focus)!==0){const[B,w]=Ie(a,i.anchor,i.focus)===-1?[i.anchor,i.focus]:[i.focus,i.anchor];if(B.block===e.block&&w.block===e.block)if(this.suggestingMode&&!b){const{retainedLength:T}=this.suggestionEngine.applySuggestedDeletionToTextRange(p,B.offset,w.offset-B.offset,k??void 0);F=B.offset+T}else p.delete(B.offset,w.offset-B.offset),F=B.offset}la(p,F,t,{marksToApply:A,marksToRemove:C}),!b&&this.suggestingMode&&t.length>0&&this.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(p,F,t.length)});const E=S.createRelativePositionFromTypeIndex(p,F+t.length),P=li({blockId:g.blockId,textOffset:E},this.ydoc);if(P){const B={anchor:P,focus:P};return this.setSelectionAfterOperation(B),this.afterOperationRelativeSelection=H(B,this.ydoc,this.getDocument()),!0}return this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=H(r,this.ydoc,this.getDocument()),!0}insertTextNodes(e,t,n,i){if(t.length===0)return null;const r=this.getDocument(),o=K(this.ydoc,e.block);if(!o)return null;const a=ae(o);if(!a)return null;const l=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r,e.block),c=l?t.map(h=>({...h,marks:this.suggestionEngine.stripSuggestionMarksFromTextMark(h.marks)})):t;let d=e.offset,g=0;const u=[];this.transact(()=>{if(n&&n.anchor&&n.focus&&Ie(r,n.anchor,n.focus)!==0){const[f,m]=Ie(r,n.anchor,n.focus)===-1?[n.anchor,n.focus]:[n.focus,n.anchor];if(f.block===e.block&&m.block===e.block)if(this.suggestingMode&&!l){const{retainedLength:y}=this.suggestionEngine.applySuggestedDeletionToTextRange(a,f.offset,m.offset-f.offset,i);d=f.offset+y}else a.delete(f.offset,m.offset-f.offset),d=f.offset}let h=d;for(const f of c)if(f.text.length>0){const m={...f.marks||{}};ne(a,h,f.text,m),m.insertion&&u.push({start:h,length:f.text.length}),h+=f.text.length,g+=f.text.length}for(const f of u)this.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(a,f.start,f.length);o.getAttribute("_emptyTextMarks")&&o.removeAttribute("_emptyTextMarks")});const p=d+g;return{block:e.block,offset:p}}insertParagraphInternal(e,t,n=this.getYContentFragment()){if(e<0||e>n.length)return!1;const i=new S.XmlElement("paragraph");i.setAttribute("id",t.id||Y()),t.heading&&i.setAttribute("heading",String(t.heading)),t.align&&i.setAttribute("align",t.align),t.lineSpacing!==void 0&&i.setAttribute("lineSpacing",String(t.lineSpacing)),pn(i,t);const r=Ye(t);r!==void 0&&i.setAttribute("pagination",r),t.styleId!==void 0&&i.setAttribute("styleId",t.styleId),t.direction!==void 0&&i.setAttribute("direction",t.direction),t.tabStops!==void 0&&i.setAttribute("tabStops",t.tabStops),t.borders!==void 0&&i.setAttribute("borders",t.borders),t.shading!==void 0&&i.setAttribute("shading",t.shading),t.oxmlAttrs!==void 0&&i.setAttribute("oxmlAttrs",t.oxmlAttrs),t.oxmlPPr!==void 0&&i.setAttribute("oxmlPPr",t.oxmlPPr);const o=Re(t.leftIndent);o!==void 0&&i.setAttribute("leftIndent",String(o));const a=De(t.firstLineIndent);a!==void 0&&i.setAttribute("firstLineIndent",String(a));const l=new S.XmlText;n.insert(e,[i]),i.insert(0,[l]);let c=0;return t.children.forEach(d=>{if(d.type==="text"&&d.text.length>0){const g={...d.marks||{}};ne(l,c,d.text,g),c+=d.text.length}}),!0}insertParagraph(e,t){const n=this.getYContentFragment();return e<0||e>n.length?!1:(this.transact(()=>{this.insertParagraphInternal(e,t)}),!0)}deleteText(e,t,n,i){this.beforeOperationSelection=n;const r=this.getDocument();this.beforeOperationRelativeSelection=H(n,this.ydoc,r);const o=z(r,e.block);if(!o)return!1;if(o.type==="list")return this.listOperations.deleteTextInList(e,t,n,i);if(bn(o))return this.deleteTextInCodeBlock(e,t,n,i);if(o.type!=="paragraph")return!1;const a=o,l=this.getEmptyTextMarksForBlockId(e.block),c=mn(r,a,e,l);let d=0;for(const k of a.children)k.type==="text"&&(d+=k.text.length);let g=e.offset,u=e.offset+t,p=!1;{let k=0;for(const I of a.children){if(I.type!=="text")continue;const v=k+I.text.length;I.marks?.footnoteRef&&k<u&&v>g&&(p=!0,g=Math.min(g,k),u=Math.max(u,v)),k=v}}p&&(e={...e,offset:g},t=u-g);const h=d-e.offset,f=Math.min(t,h),m=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r,e.block);let y=null;this.transact(()=>{const k=K(this.ydoc,e.block);if(!k)return;const I=ae(k);if(I){if(this.suggestingMode&&!m){const v=this.suggestionEngine.applySuggestedDeletionToTextRange(I,e.offset,f);f>1&&v.retainedLength>0&&(y=this.normalizeAdjacentManualReplacementOrder(I,e.offset))}else I.delete(e.offset,f);I.length===0&&ki(k,c)}});const b=y?Zr(i,e.block,y):i;return this.setSelectionAfterOperation(b),this.afterOperationRelativeSelection=H(b,this.ydoc,this.getDocument()),p&&!this.suggestingMode&&this.reconcileFootnotes(),!0}deleteSelection(e,t,n,i){this.beforeOperationSelection||(this.beforeOperationSelection=n);const r=this.getDocument();this.beforeOperationRelativeSelection||(this.beforeOperationRelativeSelection=H(n,this.ydoc,r));let o=Wt(r,e.block),a=Wt(r,t.block);if(o===-1||a===-1){const p=h=>{const f=(r.chrome??[]).findIndex(y=>y.id===h||y.children.some(b=>b.id===h));if(f!==-1)return r.children.length+f;const m=(r.notes??[]).findIndex(y=>y.id===h||y.children.some(b=>b.id===h));return m!==-1?r.children.length+(r.chrome?.length??0)+m:-1};if(o=p(e.block),a=p(t.block),o===-1||a===-1||e.block!==t.block&&(r.chrome??[]).some(h=>h.children.some(f=>f.id===e.block)))return!1}const l=e.block===t.block;if(l){const p=z(r,e.block);if(!p)return!1;if(this.suggestingMode&&p.type==="paragraph")return this.deleteSingleParagraphSelection(e,t,n,i);if(this.suggestingMode&&p.type==="list"){const f=p,m=this.listOperations.getListCursorInfo(f,e),y=this.listOperations.getListCursorInfo(f,t);if(m&&y&&m.itemIndex+1===y.itemIndex&&m.offsetInItem===this.listOperations.getListItemPlainText(f.children[m.itemIndex]).length&&y.offsetInItem===0){const b=ce(),k=this.mergeAdjacentListItemsSnapshot(f,m.itemIndex,b);if(k){const I=this.suggestionEngine.runWithoutSuggesting(()=>this.updateBlockById(f.id,k,n,i));return I&&this.suggestionEngine.saveLiveSuggestion({id:b,type:"block-change",blockId:f.id,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(f),label:"Join"}),I}}}const h=Qe().getHandlerForBlock(p);if(h&&h.handleDeleteSelection){const f=K(this.ydoc,p.id);if(!f)return!1;let m=!1;if(this.transact(()=>{m=!h.handleDeleteSelection(p,f,e,t),p.type==="paragraph"&&e.offset===0&&t.offset>=p.children.reduce((y,b)=>y+(b.type==="text"?b.text.length:0),0)&&Si(p)&&ki(f,mn(r,p,e))}),m){const y=ec(r,e.block),b=tc(r,e.block);let k;if(y&&y.id){const v=xc(r,y.id);v?k=v:k={block:y.id,offset:0}}else if(b&&b.id)k={block:b.id,offset:0};else return!1;const I={anchor:k,focus:k};return this.deleteBlockById(e.block,n,I)}return this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0}return p.type==="paragraph"?this.deleteSingleParagraphSelection(e,t,n,i):this.deleteBlockById(e.block,n,i)}if(this.suggestingMode&&!l&&this.suggestionEngine.deleteMultiParagraphSelectionAsSuggestion(e,t,o,a,i))return!0;const c=Je(r,e.block),d=Je(r,t.block),g=z(r,e.block),u=z(r,t.block);return c&&d&&c===d&&g?.type==="paragraph"&&u?.type==="paragraph"?this.mergeAdjacentParagraphs(g,u,e,t,c,n,i):this.deleteMultiBlockSelection(e,t,r,n,i)}mergeAdjacentParagraphs(e,t,n,i,r,o,a){const l=K(this.ydoc,e.id),c=K(this.ydoc,t.id);if(!l||!c)return console.error("[mergeAdjacentParagraphs] Could not find Y.js blocks"),!1;let d=null,g=null;for(let y=0;y<l.length;y++){const b=l.get(y);if(b instanceof S.XmlText){d=b;break}}for(let y=0;y<c.length;y++){const b=c.get(y);if(b instanceof S.XmlText){g=b;break}}if(!d||!g)return console.error("[mergeAdjacentParagraphs] Could not find Y.XmlText"),!1;const u=n.offset===d.length&&i.offset===0;if(u){const y=this.isPlainEmptyParagraph(e),b=this.isPlainEmptyParagraph(t),k=this.isInsertedParagraph(e),I=this.isInsertedParagraph(t);if(y&&I||k&&b){const v=y?e:t,x=y?t:e,A=y?0:this.getParagraphTextLength(x),C={block:x.id,offset:A},F={anchor:C,focus:C};return this.deleteBlockById(v.id,o,F)}}if(this.suggestingMode&&u){const y=this.getCancelableParagraphSplitRecord(e,t);if(y){const k=this.suggestionEngine.rejectLiveSuggestion(y.id);if(k){const I={block:y.blockId,offset:this.getParagraphTextLength(e)},v={anchor:I,focus:I};this.setSelectionAfterOperation(v),this.afterOperationRelativeSelection=H(v,this.ydoc,this.getDocument())}return k}const b=ce();return this.transact(()=>{this.suggestionEngine.clearParagraphStructuralSuggestion(l),this.suggestionEngine.clearParagraphStructuralSuggestion(c),this.suggestionEngine.setParagraphStructuralSuggestion(l,"merge","before",b),this.suggestionEngine.setParagraphStructuralSuggestion(c,"merge","after",b),this.suggestionEngine.saveLiveSuggestion({id:b,type:"paragraph-merge",firstBlockId:e.id,secondBlockId:t.id})}),this.setSelectionAfterOperation(a),this.afterOperationRelativeSelection=H(a,this.ydoc,this.getDocument()),!0}const p=G(this.ydoc,e.id),h=G(this.ydoc,t.id);if(!p||!h)return console.error("[mergeAdjacentParagraphs] Could not find Y.js parent"),!1;if(p.yParent!==h.yParent)return console.error("[mergeAdjacentParagraphs] Paragraphs have different Y.js parents"),!1;const f=p.index,m=h.index;return this.transact(()=>{this.suggestionEngine.clearParagraphStructuralSuggestion(l);const y=d.length;n.offset<y&&d.delete(n.offset,y-n.offset);const b=Z(g).slice(0);let k=[],I=0;for(const A of b)if(typeof A.insert=="string"){const C=A.insert;if(I+C.length<=i.offset)I+=C.length;else if(I>=i.offset)k.push(A);else{const F=i.offset-I,E=C.slice(F);E.length>0&&k.push({...A,insert:E}),I+=C.length}}for(const A of k)typeof A.insert=="string"&&d.insert(d.length,A.insert,A.attributes||{});const{yParent:v}=p,x=m-f;x>0&&v.delete(f+1,x)}),this.setSelectionAfterOperation(a),this.afterOperationRelativeSelection=H(a,this.ydoc,this.getDocument()),!0}deleteMultiBlockSelection(e,t,n,i,r){const o=ht(n,e.block),a=ht(n,t.block);if(!o||!a)return!1;const l=z(n,e.block),c=z(n,t.block);if(!l||!c)return!1;const d=[];for(const{block:A,path:C}of nc(n)){const F=Pt(C,o),E=Pt(C,a);if(!(F<0)){if(E>0)break;d.push({block:A,path:C,isFirst:F===0,isLast:E===0})}}if(d.length===0)return!1;const g=o[0],u=a[0],p=n.children[g],h=n.children[u];if(g!==u&&p?.type==="list"&&h?.type==="list"&&this.listOperations.mergeAdjacentListsOnDelete(p,h,g,u,e,t,r))return!0;const f=d[0],m=d[d.length-1],y=f.block.type==="paragraph",b=m.block.type==="paragraph",k=G(this.ydoc,f.block.id),I=G(this.ydoc,m.block.id);if(!k||!I)return!1;const v=k.yBlock,x=I.yBlock;return this.transact(()=>{let A=null,C=null;y&&(A=ae(v)),b&&(C=ae(x));const F=y?e.offset:0,E=b?t.offset:0,P=d.length===2&&y&&b&&A!==null&&F===A.length&&E===0;let B="";const w={};if(b&&C){const T=Z(C);let N=0;for(const L of T)if(L.insert&&typeof L.insert=="string"){const _=L.insert.length;N>=E?(B+=L.insert,L.attributes&&Object.assign(w,L.attributes)):N+_>E&&(B+=L.insert.slice(E-N),L.attributes&&Object.assign(w,L.attributes)),N+=_}}if(y&&A&&F<A.length&&A.delete(F,A.length-F),P&&v instanceof S.XmlElement&&x instanceof S.XmlElement){const T=x.getAttribute("heading");T?v.setAttribute("heading",T):v.removeAttribute("heading");const N=ee(x,"align");N&&v.setAttribute("align",N);const L=ee(x,"lineSpacing");L?v.setAttribute("lineSpacing",L):J(v,"lineSpacing"),jh(x,v,!0);const _=ee(x,"pagination");_?v.setAttribute("pagination",_):J(v,"pagination");const $=ee(x,"tabStops");$?v.setAttribute("tabStops",$):J(v,"tabStops");for(const O of["oxmlAttrs","oxmlPPr"]){const D=ee(x,O);D?v.setAttribute(O,D):J(v,O)}const R=ee(x,"leftIndent");R?v.setAttribute("leftIndent",R):J(v,"leftIndent");const M=ee(x,"firstLineIndent");M?v.setAttribute("firstLineIndent",M):J(v,"firstLineIndent")}y&&A&&B?ne(A,A.length,B,w):!y&&b&&C&&E>0&&C.delete(0,Math.min(E,C.length));for(let T=d.length-1;T>=0;T--){const N=d[T],L=N.isFirst&&y,_=!y&&N.isLast&&b;if(L||_)continue;const $=G(this.ydoc,N.block.id);if($){const{yBlock:R,yParent:M,index:O}=$;if(M.length===1){if(N.block.type==="paragraph"){const D=Je(n,N.block.id);if(D?.type==="container"&&D.id){const j=G(this.ydoc,D.id);if(j&&j.yParent.length>1){j.yParent.delete(j.index,1);continue}}const X=ae(R);X&&X.length>0&&X.delete(0,X.length)}else{M.delete(O,1);const D=new S.XmlElement("paragraph");D.setAttribute("id",Y());const X=new S.XmlText;D.insert(0,[X]),M.insert(0,[D])}continue}M.delete(O,1)}}}),this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=H(r,this.ydoc,this.getDocument()),!0}deleteSingleParagraphSelection(e,t,n,i){const r=this.getDocument(),o=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r,e.block),a=this.getParagraphOffsetForPosition(e,r),l=this.getParagraphOffsetForPosition(t,r);if(!a||!l||!this.arePathsEqual(a.paragraphPath,l.paragraphPath))return!1;const c=this.getEmptyTextMarksForBlockId(e.block),d=mn(r,a.paragraph,e,c);let g=null;this.transact(()=>{const p=K(this.ydoc,e.block);if(!(p instanceof S.XmlElement))return;let h=null;for(let f=0;f<p.length;f++){const m=p.get(f);if(m instanceof S.XmlText){h=m;break}}!h||a.paragraph.type!=="paragraph"||(this.suggestingMode&&!o?this.suggestionEngine.applySuggestedDeletionToTextRange(h,a.offset,l.offset-a.offset).retainedLength>0&&(g=this.normalizeAdjacentManualReplacementOrder(h,a.offset)):h.delete(a.offset,l.offset-a.offset),h.length===0&&ki(p,d))});const u=g?Zr(i,e.block,g):i;return this.setSelectionAfterOperation(u),this.afterOperationRelativeSelection=H(u,this.ydoc,this.getDocument()),!0}deleteBlock(e,t,n){this.beforeOperationSelection=t;const i=this.getDocument();return i.children.length<=1?!1:(this.beforeOperationRelativeSelection=H(t,this.ydoc,i),this.transact(()=>{const r=this.getYContentFragment();e<r.length&&r.delete(e,1)}),this.afterOperationRelativeSelection=H(n,this.ydoc,this.getDocument()),!0)}deleteBlockById(e,t,n){this.beforeOperationSelection=t;const i=this.getDocument(),r=z(i,e);if(!r)return!1;const o=G(this.ydoc,e);if(!o)return!1;const{yBlock:a,yParent:l,index:c}=o;if(this.suggestingMode&&a instanceof S.XmlElement){const d=(r.type==="paragraph"||r.type==="list"?r.structuralSuggestionKind==="insert"?r.structuralSuggestionId:void 0:"diffState"in r&&r.diffState==="insert"&&"suggestionId"in r?r.suggestionId:void 0)??void 0;if(d&&this.suggestionEngine.getLiveSuggestion(d)?.type==="block-insert")return this.suggestionEngine.rejectLiveSuggestion(d);if(r.type==="paragraph"){const g=ae(a),u=g?.length??0;if(g&&u>0)return this.beforeOperationRelativeSelection=H(t,this.ydoc,i),this.transact(()=>{this.suggestionEngine.applySuggestedDeletionToTextRange(g,0,u)}),this.afterOperationRelativeSelection=H(n,this.ydoc,this.getDocument()),!0}else{const g=ce(),u=this.getTrailingCleanupParagraphIdForTopLevelBlock(i,e);return this.beforeOperationRelativeSelection=H(t,this.ydoc,i),this.transact(()=>{this.suggestionEngine.markDeletedBlockElement(a,g),this.suggestionEngine.saveLiveSuggestion({id:g,type:"block-delete",blockId:e,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(r),label:"Delete",cleanupTrailingParagraphId:u})}),this.afterOperationRelativeSelection=H(n,this.ydoc,this.getDocument()),!0}}if(l.length===1){if(r.type==="paragraph"){const u=ae(a);return u&&u.length>0?(this.beforeOperationRelativeSelection=H(t,this.ydoc,i),this.transact(()=>{u.delete(0,u.length)}),this.afterOperationRelativeSelection=H(n,this.ydoc,this.getDocument()),!0):!1}this.beforeOperationRelativeSelection=H(t,this.ydoc,i);const d=Y();this.transact(()=>{l.delete(c,1);const u=new S.XmlElement("paragraph");u.setAttribute("id",d);const p=new S.XmlText;u.insert(0,[p]),l.insert(0,[u])});const g={anchor:{block:d,offset:0},focus:{block:d,offset:0}};return this.afterOperationRelativeSelection=H(g,this.ydoc,this.getDocument()),this.setSelectionAfterOperation(g),!0}return this.beforeOperationRelativeSelection=H(t,this.ydoc,i),this.transact(()=>{l.delete(c,1)}),this.afterOperationRelativeSelection=H(n,this.ydoc,this.getDocument()),this.ensureTrailingParagraph(),!0}static splitBordersAttr(e){try{const t=JSON.parse(e),n=i=>{const r={};for(const o of i)t[o]!==void 0&&(r[o]=t[o]);return Object.keys(r).length>0?JSON.stringify(r):null};return{upper:n(["top","left","right"]),lower:n(["bottom","left","right"])}}catch{return{upper:e,lower:e}}}static isTailFullyDeletionMarked(e,t){if(!("children"in e)||!Array.isArray(e.children))return!1;let n=0,i=!1;for(const r of e.children){if(r.type!=="text")continue;const o=n+r.text.length;if(o>t&&r.text.length>0&&(i=!0,!r.marks?.deletion))return!1;n=o}return i}splitParagraph(e,t){this.beforeOperationSelection=t;const n=this.getDocument();this.beforeOperationRelativeSelection=H(t,this.ydoc,n);const i=z(n,e.block);if(!i)return null;let r=null;if(i.type==="list")return this.listOperations.splitListItem(e,t);if(i.type!=="paragraph")return null;if(this.suggestingMode){const E=this.getCancelableParagraphMergeRecord(i,e.offset);if(E&&this.suggestionEngine.rejectLiveSuggestion(E.id)){const P={anchor:e,focus:e};return this.setSelectionAfterOperation(P),this.afterOperationRelativeSelection=H(P,this.ydoc,this.getDocument()),e}}const o=G(this.ydoc,e.block);if(!o)return null;const{yBlock:a,yParent:l,index:c}=o,d=i.structuralSuggestionId?this.suggestionEngine.getLiveSuggestion(i.structuralSuggestionId):void 0,g=d?.type==="block-change"&&d.sequenceBlockIds?d:null,u=this.getEmptyTextMarksForBlockId(e.block),p=e.offset,h=this.suggestionEngine.getStructuralInsertSuggestionIdAtPosition(n,e),f=i.children.reduce((E,P)=>P.type==="text"?E+P.text.length:E,0),m=this.suggestingMode&&p>0&&p<f&&lt.isTailFullyDeletionMarked(i,p),y=typeof h=="string"&&(p===0||p===f),b=this.suggestingMode&&typeof h=="string"&&p>0&&p<f,k=typeof h=="string",I=g?null:b?h:this.suggestingMode&&!y?ce():null,v=b||this.suggestingMode&&!y&&(f===0||p===0||p===f||m),x=p===0&&!(v&&f===0),A=this.suggestingMode&&!k&&I;if(p===0){if(this.transact(()=>{r=Y();const B=new S.XmlElement("paragraph");B.setAttribute("id",r);const w=a.getAttribute("heading"),T=a.getAttribute("styleId"),N=w!=null?!0:typeof T=="string"&&/^heading\d/i.test(T);oa(a,B);const L=ee(a,"direction");if((L==="rtl"||L==="ltr")&&B.setAttribute("direction",L),!N){const M=ee(a,"align");M&&B.setAttribute("align",M);const O=a.getAttribute("styleId");O!=null&&B.setAttribute("styleId",O)}const _=ee(a,"borders");if(_!=null){const{upper:M,lower:O}=lt.splitBordersAttr(_);M?B.setAttribute("borders",M):J(B,"borders"),O?a.setAttribute("borders",O):J(a,"borders")}const $=new S.XmlText,R=N?null:mn(n,i,e,u);R&&B.setAttribute("_emptyTextMarks",JSON.stringify(R)),this.suggestionEngine.clearParagraphStructuralSuggestion(a),this.suggestionEngine.clearParagraphStructuralSuggestion(B),k&&h&&this.suggestionEngine.setParagraphStructuralSuggestion(a,"insert",void 0,h,"Insert"),I&&(v?this.suggestionEngine.setParagraphStructuralSuggestion(B,"insert",void 0,I,"Insert"):(this.suggestionEngine.setParagraphStructuralSuggestion(B,"split","before",I),this.suggestionEngine.setParagraphStructuralSuggestion(a,"split","after",I))),B.insert(0,[$]),l.insert(x?c:c+1,[B]),g&&this.suggestionEngine.preserveSequenceAfterParagraphSplit(g,[a,B]),N&&r&&this.applyStylesheetHeadingDefaults(B,{type:"paragraph",id:r,heading:i.heading,styleId:i.styleId,children:[]},n,void 0)}),!r)return null;A&&I&&this.suggestionEngine.saveLiveSuggestion({id:I,type:"block-insert",blockId:r,label:"Insert"});const E={block:k?e.block:this.suggestingMode&&v?r:e.block,offset:0},P={anchor:E,focus:E};return this.setSelectionAfterOperation(P),this.afterOperationRelativeSelection=H(P,this.ydoc,this.getDocument()),E}if(this.transact(()=>{let E=null;for(let X=0;X<a.length;X++){const j=a.get(X);if(j instanceof S.XmlText){E=j;break}}if(!E||i.type!=="paragraph")return;const P=Z(E);let B=0;const w=[];if(!m){for(const X of P)if(X.insert&&typeof X.insert=="string"){const j=X.insert.length;if(B+j<=p)B+=j;else if(B>=p)w.push(X);else{const U=p-B,q=X.insert.slice(U);q&&w.push({insert:q,...X.attributes&&{attributes:X.attributes}}),B=p}}p<E.length&&E.delete(p,E.length-p)}this.suggestionEngine.clearParagraphStructuralSuggestion(a),r=Y();const T=new S.XmlElement("paragraph");T.setAttribute("id",r),oa(a,T);const N=ee(a,"align");N&&T.setAttribute("align",N);const L=a.getAttribute("styleId");L!=null&&T.setAttribute("styleId",L);const _=ee(a,"direction");(_==="rtl"||_==="ltr")&&T.setAttribute("direction",_);const $=ee(a,"borders");if($!=null){const{upper:X,lower:j}=lt.splitBordersAttr($);j?T.setAttribute("borders",j):J(T,"borders"),X?a.setAttribute("borders",X):J(a,"borders")}const R=new S.XmlText,M=mn(n,i,e,u),O=i.heading!==void 0&&vs(n.stylesheet)!==void 0;let D=null;if(O&&w.length>0){const X=n.stylesheet,j=(i.styleId?xs(X,i.styleId):void 0)??Li(X,i.heading),U=vs(X);D=As(j?.runMarks,U?.runMarks)}if(w.length>0){let X=0;for(const j of w)if(j.insert&&typeof j.insert=="string"){let U=j.attributes||{};if(D){U={...U};for(const[q,oe]of Object.entries(D))oe===!1||oe===void 0?delete U[q]:U[q]=oe}ne(R,X,j.insert,U),X+=j.insert.length}}else M&&T.setAttribute("_emptyTextMarks",JSON.stringify(M));this.suggestionEngine.clearParagraphStructuralSuggestion(T),k&&h&&this.suggestionEngine.setParagraphStructuralSuggestion(a,"insert",void 0,h,"Insert"),I&&(v?this.suggestionEngine.setParagraphStructuralSuggestion(T,"insert",void 0,I,"Insert"):(this.suggestionEngine.setParagraphStructuralSuggestion(T,"split","after",I),this.suggestionEngine.setParagraphStructuralSuggestion(a,"split","before",I))),T.insert(0,[R]),l.insert(c+1,[T]),g&&this.suggestionEngine.preserveSequenceAfterParagraphSplit(g,[a,T]),O&&r&&(this.applyStylesheetHeadingDefaults(T,{type:"paragraph",id:r,heading:i.heading,styleId:i.styleId,children:[]},n,void 0),w.length>0&&T.removeAttribute("_emptyTextMarks"))}),!r)return null;A&&I&&(v?this.suggestionEngine.saveLiveSuggestion({id:I,type:"block-insert",blockId:r,label:"Insert"}):this.suggestionEngine.saveLiveSuggestion({id:I,type:"paragraph-split",blockId:i.id,insertedBlockId:r,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(i)}));const C={block:r,offset:0},F={anchor:C,focus:C};return this.setSelectionAfterOperation(F),this.afterOperationRelativeSelection=H(F,this.ydoc,this.getDocument()),C}applyFormatting(e,t,n,i,r){this.beforeOperationSelection=i;const o=this.getDocument();this.beforeOperationRelativeSelection=H(i,this.ydoc,o);let a=!1,l=null;const c=[];return this.transact(()=>{const d=this.getYContentFragment(),g=this.collectInlineFormattingRanges(e,t,d,o);if(g.length===0)return;const u=this.suggestingMode?(()=>{let p=null;for(const h of g){if(!h.blockId)return null;const f=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(o,h.blockId);if(!f)return null;if(!p){p=f;continue}if(p!==f)return null}return p})():null;l=this.suggestingMode&&!u?ce():null;e:for(const{yText:p,start:h,end:f}of g){const m=Z(p);let y=0;for(const b of m)if(b.insert&&typeof b.insert=="string"){const k=b.insert.length,I=y+k;if(y<f&&I>h&&!(b.attributes||{})[n]){a=!0;break e}y+=k}}for(const{yText:p,start:h,end:f,blockId:m,itemIndex:y}of g){const b=Math.max(0,f-h),k=this.suggestingMode&&l&&b>0?this.collectOverlappingTextSpans(p,h,b):[];if(this.suggestingMode&&l&&b>0&&m)for(const v of k)v.attributes?.insertion||v.attributes?.deletion||c.push({blockId:m,itemIndex:y,start:v.start,end:v.start+v.length,attributes:v.attributes});const I=n==="superscript"&&a?{superscript:!0,subscript:!1}:n==="subscript"&&a?{subscript:!0,superscript:!1}:{[n]:a};if(this.suggestingMode&&l&&b>0){const v=this.suggestionEngine.buildInlineSuggestionMetadataMarks(l,this.getFormattingDescriptionFromMarkKey(n));for(const x of k)x.attributes?.deletion||(ie(p,x.start,x.length,I),!x.attributes?.insertion&&ie(p,x.start,x.length,{formatChange:!0,...v,suggestionPriorAttributes:hn(x.attributes)}))}else ie(p,h,b,I)}this.suggestingMode&&l&&c.length>0&&this.suggestionEngine.saveLiveSuggestion({id:l,type:"inline-format",label:this.getFormattingDescriptionFromMarkKey(n),spans:c})}),this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=H(r,this.ydoc,this.getDocument()),!0}formatRangesWithValue(e,t,n){if(!this.suggestingMode){for(const{yText:a,start:l,end:c}of e){const d=Math.max(0,c-l);d>0&&ie(a,l,d,t)}return}const i=ce(),r=this.suggestionEngine.buildInlineSuggestionMetadataMarks(i,n),o=[];for(const{yText:a,start:l,end:c,blockId:d,itemIndex:g}of e){const u=Math.max(0,c-l);if(u===0)continue;const p=this.collectOverlappingTextSpans(a,l,u);for(const h of p)h.attributes?.deletion||!Object.entries(t).some(([f,m])=>{const y=h.attributes?.[f];return m===!1||m===null?y!=null&&y!==!1:y!==m})||(ie(a,h.start,h.length,t),!h.attributes?.insertion&&(ie(a,h.start,h.length,{formatChange:!0,...r,suggestionPriorAttributes:hn(h.attributes)}),d&&o.push({blockId:d,itemIndex:g,start:h.start,end:h.start+h.length,attributes:h.attributes??{}})))}o.length>0&&this.suggestionEngine.saveLiveSuggestion({id:i,type:"inline-format",label:n,spans:o})}setFontFamily(e,t,n,i){this.beforeOperationSelection=i;const r=this.getDocument();return this.beforeOperationRelativeSelection=H(i,this.ydoc,r),this.transact(()=>{const o=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,o,r),l=Ie(r,e,t)===0;if(a.length===0){l&&this.updateEmptyTextMarksAtPosition(e,"fontFamily",n,r);return}this.formatRangesWithValue(a,{fontFamily:n??!1},"Font"),l&&this.updateEmptyTextMarksAtPosition(e,"fontFamily",n,r)}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0}setFontSize(e,t,n,i){this.beforeOperationSelection=i;const r=this.getDocument();return this.beforeOperationRelativeSelection=H(i,this.ydoc,r),this.transact(()=>{const o=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,o,r),l=Ie(r,e,t)===0;if(a.length===0){l&&this.updateEmptyTextMarksAtPosition(e,"fontSize",n,r);return}this.formatRangesWithValue(a,{fontSize:n??!1},"Font Size"),l&&this.updateEmptyTextMarksAtPosition(e,"fontSize",n,r)}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0}setLetterSpacing(e,t,n,i){this.beforeOperationSelection=i;const r=this.getDocument();return this.beforeOperationRelativeSelection=H(i,this.ydoc,r),this.transact(()=>{const o=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,o,r),l=Ie(r,e,t)===0;if(a.length===0){l&&this.updateEmptyTextMarksAtPosition(e,"letterSpacing",n,r);return}this.formatRangesWithValue(a,{letterSpacing:n??!1},"Letter Spacing"),l&&this.updateEmptyTextMarksAtPosition(e,"letterSpacing",n,r)}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0}setTextColor(e,t,n,i){this.beforeOperationSelection=i;const r=this.getDocument();return this.beforeOperationRelativeSelection=H(i,this.ydoc,r),this.transact(()=>{const o=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,o,r),l=Ie(r,e,t)===0;if(a.length===0){l&&this.updateEmptyTextMarksAtPosition(e,"color",n,r);return}this.formatRangesWithValue(a,{color:n??!1},"Text Color"),l&&this.updateEmptyTextMarksAtPosition(e,"color",n,r)}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0}setBackgroundColor(e,t,n,i){const r=fc(n);this.beforeOperationSelection=i;const o=this.getDocument();return this.beforeOperationRelativeSelection=H(i,this.ydoc,o),this.transact(()=>{const a=this.getYContentFragment(),l=this.collectInlineFormattingRanges(e,t,a,o),c=Ie(o,e,t)===0;if(l.length===0){c&&this.updateBackgroundColorEmptyMarksAtPosition(e,r,o);return}this.formatRangesWithValue(l,{backgroundColor:r??null},"Highlight"),c&&this.updateBackgroundColorEmptyMarksAtPosition(e,r,o)}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0}clearFormatting(e,t,n){this.beforeOperationSelection=n;const i=this.getDocument();this.beforeOperationRelativeSelection=H(n,this.ydoc,i);let r=!1;return this.transact(()=>{const o=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,o,i),l=this.collectParagraphBlockIdsInRange(e,t,i);a.some(({start:c,end:d})=>d>c)&&(this.formatRangesWithValue(a,Es,"Clear Formatting"),r=!0);for(const c of l){const d=K(this.ydoc,c);if(d)for(const g of Ms)ee(d,g)!==void 0&&(J(d,g),r=!0)}Ie(i,e,t)===0&&this.clearFormattingEmptyMarksAtPosition(e,i)&&(r=!0)}),this.setSelectionAfterOperation(n),this.afterOperationRelativeSelection=H(n,this.ydoc,this.getDocument()),r}setLink(e,t,n,i){this.beforeOperationSelection=i;const r=this.getDocument();return this.beforeOperationRelativeSelection=H(i,this.ydoc,r),this.transact(()=>{const o=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,o,r);if(a.length===0)return;if(!this.suggestingMode){for(const{yText:c,start:d,end:g}of a){const u=Math.max(0,g-d);n?ie(c,d,u,{link:n}):ie(c,d,u,{link:!1})}return}const l=this.getPendingLinkSuggestionIdForRanges(a);if(l){if(!n&&!this.pendingLinkSuggestionHadPriorLink(a)){this.suggestionEngine.rejectLiveSuggestion(l);return}for(const{yText:c,start:d,end:g}of a){const u=Math.max(0,g-d);u!==0&&ie(c,d,u,{link:n??!1})}return}this.formatRangesWithValue(a,{link:n??!1},"Link")}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0}getPendingLinkSuggestionIdForRanges(e){let t=null;for(const{yText:n,start:i,end:r}of e){const o=Math.max(0,r-i);if(o!==0)for(const a of this.collectOverlappingTextSpans(n,i,o)){const l=a.attributes?.suggestionId;if(!a.attributes?.formatChange||!l)return null;const c=this.suggestionEngine.getLiveSuggestion(l);if(c?.type!=="inline-format"||c.label!=="Link"||t&&t!==l)return null;t=l}}return t}pendingLinkSuggestionHadPriorLink(e){for(const{yText:t,start:n,end:i}of e){const r=Math.max(0,i-n);if(r!==0)for(const o of this.collectOverlappingTextSpans(t,n,r)){const a=o.attributes?.suggestionPriorAttributes;if(typeof a=="string")try{if(JSON.parse(a).link)return!0}catch{}}}return!1}setCodeBlockLanguage(e,t){const n=this.getDocument(),i=z(n,e);if(!i||i.type!=="code")return!1;const r=n.children.findIndex(o=>o.id===e);return r===-1?!1:(this.transact(()=>{const o=this.getYContentFragment().get(r);o instanceof S.XmlElement&&o.nodeName==="code"&&(t?(o.setAttribute("language",t),pc(t)&&(o.getAttribute("renderDiagram")===null&&o.setAttribute("renderDiagram","true"),o.getAttribute("showDiagramSource")===null&&o.setAttribute("showDiagramSource","true"))):o.removeAttribute("language"))}),!0)}setCodeBlockRenderDiagram(e,t){const n=this.getDocument(),i=z(n,e);if(!i||i.type!=="code")return!1;const r=n.children.findIndex(o=>o.id===e);return r===-1?!1:(this.transact(()=>{const o=this.getYContentFragment().get(r);o instanceof S.XmlElement&&o.nodeName==="code"&&(o.setAttribute("renderDiagram",String(t)),t&&o.getAttribute("showDiagramSource")===null&&o.setAttribute("showDiagramSource","true"))}),!0)}setCodeBlockShowDiagramSource(e,t){const n=this.getDocument(),i=z(n,e);if(!i||i.type!=="code")return!1;const r=n.children.findIndex(o=>o.id===e);return r===-1?!1:(this.transact(()=>{const o=this.getYContentFragment().get(r);o instanceof S.XmlElement&&o.nodeName==="code"&&o.setAttribute("showDiagramSource",String(t))}),!0)}setMathBlockContent(e,t){const n=this.getDocument(),i=z(n,e);if(!i||i.type!=="math"&&!Ut(i))return!1;const r=G(this.ydoc,e);return r?(this.transact(()=>{const o=r.yBlock;if(!(o instanceof S.XmlElement))return;const a=Ut(i)?"code":"math";if(o.nodeName!==a)return;let l=o.get(0);l instanceof S.XmlText||(l=new S.XmlText,o.insert(0,[l]));const c=l.length;c>0&&l.delete(0,c),l.insert(0,t)}),!0):!1}setMathBlockDisplayMode(e,t){const n=this.getDocument(),i=z(n,e);if(!i||i.type!=="math"&&!Ut(i))return!1;const r=G(this.ydoc,e);return r?(this.transact(()=>{const o=r.yBlock;if(o instanceof S.XmlElement){if(Ut(i)&&o.nodeName==="code"){const a=t==="inline"?"latex-inline":"latex";o.setAttribute("language",a),o.getAttribute("renderDiagram")===null&&o.setAttribute("renderDiagram","true"),o.getAttribute("showDiagramSource")===null&&o.setAttribute("showDiagramSource","true");return}o.nodeName==="math"&&o.setAttribute("displayMode",t)}}),!0):!1}setMathBlockAlign(e,t){const n=this.getDocument(),i=z(n,e);if(!i||i.type!=="math"&&!Ut(i))return!1;if(Ut(i))return!0;const r=n.children.findIndex(o=>o.id===e);return r===-1?!1:(this.transact(()=>{const o=this.getYContentFragment().get(r);o instanceof S.XmlElement&&o.nodeName==="math"&&o.setAttribute("align",t)}),!0)}replaceParagraph(e,t,n,i){this.beforeOperationSelection=n;const r=this.getDocument();return this.beforeOperationRelativeSelection=H(n,this.ydoc,r),e<0||e>=r.children.length?!1:(r.children[e],this.transact(()=>{const o=this.getYContentFragment(),a=o.get(e),l=a instanceof S.XmlElement?a.getAttribute("id"):void 0,c=new S.XmlElement("paragraph");c.setAttribute("id",t.id||l||Y()),t.heading&&c.setAttribute("heading",String(t.heading)),t.align&&c.setAttribute("align",t.align),t.lineSpacing!==void 0&&c.setAttribute("lineSpacing",String(t.lineSpacing)),pn(c,t);{const h=Ye(t);h!==void 0&&c.setAttribute("pagination",h)}t.styleId!==void 0&&c.setAttribute("styleId",t.styleId),t.direction!==void 0&&c.setAttribute("direction",t.direction),t.tabStops!==void 0&&c.setAttribute("tabStops",t.tabStops),t.borders!==void 0&&c.setAttribute("borders",t.borders),t.shading!==void 0&&c.setAttribute("shading",t.shading),t.oxmlAttrs!==void 0&&c.setAttribute("oxmlAttrs",t.oxmlAttrs),t.oxmlPPr!==void 0&&c.setAttribute("oxmlPPr",t.oxmlPPr);const d=Re(t.leftIndent);d!==void 0&&c.setAttribute("leftIndent",String(d));const g=De(t.firstLineIndent);g!==void 0&&c.setAttribute("firstLineIndent",String(g));const u=new S.XmlText;let p=0;t.children.forEach(h=>{if(h.type==="text"){const f={...h.marks||{}};ne(u,p,h.text,f),p+=h.text.length}}),c.insert(0,[u]),o.delete(e,1),o.insert(e,[c])}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0)}pasteParagraphsAsSuggestions(e,t,n,i){let r={block:e.block,offset:e.offset},o={anchor:n.anchor?{...n.anchor}:null,focus:n.focus?{...n.focus}:null},a=!1;const l=()=>{const d=this.getAfterOperationSelection();return d?.focus?{block:d.focus.block,offset:d.focus.offset}:null};let c=null;if(this.transact(()=>{for(let d=0;d<t.length;d++){if(d>0){const g=this.splitParagraph(r,{anchor:r,focus:r});if(!g)return;r=g,o={anchor:r,focus:r}}for(const g of t[d].children){if(g.type!=="text"||g.text.length===0)continue;const u=this.suggestionEngine.stripSuggestionMarksFromTextMark(g.marks)??{};if(!this.insertFormattedText(r,g.text,u,o,{anchor:r,focus:r},i))return;a=!0;const p=l();p&&(r=p),o={anchor:r,focus:r}}}c=r}),!a&&!c)return null;if(c){const d={anchor:c,focus:c};this.setSelectionAfterOperation(d),this.afterOperationRelativeSelection=H(d,this.ydoc,this.getDocument())}return c}pasteParagraphs(e,t,n,i={}){if(t.length===0||!t.some(b=>b.children.some(k=>k.type==="text"&&k.text.length>0)))return null;const r=dt(Ni(this.getDocument(),e,n)?.marks);if(r?.fontFamily===Fe&&delete r.fontFamily,r&&(t=t.map(b=>b.type==="paragraph"?{...b,children:b.children.map(k=>k.type==="text"?{...k,marks:{...r,...k.marks??{}}}:k)}:b)),this.suggestingMode)return this.pasteParagraphsAsSuggestions(e,t,n,i.suggestionIdOverride);this.beforeOperationSelection={anchor:n.anchor?{...n.anchor}:null,focus:n.focus?{...n.focus}:null};const o=this.getDocument();this.beforeOperationRelativeSelection=H(n,this.ydoc,o);let a=null;const l=i.preserveStructure===!0&&t.length>1;let c,d=null,g=null,u=null,p=!1,h=null,f=null;const m=b=>{if(!b.id)return null;let k=0;for(const I of b.children)I.type==="text"&&(k+=I.text.length);return{block:b.id,offset:k}},y=b=>b.id?b:{...b,id:Y()};try{this.transact(()=>{const k=n.anchor&&n.focus&&Ie(o,n.anchor,n.focus)!==0;let I={block:e.block,offset:e.offset};if(k&&n.anchor&&n.focus){const D={block:e.block,offset:e.offset},X=n.anchor.block===D.block&&n.anchor.offset===D.offset,j=n.focus.block===D.block&&n.focus.offset===D.offset,U=D,q=X?{block:n.focus.block,offset:n.focus.offset}:j?{block:n.anchor.block,offset:n.anchor.offset}:Ie(o,n.anchor,n.focus)<=0?{block:n.focus.block,offset:n.focus.offset}:{block:n.anchor.block,offset:n.anchor.offset},oe=this.getParagraphOffsetForPosition(U,o),be=this.getParagraphOffsetForPosition(q,o);oe&&be&&this.arePathsEqual(oe.paragraphPath,be.paragraphPath)&&(d=be.offset);const Xe=oe?.offset??U.offset;this.deleteSelection({block:U.block,offset:U.offset},{block:q.block,offset:q.offset},{anchor:n.anchor?{block:n.anchor.block,offset:n.anchor.offset}:null,focus:n.focus?{block:n.focus.block,offset:n.focus.offset}:null},{anchor:{block:U.block,offset:U.offset},focus:{block:U.block,offset:U.offset}});const Oe=this.getDocument(),W=z(Oe,U.block);(W?.type==="paragraph"||W?.type==="list")&&W.id&&(I={block:W.id,offset:Xe})}const v=d!==null?o:this.getDocument(),x=this.getBlockContextById(v,I.block);if(!x){a=null;return}if(x.block.type==="list"){const D=t[0],X=D.children.filter(j=>j.type==="text").map(j=>j.text).join("");if(X){const j=D.children.find(q=>q.type==="text")?.marks||null,U=this.listOperations.insertTextInListItem(I,X,j);U&&(a=U)}return}if(x.block.type!=="paragraph"){a=null;return}const A=x.block;if(!A||A.type!=="paragraph"){a=null;return}const C=[],F=this.getParagraphOffsetForPosition(I,v)?.offset??0,E=d??F;let P=0;for(let D=0;D<A.children.length;D++){const X=A.children[D];if(X.type==="text"){const j=P;if(P+X.text.length>E){const U=Math.max(0,E-j);U<X.text.length&&C.push({type:"text",text:X.text.substring(U),marks:X.marks})}P+=X.text.length}}const B=C.length>0&&C.some(D=>D.text.length>0);if(p=B,B){let D=0;for(const j of A.children)j.type==="text"&&(D+=j.text.length);const X={block:A.id,offset:D};this.deleteSelection(I,X,{anchor:I,focus:X},{anchor:I,focus:I})}const w=t[0],T=K(this.ydoc,I.block);if(!T){a=null;return}const N=ae(T);if(!N){a=null;return}if(N.length===0&&w.type==="paragraph"){w.heading!==void 0?T.setAttribute("heading",String(w.heading)):T.removeAttribute("heading"),w.align?T.setAttribute("align",w.align):J(T,"align"),w.lineSpacing!==void 0?T.setAttribute("lineSpacing",String(w.lineSpacing)):J(T,"lineSpacing");for(const j of nl)J(T,j);pn(T,w);{const j=Ye(w);j!==void 0?T.setAttribute("pagination",j):J(T,"pagination")}w.styleId!==void 0?T.setAttribute("styleId",w.styleId):T.removeAttribute("styleId"),w.direction!==void 0?T.setAttribute("direction",w.direction):J(T,"direction"),w.tabStops!==void 0?T.setAttribute("tabStops",w.tabStops):J(T,"tabStops"),w.borders!==void 0?T.setAttribute("borders",w.borders):J(T,"borders"),w.shading!==void 0?T.setAttribute("shading",w.shading):J(T,"shading");const D=Re(w.leftIndent);D!==void 0?T.setAttribute("leftIndent",String(D)):J(T,"leftIndent");const X=De(w.firstLineIndent);X!==void 0?T.setAttribute("firstLineIndent",String(X)):J(T,"firstLineIndent")}const L=w.children.filter(D=>D.type==="text"),_=this.insertTextNodes(I,L);if(!_){a=null;return}if(g=_,a=_,t.length===1&&!B){u=_.block;return}const $=G(this.ydoc,I.block);if(!$)return;const R=$.yParent;let M=$.index+1;if(l){const D=[];let X=null;for(let j=1;j<t.length;j++){const U=y(t[j]);this.insertParagraphInternal(M,U,R),D.push(U.id),M++}if(B){const j={type:"paragraph",id:Y(),children:C.map(oe=>({type:"text",text:oe.text,marks:oe.marks?{...oe.marks}:void 0}))};A.heading!==void 0&&(j.heading=A.heading),A.align&&(j.align=A.align),A.direction!==void 0&&(j.direction=A.direction),A.tabStops!==void 0&&(j.tabStops=A.tabStops),A.lineSpacing!==void 0&&(j.lineSpacing=A.lineSpacing),A.spaceBefore!==void 0&&(j.spaceBefore=A.spaceBefore),A.spaceAfter!==void 0&&(j.spaceAfter=A.spaceAfter),A.contextualSpacing!==void 0&&(j.contextualSpacing=A.contextualSpacing),A.keepNext!==void 0&&(j.keepNext=A.keepNext),A.keepLines!==void 0&&(j.keepLines=A.keepLines),A.widowControl!==void 0&&(j.widowControl=A.widowControl);const U=Re(A.leftIndent);U!==void 0&&(j.leftIndent=U);const q=De(A.firstLineIndent);q!==void 0&&(j.firstLineIndent=q),this.insertParagraphInternal(M,j,R),X=j.id,M++}c={insertedParagraphIds:D,remainderParagraphId:X};return}let O=I.block;for(let D=1;D<t.length;D++){const X=y(t[D]);this.insertParagraphInternal(M,X,R),O=X.id,M++}if(u=O,B){const D=t.length>1?R.get(M-1):T;if(D instanceof S.XmlElement){let X=null;for(let j=0;j<D.length;j++){const U=D.get(j);if(U instanceof S.XmlText){X=U;break}}if(X){let j=X.length;h=j,f=O;for(const U of C){if(!U.text.length)continue;const q={...U.marks||{}};X.insert(j,U.text,q),j+=U.text.length}}}}});const b=this.getDocument();if(l&&c){const{insertedParagraphIds:k,remainderParagraphId:I}=c;if(k.length>0){const v=k[k.length-1],x=z(b,v);x&&x.type==="paragraph"?a=m(x):a={block:v,offset:0}}else if(I!==null){const v=z(b,I);v&&v.type==="paragraph"?a=m(v):a={block:I,offset:0}}else g&&(a=g)}else if(!l)if(p&&f!==null&&h!==null)a={block:f,offset:h};else if(p&&g)a=g;else if(u!==null){const k=z(b,u);k&&k.type==="paragraph"?a=m(k):g?a=g:a={block:u,offset:0}}else g&&(a=g);!a&&g&&(a=g)}catch(b){return console.error("Error in pasteParagraphs:",b),null}return a||(a=g??e),a&&(a=this.normalizeCursorPosition(a),this.setSelectionAfterOperation({anchor:a,focus:a}),this.updateAfterOperationRelativeSelection(this.getDocument())),a}normalizeCursorPosition(e){return this.getDocument().children.length,e}replaceDocument(e){return this.undoManager.stopCapturing(),this.transact(()=>{const t=this.getYContentFragment();t.length>0&&t.delete(0,t.length),e.children.forEach(n=>{if(n.type==="placeholder"){const i=new S.XmlElement("placeholder");i.setAttribute("id",n.id||Y()),i.setAttribute("height",String(n.height)),t.push([i])}else if(n.type==="image"){const i=n,r=new S.XmlElement("image");r.setAttribute("id",n.id||Y()),r.setAttribute("src",i.src),i.sourceUrl&&r.setAttribute("sourceUrl",i.sourceUrl),r.setAttribute("width",String(i.width)),r.setAttribute("height",String(i.height)),i.alt&&r.setAttribute("alt",i.alt),t.push([r])}else if(n.type==="paragraph"){const i=new S.XmlElement("paragraph");i.setAttribute("id",n.id||Y()),n.heading&&i.setAttribute("heading",String(n.heading)),n.align&&i.setAttribute("align",n.align),n.lineSpacing!==void 0&&i.setAttribute("lineSpacing",String(n.lineSpacing)),pn(i,n);{const c=Ye(n);c!==void 0&&i.setAttribute("pagination",c)}n.styleId!==void 0&&i.setAttribute("styleId",n.styleId),n.direction!==void 0&&i.setAttribute("direction",n.direction),n.tabStops!==void 0&&i.setAttribute("tabStops",n.tabStops),n.borders!==void 0&&i.setAttribute("borders",n.borders),n.shading!==void 0&&i.setAttribute("shading",n.shading);const r=Re(n.leftIndent);r!==void 0&&i.setAttribute("leftIndent",String(r));const o=De(n.firstLineIndent);o!==void 0&&i.setAttribute("firstLineIndent",String(o));const a=new S.XmlText;let l=0;n.children.forEach(c=>{if(c.type==="text"){const d={...c.marks||{}};ne(a,l,c.text,d),l+=c.text.length}}),i.insert(0,[a]),t.push([i])}else if(n.type==="list"){const i=n,r=new S.XmlElement("list");r.setAttribute("id",n.id||Y()),r.setAttribute("variant",i.variant),i.startNumber!==void 0&&r.setAttribute("startNumber",String(i.startNumber)),i.numberingChainId&&r.setAttribute("numberingChainId",i.numberingChainId),i.numberingFormat&&r.setAttribute("numberingFormat",i.numberingFormat),i.children.forEach(o=>{const a=new S.XmlElement("list-item");Ct(a,o),a.setAttribute("id",o.id||Y()),i.variant==="todo"&&a.setAttribute("checked",String(o.checked??!1)),o.indentLevel!==void 0&&o.indentLevel>0&&a.setAttribute("indentLevel",String(o.indentLevel)),o.direction!==void 0&&a.setAttribute("direction",o.direction);const l=new S.XmlText;let c=0;o.children.forEach(d=>{if(d.type==="text"){const g={...d.marks||{}};l.insert(c,d.text,g),c+=d.text.length}}),a.insert(0,[l]),r.push([a])}),t.push([r])}})}),this.undoManager.clear(),!0}alignNormalizationDirection(e,t){const n=e?.type==="paragraph"?e:void 0,i=Object.prototype.hasOwnProperty.call(t,"direction")?t.direction??void 0:n?.direction;let r="";if(n)for(const o of n.children)r+=o.text??"";return mc(i,r)}updateParagraphAttributes(e,t,n,i){this.beforeOperationSelection=n;const r=this.getDocument();if(this.beforeOperationRelativeSelection=H(n,this.ydoc,r),e<0||e>=r.children.length)return!1;(Object.prototype.hasOwnProperty.call(t,"leftIndent")||Object.prototype.hasOwnProperty.call(t,"firstLineIndent"))&&this.ensureParagraphIndentStorageUsesUnits();const o=this.alignNormalizationDirection(r.children[e],t);return this.transact(()=>{const a=this.getYContentFragment().get(e);if(a instanceof S.XmlElement){if(Object.prototype.hasOwnProperty.call(t,"align")&&(t.align===void 0||t.align==="left"&&o==="ltr"?J(a,"align"):a.setAttribute("align",t.align)),Object.prototype.hasOwnProperty.call(t,"heading")){t.heading===void 0?a.removeAttribute("heading"):a.setAttribute("heading",String(t.heading));const l=r.children[e];l&&!this.applyStylesheetHeadingDefaults(a,l,r,t.heading)&&this.clearFontSizeMarksForHeadingChange(l,r)}if(Object.prototype.hasOwnProperty.call(t,"lineSpacing")&&(t.lineSpacing===void 0?J(a,"lineSpacing"):a.setAttribute("lineSpacing",String(t.lineSpacing))),Object.prototype.hasOwnProperty.call(t,"styleId")&&(t.styleId===null||t.styleId===void 0?a.removeAttribute("styleId"):a.setAttribute("styleId",t.styleId)),Object.prototype.hasOwnProperty.call(t,"direction")&&(t.direction===null||t.direction===void 0?J(a,"direction"):a.setAttribute("direction",t.direction)),Object.prototype.hasOwnProperty.call(t,"tabStops")&&(t.tabStops===null||t.tabStops===void 0?J(a,"tabStops"):a.setAttribute("tabStops",t.tabStops)),Object.prototype.hasOwnProperty.call(t,"borders")&&(t.borders===null||t.borders===void 0?J(a,"borders"):a.setAttribute("borders",t.borders)),Object.prototype.hasOwnProperty.call(t,"shading")&&(t.shading===null||t.shading===void 0?J(a,"shading"):a.setAttribute("shading",t.shading)),Object.prototype.hasOwnProperty.call(t,"keepNext")||Object.prototype.hasOwnProperty.call(t,"keepLines")||Object.prototype.hasOwnProperty.call(t,"widowControl")){const l={};Ei(l,ee(a,"pagination"));for(const d of["keepNext","keepLines","widowControl"])Object.prototype.hasOwnProperty.call(t,d)&&(t[d]===void 0?delete l[d]:l[d]=t[d]);const c=Ye(l);c===void 0?J(a,"pagination"):a.setAttribute("pagination",c)}if(Object.prototype.hasOwnProperty.call(t,"leftIndent")){const l=Re(t.leftIndent);l===void 0?J(a,"leftIndent"):a.setAttribute("leftIndent",String(l))}if(Object.prototype.hasOwnProperty.call(t,"firstLineIndent")){const l=De(t.firstLineIndent);l===void 0?J(a,"firstLineIndent"):a.setAttribute("firstLineIndent",String(l))}}}),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0}applyStylesheetHeadingDefaults(e,t,n,i){if(t.type!=="paragraph"||!t.id)return!1;const r=n.stylesheet,o=Li(r,i);if(!r||!o)return!1;const a=(t.styleId?xs(r,t.styleId):void 0)??Li(r,t.heading);i!==void 0&&o.styleId.toLowerCase()!=="normal"?e.setAttribute("styleId",o.styleId):e.removeAttribute("styleId");const l=a?.paragraphAttrs??{},c=o.paragraphAttrs??{},d=(f,m)=>Object.prototype.hasOwnProperty.call(f,m),g=["align","lineSpacing","spaceBefore","spaceAfter","contextualSpacing","leftIndent","firstLineIndent","direction","borders","shading","tabStops"];(d(c,"leftIndent")||d(c,"firstLineIndent"))&&(c.leftIndent!==void 0||c.firstLineIndent!==void 0)&&this.ensureParagraphIndentStorageUsesUnits();for(const f of g){if(!d(l,f)&&!d(c,f))continue;const m=c[f];m===void 0||m===!1?J(e,f):e.setAttribute(f,String(m))}const u=["keepNext","keepLines","widowControl"];if(u.some(f=>d(l,f)||d(c,f))){const f={};Ei(f,ee(e,"pagination"));for(const y of u)!d(l,y)&&!d(c,y)||(c[y]===void 0?delete f[y]:f[y]=c[y]);const m=Ye(f);m===void 0?J(e,"pagination"):e.setAttribute("pagination",m)}const p=As(a?.runMarks,o.runMarks),h=t.children.reduce((f,m)=>m.type==="text"?f+m.text.length:f,0);if(h>0){const f=this.getYContentFragment(),m=this.collectInlineFormattingRanges({block:t.id,offset:0},{block:t.id,offset:h},f,n);for(const{yText:y,start:b,end:k}of m){const I=Math.max(0,k-b);I>0&&ie(y,b,I,p)}}else ki(e,o.runMarks);return!0}clearFontSizeMarksForHeadingChange(e,t){if(e.type!=="paragraph"||!e.id)return;const n=e.children.reduce((o,a)=>a.type==="text"?o+a.text.length:o,0);if(!e.children.some(o=>o.type==="text"&&o.marks?.fontSize!==void 0))return;if(n===0){this.updateEmptyTextMarksAtPosition({block:e.id,offset:0},"fontSize",void 0,t);return}const i=this.getYContentFragment(),r=this.collectInlineFormattingRanges({block:e.id,offset:0},{block:e.id,offset:n},i,t);for(const{yText:o,start:a,end:l}of r){const c=Math.max(0,l-a);c>0&&ie(o,a,c,{fontSize:!1})}}updateParagraphAttributesById(e,t,n,i){const r=z(this.getDocument(),e);if(!r||r.type!=="paragraph"&&r.type!=="list")return!1;const o=K(this.ydoc,e);if(!o)return!1;this.beforeOperationSelection=n;const a=this.getDocument();this.beforeOperationRelativeSelection=H(n,this.ydoc,a);const l=Object.prototype.hasOwnProperty.call(t,"leftIndent")||Object.prototype.hasOwnProperty.call(t,"firstLineIndent"),c=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(a,e),d=this.suggestingMode&&!c?ce():null;l&&this.ensureParagraphIndentStorageUsesUnits();const g=this.alignNormalizationDirection(z(a,e)??void 0,t);return this.transact(()=>{if(Object.prototype.hasOwnProperty.call(t,"align")&&(t.align===void 0||t.align==="left"&&g==="ltr"?J(o,"align"):o.setAttribute("align",t.align)),Object.prototype.hasOwnProperty.call(t,"heading")&&(t.heading===void 0?o.removeAttribute("heading"):o.setAttribute("heading",String(t.heading)),this.applyStylesheetHeadingDefaults(o,r,a,t.heading)||this.clearFontSizeMarksForHeadingChange(r,a)),Object.prototype.hasOwnProperty.call(t,"lineSpacing")&&(t.lineSpacing===void 0?J(o,"lineSpacing"):o.setAttribute("lineSpacing",String(t.lineSpacing))),Object.prototype.hasOwnProperty.call(t,"styleId")&&(t.styleId===null||t.styleId===void 0?o.removeAttribute("styleId"):o.setAttribute("styleId",t.styleId)),Object.prototype.hasOwnProperty.call(t,"direction")&&(t.direction===null||t.direction===void 0?J(o,"direction"):o.setAttribute("direction",t.direction)),Object.prototype.hasOwnProperty.call(t,"tabStops")&&(t.tabStops===null||t.tabStops===void 0?J(o,"tabStops"):o.setAttribute("tabStops",t.tabStops)),Object.prototype.hasOwnProperty.call(t,"borders")&&(t.borders===null||t.borders===void 0?J(o,"borders"):o.setAttribute("borders",t.borders)),Object.prototype.hasOwnProperty.call(t,"shading")&&(t.shading===null||t.shading===void 0?J(o,"shading"):o.setAttribute("shading",t.shading)),Object.prototype.hasOwnProperty.call(t,"keepNext")||Object.prototype.hasOwnProperty.call(t,"keepLines")||Object.prototype.hasOwnProperty.call(t,"widowControl")){const u={};Ei(u,ee(o,"pagination"));for(const h of["keepNext","keepLines","widowControl"])Object.prototype.hasOwnProperty.call(t,h)&&(t[h]===void 0?delete u[h]:u[h]=t[h]);const p=Ye(u);p===void 0?J(o,"pagination"):o.setAttribute("pagination",p)}if(Object.prototype.hasOwnProperty.call(t,"leftIndent")){const u=Re(t.leftIndent);u===void 0?J(o,"leftIndent"):o.setAttribute("leftIndent",String(u))}if(Object.prototype.hasOwnProperty.call(t,"firstLineIndent")){const u=De(t.firstLineIndent);u===void 0?J(o,"firstLineIndent"):o.setAttribute("firstLineIndent",String(u))}this.suggestingMode&&d&&(this.suggestionEngine.clearElementStructuralSuggestion(o),this.suggestionEngine.setElementStructuralSuggestion(o,"change",void 0,d,"Format"),this.suggestionEngine.saveLiveSuggestion({id:d,type:"block-change",blockId:e,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(r),label:"Format"}))}),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0}updateTocAttributesById(e,t,n,i){const r=z(this.getDocument(),e);if(!r||r.type!=="toc")return!1;const o=K(this.ydoc,e);return o?(this.beforeOperationSelection=n,this.beforeOperationRelativeSelection=H(n,this.ydoc,this.getDocument()),this.transact(()=>{Object.prototype.hasOwnProperty.call(t,"fontFamily")&&(t.fontFamily==null||t.fontFamily===""?o.removeAttribute("fontFamily"):o.setAttribute("fontFamily",t.fontFamily)),Object.prototype.hasOwnProperty.call(t,"fontSize")&&(t.fontSize==null?o.removeAttribute("fontSize"):o.setAttribute("fontSize",String(t.fontSize))),Object.prototype.hasOwnProperty.call(t,"color")&&(t.color==null||t.color===""?o.removeAttribute("color"):o.setAttribute("color",t.color))}),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0):!1}beginGroup(e){this.batchingUpdates=!0,this.pendingUpdate=null}endGroup(){if(this.undoManager.stopCapturing(),this.batchingUpdates=!1,this.pendingUpdate){const e=this.pendingUpdate;this.pendingUpdate=null,e()}}getHistoryInfo(){return{undoStackSize:this.undoManager.undoStack.length,redoStackSize:this.undoManager.redoStack.length}}clearHistory(){this.undoManager.clear()}extractTextNodesForRange(e,t,n){if(n<=t)return[];const i=[];let r=0;for(const o of e.children){if(o.type!=="text")continue;const a=r,l=r+o.text.length,c=Math.max(t,a),d=Math.min(n,l);if(c<d&&i.push({type:"text",text:o.text.slice(c-a,d-a),marks:this.suggestionEngine.sanitizePreviewMarks(o.marks)}),r=l,r>=n)break}return i}buildParagraphReplacementLiveBlock(e,t,n,i){const r=(g,u)=>g.map(p=>{const h=this.suggestionEngine.sanitizePreviewMarks(p.marks)??{};return delete h.deletion,delete h.insertion,delete h.formatChange,{type:"text",text:p.text,marks:{...h,[u]:!0,suggestionId:n}}}),o=r(e.children,"deletion"),a=r(t.children,"insertion"),l=o.map(g=>g.text).join(""),c=a.map(g=>g.text).join(""),d=l.length>0&&c.length>0&&!/\s$/.test(l)&&!/^\s/.test(c);return{...t,children:[...o,...d?[{type:"text",text:" "}]:[],...a],structuralSuggestionId:n,structuralSuggestionKind:"change",structuralSuggestionLabel:i}}canBridgeListItemChangeAsInline(e,t){return xn.every(n=>e[n]===t[n])&&e.direction===t.direction&&(e.checked??!1)===(t.checked??!1)&&(e.indentLevel??0)===(t.indentLevel??0)}replaceBlockByIdWithoutSelection(e,t,n){const i=n?n.yBlock._item:null,r=n&&!i?.deleted&&n.yParent.get(n.index)===n.yBlock,o=r?null:G(this.ydoc,e),a=r?n.yParent:o?.yParent,l=r?n.index:o?.index;return!a||l===void 0?!1:(this.transact(()=>{const c=a.get(l);if(t.type==="list"&&c instanceof S.XmlElement&&c.nodeName==="list"){_r(c,t);return}const d=this.blockToYjsElement(t);a.delete(l,1),a.insert(l,[d])}),!0)}paragraphReplaceShouldStayAtomic(e,t){return!Ht(e,t)}resolvePositionAwareInsertionReference(e){const t=[...e.mustBeAfter].reverse().find(r=>typeof r=="string"&&r.length>0);if(t)return{referenceId:t,position:"after"};const n=e.mustBeBefore.find(r=>typeof r=="string"&&r.length>0);if(n)return{referenceId:n,position:"before"};const i=e.baseDoc.children[0]?.id;return i?{referenceId:i,position:"before"}:e.baseDoc.children.length===0?{referenceId:Gt,position:"after"}:null}tryCancelInsertedBlockForRemoveAction(e,t){if(!e?.length)return null;const n=e.length===1?e[0]:void 0,i=n?.arguments;if(n?.name==="remove_block"&&typeof i?.count=="number"&&Number.isInteger(i.count)&&i.count>1){const c=t.children.findIndex(d=>d.id===i.id);if(c<0||c+i.count>t.children.length)return null;e=t.children.slice(c,c+i.count).map(d=>({name:"remove_block",arguments:{id:d.id}}))}const r=this.getDocument(),o=new Set,a=new Set,l=new Set;for(const c of e){if(c.name!=="remove_block")return null;const d=c.arguments;if(typeof d?.id!="string"||d.count!==void 0&&d.count!==1)return null;const g=z(r,d.id)??z(t,d.id),u=this.suggestionEngine.getBlockInsertSuggestionIdForBlock(g),p=u?this.suggestionEngine.getLiveSuggestion(u):void 0;if(!g)return null;if(o.add(d.id),!u){l.add(d.id);continue}if(p?.type!=="block-insert")return null;a.add(u)}for(const c of a){const d=this.suggestionEngine.getLiveSuggestion(c);d?.type==="block-insert"&&d.cleanupTrailingParagraphId&&l.delete(d.cleanupTrailingParagraphId)}if(l.size>0||a.size===0)return null;for(const c of a)if(this.collectStructuralInsertBlockIds(r,c).some(d=>!o.has(d)))return null;return this.suggestionEngine.rejectLiveSuggestions([...a])===0?null:{success:!0,planningSuggestionIds:[],agentFeedback:`Removed pending inserted block${o.size===1?"":"s"} ${[...o].join(", ")}.`}}getActionTargetBlockIds(e,t){if(!e)return[];const n=new Set;for(const i of e){const r=i.arguments&&typeof i.arguments=="object"?i.arguments:null;if(!r||typeof r.id!="string"||r.id.length===0)continue;const o=r.id;if(n.add(o),i.name!=="replace_block")continue;const a=typeof r.count=="number"&&Number.isFinite(r.count)?Math.max(1,Math.floor(r.count)):1;if(a<=1)continue;const l=Wt(t,o);if(!(l<0))for(let c=l+1;c<Math.min(t.children.length,l+a);c++){const d=t.children[c]?.id;d&&n.add(d)}}return Array.from(n)}applyAgentActions(e,t,n){if(t||(t="default-"+Date.now()),e.actions?.some(a=>a.name==="move_blocks")){if(e.actions.length!==1||e.actions[0].name!=="move_blocks")return{success:!1,error:"move_blocks must be the only action in its tool call."};const{block_ids:a,reference_id:l,position:c}=e.actions[0].arguments,d=this.getDocument(),g=h=>{throw new fe("invalid_move",h,"validation")};let u,p;try{(!Array.isArray(a)||!a.length||a.length>100||new Set(a).size!==a.length||a.some(M=>typeof M!="string"))&&g("Provide one to 100 unique top-level block IDs in document order."),c!=="before"&&c!=="after"&&g("position must be before or after.");const h=d.children.findIndex(M=>M.id===a[0]),f=d.children.findIndex(M=>M.id===l);(h<0||f<0||a.some((M,O)=>d.children[h+O]?.id!==M))&&g("Source blocks must be contiguous top-level blocks in document order, and the destination must be a current top-level block. Read the current section first.");const m=h+a.length-1;f>=h&&f<=m&&g("The destination is inside the source range; choose a reference block outside the range.");const y=d.children.slice(h,m+1),b=y[0].structuralSuggestionId??y[0].suggestionId;if(b){const M=(X,j)=>(X.structuralSuggestionId??X.suggestionId)===b&&(X.structuralSuggestionKind??X.diffState)===j;let O=!1;const D=X=>{try{JSON.parse(X.marks?.docxMove??"null")?.wholeBlocks&&X.marks?.suggestionId===b&&(O=!0)}catch{}X.children?.forEach(D)};if(y.forEach(D),O&&y.every(X=>M(X,"delete"))){const X=c==="after"?f+1:f-a.length,j=d.children.slice(X,X+a.length);if(j.length===a.length&&j.every(U=>M(U,"insert")))return{success:!0,resultCode:"already_satisfied",suggestionIds:[b],agentFeedback:`This move is already proposed at the requested destination; no additional changes were made. Destination block IDs: ${j.map(U=>U.id).join(", ")}.`};g(`These are the deleted originals of an existing pending Move. To correct that proposal, use its complete current destination range instead: ${d.children.filter(U=>M(U,"insert")).map(U=>U.id).join(", ")}. Do not move or anchor to the deleted originals.`)}}const k=M=>{const O=M.structuralSuggestionId??M.suggestionId;if(!O||(M.structuralSuggestionKind??M.diffState)!=="insert")return null;let D=!1;const X=j=>{if(j.marks?.comment||j.marks?.deletion||[j.suggestionId,j.structuralSuggestionId,j.marks?.suggestionId].some(U=>U&&U!==O)||j.structuralSuggestionKind&&j.structuralSuggestionKind!=="insert"||j.diffState&&j.diffState!=="insert")return!1;if(j.type==="text"&&j.text){D=!0;try{const U=JSON.parse(j.marks?.docxMove??"null");if(j.marks?.suggestionId!==O||!j.marks?.insertion||!U?.wholeBlocks||U.role!=="to")return!1}catch{return!1}}return!j.children||j.children.every(X)};return X(M)&&D?O:null},I=k(y[0]),v=I&&y.every(M=>k(M)===I)?I:null;if(v){const M=D=>{if(D.type==="text"&&D.text){const X=D.marks,j=JSON.parse(X.docxMove);if(X.suggestionSource!=="agent"||X.suggestionAuthorName!==(e.agentName??ze)||j.name!==`reviseMove-${v}`||X.suggestionAgentConversationId&&X.suggestionAgentConversationId!==e.agentConversationId)return!1}return!D.children||D.children.every(M)};y.every(M)||g("Only this agent's own pending Move can be repositioned. Review imported or other authors' moves first."),d.children.some(D=>(D.structuralSuggestionId??D.suggestionId)===v&&(D.structuralSuggestionKind??D.diffState)==="delete")||g("This pending Move has no original source; it cannot be repositioned safely.");const O=d.children.filter(D=>(D.structuralSuggestionId??D.suggestionId)===v&&(D.structuralSuggestionKind??D.diffState)==="insert");(O.length!==y.length||O.some((D,X)=>D.id!==a[X]))&&g("To correct a pending Move, supply its complete destination range in current document order; moving only part would split the linked change."),n?.applyBlockMovesDirectly&&g("An existing tracked Move must be corrected in suggesting mode.")}const x=k(d.children[f]);if(x){const M=d.children[f+(c==="after"?1:-1)];M&&(M.structuralSuggestionId??M.suggestionId)===x&&(M.structuralSuggestionKind??M.diffState)==="insert"&&g("Do not insert inside an existing multi-block Move destination. Anchor before its first block or after its last block.")}const A=new Set,C=M=>{M.id&&A.add(M.id),M.children?.forEach(C)};[...y,d.children[f]].forEach(C),this.getComments().some(M=>M.anchorBlockId&&A.has(M.anchorBlockId))&&g("Moving blocks with anchored comments is not supported yet; no change was made.");for(const M of this.getLiveSuggestionStore().values())this.suggestionEngine.liveSuggestionRecordTouchesAnyBlock(M,A)&&g("Source or destination has pending tracked changes; inspect those changes before moving it.");const F=M=>{(M.suggestionId||M.structuralSuggestionId||M.diffState||M.marks?.suggestionId||M.marks?.insertion||M.marks?.deletion||M.marks?.docxMove)&&g("Source and destination must have no pending tracked changes. Review them before moving these blocks."),M.marks?.comment&&g("Moving blocks with anchored comments is not supported yet; no change was made."),M.children?.forEach(F)};v||y.forEach(F),x||F(d.children[f]);const E=d.children.filter(M=>(M.structuralSuggestionKind??M.diffState)!=="delete"),P=E.findIndex(M=>M.id===a[0]),B=E.findIndex(M=>M.id===l);if(B===P-1&&c==="after"||B===P+a.length&&c==="before")return{success:!0,resultCode:"already_satisfied",...v?{suggestionIds:[v]}:{},agentFeedback:`These blocks are already at the requested position; no additional change was made. Current block IDs: ${a.join(", ")}. Continue with the remaining blocks.`};y.some(M=>!["paragraph","list","table"].includes(M.type))&&g("move_blocks currently supports paragraphs, lists and tables, including mixed ranges."),p=this.cloneYDoc(this.ydoc),this.agentMoveClientId??(this.agentMoveClientId=p.clientID),p.clientID=this.agentMoveClientId,u=new lt(he(p),()=>{},void 0,p,"agent-move-staging",!0,new rn,{canRepairIdentity:()=>!1});const w=u;if(v){w.transact(()=>{const j=w.getYContentFragment(),U=y.map(q=>K(p,q.id).clone());j.delete(h,y.length),j.insert(f-(h<f?y.length:0)+(c==="after"?1:0),U)});const M=w.getDocument().children,O=M.findIndex(j=>j.id===a[0]),D=M.filter(j=>(j.structuralSuggestionId??j.suggestionId)===v&&(j.structuralSuggestionKind??j.diffState)==="delete");(M[O-1]?.id===D.at(-1)?.id||M[O+y.length]?.id===D[0]?.id)&&g("This would put the blocks back at their original source; reject the Move instead of creating a move that goes nowhere."),M.filter(j=>(j.structuralSuggestionKind??j.diffState)!=="delete").at(-1)?.type!=="paragraph"&&g("Correcting this Move would remove the final caret paragraph. Choose a destination that leaves a paragraph at the document end.");const X=S.encodeStateAsUpdate(p,S.encodeStateVector(this.ydoc));return this.runWithUndoGroup("agent-block-move",()=>this.transact(()=>S.applyUpdate(this.ydoc,X,this.origin))),{success:!0,suggestionIds:[v],agentFeedback:`Corrected the destination of the existing tracked Move; its original source and accept/reject behavior are preserved. Destination block IDs remain: ${a.join(", ")}. Independent neighboring moves stay where they were.`}}const T=Y(),N=yg(y),L=new Set,_=M=>{M.id&&L.add(M.id),M.children?.forEach(_)};_(d),d.notes?.forEach(_);const $=M=>{if(M.id){for(;L.has(M.id);)M.id=Y();L.add(M.id)}M.children?.forEach($)};N.forEach($),w.suggestionEngine.withSuggestionMetadata({source:"agent",authorType:"ai",label:"Move",agentName:e.agentName??ze,commentThreadId:e.commentThreadId,agentModel:e.agentModel,agentConversationId:e.agentConversationId,agentRequestId:e.agentRequestId,agentTurn:e.agentTurn},()=>w.transact(()=>{const M=w.getYContentFragment(),O=(U,q)=>U instanceof S.XmlText?U.length?(ie(U,0,U.length,{...w.suggestionEngine.buildInlineSuggestionMetadataMarks(T,"Move"),...q==="from"?{deletion:!0}:{insertion:!0}}),U.length):0:U instanceof S.XmlFragment||U instanceof S.XmlElement?U.toArray().reduce((oe,be)=>oe+(be instanceof S.AbstractType?O(be,q):0),0):0;let D=0;for(const U of a){const q=K(p,U);D+=O(q,"from"),w.suggestionEngine.markDeletedBlockElement(q,T,"Move")}D||g("A tracked move requires text in the source range; empty-only moves are not supported.");const X=N.map(U=>w.blockToYjsElement(U));M.insert(f+(c==="after"?1:0),X);for(const U of X)O(U,"to"),w.suggestionEngine.markInsertedBlockElement(U,T,"Move");const j=M.toArray().filter(U=>!(U instanceof S.XmlElement&&(U.getAttribute("structuralSuggestionKind")==="delete"||U.getAttribute("diffState")==="delete"))).at(-1);if(j instanceof S.XmlElement&&j.nodeName!=="paragraph"){const U=w.blockToYjsElement({type:"paragraph",id:Y(),children:[{type:"text",text:""}]});M.insert(M.length,[U]),w.suggestionEngine.markInsertedBlockElement(U,T,"Move")}w.completeInternalTextMove([T],[T],T,{wholeBlocks:!0})||g("Unable to link both move halves; no change was made.")})),n?.applyBlockMovesDirectly&&w.acceptLiveSuggestions([T]);const R=S.encodeStateAsUpdate(p,S.encodeStateVector(this.ydoc));return this.runWithUndoGroup("agent-block-move",()=>this.transact(()=>S.applyUpdate(this.ydoc,R,this.origin))),{success:!0,suggestionIds:n?.applyBlockMovesDirectly?[]:[T],agentFeedback:n?.applyBlockMovesDirectly?`Moved ${a.length} block(s). Destination block IDs: ${N.map(M=>M.id).join(", ")}.`:`Moved ${a.length} block(s) as one tracked Move. Destination block IDs: ${N.map(M=>M.id).join(", ")}. Source IDs remain only in the before/review view.${x?` Positioned next to pending Move ${x}; if that move is rejected, these blocks stay where its destination was.`:""}`}}catch(h){return{success:!1,error:h instanceof Error?h.message:String(h),failure:Mt(h)}}finally{u?.dispose(),p?.destroy()}}const i=(e.actions??[]).filter(a=>a.name==="insert_footnote");if(i.length>0){const a=[];for(const d of i){const g=d.arguments??{},u=g.id??"";let p;try{p=Dc(this,u,g.find??"")}catch(f){return{success:!1,error:f instanceof Error?f.message:String(f),failure:Mt(f)}}const h=this.suggestingMode;this.suggestingMode=!0;try{const{result:f}=this.suggestionEngine.withSuggestionMetadata({source:"agent",authorType:"ai",label:g.kind==="endnote"?"Insert endnote":"Insert footnote",agentName:e.agentName??ze,agentModel:e.agentModel,commentThreadId:e.commentThreadId,agentConversationId:e.agentConversationId,agentRequestId:e.agentRequestId,agentTurn:e.agentTurn,historyOrigin:`live-suggestions:${t}`},()=>this.insertFootnote(p,g.text??"",{anchor:p,focus:p},g.kind==="endnote"?"endnote":"footnote"));if(!f)return{success:!1,error:"insert_footnote: failed to insert"};f.suggestionId&&a.push(f.suggestionId)}finally{this.suggestingMode=h}}const l={...e,actions:(e.actions??[]).filter(d=>d.name!=="insert_footnote")};if(l.actions.length===0)return{success:!0,suggestionIds:a};const c=this.applyAgentActions(l,t,n);return c.success&&(c.suggestionIds=[...c.suggestionIds??[],...a]),c}this.detachedSuggestionStore.getPendingSuggestions().size===0&&this.toolCallHistory.getAllToolCalls().length>0&&this.toolCallHistory.clear();let r;try{r=Cu(e,t,this.preprocessorSession,this.getDocument())}catch(a){const l=a instanceof jr?a:void 0,c=l?Me(l.action):void 0;return{success:!1,failure:Mt(l?.originalError??a),error:a instanceof Error?a.message:String(a),...l?{failedActions:[{actionIndex:l.actionIndex,actionName:l.action.name,error:l.message,failure:Mt(l.originalError),sourceEditIndex:c?.sourceEditIndex,sourceEditType:c?.sourceEditType}]}:{}}}if(n?.maxPreprocessedActions!==void 0&&(r.actions?.length??0)>n.maxPreprocessedActions)return{success:!1,error:`This edit expands to ${r.actions.length} tracked changes, above the per-call limit of ${n.maxPreprocessedActions}. Split it into smaller edits, or use replace_document_content/import_document when replacing most of a document.`};const o=gl(e.actions,r.actions);if(r.actions){for(const g of r.actions)if(g.name==="set_title")this.setTitle(g.arguments.title),g.arguments.title;else if(g.name==="set_notes"){const u=g.arguments?.notes,p=typeof u=="string"?u:u==null?"":String(u);this.setNotes(p)}else if(g.name==="set_page_layout"){const u=this.applySetPageLayoutAction(g.arguments??{});if(u.error)return{success:!1,error:`set_page_layout: ${u.error}`}}else g.name==="set_header_footer"&&this.applySetHeaderFooterAction(g.arguments??{});const a={...r,actions:r.actions.filter(g=>g.name!=="set_title"&&g.name!=="set_notes"&&g.name!=="set_page_layout"&&g.name!=="set_header_footer")},l=a.actions.length>=100,c=Date.now(),d=g=>{l&&(`${a.actions.length}${g}`,Date.now()-c)};if(d("preprocessed"),a.actions.length>0){const g=this.suggestionEngine.getLiveSuggestionIds().length>0;let u,p,h,f;if(g){const w=this.suggestionEngine.createLiveSuggestionProjection("accept"),T=this.suggestionEngine.createLiveSuggestionProjection("reject");u=w.doc,p=T.doc,h=this.cloneYDoc(w.ydoc),f=this.cloneYDoc(T.ydoc)}else u=this.getDocument(),p=u,h=this.cloneYDoc(this.ydoc),f=this.cloneYDoc(this.ydoc);const m=u,y=this.tryCancelInsertedBlockForRemoveAction(a.actions,m);if(y)return y;const{anchorsByAction:b,failures:k,alreadySatisfied:I}=fg(h,a.actions,t,m,{rejectUnchangedAction:!0,continueAfterError:!0,canonicalDocument:()=>he(h),skipContextForFirstAction:!0});d("validated");const v=a.actions.length===1?Me(a.actions[0])?.styleEffects:void 0;if(k.length>0){const w=T=>`${T.actionName}: ${T.error}`;return k.length===1?{success:!1,error:`Failed operation: ${w(k[0])}`,failedActions:k,failure:k[0]?.failure}:{success:!1,error:`Failed operations: ${k.map(w).join("; ")}`,failedActions:k,failure:k[0]?.failure}}if(I)return h.destroy(),f.destroy(),{success:!0,resultCode:"already_satisfied",styleEffects:v,suggestionIds:[],planningSuggestionIds:[],agentFeedback:(a.actions.length===1?nr(a.actions[0]):void 0)??"Verified that the requested state is already satisfied; no document change was needed."};this.toolCallHistory.addToolCalls(a,t);const x=(a.actions.length===1?nr(a.actions[0]):void 0)??gl(e.actions,r.actions,b)??o,A=he(h);d("materialized validation document");const C=new Set,F=w=>{if(!w)return;C.add(w);const T=z(m,w)??z(A,w);T?.id&&C.add(T.id)};for(const w of b)for(const T of w)typeof T?.paragraphId=="string"&&T.paragraphId.length>0&&F(T.paragraphId);for(const w of a.actions){const T=w?.name,N=w?.arguments;(T==="replace"||T==="replace_all"||T==="replace_many"||T==="replace_block"||T==="remove_block"||T==="set_block_attribute"||T==="clear_block_formatting")&&typeof N?.id=="string"&&N.id.length>0&&F(N.id),typeof N?.referenceId=="string"&&N.referenceId.length>0&&F(N.referenceId),typeof N?.tableId=="string"&&N.tableId.length>0&&F(N.tableId)}const E=Yh(m,a.actions);for(const w of E)C.add(w.currentBlockId),C.add(w.finalBlockId);this.suggestionEngine.expandPendingSequenceBlockIds(C);const P=C.size>0||E.length>0?{...C.size>0?{affectedBlockIds:Array.from(C)}:{},...E.length>0?{replacementBlockMatches:E}:{}}:void 0,B=this.suggestionEngine.applyValidatedAgentActionsAsSuggestions({validationFork:h,baseFork:f,flattenOptions:P,toolCallId:t,originalActions:e.actions,processedActions:r.actions,validationAnchorsByAction:b,docBeforeToolCall:m,docAfterToolCall:A,baseDocForSuggestions:p,agentFeedback:x,agentName:e.agentName,agentModel:e.agentModel,commentThreadId:e.commentThreadId,agentConversationId:e.agentConversationId,agentRequestId:e.agentRequestId,agentTurn:e.agentTurn,optimizeStyleFormatting:n?.optimizeStyleFormatting});return d("applied live suggestions"),this.materializePendingFootnoteBodies(),{...B,styleEffects:v}}}return{success:!0,planningSuggestionIds:[],agentFeedback:o}}getAllOperations(){return[]}onRemoteDocumentChange(e){}insertBlock(e,t,n,i){this.beforeOperationSelection=n;const r=this.suggestingMode?ce():null,o=e.id||Y(),a=this.getDocument();if(t<0||t>a.children.length)return!1;const l=Qe().getHandlerForBlock(e);this.beforeOperationRelativeSelection=l.allowsInternalCursor()?H(n,this.ydoc,a):null,this.transact(()=>{const d=this.getYContentFragment(),g={...e,id:o};let u;if(g.type==="list"){const p=g,h=new S.XmlElement("list");h.setAttribute("variant",p.variant),p.id&&h.setAttribute("id",p.id),p.startNumber!==void 0&&h.setAttribute("startNumber",String(p.startNumber)),p.numberingChainId&&h.setAttribute("numberingChainId",p.numberingChainId),p.numberingFormat&&h.setAttribute("numberingFormat",p.numberingFormat);const f=[];p.children.forEach(m=>{const y=new S.XmlElement("list-item");Ct(y,m),m.id&&y.setAttribute("id",m.id),m.checked!==void 0&&y.setAttribute("checked",String(m.checked)),m.indentLevel!==void 0&&y.setAttribute("indentLevel",String(m.indentLevel)),m.direction!==void 0&&y.setAttribute("direction",m.direction);const b=new S.XmlText;let k=0;m.children.forEach(I=>{if(I.type==="text"){const v=I.marks?{...I.marks}:void 0;ne(b,k,I.text,v),k+=I.text.length}}),y.insert(0,[b]),f.push(y)}),h.insert(0,f),u=h}else u=l.toYjs(g,this.ydoc);r&&u instanceof S.XmlElement&&(u.setAttribute("id",o),this.suggestionEngine.markInsertedBlockElement(u,r)),d.insert(t,[u])}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=l.allowsInternalCursor()?H(i,this.ydoc,this.getDocument()):null;const c=this.ensureTrailingParagraph();return r&&this.suggestionEngine.saveLiveSuggestion({id:r,type:"block-insert",blockId:o,label:"Insert",cleanupTrailingParagraphId:c??void 0}),!0}ensureTrailingParagraph(){const e=this.getYContentFragment();if(e.length===0)return null;const t=e.get(e.length-1);if(t instanceof S.XmlElement&&t.nodeName==="paragraph")return null;const n=new S.XmlElement("paragraph"),i=Y();n.setAttribute("id",i);const r=new S.XmlText;return n.insert(0,[r]),this.transact(()=>{e.insert(e.length,[n])}),i}getComments(){return $g(this.kernel)}addComment(e,t,n,i,r){return Lg(this.kernel,e,t,n,i,r)}addCommentToRanges(e,t,n){return vr(this.kernel,e,t,n)}addBlockComment(e,t,n){return ha(this.kernel,e,t,n)}addCommentForSuggestion(e,t,n){return this.addCommentForSuggestions([e],t,n)}getSuggestionCommentRanges(e){return Fg(this.kernel,e)}addCommentForSuggestions(e,t,n){const i=Array.from(new Set(e)).filter(a=>typeof a=="string"&&a.length>0);if(i.length===0)return null;const r=this.getSuggestionCommentRanges(i).map(({blockId:a,start:l,end:c})=>({blockId:a,start:l,end:c})),o={...n,suggestionId:i[0],...i.length>1?{relatedSuggestionIds:i}:{}};if(r.length>0)return vr(this.kernel,r,t,o);for(const a of i){const l=this.getLiveSuggestion(a),c=l&&"blockId"in l?l.blockId:l&&"firstBlockId"in l?l.firstBlockId:void 0;if(c)return ha(this.kernel,c,t,o)}return null}replyToComment(e,t,n){return Og(this.kernel,e,t,n)}relinkCommentSuggestionIds(){return _g(this.kernel,e=>this.suggestionEngine.canResolveLiveSuggestion(e))}resolveCommentsForSettledSuggestions(e){return Dg(this.kernel,e,t=>this.suggestionEngine.canResolveLiveSuggestion(t))}setCommentResolved(e,t){return Rg(this.kernel,e,t)}deleteComment(e){return jg(this.kernel,e)}isBlockInsideFootnote(e,t){return Xg(e,t)}getFootnotes(){return Ug(this.kernel)}renumberFootnotes(){return It(this.kernel)}materializePendingFootnoteBodies(){return pa(this.kernel)}addPastedFootnoteBodies(e){const t=this.getYNotesFragment();t.insert(t.length,e.map(n=>this.kernel.blockToYjsElement(n))),this.reconcileFootnotes()}reconcileFootnotes(){zg(this.kernel)}insertFootnote(e,t,n,i="footnote"){return Wg(this.kernel,e,t,n,i)}setFootnoteBodyText(e,t){return Yg(this.kernel,e,t)}replaceFootnoteBodyText(e,t,n,i=!1){return qg(this.kernel,e,t,n,i)}convertAllNoteKinds(e){return Jg(this.kernel,e)}removeFootnote(e){return Kg(this.kernel,e)}blockToYjsElement(e){const t={...e,id:e.id||Y()};return t.type==="list"?Se(t):Qe().getHandlerForBlock(t).toYjs(t,this.ydoc)}insertBlockAfterId(e,t,n,i){const r=G(this.ydoc,t);if(!r)return!1;const{yParent:o,index:a}=r;this.beforeOperationSelection=n;const l=this.suggestingMode?ce():null,c=e.id||Y();this.transact(()=>{const g=this.blockToYjsElement(e);l&&g instanceof S.XmlElement&&(g.setAttribute("id",c),this.suggestionEngine.markInsertedBlockElement(g,l)),o.insert(a+1,[g])}),this.setSelectionAfterOperation(i),this.updateAfterOperationRelativeSelection(this.getDocument());const d=this.ensureTrailingParagraph();return l&&this.suggestionEngine.saveLiveSuggestion({id:l,type:"block-insert",blockId:c,label:"Insert",cleanupTrailingParagraphId:d??void 0}),!0}insertBlockBeforeId(e,t,n,i){const r=G(this.ydoc,t);if(!r)return!1;const{yParent:o,index:a}=r;this.beforeOperationSelection=n;const l=this.suggestingMode?ce():null,c=e.id||Y();this.transact(()=>{const g=this.blockToYjsElement(e);l&&g instanceof S.XmlElement&&(g.setAttribute("id",c),this.suggestionEngine.markInsertedBlockElement(g,l)),o.insert(a,[g])}),this.setSelectionAfterOperation(i),this.updateAfterOperationRelativeSelection(this.getDocument());const d=this.ensureTrailingParagraph();return l&&this.suggestionEngine.saveLiveSuggestion({id:l,type:"block-insert",blockId:c,label:"Insert",cleanupTrailingParagraphId:d??void 0}),!0}insertBlockIntoParent(e,t,n,i){const r=G(this.ydoc,t);if(!r)return!1;const{yBlock:o}=r;if(!(o instanceof S.XmlElement))return!1;const a=o.nodeName;if(!(a==="container"||a==="table-cell"))return!1;this.beforeOperationSelection=n;const l=this.suggestingMode?ce():null,c=e.id||Y();return this.transact(()=>{const d=this.blockToYjsElement(e);l&&d instanceof S.XmlElement&&(d.setAttribute("id",c),this.suggestionEngine.markInsertedBlockElement(d,l)),o.insert(0,[d])}),this.setSelectionAfterOperation(i),this.updateAfterOperationRelativeSelection(this.getDocument()),l&&this.suggestionEngine.saveLiveSuggestion({id:l,type:"block-insert",blockId:c,label:"Insert"}),!0}insertBlockAtStart(e,t,n){return this.insertBlock(e,0,t,n)}insertBlockAtEnd(e,t,n){const i=this.getDocument();return this.insertBlock(e,i.children.length,t,n)}updateBlock(e,t,n,i){this.beforeOperationSelection=n;const r=this.getDocument();if(e<0||e>=r.children.length)return!1;const o=r.children[e];if(o.type!==t.type)return console.warn(`[DocumentMutator] updateBlock type mismatch: ${o.type} -> ${t.type}`),!1;const a=Qe().getHandlerForBlock(t);return this.beforeOperationRelativeSelection=a.allowsInternalCursor()?H(n,this.ydoc,r):null,Tt(this.ydoc)&&Vl(this.ydoc),this.transact(()=>{const l=this.getYContentFragment();if(e<0||e>=l.length)return;const c={...t,id:t.id||o.id||Y()},d=l.get(e);if(t.type==="list"&&d instanceof S.XmlElement&&d.nodeName==="list")_r(d,c);else{const g=c.type==="list"?Se(c):a.toYjs(c,this.ydoc);l.delete(e,1),l.insert(e,[g])}}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=a.allowsInternalCursor()?H(i,this.ydoc,this.getDocument()):null,!0}updateBlockById(e,t,n,i){this.beforeOperationSelection=n;const r=this.getDocument(),o=z(r,e);if(!o)return!1;if(o.type!==t.type)return console.warn(`[DocumentMutator] updateBlockById type mismatch: ${o.type} -> ${t.type}`),!1;const a=G(this.ydoc,e);if(!a)return!1;const{yParent:l,index:c}=a,d=Qe().getHandlerForBlock(t),g=this.suggestingMode?ce():null;let u=t,p=null;if(this.suggestingMode&&g&&o.type==="table"&&t.type==="table"){const h=this.suggestionEngine.buildSuggestedTableChange(o,t,g);if(h)u=h.liveBlock,p=h.record;else if(!this.suggestionEngine.hasSameTableGeometry(o,t))return!1}return this.beforeOperationRelativeSelection=d.allowsInternalCursor()?H(n,this.ydoc,r):null,this.transact(()=>{const h={...u,id:u.id||o.id||Y()},f=l.get(c);if(u.type==="list"&&f instanceof S.XmlElement&&f.nodeName==="list")_r(f,h);else{const m=h.type==="list"?Se(h):d.toYjs(h,this.ydoc);l.delete(c,1),l.insert(c,[m])}p&&this.suggestionEngine.saveLiveSuggestion(p)}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=d.allowsInternalCursor()?H(i,this.ydoc,this.getDocument()):null,!0}replaceParagraphById(e,t,n,i){this.beforeOperationSelection=n;const r=this.getDocument();if(!z(r,e))return!1;const o=G(this.ydoc,e);if(!o)return!1;const{yBlock:a,yParent:l,index:c}=o;return this.beforeOperationRelativeSelection=H(n,this.ydoc,r),this.transact(()=>{const d=a instanceof S.XmlElement?a.getAttribute("id"):void 0,g=new S.XmlElement("paragraph");g.setAttribute("id",t.id||d||Y()),t.heading&&g.setAttribute("heading",String(t.heading)),t.align&&g.setAttribute("align",t.align),t.lineSpacing!==void 0&&g.setAttribute("lineSpacing",String(t.lineSpacing)),pn(g,t);{const m=Ye(t);m!==void 0&&g.setAttribute("pagination",m)}t.styleId!==void 0&&g.setAttribute("styleId",t.styleId),t.direction!==void 0&&g.setAttribute("direction",t.direction),t.tabStops!==void 0&&g.setAttribute("tabStops",t.tabStops),t.borders!==void 0&&g.setAttribute("borders",t.borders),t.shading!==void 0&&g.setAttribute("shading",t.shading),t.oxmlAttrs!==void 0&&g.setAttribute("oxmlAttrs",t.oxmlAttrs),t.oxmlPPr!==void 0&&g.setAttribute("oxmlPPr",t.oxmlPPr);const u=Re(t.leftIndent);u!==void 0&&g.setAttribute("leftIndent",String(u));const p=De(t.firstLineIndent);p!==void 0&&g.setAttribute("firstLineIndent",String(p));const h=new S.XmlText;let f=0;t.children.forEach(m=>{if(m.type==="text"){const y={...m.marks||{}};ne(h,f,m.text,y),f+=m.text.length}}),g.insert(0,[h]),l.delete(c,1),l.insert(c,[g])}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=H(i,this.ydoc,this.getDocument()),!0}toggleTodoItem(e,t,n,i,r){const o=this.getDocument(),a=o.children[e];if(!a||a.type!=="list"||a.variant!=="todo"||t<0||t>=a.children.length)return!1;this.beforeOperationSelection=i;const l=Qe().getHandlerForBlock(a);return this.beforeOperationRelativeSelection=l?.allowsInternalCursor()?H(i,this.ydoc,o):null,this.transact(()=>{const c=this.getYContentFragment().get(e);if(!(c instanceof S.XmlElement))return;let d=0;for(let g=0;g<c.length;g++){const u=c.get(g);if(u instanceof S.XmlElement&&u.nodeName==="list-item"){if(d===t){n?u.setAttribute("checked","true"):u.removeAttribute("checked");return}d++}}}),this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=l?.allowsInternalCursor()?H(r,this.ydoc,this.getDocument()):null,!0}toggleTodoItemById(e,t,n,i,r){const o=this.getDocument(),a=z(o,e);if(!a||a.type!=="list"||a.variant!=="todo"||t<0||t>=a.children.length)return!1;const l=G(this.ydoc,e);if(!l)return!1;const{yBlock:c}=l;this.beforeOperationSelection=i;const d=Qe().getHandlerForBlock(a);return this.beforeOperationRelativeSelection=d?.allowsInternalCursor()?H(i,this.ydoc,o):null,this.transact(()=>{if(!(c instanceof S.XmlElement))return;let g=0;for(let u=0;u<c.length;u++){const p=c.get(u);if(p instanceof S.XmlElement&&p.nodeName==="list-item"){if(g===t){n?p.setAttribute("checked","true"):p.removeAttribute("checked");return}g++}}}),this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=d?.allowsInternalCursor()?H(r,this.ydoc,this.getDocument()):null,!0}};ul.DEFERRED_IDENTITY_REPAIR_MS=1500;let Ii=ul;function Zr(s,e,t){const n=i=>i&&i.block===e?{...i,offset:Ii.remapOffsetAcrossReplacementNormalization(i.offset,t)}:i;return{anchor:n(s.anchor),focus:n(s.focus)}}const qh=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_FONT_FAMILY:Fe,DocumentMutator:Ii,MAX_BULK_LIVE_SUGGESTION_RESOLUTION_PASSES:el,copyMarksForUserInsertion:tl,enrichReplaceBlockFeedbackWithChangeSummary:dl,extractTextForChangeSummary:Ne,parseLayeredInsertion:fn,parseSuggestionPriorAttributes:yi,remapSelectionAcrossReplacementNormalization:Zr,sanitizeSuggestionPriorAttributes:hn},Symbol.toStringTag,{value:"Module"}));export{te as A,Ii as D,rn as P,td as a,Zc as b,lo as c,Qi as d,me as e,Ki as f,ro as g,Gi as h,ra as i,Xs as j,Et as k,Ln as l,Oc as m,Gs as n,Rc as o,to as p,io as q,Yc as r,so as s,Ui as t,et as u,Js as v,no as w,qh as x};