@reviseio/engine 0.0.0-stage → 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 (77) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/FONT-LICENSE-HAN-EXT-B.txt +91 -0
  3. package/FONT-LICENSE-KATEX.txt +95 -0
  4. package/FONT-LICENSE-LIBERATION.txt +102 -0
  5. package/FONT-LICENSE-NOTO-MULTILINGUAL.txt +93 -0
  6. package/FONT-LICENSE-NOTO-SANS-SC.txt +93 -0
  7. package/FONT-LICENSE-NOTO.txt +94 -0
  8. package/FONT-LICENSE-SOURCE-CODE-PRO.txt +94 -0
  9. package/FONT-LICENSE-SOURCE-SERIF-4.txt +93 -0
  10. package/LICENSE +141 -0
  11. package/README.md +11 -2
  12. package/THIRD-PARTY-NOTICES.md +3376 -0
  13. package/assets/historyMaterializeWorker-Kl0syEbc.js +618 -0
  14. package/chunks/AgentHtmlConverter-BnK7NaYA.js +379 -0
  15. package/chunks/AgentPageRenderViews-BTLjPZJQ.js +2 -0
  16. package/chunks/AgentPageRenderer-DLwq6nAa.js +180 -0
  17. package/chunks/BidiText-Bkp4Y90s.js +160 -0
  18. package/chunks/BlockDiff-BdlcKY-t.js +42 -0
  19. package/chunks/CanvasRenderer-Bqsj1S0p.js +110 -0
  20. package/chunks/ColorParserFull-BKH72fK8.js +446 -0
  21. package/chunks/DocumentCompare-BqyiP87r.js +6 -0
  22. package/chunks/DocumentLayout-CsU5MR-3.js +12 -0
  23. package/chunks/DocumentLayoutEngine-7iOYvyVb.js +218 -0
  24. package/chunks/DocumentMutator-DIrZBuLr.js +13 -0
  25. package/chunks/DocumentScrubber-Cz8Q05hF.js +21 -0
  26. package/chunks/DocumentSession-lXSXqua5.js +1 -0
  27. package/chunks/DocumentStylesheet-CEEt18sr.js +7 -0
  28. package/chunks/DocxConverter-BfDw7777.js +1236 -0
  29. package/chunks/DocxGraft-D0uCnGCo.js +8 -0
  30. package/chunks/HorizontalRuleOrnaments-gmUZ3R7Q.js +3 -0
  31. package/chunks/HtmlConverter-7Xj_g9Jr.js +267 -0
  32. package/chunks/ListNumbering-Qlu6AuRZ.js +23 -0
  33. package/chunks/MarkdownConverter-cnW_oePY.js +57 -0
  34. package/chunks/MathRenderer-Bz9WEVvF.js +68 -0
  35. package/chunks/OdtConverter-GwRDMnwS.js +125 -0
  36. package/chunks/OfficeImportShared-nlMtIUni.js +30 -0
  37. package/chunks/PageNumeralFonts-BWzI061X.js +5 -0
  38. package/chunks/ParagraphDiffAnalysis-DrmStvmz.js +36 -0
  39. package/chunks/PdfConverter-yOlWiVIj.js +457 -0
  40. package/chunks/RtfConverter--wLd0qrw.js +186 -0
  41. package/chunks/TableBorders-C5pNsuxP.js +32 -0
  42. package/chunks/TableGrid-DbroRucl.js +12 -0
  43. package/chunks/TextFileDecoder--rsVs3NR.js +9 -0
  44. package/chunks/TxtConverter-BoRVCDZw.js +14 -0
  45. package/chunks/Typography-DAGM5kfI.js +28 -0
  46. package/chunks/UnicodeUtils-CXtusU4g.js +10 -0
  47. package/chunks/XmlConverter-CO8Z28dX.js +55 -0
  48. package/chunks/_commonjsHelpers-DaMA6jEr.js +2 -0
  49. package/chunks/_revise-sdk-lazy-harfbuzz-CDWdjF9f.js +1 -0
  50. package/chunks/base64-Di1bxoXD.js +1 -0
  51. package/chunks/browser-module-CFmqfGkE.js +1791 -0
  52. package/chunks/bundle.min-DRpfgV69.js +782 -0
  53. package/chunks/capture-Dtinb4bY.js +11 -0
  54. package/chunks/carrier-RNy67HN4.js +6 -0
  55. package/chunks/chromeImageLayout-bgHYmqTp.js +18 -0
  56. package/chunks/engine-TnK8N-gT.js +520 -0
  57. package/chunks/footnoteFlatten-BcKaWzVs.js +6 -0
  58. package/chunks/graftExport-DxAALMHp.js +104 -0
  59. package/chunks/html2canvas.esm-CntiHiYW.js +997 -0
  60. package/chunks/index-BWdRWxoH.js +1807 -0
  61. package/chunks/index-CTti7wRd.js +1002 -0
  62. package/chunks/index.es-CI0QPo8w.js +780 -0
  63. package/chunks/jspdf.es.min-DU74zN8b.js +1792 -0
  64. package/chunks/jszip.min-CPW0h1Kx.js +476 -0
  65. package/chunks/katex-DWj8TvwO.js +1462 -0
  66. package/chunks/pdf-BLWDCiFF.js +1828 -0
  67. package/chunks/purify.es-BwLardii.js +107 -0
  68. package/chunks/serverDocumentSession-BmYdjC6e.js +1011 -0
  69. package/chunks/signatures-CU2LMLBp.js +21 -0
  70. package/chunks/suggestionAuthorship-B-IuLQlE.js +1 -0
  71. package/chunks/web-tree-sitter-BXGZGnNj.js +2 -0
  72. package/chunks/xmlScan-DXjt2cTS.js +8 -0
  73. package/engine.d.ts +179 -0
  74. package/engine.js +3 -0
  75. package/package.json +64 -4
  76. package/serverToolContract.d.ts +420 -0
  77. package/serverToolInputs.generated.d.ts +264 -0
