revise 2.2.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (134) hide show
  1. package/CHANGELOG.md +47 -1182
  2. package/LICENSE +24 -41
  3. package/README.md +103 -26
  4. package/agent.d.ts +139 -0
  5. package/chunks/chunk-U5X47PZ6.js +135 -0
  6. package/chunks/chunk-U6YKQBKL.js +15 -0
  7. package/chunks/chunk-ZLQVPMBN.js +1650 -0
  8. package/chunks/package-5SHL5FOJ.js +14 -0
  9. package/chunks/render-QD5VWKSV.js +109 -0
  10. package/cli-output.schema.json +1984 -0
  11. package/cli.js +3604 -0
  12. package/document.d.ts +320 -0
  13. package/docx.d.ts +73 -0
  14. package/errors.d.ts +14 -0
  15. package/index.d.ts +13 -975
  16. package/index.js +31 -1
  17. package/legacy/editor.d.ts +19 -0
  18. package/legacy/editor.js +16 -0
  19. package/legacy/server.d.ts +37 -0
  20. package/legacy/server.js +25 -0
  21. package/legacy/style.css +2 -0
  22. package/package.d.ts +23 -0
  23. package/package.json +49 -55
  24. package/render.d.ts +27 -0
  25. package/FONT-LICENSE-HAN-EXT-B.txt +0 -91
  26. package/FONT-LICENSE-KATEX.txt +0 -95
  27. package/FONT-LICENSE-LIBERATION.txt +0 -102
  28. package/FONT-LICENSE-NOTO-MULTILINGUAL.txt +0 -93
  29. package/FONT-LICENSE-NOTO-SANS-SC.txt +0 -93
  30. package/FONT-LICENSE-NOTO.txt +0 -94
  31. package/FONT-LICENSE-SOURCE-CODE-PRO.txt +0 -94
  32. package/FONT-LICENSE-SOURCE-SERIF-4.txt +0 -93
  33. package/THIRD-PARTY-NOTICES.md +0 -3376
  34. package/assets/historyMaterializeWorker-B51R08XN.js +0 -612
  35. package/backend.d.ts +0 -161
  36. package/backend.js +0 -3
  37. package/chunks/AgentPageRenderer-CH8kSTJn.js +0 -1
  38. package/chunks/AgentPageRenderer-P23XVguo.js +0 -1
  39. package/chunks/AttachmentDocumentImporter-B1WOaa7d.js +0 -1
  40. package/chunks/AttachmentDocumentImporter-CT_PJp_e.js +0 -1
  41. package/chunks/BidiText-Swm5fl9J.js +0 -160
  42. package/chunks/ColorParserFull-BKH72fK8.js +0 -446
  43. package/chunks/DocumentMutator-btiDK57e.js +0 -31
  44. package/chunks/DocumentScrubber-CMPfm_HF.js +0 -18
  45. package/chunks/DocumentScrubber-Cm2kH8op.js +0 -1
  46. package/chunks/DocumentScrubber-bJoKijol.js +0 -1
  47. package/chunks/DocumentStylesheet-DreoD7sD.js +0 -7
  48. package/chunks/DocxConverter-BcVG-p5K.js +0 -13
  49. package/chunks/DocxConverter-D2bO5RE-.js +0 -1125
  50. package/chunks/DocxConverter-haCfRuWb.js +0 -13
  51. package/chunks/DocxGraft-BRKh4mHQ.js +0 -1
  52. package/chunks/DocxGraft-BxSQtl12.js +0 -7
  53. package/chunks/DocxGraft-C9MBQCnf.js +0 -1
  54. package/chunks/FileImporter-CszqRfVU.js +0 -1
  55. package/chunks/FileImporter-DObFoCCn.js +0 -1
  56. package/chunks/HorizontalRuleOrnaments-gmUZ3R7Q.js +0 -3
  57. package/chunks/HtmlConverter-DwXB4IDh.js +0 -267
  58. package/chunks/ListNumbering-Qlu6AuRZ.js +0 -23
  59. package/chunks/MarkdownConverter-CUC8GgsS.js +0 -57
  60. package/chunks/MathRenderer-DT6GyJXb.js +0 -68
  61. package/chunks/OdtConverter-7h9HHMpL.js +0 -125
  62. package/chunks/OdtConverter-Ct4qypJk.js +0 -6
  63. package/chunks/OdtConverter-DFl__sJc.js +0 -6
  64. package/chunks/OfficeImportShared-BY6FdZ8d.js +0 -1
  65. package/chunks/OfficeImportShared-BrZoDM0j.js +0 -30
  66. package/chunks/OfficeImportShared-Bvm-mOyj.js +0 -1
  67. package/chunks/ParagraphDiffAnalysis-DrmStvmz.js +0 -36
  68. package/chunks/PdfConverter-1wyvoT7X.js +0 -21
  69. package/chunks/PdfConverter-BAoEHILo.js +0 -21
  70. package/chunks/PdfConverter-CKEvFj11.js +0 -448
  71. package/chunks/PdfImportService-BhLPp5uG.js +0 -2
  72. package/chunks/PdfImportService-xbzrN__L.js +0 -2
  73. package/chunks/RtfConverter-Bxn-enp8.js +0 -15
  74. package/chunks/RtfConverter-LZPzBDSr.js +0 -15
  75. package/chunks/RtfConverter-_bacXqr1.js +0 -186
  76. package/chunks/TableBorders-CwnF3jvH.js +0 -30
  77. package/chunks/TableGrid-DbroRucl.js +0 -12
  78. package/chunks/TextFileDecoder--rsVs3NR.js +0 -9
  79. package/chunks/TxtConverter-C7FOwHpH.js +0 -14
  80. package/chunks/UnicodeUtils-CXtusU4g.js +0 -10
  81. package/chunks/XmlConverter-7oo8oeQB.js +0 -2
  82. package/chunks/XmlConverter-DGORHJcZ.js +0 -96
  83. package/chunks/XmlConverter-DeLHReK_.js +0 -2
  84. package/chunks/__vite-browser-external-l0sNRNKZ.js +0 -0
  85. package/chunks/_commonjsHelpers-DaMA6jEr.js +0 -2
  86. package/chunks/_revise-sdk-lazy-harfbuzz-CDWdjF9f.js +0 -1
  87. package/chunks/_revise-sdk-lazy-harfbuzz-X8gnYTZL.js +0 -1
  88. package/chunks/ar-ComXvtmh.js +0 -13
  89. package/chunks/backend-DecaBz-I.js +0 -490
  90. package/chunks/base64-sSPOzq-u.js +0 -198
  91. package/chunks/browser-module-CFmqfGkE.js +0 -1791
  92. package/chunks/browser-module-Dj5o3kuL.js +0 -3
  93. package/chunks/browser-module-UuM_O36W.js +0 -3
  94. package/chunks/bundle.min-DRpfgV69.js +0 -782
  95. package/chunks/capture-1btcWcPF.js +0 -9
  96. package/chunks/carrier-DQeng6yq.js +0 -6
  97. package/chunks/de-BkbpIKxx.js +0 -13
  98. package/chunks/es-CKkXujOF.js +0 -13
  99. package/chunks/fil-piIHMc8F.js +0 -13
  100. package/chunks/footnoteFlatten-DUQticYy.js +0 -6
  101. package/chunks/fr-DuA8qLje.js +0 -13
  102. package/chunks/graftExport-CYnStOdU.js +0 -82
  103. package/chunks/html2canvas.esm-CntiHiYW.js +0 -997
  104. package/chunks/index-2TBhRkX7.js +0 -387
  105. package/chunks/index-BWdRWxoH.js +0 -1807
  106. package/chunks/index-Bf14eTEW.js +0 -1096
  107. package/chunks/index-BwcX_r62.js +0 -387
  108. package/chunks/index.es-CI0QPo8w.js +0 -780
  109. package/chunks/index.es-CI7cDExj.js +0 -5
  110. package/chunks/index.es-DHpGt6Y5.js +0 -5
  111. package/chunks/ja-DgrSs555.js +0 -13
  112. package/chunks/jspdf.es.min--GshOuIm.js +0 -77
  113. package/chunks/jspdf.es.min-DU74zN8b.js +0 -1792
  114. package/chunks/jspdf.es.min-DurJZ1zW.js +0 -77
  115. package/chunks/jszip.min-CPW0h1Kx.js +0 -476
  116. package/chunks/katex-DWj8TvwO.js +0 -1462
  117. package/chunks/pdf-BLWDCiFF.js +0 -1828
  118. package/chunks/persistInlineDocumentImages-DQj2iaqg.js +0 -1
  119. package/chunks/pseudoLocale-BoYTjmiK.js +0 -1
  120. package/chunks/pseudoLocale-DG2NnZmz.js +0 -1
  121. package/chunks/purify.es-BwLardii.js +0 -107
  122. package/chunks/serverDocumentSession-CJ1EH3Tp.js +0 -15
  123. package/chunks/signatures-Bwt_OGik.js +0 -17
  124. package/chunks/suggestionAuthorship-B-IuLQlE.js +0 -1
  125. package/chunks/tree-sitter-D6zWWUMP.js +0 -4
  126. package/chunks/wasmInline.generated-CBYFkdSM.js +0 -1
  127. package/chunks/web-tree-sitter-BXGZGnNj.js +0 -2
  128. package/chunks/zh-9OF3SWWO.js +0 -13
  129. package/full.js +0 -1
  130. package/root.d.ts +0 -5
  131. package/root.js +0 -2
  132. package/serverToolContract.d.ts +0 -391
  133. package/serverToolInputs.generated.d.ts +0 -250
  134. package/style.css +0 -1
