revise 2.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/assets/{historyMaterializeWorker-CoAX9ZAi.js → historyMaterializeWorker-C4uxcZEh.js} +1 -1
- package/backend.d.ts +22 -0
- package/backend.js +1 -1
- package/chunks/AgentPageRenderer-BIf_Fza8.js +1 -0
- package/chunks/AgentPageRenderer-DT9sNxEn.js +1 -0
- package/chunks/{AttachmentDocumentImporter-dNMtkxrv.js → AttachmentDocumentImporter-BUavYRxO.js} +1 -1
- package/chunks/{AttachmentDocumentImporter-DSic_6At.js → AttachmentDocumentImporter-DGwfDJSH.js} +1 -1
- package/chunks/{BidiText-B4Hzrjg9.js → BidiText-D7LYTAUL.js} +1 -1
- package/chunks/DocumentMutator-CjN7Kk-X.js +31 -0
- package/chunks/DocumentScrubber-C9ZZEcYW.js +1 -0
- package/chunks/DocumentScrubber-DrgzBlx4.js +1 -0
- package/chunks/DocumentScrubber-W0EfGmL-.js +1 -0
- package/chunks/{DocxConverter-COV6CjUM.js → DocxConverter-Be3uPNcD.js} +3 -3
- package/chunks/{DocxConverter-B7P52lw7.js → DocxConverter-CGYMfz-j.js} +6 -6
- package/chunks/{DocxConverter-Cq_zCEJC.js → DocxConverter-DabDLfsu.js} +6 -6
- package/chunks/{DocxGraft-CJ12C9WP.js → DocxGraft-B6W7fbh4.js} +1 -1
- package/chunks/{DocxGraft-DcmFuUkd.js → DocxGraft-Cj7v78BO.js} +1 -1
- package/chunks/DocxGraft-Duvo2cpy.js +1 -0
- package/chunks/FileImporter-CjUX2S4s.js +1 -0
- package/chunks/FileImporter-DtkbI6rF.js +1 -0
- package/chunks/{HtmlConverter-JvRlkQM3.js → HtmlConverter-ikXImzTY.js} +1 -1
- package/chunks/{MarkdownConverter-B-tPY7X3.js → MarkdownConverter-CFrcLyO_.js} +2 -2
- package/chunks/{OdtConverter-DYHnR4E8.js → OdtConverter-BFT_P8SI.js} +1 -1
- package/chunks/OdtConverter-Cnda9T0q.js +1 -0
- package/chunks/OdtConverter-WdwwXKVM.js +1 -0
- package/chunks/PdfConverter-D7UM58vc.js +21 -0
- package/chunks/PdfConverter-TB-QPw29.js +21 -0
- package/chunks/PdfConverter-wVP63986.js +21 -0
- package/chunks/PdfImportService-Dj1-3L2B.js +2 -0
- package/chunks/PdfImportService-OE9G383I.js +2 -0
- package/chunks/{RtfConverter-oIwzoqCD.js → RtfConverter-D-oqPWNl.js} +5 -5
- package/chunks/{RtfConverter-BQGge3K-.js → RtfConverter-D9zhE07-.js} +5 -5
- package/chunks/{RtfConverter-CMfZ4olw.js → RtfConverter-DZgwU-_R.js} +1 -1
- package/chunks/{TableBorders-BLkZYt1k.js → TableBorders-BorZS8aZ.js} +1 -1
- package/chunks/{TxtConverter-C1lp6dBS.js → TxtConverter-BYazsp6P.js} +3 -3
- package/chunks/ar-C8zx2RwP.js +8 -0
- package/chunks/backend-MFpDFVrD.js +1 -0
- package/chunks/base64-BNMNG-lN.js +1 -0
- package/chunks/{browser-module-6b2Fq-5C.js → browser-module-BbaxnHNK.js} +1 -1
- package/chunks/{browser-module-CkO57IPL.js → browser-module-D2ixluMg.js} +1 -1
- package/chunks/capture-qC26xmfy.js +1 -0
- package/chunks/{carrier-WgcRSu7a.js → carrier-BWONvrA7.js} +1 -1
- package/chunks/de-ByQFqecF.js +8 -0
- package/chunks/es-PHpJXv5S.js +8 -0
- package/chunks/{footnoteFlatten-CW-DUcgK.js → footnoteFlatten-Bdnn_bz1.js} +1 -1
- package/chunks/{graftExport-CVg7PO2A.js → graftExport-CP3h2T88.js} +1 -1
- package/chunks/index-CjeGoI2g.js +351 -0
- package/chunks/index-D7V8zn4w.js +36 -0
- package/chunks/index-DyOcu9mD.js +351 -0
- package/chunks/{index.es-DOqegDGr.js → index.es-B97tjxvW.js} +1 -1
- package/chunks/{index.es-tXDO0RMv.js → index.es-mTU7Sl3w.js} +1 -1
- package/chunks/{jspdf.es.min-CzYti8jo.js → jspdf.es.min-DGiD4mlU.js} +1 -1
- package/chunks/{jspdf.es.min-ejWOGhkJ.js → jspdf.es.min-Mykp4BZO.js} +1 -1
- package/chunks/{pseudoLocale-CdBtPHRi.js → pseudoLocale-C90lXrPg.js} +1 -1
- package/chunks/{pseudoLocale-DEVWLkGC.js → pseudoLocale-UA_TkGrH.js} +1 -1
- package/chunks/serverDocumentSession-CRZSb5SO.js +11 -0
- package/chunks/signatures-CsL_TjvW.js +1 -0
- package/full.js +1 -1
- package/index.d.ts +27 -4
- package/index.js +1 -1
- package/package.json +2 -2
- package/root.js +2 -2
- package/style.css +1 -1
- package/chunks/AgentPageRenderer-C0n4EnuW.js +0 -1
- package/chunks/AgentPageRenderer-DURfmiu0.js +0 -1
- package/chunks/DocxGraft-CQpvFcYb.js +0 -1
- package/chunks/FileImporter-DVnYOJHp.js +0 -1
- package/chunks/FileImporter-q9mCch0J.js +0 -1
- package/chunks/OdtConverter-Br81BSoJ.js +0 -1
- package/chunks/OdtConverter-CQjh0vlo.js +0 -1
- package/chunks/PdfConverter-D26rXumc.js +0 -21
- package/chunks/PdfConverter-DGZpUSVf.js +0 -21
- package/chunks/PdfConverter-DZzVP0-B.js +0 -21
- package/chunks/PdfImportService-CBD8TL1k.js +0 -2
- package/chunks/PdfImportService-D6uUKGMf.js +0 -2
- package/chunks/ar-kgSWdrXF.js +0 -8
- package/chunks/backend-Cq-khfdG.js +0 -1
- package/chunks/base64-CfDUyGi8.js +0 -36
- package/chunks/capture-DU3MC7tb.js +0 -1
- package/chunks/de-C2QTHrqo.js +0 -8
- package/chunks/es-BKboUn4q.js +0 -8
- package/chunks/index-CLw_BlSL.js +0 -353
- package/chunks/index-F-kHIwWT.js +0 -353
- package/chunks/serverDocumentSession-DZrYbdpk.js +0 -42
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import{r as Ve,p as Ce,c as ro,a as oo,e as bl,n as xi,f as yl,j as kl,H as Ai,S as Sl,k as kn,l as so,q as wi,s as Re,u as ao,v as De,w as Y,x as te,z as Il,A as vl,B as xl,C as Al,D as wl,E as lo,P as Ge,F as Ti,G as Ci,I as co,J as Tl,K as go,L as q,M as ye,y as fe,N as G,O as ee,Q as ne,T as ct,U as J,V as zt,W as ie,X as oe,Y as uo,Z as ho,_ as Cl,$ as fo,a0 as Ye,a1 as Ht,a2 as Pl,a3 as Bl,a4 as Fl,a5 as Sn,a6 as Ml,a7 as El,a8 as $l,a9 as gt,aa as Ll,ab as po,ac as Nl,ad as Ol,ae as Rl,af as mo,ag as Dl,ah as le,ai as Pi,aj as dt,ak as Tt,al as In,am as Ct,an as bo,ao as vn,ap as xn,aq as _l,ar as An,as as jl,at as Xl,d as Bi,au as yo,av as ko,aw as So,ax as Ul,ay as Fi,az as zl,aA as Hl,aB as Wl,aC as Yl,aD as ze,aE as ql,aF as Mi,aG as Jl,aH as Kl,aI as Vl,aJ as Gl,aK as Ql,aL as Ei,aM as Zl,aN as ec,aO as Io}from"./backend-MFpDFVrD.js";import{a as X,f as Wt,r as tc,h as nc,i as ic,j as qe,t as wn,k as ke,e as Je,l as vo,m as $i,n as Li,o as Qe,p as ut,q as xo,s as Pt,u as Ni,v as rc,w as oc,x as sc}from"./index-D7V8zn4w.js";import{e as ac,r as lc,s as cc,p as gc,i as dc}from"./ListNumbering-Qlu6AuRZ.js";import{i as Ao}from"./HorizontalRuleOrnaments-gmUZ3R7Q.js";import{a as uc,R as Ze,A as wo,s as To,b as Co,c as Oi,d as Po}from"./DocumentStylesheet-byN5dtC6.js";import{b as Bt}from"./TableGrid-DVWaRZv0.js";import{p as Tn,a as Bo,c as Fo,b as Ri,d as hc,e as fc,s as Cn,f as Mo,g as Eo,h as pc,i as mc,n as $o}from"./TableBorders-BorZS8aZ.js";import{h as _e,H as Yt,D as bc,C as Lo,a as No,b as Oo,n as yc,g as kc,r as Sc}from"./BidiText-D7LYTAUL.js";import*as S from"yjs";import{j as qt,i as Ic}from"./signatures-CsL_TjvW.js";import{MarkdownConverter as Pn}from"./MarkdownConverter-CFrcLyO_.js";function vc(o){const e=o.children.filter(t=>t.type==="text");return e.length===0?[{type:"text",text:""}]:e}function Bn(o){return vc(o).reduce((e,t)=>e+t.text.length,0)}function xc(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+=Bn(n.children[r]),r<n.children.length-1&&(i+=1);return{block:t.id,offset:i}}return{block:t.id,offset:0}}class me 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 Jt(o){return o instanceof me?{code:o.code,phase:o.phase,retryable:o.retryable,mutationOutcome:o.mutationOutcome,details:o.details}:void 0}const Ro=o=>o.replace(/\\+u([0-9a-fA-F]{4})/g,(e,t)=>String.fromCharCode(Number.parseInt(t,16)));function Do(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 Ac(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 wc(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=Ac(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 Tc=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"]),Cc=/[&<>"']/,Pc=/[&<>"']/g,Bc={"&":"&","<":"<",">":">",'"':""","'":"'"};function Fc(o){return Bc[o]??o}function Mc(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 Fn=null;function Di(o){return Fn||(Fn=new DOMParser().parseFromString("","text/html")),Fn.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}),Fn}function Ec(o,e={}){return!o||e.code||e.latex?o:Ro(o.replace(/\\+(["'])/g,"$1"))}function _o(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 pe(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 _i=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:_o(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(`
|
|
2
|
+
`);return i&&r.length>0?`${i}
|
|
3
|
+
${r}`:i||r}static toInternalImageHtml(e){return this.imageBlockToHtml(e,!0)}static toInternalHtml(e){return this.toAgentHtml(e,{scanDocumentFontFamily:!1,includeImageSources:!0,includeZeroListLevels:!0})}static pageLayoutToHtmlComment(e){const t=e.pageless===!0;if(!e.pageLayout&&!t)return null;const n=Ve(e.pageLayout),i=this.formatInchesForComment(Ce(n.marginTopPx)),r=this.formatInchesForComment(Ce(n.marginRightPx)),s=this.formatInchesForComment(Ce(n.marginBottomPx)),a=this.formatInchesForComment(Ce(n.marginLeftPx)),l=this.formatInchesForComment(Ce(n.indentStepPx)),c=this.formatInchesForComment(Ce(n.blockSpacingPx)),g=n.marginTopPx===n.marginRightPx&&n.marginTopPx===n.marginBottomPx&&n.marginTopPx===n.marginLeftPx?` margin-in="${i}"`:"",d=this.getEffectivePageNumberSettings(e,n),u=` show-page-numbers="${d.showPageNumbers?"true":"false"}" page-number-position="${d.pageNumberPosition}" page-number-start="${n.pageNumberStart}"${n.pageNumberFormat!=="decimal"?` page-number-format="${n.pageNumberFormat}"`:""}`,p=this.formatInchesForComment(ro(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}"${g} 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=b=>{if(!i)return 0;const k=i instanceof Map?i.get(b):i[b];return typeof k=="number"&&Number.isFinite(k)?Math.max(0,Math.floor(k)):0},a=[],l=[],c=[];for(let b=0;b<e.children.length;b++){const k=e.children[b];k.id&&s(k.id)>0&&c.push(b),k.type==="paragraph"&&k.heading!==void 0&&k.heading<=2?a.push(b):k.type!=="image"&&l.push(b)}const g=a.length>this.MAX_OVERVIEW_BLOCKS?Math.ceil(a.length/this.MAX_OVERVIEW_BLOCKS):1,d=g>1?a.filter((b,k)=>k%g===0):a,u=Math.max(0,this.MAX_OVERVIEW_BLOCKS-d.length),p=[];let h=1;if(u>0&&l.length>0){h=Math.max(1,Math.ceil(l.length/u));for(let b=0;b<l.length;b++)b%h===0&&p.push(l[b])}const f=Array.from(new Set([...d,...p,...c])).sort((b,k)=>b-k),m=n-1;m>=0&&!f.includes(m)&&f.push(m);const y=f.map(b=>{const k=this.getBlockId(e.children[b]),I=s(k),v=r?.blocks?.get(k);return{index:b,id:k,type:this.getBlockTypeLabel(e.children[b]),preview:this.getBlockPreview(e.children[b]),...v?.wordCount!==void 0?{wordCount:v.wordCount}:{},...v?.pageStart!==void 0?{pageStart:v.pageStart,pageEnd:v.pageEnd}:{},...I>0?{pendingChangeCount:I}:{},isLast:b===m}});return{title:e.title||"Untitled",totalBlocks:n,...r?{totalWords:r.wordCount,totalParagraphs:r.paragraphCount}:{},...r?.pageCount!==void 0?{pageCount:r.pageCount}:{},blockIds:y,samplingInterval:Math.max(g,h),...r?.sections&&r.sections.length>0?{sections:r.sections}:{}}}static toDocumentLayoutContext(e){const t=Ve(e.pageLayout),n=oo(t),i=this.getEffectivePageNumberSettings(e,t);return{pageless:e.pageless===!0,pageSize:t.pageSize,orientation:t.orientation,pageWidth:this.formatInchesLength(Ce(n.pageWidth)),pageHeight:this.formatInchesLength(Ce(n.pageHeight)),marginTop:this.formatInchesLength(Ce(t.marginTopPx)),marginRight:this.formatInchesLength(Ce(t.marginRightPx)),marginBottom:this.formatInchesLength(Ce(t.marginBottomPx)),marginLeft:this.formatInchesLength(Ce(t.marginLeftPx)),indentStep:this.formatInchesLength(Ce(t.indentStepPx)),blockSpacing:this.formatInchesLength(Ce(t.blockSpacingPx)),columnCount:t.columnCount,columnGap:this.formatInchesLength(ro(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(`
|
|
4
|
+
`)}static formatOverviewPageRange(e,t){return e===void 0||t===void 0?"":e===t?`${e}`:`${e}-${t}`}static extractBlocksById(e,t,n){const i=Wt(e,t);return i===-1?null:this.extractBlocksByIndex(e,i,n)}static extractBlocksByIndex(e,t,n,i={}){const r=Math.max(0,Math.min(t,e.children.length)),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(`
|
|
5
|
+
`),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(`
|
|
6
|
+
`)}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=Mc(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),g=[];for(const d of i)d.match(l)&&g.push(d.query);g.length>0&&c&&n.push({blockId:c,blockIndex:s,matchedQueries:g})}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,g=this.resolveOmittableDocumentFontFamily(e,i),d=[...e.children,...e.notes??[]],u=this.findTopLevelIndexesByBlockId(e,t),p=n&&n.length>0?this.buildSelectionInfoForBlocks(d,n):null;for(const h of t){const f=u.get(h);if(f===void 0){s.push(h);continue}const m=d[f],y=this.getBlockId(m);if(!y){s.push(h);continue}if(r.push(h),c.has(y))continue;c.add(y);const b=p?.get(y),k=this.blockToHtmlWithSelections(m,e,b,g,p??void 0);a.push(k),l.push({id:y,blockIndex:f,html:k})}return{html:a.filter(h=>h.length>0).join(`
|
|
7
|
+
`),foundIds:r,missingIds:s,foundBlocks:l}}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 g=c.children.reduce((d,u)=>d+u.text.length,0);i.set(c.id,{listId:a.id,offset:l,length:g}),l+=g+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],g={};l===s&&(g.startOffset=r.startOffset),l===a&&(g.endOffset=r.endOffset),n.has(c)||n.set(c,[]),n.get(c).push(g)}}}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=g=>{const d=r.get(g.id);(g.type==="paragraph"||g.type==="list")&&d?.length?a.push({block:g,ranges:d}):"children"in g&&g.type!=="list"&&g.children.forEach(u=>l(u))};if(e.children.forEach(g=>l(g)),!a.length)return s;const c=document.createElement("div");c.innerHTML=s;for(const g of a){const d=Array.from(c.querySelectorAll("[id]")).find(u=>u.id===g.block.id);d&&(d.outerHTML=this.blockToHtmlWithSelections(g.block,t,g.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)}"`:"",g=e.styleId?` data-style-id="${this.escapeHtml(e.styleId)}"`:"",d=e.tabStops?` data-tab-stops="${this.escapeHtml(e.tabStops)}"`:"",u=e.direction?` dir="${e.direction}"`:"";return e.heading?`<h${e.heading}${c}${u}${g}${d}${l}>${s}</h${e.heading}>`:`<p${c}${u}${g}${d}${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,y=h.endOffset??a;l.push({pos:m,type:"open",idx:f}),l.push({pos:y,type:"close",idx:f})}),l.sort((h,f)=>h.pos!==f.pos?h.pos-f.pos:h.type==="open"&&f.type==="close"?-1:h.type==="close"&&f.type==="open"?1:0);let c=0,g=0;const d=[],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,y=c+f.length;let b=0;for(;g<l.length&&l[g].pos<=y;){const k=l[g];if(k.pos>m+b){const I=f.slice(b,k.pos-m);d.push(this.textToHtmlWithMarks(I,h.marks,r,t,u,s,i)),b=k.pos-m}d.push(k.type==="open"?"<user-selection>":"</user-selection>"),g++}if(b<f.length){const k=f.slice(b);d.push(this.textToHtmlWithMarks(k,h.marks,r,t,u,s,i))}c=y}for(;g<l.length;){const h=l[g];d.push(h.type==="open"?"<user-selection>":"</user-selection>"),g++}return d.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??tc(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 g=[];c.length>0&&g.push(`style="${c.join("; ")}"`);const d=bl(t);d.length>0&&g.push(`data-docx-explicit-false-marks="${d.join(",")}"`);const u=xi(t.docxRunPropertyResets);u&&g.push(`data-docx-run-property-resets="${u}"`),g.length>0&&(l=`<span ${g.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(`
|
|
8
|
+
`)}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="${yl(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:kl(e);if(i){const h=e.id?` id="${this.escapeHtml(e.id)}"`:"",f=Ao(i.style),m=i.width===Ai.width&&i.color.toLowerCase()===Ai.color.toLowerCase(),y=f?` data-rule="${i.style}"`:"";let b="";if(!m||!f&&i.style!==Ai.style){const k=f||i.style==="single"?"solid":i.style;b=` style="border-bottom: ${i.width}px ${k} ${i.color}"`}return`<hr${h}${y}${b} />`}const r=this.extractUniformTextFontFamily(e.children),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("; ")}"`:"",g=e.id?` id="${this.escapeHtml(e.id)}"`:"",d=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}${g}${p}${d}${u}${c}>${a}</h${e.heading}>`:`<p${g}${p}${d}${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,xi(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(d=>d.id===r&&!d.parentId),a=s?this.collectCommentThreadRecords(s.id,n):[],l=this.serializeCommentTranscript(a),c=s?.resolved===!0?"true":"false",g=s?.suggestionId?` suggestion-id="${this.escapeAttribute(s.suggestionId)}"`:"";e=`<comment-thread id="${this.escapeAttribute(r)}" resolved="${c}"${g} 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 g=l.agentName??l.author,d=(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`${g}${d}${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 Cc.test(e)?e.replace(Pc,Fc):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=Sl.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&&!so(a)&&(t.color=a)}const r=e.match(/(?:^|;)\s*letter-spacing:\s*([^;]+)/i);if(r){const a=Do(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 Ve(e?.pageLayout).indentStepPx}static applyParagraphElementAttributes(e,t,n){const i=t.getAttribute("style");if(i){const l=this.extractParagraphStyleAttributes(i,n);l.align&&(e.align=l.align),l.leftIndent!==void 0&&(e.leftIndent=l.leftIndent),l.firstLineIndent!==void 0&&(e.firstLineIndent=l.firstLineIndent),l.keepNext&&(e.keepNext=!0),l.keepLines&&(e.keepLines=!0),l.widowControl===!1&&(e.widowControl=!1);const c=l;c.borders&&(e.borders=c.borders),c.shading&&(e.shading=c.shading),this.applyParagraphSpacingAttributes(e,l)}const r=t.getAttribute("data-style-id");r&&(e.styleId=r);const 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 y=wc(e);y&&(n.borders=y);const b=e.match(/(?:^|;)\s*background-color:\s*(#[0-9a-fA-F]{3,8}|transparent)/i);b&&(n.shading=b[1])}const i=e.match(/text-align:\s*([^;]+)/i);if(i){const y=i[1].trim().toLowerCase();(y==="left"||y==="center"||y==="right"||y==="justify")&&(n.align=y)}let r,s,a;const l=e.match(/(?:^|;)\s*margin:\s*([^;]+)/i)?.[1];if(l){const y=l.trim().split(/\s+/);if(y.length>=1&&y.length<=4){const[b,k=b,I=b,v=k]=y;r=b,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 g=this.cssLengthToPx(s);g!==void 0&&(n.spaceAfter=Math.round(g*100)/100);const d=e.match(/(?:^|;)\s*line-height:\s*([\d.]+)\s*(?:;|$)/i);if(d){const y=parseFloat(d[1]);Number.isFinite(y)&&y>=.5&&y<=4&&(n.lineSpacing=y)}const u=e.match(/margin-left:\s*([^;]+)/i),p=this.cssLengthToPx(a)?a:void 0,h=wi(u?.[1]??p,{indentStepPx:t});h!==void 0&&(n.leftIndent=h);const f=e.match(/text-indent:\s*([^;]+)/i),m=wi(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: ${ao(i,n)}px`);const r=t.firstLineIndent===0?0:De(t.firstLineIndent);if(r!==void 0&&e.push(`text-indent: ${Math.sign(r)*ao(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)}"`:"",g=t?` src="${this.escapeAttribute(e.src)}"`:' data-image-source="hidden"';return`<img id="${this.escapeAttribute(e.id)}"${g}${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),T=Math.min(I,(x.endOffset??1/0)-l);return A<T?[{startOffset:A,endOffset:T}]:[]});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],T=A.indentLevel||0;if(T<I)break;if(T>=I){const E=this.extractUniformTextFontFamily(A.children),F=[...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&&F.push(`font-family: ${this.escapeHtml(E)}`);const B=F.length>0?` style="${F.join("; ")}"`:"",P=A.id?` id="${this.escapeAttribute(A.id)}"`:"",w=A.direction?` dir="${A.direction}"`:"",C=T!==0||i.includeZeroListLevels?` data-indent-level="${T}"`:"",$=`${P}${B}${w}${C}`,L=a.get(A),O=L?this.textNodesToHtmlWithSelections(A.children,n,L,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(""),M=[];let N=x+1;for(;N<k.length&&(k[N].indentLevel||0)>T;)M.push(k[N]),N++;let _=O;if(M.length>0){const R=e.variant==="ordered"?"ol":"ul",D=`<${R}>${c(M,T+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${$}>${_}</li>`),x=N}else x++}return v.join("")},g=c(e.children,0),d=e.id?` id="${this.escapeAttribute(e.id)}"`:"",u=e.variant==="ordered"?ac((n?lc(n).get(e.id):void 0)??cc(e)):1,p=e.variant==="ordered"&&u!==1?` start="${u}"`:"",h=[...e.lineSpacing!==void 0?[`line-height: ${e.lineSpacing}`]:[],...e.spaceBefore!==void 0?[`margin-top: ${e.spaceBefore}px`]:[],...e.spaceAfter!==void 0?[`margin-bottom: ${e.spaceAfter}px`]:[]],f=h.length?` style="${h.join("; ")}"`:"",m=e.contextualSpacing!==void 0?` data-contextual-spacing="${e.contextualSpacing}"`:"",y=e.numberingChainId?` data-numbering-chain-id="${this.escapeAttribute(e.numberingChainId)}" data-start-number="${e.startNumber??""}" data-effective-start="${u}"`:"",b=e.numberingFormat?` data-numbering-format="${this.escapeAttribute(e.numberingFormat)}"`:"";return`<${s}${d}${p}${f}${m}${y}${b}>${g}</${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(`
|
|
9
|
+
`);return`<div class="container"${r}${a}>
|
|
10
|
+
${l}
|
|
11
|
+
</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=Bo(e.borders);let l="";if(a){for(const u of["top","right","bottom","left"]){const p=a[u];p&&s.push(`border-${u}: ${Fo(p)}`)}l=` data-borders="${this.escapeAttribute(e.borders)}"`}const c=` style="${s.join("; ")}"`,g=Bt(e),d=e.children.map((u,p)=>{const h=e.hasHeader&&p===0?"th":"td",f=u.children.map((m,y)=>{const b=m.id?` id="${this.escapeAttribute(m.id)}"`:"",k=g.byId.get(m.id);let I="";k&&k.colSpan>1&&(I+=` colspan="${k.colSpan}"`),k&&k.rowSpan>1&&(I+=` rowspan="${k.rowSpan}"`);let v;if(k){let P=0;for(let w=k.col;w<k.col+k.colSpan;w++)P+=e.columnWidths[w]||0;v=P>0?P:void 0}else v=e.columnWidths[y];const x=[];let A="";const T=Ri(m.borders);if(T){for(const P of["top","right","bottom","left"]){const w=T[P];w&&x.push(`border-${P}: ${Fo(w)}`)}A+=` data-borders="${this.escapeAttribute(m.borders)}"`}else x.push("border: 1px solid #ccc");const E=hc(m.padding);E?x.push(`padding: ${fc(E)}`):x.push("padding: 8px"),v!==void 0&&x.push(`width: ${v}%`),m.verticalAlign&&x.push(`vertical-align: ${m.verticalAlign}`),m.backgroundColor&&x.push(`background-color: ${this.escapeHtml(m.backgroundColor)}`);const F=` style="${x.join("; ")}"`,B=m.children.map(P=>this.blockToHtml(P,t,n,i)).filter(P=>P.length>0).join("");return`<${h}${b}${I}${A}${F}>${B}</${h}>`}).join("");return`<tr${u.id?` id="${this.escapeAttribute(u.id)}"`:""}>${f}</tr>`}).join(`
|
|
12
|
+
`);return`<table${r}${l}${c}>
|
|
13
|
+
${d}
|
|
14
|
+
</table>`}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(`
|
|
15
|
+
`);return`<div class="table-cell"${r}${a}>
|
|
16
|
+
${l}
|
|
17
|
+
</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 g=Array.from(n.children);if(g.length!==1)return null;const d=g[0],u=d.tagName.toLowerCase();if(u==="img"){i=d;break}if(u!=="span")return null;n=d}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 g=e.getAttribute("style");if(g){const d=g.match(/text-align:\s*([^;]+)/);if(d){const u=d[1].trim();(u==="left"||u==="center"||u==="right")&&(a.align=u)}}}const l=g=>{const d=g.trim().match(/^(\d+(?:\.\d+)?)px$/i);if(!d)return;const u=Number(d[1]);return Number.isFinite(u)&&u>0?Math.round(u):void 0};let c=i.parentElement;for(;c&&c!==e;){const g=c.getAttribute("style")??"",d=g.match(/(?:^|;)\s*width\s*:\s*([^;]+)/i),u=g.match(/(?:^|;)\s*height\s*:\s*([^;]+)/i),p=d?l(d[1]):void 0,h=u?l(u[1]):void 0,f=i.getAttribute("style")??"";if(p!==void 0&&h!==void 0&&/(?:^|;)\s*transform\s*:/i.test(f))a.width=p,a.height=h;else if(p!==void 0){const m=r??a.width,y=s??a.height;a.width=p,a.height=Math.max(1,Math.round(p*y/m))}else if(h!==void 0){const m=r??a.width,y=s??a.height;a.height=h,a.width=Math.max(1,Math.round(h*m/y))}if(p!==void 0||h!==void 0)break;c=c.parentElement}return a}static parseImageElement(e,t){const n=t?.imageReferences?.get(e);if(n){t?.remainingImageReferences?.delete(e);const f={...n,id:t?.imageIdsToPreserve?.has(n.id)?pe(n.id,t):pe(null,t)};f.width=this.parsePositiveImageDimension(e,"width")??f.width,f.height=this.parsePositiveImageDimension(e,"height")??f.height,e.hasAttribute("alt")&&(f.alt=e.getAttribute("alt")||void 0);const m=this.parseImageAlign(e);return m&&(f.align=m),f}const i=e.getAttribute("src");if(!i)return null;t?.remainingImageReferences?.delete(e);const r=this.parsePositiveImageDimension(e,"width"),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,g=this.parseImageAlign(e),d=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),g&&(h.align=g),d&&(h.sourceUrl=d),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={},y=Math.min(n+2,8))=>{const b=[],k=h.getAttribute("style"),I=k?{...m,...this.extractTextStyleMarksFromStyle(k)}:m;for(const v of Array.from(h.children))if(v.tagName.toLowerCase()==="li"){const x=document.createElement("div");let A=!1;const T=[];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,T.push(_)):x.appendChild(N.cloneNode(!0))}else x.appendChild(N.cloneNode(!0));const E=v.getAttribute("style"),F=E?{...I,...this.extractTextStyleMarksFromStyle(E)}:I,B=x.querySelector('input[type="checkbox"]');B&&(r="todo",B.remove());const P=this.parseHtmlElement(x,F),w={type:"list-item",id:pe(v.getAttribute("id"),t),children:P.length>0?P:[{type:"text",text:"",marks:{}}]};B&&(w.checked=B.hasAttribute("checked"));const C=v.getAttribute("dir")??E?.match(/(?:^|;)\s*direction:\s*(rtl|ltr)\s*(?:;|$)/i)?.[1];if((C==="rtl"||C==="ltr")&&(w.direction=C),E){const N=this.extractParagraphStyleAttributes(E);for(const _ of["lineSpacing","spaceBefore","spaceAfter"])N[_]!==void 0&&(w[_]=N[_])}const $=v.getAttribute("data-indent-level"),L=$!==null?Number($):NaN,O=Number.isInteger(L)&&L>=0&&L<=8,M=O?L:f;if(M>0&&(w.indentLevel=M),b.push(w),A)for(const N of T){const _=O?Math.max(y,Math.min(M+2,8)):y,R=s(N,Math.min(M+1,_),F,_);b.push(...R)}}return b},a=s(e,n);if(a.length===0)return null;const l={type:"list",id:pe(e.getAttribute("id"),t),variant:r,children:a};if(r==="ordered"){const h=e.getAttribute("start");if(h){const f=parseInt(h,10);!isNaN(f)&&f!==1&&(l.startNumber=f)}}const c=e.getAttribute("style");if(c){const h=this.extractParagraphStyleAttributes(c);for(const m of["spaceBefore","spaceAfter"])h[m]!==void 0&&(l[m]=h[m]);const f=c.match(/(?:^|;)\s*line-height:\s*([\d.]+)\s*(?:;|$)/i);if(f){const m=parseFloat(f[1]);Number.isFinite(m)&&m>=.5&&m<=4&&(l.lineSpacing=m)}}const g=e.getAttribute("data-contextual-spacing");(g==="true"||g==="false")&&(l.contextualSpacing=g==="true");const d=e.getAttribute("data-numbering-chain-id");if(d&&r==="ordered"){l.numberingChainId=d;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&&gc(u)&&(l.numberingFormat=u);const p=e.getAttribute("style");if(p){const h=p.match(/font-family:\s*([^;]+)/);if(h){const f=this.resolveFontToCss(h[1].trim());for(const m of l.children)for(const y of m.children)y.type==="text"&&(y.marks||(y.marks={}),y.marks.fontFamily||(y.marks.fontFamily=f))}}return l}static parseContainerElement(e,t,n){const i=pe(e.getAttribute("id"),n),r=e.getAttribute("style");let s,a;if(r){const d=r.match(/border-color:\s*([^;]+)/);d&&(s=d[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 d of Array.from(e.children)){const u=d.tagName.toLowerCase();if(u==="p"||u.match(/^h[1-6]$/)){const p=u.match(/^h([1-6])$/),h=d.getAttribute("style"),f=this.parseHtmlElement(d,h?this.extractTextStyleMarksFromStyle(h):{}),m={type:"paragraph",id:pe(d.getAttribute("id"),n),children:f.length>0?f:[{type:"text",text:"",marks:{}}]};p&&(m.heading=parseInt(p[1])),this.applyParagraphElementAttributes(m,d,l),c.push(m)}else if(u==="ul"||u==="ol"){const p=this.parseListElement(d,n);p&&c.push(p)}else if(u==="hr")c.push(this.parseHrElement(d,n));else if(u==="img"){const p=this.parseImageElement(d,n);p&&c.push(p)}else if(u==="div"&&d.classList.contains("container")){const p=this.parseContainerElement(d,t,n);p&&c.push(p)}}if(c.length===0)return null;const g={type:"container",id:i,children:c};return s&&(g.borderColor=s),a!==void 0&&(g.padding=a),g}static parseTableElement(e,t,n){const i=pe(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 g=[],d=new Map;let u=!1;const p=Array.from(e.rows);for(let x=0;x<p.length;x++){const A=p[x],T=[],E=A.querySelectorAll(":scope > td, :scope > th");x===0&&E.length>0&&E[0].tagName.toLowerCase()==="th"&&(u=!0);for(let B=0;B<E.length;B++){const P=E[B],w=P.getAttribute("style");let C,$;if(w){const j=w.match(/vertical-align:\s*([^;]+)/);if(j){const K=j[1].trim();(K==="top"||K==="middle"||K==="bottom")&&(C=K)}const H=w.match(/background-color:\s*([^;]+)/);H&&($=H[1].trim())}const L=[],O=P.children;if(O.length===0){const j=P.textContent||"";L.push({type:"paragraph",id:pe(null,n),children:[{type:"text",text:j,marks:{}}]})}else for(const j of Array.from(O)){const H=j.tagName.toLowerCase(),K=H==="img"?this.parseImageElement(j,n):H==="p"?this.parseSingleImageParagraph(j,n):null;if(K){L.push(K);continue}if(H==="p"||H.match(/^h[1-6]$/)){const se=H.match(/^h([1-6])$/),xe=j.getAttribute("style"),Ue=this.parseHtmlElement(j,xe?this.extractTextStyleMarksFromStyle(xe):{}),Oe={type:"paragraph",id:pe(j.getAttribute("id"),n),children:Ue.length>0?Ue:[{type:"text",text:"",marks:{}}]};se&&(Oe.heading=parseInt(se[1])),this.applyParagraphElementAttributes(Oe,j,r),L.push(Oe)}else if(H==="ul"||H==="ol"){const se=this.parseListElement(j,n);se&&L.push(se)}else if(H==="hr")L.push(this.parseHrElement(j,n));else if(H==="table"){const se=this.parseTableElement(j,t,n);se&&L.push(se)}else{const se=j.textContent||"";se.trim()&&L.push({type:"paragraph",id:pe(null,n),children:[{type:"text",text:se,marks:{}}]})}}L.length===0&&L.push({type:"paragraph",id:pe(null,n),children:[{type:"text",text:"",marks:{}}]});const M={type:"table-cell",id:pe(P.getAttribute("id"),n),children:L},N=w?.match(/width:\s*([\d.]+)%/);if(N){const j=parseFloat(N[1]);Number.isFinite(j)&&j>0&&d.set(M,j)}C&&(M.verticalAlign=C),$&&(M.backgroundColor=$);const _=Ri(P.getAttribute("data-borders")),R=_?Cn(_):Mo(Eo(w));if(R&&(M.borders=R),w){const j=w.match(/(?:^|;)\s*padding\s*:\s*([^;]+)/i),H=pc(j?.[1]);H&&!(H.top===8&&H.right===8&&H.bottom===8&&H.left===8)&&(M.padding=mc(H))}const D=this.parseSpanAttribute(P.getAttribute("colspan")),U=this.parseSpanAttribute(P.getAttribute("rowspan"));D>1&&(M.colSpan=D),U>1&&(M.rowSpan=U),T.push(M)}const F=pe(A.getAttribute("id"),n);g.push({type:"table-row",id:F,children:T})}if(!g.some(x=>x.children.length>0))return null;const h=Bt({children:g,columnWidths:[]}),f=h.cols||1,m=new Array(f).fill(0),y=new Array(f).fill(!1);for(const x of h.cells){if(x.colSpan!==1||y[x.col])continue;const A=d.get(x.cell);A!==void 0&&(m[x.col]=A,y[x.col]=!0)}const b=y.filter(x=>!x).length;if(b>0){const x=m.reduce((T,E)=>T+E,0),A=Math.max(1,(100-x)/b);for(let T=0;T<f;T++)y[T]||(m[T]=A)}const k={type:"table",id:i,columnWidths:m,children:g};a!==void 0&&(k.tableWidth=a),c&&(k.align=c),l&&(k.borderColor=l),u&&(k.hasHeader=u);const I=Bo(e.getAttribute("data-borders")),v=I?Cn(I):Mo(Eo(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=pe(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 g of c)if(g.startsWith("language-")){i=g.substring(9);break}}let a="";const l=e.querySelector("code");return l?a=l.textContent||"":a=e.textContent||"",{type:"code",id:n,content:a,language:i}}static parseMathElement(e,t){const n=pe(e.getAttribute("id"),t);let i="block";e.getAttribute("display")==="inline"&&(i="inline");const r=e.textContent||"",s=te(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 Ao(r??void 0)&&(n={...n,style:r}),{type:"paragraph",id:pe(e.getAttribute("id"),t),children:[{type:"text",text:"",marks:{}}],borders:Il(n)}}static parsePageBreakElement(e,t){return{type:"page-break",id:pe(e.getAttribute("id"),t)}}static parseDocxRawElement(e,t){const n=e.getAttribute("origin");return{type:"docx-raw",id:pe(e.getAttribute("id"),t),xml:"",tagName:e.getAttribute("tag")||"unknown",...e.getAttribute("detail")?{detail:e.getAttribute("detail")}:{},origin:n==="body"?"body":"run"}}static parseTocElement(e,t){const n={type:"toc",...vl(e),id:pe(e.getAttribute("id"),t)},i=e.getAttribute("levels");if(i){const r=parseInt(i,10);Number.isFinite(r)&&r>=1&&r<=6&&(n.levels=r)}return Object.assign(n,xl(e.getAttribute("style"))),n}static parseSectionBreakElement(e,t){const n={type:"section-break",id:pe(e.getAttribute("id"),t)},i=e.getAttribute("break-type");(i==="nextPage"||i==="continuous"||i==="evenPage"||i==="oddPage")&&(n.breakType=i);const r=e.getAttribute("layout");if(r)try{const 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])$/),g=this.parseHtmlElement(a),d={type:"paragraph",id:pe(a.getAttribute("id"),n),children:g.length>0?g:[{type:"text",text:"",marks:{}}],align:"center"};c&&(d.heading=parseInt(c[1])),i.push(d);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:pe(e.getAttribute("id"),n),align:"center",children:s.length>0?s:[{type:"text",text:"",marks:{}}]}]}static parseImageAlign(e){const t=te(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,,g]=r,d=this.escapeCodeContent(c||"");return`<pre${n||""}>${a||""}<code${l||""}>${d}</code>${g||""}</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=Di(i),s=Array.from(r.body.childNodes),a=s.filter(g=>g.nodeType===Node.ELEMENT_NODE||g.nodeType===Node.TEXT_NODE&&g.textContent?.trim()),l=g=>g?.nodeType===Node.ELEMENT_NODE&&g.tagName.toLowerCase()==="li",c=a.length===0&&s.some(g=>g.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?_o({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=Di(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=>Tc.has(f.tagName.toLowerCase()))||(a=Di(`<p>${e}</p>`));const g=new Set,d=Array.from(a.body.querySelectorAll("img"));for(const f of d){s.remainingImageReferences.add(f);const m=f.getAttribute("id")??"",y=m?n?.imagesById?.get(m):void 0,b=f.getAttribute("data-image-id"),k=f.getAttribute("src")??"",I=k.startsWith("#")?k.slice(1):void 0;if(b!==null||I!==void 0){const x=b??I,A=n?.imagesById?.get(x);if(!A?.src||I!==void 0&&I!==x||y&&y.id!==x||k&&I===void 0&&k!==x&&k!==A.src)throw new me("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!==y?.src&&!/^(?:https?:\/\/|data:image\/|blob:)/i.test(k))throw new me("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"&&d.length===1?n?.imagesById?.get(t.replacementBlock.id):void 0,A=y??x;if(!A?.src)throw new me("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(g.has(A.id))throw new me("invalid_image_reference",`Image "${A.id}" is referenced more than once. Each existing image may appear only once in replacement HTML.`);g.add(A.id),s.imageReferences.set(f,A);continue}y?.src===f.getAttribute("src")&&s.imageReferences.set(f,y)}const u=Array.from(a.body.children),p=t?.parsingContext?.indentStepPx??this.resolveIndentStepPx(t?.existingDocument),h=[];u.length===0&&a.body.textContent&&h.push({type:"paragraph",id:pe(null,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 y=m.match(/^h([1-6])$/),b=f.getAttribute("style");let k,I;if(b){const A=b.match(/font-family:\s*([^;]+)/);A&&(k=this.resolveFontToCss(A[1].trim())),I=this.extractFontSizeFromStyle(b)}const v=pe(f.getAttribute("id"),s),x=b?this.extractTextStyleMarksFromStyle(b):{};if(y){const A=parseInt(y[1]),T=this.parseHtmlElement(f,x,t?.preserveExplicitMarkResets),E={type:"paragraph",id:v,heading:A,children:T.length>0?T:[{type:"text",text:"",marks:{}}]};if(k)for(const F of E.children)F.type==="text"&&(F.marks||(F.marks={}),F.marks.fontFamily||(F.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),T={type:"paragraph",id:v,children:A.length>0?A:[{type:"text",text:"",marks:{}}]};if(k)for(const E of T.children)E.type==="text"&&(E.marks||(E.marks={}),E.marks.fontFamily||(E.marks.fontFamily=k));this.applyParagraphElementAttributes(T,f,p),h.push(T)}}if(s.remainingImageReferences.size>0){const f=Array.from(s.remainingImageReferences,m=>m.getAttribute("id")||"(new image)").join(", ");throw new me("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(Al()),uc(h,t?.existingDocument?.stylesheet),this.applyInheritedFontStyling(h,t),dc(()=>pe(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=Ec(a.textContent||"",l);c&&i.push({type:"text",text:c,marks:{...l}})}else if(a.nodeType===Node.ELEMENT_NODE){const c=a,g={...l};switch(c.tagName.toLowerCase()){case"b":case"strong":g.bold=!0;break;case"i":case"em":g.italic=!0;break;case"u":g.underline=!0;break;case"s":case"strike":g.strikethrough=!0;break;case"code":g.code=!0;break;case"l":case"latex-inline":g.latex=!0;break;case"sup":{g.superscript=!0;const p=c.getAttribute("data-footnote-ref");p&&(g.footnoteRef=p);const h=c.getAttribute("data-footnote");h!==null&&(g.footnoteRef=p??Y(),g.footnotePendingBody=h,c.getAttribute("data-note-kind")==="endnote"&&(g.footnotePendingKind="endnote"));break}case"sub":g.subscript=!0;break;case"mark":{const p=c.getAttribute("color"),h=this.normalizeAgentHighlightColor(p);if(p!==null&&!h)throw new Error(`Unsupported highlight color ${JSON.stringify(p)}. Use one of: ${Yt.join(", ")}.`);g.backgroundColor=h??bc}break;case"a":const d=c.getAttribute("href");d&&(g.link=d);break;case"comment-thread":{const p=c.getAttribute("id")?.trim();if(p){const h=g.comment?.split(",").map(f=>f.trim()).filter(Boolean);g.comment=[...h??[],p].join(",")}break}case"br":i.push({type:"text",text:`
|
|
18
|
+
`,marks:{...l}});return;case"span":wl(g,c.getAttribute("data-docx-explicit-false-marks"),c.getAttribute("data-docx-run-property-resets")),c.getAttribute("data-word-hidden")==="true"&&(g.hidden=!0);{const p=c.getAttribute("data-bookmark");p&&(g.bookmark=p);const h=c.getAttribute("data-field-instr");h&&(g.fieldInstr=h);const f=c.getAttribute("data-word-lang");f&&(g.lang=f);const m=c.getAttribute("data-dynamic-field");(m==="page"||m==="numPages")&&(g.field=m);const y=c.getAttribute("data-sdt-inline");y&&(g.sdtInline=y),c.getAttribute("data-ai-generated")==="true"&&(g.aiGenerated=!0);const b=c.getAttribute("data-html-class");b&&(g.__htmlClassName=b)}const u=c.getAttribute("style");if(u){const p=u.match(/font-family:\s*([^;]+)/);p&&(g.fontFamily=this.resolveFontToCss(p[1].trim()));const h=this.extractFontSizeFromStyle(u);h!==void 0&&(g.fontSize=h);const f=this.parseCssFontWeightToBold(u);f===!0?g.bold=!0:f===!1&&(n?g.bold=!1:delete g.bold);const m=u.match(/(?:^|;)\s*font-style:\s*([^;]+)/i);if(m){const v=m[1].trim().toLowerCase();v==="italic"||v==="oblique"?g.italic=!0:v==="normal"&&(n?g.italic=!1:delete g.italic)}const y=u.match(/background-color:\s*([^;]+)/i);if(y){const v=this.normalizeAgentHighlightColor(y[1].trim());v&&(g.backgroundColor=v)}const b=u.match(/(?:^|;)\s*color:\s*([^;]+)/i);if(b){const v=kn(b[1].trim());v&&!so(v)&&(g.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?g[x]=!1:delete g[x];v.includes("line-through")&&(v.includes("double")?g.doubleStrikethrough=!0:g.strikethrough=!0)}/font-variant:\s*small-caps/i.test(u)&&(g.smallCaps=!0),/text-transform:\s*uppercase/i.test(u)&&(g.allCaps=!0);const I=u.match(/letter-spacing:\s*([^;]+)/i);if(I){const v=Do(I[1],g.fontSize);v!==void 0&&(g.letterSpacing=v)}}break}c.tagName.toLowerCase()!=="img"&&(r=g);for(const d of Array.from(a.childNodes))s(d,g)}};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;if(!i||i.length===0)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(`
|
|
19
|
+
`)}};_i.DEFAULT_FONT_FAMILY="Arial, sans-serif",_i.MAX_OVERVIEW_BLOCKS=50;let Z=_i;function be(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=>be(n)).join(t)}return""}const jo=/<!--[^]*?-->|<\/?[a-zA-Z][\w:-]*(?:\s+(?:[^"'<>]|"[^"]*"|'[^']*')*)?\s*\/?>/g,Xo={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 $c(o){return o.replace(/\\+(["'])/g,"$1")}function Kt(o){return $c(o.replace(/&(#(?:\d+|x[0-9a-f]+)|[a-z]+);/gi,(e,t)=>{if(!t.startsWith("#"))return Object.prototype.hasOwnProperty.call(Xo,t)?Xo[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(jo)>=0}function Vt(o){return Kt(o.replace(jo,e=>/^<br\b/i.test(e)?`
|
|
20
|
+
`:""))}function Mn(o){const e=Kt(o);return[...new Set(et(o)?[o,e,Vt(o)]:[o,e])]}function En(o,e,t="prefer-exact",n){if(n&&t!=="normalized"){const i=zo(o,n,e);if(i.length)return i}for(const i of Mn(e)){const r=Gt(o,i,t);if(r.length)return r}return[]}function Ft(o){return o.replace(/<\/?comment-thread\b[^>]*>/gi,"")}function Uo(o,e){return Xi(Ft(o),Ft(e))}function zo(o,e,t){if(!et(t))return[];e=Ft(e);const n=Vt(e);return n.length!==o.length||tt(n)!==tt(o)?[]:Uo(e,t).map(({start:i,end:r})=>({start:Vt(e.slice(0,i)).length,end:Vt(e.slice(0,r)).length})).filter(i=>i.end>i.start)}function ji(o){let e="";const t=[],n=[];for(let i=0;i<o.length;i++){const r=i;let s=Ho(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 Ho(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=Ho(o[t]);e+=/[\u2012-\u2014]/u.test(n)?"-":n}return e}function Xi(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 Gt(o,e,t="prefer-exact"){if(t!=="normalized"){const r=Xi(o,e);if(r.length>0||t==="exact")return r}const n=ji(o),i=ji(e).text;return i.trim()?Xi(n.text,i).map(({start:r,end:s})=>({start:n.starts[r],end:n.ends[s-1]})):[]}function Lc(o,e,t,n,i){for(const r of["exact","normalized"]){const s=i?i(e,r):En(o,e,r,n),a=i?i(t,r):En(o,t,r,n),l=[];let c=0;for(const g of s){for(;c<a.length&&a[c].start<g.end;)c++;for(let d=c;d<a.length;d++)if(l.push({start:g.start,end:a[d].end}),l.length===2)return l}if(l.length)return l}return[]}const Wo={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 Yo(o,e){if(!/<[^>]+\bid\s*=/i.test(e))return null;const t=be(o);if(t.includes(e)||t.includes(Kt(e)))return null;const n=document.createElement("template");n.innerHTML=e;const i=[...n.content.querySelectorAll("[id]")].filter(c=>Wo[c.tagName]);if(!i.length)return null;const r=new Map,s=(c,g=null)=>{if(!c||typeof c!="object")return;const d=c;d.id&&(g?g.add(d.id):r.set(d.id,[...r.get(d.id)??[],d])),d.children?.forEach(u=>s(u,g))};s(o);const a=new Set,l=new Set;for(const c of i){const g=r.get(c.id)??[];if(a.has(c.id)||g.length!==1||g[0].type!==Wo[c.tagName])throw new me("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 d=g[0],u=be(d),p=c.textContent??"",h=Gt(u,p,"prefer-exact");if(u!==p&&!h.some(y=>y.start===0&&y.end===u.length))throw new me("target_stale",`HTML matcher text for '${c.id}' no longer matches that block. Read it again before editing.`,"matching");const f=new Set;s(d,f);const m=i.filter(y=>y!==c&&c.contains(y));if(m.some(y=>!f.has(y.id)))throw new me("target_stale",`HTML matcher ids contradict the document hierarchy inside '${c.id}'.`,"target_resolution");m.length||f.forEach(y=>l.add(y))}return l}function Mt(o,e){const t=X(o,e);return t?.type==="list"&&t.id!==e?t.children.find(n=>n.id===e)??null:t}function Ui(o){if(!(!o||o.type!=="paragraph"&&o.type!=="list-item"))return Z.toAgentHtml({type:"doc",children:[{...o,type:"paragraph"}]})}function $n(o,e,t="prefer-exact"){const n=Yo(o,e),i=En(be(o),e,t,et(e)?Ui(o):void 0);if(!n)return i;const r=qo(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 qo(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=be(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 Nc(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 Jo(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 Ko=300;function zi(o,e,t,n,i){const r=Jo(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>Ko?`${s.bodyMd.slice(0,Ko)}…`:s.bodyMd}))}function Vo(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 Oc(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 g=new Set((a??[]).map(A=>A.trim()).filter(Boolean)),d=Mt(o,n);if(!d)return{success:!1,error:`Block ${n} not found`,errorCode:"target_missing"};if("whole_block"in r){const A=zi(o,d,n,null,g);if(A.length>0)return Vo(n,A);const T=t.addBlockComment(n,i,s);return T?{success:!0,commentId:T}:{success:!1,error:`Could not attach a comment to block ${n}`}}const u=Mt(e,n),p=be(u??d);let h=-1,f=-1;const m="text"in r?$n(u??d,r.text):Lc(p,r.start_text,r.end_text,Ui(u??d),(A,T)=>$n(u??d,A,T));if(m.length!==1)return{success:!1,error:m.length?`Anchor text matched ${m.length} locations in block '${n}'. Provide unique text or an HTML fragment that identifies the formatting, such as <b>claim</b> for bold or <i>claim</i> for italic. Start/end boundary text is included in the comment range; do not use surrounding separators unless they should also be commented on.`:`Anchor text was not found in block '${n}'.`,errorCode:m.length?"anchor_ambiguous":"anchor_not_found"};({start:h,end:f}=m[0]);const y=qo(u??d),b=Nc(y,h,f);if(b.length===0)return{success:!1,error:`The anchor range in block ${n} does not map to commentable text`};const k=[];for(const A of b){const T=Mt(e,A.blockId),E=Mt(o,A.blockId);if(!T||!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 F={start:A.start,end:A.end};if(be(E)!==be(T)){const B=t.mapAcceptedSuggestionRangeToLiveRange(A.blockId,A.start,A.end);if(!B)return{success:!1,error:`The anchor range in block ${n} could not be mapped across pending suggestions; read the block again and retry`};F=B}k.push({blockId:A.blockId,...F})}const I=new Map;for(const A of zi(o,d,n,{start:h,end:f},g))o.comments?.some(T=>T.id===A.id&&T.anchorBlockId===n)&&I.set(A.id,A);for(const A of k){const T=Mt(o,A.blockId);if(T)for(const E of zi(o,T,A.blockId,{start:A.start,end:A.end},g))I.set(E.id,E)}const v=Array.from(I.values());if(v.length>0)return Vo(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 Go(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 Rc(o,e,t,n,i){const r=Go(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 Dc(o,e,t){const n=X(o.getDocument(),e),i=X(o.getDocumentWithAcceptedSuggestions(),e);if(!n||!i)throw new me("target_missing",`Footnote target '${e}' no longer exists. Read the document again.`,"target_resolution");if(n.type!=="paragraph"||i.type!=="paragraph")throw new me("target_unsupported","Footnote references require a paragraph target. Read the paragraph inside this block and use its id.","target_resolution");const r=t?$n(i,t):[];if(t&&r.length!==1)throw new me(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:be(i).length;if(be(n)!==be(i)){const a=o.mapAcceptedSuggestionRangeToLiveRange(e,s,s);if(!a)throw new me("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 Hi(o,e){return{indentStepPx:Ve(e).indentStepPx,storedAsUnits:o.get(Ge.paragraphIndentStorageVersion)===Ti}}const Qo=new WeakMap;function Wi(o){return o.getXmlFragment("content")}function Zo(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=Wi(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=Zo(e,r.target);l!==null&&t.dirtyBlockIds.add(l);continue}const a=Zo(e,r.target);a!==null&&t.dirtyBlockIds.add(a)}};return t.observer=n,e.observeDeep(n),t}function es(o){let e=Qo.get(o);return e||(e=_c(o),Qo.set(o,e)),e}function Ln(o,e){const t=es(o);t.nestedBlocks=new WeakMap,t.doc=e,t.blockCache.clear(),t.elementByBlockId.clear();const n=Wi(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 Nn(o,e,t){const n=t.nestedBlocks.get(o);if(n)return n;const i=Ci(o,e,void 0,r=>Nn(r,e,t));return i&&t.nestedBlocks.set(o,i),i}const On=new WeakMap;function jc(o){let e=On.get(o);e||(e={blocks:[],dirty:!0,observing:!1},On.set(o,e));const t=o.getXmlFragment("chrome");if(e.observing||(e.observing=!0,t.observeDeep(()=>{const n=On.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=Ci(i,Hi(o.getMap("metadata"),void 0));r&&r.type==="header-footer"&&n.push(r)}e.blocks=n,e.dirty=!1}return e.blocks}const Rn=new WeakMap;function Xc(o){let e=Rn.get(o);e||(e={blocks:[],dirty:!0,observing:!1},Rn.set(o,e));const t=o.getXmlFragment("notes");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=Ci(i,Hi(o.getMap("metadata"),void 0));r&&r.type==="footnote"&&n.push(r)}e.blocks=n,e.dirty=!1}return e.blocks}function Uc(o){return!!(On.get(o)?.dirty||Rn.get(o)?.dirty)}function Dn(o,e){const t=Xc(e);t.length>0?(o.notes=t,Tl(o)):delete o.notes}function _n(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 Yi(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 jn(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 Xn(o,e){const t=jc(e);t.length>0?o.chrome=t:delete o.chrome;const n=co(t);n.headers?o.headers=n.headers:delete o.headers,n.footers?o.footers=n.footers:delete o.footers}function He(o){const e=es(o),t=Wi(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,g=n?.get("stylesheet"),d=g&&typeof g=="object"&&Array.isArray(g.paragraphStyles)&&g.paragraphStyles.length>0?g:void 0,u=n?.get("stylesXml"),p=typeof u=="string"&&u.length>0?u:void 0,h=n?.get("docxSource"),f=h&&typeof h=="object"&&Array.isArray(h.spans)?h:void 0,m=n?.get("coreProperties"),y=m&&typeof m=="object"&&Object.keys(m).length>0?m:void 0,b=n?.get("fontSubstitutes"),k=b&&typeof b=="object"&&Object.keys(b).length>0?b:void 0,I=lo(n),v=Hi(n,I);if(e.indentContext&&(e.indentContext.indentStepPx!==v.indentStepPx||e.indentContext.storedAsUnits!==v.storedAsUnits)&&(e.nestedBlocks=new WeakMap,e.doc=null,e.blockCache.clear(),e.elementByBlockId.clear()),e.indentContext=v,!e.doc){const x=[],A=t.toArray();for(let T=0;T<A.length;T++){const E=A[T];if(E instanceof S.XmlElement){const F=Nn(E,v,e);F&&(x.push(F),e.blockCache.set(F.id,F),e.elementByBlockId.set(F.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),d&&(e.doc.stylesheet=d),p&&(e.doc.stylesXml=p),f&&(e.doc.docxSource=f),y&&(e.doc.coreProperties=y),k&&(e.doc.fontSubstitutes=k),Xn(e.doc,o),Dn(e.doc,o),_n(e.doc,o),jn(e.doc,o),Yi(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,T=new Map,E=t.toArray();for(let F=0;F<E.length;F++){const B=E[F];if(B instanceof S.XmlElement){const P=B.getAttribute("id"),w=P?e.dirtyBlockIds.has(P):!0,C=P?e.blockCache.get(P):void 0,$=P!==null&&e.elementByBlockId.get(P)===B;if(P&&!w&&C&&$)x.push(C),A.set(P,C),T.set(P,B);else{const L=Nn(B,v,e);L&&(x.push(L),A.set(L.id,L),T.set(L.id,B))}}}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),d&&(e.doc.stylesheet=d),p&&(e.doc.stylesXml=p),f&&(e.doc.docxSource=f),y&&(e.doc.coreProperties=y),k&&(e.doc.fontSubstitutes=k),Xn(e.doc,o),Dn(e.doc,o),_n(e.doc,o),jn(e.doc,o),Yi(e.doc,o),e.blockCache=A,e.elementByBlockId=T,e.dirtyBlockIds.clear(),e.structuralChange=!1,e.doc}if(e.dirtyBlockIds.size>0){const x=[...e.doc.children],A=t.toArray();for(let T=0;T<x.length;T++){const E=x[T];if(E?.id&&e.dirtyBlockIds.has(E.id)&&T<A.length){const F=A[T];if(F instanceof S.XmlElement){const B=Nn(F,v,e);B&&(e.blockCache.delete(E.id),x[T]=B,e.blockCache.set(B.id,B),e.elementByBlockId.set(B.id,F))}}}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),d&&(e.doc.stylesheet=d),p&&(e.doc.stylesXml=p),f&&(e.doc.docxSource=f),y&&(e.doc.coreProperties=y),k&&(e.doc.fontSubstitutes=k),Xn(e.doc,o),Dn(e.doc,o),_n(e.doc,o),jn(e.doc,o),Yi(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,y?e.doc.coreProperties=y:delete e.doc.coreProperties,k?e.doc.fontSubstitutes=k:delete e.doc.fontSubstitutes,e.doc.chromeImages!==c&&(e.doc={...e.doc},c?e.doc.chromeImages=c:delete e.doc.chromeImages),e.doc.watermark!==a&&(e.doc={...e.doc},a!==void 0?e.doc.watermark=a:delete e.doc.watermark),e.doc.stylesheet!==d&&(e.doc={...e.doc},d!==void 0?e.doc.stylesheet=d:delete e.doc.stylesheet),Uc(o)&&(e.doc={...e.doc}),Xn(e.doc,o),Dn(e.doc,o),_n(e.doc,o),jn(e.doc,o),e.doc}const qi=new WeakMap,Qt="__revise_end_of_document__";function Se(o,e){qi.set(o,{...qi.get(o),...e})}function Be(o){return qi.get(o)}function Un(o){if(o.name==="insert_block")return Be(o)?.stableId}function zc(o){return!!Be(o)?.allowNoopContinuation}function Hc(o){if(o.name==="replace_block")return Be(o)?.multiBlockReplace}function ts(o,e){if(et(e)){let t=null;for(const n of o){const i=n.html?zo(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=En(i.text,e,t);if(r.length){if(r.length>1||n!==null)return null;n=i.blockId}}if(n!==null)return n}return null}function Ji(o){const e=Mn(o).at(-1);return ji(tt(e)).text}function ns(o){return o?.type==="paragraph"||o?.type==="list-item"||o?.type==="code"||o?.type==="math"}function is(o){const e=[],t=(n,i)=>{if(!(!n||typeof n!="object")&&(typeof n.id=="string"&&n.id.trim().length>0&&ns(n)&&e.push({blockId:n.id,topLevelBlockId:i,text:be(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 Ki(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 rs(o,e){const t=Ki(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 os(o,e){return e.has(o.blockId)||o.topLevelBlockId!==null&&e.has(o.topLevelBlockId)}function ss(o){if(!o.loadedBlockIds||o.loadedBlockIds.size===0)return null;const e=Ji(o.find);if(!e||/^\s*$/.test(e))return null;const t=X(o.doc,o.requestedBlockId);if(t&&Ji(be(t)).includes(e))return null;const n=Mn(o.find).at(-1),i=is(o.doc).filter(s=>s.blockId!==o.requestedBlockId&&os(s,o.loadedBlockIds));if(i.some(s=>Gt(s.text,n).length>0))return ts(i,n);let r=null;for(const s of i)if(Ji(s.text).includes(e)){if(r!==null)return null;r=s.blockId}return r}function Wc(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=ss({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=Be(o.action);return s&&Se(r,s),{action:r,retarget:{fromBlockId:t,toBlockId:i}}}function Yc(o){const e=[],t=[];for(const n of o.actions){const i=Wc({action:n,doc:o.doc,loadedBlockIds:o.loadedBlockIds});e.push(i.action),i.retarget&&t.push(i.retarget)}return{actions:e,retargets:t}}function Vi(o){return o.children.map(e=>{const t={type:"doc",children:[e]};return Z.toInternalHtml(t).trim()})}function qc(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 Vi(t)}function Jc(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 Kc(o,e,t,n){return Vi(Z.fromAgentHtml(Jc(o),{existingDocument:e,replacementBlock:t,listItemBaseIndent:n,preserveImageReferenceIds:!0}))}const ht=/<\/?[a-z][^>]*>/i;function Et(o){return o.replace(/\s+/g," ").trim()}function as(o){return Et(o).replace(/^>\s+/,"")}function Vc(o,e){if(o.replace==="")return null;const t=o.format==="html"||ht.test(o.replace),n=t?Z.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)?Z.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(y=>Et(be(y))):[Et(be(a))];if(l.length===0||l.some(y=>y===""))return null;const c=s.children.map(y=>Et(be(y))),g=[];for(let y=0;y+l.length<=c.length;y++)l.every((b,k)=>c[y+k]===b)&&(g.push(y),y+=l.length-1);if(g.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(g.length>1&&!o.all)throw new Error(`replace: "find" matches ${g.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 d=o.all?g:[g[0]],u=[];let p=0;for(const y of d)u.push(...s.children.slice(p,y)),u.push(...i),p=y+l.length;u.push(...s.children.slice(p));const h=d.length===1&&d[0]===0&&l.length===s.children.length,f=h?{...n.children[0],id:s.id}:{...s,children:u},m=h&&t?o.replace:Vi({children:[f]})[0];return{name:"replace_block",arguments:{id:s.id,content:[m]}}}function Gc(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)?be(Z.fromAgentHtml(o.find,{existingDocument:e,preserveImageReferenceIds:!0})):be(Pn.fromMarkdown(o.find)),i=be(t);if(as(n)!==as(i))return null;const r=o.format==="html"||!o.format&&ht.test(o.replace)?Kc(o.replace,e,t):qc(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"?rs(e,o.id):null,c=l!==null&&l!==o.id&&X(e,l)?.type==="paragraph",g=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"&&(g||Et(o.find)===Et(i)))?null:{name:"replace_block",arguments:{id:o.id,content:r}}}function Qc(o,e){return Vc(o,e)??Gc(o,e)}function Gi(o,e){const t=X(o,e);if(!t)return null;const n=JSON.stringify(t);let i=2166136261;for(let r=0;r<n.length;r++)i^=n.charCodeAt(r),i=Math.imul(i,16777619);return(i>>>0).toString(36)}function Zc(o,e){const t=new Map;for(const n of e){if(t.has(n))continue;const i=Gi(o,n);i!==null&&t.set(n,i)}return t}const ls=50,cs="document_state_changed",eg=new Set(["replace","replace_block","style_blocks","remove_block","remove_blocks"]);function Qi(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>ls)return{actions:[],error:`${i} supports at most ${ls} replacements per call`};const a=[];for(let c=0;c<s.length;c++){const g=s[c];if(!g||typeof g!="object")return{actions:[],error:`${i} replacement #${c+1} must be an object`};if(typeof g.find!="string")return{actions:[],error:`${i} replacement #${c+1} is missing "find"`};if(g.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 g.replace!="string")return{actions:[],error:`${i} replacement #${c+1} is missing "replace"`};if(g.occurrence!==void 0&&g.occurrence!==null&&g.occurrence!=="unique"&&g.occurrence!=="all")return{actions:[],error:`${i} replacement #${c+1} has invalid "occurrence"; use "unique" or "all"`};if(g.comment!==void 0&&g.comment!==null&&(typeof g.comment!="string"||g.comment.trim().length===0))return{actions:[],error:`${i} replacement #${c+1} comment must be a non-empty string when provided`};let d=typeof r=="string"?r.trim():"";if(!d&&g.find.length>0&&e&&(d=ss({doc:e.doc,requestedBlockId:"",find:g.find,loadedBlockIds:e.loadedBlockIds})??""),!d)return{actions:[],error:`${i} replacement #${c+1} requires a block id unless its find text uniquely identifies one loaded block`};if(e&&!g.comment)try{const u=Qc({type:"replace",id:d,find:g.find,replace:g.replace,format:"html",all:g.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:Jt(u)}}a.push({id:`${o.id||i}-${c+1}`,name:g.occurrence==="all"?"replace_all":"replace",arguments:{id:d,find:g.find,replace:g.replace,...typeof g.comment=="string"?{comment:g.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 tg(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(!eg.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:cs};for(const d of a.blockIds){if(Ki(t,d))return{actions:[],targetBlockIds:[],error:"Bulk search-result mutations cannot include footnote or endnote bodies. Target those note blocks individually."};const u=Gi(t,d);if(u===null||u!==a.blockHashes.get(d))return{actions:[],targetBlockIds:[],error:`Search result '${s}' is stale because block '${d}' changed or disappeared. Rerun search_document, then retry; no partial mutation was applied.`,errorCode:cs}}const{search_result_id:l,...c}=i,g=[];if(e.name==="replace")for(let d=0;d<a.blockIds.length;d++){const u=Qi({...e,id:`${e.id||"replace"}-search-${d+1}`,arguments:{...c,id:a.blockIds[d]}});if(u.error)return{actions:[],targetBlockIds:[],error:u.error};g.push(...u.actions)}else if(e.name==="replace_block"){const d=i.count;if(d!=null&&d!==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++)g.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 d=0;d<a.blockIds.length;d++)g.push({...e,id:`${e.id||"remove_block"}-search-${d+1}`,arguments:{id:a.blockIds[d],count:1}});else{const d=i.selectors,u=(Array.isArray(d)?d:typeof d=="string"?[d]:[]).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}`}));g.push({...e,arguments:{...c,selectors:p}})}return{actions:g,targetBlockIds:[...a.blockIds],resultSet:a}}function gs(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 go)t[n]===void 0&&o?.[n]===!1&&(t[n]=!1);if(t.docxRunPropertyResets===void 0){const n=xi(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:gs(l.marks,s.marks)}),a+=c,r+=c}}return n}function ng(o,e){const t=Bt(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 me("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 me("attribute_value_unsupported","Cell width must be greater than 0 and at most 100 percent.");const g=n.slice(c.col,c.col+c.colSpan).reduce((d,u)=>d+u,0);for(let d=c.col;d<c.col+c.colSpan;d++){const u=l.percent*n[d]/g;if(i.has(d)&&Math.abs(i.get(d)-u)>.001)throw new me("attribute_conflict","Conflicting cell widths constrain the same table column. Set each column once, using one unmerged row.");i.set(d,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 me("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)}let ig=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});ig.decode();const Zi=new TextEncoder;"encodeInto"in Zi||(Zi.encodeInto=function(o,e){const t=Zi.encode(o);return e.set(t),{read:o.length,written:t.length}});function rg(o,e){return null}function og(o,e){return null}let Hn;function ds(o){if(Hn===void 0){const e=Intl.Segmenter;Hn=e?new e("en",{granularity:"sentence"}):null}return Hn?Array.from(Hn.segment(o),({segment:e})=>e):[o]}const us=/[\p{L}\p{N}\p{M}_'’]/u;function sg(o,e){return e===0||e===o.length||!us.test(o[e-1])||!us.test(o[e])}function je(o,e,t){if(!t)return;const n=o[o.length-1];n?.[0]===e?n[1]+=t:o.push([e,t])}function Wn(o){const e=new Set(nc(o));return t=>e.has(t)&&sg(o,t)}function ag(o){const e=o.filter(([d])=>d!==1).map(([,d])=>d).join(""),t=o.filter(([d])=>d!==-1).map(([,d])=>d).join(""),n=Wn(e),i=Wn(t),r=[];let s=0,a=0,l="",c="";const g=()=>{je(r,-1,l),je(r,1,c),l=c=""};for(const[d,u]of o){if(d===0){let p=0,h=u.length;for(;p<h&&(!n(s+p)||!i(a+p));)p++;for(;h>p&&(!n(s+h)||!i(a+h));)h--;l+=u.slice(0,p),c+=u.slice(0,p),h>p&&(g(),je(r,0,u.slice(p,h))),l+=u.slice(h),c+=u.slice(h)}else d===-1?l+=u:c+=u;d!==1&&(s+=u.length),d!==-1&&(a+=u.length)}return g(),r}function er(o){o=ag(o);const e=[];for(let t=0;t<o.length;t++){const[n,i]=o[t];if(n!==-1||o[t+1]?.[0]!==1){je(e,n,i);continue}const r=o[++t][1],s=Wn(i),a=Wn(r);let l=0;for(;l<Math.min(i.length,r.length)&&i[l]===r[l];)l++;for(;l>0&&(!s(l)||!a(l));)l--;let c=0;for(;c<Math.min(i.length,r.length)-l&&i[i.length-1-c]===r[r.length-1-c];)c++;for(;c>0&&(!s(i.length-c)||!a(r.length-c));)c--;je(e,0,i.slice(0,l)),je(e,-1,i.slice(l,i.length-c)),je(e,1,r.slice(l,r.length-c)),je(e,0,c?i.slice(-c):"")}for(let t=2;t+2<e.length;t++){const[n,i]=e[t];n===0&&/^[\p{L}\p{M}\t ]+$/u.test(i)&&i.trim().length<=12&&i.trim().split(/\s+/).length<=2&&e[t-2][0]===-1&&e[t-1][0]===1&&e[t+1][0]===-1&&e[t+2][0]===1&&Math.max(Math.abs(e[t-1][1].length-e[t-2][1].length),Math.abs(e[t+2][1].length-e[t+1][1].length))>2*i.length&&(e.splice(t-2,5,[-1,e[t-2][1]+i+e[t+1][1]],[1,e[t-1][1]+i+e[t+2][1]]),t=Math.max(1,t-3))}return e}function lg(o,e){if(o===e)return 3;const t=o.match(/[\p{L}\p{N}]+/gu)??[],n=e.match(/[\p{L}\p{N}]+/gu)??[],i=new Map;for(const c of t)i.set(c,(i.get(c)??0)+1);let r=0;for(const c of n){const g=i.get(c)??0;g>0&&(r++,i.set(c,g-1))}const s=Math.min(t.length,n.length);let a=0;for(;a<s&&t[a]===n[a];)a++;const l=2*r/Math.max(1,t.length+n.length);return!(a===t.length&&a>=2)&&a<3&&l<.5?0:l+a/Math.max(1,s)}function cg(o,e,t){if(!o||!e||o===e)return t(o,e);const n=ds(o),i=ds(e);if(n.length*i.length>4096||n.length<=1&&i.length<=1)return er(t(o,e));const r=i.length+1,s=new Float64Array((n.length+1)*r),a=new Float64Array(n.length*i.length);for(let h=n.length-1;h>=0;h--)for(let f=i.length-1;f>=0;f--){const m=lg(n[h],i[f]);a[h*i.length+f]=m,s[h*r+f]=Math.max(s[(h+1)*r+f],s[h*r+f+1],m>0?m+s[(h+1)*r+f+1]:0)}const l=[];let c=0,g=0,d="",u="";const p=()=>{for(const[h,f]of er(t(d,u)))je(l,h,f);d=u=""};for(;c<n.length&&g<i.length;){const h=a[c*i.length+g];if(h>0&&s[c*r+g]===h+s[(c+1)*r+g+1]){p();const f=n[c++],m=i[g++],y=f.trimEnd(),b=m.trimEnd();for(const[k,I]of er(t(y,b)))je(l,k,I);for(const[k,I]of t(f.slice(y.length),m.slice(b.length)))je(l,k,I)}else s[(c+1)*r+g]>=s[c*r+g+1]?d+=n[c++]:u+=i[g++]}return d+=n.slice(c).join(""),u+=i.slice(g).join(""),p(),l}const Le=-1,nt=0,Ne=1;function Yn(o){return/[\p{L}\p{N}]/u.test(o)}function gg(o,e){const t=Math.min(o.length,e.length);let n=0;for(;n<t&&o[n]===e[n];)n++;return n}function dg(o,e){const t=Math.min(o.length,e.length);let n=0;for(;n<t&&o[o.length-1-n]===e[e.length-1-n];)n++;return n}function hs(o){const e=[];for(const[t,n]of o)n.length!==0&&(e.length>0&&e[e.length-1][0]===t?e[e.length-1][1]+=n:e.push([t,n]));return e}function ug(o){const e=[];for(let t=0;t<o.length;t++){const n=o[t],i=o[t+1];if(!n||!i||n[0]!==Le||i[0]!==Ne){e.push(n);continue}const r=n[1],s=i[1];let a=gg(r,s);if(a>0){const c=r.slice(0,a),g=r.slice(a),d=s.slice(a);if(!Yn(g)&&!Yn(d)){e.push([nt,c]),g.length>0&&e.push([Le,g]),d.length>0&&e.push([Ne,d]),t+=1;continue}}const l=dg(r,s);if(l>0&&l<r.length&&l<s.length){const c=r.slice(r.length-l),g=r.slice(0,-l),d=s.slice(0,-l);if(!Yn(g)&&!Yn(d)){g.length>0&&e.push([Le,g]),d.length>0&&e.push([Ne,d]),e.push([nt,c]),t+=1;continue}}e.push(n)}return hs(e)}function fs(o){const e=[],t=o.match(/^\s*/),n=t?t[0]:"";let i=o.slice(n.length);const r=/(\S+)(\s*)/g;let s;for(;(s=r.exec(i))!==null;)e.push({word:s[1],trailingWs:s[2]});return{leadingWs:n,tokens:e}}function hg(o,e){const t=Math.min(o.length,e.length);let n=0;for(;n<t&&o[n]===e[n];)n++;let i=0;for(;i<t-n&&o[o.length-1-i]===e[e.length-1-i];)i++;const r=o.slice(n,o.length-i),s=e.slice(n,e.length-i),a=r.length,l=s.length,c=Array(a+1).fill(null).map(()=>Array(l+1).fill(0));for(let h=1;h<=a;h++)for(let f=1;f<=l;f++)r[h-1]===s[f-1]?c[h][f]=c[h-1][f-1]+1:c[h][f]=Math.max(c[h-1][f],c[h][f-1]);const g=[];let d=a,u=l;for(;d>0&&u>0;)r[d-1]===s[u-1]?(g.push({originalIndex:n+d-1,newIndex:n+u-1}),d--,u--):c[d-1][u]>c[d][u-1]?d--:u--;g.reverse();const p=Array.from({length:n},(h,f)=>({originalIndex:f,newIndex:f}));p.push(...g);for(let h=0;h<i;h++)p.push({originalIndex:o.length-i+h,newIndex:e.length-i+h});return p}function tr(o,e,t){if(e===t)return e.length>0?[[nt,e]]:[];if(e.length===0)return t.length>0?[[Ne,t]]:[];if(t.length===0)return[[Le,e]];const n=rg();return n!==null?n:ps(o,e,t)}function ps(o,e,t){if(e===t)return e.length>0?[[nt,e]]:[];if(e.length===0)return t.length>0?[[Ne,t]]:[];if(t.length===0)return[[Le,e]];const n=fs(e),i=fs(t),r=n.tokens,s=i.tokens;if(r.length===0&&s.length===0)return e===t?[[nt,e]]:[[Le,e],[Ne,t]];if(r.length===0)return[[Le,e],[Ne,t]];if(s.length===0)return[[Le,e],[Ne,t]];const a=n.leadingWs,l=i.leadingWs,c=[];a===l?a.length>0&&c.push([nt,a]):(a.length>0&&c.push([Le,a]),l.length>0&&c.push([Ne,l]));const g=r.map(f=>f.word),d=s.map(f=>f.word),u=hg(g,d);let p=0,h=0;for(const f of u){for(;p<f.originalIndex;){const k=r[p];c.push([Le,k.word+k.trailingWs]),p++}for(;h<f.newIndex;){const k=s[h];c.push([Ne,k.word+k.trailingWs]),h++}const m=r[f.originalIndex],y=s[f.newIndex];let b=0;for(;b<m.trailingWs.length&&b<y.trailingWs.length&&m.trailingWs[b]===y.trailingWs[b];)b++;c.push([nt,m.word+m.trailingWs.slice(0,b)]),m.trailingWs.length>b&&c.push([Le,m.trailingWs.slice(b)]),y.trailingWs.length>b&&c.push([Ne,y.trailingWs.slice(b)]),p=f.originalIndex+1,h=f.newIndex+1}for(;p<r.length;){const f=r[p];c.push([Le,f.word+f.trailingWs]),p++}for(;h<s.length;){const f=s[h];c.push([Ne,f.word+f.trailingWs]),h++}return ug(hs(c))}function qn(o,e){const t=o.split(`
|
|
21
|
+
`),n=e.split(`
|
|
22
|
+
`),i=t.length>1||n.length>1,r=cg(o,e,(l,c)=>tr([],l,c)),s=Math.max(o.length,e.length);let a=0;for(const[l,c]of r)l!==nt&&(a+=c.length);return{changePercentage:s>0?a/s*100:0,hasMultipleLines:i,diffs:r}}const fg=Object.freeze(Object.defineProperty({__proto__:null,analyzeParagraphDiff:qn,roundDiffsToWordBoundaries:tr,roundDiffsToWordBoundariesJs:ps},Symbol.toStringTag,{value:"Module"}));function ms(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 g=l;g<l+c;g++)if(n[g]?.length)return{success:!1,error:`content[${g}] targets a position covered by a merged cell. Leave that slot empty or insert outside the merged span; the table was not changed.`}}}function pg(o){return{type:"paragraph",id:Y(),children:[{type:"text",text:""}]}}function mg(o){return{type:"table-cell",id:Y(),children:[pg()]}}function bs(o,e){return!o||o.length===0?mg():{type:"table-cell",id:Y(),children:o}}function Jn(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 nr(o,e){const t=Number(te(o,e));return Number.isFinite(t)&&t>1?Math.floor(t):1}function Kn(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 g=a.get(c);g instanceof S.XmlElement&&g.nodeName==="table-cell"&&(l+=nr(g,"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,g=0;for(let d=0;d<l.length;d++){const u=l.get(d);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(nr(u,"colSpan"),n-c),h=Math.min(nr(u,"rowSpan"),i-a),f={el:u,row:a,col:c,rowSpan:h,colSpan:p,physicalIndex:g};s.push(f);for(let m=a;m<a+h;m++)for(let y=c;y<c+p;y++)r[m][y]===void 0&&(r[m][y]=f);c+=p,g++}}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 ys(o){return ye(o)}function bg(o){const e=new S.XmlElement("table-row");e.setAttribute("id",o.id);let t=0;for(const n of o.children){const i=ys(n);e.insert(t++,[i])}return e}function yg(o,e,t){const n=Jn(o,e);if(!n)return{success:!1,error:`Table with ID "${e}" not found.`};const i=Kn(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((g,d)=>g+d,0),c=l>0?s.map(g=>g+a*g/l):s;n.setAttribute("columnWidths",JSON.stringify(c))}}}),{success:!0})}function kg(o,e){const t=Kn(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 g=s.filter(d=>d.col<l.col).length+a;r.insert(g,[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 Sg(o,e,t){const n=Jn(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(()=>{kg(n,t)}),{success:!0}):{success:!1,error:`Table with ID "${e}" not found.`}}function Ig(o,e,t,n,i){const r=Jn(o,e);if(!r)return{success:!1,error:`Table with ID "${e}" not found.`};const s=Kn(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 ms(s,"column",l,i)||(o.transact(()=>{for(let d=0;d<s.rows;d++){const u=l>0&&l<a&&s.occupancy[d][l-1]===s.occupancy[d][l]?s.occupancy[d][l]:void 0;if(u){u.row===d&&Zt(u.el,"colSpan",u.colSpan+1);continue}const p=i?.[d],h=bs(p),f=ys(h),m=s.cells.filter(y=>y.row===d&&y.col<l).length;s.rowEls[d].insert(m,[f])}const g=r.getAttribute("columnWidths");if(g){const d=JSON.parse(g),u=100/(a+1),p=(100-u)/100,h=d.map(f=>f*p);h.splice(l,0,u),r.setAttribute("columnWidths",JSON.stringify(h))}}),{success:!0})}function vg(o,e,t,n){const i=Kn(e);return ms(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(bs(n?.[u]));const c={id:Y(),children:l},g=bg(c);let d=e.length;if(t<i.rows){const u=i.rowEls[t];for(let p=0;p<e.length;p++)if(e.get(p)===u){d=p;break}}e.insert(d,[g])}),{success:!0})}function xg(o,e,t,n,i){const r=Jn(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 vg(o,r,a,i)}const ks=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 Ag(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(ks.has(t))return!0;if(e.length>=3){const n=e[e.length-2].toLowerCase();if(ks.has(n))return!0}return!1}catch{return!1}}function wg(o){return/^https?:\/\//i.test(o)?o:`https://${o}`}function Ss(o){return o===" "||o===" "||o===`
|
|
23
|
+
`||o==="\r"}function Is(o){if(!o||o.length<4)return[];const e=[];let t=0;for(;t<o.length;){if(Ss(o[t])){t++;continue}let n=t,i=t;for(;i<o.length&&!Ss(o[i]);)i++;const r=o.slice(n,i);Ag(r)&&e.push({url:wg(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 $t(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 Tg(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 Cg(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=zt(o);for(const r of i.toArray())if(r instanceof S.XmlElement&&n(r))return}function Pg(o,e,t,n=3){const i=et(t)?Vt(t):Kt(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 Cg(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 Bg(o,e,t){const n=Pg(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 ir=new WeakMap;function rr(o){return ir.get(o)}const ge=o=>({kind:"block",...o}),Ae=o=>({kind:"textMark",...o}),Fg=new Set(["bold","italic","underline","strikethrough","doubleStrikethrough","smallCaps","allCaps","code","superscript","subscript"]),vs={fontSize:{integer:!0,min:1,max:512},letterSpacing:{min:-20,max:100}},Mg=[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}),Ae({attr:"bold",valueType:"boolean",aliases:["fontWeight","font-weight"]}),Ae({attr:"italic",valueType:"boolean",aliases:["fontStyle","font-style"]}),Ae({attr:"underline",valueType:"boolean",aliases:["textDecoration","text-decoration"]}),Ae({attr:"strikethrough",valueType:"boolean",aliases:["strike","line-through"]}),Ae({attr:"doubleStrikethrough",valueType:"boolean",aliases:["double-strikethrough","double-strike","dstrike"]}),Ae({attr:"smallCaps",valueType:"boolean",aliases:["small-caps","fontVariant","font-variant"]}),Ae({attr:"allCaps",valueType:"boolean",aliases:["all-caps","caps"]}),Ae({attr:"letterSpacing",valueType:"number",min:-20,max:100,aliases:["letter-spacing","characterSpacing","character-spacing"]}),Ae({attr:"code",valueType:"boolean"}),Ae({attr:"superscript",valueType:"boolean"}),Ae({attr:"subscript",valueType:"boolean"}),Ae({attr:"fontSize",valueType:"number",integer:!0,min:1,max:512,aliases:["font-size"]}),Ae({attr:"fontFamily",valueType:"string",aliases:["font-family"]}),Ae({attr:"backgroundColor",valueType:"string",aliases:["background-color","background","highlightColor","highlight-color"]}),Ae({attr:"color",valueType:"string"}),Ae({attr:"link",valueType:"string",aliases:["href"]})],or=new Map,xs=(o,e)=>{const t=o.toLowerCase(),n=or.get(t)??[];n.push(e),or.set(t,n)};for(const o of Mg){xs(o.attr,o);for(const e of o.aliases??[])xs(e,o)}const As={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=ee(o);let t="";for(const n of e)n.insert&&typeof n.insert=="string"&&(t+=n.insert);return t}function ws(o,e,t){if(ft(e).length===0)return!!yt(o.getAttribute("_emptyTextMarks"))[t];const n=ee(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 Eg(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 Vn(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 Ts(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 $g(o,e,t){const n=Nt(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 Lg(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 Cs(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 Ps(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 Bs(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=Nt(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 sr(o,e,t){if(t===void 0){q(o,e);return}o.setAttribute(e,String(t))}function Fs(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(Bs("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;sr(o,"firstLineIndent",i),sr(o,"leftIndent",r)}function Ms(o,e,t){if(t===null){q(o,e);return}const n=e==="leftIndent"?Re(t):De(t);sr(o,e,n)}function Nt(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=wi(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 it(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 we(o){const e=o.getAttribute("id");return typeof e=="string"&&e.length>0?e:o.nodeName}function Gn(o){return or.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"&&Ng(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 Ng(o){const e=o.trim().replace(/\s*!important\s*$/i,"").trim().toLowerCase();return["inherit","initial","unset","revert","revert-layer"].includes(e)}function ar(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 Es(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 Ot(o,e,t,n){const i=Nt(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 Pe(o,e,t,n){const i=we(e);if(t){it(o,i,t);return}const r=`Updated ${n} on ${e.nodeName} block.`;o.push({kind:"replace",paragraphId:i,text:r,oldText:r})}function Qn(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 $s(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=!ws(t,n,i);else if(a.valueType==="boolean")c=s===void 0?!0:ar(e,i,s);else{if(s===void 0)throw new Error(`${e} "${i}" requires a value.`);a.valueType==="number"?c=Ot(e,i,s,a):c=pt(e,i,s)}if(i==="fontFamily"){const g=Qn(t,c);if(g)throw new Error(g)}if(n.length>0)ie(n,0,n.length,{[i]:c===null?null:c}),it(l,we(t),n);else{Ts(t,i,c);const g=`Text mark "${i}" ${c===null?"removed":"set"}.`;l.push({kind:"replace",paragraphId:we(t),text:g,oldText:g})}}const Ls=new Set(["fontSize","fontFamily","color"]);function Ns(o){const{toolName:e,yBlock:t,attribute:n,operation:i,value:r,config:s,anchors:a}=o;if(!Ls.has(n))throw new Error(`${e} "${n}" cannot style a table of contents: its entries are generated from the document's headings. A table of contents supports fontSize, fontFamily, color; style the headings themselves for other text formatting.`);if(i==="toggle")throw new Error(`${e} "${n}" does not support toggle. Use operation "set" with a value or "remove".`);if(i==="remove"||r===null)t.removeAttribute(n);else{if(r===void 0)throw new Error(`${e} "${n}" requires a value.`);if(n==="fontSize"){const l=Ot(e,n,r,s);if(!Pl(l))throw new Error(`${e} "fontSize" on a table of contents must be between ${Bl} and ${Fl} 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))}Pe(a,t,null,n)}function Og(o){const{yBlock:e}=o;if(e.nodeName==="paragraph"||e.nodeName==="list-item"){$s({...o,yText:ue(e)});return}if(e.nodeName==="toc"){Ns(o);return}const t=[],n=[],i=l=>{for(let c=0;c<l.length;c++){const g=l.get(c);if(g instanceof S.XmlElement&&!o.independentlySelectedTargets?.has(g)){if(g.nodeName==="paragraph"||g.nodeName==="list-item"){t.push(g);continue}if(g.nodeName==="toc"){Ls.has(o.attribute)&&n.push(g);continue}i(g)}}};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 g=Qn(c,l);if(g)throw new Error(g)}}let r=0;const s=[],a=l=>{try{$s({...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{Ns({...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 Rg(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 g;if(r==="remove"||s===null?g=null:a.valueType==="boolean"?g=ar(e,i,s):a.valueType==="number"?g=Ot(e,i,s,a):g=pt(e,i,s),i==="fontFamily"){const d=Qn(t,g);if(d)throw new Error(d)}for(const d of n)ie(c,d.start,d.length,{[i]:g===null?null:g});it(l,we(t),c)}function lr(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"){Fs(t,i,r),Pe(a,t,ue(t),n);return}if(n==="padding"&&t.nodeName==="table-cell"){if(i==="remove"||r===null)q(t,n);else{const l=Ot(e,n,r,s);t.setAttribute(n,JSON.stringify({top:l,right:l,bottom:l,left:l}))}Pe(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 g={top:c,right:c,bottom:c,left:c};t.nodeName==="table"&&(g.insideH=c,g.insideV=c);const d=Cn(g);d&&t.setAttribute("borders",d)}Pe(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=Ri(te(t,"borders")),c=n==="borderColor"?pt(e,n,r):Ot(e,n,r,s),g=["top","right","bottom","left"],d={};for(const p of g){const h=l?.[p]??{style:"single",width:1,color:"#cccccc"};d[p]={...h,...n==="borderColor"?{color:c}:{width:c}}}const u=Cn(d);u&&t.setAttribute("borders",u)}Pe(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=Ps(te(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(ar(e,n,r)):l=String(Ot(e,n,r,s)),t.nodeName==="paragraph"&&(n==="leftIndent"||n==="firstLineIndent")?Ms(t,n,Number(l)):t.setAttribute(n,l)}Pe(a,t,ue(t),n)}function Dg(o){if(o.config.nodeNames.includes(o.yBlock.nodeName)){lr(o);return}if(!(o.config.nodeNames.includes("paragraph")||o.config.nodeNames.includes("list-item"))){lr(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{lr({...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 _g(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[zt(o),o.getXmlFragment("notes")])for(const i of n.toArray())i instanceof S.XmlElement&&t(i);return e}function cr(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 jg(o,e){const t=[],n=i=>{for(let r=0;r<i.length;r++){const s=i.get(r);s instanceof S.XmlElement&&(cr(s).includes(e)&&t.push(s),n(s))}};return n(o),t}function Xg(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 en(o){return o.toLowerCase()==="th"?"td":o.toLowerCase()}function gr(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:en(e[1]),nthChild:t}}function tn(o,e){if(e.tag!=="*"&&!cr(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 Os(o,e){if(!tn(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&&!tn(t,e[n]);)t=t.parent;if(!(t instanceof S.XmlElement))return!1;t=t.parent}return!0}const dr={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 Ug(o){const e=o.split(/\s+/).filter(Boolean),t=e.findIndex(i=>dr[i.toLowerCase()]!==void 0);if(t<0)return null;const n=e.slice(t).map(i=>i.toLowerCase());return n.some(i=>!dr[i])?null:{scopeSelector:t===0?"*":e.slice(0,t).join(" "),markAttributes:Array.from(new Set(n.map(i=>dr[i])))}}function zg(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 Hg(o,e){if(e==="*")return!0;const t=o?.[e];return e==="link"||e==="backgroundColor"?typeof t=="string"&&t.length>0:t===!0}function Wg(o,e){const t=[];let n=0;for(const i of ee(o)){if(typeof i.insert!="string")continue;const r=i.insert.length,s=i.attributes;if(r>0&&e.every(a=>Hg(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 Yg(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 qg(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 Rs(o,e){const t=_g(o),n=[],i=new Set,r=[],s=[],a=l=>{const c=we(l),g=`${l.nodeName}:${c}`;i.has(g)||(i.add(g),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=en(c[1]),y=(c[2]??c[3]??c[4]).trim(),b=t.filter(k=>tn(k,{tag:m})&&k.getAttribute("styleId")===y);b.length===0&&r.push(l);for(const k of b)a(k);continue}const g=l.match(/^#([A-Za-z0-9_-]+)\s*~\s*(\*|[a-zA-Z][a-zA-Z0-9-]*)$/);if(g){const m=J(o,g[1]),y=m?.parent;if(!m||!(y instanceof S.XmlElement)&&!(y instanceof S.XmlFragment)){r.push(l);continue}const b=y.toArray(),k=b.indexOf(m),I=en(g[2]),v=t.filter(x=>x.parent===y&&b.indexOf(x)>k&&tn(x,{tag:I}));v.length===0&&r.push(l);for(const x of v)a(x);continue}const d=l.match(/^#([A-Za-z0-9_-]+)\s+(.+)$/);if(d){const m=J(o,d[1]);if(!m){r.push(l);continue}const y=d[2].split(/\s+/).filter(Boolean).map(gr);if(y.some(v=>v===null)){s.push(`selector "${l}" is not supported; descendants may use block tags, :first-child, and :nth-child(n).`);continue}const b=y,k=v=>{let x=v;for(;x;){if(x===m)return!0;x=x.parent}return!1},I=t.filter(v=>k(v)&&(b.length!==1||b[0].tag!=="*"||v!==m)&&Os(v,b));I.length===0&&r.push(l);for(const v of I)a(v);continue}const u=Xg(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 y=jg(m,en(u.tag));if(y.length===0){r.push(l);continue}for(const b of y)a(b);continue}if(l.includes(" ")&&!l.startsWith("#")){const m=l.split(/\s+/).filter(Boolean).map(gr);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 y=m;if(y.some(k=>k.tag==="span")){s.push(`selector "${l}" contains an inline selector; target its containing block instead.`);continue}const b=t.filter(k=>Os(k,y));b.length===0&&r.push(l);for(const k of b)a(k);continue}if(l.startsWith("#")){const m=l.slice(1).trim();if(!m||/[\s.#:[\]>+~]/.test(m)){s.push(`selector "${l}" is not supported; use #blockId with a plain block ID.`);continue}const y=J(o,m);y?a(y):r.push(l);continue}const p=gr(l);if(p){let m=0;for(const y of t)tn(y,p)&&(a(y),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=en(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)cr(m).includes(h)&&(a(m),f++);f===0&&r.push(l)}return{targets:n,unmatchedSelectors:r,invalidSelectorErrors:s}}function Jg(o,e){const t=qg(e),n=[],i=[];for(const c of t){const g=Ug(c);g?i.push({selector:c,parsed:g}):n.push(c)}const r=n.length>0?Rs(o,n):{targets:[],unmatchedSelectors:[],invalidSelectorErrors:[]},s=new Map,a=[...r.unmatchedSelectors],l=[...r.invalidSelectorErrors];for(const{selector:c,parsed:g}of i){const d=Rs(o,[g.scopeSelector]);if(d.invalidSelectorErrors.length>0){l.push(...d.invalidSelectorErrors.map(h=>`selector "${c}": ${h}`));continue}let u=0;const p=new Set;for(const h of d.targets)for(const f of zg(h)){const m=we(f);if(p.has(m))continue;p.add(m);const y=ue(f);if(!y)continue;const b=Wg(y,g.markAttributes);if(b.length===0)continue;u+=b.length;const k=s.get(m);k?k.ranges=Yg(k.ranges,b):s.set(m,{yBlock:f,ranges:b})}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 Kg(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 Vg(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 d=a.trim().toLowerCase();["decimal","number","numbered","numeric","ol"].includes(d)?c="ordered":["disc","circle","square","bullet","bulleted","ul"].includes(d)?c="unordered":["check","checklist","checkbox","task"].includes(d)&&(c="todo")}const g={rawName:r,entry:s,value:c};if(n.has(l)){const d=e.findIndex(u=>`${u.entry.kind}:${u.entry.attr}`===l);d>=0&&(e[d]=g);return}n.add(l),e.push(g)};for(const{rawName:r,value:s}of o){if(r.trim().toLowerCase()==="border"){if(typeof s=="string"&&Tn(s)){for(const g of Gn("borders"))i(r,g,s);continue}const l=Gn("borderWidth"),c=Gn("borderColor");if(s===null||typeof s=="number"){for(const g of l)i(r,g,s);if(s===null)for(const g of c)i(r,g,null);continue}if(typeof s=="string"){const g=s.match(/(?:^|\s)(\d+(?:\.\d+)?)(?:px|pt)?(?:\s|$)/i),d=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(g)for(const u of l)i(r,u,g[1]);if(d)for(const u of c)i(r,u,d[1]);if(g||d)continue}t.push(r);continue}const a=Gn(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 Ds(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(g=>g.entry.kind==="block"&&g.entry.nodeNames.some(d=>d===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(g=>g===e.nodeName));i.push(...l.length>0?l:s)}return i}function _s(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: ${Yt.join(", ")}.`);const n=t.value.trim(),i=_e(n);if(!i)throw new Error(`style_blocks "backgroundColor" does not support ${JSON.stringify(n)} as a text highlight. Use one of: ${Yt.join(", ")}.`);t.value=i,n.toLowerCase()!==i&&e.push(`${t.rawName}: ${n} -> ${i}`)}return e}function Rt(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 Zn(o,e){for(let t=o.length-1;t>=0;t--)if(o[t].canonicalName===e)return o[t]}function Xe(o){return typeof o=="string"?o.trim().toLowerCase():void 0}function nn(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 ei(o){return o===0?!0:typeof o=="string"&&/^[-+]?0+(?:\.0+)?(?:px|pt|in|cm|mm|%)?$/i.test(o.trim())}function Gg(o){let e=o;for(;e.parent instanceof S.XmlElement;)e=e.parent;return e}function ur(o,e){const t=we(Gg(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=ho(o.pageLayout,i?.type==="section-break"?i.layout:void 0),{pageWidth:s}=oo(r),a=Math.max(1,s-r.marginLeftPx-r.marginRightPx),l=r.columnGapTwips/15;return Math.max(1,Math.round(ic(a,r.columnCount,l)))}function Qg(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"||ei(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 Zg(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=Qg(t.value);if(!i){Rt(o.result,t,"errors",`${we(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(te(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"),Pe(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 ed(o){if(o.yBlock.nodeName!=="image")return;const e=x=>Zn(o.rawAttrs,x),t=e("display");t&&Xe(t.value)==="block"&&(o.result.handledRawNames.add(t.canonicalName),Rt(o.result,t,"ignoredAttrs",`${t.rawName}: block`));const n=e("float"),i=Xe(n?.value);n&&(i==="left"||i==="right")&&(o.result.handledRawNames.add(n.canonicalName),o.yBlock.setAttribute("align",i),Pe(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=Xe(r?.value),l=Xe(s?.value);let c;a==="auto"&&l==="auto"?c="center":a==="auto"&&(!s||ei(s.value))?c="right":l==="auto"&&(!r||ei(r.value))&&(c="left"),c&&(r&&o.result.handledRawNames.add(r.canonicalName),s&&o.result.handledRawNames.add(s.canonicalName),o.yBlock.setAttribute("align",c),Pe(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),ei(A.value)?Rt(o.result,A,"ignoredAttrs",`${A.rawName}: ${String(A.value)}`):Rt(o.result,A,"unsupportedImageSpacing",`${A.rawName}: ${String(A.value)}`))}const g=e("width"),d=e("maxwidth"),u=e("height"),p=Xe(u?.value)==="auto",h=nn(g?.value),f=nn(d?.value),m=ur(o.doc,o.yBlock),y=Math.max(1,Number(o.yBlock.getAttribute("width"))||1),b=Math.max(1,Number(o.yBlock.getAttribute("height"))||1);let k=y,I=!1,v=!1;if(h!==void 0&&g)k=Math.max(1,Math.round(m*h/100)),o.result.handledRawNames.add(g.canonicalName),I=!0,v=!0;else if(p&&g){const x=Nt("width",g.value);Number.isFinite(x)&&x>0&&(k=Math.max(1,Math.round(x)),o.result.handledRawNames.add(g.canonicalName),I=!0,v=!0)}if(f!==void 0&&d){const x=Math.max(1,Math.round(m*f/100));k=Math.min(k,x),o.result.handledRawNames.add(d.canonicalName),I=!0,o.result.approximateMappings.push(`${d.rawName}: ${String(d.value)} -> fixed ${k}px snapshot`)}if(I){o.yBlock.setAttribute("width",String(k));const x=u&&!p?Nt("height",u.value):Number.NaN,A=p||!Number.isFinite(x);if(A){const T=Math.max(1,Math.round(b*k/y));o.yBlock.setAttribute("height",String(T))}p&&u&&o.result.handledRawNames.add(u.canonicalName),Pe(o.anchors,o.yBlock,null,"width/height"),o.result.appliedAttrs.push("responsive image size -> fixed snapshot"),v&&g&&o.result.approximateMappings.push(`${g.rawName}: ${String(g.value)} -> fixed ${k}px snapshot${A?" with auto height":""}`)}else p&&u&&(o.result.handledRawNames.add(u.canonicalName),Rt(o.result,u,"ignoredAttrs",`${u.rawName}: auto`))}function td(o){if(o.yBlock.nodeName!=="table")return;const e=s=>Zn(o.rawAttrs,s),t=e("width"),n=nn(t?.value);if(t&&n!==void 0){const s=ur(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)),Pe(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");Xe(i?.value)==="auto"&&Xe(r?.value)==="auto"&&(o.result.handledRawNames.add(i.canonicalName),o.result.handledRawNames.add(r.canonicalName),o.yBlock.setAttribute("align","center"),Pe(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=>Zn(o.rawAttrs,a),t=e("breakafter"),n=e("breakbefore"),i=e("breakinside");if(!t&&!n&&!i)return;const r=new Set(String(te(o.yBlock,"pagination")??"").split(",").filter(Boolean));t&&(o.result.handledRawNames.add(t.canonicalName),t.value===null||Xe(t.value)==="auto"?r.delete("keepNext"):["avoid","avoid-page"].includes(Xe(t.value)??"")&&r.add("keepNext"),o.result.appliedAttrs.push(`${t.rawName} -> keepNext`)),i&&(o.result.handledRawNames.add(i.canonicalName),i.value===null||Xe(i.value)==="auto"?r.delete("keepLines"):["avoid","avoid-page"].includes(Xe(i.value)??"")&&r.add("keepLines"),o.result.appliedAttrs.push(`${i.rawName} -> keepLines`)),n&&(o.result.handledRawNames.add(n.canonicalName),Rt(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"),Pe(o.anchors,o.yBlock,ue(o.yBlock),"pagination")}function id(o){const e={issuesByRawName:new Map,handledRawNames:new Set,appliedAttrs:[],exactMappings:[],approximateMappings:[],ignoredAttrs:[],unsupportedImageSpacing:[],errors:[]};return Zg({yBlock:o.yBlock,rawAttrs:o.rawAttrs,anchors:o.anchors,result:e}),nd({...o,result:e}),ed({...o,result:e}),td({...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,g=o.styleEffects,d=[`style_blocks ${g.outcome==="partial"?"partially applied requested styling":g.outcome==="unchanged"?"verified requested styling unchanged":"applied requested styling"}. Matched ${g.targetBlockIds.length} blocks${e?` and ${e} inline ranges`:""}; changed ${g.changedBlockIds.length} blocks.`,...g.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&&d.push(`Compatibility mappings: ${Array.from(new Set(s)).join("; ")}.`),a.length>0&&d.push(`Approximate compatibility mappings: ${Array.from(new Set(a)).join("; ")}.`),l.length>0&&d.push(`Ignored compatibility attrs: ${Array.from(new Set(l)).join(", ")}.`),c.length>0&&d.push(`Unsupported image spacing ignored: ${Array.from(new Set(c)).join(", ")}.`),n.length>0&&d.push(`Unmatched selectors: ${n.join(", ")}.`),i.length>0&&d.push(`Invalid selectors ignored: ${i.join("; ")}.`),t.length>0&&d.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;d.push(`Skipped invalid target/style pairs: ${p.join("; ")}${h>0?`; and ${h} more`:""}.`)}return d.join(" ")}function od(o){const e=yt(o.getAttribute("_emptyTextMarks"));for(const t of Oo)delete e[t];Object.keys(e).length===0?o.removeAttribute("_emptyTextMarks"):o.setAttribute("_emptyTextMarks",JSON.stringify(e))}function sd(o,e=1){if(typeof o!="number"||!Number.isFinite(o))return e;const t=Math.floor(o);return t>=1?t:e}function ad(o){const e=ue(o);if(e){const n=ee(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 js(o,e,t){const n=ad(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 ld(o,e){const t=o.parent;if(!(t instanceof S.XmlElement)&&!(t instanceof S.XmlFragment)||o.nodeName!=="list")return!1;const n=t.toArray().indexOf(o);if(n<0)return!1;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=te(r,"direction");(a==="ltr"||a==="rtl")&&s.setAttribute("direction",a);const l=r.getAttribute("_emptyTextMarks");l&&s.setAttribute("_emptyTextMarks",l);const c=ue(r),g=new S.XmlText;c&&Cl(g,ee(c)),s.insert(0,[g]),i.push(s)}if(i.length===0)return!1;js(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!0}function Xs(o,e){if(e.link)return[{text:o,marks:e}];const t=Is(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 ti(o){return ye(fo(o,e=>!e.text||e.marks?.link?e:Xs(e.text,e.marks||{}).map(t=>({type:"text",text:t.text,marks:t.marks}))))}function Us(o,e){return qt(Ic(e==="todo"?{...o,checked:o.checked??!1}:o))}function zs(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 rt(o,e,t,n){const i=Xs(t,n);let r=e;for(const s of i)ne(o,r,s.text,s.marks),r+=s.text.length;return r}function Hs(o,e,t){const n=o.toString(),i=t??n.length,r=n.slice(e,i),s=Is(r);for(const a of s){const l=e+a.start;ie(o,l,a.end-a.start,{link:a.url})}}function hr(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 ni(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=Ye(e);n===void 0?q(o,"pagination"):o.setAttribute("pagination",n)}function cd(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 gd(o,e){return o.type!==e.type?!1:o.type==="paragraph"&&e.type==="paragraph"?hr(o,e):cd(o.children,e.children)}function Ws(o){return o.map(e=>({...e,marks:e.marks?{...e.marks}:void 0}))}function Ys(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 qs(o){return o.replace(/�?39;|'/g,"'").trim()}function dd(o,e,t){const n=o.indexOf(e);return n===-1?o:o.slice(0,n)+t+o.slice(n+e.length)}function ud(o,e){if(e.type==="paragraph")return qs(Z.toAgentHtml({type:"doc",children:[{...e,children:Ws(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:Ws(e.children),indentLevel:void 0}]},n=qs(Z.toAgentHtml({type:"doc",children:[t]})).match(/^<(?:ul|ol)(?:\s[^>]*)?>([\s\S]*)<\/(?:ul|ol)>$/);return n?n[1].trim():null}function hd(o,e,t,n){try{if(t.type==="paragraph"){const s=Z.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=Z.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 fd(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: ${Yt.join(", ")}.`}function pd(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: ${Yt.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 ot(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 md(o){return Object.fromEntries(Object.entries(o).sort(([e],[t])=>e<t?-1:e>t?1:0))}function ii(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 bd(o){return o.length===0?[]:o.reduce((e,t)=>e.filter(n=>t.includes(n)))}const bt=-1,fr=0,rn=1;function yd(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]===rn||n===rn&&r[0]===bt))){e.push([n,i]);continue}const s=n===bt?i:r[1],a=n===rn?i:r[1];let l=0;const c=Math.min(s.length,a.length);for(;l<c&&s[l]===a[l];)l++;let g=0;const d=c-l;for(;g<d&&s[s.length-1-g]===a[a.length-1-g];)g++;l>0&&e.push([fr,s.slice(0,l)]);const u=s.slice(l,s.length-g),p=a.slice(l,a.length-g);u.length>0&&e.push([bt,u]),p.length>0&&e.push([rn,p]),g>0&&e.push([fr,s.slice(s.length-g)]),t++}return e}function kd(o,e){const t=ii(o),n=ii(e),i=yd(tr([],t.map(g=>g.value).join(""),n.map(g=>g.value).join(""))),r=new Array(n.length),s=new Array(n.length);let a=0,l=0;for(let g=0;g<i.length;g++){const[d,u]=i[g];if(d===fr){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(d===bt){a+=u.length;continue}if(d!==rn)continue;const p=i[g-1],h=i[g+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),y=bd(m.map(I=>I.comment)),b=m[0]?.marks.lang,k=typeof b=="string"&&m.every(I=>I.marks.lang===b)?b:void 0;for(let I=0;I<u.length;I++)r[l+I]=y,s[l+I]=k;l+=u.length}const c=[];return n.forEach((g,d)=>{const u=r[d]??[],p=md({...g.marks,...g.marks.lang===void 0&&s[d]!==void 0?{lang:s[d]}:{},...u.length>0?{comment:u.join(",")}:{}}),h=c[c.length-1];h&&ot(h.marks)===ot(p)?h.text+=g.value:c.push({type:"text",text:g.value,...Object.keys(p).length>0?{marks:p}:{}})}),c}function Sd(o,e){const t=ii(o),n=ii(e);return t.length===n.length&&t.every((i,r)=>i.value===n[r].value&&ot(i.marks)===ot(n[r].marks)&&i.comment.join(",")===n[r].comment.join(","))}function Ks(o,e,t,n,i){if(t=Ft(t),n=Ft(n),t.length===0)return null;const r=Ys(e,o.blockId);if(!r)return null;const s=ud(o,r),a=s?Ft(s):null;if(!a||!a.includes(t))return null;const l=Uo(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.`);pd(n);const c=i?a.split(t).join(n):dd(a,t,n);if(c===a)return null;const g=hd(o,c,r,e);if(!g)throw new Error(`Matched AgentHtml in block '${o.blockId}', but the replacement is not a supported single-block text update.`);if(g.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 d={...g,children:kd(r.children,zn(r.children,g.children))};if(gd(r,d)||Sd(r.children,d.children)&&(r.type!=="paragraph"||d.type!=="paragraph"||Ht(r,d)))throw new Error(fd(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:d}}function ri(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,y)=>({value:f.text[y],marks:f.marks||{}}))),i=(h,f)=>h.value===f.value&&ot(h.marks)===ot(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,g=s.slice(a,s.length-l),d=S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(t,a,-1));c>0&&t.delete(a,c);let u=a;const p=[];for(let h=0;h<g.length;){const f=g[h].marks;let m=g[h].value;for(h++;h<g.length&&ot(g[h].marks)===ot(f);)m+=g[h].value,h++;p.push({type:"text",text:m,marks:f}),u=rt(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:d,previewTextNodes:p,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(t,a,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(t,u,0)),text:g.map(h=>h.value).join(""),oldText:r.slice(a,r.length-l).map(h=>h.value).join("")})}function We(o,e,t,n){const i=[];Se(e,{verifiedUnchanged:!1,styleEffects:void 0}),ir.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=Qi({...e,id:t??"replacement-batch"},{doc:He(o),loadedBlockIds:null});if(a.error){const g=a.failure;throw new me(g?.code??"invalid_arguments",a.error,g?.phase??"validation",g?.retryable,g?.mutationOutcome,g?.details)}let l=n,c=!0;for(const g of a.actions){const d=g,u=We(o,d,t,l);if(c=c&&!!Be(d)?.verifiedUnchanged,i.push(...u),!l){const p=He(o);l={document:p,htmlParsingContext:Z.createParsingContext(p),refreshDocumentIncrementally:!0}}}return Se(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 g=Un(e),d=n?.document??fe(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===Qt)p=zt(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(($t(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(d,I)??void 0)}}let y;if(u.includes("<")&&u.includes(">")?y=Z.fromAgentHtml(u,{previousBlock:f,existingDocument:d,parsingContext:n?.htmlParsingContext,listItemBaseIndent:p instanceof S.XmlElement&&p.nodeName==="list"?Number(J(o,a)?.getAttribute("indentLevel")??0):void 0}):y=Z.fromAgentHtml(`<p>${u}</p>`,{previousBlock:f,existingDocument:d,parsingContext:n?.htmlParsingContext,listItemBaseIndent:p instanceof S.XmlElement&&p.nodeName==="list"?Number(J(o,a)?.getAttribute("indentLevel")??0):void 0}),y.children.length!==1)throw new Error(`insert_block should produce exactly one block. Got ${y.children.length} blocks from content: ${u}`);const b=y.children[0];if(!g)throw new Error("insert_block must have stableId set by preprocessor");if(b.id=g,p instanceof S.XmlElement&&p.nodeName==="list"){const k=J(o,a),I=zs([b],Number(k?.getAttribute("indentLevel")??0),g,!0);p.insert(h,I.map(v=>ye(v))),i.push({kind:"insert",paragraphId:p.getAttribute("id"),text:I.map(v=>v.children.map(x=>x.text).join("")).join(`
|
|
24
|
+
`)});break}if(b.type==="paragraph"){const k=b,I=new S.XmlElement("paragraph");I.setAttribute("id",g),ni(I,k);const v=new S.XmlText;let x=0;k.children.forEach(T=>{if(T.type==="text"){const E=T;x=rt(v,x,E.text,E.marks||{})}}),Vn(I,k,x),I.insert(0,[v]),p.insert(h,[I]);const A=k.children.filter(T=>T.type==="text").map(T=>T.text).join("");i.push({kind:"insert",paragraphId:g,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(v,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(v,A.length,0)),text:A})}else if(b.type==="list"){const k=ti(b);p.insert(h,[k]);const I=[];for(const v of k.toArray()){if(!(v instanceof S.XmlElement))continue;const x=oe(v);if(!x)continue;const A=ee(x).map(T=>typeof T.insert=="string"?T.insert:"").join("");A.length&&I.push({yText:x,plainText:A})}I.forEach(({yText:v,plainText:x})=>{i.push({kind:"insert",paragraphId:g,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(v,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(v,x.length,0)),text:x})})}else if(b.type==="table"){const k=ti({...b,id:g});p.insert(h,[k]),i.push({kind:"insert",paragraphId:g,text:"Table inserted"})}else if(b.type==="code"){const k=b,I=new S.XmlElement("code");I.setAttribute("id",g),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:g,text:"Code block inserted"})}else if(b.type==="math"){const k=b,I=new S.XmlElement("math");I.setAttribute("id",g),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:g,text:"Math block inserted"})}else if(b.type==="page-break"){const k=new S.XmlElement("page-break");k.setAttribute("id",g),p.insert(h,[k]),i.push({kind:"insert",paragraphId:g,text:"Page break inserted"})}else if(b.type==="toc"){const k=ye({...b,id:g});p.insert(h,[k]),i.push({kind:"insert",paragraphId:g,text:"Table of contents inserted"})}else if(b.type==="image"){const k=b,I=new S.XmlElement("image");I.setAttribute("id",g),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:g,text:"Image inserted"})}else throw new Error(`insert_block expected a paragraph, list, table, code, math, image, table-of-contents, or page-break block but got ${b.type}`);n&&(n.lastInsertedBlock={id:g,yParent:p,index:h,block:b},p===o.getXmlFragment("content")?n.document.children.splice(h,0,b):(n.document=fe(o),n.htmlParsingContext=Z.createParsingContext(n.document)));break}case"replace":case"replace_all":{const{id:a}=e.arguments;let{find:l,replace:c}=e.arguments;const g=n?.document??fe(o),d=J(o,a);if(!d)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);let u=Tg(d,a);const p=Yo(Ys(g,a)??X(g,a),l);if(p&&(u=u.filter(y=>p.has(y.blockId))),p&&u.length===0)throw new me("target_stale","HTML matcher identities no longer resolve to editable text within this target. Read the target again.","target_resolution");if(u.length===0)break;if(l.length===0){if(u.length!==1||u[0].blockText.length!==0)throw new Error(`An empty find may only fill one truly empty text block; block '${a}' is not an unambiguous empty target.`);const y=u[0];mr(y.yText,0,0,l,c,y.blockId,i,yt(y.yBlock.getAttribute("_emptyTextMarks")));break}const h=y=>u.map(b=>({...b,matches:ta(b.blockText,y)})).filter(b=>b.matches.length>0);if(et(l)){const y=u.map(b=>Ks(b,g,l,c,e.name==="replace_all")).filter(b=>b!==null);if(y.length>0){if(e.name==="replace"&&y.length>1)throw new Error(`Found ${y.length} exact AgentHtml matches for "${l}" in block '${a}'. Include more surrounding AgentHtml so it matches exactly one location, or use replace_all.`);if(e.name==="replace")ri(y[0],i);else for(const b of y)ri(b,i);break}}let f=h(l);if(f.length===0){const y=Zs(l);if(y!==l&&y.trim()!==""){const b=h(y);b.length>0&&(l=y,c=Zs(c),f=b)}}if(f.length===0){const y=u.map(x=>Ks(x,g,l,c,e.name==="replace_all")).filter(x=>x!==null);if(y.length>0){if(e.name==="replace")ri(y[0],i);else for(const x of y)ri(x,i);break}const b=u.map(x=>x.blockText).join(`
|
|
25
|
+
`),k=b.length>100?b.slice(0,100)+"...":b,I=Bg(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 me("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 me("text_not_found",`No match found for "${l}" in block '${a}'. The block's stored plain text begins ${JSON.stringify(k)}.${v} Make sure the text you're searching for exists exactly as written (case-sensitive, including punctuation and spaces).${I}`,"matching")}const m=f.reduce((y,b)=>y+b.matches.length,0);if((e.name==="replace_all"||m===1)&&f.every(y=>y.matches.every(b=>Gs(y.yText,b.offset,b.length,l,c)))){Se(e,{verifiedUnchanged:!0});break}if(e.name==="replace"){const y=f.reduce((I,v)=>I+v.matches.length,0);if(y>1)throw new Error(`Found ${y} matches for "${l}" in block '${a}'. Include more surrounding context in "find" so it matches exactly one location, or use replace_all to change every occurrence.`);const b=f[0],k=b.matches[0];mr(b.yText,k.offset,k.length,l,c,b.blockId,i)}else for(const y of f){let b=-1;y.matches=y.matches.filter(k=>k.offset<b?!1:(b=k.offset+k.length,!0));for(let k=y.matches.length-1;k>=0;k--){const I=y.matches[k];mr(y.yText,I.offset,I.length,l,c,y.blockId,i)}}break}case"replace_block":{const{id:a,content:l,count:c}=e.arguments;if(c!==void 0&&(!Number.isFinite(c)||Math.floor(c)<1))throw new Error("replace_block count must be a positive integer.");const g=sd(c,1),d=n?.document??fe(o),u=X(d,a);if(!u){const I=d.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,y=$t(f);if((h.nodeName==="header-footer"||y&&g!==1)&&Lt(),g>1){const I=Math.max(0,f.length-(m+1)),v=Math.min(g-1,I);for(let x=0;x<v;x++){const A=f.get(m+1);if(!(A instanceof S.XmlElement))break;const T=A.getAttribute("id");js(A,T??void 0,i),f.delete(m+1,1)}}const b=Wt(d,a),k=b>0?d.children[b-1]:void 0;{const I=(Array.isArray(l)?l:[l]).join(""),v=Z.fromAgentHtml(I,{previousBlock:k,replacementBlock:u,existingDocument:d,listItemBaseIndent:h.nodeName==="list-item"?Number(h.getAttribute("indentLevel")??0):void 0});if(y&&(v.children.length!==1||v.children[0].type!=="paragraph")&&Lt(),h.nodeName==="list-item"&&f instanceof S.XmlElement&&f.nodeName==="list"){const x=zs(v.children,Number(h.getAttribute("indentLevel")??0),a,!0);if(g===1&&x.length===1&&u.type==="list"){const A=u.children.find(T=>T.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&&Us(A,u.variant)===Us(x[0],u.variant)){Se(e,{verifiedUnchanged:!0});break}}f.delete(m,1),f.insert(m,x.map(A=>ye(A))),i.push({kind:"replace",paragraphId:f.getAttribute("id"),oldText:"List item",text:x.map(A=>A.children.map(T=>T.text).join("")).join(`
|
|
26
|
+
`)});break}if(u.type==="paragraph"){const x=T=>T.children.filter(E=>!E.marks?.footnoteRef),A=Z.extractUniformTextFontFamily(x(u));if(A){for(const T of v.children)if(T.type==="paragraph"&&Z.extractUniformTextFontFamily(x(T)))for(const E of x(T))E.marks={...E.marks,fontFamily:A}}}if(v.children.length>0)if(v.children.length===1){const x=v.children[0];if(g===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 L=new Map(u.children.map(M=>[M.id,M])),O=u.children.length===x.children.length&&x.children.every((M,N)=>M.children.map(_=>_.text).join("")===u.children[N].children.map(_=>_.text).join(""));x.children=x.children.map((M,N)=>({...M,children:zn((L.get(M.id)??(O?u.children[N]:void 0))?.children??[],M.children)}))}const w=L=>Array.isArray(L)?L.map(w):L&&typeof L=="object"?Object.fromEntries(Object.entries(L).filter(([O,M])=>O!=="id"&&M!==void 0&&!(O==="marks"&&Object.keys(M).length===0)).sort(([O],[M])=>O.localeCompare(M)).map(([O,M])=>[O,w(M)])):L,C=L=>JSON.stringify(w(L)),$=L=>Z.toInternalHtml({type:"doc",children:[w(L)]});if(C(u)===C(x)||$(u)===$(x)){Se(e,{verifiedUnchanged:!0});break}}if(!(h instanceof S.XmlElement))break;if(x.type==="list"){f.delete(m,1);const w=ti({...x,id:a});f.insert(m,[w]);const C=u.type==="list"?"List":"Paragraph";i.push({kind:"replace",paragraphId:a,text:"List replaced",oldText:C});break}if(x.type==="table"){const w=x;f.delete(m,1);const C=ti({...w,id:a});f.insert(m,[C]);const $=u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";i.push({kind:"replace",paragraphId:a,text:"Table replaced",oldText:$});break}if(x.type==="code"){const w=x;f.delete(m,1);const C=new S.XmlElement("code");C.setAttribute("id",a),w.language&&C.setAttribute("language",w.language),w.renderDiagram!==void 0&&C.setAttribute("renderDiagram",String(w.renderDiagram)),w.showDiagramSource!==void 0&&C.setAttribute("showDiagramSource",String(w.showDiagramSource));const $=new S.XmlText;C.insert(0,[$]),ne($,0,w.content||""),f.insert(m,[C]);const L=u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";i.push({kind:"replace",paragraphId:a,text:"Code block replaced",oldText:L});break}if(x.type==="math"){const w=x;f.delete(m,1);const C=new S.XmlElement("math");C.setAttribute("id",a),w.displayMode&&C.setAttribute("displayMode",w.displayMode),w.align&&C.setAttribute("align",w.align);const $=new S.XmlText;C.insert(0,[$]),ne($,0,w.content||""),f.insert(m,[C]);const L=u.type==="math"?"Math block":u.type==="code"?"Code block":u.type==="table"?"Table":u.type==="list"?"List":"Paragraph";i.push({kind:"replace",paragraphId:a,text:"Math block replaced",oldText:L});break}if(x.type==="page-break"){f.delete(m,1);const w=new S.XmlElement("page-break");w.setAttribute("id",a),f.insert(m,[w]);const C=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:C});break}if(x.type==="toc"){f.delete(m,1);const w=ye({...x,id:a});f.insert(m,[w]),i.push({kind:"replace",paragraphId:a,text:"Table of contents replaced",oldText:"Block"});break}if(x.type==="image"){const w=x;f.delete(m,1);const C=new S.XmlElement("image");C.setAttribute("id",a),C.setAttribute("src",w.src),w.sourceUrl&&C.setAttribute("sourceUrl",w.sourceUrl),C.setAttribute("width",String(w.width)),C.setAttribute("height",String(w.height)),w.alt&&C.setAttribute("alt",w.alt),w.align&&C.setAttribute("align",w.align),f.insert(m,[C]);const $=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:$});break}if((u.type==="math"||u.type==="code")&&x.type==="paragraph"){f.delete(m,1);const w=new S.XmlElement("paragraph");w.setAttribute("id",a),ni(w,x);const C=new S.XmlText;let $=0;for(const L of x.children)L.type==="text"&&($=rt(C,$,L.text,L.marks||{}));Vn(w,x,$),w.insert(0,[C]),f.insert(m,[w]),i.push({kind:"replace",paragraphId:a,text:x.children.filter(L=>L.type==="text").map(L=>L.text).join(""),oldText:u.type==="code"?"Code block":"Math block"});break}if((u.type==="list"||u.type==="table")&&x.type==="paragraph"){f.delete(m,1);const w=new S.XmlElement("paragraph");w.setAttribute("id",a),ni(w,x);const C=new S.XmlText;let $=0;for(const L of x.children)L.type==="text"&&($=rt(C,$,L.text,L.marks||{}));Vn(w,x,$),w.insert(0,[C]),f.insert(m,[w]),i.push({kind:"replace",paragraphId:a,text:x.children.filter(L=>L.type==="text").map(L=>L.text).join(""),oldText:u.type==="table"?"Table":"List"});break}const A=ue(h);if(!A)break;const T=u.type==="paragraph"?u:null,E=A.length,F=v.children[0],B=T!==null&&hr(T,F);let P=0;if(!B){if(E>0&&A.delete(0,E),F.children.length>0){for(const w of F.children)if(w.type==="text"){const C=w;P=rt(A,P,C.text,C.marks||{})}}ni(h,F)}if(!B){const w=u.type==="paragraph"?u.children.filter(C=>C.type==="text").map(C=>C.text).join(""):"";i.push({kind:"replace",paragraphId:a,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,P,0)),text:F.children.filter(C=>C.type==="text").map(C=>C.text).join(""),oldText:w})}}else{if(!(h instanceof S.XmlElement))break;const x=ue(h);if(!x)break;const A=u.type==="paragraph"?u:null,T=x.length,E=u.type==="paragraph"?u.children.filter(C=>C.type==="text").map(C=>C.text).join(""):"",F=v.children[0],B=A!==null&&hr(A,F);let P=0;if(!B){if(T>0&&x.delete(0,T),F.children.length>0){for(const C of F.children)if(C.type==="text"){const $=C;P=rt(x,P,$.text,$.marks||{})}}F.heading&&h.setAttribute("heading",String(F.heading)),F.align&&h.setAttribute("align",F.align)}B||i.push({kind:"replace",paragraphId:a,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(x,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(x,P,0)),text:F.children.filter(C=>C.type==="text").map(C=>C.text).join(""),oldText:E});let w=m+1;for(let C=1;C<v.children.length;C++){const $=v.children[C],L=new S.XmlElement("paragraph"),O=$.id||Y();L.setAttribute("id",O),$.heading&&L.setAttribute("heading",String($.heading)),$.align&&L.setAttribute("align",$.align);const M=new S.XmlText;let N=0;$.children.forEach(R=>{if(R.type==="text"){const D=R;N=rt(M,N,D.text,D.marks||{})}}),Vn(L,$,N),L.insert(0,[M]),f.insert(w,[L]),w++;const _=$.children.filter(R=>R.type==="text").map(R=>R.text).join("");i.push({kind:"insert",paragraphId:O,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(M,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(M,_.length,0)),text:_})}}}break}case"style_blocks":{const{selectors:a,attrs:l}=e.arguments,{targets:c,inlineTargets:g,unmatchedSelectors:d,invalidSelectorErrors:u}=Jg(o,a),p=Kg(l),h=Vg(p);if(c.length===0&&g.length===0)throw new Error(`style_blocks matched no blocks. Unmatched selectors: ${d.length>0?d.join(", "):"all"}. ${u.length>0?`Invalid selectors: ${u.join("; ")}.`:""}`);const f=[],m=new Map,y=(W,Q,re)=>{const V=mt(W);let ce=m.get(V);ce||(ce={name:W,applied:new Set,skipped:new Map},m.set(V,ce)),re?ce.skipped.set(`${Q}\0${re}`,{blockId:Q,reason:re}):ce.applied.add(Q)},b=i.length,k=new Set,I=new Set,v=new Set(c),x=new Set,A=[],T=[],E=[],F=[],B=He(o),P=new Set([...c,...g.map(W=>W.yBlock)].map(we)),w=W=>"id"in W&&P.has(String(W.id))||"children"in W&&W.children.some(Q=>w(Q)),C=W=>[...W.children,...W.notes??[],...W.chrome??[]],$=new Set(C(B).filter(w).map(W=>W.id)),L=W=>qt({order:W.children.map(Q=>Q.id),noteOrder:(W.notes??[]).map(Q=>Q.id),chromeOrder:(W.chrome??[]).map(Q=>Q.id),targets:C(W).filter(Q=>$.has(Q.id))}),O=L(B),M=new Set,N=new Set,_=Zn(p,"width");if(_&&!(c.some(W=>W.nodeName==="image")&&nn(_.value)===void 0)){const W=new Map;for(const re of c){if(re.nodeName!=="table-cell")continue;let V=re.parent;for(;V instanceof S.XmlElement&&V.nodeName!=="table";)V=V.parent;if(!(V instanceof S.XmlElement))continue;const ce=X(B,we(V));if(!ce||ce.type!=="table")continue;const ae=nn(_.value),de=Nt("width",_.value),he=ce.tableWidth??ur(B,V),Ie=ae??(typeof de=="number"&&Number.isFinite(de)?de/he*100:NaN);W.has(V)||W.set(V,[]),W.get(V).push({cellId:we(re),percent:Ie}),M.add(re)}const Q=[...W].map(([re,V])=>({table:re,requests:V,widths:ng(X(B,we(re)),V)}));for(const re of Q){const V=String(re.table.getAttribute("columnWidths")??""),ce=JSON.stringify(re.widths),ae=X(B,we(re.table)),de=Bt(ae);for(const he of re.requests){const Ie=de.byId.get(he.cellId),io=fl=>fl.slice(Ie.col,Ie.col+Ie.colSpan).reduce((pl,ml)=>pl+ml,0);Math.abs(io(ae.columnWidths)-io(re.widths))>.001&&N.add(he.cellId)}V!==ce&&(re.table.setAttribute("columnWidths",ce),Pe(i,re.table,null,"columnWidths"),k.add(we(re.table))),x.add(_.canonicalName),I.add("columnWidths")}}for(const W of c){const Q=we(W);let re=!1;const V=id({doc:B,yBlock:W,rawAttrs:p,anchors:i});M.has(W)&&_&&(V.handledRawNames.add(_.canonicalName),V.appliedAttrs.push("cell width -> table columns"));for(const ae of V.handledRawNames){const de=p.find(Ie=>Ie.canonicalName===ae),he=V.issuesByRawName.get(ae)??[];y(de?.rawName??ae,Q,he.length?he.join("; "):void 0),x.add(ae)}for(const ae of V.appliedAttrs)I.add(ae),k.add(Q);A.push(...V.exactMappings),T.push(...V.approximateMappings),E.push(...V.ignoredAttrs),F.push(...V.unsupportedImageSpacing),f.push(...V.errors);const ce=Ds(h,W,!1);T.push(..._s(ce));for(const{rawName:ae,entry:de,value:he}of ce)if(!V.handledRawNames.has(mt(ae)))try{if(de.attr==="variant"&&typeof he=="string"&&he.trim().toLowerCase()==="none"&&["liststyletype","list-style-type"].includes(ae.trim().toLowerCase())){if(W.nodeName!=="list")throw new Error('style_blocks "listStyleType: none" only applies to list blocks.');re=!0;continue}if(de.kind==="textMark"){const Ie=Es(ae,de.attr,he);Og({toolName:"style_blocks",yBlock:W,attribute:de.attr,operation:Ie===null?"remove":"set",value:Ie,config:de,anchors:i,independentlySelectedTargets:v}),k.add(Q),I.add(`${ae} -> ${de.attr}`),y(ae,Q);continue}Dg({toolName:"style_blocks",yBlock:W,attribute:de.attr,operation:he===null?"remove":"set",value:he,config:{nodeNames:de.nodeNames,valueType:de.valueType,integer:de.integer,min:de.min,max:de.max,enumValues:de.enumValues},anchors:i,independentlySelectedTargets:v}),k.add(Q),I.add(`${ae} -> ${de.attr}`),y(ae,Q)}catch(Ie){y(ae,Q,Ie instanceof Error?Ie.message:String(Ie)),f.push(`${Q}.${de.attr}: ${Ie instanceof Error?Ie.message:String(Ie)}`)}re&&(ld(W,i)?(k.add(Q),I.add("listStyleType -> plain paragraphs"),y("listStyleType",Q)):f.push(`${Q}.variant: could not convert the list to plain paragraphs.`))}for(const{yBlock:W,ranges:Q}of g){const re=we(W),V=Ds(h,W,!0);T.push(..._s(V));for(const{rawName:ce,entry:ae,value:de}of V){if(ae.kind!=="textMark"){const he="Block attributes cannot apply to an inline range; select its block instead.";y(ce,re,he),f.push(`${re}.${ae.attr}: ${he}`);continue}try{const he=Es(ce,ae.attr,de);Rg({toolName:"style_blocks",yBlock:W,ranges:Q,attribute:ae.attr,operation:he===null?"remove":"set",value:he,config:ae,anchors:i}),k.add(re),I.add(`${ce} -> ${ae.attr}`),y(ce,re)}catch(he){y(ce,re,he instanceof Error?he.message:String(he)),f.push(`${re}.${ae.attr}: ${he instanceof Error?he.message:String(he)}`)}}}for(const W of h.unsupportedAttrs??[]){const Q=m.get(mt(W)),re=new Set([...Q?.skipped.values()??[]].map(V=>V.blockId));for(const V of P)!Q?.applied.has(V)&&!re.has(V)&&y(W,V,"Unsupported attribute for this target.")}const R=He(o),D=W=>{const Q=new Map,re=V=>{"id"in V&&V.id&&Q.set(V.id,V),"children"in V&&V.children.forEach(ce=>re(ce))};return C(W).forEach(re),Q},U=D(B),j=D(R),H=W=>qt(U.get(W)??null)!==qt(j.get(W)??null),K=[...new Set([...P,...i.slice(b).map(W=>W.paragraphId).filter(W=>!!W)])].filter(H),se=[...P].filter(W=>H(W)||N.has(W)),xe=[...m.values()].map(W=>({name:W.name,appliedBlockIds:[...W.applied],skipped:[...W.skipped.values()]})),Ue=xe.every(W=>W.skipped.length===0)&&I.size>0&&f.length===0&&d.length===0&&u.length===0&&E.length===0&&F.length===0&&(h.unsupportedAttrs??[]).every(W=>x.has(mt(W))),Oe={outcome:Ue?se.length?"complete":"unchanged":"partial",targetBlockIds:[...P],changedBlockIds:se,affectedBlockIds:K,attributes:xe};if(Se(e,{styleEffects:Oe}),Ue&&O===L(R)&&Se(e,{verifiedUnchanged:!0}),i.length===b&&!Be(e)?.verifiedUnchanged){if(F.length||E.length)throw new me("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."}`)}ir.set(e,rd({styleEffects:Oe,matchedTargetCount:c.length+g.reduce((W,Q)=>W+Q.ranges.length,0),inlineRangeCount:g.reduce((W,Q)=>W+Q.ranges.length,0),unsupportedAttrs:(h.unsupportedAttrs??[]).filter(W=>!x.has(mt(W))),unmatchedSelectors:d,invalidSelectorErrors:u,skippedTargetErrors:f,exactCompatibilityMappings:A,approximateCompatibilityMappings:T,ignoredCompatibilityAttrs:E,unsupportedImageSpacing:F}));break}case"set_block_attribute":{const{id:a,attribute:l,operation:c,value:g}=e.arguments,d=Cs("set_block_attribute",a),u=()=>{const b=He(o);return d.map(k=>X(b,k))},p=JSON.stringify(u());if(typeof l!="string"||l.trim().length===0)throw new Error("set_block_attribute requires a non-empty attribute name.");const h=l.trim();if(h==="id")throw new Error("set_block_attribute cannot modify the reserved 'id' attribute.");const f=Lg(c),m=[],y=(b,k)=>{if(d.length<=1)throw new Error(k);return m.push(`${b}: ${k}`),!0};for(const b of d){const k=G(o,b);if(!k){y(b,`Target block '${b}' not found in the document. Please only reference IDs you see inside <document_content>.`);continue}const{yBlock:I}=k,v=ue(I);if(h==="fontFamily"){const A=Qn(I);if(A){y(b,A);continue}}if(Fg.has(h)){if(!v||I.nodeName!=="paragraph"&&I.nodeName!=="list-item"){y(b,`set_block_attribute "${h}" only supports paragraph or list-item text blocks.`);continue}let A;if(f==="remove")A=!1;else if(f==="toggle")A=!ws(I,v,h);else if(g===void 0)A=!0;else if(typeof g=="boolean")A=g;else throw new Error(`set_block_attribute "${h}" expects a boolean value when operation is "set".`);if(v.length>0)ie(v,0,v.length,{[h]:A?!0:null}),it(i,b,v);else{Eg(I,h,A);const T=`Text mark "${h}" ${A?"enabled":"removed"}.`;i.push({kind:"replace",paragraphId:b,text:T,oldText:T})}continue}if(h in vs){if(!v||I.nodeName!=="paragraph"&&I.nodeName!=="list-item"){y(b,`set_block_attribute "${h}" only supports paragraph or list-item text blocks.`);continue}if(f==="toggle")throw new Error(`set_block_attribute "${h}" does not support toggle. Use operation "set" with a numeric value or "remove".`);const A=vs[h],T=f==="remove"?null:$g(h,g,A);if(v.length>0)ie(v,0,v.length,{[h]:T===null?null:T}),it(i,b,v);else{Ts(I,h,T);const E=`Text mark "${h}" ${T===null?"removed":"set"}.`;i.push({kind:"replace",paragraphId:b,text:E,oldText:E})}continue}if(h==="indentLevel"&&I.nodeName==="paragraph"){Fs(I,f,g),v&&it(i,b,v);continue}const x=As[h];if(!x){const A=Object.keys(As).sort().join(", ");throw new Error(`set_block_attribute "${h}" is not supported. Supported block attributes: ${A}.`)}if(!x.nodeNames.includes(I.nodeName)){y(b,`set_block_attribute "${h}" is not valid for ${I.nodeName} blocks.`);continue}if(f==="remove")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=Ps(te(I,h));I.setAttribute(h,String(!A))}else{if(g===void 0)throw new Error(`set_block_attribute "${h}" requires "value" when operation is "set".`);const A=Bs(h,g,x);I.nodeName==="paragraph"&&(h==="leftIndent"||h==="firstLineIndent")?Ms(I,h,Number(A)):I.setAttribute(h,A)}if(v)it(i,b,v);else{const A=`Updated ${h} on ${I.nodeName} block.`;i.push({kind:"replace",paragraphId:b,text:A,oldText:A})}}if(i.length===0&&m.length>0)throw new Error(`set_block_attribute could not apply to any target. Skipped targets: ${m.join("; ")}`);m.length===0&&p===JSON.stringify(u())&&Se(e,{verifiedUnchanged:!0});break}case"clear_formatting":{const{id:a}=e.arguments,l=Cs("clear_formatting",a),c=()=>{const d=He(o);return l.map(u=>X(d,u))},g=JSON.stringify(c());for(const d of l){const u=G(o,d);if(!u)throw new Error(`Target block '${d}' 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")||d;p.push({id:m,yBlock:f})}}if(p.length===0){const h=`Cleared formatting on list block ${d}.`;i.push({kind:"replace",paragraphId:d,text:h,oldText:h});continue}}else p.push({id:d,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 Lo)q(h.yBlock,m);if(od(h.yBlock),f.length>0){let m=0;for(const y of ee(f)){const b=typeof y.insert=="string"?y.insert.length:1,k={...No};typeof y.attributes?.footnoteRef=="string"&&y.attributes.footnoteRef.length>0&&delete k.superscript,ie(f,m,b,k),m+=b}it(i,h.id,f)}else{const m="Formatting cleared.";i.push({kind:"replace",paragraphId:h.id,text:m,oldText:m})}}}g===JSON.stringify(c())&&Se(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:g,index:d}=c;$t(g)&&Lt();const u=zt(o),p=g===u;for(let h=0;h<l;h++){const f=d;if(f>=g.length)break;const m=g.get(f);if(!(m instanceof S.XmlElement))break;const y=m.getAttribute("id"),b=m.nodeName;if(p&&g.length===1){if(b==="paragraph"){const k=ue(m);if(k&&k.length>0){const I=ee(k);let v="";for(const x of I)x.insert&&typeof x.insert=="string"&&(v+=x.insert);i.push({kind:"delete",paragraphId:y,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(k,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(k,v.length,0)),text:v}),k.delete(0,k.length)}}else{i.push({kind:"delete",paragraphId:y,text:b==="list"?"List removed":"Block removed"});const k=new S.XmlElement("paragraph");k.setAttribute("id",y);const I=new S.XmlText;k.insert(0,[I]),g.delete(f,1),g.insert(f,[k])}break}if(b==="list")i.push({kind:"delete",paragraphId:y,text:"List removed"});else{const k=ue(m);if(k){const I=ee(k);let v="";for(const x of I)x.insert&&typeof x.insert=="string"&&(v+=x.insert);i.push({kind:"delete",paragraphId:y,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(k,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(k,v.length,0)),text:v})}else i.push({kind:"delete",paragraphId:y,text:"Block removed"})}g.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 g=ue(c);if(!g)break;const d=g.length,u=ct(d>0?oi(g,d-1,1):yt(c.getAttribute("_emptyTextMarks"))),p=Z.fromAgentHtml(l);if(p.children.length>0){const h=[];for(const y of p.children)y.type==="paragraph"&&y.children.forEach(b=>{b.type==="text"&&h.push(b)});let f=d,m="";for(const y of h)if(y.text){const b=rt(g,f,y.text,{...u||{},...y.marks||{}});m+=y.text,f=b}m&&i.push({kind:"insert",paragraphId:a,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(g,d,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(g,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 g=n?.document??fe(o),d=X(g,a);if(!d)throw new Error(`Target block '${a}' not found in the document. Please only reference IDs you see inside <document_content>.`);if(d.type!=="paragraph")throw new Error(`break_paragraph only works on paragraphs. Block '${a}' is type '${d.type}'.`);const u=wd(d,c);if(u.length===0){const j=d.children.filter(K=>K.type==="text").map(K=>K.text).join(""),H=j.length>100?j.slice(0,100)+"...":j;throw new Error(`No match found for "${c}" in block '${a}'. The block contains: "${H}".`)}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:y}=h;if($t(m)&&Lt(),!(f instanceof S.XmlElement))throw new Error(`Target block '${a}' is not a valid Y.XmlElement.`);const b=ue(f);if(!b)throw new Error(`break_paragraph only works on text paragraphs. Block '${a}' has no text content.`);const{beforeOps:k,afterOps:I,formatAtSplit:v,originalText:x,beforeText:A,afterText:T}=Id(b,p);b.delete(0,b.length);let E=0;for(const j of k)ne(b,E,j.insert,j.attributes??{}),E+=j.insert.length;const F=Y(),B=new S.XmlElement("paragraph");B.setAttribute("id",F);const P=f.getAttribute("heading");P&&B.setAttribute("heading",P);const w=te(f,"align");w&&B.setAttribute("align",w);const C=te(f,"lineSpacing");C!=null&&B.setAttribute("lineSpacing",C);const $=te(f,"pagination");$!=null&&B.setAttribute("pagination",$);const L=f.getAttribute("styleId");L!=null&&B.setAttribute("styleId",L);const O=te(f,"direction");O!=null&&B.setAttribute("direction",O);const M=te(f,"borders");M!=null&&B.setAttribute("borders",M);const N=te(f,"shading");N!=null&&B.setAttribute("shading",N);const _=te(f,"tabStops");_!=null&&B.setAttribute("tabStops",_);const R=f.getAttribute("oxmlPPr");R!=null&&B.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")),H=ct({...j,...v??{}});H&&Object.keys(H).length>0&&B.setAttribute("_emptyTextMarks",JSON.stringify(H))}B.insert(0,[D]),m.insert(y+1,[B]),A!==x&&i.push({kind:"replace",paragraphId:a,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(b,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(b,E,0)),text:A,oldText:x}),i.push({kind:"insert",paragraphId:F,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(D,0,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(D,U,0)),text:T||"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 g=G(o,a),d=G(o,l);if(!g)throw new Error(`Target block '${a}' not found in the document.`);if(!d)throw new Error(`Target block '${l}' not found in the document.`);if(($t(g.yParent)||$t(d.yParent))&&Lt(),g.yBlock.nodeName!=="paragraph"||d.yBlock.nodeName!=="paragraph")throw new Error("join_paragraphs only works on two paragraph blocks.");if(g.yParent!==d.yParent||d.index!==g.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(g.yBlock),p=ue(d.yBlock);if(!u||!p)throw new Error("join_paragraphs only works on text paragraph blocks.");const h=u.toString(),f=p.toString(),m=c!==void 0?String(c):/\S/.test(h)&&/\S/.test(f)?" ":"",y=h.match(/\s+$/)?.[0].length??0,b=f.match(/^\s+/)?.[0].length??0,k=m.length>0,I=k?h.slice(0,h.length-y):h,v=k?f.slice(b):f;k&&y>0&&u.delete(u.length-y,y);const x=ee(u),A=ee(p),T=x.length>0?x[x.length-1].attributes??{}:{},E=A.length>0?A[0].attributes??{}:{};let F=u.length;m.length>0&&(ne(u,F,m,Object.keys(T).length>0?T:E),F+=m.length);let B=k?b:0;for(const w of A){if(typeof w.insert!="string"||w.insert.length===0)continue;const C=w.insert.slice(B);B=Math.max(0,B-w.insert.length),C.length!==0&&(ne(u,F,C,w.attributes??{}),F+=C.length)}const P=`${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:P||"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"}),d.yParent.delete(d.index,1);break}case"insert_table_row":{const a=fe(o),l=Z.createParsingContext(a),{tableId:c,referenceIndex:g,referenceRowId:d,position:u,content:p}=e.arguments,h=X(a,c);if(h?.type!=="table")throw new Error(`Table ${c} not found`);let f=g;if(d!==void 0){if(f=h.children.findIndex(k=>k.id===d),f<0)throw new Error(`Row ${d} not found in table ${c}. Read the table and use a current row ID.`);if(g!==void 0&&g!==f)throw new Error(`Row ${d} is at index ${f}, not ${g}. Use referenceRowId alone or reread the table.`)}if(f===void 0||!Number.isInteger(f)||f<0||f>=h.children.length)throw new Error("Invalid reference row index. Supply a current referenceRowId or a valid 0-based referenceIndex.");const m=h.children[f],y=p?.map(k=>{if(k==="")return;const I=Z.fromAgentHtml(k,{existingDocument:a,parsingContext:l});return I.children.length>0?I.children:void 0}),b=xg(o,c,u,f,y);if(!b.success)throw new Error(b.error||"Failed to insert table row");i.push({kind:"insert",paragraphId:c,text:`Row inserted ${u} row ${m.id} (reference index ${f}; new row index ${f+(u==="after"?1:0)})`});break}case"remove_table_row":{const{tableId:a,rowIndex:l}=e.arguments,c=Sg(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=fe(o),l=Z.createParsingContext(a),{tableId:c,referenceIndex:g,position:d,content:u}=e.arguments,p=u?.map(f=>{if(f==="")return;const m=Z.fromAgentHtml(f,{existingDocument:a,parsingContext:l});return m.children.length>0?m.children:void 0}),h=Ig(o,c,d,g,p);if(!h.success)throw new Error(h.error||"Failed to insert table column");i.push({kind:"insert",paragraphId:c,text:`Column inserted ${d} column ${g}`});break}case"remove_table_column":{const{tableId:a,columnIndex:l}=e.arguments,c=yg(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 Id(o,e){const t=[],n=[];let i={},r="",s="",a="",l=0;const c=ee(o);for(const g of c){if(!g.insert||typeof g.insert!="string")continue;const d=g.insert,u=g.attributes||{},p=l+d.length;if(r+=d,p<=e)t.push({insert:d,attributes:u}),s+=d,p===e&&(i=u);else if(l>=e)n.push({insert:d,attributes:u}),a+=d;else{const h=e-l,f=d.slice(0,h),m=d.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 oi(o,e,t){const n=e+t;let i=0,r=null;for(const s of ee(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 g of uo){const d=l[g];d!=null&&d!==!1&&(c[g]=d)}if(r===null)r=c;else for(const g of Object.keys(r))r[g]!==c[g]&&delete r[g]}if(i=a,i>=n)break}return r??{}}function pr(o){const e=new Set;if(!o.includes("<")||!o.includes(">"))return e;try{const t=Z.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 Vs(o,e){const t=Kt(o);return e.code||e.latex?t:Ro(t)}function Gs(o,e,t,n,i){if(i.includes("<")&&i.includes(">")||pr(n).size>0)return!1;const r=oi(o,e,t),s=Vs(i,r);return o.toString().slice(e,e+t)===s}function mr(o,e,t,n,i,r,s,a={}){if(!Gs(o,e,t,n,i))if(i.includes("<")&&i.includes(">")){const l={...a,...oi(o,e,t)};for(const p of pr(n))delete l[p];const c=i.trim(),g=/^<\s*(?:p|h[1-6])(?:\s|>|\/)/i.test(c)?c:`<p>${i}</p>`,d=Z.fromAgentHtml(g,{preserveExplicitMarkResets:!0}),u=d.children.length>0?d.children[0]:null;if(u&&u.type==="paragraph"&&u.children.length>0){o.delete(e,t);const p=[];for(const b of u.children)if(b.type==="text"){const k=b,I={...l,...k.marks||{}};p.push({text:k.text,marks:I})}const h=o.doc;let f=e;const m=[];for(const b of p){const k=m[m.length-1],I=JSON.stringify(b.marks||{}),v=k?JSON.stringify(k.marks||{}):null;k&&I===v?k.text+=b.text:m.push({text:b.text,marks:b.marks||{}})}const y=m.map(b=>b.text).join("");h.transact(()=>{ne(o,e,y);let b=e;for(const k of m)k.marks&&Object.keys(k.marks).length>0&&ie(o,b,k.text.length,k.marks),b+=k.text.length;f=e+y.length},"performReplacement"),Hs(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,...oi(o,e,t)},c=Vs(i,l);for(const g of pr(n))delete l[g];o.delete(e,t),c.length>0&&ne(o,e,c,l),Hs(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 si=/\\+u[0-9a-fA-F]{4}/;function Qs(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 br(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 Zs(o){return o.replace(/^(?:#{1,6}|>|[-*+]|\d+[.)])[ \t]+/,"")}function vd(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ea(o,e){const t=e.split(/(\s+)/),n=[];for(const l of t)/^\s+$/.test(l)?n.push("\\s+"):l.length>0&&n.push(vd(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 xd(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 g=c+t.length-s;g>=n&&g<=i&&r.push({offset:s,length:g})}s=o.indexOf(e,s+1)}return r}function ta(o,e){const t=Mn(e);if(t.length>1)for(const n of t){const i=Gt(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=Ad(o,n);if(i.length)return i}return[]}function Ad(o,e){if(!e)return[];if(/^\s*$/.test(e))return yr(o,e);if(si.test(o)||si.test(e))return na(o,e);const t=og();return t!==null?t:na(o,e)}function na(o,e){const t=Gt(o,e);if(t.length)return t.map(({start:g,end:d})=>({offset:g,length:d-g}));const n=tt(o),i=tt(e),r=yr(n,i);if(r.length>0)return r;const s=ea(n,i);if(s.length>0)return s;let a,l;if(si.test(o)||si.test(e)){a=Qs(o),l=Qs(e).text;const g=yr(a.text,l);if(g.length>0)return br(g,a);const d=ea(a.text,l);if(d.length>0)return br(d,a)}const c=8;if(i.length>=c*2){const g=ia(n,i,c);if(g!==null)return[g]}if(a&&l&&l.length>=c*2){const g=ia(a.text,l,c);if(g!==null)return br([g],a)}return[]}function wd(o,e){let t="";for(const n of o.children)n.type==="text"&&(t+=n.text);return ta(t,e)}function yr(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 ia(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,g=xd(o,r,s,l,c);if(g.length===1)return g[0]}return null}function Td(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||Ln(o,s);let a;const l={document:r?{...n,children:[...n.children]}:s,get htmlParsingContext(){return a??(a=Z.createParsingContext(n))},set htmlParsingContext(h){a=h},refreshDocumentIncrementally:!r},c=[],g=[],d=new Set,u=[],p=(h,f,m,y)=>{const b=Be(h);g.push({actionIndex:f,actionName:h.name,error:m,failure:y,sourceEditIndex:b?.sourceEditIndex,sourceEditType:b?.sourceEditType})};for(let h=0;h<e.length;h++){const f=e[h];try{const m=()=>We(o,f,`${t}_${h}`,!i.skipContextForFirstAction||r||h>0?l:void 0),y=i.measure?i.measure(m):m();i.skipContextForFirstAction&&!r&&h===0&&e.length>1&&(l.document=He(o)),c.push(y);const b=Be(f);if(y.length&&b?.splitReplacementGroup&&d.add(b.splitReplacementGroup),!y.length&&i.rejectUnchangedAction&&!b?.verifiedUnchanged)if(zc(f)&&b?.splitReplacementGroup)u.push({action:f,index:h,group:b.splitReplacementGroup});else{p(f,h,rr(f)??`${JSON.stringify(f.arguments)} - no change made`);break}}catch(m){if(i.throwOnError)throw m;if(p(f,h,String(m),Jt(m)),!i.continueAfterError)break}}for(const{action:h,index:f,group:m}of u)d.has(m)||p(h,f,"Split replacement made no verified change");return{anchorsByAction:c,failures:g,alreadySatisfied:g.length===0&&e.every(h=>Be(h)?.verifiedUnchanged)}}const kr=()=>{},Cd={count:kr,gauge:kr,distribution:kr},ra=new WeakSet;function Sr(o,e){try{Cd.count("frontend.editor.yjs_observer_failure",1,{event:e})}catch{}console.error(`Yjs ${e} observer failed`,o)}function oa(o,e=Sr){if(ra.has(o))return;ra.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 sa="suggestion-id-repair";function Pd(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 Bd(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=Pd(e);for(const[c,g]of e.changed)c instanceof S.XmlText?l&&i.add(c):c instanceof S.XmlFragment&&(g.has("structuralSuggestionId")||g.has("suggestionId"))&&r(c);Ml(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,g=!1;for(;c.parent;){c=c.parent;const h=c;if(h instanceof S.XmlElement&&["structuralSuggestionId","suggestionId","proposalId"].some(f=>s(h.getAttribute(f)))){g=!0;break}}if(g||!n.has(c))continue;let d=0,u,p;for(const h of ee(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,d+=f;continue}const y=JSON.stringify(Object.entries(m).filter(([b])=>b==="insertion"||b==="deletion"||b==="layeredInsertion"||b.startsWith("suggestion")).sort(([b],[k])=>b.localeCompare(k)));if(p&&u===y)p.length+=f;else{const b=S.createRelativePositionFromTypeIndex(l,d).item;if(!b){d+=f;continue}p={text:l,start:d,length:f,id:`recovered-inline-${b.client.toString(36)}-${b.clock.toString(36)}`},u=y,a.push(p)}d+=f}}return a.length&&o.transact(()=>{for(const l of a)ie(l.text,l.start,l.length,t==="strip"?{insertion:null,deletion:null,layeredInsertion:null,formatChange:null}:{suggestionId:l.id})},sa),a.length}const Fd=["borders","align","styleId","direction","_emptyTextMarks"],Md=["id","heading","oxmlAttrs",...$l],Ed=["pagination"],$d=[...El("paragraph"),...Ed].filter(o=>!Fd.includes(o)&&!Md.includes(o));function aa(o,e){for(const t of $d){const n=te(o,t);n!=null&&e.setAttribute(t,n)}}const Ir=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"]),Ld=["insertion","deletion","formatChange","suggestionId","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","docxMove"];function la(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||Ir.has(i)||i==="link"&&e.excludeLink||i==="comment"&&e.excludeComment||i!=="footnoteRef"&&(i==="superscript"&&t||n.push([i,r]));return n}function vr(o){const{explicitMarks:e,inheritedMarks:t,emptyParagraphMarks:n,exitingLink:i=!1,exitingComment:r=!1,noteBodyFontSize:s,suggestionMarks:a}=o,l={},c=[],g=p=>{c.includes(p)||c.push(p)},d=p=>l[p]!==void 0,u=p=>c.includes(p);if(e){for(const[p,h]of Object.entries(e))h===!1?g(p):h!=null&&(l[p]=h);l.footnoteRef&&(delete l.footnoteRef,t?.footnoteRef&&delete l.superscript)}for(const[p,h]of la(t,{excludeLink:i,excludeComment:r}))!d(p)&&!u(p)&&(l[p]=h);t?.footnoteRef&&!l.footnoteRef&&(g("footnoteRef"),l.superscript||g("superscript"));for(const[p,h]of la(n,{excludeLink:i,excludeComment:r}))!d(p)&&!u(p)&&(l[p]=h);if(s!=null&&l.fontSize===void 0&&!u("fontSize")&&(l.fontSize=s),i&&!l.link&&g("link"),r&&!l.comment&&g("comment"),a)Object.assign(l,a);else if(t){const p=t;for(const h of Ld)p[h]!==void 0&&p[h]!==null&&g(h)}return{marksToApply:l,marksToRemove:c}}function ca(o,e,t,n){if(ne(o,e,t),Object.keys(n.marksToApply).length>0&&ie(o,e,t.length,n.marksToApply),n.marksToRemove.length>0){const i={};for(const r of n.marksToRemove)i[r]=null;ie(o,e,t.length,i)}}function ai(o,e,t){const n=po(e,t,gt(o.getDocument().children));o.transact(()=>{const i=o.getYChromeFragment();ga(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 xr(o){return co(o.getDocument().chrome??[])}function ga(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 Nd(o,e,t,n){const i=gt(o.getDocument().children),r=po(t,n,i).map(s=>({...s,sectionIndex:e}));o.transact(()=>{const s=o.getYChromeFragment();ga(s,a=>a.getAttribute("sectionIndex")===String(e));for(const a of r)s.push([o.blockToYjsElement(a)])})}function Od(o,e){return Rl(o.getDocument().chrome??[],e)}function da(o,e,t){const n=Nl(o.getDocument().chrome??[],e,t);if(n)return n;const i=Ol(e,t,void 0,gt(o.getDocument().children));return o.transact(()=>{o.getYChromeFragment().push([o.blockToYjsElement(i)])}),i}function Rd(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){ua(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)}}),ua(o)}function ua(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&&Dl(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")??""}`,g=t.get(c);if(g===void 0){t.set(c,l);return}const d=i[g];!s(d.getAttribute("id"))&&s(a.getAttribute("id"))?(n.push(g),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 Dd(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")}):ai(o,t,n))}function _d(o,e,t="bottom-right"){const{headers:n={},footers:i={}}=xr(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=mo(t),c=l.side==="headers"?s:a;c.default||(c.default=[l.paragraph])}ai(o,Object.keys(s).length>0?s:void 0,Object.keys(a).length>0?a:void 0)}function jd(o){const e=o.ydoc.getMap("metadata");if(e.get(Ge.showPageNumbers)!==!0)return;const t=e.get(Ge.pageNumberPosition)??"bottom-right",{headers:n={},footers:i={}}=xr(o),r=mo(t),s=r.side==="headers"?n:i;if(o.transact(()=>{e.set(Ge.showPageNumbers,!1)}),!s.default){const a={...s,default:[r.paragraph]};ai(o,r.side==="headers"?a:n,r.side==="footers"?a:i)}}function Xd(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 Ud(o,e,t,n,i){const r=o.getYChromeFragment(),s=()=>{for(const g of r.toArray())if(g instanceof S.XmlElement&&g.nodeName==="header-footer"&&g.getAttribute("side")===e&&g.getAttribute("slot")===t)return g;return null};if(i){const g=s();return g?(o.transact(()=>{const d=r.toArray().indexOf(g);d>=0&&r.delete(d,1)}),!0):!1}const a=[];if(typeof n.left=="string"&&a.push([0,n.left]),typeof n.center=="string"&&a.push([1,n.center]),typeof n.right=="string"&&a.push([2,n.right]),a.length===0)return!1;da(o,e,t);const l=s();if(!l)return!1;const c=gt(o.getDocument().children);return o.transact(()=>{for(const[g,d]of a){const u=(o.getDocument().chrome??[]).find(f=>f.side===e&&f.slot===t)?.children[g],p=Ll[g],h={type:"paragraph",id:u?.id??Y(),children:Xd(d,c),...u?.align??p?{align:u?.align??p}:{}};l.get(g)&&l.delete(g,1),l.insert(g,[o.blockToYjsElement(h)])}}),!0}function st(o){return o.ydoc?o.ydoc.getMap("comments"):null}function zd(o){const e=st(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 ha(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 Hd(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 d=ha(a);i(a,typeof d=="string"&&t.has(d)?d: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,g=0;for(const d of ee(a)){if(typeof d.insert!="string")continue;const u=d.insert.length,p=g+(d.attributes?.deletion?0:u),h=d.attributes?.suggestionId??s,f=!d.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:g,projectedEnd:p,...f?{structural:!0}:{}})}c+=u,g=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 Ar(o,e,t,n){return{id:le(),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 fa(o,e,t,n){const i=st(o);if(!i||!J(o.ydoc,e))return null;const r=Ar(o,t,{...n,anchorBlockId:e});return o.transact(()=>{i.set(r.id,r)}),r.id}function Wd(o,e,t,n,i){const r=J(o.ydoc,e),s=r?oe(r):null;if(!s||n<=t||t>=s.length)return!1;const a=Math.min(n,s.length),l=ee(s);let c=0,g=!1;for(const d of l){if(typeof d.insert!="string")continue;const u=c,p=c+d.insert.length;c=p;const h=Math.max(u,t),f=Math.min(p,a);if(f<=h)continue;const m=d.attributes?.comment,y=m?m.split(","):[];y.includes(i)||y.push(i),ie(s,h,f-h,{comment:y.join(",")}),g=!0}return g}function Yd(o,e,t,n,i,r){return wr(o,[{blockId:e,start:t,end:n}],i,r)}function wr(o,e,t,n){const i=st(o);if(!i||e.length===0)return null;const r=Ar(o,t,n),s=r.id;let a=!1;return o.transact(()=>{for(const l of e)a=Wd(o,l.blockId,l.start,l.end,s)||a;a&&i.set(s,r)}),a?s:null}function qd(o,e,t,n){const i=st(o);if(!i||!i.has(e))return null;const r=Ar(o,t,n,e);return o.transact(()=>{i.set(r.id,r)}),r.id}function Jd(o,e,t){const n=st(o),i=n?.get(e);return!n||!i?!1:(o.transact(()=>{n.set(e,{...i,resolved:t})}),!0)}function Kd(o,e,t){const n=st(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 Vd(o,e){const t=st(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(g=>!e(g)))&&n.push(c)}),n.length===0)return 0;const i=new Map,r=(l,c)=>{for(const g of l.toArray()){if(g instanceof S.XmlElement){const d=ha(g);r(g,d&&e(d)?d:c);continue}if(g instanceof S.XmlText)for(const d of ee(g)){const u=d.attributes?.comment,p=d.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 g=J(o.ydoc,l.anchorBlockId)??null;for(;g;){if(g instanceof S.XmlElement){const d=g.getAttribute("structuralSuggestionId");if(typeof d=="string"&&e(d))return[d];for(const u of["structuralSuggestionRecord","structuralSuggestionRecords"]){const p=g.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{}}}g=g.parent}}return[]};let a=0;return o.transact(()=>{for(const l of n){const c=s(l);if(c.length===0)continue;const g={...l,suggestionId:c[0]};c.length>1?g.relatedSuggestionIds=c:delete g.relatedSuggestionIds,t.set(l.id,g),a+=1}}),a}function Gd(o,e){const t=st(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 ee(a)){if(typeof c.insert!="string")continue;const g=c.insert.length,d=c.attributes?.comment;if(d){const u=d.split(",").filter(p=>!n.has(p));u.length!==d.split(",").length&&ie(a,l,g,{comment:u.length>0?u.join(","):null})}l+=g}}};try{r(o.getYContentFragment()),r(o.ydoc.getXmlFragment("notes")),r(o.ydoc.getXmlFragment("chrome"))}catch{}}),!0}function pa(o,e){const t=g=>g.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=g=>{g&&n.push({type:"text",text:t(g),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 g=l[1]==="/",d=l[2].toLowerCase();if(d==="i"||d==="em")g?delete i.italic:i.italic=!0;else if(d==="b"||d==="strong")g?delete i.bold:i.bold=!0;else if(d==="u")g?delete i.underline:i.underline=!0;else if(d==="a")if(g)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(g=>({...g,text:g.text.replace(/<[^>]{1,80}>/g,"")})).filter(g=>g.text.length>0);return c.length>0?c:[{type:"text",text:t(o),marks:{...e}}]}function Dt(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 ee(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 Qd(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 Tr(o){const e=new Map;for(const[t,n]of kt(o))e.set(t,n.getAttribute("noteKind")==="endnote"?"endnote":"footnote");return e}function Zd(o){const e=[];for(const a of Dt(o))e.includes(a.footnoteId)||e.push(a.footnoteId);const t=Tr(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:Pi(r[c],c),kind:c})}return s}function St(o){const e=Dt(o);if(e.length===0)return!1;const t=Tr(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,Pi(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 eu(o){ma(o);const e=Dt(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 ma(o){let e;try{e=o.getYContentFragment()}catch{return!1}const t=[],n=g=>{for(const d of g.toArray()){if(d instanceof S.XmlElement){n(d);continue}if(!(d instanceof S.XmlText))continue;let u=0;for(const p of ee(d)){if(typeof p.insert!="string")continue;const h=p.attributes??{};typeof h.footnotePendingBody=="string"&&t.push({yText:d,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(Dt(o).map(g=>g.footnoteId)),s=o.getDocument(),a=new Map;for(const g of[...s.notes??[],...s.children.filter(d=>d.type==="footnote")])a.set(g.id,g.children.flatMap(d=>d.type==="paragraph"?d.children:[]).map(d=>d.type==="text"?d.text:"").join(""));const l=new Set;for(const g of t)if(!i.has(g.footnoteId)){for(const[d,u]of a)if(u===g.body&&!r.has(d)&&!l.has(d)&&i.has(d)){g.footnoteId=d,l.add(d);break}}const c=gt(o.getDocument().children);return o.transact(()=>{for(const g of t){if(ie(g.yText,g.start,g.length,{footnotePendingBody:null,footnotePendingKind:null,footnoteRef:g.footnoteId,superscript:!0}),i.has(g.footnoteId)){if(a.get(g.footnoteId)!==g.body){const f=i.get(g.footnoteId);let m=null;for(const b of f.toArray())if(b instanceof S.XmlElement&&b.nodeName==="paragraph"){m=b;break}const y=m?oe(m):null;if(y){const b=g.fontFamily??c;y.length>0&&y.delete(0,y.length);let k=0;for(const I of pa(g.body,{fontSize:dt,...b?{fontFamily:b}:{}}))ne(y,k,I.text,I.marks),k+=I.text.length}}continue}const d=g.fontFamily??c,u={fontSize:dt,...d?{fontFamily:d}:{}},p={type:"footnote",id:g.footnoteId,...g.kind==="endnote"?{noteKind:"endnote"}:{},children:[{type:"paragraph",id:Y(),children:pa(g.body,u)}]},h=o.blockToYjsElement(p);h.setAttribute("id",g.footnoteId),g.kind==="endnote"&&h.setAttribute("noteKind","endnote"),g.suggested&&g.suggestionId&&o.suggestions.setElementStructuralSuggestion(h,"insert",void 0,g.suggestionId,"Insert footnote"),o.getYNotesFragment().push([h]),i.set(g.footnoteId,h)}}),St(o),!0}function tu(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 nu(o,e,t,n,i="footnote"){if(!o.ydoc)return null;const r=Y(),s=o.suggestions.isSuggesting(),a=s?le():void 0,l=Tr(o),c=new Set(Dt(o).map(m=>m.footnoteId).filter(m=>(l.get(m)??"footnote")===i)).size,g=Pi(c+1,i);let d,u;{const m=X(o.getDocument(),e.block);if(m&&m.type==="paragraph"){u=m.direction;let y=0;for(const b of m.children){if(b.type!=="text")continue;const k=y+b.text.length;if(e.offset<=k&&b.marks?.fontFamily){d=b.marks.fontFamily;break}y=k}}}const p={footnoteRef:r,superscript:!0,...d?{fontFamily:d}:{},...s&&a?{insertion:!0,...o.suggestions.buildInlineMetadataMarks(a,"Insert footnote")}:{}};if(!o.insertTextNodes(e,[{type:"text",text:g,marks:p}],n))return null;const h=d??gt(o.getDocument().children),f={fontSize:dt,...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}]}]},y=o.blockToYjsElement(m);if(y.setAttribute("id",r),i==="endnote"&&y.setAttribute("noteKind","endnote"),s&&a&&o.suggestions.setElementStructuralSuggestion(y,"insert",void 0,a,"Insert footnote"),o.getYNotesFragment().push([y]),!t){const b=y.toArray()[0];b instanceof S.XmlElement&&b.setAttribute("_emptyTextMarks",JSON.stringify(f))}}),St(o),{footnoteId:r,...a?{suggestionId:a}:{}}}function iu(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=oe(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??gt(o.getDocument().children),l={fontSize:dt,...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 ru(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 y of m.toArray())if(y instanceof S.XmlElement){if(y.getAttribute("id")===e){r=y;return}s(y)}}};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=oe(r);if(!a)return{success:!1,replacements:0,error:`Note block '${e}' does not contain editable text.`};const l=ee(a).map(m=>typeof m.insert=="string"?m.insert:"").join(""),c=[];let g=0;for(;g<=l.length-t.length;){const m=l.indexOf(t,g);if(m<0)break;c.push(m),g=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 d=i?c:c.slice(0,1),u=o.suggestions.isSuggesting()?le():null,p=u?o.suggestions.buildInlineMetadataMarks(u,"Replace footnote text"):null,h=m=>{let y=0;for(const b of ee(a)){if(typeof b.insert!="string")continue;const k=y+b.insert.length;if(m<k){const I={...b.attributes??{}};return delete I.insertion,delete I.deletion,delete I.suggestionId,delete I.suggestionLabel,delete I.suggestionCreatedAt,I}y=k}return{fontSize:dt}},f=new Map(d.map(m=>[m,h(m)]));return o.transact(()=>{for(const m of[...d].reverse()){const y=f.get(m)??{fontSize:dt};u&&p?(ie(a,m,t.length,{deletion:!0,...p}),n&&ne(a,m,n,{...y,insertion:!0,deletion:null,formatChange:null,...p})):(a.delete(m,t.length),n&&ne(a,m,n,y))}}),{success:!0,replacements:d.length,...u?{suggestionId:u}:{}}}function ou(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 su(o,e){const t=Dt(o).filter(i=>i.footnoteId===e),n=kt(o).get(e);if(t.length===0&&!n)return!1;if(o.suggestions.isSuggesting()){const i=le();return o.transact(()=>{for(const r of t)ie(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 ba(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 Cr(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 au(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 lu(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 cu(o,e,t,n){const i=J(o,e);if(!i)return null;if(t==="paragraph"||t==="list-item")return oe(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 oe(a);r++}}}return null}function ya(o,e,t,n){return cu(o,e,t,n)||(Tt(o)?lu(o,e,t,n):null)}function at(o,e,t){const n=X(t,o.block);if(!n||!n.id)return null;if(n.type==="paragraph"){const i=n,r=ya(e,n.id,"paragraph");if(!r)return null;const s=i.children.filter(c=>c.type==="text").reduce((c,g)=>c+g.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 g=0;for(let d=0;d<i.children.length;d++){if(i.children[d].id===o.block){r=d,g+o.offset;break}g+=Bn(i.children[d]),d<i.children.length-1&&(g+=1)}}if(r===-1){let g=o.offset;for(let d=0;d<i.children.length;d++){const u=Bn(i.children[d]),p=d<i.children.length-1?1:0;if(g<=u){r=d,s=g;break}g-=u+p,d===i.children.length-1&&(r=d,s=u)}}r===-1&&(r=0,s=0);const a=ya(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 gu(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 g=c;let d=0;for(let u=0;u<l.length;u++){if(l.get(u)?.get("content")===e)return{blockId:s,offset:d,yTextOffset:0};u<g.children.length&&(d+=Bn(g.children[u]),u<g.children.length-1&&(d+=1))}}}return null}function li(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=au(i);if(r)return{block:r.blockId,offset:r.offset+n};if(Tt(e)){const s=fe(e),a=gu(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 z(o,e,t){return{anchor:o.anchor?at(o.anchor,e,t):null,focus:o.focus?at(o.focus,e,t):null}}function Pr(o,e){return{anchor:o.anchor?li(o.anchor,e):null,focus:o.focus?li(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 du(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 Br{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(),uu(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=oe(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 g=oe(c);return g?(ne(g,n,i,a),[{kind:"insert",paragraphId:t,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(g,n,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(g,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,g=>{const d=J(g,t);if(!d)return console.warn(`Paragraph ${t} not found for text replacement`),[];const u=oe(d);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 g=s.get(c);if(!(g instanceof S.XmlElement))continue;const d=g.getAttribute("id");if(d&&r.has(d)){a=c+1;break}}const l=ka(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);fe(t),S.applyUpdate(t,r);const a=S.encodeStateAsUpdate(t);if(fe(t),!!du(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:g,index:d}=c;g.delete(d,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 g=i.get(c);if(g instanceof S.XmlElement){const d=g.getAttribute("id");d&&a.add(d)}}for(let c=i.length-1;c>=0;c--){const g=i.get(c);if(g instanceof S.XmlElement){const d=g.getAttribute("id");if(d&&r.has(d)){s=c+1;break}}}for(let c=0;c<i.length;c++){const g=i.get(c);if(g instanceof S.XmlElement){const d=g.getAttribute("id");if(d&&n.mustBeBefore.includes(d)){c<s&&(s=c);break}}}const l=`proposal-${e}`;return this.undoManager.trackedOrigins.add(l),this.ydoc.transact(()=>{const c=ka(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,Mr.get(this.documentId)===this&&Mr.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(g=>this.suggestionMeta.get(g)?.status==="pending");if(t.length===0)return;const{createGranularSuggestionsForParagraph:n}=await Promise.resolve().then(()=>Mu),{findBlockById:i}=await import("./index-D7V8zn4w.js").then(g=>g.a0),r=fe(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 g of t){const d=this.proposals.get(g);d&&S.applyUpdate(a,d)}const l=fe(a),c=i(l,e);if(c&&c.type==="paragraph")for(const g of t)this.deleteSuggestion(g)}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 g=i.toolCallAction.arguments.id;J(this.ydoc,g);const d=new S.Doc;this.seedForkFromBase(d);const u=S.encodeStateVector(d);In(d),d.transact(()=>{if(Tt(d)){const h=d.getArray("paragraphs");for(let f=0;f<h.length;f++)if(h.get(f).get("id")===g){h.delete(f,1);break}}else{const h=G(d,g);if(h){const{yParent:f,index:m}=h;f.delete(m,1)}}}),In(d);const p=S.encodeStateAsUpdate(d,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=fe(r),l=fe(s);if(a.children.length===l.children.length)for(let g=0;g<a.children.length;g++){const d=a.children[g],u=l.children[g];if(d.type!=="paragraph"||u.type!=="paragraph")continue;const p=d,h=u,f=c(p),m=c(h);if(f!==m&&p.id===h.id){p.id;const y=new S.Doc;this.seedForkFromBase(y);const b=S.encodeStateVector(y),{analyzeParagraphDiff:k}=await Promise.resolve().then(()=>fg),I=k(f,m).diffs;y.transact(()=>{let x=null;if(Tt(y)){const A=y.getArray("paragraphs");for(let T=0;T<A.length;T++){const E=A.get(T);if(E.get("id")===p.id){x=E.get("content");break}}}else{const A=J(y,p.id);A&&(x=oe(A))}if(x){const A=[];for(const F of h.children)if(F.type==="text")for(let B=0;B<F.text.length;B++)A.push({node:F,indexInNode:B,marks:F.marks||{}});let T=0,E=0;for(const[F,B]of I)if(F===0)T+=B.length,E+=B.length;else if(F===-1)x.delete(T,B.length);else if(F===1){for(let P=0;P<B.length;P++){const w=A[E+P];if(w){const C={...w.marks,proposalId:e};ne(x,T+P,B[P],C)}}T+=B.length,E+=B.length}}});const v=S.encodeStateAsUpdate(y,b);this.proposals.set(e,v),this.saveToLocalStorage(),this.notifyListeners();return}}function c(g){return g.children.filter(d=>d.type==="text").map(d=>d.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 ka(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 g=new S.XmlElement("list-item");Ct(g,c),g.setAttribute("id",c.id||Y()),c.checked!==void 0&&g.setAttribute("checked",String(c.checked)),typeof c.indentLevel=="number"&&c.indentLevel>0&&g.setAttribute("indentLevel",String(c.indentLevel)),c.direction!==void 0&&g.setAttribute("direction",c.direction);const d=new S.XmlText;let u=0;c.children.forEach(p=>{if(p.type==="text"){const h=p,f=Fr(h.marks,t);d.insert(u,h.text,f),u+=h.text.length}}),g.insert(0,[d]),l.push([g])}),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 g of l.children){const d=new S.XmlElement("table-row");d.setAttribute("id",g.id||Y());for(const u of g.children){const p=new S.XmlElement("table-cell");p.setAttribute("id",u.id||Y()),u.verticalAlign&&p.setAttribute("verticalAlign",u.verticalAlign),u.backgroundColor&&p.setAttribute("backgroundColor",u.backgroundColor);for(const h of u.children)if(h.type==="paragraph"){const f=h,m=new S.XmlElement("paragraph");m.setAttribute("id",f.id||Y()),f.heading&&m.setAttribute("heading",String(f.heading)),f.align&&m.setAttribute("align",f.align);const y=new S.XmlText;let b=0;for(const k of f.children)if(k.type==="text"){const I=k,v=Fr(I.marks,t);ne(y,b,I.text,v),b+=I.text.length}m.insert(0,[y]),p.push([m])}d.push([p])}c.push([d])}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 g=new S.XmlText;return c.insert(0,[g]),ne(g,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 g=new S.XmlText;return c.insert(0,[g]),ne(g,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 ye({...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,g=Fr(c.marks,t);ne(s,a,c.text,g),a+=c.text.length}}),i.insert(0,[s]),i}function Fr(o,e,t){return{...o||{},proposalId:e}}const Mr=new Map;function uu(o,e){Mr.set(o,e)}const hu=new Set(["Arial","Arial, sans-serif"]);function Er(o){if(typeof o!="string")return;const e=o.trim();if(!(!e||hu.has(e)))return e}function ci(o){const e={};for(const t of Sn)if(o[t]!==void 0)if(t==="fontFamily"){const n=Er(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 Sa=uo.filter(o=>!Sn.includes(o));function _t(o){const e=ci(o);for(const t of Sa)o[t]!==void 0&&(e[t]=o[t]);return e}function fu(o){const e=Ia(o);for(const t of Sa)o[t]!==void 0&&(e[t]=o[t]);return e}function $r(o,e){return JSON.stringify(_t(o||{}))===JSON.stringify(_t(e||{}))}function Ia(o){const e=ci(o);e.docxRunPropertyResets=o.docxRunPropertyResets??null;for(const t of Sn)t in e||(e[t]=null);return e}function Lr(o,e){const t=ci(o||{}),n=ci(e||{});return JSON.stringify(t)===JSON.stringify(n)}function va(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(Er(n)!==Er(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 xa{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 lt(o,e){return{...o,id:e}}function pu(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 Aa(o){return JSON.stringify(o.children.map(e=>[e.id,e.children.map(t=>[t.id,t.rowSpan??1,t.colSpan??1])]))}function wa(o){return JSON.stringify({...o,children:o.children.map(e=>({...e,children:e.children.map(t=>({...t,children:[]}))}))})}function mu(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 Nr(o,e,t){const n=t?.affectedBlockIds?new Set(Array.from(t.affectedBlockIds).filter($=>typeof $=="string"&&$.length>0)):null,i=e.getYDoc(),r=Array.from(e.getPendingSuggestions().keys()),s=r.length>0?e.materializeWithSuggestions(r):i,a=t?.precomputedLiveDocSchema??fe(i),l=t?.precomputedCurrentDocSchema??(s===i?a:fe(s)),c=t?.precomputedFinalDocSchema??fe(o),g=qe(a),d=qe(l),u=qe(c),p=n?pu(n,d,u):null,h=new Set;for(const $ of new Set([...g.keys(),...u.keys()])){const L=g.get($)?.block,O=u.get($)?.block;L?.type!=="table"&&O?.type!=="table"||(L?.type!=="table"||O?.type!=="table"||Aa(L)!==Aa(O)||wn(L,O))&&h.add($)}if(p)for(const[$,L]of new Map([...g,...u]))L.containerPath.some(O=>p.has(O))&&p.add($);const f=new Set(Array.from(t?.atomicReplaceBlockIds??[]).filter($=>typeof $=="string"&&$.length>0)),m=new Map;for(const $ of t?.replacementBlockMatches??[])typeof $?.currentBlockId!="string"||$.currentBlockId.length===0||typeof $?.finalBlockId!="string"||$.finalBlockId.length===0||m.set($.finalBlockId,$.currentBlockId);const y=$=>{const L=m.get($);return L&&g.has(L)?L:$},b=!!p&&p.size>0,k=e.getPendingSuggestions();if(b){const $=new Set;for(const L of p){const O=e.getSuggestionsForParagraph(L);for(const M of O)k.has(M)&&$.add(M)}for(const L of $)e.deleteSuggestion(L)}else for(const[$]of k)e.deleteSuggestion($);const I=[],v=new Set,x=new Set,A=d;for(const[$,L]of g){const O=L.block;if(O.type!=="list"||u.has($)||O.children.length===0||b&&!p.has($)||L.containerPath.some(H=>h.has(H)))continue;const M=A.get($)?.block,N=(t?.listUnwrapMemberIds?.get($)??(M?.type==="list"?M.children:O.children).map(H=>H.id)).map(H=>u.get(H)).filter(H=>!!H),_=N[0];if(!_||N.some((H,K)=>H.containerPath.join("/")!==L.containerPath.join("/")||K>0&&H.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(H=>!H.id||g.has(H.id)))continue;const j=`prop_${Y()}`;e.createSuggestion(j,H=>{const K=G(H,$);return K?(K.yParent.delete(K.index,1),K.yParent.insert(K.index,U.map(se=>ye(se))),[{kind:"replace",paragraphId:$,text:"Remove list markers"}]):[]},{authorType:"ai",blockSequencePreview:{blockId:$,blocks:U},description:"AI: remove list markers"}),I.push(j),v.add($),e.setSuggestionsForParagraph($,[j]);for(const H of U)x.add(H.id),e.setSuggestionsForParagraph(H.id,[j])}const T=[],E=b?Array.from(p).filter($=>u.has($)):Array.from(u.keys());for(const $ of E){const L=u.get($);if(!L||x.has($)||L.containerPath.some(R=>x.has(R)))continue;const O=L.block,M=m.get($);if(O.type==="container"||O.type==="table-cell"||L.containerPath.some(R=>h.has(R)))continue;const N=M?g.get(M)??g.get($):g.get($),_=M&&N?.block.id===M&&M!==$?M:null;if(N?.block.id&&v.add(N.block.id),O.type==="paragraph"){const R=_!==null?lt(O,_):O;if(!N)T.push({location:L});else if(N.block.type==="paragraph"){const D=N.block,U=_r(D),j=_r(R);if(U!==j||Fu(D,R)){if(f.has($)){const K=Or(e,R);K&&(I.push(K),R.id&&e.setSuggestionsForParagraph(R.id,[K]));continue}const H=Ta(e,D,R);I.push(...H)}}else{const D=Or(e,R);D&&(I.push(D),R.id&&e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="list"){const R=_!==null?lt(O,_):O;if(!N)T.push({location:L});else if(N.block.type==="list"){const D=N.block;if(bo(D,R)){if(!Au(D,R)){const U=bu(e,D,R);U.length>0&&D.id&&(I.push(...U),e.setSuggestionsForParagraph(D.id,U))}}else{const U=Dr(e,R);U&&D.id&&(I.push(U),e.setSuggestionsForParagraph(D.id,[U]))}}else{const D=Dr(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="table"){const R=_!==null?lt(O,_):O;if(!N)T.push({location:L});else if(N.block.type==="table"){const D=N.block,U=h.has(R.id);if(U||wa(D)!==wa(R)){const j=Ca(e,U?R:mu(D,R));j&&(I.push(j),e.setSuggestionsForParagraph(R.id,[j]))}}else{const D=Ca(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="code"){const R=_!==null?lt(O,_):O;if(!N)T.push({location:L});else if(N.block.type==="code"){const D=N.block;if(D.content!==R.content||D.language!==R.language){const U=Pa(e,R);U&&R.id&&(I.push(U),e.setSuggestionsForParagraph(R.id,[U]))}}else{const D=Pa(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="math"){const R=_!==null?lt(O,_):O;if(!N)T.push({location:L});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=Ba(e,R);U&&R.id&&(I.push(U),e.setSuggestionsForParagraph(R.id,[U]))}}else{const D=Ba(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="image"){const R=_!==null?lt(O,_):O;if(!N)T.push({location:L});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=Fa(e,R);U&&R.id&&(I.push(U),e.setSuggestionsForParagraph(R.id,[U]))}}else{const D=Fa(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="page-break"){const R=_!==null?lt(O,_):O;if(!N)T.push({location:L});else if(N.block.type!=="page-break"){const D=vu(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}else if(O.type==="toc"){const R=_!==null?lt(O,_):O;if(!N)T.push({location:L});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=xu(e,R);D&&R.id&&(I.push(D),e.setSuggestionsForParagraph(R.id,[D]))}}}T.sort(($,L)=>{const O=$.location.containerPath,M=L.location.containerPath,N=Math.min(O.length,M.length);for(let _=0;_<N;_++)if(O[_]!==M[_])return O[_].localeCompare(M[_]);return O.length!==M.length?O.length-M.length:$.location.indexInParent-L.location.indexInParent});const F=$=>{const L=$.containerPath.at(-1),O=L?u.get(L)?.block:null;return O&&"children"in O?O.children:c.children},B=$=>{const L=F($);for(let O=$.indexInParent-1;O>=0;O--){const M=L[O];if(M.id)return y(M.id)}return null},P=$=>{const L=F($),O=(()=>{for(let N=$.indexInParent-1;N>=0;N--)if(L[N]?.id)return y(L[N].id);return null})(),M=(()=>{for(let N=$.indexInParent-1;N>=0;N--){const _=L[N]?.id;if(!_)continue;const R=y(_);if(g.has(R))return R}return null})();return Array.from(new Set([M,O].filter(N=>typeof N=="string"&&N.length>0)))},w=[];for(const $ of T){const L=$.location,O=B(L),M=w[w.length-1];if(M&&M.afterId===O&&M.containerPath.join("/")===L.containerPath.join("/")&&M.blocks[M.blocks.length-1].location.indexInParent===L.indexInParent-1){M.blocks.push($);continue}w.push({afterId:O,containerPath:L.containerPath,blocks:[$]})}for(const $ of w){const L=$.afterId&&g.has($.afterId);if($.blocks.length===1&&L){const{location:O}=$.blocks[0],M=O.block,N=Cu(e,M,$.afterId,a);N&&(I.push(N),M.id&&e.setSuggestionsForParagraph(M.id,[N]))}else for(let O=0;O<$.blocks.length;O++){const{location:M}=$.blocks[O],N=M.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 _=P(M),R=e.createPositionAwareInsertion(N.id,N,_,F(M).slice(M.indexInParent+1).map(D=>D.id).filter(D=>!!D&&g.has(D)).slice(0,1),{authorType:"ai",description:`AI: insert_${N.type} (position-aware)`});R&&(I.push(R),e.setSuggestionsForParagraph(N.id,[R]))}}const C=b?Array.from(p).filter($=>g.has($)):Array.from(g.keys());for(const $ of C){const L=g.get($);if(!L||v.has($))continue;const O=L.block,M=O.type==="container"&&b&&!!p?.has($);if(!(O.type==="container"&&!M)&&O.type!=="table-cell"&&!L.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==="page-break"||O.type==="section-break"||O.type==="toc"||M)){const N=Tu(e,O);N&&(I.push(N),e.setSuggestionsForParagraph($,[N]))}}return I}function Ta(o,e,t){const n=[];if(!Ht(e,t)){const u=Or(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 y=0;y<m.text.length;y++)p.push({char:m.text[y],marks:m.marks||{},nodeIndex:f,charIndexInNode:y})}}),p},r=i(e),s=i(t),a=r.map(u=>u.char).join(""),l=s.map(u=>u.char).join(""),c=qn(a,l).diffs;let g=0,d=0;for(let u=0;u<c.length;u++){const[p,h]=c[u];if(p===0){const f=h.length;for(let m=0;m<f;m++){const y=r[g+m],b=s[d+m],k=y?.marks||{},I=b?.marks||{};if(!va(k,I)){const v=m;let x=m+1;for(;x<f;){const B=r[g+x]?.marks||{},P=s[d+x]?.marks||{};if(va(B,P)||!$r(P,I))break;x++}const A=h.substring(v,x),T=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,E=fu(I),F=o.createTextReplacement(T,t.id,g+v,x-v,A,E,A,{authorType:"ai",description:"AI: apply formatting"});F&&n.push(F),m=x-1}}g+=h.length,d+=h.length}else if(p===-1){const f=h.length,m=u+1<c.length?c[u+1]:null;if(m&&m[0]===1){const y=m[1];let b=!0;if(y.length>1){const k=d<s.length?s[d].marks:{};for(let I=1;I<y.length;I++){const v=d+I<s.length?s[d+I].marks:{};if(!Lr(k,v)){b=!1;break}}}if(b){const k=d<s.length?s[d].marks:{},{...I}=k,v=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,x=o.createTextReplacement(v,t.id,g,f,y,I,h,{authorType:"ai",description:"AI: replace text"});x&&n.push(x)}else{const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,I=o.createSuggestion(k,v=>{const x=J(v,t.id);let A=null;if(x)for(let F=0;F<x.length;F++){const B=x.get(F);if(B instanceof S.XmlText){A=B;break}}if(!A)return console.warn(`Paragraph ${t.id} not found for mixed formatting replacement`),[];A.delete(g,f);let T=g,E=0;for(;E<y.length;){const F=E,B=d+E,P=B<s.length?_t(s[B].marks):{};let w=E+1;for(;w<y.length;){const $=d+w,L=$<s.length?_t(s[$].marks):{};if(!$r(P,L))break;w++}const C=y.substring(F,w);ne(A,T,C,{...P,suggestionId:k}),T+=C.length,E=w}return[{kind:"replace",paragraphId:t.id,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,g,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,g+y.length,0)),text:y,oldText:h}]},{authorType:"ai",description:"AI: replace text"});I&&n.push(I)}u++,g+=f,d+=y.length}else{const y=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,b=o.createTextDeletion(y,t.id,g,f,h,{authorType:"ai",description:"AI: delete text"});b&&n.push(b),g+=f}}else if(p===1){const f=h,m=u>0?c[u-1]:null;if(m&&m[0]===-1)continue;const y=[];let b=0;for(;b<f.length;){const k=b,I=d+b,v=I<s.length?s[I].marks:{},x=_t(v);let A=b+1;for(;A<f.length;){const E=d+A,F=E<s.length?s[E].marks:{};if(!$r(x,F))break;A++}const T=f.substring(k,A);y.push({text:T,marks:x}),b=A}if(y.length===1&&Object.keys(y[0].marks).length===0){const k=`prop_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,I=o.createTextInsertion(k,t.id,g,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 F=x.get(E);if(F instanceof S.XmlText){A=F;break}}if(!A)return console.warn(`Paragraph ${t.id} not found for mixed formatting insertion`),[];let T=g;for(const E of y){const F={...E.marks,suggestionId:k};ne(A,T,E.text,F),T+=E.text.length}return[{kind:"insert",paragraphId:t.id,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,g,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(A,g+f.length,0)),text:f}]},{authorType:"ai",description:"AI: insert text"});I&&n.push(I)}d+=f.length}}return t.id&&n.length>0&&o.setSuggestionsForParagraph(t.id,n),n}function Or(o,e){const t={name:"replace_block",arguments:{id:e.id,content:Z.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 We(n,i);const s=oe(r.yBlock)?.toDelta().map(c=>typeof c.insert=="string"?c.insert:"").join("")??"";r.yParent.delete(r.index,1);const a=ye(e);r.yParent.insert(r.index,[a]);const l=oe(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:_r(e),oldText:s}]})}function bu(o,e,t){const n=[],i=e.children.map(b=>({item:b,text:vt(b),signature:Rr(b)})),r=t.children.map(b=>({item:b,text:vt(b),signature:Rr(b)})),{beforeKeys:s,afterKeys:a}=ba(e.children,t.children,Rr),l=Cr(s,a),c=[],g=(b,k,I)=>{const v=Math.min(b.length,k.length);for(let x=0;x<v;x++)c.push({kind:"replace",index:I+x,currentItem:b[x],finalItem:k[x]});for(let x=v;x<b.length;x++)c.push({kind:"delete",index:I+x,currentItem:b[x]});for(let x=k.length-1;x>=v;x--)c.push({kind:"insert",index:I+v,finalItem:k[x]})};let d=0,u=0;for(const b of l){let k=d;for(;k<i.length&&s[k]!==b;)k+=1;let I=u;for(;I<r.length&&a[I]!==b;)I+=1;g(i.slice(d,k),r.slice(u,I),d),d=k+1,u=I+1;const v=i[k],x=r[I];v&&x&&(v.signature!==x.signature||!Ma(v.item,x.item))&&c.push({kind:"replace",index:k,currentItem:v,finalItem:x})}g(i.slice(d),r.slice(u),d);const p=c.some(b=>b.kind!=="replace"?!0:b.currentItem.signature!==b.finalItem.signature||b.currentItem.text!==b.finalItem.text);if(c.length>0&&!p){const b=yu(o,t);return b?[b]:[]}for(const b of c){if(b.kind==="insert"){const I=ku(o,e.id,b.finalItem.item,b.index,e.variant);I&&n.push(I);continue}if(b.kind==="delete"){const I=Su(o,e.id,b.index,b.currentItem.text);I&&n.push(I);continue}const k=Iu(o,e.id,b.index,b.currentItem.item,b.finalItem.item,e.variant);k&&n.push(k)}const h=c.filter(b=>b.kind==="replace").length,f=c.some(b=>b.kind!=="replace"?b.kind==="insert"||b.kind==="delete":b.currentItem.signature!==b.finalItem.signature||b.currentItem.text!==b.finalItem.text),m=Math.max(i.length,r.length),y=m>0?n.length/m:0;if(h>0&&y>.7&&f){const b=Dr(o,t);return b?[b]:[]}return n}function yu(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=oe(s);if(!l)continue;let c=0;for(const g of a.children)g.type!=="text"||g.text.length===0||(ie(l,c,g.text.length,Ia(g.marks||{})),c+=g.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 ku(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 g=0;t.children.forEach(u=>{if(u.type==="text"){const p=u,h={...p.marks||{},suggestionId:r,toolType:"list_item_insert"};c.insert(g,p.text,h),g+=p.text.length}}),l.insert(0,[c]);const d=Math.min(n,a.length);return a.insert(d,[l]),[{kind:"insert",paragraphId:e,text:vt(t)}]},{authorType:"ai",description:"AI: insert list item"})}function Su(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 Iu(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 g=null;for(let p=0;p<c.length;p++){const h=c.get(p);if(h instanceof S.XmlText){g=h;break}}if(!g)return console.warn(`No content found in list item at index ${t}`),[];const d=g.length;d>0&&g.delete(0,d);let u=0;return i.children.forEach(p=>{if(p.type==="text"){const h=p,f={..._t(h.marks||{}),suggestionId:s,toolType:"list_item_replace"};g.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 Rr(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 Dr(o,e){const t={name:"replace_block",arguments:{id:e.id,content:wu(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,[ye(e)]),[{kind:"replace",paragraphId:e.id,text:"List replaced",oldText:i.yBlock.nodeName==="list"?"List":"Paragraph"}]):[]})}function Ca(o,e){const t={name:"replace_block",arguments:{id:e.id,content:Z.toInternalHtml({type:"doc",children:[e]})}};return o.createSuggestionFromToolCall(t,(n,i)=>We(n,i))}function Pa(o,e){const t={name:"replace_block",arguments:{id:e.id,content:Z.toAgentHtml({type:"doc",children:[e]})}};return o.createSuggestionFromToolCall(t,(n,i)=>We(n,i))}function Ba(o,e){const t={name:"replace_block",arguments:{id:e.id,content:Z.toAgentHtml({type:"doc",children:[e]})}};return o.createSuggestionFromToolCall(t,(n,i)=>We(n,i))}function Fa(o,e){const t={name:"replace_block",arguments:{id:e.id,content:Z.toInternalImageHtml(e)}};return o.createSuggestionFromToolCall(t,(n,i)=>We(n,i))}function vu(o,e){const t={name:"replace_block",arguments:{id:e.id,content:Z.toAgentHtml({type:"doc",children:[e]})}};return o.createSuggestionFromToolCall(t,(n,i)=>We(n,i))}function xu(o,e){const t={name:"replace_block",arguments:{id:e.id,content:Z.toAgentHtml({type:"doc",children:[e]})}};return o.createSuggestionFromToolCall(t,(n,i)=>We(n,i))}function Au(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||!Ma(n,i))return!1}return!0}function Ma(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||!Lr(n.marks||{},i.marks||{})))return!1}return!0}function wu(o){return Z.toInternalHtml({type:"doc",children:[o]})}function Tu(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,g=a.nodeName;let d;if(g==="list")d={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=ee(h);for(const m of f)m.insert&&typeof m.insert=="string"&&(u+=m.insert)}}d={kind:"delete",paragraphId:t,text:u||"Block removed"}}return l.delete(c,1),[d]},{authorType:"ai",toolCallAction:n,description:"AI: remove_block"})}function Cu(o,e,t,n){let i,r;t===null?n.children.length>0?(i=n.children[0].id,r="before"):(i=Qt,r="after"):(i=t,r="after");const s={name:"insert_block",arguments:{referenceId:i,position:r,content:[Pu(e)]}};return Se(s,{stableId:e.id||Y()}),o.createSuggestionFromToolCall(s,(a,l)=>We(a,l))}function Pu(o){return o.type==="paragraph"?Bu(o):o.type==="image"?Z.toInternalImageHtml(o):o.type==="list"||o.type==="table"||o.type==="code"||o.type==="math"||o.type==="page-break"||o.type==="toc"?Z.toInternalHtml({type:"doc",children:[o]}):""}function Fe(o){return o.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'")}function Bu(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 d=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)}"${d}>${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 d=[];l&&d.push(`font-family: ${Fe(l)}`),c&&d.push(`font-size: ${c}px`),s.marks?.color&&d.push(`color: ${Fe(s.marks.color)}`),s.marks?.doubleStrikethrough&&d.push("text-decoration: line-through double"),s.marks?.smallCaps&&d.push("font-variant: small-caps"),s.marks?.allCaps&&d.push("text-transform: uppercase"),typeof s.marks?.letterSpacing=="number"&&Number.isFinite(s.marks.letterSpacing)&&s.marks.letterSpacing!==0&&d.push(`letter-spacing: ${s.marks.letterSpacing}px`),a=`<span style="${d.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 g=_e(s.marks?.backgroundColor);if(g&&(a=`<mark color="${Fe(g)}">${a}</mark>`),s.marks?.link&&(a=`<a href="${Fe(s.marks.link)}">${a}</a>`),s.marks?.comment)for(const d of s.marks.comment.split(",").map(u=>u.trim()).filter(Boolean).reverse())a=`<comment-thread id="${Fe(d)}">${a}</comment-thread>`;r+=a}return r+=`</${t}>`,r}function _r(o){return o.children.filter(e=>e.type==="text").map(e=>e.type==="text"?e.text:"").join("")}function Fu(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||!Lr(n.marks||{},i.marks||{})))return!0}return!1}const Mu=Object.freeze(Object.defineProperty({__proto__:null,ToolCallHistory:xa,createFlattenedSuggestions:Nr,createGranularSuggestionsForParagraph:Ta},Symbol.toStringTag,{value:"Module"}));class jr{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?oe(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 g=oe(c);return g?(g.delete(n,i),[{kind:"delete",paragraphId:t,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(g,n,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(g,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 g=oe(c);return g?(ne(g,n,i,a),[{kind:"insert",paragraphId:t,from:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(g,n,0)),to:S.encodeRelativePosition(S.createRelativePositionFromTypeIndex(g,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,d=>{const u=J(d,t);if(!u)return[];const p=oe(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,[ye(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,[ye(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 g=c.getAttribute("id");if(g&&i.mustBeAfter.includes(g)){s=l+1;break}}const a=Eu(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 Eu(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 g=new S.XmlText;let d=0;l.children.forEach(u=>{if(u.type!=="text")return;const p=Xr(u.marks,t);g.insert(d,u.text,p),d+=u.text.length}),c.insert(0,[g]),a.push([c])}),a}if(o.type==="table")return ye(fo({...o,id:e},a=>({...a,marks:Xr(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 ye({...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=Xr(a.marks,t);ne(r,s,a.text,l),s+=a.text.length}),i.insert(0,[r]),i}function Xr(o,e,t){return{...o||{},suggestionId:e}}class yn{constructor(e){this.host=e,this.batchYBlockLocationsById=null,this.stampedIdRecorder=null}recordStampedSuggestionIds(e){const t=this.stampedIdRecorder,n={deletionIds:new Set,insertionIds:new Set,structuralInsertIds:new Set,structuralDeleteIds:new Set};this.stampedIdRecorder=n;try{return{result:e(),stamped:n}}finally{this.stampedIdRecorder=t}}recordStampedId(e,t){this.stampedIdRecorder&&t&&this.stampedIdRecorder[e].add(t)}buildInlinePreviewTextNodes(e){return e.newText?[{type:"text",text:e.newText,marks:{...e.marks}}]:[]}setSuggestingMode(e){this.host.suggestingMode=e}isSuggestingMode(){return this.host.suggestingMode}cloneSuggestionSnapshot(e){return JSON.parse(JSON.stringify(e))}getLiveSuggestionStore(){return this.host.ydoc.getMap("liveSuggestions")}setDefaultSuggestionAuthorName(e){const t=e?.trim();this.host.defaultHumanAuthorName=t||null}resolveSuggestionAuthorName(e,t){return t?.trim()||(e==="ai"?Ze:this.host.defaultHumanAuthorName??wo)}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,g=e.agentConversationId??t?.agentConversationId,d=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}:{},...g?{agentConversationId:g}:{},...d!==void 0?{agentRequestId:d}:{},...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.liveSuggestionTreeRecordCache.has(e))return this.host.liveSuggestionTreeRecordCache.get(e)??null;let t=null;const n=i=>{for(const r of i.toArray()){if(t||!(r instanceof S.XmlElement))continue;const s=r.getAttribute("structuralSuggestionRecord");if(typeof s=="string"&&s.length>0)try{const l=JSON.parse(s);if(l&&l.id===e&&l.type){t=l;return}}catch{}const a=r.getAttribute("structuralSuggestionRecords");if(typeof a=="string"&&a.length>0)try{const l=JSON.parse(a),c=Array.isArray(l)?l.find(g=>g&&g.id===e&&!!g.type):void 0;if(c){t=c;return}}catch{}n(r)}};try{n(this.host.getYContentFragment()),n(this.host.getYNotesFragment())}catch{}return this.host.liveSuggestionTreeRecordCache.set(e,t),t}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=fn(n.marks?.layeredInsertion);return i&&i.id===t?{id:t,source:i.source,authorType:i.authorType,createdAt:i.createdAt,label:i.label,commentThreadId:i.commentThreadId,agentName:i.authorName,agentModel:i.agentModel,agentConversationId:i.agentConversationId,agentRequestId:i.agentRequestId,agentTurn:i.agentTurn}:n.children?this.findInlineSuggestionMetadataInValue(n.children,t):null}getInlineSuggestionMetadataFromDocument(e){return this.host.inlineSuggestionMetadataCache.has(e)?this.host.inlineSuggestionMetadataCache.get(e)??null:(this.getDocumentSuggestionIdsCache(),this.host.inlineSuggestionMetadataCache.has(e)?this.host.inlineSuggestionMetadataCache.get(e)??null:(this.host.inlineSuggestionMetadataCache.set(e,null),null))}getLiveSuggestionTooltipDescription(e){const t=this.getLiveSuggestion(e);if(!t)return null;switch(t.type){case"inline-text":return null;case"inline-format":return this.host.getInlineFormatDescription(t);case"paragraph-split":return"Split Paragraph";case"paragraph-merge":return"Join Paragraphs";case"block-insert":{const n=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"?Ze:wo}getLiveSuggestionKind(e){const t=this.getLiveSuggestion(e);if(t)switch(t.type){case"inline-format":return"format";case"block-change":return"format";case"table-change":return t.tableRevision.suggestionKind;case"block-insert":case"paragraph-split":return"insert";case"block-delete":case"paragraph-merge":return"delete"}return this.getInlineSuggestionKindFromDocument(e)}getInlineSuggestionKindFromDocument(e){return this.host.inlineSuggestionKindCache.has(e)?this.host.inlineSuggestionKindCache.get(e)??null:(this.getDocumentSuggestionIdsCache(),this.host.inlineSuggestionKindCache.has(e)?this.host.inlineSuggestionKindCache.get(e)??null:(this.host.inlineSuggestionKindCache.set(e,null),null))}getResolvableSuggestionIdsForScope(e){switch(e.kind){case"source":return this.getResolvableLiveSuggestionIdsBySource(e.source);case"author":{const t=e.authorName.trim();return this.getLiveSuggestionIds().filter(n=>this.getLiveSuggestionAuthorName(n)===t).filter(n=>this.canResolveLiveSuggestion(n))}case"suggestion-kind":return this.getLiveSuggestionIds().filter(t=>this.getLiveSuggestionKind(t)===e.suggestionKind).filter(t=>this.canResolveLiveSuggestion(t))}}getInitialSuggestionIdsForDecisionScope(e){return e.kind==="ids"?this.normalizeLiveSuggestionIds(e.suggestionIds):this.getResolvableSuggestionIdsForScope(e)}getNextSuggestionIdsForDecisionScope(e,t){return e.kind==="ids"?t===0?this.normalizeLiveSuggestionIds(e.suggestionIds):[]:this.getResolvableSuggestionIdsForScope(e)}getResolvableSuggestionIdsFromDocument(){return this.getSuggestionIdsFromDocument()}getSuggestionIdsFromDocument(){return this.getDocumentSuggestionIdsCache().ids.slice()}documentContainsSuggestionId(e){return this.getDocumentSuggestionIdsCache().idSet.has(e)}getDocumentSuggestionIdsCache(){return this.host.documentSuggestionIdsCache&&this.host.documentSuggestionIdsCache.revision===this.host.derivedDocumentRevision?this.host.documentSuggestionIdsCache:(this.host.documentSuggestionIdsCache=this.createDocumentSuggestionIdsCache(this.host.getDocument()),this.host.documentSuggestionIdsCache)}createDocumentSuggestionIdsCache(e){const t=new Set;for(const i of this.blocksWithNotesAndChrome(e)){for(const r of this.getSuggestionIdsForBlock(i))t.add(r);this.indexInlineSuggestionFacts(i)}const n=Array.from(t);return{revision:this.host.derivedDocumentRevision,ids:n,idSet:new Set(n)}}indexInlineSuggestionFacts(e){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(const r of e)this.indexInlineSuggestionFacts(r);return}const t=e,n=t.marks?.suggestionId;if(typeof n=="string"&&n.length>0){this.host.inlineSuggestionMetadataCache.has(n)||this.host.inlineSuggestionMetadataCache.set(n,{id:n,source:t.marks?.suggestionSource,authorType:t.marks?.suggestionAuthorType,createdAt:t.marks?.suggestionCreatedAt,label:t.marks?.suggestionLabel,commentThreadId:t.marks?.suggestionCommentThreadId,agentName:t.marks?.suggestionAuthorName,agentModel:t.marks?.suggestionAgentModel,agentConversationId:t.marks?.suggestionAgentConversationId,agentRequestId:t.marks?.suggestionAgentRequestId,agentTurn:t.marks?.suggestionAgentTurn});const r=t.marks?.deletion?"delete":t.marks?.insertion?"insert":t.marks?.formatChange?"format":null;r&&!this.host.inlineSuggestionKindCache.has(n)&&this.host.inlineSuggestionKindCache.set(n,r)}const i=fn(t.marks?.layeredInsertion);if(i&&(this.host.inlineSuggestionMetadataCache.has(i.id)||this.host.inlineSuggestionMetadataCache.set(i.id,{id:i.id,source:i.source,authorType:i.authorType,createdAt:i.createdAt,label:i.label,commentThreadId:i.commentThreadId,agentName:i.authorName,agentModel:i.agentModel,agentConversationId:i.agentConversationId,agentRequestId:i.agentRequestId,agentTurn:i.agentTurn}),this.host.inlineSuggestionKindCache.set(i.id,"insert")),typeof t.structuralSuggestionId=="string"&&t.structuralSuggestionId.length>0){const r=t.structuralSuggestionKind==="insert"||t.structuralSuggestionKind==="split"?"insert":t.structuralSuggestionKind==="delete"||t.structuralSuggestionKind==="merge"?"delete":t.structuralSuggestionKind==="change"?"format":null;r&&this.host.inlineSuggestionKindCache.set(t.structuralSuggestionId,r)}if(typeof t.suggestionId=="string"&&t.suggestionId.length>0&&!this.host.inlineSuggestionKindCache.has(t.suggestionId)){const r=t.diffState==="insert"?"insert":t.diffState==="delete"?"delete":null;r&&this.host.inlineSuggestionKindCache.set(t.suggestionId,r)}t.children&&this.indexInlineSuggestionFacts(t.children)}getLiveSuggestionIdsForBlock(e){return this.getSuggestionIdsForBlock(e)}getSuggestionIdsForBlock(e){const t=this.host.suggestionIdsByBlockCache.get(e);if(t)return t;const n=new Set;this.collectSuggestionIdsFromBlockValue(e,n);const i=Array.from(n);return this.host.suggestionIdsByBlockCache.set(e,i),i}canResolveLiveSuggestion(e){if(this.host.canResolveLiveSuggestionCache.has(e))return this.host.canResolveLiveSuggestionCache.get(e)??!1;const t=this.computeCanResolveLiveSuggestion(e);return this.host.canResolveLiveSuggestionCache.set(e,t),t}computeCanResolveLiveSuggestion(e){const t=this.getLiveSuggestion(e);if(!t)return this.documentContainsSuggestionId(e);const n=this.host.getDocument();switch(t.type){case"inline-text":return this.documentContainsSuggestionId(t.id);case"inline-format":return this.host.inlineFormatRecordHasLiveMarker(t);case"block-change":{if(t.sequenceBlockIds)return this.getSequenceReplacementMembers(t).length>0;const i=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=z(e,this.host.ydoc,t),i=this.createLiveSuggestionProjection("reject"),r=Pr(n,i.ydoc);if(!r.anchor||!r.focus)return null;const s=ke(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=vi.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?oe(r):null,a=J(this.host.ydoc,e),l=a?oe(a):null;if(!s||!l||n>s.length)return null;const c=S.createRelativePositionFromTypeIndex(s,t,0),g=S.createRelativePositionFromTypeIndex(s,n,-1),d=S.createAbsolutePositionFromRelativePosition(c,this.host.ydoc),u=S.createAbsolutePositionFromRelativePosition(g,this.host.ydoc);return!d||!u||d.type!==l||u.type!==l||u.index<=d.index?null:{start:d.index,end:u.index}}blocksWithNotesAndChrome(e){return[...e.children,...e.notes??[],...e.chrome??[]]}collectSuggestionIdsFromBlockValue(e,t){yn.collectSuggestionIdsFromBlockValue(e,t)}static collectSuggestionIdsFromBlockValue(e,t){if(!e||typeof e!="object")return;if(Array.isArray(e)){for(const r of e)yn.collectSuggestionIdsFromBlockValue(r,t);return}const n=e;typeof n.suggestionId=="string"&&n.suggestionId.length&&t.add(n.suggestionId);const i=fn(n.marks?.layeredInsertion);if(i&&t.add(i.id),typeof n.structuralSuggestionId=="string"&&n.structuralSuggestionId.length&&t.add(n.structuralSuggestionId),typeof n.structuralSuggestionRecords=="string"&&n.structuralSuggestionRecords.length)try{const r=JSON.parse(n.structuralSuggestionRecords);if(Array.isArray(r))for(const 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"&&yn.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 d of this.getLiveSuggestionStore().values())if(d.type==="block-change"&&d.sequenceBlockIds&&this.liveSuggestionRecordTouchesAnyBlock(d,n)&&!this.applySuggestionRecordRejection(d))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=qe(s),l=qe(t),c=new Set(i);for(const[d,u]of this.getLiveSuggestionStore())this.liveSuggestionRecordTouchesAnyBlock(u,c)&&r.add(d);for(const d of i){const u=a.get(d)?.block??X(s,d);u&&this.collectSuggestionIdsFromBlockValue(u,r)}const g=this.getSuggestionMutationSelection();for(const d of i){const u=a.get(d)?.block??X(s,d),p=l.get(d)?.block??X(t,d);if(p){if(!u||u.type==="paragraph"&&p.type==="paragraph"&&JSON.stringify(u)===JSON.stringify(p))continue;this.runWithoutSuggesting(()=>this.host.replaceAnyBlockById(d,this.cloneSuggestionSnapshot(p),g,g));continue}u&&this.runWithoutSuggesting(()=>this.host.deleteBlockById(d,g,g))}this.host.transact(()=>{for(const d of r)this.deleteLiveSuggestion(d)})}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 g=c?.type==="block-change"&&!this.host.isListItemBlockChangeRecord(c);if(g&&a.has(c.blockId)){this.deleteLiveSuggestion(l),r+=1;continue}(t==="accept"?this.acceptLiveSuggestionWithoutPruning(l):this.rejectLiveSuggestionWithoutPruning(l))&&(g&&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 g=c.length-1;g>=0;g-=1){const d=c[g];if(!(d instanceof S.XmlElement))continue;const u=d.getAttribute("id"),p=d.getAttribute("structuralSuggestionId"),h=d.getAttribute("suggestionId");if(typeof u=="string"&&i.has(u)||typeof p=="string"&&n.has(p)||typeof h=="string"&&n.has(h)){l.delete(g,1);continue}typeof p=="string"&&r.has(p)&&this.clearElementStructuralSuggestion(d),typeof h=="string"&&r.has(h)&&this.setDiffSuggestionAttributes(d,void 0,void 0),a(d)}};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<tl;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 d of l)i.add(d);const g=this.applyLiveSuggestionDecisionInternal(l,e.decision);if(s.push(...this.pruneUnresolvableLiveSuggestionsInternal()),g<=0)break;t+=g}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:le()}getSuggestionIdForSuggestedSelectionOverwrite(e,t,n){if(!this.host.suggestingMode||!n?.anchor||!n.focus||ke(e,n.anchor,n.focus)===0)return null;const[i,r]=ke(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?le():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?le():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=Je(e,n.id);if(!r||!("id"in r)||typeof r.id!="string")break;n=r}return null}stripSuggestionMarksFromTextMark(e){if(!e)return;const t={...e};return delete t.insertion,delete t.deletion,delete t.suggestionId,delete t.formatChange,delete t.suggestionSource,delete t.suggestionAuthorType,delete t.suggestionCreatedAt,delete t.suggestionLabel,delete t.suggestionCommentThreadId,delete t.suggestionAuthorName,delete t.suggestionAgentModel,delete t.suggestionAgentConversationId,delete t.suggestionAgentRequestId,delete t.suggestionAgentTurn,delete t.suggestionPriorAttributes,delete t.layeredInsertion,delete t.docxMove,Object.keys(t).length>0?t:void 0}buildInlineSuggestionMetadataMarks(e,t,n){const i=this.host.liveSuggestionMetadataContext,r=i?.source??"manual",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||ie(e,t,n,{deletion:null})}findAdjacentDeletionSuggestionAttrs(e,t,n){if(n<=0)return null;const i=t+n,r=ee(e);let s=0,a=null,l=null;for(const c of r){if(typeof c.insert!="string")continue;const g=s,d=s+c.insert.length,u=c.attributes||{},p=u.deletion&&typeof u.suggestionId=="string"&&this.isOwnPendingSuggestionSpan(u);if(p&&d===t&&(a=u),p&&g===i){l=u;break}if(s=d,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??le(),l={...this.buildInlineSuggestionMetadataMarks(a,"Delete"),...this.pickInlineSuggestionMetadataMarks(s?.suggestionId===a?s:null)};let c=0,g=!1;for(let d=r.length-1;d>=0;d--){const u=r[d],p=u.attributes||{};if(p.insertion){if(this.isOwnPendingSuggestionSpan(p)){e.delete(u.start,u.length),g=!0;continue}c+=u.length,this.recordStampedId("deletionIds",a),ie(e,u.start,u.length,{deletion:!0,...l,layeredInsertion:JSON.stringify({id:p.suggestionId,source:p.suggestionSource,authorType:p.suggestionAuthorType,createdAt:p.suggestionCreatedAt,label:p.suggestionLabel,authorName:p.suggestionAuthorName,commentThreadId:p.suggestionCommentThreadId,agentModel:p.suggestionAgentModel,agentConversationId:p.suggestionAgentConversationId,agentRequestId:p.suggestionAgentRequestId,agentTurn:p.suggestionAgentTurn}),formatChange:null,suggestionPriorAttributes:null}),g=!0;continue}if(c+=u.length,p.deletion){i&&p.suggestionId!==i&&(this.recordStampedId("deletionIds",a),ie(e,u.start,u.length,{...l,formatChange:null,suggestionPriorAttributes:null}),g=!0);continue}this.recordStampedId("deletionIds",a),ie(e,u.start,u.length,{deletion:!0,...l,formatChange:null,suggestionPriorAttributes:null}),g=!0}return{retainedLength:c,changed:g}}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 y={...m};return y.fontFamily===Ee&&delete y.fontFamily,Object.keys(y).length?y:void 0}return m}}),l=a({...e,children:[]})===a({...t,children:[]}),c=(h,f)=>{let m=0;for(const y of f)y===h[m]&&m++;return m===h.length};if(t.children.length>e.children.length&&c(r,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((b,k)=>({row:b,rowIndex:k})).filter(({row:b})=>!h.has(b.id)),m=new Set(f.map(({row:b})=>b.id)),y=f.length===1?"Insert table row":"Insert table rows";return{liveBlock:this.markTableSuggestionRows(t,m,"insert",n),label:y,record:i(y,"insert",{markers:f.map(({row:b,rowIndex:k})=>({kind:"row-insert",rowId:b.id,rowIndex:k})),operations:f.map(({row:b,rowIndex:k})=>({kind:"row",action:"insert",rowId:b.id,rowIndex:k,row:this.cloneSuggestionSnapshot(b)}))})}}if(t.children.length<e.children.length&&c(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)),y=new Map(t.children.map(I=>[I.id,I])),b=this.cloneSuggestionSnapshot(t);b.children=e.children.map(I=>y.get(I.id)??I);const k=f.length===1?"Delete table row":"Delete table rows";return{liveBlock:this.markTableSuggestionRows(b,m,"delete",n),label:k,record:i(k,"delete",{markers:f.map(({row:I,rowIndex:v})=>({kind:"row-delete",rowId:I.id,rowIndex:v})),operations:f.map(({row:I,rowIndex:v})=>({kind:"row",action:"delete",rowId:I.id,rowIndex:v,row:this.cloneSuggestionSnapshot(I)}))})}}const g=this.host.findSingleTableColumnDelta(e,t);if(g&&(a({...e,children:[],columnWidths:[]})!==a({...t,children:[],columnWidths:[]})||e.children.some((h,f)=>{const m=t.children[f];return a({...h,children:[]})!==a({...m,children:[]})?!0:h.children.some(y=>{const b=m.children.find(k=>k.id===y.id);return b&&a(y)!==a(b)})})))return null;if(g?.kind==="insert"){const h=[],f=[];for(let m=0;m<t.children.length;m++){const y=t.children[m],b=y.children[g.index];b&&(h.push({kind:"cell",action:"insert",rowId:y.id,cellId:b.id,cellIndex:g.index,cell:this.cloneSuggestionSnapshot(b)}),f.push({kind:"cell-insert",rowId:y.id,cellId:b.id,rowIndex:m,cellIndex:g.index,gridColumn:g.index}))}return h.push({kind:"grid",currentColumnWidths:[...t.columnWidths],priorColumnWidths:[...e.columnWidths],currentGridXml:"",priorGridXml:""}),{liveBlock:this.markTableSuggestionColumn(t,g.index,"insert",n),label:"Insert table column",record:i("Insert table column","insert",{markers:f,operations:h})}}if(g?.kind==="delete"){const h=[],f=[];for(let m=0;m<e.children.length;m++){const y=e.children[m],b=y.children[g.index];b&&(h.push({kind:"cell",action:"delete",rowId:y.id,cellId:b.id,cellIndex:g.index,cell:this.cloneSuggestionSnapshot(b)}),f.push({kind:"cell-delete",rowId:y.id,cellId:b.id,rowIndex:m,cellIndex:g.index,gridColumn:g.index}))}return h.push({kind:"grid",currentColumnWidths:[...t.columnWidths],priorColumnWidths:[...e.columnWidths],currentGridXml:"",priorGridXml:""}),{liveBlock:this.markTableSuggestionColumn(e,g.index,"delete",n),label:"Delete table column",record:i("Delete table column","delete",{markers:f,operations:h})}}const d=Bt(e),u=Bt(t);if(e.children.length===t.children.length&&d.rows===u.rows&&d.cols===u.cols&&e.children.every((h,f)=>h.id===t.children[f]?.id)){const h=d.cells.map(f=>{const m=u.byId.get(f.cell.id);return m?{before:f,after:m}:null}).filter(f=>!!f&&(f.before.rowSpan!==f.after.rowSpan||f.before.colSpan!==f.after.colSpan));if(h.length===1&&h[0].before.col===h[0].after.col&&h[0].before.row===h[0].after.row&&h[0].before.colSpan===h[0].after.colSpan&&h[0].before.rowSpan!==h[0].after.rowSpan){const f=h[0].before,m=h[0].after,y=m.rowSpan>f.rowSpan,b=y?f.row+f.rowSpan:m.row+m.rowSpan,k=y?m.row+m.rowSpan:f.row+f.rowSpan,I=[],v=new Set([e.children[f.row].id]);for(let E=b;E<k;E++){const F=t.children[E];F&&(v.add(F.id),I.push({kind:"cell-merge",rowId:F.id,rowIndex:E,gridColumn:m.col,...y?{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(F=>F.id===E.id))))return null;const T=y?"Merge table cells":"Split table cells";return{liveBlock:this.cloneSuggestionSnapshot(t),label:T,record:i(T,"format",{markers:I,operations:[{kind:"geometry",pendingRows:x,acceptedRows:this.cloneSuggestionSnapshot(x),rejectedRows:A}]})}}}const p=h=>JSON.stringify(h.children,(f,m)=>{if(f!=="marks"||!m||typeof m!="object")return m;const y={...m};return y.fontFamily===Ee&&delete y.fontFamily,Object.keys(y).length>0?y:void 0});if(e.children.length===t.children.length&&e.children.every((h,f)=>{const m=t.children[f];return m?.id===h.id&&h.children.length===m.children.length&&h.children.every((y,b)=>{const k=m.children[b];return k?.id===y.id&&y.colSpan===k.colSpan&&y.rowSpan===k.rowSpan&&p(y)===p(k)})})){const h=[],f=[],m=(b,k,I)=>{const v={},x={};for(const A of I){const T=b[A],E=k[A];JSON.stringify(T)!==JSON.stringify(E)&&(E!==void 0&&(v[A]=E),T!==void 0&&(x[A]=T))}return{current:v,prior:x}};JSON.stringify(e.columnWidths)!==JSON.stringify(t.columnWidths)&&h.push({kind:"grid",currentColumnWidths:[...t.columnWidths],priorColumnWidths:[...e.columnWidths],currentGridXml:"",priorGridXml:""});const y=m(e,t,["tableWidth","align","borderColor","borderWidth","borders","cellPadding"]);(Object.keys(y.current).length>0||Object.keys(y.prior).length>0)&&(f.push({kind:"table-properties"}),h.push({kind:"properties",target:"table",currentPropertiesXml:"",priorPropertiesXml:"",currentAttributes:y.current,priorAttributes:y.prior})),e.hasHeader!==t.hasHeader&&t.children[0]&&(f.push({kind:"row-properties",rowId:t.children[0].id,rowIndex:0}),h.push({kind:"properties",target:"row",rowId:t.children[0].id,currentPropertiesXml:"",priorPropertiesXml:"",currentTableAttributes:t.hasHeader===void 0?{}:{hasHeader:t.hasHeader},priorTableAttributes:e.hasHeader===void 0?{}:{hasHeader:e.hasHeader}}));for(let b=0;b<t.children.length;b++){const k=e.children[b],I=t.children[b];for(let v=0;v<I.children.length;v++){const x=k.children[v],A=I.children[v],T=m(x,A,["verticalAlign","backgroundColor","borders","padding"]);if(Object.keys(T.current).length===0&&Object.keys(T.prior).length===0)continue;const E=u.byId.get(A.id);f.push({kind:"cell-properties",rowId:I.id,cellId:A.id,rowIndex:b,cellIndex:v,gridColumn:E?.col}),h.push({kind:"properties",target:"cell",rowId:I.id,cellId:A.id,currentPropertiesXml:"",priorPropertiesXml:"",currentAttributes:T.current,priorAttributes:T.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=b=>qt(JSON.parse(JSON.stringify(b,(k,I)=>i.has(k)?void 0:I))),s=e.children,a=n.children,l=new Set(s.map(b=>b.id)),c=new Set(a.map(b=>b.id)),g=new Set(s.flatMap(b=>b.children.map(k=>k.id))),d=new Set(a.flatMap(b=>b.children.map(k=>k.id))),u=new Map([...s,...a].map(b=>[b,r(b)])),p=(b,k)=>b.id===k.id?0:l.has(k.id)||c.has(b.id)?2.25:u.get(b)===u.get(k)?0:b.children.length===k.children.length&&b.children.every((I,v)=>{const x=k.children[v];return x?.colSpan===I.colSpan&&x?.rowSpan===I.rowSpan})?.75:2.25,h=Array.from({length:s.length+1},()=>Array(a.length+1).fill(0));for(let b=0;b<=s.length;b++)h[b][0]=b;for(let b=0;b<=a.length;b++)h[0][b]=b;for(let b=1;b<=s.length;b++)for(let k=1;k<=a.length;k++)h[b][k]=Math.min(h[b-1][k]+1,h[b][k-1]+1,h[b-1][k-1]+p(s[b-1],a[k-1]));const f=[];let m=s.length,y=a.length;for(;m>0&&y>0;){const b=p(s[m-1],a[y-1]);b<2&&Math.abs(h[m][y]-(h[m-1][y-1]+b))<1e-4?(f.push([s[m-1],a[y-1]]),m--,y--):h[m][y]===h[m-1][y]+1?m--:y--}for(const[b,k]of f)if(k.id=b.id,b.children.length===k.children.length)for(let I=0;I<b.children.length;I++){const v=b.children[I],x=k.children[I];v.colSpan!==x.colSpan||v.rowSpan!==x.rowSpan||v.id!==x.id&&(g.has(x.id)||d.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(g=>g.id).find(g=>n.children.some(d=>d.id===g)),c=l?n.children.findIndex(g=>g.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 g=a.children.find(d=>d.id===c.id);if(!g&&c.diffState==="delete"){const d=s.children.slice(l+1).map(p=>p.id).find(p=>a.children.some(h=>h.id===p)),u=d?a.children.findIndex(p=>p.id===d):a.children.length;g=this.cloneSuggestionSnapshot(c),a.children.splice(u,0,g)}g&&i(c,g)}}}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 oe(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?oe(i):null}stripInlineSuggestionMarks(e,t,n){ie(e,t,n,{insertion:null,deletion:null,suggestionId:null,formatChange:null,suggestionSource:null,suggestionAuthorType:null,suggestionCreatedAt:null,suggestionLabel:null,suggestionCommentThreadId:null,suggestionAuthorName:null,suggestionAgentModel:null,suggestionAgentConversationId:null,suggestionAgentRequestId:null,suggestionAgentTurn:null,suggestionPriorAttributes:null,layeredInsertion:null,docxMove:null})}restoreInlineSuggestionFormatting(e,t,n,i){const r=this.host.collectOverlappingTextSpans(e,t,n),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=ki(a.attributes?.suggestionPriorAttributes)??i,g=new Set([...Object.keys(a.attributes||{}),...Object.keys(c||{})]);g.delete("insertion"),g.delete("deletion"),g.delete("suggestionId"),g.delete("formatChange"),g.delete("suggestionSource"),g.delete("suggestionAuthorType"),g.delete("suggestionCreatedAt"),g.delete("suggestionLabel"),g.delete("suggestionCommentThreadId"),g.delete("suggestionAuthorName"),g.delete("suggestionAgentModel"),g.delete("suggestionAgentConversationId"),g.delete("suggestionAgentRequestId"),g.delete("suggestionAgentTurn"),g.delete("suggestionPriorAttributes"),g.delete("layeredInsertion"),g.delete("docxMove");for(const d of g)Object.prototype.hasOwnProperty.call(c,d)?l[d]=c[d]:l[d]=null;ie(e,a.start,a.length,l)}}clearStructuralSuggestionById(e,t){for(const n of e.toArray()){if(!(n instanceof S.XmlElement))continue;n.getAttribute("structuralSuggestionId")===t&&this.clearElementStructuralSuggestion(n);const i=n.getAttribute("structuralSuggestionRecords");if(typeof i=="string"&&i.length>0)try{const r=JSON.parse(i);if(Array.isArray(r)){const 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:_l(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),g=r.get(a);if(!l||!c||!g)continue;const d=new Set(c.children.map(p=>p.id)),u=new Set(g.children.map(p=>p.id));l.children=l.children.filter(p=>!d.has(p.id)||u.has(p.id));for(let p=0;p<g.children.length;p++){const h=g.children[p],f=c.children.find(y=>y.id===h.id);let m=l.children.find(y=>y.id===h.id);if(!m&&!f&&(m=this.cloneSuggestionSnapshot(h),l.children.splice(Math.min(p,l.children.length),0,m)),!(!m||!f)){JSON.stringify(f.children)!==JSON.stringify(h.children)&&JSON.stringify(m.children)===JSON.stringify(f.children)&&(m.children=this.cloneSuggestionSnapshot(h.children));for(const y of["rowSpan","colSpan"])f[y]!==h[y]&&(h[y]===void 0?delete m[y]:m[y]=h[y])}}}}applyTableRevisionDecision(e,t){const n=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(y=>y.id===l.rowId);f&&m<0?i.children.splice(Math.min(l.rowIndex,i.children.length),0,this.cloneSuggestionSnapshot(l.row)):!f&&m>=0&&i.children.splice(m,1);continue}if(l.kind==="cell"){const f=i.children.find(b=>b.id===l.rowId);if(!f)continue;const m=l.action==="insert"?t==="accept":t==="reject",y=f.children.findIndex(b=>b.id===l.cellId);m&&y<0?f.children.splice(Math.min(l.cellIndex,f.children.length),0,this.cloneSuggestionSnapshot(l.cell)):!m&&y>=0&&f.children.splice(y,1);continue}if(l.kind==="geometry"){this.applyTableGeometryRows(i,l.pendingRows,t==="accept"?l.acceptedRows:l.rejectedRows);continue}if(l.kind==="grid"){const f=t==="accept"?l.currentColumnWidths:l.priorColumnWidths,m=t==="accept"?l.currentGridXml:l.priorGridXml;i.columnWidths=[...f],m&&(r.grid={xml:m,columnWidths:[...f]});continue}const c=t==="accept"?l.currentAttributes:l.priorAttributes,g=t==="accept"?l.priorAttributes:l.currentAttributes;let d;if(l.target==="table"?d=i:l.target==="row"||l.target==="row-exception"?d=i.children.find(f=>f.id===l.rowId):d=i.children.flatMap(f=>f.children).find(f=>f.id===l.cellId),d)for(const f of new Set([...Object.keys(g??{}),...Object.keys(c??{})]))c&&Object.prototype.hasOwnProperty.call(c,f)&&c[f]!==void 0?d[f]=this.cloneSuggestionSnapshot(c[f]):delete d[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=z(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=z(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=z(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=Je(n,e.firstBlockId);if(!r||r.type!=="paragraph"){const g=Je(n,e.secondBlockId),d=g?"children"in g?g.children:[]:n.children,u=d.findIndex(h=>h.id===e.secondBlockId),p=u>0?d[u-1]:null;p?.type==="paragraph"&&(r=p,s=g??n)}if(!r||!i||!s||r.type!=="paragraph"||i.type!=="paragraph")return!1;const a={block:r.id,offset:r.children.reduce((g,d)=>g+(d.type==="text"?d.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=z(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=z(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=z(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=z(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=z(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 g=s.getAttribute("structuralSuggestionId");typeof g=="string"&&e.has(g)&&(this.clearElementStructuralSuggestion(s),n.add(g));const d=s.getAttribute("suggestionId");typeof d=="string"&&e.has(d)&&(this.setDiffSuggestionAttributes(s,void 0,void 0),n.add(d)),i(s);continue}if(!(s instanceof S.XmlText))continue;const a=ee(s),l=[];let c=0;for(const g of a)typeof g.insert=="string"&&(l.push({start:c,length:g.insert.length,attributes:g.attributes||{}}),c+=g.insert.length);for(let g=l.length-1;g>=0;g--){const d=l[g],u=typeof d.attributes.suggestionId=="string"?d.attributes.suggestionId:null,p=fn(d.attributes.layeredInsertion);if(u&&e.has(u)){t==="accept"?d.attributes.deletion?s.delete(d.start,d.length):this.stripInlineSuggestionMarks(s,d.start,d.length):d.attributes.deletion&&p?ie(s,d.start,d.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}):d.attributes.insertion?s.delete(d.start,d.length):d.attributes.formatChange&&ki(d.attributes.suggestionPriorAttributes)?this.restoreInlineSuggestionFormatting(s,d.start,d.length,ki(d.attributes.suggestionPriorAttributes)):this.stripInlineSuggestionMarks(s,d.start,d.length),n.add(u);continue}p&&e.has(p.id)&&(t==="accept"?ie(s,d.start,d.length,{insertion:null,layeredInsertion:null}):s.delete(d.start,d.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=z(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,g)=>{const d=c,u=this.host.getParagraphTextLength(d),p=g===0?Math.min(e.offset,u):0,h=g===s.length-1?Math.min(t.offset,u):u;return{blockId:d.id,from:p,to:h}});if(!a.some(c=>c.to>c.from))return!1;const l=le();return this.host.transact(()=>{for(const c of a){if(c.to<=c.from)continue;const g=J(this.host.ydoc,c.blockId);if(!(g instanceof S.XmlElement))continue;const d=oe(g);d&&(this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),c.blockId)?d.delete(c.from,c.to-c.from):this.applySuggestedDeletionToTextRange(d,c.from,c.to-c.from,l).retainedLength>0&&this.host.normalizeAdjacentManualReplacementOrder(d,c.from))}for(let c=0;c+1<s.length;c++){const g=s[c],d=s[c+1],u=J(this.host.ydoc,g.id),p=J(this.host.ydoc,d.id);if(!(u instanceof S.XmlElement)||!(p instanceof S.XmlElement)||this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),g.id)||this.getEnclosingBlockInsertSuggestionIdForBlockId(this.host.getDocument(),d.id))continue;const h=le();this.setParagraphStructuralSuggestion(u,"merge","before",h),this.setParagraphStructuralSuggestion(p,"merge","after",h),this.saveLiveSuggestion({id:h,type:"paragraph-merge",firstBlockId:g.id,secondBlockId:d.id})}}),this.host.setSelectionAfterOperation(r),this.host.afterOperationRelativeSelection=z(r,this.host.ydoc,this.host.getDocument()),!0}sanitizePreviewMarks(e){let t=nl(e);for(const n of go)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===Ee||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 Cr(n,i)}getListItemAlignmentKeysForSuggestionBridge(e,t){return ba(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 y=0;y<m;y++)n.push({kind:"change",index:h+y,beforeItem:u[y],afterItem:p[y]});for(let y=m;y<u.length;y++)n.push({kind:"delete",index:h+y,beforeItem:u[y]});for(let y=m;y<p.length;y++)n.push({kind:"insert",index:h+y,afterIndex:f+y,afterItem:p[y]})};let g=0,d=0;for(const u of i){let p=g;for(;p<r.length&&r[p]!==u;)p+=1;let h=d;for(;h<s.length&&s[h]!==u;)h+=1;c(e.children.slice(g,p),t.children.slice(d,h),g,d),a[p]!==l[h]&&n.push({kind:"change",index:p,beforeItem:e.children[p],afterItem:t.children[h]}),g=p+1,d=h+1}return c(e.children.slice(g),t.children.slice(d),g,d),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 d=this.cloneSuggestionSnapshot(l??s),u=this.cloneSuggestionSnapshot(i.afterItem),p=this.findListItemIndexForSuggestionBridge(d.children,a.children[i.afterIndex-1]),h=this.findListItemIndexForSuggestionBridge(d.children,a.children[i.afterIndex+1]);let f=Math.min(i.afterIndex,d.children.length);return i.afterIndex===0?f=0:p!==-1?f=p+1:h!==-1&&(f=h),d.children.splice(f,0,{...u,structuralSuggestionId:n,structuralSuggestionKind:"insert",structuralSuggestionLabel:"Insert"}),{liveBlock:d,label:"Insert",listItemSuggestion:{kind:"insert",afterItem:this.cloneSuggestionSnapshot(u)}}}if(i.kind==="delete"){const d=this.cloneSuggestionSnapshot(l??s),u=this.findListItemIndexForSuggestionBridge(d.children,i.beforeItem);if(u!==-1){const p=d.children[u];return d.children[u]={...p,structuralSuggestionId:n,structuralSuggestionKind:"delete",structuralSuggestionLabel:"Delete"},{liveBlock:d,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),g=this.findListItemIndexForSuggestionBridge(c.children,i.beforeItem);return g!==-1?(c.children[g]={...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(!bo(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 g=c===0?e.suggestionId:le(),d=i[c];if(d.kind==="change"&&this.host.canBridgeListItemChangeAsInline(d.beforeItem,d.afterItem)){const p=this.findListItemIndexForSuggestionBridge(r.children,d.beforeItem);if(p===-1)return!1;l.push({suggestionId:g,itemIndex:p,beforeItem:this.cloneSuggestionSnapshot(d.beforeItem),afterItem:this.cloneSuggestionSnapshot(d.afterItem),formatOnly:this.host.getListItemPlainText(d.beforeItem)===this.host.getListItemPlainText(d.afterItem)});continue}const u=this.buildListSuggestionChange(t,n,g,d,r);if(!u?.listItemSuggestion)return!1;r=u.liveBlock,s=!0,a.push({id:g,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 g=this.host.getListItemPlainText(c.afterItem);let d;if(c.formatOnly){const u=this.host.extractTextNodesForRange(c.afterItem,0,g.length);d=this.applyBridgeInlineFormatSuggestion({suggestionId:c.suggestionId,blockId:e.blockId,itemIndex:c.itemIndex,start:0,end:g.length,targetAttributes:{},targetTextNodes:u,createdAt:e.createdAt})}else{const u=this.host.getListItemPlainText(c.beforeItem),p=qn(u,g).diffs;let h=0,f=0;d=!0;for(let m=0;m<p.length&&d;m++){const[y,b]=p[m];if(y===0){d=this.applyBridgeInlineFormatSuggestion({suggestionId:le(),blockId:e.blockId,itemIndex:c.itemIndex,start:f,end:f+b.length,targetAttributes:{},targetTextNodes:this.host.extractTextNodesForRange(c.afterItem,h,h+b.length),createdAt:e.createdAt}),h+=b.length,f+=b.length;continue}if(y===-1){const k=p[m+1];if(k&&k[0]===1){const I=this.host.extractTextNodesForRange(c.afterItem,h,h+k[1].length);d=this.applyBridgeInlineTextSuggestion({suggestionId:c.suggestionId,blockId:e.blockId,itemIndex:c.itemIndex,start:f,deleteLength:b.length,insertNodes:I,label:"Replace",createdAt:e.createdAt}),f+=b.length+k[1].length,h+=k[1].length,m++}else d=this.applyBridgeInlineTextSuggestion({suggestionId:c.suggestionId,blockId:e.blockId,itemIndex:c.itemIndex,start:f,deleteLength:b.length,insertNodes:[],label:"Replace",createdAt:e.createdAt}),f+=b.length}else{const k=this.host.extractTextNodesForRange(c.afterItem,h,h+b.length);d=this.applyBridgeInlineTextSuggestion({suggestionId:c.suggestionId,blockId:e.blockId,itemIndex:c.itemIndex,start:f,deleteLength:0,insertNodes:k,label:"Replace",createdAt:e.createdAt}),f+=b.length,h+=b.length}}}if(!d)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((g,d)=>g+d.text.length,0)!==n)return!1;const r=[];let s=e.start;const a=e.targetTextNodes?e.targetTextNodes.map(g=>({length:g.text.length,marks:g.marks})):[{length:n,marks:e.targetAttributes}];let l=0;for(const g of a){const d=s+g.length;for(;l<i.length&&i[l].start+i[l].length<=s;)l++;for(let u=l;u<i.length&&i[u].start<d;u++){const p=i[u],h=Math.max(p.start,s),f=Math.min(p.start+p.length,d);if(f<=h)continue;const m=e.targetTextNodes?gs(p.attributes,g.marks):{...g.marks??{}};r.push({...p,start:h,length:f-h,targetAttributes:m})}s=d}const c=[];return this.host.transact(()=>{for(const g of r){const d={formatChange:!0,...this.buildInlineSuggestionMetadataMarks(e.suggestionId,"Format",e.createdAt)},u=new Set([...Object.keys(g.attributes||{}),...Object.keys(g.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=>(g.attributes?.[p]??null)===(g.targetAttributes[p]??null))){c.push(g);for(const p of u)Object.prototype.hasOwnProperty.call(g.targetAttributes,p)?d[p]=g.targetAttributes[p]:d[p]=null;ie(t,g.start,g.length,{...d,suggestionPriorAttributes:hn(g.attributes)})}}c.length!==0&&this.saveLiveSuggestion({id:e.suggestionId,type:"inline-format",spans:c.map(g=>({blockId:e.blockId,itemIndex:e.itemIndex,start:g.start,end:g.start+g.length,attributes:g.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===Qt;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 d=this.host.blockToYjsElement({...a,id:l});c=d,d.setAttribute("id",l),this.markInsertedBlockElement(d,e.suggestionId,e.label);const u=i?r.length:e.position==="before"?s:s+1;r.insert(u,[d]),e.batchInsertedBlocks?.set(l,{yBlock:d,yParent:r,index:u})});const g=this.host.ensureTrailingParagraph();return this.host.transact(()=>{this.saveLiveSuggestion({id:e.suggestionId,type:"block-insert",blockId:l,label:e.label,createdAt:e.createdAt,cleanupTrailingParagraphId:g??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"&&$e(t)!==$e(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),g=c?.type==="table"?c:t,d=this.reconcileTableDescendantIds(g,n),u=wn(t,d),p=u?null:this.buildSuggestedTableChange(g,d,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(g,d)||u||wn(g,d))r=this.markBlockForGenericSuggestionChange(d,e.suggestionId,"Table"),s=d,l="Change";else{if(i?.type==="table"&&this.collectNestedSuggestionIdsForBlock(e.blockId,e.suggestionId).length>0)return!0;r={...this.cloneSuggestionSnapshot(d),diffState:"insert",suggestionId:e.suggestionId}}}if(e.optimizeFormatting&&t.type==="paragraph"&&n.type==="paragraph"&&$e(t)===$e(n)){const c=this.batchYBlockLocationsById?.get(e.blockId)?.yBlock??J(this.host.ydoc,e.blockId),g=c?c._item:null,d=c?oe(c):null;if(c&&d&&!g?.deleted){const u=new Set(["insertion","deletion","suggestionId","formatChange","suggestionSource","suggestionAuthorType","suggestionCreatedAt","suggestionLabel","suggestionCommentThreadId","suggestionAuthorName","suggestionAgentModel","suggestionAgentConversationId","suggestionAgentRequestId","suggestionAgentTurn","suggestionPriorAttributes","layeredInsertion","proposalId","toolCallId","toolType"]),p=[];let h=0,f=!1;for(const m of n.children){if(m.type!=="text"||m.text.length===0)continue;const y=this.sanitizePreviewMarks(m.marks)??{},b=this.host.collectOverlappingTextSpans(d,h,m.text.length);f||(f=b.some(k=>["insertion","deletion","suggestionId","formatChange"].some(I=>Object.prototype.hasOwnProperty.call(k.attributes,I)))),p.push({targetAttributes:y,spans:b}),h+=m.text.length}if(!f)return this.host.transact(()=>{An(c,r);for(const{targetAttributes:m,spans:y}of p)for(const b of y){const k=new Set([...Object.keys(b.attributes??{}),...Object.keys(m)]),I={formatChange:!0,...this.buildInlineSuggestionMetadataMarks(e.suggestionId,"Format",e.createdAt)};for(const v of k)u.has(v)||(I[v]=Object.prototype.hasOwnProperty.call(m,v)?m[v]:null);I.suggestionPriorAttributes=hn(b.attributes),ie(d,b.start,b.length,I)}this.saveLiveSuggestion({id:e.suggestionId,type:"block-change",blockId:e.blockId,beforeBlock:this.cloneSuggestionSnapshot(t),acceptedBlock:this.cloneSuggestionSnapshot(n),label:l,createdAt:e.createdAt},c)}),!0}}if(t.type==="paragraph"&&n.type==="paragraph"&&JSON.stringify(t.children)===JSON.stringify(n.children)){const c=this.batchYBlockLocationsById?.get(e.blockId),g=c?c.yBlock._item:null;if(c&&!g?.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(g=>n.add(g)),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 g=t.getSuggestion(e);if(!g)return null;const d=r??g.createdAt;if(g.blockSequencePreview){const{blockId:v,blocks:x}=g.blockSequencePreview,A=X(n,v);return!A||x.length===0?null:{proposalId:e,category:"block",blockId:v,producedBlockIds:x.map(T=>T.id),apply:()=>{const T=G(this.host.ydoc,v);if(!T)return!1;const E=x.map(F=>this.sanitizePreviewBlock(F));return this.host.transact(()=>{T.yParent.delete(T.index,1);const F=E.map(P=>this.host.blockToYjsElement(P));T.yParent.insert(T.index,F);for(const P of F)this.setElementStructuralSuggestion(P,"change",void 0,e,"Paragraph");const B=this.normalizeLiveSuggestionRecord({id:e,type:"block-change",blockId:E[0].id,beforeBlock:this.cloneSuggestionSnapshot(A),sequenceBlockIds:E.map(P=>P.id),label:"Paragraph",createdAt:d});this.saveLiveSuggestion(B,F[0]);for(const P of F.slice(1))this.embedLiveSuggestionRecordInTree(B,P)}),!0}}}if(g.blockPreview?.id){const v=X(n,g.blockPreview.id);if(!v)return null;const x=g.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"?$e(v)===$e(x)?"Format":"Replace":v.type==="table"?"Table":v.type==="list"?"List":"Change",createdAt:d})}}if(g.toolCallAction?.name==="insert_block"){const v=g.toolCallAction.arguments&&typeof g.toolCallAction.arguments=="object"?g.toolCallAction.arguments:null,x=typeof v?.referenceId=="string"?v.referenceId:null,A=v?.position==="before"||v?.position==="after"?v.position:null,T=typeof v?.content=="string"?v.content:Array.isArray(v?.content)&&typeof v?.content[0]=="string"?v?.content[0]:null;if(!x||!A||!T)return null;const E=Un(g.toolCallAction),F=(E&&s?X(s,E):null)??Z.fromAgentHtml(T,{existingDocument:n}).children[0];if(!F)return null;const B={...F,id:E||F.id||Y()};return{proposalId:e,category:"block",blockId:B.id,insertReferenceId:x,apply:()=>this.insertBlockRelativeWithSuggestion({block:B,referenceId:x,position:A,suggestionId:e,label:"Insert",createdAt:d,batchInsertedBlocks:a})}}if(g.insertionContext){const v=this.host.resolvePositionAwareInsertionReference({baseDoc:n,mustBeAfter:g.insertionContext.mustBeAfter,mustBeBefore:g.insertionContext.mustBeBefore});return v?{proposalId:e,category:"block",blockId:g.insertionContext.paragraphId,insertReferenceId:v.referenceId,apply:()=>this.insertBlockRelativeWithSuggestion({block:{...this.cloneSuggestionSnapshot(g.insertionContext.content),id:g.insertionContext.content.id||g.insertionContext.paragraphId||Y()},referenceId:v.referenceId,position:v.position,suggestionId:e,label:"Insert",createdAt:d,batchInsertedBlocks:a})}:null}const u=t.resolveAnchorsAgainstDoc(e,i),p=g.anchors?.[0]?.paragraphId??null,h=g.inlinePreview&&!g.toolCallAction?g.inlinePreview:null,f=h?{resolvedPreview:(g.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?jl(v,p):null}));if(!f)return null;const{resolvedPreview:m,previewAnchorBlock:y}=f;if(g.toolCallAction?.name==="remove_block"){const v=g.toolCallAction.arguments&&typeof g.toolCallAction.arguments=="object"?g.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:d})}}const b=g.anchors?.[0],k=u[0],I=m[0];if(b?.paragraphId){const v=X(n,b.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((F,B)=>({...F,children:F.children.map((P,w)=>({...P,children:v.children[B].children[w].children}))}))});const A=x??y;if(g.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"?$e(v)===$e(A)?"Format":"Replace":v.type==="table"?"Table":v.type==="list"?"List":"Change",createdAt:d})};if(v?.type==="paragraph"){const F=k?.fromIndex??k?.toIndex,B=b.previewStartOffset??I?.fromIndex??I?.toIndex;if(b.kind==="delete"){const P=F??B??0,w=b.text?.length??Math.max(0,(k?.toIndex??P)-P),C=Math.max(0,P-w);return{proposalId:e,category:"inline",blockId:v.id,start:C,inlinePriority:2,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:e,blockId:v.id,start:C,deleteLength:w,insertNodes:[],label:"Delete",createdAt:d})}}if(b.kind==="insert"&&(h||A?.type==="paragraph")){const P=B??F??0,w=B??P,C=b.previewStartOffset!==void 0?w+(b.text?.length??0):I?.toIndex??w+(b.text?.length??0),$=b.previewTextNodes?b.previewTextNodes.map(L=>({...L,marks:L.marks?{...L.marks}:void 0})):h?this.buildInlinePreviewTextNodes(h):this.host.extractTextNodesForRange(A,w,C);return{proposalId:e,category:"inline",blockId:v.id,start:P,inlinePriority:0,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:e,blockId:v.id,start:P,deleteLength:0,insertNodes:$,label:"Insert",createdAt:d})}}if(b.kind==="replace"&&(h||A?.type==="paragraph")){const P=B??F??0,w=B??P,C=b.previewStartOffset!==void 0?w+(b.text?.length??0):I?.toIndex??w+(b.text?.length??0),$=b.previewTextNodes?b.previewTextNodes.map(L=>({...L,marks:L.marks?{...L.marks}:void 0})):h?this.buildInlinePreviewTextNodes(h):this.host.extractTextNodesForRange(A,w,C);return b.oldText===b.text?{proposalId:e,category:"inline",blockId:v.id,start:P,inlinePriority:1,apply:()=>this.applyBridgeInlineFormatSuggestion({suggestionId:e,blockId:v.id,start:P,end:P+(b.text?.length??0),targetAttributes:{},targetTextNodes:$,createdAt:d})}:{proposalId:e,category:"inline",blockId:v.id,start:P,inlinePriority:2,apply:()=>this.applyBridgeInlineTextSuggestion({suggestionId:e,blockId:v.id,start:P,deleteLength:b.oldText?.length??0,insertNodes:$,label:"Replace",createdAt:d})}}}if(v?.type==="list"&&A?.type==="list")return{proposalId:e,category:"block",blockId:v.id,apply:()=>this.applyBridgeBlockChangeSuggestion({suggestionId:e,blockId:v.id,beforeBlock:v,afterBlock:A,optimizeFormatting:!c&&(l||b.oldText===b.text),label:"List",createdAt:d})};const T=v?.type,E=A?.type;if(T==="list-item"&&E==="list-item"){const F=v,B=A,P=Je(n,F.id)?.children.find(w=>w?.type!=="list"?!1:w.children.some(C=>C.id===F.id));if(P?.id){const w=P.children.findIndex(C=>C.id===F.id);if(w!==-1){const C=this.cloneSuggestionSnapshot(P),$=this.cloneSuggestionSnapshot(P);return $.children[w]=this.cloneSuggestionSnapshot(B),{proposalId:e,category:"block",blockId:P.id,apply:()=>{const L=X(this.host.getDocument(),P.id);return this.applyGranularListSuggestionChanges({blockId:P.id,before:C,after:$,suggestionId:e,currentLiveBlock:L?.type==="list"?L:void 0,createdAt:d})}}}}}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:d})}}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(T=>T.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,g=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 T=typeof v?.find=="string"?v.find:"";return T.length>0&&$e(A).includes(T)})??a,d=g?.name??"agent change",u=g?.arguments&&typeof g.arguments=="object"?g.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,y=f??m,b=y?y.type:null,k=p?`'${p}'${typeof b=="string"?` (${b})`:""}`:"the requested target";return!f&&m?`Could not apply ${e.category} suggestion for ${d} to block ${k}: the target was present when the action was planned but is no longer available at replay time. The attempted change was rolled back; re-read that block and retry.`:y?`Could not apply ${e.category} suggestion for ${d} 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 ${d}: 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(B=>B.name==="style_blocks"),i=new jr(e.baseFork,n),r=new Map;for(const{block:B}of qe(e.docBeforeToolCall).values())B.type==="list"&&B.id&&r.set(B.id,B.children.map(P=>P.id));for(const B of this.getLiveSuggestionIds()){const P=this.getLiveSuggestion(B);P?.type==="block-change"&&P.sequenceBlockIds&&P.beforeBlock.id&&r.set(P.beforeBlock.id,this.getSequenceReplacementMembers(P).map(({yBlock:w})=>w.getAttribute("id")))}const s=Nr(e.validationFork,i,{...e.flattenOptions,precomputedLiveDocSchema:e.baseDocForSuggestions,precomputedCurrentDocSchema:e.baseDocForSuggestions,listUnwrapMemberIds:r,precomputedFinalDocSchema:e.docAfterToolCall}),a=e.validationAnchorsByAction.flat().filter(B=>B.kind==="replace"&&B.previewStartOffset!==void 0&&!!B.paragraphId);for(const B of a){const P=s.filter(w=>(i.getSuggestion(w)?.anchors??[]).some(C=>C.kind==="replace"&&C.paragraphId===B.paragraphId&&(C.oldText??"").includes(B.oldText??"")&&(C.text??"").includes(B.text??"")));if(P.length===1){const w=i.getSuggestion(P[0]),C=B.sourceFrom?S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(B.sourceFrom),e.baseFork):null,$=B.paragraphId?J(e.baseFork,B.paragraphId):null,L=$?oe($):null,O=L?ee(L).map(M=>typeof M.insert=="string"?M.insert:"").join(""):"";w&&C&&C.type===L&&O.slice(C.index,C.index+(B.oldText?.length??0))===(B.oldText??"")&&(w.anchors=[{...B,previewStartOffset:C.index}])}}const l=s.length>=100,c=Date.now(),g=B=>{l&&(`${s.length}${B}`,Date.now()-c)};if(g("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 d=e.baseDocForSuggestions,u=(e.processedActions??[]).map((B,P)=>{const w=B.arguments&&typeof B.arguments=="object"?B.arguments:null,C=typeof w?.comment=="string"?w.comment.trim():"";return{action:B,comment:C,anchors:e.validationAnchorsByAction[P]??[]}}).filter(({action:B,comment:P})=>(B.name==="replace"||B.name==="replace_all")&&P.length>0),p=new Map;for(const B of u){const P=B.anchors.flatMap(w=>{if(!w.from||!w.to||!w.paragraphId)return[];const C=S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(w.from),e.validationFork),$=S.createAbsolutePositionFromRelativePosition(S.decodeRelativePosition(w.to),e.validationFork);if(!C||!$||C.type!==$.type)return[];const L=w.oldText??"",O=w.text??"";let M=0;for(;M<L.length&&M<O.length&&L[M]===O[M];)M++;let N=0;for(;N<L.length-M&&N<O.length-M&&L[L.length-1-N]===O[O.length-1-N];)N++;const _=L.length>O.length&&M+N===O.length?C.index+M:null;return[{paragraphId:w.paragraphId,start:C.index,end:$.index,deletionPoint:_}]});p.set(B,P)}const h=new Map,f=s.map(B=>this.buildAgentSuggestionPlanFromProposal(B,i,d,e.baseFork,void 0,e.docAfterToolCall,h,e.optimizeStyleFormatting===!0,u.length>0)).filter(B=>!!B);if(g("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(B=>B.category==="block")),y=new Map(s.map((B,P)=>[B,P])),b=f.filter(B=>B.category==="inline").sort((B,P)=>{if(B.blockId&&P.blockId&&B.blockId===P.blockId){const w=(P.start??0)-(B.start??0);if(w!==0)return w;const C=(P.inlinePriority??0)-(B.inlinePriority??0);if(C!==0)return C}return(y.get(B.proposalId)??0)-(y.get(P.proposalId)??0)});let k=[];const I=this.host.beginRollbackScope();let v=null;try{g("applying plans"),k=this.withSuggestionMetadata({source:"agent",authorType:"ai",label:`${e.agentName??Ze} revision`,agentName:e.agentName??Ze,agentModel:e.agentModel,commentThreadId:e.commentThreadId,agentConversationId:e.agentConversationId,agentRequestId:e.agentRequestId,agentTurn:e.agentTurn,historyOrigin:`live-suggestions:${e.toolCallId}`},()=>this.host.transact(()=>{const B=new Set(Array.from(e.flattenOptions?.affectedBlockIds??[]));for(const C of f)C.blockId&&B.add(C.blockId);v=m[0]??b[0]??null,this.resetLiveSuggestionsForBlocks(B,d),this.batchYBlockLocationsById=new Map;const P=new Map;for(const C of m){if(!C.blockId)continue;const $=J(this.host.ydoc,C.blockId);$&&P.set($,C.blockId)}const w=new Map;for(const[C,$]of P){const L=C.parent;if(!(L instanceof S.XmlElement||L instanceof S.XmlFragment))continue;const O=w.get(L)??new Map;O.set(C,$),w.set(L,O)}for(const[C,$]of w)C.toArray().forEach((L,O)=>{if(!(L instanceof S.XmlElement))return;const M=$.get(L);M&&this.batchYBlockLocationsById.set(M,{yBlock:L,yParent:C,index:O})});try{for(const C of m)if(v=C,!C.apply())throw new Error("suggestion application returned false");for(const C of b)if(v=C,!C.apply())throw new Error("suggestion application returned false")}finally{this.batchYBlockLocationsById=null}g("finished plan loop"),v=null})).suggestionIds,g("applied plans"),I.dispose()}catch(B){I.revert();const P=B instanceof Error?B.message:"suggestion application failed",w=P==="suggestion application returned false"?null:P,C=v?this.describeAgentSuggestionApplyFailure(v,i,d,e.originalActions):null;return{success:!1,error:C?`${C}${w?` Detail: ${w}`:""}`:w??"Could not apply the requested edit."}}this.host.relinkCommentSuggestionIds();const x=u.length?this.host.getSuggestionCommentRanges(k):[],A=[],T=[];let E=0;for(const[B,P]of p){const w=x.flatMap(O=>P.flatMap(M=>{if(O.structural){if(M.paragraphId!==O.blockId)return[];const N=Math.max(O.projectedStart,M.start),_=Math.min(O.projectedEnd,M.end);return _<N||_===N&&M.start!==M.end?[]:[{...O,start:O.start+N-O.projectedStart,end:O.start+_-O.projectedStart}]}return(()=>{if(M.paragraphId!==O.blockId)return!1;const N=O.projectedStart,_=O.projectedEnd;return N===_&&M.start===M.end?N===M.start:N===_?M.deletionPoint===N||M.start<N&&N<M.end:M.start===M.end?N<M.start&&M.start<_:N<M.end&&M.start<_})()?[O]:[]})),C=Array.from(new Set(w.map(O=>O.suggestionId)));if(C.length===0){E++;for(const O of k)A.includes(O)||A.push(O);continue}for(const O of C)A.includes(O)||A.push(O);const $={author:e.agentName??Ze,authorType:"ai",agentName:e.agentName??Ze,agentModel:e.agentModel,suggestionId:C[0],...C.length>1?{relatedSuggestionIds:C}:{}},L=w.every(O=>O.structural&&O.start===O.end)?this.host.addBlockComment(w[0].blockId,B.comment,$):this.host.addCommentToRanges(w.map(({blockId:O,start:M,end:N})=>({blockId:O,start:M,end:N})),B.comment,$);L?T.push(L):E++}const F=dl(e.agentFeedback,e.originalActions,s,e.docBeforeToolCall,e.docAfterToolCall);return{success:k.length>0,planningSuggestionIds:s,suggestionIds:k,commentedSuggestionIds:A,attachedCommentIds:T,commentAttachmentFailureCount:E,agentFeedback:k.length>0?F: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)}),Xl(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),Ln(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),g=X(e.docAfterToolCall,a);c&&g&&JSON.stringify(c)===JSON.stringify(g)&&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 jr(this.host.cloneYDoc(this.host.ydoc));return this.rebuildDetachedSuggestionsFromSnapshotWithStore(e,t)}rebuildDetachedSuggestionsFromSnapshotWithStore(e,t){const n=Bi(e);return Nr(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),Br.clearAllStoredSuggestions(this.host.documentId)}migrateLegacyDetachedSuggestionsToLiveSuggestions(e){const t=this.host.cloneYDoc(this.host.ydoc),n=new jr(t);if(this.hasSerializedDetachedSuggestions(e.serverDetachedSuggestions)){const g=this.host.cloneYDoc(this.host.ydoc),d=new Br(g,`${this.host.documentId}-legacy-proposal-materialization`,!0,e.conversationId);d.loadFromServerData(e.serverDetachedSuggestions);const u=Array.from(d.getPendingSuggestions().keys());if(u.length>0){const p=fe(d.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=fe(t),s=i.map(g=>this.buildAgentSuggestionPlanFromProposal(g,n,r,t,e.legacyCreatedAt)).filter(g=>!!g);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(g=>g.category==="block")),l=s.filter(g=>g.category==="inline").sort((g,d)=>g.blockId&&d.blockId&&g.blockId===d.blockId?(d.start??0)-(g.start??0):i.indexOf(g.proposalId)-i.indexOf(d.proposalId));let c=[];try{c=this.withSuggestionMetadata({source:"agent",authorType:"ai",createdAt:e.legacyCreatedAt,label:"Agent revision",agentName:Ze,historyOrigin:`migrated-legacy-proposals:${e.conversationId}`},()=>{for(const g of a)if(!g.apply())throw new Error(`Failed migrating block proposal ${g.proposalId}`);for(const g of l)if(!g.apply())throw new Error(`Failed migrating inline proposal ${g.proposalId}`)}).suggestionIds}catch(g){return{success:!1,migratedSuggestionCount:0,error:g instanceof Error?g.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 $u{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?le():null,l=G(this.host.ydoc,e);if(!l)return!1;const{yBlock:c,yParent:g,index:d}=l;this.host.transact(()=>{if(!(c instanceof S.XmlElement))return;const h=new S.XmlElement("list"),f=c.getAttribute("id")||Y();h.setAttribute("id",f),h.setAttribute("variant",t),a&&this.host.suggestionEngine.setElementStructuralSuggestion(h,"change",void 0,a,"List"),n&&t==="ordered"?(h.setAttribute("startNumber",String(n)),this.host.listStartNumberCache.set(f,n)):t==="ordered"?(h.setAttribute("startNumber",String(1)),this.host.listStartNumberCache.set(f,1)):this.host.listStartNumberCache.delete(f);let m,y;for(let x=0;x<c.length;x++){const A=c.get(x);if(A instanceof S.XmlText){y=A;break}}if(y&&y.length>0){const x=ee(y);for(const A of x)if(A.attributes?.fontFamily){m=A.attributes.fontFamily;break}}if(!m&&r.type==="paragraph"){for(const x of r.children)if(x.type==="text"&&x.marks?.fontFamily){m=x.marks.fontFamily;break}}const b=[],k=[],I=(x,A)=>{k.push({ops:x,plain:A})};if(y&&y.length>0){const x=ee(y);let A=[],T="";const E=()=>{I(A,T),A=[],T=""};x.forEach(F=>{if(typeof F.insert=="string"){let B=F.insert;for(;B.length>0;){const P=B.indexOf(`
|
|
29
|
+
`);if(P===-1)B.length>0&&(A.push({insert:B,attributes:F.attributes&&Object.keys(F.attributes).length>0?{...F.attributes}:void 0}),T+=B),B="";else{const w=B.slice(0,P);w.length>0&&(A.push({insert:w,attributes:F.attributes&&Object.keys(F.attributes).length>0?{...F.attributes}:void 0}),T+=w),E(),B=B.slice(P+1)}}}else if(F.insert!==void 0&&F.insert!==null){let B=null;if(typeof F.insert=="string")B=F.insert;else try{B=JSON.stringify(F.insert)}catch{B=String(F.insert)}B&&B.length>0&&(A.push({insert:B,attributes:F.attributes&&Object.keys(F.attributes).length>0?{...F.attributes}:void 0}),T+=B)}}),E()}else k.push({ops:[],plain:""});k.length===0&&k.push({ops:[],plain:""});const v=te(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 T=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(B=>B.insert.length>0)?.attributes,F={...ct(E)??{}};F.fontFamily||(F.fontFamily=m||Ee),A.setAttribute("_emptyTextMarks",JSON.stringify(F))}else{let E=0;x.ops.forEach(({insert:F,attributes:B})=>{if(F.length===0)return;const P=B?{...B}:{};P.fontFamily||(m||console.warn("[DocumentMutator] convertParagraphToList: No font found, defaulting to Arial. This may indicate a bug."),P.fontFamily=m||Ee),T.insert(E,F,P),E+=F.length})}A.insert(0,[T]),b.push(A)}),h.insert(0,b),g.delete(d,1),g.insert(d,[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"),g=l||Y();c.setAttribute("id",g),c.setAttribute("variant",n),n==="ordered"?(c.setAttribute("startNumber",String(1)),this.host.listStartNumberCache.set(g,1)):this.host.listStartNumberCache.delete(g);const d=[];let u;for(const f of r){if(f.type==="paragraph"){for(const m of f.node.children)if(m.type==="text"&&m.marks?.fontFamily){u=m.marks.fontFamily;break}}else if(f.type==="list")for(const m of f.node.children){for(const y of m.children)if(y.type==="text"&&y.marks?.fontFamily){u=y.marks.fontFamily;break}if(u)break}if(u)break}let p=!1;const h=(f,m)=>{const y=new S.XmlElement("list-item");y.setAttribute("id",Y()),n==="todo"&&y.setAttribute("checked",String(m?.checked??!1)),(m?.direction==="rtl"||m?.direction==="ltr")&&y.setAttribute("direction",m.direction);const b=new S.XmlText;let k=f;if((n==="unordered"&&(f==="-"||f==="*")||n==="ordered"&&/^\d+\.$/.test(f)||n==="todo"&&f==="[]")&&(k=""),k){const v=m?.fontFamily||u;v||console.warn("[DocumentMutator] convertParagraphRangeToList: No font found for list item, defaulting to Arial. This may indicate a bug."),b.insert(0,k,{fontFamily:v||Ee})}const I=m?.indentLevel;typeof I=="number"&&I>0&&y.setAttribute("indentLevel",String(I)),y.insert(0,[b]),d.push(y),p=!0};r.forEach(f=>{if(f.type==="paragraph"){const m=f.node.children.filter(b=>b.type==="text").map(b=>b.text).join("");let y;for(const b of f.node.children)if(b.type==="text"&&b.marks?.fontFamily){y=b.marks.fontFamily;break}(m.length>0?m.split(`
|
|
30
|
+
`):[""]).forEach(b=>{h(b,{fontFamily:y,direction:f.node.direction})})}else{const m=f.node;m.children.forEach(y=>{const b=this.getListItemPlainText(y),k=m.variant==="todo"?y.checked??!1:void 0;let I;for(const v of y.children)if(v.type==="text"&&v.marks?.fontFamily){I=v.marks.fontFamily;break}h(b,{checked:k,indentLevel:y.indentLevel,fontFamily:I,direction:y.direction})})}}),p||h(""),c.insert(0,d),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?le():null;n.id&&this.host.listStartNumberCache.delete(n.id),this.host.transact(()=>{const a=this.host.getYContentFragment(),l=a.get(e);if(!(l instanceof S.XmlElement))return;const c=[];for(let p=0;p<l.length;p++){const h=l.get(p);if(h instanceof S.XmlElement&&h.nodeName==="list-item"){let f=null;for(let m=0;m<h.length;m++){const y=h.get(m);if(y instanceof S.XmlText){f=y;break}}f?c.push({delta:ee(f)}):c.push({delta:[]})}}const g=new S.XmlElement("paragraph");g.setAttribute("id",l.getAttribute("id")||Y());{const p=n.children[0]?.direction;(p==="rtl"||p==="ltr")&&g.setAttribute("direction",p)}i&&this.host.suggestionEngine.setParagraphStructuralSuggestion(g,"change",void 0,i,"Paragraph");const d=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?d.insert(u,f.insert,f.attributes):d.insert(u,f.insert),u+=f.insert.length)}),h<c.length-1&&(d.insert(u,`
|
|
31
|
+
`),u+=1)}),g.insert(0,[d]),a.delete(e,1),a.insert(e,[g])});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"),g=c?parseInt(c,10):void 0,d=this.host.listStartNumberCache.get(s),u=n??a??g??d??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 g=l.get(c);g instanceof S.XmlElement&&g.nodeName==="list-item"&&(t==="todo"?g.getAttribute("checked")===void 0&&g.setAttribute("checked","false"):g.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?le():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:g}=a;this.host.transact(()=>{if(!(l instanceof S.XmlElement))return;const p=[];for(let f=0;f<l.length;f++){const m=l.get(f);if(m instanceof S.XmlElement&&m.nodeName==="list-item"){let y=null;for(let k=0;k<m.length;k++){const I=m.get(k);if(I instanceof S.XmlText){y=I;break}}const b=m.getAttribute("direction");p.push({delta:y?ee(y):[],...b==="rtl"||b==="ltr"?{direction:b}:{}})}}p.length===0&&p.push({delta:[]});const h=p.map((f,m)=>{const y=new S.XmlElement("paragraph");y.setAttribute("id",m===0?l.getAttribute("id")||Y():Y()),f.direction&&y.setAttribute("direction",f.direction),s&&this.host.suggestionEngine.setParagraphStructuralSuggestion(y,"change",void 0,s,"Paragraph");const b=new S.XmlText;let k=0;return f.delta.forEach(I=>{typeof I.insert=="string"&&(I.attributes&&Object.keys(I.attributes).length>0?b.insert(k,I.insert,I.attributes):b.insert(k,I.insert),k+=I.insert.length)}),y.insert(0,[b]),y});if(c.delete(g,1),c.insert(g,h),this.host.suggestingMode&&s&&r){const f=h.map(y=>y.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 y of h.slice(1))this.host.suggestionEngine.embedLiveSuggestionRecordInTree(this.host.suggestionEngine.getLiveSuggestion(s)??m,y)}});const d={block:l.getAttribute("id")||e,offset:0};this.host.setSelectionAfterOperation({anchor:d,focus:d});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,g=this.host.suggestingMode?le():null,d=G(this.host.ydoc,e);if(!d)return!1;const{yBlock:u}=d;return this.host.transact(()=>{if(u instanceof S.XmlElement){if(u.setAttribute("variant",t),g&&(this.host.suggestionEngine.clearElementStructuralSuggestion(u),this.host.suggestionEngine.setElementStructuralSuggestion(u,"change",void 0,g,"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&&g&&a&&this.host.suggestionEngine.saveLiveSuggestion({id:g,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=d=>{for(const u of d)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(d=>d.id===e);let a;for(let d=s-1;d>=0;d--)if(i[d].variant==="ordered"){a=i[d];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 g=a.numberingChainId??Y();return this.host.transact(()=>{a.numberingChainId||c.setAttribute("numberingChainId",g),l.setAttribute("numberingChainId",g),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:g,yParent:d,index:u}=c;if(!(g instanceof S.XmlElement))return null;if(a===0)return this.host.transact(()=>{g.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(g,a)),g.delete(a,g.length-a),d.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=te(r,"direction");c!==void 0&&s.setAttribute("direction",c);let g=null;for(let u=0;u<r.length;u++){const p=r.get(u);if(p instanceof S.XmlText){g=p;break}}const d=new S.XmlText;if(g&&g.length>0){const u=ee(g);let p=0;u.forEach(h=>{typeof h.insert=="string"&&(d.insert(p,h.insert,h.attributes||{}),p+=h.insert.length)})}s.insert(0,[d]),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=at(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,g=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(r):null,d=this.host.suggestingMode?le():null;let u=null,p=null,h=!0;if(this.host.transact(()=>{const f=G(this.host.ydoc,r.id);if(!f)return;const{yBlock:m,yParent:y,index:b}=f;if(!(m instanceof S.XmlElement))return;const k=[];for(let M=0;M<m.length;M++){const N=m.get(M);N instanceof S.XmlElement&&N.nodeName==="list-item"&&k.push(N)}let I=-1;for(let M=0;M<k.length;M++){const N=k[M];for(let _=0;_<N.length;_++){const R=N.get(_);if(R instanceof S.XmlText&&R===l){I=M;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(M=>M.type==="text"?M.text:"").join(""),T=this.host.suggestingMode&&c<A.length&&(()=>{let M=0,N=!1;for(const _ of x.children){if(_.type!=="text")continue;const R=M+_.text.length;if(R>c&&_.text.length>0&&(N=!0,!_.marks?.deletion))return!1;M=R}return N})();if(A.trim().length===0&&r.children.length===1){const M=new S.XmlElement("paragraph");u=Y(),M.setAttribute("id",u),(x.direction==="rtl"||x.direction==="ltr")&&M.setAttribute("direction",x.direction),h=!1;let 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&&M.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:N}));const _=new S.XmlText;M.insert(0,[_]),y.delete(b,1),y.insert(b,[M]);return}if(A.trim().length===0&&r.children.length>1){const M=I===r.children.length-1,N=I===0;if(N||M){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?y.insert(b,[_]):y.insert(b+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 H=[];for(let K=I+1;K<k.length;K++){const se=k[K],xe=new S.XmlElement("list-item");xe.setAttribute("id",se.getAttribute("id")||Y());const Ue=se.getAttribute("checked");Ue!==void 0&&xe.setAttribute("checked",Ue);const Oe=se.getAttribute("indentLevel");Oe!==void 0&&xe.setAttribute("indentLevel",Oe);const W=te(se,"direction");W!==void 0&&xe.setAttribute("direction",W);let Q=null;for(let V=0;V<se.length;V++){const ce=se.get(V);if(ce instanceof S.XmlText){Q=ce;break}}const re=new S.XmlText;if(Q&&Q.length>0){const V=ee(Q);let ce=0;V.forEach(ae=>{if(typeof ae.insert=="string"){const de=ae.attributes||{};re.insert(ce,ae.insert,de),ce+=ae.insert.length}})}xe.insert(0,[re]),H.push(xe)}R.insert(0,H),m.delete(I,_+1),y.insert(b+1,[D,R])}return}if(c===0){const M=new S.XmlElement("list-item"),N=Y();M.setAttribute("id",N),u=N,r.variant==="todo"&&M.setAttribute("checked","false");const _=x.indentLevel??0;_>0&&M.setAttribute("indentLevel",String(_)),(x.direction==="rtl"||x.direction==="ltr")&&M.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;M.insert(0,[D]),R?M.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:R})):M.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:Ee})),d&&(this.host.suggestionEngine.clearElementStructuralSuggestion(M),this.host.suggestionEngine.setElementStructuralSuggestion(M,"insert",void 0,d,"Insert")),m.insert(I,[M]),u=x.id??null,p=I+1;return}if(c>=A.length||T){const M=new S.XmlElement("list-item");u=Y(),M.setAttribute("id",u),p=I+1,r.variant==="todo"&&M.setAttribute("checked","false");const N=x.indentLevel??0;N>0&&M.setAttribute("indentLevel",String(N)),(x.direction==="rtl"||x.direction==="ltr")&&M.setAttribute("direction",x.direction);let _=this.host.getFontAtOffsetInListItem(x,c);_||(_=this.host.resolveFontFamilyForList(r));const R=new S.XmlText;M.insert(0,[R]),_?M.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:_})):M.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:Ee})),d&&(this.host.suggestionEngine.clearElementStructuralSuggestion(M),this.host.suggestionEngine.setElementStructuralSuggestion(M,"insert",void 0,d,"Insert")),m.insert(I+1,[M]);return}let E=null;for(let M=0;M<v.length;M++){const N=v.get(M);if(N instanceof S.XmlText){E=N;break}}if(!E)return;const F=ee(E);let B=0;const P=[];for(const M of F)if(M.insert&&typeof M.insert=="string"){const N=M.insert.length;if(B+N<=c)B+=N;else if(B>=c)P.push(M);else{const _=c-B,R=M.insert.slice(_);R&&P.push({insert:R,...M.attributes&&{attributes:M.attributes}}),B=c}}c<E.length&&E.delete(c,E.length-c);const w=new S.XmlElement("list-item");u=Y(),w.setAttribute("id",u),p=I+1,r.variant==="todo"&&w.setAttribute("checked","false");const C=x.indentLevel??0;C>0&&w.setAttribute("indentLevel",String(C)),(x.direction==="rtl"||x.direction==="ltr")&&w.setAttribute("direction",x.direction);const $=this.host.getFontAtOffsetInListItem(x,c),L=new S.XmlText;let O=0;if(P.length>0){for(const M of P)if(M.insert&&typeof M.insert=="string"){const N=M.attributes&&Object.keys(M.attributes).length>0?{...M.attributes}:{};N.fontFamily||($||console.warn("[DocumentMutator] splitListItem: No font found for new list item, defaulting to Arial. This may indicate a bug."),N.fontFamily=$||Ee),L.insert(O,M.insert,N),O+=M.insert.length}}else{const M=$||this.host.resolveFontFamilyForList(r)||Ee;w.setAttribute("_emptyTextMarks",JSON.stringify({fontFamily:M}))}d&&(this.host.suggestionEngine.clearElementStructuralSuggestion(v),this.host.suggestionEngine.clearElementStructuralSuggestion(w),this.host.suggestionEngine.setElementStructuralSuggestion(v,"split","before",d,"Split"),this.host.suggestionEngine.setElementStructuralSuggestion(w,"split","after",d,"Split")),w.insert(0,[L]),m.insert(I+1,[w])}),h){const f=this.host.getDocument(),m=X(f,r.id);if(!m||m.type!=="list"||p===null)return null;const y=m;let b=0;for(let v=0;v<p;v++){const x=y.children[v];for(const A of x.children)A.type==="text"&&(b+=A.text.length);v<p-1&&(b+=1)}p>0&&(b+=1);const k={block:y.id,offset:b},I={anchor:k,focus:k};return this.host.suggestingMode&&d&&g&&this.host.suggestionEngine.saveLiveSuggestion({id:d,type:"block-change",blockId:r.id,beforeBlock:g,label:"List"}),this.host.setSelectionAfterOperation(I),this.host.afterOperationRelativeSelection=z(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=z(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=at(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,g=l.index;let d=null;if(i?.anchor&&i.focus&&ke(r.doc,i.anchor,i.focus)!==0){const A=at(i.anchor,this.host.ydoc,r.doc),T=at(i.focus,this.host.ydoc,r.doc),E=A?S.createAbsolutePositionFromRelativePosition(A.textOffset,this.host.ydoc):null,F=T?S.createAbsolutePositionFromRelativePosition(T.textOffset,this.host.ydoc):null;E?.type instanceof S.XmlText&&F?.type instanceof S.XmlText&&E.type===F.type&&E.type===c&&(d={yText:c,startOffset:Math.min(E.index,F.index),endOffset:Math.max(E.index,F.index)})}const u={},p=[],h=vo(s,e),f=$i(s,e),m=Li(s,e),y=this.host.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(s,e.block),b=y?null:this.host.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(s,e),k=b?.marks?.suggestionId??null,I=this.host.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(s,e,i);{const A=!y&&this.host.suggestingMode&&t.length>0,T=vr({explicitMarks:n&&Object.keys(n).length>0?n:void 0,inheritedMarks:h?.marks,exitingLink:f,exitingComment:m,suggestionMarks:A?this.host.suggestionEngine.buildSuggestionInsertionMarks(void 0,I??k??this.host.suggestionEngine.getSuggestionIdFromInheritedMarks(h?.marks),void 0,void 0,b?.marks??h?.marks):void 0});Object.assign(u,T.marksToApply),p.push(...T.marksToRemove)}let v=d?.startOffset??g;this.host.transact(()=>{if(d&&d.endOffset>d.startOffset){const A=d.endOffset-d.startOffset;if(this.host.suggestingMode&&!y){const T=this.host.suggestionEngine.applySuggestedDeletionToTextRange(d.yText,d.startOffset,A,I??void 0);v=d.startOffset+T.retainedLength}else d.yText.delete(d.startOffset,A),v=d.startOffset}ca(c,v,t,{marksToApply:u,marksToRemove:p}),!y&&this.host.suggestingMode&&t.length>0&&this.host.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(c,v,t.length)});const x=S.createRelativePositionFromTypeIndex(c,v+t.length);return li({blockId:a.blockId,textOffset:x},this.host.ydoc)}insertTextInList(e,t,n,i){this.host.beforeOperationSelection=n;const r=this.insertTextInListItem(e,t,null,n);if(r){const s={anchor:r,focus:r};return this.host.setSelectionAfterOperation(s),this.host.afterOperationRelativeSelection=z(s,this.host.ydoc,this.host.getDocument()),!0}return this.host.setSelectionAfterOperation(i),this.host.afterOperationRelativeSelection=z(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=z(a,this.host.ydoc,this.host.getDocument()),!0}return this.host.setSelectionAfterOperation(r),this.host.afterOperationRelativeSelection=z(r,this.host.ydoc,this.host.getDocument()),!0}deleteTextInList(e,t,n,i){const r=this.resolveListContext(e);if(!r)return!1;const s=at(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,g=this.host.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r.doc,e.block);return this.host.transact(()=>{const d=l.length,u=Math.min(t,d-c);if(u>0)if(this.host.suggestingMode&&!g){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=z(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),g=l.get(i);if(!(c instanceof S.XmlElement)||!(g instanceof S.XmlElement))return!1;let d=!1;return this.host.transact(()=>{const u=[];for(let h=0;h<g.length;h++){const f=g.get(h);if(f instanceof S.XmlElement&&f.nodeName==="list-item"){const m=new S.XmlElement("list-item");m.setAttribute("id",Y());const y=f.getAttribute("checked");e.variant==="todo"&&m.setAttribute("checked",y??"false");const b=f.getAttribute("indentLevel");b!==void 0&&m.setAttribute("indentLevel",b);const k=te(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=ee(x);let T=0;A.forEach(E=>{typeof E.insert=="string"&&(I.insert(T,E.insert,E.attributes||{}),T+=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=g.getAttribute("id")||t.id;p&&this.host.listStartNumberCache.delete(p),d=!0}),d?(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 g=n.children[c].children.filter(d=>d.type==="text").reduce((d,u)=>d+u.text.length,0);if(i<=g){r=c;break}if(i-=g,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 g=c-l;if(g>0&&(t===0||(a.children[t-1].indentLevel??0)<c-1))return!1;const d=[],u=this.host.suggestingMode?this.host.suggestionEngine.cloneSuggestionSnapshot(a):null,p=this.host.suggestingMode?le():null;if(g!==0)for(let m=t+1;m<a.children.length;m++){const y=a.children[m].indentLevel??0;if(y<=l)break;if(g>0&&y+g>2)return!1;const b=Math.max(0,Math.min(2,y+g));d.push({index:m,newIndent:b})}this.host.beforeOperationSelection=i;const h=Qe().getHandlerForBlock(e);this.host.beforeOperationRelativeSelection=h?.allowsInternalCursor()?z(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 b=0;b<f.length;b++){const k=f.get(b);k instanceof S.XmlElement&&k.nodeName==="list-item"&&m.push(k)}const y=m[t];y&&(c>0?y.setAttribute("indentLevel",String(c)):y.removeAttribute("indentLevel"),p&&(this.host.suggestionEngine.clearElementStructuralSuggestion(y),this.host.suggestionEngine.setElementStructuralSuggestion(y,"change",void 0,p,g>0?"Indent":"Outdent")),d.forEach(({index:b,newIndent:k})=>{const I=m[b];I&&(k>0?I.setAttribute("indentLevel",String(k)):I.removeAttribute("indentLevel"),p&&(this.host.suggestionEngine.clearElementStructuralSuggestion(I),this.host.suggestionEngine.setElementStructuralSuggestion(I,"change",void 0,p,g>0?"Indent":"Outdent")))}),this.host.suggestingMode&&p&&u&&this.host.suggestionEngine.saveLiveSuggestion({id:p,type:"block-change",blockId:e.id,beforeBlock:u,label:g>0?"Indent":"Outdent"}))}),this.host.setSelectionAfterOperation(r),this.host.afterOperationRelativeSelection=h?.allowsInternalCursor()?z(r,this.host.ydoc,this.host.getDocument()):null,!0)}}function Lu(o,e){const t=ee(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?[]:qn(t,n).diffs)l===-1?o.delete(i,c.length):(l===1&&ne(o,i,c),i+=c.length);const r=ee(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 g=e[s],d=Math.min(c,g.text.length-a),u=g.marks??{},p=l.attributes??{},h={};for(const f of new Set([...Object.keys(u),...Object.keys(p)])){const m=u[f];JSON.stringify(m)!==JSON.stringify(p[f])&&(h[f]=m??null)}Object.keys(h).length&&ie(o,i,d,h),i+=d,a+=d,c-=d}}}function Ur(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 Cr(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 g=o.get(c);(!(g instanceof S.XmlElement)||!l.has(g))&&o.delete(c,1)}e.children.forEach((c,g)=>{const d=r.get(g);if(!d){o.insert(g,[ye(c)]);return}An(d,c);const u=d.toArray().find(h=>h instanceof S.XmlText);u&&Lu(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);te(d,"_emptyTextMarks")!==h&&d.setAttribute("_emptyTextMarks",h)}else q(d,"_emptyTextMarks")})}const Nu=300;function Ou(o){return Array.from(o).slice(0,Nu).join("")}function Ru(o){return o.children.every(e=>e.type==="paragraph"&&e.children.every(t=>t.type==="text"&&t.text.trim().length===0))}class zr 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 gi{constructor(){this.afterIdChain=new Map,this.currentTurnId=""}startNewTurn(){const e="turn_"+Date.now();this.afterIdChain.clear(),this.currentTurnId=e}getChainedAfterId(e){return e?this.afterIdChain.get(e)||e:null}updateChain(e,t){this.afterIdChain.set(e,t)}hasChain(e){return this.afterIdChain.has(e)}getCurrentTurnId(){return this.currentTurnId}reset(){this.afterIdChain.clear(),this.currentTurnId=""}}function Ea(o){return o.replace(/\s+id="[^"]*"/g,"")}function $a(o){const e=Ea(o),t=e.match(/^<p\b([^>]*)>([\s\S]*)<\/p>$/i);return t?t[1].trim().length>0?e:t[2]:e}function La(o){return Z.toInternalHtml({type:"doc",children:[o]})}function Du(o,e,t,n){if(!o.actions)return o;const i=o.actions.map((c,g)=>{const d=y=>{throw new zr(g,c,new Error(y))};if(c.name==="replace_block"&&(typeof c.arguments.id!="string"||!c.arguments.id.trim())&&d('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"&&d("insert_block position must be before or after."),typeof u=="string"&&u.trim())return c;if(!n||!Ru(n))return d("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??Qt}},m=Be(c);return m&&Se(f,m),f}),r=t||new gi;`${o.actions.length}${e}${r.getCurrentTurnId()}`;const s=[],a=n?Z.createParsingContext(n):void 0,l=(c,g,d)=>{try{const u=g.name==="insert_block"?g.arguments.referenceId:g.name==="replace_block"?g.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 Z.fromAgentHtml(c,{existingDocument:n,parsingContext:a,preserveImageReferenceIds:!0,listItemBaseIndent:h?h.indentLevel??0:void 0})}catch(u){throw new zr(d,g,u)}};for(const[c,g]of i.entries()){const d=Be(g);if(g.name==="insert_block"){const{referenceId:u,position:p,content:h}=g.arguments;let f=u;const m=p;if(p==="after"&&r.hasChain(u)){const k=r.getChainedAfterId(u);k&&(f=k)}const y=Z.coalesceAdjacentBareListFragments(Array.isArray(h)?h:[h]),b=[];for(const k of y){const I=l(k,g,c);if(I.children.length!==0)if(I.children.length===1){const v=Y();Se(g,{stableId:v});const x=I.children[0];let A;x.type==="list"||x.type==="table"||x.type==="page-break"||x.type,A=Ea(Z.toInternalHtml(I)),b.push({content:A,id:v})}else for(let v=0;v<I.children.length;v++){const x=I.children[v],A=La(x);let T;x.type==="list"||x.type==="table"||x.type==="page-break"||x.type==="toc"?T=A:T=$a(A);const E=Y();b.push({content:T,id:E})}}for(let k=0;k<b.length;k++){const{content:I,id:v}=b[k],x={name:"insert_block",arguments:{}};k===0?(x.arguments.referenceId=f,x.arguments.position=m,Se(x,{stableId:b[k].id})):(x.arguments.referenceId=b[k-1].id,x.arguments.position="after"),x.arguments.content=[I],Se(x,{...d,stableId:v}),s.push(x)}if(p==="after"&&b.length>0){const k=b[b.length-1].id;r.updateChain(u,k)}}else if(g.name==="replace_block"){const{id:u,content:p,count:h}=g.arguments,f=Z.coalesceAdjacentBareListFragments(Array.isArray(p)?p:[p]),m=[];for(const y of f){const b=l(y,g,c);if(b.children.length===0)m.push({content:y,id:u,type:"paragraph"});else for(const k of b.children){const I=La(k),v=m.length===0?u:Y();m.push({content:I,id:v,type:k.type})}}if(m.length<=1){const y={...g,arguments:{...g.arguments,content:m.length>0?[m[0].content]:f}};d&&Se(y,d),s.push(y)}else{const y={name:"replace_block",arguments:{id:u,...typeof h=="number"?{count:h}:{},content:[m[0].content]}};Se(y,{...d,allowNoopContinuation:!0,splitReplacementGroup:m[0].id,multiBlockReplace:{replacementBlockIds:m.map(b=>b.id),replacedCount:typeof h=="number"?h:1}}),s.push(y);for(let b=1;b<m.length;b++){const{content:k,id:I,type:v}=m[b];let x;v==="list"||v==="table"||v==="code"||v==="page-break"||v==="toc"?x=k:x=$a(k);const A={name:"insert_block",arguments:{referenceId:b===1?u:m[b-1].id,position:"after",content:[x]}};Se(A,{...d,stableId:I,splitReplacementGroup:m[0].id}),s.push(A)}m.length>1&&r.updateChain(u,m[m.length-1].id)}}else s.push(g)}return{...o,actions:s}}const _u=Math.floor,ju=(o,e)=>o<e?o:e,Xu=(o,e)=>o>e?o:e,Na=128,di=127,Uu=Number.MAX_SAFE_INTEGER,zu=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},on=typeof TextEncoder<"u"?new TextEncoder:null,Hu=o=>on.encode(o),Wu=on?Hu:zu;let sn=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});sn&&sn.decode(new Uint8Array).length===1&&(sn=null);const ui=(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},hi=(o,e)=>{for(;e>di;)ui(o,Na|di&e),e=_u(e/128);ui(o,di&e)},Hr=new Uint8Array(3e4),Yu=Hr.length/3,qu=(o,e)=>{if(e.length<Yu){const t=on.encodeInto(e,Hr).written||0;hi(o,t);for(let n=0;n<t;n++)ui(o,Hr[n])}else Gu(o,Wu(e))},Ju=(o,e)=>{const t=unescape(encodeURIComponent(e)),n=t.length;hi(o,n);for(let i=0;i<n;i++)ui(o,t.codePointAt(i))},Ku=on&&on.encodeInto?qu:Ju,Vu=(o,e)=>{const t=o.cbuf.length,n=o.cpos,i=ju(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(Xu(t*2,r)),o.cbuf.set(e.subarray(i)),o.cpos=r)},Gu=(o,e)=>{hi(o,e.byteLength),Vu(o,e)},Oa=o=>new Error(o),Qu=Oa("Unexpected end of array"),Zu=Oa("Integer out of Range"),eh=(o,e)=>{const t=new Uint8Array(o.arr.buffer,o.pos+o.arr.byteOffset,e);return o.pos+=e,t},th=o=>eh(o,Wr(o)),Ra=o=>o.arr[o.pos++],Wr=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&di)*t,t*=128,i<Na)return e;if(e>Uu)throw Zu}throw Qu},nh=o=>{let e=Wr(o);if(e===0)return"";{let t=String.fromCodePoint(Ra(o));if(--e<100)for(;e--;)t+=String.fromCodePoint(Ra(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))}},ih=o=>sn.decode(th(o)),Da=sn?ih:nh;var an;(function(o){o[o.Token=0]="Token",o[o.PermissionDenied=1]="PermissionDenied",o[o.Authenticated=2]="Authenticated"})(an||(an={}));const rh=(o,e)=>{hi(o,an.Token),Ku(o,e)},oh=(o,e,t)=>{switch(Wr(o)){case an.PermissionDenied:{e(Da(o));break}case an.Authenticated:{t(Da(o));break}}},_a=o=>Array.from(o.entries()).map(([e,t])=>({clientId:e,...t}));var Yr;(function(o){o[o.Connecting=0]="Connecting",o[o.Open=1]="Open",o[o.Closing=2]="Closing",o[o.Closed=3]="Closed"})(Yr||(Yr={}));function sh(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 qr(o){return new Promise(e=>setTimeout(e,o))}function ah(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 lh(o,e){const t=sh(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||ah;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 qr(c),r()};return n.attemptsRemaining>0&&n.attemptsRemaining--,t.timeout?new Promise((l,c)=>{const g=setTimeout(()=>{if(t.handleTimeout)try{l(t.handleTimeout(n,t))}catch(d){c(d)}else{const d=new Error(`Retry timeout (attemptNum: ${n.attemptNum}, timeout: ${t.timeout})`);d.code="ATTEMPT_TIMEOUT",c(d)}},t.timeout);o(n,t).then(d=>{clearTimeout(g),l(d)}).catch(d=>{clearTimeout(g),a(d).then(l).catch(c)})}):o(n,t).catch(a)}const s=t.calculateDelay?t.calculateDelay(n,t):t.initialDelay;if(s&&await qr(s),n.attemptNum<1&&t.initialJitter){const a=i(n,t);a&&await qr(a)}return r()}const ja=Math.floor,ch=(o,e)=>o<e?o:e,gh=(o,e)=>o>e?o:e,dh=64,fi=128,uh=63,ln=127,Xa=Number.MAX_SAFE_INTEGER,hh=()=>new Set,fh=Array.from,ph=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},cn=typeof TextEncoder<"u"?new TextEncoder:null,mh=o=>cn.encode(o),bh=cn?mh:ph;let gn=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});gn&&gn.decode(new Uint8Array).length===1&&(gn=null);class yh{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Jr=()=>new yh,Ua=o=>{let e=o.cpos;for(let t=0;t<o.bufs.length;t++)e+=o.bufs[t].length;return e},Kr=o=>{const e=new Uint8Array(Ua(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},pi=(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},Te=(o,e)=>{for(;e>ln;)pi(o,fi|ln&e),e=ja(e/128);pi(o,ln&e)},Vr=new Uint8Array(3e4),kh=Vr.length/3,Sh=(o,e)=>{if(e.length<kh){const t=cn.encodeInto(e,Vr).written||0;Te(o,t);for(let n=0;n<t;n++)pi(o,Vr[n])}else jt(o,bh(e))},Ih=(o,e)=>{const t=unescape(encodeURIComponent(e)),n=t.length;Te(o,n);for(let i=0;i<n;i++)pi(o,t.codePointAt(i))},Ke=cn&&cn.encodeInto?Sh:Ih,vh=(o,e)=>{const t=o.cbuf.length,n=o.cpos,i=ch(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(gh(t*2,r)),o.cbuf.set(e.subarray(i)),o.cpos=r)},jt=(o,e)=>{Te(o,e.byteLength),vh(o,e)},za=o=>new Error(o),Ha=za("Unexpected end of array"),Wa=za("Integer out of Range");class xh{constructor(e){this.arr=e,this.pos=0}}const Ya=o=>new xh(o),Ah=(o,e)=>{const t=new Uint8Array(o.arr.buffer,o.pos+o.arr.byteOffset,e);return o.pos+=e,t},mi=o=>Ah(o,xt(o)),qa=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&ln)*t,t*=128,i<fi)return e;if(e>Xa)throw Wa}throw Ha},wh=o=>{let e=o.arr[o.pos++],t=e&uh,n=64;const i=(e&dh)>0?-1:1;if((e&fi)===0)return i*t;const r=o.arr.length;for(;o.pos<r;){if(e=o.arr[o.pos++],t=t+(e&ln)*n,n*=128,e<fi)return i*t;if(t>Xa)throw Wa}throw Ha},Th=o=>{let e=xt(o);if(e===0)return"";{let t=String.fromCodePoint(qa(o));if(--e<100)for(;e--;)t+=String.fromCodePoint(qa(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))}},Ch=o=>gn.decode(mi(o)),dn=gn?Ch:Th,Ph=o=>{const e=o.pos,t=dn(o);return o.pos=e,t},Xt=Date.now,Gr=()=>new Map,Bh=(o,e,t)=>{let n=o.get(e);return n===void 0&&o.set(e,n=t()),n};class Fh{constructor(){this._observers=Gr()}on(e,t){Bh(this._observers,e,hh).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 fh((this._observers.get(e)||Gr()).values()).forEach(n=>n(...t))}destroy(){this._observers=Gr()}}const Mh=Object.keys,Ja=o=>Mh(o).length,Eh=(o,e)=>Object.prototype.hasOwnProperty.call(o,e),$h=(o,e)=>o===e,un=(o,e)=>{if(o==null||e==null)return $h(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)||!un(o.get(t),e.get(t)))return!1;break}case Object:if(Ja(o)!==Ja(e))return!1;for(const t in o)if(!Eh(o,t)||!un(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(!un(o[t],e[t]))return!1;break;default:return!1}return!0},Qr=3e4;class Lh extends Fh{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const t=Xt();this.getLocalState()!==null&&Qr/2<=t-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const n=[];this.meta.forEach((i,r)=>{r!==this.clientID&&Qr<=t-i.lastUpdated&&this.states.has(r)&&n.push(r)}),n.length>0&&bi(this,n,"timeout")},ja(Qr/10)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,n=this.meta.get(t),i=n===void 0?0:n.clock+1,r=this.states.get(t);e===null?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:i,lastUpdated:Xt()});const s=[],a=[],l=[],c=[];e===null?c.push(t):r==null?e!=null&&s.push(t):(a.push(t),un(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 bi=(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:Xt()})}n.push(r)}}n.length>0&&(o.emit("change",[{added:[],updated:[],removed:n},t]),o.emit("update",[{added:[],updated:[],removed:n},t]))},Zr=(o,e,t=o.states)=>{const n=e.length,i=Jr();Te(i,n);for(let r=0;r<n;r++){const s=e[r],a=t.get(s)||null,l=o.meta.get(s).clock;Te(i,s),Te(i,l),Ke(i,JSON.stringify(a))}return Kr(i)},Nh=(o,e,t)=>{const n=Ya(e),i=Xt(),r=[],s=[],a=[],l=[],c=xt(n);for(let g=0;g<c;g++){const d=xt(n);let u=xt(n);const p=JSON.parse(dn(n)),h=o.meta.get(d),f=o.states.get(d),m=h===void 0?0:h.clock;(m<u||m===u&&p===null&&o.states.has(d))&&(p===null?d===o.clientID&&o.getLocalState()!=null?u++:o.states.delete(d):o.states.set(d,p),o.meta.set(d,{clock:u,lastUpdated:i}),h===void 0&&p!==null?r.push(d):h!==void 0&&p===null?l.push(d):p!==null&&(un(p,f)||a.push(d),s.push(d)))}(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 Ka{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 eo{constructor(e){this.data=e,this.encoder=Jr(),this.decoder=Ya(new Uint8Array(this.data))}peekVarString(){return Ph(this.decoder)}readVarUint(){return xt(this.decoder)}readVarString(){return dn(this.decoder)}readVarUint8Array(){return mi(this.decoder)}writeVarUint(e){return Te(this.encoder,e)}writeVarString(e){return Ke(this.encoder,e)}writeVarUint8Array(e){return jt(this.encoder,e)}length(){return Ua(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 Me;(function(o){o.Connecting="connecting",o.Connected="connected",o.Disconnected="disconnected"})(Me||(Me={}));class At{constructor(){this.encoder=Jr()}get(e){return e.encoder}toUint8Array(){return Kr(this.encoder)}}class Oh extends At{constructor(){super(...arguments),this.type=ve.CLOSE,this.description="Ask the server to close the connection"}get(e){return Ke(this.encoder,e.documentName),Te(this.encoder,this.type),this.encoder}}class Rh extends Ka{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=Me.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===Me.Disconnected&&this.shouldConnect&&this.connect(),this.receivedOnOpenPayload&&this.status===Me.Connected&&e.onOpen(this.receivedOnOpenPayload)}detach(e){this.configuration.providerMap.has(e.configuration.name)&&(e.send(Oh,{documentName:e.configuration.name}),this.configuration.providerMap.delete(e.configuration.name))}setConfiguration(e={}){this.configuration={...this.configuration,...e}}async connect(){if(this.status===Me.Connected)return;this.cancelWebsocketRetry&&(this.cancelWebsocketRetry(),this.cancelWebsocketRetry=void 0),this.receivedOnOpenPayload=void 0,this.shouldConnect=!0;const e=()=>{let i=!1;return{retryPromise:lh(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=Me.Connecting,this.emit("status",{status:Me.Connecting}),this.connectionAttempt={resolve:e,reject:t}})}onMessage(e){var t;this.resolveConnectionAttempt(),this.lastMessageReceived=Xt();const n=new eo(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=Me.Connected,this.emit("status",{status:Me.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===Me.Connected&&this.lastMessageReceived&&(this.configuration.messageReconnectTimeout>=Xt()-this.lastMessageReceived||(this.closeTries+=1,this.closeTries>2?(this.onClose({event:{code:4408,reason:"forced"}}),this.closeTries=0):((e=this.webSocket)===null||e===void 0||e.close(),this.messageQueue=[])))}get serverUrl(){for(;this.configuration.url[this.configuration.url.length-1]==="/";)return this.configuration.url.slice(0,this.configuration.url.length-1);return this.configuration.url}get url(){return this.serverUrl}disconnect(){if(this.shouldConnect=!1,this.webSocket!==null)try{this.webSocket.close(),this.messageQueue=[]}catch(e){console.error(e)}}send(e){var t;((t=this.webSocket)===null||t===void 0?void 0:t.readyState)===Yr.Open?this.webSocket.send(e):this.messageQueue.push(e)}onClose({event:e}){this.closeTries=0,this.cleanupWebSocket(),this.connectionAttempt&&this.rejectConnectionAttempt(),this.status=Me.Disconnected,this.emit("status",{status:Me.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 Va=0,to=1,Ga=2,Dh=(o,e)=>{Te(o,Va);const t=S.encodeStateVector(e);jt(o,t)},_h=(o,e,t)=>{Te(o,to),jt(o,S.encodeStateAsUpdate(e,t))},jh=(o,e,t)=>_h(e,t,mi(o)),Qa=(o,e,t)=>{try{S.applyUpdate(e,mi(o),t)}catch(n){console.error("Caught error while handling a Yjs update",n)}},Xh=(o,e)=>{Te(o,Ga),jt(o,e)},Uh=Qa,zh=(o,e,t,n)=>{const i=xt(o);switch(i){case Va:jh(o,e,t);break;case to:Qa(o,t,n);break;case Ga:Uh(o,t,n);break;default:throw new Error("Unknown message type")}return i};class Hh{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,wh(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=zh(n.decoder,n.encoder,e.document,e);t&&i===to&&(e.synced=!0)}applySyncStatusMessage(e,t){t&&e.decrementUnsyncedChanges()}applyAwarenessMessage(e){if(!e.awareness)return;const{message:t}=this;Nh(e.awareness,t.readVarUint8Array(),e)}applyAuthMessage(e){const{message:t}=this;oh(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(Zr(e.awareness,Array.from(e.awareness.getStates().keys())))}}class Wh{constructor(e,t={}){this.message=new e,this.encoder=this.message.get(t)}create(){return Kr(this.encoder)}send(e){e?.send(this.create())}}class Yh 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 Ke(this.encoder,e.documentName),Te(this.encoder,this.type),rh(this.encoder,e.token),this.encoder}}class Za 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");Ke(this.encoder,e.documentName),Te(this.encoder,this.type);let t;return e.states===void 0?t=Zr(e.awareness,e.clients):t=Zr(e.awareness,e.clients,e.states),jt(this.encoder,t),this.encoder}}class qh extends At{constructor(){super(...arguments),this.type=ve.Stateless,this.description="A stateless message"}get(e){var t;return Ke(this.encoder,e.documentName),Te(this.encoder,this.type),Ke(this.encoder,(t=e.payload)!==null&&t!==void 0?t:""),this.encoder}}class el 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 Ke(this.encoder,e.documentName),Te(this.encoder,this.type),Dh(this.encoder,e.document),this.encoder}}class Jh extends At{constructor(){super(...arguments),this.type=ve.Sync,this.description="A document update"}get(e){return Ke(this.encoder,e.documentName),Te(this.encoder,this.type),Xh(this.encoder,e.update),this.encoder}}class Kh extends Error{constructor(){super(...arguments),this.code=1001}}class Vh extends Ka{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 Lh(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:_a(this.awareness.getStates())})}),(n=this.awareness)===null||n===void 0||n.on("change",()=>{this.emit("awarenessChange",{states:_a(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 Rh({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(el,{document:this.document,documentName:this.configuration.name})}pageHide(){this.awareness&&bi(this.awareness,[this.document.clientID],"page hide")}registerEventListeners(){typeof window>"u"||!("addEventListener"in window)||window.addEventListener("pagehide",this.boundPageHide)}sendStateless(e){this.send(qh,{documentName:this.configuration.name,payload:e})}documentUpdateHandler(e,t){t!==this&&(this.incrementUnsyncedChanges(),this.send(Jh,{update:e,documentName:this.configuration.name}))}awarenessUpdateHandler({added:e,updated:t,removed:n},i){const r=e.concat(t).concat(n);this.send(Za,{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(Yh,{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(el,{document:this.document,documentName:this.configuration.name}),this.awareness&&this.awareness.getLocalState()!==null&&this.send(Za,{awareness:this.awareness,clients:[this.document.clientID],documentName:this.configuration.name})}send(e,t){if(!this._isAttached)return;const n=new Wh(e,t);this.emit("outgoingMessage",{message:n.message}),n.send(this.configuration.websocketProvider)}onMessage(e){const t=new eo(e.data),n=t.readVarString();t.writeVarString(n),this.emit("message",{event:e,message:new eo(e.data)}),new Hh(t).apply(this,!0)}onClose(){this.isAuthenticated=!1,this.synced=!1,this.awareness&&bi(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&&(bi(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 Kh(`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 tl=10,yi=(o,e,t)=>Math.max(e,Math.min(t,o));function hn(o){const e={};for(const[t,n]of Object.entries(o??{}))Ir.has(t)&&t!=="aiGenerated"&&t!=="__htmlClassName"||n==null||(e[t]=n);return JSON.stringify(e)}function fn(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 ki(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 nl(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||Ir.has(i)||i!=="footnoteRef"&&(i==="superscript"&&n||(t[i]=r));return Object.keys(t).length>0?t:void 0}const il=["spaceBefore","spaceAfter","contextualSpacing"];function pn(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 Gh(o,e,t=!1){for(const n of il){const i=te(o,n);i!=null?e.setAttribute(n,i):t&&q(e,n)}}function rl(o){if(!o)return{};if(typeof o=="string")try{return JSON.parse(o)}catch{return{}}return typeof o=="object"?{...o}:{}}function ol(o){const e=rl(o.getAttribute("_emptyTextMarks"));if(Object.keys(e).length===0)return!1;for(const t of Oo)delete e[t];return Object.keys(e).length===0?o.removeAttribute("_emptyTextMarks"):o.setAttribute("_emptyTextMarks",JSON.stringify(e)),!0}function sl(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=rl(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 Si(o,e){e&&Object.keys(e).length>0?o.setAttribute("_emptyTextMarks",JSON.stringify(e)):o.removeAttribute("_emptyTextMarks")}function Ii(o){return o.children.some(e=>e.type==="text"&&e.text.length>0)}function mn(o,e,t,n){if(!Ii(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=vo(o,t);return ct(i?.marks)}const bn=o=>o?.type==="code"||o?.type==="math",Ut=o=>{if(!o||o.type!=="code")return!1;const e=o.language?.trim().toLowerCase();return e==="latex"||e==="latex-inline"},Ee="Arial, sans-serif";function al(o){if(o==null)return;const e=Number.parseFloat(o);return Number.isFinite(e)?e:void 0}function ll(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")&&ll(t,e)}}const cl=o=>o.name==="set_title"||o.name==="set_notes"||o.name==="set_page_layout"||o.name==="set_header_footer",Qh=o=>`${o} ${o===1?"proposal":"proposals"}`;function $e(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=>$e(t)).filter(t=>t.length>0).join(e)}return""}function gl(o){const e=o.replace(/\s+/g," ").trim();return e.length===0?[]:e.split(" ")}function Zh(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 ef(o,e){const t=gl(o),n=gl(e),i=Math.max(t.length,n.length);if(i===0)return null;const r=Zh(t,n),s=Math.max(0,i-r);return Math.round(s/i*100)}function tf(o,e,t){const n=X(o,t),i=X(e,t);if(!n||!i)return null;const r=$e(n),s=$e(i);return ef(r,s)}function dl(o,e,t,n,i){if(!o||!e||t.length===0)return o;const r=e.filter(d=>!cl(d));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=[Qh(t.length)],c=tf(n,i,a);c!==null&&l.push(`~${c}% words changed`);const g=o.trim();return g.endsWith(".")?`${g.slice(0,-1)} (${l.join("; ")}).`:`${g} (${l.join("; ")}).`}function nf(o,e,t){if(t<=0)return[];const n=qe(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 rf(o,e){if(!e||e.length===0)return[];const t=[];for(const n of e){if(n.name!=="replace_block")continue;const i=Hc(n);if(!i||i.replacementBlockIds.length<=1||i.replacedCount<=1)continue;const r=n.arguments&&typeof n.arguments=="object"?n.arguments:void 0,s=typeof r?.id=="string"&&r.id.trim().length>0?r.id.trim():null;if(!s)continue;const a=nf(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 g=a[c],d=i.replacementBlockIds[c];!g||!d||t.push({currentBlockId:g,finalBlockId:d})}}return t}const ul=(o,e,t)=>{if(!o||!e)return;const n=o.filter(a=>!cl(a));if(n.length!==1){if(n.length===0){const a=o.some(d=>d.name==="set_title"),l=o.some(d=>d.name==="set_notes"),c=o.some(d=>d.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 d=o.find(u=>u.name==="set_title")?.arguments?.title;return d?`Title set to "${d}".`:"Title set."}if(l)return"Notes updated.";if(c)return"Page layout updated.";const g=o.find(d=>d.name==="set_header_footer");if(g){const d=g.arguments?.side==="footer"?"Footer":"Header";return g.arguments?.clear?`${d} removed.`:`${d} 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(d=>d.name==="insert_block").map(d=>Un(d)).filter(d=>typeof d=="string"&&d.length>0);if(a.length===0)return;const l=a.length,c=a[0],g=a[a.length-1];return l===1?`Inserted block ${c}.`:`Inserted ${l} blocks; first inserted block ID was ${c}; last inserted block ID was ${g}.`}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=>Un(u)).filter(u=>typeof u=="string"&&u.length>0),g=1+c.length,d=c.length>0?c[c.length-1]:l;return g===1?`Replaced block ${l}.`:`Inserted ${g} blocks; first inserted block ID was ${l}; last inserted block ID was ${d}.`}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,g=s(a);return c==="toggle"?`Toggled ${l} on ${g}.`:c==="remove"?`Removed ${l} from ${g}.`:`Updated ${l} on ${g}.`}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,g)=>c+g,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:g}=i.arguments,d=r.find(u=>u.kind==="insert"&&u.paragraphId===a);return d?.text?`${d.text} in table ${a}.`:`Inserted 1 row ${g} 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}.`}},hl=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,y,b)=>{if(this.disposed)return;m!==yo&&m!==sa&&this.canRepairIdentity()&&(this.classifyTransactionOrigin(m)==="local"?this.repairDocumentIdentity(b,m):this.scheduleDeferredIdentityRepair());const k=this.ydoc.share.get("agent-presence"),I=k&&b.changedParentTypes.size>0&&[...b.changedParentTypes.keys()].every(x=>x===k),v=this.classifyTransactionOrigin(m);I||(this.invalidateDerivedDocumentState(),this.cachedDoc=null,this.incrementalRefreshPending=!0),this.batchingUpdates?this.pendingUpdate=()=>this.onDocumentChange(this.getDocument(),{origin:v}):this.onDocumentChange(this.getDocument(),{origin:v})},this.suggestingMode=!1,this.liveSuggestionMetadataContext=null,this.defaultHumanAuthorName=null,this.liveSuggestionTreeRecordCache=new Map,this.lastPrunedUnresolvableLiveSuggestions=[],this.listOperations=new $u(this),this.suggestionEngine=new yn(this),this.cachedKernel=null,this.strandedObservers=!1,this.strandedCheck=null,this.identityRepairedOnConstruct=!1,this.deferredIdentityRepair=null,this.ydoc=i||Bi(e),oa(this.ydoc,Sr),this.canRepairIdentity=l?.canRepairIdentity??(()=>!0),!l?.deferIdentityRepair&&this.canRepairIdentity()&&this.repairDocumentIdentity()&&(this.identityRepairedOnConstruct=!0,e=fe(this.ydoc)),this.documentId=r||"default",this.onDocumentChange=t,this.onTitleChange=n,this.detachedSuggestionStore=new Br(this.ydoc,this.documentId,s),this.toolCallHistory=new xa,this.preprocessorSession=a||new gi,this.ensureParagraphIndentStorageUsesUnits(),this.cachedDoc=e,Ln(this.ydoc,e),this.documentSuggestionIdsCache=this.suggestionEngine.createDocumentSuggestionIdsCache(e);const c=this.ydoc.getXmlFragment("content"),g=this.ydoc.getXmlFragment("chrome"),d=this.ydoc.getXmlFragment("notes"),u=this.ydoc.getArray("annotations"),p=this.suggestionEngine.getLiveSuggestionStore(),h=this.ydoc.getMap("comments");this.undoManager=new S.UndoManager([c,g,d,u,p,h],{captureTimeout:1e3,trackedOrigins:this.trackedUndoOrigins}),this.ydoc.on("update",this.handleYDocUpdate),this.undoManager.on("stack-item-added",f=>{this.isRedoing?(this.currentSelectionBeforeRedo&&f.stackItem.meta.set("beforeSelection",this.currentSelectionBeforeRedo),this.afterSelectionForRedo&&f.stackItem.meta.set("afterSelection",this.afterSelectionForRedo),this.currentSelectionBeforeRedo=null,this.afterSelectionForRedo=null,this.isRedoing=!1):(this.beforeOperationRelativeSelection?f.stackItem.meta.set("beforeSelection",this.beforeOperationRelativeSelection):this.beforeOperationSelection&&f.stackItem.meta.set("beforeSelectionAbsolute",this.beforeOperationSelection),this.afterOperationRelativeSelection&&f.stackItem.meta.set("afterSelection",this.afterOperationRelativeSelection),this.beforeOperationSelection&&f.stackItem.meta.set("beforeSelectionAbsolute",this.beforeOperationSelection)),this.beforeOperationRelativeSelection=null,this.afterOperationRelativeSelection=null}),this.undoManager.on("stack-item-popped",f=>{if(f.type==="undo"){const m=this.undoManager.redoStack;if(m.length>0&&f.stackItem.meta.size>0){const y=m[m.length-1];f.stackItem.meta.forEach((b,k)=>{y.meta.set(k,b)})}}})}invalidateDerivedDocumentState(){this.derivedDocumentRevision+=1,this.liveSuggestionIdsCache=null,this.liveSuggestionIdsBySourceCache.clear(),this.inlineSuggestionMetadataCache.clear(),this.inlineSuggestionKindCache.clear(),this.canResolveLiveSuggestionCache.clear();for(const e of this.liveSuggestionProjectionCache.values())e.projection.ydoc.destroy();this.liveSuggestionProjectionCache.clear(),this.documentSuggestionIdsCache=null,this.liveSuggestionTreeRecordCache.clear()}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 ko(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 Vh?"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===Ee||(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 g of xn)this.formattingMarkValuesEqual(l?.[g],c?.[g])||n.add(g)}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(g=>typeof g=="string"&&g.length>0))),i=new Set(n),r=this.getDocument(),s=qe(r),a=qe(t),l=new Map;for(const g of[s,a])for(const{block:d}of g.values())if(d.type==="list")for(const u of d.children)l.set(u.id,d.id);const c=(g,d)=>{let u=Je(g,d);for(;u&&u.type!=="doc";){if(u.id)return u.id;u=Je(g,u.id)}return null};return n.filter(g=>{const d=l.get(g);if(d&&i.has(d))return!1;const u=[s.get(g),a.get(g)];let p=!1;for(const f of u)if(f&&(p=!0,f.containerPath.some(m=>m!==g&&i.has(m))))return!1;if(p)return!0;let h=g;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=ee(e);let a=0;for(const l of s){if(typeof l.insert!="string")continue;const c=a,g=a+l.insert.length,d=Math.max(t,c),u=Math.min(r,g);if(d<u&&i.push({start:d,length:u-d,attributes:{...l.attributes||{}}}),a=g,a>=r)break}return i}normalizeAdjacentManualReplacementOrder(e,t){const n=[];let i=0;for(const h of ee(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),g=l.filter(h=>h.attributes.deletion);if(c.length===0||g.length===0)return null;const d=l[0].start,u=l[l.length-1].end-d;e.delete(d,u);let p=d;for(const h of[...g,...c])ne(e,p,h.text,h.attributes),p+=h.text.length;return{regionStart:d,insertionLength:c.reduce((h,f)=>h+f.text.length,0),deletionLength:g.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",g=l>0?a:s,d=l>0?s:a;let u=0;for(;u<d.length&&g[u]?.id===d[u]?.id;)u++;for(let p=u;p<d.length;p++)if(g[p+1]?.id!==d[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=z(n,this.ydoc,r),this.transact(()=>{this.replaceBlockByIdWithoutSelection(e,t,s)}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=z(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:g}=e.listItemSuggestion;if(l==="insert")t==="accept"?a.children[s]=this.suggestionEngine.cloneSuggestionSnapshot(g??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"?g??a.children[s]:c;if(!u)return!1;a.children[s]=this.suggestionEngine.cloneSuggestionSnapshot(u)}const d=this.suggestionEngine.runWithoutSuggesting(()=>this.replaceAnyBlockById(e.blockId,a,n,n));return d&&this.suggestionEngine.deleteLiveSuggestion(e.id),d}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 zt(this.ydoc)}getYChromeFragment(){if(!this.ydoc)throw new Error("No Y.Doc");return this.ydoc.getXmlFragment("chrome")}getYNotesFragment(){if(!this.ydoc)throw new Error("No Y.Doc");return this.ydoc.getXmlFragment("notes")}getYBlockContext(e,t){if(!e.length)return null;const n=this.getYContentFragment(),i=e[0];if(i<0||i>=n.length)return null;const r=n.get(i);return r instanceof S.XmlElement?{parent:n,index:i,yBlock:r}:null}getYParagraphContext(e,t){const n=this.getYBlockContext(e,t);if(!n)return null;for(let i=0;i<n.yBlock.length;i++){const r=n.yBlock.get(i);if(r instanceof S.XmlText)return{yBlock:n.yBlock,yText:r}}return null}getEmptyTextMarksForParagraph(e){const t=this.getYBlockContext(e);if(!t)return;const n=t.yBlock.getAttribute("_emptyTextMarks");if(n)try{return typeof n=="string"?JSON.parse(n):n}catch(i){console.warn("Failed to parse _emptyTextMarks",i);return}}getEmptyTextMarksForBlockId(e){const t=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?z(t,this.ydoc,e):null}getDocument(){return this.cachedDoc||(this.cachedDoc=this.incrementalRefreshPending?He(this.ydoc):fe(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],g=l[0];return c?.type==="text"&&g?.type==="text"&&JSON.stringify(c.marks||{})===JSON.stringify(g.marks||{})&&(c.text+=g.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=ke(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=ko(i,a.block)?.block??(i.notes??[]).find(p=>p.children.some(h=>h.id===a.block));if(u){const p=u.children.map(m=>m.id),h=p.indexOf(a.block),f=p.indexOf(l.block);if(h!==-1&&f!==-1){const[m,y]=h<=f?[h,f]:[f,h],b=[];for(let k=m;k<=y;k++){const I=u.children[k];if(!I.id)continue;const v=k===h?a:{block:I.id,offset:0},x=k===f?l:{block:I.id,offset:Number.MAX_SAFE_INTEGER};b.push(...this.collectSingleBlockFormattingRange({block:I.id,offset:k===h?v.offset:0},{block:I.id,offset:k===f?x.offset:Number.MAX_SAFE_INTEGER},i))}return b}}}const c=ut(i,a.block),g=ut(i,l.block);if(!c||!g){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 d=!0;for(const{block:u,path:p}of xo(i)){const h=Pt(p,c),f=Pt(p,g);if(h<0)continue;if(f>0)break;const m=f===0,y=G(this.ydoc,u.id);if(!y){d=!1;continue}const b=y.yBlock;if(u.type==="paragraph"){const k=oe(b);if(!k){d=!1;continue}let I=0,v=k.length;d&&a.block===u.id&&(I=a.offset),m&&l.block===u.id&&(v=l.offset),I=yi(I,0,k.length),v=yi(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}),d=!1;continue}if(u.type==="list"){const k=u,I=[];for(let F=0;F<b.length;F++){const B=b.get(F);B instanceof S.XmlElement&&B.nodeName==="list-item"&&I.push(B)}const v=Math.min(k.children.length,I.length);if(v===0){d=!1;continue}let x=0,A=v-1,T=0,E=Number.MAX_SAFE_INTEGER;if(d&&a.block===u.id){const F=this.listOperations.getListCursorInfo(k,a);F&&(x=Math.min(F.itemIndex,v-1),T=F.offsetInItem)}if(m&&l.block===u.id){const F=this.listOperations.getListCursorInfo(k,l);F&&(A=Math.min(F.itemIndex,v-1),E=F.offsetInItem)}for(let F=x;F<=A;F++){const B=I[F];if(!B)continue;const P=oe(B);if(!P||P.length===0)continue;let w=0,C=P.length;F===x&&(w=Math.min(T,P.length)),F===A&&(C=Math.min(E,P.length)),C>w&&r.push({yText:P,start:w,end:C})}d=!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=oe(a);if(!l)return i;let c=e.offset,g=t.offset;c=yi(c,0,l.length),g=yi(g,0,l.length);const d=Math.min(c,g),u=Math.max(c,g);u>d&&i.push({yText:l,start:d,end:u,blockId:r.id})}else if(r.type==="list"){const l=r,c=[];for(let y=0;y<a.length;y++){const b=a.get(y);b instanceof S.XmlElement&&b.nodeName==="list-item"&&c.push(b)}const g=Math.min(l.children.length,c.length);if(g===0)return i;const d=this.listOperations.getListCursorInfo(l,e),u=this.listOperations.getListCursorInfo(l,t);if(!d||!u)return i;let p=Math.min(d.itemIndex,g-1),h=Math.min(u.itemIndex,g-1),f=d.offsetInItem,m=u.offsetInItem;p>h&&([p,h]=[h,p],[f,m]=[m,f]);for(let y=p;y<=h;y++){const b=c[y];if(!b)continue;const k=oe(b);if(!k||k.length===0)continue;let I=0,v=k.length;y===p&&(I=Math.min(f,k.length)),y===h&&(v=Math.min(m,k.length)),v>I&&i.push({yText:k,start:I,end:v,blockId:r.id,itemIndex:y})}}return i}collectParagraphBlockIdsInRange(e,t,n){const i=[],r=new Set,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=ke(n,e,t)<=0,l=a?e:t,c=a?t:e,g=ut(n,l.block),d=ut(n,c.block);if(!g||!d)return s(l.block),s(c.block),i;for(const{block:u,path:p}of xo(n)){const h=Pt(p,g),f=Pt(p,d);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?ol(c.yBlock):!1}if(n.type!=="list")return!1;const i=n;this.suggestingMode&&this.suggestionEngine.cloneSuggestionSnapshot(i),this.suggestingMode&&le();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 g=r.yBlock.get(c);g instanceof S.XmlElement&&g.nodeName==="list-item"&&a.push(g)}const l=a[s.itemIndex];return l?ol(l):!1}updateEmptyTextMarksAtPosition(e,t,n,i){const r=X(i,e.block);if(!r)return!1;if(r.type==="paragraph"){const d=G(this.ydoc,r.id);if(!d)return!1;const u=r.children.some(p=>p.type==="text"&&p.text.length>0);return sl(d.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 d=0;d<a.yBlock.length;d++){const u=a.yBlock.get(d);u instanceof S.XmlElement&&u.nodeName==="list-item"&&c.push(u)}const g=c[l.itemIndex];return g?sl(g,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(!bn(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 g={block:e.block,offset:c+t.length},d={anchor:g,focus:g};return this.setSelectionAfterOperation(d),this.afterOperationRelativeSelection=z(d,this.ydoc,this.getDocument()),!0}deleteTextInCodeBlock(e,t,n,i){this.beforeOperationSelection=n;const r=this.getDocument();this.beforeOperationRelativeSelection=z(n,this.ydoc,r);const s=X(r,e.block);if(!bn(s))return!1;const a=J(this.ydoc,e.block);if(!a)return!1;let l=null;for(let d=0;d<a.length;d++){const u=a.get(d);if(u instanceof S.XmlText){l=u;break}}if(!l)return!1;const c=l.length-e.offset,g=Math.min(t,c);return this.transact(()=>{l.delete(e.offset,g)}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=z(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=z(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=z(e,this.ydoc,t)}ensureParagraphIndentStorageUsesUnits(){const e=this.ydoc.getMap("metadata");if(e.get(Ge.paragraphIndentStorageVersion)===Ti)return;const t=this.ydoc.getXmlFragment("content");if(t.length===0&&Tt(this.ydoc))return;const n=e.get(Ge.indentStepPx),i=Ve({indentStepPx:typeof n=="number"?n:void 0}).indentStepPx;this.ydoc.transact(()=>{t.length>0&&ll(t,r=>{const s=Io(al(te(r,"leftIndent")),{indentStepPx:i,storedAsUnits:!1}),a=Io(al(te(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(Ge.paragraphIndentStorageVersion,Ti)},"indent-storage-migration")}setTitle(e){const t=Ou(e);this.transact(()=>{this.ydoc.getMap("metadata").set("title",t)}),this.onTitleChange&&this.onTitleChange(t)}setNotes(e){const t=typeof e=="string"?e:String(e??"");this.transact(()=>{const n=this.ydoc.getMap("metadata");t.length===0?n.delete("notes"):n.set("notes",t)})}getDocumentNotes(){const e=this.ydoc.getMap("metadata").get("notes");return typeof e=="string"?e:""}updateSectionBreakLayout(e,t){const n=this.getYContentFragment();let i=null;for(const r of n.toArray())if(r instanceof S.XmlElement&&r.nodeName==="section-break"&&r.getAttribute("id")===e){i=r;break}return i?(this.transact(()=>{i.setAttribute("layout",JSON.stringify(t))}),!0):!1}pinInheritedPageNumbering(e){const t=Ve(this.getPageLayoutSettings()),n=this.getDocument().children.filter(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(So(r,e)??e))}})}applySetHeaderFooterAction(e){const t=e.side==="footer"?"footer":"header",n=e.slot==="first"||e.slot==="even"?e.slot:"default";return{changed:Ud(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:Ul(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(P=>P.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 P=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:P}}if(e.pageNumberFormat!=null&&!Fi(e.pageNumberFormat))return{settings:n,pageless:this.getPagelessMode(),error:`pageNumberFormat must be one of ${zl.join(", ")}, got ${JSON.stringify(e.pageNumberFormat)}`};const a=s?i[s-1]:void 0,l=a?ho(n,a.layout):n,c=this.getPagelessMode(),g=Hl(e.preset)?Wl(e.preset):void 0,d={...g?.pageLayout??{}},u={...l,...g?.pageLayout??{}};Yl(e.pageSize)&&(u.pageSize=e.pageSize,d.pageSize=e.pageSize),(e.orientation==="portrait"||e.orientation==="landscape")&&(u.orientation=e.orientation,d.orientation=e.orientation);const p=ze(e.margin);p!==void 0&&(u.marginTopPx=p,u.marginRightPx=p,u.marginBottomPx=p,u.marginLeftPx=p,d.marginTopPx=p,d.marginRightPx=p,d.marginBottomPx=p,d.marginLeftPx=p);const h=ze(e.marginTop);h!==void 0&&(u.marginTopPx=h,d.marginTopPx=h);const f=ze(e.marginRight);f!==void 0&&(u.marginRightPx=f,d.marginRightPx=f);const m=ze(e.marginBottom);m!==void 0&&(u.marginBottomPx=m,d.marginBottomPx=m);const y=ze(e.marginLeft);y!==void 0&&(u.marginLeftPx=y,d.marginLeftPx=y);const b=ze(e.indentStep);b!==void 0&&(u.indentStepPx=b,d.indentStepPx=b);const k=ze(e.blockSpacing);k!==void 0&&(u.blockSpacingPx=k,d.blockSpacingPx=k),ql(e.columnCount)&&(u.columnCount=e.columnCount,d.columnCount=e.columnCount);const I=ze(e.columnGap);if(I!==void 0){const P=Math.max(0,ec(I));u.columnGapTwips=P,d.columnGapTwips=P}if((e.noteMode==="footnotes"||e.noteMode==="endnotes")&&this.convertAllNoteKinds(e.noteMode==="endnotes"?"endnote":"footnote"),typeof e.showPageNumbers=="boolean"||Mi(e.pageNumberPosition)){const P=Mi(e.pageNumberPosition)?e.pageNumberPosition:this.ydoc.getMap("metadata").get(Ge.pageNumberPosition)??"bottom-right",w=typeof e.showPageNumbers=="boolean"?e.showPageNumbers:!0;this.setPageNumberSlot(w,P)}if(typeof e.showPageNumbers=="boolean"&&(u.showPageNumbers=!1),Mi(e.pageNumberPosition)&&(u.pageNumberPosition=e.pageNumberPosition),typeof e.pageNumberStart=="number"?(u.pageNumberStart=e.pageNumberStart,d.pageNumberStart=e.pageNumberStart):e.pageNumberRestart===!0&&(d.pageNumberStart=a?.layout?.pageNumberStart??1),Fi(e.pageNumberFormat)&&(u.pageNumberFormat=e.pageNumberFormat,d.pageNumberFormat=e.pageNumberFormat),!a){const P=s===r&&r>1;e.pageNumberRestart===!0||P&&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,d.pageBorders=t),e.lineNumbering!==void 0){const P=Jl(e.lineNumbering);P?u.lineNumbering=P:delete u.lineNumbering,d.lineNumbering=Kl(P)??""}const v=ze(e.pageWidth),x=ze(e.pageHeight);if(v!==void 0&&x!==void 0){const P=Vl(v,x);P&&(u.pageSize=P.pageSize,u.orientation=P.orientation,d.pageSize=P.pageSize,d.orientation=P.orientation)}if(e.watermark!==void 0){const P=$o(e.watermark);this.transact(()=>{const w=this.ydoc.getMap("metadata");P?w.set("watermark",P):w.delete("watermark")})}const A=Ve(u),T=typeof e.pageless=="boolean"?e.pageless:g?.pageless??c,E=e.pageNumberRestart===!1&&typeof e.pageNumberStart!="number",F=P=>{const w=So(P,d)??{...d};if(!E)return w;const{pageNumberStart:C,...$}=w;return $},B=Object.keys(d).length>0||E;if(s&&a)B&&this.updateSectionBreakLayout(a.id,F(a.layout));else if(s===r){if(e.pageBorders!==void 0||e.clearPageBorders===!0)for(const P of i)P.layout?.pageBorders!==void 0||/<w:pgBorders\b/.test(P.layout?.oxmlSectPr??"")||this.updateSectionBreakLayout(P.id,{...P.layout,pageBorders:n.pageBorders??null});this.pinInheritedPageNumbering({...Fi(e.pageNumberFormat)?{pageNumberFormat:e.pageNumberFormat}:{},...typeof e.pageNumberStart=="number"?{pageNumberStart:e.pageNumberStart}:{}}),this.setPageLayoutSettings(A)}else{if(B)for(const P of i)this.updateSectionBreakLayout(P.id,F(P.layout));this.setPageLayoutSettings(A)}return this.setPagelessMode(T),{settings:A,pageless:T}}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 ee(p)){const m=typeof f.insert=="string"?f.insert.length:1,y=f.attributes??{};y.deletion&&i.has(y.suggestionId)?s.push({text:p,start:h,length:m,attributes:y}):y.insertion&&r.has(y.suggestionId)&&a.push({text:p,start:h,length:m,attributes:y}),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 g=1e7+Math.floor(Math.random()*9e7),d=`reviseMove-${n}`,u=(p,h,f)=>{const m=JSON.stringify({version:1,name:d,role:h,rangeId:`${g}${f}`,wrapperId:`${g+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 y of p)ie(y.text,y.start,y.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=Bi(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(fe(i),()=>{},void 0,i,"live-suggestion-projection",!0,new gi,{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){ai(this.kernel,e,t)}ensureHeaderFooterBlock(e,t){return da(this.kernel,e,t)}migrateLegacyHeaderFooterMetadata(){Dd(this.kernel)}migrateNotesOutOfContent(){tu(this.kernel)}migrateChromeOutOfContent(){Rd(this.kernel)}getHeadersAndFooters(){return xr(this.kernel)}setSectionHeadersAndFooters(e,t,n){Nd(this.kernel,e,t,n)}getSectionHeadersAndFooters(e){return Od(this.kernel,e)}setPageNumberSlot(e,t="bottom-right"){_d(this.kernel,e,t)}migrateLegacyPageNumbers(){jd(this.kernel)}setPageLayoutSettings(e){this.ensureParagraphIndentStorageUsesUnits(),this.transact(()=>{Gl(this.ydoc.getMap("metadata"),e)})}setWatermark(e){const t=$o(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 lo(this.ydoc.getMap("metadata"))??Ve(void 0)}getIndentStepPx(){return this.getPageLayoutSettings().indentStepPx??0}getTitle(){return this.ydoc.getMap("metadata").get("title")}transact(e){return this.assertObserversNotStranded(),this.incrementalRefreshPending=!1,this.cachedDoc=null,this.invalidateDerivedDocumentState(),this.ydoc.transact(e,this.origin)}assertObserversNotStranded(){if(this.strandedObservers)throw new Error("The editor lost sync with the document. Reload the page to continue editing.");this.hasQueuedCleanupsOutsideTransaction()&&!this.strandedCheck&&(this.strandedCheck=setTimeout(()=>{this.strandedCheck=null,!(this.disposed||!this.hasQueuedCleanupsOutsideTransaction())&&(this.strandedObservers=!0,Sr(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 g=c._item?.id;return g!==void 0&&g.client===i&&g.clock>=r}:void 0,a=Ql(this.ydoc,{transaction:e,shouldDrop:s});if(n&&a.droppedIds.length>0){const c=new Set(a.droppedIds),g=this.suggestionEngine.getLiveSuggestionStore(),d=[];for(const[u,p]of g._map){if(p.deleted||p.id.client!==i||p.id.clock<r)continue;const h=g.get(u);h&&this.suggestionEngine.liveSuggestionRecordTouchesAnyBlock(h,c)&&d.push(u)}d.length>0&&this.ydoc.transact(()=>{for(const u of d)this.suggestionEngine.deleteLiveSuggestion(u)},yo)}const l=Bd(this.ydoc,e,n?"strip":"recover");return a.duplicatesFound===0&&l===0?!1:(this.cachedDoc=null,this.incrementalRefreshPending=!1,Ln(this.ydoc,fe(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?Pr(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?z(e,this.ydoc,i):null,this.afterSelectionForRedo=n||null,this.isRedoing=!0,this.undoManager.redo(),n?Pr(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=z(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(bn(l))return this.insertTextInCodeBlock(e,t,n,i);if(l.type!=="paragraph")return!1;const c=l,g=this.listOperations.tryApplyParagraphListTrigger(c,e,t);if(g!==null)return g;const d={type:"text",text:t},u={},p=$i(r,e),h=Li(r,e),f=Ni(r,e,n),m=this.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(r,e),y=m?.marks?.suggestionId??null,b=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r,e.block),k=this.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(r,e,n),I=!b&&this.suggestingMode&&t.length>0,v=vr({inheritedMarks:f?.marks,emptyParagraphMarks:Ii(c)?void 0:this.getEmptyTextMarksForBlockId(e.block),exitingLink:p,exitingComment:h,suggestionMarks:I?this.suggestionEngine.buildSuggestionInsertionMarks(void 0,k??y??this.suggestionEngine.getSuggestionIdFromInheritedMarks(f?.marks),void 0,void 0,m?.marks??f?.marks):void 0});Object.assign(u,v.marksToApply),Object.keys(u).length>0&&(d.marks=u);const x=this.insertTextNodes(e,[d],n,k??void 0);if(x){const A={anchor:x,focus:x};this.setSelectionAfterOperation(A),this.afterOperationRelativeSelection=z(A,this.ydoc,this.getDocument())}return x!==null}insertFormattedText(e,t,n,i,r,s){this.beforeOperationSelection=i;const a=this.getDocument();this.beforeOperationRelativeSelection=z(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(bn(l))return this.insertTextInCodeBlock(e,t,i,r);if(l.type!=="paragraph")return!1;const c=l,g=this.listOperations.tryApplyParagraphListTrigger(c,e,t);if(g!==null)return g;const d=at(e,this.ydoc,a);if(!d)return!1;const u=S.createAbsolutePositionFromRelativePosition(d.textOffset,this.ydoc);if(!u||!(u.type instanceof S.XmlText))return!1;const p=u.type,h=u.index,f=Ni(a,e,i),m=this.suggestionEngine.getInlineInsertionSuggestionNodeAtPosition(a,e),y=m?.marks?.suggestionId??null,b=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(a,e.block),k=this.suggestionEngine.getSuggestionIdForSuggestedSelectionOverwrite(a,e,i),I=$i(a,e),v=Li(a,e),x=!b&&this.suggestingMode&&t.length>0,{marksToApply:A,marksToRemove:T}=vr({explicitMarks:n&&Object.keys(n).length>0?n:void 0,inheritedMarks:f?.marks,emptyParagraphMarks:Ii(c)?void 0:this.getEmptyTextMarksForBlockId(e.block),exitingLink:I,exitingComment:v,noteBodyFontSize:this.isBlockInsideFootnote(a,e.block)?dt:void 0,suggestionMarks:x?this.suggestionEngine.buildSuggestionInsertionMarks(void 0,s??k??y??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&&ke(a,i.anchor,i.focus)!==0){const[P,w]=ke(a,i.anchor,i.focus)===-1?[i.anchor,i.focus]:[i.focus,i.anchor];if(P.block===e.block&&w.block===e.block)if(this.suggestingMode&&!b){const{retainedLength:C}=this.suggestionEngine.applySuggestedDeletionToTextRange(p,P.offset,w.offset-P.offset,k??void 0);E=P.offset+C}else p.delete(P.offset,w.offset-P.offset),E=P.offset}ca(p,E,t,{marksToApply:A,marksToRemove:T}),!b&&this.suggestingMode&&t.length>0&&this.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(p,E,t.length)});const F=S.createRelativePositionFromTypeIndex(p,E+t.length),B=li({blockId:d.blockId,textOffset:F},this.ydoc);if(B){const P={anchor:B,focus:B};return this.setSelectionAfterOperation(P),this.afterOperationRelativeSelection=z(P,this.ydoc,this.getDocument()),!0}return this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=z(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=oe(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 g=e.offset,d=0;const u=[];this.transact(()=>{if(n&&n.anchor&&n.focus&&ke(r,n.anchor,n.focus)!==0){const[f,m]=ke(r,n.anchor,n.focus)===-1?[n.anchor,n.focus]:[n.focus,n.anchor];if(f.block===e.block&&m.block===e.block)if(this.suggestingMode&&!l){const{retainedLength:y}=this.suggestionEngine.applySuggestedDeletionToTextRange(a,f.offset,m.offset-f.offset,i);g=f.offset+y}else a.delete(f.offset,m.offset-f.offset),g=f.offset}let h=g;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,d+=f.text.length}for(const f of u)this.suggestionEngine.clearInheritedDeletionFromInsertedSuggestion(a,f.start,f.length);s.getAttribute("_emptyTextMarks")&&s.removeAttribute("_emptyTextMarks")});const p=g+d;return{block:e.block,offset:p}}insertParagraphInternal(e,t,n=this.getYContentFragment()){if(e<0||e>n.length)return!1;const i=new S.XmlElement("paragraph");i.setAttribute("id",t.id||Y()),t.heading&&i.setAttribute("heading",String(t.heading)),t.align&&i.setAttribute("align",t.align),t.lineSpacing!==void 0&&i.setAttribute("lineSpacing",String(t.lineSpacing)),pn(i,t);const r=Ye(t);r!==void 0&&i.setAttribute("pagination",r),t.styleId!==void 0&&i.setAttribute("styleId",t.styleId),t.direction!==void 0&&i.setAttribute("direction",t.direction),t.tabStops!==void 0&&i.setAttribute("tabStops",t.tabStops),t.borders!==void 0&&i.setAttribute("borders",t.borders),t.shading!==void 0&&i.setAttribute("shading",t.shading),t.oxmlAttrs!==void 0&&i.setAttribute("oxmlAttrs",t.oxmlAttrs),t.oxmlPPr!==void 0&&i.setAttribute("oxmlPPr",t.oxmlPPr);const 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(g=>{if(g.type==="text"&&g.text.length>0){const d={...g.marks||{}};ne(l,c,g.text,d),c+=g.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=z(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(bn(s))return this.deleteTextInCodeBlock(e,t,n,i);if(s.type!=="paragraph")return!1;const a=s,l=this.getEmptyTextMarksForBlockId(e.block),c=mn(r,a,e,l);let g=0;for(const k of a.children)k.type==="text"&&(g+=k.text.length);let d=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>d&&(p=!0,d=Math.min(d,k),u=Math.max(u,v)),k=v}}p&&(e={...e,offset:d},t=u-d);const h=g-e.offset,f=Math.min(t,h),m=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(r,e.block);let y=null;this.transact(()=>{const k=J(this.ydoc,e.block);if(!k)return;const I=oe(k);if(I){if(this.suggestingMode&&!m){const v=this.suggestionEngine.applySuggestedDeletionToTextRange(I,e.offset,f);f>1&&v.retainedLength>0&&(y=this.normalizeAdjacentManualReplacementOrder(I,e.offset))}else I.delete(e.offset,f);I.length===0&&Si(k,c)}});const b=y?no(i,e.block,y):i;return this.setSelectionAfterOperation(b),this.afterOperationRelativeSelection=z(b,this.ydoc,this.getDocument()),p&&!this.suggestingMode&&this.reconcileFootnotes(),!0}deleteSelection(e,t,n,i){this.beforeOperationSelection||(this.beforeOperationSelection=n);const r=this.getDocument();this.beforeOperationRelativeSelection||(this.beforeOperationRelativeSelection=z(n,this.ydoc,r));let s=Wt(r,e.block),a=Wt(r,t.block);if(s===-1||a===-1){const p=h=>{const f=(r.chrome??[]).findIndex(y=>y.id===h||y.children.some(b=>b.id===h));if(f!==-1)return r.children.length+f;const m=(r.notes??[]).findIndex(y=>y.id===h||y.children.some(b=>b.id===h));return m!==-1?r.children.length+(r.chrome?.length??0)+m:-1};if(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),y=this.listOperations.getListCursorInfo(f,t);if(m&&y&&m.itemIndex+1===y.itemIndex&&m.offsetInItem===this.listOperations.getListItemPlainText(f.children[m.itemIndex]).length&&y.offsetInItem===0){const b=le(),k=this.mergeAdjacentListItemsSnapshot(f,m.itemIndex,b);if(k){const I=this.suggestionEngine.runWithoutSuggesting(()=>this.updateBlockById(f.id,k,n,i));return I&&this.suggestionEngine.saveLiveSuggestion({id:b,type:"block-change",blockId:f.id,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(f),label:"Join"}),I}}}const h=Qe().getHandlerForBlock(p);if(h&&h.handleDeleteSelection){const f=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((y,b)=>y+(b.type==="text"?b.text.length:0),0)&&Ii(p)&&Si(f,mn(r,p,e))}),m){const y=rc(r,e.block),b=oc(r,e.block);let k;if(y&&y.id){const v=xc(r,y.id);v?k=v:k={block:y.id,offset:0}}else if(b&&b.id)k={block:b.id,offset:0};else return!1;const I={anchor:k,focus:k};return this.deleteBlockById(e.block,n,I)}return this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=z(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=Je(r,e.block),g=Je(r,t.block),d=X(r,e.block),u=X(r,t.block);return c&&g&&c===g&&d?.type==="paragraph"&&u?.type==="paragraph"?this.mergeAdjacentParagraphs(d,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 g=null,d=null;for(let y=0;y<l.length;y++){const b=l.get(y);if(b instanceof S.XmlText){g=b;break}}for(let y=0;y<c.length;y++){const b=c.get(y);if(b instanceof S.XmlText){d=b;break}}if(!g||!d)return console.error("[mergeAdjacentParagraphs] Could not find Y.XmlText"),!1;const u=n.offset===g.length&&i.offset===0;if(u){const y=this.isPlainEmptyParagraph(e),b=this.isPlainEmptyParagraph(t),k=this.isInsertedParagraph(e),I=this.isInsertedParagraph(t);if(y&&I||k&&b){const v=y?e:t,x=y?t:e,A=y?0:this.getParagraphTextLength(x),T={block:x.id,offset:A},E={anchor:T,focus:T};return this.deleteBlockById(v.id,s,E)}}if(this.suggestingMode&&u){const y=this.getCancelableParagraphSplitRecord(e,t);if(y){const k=this.suggestionEngine.rejectLiveSuggestion(y.id);if(k){const I={block:y.blockId,offset:this.getParagraphTextLength(e)},v={anchor:I,focus:I};this.setSelectionAfterOperation(v),this.afterOperationRelativeSelection=z(v,this.ydoc,this.getDocument())}return k}const b=le();return this.transact(()=>{this.suggestionEngine.clearParagraphStructuralSuggestion(l),this.suggestionEngine.clearParagraphStructuralSuggestion(c),this.suggestionEngine.setParagraphStructuralSuggestion(l,"merge","before",b),this.suggestionEngine.setParagraphStructuralSuggestion(c,"merge","after",b),this.suggestionEngine.saveLiveSuggestion({id:b,type:"paragraph-merge",firstBlockId:e.id,secondBlockId:t.id})}),this.setSelectionAfterOperation(a),this.afterOperationRelativeSelection=z(a,this.ydoc,this.getDocument()),!0}const p=G(this.ydoc,e.id),h=G(this.ydoc,t.id);if(!p||!h)return console.error("[mergeAdjacentParagraphs] Could not find Y.js parent"),!1;if(p.yParent!==h.yParent)return console.error("[mergeAdjacentParagraphs] Paragraphs have different Y.js parents"),!1;const f=p.index,m=h.index;return this.transact(()=>{this.suggestionEngine.clearParagraphStructuralSuggestion(l);const y=g.length;n.offset<y&&g.delete(n.offset,y-n.offset);const b=ee(d).slice(0);let k=[],I=0;for(const A of b)if(typeof A.insert=="string"){const T=A.insert;if(I+T.length<=i.offset)I+=T.length;else if(I>=i.offset)k.push(A);else{const E=i.offset-I,F=T.slice(E);F.length>0&&k.push({...A,insert:F}),I+=T.length}}for(const A of k)typeof A.insert=="string"&&g.insert(g.length,A.insert,A.attributes||{});const{yParent:v}=p,x=m-f;x>0&&v.delete(f+1,x)}),this.setSelectionAfterOperation(a),this.afterOperationRelativeSelection=z(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 g=[];for(const{block:A,path:T}of sc(n)){const E=Pt(T,s),F=Pt(T,a);if(!(E<0)){if(F>0)break;g.push({block:A,path:T,isFirst:E===0,isLast:F===0})}}if(g.length===0)return!1;const d=s[0],u=a[0],p=n.children[d],h=n.children[u];if(d!==u&&p?.type==="list"&&h?.type==="list"&&this.listOperations.mergeAdjacentListsOnDelete(p,h,d,u,e,t,r))return!0;const f=g[0],m=g[g.length-1],y=f.block.type==="paragraph",b=m.block.type==="paragraph",k=G(this.ydoc,f.block.id),I=G(this.ydoc,m.block.id);if(!k||!I)return!1;const v=k.yBlock,x=I.yBlock;return this.transact(()=>{let A=null,T=null;y&&(A=oe(v)),b&&(T=oe(x));const E=y?e.offset:0,F=b?t.offset:0,B=g.length===2&&y&&b&&A!==null&&E===A.length&&F===0;let P="";const w={};if(b&&T){const C=ee(T);let $=0;for(const L of C)if(L.insert&&typeof L.insert=="string"){const O=L.insert.length;$>=F?(P+=L.insert,L.attributes&&Object.assign(w,L.attributes)):$+O>F&&(P+=L.insert.slice(F-$),L.attributes&&Object.assign(w,L.attributes)),$+=O}}if(y&&A&&E<A.length&&A.delete(E,A.length-E),B&&v instanceof S.XmlElement&&x instanceof S.XmlElement){const C=x.getAttribute("heading");C?v.setAttribute("heading",C):v.removeAttribute("heading");const $=te(x,"align");$&&v.setAttribute("align",$);const L=te(x,"lineSpacing");L?v.setAttribute("lineSpacing",L):q(v,"lineSpacing"),Gh(x,v,!0);const O=te(x,"pagination");O?v.setAttribute("pagination",O):q(v,"pagination");const M=te(x,"tabStops");M?v.setAttribute("tabStops",M):q(v,"tabStops");for(const R of["oxmlAttrs","oxmlPPr"]){const D=te(x,R);D?v.setAttribute(R,D):q(v,R)}const N=te(x,"leftIndent");N?v.setAttribute("leftIndent",N):q(v,"leftIndent");const _=te(x,"firstLineIndent");_?v.setAttribute("firstLineIndent",_):q(v,"firstLineIndent")}y&&A&&P?ne(A,A.length,P,w):!y&&b&&T&&F>0&&T.delete(0,Math.min(F,T.length));for(let C=g.length-1;C>=0;C--){const $=g[C],L=$.isFirst&&y,O=!y&&$.isLast&&b;if(L||O)continue;const M=G(this.ydoc,$.block.id);if(M){const{yBlock:N,yParent:_,index:R}=M;if(_.length===1){if($.block.type==="paragraph"){const D=Je(n,$.block.id);if(D?.type==="container"&&D.id){const j=G(this.ydoc,D.id);if(j&&j.yParent.length>1){j.yParent.delete(j.index,1);continue}}const U=oe(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=z(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),g=mn(r,a.paragraph,e,c);let d=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&&(d=this.normalizeAdjacentManualReplacementOrder(h,a.offset)):h.delete(a.offset,l.offset-a.offset),h.length===0&&Si(p,g))});const u=d?no(i,e.block,d):i;return this.setSelectionAfterOperation(u),this.afterOperationRelativeSelection=z(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=z(t,this.ydoc,i),this.transact(()=>{const r=this.getYContentFragment();e<r.length&&r.delete(e,1)}),this.afterOperationRelativeSelection=z(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 g=(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(g&&this.suggestionEngine.getLiveSuggestion(g)?.type==="block-insert")return this.suggestionEngine.rejectLiveSuggestion(g);if(r.type==="paragraph"){const d=oe(a),u=d?.length??0;if(d&&u>0)return this.beforeOperationRelativeSelection=z(t,this.ydoc,i),this.transact(()=>{this.suggestionEngine.applySuggestedDeletionToTextRange(d,0,u)}),this.afterOperationRelativeSelection=z(n,this.ydoc,this.getDocument()),!0}else{const d=le(),u=this.getTrailingCleanupParagraphIdForTopLevelBlock(i,e);return this.beforeOperationRelativeSelection=z(t,this.ydoc,i),this.transact(()=>{this.suggestionEngine.markDeletedBlockElement(a,d),this.suggestionEngine.saveLiveSuggestion({id:d,type:"block-delete",blockId:e,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(r),label:"Delete",cleanupTrailingParagraphId:u})}),this.afterOperationRelativeSelection=z(n,this.ydoc,this.getDocument()),!0}}if(l.length===1){if(r.type==="paragraph"){const u=oe(a);return u&&u.length>0?(this.beforeOperationRelativeSelection=z(t,this.ydoc,i),this.transact(()=>{u.delete(0,u.length)}),this.afterOperationRelativeSelection=z(n,this.ydoc,this.getDocument()),!0):!1}this.beforeOperationRelativeSelection=z(t,this.ydoc,i);const g=Y();this.transact(()=>{l.delete(c,1);const u=new S.XmlElement("paragraph");u.setAttribute("id",g);const p=new S.XmlText;u.insert(0,[p]),l.insert(0,[u])});const d={anchor:{block:g,offset:0},focus:{block:g,offset:0}};return this.afterOperationRelativeSelection=z(d,this.ydoc,this.getDocument()),this.setSelectionAfterOperation(d),!0}return this.beforeOperationRelativeSelection=z(t,this.ydoc,i),this.transact(()=>{l.delete(c,1)}),this.afterOperationRelativeSelection=z(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=z(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 F=this.getCancelableParagraphMergeRecord(i,e.offset);if(F&&this.suggestionEngine.rejectLiveSuggestion(F.id)){const B={anchor:e,focus:e};return this.setSelectionAfterOperation(B),this.afterOperationRelativeSelection=z(B,this.ydoc,this.getDocument()),e}}const s=G(this.ydoc,e.block);if(!s)return null;const{yBlock:a,yParent:l,index:c}=s,g=i.structuralSuggestionId?this.suggestionEngine.getLiveSuggestion(i.structuralSuggestionId):void 0,d=g?.type==="block-change"&&g.sequenceBlockIds?g:null,u=this.getEmptyTextMarksForBlockId(e.block),p=e.offset,h=this.suggestionEngine.getStructuralInsertSuggestionIdAtPosition(n,e),f=i.children.reduce((F,B)=>B.type==="text"?F+B.text.length:F,0),m=this.suggestingMode&&p>0&&p<f&&wt.isTailFullyDeletionMarked(i,p),y=typeof h=="string"&&(p===0||p===f),b=this.suggestingMode&&typeof h=="string"&&p>0&&p<f,k=typeof h=="string",I=d?null:b?h:this.suggestingMode&&!y?le():null,v=b||this.suggestingMode&&!y&&(f===0||p===0||p===f||m),x=p===0&&!(v&&f===0),A=this.suggestingMode&&!k&&I;if(p===0){if(this.transact(()=>{r=Y();const P=new S.XmlElement("paragraph");P.setAttribute("id",r);const w=a.getAttribute("heading"),C=a.getAttribute("styleId"),$=w!=null?!0:typeof C=="string"&&/^heading\d/i.test(C);aa(a,P);const L=te(a,"direction");if((L==="rtl"||L==="ltr")&&P.setAttribute("direction",L),!$){const _=te(a,"align");_&&P.setAttribute("align",_);const R=a.getAttribute("styleId");R!=null&&P.setAttribute("styleId",R)}const O=te(a,"borders");if(O!=null){const{upper:_,lower:R}=wt.splitBordersAttr(O);_?P.setAttribute("borders",_):q(P,"borders"),R?a.setAttribute("borders",R):q(a,"borders")}const M=new S.XmlText,N=$?null:mn(n,i,e,u);N&&P.setAttribute("_emptyTextMarks",JSON.stringify(N)),this.suggestionEngine.clearParagraphStructuralSuggestion(a),this.suggestionEngine.clearParagraphStructuralSuggestion(P),k&&h&&this.suggestionEngine.setParagraphStructuralSuggestion(a,"insert",void 0,h,"Insert"),I&&(v?this.suggestionEngine.setParagraphStructuralSuggestion(P,"insert",void 0,I,"Insert"):(this.suggestionEngine.setParagraphStructuralSuggestion(P,"split","before",I),this.suggestionEngine.setParagraphStructuralSuggestion(a,"split","after",I))),P.insert(0,[M]),l.insert(x?c:c+1,[P]),d&&this.suggestionEngine.preserveSequenceAfterParagraphSplit(d,[a,P]),$&&r&&this.applyStylesheetHeadingDefaults(P,{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 F={block:k?e.block:this.suggestingMode&&v?r:e.block,offset:0},B={anchor:F,focus:F};return this.setSelectionAfterOperation(B),this.afterOperationRelativeSelection=z(B,this.ydoc,this.getDocument()),F}if(this.transact(()=>{let F=null;for(let U=0;U<a.length;U++){const j=a.get(U);if(j instanceof S.XmlText){F=j;break}}if(!F||i.type!=="paragraph")return;const B=ee(F);let P=0;const w=[];if(!m){for(const U of B)if(U.insert&&typeof U.insert=="string"){const j=U.insert.length;if(P+j<=p)P+=j;else if(P>=p)w.push(U);else{const H=p-P,K=U.insert.slice(H);K&&w.push({insert:K,...U.attributes&&{attributes:U.attributes}}),P=p}}p<F.length&&F.delete(p,F.length-p)}this.suggestionEngine.clearParagraphStructuralSuggestion(a),r=Y();const C=new S.XmlElement("paragraph");C.setAttribute("id",r),aa(a,C);const $=te(a,"align");$&&C.setAttribute("align",$);const L=a.getAttribute("styleId");L!=null&&C.setAttribute("styleId",L);const O=te(a,"direction");(O==="rtl"||O==="ltr")&&C.setAttribute("direction",O);const M=te(a,"borders");if(M!=null){const{upper:U,lower:j}=wt.splitBordersAttr(M);j?C.setAttribute("borders",j):q(C,"borders"),U?a.setAttribute("borders",U):q(a,"borders")}const N=new S.XmlText,_=mn(n,i,e,u),R=i.heading!==void 0&&To(n.stylesheet)!==void 0;let D=null;if(R&&w.length>0){const U=n.stylesheet,j=(i.styleId?Co(U,i.styleId):void 0)??Oi(U,i.heading),H=To(U);D=Po(j?.runMarks,H?.runMarks)}if(w.length>0){let U=0;for(const j of w)if(j.insert&&typeof j.insert=="string"){let H=j.attributes||{};if(D){H={...H};for(const[K,se]of Object.entries(D))se===!1||se===void 0?delete H[K]:H[K]=se}ne(N,U,j.insert,H),U+=j.insert.length}}else _&&C.setAttribute("_emptyTextMarks",JSON.stringify(_));this.suggestionEngine.clearParagraphStructuralSuggestion(C),k&&h&&this.suggestionEngine.setParagraphStructuralSuggestion(a,"insert",void 0,h,"Insert"),I&&(v?this.suggestionEngine.setParagraphStructuralSuggestion(C,"insert",void 0,I,"Insert"):(this.suggestionEngine.setParagraphStructuralSuggestion(C,"split","after",I),this.suggestionEngine.setParagraphStructuralSuggestion(a,"split","before",I))),C.insert(0,[N]),l.insert(c+1,[C]),d&&this.suggestionEngine.preserveSequenceAfterParagraphSplit(d,[a,C]),R&&r&&(this.applyStylesheetHeadingDefaults(C,{type:"paragraph",id:r,heading:i.heading,styleId:i.styleId,children:[]},n,void 0),w.length>0&&C.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 T={block:r,offset:0},E={anchor:T,focus:T};return this.setSelectionAfterOperation(E),this.afterOperationRelativeSelection=z(E,this.ydoc,this.getDocument()),T}applyFormatting(e,t,n,i,r){this.beforeOperationSelection=i;const s=this.getDocument();this.beforeOperationRelativeSelection=z(i,this.ydoc,s);let a=!1,l=null;const c=[];return this.transact(()=>{const g=this.getYContentFragment(),d=this.collectInlineFormattingRanges(e,t,g,s);if(d.length===0)return;const u=this.suggestingMode?(()=>{let p=null;for(const h of d){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?le():null;e:for(const{yText:p,start:h,end:f}of d){const m=ee(p);let y=0;for(const b of m)if(b.insert&&typeof b.insert=="string"){const k=b.insert.length,I=y+k;if(y<f&&I>h&&!(b.attributes||{})[n]){a=!0;break e}y+=k}}for(const{yText:p,start:h,end:f,blockId:m,itemIndex:y}of d){const b=Math.max(0,f-h),k=this.suggestingMode&&l&&b>0?this.collectOverlappingTextSpans(p,h,b):[];if(this.suggestingMode&&l&&b>0&&m)for(const v of k)v.attributes?.insertion||v.attributes?.deletion||c.push({blockId:m,itemIndex:y,start:v.start,end:v.start+v.length,attributes:v.attributes});const I=n==="superscript"&&a?{superscript:!0,subscript:!1}:n==="subscript"&&a?{subscript:!0,superscript:!1}:{[n]:a};if(this.suggestingMode&&l&&b>0){const v=this.suggestionEngine.buildInlineSuggestionMetadataMarks(l,this.getFormattingDescriptionFromMarkKey(n));for(const x of k)x.attributes?.deletion||(ie(p,x.start,x.length,I),!x.attributes?.insertion&&ie(p,x.start,x.length,{formatChange:!0,...v,suggestionPriorAttributes:hn(x.attributes)}))}else ie(p,h,b,I)}this.suggestingMode&&l&&c.length>0&&this.suggestionEngine.saveLiveSuggestion({id:l,type:"inline-format",label:this.getFormattingDescriptionFromMarkKey(n),spans:c})}),this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=z(r,this.ydoc,this.getDocument()),!0}formatRangesWithValue(e,t,n){if(!this.suggestingMode){for(const{yText:a,start:l,end:c}of e){const g=Math.max(0,c-l);g>0&&ie(a,l,g,t)}return}const i=le(),r=this.suggestionEngine.buildInlineSuggestionMetadataMarks(i,n),s=[];for(const{yText:a,start:l,end:c,blockId:g,itemIndex:d}of e){const u=Math.max(0,c-l);if(u===0)continue;const p=this.collectOverlappingTextSpans(a,l,u);for(const h of p)h.attributes?.deletion||!Object.entries(t).some(([f,m])=>{const y=h.attributes?.[f];return m===!1||m===null?y!=null&&y!==!1:y!==m})||(ie(a,h.start,h.length,t),!h.attributes?.insertion&&(ie(a,h.start,h.length,{formatChange:!0,...r,suggestionPriorAttributes:hn(h.attributes)}),g&&s.push({blockId:g,itemIndex:d,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=z(i,this.ydoc,r),this.transact(()=>{const s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,s,r),l=ke(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=z(i,this.ydoc,this.getDocument()),!0}setFontSize(e,t,n,i){this.beforeOperationSelection=i;const r=this.getDocument();return this.beforeOperationRelativeSelection=z(i,this.ydoc,r),this.transact(()=>{const s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,s,r),l=ke(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=z(i,this.ydoc,this.getDocument()),!0}setLetterSpacing(e,t,n,i){this.beforeOperationSelection=i;const r=this.getDocument();return this.beforeOperationRelativeSelection=z(i,this.ydoc,r),this.transact(()=>{const s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,s,r),l=ke(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=z(i,this.ydoc,this.getDocument()),!0}setTextColor(e,t,n,i){this.beforeOperationSelection=i;const r=this.getDocument();return this.beforeOperationRelativeSelection=z(i,this.ydoc,r),this.transact(()=>{const s=this.getYContentFragment(),a=this.collectInlineFormattingRanges(e,t,s,r),l=ke(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=z(i,this.ydoc,this.getDocument()),!0}setBackgroundColor(e,t,n,i){const r=yc(n);this.beforeOperationSelection=i;const s=this.getDocument();return this.beforeOperationRelativeSelection=z(i,this.ydoc,s),this.transact(()=>{const a=this.getYContentFragment(),l=this.collectInlineFormattingRanges(e,t,a,s),c=ke(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=z(i,this.ydoc,this.getDocument()),!0}clearFormatting(e,t,n){this.beforeOperationSelection=n;const i=this.getDocument();this.beforeOperationRelativeSelection=z(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:g})=>g>c)&&(this.formatRangesWithValue(a,No,"Clear Formatting"),r=!0);for(const c of l){const g=J(this.ydoc,c);if(g)for(const d of Lo)te(g,d)!==void 0&&(q(g,d),r=!0)}ke(i,e,t)===0&&this.clearFormattingEmptyMarksAtPosition(e,i)&&(r=!0)}),this.setSelectionAfterOperation(n),this.afterOperationRelativeSelection=z(n,this.ydoc,this.getDocument()),r}setLink(e,t,n,i){this.beforeOperationSelection=i;const r=this.getDocument();return this.beforeOperationRelativeSelection=z(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:g,end:d}of a){const u=Math.max(0,d-g);n?ie(c,g,u,{link:n}):ie(c,g,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:g,end:d}of a){const u=Math.max(0,d-g);u!==0&&ie(c,g,u,{link:n??!1})}return}this.formatRangesWithValue(a,{link:n??!1},"Link")}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=z(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),kc(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"&&!Ut(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=Ut(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"&&!Ut(i))return!1;const r=G(this.ydoc,e);return r?(this.transact(()=>{const s=r.yBlock;if(s instanceof S.XmlElement){if(Ut(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"&&!Ut(i))return!1;if(Ut(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=z(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)),pn(c,t);{const h=Ye(t);h!==void 0&&c.setAttribute("pagination",h)}t.styleId!==void 0&&c.setAttribute("styleId",t.styleId),t.direction!==void 0&&c.setAttribute("direction",t.direction),t.tabStops!==void 0&&c.setAttribute("tabStops",t.tabStops),t.borders!==void 0&&c.setAttribute("borders",t.borders),t.shading!==void 0&&c.setAttribute("shading",t.shading),t.oxmlAttrs!==void 0&&c.setAttribute("oxmlAttrs",t.oxmlAttrs),t.oxmlPPr!==void 0&&c.setAttribute("oxmlPPr",t.oxmlPPr);const g=Re(t.leftIndent);g!==void 0&&c.setAttribute("leftIndent",String(g));const d=De(t.firstLineIndent);d!==void 0&&c.setAttribute("firstLineIndent",String(d));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=z(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 g=this.getAfterOperationSelection();return g?.focus?{block:g.focus.block,offset:g.focus.offset}:null};let c=null;if(this.transact(()=>{for(let g=0;g<t.length;g++){if(g>0){const d=this.splitParagraph(r,{anchor:r,focus:r});if(!d)return;r=d,s={anchor:r,focus:r}}for(const d of t[g].children){if(d.type!=="text"||d.text.length===0)continue;const u=this.suggestionEngine.stripSuggestionMarksFromTextMark(d.marks)??{};if(!this.insertFormattedText(r,d.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 g={anchor:c,focus:c};this.setSelectionAfterOperation(g),this.afterOperationRelativeSelection=z(g,this.ydoc,this.getDocument())}return c}pasteParagraphs(e,t,n,i={}){if(t.length===0||!t.some(b=>b.children.some(k=>k.type==="text"&&k.text.length>0)))return null;const r=ct(Ni(this.getDocument(),e,n)?.marks);if(r?.fontFamily===Ee&&delete r.fontFamily,r&&(t=t.map(b=>b.type==="paragraph"?{...b,children:b.children.map(k=>k.type==="text"?{...k,marks:{...r,...k.marks??{}}}:k)}:b)),this.suggestingMode)return this.pasteParagraphsAsSuggestions(e,t,n,i.suggestionIdOverride);this.beforeOperationSelection={anchor:n.anchor?{...n.anchor}:null,focus:n.focus?{...n.focus}:null};const s=this.getDocument();this.beforeOperationRelativeSelection=z(n,this.ydoc,s);let a=null;const l=i.preserveStructure===!0&&t.length>1;let c,g=null,d=null,u=null,p=!1,h=null,f=null;const m=b=>{if(!b.id)return null;let k=0;for(const I of b.children)I.type==="text"&&(k+=I.text.length);return{block:b.id,offset:k}},y=b=>b.id?b:{...b,id:Y()};try{this.transact(()=>{const k=n.anchor&&n.focus&&ke(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,H=D,K=U?{block:n.focus.block,offset:n.focus.offset}:j?{block:n.anchor.block,offset:n.anchor.offset}:ke(s,n.anchor,n.focus)<=0?{block:n.focus.block,offset:n.focus.offset}:{block:n.anchor.block,offset:n.anchor.offset},se=this.getParagraphOffsetForPosition(H,s),xe=this.getParagraphOffsetForPosition(K,s);se&&xe&&this.arePathsEqual(se.paragraphPath,xe.paragraphPath)&&(g=xe.offset);const Ue=se?.offset??H.offset;this.deleteSelection({block:H.block,offset:H.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:H.block,offset:H.offset},focus:{block:H.block,offset:H.offset}});const Oe=this.getDocument(),W=X(Oe,H.block);(W?.type==="paragraph"||W?.type==="list")&&W.id&&(I={block:W.id,offset:Ue})}const v=g!==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,H=this.listOperations.insertTextInListItem(I,U,j);H&&(a=H)}return}if(x.block.type!=="paragraph"){a=null;return}const A=x.block;if(!A||A.type!=="paragraph"){a=null;return}const T=[],E=this.getParagraphOffsetForPosition(I,v)?.offset??0,F=g??E;let B=0;for(let D=0;D<A.children.length;D++){const U=A.children[D];if(U.type==="text"){const j=B;if(B+U.text.length>F){const H=Math.max(0,F-j);H<U.text.length&&T.push({type:"text",text:U.text.substring(H),marks:U.marks})}B+=U.text.length}}const P=T.length>0&&T.some(D=>D.text.length>0);if(p=P,P){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 w=t[0],C=J(this.ydoc,I.block);if(!C){a=null;return}const $=oe(C);if(!$){a=null;return}if($.length===0&&w.type==="paragraph"){w.heading!==void 0?C.setAttribute("heading",String(w.heading)):C.removeAttribute("heading"),w.align?C.setAttribute("align",w.align):q(C,"align"),w.lineSpacing!==void 0?C.setAttribute("lineSpacing",String(w.lineSpacing)):q(C,"lineSpacing");for(const j of il)q(C,j);pn(C,w);{const j=Ye(w);j!==void 0?C.setAttribute("pagination",j):q(C,"pagination")}w.styleId!==void 0?C.setAttribute("styleId",w.styleId):C.removeAttribute("styleId"),w.direction!==void 0?C.setAttribute("direction",w.direction):q(C,"direction"),w.tabStops!==void 0?C.setAttribute("tabStops",w.tabStops):q(C,"tabStops"),w.borders!==void 0?C.setAttribute("borders",w.borders):q(C,"borders"),w.shading!==void 0?C.setAttribute("shading",w.shading):q(C,"shading");const D=Re(w.leftIndent);D!==void 0?C.setAttribute("leftIndent",String(D)):q(C,"leftIndent");const U=De(w.firstLineIndent);U!==void 0?C.setAttribute("firstLineIndent",String(U)):q(C,"firstLineIndent")}const L=w.children.filter(D=>D.type==="text"),O=this.insertTextNodes(I,L);if(!O){a=null;return}if(d=O,a=O,t.length===1&&!P){u=O.block;return}const M=G(this.ydoc,I.block);if(!M)return;const N=M.yParent;let _=M.index+1;if(l){const D=[];let U=null;for(let j=1;j<t.length;j++){const H=y(t[j]);this.insertParagraphInternal(_,H,N),D.push(H.id),_++}if(P){const j={type:"paragraph",id:Y(),children:T.map(se=>({type:"text",text:se.text,marks:se.marks?{...se.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 H=Re(A.leftIndent);H!==void 0&&(j.leftIndent=H);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=y(t[D]);this.insertParagraphInternal(_,U,N),R=U.id,_++}if(u=R,P){const D=t.length>1?N.get(_-1):C;if(D instanceof S.XmlElement){let U=null;for(let j=0;j<D.length;j++){const H=D.get(j);if(H instanceof S.XmlText){U=H;break}}if(U){let j=U.length;h=j,f=R;for(const H of T){if(!H.text.length)continue;const K={...H.marks||{}};U.insert(j,H.text,K),j+=H.text.length}}}}});const b=this.getDocument();if(l&&c){const{insertedParagraphIds:k,remainderParagraphId:I}=c;if(k.length>0){const v=k[k.length-1],x=X(b,v);x&&x.type==="paragraph"?a=m(x):a={block:v,offset:0}}else if(I!==null){const v=X(b,I);v&&v.type==="paragraph"?a=m(v):a={block:I,offset:0}}else d&&(a=d)}else if(!l)if(p&&f!==null&&h!==null)a={block:f,offset:h};else if(p&&d)a=d;else if(u!==null){const k=X(b,u);k&&k.type==="paragraph"?a=m(k):d?a=d:a={block:u,offset:0}}else d&&(a=d);!a&&d&&(a=d)}catch(b){return console.error("Error in pasteParagraphs:",b),null}return a||(a=d??e),a&&(a=this.normalizeCursorPosition(a),this.setSelectionAfterOperation({anchor:a,focus:a}),this.updateAfterOperationRelativeSelection(this.getDocument())),a}normalizeCursorPosition(e){return this.getDocument().children.length,e}replaceDocument(e){return this.undoManager.stopCapturing(),this.transact(()=>{const t=this.getYContentFragment();t.length>0&&t.delete(0,t.length),e.children.forEach(n=>{if(n.type==="placeholder"){const i=new S.XmlElement("placeholder");i.setAttribute("id",n.id||Y()),i.setAttribute("height",String(n.height)),t.push([i])}else if(n.type==="image"){const i=n,r=new S.XmlElement("image");r.setAttribute("id",n.id||Y()),r.setAttribute("src",i.src),i.sourceUrl&&r.setAttribute("sourceUrl",i.sourceUrl),r.setAttribute("width",String(i.width)),r.setAttribute("height",String(i.height)),i.alt&&r.setAttribute("alt",i.alt),t.push([r])}else if(n.type==="paragraph"){const i=new S.XmlElement("paragraph");i.setAttribute("id",n.id||Y()),n.heading&&i.setAttribute("heading",String(n.heading)),n.align&&i.setAttribute("align",n.align),n.lineSpacing!==void 0&&i.setAttribute("lineSpacing",String(n.lineSpacing)),pn(i,n);{const c=Ye(n);c!==void 0&&i.setAttribute("pagination",c)}n.styleId!==void 0&&i.setAttribute("styleId",n.styleId),n.direction!==void 0&&i.setAttribute("direction",n.direction),n.tabStops!==void 0&&i.setAttribute("tabStops",n.tabStops),n.borders!==void 0&&i.setAttribute("borders",n.borders),n.shading!==void 0&&i.setAttribute("shading",n.shading);const r=Re(n.leftIndent);r!==void 0&&i.setAttribute("leftIndent",String(r));const 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 g={...c.marks||{}};ne(a,l,c.text,g),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(g=>{if(g.type==="text"){const d={...g.marks||{}};l.insert(c,g.text,d),c+=g.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 Sc(i,r)}updateParagraphAttributes(e,t,n,i){this.beforeOperationSelection=n;const r=this.getDocument();if(this.beforeOperationRelativeSelection=z(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={};Ei(l,te(a,"pagination"));for(const g of["keepNext","keepLines","widowControl"])Object.prototype.hasOwnProperty.call(t,g)&&(t[g]===void 0?delete l[g]:l[g]=t[g]);const c=Ye(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=z(i,this.ydoc,this.getDocument()),!0}applyStylesheetHeadingDefaults(e,t,n,i){if(t.type!=="paragraph"||!t.id)return!1;const r=n.stylesheet,s=Oi(r,i);if(!r||!s)return!1;const a=(t.styleId?Co(r,t.styleId):void 0)??Oi(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??{},g=(f,m)=>Object.prototype.hasOwnProperty.call(f,m),d=["align","lineSpacing","spaceBefore","spaceAfter","contextualSpacing","leftIndent","firstLineIndent","direction","borders","shading","tabStops"];(g(c,"leftIndent")||g(c,"firstLineIndent"))&&(c.leftIndent!==void 0||c.firstLineIndent!==void 0)&&this.ensureParagraphIndentStorageUsesUnits();for(const f of d){if(!g(l,f)&&!g(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=>g(l,f)||g(c,f))){const f={};Ei(f,te(e,"pagination"));for(const y of u)!g(l,y)&&!g(c,y)||(c[y]===void 0?delete f[y]:f[y]=c[y]);const m=Ye(f);m===void 0?q(e,"pagination"):e.setAttribute("pagination",m)}const p=Po(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:y,start:b,end:k}of m){const I=Math.max(0,k-b);I>0&&ie(y,b,I,p)}}else Si(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&&ie(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=z(n,this.ydoc,a);const l=Object.prototype.hasOwnProperty.call(t,"leftIndent")||Object.prototype.hasOwnProperty.call(t,"firstLineIndent"),c=this.suggestionEngine.getEnclosingBlockInsertSuggestionIdForBlockId(a,e),g=this.suggestingMode&&!c?le():null;l&&this.ensureParagraphIndentStorageUsesUnits();const d=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"&&d==="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={};Ei(u,te(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=Ye(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&&g&&(this.suggestionEngine.clearElementStructuralSuggestion(s),this.suggestionEngine.setElementStructuralSuggestion(s,"change",void 0,g,"Format"),this.suggestionEngine.saveLiveSuggestion({id:g,type:"block-change",blockId:e,beforeBlock:this.suggestionEngine.cloneSuggestionSnapshot(r),label:"Format"}))}),this.afterOperationRelativeSelection=z(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=z(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=z(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),g=Math.min(n,l);if(c<g&&i.push({type:"text",text:s.text.slice(c-a,g-a),marks:this.suggestionEngine.sanitizePreviewMarks(s.marks)}),r=l,r>=n)break}return i}buildParagraphReplacementLiveBlock(e,t,n,i){const r=(d,u)=>d.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(d=>d.text).join(""),c=a.map(d=>d.text).join(""),g=l.length>0&&c.length>0&&!/\s$/.test(l)&&!/^\s/.test(c);return{...t,children:[...s,...g?[{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"){Ur(c,t);return}const g=this.blockToYjsElement(t);a.delete(l,1),a.insert(l,[g])}),!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:Qt,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(g=>g.id===i.id);if(c<0||c+i.count>t.children.length)return null;e=t.children.slice(c,c+i.count).map(g=>({name:"remove_block",arguments:{id:g.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 g=c.arguments;if(typeof g?.id!="string"||g.count!==void 0&&g.count!==1)return null;const d=X(r,g.id)??X(t,g.id),u=this.suggestionEngine.getBlockInsertSuggestionIdForBlock(d),p=u?this.suggestionEngine.getLiveSuggestion(u):void 0;if(!d)return null;if(s.add(g.id),!u){l.add(g.id);continue}if(p?.type!=="block-insert")return null;a.add(u)}for(const c of a){const g=this.suggestionEngine.getLiveSuggestion(c);g?.type==="block-insert"&&g.cleanupTrailingParagraphId&&l.delete(g.cleanupTrailingParagraphId)}if(l.size>0||a.size===0)return null;for(const c of a)if(this.collectStructuralInsertBlockIds(r,c).some(g=>!s.has(g)))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=Wt(t,s);if(!(l<0))for(let c=l+1;c<Math.min(t.children.length,l+a);c++){const g=t.children[c]?.id;g&&n.add(g)}}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 g of i){const d=g.arguments??{},u=d.id??"";let p;try{p=Dc(this,u,d.find??"")}catch(f){return{success:!1,error:f instanceof Error?f.message:String(f),failure:Jt(f)}}const h=this.suggestingMode;this.suggestingMode=!0;try{const{result:f}=this.suggestionEngine.withSuggestionMetadata({source:"agent",authorType:"ai",label:d.kind==="endnote"?"Insert endnote":"Insert footnote",agentName:e.agentName??Ze,agentModel:e.agentModel,commentThreadId:e.commentThreadId,agentConversationId:e.agentConversationId,agentRequestId:e.agentRequestId,agentTurn:e.agentTurn,historyOrigin:`live-suggestions:${t}`},()=>this.insertFootnote(p,d.text??"",{anchor:p,focus:p},d.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(g=>g.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=Du(e,t,this.preprocessorSession,this.getDocument())}catch(a){const l=a instanceof zr?a:void 0,c=l?Be(l.action):void 0;return{success:!1,failure:Jt(l?.originalError??a),error:a instanceof Error?a.message:String(a),...l?{failedActions:[{actionIndex:l.actionIndex,actionName:l.action.name,error:l.message,failure:Jt(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=ul(e.actions,r.actions);if(r.actions){for(const d of r.actions)if(d.name==="set_title")this.setTitle(d.arguments.title),d.arguments.title;else if(d.name==="set_notes"){const u=d.arguments?.notes,p=typeof u=="string"?u:u==null?"":String(u);this.setNotes(p)}else if(d.name==="set_page_layout"){const u=this.applySetPageLayoutAction(d.arguments??{});if(u.error)return{success:!1,error:`set_page_layout: ${u.error}`}}else d.name==="set_header_footer"&&this.applySetHeaderFooterAction(d.arguments??{});const a={...r,actions:r.actions.filter(d=>d.name!=="set_title"&&d.name!=="set_notes"&&d.name!=="set_page_layout"&&d.name!=="set_header_footer")},l=a.actions.length>=100,c=Date.now(),g=d=>{l&&(`${a.actions.length}${d}`,Date.now()-c)};if(g("preprocessed"),a.actions.length>0){const d=this.suggestionEngine.getLiveSuggestionIds().length>0;let u,p,h,f;if(d){const w=this.suggestionEngine.createLiveSuggestionProjection("accept"),C=this.suggestionEngine.createLiveSuggestionProjection("reject");u=w.doc,p=C.doc,h=this.cloneYDoc(w.ydoc),f=this.cloneYDoc(C.ydoc)}else u=this.getDocument(),p=u,h=this.cloneYDoc(this.ydoc),f=this.cloneYDoc(this.ydoc);const m=u,y=this.tryCancelInsertedBlockForRemoveAction(a.actions,m);if(y)return y;const{anchorsByAction:b,failures:k,alreadySatisfied:I}=Td(h,a.actions,t,m,{rejectUnchangedAction:!0,continueAfterError:!0,canonicalDocument:()=>fe(h),skipContextForFirstAction:!0});g("validated");const v=a.actions.length===1?Be(a.actions[0])?.styleEffects:void 0;if(k.length>0){const w=C=>`${C.actionName}: ${C.error}`;return k.length===1?{success:!1,error:`Failed operation: ${w(k[0])}`,failedActions:k,failure:k[0]?.failure}:{success:!1,error:`Failed operations: ${k.map(w).join("; ")}`,failedActions:k,failure:k[0]?.failure}}if(I)return h.destroy(),f.destroy(),{success:!0,resultCode:"already_satisfied",styleEffects:v,suggestionIds:[],planningSuggestionIds:[],agentFeedback:(a.actions.length===1?rr(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?rr(a.actions[0]):void 0)??ul(e.actions,r.actions,b)??s,A=fe(h);g("materialized validation document");const T=new Set,E=w=>{if(!w)return;T.add(w);const C=X(m,w)??X(A,w);C?.id&&T.add(C.id)};for(const w of b)for(const C of w)typeof C?.paragraphId=="string"&&C.paragraphId.length>0&&E(C.paragraphId);for(const w of a.actions){const C=w?.name,$=w?.arguments;(C==="replace"||C==="replace_all"||C==="replace_many"||C==="replace_block"||C==="remove_block"||C==="set_block_attribute"||C==="clear_block_formatting")&&typeof $?.id=="string"&&$.id.length>0&&E($.id),typeof $?.referenceId=="string"&&$.referenceId.length>0&&E($.referenceId),typeof $?.tableId=="string"&&$.tableId.length>0&&E($.tableId)}const F=rf(m,a.actions);for(const w of F)T.add(w.currentBlockId),T.add(w.finalBlockId);this.suggestionEngine.expandPendingSequenceBlockIds(T);const B=T.size>0||F.length>0?{...T.size>0?{affectedBlockIds:Array.from(T)}:{},...F.length>0?{replacementBlockMatches:F}:{}}:void 0,P=this.suggestionEngine.applyValidatedAgentActionsAsSuggestions({validationFork:h,baseFork:f,flattenOptions:B,toolCallId:t,originalActions:e.actions,processedActions:r.actions,validationAnchorsByAction:b,docBeforeToolCall:m,docAfterToolCall:A,baseDocForSuggestions:p,agentFeedback:x,agentName:e.agentName,agentModel:e.agentModel,commentThreadId:e.commentThreadId,agentConversationId:e.agentConversationId,agentRequestId:e.agentRequestId,agentTurn:e.agentTurn,optimizeStyleFormatting:n?.optimizeStyleFormatting});return g("applied live suggestions"),this.materializePendingFootnoteBodies(),{...P,styleEffects:v}}}return{success:!0,planningSuggestionIds:[],agentFeedback:s}}getAllOperations(){return[]}onRemoteDocumentChange(e){}insertBlock(e,t,n,i){this.beforeOperationSelection=n;const r=this.suggestingMode?le():null,s=e.id||Y(),a=this.getDocument();if(t<0||t>a.children.length)return!1;const l=Qe().getHandlerForBlock(e);this.beforeOperationRelativeSelection=l.allowsInternalCursor()?z(n,this.ydoc,a):null,this.transact(()=>{const g=this.getYContentFragment(),d={...e,id:s};let u;if(d.type==="list"){const p=d,h=new S.XmlElement("list");h.setAttribute("variant",p.variant),p.id&&h.setAttribute("id",p.id),p.startNumber!==void 0&&h.setAttribute("startNumber",String(p.startNumber)),p.numberingChainId&&h.setAttribute("numberingChainId",p.numberingChainId),p.numberingFormat&&h.setAttribute("numberingFormat",p.numberingFormat);const f=[];p.children.forEach(m=>{const y=new S.XmlElement("list-item");Ct(y,m),m.id&&y.setAttribute("id",m.id),m.checked!==void 0&&y.setAttribute("checked",String(m.checked)),m.indentLevel!==void 0&&y.setAttribute("indentLevel",String(m.indentLevel)),m.direction!==void 0&&y.setAttribute("direction",m.direction);const b=new S.XmlText;let k=0;m.children.forEach(I=>{if(I.type==="text"){const v=I.marks?{...I.marks}:void 0;ne(b,k,I.text,v),k+=I.text.length}}),y.insert(0,[b]),f.push(y)}),h.insert(0,f),u=h}else u=l.toYjs(d,this.ydoc);r&&u instanceof S.XmlElement&&(u.setAttribute("id",s),this.suggestionEngine.markInsertedBlockElement(u,r)),g.insert(t,[u])}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=l.allowsInternalCursor()?z(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 zd(this.kernel)}addComment(e,t,n,i,r){return Yd(this.kernel,e,t,n,i,r)}addCommentToRanges(e,t,n){return wr(this.kernel,e,t,n)}addBlockComment(e,t,n){return fa(this.kernel,e,t,n)}addCommentForSuggestion(e,t,n){return this.addCommentForSuggestions([e],t,n)}getSuggestionCommentRanges(e){return Hd(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 wr(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 fa(this.kernel,c,t,s)}return null}replyToComment(e,t,n){return qd(this.kernel,e,t,n)}relinkCommentSuggestionIds(){return Vd(this.kernel,e=>this.suggestionEngine.canResolveLiveSuggestion(e))}resolveCommentsForSettledSuggestions(e){return Kd(this.kernel,e,t=>this.suggestionEngine.canResolveLiveSuggestion(t))}setCommentResolved(e,t){return Jd(this.kernel,e,t)}deleteComment(e){return Gd(this.kernel,e)}isBlockInsideFootnote(e,t){return Qd(e,t)}getFootnotes(){return Zd(this.kernel)}renumberFootnotes(){return St(this.kernel)}materializePendingFootnoteBodies(){return ma(this.kernel)}addPastedFootnoteBodies(e){const t=this.getYNotesFragment();t.insert(t.length,e.map(n=>this.kernel.blockToYjsElement(n))),this.reconcileFootnotes()}reconcileFootnotes(){eu(this.kernel)}insertFootnote(e,t,n,i="footnote"){return nu(this.kernel,e,t,n,i)}setFootnoteBodyText(e,t){return iu(this.kernel,e,t)}replaceFootnoteBodyText(e,t,n,i=!1){return ru(this.kernel,e,t,n,i)}convertAllNoteKinds(e){return ou(this.kernel,e)}removeFootnote(e){return su(this.kernel,e)}blockToYjsElement(e){const t={...e,id:e.id||Y()};return t.type==="list"?ye(t):Qe().getHandlerForBlock(t).toYjs(t,this.ydoc)}insertBlockAfterId(e,t,n,i){const r=G(this.ydoc,t);if(!r)return!1;const{yParent:s,index:a}=r;this.beforeOperationSelection=n;const l=this.suggestingMode?le():null,c=e.id||Y();this.transact(()=>{const d=this.blockToYjsElement(e);l&&d instanceof S.XmlElement&&(d.setAttribute("id",c),this.suggestionEngine.markInsertedBlockElement(d,l)),s.insert(a+1,[d])}),this.setSelectionAfterOperation(i),this.updateAfterOperationRelativeSelection(this.getDocument());const g=this.ensureTrailingParagraph();return l&&this.suggestionEngine.saveLiveSuggestion({id:l,type:"block-insert",blockId:c,label:"Insert",cleanupTrailingParagraphId:g??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?le():null,c=e.id||Y();this.transact(()=>{const d=this.blockToYjsElement(e);l&&d instanceof S.XmlElement&&(d.setAttribute("id",c),this.suggestionEngine.markInsertedBlockElement(d,l)),s.insert(a,[d])}),this.setSelectionAfterOperation(i),this.updateAfterOperationRelativeSelection(this.getDocument());const g=this.ensureTrailingParagraph();return l&&this.suggestionEngine.saveLiveSuggestion({id:l,type:"block-insert",blockId:c,label:"Insert",cleanupTrailingParagraphId:g??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?le():null,c=e.id||Y();return this.transact(()=>{const g=this.blockToYjsElement(e);l&&g instanceof S.XmlElement&&(g.setAttribute("id",c),this.suggestionEngine.markInsertedBlockElement(g,l)),s.insert(0,[g])}),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=Qe().getHandlerForBlock(t);return this.beforeOperationRelativeSelection=a.allowsInternalCursor()?z(n,this.ydoc,r):null,Tt(this.ydoc)&&Zl(this.ydoc),this.transact(()=>{const l=this.getYContentFragment();if(e<0||e>=l.length)return;const c={...t,id:t.id||s.id||Y()},g=l.get(e);if(t.type==="list"&&g instanceof S.XmlElement&&g.nodeName==="list")Ur(g,c);else{const d=c.type==="list"?ye(c):a.toYjs(c,this.ydoc);l.delete(e,1),l.insert(e,[d])}}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=a.allowsInternalCursor()?z(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,g=Qe().getHandlerForBlock(t),d=this.suggestingMode?le():null;let u=t,p=null;if(this.suggestingMode&&d&&s.type==="table"&&t.type==="table"){const h=this.suggestionEngine.buildSuggestedTableChange(s,t,d);if(h)u=h.liveBlock,p=h.record;else if(!this.suggestionEngine.hasSameTableGeometry(s,t))return!1}return this.beforeOperationRelativeSelection=g.allowsInternalCursor()?z(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")Ur(f,h);else{const m=h.type==="list"?ye(h):g.toYjs(h,this.ydoc);l.delete(c,1),l.insert(c,[m])}p&&this.suggestionEngine.saveLiveSuggestion(p)}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=g.allowsInternalCursor()?z(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=z(n,this.ydoc,r),this.transact(()=>{const g=a instanceof S.XmlElement?a.getAttribute("id"):void 0,d=new S.XmlElement("paragraph");d.setAttribute("id",t.id||g||Y()),t.heading&&d.setAttribute("heading",String(t.heading)),t.align&&d.setAttribute("align",t.align),t.lineSpacing!==void 0&&d.setAttribute("lineSpacing",String(t.lineSpacing)),pn(d,t);{const m=Ye(t);m!==void 0&&d.setAttribute("pagination",m)}t.styleId!==void 0&&d.setAttribute("styleId",t.styleId),t.direction!==void 0&&d.setAttribute("direction",t.direction),t.tabStops!==void 0&&d.setAttribute("tabStops",t.tabStops),t.borders!==void 0&&d.setAttribute("borders",t.borders),t.shading!==void 0&&d.setAttribute("shading",t.shading),t.oxmlAttrs!==void 0&&d.setAttribute("oxmlAttrs",t.oxmlAttrs),t.oxmlPPr!==void 0&&d.setAttribute("oxmlPPr",t.oxmlPPr);const u=Re(t.leftIndent);u!==void 0&&d.setAttribute("leftIndent",String(u));const p=De(t.firstLineIndent);p!==void 0&&d.setAttribute("firstLineIndent",String(p));const h=new S.XmlText;let f=0;t.children.forEach(m=>{if(m.type==="text"){const y={...m.marks||{}};ne(h,f,m.text,y),f+=m.text.length}}),d.insert(0,[h]),l.delete(c,1),l.insert(c,[d])}),this.setSelectionAfterOperation(i),this.afterOperationRelativeSelection=z(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=Qe().getHandlerForBlock(a);return this.beforeOperationRelativeSelection=l?.allowsInternalCursor()?z(i,this.ydoc,s):null,this.transact(()=>{const c=this.getYContentFragment().get(e);if(!(c instanceof S.XmlElement))return;let g=0;for(let d=0;d<c.length;d++){const u=c.get(d);if(u instanceof S.XmlElement&&u.nodeName==="list-item"){if(g===t){n?u.setAttribute("checked","true"):u.removeAttribute("checked");return}g++}}}),this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=l?.allowsInternalCursor()?z(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 g=Qe().getHandlerForBlock(a);return this.beforeOperationRelativeSelection=g?.allowsInternalCursor()?z(i,this.ydoc,s):null,this.transact(()=>{if(!(c instanceof S.XmlElement))return;let d=0;for(let u=0;u<c.length;u++){const p=c.get(u);if(p instanceof S.XmlElement&&p.nodeName==="list-item"){if(d===t){n?p.setAttribute("checked","true"):p.removeAttribute("checked");return}d++}}}),this.setSelectionAfterOperation(r),this.afterOperationRelativeSelection=g?.allowsInternalCursor()?z(r,this.ydoc,this.getDocument()):null,!0}};hl.DEFERRED_IDENTITY_REPAIR_MS=1500;let vi=hl;function no(o,e,t){const n=i=>i&&i.block===e?{...i,offset:vi.remapOffsetAcrossReplacementNormalization(i.offset,t)}:i;return{anchor:n(o.anchor),focus:n(o.focus)}}const of=Object.freeze(Object.defineProperty({__proto__:null,DEFAULT_FONT_FAMILY:Ee,DocumentMutator:vi,MAX_BULK_LIVE_SUGGESTION_RESOLUTION_PASSES:tl,copyMarksForUserInsertion:nl,enrichReplaceBlockFeedbackWithChangeSummary:dl,extractTextForChangeSummary:$e,parseLayeredInsertion:fn,parseSuggestionPriorAttributes:ki,remapSelectionAcrossReplacementNormalization:no,sanitizeSuggestionPriorAttributes:hn},Symbol.toStringTag,{value:"Module"}));export{Z as A,vi as D,gi as P,tg as a,Zc as b,Qi as c,rs as d,be as e,Ki as f,Gi as g,Mt as h,oa as i,$n as j,Go as k,Oc as l,Rc as m,ts as n,is as o,os as p,Ui as q,Yc as r,et as s,Jo as t,ns as u,of as v};
|