revise 2.1.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +47 -1088
- package/LICENSE +24 -41
- package/README.md +103 -26
- package/agent.d.ts +139 -0
- package/chunks/chunk-U5X47PZ6.js +135 -0
- package/chunks/chunk-U6YKQBKL.js +15 -0
- package/chunks/chunk-ZLQVPMBN.js +1650 -0
- package/chunks/package-5SHL5FOJ.js +14 -0
- package/chunks/render-QD5VWKSV.js +109 -0
- package/cli-output.schema.json +1984 -0
- package/cli.js +3604 -0
- package/document.d.ts +320 -0
- package/docx.d.ts +73 -0
- package/errors.d.ts +14 -0
- package/index.d.ts +13 -967
- package/index.js +31 -1
- package/legacy/editor.d.ts +19 -0
- package/legacy/editor.js +16 -0
- package/legacy/server.d.ts +37 -0
- package/legacy/server.js +25 -0
- package/legacy/style.css +2 -0
- package/package.d.ts +23 -0
- package/package.json +49 -55
- package/render.d.ts +27 -0
- package/FONT-LICENSE-HAN-EXT-B.txt +0 -91
- package/FONT-LICENSE-KATEX.txt +0 -95
- package/FONT-LICENSE-LIBERATION.txt +0 -102
- package/FONT-LICENSE-NOTO-MULTILINGUAL.txt +0 -93
- package/FONT-LICENSE-NOTO-SANS-SC.txt +0 -93
- package/FONT-LICENSE-NOTO.txt +0 -94
- package/FONT-LICENSE-SOURCE-CODE-PRO.txt +0 -94
- package/FONT-LICENSE-SOURCE-SERIF-4.txt +0 -93
- package/THIRD-PARTY-NOTICES.md +0 -3376
- package/assets/historyMaterializeWorker-C4uxcZEh.js +0 -607
- package/backend.d.ts +0 -155
- package/backend.js +0 -3
- package/chunks/AgentPageRenderer-BFB0arQL.js +0 -1
- package/chunks/AgentPageRenderer-Dn6SaRjW.js +0 -1
- package/chunks/AttachmentDocumentImporter-BHDJAdky.js +0 -1
- package/chunks/AttachmentDocumentImporter-CxOZqzt1.js +0 -1
- package/chunks/BidiText-C8PBPSQY.js +0 -160
- package/chunks/ColorParserFull-BKH72fK8.js +0 -446
- package/chunks/DocumentMutator-4vBJQ74L.js +0 -31
- package/chunks/DocumentScrubber-COPepQKE.js +0 -1
- package/chunks/DocumentScrubber-Cf_QqHhF.js +0 -1
- package/chunks/DocumentScrubber-DS4LFDKS.js +0 -18
- package/chunks/DocumentStylesheet-byN5dtC6.js +0 -7
- package/chunks/DocxConverter-BCEB7jWY.js +0 -1083
- package/chunks/DocxConverter-C3NflpDr.js +0 -11
- package/chunks/DocxConverter-D9ZNn4nX.js +0 -11
- package/chunks/DocxGraft-Ba63IRP4.js +0 -1
- package/chunks/DocxGraft-DjERgl-z.js +0 -7
- package/chunks/DocxGraft-cYlmw4Ab.js +0 -1
- package/chunks/FileImporter-CHXj9sNX.js +0 -1
- package/chunks/FileImporter-DetvRoJc.js +0 -1
- package/chunks/HorizontalRuleOrnaments-gmUZ3R7Q.js +0 -3
- package/chunks/HtmlConverter-Sd9t49vH.js +0 -267
- package/chunks/ListNumbering-Qlu6AuRZ.js +0 -23
- package/chunks/MarkdownConverter-BdJgh8xt.js +0 -57
- package/chunks/MathRenderer-B0Y1h1JU.js +0 -62
- package/chunks/OdtConverter-BKtyx012.js +0 -1
- package/chunks/OdtConverter-Ce9j8PRt.js +0 -1
- package/chunks/OdtConverter-D709qfYb.js +0 -31
- package/chunks/ParagraphDiffAnalysis-DrmStvmz.js +0 -36
- package/chunks/PdfConverter-BA8XLTAM.js +0 -21
- package/chunks/PdfConverter-CkDClffR.js +0 -438
- package/chunks/PdfConverter-CxLxd-LJ.js +0 -21
- package/chunks/PdfImportService-CQCgsRX1.js +0 -2
- package/chunks/PdfImportService-xl7fstr-.js +0 -2
- package/chunks/RtfConverter-BZOnMUGH.js +0 -14
- package/chunks/RtfConverter-Bs81AfXt.js +0 -14
- package/chunks/RtfConverter-DfuE5olb.js +0 -45
- package/chunks/TableBorders-Cdkc62cX.js +0 -30
- package/chunks/TableGrid-DbroRucl.js +0 -12
- package/chunks/TextFileDecoder--rsVs3NR.js +0 -9
- package/chunks/TxtConverter-C-oiFUAp.js +0 -14
- package/chunks/UnicodeUtils-CXtusU4g.js +0 -10
- package/chunks/XmlConverter-C0FnrVYk.js +0 -70
- package/chunks/XmlConverter-CQa8baOF.js +0 -2
- package/chunks/XmlConverter-DjEYaIyf.js +0 -2
- package/chunks/__vite-browser-external-l0sNRNKZ.js +0 -0
- package/chunks/_commonjsHelpers-DaMA6jEr.js +0 -2
- package/chunks/_revise-sdk-lazy-harfbuzz-CDWdjF9f.js +0 -1
- package/chunks/_revise-sdk-lazy-harfbuzz-X8gnYTZL.js +0 -1
- package/chunks/ar-BdmGnaKI.js +0 -14
- package/chunks/backend-BIhAX-Gi.js +0 -484
- package/chunks/base64-Qx0OzT4p.js +0 -196
- package/chunks/browser-module-CFmqfGkE.js +0 -1791
- package/chunks/browser-module-CYGCfEyx.js +0 -3
- package/chunks/browser-module-DgvTMhpA.js +0 -3
- package/chunks/bundle.min-DRpfgV69.js +0 -782
- package/chunks/capture-BAJ2in5p.js +0 -9
- package/chunks/carrier-C5VZRMxZ.js +0 -6
- package/chunks/de-DldIXRFC.js +0 -14
- package/chunks/es-CnyKlSPK.js +0 -14
- package/chunks/footnoteFlatten-Bekh8ZfM.js +0 -6
- package/chunks/graftExport-CRRm1Oe_.js +0 -82
- package/chunks/html2canvas.esm-CntiHiYW.js +0 -997
- package/chunks/index-B1idHquf.js +0 -1094
- package/chunks/index-BWdRWxoH.js +0 -1807
- package/chunks/index-C-4H81OE.js +0 -378
- package/chunks/index-iZC8xN0t.js +0 -378
- package/chunks/index.es-Bwt05m_b.js +0 -5
- package/chunks/index.es-CI0QPo8w.js +0 -780
- package/chunks/index.es-DAQD57G4.js +0 -5
- package/chunks/jspdf.es.min-CnNRolk9.js +0 -77
- package/chunks/jspdf.es.min-DU74zN8b.js +0 -1792
- package/chunks/jspdf.es.min-DlTF8uTw.js +0 -77
- package/chunks/jszip.min-CPW0h1Kx.js +0 -476
- package/chunks/katex-DWj8TvwO.js +0 -1462
- package/chunks/pdf-BLWDCiFF.js +0 -1828
- package/chunks/persistInlineDocumentImages-DQj2iaqg.js +0 -1
- package/chunks/pseudoLocale-BoJwIubw.js +0 -1
- package/chunks/pseudoLocale-DWAm7Dpa.js +0 -1
- package/chunks/purify.es-BwLardii.js +0 -107
- package/chunks/serverDocumentSession-DASrQAbW.js +0 -15
- package/chunks/signatures-CBF7NZUy.js +0 -17
- package/chunks/tree-sitter-D6zWWUMP.js +0 -4
- package/chunks/wasmInline.generated-CBYFkdSM.js +0 -1
- package/chunks/web-tree-sitter-BXGZGnNj.js +0 -2
- package/full.js +0 -1
- package/root.d.ts +0 -5
- package/root.js +0 -2
- package/serverToolContract.d.ts +0 -391
- package/serverToolInputs.generated.d.ts +0 -250
- package/style.css +0 -1
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import{r as Ke,p as Pe,c as Gr,a as Zr,e as sl,n as Ii,f as al,j as ll,H as vi,S as cl,k as kn,l as Qr,q as xi,s as Re,u as eo,v as De,w as Y,x as Q,z as dl,A as gl,B as ul,C as hl,D as fl,E as to,P as Ve,F as Ai,G as wi,I as no,J as pl,K as io,L as q,M as ke,y as he,N as G,O as te,Q as ne,T as ct,U as J,V as Ut,W as re,X as se,Y as ro,Z as oo,_ as ml,$ as so,a0 as We,a1 as Ht,a2 as bl,a3 as yl,a4 as kl,a5 as Sn,a6 as Sl,a7 as Il,a8 as vl,a9 as dt,aa as xl,ab as ao,ac as Al,ad as wl,ae as Tl,af as lo,ag as Cl,ah as ce,ai as Ti,aj as gt,ak as Tt,al as In,am as Ct,an as co,ao as vn,ap as xn,aq as Pl,ar as An,as as Bl,at as $l,d as Ci,au as go,av as uo,aw as ho,ax as Fl,ay as Pi,az as El,aA as Ll,aB as Ml,aC as Nl,aD as Ue,aE as Ol,aF as Bi,aG as Rl,aH as Dl,aI as _l,aJ as jl,aK as Xl,aL as $i,aM as Ul,aN as Hl,aO as fo}from"./backend-BIhAX-Gi.js";import{f as X,a as zt,r as zl,g as Wl,h as Ye,t as wn,i as Se,d as qe,j as po,k as Fi,l as Ei,m as Ge,n as ut,o as mo,p as Pt,q as Li,s as Yl,u as ql,v as Jl}from"./index-B1idHquf.js";import{b as Ze,e as Kl}from"./TableGrid-DbroRucl.js";import{e as Vl,r as bo,s as Gl,p as Zl,i as Ql}from"./ListNumbering-Qlu6AuRZ.js";import{i as yo}from"./HorizontalRuleOrnaments-gmUZ3R7Q.js";import{a as ec,R as Qe,A as ko,s as So,b as Io,c as Mi,d as vo}from"./DocumentStylesheet-byN5dtC6.js";import{p as Tn,a as xo,c as Ao,b as Ni,d as tc,e as nc,s as Cn,f as wo,g as To,h as ic,i as rc,n as Co}from"./TableBorders-Cdkc62cX.js";import{h as _e,H as Wt,D as oc,C as Po,a as Bo,b as $o,n as sc,g as ac,r as lc}from"./BidiText-C8PBPSQY.js";import*as S from"yjs";import{j as Yt,i as cc}from"./signatures-CBF7NZUy.js";import{MarkdownConverter as Pn}from"./MarkdownConverter-BdJgh8xt.js";import{r as dc,w as gc,a as Oi}from"./ParagraphDiffAnalysis-DrmStvmz.js";const Fo=/<!--[^]*?-->|<\/?[a-zA-Z][\w:-]*(?:\s+(?:[^"'<>]|"[^"]*"|'[^']*')*)?\s*\/?>/g,Eo={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 uc(o){return o.replace(/\\+(["'])/g,"$1")}function qt(o){return uc(o.replace(/&(#(?:\d+|x[0-9a-f]+)|[a-z]+);/gi,(e,t)=>{if(!t.startsWith("#"))return Object.prototype.hasOwnProperty.call(Eo,t)?Eo[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(o){return o.search(Fo)>=0}function Jt(o){return qt(o.replace(Fo,e=>/^<br\b/i.test(e)?`
|
|
2
|
-
`:""))}function Bn(o){const e=qt(o);return[...new Set(et(o)?[o,e,Jt(o)]:[o,e])]}function $n(o,e,t="prefer-exact",n){if(n&&t!=="normalized"){const i=Mo(o,n,e);if(i.length)return i}for(const i of Bn(e)){const r=Kt(o,i,t);if(r.length)return r}return[]}function Bt(o){return o.replace(/<\/?comment-thread\b[^>]*>/gi,"")}function Lo(o,e){return Di(Bt(o),Bt(e))}function Mo(o,e,t){if(!et(t))return[];e=Bt(e);const n=Jt(e);return n.length!==o.length||tt(n)!==tt(o)?[]:Lo(e,t).map(({start:i,end:r})=>({start:Jt(e.slice(0,i)).length,end:Jt(e.slice(0,r)).length})).filter(i=>i.end>i.start)}function Ri(o){let e="";const t=[],n=[];for(let i=0;i<o.length;i++){const r=i;let s=No(o[i]);if(/[\s\u0085]/u.test(s)){for(;i+1<o.length&&/[\s\u0085]/u.test(o[i+1]);)i++;s=" "}e+=s,t.push(r),n.push(i+1)}return{text:e,starts:t,ends:n}}function No(o){return/[\s\u0085]/u.test(o)?" ":/[\u2018-\u201b\u2039\u203a\uff07]/u.test(o)?"'":/[\u201c-\u201f\u00ab\u00bb\uff02]/u.test(o)?'"':o}function tt(o){let e="";for(let t=0;t<o.length;t++){const n=No(o[t]);e+=/[\u2012-\u2014]/u.test(n)?"-":n}return e}function Di(o,e){if(!e)return[];const t=[];let n=0;for(;n<=o.length-e.length;){const i=o.indexOf(e,n);if(i<0)break;t.push({start:i,end:i+e.length}),n=i+1}return t}function Kt(o,e,t="prefer-exact"){if(t!=="normalized"){const r=Di(o,e);if(r.length>0||t==="exact")return r}const n=Ri(o),i=Ri(e).text;return i.trim()?Di(n.text,i).map(({start:r,end:s})=>({start:n.starts[r],end:n.ends[s-1]})):[]}function hc(o,e,t,n,i){for(const r of["exact","normalized"]){const s=i?i(e,r):$n(o,e,r,n),a=i?i(t,r):$n(o,t,r,n),l=[];let c=0;for(const d of s){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 fc(o){const e=o.children.filter(t=>t.type==="text");return e.length===0?[{type:"text",text:""}]:e}function Fn(o){return fc(o).reduce((e,t)=>e+t.text.length,0)}function pc(o,e){const t=X(o,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+=Fn(n.children[r]),r<n.children.length-1&&(i+=1);return{block:t.id,offset:i}}return{block:t.id,offset:0}}class pe extends Error{constructor(e,t,n="validation",i=!1,r="unchanged",s){super(t),this.code=e,this.phase=n,this.retryable=i,this.mutationOutcome=r,this.details=s,this.name="SemanticToolError"}}function Vt(o){return o instanceof pe?{code:o.code,phase:o.phase,retryable:o.retryable,mutationOutcome:o.mutationOutcome,details:o.details}:void 0}const Oo=24e3,Ro=25;function mc(o,e,t){const n={type:"doc",children:o},i=o.findIndex(l=>!!X({...n,children:[l]},e)),r=o.findIndex(l=>!!X({...n,children:[l]},t)),s=o.flatMap((l,c)=>{if(l.type!=="table"||l.children.length<Ro)return[l];const d=l.children.findIndex(m=>m.children.some(b=>!!X(b,e))),g=l.children.findIndex(m=>m.children.some(b=>!!X(b,t)));if(!((i<0||c>=i)&&(r<0||c<=r))||d<0&&g<0&&i===r)return[];const u=Ze(l),p=Kl(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,b)=>l.hasHeader&&b===0||b>=h&&b<=f)}]});if(JSON.stringify(s).length<=Oo)return s;const a=[e,t].flatMap((l,c)=>{if(c&&l===e)return[];for(const d of o){const g=X({type:"doc",children:[d]},l);if(g)return[g]}return[]});return JSON.stringify(a).length<=Oo?a:[]}const Do=o=>o.replace(/\\+u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)));function _o(o,e){if(!o)return;const t=o.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 bc(o){const e=o?.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 yc(o){if(!o)return;const e=i=>o.match(new RegExp(`(?:^|;)\\s*${i}\\s*:\\s*([^;]+)`,"i"))?.[1]?.trim(),t=Tn(e("border")),n={};for(const i of["top","bottom","left","right"]){const r=o.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 s;if(r){const l=r[2].toLowerCase();s={width:l==="none"?0:parseFloat(r[1]),style:l==="solid"?"single":l,color:r[3]}}else{const l=Tn(e(`border-${i}`))??t;l&&(s={...l})}if(!s)continue;const a=bc(e(`padding-${i}`));a!==void 0&&a>0&&(s.space=Math.round(a*100)/100),n[i]=s}return Object.keys(n).length>0?JSON.stringify(n):void 0}const kc=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"]),Sc=/[&<>"']/,Ic=/[&<>"']/g,vc={"&":"&","<":"<",">":">",'"':""","'":"'"};function xc(o){return vc[o]??o}function Ac(o){const e=o.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 En=null;function _i(o){return En||(En=new DOMParser().parseFromString("","text/html")),En.body.innerHTML=o.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}),En}function wc(o,e={}){return!o||e.code||e.latex?o:Do(o.replace(/\\+(["'])/g,"$1"))}function jo(o){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 s of r.children)t(s)}}}}for(const n of o.children)t(n);return e}function fe(o,e){if(!e?.validIds)return o||Y();if(o&&e.validIds.has(o)&&!e.usedIds.has(o))return e.usedIds.add(o),o;let t=Y();for(;e.usedIds.has(t);)t=Y();return e.usedIds.add(t),t}const Ln=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:jo(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(s=>this.blockToHtml(s,e,n,t)).filter(s=>s.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=Ke(e.pageLayout),i=this.formatInchesForComment(Pe(n.marginTopPx)),r=this.formatInchesForComment(Pe(n.marginRightPx)),s=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(Gr(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="${s}" 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,s=y=>{if(!i)return 0;const k=i instanceof Map?i.get(y):i[y];return typeof k=="number"&&Number.isFinite(k)?Math.max(0,Math.floor(k)):0},a=[],l=[],c=[];for(let y=0;y<e.children.length;y++){const k=e.children[y];k.id&&s(k.id)>0&&c.push(y),k.type==="paragraph"&&k.heading!==void 0&&k.heading<=2?a.push(y):k.type!=="image"&&l.push(y)}const d=a.length>this.MAX_OVERVIEW_BLOCKS?Math.ceil(a.length/this.MAX_OVERVIEW_BLOCKS):1,g=d>1?a.filter((y,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 y=0;y<l.length;y++)y%h===0&&p.push(l[y])}const f=Array.from(new Set([...g,...p,...c])).sort((y,k)=>y-k),m=n-1;m>=0&&!f.includes(m)&&f.push(m);const b=f.map(y=>{const k=this.getBlockId(e.children[y]),I=s(k),v=r?.blocks?.get(k);return{index:y,id:k,type:this.getBlockTypeLabel(e.children[y]),preview:this.getBlockPreview(e.children[y]),...v?.wordCount!==void 0?{wordCount:v.wordCount}:{},...v?.pageStart!==void 0?{pageStart:v.pageStart,pageEnd:v.pageEnd}:{},...I>0?{pendingChangeCount:I}:{},isLast:y===m}});return{title:e.title||"Untitled",totalBlocks:n,...r?{totalWords:r.wordCount,totalParagraphs:r.paragraphCount}:{},...r?.pageCount!==void 0?{pageCount:r.pageCount}:{},blockIds:b,samplingInterval:Math.max(d,h),...r?.sections&&r.sections.length>0?{sections:r.sections}:{}}}static toDocumentLayoutContext(e){const t=Ke(e.pageLayout),n=Zr(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(Gr(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],s=l=>{if(!l||typeof l!="object")return!1;if(Array.isArray(l))return l.some(s);const c=l;return c.marks?.field==="page"||s(c.children)};if(!s(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}`:"",s=this.formatOverviewPageRange(n.pageStart,n.pageEnd),a=s?` pages=${s}`:"",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=zt(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)),s=Math.min(n,100),a=Math.min(r+s,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(s=>{if(s.startsWith("regex:")){const a=s.slice(6);try{const l=new RegExp(a,"i");return{query:s,match:c=>l.test(c)}}catch{return{query:s,match:l=>l.toLowerCase().includes(a.toLowerCase())}}}else{const a=Ac(s).toLowerCase();return{query:s,match:l=>l.toLowerCase().includes(a)}}}),r=[...e.children,...e.notes??[]];for(let s=0;s<r.length;s++){const a=r[s],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:s,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 s=e.children[r],a=this.getBlockId(s);if(!a)continue;const l=Array.from(this.collectHighlightColors(s));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=[],s=[],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){s.push(h);continue}const m=g[f],b=this.getBlockId(m);if(!b){s.push(h);continue}if(r.push(h),c.has(b))continue;c.add(b);const y=p?.get(b),k=this.blockToHtmlWithSelections(m,e,y,d,p??void 0);a.push(k),l.push({id:b,blockIndex:f,html:k})}return{html:a.filter(h=>h.length>0).join(`
|
|
8
|
-
`),foundIds:r,missingIds:s,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(s=>s.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=[],s=new Set;for(const a of t){if(s.has(a)||a<0||a>=e.children.length)continue;s.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 s=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,s)}static buildSelectionInfoForMultiple(e,t){const n=new Map;for(const i of t){let r=i,s=e.indexOf(r.startBlock),a=e.indexOf(r.endBlock);if(!(s===-1||a===-1)){(s>a||s===a&&r.startOffset!==void 0&&r.endOffset!==void 0&&r.startOffset>r.endOffset)&&([s,a]=[a,s],r={...r,startOffset:r.endOffset,endOffset:r.startOffset});for(let l=s;l<=a;l++){const c=e[l],d={};l===s&&(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 s=this.blockToHtml(e,t,i);if(!r?.size||!("children"in e))return s;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 s;const c=document.createElement("div");c.innerHTML=s;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,s=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}>${s}</h${e.heading}>`:`<p${c}${u}${d}${g}${l}>${s}</p>`}static textNodesToHtmlWithSelections(e,t,n,i,r){const s=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,b=h.endOffset??a;l.push({pos:m,type:"open",idx:f}),l.push({pos:b,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,s,r?.heading?u:void 0,i);for(const h of p)if(h.type==="text"){const f=h.text,m=c,b=c+f.length;let y=0;for(;d<l.length&&l[d].pos<=b;){const k=l[d];if(k.pos>m+y){const I=f.slice(y,k.pos-m);g.push(this.textToHtmlWithMarks(I,h.marks,r,t,u,s,i)),y=k.pos-m}g.push(k.type==="open"?"<user-selection>":"</user-selection>"),d++}if(y<f.length){const k=f.slice(y);g.push(this.textToHtmlWithMarks(k,h.marks,r,t,u,s,i))}c=b}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,s,a){let l=this.escapeHtml(e);if(l=l.replace(/\r\n|\r|\n/g,"<br>"),t){const c=[];if(t.fontFamily){const h=s??zl(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=sl(t);g.length>0&&d.push(`data-docx-explicit-false-marks="${g.join(",")}"`);const u=Ii(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 s=e.foundBlocks[i-1],a=r.blockIndex-s.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 s=(t.comments??[]).filter(a=>!a.parentId&&a.anchorBlockId===e.id).map(a=>a.id);return this.wrapWithCommentThreads(r,s,t)}static footnoteToHtml(e,t,n,i={}){const r=e.children.map(s=>this.blockToHtml(s,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="${al(e)}"${e.direction?` dir="${e.direction}"`:""}${i}></toc>`}static codeBlockToHtml(e){const t=e.language?.trim().toLowerCase();if(t==="latex"||t==="latex-inline"){const s=e.id?` id="${this.escapeAttribute(e.id)}"`:"",a=t==="latex-inline"?' display="inline"':"",l=this.escapeHtml(e.content||"");return`<latex${s}${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:ll(e);if(i){const h=e.id?` id="${this.escapeHtml(e.id)}"`:"",f=yo(i.style),m=i.width===vi.width&&i.color.toLowerCase()===vi.color.toLowerCase(),b=f?` data-rule="${i.style}"`:"";let y="";if(!m||!f&&i.style!==vi.style){const k=f||i.style==="single"?"solid":i.style;y=` style="border-bottom: ${i.width}px ${k} ${i.color}"`}return`<hr${h}${b}${y} />`}const r=this.extractUniformTextFontFamily(e.children),s=e.heading?this.extractUniformTextFontSize(e.children):void 0,a=this.coalesceAdjacentTextNodesForHtml(e.children,r,e.heading?s:void 0,n).map(h=>h.type==="text"?this.textNodeToHtml(h,e,t,s,r,n):"").join(""),l=[];e.align&&l.push(`text-align: ${e.align}`),this.appendParagraphIndentStyles(l,e,this.resolveIndentStepPx(t)),e.heading&&s!==void 0&&l.push(`font-size: ${s}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,s){return this.textToHtmlWithMarks(e.text,e.marks,t,n,i,r,s)}static coalesceAdjacentTextNodesForHtml(e,t,n,i){if(e.length<=1)return e;const r=[];let s=null;for(const a of e){const l=this.getTextSerializationKey(a.marks,t,n,i),c=r[r.length-1];if(c&&s===l){c.text+=a.text;continue}r.push({...a,marks:a.marks?{...a.marks}:void 0}),s=l}return r}static getTextSerializationKey(e,t,n,i){const r=e?.fontFamily&&e.fontFamily!==t&&e.fontFamily!==i?e.fontFamily:null,s=e?.fontSize!==void 0&&e.fontSize!==n?e.fontSize:null;return JSON.stringify([r,s,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,Ii(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 s=(n.comments??[]).find(g=>g.id===r&&!g.parentId),a=s?this.collectCommentThreadRecords(s.id,n):[],l=this.serializeCommentTranscript(a),c=s?.resolved===!0?"true":"false",d=s?.suggestionId?` suggestion-id="${this.escapeAttribute(s.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 s of n)s.parentId&&i.has(s.parentId)&&!i.has(s.id)&&(i.add(s.id),r=!0)}return n.filter(s=>i.has(s.id)).sort((s,a)=>(s.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 s=i(t.map(l=>n(l,2e3)),r);if(s.length<=4e3)return s;const a=Math.max(80,Math.floor(4e3/Math.max(1,t.length)-60));return s=i(t.map(l=>n(l,a)),!0),s.length<=4e3?s:i(t.slice(-5).map(l=>n(l,300)),!0)}static normalizeAgentHighlightColor(e){return _e(e)}static escapeHtml(e){return Sc.test(e)?e.replace(Ic,xc):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=cl.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=kn(i[1].trim());a&&!Qr(a)&&(t.color=a)}const r=e.match(/(?:^|;)\s*letter-spacing:\s*([^;]+)/i);if(r){const a=_o(r[1].trim(),t.fontSize);a!==void 0&&(t.letterSpacing=a)}const s=e.match(/(?:^|;)\s*font-family:\s*([^;]+)/i);if(s){const a=s[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 Ke(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 s=t.getAttribute("data-tab-stops");s&&(e.tabStops=s);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){if(!e)return;const t=e.trim().match(/^([\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 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 b=yc(e);b&&(n.borders=b);const y=e.match(/(?:^|;)\s*background-color:\s*(#[0-9a-fA-F]{3,8}|transparent)/i);y&&(n.shading=y[1])}const i=e.match(/text-align:\s*([^;]+)/i);if(i){const b=i[1].trim().toLowerCase();(b==="left"||b==="center"||b==="right"||b==="justify")&&(n.align=b)}let r,s,a;const l=e.match(/(?:^|;)\s*margin:\s*([^;]+)/i)?.[1];if(l){const b=l.trim().split(/\s+/);if(b.length>=1&&b.length<=4){const[y,k=y,I=y,v=k]=b;r=y,s=I,a=v}}r=e.match(/(?:^|;)\s*margin-top:\s*([^;]+)/i)?.[1]??r,s=e.match(/(?:^|;)\s*margin-bottom:\s*([^;]+)/i)?.[1]??s;const c=this.cssLengthToPx(r);c!==void 0&&(n.spaceBefore=Math.round(c*100)/100);const d=this.cssLengthToPx(s);d!==void 0&&(n.spaceAfter=Math.round(d*100)/100);const g=e.match(/(?:^|;)\s*line-height:\s*([\d.]+)\s*(?:;|$)/i);if(g){const b=parseFloat(g[1]);Number.isFinite(b)&&b>=.5&&b<=4&&(n.lineSpacing=b)}const u=e.match(/margin-left:\s*([^;]+)/i),p=this.cssLengthToPx(a)?a:void 0,h=xi(u?.[1]??p,{indentStepPx:t});h!==void 0&&(n.leftIndent=h);const f=e.match(/text-indent:\s*([^;]+)/i),m=xi(f?.[1],{indentStepPx:t,firstLine:!0});return m!==void 0&&(n.firstLineIndent=m),n}static appendParagraphIndentStyles(e,t,n){const i=t.leftIndent===0?0:Re(t.leftIndent);i!==void 0&&e.push(`margin-left: ${eo(i,n)}px`);const r=t.firstLineIndent===0?0:De(t.firstLineIndent);if(r!==void 0&&e.push(`text-indent: ${Math.sign(r)*eo(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 s=JSON.parse(t.borders);for(const a of["top","bottom","left","right"]){const l=s[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 s of r)if(!(s.type!=="text"||s.text.length===0)&&(t.add(s.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 s of r.children)if(n(s.children),t.size>1)return;break;case"container":for(const s of r.children)if(i(s),t.size>1)return;break;case"table":for(const s of r.children)for(const a of s.children)for(const l of a.children)if(i(l),t.size>1)return;break;case"table-cell":for(const s of r.children)if(i(s),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 s=0;s<r.length;s++){const a=this.getBlockId(r[s]);if(a&&i.has(a)&&(n.set(a,s),i.delete(a),i.size===0))return n}for(let s=0;s<r.length&&(this.collectRequestedBlockIndexesForTopLevel(r[s],i,n,{topLevelIndex:s,includeRootBlock:!1}),i.size!==0);s++);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 s of r.children){if(s.id&&t.has(s.id)&&(n.set(s.id,i.topLevelIndex),t.delete(s.id),t.size===0))return;for(const a of s.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),s=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}${s}>`}static listToHtml(e,t,n,i={},r){const s=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),w=Math.min(I,(x.endOffset??1/0)-l);return A<w?[{startOffset:A,endOffset:w}]:[]});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],w=A.indentLevel||0;if(w<I)break;if(w>=I){const E=this.extractUniformTextFontFamily(A.children),$=[...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`]:[]];E&&E!==t&&$.push(`font-family: ${this.escapeHtml(E)}`);const P=$.length>0?` style="${$.join("; ")}"`:"",B=A.id?` id="${this.escapeAttribute(A.id)}"`:"",C=A.direction?` dir="${A.direction}"`:"",T=w!==0||i.includeZeroListLevels?` data-indent-level="${w}"`:"",L=`${B}${P}${C}${T}`,M=a.get(A),O=M?this.textNodesToHtmlWithSelections(A.children,n,M,t):this.coalesceAdjacentTextNodesForHtml(A.children,E,void 0,t).map(R=>R.type==="text"?this.textNodeToHtml(R,void 0,n,void 0,E,t):"").join(""),F=[];let N=x+1;for(;N<k.length&&(k[N].indentLevel||0)>w;)F.push(k[N]),N++;let _=O;if(F.length>0){const R=e.variant==="ordered"?"ol":"ul",D=`<${R}>${c(F,w+1)}</${R}>`;_=O+D}if(e.variant==="todo"&&(_=`<input type="checkbox"${A.checked?" checked":""}>${_}`),n&&A.id){const R=(n.comments??[]).filter(D=>!D.parentId&&D.anchorBlockId===A.id).map(D=>D.id);_=this.wrapWithCommentThreads(_,R,n)}v.push(`<li${L}>${_}</li>`),x=N}else x++}return v.join("")},d=c(e.children,0),g=e.id?` id="${this.escapeAttribute(e.id)}"`:"",u=e.variant==="ordered"?Vl((n?bo(n).get(e.id):void 0)??Gl(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}"`:"",b=e.numberingChainId?` data-numbering-chain-id="${this.escapeAttribute(e.numberingChainId)}" data-start-number="${e.startNumber??""}" data-effective-start="${u}"`:"",y=e.numberingFormat?` data-numbering-format="${this.escapeAttribute(e.numberingFormat)}"`:"";return`<${s}${g}${p}${f}${m}${b}${y}>${d}</${s}>`}static containerToHtml(e,t,n,i={}){const r=e.id?` id="${this.escapeAttribute(e.id)}"`:"",s=[];e.borderColor&&s.push(`border-color: ${this.escapeHtml(e.borderColor)}`),e.padding!==void 0&&s.push(`padding: ${e.padding}px`);const a=s.length>0?` style="${s.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)}"`:"",s=["border-collapse: collapse"];e.tableWidth!==void 0?s.push(`width: ${e.tableWidth}px`):s.push("width: 100%"),e.align&&e.align!=="left"&&(e.align==="center"?s.push("margin-left: auto","margin-right: auto"):e.align==="right"&&s.push("margin-left: auto","margin-right: 0")),e.borderColor&&s.push(`border-color: ${this.escapeHtml(e.borderColor)}`);const a=xo(e.borders);let l="";if(a){for(const u of["top","right","bottom","left"]){const p=a[u];p&&s.push(`border-${u}: ${Ao(p)}`)}l=` data-borders="${this.escapeAttribute(e.borders)}"`}const c=` style="${s.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,s,a={}){const l=[];if(r){const h=f=>{const m=f;if(m.type==="list"){m.variant==="ordered"&&l.push([m.id,bo(r).get(m.id??"")]);return}for(const b of m.children??[])h(b)};h(t)}const c=JSON.stringify([t,l,e.columnWidths,e.hasHeader&&n===0,s,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)}"`:"",b=i.byId.get(h.id);let y="";b&&b.colSpan>1&&(y+=` colspan="${b.colSpan}"`),b&&b.rowSpan>1&&(y+=` rowspan="${b.rowSpan}"`);const k=b?` data-grid-column="${b.col}"`:' data-grid-unplaced="true"';let I;if(b){let P=0;for(let B=b.col;B<b.col+b.colSpan;B++)P+=e.columnWidths[B]||0;I=P>0?P:void 0}else I=e.columnWidths[f];const v=[];let x="";const A=Ni(h.borders);if(A){for(const P of["top","right","bottom","left"]){const B=A[P];B&&v.push(`border-${P}: ${Ao(B)}`)}x+=` data-borders="${this.escapeAttribute(h.borders)}"`}else v.push("border: 1px solid #ccc");const w=tc(h.padding);w?v.push(`padding: ${nc(w)}`):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 E=` style="${v.join("; ")}"`,$=h.children.map(P=>this.blockToHtml(P,r,s,a)).filter(P=>P.length>0).join("");return`<${g}${m}${y}${x}${E}${k}>${$}</${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)}"`:"",s=["border: 1px solid #ccc","padding: 8px"];e.verticalAlign&&s.push(`vertical-align: ${e.verticalAlign}`),e.backgroundColor&&s.push(`background-color: ${this.escapeHtml(e.backgroundColor)}`);const a=` style="${s.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"),s=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,b=s??a.height;a.width=p,a.height=Math.max(1,Math.round(p*b/m))}else if(h!==void 0){const m=r??a.width,b=s??a.height;a.height=h,a.width=Math.max(1,Math.round(h*m/b))}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)?fe(n.id,t):fe(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"),s=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=s??l??200;a&&l&&(r?p=Math.max(1,Math.round(r*l/a)):s&&(u=Math.max(1,Math.round(s*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 s=(h,f,m={},b=Math.min(n+2,8))=>{const y=[],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 w=[];for(const N of Array.from(v.childNodes))if(N.nodeType===Node.ELEMENT_NODE){const _=N,R=_.tagName.toLowerCase();R==="ul"||R==="ol"?(A=!0,w.push(_)):x.appendChild(N.cloneNode(!0))}else x.appendChild(N.cloneNode(!0));const E=v.getAttribute("style"),$=E?{...I,...this.extractTextStyleMarksFromStyle(E)}:I,P=x.querySelector('input[type="checkbox"]');P&&(r="todo",P.remove());const B=this.parseHtmlElement(x,$),C={type:"list-item",id:fe(v.getAttribute("id"),t),children:B.length>0?B:[{type:"text",text:"",marks:{}}]};P&&(C.checked=P.hasAttribute("checked"));const T=v.getAttribute("dir")??E?.match(/(?:^|;)\s*direction:\s*(rtl|ltr)\s*(?:;|$)/i)?.[1];if((T==="rtl"||T==="ltr")&&(C.direction=T),E){const N=this.extractParagraphStyleAttributes(E);for(const _ of["lineSpacing","spaceBefore","spaceAfter"])N[_]!==void 0&&(C[_]=N[_])}const L=v.getAttribute("data-indent-level"),M=L!==null?Number(L):NaN,O=Number.isInteger(M)&&M>=0&&M<=8,F=O?M:f;if(F>0&&(C.indentLevel=F),y.push(C),A)for(const N of w){const _=O?Math.max(b,Math.min(F+2,8)):b,R=s(N,Math.min(F+1,_),$,_);y.push(...R)}}return y},a=s(e,n);if(a.length===0)return null;const l={type:"list",id:fe(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&&Zl(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 b of m.children)b.type==="text"&&(b.marks||(b.marks={}),b.marks.fontFamily||(b.marks.fontFamily=f))}}return l}static parseContainerElement(e,t,n){const i=fe(e.getAttribute("id"),n),r=e.getAttribute("style");let s,a;if(r){const g=r.match(/border-color:\s*([^;]+)/);g&&(s=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:fe(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 s&&(d.borderColor=s),a!==void 0&&(d.padding=a),d}static parseTableElement(e,t,n){const i=fe(e.getAttribute("id"),n),r=this.resolveIndentStepPx(t?.existingDocument),s=e.getAttribute("style");let a,l,c;if(s){const x=s.match(/width:\s*(\d+)px/);x&&(a=parseInt(x[1],10));const A=s.match(/border-color:\s*([^;]+)/);A&&(l=A[1].trim()),/margin-left:\s*auto/.test(s)&&/margin-right:\s*auto/.test(s)?c="center":/margin-left:\s*auto/.test(s)&&/margin-right:\s*0/.test(s)&&(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],w=[],E=A.querySelectorAll(":scope > td, :scope > th");x===0&&E.length>0&&E[0].tagName.toLowerCase()==="th"&&(u=!0);for(let P=0;P<E.length;P++){const B=E[P],C=B.getAttribute("style");let T,L;if(C){const j=C.match(/vertical-align:\s*([^;]+)/);if(j){const K=j[1].trim();(K==="top"||K==="middle"||K==="bottom")&&(T=K)}const z=C.match(/background-color:\s*([^;]+)/);z&&(L=z[1].trim())}const M=[],O=B.children;if(O.length===0){const j=B.textContent||"";M.push({type:"paragraph",id:fe(null,n),children:[{type:"text",text:j,marks:{}}]})}else for(const j of Array.from(O)){const z=j.tagName.toLowerCase(),K=z==="img"?this.parseImageElement(j,n):z==="p"?this.parseSingleImageParagraph(j,n):null;if(K){M.push(K);continue}if(z==="p"||z.match(/^h[1-6]$/)){const ae=z.match(/^h([1-6])$/),xe=j.getAttribute("style"),Xe=this.parseHtmlElement(j,xe?this.extractTextStyleMarksFromStyle(xe):{}),Oe={type:"paragraph",id:fe(j.getAttribute("id"),n),children:Xe.length>0?Xe:[{type:"text",text:"",marks:{}}]};ae&&(Oe.heading=parseInt(ae[1])),this.applyParagraphElementAttributes(Oe,j,r),M.push(Oe)}else if(z==="ul"||z==="ol"){const ae=this.parseListElement(j,n);ae&&M.push(ae)}else if(z==="hr")M.push(this.parseHrElement(j,n));else if(z==="table"){const ae=this.parseTableElement(j,t,n);ae&&M.push(ae)}else{const ae=j.textContent||"";ae.trim()&&M.push({type:"paragraph",id:fe(null,n),children:[{type:"text",text:ae,marks:{}}]})}}M.length===0&&M.push({type:"paragraph",id:fe(null,n),children:[{type:"text",text:"",marks:{}}]});const F={type:"table-cell",id:fe(B.getAttribute("id"),n),children:M},N=C?.match(/width:\s*([\d.]+)%/);if(N){const j=parseFloat(N[1]);Number.isFinite(j)&&j>0&&g.set(F,j)}T&&(F.verticalAlign=T),L&&(F.backgroundColor=L);const _=Ni(B.getAttribute("data-borders")),R=_?Cn(_):wo(To(C));if(R&&(F.borders=R),C){const j=C.match(/(?:^|;)\s*padding\s*:\s*([^;]+)/i),z=ic(j?.[1]);z&&!(z.top===8&&z.right===8&&z.bottom===8&&z.left===8)&&(F.padding=rc(z))}const D=this.parseSpanAttribute(B.getAttribute("colspan")),U=this.parseSpanAttribute(B.getAttribute("rowspan"));D>1&&(F.colSpan=D),U>1&&(F.rowSpan=U),w.push(F)}const $=fe(A.getAttribute("id"),n);d.push({type:"table-row",id:$,children:w})}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),b=new Array(f).fill(!1);for(const x of h.cells){if(x.colSpan!==1||b[x.col])continue;const A=g.get(x.cell);A!==void 0&&(m[x.col]=A,b[x.col]=!0)}const y=b.filter(x=>!x).length;if(y>0){const x=m.reduce((w,E)=>w+E,0),A=Math.max(1,(100-x)/y);for(let w=0;w<f;w++)b[w]||(m[w]=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=xo(e.getAttribute("data-borders")),v=I?Cn(I):wo(To(s));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=fe(e.getAttribute("id"),t);let i;const r=e.getAttribute("language"),s=e.getAttribute("data-language");if(r)i=r;else if(s)i=s;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=fe(e.getAttribute("id"),t);let i="block";e.getAttribute("display")==="inline"&&(i="inline");const r=e.textContent||"",s=Q(e,"align"),a={type:"math",id:n,content:r,displayMode:i};return(s==="left"||s==="center"||s==="right")&&(a.align=s),a}static parseHrElement(e,t){let n;const i=e.getAttribute("style");if(i){const s=i.match(/border(?:-bottom)?:\s*([\d.]+)px\s+(solid|double|dashed|dotted)\s+(#[0-9a-fA-F]{3,8}|[a-zA-Z]+)/i);if(s){const a=s[2].toLowerCase();n={width:parseFloat(s[1]),style:a==="solid"?"single":a,color:s[3]}}}const r=e.getAttribute("data-rule");return yo(r??void 0)&&(n={...n,style:r}),{type:"paragraph",id:fe(e.getAttribute("id"),t),children:[{type:"text",text:"",marks:{}}],borders:dl(n)}}static parsePageBreakElement(e,t){return{type:"page-break",id:fe(e.getAttribute("id"),t)}}static parseDocxRawElement(e,t){const n=e.getAttribute("origin");return{type:"docx-raw",id:fe(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",...gl(e),id:fe(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,ul(e.getAttribute("style"))),n}static parseSectionBreakElement(e,t){const n={type:"section-break",id:fe(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 s=JSON.parse(r);s&&typeof s=="object"&&!Array.isArray(s)&&(n.layout=s)}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:fe(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 s=this.parseHtmlElement(e);return[{type:"paragraph",id:fe(e.getAttribute("id"),n),align:"center",children:s.length>0?s:[{type:"text",text:"",marks:{}}]}]}static parseImageAlign(e){const t=Q(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 s=this.escapeCodeContent(i);return`<pre${n||""}>${s}</pre>`})}static escapeCodeContent(e){return e.replace(/&(?!(lt|gt|amp|quot|apos|nbsp|#\d+|#x[0-9a-fA-F]+);)/g,"&").replace(/</g,"<").replace(/>/g,">")}static coalesceAdjacentBareListFragments(e){if(e.length<2)return e;const t=[];let n=!1;for(const i of e){const r=_i(i),s=Array.from(r.body.childNodes),a=s.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&&s.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?jo({children:[t.replacementBlock]}):new Set,s={validIds:i,usedIds:new Set,imageIdsToPreserve:r,imageReferences:new Map,remainingImageReferences:new Set};t={...t,parsingContext:n};let a=_i(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=>kc.has(f.tagName.toLowerCase()))||(a=_i(`<p>${e}</p>`));const d=new Set,g=Array.from(a.body.querySelectorAll("img"));for(const f of g){s.remainingImageReferences.add(f);const m=f.getAttribute("id")??"",b=m?n?.imagesById?.get(m):void 0,y=f.getAttribute("data-image-id"),k=f.getAttribute("src")??"",I=k.startsWith("#")?k.slice(1):void 0;if(y!==null||I!==void 0){const x=y??I,A=n?.imagesById?.get(x);if(!A?.src||I!==void 0&&I!==x||b&&b.id!==x||k&&I===void 0&&k!==x&&k!==A.src)throw new pe("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.`);s.imageReferences.set(f,A);continue}const v=n?.imagesById?.get(f.getAttribute("src")??"");if(v){s.imageReferences.set(f,v);continue}if(k&&k!==b?.src&&!/^(?:https?:\/\/|data:image\/|blob:)/i.test(k))throw new pe("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=b??x;if(!A?.src)throw new pe("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 pe("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),s.imageReferences.set(f,A);continue}b?.src===f.getAttribute("src")&&s.imageReferences.set(f,b)}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:fe(null,s),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,s);A&&h.push(A);continue}if(m==="ul"||m==="ol"){const A=this.parseListElement(f,s,t?.listItemBaseIndent);A&&h.push(A);continue}if(m==="div"&&f.classList.contains("container")){const A=this.parseContainerElement(f,t,s);A&&h.push(A);continue}if(m==="table"){const A=this.parseTableElement(f,t,s);A&&h.push(A);continue}if(m==="pre"){const A=this.parseCodeBlockElement(f,s);A&&h.push(A);continue}if(m==="p"){const A=this.parseSingleImageParagraph(f,s);if(A){h.push(A);continue}}if(m==="latex"){const A=this.parseMathElement(f,s);h.push(A);continue}if(m==="page-break"){h.push(this.parsePageBreakElement(f,s));continue}if(m==="docx-raw"){h.push(this.parseDocxRawElement(f,s));continue}if(m==="section-break"){h.push(this.parseSectionBreakElement(f,s));continue}if(m==="toc"){h.push(this.parseTocElement(f,s));continue}if(m==="center"){h.push(...this.parseCenterElement(f,t,s));continue}if(m==="hr"){h.push(this.parseHrElement(f,s));continue}const b=m.match(/^h([1-6])$/),y=f.getAttribute("style");let k,I;if(y){const A=y.match(/font-family:\s*([^;]+)/);A&&(k=this.resolveFontToCss(A[1].trim())),I=this.extractFontSizeFromStyle(y)}const v=fe(f.getAttribute("id"),s),x=y?this.extractTextStyleMarksFromStyle(y):{};if(b){const A=parseInt(b[1]),w=this.parseHtmlElement(f,x,t?.preserveExplicitMarkResets),E={type:"paragraph",id:v,heading:A,children:w.length>0?w:[{type:"text",text:"",marks:{}}]};if(k)for(const $ of E.children)$.type==="text"&&($.marks||($.marks={}),$.marks.fontFamily||($.marks.fontFamily=k));I!==void 0&&this.ensureTextNodesHaveFontSize(E.children,I),this.applyParagraphElementAttributes(E,f,p),h.push(E)}else{const A=this.parseHtmlElement(f,x,t?.preserveExplicitMarkResets),w={type:"paragraph",id:v,children:A.length>0?A:[{type:"text",text:"",marks:{}}]};if(k)for(const E of w.children)E.type==="text"&&(E.marks||(E.marks={}),E.marks.fontFamily||(E.marks.fontFamily=k));this.applyParagraphElementAttributes(w,f,p),h.push(w)}}if(s.remainingImageReferences.size>0){const f=Array.from(s.remainingImageReferences,m=>m.getAttribute("id")||"(new image)").join(", ");throw new pe("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(hl()),ec(h,t?.existingDocument?.stylesheet),this.applyInheritedFontStyling(h,t),Ql(()=>fe(null,s),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 s=i.id&&t?X(t,i.id):void 0;s&&s.type==="docx-raw"&&s.xml?(i.xml=s.xml,i.tagName=s.tagName,s.detail&&(i.detail=s.detail),i.origin=s.origin):e.splice(n,1);continue}const r=i.children;Array.isArray(r)&&r.length>0&&r.filter(s=>typeof s=="object"&&s!==null&&typeof s.type=="string"&&s.type!=="text").length>0&&this.hydrateDocxRawPlaceholders(r,t)}}static parseHtmlElement(e,t={},n=!1){const i=[];let r;const s=(a,l={})=>{if(a.nodeType===Node.TEXT_NODE){const c=wc(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: ${Wt.join(", ")}.`);d.backgroundColor=h??oc}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":fl(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 b=c.getAttribute("data-sdt-inline");b&&(d.sdtInline=b),c.getAttribute("data-ai-generated")==="true"&&(d.aiGenerated=!0);const y=c.getAttribute("data-html-class");y&&(d.__htmlClassName=y)}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 b=u.match(/background-color:\s*([^;]+)/i);if(b){const v=this.normalizeAgentHighlightColor(b[1].trim());v&&(d.backgroundColor=v)}const y=u.match(/(?:^|;)\s*color:\s*([^;]+)/i);if(y){const v=kn(y[1].trim());v&&!Qr(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=_o(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))s(g,d)}};for(const a of Array.from(e.childNodes))s(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)),s=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,s);else if(a.type==="list")for(const c of a.children)this.ensureTextNodesHaveFontStyling(c.children,r,s);const l=this.extractBlockFontStyling(a);r=l.fontFamily??r,s=l.fontSize??s}}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 s of r.children)s.type==="text"&&!s.marks?.footnoteRef&&t.push(s);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?mc(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 s of i){const a=this.getBlockId(s),l=r?.get(a);t.push(this.blockToHtmlWithSelections(s,void 0,l,void 0,r))}}return t.length===0?null:t.filter(n=>n.length>0).join(`
|
|
22
|
-
`)}};Ln.DEFAULT_FONT_FAMILY="Arial, sans-serif",Ln.MAX_OVERVIEW_BLOCKS=50,Ln.tableRowHtmlCache=new WeakMap;let ee=Ln;function me(o){if(!o||typeof o!="object")return"";const e=o;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 Xo={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 Uo(o,e){if(!/<[^>]+\bid\s*=/i.test(e))return null;const t=me(o);if(t.includes(e)||t.includes(qt(e)))return null;const n=document.createElement("template");n.innerHTML=e;const i=[...n.content.querySelectorAll("[id]")].filter(c=>Xo[c.tagName]);if(!i.length)return null;const r=new Map,s=(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=>s(u,d))};s(o);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!==Xo[c.tagName])throw new pe("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=Kt(u,p,"prefer-exact");if(u!==p&&!h.some(b=>b.start===0&&b.end===u.length))throw new pe("target_stale",`HTML matcher text for '${c.id}' no longer matches that block. Read it again before editing.`,"matching");const f=new Set;s(g,f);const m=i.filter(b=>b!==c&&c.contains(b));if(m.some(b=>!f.has(b.id)))throw new pe("target_stale",`HTML matcher ids contradict the document hierarchy inside '${c.id}'.`,"target_resolution");m.length||f.forEach(b=>l.add(b))}return l}function $t(o,e){const t=X(o,e);return t?.type==="list"&&t.id!==e?t.children.find(n=>n.id===e)??null:t}function ji(o){if(!(!o||o.type!=="paragraph"&&o.type!=="list-item"))return ee.toAgentHtml({type:"doc",children:[{...o,type:"paragraph"}]})}function Mn(o,e,t="prefer-exact"){const n=Uo(o,e),i=$n(me(o),e,t,et(e)?ji(o):void 0);if(!n)return i;const r=Ho(o);return i.filter(s=>{const a=r.filter(l=>l.start<s.end&&s.start<l.end);return a.length>0&&a.every(l=>n.has(l.blockId))})}function Ho(o){const e=[];let t=0;const n=i=>{if(!i||typeof i!="object")return;const r=i,s=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}}s.forEach((l,c)=>{r.type==="list"&&c>0&&(t+=1),n(l)})};return n(o),e}function Tc(o,e,t){const n=[];for(const i of o){const r=Math.max(e,i.start),s=Math.min(t,i.end);s<=r||n.push({blockId:i.blockId,start:r-i.start,end:s-i.start})}return n}function zo(o){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 s=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,s):s,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 s=r.type==="list"?1:0;r.children.forEach((a,l)=>{s&&l>0&&(t+=s),n(a)})}};return n(o),e}const Wo=300;function Xi(o,e,t,n,i){const r=zo(e);return(o.comments??[]).filter(s=>!s.parentId&&s.resolved!==!0).filter(s=>!i.has(s.id)).filter(s=>{if(s.anchorBlockId===t)return!0;const a=r.get(s.id);return a?n?n.start<a.end&&a.start<n.end:!0:!1}).map(s=>({id:s.id,author:s.agentName??s.author,bodyMd:s.bodyMd.length>Wo?`${s.bodyMd.slice(0,Wo)}…`:s.bodyMd}))}function Yo(o,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 ${o} 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 Cc(o,e,t,n,i,r,s,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=$t(o,n);if(!g)return{success:!1,error:`Block ${n} not found`,errorCode:"target_missing"};if("whole_block"in r){const A=Xi(o,g,n,null,d);if(A.length>0)return Yo(n,A);const w=t.addBlockComment(n,i,s);return w?{success:!0,commentId:w}:{success:!1,error:`Could not attach a comment to block ${n}`}}const u=$t(e,n),p=me(u??g);let h=-1,f=-1;const m="text"in r?Mn(u??g,r.text):hc(p,r.start_text,r.end_text,ji(u??g),(A,w)=>Mn(u??g,A,w));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 b=Ho(u??g),y=Tc(b,h,f);if(y.length===0)return{success:!1,error:`The anchor range in block ${n} does not map to commentable text`};const k=[];for(const A of y){const w=$t(e,A.blockId),E=$t(o,A.blockId);if(!w||!E)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 $={start:A.start,end:A.end};if(me(E)!==me(w)){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`};$=P}k.push({blockId:A.blockId,...$})}const I=new Map;for(const A of Xi(o,g,n,{start:h,end:f},d))o.comments?.some(w=>w.id===A.id&&w.anchorBlockId===n)&&I.set(A.id,A);for(const A of k){const w=$t(o,A.blockId);if(w)for(const E of Xi(o,w,A.blockId,{start:A.start,end:A.end},d))I.set(E.id,E)}const v=Array.from(I.values());if(v.length>0)return Yo(n,v);const x=t.addCommentToRanges(k,i,s);return x?{success:!0,commentId:x,range:{start:h,end:f}}:{success:!1,error:`Could not attach a comment to block ${n}`}}function qo(o,e){const t=o.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(s=>s.id===n.parentId);if(!r)break;n=r}return n}function Pc(o,e,t,n,i){const r=qo(o,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 s=e.replyToComment(r.id,n,i);return s?{success:!0,commentId:s,threadId:r.id}:{success:!1,error:`Could not reply to comment ${t}`,errorCode:"comment_mutation_failed"}}function Bc(o,e,t){const n=X(o.getDocument(),e),i=X(o.getDocumentWithAcceptedSuggestions(),e);if(!n||!i)throw new pe("target_missing",`Footnote target '${e}' no longer exists. Read the document again.`,"target_resolution");if(n.type!=="paragraph"||i.type!=="paragraph")throw new pe("target_unsupported","Footnote references require a paragraph target. Read the paragraph inside this block and use its id.","target_resolution");const r=t?Mn(i,t):[];if(t&&r.length!==1)throw new pe(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 s=t?r[0].end:me(i).length;if(me(n)!==me(i)){const a=o.mapAcceptedSuggestionRangeToLiveRange(e,s,s);if(!a)throw new pe("target_stale","Anchor could not be mapped across pending suggestions. Read the block again.","target_resolution");s=a.end}return{block:e,offset:s}}function Ui(o,e){return{indentStepPx:Ke(e).indentStepPx,storedAsUnits:o.get(Ve.paragraphIndentStorageVersion)===Ai}}const Jo=new WeakMap;function Hi(o){return o.getXmlFragment("content")}function Ko(o,e){let t=e,n=null;for(;t;){if(n=t.parent,n===o)return t instanceof S.XmlElement&&t.getAttribute("id")||null;t=n}return null}function $c(o){const e=Hi(o),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 s=r.target;for(;s&&s!==e;)s instanceof S.XmlElement&&t.nestedBlocks.delete(s),s=s.parent;if(r.target===e&&r instanceof S.YXmlEvent&&r.childListChanged){t.structuralChange=!0;continue}if(r instanceof S.YXmlEvent&&r.childListChanged){const l=Ko(e,r.target);l!==null&&t.dirtyBlockIds.add(l);continue}const a=Ko(e,r.target);a!==null&&t.dirtyBlockIds.add(a)}};return t.observer=n,e.observeDeep(n),t}function Vo(o){let e=Jo.get(o);return e||(e=$c(o),Jo.set(o,e)),e}function Nn(o,e){const t=Vo(o);t.nestedBlocks=new WeakMap,t.doc=e,t.blockCache.clear(),t.elementByBlockId.clear();const n=Hi(o).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 On(o,e,t){const n=t.nestedBlocks.get(o);if(n)return n;const i=wi(o,e,void 0,r=>On(r,e,t));return i&&t.nestedBlocks.set(o,i),i}const Rn=new WeakMap;function Fc(o){let e=Rn.get(o);e||(e={blocks:[],dirty:!0,observing:!1},Rn.set(o,e));const t=o.getXmlFragment("chrome");if(e.observing||(e.observing=!0,t.observeDeep(()=>{const n=Rn.get(o);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=wi(i,Ui(o.getMap("metadata"),void 0));r&&r.type==="header-footer"&&n.push(r)}e.blocks=n,e.dirty=!1}return e.blocks}const Dn=new WeakMap;function Ec(o){let e=Dn.get(o);e||(e={blocks:[],dirty:!0,observing:!1},Dn.set(o,e));const t=o.getXmlFragment("notes");if(e.observing||(e.observing=!0,t.observeDeep(()=>{const n=Dn.get(o);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=wi(i,Ui(o.getMap("metadata"),void 0));r&&r.type==="footnote"&&n.push(r)}e.blocks=n,e.dirty=!1}return e.blocks}function Lc(o){return!!(Rn.get(o)?.dirty||Dn.get(o)?.dirty)}function _n(o,e){const t=Ec(e);t.length>0?(o.notes=t,pl(o)):delete o.notes}function jn(o,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??"")),o.comments=n):delete o.comments}function zi(o,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)),o.oxmlRanges=n):delete o.oxmlRanges}function Xn(o,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;o.children.forEach((s,a)=>{s.id&&i.set(s.id,a)});const r=s=>s.blockIds?.[0]??s.startBlockId??"";n.sort((s,a)=>(i.get(r(s))??Number.MAX_SAFE_INTEGER)-(i.get(r(a))??Number.MAX_SAFE_INTEGER)||s.id.localeCompare(a.id)),o.sdtWrappers=n}else delete o.sdtWrappers}function Un(o,e){const t=Fc(e);t.length>0?o.chrome=t:delete o.chrome;const n=no(t);n.headers?o.headers=n.headers:delete o.headers,n.footers?o.footers=n.footers:delete o.footers}function He(o){const e=Vo(o),t=Hi(o),n=o.getMap("metadata"),i=n?.get("title"),r=n?.get("pageless"),s=n?.get("watermark"),a=typeof s=="string"&&s.trim()!==""?s: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"),b=m&&typeof m=="object"&&Object.keys(m).length>0?m:void 0,y=n?.get("fontSubstitutes"),k=y&&typeof y=="object"&&Object.keys(y).length>0?y:void 0,I=to(n),v=Ui(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 w=0;w<A.length;w++){const E=A[w];if(E instanceof S.XmlElement){const $=On(E,v,e);$&&(x.push($),e.blockCache.set($.id,$),e.elementByBlockId.set($.id,E))}}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),b&&(e.doc.coreProperties=b),k&&(e.doc.fontSubstitutes=k),Un(e.doc,o),_n(e.doc,o),jn(e.doc,o),Xn(e.doc,o),zi(e.doc,o),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,w=new Map,E=t.toArray();for(let $=0;$<E.length;$++){const P=E[$];if(P instanceof S.XmlElement){const B=P.getAttribute("id"),C=B?e.dirtyBlockIds.has(B):!0,T=B?e.blockCache.get(B):void 0,L=B!==null&&e.elementByBlockId.get(B)===P;if(B&&!C&&T&&L)x.push(T),A.set(B,T),w.set(B,P);else{const M=On(P,v,e);M&&(x.push(M),A.set(M.id,M),w.set(M.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),b&&(e.doc.coreProperties=b),k&&(e.doc.fontSubstitutes=k),Un(e.doc,o),_n(e.doc,o),jn(e.doc,o),Xn(e.doc,o),zi(e.doc,o),e.blockCache=A,e.elementByBlockId=w,e.dirtyBlockIds.clear(),e.structuralChange=!1,e.doc}if(e.dirtyBlockIds.size>0){const x=[...e.doc.children],A=t.toArray();for(let w=0;w<x.length;w++){const E=x[w];if(E?.id&&e.dirtyBlockIds.has(E.id)&&w<A.length){const $=A[w];if($ instanceof S.XmlElement){const P=On($,v,e);P&&(e.blockCache.delete(E.id),x[w]=P,e.blockCache.set(P.id,P),e.elementByBlockId.set(P.id,$))}}}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),b&&(e.doc.coreProperties=b),k&&(e.doc.fontSubstitutes=k),Un(e.doc,o),_n(e.doc,o),jn(e.doc,o),Xn(e.doc,o),zi(e.doc,o),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,b?e.doc.coreProperties=b: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),Lc(o)&&(e.doc={...e.doc}),Un(e.doc,o),_n(e.doc,o),jn(e.doc,o),Xn(e.doc,o),e.doc}const Wi=new WeakMap,Gt="__revise_end_of_document__";function Ie(o,e){Wi.set(o,{...Wi.get(o),...e})}function $e(o){return Wi.get(o)}function Hn(o){if(o.name==="insert_block")return $e(o)?.stableId}function Mc(o){return!!$e(o)?.allowNoopContinuation}function Nc(o){if(o.name==="replace_block")return $e(o)?.multiBlockReplace}function Go(o,e){if(et(e)){let t=null;for(const n of o){const i=n.html?Mo(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 o){const r=$n(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 Yi(o){const e=Bn(o).at(-1);return Ri(tt(e)).text}function Zo(o){return o?.type==="paragraph"||o?.type==="list-item"||o?.type==="code"||o?.type==="math"}function Qo(o){const e=[],t=(n,i)=>{if(!(!n||typeof n!="object")&&(typeof n.id=="string"&&n.id.trim().length>0&&Zo(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 o.children)t(n,n.id??null);for(const n of o.notes??[])t(n,n.id);return e}function qi(o,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 o.notes??[])if(t(n))return n.id;return null}function es(o,e){const t=qi(o,e);if(!t)return null;if(e!==t)return e;const n=o.notes?.find(s=>s.id===t);if(!n)return e;const i=[],r=s=>{!s||typeof s!="object"||(typeof s.id=="string"&&(s.type==="paragraph"||s.type==="list-item"||s.type==="code"||s.type==="math")&&i.push(s.id),Array.isArray(s.children)&&s.children.forEach(r))};return n.children.forEach(r),i.length===1?i[0]:e}function ts(o,e){return e.has(o.blockId)||o.topLevelBlockId!==null&&e.has(o.topLevelBlockId)}function ns(o){if(!o.loadedBlockIds||o.loadedBlockIds.size===0)return null;const e=Yi(o.find);if(!e||/^\s*$/.test(e))return null;const t=X(o.doc,o.requestedBlockId);if(t&&Yi(me(t)).includes(e))return null;const n=Bn(o.find).at(-1),i=Qo(o.doc).filter(s=>s.blockId!==o.requestedBlockId&&ts(s,o.loadedBlockIds));if(i.some(s=>Kt(s.text,n).length>0))return Go(i,n);let r=null;for(const s of i)if(Yi(s.text).includes(e)){if(r!==null)return null;r=s.blockId}return r}function Oc(o){if(o.action.name!=="replace"&&o.action.name!=="replace_all")return{action:o.action};if(!o.action.arguments||typeof o.action.arguments!="object")return{action:o.action};const e=o.action.arguments,t=typeof e.id=="string"?e.id.trim():"",n=typeof e.find=="string"?e.find:"";if(!t||!n)return{action:o.action};const i=ns({doc:o.doc,requestedBlockId:t,find:n,loadedBlockIds:o.loadedBlockIds});if(!i)return{action:o.action};const r={...o.action,arguments:{...e,id:i}},s=$e(o.action);return s&&Ie(r,s),{action:r,retarget:{fromBlockId:t,toBlockId:i}}}function Rc(o){const e=[],t=[];for(const n of o.actions){const i=Oc({action:n,doc:o.doc,loadedBlockIds:o.loadedBlockIds});e.push(i.action),i.retarget&&t.push(i.retarget)}return{actions:e,retargets:t}}function Ji(o){return o.children.map(e=>{const t={type:"doc",children:[e]};return ee.toInternalHtml(t).trim()})}function Dc(o,e=0){const t=Pn.fromMarkdown(o);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 Ji(t)}function _c(o){return o.replace(/<span\b([^>]*?)\sdir\s*=\s*["']?(ltr|rtl|auto)["']?([^>]*)>([\s\S]*?)<\/span>/gi,(e,t,n,i,r)=>{const s=n.toLowerCase(),a=s==="ltr"?"":s==="rtl"?"":"",l=`${t}${i}`.trim(),c=l?`<span ${l}>${r}</span>`:r;return`${a}${c}`})}function jc(o,e,t,n){return Ji(ee.fromAgentHtml(_c(o),{existingDocument:e,replacementBlock:t,listItemBaseIndent:n,preserveImageReferenceIds:!0}))}const ht=/<\/?[a-z][^>]*>/i;function Ft(o){return o.replace(/\s+/g," ").trim()}function is(o){return Ft(o).replace(/^>\s+/,"")}function Xc(o,e){if(o.replace==="")return null;const t=o.format==="html"||ht.test(o.replace),n=t?ee.fromAgentHtml(o.replace,{replacementBlock:X(e,o.id)??void 0,existingDocument:e,preserveImageReferenceIds:!0}):Pn.fromMarkdown(o.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=X(e,o.id);if(!r||r.type!=="list")return null;const s=r,a=ht.test(o.find)?ee.fromAgentHtml(o.find,{existingDocument:e,preserveImageReferenceIds:!0}):Pn.fromMarkdown(o.find),l=a.children.length===1&&a.children[0].type==="list"?a.children[0].children.map(b=>Ft(me(b))):[Ft(me(a))];if(l.length===0||l.some(b=>b===""))return null;const c=s.children.map(b=>Ft(me(b))),d=[];for(let b=0;b+l.length<=c.length;b++)l.every((y,k)=>c[b+k]===y)&&(d.push(b),b+=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 '${o.id}' — it did not. Include each full item's text in "find" (or use insert_markdown to add items).`);if(d.length>1&&!o.all)throw new Error(`replace: "find" matches ${d.length} runs of list items in block '${o.id}'. Include more items in "find" so it matches exactly one location, or set all: true.`);const g=o.all?d:[d[0]],u=[];let p=0;for(const b of g)u.push(...s.children.slice(p,b)),u.push(...i),p=b+l.length;u.push(...s.children.slice(p));const h=g.length===1&&g[0]===0&&l.length===s.children.length,f=h?{...n.children[0],id:s.id}:{...s,children:u},m=h&&t?o.replace:Ji({children:[f]})[0];return{name:"replace_block",arguments:{id:s.id,content:[m]}}}function Uc(o,e){if(o.replace===""||o.all)return null;const t=X(e,o.id);if(!t)return null;const n=o.format==="html"||!o.format&&ht.test(o.find)?me(ee.fromAgentHtml(o.find,{existingDocument:e,preserveImageReferenceIds:!0})):me(Pn.fromMarkdown(o.find)),i=me(t);if(is(n)!==is(i))return null;const r=o.format==="html"||!o.format&&ht.test(o.replace)?jc(o.replace,e,t):Dc(o.replace),s=r.length===1&&/^<p\b[^>]*>[\s\S]*<\/p>$/i.test(r[0]),a=(o.format==="html"||!o.format&&ht.test(o.replace))&&/^<p\s+[^>]+>/i.test(o.replace.trim()),l=t.type==="footnote"?es(e,o.id):null,c=l!==null&&l!==o.id&&X(e,l)?.type==="paragraph",d=o.format!=="markdown"&&ht.test(o.find)&&!ht.test(o.find.replace(/<\/?(?:b|strong|i|em|u|s|strike|sup|sub|code|mark|span|a|br)\b[^>]*>/gi,""));return s&&!a&&(t.type==="table-cell"||c||t.type==="paragraph"&&(d||Ft(o.find)===Ft(i)))?null:{name:"replace_block",arguments:{id:o.id,content:r}}}function Hc(o,e){return Xc(o,e)??Uc(o,e)}function Ki(o,e){const t=X(o,e);return t?rs(t):null}function rs(o){const e=JSON.stringify(o);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(o,e){const t=new Map;for(const n of e){if(t.has(n))continue;const i=Ki(o,n);i!==null&&t.set(n,i)}return t}const os=50,ss="document_state_changed",Wc=new Set(["replace","replace_block","style_blocks","remove_block","remove_blocks"]);function Vi(o,e){const t=o.name==="replace"&&!!o.arguments&&typeof o.arguments=="object"&&Object.prototype.hasOwnProperty.call(o.arguments,"replacements"),n=o.name==="replace_many";if(!t&&!n)return{actions:[o]};const i=n?"replace_many":"replace";if(!o.arguments||typeof o.arguments!="object")return{actions:[],error:`${i} requires object arguments`};const r=o.arguments.id,s=o.arguments.replacements;if(!Array.isArray(s)||s.length===0)return{actions:[],error:`${i} requires a non-empty replacements array`};if(s.length>os)return{actions:[],error:`${i} supports at most ${os} replacements per call`};const a=[];for(let c=0;c<s.length;c++){const d=s[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=ns({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=Hc({type:"replace",id:g,find:d.find,replace:d.replace,format:"html",all:d.occurrence==="all"},e.doc);if(u){a.push({...u,id:`${o.id||i}-${c+1}`});continue}}catch(u){return{actions:[],error:u instanceof Error?u.message:String(u),failure:Vt(u)}}a.push({id:`${o.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 Yc(o){const{toolCall:e,docBefore:t,resultSets:n}=o,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 s=r.trim();if(!Wc.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(s);if(!a)return{actions:[],targetBlockIds:[],error:`Search result '${s}' is unavailable. Search result references are request-scoped; rerun search_document in this request, then retry.`,errorCode:ss};for(const g of a.blockIds){if(qi(t,g))return{actions:[],targetBlockIds:[],error:"Bulk search-result mutations cannot include footnote or endnote bodies. Target those note blocks individually."};const u=Ki(t,g);if(u===null||u!==a.blockHashes.get(g))return{actions:[],targetBlockIds:[],error:`Search result '${s}' is stale because block '${g}' changed or disappeared. Rerun search_document, then retry; no partial mutation was applied.`,errorCode:ss}}const{search_result_id:l,...c}=i,d=[];if(e.name==="replace")for(let g=0;g<a.blockIds.length;g++){const u=Vi({...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 as(o,e){const t={...e};for(const n of["lang","oxmlRPr","oxmlRange","sdtInline","field","aiGenerated","__htmlClassName"])t[n]===void 0&&o?.[n]!==void 0&&Object.assign(t,{[n]:o[n]});for(const n of io)t[n]===void 0&&o?.[n]===!1&&(t[n]=!1);if(t.docxRunPropertyResets===void 0){const n=Ii(o?.docxRunPropertyResets)?.split(",").filter(i=>i==="color"?t.color===void 0:t.backgroundColor===void 0);n?.length&&(t.docxRunPropertyResets=n.join(","))}return t}function zn(o,e){const t=o.map(s=>s.text).join("");if(!t||t!==e.map(s=>s.text).join("")){const s=new Set(o.filter(l=>l.text.length>0).map(l=>l.marks?.lang)),a=s.size===1?[...s][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 s of e){if(s.text.length===0){n.push({...s,marks:s.marks?{...s.marks}:void 0});continue}let a=0;for(;a<s.text.length;){for(;r===o[i].text.length;)i++,r=0;const l=o[i],c=Math.min(s.text.length-a,l.text.length-r);n.push({...s,text:s.text.slice(a,a+c),marks:as(l.marks,s.marks)}),a+=c,r+=c}}return n}function qc(o,e){const t=Ze(o),n=Array.from({length:t.cols},(l,c)=>Math.max(.001,o.columnWidths[c]||100/t.cols)),i=new Map;for(const l of e){const c=t.byId.get(l.cellId);if(!c)throw new pe("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 pe("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 pe("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),s=n.map((l,c)=>c).filter(l=>!i.has(l));if(r>100.001||!s.length&&Math.abs(r-100)>.001||s.length&&r>=100)throw new pe("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=s.reduce((l,c)=>l+n[c],0);return n.map((l,c)=>i.get(c)??(100-r)*l/a)}function ls(o,e,t,n){if(!n?.length)return;const i=e==="row"?o.cols:o.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 o.cells){const s=e==="row"?r.row:r.col,a=e==="row"?r.rowSpan:r.colSpan;if(s>=t||s+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 Jc(o){return{type:"paragraph",id:Y(),children:[{type:"text",text:""}]}}function Kc(o){return{type:"table-cell",id:Y(),children:[Jc()]}}function cs(o,e){return!o||o.length===0?Kc():{type:"table-cell",id:Y(),children:o}}function Wn(o,e){const t=o.get("content",S.XmlFragment);function n(i){for(let r=0;r<i.length;r++){const s=i.get(r);if(s instanceof S.XmlElement){if(s.nodeName==="table"&&s.getAttribute("id")===e)return s;if(s.nodeName==="container"||s.nodeName==="footnote"||s.nodeName==="table"||s.nodeName==="table-row"||s.nodeName==="table-cell"){const a=n(s);if(a)return a}}}return null}return n(t)??n(o.getXmlFragment("notes"))}function Gi(o,e){const t=Number(Q(o,e));return Number.isFinite(t)&&t>1?Math.floor(t):1}function Yn(o){const e=[];for(let a=0;a<o.length;a++){const l=o.get(a);l instanceof S.XmlElement&&l.nodeName==="table-row"&&e.push(l)}const t=o.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+=Gi(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)),s=[];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(Gi(u,"colSpan"),n-c),h=Math.min(Gi(u,"rowSpan"),i-a),f={el:u,row:a,col:c,rowSpan:h,colSpan:p,physicalIndex:d};s.push(f);for(let m=a;m<a+h;m++)for(let b=c;b<c+p;b++)r[m][b]===void 0&&(r[m][b]=f);c+=p,d++}}return{rows:i,cols:n,cells:s,occupancy:r,rowEls:e}}function Zt(o,e,t){t>1?o.setAttribute(e,String(t)):q(o,e)}function ds(o){return ke(o)}function Vc(o){const e=new S.XmlElement("table-row");e.setAttribute("id",o.id);let t=0;for(const n of o.children){const i=ds(n);e.insert(t++,[i])}return e}function Gc(o,e,t){const n=Wn(o,e);if(!n)return{success:!1,error:`Table with ID "${e}" not found.`};const i=Yn(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."}:(o.transact(()=>{for(const s of i.cells)s.col<=t&&t<s.col+s.colSpan&&(s.colSpan>1?Zt(s.el,"colSpan",s.colSpan-1):i.rowEls[s.row].delete(s.physicalIndex,1));const r=n.getAttribute("columnWidths");if(r){const s=JSON.parse(r);if(t<s.length){const a=s[t];s.splice(t,1);const l=s.reduce((d,g)=>d+g,0),c=l>0?s.map(d=>d+a*d/l):s;n.setAttribute("columnWidths",JSON.stringify(c))}}}),{success:!0})}function Zc(o,e){const t=Yn(o);if(e<0||e>=t.rows)return;for(const r of t.cells)r.row<e&&r.row+r.rowSpan>e&&Zt(r.el,"rowSpan",r.rowSpan-1);const n=t.cells.filter(r=>r.row===e&&r.rowSpan>1).sort((r,s)=>r.col-s.col);if(n.length>0&&e+1<t.rows){const r=t.rowEls[e+1],s=t.cells.filter(l=>l.row===e+1);let a=0;for(const l of n){const c=l.el.clone();Zt(c,"rowSpan",l.rowSpan-1);const d=s.filter(g=>g.col<l.col).length+a;r.insert(d,[c]),a++}}const i=t.rowEls[e];for(let r=0;r<o.length;r++)if(o.get(r)===i){o.delete(r,1);break}}function Qc(o,e,t){const n=Wn(o,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."}:(o.transact(()=>{Zc(n,t)}),{success:!0}):{success:!1,error:`Table with ID "${e}" not found.`}}function ed(o,e,t,n,i){const r=Wn(o,e);if(!r)return{success:!1,error:`Table with ID "${e}" not found.`};const s=Yn(r);if(s.rows===0)return{success:!1,error:"Table has no rows."};const a=s.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 ls(s,"column",l,i)||(o.transact(()=>{for(let g=0;g<s.rows;g++){const u=l>0&&l<a&&s.occupancy[g][l-1]===s.occupancy[g][l]?s.occupancy[g][l]:void 0;if(u){u.row===g&&Zt(u.el,"colSpan",u.colSpan+1);continue}const p=i?.[g],h=cs(p),f=ds(h),m=s.cells.filter(b=>b.row===g&&b.col<l).length;s.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 td(o,e,t,n){const i=Yn(e);return ls(i,"row",t,n)||(o.transact(()=>{const s=i.cells.filter(u=>u.row<t&&u.row+u.rowSpan>t),a=new Set;for(const u of s){Zt(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(cs(n?.[u]));const c={id:Y(),children:l},d=Vc(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 nd(o,e,t,n,i){const r=Wn(o,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 s=r.get(0);if(!(s instanceof S.XmlElement)||s.nodeName!=="table-row")return{success:!1,error:"Table has no rows."};const a=t==="before"?n:n+1;return td(o,r,a,i)}const gs=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"]);function id(o){if(!o||o.length<4)return!1;if(/^https?:\/\//i.test(o))try{return new URL(o),!0}catch{return!1}if(/^www\./i.test(o))try{return new URL(`https://${o}`),!0}catch{return!1}if(!o.includes(".")||!/^[a-zA-Z0-9]/.test(o))return!1;try{const e=new URL(`https://${o}`).hostname.split(".").filter(n=>n.length>0);if(e.length<2)return!1;const t=e[e.length-1].toLowerCase();if(gs.has(t))return!0;if(e.length>=3){const n=e[e.length-2].toLowerCase();if(gs.has(n))return!0}return!1}catch{return!1}}function rd(o){return/^https?:\/\//i.test(o)?o:`https://${o}`}function us(o){return o===" "||o===" "||o===`
|
|
23
|
-
`||o==="\r"}function hs(o){if(!o||o.length<4)return[];const e=[];let t=0;for(;t<o.length;){if(us(o[t])){t++;continue}let n=t,i=t;for(;i<o.length&&!us(o[i]);)i++;const r=o.slice(n,i);id(r)&&e.push({url:rd(r),originalText:r,start:n,end:i}),t=i}return e}function ue(o){for(const e of o.toArray())if(e instanceof S.XmlText)return e;return null}function Et(o){return o instanceof S.XmlElement&&o.nodeName==="header-footer"}function Lt(){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 od(o,e){const t=ue(o),n=o.parent instanceof S.XmlElement&&o.parent.nodeName==="list"?o.parent.getAttribute("variant")??void 0:void 0;if(t)return[{blockId:e,yBlock:o,yText:t,blockText:ft(t),listVariant:o.nodeName==="list-item"?n:void 0}];if(o.nodeName==="list"){const s=[];for(const a of o.toArray()){if(!(a instanceof S.XmlElement)||a.nodeName!=="list-item")continue;const l=ue(a);if(!l)continue;const c=a.getAttribute("id")||e;s.push({blockId:c,yBlock:a,yText:l,blockText:ft(l),listVariant:o.getAttribute("variant")??void 0})}return s}const i=[],r=s=>{for(const a of s.toArray()){if(!(a instanceof S.XmlElement))continue;const l=ue(a);l?i.push({blockId:a.getAttribute("id")??e,yBlock:a,yText:l,blockText:ft(l)}):r(a)}};return r(o),i}function sd(o,e){const t=new Set,n=r=>{const s=r.getAttribute("id"),a=typeof s=="string"?s:"",l=ue(r);if(a&&l&&!t.has(a)){const c=e({blockId:a,yBlock:r,yText:l,blockText:ft(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=Ut(o);for(const r of i.toArray())if(r instanceof S.XmlElement&&n(r))return}function ad(o,e,t,n=3){const i=et(t)?Jt(t):qt(t);if(!i||/^\s*$/.test(i))return null;const r=tt(i);if(!r||/^\s*$/.test(r))return null;const s=[];let a=0,l=!1;return sd(o,c=>{if(!(c.blockId===e||!tt(c.blockText).includes(r))&&(a++,s.length<n&&s.push(c.blockId),a>n))return l=!0,!0}),a===0?null:{blockIds:s,totalMatches:a,truncated:l}}function ld(o,e,t){const n=ad(o,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,s=r>0?n.truncated?` and at least ${r} more`:` and ${r} more`:"";return` This text appears in other blocks: ${i}${s}. Did you mean one of those block IDs?`}const Zi=new WeakMap;function Qi(o){return Zi.get(o)}const ge=o=>({kind:"block",...o}),we=o=>({kind:"textMark",...o}),cd=new Set(["bold","italic","underline","strikethrough","doubleStrikethrough","smallCaps","allCaps","code","superscript","subscript"]),fs={fontSize:{integer:!0,min:1,max:512},letterSpacing:{min:-20,max:100}},dd=[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"]})],er=new Map,ps=(o,e)=>{const t=o.toLowerCase(),n=er.get(t)??[];n.push(e),er.set(t,n)};for(const o of dd){ps(o.attr,o);for(const e of o.aliases??[])ps(e,o)}const ms={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 ft(o){const e=te(o);let t="";for(const n of e)n.insert&&typeof n.insert=="string"&&(t+=n.insert);return t}function bs(o,e,t){if(ft(e).length===0)return!!yt(o.getAttribute("_emptyTextMarks"))[t];const n=te(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 gd(o,e,t){const n=yt(o.getAttribute("_emptyTextMarks"));t?n[e]=!0:delete n[e],Object.keys(n).length===0?o.removeAttribute("_emptyTextMarks"):o.setAttribute("_emptyTextMarks",JSON.stringify(n))}function qn(o,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&&o.setAttribute("_emptyTextMarks",JSON.stringify(n.marks))}function ys(o,e,t){const n=yt(o.getAttribute("_emptyTextMarks"));t==null?delete n[e]:n[e]=t,Object.keys(n).length===0?o.removeAttribute("_emptyTextMarks"):o.setAttribute("_emptyTextMarks",JSON.stringify(n))}function ud(o,e,t){const n=Mt(o,e);if(!Number.isFinite(n))throw new Error(`set_block_attribute "${o}" expects a number.`);if(t.integer&&!Number.isInteger(n))throw new Error(`set_block_attribute "${o}" expects an integer value.`);if(t.min!==void 0&&n<t.min)throw new Error(`set_block_attribute "${o}" must be >= ${t.min}.`);if(t.max!==void 0&&n>t.max)throw new Error(`set_block_attribute "${o}" must be <= ${t.max}.`);return n}function hd(o){if(o==null)return"set";if(o==="set"||o==="toggle"||o==="remove")return o;throw new Error('set_block_attribute operation must be one of "set", "toggle", or "remove".')}function ks(o,e){let t=Array.isArray(e)?e:[e];if(typeof e=="string"){const r=e.trim();if(r.startsWith("[")&&r.endsWith("]"))try{const s=JSON.parse(r);Array.isArray(s)&&(t=s)}catch{}}const n=[],i=new Set;for(const r of t){if(typeof r!="string"||r.trim().length===0)throw new Error(`${o} requires a valid block ID or a non-empty list of block IDs.`);const s=r.trim();i.has(s)||(i.add(s),n.push(s))}if(n.length===0)throw new Error(`${o} requires a valid block ID or a non-empty list of block IDs.`);return n}function Ss(o){if(o===!0||o===!1)return o;if(typeof o=="string"){const e=o.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return!1}function Is(o,e,t){if(t.valueType==="string"){if(typeof e!="string")throw new Error(`set_block_attribute "${o}" expects a string value.`);if(t.enumValues&&!t.enumValues.includes(e))throw new Error(`set_block_attribute "${o}" must be one of: ${t.enumValues.join(", ")}.`);return e}if(t.valueType==="boolean"){if(typeof e!="boolean")throw new Error(`set_block_attribute "${o}" expects a boolean value.`);return String(e)}const n=Mt(o,e);if(!Number.isFinite(n))throw new Error(`set_block_attribute "${o}" expects a number.`);if(t.integer&&!Number.isInteger(n))throw new Error(`set_block_attribute "${o}" expects an integer value.`);if(t.min!==void 0&&n<t.min)throw new Error(`set_block_attribute "${o}" must be >= ${t.min}.`);if(t.max!==void 0&&n>t.max)throw new Error(`set_block_attribute "${o}" must be <= ${t.max}.`);return String(n)}function tr(o,e,t){if(t===void 0){q(o,e);return}o.setAttribute(e,String(t))}function vs(o,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(Is("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;tr(o,"firstLineIndent",i),tr(o,"leftIndent",r)}function xs(o,e,t){if(t===null){q(o,e);return}const n=e==="leftIndent"?Re(t):De(t);tr(o,e,n)}function Mt(o,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(o==="leftIndent"||o==="firstLineIndent"){const s=xi(t,{firstLine:o==="firstLineIndent"});if(s!==void 0)return s}const i=n.match(/^(-?\d+(?:\.\d+)?)(px|pt|in|cm|mm)$/);if(i){const s=Number(i[1]),a=i[2],l={px:1,pt:4/3,in:96,cm:96/2.54,mm:96/25.4};return s*l[a]}if(o==="heading"){const s=n.match(/^h([1-6])$/);if(s)return Number(s[1])}if(o==="lineSpacing"){const s={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(s[n]!==void 0)return s[n]}const r=Number(t);return Number.isFinite(r)?r:Number.NaN}function nt(o,e,t){const n=ft(t);o.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(o){const e=o.getAttribute("id");return typeof e=="string"&&e.length>0?e:o.nodeName}function Jn(o){return er.get(o.trim().toLowerCase())??[]}function pt(o,e,t,n){if(typeof t!="string")throw new Error(`${o} "${e}" expects a string value.`);const i=t.trim();if(i.length===0)throw new Error(`${o} "${e}" expects a non-empty string.`);if(/[<>;]/.test(i))throw new Error(`${o} "${e}" contains unsupported characters.`);if(e==="fontFamily"&&fd(i))throw new Error(`${o} "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(`${o} "${e}" must be one of: ${n.join(", ")}.`);return n?r:i}function fd(o){const e=o.trim().replace(/\s*!important\s*$/i,"").trim().toLowerCase();return["inherit","initial","unset","revert","revert-layer"].includes(e)}function nr(o,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(`${o} "${e}" expects a boolean value.`)}function As(o,e,t){if(typeof t!="string"&&typeof t!="number")return t;const n=o.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 Nt(o,e,t,n){const i=Mt(e,t);if(!Number.isFinite(i))throw new Error(`${o} "${e}" expects a number.`);const r=n.integer?Math.round(i):i;if(n.min!==void 0&&r<n.min)throw new Error(`${o} "${e}" must be >= ${n.min}.`);if(n.max!==void 0&&r>n.max)throw new Error(`${o} "${e}" must be <= ${n.max}.`);return r}function Be(o,e,t,n){const i=Te(e);if(t){nt(o,i,t);return}const r=`Updated ${n} on ${e.nodeName} block.`;o.push({kind:"replace",paragraphId:i,text:r,oldText:r})}function Kn(o,e){const t=o.parent;if(o.nodeName!=="paragraph"||!(t instanceof S.XmlElement)||t.nodeName!=="footnote"||!o.doc)return null;const n=He(o.doc).notes?.find(i=>i.id===t.getAttribute("id"))?.children.find(i=>i.id===o.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 ws(o){const{toolName:e,yBlock:t,yText:n,attribute:i,operation:r,value:s,config:a,anchors:l}=o;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"||s===null)c=null;else if(r==="toggle")c=!bs(t,n,i);else if(a.valueType==="boolean")c=s===void 0?!0:nr(e,i,s);else{if(s===void 0)throw new Error(`${e} "${i}" requires a value.`);a.valueType==="number"?c=Nt(e,i,s,a):c=pt(e,i,s)}if(i==="fontFamily"){const d=Kn(t,c);if(d)throw new Error(d)}if(n.length>0)re(n,0,n.length,{[i]:c===null?null:c}),nt(l,Te(t),n);else{ys(t,i,c);const d=`Text mark "${i}" ${c===null?"removed":"set"}.`;l.push({kind:"replace",paragraphId:Te(t),text:d,oldText:d})}}const Ts=new Set(["fontSize","fontFamily","color"]);function Cs(o){const{toolName:e,yBlock:t,attribute:n,operation:i,value:r,config:s,anchors:a}=o;if(!Ts.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=Nt(e,n,r,s);if(!bl(l))throw new Error(`${e} "fontSize" on a table of contents must be between ${yl} and ${kl} px.`);t.setAttribute(n,String(l))}else if(n==="color"){const l=typeof r=="string"?kn(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,pt(e,n,r))}Be(a,t,null,n)}function pd(o){const{yBlock:e}=o;if(e.nodeName==="paragraph"||e.nodeName==="list-item"){ws({...o,yText:ue(e)});return}if(e.nodeName==="toc"){Cs(o);return}const t=[],n=[],i=l=>{for(let c=0;c<l.length;c++){const d=l.get(c);if(d instanceof S.XmlElement&&!o.independentlySelectedTargets?.has(d)){if(d.nodeName==="paragraph"||d.nodeName==="list-item"){t.push(d);continue}if(d.nodeName==="toc"){Ts.has(o.attribute)&&n.push(d);continue}i(d)}}};if(i(e),o.attribute==="fontFamily"&&o.operation!=="toggle"){const l=o.operation==="remove"||o.value===null?null:pt(o.toolName,o.attribute,o.value);for(const c of t){const d=Kn(c,l);if(d)throw new Error(d)}}let r=0;const s=[],a=l=>{try{ws({...o,yBlock:l,yText:ue(l)}),r++}catch(c){s.push(c instanceof Error?c.message:String(c))}};for(const l of t)a(l);for(const l of n)try{Cs({...o,yBlock:l}),r++}catch(c){s.push(c instanceof Error?c.message:String(c))}if(r===0)throw new Error(s[0]??`${o.toolName} "${o.attribute}" found no descendant text blocks to style.`)}function md(o){const{toolName:e,yBlock:t,ranges:n,attribute:i,operation:r,value:s,config:a,anchors:l}=o,c=ue(t);if(!c)throw new Error(`${e} inline selector matched a block without text content.`);let d;if(r==="remove"||s===null?d=null:a.valueType==="boolean"?d=nr(e,i,s):a.valueType==="number"?d=Nt(e,i,s,a):d=pt(e,i,s),i==="fontFamily"){const g=Kn(t,d);if(g)throw new Error(g)}for(const g of n)re(c,g.start,g.length,{[i]:d===null?null:d});nt(l,Te(t),c)}function Vn(o){const{toolName:e,yBlock:t,attribute:n,operation:i,value:r,config:s,anchors:a}=o;if(!s.nodeNames.includes(t.nodeName))throw new Error(`${e} "${n}" is not valid for ${t.nodeName} blocks.`);if(n==="indentLevel"&&t.nodeName==="paragraph"){vs(t,i,r),Be(a,t,ue(t),n);return}if(n==="padding"&&t.nodeName==="table-cell"){if(i==="remove"||r===null)q(t,n);else{const l=Nt(e,n,r,s);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)q(t,"borders");else{const l=pt(e,n,r),c=Tn(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=Cn(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)q(t,"borders");else{const l=Ni(Q(t,"borders")),c=n==="borderColor"?pt(e,n,r):Nt(e,n,r,s),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=Cn(g);u&&t.setAttribute("borders",u)}Be(a,t,null,"borders");return}if(i==="remove"||r===null)q(t,n);else if(i==="toggle"){if(s.valueType!=="boolean")throw new Error(`${e} "${n}" only supports toggle for boolean attributes.`);const l=Ss(Q(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;s.valueType==="string"?l=pt(e,n,r,s.enumValues):s.valueType==="boolean"?l=String(nr(e,n,r)):l=String(Nt(e,n,r,s)),t.nodeName==="paragraph"&&(n==="leftIndent"||n==="firstLineIndent")?xs(t,n,Number(l)):t.setAttribute(n,l)}Be(a,t,ue(t),n)}function bd(o){if(o.config.nodeNames.includes(o.yBlock.nodeName)){Vn(o);return}if(!(o.config.nodeNames.includes("paragraph")||o.config.nodeNames.includes("list-item"))){Vn(o);return}let e=0;const t=[],n=i=>{for(let r=0;r<i.length;r++){const s=i.get(r);if(s instanceof S.XmlElement&&!o.independentlySelectedTargets.has(s)){if(s.nodeName==="paragraph"||s.nodeName==="list-item"){try{Vn({...o,yBlock:s}),e++}catch(a){t.push(a instanceof Error?a.message:String(a))}continue}n(s)}}};if(n(o.yBlock),e===0)throw new Error(t[0]??`${o.toolName} "${o.attribute}" found no descendant text blocks to style.`)}function yd(o){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[Ut(o),o.getXmlFragment("notes")])for(const i of n.toArray())i instanceof S.XmlElement&&t(i);return e}function ir(o){switch(o.nodeName){case"paragraph":{const e=o.getAttribute("heading");return typeof e=="string"&&/^[1-6]$/.test(e)?[`h${e}`]:["p"]}case"list":return o.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[o.nodeName]}}function kd(o,e){const t=[],n=i=>{for(let r=0;r<i.length;r++){const s=i.get(r);s instanceof S.XmlElement&&(ir(s).includes(e)&&t.push(s),n(s))}};return n(o),t}function Sd(o){const e=o.match(/^#([A-Za-z0-9_-]+)\s+([a-zA-Z][a-zA-Z0-9-]*)$/);return e?{id:e[1],tag:e[2].toLowerCase()}:null}function Qt(o){return o.toLowerCase()==="th"?"td":o.toLowerCase()}function rr(o){const e=o.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:Qt(e[1]),nthChild:t}}function en(o,e){if(e.tag!=="*"&&!ir(o).includes(e.tag))return!1;if(e.nthChild===void 0)return!0;const t=o.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(o)+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 Ps(o,e){if(!en(o,e[e.length-1]))return!1;let t=o.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 or={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 Id(o){const e=o.split(/\s+/).filter(Boolean),t=e.findIndex(i=>or[i.toLowerCase()]!==void 0);if(t<0)return null;const n=e.slice(t).map(i=>i.toLowerCase());return n.some(i=>!or[i])?null:{scopeSelector:t===0?"*":e.slice(0,t).join(" "),markAttributes:Array.from(new Set(n.map(i=>or[i])))}}function vd(o){if(o.nodeName==="paragraph"||o.nodeName==="list-item")return[o];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(o),e}function xd(o,e){if(e==="*")return!0;const t=o?.[e];return e==="link"||e==="backgroundColor"?typeof t=="string"&&t.length>0:t===!0}function Ad(o,e){const t=[];let n=0;for(const i of te(o)){if(typeof i.insert!="string")continue;const r=i.insert.length,s=i.attributes;if(r>0&&e.every(a=>xd(s,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 wd(o,e){const t=[...o,...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 Td(o){const e=Array.isArray(o)?o:[o],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 s=r.trim(),a=["all","document",":root"].includes(s.toLowerCase())?"*":s.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 Bs(o,e){const t=yd(o),n=[],i=new Set,r=[],s=[],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=Qt(c[1]),b=(c[2]??c[3]??c[4]).trim(),y=t.filter(k=>en(k,{tag:m})&&k.getAttribute("styleId")===b);y.length===0&&r.push(l);for(const k of y)a(k);continue}const d=l.match(/^#([A-Za-z0-9_-]+)\s*~\s*(\*|[a-zA-Z][a-zA-Z0-9-]*)$/);if(d){const m=J(o,d[1]),b=m?.parent;if(!m||!(b instanceof S.XmlElement)&&!(b instanceof S.XmlFragment)){r.push(l);continue}const y=b.toArray(),k=y.indexOf(m),I=Qt(d[2]),v=t.filter(x=>x.parent===b&&y.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=J(o,g[1]);if(!m){r.push(l);continue}const b=g[2].split(/\s+/).filter(Boolean).map(rr);if(b.some(v=>v===null)){s.push(`selector "${l}" is not supported; descendants may use block tags, :first-child, and :nth-child(n).`);continue}const y=b,k=v=>{let x=v;for(;x;){if(x===m)return!0;x=x.parent}return!1},I=t.filter(v=>k(v)&&(y.length!==1||y[0].tag!=="*"||v!==m)&&Ps(v,y));I.length===0&&r.push(l);for(const v of I)a(v);continue}const u=Sd(l);if(u){if(u.tag==="span"){s.push('selector "span" is inline, not a block selector; target containing blocks with p, li, h1-h6, or #blockId.');continue}const m=J(o,u.id);if(!m){r.push(l);continue}const b=kd(m,Qt(u.tag));if(b.length===0){r.push(l);continue}for(const y of b)a(y);continue}if(l.includes(" ")&&!l.startsWith("#")){const m=l.split(/\s+/).filter(Boolean).map(rr);if(m.some(k=>k===null)){s.push(`selector "${l}" is not supported; descendant selectors may use block tags, :first-child, and :nth-child(n).`);continue}const b=m;if(b.some(k=>k.tag==="span")){s.push(`selector "${l}" contains an inline selector; target its containing block instead.`);continue}const y=t.filter(k=>Ps(k,b));y.length===0&&r.push(l);for(const k of y)a(k);continue}if(l.startsWith("#")){const m=l.slice(1).trim();if(!m||/[\s.#:[\]>+~]/.test(m)){s.push(`selector "${l}" is not supported; use #blockId with a plain block ID.`);continue}const b=J(o,m);b?a(b):r.push(l);continue}const p=rr(l);if(p){let m=0;for(const b of t)en(b,p)&&(a(b),m+=1);m===0&&r.push(l);continue}if(!/^[a-zA-Z][a-zA-Z0-9-]*$/.test(l)){s.push(`selector "${l}" is not supported; use *, #id, or tag selectors like p, h2, li, table.`);continue}const h=Qt(l);if(h==="span"){s.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)ir(m).includes(h)&&(a(m),f++);f===0&&r.push(l)}return{targets:n,unmatchedSelectors:r,invalidSelectorErrors:s}}function Cd(o,e){const t=Td(e),n=[],i=[];for(const c of t){const d=Id(c);d?i.push({selector:c,parsed:d}):n.push(c)}const r=n.length>0?Bs(o,n):{targets:[],unmatchedSelectors:[],invalidSelectorErrors:[]},s=new Map,a=[...r.unmatchedSelectors],l=[...r.invalidSelectorErrors];for(const{selector:c,parsed:d}of i){const g=Bs(o,[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 vd(h)){const m=Te(f);if(p.has(m))continue;p.add(m);const b=ue(f);if(!b)continue;const y=Ad(b,d.markAttributes);if(y.length===0)continue;u+=y.length;const k=s.get(m);k?k.ranges=wd(k.ranges,y):s.set(m,{yBlock:f,ranges:y})}u===0&&a.push(c)}return{targets:r.targets,inlineTargets:Array.from(s.values()),unmatchedSelectors:a,invalidSelectorErrors:l}}function mt(o){return o.trim().toLowerCase().replace(/[-_\s]/g,"")}function Pd(o){let e;if(Array.isArray(o))e=o.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(o&&typeof o=="object")e=Object.entries(o);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:mt(t),value:n}))}function Bd(o){const e=[],t=[],n=new Set,i=(r,s,a)=>{const l=`${s.kind}:${s.attr}`;let c=a;if(s.kind==="textMark"&&s.attr==="color"||s.kind==="block"&&(s.attr==="borderColor"||s.attr==="backgroundColor")){if(a!==null&&typeof a!="string")throw new Error(`style_blocks "${s.attr}" expects a CSS color string or null.`);if(typeof a=="string"&&(c=kn(a),!c))throw new Error(`style_blocks "${s.attr}" does not support ${JSON.stringify(a)}. Use a CSS named color, hex color, or CSS color function.`)}if(s.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:s,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:s}of o){if(r.trim().toLowerCase()==="border"){if(typeof s=="string"&&Tn(s)){for(const d of Jn("borders"))i(r,d,s);continue}const l=Jn("borderWidth"),c=Jn("borderColor");if(s===null||typeof s=="number"){for(const d of l)i(r,d,s);if(s===null)for(const d of c)i(r,d,null);continue}if(typeof s=="string"){const d=s.match(/(?:^|\s)(\d+(?:\.\d+)?)(?:px|pt)?(?:\s|$)/i),g=Array.from(s.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=Jn(r);if(a.length===0){t.push(r);continue}for(const l of a)i(r,l,s)}return Object.assign(e,{unsupportedAttrs:t})}function $s(o,e,t){const n=new Map;for(const r of o){const s=mt(r.rawName),a=n.get(s)??[];a.push(r),n.set(s,a)}const i=[];for(const r of n.values()){const s=r.filter(c=>c.entry.kind==="textMark"),a=r.filter(c=>c.entry.kind==="block");if(s.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(s.length===0||a.length===0){i.push(...r);continue}if(t){i.push(...s);continue}const l=a.filter(c=>c.entry.kind==="block"&&c.entry.nodeNames.some(d=>d===e.nodeName));i.push(...l.length>0?l:s)}return i}function Fs(o){const e=[];for(const t of o){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: ${Wt.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: ${Wt.join(", ")}.`);t.value=i,n.toLowerCase()!==i&&e.push(`${t.rawName}: ${n} -> ${i}`)}return e}function Ot(o,e,t,n){o[t].push(n);const i=o.issuesByRawName.get(e.canonicalName)??[];i.push(n),o.issuesByRawName.set(e.canonicalName,i)}function Gn(o,e){for(let t=o.length-1;t>=0;t--)if(o[t].canonicalName===e)return o[t]}function je(o){return typeof o=="string"?o.trim().toLowerCase():void 0}function tn(o){if(typeof o!="string")return;const e=o.trim().match(/^(-?\d+(?:\.\d+)?)%$/);if(!e)return;const t=Number(e[1]);return Number.isFinite(t)&&t>0?t:void 0}function Zn(o){return o===0?!0:typeof o=="string"&&/^[-+]?0+(?:\.0+)?(?:px|pt|in|cm|mm|%)?$/i.test(o.trim())}function $d(o){let e=o;for(;e.parent instanceof S.XmlElement;)e=e.parent;return e}function sr(o,e){const t=Te($d(e)),n=o.children.findIndex(c=>c.id===t),i=n>=0?o.children.slice(n).find(c=>c.type==="section-break"):void 0,r=oo(o.pageLayout,i?.type==="section-break"?i.layout:void 0),{pageWidth:s}=Zr(r),a=Math.max(1,s-r.marginLeftPx-r.marginRightPx),l=r.columnGapTwips/15;return Math.max(1,Math.round(Wl(a,r.columnCount,l)))}function Fd(o){if(o===null)return{remove:!0};if(typeof o=="number")return!Number.isFinite(o)||o<0?null:o===0?{remove:!0}:{remove:!1,style:"single",width:o};if(typeof o!="string")return null;const e=o.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 s=n?Number(n[1]):void 0,a=s===void 0?void 0:n?.[2]?.toLowerCase()==="pt"?s*(4/3):s,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 Ed(o){if(o.yBlock.nodeName!=="paragraph")return;const e={bordertop:"top",borderright:"right",borderbottom:"bottom",borderleft:"left"};for(const t of o.rawAttrs){const n=e[t.canonicalName];if(t.canonicalName!=="border"&&!n)continue;o.result.handledRawNames.add(t.canonicalName);const i=Fd(t.value);if(!i){Ot(o.result,t,"errors",`${Te(o.yBlock)}.borders: style_blocks "${t.rawName}" expects CSS border syntax such as "1px solid #cccccc".`);continue}let r={};try{const a=JSON.parse(String(Q(o.yBlock,"borders")??"{}"));a&&typeof a=="object"&&!Array.isArray(a)&&(r=a)}catch{r={}}const s=n?[n]:["top","right","bottom","left"];if(i.remove)for(const a of s)delete r[a];else for(const a of s){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?o.yBlock.setAttribute("borders",JSON.stringify(r)):q(o.yBlock,"borders"),Be(o.anchors,o.yBlock,ue(o.yBlock),"borders"),o.result.appliedAttrs.push(`${t.rawName} -> paragraph borders`),o.result.exactMappings.push(`${t.rawName} -> paragraph borders`)}}function Ld(o){if(o.yBlock.nodeName!=="image")return;const e=x=>Gn(o.rawAttrs,x),t=e("display");t&&je(t.value)==="block"&&(o.result.handledRawNames.add(t.canonicalName),Ot(o.result,t,"ignoredAttrs",`${t.rawName}: block`));const n=e("float"),i=je(n?.value);n&&(i==="left"||i==="right")&&(o.result.handledRawNames.add(n.canonicalName),o.yBlock.setAttribute("align",i),Be(o.anchors,o.yBlock,null,"align"),o.result.appliedAttrs.push(`${n.rawName} -> align`),o.result.approximateMappings.push(`${n.rawName}: ${i} -> align: ${i} without text wrapping`));const r=e("marginleft"),s=e("marginright"),a=je(r?.value),l=je(s?.value);let c;a==="auto"&&l==="auto"?c="center":a==="auto"&&(!s||Zn(s.value))?c="right":l==="auto"&&(!r||Zn(r.value))&&(c="left"),c&&(r&&o.result.handledRawNames.add(r.canonicalName),s&&o.result.handledRawNames.add(s.canonicalName),o.yBlock.setAttribute("align",c),Be(o.anchors,o.yBlock,null,"align"),o.result.appliedAttrs.push("auto margins -> align"),o.result.exactMappings.push(`margin-left/margin-right auto -> align: ${c}`));for(const x of["margintop","marginright","marginbottom","marginleft"]){const A=e(x);!A||o.result.handledRawNames.has(A.canonicalName)||(o.result.handledRawNames.add(A.canonicalName),Zn(A.value)?Ot(o.result,A,"ignoredAttrs",`${A.rawName}: ${String(A.value)}`):Ot(o.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=sr(o.doc,o.yBlock),b=Math.max(1,Number(o.yBlock.getAttribute("width"))||1),y=Math.max(1,Number(o.yBlock.getAttribute("height"))||1);let k=b,I=!1,v=!1;if(h!==void 0&&d)k=Math.max(1,Math.round(m*h/100)),o.result.handledRawNames.add(d.canonicalName),I=!0,v=!0;else if(p&&d){const x=Mt("width",d.value);Number.isFinite(x)&&x>0&&(k=Math.max(1,Math.round(x)),o.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),o.result.handledRawNames.add(g.canonicalName),I=!0,o.result.approximateMappings.push(`${g.rawName}: ${String(g.value)} -> fixed ${k}px snapshot`)}if(I){o.yBlock.setAttribute("width",String(k));const x=u&&!p?Mt("height",u.value):Number.NaN,A=p||!Number.isFinite(x);if(A){const w=Math.max(1,Math.round(y*k/b));o.yBlock.setAttribute("height",String(w))}p&&u&&o.result.handledRawNames.add(u.canonicalName),Be(o.anchors,o.yBlock,null,"width/height"),o.result.appliedAttrs.push("responsive image size -> fixed snapshot"),v&&d&&o.result.approximateMappings.push(`${d.rawName}: ${String(d.value)} -> fixed ${k}px snapshot${A?" with auto height":""}`)}else p&&u&&(o.result.handledRawNames.add(u.canonicalName),Ot(o.result,u,"ignoredAttrs",`${u.rawName}: auto`))}function Md(o){if(o.yBlock.nodeName!=="table")return;const e=s=>Gn(o.rawAttrs,s),t=e("width"),n=tn(t?.value);if(t&&n!==void 0){const s=sr(o.doc,o.yBlock),a=Math.max(1,Math.round(s*n/100));o.result.handledRawNames.add(t.canonicalName),o.yBlock.setAttribute("tableWidth",String(a)),Be(o.anchors,o.yBlock,null,"tableWidth"),o.result.appliedAttrs.push("responsive table width -> fixed snapshot"),o.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"&&(o.result.handledRawNames.add(i.canonicalName),o.result.handledRawNames.add(r.canonicalName),o.yBlock.setAttribute("align","center"),Be(o.anchors,o.yBlock,null,"align"),o.result.appliedAttrs.push("auto margins -> align"),o.result.exactMappings.push("margin-left/margin-right auto -> align: center"))}function Nd(o){if(o.yBlock.nodeName!=="paragraph")return;const e=a=>Gn(o.rawAttrs,a),t=e("breakafter"),n=e("breakbefore"),i=e("breakinside");if(!t&&!n&&!i)return;const r=new Set(String(Q(o.yBlock,"pagination")??"").split(",").filter(Boolean));t&&(o.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"),o.result.appliedAttrs.push(`${t.rawName} -> keepNext`)),i&&(o.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"),o.result.appliedAttrs.push(`${i.rawName} -> keepLines`)),n&&(o.result.handledRawNames.add(n.canonicalName),Ot(o.result,n,"ignoredAttrs",`${n.rawName}: ${String(n.value)}`));const s=Array.from(r).join(",");s?o.yBlock.setAttribute("pagination",s):q(o.yBlock,"pagination"),Be(o.anchors,o.yBlock,ue(o.yBlock),"pagination")}function Od(o){const e={issuesByRawName:new Map,handledRawNames:new Set,appliedAttrs:[],exactMappings:[],approximateMappings:[],ignoredAttrs:[],unsupportedImageSpacing:[],errors:[]};return Ed({yBlock:o.yBlock,rawAttrs:o.rawAttrs,anchors:o.anchors,result:e}),Nd({...o,result:e}),Ld({...o,result:e}),Md({...o,result:e}),e}function Rd(o){const{inlineRangeCount:e,unsupportedAttrs:t,unmatchedSelectors:n,invalidSelectorErrors:i,skippedTargetErrors:r,exactCompatibilityMappings:s,approximateCompatibilityMappings:a,ignoredCompatibilityAttrs:l,unsupportedImageSpacing:c}=o,d=o.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(s.length>0&&g.push(`Compatibility mappings: ${Array.from(new Set(s)).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 Dd(o){const e=yt(o.getAttribute("_emptyTextMarks"));for(const t of $o)delete e[t];Object.keys(e).length===0?o.removeAttribute("_emptyTextMarks"):o.setAttribute("_emptyTextMarks",JSON.stringify(e))}function _d(o,e=1){if(typeof o!="number"||!Number.isFinite(o))return e;const t=Math.floor(o);return t>=1?t:e}function jd(o){const e=ue(o);if(e){const n=te(e);let i="";for(const r of n)r.insert&&typeof r.insert=="string"&&(i+=r.insert);return i}const t=o.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 Es(o,e,t){const n=jd(o),i=ue(o),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 Xd(o,e){const t=o.parent;if(!(t instanceof S.XmlElement)&&!(t instanceof S.XmlFragment)||o.nodeName!=="list")return null;const n=t.toArray().indexOf(o);if(n<0)return null;const i=[];for(const r of o.toArray()){if(!(r instanceof S.XmlElement)||r.nodeName!=="list-item")continue;const s=new S.XmlElement("paragraph");s.setAttribute("id",r.getAttribute("id")||Y());const a=Q(r,"direction");(a==="ltr"||a==="rtl")&&s.setAttribute("direction",a);for(const g of["lineSpacing","spaceBefore","spaceAfter","contextualSpacing"]){const u=Q(r,g)??Q(o,g);u!==void 0&&s.setAttribute(g,String(u))}const l=r.getAttribute("_emptyTextMarks");l&&s.setAttribute("_emptyTextMarks",l);const c=ue(r),d=new S.XmlText;c&&ml(d,te(c)),s.insert(0,[d]),i.push(s)}if(i.length===0)return null;Es(o,o.getAttribute("id"),e),t.delete(n,1),t.insert(n,i);for(const r of i){const s=ue(r);if(!s)continue;const a=ft(s);e.push({kind:"insert",paragraphId:r.getAttribute("id"),from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(s,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(s,a.length,0)),text:a})}return i}function Ls(o,e){if(e.link)return[{text:o,marks:e}];const t=hs(o);if(t.length===0)return[{text:o,marks:e}];const n=[];let i=0;for(const r of t)r.start>i&&n.push({text:o.slice(i,r.start),marks:e}),n.push({text:r.originalText,marks:{...e,link:r.url}}),i=r.end;return i<o.length&&n.push({text:o.slice(i),marks:e}),n}function Qn(o){return ke(so(o,e=>!e.text||e.marks?.link?e:Ls(e.text,e.marks||{}).map(t=>({type:"text",text:t.text,marks:t.marks}))))}function Ms(o,e){return Yt(cc(e==="todo"?{...o,checked:o.checked??!1}:o))}function Ns(o,e,t,n=!1){return o.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(o,e,t,n){const i=Ls(t,n);let r=e;for(const s of i)ne(o,r,s.text,s.marks),r+=s.text.length;return r}function Os(o,e,t){const n=o.toString(),i=t??n.length,r=n.slice(e,i),s=hs(r);for(const a of s){const l=e+a.start;re(o,l,a.end-a.start,{link:a.url})}}function ar(o,e){if(!Ht(o,e)||o.children.length!==e.children.length)return!1;for(let t=0;t<o.children.length;t++){const n=o.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 ei(o,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?q(o,i):o.setAttribute(i,String(r))}const n=We(e);n===void 0?q(o,"pagination"):o.setAttribute("pagination",n)}function Ud(o,e){if(o.length!==e.length)return!1;for(let t=0;t<o.length;t++){const n=o[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 Hd(o,e){return o.type!==e.type?!1:o.type==="paragraph"&&e.type==="paragraph"?ar(o,e):Ud(o.children,e.children)}function Rs(o){return o.map(e=>({...e,marks:e.marks?{...e.marks}:void 0}))}function Ds(o,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 s of r.children){const a=t(s.children);if(a)return a}}return null};return t(o.children)}function _s(o){return o.replace(/�?39;|'/g,"'").trim()}function zd(o,e,t){const n=o.indexOf(e);return n===-1?o:o.slice(0,n)+t+o.slice(n+e.length)}function Wd(o,e){if(e.type==="paragraph")return _s(ee.toAgentHtml({type:"doc",children:[{...e,children:Rs(e.children)}]}));if(o.listVariant==="todo")return null;const t={type:"list",id:"__agent_html_replace__",variant:o.listVariant==="ordered"?"ordered":"unordered",children:[{...e,children:Rs(e.children),indentLevel:void 0}]},n=_s(ee.toAgentHtml({type:"doc",children:[t]})).match(/^<(?:ul|ol)(?:\s[^>]*)?>([\s\S]*)<\/(?:ul|ol)>$/);return n?n[1].trim():null}function Yd(o,e,t,n){try{if(t.type==="paragraph"){const s=ee.fromAgentHtml(e,{existingDocument:n,replacementBlock:t});return s.children.length!==1||s.children[0].type!=="paragraph"?null:s.children[0]}if(o.listVariant==="todo")return null;const i=o.listVariant==="ordered"?"ol":"ul",r=ee.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 qd(o,e){const t=/<mark\b[^>]*\bcolor=(?:"([^"]+)"|'([^']+)')[^>]*>/i,n=o.match(t),i=e.match(t),r=n?.[1]??n?.[2],s=i?.[1]??i?.[2];if(!r||!s||r===s)return null;const a=_e(r),l=_e(s);return!a||a!==l?null:`Highlight colors ${JSON.stringify(r)} and ${JSON.stringify(s)} both resolve to ${JSON.stringify(a)}, so this replacement is a no-op. Use a different canonical highlight color: ${Wt.join(", ")}.`}function Jd(o){const e=/<mark\b[^>]*\bcolor=(?:"([^"]+)"|'([^']+)')[^>]*>/gi;for(const t of o.matchAll(e)){const n=t[1]??t[2];if(n&&!_e(n))throw new Error(`Unsupported highlight color ${JSON.stringify(n)}. Use one of: ${Wt.join(", ")}.`)}}function js(o){const e=o?.comment;return typeof e!="string"||e.length===0?[]:Array.from(new Set(e.split(",").map(t=>t.trim()).filter(Boolean))).sort()}function rt(o,e={}){const t=Object.entries(o??{}).filter(([n,i])=>i!==void 0&&(n!=="comment"||!e.ignoreComment)).map(([n,i])=>n==="comment"?[n,js(o).join(",")]:[n,i]).filter(([,n])=>n!=="").sort(([n],[i])=>n<i?-1:n>i?1:0);return JSON.stringify(t)}function Kd(o){return Object.fromEntries(Object.entries(o).sort(([e],[t])=>e<t?-1:e>t?1:0))}function ti(o){return o.flatMap(e=>{const{comment:t,...n}=e.marks??{},i=js(e.marks);return Array.from({length:e.text.length},(r,s)=>({value:e.text[s],marks:n,comment:i}))})}function Vd(o){return o.length===0?[]:o.reduce((e,t)=>e.filter(n=>t.includes(n)))}const bt=-1,lr=0,nn=1;function Gd(o){const e=[];for(let t=0;t<o.length;t++){const[n,i]=o[t],r=o[t+1];if(!(r!==void 0&&(n===bt&&r[0]===nn||n===nn&&r[0]===bt))){e.push([n,i]);continue}const s=n===bt?i:r[1],a=n===nn?i:r[1];let l=0;const c=Math.min(s.length,a.length);for(;l<c&&s[l]===a[l];)l++;let d=0;const g=c-l;for(;d<g&&s[s.length-1-d]===a[a.length-1-d];)d++;l>0&&e.push([lr,s.slice(0,l)]);const u=s.slice(l,s.length-d),p=a.slice(l,a.length-d);u.length>0&&e.push([bt,u]),p.length>0&&e.push([nn,p]),d>0&&e.push([lr,s.slice(s.length-d)]),t++}return e}function Zd(o,e){const t=ti(o),n=ti(e),i=Gd(dc([],t.map(d=>d.value).join(""),n.map(d=>d.value).join(""))),r=new Array(n.length),s=new Array(n.length);let a=0,l=0;for(let d=0;d<i.length;d++){const[g,u]=i[d];if(g===lr){for(let I=0;I<u.length;I++)r[l+I]=t[a+I].comment,s[l+I]=t[a+I].marks.lang;a+=u.length,l+=u.length;continue}if(g===bt){a+=u.length;continue}if(g!==nn)continue;const p=i[d-1],h=i[d+1],f=[];p?.[0]===bt&&f.push(...t.slice(a-p[1].length,a)),h?.[0]===bt&&f.push(...t.slice(a,a+h[1].length));const m=f.length>0?f:[t[a-1],t[a]].filter(I=>!!I),b=Vd(m.map(I=>I.comment)),y=m[0]?.marks.lang,k=typeof y=="string"&&m.every(I=>I.marks.lang===y)?y:void 0;for(let I=0;I<u.length;I++)r[l+I]=b,s[l+I]=k;l+=u.length}const c=[];return n.forEach((d,g)=>{const u=r[g]??[],p=Kd({...d.marks,...d.marks.lang===void 0&&s[g]!==void 0?{lang:s[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 Qd(o,e){const t=ti(o),n=ti(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 Xs(o,e,t,n,i){if(t=Bt(t),n=Bt(n),t.length===0)return null;const r=Ds(e,o.blockId);if(!r)return null;const s=Wd(o,r),a=s?Bt(s):null;if(!a||!a.includes(t))return null;const l=Lo(a,t).length;if(!i&&l>1)throw new Error(`Found ${l} matches for ${JSON.stringify(t)} in block '${o.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.`);Jd(n);const c=i?a.split(t).join(n):zd(a,t,n);if(c===a)return null;const d=Yd(o,c,r,e);if(!d)throw new Error(`Matched AgentHtml in block '${o.blockId}', but the replacement is not a supported single-block text update.`);if(d.type!==r.type)throw new Error(`Matched AgentHtml in block '${o.blockId}', but the replacement changes the block structure. Keep replace() within a single compatible text block.`);const g={...d,children:Zd(r.children,zn(r.children,d.children))};if(Hd(r,g)||Qd(r.children,g.children)&&(r.type!=="paragraph"||g.type!=="paragraph"||Ht(r,g)))throw new Error(qd(t,n)??`Matched AgentHtml in block '${o.blockId}', but the replacement would not change any supported text or formatting.`);return{blockId:o.blockId,yBlock:o.yBlock,currentBlock:r,replacementBlock:g}}function ni(o,e){const t=ue(o.yBlock);if(!t)throw new Error(`Target block '${o.blockId}' has no text content to replace.`);const n=h=>h.flatMap(f=>Array.from({length:f.text.length},(m,b)=>({value:f.text[b],marks:f.marks||{}}))),i=(h,f)=>h.value===f.value&&rt(h.marks)===rt(f.marks),r=n(o.currentBlock.children),s=n(o.replacementBlock.children);let a=0;for(;a<r.length&&a<s.length&&i(r[a],s[a]);)a++;let l=0;for(;l<r.length-a&&l<s.length-a&&i(r[r.length-l-1],s[s.length-l-1]);)l++;const c=r.length-a-l,d=s.slice(a,s.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)}o.currentBlock.type==="paragraph"&&o.replacementBlock.type==="paragraph"&&(o.replacementBlock.heading?o.yBlock.setAttribute("heading",String(o.replacementBlock.heading)):o.yBlock.removeAttribute("heading"),o.replacementBlock.align?o.yBlock.setAttribute("align",o.replacementBlock.align):q(o.yBlock,"align")),e.push({kind:"replace",paragraphId:o.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 ze(o,e,t,n){const i=[];Ie(e,{verifiedUnchanged:!1,styleEffects:void 0}),Zi.delete(e);const r=e.name;n&&r!=="insert_block"&&(n.lastInsertedBlock=void 0);const s=e.arguments;if(r==="replace_many"||r==="replace"&&Array.isArray(s?.replacements)){const a=Vi({...e,id:t??"replacement-batch"},{doc:He(o),loadedBlockIds:null});if(a.error){const d=a.failure;throw new pe(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=ze(o,g,t,l);if(c=c&&!!$e(g)?.verifiedUnchanged,i.push(...u),!l){const p=He(o);l={document:p,htmlParsingContext:ee.createParsingContext(p),refreshDocumentIncrementally:!0}}}return Ie(e,{verifiedUnchanged:c}),i}switch(e.name){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(o);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=Ut(o),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(o,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((Et(p)||p===o.getXmlFragment("chrome"))&&Lt(),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:X(g,I)??void 0)}}let b;if(u.includes("<")&&u.includes(">")?b=ee.fromAgentHtml(u,{previousBlock:f,existingDocument:g,parsingContext:n?.htmlParsingContext,listItemBaseIndent:p instanceof S.XmlElement&&p.nodeName==="list"?Number(J(o,a)?.getAttribute("indentLevel")??0):void 0}):b=ee.fromAgentHtml(`<p>${u}</p>`,{previousBlock:f,existingDocument:g,parsingContext:n?.htmlParsingContext,listItemBaseIndent:p instanceof S.XmlElement&&p.nodeName==="list"?Number(J(o,a)?.getAttribute("indentLevel")??0):void 0}),b.children.length!==1)throw new Error(`insert_block should produce exactly one block. Got ${b.children.length} blocks from content: ${u}`);const y=b.children[0];if(!d)throw new Error("insert_block must have stableId set by preprocessor");if(y.id=d,p instanceof S.XmlElement&&p.nodeName==="list"){const k=J(o,a),I=Ns([y],Number(k?.getAttribute("indentLevel")??0),d,!0);p.insert(h,I.map(v=>ke(v))),i.push({kind:"insert",paragraphId:p.getAttribute("id"),text:I.map(v=>v.children.map(x=>x.text).join("")).join(`
|
|
24
|
-
`)});break}if(y.type==="paragraph"){const k=y,I=new S.XmlElement("paragraph");I.setAttribute("id",d),ei(I,k);const v=new S.XmlText;let x=0;k.children.forEach(w=>{if(w.type==="text"){const E=w;x=it(v,x,E.text,E.marks||{})}}),qn(I,k,x),I.insert(0,[v]),p.insert(h,[I]);const A=k.children.filter(w=>w.type==="text").map(w=>w.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(y.type==="list"){const k=Qn(y);p.insert(h,[k]);const I=[];for(const v of k.toArray()){if(!(v instanceof S.XmlElement))continue;const x=se(v);if(!x)continue;const A=te(x).map(w=>typeof w.insert=="string"?w.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(y.type==="table"){const k=Qn({...y,id:d});p.insert(h,[k]),i.push({kind:"insert",paragraphId:d,text:"Table inserted"})}else if(y.type==="code"){const k=y,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(y.type==="math"){const k=y,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(y.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(y.type==="toc"){const k=ke({...y,id:d});p.insert(h,[k]),i.push({kind:"insert",paragraphId:d,text:"Table of contents inserted"})}else if(y.type==="image"){const k=y,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 ${y.type}`);n&&(n.lastInsertedBlock={id:d,yParent:p,index:h,block:y},p===o.getXmlFragment("content")?n.document.children.splice(h,0,y):(n.document=he(o),n.htmlParsingContext=ee.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(o),g=J(o,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=od(g,a);const p=Uo(Ds(d,a)??X(d,a),l);if(p&&(u=u.filter(b=>p.has(b.blockId))),p&&u.length===0)throw new pe("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 b=u[0];dr(b.yText,0,0,l,c,b.blockId,i,yt(b.yBlock.getAttribute("_emptyTextMarks")));break}const h=b=>u.map(y=>({...y,matches:qs(y.blockText,b)})).filter(y=>y.matches.length>0);if(et(l)){const b=u.map(y=>Xs(y,d,l,c,e.name==="replace_all")).filter(y=>y!==null);if(b.length>0){if(e.name==="replace"&&b.length>1)throw new Error(`Found ${b.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")ni(b[0],i);else for(const y of b)ni(y,i);break}}let f=h(l);if(f.length===0){const b=Ws(l);if(b!==l&&b.trim()!==""){const y=h(b);y.length>0&&(l=b,c=Ws(c),f=y)}}if(f.length===0){const b=u.map(x=>Xs(x,d,l,c,e.name==="replace_all")).filter(x=>x!==null);if(b.length>0){if(e.name==="replace")ni(b[0],i);else for(const x of b)ni(x,i);break}const y=u.map(x=>x.blockText).join(`
|
|
25
|
-
`),k=y.length>100?y.slice(0,100)+"...":y,I=ld(o,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 pe("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 pe("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((b,y)=>b+y.matches.length,0);if((e.name==="replace_all"||m===1)&&f.every(b=>b.matches.every(y=>Hs(b.yText,y.offset,y.length,l,c)))){Ie(e,{verifiedUnchanged:!0});break}if(e.name==="replace"){const b=f.reduce((I,v)=>I+v.matches.length,0);if(b>1)throw new Error(`Found ${b} 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 y=f[0],k=y.matches[0];dr(y.yText,k.offset,k.length,l,c,y.blockId,i)}else for(const b of f){let y=-1;b.matches=b.matches.filter(k=>k.offset<y?!1:(y=k.offset+k.length,!0));for(let k=b.matches.length-1;k>=0;k--){const I=b.matches[k];dr(b.yText,I.offset,I.length,l,c,b.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=_d(c,1),g=n?.document??he(o),u=X(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(o,a);if(!p)throw new Error(`Y.js block not found for id: ${a}`);const{yBlock:h,yParent:f,index:m}=p,b=Et(f);if((h.nodeName==="header-footer"||b&&d!==1)&&Lt(),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 w=A.getAttribute("id");Es(A,w??void 0,i),f.delete(m+1,1)}}const y=zt(g,a),k=y>0?g.children[y-1]:void 0;{const I=(Array.isArray(l)?l:[l]).join(""),v=ee.fromAgentHtml(I,{previousBlock:k,replacementBlock:u,existingDocument:g,listItemBaseIndent:h.nodeName==="list-item"?Number(h.getAttribute("indentLevel")??0):void 0});if(b&&(v.children.length!==1||v.children[0].type!=="paragraph")&&Lt(),h.nodeName==="list-item"&&f instanceof S.XmlElement&&f.nodeName==="list"){const x=Ns(v.children,Number(h.getAttribute("indentLevel")??0),a,!0);if(d===1&&x.length===1&&u.type==="list"){const A=u.children.find(w=>w.id===a);if(u.variant==="todo"&&x[0].checked===void 0&&A?.checked!==void 0&&(x[0].checked=A.checked),x[0].children=zn(A?.children??[],x[0].children),A&&Ms(A,u.variant)===Ms(x[0],u.variant)){Ie(e,{verifiedUnchanged:!0});break}}f.delete(m,1),f.insert(m,x.map(A=>ke(A))),i.push({kind:"replace",paragraphId:f.getAttribute("id"),oldText:"List item",text:x.map(A=>A.children.map(w=>w.text).join("")).join(`
|
|
26
|
-
`)});break}if(u.type==="paragraph"){const x=w=>w.children.filter(E=>!E.marks?.footnoteRef),A=ee.extractUniformTextFontFamily(x(u));if(A){for(const w of v.children)if(w.type==="paragraph"&&ee.extractUniformTextFontFamily(x(w)))for(const E of x(w))E.marks={...E.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=zn(u.children,x.children);else if(u.type==="list"&&x.type==="list"){const M=new Map(u.children.map(F=>[F.id,F])),O=u.children.length===x.children.length&&x.children.every((F,N)=>F.children.map(_=>_.text).join("")===u.children[N].children.map(_=>_.text).join(""));x.children=x.children.map((F,N)=>({...F,children:zn((M.get(F.id)??(O?u.children[N]:void 0))?.children??[],F.children)}))}const C=M=>Array.isArray(M)?M.map(C):M&&typeof M=="object"?Object.fromEntries(Object.entries(M).filter(([O,F])=>O!=="id"&&F!==void 0&&!(O==="marks"&&Object.keys(F).length===0)).sort(([O],[F])=>O.localeCompare(F)).map(([O,F])=>[O,C(F)])):M,T=M=>JSON.stringify(C(M)),L=M=>ee.toInternalHtml({type:"doc",children:[C(M)]});if(T(u)===T(x)||L(u)===L(x)){Ie(e,{verifiedUnchanged:!0});break}}if(!(h instanceof S.XmlElement))break;if(x.type==="list"){f.delete(m,1);const C=Qn({...x,id:a});f.insert(m,[C]);const T=u.type==="list"?"List":"Paragraph";i.push({kind:"replace",paragraphId:a,text:"List replaced",oldText:T});break}if(x.type==="table"){const C=x;f.delete(m,1);const T=Qn({...C,id:a});f.insert(m,[T]);const L=u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";i.push({kind:"replace",paragraphId:a,text:"Table replaced",oldText:L});break}if(x.type==="code"){const C=x;f.delete(m,1);const T=new S.XmlElement("code");T.setAttribute("id",a),C.language&&T.setAttribute("language",C.language),C.renderDiagram!==void 0&&T.setAttribute("renderDiagram",String(C.renderDiagram)),C.showDiagramSource!==void 0&&T.setAttribute("showDiagramSource",String(C.showDiagramSource));const L=new S.XmlText;T.insert(0,[L]),ne(L,0,C.content||""),f.insert(m,[T]);const M=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:M});break}if(x.type==="math"){const C=x;f.delete(m,1);const T=new S.XmlElement("math");T.setAttribute("id",a),C.displayMode&&T.setAttribute("displayMode",C.displayMode),C.align&&T.setAttribute("align",C.align);const L=new S.XmlText;T.insert(0,[L]),ne(L,0,C.content||""),f.insert(m,[T]);const M=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:M});break}if(x.type==="page-break"){f.delete(m,1);const C=new S.XmlElement("page-break");C.setAttribute("id",a),f.insert(m,[C]);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 C=ke({...x,id:a});f.insert(m,[C]),i.push({kind:"replace",paragraphId:a,text:"Table of contents replaced",oldText:"Block"});break}if(x.type==="image"){const C=x;f.delete(m,1);const T=new S.XmlElement("image");T.setAttribute("id",a),T.setAttribute("src",C.src),C.sourceUrl&&T.setAttribute("sourceUrl",C.sourceUrl),T.setAttribute("width",String(C.width)),T.setAttribute("height",String(C.height)),C.alt&&T.setAttribute("alt",C.alt),C.align&&T.setAttribute("align",C.align),f.insert(m,[T]);const L=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:L});break}if((u.type==="math"||u.type==="code")&&x.type==="paragraph"){f.delete(m,1);const C=new S.XmlElement("paragraph");C.setAttribute("id",a),ei(C,x);const T=new S.XmlText;let L=0;for(const M of x.children)M.type==="text"&&(L=it(T,L,M.text,M.marks||{}));qn(C,x,L),C.insert(0,[T]),f.insert(m,[C]),i.push({kind:"replace",paragraphId:a,text:x.children.filter(M=>M.type==="text").map(M=>M.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 C=new S.XmlElement("paragraph");C.setAttribute("id",a),ei(C,x);const T=new S.XmlText;let L=0;for(const M of x.children)M.type==="text"&&(L=it(T,L,M.text,M.marks||{}));qn(C,x,L),C.insert(0,[T]),f.insert(m,[C]),i.push({kind:"replace",paragraphId:a,text:x.children.filter(M=>M.type==="text").map(M=>M.text).join(""),oldText:u.type==="table"?"Table":"List"});break}const A=ue(h);if(!A)break;const w=u.type==="paragraph"?u:null,E=A.length,$=v.children[0],P=w!==null&&ar(w,$);let B=0;if(!P){if(E>0&&A.delete(0,E),$.children.length>0){for(const C of $.children)if(C.type==="text"){const T=C;B=it(A,B,T.text,T.marks||{})}}ei(h,$)}if(!P){const C=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:$.children.filter(T=>T.type==="text").map(T=>T.text).join(""),oldText:C})}}else{if(!(h instanceof S.XmlElement))break;const x=ue(h);if(!x)break;const A=u.type==="paragraph"?u:null,w=x.length,E=u.type==="paragraph"?u.children.filter(T=>T.type==="text").map(T=>T.text).join(""):"",$=v.children[0],P=A!==null&&ar(A,$);let B=0;if(!P){if(w>0&&x.delete(0,w),$.children.length>0){for(const T of $.children)if(T.type==="text"){const L=T;B=it(x,B,L.text,L.marks||{})}}$.heading&&h.setAttribute("heading",String($.heading)),$.align&&h.setAttribute("align",$.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:$.children.filter(T=>T.type==="text").map(T=>T.text).join(""),oldText:E});let C=m+1;for(let T=1;T<v.children.length;T++){const L=v.children[T],M=new S.XmlElement("paragraph"),O=L.id||Y();M.setAttribute("id",O),L.heading&&M.setAttribute("heading",String(L.heading)),L.align&&M.setAttribute("align",L.align);const F=new S.XmlText;let N=0;L.children.forEach(R=>{if(R.type==="text"){const D=R;N=it(F,N,D.text,D.marks||{})}}),qn(M,L,N),M.insert(0,[F]),f.insert(C,[M]),C++;const _=L.children.filter(R=>R.type==="text").map(R=>R.text).join("");i.push({kind:"insert",paragraphId:O,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(F,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(F,_.length,0)),text:_})}}}break}case"style_blocks":{const{selectors:a,attrs:l}=e.arguments,{targets:c,inlineTargets:d,unmatchedSelectors:g,invalidSelectorErrors:u}=Cd(o,a),p=Pd(l),h=Bd(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,b=(W,Z,oe)=>{const V=mt(W);let de=m.get(V);de||(de={name:W,applied:new Set,skipped:new Map},m.set(V,de)),oe?de.skipped.set(`${Z}\0${oe}`,{blockId:Z,reason:oe}):de.applied.add(Z)},y=i.length,k=new Set,I=new Set,v=new Set(c),x=new Set,A=[],w=[],E=[],$=[],P=He(o),B=new Set([...c,...d.map(W=>W.yBlock)].map(Te)),C=W=>"id"in W&&B.has(String(W.id))||"children"in W&&W.children.some(Z=>C(Z)),T=W=>[...W.children,...W.notes??[],...W.chrome??[]],L=new Set(T(P).filter(C).map(W=>W.id)),M=W=>Yt({order:W.children.map(Z=>Z.id),noteOrder:(W.notes??[]).map(Z=>Z.id),chromeOrder:(W.chrome??[]).map(Z=>Z.id),targets:T(W).filter(Z=>L.has(Z.id))}),O=M(P),F=new Set,N=new Set,_=Gn(p,"width");if(_&&!(c.some(W=>W.nodeName==="image")&&tn(_.value)===void 0)){const W=new Map;for(const oe of c){if(oe.nodeName!=="table-cell")continue;let V=oe.parent;for(;V instanceof S.XmlElement&&V.nodeName!=="table";)V=V.parent;if(!(V instanceof S.XmlElement))continue;const de=X(P,Te(V));if(!de||de.type!=="table")continue;const be=tn(_.value),Ne=Mt("width",_.value),ie=de.tableWidth??sr(P,V),le=be??(typeof Ne=="number"&&Number.isFinite(Ne)?Ne/ie*100:NaN);W.has(V)||W.set(V,[]),W.get(V).push({cellId:Te(oe),percent:le}),F.add(oe)}const Z=[...W].map(([oe,V])=>({table:oe,requests:V,widths:qc(X(P,Te(oe)),V)}));for(const oe of Z){const V=String(oe.table.getAttribute("columnWidths")??""),de=JSON.stringify(oe.widths),be=X(P,Te(oe.table)),Ne=Ze(be);for(const ie of oe.requests){const le=Ne.byId.get(ie.cellId),ye=Ae=>Ae.slice(le.col,le.col+le.colSpan).reduce((lt,yn)=>lt+yn,0);Math.abs(ye(be.columnWidths)-ye(oe.widths))>.001&&N.add(ie.cellId)}V!==de&&(oe.table.setAttribute("columnWidths",de),Be(i,oe.table,null,"columnWidths"),k.add(Te(oe.table))),x.add(_.canonicalName),I.add("columnWidths")}}for(const W of c){const Z=Te(W);let oe=!1;const V=Od({doc:P,yBlock:W,rawAttrs:p,anchors:i});F.has(W)&&_&&(V.handledRawNames.add(_.canonicalName),V.appliedAttrs.push("cell width -> table columns"));for(const ie of V.handledRawNames){const le=p.find(Ae=>Ae.canonicalName===ie),ye=V.issuesByRawName.get(ie)??[];b(le?.rawName??ie,Z,ye.length?ye.join("; "):void 0),x.add(ie)}for(const ie of V.appliedAttrs)I.add(ie),k.add(Z);A.push(...V.exactMappings),w.push(...V.approximateMappings),E.push(...V.ignoredAttrs),$.push(...V.unsupportedImageSpacing),f.push(...V.errors);const de=$s(h,W,!1);w.push(...Fs(de));const be=de.some(({rawName:ie,value:le})=>["liststyletype","list-style-type"].includes(ie.toLowerCase())&&typeof le=="string"&&le.toLowerCase()==="none"),Ne=[];for(const{rawName:ie,entry:le,value:ye}of de){if(be&&W.nodeName==="list"&&le.kind!=="textMark"&&le.nodeNames.includes("paragraph")&&!le.nodeNames.includes("list-item")){Ne.push({rawName:ie,entry:le,value:ye});continue}if(!V.handledRawNames.has(mt(ie)))try{if(le.attr==="variant"&&typeof ye=="string"&&ye.trim().toLowerCase()==="none"&&["liststyletype","list-style-type"].includes(ie.trim().toLowerCase())){if(W.nodeName!=="list")throw new Error('style_blocks "listStyleType: none" only applies to list blocks.');oe=!0;continue}if(le.kind==="textMark"){const Ae=As(ie,le.attr,ye);pd({toolName:"style_blocks",yBlock:W,attribute:le.attr,operation:Ae===null?"remove":"set",value:Ae,config:le,anchors:i,independentlySelectedTargets:v}),k.add(Z),I.add(`${ie} -> ${le.attr}`),b(ie,Z);continue}bd({toolName:"style_blocks",yBlock:W,attribute:le.attr,operation:ye===null?"remove":"set",value:ye,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(Z),I.add(`${ie} -> ${le.attr}`),b(ie,Z)}catch(Ae){b(ie,Z,Ae instanceof Error?Ae.message:String(Ae)),f.push(`${Z}.${le.attr}: ${Ae instanceof Error?Ae.message:String(Ae)}`)}}if(oe){const ie=Xd(W,i);if(ie){for(const{rawName:le,entry:ye,value:Ae}of Ne)if(ye.kind!=="textMark")try{for(const lt of ie)Vn({toolName:"style_blocks",yBlock:lt,attribute:ye.attr,operation:Ae===null?"remove":"set",value:Ae,config:ye,anchors:i});I.add(`${le} -> ${ye.attr}`),b(le,Z)}catch(lt){const yn=lt instanceof Error?lt.message:String(lt);b(le,Z,yn),f.push(`${Z}.${ye.attr}: ${yn}`)}k.add(Z),I.add("listStyleType -> plain paragraphs"),b("listStyleType",Z)}else f.push(`${Z}.variant: could not convert the list to plain paragraphs.`)}}for(const{yBlock:W,ranges:Z}of d){const oe=Te(W),V=$s(h,W,!0);w.push(...Fs(V));for(const{rawName:de,entry:be,value:Ne}of V){if(be.kind!=="textMark"){const ie="Block attributes cannot apply to an inline range; select its block instead.";b(de,oe,ie),f.push(`${oe}.${be.attr}: ${ie}`);continue}try{const ie=As(de,be.attr,Ne);md({toolName:"style_blocks",yBlock:W,ranges:Z,attribute:be.attr,operation:ie===null?"remove":"set",value:ie,config:be,anchors:i}),k.add(oe),I.add(`${de} -> ${be.attr}`),b(de,oe)}catch(ie){b(de,oe,ie instanceof Error?ie.message:String(ie)),f.push(`${oe}.${be.attr}: ${ie instanceof Error?ie.message:String(ie)}`)}}}for(const W of h.unsupportedAttrs??[]){const Z=m.get(mt(W)),oe=new Set([...Z?.skipped.values()??[]].map(V=>V.blockId));for(const V of B)!Z?.applied.has(V)&&!oe.has(V)&&b(W,V,"Unsupported attribute for this target.")}const R=He(o),D=W=>{const Z=new Map,oe=V=>{"id"in V&&V.id&&Z.set(V.id,V),"children"in V&&V.children.forEach(de=>oe(de))};return T(W).forEach(oe),Z},U=D(P),j=D(R),z=W=>Yt(U.get(W)??null)!==Yt(j.get(W)??null),K=[...new Set([...B,...i.slice(y).map(W=>W.paragraphId).filter(W=>!!W)])].filter(z),ae=[...B].filter(W=>z(W)||N.has(W)),xe=[...m.values()].map(W=>({name:W.name,appliedBlockIds:[...W.applied],skipped:[...W.skipped.values()]})),Xe=xe.every(W=>W.skipped.length===0)&&I.size>0&&f.length===0&&g.length===0&&u.length===0&&E.length===0&&$.length===0&&(h.unsupportedAttrs??[]).every(W=>x.has(mt(W))),Oe={outcome:Xe?ae.length?"complete":"unchanged":"partial",targetBlockIds:[...B],changedBlockIds:ae,affectedBlockIds:K,attributes:xe};if(Ie(e,{styleEffects:Oe}),Xe&&O===M(R)&&Ie(e,{verifiedUnchanged:!0}),i.length===y&&!$e(e)?.verifiedUnchanged){if($.length||E.length)throw new pe("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."}`)}Zi.set(e,Rd({styleEffects:Oe,matchedTargetCount:c.length+d.reduce((W,Z)=>W+Z.ranges.length,0),inlineRangeCount:d.reduce((W,Z)=>W+Z.ranges.length,0),unsupportedAttrs:(h.unsupportedAttrs??[]).filter(W=>!x.has(mt(W))),unmatchedSelectors:g,invalidSelectorErrors:u,skippedTargetErrors:f,exactCompatibilityMappings:A,approximateCompatibilityMappings:w,ignoredCompatibilityAttrs:E,unsupportedImageSpacing:$}));break}case"set_block_attribute":{const{id:a,attribute:l,operation:c,value:d}=e.arguments,g=ks("set_block_attribute",a),u=()=>{const y=He(o);return g.map(k=>X(y,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=hd(c),m=[],b=(y,k)=>{if(g.length<=1)throw new Error(k);return m.push(`${y}: ${k}`),!0};for(const y of g){const k=G(o,y);if(!k){b(y,`Target block '${y}' 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=Kn(I);if(A){b(y,A);continue}}if(cd.has(h)){if(!v||I.nodeName!=="paragraph"&&I.nodeName!=="list-item"){b(y,`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=!bs(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)re(v,0,v.length,{[h]:A?!0:null}),nt(i,y,v);else{gd(I,h,A);const w=`Text mark "${h}" ${A?"enabled":"removed"}.`;i.push({kind:"replace",paragraphId:y,text:w,oldText:w})}continue}if(h in fs){if(!v||I.nodeName!=="paragraph"&&I.nodeName!=="list-item"){b(y,`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=fs[h],w=f==="remove"?null:ud(h,d,A);if(v.length>0)re(v,0,v.length,{[h]:w===null?null:w}),nt(i,y,v);else{ys(I,h,w);const E=`Text mark "${h}" ${w===null?"removed":"set"}.`;i.push({kind:"replace",paragraphId:y,text:E,oldText:E})}continue}if(h==="indentLevel"&&I.nodeName==="paragraph"){vs(I,f,d),v&&nt(i,y,v);continue}const x=ms[h];if(!x){const A=Object.keys(ms).sort().join(", ");throw new Error(`set_block_attribute "${h}" is not supported. Supported block attributes: ${A}.`)}if(!x.nodeNames.includes(I.nodeName)){b(y,`set_block_attribute "${h}" is not valid for ${I.nodeName} blocks.`);continue}if(f==="remove")q(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=Ss(Q(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=Is(h,d,x);I.nodeName==="paragraph"&&(h==="leftIndent"||h==="firstLineIndent")?xs(I,h,Number(A)):I.setAttribute(h,A)}if(v)nt(i,y,v);else{const A=`Updated ${h} on ${I.nodeName} block.`;i.push({kind:"replace",paragraphId:y,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())&&Ie(e,{verifiedUnchanged:!0});break}case"clear_formatting":{const{id:a}=e.arguments,l=ks("clear_formatting",a),c=()=>{const g=He(o);return l.map(u=>X(g,u))},d=JSON.stringify(c());for(const g of l){const u=G(o,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 Po)q(h.yBlock,m);if(Dd(h.yBlock),f.length>0){let m=0;for(const b of te(f)){const y=typeof b.insert=="string"?b.insert.length:1,k={...Bo};typeof b.attributes?.footnoteRef=="string"&&b.attributes.footnoteRef.length>0&&delete k.superscript,re(f,m,y,k),m+=y}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())&&Ie(e,{verifiedUnchanged:!0});break}case"remove_block":{const{id:a,count:l=1}=e.arguments,c=G(o,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;Et(d)&&Lt();const u=Ut(o),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 b=m.getAttribute("id"),y=m.nodeName;if(p&&d.length===1){if(y==="paragraph"){const k=ue(m);if(k&&k.length>0){const I=te(k);let v="";for(const x of I)x.insert&&typeof x.insert=="string"&&(v+=x.insert);i.push({kind:"delete",paragraphId:b,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:b,text:y==="list"?"List removed":"Block removed"});const k=new S.XmlElement("paragraph");k.setAttribute("id",b);const I=new S.XmlText;k.insert(0,[I]),d.delete(f,1),d.insert(f,[k])}break}if(y==="list")i.push({kind:"delete",paragraphId:b,text:"List removed"});else{const k=ue(m);if(k){const I=te(k);let v="";for(const x of I)x.insert&&typeof x.insert=="string"&&(v+=x.insert);i.push({kind:"delete",paragraphId:b,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:b,text:"Block removed"})}d.delete(f,1)}break}case"append_to_paragraph":{const{id:a,content:l}=e.arguments,c=J(o,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);if(!d)break;const g=d.length,u=ct(g>0?ii(d,g-1,1):yt(c.getAttribute("_emptyTextMarks"))),p=ee.fromAgentHtml(l);if(p.children.length>0){const h=[];for(const b of p.children)b.type==="paragraph"&&b.children.forEach(y=>{y.type==="text"&&h.push(y)});let f=g,m="";for(const b of h)if(b.text){const y=it(d,f,b.text,{...u||{},...b.marks||{}});m+=b.text,f=y}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(o),g=X(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=rg(g,c);if(u.length===0){const j=g.children.filter(K=>K.type==="text").map(K=>K.text).join(""),z=j.length>100?j.slice(0,100)+"...":j;throw new Error(`No match found for "${c}" in block '${a}'. The block contains: "${z}".`)}const p=u[0].offset,h=G(o,a);if(!h)throw new Error(`Y.js block not found for id: ${a}`);const{yBlock:f,yParent:m,index:b}=h;if(Et(m)&&Lt(),!(f instanceof S.XmlElement))throw new Error(`Target block '${a}' is not a valid Y.XmlElement.`);const y=ue(f);if(!y)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:w}=eg(y,p);y.delete(0,y.length);let E=0;for(const j of k)ne(y,E,j.insert,j.attributes??{}),E+=j.insert.length;const $=Y(),P=new S.XmlElement("paragraph");P.setAttribute("id",$);const B=f.getAttribute("heading");B&&P.setAttribute("heading",B);const C=Q(f,"align");C&&P.setAttribute("align",C);const T=Q(f,"lineSpacing");T!=null&&P.setAttribute("lineSpacing",T);const L=Q(f,"pagination");L!=null&&P.setAttribute("pagination",L);const M=f.getAttribute("styleId");M!=null&&P.setAttribute("styleId",M);const O=Q(f,"direction");O!=null&&P.setAttribute("direction",O);const F=Q(f,"borders");F!=null&&P.setAttribute("borders",F);const N=Q(f,"shading");N!=null&&P.setAttribute("shading",N);const _=Q(f,"tabStops");_!=null&&P.setAttribute("tabStops",_);const R=f.getAttribute("oxmlPPr");R!=null&&P.setAttribute("oxmlPPr",R);const D=new S.XmlText;let U=0;for(const j of I)D.insert(U,j.insert,j.attributes??{}),U+=j.insert.length;if(I.length===0){const j=yt(f.getAttribute("_emptyTextMarks")),z=ct({...j,...v??{}});z&&Object.keys(z).length>0&&P.setAttribute("_emptyTextMarks",JSON.stringify(z))}P.insert(0,[D]),m.insert(b+1,[P]),A!==x&&i.push({kind:"replace",paragraphId:a,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(y,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(y,E,0)),text:A,oldText:x}),i.push({kind:"insert",paragraphId:$,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(D,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(D,U,0)),text:w||"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(o,a),g=G(o,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((Et(d.yParent)||Et(g.yParent))&&Lt(),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)?" ":"",b=h.match(/\s+$/)?.[0].length??0,y=f.match(/^\s+/)?.[0].length??0,k=m.length>0,I=k?h.slice(0,h.length-b):h,v=k?f.slice(y):f;k&&b>0&&u.delete(u.length-b,b);const x=te(u),A=te(p),w=x.length>0?x[x.length-1].attributes??{}:{},E=A.length>0?A[0].attributes??{}:{};let $=u.length;m.length>0&&(ne(u,$,m,Object.keys(w).length>0?w:E),$+=m.length);let P=k?y:0;for(const C of A){if(typeof C.insert!="string"||C.insert.length===0)continue;const T=C.insert.slice(P);P=Math.max(0,P-C.insert.length),T.length!==0&&(ne(u,$,T,C.attributes??{}),$+=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(o),l=ee.createParsingContext(a),{tableId:c,referenceIndex:d,referenceRowId:g,position:u,content:p}=e.arguments,h=X(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],b=p?.map(k=>{if(k==="")return;const I=ee.fromAgentHtml(k,{existingDocument:a,parsingContext:l});return I.children.length>0?I.children:void 0}),y=nd(o,c,u,f,b);if(!y.success)throw new Error(y.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=Qc(o,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(o),l=ee.createParsingContext(a),{tableId:c,referenceIndex:d,position:g,content:u}=e.arguments,p=u?.map(f=>{if(f==="")return;const m=ee.fromAgentHtml(f,{existingDocument:a,parsingContext:l});return m.children.length>0?m.children:void 0}),h=ed(o,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=Gc(o,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(o)),i}function yt(o){if(!o)return{};try{const e=JSON.parse(o);if(e&&typeof e=="object")return e}catch{}return{}}function eg(o,e){const t=[],n=[];let i={},r="",s="",a="",l=0;const c=te(o);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}),s+=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}),s+=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:s,afterText:a}}function ii(o,e,t){const n=e+t;let i=0,r=null;for(const s of te(o)){if(typeof s.insert!="string")continue;const a=i+s.insert.length;if(a>e&&i<n){const l=s.attributes||{},c={};for(const d of ro){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 cr(o){const e=new Set;if(!o.includes("<")||!o.includes(">"))return e;try{const t=ee.fromAgentHtml(o),n=i=>{if(i.type==="text"){for(const r of Sn)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 Us(o,e){const t=qt(o);return e.code||e.latex?t:Do(t)}function Hs(o,e,t,n,i){if(i.includes("<")&&i.includes(">")||cr(n).size>0)return!1;const r=ii(o,e,t),s=Us(i,r);return o.toString().slice(e,e+t)===s}function dr(o,e,t,n,i,r,s,a={}){if(!Hs(o,e,t,n,i))if(i.includes("<")&&i.includes(">")){const l={...a,...ii(o,e,t)};for(const p of cr(n))delete l[p];const c=i.trim(),d=/^<\s*(?:p|h[1-6])(?:\s|>|\/)/i.test(c)?c:`<p>${i}</p>`,g=ee.fromAgentHtml(d,{preserveExplicitMarkResets:!0}),u=g.children.length>0?g.children[0]:null;if(u&&u.type==="paragraph"&&u.children.length>0){o.delete(e,t);const p=[];for(const y of u.children)if(y.type==="text"){const k=y,I={...l,...k.marks||{}};p.push({text:k.text,marks:I})}const h=o.doc;let f=e;const m=[];for(const y of p){const k=m[m.length-1],I=JSON.stringify(y.marks||{}),v=k?JSON.stringify(k.marks||{}):null;k&&I===v?k.text+=y.text:m.push({text:y.text,marks:y.marks||{}})}const b=m.map(y=>y.text).join("");h.transact(()=>{ne(o,e,b);let y=e;for(const k of m)k.marks&&Object.keys(k.marks).length>0&&re(o,y,k.text.length,k.marks),y+=k.text.length;f=e+b.length},"performReplacement"),Os(o,e,f),s.push({kind:"replace",paragraphId:r,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(o,e,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(o,f,0)),text:i.replace(/<[^>]*>/g,""),oldText:n.replace(/<[^>]*>/g,"")})}}else{const l={...a,...ii(o,e,t)},c=Us(i,l);for(const d of cr(n))delete l[d];o.delete(e,t),c.length>0&&ne(o,e,c,l),Os(o,e,e+c.length),s.push({kind:"replace",paragraphId:r,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(o,e,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(o,e+c.length,0)),text:c,oldText:n.replace(/<[^>]*>/g,"")})}}const ri=/\\+u[0-9a-fA-F]{4}/;function zs(o){let e="";const t=[],n=[];for(let i=0;i<o.length;){const r=o.slice(i).match(/^(\\+u)([0-9a-fA-F]{4})/),s=r?i+r[0].length:i+1,a=r?String.fromCharCode(Number.parseInt(r[2],16)):o[i],l=tt(a);e+=l;for(let c=0;c<l.length;c++)t.push(i),n.push(s);i=s}return{text:e,sourceStarts:t,sourceEnds:n}}function gr(o,e){return o.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 Ws(o){return o.replace(/^(?:#{1,6}|>|[-*+]|\d+[.)])[ \t]+/,"")}function tg(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ys(o,e){const t=e.split(/(\s+)/),n=[];for(const l of t)/^\s+$/.test(l)?n.push("\\s+"):l.length>0&&n.push(tg(l));if(n.length===0)return[];const i=n.join(""),r=new RegExp(i,"g"),s=[];let a;for(;(a=r.exec(o))!==null;)s.push({offset:a.index,length:a[0].length});return s}function ng(o,e,t,n,i){const r=[];let s=o.indexOf(e);for(;s!==-1;){const a=s+n-t.length,l=Math.min(s+i-t.length+1,o.length);for(let c=a;c<l;c++)if(o.substring(c,c+t.length)===t){const d=c+t.length-s;d>=n&&d<=i&&r.push({offset:s,length:d})}s=o.indexOf(e,s+1)}return r}function qs(o,e){const t=Bn(e);if(t.length>1)for(const n of t){const i=Kt(o,n);if(i.length)return i.map(({start:r,end:s})=>({offset:r,length:s-r}))}for(const n of t){if(et(n))continue;const i=ig(o,n);if(i.length)return i}return[]}function ig(o,e){if(!e)return[];if(/^\s*$/.test(e))return ur(o,e);if(ri.test(o)||ri.test(e))return Js(o,e);const t=gc();return t!==null?t:Js(o,e)}function Js(o,e){const t=Kt(o,e);if(t.length)return t.map(({start:d,end:g})=>({offset:d,length:g-d}));const n=tt(o),i=tt(e),r=ur(n,i);if(r.length>0)return r;const s=Ys(n,i);if(s.length>0)return s;let a,l;if(ri.test(o)||ri.test(e)){a=zs(o),l=zs(e).text;const d=ur(a.text,l);if(d.length>0)return gr(d,a);const g=Ys(a.text,l);if(g.length>0)return gr(g,a)}const c=8;if(i.length>=c*2){const d=Ks(n,i,c);if(d!==null)return[d]}if(a&&l&&l.length>=c*2){const d=Ks(a.text,l,c);if(d!==null)return gr([d],a)}return[]}function rg(o,e){let t="";for(const n of o.children)n.type==="text"&&(t+=n.text);return qs(t,e)}function ur(o,e){const t=[];let n=o.indexOf(e);for(;n!==-1;)t.push({offset:n,length:e.length}),n=o.indexOf(e,n+e.length);return t}function Ks(o,e,t){const n=Math.floor(e.length/2);for(let i=n;i>=t;i--){const r=e.substring(0,i),s=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=ng(o,r,s,l,c);if(d.length===1)return d[0]}return null}function og(o,e,t,n,i={}){if(!e.length)return{anchorsByAction:[],failures:[],alreadySatisfied:!1};const r=e.every(h=>h.name==="insert_block"),s=r?n:i.canonicalDocument?.()??n;r||Nn(o,s);let a;const l={document:r?{...n,children:[...n.children]}:s,get htmlParsingContext(){return a??(a=ee.createParsingContext(n))},set htmlParsingContext(h){a=h},refreshDocumentIncrementally:!r},c=[],d=[],g=new Set,u=[],p=(h,f,m,b)=>{const y=$e(h);d.push({actionIndex:f,actionName:h.name,error:m,failure:b,sourceEditIndex:y?.sourceEditIndex,sourceEditType:y?.sourceEditType})};for(let h=0;h<e.length;h++){const f=e[h];try{const m=()=>ze(o,f,`${t}_${h}`,!i.skipContextForFirstAction||r||h>0?l:void 0),b=i.measure?i.measure(m):m();i.skipContextForFirstAction&&!r&&h===0&&e.length>1&&(l.document=He(o)),c.push(b);const y=$e(f);if(b.length&&y?.splitReplacementGroup&&g.add(y.splitReplacementGroup),!b.length&&i.rejectUnchangedAction&&!y?.verifiedUnchanged)if(Mc(f)&&y?.splitReplacementGroup)u.push({action:f,index:h,group:y.splitReplacementGroup});else{p(f,h,Qi(f)??`${JSON.stringify(f.arguments)} - no change made`);break}}catch(m){if(i.throwOnError)throw m;if(p(f,h,String(m),Vt(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=>$e(h)?.verifiedUnchanged)}}const hr=()=>{},sg={count:hr,gauge:hr,distribution:hr},Vs=new WeakSet;function fr(o,e){try{sg.count("frontend.editor.yjs_observer_failure",1,{event:e})}catch{}console.error(`Yjs ${e} observer failed`,o)}function Gs(o,e=fr){if(Vs.has(o))return;Vs.add(o);const t=o.emit;let n=Number.NEGATIVE_INFINITY;o.emit=function(i,r){if(!["update","updateV2","afterTransactionCleanup"].includes(i))return t.call(this,i,r);const s=Array.from(this._observers.get(i)??[]);for(const a of s)try{a(...r)}catch(l){const c=Date.now();if(c-n>=3e4){n=c;try{e(l,i)}catch{}}}}}const Zs="suggestion-id-repair";function ag(o){if(o.deleteSet.clients.size>0)return!0;for(const[e,t]of o.afterState){const n=o.beforeState.get(e)??0;if(n===t)continue;const i=o.doc.store.clients.get(e);for(let r=S.findIndexSS(i,n);r<i.length&&i[r].id.clock<t;r++){const s=i[r];if(s instanceof S.Item&&s.content instanceof S.ContentFormat&&["insertion","deletion","suggestionId","proposalId"].includes(s.content.key))return!0}}return!1}function lg(o,e,t="recover"){const n=new Set(["content","chrome","notes"].filter(l=>o.share.has(l)).map(l=>o.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=ag(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);Sl(e,c=>{c.deleted||c.content instanceof S.ContentType&&r(c.content.type)})}else n.forEach(r);const s=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=>s(h.getAttribute(f)))){d=!0;break}}if(d||!n.has(c))continue;let g=0,u,p;for(const h of te(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)||s(m.suggestionId)||s(m.proposalId)){u=void 0,p=void 0,g+=f;continue}const b=JSON.stringify(Object.entries(m).filter(([y])=>y==="insertion"||y==="deletion"||y==="layeredInsertion"||y.startsWith("suggestion")).sort(([y],[k])=>y.localeCompare(k)));if(p&&u===b)p.length+=f;else{const y=S.createRelativePositionFromTypeIndex(l,g).item;if(!y){g+=f;continue}p={text:l,start:g,length:f,id:`recovered-inline-${y.client.toString(36)}-${y.clock.toString(36)}`},u=b,a.push(p)}g+=f}}return a.length&&o.transact(()=>{for(const l of a)re(l.text,l.start,l.length,t==="strip"?{insertion:null,deletion:null,layeredInsertion:null,formatChange:null}:{suggestionId:l.id})},Zs),a.length}const cg=["borders","align","styleId","direction","_emptyTextMarks"],dg=["id","heading","oxmlAttrs",...vl],gg=["pagination"],ug=[...Il("paragraph"),...gg].filter(o=>!cg.includes(o)&&!dg.includes(o));function Qs(o,e){for(const t of ug){const n=Q(o,t);n!=null&&e.setAttribute(t,n)}}const pr=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"]),hg=["insertion","deletion","formatChange","suggestionId","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","docxMove"];function ea(o,e){if(!o)return[];const t=!!o.footnoteRef,n=[];for(const[i,r]of Object.entries(o))r===void 0||r===!1||r===null||pr.has(i)||i==="link"&&e.excludeLink||i==="comment"&&e.excludeComment||i!=="footnoteRef"&&(i==="superscript"&&t||n.push([i,r]));return n}function mr(o){const{explicitMarks:e,inheritedMarks:t,emptyParagraphMarks:n,exitingLink:i=!1,exitingComment:r=!1,noteBodyFontSize:s,suggestionMarks:a}=o,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 ea(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 ea(n,{excludeLink:i,excludeComment:r}))!g(p)&&!u(p)&&(l[p]=h);if(s!=null&&l.fontSize===void 0&&!u("fontSize")&&(l.fontSize=s),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 hg)p[h]!==void 0&&p[h]!==null&&d(h)}return{marksToApply:l,marksToRemove:c}}function ta(o,e,t,n){if(ne(o,e,t),Object.keys(n.marksToApply).length>0&&re(o,e,t.length,n.marksToApply),n.marksToRemove.length>0){const i={};for(const r of n.marksToRemove)i[r]=null;re(o,e,t.length,i)}}function oi(o,e,t){const n=ao(e,t,dt(o.getDocument().children));o.transact(()=>{const i=o.getYChromeFragment();na(i,s=>s.getAttribute("sectionIndex")===void 0);for(const s of n)i.push([o.blockToYjsElement(s)]);const r=o.ydoc.getMap("metadata");r.delete("headers"),r.delete("footers")})}function br(o){return no(o.getDocument().chrome??[])}function na(o,e){for(let t=o.length-1;t>=0;t--){const n=o.get(t);n instanceof S.XmlElement&&e(n)&&o.delete(t,1)}}function fg(o,e,t,n){const i=dt(o.getDocument().children),r=ao(t,n,i).map(s=>({...s,sectionIndex:e}));o.transact(()=>{const s=o.getYChromeFragment();na(s,a=>a.getAttribute("sectionIndex")===String(e));for(const a of r)s.push([o.blockToYjsElement(a)])})}function pg(o,e){return Tl(o.getDocument().chrome??[],e)}function ia(o,e,t){const n=Al(o.getDocument().chrome??[],e,t);if(n)return n;const i=wl(e,t,void 0,dt(o.getDocument().children));return o.transact(()=>{o.getYChromeFragment().push([o.blockToYjsElement(i)])}),i}function mg(o){const e=o.getYContentFragment(),t=[];for(const r of e.toArray())r instanceof S.XmlElement&&r.nodeName==="header-footer"&&t.push(r);const n=o.getYChromeFragment();if(t.length===0&&n.length<=3){ra(o);return}const i=o.getYChromeFragment();o.transact(()=>{for(const s of t){const a=o.getDocument().children.find(l=>l.type==="header-footer"&&l.id===s.getAttribute("id"));a&&i.push([o.blockToYjsElement(a)])}const r=e.toArray();for(let s=r.length-1;s>=0;s--){const a=r[s];a instanceof S.XmlElement&&a.nodeName==="header-footer"&&e.delete(s,1)}}),ra(o)}function ra(o){const e=o.getYChromeFragment(),t=new Map,n=[],i=e.toArray(),r=o.getDocument().chrome??[],s=a=>{const l=r.find(c=>c.id===a);return!!(l&&Cl(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];!s(g.getAttribute("id"))&&s(a.getAttribute("id"))?(n.push(d),t.set(c,l)):n.push(l)}),n.length!==0&&o.transact(()=>{for(const a of n.sort((l,c)=>c-l))e.delete(a,1)})}function bg(o){const e=o.ydoc.getMap("metadata"),t=e.get("headers"),n=e.get("footers");!t&&!n||((o.getDocument().chrome?.length??0)>0?o.transact(()=>{e.delete("headers"),e.delete("footers")}):oi(o,t,n))}function yg(o,e,t="bottom-right"){const{headers:n={},footers:i={}}=br(o),r=l=>!!(l&&l.length===1&&l[0].children.every(c=>c.type==="text"&&(c.marks?.field==="page"||c.text.trim()===""))),s={...n},a={...i};if(r(s.default)&&delete s.default,r(a.default)&&delete a.default,e){const l=lo(t),c=l.side==="headers"?s:a;c.default||(c.default=[l.paragraph])}oi(o,Object.keys(s).length>0?s:void 0,Object.keys(a).length>0?a:void 0)}function kg(o){const e=o.ydoc.getMap("metadata");if(e.get(Ve.showPageNumbers)!==!0)return;const t=e.get(Ve.pageNumberPosition)??"bottom-right",{headers:n={},footers:i={}}=br(o),r=lo(t),s=r.side==="headers"?n:i;if(o.transact(()=>{e.set(Ve.showPageNumbers,!1)}),!s.default){const a={...s,default:[r.paragraph]};oi(o,r.side==="headers"?a:n,r.side==="footers"?a:i)}}function Sg(o,e){const t=e?{fontFamily:e}:{},n=[];for(const i of o.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 Ig(o,e,t,n,i){const r=o.getYChromeFragment(),s=()=>{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=s();return d?(o.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;ia(o,e,t);const l=s();if(!l)return!1;const c=dt(o.getDocument().children);return o.transact(()=>{for(const[d,g]of a){const u=(o.getDocument().chrome??[]).find(f=>f.side===e&&f.slot===t)?.children[d],p=xl[d],h={type:"paragraph",id:u?.id??Y(),children:Sg(g,c),...u?.align??p?{align:u?.align??p}:{}};l.get(d)&&l.delete(d,1),l.insert(d,[o.blockToYjsElement(h)])}}),!0}function ot(o){return o.ydoc?o.ydoc.getMap("comments"):null}function vg(o){const e=ot(o);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 oa(o){const e=o.getAttribute("structuralSuggestionKind")==="insert"?o.getAttribute("structuralSuggestionId"):o.getAttribute("diffState")==="insert"?o.getAttribute("suggestionId"):void 0;return typeof e=="string"?e:void 0}function xg(o,e){if(!o.ydoc||e.length===0)return[];const t=new Set(e),n=[],i=(r,s)=>{for(const a of r.toArray()){if(a instanceof S.XmlElement){const g=oa(a);i(a,typeof g=="string"&&t.has(g)?g:s);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 te(a)){if(typeof g.insert!="string")continue;const u=g.insert.length,p=d+(g.attributes?.deletion?0:u),h=g.attributes?.suggestionId??s,f=!g.attributes?.suggestionId&&!!s;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&&s&&n.push({blockId:l,suggestionId:s,start:0,end:0,projectedStart:0,projectedEnd:0,structural:!0})}};return i(o.getYContentFragment()),i(o.ydoc.getXmlFragment("notes")),i(o.ydoc.getXmlFragment("chrome")),n}function yr(o,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 sa(o,e,t,n){const i=ot(o);if(!i||!J(o.ydoc,e))return null;const r=yr(o,t,{...n,anchorBlockId:e});return o.transact(()=>{i.set(r.id,r)}),r.id}function Ag(o,e,t,n,i){const r=J(o.ydoc,e),s=r?se(r):null;if(!s||n<=t||t>=s.length)return!1;const a=Math.min(n,s.length),l=te(s);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,b=m?m.split(","):[];b.includes(i)||b.push(i),re(s,h,f-h,{comment:b.join(",")}),d=!0}return d}function wg(o,e,t,n,i,r){return kr(o,[{blockId:e,start:t,end:n}],i,r)}function kr(o,e,t,n){const i=ot(o);if(!i||e.length===0)return null;const r=yr(o,t,n),s=r.id;let a=!1;return o.transact(()=>{for(const l of e)a=Ag(o,l.blockId,l.start,l.end,s)||a;a&&i.set(s,r)}),a?s:null}function Tg(o,e,t,n){const i=ot(o);if(!i||!i.has(e))return null;const r=yr(o,t,n,e);return o.transact(()=>{i.set(r.id,r)}),r.id}function Cg(o,e,t){const n=ot(o),i=n?.get(e);return!n||!i?!1:(o.transact(()=>{n.set(e,{...i,resolved:t})}),!0)}function Pg(o,e,t){const n=ot(o);if(!n)return 0;const i=new Set(e);if(i.size===0)return 0;const r=[];return n.forEach(s=>{const a=s;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:(o.transact(()=>{for(const s of r)n.set(s.id,{...s,resolved:!0})}),r.length)}function Bg(o,e){const t=ot(o);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=oa(d);r(d,g&&e(g)?g:c);continue}if(d instanceof S.XmlText)for(const g of te(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(o.getYContentFragment()),r(o.ydoc.getXmlFragment("notes")),r(o.ydoc.getXmlFragment("chrome"))}catch{}const s=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=J(o.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 o.transact(()=>{for(const l of n){const c=s(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 $g(o,e){const t=ot(o);if(!t||!t.has(e))return!1;const n=new Set([e]);let i=!0;for(;i;)i=!1,t.forEach((r,s)=>{const a=r;a?.parentId&&n.has(a.parentId)&&!n.has(s)&&(n.add(s),i=!0)});return o.transact(()=>{for(const s of n)t.delete(s);const r=s=>{for(const a of s.toArray()){if(a instanceof S.XmlElement){r(a);continue}if(!(a instanceof S.XmlText))continue;let l=0;for(const c of te(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&&re(a,l,d,{comment:u.length>0?u.join(","):null})}l+=d}}};try{r(o.getYContentFragment()),r(o.ydoc.getXmlFragment("notes")),r(o.ydoc.getXmlFragment("chrome"))}catch{}}),!0}function aa(o,e){const t=d=>d.replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&");if(!o.includes("<")||!o.includes(">"))return[{type:"text",text:t(o),marks:{...e}}];const n=[],i={},r=d=>{d&&n.push({type:"text",text:t(d),marks:{...i,...e}})},s=/<(\/?)(i|em|b|strong|u|a)((?:\s+[a-zA-Z-]+="[^"]*")*)\s*\/?>/g;let a=0,l;for(;(l=s.exec(o))!==null;){r(o.slice(a,l.index)),a=s.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(o.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(o),marks:{...e}}]}function Rt(o){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 s of te(i)){if(typeof s.insert!="string")continue;const a=s.attributes??{};typeof a.footnoteRef=="string"&&a.footnoteRef&&e.push({yText:i,start:r,length:s.insert.length,text:s.insert,attributes:a,footnoteId:a.footnoteRef}),r+=s.insert.length}}};try{t(o.getYContentFragment())}catch{}return e}function kt(o){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(o.getYNotesFragment()),t(o.getYContentFragment())}catch{}return e}function Fg(o,e){const t=[...o.notes??[],...o.children.filter(n=>n.type==="footnote")];for(const n of t)if(n.id===e||X(n,e))return!0;return!1}function Sr(o){const e=new Map;for(const[t,n]of kt(o))e.set(t,n.getAttribute("noteKind")==="endnote"?"endnote":"footnote");return e}function Eg(o){const e=[];for(const a of Rt(o))e.includes(a.footnoteId)||e.push(a.footnoteId);const t=Sr(o),n=new Map,i=o.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},s=[];for(const a of e){const l=n.get(a);if(!l)continue;const c=t.get(a)??"footnote";r[c]+=1,s.push({footnote:l,number:r[c],display:Ti(r[c],c),kind:c})}return s}function St(o){const e=Rt(o);if(e.length===0)return!1;const t=Sr(o),n=new Map,i={footnote:0,endnote:0};for(const s of e)if(!n.has(s.footnoteId)){const a=t.get(s.footnoteId)??"footnote";i[a]+=1,n.set(s.footnoteId,Ti(i[a],a))}const r=e.filter(s=>s.text!==n.get(s.footnoteId));return r.length===0?!1:(o.transact(()=>{for(const s of[...r].sort((a,l)=>l.start-a.start)){const a=n.get(s.footnoteId)??"";s.yText.delete(s.start,s.length),ne(s.yText,s.start,a,s.attributes)}}),!0)}function Lg(o){la(o);const e=Rt(o),t=kt(o);if(e.length===0&&t.size===0)return;const n=new Set(e.map(i=>i.footnoteId));o.transact(()=>{for(const[i,r]of t)if(!n.has(i)&&!r.getAttribute("structuralSuggestionId")){const s=r.parent;if(s){const a=s.toArray().indexOf(r);a>=0&&s.delete(a,1)}}for(const i of[...e].sort((r,s)=>s.start-r.start))t.has(i.footnoteId)||i.yText.delete(i.start,i.length)}),St(o)}function la(o){let e;try{e=o.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 te(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=kt(o),r=new Set(Rt(o).map(d=>d.footnoteId)),s=o.getDocument(),a=new Map;for(const d of[...s.notes??[],...s.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=dt(o.getDocument().children);return o.transact(()=>{for(const d of t){if(re(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 y of f.toArray())if(y instanceof S.XmlElement&&y.nodeName==="paragraph"){m=y;break}const b=m?se(m):null;if(b){const y=d.fontFamily??c;b.length>0&&b.delete(0,b.length);let k=0;for(const I of aa(d.body,{fontSize:gt,...y?{fontFamily:y}:{}}))ne(b,k,I.text,I.marks),k+=I.text.length}}continue}const g=d.fontFamily??c,u={fontSize:gt,...g?{fontFamily:g}:{}},p={type:"footnote",id:d.footnoteId,...d.kind==="endnote"?{noteKind:"endnote"}:{},children:[{type:"paragraph",id:Y(),children:aa(d.body,u)}]},h=o.blockToYjsElement(p);h.setAttribute("id",d.footnoteId),d.kind==="endnote"&&h.setAttribute("noteKind","endnote"),d.suggested&&d.suggestionId&&o.suggestions.setElementStructuralSuggestion(h,"insert",void 0,d.suggestionId,"Insert footnote"),o.getYNotesFragment().push([h]),i.set(d.footnoteId,h)}}),St(o),!0}function Mg(o){let e;try{e=o.getYContentFragment()}catch{return}const t=[];for(const s of e.toArray())s instanceof S.XmlElement&&s.nodeName==="footnote"&&t.push(s);if(t.length===0)return;const n=o.getYNotesFragment(),i=o.getDocument(),r=new Map([...i.notes??[],...i.children.filter(s=>s.type==="footnote")].map(s=>[s.id,s]));o.transact(()=>{for(const a of t){const l=a.getAttribute("id"),c=typeof l=="string"?r.get(l):void 0;c&&n.push([o.blockToYjsElement(c)])}const s=e.toArray();for(let a=s.length-1;a>=0;a--){const l=s[a];l instanceof S.XmlElement&&l.nodeName==="footnote"&&e.delete(a,1)}}),St(o)}function Ng(o,e,t,n,i="footnote"){if(!o.ydoc)return null;const r=Y(),s=o.suggestions.isSuggesting(),a=s?ce():void 0,l=Sr(o),c=new Set(Rt(o).map(m=>m.footnoteId).filter(m=>(l.get(m)??"footnote")===i)).size,d=Ti(c+1,i);let g,u;{const m=X(o.getDocument(),e.block);if(m&&m.type==="paragraph"){u=m.direction;let b=0;for(const y of m.children){if(y.type!=="text")continue;const k=b+y.text.length;if(e.offset<=k&&y.marks?.fontFamily){g=y.marks.fontFamily;break}b=k}}}const p={footnoteRef:r,superscript:!0,...g?{fontFamily:g}:{},...s&&a?{insertion:!0,...o.suggestions.buildInlineMetadataMarks(a,"Insert footnote")}:{}};if(!o.insertTextNodes(e,[{type:"text",text:d,marks:p}],n))return null;const h=g??dt(o.getDocument().children),f={fontSize:gt,...h?{fontFamily:h}:{}};return o.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}]}]},b=o.blockToYjsElement(m);if(b.setAttribute("id",r),i==="endnote"&&b.setAttribute("noteKind","endnote"),s&&a&&o.suggestions.setElementStructuralSuggestion(b,"insert",void 0,a,"Insert footnote"),o.getYNotesFragment().push([b]),!t){const y=b.toArray()[0];y instanceof S.XmlElement&&y.setAttribute("_emptyTextMarks",JSON.stringify(f))}}),St(o),{footnoteId:r,...a?{suggestionId:a}:{}}}function Og(o,e,t){const n=kt(o).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=se(i);if(!r)return!1;const s=o.getDocument(),a=[...s.notes??[],...s.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??dt(o.getDocument().children),l={fontSize:gt,...a?{fontFamily:a}:{}};return o.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 Rg(o,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 s=m=>{if(!r){for(const b of m.toArray())if(b instanceof S.XmlElement){if(b.getAttribute("id")===e){r=b;return}s(b)}}};for(const m of kt(o).values()){if(m.getAttribute("id")===e){r=m;break}if(s(m),r)break}if(!r)return{success:!1,replacements:0,error:`Note block '${e}' was not found.`};const a=se(r);if(!a)return{success:!1,replacements:0,error:`Note block '${e}' does not contain editable text.`};const l=te(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=o.suggestions.isSuggesting()?ce():null,p=u?o.suggestions.buildInlineMetadataMarks(u,"Replace footnote text"):null,h=m=>{let b=0;for(const y of te(a)){if(typeof y.insert!="string")continue;const k=b+y.insert.length;if(m<k){const I={...y.attributes??{}};return delete I.insertion,delete I.deletion,delete I.suggestionId,delete I.suggestionLabel,delete I.suggestionCreatedAt,I}b=k}return{fontSize:gt}},f=new Map(g.map(m=>[m,h(m)]));return o.transact(()=>{for(const m of[...g].reverse()){const b=f.get(m)??{fontSize:gt};u&&p?(re(a,m,t.length,{deletion:!0,...p}),n&&ne(a,m,n,{...b,insertion:!0,deletion:null,formatChange:null,...p})):(a.delete(m,t.length),n&&ne(a,m,n,b))}}),{success:!0,replacements:g.length,...u?{suggestionId:u}:{}}}function Dg(o,e){const t=kt(o);return t.size===0?!1:(o.transact(()=>{for(const n of t.values())e==="endnote"?n.setAttribute("noteKind","endnote"):n.removeAttribute("noteKind")}),St(o),!0)}function _g(o,e){const t=Rt(o).filter(i=>i.footnoteId===e),n=kt(o).get(e);if(t.length===0&&!n)return!1;if(o.suggestions.isSuggesting()){const i=ce();return o.transact(()=>{for(const r of t)re(r.yText,r.start,r.length,{deletion:!0,...o.suggestions.buildInlineMetadataMarks(i,"Delete footnote")});n&&o.suggestions.setElementStructuralSuggestion(n,"delete",void 0,i,"Delete footnote")}),!0}return o.transact(()=>{for(const i of[...t].sort((r,s)=>s.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)}}}),St(o),!0}function ca(o,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(o),r=n(e),s=a=>a.id&&i.get(a.id)===1&&r.get(a.id)===1?`id:${a.id}`:`content:${t(a)}`;return{beforeKeys:o.map(s),afterKeys:e.map(s)}}function Ir(o,e){const t=o.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++)o[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 s=t,a=n;for(;s>0&&a>0;)o[s-1]===e[a-1]?(r.unshift(o[s-1]),s-=1,a-=1):i[s-1][a]>i[s][a-1]?s-=1:a-=1;return r}function jg(o){let e=o,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 s=0;s<e.length;s++){const a=e.get(s);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 Xg(o,e,t,n){const i=o.getArray("paragraphs"),r=i.toArray().findIndex(a=>a?.get("id")===e);if(r<0)return null;const s=i.get(r);if(!s)return null;if(t==="paragraph")return s.get("content");if(t==="list"&&n!==void 0){const a=s.get("items");return!a||n>=a.length?null:a.get(n)?.get("content")}return null}function Ug(o,e,t,n){const i=J(o,e);if(!i)return null;if(t==="paragraph"||t==="list-item")return se(i);if(t==="list"&&n!==void 0){let r=0;for(let s=0;s<i.length;s++){const a=i.get(s);if(a instanceof S.XmlElement&&a.nodeName==="list-item"){if(r===n)return se(a);r++}}}return null}function da(o,e,t,n){return Ug(o,e,t,n)||(Tt(o)?Xg(o,e,t,n):null)}function st(o,e,t){const n=X(t,o.block);if(!n||!n.id)return null;if(n.type==="paragraph"){const i=n,r=da(e,n.id,"paragraph");if(!r)return null;const s=i.children.filter(c=>c.type==="text").reduce((c,d)=>c+d.text.length,0),a=Math.max(0,Math.min(o.offset,s)),l=S.createRelativePositionFromTypeIndex(r,a);return{blockId:n.id,textOffset:l}}if(n.type==="list"){const i=n;let r=-1,s=o.offset;if(o.offset,o.block!==n.id){let d=0;for(let g=0;g<i.children.length;g++){if(i.children[g].id===o.block){r=g,d+o.offset;break}d+=Fn(i.children[g]),g<i.children.length-1&&(d+=1)}}if(r===-1){let d=o.offset;for(let g=0;g<i.children.length;g++){const u=Fn(i.children[g]),p=g<i.children.length-1?1:0;if(d<=u){r=g,s=d;break}d-=u+p,g===i.children.length-1&&(r=g,s=u)}}r===-1&&(r=0,s=0);const a=da(e,n.id,"list",r);if(!a)return null;const l=Math.max(0,Math.min(s,a.length)),c=S.createRelativePositionFromTypeIndex(a,l);return{blockId:n.id,textOffset:c}}return null}function Hg(o,e,t){const n=o.getArray("paragraphs");for(let i=0;i<n.length;i++){const r=n.get(i);if(!r)continue;const s=r.get("id");if(!s)continue;const a=r.get("type");if(a==="paragraph"&&r.get("content")===e)return{blockId:s,offset:0,yTextOffset:0};if(a==="list"){const l=r.get("items");if(!l)continue;const c=X(t,s);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:s,offset:g,yTextOffset:0};u<d.children.length&&(g+=Fn(d.children[u]),u<d.children.length-1&&(g+=1))}}}return null}function si(o,e){const t=S.createAbsolutePositionFromRelativePosition(o.textOffset,e);if(!t||!(t.type instanceof S.XmlText))return J(e,o.blockId)?{block:o.blockId,offset:0}:null;const n=t.index,i=t.type,r=jg(i);if(r)return{block:r.blockId,offset:r.offset+n};if(Tt(e)){const s=he(e),a=Hg(e,i,s);if(a)return{block:a.blockId,offset:a.offset+n}}return J(e,o.blockId)?{block:o.blockId,offset:n}:null}function H(o,e,t){return{anchor:o.anchor?st(o.anchor,e,t):null,focus:o.focus?st(o.focus,e,t):null}}function vr(o,e){return{anchor:o.anchor?si(o.anchor,e):null,focus:o.focus?si(o.focus,e):null}}function It(o){if(typeof window>"u")return null;try{return window.localStorage??null}catch(e){return console.warn(`[${o}] localStorage unavailable:`,e),null}}function zg(o,e){if(o.length!==e.length)return!1;for(let t=0;t<o.length;t++)if(o[t]!==e[t])return!1;return!0}class xr{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(),Wg(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=It("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(s=>({...s,from:s.from?btoa(String.fromCharCode(...s.from)):s.from,to:s.to?btoa(String.fromCharCode(...s.to)):s.to}))),e.metadata[n]=r}for(const[n,i]of this.paragraphSuggestions){const r=i.filter(s=>t.has(s));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),s=>s.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(s=>({...s,from:s.from?Uint8Array.from(atob(s.from),a=>a.charCodeAt(0)):s.from,to:s.to?Uint8Array.from(atob(s.to),a=>a.charCodeAt(0)):s.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=It("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=It("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=It("DetachedSuggestionStore");if(!t)return;const n=`proposals_${e}`,i=[];for(let r=0;r<t.length;r++){const s=t.key(r);s&&(s===n||s.startsWith(`${n}_`))&&i.push(s)}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=It("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 s=Uint8Array.from(atob(r),a=>a.charCodeAt(0));this.proposals.set(i,s)}if(n.metadata)for(const[i,r]of Object.entries(n.metadata)){const s=r;s.anchors&&(s.anchors=s.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,s)}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=It("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(s=>({...s,from:s.from?btoa(String.fromCharCode(...s.from)):s.from,to:s.to?btoa(String.fromCharCode(...s.to)):s.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 s=[];i.transact(()=>{s=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:s,...n}),this.saveToLocalStorage(),this.notifyListeners(),s.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,s={}){return this.createSuggestion(e,a=>{const l=J(a,t);if(!l)return console.warn(`Paragraph ${t} not found for text deletion`),[];const c=se(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}`),[])},{...s,id:e})}createTextInsertion(e,t,n,i,r={},s={}){const a={...r,proposalId:e};return this.createSuggestion(e,l=>{const c=J(l,t);if(!c)return console.warn(`Paragraph ${t} not found for text insertion`),[];const d=se(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}`),[])},{...s,id:e})}createTextReplacement(e,t,n,i,r,s={},a,l={}){const c={...s,proposalId:e};return this.createSuggestion(e,d=>{const g=J(d,t);if(!g)return console.warn(`Paragraph ${t} not found for text replacement`),[];const u=se(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 s=this.generateId();return this.suggestionMeta.set(s,{id:s,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,s}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 s=r.insertionContext;s&&t.set(s.paragraphId,s)}const n=new Set,i=[...e.mustBeAfter];for(;i.length>0;){const r=i.pop();if(n.has(r))continue;n.add(r);const s=t.get(r);s&&i.push(...s.mustBeAfter)}return n}applyPositionAwareInsertionToDoc(e,t,n){const i=n.insertionContext;if(!i)return;const r=this.expandPositionAwarePredecessors(i),s=e.getXmlFragment("content");let a=0;for(let c=s.length-1;c>=0;c--){const d=s.get(c);if(!(d instanceof S.XmlElement))continue;const g=d.getAttribute("id");if(g&&r.has(g)){a=c+1;break}}const l=ga(i.content,i.paragraphId,t);s.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 s=S.encodeStateAsUpdate(t);he(t),S.applyUpdate(t,r);const a=S.encodeStateAsUpdate(t);if(he(t),!!zg(s,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 s={type:"accept",suggestionId:e,timestamp:Date.now()};return s.suggestionId,this.undoStack.length,this.recordAction(s),this.notifyListeners(),!0}}acceptPositionAwareInsertion(e,t){const n=t.insertionContext,i=this.ydoc.getXmlFragment("content"),r=this.expandPositionAwarePredecessors(n);let s=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)){s=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<s&&(s=c);break}}}const l=`proposal-${e}`;return this.undoManager.trackedOrigins.add(l),this.ydoc.transact(()=>{const c=ga(n.content,n.paragraphId,e);i.insert(s,[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 s=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(s)},"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 s=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:s?.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],s=n[i];if(r.paragraphId&&s.fromIndex===null)return"conflicted"}}try{const n=this.materializeWithSuggestion(e);if(!n)return"stale";const i=In(this.ydoc),r=In(n),s=t.anchors?.filter(a=>a.kind==="insert"&&!a.paragraphId).length||0;return Math.abs(r-i)>s+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||It("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,wr.get(this.documentId)===this&&wr.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(()=>du),{findBlockById:i}=await import("./index-B1idHquf.js").then(d=>d.a0),r=he(this.ydoc),s=i(r,e);if(!s){console.warn(`[DetachedSuggestionStore] Paragraph ${e} not found in document`);return}if(s.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;J(this.ydoc,d);const g=new S.Doc;this.seedForkFromBase(g);const u=S.encodeStateVector(g);In(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)}}}),In(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 s=new S.Doc;S.applyUpdate(s,n);const a=he(r),l=he(s);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 b=new S.Doc;this.seedForkFromBase(b);const y=S.encodeStateVector(b),{analyzeParagraphDiff:k}=await import("./ParagraphDiffAnalysis-DrmStvmz.js").then(x=>x.P),I=k(f,m).diffs;b.transact(()=>{let x=null;if(Tt(b)){const A=b.getArray("paragraphs");for(let w=0;w<A.length;w++){const E=A.get(w);if(E.get("id")===p.id){x=E.get("content");break}}}else{const A=J(b,p.id);A&&(x=se(A))}if(x){const A=[];for(const $ of h.children)if($.type==="text")for(let P=0;P<$.text.length;P++)A.push({node:$,indexInNode:P,marks:$.marks||{}});let w=0,E=0;for(const[$,P]of I)if($===0)w+=P.length,E+=P.length;else if($===-1)x.delete(w,P.length);else if($===1){for(let B=0;B<P.length;B++){const C=A[E+B];if(C){const T={...C.marks,proposalId:e};ne(x,w+B,P[B],T)}}w+=P.length,E+=P.length}}});const v=S.encodeStateAsUpdate(b,y);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 ga(o,e,t,n){if(o.type==="list"){const l=new S.XmlElement("list");return l.setAttribute("id",e),l.setAttribute("variant",o.variant??"unordered"),o.startNumber!==void 0&&l.setAttribute("startNumber",String(o.startNumber)),o.numberingChainId&&l.setAttribute("numberingChainId",o.numberingChainId),o.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=Ar(h.marks,t);g.insert(u,h.text,f),u+=h.text.length}}),d.insert(0,[g]),l.push([d])}),l}if(o.type==="table"){const l=o,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 b=new S.XmlText;let y=0;for(const k of f.children)if(k.type==="text"){const I=k,v=Ar(I.marks,t);ne(b,y,I.text,v),y+=I.text.length}m.insert(0,[b]),p.push([m])}g.push([p])}c.push([g])}return c}if(o.type==="code"){const l=o,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(o.type==="math"){const l=o,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(o.type==="image"){const l=o,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(o.type==="page-break"){const l=new S.XmlElement("page-break");return l.setAttribute("id",e),l}if(o.type==="toc")return ke({...o,id:e});if(o.type==="section-break"){const l=new S.XmlElement("section-break");return l.setAttribute("id",e),o.layout&&l.setAttribute("layout",JSON.stringify(o.layout)),o.breakType&&l.setAttribute("breakType",o.breakType),l}const i=new S.XmlElement("paragraph"),r=o;i.setAttribute("id",e),r.heading&&i.setAttribute("heading",String(r.heading)),r.align&&i.setAttribute("align",r.align);const s=new S.XmlText;let a=0;return r.children.forEach(l=>{if(l.type==="text"){const c=l,d=Ar(c.marks,t);ne(s,a,c.text,d),a+=c.text.length}}),i.insert(0,[s]),i}function Ar(o,e,t){return{...o||{},proposalId:e}}const wr=new Map;function Wg(o,e){wr.set(o,e)}const Yg=new Set(["Arial","Arial, sans-serif"]);function Tr(o){if(typeof o!="string")return;const e=o.trim();if(!(!e||Yg.has(e)))return e}function ai(o){const e={};for(const t of Sn)if(o[t]!==void 0)if(t==="fontFamily"){const n=Tr(o[t]);n&&(e[t]=n)}else(t==="color"||t==="backgroundColor")&&typeof o[t]=="string"&&/^#[0-9a-fA-F]{6}$/.test(o[t])?e[t]=o[t].toLowerCase():e[t]=o[t];return e}const ua=ro.filter(o=>!Sn.includes(o));function Dt(o){const e=ai(o);for(const t of ua)o[t]!==void 0&&(e[t]=o[t]);return e}function qg(o){const e=ha(o);for(const t of ua)o[t]!==void 0&&(e[t]=o[t]);return e}function Cr(o,e){return JSON.stringify(Dt(o||{}))===JSON.stringify(Dt(e||{}))}function ha(o){const e=ai(o);e.docxRunPropertyResets=o.docxRunPropertyResets??null;for(const t of Sn)t in e||(e[t]=null);return e}function Pr(o,e){const t=ai(o||{}),n=ai(e||{});return JSON.stringify(t)===JSON.stringify(n)}function fa(o,e){for(const t of xn){const n=o[t],i=e[t];if(t==="link"||t==="backgroundColor"||t==="color"){const r=l=>typeof l=="string"&&/^#[0-9a-fA-F]{6}$/.test(l),s=r(n)?n.toLowerCase():n,a=r(i)?i.toLowerCase():i;if(s!==a)return!1}else if(t==="fontFamily"){if(Tr(n)!==Tr(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 pa{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(o,e){return{...o,id:e}}function Jg(o,e,t){const n=new Set(o),i=r=>{if(r){if(r.block.type==="table"&&r.block.id){n.add(r.block.id);return}for(let s=r.containerPath.length-1;s>=0;s--){const a=r.containerPath[s];if((t.get(a)?.block??e.get(a)?.block)?.type==="table"){n.add(a);break}}}};for(const r of o)i(t.get(r)),i(e.get(r));return n}function ma(o){return JSON.stringify(o.children.map(e=>[e.id,e.children.map(t=>[t.id,t.rowSpan??1,t.colSpan??1])]))}function ba(o){return JSON.stringify({...o,children:o.children.map(e=>({...e,children:e.children.map(t=>({...t,children:[]}))}))})}function Kg(o,e){return{...e,children:e.children.map((t,n)=>({...t,children:t.children.map((i,r)=>({...i,children:o.children[n].children[r].children}))}))}}function Br(o,e,t){const n=t?.affectedBlockIds?new Set(Array.from(t.affectedBlockIds).filter(L=>typeof L=="string"&&L.length>0)):null,i=e.getYDoc(),r=Array.from(e.getPendingSuggestions().keys()),s=r.length>0?e.materializeWithSuggestions(r):i,a=t?.precomputedLiveDocSchema??he(i),l=t?.precomputedCurrentDocSchema??(s===i?a:he(s)),c=t?.precomputedFinalDocSchema??he(o),d=Ye(a),g=Ye(l),u=Ye(c),p=n?Jg(n,g,u):null,h=new Set;for(const L of new Set([...d.keys(),...u.keys()])){const M=d.get(L)?.block,O=u.get(L)?.block;M?.type!=="table"&&O?.type!=="table"||(M?.type!=="table"||O?.type!=="table"||ma(M)!==ma(O)||wn(M,O))&&h.add(L)}if(p)for(const[L,M]of new Map([...d,...u]))M.containerPath.some(O=>p.has(O))&&p.add(L);const f=new Set(Array.from(t?.atomicReplaceBlockIds??[]).filter(L=>typeof L=="string"&&L.length>0)),m=new Map;for(const L of t?.replacementBlockMatches??[])typeof L?.currentBlockId!="string"||L.currentBlockId.length===0||typeof L?.finalBlockId!="string"||L.finalBlockId.length===0||m.set(L.finalBlockId,L.currentBlockId);const b=L=>{const M=m.get(L);return M&&d.has(M)?M:L},y=!!p&&p.size>0,k=e.getPendingSuggestions();if(y){const L=new Set;for(const M of p){const O=e.getSuggestionsForParagraph(M);for(const F of O)k.has(F)&&L.add(F)}for(const M of L)e.deleteSuggestion(M)}else for(const[L]of k)e.deleteSuggestion(L);const I=[],v=new Set,x=new Set,A=g;for(const[L,M]of d){const O=M.block;if(O.type!=="list"||u.has(L)||O.children.length===0||y&&!p.has(L)||M.containerPath.some(z=>h.has(z)))continue;const F=A.get(L)?.block,N=(t?.listUnwrapMemberIds?.get(L)??(F?.type==="list"?F.children:O.children).map(z=>z.id)).map(z=>u.get(z)).filter(z=>!!z),_=N[0];if(!_||N.some((z,K)=>z.containerPath.join("/")!==M.containerPath.join("/")||K>0&&z.indexInParent<=N[K-1].indexInParent))continue;const R=_.containerPath.at(-1),D=R?u.get(R)?.block:null,U=(D&&"children"in D?D.children:c.children).slice(_.indexInParent,N.at(-1).indexInParent+1);if(U.some(z=>!z.id||d.has(z.id)))continue;const j=`prop_${Y()}`;e.createSuggestion(j,z=>{const K=G(z,L);return K?(K.yParent.delete(K.index,1),K.yParent.insert(K.index,U.map(ae=>ke(ae))),[{kind:"replace",paragraphId:L,text:"Remove list markers"}]):[]},{authorType:"ai",blockSequencePreview:{blockId:L,blocks:U},description:"AI: remove list markers"}),I.push(j),v.add(L),e.setSuggestionsForParagraph(L,[j]);for(const z of U)x.add(z.id),e.setSuggestionsForParagraph(z.id,[j])}const w=[],E=y?Array.from(p).filter(L=>u.has(L)):Array.from(u.keys());for(const L of E){const M=u.get(L);if(!M||x.has(L)||M.containerPath.some(R=>x.has(R)))continue;const O=M.block,F=m.get(L);if(O.type==="container"||O.type==="table-cell"||M.containerPath.some(R=>h.has(R)))continue;const N=F?d.get(F)??d.get(L):d.get(L),_=F&&N?.block.id===F&&F!==L?F:null;if(N?.block.id&&v.add(N.block.id),O.type==="paragraph"){const R=_!==null?at(O,_):O;if(!N)w.push({location:M});else if(N.block.type==="paragraph"){const D=N.block,U=Lr(D),j=Lr(R);if(U!==j||cu(D,R)){if(f.has(L)){const K=$r(e,R);K&&(I.push(K),R.id&&e.setSuggestionsForParagraph(R.id,[K]));continue}const z=ya(e,D,R);I.push(...z)}}else{const D=$r(e,R);D&&(I.push(D),R.id&&e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="list"){const R=_!==null?at(O,_):O;if(!N)w.push({location:M});else if(N.block.type==="list"){const D=N.block;if(co(D,R)){if(!iu(D,R)){const U=Vg(e,D,R);U.length>0&&D.id&&(I.push(...U),e.setSuggestionsForParagraph(D.id,U))}}else{const U=Er(e,R);U&&D.id&&(I.push(U),e.setSuggestionsForParagraph(D.id,[U]))}}else{const D=Er(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="table"){const R=_!==null?at(O,_):O;if(!N)w.push({location:M});else if(N.block.type==="table"){const D=N.block,U=h.has(R.id);if(U||ba(D)!==ba(R)){const j=ka(e,U?R:Kg(D,R));j&&(I.push(j),e.setSuggestionsForParagraph(R.id,[j]))}}else{const D=ka(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="code"){const R=_!==null?at(O,_):O;if(!N)w.push({location:M});else if(N.block.type==="code"){const D=N.block;if(D.content!==R.content||D.language!==R.language){const U=Sa(e,R);U&&R.id&&(I.push(U),e.setSuggestionsForParagraph(R.id,[U]))}}else{const D=Sa(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="math"){const R=_!==null?at(O,_):O;if(!N)w.push({location:M});else if(N.block.type==="math"){const D=N.block;if(D.content!==R.content||D.displayMode!==R.displayMode||D.align!==R.align){const U=Ia(e,R);U&&R.id&&(I.push(U),e.setSuggestionsForParagraph(R.id,[U]))}}else{const D=Ia(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="image"){const R=_!==null?at(O,_):O;if(!N)w.push({location:M});else if(N.block.type==="image"){const D=N.block;if(D.src!==R.src||D.width!==R.width||D.height!==R.height||D.alt!==R.alt||D.align!==R.align){const U=va(e,R);U&&R.id&&(I.push(U),e.setSuggestionsForParagraph(R.id,[U]))}}else{const D=va(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="page-break"){const R=_!==null?at(O,_):O;if(!N)w.push({location:M});else if(N.block.type!=="page-break"){const D=tu(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="toc"){const R=_!==null?at(O,_):O;if(!N)w.push({location:M});else if(N.block.type!=="toc"||N.block.levels!==R.levels||N.block.instr!==R.instr||N.block.fontFamily!==R.fontFamily||N.block.fontSize!==R.fontSize||N.block.color!==R.color||N.block.direction!==R.direction||N.block.align!==R.align){const D=nu(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}}w.sort((L,M)=>{const O=L.location.containerPath,F=M.location.containerPath,N=Math.min(O.length,F.length);for(let _=0;_<N;_++)if(O[_]!==F[_])return O[_].localeCompare(F[_]);return O.length!==F.length?O.length-F.length:L.location.indexInParent-M.location.indexInParent});const $=L=>{const M=L.containerPath.at(-1),O=M?u.get(M)?.block:null;return O&&"children"in O?O.children:c.children},P=L=>{const M=$(L);for(let O=L.indexInParent-1;O>=0;O--){const F=M[O];if(F.id)return b(F.id)}return null},B=L=>{const M=$(L),O=(()=>{for(let N=L.indexInParent-1;N>=0;N--)if(M[N]?.id)return b(M[N].id);return null})(),F=(()=>{for(let N=L.indexInParent-1;N>=0;N--){const _=M[N]?.id;if(!_)continue;const R=b(_);if(d.has(R))return R}return null})();return Array.from(new Set([F,O].filter(N=>typeof N=="string"&&N.length>0)))},C=[];for(const L of w){const M=L.location,O=P(M),F=C[C.length-1];if(F&&F.afterId===O&&F.containerPath.join("/")===M.containerPath.join("/")&&F.blocks[F.blocks.length-1].location.indexInParent===M.indexInParent-1){F.blocks.push(L);continue}C.push({afterId:O,containerPath:M.containerPath,blocks:[L]})}for(const L of C){const M=L.afterId&&d.has(L.afterId);if(L.blocks.length===1&&M){const{location:O}=L.blocks[0],F=O.block,N=su(e,F,L.afterId,a);N&&(I.push(N),F.id&&e.setSuggestionsForParagraph(F.id,[N]))}else for(let O=0;O<L.blocks.length;O++){const{location:F}=L.blocks[O],N=F.block;if(N.type!=="paragraph"&&N.type!=="list"&&N.type!=="table"&&N.type!=="code"&&N.type!=="math"&&N.type!=="image"&&N.type!=="page-break"&&N.type!=="toc"){console.warn("[SuggestionPlanner] Skipping unsupported block type for position-aware insertion:",N.type);continue}const _=B(F),R=e.createPositionAwareInsertion(N.id,N,_,$(F).slice(F.indexInParent+1).map(D=>D.id).filter(D=>!!D&&d.has(D)).slice(0,1),{authorType:"ai",description:`AI: insert_${N.type} (position-aware)`});R&&(I.push(R),e.setSuggestionsForParagraph(N.id,[R]))}}const T=y?Array.from(p).filter(L=>d.has(L)):Array.from(d.keys());for(const L of T){const M=d.get(L);if(!M||v.has(L))continue;const O=M.block,F=O.type==="container"&&y&&!!p?.has(L);if(!(O.type==="container"&&!F)&&O.type!=="table-cell"&&!M.containerPath.some(N=>h.has(N))&&(O.type==="paragraph"||O.type==="list"||O.type==="table"||O.type==="code"||O.type==="math"||O.type==="image"||O.type==="docx-raw"||O.type==="page-break"||O.type==="section-break"||O.type==="toc"||F)){const N=ou(e,O);N&&(I.push(N),e.setSuggestionsForParagraph(L,[N]))}}return I}function ya(o,e,t){const n=[];if(!Ht(e,t)){const u=$r(o,t);if(u)return o.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 b=0;b<m.text.length;b++)p.push({char:m.text[b],marks:m.marks||{},nodeIndex:f,charIndexInNode:b})}}),p},r=i(e),s=i(t),a=r.map(u=>u.char).join(""),l=s.map(u=>u.char).join(""),c=Oi(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 b=r[d+m],y=s[g+m],k=b?.marks||{},I=y?.marks||{};if(!fa(k,I)){const v=m;let x=m+1;for(;x<f;){const P=r[d+x]?.marks||{},B=s[g+x]?.marks||{};if(fa(P,B)||!Cr(B,I))break;x++}const A=h.substring(v,x),w=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,E=qg(I),$=o.createTextReplacement(w,t.id,d+v,x-v,A,E,A,{authorType:"ai",description:"AI: apply formatting"});$&&n.push($),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 b=m[1];let y=!0;if(b.length>1){const k=g<s.length?s[g].marks:{};for(let I=1;I<b.length;I++){const v=g+I<s.length?s[g+I].marks:{};if(!Pr(k,v)){y=!1;break}}}if(y){const k=g<s.length?s[g].marks:{},{...I}=k,v=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,x=o.createTextReplacement(v,t.id,d,f,b,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=o.createSuggestion(k,v=>{const x=J(v,t.id);let A=null;if(x)for(let $=0;$<x.length;$++){const P=x.get($);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 w=d,E=0;for(;E<b.length;){const $=E,P=g+E,B=P<s.length?Dt(s[P].marks):{};let C=E+1;for(;C<b.length;){const L=g+C,M=L<s.length?Dt(s[L].marks):{};if(!Cr(B,M))break;C++}const T=b.substring($,C);ne(A,w,T,{...B,suggestionId:k}),w+=T.length,E=C}return[{kind:"replace",paragraphId:t.id,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,d,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,d+b.length,0)),text:b,oldText:h}]},{authorType:"ai",description:"AI: replace text"});I&&n.push(I)}u++,d+=f,g+=b.length}else{const b=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,y=o.createTextDeletion(b,t.id,d,f,h,{authorType:"ai",description:"AI: delete text"});y&&n.push(y),d+=f}}else if(p===1){const f=h,m=u>0?c[u-1]:null;if(m&&m[0]===-1)continue;const b=[];let y=0;for(;y<f.length;){const k=y,I=g+y,v=I<s.length?s[I].marks:{},x=Dt(v);let A=y+1;for(;A<f.length;){const E=g+A,$=E<s.length?s[E].marks:{};if(!Cr(x,$))break;A++}const w=f.substring(k,A);b.push({text:w,marks:x}),y=A}if(b.length===1&&Object.keys(b[0].marks).length===0){const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,I=o.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=o.createSuggestion(k,v=>{const x=J(v,t.id);let A=null;if(x)for(let E=0;E<x.length;E++){const $=x.get(E);if($ instanceof S.XmlText){A=$;break}}if(!A)return console.warn(`Paragraph ${t.id} not found for mixed formatting insertion`),[];let w=d;for(const E of b){const $={...E.marks,suggestionId:k};ne(A,w,E.text,$),w+=E.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&&o.setSuggestionsForParagraph(t.id,n),n}function $r(o,e){const t={name:"replace_block",arguments:{id:e.id,content:ee.toAgentHtml({type:"doc",children:[e]})}};if(o.createBlockReplacementSuggestion){const n=o.createBlockReplacementSuggestion(e,t);if(n)return n}return o.createSuggestionFromToolCall(t,(n,i)=>{const r=G(n,e.id);if(!r||r.yBlock.nodeName!=="paragraph")return ze(n,i);const s=se(r.yBlock)?.toDelta().map(c=>typeof c.insert=="string"?c.insert:"").join("")??"";r.yParent.delete(r.index,1);const a=ke(e);r.yParent.insert(r.index,[a]);const l=se(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:Lr(e),oldText:s}]})}function Vg(o,e,t){const n=[],i=e.children.map(y=>({item:y,text:vt(y),signature:Fr(y)})),r=t.children.map(y=>({item:y,text:vt(y),signature:Fr(y)})),{beforeKeys:s,afterKeys:a}=ca(e.children,t.children,Fr),l=Ir(s,a),c=[],d=(y,k,I)=>{const v=Math.min(y.length,k.length);for(let x=0;x<v;x++)c.push({kind:"replace",index:I+x,currentItem:y[x],finalItem:k[x]});for(let x=v;x<y.length;x++)c.push({kind:"delete",index:I+x,currentItem:y[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 y of l){let k=g;for(;k<i.length&&s[k]!==y;)k+=1;let I=u;for(;I<r.length&&a[I]!==y;)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||!xa(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(y=>y.kind!=="replace"?!0:y.currentItem.signature!==y.finalItem.signature||y.currentItem.text!==y.finalItem.text);if(c.length>0&&!p){const y=Gg(o,t);return y?[y]:[]}for(const y of c){if(y.kind==="insert"){const I=Zg(o,e.id,y.finalItem.item,y.index,e.variant);I&&n.push(I);continue}if(y.kind==="delete"){const I=Qg(o,e.id,y.index,y.currentItem.text);I&&n.push(I);continue}const k=eu(o,e.id,y.index,y.currentItem.item,y.finalItem.item,e.variant);k&&n.push(k)}const h=c.filter(y=>y.kind==="replace").length,f=c.some(y=>y.kind!=="replace"?y.kind==="insert"||y.kind==="delete":y.currentItem.signature!==y.finalItem.signature||y.currentItem.text!==y.finalItem.text),m=Math.max(i.length,r.length),b=m>0?n.length/m:0;if(h>0&&b>.7&&f){const y=Er(o,t);return y?[y]:[]}return n}function Gg(o,e){if(!e.id)return null;const t=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return o.createSuggestion(t,n=>{const i=J(n,e.id);if(!i||i.nodeName!=="list")return[];for(let r=0;r<e.children.length;r++){const s=i.get(r),a=e.children[r];if(!(s instanceof S.XmlElement)||!a)continue;const l=se(s);if(!l)continue;let c=0;for(const d of a.children)d.type!=="text"||d.text.length===0||(re(l,c,d.text.length,ha(d.marks||{})),c+=d.text.length)}return[{kind:"replace",paragraphId:e.id,text:e.children.map(vt).join(`
|
|
27
|
-
`),oldText:e.children.map(vt).join(`
|
|
28
|
-
`)}]},{authorType:"ai",description:"AI: apply list formatting"})}function Zg(o,e,t,n,i){const r=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return o.createSuggestion(r,s=>{const a=J(s,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:vt(t)}]},{authorType:"ai",description:"AI: insert list item"})}function Qg(o,e,t,n){const i=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return o.createSuggestion(i,r=>{const s=J(r,e);return!s||s.nodeName!=="list"?(console.warn(`List ${e} not found for item deletion`),[]):t>=s.length?(console.warn(`Item index ${t} out of bounds for list ${e}`),[]):(s.delete(t,1),[{kind:"delete",paragraphId:e,text:n}])},{authorType:"ai",description:"AI: delete list item"})}function eu(o,e,t,n,i,r){const s=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return o.createSuggestion(s,a=>{const l=J(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={...Dt(h.marks||{}),suggestionId:s,toolType:"list_item_replace"};d.insert(u,h.text,f),u+=h.text.length}}),[{kind:"replace",paragraphId:e,text:vt(i),oldText:vt(n)}]},{authorType:"ai",description:"AI: replace list item"})}function vt(o){return o.children.filter(e=>e.type==="text").map(e=>e.text).join("")}function Fr(o){return JSON.stringify({...Object.fromEntries(vn.map(e=>[e,o[e]])),direction:o.direction,checked:o.checked??!1,indentLevel:o.indentLevel??0,children:o.children.map(e=>e.type==="text"?{type:"text",text:e.text}:{type:e.type})})}function Er(o,e){const t={name:"replace_block",arguments:{id:e.id,content:ru(e)}};return o.createSuggestionFromToolCall(t,n=>{const i=G(n,e.id);return i?(i.yParent.delete(i.index,1),i.yParent.insert(i.index,[ke(e)]),[{kind:"replace",paragraphId:e.id,text:"List replaced",oldText:i.yBlock.nodeName==="list"?"List":"Paragraph"}]):[]})}function ka(o,e){const t={name:"replace_block",arguments:{id:e.id,content:ee.toInternalHtml({type:"doc",children:[e]})}};return o.createSuggestionFromToolCall(t,(n,i)=>ze(n,i))}function Sa(o,e){const t={name:"replace_block",arguments:{id:e.id,content:ee.toAgentHtml({type:"doc",children:[e]})}};return o.createSuggestionFromToolCall(t,(n,i)=>ze(n,i))}function Ia(o,e){const t={name:"replace_block",arguments:{id:e.id,content:ee.toAgentHtml({type:"doc",children:[e]})}};return o.createSuggestionFromToolCall(t,(n,i)=>ze(n,i))}function va(o,e){const t={name:"replace_block",arguments:{id:e.id,content:ee.toInternalImageHtml(e)}};return o.createSuggestionFromToolCall(t,(n,i)=>ze(n,i))}function tu(o,e){const t={name:"replace_block",arguments:{id:e.id,content:ee.toAgentHtml({type:"doc",children:[e]})}};return o.createSuggestionFromToolCall(t,(n,i)=>ze(n,i))}function nu(o,e){const t={name:"replace_block",arguments:{id:e.id,content:ee.toAgentHtml({type:"doc",children:[e]})}};return o.createSuggestionFromToolCall(t,(n,i)=>ze(n,i))}function iu(o,e){if(o.children.length!==e.children.length)return!1;for(let t=0;t<o.children.length;t++){const n=o.children[t],i=e.children[t];if(vn.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(""),s=i.children.filter(a=>a.type==="text").map(a=>a.text).join("");if(r!==s||!xa(n,i))return!1}return!0}function xa(o,e){if(o.children.length!==e.children.length)return!1;for(let t=0;t<o.children.length;t++){const n=o.children[t],i=e.children[t];if(n.type!==i.type||n.type==="text"&&i.type==="text"&&(n.text!==i.text||!Pr(n.marks||{},i.marks||{})))return!1}return!0}function ru(o){return ee.toInternalHtml({type:"doc",children:[o]})}function ou(o,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 o.createSuggestion(i,r=>{const s=G(r,t);if(!s)return console.warn(`[SuggestionPlanner] Block ${t} not found for removal`),[];const{yBlock:a,yParent:l,index:c}=s,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=te(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 su(o,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 s={name:"insert_block",arguments:{referenceId:i,position:r,content:[au(e)]}};return Ie(s,{stableId:e.id||Y()}),o.createSuggestionFromToolCall(s,(a,l)=>ze(a,l))}function au(o){return o.type==="paragraph"?lu(o):o.type==="image"?ee.toInternalImageHtml(o):o.type==="list"||o.type==="table"||o.type==="code"||o.type==="math"||o.type==="page-break"||o.type==="toc"?ee.toInternalHtml({type:"doc",children:[o]}):""}function Fe(o){return o.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'")}function lu(o,e){const t=o.heading?`h${o.heading}`:"p",n=[];o.align&&n.push(`text-align: ${o.align}`);const i=n.length>0?` style="${n.join("; ")}"`:"";let r=`<${t}${i}>`;for(const s of o.children)if(s.type==="text"){let a=s.text.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'");if(s.marks?.bold&&(a=`<b>${a}</b>`),s.marks?.italic&&(a=`<i>${a}</i>`),s.marks?.underline&&(a=`<u>${a}</u>`),s.marks?.strikethrough&&(a=`<s>${a}</s>`),s.marks?.code&&(a=`<code>${a}</code>`),s.marks?.latex&&(a=`<latex-inline>${a}</latex-inline>`),s.marks?.superscript||s.marks?.footnoteRef){const g=s.marks?.footnotePendingBody!==void 0?` data-footnote="${Fe(s.marks.footnotePendingBody)}"${s.marks?.footnotePendingKind==="endnote"?' data-note-kind="endnote"':""}`:"";a=s.marks?.footnoteRef?`<sup data-footnote-ref="${Fe(s.marks.footnoteRef)}"${g}>${a}</sup>`:`<sup>${a}</sup>`}else s.marks?.subscript&&(a=`<sub>${a}</sub>`);const l=s.marks?.fontFamily,c=s.marks?.fontSize;if(l||c||s.marks?.color||s.marks?.doubleStrikethrough||s.marks?.smallCaps||s.marks?.allCaps||s.marks?.letterSpacing){const g=[];l&&g.push(`font-family: ${Fe(l)}`),c&&g.push(`font-size: ${c}px`),s.marks?.color&&g.push(`color: ${Fe(s.marks.color)}`),s.marks?.doubleStrikethrough&&g.push("text-decoration: line-through double"),s.marks?.smallCaps&&g.push("font-variant: small-caps"),s.marks?.allCaps&&g.push("text-transform: uppercase"),typeof s.marks?.letterSpacing=="number"&&Number.isFinite(s.marks.letterSpacing)&&s.marks.letterSpacing!==0&&g.push(`letter-spacing: ${s.marks.letterSpacing}px`),a=`<span style="${g.join("; ")}">${a}</span>`}s.marks?.hidden&&(a=`<span data-word-hidden="true">${a}</span>`),s.marks?.lang&&(a=`<span data-word-lang="${Fe(s.marks.lang)}">${a}</span>`),s.marks?.bookmark&&(a=`<span data-bookmark="${Fe(s.marks.bookmark)}">${a}</span>`),s.marks?.fieldInstr&&(a=`<span data-field-instr="${Fe(s.marks.fieldInstr)}">${a}</span>`),s.marks?.field&&(a=`<span data-dynamic-field="${Fe(s.marks.field)}">${a}</span>`),s.marks?.sdtInline&&(a=`<span data-sdt-inline="${Fe(s.marks.sdtInline)}">${a}</span>`),s.marks?.aiGenerated&&(a=`<span data-ai-generated="true">${a}</span>`),s.marks?.__htmlClassName&&(a=`<span data-html-class="${Fe(s.marks.__htmlClassName)}">${a}</span>`);const d=_e(s.marks?.backgroundColor);if(d&&(a=`<mark color="${Fe(d)}">${a}</mark>`),s.marks?.link&&(a=`<a href="${Fe(s.marks.link)}">${a}</a>`),s.marks?.comment)for(const g of s.marks.comment.split(",").map(u=>u.trim()).filter(Boolean).reverse())a=`<comment-thread id="${Fe(g)}">${a}</comment-thread>`;r+=a}return r+=`</${t}>`,r}function Lr(o){return o.children.filter(e=>e.type==="text").map(e=>e.type==="text"?e.text:"").join("")}function cu(o,e){if(!Ht(o,e)||o.children.length!==e.children.length)return!0;for(let t=0;t<o.children.length;t++){const n=o.children[t],i=e.children[t];if(n.type!==i.type||n.type==="text"&&i.type==="text"&&(n.text!==i.text||!Pr(n.marks||{},i.marks||{})))return!0}return!1}const du=Object.freeze(Object.defineProperty({__proto__:null,ToolCallHistory:pa,createFlattenedSuggestions:Br,createGranularSuggestionsForParagraph:ya},Symbol.toStringTag,{value:"Module"}));class Mr{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=J(this.ydoc,e.paragraphId),n=t?se(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)),s=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:s,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 s=[];i.transact(()=>{s=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:s,...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?J(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,s={}){return this.createForklessTextSuggestion({id:e,kind:"delete",paragraphId:t,startOffset:n,deleteLength:i,newText:"",marks:{},anchorText:r,metadata:{...s,id:e}})||this.createSuggestion(e,l=>{const c=J(l,t);if(!c)return[];const d=se(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}]):[]},{...s,id:e,inlinePreview:{startOffset:n,newText:"",marks:{}}})}createTextInsertion(e,t,n,i,r={},s={}){const a={...r,suggestionId:e};return this.createSuggestion(e,l=>{const c=J(l,t);if(!c)return[];const d=se(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}]):[]},{...s,id:e})}createTextReplacement(e,t,n,i,r,s={},a,l={}){const c={...s,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=J(g,t);if(!u)return[];const p=se(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 s=this.generateId();return this.suggestionMeta.set(s,{id:s,authorId:r.authorId||"system",authorType:r.authorType||"ai",createdAt:Date.now(),status:"pending",insertionContext:{paragraphId:e,content:t,mustBeAfter:n,mustBeBefore:i},...r}),s}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,[ke(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 s=G(t,i.blockPreview.id);s&&(s.yParent.delete(s.index,1),s.yParent.insert(s.index,[ke(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,s=i.to?S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(i.to),t):null;return{kind:i.kind,paragraphId:i.paragraphId,fromIndex:r?.index??null,toIndex:s?.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 s=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)){s=l+1;break}}const a=gu(i.content,i.paragraphId,t);r.insert(s,[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,s]of n)s===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 gu(o,e,t,n){if(o.type==="list"){const a=new S.XmlElement("list");return a.setAttribute("id",e),a.setAttribute("variant",o.variant??"unordered"),o.startNumber!==void 0&&a.setAttribute("startNumber",String(o.startNumber)),o.numberingChainId&&a.setAttribute("numberingChainId",o.numberingChainId),o.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=Nr(u.marks,t);d.insert(g,u.text,p),g+=u.text.length}),c.insert(0,[d]),a.push([c])}),a}if(o.type==="table")return ke(so({...o,id:e},a=>({...a,marks:Nr(a.marks,t)})));if(o.type==="code"){const a=new S.XmlElement("code");a.setAttribute("id",e),o.language&&a.setAttribute("language",o.language),o.renderDiagram!==void 0&&a.setAttribute("renderDiagram",String(o.renderDiagram)),o.showDiagramSource!==void 0&&a.setAttribute("showDiagramSource",String(o.showDiagramSource));const l=new S.XmlText;return a.insert(0,[l]),ne(l,0,o.content||""),a}if(o.type==="math"){const a=new S.XmlElement("math");a.setAttribute("id",e),o.displayMode&&a.setAttribute("displayMode",o.displayMode),o.align&&a.setAttribute("align",o.align);const l=new S.XmlText;return a.insert(0,[l]),ne(l,0,o.content||""),a}if(o.type==="image"){const a=new S.XmlElement("image");return a.setAttribute("id",e),a.setAttribute("src",o.src),o.sourceUrl&&a.setAttribute("sourceUrl",o.sourceUrl),a.setAttribute("width",String(o.width)),a.setAttribute("height",String(o.height)),o.alt&&a.setAttribute("alt",o.alt),o.align&&a.setAttribute("align",o.align),a}if(o.type==="page-break"){const a=new S.XmlElement("page-break");return a.setAttribute("id",e),a}if(o.type==="toc")return ke({...o,id:e});if(o.type==="section-break"){const a=new S.XmlElement("section-break");return a.setAttribute("id",e),o.layout&&a.setAttribute("layout",JSON.stringify(o.layout)),o.breakType&&a.setAttribute("breakType",o.breakType),a}const i=new S.XmlElement("paragraph");i.setAttribute("id",e),o.heading&&i.setAttribute("heading",String(o.heading)),o.align&&i.setAttribute("align",o.align);const r=new S.XmlText;let s=0;return o.children.forEach(a=>{if(a.type!=="text")return;const l=Nr(a.marks,t);ne(r,s,a.text,l),s+=a.text.length}),i.insert(0,[r]),i}function Nr(o,e,t){return{...o||{},suggestionId:e}}class bn{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"?Qe:this.host.defaultHumanAuthorName??ko)}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},s=()=>{this.host.liveSuggestionMetadataContext=r;try{return t()}finally{this.host.liveSuggestionMetadataContext=n}},a=e.batchHistory===!1?s():this.host.runWithUndoGroup(e.historyOrigin??`live-suggestions:${r.createdAt}`,s),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(),s=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:s,...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??J(this.host.ydoc,n);if(i instanceof S.XmlElement)try{if(e.type==="table-change"){let r=[];const s=i.getAttribute("structuralSuggestionRecords");if(typeof s=="string")try{const a=JSON.parse(s);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=J(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 s of r.toArray()){if(!(s instanceof S.XmlElement))continue;const a=s.getAttribute("structuralSuggestionRecord");if(typeof a=="string"&&a.length>0)try{n(JSON.parse(a))}catch{}const l=s.getAttribute("structuralSuggestionRecords");if(typeof l=="string"&&l.length>0)try{const c=JSON.parse(l);Array.isArray(c)&&c.forEach(n)}catch{}i(s)}};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 s=this.findInlineSuggestionMetadataInValue(r,t);if(s)return s}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=hn(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=X(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??X(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 s=this.getLiveSuggestion(i);return s?.source?s.source===e:e==="agent"&&s?.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"?Qe:ko}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=hn(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=X(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=X(n,t.tableId);return i?.type!=="table"||!this.blockContainsSuggestionMarker(i,t.id)?!1:t.tableRevision.operations.some(r=>r.kind==="row"?i.children.some(s=>s.id===r.rowId):r.kind==="cell"?i.children.some(s=>s.id===r.rowId&&s.children.some(a=>a.id===r.cellId)):r.kind==="geometry"?r.pendingRows.some(s=>i.children.some(a=>a.id===s.id)):r.kind==="grid"||r.target==="table"?!0:r.target==="row"||r.target==="row-exception"?i.children.some(s=>s.id===r.rowId):i.children.some(s=>s.children.some(a=>a.id===r.cellId)))}case"block-insert":{const i=X(n,t.blockId);return i&&this.blockContainsSuggestionMarker(i,t.id)?!0:this.host.collectStructuralInsertBlockIds(n,t.id).length>0}case"block-delete":{const i=X(n,t.blockId);return!!(i&&this.blockContainsSuggestionMarker(i,t.id))}case"paragraph-split":{const i=X(n,t.blockId),r=X(n,t.insertedBlockId);return!!(i&&r&&(this.blockContainsSuggestionMarker(i,t.id)||this.blockContainsSuggestionMarker(r,t.id)))}case"paragraph-merge":{const i=X(n,t.firstBlockId),r=X(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=vr(n,i.ydoc);if(!r.anchor||!r.focus)return null;const s=Se(i.doc,r.anchor,r.focus)<=0;return{doc:i.doc,start:s?r.anchor:r.focus,end:s?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=Si.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=J(i.ydoc,e),s=r?se(r):null,a=J(this.host.ydoc,e),l=a?se(a):null;if(!s||!l||n>s.length)return null;const c=S.createRelativePositionFromTypeIndex(s,t,0),d=S.createRelativePositionFromTypeIndex(s,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){bn.collectSuggestionIdsFromBlockValue(e,t)}static collectSuggestionIdsFromBlockValue(e,t){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(const r of e)bn.collectSuggestionIdsFromBlockValue(r,t);return}const n=e;typeof n.suggestionId=="string"&&n.suggestionId.length&&t.add(n.suggestionId);const i=hn(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 s of r)s&&typeof s.id=="string"&&s.id&&t.add(s.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"&&bn.collectSuggestionIdsFromBlockValue(r,t)}getSequenceReplacementMembers(e){const t=[],n=i=>{i.toArray().forEach((r,s)=>{r instanceof S.XmlElement&&(r.getAttribute("structuralSuggestionId")===e.id?t.push({yBlock:r,yParent:i,index:s}):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,s=this.host.getDocument(),a=Ye(s),l=Ye(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??X(s,g);u&&this.collectSuggestionIdsFromBlockValue(u,r)}const d=this.getSuggestionMutationSelection();for(const g of i){const u=a.get(g)?.block??X(s,g),p=l.get(g)?.block??X(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 s=this.host.documentId==="live-suggestion-projection"?this.applySimpleProjectionBlockDecisions(n,t):new Set;r+=s.size;const a=new Set;for(const l of n){if(s.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,s=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),s.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),s.add(l))}}if(s.size===0)return s;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 s)this.deleteLiveSuggestion(l)}),s}applyLiveSuggestionDecisionScopeInternal(e){let t=0,n=[];const i=new Set,r=new Set,s=[];for(let a=0;a<qa;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(s.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:s}}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 s=this.applyLiveSuggestionDecisionScopeInternal(e),a=s.prunedSuggestions.concat(this.pruneUnresolvableLiveSuggestionsInternal());i={...s,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||Se(e,n.anchor,n.focus)===0)return null;const[i,r]=Se(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 s=X(e,t.block);if(!s)return null;if(s.type==="paragraph")return r.offset>i.offset?ce():null;if(s.type!=="list")return null;const a=this.host.getListCursorInfo(s,i),l=this.host.getListCursorInfo(s,r);return!a||!l||a.itemIndex!==l.itemIndex?null:(s.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 s=r.text.length,a=n+s,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=X(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=X(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=X(e,t);for(;n;){const i=this.getBlockInsertSuggestionIdForBlock(n);if(i)return i;if(typeof n.id!="string")break;const r=qe(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",s=i?.authorType??(r==="agent"?"ai":"human");return{suggestionId:e,suggestionSource:r,suggestionAuthorType:s,suggestionCreatedAt:n??i?.createdAt??Date.now(),suggestionLabel:t??i?.label,...i?.commentThreadId?{suggestionCommentThreadId:i.commentThreadId}:{},suggestionAuthorName:this.resolveSuggestionAuthorName(s,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 s=e?.suggestionId===t?e:r?.suggestionId===t?r:null;return this.recordStampedId("insertionIds",t),{...e||{},insertion:!0,...this.buildInlineSuggestionMetadataMarks(t,n,i),...this.pickInlineSuggestionMetadataMarks(s)}}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||re(e,t,n,{deletion:null})}findAdjacentDeletionSuggestionAttrs(e,t,n){if(n<=0)return null;const i=t+n,r=te(e);let s=0,a=null,l=null;for(const c of r){if(typeof c.insert!="string")continue;const d=s,g=s+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(s=g,s>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 s=i?null:this.findAdjacentDeletionSuggestionAttrs(e,t,n),a=i??s?.suggestionId??ce(),l={...this.buildInlineSuggestionMetadataMarks(a,"Delete"),...this.pickInlineSuggestionMetadataMarks(s?.suggestionId===a?s: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),re(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),re(e,u.start,u.length,{...l,formatChange:null,suggestionPriorAttributes:null}),d=!0);continue}this.recordStampedId("deletionIds",a),re(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(s=>t.has(s.id)?{...s,diffState:n,suggestionId:i,children:s.children.map(a=>({...a,diffState:n,suggestionId:i}))}:s),r}markTableSuggestionColumn(e,t,n,i){const r=this.cloneSuggestionSnapshot(e);return r.children=r.children.map(s=>({...s,children:s.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),s=t.children.map(h=>h.id),a=h=>JSON.stringify(h,(f,m)=>{if(f!=="id"){if(f==="marks"&&m&&typeof m=="object"){const b={...m};return b.fontFamily===Le&&delete b.fontFamily,Object.keys(b).length?b:void 0}return m}}),l=a({...e,children:[]})===a({...t,children:[]}),c=(h,f)=>{let m=0;for(const b of f)b===h[m]&&m++;return m===h.length};if(t.children.length>e.children.length&&c(r,s)&&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((y,k)=>({row:y,rowIndex:k})).filter(({row:y})=>!h.has(y.id)),m=new Set(f.map(({row:y})=>y.id)),b=f.length===1?"Insert table row":"Insert table rows";return{liveBlock:this.markTableSuggestionRows(t,m,"insert",n),label:b,record:i(b,"insert",{markers:f.map(({row:y,rowIndex:k})=>({kind:"row-insert",rowId:y.id,rowIndex:k})),operations:f.map(({row:y,rowIndex:k})=>({kind:"row",action:"insert",rowId:y.id,rowIndex:k,row:this.cloneSuggestionSnapshot(y)}))})}}if(t.children.length<e.children.length&&c(s,r)&&l&&t.children.every(h=>a(h)===a(e.children.find(f=>f.id===h.id)))){const h=new Set(s),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)),b=new Map(t.children.map(I=>[I.id,I])),y=this.cloneSuggestionSnapshot(t);y.children=e.children.map(I=>b.get(I.id)??I);const k=f.length===1?"Delete table row":"Delete table rows";return{liveBlock:this.markTableSuggestionRows(y,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(b=>{const y=m.children.find(k=>k.id===b.id);return y&&a(b)!==a(y)})})))return null;if(d?.kind==="insert"){const h=[],f=[];for(let m=0;m<t.children.length;m++){const b=t.children[m],y=b.children[d.index];y&&(h.push({kind:"cell",action:"insert",rowId:b.id,cellId:y.id,cellIndex:d.index,cell:this.cloneSuggestionSnapshot(y)}),f.push({kind:"cell-insert",rowId:b.id,cellId:y.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 b=e.children[m],y=b.children[d.index];y&&(h.push({kind:"cell",action:"delete",rowId:b.id,cellId:y.id,cellIndex:d.index,cell:this.cloneSuggestionSnapshot(y)}),f.push({kind:"cell-delete",rowId:b.id,cellId:y.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,b=m.rowSpan>f.rowSpan,y=b?f.row+f.rowSpan:m.row+m.rowSpan,k=b?m.row+m.rowSpan:f.row+f.rowSpan,I=[],v=new Set([e.children[f.row].id]);for(let E=y;E<k;E++){const $=t.children[E];$&&(v.add($.id),I.push({kind:"cell-merge",rowId:$.id,rowIndex:E,gridColumn:m.col,...b?{vMerge:"cont"}:{vMergeOrig:"cont"}}))}const x=t.children.filter(E=>v.has(E.id)).map(E=>this.cloneSuggestionSnapshot(E)),A=e.children.filter(E=>v.has(E.id)).map(E=>this.cloneSuggestionSnapshot(E));if(!l||e.children.some(E=>!v.has(E.id)&&a(E)!==a(t.children.find($=>$.id===E.id))))return null;const w=b?"Merge table cells":"Split table cells";return{liveBlock:this.cloneSuggestionSnapshot(t),label:w,record:i(w,"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 b={...m};return b.fontFamily===Le&&delete b.fontFamily,Object.keys(b).length>0?b: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((b,y)=>{const k=m.children[y];return k?.id===b.id&&b.colSpan===k.colSpan&&b.rowSpan===k.rowSpan&&p(b)===p(k)})})){const h=[],f=[],m=(y,k,I)=>{const v={},x={};for(const A of I){const w=y[A],E=k[A];JSON.stringify(w)!==JSON.stringify(E)&&(E!==void 0&&(v[A]=E),w!==void 0&&(x[A]=w))}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 b=m(e,t,["tableWidth","align","borderColor","borderWidth","borders","cellPadding"]);(Object.keys(b.current).length>0||Object.keys(b.prior).length>0)&&(f.push({kind:"table-properties"}),h.push({kind:"properties",target:"table",currentPropertiesXml:"",priorPropertiesXml:"",currentAttributes:b.current,priorAttributes:b.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 y=0;y<t.children.length;y++){const k=e.children[y],I=t.children[y];for(let v=0;v<I.children.length;v++){const x=k.children[v],A=I.children[v],w=m(x,A,["verticalAlign","backgroundColor","borders","padding"]);if(Object.keys(w.current).length===0&&Object.keys(w.prior).length===0)continue;const E=u.byId.get(A.id);f.push({kind:"cell-properties",rowId:I.id,cellId:A.id,rowIndex:y,cellIndex:v,gridColumn:E?.col}),h.push({kind:"properties",target:"cell",rowId:I.id,cellId:A.id,currentPropertiesXml:"",priorPropertiesXml:"",currentAttributes:w.current,priorAttributes:w.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((s,a)=>{const l=r.children[a];return l?.id===s.id&&l.colSpan===s.colSpan&&l.rowSpan===s.rowSpan})})}reconcileTableDescendantIds(e,t){const n=this.cloneSuggestionSnapshot(t),i=new Set(["id","diffState","suggestionId","structuralSuggestionId","structuralSuggestionKind","structuralSuggestionRole","structuralSuggestionLabel","structuralSuggestionRecord","structuralSuggestionRecords"]),r=y=>Yt(JSON.parse(JSON.stringify(y,(k,I)=>i.has(k)?void 0:I))),s=e.children,a=n.children,l=new Set(s.map(y=>y.id)),c=new Set(a.map(y=>y.id)),d=new Set(s.flatMap(y=>y.children.map(k=>k.id))),g=new Set(a.flatMap(y=>y.children.map(k=>k.id))),u=new Map([...s,...a].map(y=>[y,r(y)])),p=(y,k)=>y.id===k.id?0:l.has(k.id)||c.has(y.id)?2.25:u.get(y)===u.get(k)?0:y.children.length===k.children.length&&y.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:s.length+1},()=>Array(a.length+1).fill(0));for(let y=0;y<=s.length;y++)h[y][0]=y;for(let y=0;y<=a.length;y++)h[0][y]=y;for(let y=1;y<=s.length;y++)for(let k=1;k<=a.length;k++)h[y][k]=Math.min(h[y-1][k]+1,h[y][k-1]+1,h[y-1][k-1]+p(s[y-1],a[k-1]));const f=[];let m=s.length,b=a.length;for(;m>0&&b>0;){const y=p(s[m-1],a[b-1]);y<2&&Math.abs(h[m][b]-(h[m-1][b-1]+y))<1e-4?(f.push([s[m-1],a[b-1]]),m--,b--):h[m][b]===h[m-1][b]+1?m--:b--}for(const[y,k]of f)if(k.id=y.id,y.children.length===k.children.length)for(let I=0;I<y.children.length;I++){const v=y.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,s)=>{!s.diffState&&r.diffState&&(s.diffState=r.diffState),!s.suggestionId&&r.suggestionId&&(s.suggestionId=r.suggestionId)};for(let r=0;r<e.children.length;r++){const s=e.children[r];let a=n.children.find(l=>l.id===s.id);if(!a&&s.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(s),n.children.splice(c,0,a)}if(a){i(s,a);for(let l=0;l<s.children.length;l++){const c=s.children[l];let d=a.children.find(g=>g.id===c.id);if(!d&&c.diffState==="delete"){const g=s.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=J(this.host.ydoc,e.blockId);if(!(t instanceof S.XmlElement))return null;if(e.itemIndex===void 0)return se(t);const n=[];for(let r=0;r<t.length;r++){const s=t.get(r);s instanceof S.XmlElement&&s.nodeName==="list-item"&&n.push(s)}const i=n[e.itemIndex];return i?se(i):null}stripInlineSuggestionMarks(e,t,n){re(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),s=r.length>0?r:[{start:t,length:n,attributes:{}}];for(const a of s){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=bi(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;re(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 s=r.filter(a=>a?.id!==t);s.length!==r.length&&(s.length>0?n.setAttribute("structuralSuggestionRecords",JSON.stringify(s)):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=X(this.host.getDocument(),e.blockId);return t?this.blockContainsSuggestionMarker(t,e.id)?!0:t.structuralSuggestionId?!1:Pl(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=X(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(s=>s?.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])),s=new Set([...i.keys(),...r.keys()]);for(const a of s){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(b=>b.id===h.id);let m=l.children.find(b=>b.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 b of["rowSpan","colSpan"])f[b]!==h[b]&&(h[b]===void 0?delete m[b]:m[b]=h[b])}}}}applyTableRevisionDecision(e,t){const n=X(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(b=>b.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(y=>y.id===l.rowId);if(!f)continue;const m=l.action==="insert"?t==="accept":t==="reject",b=f.children.findIndex(y=>y.id===l.cellId);m&&b<0?f.children.splice(Math.min(l.cellIndex,f.children.length),0,this.cloneSuggestionSnapshot(l.cell)):!m&&b>=0&&f.children.splice(b,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 s=this.getSuggestionMutationSelection(),a=this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(e.tableId,i,s,s));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=X(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=X(n,e.secondBlockId);let r=X(n,e.firstBlockId),s=qe(n,e.firstBlockId);if(!r||r.type!=="paragraph"){const d=qe(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,s=d??n)}if(!r||!i||!s||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,s,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(s=>s.yParent!==r.yParent)?!1:(this.host.transact(()=>{for(const s of[...i].sort((a,l)=>l.index-a.index))s.yParent.delete(s.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 s=!1;for(const a of[...r].reverse())s=this.runWithoutSuggesting(()=>this.host.deleteBlockById(a,t,t))||s;if(s){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 s}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!X(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;if(this.host.transact(()=>{const i=r=>{for(const s of r.toArray()){if(s instanceof S.XmlElement){const d=s.getAttribute("structuralSuggestionId");typeof d=="string"&&e.has(d)&&(this.clearElementStructuralSuggestion(s),n.add(d));const g=s.getAttribute("suggestionId");typeof g=="string"&&e.has(g)&&(this.setDiffSuggestionAttributes(s,void 0,void 0),n.add(g)),i(s);continue}if(!(s instanceof S.XmlText))continue;const a=te(s),l=[];let c=0;for(const d of a)typeof d.insert=="string"&&(l.push({start:c,length:d.insert.length,attributes:d.attributes||{}}),c+=d.insert.length);for(let d=l.length-1;d>=0;d--){const g=l[d],u=typeof g.attributes.suggestionId=="string"?g.attributes.suggestionId:null,p=hn(g.attributes.layeredInsertion);if(u&&e.has(u)){t==="accept"?g.attributes.deletion?s.delete(g.start,g.length):this.stripInlineSuggestionMarks(s,g.start,g.length):g.attributes.deletion&&p?re(s,g.start,g.length,{deletion:null,layeredInsertion:null,insertion:!0,suggestionId:p.id,suggestionSource:p.source??null,suggestionAuthorType:p.authorType??null,suggestionCreatedAt:p.createdAt??null,suggestionLabel:p.label??"Insert",suggestionCommentThreadId:p.commentThreadId??null,suggestionAuthorName:p.authorName??null,suggestionAgentModel:p.agentModel??null,suggestionAgentConversationId:p.agentConversationId??null,suggestionAgentRequestId:p.agentRequestId??null,suggestionAgentTurn:p.agentTurn??null}):g.attributes.insertion?s.delete(g.start,g.length):g.attributes.formatChange&&bi(g.attributes.suggestionPriorAttributes)?this.restoreInlineSuggestionFormatting(s,g.start,g.length,bi(g.attributes.suggestionPriorAttributes)):this.stripInlineSuggestionMarks(s,g.start,g.length),n.add(u);continue}p&&e.has(p.id)&&(t==="accept"?re(s,g.start,g.length,{insertion:null,layeredInsertion:null}):s.delete(g.start,g.length),n.add(p.id))}}};i(this.host.getYContentFragment()),i(this.host.getYNotesFragment()),i(this.host.ydoc.getXmlFragment("chrome"))}),n.size>0){const i=this.getSuggestionMutationSelection();this.host.setSelectionAfterOperation(i),this.host.afterOperationRelativeSelection=H(i,this.host.ydoc,this.host.getDocument());for(const r of n)this.deleteLiveSuggestion(r)}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 s=this.host.getDocument().children.slice(n,i+1);if(s.length<2||s.some(c=>c.type!=="paragraph"))return!1;const a=s.map((c,d)=>{const g=c,u=this.host.getParagraphTextLength(g),p=d===0?Math.min(e.offset,u):0,h=d===s.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=J(this.host.ydoc,c.blockId);if(!(d instanceof S.XmlElement))continue;const g=se(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<s.length;c++){const d=s[c],g=s[c+1],u=J(this.host.ydoc,d.id),p=J(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=Ja(e);for(const n of io)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(s=>this.sanitizePreviewBlock(s))}))}))});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===Le||i.fontFamily==="Arial"){const r={...i};return delete r.fontFamily,r}return i};return JSON.stringify({...Object.fromEntries(vn.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 Ir(n,i)}getListItemAlignmentKeysForSuggestionBridge(e,t){return ca(e,t,n=>this.getListItemSignatureForSuggestionBridge(n))}computeListSuggestionBridgeOperations(e,t){const n=[],i=this.computeListItemLcsForSuggestionBridge(e.children,t.children),{beforeKeys:r,afterKeys:s}=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 b=0;b<m;b++)n.push({kind:"change",index:h+b,beforeItem:u[b],afterItem:p[b]});for(let b=m;b<u.length;b++)n.push({kind:"delete",index:h+b,beforeItem:u[b]});for(let b=m;b<p.length;b++)n.push({kind:"insert",index:h+b,afterIndex:f+b,afterItem:p[b]})};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<s.length&&s[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 s=this.sanitizePreviewBlock(e),a=this.sanitizePreviewBlock(t),l=r?this.cloneSuggestionSnapshot(r):null;if(i.kind==="insert"){const g=this.cloneSuggestionSnapshot(l??s),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??s),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??s),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(!co(t,n))return!1;const i=this.computeListSuggestionBridgeOperations(t,n);if(i.length===0)return!1;let r=this.cloneSuggestionSnapshot(e.currentLiveBlock??t),s=!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,s=!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(s&&!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=Oi(u,d).diffs;let h=0,f=0;g=!0;for(let m=0;m<p.length&&g;m++){const[b,y]=p[m];if(b===0){g=this.applyBridgeInlineFormatSuggestion({suggestionId:ce(),blockId:e.blockId,itemIndex:c.itemIndex,start:f,end:f+y.length,targetAttributes:{},targetTextNodes:this.host.extractTextNodesForRange(c.afterItem,h,h+y.length),createdAt:e.createdAt}),h+=y.length,f+=y.length;continue}if(b===-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:y.length,insertNodes:I,label:"Replace",createdAt:e.createdAt}),f+=y.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:y.length,insertNodes:[],label:"Replace",createdAt:e.createdAt}),f+=y.length}else{const k=this.host.extractTextNodesForRange(c.afterItem,h,h+y.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+=y.length,h+=y.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 s=this.applySuggestedDeletionToTextRange(t,e.start,e.deleteLength,e.suggestionId);i=e.start+s.retainedLength,n=n||s.changed}let r=i;for(const s of e.insertNodes){if(!s.text)continue;const a=this.buildSuggestionInsertionMarks(this.sanitizePreviewMarks(s.marks),e.suggestionId,e.label,e.createdAt);ne(t,r,s.text,a),r+=s.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 s=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=s+d.length;for(;l<i.length&&i[l].start+i[l].length<=s;)l++;for(let u=l;u<i.length&&i[u].start<g;u++){const p=i[u],h=Math.max(p.start,s),f=Math.min(p.start+p.length,g);if(f<=h)continue;const m=e.targetTextNodes?as(p.attributes,d.marks):{...d.marks??{}};r.push({...p,start:h,length:f-h,targetAttributes:m})}s=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;re(t,d.start,d.length,{...g,suggestionPriorAttributes:un(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(),s=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"?s:s+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=J(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"?X(this.host.getDocument(),e.blockId):null;let r=this.markBlockForGenericSuggestionChange(n,e.suggestionId,e.label),s,a,l=e.label;if(t.type==="paragraph"&&n.type==="paragraph"&&Me(t)!==Me(n))r=this.host.buildParagraphReplacementLiveBlock(t,n,e.suggestionId,e.label),s=n;else if(t.type==="paragraph"&&n.type==="paragraph")s=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"},s=n,l="List"}else if(t.type==="table"&&n.type==="table"){const c=X(this.createLiveSuggestionProjection("accept").doc,e.blockId),d=c?.type==="table"?c:t,g=this.reconcileTableDescendantIds(d,n),u=wn(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||wn(d,g))r=this.markBlockForGenericSuggestionChange(g,e.suggestionId,"Table"),s=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"&&Me(t)===Me(n)){const c=this.batchYBlockLocationsById?.get(e.blockId)?.yBlock??J(this.host.ydoc,e.blockId),d=c?c._item:null,g=c?se(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 b=this.sanitizePreviewMarks(m.marks)??{},y=this.host.collectOverlappingTextSpans(g,h,m.text.length);f||(f=y.some(k=>["insertion","deletion","suggestionId","formatChange"].some(I=>Object.prototype.hasOwnProperty.call(k.attributes,I)))),p.push({targetAttributes:b,spans:y}),h+=m.text.length}if(!f)return this.host.transact(()=>{An(c,r);for(const{targetAttributes:m,spans:b}of p)for(const y of b){const k=new Set([...Object.keys(y.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=un(y.attributes),re(g,y.start,y.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 An(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:s?this.cloneSuggestionSnapshot(s):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(s=>[s.blockId,...s.producedBlockIds??[]]).filter(s=>!!s));for(;i.length>0;){let s=!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),s=!0;break}}if(!s){t.push(...i);break}}return t}buildAgentSuggestionPlanFromProposal(e,t,n,i,r,s,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=X(n,v);return!A||x.length===0?null:{proposalId:e,category:"block",blockId:v,producedBlockIds:x.map(w=>w.id),apply:()=>{const w=G(this.host.ydoc,v);if(!w)return!1;const E=x.map($=>this.sanitizePreviewBlock($));return this.host.transact(()=>{w.yParent.delete(w.index,1);const $=E.map(B=>this.host.blockToYjsElement(B));w.yParent.insert(w.index,$);for(const B of $)this.setElementStructuralSuggestion(B,"change",void 0,e,"Paragraph");const P=this.normalizeLiveSuggestionRecord({id:e,type:"block-change",blockId:E[0].id,beforeBlock:this.cloneSuggestionSnapshot(A),sequenceBlockIds:E.map(B=>B.id),label:"Paragraph",createdAt:g});this.saveLiveSuggestion(P,$[0]);for(const B of $.slice(1))this.embedLiveSuggestionRecordInTree(P,B)}),!0}}}if(d.blockPreview?.id){const v=X(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"?Me(v)===Me(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,w=typeof v?.content=="string"?v.content:Array.isArray(v?.content)&&typeof v?.content[0]=="string"?v?.content[0]:null;if(!x||!A||!w)return null;const E=Hn(d.toolCallAction),$=(E&&s?X(s,E):null)??ee.fromAgentHtml(w,{existingDocument:n}).children[0];if(!$)return null;const P={...$,id: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?Bl(v,p):null}));if(!f)return null;const{resolvedPreview:m,previewAnchorBlock:b}=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?X(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 y=d.anchors?.[0],k=u[0],I=m[0];if(y?.paragraphId){const v=X(n,y.paragraphId);let x=v?.type==="table"&&s?X(s,v.id):null;v?.type==="table"&&x?.type==="table"&&this.hasSameTableGeometry(v,x)&&!wn(v,x)&&(x={...x,children:x.children.map(($,P)=>({...$,children:$.children.map((B,C)=>({...B,children:v.children[P].children[C].children}))}))});const A=x??b;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"?Me(v)===Me(A)?"Format":"Replace":v.type==="table"?"Table":v.type==="list"?"List":"Change",createdAt:g})};if(v?.type==="paragraph"){const $=k?.fromIndex??k?.toIndex,P=y.previewStartOffset??I?.fromIndex??I?.toIndex;if(y.kind==="delete"){const B=$??P??0,C=y.text?.length??Math.max(0,(k?.toIndex??B)-B),T=Math.max(0,B-C);return{proposalId:e,category:"inline",blockId:v.id,start:T,inlinePriority:2,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:e,blockId:v.id,start:T,deleteLength:C,insertNodes:[],label:"Delete",createdAt:g})}}if(y.kind==="insert"&&(h||A?.type==="paragraph")){const B=P??$??0,C=P??B,T=y.previewStartOffset!==void 0?C+(y.text?.length??0):I?.toIndex??C+(y.text?.length??0),L=y.previewTextNodes?y.previewTextNodes.map(M=>({...M,marks:M.marks?{...M.marks}:void 0})):h?this.buildInlinePreviewTextNodes(h):this.host.extractTextNodesForRange(A,C,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:L,label:"Insert",createdAt:g})}}if(y.kind==="replace"&&(h||A?.type==="paragraph")){const B=P??$??0,C=P??B,T=y.previewStartOffset!==void 0?C+(y.text?.length??0):I?.toIndex??C+(y.text?.length??0),L=y.previewTextNodes?y.previewTextNodes.map(M=>({...M,marks:M.marks?{...M.marks}:void 0})):h?this.buildInlinePreviewTextNodes(h):this.host.extractTextNodesForRange(A,C,T);return y.oldText===y.text?{proposalId:e,category:"inline",blockId:v.id,start:B,inlinePriority:1,apply:()=>this.applyBridgeInlineFormatSuggestion({suggestionId:e,blockId:v.id,start:B,end:B+(y.text?.length??0),targetAttributes:{},targetTextNodes:L,createdAt:g})}:{proposalId:e,category:"inline",blockId:v.id,start:B,inlinePriority:2,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:e,blockId:v.id,start:B,deleteLength:y.oldText?.length??0,insertNodes:L,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||y.oldText===y.text),label:"List",createdAt:g})};const w=v?.type,E=A?.type;if(w==="list-item"&&E==="list-item"){const $=v,P=A,B=qe(n,$.id)?.children.find(C=>C?.type!=="list"?!1:C.children.some(T=>T.id===$.id));if(B?.id){const C=B.children.findIndex(T=>T.id===$.id);if(C!==-1){const T=this.cloneSuggestionSnapshot(B),L=this.cloneSuggestionSnapshot(B);return L.children[C]=this.cloneSuggestionSnapshot(P),{proposalId:e,category:"block",blockId:B.id,apply:()=>{const M=X(this.host.getDocument(),B.id);return this.applyGranularListSuggestionChanges({blockId:B.id,before:T,after:L,suggestionId:e,currentLiveBlock:M?.type==="list"?M: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),s=(I,v)=>{const x=X(I,v);if(!x||x.id===v)return x;if(x.type==="list"){const A=x.children.find(w=>w.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?s(n,x):null;if(!A)return!1;if(x===c)return!0;const w=typeof v?.find=="string"?v.find:"";return w.length>0&&Me(A).includes(w)})??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?s(h,p):null,m=p?s(n,p):null,b=f??m,y=b?b.type:null,k=p?`'${p}'${typeof y=="string"?` (${y})`:""}`:"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.`:b?`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 Mr(e.baseFork,n),r=new Map;for(const{block:P}of Ye(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:C})=>C.getAttribute("id")))}const s=Br(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=s.filter(C=>(i.getSuggestion(C)?.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 C=i.getSuggestion(B[0]),T=P.sourceFrom?S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(P.sourceFrom),e.baseFork):null,L=P.paragraphId?J(e.baseFork,P.paragraphId):null,M=L?se(L):null,O=M?te(M).map(F=>typeof F.insert=="string"?F.insert:"").join(""):"";C&&T&&T.type===M&&O.slice(T.index,T.index+(P.oldText?.length??0))===(P.oldText??"")&&(C.anchors=[{...P,previewStartOffset:T.index}])}}const l=s.length>=100,c=Date.now(),d=P=>{l&&(`${s.length}${P}`,Date.now()-c)};if(d("flattened"),s.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 C=P.arguments&&typeof P.arguments=="object"?P.arguments:null,T=typeof C?.comment=="string"?C.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(C=>{if(!C.from||!C.to||!C.paragraphId)return[];const T=S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(C.from),e.validationFork),L=S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(C.to),e.validationFork);if(!T||!L||T.type!==L.type)return[];const M=C.oldText??"",O=C.text??"";let F=0;for(;F<M.length&&F<O.length&&M[F]===O[F];)F++;let N=0;for(;N<M.length-F&&N<O.length-F&&M[M.length-1-N]===O[O.length-1-N];)N++;const _=M.length>O.length&&F+N===O.length?T.index+F:null;return[{paragraphId:C.paragraphId,start:T.index,end:L.index,deletionPoint:_}]});p.set(P,B)}const h=new Map,f=s.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!==s.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")),b=new Map(s.map((P,B)=>[P,B])),y=f.filter(P=>P.category==="inline").sort((P,B)=>{if(P.blockId&&B.blockId&&P.blockId===B.blockId){const C=(B.start??0)-(P.start??0);if(C!==0)return C;const T=(B.inlinePriority??0)-(P.inlinePriority??0);if(T!==0)return T}return(b.get(P.proposalId)??0)-(b.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??Qe} revision`,agentName:e.agentName??Qe,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]??y[0]??null,this.resetLiveSuggestionsForBlocks(P,g),this.batchYBlockLocationsById=new Map;const B=new Map;for(const T of m){if(!T.blockId)continue;const L=J(this.host.ydoc,T.blockId);L&&B.set(L,T.blockId)}const C=new Map;for(const[T,L]of B){const M=T.parent;if(!(M instanceof S.XmlElement||M instanceof S.XmlFragment))continue;const O=C.get(M)??new Map;O.set(T,L),C.set(M,O)}for(const[T,L]of C)T.toArray().forEach((M,O)=>{if(!(M instanceof S.XmlElement))return;const F=L.get(M);F&&this.batchYBlockLocationsById.set(F,{yBlock:M,yParent:T,index:O})});try{for(const T of m)if(v=T,!T.apply())throw new Error("suggestion application returned false");for(const T of y)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",C=B==="suggestion application returned false"?null:B,T=v?this.describeAgentSuggestionApplyFailure(v,i,g,e.originalActions):null;return{success:!1,error:T?`${T}${C?` Detail: ${C}`:""}`:C??"Could not apply the requested edit."}}this.host.relinkCommentSuggestionIds();const x=u.length?this.host.getSuggestionCommentRanges(k):[],A=[],w=[];let E=0;for(const[P,B]of p){const C=x.flatMap(O=>B.flatMap(F=>{if(O.structural){if(F.paragraphId!==O.blockId)return[];const N=Math.max(O.projectedStart,F.start),_=Math.min(O.projectedEnd,F.end);return _<N||_===N&&F.start!==F.end?[]:[{...O,start:O.start+N-O.projectedStart,end:O.start+_-O.projectedStart}]}return(()=>{if(F.paragraphId!==O.blockId)return!1;const N=O.projectedStart,_=O.projectedEnd;return N===_&&F.start===F.end?N===F.start:N===_?F.deletionPoint===N||F.start<N&&N<F.end:F.start===F.end?N<F.start&&F.start<_:N<F.end&&F.start<_})()?[O]:[]})),T=Array.from(new Set(C.map(O=>O.suggestionId)));if(T.length===0){E++;for(const O of k)A.includes(O)||A.push(O);continue}for(const O of T)A.includes(O)||A.push(O);const L={author:e.agentName??Qe,authorType:"ai",agentName:e.agentName??Qe,agentModel:e.agentModel,suggestionId:T[0],...T.length>1?{relatedSuggestionIds:T}:{}},M=C.every(O=>O.structural&&O.start===O.end)?this.host.addBlockComment(C[0].blockId,P.comment,L):this.host.addCommentToRanges(C.map(({blockId:O,start:F,end:N})=>({blockId:O,start:F,end:N})),P.comment,L);M?w.push(M):E++}const $=il(e.agentFeedback,e.originalActions,s,e.docBeforeToolCall,e.docAfterToolCall);return{success:k.length>0,planningSuggestionIds:s,suggestionIds:k,commentedSuggestionIds:A,attachedCommentIds:w,commentAttachmentFailureCount:E,agentFeedback:k.length>0?$: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)}),$l(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,s]of e.liveSuggestions)i.set(r,this.cloneSuggestionSnapshot(s))}),this.host.cachedDoc=this.cloneSuggestionSnapshot(e.doc),Nn(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=X(n,a);l&&this.collectSuggestionIdsFromBlockValue(l,i);const c=X(e.baseDoc,a),d=X(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 s=r.length===1?`block ${r[0]}`:`${r.length} blocks`;return{success:!0,planningSuggestionIds:[],suggestionIds:[],agentFeedback:`Rejected pending suggestion changes for ${s}.`}}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 Mr(this.host.cloneYDoc(this.host.ydoc));return this.rebuildDetachedSuggestionsFromSnapshotWithStore(e,t)}rebuildDetachedSuggestionsFromSnapshotWithStore(e,t){const n=Ci(e);return Br(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),xr.clearAllStoredSuggestions(this.host.documentId)}migrateLegacyDetachedSuggestionsToLiveSuggestions(e){const t=this.host.cloneYDoc(this.host.ydoc),n=new Mr(t);if(this.hasSerializedDetachedSuggestions(e.serverDetachedSuggestions)){const d=this.host.cloneYDoc(this.host.ydoc),g=new xr(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),s=i.map(d=>this.buildAgentSuggestionPlanFromProposal(d,n,r,t,e.legacyCreatedAt)).filter(d=>!!d);if(s.length!==i.length)return{success:!1,migratedSuggestionCount:0,error:"Could not translate one or more legacy proposals into live suggestions."};const a=this.sortBlockSuggestionPlansByDependency(s.filter(d=>d.category==="block")),l=s.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:Qe,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 uu{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 s=n.yContext.yBlock.get(r);s instanceof S.XmlElement&&s.nodeName==="list-item"&&i.push(s)}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=X(i,e);if(!r||r.type!=="paragraph")return!1;const s=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,b;for(let x=0;x<c.length;x++){const A=c.get(x);if(A instanceof S.XmlText){b=A;break}}if(b&&b.length>0){const x=te(b);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 y=[],k=[],I=(x,A)=>{k.push({ops:x,plain:A})};if(b&&b.length>0){const x=te(b);let A=[],w="";const E=()=>{I(A,w),A=[],w=""};x.forEach($=>{if(typeof $.insert=="string"){let P=$.insert;for(;P.length>0;){const B=P.indexOf(`
|
|
29
|
-
`);if(B===-1)P.length>0&&(A.push({insert:P,attributes:$.attributes&&Object.keys($.attributes).length>0?{...$.attributes}:void 0}),w+=P),P="";else{const C=P.slice(0,B);C.length>0&&(A.push({insert:C,attributes:$.attributes&&Object.keys($.attributes).length>0?{...$.attributes}:void 0}),w+=C),E(),P=P.slice(B+1)}}}else if($.insert!==void 0&&$.insert!==null){let P=null;if(typeof $.insert=="string")P=$.insert;else try{P=JSON.stringify($.insert)}catch{P=String($.insert)}P&&P.length>0&&(A.push({insert:P,attributes:$.attributes&&Object.keys($.attributes).length>0?{...$.attributes}:void 0}),w+=P)}}),E()}else k.push({ops:[],plain:""});k.length===0&&k.push({ops:[],plain:""});const v=Q(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 w=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 E=[...x.ops].reverse().find(P=>P.insert.length>0)?.attributes,$={...ct(E)??{}};$.fontFamily||($.fontFamily=m||Le),A.setAttribute("_emptyTextMarks",JSON.stringify($))}else{let E=0;x.ops.forEach(({insert:$,attributes:P})=>{if($.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||Le),w.insert(E,$,B),E+=$.length})}A.insert(0,[w]),y.push(A)}),h.insert(0,y),d.delete(g,1),d.insert(g,[h]),this.host.suggestingMode&&a&&s&&this.host.suggestionEngine.saveLiveSuggestion({id:a,type:"block-change",blockId:e,beforeBlock:s,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 s=i.get(r);!(s instanceof S.XmlElement)||s.nodeName!=="list-item"||(t===null?q(s,"direction"):s.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 s=e;s<=t;s++){const a=i.children[s];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 s=this.host.getYContentFragment(),a=s.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 b of m.children)if(b.type==="text"&&b.marks?.fontFamily){u=b.marks.fontFamily;break}if(u)break}if(u)break}let p=!1;const h=(f,m)=>{const b=new S.XmlElement("list-item");b.setAttribute("id",Y()),n==="todo"&&b.setAttribute("checked",String(m?.checked??!1)),(m?.direction==="rtl"||m?.direction==="ltr")&&b.setAttribute("direction",m.direction);const y=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."),y.insert(0,k,{fontFamily:v||Le})}const I=m?.indentLevel;typeof I=="number"&&I>0&&b.setAttribute("indentLevel",String(I)),b.insert(0,[y]),g.push(b),p=!0};r.forEach(f=>{if(f.type==="paragraph"){const m=f.node.children.filter(y=>y.type==="text").map(y=>y.text).join("");let b;for(const y of f.node.children)if(y.type==="text"&&y.marks?.fontFamily){b=y.marks.fontFamily;break}(m.length>0?m.split(`
|
|
30
|
-
`):[""]).forEach(y=>{h(y,{fontFamily:b,direction:f.node.direction})})}else{const m=f.node;m.children.forEach(b=>{const y=this.getListItemPlainText(b),k=m.variant==="todo"?b.checked??!1:void 0;let I;for(const v of b.children)if(v.type==="text"&&v.marks?.fontFamily){I=v.marks.fontFamily;break}h(y,{checked:k,indentLevel:b.indentLevel,fontFamily:I,direction:b.direction})})}}),p||h(""),c.insert(0,g),s.delete(e,t-e+1),s.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 b=h.get(m);if(b instanceof S.XmlText){f=b;break}}f?c.push({delta:te(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(),s=r.children[e]?.id?this.host.cursorAtBlock(e,0,r):null;return s&&(this.host.setSelectionAfterOperation({anchor:s,focus:s}),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,s=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(s),u=n??a??d??g??1;l.setAttribute("startNumber",String(u)),this.host.listStartNumberCache.set(s,u)}else a!==void 0&&this.host.listStartNumberCache.set(s,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=X(t,e);if(!n||n.type!=="list")return!1;const i=n,r=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(i):null,s=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 b=null;for(let k=0;k<m.length;k++){const I=m.get(k);if(I instanceof S.XmlText){b=I;break}}const y=m.getAttribute("direction");p.push({delta:b?te(b):[],...y==="rtl"||y==="ltr"?{direction:y}:{}})}}p.length===0&&p.push({delta:[]});const h=p.map((f,m)=>{const b=new S.XmlElement("paragraph");b.setAttribute("id",m===0?l.getAttribute("id")||Y():Y()),f.direction&&b.setAttribute("direction",f.direction),s&&this.host.suggestionEngine.setParagraphStructuralSuggestion(b,"change",void 0,s,"Paragraph");const y=new S.XmlText;let k=0;return f.delta.forEach(I=>{typeof I.insert=="string"&&(I.attributes&&Object.keys(I.attributes).length>0?y.insert(k,I.insert,I.attributes):y.insert(k,I.insert),k+=I.insert.length)}),b.insert(0,[y]),b});if(c.delete(d,1),c.insert(d,h),this.host.suggestingMode&&s&&r){const f=h.map(b=>b.getAttribute("id")),m={id:s,type:"block-change",blockId:f[0],beforeBlock:r,...f.length>1?{sequenceBlockIds:f}:{},label:"Paragraph"};this.host.suggestionEngine.saveLiveSuggestion(m,h[0]);for(const b of h.slice(1))this.host.suggestionEngine.embedLiveSuggestionRecordInTree(this.host.suggestionEngine.getLiveSuggestion(s)??m,b)}});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=X(i,e);if(!r||r.type!=="list")return!1;const s=r,a=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(s):null,l=s.id||e,c=s.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=X(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 s=i.findIndex(g=>g.id===e);let a;for(let g=s-1;g>=0;g--)if(i[g].variant==="ordered"){a=i[g];break}if(s<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=X(i,e);if(!r||r.type!=="list"||r.variant!=="ordered"||!Number.isFinite(t)||t<1)return null;const s=r,a=Math.max(0,Math.min(Math.floor(n),s.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(s.id,l),s.id;const p=Y();return this.host.transact(()=>{const h=new S.XmlElement("list");h.setAttribute("id",p),h.setAttribute("variant",s.variant);const f=s.numberingChainId;f&&h.setAttribute("numberingChainId",f),s.numberingFormat&&h.setAttribute("numberingFormat",s.numberingFormat),h.setAttribute("startNumber",String(l)),s.lineSpacing!==void 0&&h.setAttribute("lineSpacing",String(s.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 s=new S.XmlElement("list-item");s.setAttribute("id",r.getAttribute("id")||Y());const a=r.getAttribute("checked");a!==void 0&&s.setAttribute("checked",a);const l=r.getAttribute("indentLevel");l!==void 0&&s.setAttribute("indentLevel",l);const c=Q(r,"direction");c!==void 0&&s.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=te(d);let p=0;u.forEach(h=>{typeof h.insert=="string"&&(g.insert(p,h.insert,h.attributes||{}),p+=h.insert.length)})}s.insert(0,[g]),n.push(s)}return n}splitListItem(e,t){this.host.beforeOperationSelection=t;const n=this.host.getDocument(),i=X(n,e.block);if(!i||i.type!=="list")return null;const r=i,s=st(e,this.host.ydoc,n);if(!s)return null;const a=S.createAbsolutePositionFromRelativePosition(s.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:b,index:y}=f;if(!(m instanceof S.XmlElement))return;const k=[];for(let F=0;F<m.length;F++){const N=m.get(F);N instanceof S.XmlElement&&N.nodeName==="list-item"&&k.push(N)}let I=-1;for(let F=0;F<k.length;F++){const N=k[F];for(let _=0;_<N.length;_++){const R=N.get(_);if(R instanceof S.XmlText&&R===l){I=F;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(F=>F.type==="text"?F.text:"").join(""),w=this.host.suggestingMode&&c<A.length&&(()=>{let F=0,N=!1;for(const _ of x.children){if(_.type!=="text")continue;const R=F+_.text.length;if(R>c&&_.text.length>0&&(N=!0,!_.marks?.deletion))return!1;F=R}return N})();if(A.trim().length===0&&r.children.length===1){const F=new S.XmlElement("paragraph");u=Y(),F.setAttribute("id",u),(x.direction==="rtl"||x.direction==="ltr")&&F.setAttribute("direction",x.direction),h=!1;let N;for(const R of x.children)if(R.type==="text"&&R.marks?.fontFamily){N=R.marks.fontFamily;break}N||(N=this.host.resolveFontFamilyForList(r)),N&&F.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:N}));const _=new S.XmlText;F.insert(0,[_]),b.delete(y,1),b.insert(y,[F]);return}if(A.trim().length===0&&r.children.length>1){const F=I===r.children.length-1,N=I===0;if(N||F){m.delete(I,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 U of x.children)if(U.type==="text"&&U.marks?.fontFamily){R=U.marks.fontFamily;break}R||(R=this.host.resolveFontFamilyForList(r)),R&&_.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:R}));const D=new S.XmlText;_.insert(0,[D]),N?b.insert(y,[_]):b.insert(y+1,[_])}else{const _=r.children.length-I-1,R=new S.XmlElement("list");if(R.setAttribute("id",Y()),R.setAttribute("variant",r.variant),r.variant==="ordered"){const K=r.numberingChainId??Y();r.numberingChainId||m.setAttribute("numberingChainId",K),R.setAttribute("numberingChainId",K),r.numberingFormat&&R.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 U;for(const K of x.children)if(K.type==="text"&&K.marks?.fontFamily){U=K.marks.fontFamily;break}U||(U=this.host.resolveFontFamilyForList(r)),U&&D.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:U}));const j=new S.XmlText;D.insert(0,[j]);const z=[];for(let K=I+1;K<k.length;K++){const ae=k[K],xe=new S.XmlElement("list-item");xe.setAttribute("id",ae.getAttribute("id")||Y());const Xe=ae.getAttribute("checked");Xe!==void 0&&xe.setAttribute("checked",Xe);const Oe=ae.getAttribute("indentLevel");Oe!==void 0&&xe.setAttribute("indentLevel",Oe);const W=Q(ae,"direction");W!==void 0&&xe.setAttribute("direction",W);let Z=null;for(let V=0;V<ae.length;V++){const de=ae.get(V);if(de instanceof S.XmlText){Z=de;break}}const oe=new S.XmlText;if(Z&&Z.length>0){const V=te(Z);let de=0;V.forEach(be=>{if(typeof be.insert=="string"){const Ne=be.attributes||{};oe.insert(de,be.insert,Ne),de+=be.insert.length}})}xe.insert(0,[oe]),z.push(xe)}R.insert(0,z),m.delete(I,_+1),b.insert(y+1,[D,R])}return}if(c===0){const F=new S.XmlElement("list-item"),N=Y();F.setAttribute("id",N),u=N,r.variant==="todo"&&F.setAttribute("checked","false");const _=x.indentLevel??0;_>0&&F.setAttribute("indentLevel",String(_)),(x.direction==="rtl"||x.direction==="ltr")&&F.setAttribute("direction",x.direction);let R;for(const U of x.children)if(U.type==="text"&&U.marks?.fontFamily){R=U.marks.fontFamily;break}R||(R=this.host.resolveFontFamilyForList(r));const D=new S.XmlText;F.insert(0,[D]),R?F.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:R})):F.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:Le})),g&&(this.host.suggestionEngine.clearElementStructuralSuggestion(F),this.host.suggestionEngine.setElementStructuralSuggestion(F,"insert",void 0,g,"Insert")),m.insert(I,[F]),u=x.id??null,p=I+1;return}if(c>=A.length||w){const F=new S.XmlElement("list-item");u=Y(),F.setAttribute("id",u),p=I+1,r.variant==="todo"&&F.setAttribute("checked","false");const N=x.indentLevel??0;N>0&&F.setAttribute("indentLevel",String(N)),(x.direction==="rtl"||x.direction==="ltr")&&F.setAttribute("direction",x.direction);let _=this.host.getFontAtOffsetInListItem(x,c);_||(_=this.host.resolveFontFamilyForList(r));const R=new S.XmlText;F.insert(0,[R]),_?F.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:_})):F.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:Le})),g&&(this.host.suggestionEngine.clearElementStructuralSuggestion(F),this.host.suggestionEngine.setElementStructuralSuggestion(F,"insert",void 0,g,"Insert")),m.insert(I+1,[F]);return}let E=null;for(let F=0;F<v.length;F++){const N=v.get(F);if(N instanceof S.XmlText){E=N;break}}if(!E)return;const $=te(E);let P=0;const B=[];for(const F of $)if(F.insert&&typeof F.insert=="string"){const N=F.insert.length;if(P+N<=c)P+=N;else if(P>=c)B.push(F);else{const _=c-P,R=F.insert.slice(_);R&&B.push({insert:R,...F.attributes&&{attributes:F.attributes}}),P=c}}c<E.length&&E.delete(c,E.length-c);const C=new S.XmlElement("list-item");u=Y(),C.setAttribute("id",u),p=I+1,r.variant==="todo"&&C.setAttribute("checked","false");const T=x.indentLevel??0;T>0&&C.setAttribute("indentLevel",String(T)),(x.direction==="rtl"||x.direction==="ltr")&&C.setAttribute("direction",x.direction);const L=this.host.getFontAtOffsetInListItem(x,c),M=new S.XmlText;let O=0;if(B.length>0){for(const F of B)if(F.insert&&typeof F.insert=="string"){const N=F.attributes&&Object.keys(F.attributes).length>0?{...F.attributes}:{};N.fontFamily||(L||console.warn("[DocumentMutator] splitListItem: No font found for new list item, defaulting to Arial. This may indicate a bug."),N.fontFamily=L||Le),M.insert(O,F.insert,N),O+=F.insert.length}}else{const F=L||this.host.resolveFontFamilyForList(r)||Le;C.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:F}))}g&&(this.host.suggestionEngine.clearElementStructuralSuggestion(v),this.host.suggestionEngine.clearElementStructuralSuggestion(C),this.host.suggestionEngine.setElementStructuralSuggestion(v,"split","before",g,"Split"),this.host.suggestionEngine.setElementStructuralSuggestion(C,"split","after",g,"Split")),C.insert(0,[M]),m.insert(I+1,[C])}),h){const f=this.host.getDocument(),m=X(f,r.id);if(!m||m.type!=="list"||p===null)return null;const b=m;let y=0;for(let v=0;v<p;v++){const x=b.children[v];for(const A of x.children)A.type==="text"&&(y+=A.text.length);v<p-1&&(y+=1)}p>0&&(y+=1);const k={block:b.id,offset:y},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:s}=r,a=st(e,this.host.ydoc,s);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&&Se(r.doc,i.anchor,i.focus)!==0){const A=st(i.anchor,this.host.ydoc,r.doc),w=st(i.focus,this.host.ydoc,r.doc),E=A?S.createAbsolutePositionFromRelativePosition(A.textOffset,this.host.ydoc):null,$=w?S.createAbsolutePositionFromRelativePosition(w.textOffset,this.host.ydoc):null;E?.type instanceof S.XmlText&&$?.type instanceof S.XmlText&&E.type===$.type&&E.type===c&&(g={yText:c,startOffset:Math.min(E.index,$.index),endOffset:Math.max(E.index,$.index)})}const u={},p=[],h=po(s,e),f=Fi(s,e),m=Ei(s,e),b=this.host.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(s,e.block),y=b?null:this.host.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(s,e),k=y?.marks?.suggestionId??null,I=this.host.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(s,e,i);{const A=!b&&this.host.suggestingMode&&t.length>0,w=mr({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,y?.marks??h?.marks):void 0});Object.assign(u,w.marksToApply),p.push(...w.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&&!b){const w=this.host.suggestionEngine.applySuggestedDeletionToTextRange(g.yText,g.startOffset,A,I??void 0);v=g.startOffset+w.retainedLength}else g.yText.delete(g.startOffset,A),v=g.startOffset}ta(c,v,t,{marksToApply:u,marksToRemove:p}),!b&&this.host.suggestingMode&&t.length>0&&this.host.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(c,v,t.length)});const x=S.createRelativePositionFromTypeIndex(c,v+t.length);return si({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 s={anchor:r,focus:r};return this.host.setSelectionAfterOperation(s),this.host.afterOperationRelativeSelection=H(s,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 s=this.insertTextInListItem(e,t,n,i);if(s){const a={anchor:s,focus:s};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 s=st(e,this.host.ydoc,r.doc);if(!s)return!1;const a=S.createAbsolutePositionFromRelativePosition(s.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,s,a){if(i!==n+1||!this.isCursorAtEndOfList(e,r)||!this.isCursorAtStartOfList(t,s))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 b=f.getAttribute("checked");e.variant==="todo"&&m.setAttribute("checked",b??"false");const y=f.getAttribute("indentLevel");y!==void 0&&m.setAttribute("indentLevel",y);const k=Q(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=te(x);let w=0;A.forEach(E=>{typeof E.insert=="string"&&(I.insert(w,E.insert,E.attributes||{}),w+=E.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(s=>s.type==="text").reduce((s,a)=>s+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 s=e.children[r],a=this.getListItemTextLength(s),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 s=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 b=a.children[m].indentLevel??0;if(b<=l)break;if(d>0&&b+d>2)return!1;const y=Math.max(0,Math.min(2,b+d));g.push({index:m,newIndent:y})}this.host.beforeOperationSelection=i;const h=Ge().getHandlerForBlock(e);this.host.beforeOperationRelativeSelection=h?.allowsInternalCursor()?H(i,this.host.ydoc,s):null;const f=J(this.host.ydoc,e.id??"");return!f||!(f instanceof S.XmlElement)?!1:(this.host.transact(()=>{const m=[];for(let y=0;y<f.length;y++){const k=f.get(y);k instanceof S.XmlElement&&k.nodeName==="list-item"&&m.push(k)}const b=m[t];b&&(c>0?b.setAttribute("indentLevel",String(c)):b.removeAttribute("indentLevel"),p&&(this.host.suggestionEngine.clearElementStructuralSuggestion(b),this.host.suggestionEngine.setElementStructuralSuggestion(b,"change",void 0,p,d>0?"Indent":"Outdent")),g.forEach(({index:y,newIndent:k})=>{const I=m[y];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 hu(o,e){const t=te(o).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?[]:Oi(t,n).diffs)l===-1?o.delete(i,c.length):(l===1&&ne(o,i,c),i+=c.length);const r=te(o);let s=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(;s<e.length&&a===e[s].text.length;)s++,a=0;const d=e[s],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&&re(o,i,g,h),i+=g,a+=g,c-=g}}}function Or(o,e){const t=o.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 s=0,a=0;for(const c of Ir(n,i)){for(;n[s]!==c;)s++;for(;i[a]!==c;)a++;r.set(a++,t[s++])}const l=new Set(r.values());An(o,e);for(let c=o.length-1;c>=0;c--){const d=o.get(c);(!(d instanceof S.XmlElement)||!l.has(d))&&o.delete(c,1)}e.children.forEach((c,d)=>{const g=r.get(d);if(!g){o.insert(d,[ke(c)]);return}An(g,c);const u=g.toArray().find(h=>h instanceof S.XmlText);u&&hu(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);Q(g,"_emptyTextMarks")!==h&&g.setAttribute("_emptyTextMarks",h)}else q(g,"_emptyTextMarks")})}const fu=300;function pu(o){return Array.from(o).slice(0,fu).join("")}function mu(o){return o.children.every(e=>e.type==="paragraph"&&e.children.every(t=>t.type==="text"&&t.text.trim().length===0))}class Rr 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 li{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 Aa(o){return o.replace(/\s+id="[^"]*"/g,"")}function wa(o){const e=Aa(o),t=e.match(/^<p\b([^>]*)>([\s\S]*)<\/p>$/i);return t?t[1].trim().length>0?e:t[2]:e}function Ta(o){return ee.toInternalHtml({type:"doc",children:[o]})}function bu(o,e,t,n){if(!o.actions)return o;const i=o.actions.map((c,d)=>{const g=b=>{throw new Rr(d,c,new Error(b))};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||!mu(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=$e(c);return m&&Ie(f,m),f}),r=t||new li;`${o.actions.length}${e}${r.getCurrentTurnId()}`;const s=[],a=n?ee.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?X(n,u):null,h=p?.type==="list"?p.children.find(f=>f.id===u):void 0;return ee.fromAgentHtml(c,{existingDocument:n,parsingContext:a,preserveImageReferenceIds:!0,listItemBaseIndent:h?h.indentLevel??0:void 0})}catch(u){throw new Rr(g,d,u)}};for(const[c,d]of i.entries()){const g=$e(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 b=ee.coalesceAdjacentBareListFragments(Array.isArray(h)?h:[h]),y=[];for(const k of b){const I=l(k,d,c);if(I.children.length!==0)if(I.children.length===1){const v=Y();Ie(d,{stableId:v});const x=I.children[0];let A;x.type==="list"||x.type==="table"||x.type==="page-break"||x.type,A=Aa(ee.toInternalHtml(I)),y.push({content:A,id:v})}else for(let v=0;v<I.children.length;v++){const x=I.children[v],A=Ta(x);let w;x.type==="list"||x.type==="table"||x.type==="page-break"||x.type==="toc"?w=A:w=wa(A);const E=Y();y.push({content:w,id:E})}}for(let k=0;k<y.length;k++){const{content:I,id:v}=y[k],x={name:"insert_block",arguments:{}};k===0?(x.arguments.referenceId=f,x.arguments.position=m,Ie(x,{stableId:y[k].id})):(x.arguments.referenceId=y[k-1].id,x.arguments.position="after"),x.arguments.content=[I],Ie(x,{...g,stableId:v}),s.push(x)}if(p==="after"&&y.length>0){const k=y[y.length-1].id;r.updateChain(u,k)}}else if(d.name==="replace_block"){const{id:u,content:p,count:h}=d.arguments,f=ee.coalesceAdjacentBareListFragments(Array.isArray(p)?p:[p]),m=[];for(const b of f){const y=l(b,d,c);if(y.children.length===0)m.push({content:b,id:u,type:"paragraph"});else for(const k of y.children){const I=Ta(k),v=m.length===0?u:Y();m.push({content:I,id:v,type:k.type})}}if(m.length<=1){const b={...d,arguments:{...d.arguments,content:m.length>0?[m[0].content]:f}};g&&Ie(b,g),s.push(b)}else{const b={name:"replace_block",arguments:{id:u,...typeof h=="number"?{count:h}:{},content:[m[0].content]}};Ie(b,{...g,allowNoopContinuation:!0,splitReplacementGroup:m[0].id,multiBlockReplace:{replacementBlockIds:m.map(y=>y.id),replacedCount:typeof h=="number"?h:1}}),s.push(b);for(let y=1;y<m.length;y++){const{content:k,id:I,type:v}=m[y];let x;v==="list"||v==="table"||v==="code"||v==="page-break"||v==="toc"?x=k:x=wa(k);const A={name:"insert_block",arguments:{referenceId:y===1?u:m[y-1].id,position:"after",content:[x]}};Ie(A,{...g,stableId:I,splitReplacementGroup:m[0].id}),s.push(A)}m.length>1&&r.updateChain(u,m[m.length-1].id)}}else s.push(d)}return{...o,actions:s}}const yu=Math.floor,ku=(o,e)=>o<e?o:e,Su=(o,e)=>o>e?o:e,Ca=128,ci=127,Iu=Number.MAX_SAFE_INTEGER,vu=o=>{const e=unescape(encodeURIComponent(o)),t=e.length,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e.codePointAt(i);return n},rn=typeof TextEncoder<"u"?new TextEncoder:null,xu=o=>rn.encode(o),Au=rn?xu:vu;let on=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});on&&on.decode(new Uint8Array).length===1&&(on=null);const di=(o,e)=>{const t=o.cbuf.length;o.cpos===t&&(o.bufs.push(o.cbuf),o.cbuf=new Uint8Array(t*2),o.cpos=0),o.cbuf[o.cpos++]=e},gi=(o,e)=>{for(;e>ci;)di(o,Ca|ci&e),e=yu(e/128);di(o,ci&e)},Dr=new Uint8Array(3e4),wu=Dr.length/3,Tu=(o,e)=>{if(e.length<wu){const t=rn.encodeInto(e,Dr).written||0;gi(o,t);for(let n=0;n<t;n++)di(o,Dr[n])}else $u(o,Au(e))},Cu=(o,e)=>{const t=unescape(encodeURIComponent(e)),n=t.length;gi(o,n);for(let i=0;i<n;i++)di(o,t.codePointAt(i))},Pu=rn&&rn.encodeInto?Tu:Cu,Bu=(o,e)=>{const t=o.cbuf.length,n=o.cpos,i=ku(t-n,e.length),r=e.length-i;o.cbuf.set(e.subarray(0,i),n),o.cpos+=i,r>0&&(o.bufs.push(o.cbuf),o.cbuf=new Uint8Array(Su(t*2,r)),o.cbuf.set(e.subarray(i)),o.cpos=r)},$u=(o,e)=>{gi(o,e.byteLength),Bu(o,e)},Pa=o=>new Error(o),Fu=Pa("Unexpected end of array"),Eu=Pa("Integer out of Range"),Lu=(o,e)=>{const t=new Uint8Array(o.arr.buffer,o.pos+o.arr.byteOffset,e);return o.pos+=e,t},Mu=o=>Lu(o,_r(o)),Ba=o=>o.arr[o.pos++],_r=o=>{let e=0,t=1;const n=o.arr.length;for(;o.pos<n;){const i=o.arr[o.pos++];if(e=e+(i&ci)*t,t*=128,i<Ca)return e;if(e>Iu)throw Eu}throw Fu},Nu=o=>{let e=_r(o);if(e===0)return"";{let t=String.fromCodePoint(Ba(o));if(--e<100)for(;e--;)t+=String.fromCodePoint(Ba(o));else for(;e>0;){const n=e<1e4?e:1e4,i=o.arr.subarray(o.pos,o.pos+n);o.pos+=n,t+=String.fromCodePoint.apply(null,i),e-=n}return decodeURIComponent(escape(t))}},Ou=o=>on.decode(Mu(o)),$a=on?Ou:Nu;var sn;(function(o){o[o.Token=0]="Token",o[o.PermissionDenied=1]="PermissionDenied",o[o.Authenticated=2]="Authenticated"})(sn||(sn={}));const Ru=(o,e)=>{gi(o,sn.Token),Pu(o,e)},Du=(o,e,t)=>{switch(_r(o)){case sn.PermissionDenied:{e($a(o));break}case sn.Authenticated:{t($a(o));break}}},Fa=o=>Array.from(o.entries()).map(([e,t])=>({clientId:e,...t}));var jr;(function(o){o[o.Connecting=0]="Connecting",o[o.Open=1]="Open",o[o.Closing=2]="Closing",o[o.Closed=3]="Closed"})(jr||(jr={}));function _u(o){return o||(o={}),{delay:o.delay===void 0?200:o.delay,initialDelay:o.initialDelay===void 0?0:o.initialDelay,minDelay:o.minDelay===void 0?0:o.minDelay,maxDelay:o.maxDelay===void 0?0:o.maxDelay,factor:o.factor===void 0?0:o.factor,maxAttempts:o.maxAttempts===void 0?3:o.maxAttempts,timeout:o.timeout===void 0?0:o.timeout,jitter:o.jitter===!0,initialJitter:o.initialJitter===!0,handleError:o.handleError===void 0?null:o.handleError,handleTimeout:o.handleTimeout===void 0?null:o.handleTimeout,beforeAttempt:o.beforeAttempt===void 0?null:o.beforeAttempt,calculateDelay:o.calculateDelay===void 0?null:o.calculateDelay}}async function Xr(o){return new Promise(e=>setTimeout(e,o))}function ju(o,e){let t=e.delay;if(t===0)return 0;if(e.factor&&(t*=Math.pow(e.factor,o.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 Xu(o,e){const t=_u(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||ju;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 Xr(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);o(n,t).then(g=>{clearTimeout(d),l(g)}).catch(g=>{clearTimeout(d),a(g).then(l).catch(c)})}):o(n,t).catch(a)}const s=t.calculateDelay?t.calculateDelay(n,t):t.initialDelay;if(s&&await Xr(s),n.attemptNum<1&&t.initialJitter){const a=i(n,t);a&&await Xr(a)}return r()}const Ea=Math.floor,Uu=(o,e)=>o<e?o:e,Hu=(o,e)=>o>e?o:e,zu=64,ui=128,Wu=63,an=127,La=Number.MAX_SAFE_INTEGER,Yu=()=>new Set,qu=Array.from,Ju=o=>{const e=unescape(encodeURIComponent(o)),t=e.length,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e.codePointAt(i);return n},ln=typeof TextEncoder<"u"?new TextEncoder:null,Ku=o=>ln.encode(o),Vu=ln?Ku:Ju;let cn=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});cn&&cn.decode(new Uint8Array).length===1&&(cn=null);class Gu{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Ur=()=>new Gu,Ma=o=>{let e=o.cpos;for(let t=0;t<o.bufs.length;t++)e+=o.bufs[t].length;return e},Hr=o=>{const e=new Uint8Array(Ma(o));let t=0;for(let n=0;n<o.bufs.length;n++){const i=o.bufs[n];e.set(i,t),t+=i.length}return e.set(new Uint8Array(o.cbuf.buffer,0,o.cpos),t),e},hi=(o,e)=>{const t=o.cbuf.length;o.cpos===t&&(o.bufs.push(o.cbuf),o.cbuf=new Uint8Array(t*2),o.cpos=0),o.cbuf[o.cpos++]=e},Ce=(o,e)=>{for(;e>an;)hi(o,ui|an&e),e=Ea(e/128);hi(o,an&e)},zr=new Uint8Array(3e4),Zu=zr.length/3,Qu=(o,e)=>{if(e.length<Zu){const t=ln.encodeInto(e,zr).written||0;Ce(o,t);for(let n=0;n<t;n++)hi(o,zr[n])}else _t(o,Vu(e))},eh=(o,e)=>{const t=unescape(encodeURIComponent(e)),n=t.length;Ce(o,n);for(let i=0;i<n;i++)hi(o,t.codePointAt(i))},Je=ln&&ln.encodeInto?Qu:eh,th=(o,e)=>{const t=o.cbuf.length,n=o.cpos,i=Uu(t-n,e.length),r=e.length-i;o.cbuf.set(e.subarray(0,i),n),o.cpos+=i,r>0&&(o.bufs.push(o.cbuf),o.cbuf=new Uint8Array(Hu(t*2,r)),o.cbuf.set(e.subarray(i)),o.cpos=r)},_t=(o,e)=>{Ce(o,e.byteLength),th(o,e)},Na=o=>new Error(o),Oa=Na("Unexpected end of array"),Ra=Na("Integer out of Range");class nh{constructor(e){this.arr=e,this.pos=0}}const Da=o=>new nh(o),ih=(o,e)=>{const t=new Uint8Array(o.arr.buffer,o.pos+o.arr.byteOffset,e);return o.pos+=e,t},fi=o=>ih(o,xt(o)),_a=o=>o.arr[o.pos++],xt=o=>{let e=0,t=1;const n=o.arr.length;for(;o.pos<n;){const i=o.arr[o.pos++];if(e=e+(i&an)*t,t*=128,i<ui)return e;if(e>La)throw Ra}throw Oa},rh=o=>{let e=o.arr[o.pos++],t=e&Wu,n=64;const i=(e&zu)>0?-1:1;if((e&ui)===0)return i*t;const r=o.arr.length;for(;o.pos<r;){if(e=o.arr[o.pos++],t=t+(e&an)*n,n*=128,e<ui)return i*t;if(t>La)throw Ra}throw Oa},oh=o=>{let e=xt(o);if(e===0)return"";{let t=String.fromCodePoint(_a(o));if(--e<100)for(;e--;)t+=String.fromCodePoint(_a(o));else for(;e>0;){const n=e<1e4?e:1e4,i=o.arr.subarray(o.pos,o.pos+n);o.pos+=n,t+=String.fromCodePoint.apply(null,i),e-=n}return decodeURIComponent(escape(t))}},sh=o=>cn.decode(fi(o)),dn=cn?sh:oh,ah=o=>{const e=o.pos,t=dn(o);return o.pos=e,t},jt=Date.now,Wr=()=>new Map,lh=(o,e,t)=>{let n=o.get(e);return n===void 0&&o.set(e,n=t()),n};class ch{constructor(){this._observers=Wr()}on(e,t){lh(this._observers,e,Yu).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 qu((this._observers.get(e)||Wr()).values()).forEach(n=>n(...t))}destroy(){this._observers=Wr()}}const dh=Object.keys,ja=o=>dh(o).length,gh=(o,e)=>Object.prototype.hasOwnProperty.call(o,e),uh=(o,e)=>o===e,gn=(o,e)=>{if(o==null||e==null)return uh(o,e);if(o.constructor!==e.constructor)return!1;if(o===e)return!0;switch(o.constructor){case ArrayBuffer:o=new Uint8Array(o),e=new Uint8Array(e);case Uint8Array:{if(o.byteLength!==e.byteLength)return!1;for(let t=0;t<o.length;t++)if(o[t]!==e[t])return!1;break}case Set:{if(o.size!==e.size)return!1;for(const t of o)if(!e.has(t))return!1;break}case Map:{if(o.size!==e.size)return!1;for(const t of o.keys())if(!e.has(t)||!gn(o.get(t),e.get(t)))return!1;break}case Object:if(ja(o)!==ja(e))return!1;for(const t in o)if(!gh(o,t)||!gn(o[t],e[t]))return!1;break;case Array:if(o.length!==e.length)return!1;for(let t=0;t<o.length;t++)if(!gn(o[t],e[t]))return!1;break;default:return!1}return!0},Yr=3e4;class hh extends ch{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const t=jt();this.getLocalState()!==null&&Yr/2<=t-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const n=[];this.meta.forEach((i,r)=>{r!==this.clientID&&Yr<=t-i.lastUpdated&&this.states.has(r)&&n.push(r)}),n.length>0&&pi(this,n,"timeout")},Ea(Yr/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:jt()});const s=[],a=[],l=[],c=[];e===null?c.push(t):r==null?e!=null&&s.push(t):(a.push(t),gn(r,e)||l.push(t)),(s.length>0||l.length>0||c.length>0)&&this.emit("change",[{added:s,updated:l,removed:c},"local"]),this.emit("update",[{added:s,updated:a,removed:c},"local"])}setLocalStateField(e,t){const n=this.getLocalState();n!==null&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}}const pi=(o,e,t)=>{const n=[];for(let i=0;i<e.length;i++){const r=e[i];if(o.states.has(r)){if(o.states.delete(r),r===o.clientID){const s=o.meta.get(r);o.meta.set(r,{clock:s.clock+1,lastUpdated:jt()})}n.push(r)}}n.length>0&&(o.emit("change",[{added:[],updated:[],removed:n},t]),o.emit("update",[{added:[],updated:[],removed:n},t]))},qr=(o,e,t=o.states)=>{const n=e.length,i=Ur();Ce(i,n);for(let r=0;r<n;r++){const s=e[r],a=t.get(s)||null,l=o.meta.get(s).clock;Ce(i,s),Ce(i,l),Je(i,JSON.stringify(a))}return Hr(i)},fh=(o,e,t)=>{const n=Da(e),i=jt(),r=[],s=[],a=[],l=[],c=xt(n);for(let d=0;d<c;d++){const g=xt(n);let u=xt(n);const p=JSON.parse(dn(n)),h=o.meta.get(g),f=o.states.get(g),m=h===void 0?0:h.clock;(m<u||m===u&&p===null&&o.states.has(g))&&(p===null?g===o.clientID&&o.getLocalState()!=null?u++:o.states.delete(g):o.states.set(g,p),o.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&&(gn(p,f)||a.push(g),s.push(g)))}(r.length>0||a.length>0||l.length>0)&&o.emit("change",[{added:r,updated:a,removed:l},t]),(r.length>0||s.length>0||l.length>0)&&o.emit("update",[{added:r,updated:s,removed:l},t])};class Xa{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 Jr{constructor(e){this.data=e,this.encoder=Ur(),this.decoder=Da(new Uint8Array(this.data))}peekVarString(){return ah(this.decoder)}readVarUint(){return xt(this.decoder)}readVarString(){return dn(this.decoder)}readVarUint8Array(){return fi(this.decoder)}writeVarUint(e){return Ce(this.encoder,e)}writeVarString(e){return Je(this.encoder,e)}writeVarUint8Array(e){return _t(this.encoder,e)}length(){return Ma(this.encoder)}}var ve;(function(o){o[o.Sync=0]="Sync",o[o.Awareness=1]="Awareness",o[o.Auth=2]="Auth",o[o.QueryAwareness=3]="QueryAwareness",o[o.Stateless=5]="Stateless",o[o.CLOSE=7]="CLOSE",o[o.SyncStatus=8]="SyncStatus"})(ve||(ve={}));var Ee;(function(o){o.Connecting="connecting",o.Connected="connected",o.Disconnected="disconnected"})(Ee||(Ee={}));class At{constructor(){this.encoder=Ur()}get(e){return e.encoder}toUint8Array(){return Hr(this.encoder)}}class ph extends At{constructor(){super(...arguments),this.type=ve.CLOSE,this.description="Ask the server to close the connection"}get(e){return Je(this.encoder,e.documentName),Ce(this.encoder,this.type),this.encoder}}class mh extends Xa{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=Ee.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===Ee.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===Ee.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){this.configuration.providerMap.has(e.configuration.name)&&(e.send(ph,{documentName:e.configuration.name}),this.configuration.providerMap.delete(e.configuration.name))}setConfiguration(e={}){this.configuration={...this.configuration,...e}}async connect(){if(this.status===Ee.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const e=()=>{let i=!1;return{retryPromise:Xu(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}),s=c=>this.emit("open",c),a=c=>{t(c)};this.webSocketHandlers[n]={message:i,close:r,open:s,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=Ee.Connecting,this.emit("status",{status:Ee.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){var t;this.resolveConnectionAttempt(),this.lastMessageReceived=jt();const n=new Jr(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=Ee.Connected,this.emit("status",{status:Ee.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===Ee.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=jt()-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)===jr.Open?this.webSocket.send(e):this.messageQueue.push(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=Ee.Disconnected,this.emit("status",{status:Ee.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 Ua=0,Kr=1,Ha=2,bh=(o,e)=>{Ce(o,Ua);const t=S.encodeStateVector(e);_t(o,t)},yh=(o,e,t)=>{Ce(o,Kr),_t(o,S.encodeStateAsUpdate(e,t))},kh=(o,e,t)=>yh(e,t,fi(o)),za=(o,e,t)=>{try{S.applyUpdate(e,fi(o),t)}catch(n){console.error("Caught error while handling a Yjs update",n)}},Sh=(o,e)=>{Ce(o,Ha),_t(o,e)},Ih=za,vh=(o,e,t,n)=>{const i=xt(o);switch(i){case Ua:kh(o,e,t);break;case Kr:za(o,t,n);break;case Ha:Ih(o,t,n);break;default:throw new Error("Unknown message type")}return i};class xh{constructor(e){this.message=e}apply(e,t){const{message:n}=this,i=n.readVarUint(),r=n.length();switch(i){case ve.Sync:this.applySyncMessage(e,t);break;case ve.Awareness:this.applyAwarenessMessage(e);break;case ve.Auth:this.applyAuthMessage(e);break;case ve.QueryAwareness:this.applyQueryAwarenessMessage(e);break;case ve.Stateless:e.receiveStateless(dn(n.decoder));break;case ve.SyncStatus:this.applySyncStatusMessage(e,rh(n.decoder)===1);break;case ve.CLOSE:const s={code:1e3,reason:dn(n.decoder),target:e.configuration.websocketProvider.webSocket,type:"close"};e.onClose(),e.configuration.onClose({event:s}),e.forwardClose(s);break;default:throw new Error(`Can’t apply message of unknown type: ${i}`)}n.length()>r+1&&e.send(At,{encoder:n.encoder})}applySyncMessage(e,t){const{message:n}=this;n.writeVarUint(ve.Sync);const i=vh(n.decoder,n.encoder,e.document,e);t&&i===Kr&&(e.synced=!0)}applySyncStatusMessage(e,t){t&&e.decrementUnsyncedChanges()}applyAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;fh(e.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){const{message:t}=this;Du(t.decoder,e.permissionDeniedHandler.bind(e),e.authenticatedHandler.bind(e))}applyQueryAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;t.writeVarUint(ve.Awareness),t.writeVarUint8Array(qr(e.awareness,Array.from(e.awareness.getStates().keys())))}}class Ah{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return Hr(this.encoder)}send(e){e?.send(this.create())}}class wh extends At{constructor(){super(...arguments),this.type=ve.Auth,this.description="Authentication"}get(e){if(typeof e.token>"u")throw new Error("The authentication message requires `token` as an argument.");return Je(this.encoder,e.documentName),Ce(this.encoder,this.type),Ru(this.encoder,e.token),this.encoder}}class Wa extends At{constructor(){super(...arguments),this.type=ve.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");Je(this.encoder,e.documentName),Ce(this.encoder,this.type);let t;return e.states===void 0?t=qr(e.awareness,e.clients):t=qr(e.awareness,e.clients,e.states),_t(this.encoder,t),this.encoder}}class Th extends At{constructor(){super(...arguments),this.type=ve.Stateless,this.description="A stateless message"}get(e){var t;return Je(this.encoder,e.documentName),Ce(this.encoder,this.type),Je(this.encoder,(t=e.payload)!==null&&t!==void 0?t:""),this.encoder}}class Ya extends At{constructor(){super(...arguments),this.type=ve.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 Je(this.encoder,e.documentName),Ce(this.encoder,this.type),bh(this.encoder,e.document),this.encoder}}class Ch extends At{constructor(){super(...arguments),this.type=ve.Sync,this.description="A document update"}get(e){return Je(this.encoder,e.documentName),Ce(this.encoder,this.type),Sh(this.encoder,e.update),this.encoder}}class Ph extends Error{constructor(){super(...arguments),this.code=1001}}class Bh extends Xa{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 hh(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:Fa(this.awareness.getStates())})}),(n=this.awareness)===null||n===void 0||n.on("change",()=>{this.emit("awarenessChange",{states:Fa(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 mh({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(Ya,{document:this.document,documentName:this.configuration.name})}pageHide(){this.awareness&&pi(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){typeof window>"u"||!("addEventListener"in window)||window.addEventListener("pagehide",this.boundPageHide)}sendStateless(e){this.send(Th,{documentName:this.configuration.name,payload:e})}documentUpdateHandler(e,t){t!==this&&(this.incrementUnsyncedChanges(),this.send(Ch,{update:e,documentName:this.configuration.name}))}awarenessUpdateHandler({added:e,updated:t,removed:n},i){const r=e.concat(t).concat(n);this.send(Wa,{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(wh,{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(Ya,{document:this.document,documentName:this.configuration.name}),this.awareness&&this.awareness.getLocalState()!==null&&this.send(Wa,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.configuration.name})}send(e,t){if(!this._isAttached)return;const n=new Ah(e,t);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){const t=new Jr(e.data),n=t.readVarString();t.writeVarString(n),this.emit("message",{event:e,message:new Jr(e.data)}),new xh(t).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,this.awareness&&pi(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&&(pi(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 Ph(`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 qa=10,mi=(o,e,t)=>Math.max(e,Math.min(t,o));function un(o){const e={};for(const[t,n]of Object.entries(o??{}))pr.has(t)&&t!=="aiGenerated"&&t!=="__htmlClassName"||n==null||(e[t]=n);return JSON.stringify(e)}function hn(o){if(typeof o!="string"||o.length===0)return null;try{const e=JSON.parse(o);return e&&typeof e=="object"&&typeof e.id=="string"?e:null}catch{return null}}function bi(o){if(typeof o!="string"||o.length===0)return null;try{const e=JSON.parse(o);return e&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}function Ja(o,e){if(!o)return;const t={},n=!!o.footnoteRef;for(const[i,r]of Object.entries(o))r===void 0||r===!1||r===null||pr.has(i)||i!=="footnoteRef"&&(i==="superscript"&&n||(t[i]=r));return Object.keys(t).length>0?t:void 0}const Ka=["spaceBefore","spaceAfter","contextualSpacing"];function fn(o,e){e.spaceBefore!==void 0&&o.setAttribute("spaceBefore",String(e.spaceBefore)),e.spaceAfter!==void 0&&o.setAttribute("spaceAfter",String(e.spaceAfter)),e.contextualSpacing!==void 0&&o.setAttribute("contextualSpacing",String(e.contextualSpacing))}function $h(o,e,t=!1){for(const n of Ka){const i=Q(o,n);i!=null?e.setAttribute(n,i):t&&q(e,n)}}function Va(o){if(!o)return{};if(typeof o=="string")try{return JSON.parse(o)}catch{return{}}return typeof o=="object"?{...o}:{}}function Ga(o){const e=Va(o.getAttribute("_emptyTextMarks"));if(Object.keys(e).length===0)return!1;for(const t of $o)delete e[t];return Object.keys(e).length===0?o.removeAttribute("_emptyTextMarks"):o.setAttribute("_emptyTextMarks",JSON.stringify(e)),!0}function Za(o,e,t,n){const i=o.getAttribute("_emptyTextMarks"),r=i!=null,s=t==null||t===!1;if(!r&&!n&&!s)return!1;const a=Va(i),l=Object.prototype.hasOwnProperty.call(a,e);if(s){if(!l)return!1;delete a[e]}else{if(a[e]===t)return!1;a[e]=t}return Object.keys(a).length===0?o.removeAttribute("_emptyTextMarks"):o.setAttribute("_emptyTextMarks",JSON.stringify(a)),!0}function yi(o,e){e&&Object.keys(e).length>0?o.setAttribute("_emptyTextMarks",JSON.stringify(e)):o.removeAttribute("_emptyTextMarks")}function ki(o){return o.children.some(e=>e.type==="text"&&e.text.length>0)}function pn(o,e,t,n){if(!ki(e))return ct(n);if(t.offset<=0){const r=e.children.find(s=>s.type==="text"&&s.text.length>0);return ct(r?.marks)}const i=po(o,t);return ct(i?.marks)}const mn=o=>o?.type==="code"||o?.type==="math",Xt=o=>{if(!o||o.type!=="code")return!1;const e=o.language?.trim().toLowerCase();return e==="latex"||e==="latex-inline"},Le="Arial, sans-serif";function Qa(o){if(o==null)return;const e=Number.parseFloat(o);return Number.isFinite(e)?e:void 0}function el(o,e){for(const t of o.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")&&el(t,e)}}const tl=o=>o.name==="set_title"||o.name==="set_notes"||o.name==="set_page_layout"||o.name==="set_header_footer",Fh=o=>`${o} ${o===1?"proposal":"proposals"}`;function Me(o){if(!o||typeof o!="object")return"";if(o.type==="text"&&typeof o.text=="string")return o.text;if((o.type==="code"||o.type==="math")&&typeof o.content=="string")return o.content;if(Array.isArray(o.children)){const e=o.type==="paragraph"||o.type==="list-item"?"":" ";return o.children.map(t=>Me(t)).filter(t=>t.length>0).join(e)}return""}function nl(o){const e=o.replace(/\s+/g," ").trim();return e.length===0?[]:e.split(" ")}function Eh(o,e){if(o.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<=o.length;i++){for(let r=1;r<=e.length;r++)n[r]=o[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 Lh(o,e){const t=nl(o),n=nl(e),i=Math.max(t.length,n.length);if(i===0)return null;const r=Eh(t,n),s=Math.max(0,i-r);return Math.round(s/i*100)}function Mh(o,e,t){const n=X(o,t),i=X(e,t);if(!n||!i)return null;const r=Me(n),s=Me(i);return Lh(r,s)}function il(o,e,t,n,i){if(!o||!e||t.length===0)return o;const r=e.filter(g=>!tl(g));if(r.length!==1||r[0].name!=="replace_block")return o;const s=r[0].arguments&&typeof r[0].arguments=="object"?r[0].arguments:void 0,a=typeof s?.id=="string"&&s.id.trim().length>0?s.id.trim():null;if(!a||(typeof s?.count=="number"&&Number.isFinite(s.count)?Math.max(1,Math.floor(s.count)):1)!==1)return o;const l=[Fh(t.length)],c=Mh(n,i,a);c!==null&&l.push(`~${c}% words changed`);const d=o.trim();return d.endsWith(".")?`${d.slice(0,-1)} (${l.join("; ")}).`:`${d} (${l.join("; ")}).`}function Nh(o,e,t){if(t<=0)return[];const n=Ye(o).get(e);if(!n)return[];const i=n.parentContainer?n.parentContainer.children:o.children,r=[];for(let s=n.indexInParent;s<i.length&&r.length<t;s+=1){const a=i[s];if(!a?.id)break;r.push(a.id)}return r}function Oh(o,e){if(!e||e.length===0)return[];const t=[];for(const n of e){if(n.name!=="replace_block")continue;const i=Nc(n);if(!i||i.replacementBlockIds.length<=1||i.replacedCount<=1)continue;const r=n.arguments&&typeof n.arguments=="object"?n.arguments:void 0,s=typeof r?.id=="string"&&r.id.trim().length>0?r.id.trim():null;if(!s)continue;const a=Nh(o,s,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 rl=(o,e,t)=>{if(!o||!e)return;const n=o.filter(a=>!tl(a));if(n.length!==1){if(n.length===0){const a=o.some(g=>g.name==="set_title"),l=o.some(g=>g.name==="set_notes"),c=o.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=o.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=o.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]??[],s=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=s(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 ${s(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}.`}},ol=class wt{constructor(e,t=()=>{},n,i,r,s,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,b,y)=>{if(this.disposed)return;m!==go&&m!==Zs&&this.canRepairIdentity()&&(this.classifyTransactionOrigin(m)==="local"?this.repairDocumentIdentity(y,m):this.scheduleDeferredIdentityRepair());const k=this.ydoc.share.get("agent-presence"),I=k&&y.changedParentTypes.size>0&&[...y.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 uu(this),this.suggestionEngine=new bn(this),this.cachedKernel=null,this.strandedObservers=!1,this.strandedCheck=null,this.identityRepairedOnConstruct=!1,this.deferredIdentityRepair=null,this.ydoc=i||Ci(e),Gs(this.ydoc,fr),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 xr(this.ydoc,this.documentId,s),this.toolCallHistory=new pa,this.preprocessorSession=a||new li,this.ensureParagraphIndentStorageUsesUnits(),this.cachedDoc=e,Nn(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 b=m[m.length-1];f.stackItem.meta.forEach((y,k)=>{b.meta.set(k,y)})}}})}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=X(e,t);if(!n)return null;const i=ut(e,t);if(!i||i.length===0)return uo(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 s=r.text.length;if(r.marks?.fontFamily&&(i=r.marks.fontFamily),n+s>=t)return r.marks?.fontFamily||i;n+=s}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 Bh?"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=X(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 s=0;for(const a of r){if(a.type!=="text")continue;const l=s+a.text.length;if(n<l||a.text.length===0&&n===s)return a.marks;s=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 s=this.getTextMarksAtBlockOffset(r.blockId,r.itemIndex,r.start);for(const a of i){const l=r.attributes[a],c=s?.[a];a==="fontFamily"&&(l??void 0)===void 0&&c===Le||(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(s=>{const a=this.getNaturalFormatCategoryFromMarkKey(s);return n.has(s)?`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 s=Math.max(i.length,r.length);for(let a=0;a<s;a++){const l=this.getTextMarksAtOffset(e,a),c=this.getTextMarksAtOffset(t,a);for(const d of xn)this.formattingMarkValuesEqual(l?.[d],c?.[d])||n.add(d)}if(s===0){const a=e[0]?.marks,l=t[0]?.marks;for(const c of xn)this.formattingMarkValuesEqual(a?.[c],l?.[c])||n.add(c)}return xn.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 s=0;s<r;s++){const a=e.children[s],l=t.children[s];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(),s=Ye(r),a=Ye(t),l=new Map;for(const d of[s,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=qe(d,g);for(;u&&u.type!=="doc";){if(u.id)return u.id;u=qe(d,u.id)}return null};return n.filter(d=>{const g=l.get(d);if(g&&i.has(g))return!1;const u=[s.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,s=te(e);let a=0;for(const l of s){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 te(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 s=r-1;if(n[s].end!==t||!n[s].attributes.insertion)return null;for(;s>0&&n[s-1].end===n[s].start&&n[s-1].attributes.insertion;)s-=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(s,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,s=n+i+r;return e<=n||e>s?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 s=e.children[r].children,a=t.children[r].children,l=a.length-s.length;if(Math.abs(l)!==1)return null;const c=l>0?"insert":"delete",d=l>0?a:s,g=l>0?s: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(!X(r,e))return!1;const s=G(this.ydoc,e);return s?(this.beforeOperationRelativeSelection=H(n,this.ydoc,r),this.transact(()=>{this.replaceBlockByIdWithoutSelection(e,t,s)}),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=X(this.getDocument(),e.blockId);if(!i||i.type!=="list")return!1;const r=this.suggestionEngine.cloneSuggestionSnapshot(i),s=r.children.findIndex(u=>u.structuralSuggestionId===e.id);if(s===-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[s]=this.suggestionEngine.cloneSuggestionSnapshot(d??a.children[s]):a.children.splice(s,1);else if(l==="delete")t==="accept"?a.children.splice(s,1):a.children[s]=this.suggestionEngine.cloneSuggestionSnapshot(c??a.children[s]);else{const u=t==="accept"?d??a.children[s]:c;if(!u)return!1;a.children[s]=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 s of t.children)s.type==="text"&&(i+=s.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 Ut(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=J(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},s=G(this.ydoc,i.block.id),a=s?{parent:s.yParent,index:s.index,yBlock:s.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],s=i.children[t+1];if(!r||!s)return null;const a=this.suggestionEngine.cloneSuggestionSnapshot(r.children),l=this.suggestionEngine.cloneSuggestionSnapshot(s.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=[],s=Se(i,e,t)<=0,a=s?e:t,l=s?t:e;if(a.block===l.block)return this.collectSingleBlockFormattingRange(a,l,i);{const u=uo(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,b]=h<=f?[h,f]:[f,h],y=[];for(let k=m;k<=b;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};y.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 y}}}const c=ut(i,a.block),d=ut(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 mo(i)){const h=Pt(p,c),f=Pt(p,d);if(h<0)continue;if(f>0)break;const m=f===0,b=G(this.ydoc,u.id);if(!b){g=!1;continue}const y=b.yBlock;if(u.type==="paragraph"){const k=se(y);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=mi(I,0,k.length),v=mi(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 $=0;$<y.length;$++){const P=y.get($);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,w=0,E=Number.MAX_SAFE_INTEGER;if(g&&a.block===u.id){const $=this.listOperations.getListCursorInfo(k,a);$&&(x=Math.min($.itemIndex,v-1),w=$.offsetInItem)}if(m&&l.block===u.id){const $=this.listOperations.getListCursorInfo(k,l);$&&(A=Math.min($.itemIndex,v-1),E=$.offsetInItem)}for(let $=x;$<=A;$++){const P=I[$];if(!P)continue;const B=se(P);if(!B||B.length===0)continue;let C=0,T=B.length;$===x&&(C=Math.min(w,B.length)),$===A&&(T=Math.min(E,B.length)),T>C&&r.push({yText:B,start:C,end:T})}g=!1}}return r}collectSingleBlockFormattingRange(e,t,n){const i=[],r=X(n,e.block);if(!r)return i;const s=G(this.ydoc,e.block);if(!s)return i;const a=s.yBlock;if(r.type==="paragraph"){const l=se(a);if(!l)return i;let c=e.offset,d=t.offset;c=mi(c,0,l.length),d=mi(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 b=0;b<a.length;b++){const y=a.get(b);y instanceof S.XmlElement&&y.nodeName==="list-item"&&c.push(y)}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 b=p;b<=h;b++){const y=c[b];if(!y)continue;const k=se(y);if(!k||k.length===0)continue;let I=0,v=k.length;b===p&&(I=Math.min(f,k.length)),b===h&&(v=Math.min(m,k.length)),v>I&&i.push({yText:k,start:I,end:v,blockId:r.id,itemIndex:b})}}return i}collectParagraphBlockIdsInRange(e,t,n){const i=[],r=new Set,s=u=>{const p=X(n,u);p?.type==="paragraph"&&p.id&&!r.has(p.id)&&(r.add(p.id),i.push(p.id))},a=Se(n,e,t)<=0,l=a?e:t,c=a?t:e,d=ut(n,l.block),g=ut(n,c.block);if(!d||!g)return s(l.block),s(c.block),i;for(const{block:u,path:p}of mo(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&&s(l.block),i}clearFormattingEmptyMarksAtPosition(e,t){const n=X(t,e.block);if(!n)return!1;if(n.type==="paragraph"){const c=G(this.ydoc,n.id);return c?Ga(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 s=this.listOperations.getListCursorInfo(i,e);if(!s)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[s.itemIndex];return l?Ga(l):!1}updateEmptyTextMarksAtPosition(e,t,n,i){const r=X(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 Za(g.yBlock,t,n,!u)}if(r.type!=="list")return!1;const s=r,a=G(this.ydoc,r.id);if(!a)return!1;const l=this.listOperations.getListCursorInfo(s,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?Za(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(),s=X(r,e.block);if(!mn(s))return!1;const a=J(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 s=X(r,e.block);if(!mn(s))return!1;const a=J(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(Ve.paragraphIndentStorageVersion)===Ai)return;const t=this.ydoc.getXmlFragment("content");if(t.length===0&&Tt(this.ydoc))return;const n=e.get(Ve.indentStepPx),i=Ke({indentStepPx:typeof n=="number"?n:void 0}).indentStepPx;this.ydoc.transact(()=>{t.length>0&&el(t,r=>{const s=fo(Qa(Q(r,"leftIndent")),{indentStepPx:i,storedAsUnits:!1}),a=fo(Qa(Q(r,"firstLineIndent")),{indentStepPx:i,storedAsUnits:!1,firstLine:!0});s===void 0?q(r,"leftIndent"):r.setAttribute("leftIndent",String(s)),a===void 0?q(r,"firstLineIndent"):r.setAttribute("firstLineIndent",String(a))}),e.set(Ve.paragraphIndentStorageVersion,Ai)},"indent-storage-migration")}setTitle(e){const t=pu(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=Ke(this.getPageLayoutSettings()),n=this.getDocument().children.filter(s=>s.type==="section-break"),i=e.pageNumberFormat!==void 0&&e.pageNumberFormat!==t.pageNumberFormat,r=e.pageNumberStart!==void 0&&e.pageNumberStart!==t.pageNumberStart;n.forEach((s,a)=>{const l=s.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(s.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 s=n.getAttribute("layout");i=typeof s=="string"?JSON.parse(s):{}}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(ho(r,e)??e))}})}applySetHeaderFooterAction(e){const t=e.side==="footer"?"footer":"header",n=e.slot==="first"||e.slot==="even"?e.slot:"default";return{changed:Ig(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:Fl(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,s=typeof e.sectionIndex=="number"&&Number.isInteger(e.sectionIndex)&&e.sectionIndex>=1&&e.sectionIndex<=r?e.sectionIndex:void 0;if(e.sectionIndex!=null&&s===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&&!Pi(e.pageNumberFormat))return{settings:n,pageless:this.getPagelessMode(),error:`pageNumberFormat must be one of ${El.join(", ")}, got ${JSON.stringify(e.pageNumberFormat)}`};const a=s?i[s-1]:void 0,l=a?oo(n,a.layout):n,c=this.getPagelessMode(),d=Ll(e.preset)?Ml(e.preset):void 0,g={...d?.pageLayout??{}},u={...l,...d?.pageLayout??{}};Nl(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 b=Ue(e.marginLeft);b!==void 0&&(u.marginLeftPx=b,g.marginLeftPx=b);const y=Ue(e.indentStep);y!==void 0&&(u.indentStepPx=y,g.indentStepPx=y);const k=Ue(e.blockSpacing);k!==void 0&&(u.blockSpacingPx=k,g.blockSpacingPx=k),Ol(e.columnCount)&&(u.columnCount=e.columnCount,g.columnCount=e.columnCount);const I=Ue(e.columnGap);if(I!==void 0){const B=Math.max(0,Hl(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"||Bi(e.pageNumberPosition)){const B=Bi(e.pageNumberPosition)?e.pageNumberPosition:this.ydoc.getMap("metadata").get(Ve.pageNumberPosition)??"bottom-right",C=typeof e.showPageNumbers=="boolean"?e.showPageNumbers:!0;this.setPageNumberSlot(C,B)}if(typeof e.showPageNumbers=="boolean"&&(u.showPageNumbers=!1),Bi(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),Pi(e.pageNumberFormat)&&(u.pageNumberFormat=e.pageNumberFormat,g.pageNumberFormat=e.pageNumberFormat),!a){const B=s===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=Rl(e.lineNumbering);B?u.lineNumbering=B:delete u.lineNumbering,g.lineNumbering=Dl(B)??""}const v=Ue(e.pageWidth),x=Ue(e.pageHeight);if(v!==void 0&&x!==void 0){const B=_l(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=Co(e.watermark);this.transact(()=>{const C=this.ydoc.getMap("metadata");B?C.set("watermark",B):C.delete("watermark")})}const A=Ke(u),w=typeof e.pageless=="boolean"?e.pageless:d?.pageless??c,E=e.pageNumberRestart===!1&&typeof e.pageNumberStart!="number",$=B=>{const C=ho(B,g)??{...g};if(!E)return C;const{pageNumberStart:T,...L}=C;return L},P=Object.keys(g).length>0||E;if(s&&a)P&&this.updateSectionBreakLayout(a.id,$(a.layout));else if(s===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({...Pi(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,$(B.layout));this.setPageLayoutSettings(A)}return this.setPagelessMode(w),{settings:A,pageless:w}}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){const i=new Set(e),r=new Set(t),s=[],a=[],l=[],c=p=>{if(p instanceof S.XmlText){let h=0;for(const f of te(p)){const m=typeof f.insert=="string"?f.insert.length:1,b=f.attributes??{};b.deletion&&i.has(b.suggestionId)?s.push({text:p,start:h,length:m,attributes:b}):b.insertion&&r.has(b.suggestionId)&&a.push({text:p,start:h,length:m,attributes:b}),h+=m}}if(p instanceof S.XmlFragment||p instanceof S.XmlElement){p instanceof S.XmlElement&&(i.has(p.getAttribute("structuralSuggestionId"))||r.has(p.getAttribute("structuralSuggestionId")))&&l.push(p);for(let h=0;h<p.length;h++){const f=p.get(h);f instanceof S.AbstractType&&c(f)}}};if(c(this.getYContentFragment()),s.length===0||a.length===0)return!1;const d=1e7+Math.floor(Math.random()*9e7),g=`reviseMove-${n}`,u=(p,h,f)=>{const m=JSON.stringify({version:1,name:g,role:h,rangeId:`${d}${f}`,wrapperId:`${d+1}${f}`,fallbackSuggestionId:p[0].attributes.suggestionId,...p[0].attributes.suggestionAuthorName?{rangeAuthor:p[0].attributes.suggestionAuthorName}:{},...typeof p[0].attributes.suggestionCreatedAt=="number"?{rangeCreatedAt:p[0].attributes.suggestionCreatedAt}:{}});for(const b of p)re(b.text,b.start,b.length,{suggestionId:n,suggestionLabel:"Move",docxMove:m})};return this.transact(()=>{u(s,"from","1"),u(a,"to","2");for(const p of l)p.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:s}=this.recordStampedSuggestionIds(n);return i(r)&&this.completeInternalTextMove(t,[...s.insertionIds,...s.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=Ci(e);try{const i=wt.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 wt(he(i),()=>{},void 0,i,"live-suggestion-projection",!0,new li,{canRepairIdentity:()=>!1}),s=n?Array.from(new Set(n.filter(a=>typeof a=="string"&&a.length>0))):r.getLiveSuggestionIds();try{return t==="accept"?r.suggestionEngine.applyLiveSuggestionDecisionInternal(s,"accept"):r.suggestionEngine.applyLiveSuggestionDecisionInternal(s,"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){oi(this.kernel,e,t)}ensureHeaderFooterBlock(e,t){return ia(this.kernel,e,t)}migrateLegacyHeaderFooterMetadata(){bg(this.kernel)}migrateNotesOutOfContent(){Mg(this.kernel)}migrateChromeOutOfContent(){mg(this.kernel)}getHeadersAndFooters(){return br(this.kernel)}setSectionHeadersAndFooters(e,t,n){fg(this.kernel,e,t,n)}getSectionHeadersAndFooters(e){return pg(this.kernel,e)}setPageNumberSlot(e,t="bottom-right"){yg(this.kernel,e,t)}migrateLegacyPageNumbers(){kg(this.kernel)}setPageLayoutSettings(e){this.ensureParagraphIndentStorageUsesUnits(),this.transact(()=>{jl(this.ydoc.getMap("metadata"),e)})}setWatermark(e){const t=Co(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 to(this.ydoc.getMap("metadata"))??Ke(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,fr(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"})},wt.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,s=n?c=>{const d=c._item?.id;return d!==void 0&&d.client===i&&d.clock>=r}:void 0,a=Xl(this.ydoc,{transaction:e,shouldDrop:s});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)},go)}const l=lg(this.ydoc,e,n?"strip":"recover");return a.duplicatesFound===0&&l===0?!1:(this.cachedDoc=null,this.incrementalRefreshPending=!1,Nn(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?vr(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?vr(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 s=this.resolveEditableContext(e,r);if(!s)return!1;const{editable:a}=s,l=a.block;if(l.type==="list")return this.listOperations.insertTextInList(e,t,n,i);if(mn(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=Fi(r,e),h=Ei(r,e),f=Li(r,e,n),m=this.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(r,e),b=m?.marks?.suggestionId??null,y=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r,e.block),k=this.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(r,e,n),I=!y&&this.suggestingMode&&t.length>0,v=mr({inheritedMarks:f?.marks,emptyParagraphMarks:ki(c)?void 0:this.getEmptyTextMarksForBlockId(e.block),exitingLink:p,exitingComment:h,suggestionMarks:I?this.suggestionEngine.buildSuggestionInsertionMarks(void 0,k??b??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,s){this.beforeOperationSelection=i;const a=this.getDocument();this.beforeOperationRelativeSelection=H(i,this.ydoc,a);const l=X(a,e.block);if(!l)return!1;if(l.type==="list")return this.listOperations.insertFormattedTextInList(e,t,n,i,r);if(mn(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=st(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=Li(a,e,i),m=this.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(a,e),b=m?.marks?.suggestionId??null,y=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(a,e.block),k=this.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(a,e,i),I=Fi(a,e),v=Ei(a,e),x=!y&&this.suggestingMode&&t.length>0,{marksToApply:A,marksToRemove:w}=mr({explicitMarks:n&&Object.keys(n).length>0?n:void 0,inheritedMarks:f?.marks,emptyParagraphMarks:ki(c)?void 0:this.getEmptyTextMarksForBlockId(e.block),exitingLink:I,exitingComment:v,noteBodyFontSize:this.isBlockInsideFootnote(a,e.block)?gt:void 0,suggestionMarks:x?this.suggestionEngine.buildSuggestionInsertionMarks(void 0,s??k??b??this.suggestionEngine.getSuggestionIdFromInheritedMarks(f?.marks),void 0,void 0,m?.marks??f?.marks):void 0});let E=h;this.transact(()=>{if(i&&i.anchor&&i.focus&&Se(a,i.anchor,i.focus)!==0){const[B,C]=Se(a,i.anchor,i.focus)===-1?[i.anchor,i.focus]:[i.focus,i.anchor];if(B.block===e.block&&C.block===e.block)if(this.suggestingMode&&!y){const{retainedLength:T}=this.suggestionEngine.applySuggestedDeletionToTextRange(p,B.offset,C.offset-B.offset,k??void 0);E=B.offset+T}else p.delete(B.offset,C.offset-B.offset),E=B.offset}ta(p,E,t,{marksToApply:A,marksToRemove:w}),!y&&this.suggestingMode&&t.length>0&&this.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(p,E,t.length)});const $=S.createRelativePositionFromTypeIndex(p,E+t.length),P=si({blockId:g.blockId,textOffset:$},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(),s=J(this.ydoc,e.block);if(!s)return null;const a=se(s);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&&Se(r,n.anchor,n.focus)!==0){const[f,m]=Se(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:b}=this.suggestionEngine.applySuggestedDeletionToTextRange(a,f.offset,m.offset-f.offset,i);d=f.offset+b}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);s.getAttribute("_emptyTextMarks")&&s.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)),fn(i,t);const r=We(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 s=Re(t.leftIndent);s!==void 0&&i.setAttribute("leftIndent",String(s));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 s=X(r,e.block);if(!s)return!1;if(s.type==="list")return this.listOperations.deleteTextInList(e,t,n,i);if(mn(s))return this.deleteTextInCodeBlock(e,t,n,i);if(s.type!=="paragraph")return!1;const a=s,l=this.getEmptyTextMarksForBlockId(e.block),c=pn(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 b=null;this.transact(()=>{const k=J(this.ydoc,e.block);if(!k)return;const I=se(k);if(I){if(this.suggestingMode&&!m){const v=this.suggestionEngine.applySuggestedDeletionToTextRange(I,e.offset,f);f>1&&v.retainedLength>0&&(b=this.normalizeAdjacentManualReplacementOrder(I,e.offset))}else I.delete(e.offset,f);I.length===0&&yi(k,c)}});const y=b?Vr(i,e.block,b):i;return this.setSelectionAfterOperation(y),this.afterOperationRelativeSelection=H(y,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 s=zt(r,e.block),a=zt(r,t.block);if(s===-1||a===-1){const p=h=>{const f=(r.chrome??[]).findIndex(b=>b.id===h||b.children.some(y=>y.id===h));if(f!==-1)return r.children.length+f;const m=(r.notes??[]).findIndex(b=>b.id===h||b.children.some(y=>y.id===h));return m!==-1?r.children.length+(r.chrome?.length??0)+m:-1};if(s=p(e.block),a=p(t.block),s===-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=X(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),b=this.listOperations.getListCursorInfo(f,t);if(m&&b&&m.itemIndex+1===b.itemIndex&&m.offsetInItem===this.listOperations.getListItemPlainText(f.children[m.itemIndex]).length&&b.offsetInItem===0){const y=ce(),k=this.mergeAdjacentListItemsSnapshot(f,m.itemIndex,y);if(k){const I=this.suggestionEngine.runWithoutSuggesting(()=>this.updateBlockById(f.id,k,n,i));return I&&this.suggestionEngine.saveLiveSuggestion({id:y,type:"block-change",blockId:f.id,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(f),label:"Join"}),I}}}const h=Ge().getHandlerForBlock(p);if(h&&h.handleDeleteSelection){const f=J(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((b,y)=>b+(y.type==="text"?y.text.length:0),0)&&ki(p)&&yi(f,pn(r,p,e))}),m){const b=Yl(r,e.block),y=ql(r,e.block);let k;if(b&&b.id){const v=pc(r,b.id);v?k=v:k={block:b.id,offset:0}}else if(y&&y.id)k={block:y.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,s,a,i))return!0;const c=qe(r,e.block),d=qe(r,t.block),g=X(r,e.block),u=X(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,s,a){const l=J(this.ydoc,e.id),c=J(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 b=0;b<l.length;b++){const y=l.get(b);if(y instanceof S.XmlText){d=y;break}}for(let b=0;b<c.length;b++){const y=c.get(b);if(y instanceof S.XmlText){g=y;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 b=this.isPlainEmptyParagraph(e),y=this.isPlainEmptyParagraph(t),k=this.isInsertedParagraph(e),I=this.isInsertedParagraph(t);if(b&&I||k&&y){const v=b?e:t,x=b?t:e,A=b?0:this.getParagraphTextLength(x),w={block:x.id,offset:A},E={anchor:w,focus:w};return this.deleteBlockById(v.id,s,E)}}if(this.suggestingMode&&u){const b=this.getCancelableParagraphSplitRecord(e,t);if(b){const k=this.suggestionEngine.rejectLiveSuggestion(b.id);if(k){const I={block:b.blockId,offset:this.getParagraphTextLength(e)},v={anchor:I,focus:I};this.setSelectionAfterOperation(v),this.afterOperationRelativeSelection=H(v,this.ydoc,this.getDocument())}return k}const y=ce();return this.transact(()=>{this.suggestionEngine.clearParagraphStructuralSuggestion(l),this.suggestionEngine.clearParagraphStructuralSuggestion(c),this.suggestionEngine.setParagraphStructuralSuggestion(l,"merge","before",y),this.suggestionEngine.setParagraphStructuralSuggestion(c,"merge","after",y),this.suggestionEngine.saveLiveSuggestion({id:y,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 b=d.length;n.offset<b&&d.delete(n.offset,b-n.offset);const y=te(g).slice(0);let k=[],I=0;for(const A of y)if(typeof A.insert=="string"){const w=A.insert;if(I+w.length<=i.offset)I+=w.length;else if(I>=i.offset)k.push(A);else{const E=i.offset-I,$=w.slice(E);$.length>0&&k.push({...A,insert:$}),I+=w.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 s=ut(n,e.block),a=ut(n,t.block);if(!s||!a)return!1;const l=X(n,e.block),c=X(n,t.block);if(!l||!c)return!1;const d=[];for(const{block:A,path:w}of Jl(n)){const E=Pt(w,s),$=Pt(w,a);if(!(E<0)){if($>0)break;d.push({block:A,path:w,isFirst:E===0,isLast:$===0})}}if(d.length===0)return!1;const g=s[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],b=f.block.type==="paragraph",y=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,w=null;b&&(A=se(v)),y&&(w=se(x));const E=b?e.offset:0,$=y?t.offset:0,P=d.length===2&&b&&y&&A!==null&&E===A.length&&$===0;let B="";const C={};if(y&&w){const T=te(w);let L=0;for(const M of T)if(M.insert&&typeof M.insert=="string"){const O=M.insert.length;L>=$?(B+=M.insert,M.attributes&&Object.assign(C,M.attributes)):L+O>$&&(B+=M.insert.slice($-L),M.attributes&&Object.assign(C,M.attributes)),L+=O}}if(b&&A&&E<A.length&&A.delete(E,A.length-E),P&&v instanceof S.XmlElement&&x instanceof S.XmlElement){const T=x.getAttribute("heading");T?v.setAttribute("heading",T):v.removeAttribute("heading");const L=Q(x,"align");L&&v.setAttribute("align",L);const M=Q(x,"lineSpacing");M?v.setAttribute("lineSpacing",M):q(v,"lineSpacing"),$h(x,v,!0);const O=Q(x,"pagination");O?v.setAttribute("pagination",O):q(v,"pagination");const F=Q(x,"tabStops");F?v.setAttribute("tabStops",F):q(v,"tabStops");for(const R of["oxmlAttrs","oxmlPPr"]){const D=Q(x,R);D?v.setAttribute(R,D):q(v,R)}const N=Q(x,"leftIndent");N?v.setAttribute("leftIndent",N):q(v,"leftIndent");const _=Q(x,"firstLineIndent");_?v.setAttribute("firstLineIndent",_):q(v,"firstLineIndent")}b&&A&&B?ne(A,A.length,B,C):!b&&y&&w&&$>0&&w.delete(0,Math.min($,w.length));for(let T=d.length-1;T>=0;T--){const L=d[T],M=L.isFirst&&b,O=!b&&L.isLast&&y;if(M||O)continue;const F=G(this.ydoc,L.block.id);if(F){const{yBlock:N,yParent:_,index:R}=F;if(_.length===1){if(L.block.type==="paragraph"){const D=qe(n,L.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 U=se(N);U&&U.length>0&&U.delete(0,U.length)}else{_.delete(R,1);const D=new S.XmlElement("paragraph");D.setAttribute("id",Y());const U=new S.XmlText;D.insert(0,[U]),_.insert(0,[D])}continue}_.delete(R,1)}}}),this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=H(r,this.ydoc,this.getDocument()),!0}deleteSingleParagraphSelection(e,t,n,i){const r=this.getDocument(),s=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=pn(r,a.paragraph,e,c);let g=null;this.transact(()=>{const p=J(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&&!s?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&&yi(p,d))});const u=g?Vr(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=X(i,e);if(!r)return!1;const s=G(this.ydoc,e);if(!s)return!1;const{yBlock:a,yParent:l,index:c}=s;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=se(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=se(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 s of i)t[s]!==void 0&&(r[s]=t[s]);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 s=n+r.text.length;if(s>t&&r.text.length>0&&(i=!0,!r.marks?.deletion))return!1;n=s}return i}splitParagraph(e,t){this.beforeOperationSelection=t;const n=this.getDocument();this.beforeOperationRelativeSelection=H(t,this.ydoc,n);const i=X(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 $=this.getCancelableParagraphMergeRecord(i,e.offset);if($&&this.suggestionEngine.rejectLiveSuggestion($.id)){const P={anchor:e,focus:e};return this.setSelectionAfterOperation(P),this.afterOperationRelativeSelection=H(P,this.ydoc,this.getDocument()),e}}const s=G(this.ydoc,e.block);if(!s)return null;const{yBlock:a,yParent:l,index:c}=s,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(($,P)=>P.type==="text"?$+P.text.length:$,0),m=this.suggestingMode&&p>0&&p<f&&wt.isTailFullyDeletionMarked(i,p),b=typeof h=="string"&&(p===0||p===f),y=this.suggestingMode&&typeof h=="string"&&p>0&&p<f,k=typeof h=="string",I=g?null:y?h:this.suggestingMode&&!b?ce():null,v=y||this.suggestingMode&&!b&&(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 C=a.getAttribute("heading"),T=a.getAttribute("styleId"),L=C!=null?!0:typeof T=="string"&&/^heading\d/i.test(T);Qs(a,B);const M=Q(a,"direction");if((M==="rtl"||M==="ltr")&&B.setAttribute("direction",M),!L){const _=Q(a,"align");_&&B.setAttribute("align",_);const R=a.getAttribute("styleId");R!=null&&B.setAttribute("styleId",R)}const O=Q(a,"borders");if(O!=null){const{upper:_,lower:R}=wt.splitBordersAttr(O);_?B.setAttribute("borders",_):q(B,"borders"),R?a.setAttribute("borders",R):q(a,"borders")}const F=new S.XmlText,N=L?null:pn(n,i,e,u);N&&B.setAttribute("_emptyTextMarks",JSON.stringify(N)),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,[F]),l.insert(x?c:c+1,[B]),g&&this.suggestionEngine.preserveSequenceAfterParagraphSplit(g,[a,B]),L&&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 $={block:k?e.block:this.suggestingMode&&v?r:e.block,offset:0},P={anchor:$,focus:$};return this.setSelectionAfterOperation(P),this.afterOperationRelativeSelection=H(P,this.ydoc,this.getDocument()),$}if(this.transact(()=>{let $=null;for(let U=0;U<a.length;U++){const j=a.get(U);if(j instanceof S.XmlText){$=j;break}}if(!$||i.type!=="paragraph")return;const P=te($);let B=0;const C=[];if(!m){for(const U of P)if(U.insert&&typeof U.insert=="string"){const j=U.insert.length;if(B+j<=p)B+=j;else if(B>=p)C.push(U);else{const z=p-B,K=U.insert.slice(z);K&&C.push({insert:K,...U.attributes&&{attributes:U.attributes}}),B=p}}p<$.length&&$.delete(p,$.length-p)}this.suggestionEngine.clearParagraphStructuralSuggestion(a),r=Y();const T=new S.XmlElement("paragraph");T.setAttribute("id",r),Qs(a,T);const L=Q(a,"align");L&&T.setAttribute("align",L);const M=a.getAttribute("styleId");M!=null&&T.setAttribute("styleId",M);const O=Q(a,"direction");(O==="rtl"||O==="ltr")&&T.setAttribute("direction",O);const F=Q(a,"borders");if(F!=null){const{upper:U,lower:j}=wt.splitBordersAttr(F);j?T.setAttribute("borders",j):q(T,"borders"),U?a.setAttribute("borders",U):q(a,"borders")}const N=new S.XmlText,_=pn(n,i,e,u),R=i.heading!==void 0&&So(n.stylesheet)!==void 0;let D=null;if(R&&C.length>0){const U=n.stylesheet,j=(i.styleId?Io(U,i.styleId):void 0)??Mi(U,i.heading),z=So(U);D=vo(j?.runMarks,z?.runMarks)}if(C.length>0){let U=0;for(const j of C)if(j.insert&&typeof j.insert=="string"){let z=j.attributes||{};if(D){z={...z};for(const[K,ae]of Object.entries(D))ae===!1||ae===void 0?delete z[K]:z[K]=ae}ne(N,U,j.insert,z),U+=j.insert.length}}else _&&T.setAttribute("_emptyTextMarks",JSON.stringify(_));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,[N]),l.insert(c+1,[T]),g&&this.suggestionEngine.preserveSequenceAfterParagraphSplit(g,[a,T]),R&&r&&(this.applyStylesheetHeadingDefaults(T,{type:"paragraph",id:r,heading:i.heading,styleId:i.styleId,children:[]},n,void 0),C.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 w={block:r,offset:0},E={anchor:w,focus:w};return this.setSelectionAfterOperation(E),this.afterOperationRelativeSelection=H(E,this.ydoc,this.getDocument()),w}applyFormatting(e,t,n,i,r){this.beforeOperationSelection=i;const s=this.getDocument();this.beforeOperationRelativeSelection=H(i,this.ydoc,s);let a=!1,l=null;const c=[];return this.transact(()=>{const d=this.getYContentFragment(),g=this.collectInlineFormattingRanges(e,t,d,s);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(s,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=te(p);let b=0;for(const y of m)if(y.insert&&typeof y.insert=="string"){const k=y.insert.length,I=b+k;if(b<f&&I>h&&!(y.attributes||{})[n]){a=!0;break e}b+=k}}for(const{yText:p,start:h,end:f,blockId:m,itemIndex:b}of g){const y=Math.max(0,f-h),k=this.suggestingMode&&l&&y>0?this.collectOverlappingTextSpans(p,h,y):[];if(this.suggestingMode&&l&&y>0&&m)for(const v of k)v.attributes?.insertion||v.attributes?.deletion||c.push({blockId:m,itemIndex:b,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&&y>0){const v=this.suggestionEngine.buildInlineSuggestionMetadataMarks(l,this.getFormattingDescriptionFromMarkKey(n));for(const x of k)x.attributes?.deletion||(re(p,x.start,x.length,I),!x.attributes?.insertion&&re(p,x.start,x.length,{formatChange:!0,...v,suggestionPriorAttributes:un(x.attributes)}))}else re(p,h,y,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&&re(a,l,d,t)}return}const i=ce(),r=this.suggestionEngine.buildInlineSuggestionMetadataMarks(i,n),s=[];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 b=h.attributes?.[f];return m===!1||m===null?b!=null&&b!==!1:b!==m})||(re(a,h.start,h.length,t),!h.attributes?.insertion&&(re(a,h.start,h.length,{formatChange:!0,...r,suggestionPriorAttributes:un(h.attributes)}),d&&s.push({blockId:d,itemIndex:g,start:h.start,end:h.start+h.length,attributes:h.attributes??{}})))}s.length>0&&this.suggestionEngine.saveLiveSuggestion({id:i,type:"inline-format",label:n,spans:s})}setFontFamily(e,t,n,i){this.beforeOperationSelection=i;const r=this.getDocument();return this.beforeOperationRelativeSelection=H(i,this.ydoc,r),this.transact(()=>{const s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,s,r),l=Se(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 s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,s,r),l=Se(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 s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,s,r),l=Se(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 s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,s,r),l=Se(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=sc(n);this.beforeOperationSelection=i;const s=this.getDocument();return this.beforeOperationRelativeSelection=H(i,this.ydoc,s),this.transact(()=>{const a=this.getYContentFragment(),l=this.collectInlineFormattingRanges(e,t,a,s),c=Se(s,e,t)===0;if(l.length===0){c&&this.updateBackgroundColorEmptyMarksAtPosition(e,r,s);return}this.formatRangesWithValue(l,{backgroundColor:r??null},"Highlight"),c&&this.updateBackgroundColorEmptyMarksAtPosition(e,r,s)}),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 s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,s,i),l=this.collectParagraphBlockIdsInRange(e,t,i);a.some(({start:c,end:d})=>d>c)&&(this.formatRangesWithValue(a,Bo,"Clear Formatting"),r=!0);for(const c of l){const d=J(this.ydoc,c);if(d)for(const g of Po)Q(d,g)!==void 0&&(q(d,g),r=!0)}Se(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 s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,s,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?re(c,d,u,{link:n}):re(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&&re(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 s=Math.max(0,r-i);if(s!==0)for(const a of this.collectOverlappingTextSpans(n,i,s)){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 s of this.collectOverlappingTextSpans(t,n,r)){const a=s.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=X(n,e);if(!i||i.type!=="code")return!1;const r=n.children.findIndex(s=>s.id===e);return r===-1?!1:(this.transact(()=>{const s=this.getYContentFragment().get(r);s instanceof S.XmlElement&&s.nodeName==="code"&&(t?(s.setAttribute("language",t),ac(t)&&(s.getAttribute("renderDiagram")===null&&s.setAttribute("renderDiagram","true"),s.getAttribute("showDiagramSource")===null&&s.setAttribute("showDiagramSource","true"))):s.removeAttribute("language"))}),!0)}setCodeBlockRenderDiagram(e,t){const n=this.getDocument(),i=X(n,e);if(!i||i.type!=="code")return!1;const r=n.children.findIndex(s=>s.id===e);return r===-1?!1:(this.transact(()=>{const s=this.getYContentFragment().get(r);s instanceof S.XmlElement&&s.nodeName==="code"&&(s.setAttribute("renderDiagram",String(t)),t&&s.getAttribute("showDiagramSource")===null&&s.setAttribute("showDiagramSource","true"))}),!0)}setCodeBlockShowDiagramSource(e,t){const n=this.getDocument(),i=X(n,e);if(!i||i.type!=="code")return!1;const r=n.children.findIndex(s=>s.id===e);return r===-1?!1:(this.transact(()=>{const s=this.getYContentFragment().get(r);s instanceof S.XmlElement&&s.nodeName==="code"&&s.setAttribute("showDiagramSource",String(t))}),!0)}setMathBlockContent(e,t){const n=this.getDocument(),i=X(n,e);if(!i||i.type!=="math"&&!Xt(i))return!1;const r=G(this.ydoc,e);return r?(this.transact(()=>{const s=r.yBlock;if(!(s instanceof S.XmlElement))return;const a=Xt(i)?"code":"math";if(s.nodeName!==a)return;let l=s.get(0);l instanceof S.XmlText||(l=new S.XmlText,s.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=X(n,e);if(!i||i.type!=="math"&&!Xt(i))return!1;const r=G(this.ydoc,e);return r?(this.transact(()=>{const s=r.yBlock;if(s instanceof S.XmlElement){if(Xt(i)&&s.nodeName==="code"){const a=t==="inline"?"latex-inline":"latex";s.setAttribute("language",a),s.getAttribute("renderDiagram")===null&&s.setAttribute("renderDiagram","true"),s.getAttribute("showDiagramSource")===null&&s.setAttribute("showDiagramSource","true");return}s.nodeName==="math"&&s.setAttribute("displayMode",t)}}),!0):!1}setMathBlockAlign(e,t){const n=this.getDocument(),i=X(n,e);if(!i||i.type!=="math"&&!Xt(i))return!1;if(Xt(i))return!0;const r=n.children.findIndex(s=>s.id===e);return r===-1?!1:(this.transact(()=>{const s=this.getYContentFragment().get(r);s instanceof S.XmlElement&&s.nodeName==="math"&&s.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 s=this.getYContentFragment(),a=s.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)),fn(c,t);{const h=We(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]),s.delete(e,1),s.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},s={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,s={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,s,{anchor:r,focus:r},i))return;a=!0;const p=l();p&&(r=p),s={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(y=>y.children.some(k=>k.type==="text"&&k.text.length>0)))return null;const r=ct(Li(this.getDocument(),e,n)?.marks);if(r?.fontFamily===Le&&delete r.fontFamily,r&&(t=t.map(y=>y.type==="paragraph"?{...y,children:y.children.map(k=>k.type==="text"?{...k,marks:{...r,...k.marks??{}}}:k)}:y)),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 s=this.getDocument();this.beforeOperationRelativeSelection=H(n,this.ydoc,s);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=y=>{if(!y.id)return null;let k=0;for(const I of y.children)I.type==="text"&&(k+=I.text.length);return{block:y.id,offset:k}},b=y=>y.id?y:{...y,id:Y()};try{this.transact(()=>{const k=n.anchor&&n.focus&&Se(s,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},U=n.anchor.block===D.block&&n.anchor.offset===D.offset,j=n.focus.block===D.block&&n.focus.offset===D.offset,z=D,K=U?{block:n.focus.block,offset:n.focus.offset}:j?{block:n.anchor.block,offset:n.anchor.offset}:Se(s,n.anchor,n.focus)<=0?{block:n.focus.block,offset:n.focus.offset}:{block:n.anchor.block,offset:n.anchor.offset},ae=this.getParagraphOffsetForPosition(z,s),xe=this.getParagraphOffsetForPosition(K,s);ae&&xe&&this.arePathsEqual(ae.paragraphPath,xe.paragraphPath)&&(d=xe.offset);const Xe=ae?.offset??z.offset;this.deleteSelection({block:z.block,offset:z.offset},{block:K.block,offset:K.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:z.block,offset:z.offset},focus:{block:z.block,offset:z.offset}});const Oe=this.getDocument(),W=X(Oe,z.block);(W?.type==="paragraph"||W?.type==="list")&&W.id&&(I={block:W.id,offset:Xe})}const v=d!==null?s:this.getDocument(),x=this.getBlockContextById(v,I.block);if(!x){a=null;return}if(x.block.type==="list"){const D=t[0],U=D.children.filter(j=>j.type==="text").map(j=>j.text).join("");if(U){const j=D.children.find(K=>K.type==="text")?.marks||null,z=this.listOperations.insertTextInListItem(I,U,j);z&&(a=z)}return}if(x.block.type!=="paragraph"){a=null;return}const A=x.block;if(!A||A.type!=="paragraph"){a=null;return}const w=[],E=this.getParagraphOffsetForPosition(I,v)?.offset??0,$=d??E;let P=0;for(let D=0;D<A.children.length;D++){const U=A.children[D];if(U.type==="text"){const j=P;if(P+U.text.length>$){const z=Math.max(0,$-j);z<U.text.length&&w.push({type:"text",text:U.text.substring(z),marks:U.marks})}P+=U.text.length}}const B=w.length>0&&w.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 U={block:A.id,offset:D};this.deleteSelection(I,U,{anchor:I,focus:U},{anchor:I,focus:I})}const C=t[0],T=J(this.ydoc,I.block);if(!T){a=null;return}const L=se(T);if(!L){a=null;return}if(L.length===0&&C.type==="paragraph"){C.heading!==void 0?T.setAttribute("heading",String(C.heading)):T.removeAttribute("heading"),C.align?T.setAttribute("align",C.align):q(T,"align"),C.lineSpacing!==void 0?T.setAttribute("lineSpacing",String(C.lineSpacing)):q(T,"lineSpacing");for(const j of Ka)q(T,j);fn(T,C);{const j=We(C);j!==void 0?T.setAttribute("pagination",j):q(T,"pagination")}C.styleId!==void 0?T.setAttribute("styleId",C.styleId):T.removeAttribute("styleId"),C.direction!==void 0?T.setAttribute("direction",C.direction):q(T,"direction"),C.tabStops!==void 0?T.setAttribute("tabStops",C.tabStops):q(T,"tabStops"),C.borders!==void 0?T.setAttribute("borders",C.borders):q(T,"borders"),C.shading!==void 0?T.setAttribute("shading",C.shading):q(T,"shading");const D=Re(C.leftIndent);D!==void 0?T.setAttribute("leftIndent",String(D)):q(T,"leftIndent");const U=De(C.firstLineIndent);U!==void 0?T.setAttribute("firstLineIndent",String(U)):q(T,"firstLineIndent")}const M=C.children.filter(D=>D.type==="text"),O=this.insertTextNodes(I,M);if(!O){a=null;return}if(g=O,a=O,t.length===1&&!B){u=O.block;return}const F=G(this.ydoc,I.block);if(!F)return;const N=F.yParent;let _=F.index+1;if(l){const D=[];let U=null;for(let j=1;j<t.length;j++){const z=b(t[j]);this.insertParagraphInternal(_,z,N),D.push(z.id),_++}if(B){const j={type:"paragraph",id:Y(),children:w.map(ae=>({type:"text",text:ae.text,marks:ae.marks?{...ae.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 z=Re(A.leftIndent);z!==void 0&&(j.leftIndent=z);const K=De(A.firstLineIndent);K!==void 0&&(j.firstLineIndent=K),this.insertParagraphInternal(_,j,N),U=j.id,_++}c={insertedParagraphIds:D,remainderParagraphId:U};return}let R=I.block;for(let D=1;D<t.length;D++){const U=b(t[D]);this.insertParagraphInternal(_,U,N),R=U.id,_++}if(u=R,B){const D=t.length>1?N.get(_-1):T;if(D instanceof S.XmlElement){let U=null;for(let j=0;j<D.length;j++){const z=D.get(j);if(z instanceof S.XmlText){U=z;break}}if(U){let j=U.length;h=j,f=R;for(const z of w){if(!z.text.length)continue;const K={...z.marks||{}};U.insert(j,z.text,K),j+=z.text.length}}}}});const y=this.getDocument();if(l&&c){const{insertedParagraphIds:k,remainderParagraphId:I}=c;if(k.length>0){const v=k[k.length-1],x=X(y,v);x&&x.type==="paragraph"?a=m(x):a={block:v,offset:0}}else if(I!==null){const v=X(y,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=X(y,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(y){return console.error("Error in pasteParagraphs:",y),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)),fn(i,n);{const c=We(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 s=De(n.firstLineIndent);s!==void 0&&i.setAttribute("firstLineIndent",String(s));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(s=>{const a=new S.XmlElement("list-item");Ct(a,s),a.setAttribute("id",s.id||Y()),i.variant==="todo"&&a.setAttribute("checked",String(s.checked??!1)),s.indentLevel!==void 0&&s.indentLevel>0&&a.setAttribute("indentLevel",String(s.indentLevel)),s.direction!==void 0&&a.setAttribute("direction",s.direction);const l=new S.XmlText;let c=0;s.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 s of n.children)r+=s.text??"";return lc(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 s=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"&&s==="ltr"?q(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?q(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?q(a,"direction"):a.setAttribute("direction",t.direction)),Object.prototype.hasOwnProperty.call(t,"tabStops")&&(t.tabStops===null||t.tabStops===void 0?q(a,"tabStops"):a.setAttribute("tabStops",t.tabStops)),Object.prototype.hasOwnProperty.call(t,"borders")&&(t.borders===null||t.borders===void 0?q(a,"borders"):a.setAttribute("borders",t.borders)),Object.prototype.hasOwnProperty.call(t,"shading")&&(t.shading===null||t.shading===void 0?q(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={};$i(l,Q(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=We(l);c===void 0?q(a,"pagination"):a.setAttribute("pagination",c)}if(Object.prototype.hasOwnProperty.call(t,"leftIndent")){const l=Re(t.leftIndent);l===void 0?q(a,"leftIndent"):a.setAttribute("leftIndent",String(l))}if(Object.prototype.hasOwnProperty.call(t,"firstLineIndent")){const l=De(t.firstLineIndent);l===void 0?q(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,s=Mi(r,i);if(!r||!s)return!1;const a=(t.styleId?Io(r,t.styleId):void 0)??Mi(r,t.heading);i!==void 0&&s.styleId.toLowerCase()!=="normal"?e.setAttribute("styleId",s.styleId):e.removeAttribute("styleId");const l=a?.paragraphAttrs??{},c=s.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?q(e,f):e.setAttribute(f,String(m))}const u=["keepNext","keepLines","widowControl"];if(u.some(f=>d(l,f)||d(c,f))){const f={};$i(f,Q(e,"pagination"));for(const b of u)!d(l,b)&&!d(c,b)||(c[b]===void 0?delete f[b]:f[b]=c[b]);const m=We(f);m===void 0?q(e,"pagination"):e.setAttribute("pagination",m)}const p=vo(a?.runMarks,s.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:b,start:y,end:k}of m){const I=Math.max(0,k-y);I>0&&re(b,y,I,p)}}else yi(e,s.runMarks);return!0}clearFontSizeMarksForHeadingChange(e,t){if(e.type!=="paragraph"||!e.id)return;const n=e.children.reduce((s,a)=>a.type==="text"?s+a.text.length:s,0);if(!e.children.some(s=>s.type==="text"&&s.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:s,start:a,end:l}of r){const c=Math.max(0,l-a);c>0&&re(s,a,c,{fontSize:!1})}}updateParagraphAttributesById(e,t,n,i){const r=X(this.getDocument(),e);if(!r||r.type!=="paragraph"&&r.type!=="list")return!1;const s=J(this.ydoc,e);if(!s)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(X(a,e)??void 0,t);return this.transact(()=>{if(Object.prototype.hasOwnProperty.call(t,"align")&&(t.align===void 0||t.align==="left"&&g==="ltr"?q(s,"align"):s.setAttribute("align",t.align)),Object.prototype.hasOwnProperty.call(t,"heading")&&(t.heading===void 0?s.removeAttribute("heading"):s.setAttribute("heading",String(t.heading)),this.applyStylesheetHeadingDefaults(s,r,a,t.heading)||this.clearFontSizeMarksForHeadingChange(r,a)),Object.prototype.hasOwnProperty.call(t,"lineSpacing")&&(t.lineSpacing===void 0?q(s,"lineSpacing"):s.setAttribute("lineSpacing",String(t.lineSpacing))),Object.prototype.hasOwnProperty.call(t,"styleId")&&(t.styleId===null||t.styleId===void 0?s.removeAttribute("styleId"):s.setAttribute("styleId",t.styleId)),Object.prototype.hasOwnProperty.call(t,"direction")&&(t.direction===null||t.direction===void 0?q(s,"direction"):s.setAttribute("direction",t.direction)),Object.prototype.hasOwnProperty.call(t,"tabStops")&&(t.tabStops===null||t.tabStops===void 0?q(s,"tabStops"):s.setAttribute("tabStops",t.tabStops)),Object.prototype.hasOwnProperty.call(t,"borders")&&(t.borders===null||t.borders===void 0?q(s,"borders"):s.setAttribute("borders",t.borders)),Object.prototype.hasOwnProperty.call(t,"shading")&&(t.shading===null||t.shading===void 0?q(s,"shading"):s.setAttribute("shading",t.shading)),Object.prototype.hasOwnProperty.call(t,"keepNext")||Object.prototype.hasOwnProperty.call(t,"keepLines")||Object.prototype.hasOwnProperty.call(t,"widowControl")){const u={};$i(u,Q(s,"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=We(u);p===void 0?q(s,"pagination"):s.setAttribute("pagination",p)}if(Object.prototype.hasOwnProperty.call(t,"leftIndent")){const u=Re(t.leftIndent);u===void 0?q(s,"leftIndent"):s.setAttribute("leftIndent",String(u))}if(Object.prototype.hasOwnProperty.call(t,"firstLineIndent")){const u=De(t.firstLineIndent);u===void 0?q(s,"firstLineIndent"):s.setAttribute("firstLineIndent",String(u))}this.suggestingMode&&d&&(this.suggestionEngine.clearElementStructuralSuggestion(s),this.suggestionEngine.setElementStructuralSuggestion(s,"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=X(this.getDocument(),e);if(!r||r.type!=="toc")return!1;const s=J(this.ydoc,e);return s?(this.beforeOperationSelection=n,this.beforeOperationRelativeSelection=H(n,this.ydoc,this.getDocument()),this.transact(()=>{Object.prototype.hasOwnProperty.call(t,"fontFamily")&&(t.fontFamily==null||t.fontFamily===""?s.removeAttribute("fontFamily"):s.setAttribute("fontFamily",t.fontFamily)),Object.prototype.hasOwnProperty.call(t,"fontSize")&&(t.fontSize==null?s.removeAttribute("fontSize"):s.setAttribute("fontSize",String(t.fontSize))),Object.prototype.hasOwnProperty.call(t,"color")&&(t.color==null||t.color===""?s.removeAttribute("color"):s.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 s of e.children){if(s.type!=="text")continue;const a=r,l=r+s.text.length,c=Math.max(t,a),d=Math.min(n,l);if(c<d&&i.push({type:"text",text:s.text.slice(c-a,d-a),marks:this.suggestionEngine.sanitizePreviewMarks(s.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}}}),s=r(e.children,"deletion"),a=r(t.children,"insertion"),l=s.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:[...s,...d?[{type:"text",text:" "}]:[],...a],structuralSuggestionId:n,structuralSuggestionKind:"change",structuralSuggestionLabel:i}}canBridgeListItemChangeAsInline(e,t){return vn.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,s=r?null:G(this.ydoc,e),a=r?n.yParent:s?.yParent,l=r?n.index:s?.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"){Or(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(),s=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=X(r,d.id)??X(t,d.id),u=this.suggestionEngine.getBlockInsertSuggestionIdForBlock(g),p=u?this.suggestionEngine.getLiveSuggestion(u):void 0;if(!g)return null;if(s.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=>!s.has(d)))return null;return this.suggestionEngine.rejectLiveSuggestions([...a])===0?null:{success:!0,planningSuggestionIds:[],agentFeedback:`Removed pending inserted block${s.size===1?"":"s"} ${[...s].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 s=r.id;if(n.add(s),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=zt(t,s);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){t||(t="default-"+Date.now());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=Bc(this,u,g.find??"")}catch(f){return{success:!1,error:f instanceof Error?f.message:String(f),failure:Vt(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??Qe,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=bu(e,t,this.preprocessorSession,this.getDocument())}catch(a){const l=a instanceof Rr?a:void 0,c=l?$e(l.action):void 0;return{success:!1,failure:Vt(l?.originalError??a),error:a instanceof Error?a.message:String(a),...l?{failedActions:[{actionIndex:l.actionIndex,actionName:l.action.name,error:l.message,failure:Vt(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 s=rl(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 C=this.suggestionEngine.createLiveSuggestionProjection("accept"),T=this.suggestionEngine.createLiveSuggestionProjection("reject");u=C.doc,p=T.doc,h=this.cloneYDoc(C.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,b=this.tryCancelInsertedBlockForRemoveAction(a.actions,m);if(b)return b;const{anchorsByAction:y,failures:k,alreadySatisfied:I}=og(h,a.actions,t,m,{rejectUnchangedAction:!0,continueAfterError:!0,canonicalDocument:()=>he(h),skipContextForFirstAction:!0});d("validated");const v=a.actions.length===1?$e(a.actions[0])?.styleEffects:void 0;if(k.length>0){const C=T=>`${T.actionName}: ${T.error}`;return k.length===1?{success:!1,error:`Failed operation: ${C(k[0])}`,failedActions:k,failure:k[0]?.failure}:{success:!1,error:`Failed operations: ${k.map(C).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?Qi(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?Qi(a.actions[0]):void 0)??rl(e.actions,r.actions,y)??s,A=he(h);d("materialized validation document");const w=new Set,E=C=>{if(!C)return;w.add(C);const T=X(m,C)??X(A,C);T?.id&&w.add(T.id)};for(const C of y)for(const T of C)typeof T?.paragraphId=="string"&&T.paragraphId.length>0&&E(T.paragraphId);for(const C of a.actions){const T=C?.name,L=C?.arguments;(T==="replace"||T==="replace_all"||T==="replace_many"||T==="replace_block"||T==="remove_block"||T==="set_block_attribute"||T==="clear_block_formatting")&&typeof L?.id=="string"&&L.id.length>0&&E(L.id),typeof L?.referenceId=="string"&&L.referenceId.length>0&&E(L.referenceId),typeof L?.tableId=="string"&&L.tableId.length>0&&E(L.tableId)}const $=Oh(m,a.actions);for(const C of $)w.add(C.currentBlockId),w.add(C.finalBlockId);this.suggestionEngine.expandPendingSequenceBlockIds(w);const P=w.size>0||$.length>0?{...w.size>0?{affectedBlockIds:Array.from(w)}:{},...$.length>0?{replacementBlockMatches:$}:{}}:void 0,B=this.suggestionEngine.applyValidatedAgentActionsAsSuggestions({validationFork:h,baseFork:f,flattenOptions:P,toolCallId:t,originalActions:e.actions,processedActions:r.actions,validationAnchorsByAction:y,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:s}}getAllOperations(){return[]}onRemoteDocumentChange(e){}insertBlock(e,t,n,i){this.beforeOperationSelection=n;const r=this.suggestingMode?ce():null,s=e.id||Y(),a=this.getDocument();if(t<0||t>a.children.length)return!1;const l=Ge().getHandlerForBlock(e);this.beforeOperationRelativeSelection=l.allowsInternalCursor()?H(n,this.ydoc,a):null,this.transact(()=>{const d=this.getYContentFragment(),g={...e,id:s};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 b=new S.XmlElement("list-item");Ct(b,m),m.id&&b.setAttribute("id",m.id),m.checked!==void 0&&b.setAttribute("checked",String(m.checked)),m.indentLevel!==void 0&&b.setAttribute("indentLevel",String(m.indentLevel)),m.direction!==void 0&&b.setAttribute("direction",m.direction);const y=new S.XmlText;let k=0;m.children.forEach(I=>{if(I.type==="text"){const v=I.marks?{...I.marks}:void 0;ne(y,k,I.text,v),k+=I.text.length}}),b.insert(0,[y]),f.push(b)}),h.insert(0,f),u=h}else u=l.toYjs(g,this.ydoc);r&&u instanceof S.XmlElement&&(u.setAttribute("id",s),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:s,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 vg(this.kernel)}addComment(e,t,n,i,r){return wg(this.kernel,e,t,n,i,r)}addCommentToRanges(e,t,n){return kr(this.kernel,e,t,n)}addBlockComment(e,t,n){return sa(this.kernel,e,t,n)}addCommentForSuggestion(e,t,n){return this.addCommentForSuggestions([e],t,n)}getSuggestionCommentRanges(e){return xg(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})),s={...n,suggestionId:i[0],...i.length>1?{relatedSuggestionIds:i}:{}};if(r.length>0)return kr(this.kernel,r,t,s);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 sa(this.kernel,c,t,s)}return null}replyToComment(e,t,n){return Tg(this.kernel,e,t,n)}relinkCommentSuggestionIds(){return Bg(this.kernel,e=>this.suggestionEngine.canResolveLiveSuggestion(e))}resolveCommentsForSettledSuggestions(e){return Pg(this.kernel,e,t=>this.suggestionEngine.canResolveLiveSuggestion(t))}setCommentResolved(e,t){return Cg(this.kernel,e,t)}deleteComment(e){return $g(this.kernel,e)}isBlockInsideFootnote(e,t){return Fg(e,t)}getFootnotes(){return Eg(this.kernel)}renumberFootnotes(){return St(this.kernel)}materializePendingFootnoteBodies(){return la(this.kernel)}addPastedFootnoteBodies(e){const t=this.getYNotesFragment();t.insert(t.length,e.map(n=>this.kernel.blockToYjsElement(n))),this.reconcileFootnotes()}reconcileFootnotes(){Lg(this.kernel)}insertFootnote(e,t,n,i="footnote"){return Ng(this.kernel,e,t,n,i)}setFootnoteBodyText(e,t){return Og(this.kernel,e,t)}replaceFootnoteBodyText(e,t,n,i=!1){return Rg(this.kernel,e,t,n,i)}convertAllNoteKinds(e){return Dg(this.kernel,e)}removeFootnote(e){return _g(this.kernel,e)}blockToYjsElement(e){const t={...e,id:e.id||Y()};return t.type==="list"?ke(t):Ge().getHandlerForBlock(t).toYjs(t,this.ydoc)}insertBlockAfterId(e,t,n,i){const r=G(this.ydoc,t);if(!r)return!1;const{yParent:s,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)),s.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:s,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)),s.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:s}=r;if(!(s instanceof S.XmlElement))return!1;const a=s.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)),s.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 s=r.children[e];if(s.type!==t.type)return console.warn(`[DocumentMutator] updateBlock type mismatch: ${s.type} -> ${t.type}`),!1;const a=Ge().getHandlerForBlock(t);return this.beforeOperationRelativeSelection=a.allowsInternalCursor()?H(n,this.ydoc,r):null,Tt(this.ydoc)&&Ul(this.ydoc),this.transact(()=>{const l=this.getYContentFragment();if(e<0||e>=l.length)return;const c={...t,id:t.id||s.id||Y()},d=l.get(e);if(t.type==="list"&&d instanceof S.XmlElement&&d.nodeName==="list")Or(d,c);else{const g=c.type==="list"?ke(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(),s=X(r,e);if(!s)return!1;if(s.type!==t.type)return console.warn(`[DocumentMutator] updateBlockById type mismatch: ${s.type} -> ${t.type}`),!1;const a=G(this.ydoc,e);if(!a)return!1;const{yParent:l,index:c}=a,d=Ge().getHandlerForBlock(t),g=this.suggestingMode?ce():null;let u=t,p=null;if(this.suggestingMode&&g&&s.type==="table"&&t.type==="table"){const h=this.suggestionEngine.buildSuggestedTableChange(s,t,g);if(h)u=h.liveBlock,p=h.record;else if(!this.suggestionEngine.hasSameTableGeometry(s,t))return!1}return this.beforeOperationRelativeSelection=d.allowsInternalCursor()?H(n,this.ydoc,r):null,this.transact(()=>{const h={...u,id:u.id||s.id||Y()},f=l.get(c);if(u.type==="list"&&f instanceof S.XmlElement&&f.nodeName==="list")Or(f,h);else{const m=h.type==="list"?ke(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(!X(r,e))return!1;const s=G(this.ydoc,e);if(!s)return!1;const{yBlock:a,yParent:l,index:c}=s;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)),fn(g,t);{const m=We(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 b={...m.marks||{}};ne(h,f,m.text,b),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 s=this.getDocument(),a=s.children[e];if(!a||a.type!=="list"||a.variant!=="todo"||t<0||t>=a.children.length)return!1;this.beforeOperationSelection=i;const l=Ge().getHandlerForBlock(a);return this.beforeOperationRelativeSelection=l?.allowsInternalCursor()?H(i,this.ydoc,s):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 s=this.getDocument(),a=X(s,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=Ge().getHandlerForBlock(a);return this.beforeOperationRelativeSelection=d?.allowsInternalCursor()?H(i,this.ydoc,s):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}};ol.DEFERRED_IDENTITY_REPAIR_MS=1500;let Si=ol;function Vr(o,e,t){const n=i=>i&&i.block===e?{...i,offset:Si.remapOffsetAcrossReplacementNormalization(i.offset,t)}:i;return{anchor:n(o.anchor),focus:n(o.focus)}}const Rh=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_FONT_FAMILY:Le,DocumentMutator:Si,MAX_BULK_LIVE_SUGGESTION_RESOLUTION_PASSES:qa,copyMarksForUserInsertion:Ja,enrichReplaceBlockFeedbackWithChangeSummary:il,extractTextForChangeSummary:Me,parseLayeredInsertion:hn,parseSuggestionPriorAttributes:bi,remapSelectionAcrossReplacementNormalization:Vr,sanitizeSuggestionPriorAttributes:un},Symbol.toStringTag,{value:"Module"}));export{ee as A,Si as D,li as P,Yc as a,zc as b,rs as c,Vi as d,me as e,qi as f,es as g,Ki as h,Gs as i,Ro as j,$t as k,Mn as l,Cc as m,qo as n,Pc as o,Go as p,Qo as q,Rc as r,ts as s,ji as t,et as u,zo as v,Zo as w,Rh as x};
|