@@ -1,13 +0,0 @@
1
- import{ah as Ae,ai as gi,aj as Pr,ak as ui,c as fi,h as wi,al as Ar,am as bi,an as yi,ao as vi,ap as Te,E as xi,aq as Si,ar as Ii,as as ki,H as Dt,at as Bt,au as Pi,av as Ai,R as It,aw as Ci,ax as qt,I as qe,ay as Cr,az as Ni,aA as Nr,aB as Ti,aC as Vt,aD as Mi,aE as Ei,aF as Di,aG as Bi,q as Ri,t as Fi,G as Oi,X as $i,aH as Tr,aI as Li,aJ as _i,a8 as Xi,a9 as Wi,aK as zi,aL as Hi,aM as ji,aN as Yt,aO as Gi,aP as Ji,M as Ui,aQ as Zi,aR as Ki,aS as qi,aT as Mr,F as Vi,aU as Yi,m as Qt,aV as Er,aW as Qi,aX as en,aY as tn,aZ as Dr,a_ as er,a$ as rn,b0 as nn}from"./index-BwcX_r62.js";const Br=()=>new XMLSerializer,Rr=new Set(["w:rStyle","w:b","w:i","w:u","w:strike","w:dstrike","w:smallCaps","w:caps","w:vanish","w:lang","w:spacing","w:vertAlign","w:color","w:highlight","w:shd","w:rFonts","w:sz","w:rPrChange","w:bCs","w:iCs","w:szCs","w:highlightCs","w:ins","w:del","w:rtl","w:specVanish","w:imprint","w:emboss","w:snapToGrid"]),Fr=new Set(["w:pStyle","w:keepNext","w:keepLines","w:widowControl","w:bidi","w:jc","w:ind","w:pageBreakBefore","w:spacing","w:contextualSpacing","w:outlineLvl","w:numPr","w:pBdr","w:shd","w:tabs","w:rPr","w:sectPr","w:pPrChange"]),Or=new Set(["w:tblStyle","w:tblW","w:jc","w:tblInd","w:tblBorders","w:tblLayout","w:tblCellMar","w:tblPrChange"]),$r=new Set(["w:tblHeader","w:ins","w:del","w:trPrChange"]),Lr=new Set(["w:tcW","w:gridSpan","w:vMerge","w:tcBorders","w:shd","w:tcMar","w:vAlign","w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"]),_r=new Set(["w:pgSz","w:pgMar","w:pgNumType","w:lnNumType","w:cols","w:type","w:docGrid","w:titlePg","w:headerReference","w:footerReference","w:sectPrChange","w:rPr"]);function rt(O,e){if(!O)return;let r="";const t=Br();for(let i=0;i<O.children.length;i++){const n=O.children[i];e.has(n.tagName)||(r+=t.serializeToString(n))}return r?rr(r):void 0}function tr(O){if(!O||O.attributes.length===0)return;const e={};for(let i=0;i<O.attributes.length;i++){const n=O.attributes[i];n.name==="xmlns"||n.name.startsWith("xmlns:")||(e[n.name]=n.value)}const r=Object.keys(e).sort();if(r.length===0)return;const t={};for(const i of r)t[i]=e[i];return JSON.stringify(t)}function rr(O){if(!/[\n\r\t]/.test(O))return O;let e="",r=!1,t=null;for(let i=0;i<O.length;i++){const n=O[i];if(t){n===t?(t=null,e+=n):n===`
2
- `?e+="&#10;":n==="\r"?e+="&#13;":n===" "?e+="&#9;":e+=n;continue}r&&(n==='"'||n==="'")?t=n:n==="<"?r=!0:n===">"&&(r=!1),e+=n}return e}function ir(O){const e=rr(Br().serializeToString(O));let r;const t=O.getElementsByTagName("o:OLEObject")[0];if(t)r=t.getAttribute("ProgID")??void 0;else if(O.tagName==="w:altChunk")r=O.getAttribute("r:id")??void 0;else{const i=O.getElementsByTagName("a:graphicData")[0]?.getAttribute("uri")?.split("/").filter(Boolean).pop();i&&i!=="picture"&&(r=i)}return{xml:e,tagName:O.tagName,...r?{detail:r}:{}}}function nr(O){return O.includes("http://schemas.openxmlformats.org/officeDocument/2006/relationships")}const Xr=new Set(["w:p","w:tbl","w:sdt","w:customXml","w:sectPr","w:bookmarkStart","w:bookmarkEnd","w:commentRangeStart","w:commentRangeEnd","w:moveFromRangeStart","w:moveFromRangeEnd","w:moveToRangeStart","w:moveToRangeEnd","w:permStart","w:permEnd","w:ins","w:del","w:moveFrom","w:moveTo","w:proofErr","w:tcPr","w:trPr","w:tblPr","w:tblGrid","w:tblPrEx","w:pPr"]),on=/^[A-Za-z_][\w.-]*(?::[\w.-]+)?$/;function Wr(O,e){let r;try{r=JSON.parse(O)}catch{return""}if(r===null||typeof r!="object"||Array.isArray(r))return"";let t="";for(const[i,n]of Object.entries(r)){if(typeof n!="string"||!on.test(i)||e?.has(i))continue;const s=n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/"/g,"&quot;");t+=` ${i}="${s}"`}return t}const sn=Object.freeze(Object.defineProperty({__proto__:null,KNOWN_BODY_TAGS:Xr,KNOWN_PPR_TAGS:Fr,KNOWN_RPR_TAGS:Rr,KNOWN_SECTPR_TAGS:_r,KNOWN_TBLPR_TAGS:Or,KNOWN_TCPR_TAGS:Lr,KNOWN_TRPR_TAGS:$r,attrsJsonToXmlAttributes:Wr,captureRawElement:ir,extractElementAttrsJson:tr,extractOpaqueChildrenXml:rt,stabilizeSerializedXml:rr,xmlReferencesRelationships:nr},Symbol.toStringTag,{value:"Module"})),an="http://schemas.openxmlformats.org/officeDocument/2006/math",zr=`<m:oMath xmlns:m="${an}">`,ln=new Set("∑∏∐∫∬∭∮∯∰∱∲∳⋀⋁⋂⋃⨀⨁⨂⨄⨆".split("")),cn=new Set(["sin","cos","tan","cot","sec","csc","arcsin","arccos","arctan","sinh","cosh","tanh","coth","log","ln","lg","exp","det","dim","ker","deg","gcd","hom","arg","max","min","sup","inf","lim","liminf","limsup","Pr"]),dn=new Set(["lim","liminf","limsup","max","min","sup","inf","Pr"]),Hr={"^":"̂","ˆ":"̂","̂":"̂","~":"̃","˜":"̃","̃":"̃","ˉ":"̄","¯":"̄","̄":"̄","˙":"̇","̇":"̇","¨":"̈","̈":"̈","ˊ":"́","´":"́","́":"́","ˋ":"̀","`":"̀","̀":"̀","ˇ":"̌","̌":"̌","˘":"̆","̆":"̆","→":"⃗","⃗":"⃗"},pn=new Set(["‾","¯","_","―","−"]),hn=new Set(["⏞","⏟","⏜","⏝","⎴","⎵"]),mn=new Set(["⁡","⁢","⁣","⁤"]),or={normal:'<m:sty m:val="p"/>',bold:'<m:sty m:val="b"/>',italic:'<m:sty m:val="i"/>',"bold-italic":'<m:sty m:val="bi"/>',"double-struck":'<m:scr m:val="double-struck"/><m:sty m:val="p"/>',script:'<m:scr m:val="script"/>',"bold-script":'<m:scr m:val="script"/><m:sty m:val="b"/>',fraktur:'<m:scr m:val="fraktur"/>',"bold-fraktur":'<m:scr m:val="fraktur"/><m:sty m:val="b"/>',"sans-serif":'<m:scr m:val="sans-serif"/><m:sty m:val="p"/>',monospace:'<m:scr m:val="monospace"/><m:sty m:val="p"/>'};function jr(O){return O.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function it(O){return jr(O)}function Le(O){return Array.from(O.children)}function Fe(O){return(O.textContent??"").replace(/[⁡-⁤]/g,"")}function ve(O){return O.localName.toLowerCase()}function sr(O){let e=O;for(;["mrow","mstyle","mpadded","semantics"].includes(ve(e))&&Le(e).filter(r=>!Rt(r)).length===1;)e=Le(e).filter(r=>!Rt(r))[0];return e}function Rt(O){return ve(O)==="mo"&&mn.has((O.textContent??"").trim())}function Ft(O){if(!O)return null;const e=sr(O);if(ve(e)!=="mo")return null;const r=Fe(e).trim();return ln.has(r)?r:null}function Ot(O){if(!O)return null;const e=sr(O);if(!["mi","mo"].includes(ve(e)))return null;const r=Fe(e).trim();return cn.has(r)?r:null}const gn=new Set("+-−=<>≤≥≠≈≡∼≃≅∝,;:∣∈∉⊂⊆⊃⊇→←↔⇒⇐⇔".split(""));function un(O){return ve(O)==="mo"&&gn.has(Fe(O).trim())}function Gr(O,e){let r=e;for(;r<O.length&&!un(O[r]);)r+=1;return r}function Jr(O){return!!O&&ve(O)==="mo"&&O.getAttribute("fence")==="true"}function He(O,e){if(!O)return"";const r=/^\s+$/.test(O)?`${O}​`:O,t=/^\s|\s$/.test(r)?' xml:space="preserve"':"";return`<m:r>${e?`<m:rPr>${e}</m:rPr>`:""}<m:t${t}>${jr(r)}</m:t></m:r>`}function fn(O,e){const r=ve(O),t=Fe(O);if(!t)return"";if(r==="mtext"||r==="ms")return He(t,"<m:nor/>");const i=O.getAttribute("mathvariant")??e.mathvariant;return i&&or[i]?He(t,or[i]):r==="mi"&&[...t].length>1?He(t,'<m:sty m:val="p"/>'):He(t,"")}function ne(O,e){return`<m:${O}>${e}</m:${O}>`}function Ur(O,e,r,t,i){return`<m:nary><m:naryPr>${`<m:chr m:val="${it(O)}"/><m:limLoc m:val="${e}"/>`+(r===null?'<m:subHide m:val="1"/>':"")+(t===null?'<m:supHide m:val="1"/>':"")}</m:naryPr>`+ne("sub",r??"")+ne("sup",t??"")+ne("e",i)+"</m:nary>"}function Zr(O,e){return`<m:func>${ne("fName",O)}${ne("e",e)}</m:func>`}function Kr(O){return parseFloat(O.getAttribute("width")??"")>0?" ":""}function wn(O){return ve(O)==="mrow"&&O.children.length===0&&!Fe(O).trim()}function je(O,e){const r=O.filter(i=>!Rt(i)&&!wn(i));if(r.length>=2&&Jr(r[0])){const i=r[r.length-1],n=Jr(i),s=r.slice(1,n?-1:void 0),o=Fe(r[0]).trim(),a=n?Fe(i).trim():"";return`<m:d><m:dPr><m:begChr m:val="${it(o)}"/><m:endChr m:val="${it(a)}"/></m:dPr>`+ne("e",je(s,e))+"</m:d>"}let t="";for(let i=0;i<r.length;i+=1){const n=r[i],s=ve(n),o=r[i+1];if(["msub","msup","msubsup","munder","mover","munderover"].includes(s)&&Ft(Le(n)[0])){const[d,p,m]=Le(n),h=Ft(d),g=s.startsWith("mu")?"undOvr":"subSup",w=["msub","msubsup","munder","munderover"].includes(s)?he(p,e):null,u=s==="msubsup"||s==="munderover"?he(m,e):s==="msup"||s==="mover"?he(p,e):null,f=Gr(r,i+1);t+=Ur(h,g,w,u,je(r.slice(i+1,f),e)),i=f-1;continue}if(s==="mo"&&Ft(n)){const d=Gr(r,i+1);t+=Ur(Ft(n),"undOvr",null,null,je(r.slice(i+1,d),e)),i=d-1;continue}const a=["msub","munder"].includes(s)?Ot(Le(n)[0]):null;if(a&&dn.has(a)&&o){const[d,p]=Le(n),m=`<m:limLow>${ne("e",He(Ot(d),'<m:sty m:val="p"/>'))}${ne("lim",he(p,e))}</m:limLow>`;t+=Zr(m,he(o,e)),i+=1;continue}if(Ot(n)&&o){t+=Zr(He(Ot(n),'<m:sty m:val="p"/>'),he(o,e)),i+=1;continue}if(s==="mtext"||s==="mspace"){let d="",p=i;for(;r[p]&&["mtext","mspace"].includes(ve(r[p]));)d+=ve(r[p])==="mtext"?Fe(r[p]):Kr(r[p]),p+=1;i=p-1;const m=d.replace(/\s{2,}/g," ");m&&(t+=He(m,"<m:nor/>"));continue}const l=s==="mi"?n.getAttribute("mathvariant"):null;if(l){let d=Fe(n);for(;r[i+1]&&ve(r[i+1])==="mi"&&r[i+1].getAttribute("mathvariant")===l;)i+=1,d+=Fe(r[i]);t+=He(d,or[l]??"");continue}t+=he(n,e)}return t}function he(O,e){if(!O)return"";const r=ve(O),t=Le(O);switch(r){case"math":case"semantics":case"mrow":case"mpadded":case"merror":return je(t,e);case"mstyle":{const i=O.getAttribute("mathvariant");return je(t,i?{...e,mathvariant:i}:e)}case"annotation":case"annotation-xml":case"mphantom":case"none":case"mprescripts":return"";case"mi":case"mn":case"mo":case"mtext":case"ms":return Rt(O)?"":fn(O,e);case"mspace":{const i=Kr(O);return i?He(i,"<m:nor/>"):""}case"mfrac":{const i=O.getAttribute("linethickness");return`<m:f>${i!==null&&parseFloat(i)===0?'<m:fPr><m:type m:val="noBar"/></m:fPr>':""}`+ne("num",he(t[0],e))+ne("den",he(t[1],e))+"</m:f>"}case"msqrt":return'<m:rad><m:radPr><m:degHide m:val="1"/></m:radPr><m:deg/>'+ne("e",je(t,e))+"</m:rad>";case"mroot":return"<m:rad>"+ne("deg",he(t[1],e))+ne("e",he(t[0],e))+"</m:rad>";case"msub":return`<m:sSub>${ne("e",he(t[0],e))}${ne("sub",he(t[1],e))}</m:sSub>`;case"msup":return`<m:sSup>${ne("e",he(t[0],e))}${ne("sup",he(t[1],e))}</m:sSup>`;case"msubsup":return`<m:sSubSup>${ne("e",he(t[0],e))}`+ne("sub",he(t[1],e))+ne("sup",he(t[2],e))+"</m:sSubSup>";case"mover":case"munder":return bn(O,r==="mover"?"top":"bot",e);case"munderover":{const[i,n,s]=t,o=`<m:limLow>${ne("e",he(i,e))}${ne("lim",he(n,e))}</m:limLow>`;return`<m:limUpp>${ne("e",o)}${ne("lim",he(s,e))}</m:limUpp>`}case"mtable":return"<m:m>"+t.filter(i=>["mtr","mlabeledtr"].includes(ve(i))).map(i=>"<m:mr>"+Le(i).filter(n=>ve(n)==="mtd").map(n=>ne("e",je(Le(n),e))).join("")+"</m:mr>").join("")+"</m:m>";case"menclose":{const i=je(t,e),n=O.getAttribute("notation")??"";return/\bbox\b|roundedbox/.test(n)?`<m:borderBox>${ne("e",i)}</m:borderBox>`:i}case"mfenced":{const i=O.getAttribute("open")??"(",n=O.getAttribute("close")??")";return`<m:d><m:dPr><m:begChr m:val="${it(i)}"/><m:endChr m:val="${it(n)}"/></m:dPr>`+t.map(s=>ne("e",he(s,e))).join("")+"</m:d>"}default:return je(t,e)}}function bn(O,e,r){const[t,i]=Le(O),n=he(t,r),s=i?sr(i):void 0,o=s&&ve(s)==="mo"?Fe(s).trim():"";if(o&&pn.has(o))return`<m:bar><m:barPr><m:pos m:val="${e}"/></m:barPr>${ne("e",n)}</m:bar>`;if(o&&hn.has(o))return`<m:groupChr><m:groupChrPr><m:chr m:val="${it(o)}"/><m:pos m:val="${e}"/><m:vertJc m:val="${e==="top"?"bot":"top"}"/></m:groupChrPr>`+ne("e",n)+"</m:groupChr>";const a=O.getAttribute(e==="top"?"accent":"accentunder")==="true";if(e==="top"&&o&&(a||Hr[o])){const d=Hr[o]??o;return`<m:acc><m:accPr><m:chr m:val="${it(d)}"/></m:accPr>${ne("e",n)}</m:acc>`}const l=e==="top"?"limUpp":"limLow";return`<m:${l}>${ne("e",n)}${ne("lim",he(i,r))}</m:${l}>`}function yn(O){return new DOMParser().parseFromString(O,"text/html").querySelector("math")}function vn(O){const e=yn(O);if(!e)throw new Error("mathmlToOmml: no <math> element in input");return`${zr}${he(e,{})}</m:oMath>`}const qr="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",fe=class ar{static async parseFile(e,r){if(!e.name.toLowerCase().endsWith(".docx"))throw new Error(`DocxConverter only supports .docx files, got: ${e.name}`);return this.parseDocxFile(e,r)}static async parseDocxFile(e,r){const t=await e.arrayBuffer(),i=await Pr.loadAsync(t),n=await i.file("word/document.xml")?.async("string");if(!n)return{type:"doc",children:[this.createEmptyParagraph()]};const s=this.parseDocumentXml(n);if(!s)return{type:"doc",children:[this.createEmptyParagraph()]};const o=await this.loadOOXMLPackageContext(i,n),a=await this.parseDocumentPageLayoutFromPackage(n,i,s),l=await i.file("word/fontTable.xml")?.async("string"),d=this.parseFontTableXml(l),p=await i.file("word/settings.xml")?.async("string"),m=!!(p&&/<w:autoHyphenation(?![^>]*w:val="(?:0|false)")[^>]*\/?>/.test(p)),h=r?.retainSource?new Map:void 0,g=await this.parseStructuredDocxDocument(n,a,o,s,h),w=await i.file("docProps/custom.xml")?.async("string");if(w){const B=this.parseDocumentXml(w),$=(B&&Array.from(B.getElementsByTagNameNS("*","property")).find(z=>z.getAttribute("name")==="Revise.BlockSpacingPx"))?.textContent?.trim(),W=$?Number($):NaN;Number.isFinite(W)&&W>=0&&W<=192&&(g.pageLayout={...g.pageLayout??{},blockSpacingPx:W})}m&&(g.pageLayout={...g.pageLayout??{},hyphenationEnabled:!0}),d&&(g.fontSubstitutes=d,ui(d));const u=await i.file("word/footnotes.xml")?.async("string"),f=await i.file("word/endnotes.xml")?.async("string"),b=new Map;u&&await this.collectNotesFromXml(g,u,"w:footnote","docxfn","footnote",b,o),f&&await this.collectNotesFromXml(g,f,"w:endnote","docxen","endnote",b,o),this.finalizeImportedFootnoteRefs(g,b);const I=await i.file("word/comments.xml")?.async("string");if(I){const B=await i.file("word/commentsExtended.xml")?.async("string");this.attachCommentsFromXml(g,I,B,o)}await this.attachHeadersFootersFromPackage(g,n,i,o,s);const y=await i.file("docProps/core.xml")?.async("string");if(y){const B=this.parseCoreProperties(y);B&&(g.coreProperties=B)}return h&&fi(g,h,await wi(new Uint8Array(t))),g}static parseCoreProperties(e){const r=this.parseDocumentXml(e);if(!r)return;const t=new Set(this.CORE_PROPERTY_LOCAL_NAMES),i={},n=r.documentElement;for(let s=0;s<n.children.length;s++){const o=n.children[s],a=o.tagName.split(":").pop()??o.tagName;if(!t.has(a))continue;const l=o.textContent??"";l.trim().length!==0&&(i[a]=l)}return Object.keys(i).length>0?i:void 0}static readHeaderFooterReferences(e,r){const t={};for(let i=0;i<e.children.length;i++){const n=e.children[i];if(n.tagName!==r)continue;const s=n.getAttribute("w:type")??"default",o=s==="first"||s==="even"?s:"default",a=n.getAttribute("r:id")??n.getAttribute("relationships:id");a&&(t[o]=a)}return t}static resolveSectionHeaderFooterReferences(e){const r=[];for(let t=0;t<e.length;t++){const i=r[t-1]??{header:{},footer:{}};r.push({header:{...i.header,...this.readHeaderFooterReferences(e[t],"w:headerReference")},footer:{...i.footer,...this.readHeaderFooterReferences(e[t],"w:footerReference")}})}return r}static async attachHeadersFootersFromPackage(e,r,t,i,n){const s=(n??this.parseDocumentXml(r))?.getElementsByTagName("w:body")[0];if(!s)return;const o=this.findAllSectionProperties(s);if(o.length===0)return;const a=this.resolveSectionHeaderFooterReferences(o),l=o.length-1,d=a[l],p=new Map,m=async $=>{const W=p.get($);if(W)return W;const z={paragraphs:[],images:[]},D=i?.relationships.get($);if(D){const T=D.target.startsWith("word/")?D.target:`word/${D.target.replace(/^\//,"")}`,F=await t.file(T)?.async("string");if(F){const S=T.split("/").pop()??T,E=await t.file(`word/_rels/${S}.rels`)?.async("string");if(z.paragraphs=await this.parseHeaderFooterPart(F,E?this.parseRelationshipsXml(E,T):void 0),!e.watermark){const M=this.parseVmlWatermark(F);M&&(e.watermark=M)}z.images=await this.parseHeaderFooterImages(F,T,t,i)}}return p.set($,z),z},h=async $=>(await m($)).paragraphs,g=["default","first","even"],w=[],u=async($,W)=>{const z={};for(const D of g){const T=$[D];if(!T)continue;const F=await m(T);F.paragraphs.length>0&&(z[D]=F.paragraphs);for(const S of F.images)w.push({side:W,slot:D,...S})}return Object.keys(z).length>0?z:void 0},f=await u(d.header,"header"),b=await u(d.footer,"footer");f&&(e.headers=f),b&&(e.footers=b),w.length>0&&(e.chromeImages=w);const I=[];for(let $=0;$<l;$++)for(const W of["header","footer"])for(const z of g){const D=a[$][W][z],T=d[W][z];if(D===T)continue;const F=D?await h(D):[];I.push(Ar(W,z,F.length>0?bi(F):void 0,void 0,$))}const y=[],B=new Set(I.map($=>`${$.side}/${$.slot}/${$.sectionIndex}`));for(let $=0;$<o.length;$++)if(o[$].getElementsByTagName("w:titlePg").length!==0)for(const W of["header","footer"]){const z=a[$][W].first;if((z?await h(z):[]).length>0||!a[$][W].default)continue;const D=$===l?void 0:$;B.has(`${W}/first/${D}`)||y.push(Ar(W,"first",void 0,void 0,D))}(I.length>0||y.length>0)&&(e.chrome=[...yi(e.headers,e.footers),...I,...y])}static parseVmlWatermark(e){if(!e.includes("v:textpath"))return;const r=this.parseDocumentXml(e);if(!r)return;const t=r.getElementsByTagName("v:textpath");for(let i=0;i<t.length;i++){const n=t[i],s=(n.getAttribute("string")??"").trim();if(!s)continue;let o=n.parentNode;for(;o&&o.tagName!=="v:shape";)o=o.parentNode;const a=(o?.getAttribute("style")??"").match(/rotation:\s*(-?\d+(?:\.\d+)?)/),l=a?(parseFloat(a[1])%360+360)%360:0,d=this.vmlFillColorToHex(o?.getAttribute("fillcolor")??"");let p;const m=o?.getElementsByTagName("v:fill")[0]?.getAttribute("opacity");if(m){const w=m.endsWith("f")?parseFloat(m)/65536:parseFloat(m);Number.isFinite(w)&&w>0&&w<=1&&(p=Math.abs(w-Tr)<.05?void 0:w)}const h=(n.getAttribute("style")??"").match(/font-size:\s*(\d+(?:\.\d+)?)pt/),g=h?parseFloat(h[1]):void 0;return vi({text:s,...d?{color:d}:{},...p!==void 0?{opacity:p}:{},diagonal:l!==0,...g&&g>2?{fontSizePx:Math.round(g*(4/3))}:{}})}}static vmlFillColorToHex(e){const r=e.trim().toLowerCase();if(r){if(r.startsWith("#")){const t=r.slice(1,7);return/^[0-9a-f]{6}$/.test(t)?`#${t.toUpperCase()}`:void 0}return{silver:"#C0C0C0",gray:"#808080",grey:"#808080",black:"#000000",red:"#FF0000",blue:"#0000FF",green:"#008000",white:"#FFFFFF"}[r]}}static async parseHeaderFooterImages(e,r,t,i){if(!i||!e.includes("w:drawing"))return[];const n=this.parseDocumentXml(e);if(!n)return[];const s=n.getElementsByTagName("w:drawing");if(s.length===0)return[];const o=r.split("/").pop()??r,a=await t.file(`word/_rels/${o}.rels`)?.async("string"),l={...i,relationships:this.parseRelationshipsXml(a,r)},d=[];for(let p=0;p<s.length;p++){const m=await this.parseImageFromDrawing(s[p],void 0,l);m&&d.push({src:m.src,width:m.width,height:m.height,...m.alt?{alt:m.alt}:{}})}return d}static async parseHeaderFooterPart(e,r){const t=this.parseDocumentXml(e);if(!t)return[];const i=[],n=Array.from(t.getElementsByTagName("w:p")).filter(s=>{let o=s.parentElement;for(;o;){if(o.tagName==="w:txbxContent")return!1;o=o.parentElement}return!0});for(let s=0;s<n.length;s++){const o=n[s],a=[];let l=null,d=!1;const p=f=>{const b={},I=this.getDirectChild(f,"w:rPr");I&&(this.applyRunPropertiesFromElement(b,I),(this.getDirectChild(I,"w:rStyle")?.getAttribute("w:val")||void 0)===this.CODE_INLINE_STYLE_ID&&(b.code=!0,/courier/i.test(b.fontFamily??"")&&delete b.fontFamily,/^(light)?gray$/i.test(b.backgroundColor??"")&&delete b.backgroundColor));let y=f.parentElement;for(;y&&y!==o;){if(y.tagName==="w:hyperlink"){const B=y.getAttribute("r:id"),$=y.getAttribute("w:anchor"),W=B?r?.get(B)?.target:void 0;W?b.link=W:$&&(b.link=`#${$}`);break}y=y.parentElement}return b},m=Array.from(o.getElementsByTagName("w:r")).filter(f=>{let b=f.parentElement;for(;b&&b!==o;){if(b.tagName==="w:p")return!1;b=b.parentElement}return b===o});for(let f=0;f<m.length;f++){const b=m[f],I=p(b);for(let y=0;y<b.children.length;y++){const B=b.children[y];if(B.tagName==="w:t"){if(d)continue;const $=B.textContent??"";$&&a.push({type:"text",text:$,...Object.keys(I).length>0?{marks:I}:{}})}else if(B.tagName==="w:tab")a.push({type:"text",text:" "});else if(B.tagName==="w:br"&&!d&&(B.getAttribute("w:type")??"textWrapping")==="textWrapping")a.push({type:"text",text:`
3
- `,...Object.keys(I).length>0?{marks:I}:{}});else if(B.tagName==="w:fldChar"){const $=B.getAttribute("w:fldCharType");$==="begin"&&(d=!0),$==="end"&&(l&&a.push({type:"text",text:"1",marks:{...I,field:l}}),l=null,d=!1)}else if(B.tagName==="w:instrText"&&d){const $=(B.textContent??"").trim().toUpperCase();$.startsWith("PAGE")?l="page":$.startsWith("NUMPAGES")&&(l="numPages")}}}const h=o.getElementsByTagName("w:fldSimple");for(let f=0;f<h.length;f++){const b=(h[f].getAttribute("w:instr")??"").trim().toUpperCase();b.startsWith("PAGE")?a.push({type:"text",text:"1",marks:{field:"page"}}):b.startsWith("NUMPAGES")&&a.push({type:"text",text:"1",marks:{field:"numPages"}})}const g=this.getDirectChild(this.getDirectChild(o,"w:pPr")??o,"w:jc")?.getAttribute("w:val"),w=g==="center"?"center":g==="right"||g==="end"?"right":g==="both"?"justify":void 0;a.length>0&&i.push({type:"paragraph",id:this.generateId(),children:a,...w?{align:w}:{}});const u=await this.parseTextBoxContent(o,void 0);i.push(...u.filter(f=>f.type==="paragraph"))}return i}static attachCommentsFromXml(e,r,t,i){const n=this.parseDocumentXml(r);if(!n)return;const s=new Set,o=u=>{if(!u||typeof u!="object")return;if(Array.isArray(u)){u.forEach(o);return}const f=u;f.marks?.comment&&f.marks.comment.split(",").forEach(b=>s.add(b)),o(f.children)};o(e.children);const a=(i??this.fallbackCommentState).collapsedCommentAnchorBlockById;a?.forEach((u,f)=>s.add(`docxcmt-${f}`));const l=new Map;if(t){const u=this.parseDocumentXml(t)?.getElementsByTagName("w15:commentEx")??[];for(let f=0;f<u.length;f++){const b=u[f],I=b.getAttribute("w15:paraId");I&&l.set(I,{done:b.getAttribute("w15:done")==="1",parentParaId:b.getAttribute("w15:paraIdParent")??void 0})}}const d=[],p=new Map,m=new Map,h=n.getElementsByTagName("w:comment");for(let u=0;u<h.length;u++){const f=h[u],b=f.getAttribute("w:id");if(!b)continue;const I=`docxcmt-${b}`,y=f.getElementsByTagName("w:p"),B=[];for(let D=0;D<y.length;D++){const T=y[D].getElementsByTagName("w:t");let F="";for(let E=0;E<T.length;E++)F+=T[E].textContent??"";B.push(F);const S=y[D].getAttribute("w14:paraId");S&&(p.set(I,S),m.set(S,I))}const $=f.getAttribute("w:date"),W=$?Date.parse($):NaN,z=a?.get(b);d.push({id:I,author:f.getAttribute("w:author")??"Unknown",...f.getAttribute("w:initials")?{initials:f.getAttribute("w:initials")}:{},createdAt:Number.isFinite(W)?new Date(W).toISOString():new Date(0).toISOString(),bodyMd:B.filter(D=>D.length>0).join(`
4
-
5
- `),importedId:parseInt(b,10),...z?{anchorBlockId:z}:{}})}for(const u of d){const f=p.get(u.id),b=f?l.get(f):void 0;if(b?.done&&(u.resolved=!0),b?.parentParaId){const I=m.get(b.parentParaId);I&&(u.parentId=I)}}const g=u=>{let f=u;const b=new Map(d.map(I=>[I.id,I]));for(;f.parentId&&b.has(f.parentId);)f=b.get(f.parentId);return f.id},w=d.filter(u=>s.has(g(u)));w.length>0&&(e.comments=w)}static async collectNotesFromXml(e,r,t,i,n,s,o){const a=this.parseDocumentXml(r);if(!a)return;if(o){const p=t==="w:footnote"?"footnotes":"endnotes",m=await o.zip.file(`word/_rels/${p}.xml.rels`)?.async("string");if(m){const h=this.parseRelationshipsXml(m,`word/${p}.xml`);h.size>0&&(o={...o,relationships:new Map([...o.relationships,...h])})}}const l=Te(e.pageLayout).indentStepPx,d=a.getElementsByTagName(t);for(let p=0;p<d.length;p++){const m=d[p],h=m.getAttribute("w:type");if(h==="separator"||h==="continuationSeparator")continue;const g=m.getAttribute("w:id");if(!g)continue;const w=await this.parseBodyChildren(m,l,o),u=w.length>0?w:[this.createEmptyParagraph()];xi(u),s.set(`${i}-${g}`,{type:"footnote",id:`${i}-${g}`,...n==="endnote"?{noteKind:"endnote"}:{},children:u})}}static finalizeImportedFootnoteRefs(e,r){const t=[],i={footnote:0,endnote:0},n=new Map,s=(o,a)=>{if(!o||typeof o!="object")return;if(Array.isArray(o)){o.forEach(p=>s(p));return}const l=o,d=l.marks?.footnoteRef;if(d&&(d.startsWith("docxfn-")||d.startsWith("docxen-")))if(!r.has(d))l.text="",delete l.marks.footnoteRef,delete l.marks.superscript;else{if(!t.includes(d)){t.push(d);const p=d.startsWith("docxen-")?"endnote":"footnote";i[p]+=1,n.set(d,Vi(i[p],p))}l.text=n.get(d)??""}s(l.children)};s(e.children);for(const o of t){const a=r.get(o);a&&e.children.push(a)}}static documentHasMath(e){return e.includes("m:oMath")||e.includes("m:oMathPara")}static documentHasNativePageBreaks(e){return e.includes('w:br w:type="page"')||e.includes("<w:lastRenderedPageBreak")||e.includes("<w:pageBreakBefore")}static documentHasComplexBodyContent(e){return e.includes("<w:tbl")||e.includes("<w:drawing")||e.includes("<w:pict")||e.includes("<w:object")}static shouldUseStructuredDocxParser(e){return!!(this.documentHasMath(e)||this.documentHasNativePageBreaks(e)&&!this.documentHasComplexBodyContent(e))}static resolveIndentStepPx(e){return Te(e?.pageLayout).indentStepPx}static stripXmlBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}static parseDocumentXml(e){const r=new DOMParser().parseFromString(this.stripXmlBom(e),"application/xml");return r.querySelector("parsererror")?null:r}static async loadOOXMLPackageContext(e,r){const[t,i,n,s]=await Promise.all([e.file("word/_rels/document.xml.rels")?.async("string"),e.file("word/styles.xml")?.async("string"),e.file("word/numbering.xml")?.async("string"),e.file("[Content_Types].xml")?.async("string")]),o=this.parseRelationshipsXml(t,"word/document.xml");return{zip:e,documentXml:r,relationships:o,styles:this.parseStylesXml(i),stylesXmlRaw:i||void 0,numbering:this.parseNumberingXml(n),contentTypes:this.parseContentTypesXml(s),themeFonts:await this.parseThemeFonts(e,o)}}static async parseThemeFonts(e,r){let t="word/theme/theme1.xml";for(const l of r.values())if(l.type.endsWith("/theme")&&l.targetMode!=="External"){t=l.target;break}const i=await e.file(t)?.async("string");if(!i)return;const n=this.parseDocumentXml(i);if(!n)return;const s=l=>n.getElementsByTagName(l)[0]?.getElementsByTagName("a:latin")[0]?.getAttribute("typeface")?.trim()||void 0,o=s("a:majorFont"),a=s("a:minorFont");if(!(!o&&!a))return{...o?{major:o}:{},...a?{minor:a}:{}}}static parseRelationshipsXml(e,r){const t=new Map;if(!e)return t;const i=this.parseDocumentXml(e);if(!i)return t;const n=i.getElementsByTagName("Relationship");for(let s=0;s<n.length;s++){const o=n[s],a=o.getAttribute("Id"),l=o.getAttribute("Target"),d=o.getAttribute("Type");if(!a||!l||!d)continue;const p=o.getAttribute("TargetMode")||void 0;t.set(a,{id:a,type:d,target:p?.toLowerCase()==="external"?l:this.resolvePackageTargetPath(r,l),targetMode:p})}return t}static resolvePackageTargetPath(e,r){if(r.startsWith("/"))return r.replace(/^\/+/,"");const t=e.split("/");t.pop();const i=r.split("/");for(const n of i)if(!(!n||n===".")){if(n===".."){t.pop();continue}t.push(n)}return t.join("/")}static parseStylesXml(e){const r={stylesById:new Map,defaultStyleIdByType:new Map};if(!e)return r;const t=this.parseDocumentXml(e);if(!t)return r;const i=t.getElementsByTagName("w:docDefaults")[0];if(i){const s=i.getElementsByTagName("w:pPrDefault")[0],o=i.getElementsByTagName("w:rPrDefault")[0];r.paragraphDefault=s?this.getDirectChild(s,"w:pPr"):void 0,r.runDefault=o?this.getDirectChild(o,"w:rPr"):void 0}const n=t.getElementsByTagName("w:style");for(let s=0;s<n.length;s++){const o=n[s],a=o.getAttribute("w:styleId");if(!a)continue;const l=this.getDirectChild(o,"w:name"),d=this.getDirectChild(o,"w:basedOn"),p=o.getAttribute("w:type")||"";r.stylesById.set(a,{id:a,type:p,basedOn:d?.getAttribute("w:val")||void 0,name:l?.getAttribute("w:val")||void 0,pPr:this.getDirectChild(o,"w:pPr"),rPr:this.getDirectChild(o,"w:rPr"),tblPr:this.getDirectChild(o,"w:tblPr")}),p&&this.isOnAttribute(o.getAttribute("w:default"))&&(r.defaultStyleIdByType.has(p)||r.defaultStyleIdByType.set(p,a))}return r}static parseFontTableXml(e){if(!e)return;const r=this.parseDocumentXml(e);if(!r)return;const t={},i=r.getElementsByTagName("w:font");for(let n=0;n<i.length;n++){const s=i[n],o=(s.getAttribute("w:name")||"").trim();if(!o)continue;const a=(this.getDirectChild(s,"w:altName")?.getAttribute("w:val")||"").trim(),l=(this.getDirectChild(s,"w:family")?.getAttribute("w:val")||"").trim().toLowerCase(),d=(this.getDirectChild(s,"w:pitch")?.getAttribute("w:val")||"").trim().toLowerCase(),p=(this.getDirectChild(s,"w:panose1")?.getAttribute("w:val")||"").trim(),m={};a&&(m.alt=a);const h=this.genericFamilyFromFontMetrics(l,d,p);h&&(m.generic=h),(m.alt||m.generic)&&(t[o.toLowerCase()]=m)}return Object.keys(t).length>0?t:void 0}static genericFamilyFromFontMetrics(e,r,t){if(r==="fixed"||e==="modern")return"monospace";if(/^[0-9a-fA-F]{20}$/.test(t)){const i=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16);if(i===2){if(n>=2&&n<=10)return"serif";if(n>=11&&n<=15)return"sans-serif"}}if(e==="roman")return"serif";if(e==="swiss")return"sans-serif"}static parseNumberingXml(e){const r={abstractNums:new Map,nums:new Map};if(!e)return r;const t=this.parseDocumentXml(e);if(!t)return r;const i=t.getElementsByTagName("w:abstractNum");for(let s=0;s<i.length;s++){const o=i[s],a=o.getAttribute("w:abstractNumId");if(!a)continue;const l=new Map,d=o.getElementsByTagName("w:lvl");for(let p=0;p<d.length;p++){const m=d[p],h=m.getAttribute("w:ilvl"),g=h?parseInt(h,10):NaN;if(!Number.isFinite(g))continue;const w=this.getDirectChild(m,"w:numFmt"),u=this.getDirectChild(m,"w:lvlText"),f=this.getDirectChild(m,"w:start")?.getAttribute("w:val");l.set(g,{level:g,format:w?.getAttribute("w:val")||void 0,text:u?.getAttribute("w:val")||void 0,start:f&&Number.isFinite(parseInt(f,10))?parseInt(f,10):void 0})}r.abstractNums.set(a,{abstractNumId:a,levels:l})}const n=t.getElementsByTagName("w:num");for(let s=0;s<n.length;s++){const o=n[s],a=o.getAttribute("w:numId");if(!a)continue;const l=this.getDirectChild(o,"w:abstractNumId"),d=new Map,p=o.getElementsByTagName("w:lvlOverride");for(let m=0;m<p.length;m++){const h=p[m],g=h.getAttribute("w:ilvl"),w=g?parseInt(g,10):NaN;if(!Number.isFinite(w))continue;const u=h.getElementsByTagName("w:startOverride")[0]?.getAttribute("w:val");u&&Number.isFinite(parseInt(u,10))&&d.set(w,parseInt(u,10))}r.nums.set(a,{numId:a,abstractNumId:l?.getAttribute("w:val")||void 0,levelStartOverrides:d})}return r}static parseContentTypesXml(e){const r=new Map;if(!e)return r;const t=this.parseDocumentXml(e);if(!t)return r;const i=t.getElementsByTagName("Default");for(let s=0;s<i.length;s++){const o=i[s],a=(o.getAttribute("Extension")||"").toLowerCase(),l=o.getAttribute("ContentType");a&&l&&r.set(a,l)}const n=t.getElementsByTagName("Override");for(let s=0;s<n.length;s++){const o=n[s],a=o.getAttribute("PartName"),l=o.getAttribute("ContentType");a&&l&&r.set(a.replace(/^\/+/,""),l)}return r}static getDirectChild(e,r){for(let t=0;t<e.children.length;t++){const i=e.children[t];if(i.tagName===r)return i}}static parseTwipsAttribute(e,r){if(!e)return;const t=e.getAttribute(r);if(!t)return;const i=Number.parseInt(t,10);return Number.isFinite(i)?i:void 0}static parseOnOffElement(e){if(!e)return;const r=(e.getAttribute("w:val")||e.getAttribute("val")||"").trim().toLowerCase();return r?!(r==="0"||r==="false"||r==="off"):!0}static pxToTwips(e){return Number.isFinite(e)?Math.round(e*this.TWIPS_PER_PX):0}static pxToDocxHalfPoints(e){return Number.isFinite(e)?Math.max(2,Math.round(e*this.DOCX_HALF_POINTS_PER_PX)):2}static twipsToPx(e){return Number.isFinite(e)?e/this.TWIPS_PER_PX:0}static inferPageSizePresetFromTwips(e,r){const t=e/this.TWIPS_PER_INCH,i=r/this.TWIPS_PER_INCH,n=Math.min(t,i),s=Math.max(t,i);let o="letter",a=Number.POSITIVE_INFINITY;for(const l of this.PAGE_SIZE_PRESETS){const d=Math.abs(n-l.width)+Math.abs(s-l.height);d<a&&(a=d,o=l.preset)}return o}static findAllSectionProperties(e){const r=[],t=i=>{for(const n of Array.from(i.children)){if(n.tagName==="w:sdt"){const s=this.getDirectChild(n,"w:sdtContent");s&&t(s);continue}if(n.tagName==="w:p"){const s=this.getDirectChild(n,"w:pPr"),o=s?this.getDirectChild(s,"w:sectPr"):void 0;o&&r.push(o)}n.tagName==="w:sectPr"&&r.push(n)}};return t(e),r}static findBodySectionProperties(e){const r=this.findAllSectionProperties(e);return r[r.length-1]}static parseSectionPropertiesElement(e){const r={},t=this.getDirectChild(e,"w:pgSz");if(t){const m=this.parseTwipsAttribute(t,"w:w"),h=this.parseTwipsAttribute(t,"w:h"),g=(t.getAttribute("w:orient")||"").trim().toLowerCase();m!==void 0&&m>0&&h!==void 0&&h>0?r.orientation=m>h?"landscape":"portrait":(g==="landscape"||g==="portrait")&&(r.orientation=g),m!==void 0&&m>0&&h!==void 0&&h>0&&(r.pageSize=this.inferPageSizePresetFromTwips(m,h))}const i=this.getDirectChild(e,"w:pgMar");if(i){const m=this.parseTwipsAttribute(i,"w:top"),h=this.parseTwipsAttribute(i,"w:right"),g=this.parseTwipsAttribute(i,"w:bottom"),w=this.parseTwipsAttribute(i,"w:left");m!==void 0&&(r.marginTopPx=this.twipsToPx(m)),h!==void 0&&(r.marginRightPx=this.twipsToPx(h)),g!==void 0&&(r.marginBottomPx=this.twipsToPx(g)),w!==void 0&&(r.marginLeftPx=this.twipsToPx(w))}const n=this.getDirectChild(e,"w:pgNumType"),s=(n?.getAttribute("w:start")||"").trim();if(s!==""){const m=parseInt(s,10);Number.isFinite(m)&&m>0&&(r.pageNumberStart=m)}const o=(n?.getAttribute("w:fmt")||"").trim();Si(o)&&(r.pageNumberFormat=o);const a=this.getDirectChild(e,"w:lnNumType");if(a){const m=(a.getAttribute("w:countBy")||"").trim(),h=(a.getAttribute("w:start")||"").trim(),g=(a.getAttribute("w:restart")||"").trim(),w=(a.getAttribute("w:distance")||"").trim(),u=m?parseInt(m,10):NaN,f=h?parseInt(h,10):NaN,b=w?parseInt(w,10):NaN;r.lineNumbering=Ii({countBy:Number.isFinite(u)&&u>=1?u:1,start:Number.isFinite(f)&&f>=1?f:1,restart:g==="newSection"||g==="continuous"?g:"newPage",...Number.isFinite(b)&&b>=0?{distancePx:b/15}:{}})}const l=this.getDirectChild(e,"w:cols");if(l){const m=(l.getAttribute("w:num")||"").trim(),h=m?parseInt(m,10):NaN;if(Number.isFinite(h)&&h>1){r.columnCount=h;const g=(l.getAttribute("w:space")||"").trim(),w=g?parseInt(g,10):NaN;Number.isFinite(w)&&w>=0&&(r.columnGapTwips=w)}}const d=ki(this.getDirectChild(e,"w:pgBorders"));d&&(r.pageBorders=d);const p=rt(e,_r);return p&&(r.oxmlSectPr=p),Object.keys(r).length>0?r:void 0}static parseSectionStartType(e){const r=(this.getDirectChild(e,"w:type")?.getAttribute("w:val")||"").trim();if(r==="continuous")return"continuous";if(r==="evenPage")return"evenPage";if(r==="oddPage")return"oddPage";if(r==="nextPage")return"nextPage"}static parseDocumentPageLayout(e,r){const t=r??this.parseDocumentXml(e);if(!t)return;const i=t.getElementsByTagName("w:body")[0];if(!i)return;const n=this.findBodySectionProperties(i);if(!n)return;const s=this.parseSectionPropertiesElement(n);return s?.pageNumberStart!==void 0&&(s.pageNumberRestart=!0),s}static async parseDocumentPageLayoutFromPackage(e,r,t){const i=t??this.parseDocumentXml(e);if(!i)return;const n=this.parseDocumentPageLayout(e,i)??{},s=i.getElementsByTagName("w:body")[0];if(!s)return Object.keys(n).length>0?n:void 0;const o=this.findAllSectionProperties(s);if(o.length===0)return Object.keys(n).length>0?n:void 0;const a=this.resolveSectionHeaderFooterReferences(o)[o.length-1],l=await r.file("word/_rels/document.xml.rels")?.async("string");if(!l)return Object.keys(n).length>0?n:void 0;const d=this.parseDocumentXml(l);if(!d)return Object.keys(n).length>0?n:void 0;const p=new Map,m=d.getElementsByTagName("Relationship");for(let g=0;g<m.length;g++){const w=m[g],u=w.getAttribute("Id"),f=w.getAttribute("Target");u&&f&&p.set(u,f)}const h=async(g,w)=>{const u=a[g].default,f=u?p.get(u):void 0;if(!f)return;const b=f.startsWith("/")?f.slice(1):f.startsWith("word/")?f:`word/${f.replace(/^\.?\//,"")}`,I=await r.file(b)?.async("string");if(!I)return;const y=this.parsePageNumberInfoFromReferenceXml(I);y&&(n.showPageNumbers=!0,n.pageNumberPosition=`${w}-${y.horizontal}`)};return await h("header","top"),n.showPageNumbers||await h("footer","bottom"),Object.keys(n).length>0?n:void 0}static parsePageNumberInfoFromReferenceXml(e){const r=this.parseDocumentXml(e);if(!r)return;const t=r.getElementsByTagName("w:p");for(let i=0;i<t.length;i++){const n=t[i],s=n.getElementsByTagName("w:instrText");let o=!1;for(let l=0;l<s.length;l++)if((s[l].textContent||"").toUpperCase().includes("PAGE")){o=!0;break}if(!o){const l=n.getElementsByTagName("w:fldSimple");for(let d=0;d<l.length;d++)if((l[d].getAttribute("w:instr")||"").toUpperCase().includes("PAGE")){o=!0;break}}if(!o)continue;const a=this.getDirectChild(n,"w:pPr");return{horizontal:((a?this.getDirectChild(a,"w:jc"):void 0)?.getAttribute("w:val")||"").toLowerCase()==="left"?"left":"right"}}}static parseWordParagraphProperties(e,r){const t=this.getDirectChild(e,"w:pPr");if(!t)return{isList:!1};const i={isList:!!this.getDirectChild(t,"w:numPr")},n=this.parseOnOffElement(this.getDirectChild(t,"w:pageBreakBefore"));n!==void 0&&(i.pageBreakBefore=n),this.getDirectChild(t,"w:keepNext")&&(i.keepNext=this.isOn(t,"w:keepNext")),this.getDirectChild(t,"w:keepLines")&&(i.keepLines=this.isOn(t,"w:keepLines")),this.getDirectChild(t,"w:widowControl")&&(i.widowControl=this.isOn(t,"w:widowControl")),this.getDirectChild(t,"w:bidi")&&(i.direction=this.isOn(t,"w:bidi")?"rtl":"ltr"),this.parseParagraphDecoration(t,i),this.applyTabStopsFromPPr(i,t),this.applyJcFromPPr(i,t);const s=this.getDirectChild(t,"w:ind");if(s){const o=this.parseTwipsAttribute(s,"w:start")??this.parseTwipsAttribute(s,"w:left");if(o===0)i.leftIndent=0;else if(o!==void 0&&o>0){const d=Dt(this.twipsToPx(o),{indentStepPx:r,storedAsUnits:!1});d!==void 0&&(i.leftIndent=d)}const a=this.parseTwipsAttribute(s,"w:firstLine"),l=this.parseTwipsAttribute(s,"w:hanging");if(l!==void 0&&l>0)i.firstLineIndent=-1;else if(a===0)i.firstLineIndent=0;else if(a!==void 0&&a>0){const d=Dt(this.twipsToPx(a),{indentStepPx:r,storedAsUnits:!1,firstLine:!0});d!==void 0&&(i.firstLineIndent=d)}}return this.resolveLogicalAlignment(i),i}static applyJcFromPPr(e,r){const t=(this.getDirectChild(r,"w:jc")?.getAttribute("w:val")||"").toLowerCase();t==="center"?(e.align=t,delete e.jcLogical,delete e.jcPhysical):t==="left"||t==="right"?(e.jcPhysical=t,delete e.align,delete e.jcLogical):t==="both"||t==="justify"?(e.align="justify",delete e.jcLogical,delete e.jcPhysical):(t==="start"||t==="end")&&(e.jcLogical=t,delete e.align,delete e.jcPhysical)}static resolveLogicalAlignment(e){const r=e.direction==="rtl",t=e.jcPhysical;if(t){if(delete e.jcPhysical,delete e.jcLogical,!r){e.align=t;return}const s=t==="left"?"right":"left";s==="right"?delete e.align:e.align=s;return}const i=e.jcLogical;if(!i)return;delete e.jcLogical;const n=i==="start"?r?"right":"left":r?"left":"right";n===(r?"right":"left")?delete e.align:e.align=n}static extractTopLevelParagraphProperties(e,r){const t=this.parseDocumentXml(e);if(!t)return[];const i=t.getElementsByTagName("w:body")[0];if(!i)return[];const n=[];for(let s=0;s<i.children.length;s++){const o=i.children[s];o.tagName==="w:p"&&n.push(this.parseWordParagraphProperties(o,r))}return n}static applyTopLevelParagraphProperties(e,r){const t=r.filter(n=>!n.isList);let i=0;for(const n of e.children){if(n.type!=="paragraph")continue;const s=t[i];if(!s)break;i+=1,s.align&&(n.align=s.align),s.leftIndent!==void 0&&(n.leftIndent=s.leftIndent),s.firstLineIndent!==void 0&&(n.firstLineIndent=s.firstLineIndent);const o=this.directionAttrFor(s.direction,this.paragraphNodeText(n));o&&(n.direction=o)}}static paragraphNodeText(e){let r="";for(const t of e.children)t.type==="text"&&(r+=t.text);return r}static directionAttrFor(e,r){if(e==="rtl")return"rtl";if(e==="ltr"&&Bt(r)==="rtl")return"ltr"}static async parseStructuredDocxDocument(e,r,t,i,n){t||(this.fallbackCommentState={});const s=i??this.parseDocumentXml(e);if(!s)return{type:"doc",children:[this.createEmptyParagraph()]};const o=s.getElementsByTagName("w:body")[0];if(!o)return{type:"doc",children:[this.createEmptyParagraph()]};const a=Te(r).indentStepPx,l=[];this.importSdtWrappers=l;const d=[];this.importOxmlRanges=d,this.sdtAncestorStack=[];const p=t??this.fallbackCommentState;p.moveRangeByWrapper=e.includes("<w:moveFrom")||e.includes("<w:moveTo")?this.indexImportedMoveRanges(s):new WeakMap,p.collapsedCommentAnchorBlockById=new Map;let m;try{m=await this.parseBodyChildren(o,a,t,l,n)}finally{this.importSdtWrappers=void 0,this.importOxmlRanges=void 0,this.sdtAncestorStack=[],delete p.moveRangeByWrapper}this.finalizeImportedMovePairs(m),m=this.applyParagraphMarkMoves(m),this.applyTableMoves(m),this.applyParagraphMarkRevisions(m),m=this.collapseTocRegions(m);const h=this.findAllSectionProperties(o);if(h.length>1){let w=0;for(const u of m){if(u.type!=="section-break")continue;const f=h[w+1];if(f){const b=this.parseSectionStartType(f);b&&(u.breakType=b)}w++}}const g={type:"doc",children:m.length>0?m:[this.createEmptyParagraph()]};if(r){if(g.pageLayout=r,r.pageNumberFormat&&r.pageNumberFormat!=="decimal")for(const w of g.children)w.type==="section-break"&&w.layout?.pageNumberFormat===void 0&&(w.layout={...w.layout??{},pageNumberFormat:"decimal"});if((r.columnCount??1)>1)for(const w of g.children)w.type==="section-break"&&w.layout?.columnCount===void 0&&(w.layout={...w.layout??{},columnCount:1})}if(l.length>0&&(g.sdtWrappers=l),d.length>0&&(g.oxmlRanges=d),t?.stylesXmlRaw){g.stylesXml=t.stylesXmlRaw;const w=this.buildDocumentStylesheet(t,a);w&&(g.stylesheet=w)}return g}static resolveStylesheetFromStylesXml(e,r){const t=this.parseStylesXml(e);return this.buildDocumentStylesheet({styles:t,numbering:{abstractNums:new Map,nums:new Map}},Te(r).indentStepPx)}static buildDocumentStylesheet(e,r){const t=e.styles;if(t.stylesById.size===0)return;const i=t.defaultStyleIdByType?.get("paragraph"),n=[];for(const s of t.stylesById.values()){if(s.type!=="paragraph")continue;const o={isList:!1},a=[];t.paragraphDefault&&a.push(t.paragraphDefault),a.push(...this.resolveStyleChainPPr(s.id,t,"paragraph"));const l=this.resolveRunMarks(void 0,s.id,e),d=typeof l.fontSize=="number"&&l.fontSize>0?l.fontSize:Ae.paragraph;for(const g of a)this.applyParagraphPropertiesFromElement(o,g,r,e,d);this.resolveLogicalAlignment(o);const p={};o.align&&(p.align=o.align),o.direction&&(p.direction=o.direction),o.leftIndent!==void 0&&(p.leftIndent=o.leftIndent),o.firstLineIndent!==void 0&&(p.firstLineIndent=o.firstLineIndent),o.lineSpacing!==void 0&&(p.lineSpacing=o.lineSpacing),this.applyDocxParagraphSpacing(p,o),o.keepNext!==void 0&&(p.keepNext=o.keepNext),o.keepLines!==void 0&&(p.keepLines=o.keepLines),o.widowControl!==void 0&&(p.widowControl=o.widowControl),o.bordersJson&&(p.borders=o.bordersJson),o.shading&&(p.shading=o.shading),o.tabStops&&o.tabStops.length>0&&(p.tabStops=JSON.stringify(o.tabStops));const m={styleId:s.id};s.name&&(m.name=s.name);const h=this.headingLevelForStyle(s)||o.heading;h&&(m.headingLevel=h),s.id===i&&(m.default=!0),Object.keys(p).length>0&&(m.paragraphAttrs=p),Object.keys(l).length>0&&(m.runMarks=l),n.push(m)}return n.length>0?{paragraphStyles:n}:void 0}static tocInstrOfBlock(e){if(e.type!=="paragraph")return;const r=e.children.filter(i=>i.type==="text"&&((i.text??"")!==""||i.marks?.fieldInstr));if(r.length===0)return;const t=r[0].marks?.fieldInstr;if(!(!t||!/^TOC\b/i.test(t.trim())))return r.every(i=>i.marks?.fieldInstr===t)?t:void 0}static tocTypographyOfRegion(e,r){const t=e.flatMap(l=>l.children.filter(d=>d.type==="text"&&(d.text??"").trim()!=="")),i=l=>{if(t.length===0)return;const d=l(t[0]);if(d!==void 0)return t.every(p=>l(p)===d)?d:void 0},n={},s=i(l=>l.marks?.fontFamily);s&&s!==r&&(n.fontFamily=s);const o=i(l=>l.marks?.fontSize);Pi(o)&&(n.fontSize=o);const a=i(l=>Mr(l.marks?.color));return a&&(n.color=a),n}static collapseTocRegions(e){const r=[];let t,i,n=[],s={},o,a=!1;const l=()=>{if(t){a||(o=this.inferDocumentFontFamily({type:"doc",children:e.filter(p=>!this.tocInstrOfBlock(p))}),a=!0);const d={type:"toc",...s,...this.tocTypographyOfRegion(n,o),id:i||this.generateId(),instr:t,levels:Yi(t)};r.push(d)}t=void 0,i=void 0,n=[],s={}};for(const d of e){const p=this.tocInstrOfBlock(d);if(p&&p===t){d.type==="paragraph"&&n.push(d);continue}if(t&&l(),p){t=p,i=d.id,d.type==="paragraph"&&(n.push(d),d.direction&&(s.direction=d.direction,s.align=d.direction==="rtl"?"right":"left"),d.align&&(s.align=d.align));continue}r.push(d)}return l(),r}static parseParagraphMarkRevision(e){const r=this.getDirectChild(e,"w:pPr"),t=r?this.getDirectChild(r,"w:rPr"):void 0;if(!t)return null;const i=this.getDirectChild(t,"w:ins");if(i)return{kind:"split",meta:this.parseTrackedRevisionMeta(i)};const n=this.getDirectChild(t,"w:del");return n?{kind:"merge",meta:this.parseTrackedRevisionMeta(n)}:null}static parseParagraphMarkMove(e,r){const t=this.getDirectChild(e,"w:pPr"),i=t?this.getDirectChild(t,"w:rPr"):void 0;if(!i)return null;const n=this.getDirectChild(i,"w:moveFrom")??this.getDirectChild(i,"w:moveTo");if(!n)return null;const s=(r??this.fallbackCommentState).moveRangeByWrapper?.get(n);return{role:n.tagName==="w:moveFrom"?"from":"to",meta:this.parseTrackedRevisionMeta(n),...s?{move:s}:{}}}static markWholeBlockMove(e,r){if(!e||typeof e!="object")return;if(Array.isArray(e)){e.forEach(i=>this.markWholeBlockMove(i,r));return}const t=e;if(t.marks?.suggestionId===r&&t.marks.docxMove)try{t.marks.docxMove=JSON.stringify({...JSON.parse(t.marks.docxMove),wholeBlocks:!0})}catch{}this.markWholeBlockMove(t.children,r)}static applyParagraphMarkMoves(e){const r=new Set,t=a=>{if(!a||typeof a!="object")return;if(Array.isArray(a)){a.forEach(t);return}const l=a;l.marks?.docxMove&&l.marks.suggestionId&&r.add(l.marks.suggestionId),t(l.children)};t(e);const i=(a,l)=>{if(!a?.move)return;const d=`docxmove-${encodeURIComponent(a.move.name)}`;return r.has(d)&&l.every(p=>p.type!=="text"||!p.text||p.marks?.suggestionId===d&&this.parseDocxMoveMark(p.marks.docxMove)?.role===a.role)?d:void 0},n=a=>{if(!(!a||typeof a!="object")){if(Array.isArray(a)){a.forEach(n);return}delete a.__pilcrowMove,n(a.children)}},s=(a,l,d)=>{a.structuralSuggestionId=d,a.structuralSuggestionKind=l.role==="from"?"delete":"insert",a.structuralSuggestionLabel="Move",this.markWholeBlockMove(a,d),delete a.structuralSuggestionRole,delete a.structuralSuggestionRecord},o=[];for(const a of e){if(a.type==="paragraph"){const l=a.__pilcrowMove;delete a.__pilcrowMove;const d=i(l,a.children);l&&d?s(a,l,d):l&&!a.structuralSuggestionKind&&(a.__pilcrowRevision={kind:l.role==="from"?"merge":"split",meta:l.meta}),n(a.children),o.push(a);continue}if(a.type==="list"&&a.children.length>0){const l=[];for(const p of a.children){const m=p.__pilcrowMove,h=i(m,p.children),g=m&&h?{marker:m,moveId:h}:void 0,w=g?`${g.moveId}\0${g.marker.role}`:"",u=l[l.length-1];u&&u.key===w?u.items.push(p):l.push({key:w,move:g,items:[p]})}const d={...a};l.forEach((p,m)=>{const h=m===0?a:{...d,id:this.generateId()};m>0&&a.numberingChainId&&delete h.startNumber,h.children=p.items,p.move&&s(h,p.move.marker,p.move.moveId);for(const g of p.items)delete g.__pilcrowMove;n(h.children),o.push(h)});continue}n(a),o.push(a)}return o}static applyTableMoves(e){for(const r of e){if(r.type!=="table"||r.children.length===0)continue;const t=r.children[0].diffState,i=r.children[0].suggestionId;if(t!=="insert"&&t!=="delete"||!i||!r.children.every(m=>m.diffState===t&&m.suggestionId===i))continue;const n=t==="delete"?"from":"to",s=new Set;let o=!0;const a=m=>{if(!o||!m||typeof m!="object")return;if(Array.isArray(m)){m.forEach(a);return}const h=m;h.type==="table-cell"&&h.diffState&&(o=!1),h.type==="text"&&h.text&&(this.parseDocxMoveMark(h.marks?.docxMove)?.role===n&&h.marks?.suggestionId&&(n==="from"?h.marks.deletion:h.marks.insertion)?s.add(h.marks.suggestionId):o=!1),a(h.children)};if(a(r.children),!o||s.size!==1)continue;let l=[];try{const m=JSON.parse(r.structuralSuggestionRecords??"[]");Array.isArray(m)&&(l=m)}catch{continue}const d=l.find(m=>m?.id===i);if(d?.type!=="table-change"||d.tableRevision.operations.length!==r.children.length||!d.tableRevision.operations.every(m=>m.kind==="row"&&m.action===t))continue;const p=l.filter(m=>m!==d);p.length>0?r.structuralSuggestionRecords=JSON.stringify(p):delete r.structuralSuggestionRecords;for(const m of r.children)delete m.diffState,delete m.suggestionId;r.diffState=t,r.suggestionId=[...s][0],this.markWholeBlockMove(r,r.suggestionId)}}static applyParagraphMarkRevisions(e){for(let r=0;r<e.length;r++){const t=e[r],i=t.__pilcrowRevision;if(i&&delete t.__pilcrowRevision,!i||t.type!=="paragraph")continue;const n=e[r+1];if(!n||n.type!=="paragraph")continue;const s=i.meta.revisionId?`docxrev-${i.meta.revisionId}`:this.generateId(),o=i.kind==="split"?"Split":"Merge",a=this.revisionAuthorIdentity(i.meta.author),l={id:s,source:a.suggestionSource,authorType:a.suggestionAuthorType,label:o,...i.meta.createdAt!==void 0?{createdAt:i.meta.createdAt}:{},...i.meta.author?{agentName:i.meta.author}:{}},d=i.kind==="split"?{...l,type:"paragraph-split",blockId:t.id,insertedBlockId:n.id,beforeBlock:{type:"paragraph",id:t.id,children:[...t.children,...n.children]}}:{...l,type:"paragraph-merge",firstBlockId:t.id,secondBlockId:n.id};t.structuralSuggestionId=s,t.structuralSuggestionKind=i.kind,t.structuralSuggestionRole="before",t.structuralSuggestionLabel=o,t.structuralSuggestionRecord=JSON.stringify(d),n.structuralSuggestionId=s,n.structuralSuggestionKind=i.kind,n.structuralSuggestionRole="after",n.structuralSuggestionLabel=o}}static parseParagraphPropertyChange(e,r,t){const i=this.getDirectChild(e,"w:pPr"),n=i?this.getDirectChild(i,"w:pPrChange"):void 0;if(!n)return null;const s=this.parseTrackedRevisionMeta(n),o=this.getDirectChild(n,"w:pPr"),a={isList:!1};if(t){const l=o&&this.getDirectChild(o,"w:pStyle")?.getAttribute("w:val")||void 0;a.styleId=l;const d=[];t.styles.paragraphDefault&&d.push(t.styles.paragraphDefault),d.push(...this.resolveStyleChainPPr(l,t.styles,"paragraph")),o&&d.push(o);for(const p of d)this.applyParagraphPropertiesFromElement(a,p,r,t)}else o&&this.applyParagraphPropertiesFromElement(a,o,r);return this.resolveLogicalAlignment(a),{meta:s,priorProps:a}}static applyParsedPropertiesToParagraphNode(e,r){delete e.align,delete e.leftIndent,delete e.firstLineIndent,delete e.heading,delete e.lineSpacing,delete e.keepNext,delete e.keepLines,delete e.widowControl,delete e.borders,delete e.shading,delete e.styleId,delete e.direction,r.align&&(e.align=r.align);const t=this.directionAttrFor(r.direction,this.paragraphNodeText(e));t&&(e.direction=t),r.leftIndent!==void 0&&(e.leftIndent=r.leftIndent),r.firstLineIndent!==void 0&&(e.firstLineIndent=r.firstLineIndent),r.heading&&(e.heading=r.heading),r.lineSpacing!==void 0&&(e.lineSpacing=r.lineSpacing),this.applyDocxParagraphSpacing(e,r),r.keepNext&&(e.keepNext=!0),r.keepLines&&(e.keepLines=!0),r.widowControl===!1&&(e.widowControl=!1),r.bordersJson&&(e.borders=r.bordersJson),r.shading&&(e.shading=r.shading);const i=r.styleId;i&&i.toLowerCase()!=="normal"&&(e.styleId=i)}static applyDocxParagraphSpacing(e,r){r.contextualSpacing&&(e.contextualSpacing=!0),e.spaceBefore=r.spaceBefore??0,e.spaceAfter=r.spaceAfter??0}static async parseWordParagraphBlocks(e,r,t){const i=[];for(let f=0;f+1<e.children.length;f++){const b=e.children[f],I=e.children[f+1],y=b.getAttribute("w:id");b.tagName==="w:commentRangeStart"&&I.tagName==="w:commentRangeEnd"&&y&&I.getAttribute("w:id")===y&&i.push(y)}const n=this.resolveParagraphProperties(e,r,t),s=this.parseParagraphMarkRevision(e),o=s?null:this.parseParagraphMarkMove(e,t),a=[];let l=!1,d="";const p=[];n.pageBreakBefore&&p.push(this.createPageBreakBlock());for(let f=0;f<e.children.length;f++){const b=e.children[f],I=b.tagName;if(!this.trackCommentRangeMarker(b,t)&&!(this.trackBookmarkMarker(b,t)||this.trackOxmlRangeMarker(b,t))){if(I==="w:fldSimple"){a.push(...await this.parseFldSimpleItems(b,n,t));continue}if(I==="mc:AlternateContent"){const y=this.selectAlternateContentBranch(b);y&&a.push(...await this.parseInlineItemsFromChildren(y,n,t));continue}if(I==="w:r")a.push(...this.stampOpenComments(await this.parseWordRunItems(b,n,t),t));else if(I==="w:sdt")a.push(...await this.parseInlineSdtItems(b,n,t));else if(I==="w:ins"||I==="w:del"||I==="w:moveFrom"||I==="w:moveTo")a.push(...await this.parseTrackedChangeItems(b,n,t));else if(I==="w:hyperlink")a.push(...await this.parseHyperlinkItems(b,n,t));else if(I==="m:oMathPara"){const y=this.ommlToLatex(b);y&&(a.some(B=>B.kind==="text"&&B.node.text.trim()!=="")?a.push({kind:"text",node:{type:"text",text:y,marks:{latex:!0}}}):(l=!0,d=y))}else if(I==="m:oMath"){const y=this.ommlToLatex(b);y&&a.push({kind:"text",node:{type:"text",text:y,marks:{latex:!0}}})}}}const m=a.filter(f=>f.kind==="text");if(l&&m.every(f=>f.node.text.trim()===""))return p.push({type:"math",id:this.generateId(),content:d,displayMode:"block",align:n.align==="left"||n.align==="right"||n.align==="center"?n.align:"center"}),p;const h=p.concat(this.buildBlocksFromParagraphItems(a,n));if(t){const f=h.find(I=>I.type==="paragraph"),b=f?.children[0];if(f&&f.children.length===1&&b?.type==="text"&&b.text===""&&b.marks?.fontSize===void 0){const I=this.getDirectChild(e,"w:pPr"),y=this.resolveRunMarks(I?this.getDirectChild(I,"w:rPr"):void 0,n.styleId,t),B={};typeof y.fontSize=="number"&&y.fontSize>0&&(B.fontSize=y.fontSize),y.fontFamily&&!b.marks?.fontFamily&&(B.fontFamily=y.fontFamily),Object.keys(B).length>0&&(b.marks={...b.marks,...B})}}const g=this.getDirectChild(e,"w:pPr"),w=tr(e),u=rt(g,Fr);if(w||u){const f=h.find(b=>b.type==="paragraph");f&&(w&&(f.oxmlAttrs=w),u&&(f.oxmlPPr=u))}if(i.length>0){const f=h.find(b=>b.type==="paragraph");if(f?.id){const b=t??this.fallbackCommentState,I=b.collapsedCommentAnchorBlockById??(b.collapsedCommentAnchorBlockById=new Map);for(const y of i)I.set(y,f.id)}}if(!n.list&&!s){const f=this.parseParagraphPropertyChange(e,r,t);if(f)for(let b=h.length-1;b>=0;b--){const I=h[b];if(I.type!=="paragraph")continue;const y=f.meta.revisionId?`docxrev-${f.meta.revisionId}`:this.generateId(),B=this.revisionAuthorIdentity(f.meta.author),$=JSON.parse(JSON.stringify(I)),W=JSON.parse(JSON.stringify(I));this.applyParsedPropertiesToParagraphNode(W,f.priorProps),I.structuralSuggestionId=y,I.structuralSuggestionKind="change",I.structuralSuggestionLabel="Paragraph format",I.structuralSuggestionRecord=JSON.stringify({id:y,type:"block-change",blockId:I.id,source:B.suggestionSource,authorType:B.suggestionAuthorType,label:"Paragraph format",...f.meta.createdAt!==void 0?{createdAt:f.meta.createdAt}:{},...f.meta.author?{agentName:f.meta.author}:{},beforeBlock:W,acceptedBlock:$});break}}if(s){for(let f=h.length-1;f>=0;f--)if(h[f].type==="paragraph"){h[f].__pilcrowRevision=s;break}}if(o){for(let f=h.length-1;f>=0;f--)if(h[f].type==="paragraph"){h[f].__pilcrowMove=o;break}}return h}static async parseBodyChildren(e,r,t,i,n){const s=[];let o;const a=new Map,l=f=>f.abstractNumId??f.numId,d=f=>{const b=l(f);let I=a.get(b);return I||(I={chainId:this.generateId(),seenNumIds:new Set,started:!1},a.set(b,I)),I},p=f=>{const b=d(f),I=f.hasLevel0StartOverride&&!b.seenNumIds.has(f.numId);if(!b.started||I)return f.startNumber},m=()=>{o&&o.list.children.length>0&&s.push(o.list),o=void 0},h=Array.from(e.children),g=[];let w;const u=(f,b)=>{if(n){for(const I of g)Qt(n,f,I);g.length=0,Qt(n,f,b),w=f}};for(let f=0;f<h.length;f++){const b=h[f],I=b.tagName==="w:bookmarkStart"||this.OXML_RANGE_PAIRS.has(b.tagName)?"start":b.tagName==="w:bookmarkEnd"||[...this.OXML_RANGE_PAIRS.values()].includes(b.tagName)?"end":null;if(this.trackBookmarkMarker(b,t)||this.trackOxmlRangeMarker(b,t)){n&&I==="end"&&w?Qt(n,w,f):n&&I!==null&&g.push(f);continue}const y=i&&b.tagName==="w:sdt"?this.getDirectChild(b,"w:sdtPr"):void 0;let B=-1,$,W;y&&(m(),B=s.length,$=this.generateId(),W=this.sdtAncestorStack[this.sdtAncestorStack.length-1]?.id,this.sdtAncestorStack.push({el:b,id:$}));let z;try{z=await this.parseBodyChild(b,r,t)}finally{y&&this.sdtAncestorStack.pop()}for(const D of z){if(D.kind==="list-item"){if(!o||o.numId!==D.list.numId||o.variant!==D.list.variant){m();const T=D.list.variant==="ordered",F=T?d(D.list):null;o={numId:D.list.numId,variant:D.list.variant,list:{type:"list",id:this.generateId(),variant:D.list.variant,children:[],startNumber:T?p(D.list):void 0,lineSpacing:D.list.lineSpacing,...T&&D.list.formatSpec?{numberingFormat:D.list.formatSpec}:{}}},F&&(o.list.numberingChainId=F.chainId,F.started=!0,F.seenNumIds.add(D.list.numId))}o.list.lineSpacing===void 0&&D.list.lineSpacing!==void 0&&(o.list.lineSpacing=D.list.lineSpacing),o.list.spaceBefore===void 0&&this.applyDocxParagraphSpacing(o.list,D.list);for(const T of["lineSpacing","spaceBefore","spaceAfter"])(D.item[T]===void 0||D.item[T]===o.list[T])&&delete D.item[T];o.list.children.push(D.item),u(o.list,f);continue}m(),s.push(D.block),u(D.block,f)}if(y&&B>=0){m();const D=s.slice(B).map(T=>T.id).filter(T=>!!T);if(D.length>0&&i)try{const T=new XMLSerializer().serializeToString(y);i.push({id:$??this.generateId(),prXml:T,...W?{parentId:W}:{},blockIds:D})}catch{}}}return m(),s}static async parseBodyChild(e,r,t){if(e.tagName==="w:sdt"){const i=this.getDirectChild(e,"w:sdtContent");if(!i)return[];const n=this.sdtAncestorStack,s=n.length>0&&n[n.length-1].el===e;let o;if(!s&&n.length>0&&this.importSdtWrappers){const l=this.getDirectChild(e,"w:sdtPr");if(l)try{o={id:this.generateId(),prXml:new XMLSerializer().serializeToString(l),parentId:n[n.length-1].id}}catch{}}o&&n.push({el:e,id:o.id});const a=[];try{for(let l=0;l<i.children.length;l++)a.push(...await this.parseBodyChild(i.children[l],r,t))}finally{o&&n.pop()}if(o&&this.importSdtWrappers){const l=a.filter(d=>d.kind==="block").map(d=>d.block.id).filter(d=>!!d);l.length>0&&(o.blockIds=l,this.importSdtWrappers.push(o))}return a}if(e.tagName==="w:p"){const i=await this.parseWordParagraphBlocks(e,r,t),n=this.getDirectChild(e,"w:pPr"),s=n?this.getDirectChild(n,"w:sectPr"):void 0;if(s){const a={...this.parseSectionPropertiesElement(s),...this.getDirectChild(s,"w:pgBorders")?{}:{pageBorders:null}},l=i.find(h=>h.type==="paragraph"&&h.__pilcrowRevision),d=l?.__pilcrowRevision?.kind==="merge"?l.__pilcrowRevision:void 0;d&&l&&delete l.__pilcrowRevision;const p={kind:"block",block:{type:"section-break",id:this.generateId(),...a?{layout:a}:{},...d?{diffState:"delete",suggestionId:d.meta.revisionId?`docxrev-${d.meta.revisionId}`:this.generateId(),...d.meta.author?{suggestionAuthorName:d.meta.author}:{},...d.meta.createdAt!==void 0?{suggestionCreatedAt:d.meta.createdAt}:{}}:{}}};if(i.length===1&&i[0].type==="paragraph"&&!i[0].__pilcrowRevision&&i[0].children.every(h=>h.type==="text"&&h.text.length===0))return[p];const m=[];for(const h of i)m.push({kind:"block",block:h});return m.push(p),m}const o=[];for(const a of i){if(a.type!=="paragraph"){o.push({kind:"block",block:a});continue}const l=this.codeBlockFromStyledParagraph(a);if(l){o.push({kind:"block",block:l});continue}const d=this.resolveParagraphProperties(e,r,t);if(!d.list){const p=this.todoItemFromParagraph(a,d);if(p){o.push(p);continue}o.push({kind:"block",block:a});continue}o.push({kind:"list-item",list:d.list,item:this.carryPilcrowMove(a,{type:"list-item",id:this.generateId(),children:a.children,lineSpacing:d.lineSpacing,spaceBefore:d.spaceBefore,spaceAfter:d.spaceAfter,indentLevel:d.list.level})})}return o}if(e.tagName==="w:tbl"){const i=await this.parseTableBlock(e,r,t);return i?[{kind:"block",block:i}]:[]}if(e.tagName==="w:customXml"){const i=[];for(let n=0;n<e.children.length;n++)i.push(...await this.parseBodyChild(e.children[n],r,t));return i}if(!Xr.has(e.tagName))try{return[{kind:"block",block:{type:"docx-raw",id:this.generateId(),origin:"body",...ir(e)}}]}catch{}return[]}static codeBlockFromStyledParagraph(e){const r=e.styleId;if(!r||!r.startsWith(this.CODE_BLOCK_STYLE_ID))return;const t=r.slice(this.CODE_BLOCK_STYLE_ID.length);if(t.length>0&&!t.startsWith("_"))return;const i=t.startsWith("_")?t.slice(1):void 0,n=e.children.filter(s=>s.type==="text").map(s=>s.text).join("");return{type:"code",id:e.id??this.generateId(),content:n,...i?{language:i}:{}}}static todoItemFromParagraph(e,r){if(e.styleId||r.heading)return;const t=e.children[0];if(!t||t.type!=="text")return;const i=this.TODO_MARKERS.find(([a])=>t.text.startsWith(a));if(!i)return;const n=t.text.slice(i[0].length),s=[...n.length>0?[{...t,text:n}]:[],...e.children.slice(1)].filter(a=>a.type==="text");s.length===0&&s.push({type:"text",text:""});const o=Math.max(0,Math.round(Number(e.leftIndent??0)>0?Number(e.leftIndent)-1:0));return{kind:"list-item",list:{numId:"revise-todo",level:o,variant:"todo",lineSpacing:r.lineSpacing,spaceBefore:r.spaceBefore,spaceAfter:r.spaceAfter,contextualSpacing:r.contextualSpacing},item:this.carryPilcrowMove(e,{type:"list-item",id:this.generateId(),children:s,lineSpacing:r.lineSpacing,spaceBefore:r.spaceBefore,spaceAfter:r.spaceAfter,indentLevel:o,...i[1]?{checked:!0}:{}})}}static carryPilcrowMove(e,r){const t=e.__pilcrowMove;return t&&(r.__pilcrowMove=t),r}static buildBlocksFromParagraphItems(e,r){const t=[];let i=[];const n=(s=!1)=>{if(i.length===0&&!s)return;const o={type:"paragraph",id:this.generateId(),children:i.length>0?i:[{type:"text",text:"",marks:{}}]};r.align&&(o.align=r.align),r.leftIndent!==void 0&&(o.leftIndent=r.leftIndent),r.firstLineIndent!==void 0&&(o.firstLineIndent=r.firstLineIndent),r.heading&&(o.heading=r.heading),r.lineSpacing!==void 0&&(o.lineSpacing=r.lineSpacing),this.applyDocxParagraphSpacing(o,r),r.keepNext&&(o.keepNext=!0),r.keepLines&&(o.keepLines=!0),r.widowControl===!1&&(o.widowControl=!1),r.bordersJson&&(o.borders=r.bordersJson),r.shading&&(o.shading=r.shading);const a=r.styleId;a&&a.toLowerCase()!=="normal"&&(o.styleId=a),r.tabStops&&r.tabStops.length&&(o.tabStops=JSON.stringify(r.tabStops));const l=this.directionAttrFor(r.direction,this.paragraphNodeText(o));l&&(o.direction=l),t.push(o),i=[]};for(const s of e){if(s.kind==="text"){i.push(s.node);continue}if(s.kind==="pagebreak"){n(),t.push(this.createPageBreakBlock());continue}if(s.kind==="blocks"){n(),t.push(...s.blocks);continue}n(),t.push(s.node)}return t.length===0&&i.length===0?n(!0):n(),t}static resolveParagraphProperties(e,r,t){if(!t)return this.parseWordParagraphProperties(e,r);const i=this.getDirectChild(e,"w:pPr"),n=this.getDirectChild(i||e,"w:pStyle")?.getAttribute("w:val")||void 0,s={isList:!1,styleId:n},o=this.effectiveParagraphStyleId(n,t.styles),a=[];t.styles.paragraphDefault&&a.push(t.styles.paragraphDefault),a.push(...this.resolveStyleChainPPr(o,t.styles,"paragraph")),i&&a.push(i);const l=this.resolveParagraphFontSizePx(i,o,t);for(const d of a)this.applyParagraphPropertiesFromElement(s,d,r,t,l);return this.resolveLogicalAlignment(s),s}static lineSpacingFromDocxSpacing(e,r,t){const i=(r||"auto").trim().toLowerCase();if(i!=="exact"&&i!=="atleast")return Math.round(e/240*100)/100;const n=t&&t>0?t:Ae.paragraph,s=e/20*(4/3),o=Math.round(s/n*100)/100;return i==="atleast"?o>Ai.paragraph?o:void 0:Math.max(.1,o)}static effectiveParagraphStyleId(e,r){return e??r.defaultStyleIdByType?.get("paragraph")}static resolveParagraphFontSizePx(e,r,t){const i=e?this.getDirectChild(e,"w:rPr"):void 0,n=this.resolveRunMarks(i,r,t);return typeof n.fontSize=="number"&&n.fontSize>0?n.fontSize:Ae.paragraph}static resolveStyleChainPPr(e,r,t){return e?this.resolveStyleChain(e,r,t).map(i=>i.pPr).filter(Boolean):[]}static resolveStyleChainRPr(e,r,t){return e?this.resolveStyleChain(e,r,t).map(i=>i.rPr).filter(Boolean):[]}static resolveStyleChain(e,r,t){const i=[],n=new Set;let s=r.stylesById.get(e);for(;s&&!n.has(s.id);)n.add(s.id),(!t||s.type===t)&&i.unshift(s),s=s.basedOn?r.stylesById.get(s.basedOn):void 0;return i}static applyParagraphPropertiesFromElement(e,r,t,i,n){if(!r)return;this.getDirectChild(r,"w:keepNext")&&(e.keepNext=this.isOn(r,"w:keepNext")),this.getDirectChild(r,"w:keepLines")&&(e.keepLines=this.isOn(r,"w:keepLines")),this.getDirectChild(r,"w:widowControl")&&(e.widowControl=this.isOn(r,"w:widowControl")),this.getDirectChild(r,"w:bidi")&&(e.direction=this.isOn(r,"w:bidi")?"rtl":"ltr"),this.parseParagraphDecoration(r,e),this.applyTabStopsFromPPr(e,r),this.applyJcFromPPr(e,r);const s=this.getDirectChild(r,"w:ind");if(s){const f=this.parseTwipsAttribute(s,"w:start")??this.parseTwipsAttribute(s,"w:left");if(f===0)e.leftIndent=0;else if(f!==void 0&&f>0){const y=Dt(this.twipsToPx(f),{indentStepPx:t,storedAsUnits:!1});y!==void 0&&(e.leftIndent=y)}const b=this.parseTwipsAttribute(s,"w:firstLine"),I=this.parseTwipsAttribute(s,"w:hanging");if(I!==void 0&&I>0)e.firstLineIndent=-1;else if(b===0)e.firstLineIndent=0;else if(b!==void 0&&b>0){const y=Dt(this.twipsToPx(b),{indentStepPx:t,storedAsUnits:!1,firstLine:!0});y!==void 0&&(e.firstLineIndent=y)}}const o=this.parseOnOffElement(this.getDirectChild(r,"w:pageBreakBefore"));o!==void 0&&(e.pageBreakBefore=o);const a=this.getDirectChild(r,"w:spacing"),l=a?.getAttribute("w:line");if(l){const f=parseInt(l,10);if(Number.isFinite(f)&&f>0){const b=this.lineSpacingFromDocxSpacing(f,a?.getAttribute("w:lineRule"),n);b!==void 0&&(e.lineSpacing=b)}}const d=f=>Math.max(0,Math.round(this.twipsToPx(f)*100)/100),p=this.parseTwipsAttribute(a,"w:before");p!==void 0&&(e.spaceBefore=d(p));const m=this.parseTwipsAttribute(a,"w:after");m!==void 0&&(e.spaceAfter=d(m)),this.getDirectChild(r,"w:contextualSpacing")&&(e.contextualSpacing=this.isOn(r,"w:contextualSpacing"));const h=this.getDirectChild(r,"w:outlineLvl")?.getAttribute("w:val"),g=h?parseInt(h,10):NaN;Number.isFinite(g)&&g>=0&&g<6&&(e.heading=g+1);const w=this.getDirectChild(r,"w:pStyle")?.getAttribute("w:val");if(w){e.styleId=w;const f=i?this.headingLevelForStyle(i.styles.stylesById.get(w)):this.headingLevelForStyle({id:w});f&&(e.heading=f)}const u=i?this.getDirectChild(r,"w:numPr"):void 0;if(u&&i){const f=this.getDirectChild(u,"w:ilvl"),b=this.getDirectChild(u,"w:numId")?.getAttribute("w:val"),I=f?.getAttribute("w:val"),y=I&&Number.isFinite(parseInt(I,10))?parseInt(I,10):0;if(b&&b!=="0"){const B=this.resolveListInfo(b,y,i.numbering);B&&(e.list={...B,lineSpacing:e.lineSpacing,spaceBefore:e.spaceBefore,spaceAfter:e.spaceAfter,contextualSpacing:e.contextualSpacing},e.isList=!0)}}}static headingLevelForStyle(e){if(!e)return;const r=[e.id,e.name].filter(Boolean).map(t=>t.toLowerCase().replace(/[\s_-]+/g,""));for(const t of r){const i=t.match(/heading([1-6])$/);if(i)return parseInt(i[1],10)}}static resolveListInfo(e,r,t){const i=t.nums.get(e),n=i?.abstractNumId?t.abstractNums.get(i.abstractNumId):void 0,s=n?.levels.get(r);if(!s)return;const o=(s.format||"").toLowerCase()==="bullet"?"unordered":"ordered",a=i?.levelStartOverrides.get(r)??s.start;let l;if(o==="ordered"&&n){const d=[];let p=!1;for(let m=0;m<=2;m++){const h=n.levels.get(m);(h?.format||h?.text)&&(p=!0),d.push({...h?.format?{numFmt:h.format}:{},...h?.text?{lvlText:h.text}:{}})}p&&(l=JSON.stringify(d))}return{numId:e,level:r,variant:o,startNumber:a,abstractNumId:i?.abstractNumId,hasLevel0StartOverride:i?.levelStartOverrides.has(0)??!1,formatSpec:l}}static async parseHyperlinkItems(e,r,t){const i=e.getAttribute("r:id"),n=e.getAttribute("w:anchor"),s=(i?t?.relationships.get(i)?.target:void 0)||(n?`#${n}`:void 0),o=[];for(let a=0;a<e.children.length;a++){const l=e.children[a];this.trackBookmarkMarker(l,t)||this.trackOxmlRangeMarker(l,t)||l.tagName==="w:r"&&o.push(...await this.parseWordRunItems(l,r,t,s))}return o}static revisionAuthorIdentity(e){return e?.trim()===It?{suggestionSource:"agent",suggestionAuthorType:"ai"}:{suggestionSource:"manual",suggestionAuthorType:"human"}}static indexImportedMoveRanges(e){const r=new WeakMap,t={from:[],to:[]},i=(s,o)=>{const a=s?.getAttribute("w:name")?.trim(),l=s?.getAttribute("w:id")?.trim();if(!s||!a||!l)return;const d=s.getAttribute("w:date"),p=d?Date.parse(d):NaN;return{version:1,name:a,role:o,rangeId:l,...s.getAttribute("w:author")?.trim()?{rangeAuthor:s.getAttribute("w:author").trim()}:{},...Number.isFinite(p)?{rangeCreatedAt:p}:{}}},n=Array.from(e.getElementsByTagName("*"));for(let s=0;s<n.length;s++){const o=n[s],a=o.tagName==="w:moveFromRangeStart"?"from":o.tagName==="w:moveToRangeStart"?"to":void 0;if(a){const p=i(o,a);p&&t[a].push(p);continue}const l=o.tagName==="w:moveFrom"?"from":o.tagName==="w:moveTo"?"to":void 0;if(l){let p=t[l][t[l].length-1];const m=o.parentElement,h=m?.parentElement;!p&&m?.tagName==="w:rPr"&&h?.tagName==="w:pPr"&&h.parentElement?.tagName==="w:p"&&(p=i(h.parentElement.getElementsByTagName(l==="from"?"w:moveFromRangeStart":"w:moveToRangeStart")[0],l));const g=o.getAttribute("w:id")?.trim();p&&g&&r.set(o,{...p,wrapperId:g,fallbackSuggestionId:`docxrev-${g}`});continue}const d=o.tagName==="w:moveFromRangeEnd"?"from":o.tagName==="w:moveToRangeEnd"?"to":void 0;if(d){const p=o.getAttribute("w:id")?.trim(),m=t[d],h=p?m.map(g=>g.rangeId).lastIndexOf(p):m.length-1;h>=0&&m.splice(h,1)}}return r}static parseDocxMoveMark(e){if(!(typeof e!="string"||!e))try{const r=JSON.parse(e);return r.version!==1||typeof r.name!="string"||!r.name||r.role!=="from"&&r.role!=="to"||typeof r.rangeId!="string"||!r.rangeId||typeof r.wrapperId!="string"||!r.wrapperId||typeof r.fallbackSuggestionId!="string"||!r.fallbackSuggestionId?void 0:r}catch{return}}static finalizeImportedMovePairs(e){const r=new Map,t=i=>{if(!i||typeof i!="object")return;if(Array.isArray(i)){i.forEach(t);return}const n=i;if(n.type==="text"&&n.marks?.docxMove){const s=this.parseDocxMoveMark(n.marks.docxMove);if(s){const o=r.get(s.name)??{roles:new Set,nodes:[]};o.roles.add(s.role),o.nodes.push(n),r.set(s.name,o)}}t(n.children)};t(e);for(const i of r.values())if(!(i.roles.has("from")&&i.roles.has("to")))for(const n of i.nodes){const s=this.parseDocxMoveMark(n.marks?.docxMove);!s||!n.marks||(n.marks.suggestionId=s.fallbackSuggestionId,delete n.marks.docxMove)}}static hasDocxMoveMarks(e){if(!e||typeof e!="object")return!1;if(Array.isArray(e))return e.some(t=>this.hasDocxMoveMarks(t));const r=e;return!!r.marks?.docxMove||this.hasDocxMoveMarks(r.children)}static applyTabStopsFromPPr(e,r){const t=this.getDirectChild(r,"w:tabs");if(!t)return;const i=e.tabStops?[...e.tabStops]:[];for(let n=0;n<t.children.length;n++){const s=t.children[n];if(s.tagName!=="w:tab")continue;const o=parseFloat(s.getAttribute("w:pos")||"");if(!Number.isFinite(o)||o<0)continue;const a=this.twipsToPx(o),l=i.findIndex(g=>Math.abs(g.pos-a)<.5);l>=0&&i.splice(l,1);const d=(s.getAttribute("w:val")||"left").toLowerCase();if(d==="clear")continue;let p;if(d==="right"||d==="end")p="right";else if(d==="center")p="center";else if(d==="decimal")p="decimal";else if(d==="left"||d==="start"||d==="num")p="left";else continue;const m={pos:a,align:p},h=(s.getAttribute("w:leader")||"").toLowerCase();h==="dot"||h==="middledot"?m.leader="dot":h==="hyphen"?m.leader="hyphen":(h==="underscore"||h==="heavy")&&(m.leader="underscore"),i.push(m)}i.sort((n,s)=>n.pos-s.pos),i.length>0?e.tabStops=i:delete e.tabStops}static parseParagraphDecoration(e,r){const t=this.getDirectChild(e,"w:pBdr");if(t){let n={};if(r.bordersJson)try{n=JSON.parse(r.bordersJson)}catch{n={}}for(const s of["top","bottom","left","right"]){const o=this.getDirectChild(t,`w:${s}`);if(!o)continue;const a=(o.getAttribute("w:val")||"single").toLowerCase();if(a==="none"||a==="nil"){n[s]={style:"none",width:0,color:"#000000"};continue}const l=["dashed","dotted","double"].includes(a)?a:"single",d=parseInt(o.getAttribute("w:sz")||"4",10),p=Math.max(.5,Math.round((Number.isFinite(d)?d:4)/6*100)/100),m=(o.getAttribute("w:color")||"auto").trim(),h=m.toLowerCase()==="auto"?"#000000":`#${m.replace(/^#/,"")}`;n[s]={style:l,width:p,color:h}}Object.keys(n).length>0&&(r.bordersJson=JSON.stringify(n))}const i=this.getDirectChild(e,"w:shd");if(i){const n=(i.getAttribute("w:fill")||"").trim(),s=(i.getAttribute("w:val")||"clear").toLowerCase();n&&n.toLowerCase()!=="auto"?r.shading=`#${n.replace(/^#/,"")}`:(!n||n.toLowerCase()==="auto"||s==="nil"||s==="none")&&(r.shading="transparent")}}static trackBookmarkMarker(e,r){const t=r??this.fallbackCommentState;if(e.tagName==="w:bookmarkStart"){const i=e.getAttribute("w:id"),n=e.getAttribute("w:name");return i&&n&&n!=="_GoBack"&&((t.openBookmarkNames??(t.openBookmarkNames=new Set)).add(n),(t.bookmarkNameById??(t.bookmarkNameById=new Map)).set(i,n)),!0}if(e.tagName==="w:bookmarkEnd"){const i=e.getAttribute("w:id"),n=i?t.bookmarkNameById?.get(i):void 0;return n&&t.openBookmarkNames?.delete(n),!0}return!1}static trackOxmlRangeMarker(e,r){const t=r??this.fallbackCommentState;if(this.OXML_RANGE_PAIRS.has(e.tagName)){const i=e.getAttribute("w:id");if(i)try{const n={id:this.generateId(),tagName:e.tagName,startXml:new XMLSerializer().serializeToString(e),endXml:""};(t.openOxmlRanges??(t.openOxmlRanges=new Map)).set(i,n)}catch{}return!0}for(const[i,n]of this.OXML_RANGE_PAIRS){if(e.tagName!==n)continue;const s=e.getAttribute("w:id"),o=s?t.openOxmlRanges?.get(s):void 0;if(o&&s){try{o.endXml=new XMLSerializer().serializeToString(e),this.importOxmlRanges?.push(o)}catch{}t.openOxmlRanges.delete(s)}return!0}return!1}static async parseFldSimpleItems(e,r,t){const i=(e.getAttribute("w:instr")||"").trim(),n=await this.parseInlineItemsFromChildren(e,r,t);if(!i)return n;for(const s of n)s.kind==="text"&&s.node&&(s.node.marks={...s.node.marks??{},fieldInstr:i});return n}static trackCommentRangeMarker(e,r){const t=r??this.fallbackCommentState;if(e.tagName==="w:commentRangeStart"){const i=e.getAttribute("w:id");return i&&(t.openCommentIds??(t.openCommentIds=new Set)).add(i),!0}if(e.tagName==="w:commentRangeEnd"){const i=e.getAttribute("w:id");return i&&t.openCommentIds?.delete(i),!0}return!1}static stampOpenComments(e,r){const t=(r??this.fallbackCommentState).openCommentIds;if(!t||t.size===0)return e;const i=[...t].sort().map(n=>`docxcmt-${n}`).join(",");for(const n of e)n.kind==="text"&&n.node&&(n.node.marks={...n.node.marks??{},comment:i});return e}static async parseInlineSdtItems(e,r,t){const i=this.getDirectChild(e,"w:sdtContent");if(!i)return[];const n=this.importSdtWrappers;let s;if(n){const a=this.getDirectChild(e,"w:sdtPr");if(a)try{const l=this.sdtAncestorStack[this.sdtAncestorStack.length-1];s={id:this.generateId(),prXml:new XMLSerializer().serializeToString(a),scope:"inline",...l?{parentId:l.id}:{}}}catch{}}s&&this.sdtAncestorStack.push({el:e,id:s.id});let o;try{o=await this.parseInlineItemsFromChildren(i,r,t)}finally{s&&this.sdtAncestorStack.pop()}if(s&&n){let a=!1;for(const l of o)if(l.kind==="text"&&l.node){const d=l.node.marks?.sdtInline;l.node.marks={...l.node.marks??{},sdtInline:d?`${d},${s.id}`:s.id},a=!0}a&&n.push(s)}return o}static async parseInlineItemsFromChildren(e,r,t){const i=[];for(let n=0;n<e.children.length;n++){const s=e.children[n];if(!this.trackCommentRangeMarker(s,t)&&!(this.trackBookmarkMarker(s,t)||this.trackOxmlRangeMarker(s,t))){if(s.tagName==="w:fldSimple"){i.push(...await this.parseFldSimpleItems(s,r,t));continue}if(s.tagName==="mc:AlternateContent"){const o=this.selectAlternateContentBranch(s);o&&i.push(...await this.parseInlineItemsFromChildren(o,r,t));continue}s.tagName==="w:r"?i.push(...this.stampOpenComments(await this.parseWordRunItems(s,r,t),t)):s.tagName==="w:hyperlink"?i.push(...await this.parseHyperlinkItems(s,r,t)):s.tagName==="w:ins"||s.tagName==="w:del"||s.tagName==="w:moveFrom"||s.tagName==="w:moveTo"?i.push(...await this.parseTrackedChangeItems(s,r,t)):s.tagName==="w:sdt"&&i.push(...await this.parseInlineSdtItems(s,r,t))}}return i}static parseTrackedRevisionMeta(e){const r=e.getAttribute("w:id"),t=e.getAttribute("w:author")?.trim()||void 0,i=e.getAttribute("w:date"),n=i?Date.parse(i):NaN;return{revisionId:r&&r.length>0?r:null,author:t,createdAt:Number.isFinite(n)?n:void 0}}static async parseTrackedChangeItems(e,r,t,i){const n=e.tagName==="w:ins"||e.tagName==="w:moveTo",s=e.tagName==="w:moveFrom"||e.tagName==="w:moveTo",o=this.parseTrackedRevisionMeta(e),a=s?(t??this.fallbackCommentState).moveRangeByWrapper?.get(e):void 0,l=a?`docxmove-${encodeURIComponent(a.name)}`:o.revisionId?`docxrev-${o.revisionId}`:this.generateId(),d={...n?{insertion:!0}:{deletion:!0},suggestionId:l,...this.revisionAuthorIdentity(o.author),suggestionLabel:s?"Move":n?"Insert":"Delete",...o.createdAt!==void 0?{suggestionCreatedAt:o.createdAt}:{},...o.author?{suggestionAuthorName:o.author}:{},...a?{docxMove:JSON.stringify(a)}:{},...!n&&i?{layeredInsertion:JSON.stringify(i)}:{}},p=h=>h.map(g=>g.kind==="text"?{...g,node:{...g.node,marks:{...g.node.marks??{},...d}}}:g),m=[];for(let h=0;h<e.children.length;h++){const g=e.children[h];this.trackCommentRangeMarker(g,t)||this.trackBookmarkMarker(g,t)||this.trackOxmlRangeMarker(g,t)||(g.tagName==="w:r"?m.push(...p(this.stampOpenComments(await this.parseWordRunItems(g,r,t),t))):g.tagName==="w:hyperlink"?m.push(...p(this.stampOpenComments(await this.parseHyperlinkItems(g,r,t),t))):g.tagName==="w:del"&&n?m.push(...await this.parseTrackedChangeItems(g,r,t,{id:l,...(()=>{const w=this.revisionAuthorIdentity(o.author);return{source:w.suggestionSource,authorType:w.suggestionAuthorType}})(),createdAt:o.createdAt,label:"Insert",authorName:o.author})):(g.tagName==="w:ins"||g.tagName==="w:del")&&m.push(...await this.parseTrackedChangeItems(g,r,t)))}return m}static async parseWordRunItems(e,r,t,i,n){const s=this.getDirectChild(e,"w:rPr"),o=n?{...n}:this.resolveRunMarks(s,r.styleId,t,i);if(!n&&!r.heading&&o.fontSize===Ae.paragraph&&this.docDefaultRunSizePx(t)===Ae.paragraph&&delete o.fontSize,!n){const h=rt(s,Rr);h&&(o.oxmlRPr=h)}const a=!n&&s?this.getDirectChild(s,"w:rPrChange"):void 0;if(a){const h=this.parseTrackedRevisionMeta(a),g=this.getDirectChild(a,"w:rPr"),w=this.resolveRunMarks(g,r.styleId,t,i);Object.assign(o,{formatChange:!0,suggestionId:h.revisionId?`docxrev-${h.revisionId}`:this.generateId(),...this.revisionAuthorIdentity(h.author),suggestionLabel:"Format",...h.createdAt!==void 0?{suggestionCreatedAt:h.createdAt}:{},...h.author?{suggestionAuthorName:h.author}:{},suggestionPriorAttributes:JSON.stringify(w??{})})}const l=[];let d="";const p=t??this.fallbackCommentState,m=()=>{if(!d)return;const h={...o},g=p.openBookmarkNames;g&&g.size>0&&(h.bookmark=[...g].sort().join(","));const w=p.openOxmlRanges;w&&w.size>0&&(h.oxmlRange=[...w.values()].map(f=>f.id).sort().join(","));const u=p.fieldInstrStack?.[0];u?.inResult&&u.instr.trim()&&(h.fieldInstr=u.instr.trim()),l.push({kind:"text",node:{type:"text",text:d,marks:Object.keys(h).length>0?h:void 0}}),d=""};for(let h=0;h<e.children.length;h++){const g=e.children[h];if(g.tagName==="w:t"){d+=g.textContent||"";continue}if(g.tagName==="w:fldChar"){const w=g.getAttribute("w:fldCharType"),u=p.fieldInstrStack??(p.fieldInstrStack=[]);m(),w==="begin"?u.push({instr:"",inResult:!1}):w==="separate"?u.length>0&&(u[u.length-1].inResult=!0):w==="end"&&u.pop();continue}if(g.tagName==="w:instrText"){const w=p.fieldInstrStack;w&&w.length>0&&(w[w.length-1].instr+=g.textContent||"");continue}if(g.tagName==="w:footnoteReference"||g.tagName==="w:endnoteReference"){const w=g.getAttribute("w:id");if(w){m();const u=g.tagName==="w:endnoteReference"?"docxen":"docxfn";l.push({kind:"text",node:{type:"text",text:"0",marks:{...o,footnoteRef:`${u}-${w}`,superscript:!0}}})}continue}if(g.tagName==="w:delText"){d+=g.textContent||"";continue}if(g.tagName==="w:tab"){d+=" ";continue}if(g.tagName==="w:br"){(g.getAttribute("w:type")||"").trim().toLowerCase()==="page"?(m(),l.push({kind:"pagebreak"})):d+=`
6
- `;continue}if(g.tagName!=="w:lastRenderedPageBreak"){if(g.tagName==="mc:AlternateContent"){m();const w=this.selectAlternateContentBranch(g);w&&l.push(...await this.parseWordRunItems(w,r,t,i,o));continue}if(g.tagName==="w:drawing"){m();const w=await this.parseImageFromDrawing(g,r.align,t);w&&l.push({kind:"image",node:w});const u=await this.parseTextBoxContent(g,t);if(u.length>0&&l.push({kind:"blocks",blocks:u}),!w&&u.length===0){const f=this.rawChipFromRunChild(g);f&&l.push({kind:"blocks",blocks:[f]})}continue}if(g.tagName==="w:pict"||g.tagName==="w:object"){m();const w=g.getElementsByTagName("*");let u=!1;for(let b=0;b<w.length;b++){const I=(w[b].getAttribute("o:hr")||"").toLowerCase();if(I==="t"||I==="true"||I==="1"){u=!0;break}}if(u){const b={type:"paragraph",id:this.generateId(),children:[{type:"text",text:"",marks:{}}],borders:Ci()};l.push({kind:"blocks",blocks:[b]});continue}const f=await this.parseTextBoxContent(g,t);if(f.length>0)l.push({kind:"blocks",blocks:f});else{const b=this.rawChipFromRunChild(g);b&&l.push({kind:"blocks",blocks:[b]})}continue}}}return m(),l}static rawChipFromRunChild(e){try{return{type:"docx-raw",id:this.generateId(),origin:"run",...ir(e)}}catch{return}}static async parseTextBoxContent(e,r){const t=e.getElementsByTagName("w:txbxContent");if(t.length===0)return[];const i=Te(void 0).indentStepPx,n=[];for(let s=0;s<t.length;s++){const o=t[s];let a=o.parentElement,l=!1;for(;a&&a!==e;){if(a.tagName==="mc:Fallback"){const p=a.parentElement,m=p?Array.from(p.children).find(h=>h.tagName==="mc:Choice"):void 0;l=!!(m&&m.getElementsByTagName("w:txbxContent").length>0);break}a=a.parentElement}if(l)continue;const d=(await this.parseBodyChildren(o,i,r)).filter(p=>p.type!=="paragraph"||p.children.some(m=>m.type==="text"&&m.text.trim()!==""));n.push(...d)}return n}static selectAlternateContentBranch(e){let r;for(let t=0;t<e.children.length;t++){const i=e.children[t];if(i.tagName==="mc:Fallback"){r=i;continue}if(i.tagName==="mc:Choice"&&(i.getElementsByTagName("w:t").length>0||i.getElementsByTagName("w:delText").length>0||i.getElementsByTagName("w:txbxContent").length>0||i.getElementsByTagName("a:blip").length>0))return i}return r}static resolveRunMarks(e,r,t,i){const n={};if(t){const s=[];t.styles.runDefault&&s.push(t.styles.runDefault),s.push(...this.resolveStyleChainRPr(this.effectiveParagraphStyleId(r,t.styles),t.styles,"paragraph"));const o=e&&this.getDirectChild(e,"w:rStyle")?.getAttribute("w:val")||void 0;s.push(...this.resolveStyleChainRPr(o,t.styles,"character")),e&&s.push(e);for(const a of s)this.applyRunPropertiesFromElement(n,a,t.themeFonts);o===this.CODE_INLINE_STYLE_ID&&(n.code=!0,/courier/i.test(n.fontFamily??"")&&delete n.fontFamily,/^(light)?gray$/i.test(n.backgroundColor??"")&&delete n.backgroundColor)}else e&&this.applyRunPropertiesFromElement(n,e);return i&&(n.link=i),n}static applyRunPropertiesFromElement(e,r,t){if(!r)return;const i=(y,B)=>{this.getDirectChild(r,y)&&(e[B]=this.isOn(r,y))},n=()=>new Set(e.docxRunPropertyResets?.split(",").map(y=>y.trim()).filter(Boolean)??[]),s=(y,B)=>{const $=n();B?$.add(y):$.delete(y),$.size>0?e.docxRunPropertyResets=[...$].sort().join(","):delete e.docxRunPropertyResets};i("w:b","bold"),i("w:i","italic");const o=this.getDirectChild(r,"w:u");if(o){const y=(o.getAttribute("w:val")||"").toLowerCase();e.underline=!["none","0","false","off"].includes(y)}i("w:strike","strikethrough"),i("w:dstrike","doubleStrikethrough"),i("w:smallCaps","smallCaps"),i("w:caps","allCaps"),i("w:vanish","hidden");const a=this.getDirectChild(r,"w:lang")?.getAttribute("w:val");a&&(e.lang=a);const l=(this.getDirectChild(r,"w:spacing")?.getAttribute("w:val")||"").trim();if(l!==""){const y=parseInt(l,10);Number.isFinite(y)&&(e.letterSpacing=Math.round(y/15*100)/100)}const d=(this.getDirectChild(r,"w:vertAlign")?.getAttribute("w:val")||"").toLowerCase();d==="superscript"?(e.superscript=!0,e.subscript=!1):d==="subscript"?(e.superscript=!1,e.subscript=!0):d==="baseline"&&(e.superscript=!1,e.subscript=!1);const p=this.getDirectChild(r,"w:color"),m=p?.getAttribute("w:val");p&&m?.toLowerCase()==="auto"?(delete e.color,s("color",!0)):m&&(e.color=`#${m.replace(/^#/,"")}`,s("color",!1));const h=this.getDirectChild(r,"w:highlight")?.getAttribute("w:val");h?.toLowerCase()==="none"?(delete e.backgroundColor,s("highlight",!0)):h&&(e.backgroundColor=this.highlightValueToColor(h),s("highlight",!1));const g=this.getDirectChild(r,"w:shd")?.getAttribute("w:fill");if(g&&["auto","none"].includes(g.toLowerCase()))delete e.backgroundColor,s("highlight",!0);else if(g){const y=qt(g);y&&(e.backgroundColor=y,s("highlight",!1))}const w=this.getDirectChild(r,"w:rFonts"),u=w?.getAttribute("w:asciiTheme")||w?.getAttribute("w:hAnsiTheme")||w?.getAttribute("w:cstheme")||w?.getAttribute("w:eastAsiaTheme"),f=u&&t?u.toLowerCase().startsWith("major")?t.major:t.minor:void 0,b=w?.getAttribute("w:ascii")||w?.getAttribute("w:hAnsi")||w?.getAttribute("w:cs")||w?.getAttribute("w:eastAsia")||f;b&&(e.fontFamily=b);const I=this.getDirectChild(r,"w:sz")?.getAttribute("w:val");if(I){const y=parseInt(I,10);Number.isFinite(y)&&y>0&&(e.fontSize=Math.max(1,Math.round(y*(2/3)*100)/100))}}static collectLinkedMoveSides(e){const r=new Map,t=i=>{if(!i||typeof i!="object")return;if(Array.isArray(i)){i.forEach(t);return}const n=i,s=n.marks;if(n.type==="text"&&s?.docxMove&&typeof s.suggestionId=="string"){const o=this.parseDocxMoveMark(s.docxMove);if(o&&(o.role==="from"&&s.deletion||o.role==="to"&&s.insertion)){const a=r.get(s.suggestionId)??{};if(!a[o.role]){const l=this.suggestionRevisionAttrs(s);a[o.role]={move:o,author:o.rangeAuthor??l.author,date:typeof o.rangeCreatedAt=="number"?new Date(o.rangeCreatedAt).toISOString():l.date}}r.set(s.suggestionId,a)}}t(n.children)};t(e);for(const[i,n]of r)(!n.from||!n.to)&&r.delete(i);return r}static linkedMoveSideFor(e,r){if(typeof e!="string")return;const t=r==="delete"?"from":r==="insert"?"to":void 0;return t?this.exportLinkedMoveSides?.get(e)?.[t]:void 0}static collectLinkedMoveBlockIds(e,r){const t=new Map;if(r.size===0)return t;const i=o=>o==="delete"?"from":o==="insert"?"to":void 0,n=new Map,s=o=>{const a=n.get(o);if(n.delete(o),!a?.marked)return;const l=t.get(o)??new Set;a.ids.forEach(d=>l.add(d)),t.set(o,l)};for(const o of e){const a=new Set,l=new Set,d=[],p=m=>{if(!m||typeof m!="object")return;if(Array.isArray(m)){m.forEach(p);return}const h=m;typeof h.id=="string"&&d.push(h.id);const g=i(h.structuralSuggestionKind);typeof h.structuralSuggestionId=="string"&&g&&a.add(`${h.structuralSuggestionId}\0${g}`);const w=i(h.diffState);typeof h.suggestionId=="string"&&w&&a.add(`${h.suggestionId}\0${w}`);const u=h.marks;if(h.type==="text"&&u?.docxMove&&typeof u.suggestionId=="string"){const f=this.parseDocxMoveMark(u.docxMove);if(f&&(f.role==="from"&&u.deletion||f.role==="to"&&u.insertion)){const b=`${u.suggestionId}\0${f.role}`;a.add(b),l.add(b)}}p(h.children)};p(o);for(const m of Array.from(n.keys()))a.has(m)||s(m);for(const m of a){const h=n.get(m)??{marked:!1,ids:[]};h.marked||(h.marked=l.has(m)),h.ids.push(...d),n.set(m,h)}}for(const o of Array.from(n.keys()))s(o);return t}static isInLinkedMoveRange(e,r){return!this.exportLinkedMoveBlockIds||typeof e.id!="string"?!0:this.exportLinkedMoveBlockIds.get(`${e.structuralSuggestionId}\0${r}`)?.has(e.id)??!1}static inferDefaultRunSizeHalfPoints(e){const r=e.stylesheet?.paragraphStyles.find(t=>t.default)?.runMarks?.fontSize;return typeof r=="number"&&r>0&&r!==Ae.paragraph?this.DEFAULT_RUN_SIZE_HALF_POINTS:void 0}static docDefaultRunSizePx(e){const r=e?.styles.runDefault;if(!r)return;const t=this.getDirectChild(r,"w:sz")?.getAttribute("w:val"),i=t?parseInt(t,10):NaN;return Number.isFinite(i)&&i>0?Math.max(1,Math.round(i*(2/3)*100)/100):void 0}static isOnAttribute(e){const r=(e||"").trim().toLowerCase();return r==="1"||r==="true"||r==="on"}static isOn(e,r){const t=this.getDirectChild(e,r);if(!t)return!1;const i=(t.getAttribute("w:val")||"").toLowerCase();return i!=="false"&&i!=="0"&&i!=="off"}static async parseImageFromDrawing(e,r,t){if(!t)return null;const i=e.getElementsByTagName("a:blip")[0],n=i?.getAttribute("r:embed")||i?.getAttribute("r:link")||"";if(!n)return null;const s=t.relationships.get(n);if(!s)return null;const o=i?this.findSvgBlipRelationshipId(i):void 0;let a,l;if(o){const B=t.relationships.get(o),$=B?t.zip.file(B.target):void 0;$&&(a=await $.async("uint8array"),l="image/svg+xml")}if(!a||!l){const B=t.zip.file(s.target);if(!B)return null;a=await B.async("uint8array"),l=this.getContentTypeForPart(s.target,t.contentTypes)||this.inferImagePartMimeType(s.target)}if(!a)return null;const d=l?this.vectorFormatForMimeType(l):void 0;if(!d&&(!l||!this.isSupportedImageMimeType(l)))return null;const p=e.getElementsByTagName("wp:extent")[0]||e.getElementsByTagName("a:ext")[0],m=p?.getAttribute("cx"),h=p?.getAttribute("cy"),g=m?Math.max(1,Math.round(parseInt(m,10)/9525)):200,w=h?Math.max(1,Math.round(parseInt(h,10)/9525)):200,u=e.getElementsByTagName("wp:docPr")[0],f=u?.getAttribute("descr")||u?.getAttribute("title")||u?.getAttribute("name")||void 0,b=this.buildImageDataUrl(a,d?d==="emf"?"image/x-emf":"image/x-wmf":l),I={type:"image",id:this.generateId(),src:b,width:g,height:w,alt:f,align:r&&r!=="justify"?r:void 0};d&&(I.originalFormat=d,I.originalDataUrl=b);const y=this.getDirectChild(e,"wp:anchor");if(y)try{I.anchorXml=this.serializeXmlPreservingPrefixes(y)}catch{}return I}static findSvgBlipRelationshipId(e){const r=e.getElementsByTagName("*");for(let t=0;t<r.length;t++){const i=r[t],n=i.tagName||"";if(n==="svgBlip"||n.endsWith(":svgBlip"))return i.getAttribute("r:embed")||i.getAttribute("r:link")||void 0}}static inferImagePartMimeType(e){const r=e.split(".").pop()?.toLowerCase();switch(r){case"svg":return"image/svg+xml";case"emf":return"image/x-emf";case"wmf":return"image/x-wmf";default:return r?this.inferMimeTypeFromPath(e):void 0}}static vectorFormatForMimeType(e){const r=e.toLowerCase();if(r==="image/x-emf"||r==="image/emf")return"emf";if(r==="image/x-wmf"||r==="image/wmf")return"wmf"}static async parseTableBlock(e,r,t){const i=[],n=[],s=[],o=(k,X)=>{for(const G of Array.from(k.children))if(G.tagName==="w:tr")X&&X.trIndexes.push(n.length),n.push(G);else if(G.tagName==="w:sdt"){const q=this.getDirectChild(G,"w:sdtContent");if(q){let Z=X;if(this.importSdtWrappers&&!X){const we=this.getDirectChild(G,"w:sdtPr");if(we)try{Z={prXml:new XMLSerializer().serializeToString(we),trIndexes:[]},s.push(Z)}catch{Z=X}}o(q,Z)}}};o(e);const a=this.getDirectChild(e,"w:tblPr"),l=a?this.getDirectChild(a,"w:tblCellMar"):void 0,d=l?this.nonUniformCellMarginJson(l):void 0,p=this.getDirectChild(e,"w:tblGrid"),m=p?this.getDirectChild(p,"w:tblGridChange"):void 0,h=m?this.getDirectChild(m,"w:tblGrid"):void 0,g=k=>{if(!k)return[];const X=[];for(const G of Array.from(k.children)){if(G.tagName!=="w:gridCol")continue;const q=Number(G.getAttribute("w:w"));Number.isFinite(q)&&q>0&&X.push(q)}return X},w=k=>{const X=g(k),G=X.reduce((q,Z)=>q+Z,0);return G>0?X.map(q=>Math.round(q/G*100)):[]},u=[],f=[],b=[],I=[],y=[],B=[],$=[],W=a?this.getDirectChild(a,"w:tblPrChange"):void 0,z=W?this.getDirectChild(W,"w:tblPr"):void 0,D=W?this.parseTrackedRevisionMeta(W):null;let T;if(z)try{T=new XMLSerializer().serializeToString(z)}catch{T=void 0}const F=new Map,S=new Map,E=[];for(let k=0;k<n.length;k++){const X=n[k],G=this.generateId(),q=this.getDirectChild(X,"w:tblPrEx"),Z=q?this.getDirectChild(q,"w:tblPrExChange"):void 0,we=Z?this.getDirectChild(Z,"w:tblPrEx"):void 0,ae=this.getDirectChild(X,"w:trPr"),ye=ae?this.getDirectChild(ae,"w:ins"):void 0,xe=ae?this.getDirectChild(ae,"w:del"):void 0,ge=ae?this.getDirectChild(ae,"w:trPrChange"):void 0,Ve=ge?this.getDirectChild(ge,"w:trPr"):void 0;if(ye){const ke=this.parseTrackedRevisionMeta(ye);u.push({rowId:G,kind:"insert",...ke})}else if(xe){const ke=this.parseTrackedRevisionMeta(xe);u.push({rowId:G,kind:"delete",...ke})}ae&&ge&&Ve&&f.push({rowId:G,rowIndex:k,...this.parseTrackedRevisionMeta(ge),currentXml:this.serializePropertiesWithoutRevisionChildren(ae,new Set(["w:ins","w:del","w:trPrChange"])),priorXml:new XMLSerializer().serializeToString(Ve),...k===0?{currentTableAttributes:this.tableHeaderAttributesFromRowProperties(ae),priorTableAttributes:this.tableHeaderAttributesFromRowProperties(Ve)}:{}}),q&&Z&&we&&b.push({rowId:G,rowIndex:k,...this.parseTrackedRevisionMeta(Z),currentXml:this.serializePropertiesWithoutRevisionChildren(q,new Set(["w:tblPrExChange"])),priorXml:new XMLSerializer().serializeToString(we)});const ee=[];let me=0;const Se=[];for(let ke=0;ke<X.children.length;ke++){const Pe=X.children[ke];if(Pe.tagName==="w:tc")Se.push({el:Pe});else if(Pe.tagName==="w:sdt"){const se=this.getDirectChild(Pe,"w:sdtContent");if(!se)continue;let Me;if(this.importSdtWrappers){const Oe=this.getDirectChild(Pe,"w:sdtPr");if(Oe)try{Me={prXml:new XMLSerializer().serializeToString(Oe),cellIds:[]},E.push(Me)}catch{Me=void 0}}for(const Oe of Array.from(se.children))Oe.tagName==="w:tc"&&Se.push({el:Oe,sdtGroup:Me})}}for(let ke=0;ke<Se.length;ke++){const Pe=Se[ke].el,se=this.getDirectChild(Pe,"w:tcPr"),Me=this.getDirectChild(se||Pe,"w:shd")?.getAttribute("w:fill"),Oe=se?this.getDirectChild(se,"w:gridSpan")?.getAttribute("w:val"):void 0,Ee=Oe?parseInt(Oe,10):1,Ge=Number.isFinite(Ee)?Math.min(Math.max(1,Ee),1e3):1,Ye=se?this.getDirectChild(se,"w:cellIns"):void 0,Qe=se?this.getDirectChild(se,"w:cellDel"):void 0,ce=se?this.getDirectChild(se,"w:cellMerge"):void 0,$e=se?this.getDirectChild(se,"w:tcPrChange"):void 0,Je=$e?this.getDirectChild($e,"w:tcPr"):void 0,be={type:"table-cell",id:this.generateId(),backgroundColor:Me&&Me.toLowerCase()!=="auto"&&Me.toLowerCase()!=="none"?`#${Me.replace(/^#/,"")}`:void 0,children:await this.parseBodyChildren(Pe,r,t)};Ge>1&&(be.colSpan=Ge);const kt=rt(se,Lr);kt&&(be.oxmlTcPr=kt);const Pt=se?this.getDirectChild(se,"w:tcBorders"):void 0,et=Pt?this.parseDocxBordersElement(Pt,!1):void 0;et&&(be.borders=et);const At=se?this.getDirectChild(se,"w:tcMar"):void 0,ot=(At?this.parseDocxCellMargins(At):void 0)??d;ot&&(be.padding=ot);const Ue=se?this.getDirectChild(se,"w:vAlign")?.getAttribute("w:val"):void 0;(Ue==="top"||Ue==="center"||Ue==="bottom")&&(be.verticalAlign=Ue==="center"?"middle":Ue),ce&&B.push({rowId:G,gridColumn:me,...this.parseTrackedRevisionMeta(ce),...ce.getAttribute("w:vMerge")?{vMerge:ce.getAttribute("w:vMerge")}:{},...ce.getAttribute("w:vMergeOrig")?{vMergeOrig:ce.getAttribute("w:vMergeOrig")}:{}});const tt=se?this.getDirectChild(se,"w:vMerge"):void 0,gt=tt?.getAttribute("w:val");if(tt&&gt!=="restart"){const Be=F.get(me);if(Be){if(Be.cell.rowSpan=(Be.cell.rowSpan??1)+1,ce){const Ze=this.parseTrackedRevisionMeta(ce);$.push({row:k,pos:ee.length,colSpan:Ge,anchorRow:Be.rowIndex,anchorPos:Be.cellPos,rowId:G,gridColumn:me,restoredCellId:be.id,restoredCell:JSON.parse(JSON.stringify(be)),direction:"merge",...Ze,...ce.getAttribute("w:vMerge")?{vMerge:ce.getAttribute("w:vMerge")}:{},...ce.getAttribute("w:vMergeOrig")?{vMergeOrig:ce.getAttribute("w:vMergeOrig")}:{}})}me+=Ge;continue}}tt&&gt==="restart"?F.set(me,{cell:be,rowIndex:k,cellPos:ee.length}):F.delete(me);const st=ce?.hasAttribute("w:vMergeOrig")?ce.getAttribute("w:vMergeOrig"):tt?gt??"continue":void 0,at=st==="restart"||st==="rest",lt=st==="continue"||st==="cont";if(at)S.set(me,{cell:be,rowIndex:k,cellPos:ee.length});else if(lt){const Be=S.get(me);if(Be&&ce&&!tt){const Ze=this.parseTrackedRevisionMeta(ce);$.push({row:k,pos:ee.length,colSpan:Ge,anchorRow:Be.rowIndex,anchorPos:Be.cellPos,rowId:G,gridColumn:me,restoredCellId:be.id,restoredCell:JSON.parse(JSON.stringify(be)),direction:"unmerge",...Ze,...ce.getAttribute("w:vMerge")?{vMerge:ce.getAttribute("w:vMerge")}:{},...ce.getAttribute("w:vMergeOrig")?{vMergeOrig:ce.getAttribute("w:vMergeOrig")}:{}})}}else S.delete(me);Ye&&I.push({cellId:be.id,kind:"insert",...this.parseTrackedRevisionMeta(Ye)}),Qe&&I.push({cellId:be.id,kind:"delete",...this.parseTrackedRevisionMeta(Qe)}),$e&&Je&&y.push({rowId:G,cellId:be.id,rowIndex:k,cellIndex:ee.length,gridColumn:me,...this.parseTrackedRevisionMeta($e),currentXml:this.serializePropertiesWithoutRevisionChildren(se,new Set(["w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"])),priorXml:new XMLSerializer().serializeToString(Je),currentAttributes:this.tableCellAttributesFromProperties(se),priorAttributes:this.tableCellAttributesFromProperties(Je)}),Se[ke].sdtGroup?.cellIds.push(be.id),ee.push(be),me+=Ge}const De={type:"table-row",id:G,children:ee},Ie=tr(X);Ie&&(De.oxmlAttrs=Ie);const nt=rt(ae,$r);nt&&(De.oxmlTrPr=nt),i.push(De)}if(i.length===0)return null;if(this.importSdtWrappers){const k=this.sdtAncestorStack[this.sdtAncestorStack.length-1];for(const X of s){const G=X.trIndexes.map(q=>i[q]?.id).filter(q=>!!q);G.length>0&&this.importSdtWrappers.push({id:this.generateId(),prXml:X.prXml,scope:"row",...k?{parentId:k.id}:{},blockIds:G})}for(const X of E)X.cellIds.length>0&&this.importSdtWrappers.push({id:this.generateId(),prXml:X.prXml,scope:"cell",...k?{parentId:k.id}:{},blockIds:[...X.cellIds]})}const M=w(p),v=n[0]?this.getDirectChild(n[0],"w:trPr"):void 0,R=v?this.tableHeaderAttributesFromRowProperties(v).hasHeader===!0:!1,_=this.generateId(),L=new Map,H=(k,X,G)=>{const q=k.revisionId?`docxrev-${k.revisionId}`:this.generateId(),Z=L.get(q);if(Z)return Z;const we=this.revisionAuthorIdentity(k.author),ae={id:q,type:"table-change",tableId:_,source:we.suggestionSource,authorType:we.suggestionAuthorType,label:X,...k.createdAt!==void 0?{createdAt:k.createdAt}:{},...k.author?{agentName:k.author}:{},tableRevision:{version:1,suggestionKind:G,markers:[],operations:[]}};return L.set(q,ae),ae};if(p&&m&&h){const k=this.parseTrackedRevisionMeta(m),X=this.serializePropertiesWithoutRevisionChildren(p,new Set(["w:tblGridChange"])),G=new XMLSerializer().serializeToString(h),q=w(p),Z=w(h),we=H(k,"Change table column widths","format");we.tableRevision.markers.push({kind:"table-grid",revisionId:k.revisionId,author:k.author,createdAt:k.createdAt,currentPropertiesXml:X,priorPropertiesXml:G,currentColumnWidths:q,priorColumnWidths:Z}),we.tableRevision.operations.push({kind:"grid",currentGridXml:X,priorGridXml:G,currentColumnWidths:q,priorColumnWidths:Z})}for(const k of u){const X=i.findIndex(Z=>Z.id===k.rowId),G=i[X];if(!G)continue;const q=H(k,k.kind==="insert"?"Insert table row":"Delete table row",k.kind);q.tableRevision.markers.push({kind:k.kind==="insert"?"row-insert":"row-delete",rowId:k.rowId,rowIndex:X,revisionId:k.revisionId,author:k.author,createdAt:k.createdAt}),q.tableRevision.operations.push({kind:"row",action:k.kind,rowId:k.rowId,rowIndex:X,row:JSON.parse(JSON.stringify(G))}),G.diffState=k.kind,G.suggestionId=q.id}for(const k of I){let X=-1,G=-1,q,Z;for(let ye=0;ye<i.length&&!Z;ye++){const xe=i[ye].children.findIndex(ge=>ge.id===k.cellId);xe>=0&&(X=ye,G=xe,q=i[ye],Z=q.children[xe])}if(!q||!Z)continue;const we=qe({children:i,columnWidths:M}).byId.get(Z.id),ae=H(k,k.kind==="insert"?"Insert table cell":"Delete table cell",k.kind);ae.tableRevision.markers.push({kind:k.kind==="insert"?"cell-insert":"cell-delete",rowId:q.id,cellId:Z.id,rowIndex:X,cellIndex:G,gridColumn:we?.col,revisionId:k.revisionId,author:k.author,createdAt:k.createdAt}),ae.tableRevision.operations.push({kind:"cell",action:k.kind,rowId:q.id,cellId:Z.id,cellIndex:G,cell:JSON.parse(JSON.stringify(Z))}),Z.diffState=k.kind,Z.suggestionId=ae.id}for(const k of f){const X=H(k,"Change table row properties","format");X.tableRevision.markers.push({kind:"row-properties",rowId:k.rowId,rowIndex:k.rowIndex,revisionId:k.revisionId,author:k.author,createdAt:k.createdAt,currentPropertiesXml:k.currentXml,priorPropertiesXml:k.priorXml}),X.tableRevision.operations.push({kind:"properties",target:"row",rowId:k.rowId,currentPropertiesXml:k.currentXml,priorPropertiesXml:k.priorXml,currentTableAttributes:k.currentTableAttributes,priorTableAttributes:k.priorTableAttributes})}for(const k of b){const X=H(k,"Change row table-style exceptions","format");X.tableRevision.markers.push({kind:"row-exception-properties",rowId:k.rowId,rowIndex:k.rowIndex,revisionId:k.revisionId,author:k.author,createdAt:k.createdAt,currentPropertiesXml:k.currentXml,priorPropertiesXml:k.priorXml}),X.tableRevision.operations.push({kind:"properties",target:"row-exception",rowId:k.rowId,currentPropertiesXml:k.currentXml,priorPropertiesXml:k.priorXml})}for(const k of y){const X=H(k,"Change table cell properties","format");X.tableRevision.markers.push({kind:"cell-properties",rowId:k.rowId,cellId:k.cellId,rowIndex:k.rowIndex,cellIndex:k.cellIndex,gridColumn:k.gridColumn,revisionId:k.revisionId,author:k.author,createdAt:k.createdAt,currentPropertiesXml:k.currentXml,priorPropertiesXml:k.priorXml}),X.tableRevision.operations.push({kind:"properties",target:"cell",rowId:k.rowId,cellId:k.cellId,currentPropertiesXml:k.currentXml,priorPropertiesXml:k.priorXml,currentAttributes:k.currentAttributes,priorAttributes:k.priorAttributes})}const U=new Map;for(const k of $){const X=k.revisionId?`docxrev-${k.revisionId}`:this.generateId(),G=U.get(X)??[];G.push(k),U.set(X,G)}for(const[k,X]of U){const G=X[0],q={revisionId:G.revisionId,author:G.author,createdAt:G.createdAt},Z=H(q,X.every(ee=>ee.direction==="unmerge")?"Split table cells":"Merge table cells","format");Z.id!==k&&!L.has(k)&&(L.delete(Z.id),Z.id=k,L.set(k,Z));const we=G.revisionId?B.filter(ee=>ee.revisionId===G.revisionId):X;for(const ee of we)Z.tableRevision.markers.push({kind:"cell-merge",rowId:ee.rowId,gridColumn:ee.gridColumn,revisionId:ee.revisionId,author:ee.author,createdAt:ee.createdAt,vMerge:ee.vMerge,vMergeOrig:ee.vMergeOrig});const ae=JSON.parse(JSON.stringify(i)),ye=new Map,xe=new Set;for(const ee of X){const me=ae[ee.anchorRow]?.children[ee.anchorPos],Se=ae[ee.row];if(ee.direction==="merge"){if(me?.rowSpan!==void 0){const Ie=me.rowSpan-1;Ie>1?me.rowSpan=Ie:delete me.rowSpan}if(Se){const Ie=ye.get(ee.row)??0;Se.children.splice(ee.pos+Ie,0,JSON.parse(JSON.stringify(ee.restoredCell))),ye.set(ee.row,Ie+1)}}else if(me&&(me.rowSpan=(me.rowSpan??1)+1),Se){const Ie=Se.children.findIndex(nt=>nt.id===ee.restoredCellId);Ie>=0&&Se.children.splice(Ie,1)}Se&&xe.add(Se.id);const De=ae[ee.anchorRow];De&&xe.add(De.id)}const ge=i.filter(ee=>xe.has(ee.id)).map(ee=>JSON.parse(JSON.stringify(ee))),Ve=ae.filter(ee=>xe.has(ee.id));Z.tableRevision.operations.push({kind:"geometry",pendingRows:ge,acceptedRows:JSON.parse(JSON.stringify(ge)),rejectedRows:Ve})}if(D&&a&&z){const k=H(D,"Change table properties","format"),X=this.serializePropertiesWithoutRevisionChildren(a,new Set(["w:tblPrChange"])),G=T??new XMLSerializer().serializeToString(z);k.tableRevision.markers.push({kind:"table-properties",revisionId:D.revisionId,author:D.author,createdAt:D.createdAt,currentPropertiesXml:X,priorPropertiesXml:G}),k.tableRevision.operations.push({kind:"properties",target:"table",currentPropertiesXml:X,priorPropertiesXml:G,currentAttributes:{...this.tableAttributesFromProperties(a,t)},priorAttributes:{...this.tableAttributesFromProperties(z,t)}})}const J=Array.from(L.values()),Q=this.tableAttributesFromProperties(a,t);return{type:"table",id:_,...J.length>0?{structuralSuggestionRecords:JSON.stringify(J)}:{},children:i,columnWidths:M,...Q,...R?{hasHeader:!0}:{},...(()=>{const k=rt(a,Or);return k?{oxmlTblPr:k}:{}})()}}static serializePropertiesWithoutRevisionChildren(e,r){const t=e.cloneNode(!0);for(const i of Array.from(t.children))r.has(i.tagName)&&i.remove();return new XMLSerializer().serializeToString(t)}static tableCellAttributesFromProperties(e){const r={},t=this.getDirectChild(e,"w:shd")?.getAttribute("w:fill");t&&t.toLowerCase()!=="auto"&&t.toLowerCase()!=="none"&&(r.backgroundColor=`#${t.replace(/^#/,"")}`);const i=this.getDirectChild(e,"w:tcBorders"),n=i?this.parseDocxBordersElement(i,!1):void 0;n&&(r.borders=n);const s=this.getDirectChild(e,"w:tcMar"),o=s?this.parseDocxCellMargins(s):void 0;o&&(r.padding=o);const a=this.getDirectChild(e,"w:gridSpan")?.getAttribute("w:val"),l=a?Number(a):void 0;l&&Number.isFinite(l)&&l>1&&(r.colSpan=l);const d=this.getDirectChild(e,"w:vAlign")?.getAttribute("w:val");return(d==="top"||d==="center"||d==="bottom")&&(r.verticalAlign=d==="center"?"middle":d),r}static tableHeaderAttributesFromRowProperties(e){const r=this.getDirectChild(e,"w:tblHeader");if(!r)return{};const t=r.getAttribute("w:val")?.trim().toLowerCase();return t==="0"||t==="false"||t==="off"||t==="no"?{}:{hasHeader:!0}}static tableAttributesFromProperties(e,r){const t={};if(t.borders=this.resolveTableBordersJson(e,r),!e)return t;const i=this.getDirectChild(e,"w:jc")?.getAttribute("w:val");i==="center"||i==="right"?t.align=i:i==="left"||i==="start"?t.align="left":i==="end"&&(t.align="right");const n=this.getDirectChild(e,"w:tblW"),s=n?.getAttribute("w:type"),o=Number(n?.getAttribute("w:w"));s==="dxa"&&Number.isFinite(o)&&o>0&&(t.tableWidth=Math.round(o/15));const a=this.getDirectChild(e,"w:tblCellMar"),l=a?this.parseDocxCellMargins(a):void 0;if(l)try{const d=JSON.parse(l),p=[d.top,d.right,d.bottom,d.left];p.every(m=>Number.isFinite(m))&&p.every(m=>m===p[0])&&(t.cellPadding=p[0])}catch{}return t}static mapDocxBorderStyle(e){switch((e||"").trim()){case"none":case"nil":return"none";case"dotted":return"dotted";case"dashed":case"dashSmallGap":case"dashDotStroked":case"dotDash":case"dotDotDash":return"dashed";case"double":case"triple":case"doubleWave":return"double";default:return"single"}}static parseDocxBordersElement(e,r){return Cr(this.parseDocxBordersSpec(e,r))}static resolveTableBordersJson(e,r){const t={},i=a=>{a&&Object.assign(t,this.parseDocxBordersSpec(a,!0))},n=r?.styles;if(n){const a=(e&&this.getDirectChild(e,"w:tblStyle")?.getAttribute("w:val")||void 0)??n.defaultStyleIdByType?.get("table"),l=a?this.resolveStyleChain(a,n,"table"):[];for(const d of l)i(d.tblPr?this.getDirectChild(d.tblPr,"w:tblBorders"):void 0)}i(e?this.getDirectChild(e,"w:tblBorders"):void 0);const s={style:"none",width:0,color:"#000000"},o={top:t.top??s,bottom:t.bottom??s,left:t.left??s,right:t.right??s,insideH:t.insideH??s,insideV:t.insideV??s};return Cr(o)}static parseDocxBordersSpec(e,r){const t=(...l)=>{let d;for(const f of l)if(d=this.getDirectChild(e,f),d)break;if(!d)return;const p=this.mapDocxBorderStyle(d.getAttribute("w:val")),m=parseInt(d.getAttribute("w:sz")||"",10),h=p!=="none"&&m===0?"none":p,g=h==="none"?0:Number.isFinite(m)&&m>0?Math.max(.25,Math.round(m/6*100)/100):1,w=(d.getAttribute("w:color")||"").trim(),u=w&&w.toLowerCase()!=="auto"?`#${w.replace(/^#/,"").toLowerCase()}`:"#000000";return{style:h,width:g,color:u}},i={},n=t("w:top"),s=t("w:bottom"),o=t("w:left","w:start"),a=t("w:right","w:end");if(n&&(i.top=n),s&&(i.bottom=s),o&&(i.left=o),a&&(i.right=a),r){const l=t("w:insideH"),d=t("w:insideV");l&&(i.insideH=l),d&&(i.insideV=d)}return i}static nonUniformCellMarginJson(e){const r=this.parseDocxCellMargins(e);if(r){try{const t=JSON.parse(r),i=[t.top,t.right,t.bottom,t.left];if(i.every(n=>Number.isFinite(n))&&i.every(n=>n===i[0]))return}catch{return}return r}}static parseDocxCellMargins(e){const r=(...o)=>{let a;for(const d of o)if(a=this.getDirectChild(e,d),a)break;if(!a)return;const l=parseInt(a.getAttribute("w:w")||"",10);if(!(!Number.isFinite(l)||l<0))return Math.round(l/15*100)/100},t=r("w:top"),i=r("w:bottom"),n=r("w:left","w:start"),s=r("w:right","w:end");if(!(t===void 0&&i===void 0&&n===void 0&&s===void 0))return Ni({top:t??0,bottom:i??0,left:n??7.2,right:s??7.2})}static getContentTypeForPart(e,r){const t=r.get(e);if(t)return t;const i=e.split(".").pop()?.toLowerCase();return i?r.get(i):void 0}static isSupportedImageMimeType(e){return e==="image/png"||e==="image/jpeg"||e==="image/jpg"||e==="image/gif"||e==="image/bmp"||e==="image/svg+xml"}static buildImageDataUrl(e,r){return`data:${r};base64,${this.uint8ArrayToBase64(e)}`}static uint8ArrayToBase64(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let r="";const t=32768;for(let i=0;i<e.length;i+=t){const n=e.subarray(i,i+t);r+=String.fromCharCode(...n)}return btoa(r)}static createEmptyParagraph(){return{type:"paragraph",id:this.generateId(),children:[{type:"text",text:"",marks:{}}]}}static createPageBreakBlock(){return{type:"page-break",id:this.generateId()}}static generateId(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let r="";for(let t=0;t<6;t++)r+=e.charAt(Math.floor(Math.random()*e.length));return r}static ommlToLatex(e){try{return this.parseOmmlElement(e)}catch(r){return console.warn("Failed to convert OMML to LaTeX:",r),""}}static parseOmmlElement(e){const r=e.tagName;switch(r){case"m:oMathPara":case"m:oMath":return this.parseOmmlChildren(e);case"m:r":{const t=e.getElementsByTagName("m:t")[0];if(!t)return"";const i=(t.textContent||"").replace(/\u200B/g,""),n=e.getElementsByTagName("m:rPr")[0];if(n?.getElementsByTagName("m:nor")[0]){const d=i.replace(/\u00a0/g," "),p={"\\":"\\textbackslash{}","{":"\\{","}":"\\}","&":"\\&","%":"\\%",$:"\\$","#":"\\#",_:"\\_","^":"\\textasciicircum{}","~":"\\textasciitilde{}"};return`\\text{${d.replace(/[\\{}&%$#_^~]/g,m=>p[m])}}`}const s=this.cleanMathText(i),o=n?.getElementsByTagName("m:scr")[0]?.getAttribute("m:val"),a=n?.getElementsByTagName("m:sty")[0]?.getAttribute("m:val"),l={"double-struck":"\\mathbb",script:"\\mathcal",fraktur:"\\mathfrak","sans-serif":"\\mathsf",monospace:"\\mathtt"};return o&&l[o]?`${l[o]}{${s}}`:a==="b"||a==="bi"?`\\mathbf{${s}}`:a==="p"&&/^[A-Za-z]+$/.test(i)?ar.OMML_FUNCTION_NAMES.includes(i)?`\\${i} `:`\\mathrm{${i}}`:s}case"m:sSub":{const t=e.getElementsByTagName("m:e")[0],i=e.getElementsByTagName("m:sub")[0],n=t?this.parseOmmlChildren(t):"",s=i?this.parseOmmlChildren(i):"";return`${n}_{${s}}`}case"m:sSup":{const t=e.getElementsByTagName("m:e")[0],i=e.getElementsByTagName("m:sup")[0],n=t?this.parseOmmlChildren(t):"",s=i?this.parseOmmlChildren(i):"";return`${n}^{${s}}`}case"m:sSubSup":{const t=e.getElementsByTagName("m:e")[0],i=e.getElementsByTagName("m:sub")[0],n=e.getElementsByTagName("m:sup")[0],s=t?this.parseOmmlChildren(t):"",o=i?this.parseOmmlChildren(i):"",a=n?this.parseOmmlChildren(n):"";return`${s}_{${o}}^{${a}}`}case"m:f":{const t=e.getElementsByTagName("m:num")[0],i=e.getElementsByTagName("m:den")[0],n=t?this.parseOmmlChildren(t):"",s=i?this.parseOmmlChildren(i):"";return e.getElementsByTagName("m:fPr")[0]?.getElementsByTagName("m:type")[0]?.getAttribute("m:val")==="noBar"?`{${n} \\atop ${s}}`:`\\frac{${n}}{${s}}`}case"m:rad":{const t=e.getElementsByTagName("m:deg")[0],i=e.getElementsByTagName("m:e")[0],n=t?this.parseOmmlChildren(t).trim():"",s=i?this.parseOmmlChildren(i):"";return n&&n!=="2"?`\\sqrt[${n}]{${s}}`:`\\sqrt{${s}}`}case"m:nary":{const t=e.getElementsByTagName("m:naryPr")[0],i=e.getElementsByTagName("m:sub")[0],n=e.getElementsByTagName("m:sup")[0],s=e.getElementsByTagName("m:e")[0];let o="\\sum";if(t){const m=t.getElementsByTagName("m:chr")[0]?.getAttribute("m:val");m&&(o={"∑":"\\sum","∏":"\\prod","∫":"\\int","∬":"\\iint","∭":"\\iiint","∮":"\\oint","⋃":"\\bigcup","⋂":"\\bigcap"}[m]||"\\sum")}const a=i?this.parseOmmlChildren(i):"",l=n?this.parseOmmlChildren(n):"",d=s?this.parseOmmlChildren(s):"";let p=o;return a&&(p+=`_{${a}}`),l&&(p+=`^{${l}}`),p+=` ${d}`,p}case"m:d":{const t=e.getElementsByTagName("m:dPr")[0],i=e.getElementsByTagName("m:e")[0];let n="(",s=")";if(t){const l=t.getElementsByTagName("m:begChr")[0],d=t.getElementsByTagName("m:endChr")[0];l?.hasAttribute("m:val")&&(n=l.getAttribute("m:val")??""),d?.hasAttribute("m:val")&&(s=d.getAttribute("m:val")??"")}const o=l=>({"":".","{":"\\{","}":"\\}","⟨":"\\langle","⟩":"\\rangle","‖":"\\|","∥":"\\|","∣":"|","⌊":"\\lfloor","⌋":"\\rfloor","⌈":"\\lceil","⌉":"\\rceil"})[l]??l,a=i?this.parseOmmlChildren(i):"";return`\\left${o(n)}${a}\\right${o(s)}`}case"m:m":{const t=Array.from(e.children).filter(n=>n.tagName==="m:mr");if(t.length===0)return"";let i="\\begin{matrix}";for(let n=0;n<t.length;n++){const s=Array.from(t[n].children).filter(a=>a.tagName==="m:e"),o=[];for(let a=0;a<s.length;a++)o.push(this.parseOmmlChildren(s[a]));i+=o.join(" & "),n<t.length-1&&(i+=" \\\\ ")}return i+="\\end{matrix}",i}case"m:bar":{const t=e.getElementsByTagName("m:e")[0],i=t?this.parseOmmlChildren(t):"";return e.getElementsByTagName("m:barPr")[0]?.getElementsByTagName("m:pos")[0]?.getAttribute("m:val")==="bot"?`\\underline{${i}}`:`\\overline{${i}}`}case"m:acc":{const t=e.getElementsByTagName("m:accPr")[0],i=e.getElementsByTagName("m:e")[0],n=i?this.parseOmmlChildren(i):"";let s="\\hat";if(t){const o=t.getElementsByTagName("m:chr")[0]?.getAttribute("m:val");o&&(s={"̂":"\\hat","~":"\\tilde","̃":"\\tilde","̌":"\\check","̆":"\\breve","́":"\\acute","̀":"\\grave","̇":"\\dot","̈":"\\ddot","̄":"\\bar","⃗":"\\vec"}[o]||"\\hat")}return`${s}{${n}}`}case"m:limLow":case"m:limUpp":{const t=e.getElementsByTagName("m:e")[0],i=e.getElementsByTagName("m:lim")[0],n=t?this.parseOmmlChildren(t):"",s=i?this.parseOmmlChildren(i):"";return r==="m:limLow"?`${n}_{${s}}`:`${n}^{${s}}`}case"m:borderBox":{const t=Array.from(e.children).find(i=>i.tagName==="m:e");return`\\boxed{${t?this.parseOmmlChildren(t):""}}`}case"m:groupChr":{const t=e.getElementsByTagName("m:e")[0],i=t?this.parseOmmlChildren(t):"",n=e.getElementsByTagName("m:groupChrPr")[0],s=n?.getElementsByTagName("m:chr")[0]?.getAttribute("m:val");return n?.getElementsByTagName("m:pos")[0]?.getAttribute("m:val")!=="top"&&s!=="⏞"?`\\underbrace{${i}}`:`\\overbrace{${i}}`}case"m:func":{const t=Array.from(e.children).find(l=>l.tagName==="m:fName"),i=Array.from(e.children).find(l=>l.tagName==="m:e"),n=t?Array.from(t.children).find(l=>l.tagName==="m:limLow"):void 0;if(n){const l=Array.from(n.children).find(w=>w.tagName==="m:e"),d=Array.from(n.children).find(w=>w.tagName==="m:lim"),p=(l?.textContent??"").trim(),m=i?this.parseOmmlChildren(i):"",h=d?this.parseOmmlChildren(d):"",g=/^[A-Za-z]+$/.test(p)?`\\operatorname*{${p}}`:p;return`${["lim","max","min","sup","inf","liminf","limsup"].includes(p)?`\\${p}`:g}_{${h}} ${m}`}const s=(t?.textContent??"").trim(),o=i?this.parseOmmlChildren(i):"",a=ar.OMML_FUNCTION_NAMES;return a.includes(s)?`\\${s}{${o}}`:a.includes(s.toLowerCase())?`\\${s.toLowerCase()}{${o}}`:/^[A-Za-z]+$/.test(s)?`\\operatorname{${s}}{${o}}`:`${s}(${o})`}default:return this.parseOmmlChildren(e)}}static parseOmmlChildren(e){let r="";for(let t=0;t<e.children.length;t++){const i=e.children[t];i.tagName.endsWith("Pr")||i.tagName==="m:ctrlPr"||i.tagName==="m:t"||(r+=this.parseOmmlElement(i))}return r}static cleanMathText(e){const r={"𝐴":"A","𝐵":"B","𝐶":"C","𝐷":"D","𝐸":"E","𝐹":"F","𝐺":"G","𝐻":"H","𝐼":"I","𝐽":"J","𝐾":"K","𝐿":"L","𝑀":"M","𝑁":"N","𝑂":"O","𝑃":"P","𝑄":"Q","𝑅":"R","𝑆":"S","𝑇":"T","𝑈":"U","𝑉":"V","𝑊":"W","𝑋":"X","𝑌":"Y","𝑍":"Z","𝑎":"a","𝑏":"b","𝑐":"c","𝑑":"d","𝑒":"e","𝑓":"f","𝑔":"g",ℎ:"h","𝑖":"i","𝑗":"j","𝑘":"k","𝑙":"l","𝑚":"m","𝑛":"n","𝑜":"o","𝑝":"p","𝑞":"q","𝑟":"r","𝑠":"s","𝑡":"t","𝑢":"u","𝑣":"v","𝑤":"w","𝑥":"x","𝑦":"y","𝑧":"z",α:"\\alpha",β:"\\beta",γ:"\\gamma",δ:"\\delta",ε:"\\epsilon",ζ:"\\zeta",η:"\\eta",θ:"\\theta",ι:"\\iota",κ:"\\kappa",λ:"\\lambda",μ:"\\mu",ν:"\\nu",ξ:"\\xi",π:"\\pi",ρ:"\\rho",σ:"\\sigma",τ:"\\tau",υ:"\\upsilon",φ:"\\phi",χ:"\\chi",ψ:"\\psi",ω:"\\omega",Γ:"\\Gamma",Δ:"\\Delta",Θ:"\\Theta",Λ:"\\Lambda",Ξ:"\\Xi",Π:"\\Pi",Σ:"\\Sigma",Φ:"\\Phi",Ψ:"\\Psi",Ω:"\\Omega","∞":"\\infty","∂":"\\partial","∇":"\\nabla","±":"\\pm","∓":"\\mp","×":"\\times","÷":"\\div","≠":"\\neq","≈":"\\approx","≤":"\\leq","≥":"\\geq","∈":"\\in","∉":"\\notin","⊂":"\\subset","⊃":"\\supset","∪":"\\cup","∩":"\\cap","→":"\\rightarrow","←":"\\leftarrow","⇒":"\\Rightarrow","⇐":"\\Leftarrow","⇔":"\\Leftrightarrow","∀":"\\forall","∃":"\\exists","∄":"\\nexists","∴":"\\therefore","∵":"\\because","…":"\\ldots","⋯":"\\cdots","⋮":"\\vdots","⋱":"\\ddots"},t={"&":"\\&","%":"\\%","#":"\\#",$:"\\$","{":"\\{","}":"\\}"};let i="";for(const n of e){const s=r[n];s?i+=s.startsWith("\\")?`${s} `:s:i+=t[n]??n}return i}static async loadZipFromBlob(e){const r=typeof e.arrayBuffer=="function"?await e.arrayBuffer():e;return Pr.loadAsync(r)}static async generateCompressedZipBlob(e){return e.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}})}static async toBlob(e,r,t){Nr()||await Ti();const i=await import("./index-BWdRWxoH.js"),{Document:n,Packer:s,Tab:o,TabStopType:a,LeaderType:l,CommentRangeStart:d,CommentRangeEnd:p,CommentReference:m,BookmarkStart:h,BookmarkEnd:g,Paragraph:w,TextRun:u,InsertedTextRun:f,DeletedTextRun:b,FootnoteReference:I,Header:y,Footer:B,ExternalHyperlink:$,InternalHyperlink:W,HeadingLevel:z,AlignmentType:D,PageOrientation:T,PageNumber:F,PageBreak:S,SectionType:E,UnderlineType:M,Table:v,TableRow:R,TableCell:_,WidthType:L,BorderStyle:H,ShadingType:U,ImportedXmlComponent:J,ImageRun:Q,LevelFormat:k,LevelSuffix:X}=i,G=c=>{const x=`<root>${c}</root>`,P=J.fromXmlString(x),N=P.root?.[0];if(N?.root){for(const A of N.root)if(A?.rootKey?.startsWith("m:"))return A}return P},q=(c,x)=>{const P=c?.root;if(Array.isArray(P)){for(const N of P)if(N?.rootKey===x)return N;for(const N of P){if(N?.rootKey==="w:rPr"||N?.rootKey==="w:pPr"||N?.rootKey==="w:tblPr"||N?.rootKey==="w:trPr"||N?.rootKey==="w:tcPr")continue;const A=q(N,x);if(A)return A}}},Z=(c,x,P)=>{try{const N=q(c,x);if(!N||!Array.isArray(N.root))return;const A=(J.fromXmlString(`<root>${P}</root>`).root?.[0]?.root??[]).filter(V=>V?.rootKey&&V.rootKey!=="_attr");N.root.push(...A)}catch{}},we=c=>{try{const x=J.fromXmlString(`<root>${c}</root>`);for(const P of x.root?.[0]?.root??[])if(P?.rootKey&&P.rootKey!=="_attr")return P}catch{}return null},ae=[],ye=[],xe=(c,x,P="w:pPr")=>{const N=ae.length;ae.push(x),Z(c,P,`<w:rvseOxmlAttrs w:val="${N}"/>`)},ge=Te(e.pageLayout),Ve=Vt(ge),ee=(c,x,P="only")=>{const N=(()=>{const j=Te(Er(e.pageLayout,c)).pageNumberStart;switch(P){case"middle":return c?.pageNumberStart;case"first":return c?.pageNumberStart??(j!==1?j:void 0);case"final":return e.pageLayout?.pageNumberRestart===!0?j:void 0;case"only":return e.pageLayout?.pageNumberRestart===!0||j!==1?j:void 0}})(),A=Te(c),V=Vt(A),C={...x&&x!=="nextPage"?{type:x==="continuous"?E.CONTINUOUS:x==="evenPage"?E.EVEN_PAGE:E.ODD_PAGE}:{},page:{size:{width:this.pxToTwips(A.orientation==="landscape"?V.pageHeight:V.pageWidth),height:this.pxToTwips(A.orientation==="landscape"?V.pageWidth:V.pageHeight),orientation:A.orientation==="landscape"?T.LANDSCAPE:T.PORTRAIT},margin:{top:this.pxToTwips(A.marginTopPx),right:this.pxToTwips(A.marginRightPx),bottom:this.pxToTwips(A.marginBottomPx),left:this.pxToTwips(A.marginLeftPx)},...(()=>{const j=Te(Er(e.pageLayout,c)).pageNumberFormat,K={...N!==void 0?{start:N}:{},...j!=="decimal"?{formatType:j}:{}};return Object.keys(K).length>0?{pageNumbers:K}:{}})()}};return c?.columnCount&&c.columnCount>1&&(C.column={count:c.columnCount,...c.columnGapTwips!==void 0?{space:c.columnGapTwips}:{}}),!A.lineNumbering&&A.pleadingGrid?C.lineNumbers={countBy:1,start:1,restart:"newPage",distance:Math.round((A.pleadingGrid.distancePx??14)*15)}:A.lineNumbering&&(C.lineNumbers={countBy:A.lineNumbering.countBy,start:A.lineNumbering.start,restart:A.lineNumbering.restart,...A.lineNumbering.distancePx!==void 0?{distance:Math.round(A.lineNumbering.distancePx*15)}:{}}),C},me=ee(e.pageLayout),Se=ge.pageNumberPosition.endsWith("right")?D.RIGHT:D.LEFT,De=new w({alignment:Se,children:[new u({children:[F.CURRENT]})]}),Ie=Math.round((Ve.pageWidth-ge.marginLeftPx-ge.marginRightPx)*15),nt=c=>{const x=[],P=(C,j)=>(j.oxmlRPr&&Z(C,"w:rPr",j.oxmlRPr),C);for(const C of c.children){if(C.type!=="text")continue;const j=this.textNodeToDocx(C)[0]??{},K=Je(j);if(C.marks?.field==="page"||C.marks?.field==="numPages"){x.push(new u({...K,children:[C.marks.field==="page"?F.CURRENT:F.TOTAL_PAGES]}));continue}if(C.text)if(/[\t\n]/.test(C.text)&&!C.marks?.link)C.text.split(`
7
- `).forEach((Y,re)=>{const ie=[];Y.split(" ").forEach((ue,le)=>{le>0&&ie.push(new o),ue&&ie.push(ue)}),x.push(new u({children:ie,...K,...re>0?{break:1}:{}}))});else if(C.marks?.link){const Y={...K};Y.underline??(Y.underline={type:M.SINGLE}),Y.color??(Y.color="2563EB");const re=[P(new u({text:C.text,...Y}),j)];x.push(C.marks.link.startsWith("#")?new W({anchor:C.marks.link.slice(1),children:re}):new $({link:C.marks.link,children:re}))}else x.push(P(new u({text:C.text,...K}),j))}const N=c.children.some(C=>C.type==="text"&&C.text.includes(" ")),A={left:D.LEFT,center:D.CENTER,right:D.RIGHT,justify:D.JUSTIFIED},V=new w({children:x,...c.align&&A[c.align]?{alignment:A[c.align]}:{},...N?{tabStops:[{type:a.CENTER,position:Math.round(Ie/2)},{type:a.RIGHT,position:Ie}]}:{}});return c.oxmlPPr&&Z(V,"w:pPr",c.oxmlPPr),c.oxmlAttrs&&xe(V,c.oxmlAttrs),V},ke=c=>{const x=c.src.match(/^data:([^;,]+);base64,(.*)$/);if(!x)return null;const P={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/bmp":"bmp"}[x[1].toLowerCase()];if(!P)return null;try{return new w({children:[new Q({type:P,data:this.base64ToUint8Array(x[2]),...c.alt?{altText:{name:c.alt,description:c.alt,title:c.alt}}:{},transformation:{width:Math.max(1,Math.round(c.width)),height:Math.max(1,Math.round(c.height))}})]})}catch{return null}},Pe=(c,x,P)=>{const N=V=>P?(e.chromeImages??[]).filter(C=>C.side===P&&C.slot===V).map(ke).filter(C=>C!==null):[],A={};for(const V of["default","first","even"]){const C=[...(c?.[V]??[]).map(nt),...N(V)];C.length>0&&(A[V]=new x({children:C}))}return Object.keys(A).length>0?A:void 0},se=(c,x)=>(e.chrome??[]).some(P=>P.slot===c&&(x==="any"||P.sectionIndex===void 0)&&(c==="first"||Qi(P))),Me=!!(e.headers?.first||e.footers?.first)||se("first","unscoped"),Oe=!!(e.headers?.even||e.footers?.even)||se("even","any");Me&&(me.titlePage=!0);const Ee={},Ge=this.buildDocxNumberingConfig(e,{AlignmentType:D,LevelFormat:k,LevelSuffix:X}),Ye=new Set;let Qe=1e5;const ce=c=>{if(c!==void 0&&!Ye.has(c))return Ye.add(c),c;for(;Ye.has(Qe);)Qe++;return Ye.add(Qe),Qe};let $e=!1;const Je=c=>{const x={};return c.bold!==void 0&&(x.bold=c.bold),c.italic!==void 0&&(x.italics=c.italic),c.underline&&(x.underline={type:c.underline==="NONE"?"none":M.SINGLE}),c.strike!==void 0&&(x.strike=c.strike),c.doubleStrike!==void 0&&(x.doubleStrike=c.doubleStrike),c.smallCaps!==void 0&&(x.smallCaps=c.smallCaps),c.allCaps!==void 0&&(c.smallCaps!==void 0?(x.snapToGrid=c.allCaps,$e=!0):x.allCaps=c.allCaps),c.vanish===!0?x.vanish=!0:c.vanish===!1&&(x.specVanish=!0,$e=!0),c.lang&&(x.language={value:c.lang}),c.characterSpacing?x.characterSpacing=c.characterSpacing:c.characterSpacing===0&&(x.imprint=!0,$e=!0),c.superScript&&(x.superScript=!0),c.subScript&&(x.subScript=!0),c.baseline&&(x.emboss=!0,$e=!0),c.rightToLeft&&(x.rightToLeft=!0),c.color&&(x.color=c.color),c.highlight&&(x.highlight=c.highlight),c.font&&(x.font=c.font.split(",")[0].replaceAll("'","").replaceAll('"',"")),c.size&&(x.size=c.size),c.characterStyle&&(x.style=c.characterStyle),x};let be=0,kt=1e5;const Pt=new Set((e.sdtWrappers??[]).filter(c=>c.scope==="inline").map(c=>c.id)),et=new Map,At=(c,x,P,N)=>{const A=`${c.name}\0${c.role}\0${c.rangeId}`,V=et.get(A);if(V){V.wrapperIds.push(x);return}et.set(A,{name:c.name,role:c.role,rangeId:c.rangeId,author:c.rangeAuthor??P,date:typeof c.rangeCreatedAt=="number"?new Date(c.rangeCreatedAt).toISOString():N,wrapperIds:[x]})},ot=c=>{const x=C=>C?.sdtInline?.split(",").filter(j=>j&&Pt.has(j))??[],P=new Map,N=c.children.flatMap((C,j)=>{if(C.mathOmml)return G(C.mathOmml);const K={text:C.text,...Je(C)};C.break&&(K.break=1),C.footnoteReference!==void 0&&(delete K.text,K.style??(K.style="FootnoteReference"),K.children=[new I(C.footnoteReference)]),C.rPrChange&&(K.revision={id:ce(C.rPrChange.importedId),author:C.rPrChange.author,date:C.rPrChange.date,...Je(C.rPrChange.prior)});const Y=()=>{let oe;if(C.revision){const de=ce(C.revision.importedId),mt={...K,id:de,author:C.revision.author,date:C.revision.date};C.revision.move&&At(C.revision.move,de,C.revision.author,C.revision.date),oe=C.revision.kind==="delete"?new b(mt):new f(mt)}else oe=new u(K);return C.oxmlRPr&&Z(oe,"w:rPr",C.oxmlRPr),oe},re=C.link?(()=>{K.underline??(K.underline={type:M.SINGLE}),K.color??(K.color="2563EB");const oe=[Y()];return C.link.startsWith("#")?new W({anchor:C.link.slice(1),children:oe}):new $({link:C.link,children:oe})})():Y(),ie=[];for(const oe of pr.get(C)??[]){const de=Re.get(oe);de!==void 0&&ie.push(new d(de))}const ue=x(c.children[j-1]),le=x(C),xt=x(c.children[j+1]);for(const oe of[...le].reverse()){if(ue.includes(oe))continue;const de={name:`__rvSdt:${oe}:${be++}`,numericId:kt++};P.set(oe,de),ie.push(new h(de.name,de.numericId))}for(const oe of Xt.get(C)??[])ie.push(new h(oe,_t.get(oe)));for(const oe of zt.get(C)??[]){const de=we(Nt.get(oe).startXml);de&&ie.push(de)}const ht=Gt.has(c),pe=C.fieldInstr;pe&&!ht&&c.children[j-1]?.fieldInstr!==pe&&ie.push(...fr(pe)),ie.push(re),pe&&!ht&&c.children[j+1]?.fieldInstr!==pe&&ie.push(...wr());for(const oe of Ht.get(C)??[]){const de=we(Nt.get(oe).endXml);de&&ie.push(de)}for(const oe of Wt.get(C)??[])ie.push(new g(_t.get(oe)));for(const oe of le){if(xt.includes(oe))continue;const de=P.get(oe);de&&(ie.push(new g(de.numericId)),P.delete(oe))}for(const oe of hr.get(C)??[]){const de=Re.get(oe);de!==void 0&&(ie.push(new p(de)),ie.push(new u({children:[new m(de)]})))}return ie});for(const C of Lt.get(c.sourceBlockId??"")??[]){const j=Re.get(C);j!==void 0&&(N.push(new d(j)),N.push(new p(j)),N.push(new u({children:[new m(j)]})))}jt.has(c)&&N.unshift(...fr(jt.get(c))),ur.has(c)&&N.push(...wr());const A={children:N};if(c.children.length>0&&c.children.every(C=>!C.text&&!C.break&&!C.mathOmml&&C.footnoteReference===void 0)){const C=c.children.find(j=>j.size||j.font);if(C){const{size:j,font:K}=Je({size:C.size,font:C.font});A.run={...j?{size:j}:{},...K?{font:K}:{}}}}if(c.keepNext&&(A.keepNext=!0),c.keepLines&&(A.keepLines=!0),c.widowControl===!1&&(A.widowControl=!1),c.bidirectional!==void 0&&(A.bidirectional=c.bidirectional),c.tabStopsJson){const C=en(c.tabStopsJson);if(C){const j={left:a.LEFT,right:a.RIGHT,center:a.CENTER,decimal:a.DECIMAL},K={dot:l.DOT,hyphen:l.HYPHEN,underscore:l.UNDERSCORE};A.tabStops=C.map(Y=>({type:j[Y.align]??a.LEFT,position:Math.round(Y.pos*15),...Y.leader?{leader:K[Y.leader]}:{}}))}}if(c.bordersJson)try{const C=JSON.parse(c.bordersJson),j=Y=>{switch(Y){case"dashed":return H.DASHED;case"dotted":return H.DOTTED;case"double":return H.DOUBLE;case"none":return H.NONE;default:return H.SINGLE}},K={};for(const Y of["top","bottom","left","right"]){const re=C[Y];re&&(K[Y]={style:j(re.style),size:re.style==="none"?0:Math.max(1,Math.round((re.width??1)*6)),color:this.toDocxHex(re.color)??"auto"})}Object.keys(K).length>0&&(A.border=K)}catch{}if(c.shadingFill){const C=this.toDocxHex(c.shadingFill);A.shading=C?{type:U.CLEAR,fill:C}:{type:U.CLEAR,fill:"auto",color:"auto"}}if(c.heading&&!c.styleId){const C={HEADING_1:z.HEADING_1,HEADING_2:z.HEADING_2,HEADING_3:z.HEADING_3,HEADING_4:z.HEADING_4,HEADING_5:z.HEADING_5,HEADING_6:z.HEADING_6};A.heading=C[c.heading]}if(c.alignment){const C={LEFT:D.LEFT,CENTER:D.CENTER,RIGHT:D.RIGHT,JUSTIFIED:D.JUSTIFIED};A.alignment=C[c.alignment]}c.styleId?A.style=c.styleId:c.style&&(A.style=c.style),c.lineSpacing!==void 0&&(A.spacing={...A.spacing,line:Math.round(c.lineSpacing*240)}),c.spacingBeforeTwips!==void 0&&(A.spacing={...A.spacing,before:c.spacingBeforeTwips}),c.spacingAfterTwips!==void 0&&(A.spacing={...A.spacing,after:c.spacingAfterTwips}),c.contextualSpacing&&(A.contextualSpacing=!0),c.indent&&(A.indent={...A.indent,...c.indent}),c.list&&(c.list.variant==="todo"?A.indent=this.getListIndentOptions(c.list.level):c.list.reference&&(A.numbering={reference:c.list.reference,level:c.list.level,instance:c.list.instance??0}));const V=new w(A);return c.oxmlPPr&&Z(V,"w:pPr",c.oxmlPPr),c.oxmlAttrs&&xe(V,c.oxmlAttrs),V},Ue=c=>{const x=Number.isFinite(c.borderWidth)?Math.max(0,Math.round(c.borderWidth)):1,P=x>0?{style:H.SINGLE,size:Math.max(1,x*6),color:this.toDocxHex(c.borderColor)??"D1D5DB"}:{style:H.NONE,size:0,color:"auto"},N=le=>{const xt={single:H.SINGLE,dashed:H.DASHED,dotted:H.DOTTED,double:H.DOUBLE,none:H.NONE};return le.style==="none"||le.width<=0?{style:H.NONE,size:0,color:"auto"}:{style:xt[le.style]??H.SINGLE,size:Math.max(1,Math.round(le.width*6)),color:this.toDocxHex(le.color)??"auto"}},A=er(c.borders),V=A?{top:N(A.top??{style:"single",width:1,color:"#d1d5db"}),bottom:N(A.bottom??{style:"single",width:1,color:"#d1d5db"}),left:N(A.left??{style:"single",width:1,color:"#d1d5db"}),right:N(A.right??{style:"single",width:1,color:"#d1d5db"}),insideHorizontal:N(A.insideH??{style:"single",width:1,color:"#d1d5db"}),insideVertical:N(A.insideV??{style:"single",width:1,color:"#d1d5db"})}:void 0,C=c.rows.map(le=>{const xt=le.cells.map((pe,oe)=>{const de=pe.blocks??pe.paragraphs,mt=de.map(Ne=>Ne.type==="table"?Ue(Ne):ot(Ne));(mt.length===0||de[de.length-1]?.type==="table")&&mt.push(new w({}));const hi=Math.max(c.columnWidths.length,1),mi=pe.colSpan??1,Sr=pe.gridColumn??oe;let Ir=0;for(let Ne=Sr;Ne<Sr+mi;Ne++)Ir+=c.columnWidths[Ne]||100/hi;const We={children:mt,width:{size:Ir,type:L.PERCENTAGE}};pe.verticalAlign&&(We.verticalAlign=pe.verticalAlign==="middle"?"center":pe.verticalAlign);const ze=rn(pe.borders);if(ze){const Ne={};ze.top&&(Ne.top=N(ze.top)),ze.bottom&&(Ne.bottom=N(ze.bottom)),ze.left&&(Ne.left=N(ze.left)),ze.right&&(Ne.right=N(ze.right)),We.borders=Ne}else V||(We.borders={top:P,bottom:P,left:P,right:P});const St=nn(pe.padding);St&&(We.margins={marginUnitType:L.DXA,top:Math.round(St.top*15),bottom:Math.round(St.bottom*15),left:Math.round(St.left*15),right:Math.round(St.right*15)}),pe.colSpan&&pe.colSpan>1&&(We.columnSpan=pe.colSpan),pe.rowSpan&&pe.rowSpan>1&&(We.rowSpan=pe.rowSpan);const Kt=this.toDocxHex(pe.backgroundColor);Kt?We.shading={type:U.SOLID,color:Kt,fill:Kt}:le.isHeader&&!pe.backgroundColor&&(We.shading={type:U.SOLID,color:"F9FAFB",fill:"F9FAFB"});const kr=new _(We);return pe.oxmlTcPr&&Z(kr,"w:tcPr",pe.oxmlTcPr),kr}),ht=new R({children:xt,tableHeader:le.isHeader===!0?!0:void 0});return le.oxmlTrPr&&Z(ht,"w:trPr",le.oxmlTrPr),le.oxmlAttrs&&xe(ht,le.oxmlAttrs,"w:trPr"),ht}),j=typeof c.tableWidth=="number"&&Number.isFinite(c.tableWidth)&&c.tableWidth>0?Math.round(c.tableWidth*15):void 0,K=j??9e3,Y=c.columnWidths.filter(le=>Number.isFinite(le)&&le>0).map(le=>Math.max(1,Math.round(le/100*K))),re=c.align==="center"?D.CENTER:c.align==="right"?D.RIGHT:c.align==="left"?D.LEFT:void 0,ie=typeof c.cellPadding=="number"&&Number.isFinite(c.cellPadding)&&c.cellPadding>=0?{marginUnitType:L.DXA,top:Math.round(c.cellPadding*15),bottom:Math.round(c.cellPadding*15),left:Math.round(c.cellPadding*15),right:Math.round(c.cellPadding*15)}:void 0,ue=new v({rows:C,width:j?{size:j,type:L.DXA}:{size:100,type:L.PERCENTAGE},...Y.length===c.columnWidths.length&&Y.length>0?{columnWidths:Y}:{},...re?{alignment:re}:{},...ie?{margins:ie}:{},borders:V??{top:P,bottom:P,left:P,right:P,insideHorizontal:P,insideVertical:P}});return c.oxmlTblPr&&Z(ue,"w:tblPr",c.oxmlTblPr),ue},tt=c=>{const x=c.split(",")[1]||"";if(typeof atob!="function")throw new Error("Base64 decoding is unavailable in this environment");const P=atob(x),N=new Uint8Array(P.length);for(let A=0;A<P.length;A++)N[A]=P.charCodeAt(A);return N},gt=c=>{if(c.renderDiagram)return c.diagramPngDataUrl?new w({children:[new Q({type:"png",data:tt(c.diagramPngDataUrl),transformation:{width:Math.max(120,Math.round(c.diagramWidth||600)),height:Math.max(60,Math.round(c.diagramHeight||180))}})],spacing:{before:120,after:120}}):new w({children:[new u({text:"Diagram unavailable"})],spacing:{before:120,after:120}});const x=c.runs.map(N=>{const A={text:N.text,font:N.font||"Courier New"};return N.color&&(A.color=N.color),N.break&&(A.break=N.text.split(`
8
- `).length-1,A.text=""),new u(A)}),P=this.toDocxHex(c.backgroundColor)??"F5F5F5";return new w({children:x,...c.styleId?{style:c.styleId}:{},shading:{type:U.SOLID,color:P,fill:P},spacing:{before:120,after:120}})},st=c=>{if(!c.omml)return new w({children:[new u({text:c.content})],alignment:c.alignment==="center"?D.CENTER:c.alignment==="right"?D.RIGHT:D.LEFT});const x=G(c.omml);return new w({children:[x],alignment:c.alignment==="center"?D.CENTER:c.alignment==="right"?D.RIGHT:D.LEFT,spacing:{before:120,after:120}})},at=[],lt=[],Be=c=>{if(!c.anchorXml)return;const x=`__revise-anchor:${lt.length}__`;return lt.push({marker:x,anchorXml:c.anchorXml}),x},Ze=c=>({alignment:c.align==="center"?D.CENTER:c.align==="right"?D.RIGHT:D.LEFT,spacing:{before:120,after:120}}),Vr=async c=>{const x=Be(c);if(c.originalFormat&&c.originalDataUrl){const N=`__revise-original-media:${at.length}__`;return at.push({marker:N,format:c.originalFormat,dataUrl:c.originalDataUrl,alt:c.alt}),new w({children:[new Q({type:"png",data:this.base64ToUint8Array(qr),altText:{name:c.alt||"Image",description:N,title:x??c.alt},transformation:{width:Math.max(1,Math.round(c.width)),height:Math.max(1,Math.round(c.height))}})],...Ze(c)})}if(c.src.match(/^data:image\/svg\+xml(;base64)?,/i)){const N=this.dataUrlToUint8Array(c.src);if(N){const A=Math.max(1,Math.round(c.width)),V=Math.max(1,Math.round(c.height)),C=await this.rasterizeSvgDataUrlToPng(c.src,A,V)??this.base64ToUint8Array(qr);return new w({children:[new Q({type:"svg",data:N,fallback:{type:"png",data:C},altText:{name:c.alt||"Image",description:c.alt,title:x??c.alt},transformation:{width:A,height:V}})],...Ze(c)})}}const P=await this.resolveImageSourceForDocx(c.src);return P?new w({children:[new Q({type:P.type,data:P.data,altText:{name:c.alt||"Image",description:c.alt,title:x??c.alt},transformation:{width:Math.max(1,Math.round(c.width)),height:Math.max(1,Math.round(c.height))}})],...Ze(c)}):new w({children:[new u({text:c.alt||"Image unavailable"})],...Ze(c)})},Yr=()=>new w({children:[new S]}),ut=[...e.notes??[],...e.children.filter(c=>c.type==="footnote")],ft=new Map;for(const c of ut)ft.set(c.id,c.noteKind==="endnote"?"endnote":"footnote");const Qr=ut.filter(c=>ft.get(c.id)==="footnote"),wt=ut.filter(c=>ft.get(c.id)==="endnote"),Ct=new Map,ct=new Map;{const c=x=>{if(!x||typeof x!="object")return;if(Array.isArray(x)){x.forEach(c);return}const P=x;if(P.type==="footnote")return;const N=P.marks?.footnoteRef;if(N){const A=ft.get(N)==="endnote"?ct:Ct;A.has(N)||A.set(N,A.size+1)}c(P.children)};c(e.children.filter(x=>x.type!=="footnote"))}for(const c of wt)ct.has(c.id)||ct.set(c.id,ct.size+1);const _e=e.comments??[],Re=new Map,dt=new Set;for(const c of _e){const x=c.importedId;Number.isSafeInteger(x)&&x>=0&&x<=2147483647&&!dt.has(x)&&(dt.add(x),Re.set(c.id,x))}let Ke=0;for(const c of _e)if(!Re.has(c.id)){for(;dt.has(Ke);)Ke++;Re.set(c.id,Ke),dt.add(Ke++)}const bt=new Map,lr=c=>{const x=new Map(_e.map(A=>[A.id,A]));let P=c;const N=new Set;for(;P.parentId&&!N.has(P.id);){N.add(P.id);const A=x.get(P.parentId);if(!A)break;P=A}return P.id};for(const c of _e){const x=lr(c),P=bt.get(x)??[];P.includes(c.id)||P.push(c.id),bt.set(x,P)}const ei=e.children.some(c=>c.type==="header-footer");let Xe=ut.length>0||ei?{...e,children:e.children.filter(c=>c.type!=="footnote"&&c.type!=="header-footer")}:e;if(ut.length>0){Xe=JSON.parse(JSON.stringify(Xe));const c=x=>{if(!x||typeof x!="object")return;if(Array.isArray(x)){x.forEach(c);return}const P=x,N=P.marks?.footnoteRef;if(N)if(ft.get(N)==="endnote"){const A=ct.get(N)??1;P.text=`__RVSE_EN_${A}__`,P.marks&&(delete P.marks.footnoteRef,P.marks.superscript=!0)}else P.text=String(Ct.get(N)??1);c(P.children)};c(Xe.children)}this.hasDocxMoveMarks(Xe.children)&&(Xe=JSON.parse(JSON.stringify(Xe)),this.finalizeImportedMovePairs(Xe.children));const cr=this.collectTableRevisionPatches(Xe),$t=t?.graft?[]:void 0,yt=this.toDocxFormatWithTables(Xe,r,t?.headingPageNumbers,$t),vt=[],dr=c=>{for(const x of c){if(x.type==="paragraph"){vt.push(x);continue}for(const P of x.rows)for(const N of P.cells)dr(N.blocks??N.paragraphs)}};dr(yt.filter(c=>c.type==="paragraph"||c.type==="table"));const pr=new Map,hr=new Map,Lt=new Map,mr=[];{const c=[];for(const C of vt)c.push(...C.children);const x=C=>(C.text??"")===""&&!C.break&&!C.mathOmml&&C.footnoteReference===void 0&&!C.fieldInstr,P=new Map;for(const[C,j]of bt)for(const K of j)P.set(K,C);const N=new Map;c.forEach((C,j)=>{const K=new Set((C.comment?.split(",")??[]).filter(Boolean).map(Y=>P.get(Y)??Y));for(const Y of K){const re=N.get(Y)??[],ie=re[re.length-1];let ue=!!ie;for(let le=ie?ie.lastIndex+1:j;le<j;le++)if(!x(c[le])){ue=!1;break}ie&&ue?(ie.last=C,ie.lastIndex=j):re.push({first:C,last:C,lastIndex:j}),N.set(Y,re)}});const A=new Set,V=(C,j,K)=>C.set(j,[...C.get(j)??[],...K]);for(const[C,j]of N){const K=bt.get(C)??[C];K.forEach(Y=>A.add(Y)),j.forEach((Y,re)=>{let ie=K;if(re>0){if(!Re.has(C))return;const ue=`${C}\0fragment${re}`;for(;dt.has(Ke);)Ke++;Re.set(ue,Ke),dt.add(Ke++),mr.push({cloneId:ue,sourceId:C}),ie=[ue]}V(pr,Y.first,ie),V(hr,Y.last,ie)})}for(const C of _e){const j=C.anchorBlockId;if(!j||A.has(C.id))continue;const K=bt.get(C.id)??[C.id],Y=Lt.get(j)??[];for(const re of K)Y.includes(re)||Y.push(re);Lt.set(j,Y)}}const ti=new Map(_e.map(c=>[c.id,c])),gr=[..._e.map(c=>({id:c.id,record:c,isClone:!1})),...mr.map(({cloneId:c,sourceId:x})=>({id:c,record:ti.get(x),isClone:!0}))],_t=new Map,Xt=new Map,Wt=new Map;{const c=new Map,x=new Map;for(const N of vt)for(const A of N.children)for(const V of A.bookmark?.split(",")??[])V&&(c.has(V)||c.set(V,A),x.set(V,A));let P=1;for(const[N,A]of c)_t.set(N,P++),Xt.set(A,[...Xt.get(A)??[],N]);for(const[N,A]of x)Wt.set(A,[...Wt.get(A)??[],N])}const zt=new Map,Ht=new Map,Nt=new Map((e.oxmlRanges??[]).filter(c=>c.startXml&&c.endXml).map(c=>[c.id,c]));if(Nt.size>0){const c=new Map,x=new Map;for(const P of vt)for(const N of P.children)for(const A of N.oxmlRange?.split(",")??[])!A||!Nt.has(A)||(c.has(A)||c.set(A,N),x.set(A,N));for(const[P,N]of c)zt.set(N,[...zt.get(N)??[],P]);for(const[P,N]of x)Ht.set(N,[...Ht.get(N)??[],P])}const ri=c=>{const x=c.children.filter(N=>(N.text??"")!==""||N.fieldInstr);if(x.length===0)return;const P=x[0].fieldInstr;if(!(!P||!/^TOC\b/i.test(P.trim())))return x.every(N=>N.fieldInstr===P)?P:void 0},jt=new Map,ur=new Set,Gt=new Set;{let c,x=[];const P=()=>{c&&x.length>0&&(jt.set(x[0],c),ur.add(x[x.length-1]),x.forEach(N=>Gt.add(N))),c=void 0,x=[]};for(const N of yt){const A=N.type==="paragraph"?N:void 0,V=A?ri(A):void 0;if(A&&V&&V===c){x.push(A);continue}P(),A&&V&&(c=V,x=[A])}P()}const Tt=c=>{const x=`<root><w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${c}</w:r></root>`,P=J.fromXmlString(x).root?.[0];if(P?.root){for(const N of P.root)if(N?.rootKey==="w:r")return N}},ii=c=>c.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),fr=c=>[Tt('<w:fldChar w:fldCharType="begin"/>'),Tt(`<w:instrText xml:space="preserve"> ${ii(c)} </w:instrText>`),Tt('<w:fldChar w:fldCharType="separate"/>')].filter(Boolean),wr=()=>[Tt('<w:fldChar w:fldCharType="end"/>')].filter(Boolean),ni=Gt.size>0||vt.some(c=>c.children.some(x=>x.fieldInstr)),oi=c=>{if(nr(c.xml))return new w({});try{const x=c.origin==="run"?`<root><w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:r>${c.xml}</w:r></w:p></root>`:`<root>${c.xml}</root>`,P=J.fromXmlString(x).root?.[0];for(const N of P?.root??[])if(N?.rootKey&&N.rootKey!=="_attr")return N}catch{}return new w({})},br=async c=>c.type==="table"?Ue(c):c.type==="codeblock"?gt(c):c.type==="mathblock"?st(c):c.type==="pagebreak"?Yr():c.type==="sectionbreak"?null:c.type==="image"?Vr(c):c.type==="docxraw"?oi(c):ot(c),si=await Promise.all(yt.map(br)),Jt={},Mt=new Map,yr=c=>{for(const x of c)if(x.type==="paragraph"&&x.list?.reference){const P=`${x.list.reference}\0${x.list.instance??0}`;Mt.has(P)||Mt.set(P,x.list)}else if(x.type==="table")for(const P of x.rows)for(const N of P.cells)yr(N.blocks??N.paragraphs)},vr=async(c,x)=>{const P=this.toDocxFormatWithTables({...e,children:c.children},r);yr(P);const N=(await Promise.all(P.map(br))).filter(A=>A!==null).map(A=>A);Jt[String(x)]={children:N.length>0?N:[new w({})]}};let ai=Ct.size;for(const c of Qr){const x=Ct.get(c.id)??++ai;await vr(c,x)}const xr=new Map;for(let c=0;c<wt.length;c++){const x=wt[c],P=1e6+c;xr.set(x.id,P),await vr(x,P)}const Ut=[...Mt.keys()],li=Ut.map((c,x)=>ot({type:"paragraph",children:[{text:`__RVSE_NOTE_NUM_${x}__`}],list:Mt.get(c)}));{const c=Mi(e.chrome??[]),x=Pe(e.headers??c.headers,y,"header"),P=Pe(e.footers??c.footers,B,"footer");x&&(Ee.headers=x),P&&(Ee.footers=P),e.watermark&&!Ee.headers&&(Ee.headers={default:new y({children:[new w({})]})}),ge.showPageNumbers&&(ge.pageNumberPosition.startsWith("top")&&!Ee.headers?Ee.headers={default:new y({children:[De]})}:!ge.pageNumberPosition.startsWith("top")&&!Ee.footers&&(Ee.footers={default:new B({children:[De]})}))}const Ce=e.coreProperties??{},ci={...Ce.title!==void 0?{title:Ce.title}:{},...Ce.subject!==void 0?{subject:Ce.subject}:{},...Ce.creator!==void 0?{creator:Ce.creator}:{},...Ce.keywords!==void 0?{keywords:Ce.keywords}:{},...Ce.description!==void 0?{description:Ce.description}:{},...Ce.lastModifiedBy!==void 0?{lastModifiedBy:Ce.lastModifiedBy}:{}},di=new n({...ci,...e.pageLayout?.blockSpacingPx!==void 0?{customProperties:[{name:"Revise.BlockSpacingPx",value:String(Te(e.pageLayout).blockSpacingPx)}]}:{},numbering:Ge,...ni?{features:{updateFields:!0}}:{},...Oe?{evenAndOddHeaderAndFooters:!0}:{},..._e.length>0?{comments:{children:gr.map(({id:c,record:x})=>({id:Re.get(c),author:x.author,...x.initials?{initials:x.initials}:{},date:new Date(x.createdAt),children:(x.bodyMd||" ").split(/\n\n+/).map(P=>new w({children:[new u({text:P})]}))}))}}:{},...Object.keys(Jt).length>0?{footnotes:Jt}:{},styles:{default:{document:{run:{size:this.DEFAULT_RUN_SIZE_HALF_POINTS}},...this.buildExportHeadingDefaults()},paragraphStyles:this.buildExportParagraphStyles(e),characterStyles:this.buildExportCharacterStyles()},sections:(()=>{const c=e.chrome??[],x=Ei(c),P=K=>{if(["header","footer"].some(re=>tn(c,re,"first",K)))return!0;if(!x)return Me;const Y=Dr(c,K);return!!(Y.headers?.first||Y.footers?.first)},N=K=>{if(!x)return Ee;const Y=Dr(c,K),re={},ie=Pe(Y.headers,y),ue=Pe(Y.footers,B);return ie&&(re.headers=ie),ue&&(re.footers=ue),ge.showPageNumbers&&(ge.pageNumberPosition.startsWith("top")&&!re.headers?re.headers={default:new y({children:[De]})}:!ge.pageNumberPosition.startsWith("top")&&!re.footers&&(re.footers={default:new B({children:[De]})})),re},A=[];let V=[],C;yt.forEach((K,Y)=>{if("type"in K&&K.type==="sectionbreak"){const ie=K;ye.push(Di(e.pageLayout,ie.layout));const ue=ee(ie.layout,C,A.length===0?"first":"middle");P(A.length)&&(ue.titlePage=!0),A.push({properties:ue,...N(A.length),children:V}),V=[],C=ie.breakType;return}const re=si[Y];re!=null&&V.push(re)}),ye.push(Bi(e.pageLayout));const j=A.length===0?me:ee(e.pageLayout,C,"final");return P(A.length)?j.titlePage=!0:x&&j===me&&delete j.titlePage,A.push({properties:j,...N(A.length),children:[...V,...li]}),A})()}),pi=await this.stabilizeHyperlinkRelIds(await this.stabilizeAttributeWhitespace(await s.toBlob(di))),Et=[],Zt=[];let pt=0;for(const c of yt){if("type"in c&&c.type==="table")continue;if("type"in c&&c.type==="docxraw"){c.emitsParagraph&&pt++;continue}if("type"in c&&c.type==="sectionbreak"){const N=c.pendingDeletion;N&&Et.push({pIndex:pt,kind:"merge",...N}),pt++;continue}const x=c.paragraphMarkRevision;x&&Et.push({pIndex:pt,...x});const P=c.paragraphPropertiesChange;P&&Zt.push({pIndex:pt,...P}),pt++}let te=pi;if(et.size>0&&(te=await this.patchLinkedMoveRevisions(te,Array.from(et.values()))),Ut.length>0&&(te=await this.patchNoteNumberingReferences(te,Ut)),$e&&(te=await this.patchRunPropertyResetMarkers(te)),ae.length>0&&(te=await this.applyOxmlAttrMarkers(te,ae)),ye.some(c=>c)&&(te=await this.injectSectPrOpaquePayloads(te,ye)),lt.length>0)try{te=await this.patchAnchoredImages(te,lt)}catch(c){console.warn("docx export: anchored-image restore failed; exporting images inline",c)}if(at.length>0)try{te=await this.patchOriginalVectorImages(te,at)}catch(c){console.warn("docx export: EMF/WMF original-media patch failed; exporting placeholder images",c)}if(Et.length>0)try{te=await this.patchParagraphMarkRevisions(te,Et,ce)}catch(c){console.warn("docx export: paragraph-mark revision patch failed; exporting without pilcrow markup",c)}if(Zt.length>0)try{te=await this.patchParagraphPropertyChanges(te,Zt,ce)}catch(c){console.warn("docx export: w:pPrChange patch failed; exporting without paragraph property-change markup",c)}if(cr.length>0)try{te=await this.patchTableRevisions(te,cr,ce)}catch(c){console.warn("docx export: table revision patch failed; exporting table content without revision markup",c)}if(_e.length>0)try{te=await this.appendCommentsExtendedPart(te,gr.map(({id:c,record:x,isClone:P})=>{const N=!P&&x.parentId?lr(x):void 0;return{numericId:Re.get(c),resolved:x.resolved===!0,parentNumericId:N&&N!==x.id?Re.get(N):void 0}}))}catch(c){console.warn("docx export: commentsExtended generation failed; comments export flat/unresolved",c)}if(wt.length>0)try{te=await this.appendEndnotesPart(te,wt.map(c=>({index:ct.get(c.id),note:c,syntheticFootnoteId:xr.get(c.id)})))}catch(c){console.warn("docx export: endnotes part generation failed; endnote markers left in text",c)}if(e.sdtWrappers&&e.sdtWrappers.length>0)try{te=await this.applySdtWrappers(te,e)}catch(c){console.warn("docx export: content-control wrapping failed; content exported unwrapped",c)}if(e.coreProperties)try{te=await this.patchCoreProperties(te,Ce)}catch(c){console.warn("docx export: core-property patch failed; library defaults kept",c)}if(e.stylesXml)try{te=await this.mergeImportedStyles(te,e.stylesXml)}catch(c){console.warn("docx export: styles.xml merge failed; imported named styles dropped",c)}if(e.watermark)try{te=await this.injectWatermarkIntoHeaders(te,e.watermark)}catch(c){console.warn("docx export: watermark header injection failed; exporting without watermark",c)}if(Te(e.pageLayout).hyphenationEnabled)try{te=await this.injectAutoHyphenationSetting(te)}catch(c){console.warn("docx export: autoHyphenation setting injection failed",c)}try{te=await this.stampApplicationProperty(te)}catch(c){console.warn("docx export: application stamp failed; exporting without it",c)}if(t?.graft&&$t){const c=x=>{try{t.graft?.onOutcome?.(x)}catch{}};if(!e.docxSource)return console.warn("docx export: graft requested but document has no docxSource capture; exporting regenerated package"),c({mode:"regenerated",fallbackCode:"no-capture"}),te;try{te=await Ri({generatedBlob:te,originalDocx:t.graft.originalDocx,doc:e,blockRanges:$t});const x=Fi(e);c({mode:x.fullyExact?"exact":"grafted",regeneratedBlockCount:x.regeneratedBlockIds.length,changedDomains:Object.entries(x.domains).filter(([,P])=>!P).map(([P])=>P)})}catch(x){const P=x instanceof Oi?x.code:"internalError";console.warn(`docx export: OOXML graft rejected [${P}]; exporting regenerated package`,x),c({mode:"regenerated",fallbackCode:P})}}return te}static async patchNoteNumberingReferences(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;let n=await i.async("text");const s=new Map;n=n.replace(/<w:p\b[^>]*>[\s\S]*?<\/w:p>/g,l=>{const d=/__RVSE_NOTE_NUM_(\d+)__/.exec(l);if(!d)return l;const p=Number(d[1]),m=/<w:numId\b[^>]*w:val="([^"]+)"/.exec(l)?.[1],h=r[p];return h&&m&&!m.startsWith("{")&&s.set(h,m),""}),t.file("word/document.xml",n);const o=l=>l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");for(const[l,d]of Object.entries(t.files)){if(!l.startsWith("word/")||!l.endsWith(".xml")||d.dir)continue;let p=await d.async("text"),m=!1;for(const[h,g]of s){const[w,u]=h.split("\0"),f=`{${w}-${u}}`,b=p.replace(new RegExp(`w:val="${o(f)}"`,"g"),`w:val="${g}"`);m||(m=b!==p),p=b}m&&t.file(l,p)}const a=await this.generateCompressedZipBlob(t);return new Blob([a],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async injectSectPrOpaquePayloads(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;let n=await i.async("text"),s=0;n=n.replace(/<w:sectPr\b[^>]*>[\s\S]*?<\/w:sectPr>|<w:sectPr\b[^>]*\/>/g,d=>{const p=r[s++];return p?d.endsWith("/>")?`${d.slice(0,-2)}>${p}</w:sectPr>`:d.replace(/<\/w:sectPr>$/,`${p}</w:sectPr>`):d});const o=new DOMParser().parseFromString(n,"application/xml"),a=new Set(["w:lnNumType","w:pgNumType","w:cols","w:formProt","w:vAlign","w:noEndnote","w:titlePg","w:textDirection","w:bidi","w:rtlGutter","w:docGrid","w:printerSettings","w:sectPrChange"]);for(const d of Array.from(o.getElementsByTagName("w:sectPr"))){const p=Array.from(d.children).find(h=>h.tagName==="w:pgBorders"),m=Array.from(d.children).find(h=>a.has(h.tagName));p&&m&&d.insertBefore(p,m)}n=new XMLSerializer().serializeToString(o),t.file("word/document.xml",n);const l=await this.generateCompressedZipBlob(t);return new Blob([l],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async stabilizeAttributeWhitespace(e){let r;try{r=await this.loadZipFromBlob(e)}catch{return e}const{stabilizeSerializedXml:t}=await Promise.resolve().then(()=>sn);let i=!1;for(const[s,o]of Object.entries(r.files)){if(!s.endsWith(".xml")||o.dir)continue;const a=await o.async("text"),l=t(a);l!==a&&(r.file(s,l),i=!0)}if(!i)return e;const n=await this.generateCompressedZipBlob(r);return new Blob([n],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async stabilizeHyperlinkRelIds(e){let r;try{r=await this.loadZipFromBlob(e)}catch{return e}let t=!1;for(const[n,s]of Object.entries(r.files)){const o=/^(.*)_rels\/([^/]+)\.rels$/.exec(n);if(!o||s.dir)continue;const a=`${o[1]}${o[2]}`,l=r.file(a);if(!l)continue;let d=await s.async("text");const p=[];for(const g of d.matchAll(/<Relationship\b[^>]*\/?>/g)){if(!/Type="[^"]*\/hyperlink"/.test(g[0]))continue;const w=/Id="([^"]+)"/.exec(g[0])?.[1];w&&p.push(w)}if(p.length===0)continue;let m=await l.async("text");const h=[...p].sort((g,w)=>{const u=m.indexOf(`"${g}"`),f=m.indexOf(`"${w}"`);return(u<0?1/0:u)-(f<0?1/0:f)});h.forEach((g,w)=>{g!==`rvseLnk${w+1}`&&(m=m.replaceAll(`r:id="${g}"`,`r:id="__rvseLnkTmp${w+1}__"`),d=d.replace(`Id="${g}"`,`Id="__rvseLnkTmp${w+1}__"`),t=!0)}),h.forEach((g,w)=>{m=m.replaceAll(`r:id="__rvseLnkTmp${w+1}__"`,`r:id="rvseLnk${w+1}"`),d=d.replace(`Id="__rvseLnkTmp${w+1}__"`,`Id="rvseLnk${w+1}"`)}),r.file(a,m),r.file(n,d)}if(!t)return e;const i=await this.generateCompressedZipBlob(r);return new Blob([i],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async applyOxmlAttrMarkers(e,r){const t=await this.loadZipFromBlob(e);for(const[n,s]of Object.entries(t.files)){if(!n.startsWith("word/")||!n.endsWith(".xml")||s.dir)continue;let o=await s.async("text");if(o.includes("<w:rvseOxmlAttrs ")){for(const a of["w:p","w:tr"])o=o.replace(new RegExp(`<${a}\\b([^>]*)>((?:(?!<${a}\\b)(?!</${a}>)[\\s\\S])*?)<w:rvseOxmlAttrs w:val="(\\d+)"/>`,"g"),(l,d,p,m)=>{const h=r[Number(m)];if(!h)return`<${a}${d}>${p}`;const g=new Set([...d.matchAll(/([\w:.-]+)=/g)].map(u=>u[1])),w=Wr(h,g);return`<${a}${d}${w}>${p}`});o=o.replace(/<w:rvseOxmlAttrs w:val="\d+"\/>/g,"").replace(/<w:pPr><\/w:pPr>|<w:pPr\/>/g,"").replace(/<w:trPr><\/w:trPr>|<w:trPr\/>/g,""),t.file(n,o)}}const i=await this.generateCompressedZipBlob(t);return new Blob([i],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchRunPropertyResetMarkers(e){const r=await this.loadZipFromBlob(e);for(const[i,n]of Object.entries(r.files)){if(!i.startsWith("word/")||!i.endsWith(".xml")||n.dir)continue;let s=await n.async("text");/<w:(?:specVanish|imprint|emboss|snapToGrid)\b/.test(s)&&(s=s.replace(/<w:specVanish\b[^>]*\/>/g,'<w:vanish w:val="false"/>').replace(/<w:imprint\b[^>]*\/>/g,'<w:spacing w:val="0"/>').replace(/<w:emboss\b[^>]*\/>/g,'<w:vertAlign w:val="baseline"/>').replace(/<w:snapToGrid\b([^>]*)\/>/g,(o,a)=>/\bw:val="(?:false|0|off)"/i.test(a)?'<w:caps w:val="false"/>':"<w:caps/>"),r.file(i,s))}const t=await this.generateCompressedZipBlob(r);return new Blob([t],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async injectAutoHyphenationSetting(e){const r=await this.loadZipFromBlob(e),t=r.file("word/settings.xml");if(!t)return e;let i=await t.async("text");if(i.includes("<w:autoHyphenation"))return e;i=i.replace(/<\/w:settings>/,"<w:autoHyphenation/></w:settings>"),r.file("word/settings.xml",i);const n=await this.generateCompressedZipBlob(r);return new Blob([n],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static escapeXml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/\n/g,"&#10;").replace(/\r/g,"&#13;").replace(/\t/g,"&#9;")}static dataUrlToUint8Array(e){const r=e.match(/^data:([^;,]+)(;base64)?,(.*)$/i);if(!r)return;const t=r[3]||"";try{return r[2]?this.base64ToUint8Array(t):new TextEncoder().encode(decodeURIComponent(t))}catch{return}}static async resolveBinarySourceForDocx(e){const r=this.dataUrlToUint8Array(e);if(r)return r;if(typeof fetch=="function")try{const t=await fetch(e);return t.ok?new Uint8Array(await t.arrayBuffer()):void 0}catch{return}}static async rasterizeSvgDataUrlToPng(e,r,t){if(!(typeof document>"u"||typeof Image>"u"||typeof navigator<"u"&&navigator.userAgent?.includes("jsdom")))return new Promise(i=>{let n=!1;const s=l=>{n||(n=!0,i(l))},o=setTimeout(()=>s(void 0),3e3),a=new Image;a.onload=()=>{clearTimeout(o);try{const l=document.createElement("canvas");l.width=Math.max(1,Math.round(r)),l.height=Math.max(1,Math.round(t));const d=l.getContext("2d");if(!d){s(void 0);return}d.drawImage(a,0,0,l.width,l.height),l.toBlob(async p=>{if(!p){s(void 0);return}s(new Uint8Array(await p.arrayBuffer()))},"image/png")}catch{s(void 0)}},a.onerror=()=>{clearTimeout(o),s(void 0)},a.src=e})}static serializeXmlPreservingPrefixes(e){const r=new Map,t=(s,o)=>{const a=o.indexOf(":");if(a<=0)return;const l=o.slice(0,a);if(l==="xmlns"||l==="xml"||r.has(l))return;const d=s.lookupNamespaceURI(l);d&&r.set(l,d)},i=s=>{t(s,s.tagName);for(let o=0;o<s.attributes.length;o++)t(s,s.attributes[o].name);for(let o=0;o<s.children.length;o++)i(s.children[o])};i(e);const n=(s,o)=>{if(s.nodeType===3)return(s.nodeValue??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");if(s.nodeType!==1)return"";const a=s;let l=`<${a.tagName}`;const d=new Set;for(let m=0;m<a.attributes.length;m++){const h=a.attributes[m];h.name.startsWith("xmlns:")&&d.add(h.name.slice(6)),l+=` ${h.name}="${this.escapeXml(h.value)}"`}if(o)for(const[m,h]of r)d.has(m)||(l+=` xmlns:${m}="${this.escapeXml(h)}"`);const p=a.childNodes;if(p.length===0)return`${l}/>`;l+=">";for(let m=0;m<p.length;m++)l+=n(p[m],!1);return`${l}</${a.tagName}>`};return n(e,!0)}static async patchAnchoredImages(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;let n=await i.async("string"),s=!1;for(const o of r){const a=`title="${this.escapeXml(o.marker)}"`,l=n.indexOf(a);if(l===-1)continue;const d=()=>{n=n.replace(` ${a}`,""),s=!0},p=n.lastIndexOf("<wp:inline",l),m=n.indexOf("</wp:inline>",l);if(p===-1||m===-1){d();continue}const h=m+12,g=n.slice(p,h),w=Array.from(g.matchAll(/r:embed="([^"]+)"/g)).map(I=>I[1]);if(w.length===0){d();continue}let u=0,f=o.anchorXml.replace(/(r:(?:embed|link)=")[^"]*(")/g,(I,y,B)=>{const $=w[Math.min(u,w.length-1)];return u++,`${y}${$}${B}`});const b=g.match(/<wp:docPr\b[^>]*/)?.[0].match(/ descr="([^"]*)"/);f=f.replace(/<wp:docPr\b([^>]*?)(\/?>)/,(I,y,B)=>{const $=y.replace(/\s+descr="[^"]*"/,""),W=b?` descr="${b[1]}"`:"";return`<wp:docPr${$}${W}${B}`}),n=n.slice(0,p)+f+n.slice(h),s=!0}return s?(t.file("word/document.xml",n),this.generateCompressedZipBlob(t)):e}static async patchOriginalVectorImages(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml"),n=t.file("word/_rels/document.xml.rels"),s=t.file("[Content_Types].xml");if(!i||!n||!s)return e;let o=await i.async("string"),a=await n.async("string"),l=await s.async("string");const d=new Set;for(let p=0;p<r.length;p++){const m=r[p],h=await this.resolveBinarySourceForDocx(m.dataUrl);if(!h)continue;const g=this.escapeXml(m.marker),w=o.indexOf(g);if(w===-1)continue;const u=o.slice(w).match(/r:embed="([^"]+)"/);if(!u)continue;const f=u[1],b=`media/reviseOriginal${p}.${m.format}`,I=new RegExp(`(<Relationship\\b[^>]*\\bId="${f}"[^>]*\\bTarget=")[^"]*(")`),y=new RegExp(`(<Relationship\\b[^>]*\\bTarget=")[^"]*("[^>]*\\bId="${f}")`);if(I.test(a))a=a.replace(I,`$1${b}$2`);else if(y.test(a))a=a.replace(y,`$1${b}$2`);else continue;t.file(`word/${b}`,h),d.add(m.format),o=m.alt?o.replace(`descr="${g}"`,`descr="${this.escapeXml(m.alt)}"`):o.replace(` descr="${g}"`,"")}for(const p of d)new RegExp(`Extension="${p}"`).test(l)||(l=l.replace("</Types>",`<Default Extension="${p}" ContentType="image/x-${p}"/></Types>`));return t.file("word/document.xml",o),t.file("word/_rels/document.xml.rels",a),t.file("[Content_Types].xml",l),this.generateCompressedZipBlob(t)}static async injectWatermarkIntoHeaders(e,r){const t=$i(r);if(!t)return e;const i=await this.loadZipFromBlob(e),n=Object.keys(i.files).filter(g=>/^word\/header\d+\.xml$/.test(g));if(n.length===0)return e;const s=g=>g.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),o=468,a=Math.max(40,Math.round(o/Math.max(2,t.text.length*.55))),l=t.diagonal?"rotation:315;":"",d=t.fontSizePx?`${Math.max(1,Math.round(t.fontSizePx*.75))}pt`:"1pt",p=`<w:p><w:pPr><w:rPr><w:noProof/></w:rPr></w:pPr><w:r><w:rPr><w:noProof/></w:rPr><w:pict xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w10="urn:schemas-microsoft-com:office:word"><v:shapetype id="_x0000_t136" coordsize="21600,21600" o:spt="136" adj="10800" path="m@7,l@8,m@5,21600l@6,21600e"><v:formulas><v:f eqn="sum #0 0 10800"/><v:f eqn="prod #0 2 1"/><v:f eqn="sum 21600 0 @1"/><v:f eqn="sum 0 0 @2"/><v:f eqn="sum 21600 0 @3"/><v:f eqn="if @0 @3 0"/><v:f eqn="if @0 21600 @1"/><v:f eqn="if @0 0 @2"/><v:f eqn="if @0 @4 21600"/><v:f eqn="mid @5 @6"/><v:f eqn="mid @8 @5"/><v:f eqn="mid @7 @8"/><v:f eqn="mid @6 @7"/><v:f eqn="sum @6 0 @5"/></v:formulas><v:path textpathok="t" o:connecttype="custom" o:connectlocs="@9,0;@10,10800;@11,21600;@12,10800" o:connectangles="270,180,90,0"/><v:textpath on="t" fitshape="t"/><v:handles><v:h position="#0,bottomRight" xrange="6629,14971"/></v:handles><o:lock v:ext="edit" text="t" shapetype="t"/></v:shapetype><v:shape id="PowerPlusWaterMarkObject1" o:spid="_x0000_s2049" type="#_x0000_t136" style="position:absolute;margin-left:0;margin-top:0;width:${o}pt;height:${a}pt;${l}z-index:-251654144;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin" o:allowincell="f" fillcolor="${s(t.color)}" stroked="f"><v:fill opacity="${t.opacity===Li?Tr:t.opacity}"/><v:textpath style="font-family:&quot;Calibri&quot;;font-size:${d}" string="${s(t.text)}"/></v:shape></w:pict></w:r></w:p>`;let m=!1;for(const g of n){const w=await i.file(g).async("text");if(w.includes("v:textpath"))continue;const u=w.replace(/(<w:hdr[^>]*>)/,`$1${p}`);u!==w&&(i.file(g,u),m=!0)}if(!m)return e;const h=await this.generateCompressedZipBlob(i);return new Blob([h],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async mergeImportedStyles(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/styles.xml");if(!i)return e;let n=await i.async("text");const s=r.match(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/)?.[0];s&&(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/.test(n)?n=n.replace(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/,s):n=n.replace(/(<w:styles\b[^>]*>)/,`$1${s}`));const o=new Map;for(const u of r.matchAll(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g)){const f=u[0].match(/w:styleId="([^"]+)"/);f&&o.set(f[1],u[0])}if(o.size===0&&!s)return e;const a=new Set;n=n.replace(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g,u=>{const f=u.match(/w:styleId="([^"]+)"/),b=f?o.get(f[1]):void 0;return b?(a.add(f[1]),b):u});const l=[];for(const[u,f]of o)a.has(u)||l.push(f);n=n.replace(/<\/w:styles>/,`${l.join("")}</w:styles>`);const d=new Set,p=u=>{for(const f of u.matchAll(/<w:(?:pStyle|rStyle|tblStyle)\b[^>]*w:val="([^"]+)"/g))d.add(f[1])};for(const u of Object.keys(t.files))/^word\/[^/]+\.xml$/.test(u)&&u!=="word/styles.xml"&&p(await t.file(u).async("text"));const m=new Map;for(const u of n.matchAll(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g)){const f=u[0].match(/w:styleId="([^"]+)"/);f&&m.set(f[1],u[0])}const h=(u,f)=>o.has(u)||/w:default="(?:1|true)"/.test(f.slice(0,f.indexOf(">")))||d.has(u);let g=!0;for(;g;){g=!1;for(const[u,f]of m)if(h(u,f))for(const b of f.matchAll(/<w:(?:basedOn|link|next)\b[^>]*w:val="([^"]+)"/g))d.has(b[1])||(d.add(b[1]),g=!0)}n=n.replace(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g,u=>{const f=u.match(/w:styleId="([^"]+)"/);return!f||h(f[1],u)?u:""}),t.file("word/styles.xml",n);const w=await this.generateCompressedZipBlob(t);return new Blob([w],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchCoreProperties(e,r){const t=await this.loadZipFromBlob(e),i=t.file("docProps/core.xml");if(!i)return e;let n=await i.async("text");const s=l=>l.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");for(const l of["created","modified"]){const d=r[l];if(!d)continue;const p=new RegExp(`(<dcterms:${l}\\b[^>]*>)[^<]*(</dcterms:${l}>)`);p.test(n)?n=n.replace(p,`$1${s(d)}$2`):n=n.replace(/<\/cp:coreProperties>/,`<dcterms:${l} xsi:type="dcterms:W3CDTF">${s(d)}</dcterms:${l}></cp:coreProperties>`)}const o=/<cp:revision>[^<]*<\/cp:revision>/;if(r.revision){const l=`<cp:revision>${s(r.revision)}</cp:revision>`;n=o.test(n)?n.replace(o,l):n.replace(/<\/cp:coreProperties>/,`${l}</cp:coreProperties>`)}else n=n.replace(o,"");for(const[l,d]of[["creator","dc:creator"],["lastModifiedBy","cp:lastModifiedBy"]])r[l]||(n=n.replace(new RegExp(`<${d}>[^<]*</${d}>`),""));t.file("docProps/core.xml",n);const a=await this.generateCompressedZipBlob(t);return new Blob([a],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async stampApplicationProperty(e){const r=await this.loadZipFromBlob(e),t=r.file("docProps/app.xml");if(!t)return e;let i=await t.async("text");const n="<Application>Revise (revise.io)</Application>";if(/<Application[\s>]/.test(i))return e;if(/<Properties\b[^>]*\/>/.test(i))i=i.replace(/<Properties\b([^>]*)\/>/,`<Properties$1>${n}</Properties>`);else if(i.includes("</Properties>"))i=i.replace("</Properties>",`${n}</Properties>`);else return e;r.file("docProps/app.xml",i);const s=await this.generateCompressedZipBlob(r);return new Blob([s],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async appendCommentsExtendedPart(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/comments.xml");if(!i)return e;let n=await i.async("text");n.includes("xmlns:w14=")||(n=n.replace(/<w:comments /,'<w:comments xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" '));const s=p=>(268435456+p).toString(16).toUpperCase().padStart(8,"0");n=n.replace(/<w:comment\b([^>]*)>([\s\S]*?)<\/w:comment>/g,(p,m,h)=>{const g=m.match(/w:id="(\d+)"/);if(!g)return p;const w=s(parseInt(g[1],10)),u=h.lastIndexOf("<w:p");if(u===-1)return p;const f=h.slice(0,u)+h.slice(u).replace(/<w:p(\s|>)/,`<w:p w14:paraId="${w}"$1`);return`<w:comment${m}>${f}</w:comment>`}),t.file("word/comments.xml",n);const o='<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w15:commentsEx xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml">'+r.map(({numericId:p,resolved:m,parentNumericId:h})=>`<w15:commentEx ${[`w15:paraId="${s(p)}"`,...h!==void 0?[`w15:paraIdParent="${s(h)}"`]:[],`w15:done="${m?"1":"0"}"`].join(" ")}/>`).join("")+"</w15:commentsEx>";t.file("word/commentsExtended.xml",o);const a=t.file("[Content_Types].xml");if(a){let p=await a.async("text");p.includes("/word/commentsExtended.xml")||(p=p.replace("</Types>",'<Override PartName="/word/commentsExtended.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml"/></Types>'),t.file("[Content_Types].xml",p))}const l=t.file("word/_rels/document.xml.rels");if(l){let p=await l.async("text");p.includes("commentsExtended.xml")||(p=p.replace("</Relationships>",'<Relationship Id="rIdRvseCommentsEx" Type="http://schemas.microsoft.com/office/2011/relationships/commentsExtended" Target="commentsExtended.xml"/></Relationships>'),t.file("word/_rels/document.xml.rels",p))}const d=await this.generateCompressedZipBlob(t);return new Blob([d],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async appendEndnotesPart(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;let n=await i.async("text");for(const{index:u}of r){const f=`__RVSE_EN_${u}__`;for(const b of["w:t","w:delText"])n=n.replaceAll(`<${b} xml:space="preserve">${f}</${b}>`,`<w:endnoteReference w:id="${u}"/>`).replaceAll(`<${b}>${f}</${b}>`,`<w:endnoteReference w:id="${u}"/>`)}t.file("word/document.xml",n);const s=new Map;let o='<w:endnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">';const a=t.file("word/footnotes.xml");if(a){let u=await a.async("text");const f=u.match(/<w:footnotes\b[^>]*>/)?.[0];f&&(o=f.replace(/<w:footnotes\b/,"<w:endnotes"));const b=new Set(r.map(y=>y.syntheticFootnoteId).filter(y=>y!==void 0));u=u.replace(/<w:footnote\b[^>]*>[\s\S]*?<\/w:footnote>/g,y=>{const B=/\bw:id="(-?\d+)"/.exec(y)?.[1],$=B?Number(B):NaN;if(!b.has($))return y;const W=r.find(D=>D.syntheticFootnoteId===$);if(!W)return y;const z=y.replace(/^<w:footnote\b[^>]*>/,`<w:endnote w:id="${W.index}">`).replace(/<\/w:footnote>$/,"</w:endnote>").replaceAll("w:footnoteRef","w:endnoteRef").replaceAll("FootnoteReference","EndnoteReference").replaceAll("FootnoteText","EndnoteText");return s.set($,z),""}),t.file("word/footnotes.xml",u);const I=t.file("word/_rels/footnotes.xml.rels");I&&t.file("word/_rels/endnotes.xml.rels",await I.async("text"))}const l=u=>u.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),d=(u,f)=>{const b=u.marks??{},I=[];if(b.bold&&I.push("<w:b/>"),b.italic&&I.push("<w:i/>"),b.underline&&I.push('<w:u w:val="single"/>'),b.strikethrough&&I.push("<w:strike/>"),b.doubleStrikethrough&&I.push("<w:dstrike/>"),b.smallCaps&&I.push("<w:smallCaps/>"),b.allCaps&&I.push("<w:caps/>"),b.hidden&&I.push("<w:vanish/>"),b.color&&I.push(`<w:color w:val="${l(this.normalizeColor(b.color))}"/>`),b.backgroundColor&&I.push(`<w:highlight w:val="${l(b.backgroundColor)}"/>`),typeof b.fontSize=="number"&&b.fontSize>0&&I.push(`<w:sz w:val="${Math.max(2,Math.round(b.fontSize*this.DOCX_HALF_POINTS_PER_PX))}"/>`),b.fontFamily){const B=l(b.fontFamily.split(",")[0].replaceAll('"',"").replaceAll("'","").trim());I.push(`<w:rFonts w:ascii="${B}" w:hAnsi="${B}"/>`)}typeof b.letterSpacing=="number"&&Number.isFinite(b.letterSpacing)&&b.letterSpacing!==0&&I.push(`<w:spacing w:val="${Math.round(b.letterSpacing*15)}"/>`),b.superscript?I.push('<w:vertAlign w:val="superscript"/>'):b.subscript&&I.push('<w:vertAlign w:val="subscript"/>'),b.lang&&I.push(`<w:lang w:val="${l(b.lang)}"/>`);const y=f&&!/^\s/.test(u.text??"")?` ${u.text??""}`:u.text??"";return`<w:r>${I.length>0?`<w:rPr>${I.join("")}</w:rPr>`:""}<w:t xml:space="preserve">${l(y)}</w:t></w:r>`},p=r.sort((u,f)=>u.index-f.index).map(({index:u,note:f,syntheticFootnoteId:b})=>{const I=b!==void 0?s.get(b):void 0;if(I)return I;const y=f.children.filter(B=>B.type==="paragraph").map((B,$)=>'<w:p><w:pPr><w:pStyle w:val="EndnoteText"/></w:pPr><w:r><w:rPr><w:rStyle w:val="EndnoteReference"/></w:rPr><w:endnoteRef/></w:r>'+(B.children.filter(W=>(W.text??"")!=="").map((W,z)=>d(W,$===0&&z===0)).join("")||'<w:r><w:t xml:space="preserve"> </w:t></w:r>')+"</w:p>").join("");return`<w:endnote w:id="${u}">${y}</w:endnote>`}).join(""),m='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+o+'<w:endnote w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:endnote><w:endnote w:type="continuationSeparator" w:id="0"><w:p><w:r><w:continuationSeparator/></w:r></w:p></w:endnote>'+p+"</w:endnotes>";t.file("word/endnotes.xml",m);const h=t.file("[Content_Types].xml");if(h){let u=await h.async("text");u.includes("/word/endnotes.xml")||(u=u.replace("</Types>",'<Override PartName="/word/endnotes.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml"/></Types>'),t.file("[Content_Types].xml",u))}const g=t.file("word/_rels/document.xml.rels");if(g){let u=await g.async("text");u.includes("endnotes.xml")||(u=u.replace("</Relationships>",'<Relationship Id="rIdRvseEndnotes" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/endnotes" Target="endnotes.xml"/></Relationships>'),t.file("word/_rels/document.xml.rels",u))}const w=await this.generateCompressedZipBlob(t);return new Blob([w],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static emittedBodySlotCount(e){switch(e.type){case"paragraph":case"table":case"code":case"math":case"image":case"page-break":case"section-break":return 1;case"list":return e.children.filter(r=>r.type==="list-item").length;default:return 0}}static async applySdtWrappers(e,r){const t=r.sdtWrappers??[];if(t.length===0)return e;const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const s=await n.async("text"),o=this.parseDocumentXml(s);if(!o)return e;const a=o.getElementsByTagName("w:body")[0];if(!a)return e;const l="http://schemas.openxmlformats.org/wordprocessingml/2006/main",d=Array.from(a.children).filter(F=>F.tagName==="w:p"||F.tagName==="w:tbl"),p=r.children.filter(F=>F.type!=="footnote"&&F.type!=="header-footer"),m=new Map,h=[];let g=!0;{let F=0;p.forEach((S,E)=>{S.id&&m.set(S.id,E),h[E]=F,F+=this.emittedBodySlotCount(S)}),F!==d.length&&(console.warn(`docx export: content-control slot accounting mismatch (${F} computed vs ${d.length} body elements); exporting without sdt wrappers`),g=!1)}const w=F=>{if(F.blockIds&&F.blockIds.length>0)return F.blockIds;const S=F.startBlockId?m.get(F.startBlockId):void 0;if(S===void 0)return[];const E=Math.min(S+Math.max(1,F.blockCount??1),p.length);return p.slice(S,E).map(M=>M.id).filter(M=>!!M)};let u=!1;const f=new Map(t.map(F=>[F.id,F])),b=F=>this.parseDocumentXml(`<w:root xmlns:w="${l}">${F.prXml}</w:root>`)?.getElementsByTagName("w:sdtPr")[0]??void 0,I=(F,S)=>{const E=F[0].parentNode;if(!E)return;const M=o.createElementNS(l,"w:sdt"),v=o.createElementNS(l,"w:sdtContent");E.insertBefore(M,F[0]),M.appendChild(o.importNode(S,!0)),M.appendChild(v);for(const R of F)v.appendChild(R);u=!0};{const F=Array.from(o.getElementsByTagName("w:bookmarkStart")).filter(S=>(S.getAttribute("w:name")??"").startsWith("__rvSdt:"));if(F.length>0){const S=new Map;for(const v of Array.from(o.getElementsByTagName("w:bookmarkEnd"))){const R=v.getAttribute("w:id");R&&S.set(R,v)}const E=v=>{v.parentNode&&(v.parentNode.removeChild(v),u=!0)},M=[];for(const v of F){const R=(v.getAttribute("w:name")??"").slice(8).split(":")[0],_=S.get(v.getAttribute("w:id")??""),L=f.get(R);if(!_||!L||L.scope!=="inline"||_.parentNode!==v.parentNode||!v.parentNode){E(v),_&&E(_);continue}let H=0;for(let U=v.nextSibling;U&&U!==_;U=U.nextSibling)H++;M.push({record:L,start:v,end:_,covered:H})}M.sort((v,R)=>v.covered-R.covered);for(const v of M){const R=v.start.parentNode===v.end.parentNode&&v.start.parentNode?b(v.record):void 0;if(R){const _=[];for(let L=v.start.nextSibling;L&&L!==v.end;L=L.nextSibling)L.nodeType===1&&_.push(L);_.length>0&&I(_,R)}E(v.start),E(v.end)}}}const y=new Map,B=new Map,$=new Map;g&&p.forEach((F,S)=>{if(F.type!=="table")return;const E=d[h[S]];if(!E||E.tagName!=="w:tbl")return;$.set(S,Array.from(E.children).filter(R=>R.tagName==="w:tr"));const M=F,v=qe(M);M.children.forEach((R,_)=>{R.id&&y.set(R.id,{tableIndex:S,rowIndex:_});for(const L of R.children)L.id&&B.set(L.id,{tableIndex:S,rowIndex:_,gridCol:v.byId.get(L.id)?.col??0})})});for(const F of t){if(F.scope!=="cell")continue;if(!g)break;const S=(F.blockIds??[]).map(v=>B.get(v)).filter(v=>!!v);if(S.length===0){console.warn(`docx export: content control ${F.id} has no surviving member blocks; dropping wrapper`);continue}const E=b(F);if(!E)continue;const M=new Map;for(const v of S){const R=`${v.tableIndex}:${v.rowIndex}`;M.set(R,[...M.get(R)??[],v])}for(const v of M.values()){const R=$.get(v[0].tableIndex)?.[v[0].rowIndex];if(!R)continue;const _=new Set(v.map(k=>k.gridCol)),L=Array.from(R.children).filter(k=>k.tagName==="w:tc"),H=[];let U=0;if(L.forEach((k,X)=>{_.has(U)&&H.push(X);const G=this.getDirectChild(k,"w:tcPr"),q=G?this.getDirectChild(G,"w:gridSpan")?.getAttribute("w:val"):void 0,Z=q?parseInt(q,10):1;U+=Number.isFinite(Z)&&Z>0?Z:1}),H.length===0)continue;const J=H[0],Q=H[H.length-1];I(L.slice(J,Q+1),E)}}for(const F of t){if(F.scope!=="row")continue;if(!g)break;const S=(F.blockIds??[]).map(L=>y.get(L)).filter(L=>!!L);if(S.length===0){console.warn(`docx export: content control ${F.id} has no surviving member blocks; dropping wrapper`);continue}const E=b(F);if(!E)continue;const M=S[0].tableIndex,v=$.get(M);if(!v)continue;const R=S.filter(L=>L.tableIndex===M).map(L=>L.rowIndex).sort((L,H)=>L-H),_=v.slice(R[0],R[R.length-1]+1).filter(L=>!!L.parentNode);_.length>0&&I(_,E)}const W=F=>{let S=0;const E=new Set([F.id]);let M=F;for(;M?.parentId&&!E.has(M.parentId);)E.add(M.parentId),M=f.get(M.parentId),M&&S++;return S},z=t.filter(F=>!F.scope||F.scope==="block").sort((F,S)=>W(S)-W(F));for(const F of z){if(!g)break;const S=w(F).map(H=>m.get(H)).filter(H=>H!==void 0).sort((H,U)=>H-U);if(S.length===0){console.warn(`docx export: content control ${F.id} has no surviving member blocks; dropping wrapper`);continue}const E=S[0],M=S[S.length-1],v=h[E];let R=0;for(let H=E;H<=M;H++)R+=this.emittedBodySlotCount(p[H]);if(R===0)continue;const _=[];for(const H of d.slice(v,v+R)){let U=H;for(;U.parentNode&&U.parentNode!==a&&U.parentNode.nodeType===1;)U=U.parentNode;U.parentNode===a&&!_.includes(U)&&_.push(U)}if(_.length===0)continue;const L=b(F);L&&I(_,L)}if(!u)return e;const D=new XMLSerializer().serializeToString(o);i.file("word/document.xml",D);const T=await this.generateCompressedZipBlob(i);return new Blob([T],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchParagraphMarkRevisions(e,r,t){const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const s=await n.async("text"),o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=new DOMParser().parseFromString(s,"application/xml"),l=a.getElementsByTagName("w:body")[0];if(!l)return e;const d=[];for(let h=0;h<l.children.length;h++)l.children[h].tagName==="w:p"&&d.push(l.children[h]);for(const h of r){const g=d[h.pIndex];if(!g)continue;let w=this.getDirectChild(g,"w:pPr");w||(w=a.createElementNS(o,"w:pPr"),g.insertBefore(w,g.firstChild));let u=this.getDirectChild(w,"w:rPr");if(!u){u=a.createElementNS(o,"w:rPr");const b=this.getDirectChild(w,"w:sectPr");b?w.insertBefore(u,b):w.appendChild(u)}const f=a.createElementNS(o,h.kind==="moveFrom"?"w:moveFrom":h.kind==="moveTo"?"w:moveTo":h.kind==="split"||h.kind==="insert"?"w:ins":"w:del");f.setAttributeNS(o,"w:id",String(t(h.importedId))),f.setAttributeNS(o,"w:author",h.author),f.setAttributeNS(o,"w:date",h.date),u.insertBefore(f,u.firstChild)}const p=new XMLSerializer().serializeToString(a);i.file("word/document.xml",p);const m=await this.generateCompressedZipBlob(i);return new Blob([m],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchParagraphPropertyChanges(e,r,t){const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const s=await n.async("text"),o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=new DOMParser().parseFromString(s,"application/xml"),l=a.getElementsByTagName("w:body")[0];if(!l)return e;const d=[];for(let g=0;g<l.children.length;g++)l.children[g].tagName==="w:p"&&d.push(l.children[g]);const p=(g,w)=>{const u=a.createElementNS(o,g);for(const[f,b]of Object.entries(w??{}))u.setAttributeNS(o,f,b);return u};for(const g of r){const w=d[g.pIndex];if(!w)continue;let u=this.getDirectChild(w,"w:pPr");u||(u=a.createElementNS(o,"w:pPr"),w.insertBefore(u,w.firstChild));const f=p("w:pPrChange",{"w:id":String(t(g.importedId)),"w:author":g.author,"w:date":g.date}),b=g.prior,I=a.createElementNS(o,"w:pPr");if(b.styleId&&I.appendChild(p("w:pStyle",{"w:val":b.styleId})),b.keepNext&&I.appendChild(p("w:keepNext")),b.keepLines&&I.appendChild(p("w:keepLines")),b.widowControl===!1&&I.appendChild(p("w:widowControl",{"w:val":"0"})),b.bordersJson)try{const y=JSON.parse(b.bordersJson),B=a.createElementNS(o,"w:pBdr");for(const $ of["top","left","bottom","right"]){const W=y[$];W&&B.appendChild(p(`w:${$}`,{"w:val":W.style||"single","w:sz":String(Math.max(2,Math.round((W.width??.5)*6))),"w:space":"1","w:color":(W.color||"#000000").replace(/^#/,"")}))}B.children.length>0&&I.appendChild(B)}catch{}b.shadingFill&&I.appendChild(p("w:shd",{"w:val":"clear","w:fill":this.toDocxHex(b.shadingFill)??"auto"})),b.direction&&I.appendChild(p("w:bidi",b.direction==="ltr"?{"w:val":"0"}:{})),b.lineSpacing!==void 0&&I.appendChild(p("w:spacing",{"w:line":String(Math.round(b.lineSpacing*240)),"w:lineRule":"auto"})),(b.leftIndentTwips!==void 0||b.firstLineIndentTwips!==void 0)&&I.appendChild(p("w:ind",{...b.leftIndentTwips!==void 0?{"w:left":String(b.leftIndentTwips)}:{},...b.firstLineIndentTwips!==void 0?{"w:firstLine":String(b.firstLineIndentTwips)}:{}})),b.align&&I.appendChild(p("w:jc",{"w:val":b.align==="justify"?"both":b.align})),f.appendChild(I),u.appendChild(f)}const m=new XMLSerializer().serializeToString(a);i.file("word/document.xml",m);const h=await this.generateCompressedZipBlob(i);return new Blob([h],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchLinkedMoveRevisions(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;const n=await i.async("text"),s="http://schemas.openxmlformats.org/wordprocessingml/2006/main",o=new DOMParser().parseFromString(n,"application/xml"),a=(p,m)=>{const h=o.createElementNS(s,m);for(const g of Array.from(p.attributes))h.setAttributeNS(g.namespaceURI,g.name,g.value);for(;p.firstChild;)h.appendChild(p.firstChild);return p.replaceWith(h),h},l=(p,m,h)=>{const g=o.createElementNS(s,p);return g.setAttributeNS(s,"w:id",m.rangeId),h&&(g.setAttributeNS(s,"w:name",m.name),g.setAttributeNS(s,"w:author",m.author),g.setAttributeNS(s,"w:date",m.date)),g};for(const p of r){const m=p.role==="from"?"w:del":"w:ins",h=p.role==="from"?"w:moveFrom":"w:moveTo",g=new Set(p.wrapperIds.map(String)),w=Array.from(o.getElementsByTagName(m)).filter(y=>g.has(y.getAttribute("w:id")??""));if(w.length!==g.size)throw new Error(`linked move ${p.name}/${p.role}: expected ${g.size} temporary revision wrappers, found ${w.length}`);const u=w.map(y=>a(y,h)),f=u[0],b=u[u.length-1],I=p.role==="from"?"w:moveFromRange":"w:moveToRange";f.parentNode?.insertBefore(l(`${I}Start`,p,!0),f),b.parentNode?.insertBefore(l(`${I}End`,p,!1),b.nextSibling)}t.file("word/document.xml",new XMLSerializer().serializeToString(o));const d=await this.generateCompressedZipBlob(t);return new Blob([d],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchTableRevisions(e,r,t){const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const s=await n.async("text"),o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=new DOMParser().parseFromString(s,"application/xml"),l=a.getElementsByTagName("w:body")[0];if(!l)return e;const d=Array.from(l.getElementsByTagName("w:tbl")),p=(S,E)=>Array.from(S.children).filter(M=>M.tagName===E),m=(S,E)=>{const M=this.getDirectChild(S,E);if(M)return M;const v=a.createElementNS(o,E);return S.insertBefore(v,S.firstChild),v},h=(S,E)=>{const M=new DOMParser().parseFromString(S,"application/xml");if(!(M.getElementsByTagName("parsererror").length>0||M.documentElement?.tagName!==E))return a.importNode(M.documentElement,!0)},g=(S,E)=>{const M=h(E,"w:tblGrid");if(!M)return this.getDirectChild(S,"w:tblGrid");const v=this.getDirectChild(S,"w:tblGrid");if(v)v.replaceWith(M);else{const R=this.getDirectChild(S,"w:tblPr");S.insertBefore(M,R?.nextSibling??S.firstChild)}return M},w=(S,E)=>{const M=h(E,"w:tblPrEx");if(!M)return this.getDirectChild(S,"w:tblPrEx");const v=this.getDirectChild(S,"w:tblPrEx");return v?v.replaceWith(M):S.insertBefore(M,S.firstChild),M},u=(S,E,M)=>{const v=h(M,E);if(!v)return m(S,E);const R=this.getDirectChild(S,E);return R?R.replaceWith(v):S.insertBefore(v,S.firstChild),v},f={"w:tblPr":["w:tblStyle","w:tblpPr","w:tblOverlap","w:bidiVisual","w:tblStyleRowBandSize","w:tblStyleColBandSize","w:tblW","w:jc","w:tblCellSpacing","w:tblInd","w:tblBorders","w:shd","w:tblLayout","w:tblCellMar","w:tblLook","w:tblCaption","w:tblDescription","w:tblPrChange"],"w:trPr":["w:cnfStyle","w:divId","w:gridBefore","w:gridAfter","w:wBefore","w:wAfter","w:cantSplit","w:trHeight","w:tblHeader","w:tblCellSpacing","w:jc","w:hidden","w:ins","w:del","w:trPrChange"],"w:tcPr":["w:cnfStyle","w:tcW","w:gridSpan","w:hMerge","w:vMerge","w:tcBorders","w:shd","w:noWrap","w:tcMar","w:textDirection","w:tcFitText","w:vAlign","w:hideMark","w:headers","w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"]},b=(S,E,M,v)=>{const R=m(S,E),_=h(M,E);if(!_)return R;const L=[],H=Array.from(R.children),U=Array.from(_.children),J=new Set([...H.map(X=>X.tagName),...U.map(X=>X.tagName)]);for(const X of J){const G=v.has(X)?H:U.some(q=>q.tagName===X)?U:H;for(const q of G.filter(Z=>Z.tagName===X))L.push(a.importNode(q,!0))}const Q=new Map(f[E].map((X,G)=>[X,G]));L.sort((X,G)=>(Q.get(X.tagName)??Number.MAX_SAFE_INTEGER)-(Q.get(G.tagName)??Number.MAX_SAFE_INTEGER));const k=a.createElementNS(o,E);for(const X of Array.from(_.attributes))k.setAttributeNS(X.namespaceURI,X.name,X.value);for(const X of L)k.appendChild(X);return R.replaceWith(k),k},I=new Map,y=(S,E)=>{const M=a.createElementNS(o,S),v=I;let R;return E.importedId===void 0&&E.revisionGroup&&(R=v.get(E.revisionGroup),R===void 0&&(R=t(),v.set(E.revisionGroup,R))),M.setAttributeNS(o,"w:id",String(E.importedId!==void 0?E.importedId:R??t())),M.setAttributeNS(o,"w:author",E.author),M.setAttributeNS(o,"w:date",E.date),M},B=(S,E)=>{let M=0;for(const v of p(S,"w:tc")){if(M===E)return v;const R=this.getDirectChild(v,"w:tcPr"),_=R?this.getDirectChild(R,"w:gridSpan")?.getAttribute("w:val"):void 0,L=_?Number(_):1;M+=Number.isFinite(L)&&L>0?L:1}},$=(S,E)=>{const M=er(E);if(!M)return;const v=a.createElementNS(o,"w:tblBorders"),R=[["top","top"],["bottom","bottom"],["left","left"],["right","right"],["insideH","insideH"],["insideV","insideV"]];for(const[_,L]of R){const H=M[_];if(!H)continue;const U=a.createElementNS(o,`w:${L}`);U.setAttributeNS(o,"w:val",H.style),U.setAttributeNS(o,"w:sz",String(Math.max(0,Math.round(H.width*6)))),U.setAttributeNS(o,"w:color",H.color.replace(/^#/,"")),v.appendChild(U)}v.children.length>0&&S.appendChild(v)},W=(S,E,M)=>{for(const v of p(S,E))v.remove();M&&S.appendChild(M)},z=(S,E)=>{const M=er(E);if(!M)return;const v=a.createElementNS(o,S),R=[["top","top"],["bottom","bottom"],["left","left"],["right","right"],...S==="w:tblBorders"?[["insideH","insideH"],["insideV","insideV"]]:[]];for(const[_,L]of R){const H=M[_];if(!H)continue;const U=a.createElementNS(o,`w:${L}`);U.setAttributeNS(o,"w:val",H.style),U.setAttributeNS(o,"w:sz",String(Math.max(0,Math.round(H.width*6)))),U.setAttributeNS(o,"w:color",H.color.replace(/^#/,"")),v.appendChild(U)}return v.children.length>0?v:void 0},D=(S,E)=>{let M;if(typeof E=="number"&&Number.isFinite(E))M={top:E,right:E,bottom:E,left:E};else if(typeof E=="string")try{M=JSON.parse(E)}catch{return}if(!M)return;const v=a.createElementNS(o,S);for(const R of["top","right","bottom","left"]){const _=M[R];if(!Number.isFinite(_))continue;const L=a.createElementNS(o,`w:${R}`);L.setAttributeNS(o,"w:w",String(Math.round(_*15))),L.setAttributeNS(o,"w:type","dxa"),v.appendChild(L)}return v.children.length>0?v:void 0},T=(S,E,M,v,R,_)=>{const L=J=>Object.prototype.hasOwnProperty.call(M??{},J)||Object.prototype.hasOwnProperty.call(v??{},J);if(E==="w:tblPr"){if(L("tableWidth")){const J=M?.tableWidth;let Q;typeof J=="number"&&Number.isFinite(J)&&(Q=a.createElementNS(o,"w:tblW"),Q.setAttributeNS(o,"w:w",String(Math.round(J*15))),Q.setAttributeNS(o,"w:type","dxa")),W(S,"w:tblW",Q)}if(L("align")){const J=M?.align;let Q;(J==="left"||J==="center"||J==="right")&&(Q=a.createElementNS(o,"w:jc"),Q.setAttributeNS(o,"w:val",J)),W(S,"w:jc",Q)}if(L("borders")&&W(S,"w:tblBorders",typeof M?.borders=="string"?z("w:tblBorders",M.borders):void 0),L("borderColor")||L("borderWidth")){let J=this.getDirectChild(S,"w:tblBorders");if(!J){J=a.createElementNS(o,"w:tblBorders");for(const Q of["top","left","bottom","right","insideH","insideV"]){const k=a.createElementNS(o,`w:${Q}`);k.setAttributeNS(o,"w:val","single"),J.appendChild(k)}S.appendChild(J)}for(const Q of Array.from(J.children)){if(L("borderColor")){const k=M?.borderColor;Q.setAttributeNS(o,"w:color",typeof k=="string"&&k?k.replace(/^#/,""):"auto")}if(L("borderWidth")){const k=M?.borderWidth;Q.setAttributeNS(o,"w:sz",typeof k=="number"&&Number.isFinite(k)?String(Math.max(0,Math.round(k*6))):"4")}}}L("cellPadding")&&W(S,"w:tblCellMar",D("w:tblCellMar",M?.cellPadding))}else if(E==="w:tcPr"){if(L("backgroundColor")){const J=M?.backgroundColor;let Q;typeof J=="string"&&J&&(Q=a.createElementNS(o,"w:shd"),Q.setAttributeNS(o,"w:fill",J.replace(/^#/,""))),W(S,"w:shd",Q)}if(L("verticalAlign")){const J=M?.verticalAlign;let Q;(J==="top"||J==="middle"||J==="bottom")&&(Q=a.createElementNS(o,"w:vAlign"),Q.setAttributeNS(o,"w:val",J==="middle"?"center":J)),W(S,"w:vAlign",Q)}L("borders")&&W(S,"w:tcBorders",typeof M?.borders=="string"?z("w:tcBorders",M.borders):void 0),L("padding")&&W(S,"w:tcMar",D("w:tcMar",M?.padding))}if(E==="w:trPr"&&(J=>Object.prototype.hasOwnProperty.call(R??{},J)||Object.prototype.hasOwnProperty.call(_??{},J))("hasHeader")){const J=R?.hasHeader?a.createElementNS(o,"w:tblHeader"):void 0;W(S,"w:tblHeader",J)}const H=new Map(f[E].map((J,Q)=>[J,Q])),U=Array.from(S.children).sort((J,Q)=>(H.get(J.tagName)??Number.MAX_SAFE_INTEGER)-(H.get(Q.tagName)??Number.MAX_SAFE_INTEGER));for(const J of U)S.appendChild(J)};for(const S of r){const E=d[S.tableIndex];if(!E)continue;const M=p(E,"w:tr");S.propertyOverrides?.table&&b(E,"w:tblPr",S.propertyOverrides.table,new Set(["w:tblW","w:jc","w:tblBorders","w:tblCellMar"])),S.propertyOverrides?.grid&&g(E,S.propertyOverrides.grid);for(const v of S.propertyOverrides?.rows??[]){const R=M[v.rowIndex];R&&b(R,"w:trPr",v.xml,new Set(["w:tblHeader"]))}for(const v of S.propertyOverrides?.rowExceptions??[]){const R=M[v.rowIndex];R&&w(R,v.xml)}for(const v of S.propertyOverrides?.cells??[]){const R=M[v.rowIndex],_=R?B(R,v.gridColumn):void 0;_&&b(_,"w:tcPr",v.xml,new Set(["w:tcW","w:gridSpan","w:vMerge","w:tcBorders","w:shd","w:tcMar","w:vAlign"]))}for(const v of S.rowProperties){const R=M[v.rowIndex];R&&(v.currentXml?u(R,"w:trPr",v.currentXml):T(m(R,"w:trPr"),"w:trPr",v.currentAttributes,v.priorAttributes,v.currentTableAttributes,v.priorTableAttributes))}for(const v of S.rowExceptionProperties){const R=M[v.rowIndex];R&&w(R,v.currentXml)}for(const v of S.cellProperties){const R=M[v.rowIndex],_=R?B(R,v.gridColumn):void 0;_&&(v.currentXml?u(_,"w:tcPr",v.currentXml):T(m(_,"w:tcPr"),"w:tcPr",v.currentAttributes,v.priorAttributes))}for(const v of S.rows){const R=M[v.rowIndex];R&&m(R,"w:trPr").appendChild(y(v.kind==="insert"?"w:ins":"w:del",v))}for(const v of S.cells){const R=M[v.rowIndex],_=R?B(R,v.gridColumn):void 0;_&&m(_,"w:tcPr").appendChild(y(v.kind==="insert"?"w:cellIns":"w:cellDel",v))}for(const v of S.merges){const R=M[v.rowIndex],_=R?B(R,v.gridColumn):void 0;if(!_)continue;const L=y("w:cellMerge",v);v.vMerge&&L.setAttributeNS(o,"w:vMerge",v.vMerge),v.vMergeOrig&&L.setAttributeNS(o,"w:vMergeOrig",v.vMergeOrig),m(_,"w:tcPr").appendChild(L)}if(S.tableGrid){const v=g(E,S.tableGrid.currentXml);if(v){const R=y("w:tblGridChange",S.tableGrid),_=h(S.tableGrid.priorXml,"w:tblGrid");_&&R.appendChild(_),v.appendChild(R)}}for(const v of S.rowProperties){const R=M[v.rowIndex];if(!R)continue;const _=y("w:trPrChange",v),L=m(R,"w:trPr"),H=v.priorXml?h(v.priorXml,"w:trPr"):L.cloneNode(!0);if(H){if(!v.priorXml){for(const U of["w:ins","w:del","w:trPrChange"])for(const J of p(H,U))J.remove();T(H,"w:trPr",v.priorAttributes,v.currentAttributes,v.priorTableAttributes,v.currentTableAttributes)}_.appendChild(H)}L.appendChild(_)}for(const v of S.rowExceptionProperties){const R=M[v.rowIndex];if(!R)continue;const _=this.getDirectChild(R,"w:tblPrEx")??w(R,v.currentXml);if(!_)continue;const L=y("w:tblPrExChange",v),H=h(v.priorXml,"w:tblPrEx");H&&L.appendChild(H),_.appendChild(L)}for(const v of S.cellProperties){const R=M[v.rowIndex],_=R?B(R,v.gridColumn):void 0;if(!_)continue;const L=y("w:tcPrChange",v),H=m(_,"w:tcPr"),U=v.priorXml?h(v.priorXml,"w:tcPr"):H.cloneNode(!0);if(U){if(!v.priorXml){for(const J of["w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"])for(const Q of p(U,J))Q.remove();T(U,"w:tcPr",v.priorAttributes,v.currentAttributes)}L.appendChild(U)}H.appendChild(L)}if(S.tableProperties){const v=S.tableProperties.currentXml?u(E,"w:tblPr",S.tableProperties.currentXml):m(E,"w:tblPr");S.tableProperties.currentXml||T(v,"w:tblPr",S.tableProperties.currentAttributes,S.tableProperties.priorAttributes);const R=y("w:tblPrChange",S.tableProperties);let _;S.tableProperties.priorXml&&(_=h(S.tableProperties.priorXml,"w:tblPr")),_||(_=v.cloneNode(!0),T(_,"w:tblPr",S.tableProperties.priorAttributes,S.tableProperties.currentAttributes),S.tableProperties.priorBorders&&$(_,S.tableProperties.priorBorders)),R.appendChild(_),v.appendChild(R)}}i.file("word/document.xml",new XMLSerializer().serializeToString(a));const F=await this.generateCompressedZipBlob(i);return new Blob([F],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static inferDocumentFontFamily(e){if(!e?.children)return;const r=new Map;let t=0;const i=(o,a)=>{for(const l of o){if(l.type!=="text")continue;const d=l.text.length;if(d===0)continue;t+=d;const p=l.marks?.fontFamily??a;p&&r.set(p,(r.get(p)??0)+d)}};for(const o of e.children)if(o.type==="paragraph"){const a=o;i(o.children,a.fontFamily)}else if(o.type==="list")for(const a of o.children)i(a.children);if(t===0)return;let n,s=0;for(const[o,a]of r)a>s&&(n=o,s=a);return n&&s*2>t?n:void 0}static codeBlockStyleId(e){const r=(e??"").replace(/[^A-Za-z0-9]/g,"");return r?`${this.CODE_BLOCK_STYLE_ID}_${r}`:this.CODE_BLOCK_STYLE_ID}static buildExportHeadingDefaults(){const e=[["heading1",Ae.h1],["heading2",Ae.h2],["heading3",Ae.h3],["heading4",Ae.h4],["heading5",Ae.h5],["heading6",Ae.h6]];return Object.fromEntries(e.map(([r,t])=>[r,{run:{size:this.pxToDocxHalfPoints(t)}}]))}static buildExportParagraphStyles(e){const r=[],t=new Set,i=n=>{for(const s of n)if(s.type==="code"&&!s.renderDiagram)t.add(this.codeBlockStyleId(s.language));else if(s.type==="container"||s.type==="footnote"||s.type==="table-cell")i(s.children);else if(s.type==="table")for(const o of s.children)i(o.children)};if(i(e.children),e.notes&&i(e.notes),t.size>0){r.push({id:this.CODE_BLOCK_STYLE_ID,name:"Code Block",basedOn:"Normal",run:{font:"Courier New",size:this.pxToDocxHalfPoints(Ae.code)}});for(const n of t)n!==this.CODE_BLOCK_STYLE_ID&&r.push({id:n,name:`Code Block (${n.slice(this.CODE_BLOCK_STYLE_ID.length+1)})`,basedOn:this.CODE_BLOCK_STYLE_ID})}return r}static buildExportCharacterStyles(){return[{id:this.CODE_INLINE_STYLE_ID,name:"Code Inline",run:{font:"Courier New",highlight:"lightGray"}}]}static toDocxFormat(e){const r=[],t=this.inferDocumentFontFamily(e),i=this.resolveIndentStepPx(e),n=this.buildOrderedNumberingExportPlan(e).byListId;this.exportOrderedPlan=n,this.exportLinkedMoveSides=this.collectLinkedMoveSides(e.children),this.exportLinkedMoveBlockIds=this.collectLinkedMoveBlockIds(e.children,this.exportLinkedMoveSides);for(const s of e.children)s.type==="paragraph"?r.push(this.paragraphToDocx(s,t,i)):s.type==="list"?r.push(...this.listToDocxParagraphs(s,t,n)):s.type==="page-break"?r.push({type:"pagebreak"}):s.type==="toc"&&r.push(...this.tocBlockToDocxParagraphs(s,e));return r}static tocBlockToDocxParagraphs(e,r,t){const i=_i(e),n=Xi(r,Wi(e)),s=Te(r.pageLayout),o=Vt(s),a=Math.max(o.pageWidth-s.marginLeftPx-s.marginRightPx,96),l=e.direction==="rtl",d=this.docxAlignmentForExport({type:"paragraph",id:e.id,children:[],direction:e.direction??"ltr",align:e.align??(l?"right":"left")}),p={bidirectional:l,alignment:d},m=JSON.stringify([{pos:Math.round(a),align:"right",leader:"dot"}]),h=e.fontFamily??this.inferDocumentFontFamily(r),g=this.toDocxHex(e.color),w={...h?{font:h}:{},...e.fontSize?{size:Math.round(e.fontSize*this.DOCX_HALF_POINTS_PER_PX)}:{},...g?{color:g}:{}};if(n.length===0)return[{type:"paragraph",...p,children:[{text:" ",fieldInstr:i,...w}]}];const u=24;return n.map(f=>({type:"paragraph",...p,children:[{text:`${f.text} `,fieldInstr:i,...w,...l?{rightToLeft:!0}:{}},...t?.has(f.blockId)?[{text:String(t.get(f.blockId)),fieldInstr:i,...w,rightToLeft:!1}]:[]],tabStopsJson:m,...f.level>1?{indent:{left:this.pxToTwips((f.level-1)*u)}}:{}}))}static toDocxFormatWithTables(e,r,t,i){const n=[],s=this.inferDocumentFontFamily(e);this.exportDefaultRunSizeHalfPoints=this.inferDefaultRunSizeHalfPoints(e);const o=r||zi,a=this.resolveIndentStepPx(e),l=this.buildOrderedNumberingExportPlan(e).byListId;this.exportOrderedPlan=l,this.exportLinkedMoveSides=this.collectLinkedMoveSides(e.children),this.exportLinkedMoveBlockIds=this.collectLinkedMoveBlockIds(e.children,this.exportLinkedMoveSides);const d=this.styleExportContext(e);for(const h of e.children){const g=n.length;if(h.type==="paragraph")n.push(this.styledParagraphToDocxWithMath(h,s,a,d));else if(h.type==="list")n.push(...this.listToDocxParagraphsWithMath(h,s,l));else if(h.type==="table")n.push(this.tableToDocxWithMath(h,s,a,d));else if(h.type==="code"){const w=this.legacyLatexCodeBlockAsMath(h);n.push(w?this.mathBlockToDocx(w):this.codeBlockToDocx(h,o))}else if(h.type==="math")n.push(this.mathBlockToDocx(h));else if(h.type==="image")n.push(this.imageBlockToDocx(h));else if(h.type==="page-break")n.push({type:"pagebreak"});else if(h.type==="section-break"){const w=h.diffState==="delete"&&h.suggestionId?/^docxrev-(\d+)$/.exec(h.suggestionId):null;n.push({type:"sectionbreak",...h.layout?{layout:h.layout}:{},...h.breakType?{breakType:h.breakType}:{},...h.diffState==="delete"?{pendingDeletion:{author:h.suggestionAuthorName??"Anonymous",date:new Date(h.suggestionCreatedAt??Date.now()).toISOString(),...w?{importedId:Number(w[1])}:{}}}:{}})}else h.type==="toc"?n.push(...this.tocBlockToDocxParagraphs(h,e,t)):h.type==="docx-raw"&&(nr(h.xml)?n.push(this.styledParagraphToDocxWithMath({type:"paragraph",id:h.id,children:[{type:"text",text:""}]},s,a,d)):n.push({type:"docxraw",sourceBlockId:h.id,xml:h.xml,origin:h.origin,emitsParagraph:h.origin==="run"}));i?.push({blockId:h.id,start:g,count:n.length-g})}const p=this.pxToTwips(Te(e.pageLayout).blockSpacingPx),m=h=>{for(const g of h.rows)for(const w of g.cells){for(const u of w.paragraphs)u.spacingAfterTwips??(u.spacingAfterTwips=p),u.spacingBeforeTwips??(u.spacingBeforeTwips=0);for(const u of w.blocks??[])u.type==="paragraph"?(u.spacingAfterTwips??(u.spacingAfterTwips=p),u.spacingBeforeTwips??(u.spacingBeforeTwips=0)):m(u)}};for(const h of n)h.type==="paragraph"?h.styleProvidesSpacing||(h.spacingAfterTwips??(h.spacingAfterTwips=p),h.spacingBeforeTwips??(h.spacingBeforeTwips=0)):h.type==="table"&&m(h);return n}static applyExportParagraphSpacing(e,r){typeof r.spaceBefore=="number"&&(e.spacingBeforeTwips=this.pxToTwips(r.spaceBefore)),typeof r.spaceAfter=="number"&&(e.spacingAfterTwips=this.pxToTwips(r.spaceAfter)),r.contextualSpacing&&(e.contextualSpacing=!0)}static latexToOmml(e,r){const t=Nr();if(!t)return"";try{const i=t.renderToString(e,{output:"mathml",displayMode:r,throwOnError:!1});let n=vn(i);return r&&(n=n.replace(zr,'<m:oMathPara xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><m:oMath>'),n=n.replace(/<\/m:oMath>$/,"</m:oMath></m:oMathPara>")),n}catch{return""}}static legacyLatexCodeBlockAsMath(e){const r=e.language?.trim().toLowerCase();return r!=="latex"&&r!=="latex-inline"||e.renderDiagram===!1?null:{type:"math",id:e.id,content:e.content||"",displayMode:r==="latex-inline"?"inline":"block",align:"center"}}static mathBlockToDocx(e){const r=e.displayMode!=="inline",t=e.align||"center",i=this.latexToOmml(e.content,r);return{type:"mathblock",content:e.content,displayMode:r,alignment:t,omml:i||void 0}}static imageBlockToDocx(e){return{type:"image",src:e.src,width:e.width,height:e.height,alt:e.alt,align:e.align,originalFormat:e.originalFormat,originalDataUrl:e.originalDataUrl,anchorXml:e.anchorXml}}static buildParagraphIndent(e,r){const t=e.leftIndent===0?0:Hi(e.leftIndent),i=e.firstLineIndent===0?0:ji(e.firstLineIndent),n={};return t!==void 0&&(n.left=this.pxToTwips(Yt(t,r))),i!==void 0&&(i<0?n.hanging=this.pxToTwips(Yt(-i,r)):n.firstLine=this.pxToTwips(Yt(i,r))),Object.keys(n).length>0?n:void 0}static tableToDocx(e,r){const t=qe(e);return{type:"table",rows:e.children.map((i,n)=>{const s=e.hasHeader&&n===0;return{cells:i.children.map(o=>{const a=[],l=[];for(const p of o.children)if(p.type==="paragraph"){const m=this.paragraphToDocx(p,r);a.push(m),l.push(m)}else if(p.type==="list"){const m=this.listToDocxParagraphs(p,r,this.exportOrderedPlan);a.push(...m),l.push(...m)}else p.type==="table"&&l.push(this.tableToDocx(p,r));const d=t.byId.get(o.id);return{paragraphs:a,...l.some(p=>p.type==="table")?{blocks:l}:{},backgroundColor:o.backgroundColor,verticalAlign:o.verticalAlign,borders:o.borders,padding:o.padding,colSpan:d&&d.colSpan>1?d.colSpan:void 0,rowSpan:d&&d.rowSpan>1?d.rowSpan:void 0,gridColumn:d?.col,...o.oxmlTcPr?{oxmlTcPr:o.oxmlTcPr}:{}}}),isHeader:s,...i.oxmlAttrs?{oxmlAttrs:i.oxmlAttrs}:{},...i.oxmlTrPr?{oxmlTrPr:i.oxmlTrPr}:{}}}),columnWidths:e.columnWidths||[],hasHeader:e.hasHeader,tableWidth:e.tableWidth,align:e.align,cellPadding:e.cellPadding,borders:e.borders,borderWidth:e.borderWidth,borderColor:e.borderColor,...e.oxmlTblPr?{oxmlTblPr:e.oxmlTblPr}:{}}}static codeBlockToDocx(e,r){const t=e.content||"",i=e.language||"",n=Gi(i);if(n&&e.renderDiagram!==!1&&n){const a=Ji({protocol:n,source:t,theme:Ui(),maxWidth:900});return{type:"codeblock",content:"",language:i,runs:[],backgroundColor:r.background,renderDiagram:!0,diagramPngDataUrl:a?.dataUrl,diagramWidth:a?.width,diagramHeight:a?.height}}const s=i?Zi(t,i,r):null,o=[];if(s&&s.length>0)for(const a of s){const l=a.text.split(`
9
- `);for(let d=0;d<l.length;d++)l[d]&&o.push({text:l[d],font:"Courier New",color:this.normalizeColor(a.color)}),d<l.length-1&&o.push({text:`
10
- `,font:"Courier New",break:!0})}else{const a=t.split(`
11
- `);for(let l=0;l<a.length;l++)a[l]&&o.push({text:a[l],font:"Courier New",color:this.normalizeColor(r.default)}),l<a.length-1&&o.push({text:`
12
- `,font:"Courier New",break:!0})}return{type:"codeblock",content:t,language:i,styleId:this.codeBlockStyleId(i),runs:o,backgroundColor:r.background,renderDiagram:!1}}static createStyleMarksResolver(e){const r=e.stylesXml;if(!r)return;let t;const i=new Map;return n=>{if(!n)return;const s=i.get(n);if(s)return s;t??(t=this.parseStylesXml(r));const o=this.resolveRunMarks(void 0,n,{styles:t});return i.set(n,o),o}}static styleExportContext(e){return{stylesheet:e.stylesheet,styleMarksFor:this.createStyleMarksResolver(e)}}static styledParagraphToDocxWithMath(e,r,t,i){const n=e.styleId?Ki(i.stylesheet,e.styleId)?.paragraphAttrs:void 0,s=this.stripStyleProvidedParagraphAttrs(e,n),o=i.styleMarksFor?.(e.styleId),a=this.paragraphToDocxWithMath(s,o?.fontFamily?void 0:r,t,o);return s.spaceAfter===void 0&&e.spaceAfter!==void 0&&(a.styleProvidesSpacing=!0),a}static stripStyleProvidedParagraphAttrs(e,r){if(!r)return e;const t={...e},i=(n,s)=>n!==void 0&&s!==void 0&&Math.abs(n-s)<.011;return t.align!==void 0&&t.align===r.align&&delete t.align,i(t.lineSpacing,r.lineSpacing)&&delete t.lineSpacing,i(t.spaceBefore,r.spaceBefore)&&i(t.spaceAfter,r.spaceAfter)&&(t.contextualSpacing??!1)===(r.contextualSpacing??!1)&&(delete t.spaceBefore,delete t.spaceAfter,delete t.contextualSpacing),t.keepNext===!0&&r.keepNext===!0&&delete t.keepNext,t.keepLines===!0&&r.keepLines===!0&&delete t.keepLines,t.widowControl===!1&&r.widowControl===!1&&delete t.widowControl,i(t.leftIndent,r.leftIndent)&&delete t.leftIndent,i(t.firstLineIndent,r.firstLineIndent)&&delete t.firstLineIndent,t.tabStops!==void 0&&t.tabStops===r.tabStops&&delete t.tabStops,t.borders!==void 0&&t.borders===r.borders&&delete t.borders,t.shading!==void 0&&t.shading===r.shading&&delete t.shading,t}static stripStyleProvidedMarks(e,r){if(!e||!r)return e;const t=n=>String(n).split(",")[0].replaceAll('"',"").replaceAll("'","").trim().toLowerCase(),i={...e};for(const n of Object.keys(r))i[n]!==void 0&&(n==="fontFamily"?t(i[n])===t(r[n]):i[n]===r[n])&&delete i[n];return i}static paragraphToDocxWithMath(e,r,t=this.resolveIndentStepPx(),i){const n=this.exportDefaultRunSizeHalfPoints;(e.heading||i?.fontSize)&&(this.exportDefaultRunSizeHalfPoints=void 0);try{return this.paragraphToDocxWithMathInner(e,r,t,i)}finally{this.exportDefaultRunSizeHalfPoints=n}}static paragraphToDocxWithMathInner(e,r,t=this.resolveIndentStepPx(),i){const n={type:"paragraph",sourceBlockId:e.id,children:[]};e.styleId&&(n.styleId=e.styleId),e.heading&&(n.heading=`HEADING_${e.heading}`);{const a=this.docxAlignmentForExport(e);a&&(n.alignment=a)}e.lineSpacing!==void 0&&(n.lineSpacing=e.lineSpacing),this.applyExportParagraphSpacing(n,e),e.keepNext&&(n.keepNext=!0),e.keepLines&&(n.keepLines=!0),e.widowControl===!1&&(n.widowControl=!1),e.borders&&(n.bordersJson=e.borders),e.shading&&(n.shadingFill=e.shading),e.tabStops&&(n.tabStopsJson=e.tabStops),e.oxmlAttrs&&(n.oxmlAttrs=e.oxmlAttrs),e.oxmlPPr&&(n.oxmlPPr=e.oxmlPPr);const s=this.buildParagraphIndent(e,t);s&&(n.indent=s);const o=e;if(o.fontFamily&&(n.style=o.fontFamily),this.applyParagraphMarkRevisionInfo(n,e),this.applyParagraphPropertyChangeInfo(n,e,t),e.children.length===0)return this.applyWholeBlockRevisionInfo(n,e),this.applyBidiExportFlags(n,e),n;for(const a of e.children)if(a.type==="text"){const l=i&&e.styleId?{...a,marks:this.stripStyleProvidedMarks(a.marks,i)}:a,d=this.textNodeToDocxWithLatex(l,r);n.children.push(...d)}return this.applyWholeBlockRevisionInfo(n,e),this.applyBidiExportFlags(n,e),n}static docxAlignmentForExport(e){if(!e.align)return;const r=e.direction==="rtl"||e.direction===void 0&&Bt(this.paragraphNodeText(e))==="rtl",t=r&&e.align==="left"?"right":r&&e.align==="right"?"left":e.align;return{left:"LEFT",center:"CENTER",right:"RIGHT",justify:"JUSTIFIED"}[t]}static applyBidiExportFlags(e,r){const t=this.paragraphNodeText(r);if(r.direction==="ltr"){Bt(t)==="rtl"&&(e.bidirectional=!1);return}if(r.direction==="rtl"||r.direction===void 0&&Bt(t)==="rtl"){e.bidirectional=!0;for(const i of e.children)i.text&&qi(i.text)&&(i.rightToLeft=!0)}}static listToDocxParagraphsWithMath(e,r,t){const i=[],n={level0:(e.startNumber??1)-1,level1:0,level2:0};for(const s of e.children){if(s.type!=="list-item")continue;const o=this.getClampedIndentLevel(s.indentLevel),a={type:"paragraph",sourceBlockId:s.id,children:[],lineSpacing:s.lineSpacing??e.lineSpacing,...typeof(s.spaceBefore??e.spaceBefore)=="number"?{spacingBeforeTwips:this.pxToTwips(s.spaceBefore??e.spaceBefore)}:{},...typeof(s.spaceAfter??e.spaceAfter)=="number"?{spacingAfterTwips:this.pxToTwips(s.spaceAfter??e.spaceAfter)}:{},...e.contextualSpacing?{contextualSpacing:!0}:{},list:{variant:e.variant,level:o,label:"",checked:e.variant==="todo"?!!s.checked:void 0,reference:t?.get(e.id)?.reference??this.getDocxListReference(e),instance:t?.get(e.id)?.instance??0}},l=this.getListLabel(e,s,n);if(a.list&&(a.list.label=l),e.variant==="todo"&&a.children.push({text:`${l} `}),s.children.length>0){for(const d of s.children)if(d.type==="text"){const p=this.textNodeToDocxWithLatex(d,r);a.children.push(...p)}}this.applyWholeBlockRevisionInfo(a,s.structuralSuggestionKind?s:e),i.push(a)}return i}static tableToDocxWithMath(e,r,t=this.resolveIndentStepPx(),i){const n=qe(e),s=[];for(let o=0;o<e.children.length;o++){const a=e.children[o],l=e.hasHeader&&o===0,d=[];for(const p of a.children){const m=[],h=[];for(const w of p.children)if(w.type==="paragraph"){const u=i?this.styledParagraphToDocxWithMath(w,r,t,i):this.paragraphToDocxWithMath(w,r,t);m.push(u),h.push(u)}else if(w.type==="list"){const u=this.listToDocxParagraphsWithMath(w,r,this.exportOrderedPlan);m.push(...u),h.push(...u)}else w.type==="table"&&h.push(this.tableToDocxWithMath(w,r,t,i));const g=n.byId.get(p.id);d.push({paragraphs:m,...h.some(w=>w.type==="table")?{blocks:h}:{},backgroundColor:p.backgroundColor,verticalAlign:p.verticalAlign,borders:p.borders,padding:p.padding,colSpan:g&&g.colSpan>1?g.colSpan:void 0,rowSpan:g&&g.rowSpan>1?g.rowSpan:void 0,gridColumn:g?.col,...p.oxmlTcPr?{oxmlTcPr:p.oxmlTcPr}:{}})}s.push({cells:d,isHeader:l,...a.oxmlAttrs?{oxmlAttrs:a.oxmlAttrs}:{},...a.oxmlTrPr?{oxmlTrPr:a.oxmlTrPr}:{}})}return{type:"table",rows:s,columnWidths:e.columnWidths||[],hasHeader:e.hasHeader,tableWidth:e.tableWidth,align:e.align,cellPadding:e.cellPadding,borders:e.borders,borderWidth:e.borderWidth,borderColor:e.borderColor,...e.oxmlTblPr?{oxmlTblPr:e.oxmlTblPr}:{}}}static applyParagraphMarkRevisionInfo(e,r){if(r.structuralSuggestionKind!=="split"&&r.structuralSuggestionKind!=="merge"||r.structuralSuggestionRole!=="before")return;let t="Anonymous",i=new Date().toISOString(),n;try{const o=JSON.parse(r.structuralSuggestionRecord??"{}");typeof o.agentName=="string"&&o.agentName.trim()?t=o.agentName.trim():o.authorType==="ai"&&(t="Revise Agent"),typeof o.createdAt=="number"&&(i=new Date(o.createdAt).toISOString())}catch{}const s=typeof r.structuralSuggestionId=="string"?/^docxrev-(\d+)$/.exec(r.structuralSuggestionId):null;s&&(n=Number(s[1])),e.paragraphMarkRevision={kind:r.structuralSuggestionKind,author:t,date:i,...n!==void 0?{importedId:n}:{}}}static applyWholeBlockRevisionInfo(e,r){if(r.structuralSuggestionKind!=="insert"&&r.structuralSuggestionKind!=="delete")return;const t=this.linkedMoveSideFor(r.structuralSuggestionId,r.structuralSuggestionKind);if(t&&!this.isInLinkedMoveRange(r,t.move.role)){const a={kind:r.structuralSuggestionKind,author:t.author,date:t.date};e.paragraphMarkRevision=a;for(const l of e.children)l.text&&(l.revision??(l.revision=a));return}if(t){e.paragraphMarkRevision={kind:t.move.role==="from"?"moveFrom":"moveTo",author:t.author,date:t.date};const a=/^\d+$/.test(t.move.wrapperId)?Number(t.move.wrapperId):void 0;e.children.length===0&&e.children.push({text:""});for(const l of e.children)l.revision??(l.revision={kind:r.structuralSuggestionKind,author:t.author,date:t.date,...a!==void 0?{importedId:a}:{},move:t.move});return}let i="Anonymous",n=new Date().toISOString();try{const a=JSON.parse(r.structuralSuggestionRecord??"{}");typeof a.agentName=="string"&&a.agentName.trim()?i=a.agentName.trim():a.authorType==="ai"&&(i=It),typeof a.createdAt=="number"&&(n=new Date(a.createdAt).toISOString())}catch{}const s=typeof r.structuralSuggestionId=="string"?/^docxrev-(\d+)$/.exec(r.structuralSuggestionId):null,o={kind:r.structuralSuggestionKind,author:i,date:n,...s?{importedId:Number(s[1])}:{}};e.paragraphMarkRevision=o;for(const a of e.children)a.revision??(a.revision=o)}static applyParagraphPropertyChangeInfo(e,r,t){if(r.structuralSuggestionKind!=="change")return;let i;try{i=JSON.parse(r.structuralSuggestionRecord??"{}")}catch{return}if(i.type!=="block-change"||i.beforeBlock?.type!=="paragraph")return;const n=i.beforeBlock;let s="Anonymous";typeof i.agentName=="string"&&i.agentName.trim()?s=i.agentName.trim():i.authorType==="ai"&&(s=It);const o=typeof i.createdAt=="number"?new Date(i.createdAt).toISOString():new Date().toISOString(),a=typeof r.structuralSuggestionId=="string"?/^docxrev-(\d+)$/.exec(r.structuralSuggestionId):null,l=this.buildParagraphIndent(n,t);e.paragraphPropertiesChange={author:s,date:o,...a?{importedId:Number(a[1])}:{},prior:{...n.align?{align:n.align}:{},...l?.left!==void 0?{leftIndentTwips:l.left}:{},...l?.firstLine!==void 0?{firstLineIndentTwips:l.firstLine}:{},...n.lineSpacing!==void 0?{lineSpacing:n.lineSpacing}:{},...n.keepNext?{keepNext:!0}:{},...n.keepLines?{keepLines:!0}:{},...n.widowControl===!1?{widowControl:!1}:{},...n.direction?{direction:n.direction}:{},...n.borders?{bordersJson:n.borders}:{},...n.shading?{shadingFill:n.shading}:{},...n.styleId?{styleId:n.styleId}:n.heading?{styleId:`Heading${n.heading}`}:{}}}}static collectTableRevisionPatches(e){const r=[];let t=0;const i=[],n=o=>{for(const a of o)if(a.type==="table"){i.push(a);for(const l of a.children)for(const d of l.children)n(d.children)}else a.type==="container"&&n(a.children)};n(e.children);const s=this.collectLinkedMoveSides(e.children);for(const o of i){const a=t++,l=o.diffState==="insert"||o.diffState==="delete"?o.diffState:void 0,d=l&&typeof o.suggestionId=="string"?s.get(o.suggestionId)?.[l==="delete"?"from":"to"]:void 0;if(l&&d){r.push({tableIndex:a,rows:o.children.map((y,B)=>({rowIndex:B,kind:l,author:d.author,date:d.date,revisionGroup:`${o.suggestionId}\0${l}`})),cells:[],merges:[],rowProperties:[],rowExceptionProperties:[],cellProperties:[]});continue}let p=[];if(o.structuralSuggestionRecords)try{const y=JSON.parse(o.structuralSuggestionRecords);Array.isArray(y)&&(p=y.filter(B=>B?.type==="table-change"))}catch{}let m;if(o.docxTablePropertyOverrides)try{const y=JSON.parse(o.docxTablePropertyOverrides);y?.version===1&&(m=y)}catch{}if(p.length>0||m){const y={tableIndex:a,rows:[],cells:[],merges:[],rowProperties:[],rowExceptionProperties:[],cellProperties:[]},B=qe(o),$=new Map(o.children.map((D,T)=>[D.id,T])),W=(D,T)=>{const F=T.author?.trim()||D.agentName?.trim()||(D.authorType==="ai"?It:"Anonymous"),S=typeof T.createdAt=="number"?T.createdAt:typeof D.createdAt=="number"?D.createdAt:Date.now(),E=T.revisionId??/^docxrev-(\d+)$/.exec(D.id)?.[1],M=typeof E=="string"&&/^\d+$/.test(E)?Number(E):void 0;return{author:F,date:new Date(S).toISOString(),revisionGroup:D.id,...M!==void 0?{importedId:M}:{}}},z=D=>{const T=D.map(S=>Number.isFinite(S)&&S>0?S:1),F=T.reduce((S,E)=>S+E,0)||1;return`<w:tblGrid xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${T.map(S=>`<w:gridCol w:w="${Math.max(1,Math.round(S/F*1e4))}"/>`).join("")}</w:tblGrid>`};if(m){const D={...m.table?{table:m.table}:{},...m.grid&&JSON.stringify(m.grid.columnWidths)===JSON.stringify(o.columnWidths)?{grid:m.grid.xml}:{},rows:[],rowExceptions:[],cells:[]};for(const[T,F]of Object.entries(m.rows??{})){const S=$.get(T);S!==void 0&&D.rows.push({rowIndex:S,xml:F})}for(const[T,F]of Object.entries(m.rowExceptions??{})){const S=$.get(T);S!==void 0&&D.rowExceptions.push({rowIndex:S,xml:F})}for(const[T,F]of Object.entries(m.cells??{})){const S=B.byId.get(T);S&&D.cells.push({rowIndex:S.row,gridColumn:S.col,xml:F})}y.propertyOverrides=D}for(const D of p){for(const T of D.tableRevision.markers){const F=W(D,T);if(T.kind==="row-insert"||T.kind==="row-delete"){const v=T.rowId?$.get(T.rowId):T.rowIndex;v!==void 0&&y.rows.push({rowIndex:v,kind:T.kind==="row-insert"?"insert":"delete",...F});continue}if(T.kind==="cell-insert"||T.kind==="cell-delete"){const v=T.cellId?B.byId.get(T.cellId):void 0,R=v?.row??T.rowIndex,_=v?.col??T.gridColumn;R!==void 0&&_!==void 0&&y.cells.push({rowIndex:R,gridColumn:_,kind:T.kind==="cell-insert"?"insert":"delete",...F});continue}if(T.kind==="cell-merge"){const v=T.rowId?$.get(T.rowId):T.rowIndex;v!==void 0&&T.gridColumn!==void 0&&y.merges.push({rowIndex:v,gridColumn:T.gridColumn,...F,...T.vMerge?{vMerge:T.vMerge}:{},...T.vMergeOrig?{vMergeOrig:T.vMergeOrig}:{}});continue}if(T.kind==="table-grid"&&T.currentPropertiesXml&&T.priorPropertiesXml){y.tableGrid={...F,currentXml:T.currentPropertiesXml,priorXml:T.priorPropertiesXml};continue}const S=D.tableRevision.operations.find(v=>v.kind==="properties"&&(T.kind==="table-properties"&&v.target==="table"||T.kind==="row-properties"&&v.target==="row"&&(!T.rowId||v.rowId===T.rowId)||T.kind==="row-exception-properties"&&v.target==="row-exception"&&(!T.rowId||v.rowId===T.rowId)||T.kind==="cell-properties"&&v.target==="cell"&&(!T.cellId||v.cellId===T.cellId))),E=T.currentPropertiesXml??(S?.kind==="properties"?S.currentPropertiesXml:void 0),M=T.priorPropertiesXml??(S?.kind==="properties"?S.priorPropertiesXml:void 0);if(T.kind==="table-properties")y.tableProperties={...F,...E?{currentXml:E}:{},...M?{priorXml:M}:{},...S?.kind==="properties"?{currentAttributes:S.currentAttributes,priorAttributes:S.priorAttributes}:{}};else if(T.kind==="row-properties"||T.kind==="row-exception-properties"){const v=T.rowId?$.get(T.rowId):T.rowIndex;v!==void 0&&(T.kind==="row-properties"?y.rowProperties:y.rowExceptionProperties).push({rowIndex:v,...F,currentXml:E??"",priorXml:M??"",...S?.kind==="properties"?{currentAttributes:S.currentAttributes,priorAttributes:S.priorAttributes,currentTableAttributes:S.currentTableAttributes,priorTableAttributes:S.priorTableAttributes}:{}})}else if(T.kind==="cell-properties"){const v=T.cellId?B.byId.get(T.cellId):void 0,R=v?.row??T.rowIndex,_=v?.col??T.gridColumn;R!==void 0&&_!==void 0&&y.cellProperties.push({rowIndex:R,gridColumn:_,...F,...E?{currentXml:E}:{},...M?{priorXml:M}:{},...S?.kind==="properties"?{currentAttributes:S.currentAttributes,priorAttributes:S.priorAttributes}:{}})}}if(!y.tableGrid){const T=D.tableRevision.operations.find(F=>F.kind==="grid");T?.kind==="grid"&&(y.tableGrid={...W(D,{}),currentXml:T.currentGridXml||z(T.currentColumnWidths),priorXml:T.priorGridXml||z(T.priorColumnWidths)})}}(y.rows.length||y.cells.length||y.merges.length||y.tableGrid||y.rowProperties.length||y.rowExceptionProperties.length||y.cellProperties.length||y.tableProperties||y.propertyOverrides)&&r.push(y);continue}if(o.structuralSuggestionKind!=="change"||!o.structuralSuggestionRecord)continue;let h;try{h=JSON.parse(o.structuralSuggestionRecord)}catch{continue}if(h.type!=="block-change"||h.beforeBlock?.type!=="table"||h.acceptedBlock?.type!=="table")continue;const g=/^docxrev-(\d+)$/.exec(o.structuralSuggestionId??"")?.[1],w=y=>{const B=typeof y?.author=="string"&&y.author.trim()?y.author.trim():typeof h.agentName=="string"&&h.agentName.trim()?h.agentName.trim():h.authorType==="ai"?It:"Anonymous",$=typeof y?.createdAt=="number"&&Number.isFinite(y.createdAt)?y.createdAt:typeof h.createdAt=="number"&&Number.isFinite(h.createdAt)?h.createdAt:Date.now(),W=y?.revisionId??g,z=typeof W=="string"&&/^\d+$/.test(W)?Number(W):void 0;return{author:B,date:new Date($).toISOString(),...z!==void 0?{importedId:z}:{}}},u={tableIndex:a,rows:[],cells:[],merges:[],rowProperties:[],rowExceptionProperties:[],cellProperties:[]},f=h.docxTableRevisions,b=qe(o),I=new Map(o.children.map((y,B)=>[y.id,B]));if(f?.version===1){for(const y of f.rows??[]){const B=I.get(y.rowId);B!==void 0&&u.rows.push({rowIndex:B,kind:y.kind,...w(y)})}for(const y of f.cells??[]){const B=b.byId.get(y.cellId);B&&u.cells.push({rowIndex:B.row,gridColumn:B.col,kind:y.kind,...w(y)})}for(const y of f.merges??[]){const B=I.get(y.rowId);B!==void 0&&u.merges.push({rowIndex:B,gridColumn:y.gridColumn,...w(y),...y.vMerge?{vMerge:y.vMerge}:{},...y.vMergeOrig?{vMergeOrig:y.vMergeOrig}:{}})}f.tableProperties&&(u.tableProperties={...w(f.tableProperties),...f.tableProperties.priorXml?{priorXml:f.tableProperties.priorXml}:{},...h.beforeBlock.borders?{priorBorders:h.beforeBlock.borders}:{}})}else{const y=new Set(h.beforeBlock.children.map(z=>z.id)),B=new Set(h.acceptedBlock.children.map(z=>z.id));for(let z=0;z<o.children.length;z++){const D=o.children[z];!y.has(D.id)&&B.has(D.id)?u.rows.push({rowIndex:z,kind:"insert",...w()}):y.has(D.id)&&!B.has(D.id)&&u.rows.push({rowIndex:z,kind:"delete",...w()})}const $=qe(h.beforeBlock),W=qe(h.acceptedBlock);for(const z of b.cells){const D=$.byId.has(z.cell.id),T=W.byId.has(z.cell.id);!D&&T?u.cells.push({rowIndex:z.row,gridColumn:z.col,kind:"insert",...w()}):D&&!T&&u.cells.push({rowIndex:z.row,gridColumn:z.col,kind:"delete",...w()});const F=$.byId.get(z.cell.id)?.rowSpan??1,S=W.byId.get(z.cell.id)?.rowSpan??1;if(S>F&&z.rowSpan>F)for(let E=F;E<Math.min(S,z.rowSpan);E++)u.merges.push({rowIndex:z.row+E,gridColumn:z.col,vMerge:"cont",...w()})}h.beforeBlock.borders!==h.acceptedBlock.borders&&(u.tableProperties={...w(),...h.beforeBlock.borders?{priorBorders:h.beforeBlock.borders}:{}})}(u.rows.length>0||u.cells.length>0||u.merges.length>0||u.tableProperties)&&r.push(u)}return r}static textNodeToDocxWithLatex(e,r){if(e.marks?.latex){const t=this.latexToOmml(e.text,!1);return t?[{text:"",mathOmml:t}]:[{text:e.text}]}return this.textNodeToDocx(e,r)}static paragraphToDocx(e,r,t=this.resolveIndentStepPx()){const i={type:"paragraph",sourceBlockId:e.id,children:[]};e.styleId&&(i.styleId=e.styleId),e.heading&&(i.heading=`HEADING_${e.heading}`);{const o=this.docxAlignmentForExport(e);o&&(i.alignment=o)}e.lineSpacing!==void 0&&(i.lineSpacing=e.lineSpacing),this.applyExportParagraphSpacing(i,e),e.keepNext&&(i.keepNext=!0),e.keepLines&&(i.keepLines=!0),e.widowControl===!1&&(i.widowControl=!1),e.borders&&(i.bordersJson=e.borders),e.shading&&(i.shadingFill=e.shading),e.tabStops&&(i.tabStopsJson=e.tabStops),e.oxmlAttrs&&(i.oxmlAttrs=e.oxmlAttrs),e.oxmlPPr&&(i.oxmlPPr=e.oxmlPPr);const n=this.buildParagraphIndent(e,t);n&&(i.indent=n);const s=e;return s.fontFamily&&(i.style=s.fontFamily),this.applyParagraphMarkRevisionInfo(i,e),this.applyParagraphPropertyChangeInfo(i,e,t),e.children.length===0?(this.applyWholeBlockRevisionInfo(i,e),this.applyBidiExportFlags(i,e),i):(e.children.forEach(o=>{if(o.type==="text"){const a=this.textNodeToDocx(o,r);i.children.push(...a)}}),this.applyWholeBlockRevisionInfo(i,e),this.applyBidiExportFlags(i,e),i)}static listToDocxParagraphs(e,r,t){const i=[],n={level0:(e.startNumber??1)-1,level1:0,level2:0};for(const s of e.children){if(s.type!=="list-item")continue;const o=this.getClampedIndentLevel(s.indentLevel),a={type:"paragraph",sourceBlockId:s.id,children:[],lineSpacing:s.lineSpacing??e.lineSpacing,...typeof(s.spaceBefore??e.spaceBefore)=="number"?{spacingBeforeTwips:this.pxToTwips(s.spaceBefore??e.spaceBefore)}:{},...typeof(s.spaceAfter??e.spaceAfter)=="number"?{spacingAfterTwips:this.pxToTwips(s.spaceAfter??e.spaceAfter)}:{},...e.contextualSpacing?{contextualSpacing:!0}:{},list:{variant:e.variant,level:o,label:"",checked:e.variant==="todo"?!!s.checked:void 0,reference:t?.get(e.id)?.reference??this.getDocxListReference(e),instance:t?.get(e.id)?.instance??0}},l=this.getListLabel(e,s,n);a.list&&(a.list.label=l),e.variant==="todo"&&a.children.push({text:`${l} `}),s.children.length>0&&s.children.forEach(d=>{if(d.type==="text"){const p=this.textNodeToDocx(d,r);a.children.push(...p)}}),this.applyWholeBlockRevisionInfo(a,s.structuralSuggestionKind?s:e),i.push(a)}return i}static marksToDocxRunOptions(e,r){const t={};if(e){e.bold!==void 0&&(t.bold=e.bold),e.italic!==void 0&&(t.italic=e.italic),e.underline!==void 0&&(t.underline=e.underline?"SINGLE":"NONE"),e.strikethrough!==void 0&&(t.strike=e.strikethrough),e.doubleStrikethrough!==void 0&&(t.doubleStrike=e.doubleStrikethrough),e.smallCaps!==void 0&&(t.smallCaps=e.smallCaps),e.allCaps!==void 0&&(t.allCaps=e.allCaps),e.hidden!==void 0&&(t.vanish=e.hidden),e.lang&&(t.lang=e.lang),typeof e.letterSpacing=="number"&&Number.isFinite(e.letterSpacing)&&(t.characterSpacing=Math.round(e.letterSpacing*15)),e.superscript&&(t.superScript=!0),e.subscript&&(t.subScript=!0),!e.superscript&&!e.subscript&&(e.superscript===!1||e.subscript===!1)&&(t.baseline=!0),e.color&&(t.color=this.normalizeColor(e.color)),e.backgroundColor&&(t.highlight=this.colorToHighlight(e.backgroundColor));const i=new Set(e.docxRunPropertyResets?.split(",").filter(Boolean)??[]);i.has("color")&&(t.color="auto"),i.has("highlight")&&(t.highlight="none"),e.fontFamily?t.font=e.fontFamily:e.code&&(t.font="Courier New",t.highlight="lightGray",t.characterStyle=this.CODE_INLINE_STYLE_ID),e.fontSize&&(t.size=this.pxToDocxHalfPoints(e.fontSize))}return t.size===void 0&&!e?.code&&this.exportDefaultRunSizeHalfPoints!==void 0&&(t.size=this.exportDefaultRunSizeHalfPoints),e&&(e.link&&(t.link=e.link),e.oxmlRPr&&(t.oxmlRPr=e.oxmlRPr)),!t.font&&r&&(t.font=r),t}static suggestionRevisionAttrs(e){const r=e.suggestionAuthorName?.trim()||(e.suggestionAuthorType==="ai"?"Revise Agent":"Anonymous"),t=new Date(typeof e.suggestionCreatedAt=="number"?e.suggestionCreatedAt:Date.now()).toISOString(),i=typeof e.suggestionId=="string"?/^docxrev-(\d+)$/.exec(e.suggestionId):null;return{author:r,date:t,...i?{importedId:Number(i[1])}:{}}}static textNodeToDocx(e,r){const t=this.marksToDocxRunOptions(e.marks,r);if(e.marks?.comment&&(t.comment=e.marks.comment),e.marks?.bookmark&&(t.bookmark=e.marks.bookmark),e.marks?.oxmlRange&&(t.oxmlRange=e.marks.oxmlRange),e.marks?.sdtInline&&(t.sdtInline=e.marks.sdtInline),e.marks?.fieldInstr&&(t.fieldInstr=e.marks.fieldInstr),e.marks?.insertion||e.marks?.deletion){const s=this.parseDocxMoveMark(e.marks.docxMove),o=s&&/^\d+$/.test(s.wrapperId)?Number(s.wrapperId):void 0;t.revision={kind:e.marks.deletion?"delete":"insert",...this.suggestionRevisionAttrs(e.marks),...o!==void 0?{importedId:o}:{},...s?{move:s}:{}}}else if(e.marks?.formatChange){let s={};try{s=JSON.parse(e.marks.suggestionPriorAttributes??"{}")}catch{s={}}t.rPrChange={...this.suggestionRevisionAttrs(e.marks),prior:this.marksToDocxRunOptions(s)}}if(e.marks?.footnoteRef){const s=parseInt(e.text,10);return[{...t,text:"",footnoteReference:Number.isFinite(s)&&s>0?s:1}]}const i=e.text.split(`
13
- `),n=[];for(let s=0;s<i.length;s++){const o=i[s];(o||s===0)&&n.push({...t,text:o}),s<i.length-1&&n.push({...t,text:"",break:!0})}return n.length===0&&n.push({...t,text:""}),n}static getListIndentOptions(e){const r=Math.max(0,Math.min(2,Math.floor(e)));return{left:this.LIST_BASE_INDENT_TWIPS+r*this.LIST_INDENT_INCREMENT_TWIPS,hanging:this.LIST_HANGING_INDENT_TWIPS}}static getListLabel(e,r,t){const i=this.getClampedIndentLevel(r.indentLevel);if(e.variant==="unordered"){const n=["•","◦","▪"];return n[Math.min(i,n.length-1)]}return e.variant==="todo"?r.checked?"☒":"☐":this.computeOrderedLabel(e.startNumber??1,i,t)}static numberingFormatHash(e){let r=5381;for(let t=0;t<e.length;t++)r=(r<<5)+r+e.charCodeAt(t)|0;return(r>>>0).toString(36)}static buildOrderedNumberingExportPlan(e){const r=new Map,t=new Map,i=new Map,n=new Map,s=a=>{if(a.variant==="ordered")if(a.numberingChainId){const l=a.numberingChainId;let d=i.get(l);if(!d||a.startNumber!==void 0){const p=d?d.segmentIndex+1:0,m=`revise-chain-${l.replace(/[^A-Za-z0-9_-]/g,"")}-s${p}`;d={reference:m,segmentIndex:p},i.set(l,d),t.set(m,{start:a.startNumber??1,formatJson:a.numberingFormat})}r.set(a.id,{reference:d.reference,instance:0})}else{const l=a.startNumber??1,d=a.numberingFormat?`revise-ordered-${l}-f${this.numberingFormatHash(a.numberingFormat)}`:`revise-ordered-${l}`;t.has(d)||t.set(d,{start:l,formatJson:a.numberingFormat});const p=n.get(d)??0;n.set(d,p+1),r.set(a.id,{reference:d,instance:p})}},o=a=>{for(const l of a)if(l.type==="list")s(l);else if(l.type==="container"||l.type==="footnote")o(l.children);else if(l.type==="table")for(const d of l.children)for(const p of d.children)o(p.children)};return o(e.children),e.notes&&o(e.notes),{byListId:r,references:t}}static getDocxListReference(e){if(e.variant!=="todo")return e.variant==="unordered"?"revise-unordered":`revise-ordered-${e.startNumber??1}`}static buildDocxNumberingConfig(e,r){const t=[];let i=!1;const n=a=>{for(const l of a)if(l.type==="list"&&l.variant==="unordered")i=!0;else if(l.type==="container"||l.type==="footnote")n(l.children);else if(l.type==="table")for(const d of l.children)for(const p of d.children)n(p.children)};n(e.children),e.notes&&n(e.notes);const s=this.buildOrderedNumberingExportPlan(e).references;i&&t.push({reference:"revise-unordered",levels:[0,1,2].map(a=>({level:a,format:r.LevelFormat.BULLET,text:["•","◦","▪"][a],alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(a)}}}))});const o=a=>{switch((a||"decimal").trim()){case"lowerLetter":return r.LevelFormat.LOWER_LETTER;case"upperLetter":return r.LevelFormat.UPPER_LETTER;case"lowerRoman":return r.LevelFormat.LOWER_ROMAN;case"upperRoman":return r.LevelFormat.UPPER_ROMAN;case"decimalZero":return r.LevelFormat.DECIMAL_ZERO??r.LevelFormat.DECIMAL;case"bullet":return r.LevelFormat.BULLET;case"none":return r.LevelFormat.NONE??r.LevelFormat.DECIMAL;default:return r.LevelFormat.DECIMAL}};for(const[a,l]of s){const d=l.start,p=l.formatJson?(()=>{try{const m=JSON.parse(l.formatJson);return Array.isArray(m)?m:void 0}catch{return}})():void 0;if(p){t.push({reference:a,levels:[0,1,2].map(m=>({level:m,format:o(p[m]?.numFmt),text:p[m]?.lvlText??["%1.","%1.%2.","%1.%2.%3."][m],start:m===0?d:1,alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(m)}}}))});continue}t.push({reference:a,levels:[{level:0,format:r.LevelFormat.DECIMAL,text:"%1.",start:d,alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(0)}}},{level:1,format:r.LevelFormat.LOWER_LETTER,text:"%1 %2.",start:1,alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(1)}}},{level:2,format:r.LevelFormat.LOWER_ROMAN,text:"%1 %2 %3.",start:1,alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(2)}}}]})}return t.length>0?{config:t}:void 0}static computeOrderedLabel(e,r,t){return r<=0?(t.level0=Math.max(t.level0+1,e),t.level1=0,t.level2=0,`${t.level0}.`):r===1?(t.level0<e&&(t.level0=e),t.level1+=1,t.level2=0,`${t.level0} ${this.toAlphabetic(t.level1)}.`):(t.level0<e&&(t.level0=e),t.level1===0&&(t.level1=1),t.level2+=1,`${t.level0} ${this.toAlphabetic(t.level1)} ${this.toRoman(t.level2)}.`)}static toAlphabetic(e){let r=Math.max(1,e),t="";for(;r>0;)r-=1,t=String.fromCharCode(97+r%26)+t,r=Math.floor(r/26);return t}static toRoman(e){const r=[[1e3,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]];let t=Math.max(1,e),i="";for(const[n,s]of r){for(;t>=n;)i+=s,t-=n;if(t===0)break}return i||"i"}static getClampedIndentLevel(e){if(!Number.isFinite(e))return 0;const r=Math.floor(e);return Math.max(0,Math.min(2,r))}static async resolveImageSourceForDocx(e){const r=e.match(/^data:([^;,]+)(;base64)?,(.*)$/i);if(r){const t=r[1].toLowerCase(),i=this.docxImageTypeForMimeType(t);if(!i)return;const n=!!r[2],s=r[3]||"",o=n?this.base64ToUint8Array(s):new TextEncoder().encode(decodeURIComponent(s));return{type:i,data:o}}if(typeof fetch=="function")try{const t=await fetch(e);if(!t.ok)return;const i=await t.blob(),n=this.docxImageTypeForMimeType(i.type||this.inferMimeTypeFromPath(e)||"");return n?{type:n,data:new Uint8Array(await i.arrayBuffer())}:void 0}catch{return}}static base64ToUint8Array(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));const r=atob(e),t=new Uint8Array(r.length);for(let i=0;i<r.length;i++)t[i]=r.charCodeAt(i);return t}static inferMimeTypeFromPath(e){const r=e.split("?")[0].toLowerCase();if(r.endsWith(".png"))return"image/png";if(r.endsWith(".jpg")||r.endsWith(".jpeg"))return"image/jpeg";if(r.endsWith(".gif"))return"image/gif";if(r.endsWith(".bmp"))return"image/bmp"}static docxImageTypeForMimeType(e){switch(e.toLowerCase()){case"image/png":return"png";case"image/jpeg":case"image/jpg":return"jpg";case"image/gif":return"gif";case"image/bmp":return"bmp";default:return}}static toDocxHex(e){return e?Mr(e)?.slice(1).toUpperCase():void 0}static normalizeColor(e){return this.toDocxHex(e)??"000000"}static highlightValueToColor(e){return qt(e)??"yellow"}static colorToHighlight(e){const r=qt(e);if(r)return{yellow:"yellow",orange:"darkYellow",green:"green",blue:"blue",purple:"darkMagenta",pink:"magenta",gray:"lightGray"}[r]||"yellow";const t=this.normalizeColor(e);return{FFFF00:"yellow",FF0000:"red","00FF00":"green","0000FF":"blue",FFA500:"orange",FF00FF:"magenta","00FFFF":"cyan",808080:"darkGray",D3D3D3:"lightGray"}[t]||"yellow"}};fe.LIST_BASE_INDENT_TWIPS=720,fe.LIST_INDENT_INCREMENT_TWIPS=360,fe.LIST_HANGING_INDENT_TWIPS=360,fe.TWIPS_PER_INCH=1440,fe.TWIPS_PER_PX=fe.TWIPS_PER_INCH/96,fe.DOCX_HALF_POINTS_PER_PX=1.5,fe.DEFAULT_RUN_SIZE_HALF_POINTS=fe.pxToDocxHalfPoints(Ae.paragraph),fe.PAGE_SIZE_PRESETS=Object.entries(gi).map(([O,e])=>({preset:O,width:Math.min(e.width,e.height),height:Math.max(e.width,e.height)})),fe.CORE_PROPERTY_LOCAL_NAMES=["title","creator","subject","keywords","description","lastModifiedBy","created","modified","revision"],fe.TODO_MARKERS=[["☒ ",!0],["☐ ",!1],["[x] ",!0],["[X] ",!0],["[ ] ",!1]],fe.fallbackCommentState={},fe.sdtAncestorStack=[],fe.OXML_RANGE_PAIRS=new Map([["w:permStart","w:permEnd"]]),fe.OMML_FUNCTION_NAMES=["sin","cos","tan","cot","sec","csc","arcsin","arccos","arctan","sinh","cosh","tanh","coth","log","ln","lg","exp","det","dim","ker","deg","gcd","hom","arg","max","min","sup","inf","lim","liminf","limsup","Pr"],fe.CODE_BLOCK_STYLE_ID="CodeBlock",fe.CODE_INLINE_STYLE_ID="CodeInline";let xn=fe;export{xn as DocxConverter};