@@ -0,0 +1,1236 @@
1
+ import{b8 as Pi,b9 as Ci,a8 as Er,ab as Ni,a7 as Ai,r as Ee,b1 as Ti,av as Mi,aE as Ei,ba as Di,aN as Lt,X as Ri,aX as Bi,e as tr,v as Dr,bb as Oi,bc as Li,bd as $i,be as Fi,b0 as _i,aR as Wi,O as Xi,
2
+ N as zi,aW as rr,W as Rr,ae as ji,bf as Hi,ar as Br,ad as Ji,bg as Gi,at as Ui,a9 as Or}from"./engine-TnK8N-gT.js";import{c as Ki,h as Zi,m as ir}from"./capture-Dtinb4bY.js";import{g as Vi,a as qi,G as Yi}from"./graftExport-DxAALMHp.js";
3
+ import{b as $t,l as Qi,g as en,d as tn,h as rn,t as nn}from"./BidiText-Bkp4Y90s.js";import{k as on,s as Lr,j as sn,p as an,W as $r,l as ln,c as nr,b as cn,e as dn}from"./TableBorders-C5pNsuxP.js";import{
4
+ b as Qe}from"./TableGrid-DbroRucl.js";import{R as Ct}from"./suggestionAuthorship-B-IuLQlE.js";import{b as pn,c as Fr}from"./MathRenderer-Bz9WEVvF.js";import{J as _r}from"./jszip.min-CPW0h1Kx.js";import{
5
+ F as Ae,L as hn,h as or,g as mn}from"./Typography-DAGM5kfI.js";import{c as gn}from"./chromeImageLayout-bgHYmqTp.js";import{a as un}from"./DocumentStylesheet-CEEt18sr.js";const Wr=()=>new XMLSerializer,
6
+ Xr=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:\
7
+ bCs","w:iCs","w:szCs","w:highlightCs","w:ins","w:del","w:rtl","w:specVanish","w:imprint","w:emboss","w:snapToGrid"]),zr=new Set(["w:pStyle","w:keepNext","w:keepLines","w:widowControl","w:bidi","w:jc",
8
+ "w:ind","w:pageBreakBefore","w:spacing","w:contextualSpacing","w:outlineLvl","w:numPr","w:pBdr","w:shd","w:tabs","w:rPr","w:sectPr","w:pPrChange"]),jr=new Set(["w:tblStyle","w:tblW","w:jc","w:tblInd",
9
+ "w:tblBorders","w:tblLayout","w:tblCellMar","w:tblPrChange"]),Hr=new Set(["w:tblHeader","w:ins","w:del","w:trPrChange"]),Jr=new Set(["w:tcW","w:gridSpan","w:vMerge","w:tcBorders","w:shd","w:tcMar","w:\
10
+ vAlign","w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"]),Gr=new Set(["w:pgSz","w:pgMar","w:pgNumType","w:lnNumType","w:cols","w:type","w:docGrid","w:titlePg","w:headerReference","w:footerReferen\
11
+ ce","w:sectPrChange","w:rPr"]);function at(L,e){if(!L)return;let r="";const t=Wr();for(let i=0;i<L.children.length;i++){const n=L.children[i];e.has(n.tagName)||(r+=t.serializeToString(n))}return r?ar(
12
+ r):void 0}function sr(L){if(!L||L.attributes.length===0)return;const e={};for(let i=0;i<L.attributes.length;i++){const n=L.attributes[i];n.name==="xmlns"||n.name.startsWith("xmlns:")||(e[n.name]=n.value)}
13
+ 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 ar(L){if(!/[\n\r\t]/.test(L))return L;let e="",r=!1,t=null;for(let i=0;i<L.
14
+ length;i++){const n=L[i];if(t){n===t?(t=null,e+=n):n===`
15
+ `?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 lr(L){const e=ar(Wr().serializeToString(L));let r;const t=L.
16
+ getElementsByTagName("o:OLEObject")[0];if(t)r=t.getAttribute("ProgID")??void 0;else if(L.tagName==="w:altChunk")r=L.getAttribute("r:id")??void 0;else{const i=L.getElementsByTagName("a:graphicData")[0]?.
17
+ getAttribute("uri")?.split("/").filter(Boolean).pop();i&&i!=="picture"&&(r=i)}return{xml:e,tagName:L.tagName,...r?{detail:r}:{}}}function cr(L){return L.includes("http://schemas.openxmlformats.org/off\
18
+ iceDocument/2006/relationships")}const Ur=new Set(["w:p","w:tbl","w:sdt","w:customXml","w:sectPr","w:bookmarkStart","w:bookmarkEnd","w:commentRangeStart","w:commentRangeEnd","w:moveFromRangeStart","w:\
19
+ 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"]),fn=/^[A-Za-z_][\w.-]*(?::[\w.-]+)?$/;
20
+ function Kr(L,e){let r;try{r=JSON.parse(L)}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"||!fn.test(i)||e?.
21
+ has(i))continue;const a=n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/"/g,"&quot;");t+=` ${i}="${a}"`}return t}const wn=Object.freeze(Object.defineProperty({__proto__:null,KNOWN_BODY_TAGS:Ur,KNOWN_PPR_TAGS:zr,
22
+ KNOWN_RPR_TAGS:Xr,KNOWN_SECTPR_TAGS:Gr,KNOWN_TBLPR_TAGS:jr,KNOWN_TCPR_TAGS:Jr,KNOWN_TRPR_TAGS:Hr,attrsJsonToXmlAttributes:Kr,captureRawElement:lr,extractElementAttrsJson:sr,extractOpaqueChildrenXml:at,
23
+ stabilizeSerializedXml:ar,xmlReferencesRelationships:cr},Symbol.toStringTag,{value:"Module"})),bn="http://schemas.openxmlformats.org/officeDocument/2006/math",Zr=`<m:oMath xmlns:m="${bn}">`,yn=new Set(
24
+ "∑∏∐∫∬∭∮∯∰∱∲∳⋀⋁⋂⋃⨀⨁⨂⨄⨆".split("")),vn=new Set(["sin","cos","tan","cot","sec","csc","arcsin","arccos","arctan","sinh","cosh","tanh","coth","log","ln","lg","exp",
25
+ "det","dim","ker","deg","gcd","hom","arg","max","min","sup","inf","lim","liminf","limsup","Pr"]),xn=new Set(["lim","liminf","limsup","max","min","sup","inf","Pr"]),Vr={"^":"̂","ˆ":"̂","̂":"̂","~":"\
26
+ ̃","˜":"̃","̃":"̃","ˉ":"̄","¯":"̄","̄":"̄","˙":"̇","̇":"̇","¨":"̈","̈":"̈","ˊ":"́","´":"́","́":"́","ˋ":"̀","`":"̀","̀":"̀","ˇ":"̌","̌":"̌","˘":"̆","̆":"̆","→":"\
27
+ ⃗","⃗":"⃗"},Sn=new Set(["‾","¯","_","―","−"]),kn=new Set(["⏞","⏟","⏜","⏝","⎴","⎵"]),In=new Set(["⁡","⁢","⁣","⁤"]),dr={normal:'<m:sty m:val="p"/>',bold:'<m:sty m:val="b\
28
+ "/>',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="sc\
29
+ ript"/><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\
30
+ m:val="monospace"/><m:sty m:val="p"/>'};function qr(L){return L.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function lt(L){return qr(L)}function We(L){return Array.
31
+ from(L.children)}function $e(L){return(L.textContent??"").replace(/[⁡-⁤]/g,"")}function xe(L){return L.localName.toLowerCase()}function pr(L){let e=L;for(;["mrow","mstyle","mpadded","semantics"].includes(
32
+ xe(e))&&We(e).filter(r=>!Ft(r)).length===1;)e=We(e).filter(r=>!Ft(r))[0];return e}function Ft(L){return xe(L)==="mo"&&In.has((L.textContent??"").trim())}function _t(L){if(!L)return null;const e=pr(L);
33
+ if(xe(e)!=="mo")return null;const r=$e(e).trim();return yn.has(r)?r:null}function Wt(L){if(!L)return null;const e=pr(L);if(!["mi","mo"].includes(xe(e)))return null;const r=$e(e).trim();return vn.has(r)?
34
+ r:null}const Pn=new Set("+-−=<>≤≥≠≈≡∼≃≅∝,;:∣∈∉⊂⊆⊃⊇→←↔⇒⇐⇔".split(""));function Cn(L){return xe(L)==="mo"&&Pn.has($e(L).trim())}function Yr(L,e){let r=e;for(;r<
35
+ L.length&&!Cn(L[r]);)r+=1;return r}function Qr(L){return!!L&&xe(L)==="mo"&&L.getAttribute("fence")==="true"}function Ge(L,e){if(!L)return"";const r=/^\s+$/.test(L)?`${L}​`:L,t=/^\s|\s$/.test(r)?' xm\
36
+ l:space="preserve"':"";return`<m:r>${e?`<m:rPr>${e}</m:rPr>`:""}<m:t${t}>${qr(r)}</m:t></m:r>`}function Nn(L,e){const r=xe(L),t=$e(L);if(!t)return"";if(r==="mtext"||r==="ms")return Ge(t,"<m:nor/>");const i=L.
37
+ getAttribute("mathvariant")??e.mathvariant;return i&&dr[i]?Ge(t,dr[i]):r==="mi"&&[...t].length>1?Ge(t,'<m:sty m:val="p"/>'):Ge(t,"")}function le(L,e){return`<m:${L}>${e}</m:${L}>`}function ei(L,e,r,t,i){
38
+ return`<m:nary><m:naryPr>${`<m:chr m:val="${lt(L)}"/><m:limLoc m:val="${e}"/>`+(r===null?'<m:subHide m:val="1"/>':"")+(t===null?'<m:supHide m:val="1"/>':"")}</m:naryPr>`+le("sub",r??"")+le("sup",t??"")+
39
+ le("e",i)+"</m:nary>"}function ti(L,e){return`<m:func>${le("fName",L)}${le("e",e)}</m:func>`}function ri(L){return parseFloat(L.getAttribute("width")??"")>0?" ":""}function An(L){return xe(L)==="mrow"&&
40
+ L.children.length===0&&!$e(L).trim()}function Ue(L,e){const r=L.filter(i=>!Ft(i)&&!An(i));if(r.length>=2&&Qr(r[0])){const i=r[r.length-1],n=Qr(i),a=r.slice(1,n?-1:void 0),o=$e(r[0]).trim(),s=n?$e(i).trim():
41
+ "";return`<m:d><m:dPr><m:begChr m:val="${lt(o)}"/><m:endChr m:val="${lt(s)}"/></m:dPr>`+le("e",Ue(a,e))+"</m:d>"}let t="";for(let i=0;i<r.length;i+=1){const n=r[i],a=xe(n),o=r[i+1];if(["msub","msup","\
42
+ msubsup","munder","mover","munderover"].includes(a)&&_t(We(n)[0])){const[c,p,h]=We(n),m=_t(c),f=a.startsWith("mu")?"undOvr":"subSup",w=["msub","msubsup","munder","munderover"].includes(a)?pe(p,e):null,
43
+ u=a==="msubsup"||a==="munderover"?pe(h,e):a==="msup"||a==="mover"?pe(p,e):null,g=Yr(r,i+1);t+=ei(m,f,w,u,Ue(r.slice(i+1,g),e)),i=g-1;continue}if(a==="mo"&&_t(n)){const c=Yr(r,i+1);t+=ei(_t(n),"undOvr",
44
+ null,null,Ue(r.slice(i+1,c),e)),i=c-1;continue}const s=["msub","munder"].includes(a)?Wt(We(n)[0]):null;if(s&&xn.has(s)&&o){const[c,p]=We(n),h=`<m:limLow>${le("e",Ge(Wt(c),'<m:sty m:val="p"/>'))}${le("\
45
+ lim",pe(p,e))}</m:limLow>`;t+=ti(h,pe(o,e)),i+=1;continue}if(Wt(n)&&o){t+=ti(Ge(Wt(n),'<m:sty m:val="p"/>'),pe(o,e)),i+=1;continue}if(a==="mtext"||a==="mspace"){let c="",p=i;for(;r[p]&&["mtext","mspac\
46
+ e"].includes(xe(r[p]));)c+=xe(r[p])==="mtext"?$e(r[p]):ri(r[p]),p+=1;i=p-1;const h=c.replace(/\s{2,}/g," ");h&&(t+=Ge(h,"<m:nor/>"));continue}const l=a==="mi"?n.getAttribute("mathvariant"):null;if(l){
47
+ let c=$e(n);for(;r[i+1]&&xe(r[i+1])==="mi"&&r[i+1].getAttribute("mathvariant")===l;)i+=1,c+=$e(r[i]);t+=Ge(c,dr[l]??"");continue}t+=pe(n,e)}return t}function pe(L,e){if(!L)return"";const r=xe(L),t=We(
48
+ L);switch(r){case"math":case"semantics":case"mrow":case"mpadded":case"merror":return Ue(t,e);case"mstyle":{const i=L.getAttribute("mathvariant");return Ue(t,i?{...e,mathvariant:i}:e)}case"annotation":case"\
49
+ annotation-xml":case"mphantom":case"none":case"mprescripts":return"";case"mi":case"mn":case"mo":case"mtext":case"ms":return Ft(L)?"":Nn(L,e);case"mspace":{const i=ri(L);return i?Ge(i,"<m:nor/>"):""}case"\
50
+ mfrac":{const i=L.getAttribute("linethickness");return`<m:f>${i!==null&&parseFloat(i)===0?'<m:fPr><m:type m:val="noBar"/></m:fPr>':""}`+le("num",pe(t[0],e))+le("den",pe(t[1],e))+"</m:f>"}case"msqrt":return'\
51
+ <m:rad><m:radPr><m:degHide m:val="1"/></m:radPr><m:deg/>'+le("e",Ue(t,e))+"</m:rad>";case"mroot":return"<m:rad>"+le("deg",pe(t[1],e))+le("e",pe(t[0],e))+"</m:rad>";case"msub":return`<m:sSub>${le("e",pe(
52
+ t[0],e))}${le("sub",pe(t[1],e))}</m:sSub>`;case"msup":return`<m:sSup>${le("e",pe(t[0],e))}${le("sup",pe(t[1],e))}</m:sSup>`;case"msubsup":return`<m:sSubSup>${le("e",pe(t[0],e))}`+le("sub",pe(t[1],e))+
53
+ le("sup",pe(t[2],e))+"</m:sSubSup>";case"mover":case"munder":return Tn(L,r==="mover"?"top":"bot",e);case"munderover":{const[i,n,a]=t,o=`<m:limLow>${le("e",pe(i,e))}${le("lim",pe(n,e))}</m:limLow>`;return`\
54
+ <m:limUpp>${le("e",o)}${le("lim",pe(a,e))}</m:limUpp>`}case"mtable":return"<m:m>"+t.filter(i=>["mtr","mlabeledtr"].includes(xe(i))).map(i=>"<m:mr>"+We(i).filter(n=>xe(n)==="mtd").map(n=>le("e",Ue(We(n),
55
+ e))).join("")+"</m:mr>").join("")+"</m:m>";case"menclose":{const i=Ue(t,e),n=L.getAttribute("notation")??"";return/\bbox\b|roundedbox/.test(n)?`<m:borderBox>${le("e",i)}</m:borderBox>`:i}case"mfenced":{
56
+ const i=L.getAttribute("open")??"(",n=L.getAttribute("close")??")";return`<m:d><m:dPr><m:begChr m:val="${lt(i)}"/><m:endChr m:val="${lt(n)}"/></m:dPr>`+t.map(a=>le("e",pe(a,e))).join("")+"</m:d>"}default:
57
+ return Ue(t,e)}}function Tn(L,e,r){const[t,i]=We(L),n=pe(t,r),a=i?pr(i):void 0,o=a&&xe(a)==="mo"?$e(a).trim():"";if(o&&Sn.has(o))return`<m:bar><m:barPr><m:pos m:val="${e}"/></m:barPr>${le("e",n)}</m:b\
58
+ ar>`;if(o&&kn.has(o))return`<m:groupChr><m:groupChrPr><m:chr m:val="${lt(o)}"/><m:pos m:val="${e}"/><m:vertJc m:val="${e==="top"?"bot":"top"}"/></m:groupChrPr>`+le("e",n)+"</m:groupChr>";const s=L.getAttribute(
59
+ e==="top"?"accent":"accentunder")==="true";if(e==="top"&&o&&(s||Vr[o])){const c=Vr[o]??o;return`<m:acc><m:accPr><m:chr m:val="${lt(c)}"/></m:accPr>${le("e",n)}</m:acc>`}const l=e==="top"?"limUpp":"lim\
60
+ Low";return`<m:${l}>${le("e",n)}${le("lim",pe(i,r))}</m:${l}>`}function Mn(L){return new DOMParser().parseFromString(L,"text/html").querySelector("math")}function En(L){const e=Mn(L);if(!e)throw new Error(
61
+ "mathmlToOmml: no <math> element in input");return`${Zr}${pe(e,{})}</m:oMath>`}const ii="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",ue=class hr{static async parseFile(e,r){
62
+ 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(),
63
+ i=await _r.loadAsync(t),n=await i.file("word/document.xml")?.async("string");if(!n)return{type:"doc",children:[this.createEmptyParagraph()]};const a=this.parseDocumentXml(n);if(!a)return{type:"doc",children:[
64
+ this.createEmptyParagraph()]};const o=await this.loadOOXMLPackageContext(i,n),s=await this.parseDocumentPageLayoutFromPackage(n,i,a),l=await i.file("word/fontTable.xml")?.async("string"),c=this.parseFontTableXml(
65
+ l),p=await i.file("word/settings.xml")?.async("string"),h=!!(p&&/<w:autoHyphenation(?![^>]*w:val="(?:0|false)")[^>]*\/?>/.test(p)),m=r?.retainSource?new Map:void 0,f=await this.parseStructuredDocxDocument(
66
+ n,s,o,a,m),w=await i.file("docProps/custom.xml")?.async("string");if(w){const D=this.parseDocumentXml(w),$=(D&&Array.from(D.getElementsByTagNameNS("*","property")).find(W=>W.getAttribute("name")==="Re\
67
+ vise.BlockSpacingPx"))?.textContent?.trim(),j=$?Number($):NaN;Number.isFinite(j)&&j>=0&&j<=192&&(f.pageLayout={...f.pageLayout??{},blockSpacingPx:j})}h&&(f.pageLayout={...f.pageLayout??{},hyphenationEnabled:!0}),
68
+ c&&(f.fontSubstitutes=c,Ci(c));const u=await i.file("word/footnotes.xml")?.async("string"),g=await i.file("word/endnotes.xml")?.async("string"),b=new Map;u&&await this.collectNotesFromXml(f,u,"w:footn\
69
+ ote","docxfn","footnote",b,o),g&&await this.collectNotesFromXml(f,g,"w:endnote","docxen","endnote",b,o),this.finalizeImportedFootnoteRefs(f,b);const v=await i.file("word/comments.xml")?.async("string");
70
+ if(v){const D=await i.file("word/commentsExtended.xml")?.async("string");this.attachCommentsFromXml(f,v,D,o)}await this.attachHeadersFootersFromPackage(f,n,i,o,a);const y=await i.file("docProps/core.x\
71
+ ml")?.async("string");if(y){const D=this.parseCoreProperties(y);D&&(f.coreProperties=D)}return m&&Ki(f,m,await Zi(new Uint8Array(t))),f}static parseCoreProperties(e){const r=this.parseDocumentXml(e);if(!r)
72
+ return;const t=new Set(this.CORE_PROPERTY_LOCAL_NAMES),i={},n=r.documentElement;for(let a=0;a<n.children.length;a++){const o=n.children[a],s=o.tagName.split(":").pop()??o.tagName;if(!t.has(s))continue;
73
+ const l=o.textContent??"";l.trim().length!==0&&(i[s]=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];
74
+ if(n.tagName!==r)continue;const a=n.getAttribute("w:type")??"default",o=a==="first"||a==="even"?a:"default",s=n.getAttribute("r:id")??n.getAttribute("relationships:id");s&&(t[o]=s)}return t}static resolveSectionHeaderFooterReferences(e){
75
+ 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(
76
+ e[t],"w:footerReference")}})}return r}static async attachHeadersFootersFromPackage(e,r,t,i,n){const a=(n??this.parseDocumentXml(r))?.getElementsByTagName("w:body")[0];if(!a)return;const o=this.findAllSectionProperties(
77
+ a);if(o.length===0)return;const s=this.resolveSectionHeaderFooterReferences(o),l=o.length-1,c=s[l],p=new Map,h=async $=>{const j=p.get($);if(j)return j;const W={paragraphs:[],images:[]},E=i?.relationships.
78
+ get($);if(E){const T=E.target.startsWith("word/")?E.target:`word/${E.target.replace(/^\//,"")}`,O=await t.file(T)?.async("string");if(O){const k=T.split("/").pop()??T,R=await t.file(`word/_rels/${k}.r\
79
+ els`)?.async("string");if(W.paragraphs=await this.parseHeaderFooterPart(O,R?this.parseRelationshipsXml(R,T):void 0),!e.watermark){const M=this.parseVmlWatermark(O);M&&(e.watermark=M)}W.images=await this.
80
+ parseHeaderFooterImages(O,T,t,i)}}return p.set($,W),W},m=async $=>(await h($)).paragraphs,f=["default","first","even"],w=[],u=async($,j)=>{const W={};for(const E of f){const T=$[E];if(!T)continue;const O=await h(
81
+ T);O.paragraphs.length>0&&(W[E]=O.paragraphs);for(const k of O.images)w.push({side:j,slot:E,...k})}return Object.keys(W).length>0?W:void 0},g=await u(c.header,"header"),b=await u(c.footer,"footer");g&&
82
+ (e.headers=g),b&&(e.footers=b),w.length>0&&(e.chromeImages=w);const v=[];for(let $=0;$<l;$++)for(const j of["header","footer"])for(const W of f){const E=s[$][j][W],T=c[j][W];if(E===T)continue;const O=E?
83
+ await m(E):[];v.push(Er(j,W,O.length>0?Ni(O):void 0,void 0,$))}const y=[],D=new Set(v.map($=>`${$.side}/${$.slot}/${$.sectionIndex}`));for(let $=0;$<o.length;$++)if(o[$].getElementsByTagName("w:titleP\
84
+ g").length!==0)for(const j of["header","footer"]){const W=s[$][j].first;if((W?await m(W):[]).length>0||!s[$][j].default)continue;const E=$===l?void 0:$;D.has(`${j}/first/${E}`)||y.push(Er(j,"first",void 0,
85
+ void 0,E))}(v.length>0||y.length>0)&&(e.chrome=[...Ai(e.headers,e.footers),...v,...y])}static parseVmlWatermark(e){if(!e.includes("v:textpath"))return;const r=this.parseDocumentXml(e);if(!r)return;const t=r.
86
+ getElementsByTagName("v:textpath");for(let i=0;i<t.length;i++){const n=t[i],a=(n.getAttribute("string")??"").trim();if(!a)continue;let o=n.parentNode;for(;o&&o.tagName!=="v:shape";)o=o.parentNode;const s=(o?.
87
+ getAttribute("style")??"").match(/rotation:\s*(-?\d+(?:\.\d+)?)/),l=s?(parseFloat(s[1])%360+360)%360:0,c=this.vmlFillColorToHex(o?.getAttribute("fillcolor")??"");let p;const h=o?.getElementsByTagName(
88
+ "v:fill")[0]?.getAttribute("opacity");if(h){const w=h.endsWith("f")?parseFloat(h)/65536:parseFloat(h);Number.isFinite(w)&&w>0&&w<=1&&(p=Math.abs(w-$r)<.05?void 0:w)}const m=(n.getAttribute("style")??"").
89
+ match(/font-size:\s*(\d+(?:\.\d+)?)pt/),f=m?parseFloat(m[1]):void 0;return on({text:a,...c?{color:c}:{},...p!==void 0?{opacity:p}:{},diagonal:l!==0,...f&&f>2?{fontSizePx:Math.round(f*(4/3))}:{}})}}static vmlFillColorToHex(e){
90
+ 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:"\
91
+ #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)
92
+ return[];const a=n.getElementsByTagName("w:drawing");if(a.length===0)return[];const o=r.split("/").pop()??r,s=await t.file(`word/_rels/${o}.rels`)?.async("string"),l={...i,relationships:this.parseRelationshipsXml(
93
+ s,r)},c=[];for(let p=0;p<a.length;p++){const h=await this.parseImageFromDrawing(a[p],void 0,l);if(h){const m=this.headerFooterImageAlign(a[p]);c.push({src:h.src,width:h.width,height:h.height,...h.alt?
94
+ {alt:h.alt}:{},...m?{align:m}:{}})}}return c}static headerFooterImageAlign(e){let r=e.parentElement;for(;r&&r.tagName!=="w:p";)r=r.parentElement;if(!r)return;const t=Array.from(r.children).find(n=>n.tagName===
95
+ "w:pPr"),i=(t?Array.from(t.children).find(n=>n.tagName==="w:jc"):void 0)?.getAttribute("w:val");if(i==="center")return"center";if(i==="right"||i==="end")return"right"}static async parseHeaderFooterPart(e,r){
96
+ const t=this.parseDocumentXml(e);if(!t)return[];const i=[],n=Array.from(t.getElementsByTagName("w:p")).filter(a=>{let o=a.parentElement;for(;o;){if(o.tagName==="w:txbxContent")return!1;o=o.parentElement}
97
+ return!0});for(let a=0;a<n.length;a++){const o=n[a],s=[];let l=null,c=!1;const p=g=>{const b={},v=this.getDirectChild(g,"w:rPr");v&&(this.applyRunPropertiesFromElement(b,v),(this.getDirectChild(v,"w:r\
98
+ Style")?.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));
99
+ let y=g.parentElement;for(;y&&y!==o;){if(y.tagName==="w:hyperlink"){const D=y.getAttribute("r:id"),$=y.getAttribute("w:anchor"),j=D?r?.get(D)?.target:void 0;j?b.link=j:$&&(b.link=`#${$}`);break}y=y.parentElement}
100
+ return b},h=Array.from(o.getElementsByTagName("w:r")).filter(g=>{let b=g.parentElement;for(;b&&b!==o;){if(b.tagName==="w:p")return!1;b=b.parentElement}return b===o});for(let g=0;g<h.length;g++){const b=h[g],
101
+ v=p(b);for(let y=0;y<b.children.length;y++){const D=b.children[y];if(D.tagName==="w:t"){if(c)continue;const $=D.textContent??"";$&&s.push({type:"text",text:$,...Object.keys(v).length>0?{marks:v}:{}})}else if(D.
102
+ tagName==="w:tab")s.push({type:"text",text:" "});else if(D.tagName==="w:br"&&!c&&(D.getAttribute("w:type")??"textWrapping")==="textWrapping")s.push({type:"text",text:`
103
+ `,...Object.keys(v).length>0?{marks:v}:{}});else if(D.tagName==="w:fldChar"){const $=D.getAttribute("w:fldCharType");$==="begin"&&(c=!0),$==="end"&&(l&&s.push({type:"text",text:"1",marks:{...v,field:l}}),
104
+ l=null,c=!1)}else if(D.tagName==="w:instrText"&&c){const $=(D.textContent??"").trim().toUpperCase();$.startsWith("PAGE")?l="page":$.startsWith("NUMPAGES")&&(l="numPages")}}}const m=o.getElementsByTagName(
105
+ "w:fldSimple");for(let g=0;g<m.length;g++){const b=(m[g].getAttribute("w:instr")??"").trim().toUpperCase();b.startsWith("PAGE")?s.push({type:"text",text:"1",marks:{field:"page"}}):b.startsWith("NUMPAG\
106
+ ES")&&s.push({type:"text",text:"1",marks:{field:"numPages"}})}const f=this.getDirectChild(this.getDirectChild(o,"w:pPr")??o,"w:jc")?.getAttribute("w:val"),w=f==="center"?"center":f==="right"||f==="end"?
107
+ "right":f==="both"?"justify":void 0;s.length>0&&i.push({type:"paragraph",id:this.generateId(),children:s,...w?{align:w}:{}});const u=await this.parseTextBoxContent(o,void 0);i.push(...u.filter(g=>g.type===
108
+ "paragraph"))}return i}static attachCommentsFromXml(e,r,t,i){const n=this.parseDocumentXml(r);if(!n)return;const a=new Set,o=u=>{if(!u||typeof u!="object")return;if(Array.isArray(u)){u.forEach(o);return}
109
+ const g=u;g.marks?.comment&&g.marks.comment.split(",").forEach(b=>a.add(b)),o(g.children)};o(e.children);const s=(i??this.fallbackCommentState).collapsedCommentAnchorBlockById;s?.forEach((u,g)=>a.add(
110
+ `docxcmt-${g}`));const l=new Map;if(t){const u=this.parseDocumentXml(t)?.getElementsByTagName("w15:commentEx")??[];for(let g=0;g<u.length;g++){const b=u[g],v=b.getAttribute("w15:paraId");v&&l.set(v,{done:b.
111
+ getAttribute("w15:done")==="1",parentParaId:b.getAttribute("w15:paraIdParent")??void 0})}}const c=[],p=new Map,h=new Map,m=n.getElementsByTagName("w:comment");for(let u=0;u<m.length;u++){const g=m[u],
112
+ b=g.getAttribute("w:id");if(!b)continue;const v=`docxcmt-${b}`,y=g.getElementsByTagName("w:p"),D=[];for(let E=0;E<y.length;E++){const T=y[E].getElementsByTagName("w:t");let O="";for(let R=0;R<T.length;R++)
113
+ O+=T[R].textContent??"";D.push(O);const k=y[E].getAttribute("w14:paraId");k&&(p.set(v,k),h.set(k,v))}const $=g.getAttribute("w:date"),j=$?Date.parse($):NaN,W=s?.get(b);c.push({id:v,author:g.getAttribute(
114
+ "w:author")??"Unknown",...g.getAttribute("w:initials")?{initials:g.getAttribute("w:initials")}:{},createdAt:Number.isFinite(j)?new Date(j).toISOString():new Date(0).toISOString(),bodyMd:D.filter(E=>E.
115
+ length>0).join(`
116
+
117
+ `),importedId:parseInt(b,10),...W?{anchorBlockId:W}:{}})}for(const u of c){const g=p.get(u.id),b=g?l.get(g):void 0;if(b?.done&&(u.resolved=!0),b?.parentParaId){const v=h.get(b.parentParaId);v&&(u.parentId=
118
+ v)}}const f=u=>{let g=u;const b=new Map(c.map(v=>[v.id,v]));for(;g.parentId&&b.has(g.parentId);)g=b.get(g.parentId);return g.id},w=c.filter(u=>a.has(f(u)));w.length>0&&(e.comments=w)}static async collectNotesFromXml(e,r,t,i,n,a,o){
119
+ const s=this.parseDocumentXml(r);if(!s)return;if(o){const p=t==="w:footnote"?"footnotes":"endnotes",h=await o.zip.file(`word/_rels/${p}.xml.rels`)?.async("string");if(h){const m=this.parseRelationshipsXml(
120
+ h,`word/${p}.xml`);m.size>0&&(o={...o,relationships:new Map([...o.relationships,...m])})}}const l=Ee(e.pageLayout).indentStepPx,c=s.getElementsByTagName(t);for(let p=0;p<c.length;p++){const h=c[p],m=h.
121
+ getAttribute("w:type");if(m==="separator"||m==="continuationSeparator")continue;const f=h.getAttribute("w:id");if(!f)continue;const w=await this.parseBodyChildren(h,l,o),u=this.applyParagraphMarkRevisions(
122
+ w),g=u.length>0?u:[this.createEmptyParagraph()];Ti(g),a.set(`${i}-${f}`,{type:"footnote",id:`${i}-${f}`,...n==="endnote"?{noteKind:"endnote"}:{},children:g})}}static finalizeImportedFootnoteRefs(e,r){
123
+ const t=[],i={footnote:0,endnote:0},n=new Map,a=(o,s)=>{if(!o||typeof o!="object")return;if(Array.isArray(o)){o.forEach(p=>a(p));return}const l=o,c=l.marks?.footnoteRef;if(c&&(c.startsWith("docxfn-")||
124
+ c.startsWith("docxen-")))if(!r.has(c))l.text="",delete l.marks.footnoteRef,delete l.marks.superscript;else{if(!t.includes(c)){t.push(c);const p=c.startsWith("docxen-")?"endnote":"footnote";i[p]+=1,n.set(
125
+ c,ji(i[p],p))}l.text=n.get(c)??""}a(l.children)};a(e.children);for(const o of t){const s=r.get(o);s&&e.children.push(s)}}static documentHasMath(e){return e.includes("m:oMath")||e.includes("m:oMathPara")}static documentHasNativePageBreaks(e){
126
+ 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:dr\
127
+ awing")||e.includes("<w:pict")||e.includes("<w:object")}static shouldUseStructuredDocxParser(e){return!!(this.documentHasMath(e)||this.documentHasNativePageBreaks(e)&&!this.documentHasComplexBodyContent(
128
+ e))}static resolveIndentStepPx(e){return Ee(e?.pageLayout).indentStepPx}static stripXmlBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}static parseDocumentXml(e){const r=new DOMParser().parseFromString(
129
+ this.stripXmlBom(e),"application/xml");return r.querySelector("parsererror")?null:r}static async loadOOXMLPackageContext(e,r){const[t,i,n,a]=await Promise.all([e.file("word/_rels/document.xml.rels")?.
130
+ 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.\
131
+ xml");return{zip:e,documentXml:r,relationships:o,styles:this.parseStylesXml(i),stylesXmlRaw:i||void 0,numbering:this.parseNumberingXml(n),contentTypes:this.parseContentTypesXml(a),themeFonts:await this.
132
+ 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.
133
+ file(t)?.async("string");if(!i)return;const n=this.parseDocumentXml(i);if(!n)return;const a=l=>n.getElementsByTagName(l)[0]?.getElementsByTagName("a:latin")[0]?.getAttribute("typeface")?.trim()||void 0,
134
+ o=a("a:majorFont"),s=a("a:minorFont");if(!(!o&&!s))return{...o?{major:o}:{},...s?{minor:s}:{}}}static parseRelationshipsXml(e,r){const t=new Map;if(!e)return t;const i=this.parseDocumentXml(e);if(!i)return t;
135
+ const n=i.getElementsByTagName("Relationship");for(let a=0;a<n.length;a++){const o=n[a],s=o.getAttribute("Id"),l=o.getAttribute("Target"),c=o.getAttribute("Type");if(!s||!l||!c)continue;const p=o.getAttribute(
136
+ "TargetMode")||void 0;t.set(s,{id:s,type:c,target:p?.toLowerCase()==="external"?l:this.resolvePackageTargetPath(r,l),targetMode:p})}return t}static resolvePackageTargetPath(e,r){if(r.startsWith("/"))return r.
137
+ 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,
138
+ 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 a=i.getElementsByTagName("w:pPrDefault")[0],
139
+ o=i.getElementsByTagName("w:rPrDefault")[0];r.paragraphDefault=a?this.getDirectChild(a,"w:pPr"):void 0,r.runDefault=o?this.getDirectChild(o,"w:rPr"):void 0}const n=t.getElementsByTagName("w:style");for(let a=0;a<
140
+ n.length;a++){const o=n[a],s=o.getAttribute("w:styleId");if(!s)continue;const l=this.getDirectChild(o,"w:name"),c=this.getDirectChild(o,"w:basedOn"),p=o.getAttribute("w:type")||"";r.stylesById.set(s,{
141
+ id:s,type:p,basedOn:c?.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")}),
142
+ p&&this.isOnAttribute(o.getAttribute("w:default"))&&(r.defaultStyleIdByType.has(p)||r.defaultStyleIdByType.set(p,s))}return r}static parseFontTableXml(e){if(!e)return;const r=this.parseDocumentXml(e);
143
+ if(!r)return;const t={},i=r.getElementsByTagName("w:font");for(let n=0;n<i.length;n++){const a=i[n],o=(a.getAttribute("w:name")||"").trim();if(!o)continue;const s=(this.getDirectChild(a,"w:altName")?.
144
+ getAttribute("w:val")||"").trim(),l=(this.getDirectChild(a,"w:family")?.getAttribute("w:val")||"").trim().toLowerCase(),c=(this.getDirectChild(a,"w:pitch")?.getAttribute("w:val")||"").trim().toLowerCase(),
145
+ p=(this.getDirectChild(a,"w:panose1")?.getAttribute("w:val")||"").trim(),h={};s&&(h.alt=s);const m=this.genericFamilyFromFontMetrics(l,c,p);m&&(h.generic=m),(h.alt||h.generic)&&(t[o.toLowerCase()]=h)}
146
+ 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(
147
+ 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,
148
+ nums:new Map};if(!e)return r;const t=this.parseDocumentXml(e);if(!t)return r;const i=t.getElementsByTagName("w:abstractNum");for(let a=0;a<i.length;a++){const o=i[a],s=o.getAttribute("w:abstractNumId");
149
+ if(!s)continue;const l=new Map,c=o.getElementsByTagName("w:lvl");for(let p=0;p<c.length;p++){const h=c[p],m=h.getAttribute("w:ilvl"),f=m?parseInt(m,10):NaN;if(!Number.isFinite(f))continue;const w=this.
150
+ getDirectChild(h,"w:numFmt"),u=this.getDirectChild(h,"w:lvlText"),g=this.getDirectChild(h,"w:start")?.getAttribute("w:val");l.set(f,{level:f,format:w?.getAttribute("w:val")||void 0,text:u?.getAttribute(
151
+ "w:val")||void 0,start:g&&Number.isFinite(parseInt(g,10))?parseInt(g,10):void 0})}r.abstractNums.set(s,{abstractNumId:s,levels:l})}const n=t.getElementsByTagName("w:num");for(let a=0;a<n.length;a++){const o=n[a],
152
+ s=o.getAttribute("w:numId");if(!s)continue;const l=this.getDirectChild(o,"w:abstractNumId"),c=new Map,p=o.getElementsByTagName("w:lvlOverride");for(let h=0;h<p.length;h++){const m=p[h],f=m.getAttribute(
153
+ "w:ilvl"),w=f?parseInt(f,10):NaN;if(!Number.isFinite(w))continue;const u=m.getElementsByTagName("w:startOverride")[0]?.getAttribute("w:val");u&&Number.isFinite(parseInt(u,10))&&c.set(w,parseInt(u,10))}
154
+ r.nums.set(s,{numId:s,abstractNumId:l?.getAttribute("w:val")||void 0,levelStartOverrides:c})}return r}static parseContentTypesXml(e){const r=new Map;if(!e)return r;const t=this.parseDocumentXml(e);if(!t)
155
+ return r;const i=t.getElementsByTagName("Default");for(let a=0;a<i.length;a++){const o=i[a],s=(o.getAttribute("Extension")||"").toLowerCase(),l=o.getAttribute("ContentType");s&&l&&r.set(s,l)}const n=t.
156
+ getElementsByTagName("Override");for(let a=0;a<n.length;a++){const o=n[a],s=o.getAttribute("PartName"),l=o.getAttribute("ContentType");s&&l&&r.set(s.replace(/^\/+/,""),l)}return r}static getDirectChild(e,r){
157
+ 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);
158
+ 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"):
159
+ !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){
160
+ 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),a=Math.max(t,i);let o="letter",s=Number.POSITIVE_INFINITY;
161
+ for(const l of this.PAGE_SIZE_PRESETS){const c=Math.abs(n-l.width)+Math.abs(a-l.height);c<s&&(s=c,o=l.preset)}return o}static findAllSectionProperties(e){const r=[],t=i=>{for(const n of Array.from(i.children)){
162
+ if(n.tagName==="w:sdt"){const a=this.getDirectChild(n,"w:sdtContent");a&&t(a);continue}if(n.tagName==="w:p"){const a=this.getDirectChild(n,"w:pPr"),o=a?this.getDirectChild(a,"w:sectPr"):void 0;o&&r.push(
163
+ 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={},
164
+ t=this.getDirectChild(e,"w:pgSz");if(t){const h=this.parseTwipsAttribute(t,"w:w"),m=this.parseTwipsAttribute(t,"w:h"),f=(t.getAttribute("w:orient")||"").trim().toLowerCase();h!==void 0&&h>0&&m!==void 0&&
165
+ m>0?r.orientation=h>m?"landscape":"portrait":(f==="landscape"||f==="portrait")&&(r.orientation=f),h!==void 0&&h>0&&m!==void 0&&m>0&&(r.pageSize=this.inferPageSizePresetFromTwips(h,m))}const i=this.getDirectChild(
166
+ e,"w:pgMar");if(i){const h=this.parseTwipsAttribute(i,"w:top"),m=this.parseTwipsAttribute(i,"w:right"),f=this.parseTwipsAttribute(i,"w:bottom"),w=this.parseTwipsAttribute(i,"w:left");h!==void 0&&(r.marginTopPx=
167
+ this.twipsToPx(h)),m!==void 0&&(r.marginRightPx=this.twipsToPx(m)),f!==void 0&&(r.marginBottomPx=this.twipsToPx(f)),w!==void 0&&(r.marginLeftPx=this.twipsToPx(w))}const n=this.getDirectChild(e,"w:pgNu\
168
+ mType"),a=(n?.getAttribute("w:start")||"").trim();if(a!==""){const h=parseInt(a,10);Number.isFinite(h)&&h>0&&(r.pageNumberStart=h)}const o=(n?.getAttribute("w:fmt")||"").trim();Mi(o)&&(r.pageNumberFormat=
169
+ o);const s=this.getDirectChild(e,"w:lnNumType");if(s){const h=(s.getAttribute("w:countBy")||"").trim(),m=(s.getAttribute("w:start")||"").trim(),f=(s.getAttribute("w:restart")||"").trim(),w=(s.getAttribute(
170
+ "w:distance")||"").trim(),u=h?parseInt(h,10):NaN,g=m?parseInt(m,10):NaN,b=w?parseInt(w,10):NaN;r.lineNumbering=Ei({countBy:Number.isFinite(u)&&u>=1?u:1,start:Number.isFinite(g)&&g>=1?g:1,restart:f==="\
171
+ newSection"||f==="continuous"?f:"newPage",...Number.isFinite(b)&&b>=0?{distancePx:b/15}:{}})}const l=this.getDirectChild(e,"w:cols");if(l){const h=(l.getAttribute("w:num")||"").trim(),m=h?parseInt(h,10):
172
+ NaN;if(Number.isFinite(m)&&m>1){r.columnCount=m;const f=(l.getAttribute("w:space")||"").trim(),w=f?parseInt(f,10):NaN;Number.isFinite(w)&&w>=0&&(r.columnGapTwips=w)}}const c=Di(this.getDirectChild(e,"\
173
+ w:pgBorders"));c&&(r.pageBorders=c);const p=at(e,Gr);return p&&(r.oxmlSectPr=p),Object.keys(r).length>0?r:void 0}static parseSectionStartType(e){const r=(this.getDirectChild(e,"w:type")?.getAttribute(
174
+ "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??
175
+ 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 a=this.parseSectionPropertiesElement(n);return a?.
176
+ pageNumberStart!==void 0&&(a.pageNumberRestart=!0),a}static async parseDocumentPageLayoutFromPackage(e,r,t){const i=t??this.parseDocumentXml(e);if(!i)return;const n=this.parseDocumentPageLayout(e,i)??
177
+ {},a=i.getElementsByTagName("w:body")[0];if(!a)return Object.keys(n).length>0?n:void 0;const o=this.findAllSectionProperties(a);if(o.length===0)return Object.keys(n).length>0?n:void 0;const s=this.resolveSectionHeaderFooterReferences(
178
+ 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 c=this.parseDocumentXml(l);if(!c)return Object.keys(n).length>0?n:void 0;
179
+ const p=new Map,h=c.getElementsByTagName("Relationship");for(let f=0;f<h.length;f++){const w=h[f],u=w.getAttribute("Id"),g=w.getAttribute("Target");u&&g&&p.set(u,g)}const m=async(f,w)=>{const u=s[f].default,
180
+ g=u?p.get(u):void 0;if(!g)return;const b=g.startsWith("/")?g.slice(1):g.startsWith("word/")?g:`word/${g.replace(/^\.?\//,"")}`,v=await r.file(b)?.async("string");if(!v)return;const y=this.parsePageNumberInfoFromReferenceXml(
181
+ v);y&&(n.showPageNumbers=!0,n.pageNumberPosition=`${w}-${y.horizontal}`)};return await m("header","top"),n.showPageNumbers||await m("footer","bottom"),Object.keys(n).length>0?n:void 0}static parsePageNumberInfoFromReferenceXml(e){
182
+ 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],a=n.getElementsByTagName("w:instrText");let o=!1;for(let l=0;l<a.length;l++)
183
+ if((a[l].textContent||"").toUpperCase().includes("PAGE")){o=!0;break}if(!o){const l=n.getElementsByTagName("w:fldSimple");for(let c=0;c<l.length;c++)if((l[c].getAttribute("w:instr")||"").toUpperCase().
184
+ includes("PAGE")){o=!0;break}}if(!o)continue;const s=this.getDirectChild(n,"w:pPr");return{horizontal:((s?this.getDirectChild(s,"w:jc"):void 0)?.getAttribute("w:val")||"").toLowerCase()==="left"?"left":
185
+ "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(
186
+ 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:\
187
+ 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(
188
+ t,i),this.applyTabStopsFromPPr(i,t),this.applyJcFromPPr(i,t);const a=this.getDirectChild(t,"w:ind");if(a){const o=this.parseTwipsAttribute(a,"w:start")??this.parseTwipsAttribute(a,"w:left");if(o===0)i.
189
+ leftIndent=0;else if(o!==void 0&&o>0){const c=Lt(this.twipsToPx(o),{indentStepPx:r,storedAsUnits:!1});c!==void 0&&(i.leftIndent=c)}const s=this.parseTwipsAttribute(a,"w:firstLine"),l=this.parseTwipsAttribute(
190
+ a,"w:hanging");if(l!==void 0&&l>0)i.firstLineIndent=-1;else if(s===0)i.firstLineIndent=0;else if(s!==void 0&&s>0){const c=Lt(this.twipsToPx(s),{indentStepPx:r,storedAsUnits:!1,firstLine:!0});c!==void 0&&
191
+ (i.firstLineIndent=c)}}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.
192
+ 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==="sta\
193
+ rt"||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=
194
+ t;return}const a=t==="left"?"right":"left";a==="right"?delete e.align:e.align=a;return}const i=e.jcLogical;if(!i)return;delete e.jcLogical;const n=i==="start"?r?"right":"left":r?"left":"right";n===(r?
195
+ "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=[];
196
+ for(let a=0;a<i.children.length;a++){const o=i.children[a];o.tagName==="w:p"&&n.push(this.parseWordParagraphProperties(o,r))}return n}static applyTopLevelParagraphProperties(e,r){const t=r.filter(n=>!n.
197
+ isList);let i=0;for(const n of e.children){if(n.type!=="paragraph")continue;const a=t[i];if(!a)break;i+=1,a.align&&(n.align=a.align),a.leftIndent!==void 0&&(n.leftIndent=a.leftIndent),a.firstLineIndent!==
198
+ void 0&&(n.firstLineIndent=a.firstLineIndent);const o=this.directionAttrFor(a.direction,this.paragraphNodeText(n));o&&(n.direction=o)}}static paragraphNodeText(e){let r="";for(const t of e.children)t.
199
+ type==="text"&&(r+=t.text);return r}static directionAttrFor(e,r){if(e==="rtl")return"rtl";if(e==="ltr"&&$t(r)==="rtl")return"ltr"}static async parseStructuredDocxDocument(e,r,t,i,n){t||(this.fallbackCommentState=
200
+ {});const a=i??this.parseDocumentXml(e);if(!a)return{type:"doc",children:[this.createEmptyParagraph()]};const o=a.getElementsByTagName("w:body")[0];if(!o)return{type:"doc",children:[this.createEmptyParagraph()]};
201
+ const s=Ee(r).indentStepPx,l=[];this.importSdtWrappers=l;const c=[];this.importOxmlRanges=c,this.sdtAncestorStack=[];const p=t??this.fallbackCommentState;p.moveRangeByWrapper=e.includes("<w:moveFrom")||
202
+ e.includes("<w:moveTo")?this.indexImportedMoveRanges(a):new WeakMap,p.collapsedCommentAnchorBlockById=new Map;let h;try{h=await this.parseBodyChildren(o,s,t,l,n)}finally{this.importSdtWrappers=void 0,
203
+ this.importOxmlRanges=void 0,this.sdtAncestorStack=[],delete p.moveRangeByWrapper}this.finalizeImportedMovePairs(h),h=this.applyParagraphMarkMoves(h),this.applyTableMoves(h),h=this.applyParagraphMarkRevisions(
204
+ h),h=this.collapseTocRegions(h);const m=this.findAllSectionProperties(o);if(m.length>1){let w=0;for(const u of h){if(u.type!=="section-break")continue;const g=m[w+1];if(g){const b=this.parseSectionStartType(
205
+ g);b&&(u.breakType=b)}w++}}const f={type:"doc",children:h.length>0?h:[this.createEmptyParagraph()]};if(r){if(f.pageLayout=r,r.pageNumberFormat&&r.pageNumberFormat!=="decimal")for(const w of f.children)
206
+ w.type==="section-break"&&w.layout?.pageNumberFormat===void 0&&(w.layout={...w.layout??{},pageNumberFormat:"decimal"});if((r.columnCount??1)>1)for(const w of f.children)w.type==="section-break"&&w.layout?.
207
+ columnCount===void 0&&(w.layout={...w.layout??{},columnCount:1})}if(l.length>0&&(f.sdtWrappers=l),c.length>0&&(f.oxmlRanges=c),t?.stylesXmlRaw){f.stylesXml=t.stylesXmlRaw;const w=this.buildDocumentStylesheet(
208
+ t,s);w&&(f.stylesheet=w)}return f}static resolveStylesheetFromStylesXml(e,r){const t=this.parseStylesXml(e);return this.buildDocumentStylesheet({styles:t,numbering:{abstractNums:new Map,nums:new Map}},
209
+ Ee(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 a of t.stylesById.values()){if(a.
210
+ type!=="paragraph")continue;const o={isList:!1},s=[];t.paragraphDefault&&s.push(t.paragraphDefault),s.push(...this.resolveStyleChainPPr(a.id,t,"paragraph"));const l=this.resolveRunMarks(void 0,a.id,e),
211
+ c=typeof l.fontSize=="number"&&l.fontSize>0?l.fontSize:Ae.paragraph;for(const f of s)this.applyParagraphPropertiesFromElement(o,f,r,e,c);this.resolveLogicalAlignment(o);const p={};o.align&&(p.align=o.
212
+ 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=
213
+ 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),
214
+ 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 h={styleId:a.id};a.name&&(h.name=a.name);const m=this.
215
+ headingLevelForStyle(a)||o.heading;m&&(h.headingLevel=m),a.id===i&&(h.default=!0),Object.keys(p).length>0&&(h.paragraphAttrs=p),Object.keys(l).length>0&&(h.runMarks=l),n.push(h)}return n.length>0?{paragraphStyles:n}:
216
+ 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;
217
+ 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(c=>c.type==="text"&&(c.text??"").trim()!==
218
+ "")),i=l=>{if(t.length===0)return;const c=l(t[0]);if(c!==void 0)return t.every(p=>l(p)===c)?c:void 0},n={},a=i(l=>l.marks?.fontFamily);a&&a!==r&&(n.fontFamily=a);const o=i(l=>l.marks?.fontSize);Ri(o)&&
219
+ (n.fontSize=o);const s=i(l=>Rr(l.marks?.color));return s&&(n.color=s),n}static collapseTocRegions(e){const r=[];let t,i,n=[],a={},o,s=!1;const l=()=>{if(t){s||(o=this.inferDocumentFontFamily({type:"do\
220
+ c",children:e.filter(p=>!this.tocInstrOfBlock(p))}),s=!0);const c={type:"toc",...a,...this.tocTypographyOfRegion(n,o),id:i||this.generateId(),instr:t,levels:Hi(t)};r.push(c)}t=void 0,i=void 0,n=[],a={}};
221
+ for(const c of e){const p=this.tocInstrOfBlock(c);if(p&&p===t){c.type==="paragraph"&&n.push(c);continue}if(t&&l(),p){t=p,i=c.id,c.type==="paragraph"&&(n.push(c),c.direction&&(a.direction=c.direction,a.
222
+ align=c.direction==="rtl"?"right":"left"),c.align&&(a.align=c.align));continue}r.push(c)}return l(),r}static parseParagraphMarkRevision(e){const r=this.getDirectChild(e,"w:pPr"),t=r?this.getDirectChild(
223
+ 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",
224
+ 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(
225
+ i,"w:moveFrom")??this.getDirectChild(i,"w:moveTo");if(!n)return null;const a=(r??this.fallbackCommentState).moveRangeByWrapper?.get(n);return{role:n.tagName==="w:moveFrom"?"from":"to",meta:this.parseTrackedRevisionMeta(
226
+ n),...a?{move:a}:{}}}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.
227
+ 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=s=>{if(!s||
228
+ typeof s!="object")return;if(Array.isArray(s)){s.forEach(t);return}const l=s;l.marks?.docxMove&&l.marks.suggestionId&&r.add(l.marks.suggestionId),t(l.children)};t(e);const i=(s,l)=>{if(!s?.move)return;
229
+ const c=`docxmove-${encodeURIComponent(s.move.name)}`;return r.has(c)&&l.every(p=>p.type!=="text"||!p.text||p.marks?.suggestionId===c&&this.parseDocxMoveMark(p.marks.docxMove)?.role===s.role)?c:void 0},
230
+ n=s=>{if(!(!s||typeof s!="object")){if(Array.isArray(s)){s.forEach(n);return}delete s.__pilcrowMove,n(s.children)}},a=(s,l,c)=>{s.structuralSuggestionId=c,s.structuralSuggestionKind=l.role==="from"?"d\
231
+ elete":"insert",s.structuralSuggestionLabel="Move",this.markWholeBlockMove(s,c),delete s.structuralSuggestionRole,delete s.structuralSuggestionRecord},o=[];for(const s of e){if(s.type==="paragraph"){const l=s.
232
+ __pilcrowMove;delete s.__pilcrowMove;const c=i(l,s.children);l&&c?a(s,l,c):l&&!s.structuralSuggestionKind&&(s.__pilcrowRevision={kind:l.role==="from"?"merge":"split",meta:l.meta}),n(s.children),o.push(
233
+ s);continue}if(s.type==="list"&&s.children.length>0){const l=[];for(const p of s.children){const h=p.__pilcrowMove,m=i(h,p.children),f=h&&m?{marker:h,moveId:m}:void 0,w=f?`${f.moveId}\0${f.marker.role}`:
234
+ "",u=l[l.length-1];u&&u.key===w?u.items.push(p):l.push({key:w,move:f,items:[p]})}const c={...s};l.forEach((p,h)=>{const m=h===0?s:{...c,id:this.generateId()};h>0&&s.numberingChainId&&delete m.startNumber,
235
+ m.children=p.items,p.move&&a(m,p.move.marker,p.move.moveId);for(const f of p.items)delete f.__pilcrowMove;n(m.children),o.push(m)});continue}n(s),o.push(s)}return o}static applyTableMoves(e){for(const r of e){
236
+ 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(h=>h.diffState===t&&h.suggestionId===
237
+ i))continue;const n=t==="delete"?"from":"to",a=new Set;let o=!0;const s=h=>{if(!o||!h||typeof h!="object")return;if(Array.isArray(h)){h.forEach(s);return}const m=h;m.type==="table-cell"&&m.diffState&&
238
+ (o=!1),m.type==="text"&&m.text&&(this.parseDocxMoveMark(m.marks?.docxMove)?.role===n&&m.marks?.suggestionId&&(n==="from"?m.marks.deletion:m.marks.insertion)?a.add(m.marks.suggestionId):o=!1),s(m.children)};
239
+ if(s(r.children),!o||a.size!==1)continue;let l=[];try{const h=JSON.parse(r.structuralSuggestionRecords??"[]");Array.isArray(h)&&(l=h)}catch{continue}const c=l.find(h=>h?.id===i);if(c?.type!=="table-ch\
240
+ ange"||c.tableRevision.operations.length!==r.children.length||!c.tableRevision.operations.every(h=>h.kind==="row"&&h.action===t))continue;const p=l.filter(h=>h!==c);p.length>0?r.structuralSuggestionRecords=
241
+ JSON.stringify(p):delete r.structuralSuggestionRecords;for(const h of r.children)delete h.diffState,delete h.suggestionId;r.diffState=t,r.suggestionId=[...a][0],this.markWholeBlockMove(r,r.suggestionId)}}static applyParagraphMarkRevisions(e){
242
+ const r=(a,o)=>{if(a.type!=="paragraph")return!1;const s=o==="insertion"?"deletion":"insertion";return a.children.every(l=>{const c=l.marks;return!!c?.[o]&&!c?.[s]})},t=a=>a.__pilcrowRevision?.kind;for(let a=0;a<
243
+ e.length;a++){const o=t(e[a]);if(!o||e[a].type!=="paragraph")continue;const s=o==="split"?"insertion":"deletion";if(r(e[a],s))continue;let l=a+1;for(;l<e.length&&r(e[l],s)&&t(e[l])===o;)l+=1;l<e.length&&
244
+ r(e[l],s)&&!t(e[l])&&(e[l].__pilcrowRevision=e[a].__pilcrowRevision,delete e[a].__pilcrowRevision)}const i=[];let n=0;for(;n<e.length;){const a=e[n];if(a.type!=="paragraph"||!a.__pilcrowRevision){i.push(
245
+ a),n+=1;continue}let o=n;for(;o<e.length&&e[o].type==="paragraph"&&e[o].__pilcrowRevision;)o+=1;const s=e.slice(n,o),l=o<e.length&&e[o].type==="paragraph"?e[o]:void 0,c=s.map(p=>p.__pilcrowRevision);s.
246
+ forEach(p=>delete p.__pilcrowRevision),s.every((p,h)=>r(p,c[h].kind==="split"?"insertion":"deletion"))?(s.forEach((p,h)=>this.markWholeParagraphRevision(p,c[h])),i.push(...s),n=o):s.length===1&&!l?(i.
247
+ push(s[0]),n=o):s.length===1&&l&&!s[0].structuralSuggestionId&&!l.structuralSuggestionId?(this.linkParagraphMarkRevision(s[0],l,c[0]),i.push(s[0],l),n=o+1):(i.push(...this.replaceParagraphMarkRun(l?[...s,
248
+ l]:s,c)),n=l?o+1:o)}return i}static markWholeParagraphRevision(e,r){const t=r.kind==="split"?"insert":"delete";e.children=this.unwrapWholeBlockRunMarks(e.children,r);const i=r.meta.revisionId?`docxrev\
249
+ -${r.meta.revisionId}`:this.generateId(),n=this.revisionAuthorIdentity(r.meta.author),a={id:i,blockId:e.id,source:n.suggestionSource,authorType:n.suggestionAuthorType,label:t==="insert"?"Insert":"Dele\
250
+ te",...r.meta.createdAt!==void 0?{createdAt:r.meta.createdAt}:{},...r.meta.author?{agentName:r.meta.author}:{}},o=t==="insert"?{...a,type:"block-insert"}:{...a,type:"block-delete",beforeBlock:{...e}};
251
+ e.structuralSuggestionId=i,e.structuralSuggestionKind=t,e.structuralSuggestionRecord=JSON.stringify(o)}static unwrapWholeBlockRunMarks(e,r){const t=r.kind==="split"?"insertion":"deletion",i=n=>!!n[t]&&
252
+ (r.meta.author===void 0||n.suggestionAuthorName===r.meta.author)&&(r.meta.createdAt===void 0||n.suggestionCreatedAt===r.meta.createdAt);return e.map(n=>{const a=n.marks;if(!a||!i(a))return n;const o=Object.
253
+ fromEntries(Object.entries(a).filter(([s])=>s!=="insertion"&&s!=="deletion"&&s!=="formatChange"&&s!=="layeredInsertion"&&!s.startsWith("suggestion")));if(t==="deletion"&&typeof a.layeredInsertion=="st\
254
+ ring")try{const s=JSON.parse(a.layeredInsertion);Object.assign(o,{insertion:!0,...s.id?{suggestionId:s.id}:{},...s.source?{suggestionSource:s.source}:{},...s.authorType?{suggestionAuthorType:s.authorType}:
255
+ {},...s.createdAt!==void 0?{suggestionCreatedAt:s.createdAt}:{},suggestionLabel:s.label??"Insert",...s.authorName?{suggestionAuthorName:s.authorName}:{}})}catch{}return{...n,marks:o}})}static markListItemPropertyChange(e,r){
256
+ const t=r,i=t.__propertyChange;if(delete t.__propertyChange,!i||r.structuralSuggestionId)return;const n=i.priorProps,a=r,o=e,s={type:"list-item",id:r.id,children:[]},l={type:"list-item",id:r.id,children:[]};
257
+ let c=!1;for(const m of this.LIST_ITEM_PROPERTY_FIELDS){const f=a[m]??o[m],w=n[m]??o[m];f!==void 0&&(l[m]=f),w!==void 0&&(s[m]=w),JSON.stringify(f)!==JSON.stringify(w)&&(c=!0)}if(i.priorLevel!==void 0){
258
+ const m=r.indentLevel??0;l.indentLevel=m,s.indentLevel=i.priorLevel,m!==i.priorLevel&&(c=!0)}if(!c)return;const p=i.meta.revisionId?`docxrev-${i.meta.revisionId}`:this.generateId(),h=this.revisionAuthorIdentity(
259
+ i.meta.author);r.structuralSuggestionId=p,r.structuralSuggestionKind="change",r.structuralSuggestionLabel="Format",r.structuralSuggestionRecord=JSON.stringify({id:p,type:"block-change",blockId:e.id,beforeBlock:{
260
+ ...e,children:[]},listItemSuggestion:{kind:"change",beforeItem:s,afterItem:l},label:"Format",source:h.suggestionSource,authorType:h.suggestionAuthorType,...i.meta.createdAt!==void 0?{createdAt:i.meta.
261
+ createdAt}:{},...i.meta.author?{agentName:i.meta.author}:{}})}static markWholeListItemRevision(e,r){const t=r,i=t.__pilcrowRevision;if(delete t.__pilcrowRevision,!i)return;const n=i.kind==="split"?"in\
262
+ sertion":"deletion",a=n==="insertion"?"deletion":"insertion";if(!r.children.every(h=>{const m=h.marks;return!!m?.[n]&&!m?.[a]}))return;r.children=this.unwrapWholeBlockRunMarks(r.children,i);const o=i.
263
+ kind==="split"?"insert":"delete",s=i.meta.revisionId?`docxrev-${i.meta.revisionId}`:this.generateId(),l=this.revisionAuthorIdentity(i.meta.author),c=JSON.parse(JSON.stringify(r)),p=o==="insert"?"Inser\
264
+ t":"Delete";r.structuralSuggestionId=s,r.structuralSuggestionKind=o,r.structuralSuggestionLabel=p,r.structuralSuggestionRecord=JSON.stringify({id:s,type:"block-change",blockId:e.id,beforeBlock:{...e,children:[]},
265
+ listItemSuggestion:o==="insert"?{kind:o,afterItem:c}:{kind:o,beforeItem:c},label:p,source:l.suggestionSource,authorType:l.suggestionAuthorType,...i.meta.createdAt!==void 0?{createdAt:i.meta.createdAt}:
266
+ {},...i.meta.author?{agentName:i.meta.author}:{}})}static linkParagraphMarkRevision(e,r,t){const i=t.meta.revisionId?`docxrev-${t.meta.revisionId}`:this.generateId(),n=t.kind==="split"?"Split":"Merge",
267
+ a=this.revisionAuthorIdentity(t.meta.author),o={id:i,source:a.suggestionSource,authorType:a.suggestionAuthorType,label:n,...t.meta.createdAt!==void 0?{createdAt:t.meta.createdAt}:{},...t.meta.author?{
268
+ agentName:t.meta.author}:{}},s=t.kind==="split"?{...o,type:"paragraph-split",blockId:e.id,insertedBlockId:r.id,beforeBlock:{...this.paragraphPropertiesOf(r),type:"paragraph",id:e.id,children:[...e.children,
269
+ ...r.children]}}:{...o,type:"paragraph-merge",firstBlockId:e.id,secondBlockId:r.id};e.structuralSuggestionId=i,e.structuralSuggestionKind=t.kind,e.structuralSuggestionRole="before",e.structuralSuggestionLabel=
270
+ n,e.structuralSuggestionRecord=JSON.stringify(s),r.structuralSuggestionId=i,r.structuralSuggestionKind=t.kind,r.structuralSuggestionRole="after",r.structuralSuggestionLabel=n}static paragraphPropertiesOf(e){
271
+ const{id:r,type:t,children:i,structuralSuggestionId:n,structuralSuggestionKind:a,structuralSuggestionRole:o,structuralSuggestionLabel:s,structuralSuggestionRecord:l,...c}=e;return delete c.__pilcrowRevision,
272
+ c}static replaceParagraphMarkRun(e,r){const t=r[0].meta,i=c=>c==="insertion"||c==="deletion"||c==="formatChange"||c==="layeredInsertion"||c==="docxMove"||c.startsWith("suggestion"),n=c=>Object.fromEntries(
273
+ Object.entries(c).filter(([p])=>!i(p))),a=(c,p)=>c.children.filter(h=>{const m=h.marks;return p==="before"?!m?.insertion:!m?.deletion}).map(h=>{const m=h.marks;if(!m)return h;if(p==="before"&&m.formatChange){
274
+ let f={};try{f=JSON.parse(m.suggestionPriorAttributes??"{}")}catch{f={}}return{...h,marks:n(f)}}return{...h,marks:n(m)}}),o=c=>{const p=c==="before"?"split":"merge",h=[[]];return e.forEach((m,f)=>{h[h.
275
+ length-1].push(m),(f>=r.length||r[f].kind!==p)&&h.push([])}),h.filter(m=>m.length>0)},s=this.revisionAuthorIdentity(t.author),l=(c,p)=>{const h=c[c.length-1],m=h.structuralSuggestionRecord?JSON.parse(
276
+ h.structuralSuggestionRecord):void 0,f=p==="before"&&m?.type==="block-change"&&m.beforeBlock?m.beforeBlock:h,w={...this.paragraphPropertiesOf(f),type:"paragraph",id:p==="after"?c[0].id:this.generateId(),
277
+ children:c.flatMap(v=>a(v,p))},u=p==="after"?"insert":"delete",g=this.generateId(),b={id:g,blockId:w.id,source:s.suggestionSource,authorType:s.suggestionAuthorType,label:u==="insert"?"Insert":"Delete",
278
+ ...t.createdAt!==void 0?{createdAt:t.createdAt}:{},...t.author?{agentName:t.author}:{}};return{...w,structuralSuggestionId:g,structuralSuggestionKind:u,structuralSuggestionRecord:JSON.stringify(u==="i\
279
+ nsert"?{...b,type:"block-insert"}:{...b,type:"block-delete",beforeBlock:w})}};return[...o("before").map(c=>l(c,"before")),...o("after").map(c=>l(c,"after"))]}static parseParagraphPropertyChange(e,r,t){
280
+ const i=this.getDirectChild(e,"w:pPr"),n=i?this.getDirectChild(i,"w:pPrChange"):void 0;if(!n)return null;const a=this.parseTrackedRevisionMeta(n),o=this.getDirectChild(n,"w:pPr"),s={isList:!1};if(t){const p=o&&
281
+ this.getDirectChild(o,"w:pStyle")?.getAttribute("w:val")||void 0;s.styleId=p;const h=[];t.styles.paragraphDefault&&h.push(t.styles.paragraphDefault),h.push(...this.resolveStyleChainPPr(p,t.styles,"par\
282
+ agraph")),o&&h.push(o);for(const m of h)this.applyParagraphPropertiesFromElement(s,m,r,t)}else o&&this.applyParagraphPropertiesFromElement(s,o,r);this.resolveLogicalAlignment(s);const l=o?this.getDirectChild(
283
+ this.getDirectChild(o,"w:numPr")??o,"w:ilvl")?.getAttribute("w:val"):void 0,c=o&&this.getDirectChild(o,"w:numPr")&&l?parseInt(l,10):void 0;return{meta:a,priorProps:s,...c!==void 0&&Number.isFinite(c)?
284
+ {priorLevel:c}:{}}}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,
285
+ 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=
286
+ 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),
287
+ 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.
288
+ 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=
289
+ r.spaceAfter??0}static async parseWordParagraphBlocks(e,r,t){const i=[];for(let g=0;g+1<e.children.length;g++){const b=e.children[g],v=e.children[g+1],y=b.getAttribute("w:id");b.tagName==="w:commentRa\
290
+ ngeStart"&&v.tagName==="w:commentRangeEnd"&&y&&v.getAttribute("w:id")===y&&i.push(y)}const n=this.resolveParagraphProperties(e,r,t),a=this.parseParagraphMarkRevision(e),o=a?null:this.parseParagraphMarkMove(
291
+ e,t),s=[];let l=!1,c="";const p=[];n.pageBreakBefore&&p.push(this.createPageBreakBlock());for(let g=0;g<e.children.length;g++){const b=e.children[g],v=b.tagName;if(!this.trackCommentRangeMarker(b,t)&&
292
+ !(this.trackBookmarkMarker(b,t)||this.trackOxmlRangeMarker(b,t))){if(v==="w:fldSimple"){s.push(...await this.parseFldSimpleItems(b,n,t));continue}if(v==="mc:AlternateContent"){const y=this.selectAlternateContentBranch(
293
+ b);y&&s.push(...await this.parseInlineItemsFromChildren(y,n,t));continue}if(v==="w:r")s.push(...this.stampOpenComments(await this.parseWordRunItems(b,n,t),t));else if(v==="w:sdt")s.push(...await this.
294
+ parseInlineSdtItems(b,n,t));else if(v==="w:ins"||v==="w:del"||v==="w:moveFrom"||v==="w:moveTo")s.push(...await this.parseTrackedChangeItems(b,n,t));else if(v==="w:hyperlink")s.push(...await this.parseHyperlinkItems(
295
+ b,n,t));else if(v==="m:oMathPara"){const y=this.ommlToLatex(b);y&&(s.some(D=>D.kind==="text"&&D.node.text.trim()!=="")?s.push({kind:"text",node:{type:"text",text:y,marks:{latex:!0}}}):(l=!0,c=y))}else if(v===
296
+ "m:oMath"){const y=this.ommlToLatex(b);y&&s.push({kind:"text",node:{type:"text",text:y,marks:{latex:!0}}})}}}const h=s.filter(g=>g.kind==="text");if(l&&h.every(g=>g.node.text.trim()===""))return p.push(
297
+ {type:"math",id:this.generateId(),content:c,displayMode:"block",align:n.align==="left"||n.align==="right"||n.align==="center"?n.align:"center"}),p;const m=p.concat(this.buildBlocksFromParagraphItems(s,
298
+ n));if(t){const g=m.find(v=>v.type==="paragraph"),b=g?.children[0];if(g&&g.children.length===1&&b?.type==="text"&&b.text===""&&b.marks?.fontSize===void 0){const v=this.getDirectChild(e,"w:pPr"),y=this.
299
+ resolveRunMarks(v?this.getDirectChild(v,"w:rPr"):void 0,n.styleId,t),D={};typeof y.fontSize=="number"&&y.fontSize>0&&(D.fontSize=y.fontSize),y.fontFamily&&!b.marks?.fontFamily&&(D.fontFamily=y.fontFamily),
300
+ Object.keys(D).length>0&&(b.marks={...b.marks,...D})}}const f=this.getDirectChild(e,"w:pPr"),w=sr(e),u=at(f,zr);if(w||u){const g=m.find(b=>b.type==="paragraph");g&&(w&&(g.oxmlAttrs=w),u&&(g.oxmlPPr=u))}
301
+ if(i.length>0){const g=m.find(b=>b.type==="paragraph");if(g?.id){const b=t??this.fallbackCommentState,v=b.collapsedCommentAnchorBlockById??(b.collapsedCommentAnchorBlockById=new Map);for(const y of i)
302
+ v.set(y,g.id)}}if(n.list&&!a){const g=this.parseParagraphPropertyChange(e,r,t);if(g){for(let b=m.length-1;b>=0;b--)if(m[b].type==="paragraph"){m[b].__propertyChange=g;break}}}if(!n.list&&!a){const g=this.
303
+ parseParagraphPropertyChange(e,r,t);if(g)for(let b=m.length-1;b>=0;b--){const v=m[b];if(v.type!=="paragraph")continue;const y=g.meta.revisionId?`docxrev-${g.meta.revisionId}`:this.generateId(),D=this.
304
+ revisionAuthorIdentity(g.meta.author),$=JSON.parse(JSON.stringify(v)),j=JSON.parse(JSON.stringify(v));this.applyParsedPropertiesToParagraphNode(j,g.priorProps),v.structuralSuggestionId=y,v.structuralSuggestionKind=
305
+ "change",v.structuralSuggestionLabel="Paragraph format",v.structuralSuggestionRecord=JSON.stringify({id:y,type:"block-change",blockId:v.id,source:D.suggestionSource,authorType:D.suggestionAuthorType,label:"\
306
+ Paragraph format",...g.meta.createdAt!==void 0?{createdAt:g.meta.createdAt}:{},...g.meta.author?{agentName:g.meta.author}:{},beforeBlock:j,acceptedBlock:$});break}}if(a){for(let g=m.length-1;g>=0;g--)
307
+ if(m[g].type==="paragraph"){m[g].__pilcrowRevision=a;break}}if(o){for(let g=m.length-1;g>=0;g--)if(m[g].type==="paragraph"){m[g].__pilcrowMove=o;break}}return m}static async parseBodyChildren(e,r,t,i,n){
308
+ const a=[];let o;const s=new Map,l=g=>g.abstractNumId??g.numId,c=g=>{const b=l(g);let v=s.get(b);return v||(v={chainId:this.generateId(),seenNumIds:new Set,started:!1},s.set(b,v)),v},p=g=>{const b=c(g),
309
+ v=g.hasLevel0StartOverride&&!b.seenNumIds.has(g.numId);if(!b.started||v)return g.startNumber},h=()=>{o&&o.list.children.length>0&&a.push(o.list),o=void 0},m=Array.from(e.children),f=[];let w;const u=(g,b)=>{
310
+ if(n){for(const v of f)ir(n,g,v);f.length=0,ir(n,g,b),w=g}};for(let g=0;g<m.length;g++){const b=m[g],v=b.tagName==="w:bookmarkStart"||this.OXML_RANGE_PAIRS.has(b.tagName)?"start":b.tagName==="w:bookma\
311
+ rkEnd"||[...this.OXML_RANGE_PAIRS.values()].includes(b.tagName)?"end":null;if(this.trackBookmarkMarker(b,t)||this.trackOxmlRangeMarker(b,t)){n&&v==="end"&&w?ir(n,w,g):n&&v!==null&&f.push(g);continue}const y=i&&
312
+ b.tagName==="w:sdt"?this.getDirectChild(b,"w:sdtPr"):void 0;let D=-1,$,j;y&&(h(),D=a.length,$=this.generateId(),j=this.sdtAncestorStack[this.sdtAncestorStack.length-1]?.id,this.sdtAncestorStack.push({
313
+ el:b,id:$}));let W;try{W=await this.parseBodyChild(b,r,t)}finally{y&&this.sdtAncestorStack.pop()}for(const E of W){if(E.kind==="list-item"){if(!o||o.numId!==E.list.numId||o.variant!==E.list.variant){h();
314
+ const T=E.list.variant==="ordered",O=T?c(E.list):null;o={numId:E.list.numId,variant:E.list.variant,list:{type:"list",id:this.generateId(),variant:E.list.variant,children:[],startNumber:T?p(E.list):void 0,
315
+ lineSpacing:E.list.lineSpacing,...T&&E.list.formatSpec?{numberingFormat:E.list.formatSpec}:{}}},O&&(o.list.numberingChainId=O.chainId,O.started=!0,O.seenNumIds.add(E.list.numId))}o.list.lineSpacing===
316
+ void 0&&E.list.lineSpacing!==void 0&&(o.list.lineSpacing=E.list.lineSpacing),o.list.spaceBefore===void 0&&this.applyDocxParagraphSpacing(o.list,E.list);for(const T of["lineSpacing","spaceBefore","spac\
317
+ eAfter"])(E.item[T]===void 0||E.item[T]===o.list[T])&&delete E.item[T];this.markWholeListItemRevision(o.list,E.item),this.markListItemPropertyChange(o.list,E.item),o.list.children.push(E.item),u(o.list,
318
+ g);continue}h(),a.push(E.block),u(E.block,g)}if(y&&D>=0){h();const E=a.slice(D).map(T=>T.id).filter(T=>!!T);if(E.length>0&&i)try{const T=new XMLSerializer().serializeToString(y);i.push({id:$??this.generateId(),
319
+ prXml:T,...j?{parentId:j}:{},blockIds:E})}catch{}}}return h(),a}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,
320
+ a=n.length>0&&n[n.length-1].el===e;let o;if(!a&&n.length>0&&this.importSdtWrappers){const l=this.getDirectChild(e,"w:sdtPr");if(l)try{o={id:this.generateId(),prXml:new XMLSerializer().serializeToString(
321
+ l),parentId:n[n.length-1].id}}catch{}}o&&n.push({el:e,id:o.id});const s=[];try{for(let l=0;l<i.children.length;l++)s.push(...await this.parseBodyChild(i.children[l],r,t))}finally{o&&n.pop()}if(o&&this.
322
+ importSdtWrappers){const l=s.filter(c=>c.kind==="block").map(c=>c.block.id).filter(c=>!!c);l.length>0&&(o.blockIds=l,this.importSdtWrappers.push(o))}return s}if(e.tagName==="w:p"){const i=await this.parseWordParagraphBlocks(
323
+ e,r,t),n=this.getDirectChild(e,"w:pPr"),a=n?this.getDirectChild(n,"w:sectPr"):void 0;if(a){const s={...this.parseSectionPropertiesElement(a),...this.getDirectChild(a,"w:pgBorders")?{}:{pageBorders:null}},
324
+ l=i.find(m=>m.type==="paragraph"&&m.__pilcrowRevision),c=l?.__pilcrowRevision?.kind==="merge"?l.__pilcrowRevision:void 0;c&&l&&delete l.__pilcrowRevision;const p={kind:"block",block:{type:"section-bre\
325
+ ak",id:this.generateId(),...s?{layout:s}:{},...c?{diffState:"delete",suggestionId:c.meta.revisionId?`docxrev-${c.meta.revisionId}`:this.generateId(),...c.meta.author?{suggestionAuthorName:c.meta.author}:
326
+ {},...c.meta.createdAt!==void 0?{suggestionCreatedAt:c.meta.createdAt}:{}}:{}}};if(i.length===1&&i[0].type==="paragraph"&&!i[0].__pilcrowRevision&&i[0].children.every(m=>m.type==="text"&&m.text.length===
327
+ 0))return[p];const h=[];for(const m of i)h.push({kind:"block",block:m});return h.push(p),h}const o=[];for(const s of i){if(s.type!=="paragraph"){o.push({kind:"block",block:s});continue}const l=this.codeBlockFromStyledParagraph(
328
+ s);if(l){o.push({kind:"block",block:l});continue}const c=this.resolveParagraphProperties(e,r,t);if(!c.list){const p=this.todoItemFromParagraph(s,c);if(p){o.push(p);continue}o.push({kind:"block",block:s});
329
+ continue}o.push({kind:"list-item",list:c.list,item:this.carryPilcrowMove(s,{type:"list-item",id:this.generateId(),children:s.children,lineSpacing:c.lineSpacing,spaceBefore:c.spaceBefore,spaceAfter:c.spaceAfter,
330
+ indentLevel:c.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.
331
+ length;n++)i.push(...await this.parseBodyChild(e.children[n],r,t));return i}if(!Ur.has(e.tagName))try{return[{kind:"block",block:{type:"docx-raw",id:this.generateId(),origin:"body",...lr(e)}}]}catch{}
332
+ 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("_"))
333
+ return;const i=t.startsWith("_")?t.slice(1):void 0,n=e.children.filter(a=>a.type==="text").map(a=>a.text).join("");return{type:"code",id:e.id??this.generateId(),content:n,...i?{language:i}:{}}}static todoItemFromParagraph(e,r){
334
+ if(e.styleId||r.heading)return;const t=e.children[0];if(!t||t.type!=="text")return;const i=this.TODO_MARKERS.find(([s])=>t.text.startsWith(s));if(!i)return;const n=t.text.slice(i[0].length),a=[...n.length>
335
+ 0?[{...t,text:n}]:[],...e.children.slice(1)].filter(s=>s.type==="text");a.length===0&&a.push({type:"text",text:""});const o=Math.max(0,Math.round(Number(e.leftIndent??0)>0?Number(e.leftIndent)-1:0));return{
336
+ 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(
337
+ e,{type:"list-item",id:this.generateId(),children:a,lineSpacing:r.lineSpacing,spaceBefore:r.spaceBefore,spaceAfter:r.spaceAfter,indentLevel:o,...i[1]?{checked:!0}:{}})}}static carryPilcrowMove(e,r){const t=e.
338
+ __pilcrowMove;t&&(r.__pilcrowMove=t);const i=e.__pilcrowRevision;i&&(r.__pilcrowRevision=i);const n=e.__propertyChange;return n&&(r.__propertyChange=n),r}static buildBlocksFromParagraphItems(e,r){const t=[];
339
+ let i=[];const n=(a=!1)=>{if(i.length===0&&!a)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&&
340
+ (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(
341
+ 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 s=r.styleId;s&&s.
342
+ toLowerCase()!=="normal"&&(o.styleId=s),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.
343
+ push(o),i=[]};for(const a of e){if(a.kind==="text"){i.push(a.node);continue}if(a.kind==="pagebreak"){n(),t.push(this.createPageBreakBlock());continue}if(a.kind==="blocks"){n(),t.push(...a.blocks);continue}
344
+ n(),t.push(a.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.
345
+ getDirectChild(i||e,"w:pStyle")?.getAttribute("w:val")||void 0,a={isList:!1,styleId:n},o=this.effectiveParagraphStyleId(n,t.styles),s=[];t.styles.paragraphDefault&&s.push(t.styles.paragraphDefault),s.
346
+ push(...this.resolveStyleChainPPr(o,t.styles,"paragraph")),i&&s.push(i);const l=this.resolveParagraphFontSizePx(i,o,t);for(const c of s)this.applyParagraphPropertiesFromElement(a,c,r,t,l);return this.
347
+ resolveLogicalAlignment(a),a}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,
348
+ a=e/20*(4/3),o=Math.round(a/n*100)/100;return i==="atleast"?o>hn.paragraph?o:void 0:Math.max(.1,o)}static effectiveParagraphStyleId(e,r){return e??r.defaultStyleIdByType?.get("paragraph")}static resolveParagraphFontSizePx(e,r,t){
349
+ 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.
350
+ 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=[],
351
+ n=new Set;let a=r.stylesById.get(e);for(;a&&!n.has(a.id);)n.add(a.id),(!t||a.type===t)&&i.unshift(a),a=a.basedOn?r.stylesById.get(a.basedOn):void 0;return i}static applyParagraphPropertiesFromElement(e,r,t,i,n){
352
+ 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:widowCo\
353
+ ntrol")&&(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,
354
+ r),this.applyJcFromPPr(e,r);const a=this.getDirectChild(r,"w:ind");if(a){const g=this.parseTwipsAttribute(a,"w:start")??this.parseTwipsAttribute(a,"w:left");if(g===0)e.leftIndent=0;else if(g!==void 0&&
355
+ g>0){const y=Lt(this.twipsToPx(g),{indentStepPx:t,storedAsUnits:!1});y!==void 0&&(e.leftIndent=y)}const b=this.parseTwipsAttribute(a,"w:firstLine"),v=this.parseTwipsAttribute(a,"w:hanging");if(v!==void 0&&
356
+ v>0)e.firstLineIndent=-1;else if(b===0)e.firstLineIndent=0;else if(b!==void 0&&b>0){const y=Lt(this.twipsToPx(b),{indentStepPx:t,storedAsUnits:!1,firstLine:!0});y!==void 0&&(e.firstLineIndent=y)}}const o=this.
357
+ parseOnOffElement(this.getDirectChild(r,"w:pageBreakBefore"));o!==void 0&&(e.pageBreakBefore=o);const s=this.getDirectChild(r,"w:spacing"),l=s?.getAttribute("w:line");if(l){const g=parseInt(l,10);if(Number.
358
+ isFinite(g)&&g>0){const b=this.lineSpacingFromDocxSpacing(g,s?.getAttribute("w:lineRule"),n);b!==void 0&&(e.lineSpacing=b)}}const c=g=>Math.max(0,Math.round(this.twipsToPx(g)*100)/100),p=this.parseTwipsAttribute(
359
+ s,"w:before");p!==void 0&&(e.spaceBefore=c(p));const h=this.parseTwipsAttribute(s,"w:after");h!==void 0&&(e.spaceAfter=c(h)),this.getDirectChild(r,"w:contextualSpacing")&&(e.contextualSpacing=this.isOn(
360
+ r,"w:contextualSpacing"));const m=this.getDirectChild(r,"w:outlineLvl")?.getAttribute("w:val"),f=m?parseInt(m,10):NaN;Number.isFinite(f)&&f>=0&&f<6&&(e.heading=f+1);const w=this.getDirectChild(r,"w:pS\
361
+ tyle")?.getAttribute("w:val");if(w){e.styleId=w;const g=i?this.headingLevelForStyle(i.styles.stylesById.get(w)):this.headingLevelForStyle({id:w});g&&(e.heading=g)}const u=i?this.getDirectChild(r,"w:nu\
362
+ mPr"):void 0;if(u&&i){const g=this.getDirectChild(u,"w:ilvl"),b=this.getDirectChild(u,"w:numId")?.getAttribute("w:val"),v=g?.getAttribute("w:val"),y=v&&Number.isFinite(parseInt(v,10))?parseInt(v,10):0;
363
+ if(b&&b!=="0"){const D=this.resolveListInfo(b,y,i.numbering);D&&(e.list={...D,lineSpacing:e.lineSpacing,spaceBefore:e.spaceBefore,spaceAfter:e.spaceAfter,contextualSpacing:e.contextualSpacing},e.isList=
364
+ !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(
365
+ i[1],10)}}static resolveListInfo(e,r,t){const i=t.nums.get(e),n=i?.abstractNumId?t.abstractNums.get(i.abstractNumId):void 0,a=n?.levels.get(r);if(!a)return;const o=(a.format||"").toLowerCase()==="bull\
366
+ et"?"unordered":"ordered",s=i?.levelStartOverrides.get(r)??a.start;let l;if(o==="ordered"&&n){const c=[];let p=!1;for(let h=0;h<=2;h++){const m=n.levels.get(h);(m?.format||m?.text)&&(p=!0),c.push({...m?.
367
+ format?{numFmt:m.format}:{},...m?.text?{lvlText:m.text}:{}})}p&&(l=JSON.stringify(c))}return{numId:e,level:r,variant:o,startNumber:s,abstractNumId:i?.abstractNumId,hasLevel0StartOverride:i?.levelStartOverrides.
368
+ has(0)??!1,formatSpec:l}}static async parseHyperlinkItems(e,r,t){const i=e.getAttribute("r:id"),n=e.getAttribute("w:anchor"),a=(i?t?.relationships.get(i)?.target:void 0)||(n?`#${n}`:void 0),o=[];for(let s=0;s<
369
+ e.children.length;s++){const l=e.children[s];if(!(this.trackBookmarkMarker(l,t)||this.trackOxmlRangeMarker(l,t))){if(l.tagName==="w:ins"||l.tagName==="w:del"){const c=await this.parseTrackedChangeItems(
370
+ l,r,t),p=h=>{const m={...h,link:h?.link??a};if(m.suggestionPriorAttributes)try{const f=JSON.parse(m.suggestionPriorAttributes);f&&typeof f=="object"&&!f.link&&(m.suggestionPriorAttributes=JSON.stringify(
371
+ {...f,link:a}))}catch{}return m};o.push(...c.map(h=>h.kind==="text"&&a?{...h,node:{...h.node,marks:p(h.node.marks)}}:h));continue}l.tagName==="w:r"&&o.push(...await this.parseWordRunItems(l,r,t,a))}}return o}static revisionAuthorIdentity(e){
372
+ return e?.trim()===Ct?{suggestionSource:"agent",suggestionAuthorType:"ai"}:{suggestionSource:"manual",suggestionAuthorType:"human"}}static indexImportedMoveRanges(e){const r=new WeakMap,t={from:[],to:[]},
373
+ i=(a,o)=>{const s=a?.getAttribute("w:name")?.trim(),l=a?.getAttribute("w:id")?.trim();if(!a||!s||!l)return;const c=a.getAttribute("w:date"),p=c?Date.parse(c):NaN;return{version:1,name:s,role:o,rangeId:l,
374
+ ...a.getAttribute("w:author")?.trim()?{rangeAuthor:a.getAttribute("w:author").trim()}:{},...Number.isFinite(p)?{rangeCreatedAt:p}:{}}},n=Array.from(e.getElementsByTagName("*"));for(let a=0;a<n.length;a++){
375
+ const o=n[a],s=o.tagName==="w:moveFromRangeStart"?"from":o.tagName==="w:moveToRangeStart"?"to":void 0;if(s){const p=i(o,s);p&&t[s].push(p);continue}const l=o.tagName==="w:moveFrom"?"from":o.tagName===
376
+ "w:moveTo"?"to":void 0;if(l){let p=t[l][t[l].length-1];const h=o.parentElement,m=h?.parentElement;!p&&h?.tagName==="w:rPr"&&m?.tagName==="w:pPr"&&m.parentElement?.tagName==="w:p"&&(p=i(m.parentElement.
377
+ getElementsByTagName(l==="from"?"w:moveFromRangeStart":"w:moveToRangeStart")[0],l));const f=o.getAttribute("w:id")?.trim();p&&f&&r.set(o,{...p,wrapperId:f,fallbackSuggestionId:`docxrev-${f}`});continue}
378
+ const c=o.tagName==="w:moveFromRangeEnd"?"from":o.tagName==="w:moveToRangeEnd"?"to":void 0;if(c){const p=o.getAttribute("w:id")?.trim(),h=t[c],m=p?h.map(f=>f.rangeId).lastIndexOf(p):h.length-1;m>=0&&h.
379
+ splice(m,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.
380
+ 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,
381
+ 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 a=this.parseDocxMoveMark(n.marks.docxMove);if(a){const o=r.get(a.
382
+ name)??{roles:new Set,nodes:[]};o.roles.add(a.role),o.nodes.push(n),r.set(a.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){
383
+ const a=this.parseDocxMoveMark(n.marks?.docxMove);!a||!n.marks||(n.marks.suggestionId=a.fallbackSuggestionId,delete n.marks.docxMove)}}static hasDocxMoveMarks(e){if(!e||typeof e!="object")return!1;if(Array.
384
+ 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)
385
+ return;const i=e.tabStops?[...e.tabStops]:[];for(let n=0;n<t.children.length;n++){const a=t.children[n];if(a.tagName!=="w:tab")continue;const o=parseFloat(a.getAttribute("w:pos")||"");if(!Number.isFinite(
386
+ o)||o<0)continue;const s=this.twipsToPx(o),l=i.findIndex(f=>Math.abs(f.pos-s)<.5);l>=0&&i.splice(l,1);const c=(a.getAttribute("w:val")||"left").toLowerCase();if(c==="clear")continue;let p;if(c==="righ\
387
+ t"||c==="end")p="right";else if(c==="center")p="center";else if(c==="decimal")p="decimal";else if(c==="left"||c==="start"||c==="num")p="left";else continue;const h={pos:s,align:p},m=(a.getAttribute("w\
388
+ :leader")||"").toLowerCase();m==="dot"||m==="middledot"?h.leader="dot":m==="hyphen"?h.leader="hyphen":(m==="underscore"||m==="heavy")&&(h.leader="underscore"),i.push(h)}i.sort((n,a)=>n.pos-a.pos),i.length>
389
+ 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 a of[
390
+ "top","bottom","left","right"]){const o=this.getDirectChild(t,`w:${a}`);if(!o)continue;const s=(o.getAttribute("w:val")||"single").toLowerCase();if(s==="none"||s==="nil"){n[a]={style:"none",width:0,color:"\
391
+ #000000"};continue}const l=["dashed","dotted","double"].includes(s)?s:"single",c=parseInt(o.getAttribute("w:sz")||"4",10),p=Math.max(.5,Math.round((Number.isFinite(c)?c:4)/6*100)/100),h=(o.getAttribute(
392
+ "w:color")||"auto").trim(),m=h.toLowerCase()==="auto"?"#000000":`#${h.replace(/^#/,"")}`;n[a]={style:l,width:p,color:m}}Object.keys(n).length>0&&(r.bordersJson=JSON.stringify(n))}const i=this.getDirectChild(
393
+ e,"w:shd");if(i){const n=(i.getAttribute("w:fill")||"").trim(),a=(i.getAttribute("w:val")||"clear").toLowerCase();n&&n.toLowerCase()!=="auto"?r.shading=`#${n.replace(/^#/,"")}`:(!n||n.toLowerCase()===
394
+ "auto"||a==="nil"||a==="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(
395
+ "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.
396
+ 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.
397
+ 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=
398
+ new Map)).set(i,n)}catch{}return!0}for(const[i,n]of this.OXML_RANGE_PAIRS){if(e.tagName!==n)continue;const a=e.getAttribute("w:id"),o=a?t.openOxmlRanges?.get(a):void 0;if(o&&a){try{o.endXml=new XMLSerializer().
399
+ serializeToString(e),this.importOxmlRanges?.push(o)}catch{}t.openOxmlRanges.delete(a)}return!0}return!1}static async parseFldSimpleItems(e,r,t){const i=(e.getAttribute("w:instr")||"").trim(),n=await this.
400
+ parseInlineItemsFromChildren(e,r,t);if(!i)return n;for(const a of n)a.kind==="text"&&a.node&&(a.node.marks={...a.node.marks??{},fieldInstr:i});return n}static trackCommentRangeMarker(e,r){const t=r??this.
401
+ 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.
402
+ 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().
403
+ 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,
404
+ "w:sdtContent");if(!i)return[];const n=this.importSdtWrappers;let a;if(n){const s=this.getDirectChild(e,"w:sdtPr");if(s)try{const l=this.sdtAncestorStack[this.sdtAncestorStack.length-1];a={id:this.generateId(),
405
+ prXml:new XMLSerializer().serializeToString(s),scope:"inline",...l?{parentId:l.id}:{}}}catch{}}a&&this.sdtAncestorStack.push({el:e,id:a.id});let o;try{o=await this.parseInlineItemsFromChildren(i,r,t)}finally{
406
+ a&&this.sdtAncestorStack.pop()}if(a&&n){let s=!1;for(const l of o)if(l.kind==="text"&&l.node){const c=l.node.marks?.sdtInline;l.node.marks={...l.node.marks??{},sdtInline:c?`${c},${a.id}`:a.id},s=!0}s&&
407
+ n.push(a)}return o}static async parseInlineItemsFromChildren(e,r,t){const i=[];for(let n=0;n<e.children.length;n++){const a=e.children[n];if(!this.trackCommentRangeMarker(a,t)&&!(this.trackBookmarkMarker(
408
+ a,t)||this.trackOxmlRangeMarker(a,t))){if(a.tagName==="w:fldSimple"){i.push(...await this.parseFldSimpleItems(a,r,t));continue}if(a.tagName==="mc:AlternateContent"){const o=this.selectAlternateContentBranch(
409
+ a);o&&i.push(...await this.parseInlineItemsFromChildren(o,r,t));continue}a.tagName==="w:r"?i.push(...this.stampOpenComments(await this.parseWordRunItems(a,r,t),t)):a.tagName==="w:hyperlink"?i.push(...await this.
410
+ parseHyperlinkItems(a,r,t)):a.tagName==="w:ins"||a.tagName==="w:del"||a.tagName==="w:moveFrom"||a.tagName==="w:moveTo"?i.push(...await this.parseTrackedChangeItems(a,r,t)):a.tagName==="w:sdt"&&i.push(
411
+ ...await this.parseInlineSdtItems(a,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(
412
+ 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",a=e.tagName===
413
+ "w:moveFrom"||e.tagName==="w:moveTo",o=this.parseTrackedRevisionMeta(e),s=a?(t??this.fallbackCommentState).moveRangeByWrapper?.get(e):void 0,l=s?`docxmove-${encodeURIComponent(s.name)}`:o.revisionId?`\
414
+ docxrev-${o.revisionId}`:this.generateId(),c={...n?{insertion:!0}:{deletion:!0},suggestionId:l,...this.revisionAuthorIdentity(o.author),suggestionLabel:a?"Move":n?"Insert":"Delete",...o.createdAt!==void 0?
415
+ {suggestionCreatedAt:o.createdAt}:{},...o.author?{suggestionAuthorName:o.author}:{},...s?{docxMove:JSON.stringify(s)}:{},...!n&&i?{layeredInsertion:JSON.stringify(i)}:{}},p=m=>m.map(f=>f.kind==="text"?
416
+ {...f,node:{...f.node,marks:{...f.node.marks??{},...c}}}:f),h=[];for(let m=0;m<e.children.length;m++){const f=e.children[m];this.trackCommentRangeMarker(f,t)||this.trackBookmarkMarker(f,t)||this.trackOxmlRangeMarker(
417
+ f,t)||(f.tagName==="w:r"?h.push(...p(this.stampOpenComments(await this.parseWordRunItems(f,r,t),t))):f.tagName==="w:hyperlink"?h.push(...p(this.stampOpenComments(await this.parseHyperlinkItems(f,r,t),
418
+ t))):f.tagName==="w:del"&&n?h.push(...await this.parseTrackedChangeItems(f,r,t,{id:l,...(()=>{const w=this.revisionAuthorIdentity(o.author);return{source:w.suggestionSource,authorType:w.suggestionAuthorType}})(),
419
+ createdAt:o.createdAt,label:"Insert",authorName:o.author})):(f.tagName==="w:ins"||f.tagName==="w:del")&&h.push(...await this.parseTrackedChangeItems(f,r,t)))}return h}static async parseWordRunItems(e,r,t,i,n){
420
+ const a=this.getDirectChild(e,"w:rPr"),o=n?{...n}:this.resolveRunMarks(a,r.styleId,t,i);if(!n&&!r.heading&&o.fontSize===Ae.paragraph&&this.docDefaultRunSizePx(t)===Ae.paragraph&&delete o.fontSize,!n){
421
+ const m=at(a,Xr);m&&(o.oxmlRPr=m)}const s=!n&&a?this.getDirectChild(a,"w:rPrChange"):void 0;if(s){const m=this.parseTrackedRevisionMeta(s),f=this.getDirectChild(s,"w:rPr"),w=this.resolveRunMarks(f,r.styleId,
422
+ t,i);Object.assign(o,{formatChange:!0,suggestionId:m.revisionId?`docxrev-${m.revisionId}`:this.generateId(),...this.revisionAuthorIdentity(m.author),suggestionLabel:"Format",...m.createdAt!==void 0?{suggestionCreatedAt:m.
423
+ createdAt}:{},...m.author?{suggestionAuthorName:m.author}:{},suggestionPriorAttributes:JSON.stringify(w??{})})}const l=[];let c="";const p=t??this.fallbackCommentState,h=()=>{if(!c)return;const m={...o},
424
+ f=p.openBookmarkNames;f&&f.size>0&&(m.bookmark=[...f].sort().join(","));const w=p.openOxmlRanges;w&&w.size>0&&(m.oxmlRange=[...w.values()].map(g=>g.id).sort().join(","));const u=p.fieldInstrStack?.[0];
425
+ u?.inResult&&u.instr.trim()&&(m.fieldInstr=u.instr.trim()),l.push({kind:"text",node:{type:"text",text:c,marks:Object.keys(m).length>0?m:void 0}}),c=""};for(let m=0;m<e.children.length;m++){const f=e.children[m];
426
+ if(f.tagName==="w:t"){c+=f.textContent||"";continue}if(f.tagName==="w:fldChar"){const w=f.getAttribute("w:fldCharType"),u=p.fieldInstrStack??(p.fieldInstrStack=[]);h(),w==="begin"?u.push({instr:"",inResult:!1}):
427
+ w==="separate"?u.length>0&&(u[u.length-1].inResult=!0):w==="end"&&u.pop();continue}if(f.tagName==="w:instrText"){const w=p.fieldInstrStack;w&&w.length>0&&(w[w.length-1].instr+=f.textContent||"");continue}
428
+ if(f.tagName==="w:footnoteReference"||f.tagName==="w:endnoteReference"){const w=f.getAttribute("w:id");if(w){h();const u=f.tagName==="w:endnoteReference"?"docxen":"docxfn";l.push({kind:"text",node:{type:"\
429
+ text",text:"0",marks:{...o,footnoteRef:`${u}-${w}`,superscript:!0}}})}continue}if(f.tagName==="w:delText"){c+=f.textContent||"";continue}if(f.tagName==="w:tab"){c+=" ";continue}if(f.tagName==="w:br"){
430
+ (f.getAttribute("w:type")||"").trim().toLowerCase()==="page"?(h(),l.push({kind:"pagebreak"})):c+=`
431
+ `;continue}if(f.tagName!=="w:lastRenderedPageBreak"){if(f.tagName==="mc:AlternateContent"){h();const w=this.selectAlternateContentBranch(f);w&&l.push(...await this.parseWordRunItems(w,r,t,i,o));continue}
432
+ if(f.tagName==="w:drawing"){h();const w=await this.parseImageFromDrawing(f,r.align,t);w&&l.push({kind:"image",node:w});const u=await this.parseTextBoxContent(f,t);if(u.length>0&&l.push({kind:"blocks",
433
+ blocks:u}),!w&&u.length===0){const g=this.rawChipFromRunChild(f);g&&l.push({kind:"blocks",blocks:[g]})}continue}if(f.tagName==="w:pict"||f.tagName==="w:object"){h();const w=f.getElementsByTagName("*");
434
+ let u=!1;for(let b=0;b<w.length;b++){const v=(w[b].getAttribute("o:hr")||"").toLowerCase();if(v==="t"||v==="true"||v==="1"){u=!0;break}}if(u){const b={type:"paragraph",id:this.generateId(),children:[{
435
+ type:"text",text:"",marks:{}}],borders:Bi()};l.push({kind:"blocks",blocks:[b]});continue}const g=await this.parseTextBoxContent(f,t);if(g.length>0)l.push({kind:"blocks",blocks:g});else{const b=this.rawChipFromRunChild(
436
+ f);b&&l.push({kind:"blocks",blocks:[b]})}continue}}}return h(),l}static rawChipFromRunChild(e){try{return{type:"docx-raw",id:this.generateId(),origin:"run",...lr(e)}}catch{return}}static async parseTextBoxContent(e,r){
437
+ const t=e.getElementsByTagName("w:txbxContent");if(t.length===0)return[];const i=Ee(void 0).indentStepPx,n=[];for(let a=0;a<t.length;a++){const o=t[a];let s=o.parentElement,l=!1;for(;s&&s!==e;){if(s.tagName===
438
+ "mc:Fallback"){const p=s.parentElement,h=p?Array.from(p.children).find(m=>m.tagName==="mc:Choice"):void 0;l=!!(h&&h.getElementsByTagName("w:txbxContent").length>0);break}s=s.parentElement}if(l)continue;
439
+ const c=(await this.parseBodyChildren(o,i,r)).filter(p=>p.type!=="paragraph"||p.children.some(h=>h.type==="text"&&h.text.trim()!==""));n.push(...c)}return n}static selectAlternateContentBranch(e){let r;
440
+ 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:del\
441
+ Text").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 a=[];t.styles.runDefault&&
442
+ a.push(t.styles.runDefault),a.push(...this.resolveStyleChainRPr(this.effectiveParagraphStyleId(r,t.styles),t.styles,"paragraph"));const o=e&&this.getDirectChild(e,"w:rStyle")?.getAttribute("w:val")||void 0;
443
+ a.push(...this.resolveStyleChainRPr(o,t.styles,"character")),e&&a.push(e);for(const s of a)this.applyRunPropertiesFromElement(n,s,t.themeFonts);o===this.CODE_INLINE_STYLE_ID&&(n.code=!0,/courier/i.test(
444
+ 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){
445
+ if(!r)return;const i=(y,D)=>{this.getDirectChild(r,y)&&(e[D]=this.isOn(r,y))},n=()=>new Set(e.docxRunPropertyResets?.split(",").map(y=>y.trim()).filter(Boolean)??[]),a=(y,D)=>{const $=n();D?$.add(y):$.
446
+ 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(
447
+ "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(
448
+ "w:vanish","hidden");const s=this.getDirectChild(r,"w:lang")?.getAttribute("w:val");s&&(e.lang=s);const l=(this.getDirectChild(r,"w:spacing")?.getAttribute("w:val")||"").trim();if(l!==""){const y=parseInt(
449
+ l,10);Number.isFinite(y)&&(e.letterSpacing=Math.round(y/15*100)/100)}const c=(this.getDirectChild(r,"w:vertAlign")?.getAttribute("w:val")||"").toLowerCase();c==="superscript"?(e.superscript=!0,e.subscript=
450
+ !1):c==="subscript"?(e.superscript=!1,e.subscript=!0):c==="baseline"&&(e.superscript=!1,e.subscript=!1);const p=this.getDirectChild(r,"w:color"),h=p?.getAttribute("w:val");p&&h?.toLowerCase()==="auto"?
451
+ (delete e.color,a("color",!0)):h&&(e.color=`#${h.replace(/^#/,"")}`,a("color",!1));const m=this.getDirectChild(r,"w:highlight")?.getAttribute("w:val");m?.toLowerCase()==="none"?(delete e.backgroundColor,
452
+ a("highlight",!0)):m&&(e.backgroundColor=this.highlightValueToColor(m),a("highlight",!1));const f=this.getDirectChild(r,"w:shd")?.getAttribute("w:fill");if(f&&["auto","none"].includes(f.toLowerCase()))
453
+ delete e.backgroundColor,a("highlight",!0);else if(f){const y=or(f);y&&(e.backgroundColor=y,a("highlight",!1))}const w=this.getDirectChild(r,"w:rFonts"),u=w?.getAttribute("w:asciiTheme")||w?.getAttribute(
454
+ "w:hAnsiTheme")||w?.getAttribute("w:cstheme")||w?.getAttribute("w:eastAsiaTheme"),g=u&&t?u.toLowerCase().startsWith("major")?t.major:t.minor:void 0,b=w?.getAttribute("w:ascii")||w?.getAttribute("w:hAn\
455
+ si")||w?.getAttribute("w:cs")||w?.getAttribute("w:eastAsia")||g;b&&(e.fontFamily=b);const v=this.getDirectChild(r,"w:sz")?.getAttribute("w:val");if(v){const y=parseInt(v,10);Number.isFinite(y)&&y>0&&(e.
456
+ fontSize=Math.max(1,Math.round(y*(2/3)*100)/100))}}static collectTextlessMoveHalves(e){const r=this.exportLinkedMoveSides,t=s=>{const l=s;let c,p,h=!1;return this.UNTRACKABLE_MOVE_KINDS.has(s.type)?(c=
457
+ l.diffState,p=l.suggestionId,h=!0):s.type==="paragraph"&&s.children.every(m=>m.type==="text"&&m.text==="")&&(c=l.structuralSuggestionKind??l.diffState,p=l.structuralSuggestionId??l.suggestionId),c!=="\
458
+ insert"&&c!=="delete"||!p||!h&&r?.has(p)?null:{kind:c,id:p}},i=s=>{const l={};for(const[c,p]of Object.entries(s))c==="id"||c==="diffState"||c==="suggestionId"||c.startsWith("structuralSuggestion")||(l[c]=
459
+ p);return JSON.stringify(l)},n=new Map;for(const s of e){const l=t(s);if(l?.kind!=="delete")continue;const c=`${l.id}\0${i(s)}`;n.set(c,[...n.get(c)??[],s])}const a=new Set,o=new Set;for(const s of e){
460
+ const l=t(s);if(l?.kind!=="insert")continue;const c=n.get(`${l.id}\0${i(s)}`)?.shift();c&&(a.add(s.id),o.add(c.id))}return{destinations:a,sources:o}}static withoutMoveState(e){const r={};for(const[t,i]of Object.
461
+ entries(e))t==="diffState"||t==="suggestionId"||t.startsWith("structuralSuggestion")||(r[t]=i);return r}static collectLinkedMoveSides(e){const r=new Map,t=i=>{if(!i||typeof i!="object")return;if(Array.
462
+ isArray(i)){i.forEach(t);return}const n=i,a=n.marks;if(n.type==="text"&&a?.docxMove&&typeof a.suggestionId=="string"){const o=this.parseDocxMoveMark(a.docxMove);if(o&&(o.role==="from"&&a.deletion||o.role===
463
+ "to"&&a.insertion)){const s=r.get(a.suggestionId)??{};if(!s[o.role]){const l=this.suggestionRevisionAttrs(a);s[o.role]={move:o,author:o.rangeAuthor??l.author,date:typeof o.rangeCreatedAt=="number"?new Date(
464
+ o.rangeCreatedAt).toISOString():l.date}}r.set(a.suggestionId,s)}}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;
465
+ 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===
466
+ "delete"?"from":o==="insert"?"to":void 0,n=new Map,a=o=>{const s=n.get(o);if(n.delete(o),!s?.marked)return;const l=t.get(o)??new Set;s.ids.forEach(c=>l.add(c)),t.set(o,l)};for(const o of e){const s=new Set,
467
+ l=new Set,c=[],p=h=>{if(!h||typeof h!="object")return;if(Array.isArray(h)){h.forEach(p);return}const m=h;typeof m.id=="string"&&c.push(m.id);const f=i(m.structuralSuggestionKind);typeof m.structuralSuggestionId==
468
+ "string"&&f&&s.add(`${m.structuralSuggestionId}\0${f}`);const w=i(m.diffState);typeof m.suggestionId=="string"&&w&&s.add(`${m.suggestionId}\0${w}`);const u=m.marks;if(m.type==="text"&&u?.docxMove&&typeof u.
469
+ suggestionId=="string"){const g=this.parseDocxMoveMark(u.docxMove);if(g&&(g.role==="from"&&u.deletion||g.role==="to"&&u.insertion)){const b=`${u.suggestionId}\0${g.role}`;s.add(b),l.add(b)}}p(m.children)};
470
+ p(o);for(const h of Array.from(n.keys()))s.has(h)||a(h);for(const h of s){const m=n.get(h)??{marked:!1,ids:[]};m.marked||(m.marked=l.has(h)),m.ids.push(...c),n.set(h,m)}}for(const o of Array.from(n.keys()))
471
+ a(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){
472
+ 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?.
473
+ 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){
474
+ 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!==
475
+ "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;
476
+ const a=t.relationships.get(n);if(!a)return null;const o=i?this.findSvgBlipRelationshipId(i):void 0;let s,l;if(o){const D=t.relationships.get(o),$=D?t.zip.file(D.target):void 0;$&&(s=await $.async("ui\
477
+ nt8array"),l="image/svg+xml")}if(!s||!l){const D=t.zip.file(a.target);if(!D)return null;s=await D.async("uint8array"),l=this.getContentTypeForPart(a.target,t.contentTypes)||this.inferImagePartMimeType(
478
+ a.target)}if(!s)return null;const c=l?this.vectorFormatForMimeType(l):void 0;if(!c&&(!l||!this.isSupportedImageMimeType(l)))return null;const p=e.getElementsByTagName("wp:extent")[0]||e.getElementsByTagName(
479
+ "a:ext")[0],h=p?.getAttribute("cx"),m=p?.getAttribute("cy"),f=h?Math.max(1,Math.round(parseInt(h,10)/9525)):200,w=m?Math.max(1,Math.round(parseInt(m,10)/9525)):200,u=e.getElementsByTagName("wp:docPr")[0],
480
+ g=u?.getAttribute("descr")||u?.getAttribute("title")||u?.getAttribute("name")||void 0,b=this.buildImageDataUrl(s,c?c==="emf"?"image/x-emf":"image/x-wmf":l),v={type:"image",id:this.generateId(),src:b,width:f,
481
+ height:w,alt:g,align:r&&r!=="justify"?r:void 0};c&&(v.originalFormat=c,v.originalDataUrl=b);const y=this.getDirectChild(e,"wp:anchor");if(y)try{v.anchorXml=this.serializeXmlPreservingPrefixes(y)}catch{}
482
+ return v}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(
483
+ "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"wm\
484
+ f":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/\
485
+ x-wmf"||r==="image/wmf")return"wmf"}static async parseTableBlock(e,r,t){const i=[],n=[],a=[],o=(I,X)=>{for(const J of Array.from(I.children))if(J.tagName==="w:tr")X&&X.trIndexes.push(n.length),n.push(
486
+ J);else if(J.tagName==="w:sdt"){const q=this.getDirectChild(J,"w:sdtContent");if(q){let K=X;if(this.importSdtWrappers&&!X){const be=this.getDirectChild(J,"w:sdtPr");if(be)try{K={prXml:new XMLSerializer().
487
+ serializeToString(be),trIndexes:[]},a.push(K)}catch{K=X}}o(q,K)}}};o(e);const s=this.getDirectChild(e,"w:tblPr"),l=s?this.getDirectChild(s,"w:tblCellMar"):void 0,c=l?this.nonUniformCellMarginJson(l):void 0,
488
+ p=this.getDirectChild(e,"w:tblGrid"),h=p?this.getDirectChild(p,"w:tblGridChange"):void 0,m=h?this.getDirectChild(h,"w:tblGrid"):void 0,f=I=>{if(!I)return[];const X=[];for(const J of Array.from(I.children)){
489
+ if(J.tagName!=="w:gridCol")continue;const q=Number(J.getAttribute("w:w"));Number.isFinite(q)&&q>0&&X.push(q)}return X},w=I=>{const X=f(I),J=X.reduce((q,K)=>q+K,0);return J>0?X.map(q=>Math.round(q/J*100)):
490
+ []},u=[],g=[],b=[],v=[],y=[],D=[],$=[],j=s?this.getDirectChild(s,"w:tblPrChange"):void 0,W=j?this.getDirectChild(j,"w:tblPr"):void 0,E=j?this.parseTrackedRevisionMeta(j):null;let T;if(W)try{T=new XMLSerializer().
491
+ serializeToString(W)}catch{T=void 0}const O=new Map,k=new Map,R=[];for(let I=0;I<n.length;I++){const X=n[I],J=this.generateId(),q=this.getDirectChild(X,"w:tblPrEx"),K=q?this.getDirectChild(q,"w:tblPrE\
492
+ xChange"):void 0,be=K?this.getDirectChild(K,"w:tblPrEx"):void 0,de=this.getDirectChild(X,"w:trPr"),ve=de?this.getDirectChild(de,"w:ins"):void 0,Se=de?this.getDirectChild(de,"w:del"):void 0,fe=de?this.
493
+ getDirectChild(de,"w:trPrChange"):void 0,et=fe?this.getDirectChild(fe,"w:trPr"):void 0;if(ve){const we=this.parseTrackedRevisionMeta(ve);u.push({rowId:J,kind:"insert",...we})}else if(Se){const we=this.
494
+ parseTrackedRevisionMeta(Se);u.push({rowId:J,kind:"delete",...we})}de&&fe&&et&&g.push({rowId:J,rowIndex:I,...this.parseTrackedRevisionMeta(fe),currentXml:this.serializePropertiesWithoutRevisionChildren(
495
+ de,new Set(["w:ins","w:del","w:trPrChange"])),priorXml:new XMLSerializer().serializeToString(et),...I===0?{currentTableAttributes:this.tableHeaderAttributesFromRowProperties(de),priorTableAttributes:this.
496
+ tableHeaderAttributesFromRowProperties(et)}:{}}),q&&K&&be&&b.push({rowId:J,rowIndex:I,...this.parseTrackedRevisionMeta(K),currentXml:this.serializePropertiesWithoutRevisionChildren(q,new Set(["w:tblPr\
497
+ ExChange"])),priorXml:new XMLSerializer().serializeToString(be)});const ie=[];let he=0;const ke=[];for(let we=0;we<X.children.length;we++){const Pe=X.children[we];if(Pe.tagName==="w:tc")ke.push({el:Pe});else if(Pe.
498
+ tagName==="w:sdt"){const ce=this.getDirectChild(Pe,"w:sdtContent");if(!ce)continue;let De;if(this.importSdtWrappers){const Re=this.getDirectChild(Pe,"w:sdtPr");if(Re)try{De={prXml:new XMLSerializer().
499
+ serializeToString(Re),cellIds:[]},R.push(De)}catch{De=void 0}}for(const Re of Array.from(ce.children))Re.tagName==="w:tc"&&ke.push({el:Re,sdtGroup:De})}}for(let we=0;we<ke.length;we++){const Pe=ke[we].
500
+ el,ce=this.getDirectChild(Pe,"w:tcPr"),De=this.getDirectChild(ce||Pe,"w:shd")?.getAttribute("w:fill"),Re=ce?this.getDirectChild(ce,"w:gridSpan")?.getAttribute("w:val"):void 0,Nt=Re?parseInt(Re,10):1,Ke=Number.
501
+ isFinite(Nt)?Math.min(Math.max(1,Nt),1e3):1,tt=ce?this.getDirectChild(ce,"w:cellIns"):void 0,ft=ce?this.getDirectChild(ce,"w:cellDel"):void 0,me=ce?this.getDirectChild(ce,"w:cellMerge"):void 0,dt=ce?this.
502
+ getDirectChild(ce,"w:tcPrChange"):void 0,Ce=dt?this.getDirectChild(dt,"w:tcPr"):void 0,ye={type:"table-cell",id:this.generateId(),backgroundColor:De&&De.toLowerCase()!=="auto"&&De.toLowerCase()!=="non\
503
+ e"?`#${De.replace(/^#/,"")}`:void 0,children:this.applyParagraphMarkRevisions(await this.parseBodyChildren(Pe,r,t))};Ke>1&&(ye.colSpan=Ke);const rt=at(ce,Jr);rt&&(ye.oxmlTcPr=rt);const wt=ce?this.getDirectChild(
504
+ ce,"w:tcBorders"):void 0,Ze=wt?this.parseDocxBordersElement(wt,!1):void 0;Ze&&(ye.borders=Ze);const Fe=ce?this.getDirectChild(ce,"w:tcMar"):void 0,Ve=(Fe?this.parseDocxCellMargins(Fe):void 0)??c;Ve&&(ye.
505
+ padding=Ve);const _e=ce?this.getDirectChild(ce,"w:vAlign")?.getAttribute("w:val"):void 0;(_e==="top"||_e==="center"||_e==="bottom")&&(ye.verticalAlign=_e==="center"?"middle":_e),me&&D.push({rowId:J,gridColumn:he,
506
+ ...this.parseTrackedRevisionMeta(me),...me.getAttribute("w:vMerge")?{vMerge:me.getAttribute("w:vMerge")}:{},...me.getAttribute("w:vMergeOrig")?{vMergeOrig:me.getAttribute("w:vMergeOrig")}:{}});const it=ce?
507
+ this.getDirectChild(ce,"w:vMerge"):void 0,nt=it?.getAttribute("w:val");if(it&&nt!=="restart"){const Ne=O.get(he);if(Ne){if(Ne.cell.rowSpan=(Ne.cell.rowSpan??1)+1,me){const ot=this.parseTrackedRevisionMeta(
508
+ me);$.push({row:I,pos:ie.length,colSpan:Ke,anchorRow:Ne.rowIndex,anchorPos:Ne.cellPos,rowId:J,gridColumn:he,restoredCellId:ye.id,restoredCell:JSON.parse(JSON.stringify(ye)),direction:"merge",...ot,...me.
509
+ getAttribute("w:vMerge")?{vMerge:me.getAttribute("w:vMerge")}:{},...me.getAttribute("w:vMergeOrig")?{vMergeOrig:me.getAttribute("w:vMergeOrig")}:{}})}he+=Ke;continue}}it&&nt==="restart"?O.set(he,{cell:ye,
510
+ rowIndex:I,cellPos:ie.length}):O.delete(he);const pt=me?.hasAttribute("w:vMergeOrig")?me.getAttribute("w:vMergeOrig"):it?nt??"continue":void 0,ht=pt==="restart"||pt==="rest",bt=pt==="continue"||pt==="\
511
+ cont";if(ht)k.set(he,{cell:ye,rowIndex:I,cellPos:ie.length});else if(bt){const Ne=k.get(he);if(Ne&&me&&!it){const ot=this.parseTrackedRevisionMeta(me);$.push({row:I,pos:ie.length,colSpan:Ke,anchorRow:Ne.
512
+ rowIndex,anchorPos:Ne.cellPos,rowId:J,gridColumn:he,restoredCellId:ye.id,restoredCell:JSON.parse(JSON.stringify(ye)),direction:"unmerge",...ot,...me.getAttribute("w:vMerge")?{vMerge:me.getAttribute("w\
513
+ :vMerge")}:{},...me.getAttribute("w:vMergeOrig")?{vMergeOrig:me.getAttribute("w:vMergeOrig")}:{}})}}else k.delete(he);tt&&v.push({cellId:ye.id,kind:"insert",...this.parseTrackedRevisionMeta(tt)}),ft&&
514
+ v.push({cellId:ye.id,kind:"delete",...this.parseTrackedRevisionMeta(ft)}),dt&&Ce&&y.push({rowId:J,cellId:ye.id,rowIndex:I,cellIndex:ie.length,gridColumn:he,...this.parseTrackedRevisionMeta(dt),currentXml:this.
515
+ serializePropertiesWithoutRevisionChildren(ce,new Set(["w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"])),priorXml:new XMLSerializer().serializeToString(Ce),currentAttributes:this.tableCellAttributesFromProperties(
516
+ ce),priorAttributes:this.tableCellAttributesFromProperties(Ce)}),ke[we].sdtGroup?.cellIds.push(ye.id),ie.push(ye),he+=Ke}const Oe={type:"table-row",id:J,children:ie},Ie=sr(X);Ie&&(Oe.oxmlAttrs=Ie);const ct=at(
517
+ de,Hr);ct&&(Oe.oxmlTrPr=ct),i.push(Oe)}if(i.length===0)return null;if(this.importSdtWrappers){const I=this.sdtAncestorStack[this.sdtAncestorStack.length-1];for(const X of a){const J=X.trIndexes.map(q=>i[q]?.
518
+ id).filter(q=>!!q);J.length>0&&this.importSdtWrappers.push({id:this.generateId(),prXml:X.prXml,scope:"row",...I?{parentId:I.id}:{},blockIds:J})}for(const X of R)X.cellIds.length>0&&this.importSdtWrappers.
519
+ push({id:this.generateId(),prXml:X.prXml,scope:"cell",...I?{parentId:I.id}:{},blockIds:[...X.cellIds]})}const M=w(p),S=n[0]?this.getDirectChild(n[0],"w:trPr"):void 0,B=S?this.tableHeaderAttributesFromRowProperties(
520
+ S).hasHeader===!0:!1,_=this.generateId(),F=new Map,H=(I,X,J)=>{const q=I.revisionId?`docxrev-${I.revisionId}`:this.generateId(),K=F.get(q);if(K)return K;const be=this.revisionAuthorIdentity(I.author),
521
+ de={id:q,type:"table-change",tableId:_,source:be.suggestionSource,authorType:be.suggestionAuthorType,label:X,...I.createdAt!==void 0?{createdAt:I.createdAt}:{},...I.author?{agentName:I.author}:{},tableRevision:{
522
+ version:1,suggestionKind:J,markers:[],operations:[]}};return F.set(q,de),de};if(p&&h&&m){const I=this.parseTrackedRevisionMeta(h),X=this.serializePropertiesWithoutRevisionChildren(p,new Set(["w:tblGri\
523
+ dChange"])),J=new XMLSerializer().serializeToString(m),q=w(p),K=w(m),be=H(I,"Change table column widths","format");be.tableRevision.markers.push({kind:"table-grid",revisionId:I.revisionId,author:I.author,
524
+ createdAt:I.createdAt,currentPropertiesXml:X,priorPropertiesXml:J,currentColumnWidths:q,priorColumnWidths:K}),be.tableRevision.operations.push({kind:"grid",currentGridXml:X,priorGridXml:J,currentColumnWidths:q,
525
+ priorColumnWidths:K})}for(const I of u){const X=i.findIndex(K=>K.id===I.rowId),J=i[X];if(!J)continue;const q=H(I,I.kind==="insert"?"Insert table row":"Delete table row",I.kind);q.tableRevision.markers.
526
+ push({kind:I.kind==="insert"?"row-insert":"row-delete",rowId:I.rowId,rowIndex:X,revisionId:I.revisionId,author:I.author,createdAt:I.createdAt}),q.tableRevision.operations.push({kind:"row",action:I.kind,
527
+ rowId:I.rowId,rowIndex:X,row:JSON.parse(JSON.stringify(J))}),J.diffState=I.kind,J.suggestionId=q.id}for(const I of v){let X=-1,J=-1,q,K;for(let ve=0;ve<i.length&&!K;ve++){const Se=i[ve].children.findIndex(
528
+ fe=>fe.id===I.cellId);Se>=0&&(X=ve,J=Se,q=i[ve],K=q.children[Se])}if(!q||!K)continue;const be=Qe({children:i,columnWidths:M}).byId.get(K.id),de=H(I,I.kind==="insert"?"Insert table cell":"Delete table \
529
+ cell",I.kind);de.tableRevision.markers.push({kind:I.kind==="insert"?"cell-insert":"cell-delete",rowId:q.id,cellId:K.id,rowIndex:X,cellIndex:J,gridColumn:be?.col,revisionId:I.revisionId,author:I.author,
530
+ createdAt:I.createdAt}),de.tableRevision.operations.push({kind:"cell",action:I.kind,rowId:q.id,cellId:K.id,cellIndex:J,cell:JSON.parse(JSON.stringify(K))}),K.diffState=I.kind,K.suggestionId=de.id}for(const I of g){
531
+ const X=H(I,"Change table row properties","format");X.tableRevision.markers.push({kind:"row-properties",rowId:I.rowId,rowIndex:I.rowIndex,revisionId:I.revisionId,author:I.author,createdAt:I.createdAt,
532
+ currentPropertiesXml:I.currentXml,priorPropertiesXml:I.priorXml}),X.tableRevision.operations.push({kind:"properties",target:"row",rowId:I.rowId,currentPropertiesXml:I.currentXml,priorPropertiesXml:I.priorXml,
533
+ currentTableAttributes:I.currentTableAttributes,priorTableAttributes:I.priorTableAttributes})}for(const I of b){const X=H(I,"Change row table-style exceptions","format");X.tableRevision.markers.push({
534
+ kind:"row-exception-properties",rowId:I.rowId,rowIndex:I.rowIndex,revisionId:I.revisionId,author:I.author,createdAt:I.createdAt,currentPropertiesXml:I.currentXml,priorPropertiesXml:I.priorXml}),X.tableRevision.
535
+ operations.push({kind:"properties",target:"row-exception",rowId:I.rowId,currentPropertiesXml:I.currentXml,priorPropertiesXml:I.priorXml})}for(const I of y){const X=H(I,"Change table cell properties","\
536
+ format");X.tableRevision.markers.push({kind:"cell-properties",rowId:I.rowId,cellId:I.cellId,rowIndex:I.rowIndex,cellIndex:I.cellIndex,gridColumn:I.gridColumn,revisionId:I.revisionId,author:I.author,createdAt:I.
537
+ createdAt,currentPropertiesXml:I.currentXml,priorPropertiesXml:I.priorXml}),X.tableRevision.operations.push({kind:"properties",target:"cell",rowId:I.rowId,cellId:I.cellId,currentPropertiesXml:I.currentXml,
538
+ priorPropertiesXml:I.priorXml,currentAttributes:I.currentAttributes,priorAttributes:I.priorAttributes})}const U=new Map;for(const I of $){const X=I.revisionId?`docxrev-${I.revisionId}`:this.generateId(),
539
+ J=U.get(X)??[];J.push(I),U.set(X,J)}for(const[I,X]of U){const J=X[0],q={revisionId:J.revisionId,author:J.author,createdAt:J.createdAt},K=H(q,X.every(ie=>ie.direction==="unmerge")?"Split table cells":"\
540
+ Merge table cells","format");K.id!==I&&!F.has(I)&&(F.delete(K.id),K.id=I,F.set(I,K));const be=J.revisionId?D.filter(ie=>ie.revisionId===J.revisionId):X;for(const ie of be)K.tableRevision.markers.push(
541
+ {kind:"cell-merge",rowId:ie.rowId,gridColumn:ie.gridColumn,revisionId:ie.revisionId,author:ie.author,createdAt:ie.createdAt,vMerge:ie.vMerge,vMergeOrig:ie.vMergeOrig});const de=JSON.parse(JSON.stringify(
542
+ i)),ve=new Map,Se=new Set;for(const ie of X){const he=de[ie.anchorRow]?.children[ie.anchorPos],ke=de[ie.row];if(ie.direction==="merge"){if(he?.rowSpan!==void 0){const Ie=he.rowSpan-1;Ie>1?he.rowSpan=Ie:
543
+ delete he.rowSpan}if(ke){const Ie=ve.get(ie.row)??0;ke.children.splice(ie.pos+Ie,0,JSON.parse(JSON.stringify(ie.restoredCell))),ve.set(ie.row,Ie+1)}}else if(he&&(he.rowSpan=(he.rowSpan??1)+1),ke){const Ie=ke.
544
+ children.findIndex(ct=>ct.id===ie.restoredCellId);Ie>=0&&ke.children.splice(Ie,1)}ke&&Se.add(ke.id);const Oe=de[ie.anchorRow];Oe&&Se.add(Oe.id)}const fe=i.filter(ie=>Se.has(ie.id)).map(ie=>JSON.parse(
545
+ JSON.stringify(ie))),et=de.filter(ie=>Se.has(ie.id));K.tableRevision.operations.push({kind:"geometry",pendingRows:fe,acceptedRows:JSON.parse(JSON.stringify(fe)),rejectedRows:et})}if(E&&s&&W){const I=H(
546
+ E,"Change table properties","format"),X=this.serializePropertiesWithoutRevisionChildren(s,new Set(["w:tblPrChange"])),J=T??new XMLSerializer().serializeToString(W);I.tableRevision.markers.push({kind:"\
547
+ table-properties",revisionId:E.revisionId,author:E.author,createdAt:E.createdAt,currentPropertiesXml:X,priorPropertiesXml:J}),I.tableRevision.operations.push({kind:"properties",target:"table",currentPropertiesXml:X,
548
+ priorPropertiesXml:J,currentAttributes:{...this.tableAttributesFromProperties(s,t)},priorAttributes:{...this.tableAttributesFromProperties(W,t)}})}const G=Array.from(F.values()),re=this.tableAttributesFromProperties(
549
+ s,t);return{type:"table",id:_,...G.length>0?{structuralSuggestionRecords:JSON.stringify(G)}:{},children:i,columnWidths:M,...re,...B?{hasHeader:!0}:{},...(()=>{const I=at(s,jr);return I?{oxmlTblPr:I}:{}})()}}static serializePropertiesWithoutRevisionChildren(e,r){
550
+ 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.
551
+ 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.
552
+ parseDocxBordersElement(i,!1):void 0;n&&(r.borders=n);const a=this.getDirectChild(e,"w:tcMar"),o=a?this.parseDocxCellMargins(a):void 0;o&&(r.padding=o);const s=this.getDirectChild(e,"w:gridSpan")?.getAttribute(
553
+ "w:val"),l=s?Number(s):void 0;l&&Number.isFinite(l)&&l>1&&(r.colSpan=l);const c=this.getDirectChild(e,"w:vAlign")?.getAttribute("w:val");return(c==="top"||c==="center"||c==="bottom")&&(r.verticalAlign=
554
+ c==="center"?"middle":c),r}static tableHeaderAttributesFromRowProperties(e){const r=this.getDirectChild(e,"w:tblHeader");if(!r)return{};const t=r.getAttribute("w:val")?.trim().toLowerCase();return t===
555
+ "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\
556
+ :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"),a=n?.getAttribute("w:type"),
557
+ o=Number(n?.getAttribute("w:w"));a==="dxa"&&Number.isFinite(o)&&o>0&&(t.tableWidth=Math.round(o/15));const s=this.getDirectChild(e,"w:tblCellMar"),l=s?this.parseDocxCellMargins(s):void 0;if(l)try{const c=JSON.
558
+ parse(l),p=[c.top,c.right,c.bottom,c.left];p.every(h=>Number.isFinite(h))&&p.every(h=>h===p[0])&&(t.cellPadding=p[0])}catch{}return t}static mapDocxBorderStyle(e){switch((e||"").trim()){case"none":case"\
559
+ 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"doubl\
560
+ e";default:return"single"}}static parseDocxBordersElement(e,r){return Lr(this.parseDocxBordersSpec(e,r))}static resolveTableBordersJson(e,r){const t={},i=s=>{s&&Object.assign(t,this.parseDocxBordersSpec(
561
+ s,!0))},n=r?.styles;if(n){const s=(e&&this.getDirectChild(e,"w:tblStyle")?.getAttribute("w:val")||void 0)??n.defaultStyleIdByType?.get("table"),l=s?this.resolveStyleChain(s,n,"table"):[];for(const c of l)
562
+ i(c.tblPr?this.getDirectChild(c.tblPr,"w:tblBorders"):void 0)}i(e?this.getDirectChild(e,"w:tblBorders"):void 0);const a={style:"none",width:0,color:"#000000"},o={top:t.top??a,bottom:t.bottom??a,left:t.
563
+ left??a,right:t.right??a,insideH:t.insideH??a,insideV:t.insideV??a};return Lr(o)}static parseDocxBordersSpec(e,r){const t=(...l)=>{let c;for(const g of l)if(c=this.getDirectChild(e,g),c)break;if(!c)return;
564
+ const p=this.mapDocxBorderStyle(c.getAttribute("w:val")),h=parseInt(c.getAttribute("w:sz")||"",10),m=p!=="none"&&h===0?"none":p,f=m==="none"?0:Number.isFinite(h)&&h>0?Math.max(.25,Math.round(h/6*100)/
565
+ 100):1,w=(c.getAttribute("w:color")||"").trim(),u=w&&w.toLowerCase()!=="auto"?`#${w.replace(/^#/,"").toLowerCase()}`:"#000000";return{style:m,width:f,color:u}},i={},n=t("w:top"),a=t("w:bottom"),o=t("w\
566
+ :left","w:start"),s=t("w:right","w:end");if(n&&(i.top=n),a&&(i.bottom=a),o&&(i.left=o),s&&(i.right=s),r){const l=t("w:insideH"),c=t("w:insideV");l&&(i.insideH=l),c&&(i.insideV=c)}return i}static nonUniformCellMarginJson(e){
567
+ 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){
568
+ const r=(...o)=>{let s;for(const c of o)if(s=this.getDirectChild(e,c),s)break;if(!s)return;const l=parseInt(s.getAttribute("w:w")||"",10);if(!(!Number.isFinite(l)||l<0))return Math.round(l/15*100)/100},
569
+ t=r("w:top"),i=r("w:bottom"),n=r("w:left","w:start"),a=r("w:right","w:end");if(!(t===void 0&&i===void 0&&n===void 0&&a===void 0))return sn({top:t??0,bottom:i??0,left:n??7.2,right:a??7.2})}static getContentTypeForPart(e,r){
570
+ 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==="ima\
571
+ ge/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(
572
+ 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.
573
+ generateId(),children:[{type:"text",text:"",marks:{}}]}}static createPageBreakBlock(){return{type:"page-break",id:this.generateId()}}static generateId(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkl\
574
+ mnopqrstuvwxyz0123456789";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("\
575
+ 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(
576
+ "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 c=i.replace(/\u00a0/g," "),p={"\\":"\\textb\
577
+ ackslash{}","{":"\\{","}":"\\}","&":"\\&","%":"\\%",$:"\\$","#":"\\#",_:"\\_","^":"\\textasciicircum{}","~":"\\textasciitilde{}"};return`\\text{${c.replace(/[\\{}&%$#_^~]/g,h=>p[h])}}`}const a=this.cleanMathText(
578
+ i),o=n?.getElementsByTagName("m:scr")[0]?.getAttribute("m:val"),s=n?.getElementsByTagName("m:sty")[0]?.getAttribute("m:val"),l={"double-struck":"\\mathbb",script:"\\mathcal",fraktur:"\\mathfrak","sans\
579
+ -serif":"\\mathsf",monospace:"\\mathtt"};return o&&l[o]?`${l[o]}{${a}}`:s==="b"||s==="bi"?`\\mathbf{${a}}`:s==="p"&&/^[A-Za-z]+$/.test(i)?hr.OMML_FUNCTION_NAMES.includes(i)?`\\${i} `:`\\mathrm{${i}}`:
580
+ a}case"m:sSub":{const t=e.getElementsByTagName("m:e")[0],i=e.getElementsByTagName("m:sub")[0],n=t?this.parseOmmlChildren(t):"",a=i?this.parseOmmlChildren(i):"";return`${n}_{${a}}`}case"m:sSup":{const t=e.
581
+ getElementsByTagName("m:e")[0],i=e.getElementsByTagName("m:sup")[0],n=t?this.parseOmmlChildren(t):"",a=i?this.parseOmmlChildren(i):"";return`${n}^{${a}}`}case"m:sSubSup":{const t=e.getElementsByTagName(
582
+ "m:e")[0],i=e.getElementsByTagName("m:sub")[0],n=e.getElementsByTagName("m:sup")[0],a=t?this.parseOmmlChildren(t):"",o=i?this.parseOmmlChildren(i):"",s=n?this.parseOmmlChildren(n):"";return`${a}_{${o}\
583
+ }^{${s}}`}case"m:f":{const t=e.getElementsByTagName("m:num")[0],i=e.getElementsByTagName("m:den")[0],n=t?this.parseOmmlChildren(t):"",a=i?this.parseOmmlChildren(i):"";return e.getElementsByTagName("m:\
584
+ fPr")[0]?.getElementsByTagName("m:type")[0]?.getAttribute("m:val")==="noBar"?`{${n} \\atop ${a}}`:`\\frac{${n}}{${a}}`}case"m:rad":{const t=e.getElementsByTagName("m:deg")[0],i=e.getElementsByTagName(
585
+ "m:e")[0],n=t?this.parseOmmlChildren(t).trim():"",a=i?this.parseOmmlChildren(i):"";return n&&n!=="2"?`\\sqrt[${n}]{${a}}`:`\\sqrt{${a}}`}case"m:nary":{const t=e.getElementsByTagName("m:naryPr")[0],i=e.
586
+ getElementsByTagName("m:sub")[0],n=e.getElementsByTagName("m:sup")[0],a=e.getElementsByTagName("m:e")[0];let o="\\sum";if(t){const h=t.getElementsByTagName("m:chr")[0]?.getAttribute("m:val");h&&(o={"∑":"\
587
+ \\sum","∏":"\\prod","∫":"\\int","∬":"\\iint","∭":"\\iiint","∮":"\\oint","⋃":"\\bigcup","⋂":"\\bigcap"}[h]||"\\sum")}const s=i?this.parseOmmlChildren(i):"",l=n?this.parseOmmlChildren(n):"",
588
+ c=a?this.parseOmmlChildren(a):"";let p=o;return s&&(p+=`_{${s}}`),l&&(p+=`^{${l}}`),p+=` ${c}`,p}case"m:d":{const t=e.getElementsByTagName("m:dPr")[0],i=e.getElementsByTagName("m:e")[0];let n="(",a=")";
589
+ if(t){const l=t.getElementsByTagName("m:begChr")[0],c=t.getElementsByTagName("m:endChr")[0];l?.hasAttribute("m:val")&&(n=l.getAttribute("m:val")??""),c?.hasAttribute("m:val")&&(a=c.getAttribute("m:val")??
590
+ "")}const o=l=>({"":".","{":"\\{","}":"\\}","⟨":"\\langle","⟩":"\\rangle","‖":"\\|","∥":"\\|","∣":"|","⌊":"\\lfloor","⌋":"\\rfloor","⌈":"\\lceil","⌉":"\\rceil"})[l]??l,s=i?this.parseOmmlChildren(
591
+ i):"";return`\\left${o(n)}${s}\\right${o(a)}`}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 a=Array.
592
+ from(t[n].children).filter(s=>s.tagName==="m:e"),o=[];for(let s=0;s<a.length;s++)o.push(this.parseOmmlChildren(a[s]));i+=o.join(" & "),n<t.length-1&&(i+=" \\\\ ")}return i+="\\end{matrix}",i}case"m:ba\
593
+ r":{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}\
594
+ }`:`\\overline{${i}}`}case"m:acc":{const t=e.getElementsByTagName("m:accPr")[0],i=e.getElementsByTagName("m:e")[0],n=i?this.parseOmmlChildren(i):"";let a="\\hat";if(t){const o=t.getElementsByTagName("\
595
+ m:chr")[0]?.getAttribute("m:val");o&&(a={"̂":"\\hat","~":"\\tilde","̃":"\\tilde","̌":"\\check","̆":"\\breve","́":"\\acute","̀":"\\grave","̇":"\\dot","̈":"\\ddot","̄":"\\bar","⃗":"\\vec"}[o]||
596
+ "\\hat")}return`${a}{${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):"",a=i?this.parseOmmlChildren(i):
597
+ "";return r==="m:limLow"?`${n}_{${a}}`:`${n}^{${a}}`}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.
598
+ getElementsByTagName("m:e")[0],i=t?this.parseOmmlChildren(t):"",n=e.getElementsByTagName("m:groupChrPr")[0],a=n?.getElementsByTagName("m:chr")[0]?.getAttribute("m:val");return n?.getElementsByTagName(
599
+ "m:pos")[0]?.getAttribute("m:val")!=="top"&&a!=="⏞"?`\\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(
600
+ 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"),c=Array.from(n.children).find(w=>w.tagName==="m:\
601
+ lim"),p=(l?.textContent??"").trim(),h=i?this.parseOmmlChildren(i):"",m=c?this.parseOmmlChildren(c):"",f=/^[A-Za-z]+$/.test(p)?`\\operatorname*{${p}}`:p;return`${["lim","max","min","sup","inf","liminf",
602
+ "limsup"].includes(p)?`\\${p}`:f}_{${m}} ${h}`}const a=(t?.textContent??"").trim(),o=i?this.parseOmmlChildren(i):"",s=hr.OMML_FUNCTION_NAMES;return s.includes(a)?`\\${a}{${o}}`:s.includes(a.toLowerCase())?
603
+ `\\${a.toLowerCase()}{${o}}`:/^[A-Za-z]+$/.test(a)?`\\operatorname{${a}}{${o}}`:`${a}(${o})`}default:return this.parseOmmlChildren(e)}}static parseOmmlChildren(e){let r="";for(let t=0;t<e.children.length;t++){
604
+ 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","𝐷":"\
605
+ D","𝐸":"E","𝐹":"F","𝐺":"G","𝐻":"H","𝐼":"I","𝐽":"J","𝐾":"K","𝐿":"L","𝑀":"M","𝑁":"N","𝑂":"O","𝑃":"P","𝑄":"Q","𝑅":"R","𝑆":"S","𝑇":"T","𝑈":"U","𝑉":"V",
606
+ "𝑊":"W","𝑋":"X","𝑌":"Y","𝑍":"Z","𝑎":"a","𝑏":"b","𝑐":"c","𝑑":"d","𝑒":"e","𝑓":"f","𝑔":"g",ℎ:"h","𝑖":"i","𝑗":"j","𝑘":"k","𝑙":"l","𝑚":"m","𝑛":"n","𝑜":"\
607
+ o","𝑝":"p","𝑞":"q","𝑟":"r","𝑠":"s","𝑡":"t","𝑢":"u","𝑣":"v","𝑤":"w","𝑥":"x","𝑦":"y","𝑧":"z",α:"\\alpha",β:"\\beta",γ:"\\gamma",δ:"\\delta",ε:"\\epsilon",ζ:"\\zeta",
608
+ η:"\\eta",θ:"\\theta",ι:"\\iota",κ:"\\kappa",λ:"\\lambda",μ:"\\mu",ν:"\\nu",ξ:"\\xi",π:"\\pi",ρ:"\\rho",σ:"\\sigma",τ:"\\tau",υ:"\\upsilon",φ:"\\phi",χ:"\\chi",ψ:"\\psi",ω:"\\omega",Γ:"\
609
+ \\Gamma",Δ:"\\Delta",Θ:"\\Theta",Λ:"\\Lambda",Ξ:"\\Xi",Π:"\\Pi",Σ:"\\Sigma",Φ:"\\Phi",Ψ:"\\Psi",Ω:"\\Omega","∞":"\\infty","∂":"\\partial","∇":"\\nabla","±":"\\pm","∓":"\\mp","×":"\\t\
610
+ imes","÷":"\\div","≠":"\\neq","≈":"\\approx","≤":"\\leq","≥":"\\geq","∈":"\\in","∉":"\\notin","⊂":"\\subset","⊃":"\\supset","∪":"\\cup","∩":"\\cap","→":"\\rightarrow","←":"\\le\
611
+ ftarrow","⇒":"\\Rightarrow","⇐":"\\Leftarrow","⇔":"\\Leftrightarrow","∀":"\\forall","∃":"\\exists","∄":"\\nexists","∴":"\\therefore","∵":"\\because","…":"\\ldots","⋯":"\\cdots","⋮":"\
612
+ \\vdots","⋱":"\\ddots"},t={"&":"\\&","%":"\\%","#":"\\#",$:"\\$","{":"\\{","}":"\\}"};let i="";for(const n of e){const a=r[n];a?i+=a.startsWith("\\")?`${a} `:a:i+=t[n]??n}return i}static async loadZipFromBlob(e){
613
+ const r=typeof e.arrayBuffer=="function"?await e.arrayBuffer():e;return _r.loadAsync(r)}static async generateCompressedZipBlob(e){return e.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{
614
+ level:6}})}static async toBlob(e,r,t){if(t?.onWarning){const d=this.pendingListNumberingChanges(e.children);d.length>0&&t.onWarning({code:"list_numbering_tracked_unsupported",message:`${d.length===1?"\
615
+ A list has":`${d.length} lists have`} a pending numbering restart or list-type change. Word cannot track that, so the .docx shows ${d.length===1?"it":"them"} as already applied, with no revision to ac\
616
+ cept or reject. Accept or reject ${d.length===1?"it":"them"} in Revise before exporting to keep the choice.`,blockIds:d})}Fr()||await pn();const i=await import("./index-BWdRWxoH.js"),{Document:n,Packer:a,
617
+ Tab:o,TabStopType:s,LeaderType:l,CommentRangeStart:c,CommentRangeEnd:p,CommentReference:h,BookmarkStart:m,BookmarkEnd:f,Paragraph:w,TextRun:u,InsertedTextRun:g,DeletedTextRun:b,FootnoteReference:v,Header:y,
618
+ Footer:D,ExternalHyperlink:$,InternalHyperlink:j,HeadingLevel:W,AlignmentType:E,PageOrientation:T,PageNumber:O,PageBreak:k,SectionType:R,UnderlineType:M,Table:S,TableRow:B,TableCell:_,WidthType:F,BorderStyle:H,
619
+ ShadingType:U,ImportedXmlComponent:G,ImageRun:re,LevelFormat:I,LevelSuffix:X}=i,J=d=>{const x=`<root>${d}</root>`,C=G.fromXmlString(x),N=C.root?.[0];if(N?.root){for(const A of N.root)if(A?.rootKey?.startsWith(
620
+ "m:"))return A}return C},q=(d,x)=>{const C=d?.root;if(Array.isArray(C)){for(const N of C)if(N?.rootKey===x)return N;for(const N of C){if(N?.rootKey==="w:rPr"||N?.rootKey==="w:pPr"||N?.rootKey==="w:tbl\
621
+ Pr"||N?.rootKey==="w:trPr"||N?.rootKey==="w:tcPr")continue;const A=q(N,x);if(A)return A}}},K=(d,x,C)=>{try{const N=q(d,x);if(!N||!Array.isArray(N.root))return;const A=(G.fromXmlString(`<root>${C}</roo\
622
+ t>`).root?.[0]?.root??[]).filter(Z=>Z?.rootKey&&Z.rootKey!=="_attr");N.root.push(...A)}catch{}},be=d=>{try{const x=G.fromXmlString(`<root>${d}</root>`);for(const C of x.root?.[0]?.root??[])if(C?.rootKey&&
623
+ C.rootKey!=="_attr")return C}catch{}return null},de=[],ve=[],Se=(d,x,C="w:pPr")=>{const N=de.length;de.push(x),K(d,C,`<w:rvseOxmlAttrs w:val="${N}"/>`)},fe=Ee(e.pageLayout),et=tr(fe),ie=(d,x,C="only")=>{
624
+ const N=(()=>{const z=Ee(Br(e.pageLayout,d)).pageNumberStart;switch(C){case"middle":return d?.pageNumberStart;case"first":return d?.pageNumberStart??(z!==1?z:void 0);case"final":return e.pageLayout?.pageNumberRestart===
625
+ !0?z:void 0;case"only":return e.pageLayout?.pageNumberRestart===!0||z!==1?z:void 0}})(),A=Ee(d),Z=tr(A),P={...x&&x!=="nextPage"?{type:x==="continuous"?R.CONTINUOUS:x==="evenPage"?R.EVEN_PAGE:R.ODD_PAGE}:
626
+ {},page:{size:{width:this.pxToTwips(A.orientation==="landscape"?Z.pageHeight:Z.pageWidth),height:this.pxToTwips(A.orientation==="landscape"?Z.pageWidth:Z.pageHeight),orientation:A.orientation==="lands\
627
+ cape"?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 z=Ee(
628
+ Br(e.pageLayout,d)).pageNumberFormat,Y={...N!==void 0?{start:N}:{},...z!=="decimal"?{formatType:z}:{}};return Object.keys(Y).length>0?{pageNumbers:Y}:{}})()}};return d?.columnCount&&d.columnCount>1&&(P.
629
+ column={count:d.columnCount,...d.columnGapTwips!==void 0?{space:d.columnGapTwips}:{}}),!A.lineNumbering&&A.pleadingGrid?P.lineNumbers={countBy:1,start:1,restart:"newPage",distance:Math.round((A.pleadingGrid.
630
+ distancePx??14)*15)}:A.lineNumbering&&(P.lineNumbers={countBy:A.lineNumbering.countBy,start:A.lineNumbering.start,restart:A.lineNumbering.restart,...A.lineNumbering.distancePx!==void 0?{distance:Math.
631
+ round(A.lineNumbering.distancePx*15)}:{}}),P},he=ie(e.pageLayout),ke=fe.pageNumberPosition.endsWith("right")?E.RIGHT:E.LEFT,Oe=new w({alignment:ke,children:[new u({children:[O.CURRENT]})]}),Ie=Math.round(
632
+ (et.pageWidth-fe.marginLeftPx-fe.marginRightPx)*15),ct=d=>{const x=[],C=(P,z)=>(z.oxmlRPr&&K(P,"w:rPr",z.oxmlRPr),P);for(const P of d.children){if(P.type!=="text")continue;const z=this.textNodeToDocx(
633
+ P)[0]??{},Y=_e(z);if(P.marks?.field==="page"||P.marks?.field==="numPages"){x.push(new u({...Y,children:[P.marks.field==="page"?O.CURRENT:O.TOTAL_PAGES]}));continue}if(P.text)if(/[\t\n]/.test(P.text)&&
634
+ !P.marks?.link)P.text.split(`
635
+ `).forEach((V,oe)=>{const te=[];V.split(" ").forEach((ge,ee)=>{ee>0&&te.push(new o),ge&&te.push(ge)}),x.push(new u({children:te,...Y,...oe>0?{break:1}:{}}))});else if(P.marks?.link){const V={...Y};V.underline??
636
+ (V.underline={type:M.SINGLE}),V.color??(V.color="2563EB");const oe=[C(new u({text:P.text,...V}),z)];x.push(P.marks.link.startsWith("#")?new j({anchor:P.marks.link.slice(1),children:oe}):new $({link:P.
637
+ marks.link,children:oe}))}else x.push(C(new u({text:P.text,...Y}),z))}const N=d.children.some(P=>P.type==="text"&&P.text.includes(" ")),A={left:E.LEFT,center:E.CENTER,right:E.RIGHT,justify:E.JUSTIFIED},
638
+ Z=new w({children:x,...d.align&&A[d.align]?{alignment:A[d.align]}:{},...N?{tabStops:[{type:s.CENTER,position:Math.round(Ie/2)},{type:s.RIGHT,position:Ie}]}:{}});return d.oxmlPPr&&K(Z,"w:pPr",d.oxmlPPr),
639
+ d.oxmlAttrs&&Se(Z,d.oxmlAttrs),Z},we=new Map,Pe=gn(e),ce=Pe.sizes,De=d=>d.fit==="band"?ce.get(d):{width:d.width,height:d.height},Re=(d,x)=>d.fit!=="band"||x===void 0||!!Pe.sectionsShowing.get(d)?.has(
640
+ x),Nt=(e.chromeImages??[]).some(d=>d.fit==="band"&&!!ce.get(d)&&(Pe.sectionsShowing.get(d)?.size??0)<Pe.sectionCount);for(const d of e.chromeImages??[]){if(!De(d))continue;const x=await this.resolveImageSourceForDocx(
641
+ d.src);x&&we.set(d,x)}const Ke=d=>{const x=we.get(d),C=De(d);if(!x||!C)return null;try{return new w({...d.align==="center"?{alignment:E.CENTER}:d.align==="right"?{alignment:E.RIGHT}:{},children:[new re(
642
+ {type:x.type,data:x.data,...d.alt?{altText:{name:d.alt,description:d.alt,title:d.alt}}:{},transformation:{width:Math.max(1,Math.round(C.width)),height:Math.max(1,Math.round(C.height))}})]})}catch{return null}},
643
+ tt=(d,x,C,N)=>{const A=P=>C?(e.chromeImages??[]).filter(z=>z.side===C&&z.slot===P&&(!N?.bandOnly||z.fit==="band")&&Re(z,N?.sectionIndex)).map(Ke).filter(z=>z!==null):[],Z={};for(const P of["default","\
644
+ first","even"]){const z=[...(d?.[P]??[]).map(ct),...A(P)];z.length>0&&(Z[P]=new x({children:z}))}return Object.keys(Z).length>0?Z:void 0},ft=(d,x)=>(e.chrome??[]).some(C=>C.slot===d&&(x==="any"||C.sectionIndex===
645
+ void 0)&&(d==="first"||Ji(C)))||Array.from(we.keys()).some(C=>C.slot===d),me=!!(e.headers?.first||e.footers?.first)||ft("first","unscoped"),dt=!!(e.headers?.even||e.footers?.even)||ft("even","any");me&&
646
+ (he.titlePage=!0);const Ce={},ye=this.buildDocxNumberingConfig(e,{AlignmentType:E,LevelFormat:I,LevelSuffix:X}),rt=new Set,wt=new Set;for(const d of JSON.stringify(e).matchAll(/docxrev-(\d+)/g))wt.add(
647
+ Number(d[1]));let Ze=1e5;const Fe=d=>{if(d!==void 0&&!rt.has(d))return rt.add(d),d;for(;rt.has(Ze)||wt.has(Ze);)Ze++;return rt.add(Ze),Ze};let Ve=!1;const _e=d=>{const x={};return d.bold!==void 0&&(x.
648
+ bold=d.bold),d.italic!==void 0&&(x.italics=d.italic),d.underline&&(x.underline={type:d.underline==="NONE"?"none":M.SINGLE}),d.strike!==void 0&&(x.strike=d.strike),d.doubleStrike!==void 0&&(x.doubleStrike=
649
+ d.doubleStrike),d.smallCaps!==void 0&&(x.smallCaps=d.smallCaps),d.allCaps!==void 0&&(d.smallCaps!==void 0?(x.snapToGrid=d.allCaps,Ve=!0):x.allCaps=d.allCaps),d.vanish===!0?x.vanish=!0:d.vanish===!1&&(x.
650
+ specVanish=!0,Ve=!0),d.lang&&(x.language={value:d.lang}),d.characterSpacing?x.characterSpacing=d.characterSpacing:d.characterSpacing===0&&(x.imprint=!0,Ve=!0),d.superScript&&(x.superScript=!0),d.subScript&&
651
+ (x.subScript=!0),d.baseline&&(x.emboss=!0,Ve=!0),d.rightToLeft&&(x.rightToLeft=!0),d.color&&(x.color=d.color),d.highlight&&(x.highlight=d.highlight),d.font&&(x.font=d.font.split(",")[0].replaceAll("'",
652
+ "").replaceAll('"',"")),d.size&&(x.size=d.size),d.characterStyle&&(x.style=d.characterStyle),x};let it=0,nt=1e5;const pt=new Set((e.sdtWrappers??[]).filter(d=>d.scope==="inline").map(d=>d.id)),ht=new Map,
653
+ bt=[],Ne=[],ot=[],ni=(d,x,C,N)=>{const A=`${d.name}\0${d.role}\0${d.rangeId}`,Z=ht.get(A);if(Z){Z.wrapperIds.push(x);return}ht.set(A,{name:d.name,role:d.role,rangeId:d.rangeId,author:d.rangeAuthor??C,
654
+ date:typeof d.rangeCreatedAt=="number"?new Date(d.rangeCreatedAt).toISOString():N,wrapperIds:[x]})},Xt=d=>{const x=P=>P?.sdtInline?.split(",").filter(z=>z&&pt.has(z))??[],C=new Map,N=d.children.flatMap(
655
+ (P,z)=>{if(P.mathOmml)return J(P.mathOmml);const Y={text:P.text,..._e(P)};P.break&&(Y.break=1),P.footnoteReference!==void 0&&(delete Y.text,Y.style??(Y.style="FootnoteReference"),Y.children=[new v(P.footnoteReference)]),
656
+ P.rPrChange&&(Y.revision={id:Fe(P.rPrChange.importedId),author:P.rPrChange.author,date:P.rPrChange.date,..._e(P.rPrChange.prior)});const V=()=>{let ne;if(P.revision){const ae=Fe(P.revision.importedId),
657
+ Be={...Y,id:ae,author:P.revision.author,date:P.revision.date};P.revision.kind==="delete"&&P.revision.layeredInsertion&&ot.push({deletionId:ae,insertionId:Fe(P.revision.layeredInsertion.importedId),author:P.
658
+ revision.layeredInsertion.author,date:P.revision.layeredInsertion.date}),P.revision.move&&ni(P.revision.move,ae,P.revision.author,P.revision.date),ne=P.revision.kind==="delete"?new b(Be):new g(Be)}else
659
+ ne=new u(Y);return P.oxmlRPr&&K(ne,"w:rPr",P.oxmlRPr),ne},oe=P.link?(()=>{Y.underline??(Y.underline={type:M.SINGLE}),Y.color??(Y.color="2563EB");const ne=[V()];return P.link.startsWith("#")?new j({anchor:P.
660
+ link.slice(1),children:ne}):new $({link:P.link,children:ne})})():V(),te=[];for(const ne of wr.get(P)??[]){const ae=Le.get(ne);ae!==void 0&&te.push(new c(ae))}const ge=x(d.children[z-1]),ee=x(P),Ye=x(d.
661
+ children[z+1]);for(const ne of[...ee].reverse()){if(ge.includes(ne))continue;const ae={name:`__rvSdt:${ne}:${it++}`,numericId:nt++};C.set(ne,ae),te.push(new m(ae.name,ae.numericId))}for(const ne of Jt.
662
+ get(P)??[])te.push(new m(ne,Ht.get(ne)));for(const ne of Ut.get(P)??[]){const ae=be(Dt.get(ne).startXml);ae&&te.push(ae)}const je=Vt.has(d),se=P.fieldInstr;se&&!je&&d.children[z-1]?.fieldInstr!==se&&te.
663
+ push(...Sr(se)),te.push(oe),se&&!je&&d.children[z+1]?.fieldInstr!==se&&te.push(...kr());for(const ne of Kt.get(P)??[]){const ae=be(Dt.get(ne).endXml);ae&&te.push(ae)}for(const ne of Gt.get(P)??[])te.push(
664
+ new f(Ht.get(ne)));for(const ne of ee){if(Ye.includes(ne))continue;const ae=C.get(ne);ae&&(te.push(new f(ae.numericId)),C.delete(ne))}for(const ne of br.get(P)??[]){const ae=Le.get(ne);ae!==void 0&&(te.
665
+ push(new p(ae)),te.push(new u({children:[new h(ae)]})))}return te});for(const P of jt.get(d.sourceBlockId??"")??[]){const z=Le.get(P);z!==void 0&&(N.push(new c(z)),N.push(new p(z)),N.push(new u({children:[
666
+ new h(z)]})))}if(Zt.has(d)&&N.unshift(...Sr(Zt.get(d))),d.inTableCell&&d.paragraphPropertiesChange){const P=`__rvPp:${bt.length}`,z=nt++;bt.push({pIndex:-1,marker:P,...d.paragraphPropertiesChange}),N.
667
+ unshift(new m(P,z),new f(z))}if((d.inTableCell||d.inNote)&&d.paragraphMarkRevision){const P=`__rvPm:${Ne.length}`,z=nt++;Ne.push({name:P,...d.paragraphMarkRevision}),N.unshift(new m(P,z),new f(z))}xr.
668
+ has(d)&&N.push(...kr());const A={children:N};if(d.children.length>0&&d.children.every(P=>!P.text&&!P.break&&!P.mathOmml&&P.footnoteReference===void 0)){const P=d.children.find(z=>z.size||z.font);if(P){
669
+ const{size:z,font:Y}=_e({size:P.size,font:P.font});A.run={...z?{size:z}:{},...Y?{font:Y}:{}}}}if(d.keepNext&&(A.keepNext=!0),d.keepLines&&(A.keepLines=!0),d.widowControl===!1&&(A.widowControl=!1),d.bidirectional!==
670
+ void 0&&(A.bidirectional=d.bidirectional),d.tabStopsJson){const P=Gi(d.tabStopsJson);if(P){const z={left:s.LEFT,right:s.RIGHT,center:s.CENTER,decimal:s.DECIMAL},Y={dot:l.DOT,hyphen:l.HYPHEN,underscore:l.
671
+ UNDERSCORE};A.tabStops=P.map(V=>({type:z[V.align]??s.LEFT,position:Math.round(V.pos*15),...V.leader?{leader:Y[V.leader]}:{}}))}}if(d.bordersJson)try{const P=JSON.parse(d.bordersJson),z=V=>{switch(V){case"\
672
+ dashed":return H.DASHED;case"dotted":return H.DOTTED;case"double":return H.DOUBLE;case"none":return H.NONE;default:return H.SINGLE}},Y={};for(const V of["top","bottom","left","right"]){const oe=P[V];oe&&
673
+ (Y[V]={style:z(oe.style),size:oe.style==="none"?0:Math.max(1,Math.round((oe.width??1)*6)),color:this.toDocxHex(oe.color)??"auto"})}Object.keys(Y).length>0&&(A.border=Y)}catch{}if(d.shadingFill){const P=this.
674
+ toDocxHex(d.shadingFill);A.shading=P?{type:U.CLEAR,fill:P}:{type:U.CLEAR,fill:"auto",color:"auto"}}if(d.heading&&!d.styleId){const P={HEADING_1:W.HEADING_1,HEADING_2:W.HEADING_2,HEADING_3:W.HEADING_3,
675
+ HEADING_4:W.HEADING_4,HEADING_5:W.HEADING_5,HEADING_6:W.HEADING_6};A.heading=P[d.heading]}if(d.alignment){const P={LEFT:E.LEFT,CENTER:E.CENTER,RIGHT:E.RIGHT,JUSTIFIED:E.JUSTIFIED};A.alignment=P[d.alignment]}
676
+ d.styleId?A.style=d.styleId:d.style&&(A.style=d.style),d.lineSpacing!==void 0&&(A.spacing={...A.spacing,line:Math.round(d.lineSpacing*240)}),d.spacingBeforeTwips!==void 0&&(A.spacing={...A.spacing,before:d.
677
+ spacingBeforeTwips}),d.spacingAfterTwips!==void 0&&(A.spacing={...A.spacing,after:d.spacingAfterTwips}),d.contextualSpacing&&(A.contextualSpacing=!0),d.indent&&(A.indent={...A.indent,...d.indent}),d.list&&
678
+ (d.list.variant==="todo"?A.indent=this.getListIndentOptions(d.list.level):d.list.reference&&(A.numbering={reference:d.list.reference,level:d.list.level,instance:d.list.instance??0}));const Z=new w(A);
679
+ return d.oxmlPPr&&K(Z,"w:pPr",d.oxmlPPr),d.oxmlAttrs&&Se(Z,d.oxmlAttrs),Z},mr=d=>{const x=Number.isFinite(d.borderWidth)?Math.max(0,Math.round(d.borderWidth)):1,C=x>0?{style:H.SINGLE,size:Math.max(1,x*
680
+ 6),color:this.toDocxHex(d.borderColor)??"D1D5DB"}:{style:H.NONE,size:0,color:"auto"},N=ee=>{const Ye={single:H.SINGLE,dashed:H.DASHED,dotted:H.DOTTED,double:H.DOUBLE,none:H.NONE};return ee.style==="no\
681
+ ne"||ee.width<=0?{style:H.NONE,size:0,color:"auto"}:{style:Ye[ee.style]??H.SINGLE,size:Math.max(1,Math.round(ee.width*6)),color:this.toDocxHex(ee.color)??"auto"}},A=nr(d.borders),Z=A?{top:N(A.top??{style:"\
682
+ 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:"\
683
+ #d1d5db"}),insideHorizontal:N(A.insideH??{style:"single",width:1,color:"#d1d5db"}),insideVertical:N(A.insideV??{style:"single",width:1,color:"#d1d5db"})}:void 0,P=d.rows.map(ee=>{const Ye=ee.cells.map(
684
+ (se,ne)=>{const ae=se.blocks??se.paragraphs,Be=ae.map(Me=>Me.type==="table"?mr(Me):Xt(Me));(Be.length===0||ae[ae.length-1]?.type==="table")&&Be.push(new w({}));const st=Math.max(d.columnWidths.length,
685
+ 1),Ii=se.colSpan??1,Ar=se.gridColumn??ne;let Tr=0;for(let Me=Ar;Me<Ar+Ii;Me++)Tr+=d.columnWidths[Me]||100/st;const He={children:Be,width:{size:Tr,type:F.PERCENTAGE}};se.verticalAlign&&(He.verticalAlign=
686
+ se.verticalAlign==="middle"?"center":se.verticalAlign);const Je=cn(se.borders);if(Je){const Me={};Je.top&&(Me.top=N(Je.top)),Je.bottom&&(Me.bottom=N(Je.bottom)),Je.left&&(Me.left=N(Je.left)),Je.right&&
687
+ (Me.right=N(Je.right)),He.borders=Me}else Z||(He.borders={top:C,bottom:C,left:C,right:C});const Pt=dn(se.padding);Pt&&(He.margins={marginUnitType:F.DXA,top:Math.round(Pt.top*15),bottom:Math.round(Pt.bottom*
688
+ 15),left:Math.round(Pt.left*15),right:Math.round(Pt.right*15)}),se.colSpan&&se.colSpan>1&&(He.columnSpan=se.colSpan),se.rowSpan&&se.rowSpan>1&&(He.rowSpan=se.rowSpan);const er=this.toDocxHex(se.backgroundColor);
689
+ er?He.shading={type:U.SOLID,color:er,fill:er}:ee.isHeader&&!se.backgroundColor&&(He.shading={type:U.SOLID,color:"F9FAFB",fill:"F9FAFB"});const Mr=new _(He);return se.oxmlTcPr&&K(Mr,"w:tcPr",se.oxmlTcPr),
690
+ Mr}),je=new B({children:Ye,tableHeader:ee.isHeader===!0?!0:void 0});return ee.oxmlTrPr&&K(je,"w:trPr",ee.oxmlTrPr),ee.oxmlAttrs&&Se(je,ee.oxmlAttrs,"w:trPr"),je}),z=typeof d.tableWidth=="number"&&Number.
691
+ isFinite(d.tableWidth)&&d.tableWidth>0?Math.round(d.tableWidth*15):void 0,Y=z??9e3,V=d.columnWidths.filter(ee=>Number.isFinite(ee)&&ee>0).map(ee=>Math.max(1,Math.round(ee/100*Y))),oe=d.align==="center"?
692
+ E.CENTER:d.align==="right"?E.RIGHT:d.align==="left"?E.LEFT:void 0,te=typeof d.cellPadding=="number"&&Number.isFinite(d.cellPadding)&&d.cellPadding>=0?{marginUnitType:F.DXA,top:Math.round(d.cellPadding*
693
+ 15),bottom:Math.round(d.cellPadding*15),left:Math.round(d.cellPadding*15),right:Math.round(d.cellPadding*15)}:void 0,ge=new S({rows:P,width:z?{size:z,type:F.DXA}:{size:100,type:F.PERCENTAGE},...V.length===
694
+ d.columnWidths.length&&V.length>0?{columnWidths:V}:{},...oe?{alignment:oe}:{},...te?{margins:te}:{},borders:Z??{top:C,bottom:C,left:C,right:C,insideHorizontal:C,insideVertical:C}});return d.oxmlTblPr&&
695
+ K(ge,"w:tblPr",d.oxmlTblPr),ge},oi=d=>{const x=d.split(",")[1]||"";if(typeof atob!="function")throw new Error("Base64 decoding is unavailable in this environment");const C=atob(x),N=new Uint8Array(C.length);
696
+ for(let A=0;A<C.length;A++)N[A]=C.charCodeAt(A);return N},si=d=>{if(d.renderDiagram)return d.diagramPngDataUrl?new w({children:[new re({type:"png",data:oi(d.diagramPngDataUrl),transformation:{width:Math.
697
+ max(120,Math.round(d.diagramWidth||600)),height:Math.max(60,Math.round(d.diagramHeight||180))}})],spacing:{before:120,after:120}}):new w({children:[new u({text:"Diagram unavailable"})],spacing:{before:120,
698
+ after:120}});const x=d.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(`
699
+ `).length-1,A.text=""),new u(A)}),C=this.toDocxHex(d.backgroundColor)??"F5F5F5";return new w({children:x,...d.styleId?{style:d.styleId}:{},shading:{type:U.SOLID,color:C,fill:C},spacing:{before:120,after:120}})},
700
+ ai=d=>{if(!d.omml)return new w({children:[new u({text:d.content})],alignment:d.alignment==="center"?E.CENTER:d.alignment==="right"?E.RIGHT:E.LEFT});const x=J(d.omml);return new w({children:[x],alignment:d.
701
+ alignment==="center"?E.CENTER:d.alignment==="right"?E.RIGHT:E.LEFT,spacing:{before:120,after:120}})},At=[],Tt=[],li=d=>{if(!d.anchorXml)return;const x=`__revise-anchor:${Tt.length}__`;return Tt.push({
702
+ marker:x,anchorXml:d.anchorXml}),x},Mt=d=>({alignment:d.align==="center"?E.CENTER:d.align==="right"?E.RIGHT:E.LEFT,spacing:{before:120,after:120}}),ci=async d=>{const x=li(d);if(d.originalFormat&&d.originalDataUrl){
703
+ const N=`__revise-original-media:${At.length}__`;return At.push({marker:N,format:d.originalFormat,dataUrl:d.originalDataUrl,alt:d.alt}),new w({children:[new re({type:"png",data:this.base64ToUint8Array(
704
+ ii),altText:{name:d.alt||"Image",description:N,title:x??d.alt},transformation:{width:Math.max(1,Math.round(d.width)),height:Math.max(1,Math.round(d.height))}})],...Mt(d)})}if(d.src.match(/^data:image\/svg\+xml(;base64)?,/i)){
705
+ const N=this.dataUrlToUint8Array(d.src);if(N){const A=Math.max(1,Math.round(d.width)),Z=Math.max(1,Math.round(d.height)),P=await this.rasterizeSvgDataUrlToPng(d.src,A,Z)??this.base64ToUint8Array(ii);return new w(
706
+ {children:[new re({type:"svg",data:N,fallback:{type:"png",data:P},altText:{name:d.alt||"Image",description:d.alt,title:x??d.alt},transformation:{width:A,height:Z}})],...Mt(d)})}}const C=await this.resolveImageSourceForDocx(
707
+ d.src);return C?new w({children:[new re({type:C.type,data:C.data,altText:{name:d.alt||"Image",description:d.alt,title:x??d.alt},transformation:{width:Math.max(1,Math.round(d.width)),height:Math.max(1,
708
+ Math.round(d.height))}})],...Mt(d)}):new w({children:[new u({text:d.alt||"Image unavailable"})],...Mt(d)})},di=()=>new w({children:[new k]}),yt=[...e.notes??[],...e.children.filter(d=>d.type==="footno\
709
+ te")],vt=new Map;for(const d of yt)vt.set(d.id,d.noteKind==="endnote"?"endnote":"footnote");const pi=yt.filter(d=>vt.get(d.id)==="footnote"),xt=yt.filter(d=>vt.get(d.id)==="endnote"),Et=new Map,mt=new Map;
710
+ {const d=x=>{if(!x||typeof x!="object")return;if(Array.isArray(x)){x.forEach(d);return}const C=x;if(C.type==="footnote")return;const N=C.marks?.footnoteRef;if(N){const A=vt.get(N)==="endnote"?mt:Et;A.
711
+ has(N)||A.set(N,A.size+1)}d(C.children)};d(e.children.filter(x=>x.type!=="footnote"))}for(const d of xt)mt.has(d.id)||mt.set(d.id,mt.size+1);const Xe=e.comments??[],Le=new Map,gt=new Set;for(const d of Xe){
712
+ const x=d.importedId;Number.isSafeInteger(x)&&x>=0&&x<=2147483647&&!gt.has(x)&&(gt.add(x),Le.set(d.id,x))}let qe=0;for(const d of Xe)if(!Le.has(d.id)){for(;gt.has(qe);)qe++;Le.set(d.id,qe),gt.add(qe++)}
713
+ const St=new Map,gr=d=>{const x=new Map(Xe.map(A=>[A.id,A]));let C=d;const N=new Set;for(;C.parentId&&!N.has(C.id);){N.add(C.id);const A=x.get(C.parentId);if(!A)break;C=A}return C.id};for(const d of Xe){
714
+ const x=gr(d),C=St.get(x)??[];C.includes(d.id)||C.push(d.id),St.set(x,C)}const hi=e.children.some(d=>d.type==="header-footer");let ze=yt.length>0||hi?{...e,children:e.children.filter(d=>d.type!=="foot\
715
+ note"&&d.type!=="header-footer")}:e;if(yt.length>0){ze=JSON.parse(JSON.stringify(ze));const d=x=>{if(!x||typeof x!="object")return;if(Array.isArray(x)){x.forEach(d);return}const C=x,N=C.marks?.footnoteRef;
716
+ if(N)if(vt.get(N)==="endnote"){const A=mt.get(N)??1;C.text=`__RVSE_EN_${A}__`,C.marks&&(delete C.marks.footnoteRef,C.marks.superscript=!0)}else C.text=String(Et.get(N)??1);d(C.children)};d(ze.children)}
717
+ this.hasDocxMoveMarks(ze.children)&&(ze=JSON.parse(JSON.stringify(ze)),this.finalizeImportedMovePairs(ze.children));const ur=this.collectTableRevisionPatches(ze),zt=t?.graft?[]:void 0,kt=this.toDocxFormatWithTables(
718
+ ze,r,t?.headingPageNumbers,zt),It=[],fr=d=>{for(const x of d){if(x.type==="paragraph"){It.push(x);continue}for(const C of x.rows)for(const N of C.cells)fr(N.blocks??N.paragraphs)}};fr(kt.filter(d=>d.type===
719
+ "paragraph"||d.type==="table"));const wr=new Map,br=new Map,jt=new Map,yr=[];{const d=[];for(const P of It)d.push(...P.children);const x=P=>(P.text??"")===""&&!P.break&&!P.mathOmml&&P.footnoteReference===
720
+ void 0&&!P.fieldInstr,C=new Map;for(const[P,z]of St)for(const Y of z)C.set(Y,P);const N=new Map;d.forEach((P,z)=>{const Y=new Set((P.comment?.split(",")??[]).filter(Boolean).map(V=>C.get(V)??V));for(const V of Y){
721
+ const oe=N.get(V)??[],te=oe[oe.length-1];let ge=!!te;for(let ee=te?te.lastIndex+1:z;ee<z;ee++)if(!x(d[ee])){ge=!1;break}te&&ge?(te.last=P,te.lastIndex=z):oe.push({first:P,last:P,lastIndex:z}),N.set(V,
722
+ oe)}});const A=new Set,Z=(P,z,Y)=>P.set(z,[...P.get(z)??[],...Y]);for(const[P,z]of N){const Y=St.get(P)??[P];Y.forEach(V=>A.add(V)),z.forEach((V,oe)=>{let te=Y;if(oe>0){if(!Le.has(P))return;const ge=`${P}\
723
+ \0fragment${oe}`;for(;gt.has(qe);)qe++;Le.set(ge,qe),gt.add(qe++),yr.push({cloneId:ge,sourceId:P}),te=[ge]}Z(wr,V.first,te),Z(br,V.last,te)})}for(const P of Xe){const z=P.anchorBlockId;if(!z||A.has(P.
724
+ id))continue;const Y=St.get(P.id)??[P.id],V=jt.get(z)??[];for(const oe of Y)V.includes(oe)||V.push(oe);jt.set(z,V)}}const mi=new Map(Xe.map(d=>[d.id,d])),vr=[...Xe.map(d=>({id:d.id,record:d,isClone:!1})),
725
+ ...yr.map(({cloneId:d,sourceId:x})=>({id:d,record:mi.get(x),isClone:!0}))],Ht=new Map,Jt=new Map,Gt=new Map;{const d=new Map,x=new Map;for(const N of It)for(const A of N.children)for(const Z of A.bookmark?.
726
+ split(",")??[])Z&&(d.has(Z)||d.set(Z,A),x.set(Z,A));let C=1;for(const[N,A]of d)Ht.set(N,C++),Jt.set(A,[...Jt.get(A)??[],N]);for(const[N,A]of x)Gt.set(A,[...Gt.get(A)??[],N])}const Ut=new Map,Kt=new Map,
727
+ Dt=new Map((e.oxmlRanges??[]).filter(d=>d.startXml&&d.endXml).map(d=>[d.id,d]));if(Dt.size>0){const d=new Map,x=new Map;for(const C of It)for(const N of C.children)for(const A of N.oxmlRange?.split(",")??
728
+ [])!A||!Dt.has(A)||(d.has(A)||d.set(A,N),x.set(A,N));for(const[C,N]of d)Ut.set(N,[...Ut.get(N)??[],C]);for(const[C,N]of x)Kt.set(N,[...Kt.get(N)??[],C])}const gi=d=>{const x=d.children.filter(N=>(N.text??
729
+ "")!==""||N.fieldInstr);if(x.length===0)return;const C=x[0].fieldInstr;if(!(!C||!/^TOC\b/i.test(C.trim())))return x.every(N=>N.fieldInstr===C)?C:void 0},Zt=new Map,xr=new Set,Vt=new Set;{let d,x=[];const C=()=>{
730
+ d&&x.length>0&&(Zt.set(x[0],d),xr.add(x[x.length-1]),x.forEach(N=>Vt.add(N))),d=void 0,x=[]};for(const N of kt){const A=N.type==="paragraph"?N:void 0,Z=A?gi(A):void 0;if(A&&Z&&Z===d){x.push(A);continue}
731
+ C(),A&&Z&&(d=Z,x=[A])}C()}const Rt=d=>{const x=`<root><w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${d}</w:r></root>`,C=G.fromXmlString(x).root?.[0];if(C?.root){for(const N of C.
732
+ root)if(N?.rootKey==="w:r")return N}},ui=d=>d.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Sr=d=>[Rt('<w:fldChar w:fldCharType="begin"/>'),Rt(`<w:instrText xml:space="preserve"> ${ui(
733
+ d)} </w:instrText>`),Rt('<w:fldChar w:fldCharType="separate"/>')].filter(Boolean),kr=()=>[Rt('<w:fldChar w:fldCharType="end"/>')].filter(Boolean),fi=Vt.size>0||It.some(d=>d.children.some(x=>x.fieldInstr)),
734
+ wi=d=>{if(cr(d.xml))return new w({});try{const x=d.origin==="run"?`<root><w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:r>${d.xml}</w:r></w:p></root>`:`<root>${d.xml}</\
735
+ root>`,C=G.fromXmlString(x).root?.[0];for(const N of C?.root??[])if(N?.rootKey&&N.rootKey!=="_attr")return N}catch{}return new w({})},Ir=async d=>d.type==="table"?mr(d):d.type==="codeblock"?si(d):d.type===
736
+ "mathblock"?ai(d):d.type==="pagebreak"?di():d.type==="sectionbreak"?null:d.type==="image"?ci(d):d.type==="docxraw"?wi(d):Xt(d),bi=await Promise.all(kt.map(Ir)),qt={},Bt=new Map,Pr=d=>{for(const x of d)
737
+ if(x.type==="paragraph"&&x.list?.reference){const C=`${x.list.reference}\0${x.list.instance??0}`;Bt.has(C)||Bt.set(C,x.list)}else if(x.type==="table")for(const C of x.rows)for(const N of C.cells)Pr(N.
738
+ blocks??N.paragraphs)},Cr=async(d,x)=>{const C=this.toDocxFormatWithTables({...e,children:d.children},r);Pr(C);for(const A of C)A.type==="paragraph"&&(A.inNote=!0);const N=(await Promise.all(C.map(Ir))).
739
+ filter(A=>A!==null).map(A=>A);qt[String(x)]={children:N.length>0?N:[new w({})]}};let yi=Et.size;for(const d of pi){const x=Et.get(d.id)??++yi;await Cr(d,x)}const Nr=new Map;for(let d=0;d<xt.length;d++){
740
+ const x=xt[d],C=1e6+d;Nr.set(x.id,C),await Cr(x,C)}const Yt=[...Bt.keys()],vi=Yt.map((d,x)=>Xt({type:"paragraph",children:[{text:`__RVSE_NOTE_NUM_${x}__`}],list:Bt.get(d)}));{const d=Dr(e.chrome??[]),
741
+ x=tt(e.headers??d.headers,y,"header"),C=tt(e.footers??d.footers,D,"footer");x&&(Ce.headers=x),C&&(Ce.footers=C),e.watermark&&!Ce.headers&&(Ce.headers={default:new y({children:[new w({})]})}),fe.showPageNumbers&&
742
+ (fe.pageNumberPosition.startsWith("top")&&!Ce.headers?Ce.headers={default:new y({children:[Oe]})}:!fe.pageNumberPosition.startsWith("top")&&!Ce.footers&&(Ce.footers={default:new D({children:[Oe]})}))}
743
+ const Te=e.coreProperties??{},xi={...Te.title!==void 0?{title:Te.title}:{},...Te.subject!==void 0?{subject:Te.subject}:{},...Te.creator!==void 0?{creator:Te.creator}:{},...Te.keywords!==void 0?{keywords:Te.
744
+ keywords}:{},...Te.description!==void 0?{description:Te.description}:{},...Te.lastModifiedBy!==void 0?{lastModifiedBy:Te.lastModifiedBy}:{}},Si=new n({...xi,...e.pageLayout?.blockSpacingPx!==void 0?{customProperties:[
745
+ {name:"Revise.BlockSpacingPx",value:String(Ee(e.pageLayout).blockSpacingPx)}]}:{},numbering:ye,...fi?{features:{updateFields:!0}}:{},...dt?{evenAndOddHeaderAndFooters:!0}:{},...Xe.length>0?{comments:{
746
+ children:vr.map(({id:d,record:x})=>({id:Le.get(d),author:x.author,...x.initials?{initials:x.initials}:{},date:new Date(x.createdAt),children:(x.bodyMd||" ").split(/\n\n+/).map(C=>new w({children:[new u(
747
+ {text:C})]}))}))}}:{},...Object.keys(qt).length>0?{footnotes:qt}:{},styles:{default:{document:{run:{size:this.DEFAULT_RUN_SIZE_HALF_POINTS}},...this.buildExportHeadingDefaults()},paragraphStyles:this.
748
+ buildExportParagraphStyles(e),characterStyles:this.buildExportCharacterStyles()},sections:(()=>{const d=e.chrome??[],x=Oi(d),C=V=>{if(["header","footer"].some(te=>Ui(d,te,"first",V)))return!0;if(!x)return me;
749
+ if(Array.from(we.keys()).some(te=>te.slot==="first"&&te.fit==="band"))return!0;const oe=Or(d,V);return!!(oe.headers?.first||oe.footers?.first)},N=new Map,A=V=>{let oe="";if(!x){if(!Nt)return Ce;const se=(e.
750
+ chromeImages??[]).flatMap((ae,Be)=>we.has(ae)&&!Re(ae,V)?[Be]:[]);if(se.length===0)return Ce;oe=se.join(",");const ne=N.get(oe);if(ne)return ne}const te=x?Or(d,V):(()=>{const se=Dr(d);return{headers:e.
751
+ headers??se.headers,footers:e.footers??se.footers}})(),ge={sectionIndex:V,bandOnly:x},ee={},Ye=tt(te.headers,y,"header",ge),je=tt(te.footers,D,"footer",ge);Ye&&(ee.headers=Ye),je&&(ee.footers=je),e.watermark&&
752
+ !ee.headers&&(ee.headers={default:new y({children:[new w({})]})}),fe.showPageNumbers&&(fe.pageNumberPosition.startsWith("top")&&!ee.headers?ee.headers={default:new y({children:[Oe]})}:!fe.pageNumberPosition.
753
+ startsWith("top")&&!ee.footers&&(ee.footers={default:new D({children:[Oe]})}));for(const[se,ne,ae]of[["header","headers",y],["footer","footers",D]])for(const Be of["default","first","even"])ee[ne]?.[Be]||
754
+ !(e.chromeImages??[]).some(st=>st.side===se&&st.slot===Be&&we.has(st)&&(!x||st.fit==="band")&&!Re(st,V))||(ee[ne]={...ee[ne]??{},[Be]:new ae({children:[new w({})]})});return x||N.set(oe,ee),ee},Z=[];let P=[],
755
+ z;kt.forEach((V,oe)=>{if("type"in V&&V.type==="sectionbreak"){const ge=V;ve.push(Li(e.pageLayout,ge.layout));const ee=ie(ge.layout,z,Z.length===0?"first":"middle");C(Z.length)&&(ee.titlePage=!0),Z.push(
756
+ {properties:ee,...A(Z.length),children:P}),P=[],z=ge.breakType;return}const te=bi[oe];te!=null&&P.push(te)}),ve.push($i(e.pageLayout));const Y=Z.length===0?he:ie(e.pageLayout,z,"final");return C(Z.length)?
757
+ Y.titlePage=!0:x&&Y===he&&delete Y.titlePage,Z.push({properties:Y,...A(Z.length),children:[...P,...vi]}),Z})()}),ki=await this.stabilizeHyperlinkRelIds(await this.stabilizeAttributeWhitespace(await a.
758
+ toBlob(Si))),Ot=[],Qt=[...bt];let ut=0;for(const d of kt){if("type"in d&&d.type==="table")continue;if("type"in d&&d.type==="docxraw"){d.emitsParagraph&&ut++;continue}if("type"in d&&d.type==="sectionbr\
759
+ eak"){const N=d.pendingDeletion;N&&Ot.push({pIndex:ut,kind:"merge",...N}),ut++;continue}const x=d.paragraphMarkRevision;x&&Ot.push({pIndex:ut,...x});const C=d.paragraphPropertiesChange;C&&Qt.push({pIndex:ut,
760
+ ...C}),ut++}let Q=ki;if(ht.size>0&&(Q=await this.patchLinkedMoveRevisions(Q,Array.from(ht.values()))),Yt.length>0&&(Q=await this.patchNoteNumberingReferences(Q,Yt)),Ve&&(Q=await this.patchRunPropertyResetMarkers(
761
+ Q)),Ne.length>0&&(Q=await this.patchMarkedParagraphMarkRevisions(Q,Ne.map(d=>({...d,id:Fe(d.importedId)})))),ot.length>0&&(Q=await this.patchLayeredDeletions(Q,ot)),de.length>0&&(Q=await this.applyOxmlAttrMarkers(
762
+ Q,de)),ve.some(d=>d)&&(Q=await this.injectSectPrOpaquePayloads(Q,ve)),Tt.length>0)try{Q=await this.patchAnchoredImages(Q,Tt)}catch(d){console.warn("docx export: anchored-image restore failed; exportin\
763
+ g images inline",d)}if(At.length>0)try{Q=await this.patchOriginalVectorImages(Q,At)}catch(d){console.warn("docx export: EMF/WMF original-media patch failed; exporting placeholder images",d)}if(Ot.length>
764
+ 0)try{Q=await this.patchParagraphMarkRevisions(Q,Ot,Fe)}catch(d){console.warn("docx export: paragraph-mark revision patch failed; exporting without pilcrow markup",d)}if(Qt.length>0)try{Q=await this.patchParagraphPropertyChanges(
765
+ Q,Qt,Fe)}catch(d){console.warn("docx export: w:pPrChange patch failed; exporting without paragraph property-change markup",d)}if(ur.length>0)try{Q=await this.patchTableRevisions(Q,ur,Fe)}catch(d){console.
766
+ warn("docx export: table revision patch failed; exporting table content without revision markup",d)}if(Xe.length>0)try{Q=await this.appendCommentsExtendedPart(Q,vr.map(({id:d,record:x,isClone:C})=>{const N=!C&&
767
+ x.parentId?gr(x):void 0;return{numericId:Le.get(d),resolved:x.resolved===!0,parentNumericId:N&&N!==x.id?Le.get(N):void 0}}))}catch(d){console.warn("docx export: commentsExtended generation failed; com\
768
+ ments export flat/unresolved",d)}if(xt.length>0)try{Q=await this.appendEndnotesPart(Q,xt.map(d=>({index:mt.get(d.id),note:d,syntheticFootnoteId:Nr.get(d.id)})))}catch(d){console.warn("docx export: end\
769
+ notes part generation failed; endnote markers left in text",d)}if(e.sdtWrappers&&e.sdtWrappers.length>0)try{Q=await this.applySdtWrappers(Q,e)}catch(d){console.warn("docx export: content-control wrapp\
770
+ ing failed; content exported unwrapped",d)}if(e.coreProperties)try{Q=await this.patchCoreProperties(Q,Te)}catch(d){console.warn("docx export: core-property patch failed; library defaults kept",d)}if(e.
771
+ stylesXml)try{Q=await this.mergeImportedStyles(Q,e.stylesXml)}catch(d){console.warn("docx export: styles.xml merge failed; imported named styles dropped",d)}if(e.watermark)try{Q=await this.injectWatermarkIntoHeaders(
772
+ Q,e.watermark)}catch(d){console.warn("docx export: watermark header injection failed; exporting without watermark",d)}if(Ee(e.pageLayout).hyphenationEnabled)try{Q=await this.injectAutoHyphenationSetting(
773
+ Q)}catch(d){console.warn("docx export: autoHyphenation setting injection failed",d)}try{Q=await this.stampApplicationProperty(Q)}catch(d){console.warn("docx export: application stamp failed; exporting\
774
+ without it",d)}if(t?.graft&&zt){const d=x=>{try{t.graft?.onOutcome?.(x)}catch{}};if(!e.docxSource)return console.warn("docx export: graft requested but document has no docxSource capture; exporting r\
775
+ egenerated package"),d({mode:"regenerated",fallbackCode:"no-capture"}),Q;try{Q=await Vi({generatedBlob:Q,originalDocx:t.graft.originalDocx,doc:e,blockRanges:zt});const x=qi(e);d({mode:x.fullyExact?"ex\
776
+ act":"grafted",regeneratedBlockCount:x.regeneratedBlockIds.length,changedDomains:Object.entries(x.domains).filter(([,C])=>!C).map(([C])=>C)})}catch(x){const C=x instanceof Yi?x.code:"internalError";console.
777
+ warn(`docx export: OOXML graft rejected [${C}]; exporting regenerated package`,x),d({mode:"regenerated",fallbackCode:C})}}return Q}static async patchNoteNumberingReferences(e,r){const t=await this.loadZipFromBlob(
778
+ e),i=t.file("word/document.xml");if(!i)return e;let n=await i.async("text");const a=new Map;n=n.replace(/<w:p\b[^>]*>[\s\S]*?<\/w:p>/g,l=>{const c=/__RVSE_NOTE_NUM_(\d+)__/.exec(l);if(!c)return l;const p=Number(
779
+ c[1]),h=/<w:numId\b[^>]*w:val="([^"]+)"/.exec(l)?.[1],m=r[p];return m&&h&&!h.startsWith("{")&&a.set(m,h),""}),t.file("word/document.xml",n);const o=l=>l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");for(const[
780
+ l,c]of Object.entries(t.files)){if(!l.startsWith("word/")||!l.endsWith(".xml")||c.dir)continue;let p=await c.async("text"),h=!1;for(const[m,f]of a){const[w,u]=m.split("\0"),g=`{${w}-${u}}`,b=p.replace(
781
+ new RegExp(`w:val="${o(g)}"`,"g"),`w:val="${f}"`);h||(h=b!==p),p=b}h&&t.file(l,p)}const s=await this.generateCompressedZipBlob(t);return new Blob([s],{type:"application/vnd.openxmlformats-officedocume\
782
+ nt.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"),a=0;n=n.replace(
783
+ /<w:sectPr\b[^>]*>[\s\S]*?<\/w:sectPr>|<w:sectPr\b[^>]*\/>/g,c=>{const p=r[a++];return p?c.endsWith("/>")?`${c.slice(0,-2)}>${p}</w:sectPr>`:c.replace(/<\/w:sectPr>$/,`${p}</w:sectPr>`):c});const o=new DOMParser().
784
+ parseFromString(n,"application/xml"),s=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:printerSe\
785
+ ttings","w:sectPrChange"]);for(const c of Array.from(o.getElementsByTagName("w:sectPr"))){const p=Array.from(c.children).find(m=>m.tagName==="w:pgBorders"),h=Array.from(c.children).find(m=>s.has(m.tagName));
786
+ p&&h&&c.insertBefore(p,h)}n=new XMLSerializer().serializeToString(o),t.file("word/document.xml",n);const l=await this.generateCompressedZipBlob(t);return new Blob([l],{type:"application/vnd.openxmlfor\
787
+ mats-officedocument.wordprocessingml.document"})}static async stabilizeAttributeWhitespace(e){let r;try{r=await this.loadZipFromBlob(e)}catch{return e}const{stabilizeSerializedXml:t}=await Promise.resolve().
788
+ then(()=>wn);let i=!1;for(const[a,o]of Object.entries(r.files)){if(!a.endsWith(".xml")||o.dir)continue;const s=await o.async("text"),l=t(s);l!==s&&(r.file(a,l),i=!0)}if(!i)return e;const n=await this.
789
+ generateCompressedZipBlob(r);return new Blob([n],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async stabilizeHyperlinkRelIds(e){let r;try{r=await this.loadZipFromBlob(
790
+ e)}catch{return e}let t=!1;for(const[n,a]of Object.entries(r.files)){const o=/^(.*)_rels\/([^/]+)\.rels$/.exec(n);if(!o||a.dir)continue;const s=`${o[1]}${o[2]}`,l=r.file(s);if(!l)continue;let c=await a.
791
+ async("text");const p=[];for(const f of c.matchAll(/<Relationship\b[^>]*\/?>/g)){if(!/Type="[^"]*\/hyperlink"/.test(f[0]))continue;const w=/Id="([^"]+)"/.exec(f[0])?.[1];w&&p.push(w)}if(p.length===0)continue;
792
+ let h=await l.async("text");const m=[...p].sort((f,w)=>{const u=h.indexOf(`"${f}"`),g=h.indexOf(`"${w}"`);return(u<0?1/0:u)-(g<0?1/0:g)});m.forEach((f,w)=>{f!==`rvseLnk${w+1}`&&(h=h.replaceAll(`r:id="${f}\
793
+ "`,`r:id="__rvseLnkTmp${w+1}__"`),c=c.replace(`Id="${f}"`,`Id="__rvseLnkTmp${w+1}__"`),t=!0)}),m.forEach((f,w)=>{h=h.replaceAll(`r:id="__rvseLnkTmp${w+1}__"`,`r:id="rvseLnk${w+1}"`),c=c.replace(`Id="_\
794
+ _rvseLnkTmp${w+1}__"`,`Id="rvseLnk${w+1}"`)}),r.file(s,h),r.file(n,c)}if(!t)return e;const i=await this.generateCompressedZipBlob(r);return new Blob([i],{type:"application/vnd.openxmlformats-officedoc\
795
+ ument.wordprocessingml.document"})}static async applyOxmlAttrMarkers(e,r){const t=await this.loadZipFromBlob(e);for(const[n,a]of Object.entries(t.files)){if(!n.startsWith("word/")||!n.endsWith(".xml")||
796
+ a.dir)continue;let o=await a.async("text");if(o.includes("<w:rvseOxmlAttrs ")){for(const s of["w:p","w:tr"])o=o.replace(new RegExp(`<${s}\\b([^>]*)>((?:(?!<${s}\\b)(?!</${s}>)[\\s\\S])*?)<w:rvseOxmlAttr\
797
+ s w:val="(\\d+)"/>`,"g"),(l,c,p,h)=>{const m=r[Number(h)];if(!m)return`<${s}${c}>${p}`;const f=new Set([...c.matchAll(/([\w:.-]+)=/g)].map(u=>u[1])),w=Kr(m,f);return`<${s}${c}${w}>${p}`});o=o.replace(
798
+ /<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(
799
+ [i],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchMarkedParagraphMarkRevisions(e,r){const t=await this.loadZipFromBlob(e),i="http://schemas.openxm\
800
+ lformats.org/wordprocessingml/2006/main",n=new Map(r.map(o=>[o.name,o]));for(const o of["word/document.xml","word/footnotes.xml","word/endnotes.xml"]){const s=t.file(o);if(!s)continue;const l=await s.
801
+ async("text");if(!l.includes("__rvPm:"))continue;const c=this.parseDocumentXml(l);if(!c)continue;const p=Array.from(c.getElementsByTagName("w:bookmarkStart"));for(const h of p){const m=n.get(h.getAttribute(
802
+ "w:name")??"");if(!m)continue;const f=h.getAttribute("w:id");let w=h.parentElement;for(;w&&w.tagName!=="w:p";)w=w.parentElement;for(const y of Array.from(c.getElementsByTagName("w:bookmarkEnd")))y.getAttribute(
803
+ "w:id")===f&&y.parentNode?.removeChild(y);if(h.parentNode?.removeChild(h),!w)continue;let u=Array.from(w.children).find(y=>y.tagName==="w:pPr");u||(u=c.createElementNS(i,"w:pPr"),w.insertBefore(u,w.firstChild));
804
+ let g=Array.from(u.children).find(y=>y.tagName==="w:rPr");if(!g){g=c.createElementNS(i,"w:rPr");const y=Array.from(u.children).find(D=>D.tagName==="w:sectPr"||D.tagName==="w:pPrChange");u.insertBefore(
805
+ g,y??null)}const b=m.kind==="split"||m.kind==="insert"?"w:ins":m.kind==="moveTo"?"w:moveTo":m.kind==="moveFrom"?"w:moveFrom":"w:del",v=c.createElementNS(i,b);v.setAttribute("w:id",String(m.id)),v.setAttribute(
806
+ "w:author",m.author),v.setAttribute("w:date",m.date),g.insertBefore(v,g.firstChild)}t.file(o,new XMLSerializer().serializeToString(c))}const a=await this.generateCompressedZipBlob(t);return new Blob([
807
+ a],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchLayeredDeletions(e,r){const t=o=>o.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").
808
+ replace(/"/g,"&quot;"),i=new Map(r.map(o=>[o.deletionId,o])),n=await this.loadZipFromBlob(e);for(const[o,s]of Object.entries(n.files)){if(!o.startsWith("word/")||!o.endsWith(".xml")||s.dir)continue;const l=await s.
809
+ async("text");if(!l.includes("<w:del "))continue;const c=l.replace(/<w:del\b[^>]*\bw:id="(\d+)"[^>]*(?<!\/)>[\s\S]*?<\/w:del>/g,(p,h)=>{const m=i.get(Number(h));return m?`<w:ins w:id="${m.insertionId}\
810
+ " w:author="${t(m.author)}" w:date="${m.date}">${p}</w:ins>`:p});c!==l&&n.file(o,c)}const a=await this.generateCompressedZipBlob(n);return new Blob([a],{type:"application/vnd.openxmlformats-officedocu\
811
+ ment.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(".\
812
+ xml")||n.dir)continue;let a=await n.async("text");/<w:(?:specVanish|imprint|emboss|snapToGrid)\b/.test(a)&&(a=a.replace(/<w:specVanish\b[^>]*\/>/g,'<w:vanish w:val="false"/>').replace(/<w:imprint\b[^>]*\/>/g,
813
+ '<w:spacing w:val="0"/>').replace(/<w:emboss\b[^>]*\/>/g,'<w:vertAlign w:val="baseline"/>').replace(/<w:snapToGrid\b([^>]*)\/>/g,(o,s)=>/\bw:val="(?:false|0|off)"/i.test(s)?'<w:caps w:val="false"/>':"\
814
+ <w:caps/>"),r.file(i,a))}const t=await this.generateCompressedZipBlob(r);return new Blob([t],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async injectAutoHyphenationSetting(e){
815
+ 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:autoHyphena\
816
+ tion/></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){
817
+ 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){
818
+ 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){
819
+ 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){
820
+ if(!(typeof document>"u"||typeof Image>"u"||typeof navigator<"u"&&navigator.userAgent?.includes("jsdom")))return new Promise(i=>{let n=!1;const a=l=>{n||(n=!0,i(l))},o=setTimeout(()=>a(void 0),3e3),s=new Image;
821
+ s.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 c=l.getContext("2d");if(!c){a(void 0);return}c.drawImage(
822
+ s,0,0,l.width,l.height),l.toBlob(async p=>{if(!p){a(void 0);return}a(new Uint8Array(await p.arrayBuffer()))},"image/png")}catch{a(void 0)}},s.onerror=()=>{clearTimeout(o),a(void 0)},s.src=e})}static serializeXmlPreservingPrefixes(e){
823
+ const r=new Map,t=(a,o)=>{const s=o.indexOf(":");if(s<=0)return;const l=o.slice(0,s);if(l==="xmlns"||l==="xml"||r.has(l))return;const c=a.lookupNamespaceURI(l);c&&r.set(l,c)},i=a=>{t(a,a.tagName);for(let o=0;o<
824
+ a.attributes.length;o++)t(a,a.attributes[o].name);for(let o=0;o<a.children.length;o++)i(a.children[o])};i(e);const n=(a,o)=>{if(a.nodeType===3)return(a.nodeValue??"").replace(/&/g,"&amp;").replace(/</g,
825
+ "&lt;").replace(/>/g,"&gt;");if(a.nodeType!==1)return"";const s=a;let l=`<${s.tagName}`;const c=new Set;for(let h=0;h<s.attributes.length;h++){const m=s.attributes[h];m.name.startsWith("xmlns:")&&c.add(
826
+ m.name.slice(6)),l+=` ${m.name}="${this.escapeXml(m.value)}"`}if(o)for(const[h,m]of r)c.has(h)||(l+=` xmlns:${h}="${this.escapeXml(m)}"`);const p=s.childNodes;if(p.length===0)return`${l}/>`;l+=">";for(let h=0;h<
827
+ p.length;h++)l+=n(p[h],!1);return`${l}</${s.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.
828
+ async("string"),a=!1;for(const o of r){const s=`title="${this.escapeXml(o.marker)}"`,l=n.indexOf(s);if(l===-1)continue;const c=()=>{n=n.replace(` ${s}`,""),a=!0},p=n.lastIndexOf("<wp:inline",l),h=n.indexOf(
829
+ "</wp:inline>",l);if(p===-1||h===-1){c();continue}const m=h+12,f=n.slice(p,m),w=Array.from(f.matchAll(/r:embed="([^"]+)"/g)).map(v=>v[1]);if(w.length===0){c();continue}let u=0,g=o.anchorXml.replace(/(r:(?:embed|link)=")[^"]*(")/g,
830
+ (v,y,D)=>{const $=w[Math.min(u,w.length-1)];return u++,`${y}${$}${D}`});const b=f.match(/<wp:docPr\b[^>]*/)?.[0].match(/ descr="([^"]*)"/);g=g.replace(/<wp:docPr\b([^>]*?)(\/?>)/,(v,y,D)=>{const $=y.replace(
831
+ /\s+descr="[^"]*"/,""),j=b?` descr="${b[1]}"`:"";return`<wp:docPr${$}${j}${D}`}),n=n.slice(0,p)+g+n.slice(m),a=!0}return a?(t.file("word/document.xml",n),this.generateCompressedZipBlob(t)):e}static async patchOriginalVectorImages(e,r){
832
+ const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml"),n=t.file("word/_rels/document.xml.rels"),a=t.file("[Content_Types].xml");if(!i||!n||!a)return e;let o=await i.async("string"),s=await n.
833
+ async("string"),l=await a.async("string");const c=new Set;for(let p=0;p<r.length;p++){const h=r[p],m=await this.resolveBinarySourceForDocx(h.dataUrl);if(!m)continue;const f=this.escapeXml(h.marker),w=o.
834
+ indexOf(f);if(w===-1)continue;const u=o.slice(w).match(/r:embed="([^"]+)"/);if(!u)continue;const g=u[1],b=`media/reviseOriginal${p}.${h.format}`,v=new RegExp(`(<Relationship\\b[^>]*\\bId="${g}"[^>]*\\b\
835
+ Target=")[^"]*(")`),y=new RegExp(`(<Relationship\\b[^>]*\\bTarget=")[^"]*("[^>]*\\bId="${g}")`);if(v.test(s))s=s.replace(v,`$1${b}$2`);else if(y.test(s))s=s.replace(y,`$1${b}$2`);else continue;t.file(
836
+ `word/${b}`,m),c.add(h.format),o=h.alt?o.replace(`descr="${f}"`,`descr="${this.escapeXml(h.alt)}"`):o.replace(` descr="${f}"`,"")}for(const p of c)new RegExp(`Extension="${p}"`).test(l)||(l=l.replace(
837
+ "</Types>",`<Default Extension="${p}" ContentType="image/x-${p}"/></Types>`));return t.file("word/document.xml",o),t.file("word/_rels/document.xml.rels",s),t.file("[Content_Types].xml",l),this.generateCompressedZipBlob(
838
+ t)}static async injectWatermarkIntoHeaders(e,r){const t=an(r);if(!t)return e;const i=await this.loadZipFromBlob(e),n=Object.keys(i.files).filter(f=>/^word\/header\d+\.xml$/.test(f));if(n.length===0)return e;
839
+ const a=f=>f.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),o=468,s=Math.max(40,Math.round(o/Math.max(2,t.text.length*.55))),l=t.diagonal?"rotation:315;":"",c=t.
840
+ 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\
841
+ :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,\
842
+ 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\
843
+ :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:co\
844
+ nnecttype="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"/></\
845
+ 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\
846
+ :0;width:${o}pt;height:${s}pt;${l}z-index:-251654144;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin" o:allowi\
847
+ ncell="f" fillcolor="${a(t.color)}" stroked="f"><v:fill opacity="${t.opacity===ln?$r:t.opacity}"/><v:textpath style="font-family:&quot;Calibri&quot;;font-size:${c}" string="${a(t.text)}"/></v:shape></\
848
+ w:pict></w:r></w:p>`;let h=!1;for(const f of n){const w=await i.file(f).async("text");if(w.includes("v:textpath"))continue;const u=w.replace(/(<w:hdr[^>]*>)/,`$1${p}`);u!==w&&(i.file(f,u),h=!0)}if(!h)
849
+ return e;const m=await this.generateCompressedZipBlob(i);return new Blob([m],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async mergeImportedStyles(e,r){const t=await this.
850
+ loadZipFromBlob(e),i=t.file("word/styles.xml");if(!i)return e;let n=await i.async("text");const a=r.match(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/)?.[0];a&&(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/.
851
+ test(n)?n=n.replace(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/,a):n=n.replace(/(<w:styles\b[^>]*>)/,`$1${a}`));const o=new Map;for(const u of r.matchAll(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g)){const g=u[0].
852
+ match(/w:styleId="([^"]+)"/);g&&o.set(g[1],u[0])}if(o.size===0&&!a)return e;const s=new Set;n=n.replace(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g,u=>{const g=u.match(/w:styleId="([^"]+)"/),b=g?o.get(g[1]):
853
+ void 0;return b?(s.add(g[1]),b):u});const l=[];for(const[u,g]of o)s.has(u)||l.push(g);n=n.replace(/<\/w:styles>/,`${l.join("")}</w:styles>`);const c=new Set,p=u=>{for(const g of u.matchAll(/<w:(?:pStyle|rStyle|tblStyle)\b[^>]*w:val="([^"]+)"/g))
854
+ c.add(g[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 h=new Map;for(const u of n.matchAll(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g)){
855
+ const g=u[0].match(/w:styleId="([^"]+)"/);g&&h.set(g[1],u[0])}const m=(u,g)=>o.has(u)||/w:default="(?:1|true)"/.test(g.slice(0,g.indexOf(">")))||c.has(u);let f=!0;for(;f;){f=!1;for(const[u,g]of h)if(m(
856
+ u,g))for(const b of g.matchAll(/<w:(?:basedOn|link|next)\b[^>]*w:val="([^"]+)"/g))c.has(b[1])||(c.add(b[1]),f=!0)}n=n.replace(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g,u=>{const g=u.match(/w:styleId="([^"]+)"/);
857
+ return!g||m(g[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.documen\
858
+ t"})}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 a=l=>l.replace(/&/g,"&amp;").replace(/</g,
859
+ "&lt;").replace(/>/g,"&gt;");for(const l of["created","modified"]){const c=r[l];if(!c)continue;const p=new RegExp(`(<dcterms:${l}\\b[^>]*>)[^<]*(</dcterms:${l}>)`);p.test(n)?n=n.replace(p,`$1${a(c)}$2`):
860
+ n=n.replace(/<\/cp:coreProperties>/,`<dcterms:${l} xsi:type="dcterms:W3CDTF">${a(c)}</dcterms:${l}></cp:coreProperties>`)}const o=/<cp:revision>[^<]*<\/cp:revision>/;if(r.revision){const l=`<cp:revisi\
861
+ on>${a(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,c]of[["creator","dc:creator"],["lastModif\
862
+ iedBy","cp:lastModifiedBy"]])r[l]||(n=n.replace(new RegExp(`<${c}>[^<]*</${c}>`),""));t.file("docProps/core.xml",n);const s=await this.generateCompressedZipBlob(t);return new Blob([s],{type:"applicati\
863
+ on/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.
864
+ 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}\
865
+ </Properties>`);else if(i.includes("</Properties>"))i=i.replace("</Properties>",`${n}</Properties>`);else return e;r.file("docProps/app.xml",i);const a=await this.generateCompressedZipBlob(r);return new Blob(
866
+ [a],{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)
867
+ 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 a=p=>(268435456+p).toString(
868
+ 16).toUpperCase().padStart(8,"0");n=n.replace(/<w:comment\b([^>]*)>([\s\S]*?)<\/w:comment>/g,(p,h,m)=>{const f=h.match(/w:id="(\d+)"/);if(!f)return p;const w=a(parseInt(f[1],10)),u=m.lastIndexOf("<w:p");
869
+ if(u===-1)return p;const g=m.slice(0,u)+m.slice(u).replace(/<w:p(\s|>)/,`<w:p w14:paraId="${w}"$1`);return`<w:comment${h}>${g}</w:comment>`}),t.file("word/comments.xml",n);const o='<?xml version="1.0"\
870
+ encoding="UTF-8" standalone="yes"?><w15:commentsEx xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml">'+r.map(({numericId:p,resolved:h,parentNumericId:m})=>`<w15:commentEx ${[`w15:paraI\
871
+ d="${a(p)}"`,...m!==void 0?[`w15:paraIdParent="${a(m)}"`]:[],`w15:done="${h?"1":"0"}"`].join(" ")}/>`).join("")+"</w15:commentsEx>";t.file("word/commentsExtended.xml",o);const s=t.file("[Content_Types\
872
+ ].xml");if(s){let p=await s.async("text");p.includes("/word/commentsExtended.xml")||(p=p.replace("</Types>",'<Override PartName="/word/commentsExtended.xml" ContentType="application/vnd.openxmlformats\
873
+ -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("comment\
874
+ sExtended.xml")||(p=p.replace("</Relationships>",'<Relationship Id="rIdRvseCommentsEx" Type="http://schemas.microsoft.com/office/2011/relationships/commentsExtended" Target="commentsExtended.xml"/></R\
875
+ elationships>'),t.file("word/_rels/document.xml.rels",p))}const c=await this.generateCompressedZipBlob(t);return new Blob([c],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.docu\
876
+ ment"})}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 g=`__RVSE_EN_${u}\
877
+ __`;for(const b of["w:t","w:delText"])n=n.replaceAll(`<${b} xml:space="preserve">${g}</${b}>`,`<w:endnoteReference w:id="${u}"/>`).replaceAll(`<${b}>${g}</${b}>`,`<w:endnoteReference w:id="${u}"/>`)}t.
878
+ file("word/document.xml",n);const a=new Map;let o='<w:endnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">';const s=t.file("word/footnotes.xml");if(s){let u=await s.async("\
879
+ text");const g=u.match(/<w:footnotes\b[^>]*>/)?.[0];g&&(o=g.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,
880
+ y=>{const D=/\bw:id="(-?\d+)"/.exec(y)?.[1],$=D?Number(D):NaN;if(!b.has($))return y;const j=r.find(E=>E.syntheticFootnoteId===$);if(!j)return y;const W=y.replace(/^<w:footnote\b[^>]*>/,`<w:endnote w:i\
881
+ d="${j.index}">`).replace(/<\/w:footnote>$/,"</w:endnote>").replaceAll("w:footnoteRef","w:endnoteRef").replaceAll("FootnoteReference","EndnoteReference").replaceAll("FootnoteText","EndnoteText");return a.
882
+ set($,W),""}),t.file("word/footnotes.xml",u);const v=t.file("word/_rels/footnotes.xml.rels");v&&t.file("word/_rels/endnotes.xml.rels",await v.async("text"))}const l=u=>u.replace(/&/g,"&amp;").replace(
883
+ /</g,"&lt;").replace(/>/g,"&gt;"),c=(u,g)=>{const b=u.marks??{},v=[];if(b.bold&&v.push("<w:b/>"),b.italic&&v.push("<w:i/>"),b.underline&&v.push('<w:u w:val="single"/>'),b.strikethrough&&v.push("<w:str\
884
+ ike/>"),b.doubleStrikethrough&&v.push("<w:dstrike/>"),b.smallCaps&&v.push("<w:smallCaps/>"),b.allCaps&&v.push("<w:caps/>"),b.hidden&&v.push("<w:vanish/>"),b.color&&v.push(`<w:color w:val="${l(this.normalizeColor(
885
+ b.color))}"/>`),b.backgroundColor&&v.push(`<w:highlight w:val="${l(b.backgroundColor)}"/>`),typeof b.fontSize=="number"&&b.fontSize>0&&v.push(`<w:sz w:val="${Math.max(2,Math.round(b.fontSize*this.DOCX_HALF_POINTS_PER_PX))}\
886
+ "/>`),b.fontFamily){const D=l(b.fontFamily.split(",")[0].replaceAll('"',"").replaceAll("'","").trim());v.push(`<w:rFonts w:ascii="${D}" w:hAnsi="${D}"/>`)}typeof b.letterSpacing=="number"&&Number.isFinite(
887
+ b.letterSpacing)&&b.letterSpacing!==0&&v.push(`<w:spacing w:val="${Math.round(b.letterSpacing*15)}"/>`),b.superscript?v.push('<w:vertAlign w:val="superscript"/>'):b.subscript&&v.push('<w:vertAlign w:v\
888
+ al="subscript"/>'),b.lang&&v.push(`<w:lang w:val="${l(b.lang)}"/>`);const y=g&&!/^\s/.test(u.text??"")?` ${u.text??""}`:u.text??"";return`<w:r>${v.length>0?`<w:rPr>${v.join("")}</w:rPr>`:""}<w:t xml:s\
889
+ pace="preserve">${l(y)}</w:t></w:r>`},p=r.sort((u,g)=>u.index-g.index).map(({index:u,note:g,syntheticFootnoteId:b})=>{const v=b!==void 0?a.get(b):void 0;if(v)return v;const y=g.children.filter(D=>D.type===
890
+ "paragraph").map((D,$)=>'<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>'+(D.children.filter(j=>(j.text??"")!=="").map(
891
+ (j,W)=>c(j,$===0&&W===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(""),h='<?xml version="1.0" encoding="UTF-8\
892
+ " 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/>\
893
+ </w:r></w:p></w:endnote>'+p+"</w:endnotes>";t.file("word/endnotes.xml",h);const m=t.file("[Content_Types].xml");if(m){let u=await m.async("text");u.includes("/word/endnotes.xml")||(u=u.replace("</Type\
894
+ s>",'<Override PartName="/word/endnotes.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml"/></Types>'),t.file("[Content_Types].xml",u))}const f=t.file("word\
895
+ /_rels/document.xml.rels");if(f){let u=await f.async("text");u.includes("endnotes.xml")||(u=u.replace("</Relationships>",'<Relationship Id="rIdRvseEndnotes" Type="http://schemas.openxmlformats.org/off\
896
+ iceDocument/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:"\
897
+ 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"\
898
+ 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.
899
+ loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const a=await n.async("text"),o=this.parseDocumentXml(a);if(!o)return e;const s=o.getElementsByTagName("w:body")[0];if(!s)return e;const l="\
900
+ http://schemas.openxmlformats.org/wordprocessingml/2006/main",c=Array.from(s.children).filter(O=>O.tagName==="w:p"||O.tagName==="w:tbl"),p=r.children.filter(O=>O.type!=="footnote"&&O.type!=="header-fo\
901
+ oter"),h=new Map,m=[];let f=!0;{let O=0;p.forEach((k,R)=>{k.id&&h.set(k.id,R),m[R]=O,O+=this.emittedBodySlotCount(k)}),O!==c.length&&(console.warn(`docx export: content-control slot accounting mismatc\
902
+ h (${O} computed vs ${c.length} body elements); exporting without sdt wrappers`),f=!1)}const w=O=>{if(O.blockIds&&O.blockIds.length>0)return O.blockIds;const k=O.startBlockId?h.get(O.startBlockId):void 0;
903
+ if(k===void 0)return[];const R=Math.min(k+Math.max(1,O.blockCount??1),p.length);return p.slice(k,R).map(M=>M.id).filter(M=>!!M)};let u=!1;const g=new Map(t.map(O=>[O.id,O])),b=O=>this.parseDocumentXml(
904
+ `<w:root xmlns:w="${l}">${O.prXml}</w:root>`)?.getElementsByTagName("w:sdtPr")[0]??void 0,v=(O,k)=>{const R=O[0].parentNode;if(!R)return;const M=o.createElementNS(l,"w:sdt"),S=o.createElementNS(l,"w:s\
905
+ dtContent");R.insertBefore(M,O[0]),M.appendChild(o.importNode(k,!0)),M.appendChild(S);for(const B of O)S.appendChild(B);u=!0};{const O=Array.from(o.getElementsByTagName("w:bookmarkStart")).filter(k=>(k.
906
+ getAttribute("w:name")??"").startsWith("__rvSdt:"));if(O.length>0){const k=new Map;for(const S of Array.from(o.getElementsByTagName("w:bookmarkEnd"))){const B=S.getAttribute("w:id");B&&k.set(B,S)}const R=S=>{
907
+ S.parentNode&&(S.parentNode.removeChild(S),u=!0)},M=[];for(const S of O){const B=(S.getAttribute("w:name")??"").slice(8).split(":")[0],_=k.get(S.getAttribute("w:id")??""),F=g.get(B);if(!_||!F||F.scope!==
908
+ "inline"||_.parentNode!==S.parentNode||!S.parentNode){R(S),_&&R(_);continue}let H=0;for(let U=S.nextSibling;U&&U!==_;U=U.nextSibling)H++;M.push({record:F,start:S,end:_,covered:H})}M.sort((S,B)=>S.covered-
909
+ B.covered);for(const S of M){const B=S.start.parentNode===S.end.parentNode&&S.start.parentNode?b(S.record):void 0;if(B){const _=[];for(let F=S.start.nextSibling;F&&F!==S.end;F=F.nextSibling)F.nodeType===
910
+ 1&&_.push(F);_.length>0&&v(_,B)}R(S.start),R(S.end)}}}const y=new Map,D=new Map,$=new Map;f&&p.forEach((O,k)=>{if(O.type!=="table")return;const R=c[m[k]];if(!R||R.tagName!=="w:tbl")return;$.set(k,Array.
911
+ from(R.children).filter(B=>B.tagName==="w:tr"));const M=O,S=Qe(M);M.children.forEach((B,_)=>{B.id&&y.set(B.id,{tableIndex:k,rowIndex:_});for(const F of B.children)F.id&&D.set(F.id,{tableIndex:k,rowIndex:_,
912
+ gridCol:S.byId.get(F.id)?.col??0})})});for(const O of t){if(O.scope!=="cell")continue;if(!f)break;const k=(O.blockIds??[]).map(S=>D.get(S)).filter(S=>!!S);if(k.length===0){console.warn(`docx export: c\
913
+ ontent control ${O.id} has no surviving member blocks; dropping wrapper`);continue}const R=b(O);if(!R)continue;const M=new Map;for(const S of k){const B=`${S.tableIndex}:${S.rowIndex}`;M.set(B,[...M.get(
914
+ B)??[],S])}for(const S of M.values()){const B=$.get(S[0].tableIndex)?.[S[0].rowIndex];if(!B)continue;const _=new Set(S.map(I=>I.gridCol)),F=Array.from(B.children).filter(I=>I.tagName==="w:tc"),H=[];let U=0;
915
+ if(F.forEach((I,X)=>{_.has(U)&&H.push(X);const J=this.getDirectChild(I,"w:tcPr"),q=J?this.getDirectChild(J,"w:gridSpan")?.getAttribute("w:val"):void 0,K=q?parseInt(q,10):1;U+=Number.isFinite(K)&&K>0?K:
916
+ 1}),H.length===0)continue;const G=H[0],re=H[H.length-1];v(F.slice(G,re+1),R)}}for(const O of t){if(O.scope!=="row")continue;if(!f)break;const k=(O.blockIds??[]).map(F=>y.get(F)).filter(F=>!!F);if(k.length===
917
+ 0){console.warn(`docx export: content control ${O.id} has no surviving member blocks; dropping wrapper`);continue}const R=b(O);if(!R)continue;const M=k[0].tableIndex,S=$.get(M);if(!S)continue;const B=k.
918
+ filter(F=>F.tableIndex===M).map(F=>F.rowIndex).sort((F,H)=>F-H),_=S.slice(B[0],B[B.length-1]+1).filter(F=>!!F.parentNode);_.length>0&&v(_,R)}const j=O=>{let k=0;const R=new Set([O.id]);let M=O;for(;M?.
919
+ parentId&&!R.has(M.parentId);)R.add(M.parentId),M=g.get(M.parentId),M&&k++;return k},W=t.filter(O=>!O.scope||O.scope==="block").sort((O,k)=>j(k)-j(O));for(const O of W){if(!f)break;const k=w(O).map(H=>h.
920
+ get(H)).filter(H=>H!==void 0).sort((H,U)=>H-U);if(k.length===0){console.warn(`docx export: content control ${O.id} has no surviving member blocks; dropping wrapper`);continue}const R=k[0],M=k[k.length-
921
+ 1],S=m[R];let B=0;for(let H=R;H<=M;H++)B+=this.emittedBodySlotCount(p[H]);if(B===0)continue;const _=[];for(const H of c.slice(S,S+B)){let U=H;for(;U.parentNode&&U.parentNode!==s&&U.parentNode.nodeType===
922
+ 1;)U=U.parentNode;U.parentNode===s&&!_.includes(U)&&_.push(U)}if(_.length===0)continue;const F=b(O);F&&v(_,F)}if(!u)return e;const E=new XMLSerializer().serializeToString(o);i.file("word/document.xml",
923
+ E);const T=await this.generateCompressedZipBlob(i);return new Blob([T],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchParagraphMarkRevisions(e,r,t){
924
+ const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const a=await n.async("text"),o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",s=new DOMParser().parseFromString(
925
+ a,"application/xml"),l=s.getElementsByTagName("w:body")[0];if(!l)return e;const c=[];for(let m=0;m<l.children.length;m++)l.children[m].tagName==="w:p"&&c.push(l.children[m]);for(const m of r){const f=c[m.
926
+ pIndex];if(!f)continue;let w=this.getDirectChild(f,"w:pPr");w||(w=s.createElementNS(o,"w:pPr"),f.insertBefore(w,f.firstChild));let u=this.getDirectChild(w,"w:rPr");if(!u){u=s.createElementNS(o,"w:rPr");
927
+ const b=this.getDirectChild(w,"w:sectPr");b?w.insertBefore(u,b):w.appendChild(u)}const g=s.createElementNS(o,m.kind==="moveFrom"?"w:moveFrom":m.kind==="moveTo"?"w:moveTo":m.kind==="split"||m.kind==="i\
928
+ nsert"?"w:ins":"w:del");g.setAttributeNS(o,"w:id",String(t(m.importedId))),g.setAttributeNS(o,"w:author",m.author),g.setAttributeNS(o,"w:date",m.date),u.insertBefore(g,u.firstChild)}const p=new XMLSerializer().
929
+ serializeToString(s);i.file("word/document.xml",p);const h=await this.generateCompressedZipBlob(i);return new Blob([h],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchParagraphPropertyChanges(e,r,t){
930
+ const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const a=await n.async("text"),o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",s=new DOMParser().parseFromString(
931
+ a,"application/xml"),l=s.getElementsByTagName("w:body")[0];if(!l)return e;const c=[];for(let w=0;w<l.children.length;w++)l.children[w].tagName==="w:p"&&c.push(l.children[w]);const p=(w,u)=>{const g=s.
932
+ createElementNS(o,w);for(const[b,v]of Object.entries(u??{}))g.setAttributeNS(o,b,v);return g},h=w=>{const u=Array.from(s.getElementsByTagName("w:bookmarkStart")).find(v=>v.getAttribute("w:name")===w);
933
+ if(!u)return;const g=u.getAttribute("w:id");let b=u.parentNode;for(;b&&b.tagName!=="w:p";)b=b.parentNode;for(const v of Array.from(s.getElementsByTagName("w:bookmarkEnd")))v.getAttribute("w:id")===g&&
934
+ v.parentNode?.removeChild(v);return u.parentNode?.removeChild(u),b??void 0};for(const w of r){const u=w.marker?h(w.marker):c[w.pIndex];if(!u)continue;let g=this.getDirectChild(u,"w:pPr");g||(g=s.createElementNS(
935
+ o,"w:pPr"),u.insertBefore(g,u.firstChild));const b=p("w:pPrChange",{"w:id":String(t(w.importedId)),"w:author":w.author,"w:date":w.date}),v=w.prior,y=s.createElementNS(o,"w:pPr");if(v.styleId&&y.appendChild(
936
+ p("w:pStyle",{"w:val":v.styleId})),v.keepNext&&y.appendChild(p("w:keepNext")),v.keepLines&&y.appendChild(p("w:keepLines")),v.widowControl===!1&&y.appendChild(p("w:widowControl",{"w:val":"0"})),v.ilvl!==
937
+ void 0){const D=this.getDirectChild(this.getDirectChild(g,"w:numPr")??g,"w:numId")?.getAttribute("w:val");if(D){const $=p("w:numPr");$.appendChild(p("w:ilvl",{"w:val":String(v.ilvl)})),$.appendChild(p(
938
+ "w:numId",{"w:val":D})),y.appendChild($)}}if(v.bordersJson)try{const D=JSON.parse(v.bordersJson),$=s.createElementNS(o,"w:pBdr");for(const j of["top","left","bottom","right"]){const W=D[j];W&&$.appendChild(
939
+ p(`w:${j}`,{"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(/^#/,"")}))}$.children.length>0&&y.appendChild($)}catch{}
940
+ v.shadingFill&&y.appendChild(p("w:shd",{"w:val":"clear","w:fill":this.toDocxHex(v.shadingFill)??"auto"})),v.direction&&y.appendChild(p("w:bidi",v.direction==="ltr"?{"w:val":"0"}:{})),(v.lineSpacing!==
941
+ void 0||v.spaceBeforeTwips!==void 0||v.spaceAfterTwips!==void 0)&&y.appendChild(p("w:spacing",{...v.spaceBeforeTwips!==void 0?{"w:before":String(v.spaceBeforeTwips)}:{},...v.spaceAfterTwips!==void 0?{
942
+ "w:after":String(v.spaceAfterTwips)}:{},...v.lineSpacing!==void 0?{"w:line":String(Math.round(v.lineSpacing*240)),"w:lineRule":"auto"}:{}})),(v.leftIndentTwips!==void 0||v.firstLineIndentTwips!==void 0)&&
943
+ y.appendChild(p("w:ind",{...v.leftIndentTwips!==void 0?{"w:left":String(v.leftIndentTwips)}:{},...v.firstLineIndentTwips!==void 0?{"w:firstLine":String(v.firstLineIndentTwips)}:{}})),v.align&&y.appendChild(
944
+ p("w:jc",{"w:val":v.align==="justify"?"both":v.align})),b.appendChild(y),g.appendChild(b)}const m=new XMLSerializer().serializeToString(s);i.file("word/document.xml",m);const f=await this.generateCompressedZipBlob(
945
+ i);return new Blob([f],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchLinkedMoveRevisions(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word\
946
+ /document.xml");if(!i)return e;const n=await i.async("text"),a="http://schemas.openxmlformats.org/wordprocessingml/2006/main",o=new DOMParser().parseFromString(n,"application/xml"),s=(p,h)=>{const m=o.
947
+ createElementNS(a,h);for(const f of Array.from(p.attributes))m.setAttributeNS(f.namespaceURI,f.name,f.value);for(;p.firstChild;)m.appendChild(p.firstChild);return p.replaceWith(m),m},l=(p,h,m)=>{const f=o.
948
+ createElementNS(a,p);return f.setAttributeNS(a,"w:id",h.rangeId),m&&(f.setAttributeNS(a,"w:name",h.name),f.setAttributeNS(a,"w:author",h.author),f.setAttributeNS(a,"w:date",h.date)),f};for(const p of r){
949
+ const h=p.role==="from"?"w:del":"w:ins",m=p.role==="from"?"w:moveFrom":"w:moveTo",f=new Set(p.wrapperIds.map(String)),w=Array.from(o.getElementsByTagName(h)).filter(y=>f.has(y.getAttribute("w:id")??""));
950
+ if(w.length!==f.size)throw new Error(`linked move ${p.name}/${p.role}: expected ${f.size} temporary revision wrappers, found ${w.length}`);const u=w.map(y=>s(y,m)),g=u[0],b=u[u.length-1],v=p.role==="f\
951
+ rom"?"w:moveFromRange":"w:moveToRange";g.parentNode?.insertBefore(l(`${v}Start`,p,!0),g),b.parentNode?.insertBefore(l(`${v}End`,p,!1),b.nextSibling)}t.file("word/document.xml",new XMLSerializer().serializeToString(
952
+ o));const c=await this.generateCompressedZipBlob(t);return new Blob([c],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchTableRevisions(e,r,t){const i=await this.
953
+ loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const a=await n.async("text"),o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",s=new DOMParser().parseFromString(a,"appl\
954
+ ication/xml"),l=s.getElementsByTagName("w:body")[0];if(!l)return e;const c=Array.from(l.getElementsByTagName("w:tbl")),p=(k,R)=>Array.from(k.children).filter(M=>M.tagName===R),h=(k,R)=>{const M=this.getDirectChild(
955
+ k,R);if(M)return M;const S=s.createElementNS(o,R);return k.insertBefore(S,k.firstChild),S},m=(k,R)=>{const M=new DOMParser().parseFromString(k,"application/xml");if(!(M.getElementsByTagName("parsererr\
956
+ or").length>0||M.documentElement?.tagName!==R))return s.importNode(M.documentElement,!0)},f=(k,R)=>{const M=m(R,"w:tblGrid");if(!M)return this.getDirectChild(k,"w:tblGrid");const S=this.getDirectChild(
957
+ k,"w:tblGrid");if(S)S.replaceWith(M);else{const B=this.getDirectChild(k,"w:tblPr");k.insertBefore(M,B?.nextSibling??k.firstChild)}return M},w=(k,R)=>{const M=m(R,"w:tblPrEx");if(!M)return this.getDirectChild(
958
+ k,"w:tblPrEx");const S=this.getDirectChild(k,"w:tblPrEx");return S?S.replaceWith(M):k.insertBefore(M,k.firstChild),M},u=(k,R,M)=>{const S=m(M,R);if(!S)return h(k,R);const B=this.getDirectChild(k,R);return B?
959
+ B.replaceWith(S):k.insertBefore(S,k.firstChild),S},g={"w:tblPr":["w:tblStyle","w:tblpPr","w:tblOverlap","w:bidiVisual","w:tblStyleRowBandSize","w:tblStyleColBandSize","w:tblW","w:jc","w:tblCellSpacing",
960
+ "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",
961
+ "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",
962
+ "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=(k,R,M,S)=>{const B=h(k,R),_=m(M,R);if(!_)return B;
963
+ const F=[],H=Array.from(B.children),U=Array.from(_.children),G=new Set([...H.map(X=>X.tagName),...U.map(X=>X.tagName)]);for(const X of G){const J=S.has(X)?H:U.some(q=>q.tagName===X)?U:H;for(const q of J.
964
+ filter(K=>K.tagName===X))F.push(s.importNode(q,!0))}const re=new Map(g[R].map((X,J)=>[X,J]));F.sort((X,J)=>(re.get(X.tagName)??Number.MAX_SAFE_INTEGER)-(re.get(J.tagName)??Number.MAX_SAFE_INTEGER));const I=s.
965
+ createElementNS(o,R);for(const X of Array.from(_.attributes))I.setAttributeNS(X.namespaceURI,X.name,X.value);for(const X of F)I.appendChild(X);return B.replaceWith(I),I},v=new Map,y=(k,R)=>{const M=s.
966
+ createElementNS(o,k),S=v;let B;return R.importedId===void 0&&R.revisionGroup&&(B=S.get(R.revisionGroup),B===void 0&&(B=t(),S.set(R.revisionGroup,B))),M.setAttributeNS(o,"w:id",String(R.importedId!==void 0?
967
+ R.importedId:B??t())),M.setAttributeNS(o,"w:author",R.author),M.setAttributeNS(o,"w:date",R.date),M},D=(k,R)=>{let M=0;for(const S of p(k,"w:tc")){if(M===R)return S;const B=this.getDirectChild(S,"w:tc\
968
+ Pr"),_=B?this.getDirectChild(B,"w:gridSpan")?.getAttribute("w:val"):void 0,F=_?Number(_):1;M+=Number.isFinite(F)&&F>0?F:1}},$=(k,R)=>{const M=nr(R);if(!M)return;const S=s.createElementNS(o,"w:tblBorde\
969
+ rs"),B=[["top","top"],["bottom","bottom"],["left","left"],["right","right"],["insideH","insideH"],["insideV","insideV"]];for(const[_,F]of B){const H=M[_];if(!H)continue;const U=s.createElementNS(o,`w:${F}`);
970
+ 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(/^#/,"")),S.appendChild(U)}S.children.length>0&&k.
971
+ appendChild(S)},j=(k,R,M)=>{for(const S of p(k,R))S.remove();M&&k.appendChild(M)},W=(k,R)=>{const M=nr(R);if(!M)return;const S=s.createElementNS(o,k),B=[["top","top"],["bottom","bottom"],["left","left"],
972
+ ["right","right"],...k==="w:tblBorders"?[["insideH","insideH"],["insideV","insideV"]]:[]];for(const[_,F]of B){const H=M[_];if(!H)continue;const U=s.createElementNS(o,`w:${F}`);U.setAttributeNS(o,"w:va\
973
+ l",H.style),U.setAttributeNS(o,"w:sz",String(Math.max(0,Math.round(H.width*6)))),U.setAttributeNS(o,"w:color",H.color.replace(/^#/,"")),S.appendChild(U)}return S.children.length>0?S:void 0},E=(k,R)=>{
974
+ let M;if(typeof R=="number"&&Number.isFinite(R))M={top:R,right:R,bottom:R,left:R};else if(typeof R=="string")try{M=JSON.parse(R)}catch{return}if(!M)return;const S=s.createElementNS(o,k);for(const B of[
975
+ "top","right","bottom","left"]){const _=M[B];if(!Number.isFinite(_))continue;const F=s.createElementNS(o,`w:${B}`);F.setAttributeNS(o,"w:w",String(Math.round(_*15))),F.setAttributeNS(o,"w:type","dxa"),
976
+ S.appendChild(F)}return S.children.length>0?S:void 0},T=(k,R,M,S,B,_)=>{const F=G=>Object.prototype.hasOwnProperty.call(M??{},G)||Object.prototype.hasOwnProperty.call(S??{},G);if(R==="w:tblPr"){if(F("\
977
+ tableWidth")){const G=M?.tableWidth;let re;typeof G=="number"&&Number.isFinite(G)&&(re=s.createElementNS(o,"w:tblW"),re.setAttributeNS(o,"w:w",String(Math.round(G*15))),re.setAttributeNS(o,"w:type","d\
978
+ xa")),j(k,"w:tblW",re)}if(F("align")){const G=M?.align;let re;(G==="left"||G==="center"||G==="right")&&(re=s.createElementNS(o,"w:jc"),re.setAttributeNS(o,"w:val",G)),j(k,"w:jc",re)}if(F("borders")&&j(
979
+ k,"w:tblBorders",typeof M?.borders=="string"?W("w:tblBorders",M.borders):void 0),F("borderColor")||F("borderWidth")){let G=this.getDirectChild(k,"w:tblBorders");if(!G){G=s.createElementNS(o,"w:tblBord\
980
+ ers");for(const re of["top","left","bottom","right","insideH","insideV"]){const I=s.createElementNS(o,`w:${re}`);I.setAttributeNS(o,"w:val","single"),G.appendChild(I)}k.appendChild(G)}for(const re of Array.
981
+ from(G.children)){if(F("borderColor")){const I=M?.borderColor;re.setAttributeNS(o,"w:color",typeof I=="string"&&I?I.replace(/^#/,""):"auto")}if(F("borderWidth")){const I=M?.borderWidth;re.setAttributeNS(
982
+ o,"w:sz",typeof I=="number"&&Number.isFinite(I)?String(Math.max(0,Math.round(I*6))):"4")}}}F("cellPadding")&&j(k,"w:tblCellMar",E("w:tblCellMar",M?.cellPadding))}else if(R==="w:tcPr"){if(F("background\
983
+ Color")){const G=M?.backgroundColor;let re;typeof G=="string"&&G&&(re=s.createElementNS(o,"w:shd"),re.setAttributeNS(o,"w:fill",G.replace(/^#/,""))),j(k,"w:shd",re)}if(F("verticalAlign")){const G=M?.verticalAlign;
984
+ let re;(G==="top"||G==="middle"||G==="bottom")&&(re=s.createElementNS(o,"w:vAlign"),re.setAttributeNS(o,"w:val",G==="middle"?"center":G)),j(k,"w:vAlign",re)}F("borders")&&j(k,"w:tcBorders",typeof M?.borders==
985
+ "string"?W("w:tcBorders",M.borders):void 0),F("padding")&&j(k,"w:tcMar",E("w:tcMar",M?.padding))}if(R==="w:trPr"&&(G=>Object.prototype.hasOwnProperty.call(B??{},G)||Object.prototype.hasOwnProperty.call(
986
+ _??{},G))("hasHeader")){const G=B?.hasHeader?s.createElementNS(o,"w:tblHeader"):void 0;j(k,"w:tblHeader",G)}const H=new Map(g[R].map((G,re)=>[G,re])),U=Array.from(k.children).sort((G,re)=>(H.get(G.tagName)??
987
+ Number.MAX_SAFE_INTEGER)-(H.get(re.tagName)??Number.MAX_SAFE_INTEGER));for(const G of U)k.appendChild(G)};for(const k of r){const R=c[k.tableIndex];if(!R)continue;const M=p(R,"w:tr");k.propertyOverrides?.
988
+ table&&b(R,"w:tblPr",k.propertyOverrides.table,new Set(["w:tblW","w:jc","w:tblBorders","w:tblCellMar"])),k.propertyOverrides?.grid&&f(R,k.propertyOverrides.grid);for(const S of k.propertyOverrides?.rows??
989
+ []){const B=M[S.rowIndex];B&&b(B,"w:trPr",S.xml,new Set(["w:tblHeader"]))}for(const S of k.propertyOverrides?.rowExceptions??[]){const B=M[S.rowIndex];B&&w(B,S.xml)}for(const S of k.propertyOverrides?.
990
+ cells??[]){const B=M[S.rowIndex],_=B?D(B,S.gridColumn):void 0;_&&b(_,"w:tcPr",S.xml,new Set(["w:tcW","w:gridSpan","w:vMerge","w:tcBorders","w:shd","w:tcMar","w:vAlign"]))}for(const S of k.rowProperties){
991
+ const B=M[S.rowIndex];B&&(S.currentXml?u(B,"w:trPr",S.currentXml):T(h(B,"w:trPr"),"w:trPr",S.currentAttributes,S.priorAttributes,S.currentTableAttributes,S.priorTableAttributes))}for(const S of k.rowExceptionProperties){
992
+ const B=M[S.rowIndex];B&&w(B,S.currentXml)}for(const S of k.cellProperties){const B=M[S.rowIndex],_=B?D(B,S.gridColumn):void 0;_&&(S.currentXml?u(_,"w:tcPr",S.currentXml):T(h(_,"w:tcPr"),"w:tcPr",S.currentAttributes,
993
+ S.priorAttributes))}for(const S of k.rows){const B=M[S.rowIndex];B&&h(B,"w:trPr").appendChild(y(S.kind==="insert"?"w:ins":"w:del",S))}for(const S of k.cells){const B=M[S.rowIndex],_=B?D(B,S.gridColumn):
994
+ void 0;_&&h(_,"w:tcPr").appendChild(y(S.kind==="insert"?"w:cellIns":"w:cellDel",S))}for(const S of k.merges){const B=M[S.rowIndex],_=B?D(B,S.gridColumn):void 0;if(!_)continue;const F=y("w:cellMerge",S);
995
+ S.vMerge&&F.setAttributeNS(o,"w:vMerge",S.vMerge),S.vMergeOrig&&F.setAttributeNS(o,"w:vMergeOrig",S.vMergeOrig),h(_,"w:tcPr").appendChild(F)}if(k.tableGrid){const S=f(R,k.tableGrid.currentXml);if(S){const B=y(
996
+ "w:tblGridChange",k.tableGrid),_=m(k.tableGrid.priorXml,"w:tblGrid");_&&B.appendChild(_),S.appendChild(B)}}for(const S of k.rowProperties){const B=M[S.rowIndex];if(!B)continue;const _=y("w:trPrChange",
997
+ S),F=h(B,"w:trPr"),H=S.priorXml?m(S.priorXml,"w:trPr"):F.cloneNode(!0);if(H){if(!S.priorXml){for(const U of["w:ins","w:del","w:trPrChange"])for(const G of p(H,U))G.remove();T(H,"w:trPr",S.priorAttributes,
998
+ S.currentAttributes,S.priorTableAttributes,S.currentTableAttributes)}_.appendChild(H)}F.appendChild(_)}for(const S of k.rowExceptionProperties){const B=M[S.rowIndex];if(!B)continue;const _=this.getDirectChild(
999
+ B,"w:tblPrEx")??w(B,S.currentXml);if(!_)continue;const F=y("w:tblPrExChange",S),H=m(S.priorXml,"w:tblPrEx");H&&F.appendChild(H),_.appendChild(F)}for(const S of k.cellProperties){const B=M[S.rowIndex],
1000
+ _=B?D(B,S.gridColumn):void 0;if(!_)continue;const F=y("w:tcPrChange",S),H=h(_,"w:tcPr"),U=S.priorXml?m(S.priorXml,"w:tcPr"):H.cloneNode(!0);if(U){if(!S.priorXml){for(const G of["w:cellIns","w:cellDel",
1001
+ "w:cellMerge","w:tcPrChange"])for(const re of p(U,G))re.remove();T(U,"w:tcPr",S.priorAttributes,S.currentAttributes)}F.appendChild(U)}H.appendChild(F)}if(k.tableProperties){const S=k.tableProperties.currentXml?
1002
+ u(R,"w:tblPr",k.tableProperties.currentXml):h(R,"w:tblPr");k.tableProperties.currentXml||T(S,"w:tblPr",k.tableProperties.currentAttributes,k.tableProperties.priorAttributes);const B=y("w:tblPrChange",
1003
+ k.tableProperties);let _;k.tableProperties.priorXml&&(_=m(k.tableProperties.priorXml,"w:tblPr")),_||(_=S.cloneNode(!0),T(_,"w:tblPr",k.tableProperties.priorAttributes,k.tableProperties.currentAttributes),
1004
+ k.tableProperties.priorBorders&&$(_,k.tableProperties.priorBorders)),B.appendChild(_),S.appendChild(B)}}i.file("word/document.xml",new XMLSerializer().serializeToString(s));const O=await this.generateCompressedZipBlob(
1005
+ i);return new Blob([O],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static inferDocumentFontFamily(e){if(!e?.children)return;const r=new Map;let t=0;const i=(o,s)=>{
1006
+ for(const l of o){if(l.type!=="text")continue;const c=l.text.length;if(c===0)continue;t+=c;const p=l.marks?.fontFamily??s;p&&r.set(p,(r.get(p)??0)+c)}};for(const o of e.children)if(o.type==="paragraph"){
1007
+ const s=o;i(o.children,s.fontFamily)}else if(o.type==="list")for(const s of o.children)i(s.children);if(t===0)return;let n,a=0;for(const[o,s]of r)s>a&&(n=o,a=s);return n&&a*2>t?n:void 0}static codeBlockStyleId(e){
1008
+ 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],["he\
1009
+ ading3",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=[],
1010
+ t=new Set,i=n=>{for(const a of n)if(a.type==="code"&&!a.renderDiagram)t.add(this.codeBlockStyleId(a.language));else if(a.type==="container"||a.type==="footnote"||a.type==="table-cell")i(a.children);else if(a.
1011
+ type==="table")for(const o of a.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.
1012
+ 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(){
1013
+ 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(
1014
+ e),n=this.buildOrderedNumberingExportPlan(e).byListId;this.exportOrderedPlan=n,this.exportLinkedMoveSides=this.collectLinkedMoveSides(e.children),this.exportLinkedMoveBlockIds=this.collectLinkedMoveBlockIds(
1015
+ e.children,this.exportLinkedMoveSides);const a=this.collectTextlessMoveHalves(e.children);for(const o of e.children){if(a.destinations.has(o.id))continue;const s=a.sources.has(o.id)?this.withoutMoveState(
1016
+ o):o;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.
1017
+ tocBlockToDocxParagraphs(s,e))}return r}static tocBlockToDocxParagraphs(e,r,t){const i=Fi(e),n=_i(r,Wi(e)),a=Ee(r.pageLayout),o=tr(a),s=Math.max(o.pageWidth-a.marginLeftPx-a.marginRightPx,96),l=e.direction===
1018
+ "rtl",c=this.docxAlignmentForExport({type:"paragraph",id:e.id,children:[],direction:e.direction??"ltr",align:e.align??(l?"right":"left")}),p={bidirectional:l,alignment:c},h=JSON.stringify([{pos:Math.round(
1019
+ s),align:"right",leader:"dot"}]),m=e.fontFamily??this.inferDocumentFontFamily(r),f=this.toDocxHex(e.color),w={...m?{font:m}:{},...e.fontSize?{size:Math.round(e.fontSize*this.DOCX_HALF_POINTS_PER_PX)}:
1020
+ {},...f?{color:f}:{}};if(n.length===0)return[{type:"paragraph",...p,children:[{text:" ",fieldInstr:i,...w}]}];const u=24;return n.map(g=>({type:"paragraph",...p,children:[{text:`${g.text} `,fieldInstr:i,
1021
+ ...w,...l?{rightToLeft:!0}:{}},...t?.has(g.blockId)?[{text:String(t.get(g.blockId)),fieldInstr:i,...w,rightToLeft:!1}]:[]],tabStopsJson:h,...g.level>1?{indent:{left:this.pxToTwips((g.level-1)*u)}}:{}}))}static toDocxFormatWithTables(e,r,t,i){
1022
+ const n=[],a=this.inferDocumentFontFamily(e);this.exportDefaultRunSizeHalfPoints=this.inferDefaultRunSizeHalfPoints(e);const o=r||Qi,s=this.resolveIndentStepPx(e),l=this.buildOrderedNumberingExportPlan(
1023
+ e).byListId;this.exportOrderedPlan=l,this.exportLinkedMoveSides=this.collectLinkedMoveSides(e.children),this.exportLinkedMoveBlockIds=this.collectLinkedMoveBlockIds(e.children,this.exportLinkedMoveSides);
1024
+ const c=this.styleExportContext(e),p=this.collectTextlessMoveHalves(e.children);for(const f of e.children){const w=n.length;if(p.destinations.has(f.id)){i?.push({blockId:f.id,start:w,count:0});continue}
1025
+ const u=p.sources.has(f.id)?this.withoutMoveState(f):f;if(u.type==="paragraph")n.push(this.styledParagraphToDocxWithMath(u,a,s,c));else if(u.type==="list")n.push(...this.listToDocxParagraphsWithMath(u,
1026
+ a,l));else if(u.type==="table")n.push(this.tableToDocxWithMath(u,a,s,c));else if(u.type==="code"){const g=this.legacyLatexCodeBlockAsMath(u);n.push(g?this.mathBlockToDocx(g):this.codeBlockToDocx(u,o))}else if(u.
1027
+ type==="math")n.push(this.mathBlockToDocx(u));else if(u.type==="image")n.push(this.imageBlockToDocx(u));else if(u.type==="page-break")n.push({type:"pagebreak"});else if(u.type==="section-break"){const g=u.
1028
+ diffState==="delete"&&u.suggestionId?/^docxrev-(\d+)$/.exec(u.suggestionId):null;n.push({type:"sectionbreak",...u.layout?{layout:u.layout}:{},...u.breakType?{breakType:u.breakType}:{},...u.diffState===
1029
+ "delete"?{pendingDeletion:{author:u.suggestionAuthorName??"Anonymous",date:new Date(u.suggestionCreatedAt??Date.now()).toISOString(),...g?{importedId:Number(g[1])}:{}}}:{}})}else u.type==="toc"?n.push(
1030
+ ...this.tocBlockToDocxParagraphs(u,e,t)):u.type==="docx-raw"&&(cr(u.xml)?n.push(this.styledParagraphToDocxWithMath({type:"paragraph",id:u.id,children:[{type:"text",text:""}]},a,s,c)):n.push({type:"doc\
1031
+ xraw",sourceBlockId:u.id,xml:u.xml,origin:u.origin,emitsParagraph:u.origin==="run"}));i?.push({blockId:u.id,start:w,count:n.length-w})}const h=this.pxToTwips(Ee(e.pageLayout).blockSpacingPx),m=f=>{for(const w of f.
1032
+ rows)for(const u of w.cells){for(const g of u.paragraphs)g.spacingAfterTwips??(g.spacingAfterTwips=h),g.spacingBeforeTwips??(g.spacingBeforeTwips=0);for(const g of u.blocks??[])g.type==="paragraph"?(g.
1033
+ spacingAfterTwips??(g.spacingAfterTwips=h),g.spacingBeforeTwips??(g.spacingBeforeTwips=0)):m(g)}};for(const f of n)f.type==="paragraph"?f.styleProvidesSpacing||(f.spacingAfterTwips??(f.spacingAfterTwips=
1034
+ h),f.spacingBeforeTwips??(f.spacingBeforeTwips=0)):f.type==="table"&&m(f);return n}static applyExportParagraphSpacing(e,r){typeof r.spaceBefore=="number"&&(e.spacingBeforeTwips=this.pxToTwips(r.spaceBefore)),
1035
+ typeof r.spaceAfter=="number"&&(e.spacingAfterTwips=this.pxToTwips(r.spaceAfter)),r.contextualSpacing&&(e.contextualSpacing=!0)}static latexToOmml(e,r){const t=Fr();if(!t)return"";try{const i=t.renderToString(
1036
+ e,{output:"mathml",displayMode:r,throwOnError:!1});let n=En(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>$/,
1037
+ "</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:"ma\
1038
+ th",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,
1039
+ 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.
1040
+ originalFormat,originalDataUrl:e.originalDataUrl,anchorXml:e.anchorXml}}static buildParagraphIndent(e,r){const t=e.leftIndent===0?0:Xi(e.leftIndent),i=e.firstLineIndent===0?0:zi(e.firstLineIndent),n={};
1041
+ return t!==void 0&&(n.left=this.pxToTwips(rr(t,r))),i!==void 0&&(i<0?n.hanging=this.pxToTwips(rr(-i,r)):n.firstLine=this.pxToTwips(rr(i,r))),Object.keys(n).length>0?n:void 0}static headerRowIndexes(e){
1042
+ if(!e.hasHeader)return new Set;const r=new Set;try{const n=JSON.parse(e.structuralSuggestionRecords??"[]");for(const a of Array.isArray(n)?n:[])if(a?.type==="table-change")for(const o of a.tableRevision?.
1043
+ markers??[])o.kind==="row-delete"&&o.rowId&&r.add(o.rowId)}catch{}const t=new Set([0]),i=e.children.findIndex(n=>n.diffState!=="delete"&&!(n.id&&r.has(n.id)));return i>0&&t.add(i),t}static tableToDocx(e,r){
1044
+ const t=Qe(e),i=this.headerRowIndexes(e);return{type:"table",rows:e.children.map((n,a)=>{const o=i.has(a);return{cells:n.children.map(s=>{const l=[],c=[];for(const h of s.children)if(h.type==="paragra\
1045
+ ph"){const m=this.paragraphToDocx(h,r);m.inTableCell=!0,l.push(m),c.push(m)}else if(h.type==="list"){const m=this.listToDocxParagraphs(h,r,this.exportOrderedPlan);for(const f of m)f.inTableCell=!0;l.push(
1046
+ ...m),c.push(...m)}else h.type==="table"&&c.push(this.tableToDocx(h,r));const p=t.byId.get(s.id);return{paragraphs:l,...c.some(h=>h.type==="table")?{blocks:c}:{},backgroundColor:s.backgroundColor,verticalAlign:s.
1047
+ verticalAlign,borders:s.borders,padding:s.padding,colSpan:p&&p.colSpan>1?p.colSpan:void 0,rowSpan:p&&p.rowSpan>1?p.rowSpan:void 0,gridColumn:p?.col,...s.oxmlTcPr?{oxmlTcPr:s.oxmlTcPr}:{}}}),isHeader:o,
1048
+ ...n.oxmlAttrs?{oxmlAttrs:n.oxmlAttrs}:{},...n.oxmlTrPr?{oxmlTrPr:n.oxmlTrPr}:{}}}),columnWidths:e.columnWidths||[],hasHeader:e.hasHeader,tableWidth:e.tableWidth,align:e.align,cellPadding:e.cellPadding,
1049
+ 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=en(i);if(n&&e.renderDiagram!==
1050
+ !1&&n){const s=tn({protocol:n,source:t,theme:mn(),maxWidth:900});return{type:"codeblock",content:"",language:i,runs:[],backgroundColor:r.background,renderDiagram:!0,diagramPngDataUrl:s?.dataUrl,diagramWidth:s?.
1051
+ width,diagramHeight:s?.height}}const a=i?rn(t,i,r):null,o=[];if(a&&a.length>0)for(const s of a){const l=s.text.split(`
1052
+ `);for(let c=0;c<l.length;c++)l[c]&&o.push({text:l[c],font:"Courier New",color:this.normalizeColor(s.color)}),c<l.length-1&&o.push({text:`
1053
+ `,font:"Courier New",break:!0})}else{const s=t.split(`
1054
+ `);for(let l=0;l<s.length;l++)s[l]&&o.push({text:s[l],font:"Courier New",color:this.normalizeColor(r.default)}),l<s.length-1&&o.push({text:`
1055
+ `,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.
1056
+ stylesXml;if(!r)return;let t;const i=new Map;return n=>{if(!n)return;const a=i.get(n);if(a)return a;t??(t=this.parseStylesXml(r));const o=this.resolveRunMarks(void 0,n,{styles:t});return i.set(n,o),o}}static styleExportContext(e){
1057
+ return{stylesheet:e.stylesheet,styleMarksFor:this.createStyleMarksResolver(e)}}static styledParagraphToDocxWithMath(e,r,t,i){const n=e.styleId?un(i.stylesheet,e.styleId)?.paragraphAttrs:void 0,a=this.
1058
+ stripStyleProvidedParagraphAttrs(e,n),o=i.styleMarksFor?.(e.styleId),s=this.paragraphToDocxWithMath(a,o?.fontFamily?void 0:r,t,o);return a.spaceAfter===void 0&&e.spaceAfter!==void 0&&(s.styleProvidesSpacing=
1059
+ !0),s}static stripStyleProvidedParagraphAttrs(e,r){if(!r)return e;const t={...e},i=(n,a)=>n!==void 0&&a!==void 0&&Math.abs(n-a)<.011;return t.align!==void 0&&t.align===r.align&&delete t.align,i(t.lineSpacing,
1060
+ 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.
1061
+ 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,
1062
+ 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&&
1063
+ 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("\
1064
+ '","").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){
1065
+ const n=this.exportDefaultRunSizeHalfPoints;(e.heading||i?.fontSize)&&(this.exportDefaultRunSizeHalfPoints=void 0);try{return this.paragraphToDocxWithMathInner(e,r,t,i)}finally{this.exportDefaultRunSizeHalfPoints=
1066
+ 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.
1067
+ heading}`);{const s=this.docxAlignmentForExport(e);s&&(n.alignment=s)}e.lineSpacing!==void 0&&(n.lineSpacing=e.lineSpacing),this.applyExportParagraphSpacing(n,e),e.keepNext&&(n.keepNext=!0),e.keepLines&&
1068
+ (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.
1069
+ oxmlAttrs),e.oxmlPPr&&(n.oxmlPPr=e.oxmlPPr);const a=this.buildParagraphIndent(e,t);a&&(n.indent=a);const o=e;if(o.fontFamily&&(n.style=o.fontFamily),this.applyParagraphMarkRevisionInfo(n,e),this.applyParagraphPropertyChangeInfo(
1070
+ n,e,t),e.children.length===0)return this.applyWholeBlockRevisionInfo(n,e),this.applyBidiExportFlags(n,e),n;for(const s of this.dropReplacementSeparators(this.runRevisionsForBlockChange(e)))if(s.type===
1071
+ "text"){const l=i&&e.styleId?{...s,marks:this.stripStyleProvidedMarks(s.marks,i)}:s,c=this.textNodeToDocxWithLatex(l,r);n.children.push(...c)}return this.applyWholeBlockRevisionInfo(n,e),this.applyBidiExportFlags(
1072
+ n,e),n}static docxAlignmentForExport(e){if(!e.align)return;const r=e.direction==="rtl"||e.direction===void 0&&$t(this.paragraphNodeText(e))==="rtl",t=r&&e.align==="left"?"right":r&&e.align==="right"?"\
1073
+ 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"){$t(t)==="rtl"&&(e.bidirectional=
1074
+ !1);return}if(r.direction==="rtl"||r.direction===void 0&&$t(t)==="rtl"){e.bidirectional=!0;for(const i of e.children)i.text&&nn(i.text)&&(i.rightToLeft=!0)}}static listToDocxParagraphsWithMath(e,r,t){
1075
+ e=this.listWithItemRevisions(e);const i=[],n={level0:(e.startNumber??1)-1,level1:0,level2:0};for(const a of e.children){if(a.type!=="list-item")continue;const o=this.getClampedIndentLevel(a.indentLevel),
1076
+ s={type:"paragraph",sourceBlockId:a.id,children:[],lineSpacing:a.lineSpacing??e.lineSpacing,...typeof(a.spaceBefore??e.spaceBefore)=="number"?{spacingBeforeTwips:this.pxToTwips(a.spaceBefore??e.spaceBefore)}:
1077
+ {},...typeof(a.spaceAfter??e.spaceAfter)=="number"?{spacingAfterTwips:this.pxToTwips(a.spaceAfter??e.spaceAfter)}:{},...e.contextualSpacing?{contextualSpacing:!0}:{},list:{variant:e.variant,level:o,label:"",
1078
+ checked:e.variant==="todo"?!!a.checked:void 0,reference:t?.get(e.id)?.reference??this.getDocxListReference(e),instance:t?.get(e.id)?.instance??0}},l=this.getListLabel(e,a,n);if(s.list&&(s.list.label=l),
1079
+ e.variant==="todo"&&s.children.push({text:`${l} `}),a.children.length>0){for(const c of a.children)if(c.type==="text"){const p=this.textNodeToDocxWithLatex(c,r);s.children.push(...p)}}this.applyWholeBlockRevisionInfo(
1080
+ s,a.structuralSuggestionKind?a:e),this.applyParagraphPropertyChangeInfo(s,a,0),i.push(s)}return i}static tableToDocxWithMath(e,r,t=this.resolveIndentStepPx(),i){const n=Qe(e),a=[],o=this.headerRowIndexes(
1081
+ e);for(let s=0;s<e.children.length;s++){const l=e.children[s],c=o.has(s),p=[];for(const h of l.children){const m=[],f=[];for(const u of h.children)if(u.type==="paragraph"){const g=i?this.styledParagraphToDocxWithMath(
1082
+ u,r,t,i):this.paragraphToDocxWithMath(u,r,t);g.inTableCell=!0,m.push(g),f.push(g)}else if(u.type==="list"){const g=this.listToDocxParagraphsWithMath(u,r,this.exportOrderedPlan);for(const b of g)b.inTableCell=
1083
+ !0;m.push(...g),f.push(...g)}else u.type==="table"&&f.push(this.tableToDocxWithMath(u,r,t,i));const w=n.byId.get(h.id);p.push({paragraphs:m,...f.some(u=>u.type==="table")?{blocks:f}:{},backgroundColor:h.
1084
+ backgroundColor,verticalAlign:h.verticalAlign,borders:h.borders,padding:h.padding,colSpan:w&&w.colSpan>1?w.colSpan:void 0,rowSpan:w&&w.rowSpan>1?w.rowSpan:void 0,gridColumn:w?.col,...h.oxmlTcPr?{oxmlTcPr:h.
1085
+ oxmlTcPr}:{}})}a.push({cells:p,isHeader:c,...l.oxmlAttrs?{oxmlAttrs:l.oxmlAttrs}:{},...l.oxmlTrPr?{oxmlTrPr:l.oxmlTrPr}:{}})}return{type:"table",rows:a,columnWidths:e.columnWidths||[],hasHeader:e.hasHeader,
1086
+ 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){
1087
+ 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??
1088
+ "{}");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 a=typeof r.
1089
+ structuralSuggestionId=="string"?/^docxrev-(\d+)$/.exec(r.structuralSuggestionId):null;a&&(n=Number(a[1])),e.paragraphMarkRevision={kind:r.structuralSuggestionKind,author:t,date:i,...n!==void 0?{importedId:n}:
1090
+ {}}}static applyWholeBlockRevisionInfo(e,r){if(r.structuralSuggestionKind!=="insert"&&r.structuralSuggestionKind!=="delete")return;const t=this.linkedMoveSideFor(r.structuralSuggestionId,r.structuralSuggestionKind);
1091
+ if(t&&!this.isInLinkedMoveRange(r,t.move.role)){const s={kind:r.structuralSuggestionKind,author:t.author,date:t.date};e.paragraphMarkRevision=s;for(const l of e.children)l.text&&(l.revision??(l.revision=
1092
+ s));return}if(t){e.paragraphMarkRevision={kind:t.move.role==="from"?"moveFrom":"moveTo",author:t.author,date:t.date};const s=/^\d+$/.test(t.move.wrapperId)?Number(t.move.wrapperId):void 0;e.children.length===
1093
+ 0&&e.children.push({text:""});for(const l of e.children)l.revision??(l.revision={kind:r.structuralSuggestionKind,author:t.author,date:t.date,...s!==void 0?{importedId:s}:{},move:t.move});return}let i="\
1094
+ Anonymous",n=new Date().toISOString();try{const s=JSON.parse(r.structuralSuggestionRecord??"{}");typeof s.agentName=="string"&&s.agentName.trim()?i=s.agentName.trim():s.authorType==="ai"&&(i=Ct),typeof s.
1095
+ createdAt=="number"&&(n=new Date(s.createdAt).toISOString())}catch{}const a=typeof r.structuralSuggestionId=="string"?/^docxrev-(\d+)$/.exec(r.structuralSuggestionId):null,o={kind:r.structuralSuggestionKind,
1096
+ author:i,date:n,...a?{importedId:Number(a[1])}:{}};e.paragraphMarkRevision=o;for(const s of e.children){if(o.kind==="delete"&&s.revision?.kind==="insert"&&!s.revision.move&&!s.revision.layeredInsertion){
1097
+ s.revision={kind:"delete",author:i,date:n,layeredInsertion:{author:s.revision.author,date:s.revision.date,...s.revision.importedId!==void 0?{importedId:s.revision.importedId}:{}}};continue}s.revision??
1098
+ (s.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!=="bloc\
1099
+ k-change"||i.beforeBlock?.type!=="paragraph")return;const n=i.beforeBlock;let a="Anonymous";typeof i.agentName=="string"&&i.agentName.trim()?a=i.agentName.trim():i.authorType==="ai"&&(a=Ct);const o=typeof i.
1100
+ createdAt=="number"?new Date(i.createdAt).toISOString():new Date().toISOString(),s=typeof r.structuralSuggestionId=="string"?/^docxrev-(\d+)$/.exec(r.structuralSuggestionId):null,l=this.buildParagraphIndent(
1101
+ n,t);e.paragraphPropertiesChange={author:a,date:o,...s?{importedId:Number(s[1])}:{},prior:{...typeof n.indentLevel=="number"?{ilvl:n.indentLevel}:{},...n.align?{align:n.align}:{},...l?.left!==void 0?{
1102
+ leftIndentTwips:l.left}:{},...l?.firstLine!==void 0?{firstLineIndentTwips:l.firstLine}:{},...n.lineSpacing!==void 0?{lineSpacing:n.lineSpacing}:{},...typeof n.spaceBefore=="number"?{spaceBeforeTwips:this.
1103
+ pxToTwips(n.spaceBefore)}:{},...typeof n.spaceAfter=="number"?{spaceAfterTwips:this.pxToTwips(n.spaceAfter)}:{},...n.keepNext?{keepNext:!0}:{},...n.keepLines?{keepLines:!0}:{},...n.widowControl===!1?{
1104
+ 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:`Headi\
1105
+ ng${n.heading}`}:{}}}}static collectTableRevisionPatches(e){const r=[];let t=0;const i=[],n=o=>{for(const s of o)if(s.type==="table"){i.push(s);for(const l of s.children)for(const c of l.children)n(c.
1106
+ children)}else s.type==="container"&&n(s.children)};n(e.children);const a=this.collectLinkedMoveSides(e.children);for(const o of i){const s=t++,l=o.diffState==="insert"||o.diffState==="delete"?o.diffState:
1107
+ void 0,c=l&&typeof o.suggestionId=="string"?a.get(o.suggestionId)?.[l==="delete"?"from":"to"]:void 0;if(l&&c){r.push({tableIndex:s,rows:o.children.map((y,D)=>({rowIndex:D,kind:l,author:c.author,date:c.
1108
+ date,revisionGroup:`${o.suggestionId}\0${l}`})),cells:[],merges:[],rowProperties:[],rowExceptionProperties:[],cellProperties:[]});continue}let p=[];if(o.structuralSuggestionRecords)try{const y=JSON.parse(
1109
+ o.structuralSuggestionRecords);Array.isArray(y)&&(p=y.filter(D=>D?.type==="table-change"))}catch{}let h;if(o.docxTablePropertyOverrides)try{const y=JSON.parse(o.docxTablePropertyOverrides);y?.version===
1110
+ 1&&(h=y)}catch{}if(p.length>0||h){const y={tableIndex:s,rows:[],cells:[],merges:[],rowProperties:[],rowExceptionProperties:[],cellProperties:[]},D=Qe(o),$=new Map(o.children.map((E,T)=>[E.id,T])),j=(E,T)=>{
1111
+ const O=T.author?.trim()||E.agentName?.trim()||(E.authorType==="ai"?Ct:"Anonymous"),k=typeof T.createdAt=="number"?T.createdAt:typeof E.createdAt=="number"?E.createdAt:Date.now(),R=T.revisionId??/^docxrev-(\d+)$/.
1112
+ exec(E.id)?.[1],M=typeof R=="string"&&/^\d+$/.test(R)?Number(R):void 0;return{author:O,date:new Date(k).toISOString(),revisionGroup:E.id,...M!==void 0?{importedId:M}:{}}},W=E=>{const T=E.map(k=>Number.
1113
+ isFinite(k)&&k>0?k:1),O=T.reduce((k,R)=>k+R,0)||1;return`<w:tblGrid xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${T.map(k=>`<w:gridCol w:w="${Math.max(1,Math.round(k/O*1e4))}\
1114
+ "/>`).join("")}</w:tblGrid>`};if(h){const E={...h.table?{table:h.table}:{},...h.grid&&JSON.stringify(h.grid.columnWidths)===JSON.stringify(o.columnWidths)?{grid:h.grid.xml}:{},rows:[],rowExceptions:[],
1115
+ cells:[]};for(const[T,O]of Object.entries(h.rows??{})){const k=$.get(T);k!==void 0&&E.rows.push({rowIndex:k,xml:O})}for(const[T,O]of Object.entries(h.rowExceptions??{})){const k=$.get(T);k!==void 0&&E.
1116
+ rowExceptions.push({rowIndex:k,xml:O})}for(const[T,O]of Object.entries(h.cells??{})){const k=D.byId.get(T);k&&E.cells.push({rowIndex:k.row,gridColumn:k.col,xml:O})}y.propertyOverrides=E}for(const E of p){
1117
+ for(const T of E.tableRevision.markers){const O=j(E,T);if(T.kind==="row-insert"||T.kind==="row-delete"){const S=T.rowId?$.get(T.rowId):T.rowIndex;S!==void 0&&y.rows.push({rowIndex:S,kind:T.kind==="row\
1118
+ -insert"?"insert":"delete",...O});continue}if(T.kind==="cell-insert"||T.kind==="cell-delete"){const S=T.cellId?D.byId.get(T.cellId):void 0,B=S?.row??T.rowIndex,_=S?.col??T.gridColumn;B!==void 0&&_!==void 0&&
1119
+ y.cells.push({rowIndex:B,gridColumn:_,kind:T.kind==="cell-insert"?"insert":"delete",...O});continue}if(T.kind==="cell-merge"){const S=T.rowId?$.get(T.rowId):T.rowIndex;S!==void 0&&T.gridColumn!==void 0&&
1120
+ y.merges.push({rowIndex:S,gridColumn:T.gridColumn,...O,...T.vMerge?{vMerge:T.vMerge}:{},...T.vMergeOrig?{vMergeOrig:T.vMergeOrig}:{}});continue}if(T.kind==="table-grid"&&T.currentPropertiesXml&&T.priorPropertiesXml){
1121
+ y.tableGrid={...O,currentXml:T.currentPropertiesXml,priorXml:T.priorPropertiesXml};continue}const k=E.tableRevision.operations.find(S=>S.kind==="properties"&&(T.kind==="table-properties"&&S.target==="\
1122
+ table"||T.kind==="row-properties"&&S.target==="row"&&(!T.rowId||S.rowId===T.rowId)||T.kind==="row-exception-properties"&&S.target==="row-exception"&&(!T.rowId||S.rowId===T.rowId)||T.kind==="cell-prope\
1123
+ rties"&&S.target==="cell"&&(!T.cellId||S.cellId===T.cellId))),R=T.currentPropertiesXml??(k?.kind==="properties"?k.currentPropertiesXml:void 0),M=T.priorPropertiesXml??(k?.kind==="properties"?k.priorPropertiesXml:
1124
+ void 0);if(T.kind==="table-properties")y.tableProperties={...O,...R?{currentXml:R}:{},...M?{priorXml:M}:{},...k?.kind==="properties"?{currentAttributes:k.currentAttributes,priorAttributes:k.priorAttributes}:
1125
+ {}};else if(T.kind==="row-properties"||T.kind==="row-exception-properties"){const S=T.rowId?$.get(T.rowId):T.rowIndex;S!==void 0&&(T.kind==="row-properties"?y.rowProperties:y.rowExceptionProperties).push(
1126
+ {rowIndex:S,...O,currentXml:R??"",priorXml:M??"",...k?.kind==="properties"?{currentAttributes:k.currentAttributes,priorAttributes:k.priorAttributes,currentTableAttributes:k.currentTableAttributes,priorTableAttributes:k.
1127
+ priorTableAttributes}:{}})}else if(T.kind==="cell-properties"){const S=T.cellId?D.byId.get(T.cellId):void 0,B=S?.row??T.rowIndex,_=S?.col??T.gridColumn;B!==void 0&&_!==void 0&&y.cellProperties.push({rowIndex:B,
1128
+ gridColumn:_,...O,...R?{currentXml:R}:{},...M?{priorXml:M}:{},...k?.kind==="properties"?{currentAttributes:k.currentAttributes,priorAttributes:k.priorAttributes}:{}})}}if(!y.tableGrid){const T=E.tableRevision.
1129
+ operations.find(O=>O.kind==="grid");T?.kind==="grid"&&(y.tableGrid={...j(E,{}),currentXml:T.currentGridXml||W(T.currentColumnWidths),priorXml:T.priorGridXml||W(T.priorColumnWidths)})}}(y.rows.length||
1130
+ 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!==
1131
+ "change"||!o.structuralSuggestionRecord)continue;let m;try{m=JSON.parse(o.structuralSuggestionRecord)}catch{continue}if(m.type!=="block-change"||m.beforeBlock?.type!=="table"||m.acceptedBlock?.type!==
1132
+ "table")continue;const f=/^docxrev-(\d+)$/.exec(o.structuralSuggestionId??"")?.[1],w=y=>{const D=typeof y?.author=="string"&&y.author.trim()?y.author.trim():typeof m.agentName=="string"&&m.agentName.trim()?
1133
+ m.agentName.trim():m.authorType==="ai"?Ct:"Anonymous",$=typeof y?.createdAt=="number"&&Number.isFinite(y.createdAt)?y.createdAt:typeof m.createdAt=="number"&&Number.isFinite(m.createdAt)?m.createdAt:Date.
1134
+ now(),j=y?.revisionId??f,W=typeof j=="string"&&/^\d+$/.test(j)?Number(j):void 0;return{author:D,date:new Date($).toISOString(),...W!==void 0?{importedId:W}:{}}},u={tableIndex:s,rows:[],cells:[],merges:[],
1135
+ rowProperties:[],rowExceptionProperties:[],cellProperties:[]},g=m.docxTableRevisions,b=Qe(o),v=new Map(o.children.map((y,D)=>[y.id,D]));if(g?.version===1){for(const y of g.rows??[]){const D=v.get(y.rowId);
1136
+ D!==void 0&&u.rows.push({rowIndex:D,kind:y.kind,...w(y)})}for(const y of g.cells??[]){const D=b.byId.get(y.cellId);D&&u.cells.push({rowIndex:D.row,gridColumn:D.col,kind:y.kind,...w(y)})}for(const y of g.
1137
+ merges??[]){const D=v.get(y.rowId);D!==void 0&&u.merges.push({rowIndex:D,gridColumn:y.gridColumn,...w(y),...y.vMerge?{vMerge:y.vMerge}:{},...y.vMergeOrig?{vMergeOrig:y.vMergeOrig}:{}})}g.tableProperties&&
1138
+ (u.tableProperties={...w(g.tableProperties),...g.tableProperties.priorXml?{priorXml:g.tableProperties.priorXml}:{},...m.beforeBlock.borders?{priorBorders:m.beforeBlock.borders}:{}})}else{const y=new Set(
1139
+ m.beforeBlock.children.map(W=>W.id)),D=new Set(m.acceptedBlock.children.map(W=>W.id));for(let W=0;W<o.children.length;W++){const E=o.children[W];!y.has(E.id)&&D.has(E.id)?u.rows.push({rowIndex:W,kind:"\
1140
+ insert",...w()}):y.has(E.id)&&!D.has(E.id)&&u.rows.push({rowIndex:W,kind:"delete",...w()})}const $=Qe(m.beforeBlock),j=Qe(m.acceptedBlock);for(const W of b.cells){const E=$.byId.has(W.cell.id),T=j.byId.
1141
+ has(W.cell.id);!E&&T?u.cells.push({rowIndex:W.row,gridColumn:W.col,kind:"insert",...w()}):E&&!T&&u.cells.push({rowIndex:W.row,gridColumn:W.col,kind:"delete",...w()});const O=$.byId.get(W.cell.id)?.rowSpan??
1142
+ 1,k=j.byId.get(W.cell.id)?.rowSpan??1;if(k>O&&W.rowSpan>O)for(let R=O;R<Math.min(k,W.rowSpan);R++)u.merges.push({rowIndex:W.row+R,gridColumn:W.col,vMerge:"cont",...w()})}m.beforeBlock.borders!==m.acceptedBlock.
1143
+ borders&&(u.tableProperties={...w(),...m.beforeBlock.borders?{priorBorders:m.beforeBlock.borders}:{}})}(u.rows.length>0||u.cells.length>0||u.merges.length>0||u.tableProperties)&&r.push(u)}return r}static listWithItemRevisions(e){
1144
+ const r=s=>{try{return s?JSON.parse(s):null}catch{return null}},t=s=>{const l={...s};return delete l.structuralSuggestionId,delete l.structuralSuggestionKind,delete l.structuralSuggestionLabel,delete l.
1145
+ structuralSuggestionRecord,l},i=s=>JSON.stringify(s.flatMap(l=>{const c=JSON.stringify(Object.entries(l.marks??{}).filter(([p,h])=>!p.startsWith("suggestion")&&h!==void 0&&h!==null&&h!==!1).map(([p,h])=>[
1146
+ p,p==="fontFamily"&&typeof h=="string"?h.split(",")[0].replace(/['"]/g,"").trim().toLowerCase():h]).sort(([p],[h])=>String(p).localeCompare(String(h))));return Array.from(l.text,p=>`${p}${c}`)})),n=(s,l,c,p)=>{
1147
+ let h=t(s);const m={suggestionId:c,...p.authorType?{suggestionAuthorType:p.authorType}:{},...p.agentName?{suggestionAuthorName:p.agentName}:{},...p.createdAt!==void 0?{suggestionCreatedAt:p.createdAt}:
1148
+ {}},f=[...s.children,...l.children].some(g=>g.marks?.insertion||g.marks?.deletion||g.marks?.formatChange);if(l.children.length>0&&!f&&i(l.children)!==i(s.children)){const g=(b,v)=>b.map(y=>({...y,marks:{
1149
+ ...y.marks,...m,[v]:!0}}));h={...h,children:[...g(l.children,"deletion"),...g(s.children,"insertion")]}}const w={};let u=!1;(l.indentLevel??0)!==(s.indentLevel??0)&&(w.indentLevel=l.indentLevel??0,u=!0);
1150
+ for(const g of this.LIST_ITEM_PROPERTY_FIELDS){const b=l[g]??e[g],v=s[g]??e[g];b!==void 0&&(w[g]=b),JSON.stringify(b)!==JSON.stringify(v)&&(u=!0)}return u&&(h={...h,structuralSuggestionId:c,structuralSuggestionKind:"\
1151
+ change",structuralSuggestionRecord:JSON.stringify({type:"block-change",beforeBlock:{type:"paragraph",id:s.id,...w},agentName:p.agentName,authorType:p.authorType,createdAt:p.createdAt})}),h},a=e.structuralSuggestionKind===
1152
+ "change"?r(e.structuralSuggestionRecord):null,o=a?.type==="block-change"&&a.beforeBlock?.type==="list"?a.beforeBlock:null;if(o&&e.structuralSuggestionId){const s=e.structuralSuggestionId,l=a,c=(g,b)=>({
1153
+ ...t(g),structuralSuggestionId:s,structuralSuggestionKind:b,structuralSuggestionRecord:JSON.stringify({agentName:l.agentName,authorType:l.authorType,createdAt:l.createdAt})}),p=new Set(e.children.map(
1154
+ g=>g.id)),h=new Map(o.children.map(g=>[g.id,g])),m=new Map;let f=null;for(const g of o.children)p.has(g.id)?f=g.id:m.set(f,[...m.get(f)??[],c(g,"delete")]);const w=[...m.get(null)??[]];for(const g of e.
1155
+ children){const b=h.get(g.id);w.push(b?n(g,b,s,l):c(g,"insert"),...m.get(g.id)??[])}const u={...e,children:w};return delete u.structuralSuggestionKind,u}return e.children.some(s=>s.structuralSuggestionKind===
1156
+ "change")?{...e,children:e.children.map(s=>{if(s.structuralSuggestionKind!=="change")return s;const l=r(s.structuralSuggestionRecord),c=l?.listItemSuggestion?.beforeItem;return!l||!c||!s.structuralSuggestionId?
1157
+ s:n(s,c.children.length>0?c:{...c,children:s.children},s.structuralSuggestionId,l)})}:e}static pendingListNumberingChanges(e){const r=[],t=i=>{if(i.type==="list"){if(i.structuralSuggestionKind==="chan\
1158
+ ge")try{const n=JSON.parse(i.structuralSuggestionRecord??"{}").beforeBlock;n?.type==="list"&&(n.variant!==i.variant||(n.startNumber??1)!==(i.startNumber??1)||(n.numberingFormat??null)!==(i.numberingFormat??
1159
+ null))&&r.push(i.id)}catch{}return}if(i.type==="table")for(const n of i.children)for(const a of n.children)a.children.forEach(t);else if("children"in i&&Array.isArray(i.children))for(const n of i.children)
1160
+ n&&typeof n=="object"&&"type"in n&&t(n)};return e.forEach(t),r}static pendingLinkChangeAsReplacement(e){const r=e.marks;if(!r?.formatChange||r.insertion||r.deletion)return null;let t;try{t=JSON.parse(
1161
+ r.suggestionPriorAttributes??"{}")}catch{return null}if((t.link??null)===(r.link??null))return null;const i=Object.fromEntries(Object.entries(r).filter(([a])=>a.startsWith("suggestion")&&a!=="suggesti\
1162
+ onPriorAttributes")),n=Object.fromEntries(Object.entries(r).filter(([a])=>a!=="formatChange"&&!a.startsWith("suggestion")));return[{...e,marks:{...t,...i,deletion:!0}},{...e,marks:{...n,...i,insertion:!0}}]}static runRevisionsForBlockChange(e){
1163
+ if(e.structuralSuggestionKind!=="change")return e.children;let r;try{r=JSON.parse(e.structuralSuggestionRecord??"{}")}catch{return e.children}const t=r.beforeBlock;if(r.type!=="block-change"||t?.type!==
1164
+ "paragraph")return e.children;const i=s=>s.map(l=>l.type==="text"?l.text:"\0").join("");if(i(t.children)!==i(e.children)||[...t.children,...e.children].some(s=>s.type!=="text"||s.marks?.insertion||s.marks?.
1165
+ deletion||s.marks?.formatChange))return e.children;const n=s=>JSON.stringify(s.map(l=>{const c=Object.fromEntries(Object.entries(l.marks??{}).filter(([p])=>!p.startsWith("suggestion")).sort(([p],[h])=>p.
1166
+ localeCompare(h)));return[l.text,c]}));if(n(t.children)===n(e.children))return e.children;const a={suggestionId:e.structuralSuggestionId,...r.authorType?{suggestionAuthorType:r.authorType}:{},...r.agentName?
1167
+ {suggestionAuthorName:r.agentName}:{},...r.createdAt!==void 0?{suggestionCreatedAt:r.createdAt}:{}},o=(s,l)=>s.map(c=>({...c,marks:{...c.marks,...a,[l]:!0}}));return[...o(t.children,"deletion"),...o(e.
1168
+ children,"insertion")]}static dropReplacementSeparators(e){return e.filter((r,t)=>{if(r.type!=="text")return!0;const i=r;if(i.marks?.insertion||i.marks?.deletion||!/^\s+$/.test(i.text))return!0;const n=e[t-
1169
+ 1],a=e[t+1];return!(n?.type==="text"&&a?.type==="text"&&n.marks?.deletion&&a.marks?.insertion&&a.marks.suggestionId&&n.marks.suggestionId===a.marks.suggestionId)})}static textNodeToDocxWithLatex(e,r){
1170
+ 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={
1171
+ 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!==
1172
+ 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=
1173
+ 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&&
1174
+ (i.indent=n);const a=e;return a.fontFamily&&(i.style=a.fontFamily),this.applyParagraphMarkRevisionInfo(i,e),this.applyParagraphPropertyChangeInfo(i,e,t),e.children.length===0?(this.applyWholeBlockRevisionInfo(
1175
+ i,e),this.applyBidiExportFlags(i,e),i):(this.dropReplacementSeparators(this.runRevisionsForBlockChange(e)).forEach(o=>{if(o.type==="text"){const s=this.textNodeToDocx(o,r);i.children.push(...s)}}),this.
1176
+ applyWholeBlockRevisionInfo(i,e),this.applyBidiExportFlags(i,e),i)}static listToDocxParagraphs(e,r,t){e=this.listWithItemRevisions(e);const i=[],n={level0:(e.startNumber??1)-1,level1:0,level2:0};for(const a of e.
1177
+ children){if(a.type!=="list-item")continue;const o=this.getClampedIndentLevel(a.indentLevel),s={type:"paragraph",sourceBlockId:a.id,children:[],lineSpacing:a.lineSpacing??e.lineSpacing,...typeof(a.spaceBefore??
1178
+ e.spaceBefore)=="number"?{spacingBeforeTwips:this.pxToTwips(a.spaceBefore??e.spaceBefore)}:{},...typeof(a.spaceAfter??e.spaceAfter)=="number"?{spacingAfterTwips:this.pxToTwips(a.spaceAfter??e.spaceAfter)}:
1179
+ {},...e.contextualSpacing?{contextualSpacing:!0}:{},list:{variant:e.variant,level:o,label:"",checked:e.variant==="todo"?!!a.checked:void 0,reference:t?.get(e.id)?.reference??this.getDocxListReference(
1180
+ e),instance:t?.get(e.id)?.instance??0}},l=this.getListLabel(e,a,n);s.list&&(s.list.label=l),e.variant==="todo"&&s.children.push({text:`${l} `}),a.children.length>0&&a.children.forEach(c=>{if(c.type===
1181
+ "text"){const p=this.textNodeToDocx(c,r);s.children.push(...p)}}),this.applyWholeBlockRevisionInfo(s,a.structuralSuggestionKind?a:e),this.applyParagraphPropertyChangeInfo(s,a,0),i.push(s)}return i}static marksToDocxRunOptions(e,r){
1182
+ 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),
1183
+ 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),
1184
+ 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=
1185
+ !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));
1186
+ 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="Cou\
1187
+ rier 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!==
1188
+ 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?.
1189
+ 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+)$/.
1190
+ exec(e.suggestionId):null;return{author:r,date:t,...i?{importedId:Number(i[1])}:{}}}static textNodeToDocx(e,r){const t=this.pendingLinkChangeAsReplacement(e);if(t)return t.flatMap(o=>this.textNodeToDocx(
1191
+ o,r));const i=this.marksToDocxRunOptions(e.marks,r);if(e.marks?.comment&&(i.comment=e.marks.comment),e.marks?.bookmark&&(i.bookmark=e.marks.bookmark),e.marks?.oxmlRange&&(i.oxmlRange=e.marks.oxmlRange),
1192
+ e.marks?.sdtInline&&(i.sdtInline=e.marks.sdtInline),e.marks?.fieldInstr&&(i.fieldInstr=e.marks.fieldInstr),e.marks?.insertion||e.marks?.deletion){const o=this.parseDocxMoveMark(e.marks.docxMove),s=o&&
1193
+ /^\d+$/.test(o.wrapperId)?Number(o.wrapperId):void 0;let l;if(e.marks.deletion&&e.marks.layeredInsertion)try{const c=JSON.parse(e.marks.layeredInsertion),p=typeof c.id=="string"?/^docxrev-(\d+)$/.exec(
1194
+ c.id):null;l={author:c.authorName?.trim()||(c.authorType==="ai"?"Revise Agent":"Anonymous"),date:new Date(typeof c.createdAt=="number"?c.createdAt:Date.now()).toISOString(),...p?{importedId:Number(p[1])}:
1195
+ {}}}catch{l=void 0}i.revision={kind:e.marks.deletion?"delete":"insert",...this.suggestionRevisionAttrs(e.marks),...s!==void 0?{importedId:s}:{},...o?{move:o}:{},...l?{layeredInsertion:l}:{}}}else if(e.
1196
+ marks?.formatChange){let o={};try{o=JSON.parse(e.marks.suggestionPriorAttributes??"{}")}catch{o={}}i.rPrChange={...this.suggestionRevisionAttrs(e.marks),prior:this.marksToDocxRunOptions(o)}}if(e.marks?.
1197
+ footnoteRef){const o=parseInt(e.text,10);return[{...i,text:"",footnoteReference:Number.isFinite(o)&&o>0?o:1}]}const n=e.text.split(`
1198
+ `),a=[];for(let o=0;o<n.length;o++){const s=n[o];(s||o===0)&&a.push({...i,text:s}),o<n.length-1&&a.push({...i,text:"",break:!0})}return a.length===0&&a.push({...i,text:""}),a}static getListIndentOptions(e){
1199
+ 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.
1200
+ 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.
1201
+ 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,
1202
+ t=new Map,i=new Map,n=new Map,a=s=>{if(s.variant==="ordered")if(s.numberingChainId){const l=s.numberingChainId;let c=i.get(l);if(!c||s.startNumber!==void 0){const p=c?c.segmentIndex+1:0,h=`revise-chai\
1203
+ n-${l.replace(/[^A-Za-z0-9_-]/g,"")}-s${p}`;c={reference:h,segmentIndex:p},i.set(l,c),t.set(h,{start:s.startNumber??1,formatJson:s.numberingFormat})}r.set(s.id,{reference:c.reference,instance:0})}else{
1204
+ const l=s.startNumber??1,c=s.numberingFormat?`revise-ordered-${l}-f${this.numberingFormatHash(s.numberingFormat)}`:`revise-ordered-${l}`;t.has(c)||t.set(c,{start:l,formatJson:s.numberingFormat});const p=n.
1205
+ get(c)??0;n.set(c,p+1),r.set(s.id,{reference:c,instance:p})}},o=s=>{for(const l of s)if(l.type==="list")a(l);else if(l.type==="container"||l.type==="footnote")o(l.children);else if(l.type==="table")for(const c of l.
1206
+ children)for(const p of c.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"?
1207
+ "revise-unordered":`revise-ordered-${e.startNumber??1}`}static buildDocxNumberingConfig(e,r){const t=[];let i=!1;const n=s=>{for(const l of s)if(l.type==="list"&&l.variant==="unordered")i=!0;else if(l.
1208
+ type==="container"||l.type==="footnote")n(l.children);else if(l.type==="table")for(const c of l.children)for(const p of c.children)n(p.children)};n(e.children),e.notes&&n(e.notes);const a=this.buildOrderedNumberingExportPlan(
1209
+ e).references;i&&t.push({reference:"revise-unordered",levels:[0,1,2].map(s=>({level:s,format:r.LevelFormat.BULLET,text:["•","◦","▪"][s],alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,
1210
+ style:{paragraph:{indent:this.getListIndentOptions(s)}}}))});const o=s=>{switch((s||"decimal").trim()){case"lowerLetter":return r.LevelFormat.LOWER_LETTER;case"upperLetter":return r.LevelFormat.UPPER_LETTER;case"\
1211
+ 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.
1212
+ BULLET;case"none":return r.LevelFormat.NONE??r.LevelFormat.DECIMAL;default:return r.LevelFormat.DECIMAL}};for(const[s,l]of a){const c=l.start,p=l.formatJson?(()=>{try{const h=JSON.parse(l.formatJson);
1213
+ return Array.isArray(h)?h:void 0}catch{return}})():void 0;if(p){t.push({reference:s,levels:[0,1,2].map(h=>({level:h,format:o(p[h]?.numFmt),text:p[h]?.lvlText??["%1.","%1.%2.","%1.%2.%3."][h],start:h===
1214
+ 0?c:1,alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(h)}}}))});continue}t.push({reference:s,levels:[{level:0,format:r.LevelFormat.DECIMAL,
1215
+ text:"%1.",start:c,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.
1216
+ 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,
1217
+ 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),
1218
+ 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+=
1219
+ 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){
1220
+ 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,a]of r){for(;t>=n;)i+=a,t-=n;
1221
+ 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.
1222
+ match(/^data:([^;,]+)(;base64)?,(.*)$/i);if(r){const t=r[1].toLowerCase(),i=this.docxImageTypeForMimeType(t);if(!i)return;const n=!!r[2],a=r[3]||"",o=n?this.base64ToUint8Array(a):new TextEncoder().encode(
1223
+ decodeURIComponent(a));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(
1224
+ 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(
1225
+ 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.
1226
+ 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"\
1227
+ 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?Rr(e)?.slice(1).toUpperCase():void 0}static normalizeColor(e){
1228
+ return this.toDocxHex(e)??"000000"}static highlightValueToColor(e){return or(e)??"yellow"}static colorToHighlight(e){const r=or(e);if(r)return{yellow:"yellow",orange:"darkYellow",green:"green",blue:"b\
1229
+ lue",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:"mage\
1230
+ nta","00FFFF":"cyan",808080:"darkGray",D3D3D3:"lightGray"}[t]||"yellow"}};ue.LIST_BASE_INDENT_TWIPS=720,ue.LIST_INDENT_INCREMENT_TWIPS=360,ue.LIST_HANGING_INDENT_TWIPS=360,ue.TWIPS_PER_INCH=1440,ue.TWIPS_PER_PX=
1231
+ ue.TWIPS_PER_INCH/96,ue.DOCX_HALF_POINTS_PER_PX=1.5,ue.DEFAULT_RUN_SIZE_HALF_POINTS=ue.pxToDocxHalfPoints(Ae.paragraph),ue.PAGE_SIZE_PRESETS=Object.entries(Pi).map(([L,e])=>({preset:L,width:Math.min(e.
1232
+ width,e.height),height:Math.max(e.width,e.height)})),ue.CORE_PROPERTY_LOCAL_NAMES=["title","creator","subject","keywords","description","lastModifiedBy","created","modified","revision"],ue.LIST_ITEM_PROPERTY_FIELDS=
1233
+ ["spaceBefore","spaceAfter","lineSpacing","direction"],ue.TODO_MARKERS=[["☒ ",!0],["☐ ",!1],["[x] ",!0],["[X] ",!0],["[ ] ",!1]],ue.fallbackCommentState={},ue.sdtAncestorStack=[],ue.OXML_RANGE_PAIRS=
1234
+ new Map([["w:permStart","w:permEnd"]]),ue.UNTRACKABLE_MOVE_KINDS=new Set(["image","code","math","page-break","toc"]),ue.OMML_FUNCTION_NAMES=["sin","cos","tan","cot","sec","csc","arcsin","arccos","arct\
1235
+ an","sinh","cosh","tanh","coth","log","ln","lg","exp","det","dim","ker","deg","gcd","hom","arg","max","min","sup","inf","lim","liminf","limsup","Pr"],ue.CODE_BLOCK_STYLE_ID="CodeBlock",ue.CODE_INLINE_STYLE_ID=
1236
+ "CodeInline";let Dn=ue;export{Dn as DocxConverter};