revise 1.0.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +962 -0
- package/FONT-LICENSE-HAN-EXT-B.txt +91 -0
- package/FONT-LICENSE-KATEX.txt +95 -0
- package/FONT-LICENSE-LIBERATION.txt +102 -0
- package/FONT-LICENSE-NOTO-MULTILINGUAL.txt +93 -0
- package/FONT-LICENSE-NOTO-SANS-SC.txt +93 -0
- package/FONT-LICENSE-NOTO.txt +94 -0
- package/FONT-LICENSE-SOURCE-CODE-PRO.txt +94 -0
- package/FONT-LICENSE-SOURCE-SERIF-4.txt +93 -0
- package/LICENSE +41 -21
- package/README.md +39 -1
- package/THIRD-PARTY-NOTICES.md +3376 -0
- package/assets/historyMaterializeWorker-CoAX9ZAi.js +3 -0
- package/backend.d.ts +133 -0
- package/backend.js +1 -0
- package/chunks/AgentPageRenderer-C0n4EnuW.js +1 -0
- package/chunks/AgentPageRenderer-DURfmiu0.js +1 -0
- package/chunks/AttachmentDocumentImporter-DSic_6At.js +1 -0
- package/chunks/AttachmentDocumentImporter-dNMtkxrv.js +1 -0
- package/chunks/BidiText-B4Hzrjg9.js +1 -0
- package/chunks/ColorParserFull-BKH72fK8.js +1 -0
- package/chunks/DocumentStylesheet-byN5dtC6.js +1 -0
- package/chunks/DocxConverter-B7P52lw7.js +11 -0
- package/chunks/DocxConverter-COV6CjUM.js +11 -0
- package/chunks/DocxConverter-Cq_zCEJC.js +11 -0
- package/chunks/DocxGraft-CJ12C9WP.js +1 -0
- package/chunks/DocxGraft-CQpvFcYb.js +1 -0
- package/chunks/DocxGraft-DcmFuUkd.js +1 -0
- package/chunks/FileImporter-DVnYOJHp.js +1 -0
- package/chunks/FileImporter-q9mCch0J.js +1 -0
- package/chunks/HorizontalRuleOrnaments-gmUZ3R7Q.js +1 -0
- package/chunks/HtmlConverter-JvRlkQM3.js +61 -0
- package/chunks/ListNumbering-Qlu6AuRZ.js +1 -0
- package/chunks/MarkdownConverter-B-tPY7X3.js +17 -0
- package/chunks/MathRenderer-B0Y1h1JU.js +33 -0
- package/chunks/OdtConverter-Br81BSoJ.js +1 -0
- package/chunks/OdtConverter-CQjh0vlo.js +1 -0
- package/chunks/OdtConverter-DYHnR4E8.js +1 -0
- package/chunks/PdfConverter-D26rXumc.js +21 -0
- package/chunks/PdfConverter-DGZpUSVf.js +21 -0
- package/chunks/PdfConverter-DZzVP0-B.js +21 -0
- package/chunks/PdfImportService-CBD8TL1k.js +2 -0
- package/chunks/PdfImportService-D6uUKGMf.js +2 -0
- package/chunks/RtfConverter-BQGge3K-.js +14 -0
- package/chunks/RtfConverter-CMfZ4olw.js +14 -0
- package/chunks/RtfConverter-oIwzoqCD.js +14 -0
- package/chunks/TableBorders-BLkZYt1k.js +1 -0
- package/chunks/TableGrid-DVWaRZv0.js +1 -0
- package/chunks/TextFileDecoder--rsVs3NR.js +2 -0
- package/chunks/TxtConverter-C1lp6dBS.js +11 -0
- package/chunks/__vite-browser-external-l0sNRNKZ.js +0 -0
- package/chunks/_commonjsHelpers-DaMA6jEr.js +1 -0
- package/chunks/_revise-sdk-lazy-harfbuzz-CDWdjF9f.js +1 -0
- package/chunks/_revise-sdk-lazy-harfbuzz-X8gnYTZL.js +1 -0
- package/chunks/ar-kgSWdrXF.js +8 -0
- package/chunks/backend-Cq-khfdG.js +1 -0
- package/chunks/base64-CfDUyGi8.js +36 -0
- package/chunks/browser-module-6b2Fq-5C.js +3 -0
- package/chunks/browser-module-CFmqfGkE.js +3 -0
- package/chunks/browser-module-CkO57IPL.js +3 -0
- package/chunks/bundle.min-DRpfgV69.js +8 -0
- package/chunks/capture-DU3MC7tb.js +1 -0
- package/chunks/carrier-WgcRSu7a.js +1 -0
- package/chunks/de-C2QTHrqo.js +8 -0
- package/chunks/es-BKboUn4q.js +8 -0
- package/chunks/footnoteFlatten-CW-DUcgK.js +1 -0
- package/chunks/graftExport-CVg7PO2A.js +2 -0
- package/chunks/html2canvas.esm-CntiHiYW.js +5 -0
- package/chunks/index-BWdRWxoH.js +24 -0
- package/chunks/index-CLw_BlSL.js +353 -0
- package/chunks/index-F-kHIwWT.js +353 -0
- package/chunks/index.es-CI0QPo8w.js +5 -0
- package/chunks/index.es-DOqegDGr.js +5 -0
- package/chunks/index.es-tXDO0RMv.js +5 -0
- package/chunks/jspdf.es.min-CzYti8jo.js +77 -0
- package/chunks/jspdf.es.min-DU74zN8b.js +77 -0
- package/chunks/jspdf.es.min-ejWOGhkJ.js +77 -0
- package/chunks/jszip.min-CPW0h1Kx.js +2 -0
- package/chunks/katex-DWj8TvwO.js +261 -0
- package/chunks/pdf-BLWDCiFF.js +12 -0
- package/chunks/persistInlineDocumentImages-DQj2iaqg.js +1 -0
- package/chunks/pseudoLocale-CdBtPHRi.js +1 -0
- package/chunks/pseudoLocale-DEVWLkGC.js +1 -0
- package/chunks/purify.es-BwLardii.js +2 -0
- package/chunks/serverDocumentSession-DZrYbdpk.js +42 -0
- package/chunks/tree-sitter-D6zWWUMP.js +4 -0
- package/chunks/wasmInline.generated-CBYFkdSM.js +1 -0
- package/chunks/web-tree-sitter-BXGZGnNj.js +1 -0
- package/full.js +1 -0
- package/index.d.ts +929 -0
- package/index.js +1 -0
- package/package.json +93 -26
- package/root.d.ts +5 -0
- package/root.js +2 -0
- package/serverToolContract.d.ts +373 -0
- package/serverToolInputs.generated.d.ts +229 -0
- package/style.css +1 -0
- package/.npmignore +0 -4
- package/.travis.yml +0 -16
- package/revise.js +0 -16
- package/t/cover +0 -18
- package/t/revise/comparator.t.js +0 -31
- package/t/revise/extractor.t.js +0 -29
- package/t/test +0 -20
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{a5 as ke,a6 as gi,a7 as Cr,a8 as ui,c as fi,h as wi,a9 as kr,aa as bi,ab as yi,ac as xi,ad as Te,ae as vi,af as Si,ag as Ii,ah as Pi,ai as Bt,aj as Dt,ak as Ci,al as ki,am as It,an as Ai,ao as qt,_ as qe,ap as Ar,aq as Ni,ar as Nr,as as Ti,at as Vt,au as Ei,av as Mi,aw as Bi,ax as Di,q as Ri,t as Fi,G as Oi,I as $i,ay as Tr,az as Li,aA as _i,W as Xi,X as Wi,aB as zi,aC as Hi,aD as ji,aE as Yt,aF as Gi,aG as Ji,y as Ui,aH as Zi,aI as Ki,aJ as qi,aK as Er,aL as Vi,aM as Yi,m as Qt,aN as Mr,aO as Qi,aP as en,aQ as tn,aR as Br,aS as er,aT as rn,aU as nn}from"./index-F-kHIwWT.js";const Dr=()=>new XMLSerializer,Rr=new Set(["w:rStyle","w:b","w:i","w:u","w:strike","w:dstrike","w:smallCaps","w:caps","w:vanish","w:lang","w:spacing","w:vertAlign","w:color","w:highlight","w:shd","w:rFonts","w:sz","w:rPrChange","w:bCs","w:iCs","w:szCs","w:highlightCs","w:ins","w:del","w:rtl","w:specVanish","w:imprint","w:emboss","w:snapToGrid"]),Fr=new Set(["w:pStyle","w:keepNext","w:keepLines","w:widowControl","w:bidi","w:jc","w:ind","w:pageBreakBefore","w:spacing","w:contextualSpacing","w:outlineLvl","w:numPr","w:pBdr","w:shd","w:tabs","w:rPr","w:sectPr","w:pPrChange"]),Or=new Set(["w:tblStyle","w:tblW","w:jc","w:tblInd","w:tblBorders","w:tblLayout","w:tblCellMar","w:tblPrChange"]),$r=new Set(["w:tblHeader","w:ins","w:del","w:trPrChange"]),Lr=new Set(["w:tcW","w:gridSpan","w:vMerge","w:tcBorders","w:shd","w:tcMar","w:vAlign","w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"]),_r=new Set(["w:pgSz","w:pgMar","w:pgNumType","w:lnNumType","w:cols","w:type","w:docGrid","w:titlePg","w:headerReference","w:footerReference","w:sectPrChange","w:rPr"]);function rt(O,e){if(!O)return;let r="";const t=Dr();for(let i=0;i<O.children.length;i++){const n=O.children[i];e.has(n.tagName)||(r+=t.serializeToString(n))}return r?rr(r):void 0}function tr(O){if(!O||O.attributes.length===0)return;const e={};for(let i=0;i<O.attributes.length;i++){const n=O.attributes[i];n.name==="xmlns"||n.name.startsWith("xmlns:")||(e[n.name]=n.value)}const r=Object.keys(e).sort();if(r.length===0)return;const t={};for(const i of r)t[i]=e[i];return JSON.stringify(t)}function rr(O){if(!/[\n\r\t]/.test(O))return O;let e="",r=!1,t=null;for(let i=0;i<O.length;i++){const n=O[i];if(t){n===t?(t=null,e+=n):n===`
|
|
2
|
+
`?e+=" ":n==="\r"?e+=" ":n===" "?e+="	":e+=n;continue}r&&(n==='"'||n==="'")?t=n:n==="<"?r=!0:n===">"&&(r=!1),e+=n}return e}function ir(O){const e=rr(Dr().serializeToString(O));let r;const t=O.getElementsByTagName("o:OLEObject")[0];if(t)r=t.getAttribute("ProgID")??void 0;else if(O.tagName==="w:altChunk")r=O.getAttribute("r:id")??void 0;else{const i=O.getElementsByTagName("a:graphicData")[0]?.getAttribute("uri")?.split("/").filter(Boolean).pop();i&&i!=="picture"&&(r=i)}return{xml:e,tagName:O.tagName,...r?{detail:r}:{}}}function nr(O){return O.includes("http://schemas.openxmlformats.org/officeDocument/2006/relationships")}const Xr=new Set(["w:p","w:tbl","w:sdt","w:customXml","w:sectPr","w:bookmarkStart","w:bookmarkEnd","w:commentRangeStart","w:commentRangeEnd","w:moveFromRangeStart","w:moveFromRangeEnd","w:moveToRangeStart","w:moveToRangeEnd","w:permStart","w:permEnd","w:ins","w:del","w:moveFrom","w:moveTo","w:proofErr","w:tcPr","w:trPr","w:tblPr","w:tblGrid","w:tblPrEx","w:pPr"]),on=/^[A-Za-z_][\w.-]*(?::[\w.-]+)?$/;function Wr(O,e){let r;try{r=JSON.parse(O)}catch{return""}if(r===null||typeof r!="object"||Array.isArray(r))return"";let t="";for(const[i,n]of Object.entries(r)){if(typeof n!="string"||!on.test(i)||e?.has(i))continue;const o=n.replace(/&/g,"&").replace(/</g,"<").replace(/"/g,""");t+=` ${i}="${o}"`}return t}const sn=Object.freeze(Object.defineProperty({__proto__:null,KNOWN_BODY_TAGS:Xr,KNOWN_PPR_TAGS:Fr,KNOWN_RPR_TAGS:Rr,KNOWN_SECTPR_TAGS:_r,KNOWN_TBLPR_TAGS:Or,KNOWN_TCPR_TAGS:Lr,KNOWN_TRPR_TAGS:$r,attrsJsonToXmlAttributes:Wr,captureRawElement:ir,extractElementAttrsJson:tr,extractOpaqueChildrenXml:rt,stabilizeSerializedXml:rr,xmlReferencesRelationships:nr},Symbol.toStringTag,{value:"Module"})),an="http://schemas.openxmlformats.org/officeDocument/2006/math",zr=`<m:oMath xmlns:m="${an}">`,ln=new Set("∑∏∐∫∬∭∮∯∰∱∲∳⋀⋁⋂⋃⨀⨁⨂⨄⨆".split("")),cn=new Set(["sin","cos","tan","cot","sec","csc","arcsin","arccos","arctan","sinh","cosh","tanh","coth","log","ln","lg","exp","det","dim","ker","deg","gcd","hom","arg","max","min","sup","inf","lim","liminf","limsup","Pr"]),dn=new Set(["lim","liminf","limsup","max","min","sup","inf","Pr"]),Hr={"^":"̂","ˆ":"̂","̂":"̂","~":"̃","˜":"̃","̃":"̃","ˉ":"̄","¯":"̄","̄":"̄","˙":"̇","̇":"̇","¨":"̈","̈":"̈","ˊ":"́","´":"́","́":"́","ˋ":"̀","`":"̀","̀":"̀","ˇ":"̌","̌":"̌","˘":"̆","̆":"̆","→":"⃗","⃗":"⃗"},pn=new Set(["‾","¯","_","―","−"]),hn=new Set(["⏞","⏟","⏜","⏝","⎴","⎵"]),mn=new Set(["","","",""]),or={normal:'<m:sty m:val="p"/>',bold:'<m:sty m:val="b"/>',italic:'<m:sty m:val="i"/>',"bold-italic":'<m:sty m:val="bi"/>',"double-struck":'<m:scr m:val="double-struck"/><m:sty m:val="p"/>',script:'<m:scr m:val="script"/>',"bold-script":'<m:scr m:val="script"/><m:sty m:val="b"/>',fraktur:'<m:scr m:val="fraktur"/>',"bold-fraktur":'<m:scr m:val="fraktur"/><m:sty m:val="b"/>',"sans-serif":'<m:scr m:val="sans-serif"/><m:sty m:val="p"/>',monospace:'<m:scr m:val="monospace"/><m:sty m:val="p"/>'};function jr(O){return O.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function it(O){return jr(O)}function Le(O){return Array.from(O.children)}function Fe(O){return(O.textContent??"").replace(/[-]/g,"")}function xe(O){return O.localName.toLowerCase()}function sr(O){let e=O;for(;["mrow","mstyle","mpadded","semantics"].includes(xe(e))&&Le(e).filter(r=>!Rt(r)).length===1;)e=Le(e).filter(r=>!Rt(r))[0];return e}function Rt(O){return xe(O)==="mo"&&mn.has((O.textContent??"").trim())}function Ft(O){if(!O)return null;const e=sr(O);if(xe(e)!=="mo")return null;const r=Fe(e).trim();return ln.has(r)?r:null}function Ot(O){if(!O)return null;const e=sr(O);if(!["mi","mo"].includes(xe(e)))return null;const r=Fe(e).trim();return cn.has(r)?r:null}const gn=new Set("+-−=<>≤≥≠≈≡∼≃≅∝,;:∣∈∉⊂⊆⊃⊇→←↔⇒⇐⇔".split(""));function un(O){return xe(O)==="mo"&&gn.has(Fe(O).trim())}function Gr(O,e){let r=e;for(;r<O.length&&!un(O[r]);)r+=1;return r}function Jr(O){return!!O&&xe(O)==="mo"&&O.getAttribute("fence")==="true"}function He(O,e){if(!O)return"";const r=/^\s+$/.test(O)?`${O}`:O,t=/^\s|\s$/.test(r)?' xml:space="preserve"':"";return`<m:r>${e?`<m:rPr>${e}</m:rPr>`:""}<m:t${t}>${jr(r)}</m:t></m:r>`}function fn(O,e){const r=xe(O),t=Fe(O);if(!t)return"";if(r==="mtext"||r==="ms")return He(t,"<m:nor/>");const i=O.getAttribute("mathvariant")??e.mathvariant;return i&&or[i]?He(t,or[i]):r==="mi"&&[...t].length>1?He(t,'<m:sty m:val="p"/>'):He(t,"")}function ne(O,e){return`<m:${O}>${e}</m:${O}>`}function Ur(O,e,r,t,i){return`<m:nary><m:naryPr>${`<m:chr m:val="${it(O)}"/><m:limLoc m:val="${e}"/>`+(r===null?'<m:subHide m:val="1"/>':"")+(t===null?'<m:supHide m:val="1"/>':"")}</m:naryPr>`+ne("sub",r??"")+ne("sup",t??"")+ne("e",i)+"</m:nary>"}function Zr(O,e){return`<m:func>${ne("fName",O)}${ne("e",e)}</m:func>`}function Kr(O){return parseFloat(O.getAttribute("width")??"")>0?" ":""}function wn(O){return xe(O)==="mrow"&&O.children.length===0&&!Fe(O).trim()}function je(O,e){const r=O.filter(i=>!Rt(i)&&!wn(i));if(r.length>=2&&Jr(r[0])){const i=r[r.length-1],n=Jr(i),o=r.slice(1,n?-1:void 0),s=Fe(r[0]).trim(),a=n?Fe(i).trim():"";return`<m:d><m:dPr><m:begChr m:val="${it(s)}"/><m:endChr m:val="${it(a)}"/></m:dPr>`+ne("e",je(o,e))+"</m:d>"}let t="";for(let i=0;i<r.length;i+=1){const n=r[i],o=xe(n),s=r[i+1];if(["msub","msup","msubsup","munder","mover","munderover"].includes(o)&&Ft(Le(n)[0])){const[d,p,h]=Le(n),m=Ft(d),f=o.startsWith("mu")?"undOvr":"subSup",b=["msub","msubsup","munder","munderover"].includes(o)?he(p,e):null,u=o==="msubsup"||o==="munderover"?he(h,e):o==="msup"||o==="mover"?he(p,e):null,g=Gr(r,i+1);t+=Ur(m,f,b,u,je(r.slice(i+1,g),e)),i=g-1;continue}if(o==="mo"&&Ft(n)){const d=Gr(r,i+1);t+=Ur(Ft(n),"undOvr",null,null,je(r.slice(i+1,d),e)),i=d-1;continue}const a=["msub","munder"].includes(o)?Ot(Le(n)[0]):null;if(a&&dn.has(a)&&s){const[d,p]=Le(n),h=`<m:limLow>${ne("e",He(Ot(d),'<m:sty m:val="p"/>'))}${ne("lim",he(p,e))}</m:limLow>`;t+=Zr(h,he(s,e)),i+=1;continue}if(Ot(n)&&s){t+=Zr(He(Ot(n),'<m:sty m:val="p"/>'),he(s,e)),i+=1;continue}if(o==="mtext"||o==="mspace"){let d="",p=i;for(;r[p]&&["mtext","mspace"].includes(xe(r[p]));)d+=xe(r[p])==="mtext"?Fe(r[p]):Kr(r[p]),p+=1;i=p-1;const h=d.replace(/\s{2,}/g," ");h&&(t+=He(h,"<m:nor/>"));continue}const l=o==="mi"?n.getAttribute("mathvariant"):null;if(l){let d=Fe(n);for(;r[i+1]&&xe(r[i+1])==="mi"&&r[i+1].getAttribute("mathvariant")===l;)i+=1,d+=Fe(r[i]);t+=He(d,or[l]??"");continue}t+=he(n,e)}return t}function he(O,e){if(!O)return"";const r=xe(O),t=Le(O);switch(r){case"math":case"semantics":case"mrow":case"mpadded":case"merror":return je(t,e);case"mstyle":{const i=O.getAttribute("mathvariant");return je(t,i?{...e,mathvariant:i}:e)}case"annotation":case"annotation-xml":case"mphantom":case"none":case"mprescripts":return"";case"mi":case"mn":case"mo":case"mtext":case"ms":return Rt(O)?"":fn(O,e);case"mspace":{const i=Kr(O);return i?He(i,"<m:nor/>"):""}case"mfrac":{const i=O.getAttribute("linethickness");return`<m:f>${i!==null&&parseFloat(i)===0?'<m:fPr><m:type m:val="noBar"/></m:fPr>':""}`+ne("num",he(t[0],e))+ne("den",he(t[1],e))+"</m:f>"}case"msqrt":return'<m:rad><m:radPr><m:degHide m:val="1"/></m:radPr><m:deg/>'+ne("e",je(t,e))+"</m:rad>";case"mroot":return"<m:rad>"+ne("deg",he(t[1],e))+ne("e",he(t[0],e))+"</m:rad>";case"msub":return`<m:sSub>${ne("e",he(t[0],e))}${ne("sub",he(t[1],e))}</m:sSub>`;case"msup":return`<m:sSup>${ne("e",he(t[0],e))}${ne("sup",he(t[1],e))}</m:sSup>`;case"msubsup":return`<m:sSubSup>${ne("e",he(t[0],e))}`+ne("sub",he(t[1],e))+ne("sup",he(t[2],e))+"</m:sSubSup>";case"mover":case"munder":return bn(O,r==="mover"?"top":"bot",e);case"munderover":{const[i,n,o]=t,s=`<m:limLow>${ne("e",he(i,e))}${ne("lim",he(n,e))}</m:limLow>`;return`<m:limUpp>${ne("e",s)}${ne("lim",he(o,e))}</m:limUpp>`}case"mtable":return"<m:m>"+t.filter(i=>["mtr","mlabeledtr"].includes(xe(i))).map(i=>"<m:mr>"+Le(i).filter(n=>xe(n)==="mtd").map(n=>ne("e",je(Le(n),e))).join("")+"</m:mr>").join("")+"</m:m>";case"menclose":{const i=je(t,e),n=O.getAttribute("notation")??"";return/\bbox\b|roundedbox/.test(n)?`<m:borderBox>${ne("e",i)}</m:borderBox>`:i}case"mfenced":{const i=O.getAttribute("open")??"(",n=O.getAttribute("close")??")";return`<m:d><m:dPr><m:begChr m:val="${it(i)}"/><m:endChr m:val="${it(n)}"/></m:dPr>`+t.map(o=>ne("e",he(o,e))).join("")+"</m:d>"}default:return je(t,e)}}function bn(O,e,r){const[t,i]=Le(O),n=he(t,r),o=i?sr(i):void 0,s=o&&xe(o)==="mo"?Fe(o).trim():"";if(s&&pn.has(s))return`<m:bar><m:barPr><m:pos m:val="${e}"/></m:barPr>${ne("e",n)}</m:bar>`;if(s&&hn.has(s))return`<m:groupChr><m:groupChrPr><m:chr m:val="${it(s)}"/><m:pos m:val="${e}"/><m:vertJc m:val="${e==="top"?"bot":"top"}"/></m:groupChrPr>`+ne("e",n)+"</m:groupChr>";const a=O.getAttribute(e==="top"?"accent":"accentunder")==="true";if(e==="top"&&s&&(a||Hr[s])){const d=Hr[s]??s;return`<m:acc><m:accPr><m:chr m:val="${it(d)}"/></m:accPr>${ne("e",n)}</m:acc>`}const l=e==="top"?"limUpp":"limLow";return`<m:${l}>${ne("e",n)}${ne("lim",he(i,r))}</m:${l}>`}function yn(O){return new DOMParser().parseFromString(O,"text/html").querySelector("math")}function xn(O){const e=yn(O);if(!e)throw new Error("mathmlToOmml: no <math> element in input");return`${zr}${he(e,{})}</m:oMath>`}const qr="iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==",fe=class ar{static async parseFile(e,r){if(!e.name.toLowerCase().endsWith(".docx"))throw new Error(`DocxConverter only supports .docx files, got: ${e.name}`);return this.parseDocxFile(e,r)}static async parseDocxFile(e,r){const t=await e.arrayBuffer(),i=await Cr.loadAsync(t),n=await i.file("word/document.xml")?.async("string");if(!n)return{type:"doc",children:[this.createEmptyParagraph()]};const o=this.parseDocumentXml(n);if(!o)return{type:"doc",children:[this.createEmptyParagraph()]};const s=await this.loadOOXMLPackageContext(i,n),a=await this.parseDocumentPageLayoutFromPackage(n,i,o),l=await i.file("word/fontTable.xml")?.async("string"),d=this.parseFontTableXml(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(n,a,s,o,m),b=await i.file("docProps/custom.xml")?.async("string");if(b){const F=this.parseDocumentXml(b),B=(F&&Array.from(F.getElementsByTagNameNS("*","property")).find(z=>z.getAttribute("name")==="Revise.BlockSpacingPx"))?.textContent?.trim(),P=B?Number(B):NaN;Number.isFinite(P)&&P>=0&&P<=192&&(f.pageLayout={...f.pageLayout??{},blockSpacingPx:P})}h&&(f.pageLayout={...f.pageLayout??{},hyphenationEnabled:!0}),d&&(f.fontSubstitutes=d,ui(d));const u=await i.file("word/footnotes.xml")?.async("string"),g=await i.file("word/endnotes.xml")?.async("string"),w=new Map;u&&await this.collectNotesFromXml(f,u,"w:footnote","docxfn","footnote",w,s),g&&await this.collectNotesFromXml(f,g,"w:endnote","docxen","endnote",w,s),this.finalizeImportedFootnoteRefs(f,w);const S=await i.file("word/comments.xml")?.async("string");if(S){const F=await i.file("word/commentsExtended.xml")?.async("string");this.attachCommentsFromXml(f,S,F,s)}await this.attachHeadersFootersFromPackage(f,n,i,s,o);const T=await i.file("docProps/core.xml")?.async("string");if(T){const F=this.parseCoreProperties(T);F&&(f.coreProperties=F)}return m&&fi(f,m,await wi(new Uint8Array(t))),f}static parseCoreProperties(e){const r=this.parseDocumentXml(e);if(!r)return;const t=new Set(this.CORE_PROPERTY_LOCAL_NAMES),i={},n=r.documentElement;for(let o=0;o<n.children.length;o++){const s=n.children[o],a=s.tagName.split(":").pop()??s.tagName;if(!t.has(a))continue;const l=s.textContent??"";l.trim().length!==0&&(i[a]=l)}return Object.keys(i).length>0?i:void 0}static readHeaderFooterReferences(e,r){const t={};for(let i=0;i<e.children.length;i++){const n=e.children[i];if(n.tagName!==r)continue;const o=n.getAttribute("w:type")??"default",s=o==="first"||o==="even"?o:"default",a=n.getAttribute("r:id")??n.getAttribute("relationships:id");a&&(t[s]=a)}return t}static resolveSectionHeaderFooterReferences(e){const r=[];for(let t=0;t<e.length;t++){const i=r[t-1]??{header:{},footer:{}};r.push({header:{...i.header,...this.readHeaderFooterReferences(e[t],"w:headerReference")},footer:{...i.footer,...this.readHeaderFooterReferences(e[t],"w:footerReference")}})}return r}static async attachHeadersFootersFromPackage(e,r,t,i,n){const o=(n??this.parseDocumentXml(r))?.getElementsByTagName("w:body")[0];if(!o)return;const s=this.findAllSectionProperties(o);if(s.length===0)return;const a=this.resolveSectionHeaderFooterReferences(s),l=s.length-1,d=a[l],p=new Map,h=async B=>{const P=p.get(B);if(P)return P;const z={paragraphs:[],images:[]},E=i?.relationships.get(B);if(E){const G=E.target.startsWith("word/")?E.target:`word/${E.target.replace(/^\//,"")}`,$=await t.file(G)?.async("string");if($){const v=G.split("/").pop()??G,D=await t.file(`word/_rels/${v}.rels`)?.async("string");if(z.paragraphs=await this.parseHeaderFooterPart($,D?this.parseRelationshipsXml(D,G):void 0),!e.watermark){const M=this.parseVmlWatermark($);M&&(e.watermark=M)}z.images=await this.parseHeaderFooterImages($,G,t,i)}}return p.set(B,z),z},m=async B=>(await h(B)).paragraphs,f=["default","first","even"],b=[],u=async(B,P)=>{const z={};for(const E of f){const G=B[E];if(!G)continue;const $=await h(G);$.paragraphs.length>0&&(z[E]=$.paragraphs);for(const v of $.images)b.push({side:P,slot:E,...v})}return Object.keys(z).length>0?z:void 0},g=await u(d.header,"header"),w=await u(d.footer,"footer");g&&(e.headers=g),w&&(e.footers=w),b.length>0&&(e.chromeImages=b);const S=[];for(let B=0;B<l;B++)for(const P of["header","footer"])for(const z of f){const E=a[B][P][z],G=d[P][z];if(E===G)continue;const $=E?await m(E):[];S.push(kr(P,z,$.length>0?bi($):void 0,void 0,B))}const T=[],F=new Set(S.map(B=>`${B.side}/${B.slot}/${B.sectionIndex}`));for(let B=0;B<s.length;B++)if(s[B].getElementsByTagName("w:titlePg").length!==0)for(const P of["header","footer"]){const z=a[B][P].first;if((z?await m(z):[]).length>0||!a[B][P].default)continue;const E=B===l?void 0:B;F.has(`${P}/first/${E}`)||T.push(kr(P,"first",void 0,void 0,E))}(S.length>0||T.length>0)&&(e.chrome=[...yi(e.headers,e.footers),...S,...T])}static parseVmlWatermark(e){if(!e.includes("v:textpath"))return;const r=this.parseDocumentXml(e);if(!r)return;const t=r.getElementsByTagName("v:textpath");for(let i=0;i<t.length;i++){const n=t[i],o=(n.getAttribute("string")??"").trim();if(!o)continue;let s=n.parentNode;for(;s&&s.tagName!=="v:shape";)s=s.parentNode;const a=(s?.getAttribute("style")??"").match(/rotation:\s*(-?\d+(?:\.\d+)?)/),l=a?(parseFloat(a[1])%360+360)%360:0,d=this.vmlFillColorToHex(s?.getAttribute("fillcolor")??"");let p;const h=s?.getElementsByTagName("v:fill")[0]?.getAttribute("opacity");if(h){const b=h.endsWith("f")?parseFloat(h)/65536:parseFloat(h);Number.isFinite(b)&&b>0&&b<=1&&(p=Math.abs(b-Tr)<.05?void 0:b)}const m=(n.getAttribute("style")??"").match(/font-size:\s*(\d+(?:\.\d+)?)pt/),f=m?parseFloat(m[1]):void 0;return xi({text:o,...d?{color:d}:{},...p!==void 0?{opacity:p}:{},diagonal:l!==0,...f&&f>2?{fontSizePx:Math.round(f*(4/3))}:{}})}}static vmlFillColorToHex(e){const r=e.trim().toLowerCase();if(r){if(r.startsWith("#")){const t=r.slice(1,7);return/^[0-9a-f]{6}$/.test(t)?`#${t.toUpperCase()}`:void 0}return{silver:"#C0C0C0",gray:"#808080",grey:"#808080",black:"#000000",red:"#FF0000",blue:"#0000FF",green:"#008000",white:"#FFFFFF"}[r]}}static async parseHeaderFooterImages(e,r,t,i){if(!i||!e.includes("w:drawing"))return[];const n=this.parseDocumentXml(e);if(!n)return[];const o=n.getElementsByTagName("w:drawing");if(o.length===0)return[];const s=r.split("/").pop()??r,a=await t.file(`word/_rels/${s}.rels`)?.async("string"),l={...i,relationships:this.parseRelationshipsXml(a,r)},d=[];for(let p=0;p<o.length;p++){const h=await this.parseImageFromDrawing(o[p],void 0,l);h&&d.push({src:h.src,width:h.width,height:h.height,...h.alt?{alt:h.alt}:{}})}return d}static async parseHeaderFooterPart(e,r){const t=this.parseDocumentXml(e);if(!t)return[];const i=[],n=Array.from(t.getElementsByTagName("w:p")).filter(o=>{let s=o.parentElement;for(;s;){if(s.tagName==="w:txbxContent")return!1;s=s.parentElement}return!0});for(let o=0;o<n.length;o++){const s=n[o],a=[];let l=null,d=!1;const p=g=>{const w={},S=this.getDirectChild(g,"w:rPr");S&&(this.applyRunPropertiesFromElement(w,S),(this.getDirectChild(S,"w:rStyle")?.getAttribute("w:val")||void 0)===this.CODE_INLINE_STYLE_ID&&(w.code=!0,/courier/i.test(w.fontFamily??"")&&delete w.fontFamily,/^(light)?gray$/i.test(w.backgroundColor??"")&&delete w.backgroundColor));let T=g.parentElement;for(;T&&T!==s;){if(T.tagName==="w:hyperlink"){const F=T.getAttribute("r:id"),B=T.getAttribute("w:anchor"),P=F?r?.get(F)?.target:void 0;P?w.link=P:B&&(w.link=`#${B}`);break}T=T.parentElement}return w},h=Array.from(s.getElementsByTagName("w:r")).filter(g=>{let w=g.parentElement;for(;w&&w!==s;){if(w.tagName==="w:p")return!1;w=w.parentElement}return w===s});for(let g=0;g<h.length;g++){const w=h[g],S=p(w);for(let T=0;T<w.children.length;T++){const F=w.children[T];if(F.tagName==="w:t"){if(d)continue;const B=F.textContent??"";B&&a.push({type:"text",text:B,...Object.keys(S).length>0?{marks:S}:{}})}else if(F.tagName==="w:tab")a.push({type:"text",text:" "});else if(F.tagName==="w:fldChar"){const B=F.getAttribute("w:fldCharType");B==="begin"&&(d=!0),B==="end"&&(l&&a.push({type:"text",text:"1",marks:{...S,field:l}}),l=null,d=!1)}else if(F.tagName==="w:instrText"&&d){const B=(F.textContent??"").trim().toUpperCase();B.startsWith("PAGE")?l="page":B.startsWith("NUMPAGES")&&(l="numPages")}}}const m=s.getElementsByTagName("w:fldSimple");for(let g=0;g<m.length;g++){const w=(m[g].getAttribute("w:instr")??"").trim().toUpperCase();w.startsWith("PAGE")?a.push({type:"text",text:"1",marks:{field:"page"}}):w.startsWith("NUMPAGES")&&a.push({type:"text",text:"1",marks:{field:"numPages"}})}const f=this.getDirectChild(this.getDirectChild(s,"w:pPr")??s,"w:jc")?.getAttribute("w:val"),b=f==="center"?"center":f==="right"||f==="end"?"right":f==="both"?"justify":void 0;a.length>0&&i.push({type:"paragraph",id:this.generateId(),children:a,...b?{align:b}:{}});const u=await this.parseTextBoxContent(s,void 0);i.push(...u.filter(g=>g.type==="paragraph"))}return i}static attachCommentsFromXml(e,r,t,i){const n=this.parseDocumentXml(r);if(!n)return;const o=new Set,s=u=>{if(!u||typeof u!="object")return;if(Array.isArray(u)){u.forEach(s);return}const g=u;g.marks?.comment&&g.marks.comment.split(",").forEach(w=>o.add(w)),s(g.children)};s(e.children);const a=(i??this.fallbackCommentState).collapsedCommentAnchorBlockById;a?.forEach((u,g)=>o.add(`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 w=u[g],S=w.getAttribute("w15:paraId");S&&l.set(S,{done:w.getAttribute("w15:done")==="1",parentParaId:w.getAttribute("w15:paraIdParent")??void 0})}}const d=[],p=new Map,h=new Map,m=n.getElementsByTagName("w:comment");for(let u=0;u<m.length;u++){const g=m[u],w=g.getAttribute("w:id");if(!w)continue;const S=`docxcmt-${w}`,T=g.getElementsByTagName("w:p"),F=[];for(let E=0;E<T.length;E++){const G=T[E].getElementsByTagName("w:t");let $="";for(let D=0;D<G.length;D++)$+=G[D].textContent??"";F.push($);const v=T[E].getAttribute("w14:paraId");v&&(p.set(S,v),h.set(v,S))}const B=g.getAttribute("w:date"),P=B?Date.parse(B):NaN,z=a?.get(w);d.push({id:S,author:g.getAttribute("w:author")??"Unknown",...g.getAttribute("w:initials")?{initials:g.getAttribute("w:initials")}:{},createdAt:Number.isFinite(P)?new Date(P).toISOString():new Date(0).toISOString(),bodyMd:F.filter(E=>E.length>0).join(`
|
|
3
|
+
|
|
4
|
+
`),importedId:parseInt(w,10),...z?{anchorBlockId:z}:{}})}for(const u of d){const g=p.get(u.id),w=g?l.get(g):void 0;if(w?.done&&(u.resolved=!0),w?.parentParaId){const S=h.get(w.parentParaId);S&&(u.parentId=S)}}const f=u=>{let g=u;const w=new Map(d.map(S=>[S.id,S]));for(;g.parentId&&w.has(g.parentId);)g=w.get(g.parentId);return g.id},b=d.filter(u=>o.has(f(u)));b.length>0&&(e.comments=b)}static async collectNotesFromXml(e,r,t,i,n,o,s){const a=this.parseDocumentXml(r);if(!a)return;if(s){const p=t==="w:footnote"?"footnotes":"endnotes",h=await s.zip.file(`word/_rels/${p}.xml.rels`)?.async("string");if(h){const m=this.parseRelationshipsXml(h,`word/${p}.xml`);m.size>0&&(s={...s,relationships:new Map([...s.relationships,...m])})}}const l=Te(e.pageLayout).indentStepPx,d=a.getElementsByTagName(t);for(let p=0;p<d.length;p++){const h=d[p],m=h.getAttribute("w:type");if(m==="separator"||m==="continuationSeparator")continue;const f=h.getAttribute("w:id");if(!f)continue;const b=await this.parseBodyChildren(h,l,s),u=b.length>0?b:[this.createEmptyParagraph()];vi(u),o.set(`${i}-${f}`,{type:"footnote",id:`${i}-${f}`,...n==="endnote"?{noteKind:"endnote"}:{},children:u})}}static finalizeImportedFootnoteRefs(e,r){const t=[],i={footnote:0,endnote:0},n=new Map,o=(s,a)=>{if(!s||typeof s!="object")return;if(Array.isArray(s)){s.forEach(p=>o(p));return}const l=s,d=l.marks?.footnoteRef;if(d&&(d.startsWith("docxfn-")||d.startsWith("docxen-")))if(!r.has(d))l.text="",delete l.marks.footnoteRef,delete l.marks.superscript;else{if(!t.includes(d)){t.push(d);const p=d.startsWith("docxen-")?"endnote":"footnote";i[p]+=1,n.set(d,Vi(i[p],p))}l.text=n.get(d)??""}o(l.children)};o(e.children);for(const s of t){const a=r.get(s);a&&e.children.push(a)}}static documentHasMath(e){return e.includes("m:oMath")||e.includes("m:oMathPara")}static documentHasNativePageBreaks(e){return e.includes('w:br w:type="page"')||e.includes("<w:lastRenderedPageBreak")||e.includes("<w:pageBreakBefore")}static documentHasComplexBodyContent(e){return e.includes("<w:tbl")||e.includes("<w:drawing")||e.includes("<w:pict")||e.includes("<w:object")}static shouldUseStructuredDocxParser(e){return!!(this.documentHasMath(e)||this.documentHasNativePageBreaks(e)&&!this.documentHasComplexBodyContent(e))}static resolveIndentStepPx(e){return Te(e?.pageLayout).indentStepPx}static stripXmlBom(e){return e.charCodeAt(0)===65279?e.slice(1):e}static parseDocumentXml(e){const r=new DOMParser().parseFromString(this.stripXmlBom(e),"application/xml");return r.querySelector("parsererror")?null:r}static async loadOOXMLPackageContext(e,r){const[t,i,n,o]=await Promise.all([e.file("word/_rels/document.xml.rels")?.async("string"),e.file("word/styles.xml")?.async("string"),e.file("word/numbering.xml")?.async("string"),e.file("[Content_Types].xml")?.async("string")]),s=this.parseRelationshipsXml(t,"word/document.xml");return{zip:e,documentXml:r,relationships:s,styles:this.parseStylesXml(i),stylesXmlRaw:i||void 0,numbering:this.parseNumberingXml(n),contentTypes:this.parseContentTypesXml(o),themeFonts:await this.parseThemeFonts(e,s)}}static async parseThemeFonts(e,r){let t="word/theme/theme1.xml";for(const l of r.values())if(l.type.endsWith("/theme")&&l.targetMode!=="External"){t=l.target;break}const i=await e.file(t)?.async("string");if(!i)return;const n=this.parseDocumentXml(i);if(!n)return;const o=l=>n.getElementsByTagName(l)[0]?.getElementsByTagName("a:latin")[0]?.getAttribute("typeface")?.trim()||void 0,s=o("a:majorFont"),a=o("a:minorFont");if(!(!s&&!a))return{...s?{major:s}:{},...a?{minor:a}:{}}}static parseRelationshipsXml(e,r){const t=new Map;if(!e)return t;const i=this.parseDocumentXml(e);if(!i)return t;const n=i.getElementsByTagName("Relationship");for(let o=0;o<n.length;o++){const s=n[o],a=s.getAttribute("Id"),l=s.getAttribute("Target"),d=s.getAttribute("Type");if(!a||!l||!d)continue;const p=s.getAttribute("TargetMode")||void 0;t.set(a,{id:a,type:d,target:p?.toLowerCase()==="external"?l:this.resolvePackageTargetPath(r,l),targetMode:p})}return t}static resolvePackageTargetPath(e,r){if(r.startsWith("/"))return r.replace(/^\/+/,"");const t=e.split("/");t.pop();const i=r.split("/");for(const n of i)if(!(!n||n===".")){if(n===".."){t.pop();continue}t.push(n)}return t.join("/")}static parseStylesXml(e){const r={stylesById:new Map,defaultStyleIdByType:new Map};if(!e)return r;const t=this.parseDocumentXml(e);if(!t)return r;const i=t.getElementsByTagName("w:docDefaults")[0];if(i){const o=i.getElementsByTagName("w:pPrDefault")[0],s=i.getElementsByTagName("w:rPrDefault")[0];r.paragraphDefault=o?this.getDirectChild(o,"w:pPr"):void 0,r.runDefault=s?this.getDirectChild(s,"w:rPr"):void 0}const n=t.getElementsByTagName("w:style");for(let o=0;o<n.length;o++){const s=n[o],a=s.getAttribute("w:styleId");if(!a)continue;const l=this.getDirectChild(s,"w:name"),d=this.getDirectChild(s,"w:basedOn"),p=s.getAttribute("w:type")||"";r.stylesById.set(a,{id:a,type:p,basedOn:d?.getAttribute("w:val")||void 0,name:l?.getAttribute("w:val")||void 0,pPr:this.getDirectChild(s,"w:pPr"),rPr:this.getDirectChild(s,"w:rPr"),tblPr:this.getDirectChild(s,"w:tblPr")}),p&&this.isOnAttribute(s.getAttribute("w:default"))&&(r.defaultStyleIdByType.has(p)||r.defaultStyleIdByType.set(p,a))}return r}static parseFontTableXml(e){if(!e)return;const r=this.parseDocumentXml(e);if(!r)return;const t={},i=r.getElementsByTagName("w:font");for(let n=0;n<i.length;n++){const o=i[n],s=(o.getAttribute("w:name")||"").trim();if(!s)continue;const a=(this.getDirectChild(o,"w:altName")?.getAttribute("w:val")||"").trim(),l=(this.getDirectChild(o,"w:family")?.getAttribute("w:val")||"").trim().toLowerCase(),d=(this.getDirectChild(o,"w:pitch")?.getAttribute("w:val")||"").trim().toLowerCase(),p=(this.getDirectChild(o,"w:panose1")?.getAttribute("w:val")||"").trim(),h={};a&&(h.alt=a);const m=this.genericFamilyFromFontMetrics(l,d,p);m&&(h.generic=m),(h.alt||h.generic)&&(t[s.toLowerCase()]=h)}return Object.keys(t).length>0?t:void 0}static genericFamilyFromFontMetrics(e,r,t){if(r==="fixed"||e==="modern")return"monospace";if(/^[0-9a-fA-F]{20}$/.test(t)){const i=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16);if(i===2){if(n>=2&&n<=10)return"serif";if(n>=11&&n<=15)return"sans-serif"}}if(e==="roman")return"serif";if(e==="swiss")return"sans-serif"}static parseNumberingXml(e){const r={abstractNums:new Map,nums:new Map};if(!e)return r;const t=this.parseDocumentXml(e);if(!t)return r;const i=t.getElementsByTagName("w:abstractNum");for(let o=0;o<i.length;o++){const s=i[o],a=s.getAttribute("w:abstractNumId");if(!a)continue;const l=new Map,d=s.getElementsByTagName("w:lvl");for(let p=0;p<d.length;p++){const h=d[p],m=h.getAttribute("w:ilvl"),f=m?parseInt(m,10):NaN;if(!Number.isFinite(f))continue;const b=this.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:b?.getAttribute("w:val")||void 0,text:u?.getAttribute("w:val")||void 0,start:g&&Number.isFinite(parseInt(g,10))?parseInt(g,10):void 0})}r.abstractNums.set(a,{abstractNumId:a,levels:l})}const n=t.getElementsByTagName("w:num");for(let o=0;o<n.length;o++){const s=n[o],a=s.getAttribute("w:numId");if(!a)continue;const l=this.getDirectChild(s,"w:abstractNumId"),d=new Map,p=s.getElementsByTagName("w:lvlOverride");for(let h=0;h<p.length;h++){const m=p[h],f=m.getAttribute("w:ilvl"),b=f?parseInt(f,10):NaN;if(!Number.isFinite(b))continue;const u=m.getElementsByTagName("w:startOverride")[0]?.getAttribute("w:val");u&&Number.isFinite(parseInt(u,10))&&d.set(b,parseInt(u,10))}r.nums.set(a,{numId:a,abstractNumId:l?.getAttribute("w:val")||void 0,levelStartOverrides:d})}return r}static parseContentTypesXml(e){const r=new Map;if(!e)return r;const t=this.parseDocumentXml(e);if(!t)return r;const i=t.getElementsByTagName("Default");for(let o=0;o<i.length;o++){const s=i[o],a=(s.getAttribute("Extension")||"").toLowerCase(),l=s.getAttribute("ContentType");a&&l&&r.set(a,l)}const n=t.getElementsByTagName("Override");for(let o=0;o<n.length;o++){const s=n[o],a=s.getAttribute("PartName"),l=s.getAttribute("ContentType");a&&l&&r.set(a.replace(/^\/+/,""),l)}return r}static getDirectChild(e,r){for(let t=0;t<e.children.length;t++){const i=e.children[t];if(i.tagName===r)return i}}static parseTwipsAttribute(e,r){if(!e)return;const t=e.getAttribute(r);if(!t)return;const i=Number.parseInt(t,10);return Number.isFinite(i)?i:void 0}static parseOnOffElement(e){if(!e)return;const r=(e.getAttribute("w:val")||e.getAttribute("val")||"").trim().toLowerCase();return r?!(r==="0"||r==="false"||r==="off"):!0}static pxToTwips(e){return Number.isFinite(e)?Math.round(e*this.TWIPS_PER_PX):0}static pxToDocxHalfPoints(e){return Number.isFinite(e)?Math.max(2,Math.round(e*this.DOCX_HALF_POINTS_PER_PX)):2}static twipsToPx(e){return Number.isFinite(e)?e/this.TWIPS_PER_PX:0}static inferPageSizePresetFromTwips(e,r){const t=e/this.TWIPS_PER_INCH,i=r/this.TWIPS_PER_INCH,n=Math.min(t,i),o=Math.max(t,i);let s="letter",a=Number.POSITIVE_INFINITY;for(const l of this.PAGE_SIZE_PRESETS){const d=Math.abs(n-l.width)+Math.abs(o-l.height);d<a&&(a=d,s=l.preset)}return s}static findAllSectionProperties(e){const r=[],t=i=>{for(const n of Array.from(i.children)){if(n.tagName==="w:sdt"){const o=this.getDirectChild(n,"w:sdtContent");o&&t(o);continue}if(n.tagName==="w:p"){const o=this.getDirectChild(n,"w:pPr"),s=o?this.getDirectChild(o,"w:sectPr"):void 0;s&&r.push(s)}n.tagName==="w:sectPr"&&r.push(n)}};return t(e),r}static findBodySectionProperties(e){const r=this.findAllSectionProperties(e);return r[r.length-1]}static parseSectionPropertiesElement(e){const r={},t=this.getDirectChild(e,"w:pgSz");if(t){const 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&&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(e,"w:pgMar");if(i){const h=this.parseTwipsAttribute(i,"w:top"),m=this.parseTwipsAttribute(i,"w:right"),f=this.parseTwipsAttribute(i,"w:bottom"),b=this.parseTwipsAttribute(i,"w:left");h!==void 0&&(r.marginTopPx=this.twipsToPx(h)),m!==void 0&&(r.marginRightPx=this.twipsToPx(m)),f!==void 0&&(r.marginBottomPx=this.twipsToPx(f)),b!==void 0&&(r.marginLeftPx=this.twipsToPx(b))}const n=this.getDirectChild(e,"w:pgNumType"),o=(n?.getAttribute("w:start")||"").trim();if(o!==""){const h=parseInt(o,10);Number.isFinite(h)&&h>0&&(r.pageNumberStart=h)}const s=(n?.getAttribute("w:fmt")||"").trim();Si(s)&&(r.pageNumberFormat=s);const a=this.getDirectChild(e,"w:lnNumType");if(a){const h=(a.getAttribute("w:countBy")||"").trim(),m=(a.getAttribute("w:start")||"").trim(),f=(a.getAttribute("w:restart")||"").trim(),b=(a.getAttribute("w:distance")||"").trim(),u=h?parseInt(h,10):NaN,g=m?parseInt(m,10):NaN,w=b?parseInt(b,10):NaN;r.lineNumbering=Ii({countBy:Number.isFinite(u)&&u>=1?u:1,start:Number.isFinite(g)&&g>=1?g:1,restart:f==="newSection"||f==="continuous"?f:"newPage",...Number.isFinite(w)&&w>=0?{distancePx:w/15}:{}})}const l=this.getDirectChild(e,"w:cols");if(l){const h=(l.getAttribute("w:num")||"").trim(),m=h?parseInt(h,10):NaN;if(Number.isFinite(m)&&m>1){r.columnCount=m;const f=(l.getAttribute("w:space")||"").trim(),b=f?parseInt(f,10):NaN;Number.isFinite(b)&&b>=0&&(r.columnGapTwips=b)}}const d=Pi(this.getDirectChild(e,"w:pgBorders"));d&&(r.pageBorders=d);const p=rt(e,_r);return p&&(r.oxmlSectPr=p),Object.keys(r).length>0?r:void 0}static parseSectionStartType(e){const r=(this.getDirectChild(e,"w:type")?.getAttribute("w:val")||"").trim();if(r==="continuous")return"continuous";if(r==="evenPage")return"evenPage";if(r==="oddPage")return"oddPage";if(r==="nextPage")return"nextPage"}static parseDocumentPageLayout(e,r){const t=r??this.parseDocumentXml(e);if(!t)return;const i=t.getElementsByTagName("w:body")[0];if(!i)return;const n=this.findBodySectionProperties(i);if(!n)return;const o=this.parseSectionPropertiesElement(n);return o?.pageNumberStart!==void 0&&(o.pageNumberRestart=!0),o}static async parseDocumentPageLayoutFromPackage(e,r,t){const i=t??this.parseDocumentXml(e);if(!i)return;const n=this.parseDocumentPageLayout(e,i)??{},o=i.getElementsByTagName("w:body")[0];if(!o)return Object.keys(n).length>0?n:void 0;const s=this.findAllSectionProperties(o);if(s.length===0)return Object.keys(n).length>0?n:void 0;const a=this.resolveSectionHeaderFooterReferences(s)[s.length-1],l=await r.file("word/_rels/document.xml.rels")?.async("string");if(!l)return Object.keys(n).length>0?n:void 0;const d=this.parseDocumentXml(l);if(!d)return Object.keys(n).length>0?n:void 0;const p=new Map,h=d.getElementsByTagName("Relationship");for(let f=0;f<h.length;f++){const b=h[f],u=b.getAttribute("Id"),g=b.getAttribute("Target");u&&g&&p.set(u,g)}const m=async(f,b)=>{const u=a[f].default,g=u?p.get(u):void 0;if(!g)return;const w=g.startsWith("/")?g.slice(1):g.startsWith("word/")?g:`word/${g.replace(/^\.?\//,"")}`,S=await r.file(w)?.async("string");if(!S)return;const T=this.parsePageNumberInfoFromReferenceXml(S);T&&(n.showPageNumbers=!0,n.pageNumberPosition=`${b}-${T.horizontal}`)};return await m("header","top"),n.showPageNumbers||await m("footer","bottom"),Object.keys(n).length>0?n:void 0}static parsePageNumberInfoFromReferenceXml(e){const r=this.parseDocumentXml(e);if(!r)return;const t=r.getElementsByTagName("w:p");for(let i=0;i<t.length;i++){const n=t[i],o=n.getElementsByTagName("w:instrText");let s=!1;for(let l=0;l<o.length;l++)if((o[l].textContent||"").toUpperCase().includes("PAGE")){s=!0;break}if(!s){const l=n.getElementsByTagName("w:fldSimple");for(let d=0;d<l.length;d++)if((l[d].getAttribute("w:instr")||"").toUpperCase().includes("PAGE")){s=!0;break}}if(!s)continue;const a=this.getDirectChild(n,"w:pPr");return{horizontal:((a?this.getDirectChild(a,"w:jc"):void 0)?.getAttribute("w:val")||"").toLowerCase()==="left"?"left":"right"}}}static parseWordParagraphProperties(e,r){const t=this.getDirectChild(e,"w:pPr");if(!t)return{isList:!1};const i={isList:!!this.getDirectChild(t,"w:numPr")},n=this.parseOnOffElement(this.getDirectChild(t,"w:pageBreakBefore"));n!==void 0&&(i.pageBreakBefore=n),this.getDirectChild(t,"w:keepNext")&&(i.keepNext=this.isOn(t,"w:keepNext")),this.getDirectChild(t,"w:keepLines")&&(i.keepLines=this.isOn(t,"w:keepLines")),this.getDirectChild(t,"w:widowControl")&&(i.widowControl=this.isOn(t,"w:widowControl")),this.getDirectChild(t,"w:bidi")&&(i.direction=this.isOn(t,"w:bidi")?"rtl":"ltr"),this.parseParagraphDecoration(t,i),this.applyTabStopsFromPPr(i,t),this.applyJcFromPPr(i,t);const o=this.getDirectChild(t,"w:ind");if(o){const s=this.parseTwipsAttribute(o,"w:start")??this.parseTwipsAttribute(o,"w:left");if(s===0)i.leftIndent=0;else if(s!==void 0&&s>0){const d=Bt(this.twipsToPx(s),{indentStepPx:r,storedAsUnits:!1});d!==void 0&&(i.leftIndent=d)}const a=this.parseTwipsAttribute(o,"w:firstLine"),l=this.parseTwipsAttribute(o,"w:hanging");if(l!==void 0&&l>0)i.firstLineIndent=-1;else if(a===0)i.firstLineIndent=0;else if(a!==void 0&&a>0){const d=Bt(this.twipsToPx(a),{indentStepPx:r,storedAsUnits:!1,firstLine:!0});d!==void 0&&(i.firstLineIndent=d)}}return this.resolveLogicalAlignment(i),i}static applyJcFromPPr(e,r){const t=(this.getDirectChild(r,"w:jc")?.getAttribute("w:val")||"").toLowerCase();t==="center"?(e.align=t,delete e.jcLogical,delete e.jcPhysical):t==="left"||t==="right"?(e.jcPhysical=t,delete e.align,delete e.jcLogical):t==="both"||t==="justify"?(e.align="justify",delete e.jcLogical,delete e.jcPhysical):(t==="start"||t==="end")&&(e.jcLogical=t,delete e.align,delete e.jcPhysical)}static resolveLogicalAlignment(e){const r=e.direction==="rtl",t=e.jcPhysical;if(t){if(delete e.jcPhysical,delete e.jcLogical,!r){e.align=t;return}const o=t==="left"?"right":"left";o==="right"?delete e.align:e.align=o;return}const i=e.jcLogical;if(!i)return;delete e.jcLogical;const n=i==="start"?r?"right":"left":r?"left":"right";n===(r?"right":"left")?delete e.align:e.align=n}static extractTopLevelParagraphProperties(e,r){const t=this.parseDocumentXml(e);if(!t)return[];const i=t.getElementsByTagName("w:body")[0];if(!i)return[];const n=[];for(let o=0;o<i.children.length;o++){const s=i.children[o];s.tagName==="w:p"&&n.push(this.parseWordParagraphProperties(s,r))}return n}static applyTopLevelParagraphProperties(e,r){const t=r.filter(n=>!n.isList);let i=0;for(const n of e.children){if(n.type!=="paragraph")continue;const o=t[i];if(!o)break;i+=1,o.align&&(n.align=o.align),o.leftIndent!==void 0&&(n.leftIndent=o.leftIndent),o.firstLineIndent!==void 0&&(n.firstLineIndent=o.firstLineIndent);const s=this.directionAttrFor(o.direction,this.paragraphNodeText(n));s&&(n.direction=s)}}static paragraphNodeText(e){let r="";for(const t of e.children)t.type==="text"&&(r+=t.text);return r}static directionAttrFor(e,r){if(e==="rtl")return"rtl";if(e==="ltr"&&Dt(r)==="rtl")return"ltr"}static async parseStructuredDocxDocument(e,r,t,i,n){t||(this.fallbackCommentState={});const o=i??this.parseDocumentXml(e);if(!o)return{type:"doc",children:[this.createEmptyParagraph()]};const s=o.getElementsByTagName("w:body")[0];if(!s)return{type:"doc",children:[this.createEmptyParagraph()]};const a=Te(r).indentStepPx,l=[];this.importSdtWrappers=l;const d=[];this.importOxmlRanges=d,this.sdtAncestorStack=[];const p=t??this.fallbackCommentState;p.moveRangeByWrapper=e.includes("<w:moveFrom")||e.includes("<w:moveTo")?this.indexImportedMoveRanges(o):new WeakMap,p.collapsedCommentAnchorBlockById=new Map;let h;try{h=await this.parseBodyChildren(s,a,t,l,n)}finally{this.importSdtWrappers=void 0,this.importOxmlRanges=void 0,this.sdtAncestorStack=[],delete p.moveRangeByWrapper}this.finalizeImportedMovePairs(h),this.applyParagraphMarkRevisions(h),h=this.collapseTocRegions(h);const m=this.findAllSectionProperties(s);if(m.length>1){let b=0;for(const u of h){if(u.type!=="section-break")continue;const g=m[b+1];if(g){const w=this.parseSectionStartType(g);w&&(u.breakType=w)}b++}}const f={type:"doc",children:h.length>0?h:[this.createEmptyParagraph()]};if(r&&(f.pageLayout=r,r.pageNumberFormat&&r.pageNumberFormat!=="decimal"))for(const b of f.children)b.type==="section-break"&&b.layout?.pageNumberFormat===void 0&&(b.layout={...b.layout??{},pageNumberFormat:"decimal"});if(l.length>0&&(f.sdtWrappers=l),d.length>0&&(f.oxmlRanges=d),t?.stylesXmlRaw){f.stylesXml=t.stylesXmlRaw;const b=this.buildDocumentStylesheet(t,a);b&&(f.stylesheet=b)}return f}static resolveStylesheetFromStylesXml(e,r){const t=this.parseStylesXml(e);return this.buildDocumentStylesheet({styles:t,numbering:{abstractNums:new Map,nums:new Map}},Te(r).indentStepPx)}static buildDocumentStylesheet(e,r){const t=e.styles;if(t.stylesById.size===0)return;const i=t.defaultStyleIdByType?.get("paragraph"),n=[];for(const o of t.stylesById.values()){if(o.type!=="paragraph")continue;const s={isList:!1},a=[];t.paragraphDefault&&a.push(t.paragraphDefault),a.push(...this.resolveStyleChainPPr(o.id,t,"paragraph"));const l=this.resolveRunMarks(void 0,o.id,e),d=typeof l.fontSize=="number"&&l.fontSize>0?l.fontSize:ke.paragraph;for(const f of a)this.applyParagraphPropertiesFromElement(s,f,r,e,d);this.resolveLogicalAlignment(s);const p={};s.align&&(p.align=s.align),s.direction&&(p.direction=s.direction),s.leftIndent!==void 0&&(p.leftIndent=s.leftIndent),s.firstLineIndent!==void 0&&(p.firstLineIndent=s.firstLineIndent),s.lineSpacing!==void 0&&(p.lineSpacing=s.lineSpacing),this.applyDocxParagraphSpacing(p,s),s.keepNext!==void 0&&(p.keepNext=s.keepNext),s.keepLines!==void 0&&(p.keepLines=s.keepLines),s.widowControl!==void 0&&(p.widowControl=s.widowControl),s.bordersJson&&(p.borders=s.bordersJson),s.shading&&(p.shading=s.shading),s.tabStops&&s.tabStops.length>0&&(p.tabStops=JSON.stringify(s.tabStops));const h={styleId:o.id};o.name&&(h.name=o.name);const m=this.headingLevelForStyle(o)||s.heading;m&&(h.headingLevel=m),o.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}:void 0}static tocInstrOfBlock(e){if(e.type!=="paragraph")return;const r=e.children.filter(i=>i.type==="text"&&((i.text??"")!==""||i.marks?.fieldInstr));if(r.length===0)return;const t=r[0].marks?.fieldInstr;if(!(!t||!/^TOC\b/i.test(t.trim())))return r.every(i=>i.marks?.fieldInstr===t)?t:void 0}static tocTypographyOfRegion(e,r){const t=e.flatMap(l=>l.children.filter(d=>d.type==="text"&&(d.text??"").trim()!=="")),i=l=>{if(t.length===0)return;const d=l(t[0]);if(d!==void 0)return t.every(p=>l(p)===d)?d:void 0},n={},o=i(l=>l.marks?.fontFamily);o&&o!==r&&(n.fontFamily=o);const s=i(l=>l.marks?.fontSize);Ci(s)&&(n.fontSize=s);const a=i(l=>Er(l.marks?.color));return a&&(n.color=a),n}static collapseTocRegions(e){const r=[];let t,i,n=[],o={},s,a=!1;const l=()=>{if(t){a||(s=this.inferDocumentFontFamily({type:"doc",children:e.filter(p=>!this.tocInstrOfBlock(p))}),a=!0);const d={type:"toc",...o,...this.tocTypographyOfRegion(n,s),id:i||this.generateId(),instr:t,levels:Yi(t)};r.push(d)}t=void 0,i=void 0,n=[],o={}};for(const d of e){const p=this.tocInstrOfBlock(d);if(p&&p===t){d.type==="paragraph"&&n.push(d);continue}if(t&&l(),p){t=p,i=d.id,d.type==="paragraph"&&(n.push(d),d.direction&&(o.direction=d.direction,o.align=d.direction==="rtl"?"right":"left"),d.align&&(o.align=d.align));continue}r.push(d)}return l(),r}static parseParagraphMarkRevision(e){const r=this.getDirectChild(e,"w:pPr"),t=r?this.getDirectChild(r,"w:rPr"):void 0;if(!t)return null;const i=this.getDirectChild(t,"w:ins");if(i)return{kind:"split",meta:this.parseTrackedRevisionMeta(i)};const n=this.getDirectChild(t,"w:del");return n?{kind:"merge",meta:this.parseTrackedRevisionMeta(n)}:null}static applyParagraphMarkRevisions(e){for(let r=0;r<e.length;r++){const t=e[r],i=t.__pilcrowRevision;if(i&&delete t.__pilcrowRevision,!i||t.type!=="paragraph")continue;const n=e[r+1];if(!n||n.type!=="paragraph")continue;const o=i.meta.revisionId?`docxrev-${i.meta.revisionId}`:this.generateId(),s=i.kind==="split"?"Split":"Merge",a=this.revisionAuthorIdentity(i.meta.author),l={id:o,source:a.suggestionSource,authorType:a.suggestionAuthorType,label:s,...i.meta.createdAt!==void 0?{createdAt:i.meta.createdAt}:{},...i.meta.author?{agentName:i.meta.author}:{}},d=i.kind==="split"?{...l,type:"paragraph-split",blockId:t.id,insertedBlockId:n.id,beforeBlock:{type:"paragraph",id:t.id,children:[...t.children,...n.children]}}:{...l,type:"paragraph-merge",firstBlockId:t.id,secondBlockId:n.id};t.structuralSuggestionId=o,t.structuralSuggestionKind=i.kind,t.structuralSuggestionRole="before",t.structuralSuggestionLabel=s,t.structuralSuggestionRecord=JSON.stringify(d),n.structuralSuggestionId=o,n.structuralSuggestionKind=i.kind,n.structuralSuggestionRole="after",n.structuralSuggestionLabel=s}}static parseParagraphPropertyChange(e,r,t){const i=this.getDirectChild(e,"w:pPr"),n=i?this.getDirectChild(i,"w:pPrChange"):void 0;if(!n)return null;const o=this.parseTrackedRevisionMeta(n),s=this.getDirectChild(n,"w:pPr"),a={isList:!1};if(t){const l=s&&this.getDirectChild(s,"w:pStyle")?.getAttribute("w:val")||void 0;a.styleId=l;const d=[];t.styles.paragraphDefault&&d.push(t.styles.paragraphDefault),d.push(...this.resolveStyleChainPPr(l,t.styles,"paragraph")),s&&d.push(s);for(const p of d)this.applyParagraphPropertiesFromElement(a,p,r,t)}else s&&this.applyParagraphPropertiesFromElement(a,s,r);return this.resolveLogicalAlignment(a),{meta:o,priorProps:a}}static applyParsedPropertiesToParagraphNode(e,r){delete e.align,delete e.leftIndent,delete e.firstLineIndent,delete e.heading,delete e.lineSpacing,delete e.keepNext,delete e.keepLines,delete e.widowControl,delete e.borders,delete e.shading,delete e.styleId,delete e.direction,r.align&&(e.align=r.align);const t=this.directionAttrFor(r.direction,this.paragraphNodeText(e));t&&(e.direction=t),r.leftIndent!==void 0&&(e.leftIndent=r.leftIndent),r.firstLineIndent!==void 0&&(e.firstLineIndent=r.firstLineIndent),r.heading&&(e.heading=r.heading),r.lineSpacing!==void 0&&(e.lineSpacing=r.lineSpacing),this.applyDocxParagraphSpacing(e,r),r.keepNext&&(e.keepNext=!0),r.keepLines&&(e.keepLines=!0),r.widowControl===!1&&(e.widowControl=!1),r.bordersJson&&(e.borders=r.bordersJson),r.shading&&(e.shading=r.shading);const i=r.styleId;i&&i.toLowerCase()!=="normal"&&(e.styleId=i)}static applyDocxParagraphSpacing(e,r){if(r.contextualSpacing){e.contextualSpacing=!0,e.spaceBefore=0,e.spaceAfter=0;return}e.spaceBefore=r.spaceBefore??0,e.spaceAfter=r.spaceAfter??0}static async parseWordParagraphBlocks(e,r,t){const i=[];for(let u=0;u+1<e.children.length;u++){const g=e.children[u],w=e.children[u+1],S=g.getAttribute("w:id");g.tagName==="w:commentRangeStart"&&w.tagName==="w:commentRangeEnd"&&S&&w.getAttribute("w:id")===S&&i.push(S)}const n=this.resolveParagraphProperties(e,r,t),o=this.parseParagraphMarkRevision(e),s=[];let a=!1,l="";const d=[];n.pageBreakBefore&&d.push(this.createPageBreakBlock());for(let u=0;u<e.children.length;u++){const g=e.children[u],w=g.tagName;if(!this.trackCommentRangeMarker(g,t)&&!(this.trackBookmarkMarker(g,t)||this.trackOxmlRangeMarker(g,t))){if(w==="w:fldSimple"){s.push(...await this.parseFldSimpleItems(g,n,t));continue}if(w==="mc:AlternateContent"){const S=this.selectAlternateContentBranch(g);S&&s.push(...await this.parseInlineItemsFromChildren(S,n,t));continue}if(w==="w:r")s.push(...this.stampOpenComments(await this.parseWordRunItems(g,n,t),t));else if(w==="w:sdt")s.push(...await this.parseInlineSdtItems(g,n,t));else if(w==="w:ins"||w==="w:del"||w==="w:moveFrom"||w==="w:moveTo")s.push(...await this.parseTrackedChangeItems(g,n,t));else if(w==="w:hyperlink")s.push(...await this.parseHyperlinkItems(g,n,t));else if(w==="m:oMathPara"){const S=this.ommlToLatex(g);S&&(s.some(T=>T.kind==="text"&&T.node.text.trim()!=="")?s.push({kind:"text",node:{type:"text",text:S,marks:{latex:!0}}}):(a=!0,l=S))}else if(w==="m:oMath"){const S=this.ommlToLatex(g);S&&s.push({kind:"text",node:{type:"text",text:S,marks:{latex:!0}}})}}}const p=s.filter(u=>u.kind==="text");if(a&&p.every(u=>u.node.text.trim()===""))return d.push({type:"math",id:this.generateId(),content:l,displayMode:"block",align:n.align==="left"||n.align==="right"||n.align==="center"?n.align:"center"}),d;const h=d.concat(this.buildBlocksFromParagraphItems(s,n));if(t){const u=h.find(w=>w.type==="paragraph"),g=u?.children[0];if(u&&u.children.length===1&&g?.type==="text"&&g.text===""&&g.marks?.fontSize===void 0){const w=this.getDirectChild(e,"w:pPr"),S=this.resolveRunMarks(w?this.getDirectChild(w,"w:rPr"):void 0,n.styleId,t),T={};typeof S.fontSize=="number"&&S.fontSize>0&&(T.fontSize=S.fontSize),S.fontFamily&&!g.marks?.fontFamily&&(T.fontFamily=S.fontFamily),Object.keys(T).length>0&&(g.marks={...g.marks,...T})}}const m=this.getDirectChild(e,"w:pPr"),f=tr(e),b=rt(m,Fr);if(f||b){const u=h.find(g=>g.type==="paragraph");u&&(f&&(u.oxmlAttrs=f),b&&(u.oxmlPPr=b))}if(i.length>0){const u=h.find(g=>g.type==="paragraph");if(u?.id){const g=t??this.fallbackCommentState,w=g.collapsedCommentAnchorBlockById??(g.collapsedCommentAnchorBlockById=new Map);for(const S of i)w.set(S,u.id)}}if(!n.list&&!o){const u=this.parseParagraphPropertyChange(e,r,t);if(u)for(let g=h.length-1;g>=0;g--){const w=h[g];if(w.type!=="paragraph")continue;const S=u.meta.revisionId?`docxrev-${u.meta.revisionId}`:this.generateId(),T=this.revisionAuthorIdentity(u.meta.author),F=JSON.parse(JSON.stringify(w)),B=JSON.parse(JSON.stringify(w));this.applyParsedPropertiesToParagraphNode(B,u.priorProps),w.structuralSuggestionId=S,w.structuralSuggestionKind="change",w.structuralSuggestionLabel="Paragraph format",w.structuralSuggestionRecord=JSON.stringify({id:S,type:"block-change",blockId:w.id,source:T.suggestionSource,authorType:T.suggestionAuthorType,label:"Paragraph format",...u.meta.createdAt!==void 0?{createdAt:u.meta.createdAt}:{},...u.meta.author?{agentName:u.meta.author}:{},beforeBlock:B,acceptedBlock:F});break}}if(o){for(let u=h.length-1;u>=0;u--)if(h[u].type==="paragraph"){h[u].__pilcrowRevision=o;break}}return h}static async parseBodyChildren(e,r,t,i,n){const o=[];let s;const a=new Map,l=g=>g.abstractNumId??g.numId,d=g=>{const w=l(g);let S=a.get(w);return S||(S={chainId:this.generateId(),seenNumIds:new Set,started:!1},a.set(w,S)),S},p=g=>{const w=d(g),S=g.hasLevel0StartOverride&&!w.seenNumIds.has(g.numId);if(!w.started||S)return g.startNumber},h=()=>{s&&s.list.children.length>0&&o.push(s.list),s=void 0},m=Array.from(e.children),f=[];let b;const u=(g,w)=>{if(n){for(const S of f)Qt(n,g,S);f.length=0,Qt(n,g,w),b=g}};for(let g=0;g<m.length;g++){const w=m[g],S=w.tagName==="w:bookmarkStart"||this.OXML_RANGE_PAIRS.has(w.tagName)?"start":w.tagName==="w:bookmarkEnd"||[...this.OXML_RANGE_PAIRS.values()].includes(w.tagName)?"end":null;if(this.trackBookmarkMarker(w,t)||this.trackOxmlRangeMarker(w,t)){n&&S==="end"&&b?Qt(n,b,g):n&&S!==null&&f.push(g);continue}const T=i&&w.tagName==="w:sdt"?this.getDirectChild(w,"w:sdtPr"):void 0;let F=-1,B,P;T&&(h(),F=o.length,B=this.generateId(),P=this.sdtAncestorStack[this.sdtAncestorStack.length-1]?.id,this.sdtAncestorStack.push({el:w,id:B}));let z;try{z=await this.parseBodyChild(w,r,t)}finally{T&&this.sdtAncestorStack.pop()}for(const E of z){if(E.kind==="list-item"){if(!s||s.numId!==E.list.numId||s.variant!==E.list.variant){h();const G=E.list.variant==="ordered",$=G?d(E.list):null;s={numId:E.list.numId,variant:E.list.variant,list:{type:"list",id:this.generateId(),variant:E.list.variant,children:[],startNumber:G?p(E.list):void 0,lineSpacing:E.list.lineSpacing,...G&&E.list.formatSpec?{numberingFormat:E.list.formatSpec}:{}}},$&&(s.list.numberingChainId=$.chainId,$.started=!0,$.seenNumIds.add(E.list.numId))}s.list.lineSpacing===void 0&&E.list.lineSpacing!==void 0&&(s.list.lineSpacing=E.list.lineSpacing),s.list.spaceBefore===void 0&&this.applyDocxParagraphSpacing(s.list,E.list);for(const G of["lineSpacing","spaceBefore","spaceAfter"])(E.item[G]===void 0||E.item[G]===s.list[G])&&delete E.item[G];s.list.children.push(E.item),u(s.list,g);continue}h(),o.push(E.block),u(E.block,g)}if(T&&F>=0){h();const E=o.slice(F).map(G=>G.id).filter(G=>!!G);if(E.length>0&&i)try{const G=new XMLSerializer().serializeToString(T);i.push({id:B??this.generateId(),prXml:G,...P?{parentId:P}:{},blockIds:E})}catch{}}}return h(),o}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,o=n.length>0&&n[n.length-1].el===e;let s;if(!o&&n.length>0&&this.importSdtWrappers){const l=this.getDirectChild(e,"w:sdtPr");if(l)try{s={id:this.generateId(),prXml:new XMLSerializer().serializeToString(l),parentId:n[n.length-1].id}}catch{}}s&&n.push({el:e,id:s.id});const a=[];try{for(let l=0;l<i.children.length;l++)a.push(...await this.parseBodyChild(i.children[l],r,t))}finally{s&&n.pop()}if(s&&this.importSdtWrappers){const l=a.filter(d=>d.kind==="block").map(d=>d.block.id).filter(d=>!!d);l.length>0&&(s.blockIds=l,this.importSdtWrappers.push(s))}return a}if(e.tagName==="w:p"){const i=await this.parseWordParagraphBlocks(e,r,t),n=this.getDirectChild(e,"w:pPr"),o=n?this.getDirectChild(n,"w:sectPr"):void 0;if(o){const a={...this.parseSectionPropertiesElement(o),...this.getDirectChild(o,"w:pgBorders")?{}:{pageBorders:null}},l=i.find(m=>m.type==="paragraph"&&m.__pilcrowRevision),d=l?.__pilcrowRevision?.kind==="merge"?l.__pilcrowRevision:void 0;d&&l&&delete l.__pilcrowRevision;const p={kind:"block",block:{type:"section-break",id:this.generateId(),...a?{layout:a}:{},...d?{diffState:"delete",suggestionId:d.meta.revisionId?`docxrev-${d.meta.revisionId}`:this.generateId(),...d.meta.author?{suggestionAuthorName:d.meta.author}:{},...d.meta.createdAt!==void 0?{suggestionCreatedAt:d.meta.createdAt}:{}}:{}}};if(i.length===1&&i[0].type==="paragraph"&&!i[0].__pilcrowRevision&&i[0].children.every(m=>m.type==="text"&&m.text.length===0))return[p];const h=[];for(const m of i)h.push({kind:"block",block:m});return h.push(p),h}const s=[];for(const a of i){if(a.type!=="paragraph"){s.push({kind:"block",block:a});continue}const l=this.codeBlockFromStyledParagraph(a);if(l){s.push({kind:"block",block:l});continue}const d=this.resolveParagraphProperties(e,r,t);if(!d.list){const p=this.todoItemFromParagraph(a,d);if(p){s.push(p);continue}s.push({kind:"block",block:a});continue}s.push({kind:"list-item",list:d.list,item:{type:"list-item",id:this.generateId(),children:a.children,lineSpacing:d.lineSpacing,spaceBefore:d.spaceBefore,spaceAfter:d.spaceAfter,indentLevel:d.list.level}})}return s}if(e.tagName==="w:tbl"){const i=await this.parseTableBlock(e,r,t);return i?[{kind:"block",block:i}]:[]}if(e.tagName==="w:customXml"){const i=[];for(let n=0;n<e.children.length;n++)i.push(...await this.parseBodyChild(e.children[n],r,t));return i}if(!Xr.has(e.tagName))try{return[{kind:"block",block:{type:"docx-raw",id:this.generateId(),origin:"body",...ir(e)}}]}catch{}return[]}static codeBlockFromStyledParagraph(e){const r=e.styleId;if(!r||!r.startsWith(this.CODE_BLOCK_STYLE_ID))return;const t=r.slice(this.CODE_BLOCK_STYLE_ID.length);if(t.length>0&&!t.startsWith("_"))return;const i=t.startsWith("_")?t.slice(1):void 0,n=e.children.filter(o=>o.type==="text").map(o=>o.text).join("");return{type:"code",id:e.id??this.generateId(),content:n,...i?{language:i}:{}}}static todoItemFromParagraph(e,r){if(e.styleId||r.heading)return;const t=e.children[0];if(!t||t.type!=="text")return;const i=this.TODO_MARKERS.find(([a])=>t.text.startsWith(a));if(!i)return;const n=t.text.slice(i[0].length),o=[...n.length>0?[{...t,text:n}]:[],...e.children.slice(1)].filter(a=>a.type==="text");o.length===0&&o.push({type:"text",text:""});const s=Math.max(0,Math.round(Number(e.leftIndent??0)>0?Number(e.leftIndent)-1:0));return{kind:"list-item",list:{numId:"revise-todo",level:s,variant:"todo",lineSpacing:r.lineSpacing,spaceBefore:r.spaceBefore,spaceAfter:r.spaceAfter,contextualSpacing:r.contextualSpacing},item:{type:"list-item",id:this.generateId(),children:o,lineSpacing:r.lineSpacing,spaceBefore:r.spaceBefore,spaceAfter:r.spaceAfter,indentLevel:s,...i[1]?{checked:!0}:{}}}}static buildBlocksFromParagraphItems(e,r){const t=[];let i=[];const n=(o=!1)=>{if(i.length===0&&!o)return;const s={type:"paragraph",id:this.generateId(),children:i.length>0?i:[{type:"text",text:"",marks:{}}]};r.align&&(s.align=r.align),r.leftIndent!==void 0&&(s.leftIndent=r.leftIndent),r.firstLineIndent!==void 0&&(s.firstLineIndent=r.firstLineIndent),r.heading&&(s.heading=r.heading),r.lineSpacing!==void 0&&(s.lineSpacing=r.lineSpacing),this.applyDocxParagraphSpacing(s,r),r.keepNext&&(s.keepNext=!0),r.keepLines&&(s.keepLines=!0),r.widowControl===!1&&(s.widowControl=!1),r.bordersJson&&(s.borders=r.bordersJson),r.shading&&(s.shading=r.shading);const a=r.styleId;a&&a.toLowerCase()!=="normal"&&(s.styleId=a),r.tabStops&&r.tabStops.length&&(s.tabStops=JSON.stringify(r.tabStops));const l=this.directionAttrFor(r.direction,this.paragraphNodeText(s));l&&(s.direction=l),t.push(s),i=[]};for(const o of e){if(o.kind==="text"){i.push(o.node);continue}if(o.kind==="pagebreak"){n(),t.push(this.createPageBreakBlock());continue}if(o.kind==="blocks"){n(),t.push(...o.blocks);continue}n(),t.push(o.node)}return t.length===0&&i.length===0?n(!0):n(),t}static resolveParagraphProperties(e,r,t){if(!t)return this.parseWordParagraphProperties(e,r);const i=this.getDirectChild(e,"w:pPr"),n=this.getDirectChild(i||e,"w:pStyle")?.getAttribute("w:val")||void 0,o={isList:!1,styleId:n},s=this.effectiveParagraphStyleId(n,t.styles),a=[];t.styles.paragraphDefault&&a.push(t.styles.paragraphDefault),a.push(...this.resolveStyleChainPPr(s,t.styles,"paragraph")),i&&a.push(i);const l=this.resolveParagraphFontSizePx(i,s,t);for(const d of a)this.applyParagraphPropertiesFromElement(o,d,r,t,l);return this.resolveLogicalAlignment(o),o}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:ke.paragraph,o=e/20*(4/3),s=Math.round(o/n*100)/100;return i==="atleast"?s>ki.paragraph?s:void 0:Math.max(.1,s)}static effectiveParagraphStyleId(e,r){return e??r.defaultStyleIdByType?.get("paragraph")}static resolveParagraphFontSizePx(e,r,t){const i=e?this.getDirectChild(e,"w:rPr"):void 0,n=this.resolveRunMarks(i,r,t);return typeof n.fontSize=="number"&&n.fontSize>0?n.fontSize:ke.paragraph}static resolveStyleChainPPr(e,r,t){return e?this.resolveStyleChain(e,r,t).map(i=>i.pPr).filter(Boolean):[]}static resolveStyleChainRPr(e,r,t){return e?this.resolveStyleChain(e,r,t).map(i=>i.rPr).filter(Boolean):[]}static resolveStyleChain(e,r,t){const i=[],n=new Set;let o=r.stylesById.get(e);for(;o&&!n.has(o.id);)n.add(o.id),(!t||o.type===t)&&i.unshift(o),o=o.basedOn?r.stylesById.get(o.basedOn):void 0;return i}static applyParagraphPropertiesFromElement(e,r,t,i,n){if(!r)return;this.getDirectChild(r,"w:keepNext")&&(e.keepNext=this.isOn(r,"w:keepNext")),this.getDirectChild(r,"w:keepLines")&&(e.keepLines=this.isOn(r,"w:keepLines")),this.getDirectChild(r,"w:widowControl")&&(e.widowControl=this.isOn(r,"w:widowControl")),this.getDirectChild(r,"w:bidi")&&(e.direction=this.isOn(r,"w:bidi")?"rtl":"ltr"),this.parseParagraphDecoration(r,e),this.applyTabStopsFromPPr(e,r),this.applyJcFromPPr(e,r);const o=this.getDirectChild(r,"w:ind");if(o){const g=this.parseTwipsAttribute(o,"w:start")??this.parseTwipsAttribute(o,"w:left");if(g===0)e.leftIndent=0;else if(g!==void 0&&g>0){const T=Bt(this.twipsToPx(g),{indentStepPx:t,storedAsUnits:!1});T!==void 0&&(e.leftIndent=T)}const w=this.parseTwipsAttribute(o,"w:firstLine"),S=this.parseTwipsAttribute(o,"w:hanging");if(S!==void 0&&S>0)e.firstLineIndent=-1;else if(w===0)e.firstLineIndent=0;else if(w!==void 0&&w>0){const T=Bt(this.twipsToPx(w),{indentStepPx:t,storedAsUnits:!1,firstLine:!0});T!==void 0&&(e.firstLineIndent=T)}}const s=this.parseOnOffElement(this.getDirectChild(r,"w:pageBreakBefore"));s!==void 0&&(e.pageBreakBefore=s);const a=this.getDirectChild(r,"w:spacing"),l=a?.getAttribute("w:line");if(l){const g=parseInt(l,10);if(Number.isFinite(g)&&g>0){const w=this.lineSpacingFromDocxSpacing(g,a?.getAttribute("w:lineRule"),n);w!==void 0&&(e.lineSpacing=w)}}const d=g=>Math.max(0,Math.round(this.twipsToPx(g)*100)/100),p=this.parseTwipsAttribute(a,"w:before");p!==void 0&&(e.spaceBefore=d(p));const h=this.parseTwipsAttribute(a,"w:after");h!==void 0&&(e.spaceAfter=d(h)),this.getDirectChild(r,"w:contextualSpacing")&&(e.contextualSpacing=this.isOn(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 b=this.getDirectChild(r,"w:pStyle")?.getAttribute("w:val");if(b){e.styleId=b;const g=i?this.headingLevelForStyle(i.styles.stylesById.get(b)):this.headingLevelForStyle({id:b});g&&(e.heading=g)}const u=i?this.getDirectChild(r,"w:numPr"):void 0;if(u&&i){const g=this.getDirectChild(u,"w:ilvl"),w=this.getDirectChild(u,"w:numId")?.getAttribute("w:val"),S=g?.getAttribute("w:val"),T=S&&Number.isFinite(parseInt(S,10))?parseInt(S,10):0;if(w&&w!=="0"){const F=this.resolveListInfo(w,T,i.numbering);F&&(e.list={...F,lineSpacing:e.lineSpacing,spaceBefore:e.spaceBefore,spaceAfter:e.spaceAfter,contextualSpacing:e.contextualSpacing},e.isList=!0)}}}static headingLevelForStyle(e){if(!e)return;const r=[e.id,e.name].filter(Boolean).map(t=>t.toLowerCase().replace(/[\s_-]+/g,""));for(const t of r){const i=t.match(/heading([1-6])$/);if(i)return parseInt(i[1],10)}}static resolveListInfo(e,r,t){const i=t.nums.get(e),n=i?.abstractNumId?t.abstractNums.get(i.abstractNumId):void 0,o=n?.levels.get(r);if(!o)return;const s=(o.format||"").toLowerCase()==="bullet"?"unordered":"ordered",a=i?.levelStartOverrides.get(r)??o.start;let l;if(s==="ordered"&&n){const d=[];let p=!1;for(let h=0;h<=2;h++){const m=n.levels.get(h);(m?.format||m?.text)&&(p=!0),d.push({...m?.format?{numFmt:m.format}:{},...m?.text?{lvlText:m.text}:{}})}p&&(l=JSON.stringify(d))}return{numId:e,level:r,variant:s,startNumber:a,abstractNumId:i?.abstractNumId,hasLevel0StartOverride:i?.levelStartOverrides.has(0)??!1,formatSpec:l}}static async parseHyperlinkItems(e,r,t){const i=e.getAttribute("r:id"),n=e.getAttribute("w:anchor"),o=(i?t?.relationships.get(i)?.target:void 0)||(n?`#${n}`:void 0),s=[];for(let a=0;a<e.children.length;a++){const l=e.children[a];this.trackBookmarkMarker(l,t)||this.trackOxmlRangeMarker(l,t)||l.tagName==="w:r"&&s.push(...await this.parseWordRunItems(l,r,t,o))}return s}static revisionAuthorIdentity(e){return e?.trim()===It?{suggestionSource:"agent",suggestionAuthorType:"ai"}:{suggestionSource:"manual",suggestionAuthorType:"human"}}static indexImportedMoveRanges(e){const r=new WeakMap,t={from:[],to:[]},i=Array.from(e.getElementsByTagName("*"));for(let n=0;n<i.length;n++){const o=i[n],s=o.tagName==="w:moveFromRangeStart"?"from":o.tagName==="w:moveToRangeStart"?"to":void 0;if(s){const d=o.getAttribute("w:name")?.trim(),p=o.getAttribute("w:id")?.trim();if(d&&p){const h=o.getAttribute("w:date"),m=h?Date.parse(h):NaN;t[s].push({version:1,name:d,role:s,rangeId:p,...o.getAttribute("w:author")?.trim()?{rangeAuthor:o.getAttribute("w:author").trim()}:{},...Number.isFinite(m)?{rangeCreatedAt:m}:{}})}continue}const a=o.tagName==="w:moveFrom"?"from":o.tagName==="w:moveTo"?"to":void 0;if(a){const d=t[a][t[a].length-1],p=o.getAttribute("w:id")?.trim();d&&p&&r.set(o,{...d,wrapperId:p,fallbackSuggestionId:`docxrev-${p}`});continue}const l=o.tagName==="w:moveFromRangeEnd"?"from":o.tagName==="w:moveToRangeEnd"?"to":void 0;if(l){const d=o.getAttribute("w:id")?.trim(),p=t[l],h=d?p.map(m=>m.rangeId).lastIndexOf(d):p.length-1;h>=0&&p.splice(h,1)}}return r}static parseDocxMoveMark(e){if(!(typeof e!="string"||!e))try{const r=JSON.parse(e);return r.version!==1||typeof r.name!="string"||!r.name||r.role!=="from"&&r.role!=="to"||typeof r.rangeId!="string"||!r.rangeId||typeof r.wrapperId!="string"||!r.wrapperId||typeof r.fallbackSuggestionId!="string"||!r.fallbackSuggestionId?void 0:r}catch{return}}static finalizeImportedMovePairs(e){const r=new Map,t=i=>{if(!i||typeof i!="object")return;if(Array.isArray(i)){i.forEach(t);return}const n=i;if(n.type==="text"&&n.marks?.docxMove){const o=this.parseDocxMoveMark(n.marks.docxMove);if(o){const s=r.get(o.name)??{roles:new Set,nodes:[]};s.roles.add(o.role),s.nodes.push(n),r.set(o.name,s)}}t(n.children)};t(e);for(const i of r.values())if(!(i.roles.has("from")&&i.roles.has("to")))for(const n of i.nodes){const o=this.parseDocxMoveMark(n.marks?.docxMove);!o||!n.marks||(n.marks.suggestionId=o.fallbackSuggestionId,delete n.marks.docxMove)}}static hasDocxMoveMarks(e){if(!e||typeof e!="object")return!1;if(Array.isArray(e))return e.some(t=>this.hasDocxMoveMarks(t));const r=e;return!!r.marks?.docxMove||this.hasDocxMoveMarks(r.children)}static applyTabStopsFromPPr(e,r){const t=this.getDirectChild(r,"w:tabs");if(!t)return;const i=e.tabStops?[...e.tabStops]:[];for(let n=0;n<t.children.length;n++){const o=t.children[n];if(o.tagName!=="w:tab")continue;const s=parseFloat(o.getAttribute("w:pos")||"");if(!Number.isFinite(s)||s<0)continue;const a=this.twipsToPx(s),l=i.findIndex(f=>Math.abs(f.pos-a)<.5);l>=0&&i.splice(l,1);const d=(o.getAttribute("w:val")||"left").toLowerCase();if(d==="clear")continue;let p;if(d==="right"||d==="end")p="right";else if(d==="center")p="center";else if(d==="decimal")p="decimal";else if(d==="left"||d==="start"||d==="num")p="left";else continue;const h={pos:a,align:p},m=(o.getAttribute("w: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,o)=>n.pos-o.pos),i.length>0?e.tabStops=i:delete e.tabStops}static parseParagraphDecoration(e,r){const t=this.getDirectChild(e,"w:pBdr");if(t){let n={};if(r.bordersJson)try{n=JSON.parse(r.bordersJson)}catch{n={}}for(const o of["top","bottom","left","right"]){const s=this.getDirectChild(t,`w:${o}`);if(!s)continue;const a=(s.getAttribute("w:val")||"single").toLowerCase();if(a==="none"||a==="nil"){n[o]={style:"none",width:0,color:"#000000"};continue}const l=["dashed","dotted","double"].includes(a)?a:"single",d=parseInt(s.getAttribute("w:sz")||"4",10),p=Math.max(.5,Math.round((Number.isFinite(d)?d:4)/6*100)/100),h=(s.getAttribute("w:color")||"auto").trim(),m=h.toLowerCase()==="auto"?"#000000":`#${h.replace(/^#/,"")}`;n[o]={style:l,width:p,color:m}}Object.keys(n).length>0&&(r.bordersJson=JSON.stringify(n))}const i=this.getDirectChild(e,"w:shd");if(i){const n=(i.getAttribute("w:fill")||"").trim(),o=(i.getAttribute("w:val")||"clear").toLowerCase();n&&n.toLowerCase()!=="auto"?r.shading=`#${n.replace(/^#/,"")}`:(!n||n.toLowerCase()==="auto"||o==="nil"||o==="none")&&(r.shading="transparent")}}static trackBookmarkMarker(e,r){const t=r??this.fallbackCommentState;if(e.tagName==="w:bookmarkStart"){const i=e.getAttribute("w:id"),n=e.getAttribute("w:name");return i&&n&&n!=="_GoBack"&&((t.openBookmarkNames??(t.openBookmarkNames=new Set)).add(n),(t.bookmarkNameById??(t.bookmarkNameById=new Map)).set(i,n)),!0}if(e.tagName==="w:bookmarkEnd"){const i=e.getAttribute("w:id"),n=i?t.bookmarkNameById?.get(i):void 0;return n&&t.openBookmarkNames?.delete(n),!0}return!1}static trackOxmlRangeMarker(e,r){const t=r??this.fallbackCommentState;if(this.OXML_RANGE_PAIRS.has(e.tagName)){const i=e.getAttribute("w:id");if(i)try{const n={id:this.generateId(),tagName:e.tagName,startXml:new XMLSerializer().serializeToString(e),endXml:""};(t.openOxmlRanges??(t.openOxmlRanges=new Map)).set(i,n)}catch{}return!0}for(const[i,n]of this.OXML_RANGE_PAIRS){if(e.tagName!==n)continue;const o=e.getAttribute("w:id"),s=o?t.openOxmlRanges?.get(o):void 0;if(s&&o){try{s.endXml=new XMLSerializer().serializeToString(e),this.importOxmlRanges?.push(s)}catch{}t.openOxmlRanges.delete(o)}return!0}return!1}static async parseFldSimpleItems(e,r,t){const i=(e.getAttribute("w:instr")||"").trim(),n=await this.parseInlineItemsFromChildren(e,r,t);if(!i)return n;for(const o of n)o.kind==="text"&&o.node&&(o.node.marks={...o.node.marks??{},fieldInstr:i});return n}static trackCommentRangeMarker(e,r){const t=r??this.fallbackCommentState;if(e.tagName==="w:commentRangeStart"){const i=e.getAttribute("w:id");return i&&(t.openCommentIds??(t.openCommentIds=new Set)).add(i),!0}if(e.tagName==="w:commentRangeEnd"){const i=e.getAttribute("w:id");return i&&t.openCommentIds?.delete(i),!0}return!1}static stampOpenComments(e,r){const t=(r??this.fallbackCommentState).openCommentIds;if(!t||t.size===0)return e;const i=[...t].sort().map(n=>`docxcmt-${n}`).join(",");for(const n of e)n.kind==="text"&&n.node&&(n.node.marks={...n.node.marks??{},comment:i});return e}static async parseInlineSdtItems(e,r,t){const i=this.getDirectChild(e,"w:sdtContent");if(!i)return[];const n=this.importSdtWrappers;let o;if(n){const a=this.getDirectChild(e,"w:sdtPr");if(a)try{const l=this.sdtAncestorStack[this.sdtAncestorStack.length-1];o={id:this.generateId(),prXml:new XMLSerializer().serializeToString(a),scope:"inline",...l?{parentId:l.id}:{}}}catch{}}o&&this.sdtAncestorStack.push({el:e,id:o.id});let s;try{s=await this.parseInlineItemsFromChildren(i,r,t)}finally{o&&this.sdtAncestorStack.pop()}if(o&&n){let a=!1;for(const l of s)if(l.kind==="text"&&l.node){const d=l.node.marks?.sdtInline;l.node.marks={...l.node.marks??{},sdtInline:d?`${d},${o.id}`:o.id},a=!0}a&&n.push(o)}return s}static async parseInlineItemsFromChildren(e,r,t){const i=[];for(let n=0;n<e.children.length;n++){const o=e.children[n];if(!this.trackCommentRangeMarker(o,t)&&!(this.trackBookmarkMarker(o,t)||this.trackOxmlRangeMarker(o,t))){if(o.tagName==="w:fldSimple"){i.push(...await this.parseFldSimpleItems(o,r,t));continue}if(o.tagName==="mc:AlternateContent"){const s=this.selectAlternateContentBranch(o);s&&i.push(...await this.parseInlineItemsFromChildren(s,r,t));continue}o.tagName==="w:r"?i.push(...this.stampOpenComments(await this.parseWordRunItems(o,r,t),t)):o.tagName==="w:hyperlink"?i.push(...await this.parseHyperlinkItems(o,r,t)):o.tagName==="w:ins"||o.tagName==="w:del"||o.tagName==="w:moveFrom"||o.tagName==="w:moveTo"?i.push(...await this.parseTrackedChangeItems(o,r,t)):o.tagName==="w:sdt"&&i.push(...await this.parseInlineSdtItems(o,r,t))}}return i}static parseTrackedRevisionMeta(e){const r=e.getAttribute("w:id"),t=e.getAttribute("w:author")?.trim()||void 0,i=e.getAttribute("w:date"),n=i?Date.parse(i):NaN;return{revisionId:r&&r.length>0?r:null,author:t,createdAt:Number.isFinite(n)?n:void 0}}static async parseTrackedChangeItems(e,r,t,i){const n=e.tagName==="w:ins"||e.tagName==="w:moveTo",o=e.tagName==="w:moveFrom"||e.tagName==="w:moveTo",s=this.parseTrackedRevisionMeta(e),a=o?(t??this.fallbackCommentState).moveRangeByWrapper?.get(e):void 0,l=a?`docxmove-${encodeURIComponent(a.name)}`:s.revisionId?`docxrev-${s.revisionId}`:this.generateId(),d={...n?{insertion:!0}:{deletion:!0},suggestionId:l,...this.revisionAuthorIdentity(s.author),suggestionLabel:o?"Move":n?"Insert":"Delete",...s.createdAt!==void 0?{suggestionCreatedAt:s.createdAt}:{},...s.author?{suggestionAuthorName:s.author}:{},...a?{docxMove:JSON.stringify(a)}:{},...!n&&i?{layeredInsertion:JSON.stringify(i)}:{}},p=m=>m.map(f=>f.kind==="text"?{...f,node:{...f.node,marks:{...f.node.marks??{},...d}}}: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(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),t))):f.tagName==="w:del"&&n?h.push(...await this.parseTrackedChangeItems(f,r,t,{id:l,...(()=>{const b=this.revisionAuthorIdentity(s.author);return{source:b.suggestionSource,authorType:b.suggestionAuthorType}})(),createdAt:s.createdAt,label:"Insert",authorName:s.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){const o=this.getDirectChild(e,"w:rPr"),s=n?{...n}:this.resolveRunMarks(o,r.styleId,t,i);if(!n&&!r.heading&&s.fontSize===ke.paragraph&&this.docDefaultRunSizePx(t)===ke.paragraph&&delete s.fontSize,!n){const m=rt(o,Rr);m&&(s.oxmlRPr=m)}const a=!n&&o?this.getDirectChild(o,"w:rPrChange"):void 0;if(a){const m=this.parseTrackedRevisionMeta(a),f=this.getDirectChild(a,"w:rPr"),b=this.resolveRunMarks(f,r.styleId,t,i);Object.assign(s,{formatChange:!0,suggestionId:m.revisionId?`docxrev-${m.revisionId}`:this.generateId(),...this.revisionAuthorIdentity(m.author),suggestionLabel:"Format",...m.createdAt!==void 0?{suggestionCreatedAt:m.createdAt}:{},...m.author?{suggestionAuthorName:m.author}:{},suggestionPriorAttributes:JSON.stringify(b??{})})}const l=[];let d="";const p=t??this.fallbackCommentState,h=()=>{if(!d)return;const m={...s},f=p.openBookmarkNames;f&&f.size>0&&(m.bookmark=[...f].sort().join(","));const b=p.openOxmlRanges;b&&b.size>0&&(m.oxmlRange=[...b.values()].map(g=>g.id).sort().join(","));const u=p.fieldInstrStack?.[0];u?.inResult&&u.instr.trim()&&(m.fieldInstr=u.instr.trim()),l.push({kind:"text",node:{type:"text",text:d,marks:Object.keys(m).length>0?m:void 0}}),d=""};for(let m=0;m<e.children.length;m++){const f=e.children[m];if(f.tagName==="w:t"){d+=f.textContent||"";continue}if(f.tagName==="w:fldChar"){const b=f.getAttribute("w:fldCharType"),u=p.fieldInstrStack??(p.fieldInstrStack=[]);h(),b==="begin"?u.push({instr:"",inResult:!1}):b==="separate"?u.length>0&&(u[u.length-1].inResult=!0):b==="end"&&u.pop();continue}if(f.tagName==="w:instrText"){const b=p.fieldInstrStack;b&&b.length>0&&(b[b.length-1].instr+=f.textContent||"");continue}if(f.tagName==="w:footnoteReference"||f.tagName==="w:endnoteReference"){const b=f.getAttribute("w:id");if(b){h();const u=f.tagName==="w:endnoteReference"?"docxen":"docxfn";l.push({kind:"text",node:{type:"text",text:"0",marks:{...s,footnoteRef:`${u}-${b}`,superscript:!0}}})}continue}if(f.tagName==="w:delText"){d+=f.textContent||"";continue}if(f.tagName==="w:tab"){d+=" ";continue}if(f.tagName==="w:br"){(f.getAttribute("w:type")||"").trim().toLowerCase()==="page"?(h(),l.push({kind:"pagebreak"})):d+=`
|
|
5
|
+
`;continue}if(f.tagName!=="w:lastRenderedPageBreak"){if(f.tagName==="mc:AlternateContent"){h();const b=this.selectAlternateContentBranch(f);b&&l.push(...await this.parseWordRunItems(b,r,t,i,s));continue}if(f.tagName==="w:drawing"){h();const b=await this.parseImageFromDrawing(f,r.align,t);b&&l.push({kind:"image",node:b});const u=await this.parseTextBoxContent(f,t);if(u.length>0&&l.push({kind:"blocks",blocks:u}),!b&&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 b=f.getElementsByTagName("*");let u=!1;for(let w=0;w<b.length;w++){const S=(b[w].getAttribute("o:hr")||"").toLowerCase();if(S==="t"||S==="true"||S==="1"){u=!0;break}}if(u){const w={type:"paragraph",id:this.generateId(),children:[{type:"text",text:"",marks:{}}],borders:Ai()};l.push({kind:"blocks",blocks:[w]});continue}const g=await this.parseTextBoxContent(f,t);if(g.length>0)l.push({kind:"blocks",blocks:g});else{const w=this.rawChipFromRunChild(f);w&&l.push({kind:"blocks",blocks:[w]})}continue}}}return h(),l}static rawChipFromRunChild(e){try{return{type:"docx-raw",id:this.generateId(),origin:"run",...ir(e)}}catch{return}}static async parseTextBoxContent(e,r){const t=e.getElementsByTagName("w:txbxContent");if(t.length===0)return[];const i=Te(void 0).indentStepPx,n=[];for(let o=0;o<t.length;o++){const s=t[o];let a=s.parentElement,l=!1;for(;a&&a!==e;){if(a.tagName==="mc:Fallback"){const p=a.parentElement,h=p?Array.from(p.children).find(m=>m.tagName==="mc:Choice"):void 0;l=!!(h&&h.getElementsByTagName("w:txbxContent").length>0);break}a=a.parentElement}if(l)continue;const d=(await this.parseBodyChildren(s,i,r)).filter(p=>p.type!=="paragraph"||p.children.some(h=>h.type==="text"&&h.text.trim()!==""));n.push(...d)}return n}static selectAlternateContentBranch(e){let r;for(let t=0;t<e.children.length;t++){const i=e.children[t];if(i.tagName==="mc:Fallback"){r=i;continue}if(i.tagName==="mc:Choice"&&(i.getElementsByTagName("w:t").length>0||i.getElementsByTagName("w:delText").length>0||i.getElementsByTagName("w:txbxContent").length>0||i.getElementsByTagName("a:blip").length>0))return i}return r}static resolveRunMarks(e,r,t,i){const n={};if(t){const o=[];t.styles.runDefault&&o.push(t.styles.runDefault),o.push(...this.resolveStyleChainRPr(this.effectiveParagraphStyleId(r,t.styles),t.styles,"paragraph"));const s=e&&this.getDirectChild(e,"w:rStyle")?.getAttribute("w:val")||void 0;o.push(...this.resolveStyleChainRPr(s,t.styles,"character")),e&&o.push(e);for(const a of o)this.applyRunPropertiesFromElement(n,a,t.themeFonts);s===this.CODE_INLINE_STYLE_ID&&(n.code=!0,/courier/i.test(n.fontFamily??"")&&delete n.fontFamily,/^(light)?gray$/i.test(n.backgroundColor??"")&&delete n.backgroundColor)}else e&&this.applyRunPropertiesFromElement(n,e);return i&&(n.link=i),n}static applyRunPropertiesFromElement(e,r,t){if(!r)return;const i=(T,F)=>{this.getDirectChild(r,T)&&(e[F]=this.isOn(r,T))},n=()=>new Set(e.docxRunPropertyResets?.split(",").map(T=>T.trim()).filter(Boolean)??[]),o=(T,F)=>{const B=n();F?B.add(T):B.delete(T),B.size>0?e.docxRunPropertyResets=[...B].sort().join(","):delete e.docxRunPropertyResets};i("w:b","bold"),i("w:i","italic");const s=this.getDirectChild(r,"w:u");if(s){const T=(s.getAttribute("w:val")||"").toLowerCase();e.underline=!["none","0","false","off"].includes(T)}i("w:strike","strikethrough"),i("w:dstrike","doubleStrikethrough"),i("w:smallCaps","smallCaps"),i("w:caps","allCaps"),i("w:vanish","hidden");const a=this.getDirectChild(r,"w:lang")?.getAttribute("w:val");a&&(e.lang=a);const l=(this.getDirectChild(r,"w:spacing")?.getAttribute("w:val")||"").trim();if(l!==""){const T=parseInt(l,10);Number.isFinite(T)&&(e.letterSpacing=Math.round(T/15*100)/100)}const d=(this.getDirectChild(r,"w:vertAlign")?.getAttribute("w:val")||"").toLowerCase();d==="superscript"?(e.superscript=!0,e.subscript=!1):d==="subscript"?(e.superscript=!1,e.subscript=!0):d==="baseline"&&(e.superscript=!1,e.subscript=!1);const p=this.getDirectChild(r,"w:color"),h=p?.getAttribute("w:val");p&&h?.toLowerCase()==="auto"?(delete e.color,o("color",!0)):h&&(e.color=`#${h.replace(/^#/,"")}`,o("color",!1));const m=this.getDirectChild(r,"w:highlight")?.getAttribute("w:val");m?.toLowerCase()==="none"?(delete e.backgroundColor,o("highlight",!0)):m&&(e.backgroundColor=this.highlightValueToColor(m),o("highlight",!1));const f=this.getDirectChild(r,"w:shd")?.getAttribute("w:fill");if(f&&["auto","none"].includes(f.toLowerCase()))delete e.backgroundColor,o("highlight",!0);else if(f){const T=qt(f);T&&(e.backgroundColor=T,o("highlight",!1))}const b=this.getDirectChild(r,"w:rFonts"),u=b?.getAttribute("w:asciiTheme")||b?.getAttribute("w:hAnsiTheme")||b?.getAttribute("w:cstheme")||b?.getAttribute("w:eastAsiaTheme"),g=u&&t?u.toLowerCase().startsWith("major")?t.major:t.minor:void 0,w=b?.getAttribute("w:ascii")||b?.getAttribute("w:hAnsi")||b?.getAttribute("w:cs")||b?.getAttribute("w:eastAsia")||g;w&&(e.fontFamily=w);const S=this.getDirectChild(r,"w:sz")?.getAttribute("w:val");if(S){const T=parseInt(S,10);Number.isFinite(T)&&T>0&&(e.fontSize=Math.max(1,Math.round(T*(2/3)*100)/100))}}static inferDefaultRunSizeHalfPoints(e){const r=e.stylesheet?.paragraphStyles.find(t=>t.default)?.runMarks?.fontSize;return typeof r=="number"&&r>0&&r!==ke.paragraph?this.DEFAULT_RUN_SIZE_HALF_POINTS:void 0}static docDefaultRunSizePx(e){const r=e?.styles.runDefault;if(!r)return;const t=this.getDirectChild(r,"w:sz")?.getAttribute("w:val"),i=t?parseInt(t,10):NaN;return Number.isFinite(i)&&i>0?Math.max(1,Math.round(i*(2/3)*100)/100):void 0}static isOnAttribute(e){const r=(e||"").trim().toLowerCase();return r==="1"||r==="true"||r==="on"}static isOn(e,r){const t=this.getDirectChild(e,r);if(!t)return!1;const i=(t.getAttribute("w:val")||"").toLowerCase();return i!=="false"&&i!=="0"&&i!=="off"}static async parseImageFromDrawing(e,r,t){if(!t)return null;const i=e.getElementsByTagName("a:blip")[0],n=i?.getAttribute("r:embed")||i?.getAttribute("r:link")||"";if(!n)return null;const o=t.relationships.get(n);if(!o)return null;const s=i?this.findSvgBlipRelationshipId(i):void 0;let a,l;if(s){const F=t.relationships.get(s),B=F?t.zip.file(F.target):void 0;B&&(a=await B.async("uint8array"),l="image/svg+xml")}if(!a||!l){const F=t.zip.file(o.target);if(!F)return null;a=await F.async("uint8array"),l=this.getContentTypeForPart(o.target,t.contentTypes)||this.inferImagePartMimeType(o.target)}if(!a)return null;const d=l?this.vectorFormatForMimeType(l):void 0;if(!d&&(!l||!this.isSupportedImageMimeType(l)))return null;const p=e.getElementsByTagName("wp:extent")[0]||e.getElementsByTagName("a:ext")[0],h=p?.getAttribute("cx"),m=p?.getAttribute("cy"),f=h?Math.max(1,Math.round(parseInt(h,10)/9525)):200,b=m?Math.max(1,Math.round(parseInt(m,10)/9525)):200,u=e.getElementsByTagName("wp:docPr")[0],g=u?.getAttribute("descr")||u?.getAttribute("title")||u?.getAttribute("name")||void 0,w=this.buildImageDataUrl(a,d?d==="emf"?"image/x-emf":"image/x-wmf":l),S={type:"image",id:this.generateId(),src:w,width:f,height:b,alt:g,align:r&&r!=="justify"?r:void 0};d&&(S.originalFormat=d,S.originalDataUrl=w);const T=this.getDirectChild(e,"wp:anchor");if(T)try{S.anchorXml=this.serializeXmlPreservingPrefixes(T)}catch{}return S}static findSvgBlipRelationshipId(e){const r=e.getElementsByTagName("*");for(let t=0;t<r.length;t++){const i=r[t],n=i.tagName||"";if(n==="svgBlip"||n.endsWith(":svgBlip"))return i.getAttribute("r:embed")||i.getAttribute("r:link")||void 0}}static inferImagePartMimeType(e){const r=e.split(".").pop()?.toLowerCase();switch(r){case"svg":return"image/svg+xml";case"emf":return"image/x-emf";case"wmf":return"image/x-wmf";default:return r?this.inferMimeTypeFromPath(e):void 0}}static vectorFormatForMimeType(e){const r=e.toLowerCase();if(r==="image/x-emf"||r==="image/emf")return"emf";if(r==="image/x-wmf"||r==="image/wmf")return"wmf"}static async parseTableBlock(e,r,t){const i=[],n=[],o=[],s=(I,_)=>{for(const j of Array.from(I.children))if(j.tagName==="w:tr")_&&_.trIndexes.push(n.length),n.push(j);else if(j.tagName==="w:sdt"){const q=this.getDirectChild(j,"w:sdtContent");if(q){let Z=_;if(this.importSdtWrappers&&!_){const we=this.getDirectChild(j,"w:sdtPr");if(we)try{Z={prXml:new XMLSerializer().serializeToString(we),trIndexes:[]},o.push(Z)}catch{Z=_}}s(q,Z)}}};s(e);const a=this.getDirectChild(e,"w:tblPr"),l=a?this.getDirectChild(a,"w:tblCellMar"):void 0,d=l?this.nonUniformCellMarginJson(l):void 0,p=this.getDirectChild(e,"w:tblGrid"),h=p?this.getDirectChild(p,"w:tblGridChange"):void 0,m=h?this.getDirectChild(h,"w:tblGrid"):void 0,f=I=>{if(!I)return[];const _=[];for(const j of Array.from(I.children)){if(j.tagName!=="w:gridCol")continue;const q=Number(j.getAttribute("w:w"));Number.isFinite(q)&&q>0&&_.push(q)}return _},b=I=>{const _=f(I),j=_.reduce((q,Z)=>q+Z,0);return j>0?_.map(q=>Math.round(q/j*100)):[]},u=[],g=[],w=[],S=[],T=[],F=[],B=[],P=a?this.getDirectChild(a,"w:tblPrChange"):void 0,z=P?this.getDirectChild(P,"w:tblPr"):void 0,E=P?this.parseTrackedRevisionMeta(P):null;let G;if(z)try{G=new XMLSerializer().serializeToString(z)}catch{G=void 0}const $=new Map,v=new Map,D=[];for(let I=0;I<n.length;I++){const _=n[I],j=this.generateId(),q=this.getDirectChild(_,"w:tblPrEx"),Z=q?this.getDirectChild(q,"w:tblPrExChange"):void 0,we=Z?this.getDirectChild(Z,"w:tblPrEx"):void 0,ae=this.getDirectChild(_,"w:trPr"),ye=ae?this.getDirectChild(ae,"w:ins"):void 0,ve=ae?this.getDirectChild(ae,"w:del"):void 0,ge=ae?this.getDirectChild(ae,"w:trPrChange"):void 0,Ve=ge?this.getDirectChild(ge,"w:trPr"):void 0;if(ye){const Pe=this.parseTrackedRevisionMeta(ye);u.push({rowId:j,kind:"insert",...Pe})}else if(ve){const Pe=this.parseTrackedRevisionMeta(ve);u.push({rowId:j,kind:"delete",...Pe})}ae&&ge&&Ve&&g.push({rowId:j,rowIndex:I,...this.parseTrackedRevisionMeta(ge),currentXml:this.serializePropertiesWithoutRevisionChildren(ae,new Set(["w:ins","w:del","w:trPrChange"])),priorXml:new XMLSerializer().serializeToString(Ve),...I===0?{currentTableAttributes:this.tableHeaderAttributesFromRowProperties(ae),priorTableAttributes:this.tableHeaderAttributesFromRowProperties(Ve)}:{}}),q&&Z&&we&&w.push({rowId:j,rowIndex:I,...this.parseTrackedRevisionMeta(Z),currentXml:this.serializePropertiesWithoutRevisionChildren(q,new Set(["w:tblPrExChange"])),priorXml:new XMLSerializer().serializeToString(we)});const te=[];let me=0;const Se=[];for(let Pe=0;Pe<_.children.length;Pe++){const Ce=_.children[Pe];if(Ce.tagName==="w:tc")Se.push({el:Ce});else if(Ce.tagName==="w:sdt"){const se=this.getDirectChild(Ce,"w:sdtContent");if(!se)continue;let Ee;if(this.importSdtWrappers){const Oe=this.getDirectChild(Ce,"w:sdtPr");if(Oe)try{Ee={prXml:new XMLSerializer().serializeToString(Oe),cellIds:[]},D.push(Ee)}catch{Ee=void 0}}for(const Oe of Array.from(se.children))Oe.tagName==="w:tc"&&Se.push({el:Oe,sdtGroup:Ee})}}for(let Pe=0;Pe<Se.length;Pe++){const Ce=Se[Pe].el,se=this.getDirectChild(Ce,"w:tcPr"),Ee=this.getDirectChild(se||Ce,"w:shd")?.getAttribute("w:fill"),Oe=se?this.getDirectChild(se,"w:gridSpan")?.getAttribute("w:val"):void 0,Me=Oe?parseInt(Oe,10):1,Ge=Number.isFinite(Me)?Math.min(Math.max(1,Me),1e3):1,Ye=se?this.getDirectChild(se,"w:cellIns"):void 0,Qe=se?this.getDirectChild(se,"w:cellDel"):void 0,le=se?this.getDirectChild(se,"w:cellMerge"):void 0,$e=se?this.getDirectChild(se,"w:tcPrChange"):void 0,Je=$e?this.getDirectChild($e,"w:tcPr"):void 0,be={type:"table-cell",id:this.generateId(),backgroundColor:Ee&&Ee.toLowerCase()!=="auto"&&Ee.toLowerCase()!=="none"?`#${Ee.replace(/^#/,"")}`:void 0,children:await this.parseBodyChildren(Ce,r,t)};Ge>1&&(be.colSpan=Ge);const Pt=rt(se,Lr);Pt&&(be.oxmlTcPr=Pt);const Ct=se?this.getDirectChild(se,"w:tcBorders"):void 0,et=Ct?this.parseDocxBordersElement(Ct,!1):void 0;et&&(be.borders=et);const kt=se?this.getDirectChild(se,"w:tcMar"):void 0,ot=(kt?this.parseDocxCellMargins(kt):void 0)??d;ot&&(be.padding=ot);const Ue=se?this.getDirectChild(se,"w:vAlign")?.getAttribute("w:val"):void 0;(Ue==="top"||Ue==="center"||Ue==="bottom")&&(be.verticalAlign=Ue==="center"?"middle":Ue),le&&F.push({rowId:j,gridColumn:me,...this.parseTrackedRevisionMeta(le),...le.getAttribute("w:vMerge")?{vMerge:le.getAttribute("w:vMerge")}:{},...le.getAttribute("w:vMergeOrig")?{vMergeOrig:le.getAttribute("w:vMergeOrig")}:{}});const tt=se?this.getDirectChild(se,"w:vMerge"):void 0,gt=tt?.getAttribute("w:val");if(tt&>!=="restart"){const De=$.get(me);if(De){if(De.cell.rowSpan=(De.cell.rowSpan??1)+1,le){const Ze=this.parseTrackedRevisionMeta(le);B.push({row:I,pos:te.length,colSpan:Ge,anchorRow:De.rowIndex,anchorPos:De.cellPos,rowId:j,gridColumn:me,restoredCellId:be.id,restoredCell:JSON.parse(JSON.stringify(be)),direction:"merge",...Ze,...le.getAttribute("w:vMerge")?{vMerge:le.getAttribute("w:vMerge")}:{},...le.getAttribute("w:vMergeOrig")?{vMergeOrig:le.getAttribute("w:vMergeOrig")}:{}})}me+=Ge;continue}}tt&>==="restart"?$.set(me,{cell:be,rowIndex:I,cellPos:te.length}):$.delete(me);const st=le?.hasAttribute("w:vMergeOrig")?le.getAttribute("w:vMergeOrig"):tt?gt??"continue":void 0,at=st==="restart"||st==="rest",lt=st==="continue"||st==="cont";if(at)v.set(me,{cell:be,rowIndex:I,cellPos:te.length});else if(lt){const De=v.get(me);if(De&&le&&!tt){const Ze=this.parseTrackedRevisionMeta(le);B.push({row:I,pos:te.length,colSpan:Ge,anchorRow:De.rowIndex,anchorPos:De.cellPos,rowId:j,gridColumn:me,restoredCellId:be.id,restoredCell:JSON.parse(JSON.stringify(be)),direction:"unmerge",...Ze,...le.getAttribute("w:vMerge")?{vMerge:le.getAttribute("w:vMerge")}:{},...le.getAttribute("w:vMergeOrig")?{vMergeOrig:le.getAttribute("w:vMergeOrig")}:{}})}}else v.delete(me);Ye&&S.push({cellId:be.id,kind:"insert",...this.parseTrackedRevisionMeta(Ye)}),Qe&&S.push({cellId:be.id,kind:"delete",...this.parseTrackedRevisionMeta(Qe)}),$e&&Je&&T.push({rowId:j,cellId:be.id,rowIndex:I,cellIndex:te.length,gridColumn:me,...this.parseTrackedRevisionMeta($e),currentXml:this.serializePropertiesWithoutRevisionChildren(se,new Set(["w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"])),priorXml:new XMLSerializer().serializeToString(Je),currentAttributes:this.tableCellAttributesFromProperties(se),priorAttributes:this.tableCellAttributesFromProperties(Je)}),Se[Pe].sdtGroup?.cellIds.push(be.id),te.push(be),me+=Ge}const Be={type:"table-row",id:j,children:te},Ie=tr(_);Ie&&(Be.oxmlAttrs=Ie);const nt=rt(ae,$r);nt&&(Be.oxmlTrPr=nt),i.push(Be)}if(i.length===0)return null;if(this.importSdtWrappers){const I=this.sdtAncestorStack[this.sdtAncestorStack.length-1];for(const _ of o){const j=_.trIndexes.map(q=>i[q]?.id).filter(q=>!!q);j.length>0&&this.importSdtWrappers.push({id:this.generateId(),prXml:_.prXml,scope:"row",...I?{parentId:I.id}:{},blockIds:j})}for(const _ of D)_.cellIds.length>0&&this.importSdtWrappers.push({id:this.generateId(),prXml:_.prXml,scope:"cell",...I?{parentId:I.id}:{},blockIds:[..._.cellIds]})}const M=b(p),x=n[0]?this.getDirectChild(n[0],"w:trPr"):void 0,R=x?this.tableHeaderAttributesFromRowProperties(x).hasHeader===!0:!1,X=this.generateId(),L=new Map,W=(I,_,j)=>{const q=I.revisionId?`docxrev-${I.revisionId}`:this.generateId(),Z=L.get(q);if(Z)return Z;const we=this.revisionAuthorIdentity(I.author),ae={id:q,type:"table-change",tableId:X,source:we.suggestionSource,authorType:we.suggestionAuthorType,label:_,...I.createdAt!==void 0?{createdAt:I.createdAt}:{},...I.author?{agentName:I.author}:{},tableRevision:{version:1,suggestionKind:j,markers:[],operations:[]}};return L.set(q,ae),ae};if(p&&h&&m){const I=this.parseTrackedRevisionMeta(h),_=this.serializePropertiesWithoutRevisionChildren(p,new Set(["w:tblGridChange"])),j=new XMLSerializer().serializeToString(m),q=b(p),Z=b(m),we=W(I,"Change table column widths","format");we.tableRevision.markers.push({kind:"table-grid",revisionId:I.revisionId,author:I.author,createdAt:I.createdAt,currentPropertiesXml:_,priorPropertiesXml:j,currentColumnWidths:q,priorColumnWidths:Z}),we.tableRevision.operations.push({kind:"grid",currentGridXml:_,priorGridXml:j,currentColumnWidths:q,priorColumnWidths:Z})}for(const I of u){const _=i.findIndex(Z=>Z.id===I.rowId),j=i[_];if(!j)continue;const q=W(I,I.kind==="insert"?"Insert table row":"Delete table row",I.kind);q.tableRevision.markers.push({kind:I.kind==="insert"?"row-insert":"row-delete",rowId:I.rowId,rowIndex:_,revisionId:I.revisionId,author:I.author,createdAt:I.createdAt}),q.tableRevision.operations.push({kind:"row",action:I.kind,rowId:I.rowId,rowIndex:_,row:JSON.parse(JSON.stringify(j))}),j.diffState=I.kind,j.suggestionId=q.id}for(const I of S){let _=-1,j=-1,q,Z;for(let ye=0;ye<i.length&&!Z;ye++){const ve=i[ye].children.findIndex(ge=>ge.id===I.cellId);ve>=0&&(_=ye,j=ve,q=i[ye],Z=q.children[ve])}if(!q||!Z)continue;const we=qe({children:i,columnWidths:M}).byId.get(Z.id),ae=W(I,I.kind==="insert"?"Insert table cell":"Delete table cell",I.kind);ae.tableRevision.markers.push({kind:I.kind==="insert"?"cell-insert":"cell-delete",rowId:q.id,cellId:Z.id,rowIndex:_,cellIndex:j,gridColumn:we?.col,revisionId:I.revisionId,author:I.author,createdAt:I.createdAt}),ae.tableRevision.operations.push({kind:"cell",action:I.kind,rowId:q.id,cellId:Z.id,cellIndex:j,cell:JSON.parse(JSON.stringify(Z))}),Z.diffState=I.kind,Z.suggestionId=ae.id}for(const I of g){const _=W(I,"Change table row properties","format");_.tableRevision.markers.push({kind:"row-properties",rowId:I.rowId,rowIndex:I.rowIndex,revisionId:I.revisionId,author:I.author,createdAt:I.createdAt,currentPropertiesXml:I.currentXml,priorPropertiesXml:I.priorXml}),_.tableRevision.operations.push({kind:"properties",target:"row",rowId:I.rowId,currentPropertiesXml:I.currentXml,priorPropertiesXml:I.priorXml,currentTableAttributes:I.currentTableAttributes,priorTableAttributes:I.priorTableAttributes})}for(const I of w){const _=W(I,"Change row table-style exceptions","format");_.tableRevision.markers.push({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}),_.tableRevision.operations.push({kind:"properties",target:"row-exception",rowId:I.rowId,currentPropertiesXml:I.currentXml,priorPropertiesXml:I.priorXml})}for(const I of T){const _=W(I,"Change table cell properties","format");_.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.createdAt,currentPropertiesXml:I.currentXml,priorPropertiesXml:I.priorXml}),_.tableRevision.operations.push({kind:"properties",target:"cell",rowId:I.rowId,cellId:I.cellId,currentPropertiesXml:I.currentXml,priorPropertiesXml:I.priorXml,currentAttributes:I.currentAttributes,priorAttributes:I.priorAttributes})}const U=new Map;for(const I of B){const _=I.revisionId?`docxrev-${I.revisionId}`:this.generateId(),j=U.get(_)??[];j.push(I),U.set(_,j)}for(const[I,_]of U){const j=_[0],q={revisionId:j.revisionId,author:j.author,createdAt:j.createdAt},Z=W(q,_.every(te=>te.direction==="unmerge")?"Split table cells":"Merge table cells","format");Z.id!==I&&!L.has(I)&&(L.delete(Z.id),Z.id=I,L.set(I,Z));const we=j.revisionId?F.filter(te=>te.revisionId===j.revisionId):_;for(const te of we)Z.tableRevision.markers.push({kind:"cell-merge",rowId:te.rowId,gridColumn:te.gridColumn,revisionId:te.revisionId,author:te.author,createdAt:te.createdAt,vMerge:te.vMerge,vMergeOrig:te.vMergeOrig});const ae=JSON.parse(JSON.stringify(i)),ye=new Map,ve=new Set;for(const te of _){const me=ae[te.anchorRow]?.children[te.anchorPos],Se=ae[te.row];if(te.direction==="merge"){if(me?.rowSpan!==void 0){const Ie=me.rowSpan-1;Ie>1?me.rowSpan=Ie:delete me.rowSpan}if(Se){const Ie=ye.get(te.row)??0;Se.children.splice(te.pos+Ie,0,JSON.parse(JSON.stringify(te.restoredCell))),ye.set(te.row,Ie+1)}}else if(me&&(me.rowSpan=(me.rowSpan??1)+1),Se){const Ie=Se.children.findIndex(nt=>nt.id===te.restoredCellId);Ie>=0&&Se.children.splice(Ie,1)}Se&&ve.add(Se.id);const Be=ae[te.anchorRow];Be&&ve.add(Be.id)}const ge=i.filter(te=>ve.has(te.id)).map(te=>JSON.parse(JSON.stringify(te))),Ve=ae.filter(te=>ve.has(te.id));Z.tableRevision.operations.push({kind:"geometry",pendingRows:ge,acceptedRows:JSON.parse(JSON.stringify(ge)),rejectedRows:Ve})}if(E&&a&&z){const I=W(E,"Change table properties","format"),_=this.serializePropertiesWithoutRevisionChildren(a,new Set(["w:tblPrChange"])),j=G??new XMLSerializer().serializeToString(z);I.tableRevision.markers.push({kind:"table-properties",revisionId:E.revisionId,author:E.author,createdAt:E.createdAt,currentPropertiesXml:_,priorPropertiesXml:j}),I.tableRevision.operations.push({kind:"properties",target:"table",currentPropertiesXml:_,priorPropertiesXml:j,currentAttributes:{...this.tableAttributesFromProperties(a,t)},priorAttributes:{...this.tableAttributesFromProperties(z,t)}})}const J=Array.from(L.values()),ee=this.tableAttributesFromProperties(a,t);return{type:"table",id:X,...J.length>0?{structuralSuggestionRecords:JSON.stringify(J)}:{},children:i,columnWidths:M,...ee,...R?{hasHeader:!0}:{},...(()=>{const I=rt(a,Or);return I?{oxmlTblPr:I}:{}})()}}static serializePropertiesWithoutRevisionChildren(e,r){const t=e.cloneNode(!0);for(const i of Array.from(t.children))r.has(i.tagName)&&i.remove();return new XMLSerializer().serializeToString(t)}static tableCellAttributesFromProperties(e){const r={},t=this.getDirectChild(e,"w:shd")?.getAttribute("w:fill");t&&t.toLowerCase()!=="auto"&&t.toLowerCase()!=="none"&&(r.backgroundColor=`#${t.replace(/^#/,"")}`);const i=this.getDirectChild(e,"w:tcBorders"),n=i?this.parseDocxBordersElement(i,!1):void 0;n&&(r.borders=n);const o=this.getDirectChild(e,"w:tcMar"),s=o?this.parseDocxCellMargins(o):void 0;s&&(r.padding=s);const a=this.getDirectChild(e,"w:gridSpan")?.getAttribute("w:val"),l=a?Number(a):void 0;l&&Number.isFinite(l)&&l>1&&(r.colSpan=l);const d=this.getDirectChild(e,"w:vAlign")?.getAttribute("w:val");return(d==="top"||d==="center"||d==="bottom")&&(r.verticalAlign=d==="center"?"middle":d),r}static tableHeaderAttributesFromRowProperties(e){const r=this.getDirectChild(e,"w:tblHeader");if(!r)return{};const t=r.getAttribute("w:val")?.trim().toLowerCase();return t==="0"||t==="false"||t==="off"||t==="no"?{}:{hasHeader:!0}}static tableAttributesFromProperties(e,r){const t={};if(t.borders=this.resolveTableBordersJson(e,r),!e)return t;const i=this.getDirectChild(e,"w:jc")?.getAttribute("w:val");i==="center"||i==="right"?t.align=i:i==="left"||i==="start"?t.align="left":i==="end"&&(t.align="right");const n=this.getDirectChild(e,"w:tblW"),o=n?.getAttribute("w:type"),s=Number(n?.getAttribute("w:w"));o==="dxa"&&Number.isFinite(s)&&s>0&&(t.tableWidth=Math.round(s/15));const a=this.getDirectChild(e,"w:tblCellMar"),l=a?this.parseDocxCellMargins(a):void 0;if(l)try{const d=JSON.parse(l),p=[d.top,d.right,d.bottom,d.left];p.every(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"nil":return"none";case"dotted":return"dotted";case"dashed":case"dashSmallGap":case"dashDotStroked":case"dotDash":case"dotDotDash":return"dashed";case"double":case"triple":case"doubleWave":return"double";default:return"single"}}static parseDocxBordersElement(e,r){return Ar(this.parseDocxBordersSpec(e,r))}static resolveTableBordersJson(e,r){const t={},i=a=>{a&&Object.assign(t,this.parseDocxBordersSpec(a,!0))},n=r?.styles;if(n){const a=(e&&this.getDirectChild(e,"w:tblStyle")?.getAttribute("w:val")||void 0)??n.defaultStyleIdByType?.get("table"),l=a?this.resolveStyleChain(a,n,"table"):[];for(const d of l)i(d.tblPr?this.getDirectChild(d.tblPr,"w:tblBorders"):void 0)}i(e?this.getDirectChild(e,"w:tblBorders"):void 0);const o={style:"none",width:0,color:"#000000"},s={top:t.top??o,bottom:t.bottom??o,left:t.left??o,right:t.right??o,insideH:t.insideH??o,insideV:t.insideV??o};return Ar(s)}static parseDocxBordersSpec(e,r){const t=(...l)=>{let d;for(const g of l)if(d=this.getDirectChild(e,g),d)break;if(!d)return;const p=this.mapDocxBorderStyle(d.getAttribute("w:val")),h=parseInt(d.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)/100):1,b=(d.getAttribute("w:color")||"").trim(),u=b&&b.toLowerCase()!=="auto"?`#${b.replace(/^#/,"").toLowerCase()}`:"#000000";return{style:m,width:f,color:u}},i={},n=t("w:top"),o=t("w:bottom"),s=t("w:left","w:start"),a=t("w:right","w:end");if(n&&(i.top=n),o&&(i.bottom=o),s&&(i.left=s),a&&(i.right=a),r){const l=t("w:insideH"),d=t("w:insideV");l&&(i.insideH=l),d&&(i.insideV=d)}return i}static nonUniformCellMarginJson(e){const r=this.parseDocxCellMargins(e);if(r){try{const t=JSON.parse(r),i=[t.top,t.right,t.bottom,t.left];if(i.every(n=>Number.isFinite(n))&&i.every(n=>n===i[0]))return}catch{return}return r}}static parseDocxCellMargins(e){const r=(...s)=>{let a;for(const d of s)if(a=this.getDirectChild(e,d),a)break;if(!a)return;const l=parseInt(a.getAttribute("w:w")||"",10);if(!(!Number.isFinite(l)||l<0))return Math.round(l/15*100)/100},t=r("w:top"),i=r("w:bottom"),n=r("w:left","w:start"),o=r("w:right","w:end");if(!(t===void 0&&i===void 0&&n===void 0&&o===void 0))return Ni({top:t??0,bottom:i??0,left:n??7.2,right:o??7.2})}static getContentTypeForPart(e,r){const t=r.get(e);if(t)return t;const i=e.split(".").pop()?.toLowerCase();return i?r.get(i):void 0}static isSupportedImageMimeType(e){return e==="image/png"||e==="image/jpeg"||e==="image/jpg"||e==="image/gif"||e==="image/bmp"||e==="image/svg+xml"}static buildImageDataUrl(e,r){return`data:${r};base64,${this.uint8ArrayToBase64(e)}`}static uint8ArrayToBase64(e){if(typeof Buffer<"u")return Buffer.from(e).toString("base64");let r="";const t=32768;for(let i=0;i<e.length;i+=t){const n=e.subarray(i,i+t);r+=String.fromCharCode(...n)}return btoa(r)}static createEmptyParagraph(){return{type:"paragraph",id:this.generateId(),children:[{type:"text",text:"",marks:{}}]}}static createPageBreakBlock(){return{type:"page-break",id:this.generateId()}}static generateId(){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";let r="";for(let t=0;t<6;t++)r+=e.charAt(Math.floor(Math.random()*e.length));return r}static ommlToLatex(e){try{return this.parseOmmlElement(e)}catch(r){return console.warn("Failed to convert OMML to LaTeX:",r),""}}static parseOmmlElement(e){const r=e.tagName;switch(r){case"m:oMathPara":case"m:oMath":return this.parseOmmlChildren(e);case"m:r":{const t=e.getElementsByTagName("m:t")[0];if(!t)return"";const i=(t.textContent||"").replace(/\u200B/g,""),n=e.getElementsByTagName("m:rPr")[0];if(n?.getElementsByTagName("m:nor")[0]){const d=i.replace(/\u00a0/g," "),p={"\\":"\\textbackslash{}","{":"\\{","}":"\\}","&":"\\&","%":"\\%",$:"\\$","#":"\\#",_:"\\_","^":"\\textasciicircum{}","~":"\\textasciitilde{}"};return`\\text{${d.replace(/[\\{}&%$#_^~]/g,h=>p[h])}}`}const o=this.cleanMathText(i),s=n?.getElementsByTagName("m:scr")[0]?.getAttribute("m:val"),a=n?.getElementsByTagName("m:sty")[0]?.getAttribute("m:val"),l={"double-struck":"\\mathbb",script:"\\mathcal",fraktur:"\\mathfrak","sans-serif":"\\mathsf",monospace:"\\mathtt"};return s&&l[s]?`${l[s]}{${o}}`:a==="b"||a==="bi"?`\\mathbf{${o}}`:a==="p"&&/^[A-Za-z]+$/.test(i)?ar.OMML_FUNCTION_NAMES.includes(i)?`\\${i} `:`\\mathrm{${i}}`:o}case"m:sSub":{const t=e.getElementsByTagName("m:e")[0],i=e.getElementsByTagName("m:sub")[0],n=t?this.parseOmmlChildren(t):"",o=i?this.parseOmmlChildren(i):"";return`${n}_{${o}}`}case"m:sSup":{const t=e.getElementsByTagName("m:e")[0],i=e.getElementsByTagName("m:sup")[0],n=t?this.parseOmmlChildren(t):"",o=i?this.parseOmmlChildren(i):"";return`${n}^{${o}}`}case"m:sSubSup":{const t=e.getElementsByTagName("m:e")[0],i=e.getElementsByTagName("m:sub")[0],n=e.getElementsByTagName("m:sup")[0],o=t?this.parseOmmlChildren(t):"",s=i?this.parseOmmlChildren(i):"",a=n?this.parseOmmlChildren(n):"";return`${o}_{${s}}^{${a}}`}case"m:f":{const t=e.getElementsByTagName("m:num")[0],i=e.getElementsByTagName("m:den")[0],n=t?this.parseOmmlChildren(t):"",o=i?this.parseOmmlChildren(i):"";return e.getElementsByTagName("m:fPr")[0]?.getElementsByTagName("m:type")[0]?.getAttribute("m:val")==="noBar"?`{${n} \\atop ${o}}`:`\\frac{${n}}{${o}}`}case"m:rad":{const t=e.getElementsByTagName("m:deg")[0],i=e.getElementsByTagName("m:e")[0],n=t?this.parseOmmlChildren(t).trim():"",o=i?this.parseOmmlChildren(i):"";return n&&n!=="2"?`\\sqrt[${n}]{${o}}`:`\\sqrt{${o}}`}case"m:nary":{const t=e.getElementsByTagName("m:naryPr")[0],i=e.getElementsByTagName("m:sub")[0],n=e.getElementsByTagName("m:sup")[0],o=e.getElementsByTagName("m:e")[0];let s="\\sum";if(t){const h=t.getElementsByTagName("m:chr")[0]?.getAttribute("m:val");h&&(s={"∑":"\\sum","∏":"\\prod","∫":"\\int","∬":"\\iint","∭":"\\iiint","∮":"\\oint","⋃":"\\bigcup","⋂":"\\bigcap"}[h]||"\\sum")}const a=i?this.parseOmmlChildren(i):"",l=n?this.parseOmmlChildren(n):"",d=o?this.parseOmmlChildren(o):"";let p=s;return a&&(p+=`_{${a}}`),l&&(p+=`^{${l}}`),p+=` ${d}`,p}case"m:d":{const t=e.getElementsByTagName("m:dPr")[0],i=e.getElementsByTagName("m:e")[0];let n="(",o=")";if(t){const l=t.getElementsByTagName("m:begChr")[0],d=t.getElementsByTagName("m:endChr")[0];l?.hasAttribute("m:val")&&(n=l.getAttribute("m:val")??""),d?.hasAttribute("m:val")&&(o=d.getAttribute("m:val")??"")}const s=l=>({"":".","{":"\\{","}":"\\}","⟨":"\\langle","⟩":"\\rangle","‖":"\\|","∥":"\\|","∣":"|","⌊":"\\lfloor","⌋":"\\rfloor","⌈":"\\lceil","⌉":"\\rceil"})[l]??l,a=i?this.parseOmmlChildren(i):"";return`\\left${s(n)}${a}\\right${s(o)}`}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 o=Array.from(t[n].children).filter(a=>a.tagName==="m:e"),s=[];for(let a=0;a<o.length;a++)s.push(this.parseOmmlChildren(o[a]));i+=s.join(" & "),n<t.length-1&&(i+=" \\\\ ")}return i+="\\end{matrix}",i}case"m:bar":{const t=e.getElementsByTagName("m:e")[0],i=t?this.parseOmmlChildren(t):"";return e.getElementsByTagName("m:barPr")[0]?.getElementsByTagName("m:pos")[0]?.getAttribute("m:val")==="bot"?`\\underline{${i}}`:`\\overline{${i}}`}case"m:acc":{const t=e.getElementsByTagName("m:accPr")[0],i=e.getElementsByTagName("m:e")[0],n=i?this.parseOmmlChildren(i):"";let o="\\hat";if(t){const s=t.getElementsByTagName("m:chr")[0]?.getAttribute("m:val");s&&(o={"̂":"\\hat","~":"\\tilde","̃":"\\tilde","̌":"\\check","̆":"\\breve","́":"\\acute","̀":"\\grave","̇":"\\dot","̈":"\\ddot","̄":"\\bar","⃗":"\\vec"}[s]||"\\hat")}return`${o}{${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):"",o=i?this.parseOmmlChildren(i):"";return r==="m:limLow"?`${n}_{${o}}`:`${n}^{${o}}`}case"m:borderBox":{const t=Array.from(e.children).find(i=>i.tagName==="m:e");return`\\boxed{${t?this.parseOmmlChildren(t):""}}`}case"m:groupChr":{const t=e.getElementsByTagName("m:e")[0],i=t?this.parseOmmlChildren(t):"",n=e.getElementsByTagName("m:groupChrPr")[0],o=n?.getElementsByTagName("m:chr")[0]?.getAttribute("m:val");return n?.getElementsByTagName("m:pos")[0]?.getAttribute("m:val")!=="top"&&o!=="⏞"?`\\underbrace{${i}}`:`\\overbrace{${i}}`}case"m:func":{const t=Array.from(e.children).find(l=>l.tagName==="m:fName"),i=Array.from(e.children).find(l=>l.tagName==="m:e"),n=t?Array.from(t.children).find(l=>l.tagName==="m:limLow"):void 0;if(n){const l=Array.from(n.children).find(b=>b.tagName==="m:e"),d=Array.from(n.children).find(b=>b.tagName==="m:lim"),p=(l?.textContent??"").trim(),h=i?this.parseOmmlChildren(i):"",m=d?this.parseOmmlChildren(d):"",f=/^[A-Za-z]+$/.test(p)?`\\operatorname*{${p}}`:p;return`${["lim","max","min","sup","inf","liminf","limsup"].includes(p)?`\\${p}`:f}_{${m}} ${h}`}const o=(t?.textContent??"").trim(),s=i?this.parseOmmlChildren(i):"",a=ar.OMML_FUNCTION_NAMES;return a.includes(o)?`\\${o}{${s}}`:a.includes(o.toLowerCase())?`\\${o.toLowerCase()}{${s}}`:/^[A-Za-z]+$/.test(o)?`\\operatorname{${o}}{${s}}`:`${o}(${s})`}default:return this.parseOmmlChildren(e)}}static parseOmmlChildren(e){let r="";for(let t=0;t<e.children.length;t++){const i=e.children[t];i.tagName.endsWith("Pr")||i.tagName==="m:ctrlPr"||i.tagName==="m:t"||(r+=this.parseOmmlElement(i))}return r}static cleanMathText(e){const r={"𝐴":"A","𝐵":"B","𝐶":"C","𝐷":"D","𝐸":"E","𝐹":"F","𝐺":"G","𝐻":"H","𝐼":"I","𝐽":"J","𝐾":"K","𝐿":"L","𝑀":"M","𝑁":"N","𝑂":"O","𝑃":"P","𝑄":"Q","𝑅":"R","𝑆":"S","𝑇":"T","𝑈":"U","𝑉":"V","𝑊":"W","𝑋":"X","𝑌":"Y","𝑍":"Z","𝑎":"a","𝑏":"b","𝑐":"c","𝑑":"d","𝑒":"e","𝑓":"f","𝑔":"g",ℎ:"h","𝑖":"i","𝑗":"j","𝑘":"k","𝑙":"l","𝑚":"m","𝑛":"n","𝑜":"o","𝑝":"p","𝑞":"q","𝑟":"r","𝑠":"s","𝑡":"t","𝑢":"u","𝑣":"v","𝑤":"w","𝑥":"x","𝑦":"y","𝑧":"z",α:"\\alpha",β:"\\beta",γ:"\\gamma",δ:"\\delta",ε:"\\epsilon",ζ:"\\zeta",η:"\\eta",θ:"\\theta",ι:"\\iota",κ:"\\kappa",λ:"\\lambda",μ:"\\mu",ν:"\\nu",ξ:"\\xi",π:"\\pi",ρ:"\\rho",σ:"\\sigma",τ:"\\tau",υ:"\\upsilon",φ:"\\phi",χ:"\\chi",ψ:"\\psi",ω:"\\omega",Γ:"\\Gamma",Δ:"\\Delta",Θ:"\\Theta",Λ:"\\Lambda",Ξ:"\\Xi",Π:"\\Pi",Σ:"\\Sigma",Φ:"\\Phi",Ψ:"\\Psi",Ω:"\\Omega","∞":"\\infty","∂":"\\partial","∇":"\\nabla","±":"\\pm","∓":"\\mp","×":"\\times","÷":"\\div","≠":"\\neq","≈":"\\approx","≤":"\\leq","≥":"\\geq","∈":"\\in","∉":"\\notin","⊂":"\\subset","⊃":"\\supset","∪":"\\cup","∩":"\\cap","→":"\\rightarrow","←":"\\leftarrow","⇒":"\\Rightarrow","⇐":"\\Leftarrow","⇔":"\\Leftrightarrow","∀":"\\forall","∃":"\\exists","∄":"\\nexists","∴":"\\therefore","∵":"\\because","…":"\\ldots","⋯":"\\cdots","⋮":"\\vdots","⋱":"\\ddots"},t={"&":"\\&","%":"\\%","#":"\\#",$:"\\$","{":"\\{","}":"\\}"};let i="";for(const n of e){const o=r[n];o?i+=o.startsWith("\\")?`${o} `:o:i+=t[n]??n}return i}static async loadZipFromBlob(e){const r=typeof e.arrayBuffer=="function"?await e.arrayBuffer():e;return Cr.loadAsync(r)}static async generateCompressedZipBlob(e){return e.generateAsync({type:"blob",compression:"DEFLATE",compressionOptions:{level:6}})}static async toBlob(e,r,t){Nr()||await Ti();const i=await import("./index-BWdRWxoH.js"),{Document:n,Packer:o,Tab:s,TabStopType:a,LeaderType:l,CommentRangeStart:d,CommentRangeEnd:p,CommentReference:h,BookmarkStart:m,BookmarkEnd:f,Paragraph:b,TextRun:u,InsertedTextRun:g,DeletedTextRun:w,FootnoteReference:S,Header:T,Footer:F,ExternalHyperlink:B,InternalHyperlink:P,HeadingLevel:z,AlignmentType:E,PageOrientation:G,PageNumber:$,PageBreak:v,SectionType:D,UnderlineType:M,Table:x,TableRow:R,TableCell:X,WidthType:L,BorderStyle:W,ShadingType:U,ImportedXmlComponent:J,ImageRun:ee,LevelFormat:I,LevelSuffix:_}=i,j=c=>{const y=`<root>${c}</root>`,C=J.fromXmlString(y),k=C.root?.[0];if(k?.root){for(const A of k.root)if(A?.rootKey?.startsWith("m:"))return A}return C},q=(c,y)=>{const C=c?.root;if(Array.isArray(C)){for(const k of C)if(k?.rootKey===y)return k;for(const k of C){if(k?.rootKey==="w:rPr"||k?.rootKey==="w:pPr"||k?.rootKey==="w:tblPr"||k?.rootKey==="w:trPr"||k?.rootKey==="w:tcPr")continue;const A=q(k,y);if(A)return A}}},Z=(c,y,C)=>{try{const k=q(c,y);if(!k||!Array.isArray(k.root))return;const A=(J.fromXmlString(`<root>${C}</root>`).root?.[0]?.root??[]).filter(V=>V?.rootKey&&V.rootKey!=="_attr");k.root.push(...A)}catch{}},we=c=>{try{const y=J.fromXmlString(`<root>${c}</root>`);for(const C of y.root?.[0]?.root??[])if(C?.rootKey&&C.rootKey!=="_attr")return C}catch{}return null},ae=[],ye=[],ve=(c,y,C="w:pPr")=>{const k=ae.length;ae.push(y),Z(c,C,`<w:rvseOxmlAttrs w:val="${k}"/>`)},ge=Te(e.pageLayout),Ve=Vt(ge),te=(c,y,C="only")=>{const k=(()=>{const H=Te(Mr(e.pageLayout,c)).pageNumberStart;switch(C){case"middle":return c?.pageNumberStart;case"first":return c?.pageNumberStart??(H!==1?H:void 0);case"final":return e.pageLayout?.pageNumberRestart===!0?H:void 0;case"only":return e.pageLayout?.pageNumberRestart===!0||H!==1?H:void 0}})(),A=Te(c),V=Vt(A),N={...y&&y!=="nextPage"?{type:y==="continuous"?D.CONTINUOUS:y==="evenPage"?D.EVEN_PAGE:D.ODD_PAGE}:{},page:{size:{width:this.pxToTwips(A.orientation==="landscape"?V.pageHeight:V.pageWidth),height:this.pxToTwips(A.orientation==="landscape"?V.pageWidth:V.pageHeight),orientation:A.orientation==="landscape"?G.LANDSCAPE:G.PORTRAIT},margin:{top:this.pxToTwips(A.marginTopPx),right:this.pxToTwips(A.marginRightPx),bottom:this.pxToTwips(A.marginBottomPx),left:this.pxToTwips(A.marginLeftPx)},...(()=>{const H=Te(Mr(e.pageLayout,c)).pageNumberFormat,K={...k!==void 0?{start:k}:{},...H!=="decimal"?{formatType:H}:{}};return Object.keys(K).length>0?{pageNumbers:K}:{}})()}};return c?.columnCount&&c.columnCount>1&&(N.column={count:c.columnCount,...c.columnGapTwips!==void 0?{space:c.columnGapTwips}:{}}),A.lineNumbering&&(N.lineNumbers={countBy:A.lineNumbering.countBy,start:A.lineNumbering.start,restart:A.lineNumbering.restart,...A.lineNumbering.distancePx!==void 0?{distance:Math.round(A.lineNumbering.distancePx*15)}:{}}),N},me=te(e.pageLayout),Se=ge.pageNumberPosition.endsWith("right")?E.RIGHT:E.LEFT,Be=new b({alignment:Se,children:[new u({children:[$.CURRENT]})]}),Ie=Math.round((Ve.pageWidth-ge.marginLeftPx-ge.marginRightPx)*15),nt=c=>{const y=[],C=(N,H)=>(H.oxmlRPr&&Z(N,"w:rPr",H.oxmlRPr),N);for(const N of c.children){if(N.type!=="text")continue;const H=this.textNodeToDocx(N)[0]??{},K=Je(H);if(N.marks?.field==="page"||N.marks?.field==="numPages"){y.push(new u({...K,children:[N.marks.field==="page"?$.CURRENT:$.TOTAL_PAGES]}));continue}if(N.text)if(N.text.includes(" ")){const Y=N.text.split(" "),Q=[];Y.forEach((ie,ue)=>{ue>0&&Q.push(new s),ie&&Q.push(ie)}),y.push(new u({children:Q,...K}))}else if(N.marks?.link){const Y={...K};Y.underline??(Y.underline={type:M.SINGLE}),Y.color??(Y.color="2563EB");const Q=[C(new u({text:N.text,...Y}),H)];y.push(N.marks.link.startsWith("#")?new P({anchor:N.marks.link.slice(1),children:Q}):new B({link:N.marks.link,children:Q}))}else y.push(C(new u({text:N.text,...K}),H))}const k=c.children.some(N=>N.type==="text"&&N.text.includes(" ")),A={left:E.LEFT,center:E.CENTER,right:E.RIGHT,justify:E.JUSTIFIED},V=new b({children:y,...c.align&&A[c.align]?{alignment:A[c.align]}:{},...k?{tabStops:[{type:a.CENTER,position:Math.round(Ie/2)},{type:a.RIGHT,position:Ie}]}:{}});return c.oxmlPPr&&Z(V,"w:pPr",c.oxmlPPr),c.oxmlAttrs&&ve(V,c.oxmlAttrs),V},Pe=c=>{const y=c.src.match(/^data:([^;,]+);base64,(.*)$/);if(!y)return null;const C={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/bmp":"bmp"}[y[1].toLowerCase()];if(!C)return null;try{return new b({children:[new ee({type:C,data:this.base64ToUint8Array(y[2]),...c.alt?{altText:{name:c.alt,description:c.alt,title:c.alt}}:{},transformation:{width:Math.max(1,Math.round(c.width)),height:Math.max(1,Math.round(c.height))}})]})}catch{return null}},Ce=(c,y,C)=>{const k=V=>C?(e.chromeImages??[]).filter(N=>N.side===C&&N.slot===V).map(Pe).filter(N=>N!==null):[],A={};for(const V of["default","first","even"]){const N=[...(c?.[V]??[]).map(nt),...k(V)];N.length>0&&(A[V]=new y({children:N}))}return Object.keys(A).length>0?A:void 0},se=(c,y)=>(e.chrome??[]).some(C=>C.slot===c&&(y==="any"||C.sectionIndex===void 0)&&(c==="first"||Qi(C))),Ee=!!(e.headers?.first||e.footers?.first)||se("first","unscoped"),Oe=!!(e.headers?.even||e.footers?.even)||se("even","any");Ee&&(me.titlePage=!0);const Me={},Ge=this.buildDocxNumberingConfig(e,{AlignmentType:E,LevelFormat:I,LevelSuffix:_}),Ye=new Set;let Qe=1e5;const le=c=>{if(c!==void 0&&!Ye.has(c))return Ye.add(c),c;for(;Ye.has(Qe);)Qe++;return Ye.add(Qe),Qe};let $e=!1;const Je=c=>{const y={};return c.bold!==void 0&&(y.bold=c.bold),c.italic!==void 0&&(y.italics=c.italic),c.underline&&(y.underline={type:c.underline==="NONE"?"none":M.SINGLE}),c.strike!==void 0&&(y.strike=c.strike),c.doubleStrike!==void 0&&(y.doubleStrike=c.doubleStrike),c.smallCaps!==void 0&&(y.smallCaps=c.smallCaps),c.allCaps!==void 0&&(c.smallCaps!==void 0?(y.snapToGrid=c.allCaps,$e=!0):y.allCaps=c.allCaps),c.vanish===!0?y.vanish=!0:c.vanish===!1&&(y.specVanish=!0,$e=!0),c.lang&&(y.language={value:c.lang}),c.characterSpacing?y.characterSpacing=c.characterSpacing:c.characterSpacing===0&&(y.imprint=!0,$e=!0),c.superScript&&(y.superScript=!0),c.subScript&&(y.subScript=!0),c.baseline&&(y.emboss=!0,$e=!0),c.rightToLeft&&(y.rightToLeft=!0),c.color&&(y.color=c.color),c.highlight&&(y.highlight=c.highlight),c.font&&(y.font=c.font.split(",")[0].replaceAll("'","").replaceAll('"',"")),c.size&&(y.size=c.size),c.characterStyle&&(y.style=c.characterStyle),y};let be=0,Pt=1e5;const Ct=new Set((e.sdtWrappers??[]).filter(c=>c.scope==="inline").map(c=>c.id)),et=new Map,kt=(c,y,C,k)=>{const A=`${c.name}\0${c.role}\0${c.rangeId}`,V=et.get(A);if(V){V.wrapperIds.push(y);return}et.set(A,{name:c.name,role:c.role,rangeId:c.rangeId,author:c.rangeAuthor??C,date:typeof c.rangeCreatedAt=="number"?new Date(c.rangeCreatedAt).toISOString():k,wrapperIds:[y]})},ot=c=>{const y=N=>N?.sdtInline?.split(",").filter(H=>H&&Ct.has(H))??[],C=new Map,k=c.children.flatMap((N,H)=>{if(N.mathOmml)return j(N.mathOmml);const K={text:N.text,...Je(N)};N.break&&(K.break=1),N.footnoteReference!==void 0&&(delete K.text,K.style??(K.style="FootnoteReference"),K.children=[new S(N.footnoteReference)]),N.rPrChange&&(K.revision={id:le(N.rPrChange.importedId),author:N.rPrChange.author,date:N.rPrChange.date,...Je(N.rPrChange.prior)});const Y=()=>{let oe;if(N.revision){const ce=le(N.revision.importedId),mt={...K,id:ce,author:N.revision.author,date:N.revision.date};N.revision.move&&kt(N.revision.move,ce,N.revision.author,N.revision.date),oe=N.revision.kind==="delete"?new w(mt):new g(mt)}else oe=new u(K);return N.oxmlRPr&&Z(oe,"w:rPr",N.oxmlRPr),oe},Q=N.link?(()=>{K.underline??(K.underline={type:M.SINGLE}),K.color??(K.color="2563EB");const oe=[Y()];return N.link.startsWith("#")?new P({anchor:N.link.slice(1),children:oe}):new B({link:N.link,children:oe})})():Y(),ie=[];for(const oe of pr.get(N)??[]){const ce=Re.get(oe);ce!==void 0&&ie.push(new d(ce))}const ue=y(c.children[H-1]),de=y(N),vt=y(c.children[H+1]);for(const oe of[...de].reverse()){if(ue.includes(oe))continue;const ce={name:`__rvSdt:${oe}:${be++}`,numericId:Pt++};C.set(oe,ce),ie.push(new m(ce.name,ce.numericId))}for(const oe of Xt.get(N)??[])ie.push(new m(oe,_t.get(oe)));for(const oe of zt.get(N)??[]){const ce=we(Nt.get(oe).startXml);ce&&ie.push(ce)}const ht=Gt.has(c),pe=N.fieldInstr;pe&&!ht&&c.children[H-1]?.fieldInstr!==pe&&ie.push(...fr(pe)),ie.push(Q),pe&&!ht&&c.children[H+1]?.fieldInstr!==pe&&ie.push(...wr());for(const oe of Ht.get(N)??[]){const ce=we(Nt.get(oe).endXml);ce&&ie.push(ce)}for(const oe of Wt.get(N)??[])ie.push(new f(_t.get(oe)));for(const oe of de){if(vt.includes(oe))continue;const ce=C.get(oe);ce&&(ie.push(new f(ce.numericId)),C.delete(oe))}for(const oe of hr.get(N)??[]){const ce=Re.get(oe);ce!==void 0&&(ie.push(new p(ce)),ie.push(new u({children:[new h(ce)]})))}return ie});for(const N of Lt.get(c.sourceBlockId??"")??[]){const H=Re.get(N);H!==void 0&&(k.push(new d(H)),k.push(new p(H)),k.push(new u({children:[new h(H)]})))}jt.has(c)&&k.unshift(...fr(jt.get(c))),ur.has(c)&&k.push(...wr());const A={children:k};if(c.children.length>0&&c.children.every(N=>!N.text&&!N.break&&!N.mathOmml&&N.footnoteReference===void 0)){const N=c.children.find(H=>H.size||H.font);if(N){const{size:H,font:K}=Je({size:N.size,font:N.font});A.run={...H?{size:H}:{},...K?{font:K}:{}}}}if(c.keepNext&&(A.keepNext=!0),c.keepLines&&(A.keepLines=!0),c.widowControl===!1&&(A.widowControl=!1),c.bidirectional!==void 0&&(A.bidirectional=c.bidirectional),c.tabStopsJson){const N=en(c.tabStopsJson);if(N){const H={left:a.LEFT,right:a.RIGHT,center:a.CENTER,decimal:a.DECIMAL},K={dot:l.DOT,hyphen:l.HYPHEN,underscore:l.UNDERSCORE};A.tabStops=N.map(Y=>({type:H[Y.align]??a.LEFT,position:Math.round(Y.pos*15),...Y.leader?{leader:K[Y.leader]}:{}}))}}if(c.bordersJson)try{const N=JSON.parse(c.bordersJson),H=Y=>{switch(Y){case"dashed":return W.DASHED;case"dotted":return W.DOTTED;case"double":return W.DOUBLE;case"none":return W.NONE;default:return W.SINGLE}},K={};for(const Y of["top","bottom","left","right"]){const Q=N[Y];Q&&(K[Y]={style:H(Q.style),size:Q.style==="none"?0:Math.max(1,Math.round((Q.width??1)*6)),color:this.toDocxHex(Q.color)??"auto"})}Object.keys(K).length>0&&(A.border=K)}catch{}if(c.shadingFill){const N=this.toDocxHex(c.shadingFill);A.shading=N?{type:U.CLEAR,fill:N}:{type:U.CLEAR,fill:"auto",color:"auto"}}if(c.heading&&!c.styleId){const N={HEADING_1:z.HEADING_1,HEADING_2:z.HEADING_2,HEADING_3:z.HEADING_3,HEADING_4:z.HEADING_4,HEADING_5:z.HEADING_5,HEADING_6:z.HEADING_6};A.heading=N[c.heading]}if(c.alignment){const N={LEFT:E.LEFT,CENTER:E.CENTER,RIGHT:E.RIGHT,JUSTIFIED:E.JUSTIFIED};A.alignment=N[c.alignment]}c.styleId?A.style=c.styleId:c.style&&(A.style=c.style),c.lineSpacing!==void 0&&(A.spacing={...A.spacing,line:Math.round(c.lineSpacing*240)}),c.spacingBeforeTwips!==void 0&&(A.spacing={...A.spacing,before:c.spacingBeforeTwips}),c.spacingAfterTwips!==void 0&&(A.spacing={...A.spacing,after:c.spacingAfterTwips}),c.contextualSpacing&&(A.contextualSpacing=!0),c.indent&&(A.indent={...A.indent,...c.indent}),c.list&&(c.list.variant==="todo"?A.indent=this.getListIndentOptions(c.list.level):c.list.reference&&(A.numbering={reference:c.list.reference,level:c.list.level,instance:c.list.instance??0}));const V=new b(A);return c.oxmlPPr&&Z(V,"w:pPr",c.oxmlPPr),c.oxmlAttrs&&ve(V,c.oxmlAttrs),V},Ue=c=>{const y=Number.isFinite(c.borderWidth)?Math.max(0,Math.round(c.borderWidth)):1,C=y>0?{style:W.SINGLE,size:Math.max(1,y*6),color:this.toDocxHex(c.borderColor)??"D1D5DB"}:{style:W.NONE,size:0,color:"auto"},k=de=>{const vt={single:W.SINGLE,dashed:W.DASHED,dotted:W.DOTTED,double:W.DOUBLE,none:W.NONE};return de.style==="none"||de.width<=0?{style:W.NONE,size:0,color:"auto"}:{style:vt[de.style]??W.SINGLE,size:Math.max(1,Math.round(de.width*6)),color:this.toDocxHex(de.color)??"auto"}},A=er(c.borders),V=A?{top:k(A.top??{style:"single",width:1,color:"#d1d5db"}),bottom:k(A.bottom??{style:"single",width:1,color:"#d1d5db"}),left:k(A.left??{style:"single",width:1,color:"#d1d5db"}),right:k(A.right??{style:"single",width:1,color:"#d1d5db"}),insideHorizontal:k(A.insideH??{style:"single",width:1,color:"#d1d5db"}),insideVertical:k(A.insideV??{style:"single",width:1,color:"#d1d5db"})}:void 0,N=c.rows.map(de=>{const vt=de.cells.map((pe,oe)=>{const ce=pe.blocks??pe.paragraphs,mt=ce.map(Ne=>Ne.type==="table"?Ue(Ne):ot(Ne));(mt.length===0||ce[ce.length-1]?.type==="table")&&mt.push(new b({}));const hi=Math.max(c.columnWidths.length,1),mi=pe.colSpan??1,Sr=pe.gridColumn??oe;let Ir=0;for(let Ne=Sr;Ne<Sr+mi;Ne++)Ir+=c.columnWidths[Ne]||100/hi;const We={children:mt,width:{size:Ir,type:L.PERCENTAGE}};pe.verticalAlign&&(We.verticalAlign=pe.verticalAlign==="middle"?"center":pe.verticalAlign);const ze=rn(pe.borders);if(ze){const Ne={};ze.top&&(Ne.top=k(ze.top)),ze.bottom&&(Ne.bottom=k(ze.bottom)),ze.left&&(Ne.left=k(ze.left)),ze.right&&(Ne.right=k(ze.right)),We.borders=Ne}else V||(We.borders={top:C,bottom:C,left:C,right:C});const St=nn(pe.padding);St&&(We.margins={marginUnitType:L.DXA,top:Math.round(St.top*15),bottom:Math.round(St.bottom*15),left:Math.round(St.left*15),right:Math.round(St.right*15)}),pe.colSpan&&pe.colSpan>1&&(We.columnSpan=pe.colSpan),pe.rowSpan&&pe.rowSpan>1&&(We.rowSpan=pe.rowSpan);const Kt=this.toDocxHex(pe.backgroundColor);Kt?We.shading={type:U.SOLID,color:Kt,fill:Kt}:de.isHeader&&!pe.backgroundColor&&(We.shading={type:U.SOLID,color:"F9FAFB",fill:"F9FAFB"});const Pr=new X(We);return pe.oxmlTcPr&&Z(Pr,"w:tcPr",pe.oxmlTcPr),Pr}),ht=new R({children:vt,tableHeader:de.isHeader===!0?!0:void 0});return de.oxmlTrPr&&Z(ht,"w:trPr",de.oxmlTrPr),de.oxmlAttrs&&ve(ht,de.oxmlAttrs,"w:trPr"),ht}),H=typeof c.tableWidth=="number"&&Number.isFinite(c.tableWidth)&&c.tableWidth>0?Math.round(c.tableWidth*15):void 0,K=H??9e3,Y=c.columnWidths.filter(de=>Number.isFinite(de)&&de>0).map(de=>Math.max(1,Math.round(de/100*K))),Q=c.align==="center"?E.CENTER:c.align==="right"?E.RIGHT:c.align==="left"?E.LEFT:void 0,ie=typeof c.cellPadding=="number"&&Number.isFinite(c.cellPadding)&&c.cellPadding>=0?{marginUnitType:L.DXA,top:Math.round(c.cellPadding*15),bottom:Math.round(c.cellPadding*15),left:Math.round(c.cellPadding*15),right:Math.round(c.cellPadding*15)}:void 0,ue=new x({rows:N,width:H?{size:H,type:L.DXA}:{size:100,type:L.PERCENTAGE},...Y.length===c.columnWidths.length&&Y.length>0?{columnWidths:Y}:{},...Q?{alignment:Q}:{},...ie?{margins:ie}:{},borders:V??{top:C,bottom:C,left:C,right:C,insideHorizontal:C,insideVertical:C}});return c.oxmlTblPr&&Z(ue,"w:tblPr",c.oxmlTblPr),ue},tt=c=>{const y=c.split(",")[1]||"";if(typeof atob!="function")throw new Error("Base64 decoding is unavailable in this environment");const C=atob(y),k=new Uint8Array(C.length);for(let A=0;A<C.length;A++)k[A]=C.charCodeAt(A);return k},gt=c=>{if(c.renderDiagram)return c.diagramPngDataUrl?new b({children:[new ee({type:"png",data:tt(c.diagramPngDataUrl),transformation:{width:Math.max(120,Math.round(c.diagramWidth||600)),height:Math.max(60,Math.round(c.diagramHeight||180))}})],spacing:{before:120,after:120}}):new b({children:[new u({text:"Diagram unavailable"})],spacing:{before:120,after:120}});const y=c.runs.map(k=>{const A={text:k.text,font:k.font||"Courier New"};return k.color&&(A.color=k.color),k.break&&(A.break=k.text.split(`
|
|
6
|
+
`).length-1,A.text=""),new u(A)}),C=this.toDocxHex(c.backgroundColor)??"F5F5F5";return new b({children:y,...c.styleId?{style:c.styleId}:{},shading:{type:U.SOLID,color:C,fill:C},spacing:{before:120,after:120}})},st=c=>{if(!c.omml)return new b({children:[new u({text:c.content})],alignment:c.alignment==="center"?E.CENTER:c.alignment==="right"?E.RIGHT:E.LEFT});const y=j(c.omml);return new b({children:[y],alignment:c.alignment==="center"?E.CENTER:c.alignment==="right"?E.RIGHT:E.LEFT,spacing:{before:120,after:120}})},at=[],lt=[],De=c=>{if(!c.anchorXml)return;const y=`__revise-anchor:${lt.length}__`;return lt.push({marker:y,anchorXml:c.anchorXml}),y},Ze=c=>({alignment:c.align==="center"?E.CENTER:c.align==="right"?E.RIGHT:E.LEFT,spacing:{before:120,after:120}}),Vr=async c=>{const y=De(c);if(c.originalFormat&&c.originalDataUrl){const k=`__revise-original-media:${at.length}__`;return at.push({marker:k,format:c.originalFormat,dataUrl:c.originalDataUrl,alt:c.alt}),new b({children:[new ee({type:"png",data:this.base64ToUint8Array(qr),altText:{name:c.alt||"Image",description:k,title:y??c.alt},transformation:{width:Math.max(1,Math.round(c.width)),height:Math.max(1,Math.round(c.height))}})],...Ze(c)})}if(c.src.match(/^data:image\/svg\+xml(;base64)?,/i)){const k=this.dataUrlToUint8Array(c.src);if(k){const A=Math.max(1,Math.round(c.width)),V=Math.max(1,Math.round(c.height)),N=await this.rasterizeSvgDataUrlToPng(c.src,A,V)??this.base64ToUint8Array(qr);return new b({children:[new ee({type:"svg",data:k,fallback:{type:"png",data:N},altText:{name:c.alt||"Image",description:c.alt,title:y??c.alt},transformation:{width:A,height:V}})],...Ze(c)})}}const C=await this.resolveImageSourceForDocx(c.src);return C?new b({children:[new ee({type:C.type,data:C.data,altText:{name:c.alt||"Image",description:c.alt,title:y??c.alt},transformation:{width:Math.max(1,Math.round(c.width)),height:Math.max(1,Math.round(c.height))}})],...Ze(c)}):new b({children:[new u({text:c.alt||"Image unavailable"})],...Ze(c)})},Yr=()=>new b({children:[new v]}),ut=[...e.notes??[],...e.children.filter(c=>c.type==="footnote")],ft=new Map;for(const c of ut)ft.set(c.id,c.noteKind==="endnote"?"endnote":"footnote");const Qr=ut.filter(c=>ft.get(c.id)==="footnote"),wt=ut.filter(c=>ft.get(c.id)==="endnote"),At=new Map,ct=new Map;{const c=y=>{if(!y||typeof y!="object")return;if(Array.isArray(y)){y.forEach(c);return}const C=y;if(C.type==="footnote")return;const k=C.marks?.footnoteRef;if(k){const A=ft.get(k)==="endnote"?ct:At;A.has(k)||A.set(k,A.size+1)}c(C.children)};c(e.children.filter(y=>y.type!=="footnote"))}for(const c of wt)ct.has(c.id)||ct.set(c.id,ct.size+1);const _e=e.comments??[],Re=new Map,dt=new Set;for(const c of _e){const y=c.importedId;Number.isSafeInteger(y)&&y>=0&&y<=2147483647&&!dt.has(y)&&(dt.add(y),Re.set(c.id,y))}let Ke=0;for(const c of _e)if(!Re.has(c.id)){for(;dt.has(Ke);)Ke++;Re.set(c.id,Ke),dt.add(Ke++)}const bt=new Map,lr=c=>{const y=new Map(_e.map(A=>[A.id,A]));let C=c;const k=new Set;for(;C.parentId&&!k.has(C.id);){k.add(C.id);const A=y.get(C.parentId);if(!A)break;C=A}return C.id};for(const c of _e){const y=lr(c),C=bt.get(y)??[];C.includes(c.id)||C.push(c.id),bt.set(y,C)}const ei=e.children.some(c=>c.type==="header-footer");let Xe=ut.length>0||ei?{...e,children:e.children.filter(c=>c.type!=="footnote"&&c.type!=="header-footer")}:e;if(ut.length>0){Xe=JSON.parse(JSON.stringify(Xe));const c=y=>{if(!y||typeof y!="object")return;if(Array.isArray(y)){y.forEach(c);return}const C=y,k=C.marks?.footnoteRef;if(k)if(ft.get(k)==="endnote"){const A=ct.get(k)??1;C.text=`__RVSE_EN_${A}__`,C.marks&&(delete C.marks.footnoteRef,C.marks.superscript=!0)}else C.text=String(At.get(k)??1);c(C.children)};c(Xe.children)}this.hasDocxMoveMarks(Xe.children)&&(Xe=JSON.parse(JSON.stringify(Xe)),this.finalizeImportedMovePairs(Xe.children));const cr=this.collectTableRevisionPatches(Xe),$t=t?.graft?[]:void 0,yt=this.toDocxFormatWithTables(Xe,r,t?.headingPageNumbers,$t),xt=[],dr=c=>{for(const y of c){if(y.type==="paragraph"){xt.push(y);continue}for(const C of y.rows)for(const k of C.cells)dr(k.blocks??k.paragraphs)}};dr(yt.filter(c=>c.type==="paragraph"||c.type==="table"));const pr=new Map,hr=new Map,Lt=new Map,mr=[];{const c=[];for(const N of xt)c.push(...N.children);const y=N=>(N.text??"")===""&&!N.break&&!N.mathOmml&&N.footnoteReference===void 0&&!N.fieldInstr,C=new Map;for(const[N,H]of bt)for(const K of H)C.set(K,N);const k=new Map;c.forEach((N,H)=>{const K=new Set((N.comment?.split(",")??[]).filter(Boolean).map(Y=>C.get(Y)??Y));for(const Y of K){const Q=k.get(Y)??[],ie=Q[Q.length-1];let ue=!!ie;for(let de=ie?ie.lastIndex+1:H;de<H;de++)if(!y(c[de])){ue=!1;break}ie&&ue?(ie.last=N,ie.lastIndex=H):Q.push({first:N,last:N,lastIndex:H}),k.set(Y,Q)}});const A=new Set,V=(N,H,K)=>N.set(H,[...N.get(H)??[],...K]);for(const[N,H]of k){const K=bt.get(N)??[N];K.forEach(Y=>A.add(Y)),H.forEach((Y,Q)=>{let ie=K;if(Q>0){if(!Re.has(N))return;const ue=`${N}\0fragment${Q}`;for(;dt.has(Ke);)Ke++;Re.set(ue,Ke),dt.add(Ke++),mr.push({cloneId:ue,sourceId:N}),ie=[ue]}V(pr,Y.first,ie),V(hr,Y.last,ie)})}for(const N of _e){const H=N.anchorBlockId;if(!H||A.has(N.id))continue;const K=bt.get(N.id)??[N.id],Y=Lt.get(H)??[];for(const Q of K)Y.includes(Q)||Y.push(Q);Lt.set(H,Y)}}const ti=new Map(_e.map(c=>[c.id,c])),gr=[..._e.map(c=>({id:c.id,record:c,isClone:!1})),...mr.map(({cloneId:c,sourceId:y})=>({id:c,record:ti.get(y),isClone:!0}))],_t=new Map,Xt=new Map,Wt=new Map;{const c=new Map,y=new Map;for(const k of xt)for(const A of k.children)for(const V of A.bookmark?.split(",")??[])V&&(c.has(V)||c.set(V,A),y.set(V,A));let C=1;for(const[k,A]of c)_t.set(k,C++),Xt.set(A,[...Xt.get(A)??[],k]);for(const[k,A]of y)Wt.set(A,[...Wt.get(A)??[],k])}const zt=new Map,Ht=new Map,Nt=new Map((e.oxmlRanges??[]).filter(c=>c.startXml&&c.endXml).map(c=>[c.id,c]));if(Nt.size>0){const c=new Map,y=new Map;for(const C of xt)for(const k of C.children)for(const A of k.oxmlRange?.split(",")??[])!A||!Nt.has(A)||(c.has(A)||c.set(A,k),y.set(A,k));for(const[C,k]of c)zt.set(k,[...zt.get(k)??[],C]);for(const[C,k]of y)Ht.set(k,[...Ht.get(k)??[],C])}const ri=c=>{const y=c.children.filter(k=>(k.text??"")!==""||k.fieldInstr);if(y.length===0)return;const C=y[0].fieldInstr;if(!(!C||!/^TOC\b/i.test(C.trim())))return y.every(k=>k.fieldInstr===C)?C:void 0},jt=new Map,ur=new Set,Gt=new Set;{let c,y=[];const C=()=>{c&&y.length>0&&(jt.set(y[0],c),ur.add(y[y.length-1]),y.forEach(k=>Gt.add(k))),c=void 0,y=[]};for(const k of yt){const A=k.type==="paragraph"?k:void 0,V=A?ri(A):void 0;if(A&&V&&V===c){y.push(A);continue}C(),A&&V&&(c=V,y=[A])}C()}const Tt=c=>{const y=`<root><w:r xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${c}</w:r></root>`,C=J.fromXmlString(y).root?.[0];if(C?.root){for(const k of C.root)if(k?.rootKey==="w:r")return k}},ii=c=>c.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),fr=c=>[Tt('<w:fldChar w:fldCharType="begin"/>'),Tt(`<w:instrText xml:space="preserve"> ${ii(c)} </w:instrText>`),Tt('<w:fldChar w:fldCharType="separate"/>')].filter(Boolean),wr=()=>[Tt('<w:fldChar w:fldCharType="end"/>')].filter(Boolean),ni=Gt.size>0||xt.some(c=>c.children.some(y=>y.fieldInstr)),oi=c=>{if(nr(c.xml))return new b({});try{const y=c.origin==="run"?`<root><w:p xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:r>${c.xml}</w:r></w:p></root>`:`<root>${c.xml}</root>`,C=J.fromXmlString(y).root?.[0];for(const k of C?.root??[])if(k?.rootKey&&k.rootKey!=="_attr")return k}catch{}return new b({})},br=async c=>c.type==="table"?Ue(c):c.type==="codeblock"?gt(c):c.type==="mathblock"?st(c):c.type==="pagebreak"?Yr():c.type==="sectionbreak"?null:c.type==="image"?Vr(c):c.type==="docxraw"?oi(c):ot(c),si=await Promise.all(yt.map(br)),Jt={},Et=new Map,yr=c=>{for(const y of c)if(y.type==="paragraph"&&y.list?.reference){const C=`${y.list.reference}\0${y.list.instance??0}`;Et.has(C)||Et.set(C,y.list)}else if(y.type==="table")for(const C of y.rows)for(const k of C.cells)yr(k.blocks??k.paragraphs)},xr=async(c,y)=>{const C=this.toDocxFormatWithTables({...e,children:c.children},r);yr(C);const k=(await Promise.all(C.map(br))).filter(A=>A!==null).map(A=>A);Jt[String(y)]={children:k.length>0?k:[new b({})]}};let ai=At.size;for(const c of Qr){const y=At.get(c.id)??++ai;await xr(c,y)}const vr=new Map;for(let c=0;c<wt.length;c++){const y=wt[c],C=1e6+c;vr.set(y.id,C),await xr(y,C)}const Ut=[...Et.keys()],li=Ut.map((c,y)=>ot({type:"paragraph",children:[{text:`__RVSE_NOTE_NUM_${y}__`}],list:Et.get(c)}));{const c=Ei(e.chrome??[]),y=Ce(e.headers??c.headers,T,"header"),C=Ce(e.footers??c.footers,F,"footer");y&&(Me.headers=y),C&&(Me.footers=C),e.watermark&&!Me.headers&&(Me.headers={default:new T({children:[new b({})]})}),ge.showPageNumbers&&(ge.pageNumberPosition.startsWith("top")&&!Me.headers?Me.headers={default:new T({children:[Be]})}:!ge.pageNumberPosition.startsWith("top")&&!Me.footers&&(Me.footers={default:new F({children:[Be]})}))}const Ae=e.coreProperties??{},ci={...Ae.title!==void 0?{title:Ae.title}:{},...Ae.subject!==void 0?{subject:Ae.subject}:{},...Ae.creator!==void 0?{creator:Ae.creator}:{},...Ae.keywords!==void 0?{keywords:Ae.keywords}:{},...Ae.description!==void 0?{description:Ae.description}:{},...Ae.lastModifiedBy!==void 0?{lastModifiedBy:Ae.lastModifiedBy}:{}},di=new n({...ci,...e.pageLayout?.blockSpacingPx!==void 0?{customProperties:[{name:"Revise.BlockSpacingPx",value:String(Te(e.pageLayout).blockSpacingPx)}]}:{},numbering:Ge,...ni?{features:{updateFields:!0}}:{},...Oe?{evenAndOddHeaderAndFooters:!0}:{},..._e.length>0?{comments:{children:gr.map(({id:c,record:y})=>({id:Re.get(c),author:y.author,...y.initials?{initials:y.initials}:{},date:new Date(y.createdAt),children:(y.bodyMd||" ").split(/\n\n+/).map(C=>new b({children:[new u({text:C})]}))}))}}:{},...Object.keys(Jt).length>0?{footnotes:Jt}:{},styles:{default:{document:{run:{size:this.DEFAULT_RUN_SIZE_HALF_POINTS}},...this.buildExportHeadingDefaults()},paragraphStyles:this.buildExportParagraphStyles(e),characterStyles:this.buildExportCharacterStyles()},sections:(()=>{const c=e.chrome??[],y=Mi(c),C=K=>{if(["header","footer"].some(Q=>tn(c,Q,"first",K)))return!0;if(!y)return Ee;const Y=Br(c,K);return!!(Y.headers?.first||Y.footers?.first)},k=K=>{if(!y)return Me;const Y=Br(c,K),Q={},ie=Ce(Y.headers,T),ue=Ce(Y.footers,F);return ie&&(Q.headers=ie),ue&&(Q.footers=ue),ge.showPageNumbers&&(ge.pageNumberPosition.startsWith("top")&&!Q.headers?Q.headers={default:new T({children:[Be]})}:!ge.pageNumberPosition.startsWith("top")&&!Q.footers&&(Q.footers={default:new F({children:[Be]})})),Q},A=[];let V=[],N;yt.forEach((K,Y)=>{if("type"in K&&K.type==="sectionbreak"){const ie=K;ye.push(Bi(e.pageLayout,ie.layout));const ue=te(ie.layout,N,A.length===0?"first":"middle");C(A.length)&&(ue.titlePage=!0),A.push({properties:ue,...k(A.length),children:V}),V=[],N=ie.breakType;return}const Q=si[Y];Q!=null&&V.push(Q)}),ye.push(Di(e.pageLayout));const H=A.length===0?me:te(e.pageLayout,N,"final");return C(A.length)?H.titlePage=!0:y&&H===me&&delete H.titlePage,A.push({properties:H,...k(A.length),children:[...V,...li]}),A})()}),pi=await this.stabilizeHyperlinkRelIds(await this.stabilizeAttributeWhitespace(await o.toBlob(di))),Mt=[],Zt=[];let pt=0;for(const c of yt){if("type"in c&&c.type==="table")continue;if("type"in c&&c.type==="docxraw"){c.emitsParagraph&&pt++;continue}if("type"in c&&c.type==="sectionbreak"){const k=c.pendingDeletion;k&&Mt.push({pIndex:pt,kind:"merge",...k}),pt++;continue}const y=c.paragraphMarkRevision;y&&Mt.push({pIndex:pt,...y});const C=c.paragraphPropertiesChange;C&&Zt.push({pIndex:pt,...C}),pt++}let re=pi;if(et.size>0&&(re=await this.patchLinkedMoveRevisions(re,Array.from(et.values()))),Ut.length>0&&(re=await this.patchNoteNumberingReferences(re,Ut)),$e&&(re=await this.patchRunPropertyResetMarkers(re)),ae.length>0&&(re=await this.applyOxmlAttrMarkers(re,ae)),ye.some(c=>c)&&(re=await this.injectSectPrOpaquePayloads(re,ye)),lt.length>0)try{re=await this.patchAnchoredImages(re,lt)}catch(c){console.warn("docx export: anchored-image restore failed; exporting images inline",c)}if(at.length>0)try{re=await this.patchOriginalVectorImages(re,at)}catch(c){console.warn("docx export: EMF/WMF original-media patch failed; exporting placeholder images",c)}if(Mt.length>0)try{re=await this.patchParagraphMarkRevisions(re,Mt,le)}catch(c){console.warn("docx export: paragraph-mark revision patch failed; exporting without pilcrow markup",c)}if(Zt.length>0)try{re=await this.patchParagraphPropertyChanges(re,Zt,le)}catch(c){console.warn("docx export: w:pPrChange patch failed; exporting without paragraph property-change markup",c)}if(cr.length>0)try{re=await this.patchTableRevisions(re,cr,le)}catch(c){console.warn("docx export: table revision patch failed; exporting table content without revision markup",c)}if(_e.length>0)try{re=await this.appendCommentsExtendedPart(re,gr.map(({id:c,record:y,isClone:C})=>{const k=!C&&y.parentId?lr(y):void 0;return{numericId:Re.get(c),resolved:y.resolved===!0,parentNumericId:k&&k!==y.id?Re.get(k):void 0}}))}catch(c){console.warn("docx export: commentsExtended generation failed; comments export flat/unresolved",c)}if(wt.length>0)try{re=await this.appendEndnotesPart(re,wt.map(c=>({index:ct.get(c.id),note:c,syntheticFootnoteId:vr.get(c.id)})))}catch(c){console.warn("docx export: endnotes part generation failed; endnote markers left in text",c)}if(e.sdtWrappers&&e.sdtWrappers.length>0)try{re=await this.applySdtWrappers(re,e)}catch(c){console.warn("docx export: content-control wrapping failed; content exported unwrapped",c)}if(e.coreProperties)try{re=await this.patchCoreProperties(re,Ae)}catch(c){console.warn("docx export: core-property patch failed; library defaults kept",c)}if(e.stylesXml)try{re=await this.mergeImportedStyles(re,e.stylesXml)}catch(c){console.warn("docx export: styles.xml merge failed; imported named styles dropped",c)}if(e.watermark)try{re=await this.injectWatermarkIntoHeaders(re,e.watermark)}catch(c){console.warn("docx export: watermark header injection failed; exporting without watermark",c)}if(Te(e.pageLayout).hyphenationEnabled)try{re=await this.injectAutoHyphenationSetting(re)}catch(c){console.warn("docx export: autoHyphenation setting injection failed",c)}try{re=await this.stampApplicationProperty(re)}catch(c){console.warn("docx export: application stamp failed; exporting without it",c)}if(t?.graft&&$t){const c=y=>{try{t.graft?.onOutcome?.(y)}catch{}};if(!e.docxSource)return console.warn("docx export: graft requested but document has no docxSource capture; exporting regenerated package"),c({mode:"regenerated",fallbackCode:"no-capture"}),re;try{re=await Ri({generatedBlob:re,originalDocx:t.graft.originalDocx,doc:e,blockRanges:$t});const y=Fi(e);c({mode:y.fullyExact?"exact":"grafted",regeneratedBlockCount:y.regeneratedBlockIds.length,changedDomains:Object.entries(y.domains).filter(([,C])=>!C).map(([C])=>C)})}catch(y){const C=y instanceof Oi?y.code:"internalError";console.warn(`docx export: OOXML graft rejected [${C}]; exporting regenerated package`,y),c({mode:"regenerated",fallbackCode:C})}}return re}static async patchNoteNumberingReferences(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;let n=await i.async("text");const o=new Map;n=n.replace(/<w:p\b[^>]*>[\s\S]*?<\/w:p>/g,l=>{const d=/__RVSE_NOTE_NUM_(\d+)__/.exec(l);if(!d)return l;const p=Number(d[1]),h=/<w:numId\b[^>]*w:val="([^"]+)"/.exec(l)?.[1],m=r[p];return m&&h&&!h.startsWith("{")&&o.set(m,h),""}),t.file("word/document.xml",n);const s=l=>l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");for(const[l,d]of Object.entries(t.files)){if(!l.startsWith("word/")||!l.endsWith(".xml")||d.dir)continue;let p=await d.async("text"),h=!1;for(const[m,f]of o){const[b,u]=m.split("\0"),g=`{${b}-${u}}`,w=p.replace(new RegExp(`w:val="${s(g)}"`,"g"),`w:val="${f}"`);h||(h=w!==p),p=w}h&&t.file(l,p)}const a=await this.generateCompressedZipBlob(t);return new Blob([a],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async injectSectPrOpaquePayloads(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;let n=await i.async("text"),o=0;n=n.replace(/<w:sectPr\b[^>]*>[\s\S]*?<\/w:sectPr>|<w:sectPr\b[^>]*\/>/g,d=>{const p=r[o++];return p?d.endsWith("/>")?`${d.slice(0,-2)}>${p}</w:sectPr>`:d.replace(/<\/w:sectPr>$/,`${p}</w:sectPr>`):d});const s=new DOMParser().parseFromString(n,"application/xml"),a=new Set(["w:lnNumType","w:pgNumType","w:cols","w:formProt","w:vAlign","w:noEndnote","w:titlePg","w:textDirection","w:bidi","w:rtlGutter","w:docGrid","w:printerSettings","w:sectPrChange"]);for(const d of Array.from(s.getElementsByTagName("w:sectPr"))){const p=Array.from(d.children).find(m=>m.tagName==="w:pgBorders"),h=Array.from(d.children).find(m=>a.has(m.tagName));p&&h&&d.insertBefore(p,h)}n=new XMLSerializer().serializeToString(s),t.file("word/document.xml",n);const l=await this.generateCompressedZipBlob(t);return new Blob([l],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async stabilizeAttributeWhitespace(e){let r;try{r=await this.loadZipFromBlob(e)}catch{return e}const{stabilizeSerializedXml:t}=await Promise.resolve().then(()=>sn);let i=!1;for(const[o,s]of Object.entries(r.files)){if(!o.endsWith(".xml")||s.dir)continue;const a=await s.async("text"),l=t(a);l!==a&&(r.file(o,l),i=!0)}if(!i)return e;const n=await this.generateCompressedZipBlob(r);return new Blob([n],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async stabilizeHyperlinkRelIds(e){let r;try{r=await this.loadZipFromBlob(e)}catch{return e}let t=!1;for(const[n,o]of Object.entries(r.files)){const s=/^(.*)_rels\/([^/]+)\.rels$/.exec(n);if(!s||o.dir)continue;const a=`${s[1]}${s[2]}`,l=r.file(a);if(!l)continue;let d=await o.async("text");const p=[];for(const f of d.matchAll(/<Relationship\b[^>]*\/?>/g)){if(!/Type="[^"]*\/hyperlink"/.test(f[0]))continue;const b=/Id="([^"]+)"/.exec(f[0])?.[1];b&&p.push(b)}if(p.length===0)continue;let h=await l.async("text");const m=[...p].sort((f,b)=>{const u=h.indexOf(`"${f}"`),g=h.indexOf(`"${b}"`);return(u<0?1/0:u)-(g<0?1/0:g)});m.forEach((f,b)=>{f!==`rvseLnk${b+1}`&&(h=h.replaceAll(`r:id="${f}"`,`r:id="__rvseLnkTmp${b+1}__"`),d=d.replace(`Id="${f}"`,`Id="__rvseLnkTmp${b+1}__"`),t=!0)}),m.forEach((f,b)=>{h=h.replaceAll(`r:id="__rvseLnkTmp${b+1}__"`,`r:id="rvseLnk${b+1}"`),d=d.replace(`Id="__rvseLnkTmp${b+1}__"`,`Id="rvseLnk${b+1}"`)}),r.file(a,h),r.file(n,d)}if(!t)return e;const i=await this.generateCompressedZipBlob(r);return new Blob([i],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async applyOxmlAttrMarkers(e,r){const t=await this.loadZipFromBlob(e);for(const[n,o]of Object.entries(t.files)){if(!n.startsWith("word/")||!n.endsWith(".xml")||o.dir)continue;let s=await o.async("text");if(s.includes("<w:rvseOxmlAttrs ")){for(const a of["w:p","w:tr"])s=s.replace(new RegExp(`<${a}\\b([^>]*)>((?:(?!<${a}\\b)(?!</${a}>)[\\s\\S])*?)<w:rvseOxmlAttrs w:val="(\\d+)"/>`,"g"),(l,d,p,h)=>{const m=r[Number(h)];if(!m)return`<${a}${d}>${p}`;const f=new Set([...d.matchAll(/([\w:.-]+)=/g)].map(u=>u[1])),b=Wr(m,f);return`<${a}${d}${b}>${p}`});s=s.replace(/<w:rvseOxmlAttrs w:val="\d+"\/>/g,"").replace(/<w:pPr><\/w:pPr>|<w:pPr\/>/g,"").replace(/<w:trPr><\/w:trPr>|<w:trPr\/>/g,""),t.file(n,s)}}const i=await this.generateCompressedZipBlob(t);return new Blob([i],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchRunPropertyResetMarkers(e){const r=await this.loadZipFromBlob(e);for(const[i,n]of Object.entries(r.files)){if(!i.startsWith("word/")||!i.endsWith(".xml")||n.dir)continue;let o=await n.async("text");/<w:(?:specVanish|imprint|emboss|snapToGrid)\b/.test(o)&&(o=o.replace(/<w:specVanish\b[^>]*\/>/g,'<w:vanish w:val="false"/>').replace(/<w:imprint\b[^>]*\/>/g,'<w:spacing w:val="0"/>').replace(/<w:emboss\b[^>]*\/>/g,'<w:vertAlign w:val="baseline"/>').replace(/<w:snapToGrid\b([^>]*)\/>/g,(s,a)=>/\bw:val="(?:false|0|off)"/i.test(a)?'<w:caps w:val="false"/>':"<w:caps/>"),r.file(i,o))}const t=await this.generateCompressedZipBlob(r);return new Blob([t],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async injectAutoHyphenationSetting(e){const r=await this.loadZipFromBlob(e),t=r.file("word/settings.xml");if(!t)return e;let i=await t.async("text");if(i.includes("<w:autoHyphenation"))return e;i=i.replace(/<\/w:settings>/,"<w:autoHyphenation/></w:settings>"),r.file("word/settings.xml",i);const n=await this.generateCompressedZipBlob(r);return new Blob([n],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static escapeXml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\n/g," ").replace(/\r/g," ").replace(/\t/g,"	")}static dataUrlToUint8Array(e){const r=e.match(/^data:([^;,]+)(;base64)?,(.*)$/i);if(!r)return;const t=r[3]||"";try{return r[2]?this.base64ToUint8Array(t):new TextEncoder().encode(decodeURIComponent(t))}catch{return}}static async resolveBinarySourceForDocx(e){const r=this.dataUrlToUint8Array(e);if(r)return r;if(typeof fetch=="function")try{const t=await fetch(e);return t.ok?new Uint8Array(await t.arrayBuffer()):void 0}catch{return}}static async rasterizeSvgDataUrlToPng(e,r,t){if(!(typeof document>"u"||typeof Image>"u"||typeof navigator<"u"&&navigator.userAgent?.includes("jsdom")))return new Promise(i=>{let n=!1;const o=l=>{n||(n=!0,i(l))},s=setTimeout(()=>o(void 0),3e3),a=new Image;a.onload=()=>{clearTimeout(s);try{const l=document.createElement("canvas");l.width=Math.max(1,Math.round(r)),l.height=Math.max(1,Math.round(t));const d=l.getContext("2d");if(!d){o(void 0);return}d.drawImage(a,0,0,l.width,l.height),l.toBlob(async p=>{if(!p){o(void 0);return}o(new Uint8Array(await p.arrayBuffer()))},"image/png")}catch{o(void 0)}},a.onerror=()=>{clearTimeout(s),o(void 0)},a.src=e})}static serializeXmlPreservingPrefixes(e){const r=new Map,t=(o,s)=>{const a=s.indexOf(":");if(a<=0)return;const l=s.slice(0,a);if(l==="xmlns"||l==="xml"||r.has(l))return;const d=o.lookupNamespaceURI(l);d&&r.set(l,d)},i=o=>{t(o,o.tagName);for(let s=0;s<o.attributes.length;s++)t(o,o.attributes[s].name);for(let s=0;s<o.children.length;s++)i(o.children[s])};i(e);const n=(o,s)=>{if(o.nodeType===3)return(o.nodeValue??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");if(o.nodeType!==1)return"";const a=o;let l=`<${a.tagName}`;const d=new Set;for(let h=0;h<a.attributes.length;h++){const m=a.attributes[h];m.name.startsWith("xmlns:")&&d.add(m.name.slice(6)),l+=` ${m.name}="${this.escapeXml(m.value)}"`}if(s)for(const[h,m]of r)d.has(h)||(l+=` xmlns:${h}="${this.escapeXml(m)}"`);const p=a.childNodes;if(p.length===0)return`${l}/>`;l+=">";for(let h=0;h<p.length;h++)l+=n(p[h],!1);return`${l}</${a.tagName}>`};return n(e,!0)}static async patchAnchoredImages(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;let n=await i.async("string"),o=!1;for(const s of r){const a=`title="${this.escapeXml(s.marker)}"`,l=n.indexOf(a);if(l===-1)continue;const d=()=>{n=n.replace(` ${a}`,""),o=!0},p=n.lastIndexOf("<wp:inline",l),h=n.indexOf("</wp:inline>",l);if(p===-1||h===-1){d();continue}const m=h+12,f=n.slice(p,m),b=Array.from(f.matchAll(/r:embed="([^"]+)"/g)).map(S=>S[1]);if(b.length===0){d();continue}let u=0,g=s.anchorXml.replace(/(r:(?:embed|link)=")[^"]*(")/g,(S,T,F)=>{const B=b[Math.min(u,b.length-1)];return u++,`${T}${B}${F}`});const w=f.match(/<wp:docPr\b[^>]*/)?.[0].match(/ descr="([^"]*)"/);g=g.replace(/<wp:docPr\b([^>]*?)(\/?>)/,(S,T,F)=>{const B=T.replace(/\s+descr="[^"]*"/,""),P=w?` descr="${w[1]}"`:"";return`<wp:docPr${B}${P}${F}`}),n=n.slice(0,p)+g+n.slice(m),o=!0}return o?(t.file("word/document.xml",n),this.generateCompressedZipBlob(t)):e}static async patchOriginalVectorImages(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml"),n=t.file("word/_rels/document.xml.rels"),o=t.file("[Content_Types].xml");if(!i||!n||!o)return e;let s=await i.async("string"),a=await n.async("string"),l=await o.async("string");const d=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),b=s.indexOf(f);if(b===-1)continue;const u=s.slice(b).match(/r:embed="([^"]+)"/);if(!u)continue;const g=u[1],w=`media/reviseOriginal${p}.${h.format}`,S=new RegExp(`(<Relationship\\b[^>]*\\bId="${g}"[^>]*\\bTarget=")[^"]*(")`),T=new RegExp(`(<Relationship\\b[^>]*\\bTarget=")[^"]*("[^>]*\\bId="${g}")`);if(S.test(a))a=a.replace(S,`$1${w}$2`);else if(T.test(a))a=a.replace(T,`$1${w}$2`);else continue;t.file(`word/${w}`,m),d.add(h.format),s=h.alt?s.replace(`descr="${f}"`,`descr="${this.escapeXml(h.alt)}"`):s.replace(` descr="${f}"`,"")}for(const p of d)new RegExp(`Extension="${p}"`).test(l)||(l=l.replace("</Types>",`<Default Extension="${p}" ContentType="image/x-${p}"/></Types>`));return t.file("word/document.xml",s),t.file("word/_rels/document.xml.rels",a),t.file("[Content_Types].xml",l),this.generateCompressedZipBlob(t)}static async injectWatermarkIntoHeaders(e,r){const t=$i(r);if(!t)return e;const i=await this.loadZipFromBlob(e),n=Object.keys(i.files).filter(f=>/^word\/header\d+\.xml$/.test(f));if(n.length===0)return e;const o=f=>f.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),s=468,a=Math.max(40,Math.round(s/Math.max(2,t.text.length*.55))),l=t.diagonal?"rotation:315;":"",d=t.fontSizePx?`${Math.max(1,Math.round(t.fontSizePx*.75))}pt`:"1pt",p=`<w:p><w:pPr><w:rPr><w:noProof/></w:rPr></w:pPr><w:r><w:rPr><w:noProof/></w:rPr><w:pict xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w10="urn:schemas-microsoft-com:office:word"><v:shapetype id="_x0000_t136" coordsize="21600,21600" o:spt="136" adj="10800" path="m@7,l@8,m@5,21600l@6,21600e"><v:formulas><v:f eqn="sum #0 0 10800"/><v:f eqn="prod #0 2 1"/><v:f eqn="sum 21600 0 @1"/><v:f eqn="sum 0 0 @2"/><v:f eqn="sum 21600 0 @3"/><v:f eqn="if @0 @3 0"/><v:f eqn="if @0 21600 @1"/><v:f eqn="if @0 0 @2"/><v:f eqn="if @0 @4 21600"/><v:f eqn="mid @5 @6"/><v:f eqn="mid @8 @5"/><v:f eqn="mid @7 @8"/><v:f eqn="mid @6 @7"/><v:f eqn="sum @6 0 @5"/></v:formulas><v:path textpathok="t" o:connecttype="custom" o:connectlocs="@9,0;@10,10800;@11,21600;@12,10800" o:connectangles="270,180,90,0"/><v:textpath on="t" fitshape="t"/><v:handles><v:h position="#0,bottomRight" xrange="6629,14971"/></v:handles><o:lock v:ext="edit" text="t" shapetype="t"/></v:shapetype><v:shape id="PowerPlusWaterMarkObject1" o:spid="_x0000_s2049" type="#_x0000_t136" style="position:absolute;margin-left:0;margin-top:0;width:${s}pt;height:${a}pt;${l}z-index:-251654144;mso-position-horizontal:center;mso-position-horizontal-relative:margin;mso-position-vertical:center;mso-position-vertical-relative:margin" o:allowincell="f" fillcolor="${o(t.color)}" stroked="f"><v:fill opacity="${t.opacity===Li?Tr:t.opacity}"/><v:textpath style="font-family:"Calibri";font-size:${d}" string="${o(t.text)}"/></v:shape></w:pict></w:r></w:p>`;let h=!1;for(const f of n){const b=await i.file(f).async("text");if(b.includes("v:textpath"))continue;const u=b.replace(/(<w:hdr[^>]*>)/,`$1${p}`);u!==b&&(i.file(f,u),h=!0)}if(!h)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.loadZipFromBlob(e),i=t.file("word/styles.xml");if(!i)return e;let n=await i.async("text");const o=r.match(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/)?.[0];o&&(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/.test(n)?n=n.replace(/<w:docDefaults\b[\s\S]*?<\/w:docDefaults>/,o):n=n.replace(/(<w:styles\b[^>]*>)/,`$1${o}`));const s=new Map;for(const u of r.matchAll(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g)){const g=u[0].match(/w:styleId="([^"]+)"/);g&&s.set(g[1],u[0])}if(s.size===0&&!o)return e;const a=new Set;n=n.replace(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g,u=>{const g=u.match(/w:styleId="([^"]+)"/),w=g?s.get(g[1]):void 0;return w?(a.add(g[1]),w):u});const l=[];for(const[u,g]of s)a.has(u)||l.push(g);n=n.replace(/<\/w:styles>/,`${l.join("")}</w:styles>`);const d=new Set,p=u=>{for(const g of u.matchAll(/<w:(?:pStyle|rStyle|tblStyle)\b[^>]*w:val="([^"]+)"/g))d.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)){const g=u[0].match(/w:styleId="([^"]+)"/);g&&h.set(g[1],u[0])}const m=(u,g)=>s.has(u)||/w:default="(?:1|true)"/.test(g.slice(0,g.indexOf(">")))||d.has(u);let f=!0;for(;f;){f=!1;for(const[u,g]of h)if(m(u,g))for(const w of g.matchAll(/<w:(?:basedOn|link|next)\b[^>]*w:val="([^"]+)"/g))d.has(w[1])||(d.add(w[1]),f=!0)}n=n.replace(/<w:style\b[^>]*>[\s\S]*?<\/w:style>/g,u=>{const g=u.match(/w:styleId="([^"]+)"/);return!g||m(g[1],u)?u:""}),t.file("word/styles.xml",n);const b=await this.generateCompressedZipBlob(t);return new Blob([b],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchCoreProperties(e,r){const t=await this.loadZipFromBlob(e),i=t.file("docProps/core.xml");if(!i)return e;let n=await i.async("text");const o=l=>l.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");for(const l of["created","modified"]){const d=r[l];if(!d)continue;const p=new RegExp(`(<dcterms:${l}\\b[^>]*>)[^<]*(</dcterms:${l}>)`);p.test(n)?n=n.replace(p,`$1${o(d)}$2`):n=n.replace(/<\/cp:coreProperties>/,`<dcterms:${l} xsi:type="dcterms:W3CDTF">${o(d)}</dcterms:${l}></cp:coreProperties>`)}const s=/<cp:revision>[^<]*<\/cp:revision>/;if(r.revision){const l=`<cp:revision>${o(r.revision)}</cp:revision>`;n=s.test(n)?n.replace(s,l):n.replace(/<\/cp:coreProperties>/,`${l}</cp:coreProperties>`)}else n=n.replace(s,"");for(const[l,d]of[["creator","dc:creator"],["lastModifiedBy","cp:lastModifiedBy"]])r[l]||(n=n.replace(new RegExp(`<${d}>[^<]*</${d}>`),""));t.file("docProps/core.xml",n);const a=await this.generateCompressedZipBlob(t);return new Blob([a],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async stampApplicationProperty(e){const r=await this.loadZipFromBlob(e),t=r.file("docProps/app.xml");if(!t)return e;let i=await t.async("text");const n="<Application>Revise (revise.io)</Application>";if(/<Application[\s>]/.test(i))return e;if(/<Properties\b[^>]*\/>/.test(i))i=i.replace(/<Properties\b([^>]*)\/>/,`<Properties$1>${n}</Properties>`);else if(i.includes("</Properties>"))i=i.replace("</Properties>",`${n}</Properties>`);else return e;r.file("docProps/app.xml",i);const o=await this.generateCompressedZipBlob(r);return new Blob([o],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async appendCommentsExtendedPart(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/comments.xml");if(!i)return e;let n=await i.async("text");n.includes("xmlns:w14=")||(n=n.replace(/<w:comments /,'<w:comments xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" '));const o=p=>(268435456+p).toString(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 b=o(parseInt(f[1],10)),u=m.lastIndexOf("<w:p");if(u===-1)return p;const g=m.slice(0,u)+m.slice(u).replace(/<w:p(\s|>)/,`<w:p w14:paraId="${b}"$1`);return`<w:comment${h}>${g}</w:comment>`}),t.file("word/comments.xml",n);const s='<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w15:commentsEx xmlns:w15="http://schemas.microsoft.com/office/word/2012/wordml">'+r.map(({numericId:p,resolved:h,parentNumericId:m})=>`<w15:commentEx ${[`w15:paraId="${o(p)}"`,...m!==void 0?[`w15:paraIdParent="${o(m)}"`]:[],`w15:done="${h?"1":"0"}"`].join(" ")}/>`).join("")+"</w15:commentsEx>";t.file("word/commentsExtended.xml",s);const a=t.file("[Content_Types].xml");if(a){let p=await a.async("text");p.includes("/word/commentsExtended.xml")||(p=p.replace("</Types>",'<Override PartName="/word/commentsExtended.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml"/></Types>'),t.file("[Content_Types].xml",p))}const l=t.file("word/_rels/document.xml.rels");if(l){let p=await l.async("text");p.includes("commentsExtended.xml")||(p=p.replace("</Relationships>",'<Relationship Id="rIdRvseCommentsEx" Type="http://schemas.microsoft.com/office/2011/relationships/commentsExtended" Target="commentsExtended.xml"/></Relationships>'),t.file("word/_rels/document.xml.rels",p))}const d=await this.generateCompressedZipBlob(t);return new Blob([d],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async appendEndnotesPart(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;let n=await i.async("text");for(const{index:u}of r){const g=`__RVSE_EN_${u}__`;for(const w of["w:t","w:delText"])n=n.replaceAll(`<${w} xml:space="preserve">${g}</${w}>`,`<w:endnoteReference w:id="${u}"/>`).replaceAll(`<${w}>${g}</${w}>`,`<w:endnoteReference w:id="${u}"/>`)}t.file("word/document.xml",n);const o=new Map;let s='<w:endnotes xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">';const a=t.file("word/footnotes.xml");if(a){let u=await a.async("text");const g=u.match(/<w:footnotes\b[^>]*>/)?.[0];g&&(s=g.replace(/<w:footnotes\b/,"<w:endnotes"));const w=new Set(r.map(T=>T.syntheticFootnoteId).filter(T=>T!==void 0));u=u.replace(/<w:footnote\b[^>]*>[\s\S]*?<\/w:footnote>/g,T=>{const F=/\bw:id="(-?\d+)"/.exec(T)?.[1],B=F?Number(F):NaN;if(!w.has(B))return T;const P=r.find(E=>E.syntheticFootnoteId===B);if(!P)return T;const z=T.replace(/^<w:footnote\b[^>]*>/,`<w:endnote w:id="${P.index}">`).replace(/<\/w:footnote>$/,"</w:endnote>").replaceAll("w:footnoteRef","w:endnoteRef").replaceAll("FootnoteReference","EndnoteReference").replaceAll("FootnoteText","EndnoteText");return o.set(B,z),""}),t.file("word/footnotes.xml",u);const S=t.file("word/_rels/footnotes.xml.rels");S&&t.file("word/_rels/endnotes.xml.rels",await S.async("text"))}const l=u=>u.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),d=(u,g)=>{const w=u.marks??{},S=[];if(w.bold&&S.push("<w:b/>"),w.italic&&S.push("<w:i/>"),w.underline&&S.push('<w:u w:val="single"/>'),w.strikethrough&&S.push("<w:strike/>"),w.doubleStrikethrough&&S.push("<w:dstrike/>"),w.smallCaps&&S.push("<w:smallCaps/>"),w.allCaps&&S.push("<w:caps/>"),w.hidden&&S.push("<w:vanish/>"),w.color&&S.push(`<w:color w:val="${l(this.normalizeColor(w.color))}"/>`),w.backgroundColor&&S.push(`<w:highlight w:val="${l(w.backgroundColor)}"/>`),typeof w.fontSize=="number"&&w.fontSize>0&&S.push(`<w:sz w:val="${Math.max(2,Math.round(w.fontSize*this.DOCX_HALF_POINTS_PER_PX))}"/>`),w.fontFamily){const F=l(w.fontFamily.split(",")[0].replaceAll('"',"").replaceAll("'","").trim());S.push(`<w:rFonts w:ascii="${F}" w:hAnsi="${F}"/>`)}typeof w.letterSpacing=="number"&&Number.isFinite(w.letterSpacing)&&w.letterSpacing!==0&&S.push(`<w:spacing w:val="${Math.round(w.letterSpacing*15)}"/>`),w.superscript?S.push('<w:vertAlign w:val="superscript"/>'):w.subscript&&S.push('<w:vertAlign w:val="subscript"/>'),w.lang&&S.push(`<w:lang w:val="${l(w.lang)}"/>`);const T=g&&!/^\s/.test(u.text??"")?` ${u.text??""}`:u.text??"";return`<w:r>${S.length>0?`<w:rPr>${S.join("")}</w:rPr>`:""}<w:t xml:space="preserve">${l(T)}</w:t></w:r>`},p=r.sort((u,g)=>u.index-g.index).map(({index:u,note:g,syntheticFootnoteId:w})=>{const S=w!==void 0?o.get(w):void 0;if(S)return S;const T=g.children.filter(F=>F.type==="paragraph").map((F,B)=>'<w:p><w:pPr><w:pStyle w:val="EndnoteText"/></w:pPr><w:r><w:rPr><w:rStyle w:val="EndnoteReference"/></w:rPr><w:endnoteRef/></w:r>'+(F.children.filter(P=>(P.text??"")!=="").map((P,z)=>d(P,B===0&&z===0)).join("")||'<w:r><w:t xml:space="preserve"> </w:t></w:r>')+"</w:p>").join("");return`<w:endnote w:id="${u}">${T}</w:endnote>`}).join(""),h='<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'+s+'<w:endnote w:type="separator" w:id="-1"><w:p><w:r><w:separator/></w:r></w:p></w:endnote><w:endnote w:type="continuationSeparator" w:id="0"><w:p><w:r><w:continuationSeparator/></w:r></w:p></w:endnote>'+p+"</w:endnotes>";t.file("word/endnotes.xml",h);const m=t.file("[Content_Types].xml");if(m){let u=await m.async("text");u.includes("/word/endnotes.xml")||(u=u.replace("</Types>",'<Override PartName="/word/endnotes.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml"/></Types>'),t.file("[Content_Types].xml",u))}const f=t.file("word/_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/officeDocument/2006/relationships/endnotes" Target="endnotes.xml"/></Relationships>'),t.file("word/_rels/document.xml.rels",u))}const b=await this.generateCompressedZipBlob(t);return new Blob([b],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static emittedBodySlotCount(e){switch(e.type){case"paragraph":case"table":case"code":case"math":case"image":case"page-break":case"section-break":return 1;case"list":return e.children.filter(r=>r.type==="list-item").length;default:return 0}}static async applySdtWrappers(e,r){const t=r.sdtWrappers??[];if(t.length===0)return e;const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const o=await n.async("text"),s=this.parseDocumentXml(o);if(!s)return e;const a=s.getElementsByTagName("w:body")[0];if(!a)return e;const l="http://schemas.openxmlformats.org/wordprocessingml/2006/main",d=Array.from(a.children).filter($=>$.tagName==="w:p"||$.tagName==="w:tbl"),p=r.children.filter($=>$.type!=="footnote"&&$.type!=="header-footer"),h=new Map,m=[];let f=!0;{let $=0;p.forEach((v,D)=>{v.id&&h.set(v.id,D),m[D]=$,$+=this.emittedBodySlotCount(v)}),$!==d.length&&(console.warn(`docx export: content-control slot accounting mismatch (${$} computed vs ${d.length} body elements); exporting without sdt wrappers`),f=!1)}const b=$=>{if($.blockIds&&$.blockIds.length>0)return $.blockIds;const v=$.startBlockId?h.get($.startBlockId):void 0;if(v===void 0)return[];const D=Math.min(v+Math.max(1,$.blockCount??1),p.length);return p.slice(v,D).map(M=>M.id).filter(M=>!!M)};let u=!1;const g=new Map(t.map($=>[$.id,$])),w=$=>this.parseDocumentXml(`<w:root xmlns:w="${l}">${$.prXml}</w:root>`)?.getElementsByTagName("w:sdtPr")[0]??void 0,S=($,v)=>{const D=$[0].parentNode;if(!D)return;const M=s.createElementNS(l,"w:sdt"),x=s.createElementNS(l,"w:sdtContent");D.insertBefore(M,$[0]),M.appendChild(s.importNode(v,!0)),M.appendChild(x);for(const R of $)x.appendChild(R);u=!0};{const $=Array.from(s.getElementsByTagName("w:bookmarkStart")).filter(v=>(v.getAttribute("w:name")??"").startsWith("__rvSdt:"));if($.length>0){const v=new Map;for(const x of Array.from(s.getElementsByTagName("w:bookmarkEnd"))){const R=x.getAttribute("w:id");R&&v.set(R,x)}const D=x=>{x.parentNode&&(x.parentNode.removeChild(x),u=!0)},M=[];for(const x of $){const R=(x.getAttribute("w:name")??"").slice(8).split(":")[0],X=v.get(x.getAttribute("w:id")??""),L=g.get(R);if(!X||!L||L.scope!=="inline"||X.parentNode!==x.parentNode||!x.parentNode){D(x),X&&D(X);continue}let W=0;for(let U=x.nextSibling;U&&U!==X;U=U.nextSibling)W++;M.push({record:L,start:x,end:X,covered:W})}M.sort((x,R)=>x.covered-R.covered);for(const x of M){const R=x.start.parentNode===x.end.parentNode&&x.start.parentNode?w(x.record):void 0;if(R){const X=[];for(let L=x.start.nextSibling;L&&L!==x.end;L=L.nextSibling)L.nodeType===1&&X.push(L);X.length>0&&S(X,R)}D(x.start),D(x.end)}}}const T=new Map,F=new Map,B=new Map;f&&p.forEach(($,v)=>{if($.type!=="table")return;const D=d[m[v]];if(!D||D.tagName!=="w:tbl")return;B.set(v,Array.from(D.children).filter(R=>R.tagName==="w:tr"));const M=$,x=qe(M);M.children.forEach((R,X)=>{R.id&&T.set(R.id,{tableIndex:v,rowIndex:X});for(const L of R.children)L.id&&F.set(L.id,{tableIndex:v,rowIndex:X,gridCol:x.byId.get(L.id)?.col??0})})});for(const $ of t){if($.scope!=="cell")continue;if(!f)break;const v=($.blockIds??[]).map(x=>F.get(x)).filter(x=>!!x);if(v.length===0){console.warn(`docx export: content control ${$.id} has no surviving member blocks; dropping wrapper`);continue}const D=w($);if(!D)continue;const M=new Map;for(const x of v){const R=`${x.tableIndex}:${x.rowIndex}`;M.set(R,[...M.get(R)??[],x])}for(const x of M.values()){const R=B.get(x[0].tableIndex)?.[x[0].rowIndex];if(!R)continue;const X=new Set(x.map(I=>I.gridCol)),L=Array.from(R.children).filter(I=>I.tagName==="w:tc"),W=[];let U=0;if(L.forEach((I,_)=>{X.has(U)&&W.push(_);const j=this.getDirectChild(I,"w:tcPr"),q=j?this.getDirectChild(j,"w:gridSpan")?.getAttribute("w:val"):void 0,Z=q?parseInt(q,10):1;U+=Number.isFinite(Z)&&Z>0?Z:1}),W.length===0)continue;const J=W[0],ee=W[W.length-1];S(L.slice(J,ee+1),D)}}for(const $ of t){if($.scope!=="row")continue;if(!f)break;const v=($.blockIds??[]).map(L=>T.get(L)).filter(L=>!!L);if(v.length===0){console.warn(`docx export: content control ${$.id} has no surviving member blocks; dropping wrapper`);continue}const D=w($);if(!D)continue;const M=v[0].tableIndex,x=B.get(M);if(!x)continue;const R=v.filter(L=>L.tableIndex===M).map(L=>L.rowIndex).sort((L,W)=>L-W),X=x.slice(R[0],R[R.length-1]+1).filter(L=>!!L.parentNode);X.length>0&&S(X,D)}const P=$=>{let v=0;const D=new Set([$.id]);let M=$;for(;M?.parentId&&!D.has(M.parentId);)D.add(M.parentId),M=g.get(M.parentId),M&&v++;return v},z=t.filter($=>!$.scope||$.scope==="block").sort(($,v)=>P(v)-P($));for(const $ of z){if(!f)break;const v=b($).map(W=>h.get(W)).filter(W=>W!==void 0).sort((W,U)=>W-U);if(v.length===0){console.warn(`docx export: content control ${$.id} has no surviving member blocks; dropping wrapper`);continue}const D=v[0],M=v[v.length-1],x=m[D];let R=0;for(let W=D;W<=M;W++)R+=this.emittedBodySlotCount(p[W]);if(R===0)continue;const X=[];for(const W of d.slice(x,x+R)){let U=W;for(;U.parentNode&&U.parentNode!==a&&U.parentNode.nodeType===1;)U=U.parentNode;U.parentNode===a&&!X.includes(U)&&X.push(U)}if(X.length===0)continue;const L=w($);L&&S(X,L)}if(!u)return e;const E=new XMLSerializer().serializeToString(s);i.file("word/document.xml",E);const G=await this.generateCompressedZipBlob(i);return new Blob([G],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchParagraphMarkRevisions(e,r,t){const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const o=await n.async("text"),s="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=new DOMParser().parseFromString(o,"application/xml"),l=a.getElementsByTagName("w:body")[0];if(!l)return e;const d=[];for(let m=0;m<l.children.length;m++)l.children[m].tagName==="w:p"&&d.push(l.children[m]);for(const m of r){const f=d[m.pIndex];if(!f)continue;let b=this.getDirectChild(f,"w:pPr");b||(b=a.createElementNS(s,"w:pPr"),f.insertBefore(b,f.firstChild));let u=this.getDirectChild(b,"w:rPr");if(!u){u=a.createElementNS(s,"w:rPr");const w=this.getDirectChild(b,"w:sectPr");w?b.insertBefore(u,w):b.appendChild(u)}const g=a.createElementNS(s,m.kind==="split"||m.kind==="insert"?"w:ins":"w:del");g.setAttributeNS(s,"w:id",String(t(m.importedId))),g.setAttributeNS(s,"w:author",m.author),g.setAttributeNS(s,"w:date",m.date),u.insertBefore(g,u.firstChild)}const p=new XMLSerializer().serializeToString(a);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){const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const o=await n.async("text"),s="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=new DOMParser().parseFromString(o,"application/xml"),l=a.getElementsByTagName("w:body")[0];if(!l)return e;const d=[];for(let f=0;f<l.children.length;f++)l.children[f].tagName==="w:p"&&d.push(l.children[f]);const p=(f,b)=>{const u=a.createElementNS(s,f);for(const[g,w]of Object.entries(b??{}))u.setAttributeNS(s,g,w);return u};for(const f of r){const b=d[f.pIndex];if(!b)continue;let u=this.getDirectChild(b,"w:pPr");u||(u=a.createElementNS(s,"w:pPr"),b.insertBefore(u,b.firstChild));const g=p("w:pPrChange",{"w:id":String(t(f.importedId)),"w:author":f.author,"w:date":f.date}),w=f.prior,S=a.createElementNS(s,"w:pPr");if(w.styleId&&S.appendChild(p("w:pStyle",{"w:val":w.styleId})),w.keepNext&&S.appendChild(p("w:keepNext")),w.keepLines&&S.appendChild(p("w:keepLines")),w.widowControl===!1&&S.appendChild(p("w:widowControl",{"w:val":"0"})),w.bordersJson)try{const T=JSON.parse(w.bordersJson),F=a.createElementNS(s,"w:pBdr");for(const B of["top","left","bottom","right"]){const P=T[B];P&&F.appendChild(p(`w:${B}`,{"w:val":P.style||"single","w:sz":String(Math.max(2,Math.round((P.width??.5)*6))),"w:space":"1","w:color":(P.color||"#000000").replace(/^#/,"")}))}F.children.length>0&&S.appendChild(F)}catch{}w.shadingFill&&S.appendChild(p("w:shd",{"w:val":"clear","w:fill":this.toDocxHex(w.shadingFill)??"auto"})),w.direction&&S.appendChild(p("w:bidi",w.direction==="ltr"?{"w:val":"0"}:{})),w.lineSpacing!==void 0&&S.appendChild(p("w:spacing",{"w:line":String(Math.round(w.lineSpacing*240)),"w:lineRule":"auto"})),(w.leftIndentTwips!==void 0||w.firstLineIndentTwips!==void 0)&&S.appendChild(p("w:ind",{...w.leftIndentTwips!==void 0?{"w:left":String(w.leftIndentTwips)}:{},...w.firstLineIndentTwips!==void 0?{"w:firstLine":String(w.firstLineIndentTwips)}:{}})),w.align&&S.appendChild(p("w:jc",{"w:val":w.align==="justify"?"both":w.align})),g.appendChild(S),u.appendChild(g)}const h=new XMLSerializer().serializeToString(a);i.file("word/document.xml",h);const m=await this.generateCompressedZipBlob(i);return new Blob([m],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchLinkedMoveRevisions(e,r){const t=await this.loadZipFromBlob(e),i=t.file("word/document.xml");if(!i)return e;const n=await i.async("text"),o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",s=new DOMParser().parseFromString(n,"application/xml"),a=(p,h)=>{const m=s.createElementNS(o,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=s.createElementNS(o,p);return f.setAttributeNS(o,"w:id",h.rangeId),m&&(f.setAttributeNS(o,"w:name",h.name),f.setAttributeNS(o,"w:author",h.author),f.setAttributeNS(o,"w:date",h.date)),f};for(const p of r){const h=p.role==="from"?"w:del":"w:ins",m=p.role==="from"?"w:moveFrom":"w:moveTo",f=new Set(p.wrapperIds.map(String)),b=Array.from(s.getElementsByTagName(h)).filter(T=>f.has(T.getAttribute("w:id")??""));if(b.length!==f.size)throw new Error(`linked move ${p.name}/${p.role}: expected ${f.size} temporary revision wrappers, found ${b.length}`);const u=b.map(T=>a(T,m)),g=u[0],w=u[u.length-1],S=p.role==="from"?"w:moveFromRange":"w:moveToRange";g.parentNode?.insertBefore(l(`${S}Start`,p,!0),g),w.parentNode?.insertBefore(l(`${S}End`,p,!1),w.nextSibling)}t.file("word/document.xml",new XMLSerializer().serializeToString(s));const d=await this.generateCompressedZipBlob(t);return new Blob([d],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static async patchTableRevisions(e,r,t){const i=await this.loadZipFromBlob(e),n=i.file("word/document.xml");if(!n)return e;const o=await n.async("text"),s="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=new DOMParser().parseFromString(o,"application/xml"),l=a.getElementsByTagName("w:body")[0];if(!l)return e;const d=Array.from(l.getElementsByTagName("w:tbl")),p=(v,D)=>Array.from(v.children).filter(M=>M.tagName===D),h=(v,D)=>{const M=this.getDirectChild(v,D);if(M)return M;const x=a.createElementNS(s,D);return v.insertBefore(x,v.firstChild),x},m=(v,D)=>{const M=new DOMParser().parseFromString(v,"application/xml");if(!(M.getElementsByTagName("parsererror").length>0||M.documentElement?.tagName!==D))return a.importNode(M.documentElement,!0)},f=(v,D)=>{const M=m(D,"w:tblGrid");if(!M)return this.getDirectChild(v,"w:tblGrid");const x=this.getDirectChild(v,"w:tblGrid");if(x)x.replaceWith(M);else{const R=this.getDirectChild(v,"w:tblPr");v.insertBefore(M,R?.nextSibling??v.firstChild)}return M},b=(v,D)=>{const M=m(D,"w:tblPrEx");if(!M)return this.getDirectChild(v,"w:tblPrEx");const x=this.getDirectChild(v,"w:tblPrEx");return x?x.replaceWith(M):v.insertBefore(M,v.firstChild),M},u=(v,D,M)=>{const x=m(M,D);if(!x)return h(v,D);const R=this.getDirectChild(v,D);return R?R.replaceWith(x):v.insertBefore(x,v.firstChild),x},g={"w:tblPr":["w:tblStyle","w:tblpPr","w:tblOverlap","w:bidiVisual","w:tblStyleRowBandSize","w:tblStyleColBandSize","w:tblW","w:jc","w:tblCellSpacing","w:tblInd","w:tblBorders","w:shd","w:tblLayout","w:tblCellMar","w:tblLook","w:tblCaption","w:tblDescription","w:tblPrChange"],"w:trPr":["w:cnfStyle","w:divId","w:gridBefore","w:gridAfter","w:wBefore","w:wAfter","w:cantSplit","w:trHeight","w:tblHeader","w:tblCellSpacing","w:jc","w:hidden","w:ins","w:del","w:trPrChange"],"w:tcPr":["w:cnfStyle","w:tcW","w:gridSpan","w:hMerge","w:vMerge","w:tcBorders","w:shd","w:noWrap","w:tcMar","w:textDirection","w:tcFitText","w:vAlign","w:hideMark","w:headers","w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"]},w=(v,D,M,x)=>{const R=h(v,D),X=m(M,D);if(!X)return R;const L=[],W=Array.from(R.children),U=Array.from(X.children),J=new Set([...W.map(_=>_.tagName),...U.map(_=>_.tagName)]);for(const _ of J){const j=x.has(_)?W:U.some(q=>q.tagName===_)?U:W;for(const q of j.filter(Z=>Z.tagName===_))L.push(a.importNode(q,!0))}const ee=new Map(g[D].map((_,j)=>[_,j]));L.sort((_,j)=>(ee.get(_.tagName)??Number.MAX_SAFE_INTEGER)-(ee.get(j.tagName)??Number.MAX_SAFE_INTEGER));const I=a.createElementNS(s,D);for(const _ of Array.from(X.attributes))I.setAttributeNS(_.namespaceURI,_.name,_.value);for(const _ of L)I.appendChild(_);return R.replaceWith(I),I},S=new Map,T=(v,D)=>{const M=a.createElementNS(s,v),x=S;let R;return D.importedId===void 0&&D.revisionGroup&&(R=x.get(D.revisionGroup),R===void 0&&(R=t(),x.set(D.revisionGroup,R))),M.setAttributeNS(s,"w:id",String(D.importedId!==void 0?D.importedId:R??t())),M.setAttributeNS(s,"w:author",D.author),M.setAttributeNS(s,"w:date",D.date),M},F=(v,D)=>{let M=0;for(const x of p(v,"w:tc")){if(M===D)return x;const R=this.getDirectChild(x,"w:tcPr"),X=R?this.getDirectChild(R,"w:gridSpan")?.getAttribute("w:val"):void 0,L=X?Number(X):1;M+=Number.isFinite(L)&&L>0?L:1}},B=(v,D)=>{const M=er(D);if(!M)return;const x=a.createElementNS(s,"w:tblBorders"),R=[["top","top"],["bottom","bottom"],["left","left"],["right","right"],["insideH","insideH"],["insideV","insideV"]];for(const[X,L]of R){const W=M[X];if(!W)continue;const U=a.createElementNS(s,`w:${L}`);U.setAttributeNS(s,"w:val",W.style),U.setAttributeNS(s,"w:sz",String(Math.max(0,Math.round(W.width*6)))),U.setAttributeNS(s,"w:color",W.color.replace(/^#/,"")),x.appendChild(U)}x.children.length>0&&v.appendChild(x)},P=(v,D,M)=>{for(const x of p(v,D))x.remove();M&&v.appendChild(M)},z=(v,D)=>{const M=er(D);if(!M)return;const x=a.createElementNS(s,v),R=[["top","top"],["bottom","bottom"],["left","left"],["right","right"],...v==="w:tblBorders"?[["insideH","insideH"],["insideV","insideV"]]:[]];for(const[X,L]of R){const W=M[X];if(!W)continue;const U=a.createElementNS(s,`w:${L}`);U.setAttributeNS(s,"w:val",W.style),U.setAttributeNS(s,"w:sz",String(Math.max(0,Math.round(W.width*6)))),U.setAttributeNS(s,"w:color",W.color.replace(/^#/,"")),x.appendChild(U)}return x.children.length>0?x:void 0},E=(v,D)=>{let M;if(typeof D=="number"&&Number.isFinite(D))M={top:D,right:D,bottom:D,left:D};else if(typeof D=="string")try{M=JSON.parse(D)}catch{return}if(!M)return;const x=a.createElementNS(s,v);for(const R of["top","right","bottom","left"]){const X=M[R];if(!Number.isFinite(X))continue;const L=a.createElementNS(s,`w:${R}`);L.setAttributeNS(s,"w:w",String(Math.round(X*15))),L.setAttributeNS(s,"w:type","dxa"),x.appendChild(L)}return x.children.length>0?x:void 0},G=(v,D,M,x,R,X)=>{const L=J=>Object.prototype.hasOwnProperty.call(M??{},J)||Object.prototype.hasOwnProperty.call(x??{},J);if(D==="w:tblPr"){if(L("tableWidth")){const J=M?.tableWidth;let ee;typeof J=="number"&&Number.isFinite(J)&&(ee=a.createElementNS(s,"w:tblW"),ee.setAttributeNS(s,"w:w",String(Math.round(J*15))),ee.setAttributeNS(s,"w:type","dxa")),P(v,"w:tblW",ee)}if(L("align")){const J=M?.align;let ee;(J==="left"||J==="center"||J==="right")&&(ee=a.createElementNS(s,"w:jc"),ee.setAttributeNS(s,"w:val",J)),P(v,"w:jc",ee)}if(L("borders")&&P(v,"w:tblBorders",typeof M?.borders=="string"?z("w:tblBorders",M.borders):void 0),L("borderColor")||L("borderWidth")){let J=this.getDirectChild(v,"w:tblBorders");if(!J){J=a.createElementNS(s,"w:tblBorders");for(const ee of["top","left","bottom","right","insideH","insideV"]){const I=a.createElementNS(s,`w:${ee}`);I.setAttributeNS(s,"w:val","single"),J.appendChild(I)}v.appendChild(J)}for(const ee of Array.from(J.children)){if(L("borderColor")){const I=M?.borderColor;ee.setAttributeNS(s,"w:color",typeof I=="string"&&I?I.replace(/^#/,""):"auto")}if(L("borderWidth")){const I=M?.borderWidth;ee.setAttributeNS(s,"w:sz",typeof I=="number"&&Number.isFinite(I)?String(Math.max(0,Math.round(I*6))):"4")}}}L("cellPadding")&&P(v,"w:tblCellMar",E("w:tblCellMar",M?.cellPadding))}else if(D==="w:tcPr"){if(L("backgroundColor")){const J=M?.backgroundColor;let ee;typeof J=="string"&&J&&(ee=a.createElementNS(s,"w:shd"),ee.setAttributeNS(s,"w:fill",J.replace(/^#/,""))),P(v,"w:shd",ee)}if(L("verticalAlign")){const J=M?.verticalAlign;let ee;(J==="top"||J==="middle"||J==="bottom")&&(ee=a.createElementNS(s,"w:vAlign"),ee.setAttributeNS(s,"w:val",J==="middle"?"center":J)),P(v,"w:vAlign",ee)}L("borders")&&P(v,"w:tcBorders",typeof M?.borders=="string"?z("w:tcBorders",M.borders):void 0),L("padding")&&P(v,"w:tcMar",E("w:tcMar",M?.padding))}if(D==="w:trPr"&&(J=>Object.prototype.hasOwnProperty.call(R??{},J)||Object.prototype.hasOwnProperty.call(X??{},J))("hasHeader")){const J=R?.hasHeader?a.createElementNS(s,"w:tblHeader"):void 0;P(v,"w:tblHeader",J)}const W=new Map(g[D].map((J,ee)=>[J,ee])),U=Array.from(v.children).sort((J,ee)=>(W.get(J.tagName)??Number.MAX_SAFE_INTEGER)-(W.get(ee.tagName)??Number.MAX_SAFE_INTEGER));for(const J of U)v.appendChild(J)};for(const v of r){const D=d[v.tableIndex];if(!D)continue;const M=p(D,"w:tr");v.propertyOverrides?.table&&w(D,"w:tblPr",v.propertyOverrides.table,new Set(["w:tblW","w:jc","w:tblBorders","w:tblCellMar"])),v.propertyOverrides?.grid&&f(D,v.propertyOverrides.grid);for(const x of v.propertyOverrides?.rows??[]){const R=M[x.rowIndex];R&&w(R,"w:trPr",x.xml,new Set(["w:tblHeader"]))}for(const x of v.propertyOverrides?.rowExceptions??[]){const R=M[x.rowIndex];R&&b(R,x.xml)}for(const x of v.propertyOverrides?.cells??[]){const R=M[x.rowIndex],X=R?F(R,x.gridColumn):void 0;X&&w(X,"w:tcPr",x.xml,new Set(["w:tcW","w:gridSpan","w:vMerge","w:tcBorders","w:shd","w:tcMar","w:vAlign"]))}for(const x of v.rowProperties){const R=M[x.rowIndex];R&&(x.currentXml?u(R,"w:trPr",x.currentXml):G(h(R,"w:trPr"),"w:trPr",x.currentAttributes,x.priorAttributes,x.currentTableAttributes,x.priorTableAttributes))}for(const x of v.rowExceptionProperties){const R=M[x.rowIndex];R&&b(R,x.currentXml)}for(const x of v.cellProperties){const R=M[x.rowIndex],X=R?F(R,x.gridColumn):void 0;X&&(x.currentXml?u(X,"w:tcPr",x.currentXml):G(h(X,"w:tcPr"),"w:tcPr",x.currentAttributes,x.priorAttributes))}for(const x of v.rows){const R=M[x.rowIndex];R&&h(R,"w:trPr").appendChild(T(x.kind==="insert"?"w:ins":"w:del",x))}for(const x of v.cells){const R=M[x.rowIndex],X=R?F(R,x.gridColumn):void 0;X&&h(X,"w:tcPr").appendChild(T(x.kind==="insert"?"w:cellIns":"w:cellDel",x))}for(const x of v.merges){const R=M[x.rowIndex],X=R?F(R,x.gridColumn):void 0;if(!X)continue;const L=T("w:cellMerge",x);x.vMerge&&L.setAttributeNS(s,"w:vMerge",x.vMerge),x.vMergeOrig&&L.setAttributeNS(s,"w:vMergeOrig",x.vMergeOrig),h(X,"w:tcPr").appendChild(L)}if(v.tableGrid){const x=f(D,v.tableGrid.currentXml);if(x){const R=T("w:tblGridChange",v.tableGrid),X=m(v.tableGrid.priorXml,"w:tblGrid");X&&R.appendChild(X),x.appendChild(R)}}for(const x of v.rowProperties){const R=M[x.rowIndex];if(!R)continue;const X=T("w:trPrChange",x),L=h(R,"w:trPr"),W=x.priorXml?m(x.priorXml,"w:trPr"):L.cloneNode(!0);if(W){if(!x.priorXml){for(const U of["w:ins","w:del","w:trPrChange"])for(const J of p(W,U))J.remove();G(W,"w:trPr",x.priorAttributes,x.currentAttributes,x.priorTableAttributes,x.currentTableAttributes)}X.appendChild(W)}L.appendChild(X)}for(const x of v.rowExceptionProperties){const R=M[x.rowIndex];if(!R)continue;const X=this.getDirectChild(R,"w:tblPrEx")??b(R,x.currentXml);if(!X)continue;const L=T("w:tblPrExChange",x),W=m(x.priorXml,"w:tblPrEx");W&&L.appendChild(W),X.appendChild(L)}for(const x of v.cellProperties){const R=M[x.rowIndex],X=R?F(R,x.gridColumn):void 0;if(!X)continue;const L=T("w:tcPrChange",x),W=h(X,"w:tcPr"),U=x.priorXml?m(x.priorXml,"w:tcPr"):W.cloneNode(!0);if(U){if(!x.priorXml){for(const J of["w:cellIns","w:cellDel","w:cellMerge","w:tcPrChange"])for(const ee of p(U,J))ee.remove();G(U,"w:tcPr",x.priorAttributes,x.currentAttributes)}L.appendChild(U)}W.appendChild(L)}if(v.tableProperties){const x=v.tableProperties.currentXml?u(D,"w:tblPr",v.tableProperties.currentXml):h(D,"w:tblPr");v.tableProperties.currentXml||G(x,"w:tblPr",v.tableProperties.currentAttributes,v.tableProperties.priorAttributes);const R=T("w:tblPrChange",v.tableProperties);let X;v.tableProperties.priorXml&&(X=m(v.tableProperties.priorXml,"w:tblPr")),X||(X=x.cloneNode(!0),G(X,"w:tblPr",v.tableProperties.priorAttributes,v.tableProperties.currentAttributes),v.tableProperties.priorBorders&&B(X,v.tableProperties.priorBorders)),R.appendChild(X),x.appendChild(R)}}i.file("word/document.xml",new XMLSerializer().serializeToString(a));const $=await this.generateCompressedZipBlob(i);return new Blob([$],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})}static inferDocumentFontFamily(e){if(!e?.children)return;const r=new Map;let t=0;const i=(s,a)=>{for(const l of s){if(l.type!=="text")continue;const d=l.text.length;if(d===0)continue;t+=d;const p=l.marks?.fontFamily??a;p&&r.set(p,(r.get(p)??0)+d)}};for(const s of e.children)if(s.type==="paragraph"){const a=s;i(s.children,a.fontFamily)}else if(s.type==="list")for(const a of s.children)i(a.children);if(t===0)return;let n,o=0;for(const[s,a]of r)a>o&&(n=s,o=a);return n&&o*2>t?n:void 0}static codeBlockStyleId(e){const r=(e??"").replace(/[^A-Za-z0-9]/g,"");return r?`${this.CODE_BLOCK_STYLE_ID}_${r}`:this.CODE_BLOCK_STYLE_ID}static buildExportHeadingDefaults(){const e=[["heading1",ke.h1],["heading2",ke.h2],["heading3",ke.h3],["heading4",ke.h4],["heading5",ke.h5],["heading6",ke.h6]];return Object.fromEntries(e.map(([r,t])=>[r,{run:{size:this.pxToDocxHalfPoints(t)}}]))}static buildExportParagraphStyles(e){const r=[],t=new Set,i=n=>{for(const o of n)if(o.type==="code"&&!o.renderDiagram)t.add(this.codeBlockStyleId(o.language));else if(o.type==="container"||o.type==="footnote"||o.type==="table-cell")i(o.children);else if(o.type==="table")for(const s of o.children)i(s.children)};if(i(e.children),e.notes&&i(e.notes),t.size>0){r.push({id:this.CODE_BLOCK_STYLE_ID,name:"Code Block",basedOn:"Normal",run:{font:"Courier New",size:this.pxToDocxHalfPoints(ke.code)}});for(const n of t)n!==this.CODE_BLOCK_STYLE_ID&&r.push({id:n,name:`Code Block (${n.slice(this.CODE_BLOCK_STYLE_ID.length+1)})`,basedOn:this.CODE_BLOCK_STYLE_ID})}return r}static buildExportCharacterStyles(){return[{id:this.CODE_INLINE_STYLE_ID,name:"Code Inline",run:{font:"Courier New",highlight:"lightGray"}}]}static toDocxFormat(e){const r=[],t=this.inferDocumentFontFamily(e),i=this.resolveIndentStepPx(e),n=this.buildOrderedNumberingExportPlan(e).byListId;this.exportOrderedPlan=n;for(const o of e.children)o.type==="paragraph"?r.push(this.paragraphToDocx(o,t,i)):o.type==="list"?r.push(...this.listToDocxParagraphs(o,t,n)):o.type==="page-break"?r.push({type:"pagebreak"}):o.type==="toc"&&r.push(...this.tocBlockToDocxParagraphs(o,e));return r}static tocBlockToDocxParagraphs(e,r,t){const i=_i(e),n=Xi(r,Wi(e)),o=Te(r.pageLayout),s=Vt(o),a=Math.max(s.pageWidth-o.marginLeftPx-o.marginRightPx,96),l=e.direction==="rtl",d=this.docxAlignmentForExport({type:"paragraph",id:e.id,children:[],direction:e.direction??"ltr",align:e.align??(l?"right":"left")}),p={bidirectional:l,alignment:d},h=JSON.stringify([{pos:Math.round(a),align:"right",leader:"dot"}]),m=e.fontFamily??this.inferDocumentFontFamily(r),f=this.toDocxHex(e.color),b={...m?{font:m}:{},...e.fontSize?{size:Math.round(e.fontSize*this.DOCX_HALF_POINTS_PER_PX)}:{},...f?{color:f}:{}};if(n.length===0)return[{type:"paragraph",...p,children:[{text:" ",fieldInstr:i,...b}]}];const u=24;return n.map(g=>({type:"paragraph",...p,children:[{text:`${g.text} `,fieldInstr:i,...b,...l?{rightToLeft:!0}:{}},...t?.has(g.blockId)?[{text:String(t.get(g.blockId)),fieldInstr:i,...b,rightToLeft:!1}]:[]],tabStopsJson:h,...g.level>1?{indent:{left:this.pxToTwips((g.level-1)*u)}}:{}}))}static toDocxFormatWithTables(e,r,t,i){const n=[],o=this.inferDocumentFontFamily(e);this.exportDefaultRunSizeHalfPoints=this.inferDefaultRunSizeHalfPoints(e);const s=r||zi,a=this.resolveIndentStepPx(e),l=this.buildOrderedNumberingExportPlan(e).byListId;this.exportOrderedPlan=l;const d=this.styleExportContext(e);for(const m of e.children){const f=n.length;if(m.type==="paragraph")n.push(this.styledParagraphToDocxWithMath(m,o,a,d));else if(m.type==="list")n.push(...this.listToDocxParagraphsWithMath(m,o,l));else if(m.type==="table")n.push(this.tableToDocxWithMath(m,o,a,d));else if(m.type==="code")n.push(this.codeBlockToDocx(m,s));else if(m.type==="math")n.push(this.mathBlockToDocx(m));else if(m.type==="image")n.push(this.imageBlockToDocx(m));else if(m.type==="page-break")n.push({type:"pagebreak"});else if(m.type==="section-break"){const b=m.diffState==="delete"&&m.suggestionId?/^docxrev-(\d+)$/.exec(m.suggestionId):null;n.push({type:"sectionbreak",...m.layout?{layout:m.layout}:{},...m.breakType?{breakType:m.breakType}:{},...m.diffState==="delete"?{pendingDeletion:{author:m.suggestionAuthorName??"Anonymous",date:new Date(m.suggestionCreatedAt??Date.now()).toISOString(),...b?{importedId:Number(b[1])}:{}}}:{}})}else m.type==="toc"?n.push(...this.tocBlockToDocxParagraphs(m,e,t)):m.type==="docx-raw"&&(nr(m.xml)?n.push(this.styledParagraphToDocxWithMath({type:"paragraph",id:m.id,children:[{type:"text",text:""}]},o,a,d)):n.push({type:"docxraw",sourceBlockId:m.id,xml:m.xml,origin:m.origin,emitsParagraph:m.origin==="run"}));i?.push({blockId:m.id,start:f,count:n.length-f})}const p=this.pxToTwips(Te(e.pageLayout).blockSpacingPx),h=m=>{for(const f of m.rows)for(const b of f.cells){for(const u of b.paragraphs)u.spacingAfterTwips??(u.spacingAfterTwips=p),u.spacingBeforeTwips??(u.spacingBeforeTwips=0);for(const u of b.blocks??[])u.type==="paragraph"?(u.spacingAfterTwips??(u.spacingAfterTwips=p),u.spacingBeforeTwips??(u.spacingBeforeTwips=0)):h(u)}};for(const m of n)m.type==="paragraph"?m.styleProvidesSpacing||(m.spacingAfterTwips??(m.spacingAfterTwips=p),m.spacingBeforeTwips??(m.spacingBeforeTwips=0)):m.type==="table"&&h(m);return n}static applyExportParagraphSpacing(e,r){typeof r.spaceBefore=="number"&&(e.spacingBeforeTwips=this.pxToTwips(r.spaceBefore)),typeof r.spaceAfter=="number"&&(e.spacingAfterTwips=this.pxToTwips(r.spaceAfter)),r.contextualSpacing&&(e.contextualSpacing=!0)}static latexToOmml(e,r){const t=Nr();if(!t)return"";try{const i=t.renderToString(e,{output:"mathml",displayMode:r,throwOnError:!1});let n=xn(i);return r&&(n=n.replace(zr,'<m:oMathPara xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"><m:oMath>'),n=n.replace(/<\/m:oMath>$/,"</m:oMath></m:oMathPara>")),n}catch{return""}}static mathBlockToDocx(e){const r=e.displayMode!=="inline",t=e.align||"center",i=this.latexToOmml(e.content,r);return{type:"mathblock",content:e.content,displayMode:r,alignment:t,omml:i||void 0}}static imageBlockToDocx(e){return{type:"image",src:e.src,width:e.width,height:e.height,alt:e.alt,align:e.align,originalFormat:e.originalFormat,originalDataUrl:e.originalDataUrl,anchorXml:e.anchorXml}}static buildParagraphIndent(e,r){const t=e.leftIndent===0?0:Hi(e.leftIndent),i=e.firstLineIndent===0?0:ji(e.firstLineIndent),n={};return t!==void 0&&(n.left=this.pxToTwips(Yt(t,r))),i!==void 0&&(i<0?n.hanging=this.pxToTwips(Yt(-i,r)):n.firstLine=this.pxToTwips(Yt(i,r))),Object.keys(n).length>0?n:void 0}static tableToDocx(e,r){const t=qe(e);return{type:"table",rows:e.children.map((i,n)=>{const o=e.hasHeader&&n===0;return{cells:i.children.map(s=>{const a=[],l=[];for(const p of s.children)if(p.type==="paragraph"){const h=this.paragraphToDocx(p,r);a.push(h),l.push(h)}else if(p.type==="list"){const h=this.listToDocxParagraphs(p,r,this.exportOrderedPlan);a.push(...h),l.push(...h)}else p.type==="table"&&l.push(this.tableToDocx(p,r));const d=t.byId.get(s.id);return{paragraphs:a,...l.some(p=>p.type==="table")?{blocks:l}:{},backgroundColor:s.backgroundColor,verticalAlign:s.verticalAlign,borders:s.borders,padding:s.padding,colSpan:d&&d.colSpan>1?d.colSpan:void 0,rowSpan:d&&d.rowSpan>1?d.rowSpan:void 0,gridColumn:d?.col,...s.oxmlTcPr?{oxmlTcPr:s.oxmlTcPr}:{}}}),isHeader:o,...i.oxmlAttrs?{oxmlAttrs:i.oxmlAttrs}:{},...i.oxmlTrPr?{oxmlTrPr:i.oxmlTrPr}:{}}}),columnWidths:e.columnWidths||[],hasHeader:e.hasHeader,tableWidth:e.tableWidth,align:e.align,cellPadding:e.cellPadding,borders:e.borders,borderWidth:e.borderWidth,borderColor:e.borderColor,...e.oxmlTblPr?{oxmlTblPr:e.oxmlTblPr}:{}}}static codeBlockToDocx(e,r){const t=e.content||"",i=e.language||"",n=Gi(i);if(n&&e.renderDiagram!==!1&&n){const a=Ji({protocol:n,source:t,theme:Ui(),maxWidth:900});return{type:"codeblock",content:"",language:i,runs:[],backgroundColor:r.background,renderDiagram:!0,diagramPngDataUrl:a?.dataUrl,diagramWidth:a?.width,diagramHeight:a?.height}}const o=i?Zi(t,i,r):null,s=[];if(o&&o.length>0)for(const a of o){const l=a.text.split(`
|
|
7
|
+
`);for(let d=0;d<l.length;d++)l[d]&&s.push({text:l[d],font:"Courier New",color:this.normalizeColor(a.color)}),d<l.length-1&&s.push({text:`
|
|
8
|
+
`,font:"Courier New",break:!0})}else{const a=t.split(`
|
|
9
|
+
`);for(let l=0;l<a.length;l++)a[l]&&s.push({text:a[l],font:"Courier New",color:this.normalizeColor(r.default)}),l<a.length-1&&s.push({text:`
|
|
10
|
+
`,font:"Courier New",break:!0})}return{type:"codeblock",content:t,language:i,styleId:this.codeBlockStyleId(i),runs:s,backgroundColor:r.background,renderDiagram:!1}}static createStyleMarksResolver(e){const r=e.stylesXml;if(!r)return;let t;const i=new Map;return n=>{if(!n)return;const o=i.get(n);if(o)return o;t??(t=this.parseStylesXml(r));const s=this.resolveRunMarks(void 0,n,{styles:t});return i.set(n,s),s}}static styleExportContext(e){return{stylesheet:e.stylesheet,styleMarksFor:this.createStyleMarksResolver(e)}}static styledParagraphToDocxWithMath(e,r,t,i){const n=e.styleId?Ki(i.stylesheet,e.styleId)?.paragraphAttrs:void 0,o=this.stripStyleProvidedParagraphAttrs(e,n),s=i.styleMarksFor?.(e.styleId),a=this.paragraphToDocxWithMath(o,s?.fontFamily?void 0:r,t,s);return o.spaceAfter===void 0&&e.spaceAfter!==void 0&&(a.styleProvidesSpacing=!0),a}static stripStyleProvidedParagraphAttrs(e,r){if(!r)return e;const t={...e},i=(n,o)=>n!==void 0&&o!==void 0&&Math.abs(n-o)<.011;return t.align!==void 0&&t.align===r.align&&delete t.align,i(t.lineSpacing,r.lineSpacing)&&delete t.lineSpacing,i(t.spaceBefore,r.spaceBefore)&&i(t.spaceAfter,r.spaceAfter)&&(t.contextualSpacing??!1)===(r.contextualSpacing??!1)&&(delete t.spaceBefore,delete t.spaceAfter,delete t.contextualSpacing),t.keepNext===!0&&r.keepNext===!0&&delete t.keepNext,t.keepLines===!0&&r.keepLines===!0&&delete t.keepLines,t.widowControl===!1&&r.widowControl===!1&&delete t.widowControl,i(t.leftIndent,r.leftIndent)&&delete t.leftIndent,i(t.firstLineIndent,r.firstLineIndent)&&delete t.firstLineIndent,t.tabStops!==void 0&&t.tabStops===r.tabStops&&delete t.tabStops,t.borders!==void 0&&t.borders===r.borders&&delete t.borders,t.shading!==void 0&&t.shading===r.shading&&delete t.shading,t}static stripStyleProvidedMarks(e,r){if(!e||!r)return e;const t=n=>String(n).split(",")[0].replaceAll('"',"").replaceAll("'","").trim().toLowerCase(),i={...e};for(const n of Object.keys(r))i[n]!==void 0&&(n==="fontFamily"?t(i[n])===t(r[n]):i[n]===r[n])&&delete i[n];return i}static paragraphToDocxWithMath(e,r,t=this.resolveIndentStepPx(),i){const n=this.exportDefaultRunSizeHalfPoints;(e.heading||i?.fontSize)&&(this.exportDefaultRunSizeHalfPoints=void 0);try{return this.paragraphToDocxWithMathInner(e,r,t,i)}finally{this.exportDefaultRunSizeHalfPoints=n}}static paragraphToDocxWithMathInner(e,r,t=this.resolveIndentStepPx(),i){const n={type:"paragraph",sourceBlockId:e.id,children:[]};e.styleId&&(n.styleId=e.styleId),e.heading&&(n.heading=`HEADING_${e.heading}`);{const a=this.docxAlignmentForExport(e);a&&(n.alignment=a)}e.lineSpacing!==void 0&&(n.lineSpacing=e.lineSpacing),this.applyExportParagraphSpacing(n,e),e.keepNext&&(n.keepNext=!0),e.keepLines&&(n.keepLines=!0),e.widowControl===!1&&(n.widowControl=!1),e.borders&&(n.bordersJson=e.borders),e.shading&&(n.shadingFill=e.shading),e.tabStops&&(n.tabStopsJson=e.tabStops),e.oxmlAttrs&&(n.oxmlAttrs=e.oxmlAttrs),e.oxmlPPr&&(n.oxmlPPr=e.oxmlPPr);const o=this.buildParagraphIndent(e,t);o&&(n.indent=o);const s=e;if(s.fontFamily&&(n.style=s.fontFamily),this.applyParagraphMarkRevisionInfo(n,e),this.applyParagraphPropertyChangeInfo(n,e,t),e.children.length===0)return this.applyWholeBlockRevisionInfo(n,e),this.applyBidiExportFlags(n,e),n;for(const a of e.children)if(a.type==="text"){const l=i&&e.styleId?{...a,marks:this.stripStyleProvidedMarks(a.marks,i)}:a,d=this.textNodeToDocxWithLatex(l,r);n.children.push(...d)}return this.applyWholeBlockRevisionInfo(n,e),this.applyBidiExportFlags(n,e),n}static docxAlignmentForExport(e){if(!e.align)return;const r=e.direction==="rtl"||e.direction===void 0&&Dt(this.paragraphNodeText(e))==="rtl",t=r&&e.align==="left"?"right":r&&e.align==="right"?"left":e.align;return{left:"LEFT",center:"CENTER",right:"RIGHT",justify:"JUSTIFIED"}[t]}static applyBidiExportFlags(e,r){const t=this.paragraphNodeText(r);if(r.direction==="ltr"){Dt(t)==="rtl"&&(e.bidirectional=!1);return}if(r.direction==="rtl"||r.direction===void 0&&Dt(t)==="rtl"){e.bidirectional=!0;for(const i of e.children)i.text&&qi(i.text)&&(i.rightToLeft=!0)}}static listToDocxParagraphsWithMath(e,r,t){const i=[],n={level0:(e.startNumber??1)-1,level1:0,level2:0};for(const o of e.children){if(o.type!=="list-item")continue;const s=this.getClampedIndentLevel(o.indentLevel),a={type:"paragraph",sourceBlockId:o.id,children:[],lineSpacing:o.lineSpacing??e.lineSpacing,...typeof(o.spaceBefore??e.spaceBefore)=="number"?{spacingBeforeTwips:this.pxToTwips(o.spaceBefore??e.spaceBefore)}:{},...typeof(o.spaceAfter??e.spaceAfter)=="number"?{spacingAfterTwips:this.pxToTwips(o.spaceAfter??e.spaceAfter)}:{},...e.contextualSpacing?{contextualSpacing:!0}:{},list:{variant:e.variant,level:s,label:"",checked:e.variant==="todo"?!!o.checked:void 0,reference:t?.get(e.id)?.reference??this.getDocxListReference(e),instance:t?.get(e.id)?.instance??0}},l=this.getListLabel(e,o,n);if(a.list&&(a.list.label=l),e.variant==="todo"&&a.children.push({text:`${l} `}),o.children.length>0){for(const d of o.children)if(d.type==="text"){const p=this.textNodeToDocxWithLatex(d,r);a.children.push(...p)}}this.applyWholeBlockRevisionInfo(a,o.structuralSuggestionKind?o:e),i.push(a)}return i}static tableToDocxWithMath(e,r,t=this.resolveIndentStepPx(),i){const n=qe(e),o=[];for(let s=0;s<e.children.length;s++){const a=e.children[s],l=e.hasHeader&&s===0,d=[];for(const p of a.children){const h=[],m=[];for(const b of p.children)if(b.type==="paragraph"){const u=i?this.styledParagraphToDocxWithMath(b,r,t,i):this.paragraphToDocxWithMath(b,r,t);h.push(u),m.push(u)}else if(b.type==="list"){const u=this.listToDocxParagraphsWithMath(b,r,this.exportOrderedPlan);h.push(...u),m.push(...u)}else b.type==="table"&&m.push(this.tableToDocxWithMath(b,r,t,i));const f=n.byId.get(p.id);d.push({paragraphs:h,...m.some(b=>b.type==="table")?{blocks:m}:{},backgroundColor:p.backgroundColor,verticalAlign:p.verticalAlign,borders:p.borders,padding:p.padding,colSpan:f&&f.colSpan>1?f.colSpan:void 0,rowSpan:f&&f.rowSpan>1?f.rowSpan:void 0,gridColumn:f?.col,...p.oxmlTcPr?{oxmlTcPr:p.oxmlTcPr}:{}})}o.push({cells:d,isHeader:l,...a.oxmlAttrs?{oxmlAttrs:a.oxmlAttrs}:{},...a.oxmlTrPr?{oxmlTrPr:a.oxmlTrPr}:{}})}return{type:"table",rows:o,columnWidths:e.columnWidths||[],hasHeader:e.hasHeader,tableWidth:e.tableWidth,align:e.align,cellPadding:e.cellPadding,borders:e.borders,borderWidth:e.borderWidth,borderColor:e.borderColor,...e.oxmlTblPr?{oxmlTblPr:e.oxmlTblPr}:{}}}static applyParagraphMarkRevisionInfo(e,r){if(r.structuralSuggestionKind!=="split"&&r.structuralSuggestionKind!=="merge"||r.structuralSuggestionRole!=="before")return;let t="Anonymous",i=new Date().toISOString(),n;try{const s=JSON.parse(r.structuralSuggestionRecord??"{}");typeof s.agentName=="string"&&s.agentName.trim()?t=s.agentName.trim():s.authorType==="ai"&&(t="Revise Agent"),typeof s.createdAt=="number"&&(i=new Date(s.createdAt).toISOString())}catch{}const o=typeof r.structuralSuggestionId=="string"?/^docxrev-(\d+)$/.exec(r.structuralSuggestionId):null;o&&(n=Number(o[1])),e.paragraphMarkRevision={kind:r.structuralSuggestionKind,author:t,date:i,...n!==void 0?{importedId:n}:{}}}static applyWholeBlockRevisionInfo(e,r){if(r.structuralSuggestionKind!=="insert"&&r.structuralSuggestionKind!=="delete")return;let t="Anonymous",i=new Date().toISOString();try{const s=JSON.parse(r.structuralSuggestionRecord??"{}");typeof s.agentName=="string"&&s.agentName.trim()?t=s.agentName.trim():s.authorType==="ai"&&(t=It),typeof s.createdAt=="number"&&(i=new Date(s.createdAt).toISOString())}catch{}const n=typeof r.structuralSuggestionId=="string"?/^docxrev-(\d+)$/.exec(r.structuralSuggestionId):null,o={kind:r.structuralSuggestionKind,author:t,date:i,...n?{importedId:Number(n[1])}:{}};e.paragraphMarkRevision=o;for(const s of e.children)s.revision??(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!=="block-change"||i.beforeBlock?.type!=="paragraph")return;const n=i.beforeBlock;let o="Anonymous";typeof i.agentName=="string"&&i.agentName.trim()?o=i.agentName.trim():i.authorType==="ai"&&(o=It);const s=typeof i.createdAt=="number"?new Date(i.createdAt).toISOString():new Date().toISOString(),a=typeof r.structuralSuggestionId=="string"?/^docxrev-(\d+)$/.exec(r.structuralSuggestionId):null,l=this.buildParagraphIndent(n,t);e.paragraphPropertiesChange={author:o,date:s,...a?{importedId:Number(a[1])}:{},prior:{...n.align?{align:n.align}:{},...l?.left!==void 0?{leftIndentTwips:l.left}:{},...l?.firstLine!==void 0?{firstLineIndentTwips:l.firstLine}:{},...n.lineSpacing!==void 0?{lineSpacing:n.lineSpacing}:{},...n.keepNext?{keepNext:!0}:{},...n.keepLines?{keepLines:!0}:{},...n.widowControl===!1?{widowControl:!1}:{},...n.direction?{direction:n.direction}:{},...n.borders?{bordersJson:n.borders}:{},...n.shading?{shadingFill:n.shading}:{},...n.styleId?{styleId:n.styleId}:n.heading?{styleId:`Heading${n.heading}`}:{}}}}static collectTableRevisionPatches(e){const r=[];let t=0;const i=[],n=o=>{for(const s of o)if(s.type==="table"){i.push(s);for(const a of s.children)for(const l of a.children)n(l.children)}else s.type==="container"&&n(s.children)};n(e.children);for(const o of i){const s=t++;let a=[];if(o.structuralSuggestionRecords)try{const g=JSON.parse(o.structuralSuggestionRecords);Array.isArray(g)&&(a=g.filter(w=>w?.type==="table-change"))}catch{}let l;if(o.docxTablePropertyOverrides)try{const g=JSON.parse(o.docxTablePropertyOverrides);g?.version===1&&(l=g)}catch{}if(a.length>0||l){const g={tableIndex:s,rows:[],cells:[],merges:[],rowProperties:[],rowExceptionProperties:[],cellProperties:[]},w=qe(o),S=new Map(o.children.map((B,P)=>[B.id,P])),T=(B,P)=>{const z=P.author?.trim()||B.agentName?.trim()||(B.authorType==="ai"?It:"Anonymous"),E=typeof P.createdAt=="number"?P.createdAt:typeof B.createdAt=="number"?B.createdAt:Date.now(),G=P.revisionId??/^docxrev-(\d+)$/.exec(B.id)?.[1],$=typeof G=="string"&&/^\d+$/.test(G)?Number(G):void 0;return{author:z,date:new Date(E).toISOString(),revisionGroup:B.id,...$!==void 0?{importedId:$}:{}}},F=B=>{const P=B.map(E=>Number.isFinite(E)&&E>0?E:1),z=P.reduce((E,G)=>E+G,0)||1;return`<w:tblGrid xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">${P.map(E=>`<w:gridCol w:w="${Math.max(1,Math.round(E/z*1e4))}"/>`).join("")}</w:tblGrid>`};if(l){const B={...l.table?{table:l.table}:{},...l.grid&&JSON.stringify(l.grid.columnWidths)===JSON.stringify(o.columnWidths)?{grid:l.grid.xml}:{},rows:[],rowExceptions:[],cells:[]};for(const[P,z]of Object.entries(l.rows??{})){const E=S.get(P);E!==void 0&&B.rows.push({rowIndex:E,xml:z})}for(const[P,z]of Object.entries(l.rowExceptions??{})){const E=S.get(P);E!==void 0&&B.rowExceptions.push({rowIndex:E,xml:z})}for(const[P,z]of Object.entries(l.cells??{})){const E=w.byId.get(P);E&&B.cells.push({rowIndex:E.row,gridColumn:E.col,xml:z})}g.propertyOverrides=B}for(const B of a){for(const P of B.tableRevision.markers){const z=T(B,P);if(P.kind==="row-insert"||P.kind==="row-delete"){const v=P.rowId?S.get(P.rowId):P.rowIndex;v!==void 0&&g.rows.push({rowIndex:v,kind:P.kind==="row-insert"?"insert":"delete",...z});continue}if(P.kind==="cell-insert"||P.kind==="cell-delete"){const v=P.cellId?w.byId.get(P.cellId):void 0,D=v?.row??P.rowIndex,M=v?.col??P.gridColumn;D!==void 0&&M!==void 0&&g.cells.push({rowIndex:D,gridColumn:M,kind:P.kind==="cell-insert"?"insert":"delete",...z});continue}if(P.kind==="cell-merge"){const v=P.rowId?S.get(P.rowId):P.rowIndex;v!==void 0&&P.gridColumn!==void 0&&g.merges.push({rowIndex:v,gridColumn:P.gridColumn,...z,...P.vMerge?{vMerge:P.vMerge}:{},...P.vMergeOrig?{vMergeOrig:P.vMergeOrig}:{}});continue}if(P.kind==="table-grid"&&P.currentPropertiesXml&&P.priorPropertiesXml){g.tableGrid={...z,currentXml:P.currentPropertiesXml,priorXml:P.priorPropertiesXml};continue}const E=B.tableRevision.operations.find(v=>v.kind==="properties"&&(P.kind==="table-properties"&&v.target==="table"||P.kind==="row-properties"&&v.target==="row"&&(!P.rowId||v.rowId===P.rowId)||P.kind==="row-exception-properties"&&v.target==="row-exception"&&(!P.rowId||v.rowId===P.rowId)||P.kind==="cell-properties"&&v.target==="cell"&&(!P.cellId||v.cellId===P.cellId))),G=P.currentPropertiesXml??(E?.kind==="properties"?E.currentPropertiesXml:void 0),$=P.priorPropertiesXml??(E?.kind==="properties"?E.priorPropertiesXml:void 0);if(P.kind==="table-properties")g.tableProperties={...z,...G?{currentXml:G}:{},...$?{priorXml:$}:{},...E?.kind==="properties"?{currentAttributes:E.currentAttributes,priorAttributes:E.priorAttributes}:{}};else if(P.kind==="row-properties"||P.kind==="row-exception-properties"){const v=P.rowId?S.get(P.rowId):P.rowIndex;v!==void 0&&(P.kind==="row-properties"?g.rowProperties:g.rowExceptionProperties).push({rowIndex:v,...z,currentXml:G??"",priorXml:$??"",...E?.kind==="properties"?{currentAttributes:E.currentAttributes,priorAttributes:E.priorAttributes,currentTableAttributes:E.currentTableAttributes,priorTableAttributes:E.priorTableAttributes}:{}})}else if(P.kind==="cell-properties"){const v=P.cellId?w.byId.get(P.cellId):void 0,D=v?.row??P.rowIndex,M=v?.col??P.gridColumn;D!==void 0&&M!==void 0&&g.cellProperties.push({rowIndex:D,gridColumn:M,...z,...G?{currentXml:G}:{},...$?{priorXml:$}:{},...E?.kind==="properties"?{currentAttributes:E.currentAttributes,priorAttributes:E.priorAttributes}:{}})}}if(!g.tableGrid){const P=B.tableRevision.operations.find(z=>z.kind==="grid");P?.kind==="grid"&&(g.tableGrid={...T(B,{}),currentXml:P.currentGridXml||F(P.currentColumnWidths),priorXml:P.priorGridXml||F(P.priorColumnWidths)})}}(g.rows.length||g.cells.length||g.merges.length||g.tableGrid||g.rowProperties.length||g.rowExceptionProperties.length||g.cellProperties.length||g.tableProperties||g.propertyOverrides)&&r.push(g);continue}if(o.structuralSuggestionKind!=="change"||!o.structuralSuggestionRecord)continue;let d;try{d=JSON.parse(o.structuralSuggestionRecord)}catch{continue}if(d.type!=="block-change"||d.beforeBlock?.type!=="table"||d.acceptedBlock?.type!=="table")continue;const p=/^docxrev-(\d+)$/.exec(o.structuralSuggestionId??"")?.[1],h=g=>{const w=typeof g?.author=="string"&&g.author.trim()?g.author.trim():typeof d.agentName=="string"&&d.agentName.trim()?d.agentName.trim():d.authorType==="ai"?It:"Anonymous",S=typeof g?.createdAt=="number"&&Number.isFinite(g.createdAt)?g.createdAt:typeof d.createdAt=="number"&&Number.isFinite(d.createdAt)?d.createdAt:Date.now(),T=g?.revisionId??p,F=typeof T=="string"&&/^\d+$/.test(T)?Number(T):void 0;return{author:w,date:new Date(S).toISOString(),...F!==void 0?{importedId:F}:{}}},m={tableIndex:s,rows:[],cells:[],merges:[],rowProperties:[],rowExceptionProperties:[],cellProperties:[]},f=d.docxTableRevisions,b=qe(o),u=new Map(o.children.map((g,w)=>[g.id,w]));if(f?.version===1){for(const g of f.rows??[]){const w=u.get(g.rowId);w!==void 0&&m.rows.push({rowIndex:w,kind:g.kind,...h(g)})}for(const g of f.cells??[]){const w=b.byId.get(g.cellId);w&&m.cells.push({rowIndex:w.row,gridColumn:w.col,kind:g.kind,...h(g)})}for(const g of f.merges??[]){const w=u.get(g.rowId);w!==void 0&&m.merges.push({rowIndex:w,gridColumn:g.gridColumn,...h(g),...g.vMerge?{vMerge:g.vMerge}:{},...g.vMergeOrig?{vMergeOrig:g.vMergeOrig}:{}})}f.tableProperties&&(m.tableProperties={...h(f.tableProperties),...f.tableProperties.priorXml?{priorXml:f.tableProperties.priorXml}:{},...d.beforeBlock.borders?{priorBorders:d.beforeBlock.borders}:{}})}else{const g=new Set(d.beforeBlock.children.map(F=>F.id)),w=new Set(d.acceptedBlock.children.map(F=>F.id));for(let F=0;F<o.children.length;F++){const B=o.children[F];!g.has(B.id)&&w.has(B.id)?m.rows.push({rowIndex:F,kind:"insert",...h()}):g.has(B.id)&&!w.has(B.id)&&m.rows.push({rowIndex:F,kind:"delete",...h()})}const S=qe(d.beforeBlock),T=qe(d.acceptedBlock);for(const F of b.cells){const B=S.byId.has(F.cell.id),P=T.byId.has(F.cell.id);!B&&P?m.cells.push({rowIndex:F.row,gridColumn:F.col,kind:"insert",...h()}):B&&!P&&m.cells.push({rowIndex:F.row,gridColumn:F.col,kind:"delete",...h()});const z=S.byId.get(F.cell.id)?.rowSpan??1,E=T.byId.get(F.cell.id)?.rowSpan??1;if(E>z&&F.rowSpan>z)for(let G=z;G<Math.min(E,F.rowSpan);G++)m.merges.push({rowIndex:F.row+G,gridColumn:F.col,vMerge:"cont",...h()})}d.beforeBlock.borders!==d.acceptedBlock.borders&&(m.tableProperties={...h(),...d.beforeBlock.borders?{priorBorders:d.beforeBlock.borders}:{}})}(m.rows.length>0||m.cells.length>0||m.merges.length>0||m.tableProperties)&&r.push(m)}return r}static textNodeToDocxWithLatex(e,r){if(e.marks?.latex){const t=this.latexToOmml(e.text,!1);return t?[{text:"",mathOmml:t}]:[{text:e.text}]}return this.textNodeToDocx(e,r)}static paragraphToDocx(e,r,t=this.resolveIndentStepPx()){const i={type:"paragraph",sourceBlockId:e.id,children:[]};e.styleId&&(i.styleId=e.styleId),e.heading&&(i.heading=`HEADING_${e.heading}`);{const s=this.docxAlignmentForExport(e);s&&(i.alignment=s)}e.lineSpacing!==void 0&&(i.lineSpacing=e.lineSpacing),this.applyExportParagraphSpacing(i,e),e.keepNext&&(i.keepNext=!0),e.keepLines&&(i.keepLines=!0),e.widowControl===!1&&(i.widowControl=!1),e.borders&&(i.bordersJson=e.borders),e.shading&&(i.shadingFill=e.shading),e.tabStops&&(i.tabStopsJson=e.tabStops),e.oxmlAttrs&&(i.oxmlAttrs=e.oxmlAttrs),e.oxmlPPr&&(i.oxmlPPr=e.oxmlPPr);const n=this.buildParagraphIndent(e,t);n&&(i.indent=n);const o=e;return o.fontFamily&&(i.style=o.fontFamily),this.applyParagraphMarkRevisionInfo(i,e),this.applyParagraphPropertyChangeInfo(i,e,t),e.children.length===0?(this.applyWholeBlockRevisionInfo(i,e),this.applyBidiExportFlags(i,e),i):(e.children.forEach(s=>{if(s.type==="text"){const a=this.textNodeToDocx(s,r);i.children.push(...a)}}),this.applyWholeBlockRevisionInfo(i,e),this.applyBidiExportFlags(i,e),i)}static listToDocxParagraphs(e,r,t){const i=[],n={level0:(e.startNumber??1)-1,level1:0,level2:0};for(const o of e.children){if(o.type!=="list-item")continue;const s=this.getClampedIndentLevel(o.indentLevel),a={type:"paragraph",sourceBlockId:o.id,children:[],lineSpacing:o.lineSpacing??e.lineSpacing,...typeof(o.spaceBefore??e.spaceBefore)=="number"?{spacingBeforeTwips:this.pxToTwips(o.spaceBefore??e.spaceBefore)}:{},...typeof(o.spaceAfter??e.spaceAfter)=="number"?{spacingAfterTwips:this.pxToTwips(o.spaceAfter??e.spaceAfter)}:{},...e.contextualSpacing?{contextualSpacing:!0}:{},list:{variant:e.variant,level:s,label:"",checked:e.variant==="todo"?!!o.checked:void 0,reference:t?.get(e.id)?.reference??this.getDocxListReference(e),instance:t?.get(e.id)?.instance??0}},l=this.getListLabel(e,o,n);a.list&&(a.list.label=l),e.variant==="todo"&&a.children.push({text:`${l} `}),o.children.length>0&&o.children.forEach(d=>{if(d.type==="text"){const p=this.textNodeToDocx(d,r);a.children.push(...p)}}),this.applyWholeBlockRevisionInfo(a,o.structuralSuggestionKind?o:e),i.push(a)}return i}static marksToDocxRunOptions(e,r){const t={};if(e){e.bold!==void 0&&(t.bold=e.bold),e.italic!==void 0&&(t.italic=e.italic),e.underline!==void 0&&(t.underline=e.underline?"SINGLE":"NONE"),e.strikethrough!==void 0&&(t.strike=e.strikethrough),e.doubleStrikethrough!==void 0&&(t.doubleStrike=e.doubleStrikethrough),e.smallCaps!==void 0&&(t.smallCaps=e.smallCaps),e.allCaps!==void 0&&(t.allCaps=e.allCaps),e.hidden!==void 0&&(t.vanish=e.hidden),e.lang&&(t.lang=e.lang),typeof e.letterSpacing=="number"&&Number.isFinite(e.letterSpacing)&&(t.characterSpacing=Math.round(e.letterSpacing*15)),e.superscript&&(t.superScript=!0),e.subscript&&(t.subScript=!0),!e.superscript&&!e.subscript&&(e.superscript===!1||e.subscript===!1)&&(t.baseline=!0),e.color&&(t.color=this.normalizeColor(e.color)),e.backgroundColor&&(t.highlight=this.colorToHighlight(e.backgroundColor));const i=new Set(e.docxRunPropertyResets?.split(",").filter(Boolean)??[]);i.has("color")&&(t.color="auto"),i.has("highlight")&&(t.highlight="none"),e.fontFamily?t.font=e.fontFamily:e.code&&(t.font="Courier New",t.highlight="lightGray",t.characterStyle=this.CODE_INLINE_STYLE_ID),e.fontSize&&(t.size=this.pxToDocxHalfPoints(e.fontSize))}return t.size===void 0&&!e?.code&&this.exportDefaultRunSizeHalfPoints!==void 0&&(t.size=this.exportDefaultRunSizeHalfPoints),e&&(e.link&&(t.link=e.link),e.oxmlRPr&&(t.oxmlRPr=e.oxmlRPr)),!t.font&&r&&(t.font=r),t}static suggestionRevisionAttrs(e){const r=e.suggestionAuthorName?.trim()||(e.suggestionAuthorType==="ai"?"Revise Agent":"Anonymous"),t=new Date(typeof e.suggestionCreatedAt=="number"?e.suggestionCreatedAt:Date.now()).toISOString(),i=typeof e.suggestionId=="string"?/^docxrev-(\d+)$/.exec(e.suggestionId):null;return{author:r,date:t,...i?{importedId:Number(i[1])}:{}}}static textNodeToDocx(e,r){const t=this.marksToDocxRunOptions(e.marks,r);if(e.marks?.comment&&(t.comment=e.marks.comment),e.marks?.bookmark&&(t.bookmark=e.marks.bookmark),e.marks?.oxmlRange&&(t.oxmlRange=e.marks.oxmlRange),e.marks?.sdtInline&&(t.sdtInline=e.marks.sdtInline),e.marks?.fieldInstr&&(t.fieldInstr=e.marks.fieldInstr),e.marks?.insertion||e.marks?.deletion){const o=this.parseDocxMoveMark(e.marks.docxMove),s=o&&/^\d+$/.test(o.wrapperId)?Number(o.wrapperId):void 0;t.revision={kind:e.marks.deletion?"delete":"insert",...this.suggestionRevisionAttrs(e.marks),...s!==void 0?{importedId:s}:{},...o?{move:o}:{}}}else if(e.marks?.formatChange){let o={};try{o=JSON.parse(e.marks.suggestionPriorAttributes??"{}")}catch{o={}}t.rPrChange={...this.suggestionRevisionAttrs(e.marks),prior:this.marksToDocxRunOptions(o)}}if(e.marks?.footnoteRef){const o=parseInt(e.text,10);return[{...t,text:"",footnoteReference:Number.isFinite(o)&&o>0?o:1}]}const i=e.text.split(`
|
|
11
|
+
`),n=[];for(let o=0;o<i.length;o++){const s=i[o];(s||o===0)&&n.push({...t,text:s}),o<i.length-1&&n.push({...t,text:"",break:!0})}return n.length===0&&n.push({...t,text:""}),n}static getListIndentOptions(e){const r=Math.max(0,Math.min(2,Math.floor(e)));return{left:this.LIST_BASE_INDENT_TWIPS+r*this.LIST_INDENT_INCREMENT_TWIPS,hanging:this.LIST_HANGING_INDENT_TWIPS}}static getListLabel(e,r,t){const i=this.getClampedIndentLevel(r.indentLevel);if(e.variant==="unordered"){const n=["•","◦","▪"];return n[Math.min(i,n.length-1)]}return e.variant==="todo"?r.checked?"☒":"☐":this.computeOrderedLabel(e.startNumber??1,i,t)}static numberingFormatHash(e){let r=5381;for(let t=0;t<e.length;t++)r=(r<<5)+r+e.charCodeAt(t)|0;return(r>>>0).toString(36)}static buildOrderedNumberingExportPlan(e){const r=new Map,t=new Map,i=new Map,n=new Map,o=a=>{if(a.variant==="ordered")if(a.numberingChainId){const l=a.numberingChainId;let d=i.get(l);if(!d||a.startNumber!==void 0){const p=d?d.segmentIndex+1:0,h=`revise-chain-${l.replace(/[^A-Za-z0-9_-]/g,"")}-s${p}`;d={reference:h,segmentIndex:p},i.set(l,d),t.set(h,{start:a.startNumber??1,formatJson:a.numberingFormat})}r.set(a.id,{reference:d.reference,instance:0})}else{const l=a.startNumber??1,d=a.numberingFormat?`revise-ordered-${l}-f${this.numberingFormatHash(a.numberingFormat)}`:`revise-ordered-${l}`;t.has(d)||t.set(d,{start:l,formatJson:a.numberingFormat});const p=n.get(d)??0;n.set(d,p+1),r.set(a.id,{reference:d,instance:p})}},s=a=>{for(const l of a)if(l.type==="list")o(l);else if(l.type==="container"||l.type==="footnote")s(l.children);else if(l.type==="table")for(const d of l.children)for(const p of d.children)s(p.children)};return s(e.children),e.notes&&s(e.notes),{byListId:r,references:t}}static getDocxListReference(e){if(e.variant!=="todo")return e.variant==="unordered"?"revise-unordered":`revise-ordered-${e.startNumber??1}`}static buildDocxNumberingConfig(e,r){const t=[];let i=!1;const n=a=>{for(const l of a)if(l.type==="list"&&l.variant==="unordered")i=!0;else if(l.type==="container"||l.type==="footnote")n(l.children);else if(l.type==="table")for(const d of l.children)for(const p of d.children)n(p.children)};n(e.children),e.notes&&n(e.notes);const o=this.buildOrderedNumberingExportPlan(e).references;i&&t.push({reference:"revise-unordered",levels:[0,1,2].map(a=>({level:a,format:r.LevelFormat.BULLET,text:["•","◦","▪"][a],alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(a)}}}))});const s=a=>{switch((a||"decimal").trim()){case"lowerLetter":return r.LevelFormat.LOWER_LETTER;case"upperLetter":return r.LevelFormat.UPPER_LETTER;case"lowerRoman":return r.LevelFormat.LOWER_ROMAN;case"upperRoman":return r.LevelFormat.UPPER_ROMAN;case"decimalZero":return r.LevelFormat.DECIMAL_ZERO??r.LevelFormat.DECIMAL;case"bullet":return r.LevelFormat.BULLET;case"none":return r.LevelFormat.NONE??r.LevelFormat.DECIMAL;default:return r.LevelFormat.DECIMAL}};for(const[a,l]of o){const d=l.start,p=l.formatJson?(()=>{try{const h=JSON.parse(l.formatJson);return Array.isArray(h)?h:void 0}catch{return}})():void 0;if(p){t.push({reference:a,levels:[0,1,2].map(h=>({level:h,format:s(p[h]?.numFmt),text:p[h]?.lvlText??["%1.","%1.%2.","%1.%2.%3."][h],start:h===0?d:1,alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(h)}}}))});continue}t.push({reference:a,levels:[{level:0,format:r.LevelFormat.DECIMAL,text:"%1.",start:d,alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(0)}}},{level:1,format:r.LevelFormat.LOWER_LETTER,text:"%1 %2.",start:1,alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(1)}}},{level:2,format:r.LevelFormat.LOWER_ROMAN,text:"%1 %2 %3.",start:1,alignment:r.AlignmentType.LEFT,suffix:r.LevelSuffix.SPACE,style:{paragraph:{indent:this.getListIndentOptions(2)}}}]})}return t.length>0?{config:t}:void 0}static computeOrderedLabel(e,r,t){return r<=0?(t.level0=Math.max(t.level0+1,e),t.level1=0,t.level2=0,`${t.level0}.`):r===1?(t.level0<e&&(t.level0=e),t.level1+=1,t.level2=0,`${t.level0} ${this.toAlphabetic(t.level1)}.`):(t.level0<e&&(t.level0=e),t.level1===0&&(t.level1=1),t.level2+=1,`${t.level0} ${this.toAlphabetic(t.level1)} ${this.toRoman(t.level2)}.`)}static toAlphabetic(e){let r=Math.max(1,e),t="";for(;r>0;)r-=1,t=String.fromCharCode(97+r%26)+t,r=Math.floor(r/26);return t}static toRoman(e){const r=[[1e3,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]];let t=Math.max(1,e),i="";for(const[n,o]of r){for(;t>=n;)i+=o,t-=n;if(t===0)break}return i||"i"}static getClampedIndentLevel(e){if(!Number.isFinite(e))return 0;const r=Math.floor(e);return Math.max(0,Math.min(2,r))}static async resolveImageSourceForDocx(e){const r=e.match(/^data:([^;,]+)(;base64)?,(.*)$/i);if(r){const t=r[1].toLowerCase(),i=this.docxImageTypeForMimeType(t);if(!i)return;const n=!!r[2],o=r[3]||"",s=n?this.base64ToUint8Array(o):new TextEncoder().encode(decodeURIComponent(o));return{type:i,data:s}}if(typeof fetch=="function")try{const t=await fetch(e);if(!t.ok)return;const i=await t.blob(),n=this.docxImageTypeForMimeType(i.type||this.inferMimeTypeFromPath(e)||"");return n?{type:n,data:new Uint8Array(await i.arrayBuffer())}:void 0}catch{return}}static base64ToUint8Array(e){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(e,"base64"));const r=atob(e),t=new Uint8Array(r.length);for(let i=0;i<r.length;i++)t[i]=r.charCodeAt(i);return t}static inferMimeTypeFromPath(e){const r=e.split("?")[0].toLowerCase();if(r.endsWith(".png"))return"image/png";if(r.endsWith(".jpg")||r.endsWith(".jpeg"))return"image/jpeg";if(r.endsWith(".gif"))return"image/gif";if(r.endsWith(".bmp"))return"image/bmp"}static docxImageTypeForMimeType(e){switch(e.toLowerCase()){case"image/png":return"png";case"image/jpeg":case"image/jpg":return"jpg";case"image/gif":return"gif";case"image/bmp":return"bmp";default:return}}static toDocxHex(e){return e?Er(e)?.slice(1).toUpperCase():void 0}static normalizeColor(e){return this.toDocxHex(e)??"000000"}static highlightValueToColor(e){return qt(e)??"yellow"}static colorToHighlight(e){const r=qt(e);if(r)return{yellow:"yellow",orange:"darkYellow",green:"green",blue:"blue",purple:"darkMagenta",pink:"magenta",gray:"lightGray"}[r]||"yellow";const t=this.normalizeColor(e);return{FFFF00:"yellow",FF0000:"red","00FF00":"green","0000FF":"blue",FFA500:"orange",FF00FF:"magenta","00FFFF":"cyan",808080:"darkGray",D3D3D3:"lightGray"}[t]||"yellow"}};fe.LIST_BASE_INDENT_TWIPS=720,fe.LIST_INDENT_INCREMENT_TWIPS=360,fe.LIST_HANGING_INDENT_TWIPS=360,fe.TWIPS_PER_INCH=1440,fe.TWIPS_PER_PX=fe.TWIPS_PER_INCH/96,fe.DOCX_HALF_POINTS_PER_PX=1.5,fe.DEFAULT_RUN_SIZE_HALF_POINTS=fe.pxToDocxHalfPoints(ke.paragraph),fe.PAGE_SIZE_PRESETS=Object.entries(gi).map(([O,e])=>({preset:O,width:Math.min(e.width,e.height),height:Math.max(e.width,e.height)})),fe.CORE_PROPERTY_LOCAL_NAMES=["title","creator","subject","keywords","description","lastModifiedBy","created","modified","revision"],fe.TODO_MARKERS=[["☒ ",!0],["☐ ",!1],["[x] ",!0],["[X] ",!0],["[ ] ",!1]],fe.fallbackCommentState={},fe.sdtAncestorStack=[],fe.OXML_RANGE_PAIRS=new Map([["w:permStart","w:permEnd"]]),fe.OMML_FUNCTION_NAMES=["sin","cos","tan","cot","sec","csc","arcsin","arccos","arctan","sinh","cosh","tanh","coth","log","ln","lg","exp","det","dim","ker","deg","gcd","hom","arg","max","min","sup","inf","lim","liminf","limsup","Pr"],fe.CODE_BLOCK_STYLE_ID="CodeBlock",fe.CODE_INLINE_STYLE_ID="CodeInline";let vn=fe;export{vn as DocxConverter};
|