@ansonlai/docx-redline-js 0.9.0 → 0.11.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/ARCHITECTURE.md +691 -669
- package/CHANGELOG.md +67 -1
- package/README.md +39 -8
- package/core/word-xml.js +160 -118
- package/dist/docx-redline-js.esm.js +528 -312
- package/dist/docx-redline-js.esm.js.map +4 -4
- package/dist/docx-redline-js.esm.min.js +94 -94
- package/dist/docx-redline-js.esm.min.js.map +4 -4
- package/dist/docx-redline.bundle.cjs +528 -312
- package/dist/docx-redline.bundle.cjs.map +4 -4
- package/dist/docx-redline.bundle.js +528 -312
- package/dist/docx-redline.bundle.js.map +4 -4
- package/docs/AGENT_KNOWLEDGE_BASE.md +64 -5
- package/docs/SKILL_AUTHORING.md +5 -1
- package/docs/TESTING.md +10 -1
- package/docs/schemas/document-operations.schema.json +1 -1
- package/engine/oxml-engine.js +748 -736
- package/engine/table-mode.js +7 -4
- package/index.d.ts +29 -2
- package/index.js +3 -0
- package/node/cli.js +993 -992
- package/package.json +1 -1
- package/pipeline/content-analysis.js +2 -1
- package/pipeline/markdown-processor.js +5 -2
- package/pipeline/structured-content.js +2 -1
- package/services/comment-parts-merge.js +124 -0
- package/services/comment-replies.js +1 -1
- package/services/document-operation-applier.js +1 -0
- package/services/document-operation-contract.js +1 -0
- package/services/document-operation-mutations.js +3362 -3346
- package/services/inspection-comparison.js +82 -0
- package/services/operation-heuristics.js +1 -1
- package/services/operation-preflight.js +42 -33
- package/services/revision-fidelity-verifier.js +5 -19
- package/services/standalone-docx-plumbing.js +38 -22
- package/services/table-reconciliation.js +11 -6
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
var
|
|
2
|
-
`,f),u==-1&&(u=s.length-1);var m=s.substring(f,u+1);(n.hasOwnProperty?n.hasOwnProperty(m):n[m]!==void 0)?c+=String.fromCharCode(n[m]):(d==a&&(m=s.substring(f),u=s.length),c+=String.fromCharCode(d),n[m]=d,r[d++]=m),f=u+1}return c}var a=4e4,i=o(e);a=65535;var l=o(t);return{chars1:i,chars2:l,lineArray:r}};U.prototype.diff_charsToLines_=function(e,t){for(var r=0;r<e.length;r++){for(var n=e[r][1],o=[],a=0;a<n.length;a++)o[a]=t[n.charCodeAt(a)];e[r][1]=o.join("")}};U.prototype.diff_commonPrefix=function(e,t){if(!e||!t||e.charAt(0)!=t.charAt(0))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,a=0;r<o;)e.substring(a,o)==t.substring(a,o)?(r=o,a=r):n=o,o=Math.floor((n-r)/2+r);return o};U.prototype.diff_commonSuffix=function(e,t){if(!e||!t||e.charAt(e.length-1)!=t.charAt(t.length-1))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,a=0;r<o;)e.substring(e.length-o,e.length-a)==t.substring(t.length-o,t.length-a)?(r=o,a=r):n=o,o=Math.floor((n-r)/2+r);return o};U.prototype.diff_commonOverlap_=function(e,t){var r=e.length,n=t.length;if(r==0||n==0)return 0;r>n?e=e.substring(r-n):r<n&&(t=t.substring(0,r));var o=Math.min(r,n);if(e==t)return o;for(var a=0,i=1;;){var l=e.substring(o-i),s=t.indexOf(l);if(s==-1)return a;i+=s,(s==0||e.substring(o-i)==t.substring(0,i))&&(a=i,i++)}};U.prototype.diff_halfMatch_=function(e,t){if(this.Diff_Timeout<=0)return null;var r=e.length>t.length?e:t,n=e.length>t.length?t:e;if(r.length<4||n.length*2<r.length)return null;var o=this;function a(p,g,h){for(var v=p.substring(h,h+Math.floor(p.length/4)),w=-1,y="",b,I,E,N;(w=g.indexOf(v,w+1))!=-1;){var R=o.diff_commonPrefix(p.substring(h),g.substring(w)),x=o.diff_commonSuffix(p.substring(0,h),g.substring(0,w));y.length<x+R&&(y=g.substring(w-x,w)+g.substring(w,w+R),b=p.substring(0,h-x),I=p.substring(h+R),E=g.substring(0,w-x),N=g.substring(w+R))}return y.length*2>=p.length?[b,I,E,N,y]:null}var i=a(r,n,Math.ceil(r.length/4)),l=a(r,n,Math.ceil(r.length/2)),s;if(!i&&!l)return null;l?i?s=i[4].length>l[4].length?i:l:s=l:s=i;var c,f,u,d;e.length>t.length?(c=s[0],f=s[1],u=s[2],d=s[3]):(u=s[0],d=s[1],c=s[2],f=s[3]);var m=s[4];return[c,f,u,d,m]};U.prototype.diff_cleanupSemantic=function(e){for(var t=!1,r=[],n=0,o=null,a=0,i=0,l=0,s=0,c=0;a<e.length;)e[a][0]==ne?(r[n++]=a,i=s,l=c,s=0,c=0,o=e[a][1]):(e[a][0]==Ae?s+=e[a][1].length:c+=e[a][1].length,o&&o.length<=Math.max(i,l)&&o.length<=Math.max(s,c)&&(e.splice(r[n-1],0,new U.Diff(Ie,o)),e[r[n-1]+1][0]=Ae,n--,n--,a=n>0?r[n-1]:-1,i=0,l=0,s=0,c=0,o=null,t=!0)),a++;for(t&&this.diff_cleanupMerge(e),this.diff_cleanupSemanticLossless(e),a=1;a<e.length;){if(e[a-1][0]==Ie&&e[a][0]==Ae){var f=e[a-1][1],u=e[a][1],d=this.diff_commonOverlap_(f,u),m=this.diff_commonOverlap_(u,f);d>=m?(d>=f.length/2||d>=u.length/2)&&(e.splice(a,0,new U.Diff(ne,u.substring(0,d))),e[a-1][1]=f.substring(0,f.length-d),e[a+1][1]=u.substring(d),a++):(m>=f.length/2||m>=u.length/2)&&(e.splice(a,0,new U.Diff(ne,f.substring(0,m))),e[a-1][0]=Ae,e[a-1][1]=u.substring(0,u.length-m),e[a+1][0]=Ie,e[a+1][1]=f.substring(m),a++),a++}a++}};U.prototype.diff_cleanupSemanticLossless=function(e){function t(m,p){if(!m||!p)return 6;var g=m.charAt(m.length-1),h=p.charAt(0),v=g.match(U.nonAlphaNumericRegex_),w=h.match(U.nonAlphaNumericRegex_),y=v&&g.match(U.whitespaceRegex_),b=w&&h.match(U.whitespaceRegex_),I=y&&g.match(U.linebreakRegex_),E=b&&h.match(U.linebreakRegex_),N=I&&m.match(U.blanklineEndRegex_),R=E&&p.match(U.blanklineStartRegex_);return N||R?5:I||E?4:v&&!y&&b?3:y||b?2:v||w?1:0}for(var r=1;r<e.length-1;){if(e[r-1][0]==ne&&e[r+1][0]==ne){var n=e[r-1][1],o=e[r][1],a=e[r+1][1],i=this.diff_commonSuffix(n,o);if(i){var l=o.substring(o.length-i);n=n.substring(0,n.length-i),o=l+o.substring(0,o.length-i),a=l+a}for(var s=n,c=o,f=a,u=t(n,o)+t(o,a);o.charAt(0)===a.charAt(0);){n+=o.charAt(0),o=o.substring(1)+a.charAt(0),a=a.substring(1);var d=t(n,o)+t(o,a);d>=u&&(u=d,s=n,c=o,f=a)}e[r-1][1]!=s&&(s?e[r-1][1]=s:(e.splice(r-1,1),r--),e[r][1]=c,f?e[r+1][1]=f:(e.splice(r+1,1),r--))}r++}};U.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;U.whitespaceRegex_=/\s/;U.linebreakRegex_=/[\r\n]/;U.blanklineEndRegex_=/\n\r?\n$/;U.blanklineStartRegex_=/^\r?\n\r?\n/;U.prototype.diff_cleanupEfficiency=function(e){for(var t=!1,r=[],n=0,o=null,a=0,i=!1,l=!1,s=!1,c=!1;a<e.length;)e[a][0]==ne?(e[a][1].length<this.Diff_EditCost&&(s||c)?(r[n++]=a,i=s,l=c,o=e[a][1]):(n=0,o=null),s=c=!1):(e[a][0]==Ie?c=!0:s=!0,o&&(i&&l&&s&&c||o.length<this.Diff_EditCost/2&&i+l+s+c==3)&&(e.splice(r[n-1],0,new U.Diff(Ie,o)),e[r[n-1]+1][0]=Ae,n--,o=null,i&&l?(s=c=!0,n=0):(n--,a=n>0?r[n-1]:-1,s=c=!1),t=!0)),a++;t&&this.diff_cleanupMerge(e)};U.prototype.diff_cleanupMerge=function(e){e.push(new U.Diff(ne,""));for(var t=0,r=0,n=0,o="",a="",i;t<e.length;)switch(e[t][0]){case Ae:n++,a+=e[t][1],t++;break;case Ie:r++,o+=e[t][1],t++;break;case ne:r+n>1?(r!==0&&n!==0&&(i=this.diff_commonPrefix(a,o),i!==0&&(t-r-n>0&&e[t-r-n-1][0]==ne?e[t-r-n-1][1]+=a.substring(0,i):(e.splice(0,0,new U.Diff(ne,a.substring(0,i))),t++),a=a.substring(i),o=o.substring(i)),i=this.diff_commonSuffix(a,o),i!==0&&(e[t][1]=a.substring(a.length-i)+e[t][1],a=a.substring(0,a.length-i),o=o.substring(0,o.length-i))),t-=r+n,e.splice(t,r+n),o.length&&(e.splice(t,0,new U.Diff(Ie,o)),t++),a.length&&(e.splice(t,0,new U.Diff(Ae,a)),t++),t++):t!==0&&e[t-1][0]==ne?(e[t-1][1]+=e[t][1],e.splice(t,1)):t++,n=0,r=0,o="",a="";break}e[e.length-1][1]===""&&e.pop();var l=!1;for(t=1;t<e.length-1;)e[t-1][0]==ne&&e[t+1][0]==ne&&(e[t][1].substring(e[t][1].length-e[t-1][1].length)==e[t-1][1]?(e[t][1]=e[t-1][1]+e[t][1].substring(0,e[t][1].length-e[t-1][1].length),e[t+1][1]=e[t-1][1]+e[t+1][1],e.splice(t-1,1),l=!0):e[t][1].substring(0,e[t+1][1].length)==e[t+1][1]&&(e[t-1][1]+=e[t+1][1],e[t][1]=e[t][1].substring(e[t+1][1].length)+e[t+1][1],e.splice(t+1,1),l=!0)),t++;l&&this.diff_cleanupMerge(e)};U.prototype.diff_xIndex=function(e,t){var r=0,n=0,o=0,a=0,i;for(i=0;i<e.length&&(e[i][0]!==Ae&&(r+=e[i][1].length),e[i][0]!==Ie&&(n+=e[i][1].length),!(r>t));i++)o=r,a=n;return e.length!=i&&e[i][0]===Ie?a:a+(t-o)};U.prototype.diff_prettyHtml=function(e){for(var t=[],r=/&/g,n=/</g,o=/>/g,a=/\n/g,i=0;i<e.length;i++){var l=e[i][0],s=e[i][1],c=s.replace(r,"&").replace(n,"<").replace(o,">").replace(a,"¶<br>");switch(l){case Ae:t[i]='<ins style="background:#e6ffe6;">'+c+"</ins>";break;case Ie:t[i]='<del style="background:#ffe6e6;">'+c+"</del>";break;case ne:t[i]="<span>"+c+"</span>";break}}return t.join("")};U.prototype.diff_text1=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==Ae&&(t[r]=e[r][1]);return t.join("")};U.prototype.diff_text2=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==Ie&&(t[r]=e[r][1]);return t.join("")};U.prototype.diff_levenshtein=function(e){for(var t=0,r=0,n=0,o=0;o<e.length;o++){var a=e[o][0],i=e[o][1];switch(a){case Ae:r+=i.length;break;case Ie:n+=i.length;break;case ne:t+=Math.max(r,n),r=0,n=0;break}}return t+=Math.max(r,n),t};U.prototype.diff_toDelta=function(e){for(var t=[],r=0;r<e.length;r++)switch(e[r][0]){case Ae:t[r]="+"+encodeURI(e[r][1]);break;case Ie:t[r]="-"+e[r][1].length;break;case ne:t[r]="="+e[r][1].length;break}return t.join(" ").replace(/%20/g," ")};U.prototype.diff_fromDelta=function(e,t){for(var r=[],n=0,o=0,a=t.split(/\t/g),i=0;i<a.length;i++){var l=a[i].substring(1);switch(a[i].charAt(0)){case"+":try{r[n++]=new U.Diff(Ae,decodeURI(l))}catch{throw new Error("Illegal escape in diff_fromDelta: "+l)}break;case"-":case"=":var s=parseInt(l,10);if(isNaN(s)||s<0)throw new Error("Invalid number in diff_fromDelta: "+l);var c=e.substring(o,o+=s);a[i].charAt(0)=="="?r[n++]=new U.Diff(ne,c):r[n++]=new U.Diff(Ie,c);break;default:if(a[i])throw new Error("Invalid diff operation in diff_fromDelta: "+a[i])}}if(o!=e.length)throw new Error("Delta length ("+o+") does not equal source text length ("+e.length+").");return r};U.prototype.match_main=function(e,t,r){if(e==null||t==null||r==null)throw new Error("Null input. (match_main)");return r=Math.max(0,Math.min(r,e.length)),e==t?0:e.length?e.substring(r,r+t.length)==t?r:this.match_bitap_(e,t,r):-1};U.prototype.match_bitap_=function(e,t,r){if(t.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");var n=this.match_alphabet_(t),o=this;function a(b,I){var E=b/t.length,N=Math.abs(r-I);return o.Match_Distance?E+N/o.Match_Distance:N?1:E}var i=this.Match_Threshold,l=e.indexOf(t,r);l!=-1&&(i=Math.min(a(0,l),i),l=e.lastIndexOf(t,r+t.length),l!=-1&&(i=Math.min(a(0,l),i)));var s=1<<t.length-1;l=-1;for(var c,f,u=t.length+e.length,d,m=0;m<t.length;m++){for(c=0,f=u;c<f;)a(m,r+f)<=i?c=f:u=f,f=Math.floor((u-c)/2+c);u=f;var p=Math.max(1,r-f+1),g=Math.min(r+f,e.length)+t.length,h=Array(g+2);h[g+1]=(1<<m)-1;for(var v=g;v>=p;v--){var w=n[e.charAt(v-1)];if(m===0?h[v]=(h[v+1]<<1|1)&w:h[v]=(h[v+1]<<1|1)&w|((d[v+1]|d[v])<<1|1)|d[v+1],h[v]&s){var y=a(m,v-1);if(y<=i)if(i=y,l=v-1,l>r)p=Math.max(1,2*r-l);else break}}if(a(m+1,r)>i)break;d=h}return l};U.prototype.match_alphabet_=function(e){for(var t={},r=0;r<e.length;r++)t[e.charAt(r)]=0;for(var r=0;r<e.length;r++)t[e.charAt(r)]|=1<<e.length-r-1;return t};U.prototype.patch_addContext_=function(e,t){if(t.length!=0){if(e.start2===null)throw Error("patch not initialized");for(var r=t.substring(e.start2,e.start2+e.length1),n=0;t.indexOf(r)!=t.lastIndexOf(r)&&r.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)n+=this.Patch_Margin,r=t.substring(e.start2-n,e.start2+e.length1+n);n+=this.Patch_Margin;var o=t.substring(e.start2-n,e.start2);o&&e.diffs.unshift(new U.Diff(ne,o));var a=t.substring(e.start2+e.length1,e.start2+e.length1+n);a&&e.diffs.push(new U.Diff(ne,a)),e.start1-=o.length,e.start2-=o.length,e.length1+=o.length+a.length,e.length2+=o.length+a.length}};U.prototype.patch_make=function(e,t,r){var n,o;if(typeof e=="string"&&typeof t=="string"&&typeof r>"u")n=e,o=this.diff_main(n,t,!0),o.length>2&&(this.diff_cleanupSemantic(o),this.diff_cleanupEfficiency(o));else if(e&&typeof e=="object"&&typeof t>"u"&&typeof r>"u")o=e,n=this.diff_text1(o);else if(typeof e=="string"&&t&&typeof t=="object"&&typeof r>"u")n=e,o=t;else if(typeof e=="string"&&typeof t=="string"&&r&&typeof r=="object")n=e,o=r;else throw new Error("Unknown call format to patch_make.");if(o.length===0)return[];for(var a=[],i=new U.patch_obj,l=0,s=0,c=0,f=n,u=n,d=0;d<o.length;d++){var m=o[d][0],p=o[d][1];switch(!l&&m!==ne&&(i.start1=s,i.start2=c),m){case Ae:i.diffs[l++]=o[d],i.length2+=p.length,u=u.substring(0,c)+p+u.substring(c);break;case Ie:i.length1+=p.length,i.diffs[l++]=o[d],u=u.substring(0,c)+u.substring(c+p.length);break;case ne:p.length<=2*this.Patch_Margin&&l&&o.length!=d+1?(i.diffs[l++]=o[d],i.length1+=p.length,i.length2+=p.length):p.length>=2*this.Patch_Margin&&l&&(this.patch_addContext_(i,f),a.push(i),i=new U.patch_obj,l=0,f=u,s=c);break}m!==Ae&&(s+=p.length),m!==Ie&&(c+=p.length)}return l&&(this.patch_addContext_(i,f),a.push(i)),a};U.prototype.patch_deepCopy=function(e){for(var t=[],r=0;r<e.length;r++){var n=e[r],o=new U.patch_obj;o.diffs=[];for(var a=0;a<n.diffs.length;a++)o.diffs[a]=new U.Diff(n.diffs[a][0],n.diffs[a][1]);o.start1=n.start1,o.start2=n.start2,o.length1=n.length1,o.length2=n.length2,t[r]=o}return t};U.prototype.patch_apply=function(e,t){if(e.length==0)return[t,[]];e=this.patch_deepCopy(e);var r=this.patch_addPadding(e);t=r+t+r,this.patch_splitMax(e);for(var n=0,o=[],a=0;a<e.length;a++){var i=e[a].start2+n,l=this.diff_text1(e[a].diffs),s,c=-1;if(l.length>this.Match_MaxBits?(s=this.match_main(t,l.substring(0,this.Match_MaxBits),i),s!=-1&&(c=this.match_main(t,l.substring(l.length-this.Match_MaxBits),i+l.length-this.Match_MaxBits),(c==-1||s>=c)&&(s=-1))):s=this.match_main(t,l,i),s==-1)o[a]=!1,n-=e[a].length2-e[a].length1;else{o[a]=!0,n=s-i;var f;if(c==-1?f=t.substring(s,s+l.length):f=t.substring(s,c+this.Match_MaxBits),l==f)t=t.substring(0,s)+this.diff_text2(e[a].diffs)+t.substring(s+l.length);else{var u=this.diff_main(l,f,!1);if(l.length>this.Match_MaxBits&&this.diff_levenshtein(u)/l.length>this.Patch_DeleteThreshold)o[a]=!1;else{this.diff_cleanupSemanticLossless(u);for(var d=0,m,p=0;p<e[a].diffs.length;p++){var g=e[a].diffs[p];g[0]!==ne&&(m=this.diff_xIndex(u,d)),g[0]===Ae?t=t.substring(0,s+m)+g[1]+t.substring(s+m):g[0]===Ie&&(t=t.substring(0,s+m)+t.substring(s+this.diff_xIndex(u,d+g[1].length))),g[0]!==Ie&&(d+=g[1].length)}}}}}return t=t.substring(r.length,t.length-r.length),[t,o]};U.prototype.patch_addPadding=function(e){for(var t=this.Patch_Margin,r="",n=1;n<=t;n++)r+=String.fromCharCode(n);for(var n=0;n<e.length;n++)e[n].start1+=t,e[n].start2+=t;var o=e[0],a=o.diffs;if(a.length==0||a[0][0]!=ne)a.unshift(new U.Diff(ne,r)),o.start1-=t,o.start2-=t,o.length1+=t,o.length2+=t;else if(t>a[0][1].length){var i=t-a[0][1].length;a[0][1]=r.substring(a[0][1].length)+a[0][1],o.start1-=i,o.start2-=i,o.length1+=i,o.length2+=i}if(o=e[e.length-1],a=o.diffs,a.length==0||a[a.length-1][0]!=ne)a.push(new U.Diff(ne,r)),o.length1+=t,o.length2+=t;else if(t>a[a.length-1][1].length){var i=t-a[a.length-1][1].length;a[a.length-1][1]+=r.substring(0,i),o.length1+=i,o.length2+=i}return r};U.prototype.patch_splitMax=function(e){for(var t=this.Match_MaxBits,r=0;r<e.length;r++)if(!(e[r].length1<=t)){var n=e[r];e.splice(r--,1);for(var o=n.start1,a=n.start2,i="";n.diffs.length!==0;){var l=new U.patch_obj,s=!0;for(l.start1=o-i.length,l.start2=a-i.length,i!==""&&(l.length1=l.length2=i.length,l.diffs.push(new U.Diff(ne,i)));n.diffs.length!==0&&l.length1<t-this.Patch_Margin;){var c=n.diffs[0][0],f=n.diffs[0][1];c===Ae?(l.length2+=f.length,a+=f.length,l.diffs.push(n.diffs.shift()),s=!1):c===Ie&&l.diffs.length==1&&l.diffs[0][0]==ne&&f.length>2*t?(l.length1+=f.length,o+=f.length,s=!1,l.diffs.push(new U.Diff(c,f)),n.diffs.shift()):(f=f.substring(0,t-l.length1-this.Patch_Margin),l.length1+=f.length,o+=f.length,c===ne?(l.length2+=f.length,a+=f.length):s=!1,l.diffs.push(new U.Diff(c,f)),f==n.diffs[0][1]?n.diffs.shift():n.diffs[0][1]=n.diffs[0][1].substring(f.length))}i=this.diff_text2(l.diffs),i=i.substring(i.length-this.Patch_Margin);var u=this.diff_text1(n.diffs).substring(0,this.Patch_Margin);u!==""&&(l.length1+=u.length,l.length2+=u.length,l.diffs.length!==0&&l.diffs[l.diffs.length-1][0]===ne?l.diffs[l.diffs.length-1][1]+=u:l.diffs.push(new U.Diff(ne,u))),s||e.splice(++r,0,l)}}};U.prototype.patch_toText=function(e){for(var t=[],r=0;r<e.length;r++)t[r]=e[r];return t.join("")};U.prototype.patch_fromText=function(e){var t=[];if(!e)return t;for(var r=e.split(`
|
|
3
|
-
`),n=0,o=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;n<r.length;){var a=r[n].match(o);if(!a)throw new Error("Invalid patch string: "+r[n]);var i=new U.patch_obj;for(t.push(i),i.start1=parseInt(a[1],10),a[2]===""?(i.start1--,i.length1=1):a[2]=="0"?i.length1=0:(i.start1--,i.length1=parseInt(a[2],10)),i.start2=parseInt(a[3],10),a[4]===""?(i.start2--,i.length2=1):a[4]=="0"?i.length2=0:(i.start2--,i.length2=parseInt(a[4],10)),n++;n<r.length;){var l=r[n].charAt(0);try{var s=decodeURI(r[n].substring(1))}catch{throw new Error("Illegal escape in patch_fromText: "+s)}if(l=="-")i.diffs.push(new U.Diff(
|
|
4
|
-
`],n,o=0;o<this.diffs.length;o++){switch(this.diffs[o][0]){case
|
|
5
|
-
`}return r.join("").replace(/%20/g," ")};
|
|
6
|
-
`)&&
|
|
7
|
-
`)&&
|
|
8
|
-
`:e}function
|
|
9
|
-
`:i.endsWith(":tab")||i==="tab"?o+=" ":i.endsWith(":noBreakHyphen")||i==="noBreakHyphen"?o+="\u2011":(i.endsWith(":softHyphen")||i==="softHyphen")&&(o+="\xAD")}return o?{kind:
|
|
10
|
-
`)},
|
|
11
|
-
`)}}function
|
|
12
|
-
`),c=
|
|
13
|
-
<w:numbering xmlns:w="${
|
|
1
|
+
var Np=Object.create;var vc=Object.defineProperty;var Tp=Object.getOwnPropertyDescriptor;var Sp=Object.getOwnPropertyNames;var Ap=Object.getPrototypeOf,Ep=Object.prototype.hasOwnProperty;var Rp=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}};var Pp=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Sp(t))!Ep.call(e,o)&&o!==r&&vc(e,o,{get:()=>t[o],enumerable:!(n=Tp(t,o))||n.enumerable});return e};var yc=(e,t,r)=>(r=e!=null?Np(Ap(e)):{},Pp(t||!e||!e.__esModule?vc(r,"default",{value:e,enumerable:!0}):r,e));var as=Rp((Ub,Un)=>{var U=function(){this.Diff_Timeout=1,this.Diff_EditCost=4,this.Match_Threshold=.5,this.Match_Distance=1e3,this.Patch_DeleteThreshold=.5,this.Patch_Margin=4,this.Match_MaxBits=32},be=-1,Ee=1,oe=0;U.Diff=function(e,t){return[e,t]};U.prototype.diff_main=function(e,t,r,n){typeof n>"u"&&(this.Diff_Timeout<=0?n=Number.MAX_VALUE:n=new Date().getTime()+this.Diff_Timeout*1e3);var o=n;if(e==null||t==null)throw new Error("Null input. (diff_main)");if(e==t)return e?[new U.Diff(oe,e)]:[];typeof r>"u"&&(r=!0);var a=r,i=this.diff_commonPrefix(e,t),l=e.substring(0,i);e=e.substring(i),t=t.substring(i),i=this.diff_commonSuffix(e,t);var s=e.substring(e.length-i);e=e.substring(0,e.length-i),t=t.substring(0,t.length-i);var c=this.diff_compute_(e,t,a,o);return l&&c.unshift(new U.Diff(oe,l)),s&&c.push(new U.Diff(oe,s)),this.diff_cleanupMerge(c),c};U.prototype.diff_compute_=function(e,t,r,n){var o;if(!e)return[new U.Diff(Ee,t)];if(!t)return[new U.Diff(be,e)];var a=e.length>t.length?e:t,i=e.length>t.length?t:e,l=a.indexOf(i);if(l!=-1)return o=[new U.Diff(Ee,a.substring(0,l)),new U.Diff(oe,i),new U.Diff(Ee,a.substring(l+i.length))],e.length>t.length&&(o[0][0]=o[2][0]=be),o;if(i.length==1)return[new U.Diff(be,e),new U.Diff(Ee,t)];var s=this.diff_halfMatch_(e,t);if(s){var c=s[0],f=s[1],u=s[2],d=s[3],m=s[4],p=this.diff_main(c,u,r,n),g=this.diff_main(f,d,r,n);return p.concat([new U.Diff(oe,m)],g)}return r&&e.length>100&&t.length>100?this.diff_lineMode_(e,t,n):this.diff_bisect_(e,t,n)};U.prototype.diff_lineMode_=function(e,t,r){var n=this.diff_linesToChars_(e,t);e=n.chars1,t=n.chars2;var o=n.lineArray,a=this.diff_main(e,t,!1,r);this.diff_charsToLines_(a,o),this.diff_cleanupSemantic(a),a.push(new U.Diff(oe,""));for(var i=0,l=0,s=0,c="",f="";i<a.length;){switch(a[i][0]){case Ee:s++,f+=a[i][1];break;case be:l++,c+=a[i][1];break;case oe:if(l>=1&&s>=1){a.splice(i-l-s,l+s),i=i-l-s;for(var u=this.diff_main(c,f,!1,r),d=u.length-1;d>=0;d--)a.splice(i,0,u[d]);i=i+u.length}s=0,l=0,c="",f="";break}i++}return a.pop(),a};U.prototype.diff_bisect_=function(e,t,r){for(var n=e.length,o=t.length,a=Math.ceil((n+o)/2),i=a,l=2*a,s=new Array(l),c=new Array(l),f=0;f<l;f++)s[f]=-1,c[f]=-1;s[i+1]=0,c[i+1]=0;for(var u=n-o,d=u%2!=0,m=0,p=0,g=0,h=0,v=0;v<a&&!(new Date().getTime()>r);v++){for(var w=-v+m;w<=v-p;w+=2){var y=i+w,x;w==-v||w!=v&&s[y-1]<s[y+1]?x=s[y+1]:x=s[y-1]+1;for(var b=x-w;x<n&&b<o&&e.charAt(x)==t.charAt(b);)x++,b++;if(s[y]=x,x>n)p+=2;else if(b>o)m+=2;else if(d){var T=i+u-w;if(T>=0&&T<l&&c[T]!=-1){var A=n-c[T];if(x>=A)return this.diff_bisectSplit_(e,t,x,b,r)}}}for(var E=-v+g;E<=v-h;E+=2){var T=i+E,A;E==-v||E!=v&&c[T-1]<c[T+1]?A=c[T+1]:A=c[T-1]+1;for(var I=A-E;A<n&&I<o&&e.charAt(n-A-1)==t.charAt(o-I-1);)A++,I++;if(c[T]=A,A>n)h+=2;else if(I>o)g+=2;else if(!d){var y=i+u-E;if(y>=0&&y<l&&s[y]!=-1){var x=s[y],b=i+x-y;if(A=n-A,x>=A)return this.diff_bisectSplit_(e,t,x,b,r)}}}}return[new U.Diff(be,e),new U.Diff(Ee,t)]};U.prototype.diff_bisectSplit_=function(e,t,r,n,o){var a=e.substring(0,r),i=t.substring(0,n),l=e.substring(r),s=t.substring(n),c=this.diff_main(a,i,!1,o),f=this.diff_main(l,s,!1,o);return c.concat(f)};U.prototype.diff_linesToChars_=function(e,t){var r=[],n={};r[0]="";function o(s){for(var c="",f=0,u=-1,d=r.length;u<s.length-1;){u=s.indexOf(`
|
|
2
|
+
`,f),u==-1&&(u=s.length-1);var m=s.substring(f,u+1);(n.hasOwnProperty?n.hasOwnProperty(m):n[m]!==void 0)?c+=String.fromCharCode(n[m]):(d==a&&(m=s.substring(f),u=s.length),c+=String.fromCharCode(d),n[m]=d,r[d++]=m),f=u+1}return c}var a=4e4,i=o(e);a=65535;var l=o(t);return{chars1:i,chars2:l,lineArray:r}};U.prototype.diff_charsToLines_=function(e,t){for(var r=0;r<e.length;r++){for(var n=e[r][1],o=[],a=0;a<n.length;a++)o[a]=t[n.charCodeAt(a)];e[r][1]=o.join("")}};U.prototype.diff_commonPrefix=function(e,t){if(!e||!t||e.charAt(0)!=t.charAt(0))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,a=0;r<o;)e.substring(a,o)==t.substring(a,o)?(r=o,a=r):n=o,o=Math.floor((n-r)/2+r);return o};U.prototype.diff_commonSuffix=function(e,t){if(!e||!t||e.charAt(e.length-1)!=t.charAt(t.length-1))return 0;for(var r=0,n=Math.min(e.length,t.length),o=n,a=0;r<o;)e.substring(e.length-o,e.length-a)==t.substring(t.length-o,t.length-a)?(r=o,a=r):n=o,o=Math.floor((n-r)/2+r);return o};U.prototype.diff_commonOverlap_=function(e,t){var r=e.length,n=t.length;if(r==0||n==0)return 0;r>n?e=e.substring(r-n):r<n&&(t=t.substring(0,r));var o=Math.min(r,n);if(e==t)return o;for(var a=0,i=1;;){var l=e.substring(o-i),s=t.indexOf(l);if(s==-1)return a;i+=s,(s==0||e.substring(o-i)==t.substring(0,i))&&(a=i,i++)}};U.prototype.diff_halfMatch_=function(e,t){if(this.Diff_Timeout<=0)return null;var r=e.length>t.length?e:t,n=e.length>t.length?t:e;if(r.length<4||n.length*2<r.length)return null;var o=this;function a(p,g,h){for(var v=p.substring(h,h+Math.floor(p.length/4)),w=-1,y="",x,b,T,A;(w=g.indexOf(v,w+1))!=-1;){var E=o.diff_commonPrefix(p.substring(h),g.substring(w)),I=o.diff_commonSuffix(p.substring(0,h),g.substring(0,w));y.length<I+E&&(y=g.substring(w-I,w)+g.substring(w,w+E),x=p.substring(0,h-I),b=p.substring(h+E),T=g.substring(0,w-I),A=g.substring(w+E))}return y.length*2>=p.length?[x,b,T,A,y]:null}var i=a(r,n,Math.ceil(r.length/4)),l=a(r,n,Math.ceil(r.length/2)),s;if(!i&&!l)return null;l?i?s=i[4].length>l[4].length?i:l:s=l:s=i;var c,f,u,d;e.length>t.length?(c=s[0],f=s[1],u=s[2],d=s[3]):(u=s[0],d=s[1],c=s[2],f=s[3]);var m=s[4];return[c,f,u,d,m]};U.prototype.diff_cleanupSemantic=function(e){for(var t=!1,r=[],n=0,o=null,a=0,i=0,l=0,s=0,c=0;a<e.length;)e[a][0]==oe?(r[n++]=a,i=s,l=c,s=0,c=0,o=e[a][1]):(e[a][0]==Ee?s+=e[a][1].length:c+=e[a][1].length,o&&o.length<=Math.max(i,l)&&o.length<=Math.max(s,c)&&(e.splice(r[n-1],0,new U.Diff(be,o)),e[r[n-1]+1][0]=Ee,n--,n--,a=n>0?r[n-1]:-1,i=0,l=0,s=0,c=0,o=null,t=!0)),a++;for(t&&this.diff_cleanupMerge(e),this.diff_cleanupSemanticLossless(e),a=1;a<e.length;){if(e[a-1][0]==be&&e[a][0]==Ee){var f=e[a-1][1],u=e[a][1],d=this.diff_commonOverlap_(f,u),m=this.diff_commonOverlap_(u,f);d>=m?(d>=f.length/2||d>=u.length/2)&&(e.splice(a,0,new U.Diff(oe,u.substring(0,d))),e[a-1][1]=f.substring(0,f.length-d),e[a+1][1]=u.substring(d),a++):(m>=f.length/2||m>=u.length/2)&&(e.splice(a,0,new U.Diff(oe,f.substring(0,m))),e[a-1][0]=Ee,e[a-1][1]=u.substring(0,u.length-m),e[a+1][0]=be,e[a+1][1]=f.substring(m),a++),a++}a++}};U.prototype.diff_cleanupSemanticLossless=function(e){function t(m,p){if(!m||!p)return 6;var g=m.charAt(m.length-1),h=p.charAt(0),v=g.match(U.nonAlphaNumericRegex_),w=h.match(U.nonAlphaNumericRegex_),y=v&&g.match(U.whitespaceRegex_),x=w&&h.match(U.whitespaceRegex_),b=y&&g.match(U.linebreakRegex_),T=x&&h.match(U.linebreakRegex_),A=b&&m.match(U.blanklineEndRegex_),E=T&&p.match(U.blanklineStartRegex_);return A||E?5:b||T?4:v&&!y&&x?3:y||x?2:v||w?1:0}for(var r=1;r<e.length-1;){if(e[r-1][0]==oe&&e[r+1][0]==oe){var n=e[r-1][1],o=e[r][1],a=e[r+1][1],i=this.diff_commonSuffix(n,o);if(i){var l=o.substring(o.length-i);n=n.substring(0,n.length-i),o=l+o.substring(0,o.length-i),a=l+a}for(var s=n,c=o,f=a,u=t(n,o)+t(o,a);o.charAt(0)===a.charAt(0);){n+=o.charAt(0),o=o.substring(1)+a.charAt(0),a=a.substring(1);var d=t(n,o)+t(o,a);d>=u&&(u=d,s=n,c=o,f=a)}e[r-1][1]!=s&&(s?e[r-1][1]=s:(e.splice(r-1,1),r--),e[r][1]=c,f?e[r+1][1]=f:(e.splice(r+1,1),r--))}r++}};U.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;U.whitespaceRegex_=/\s/;U.linebreakRegex_=/[\r\n]/;U.blanklineEndRegex_=/\n\r?\n$/;U.blanklineStartRegex_=/^\r?\n\r?\n/;U.prototype.diff_cleanupEfficiency=function(e){for(var t=!1,r=[],n=0,o=null,a=0,i=!1,l=!1,s=!1,c=!1;a<e.length;)e[a][0]==oe?(e[a][1].length<this.Diff_EditCost&&(s||c)?(r[n++]=a,i=s,l=c,o=e[a][1]):(n=0,o=null),s=c=!1):(e[a][0]==be?c=!0:s=!0,o&&(i&&l&&s&&c||o.length<this.Diff_EditCost/2&&i+l+s+c==3)&&(e.splice(r[n-1],0,new U.Diff(be,o)),e[r[n-1]+1][0]=Ee,n--,o=null,i&&l?(s=c=!0,n=0):(n--,a=n>0?r[n-1]:-1,s=c=!1),t=!0)),a++;t&&this.diff_cleanupMerge(e)};U.prototype.diff_cleanupMerge=function(e){e.push(new U.Diff(oe,""));for(var t=0,r=0,n=0,o="",a="",i;t<e.length;)switch(e[t][0]){case Ee:n++,a+=e[t][1],t++;break;case be:r++,o+=e[t][1],t++;break;case oe:r+n>1?(r!==0&&n!==0&&(i=this.diff_commonPrefix(a,o),i!==0&&(t-r-n>0&&e[t-r-n-1][0]==oe?e[t-r-n-1][1]+=a.substring(0,i):(e.splice(0,0,new U.Diff(oe,a.substring(0,i))),t++),a=a.substring(i),o=o.substring(i)),i=this.diff_commonSuffix(a,o),i!==0&&(e[t][1]=a.substring(a.length-i)+e[t][1],a=a.substring(0,a.length-i),o=o.substring(0,o.length-i))),t-=r+n,e.splice(t,r+n),o.length&&(e.splice(t,0,new U.Diff(be,o)),t++),a.length&&(e.splice(t,0,new U.Diff(Ee,a)),t++),t++):t!==0&&e[t-1][0]==oe?(e[t-1][1]+=e[t][1],e.splice(t,1)):t++,n=0,r=0,o="",a="";break}e[e.length-1][1]===""&&e.pop();var l=!1;for(t=1;t<e.length-1;)e[t-1][0]==oe&&e[t+1][0]==oe&&(e[t][1].substring(e[t][1].length-e[t-1][1].length)==e[t-1][1]?(e[t][1]=e[t-1][1]+e[t][1].substring(0,e[t][1].length-e[t-1][1].length),e[t+1][1]=e[t-1][1]+e[t+1][1],e.splice(t-1,1),l=!0):e[t][1].substring(0,e[t+1][1].length)==e[t+1][1]&&(e[t-1][1]+=e[t+1][1],e[t][1]=e[t][1].substring(e[t+1][1].length)+e[t+1][1],e.splice(t+1,1),l=!0)),t++;l&&this.diff_cleanupMerge(e)};U.prototype.diff_xIndex=function(e,t){var r=0,n=0,o=0,a=0,i;for(i=0;i<e.length&&(e[i][0]!==Ee&&(r+=e[i][1].length),e[i][0]!==be&&(n+=e[i][1].length),!(r>t));i++)o=r,a=n;return e.length!=i&&e[i][0]===be?a:a+(t-o)};U.prototype.diff_prettyHtml=function(e){for(var t=[],r=/&/g,n=/</g,o=/>/g,a=/\n/g,i=0;i<e.length;i++){var l=e[i][0],s=e[i][1],c=s.replace(r,"&").replace(n,"<").replace(o,">").replace(a,"¶<br>");switch(l){case Ee:t[i]='<ins style="background:#e6ffe6;">'+c+"</ins>";break;case be:t[i]='<del style="background:#ffe6e6;">'+c+"</del>";break;case oe:t[i]="<span>"+c+"</span>";break}}return t.join("")};U.prototype.diff_text1=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==Ee&&(t[r]=e[r][1]);return t.join("")};U.prototype.diff_text2=function(e){for(var t=[],r=0;r<e.length;r++)e[r][0]!==be&&(t[r]=e[r][1]);return t.join("")};U.prototype.diff_levenshtein=function(e){for(var t=0,r=0,n=0,o=0;o<e.length;o++){var a=e[o][0],i=e[o][1];switch(a){case Ee:r+=i.length;break;case be:n+=i.length;break;case oe:t+=Math.max(r,n),r=0,n=0;break}}return t+=Math.max(r,n),t};U.prototype.diff_toDelta=function(e){for(var t=[],r=0;r<e.length;r++)switch(e[r][0]){case Ee:t[r]="+"+encodeURI(e[r][1]);break;case be:t[r]="-"+e[r][1].length;break;case oe:t[r]="="+e[r][1].length;break}return t.join(" ").replace(/%20/g," ")};U.prototype.diff_fromDelta=function(e,t){for(var r=[],n=0,o=0,a=t.split(/\t/g),i=0;i<a.length;i++){var l=a[i].substring(1);switch(a[i].charAt(0)){case"+":try{r[n++]=new U.Diff(Ee,decodeURI(l))}catch{throw new Error("Illegal escape in diff_fromDelta: "+l)}break;case"-":case"=":var s=parseInt(l,10);if(isNaN(s)||s<0)throw new Error("Invalid number in diff_fromDelta: "+l);var c=e.substring(o,o+=s);a[i].charAt(0)=="="?r[n++]=new U.Diff(oe,c):r[n++]=new U.Diff(be,c);break;default:if(a[i])throw new Error("Invalid diff operation in diff_fromDelta: "+a[i])}}if(o!=e.length)throw new Error("Delta length ("+o+") does not equal source text length ("+e.length+").");return r};U.prototype.match_main=function(e,t,r){if(e==null||t==null||r==null)throw new Error("Null input. (match_main)");return r=Math.max(0,Math.min(r,e.length)),e==t?0:e.length?e.substring(r,r+t.length)==t?r:this.match_bitap_(e,t,r):-1};U.prototype.match_bitap_=function(e,t,r){if(t.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");var n=this.match_alphabet_(t),o=this;function a(x,b){var T=x/t.length,A=Math.abs(r-b);return o.Match_Distance?T+A/o.Match_Distance:A?1:T}var i=this.Match_Threshold,l=e.indexOf(t,r);l!=-1&&(i=Math.min(a(0,l),i),l=e.lastIndexOf(t,r+t.length),l!=-1&&(i=Math.min(a(0,l),i)));var s=1<<t.length-1;l=-1;for(var c,f,u=t.length+e.length,d,m=0;m<t.length;m++){for(c=0,f=u;c<f;)a(m,r+f)<=i?c=f:u=f,f=Math.floor((u-c)/2+c);u=f;var p=Math.max(1,r-f+1),g=Math.min(r+f,e.length)+t.length,h=Array(g+2);h[g+1]=(1<<m)-1;for(var v=g;v>=p;v--){var w=n[e.charAt(v-1)];if(m===0?h[v]=(h[v+1]<<1|1)&w:h[v]=(h[v+1]<<1|1)&w|((d[v+1]|d[v])<<1|1)|d[v+1],h[v]&s){var y=a(m,v-1);if(y<=i)if(i=y,l=v-1,l>r)p=Math.max(1,2*r-l);else break}}if(a(m+1,r)>i)break;d=h}return l};U.prototype.match_alphabet_=function(e){for(var t={},r=0;r<e.length;r++)t[e.charAt(r)]=0;for(var r=0;r<e.length;r++)t[e.charAt(r)]|=1<<e.length-r-1;return t};U.prototype.patch_addContext_=function(e,t){if(t.length!=0){if(e.start2===null)throw Error("patch not initialized");for(var r=t.substring(e.start2,e.start2+e.length1),n=0;t.indexOf(r)!=t.lastIndexOf(r)&&r.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)n+=this.Patch_Margin,r=t.substring(e.start2-n,e.start2+e.length1+n);n+=this.Patch_Margin;var o=t.substring(e.start2-n,e.start2);o&&e.diffs.unshift(new U.Diff(oe,o));var a=t.substring(e.start2+e.length1,e.start2+e.length1+n);a&&e.diffs.push(new U.Diff(oe,a)),e.start1-=o.length,e.start2-=o.length,e.length1+=o.length+a.length,e.length2+=o.length+a.length}};U.prototype.patch_make=function(e,t,r){var n,o;if(typeof e=="string"&&typeof t=="string"&&typeof r>"u")n=e,o=this.diff_main(n,t,!0),o.length>2&&(this.diff_cleanupSemantic(o),this.diff_cleanupEfficiency(o));else if(e&&typeof e=="object"&&typeof t>"u"&&typeof r>"u")o=e,n=this.diff_text1(o);else if(typeof e=="string"&&t&&typeof t=="object"&&typeof r>"u")n=e,o=t;else if(typeof e=="string"&&typeof t=="string"&&r&&typeof r=="object")n=e,o=r;else throw new Error("Unknown call format to patch_make.");if(o.length===0)return[];for(var a=[],i=new U.patch_obj,l=0,s=0,c=0,f=n,u=n,d=0;d<o.length;d++){var m=o[d][0],p=o[d][1];switch(!l&&m!==oe&&(i.start1=s,i.start2=c),m){case Ee:i.diffs[l++]=o[d],i.length2+=p.length,u=u.substring(0,c)+p+u.substring(c);break;case be:i.length1+=p.length,i.diffs[l++]=o[d],u=u.substring(0,c)+u.substring(c+p.length);break;case oe:p.length<=2*this.Patch_Margin&&l&&o.length!=d+1?(i.diffs[l++]=o[d],i.length1+=p.length,i.length2+=p.length):p.length>=2*this.Patch_Margin&&l&&(this.patch_addContext_(i,f),a.push(i),i=new U.patch_obj,l=0,f=u,s=c);break}m!==Ee&&(s+=p.length),m!==be&&(c+=p.length)}return l&&(this.patch_addContext_(i,f),a.push(i)),a};U.prototype.patch_deepCopy=function(e){for(var t=[],r=0;r<e.length;r++){var n=e[r],o=new U.patch_obj;o.diffs=[];for(var a=0;a<n.diffs.length;a++)o.diffs[a]=new U.Diff(n.diffs[a][0],n.diffs[a][1]);o.start1=n.start1,o.start2=n.start2,o.length1=n.length1,o.length2=n.length2,t[r]=o}return t};U.prototype.patch_apply=function(e,t){if(e.length==0)return[t,[]];e=this.patch_deepCopy(e);var r=this.patch_addPadding(e);t=r+t+r,this.patch_splitMax(e);for(var n=0,o=[],a=0;a<e.length;a++){var i=e[a].start2+n,l=this.diff_text1(e[a].diffs),s,c=-1;if(l.length>this.Match_MaxBits?(s=this.match_main(t,l.substring(0,this.Match_MaxBits),i),s!=-1&&(c=this.match_main(t,l.substring(l.length-this.Match_MaxBits),i+l.length-this.Match_MaxBits),(c==-1||s>=c)&&(s=-1))):s=this.match_main(t,l,i),s==-1)o[a]=!1,n-=e[a].length2-e[a].length1;else{o[a]=!0,n=s-i;var f;if(c==-1?f=t.substring(s,s+l.length):f=t.substring(s,c+this.Match_MaxBits),l==f)t=t.substring(0,s)+this.diff_text2(e[a].diffs)+t.substring(s+l.length);else{var u=this.diff_main(l,f,!1);if(l.length>this.Match_MaxBits&&this.diff_levenshtein(u)/l.length>this.Patch_DeleteThreshold)o[a]=!1;else{this.diff_cleanupSemanticLossless(u);for(var d=0,m,p=0;p<e[a].diffs.length;p++){var g=e[a].diffs[p];g[0]!==oe&&(m=this.diff_xIndex(u,d)),g[0]===Ee?t=t.substring(0,s+m)+g[1]+t.substring(s+m):g[0]===be&&(t=t.substring(0,s+m)+t.substring(s+this.diff_xIndex(u,d+g[1].length))),g[0]!==be&&(d+=g[1].length)}}}}}return t=t.substring(r.length,t.length-r.length),[t,o]};U.prototype.patch_addPadding=function(e){for(var t=this.Patch_Margin,r="",n=1;n<=t;n++)r+=String.fromCharCode(n);for(var n=0;n<e.length;n++)e[n].start1+=t,e[n].start2+=t;var o=e[0],a=o.diffs;if(a.length==0||a[0][0]!=oe)a.unshift(new U.Diff(oe,r)),o.start1-=t,o.start2-=t,o.length1+=t,o.length2+=t;else if(t>a[0][1].length){var i=t-a[0][1].length;a[0][1]=r.substring(a[0][1].length)+a[0][1],o.start1-=i,o.start2-=i,o.length1+=i,o.length2+=i}if(o=e[e.length-1],a=o.diffs,a.length==0||a[a.length-1][0]!=oe)a.push(new U.Diff(oe,r)),o.length1+=t,o.length2+=t;else if(t>a[a.length-1][1].length){var i=t-a[a.length-1][1].length;a[a.length-1][1]+=r.substring(0,i),o.length1+=i,o.length2+=i}return r};U.prototype.patch_splitMax=function(e){for(var t=this.Match_MaxBits,r=0;r<e.length;r++)if(!(e[r].length1<=t)){var n=e[r];e.splice(r--,1);for(var o=n.start1,a=n.start2,i="";n.diffs.length!==0;){var l=new U.patch_obj,s=!0;for(l.start1=o-i.length,l.start2=a-i.length,i!==""&&(l.length1=l.length2=i.length,l.diffs.push(new U.Diff(oe,i)));n.diffs.length!==0&&l.length1<t-this.Patch_Margin;){var c=n.diffs[0][0],f=n.diffs[0][1];c===Ee?(l.length2+=f.length,a+=f.length,l.diffs.push(n.diffs.shift()),s=!1):c===be&&l.diffs.length==1&&l.diffs[0][0]==oe&&f.length>2*t?(l.length1+=f.length,o+=f.length,s=!1,l.diffs.push(new U.Diff(c,f)),n.diffs.shift()):(f=f.substring(0,t-l.length1-this.Patch_Margin),l.length1+=f.length,o+=f.length,c===oe?(l.length2+=f.length,a+=f.length):s=!1,l.diffs.push(new U.Diff(c,f)),f==n.diffs[0][1]?n.diffs.shift():n.diffs[0][1]=n.diffs[0][1].substring(f.length))}i=this.diff_text2(l.diffs),i=i.substring(i.length-this.Patch_Margin);var u=this.diff_text1(n.diffs).substring(0,this.Patch_Margin);u!==""&&(l.length1+=u.length,l.length2+=u.length,l.diffs.length!==0&&l.diffs[l.diffs.length-1][0]===oe?l.diffs[l.diffs.length-1][1]+=u:l.diffs.push(new U.Diff(oe,u))),s||e.splice(++r,0,l)}}};U.prototype.patch_toText=function(e){for(var t=[],r=0;r<e.length;r++)t[r]=e[r];return t.join("")};U.prototype.patch_fromText=function(e){var t=[];if(!e)return t;for(var r=e.split(`
|
|
3
|
+
`),n=0,o=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;n<r.length;){var a=r[n].match(o);if(!a)throw new Error("Invalid patch string: "+r[n]);var i=new U.patch_obj;for(t.push(i),i.start1=parseInt(a[1],10),a[2]===""?(i.start1--,i.length1=1):a[2]=="0"?i.length1=0:(i.start1--,i.length1=parseInt(a[2],10)),i.start2=parseInt(a[3],10),a[4]===""?(i.start2--,i.length2=1):a[4]=="0"?i.length2=0:(i.start2--,i.length2=parseInt(a[4],10)),n++;n<r.length;){var l=r[n].charAt(0);try{var s=decodeURI(r[n].substring(1))}catch{throw new Error("Illegal escape in patch_fromText: "+s)}if(l=="-")i.diffs.push(new U.Diff(be,s));else if(l=="+")i.diffs.push(new U.Diff(Ee,s));else if(l==" ")i.diffs.push(new U.Diff(oe,s));else{if(l=="@")break;if(l!=="")throw new Error('Invalid patch mode "'+l+'" in: '+s)}n++}}return t};U.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0};U.patch_obj.prototype.toString=function(){var e,t;this.length1===0?e=this.start1+",0":this.length1==1?e=this.start1+1:e=this.start1+1+","+this.length1,this.length2===0?t=this.start2+",0":this.length2==1?t=this.start2+1:t=this.start2+1+","+this.length2;for(var r=["@@ -"+e+" +"+t+` @@
|
|
4
|
+
`],n,o=0;o<this.diffs.length;o++){switch(this.diffs[o][0]){case Ee:n="+";break;case be:n="-";break;case oe:n=" ";break}r[o+1]=n+encodeURI(this.diffs[o][1])+`
|
|
5
|
+
`}return r.join("").replace(/%20/g," ")};Un.exports=U;Un.exports.diff_match_patch=U;Un.exports.DIFF_DELETE=be;Un.exports.DIFF_INSERT=Ee;Un.exports.DIFF_EQUAL=oe});import{DOMParser as kp,XMLSerializer as Mp}from"@xmldom/xmldom";var xa=console,Vi=Object.freeze({silent:0,error:1,warn:2,info:3}),Cp=typeof process<"u"&&process?.env?.NODE_ENV==="production"?"warn":"info",Wi=Cp;function _p(e){let t=String(e||"").toLowerCase();return Object.prototype.hasOwnProperty.call(Vi,t)?t:Wi}function Ki(e){return Vi[Wi]>=Vi[e]}function Op(e,t={}){xa=e||console,t.level&&(Wi=_p(t.level))}function W(...e){Ki("info")&&(xa.log||(()=>{}))(...e)}function ir(...e){Ki("warn")&&(xa.warn||(()=>{}))(...e)}function Le(...e){Ki("error")&&(xa.error||(()=>{}))(...e)}var xc=null,bc=null;function Lp(e={}){"DOMParser"in e&&(xc=e.DOMParser),"XMLSerializer"in e&&(bc=e.XMLSerializer)}function Bp(){return xc||globalThis.DOMParser||kp}function $p(){return bc||globalThis.XMLSerializer||Mp}function Fp(e={}){let t=Bp();if(!t)throw new Error("DOMParser is not configured and no fallback XML parser is available.");return new t(e)}function le(){let e=$p();if(!e)throw new Error("XMLSerializer is not configured and no fallback XML serializer is available.");return new e}function Ic(e,t="text/xml"){let r=V(e,t);if(r.error){let n=new Error(r.error.message);throw n.code=r.error.code,n}return r.doc}function Dp(e){return e?.documentElement?String(e.documentElement.localName||e.documentElement.nodeName).toLowerCase()==="parsererror"?e.documentElement:e.getElementsByTagName?.("parsererror")?.[0]||null:null}function V(e,t="application/xml"){let r=[];if(typeof e!="string"||e.trim()==="")return{doc:null,error:{code:"PARSE_ERROR",message:"Input is not a non-empty XML string."},warnings:r};let n=(o,a)=>{let i=String(a||"XML parser diagnostic.");o==="fatalError"?Le("[XmlAdapter] XML fatal parse error:",i):(r.push(i),ir(`[XmlAdapter] XML ${o||"warning"}:`,i))};try{let a=Fp({onError:n}).parseFromString(e,t),i=Dp(a);if(!a?.documentElement||i){let l=i?.textContent||"Could not parse XML input.";return Le("[XmlAdapter] XML parse error:",l),{doc:null,error:{code:"PARSE_ERROR",message:l},warnings:r}}return{doc:a,error:null,warnings:r}}catch(o){let a=o?.message||String(o||"Could not parse XML input.");return Le("[XmlAdapter] XML parse error:",a),{doc:null,error:{code:"PARSE_ERROR",message:a},warnings:r}}}function Be(e){return le().serializeToString(e)}var Nc=()=>typeof process<"u"&&process.env?.DOCX_REDLINE_AUTHOR||"AI Redliner",Tc=Nc(),Sc="Unknown";function Up(e){Tc=typeof e=="string"&&e.trim()?e.trim():Nc()}function ae(){return Tc}function Xp(e){Sc=typeof e=="string"&&e.trim()?e.trim():"Unknown"}function Gi(){return Sc}var zp=[{regex:/<b>(.+?)<\/b>/i,format:{bold:!0}},{regex:/<strong>(.+?)<\/strong>/i,format:{bold:!0}},{regex:/<i>(.+?)<\/i>/i,format:{italic:!0}},{regex:/<em>(.+?)<\/em>/i,format:{italic:!0}},{regex:/<u>(.+?)<\/u>/i,format:{underline:!0}},{regex:/<s>(.+?)<\/s>/i,format:{strikethrough:!0}},{regex:/<strike>(.+?)<\/strike>/i,format:{strikethrough:!0}},{regex:/<del>(.+?)<\/del>/i,format:{strikethrough:!0}},{regex:/<b>(.+?)<\/b>/i,format:{bold:!0},isEscaped:!0},{regex:/<strong>(.+?)<\/strong>/i,format:{bold:!0},isEscaped:!0},{regex:/<i>(.+?)<\/i>/i,format:{italic:!0},isEscaped:!0},{regex:/<em>(.+?)<\/em>/i,format:{italic:!0},isEscaped:!0},{regex:/<u>(.+?)<\/u>/i,format:{underline:!0},isEscaped:!0},{regex:/<s>(.+?)<\/s>/i,format:{strikethrough:!0},isEscaped:!0},{regex:/\*\*\*(.+?)\*\*\*/,format:{bold:!0,italic:!0}},{regex:/\*\*\+\+(.+?)\+\+\*\*/,format:{bold:!0,underline:!0}},{regex:/\*\*(.+?)\*\*/,format:{bold:!0}},{regex:/(?<![A-Za-z0-9_])__(?=[^_\s])(.+?)(?<=[^_\s])__(?![A-Za-z0-9_])/,format:{bold:!0}},{regex:/\+\+(.+?)\+\+/,format:{underline:!0}},{regex:/~~(.+?)~~/,format:{strikethrough:!0}},{regex:/~(.+?)~/,format:{strikethrough:!0}},{regex:/\*(?!\*)(.+?)\*(?!\*)/,format:{italic:!0}},{regex:/(?<![A-Za-z0-9_])_(?=[^_\s])(.+?)(?<=[^_\s])_(?![A-Za-z0-9_])/,format:{italic:!0}}];function yt(e){if(!e)return{cleanText:"",formatHints:[]};let t=[],r="",n=[];for(let l of zp){let s,c=l.regex.source||l.regex.toString().replace(/^\/|\/[gimuy]*$/g,""),f="g"+(l.regex.ignoreCase?"i":""),u=new RegExp(c,f);for(;(s=u.exec(e))!==null;)n.push({start:s.index,end:s.index+s[0].length,fullMatch:s[0],innerText:l.isEscaped?jp(s[1]):s[1],format:l.format}),s.index===u.lastIndex&&u.lastIndex++}n.sort((l,s)=>l.start-s.start||s.end-l.end);let o=[],a=0;for(let l of n)l.start>=a&&(o.push(l),a=l.end);let i=0;for(let l of o){r+=e.slice(i,l.start);let s=yt(l.innerText),c=r.length;r+=s.cleanText;let f=r.length;t.push({start:c,end:f,format:l.format});for(let u of s.formatHints)t.push({start:c+u.start,end:c+u.end,format:u.format});i=l.end}return r+=e.slice(i),{cleanText:r,formatHints:t}}function sr(e,t,r){return e.filter(n=>n.start<r&&n.end>t)}function Hi(...e){let t={};for(let r of e)r&&Object.assign(t,r);return t}function jp(e){return e?e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'"):""}var ba=String.raw`(?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|\d+\.|[ivxlcIVXLC]+\.|[-*+\u2022])`,Ac=new RegExp(`^(\\s*)((?:${ba})\\s+)`),Ec=new RegExp(`^(\\s*)((?:${ba})\\s*)`),Vp=new RegExp(`^(\\s*)((?:${ba})\\s+)`,"m"),Wp=new RegExp(`^(\\s*)((?:${ba})\\s*)`,"m");function qi(e){return typeof e!="string"?!1:e.includes(`
|
|
6
|
+
`)&&Vp.test(e)}function Mn(e){return typeof e!="string"?!1:e.includes(`
|
|
7
|
+
`)&&Wp.test(e.trim())}function zt(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Ec:Ac;return e.match(n)}function Zt(e,t={}){let{allowZeroSpaceAfterMarker:r=!1}=t,n=r?Ec:Ac;return e.replace(n,"")}function Rc(e){return/^[-*+\u2022]$/.test(String(e||"").trim())?"bullet":"numbered"}function So(e){let t=String(e||"").trim();return Rc(t)==="bullet"?"bullet":/^\d+(?:\.\d+)*\.?$/.test(t)||/^\(\d+\)$/.test(t)?"decimal":/^[ivxlcdm]+\.$/.test(t)?"lowerRoman":/^[IVXLCDM]{2,}\.$/.test(t)?"upperRoman":/^[a-z]\.$/.test(t)?"lowerAlpha":/^[A-Z]\.$/.test(t)?"upperAlpha":"decimal"}function Kp(e){let t=String(e||"").trim();return/^\d+(?:\.\d+)+\.?$/.test(t)?Math.max(0,t.replace(/\.$/,"").split(".").length-1):null}function qr(e,t={}){let r=zt(String(e||""),t);if(!r)return null;let n=r[2].trim(),o=(r[1]||"").length,a=Math.max(1,Number(t.indentSpaces)||2),i=Rc(n);return{line:String(e||""),text:Zt(String(e||""),t),marker:n,indent:o,level:Math.min(8,Math.floor(o/a)),markerType:i,listType:i,numberingStyle:So(n),outlineLevel:i==="numbered"?Kp(n):null}}var B="http://schemas.openxmlformats.org/wordprocessingml/2006/main";var Bt=Object.freeze({EQUAL:"equal",DELETE:"delete",INSERT:"insert"}),H=Object.freeze({TEXT:"run",DELETION:"deletion",INSERTION:"insertion",HYPERLINK:"hyperlink",BOOKMARK:"bookmark",FIELD:"field",CONTAINER_START:"container_start",CONTAINER_END:"container_end",PARAGRAPH_START:"paragraph_start"}),Ln=Object.freeze({SDT:"sdt",SMART_TAG:"smartTag",CUSTOM_XML:"customXml",FIELD_COMPLEX:"fldComplex"}),_c=Object.freeze({PARAGRAPH:"paragraph",BULLET_LIST:"bullet_list",NUMBERED_LIST:"numbered_list",TABLE:"table"}),ve=Object.freeze({DECIMAL:"decimal",LOWER_ALPHA:"lowerLetter",UPPER_ALPHA:"upperLetter",LOWER_ROMAN:"lowerRoman",UPPER_ROMAN:"upperRoman",BULLET:"bullet",OUTLINE:"outline"}),Je=Object.freeze({PERIOD:"period",PAREN_RIGHT:"parenRight",PAREN_BOTH:"parenBoth",NONE:"none"});function Ze(e){return e?e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):""}var Yi=1e3,Pc=2147483647,Cc=1e4,Gp=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","cellIns","cellDel","comment"]),Oc=new WeakMap;function Hp(e){if(!e||e.nodeType!==1)return!1;let t=String(e.localName||e.nodeName||"").replace(/^.*:/,"");return Gp.has(t)?!e.namespaceURI||e.namespaceURI===B||String(e.nodeName||"").startsWith("w:"):!1}function qp(e){let t=e?.getAttributeNS?.(B,"id")||e?.getAttribute?.("w:id")||e?.getAttribute?.("id"),r=Number.parseInt(String(t??""),10);return Number.isInteger(r)&&r>=0?r:null}var De=class{constructor(t=Yi){this.startValue=Number.isInteger(t)&&t>=0?t:Yi,this.nextId=this.startValue,this.occupiedIds=new Set}seed(t){let r=-1,n=t?.nodeType===9?t.documentElement:t,o=n||null;for(;o;){if(Hp(o)){let i=qp(o);i!=null&&(this.occupiedIds.add(i),r=Math.max(r,i))}if(o.firstChild){o=o.firstChild;continue}for(;o&&o!==n&&!o.nextSibling;)o=o.parentNode;o=o&&o!==n?o.nextSibling:null}let a=Pc-Cc;return this.nextId=r>=a?this.startValue:Math.max(this.nextId,r+1),this.advanceToAvailableId(),this.nextId}advanceToAvailableId(){let t=Pc-Cc;for(this.nextId>=t&&(this.nextId=this.startValue);this.occupiedIds.has(this.nextId);)this.nextId+=1,this.nextId>=t&&(this.nextId=this.startValue)}next(){this.advanceToAvailableId();let t=this.nextId;return this.occupiedIds.add(t),this.nextId+=1,t}},Ao=new De;function Cr(e,t){let r=e?.nodeType===9?e:e?.ownerDocument;return r&&t instanceof De&&Oc.set(r,t),t}function lr(e){let t=e?.nodeType===9?e:e?.ownerDocument;return t&&Oc.get(t)||null}function _r(e,t=Yi){let r=new De(t);return r.seed(e),Cr(e,r),r}function kc(){return Ao.next()}function Ia(e=new Date){return e.toISOString()}function ue(e,t=null,r=null){let n=typeof e=="string"&&e.trim()?e.trim():ae(),o=t instanceof De?t:lr(t)||Ao,a=o.next();return o._receiptCollector&&o._receiptCollector.recordRevision(a,r||"structural"),{id:a,author:n,date:Ia()}}function Eo(e,t=null,{deferReceipt:r=!1}={}){let n=typeof e=="string"&&e.trim()?e.trim():ae(),o=t instanceof De?t:lr(t)||Ao,a=Ia(),i=o.next(),l=o.next();return o._receiptCollector&&!r&&(o._receiptCollector.recordRevision(i,"del"),o._receiptCollector.recordRevision(l,"ins")),{deletionId:i,insertionId:l,author:n,date:a,recordUsed:r?s=>o._receiptCollector?.recordRevision(s==="del"?i:l,s):null}}function cr(e,t=Ao){let r=t instanceof De?t:Ao,n=r.seed(e);return Cr(e,r),n}function Ji(e,t){if(!e||e.nodeType!==1)return!1;let r=String(e.localName||e.nodeName||"").replace(/^.*:/,"");return t!=null&&r!==t?!1:!e.namespaceURI||e.namespaceURI===B}function me(e,t){if(!e)return null;for(let r of Array.from(e.childNodes||[]))if(Ji(r,t))return r;return null}function Zi(e,t){return e?Array.from(e.childNodes||[]).filter(r=>Ji(r,t)):[]}function Qe(e,t){return me(e,t)}function Na(e){if(!e)return null;let t=typeof e.getAttributeNS=="function"&&e.getAttributeNS(B,"val")||e.getAttribute?.("w:val")||e.getAttribute?.("val")||null;return t===""?null:t}function Yp(e){let t=me(e,"numPr");return t?{element:t,numId:Na(me(t,"numId")),ilvl:Na(me(t,"ilvl")),numIdElement:me(t,"numId"),ilvlElement:me(t,"ilvl")}:null}function Mc(e){let t=me(e,"pStyle"),r=me(e,"outlineLvl");return{pPr:e||null,numPr:Yp(e),pStyle:Na(t),pStyleElement:t,outlineLvl:Na(r),outlineLvlElement:r}}function at(e){return Mc(me(e,"pPr"))}function Lc(e){return me(e,"rPr")}function Bc(e){let t=me(me(e,"pPr"),"pPrChange"),r=me(t,"pPr");return r?Mc(r):null}function Jp(e){if(!e||e.nodeType!==1)return[];let t=Ji(e,"p")?[e]:[];return typeof e.getElementsByTagNameNS=="function"&&t.push(...Array.from(e.getElementsByTagNameNS(B,"p"))),t}function jt(e){let t=[];for(let r of Jp(e)){let n=at(r).numPr?.numIdElement;n&&t.push(n)}return t}function Bn(e){return!e||typeof e.getElementsByTagNameNS!="function"?[]:Array.from(e.getElementsByTagNameNS(B,"numId"))}function $c(e,t){return e<t-1}function $n(e,t,r){return $c(t,r)?e+`
|
|
8
|
+
`:e}function Yr(e,t,r){return $c(t,r)?e+1:e}function Ro(e,t){return!e||typeof e.getElementsByTagName!="function"?[]:Array.from(e.getElementsByTagName(t))}function Ue(e,t){if(!e||typeof e.getElementsByTagName!="function")return null;let r=e.getElementsByTagName(t);return r.length>0?r[0]:null}function Ke(e,t,r){return!e||typeof e.getElementsByTagNameNS!="function"?[]:Array.from(e.getElementsByTagNameNS(t,r))}function Ge(e,t,r){if(!e||typeof e.getElementsByTagNameNS!="function")return null;let n=e.getElementsByTagNameNS(t,r);return n.length>0?n[0]:null}function it(e,t,r,n=`w:${r}`){let o=Ke(e,t,r);return o.length>0?o:Ro(e,n)}function st(e,t,r,n=`w:${r}`){let o=Ge(e,t,r);return o||Ue(e,n)}function $e(e){return Ue(e,"parsererror")}function Qi(e){return Array.from(e?.childNodes||[])}function Fc(e){return Array.from(e.attributes).map(t=>`${t.name}="${t.value}"`).join(" ")}function es(e,t,r=""){return!e||e.namespaceURI!==t?!1:r?e.localName===r:!0}var ts=0;function Dn(e,t={}){let r=[],n="",o=t.xmlDoc||null;if(!e&&!o)return{runModel:r,acceptedText:n,pPr:null};try{let a=o?{doc:o,error:null}:V(e,"application/xml"),i=a.doc;if(a.error||!i)return Le("OOXML parse error:",a.error?.message),{runModel:r,acceptedText:n,pPr:null,error:a.error};let l=$e(i);if(l)return Le("OOXML parse error:",l.textContent),{runModel:r,acceptedText:n,pPr:null};let s=Ke(i,B,"p");return s.length===0?(ir("No paragraphs found in OOXML"),{runModel:r,acceptedText:n,pPr:null}):Uc(s,{includeParagraphBoundaries:!0})}catch(a){return Le("Error ingesting OOXML:",a),{runModel:r,acceptedText:n,pPr:null}}}function rs(e){return e?Uc([e],{includeParagraphBoundaries:!1}):{runModel:[],acceptedText:"",pPr:null}}function Po(e){let{numPr:t}=at(e);if(!t||!t.numIdElement)return null;let r=t.numId;if(!/^\d+$/.test(r)||Number.parseInt(r,10)===0)return null;let n=r==="1"?"bullet":r==="2"?"numbered":"unknown";return{numId:r,ilvl:parseInt(t.ilvl||"0",10),type:n}}function Uc(e,t={}){let r=t.includeParagraphBoundaries??!0,n=[],o="",a=0,i=null;for(let l=0;l<e.length;l++){let s=e[l],c=Ge(s,B,"pPr");l===0&&(i=c),n.push({kind:H.PARAGRAPH_START,pPrElement:c||null,startOffset:a,endOffset:a,text:""});let f=Fn(s,a,n);o+=f.text,a=o.length,r&&(o=$n(o,l,e.length),a=Yr(a,l,e.length))}return{runModel:n,acceptedText:o,pPr:i}}function Fn(e,t,r){let n=t,o="",a=Zp(r);for(let i of Qi(e)){if(es(i,B,"pPr")||es(i,B,"proofErr"))continue;let l=a.get(i.localName);if(!l)continue;let s=l(i,n);n=s.offset,o+=s.text}return{offset:n,text:o}}function Zp(e){let t=new Map;t.set("sdt",(r,n)=>{let o=`sdt_${ts++}`,a=Ge(r,B,"sdtPr"),i=Ge(r,B,"sdtContent");e.push({kind:H.CONTAINER_START,containerKind:Ln.SDT,containerId:o,propertiesXml:a?Be(a):"",startOffset:n,endOffset:n,text:""});let l=i?Fn(i,n,e):{offset:n,text:""};return e.push({kind:H.CONTAINER_END,containerKind:Ln.SDT,containerId:o,startOffset:l.offset,endOffset:l.offset,text:""}),l}),t.set("smartTag",(r,n)=>{let o=`smartTag_${ts++}`;e.push({kind:H.CONTAINER_START,containerKind:Ln.SMART_TAG,containerId:o,propertiesXml:Fc(r),startOffset:n,endOffset:n,text:""});let a=Fn(r,n,e);return e.push({kind:H.CONTAINER_END,containerKind:Ln.SMART_TAG,containerId:o,startOffset:a.offset,endOffset:a.offset,text:""}),a}),t.set("del",(r,n)=>{let o=Dc(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveFrom",(r,n)=>{let o=Dc(r,n);return o&&e.push(o),{offset:n,text:""}}),t.set("moveTo",(r,n)=>Fn(r,n,e));for(let r of["moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"])t.set(r,(n,o)=>(e.push({kind:H.BOOKMARK,nodeXml:Be(n),startOffset:o,endOffset:o,text:""}),{offset:o,text:""}));return t.set("bookmarkStart",(r,n)=>(e.push({kind:H.BOOKMARK,nodeXml:Be(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("bookmarkEnd",(r,n)=>(e.push({kind:H.BOOKMARK,nodeXml:Be(r),startOffset:n,endOffset:n,text:""}),{offset:n,text:""})),t.set("ins",(r,n)=>Fn(r,n,e)),t.set("hyperlink",(r,n)=>{let o=`hyperlink_${ts++}`,a=r.getAttribute("r:id")||"",i=r.getAttribute("w:anchor")||"";e.push({kind:H.CONTAINER_START,containerKind:"hyperlink",containerId:o,propertiesXml:JSON.stringify({rId:a,anchor:i}),startOffset:n,endOffset:n,text:""});let l=Fn(r,n,e);return e.push({kind:H.CONTAINER_END,containerKind:"hyperlink",containerId:o,startOffset:l.offset,endOffset:l.offset,text:""}),l}),t.set("r",(r,n)=>{let o=Qp(r,n);return!o||!o.text?{offset:n,text:""}:(e.push(o),{offset:n+o.text.length,text:o.text})}),t}function Qp(e,t){let r=st(e,B,"rPr"),n=r?Be(r):"",o="";for(let a of Qi(e)){let i=a.nodeName;i.endsWith(":t")||i==="t"?o+=a.textContent||"":i.endsWith(":br")||i==="br"||i.endsWith(":cr")||i==="cr"?o+=`
|
|
9
|
+
`:i.endsWith(":tab")||i==="tab"?o+=" ":i.endsWith(":noBreakHyphen")||i==="noBreakHyphen"?o+="\u2011":(i.endsWith(":softHyphen")||i==="softHyphen")&&(o+="\xAD")}return o?{kind:H.TEXT,text:o,rPrXml:n,startOffset:t,endOffset:t+o.length}:null}function Dc(e,t){let r=e.getAttribute("w:author")||"",n="",o=Ke(e,B,"delText");for(let i of o)n+=i.textContent||"";let a=Ke(e,B,"r");for(let i of a){let l=Ke(i,B,"delText");for(let s of l)n+=s.textContent||""}return n?{kind:H.DELETION,text:n,rPrXml:"",startOffset:t,endOffset:t,author:r,nodeXml:Be(e)}:null}function os(e){let t=Ge(e,B,"tblGrid"),r=t?Ke(t,B,"gridCol"):[],n=it(e,B,"tr"),o=n.length,a=n.reduce((f,u)=>{let d=it(u,B,"tc");return Math.max(f,d.length)},0),i=r.length||a,l=Array.from({length:o},()=>Array.from({length:i},()=>null)),s=new Map,c=new Map;for(let f=0;f<n.length;f++){let u=n[f],d=it(u,B,"tc"),m=0;for(let p=0;p<d.length;p++){let g=d[p],h=Ge(g,B,"tcPr");for(;m<i&&l[f][m]!==null;)m++;if(m>=i)break;let v=h?Ge(h,B,"gridSpan")||Ue(h,"w:gridSpan"):null,w=parseInt(v?.getAttribute("w:val")||"1",10),y=h?Ge(h,B,"vMerge")||Ue(h,"w:vMerge"):null,x=y?.getAttribute("w:val"),b=y!==null,T;if(b&&x!=="restart"){let A=c.get(m);A?(A.cell.rowSpan++,T={gridRow:f,gridCol:m,rowSpan:0,colSpan:w,tcNode:g,blocks:[],tcPrXml:ns(h),isMergeOrigin:!1,isMergeContinuation:!0,mergeOrigin:A.cell}):T=eg(f,m,w,g,h)}else{let A=Xc(g);if(T={gridRow:f,gridCol:m,rowSpan:1,colSpan:w,tcNode:g,blocks:A,tcPrXml:ns(h),isMergeOrigin:b&&x==="restart",isMergeContinuation:!1,getText:()=>A.map(E=>E.acceptedText).join(`
|
|
10
|
+
`)},b&&x==="restart")for(let E=0;E<w;E++)c.set(m+E,{originRow:f,cell:T});else for(let E=0;E<w;E++)c.delete(m+E)}for(let A=0;A<w;A++){let E=m+A;E<i&&(l[f][E]=T,s.set(`${f},${E}`,T))}m+=w}}return{rowCount:o,colCount:i,grid:l,cellMap:s,tblPrXml:tg(e),tblGridXml:rg(e),trPrList:Array.from(n).map(f=>ng(f))}}function eg(e,t,r,n,o){let a=Xc(n);return{gridRow:e,gridCol:t,rowSpan:1,colSpan:r,tcNode:n,blocks:a,tcPrXml:ns(o),isMergeOrigin:!1,isMergeContinuation:!1,getText:()=>a.map(i=>i.acceptedText).join(`
|
|
11
|
+
`)}}function Xc(e){return it(e,B,"p").map(r=>{let{runModel:n,acceptedText:o,pPr:a}=rs(r);return{runModel:n,acceptedText:o,pPr:a}})}function ns(e){return e?Be(e):"<w:tcPr/>"}function tg(e){let t=Ge(e,B,"tblPr");return t?Be(t):"<w:tblPr/>"}function rg(e){let t=Ge(e,B,"tblGrid");return t?Be(t):"<w:tblGrid/>"}function ng(e){let t=Ge(e,B,"trPr");return t?Be(t):"<w:trPr/>"}var Wc=yc(as(),1);var og=65536,Ta=262144,Sa=1,Aa=55296-Sa,ag=8192,ig=Aa+ag,is=class extends Error{constructor(t=Ta){super(`Word diff exceeds the safe limit of ${t} unique tokens.`),this.name="DiffTokenLimitError",this.code="DIFF_TOKEN_LIMIT",this.limit=t}};function Kc(e){return e?.code==="DIFF_TOKEN_LIMIT"}function ss(e={}){let t=e.diffTimeoutSeconds??0;if(!Number.isFinite(t)||t<0)throw new TypeError("diffTimeoutSeconds must be a finite non-negative number.");let r=new Wc.diff_match_patch;return r.Diff_Timeout=t,r}var sg=/^[("'\[{“‘]+/u,lg=/[)"'\]}”’,.;:!?]+$/u;function zc(e,t=null){let r=[],n=s=>{if(!t||t.size===0){r.push(s);return}let c=0;for(let f=0;f<s.length;f++)t.has(s[f])&&(f>c&&r.push(s.slice(c,f)),r.push(s[f]),c=f+1);c<s.length&&r.push(s.slice(c))},o=s=>{let c=s.match(sg)?.[0]||"",f=s.slice(c.length),u=f.match(lg)?.[0]||"",d=f.slice(0,f.length-u.length);if(!d){n(s);return}for(let m of c)n(m);n(d);for(let m of u)n(m)},a=e.match(/^\s+/);a&&r.push(a[0]);let i=/(\S+)(\s*)/g;i.lastIndex=a?.[0].length||0;let l;for(;(l=i.exec(e))!==null;)l[1]&&o(l[1]),l[2]&&r.push(l[2]);return r}function cg(e,t,r={}){let n=[],o=new Map,a=r.maxTokens??Ta;if(!Number.isInteger(a)||a<1||a>Ta)throw new RangeError(`maxTokens must be an integer from 1 to ${Ta}.`);function i(u){let d="",m=[];for(let p of u){let g=o.get(p);if(g===void 0){if(n.length>=a)throw new is(a);g=n.length,n.push(p),o.set(p,g)}m.push(g),d+=String.fromCodePoint(og+g)}return{chars:d,tokenIds:m}}let l=zc(e,r.atomicChars),s=zc(t,r.atomicChars),c=i(l),f=i(s);return{chars1:c.chars,chars2:f.chars,wordArray:n,tokenIds1:c.tokenIds,tokenIds2:f.tokenIds}}function ug(e){let t=e<Aa?Sa+e:57344+(e-Aa);return String.fromCharCode(t)}function ls(e){if(e>=Sa&&e<55296)return e-Sa;if(e>=57344&&e<=65535)return Aa+e-57344;throw new RangeError(`BMP diff token U+${e.toString(16).toUpperCase()} has no mapping.`)}function jc(e){let t="";for(let r of e)t+=ug(r);return t}function fg(e,t){return e.map(([r,n])=>{let o=[];for(let a=0;a<n.length;a++){let i=ls(n.charCodeAt(a));if(i>=t.length)throw new RangeError(`BMP diff token ${i} has no mapping.`);o.push(t[i])}return[r,o.join("")]})}function dg(e,t,r){let n=0,o=Math.min(e.length,t.length);for(;n<o&&e[n]===t[n];)n++;let a=0;for(;a<o-n&&e[e.length-1-a]===t[t.length-1-a];)a++;let i=f=>f.map(u=>r[u]).join(""),l=[];n&&l.push([0,i(e.slice(0,n))]);let s=e.slice(n,e.length-a),c=t.slice(n,t.length-a);return s.length&&l.push([-1,i(s)]),c.length&&l.push([1,i(c)]),a&&l.push([0,i(e.slice(e.length-a))]),l}function Co(e,t,r={}){if(e===t)return[[0,e]];if(!e)return[[1,t]];if(!t)return[[-1,e]];let{cleanupSemantic:n=!0}=r,{wordArray:o,tokenIds1:a,tokenIds2:i}=cg(e,t,r);if(o.length>ig)return dg(a,i,o);let l=ss(r),s=l.diff_main(jc(a),jc(i));return n&&(l.diff_cleanupSemantic(s),gg(l,s,o)),fg(s,o)}var Gc=/^[\p{L}\p{N}][\p{L}\p{N}'’-]{3,}$/u;function Vc(e,t){for(let r=0;r<e.length;r++)if(Gc.test(t[ls(e.charCodeAt(r))]))return!0;return!1}var mg=25e4;function pg(e,t,r){let n=e.length,o=t.length;if(!n||!o||(n+1)*(o+1)>mg)return null;let a=d=>{let m=r[ls(d.charCodeAt(0))];return Gc.test(m)?m.length*100:m.length},i=o+1,l=new Float64Array((n+1)*i);for(let d=n-1;d>=0;d--)for(let m=o-1;m>=0;m--){let p=Math.max(l[(d+1)*i+m],l[d*i+m+1]);l[d*i+m]=e[d]===t[m]?Math.max(p,a(e[d])+l[(d+1)*i+m+1]):p}let s=[],c=(d,m)=>{let p=s[s.length-1];p?.[0]===d?p[1]+=m:s.push([d,m])},f=0,u=0;for(;f<n&&u<o;){let d=l[f*i+u];e[f]===t[u]&&d===a(e[f])+l[(f+1)*i+u+1]?(c(0,e[f]),f++,u++):l[(f+1)*i+u]>=l[f*i+u+1]?c(-1,e[f++]):c(1,t[u++])}for(;f<n;)c(-1,e[f++]);for(;u<o;)c(1,t[u++]);return s}function gg(e,t,r){for(let n=0;n<t.length;n++){let o=-1,a=-1;if(t[n][0]===-1&&t[n+1]?.[0]===1)o=n,a=n+1;else if(t[n][0]===1&&t[n+1]?.[0]===-1)a=n,o=n+1;else continue;let i=pg(t[o][1],t[a][1],r);if(!i?.some(([s,c])=>s===0&&Vc(c,r)))continue;let l=[];for(let[s,c]of i)s===0&&!Vc(c,r)?l.push([-1,c],[1,c]):l.push([s,c]);e.diff_cleanupMerge(l),t.splice(n,2,...l),n+=l.length-1}}function Hc(e,t,r={}){return e===t?[[0,e]]:ss(r).diff_main(e,t)}function qc(e,t){if(e===t)return[[0,e]];if(!e)return[[1,t]];let r=0;for(let o=0;o<t.length&&r<e.length;o++)t[o]===e[r]&&r++;if(r!==e.length)return null;let n=ss().diff_main(e,t);return n.some(([o])=>o===-1)?null:n}function Xn(e,t,r={}){if(e===t)return[{type:Bt.EQUAL,startOffset:0,endOffset:e.length,text:e}];if(!e)return[{type:Bt.INSERT,startOffset:0,endOffset:0,text:t}];if(!t)return[{type:Bt.DELETE,startOffset:0,endOffset:e.length,text:e}];let n=Co(e,t,r),o=[],a=0;for(let[i,l]of n)i===0?(o.push({type:Bt.EQUAL,startOffset:a,endOffset:a+l.length,text:l}),a+=l.length):i===-1?(o.push({type:Bt.DELETE,startOffset:a,endOffset:a+l.length,text:l}),a+=l.length):i===1&&o.push({type:Bt.INSERT,startOffset:a,endOffset:a,text:l});return o}var hg=/\s+xmlns:[^=]+="[^"]*"/g;function zn(e,t){let r=Ig(t),n=[],o=0;for(let a of e){if(a.kind!==H.TEXT&&a.kind!==H.HYPERLINK){n.push(a);continue}for(;o<r.length&&r[o]<=a.startOffset;)o++;let i=o,l=a.startOffset,s=!1;for(;i<r.length;){let c=r[i];if(c>=a.endOffset)break;c>l&&(s=!0,n.push({...a,text:a.text.slice(l-a.startOffset,c-a.startOffset),startOffset:l,endOffset:c}),l=c),i++}if(o=i,!s){n.push(a);continue}n.push({...a,text:a.text.slice(l-a.startOffset),startOffset:l,endOffset:a.endOffset})}return n}function jn(e,t,r){let{generateRedlines:n,author:o}=r,a=[],i=new Set,l=Ng(t),s=xg(e),c=bg(l.nonInsertOps),f={containerStack:[],lastParagraphStartIndex:-1,currentParagraphPPrXml:"",currentParagraphPPrElement:null};for(let d of e){if(d.kind===H.CONTAINER_START){f.containerStack.push(d.containerId),a.push({...d});continue}if(d.kind===H.CONTAINER_END){f.containerStack.pop(),a.push({...d});continue}if(d.kind===H.PARAGRAPH_START){f.currentParagraphPPrXml=typeof d.pPrXml=="string"?d.pPrXml:"",f.currentParagraphPPrElement=d.pPrElement||null,a.push({...d}),f.lastParagraphStartIndex=a.length-1;continue}if(d.kind===H.BOOKMARK||d.kind===H.DELETION){a.push({...d});continue}let m=c(d.startOffset,d.endOffset),p=l.insertOpsByStartOffset.get(d.startOffset)||[];for(let g of p)i.has(g)||(i.add(g),wg({insertOp:g,splitModel:e,styleLookup:s,patchedModel:a,state:f,options:r,generateRedlines:n,author:o}));if(!m||m.type===Bt.EQUAL){a.push({...d,containerContext:f.containerStack.length>0?f.containerStack[f.containerStack.length-1]:null});continue}m.type===Bt.DELETE&&n&&a.push({...d,kind:H.DELETION,author:o,containerContext:f.containerStack.length>0?f.containerStack[f.containerStack.length-1]:null})}let u=e.length>0?Math.max(...e.map(d=>d.endOffset)):0;for(let d of l.sortedInsertOps){if(d.startOffset<u||i.has(d))continue;let m=e[e.length-1];a.push({kind:n?H.INSERTION:H.TEXT,text:d.text,rPrXml:m?.rPrXml||"",startOffset:d.startOffset,endOffset:d.startOffset+d.text.length,author:n?o:void 0})}return a}function wg(e){let{insertOp:t,styleLookup:r,patchedModel:n,state:o,options:a,generateRedlines:i,author:l}=e,s=t.text.split(`
|
|
12
|
+
`),c=yg(r,t.startOffset,t.text);for(let f=0;f<s.length;f++){let u=vg(s[f],a.numberingService,o),d=u.lineText;if(f>0){let m=Yc(o);u.isListLine&&u.numId&&(m=a.numberingService.buildListPPr(u.numId,u.ilvl)),n.push({kind:H.PARAGRAPH_START,pPrXml:m,startOffset:t.startOffset,endOffset:t.startOffset,text:""}),o.currentParagraphPPrXml=m,o.currentParagraphPPrElement=null,o.lastParagraphStartIndex=n.length-1}else if(u.isListLine&&u.numId&&o.lastParagraphStartIndex>=0){let m=a.numberingService.buildListPPr(u.numId,u.ilvl);n[o.lastParagraphStartIndex].pPrXml=m,n[o.lastParagraphStartIndex].pPrElement=null,o.currentParagraphPPrXml=m,o.currentParagraphPPrElement=null,W(`[Patching] Converted current paragraph to list item: numId=${u.numId}, ilvl=${u.ilvl}`)}(d.length>0||f>0)&&n.push({kind:i?H.INSERTION:H.TEXT,text:d,rPrXml:c?.rPrXml||"",startOffset:t.startOffset,endOffset:t.startOffset+d.length,author:i?l:void 0,containerContext:o.containerStack.length>0?o.containerStack[o.containerStack.length-1]:null})}}function vg(e,t,r){if(!t)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let n=zt(e,{allowZeroSpaceAfterMarker:!0});if(!n)return{lineText:e,isListLine:!1,numId:null,ilvl:0};let o=n[2].trim(),a=t.detectNumberingFormat(o),i=e.match(/^(\s*)/),l=i?i[1].length:0,s=l>=4?4:2,c=Math.floor(l/s),f=Yc(r),u=Zt(e,{allowZeroSpaceAfterMarker:!0}),d=f.match(/w:numId w:val="(\d+)"/),m=f.match(/w:ilvl w:val="(\d+)"/),p=d?d[1]:null,g=m?parseInt(m[1],10):0,h=t.getOrCreateNumId({type:a.format},{numId:p,type:"unknown"}),v=a.format==="outline"?Math.min(8,a.depth):Math.min(8,c+g);return{lineText:u,isListLine:!0,numId:h,ilvl:v}}function Yc(e){return e.currentParagraphPPrXml?e.currentParagraphPPrXml:e.currentParagraphPPrElement?(e.currentParagraphPPrXml=Be(e.currentParagraphPPrElement).replace(hg,""),e.currentParagraphPPrXml):""}function yg(e,t,r){let n=e.findRunBefore(t),o=e.findRunAfter(t);return!n&&!o?null:n?o?r&&r.endsWith(" ")?o:(r&&r.startsWith(" "),n):n:o}function xg(e){let t=e.filter(o=>o.kind===H.TEXT),r=t.map(o=>o.startOffset),n=t.map(o=>o.endOffset);return{findRunBefore(o){let a=0,i=n.length-1,l=-1;for(;a<=i;){let s=a+i>>1;n[s]<=o?(l=s,a=s+1):i=s-1}return l>=0?t[l]:null},findRunAfter(o){let a=0,i=r.length-1,l=-1;for(;a<=i;){let s=a+i>>1;r[s]>=o?(l=s,i=s-1):a=s+1}return l>=0?t[l]:null}}}function bg(e){let t=0;return(r,n)=>{for(;t<e.length&&e[t].endOffset<=r;)t++;let o=e[t];return o&&o.startOffset<=r&&o.endOffset>=n?o:null}}function Ig(e){let t=new Set;for(let r of e)t.add(r.startOffset),t.add(r.endOffset);return Array.from(t).sort((r,n)=>r-n)}function Ng(e){let t=new Map,r=[],n=[];for(let o of e){if(o.type===Bt.INSERT){t.has(o.startOffset)||t.set(o.startOffset,[]),t.get(o.startOffset).push(o),n.push(o);continue}r.push(o)}return r.sort((o,a)=>o.startOffset-a.startOffset||o.endOffset-a.endOffset),n.sort((o,a)=>o.startOffset-a.startOffset||o.endOffset-a.endOffset),{insertOpsByStartOffset:t,nonInsertOps:r,sortedInsertOps:n}}var eu="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Tg="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Sg="http://schemas.microsoft.com/office/2006/xmlPackage",Jc="http://schemas.openxmlformats.org/package/2006/relationships",Ag='<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>',Zc='<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>';var Eg=`
|
|
13
|
+
<w:numbering xmlns:w="${eu}">
|
|
14
14
|
<w:abstractNum w:abstractNumId="0">
|
|
15
15
|
<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="•"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr></w:lvl>
|
|
16
16
|
</w:abstractNum>
|
|
@@ -19,23 +19,23 @@ var pp=Object.create;var sc=Object.defineProperty;var gp=Object.getOwnPropertyDe
|
|
|
19
19
|
</w:abstractNum>
|
|
20
20
|
<w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>
|
|
21
21
|
<w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num>
|
|
22
|
-
</w:numbering>`.trim();function
|
|
22
|
+
</w:numbering>`.trim();function Rg(e){return e?e.replace(/<\?xml[^>]*\?>/g,""):""}function tu(e,t=!0){let r=t?` xmlns:r="${Tg}"`:"";return`<w:document xmlns:w="${eu}"${r}><w:body>${e}</w:body></w:document>`}function Qc(e){return`
|
|
23
23
|
<pkg:part pkg:name="/word/numbering.xml" pkg:contentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml">
|
|
24
24
|
<pkg:xmlData>
|
|
25
|
-
${
|
|
25
|
+
${Rg(e)}
|
|
26
26
|
</pkg:xmlData>
|
|
27
|
-
</pkg:part>`}function
|
|
28
|
-
<pkg:package xmlns:pkg="${
|
|
27
|
+
</pkg:part>`}function ru(e,t="",r=""){return`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
28
|
+
<pkg:package xmlns:pkg="${Sg}">
|
|
29
29
|
<pkg:part pkg:name="/_rels/.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml">
|
|
30
30
|
<pkg:xmlData>
|
|
31
|
-
<Relationships xmlns="${
|
|
32
|
-
${
|
|
31
|
+
<Relationships xmlns="${Jc}">
|
|
32
|
+
${Ag}
|
|
33
33
|
</Relationships>
|
|
34
34
|
</pkg:xmlData>
|
|
35
35
|
</pkg:part>
|
|
36
36
|
<pkg:part pkg:name="/word/_rels/document.xml.rels" pkg:contentType="application/vnd.openxmlformats-package.relationships+xml">
|
|
37
37
|
<pkg:xmlData>
|
|
38
|
-
<Relationships xmlns="${
|
|
38
|
+
<Relationships xmlns="${Jc}">
|
|
39
39
|
${t}
|
|
40
40
|
</Relationships>
|
|
41
41
|
</pkg:xmlData>
|
|
@@ -45,9 +45,9 @@ var pp=Object.create;var sc=Object.defineProperty;var gp=Object.getOwnPropertyDe
|
|
|
45
45
|
${e}
|
|
46
46
|
</pkg:xmlData>
|
|
47
47
|
</pkg:part>
|
|
48
|
-
</pkg:package>`}function
|
|
48
|
+
</pkg:package>`}function nu(e,t={}){let{includeNumbering:r=!1,numberingXml:n=null,appendTrailingParagraph:o=!0}=t,a=o?`${e}<w:p><w:pPr></w:pPr></w:p>`:e,i=tu(a,!0),l="",s="";return n?(l=Zc,s+=Qc(n)):r&&(l=Zc,s+=Qc(Eg)),ru(i,l,s)}function ou(e){let t=tu(e,!0);return ru(t)}var Pg=/\s+xmlns:[^=]+="[^"]*"/g;function lt(e,t,r=[],n={}){let o=Cg(n),{generateRedlines:a}=o,i=[],l="",s=null,c=[];function f(){if(c.length>0||i.length===0){let u="";l?u=Jr(l):s?(l=Jr(Be(s)),u=l):t&&(typeof t=="string"?u=t:u=Be(t),u=Jr(u)),i.push(`<w:p>${u}${c.join("")}</w:p>`),c=[]}}for(let u of e)switch(u.kind){case H.PARAGRAPH_START:(c.length>0||i.length>0)&&f(),l=u.pPrXml||"",s=u.pPrElement||null;break;case H.TEXT:c.push(au(u,r,o));break;case H.DELETION:a&&c.push(_g(u,o));break;case H.INSERTION:a?c.push(Og(u,r,o)):c.push(au(u,r,o));break;case H.BOOKMARK:case H.HYPERLINK:u.nodeXml&&c.push(Jr(u.nodeXml));break;case H.CONTAINER_START:if(u.containerKind==="sdt")c.push(`<w:sdt>${u.propertiesXml}<w:sdtContent>`);else if(u.containerKind==="smartTag")c.push(`<w:smartTag ${u.propertiesXml}>`);else if(u.containerKind==="hyperlink"){let d=JSON.parse(u.propertiesXml),m=d.rId?` r:id="${d.rId}"`:"",p=d.anchor?` w:anchor="${d.anchor}"`:"";c.push(`<w:hyperlink${m}${p}>`)}break;case H.CONTAINER_END:u.containerKind==="sdt"?c.push("</w:sdtContent></w:sdt>"):u.containerKind==="smartTag"?c.push("</w:smartTag>"):u.containerKind==="hyperlink"&&c.push("</w:hyperlink>");break;default:ir("Unknown run kind:",u.kind)}return f(),i.join("")}function Cg(e){if(typeof e=="string")return{author:ae(),generateRedlines:!0,font:e,revisionIdAllocator:null};let t=e&&typeof e=="object"?e:{};return{author:typeof t.author=="string"&&t.author.trim()?t.author.trim():ae(),generateRedlines:t.generateRedlines??!0,font:t.font??null,revisionIdAllocator:t.revisionIdAllocator??null}}function au(e,t,r={}){let n=sr(t,e.startOffset,e.endOffset),o=r?.font??null,a=e.rPrXml?Jr(e.rPrXml):"";if(o&&(a=cs(a,o)),n.length===0)return Or(e.text,a);let i=[],l=0,s=e.text,c=e.startOffset;for(let f of n){let u=Math.max(0,f.start-c),d=Math.min(s.length,f.end-c);u>l&&i.push(Or(s.slice(l,u),a));let m=su(a,f.format);i.push(Or(s.slice(u,d),m)),l=d}return l<s.length&&i.push(Or(s.slice(l),a)),i.join("")}function Or(e,t){return e?`<w:r>${t||""}${iu(e,"w:t")}</w:r>`:""}function iu(e,t){return String(e).split(/(\r\n|[\n\r\v\t])/).map(r=>r===" "?"<w:tab/>":r===`
|
|
49
49
|
`||r==="\r"||r===`\r
|
|
50
|
-
`||r==="\v"?"<w:br/>":r?`<${t} xml:space="preserve">${
|
|
50
|
+
`||r==="\v"?"<w:br/>":r?`<${t} xml:space="preserve">${Ze(r)}</${t}>`:"").join("")}function _g(e,t={}){let r=ue(t.author??ae(),t.revisionIdAllocator,"del"),n=t.font??null,o=e.rPrXml?Jr(e.rPrXml):"";return n&&(o=cs(o,n)),`<w:del w:id="${r.id}" w:author="${Ze(r.author)}" w:date="${r.date}"><w:r>${o}${iu(e.text,"w:delText")}</w:r></w:del>`}function Og(e,t,r={}){let n=ue(r.author??ae(),r.revisionIdAllocator,"ins"),o=r.font??null,a=sr(t,e.startOffset,e.endOffset),i="",l=e.rPrXml?Jr(e.rPrXml):"";if(o&&(l=cs(l,o)),a.length===0)i=Or(e.text,l);else{let s=0,c=e.text,f=e.startOffset;for(let u of a){let d=Math.max(0,u.start-f),m=Math.min(c.length,u.end-f);d>s&&(i+=Or(c.slice(s,d),l));let p=su(l,u.format);i+=Or(c.slice(d,m),p),s=m}s<c.length&&(i+=Or(c.slice(s),l))}return`<w:ins w:id="${n.id}" w:author="${Ze(n.author)}" w:date="${n.date}">`+i+"</w:ins>"}function cs(e,t){if(!t)return e;let r="";return e&&(r=e.replace(/<\/?w:rPr[^>]*>/g,"")),r.includes("<w:rFonts")?r=r.replace(/<w:rFonts[^>]*\/>/,`<w:rFonts w:ascii="${t}" w:hAnsi="${t}"/>`):r=`<w:rFonts w:ascii="${t}" w:hAnsi="${t}"/>`+r,`<w:rPr>${r}</w:rPr>`}function su(e,t){if(!t||Object.keys(t).length===0)return e;let r="";return e&&(r=e.replace(/<\/?w:rPr[^>]*>/g,"")),t.bold&&!r.includes("<w:b")&&(r="<w:b/>"+r),t.italic&&!r.includes("<w:i")&&(r="<w:i/>"+r),t.underline&&!r.includes("<w:u")&&(r='<w:u w:val="single"/>'+r),t.strikethrough&&!r.includes("<w:strike")&&(r="<w:strike/>"+r),`<w:rPr>${r}</w:rPr>`}function kr(e,t={}){let r=kg(t);return nu(e,r)}function kg(e){return typeof e=="boolean"?{includeNumbering:e}:!e||typeof e!="object"?{}:{includeNumbering:e.includeNumbering??!1,numberingXml:e.numberingXml??null,appendTrailingParagraph:e.appendTrailingParagraph??!0}}function Jr(e){return e?e.replace(Pg,""):""}function us(e){let t=String(e??"");return/^\d+$/.test(t)&&Number.parseInt(t,10)>0}var ur=class{constructor(){this.contextMap=new Map,this.nextNumId=1e3,this.customConfigs=[]}registerExistingNumId(t,r){us(r)&&this.contextMap.set(t,String(r))}getOrCreateNumId(t,r=null){let n=t.type||ve.BULLET;if(r&&us(r.numId)&&(r.type===n||r.type==="unknown"))return r.numId;if(this.contextMap.has(n)){let a=this.contextMap.get(n);if(us(a))return a;this.contextMap.delete(n)}if(n===ve.OUTLINE)return"3";if(n===ve.DECIMAL)return"2";if(n===ve.BULLET)return"1";if((r?parseInt(r.ilvl||"0"):0)===0&&n!==ve.DECIMAL&&n!==ve.BULLET){let a=`custom_${n}`;if(this.contextMap.has(a))return this.contextMap.get(a);let i=String(this.nextNumId++);return this.customConfigs.push({numId:i,levels:[{format:n,suffix:t.suffix||Je.PERIOD}]}),this.contextMap.set(a,i),i}return"2"}detectNumberingFormat(t){let r=(t||"").trim();if(!r)return{format:ve.BULLET,suffix:Je.NONE,depth:0};if(/^[-*•]$/.test(r))return{format:ve.BULLET,suffix:Je.NONE,depth:0};let n=r.match(/^(\d+(?:\.\d+)+)\.?$/);if(n){let o=n[1].split(".").length-1;return{format:ve.OUTLINE,suffix:Je.PERIOD,depth:o}}return/^\([a-z]\)$/.test(r)?{format:ve.LOWER_ALPHA,suffix:Je.PAREN_BOTH,depth:0}:/^\([ivxlc]+\)$/i.test(r)?{format:r===r.toLowerCase()?ve.LOWER_ROMAN:ve.UPPER_ROMAN,suffix:Je.PAREN_BOTH,depth:0}:/^\(\d+\)$/.test(r)?{format:ve.DECIMAL,suffix:Je.PAREN_BOTH,depth:0}:/^\d+\.$/.test(r)?{format:ve.DECIMAL,suffix:Je.PERIOD,depth:0}:/^[a-z]\.$/.test(r)?{format:ve.LOWER_ALPHA,suffix:Je.PERIOD,depth:0}:/^[A-Z]\.$/.test(r)?{format:ve.UPPER_ALPHA,suffix:Je.PERIOD,depth:0}:/^[ivxlc]+\.$/i.test(r)?{format:r===r.toLowerCase()?ve.LOWER_ROMAN:ve.UPPER_ROMAN,suffix:Je.PERIOD,depth:0}:/^\d+/.test(r)?{format:ve.DECIMAL,suffix:Je.PERIOD,depth:0}:{format:ve.BULLET,suffix:Je.NONE,depth:0}}formatToOoxmlNumFmt(t){return{[ve.DECIMAL]:"decimal",[ve.LOWER_ALPHA]:"lowerLetter",[ve.UPPER_ALPHA]:"upperLetter",[ve.LOWER_ROMAN]:"lowerRoman",[ve.UPPER_ROMAN]:"upperRoman",[ve.BULLET]:"bullet",[ve.OUTLINE]:"decimal"}[t]||"decimal"}suffixToOoxmlLevelText(t,r,n=0){if(t===ve.BULLET)return"\u2022";let o=`%${n+1}`;if(t===ve.OUTLINE)return Array(n+1).fill(0).map((a,i)=>`%${i+1}`).join(".")+".";switch(r){case Je.PERIOD:return`${o}.`;case Je.PAREN_RIGHT:return`${o})`;case Je.PAREN_BOTH:return`(${o})`;default:return o}}buildListPPr(t,r,n={}){return`
|
|
51
51
|
<w:pPr>${n.includeListParagraphStyle===!0?`
|
|
52
52
|
<w:pStyle w:val="ListParagraph"/>`:""}
|
|
53
53
|
<w:numPr>
|
|
@@ -112,7 +112,7 @@ var pp=Object.create;var sc=Object.defineProperty;var gp=Object.getOwnPropertyDe
|
|
|
112
112
|
<w:abstractNumId w:val="2"/>
|
|
113
113
|
</w:num>
|
|
114
114
|
${l}
|
|
115
|
-
</w:numbering>`}};function
|
|
115
|
+
</w:numbering>`}};function F(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===B&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function $(e,t){return typeof e.createElementNS=="function"?e.createElementNS(B,t):e.createElement(t)}function fs(e,t){let r=Array.from(e?.getElementsByTagNameNS?.(B,t)||[]);return r.length>0?r:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>F(n,t))}var ds=["ins","del","moveFrom","moveTo","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange","cellIns","cellDel"];function fr(e){return ds.some(t=>fs(e,t).length>0)}function Mr(e){if(!e)return[];let t=new Set;for(let r of ds)for(let n of fs(e,r)){let o=n.getAttribute?.("w:author")||n.getAttribute?.("author")||(typeof n.getAttributeNS=="function"?n.getAttributeNS(B,"author"):null);o&&typeof o=="string"&&o.trim()&&t.add(o.trim())}return[...t].sort()}function Mg(e){let t=String(e||"").trim();return/^<\?xml\b[^>]*>\s*<pkg:package\b/i.test(t)||/^<pkg:package\b/i.test(t)?"package":/^<\?xml\b[^>]*>\s*<(?:w:)?document\b/i.test(t)||/^<(?:w:)?document\b/i.test(t)?"document":"fragment"}function Ce(e){return!e||typeof e!="object"||e.sourceType||typeof e.oxml!="string"?e:{...e,sourceType:Mg(e.oxml)}}function dr(e){if(!e)return!1;for(let t of ds)for(let r of fs(e,t)){let n=r.getAttribute?.("w:author")||r.getAttribute?.("author")||(typeof r.getAttributeNS=="function"?r.getAttributeNS(B,"author"):null);if(!n||!String(n).trim())return!0}return!1}function Lr(e,t,r){if(e!=="auto")return e;let n=(Array.isArray(t)?t:[t]).filter(Boolean),o=String(r||"").trim().toLowerCase();return n.some(i=>fr(i)&&(dr(i)||Mr(i).some(l=>l.trim().toLowerCase()!==o)))?"slice-cross-author":"merge-same-author"}function lu(e){return!e||e.nodeType!==1?"":e.localName||String(e.nodeName||"").replace(/^.*:/,"")}function Vn(e,t){for(let r of Array.from(e?.childNodes||[]))if(r.nodeType===1&&lu(r)===t)return r;return null}function cu(e){if(e==="ins"||e==="del")return e;throw new Error(`Unsupported paragraph-mark revision kind: ${e}`)}function uu(e,t,r){let n=t||{};if(n.metadata)return n.metadata;let o=n.revisionIdAllocator||(r?.nodeType===9?r:r?.ownerDocument)||null,a=ue(n.author,o,e);return n.date&&(a.date=n.date),a}function Lg(e,t,r){let n=$(e,t==="ins"?"w:ins":"w:del");return n.setAttribute("w:id",String(r.id)),n.setAttribute("w:author",r.author),n.setAttribute("w:date",r.date),n}function Bg(e){for(let t of Array.from(e.childNodes||[])){let r=lu(t);(r==="ins"||r==="del")&&e.removeChild(t)}}function fu(e,t){let r=Vn(t,"pPr");return r?t.firstChild!==r&&t.insertBefore(r,t.firstChild||null):(r=$(e,"w:pPr"),t.insertBefore(r,t.firstChild||null)),r}function $g(e,t){let r=Vn(t,"rPr");if(!r){r=$(e,"w:rPr");let n=Vn(t,"sectPr")||Vn(t,"pPrChange");t.insertBefore(r,n||null)}return r}function ms(e,t,r={}){let n=cu(t),o=e.ownerDocument,a=uu(n,r,e),i=$g(o,e);Bg(i);let l=Lg(o,n,a);return i.appendChild(l),l}function du(e,t,r){let n=e.ownerDocument,o=fu(n,e);return ms(o,t,{...r,revisionIdAllocator:r?.revisionIdAllocator||n})}function Zr(e,t={}){return du(e,"ins",t)}function Qr(e,t={}){return du(e,"del",t)}function mu(e,t){let r=e.ownerDocument,n=fu(r,e),o=Vn(n,"rPr")||(()=>{let i=$(r,"w:rPr");return n.appendChild(i),i})();if(Vn(o,"ins"))return null;let a=$(r,"w:ins");return t.id&&a.setAttribute("w:id",String(t.id)),a.setAttribute("w:author",t.author),t.date&&a.setAttribute("w:date",t.date),o.appendChild(a),a}function Fg(e,t={}){let r=cu(e),n=uu(r,t,null);return`<w:${r} w:id="${n.id}" w:author="${Ze(n.author)}" w:date="${n.date}"/>`}function ps(e,t={}){return`<w:pPr><w:rPr>${Fg(e,t)}</w:rPr></w:pPr>`}var _o=(e,t)=>t?.plainTextContent===!0?{cleanText:String(e??""),formatHints:[]}:yt(e);function mr(e,t={}){let{generateRedlines:r=!1,author:n="AI",revisionIdAllocator:o=null,trackAsBlock:a=!1}=t,i=r&&a,l=e.headers?.length||e.rows?.[0]?.length||1,s=`
|
|
116
116
|
<w:tblPr>
|
|
117
117
|
<w:tblW w:w="5000" w:type="pct"/>
|
|
118
118
|
<w:tblBorders>
|
|
@@ -125,54 +125,54 @@ var pp=Object.create;var sc=Object.defineProperty;var gp=Object.getOwnPropertyDe
|
|
|
125
125
|
</w:tblBorders>
|
|
126
126
|
<w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="1" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/>
|
|
127
127
|
</w:tblPr>
|
|
128
|
-
`.trim(),f=`<w:tblGrid>${Array(l).fill("<w:gridCol/>").join("")}</w:tblGrid>`,u=e.hasHeader?[e.headers,...e.rows]:e.rows,d="";for(let m=0;m<u.length;m++){let p=e.hasHeader&&m===0,g=u[m]||[],h="";for(let
|
|
128
|
+
`.trim(),f=`<w:tblGrid>${Array(l).fill("<w:gridCol/>").join("")}</w:tblGrid>`,u=e.hasHeader?[e.headers,...e.rows]:e.rows,d="";for(let m=0;m<u.length;m++){let p=e.hasHeader&&m===0,g=u[m]||[],h="";for(let x=0;x<l;x++){let b=g[x]||"",{cleanText:T,formatHints:A}=_o(b,t),E=[{kind:r?H.INSERTION:H.TEXT,text:T,rPrXml:p?"<w:rPr><w:b/></w:rPr>":"",author:n,startOffset:0,endOffset:T.length}],I=i?ps("ins",{author:n,revisionIdAllocator:o}):null,R=lt(E,I,A,{author:n,generateRedlines:r,revisionIdAllocator:o});h+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${R}</w:tc>`}let v=p?"<w:trPr><w:tblHeader/><w:cantSplit/></w:trPr>":"<w:trPr><w:cantSplit/></w:trPr>",w=i?ue(n,o):null,y=w?v.replace("</w:trPr>",`<w:ins w:id="${w.id}" w:author="${Ze(w.author)}" w:date="${w.date}"/></w:trPr>`):v;d+=`<w:tr>${y}${h}</w:tr>`}return`<w:tbl>${s}${f}${d}</w:tbl>`}function gu(e,t){let r=[],{headers:n,rows:o,hasHeader:a}=t,i=a?[n,...o]:o,l=Math.max(e.rowCount,i.length);for(let s=0;s<l;s++){if(s>=e.rowCount&&i[s]){r.push({type:"row_insert",gridRow:s,cells:i[s]});continue}if(s<e.rowCount&&!i[s]){r.push({type:"row_delete",gridRow:s});continue}let c=i[s];for(let f=0;f<e.colCount;f++){let u=e.grid[s]?.[f],d=c?.[f];u&&(u.isMergeContinuation||f>u.gridCol||d!==void 0&&pu(u.getText())!==pu(d)&&r.push({type:"cell_modify",gridRow:s,gridCol:f,originalCell:u,newText:d}))}}return r}function hu(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:a=null}=r,i=Dg(t),l="";for(let c=0;c<e.rowCount;c++){let f=i.rowDeleteByRow.get(c)||null;if(f&&!n)continue;let u="",d=0;for(;d<e.colCount;){let p=e.grid[c][d];if(!p){d++;continue}if(p.isMergeContinuation){d++;continue}let g=i.cellModifyByCoordinate.get(`${c}:${d}`)||null,h;g?h=Xg(p,g.newText,r):h=zg(p.blocks),u+=jg(p,h,r),d+=p.colSpan}let m=e.trPrList[c]||"<w:trPr/>";if(f&&n){let p=ue(o,a),g=`<w:del w:id="${p.id}" w:author="${Ze(p.author)}" w:date="${p.date}"/>`;m.includes("</w:trPr>")?m=m.replace("</w:trPr>",`${g}</w:trPr>`):m=`<w:trPr>${g}</w:trPr>`}l+=`<w:tr>${m}${u}</w:tr>`}let s=i.rowInsertOperations;for(let c of s){let f="",u=n?ue(o,a):null;for(let m of c.cells){let{cleanText:p,formatHints:g}=_o(m,r),h=[{kind:n?H.INSERTION:H.TEXT,text:p,rPrXml:"",author:o,startOffset:0,endOffset:p.length}],v=lt(h,null,g,{author:o,generateRedlines:n,revisionIdAllocator:a});f+=`<w:tc><w:tcPr><w:tcW w:w="0" w:type="auto"/></w:tcPr>${v}</w:tc>`}let d="<w:trPr/>";n&&(d=`<w:trPr><w:ins w:id="${u.id}" w:author="${Ze(u.author)}" w:date="${u.date}"/></w:trPr>`),l+=`<w:tr>${d}${f}</w:tr>`}return`
|
|
129
129
|
<w:tbl>
|
|
130
130
|
${e.tblPrXml}
|
|
131
131
|
${e.tblGridXml}
|
|
132
132
|
${l}
|
|
133
133
|
</w:tbl>
|
|
134
|
-
`}function
|
|
135
|
-
`);for(;i.length>e.blocks.length&&i[i.length-1]==="";)i.pop();let l="";e.blocks.forEach((s,c)=>{let f=i[c];if(f===void 0||f===s.acceptedText){if(f===void 0&&s.acceptedText!==""){let g
|
|
136
|
-
`).map(i=>i.trim()).filter(i=>i.startsWith("|"));if(t.length===0)return{headers:[],rows:[],hasHeader:!1};let r=i=>{let l=i.replace(/\s+/g,"");return/^\|:?-{3,}:?(\|:?-{3,}:?)
|
|
137
|
-
`).filter(t=>t.trim().length>0).map(t=>{let r=
|
|
138
|
-
`),r=t.map((i,l)=>({line:i,index:l})).filter(i=>i.line.trim().length>0);if(r.length<2)return e;let n=[],o=0;for(let{line:i,index:l}of r){let s=
|
|
139
|
-
`)}function
|
|
140
|
-
`),endIndex:a-1}}function
|
|
134
|
+
`}function Dg(e){let t=new Map,r=new Map,n=[];for(let o of e)o.type==="row_delete"?t.set(o.gridRow,o):o.type==="cell_modify"?r.set(`${o.gridRow}:${o.gridCol}`,o):o.type==="row_insert"&&n.push(o);return n.sort((o,a)=>o.gridRow-a.gridRow),{rowDeleteByRow:t,cellModifyByCoordinate:r,rowInsertOperations:n}}function pu(e){return typeof e=="string"?e.replace(/\n+$/,""):e}function Ug(e,t,r){let{generateRedlines:n,author:o,revisionIdAllocator:a=null}=r,i=String(t??"").split(`
|
|
135
|
+
`);for(;i.length>e.blocks.length&&i[i.length-1]==="";)i.pop();let l="";e.blocks.forEach((s,c)=>{let f=i[c];if(f===void 0||f===s.acceptedText){if(f===void 0&&s.acceptedText!==""){let g=Xn(s.acceptedText,""),h=jn(zn(s.runModel,g),g,{generateRedlines:n,author:o,formatHints:[]});l+=lt(h,s.pPr,[],{author:o,generateRedlines:n,revisionIdAllocator:a})}else l+=lt(s.runModel,s.pPr,[],{});return}let{cleanText:u,formatHints:d}=_o(f,r),m=Xn(s.acceptedText,u),p=jn(zn(s.runModel,m),m,{generateRedlines:n,author:o,formatHints:d});l+=lt(p,s.pPr,d,{author:o,generateRedlines:n,revisionIdAllocator:a})});for(let s=e.blocks.length;s<i.length;s++){let{cleanText:c,formatHints:f}=_o(i[s],r),u=[{kind:n?H.INSERTION:H.TEXT,text:c,rPrXml:"",author:o,startOffset:0,endOffset:c.length}],d=n?ps("ins",{author:o,revisionIdAllocator:a}):null;l+=lt(u,d,f,{author:o,generateRedlines:n,revisionIdAllocator:a})}return l}function Xg(e,t,r){if(e.blocks.length>1)return Ug(e,t,r);let{generateRedlines:n,author:o,revisionIdAllocator:a=null}=r,{cleanText:i,formatHints:l}=_o(t,r),s=e.getText(),c=Xn(s,i),f=e.blocks[0]||{runModel:[],pPr:null},u=zn(f.runModel,c),d=jn(u,c,{generateRedlines:n,author:o,formatHints:l});return lt(d,f.pPr,l,{author:o,generateRedlines:n,revisionIdAllocator:a})}function zg(e){return e.map(t=>lt(t.runModel,t.pPr,[],{})).join("")}function jg(e,t,r){let n=e.tcPrXml;return e.colSpan>1&&!n.includes("gridSpan")?n=n.replace("</w:tcPr>",`<w:gridSpan w:val="${e.colSpan}"/></w:tcPr>`):e.colSpan>1&&n==="<w:tcPr/>"&&(n=`<w:tcPr><w:gridSpan w:val="${e.colSpan}"/></w:tcPr>`),e.rowSpan>1&&e.isMergeOrigin&&!n.includes("vMerge")?n=n.replace("</w:tcPr>",'<w:vMerge w:val="restart"/></w:tcPr>'):e.rowSpan>1&&e.isMergeOrigin&&n==="<w:tcPr/>"&&(n='<w:tcPr><w:vMerge w:val="restart"/></w:tcPr>'),`<w:tc>${n}${t}</w:tc>`}function xt(e){let t=e.split(`
|
|
136
|
+
`).map(i=>i.trim()).filter(i=>i.startsWith("|"));if(t.length===0)return{headers:[],rows:[],hasHeader:!1};let r=i=>{let l=i.replace(/\s+/g,"");return/^\|:?-{3,}:?(?:(\|:?-{3,}:?)+\|?|\|)$/.test(l)},n=t.some(r),a=t.filter(i=>!r(i)).map(i=>i.split("|").slice(1,-1).map(l=>l.trim()));return n?{headers:a[0]||[],rows:a.slice(1),hasHeader:!0}:{headers:[],rows:a,hasHeader:!1}}async function Wn(e){let{cleanText:t,numberingContext:r,originalRunModel:n=[],originalText:o="",generateRedlines:a=!0,author:i="AI",font:l=null,revisionIdAllocator:s=null,numberingService:c}=e,f=Wg(t),u=Vg(f),d=u.map(E=>E.raw),m=[],p=Hg(n),g=wu(n,p),h=wu(n,p,["rFonts","kern","position","rtl","cs","lang"]),v=[];if(a){if(n&&n.length>0)v=n.filter(E=>E.kind==="text"||E.kind==="run"||E.kind===H.CONTAINER_START||E.kind===H.CONTAINER_END).map(E=>E.kind===H.CONTAINER_START||E.kind===H.CONTAINER_END?E:{...E,kind:"deletion",author:i});else if(o&&o.trim().length>0){let E=o.trim();v=[{kind:"deletion",text:E,author:i,startOffset:0,endOffset:E.length}]}}let w=(n||[]).filter(E=>E.kind===H.PARAGRAPH_START).length;if(a&&w>0&&(w>1||v.length===0)){let E=null,I=()=>{E&&(m.push(lt(E,null,[],{author:i,generateRedlines:a,revisionIdAllocator:s})),E=null)};for(let R of n)R.kind===H.PARAGRAPH_START?(I(),E=[{...R,pPrElement:null,pPrXml:gs(R.pPrElement||R.pPrXml||null,"del",i,s)}]):E&&(R.kind==="text"||R.kind==="run")?E.push({...R,kind:"deletion",author:i}):E&&(R.kind===H.CONTAINER_START||R.kind===H.CONTAINER_END)&&E.push(R);I()}else if(a&&v.length>0){let E=gs(p,"del",i,s),I=lt(v,E,[],{author:i,generateRedlines:a,revisionIdAllocator:s});m.push(I)}let y=hs(d);W(`[ListGen] Detected indentation step: ${y} spaces/chars`);let x=u.find(E=>E.marker)?.marker||"",{format:b}=c.detectNumberingFormat(x);W(`[ListGen] Detected primary marker: "${x}", format: ${b}`);for(let E=0;E<u.length;E++){let I=Kg(u,E);if(I){let N=xt(I.tableText);if(N.headers.length>0||N.rows.length>0){m.push(mr(N,{generateRedlines:a,author:i,revisionIdAllocator:s,trackAsBlock:!0})),E=I.endIndex;continue}}let R=u[E],S=Gg(R,y,r,c,a,i,l,s,g,h);m.push(S.ooxml)}let T=c.generateNumberingXml(),A=m.join("");return W(`[ListGen] \u2705 Generated OOXML for ${m.length} paragraphs, total length: ${A.length}`),W(`[ListGen] First 200 chars: ${A.substring(0,200)}...`),{ooxml:A,isValid:!0,warnings:["Paragraph expanded to list fragment"],type:"fragment",includeNumbering:!0,numberingXml:T}}function hs(e){let t=e.map(n=>n.match(/^(\s*)/)[0].length).filter(n=>n>0).sort((n,o)=>n-o);if(t.length===0)return 2;let r=t[0];for(let n=1;n<t.length;n++){let o=t[n]-t[n-1];o>0&&o<r&&(r=o)}return r||2}function Vg(e){return e.split(`
|
|
137
|
+
`).filter(t=>t.trim().length>0).map(t=>{let r=zt(t),n=t.match(/^\s*(#{1,9})\s+(.*)/);return{raw:t,marker:r?r[2].trim():"",headerMatch:n,indentSize:t.match(/^(\s*)/)?.[1].length||0,isTableLine:/^\s*\|/.test(t),isTableSeparator:/^\s*\|?[\s:-]*-[-\s|:]*\|?\s*$/.test(t)}})}function Wg(e){let t=String(e||"").split(`
|
|
138
|
+
`),r=t.map((i,l)=>({line:i,index:l})).filter(i=>i.line.trim().length>0);if(r.length<2)return e;let n=[],o=0;for(let{line:i,index:l}of r){let s=zt(i);if(!s)return e;let c=Zt(i),f=zt(c);if(!f)return e;let u=(s[2]||"").trim(),d=(f[2]||"").trim();if(!u||!d||u===d)return e;let p=`${s[1]||""}${c.trimStart()}`;n.push({index:l,rewritten:p}),o++}if(o<2)return e;let a=t.slice();for(let i of n)a[i.index]=i.rewritten;return W(`[ListGen] Normalized ${o} composite list markers (e.g., "- A." -> "A.").`),a.join(`
|
|
139
|
+
`)}function Kg(e,t){let r=e[t],n=e[t+1];if(!r?.isTableLine||!n?.isTableLine||!n?.isTableSeparator)return null;let o=[],a=t;for(;a<e.length&&e[a].isTableLine;)o.push(e[a].raw),a++;return{tableText:o.join(`
|
|
140
|
+
`),endIndex:a-1}}function Gg(e,t,r,n,o,a,i,l,s,c){let f="",u="",d=s;if(e.headerMatch){let h=Math.min(e.headerMatch[1].length,9),v=Math.min(h-1,8),w=[32,28,26,24,22,20,20,20,20],y=w[h-1]||w[w.length-1];u=e.headerMatch[2].trim(),f=`<w:pPr><w:pStyle w:val="Heading${h}"/><w:outlineLvl w:val="${v}"/><w:rPr><w:b/><w:sz w:val="${y}"/><w:szCs w:val="${y}"/></w:rPr></w:pPr>`,d=qg(c,`<w:rPr><w:b/><w:sz w:val="${y}"/><w:szCs w:val="${y}"/></w:rPr>`)}else if(e.marker){let h=n.detectNumberingFormat(e.marker),v=t>0?Math.floor(e.indentSize/t):0,w=r?.ilvl||0,y=h.format==="outline"?Math.min(8,h.depth):Math.min(8,v+w);u=Zt(e.raw);let x=n.getOrCreateNumId({type:h.format},r);f=n.buildListPPr(x,y)}else u=e.raw;o&&(f=gs(f||"<w:pPr/>","ins",a,l));let{cleanText:m,formatHints:p}=yt(u),g=[];return g.push({kind:o?"insertion":"run",text:m,rPrXml:d,author:a,startOffset:0,endOffset:m.length}),{ooxml:lt(g,f,p,{author:a,generateRedlines:o,font:i,revisionIdAllocator:l})}}function Hg(e){let t=(e||[]).find(r=>r.kind===H.PARAGRAPH_START);return t?.pPrElement||t?.pPrXml||null}function wu(e,t,r=["rFonts","kern","position","sz","szCs","rtl","cs","lang"]){let n=(e||[]).filter(a=>(a.kind===H.TEXT||a.kind==="text")&&a.rPrXml).map(a=>a.rPrXml);t&&n.push(typeof t=="string"?t:Be(t));let o=[];for(let a of r){let i=null;for(let l of n)if(i=String(l||"").match(new RegExp(`<w:${a}\\b[^>]*(?:\\/>|>[\\s\\S]*?<\\/w:${a}>)`)),i)break;i&&o.push(i[0])}return o.length>0?`<w:rPr>${o.join("")}</w:rPr>`:""}function qg(...e){let t=e.map(r=>String(r||"").replace(/^\s*<w:rPr[^>]*>|<\/w:rPr>\s*$/g,"")).filter(Boolean).join("");return t?`<w:rPr>${t}</w:rPr>`:""}function gs(e,t,r,n){let o,a;if(e?.nodeType===1)o=e.cloneNode(!0),a=o.ownerDocument;else{let i=typeof e=="string"&&e.trim()?e:"<w:pPr/>",l=V(`<w:root xmlns:w="${B}">${i}</w:root>`);if(!l.doc)throw new Error(l.error?.message||"Could not parse paragraph properties for list revision");a=l.doc,o=Array.from(a.documentElement.childNodes||[]).find(s=>s.nodeType===1&&s.localName==="pPr")}if(!o||!a)throw new Error("List paragraph properties are unavailable");return ms(o,t==="del"?"del":"ins",{author:r,revisionIdAllocator:n}),Be(o)}var Yg=new Set(["officeonline","officeweb","web"]);function Jg(e){return e?Yg.has(String(e).toLowerCase()):!1}function Zg(){return typeof process<"u"&&process?.env?.NODE_ENV==="production"}function Qg(){return new Promise(e=>setTimeout(e,0))}var Oo=class{constructor(t={}){this.generateRedlines=t.generateRedlines??!0,this.author=t.author??"AI",this.validateOutput=t.validateOutput??!0,this.validationMode=t.validationMode??"auto",this.numberingService=t.numberingService||new ur,this.font=t.font||null,this.revisionIdAllocator=t.revisionIdAllocator||null,this.platform=t.platform??Gi(),this.isWebPlatform=t.isWebPlatform??Jg(this.platform),this.enableEventLoopYielding=t.enableEventLoopYielding??this.isWebPlatform,this.yieldRunThreshold=t.yieldRunThreshold??50,this.yieldCharThreshold=t.yieldCharThreshold??5e3,this.disableSemanticCleanupOverChars=t.disableSemanticCleanupOverChars??(this.isWebPlatform?8e3:Number.POSITIVE_INFINITY)}async execute(t,r,n={}){let o=[];try{let a=n.xmlDoc?{doc:n.xmlDoc,error:null,warnings:[]}:V(t,"application/xml");if(a.error||!a.doc)return{ooxml:t,isValid:!1,status:"error",error:a.error,warnings:a.warnings||[]};o.push(...a.warnings||[]);let i=a.doc,l=Ge(i,"*","p"),{runModel:s,acceptedText:c,pPr:f}=Dn(t,{xmlDoc:i}),u=l?Po(l):null;W(`[Reconcile] Ingested ${s.length} runs, ${c.length} chars, numbering:`,u),await this.maybeYield(s.length,Math.max(c.length,r?.length||0));let{cleanText:d,formatHints:m}=yt(r);W(`[Reconcile] Preprocessed: ${m.length} format hints`),await this.maybeYield(s.length,Math.max(c.length,d.length));let p=qi(d),g=Mn(d),h=p||g;if(!p&&g&&W("[Reconcile] List-target detected via loose marker parsing; bypassing no-op short-circuit for structural conversion."),c===d&&m.length===0&&!h)return W("[Reconcile] No changes detected"),{ooxml:t,isValid:!0,warnings:["No changes detected"]};let v=Math.max(c.length,d.length)<this.disableSemanticCleanupOverChars,w=Xn(c,d,{cleanupSemantic:v});v||W("[Reconcile] Skipping semantic diff cleanup for large web payload"),await this.maybeYield(s.length,Math.max(c.length,d.length));let y=s.filter(I=>I.kind===H.PARAGRAPH_START).length,x=qi(c)||Mn(c),b=h&&x&&y>1&&c!==d;if(W(`[Reconcile] isTargetList: ${h}, paragraphCount: ${y}`),b)W("[Reconcile] Existing marked list edit detected; using run-aware patching to preserve formatting and paragraph boundaries.");else if(h)return W("[Reconcile] \u{1F3AF} ENTERING LIST GENERATION PATH"),W(`[Reconcile] cleanText preview: ${d.substring(0,100)}...`),W(`[Reconcile] acceptedText preview: ${c.substring(0,100)}...`),this.executeListGeneration(d,u,s);W(`[Reconcile] Computed ${w.length} diff operations`);let T=zn(s,w);W(`[Reconcile] Split into ${T.length} runs`);let A=jn(T,w,{generateRedlines:this.generateRedlines,author:this.author,formatHints:m,numberingService:this.numberingService});W(`[Reconcile] Patched model has ${A.length} runs`),await this.maybeYield(A.length,Math.max(c.length,d.length));let E=lt(A,f,m,{author:this.author,generateRedlines:this.generateRedlines,revisionIdAllocator:this.revisionIdAllocator});if(this.shouldRunValidation()){let I=this.validateBasic(E);I.isValid||o.push(...I.errors)}return{ooxml:E,isValid:o.length===0,warnings:o}}catch(a){return Le("[Reconcile] Pipeline error:",a),{ooxml:t,isValid:!1,warnings:[`Pipeline error: ${a.message}`],error:a?.code?{code:a.code,message:a.message}:void 0}}}validateBasic(t){let r=[];try{let n=`<root xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">${t}</root>`,o=V(n,"application/xml"),a=o.doc;if(o.error||!a)return r.push("Generated OOXML is not well-formed XML: "+(o.error?.message||"parse error")),{isValid:!1,errors:r};let i=$e(a);i&&r.push("Generated OOXML is not well-formed XML: "+i.textContent.substring(0,100)),t.includes("<w:p")||r.push("Generated OOXML missing paragraph element")}catch(n){r.push(`Validation error: ${n.message}`)}return{isValid:r.length===0,errors:r}}shouldRunValidation(){return this.validateOutput?this.validationMode==="always"?!0:this.validationMode==="never"?!1:!(this.isWebPlatform&&Zg()):!1}async maybeYield(t,r){this.enableEventLoopYielding&&(t<=this.yieldRunThreshold&&r<=this.yieldCharThreshold||await Qg())}wrapForInsertion(t,r={}){return kr(t,r)}async executeListGeneration(t,r,n,o=""){return Wn({cleanText:t,numberingContext:r,originalRunModel:n,originalText:o,generateRedlines:this.generateRedlines,author:this.author,font:this.font,revisionIdAllocator:this.revisionIdAllocator,numberingService:this.numberingService})}detectIndentationStep(t){return hs(t)}executeTableGeneration(t){let r=xt(t);return r.rows.length===0&&r.headers.length===0?{ooxml:"",isValid:!1,warnings:["Could not parse Markdown table"]}:{ooxml:mr(r,{generateRedlines:this.generateRedlines,author:this.author,revisionIdAllocator:this.revisionIdAllocator,trackAsBlock:!0}),isValid:!0,warnings:[],includeNumbering:!1}}};var vu=/^\s*(?:\|\s*:?-{3,}:?\s*\||\|?\s*:?-{3,}:?\s*(?:\|\s*:?-{3,}:?\s*)+\|?)\s*$/;function yu(e){return!e||e.trim().length===0}function xu(e){let t=String(e||"").trim();return t.startsWith("|")&&t.endsWith("|")}function eh(e){return String(e||"").trim().split("|").slice(1,-1).map(t=>t.trim())}function ws(e){return yu(e)?"blank":/^\s*#{1,9}\s+\S/.test(e)?"heading":xu(e)?"table":zt(e)?"list":"paragraph"}function Ea(e){let r=(typeof e=="string"?e.replace(/\r\n?/g,`
|
|
141
141
|
`):String(e??"")).split(`
|
|
142
|
-
`),n=[],o=[],a=0;for(;a<r.length;){if(
|
|
143
|
-
`)});continue}if(s==="list"){let d=[];for(;a<r.length&&
|
|
144
|
-
`)});continue}let f=[];for(;a<r.length&&
|
|
142
|
+
`),n=[],o=[],a=0;for(;a<r.length;){if(yu(r[a])){a++;continue}let s=ws(r[a]),c=a+1;if(s==="heading"){let d=r[a].match(/^\s*(#{1,9})\s+(.+?)\s*$/);n.push({type:"heading",level:d[1].length,text:d[2],markdown:r[a].trim()}),a++;continue}if(s==="table"){let d=[];for(;a<r.length&&xu(r[a]);)d.push(r[a].trim()),a++;let m=d.length>1&&vu.test(d[1]),p=d.filter(g=>!vu.test(g)).map(g=>eh(g).length);m||o.push({severity:"error",code:"TABLE_SEPARATOR_REQUIRED",line:c,message:"Markdown tables require a separator row immediately after the header (for example | --- | --- |)."}),p.length<2?o.push({severity:"error",code:"TABLE_DATA_ROW_REQUIRED",line:c,message:"Markdown tables require a header and at least one data row."}):new Set(p).size>1&&o.push({severity:"error",code:"TABLE_COLUMN_COUNT_MISMATCH",line:c,message:`Markdown table rows have inconsistent column counts: ${p.join(", ")}.`}),n.push({type:"table",columns:p[0]||0,rows:Math.max(0,p.length-1),hasHeader:m,markdown:d.join(`
|
|
143
|
+
`)});continue}if(s==="list"){let d=[];for(;a<r.length&&ws(r[a])==="list";)d.push(r[a].trimEnd()),a++;n.push({type:"list",items:d.length,markdown:d.join(`
|
|
144
|
+
`)});continue}let f=[];for(;a<r.length&&ws(r[a])==="paragraph";)f.push(r[a].trim()),a++;let u=f.join(" ").trim();n.push({type:"paragraph",text:u,markdown:u})}let i={heading:0,paragraph:0,list:0,table:0};for(let s of n)i[s.type]=(i[s.type]||0)+1;let l=n.map(s=>s.markdown).join(`
|
|
145
145
|
|
|
146
|
-
`);return{valid:o.every(s=>s.severity!=="error"),normalizedMarkdown:l,blocks:n,issues:o,counts:i,requiresStructuredContent:n.length>1||n.some(s=>s.type==="heading"||s.type==="table"||s.type==="list"&&s.items>1)}}function Kg(e,t,r={}){let n=Ta(t);return{...n,operation:n.valid?{type:"replace",target:e,modified:n.normalizedMarkdown,structuredContent:!0,...r.author?{author:r.author}:{},...typeof r.generateRedlines=="boolean"?{generateRedlines:r.generateRedlines}:{},...r.existingRevisions?{existingRevisions:r.existingRevisions}:{}}:null}}var Co=["w:rStyle","w:rFonts","w:b","w:bCs","w:i","w:iCs","w:caps","w:smallCaps","w:strike","w:dstrike","w:outline","w:shadow","w:emboss","w:imprint","w:noProof","w:snapToGrid","w:vanish","w:webHidden","w:color","w:spacing","w:w","w:kern","w:position","w:sz","w:szCs","w:highlight","w:u","w:effect","w:bdr","w:shd","w:fitText","w:vertAlign","w:rtl","w:cs","w:em","w:lang","w:eastAsianLayout","w:specVanish","w:oMath","w:rPrChange"];function Ze(e,t){let r=Co.indexOf(t.nodeName),n=r===-1?999:r,o=!1;for(let a of Array.from(e.childNodes)){if(a.nodeType!==1)continue;let i=Co.indexOf(a.nodeName);if((i===-1?999:i)>n){e.insertBefore(t,a),o=!0;break}}o||e.appendChild(t)}function Gg(e,t,r,n){if(!t||!r)return;let o=!!r.bold,a=!!r.italic,i=!!r.underline,l=!!r.strikethrough,s=new Set;if(o&&(s.add("w:b"),s.add("w:bCs")),a&&(s.add("w:i"),s.add("w:iCs")),i&&s.add("w:u"),l&&s.add("w:strike"),s.size>0){let c=[];for(let f of Array.from(t.childNodes))s.has(f.nodeName)&&c.push(f);for(let f of c)t.removeChild(f)}if(o){let c=F(e,"w:b");c.setAttribute("w:val",n==="add"?"1":"0"),Ze(t,c);let f=F(e,"w:bCs");f.setAttribute("w:val",n==="add"?"1":"0"),Ze(t,f)}if(a){let c=F(e,"w:i");c.setAttribute("w:val",n==="add"?"1":"0"),Ze(t,c);let f=F(e,"w:iCs");f.setAttribute("w:val",n==="add"?"1":"0"),Ze(t,f)}if(i){let c=F(e,"w:u");c.setAttribute("w:val",n==="add"?"single":"none"),Ze(t,c)}if(l){let c=F(e,"w:strike");c.setAttribute("w:val",n==="add"?"1":"0"),Ze(t,c)}}function mu(e,t,r){Gg(e,t,r,"remove")}function Qt(e){let t={bold:!1,italic:!1,underline:!1,strikethrough:!1,hasFormatting:!1};if(!e)return t;for(let r of Array.from(e.childNodes))if(r.nodeName==="w:b"&&(t.bold=Zr(r,!1)),r.nodeName==="w:i"&&(t.italic=Zr(r,!1)),r.nodeName==="w:u"&&(t.underline=Zr(r,!0)),r.nodeName==="w:strike"&&(t.strikethrough=Zr(r,!1)),r.nodeName==="w:rStyle"){let n=r.getAttribute("w:val");if(n){let o=n.toLowerCase();(o.includes("bold")||o.includes("strong"))&&(t.bold=!0),(o.includes("italic")||o.includes("emphasis"))&&(t.italic=!0),o.includes("underline")&&(t.underline=!0)}}return t.hasFormatting=t.bold||t.italic||t.underline||t.strikethrough,t}function Zr(e,t){let n=(e.getAttribute("w:val")||e.getAttribute("val")||"").toLowerCase();return n?t?n!=="none"&&n!=="0"&&n!=="false"&&n!=="off":n!=="0"&&n!=="false"&&n!=="off":!0}var du=["w:pStyle","w:keepNext","w:keepLines","w:pageBreakBefore","w:framePr","w:widowControl","w:numPr","w:suppressLineNumbers","w:pBdr","w:shd","w:tabs","w:suppressAutoHyphens","w:kinsoku","w:wordWrap","w:overflowPunct","w:topLinePunct","w:autoSpaceDE","w:autoSpaceDN","w:bidi","w:adjustRightInd","w:snapToGrid","w:spacing","w:ind","w:contextualSpacing","w:mirrorIndents","w:suppressOverlap","w:jc","w:textDirection","w:textAlignment","w:textboxTightWrap","w:outlineLvl","w:divId","w:cnfStyle","w:rPr","w:sectPr","w:pPrChange"];function dr(e,t){let r=du.indexOf(t.nodeName),n=r===-1?999:r,o=!1;for(let a of Array.from(e.childNodes)){if(a.nodeType!==1)continue;let i=du.indexOf(a.nodeName);if((i===-1?999:i)>n){e.insertBefore(t,a),o=!0;break}}o||e.appendChild(t)}function pu(e,t){if(!t)return!1;let r=Qt(e);if(t.bold!==void 0&&r.bold!==!!t.bold||t.italic!==void 0&&r.italic!==!!t.italic||t.underline!==void 0&&r.underline!==!!t.underline)return!0;let n=t.strike!==void 0?t.strike:t.strikethrough;if(n!==void 0&&r.strikethrough!==!!n)return!0;if(t.highlight!==void 0){let o=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:highlight"||l.localName==="highlight")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.highlight&&t.highlight!=="none"?String(t.highlight).toLowerCase():null;if((a||null)!==i)return!0}if(t.color!==void 0){let o=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:color"||l.localName==="color")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.color&&t.color!=="auto"?String(t.color).replace(/^#/,"").toUpperCase():null;if((a?.toUpperCase()||null)!==i)return!0}if(t.fontSize!==void 0){let o=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:sz"||l.localName==="sz")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.fontSize!==null&&t.fontSize!==""?String(t.fontSize):null;if(a!==i)return!0}if(t.fontFamily!==void 0){let o=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:rFonts"||l.localName==="rFonts")),a=o?o.getAttribute("w:ascii")||o.getAttribute("ascii"):null,i=t.fontFamily||null;if(a!==i)return!0}return!1}function gu(e,t,r){if(!t||!r)return;let n=a=>{let i=[];for(let l of Array.from(t.childNodes))l.nodeType===1&&a.includes(l.nodeName)&&i.push(l);for(let l of i)t.removeChild(l)};if(r.bold!==void 0){n(["w:b","w:bCs"]);let a=F(e,"w:b");a.setAttribute("w:val",r.bold?"1":"0"),Ze(t,a);let i=F(e,"w:bCs");i.setAttribute("w:val",r.bold?"1":"0"),Ze(t,i)}if(r.italic!==void 0){n(["w:i","w:iCs"]);let a=F(e,"w:i");a.setAttribute("w:val",r.italic?"1":"0"),Ze(t,a);let i=F(e,"w:iCs");i.setAttribute("w:val",r.italic?"1":"0"),Ze(t,i)}if(r.underline!==void 0){n(["w:u"]);let a=F(e,"w:u");a.setAttribute("w:val",r.underline?"single":"none"),Ze(t,a)}let o=r.strike!==void 0?r.strike:r.strikethrough;if(o!==void 0){n(["w:strike","w:dstrike"]);let a=F(e,"w:strike");a.setAttribute("w:val",o?"1":"0"),Ze(t,a)}if(r.highlight!==void 0&&(n(["w:highlight"]),r.highlight&&r.highlight!=="none")){let a=F(e,"w:highlight");a.setAttribute("w:val",String(r.highlight).toLowerCase()),Ze(t,a)}if(r.color!==void 0&&(n(["w:color"]),r.color&&r.color!=="auto")){let a=F(e,"w:color");a.setAttribute("w:val",String(r.color).replace(/^#/,"")),Ze(t,a)}if(r.fontSize!==void 0&&(n(["w:sz","w:szCs"]),r.fontSize!==null&&r.fontSize!=="")){let a=String(r.fontSize),i=F(e,"w:sz");i.setAttribute("w:val",a),Ze(t,i);let l=F(e,"w:szCs");l.setAttribute("w:val",a),Ze(t,l)}if(r.fontFamily!==void 0&&(n(["w:rFonts"]),r.fontFamily)){let a=F(e,"w:rFonts");a.setAttribute("w:ascii",r.fontFamily),a.setAttribute("w:hAnsi",r.fontFamily),a.setAttribute("w:cs",r.fontFamily),Ze(t,a)}}function hu(e,t){if(!t)return!1;if(t.alignment!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:jc"||o.localName==="jc"));if((r?r.getAttribute("w:val")||r.getAttribute("val"):null)!==t.alignment)return!0}if(t.keepNext!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:keepNext"||o.localName==="keepNext"));if((r?Zr(r,!1):!1)!==!!t.keepNext)return!0}if(t.keepLines!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:keepLines"||o.localName==="keepLines"));if((r?Zr(r,!1):!1)!==!!t.keepLines)return!0}if(t.pageBreakBefore!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:pageBreakBefore"||o.localName==="pageBreakBefore"));if((r?Zr(r,!1):!1)!==!!t.pageBreakBefore)return!0}if(t.style!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:pStyle"||o.localName==="pStyle"));if((r?r.getAttribute("w:val")||r.getAttribute("val"):null)!==t.style)return!0}if(t.numbering!==void 0){let r=Hg(e),n=t.numbering;if(n===null)return r!=null;if(!r||r.numId!==String(Number(n.numId))||r.level!==(Number(n.level)||0))return!0}return!1}function Hg(e){let t=Je(e,"numPr");if(!t)return null;let r=n=>{let o=Je(t,n);return o?o.getAttribute("w:val")??o.getAttribute("val"):null};return{numId:String(Number(r("numId"))),level:Number(r("ilvl"))||0}}function Vn(e,t,r){if(!t||!r)return;let n=o=>{let a=[];for(let i of Array.from(t.childNodes))i.nodeType===1&&o.includes(i.nodeName)&&a.push(i);for(let i of a)t.removeChild(i)};if(r.alignment!==void 0&&(n(["w:jc"]),r.alignment)){let o=F(e,"w:jc");o.setAttribute("w:val",r.alignment),dr(t,o)}if(r.keepNext!==void 0){n(["w:keepNext"]);let o=F(e,"w:keepNext");r.keepNext||o.setAttribute("w:val","0"),dr(t,o)}if(r.keepLines!==void 0){n(["w:keepLines"]);let o=F(e,"w:keepLines");r.keepLines||o.setAttribute("w:val","0"),dr(t,o)}if(r.pageBreakBefore!==void 0){n(["w:pageBreakBefore"]);let o=F(e,"w:pageBreakBefore");r.pageBreakBefore||o.setAttribute("w:val","0"),dr(t,o)}if(r.style!==void 0&&(n(["w:pStyle"]),r.style)){let o=F(e,"w:pStyle");o.setAttribute("w:val",r.style),dr(t,o)}if(r.numbering!==void 0&&(n(["w:numPr"]),r.numbering)){let o=F(e,"w:numPr"),a=F(e,"w:ilvl");a.setAttribute("w:val",String(Number(r.numbering.level)||0));let i=F(e,"w:numId");i.setAttribute("w:val",String(Number(r.numbering.numId))),o.appendChild(a),o.appendChild(i),dr(t,o)}}var wu="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function er(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===wu&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function qg(e){return!e||e.nodeType!==1||e.namespaceURI!==wu?!1:e.localName==="del"||e.localName==="moveFrom"}function vu(e){let t=[],r=Array.from(e?.childNodes||[]).reverse();for(;r.length>0;){let n=r.pop();if(!n||n.nodeType!==1||qg(n))continue;if(er(n,"r")){t.push(n);continue}let o=Array.from(n.childNodes||[]);for(let a=o.length-1;a>=0;a-=1)r.push(o[a])}return t}function yt(e){let t=new Set(["comment","footnote","endnote"]);return Ve(e,"*","p").filter(n=>{let o=n.parentNode;for(;o&&o.nodeName;){let a=String(o.localName||"").toLowerCase();if(t.has(a))return!1;o=o.parentNode}return!0})}function Aa(e){let t=[],r=0;for(let n=0;n<e.length;n++){let o=e[n],a=vu(o);for(let i of a){let l=$e(i,"w:rPr");Array.from(i.childNodes||[]).forEach(s=>{if(er(s,"t")){let c=s.textContent||"";c.length>0&&(t.push({charStart:r,charEnd:r+c.length,textElement:s,runElement:i,paragraph:o,container:i.parentNode,rPr:l}),r+=c.length)}else(er(s,"br")||er(s,"cr")||er(s,"tab")||er(s,"noBreakHyphen"))&&(t.push({charStart:r,charEnd:r+1,textElement:s,runElement:i,paragraph:o,container:i.parentNode,rPr:l}),r+=1)})}r=Gr(r,n,e.length)}return{textSpans:t,charOffset:r}}function Yg(e,t,r,n,o,a=null){let i=null;for(let c of Array.from(e.childNodes))if(er(c,"rPr")){i=c;break}let l=Qt(i);a&&(a.bold&&!l.bold&&(l.bold=!0),a.italic&&!l.italic&&(l.italic=!0),a.underline&&!l.underline&&(l.underline=!0),a.strikethrough&&!l.strikethrough&&(l.strikethrough=!0)),l.hasFormatting=l.bold||l.italic||l.underline||l.strikethrough;let s=r;for(let c of Array.from(e.childNodes))if(er(c,"t")){let f=c.textContent||"";if(f.length>0){let u=s,d=s+f.length;n.push({charStart:u,charEnd:d,textElement:c,runElement:e,paragraph:t,rPr:i,format:{...l}}),l.hasFormatting&&o.push({start:u,end:d,format:{...l},run:e,rPr:i}),s=d}}return s}function yu(e){let t=[],r=[],n=0,o=yt(e);for(let a=0;a<o.length;a++){let i=o[a],l=null;for(let f of Array.from(i.childNodes))if(er(f,"pPr")){for(let u of Array.from(f.childNodes))if(er(u,"rPr")){l=u;break}break}let s=Qt(l);s.hasFormatting&&K(`[OxmlEngine] Found paragraph-level formatting: ${JSON.stringify(s)}`);let c=vu(i);for(let f of c)n=Yg(f,i,n,r,t,s);n=Gr(n,a,o.length)}return K(`[OxmlEngine] Extracted ${r.length} text spans, ${t.length} format hints`),{existingFormatHints:t,textSpans:r,paragraphs:o}}var Jg=new Set(["ins","del","moveFrom","moveTo","pPrChange","rPrChange","tblPrChange","trPrChange","tcPrChange","sectPrChange"]);function dt(e){if(!e)return null;let t=e.cloneNode(!0),r=[t,...Array.from(t.getElementsByTagName?.("*")||[])];for(let n of r.reverse())Jg.has(String(n.localName||n.nodeName||"").replace(/^.*:/,""))&&n.parentNode?.removeChild(n);return t}function Bt(e,t=null){if(!e)return e;let r=e.nodeType===9?e:e.ownerDocument,n=t instanceof Fe?t:lr(r)||Pr(r),o=[e,...Array.from(e.getElementsByTagName?.("*")||[])];for(let a of o){if(!$(a,"rPrChange"))continue;let i=String(n.next());typeof a.setAttributeNS=="function"?a.setAttributeNS(B,"w:id",i):a.setAttribute("w:id",i),n._receiptCollector?.recordRevision(Number(i),"rPrChange")}return e}function tr(e,t,r,n,o=null){let a=F(e,t==="ins"?"w:ins":"w:del"),i=o||ce(n,e,t==="ins"?"ins":"del");return a.setAttribute("w:id",String(i.id)),a.setAttribute("w:author",i.author),a.setAttribute("w:date",i.date),r&&a.appendChild(r),a}function kr(e,t,r,n){let o=F(e,"w:r");if(r&&o.appendChild(r.cloneNode(!0)),!n)return bu(e,o,t),o;let a=F(e,n?"w:delText":"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=t,o.appendChild(a),o}function Sa(e,t,r,n,o,a,i){if(!t)return[];let l=new Set([0,t.length]);for(let f of n){let u=Math.max(0,f.start-o),d=Math.min(t.length,f.end-o);u>=0&&u<t.length&&l.add(u),d>0&&d<=t.length&&l.add(d)}let s=Array.from(l).sort((f,u)=>f-u),c=[];for(let f=0;f<s.length-1;f++){let u=s[f],d=s[f+1],m=t.slice(u,d);if(!m)continue;let p=o+u,g=o+d,h=n.filter(y=>y.start<=p&&y.end>=g),v={...Qt(r)};h.forEach(y=>{y.format&&Object.assign(v,y.format)});let w=h.length>0?jn(e,r,v,a,i):r?.cloneNode(!0)||null;c.push(us(e,m,w,!1))}return c}function us(e,t,r,n){let o=F(e,"w:r");if(r&&o.appendChild(r),!n)return bu(e,o,t),o;let a=F(e,n?"w:delText":"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=t,o.appendChild(a),o}function bu(e,t,r){let o=String(r||"").split(/(\t|\n|\u2011)/);for(let a of o){if(!a)continue;if(a===" "){t.appendChild(F(e,"w:tab"));continue}if(a===`
|
|
147
|
-
`){t.appendChild(
|
|
148
|
-
`).indexOf(n);if(l!==-1)for(let s of e){let c=s.startOffset,f=s.normalizedText.length;if(l>=c&&l<=c+f){o=s,a=l-c;break}}}if(!o&&e.length===1&&r.length>0){let i=e[0],l=i.normalizedTrim||"";if(l.length>0){let s=r.indexOf(l);s>=0&&(o=i,a=-s)}}return{targetInfo:o,matchOffset:a}}function
|
|
149
|
-
`:
|
|
150
|
-
`).replace(/\u00a0/g," "):""}function
|
|
151
|
-
`:s==="noBreakHyphen"?o+="\u2011":s==="softHyphen"?o+="\xAD":a(l)}};return a(e),o}var
|
|
152
|
-
`:g==="noBreakHyphen"?w="\u2011":g==="softHyphen"&&(w="\xAD"),w!==null?w.length>0&&r.push({text:w,kind:y,author:
|
|
153
|
-
|
|
154
|
-
`&&($(t,"br")||$(t,"cr"))||r===" "&&$(t,"tab")||r==="\u2011"&&$(t,"noBreakHyphen")||r==="\xAD"&&$(t,"softHyphen"))return t.cloneNode(!0);if(n){let a=F(e,"w:delText");return a.setAttribute("xml:space","preserve"),a.textContent=r,a}let o=F(e,"w:t");return o.setAttribute("xml:space","preserve"),o.textContent=r,o}function _u(e,t,r,n,o,a,i){if(o.length===0)return!1;let l=t.rPr,s=Qt(l),c={...s};if(o.forEach(E=>Object.assign(c,E.format)),!["bold","italic","underline","strikethrough"].some(E=>!!c[E]!==s[E]))return!1;let d=t.runElement.parentNode;if(!d)return!1;let m=t.textElement.textContent||"",p=t.charStart,g=r-p,h=n-p,v=m.substring(0,g),w=m.substring(g,h),y=m.substring(h);if(v.length>0){let E=kr(e,v,l,!1);d.insertBefore(E,t.runElement)}let b=jn(e,l,c,a,i),I=us(e,w,b,!1);if(d.insertBefore(I,t.runElement),y.length>0){let E=kr(e,y,l,!1);d.insertBefore(E,t.runElement)}return d.removeChild(t.runElement),!0}function bs(e,t,r,n,o,a,i=null){let l=[];if(Mo(t,r,n,m=>{l.push(m)}),l.length===0)return!1;let s=new Map;l.forEach(m=>{m.runElement?.parentNode&&(s.has(m.runElement)||s.set(m.runElement,[]),s.get(m.runElement).push(m))});let c=[];s.forEach((m,p)=>{let g=p.parentNode;if(!g)return;let h=jt(p);if(h.length===0)return;let v=1/0,w=-1/0;m.forEach(y=>{let b=h.find(N=>N.node===y.textElement);if(!b)return;let I=Math.max(0,r-y.charStart),E=Math.min(y.charEnd-y.charStart,n-y.charStart);E<=I||(v=Math.min(v,b.start+I),w=Math.max(w,b.start+E))}),!(!Number.isFinite(v)||w<=v)&&c.push({runElement:p,parent:g,rPr:m[0].rPr,beforePieces:Rt(e,h,0,v,!1),deletedPieces:Rt(e,h,v,w,!0),afterPieces:Rt(e,h,w,bt(h),!1),globalStart:Math.max(r,Math.min(...m.map(y=>y.charStart))),globalEnd:Math.min(n,Math.max(...m.map(y=>y.charEnd))),carrierGlobalStart:$(g,"ins")?Ou(t,g):null})});let f=[];for(let m of c){let p=f[f.length-1],g=p?.[p.length-1];g&&g.parent===m.parent&&vh(g.runElement)===m.runElement?p.push(m):f.push([m])}let u=!1,d=!1;for(let m of f){let p=m[0],g=null;if(a&&m.some(w=>w.deletedPieces.length>0)){let w=i?d?{...i,id:ce(o,e,"del").id}:i:null;d=!0,g=tr(e,"del",null,o,w)}for(let w of m){let{parent:y,runElement:b}=w;en(e,y,b,w.beforePieces,w.rPr),g&&w===p&&y.insertBefore(g,b),g&&w.deletedPieces.length>0&&g.appendChild(Lr(e,w.deletedPieces,w.rPr));let I=en(e,y,b,w.afterPieces,w.rPr);w.globalEnd===n&&!$(y,"ins")&&(t.replacementInsertionAnchors||(t.replacementInsertionAnchors=new Map),t.replacementInsertionAnchors.set(n,{parent:y,referenceNode:I||b.nextSibling,rPr:w.rPr})),y.removeChild(b),u=!0}let h=$(p.parent,"ins")?p.parent:null,v=Math.max(...m.map(w=>w.globalEnd));if(h&&v===n){let w=p.carrierGlobalStart,y=m.filter(I=>I.globalStart<n).reduce((I,E)=>I+E.deletedPieces.reduce((N,R)=>N+(R.textContent||"").length,0),0),b=Math.max(0,n-w-y);t.revisionInsertionAnchors||(t.revisionInsertionAnchors=new Map),t.revisionInsertionAnchors.set(n,{carrier:h,splitOffset:b,rPr:p.rPr})}}return u}function Gn(e,t,r,n,o,a=[],i=0,l=!0,s=null,c=null,f=null,u="merge-same-author"){let d=t.revisionInsertionAnchors?.get(r)||null;if(d&&u==="slice-cross-author"&&Cu(d.carrier)&&ys(d.carrier,o))return t.revisionInsertionAnchors.delete(r),vs(e,d.carrier,d.splitOffset,n,d.rPr,o,a,i,l,c);let m=t.replacementInsertionAnchors?.get(r)||null;if(m&&!f&&Cu(m.parent)&&(!m.referenceNode||m.referenceNode.parentNode===m.parent))return t.replacementInsertionAnchors.delete(r),Br(e,m.parent,m.referenceNode,n,m.rPr,o,a,i,l,c),!0;if(!f){let I=ps(t,r);if(!I&&r>0&&(I=gs(t,r)),!I&&r>0&&(I=hs(t,r)),!I&&t.spans.length>0&&(I=t.spans[t.spans.length-1]),!I)return s?(Br(e,s,null,n,null,o,a,i,l,c),!0):!1;let E=I.runElement.parentNode;if(!E)return s?(Br(e,s,null,n,I.rPr,o,a,i,l,c),!0):!1;let N=l&&!(u==="slice-cross-author"&&wh(E,o));if(l&&u==="slice-cross-author"&&ys(E,o))return vs(e,E,Pu(t,E,r),n,I.rPr,o,a,i,l,c);let R=jt(I.runElement),x=R.find(S=>S.node===I.textElement),T=x?x.start+Math.max(0,Math.min(r-I.charStart,I.charEnd-I.charStart)):r<=I.charStart?0:bt(R);if(T>0&&T<bt(R)){let S=Rt(e,R,0,T,!1),O=Rt(e,R,T,bt(R),!1);return en(e,E,I.runElement,S,I.rPr),Br(e,E,I.runElement,n,I.rPr,o,a,i,N,c),en(e,E,I.runElement,O,I.rPr),E.removeChild(I.runElement),!0}let A=r<=I.charStart?I.runElement:I.runElement.nextSibling;return Br(e,E,A,n,I.rPr,o,a,i,N,c),!0}let p=Ru(t,r,s),g=p.leftSpan&&$(p.leftSpan.runElement?.parentNode,"hyperlink"),h=p.rightSpan&&$(p.rightSpan.runElement?.parentNode,"hyperlink"),v=p.containingSpan&&$(p.containingSpan.runElement?.parentNode,"hyperlink");if(f.hyperlink==="outside"){if(p.isInterior&&v)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion outside hyperlink from strictly interior position."}}}else if(f.hyperlink==="inside"&&!g&&!h&&!v)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion inside hyperlink when no hyperlink is present at boundary."}};let w=null;if(f.formatting==="none"?w=null:f.formatting==="right"?w=p.rightSpan?.rPr||null:f.formatting==="left"?w=p.leftSpan?.rPr||null:w=(p.containingSpan||p.leftSpan||p.rightSpan)?.rPr||null,p.isInterior){let I=p.containingSpan,E=I.runElement.parentNode||s;if(!E)return!1;let N=jt(I.runElement),R=N.find(T=>T.node===I.textElement),x=R?R.start+Math.max(0,Math.min(r-I.charStart,I.charEnd-I.charStart)):r<=I.charStart?0:bt(N);if(x>0&&x<bt(N)){let T=Rt(e,N,0,x,!1),A=Rt(e,N,x,bt(N),!1);return en(e,E,I.runElement,T,I.rPr),Br(e,E,I.runElement,n,w,o,a,i,l,c),en(e,E,I.runElement,A,I.rPr),E.removeChild(I.runElement),!0}}let y=null,b=null;if(f.hyperlink==="outside"){if(h){let I=p.rightSpan.runElement.parentNode;y=I.parentNode||s,b=I}else if(g){let I=p.leftSpan.runElement.parentNode;y=I.parentNode||s,b=I.nextSibling}}else f.hyperlink==="inside"&&(h?(y=p.rightSpan.runElement.parentNode,b=p.rightSpan.runElement):g&&(y=p.leftSpan.runElement.parentNode,b=p.leftSpan.runElement.nextSibling));if(y||(p.rightSpan?(y=p.rightSpan.runElement.parentNode||s,b=p.rightSpan.runElement):p.leftSpan?(y=p.leftSpan.runElement.parentNode||s,b=p.leftSpan.runElement.nextSibling):(y=s,b=null)),f.bookmark&&y&&(f.bookmark==="outside"?(b&&$(b.previousSibling,"bookmarkStart")&&(b=b.previousSibling),p.leftSpan&&$(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(b=p.leftSpan.runElement.nextSibling.nextSibling)):f.bookmark==="inside"&&(b&&$(b,"bookmarkStart")&&(b=b.nextSibling),p.leftSpan&&$(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(b=p.leftSpan.runElement.nextSibling))),f.comment&&y)if(f.comment==="outside"){if(b&&$(b.previousSibling,"commentRangeStart")&&(b=b.previousSibling),p.leftSpan&&$(p.leftSpan.runElement.nextSibling,"commentRangeEnd")){let I=p.leftSpan.runElement.nextSibling.nextSibling;I&&($(I,"commentReference")||$(I,"r"))&&Array.from(I.childNodes||[]).some(N=>$(N,"commentReference"))&&(I=I.nextSibling),b=I}}else f.comment==="inside"&&(b&&$(b,"commentRangeStart")&&(b=b.nextSibling),p.leftSpan&&$(p.leftSpan.runElement.nextSibling,"commentRangeEnd")&&(b=p.leftSpan.runElement.nextSibling));if(l&&f.revision==="coalesce_same_author"){let I=null,E=null;if(p.leftSpan&&$(p.leftSpan.runElement.parentNode,"ins")){let N=p.leftSpan.runElement.parentNode;(N.getAttribute("w:author")||N.getAttributeNS(B,"author"))===o&&(I=N,E=p.leftSpan.runElement.nextSibling)}else if(p.rightSpan&&$(p.rightSpan.runElement.parentNode,"ins")){let N=p.rightSpan.runElement.parentNode;(N.getAttribute("w:author")||N.getAttributeNS(B,"author"))===o&&(I=N,E=p.rightSpan.runElement)}if(I){let N=kr(e,n,w,!1);return I.insertBefore(N,E),!0}}return l&&u==="slice-cross-author"&&ys(y,o)?vs(e,y,Pu(t,y,r),n,w,o,a,i,l,c):(Br(e,y,b,n,w,o,a,i,l,c),!0)}function vs(e,t,r,n,o,a,i,l,s,c){let f=t.parentNode;if(!f)return!1;let{leftCarrier:u,rightCarrier:d}=Oa(e,t,r);return u&&f.insertBefore(u,t),Br(e,f,t,n,hh(o),a,i,l,s,c),d&&f.insertBefore(d,t),f.removeChild(t),!0}function hh(e){if(!e)return null;let t=e.cloneNode(!0);return Array.from(t.getElementsByTagName?.("*")||[]).filter(n=>$(n,"rPrChange")).forEach(n=>n.parentNode?.removeChild(n)),t}function Pu(e,t,r){let n=Ou(e,t),o=e.spans.filter(a=>a.runElement?.parentNode===t).reduce((a,i)=>a+(i.charEnd-i.charStart),0);return Math.max(0,Math.min(r-n,o))}function Ou(e,t){let r=e.spans.filter(n=>n.runElement?.parentNode===t);return r.length>0?Math.min(...r.map(n=>n.charStart)):0}function ys(e,t){return $(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(B,"author")||"").trim().toLowerCase()!==String(t||"").trim().toLowerCase():!1}function wh(e,t){return $(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(B,"author")||"").trim().toLowerCase()===String(t||"").trim().toLowerCase():!1}function vh(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function Cu(e){return!!e?.parentNode}function Br(e,t,r,n,o,a,i,l,s,c=null){let f=sr(i,l,l+n.length);if(f.length===0){let d=kr(e,n,o,!1);if(s){let m=tr(e,"ins",d,a,c);t.insertBefore(m,r)}else t.insertBefore(d,r);return}let u=Sa(e,n,o,f,l,a,s);if(s){let d=tr(e,"ins",null,a,c);u.forEach(m=>d.appendChild(m)),t.insertBefore(d,r)}else u.forEach(d=>t.insertBefore(d,r))}function ku(e,t,r,n=!1){let o=[];if(Mo(e,t,r,m=>o.push(m)),o.length===0)return{safe:!1};let a=o[0].runElement,i=a?.parentNode;if(!i)return{safe:!1};if(!o.every(m=>m.runElement?.parentNode===i))return{safe:!1,structuralBoundary:!0};let s=i.localName||i.nodeName.replace(/^.*:/,"");if(["hyperlink","sdt","del","moveFrom","moveTo"].includes(s)||s==="ins"&&!n)return{safe:!1,structuralBoundary:!0};let c=new Set(["hyperlink","fldSimple","sdt","commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFrom","moveTo","ins","del"]);for(let m of o){let p=m.runElement;for(let g of Array.from(p.childNodes||[]))if(g.nodeType===1){let h=g.localName||g.nodeName.replace(/^.*:/,"");if(c.has(h)||h==="fldChar")return{safe:!1,structuralBoundary:!0}}}let f=o[o.length-1].runElement,u=a;for(;u&&u!==f;){if(u!==a){let m=u.localName||u.nodeName.replace(/^.*:/,"");if(c.has(m))return{safe:!1,structuralBoundary:!0}}u=u.nextSibling}function d(m){if(!m||m.nodeType!==1)return!1;let p=m.localName||m.nodeName.replace(/^.*:/,"");if(c.has(p)||p==="fldChar")return!0;for(let g of Array.from(m.childNodes||[]))if(g.nodeType===1&&d(g))return!0;return!1}return d(a.previousSibling)||d(f.nextSibling)?{safe:!1,structuralBoundary:!0}:{safe:!0}}function Bu(e,t,r,n,o,a,i=!0,l=null,s={},c={}){let f=l?[l]:yt(e),{fullText:u,textSpans:d}=Ca(f),m=c.existingRevisions==="slice-cross-author"?$c(u,r):null,p=m||bh(Ro(u,r,s),s),g=_a(d),h=c.pairReplacements===!0,v=[],w=0,y=0,b=!1,I=m?xh(m):[];if(I.length>1&&a.length===0)for(let R of I.slice().reverse()){let x=Ca(f).textSpans,T=_a(x),A=R.text.replace(/\n/g," ");if(A.length===0)continue;let S=Gn(e,T,R.originalPos,A,o,a,R.newPos,i,f[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(S&&typeof S=="object"&&S.error)return Pe({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:S.error});S===!0&&(b=!0)}else if(a.length===0){let R=Ih(p);for(let x of R.reverse()){let T=_a(Ca(f).textSpans);if(x.type==="insert"){let O=Gn(e,T,x.start,x.text.replace(/\n/g," "),o,a,x.newPos,i,f[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(O&&typeof O=="object"&&O.error)return Pe({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:O.error});O===!0&&(b=!0);continue}let A=null,S=null;if(x.type==="replace"&&h&&i&&x.text.replace(/\n/g," ")){let O=ku(T,x.start,x.end,c?.existingRevisions==="slice-cross-author");if(O.safe){let C=Ao(o,e);A={id:C.deletionId,author:C.author,date:C.date},S={id:C.insertionId,author:C.author,date:C.date}}else O.structuralBoundary&&v.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(bs(e,T,x.start,x.end,o,i,A)&&(b=!0),x.type==="replace"){let O=Gn(e,T,x.end,x.text.replace(/\n/g," "),o,a,x.newPos,i,f[0]||null,S,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(O&&typeof O=="object"&&O.error)return Pe({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:O.error});O===!0&&(b=!0)}}}else for(let R=0;R<p.length;R++){let[x,T]=p[R];if(x===0){let A=T.length,S=w,O=w+A;Mo(g,S,O,C=>{let P=Math.max(C.charStart,S),M=Math.min(C.charEnd,O),_=M-P,k=P-S,L=y+k,D=L+_,z=sr(a,L,D);_u(e,C,P,M,z,o,i)&&(b=!0)}),w+=A,y+=A}else if(x===-1){let A=R+1<p.length&&p[R+1][0]===1,S=!1,O=null,C=null;if(h&&i&&A&&p[R+1][1].replace(/\n/g," ").length>0){let _=ku(g,w,w+T.length,c?.existingRevisions==="slice-cross-author");if(_.safe){let k=Ao(o,e);O={id:k.deletionId,author:k.author,date:k.date},C={id:k.insertionId,author:k.author,date:k.date},S=!0}else _.structuralBoundary&&v.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(bs(e,g,w,w+T.length,o,i,O)&&(b=!0),w+=T.length,S){R++;let[,P]=p[R],M=P.replace(/\n/g," ");if(M.length>0){let _=Gn(e,g,w,M,o,a,y,i,f[0]||null,C,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(_&&typeof _=="object"&&_.error)return Pe({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:_.error});_===!0&&(b=!0)}y+=P.length}}else if(x===1){let A=T.replace(/\n/g," ");if(A.length>0){let S=Gn(e,g,w,A,o,a,y,i,f[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(S&&typeof S=="object"&&S.error)return Pe({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:S.error});S===!0&&(b=!0)}y+=T.length}}let E=f.map(R=>Q(R)).join(`
|
|
155
|
-
`),
|
|
156
|
-
`);if(c.existingRevisions==="slice-cross-author"&&
|
|
157
|
-
`:
|
|
158
|
-
`)+o[f],i(c)===l)return r.slice(s,f+1)}}return null}function
|
|
159
|
-
`).replace(/\u00a0/g," ")}function
|
|
160
|
-
|
|
161
|
-
`){let C=u(
|
|
162
|
-
`)}function Dh(e){let t=0,r=ze(e,"ins");for(let n of r){if(!n.parentNode||Fa(n))continue;let o=qu(n);for(;Ct(o,"ins")&&Ma(pr(o,"author"))===Ma(pr(n,"author"))&&Yu(o)===Yu(n);){let a=qu(o);for(;o.firstChild;)n.appendChild(o.firstChild);o.parentNode?.removeChild(o),t+=1,o=a}}return t}function Ba(e){let t=e?.parentNode;return Ct(t,"trPr")&&Ct(t?.parentNode,"tr")}function Fa(e){let t=e?.parentNode,r=t?.parentNode,n=r?.parentNode;return Ct(t,"rPr")&&Ct(r,"pPr")&&Ct(n,"p")}function Qu(e){return Fa(e)?e.parentNode.parentNode.parentNode:null}function Uh(e){let t=e?.nextSibling||null;for(;t;){if(Ct(t,"p"))return t;t=t.nextSibling}return null}function ef(e,t="accept",r=null){if(!e?.parentNode)return!1;let n=Uh(e);if(!n){if(Ct(e.parentNode,"tc")){let i=ze(e.parentNode,"p").length<=1;if(t==="reject"||i)return i&&r&&r.add(e),!1}return Be(e)}let o=Array.from(e.childNodes||[]).filter(i=>!Ct(i,"pPr")),a=n.firstChild||null;Ct(a,"pPr")&&(a=a.nextSibling||null);for(let i of o)n.insertBefore(i,a);return Be(e)}function tn(e,t={}){let r=[],n=Ts(t);if(!n.valid)return{oxml:e,hasChanges:!1,acceptedCount:0,warnings:[n.warning]};let o=As(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,acceptedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let l=0,s=new Set;for(let u of ze(a,"ins"))if(!(!u.parentNode||!Pt(u,n))){if(Fa(u)){Be(u)&&(l+=1);continue}if(Ba(u)){Be(u)&&(l+=1);continue}La(u)&&(l+=1)}for(let u of ze(a,"del")){if(!u.parentNode||!Pt(u,n))continue;let d=Qu(u);if(d){(ef(d,"accept",s)||Be(u))&&(l+=1);continue}if(Ba(u)){let m=u.parentNode?.parentNode;Be(m)&&(l+=1);continue}Be(u)&&(l+=1)}for(let u of ze(a,"tbl")){if(!u.parentNode)continue;let d=ze(u,"tc");d.length>0&&d.every(p=>{let g=ze(p,"p");return g.length===1&&s.has(g[0])&&!Array.from(g[0].childNodes||[]).some(h=>!Ct(h,"pPr"))})&&Be(u)&&(l+=1)}for(let u of ze(a,"moveFrom"))!u.parentNode||!Pt(u,n)||Be(u)&&(l+=1);for(let u of ze(a,"moveTo"))!u.parentNode||!Pt(u,n)||La(u)&&(l+=1);l+=tf(a,n);let c=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let u of c)for(let d of ze(a,u))!d.parentNode||!Pt(d,n)||Be(d)&&(l+=1);return{oxml:o.isFragmentWrapped?Array.from(a.documentElement.childNodes).map(u=>i.serializeToString(u)).join(""):i.serializeToString(a),hasChanges:l>0,acceptedCount:l,warnings:r}}function Ju(e,t){for(let r of Array.from(t.getElementsByTagNameNS(B,"delText"))){let n=F(e,"w:t"),o=r.getAttribute("xml:space");for(o&&n.setAttribute("xml:space",o);r.firstChild;)n.appendChild(r.firstChild);r.parentNode?.replaceChild(n,r)}}function zh(e,t){let r=e?.parentNode;if(!r)return!1;let n=t.endsWith("Change")?t.slice(0,-6):"";if(!n||String(r.localName||"").toLowerCase()!==n.toLowerCase()||r.namespaceURI!==B)return Be(e);let o=Array.from(e.childNodes||[]).find(s=>s.nodeType===1&&s.namespaceURI===B&&String(s.localName||"").toLowerCase()===n.toLowerCase());if(!o)return Be(e);let a=Array.from(o.childNodes||[]),i=n.toLowerCase()==="ppr"?["rpr","sectpr"]:[],l=Array.from(r.childNodes||[]).filter(s=>s.nodeType===1&&s.namespaceURI===B&&i.includes(String(s.localName||"").toLowerCase()));for(;r.firstChild;)r.removeChild(r.firstChild);for(let s of a){let c=Xh(r.ownerDocument,s);r.appendChild(c)}for(let s of l)r.appendChild(s);return!0}function Xh(e,t){return e&&typeof e.importNode=="function"?e.importNode(t,!0):t.cloneNode(!0)}function Zu(e,t,r){let n=new Set;for(let o of ze(e,t)){if(!Pt(o,r))continue;let a=pr(o,"id");a&&n.add(a)}return n}function tf(e,t){let r=0,n=Zu(e,"moveFromRangeStart",t),o=Zu(e,"moveToRangeStart",t),a=[["moveFromRangeStart",n,!0],["moveFromRangeEnd",n,!1],["moveToRangeStart",o,!0],["moveToRangeEnd",o,!1]];for(let[i,l,s]of a)for(let c of ze(e,i)){if(!c.parentNode)continue;let f=pr(c,"id");f&&(t.allAuthors||l.has(f)||s&&Pt(c,t))&&Be(c)&&(r+=1)}return r}function Fr(e,t={}){let r=[],n=Ts(t);if(!n.valid)return{oxml:e,hasChanges:!1,rejectedCount:0,warnings:[n.warning]};let o=As(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,rejectedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let l=0;for(let f of ze(a,"ins")){if(!f.parentNode||!Pt(f,n))continue;let u=Qu(f);if(u){(ef(u,"reject")||Be(f))&&(l+=1);continue}if(Ba(f)){let d=f.parentNode?.parentNode;Be(d)&&(l+=1);continue}Be(f)&&(l+=1)}for(let f of ze(a,"tbl")){if(!f.parentNode)continue;!Array.from(f.childNodes||[]).some(d=>Ct(d,"tr"))&&Be(f)&&(l+=1)}for(let f of ze(a,"del"))if(!(!f.parentNode||!Pt(f,n))){if(Fa(f)){Be(f)&&(l+=1);continue}if(Ba(f)){Be(f)&&(l+=1);continue}Ju(a,f),La(f)&&(l+=1)}for(let f of ze(a,"moveFrom"))!f.parentNode||!Pt(f,n)||(Ju(a,f),La(f)&&(l+=1));for(let f of ze(a,"moveTo"))!f.parentNode||!Pt(f,n)||Be(f)&&(l+=1);l+=tf(a,n);let s=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let f of s)for(let u of ze(a,f))!u.parentNode||!Pt(u,n)||zh(u,f)&&(l+=1);return Dh(a),{oxml:o.isFragmentWrapped?Array.from(a.documentElement.childNodes).map(f=>i.serializeToString(f)).join(""):i.serializeToString(a),hasChanges:l>0,rejectedCount:l,warnings:r}}function Vh(e,t){let r=new Set,n=ze(e,"comment");for(let o of n){if(!Pt(o,t))continue;let a=pr(o,"id");a&&r.add(a)}return{targetIds:r,commentNodes:n}}function jh(e,t){let r=0;for(let n of e){let o=pr(n,"id");!o||!t.has(o)||Be(n)&&(r+=1)}return r}function Wh(e){return Ct(e,"r")?Array.from(e.childNodes||[]).filter(r=>{if(r.nodeType===3)return String(r.nodeValue||"").trim().length>0;if(r.nodeType!==1)return!1;if(r.namespaceURI!==B)return!0;let n=String(r.localName||"").toLowerCase();return n!=="rpr"&&n!=="commentreference"}).length===0:!1}function Kh(e,t){let r=0,n=["commentRangeStart","commentRangeEnd","commentReference"];for(let o of n)for(let a of ze(e,o)){if(!a.parentNode)continue;let i=pr(a,"id");if(!(!i||!t.has(i))){if(o==="commentReference"&&Wh(a.parentNode)){Be(a.parentNode)&&(r+=1);continue}Be(a)&&(r+=1)}}return r}function Ss(e,t={}){let r=[],n=Ts(t);if(!n.valid)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,warnings:[n.warning]};let o=As(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let{targetIds:l,commentNodes:s}=Vh(a,n);if(n.allAuthors)for(let u of["commentRangeStart","commentRangeEnd","commentReference"])for(let d of ze(a,u)){let m=pr(d,"id");m&&l.add(m)}let c=jh(s,l),f=Kh(a,l);return{oxml:i.serializeToString(a),hasChanges:c>0||f>0,commentsRemoved:c,referencesRemoved:f,warnings:r}}var Gh=Object.freeze({formatOnly:Object.freeze({paragraphs:!0,formatting:!0,tables:"scoped",hyperlinks:"preserved",fields:"preserved",comments:"preserved"}),surgical:Object.freeze({paragraphs:!0,tables:"cell-scoped",hyperlinks:"preserved",fields:"preserved",comments:"preserved",notes:"preserved"}),reconstruction:Object.freeze({paragraphs:!0,hyperlinks:"sentinel-preserved",fields:"sentinel-preserved",comments:"marker-preserved",notes:"reference-preserved"}),table:Object.freeze({tables:!0,paragraphs:!0,formatting:"cell-dependent",numbering:!1}),listDirect:Object.freeze({lists:!0,numbering:!0,paragraphs:"single-source expansion",tables:"embedded-markdown blocks",formatting:"markdown hints"}),listCompatibilityPipeline:Object.freeze({lists:!0,numbering:!0,paragraphs:"multi-source patching",compatibility:!0})});function gr(e,t,r={}){let n=e?._routeInstrumentation?.onRoute;typeof n=="function"&&n(Object.freeze({route:t,capabilities:Gh[t]||null,...r}))}var Hh=new Set(["pPr","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference","customXmlInsRangeStart","customXmlInsRangeEnd","customXmlDelRangeStart","customXmlDelRangeEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","permStart","permEnd","proofErr"]);function Qe(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Lo(e){return Array.from(e?.childNodes||[]).filter(t=>t.nodeType===1)}function rn(e,t){return Lo(e).find(r=>Qe(r)===t)||null}function $a(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function Da(e){return String(e||"").trim().toLowerCase()}function qh(e){return Qe(e)!=="r"?!1:Lo(e).every(t=>["rPr","commentReference","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","proofErr"].includes(Qe(t)))}function Es(e){return Hh.has(Qe(e))||qh(e)}function Rs(e){return Qe(e)==="del"?!0:["customXml","smartTag","sdt","sdtContent"].includes(Qe(e))?Lo(e).filter(r=>!Es(r)&&Qe(r)!=="sdtPr").every(Rs):!1}function Yh(e){let t=e?.ownerDocument?.documentElement||null;if(!t)return!1;let r=new Set;for(let n of[t,...Array.from(t.getElementsByTagName?.("*")||[])]){if(n===e&&r.size>0)return!0;let o=Qe(n),a=$a(n,"id");o==="moveFromRangeStart"&&a!==""&&r.add(a),o==="moveFromRangeEnd"&&a!==""&&r.delete(a)}return!1}function rf(e){let t=rn(e,"pPr"),r=rn(t,"rPr");return rn(r,"del")}function Jh(e){for(let t of Array.from(e?.getElementsByTagName?.("*")||[])){let r=Qe(t);if(!["t","tab","br","cr","noBreakHyphen","softHyphen"].includes(r))continue;let n=t.parentNode,o=!1;for(;n&&n!==e;){let a=Qe(n);if(a==="del"||a==="moveFrom"){o=!0;break}n=n.parentNode}if(!o&&(r!=="t"||(t.textContent||"").length>0))return!0}return!1}function $r(e,t){let r=rf(e);if(!r)return{matches:!1,hasParagraphMarkDeletion:!1,foreignParagraphMarkDeletion:!1,allContentDeleted:!1,ownerAuthor:null,markDeletion:null};let n=$a(r,"author")||null,o=!n||Da(n)!==Da(t),i=Lo(e).filter(l=>!Es(l)).every(Rs);return{matches:o&&i,hasParagraphMarkDeletion:!0,foreignParagraphMarkDeletion:o,allContentDeleted:i,ownerAuthor:n,markDeletion:r}}function nn(e,t={}){let r=rn(e,"pPr");if(rn(r,"sectPr"))return{code:"SECTION_BREAK_PARAGRAPH",message:"Refusing to restore a deleted paragraph whose paragraph properties contain a section break."};let n=e?.parentNode||null;for(;n;){if(Qe(n)==="moveFrom")return{code:"UNSUPPORTED_MOVE_REVISION",message:"Refusing to restore a paragraph that is part of a pending move-from revision."};n=n.parentNode}if(Yh(e)||e?.getElementsByTagName?.("*")&&Array.from(e.getElementsByTagName("*")).some(i=>["moveFrom","moveFromRangeStart","moveFromRangeEnd"].includes(Qe(i))))return{code:"UNSUPPORTED_MOVE_REVISION",message:"Refusing to restore a paragraph that is part of a pending move-from revision."};let o=e?.parentNode||null;for(;o&&Qe(o)!=="tr";)o=o.parentNode;let a=rn(o,"trPr");if(a&&rn(a,"del"))return{code:"UNSAFE_DELETED_TABLE_ROW",message:"Refusing to restore a paragraph inside a table row with a pending row deletion."};if(t.requireFollowingParagraph!==!1){let i=e?.nextSibling||null;for(;i&&(i.nodeType!==1||Qe(i)!=="p");)i=i.nextSibling;if(!i)return{code:"UNSAFE_PARAGRAPH_PLACEMENT",message:"Refusing to restore a deleted paragraph without a following paragraph in the same structural container."}}return null}function nf(e){let t=Qe(e)==="p"?[e]:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>Qe(n)==="p"),r=[];for(let n of t){let o=rf(n);if(!o)continue;let a=$a(o,"author")||null,i=Lo(n).filter(c=>!Es(c)),l=i.filter(c=>Qe(c)!=="ins"||!Jh(c)?!1:Da($a(c,"author"))!==Da(a)),s=i.every(c=>Rs(c)||l.includes(c));l.length>0&&s&&r.push({paragraph:n,markDeletion:o,ownerAuthor:a,foreignInsertions:l})}return r}function Zh(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of ot(e,B,r)){let o=n.getAttribute?.("w:id")||n.getAttribute?.("id");o!==""&&t.add(o)}return[...t].sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function za(e,t){return Array.from(e?.childNodes||[]).find(r=>r?.nodeType===1&&r.namespaceURI===B&&r.localName===t)||null}function Qh(e,t){let r=za(za(za(e,"pPr"),"rPr"),"ins");if(!r)return null;let n=r.getAttribute("w:author")||r.getAttributeNS(B,"author")||"";return n.trim().toLowerCase()!==String(t||"").trim().toLowerCase()?null:{id:r.getAttribute("w:id")||r.getAttributeNS(B,"id")||"",author:n,date:r.getAttribute("w:date")||r.getAttributeNS(B,"date")||""}}function ew(e,t){let r=e.cloneNode(!1),n=za(e,"pPr");return n&&r.appendChild(dt(n)),t.serializeToString(r)}function tw(e,t){if(!t||typeof e!="string"||!e.trim())return e;let r=j(e,"text/xml");if(!r.doc||r.error)return e;let n=r.doc.documentElement?.localName==="p"?r.doc.documentElement:yt(r.doc)[0];return n?(ou(n,t),Me(r.doc)):e}async function Bo(e,t,r,n={}){let o=e,a=e;t=typeof t=="string"?t:String(t??""),r=typeof r=="string"?r:String(r??"");let i=n.generateRedlines??!0,l=n.author||oe(),s=se(),c=[],f=[],u=!1,d=null,m=n.existingRevisions||"merge-same-author",p=m==="accept-all-first-keep-normalized",g=Y=>{let V={...Y};u&&V.hasChanges===!1&&V.status!=="error"&&(m==="merge-same-author"||m==="slice-cross-author"?(V.oxml=a,V.hasChanges=!0,V.warnings=[...Array.isArray(V.warnings)?V.warnings:[],"Previous revisions by the same author were reverted to baseline."]):p?(V.oxml=a,V.hasChanges=!0,V.warnings=[...Array.isArray(V.warnings)?V.warnings:[],"Existing revisions were accepted before redlining."]):V.oxml=o);let ge=[...c,...f,...Array.isArray(V.warnings)?V.warnings:[]];return ge.length>0&&(V.warnings=[...new Set(ge)]),V.status||(V.status=V.hasChanges?"ok":"no-op"),d&&V.hasChanges&&typeof V.oxml=="string"&&(V.oxml=tw(V.oxml,d)),Pe(V)},h=()=>g(u&&p?{oxml:a,hasChanges:!0,warnings:["Existing revisions were accepted before redlining."]}:{oxml:o,hasChanges:!1}),v=j(o,"text/xml");c=v.warnings;let w=v.doc,y=w?Le(w):null;if(v.error||y){let Y=v.error?.message||y?.textContent||"Could not parse OOXML input.";return ke("[OxmlEngine] XML parse error:",Y),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:Y}})}let b=n?._revisionIdAllocator instanceof Fe?n._revisionIdAllocator:new Fe;cr(w,b);let I=w.documentElement&&String(w.documentElement.localName||"").toLowerCase()==="p"?[w.documentElement]:yt(w);if(I.length===1&&r.length>0){let Y=$r(I[0],l);if(Y.matches){let V=Y.ownerAuthor||"unattributed";return g({oxml:o,hasChanges:!1,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${V}). Use explicit paragraph restoration when supported.`,ownerAuthor:V}})}}if(Or(w))if(m==="merge-same-author"||m==="slice-cross-author"){let Y=qr(w),V=String(l||"").trim().toLowerCase();if(Y.length>0&&Y.every(X=>X.trim().toLowerCase()===V)){let X=Zh(w);if(X.length>0)return g({oxml:o,hasChanges:!1,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:X}});K("[OxmlEngine] Existing revisions from same author detected; rejecting previous changes to merge against baseline");let J=I.length===1?I[0]:null;d=Qh(J,l);let be=Fr(o,{author:l});if(be.status==="error")return g(be);a=d&&!String(be.oxml||"").trim()?ew(J,s):be.oxml,u=!0;let ve=j(a,"text/xml");c.push(...ve.warnings),w=ve.doc;let Te=w?Le(w):null;if(ve.error||Te){let zt=ve.error?.message||Te?.textContent||"Could not parse OOXML after rejecting same-author revisions.";return ke("[OxmlEngine] XML parse error after rejecting same-author revisions:",zt),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:zt}})}if(Or(w))return g({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Existing same-author revisions could not be completely restored to baseline; refusing to layer new revisions over unsupported revision markup."}});cr(w,b);let xo=w.documentElement&&String(w.documentElement.localName||"").toLowerCase()==="p"?[w.documentElement]:yt(w);t=xo.length>0?xo.map(zt=>Q(zt)).join(`
|
|
163
|
-
`):""}else{if(m==="merge-same-author")return
|
|
164
|
-
`)||t.includes("\r")?t.split(/\r?\n/).map(
|
|
165
|
-
`),
|
|
166
|
-
`:r==="noBreakHyphen"?"\u2011":t?.textContent||""}function
|
|
167
|
-
`)}function _s(e){if(e==null)return null;if(typeof e=="number"&&Number.isInteger(e)&&e>0)return e;let t=String(e).trim();if(!t)return null;let r=t.match(/^\[?P(\d+)(?:\.\d+)?\]?$/i);if(r)return Number.parseInt(r[1],10);let n=t.match(/^(\d+)$/);return n?Number.parseInt(n[1],10):null}function nw(e){return e==null?"":String(e).replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim()}function ow(e){let t=String(e||""),r=t.match(/^\s*\[P(\d+)(?:\.\d+)?\]\s*/i);return r?{text:t.replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim(),targetRef:Number.parseInt(r[1],10)}:{text:t.trim(),targetRef:null}}function sf(e,t,r=null){return!Number.isInteger(t)||t<1?null:r?.entries?r.entries[t-1]?.paragraph||null:ae(e)[t-1]||null}function st(e,t,r=ue){let n=e;for(;n;){if(n.nodeType===1&&n.namespaceURI===r&&n.localName===t)return n;n=n.parentNode}return null}function Va(e,t,r={}){let n=r.paragraphMetadataIndex||null,o=n?.entries||null,a=o?null:ae(e),i=String(t||"").trim();if(!i)return null;let l=o?o.find(c=>c.text.trim()===i)?.paragraph:a.find(c=>Ce(c).trim()===i);if(l)return l;let s=Z(i);return n?.byNormalizedText?n.byNormalizedText.get(s)?.[0]?.paragraph||null:a.find(c=>Z(Ce(c))===s)||null}function Cs(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=r.paragraphMetadataIndex||null,a=o?.entries||null,i=a?null:ae(e),l=String(t||"").trim();if(!l)return null;let s=Va(e,l,{paragraphMetadataIndex:o});if(s)return s;let c=Z(l),f=a?a.find(h=>h.normalizedText.length>10&&c.startsWith(h.normalizedText))?.paragraph||null:i.find(h=>{let v=Z(Ce(h));return v.length>10&&c.startsWith(v)});if(f)return n(`[Fuzzy] Prefix match (target starts with paragraph): "${Ce(f).trim().slice(0,60)}..."`),f;let u=a?a.find(h=>h.normalizedText.length>15&&c.includes(h.normalizedText))?.paragraph||null:i.find(h=>{let v=Z(Ce(h));return v.length>15&&c.includes(v)});if(u)return n(`[Fuzzy] Contains match: "${Ce(u).trim().slice(0,60)}..."`),u;let d=0,m=null,p=new Set(c.toLowerCase().split(/\s+/).filter(h=>h.length>2)),g=a?.length??i.length;for(let h=0;h<g;h++){let v=a?.[h]?.paragraph??i[h],w=(a?.[h]?.text??Ce(v)).trim();if(!w)continue;let I=Z(w).toLowerCase().split(/\s+/).filter(E=>E.length>2).filter(E=>p.has(E)).length/Math.max(p.size,1);I>d&&I>.5&&(d=I,m=v)}return m?(n(`[Fuzzy] Best word-overlap match (${(d*100).toFixed(0)}%): "${Ce(m).trim().slice(0,60)}..."`),m):null}function an(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=typeof t.onWarn=="function"?t.onWarn:()=>{},o=t.opType||"operation",a=t.targetDescriptor&&typeof t.targetDescriptor=="object"?t.targetDescriptor:null,i=a?.revisionView==="rejected"?"rejected":"accepted",l=String(a?.exactText??a?.text??t.targetText??"").trim(),s=_s(a?.index??a?.paragraphIndex??t.targetRef),c=t.strictAmbiguity===!0,f=t.paragraphMetadataIndex||null;if(f&&f.revisionView!==i?f=t.metadataIndices?.[i]||rr(e,{revisionView:i}):f||(f=rr(e,{revisionView:i})),a?.paragraphId){let d=iw(e,a.paragraphId,f);if(!d)throw mt("TARGET_NOT_FOUND",`Target paragraphId not found: "${a.paragraphId}".`);let m=f?.byParagraph?.get(d)||null,p=m?.index??ae(e).indexOf(d)+1,g=m?.fingerprint||_t(d,{revisionView:i}),h=m?.inTable??$o(d),v=m?.normalizedText||Z(Q(d,{revisionView:i}));if(s!=null&&s!==p)throw mt("TARGET_INDEX_MISMATCH",`Target paragraphId "${a.paragraphId}" (index ${p}) does not match requested index ${s}.`,m?[Gt(m)]:null);if(a.fingerprint&&a.fingerprint!==g){let w=i==="rejected"?"accepted":"rejected",y=_t(d,{revisionView:w}),b=a.fingerprint===y?` The supplied fingerprint matches the ${w} view; set target.revisionView to "${w}" or use a fingerprint extracted from the ${i} view.`:"";throw mt("TARGET_FINGERPRINT_MISMATCH",`Target paragraphId "${a.paragraphId}" no longer matches its source fingerprint.${b}`,m?[Gt(m)]:null)}if(typeof a.inTable=="boolean"&&a.inTable!==h)throw mt("TARGET_CONTEXT_MISMATCH",`Target paragraphId "${a.paragraphId}" does not match the requested table context.`,m?[Gt(m)]:null);if(l&&v!==Z(l)){let w=i==="rejected"?"accepted":"rejected",b=Z(Q(d,{revisionView:w}))===Z(l)?` The supplied text matches the ${w} view; set target.revisionView to "${w}".`:"";throw mt("TARGET_TEXT_MISMATCH",`Target paragraphId "${a.paragraphId}" no longer matches the supplied text.${b}`,m?[Gt(m)]:null)}if(a.occurrence!=null){let y=ja(e,l||v,f),b=y.findIndex(I=>I.paragraph===d)+1;if(b===0||b!==a.occurrence)throw mt("TARGET_OCCURRENCE_MISMATCH",`Target paragraphId "${a.paragraphId}" matches occurrence ${b}, not requested occurrence ${a.occurrence}.`,y.map(Gt))}return{paragraph:d,resolvedBy:"paragraph_id"}}if(a?.fingerprint&&!l&&!s){let d=(f?.entries||[]).filter(m=>m.fingerprint===a.fingerprint);if(typeof a.inTable=="boolean"&&(d=d.filter(m=>m.inTable===a.inTable)),d.length===1)return{paragraph:d[0].paragraph,resolvedBy:"fingerprint"};throw d.length>1?mt("AMBIGUOUS_TARGET","Target fingerprint matched multiple paragraphs; provide paragraphId or index.",d.map(Gt)):mt("TARGET_NOT_FOUND",`Target fingerprint not found: "${a.fingerprint}".`)}let u=[];if(l){let d=ja(e,l,f);if(u=aw(d,a),a?.fingerprint&&d.length>0&&u.length===0)throw mt("TARGET_FINGERPRINT_MISMATCH","Target text matched, but no paragraph matched the supplied source fingerprint.",d.map(Gt));if(typeof a?.inTable=="boolean"&&d.length>0&&u.length===0)throw mt("TARGET_CONTEXT_MISMATCH","Target text matched, but no paragraph matched the requested table context.",d.map(Gt));if(a?.occurrence){let m=u[a.occurrence-1]||null;if(!m)throw mt("TARGET_NOT_FOUND",`Target occurrence ${a.occurrence} was not found.`,u.map(Gt));return{paragraph:m.paragraph,resolvedBy:"occurrence"}}if(c){if(s){let m=u.find(p=>p.index===s)||null;if(m)return{paragraph:m.paragraph,resolvedBy:"ref"};if(a?.fingerprint&&u.length>0)throw mt("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${s}].`,u.map(Gt));if(u.length===1)return{paragraph:u[0].paragraph,resolvedBy:"strict_text_after_ref_drift"}}if(u.length>1)throw mt("AMBIGUOUS_TARGET",`Target text matched ${u.length} paragraphs; provide paragraphId, index, occurrence, or fingerprint.`,u.map(Gt));if(u.length===0)throw Fo(`Target paragraph not found: "${l}"`)}if(!s&&u.length===1)return{paragraph:u[0].paragraph,resolvedBy:a?.fingerprint?"fingerprint":"strict_text"}}if(s){let d=sf(e,s,f);if(d){let m=f?.byParagraph?.get(d)||null;if(a?.fingerprint&&a.fingerprint!==m?.fingerprint)throw mt("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${s}].`);if(typeof a?.inTable=="boolean"&&a.inTable!==m?.inTable)throw mt("TARGET_CONTEXT_MISMATCH",`Target paragraph reference [P${s}] does not match requested table context.`);if(l){let p=Va(e,l,{paragraphMetadataIndex:f}),g=(m?.text||Q(d,{revisionView:i})).trim(),h=Z(g),v=Z(l),w=h!==v;if(w&&p&&p!==d)return r(`[Target] [P${s}] drifted for ${o}; using strict text rematch.`),{paragraph:p,resolvedBy:"strict_text_after_ref_drift"};if(w){let y=Cs(e,l,{onInfo:r,paragraphMetadataIndex:f});if(y&&y!==d)return r(`[Target] [P${s}] drifted for ${o}; using fuzzy text rematch.`),{paragraph:y,resolvedBy:"fuzzy_text_after_ref_drift"};r(`[Target] Using [P${s}] fallback for ${o}; target text drifted.`)}else p&&p!==d&&r(`[Target] [P${s}] disambiguated duplicate target text for ${o}.`)}else r(`[Target] Using [P${s}] fallback for ${o}.`);return{paragraph:d,resolvedBy:"ref"}}n(`[WARN] Target reference [P${s}] not found; falling back to text matching for ${o}.`)}if(l&&!c){let d=Va(e,l,{paragraphMetadataIndex:f});if(d){let p=u.length;if(p>1){let g=`AMBIGUOUS_TARGET_HEURISTIC_USED: Target text matched ${p} paragraphs; permissive resolution chose candidate 1. Migrate to strict targeting (e.g. strictTargets: true with paragraphId, index, occurrence, or fingerprint) before v1.0.0.`;return n(g),{paragraph:d,resolvedBy:"strict_text",warnings:[g]}}return{paragraph:d,resolvedBy:"strict_text"}}let m=Cs(e,l,{onInfo:r,paragraphMetadataIndex:f});if(m)return{paragraph:m,resolvedBy:"fuzzy_text"}}throw Fo(l?`Target paragraph not found: "${l}"`:s?`Target paragraph reference not found: [P${s}]`:'Operation target missing: provide "target" text or "targetRef" ([P#]).')}function $o(e){return!!st(e,"tbl")}function ja(e,t,r=null){let n=Z(t);if(!n)return[];let o=r?.byNormalizedText?r:r?.paragraphMetadataIndex||null,a=r?.revisionView||o?.revisionView||"accepted";if(o?.byNormalizedText&&o.revisionView===a)return Array.from(o.byNormalizedText.get(n)||[]);let i=ae(e),l=[];for(let s=0;s<i.length;s++){let c=i[s],f=Q(c,{revisionView:a}).trim();f&&Z(f)===n&&l.push({paragraph:c,index:s+1,inTable:$o(c),paragraphId:Ke(c),fingerprint:_t(c,{text:f,index:s+1,revisionView:a}),text:f,revisionView:a})}return l}function Gt(e){return{index:e.index,paragraphId:e.paragraphId||null,text:e.text,inTable:e.inTable,fingerprint:e.fingerprint,revisionView:e.revisionView||"accepted"}}function aw(e,t){let r=e.slice();return t?.paragraphId&&(r=r.filter(n=>n.paragraphId===t.paragraphId)),typeof t?.inTable=="boolean"&&(r=r.filter(n=>n.inTable===t.inTable)),t?.fingerprint&&(r=r.filter(n=>n.fingerprint===t.fingerprint)),r}function iw(e,t,r=null){return t?r?.byId?r.byId.get(t)?.paragraph||null:ae(e).find(n=>Ke(n)===t)||null:null}function sw(e,t,r=null){if(!Array.isArray(e)||e.length===0)return null;let n=e.slice();if(typeof r=="boolean"){let o=n.filter(a=>a.inTable===r);o.length>0&&(n=o)}return Number.isInteger(t)&&t>0&&n.sort((o,a)=>Math.abs(o.index-t)-Math.abs(a.index-t)),n[0]||null}function Os(e,t=null){let r=t?.entries||null,n=r?null:ae(e),o=new Map,a=r?.length??n.length;for(let i=0;i<a;i++){let l=r?.[i]?.paragraph??n[i],s=(r?.[i]?.text??Ce(l)).trim();o.set(i+1,{text:s,normalizedText:r?.[i]?.normalizedText??Z(s),inTable:r?.[i]?.inTable??$o(l)})}return o}function Hn(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=an(e,t),o=_s(t.targetRef);if(!o||n?.resolvedBy!=="ref")return n;let a=t.targetRefSnapshot instanceof Map&&t.targetRefSnapshot.get(o)||null;if(!a)return n;let i=String(t.targetText||"").trim(),l=i||a.text||"",s=Z(l);if(!s||(t.paragraphMetadataIndex?.byParagraph?.get(n.paragraph)?.normalizedText||Z(Ce(n.paragraph)))===s)return n;let f=[];if(i&&f.push(i),a.text){let d=Z(a.text);d&&!f.some(m=>Z(m)===d)&&f.push(a.text)}let u=null;for(let d of f){let m=ja(e,d,t.paragraphMetadataIndex||null),p=sw(m,o,a.inTable);if(p&&(u||(u=p),p.paragraph!==n.paragraph)){u=p;break}}if(u&&u.paragraph!==n.paragraph){let d=t.opType||"operation";return r(`[Target] [P${o}] appears stale after prior edits; using strict text rematch for ${d}.`),{paragraph:u.paragraph,resolvedBy:"strict_text_after_ref_drift"}}throw Fo(`Target paragraph [P${o}] no longer matches its batch-start anchor.`)}function sn(e,t,r,n={}){if(!e||!t||!r)return null;let o=n?.opType||"redline",a=n?.targetRefSnapshot||null,i=typeof n?.onInfo=="function"?n.onInfo:()=>{},l=typeof n?.onWarn=="function"?n.onWarn:()=>{},s=Hn(e,{targetRef:t,opType:o,targetRefSnapshot:a,onInfo:i,onWarn:l})?.paragraph;if(!s)return null;let c=Hn(e,{targetRef:r,opType:o,targetRefSnapshot:a,onInfo:i,onWarn:l})?.paragraph;if(!c)return null;let f=Array.from(e.getElementsByTagNameNS("*","p")),u=f.indexOf(s),d=f.indexOf(c);if(u<0||d<u)return null;let m=f.slice(u,d+1);if(m.length===0)return null;let p=m[0]?.parentNode||null;return!p||!m.every(g=>g&&g.parentNode===p)?null:m}function Wa(e,t,r={}){if(!e||!e.parentNode)return{valid:!0};let n=t===""||r.operationKind==="delete",o=typeof t=="string"&&t.includes(`
|
|
168
|
-
`),a=r.targetEndParagraph||null,i=
|
|
169
|
-
`)||!
|
|
170
|
-
`),
|
|
171
|
-
`);return
|
|
172
|
-
`))return null;let i=
|
|
173
|
-
`),n=[];for(let i of r){if(!i.trim())continue;let l=
|
|
174
|
-
`)}function
|
|
175
|
-
`))return null;let r=Uo(t);if(!r||!Ls(r)||!Array.isArray(r.items)||r.items.length!==1)return null;let n=r.items[0];if(!n||n.type!=="numbered"&&n.type!=="bullet")return null;let o=String(n.marker||"").trim(),a=n.type==="numbered"?No(o||"1."):"bullet";return{type:n.type,marker:o,numberingStyle:a,startAt:gw(o,a),contentText:String(n.text||"").trim(),normalizedContent:Z(String(n.text||""))}}function Bs(e){let t=Ha(e);return t?String(t.contentText||"").trim():String(e||"").trim()}var pf={i:1,v:5,x:10,l:50,c:100,d:500,m:1e3};function pw(e){let t=String(e||"").toLowerCase();if(!/^[ivxlcdm]+$/.test(t))return null;let r=0;for(let n=0;n<t.length;n++){let o=pf[t[n]],a=pf[t[n+1]]||0;r+=o<a?-o:o}return r}function gw(e,t){let r=String(e||"").trim(),n=null;if(t==="decimal"){let o=r.match(/^(\d+)\.?$/);n=o?Number.parseInt(o[1],10):null}else if(t==="lowerRoman"||t==="upperRoman"){let o=r.match(/^([A-Za-z]+)[.)]?$/);n=o?pw(o[1]):null}else if(t==="lowerAlpha"||t==="upperAlpha"){let o=r.match(/^([A-Za-z])[.)]?$/);n=o?o[1].toLowerCase().charCodeAt(0)-96:null}else return null;return!Number.isFinite(n)||n<1||t!=="decimal"&&n===1?null:n}function qa(e,t=null){let r=e?.numberingKey?String(e.numberingKey):null,n=Number.isInteger(e?.startAt)&&e.startAt>0?e.startAt:null;if(!r)return{type:"none",numberingKey:null,startAt:n,numId:null};if(n==null)return{type:"sharedByStyle",numberingKey:r,startAt:null,numId:null};let o=t?.explicitByNumberingKey;if(!(o instanceof Map))return{type:"explicitIsolated",numberingKey:r,startAt:n,numId:null};let a=o.get(r)||null;return a&&a.numId!=null&&Number.isInteger(a.nextStartAt)&&a.nextStartAt===n?{type:"explicitReuse",numberingKey:r,startAt:n,numId:String(a.numId)}:{type:"explicitStartNew",numberingKey:r,startAt:n,numId:null}}function Ya(e,t,r,n){!e||!(e.explicitByNumberingKey instanceof Map)||!t||r==null||!Number.isInteger(n)||n<1||e.explicitByNumberingKey.set(String(t),{numId:String(r),nextStartAt:n+1})}function zo(e,t){!e||!(e.explicitByNumberingKey instanceof Map)||t&&e.explicitByNumberingKey.delete(String(t))}function cn(e,t){return e&&Array.from(e.childNodes||[]).find(r=>r&&r.nodeType===1&&r.namespaceURI==="http://schemas.openxmlformats.org/wordprocessingml/2006/main"&&r.localName===t)||null}function Ja(e,t={}){let r=t?.numId;if(r==null)return 0;let n=Number.isInteger(t?.ilvl)?Math.max(0,t.ilvl):0,o=t?.clearParagraphPropertyChanges!==!1,a=t?.removeListPropertyNode!==!1,i=t?.trackPropertyChange||null,l=(Array.isArray(e)?e:[]).filter(c=>c&&c.nodeType===1&&c.localName==="p"),s=0;for(let c of l){let f=c.ownerDocument;if(!f)continue;let u=cn(c,"pPr");u||(u=F(f,"w:pPr"),c.insertBefore(u,c.firstChild));let d=i?dt(u):null;if(o){let h=cn(u,"pPrChange");h&&u.removeChild(h)}if(a){let h=cn(u,"listPr");h&&u.removeChild(h)}let m=cn(u,"numPr");m||(m=F(f,"w:numPr"),u.appendChild(m));let p=cn(m,"ilvl");p||(p=F(f,"w:ilvl"),m.appendChild(p)),p.setAttribute("w:val",String(n));let g=cn(m,"numId");if(g||(g=F(f,"w:numId"),m.appendChild(g)),g.setAttribute("w:val",String(r)),i&&!cn(u,"pPrChange")){let h=ce(i.author,i.revisionIdAllocator||f,"pPrChange"),v=F(f,"w:pPrChange");v.setAttribute("w:id",String(h.id)),v.setAttribute("w:author",h.author),v.setAttribute("w:date",h.date),v.appendChild(d||F(f,"w:pPr")),u.appendChild(v)}s++}return s}function hf(e){let t=String(e||""),r=/xmlns:w\s*=/.test(t);return j(r?t:`<w:root xmlns:w="${B}">${t}</w:root>`,"application/xml").doc}function hw(e){let t=hf(e);return!t||Le(t)?null:ae(t)[0]||null}function ww(e){return e?String(e).replace(/<w:p>\s*<w:pPr>\s*<\/w:pPr>\s*<\/w:p>\s*$/i,""):""}function vw(e,t){for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return null}function qn(e,t){let r=vw(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function gf(e,t){e.setAttribute("w:val",String(t))}function yw(e){let t=hf(e);if(!t||Le(t))return null;let n=ae(t);for(let o of n){let a=Vt(o);for(let i of a){let l=qn(i,["w:val","val"]);if(l!=null)return String(l)}}return null}function bw(e,t,r,n={}){if(!e||!t||!Number.isInteger(r)||r<1)return e;let o=n.setAbstractStartOverride!==!1,a=se(),i=j(e,"application/xml").doc;if(!i||Le(i))return e;let c=Array.from(i.getElementsByTagNameNS("*","num")).find(p=>{let g=qn(p,["w:numId","numId"]);return g!=null&&String(g)===String(t)});if(!c)return e;let f=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null,u=qn(f,["w:val","val"]),d=Array.from(c.getElementsByTagNameNS("*","lvlOverride")).find(p=>qn(p,["w:ilvl","ilvl"])===0)||null;d||(d=F(i,"w:lvlOverride"),d.setAttribute("w:ilvl","0"),c.appendChild(d));let m=Array.from(d.getElementsByTagNameNS("*","startOverride"))[0]||null;if(m||(m=F(i,"w:startOverride"),d.appendChild(m)),gf(m,r),o&&u!=null){let g=Array.from(i.getElementsByTagNameNS("*","abstractNum")).find(h=>{let v=qn(h,["w:abstractNumId","abstractNumId"]);return v!=null&&v===u})||null;if(g){let h=Array.from(g.getElementsByTagNameNS("*","lvl")).find(w=>qn(w,["w:ilvl","ilvl"])===0)||null;h||(h=F(i,"w:lvl"),h.setAttribute("w:ilvl","0"),g.appendChild(h));let v=Array.from(h.getElementsByTagNameNS("*","start"))[0]||null;v||(v=F(i,"w:start"),h.insertBefore(v,h.firstChild)),gf(v,r)}}return a.serializeToString(i)}function un(e={}){let t=String(e.oxml||""),r=String(e.originalText||""),n=String(e.modifiedText||""),o=e.allowExistingList===!0;if(!t.trim()||!n.trim())return null;let a=hw(t);if(!a)return null;let i=_e(a);if(i&&!o)return null;let l=Ge(n).cleanText||n,s=Ha(n)||Ha(l);if(!s)return null;let c=Ha(r),f=Z(r)===Z(l),u=!!c&&c.type===s.type&&c.normalizedContent===s.normalizedContent;return!f&&!u?null:{listInput:`${s.marker} ${s.contentText}`.trim(),numberingKey:`${s.type}:${s.numberingStyle}:single`,originalText:r,wasListParagraph:!!i,numberingStyle:s.numberingStyle,startAt:s.startAt}}async function Yn(e,t={}){if(!e||!e.listInput)return{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:null,warnings:["Single-line list fallback plan missing"]};let r=t.author||"AI",n=t.generateRedlines??!0,o=t.pipeline?await t.pipeline.executeListGeneration(e.listInput,null,null,String(e.originalText||"")):await Xn({cleanText:e.listInput,numberingContext:null,originalRunModel:[],originalText:String(e.originalText||""),generateRedlines:n,author:r,revisionIdAllocator:t.revisionIdAllocator||null,numberingService:new ur}),a=o?.oxml||o?.ooxml||"",i=ww(a),l=yw(i),s=bw(o?.numberingXml||null,l,Number.isInteger(e?.startAt)?e.startAt:null,{setAbstractStartOverride:t.setAbstractStartOverride}),c=o?.isValid!==!1;return!i||!c?{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:e.numberingKey||null,warnings:["Single-line list fallback produced no valid OOXML"]}:{hasChanges:!0,oxml:i,numberingXml:s,includeNumbering:!0,listStructuralFallbackApplied:!0,listStructuralFallbackKey:e.numberingKey||null,listStructuralFallbackStartAt:Number.isInteger(e?.startAt)?e.startAt:null,warnings:["Single-line list structural fallback applied"]}}function wf(e,t){if(!e||!Array.isArray(t))return null;for(let r of t){let n=e.getAttribute(r);if(n==null||n==="")continue;let o=Number.parseInt(String(n),10);if(Number.isFinite(o))return o}return null}function Jn(e,t,r=null){let n=Number.isInteger(e)&&e>0?e:1,o=t instanceof Set?t:new Set;for(;o.has(n);)n+=1;if(Number.isInteger(r)&&r>0&&n>r){for(let a=1;a<=r;a+=1)if(!o.has(a))return a}return n}function Ht(e,t={}){let r=Number.isInteger(t?.minId)&&t.minId>0?t.minId:1,n=Number.isInteger(t?.maxPreferred)&&t.maxPreferred>=r?t.maxPreferred:32767,o=new Set,a=new Set;if(String(e||"").trim())try{let f=Xe(e),u=Array.from(f.getElementsByTagNameNS("*","abstractNum")),d=Array.from(f.getElementsByTagNameNS("*","num"));for(let m of u){let p=wf(m,["w:abstractNumId","abstractNumId"]);p!=null&&a.add(p)}for(let m of d){let p=wf(m,["w:numId","numId"]);p!=null&&o.add(p)}}catch{}let i=o.size>0?Math.max(...o):0,l=a.size>0?Math.max(...a):0,s=Math.max(r,i+1),c=Math.max(r,l+1);return{sourceNumberingXml:String(e||""),nextNumId:Jn(s,o,n),nextAbstractNumId:Jn(c,a,n),usedNumIds:o,usedAbstractNumIds:a,minId:r,maxPreferred:n}}function Iw(e){return!e||typeof e!="object"?null:(e.usedNumIds instanceof Set||(e.usedNumIds=new Set),e.usedAbstractNumIds instanceof Set||(e.usedAbstractNumIds=new Set),(!Number.isInteger(e.minId)||e.minId<1)&&(e.minId=1),(!Number.isInteger(e.maxPreferred)||e.maxPreferred<e.minId)&&(e.maxPreferred=32767),(!Number.isInteger(e.nextNumId)||e.nextNumId<e.minId)&&(e.nextNumId=e.minId),(!Number.isInteger(e.nextAbstractNumId)||e.nextAbstractNumId<e.minId)&&(e.nextAbstractNumId=e.minId),e.nextNumId=Jn(e.nextNumId,e.usedNumIds,e.maxPreferred),e.nextAbstractNumId=Jn(e.nextAbstractNumId,e.usedAbstractNumIds,e.maxPreferred),e)}function Vo(e,t="num"){let r=Iw(e);if(!r)return null;let n=t==="abstract",o=n?r.nextAbstractNumId:r.nextNumId;return!Number.isInteger(o)||o<1?null:(n?(r.usedAbstractNumIds.add(o),r.nextAbstractNumId=Jn(o+1,r.usedAbstractNumIds,r.maxPreferred)):(r.usedNumIds.add(o),r.nextNumId=Jn(o+1,r.usedNumIds,r.maxPreferred)),o)}function Zn(e){let t=Vo(e,"num"),r=Vo(e,"abstract");return t==null||r==null?null:{numId:t,abstractNumId:r}}function Ft(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:e.getElementsByTagName("parsererror").length>0}function Xo(e,t){return!!(e&&e.nodeType===1&&e.namespaceURI===ue&&e.localName===t)}function xw(e,t){for(let r of t||[]){let n=e?.getAttribute?.(r);if(n!=null&&n!=="")return n}return null}function lt(e,t){let r=xw(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function vf(e,t,r){e?.setAttribute?.(t,String(r))}function Fs(e,t){e?.setAttribute?.("w:val",String(t))}function Za(e,t){if(!(!Array.isArray(e)||t==null)){for(let r of e)if(!Ot(r))for(let n of Vt(r))Fs(n,t)}}function Qa(e){for(let t of e||[])for(let r of Vt(t)){let n=lt(r,["w:val","val"]);if(n!=null)return String(n)}return null}function ei(e,t,r){let n=String(e),o=String(t),a=Number.isInteger(r)&&r>0?r:1,i=Array.from({length:9},(l,s)=>{let c=Array.from({length:s+1},(u,d)=>`%${d+1}`).join(".")+".",f=720*(s+1);return`
|
|
146
|
+
`);return{valid:o.every(s=>s.severity!=="error"),normalizedMarkdown:l,blocks:n,issues:o,counts:i,requiresStructuredContent:n.length>1||n.some(s=>s.type==="heading"||s.type==="table"||s.type==="list"&&s.items>1)}}function th(e,t,r={}){let n=Ea(t);return{...n,operation:n.valid?{type:"replace",target:e,modified:n.normalizedMarkdown,structuredContent:!0,...r.author?{author:r.author}:{},...typeof r.generateRedlines=="boolean"?{generateRedlines:r.generateRedlines}:{},...r.existingRevisions?{existingRevisions:r.existingRevisions}:{}}:null}}var ko=["w:rStyle","w:rFonts","w:b","w:bCs","w:i","w:iCs","w:caps","w:smallCaps","w:strike","w:dstrike","w:outline","w:shadow","w:emboss","w:imprint","w:noProof","w:snapToGrid","w:vanish","w:webHidden","w:color","w:spacing","w:w","w:kern","w:position","w:sz","w:szCs","w:highlight","w:u","w:effect","w:bdr","w:shd","w:fitText","w:vertAlign","w:rtl","w:cs","w:em","w:lang","w:eastAsianLayout","w:specVanish","w:oMath","w:rPrChange"];function et(e,t){let r=ko.indexOf(t.nodeName),n=r===-1?999:r,o=!1;for(let a of Array.from(e.childNodes)){if(a.nodeType!==1)continue;let i=ko.indexOf(a.nodeName);if((i===-1?999:i)>n){e.insertBefore(t,a),o=!0;break}}o||e.appendChild(t)}function rh(e,t,r,n){if(!t||!r)return;let o=!!r.bold,a=!!r.italic,i=!!r.underline,l=!!r.strikethrough,s=new Set;if(o&&(s.add("w:b"),s.add("w:bCs")),a&&(s.add("w:i"),s.add("w:iCs")),i&&s.add("w:u"),l&&s.add("w:strike"),s.size>0){let c=[];for(let f of Array.from(t.childNodes))s.has(f.nodeName)&&c.push(f);for(let f of c)t.removeChild(f)}if(o){let c=$(e,"w:b");c.setAttribute("w:val",n==="add"?"1":"0"),et(t,c);let f=$(e,"w:bCs");f.setAttribute("w:val",n==="add"?"1":"0"),et(t,f)}if(a){let c=$(e,"w:i");c.setAttribute("w:val",n==="add"?"1":"0"),et(t,c);let f=$(e,"w:iCs");f.setAttribute("w:val",n==="add"?"1":"0"),et(t,f)}if(i){let c=$(e,"w:u");c.setAttribute("w:val",n==="add"?"single":"none"),et(t,c)}if(l){let c=$(e,"w:strike");c.setAttribute("w:val",n==="add"?"1":"0"),et(t,c)}}function Iu(e,t,r){rh(e,t,r,"remove")}function Qt(e){let t={bold:!1,italic:!1,underline:!1,strikethrough:!1,hasFormatting:!1};if(!e)return t;for(let r of Array.from(e.childNodes))if(r.nodeName==="w:b"&&(t.bold=en(r,!1)),r.nodeName==="w:i"&&(t.italic=en(r,!1)),r.nodeName==="w:u"&&(t.underline=en(r,!0)),r.nodeName==="w:strike"&&(t.strikethrough=en(r,!1)),r.nodeName==="w:rStyle"){let n=r.getAttribute("w:val");if(n){let o=n.toLowerCase();(o.includes("bold")||o.includes("strong"))&&(t.bold=!0),(o.includes("italic")||o.includes("emphasis"))&&(t.italic=!0),o.includes("underline")&&(t.underline=!0)}}return t.hasFormatting=t.bold||t.italic||t.underline||t.strikethrough,t}function en(e,t){let n=(e.getAttribute("w:val")||e.getAttribute("val")||"").toLowerCase();return n?t?n!=="none"&&n!=="0"&&n!=="false"&&n!=="off":n!=="0"&&n!=="false"&&n!=="off":!0}var bu=["w:pStyle","w:keepNext","w:keepLines","w:pageBreakBefore","w:framePr","w:widowControl","w:numPr","w:suppressLineNumbers","w:pBdr","w:shd","w:tabs","w:suppressAutoHyphens","w:kinsoku","w:wordWrap","w:overflowPunct","w:topLinePunct","w:autoSpaceDE","w:autoSpaceDN","w:bidi","w:adjustRightInd","w:snapToGrid","w:spacing","w:ind","w:contextualSpacing","w:mirrorIndents","w:suppressOverlap","w:jc","w:textDirection","w:textAlignment","w:textboxTightWrap","w:outlineLvl","w:divId","w:cnfStyle","w:rPr","w:sectPr","w:pPrChange"];function pr(e,t){let r=bu.indexOf(t.nodeName),n=r===-1?999:r,o=!1;for(let a of Array.from(e.childNodes)){if(a.nodeType!==1)continue;let i=bu.indexOf(a.nodeName);if((i===-1?999:i)>n){e.insertBefore(t,a),o=!0;break}}o||e.appendChild(t)}function Nu(e,t){if(!t)return!1;let r=Qt(e);if(t.bold!==void 0&&r.bold!==!!t.bold||t.italic!==void 0&&r.italic!==!!t.italic||t.underline!==void 0&&r.underline!==!!t.underline)return!0;let n=t.strike!==void 0?t.strike:t.strikethrough;if(n!==void 0&&r.strikethrough!==!!n)return!0;if(t.highlight!==void 0){let o=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:highlight"||l.localName==="highlight")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.highlight&&t.highlight!=="none"?String(t.highlight).toLowerCase():null;if((a||null)!==i)return!0}if(t.color!==void 0){let o=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:color"||l.localName==="color")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.color&&t.color!=="auto"?String(t.color).replace(/^#/,"").toUpperCase():null;if((a?.toUpperCase()||null)!==i)return!0}if(t.fontSize!==void 0){let o=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:sz"||l.localName==="sz")),a=o?o.getAttribute("w:val")||o.getAttribute("val"):null,i=t.fontSize!==null&&t.fontSize!==""?String(t.fontSize):null;if(a!==i)return!0}if(t.fontFamily!==void 0){let o=Array.from(e?.childNodes||[]).find(l=>l.nodeType===1&&(l.nodeName==="w:rFonts"||l.localName==="rFonts")),a=o?o.getAttribute("w:ascii")||o.getAttribute("ascii"):null,i=t.fontFamily||null;if(a!==i)return!0}return!1}function Tu(e,t,r){if(!t||!r)return;let n=a=>{let i=[];for(let l of Array.from(t.childNodes))l.nodeType===1&&a.includes(l.nodeName)&&i.push(l);for(let l of i)t.removeChild(l)};if(r.bold!==void 0){n(["w:b","w:bCs"]);let a=$(e,"w:b");a.setAttribute("w:val",r.bold?"1":"0"),et(t,a);let i=$(e,"w:bCs");i.setAttribute("w:val",r.bold?"1":"0"),et(t,i)}if(r.italic!==void 0){n(["w:i","w:iCs"]);let a=$(e,"w:i");a.setAttribute("w:val",r.italic?"1":"0"),et(t,a);let i=$(e,"w:iCs");i.setAttribute("w:val",r.italic?"1":"0"),et(t,i)}if(r.underline!==void 0){n(["w:u"]);let a=$(e,"w:u");a.setAttribute("w:val",r.underline?"single":"none"),et(t,a)}let o=r.strike!==void 0?r.strike:r.strikethrough;if(o!==void 0){n(["w:strike","w:dstrike"]);let a=$(e,"w:strike");a.setAttribute("w:val",o?"1":"0"),et(t,a)}if(r.highlight!==void 0&&(n(["w:highlight"]),r.highlight&&r.highlight!=="none")){let a=$(e,"w:highlight");a.setAttribute("w:val",String(r.highlight).toLowerCase()),et(t,a)}if(r.color!==void 0&&(n(["w:color"]),r.color&&r.color!=="auto")){let a=$(e,"w:color");a.setAttribute("w:val",String(r.color).replace(/^#/,"")),et(t,a)}if(r.fontSize!==void 0&&(n(["w:sz","w:szCs"]),r.fontSize!==null&&r.fontSize!=="")){let a=String(r.fontSize),i=$(e,"w:sz");i.setAttribute("w:val",a),et(t,i);let l=$(e,"w:szCs");l.setAttribute("w:val",a),et(t,l)}if(r.fontFamily!==void 0&&(n(["w:rFonts"]),r.fontFamily)){let a=$(e,"w:rFonts");a.setAttribute("w:ascii",r.fontFamily),a.setAttribute("w:hAnsi",r.fontFamily),a.setAttribute("w:cs",r.fontFamily),et(t,a)}}function Su(e,t){if(!t)return!1;if(t.alignment!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:jc"||o.localName==="jc"));if((r?r.getAttribute("w:val")||r.getAttribute("val"):null)!==t.alignment)return!0}if(t.keepNext!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:keepNext"||o.localName==="keepNext"));if((r?en(r,!1):!1)!==!!t.keepNext)return!0}if(t.keepLines!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:keepLines"||o.localName==="keepLines"));if((r?en(r,!1):!1)!==!!t.keepLines)return!0}if(t.pageBreakBefore!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:pageBreakBefore"||o.localName==="pageBreakBefore"));if((r?en(r,!1):!1)!==!!t.pageBreakBefore)return!0}if(t.style!==void 0){let r=Array.from(e?.childNodes||[]).find(o=>o.nodeType===1&&(o.nodeName==="w:pStyle"||o.localName==="pStyle"));if((r?r.getAttribute("w:val")||r.getAttribute("val"):null)!==t.style)return!0}if(t.numbering!==void 0){let r=nh(e),n=t.numbering;if(n===null)return r!=null;if(!r||r.numId!==String(Number(n.numId))||r.level!==(Number(n.level)||0))return!0}return!1}function nh(e){let t=Qe(e,"numPr");if(!t)return null;let r=n=>{let o=Qe(t,n);return o?o.getAttribute("w:val")??o.getAttribute("val"):null};return{numId:String(Number(r("numId"))),level:Number(r("ilvl"))||0}}function Kn(e,t,r){if(!t||!r)return;let n=o=>{let a=[];for(let i of Array.from(t.childNodes))i.nodeType===1&&o.includes(i.nodeName)&&a.push(i);for(let i of a)t.removeChild(i)};if(r.alignment!==void 0&&(n(["w:jc"]),r.alignment)){let o=$(e,"w:jc");o.setAttribute("w:val",r.alignment),pr(t,o)}if(r.keepNext!==void 0){n(["w:keepNext"]);let o=$(e,"w:keepNext");r.keepNext||o.setAttribute("w:val","0"),pr(t,o)}if(r.keepLines!==void 0){n(["w:keepLines"]);let o=$(e,"w:keepLines");r.keepLines||o.setAttribute("w:val","0"),pr(t,o)}if(r.pageBreakBefore!==void 0){n(["w:pageBreakBefore"]);let o=$(e,"w:pageBreakBefore");r.pageBreakBefore||o.setAttribute("w:val","0"),pr(t,o)}if(r.style!==void 0&&(n(["w:pStyle"]),r.style)){let o=$(e,"w:pStyle");o.setAttribute("w:val",r.style),pr(t,o)}if(r.numbering!==void 0&&(n(["w:numPr"]),r.numbering)){let o=$(e,"w:numPr"),a=$(e,"w:ilvl");a.setAttribute("w:val",String(Number(r.numbering.level)||0));let i=$(e,"w:numId");i.setAttribute("w:val",String(Number(r.numbering.numId))),o.appendChild(a),o.appendChild(i),pr(t,o)}}var Au="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function er(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===Au&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function oh(e){return!e||e.nodeType!==1||e.namespaceURI!==Au?!1:e.localName==="del"||e.localName==="moveFrom"}function Eu(e){let t=[],r=Array.from(e?.childNodes||[]).reverse();for(;r.length>0;){let n=r.pop();if(!n||n.nodeType!==1||oh(n))continue;if(er(n,"r")){t.push(n);continue}let o=Array.from(n.childNodes||[]);for(let a=o.length-1;a>=0;a-=1)r.push(o[a])}return t}function bt(e){let t=new Set(["comment","footnote","endnote"]);return Ke(e,"*","p").filter(n=>{let o=n.parentNode;for(;o&&o.nodeName;){let a=String(o.localName||"").toLowerCase();if(t.has(a))return!1;o=o.parentNode}return!0})}function Ra(e){let t=[],r=0;for(let n=0;n<e.length;n++){let o=e[n],a=Eu(o);for(let i of a){let l=Ue(i,"w:rPr");Array.from(i.childNodes||[]).forEach(s=>{if(er(s,"t")){let c=s.textContent||"";c.length>0&&(t.push({charStart:r,charEnd:r+c.length,textElement:s,runElement:i,paragraph:o,container:i.parentNode,rPr:l}),r+=c.length)}else(er(s,"br")||er(s,"cr")||er(s,"tab")||er(s,"noBreakHyphen"))&&(t.push({charStart:r,charEnd:r+1,textElement:s,runElement:i,paragraph:o,container:i.parentNode,rPr:l}),r+=1)})}r=Yr(r,n,e.length)}return{textSpans:t,charOffset:r}}function ah(e,t,r,n,o,a=null){let i=null;for(let c of Array.from(e.childNodes))if(er(c,"rPr")){i=c;break}let l=Qt(i);a&&(a.bold&&!l.bold&&(l.bold=!0),a.italic&&!l.italic&&(l.italic=!0),a.underline&&!l.underline&&(l.underline=!0),a.strikethrough&&!l.strikethrough&&(l.strikethrough=!0)),l.hasFormatting=l.bold||l.italic||l.underline||l.strikethrough;let s=r;for(let c of Array.from(e.childNodes))if(er(c,"t")){let f=c.textContent||"";if(f.length>0){let u=s,d=s+f.length;n.push({charStart:u,charEnd:d,textElement:c,runElement:e,paragraph:t,rPr:i,format:{...l}}),l.hasFormatting&&o.push({start:u,end:d,format:{...l},run:e,rPr:i}),s=d}}return s}function Ru(e){let t=[],r=[],n=0,o=bt(e);for(let a=0;a<o.length;a++){let i=o[a],l=null;for(let f of Array.from(i.childNodes))if(er(f,"pPr")){for(let u of Array.from(f.childNodes))if(er(u,"rPr")){l=u;break}break}let s=Qt(l);s.hasFormatting&&W(`[OxmlEngine] Found paragraph-level formatting: ${JSON.stringify(s)}`);let c=Eu(i);for(let f of c)n=ah(f,i,n,r,t,s);n=Yr(n,a,o.length)}return W(`[OxmlEngine] Extracted ${r.length} text spans, ${t.length} format hints`),{existingFormatHints:t,textSpans:r,paragraphs:o}}var ih=new Set(["ins","del","moveFrom","moveTo","pPrChange","rPrChange","tblPrChange","trPrChange","tcPrChange","sectPrChange"]);function pt(e){if(!e)return null;let t=e.cloneNode(!0),r=[t,...Array.from(t.getElementsByTagName?.("*")||[])];for(let n of r.reverse())ih.has(String(n.localName||n.nodeName||"").replace(/^.*:/,""))&&n.parentNode?.removeChild(n);return t}function $t(e,t=null){if(!e)return e;let r=e.nodeType===9?e:e.ownerDocument,n=t instanceof De?t:lr(r)||_r(r),o=[e,...Array.from(e.getElementsByTagName?.("*")||[])];for(let a of o){if(!F(a,"rPrChange"))continue;let i=String(n.next());typeof a.setAttributeNS=="function"?a.setAttributeNS(B,"w:id",i):a.setAttribute("w:id",i),n._receiptCollector?.recordRevision(Number(i),"rPrChange")}return e}function tr(e,t,r,n,o=null){let a=$(e,t==="ins"?"w:ins":"w:del"),i=o||ue(n,e,t==="ins"?"ins":"del");return a.setAttribute("w:id",String(i.id)),a.setAttribute("w:author",i.author),a.setAttribute("w:date",i.date),r&&a.appendChild(r),a}function Br(e,t,r,n){let o=$(e,"w:r");if(r&&o.appendChild(r.cloneNode(!0)),!n)return Pu(e,o,t),o;let a=$(e,n?"w:delText":"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=t,o.appendChild(a),o}function Pa(e,t,r,n,o,a,i){if(!t)return[];let l=new Set([0,t.length]);for(let f of n){let u=Math.max(0,f.start-o),d=Math.min(t.length,f.end-o);u>=0&&u<t.length&&l.add(u),d>0&&d<=t.length&&l.add(d)}let s=Array.from(l).sort((f,u)=>f-u),c=[];for(let f=0;f<s.length-1;f++){let u=s[f],d=s[f+1],m=t.slice(u,d);if(!m)continue;let p=o+u,g=o+d,h=n.filter(y=>y.start<=p&&y.end>=g),v={...Qt(r)};h.forEach(y=>{y.format&&Object.assign(v,y.format)});let w=h.length>0?Gn(e,r,v,a,i):r?.cloneNode(!0)||null;c.push(vs(e,m,w,!1))}return c}function vs(e,t,r,n){let o=$(e,"w:r");if(r&&o.appendChild(r),!n)return Pu(e,o,t),o;let a=$(e,n?"w:delText":"w:t");return a.setAttribute("xml:space","preserve"),a.textContent=t,o.appendChild(a),o}function Pu(e,t,r){let o=String(r||"").split(/(\t|\n|\u2011)/);for(let a of o){if(!a)continue;if(a===" "){t.appendChild($(e,"w:tab"));continue}if(a===`
|
|
147
|
+
`){t.appendChild($(e,"w:br"));continue}if(a==="\u2011"){t.appendChild($(e,"w:noBreakHyphen"));continue}let i=$(e,"w:t");/^\s|\s$/.test(a)&&i.setAttribute("xml:space","preserve"),i.textContent=a,t.appendChild(i)}}function Gn(e,t,r,n,o){let a=$(e,"w:rPr");t&&Array.from(t.childNodes).forEach(s=>{["w:b","w:bCs","w:i","w:iCs","w:u","w:strike","w:rPrChange"].includes(s.nodeName)||a.appendChild(s.cloneNode(!0))});let i=r||{bold:!1,italic:!1,underline:!1,strikethrough:!1};n&&o&&sh(e,a,n,t);let l=(s,c,f=null,u="0")=>{let d=$(e,s);c?f&&d.setAttribute("w:val",f):u&&d.setAttribute("w:val",u);let m=ko.indexOf(s),p=m===-1?999:m,g=!1;for(let h of Array.from(a.childNodes)){if(h.nodeType!==1)continue;let v=ko.indexOf(h.nodeName);if((v===-1?999:v)>p){a.insertBefore(d,h),g=!0;break}}g||a.appendChild(d)};return l("w:b",!!i.bold,"1","0"),l("w:bCs",!!i.bold,"1","0"),l("w:i",!!i.italic,"1","0"),l("w:iCs",!!i.italic,"1","0"),l("w:u",!!i.underline,"single","none"),l("w:strike",!!i.strikethrough,"1","0"),a}function Mo(e,t,r,n,o){let a=$(e,"w:rPrChange"),i=ue(r,e,"rPrChange");a.setAttribute("w:id",String(i.id)),a.setAttribute("w:author",i.author),a.setAttribute("w:date",n||i.date);let s=pt(o||t)||$(e,"w:rPr");a.appendChild(s);let c=Ue(t,"w:rPrChange");return c&&t.removeChild(c),t.appendChild(a),a}function sh(e,t,r,n){Mo(e,t,r,null,n||t)}function Hn(e,t,r,n,o){let a=$(e,"w:pPrChange"),i=ue(r,e,"pPrChange");a.setAttribute("w:id",String(i.id)),a.setAttribute("w:author",i.author),a.setAttribute("w:date",n||i.date);let s=pt(o||t)||$(e,"w:pPr");a.appendChild(s);let c=Array.from(t.childNodes).find(f=>f.nodeType===1&&(f.nodeName==="w:pPrChange"||f.localName==="pPrChange"));return c&&t.removeChild(c),t.appendChild(a),a}var lh="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function qn(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===lh&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function Ca(e,t,r){let n=new Map;for(let i of r)!i||!i.paragraph||(n.has(i.paragraph)||n.set(i.paragraph,[]),n.get(i.paragraph).push(i));let o=[],a=0;return t.forEach((i,l)=>{let s=(n.get(i)||[]).slice().sort((d,m)=>d.charStart-m.charStart),c=ch(s),f=ys(c),u=f.trim();o.push({paragraph:i,spans:s,text:c,normalizedText:f,normalizedTrim:u,startOffset:a}),a+=f.length,a=Yr(a,l,t.length)}),o}function Cu(e,t){if(!t)return null;let r=ys(t),n=r.trim();if(!n)return null;for(let o of e)if(o.normalizedText===r)return o;for(let o of e)if(o.normalizedTrim===n)return o;return null}function _u(e,t){let r=ys(t),n=r.trim(),o=null,a=0;for(let i of e)if(i.normalizedText===r)return o=i,{targetInfo:o,matchOffset:a};if(n.length>0){for(let i of e)if(i.normalizedTrim===n)return o=i,{targetInfo:o,matchOffset:a}}if(n.length>0){let l=e.map(s=>s.normalizedText).join(`
|
|
148
|
+
`).indexOf(n);if(l!==-1)for(let s of e){let c=s.startOffset,f=s.normalizedText.length;if(l>=c&&l<=c+f){o=s,a=l-c;break}}}if(!o&&e.length===1&&r.length>0){let i=e[0],l=i.normalizedTrim||"";if(l.length>0){let s=r.indexOf(l);s>=0&&(o=i,a=-s)}}return{targetInfo:o,matchOffset:a}}function Ou(e){let t=e;for(;t;){if(qn(t,"p"))return t;t=t.parentNode}return null}function ch(e){if(!e||e.length===0)return"";let t="";for(let r of e){if(!r||!r.textElement)continue;let n=r.textElement;qn(n,"t")?t+=r.textElement.textContent||"":qn(n,"tab")?t+=" ":qn(n,"br")||qn(n,"cr")?t+=`
|
|
149
|
+
`:qn(n,"noBreakHyphen")&&(t+="\u2011")}return t}function ys(e){return e?e.replace(/\r/g,`
|
|
150
|
+
`).replace(/\u00a0/g," "):""}function ku(e,t,r){let n=Array.from(new Set(r)).sort((l,s)=>l-s);if(n.length===0||t.length===0)return[...t];let o=[...t].sort((l,s)=>l.charStart-s.charStart||l.charEnd-s.charEnd),a=[],i=0;for(let l of o){for(;i<n.length&&n[i]<=l.charStart;)i++;let s=l;for(;i<n.length&&n[i]<s.charEnd;){let c=n[i],f=uh(e,s,c);if(!f){i++;continue}a.push(f[0]),s=f[1],i++}a.push(s)}return a}function uh(e,t,r){let n=t.runElement,o=n.parentNode;if(!o)return null;let a=t.textElement.textContent||"",i=r-t.charStart,l=a.substring(0,i),s=a.substring(i);if(l.length===0||s.length===0)return null;let c=Br(e,l,t.rPr,!1),f=Br(e,s,t.rPr,!1);o.insertBefore(c,n),o.insertBefore(f,n),o.removeChild(n);let u=c.getElementsByTagName("w:t")[0],d=f.getElementsByTagName("w:t")[0];return[{...t,charEnd:r,textElement:u,runElement:c},{...t,charStart:r,textElement:d,runElement:f}]}var fh="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function dh(e,t){if(!e||e.nodeType!==1)return!1;if(e.namespaceURI===fh&&e.localName===t)return!0;let r=String(e.nodeName||"");return r===`w:${t}`||r===t}function mh(e){return Array.isArray(e)?{textSpans:e,paragraphs:null,paragraphInfos:null}:!e||typeof e!="object"?{textSpans:null,paragraphs:null,paragraphInfos:null}:{textSpans:Array.isArray(e.textSpans)?e.textSpans:null,paragraphs:Array.isArray(e.paragraphs)?e.paragraphs:null,paragraphInfos:Array.isArray(e.paragraphInfos)?e.paragraphInfos:null}}function Mu(e,t,r,n,o,a=!0){let i=!1,l=new Set;W(`[OxmlEngine] Surgical format removal: ${r.length} hints to process (using w:rPrChange)`);for(let s of r){let c=s.run;if(l.has(c)||(l.add(c),!c.parentNode))continue;W("[OxmlEngine] Processing run for surgical format removal, format:",s.format);let f=Ue(c,"w:rPr");f||(f=$(e,"w:rPr"),c.insertBefore(f,c.firstChild)),a&&Mo(e,f,o||ae()),Iu(e,f,s.format),i=!0}return i?(W("[OxmlEngine] Surgical format removal completed successfully (Pure Format Mode)"),{oxml:n.serializeToString(e),hasChanges:!0}):(W("[OxmlEngine] No format changes were applied"),{oxml:n.serializeToString(e),hasChanges:!1})}function ph(e,t,r,n,o,a=!0){let i=!1,l=new Set;if(!t||t.length===0)return{oxml:n.serializeToString(e),hasChanges:!1};let s=[];for(let d of r)s.push(d.start,d.end);let f=ku(e,t,s).slice().sort((d,m)=>d.charStart-m.charStart||d.charEnd-m.charEnd),u=gh(r);for(let d of f){if(!d||!d.textElement||!dh(d.textElement,"t"))continue;let m=u(d.charStart,d.charEnd);if(m.length===0)continue;let p=Hi(...m.map(R=>R.format)),g={bold:!!p.bold,italic:!!p.italic,underline:!!p.underline,strikethrough:!!p.strikethrough},h=d.format||Qt(d.rPr),v={bold:!!h.bold,italic:!!h.italic,underline:!!h.underline,strikethrough:!!h.strikethrough};if(!["bold","italic","underline","strikethrough"].some(R=>g[R]!==v[R])||l.has(d.runElement)||(l.add(d.runElement),!(d.textElement.textContent||""))||!d.runElement.parentNode)continue;let T=d.runElement,A=Ue(T,"w:rPr"),E=Gn(e,A,g,o||ae(),a),I=A;if(!I)T.insertBefore(E,T.firstChild);else{for(;I.firstChild;)I.removeChild(I.firstChild);Array.from(E.childNodes).forEach(R=>I.appendChild(R))}i=!0}return{oxml:n.serializeToString(e),hasChanges:i}}function Lu(e,t,r,n,o,a=!0,i=null){let l=mh(i),s=l.paragraphs||bt(e),c=l.textSpans||[];if(l.textSpans||({textSpans:c}=Ra(s)),!c||c.length===0)return ir("[OxmlEngine] No spans available for surgical format-only change; requesting caller fallback strategy"),{hasChanges:!0,useNativeApi:!0,formatHints:r,originalText:t};if(!r||r.length===0)return{oxml:n.serializeToString(e),hasChanges:!1};let f=l.paragraphInfos||Ca(e,s,c),{targetInfo:u,matchOffset:d}=_u(f,t);if(!u||!u.spans||u.spans.length===0)return ir("[OxmlEngine] Unable to pinpoint target paragraph for surgical format-only change; requesting caller fallback strategy"),{hasChanges:!0,useNativeApi:!0,formatHints:r,originalText:t};let m=u.spans[0].charStart,p=u.spans.map(h=>({...h,charStart:h.charStart-m,charEnd:h.charEnd-m})),g=r.map(h=>({...h,start:h.start+d,end:h.end+d}));return ph(e,p,g,n,o,a)}function gh(e){let t=(e||[]).slice().sort((o,a)=>o.start-a.start||o.end-a.end),r=[],n=0;return(o,a)=>{for(;n<t.length&&t[n].start<a;)r.push(t[n]),n++;for(let i=r.length-1;i>=0;i--)r[i].end<=o&&r.splice(i,1);return r.filter(i=>i.start<a&&i.end>o)}}function _a(e){let t=e?.localName;return t?t.indexOf(":")<0?t:t.replace(/^.*:/,""):String(e?.nodeName||"").replace(/^.*:/,"")}function tn(e,t=null,r="accepted"){let n=r==="current"?"accepted":r,o=e;for(;o&&o!==t;){let a=_a(o);if(n==="accepted"&&(a==="del"||a==="moveFrom")||n==="rejected"&&(a==="ins"||a==="moveTo"))return!1;o=o.parentNode}return!0}function gr(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=t.boundary||null;if(!tn(e,n,r))return"";let o="",a=i=>{for(let l=i?.firstChild;l;l=l.nextSibling){if(l?.nodeType!==1||l.namespaceURI&&l.namespaceURI!==B||!tn(l,n,r))continue;let s=_a(l);s==="t"||s==="delText"&&r==="rejected"?o+=l.textContent||"":s==="tab"?o+=" ":s==="br"||s==="cr"?o+=`
|
|
151
|
+
`:s==="noBreakHyphen"?o+="\u2011":s==="softHyphen"?o+="\xAD":a(l)}};return a(e),o}var $r=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"";function Oa(e,t={}){if(!e)return[];let r=[];function n(u,d,m){for(let p of Array.from(u?.childNodes||[])){if(p?.nodeType!==1||p.namespaceURI&&p.namespaceURI!==B)continue;let g=_a(p);if(g==="pPr"||g==="rPr")continue;let h=d;g==="ins"?h={kind:"insertion",author:$r(p,"author")||void 0,revisionId:$r(p,"id")||void 0}:g==="del"?h={kind:"deletion",author:$r(p,"author")||void 0,revisionId:$r(p,"id")||void 0}:g==="moveFrom"?h={kind:"move_from",author:$r(p,"author")||void 0,revisionId:$r(p,"id")||void 0}:g==="moveTo"&&(h={kind:"move_to",author:$r(p,"author")||void 0,revisionId:$r(p,"id")||void 0});let v=m;g==="r"&&(v=p);let w=null,y=h?h.kind:"baseline",x=h?.author,b=h?.revisionId;g==="t"?w=p.textContent||"":g==="delText"?(w=p.textContent||"",h||(y="deletion")):g==="tab"?w=" ":g==="br"||g==="cr"?w=`
|
|
152
|
+
`:g==="noBreakHyphen"?w="\u2011":g==="softHyphen"&&(w="\xAD"),w!==null?w.length>0&&r.push({text:w,kind:y,author:x,revisionId:b,carrier:v||p,carrierContainer:(v||p)?.parentNode||null}):n(p,h,v)}}let o=_a(e)==="r"?e:null;if(n(e,null,o),r.length===0)return[];let a=t.mergeRuns!==!1,i=[],l=null;for(let u of r){if(!l){l={...u};continue}let d=l.kind===u.kind,m=l.author===u.author,p=l.revisionId===u.revisionId,g=l.carrier===u.carrier,h=a&&l.carrierContainer===u.carrierContainer;d&&m&&p&&(g||h)?l.text+=u.text:(i.push(l),l={...u})}l&&i.push(l);let s=0,c=0,f=[];for(let u of i){let d=u.kind!=="deletion"&&u.kind!=="move_from",m=u.kind!=="insertion"&&u.kind!=="move_to",p=d?s:null,g=m?c:null;d&&(s+=u.text.length),m&&(c+=u.text.length);let h={text:u.text,kind:u.kind,acceptedStart:p,rejectedStart:g};u.author!==void 0&&(h.author=u.author),u.revisionId!==void 0&&(h.revisionId=u.revisionId),f.push(h)}return f}function Y(e,t={}){if(!e)return"";let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=Oa(e,t);return r==="rejected"?n.filter(o=>o.rejectedStart!==null).map(o=>o.text).join(""):n.filter(o=>o.acceptedStart!==null).map(o=>o.text).join("")}var hh="http://schemas.microsoft.com/office/word/2010/wordml";function Bu(e,t,r={}){let{targetParagraphId:n=null}=r,o=it(e,B,"tbl");if(o.length===0)return{hasTableWrapper:!1,isTableCellParagraph:!1,paragraphs:[],paragraph:null,tableElement:null};let i=bt(e).filter(s=>{let c=s.parentNode;for(;c;){if(F(c,"tc"))return!0;c=c.parentNode}return!1});W(`[OxmlEngine] Table wrapper detected: ${o.length} tables, ${i.length} paragraphs in cells`);let l=null;if(n){let s=String(n).toUpperCase();l=i.find(c=>{let f=vh(c);return f&&f.toUpperCase()===s})||null,l?W(`[OxmlEngine] Found target paragraph by paraId: "${n}"`):W(`[OxmlEngine] paraId "${n}" not found in wrapper, falling back to text match`)}if(t&&t.trim()){let s=t.trim();if(!l){for(let c of i)if(Y(c).trim()===s){l=c,W(`[OxmlEngine] Found target paragraph by text match: "${s.substring(0,30)}..."`);break}}}return{hasTableWrapper:!0,isTableCellParagraph:i.length>0,targetParagraph:l,paragraphs:i,paragraph:l||i[0]||null,tableElement:o[0]}}function Lo(e,t,r){let n=Array.isArray(t)?t:[t],o="";for(let a of n){if(!a)continue;let i=r.serializeToString(a);i=i.replace(/\s+xmlns:w="[^"]*"/g,""),i=i.replace(/\s+xmlns:r="[^"]*"/g,""),i=i.replace(/\s+xmlns:wp="[^"]*"/g,""),o+=i}return W(`[OxmlEngine] Stripping table wrapper, serializing ${n.length} paragraphs`),W(`[OxmlEngine] Paragraph XML preview: ${o.substring(0,200)}...`),wh(o)}function wh(e){return ou(e)}function vh(e){if(!e)return null;let t=typeof e.getAttributeNS=="function"?e.getAttributeNS(hh,"paraId"):null;return t||e.getAttribute("w14:paraId")||e.getAttribute("w:paraId")||e.getAttribute("paraId")||null}function xs(e){return F(e,"t")||F(e,"delText")?e.textContent||"":F(e,"br")||F(e,"cr")?`
|
|
153
|
+
`:F(e,"tab")?" ":F(e,"noBreakHyphen")?"\u2011":F(e,"softHyphen")?"\xAD":""}function bs(e){return F(e,"t")||F(e,"delText")||F(e,"br")||F(e,"cr")||F(e,"tab")||F(e,"noBreakHyphen")||F(e,"softHyphen")}function ka(e){let t="",r=[];return e.forEach((n,o)=>{let a=n.parentNode;for(let i=n.firstChild;i;i=i.nextSibling)if(F(i,"r"))t+=Bo(i,n,a,t.length,r).text;else if(F(i,"hyperlink"))for(let l=i.firstChild;l;l=l.nextSibling)F(l,"r")&&(t+=Bo(l,n,a,t.length,r).text);else if(F(i,"ins"))for(let l=i.firstChild;l;l=l.nextSibling)F(l,"r")&&(t+=Bo(l,n,a,t.length,r).text);else if(F(i,"sdt")){let l=Array.from(i.childNodes||[]).find(s=>F(s,"sdtContent"));if(l)for(let s=l.firstChild;s;s=s.nextSibling)F(s,"r")&&(t+=Bo(s,n,a,t.length,r).text)}else if(F(i,"smartTag"))for(let l=i.firstChild;l;l=l.nextSibling)F(l,"r")&&(t+=Bo(l,n,a,t.length,r).text);t=$n(t,o,e.length)}),{fullText:t,textSpans:r}}function Bo(e,t,r,n,o){let a=Ue(e,"w:rPr"),i=n,l=[];for(let s=e.firstChild;s;s=s.nextSibling)if(F(s,"t")){let c=s.textContent||"";if(c.length===0)continue;o.push({charStart:i,charEnd:i+c.length,textElement:s,runElement:e,paragraph:t,container:r,rPr:a}),i+=c.length,l.push(c)}else if(bs(s)){let c=xs(s);o.push({charStart:i,charEnd:i+1,textElement:s,runElement:e,paragraph:t,container:r,rPr:a}),i+=1,l.push(c)}return{text:l.join("")}}function Ma(e){let t=e.slice().sort((o,a)=>o.charStart-a.charStart||o.charEnd-a.charEnd),r=t.map(o=>o.charStart),n=t.map(o=>o.charEnd);return{spans:t,starts:r,ends:n}}function $o(e,t,r,n){if(r<=t||e.spans.length===0)return;let o=Ss(e.ends,t);for(;o<e.spans.length;){let a=e.spans[o];if(a.charStart>=r)break;n(a),o++}}function Is(e,t){if(e.spans.length===0)return null;let r=Ss(e.starts,t)-1;if(r<0)return null;let n=e.spans[r];return t>=n.charStart&&t<n.charEnd?n:null}function Ns(e,t){let r=yh(e.ends,t);return r<e.spans.length&&e.ends[r]===t?e.spans[r]:null}function Ts(e,t){let r=Ss(e.ends,t)-1;return r>=0?e.spans[r]:null}function Ss(e,t){let r=0,n=e.length;for(;r<n;){let o=r+n>>1;e[o]<=t?r=o+1:n=o}return r}function yh(e,t){let r=0,n=e.length;for(;r<n;){let o=r+n>>1;e[o]<t?r=o+1:n=o}return r}function $u(e,t,r=null){if(!e||!e.spans||e.spans.length===0)return{leftSpan:null,rightSpan:null,containingSpan:null,isInterior:!1,fallbackParagraph:r};let n=Is(e,t),o=n!==null&&t>n.charStart&&t<n.charEnd,a=Ns(e,t)||(t>0?Ts(e,t):null),i=e.spans.find(l=>l.charStart===t)||(t===0?e.spans[0]:null);return{leftSpan:a,rightSpan:i,containingSpan:n,isInterior:o,fallbackParagraph:r}}var xh=new Set(["ins","del"]);function Vt(e){let t=[],r=0;for(let n of Array.from(e.childNodes||[])){if(F(n,"rPr")||!bs(n))continue;let o=xs(n);o.length!==0&&(t.push({node:n,start:r,end:r+o.length,text:o}),r+=o.length)}return t}function It(e){return e.length===0?0:e[e.length-1].end}function Pt(e,t,r,n,o){let a=[];return n<=r||t.forEach(i=>{let l=Math.max(r,i.start),s=Math.min(n,i.end);if(s<=l)return;let c=l-i.start,f=s-i.start,u=i.text.slice(c,f);a.push(Th(e,i.node,u,o))}),a}function Fr(e,t,r){let n=$(e,"w:r");return r&&n.appendChild(r.cloneNode(!0)),t.forEach(o=>n.appendChild(o)),n}function rn(e,t,r,n,o){if(n.length===0)return null;let a=Fr(e,n,o);return t.insertBefore(a,r),a}function La(e,t,r,n=null){let o=Nh(t);if(!xh.has(o))throw new TypeError("splitTrackChangeCarrier requires a w:ins or w:del carrier.");if(!Number.isInteger(r)||r<0)throw new RangeError("splitOffset must be a non-negative integer.");let a=Array.from(t.childNodes||[]),i=a.reduce((d,m)=>d+(F(m,"r")?It(Vt(m)):0),0);if(r>i)throw new RangeError(`splitOffset ${r} exceeds carrier text length ${i}.`);if(r===0)return{leftCarrier:null,rightCarrier:t.cloneNode(!0)};if(r===i)return{leftCarrier:t.cloneNode(!0),rightCarrier:null};let l=t.cloneNode(!1),s=t.cloneNode(!1),c=0;for(let d of a){if(!F(d,"r")){(c<=r?l:s).appendChild(d.cloneNode(!0));continue}let m=Vt(d),p=It(m),g=c+p;if(g<=r)l.appendChild(d.cloneNode(!0));else if(c>=r)s.appendChild(d.cloneNode(!0));else{let h=r-c,v=Array.from(d.childNodes||[]).find(T=>F(T,"rPr"))||null,w=o==="del",y=Pt(e,m,0,h,w),x=Pt(e,m,h,p,w);l.appendChild(Fr(e,y,v));let b=Fr(e,x,v);s.appendChild(b)}c=g}let f=bh(e,n);$t(s,f);let u=f.next();return Ih(s,"id",String(u)),f._receiptCollector?.recordRevision(u,o),{leftCarrier:l,rightCarrier:s}}function bh(e,t){return t instanceof De?t:lr(e)||_r(e)}function Ih(e,t,r){typeof e.setAttributeNS=="function"?e.setAttributeNS(B,`w:${t}`,r):e.setAttribute(`w:${t}`,r)}function Nh(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Th(e,t,r,n){if(n&&(F(t,"delText")||F(t,"t"))){let a=$(e,"w:delText");return a.setAttribute("xml:space","preserve"),a.textContent=r,a}if(F(t,"t")){let a=t.cloneNode(!1);return a.textContent=r,/^\s|\s$/.test(r)&&a.setAttribute("xml:space","preserve"),a}if(r===`
|
|
154
|
+
`&&(F(t,"br")||F(t,"cr"))||r===" "&&F(t,"tab")||r==="\u2011"&&F(t,"noBreakHyphen")||r==="\xAD"&&F(t,"softHyphen"))return t.cloneNode(!0);if(n){let a=$(e,"w:delText");return a.setAttribute("xml:space","preserve"),a.textContent=r,a}let o=$(e,"w:t");return o.setAttribute("xml:space","preserve"),o.textContent=r,o}function Uu(e,t,r,n,o,a,i){if(o.length===0)return!1;let l=t.rPr,s=Qt(l),c={...s};if(o.forEach(T=>Object.assign(c,T.format)),!["bold","italic","underline","strikethrough"].some(T=>!!c[T]!==s[T]))return!1;let d=t.runElement.parentNode;if(!d)return!1;let m=t.textElement.textContent||"",p=t.charStart,g=r-p,h=n-p,v=m.substring(0,g),w=m.substring(g,h),y=m.substring(h);if(v.length>0){let T=Br(e,v,l,!1);d.insertBefore(T,t.runElement)}let x=Gn(e,l,c,a,i),b=vs(e,w,x,!1);if(d.insertBefore(b,t.runElement),y.length>0){let T=Br(e,y,l,!1);d.insertBefore(T,t.runElement)}return d.removeChild(t.runElement),!0}function Rs(e,t,r,n,o,a,i=null){let l=[];if($o(t,r,n,m=>{l.push(m)}),l.length===0)return!1;let s=new Map;l.forEach(m=>{m.runElement?.parentNode&&(s.has(m.runElement)||s.set(m.runElement,[]),s.get(m.runElement).push(m))});let c=[];s.forEach((m,p)=>{let g=p.parentNode;if(!g)return;let h=Vt(p);if(h.length===0)return;let v=1/0,w=-1/0;m.forEach(y=>{let x=h.find(A=>A.node===y.textElement);if(!x)return;let b=Math.max(0,r-y.charStart),T=Math.min(y.charEnd-y.charStart,n-y.charStart);T<=b||(v=Math.min(v,x.start+b),w=Math.max(w,x.start+T))}),!(!Number.isFinite(v)||w<=v)&&c.push({runElement:p,parent:g,rPr:m[0].rPr,beforePieces:Pt(e,h,0,v,!1),deletedPieces:Pt(e,h,v,w,!0),afterPieces:Pt(e,h,w,It(h),!1),globalStart:Math.max(r,Math.min(...m.map(y=>y.charStart))),globalEnd:Math.min(n,Math.max(...m.map(y=>y.charEnd))),carrierGlobalStart:F(g,"ins")?Xu(t,g):null})});let f=[];for(let m of c){let p=f[f.length-1],g=p?.[p.length-1];g&&g.parent===m.parent&&Eh(g.runElement)===m.runElement?p.push(m):f.push([m])}let u=!1,d=!1;for(let m of f){let p=m[0],g=null;if(a&&m.some(w=>w.deletedPieces.length>0)){let w=i?d?{...i,id:ue(o,e,"del").id}:i:null;d=!0,g=tr(e,"del",null,o,w)}for(let w of m){let{parent:y,runElement:x}=w;rn(e,y,x,w.beforePieces,w.rPr),g&&w===p&&y.insertBefore(g,x),g&&w.deletedPieces.length>0&&g.appendChild(Fr(e,w.deletedPieces,w.rPr));let b=rn(e,y,x,w.afterPieces,w.rPr);w.globalEnd===n&&!F(y,"ins")&&(t.replacementInsertionAnchors||(t.replacementInsertionAnchors=new Map),t.replacementInsertionAnchors.set(n,{parent:y,referenceNode:b||x.nextSibling,rPr:w.rPr})),y.removeChild(x),u=!0}let h=F(p.parent,"ins")?p.parent:null,v=Math.max(...m.map(w=>w.globalEnd));if(h&&v===n){let w=p.carrierGlobalStart,y=m.filter(b=>b.globalStart<n).reduce((b,T)=>b+T.deletedPieces.reduce((A,E)=>A+(E.textContent||"").length,0),0),x=Math.max(0,n-w-y);t.revisionInsertionAnchors||(t.revisionInsertionAnchors=new Map),t.revisionInsertionAnchors.set(n,{carrier:h,splitOffset:x,rPr:p.rPr})}}return u}function Yn(e,t,r,n,o,a=[],i=0,l=!0,s=null,c=null,f=null,u="merge-same-author"){let d=t.revisionInsertionAnchors?.get(r)||null;if(d&&u==="slice-cross-author"&&Du(d.carrier)&&Es(d.carrier,o))return t.revisionInsertionAnchors.delete(r),As(e,d.carrier,d.splitOffset,n,d.rPr,o,a,i,l,c);let m=t.replacementInsertionAnchors?.get(r)||null;if(m&&!f&&Du(m.parent)&&(!m.referenceNode||m.referenceNode.parentNode===m.parent))return t.replacementInsertionAnchors.delete(r),Dr(e,m.parent,m.referenceNode,n,m.rPr,o,a,i,l,c),!0;if(!f){let b=Is(t,r);if(!b&&r>0&&(b=Ns(t,r)),!b&&r>0&&(b=Ts(t,r)),!b&&t.spans.length>0&&(b=t.spans[t.spans.length-1]),!b)return s?(Dr(e,s,null,n,null,o,a,i,l,c),!0):!1;let T=b.runElement.parentNode;if(!T)return s?(Dr(e,s,null,n,b.rPr,o,a,i,l,c),!0):!1;let A=l&&!(u==="slice-cross-author"&&Ah(T,o));if(l&&u==="slice-cross-author"&&Es(T,o))return As(e,T,Fu(t,T,r),n,b.rPr,o,a,i,l,c);let E=Vt(b.runElement),I=E.find(N=>N.node===b.textElement),R=I?I.start+Math.max(0,Math.min(r-b.charStart,b.charEnd-b.charStart)):r<=b.charStart?0:It(E);if(R>0&&R<It(E)){let N=Pt(e,E,0,R,!1),O=Pt(e,E,R,It(E),!1);return rn(e,T,b.runElement,N,b.rPr),Dr(e,T,b.runElement,n,b.rPr,o,a,i,A,c),rn(e,T,b.runElement,O,b.rPr),T.removeChild(b.runElement),!0}let S=r<=b.charStart?b.runElement:b.runElement.nextSibling;return Dr(e,T,S,n,b.rPr,o,a,i,A,c),!0}let p=$u(t,r,s),g=p.leftSpan&&F(p.leftSpan.runElement?.parentNode,"hyperlink"),h=p.rightSpan&&F(p.rightSpan.runElement?.parentNode,"hyperlink"),v=p.containingSpan&&F(p.containingSpan.runElement?.parentNode,"hyperlink");if(f.hyperlink==="outside"){if(p.isInterior&&v)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion outside hyperlink from strictly interior position."}}}else if(f.hyperlink==="inside"&&!g&&!h&&!v)return{error:{code:"UNSUPPORTED_INSERTION_AFFINITY",message:"Cannot place insertion inside hyperlink when no hyperlink is present at boundary."}};let w=null;if(f.formatting==="none"?w=null:f.formatting==="right"?w=p.rightSpan?.rPr||null:f.formatting==="left"?w=p.leftSpan?.rPr||null:w=(p.containingSpan||p.leftSpan||p.rightSpan)?.rPr||null,p.isInterior){let b=p.containingSpan,T=b.runElement.parentNode||s;if(!T)return!1;let A=Vt(b.runElement),E=A.find(R=>R.node===b.textElement),I=E?E.start+Math.max(0,Math.min(r-b.charStart,b.charEnd-b.charStart)):r<=b.charStart?0:It(A);if(I>0&&I<It(A)){let R=Pt(e,A,0,I,!1),S=Pt(e,A,I,It(A),!1);return rn(e,T,b.runElement,R,b.rPr),Dr(e,T,b.runElement,n,w,o,a,i,l,c),rn(e,T,b.runElement,S,b.rPr),T.removeChild(b.runElement),!0}}let y=null,x=null;if(f.hyperlink==="outside"){if(h){let b=p.rightSpan.runElement.parentNode;y=b.parentNode||s,x=b}else if(g){let b=p.leftSpan.runElement.parentNode;y=b.parentNode||s,x=b.nextSibling}}else f.hyperlink==="inside"&&(h?(y=p.rightSpan.runElement.parentNode,x=p.rightSpan.runElement):g&&(y=p.leftSpan.runElement.parentNode,x=p.leftSpan.runElement.nextSibling));if(y||(p.rightSpan?(y=p.rightSpan.runElement.parentNode||s,x=p.rightSpan.runElement):p.leftSpan?(y=p.leftSpan.runElement.parentNode||s,x=p.leftSpan.runElement.nextSibling):(y=s,x=null)),f.bookmark&&y&&(f.bookmark==="outside"?(x&&F(x.previousSibling,"bookmarkStart")&&(x=x.previousSibling),p.leftSpan&&F(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(x=p.leftSpan.runElement.nextSibling.nextSibling)):f.bookmark==="inside"&&(x&&F(x,"bookmarkStart")&&(x=x.nextSibling),p.leftSpan&&F(p.leftSpan.runElement.nextSibling,"bookmarkEnd")&&(x=p.leftSpan.runElement.nextSibling))),f.comment&&y)if(f.comment==="outside"){if(x&&F(x.previousSibling,"commentRangeStart")&&(x=x.previousSibling),p.leftSpan&&F(p.leftSpan.runElement.nextSibling,"commentRangeEnd")){let b=p.leftSpan.runElement.nextSibling.nextSibling;b&&(F(b,"commentReference")||F(b,"r"))&&Array.from(b.childNodes||[]).some(A=>F(A,"commentReference"))&&(b=b.nextSibling),x=b}}else f.comment==="inside"&&(x&&F(x,"commentRangeStart")&&(x=x.nextSibling),p.leftSpan&&F(p.leftSpan.runElement.nextSibling,"commentRangeEnd")&&(x=p.leftSpan.runElement.nextSibling));if(l&&f.revision==="coalesce_same_author"){let b=null,T=null;if(p.leftSpan&&F(p.leftSpan.runElement.parentNode,"ins")){let A=p.leftSpan.runElement.parentNode;(A.getAttribute("w:author")||A.getAttributeNS(B,"author"))===o&&(b=A,T=p.leftSpan.runElement.nextSibling)}else if(p.rightSpan&&F(p.rightSpan.runElement.parentNode,"ins")){let A=p.rightSpan.runElement.parentNode;(A.getAttribute("w:author")||A.getAttributeNS(B,"author"))===o&&(b=A,T=p.rightSpan.runElement)}if(b){let A=Br(e,n,w,!1);return b.insertBefore(A,T),!0}}return l&&u==="slice-cross-author"&&Es(y,o)?As(e,y,Fu(t,y,r),n,w,o,a,i,l,c):(Dr(e,y,x,n,w,o,a,i,l,c),!0)}function As(e,t,r,n,o,a,i,l,s,c){let f=t.parentNode;if(!f)return!1;let{leftCarrier:u,rightCarrier:d}=La(e,t,r);return u&&f.insertBefore(u,t),Dr(e,f,t,n,Sh(o),a,i,l,s,c),d&&f.insertBefore(d,t),f.removeChild(t),!0}function Sh(e){if(!e)return null;let t=e.cloneNode(!0);return Array.from(t.getElementsByTagName?.("*")||[]).filter(n=>F(n,"rPrChange")).forEach(n=>n.parentNode?.removeChild(n)),t}function Fu(e,t,r){let n=Xu(e,t),o=e.spans.filter(a=>a.runElement?.parentNode===t).reduce((a,i)=>a+(i.charEnd-i.charStart),0);return Math.max(0,Math.min(r-n,o))}function Xu(e,t){let r=e.spans.filter(n=>n.runElement?.parentNode===t);return r.length>0?Math.min(...r.map(n=>n.charStart)):0}function Es(e,t){return F(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(B,"author")||"").trim().toLowerCase()!==String(t||"").trim().toLowerCase():!1}function Ah(e,t){return F(e,"ins")?(e.getAttribute("w:author")||e.getAttributeNS?.(B,"author")||"").trim().toLowerCase()===String(t||"").trim().toLowerCase():!1}function Eh(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function Du(e){return!!e?.parentNode}function Dr(e,t,r,n,o,a,i,l,s,c=null){let f=sr(i,l,l+n.length);if(f.length===0){let d=Br(e,n,o,!1);if(s){let m=tr(e,"ins",d,a,c);t.insertBefore(m,r)}else t.insertBefore(d,r);return}let u=Pa(e,n,o,f,l,a,s);if(s){let d=tr(e,"ins",null,a,c);u.forEach(m=>d.appendChild(m)),t.insertBefore(d,r)}else u.forEach(d=>t.insertBefore(d,r))}function zu(e,t,r,n=!1){let o=[];if($o(e,t,r,m=>o.push(m)),o.length===0)return{safe:!1};let a=o[0].runElement,i=a?.parentNode;if(!i)return{safe:!1};if(!o.every(m=>m.runElement?.parentNode===i))return{safe:!1,structuralBoundary:!0};let s=i.localName||i.nodeName.replace(/^.*:/,"");if(["hyperlink","sdt","del","moveFrom","moveTo"].includes(s)||s==="ins"&&!n)return{safe:!1,structuralBoundary:!0};let c=new Set(["hyperlink","fldSimple","sdt","commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFrom","moveTo","ins","del"]);for(let m of o){let p=m.runElement;for(let g of Array.from(p.childNodes||[]))if(g.nodeType===1){let h=g.localName||g.nodeName.replace(/^.*:/,"");if(c.has(h)||h==="fldChar")return{safe:!1,structuralBoundary:!0}}}let f=o[o.length-1].runElement,u=a;for(;u&&u!==f;){if(u!==a){let m=u.localName||u.nodeName.replace(/^.*:/,"");if(c.has(m))return{safe:!1,structuralBoundary:!0}}u=u.nextSibling}function d(m){if(!m||m.nodeType!==1)return!1;let p=m.localName||m.nodeName.replace(/^.*:/,"");if(c.has(p)||p==="fldChar")return!0;for(let g of Array.from(m.childNodes||[]))if(g.nodeType===1&&d(g))return!0;return!1}return d(a.previousSibling)||d(f.nextSibling)?{safe:!1,structuralBoundary:!0}:{safe:!0}}function Wu(e,t,r,n,o,a,i=!0,l=null,s={},c={}){let f=l?[l]:bt(e),{fullText:u,textSpans:d}=ka(f),m=c.existingRevisions==="slice-cross-author"?qc(u,r):null,p=m||Ph(Co(u,r,s),s),g=Ma(d),h=c.pairReplacements===!0,v=[],w=0,y=0,x=!1,b=m?_h(m):[];if(b.length>1&&a.length===0)for(let E of b.slice().reverse()){let I=ka(f).textSpans,R=Ma(I),S=E.text.replace(/\n/g," ");if(S.length===0)continue;let N=Yn(e,R,E.originalPos,S,o,a,E.newPos,i,f[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(N&&typeof N=="object"&&N.error)return Ce({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:N.error});N===!0&&(x=!0)}else if(a.length===0){let E=Ch(p);for(let I of E.reverse()){let R=Ma(ka(f).textSpans);if(I.type==="insert"){let O=Yn(e,R,I.start,I.text.replace(/\n/g," "),o,a,I.newPos,i,f[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(O&&typeof O=="object"&&O.error)return Ce({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:O.error});O===!0&&(x=!0);continue}let S=null,N=null;if(I.type==="replace"&&h&&i&&I.text.replace(/\n/g," ")){let O=zu(R,I.start,I.end,c?.existingRevisions==="slice-cross-author");if(O.safe){let C=Eo(o,e);S={id:C.deletionId,author:C.author,date:C.date},N={id:C.insertionId,author:C.author,date:C.date}}else O.structuralBoundary&&v.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(Rs(e,R,I.start,I.end,o,i,S)&&(x=!0),I.type==="replace"){let O=Yn(e,R,I.end,I.text.replace(/\n/g," "),o,a,I.newPos,i,f[0]||null,N,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(O&&typeof O=="object"&&O.error)return Ce({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:O.error});O===!0&&(x=!0)}}}else for(let E=0;E<p.length;E++){let[I,R]=p[E];if(I===0){let S=R.length,N=w,O=w+S;$o(g,N,O,C=>{let P=Math.max(C.charStart,N),M=Math.min(C.charEnd,O),_=M-P,k=P-N,L=y+k,D=L+_,X=sr(a,L,D);Uu(e,C,P,M,X,o,i)&&(x=!0)}),w+=S,y+=S}else if(I===-1){let S=E+1<p.length&&p[E+1][0]===1,N=!1,O=null,C=null;if(h&&i&&S&&p[E+1][1].replace(/\n/g," ").length>0){let _=zu(g,w,w+R.length,c?.existingRevisions==="slice-cross-author");if(_.safe){let k=Eo(o,e);O={id:k.deletionId,author:k.author,date:k.date},C={id:k.insertionId,author:k.author,date:k.date},N=!0}else _.structuralBoundary&&v.push("PAIRING_SKIPPED_STRUCTURAL_BOUNDARY")}if(Rs(e,g,w,w+R.length,o,i,O)&&(x=!0),w+=R.length,N){E++;let[,P]=p[E],M=P.replace(/\n/g," ");if(M.length>0){let _=Yn(e,g,w,M,o,a,y,i,f[0]||null,C,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(_&&typeof _=="object"&&_.error)return Ce({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:_.error});_===!0&&(x=!0)}y+=P.length}}else if(I===1){let S=R.replace(/\n/g," ");if(S.length>0){let N=Yn(e,g,w,S,o,a,y,i,f[0]||null,null,c?.insertionAffinity||null,c?.existingRevisions||"merge-same-author");if(N&&typeof N=="object"&&N.error)return Ce({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:N.error});N===!0&&(x=!0)}y+=R.length}}let T=f.map(E=>Y(E)).join(`
|
|
155
|
+
`),A=String(r).replace(/\r\n/g,`
|
|
156
|
+
`);if(c.existingRevisions==="slice-cross-author"&&T!==A){let E=Rh(A,T);return Ce({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:"Generated OOXML accepted-view text does not match the requested modified text; the mutation was rejected.",mismatchOffset:E,expectedExcerpt:ju(A,E),actualExcerpt:ju(T,E),expectedCodePoint:Vu(A,E),actualCodePoint:Vu(T,E)},...v.length>0?{warnings:[...new Set(v)]}:{}})}return Ce({oxml:n.serializeToString(e),hasChanges:x,...v.length>0?{warnings:[...new Set(v)]}:{}})}function Rh(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)if(e[n]!==t[n])return n;return r}function ju(e,t,r=40){let n=Math.max(0,t-r),o=Math.min(e.length,t+r);return e.slice(n,o)}function Vu(e,t){return t>=e.length?"END":`U+${e.codePointAt(t).toString(16).toUpperCase().padStart(4,"0")}`}function Ph(e,t){let r=[];for(let n=0;n<e.length;n++){let[o,a]=e[n],i=e[n+1];if(o===-1&&i?.[0]===1&&a!==i[1]&&a.length===i[1].length&&a.replace(/\u00a0/g," ")===i[1].replace(/\u00a0/g," ")){r.push(...Hc(a,i[1],t)),n++;continue}r.push([o,a])}return r}function Ch(e){let t=[],r=0,n=0;for(let o=0;o<e.length;o++){let[a,i]=e[o];if(a===0){r+=i.length,n+=i.length;continue}if(a===-1){let l=e[o+1];l?.[0]===1?(t.push({type:"replace",start:r,end:r+i.length,newPos:n,text:l[1]}),r+=i.length,n+=l[1].length,o++):(t.push({type:"delete",start:r,end:r+i.length,newPos:n,text:""}),r+=i.length);continue}t.push({type:"insert",start:r,end:r,newPos:n,text:i}),n+=i.length}return t}function _h(e){let t=[],r=0,n=0;for(let[o,a]of e)o===0?(r+=a.length,n+=a.length):o===-1?r+=a.length:o===1&&(t.push({originalPos:r,newPos:n,text:a}),n+=a.length);return t}var Gu=yc(as(),1);var Hu=new Gu.diff_match_patch;function qu(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Oh(e,t){return e?.getAttributeNS?.(B,t)||e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function Ku(e){let t=0;return{at(r){if(t>0&&(!e[t]||r<e[t].start)){let o=0,a=t-1;for(;o<=a;){let i=Math.floor((o+a)/2);e[i].end<=r?o=i+1:a=i-1}t=o}for(;t<e.length&&e[t].end<=r;)t++;let n=e[t];return n&&n.start<=r&&r<n.end?n:null}}}function kh(e){let t=new Map;return e.forEach(r=>{t.has(r.start)||t.set(r.start,[]),t.get(r.start).push(r)}),t}function Yu(e,t,r=null){let n=e.documentElement,o=F(n,"body")||qu(n)==="package",a=r||bt(e),i=st(e,B,"body");!i&&o&&(i=n);let l="",s=[],c=[],f=[],u=new Map,d=new Map,m=new Set,p={nextCharCode:57344},g=new Set;a.forEach((S,N)=>{let O=l.length;Array.from(S.childNodes).forEach(_=>{l=Fh(_,l,s,f,u,d,p,m)}),l=$n(l,N,a.length);let C=l.length,P=st(S,B,"pPr"),M=S.parentNode;M&&g.add(M),c.push({start:O,end:C,pPr:P,paragraph:S,container:M||i})});let h="";for(let S=0;S<l.length;S++){let N=l[S];h+=m.has(N)?`
|
|
157
|
+
`:N}let v=Bh(h,t,f);v=Lh(h,l,v,m),d.forEach((S,N)=>{let O=N.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");v=v.replace(new RegExp(O,"g"),S)}),v=$h(l,v,u);let w=new Map;g.forEach(S=>{w.set(S,e.createDocumentFragment())}),i&&!w.has(i)&&w.set(i,e.createDocumentFragment()),w.has(e)||w.set(e,e.createDocumentFragment());let y=new Map,x=new Set(c.map(S=>S.start)),b=Ku(c),T=Ku(s),A=kh(f);return{paragraphs:a,body:i||e,paragraphMap:c,paragraphStarts:x,propertyMap:s,sentinelMap:f,sentinelMapByStart:A,referenceMap:u,tokenToCharMap:d,containerFragments:w,replacementContainers:y,originalFullText:l,processedModifiedText:v,getParagraphInfo:S=>{let N=b.at(S);return N||(c.length>0?c[c.length-1]:{start:0,end:0,pPr:null,container:i||e})},getRunProperties:S=>{let N=T.at(S);return N?{rPr:N.rPr,wrapper:N.wrapper}:{rPr:null}},getPropertySpanLength:(S,N)=>{let O=T.at(S);return O?Math.min(O.end-S,N):1},isParagraphStart:S=>x.has(S)}}function Ba(e,t){let r=bt(e);if(r.length===0)return[];let n=Ju(t),o=r.map(Mh);if(!n){let i=o.findIndex(l=>l==="");return i>=0?[r[i]]:null}if(r.length===1&&o[0]==="")return r;let a=[i=>i,i=>i.trim(),i=>i.replace(/\s+/g," ").trim()];for(let i of a){let l=i(n);for(let s=0;s<r.length;s++){let c="";for(let f=s;f<r.length;f++)if(c+=(f===s?"":`
|
|
158
|
+
`)+o[f],i(c)===l)return r.slice(s,f+1)}}return null}function Ju(e){return String(e??"").replace(/\r\n?/g,`
|
|
159
|
+
`).replace(/\u00a0/g," ")}function Mh(e){let t="",r=n=>{for(let o of Array.from(n?.childNodes||[]))o.nodeType===1&&(F(o,"pPr")||F(o,"del")||F(o,"moveFrom")||(F(o,"t")?t+=o.textContent||"":F(o,"tab")?t+=" ":F(o,"br")||F(o,"cr")?t+=`
|
|
160
|
+
`:F(o,"noBreakHyphen")?t+="\u2011":r(o)))};return r(e),Ju(t)}function Lh(e,t,r,n){if(n.size===0)return r;let o=Hu.diff_main(e,r),a=0,i="";for(let[l,s]of o)if(l===0){for(let c=0;c<s.length;c++){let f=t[a+c];i+=n.has(f)?f:s[c]}a+=s.length}else l===-1?a+=s.length:i+=s;return i}function Bh(e,t,r){let n=new Map;if(r.forEach(u=>{u.zeroWidth&&n.set(u.start,u)}),n.size===0)return t;let o="",a=0,i=new Map;for(let u=0;u<e.length;u++){let d=n.get(u);if(d){i.has(a)||i.set(a,[]),i.get(a).push({char:e[u],affinity:d.affinity||"right",emitted:!1});continue}o+=e[u],a++}let l=Hu.diff_main(o,t),s=0,c="",f=(u,d)=>{let m=i.get(u)||[];for(let p of m)p.emitted||d&&p.affinity!==d||(c+=p.char,p.emitted=!0)};for(let[u,d]of l){if(u===1){f(s,"left"),c+=d;continue}for(let m=0;m<d.length;m++)f(s),u===0&&(c+=d[m]),s++}return f(s),c}function $h(e,t,r){let n=t;for(let o of r.keys()){if(n.includes(o))continue;let a=e.indexOf(o);if(a<0)continue;let i=e.slice(0,a),l=e.slice(a+o.length);if(i&&n.startsWith(i)){n=`${n.slice(0,i.length)}${o}${n.slice(i.length)}`;continue}if(l&&n.endsWith(l)){let s=n.length-l.length;n=`${n.slice(0,s)}${o}${n.slice(s)}`}}return n}function Fh(e,t,r,n,o,a,i,l){return F(e,"r")?Dh(e,t,r,n,o,a,i,l):F(e,"hyperlink")||F(e,"fldSimple")?Uh(e,t,r):F(e,"sdt")||F(e,"oMath")||qu(e)==="oMath"||F(e,"bookmarkStart")||F(e,"bookmarkEnd")?(n.push({start:t.length,node:e}),t+"\uFFFC"):((F(e,"commentRangeStart")||F(e,"commentRangeEnd"))&&n.push({start:t.length,node:e,isCommentMarker:!0}),t)}function Dh(e,t,r,n,o,a,i,l){let s=t,c=st(e,B,"rPr");return Array.from(e.childNodes).forEach(f=>{if(F(f,"t")){let u=f.textContent||"";u.length>0&&(r.push({start:s.length,end:s.length+u.length,rPr:c}),s+=u)}else if(F(f,"br")||F(f,"cr")){let u=String.fromCharCode(i.nextCharCode++);o.set(u,f),l.add(u),s+=u,r.push({start:s.length-1,end:s.length,rPr:c})}else if(F(f,"tab"))s+=" ",r.push({start:s.length-1,end:s.length,rPr:c});else if(F(f,"noBreakHyphen"))s+="\u2011",r.push({start:s.length-1,end:s.length,rPr:c});else if(["drawing","pict","object","fldChar","instrText","sym"].some(u=>F(f,u))){let u=st(f,B,"txbxContent"),d=F(f,"pict")&&!!u,m=F(f,"fldChar")||F(f,"instrText"),p=F(f,"fldChar")?f.getAttributeNS?.(B,"fldCharType")||f.getAttribute("w:fldCharType")||f.getAttribute("fldCharType"):null;n.push({start:s.length,node:f,wrapInRun:!0,rPr:c,zeroWidth:m,affinity:p==="end"?"left":"right",isTextBox:d,originalContainer:d?u:void 0}),s+="\uFFFC",r.push({start:s.length-1,end:s.length,rPr:c})}else if(F(f,"footnoteReference")||F(f,"endnoteReference")){let u=Oh(f,"id");if(u){let m=`{{__${F(f,"footnoteReference")?"FN":"EN"}_${u}__}}`,p=String.fromCharCode(i.nextCharCode++);o.set(p,f),a.set(m,p),s+=p,r.push({start:s.length-1,end:s.length,rPr:c})}}else F(f,"commentReference")&&n.push({start:s.length,node:f,isCommentMarker:!0})}),s}function Uh(e,t,r){let n=t;return Array.from(e.childNodes).forEach(o=>{if(!F(o,"r"))return;let a=st(o,B,"rPr");it(o,B,"t").forEach(l=>{let s=l.textContent||"";s.length!==0&&(r.push({start:n.length,end:n.length+s.length,rPr:a,wrapper:e}),n+=s)})}),n}var Zu="http://schemas.microsoft.com/office/word/2010/wordml",Xh=["paraId","textId"];function Ps(e,t){let r=Array.from(e.childNodes).find(o=>F(o,"pPr")),n=r&&Array.from(r.childNodes).find(o=>F(o,"rPr"));return!!n&&Array.from(n.childNodes).some(o=>F(o,t))}function zh(e){e.forEach((t,r)=>{let n=t.find(o=>!Ps(o,"ins")&&!Ps(o,"del"))||t.find(o=>!Ps(o,"del"))||t[0];n&&Xh.forEach(o=>{let a=r.getAttributeNS?.(Zu,o)||r.getAttribute?.(`w14:${o}`);a&&n.setAttributeNS(Zu,`w14:${o}`,a)})})}function ef(e,t,r,n,o,a,i=!0,l={}){let{paragraphs:s,containerFragments:c,sentinelMapByStart:f,referenceMap:u,replacementContainers:d,getParagraphInfo:m,getRunProperties:p,getPropertySpanLength:g,isParagraphStart:h}=r,v=new Map,w=(_,k=null)=>{let L=$(e,"w:p");if(k&&(v.has(k)||v.set(k,[]),v.get(k).push(L)),_){let D=_.cloneNode(!0),X=st(D,B,"sectPr");X&&D.removeChild(X),L.appendChild(D)}return L},y=m(0),x=w(y.pPr,y.paragraph),b=c.get(y.container);b&&b.appendChild(x);let T=0,A=0,E=l?.pairReplacements===!0,I=null,R=null,S=new WeakSet;for(let _=0;_<t.length;_++){let[k,L]=t[_];if(k===0||k===-1){let D=k===0?"equal":"delete";if(k===0)I=null,R=null;else if(I===null){I=T;let G=!1;for(let ee=_+1;ee<t.length;ee++){if(t[ee][0]===1){G=!0;break}if(t[ee][0]===0)break}E&&i&&G&&(R=Eo(o,e,{deferReceipt:!0}))}let X=0;for(;X<L.length;){let G=T+X,ee=p(G),J=g(G,L.length-X),Z=L.substring(X,X+J);x=Qu(e,Z,D,ee.rPr,ee.wrapper,G,x,c,f,u,d,m,w,o,a,A,i,S,R).currentParagraph,k===0&&(A+=J),X+=J}T+=L.length;continue}if(k===1){let D=I!==null?I:T>0&&!h(T)?T-1:T,X=p(D);x=Qu(e,L,"insert",X.rPr,X.wrapper,T,x,c,f,u,d,m,w,o,a,A,i,S,R,I!==null).currentParagraph,A+=L.length,I=null,R=null}}for(let _ of Array.from(f.keys()).sort((k,L)=>k-L))for(let k of f.get(_))if(!(!k.isCommentMarker||S.has(k.node)))if(S.add(k.node),F(k.node,"commentReference")){let L=$(e,"w:r");L.appendChild(k.node.cloneNode(!0)),x.appendChild(L)}else x.appendChild(k.node.cloneNode(!0));i&&c.forEach(_=>{Array.from(_.childNodes).forEach(k=>{if(F(k,"p")){let L=Array.from(k.getElementsByTagNameNS(B,"t")).length>0,D=Array.from(k.getElementsByTagNameNS(B,"delText")).length>0;s.length===1&&!L&&(D||r.originalFullText.trim()!=="")&&Qr(k,{author:o,revisionIdAllocator:e})}})}),c.forEach(_=>{let k=Array.from(_.childNodes).filter(L=>F(L,"p"));if(k.length>1){let L=k[0],D=k[k.length-1],X=st(L,B,"pPr"),G=X?st(X,B,"sectPr"):null;if(G){X.removeChild(G);let ee=st(D,B,"pPr");ee||(ee=$(e,"w:pPr"),D.insertBefore(ee,D.firstChild||null)),ee.appendChild(G)}}}),zh(v);let N=new Set(s),O=new Map;s.forEach(_=>{let k=_.parentNode;if(!k||O.has(k))return;let L=_.nextSibling;for(;L&&N.has(L);)L=L.nextSibling;O.set(k,L)}),s.forEach(_=>{_.parentNode&&_.parentNode.removeChild(_)});let C=!1,P="";return c.forEach((_,k)=>{let L=d.get(k),D=L||k;if(D.nodeType===9){C=!0,_.childNodes.length===1?D.appendChild(_.firstChild):P=Array.from(_.childNodes).map(G=>n.serializeToString(G)).join("");return}let X=L?null:O.get(k);X&&X.parentNode===D?D.insertBefore(_,X):D.appendChild(_)}),{oxml:C&&P?P:n.serializeToString(e),hasChanges:!0}}function Qu(e,t,r,n,o,a,i,l,s,c,f,u,d,m,p=[],g=0,h=!0,v=new WeakSet,w=null,y=!1){let x=a,b=g,T=i,A=[];return t.split(/([\n\uFFFC]|[\uE000-\uF8FF])/).forEach(I=>{let R=s.get(x)||[],S=R.filter(C=>C.isCommentMarker&&!v.has(C.node)),N=y?new Set(S.filter(C=>F(C.node,"commentRangeEnd")).map(C=>C.node.getAttributeNS?.(B,"id")||C.node.getAttribute?.("w:id")||C.node.getAttribute?.("id"))):new Set;if(S.forEach(C=>{v.add(C.node);let P=C.node.getAttributeNS?.(B,"id")||C.node.getAttribute?.("w:id")||C.node.getAttribute?.("id");if(y&&N.has(P)&&(F(C.node,"commentRangeEnd")||F(C.node,"commentReference"))){A.push(C.node);return}if(F(C.node,"commentReference")){let M=$(e,"w:r");M.appendChild(C.node.cloneNode(!0)),T.appendChild(M)}else T.appendChild(C.node.cloneNode(!0))}),I===`
|
|
161
|
+
`){let C=u(x+1),P=d(C.pPr,C.paragraph);h&&r==="insert"?Zr(T,{author:m,revisionIdAllocator:e}):h&&r==="delete"&&Qr(T,{author:m,revisionIdAllocator:e});let M=l.get(C.container);M&&(M.appendChild(P),T=P),x++,r!=="delete"&&b++;return}if(I==="\uFFFC"){let C=R.find(P=>!P.isCommentMarker)||R[0];if(C){let P=C.node.cloneNode(!0);if(C.isTextBox&&C.originalContainer){let M=st(P,B,"txbxContent");if(M){for(;M.firstChild;)M.removeChild(M.firstChild);f.set(C.originalContainer,M)}}if(C.wrapInRun){let M=$(e,"w:r");C.rPr&&M.appendChild(C.rPr.cloneNode(!0)),M.appendChild(P),T.appendChild(M)}else T.appendChild(P)}x++,r!=="delete"&&b++;return}if(c.has(I)){if(r==="delete"&&h){let C=c.get(I);if(C){let P=$(e,"w:r");n&&P.appendChild(n.cloneNode(!0)),P.appendChild(C.cloneNode(!0));let M=null;if(w){let _=w.usedDeletionId?ue(m,e,"del").id:w.deletionId;w.usedDeletionId||w.recordUsed?.("del"),w.usedDeletionId=!0,M={id:_,author:w.author,date:w.date}}T.appendChild(tr(e,"del",P,m,M))}}if(r!=="delete"){let C=c.get(I);if(C){let P=C.cloneNode(!0),M=$(e,"w:r");n&&M.appendChild(n.cloneNode(!0)),M.appendChild(P),T.appendChild(M)}}x++,r!=="delete"&&b++;return}if(I.length===0)return;let O=T;if(o){let C=o.cloneNode(!1);O=C,T.appendChild(C)}if(r==="delete"){let C=$(e,"w:r");n&&C.appendChild(n.cloneNode(!0));let P=$(e,"w:delText");if(P.setAttribute("xml:space","preserve"),P.textContent=I,C.appendChild(P),h){let M=null;if(w){let k=w.usedDeletionId?ue(m,e,"del").id:w.deletionId;w.usedDeletionId||w.recordUsed?.("del"),w.usedDeletionId=!0,M={id:k,author:w.author,date:w.date}}let _=tr(e,"del",C,m,M);O.appendChild(_)}}else{let C=sr(p,b,b+I.length),P=Pa(e,I,n,C,b,m,h);if(r==="insert"&&h){let M=null;if(w){let k=w.usedInsertionId?ue(m,e,"ins").id:w.insertionId;w.usedInsertionId||w.recordUsed?.("ins"),w.usedInsertionId=!0,M={id:k,author:w.author,date:w.date}}let _=tr(e,"ins",null,m,M);P.forEach(k=>_.appendChild(k)),O.appendChild(_)}else P.forEach(M=>O.appendChild(M))}r!=="delete"&&(b+=I.length),x+=I.length}),A.forEach(I=>{if(F(I,"commentReference")){let R=$(e,"w:r");R.appendChild(I.cloneNode(!0)),T.appendChild(R)}else T.appendChild(I.cloneNode(!0))}),{currentParagraph:T}}function _s(e,t,r,n,o,a,i=!0,l={},s={}){let c=Ba(e,t);if(c===null)return Ce({oxml:n.serializeToString(e),hasChanges:!1,status:"error",error:{code:"PARTIAL_TARGET",message:"Original text did not identify a complete contiguous paragraph range for reconstruction."}});let f=Yu(e,r,c);if(f.paragraphs.length===0)return Ce({oxml:n.serializeToString(e),hasChanges:!1});let u=Co(f.originalFullText,f.processedModifiedText,{...l,atomicChars:new Set(f.referenceMap.keys())}),d=Kh(jh(u,f.referenceMap),f);return Ce(ef(e,d,f,n,o,a,i,s))}function tf(e,t,r){let n=0;for(;n<e.length;){if(e[n][0]===0){t(e[n]),n++;continue}let o=[];for(;n<e.length&&e[n][0]!==0;)o.push(e[n++]);r(o,o.filter(([a])=>a===-1).map(([,a])=>a).join(""),o.filter(([a])=>a===1).map(([,a])=>a).join(""))}}function Cs(e,t,r){if(t===r){t&&e.push([0,t]);return}t&&e.push([-1,t]),r&&e.push([1,r])}function jh(e,t){if(t.size===0)return e;let r=[];return tf(e,n=>r.push(n),(n,o,a)=>{let i=[...o].filter(f=>t.has(f)&&a.includes(f)),l=[...a].filter(f=>i.includes(f));if(i.length===0||i.join("")!==l.join("")){r.push(...n);return}let s=0,c=0;for(let f of i){let u=o.indexOf(f,s),d=a.indexOf(f,c);Cs(r,o.slice(s,u),a.slice(c,d)),r.push([0,f]),s=u+1,c=d+1}Cs(r,o.slice(s),a.slice(c))}),r}function Vh(e,t){let r=Math.min(e.length,t.length),n=0;for(;n<r&&e[n]===t[n];)n++;return n}function Wh(e,t,r){let n=0;for(;n<r&&e[e.length-1-n]===t[t.length-1-n];)n++;return n}function Kh(e,t){let r=a=>t.getRunProperties(a).wrapper||null,n=[],o=0;return tf(e,a=>{n.push(a),o+=a[1].length},(a,i,l)=>{let s=o,c=s+i.length;o=c;let f=m=>m>s&&m<c&&r(m-1)!==r(m),u=0,d=0;if(i&&l){let m=Wh(i,l,Math.min(i.length,l.length));for(let g=m;g>0;g--)if(f(c-g)){d=g;break}let p=Math.min(Vh(i,l),Math.min(i.length,l.length)-d);for(let g=p;g>0;g--)if(f(s+g)){u=g;break}}if(u===0&&d===0){n.push(...a);return}u>0&&n.push([0,i.slice(0,u)]),Cs(n,i.slice(u,i.length-d),l.slice(u,l.length-d)),d>0&&n.push([0,i.slice(i.length-d)])}),n}function Wt(e,t){return Ce({oxml:e.serializeToString(t),hasChanges:!1})}function rf(e,t,r,n,o,a=!0,i={}){let l=it(e,B,"tbl"),s=xt(t),c=s.rows.length>0||s.headers.length>0;if(l.length===0||!c)return Wt(r,e);let f=l[0],u=os(f),d=gu(u,s);if(d.length===0)return Wt(r,e);let m={generateRedlines:a,author:o,revisionIdAllocator:lr(e),plainTextContent:i.plainTextContent===!0},p=hu(u,d,m),g=`<root xmlns:w="${B}">${p}</root>`,h=V(g,"application/xml").doc;if(!h)return Wt(r,e);let v=$e(h);if(v)return Le("[OxmlEngine] Failed to parse reconciled table OOXML:",v.textContent),Wt(r,e);let w=st(h,B,"tbl");if(!w)return Le("[OxmlEngine] No table found in reconciled OOXML"),Wt(r,e);let y=e.importNode(w,!0);return f.parentNode.replaceChild(y,f),Ce({oxml:r.serializeToString(e),hasChanges:!0})}function nf(e,t,r,n,o,a,i={}){let l=lr(e),s=xt(t);if(!s||s.rows.length===0&&s.headers.length===0)return W("[OxmlEngine] Failed to parse table data from Markdown"),Wt(r,e);let c=mr(s,{generateRedlines:a,author:o,revisionIdAllocator:l,trackAsBlock:!0,plainTextContent:i.plainTextContent===!0}),f=V(`<root xmlns:w="${B}">${c}</root>`,"application/xml").doc;if(!f)return Wt(r,e);let u=$e(f);if(u)return Le("[OxmlEngine] Failed to parse generated table OOXML:",u.textContent),Wt(r,e);let d=Ge(f,B,"tbl");if(d||(d=Ge(f,B,"ins")),!d)return Le("[OxmlEngine] No table element found in generated OOXML"),Wt(r,e);let m=e,p=Ke(m,B,"p");if(p.length===0)return W("[OxmlEngine] No paragraphs found to replace"),Wt(r,m);let g=p[0],h=g.parentNode;if(h&&h.nodeType===9){let w=V(`<w:document xmlns:w="${B}"><w:body/></w:document>`,"application/xml").doc;if(!w)return Wt(r,m);let y=Ge(w,B,"body");p.forEach(x=>y.appendChild(w.importNode(x,!0))),m=w,Cr(m,l),p=Ke(m,B,"p"),g=p[0],h=g.parentNode}let v=m.importNode(d,!0);return a?p.forEach(w=>{Qr(w,{author:o,revisionIdAllocator:m}),Ke(w,B,"r").forEach(x=>{Ke(x,B,"t").forEach(E=>{let I=E.textContent||"";if(I.trim()){let R=$(m,"w:delText");R.textContent=I,E.parentNode.replaceChild(R,E)}});let T=$(m,"w:del"),A=ue(o,m,"del");T.setAttribute("w:id",String(A.id)),T.setAttribute("w:author",A.author),T.setAttribute("w:date",A.date),x.parentNode.insertBefore(T,x),T.appendChild(x)})}):p.slice(1).forEach(w=>w.parentNode.removeChild(w)),h.insertBefore(v,g),a||h.removeChild(g),W("[OxmlEngine] Text-to-table transformation complete"),Ce({oxml:r.serializeToString(m),hasChanges:!0})}function hr(e,t){if(!e||!e.attributes)return"";for(let r of Array.from(e.attributes))if((r.localName||"").toLowerCase()===t.toLowerCase())return String(r.value||"");return String(e.getAttribute?.(`w:${t}`)||e.getAttribute?.(t)||"")}function $a(e){return typeof e=="string"?e.trim().toLowerCase():""}function Gh(e){return!!e&&e.nodeType===1}function _t(e,t){return Gh(e)&&e.namespaceURI===B&&String(e.localName||"").toLowerCase()===t.toLowerCase()}function je(e,t){return Array.from(e.getElementsByTagNameNS(B,t))}function Os(e={}){if(e?.allAuthors===!0)return{valid:!0,allAuthors:!0,normalizedAuthor:""};let t=$a(e?.author);return t?{valid:!0,allAuthors:!1,normalizedAuthor:t}:{valid:!1,allAuthors:!1,normalizedAuthor:"",warning:"No author provided. Pass { author } or set { allAuthors: true }."}}function Ct(e,t){if(t.allAuthors)return!0;let r=$a(hr(e,"author"));return!!r&&r===t.normalizedAuthor}function ks(e,t){let r=typeof e=="string"?e.replace(/^\uFEFF/,"").trim():"",n=!1,o=V(r,"application/xml");if(o.error&&(o.error.message.includes("HierarchyRequestError")||o.error.message.includes("Only one element"))){let i=`<w:body xmlns:w="${B}">${r}</w:body>`,l=V(i,"application/xml");l.error||(o=l,n=!0)}let a=o.doc?$e(o.doc):null;if(o.error||a){let i=o.error?.message||a?.textContent||"parse error";return{xmlDoc:null,serializer:null,isFragmentWrapped:!1,warning:`${t}: ${i}`,warnings:o.warnings,error:{code:"PARSE_ERROR",message:i}}}return{xmlDoc:o.doc,serializer:le(),isFragmentWrapped:n,warning:null,warnings:o.warnings,error:null}}function Fe(e){return e?.parentNode?(e.parentNode.removeChild(e),!0):!1}function Fa(e){let t=e?.parentNode;if(!t)return!1;for(;e.firstChild;)t.insertBefore(e.firstChild,e);return t.removeChild(e),!0}function of(e){let t=e?.nextSibling||null;for(;t&&t.nodeType!==1;)t=t.nextSibling;return t}function af(e){return Array.from(e?.attributes||[]).filter(t=>String(t.localName||t.name||"").toLowerCase()!=="id").map(t=>`${t.namespaceURI||""}|${t.localName||t.name}=${t.value}`).sort().join(`
|
|
162
|
+
`)}function Hh(e){let t=0,r=je(e,"ins");for(let n of r){if(!n.parentNode||Ua(n))continue;let o=of(n);for(;_t(o,"ins")&&$a(hr(o,"author"))===$a(hr(n,"author"))&&af(o)===af(n);){let a=of(o);for(;o.firstChild;)n.appendChild(o.firstChild);o.parentNode?.removeChild(o),t+=1,o=a}}return t}function Da(e){let t=e?.parentNode;return _t(t,"trPr")&&_t(t?.parentNode,"tr")}function Ua(e){let t=e?.parentNode,r=t?.parentNode,n=r?.parentNode;return _t(t,"rPr")&&_t(r,"pPr")&&_t(n,"p")}function cf(e){return Ua(e)?e.parentNode.parentNode.parentNode:null}function qh(e){let t=e?.nextSibling||null;for(;t;){if(_t(t,"p"))return t;t=t.nextSibling}return null}function uf(e,t="accept",r=null){if(!e?.parentNode)return!1;let n=qh(e);if(!n){if(_t(e.parentNode,"tc")){let i=je(e.parentNode,"p").length<=1;if(t==="reject"||i)return i&&r&&r.add(e),!1}return Fe(e)}let o=Array.from(e.childNodes||[]).filter(i=>!_t(i,"pPr")),a=n.firstChild||null;_t(a,"pPr")&&(a=a.nextSibling||null);for(let i of o)n.insertBefore(i,a);return Fe(e)}function nn(e,t={}){let r=[],n=Os(t);if(!n.valid)return{oxml:e,hasChanges:!1,acceptedCount:0,warnings:[n.warning]};let o=ks(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,acceptedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let l=0,s=new Set;for(let u of je(a,"ins"))if(!(!u.parentNode||!Ct(u,n))){if(Ua(u)){Fe(u)&&(l+=1);continue}if(Da(u)){Fe(u)&&(l+=1);continue}Fa(u)&&(l+=1)}for(let u of je(a,"del")){if(!u.parentNode||!Ct(u,n))continue;let d=cf(u);if(d){(uf(d,"accept",s)||Fe(u))&&(l+=1);continue}if(Da(u)){let m=u.parentNode?.parentNode;Fe(m)&&(l+=1);continue}Fe(u)&&(l+=1)}for(let u of je(a,"tbl")){if(!u.parentNode)continue;let d=je(u,"tc");d.length>0&&d.every(p=>{let g=je(p,"p");return g.length===1&&s.has(g[0])&&!Array.from(g[0].childNodes||[]).some(h=>!_t(h,"pPr"))})&&Fe(u)&&(l+=1)}for(let u of je(a,"moveFrom"))!u.parentNode||!Ct(u,n)||Fe(u)&&(l+=1);for(let u of je(a,"moveTo"))!u.parentNode||!Ct(u,n)||Fa(u)&&(l+=1);l+=ff(a,n);let c=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let u of c)for(let d of je(a,u))!d.parentNode||!Ct(d,n)||Fe(d)&&(l+=1);return{oxml:o.isFragmentWrapped?Array.from(a.documentElement.childNodes).map(u=>i.serializeToString(u)).join(""):i.serializeToString(a),hasChanges:l>0,acceptedCount:l,warnings:r}}function sf(e,t){for(let r of Array.from(t.getElementsByTagNameNS(B,"delText"))){let n=$(e,"w:t"),o=r.getAttribute("xml:space");for(o&&n.setAttribute("xml:space",o);r.firstChild;)n.appendChild(r.firstChild);r.parentNode?.replaceChild(n,r)}}function Yh(e,t){let r=e?.parentNode;if(!r)return!1;let n=t.endsWith("Change")?t.slice(0,-6):"";if(!n||String(r.localName||"").toLowerCase()!==n.toLowerCase()||r.namespaceURI!==B)return Fe(e);let o=Array.from(e.childNodes||[]).find(s=>s.nodeType===1&&s.namespaceURI===B&&String(s.localName||"").toLowerCase()===n.toLowerCase());if(!o)return Fe(e);let a=Array.from(o.childNodes||[]),i=n.toLowerCase()==="ppr"?["rpr","sectpr"]:[],l=Array.from(r.childNodes||[]).filter(s=>s.nodeType===1&&s.namespaceURI===B&&i.includes(String(s.localName||"").toLowerCase()));for(;r.firstChild;)r.removeChild(r.firstChild);for(let s of a){let c=Jh(r.ownerDocument,s);r.appendChild(c)}for(let s of l)r.appendChild(s);return!0}function Jh(e,t){return e&&typeof e.importNode=="function"?e.importNode(t,!0):t.cloneNode(!0)}function lf(e,t,r){let n=new Set;for(let o of je(e,t)){if(!Ct(o,r))continue;let a=hr(o,"id");a&&n.add(a)}return n}function ff(e,t){let r=0,n=lf(e,"moveFromRangeStart",t),o=lf(e,"moveToRangeStart",t),a=[["moveFromRangeStart",n,!0],["moveFromRangeEnd",n,!1],["moveToRangeStart",o,!0],["moveToRangeEnd",o,!1]];for(let[i,l,s]of a)for(let c of je(e,i)){if(!c.parentNode)continue;let f=hr(c,"id");f&&(t.allAuthors||l.has(f)||s&&Ct(c,t))&&Fe(c)&&(r+=1)}return r}function Ur(e,t={}){let r=[],n=Os(t);if(!n.valid)return{oxml:e,hasChanges:!1,rejectedCount:0,warnings:[n.warning]};let o=ks(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,rejectedCount:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let l=0;for(let f of je(a,"ins")){if(!f.parentNode||!Ct(f,n))continue;let u=cf(f);if(u){(uf(u,"reject")||Fe(f))&&(l+=1);continue}if(Da(f)){let d=f.parentNode?.parentNode;Fe(d)&&(l+=1);continue}Fe(f)&&(l+=1)}for(let f of je(a,"tbl")){if(!f.parentNode)continue;!Array.from(f.childNodes||[]).some(d=>_t(d,"tr"))&&Fe(f)&&(l+=1)}for(let f of je(a,"del"))if(!(!f.parentNode||!Ct(f,n))){if(Ua(f)){Fe(f)&&(l+=1);continue}if(Da(f)){Fe(f)&&(l+=1);continue}sf(a,f),Fa(f)&&(l+=1)}for(let f of je(a,"moveFrom"))!f.parentNode||!Ct(f,n)||(sf(a,f),Fa(f)&&(l+=1));for(let f of je(a,"moveTo"))!f.parentNode||!Ct(f,n)||Fe(f)&&(l+=1);l+=ff(a,n);let s=["rPrChange","pPrChange","tblPrChange","trPrChange","tcPrChange"];for(let f of s)for(let u of je(a,f))!u.parentNode||!Ct(u,n)||Yh(u,f)&&(l+=1);return Hh(a),{oxml:o.isFragmentWrapped?Array.from(a.documentElement.childNodes).map(f=>i.serializeToString(f)).join(""):i.serializeToString(a),hasChanges:l>0,rejectedCount:l,warnings:r}}function Zh(e,t){let r=new Set,n=je(e,"comment");for(let o of n){if(!Ct(o,t))continue;let a=hr(o,"id");a&&r.add(a)}return{targetIds:r,commentNodes:n}}function Qh(e,t){let r=0;for(let n of e){let o=hr(n,"id");!o||!t.has(o)||Fe(n)&&(r+=1)}return r}function ew(e){return _t(e,"r")?Array.from(e.childNodes||[]).filter(r=>{if(r.nodeType===3)return String(r.nodeValue||"").trim().length>0;if(r.nodeType!==1)return!1;if(r.namespaceURI!==B)return!0;let n=String(r.localName||"").toLowerCase();return n!=="rpr"&&n!=="commentreference"}).length===0:!1}function tw(e,t){let r=0,n=["commentRangeStart","commentRangeEnd","commentReference"];for(let o of n)for(let a of je(e,o)){if(!a.parentNode)continue;let i=hr(a,"id");if(!(!i||!t.has(i))){if(o==="commentReference"&&ew(a.parentNode)){Fe(a.parentNode)&&(r+=1);continue}Fe(a)&&(r+=1)}}return r}function Ms(e,t={}){let r=[],n=Os(t);if(!n.valid)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,warnings:[n.warning]};let o=ks(e,"Failed to parse OOXML");if(!o.xmlDoc)return{oxml:e,hasChanges:!1,commentsRemoved:0,referencesRemoved:0,status:"error",error:o.error,warnings:[...o.warnings||[],o.warning]};let{xmlDoc:a,serializer:i}=o;r.push(...o.warnings||[]);let{targetIds:l,commentNodes:s}=Zh(a,n);if(n.allAuthors)for(let u of["commentRangeStart","commentRangeEnd","commentReference"])for(let d of je(a,u)){let m=hr(d,"id");m&&l.add(m)}let c=Qh(s,l),f=tw(a,l);return{oxml:i.serializeToString(a),hasChanges:c>0||f>0,commentsRemoved:c,referencesRemoved:f,warnings:r}}var rw=Object.freeze({formatOnly:Object.freeze({paragraphs:!0,formatting:!0,tables:"scoped",hyperlinks:"preserved",fields:"preserved",comments:"preserved"}),surgical:Object.freeze({paragraphs:!0,tables:"cell-scoped",hyperlinks:"preserved",fields:"preserved",comments:"preserved",notes:"preserved"}),reconstruction:Object.freeze({paragraphs:!0,hyperlinks:"sentinel-preserved",fields:"sentinel-preserved",comments:"marker-preserved",notes:"reference-preserved"}),table:Object.freeze({tables:!0,paragraphs:!0,formatting:"cell-dependent",numbering:!1}),listDirect:Object.freeze({lists:!0,numbering:!0,paragraphs:"single-source expansion",tables:"embedded-markdown blocks",formatting:"markdown hints"}),listCompatibilityPipeline:Object.freeze({lists:!0,numbering:!0,paragraphs:"multi-source patching",compatibility:!0})});function wr(e,t,r={}){let n=e?._routeInstrumentation?.onRoute;typeof n=="function"&&n(Object.freeze({route:t,capabilities:rw[t]||null,...r}))}var nw=new Set(["pPr","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference","customXmlInsRangeStart","customXmlInsRangeEnd","customXmlDelRangeStart","customXmlDelRangeEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd","permStart","permEnd","proofErr"]);function tt(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function Fo(e){return Array.from(e?.childNodes||[]).filter(t=>t.nodeType===1)}function on(e,t){return Fo(e).find(r=>tt(r)===t)||null}function Xa(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function za(e){return String(e||"").trim().toLowerCase()}function ow(e){return tt(e)!=="r"?!1:Fo(e).every(t=>["rPr","commentReference","bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","proofErr"].includes(tt(t)))}function Ls(e){return nw.has(tt(e))||ow(e)}function Bs(e){return tt(e)==="del"?!0:["customXml","smartTag","sdt","sdtContent"].includes(tt(e))?Fo(e).filter(r=>!Ls(r)&&tt(r)!=="sdtPr").every(Bs):!1}function aw(e){let t=e?.ownerDocument?.documentElement||null;if(!t)return!1;let r=new Set;for(let n of[t,...Array.from(t.getElementsByTagName?.("*")||[])]){if(n===e&&r.size>0)return!0;let o=tt(n),a=Xa(n,"id");o==="moveFromRangeStart"&&a!==""&&r.add(a),o==="moveFromRangeEnd"&&a!==""&&r.delete(a)}return!1}function df(e){let t=on(e,"pPr"),r=on(t,"rPr");return on(r,"del")}function iw(e){for(let t of Array.from(e?.getElementsByTagName?.("*")||[])){let r=tt(t);if(!["t","tab","br","cr","noBreakHyphen","softHyphen"].includes(r))continue;let n=t.parentNode,o=!1;for(;n&&n!==e;){let a=tt(n);if(a==="del"||a==="moveFrom"){o=!0;break}n=n.parentNode}if(!o&&(r!=="t"||(t.textContent||"").length>0))return!0}return!1}function Xr(e,t){let r=df(e);if(!r)return{matches:!1,hasParagraphMarkDeletion:!1,foreignParagraphMarkDeletion:!1,allContentDeleted:!1,ownerAuthor:null,markDeletion:null};let n=Xa(r,"author")||null,o=!n||za(n)!==za(t),i=Fo(e).filter(l=>!Ls(l)).every(Bs);return{matches:o&&i,hasParagraphMarkDeletion:!0,foreignParagraphMarkDeletion:o,allContentDeleted:i,ownerAuthor:n,markDeletion:r}}function an(e,t={}){let r=on(e,"pPr");if(on(r,"sectPr"))return{code:"SECTION_BREAK_PARAGRAPH",message:"Refusing to restore a deleted paragraph whose paragraph properties contain a section break."};let n=e?.parentNode||null;for(;n;){if(tt(n)==="moveFrom")return{code:"UNSUPPORTED_MOVE_REVISION",message:"Refusing to restore a paragraph that is part of a pending move-from revision."};n=n.parentNode}if(aw(e)||e?.getElementsByTagName?.("*")&&Array.from(e.getElementsByTagName("*")).some(i=>["moveFrom","moveFromRangeStart","moveFromRangeEnd"].includes(tt(i))))return{code:"UNSUPPORTED_MOVE_REVISION",message:"Refusing to restore a paragraph that is part of a pending move-from revision."};let o=e?.parentNode||null;for(;o&&tt(o)!=="tr";)o=o.parentNode;let a=on(o,"trPr");if(a&&on(a,"del"))return{code:"UNSAFE_DELETED_TABLE_ROW",message:"Refusing to restore a paragraph inside a table row with a pending row deletion."};if(t.requireFollowingParagraph!==!1){let i=e?.nextSibling||null;for(;i&&(i.nodeType!==1||tt(i)!=="p");)i=i.nextSibling;if(!i)return{code:"UNSAFE_PARAGRAPH_PLACEMENT",message:"Refusing to restore a deleted paragraph without a following paragraph in the same structural container."}}return null}function mf(e){let t=tt(e)==="p"?[e]:Array.from(e?.getElementsByTagName?.("*")||[]).filter(n=>tt(n)==="p"),r=[];for(let n of t){let o=df(n);if(!o)continue;let a=Xa(o,"author")||null,i=Fo(n).filter(c=>!Ls(c)),l=i.filter(c=>tt(c)!=="ins"||!iw(c)?!1:za(Xa(c,"author"))!==za(a)),s=i.every(c=>Bs(c)||l.includes(c));l.length>0&&s&&r.push({paragraph:n,markDeletion:o,ownerAuthor:a,foreignInsertions:l})}return r}function sw(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of it(e,B,r)){let o=n.getAttribute?.("w:id")||n.getAttribute?.("id");o!==""&&t.add(o)}return[...t].sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function Va(e,t){return Array.from(e?.childNodes||[]).find(r=>r?.nodeType===1&&r.namespaceURI===B&&r.localName===t)||null}function lw(e,t){let r=Va(Va(Va(e,"pPr"),"rPr"),"ins");if(!r)return null;let n=r.getAttribute("w:author")||r.getAttributeNS(B,"author")||"";return n.trim().toLowerCase()!==String(t||"").trim().toLowerCase()?null:{id:r.getAttribute("w:id")||r.getAttributeNS(B,"id")||"",author:n,date:r.getAttribute("w:date")||r.getAttributeNS(B,"date")||""}}function cw(e,t){let r=e.cloneNode(!1),n=Va(e,"pPr");return n&&r.appendChild(pt(n)),t.serializeToString(r)}function uw(e,t){if(!t||typeof e!="string"||!e.trim())return e;let r=V(e,"text/xml");if(!r.doc||r.error)return e;let n=r.doc.documentElement?.localName==="p"?r.doc.documentElement:bt(r.doc)[0];return n?(mu(n,t),Be(r.doc)):e}async function Do(e,t,r,n={}){let o=e,a=e;t=typeof t=="string"?t:String(t??""),r=typeof r=="string"?r:String(r??"");let i=n.generateRedlines??!0,l=n.author||ae(),s=le(),c=[],f=[],u=!1,d=null,m=n.existingRevisions||"merge-same-author",p=m==="accept-all-first-keep-normalized",g=K=>{let j={...K};u&&j.hasChanges===!1&&j.status!=="error"&&(m==="merge-same-author"||m==="slice-cross-author"?(j.oxml=a,j.hasChanges=!0,j.warnings=[...Array.isArray(j.warnings)?j.warnings:[],"Previous revisions by the same author were reverted to baseline."]):p?(j.oxml=a,j.hasChanges=!0,j.warnings=[...Array.isArray(j.warnings)?j.warnings:[],"Existing revisions were accepted before redlining."]):j.oxml=o);let ye=[...c,...f,...Array.isArray(j.warnings)?j.warnings:[]];return ye.length>0&&(j.warnings=[...new Set(ye)]),j.status||(j.status=j.hasChanges?"ok":"no-op"),d&&j.hasChanges&&typeof j.oxml=="string"&&(j.oxml=uw(j.oxml,d)),Ce(j)},h=()=>g(u&&p?{oxml:a,hasChanges:!0,warnings:["Existing revisions were accepted before redlining."]}:{oxml:o,hasChanges:!1}),v=V(o,"text/xml");c=v.warnings;let w=v.doc;m==="auto"&&(m=Lr("auto",w,l),n={...n,existingRevisions:m});let y=w?$e(w):null;if(v.error||y){let K=v.error?.message||y?.textContent||"Could not parse OOXML input.";return Le("[OxmlEngine] XML parse error:",K),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:K}})}let x=n?._revisionIdAllocator instanceof De?n._revisionIdAllocator:new De;cr(w,x);let b=w.documentElement&&String(w.documentElement.localName||"").toLowerCase()==="p"?[w.documentElement]:bt(w);if(b.length===1&&r.length>0){let K=Xr(b[0],l);if(K.matches){let j=K.ownerAuthor||"unattributed";return g({oxml:o,hasChanges:!1,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${j}). Use explicit paragraph restoration when supported.`,ownerAuthor:j}})}}if(fr(w))if(m==="merge-same-author"||m==="slice-cross-author"){let K=Mr(w),j=String(l||"").trim().toLowerCase();if(K.length>0&&!dr(w)&&K.every(Pe=>Pe.trim().toLowerCase()===j)){let Pe=sw(w);if(Pe.length>0)return g({oxml:o,hasChanges:!1,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:Pe}});W("[OxmlEngine] Existing revisions from same author detected; rejecting previous changes to merge against baseline");let z=b.length===1?b[0]:null;d=lw(z,l);let Q=Ur(o,{author:l});if(Q.status==="error")return g(Q);a=d&&!String(Q.oxml||"").trim()?cw(z,s):Q.oxml,u=!0;let Te=V(a,"text/xml");c.push(...Te.warnings),w=Te.doc;let Se=w?$e(w):null;if(Te.error||Se){let Ye=Te.error?.message||Se?.textContent||"Could not parse OOXML after rejecting same-author revisions.";return Le("[OxmlEngine] XML parse error after rejecting same-author revisions:",Ye),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:Ye}})}if(fr(w))return g({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Existing same-author revisions could not be completely restored to baseline; refusing to layer new revisions over unsupported revision markup."}});cr(w,x);let Ae=w.documentElement&&String(w.documentElement.localName||"").toLowerCase()==="p"?[w.documentElement]:bt(w);t=Ae.length>0?Ae.map(Ye=>Y(Ye)).join(`
|
|
163
|
+
`):""}else{if(m==="merge-same-author")return W("[OxmlEngine] Existing revisions detected from another/unattributed author; refusing per merge-same-author policy"),g({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:`Input OOXML contains tracked changes from another author (${K.length?K.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:K,currentPolicy:m}});if(["moveFrom","moveTo"].some(z=>it(w,B,z).length>0))return g({oxml:o,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}});W("[OxmlEngine] Existing revisions retained for cross-author surgical slicing")}}else if(m==="accept-all-first"||m==="accept-all-first-keep-normalized"){W("[OxmlEngine] Existing revisions detected; accepting all input revisions before redlining");let K=nn(o,{allAuthors:!0});if(K.status==="error")return g(K);a=K.oxml,u=!0;let j=V(a,"text/xml");c.push(...j.warnings),w=j.doc;let ye=w?$e(w):null;if(j.error||ye){let Pe=j.error?.message||ye?.textContent||"Could not parse OOXML after accepting existing revisions.";return Le("[OxmlEngine] XML parse error after accepting existing revisions:",Pe),g({oxml:o,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:Pe}})}cr(w,x)}else return W("[OxmlEngine] Existing revisions detected; rejecting input per existingRevisions policy"),g({oxml:o,hasChanges:!1,status:"error",error:{code:"EXISTING_REVISIONS",message:'Input OOXML contains existing tracked changes and existingRevisions is "reject-input".'}});let T=Bu(w,t,n);if(T.hasTableWrapper&&T.targetParagraph&&!n._isolatedTableCell){W("[OxmlEngine] Isolating table-cell paragraph before diff");let K=Lo(w,T.targetParagraph,s),j=await Do(K,t,r,{...n,_isolatedTableCell:!0});return!j.hasChanges&&j.status==="no-op"?h():j}let A=n.sanitizeInput===!0?$s(r):r;A!==r&&f.push("Input was sanitized; pass sanitizeInput: false to disable.");let E=null;if(n.structuredContent!==!1&&n.literalTextEdit!==!0)if(E=Ea(A),E.valid)E.requiresStructuredContent&&(A=E.normalizedMarkdown);else{if(n.explicitStructuredContent===!0){let K=E.issues.map(j=>`${j.code}: ${j.message}`).join(" ");return g({oxml:o,hasChanges:!1,status:"error",error:{code:"STRUCTURED_CONTENT_INVALID",message:K},warnings:E.issues.map(j=>j.message)})}E=null}let{cleanText:I,formatHints:R}=n.plainTextContent===!0?{cleanText:A,formatHints:[]}:yt(A),{existingFormatHints:S,textSpans:N,paragraphs:O}=Ru(w),C=m==="slice-cross-author"?I!==t:I.trim()!==t.trim(),P=!C&&n.explicitStructuredContent===!0&&Mn(I)&&!fw(O,I),M=C||P,_=R.length>0,k=S.length>0,{textSpans:L}=Ra(O),D=L.map(K=>pf(K)).join(""),X=t.includes(`
|
|
164
|
+
`)||t.includes("\r")?t.split(/\r?\n/).map(ja).filter(Boolean).every(K=>O.some(j=>{let ye=L.filter(Pe=>Pe.paragraph===j).map(pf).join("");return ja(ye).includes(K)})):D.includes(t.trim())||D.replace(/[\t\n\u2011]/g,"").includes(t.trim().replace(/[\t\n\u2011]/g,""))||ja(D).includes(ja(t));if(M&&typeof t=="string"&&t.trim()&&!X)return W("[OxmlEngine] Target text not found in OOXML"),g({oxml:o,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:"Original text was not found in the supplied OOXML."}});let G=null,ee=()=>(G||(G=Ca(w,O,N)),G),J=(K=null)=>{let j=Lu(w,t,R,s,l,i,K);return j.useNativeApi?(W("[OxmlEngine] Format-only surgical fallback signal encountered; retrying with OOXML reconstruction fallback"),_s(w,t,I,s,l,R,i)):j};W(`[OxmlEngine] Text changes: ${M}, New format hints: ${R.length}, Existing format hints: ${S.length}`);let Z=n.removeFormatting===!0&&!M&&!_&&k;if(!M&&!_&&!k)return wr(n,"noChange"),W("[OxmlEngine] No text changes, no format hints, and no existing formatting detected"),h();if(!M&&!_&&k&&!Z)return W("[OxmlEngine] No text or explicit formatting changes; preserving existing formatting"),h();if(Z){wr(n,"formatOnly",{removeFormatting:!0}),W("[OxmlEngine] Format REMOVAL detected: applying surgical replacement in OOXML");let K=T,j=K.targetParagraph||null;if(!j){let z=Cu(ee(),t);z&&(j=z.paragraph)}let ye=S;j&&(ye=S.filter(z=>Ou(z.run)===j));let Pe=Mu(w,N,ye,s,l,i);return K.hasTableWrapper&&j?g({oxml:Lo(w,j,s),hasChanges:Pe.hasChanges}):g(Pe)}if(!M&&_){wr(n,"formatOnly",{removeFormatting:!1}),W(`[OxmlEngine] Format-only change detected: ${R.length} format hints`);let K=T,j={textSpans:N,paragraphs:O,paragraphInfos:ee()};if(K.hasTableWrapper&&K.targetParagraph){W("[OxmlEngine] Table cell context: applying formatting to target paragraph only");let ye=J(j);return W("[OxmlEngine] Stripping table wrapper for table cell paragraph (format-only)"),g({oxml:Lo(w,K.targetParagraph,s),hasChanges:ye.hasChanges})}return g(J(j))}let ne=it(w,B,"tbl").length>0,re=/^\|.+\|/.test(I.trim())&&I.includes(`
|
|
165
|
+
`),We=n.literalTextEdit!==!0&&Mn(I),ge=n.structuredContent!==!1&&E?.requiresStructuredContent===!0,he=T,Me=ne||m==="slice-cross-author";W(`[OxmlEngine] Mode: ${Me?"SURGICAL":"RECONSTRUCTION"}, formatHints: ${R.length}, isMarkdownTable: ${re}, isTargetList: ${We}, isTableCellParagraph: ${he.isTableCellParagraph}`);try{if(re&&!ne)return wr(n,"table",{transformation:"text-to-table"}),W("[OxmlEngine] Text-to-table transformation: generating new table from Markdown"),g(nf(w,I,s,null,l,i,{plainTextContent:n.plainTextContent===!0}));if(ne&&re)return wr(n,"table",{transformation:"table-reconciliation"}),g(rf(w,I,s,null,l,i,{plainTextContent:n.plainTextContent===!0}));if(Me){wr(n,"surgical",{tableScoped:ne});let K=he.hasTableWrapper&&he.targetParagraph?he.targetParagraph:null;K&&W("[OxmlEngine] Table cell edit: scoping surgical mode to target paragraph");let j=Wu(w,t,I,s,l,R,i,K,{},n);return j.status==="error"&&j.error?.code==="PATCH_ROUNDTRIP_MISMATCH"?g({...j,oxml:o,hasChanges:!1}):he.hasTableWrapper&&j.hasChanges&&he.targetParagraph?(W("[OxmlEngine] Stripping table wrapper for table cell paragraph (surgical mode)"),g({oxml:Lo(w,he.targetParagraph,s),hasChanges:!0})):g(j)}if(We||ge){let K=it(w,B,"p"),j=K.length===1;wr(n,j?"listDirect":"listCompatibilityPipeline",{sourceParagraphCount:K.length}),W(`[OxmlEngine] \u{1F3AF} Using ${j?"direct list generation":"compatibility pipeline"} for list reconciliation`);let ye;if(j){let Pe=Dn(a,{xmlDoc:w}),z=Po(K[0]);ye=await Wn({cleanText:I,numberingContext:z,originalRunModel:Pe.runModel,originalText:Pe.acceptedText,generateRedlines:i,author:l,font:n.font||null,revisionIdAllocator:x,numberingService:new ur})}else ye=await new Oo({author:l,generateRedlines:i,revisionIdAllocator:x}).execute(a,A,{xmlDoc:w});if(ye.error?.code==="DIFF_TOKEN_LIMIT")return g({oxml:o,hasChanges:!1,status:"error",error:ye.error});if(ye.isValid&&ye.ooxml&&ye.ooxml!==a){let Pe=ye.includeNumbering===!0;W(`[OxmlEngine] Wrapping list OOXML with numbering definitions, includeNumbering=${Pe}`);let z=kr(ye.ooxml,{includeNumbering:Pe,numberingXml:ye.numberingXml});return W(`[OxmlEngine] \u2705 Wrapped OOXML length: ${z.length}`),g({oxml:z,hasChanges:!0,...Array.isArray(ye.warnings)?{warnings:ye.warnings}:{}})}return h()}return wr(n,"reconstruction"),g(_s(w,t,I,s,l,R,i,{},n))}catch(K){if(Kc(K))return g({oxml:o,hasChanges:!1,status:"error",error:{code:K.code,message:K.message}});throw K}}function fw(e,t){let r=String(t).split(/\r?\n/).filter(n=>n.trim()).length;return e.length===r&&e.every(n=>at(n).numPr!=null)}function ja(e){return String(e||"").replace(/[\t\n\u2011]/g," ").replace(/\s+/g," ").trim()}function pf(e){let t=e?.textElement,r=String(t?.localName||t?.nodeName||"").replace(/^.*:/,"");return r==="tab"?" ":r==="br"||r==="cr"?`
|
|
166
|
+
`:r==="noBreakHyphen"?"\u2011":t?.textContent||""}function $s(e){return String(e??"").replace(/^(?:Here is the redline:|Here is the text:|Sure, I can help:|Here's the updated text:)[ \t]*\r?\n/i,"")}function Ve(e){return V(e,"application/xml").doc}function Kt(e){return Be(e)}function Wa(e){return Array.from(e||[])}function Uo(e){let t=new Error(e);return t.code="TARGET_NOT_FOUND",t}function gt(e,t,r=null){let n=new Error(t);return n.code=e,Array.isArray(r)&&(n.candidates=r),n}var fe="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function gf(e,t){if(!e)return[];if(typeof e.getElementsByTagNameNS=="function"){let n=Wa(e.getElementsByTagNameNS("*",t));if(n.length>0)return n}if(typeof e.getElementsByTagName!="function")return[];let r=Wa(e.getElementsByTagName(`w:${t}`));return r.length>0?r:Wa(e.getElementsByTagName(t))}function _e(e){return e?Y(e):""}function se(e){if(!e)return[];let t=gf(e,"body"),r=t.length>0?t[0]:e;return gf(r,"p")}function He(e){return e&&Wa(e.attributes).find(r=>String(r?.localName||r?.name||"").replace(/^.*:/,"")==="paraId")?.value||null}function Ot(e,t={}){if(!e)return null;let r=t.revisionView==="rejected"?"rejected":"accepted",n=typeof t.text=="string"?t.text:Y(e,{revisionView:r}),o=Number.isInteger(t.index)?t.index:se(e.ownerDocument||e).indexOf(e)+1,a=t.paragraphId===void 0?He(e):t.paragraphId,i=typeof t.inTable=="boolean"?t.inTable:Xo(e),s=`${a||""}${o}${i?"table":"body"}${r==="rejected"?"rejected":""}${n}`,c=2166136261;for(let f=0;f<s.length;f++)c^=s.charCodeAt(f),c=Math.imul(c,16777619)>>>0;return`fnv1a32:${c.toString(16).padStart(8,"0")}`}function rr(e,t={}){let r=t.revisionView==="rejected"?"rejected":"accepted",n=se(e),o=[],a=new Map,i=new Map,l=new Map;for(let s=0;s<n.length;s++){let c=n[s],f=Y(c,{revisionView:r}),u=He(c),d=Xo(c),m=q(f),p=Object.freeze({paragraph:c,index:s+1,paragraphId:u,text:f,normalizedText:m,revisionView:r,fingerprint:Ot(c,{text:f,index:s+1,paragraphId:u,inTable:d,revisionView:r}),inTable:d});o.push(p),a.set(c,p),u&&!i.has(u)&&i.set(u,p),m&&(l.has(m)||l.set(m,[]),l.get(m).push(p))}for(let[s,c]of l)l.set(s,Object.freeze(c));return Object.freeze({revisionView:r,entries:Object.freeze(o),byParagraph:a,byId:i,byNormalizedText:l})}function q(e){return String(e||"").replace(/\s+/g," ").trim()}function sn(e){let t=String(e||"").trim();return/^\|.+\|/.test(t)&&t.includes(`
|
|
167
|
+
`)}function Ds(e){if(e==null)return null;if(typeof e=="number"&&Number.isInteger(e)&&e>0)return e;let t=String(e).trim();if(!t)return null;let r=t.match(/^\[?P(\d+)(?:\.\d+)?\]?$/i);if(r)return Number.parseInt(r[1],10);let n=t.match(/^(\d+)$/);return n?Number.parseInt(n[1],10):null}function dw(e){return e==null?"":String(e).replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim()}function mw(e){let t=String(e||""),r=t.match(/^\s*\[P(\d+)(?:\.\d+)?\]\s*/i);return r?{text:t.replace(/^\s*\[P\d+(?:\.\d+)?\]\s*/i,"").trim(),targetRef:Number.parseInt(r[1],10)}:{text:t.trim(),targetRef:null}}function hf(e,t,r=null){return!Number.isInteger(t)||t<1?null:r?.entries?r.entries[t-1]?.paragraph||null:se(e)[t-1]||null}function ct(e,t,r=fe){let n=e;for(;n;){if(n.nodeType===1&&n.namespaceURI===r&&n.localName===t)return n;n=n.parentNode}return null}function Ka(e,t,r={}){let n=r.paragraphMetadataIndex||null,o=n?.entries||null,a=o?null:se(e),i=String(t||"").trim();if(!i)return null;let l=o?o.find(c=>c.text.trim()===i)?.paragraph:a.find(c=>_e(c).trim()===i);if(l)return l;let s=q(i);return n?.byNormalizedText?n.byNormalizedText.get(s)?.[0]?.paragraph||null:a.find(c=>q(_e(c))===s)||null}function Fs(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=r.paragraphMetadataIndex||null,a=o?.entries||null,i=a?null:se(e),l=String(t||"").trim();if(!l)return null;let s=Ka(e,l,{paragraphMetadataIndex:o});if(s)return s;let c=q(l),f=a?a.find(h=>h.normalizedText.length>10&&c.startsWith(h.normalizedText))?.paragraph||null:i.find(h=>{let v=q(_e(h));return v.length>10&&c.startsWith(v)});if(f)return n(`[Fuzzy] Prefix match (target starts with paragraph): "${_e(f).trim().slice(0,60)}..."`),f;let u=a?a.find(h=>h.normalizedText.length>15&&c.includes(h.normalizedText))?.paragraph||null:i.find(h=>{let v=q(_e(h));return v.length>15&&c.includes(v)});if(u)return n(`[Fuzzy] Contains match: "${_e(u).trim().slice(0,60)}..."`),u;let d=0,m=null,p=new Set(c.toLowerCase().split(/\s+/).filter(h=>h.length>2)),g=a?.length??i.length;for(let h=0;h<g;h++){let v=a?.[h]?.paragraph??i[h],w=(a?.[h]?.text??_e(v)).trim();if(!w)continue;let b=q(w).toLowerCase().split(/\s+/).filter(T=>T.length>2).filter(T=>p.has(T)).length/Math.max(p.size,1);b>d&&b>.5&&(d=b,m=v)}return m?(n(`[Fuzzy] Best word-overlap match (${(d*100).toFixed(0)}%): "${_e(m).trim().slice(0,60)}..."`),m):null}function ln(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=typeof t.onWarn=="function"?t.onWarn:()=>{},o=t.opType||"operation",a=t.targetDescriptor&&typeof t.targetDescriptor=="object"?t.targetDescriptor:null,i=a?.revisionView==="rejected"?"rejected":"accepted",l=String(a?.exactText??a?.text??t.targetText??"").trim(),s=Ds(a?.index??a?.paragraphIndex??t.targetRef),c=t.strictAmbiguity===!0,f=t.paragraphMetadataIndex||null;if(f&&f.revisionView!==i?f=t.metadataIndices?.[i]||rr(e,{revisionView:i}):f||(f=rr(e,{revisionView:i})),a?.paragraphId){let d=gw(e,a.paragraphId,f);if(!d)throw gt("TARGET_NOT_FOUND",`Target paragraphId not found: "${a.paragraphId}".`);let m=f?.byParagraph?.get(d)||null,p=m?.index??se(e).indexOf(d)+1,g=m?.fingerprint||Ot(d,{revisionView:i}),h=m?.inTable??Xo(d),v=m?.normalizedText||q(Y(d,{revisionView:i}));if(s!=null&&s!==p)throw gt("TARGET_INDEX_MISMATCH",`Target paragraphId "${a.paragraphId}" (index ${p}) does not match requested index ${s}.`,m?[Gt(m)]:null);if(a.fingerprint&&a.fingerprint!==g){let w=i==="rejected"?"accepted":"rejected",y=Ot(d,{revisionView:w}),x=a.fingerprint===y?` The supplied fingerprint matches the ${w} view; set target.revisionView to "${w}" or use a fingerprint extracted from the ${i} view.`:"";throw gt("TARGET_FINGERPRINT_MISMATCH",`Target paragraphId "${a.paragraphId}" no longer matches its source fingerprint.${x}`,m?[Gt(m)]:null)}if(typeof a.inTable=="boolean"&&a.inTable!==h)throw gt("TARGET_CONTEXT_MISMATCH",`Target paragraphId "${a.paragraphId}" does not match the requested table context.`,m?[Gt(m)]:null);if(l&&v!==q(l)){let w=i==="rejected"?"accepted":"rejected",x=q(Y(d,{revisionView:w}))===q(l)?` The supplied text matches the ${w} view; set target.revisionView to "${w}".`:"";throw gt("TARGET_TEXT_MISMATCH",`Target paragraphId "${a.paragraphId}" no longer matches the supplied text.${x}`,m?[Gt(m)]:null)}if(a.occurrence!=null){let y=Ga(e,l||v,f),x=y.findIndex(b=>b.paragraph===d)+1;if(x===0||x!==a.occurrence)throw gt("TARGET_OCCURRENCE_MISMATCH",`Target paragraphId "${a.paragraphId}" matches occurrence ${x}, not requested occurrence ${a.occurrence}.`,y.map(Gt))}return{paragraph:d,resolvedBy:"paragraph_id"}}if(a?.fingerprint&&!l&&!s){let d=(f?.entries||[]).filter(m=>m.fingerprint===a.fingerprint);if(typeof a.inTable=="boolean"&&(d=d.filter(m=>m.inTable===a.inTable)),d.length===1)return{paragraph:d[0].paragraph,resolvedBy:"fingerprint"};throw d.length>1?gt("AMBIGUOUS_TARGET","Target fingerprint matched multiple paragraphs; provide paragraphId or index.",d.map(Gt)):gt("TARGET_NOT_FOUND",`Target fingerprint not found: "${a.fingerprint}".`)}let u=[];if(l){let d=Ga(e,l,f);if(u=pw(d,a),a?.fingerprint&&d.length>0&&u.length===0)throw gt("TARGET_FINGERPRINT_MISMATCH","Target text matched, but no paragraph matched the supplied source fingerprint.",d.map(Gt));if(typeof a?.inTable=="boolean"&&d.length>0&&u.length===0)throw gt("TARGET_CONTEXT_MISMATCH","Target text matched, but no paragraph matched the requested table context.",d.map(Gt));if(a?.occurrence){let m=u[a.occurrence-1]||null;if(!m)throw gt("TARGET_NOT_FOUND",`Target occurrence ${a.occurrence} was not found.`,u.map(Gt));return{paragraph:m.paragraph,resolvedBy:"occurrence"}}if(c){if(s){let m=u.find(p=>p.index===s)||null;if(m)return{paragraph:m.paragraph,resolvedBy:"ref"};if(a?.fingerprint&&u.length>0)throw gt("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${s}].`,u.map(Gt));if(u.length===1)return{paragraph:u[0].paragraph,resolvedBy:"strict_text_after_ref_drift"}}if(u.length>1)throw gt("AMBIGUOUS_TARGET",`Target text matched ${u.length} paragraphs; provide paragraphId, index, occurrence, or fingerprint.`,u.map(Gt));if(u.length===0)throw Uo(`Target paragraph not found: "${l}"`)}if(!s&&u.length===1)return{paragraph:u[0].paragraph,resolvedBy:a?.fingerprint?"fingerprint":"strict_text"}}if(s){let d=hf(e,s,f);if(d){let m=f?.byParagraph?.get(d)||null;if(a?.fingerprint&&a.fingerprint!==m?.fingerprint)throw gt("TARGET_FINGERPRINT_MISMATCH",`Target fingerprint does not match paragraph reference [P${s}].`);if(typeof a?.inTable=="boolean"&&a.inTable!==m?.inTable)throw gt("TARGET_CONTEXT_MISMATCH",`Target paragraph reference [P${s}] does not match requested table context.`);if(l){let p=Ka(e,l,{paragraphMetadataIndex:f}),g=(m?.text||Y(d,{revisionView:i})).trim(),h=q(g),v=q(l),w=h!==v;if(w&&p&&p!==d)return r(`[Target] [P${s}] drifted for ${o}; using strict text rematch.`),{paragraph:p,resolvedBy:"strict_text_after_ref_drift"};if(w){let y=Fs(e,l,{onInfo:r,paragraphMetadataIndex:f});if(y&&y!==d)return r(`[Target] [P${s}] drifted for ${o}; using fuzzy text rematch.`),{paragraph:y,resolvedBy:"fuzzy_text_after_ref_drift"};r(`[Target] Using [P${s}] fallback for ${o}; target text drifted.`)}else p&&p!==d&&r(`[Target] [P${s}] disambiguated duplicate target text for ${o}.`)}else r(`[Target] Using [P${s}] fallback for ${o}.`);return{paragraph:d,resolvedBy:"ref"}}n(`[WARN] Target reference [P${s}] not found; falling back to text matching for ${o}.`)}if(l&&!c){let d=Ka(e,l,{paragraphMetadataIndex:f});if(d){let p=u.length;if(p>1){let g=`AMBIGUOUS_TARGET_HEURISTIC_USED: Target text matched ${p} paragraphs; permissive resolution chose candidate 1. Migrate to strict targeting (e.g. strictTargets: true with paragraphId, index, occurrence, or fingerprint) before v1.0.0.`;return n(g),{paragraph:d,resolvedBy:"strict_text",warnings:[g]}}return{paragraph:d,resolvedBy:"strict_text"}}let m=Fs(e,l,{onInfo:r,paragraphMetadataIndex:f});if(m)return{paragraph:m,resolvedBy:"fuzzy_text"}}throw Uo(l?`Target paragraph not found: "${l}"`:s?`Target paragraph reference not found: [P${s}]`:'Operation target missing: provide "target" text or "targetRef" ([P#]).')}function Xo(e){return!!ct(e,"tbl")}function Ga(e,t,r=null){let n=q(t);if(!n)return[];let o=r?.byNormalizedText?r:r?.paragraphMetadataIndex||null,a=r?.revisionView||o?.revisionView||"accepted";if(o?.byNormalizedText&&o.revisionView===a)return Array.from(o.byNormalizedText.get(n)||[]);let i=se(e),l=[];for(let s=0;s<i.length;s++){let c=i[s],f=Y(c,{revisionView:a}).trim();f&&q(f)===n&&l.push({paragraph:c,index:s+1,inTable:Xo(c),paragraphId:He(c),fingerprint:Ot(c,{text:f,index:s+1,revisionView:a}),text:f,revisionView:a})}return l}function Gt(e){return{index:e.index,paragraphId:e.paragraphId||null,text:e.text,inTable:e.inTable,fingerprint:e.fingerprint,revisionView:e.revisionView||"accepted"}}function pw(e,t){let r=e.slice();return t?.paragraphId&&(r=r.filter(n=>n.paragraphId===t.paragraphId)),typeof t?.inTable=="boolean"&&(r=r.filter(n=>n.inTable===t.inTable)),t?.fingerprint&&(r=r.filter(n=>n.fingerprint===t.fingerprint)),r}function gw(e,t,r=null){return t?r?.byId?r.byId.get(t)?.paragraph||null:se(e).find(n=>He(n)===t)||null:null}function hw(e,t,r=null){if(!Array.isArray(e)||e.length===0)return null;let n=e.slice();if(typeof r=="boolean"){let o=n.filter(a=>a.inTable===r);o.length>0&&(n=o)}return Number.isInteger(t)&&t>0&&n.sort((o,a)=>Math.abs(o.index-t)-Math.abs(a.index-t)),n[0]||null}function Us(e,t=null){let r=t?.entries||null,n=r?null:se(e),o=new Map,a=r?.length??n.length;for(let i=0;i<a;i++){let l=r?.[i]?.paragraph??n[i],s=(r?.[i]?.text??_e(l)).trim();o.set(i+1,{text:s,normalizedText:r?.[i]?.normalizedText??q(s),inTable:r?.[i]?.inTable??Xo(l)})}return o}function Jn(e,t={}){let r=typeof t.onInfo=="function"?t.onInfo:()=>{},n=ln(e,t),o=Ds(t.targetRef);if(!o||n?.resolvedBy!=="ref")return n;let a=t.targetRefSnapshot instanceof Map&&t.targetRefSnapshot.get(o)||null;if(!a)return n;let i=String(t.targetText||"").trim(),l=i||a.text||"",s=q(l);if(!s||(t.paragraphMetadataIndex?.byParagraph?.get(n.paragraph)?.normalizedText||q(_e(n.paragraph)))===s)return n;let f=[];if(i&&f.push(i),a.text){let d=q(a.text);d&&!f.some(m=>q(m)===d)&&f.push(a.text)}let u=null;for(let d of f){let m=Ga(e,d,t.paragraphMetadataIndex||null),p=hw(m,o,a.inTable);if(p&&(u||(u=p),p.paragraph!==n.paragraph)){u=p;break}}if(u&&u.paragraph!==n.paragraph){let d=t.opType||"operation";return r(`[Target] [P${o}] appears stale after prior edits; using strict text rematch for ${d}.`),{paragraph:u.paragraph,resolvedBy:"strict_text_after_ref_drift"}}throw Uo(`Target paragraph [P${o}] no longer matches its batch-start anchor.`)}function cn(e,t,r,n={}){if(!e||!t||!r)return null;let o=n?.opType||"redline",a=n?.targetRefSnapshot||null,i=typeof n?.onInfo=="function"?n.onInfo:()=>{},l=typeof n?.onWarn=="function"?n.onWarn:()=>{},s=Jn(e,{targetRef:t,opType:o,targetRefSnapshot:a,onInfo:i,onWarn:l})?.paragraph;if(!s)return null;let c=Jn(e,{targetRef:r,opType:o,targetRefSnapshot:a,onInfo:i,onWarn:l})?.paragraph;if(!c)return null;let f=Array.from(e.getElementsByTagNameNS("*","p")),u=f.indexOf(s),d=f.indexOf(c);if(u<0||d<u)return null;let m=f.slice(u,d+1);if(m.length===0)return null;let p=m[0]?.parentNode||null;return!p||!m.every(g=>g&&g.parentNode===p)?null:m}function Ha(e,t,r={}){if(!e||!e.parentNode)return{valid:!0};let n=t===""||r.operationKind==="delete",o=typeof t=="string"&&t.includes(`
|
|
168
|
+
`),a=r.targetEndParagraph||null,i=ct(e,"tc");if(i){if(n&&Array.from(i.childNodes).filter(c=>F(c,"p")).length<=1)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to delete the sole terminal paragraph of a table cell."};if(a&&ct(a,"tc")!==i)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across different table cells."}}else if(a&&ct(a,"tc"))return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across table boundaries."};if(e.getElementsByTagNameNS(fe,"sectPr").length>0&&n)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to delete paragraph containing section properties (w:sectPr)."};if(a){let s=e;for(;s&&s!==a;){if(F(s,"p")&&s.getElementsByTagNameNS(fe,"sectPr").length>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing paragraph boundary join across section break."};s=s.nextSibling}}if(o){if(e.getElementsByTagNameNS(fe,"fldSimple").length>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to split paragraph containing a simple field instruction (w:fldSimple)."};let c=Array.from(e.getElementsByTagNameNS(fe,"fldChar"));if(c.length>0){let p=0;for(let g of c){let h=g.getAttributeNS(fe,"fldCharType")||g.getAttribute("w:fldCharType");h==="begin"?p++:h==="end"&&(p=Math.max(0,p-1))}if(p>0)return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Refusing to split paragraph across an unclosed field instruction."}}let f=Array.from(e.getElementsByTagNameNS(fe,"bookmarkStart")),u=Array.from(e.getElementsByTagNameNS(fe,"bookmarkEnd")),d=new Set(f.map(p=>p.getAttributeNS(fe,"id")||p.getAttribute("w:id"))),m=new Set(u.map(p=>p.getAttributeNS(fe,"id")||p.getAttribute("w:id")));for(let p of d)if(p&&!m.has(p))return{valid:!1,code:"UNSAFE_PARAGRAPH_BOUNDARY",message:`Refusing to split paragraph across open bookmark range (ID: ${p}).`}}return{valid:!0}}function qa(e,t){if(!e)return null;for(let r of Array.from(e.childNodes||[]))if(r?.nodeType===1&&r.localName===t)return r;return null}function wf(e){if(!e)return null;if(typeof e.getAttributeNS=="function"){let t=e.getAttributeNS(fe,"val");if(t)return t}return e.getAttribute("w:val")||e.getAttribute("val")||null}function un(e){let t=String(e||"").trim(),r=0;for(;r<4;){let n=Zt(t);if(n===t)break;t=n.trimStart(),r++}return t.trim()}function yf(e){let t=String(e||"").split(/\r?\n/g),r=[],n=!1;for(let o of t){let a=o.trimEnd();if(!a.trim())continue;let i=qr(a,{indentSpaces:2});if(i){n=!0,r.push({kind:"list",markerType:i.markerType,level:i.level,marker:i.marker,outlineLevel:i.outlineLevel,text:un(i.text)});continue}r.push({kind:"text",text:a.trim()})}return{items:r,hasListMarkers:n}}function vf(e,t,r){return`${" ".repeat(Math.max(0,e))}${t==="numbered"?"1.":"-"} ${String(r||"").trim()}`.trimEnd()}function zo(e,t){return q(e)===q(t)}function Ya(e,t,r){return Number.isInteger(e?.outlineLevel)?Math.max(0,e.outlineLevel):Math.max(0,t+((e?.level||0)-r))}function ww(e,t,r){if(!Array.isArray(e)||e.length<2||!Number.isInteger(r)||r<0)return!1;let n=e[0],o=e.slice(1).filter(a=>a.kind==="list");if(o.length===0||o.some(a=>a.markerType!=="bullet")||o.some(a=>Number.isInteger(a.outlineLevel)))return!1;if(n?.kind==="text")return zo(n.text,t);if(n?.kind==="list"&&n.markerType==="numbered"){let a=n.level||0;return o.some(l=>(l.level||0)>a)?!1:zo(n.text,t)}return!1}function vw(e,t){return e.map(r=>{let n=Math.max(0,(r.ilvl||0)-t);return{...r,ilvl:Math.min(8,t+1+n)}})}function yw(e,t,r,n){let o=e[0],a=e.slice(1).filter(i=>i.kind==="list");if(o?.kind==="text"&&zo(o.text,t)&&a.length>0){let i=a[0].level;return a.map(l=>({ilvl:Ya(l,r,i),markerType:l.markerType||n,text:l.text}))}if(e.every(i=>i.kind==="list")){let i=e[0];if(!i||!zo(i.text,t))return null;let l=i.level;return e.slice(1).map(s=>({ilvl:Ya(s,r,l),markerType:s.markerType||n,text:s.text})).filter(s=>s.text)}return null}function Oe(e){if(!e)return null;let t=qa(e,"pPr");if(!t)return null;let r=qa(t,"numPr");if(!r)return null;let n=qa(r,"numId");if(!n)return null;let o=wf(n);if(!o||o==="0")return null;let a=qa(r,"ilvl"),i=wf(a),l=Number.parseInt(i||"0",10);return{numId:String(o),ilvl:Number.isFinite(l)?l:0}}function xf(e){let t=Oe(e);if(!t)return null;let r=e.parentNode;if(!r)return null;let n=Array.from(r.childNodes||[]).filter(l=>l&&l.nodeType===1&&l.namespaceURI===fe&&l.localName==="p"),o=n.indexOf(e);if(o<0)return null;let a=o;for(;a>0;){let l=Oe(n[a-1]);if(!l||l.numId!==t.numId)break;a--}let i=o;for(;i<n.length-1;){let l=Oe(n[i+1]);if(!l||l.numId!==t.numId)break;i++}return n.slice(a,i+1)}function Xs(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},a=String(t||"");if(!a.includes(`
|
|
169
|
+
`)||!Oe(e))return null;let l=xf(e);if(!l||l.length===0)return null;let s=yf(a);if(!s.hasListMarkers||s.items.length<2)return null;let c=q(r.currentParagraphText||_e(e)),u=s.items.filter(A=>A.kind==="list")[0]?.markerType||"bullet",d=l.map(A=>({paragraph:A,list:Oe(A),text:String(_e(A)||"").trim()})),m=l.indexOf(e);if(m<0)return null;let p=Math.min(...d.map(A=>A.list?.ilvl??0)),g=d.map(A=>vf((A.list?.ilvl??0)-p,u,A.text)),h=null,v=s.items[0],w=s.items.slice(1).filter(A=>A.kind==="list");if(v?.kind==="text"&&zo(v.text,c)&&w.length>0){let A=Math.max(0,(d[m].list?.ilvl??0)-p),E=w[0].level;h=[{level:A,markerType:u,text:d[m].text},...w.map(I=>({level:Ya(I,A,E),markerType:I.markerType||u,text:I.text}))]}else if(s.items.every(A=>A.kind==="list")){let A=Math.max(0,(d[m].list?.ilvl??0)-p),E=s.items[0].level;h=s.items.map(I=>({level:Ya(I,A,E),markerType:I.markerType||u,text:I.text}))}else return o("[List] Multiline list edit did not match supported insertion/replace patterns; skipping list-block synthesis."),null;let y=h.map(A=>vf(A.level,A.markerType,A.text)),x=g.slice(0,m).concat(y).concat(g.slice(m+1)),b=g.join(`
|
|
170
|
+
`),T=x.join(`
|
|
171
|
+
`);return T===b?null:(n("[List] Expanded single-item list edit to contiguous list block for stable middle insertion."),{paragraphs:l,originalText:b,modifiedText:T})}function zs(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},a=String(t||"");if(!a.includes(`
|
|
172
|
+
`))return null;let i=Oe(e);if(!i)return null;let l=yf(a);if(!l.hasListMarkers||l.items.length<2)return null;let s=q(r.currentParagraphText||_e(e)),f=l.items.filter(m=>m.kind==="list")[0]?.markerType||"bullet",u=Math.max(0,i.ilvl),d=yw(l.items,s,u,f);return!d||d.length===0?(o("[List] Could not derive insertion-only entries from multiline list edit."),null):(ww(l.items,s,u)&&(d=vw(d,u),n("[List] Promoted bullet insertion to child depth for nested numbered-list intent.")),n("[List] Planned insertion-only list redline entries (no block rewrite)."),{targetParagraph:e,numId:i.numId,entries:d})}function jo(e){if(!e)return null;let t=String(e).trim();if(!t)return null;let r=t.split(`
|
|
173
|
+
`),n=[];for(let i of r){if(!i.trim())continue;let l=qr(i,{allowZeroSpaceAfterMarker:!1,indentSpaces:2});if(l){n.push({type:l.markerType,level:l.level,text:l.text.trim(),marker:l.marker});continue}n.push({type:"text",level:0,text:i.trim()})}if(n.length===0)return null;let o=n.some(i=>i.type==="numbered"),a=n.some(i=>i.type==="bullet");return{type:o?"numbered":a?"bullet":"text",items:n}}function js(e){return!e||!Array.isArray(e.items)?!1:e.items.some(t=>t?.type==="numbered"||t?.type==="bullet")}function xw(e,t,r){let n=new Map,o=[];for(let a of e){let i=Math.max(0,Number(a?.level)||0);for(let f of Array.from(n.keys()))f>i&&n.delete(f);let l=(n.get(i)||0)+1;n.set(i,l);let s=Iw(l,t,r),c=" ".repeat(i*4);o.push(`${c}${s} ${a.text||""}`.trimEnd())}return o.join(`
|
|
174
|
+
`)}function bw(e,t={}){let r=Math.max(1,Number(t.indentSpaces)||4);return(e||[]).map(n=>{let o=String(n??""),a=o.match(/^(\s*)/),i=a?a[1].length:0,l=Math.floor(i/r),s=o.trim(),c=null,f=zt(s,{allowZeroSpaceAfterMarker:!0});return f&&(c=f[2].trim()||null,s=Zt(s,{allowZeroSpaceAfterMarker:!0})),{text:s.trim(),level:l,removedMarker:c}})}function Iw(e,t,r){if(t==="bullet")return"-";switch(r){case"lowerAlpha":return`${bf(e,!1)}.`;case"upperAlpha":return`${bf(e,!0)}.`;case"lowerRoman":return`${If(e,!1)}.`;case"upperRoman":return`${If(e,!0)}.`;default:return`${e}.`}}function bf(e,t=!1){let r=Math.max(1,Number(e)||1),n="";for(;r>0;)r-=1,n=String.fromCharCode(97+r%26)+n,r=Math.floor(r/26);return t?n.toUpperCase():n}function If(e,t=!1){let r=Math.max(1,Number(e)||1),n=[[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"]],o="";for(let[a,i]of n)for(;r>=a;)o+=i,r-=a;return t?o:o.toLowerCase()}function Ja(e){let t=String(e||"");if(!t.trim()||t.includes(`
|
|
175
|
+
`))return null;let r=jo(t);if(!r||!js(r)||!Array.isArray(r.items)||r.items.length!==1)return null;let n=r.items[0];if(!n||n.type!=="numbered"&&n.type!=="bullet")return null;let o=String(n.marker||"").trim(),a=n.type==="numbered"?So(o||"1."):"bullet";return{type:n.type,marker:o,numberingStyle:a,startAt:Tw(o,a),contentText:String(n.text||"").trim(),normalizedContent:q(String(n.text||""))}}function Vs(e){let t=Ja(e);return t?String(t.contentText||"").trim():String(e||"").trim()}var Nf={i:1,v:5,x:10,l:50,c:100,d:500,m:1e3};function Nw(e){let t=String(e||"").toLowerCase();if(!/^[ivxlcdm]+$/.test(t))return null;let r=0;for(let n=0;n<t.length;n++){let o=Nf[t[n]],a=Nf[t[n+1]]||0;r+=o<a?-o:o}return r}function Tw(e,t){let r=String(e||"").trim(),n=null;if(t==="decimal"){let o=r.match(/^(\d+)\.?$/);n=o?Number.parseInt(o[1],10):null}else if(t==="lowerRoman"||t==="upperRoman"){let o=r.match(/^([A-Za-z]+)[.)]?$/);n=o?Nw(o[1]):null}else if(t==="lowerAlpha"||t==="upperAlpha"){let o=r.match(/^([A-Za-z])[.)]?$/);n=o?o[1].toLowerCase().charCodeAt(0)-96:null}else return null;return!Number.isFinite(n)||n<1||t!=="decimal"&&n===1?null:n}function Za(e,t=null){let r=e?.numberingKey?String(e.numberingKey):null,n=Number.isInteger(e?.startAt)&&e.startAt>0?e.startAt:null;if(!r)return{type:"none",numberingKey:null,startAt:n,numId:null};if(n==null)return{type:"sharedByStyle",numberingKey:r,startAt:null,numId:null};let o=t?.explicitByNumberingKey;if(!(o instanceof Map))return{type:"explicitIsolated",numberingKey:r,startAt:n,numId:null};let a=o.get(r)||null;return a&&a.numId!=null&&Number.isInteger(a.nextStartAt)&&a.nextStartAt===n?{type:"explicitReuse",numberingKey:r,startAt:n,numId:String(a.numId)}:{type:"explicitStartNew",numberingKey:r,startAt:n,numId:null}}function Qa(e,t,r,n){!e||!(e.explicitByNumberingKey instanceof Map)||!t||r==null||!Number.isInteger(n)||n<1||e.explicitByNumberingKey.set(String(t),{numId:String(r),nextStartAt:n+1})}function Vo(e,t){!e||!(e.explicitByNumberingKey instanceof Map)||t&&e.explicitByNumberingKey.delete(String(t))}function fn(e,t){return e&&Array.from(e.childNodes||[]).find(r=>r&&r.nodeType===1&&r.namespaceURI==="http://schemas.openxmlformats.org/wordprocessingml/2006/main"&&r.localName===t)||null}function ei(e,t={}){let r=t?.numId;if(r==null)return 0;let n=Number.isInteger(t?.ilvl)?Math.max(0,t.ilvl):0,o=t?.clearParagraphPropertyChanges!==!1,a=t?.removeListPropertyNode!==!1,i=t?.trackPropertyChange||null,l=(Array.isArray(e)?e:[]).filter(c=>c&&c.nodeType===1&&c.localName==="p"),s=0;for(let c of l){let f=c.ownerDocument;if(!f)continue;let u=fn(c,"pPr");u||(u=$(f,"w:pPr"),c.insertBefore(u,c.firstChild));let d=i?pt(u):null;if(o){let h=fn(u,"pPrChange");h&&u.removeChild(h)}if(a){let h=fn(u,"listPr");h&&u.removeChild(h)}let m=fn(u,"numPr");m||(m=$(f,"w:numPr"),u.appendChild(m));let p=fn(m,"ilvl");p||(p=$(f,"w:ilvl"),m.appendChild(p)),p.setAttribute("w:val",String(n));let g=fn(m,"numId");if(g||(g=$(f,"w:numId"),m.appendChild(g)),g.setAttribute("w:val",String(r)),i&&!fn(u,"pPrChange")){let h=ue(i.author,i.revisionIdAllocator||f,"pPrChange"),v=$(f,"w:pPrChange");v.setAttribute("w:id",String(h.id)),v.setAttribute("w:author",h.author),v.setAttribute("w:date",h.date),v.appendChild(d||$(f,"w:pPr")),u.appendChild(v)}s++}return s}function Sf(e){let t=String(e||""),r=/xmlns:w\s*=/.test(t);return V(r?t:`<w:root xmlns:w="${B}">${t}</w:root>`,"application/xml").doc}function Sw(e){let t=Sf(e);return!t||$e(t)?null:se(t)[0]||null}function Aw(e){return e?String(e).replace(/<w:p>\s*<w:pPr>\s*<\/w:pPr>\s*<\/w:p>\s*$/i,""):""}function Ew(e,t){for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return null}function Zn(e,t){let r=Ew(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function Tf(e,t){e.setAttribute("w:val",String(t))}function Rw(e){let t=Sf(e);if(!t||$e(t))return null;let n=se(t);for(let o of n){let a=jt(o);for(let i of a){let l=Zn(i,["w:val","val"]);if(l!=null)return String(l)}}return null}function Pw(e,t,r,n={}){if(!e||!t||!Number.isInteger(r)||r<1)return e;let o=n.setAbstractStartOverride!==!1,a=le(),i=V(e,"application/xml").doc;if(!i||$e(i))return e;let c=Array.from(i.getElementsByTagNameNS("*","num")).find(p=>{let g=Zn(p,["w:numId","numId"]);return g!=null&&String(g)===String(t)});if(!c)return e;let f=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null,u=Zn(f,["w:val","val"]),d=Array.from(c.getElementsByTagNameNS("*","lvlOverride")).find(p=>Zn(p,["w:ilvl","ilvl"])===0)||null;d||(d=$(i,"w:lvlOverride"),d.setAttribute("w:ilvl","0"),c.appendChild(d));let m=Array.from(d.getElementsByTagNameNS("*","startOverride"))[0]||null;if(m||(m=$(i,"w:startOverride"),d.appendChild(m)),Tf(m,r),o&&u!=null){let g=Array.from(i.getElementsByTagNameNS("*","abstractNum")).find(h=>{let v=Zn(h,["w:abstractNumId","abstractNumId"]);return v!=null&&v===u})||null;if(g){let h=Array.from(g.getElementsByTagNameNS("*","lvl")).find(w=>Zn(w,["w:ilvl","ilvl"])===0)||null;h||(h=$(i,"w:lvl"),h.setAttribute("w:ilvl","0"),g.appendChild(h));let v=Array.from(h.getElementsByTagNameNS("*","start"))[0]||null;v||(v=$(i,"w:start"),h.insertBefore(v,h.firstChild)),Tf(v,r)}}return a.serializeToString(i)}function dn(e={}){let t=String(e.oxml||""),r=String(e.originalText||""),n=String(e.modifiedText||""),o=e.allowExistingList===!0;if(!t.trim()||!n.trim())return null;let a=Sw(t);if(!a)return null;let i=Oe(a);if(i&&!o)return null;let l=yt(n).cleanText||n,s=Ja(n)||Ja(l);if(!s)return null;let c=Ja(r),f=q(r)===q(l),u=!!c&&c.type===s.type&&c.normalizedContent===s.normalizedContent;return!f&&!u?null:{listInput:`${s.marker} ${s.contentText}`.trim(),numberingKey:`${s.type}:${s.numberingStyle}:single`,originalText:r,wasListParagraph:!!i,numberingStyle:s.numberingStyle,startAt:s.startAt}}async function Qn(e,t={}){if(!e||!e.listInput)return{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:null,warnings:["Single-line list fallback plan missing"]};let r=t.author||"AI",n=t.generateRedlines??!0,o=t.pipeline?await t.pipeline.executeListGeneration(e.listInput,null,null,String(e.originalText||"")):await Wn({cleanText:e.listInput,numberingContext:null,originalRunModel:[],originalText:String(e.originalText||""),generateRedlines:n,author:r,revisionIdAllocator:t.revisionIdAllocator||null,numberingService:new ur}),a=o?.oxml||o?.ooxml||"",i=Aw(a),l=Rw(i),s=Pw(o?.numberingXml||null,l,Number.isInteger(e?.startAt)?e.startAt:null,{setAbstractStartOverride:t.setAbstractStartOverride}),c=o?.isValid!==!1;return!i||!c?{hasChanges:!1,oxml:"",numberingXml:null,includeNumbering:!1,listStructuralFallbackApplied:!1,listStructuralFallbackKey:e.numberingKey||null,warnings:["Single-line list fallback produced no valid OOXML"]}:{hasChanges:!0,oxml:i,numberingXml:s,includeNumbering:!0,listStructuralFallbackApplied:!0,listStructuralFallbackKey:e.numberingKey||null,listStructuralFallbackStartAt:Number.isInteger(e?.startAt)?e.startAt:null,warnings:["Single-line list structural fallback applied"]}}function Af(e,t){if(!e||!Array.isArray(t))return null;for(let r of t){let n=e.getAttribute(r);if(n==null||n==="")continue;let o=Number.parseInt(String(n),10);if(Number.isFinite(o))return o}return null}function eo(e,t,r=null){let n=Number.isInteger(e)&&e>0?e:1,o=t instanceof Set?t:new Set;for(;o.has(n);)n+=1;if(Number.isInteger(r)&&r>0&&n>r){for(let a=1;a<=r;a+=1)if(!o.has(a))return a}return n}function Ht(e,t={}){let r=Number.isInteger(t?.minId)&&t.minId>0?t.minId:1,n=Number.isInteger(t?.maxPreferred)&&t.maxPreferred>=r?t.maxPreferred:32767,o=new Set,a=new Set;if(String(e||"").trim())try{let f=Ve(e),u=Array.from(f.getElementsByTagNameNS("*","abstractNum")),d=Array.from(f.getElementsByTagNameNS("*","num"));for(let m of u){let p=Af(m,["w:abstractNumId","abstractNumId"]);p!=null&&a.add(p)}for(let m of d){let p=Af(m,["w:numId","numId"]);p!=null&&o.add(p)}}catch{}let i=o.size>0?Math.max(...o):0,l=a.size>0?Math.max(...a):0,s=Math.max(r,i+1),c=Math.max(r,l+1);return{sourceNumberingXml:String(e||""),nextNumId:eo(s,o,n),nextAbstractNumId:eo(c,a,n),usedNumIds:o,usedAbstractNumIds:a,minId:r,maxPreferred:n}}function Cw(e){return!e||typeof e!="object"?null:(e.usedNumIds instanceof Set||(e.usedNumIds=new Set),e.usedAbstractNumIds instanceof Set||(e.usedAbstractNumIds=new Set),(!Number.isInteger(e.minId)||e.minId<1)&&(e.minId=1),(!Number.isInteger(e.maxPreferred)||e.maxPreferred<e.minId)&&(e.maxPreferred=32767),(!Number.isInteger(e.nextNumId)||e.nextNumId<e.minId)&&(e.nextNumId=e.minId),(!Number.isInteger(e.nextAbstractNumId)||e.nextAbstractNumId<e.minId)&&(e.nextAbstractNumId=e.minId),e.nextNumId=eo(e.nextNumId,e.usedNumIds,e.maxPreferred),e.nextAbstractNumId=eo(e.nextAbstractNumId,e.usedAbstractNumIds,e.maxPreferred),e)}function Ko(e,t="num"){let r=Cw(e);if(!r)return null;let n=t==="abstract",o=n?r.nextAbstractNumId:r.nextNumId;return!Number.isInteger(o)||o<1?null:(n?(r.usedAbstractNumIds.add(o),r.nextAbstractNumId=eo(o+1,r.usedAbstractNumIds,r.maxPreferred)):(r.usedNumIds.add(o),r.nextNumId=eo(o+1,r.usedNumIds,r.maxPreferred)),o)}function to(e){let t=Ko(e,"num"),r=Ko(e,"abstract");return t==null||r==null?null:{numId:t,abstractNumId:r}}function Ft(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:e.getElementsByTagName("parsererror").length>0}function Wo(e,t){return!!(e&&e.nodeType===1&&e.namespaceURI===fe&&e.localName===t)}function _w(e,t){for(let r of t||[]){let n=e?.getAttribute?.(r);if(n!=null&&n!=="")return n}return null}function ut(e,t){let r=_w(e,t),n=Number.parseInt(String(r||""),10);return Number.isFinite(n)?n:null}function Ef(e,t,r){e?.setAttribute?.(t,String(r))}function Ws(e,t){e?.setAttribute?.("w:val",String(t))}function ti(e,t){if(!(!Array.isArray(e)||t==null)){for(let r of e)if(!kt(r))for(let n of jt(r))Ws(n,t)}}function ri(e){for(let t of e||[])for(let r of jt(t)){let n=ut(r,["w:val","val"]);if(n!=null)return String(n)}return null}function ni(e,t,r){let n=String(e),o=String(t),a=Number.isInteger(r)&&r>0?r:1,i=Array.from({length:9},(l,s)=>{let c=Array.from({length:s+1},(u,d)=>`%${d+1}`).join(".")+".",f=720*(s+1);return`
|
|
176
176
|
<w:lvl w:ilvl="${s}">
|
|
177
177
|
<w:start w:val="1"/>
|
|
178
178
|
<w:numFmt w:val="decimal"/>
|
|
@@ -180,7 +180,7 @@ var pp=Object.create;var sc=Object.defineProperty;var gp=Object.getOwnPropertyDe
|
|
|
180
180
|
<w:lvlJc w:val="left"/>
|
|
181
181
|
<w:pPr><w:ind w:left="${f}" w:hanging="360"/></w:pPr>
|
|
182
182
|
</w:lvl>`}).join("");return`
|
|
183
|
-
<w:numbering xmlns:w="${
|
|
183
|
+
<w:numbering xmlns:w="${fe}">
|
|
184
184
|
<w:abstractNum w:abstractNumId="${o}">
|
|
185
185
|
<w:multiLevelType w:val="multilevel"/>
|
|
186
186
|
${i}
|
|
@@ -191,43 +191,43 @@ var pp=Object.create;var sc=Object.defineProperty;var gp=Object.getOwnPropertyDe
|
|
|
191
191
|
<w:startOverride w:val="${a}"/>
|
|
192
192
|
</w:lvlOverride>
|
|
193
193
|
</w:num>
|
|
194
|
-
</w:numbering>`.trim()}function
|
|
195
|
-
`)})),n=r.reduce((o,a)=>Math.max(o,a.length),0);return r.forEach(o=>{for(;o.length<n;)o.push("")}),{matrix:r,rowElements:t,columnCount:n}}function
|
|
196
|
-
`)}function
|
|
197
|
-
`)||on(a))return null;let i=a.split(/\r?\n/g).map(b=>b.trim()).filter(Boolean);if(i.length<2)return null;let l=r.tableElement||st(e,"tbl"),s=st(e,"tr"),c=st(e,"tc");if(!l||!s||!c)return null;let f=Z(r.currentParagraphText||Ce(e)),u=Z(i[0]);if(f&&u&&u!==f)return o("[Table] Multiline cell text did not anchor to original cell text; skipping table-row synthesis heuristic."),null;let{matrix:d,rowElements:m,columnCount:p}=Pw(l);if(d.length===0||p===0)return null;let g=m.indexOf(s),v=ti(s,"tc").indexOf(c);if(g<0||v<0||v>=p)return null;d[g][v]=i[0];let w=_w(d[g]);w&&n("[Table] Symmetric row detected; mirroring inserted row values across columns.");for(let b=1;b<i.length;b++){let I=g+b,E=i[b];if(I<d.length&&!Z(d[I][v]))if(w)for(let N=0;N<p;N++)Z(d[I][N])||(d[I][N]=E);else d[I][v]=E;else{let N=new Array(p).fill("");if(w)for(let R=0;R<p;R++)N[R]=E;else N[v]=E;d.splice(Math.min(I,d.length),0,N)}}let y=Cw(d,p);return y?(n("[Table] Synthesized full markdown table from multiline cell edit for table-scope reconciliation."),y):null}var If=8,ri=["start","numFmt","lvlRestart","pStyle","isLgl","suff","lvlText","lvlPicBulletId","legacy","lvlJc","pPr","rPr"],De=(e,t)=>Array.from(e?.childNodes||[]).filter(r=>Xo(r,t)),pt=(e,t)=>Array.from(e?.getElementsByTagNameNS?.("*",t)||[]),nr=e=>{let t=e?.getAttribute?.("w:val")??e?.getAttribute?.("val"),r=Number.parseInt(String(t??""),10);return Number.isFinite(r)?r:null};function jo(e,t){if(e.nodeType===3||e.nodeType===4){let o=String(e.nodeValue||"").trim();return o?JSON.stringify(o):""}if(e.nodeType!==1)return"";let r=Array.from(e.attributes||[]).filter(o=>!/^xmlns(:|$)/.test(o.name)).filter(o=>!(t&&/^(w:)?(abstractNumId|numId)$/.test(o.name))).map(o=>`${o.localName||o.name}=${o.value}`).sort().join(",");if(t&&e.localName==="abstractNumId"&&e.parentNode?.localName==="num")return`<abstractNumId ${r.replace(/val=[^,]*/,"val=*")}/>`;let n=Array.from(e.childNodes||[]).map(o=>jo(o,t)).join("");return`<${e.localName} ${r}>${n}</>`}function Ow(e,t){let r=typeof e=="string"?Xe(e):e;if(!r||Ft(r))return null;let n=pt(r,"num").find(i=>lt(i,["w:numId","numId"])===Number(t));if(!n)return null;let o=nr(De(n,"abstractNumId")[0]),a=pt(r,"abstractNum").find(i=>lt(i,["w:abstractNumId","abstractNumId"])===o);return`${jo(n,!0)}|${a?jo(a,!0):"missing-abstract"}`}function Wo(e,t){let r=pt(e,"num").find(o=>lt(o,["w:numId","numId"])===Number(t)),n=nr(De(r,"abstractNumId")[0]);return n==null?null:pt(e,"abstractNum").find(o=>lt(o,["w:abstractNumId","abstractNumId"])===n)||null}function pn(e,t,r,n){let o=De(t,r)[0];if(!o){o=e.createElementNS(ue,`w:${r}`);let a=ri.indexOf(r),i=Array.from(t.childNodes||[]).find(l=>l.nodeType===1&&ri.indexOf(l.localName)>a);i?t.insertBefore(o,i):t.appendChild(o)}o.setAttribute("w:val",String(n))}function kw(e,t){let r=e.createElementNS(ue,"w:lvl");r.setAttribute("w:ilvl",String(t)),pn(e,r,"start",1),pn(e,r,"numFmt","decimal"),pn(e,r,"lvlText",`%${t+1}.`),pn(e,r,"lvlJc","left");let n=e.createElementNS(ue,"w:pPr"),o=e.createElementNS(ue,"w:ind");return o.setAttribute("w:left",String(720*(t+1))),o.setAttribute("w:hanging","360"),n.appendChild(o),r.appendChild(n),r}function Mw(e,t){let r=t.ownerDocument;for(let n of["suff","lvlJc","pPr","rPr"]){for(let s of De(t,n))t.removeChild(s);let o=De(e,n)[0];if(!o)continue;let a=r.importNode(o,!0),i=ri.indexOf(n),l=Array.from(t.childNodes||[]).find(s=>s.nodeType===1&&ri.indexOf(s.localName)>i);l?t.insertBefore(a,l):t.appendChild(a)}}function xf(e,t){let r=e.ownerDocument,n=Object.entries(t||{}).map(([o,a])=>[Number(o),Number(a)]).filter(([o,a])=>Number.isInteger(o)&&o>=0&&o<=If&&Number.isInteger(a)&&a>=0).sort((o,a)=>o[0]-a[0]);for(let[o,a]of n){for(let s of De(e,"lvlOverride"))gn(s)===o&&e.removeChild(s);let i=r.createElementNS(ue,"w:lvlOverride");i.setAttribute("w:ilvl",String(o));let l=r.createElementNS(ue,"w:startOverride");l.setAttribute("w:val",String(a)),i.appendChild(l),e.appendChild(i)}}function gn(e){return lt(e,["w:ilvl","ilvl"])}function Ko(e){let{numberingIdState:t,sourceNumberingXml:r,sourceNumId:n,levels:o=[],startOverrides:a}=e||{},i=Zn(t);if(!i)return null;let l=String(r||"").trim()?Xe(r):null,s=l&&!Ft(l)&&n!=null?Wo(l,n):null,c=new Map(pt(s,"lvl").map(w=>[gn(w),w]).filter(([w])=>w!=null)),f=Xe(`<w:numbering xmlns:w="${ue}"/>`),u=f.documentElement,d=f.createElementNS(ue,"w:abstractNum");d.setAttribute("w:abstractNumId",String(i.abstractNumId));let m=f.createElementNS(ue,"w:multiLevelType");m.setAttribute("w:val",De(s,"multiLevelType")[0]?.getAttribute("w:val")||"multilevel"),d.appendChild(m);let p=new Map(o.filter(w=>Number.isInteger(w?.ilvl)).map(w=>[w.ilvl,w])),g=Math.max(If,...c.keys(),...p.keys());for(let w=0;w<=g;w+=1){let y=c.get(w),b=y?f.importNode(y,!0):kw(f,w);for(let E of De(b,"pStyle"))b.removeChild(E);b.removeAttribute("w:tplc"),b.removeAttribute("w:tentative");let I=p.get(w);if(I){I.numFmt!=null&&pn(f,b,"numFmt",I.numFmt),I.lvlText!=null&&pn(f,b,"lvlText",I.lvlText),I.start!=null&&pn(f,b,"start",I.start);for(let E of I.dropChildren||[])for(let N of De(b,E))b.removeChild(N);if(I.dropRunFonts)for(let E of De(b,"rPr")){for(let N of De(E,"rFonts"))E.removeChild(N);Array.from(E.childNodes||[]).some(N=>N.nodeType===1)||b.removeChild(E)}}d.appendChild(b)}let h=f.createElementNS(ue,"w:num");h.setAttribute("w:numId",String(i.numId));let v=f.createElementNS(ue,"w:abstractNumId");return v.setAttribute("w:val",String(i.abstractNumId)),h.appendChild(v),xf(h,a),u.appendChild(d),u.appendChild(h),{numId:i.numId,abstractNumId:i.abstractNumId,numberingXml:Kt(f)}}function bf(e){let t=new Map;for(let r of pt(e,"lvl")){let n=gn(r),o=pt(r,"numFmt")[0]?.getAttribute("w:val")||null;n!=null&&o&&t.set(n,o)}return t}function Us(e){return e==="bullet"||e==="circle"||e==="square"?"bullet":e}function zs(e){return Vt(e).map(t=>{let r=De(t.parentNode,"ilvl")[0];return{numIdElement:t,numId:nr(t),ilvl:r?nr(r)??0:0}})}function Lw(e,t,r,n){let o=n?.sourceNumberingXml;if(!e||!String(o||"").trim()||!Array.isArray(t))return null;let a=new Set;for(let p of r||[])for(let{numId:g}of zs(p))g!=null&&g!==0&&a.add(g);if(a.size!==1)return null;let[i]=a,l=Xe(o),s=Xe(e);if(Ft(l)||Ft(s))return null;let c=Wo(l,i);if(!c)return null;let f=bf(c),u=[];for(let p of t)Ot(p)||u.push(...zs(p));if(u.length===0)return null;let d=new Map;for(let{numId:p,ilvl:g}of u){if(p==null)return null;if(!d.has(p)){let w=Wo(s,p);if(!w)return null;d.set(p,bf(w))}let h=d.get(p).get(g),v=f.get(g);if(!h||!v||Us(h)!==Us(v))return null}let m=t.map(p=>p?.cloneNode?p.cloneNode(!0):p);for(let p of m)if(!Ot(p))for(let g of Vt(p))g.setAttribute("w:val",String(i));return{numId:i,replacementNodes:m}}function Xs(e){let{numberingXml:t,replacementNodes:r,sourceParagraphs:n,numberingIdState:o,allowContinueSource:a=!0}=e||{};if(t&&o&&a){let i=Lw(t,r,n,o);if(i)return{policy:"continue-source",numberingXml:null,replacementNodes:i.replacementNodes,numId:i.numId}}if(t&&o){let i=fn(t,r,o);return{policy:"allocate",numberingXml:i.numberingXml,replacementNodes:i.replacementNodes}}return{policy:"passthrough",numberingXml:t??null,replacementNodes:r}}function Bw(e,t,r){let n=String(r||"").replace(/%\d+/g,"").trim()||".";return`list-format:${e}:${t}:${e==="bullet"?"":n}`}function Fw(e,t){let r=[];for(let p of t||[])Ot(p)||r.push(...zs(p));if(r.length===0)return null;let{numId:n,ilvl:o}=r[0];if(n==null||n===0||r.some(p=>p.numId!==n||p.ilvl!==o))return null;let a=Xe(e);if(Ft(a))return null;let i=pt(a,"num").find(p=>lt(p,["w:numId","numId"])===Number(n)),l=Wo(a,n),s=pt(l,"lvl").find(p=>gn(p)===o),c=pt(s,"numFmt")[0]?.getAttribute("w:val");if(!i||!s||!c)return null;let f=pt(s,"lvlText")[0]?.getAttribute("w:val")||"",u=De(i,"lvlOverride").find(p=>gn(p)===o),d=nr(De(u,"startOverride")[0])??nr(pt(s,"start")[0])??1,m=Us(c)==="bullet";return{numId:n,ilvl:o,count:r.length,isBullet:m,start:d,key:Bw(m?"bullet":c,o,f)}}function Nf({numberingXml:e,replacementNodes:t,sequence:r,isNumIdLive:n}){if(!(r instanceof Map)||!e)return null;let o=Fw(e,t);if(!o)return null;let a=r.get(o.key)||null,l=a&&a.numId!=null&&(typeof n!="function"||n(a.numId))&&(o.isBullet||a.nextStartAt===o.start),s=o.isBullet?null:o.start+o.count;if(!l)return r.set(o.key,{numId:String(o.numId),nextStartAt:s}),null;let c=t.map(f=>f?.cloneNode?f.cloneNode(!0):f);for(let f of c)if(!Ot(f))for(let u of Vt(f))u.setAttribute("w:val",String(a.numId));return r.set(o.key,{numId:String(a.numId),nextStartAt:s}),{numId:a.numId,replacementNodes:c}}function $w(e,t,r){let n=Array.from(e.childNodes||[]).filter(a=>a&&a.nodeType===1&&a.namespaceURI===ue),o=r==="abstract"?n.find(a=>a.localName==="num"||a.localName==="numIdMacAtCleanup"):n.find(a=>a.localName==="numIdMacAtCleanup");o?e.insertBefore(t,o):e.appendChild(t)}function Tf(e,t,r={}){let n=String(e||""),o=String(t||"");if(!o.trim())return n;if(!n.trim())return o;try{let a=Xe(n),i=Xe(o);if(Ft(a)||Ft(i))return n;let l=a.documentElement,s=i.documentElement;if(!l||!s)return n;for(let[c,f,u]of[["abstract","abstractNum","abstractNumId"],["num","num","numId"]]){let d=new Map(De(l,f).map(m=>[lt(m,[`w:${u}`,u]),m]).filter(([m])=>m!=null));for(let m of De(s,f)){let p=lt(m,[`w:${u}`,u]);if(p==null)continue;let g=d.get(p);if(g){typeof r?.onConflict=="function"&&jo(g,!1)!==jo(m,!1)&&r.onConflict({kind:f,id:p});continue}let h=a.importNode(m,!0);$w(l,h,c),d.set(p,h)}}return Kt(a)}catch{return n}}function hr(e,t,r={}){let n=String(e||"");for(let o of(Array.isArray(t)?t:[t]).filter(Boolean))n=Tf(n,o,r);return n}function Af(e,t,r=0){let n=Number(t),o=String(e?.sourceNumberingXml||""),a=o.trim()?Xe(o):null,i=a&&!Ft(a)?pt(a,"num").find(f=>lt(f,["w:numId","numId"])===n):null;if(!i)return e?.usedNumIds instanceof Set&&e.usedNumIds.has(n)?{ok:!0}:{ok:!1,reason:"unknown-num",message:`numbering.numId ${n} does not exist in the document's numbering definitions.`};let l=Wo(a,n);if(!l)return{ok:!1,reason:"missing-abstract",message:`numId ${n} points at an abstractNum that does not exist.`};let s=f=>De(f,"lvl").some(u=>Number.parseInt(u.getAttribute("w:ilvl")??u.getAttribute("ilvl")??"0",10)===r),c=De(i,"lvlOverride").some(f=>s(f));return!s(l)&&!c?{ok:!1,reason:"undefined-level",message:`numId ${n} does not define list level ${r}.`}:{ok:!0}}function Qn(e,t){let r=[],n=new Set,o=(u,d,m={})=>{let p=`${u}:${m.numId??""}:${m.abstractNumId??""}:${m.ilvl??""}`;n.has(p)||(n.add(p),r.push({code:u,severity:"error",message:d,...m}))},a=typeof e=="string"?Xe(e):e;if(!a||Ft(a))return r;let i=typeof t=="string"?t.trim()?Xe(t):null:t||null,l=i&&!Ft(i),s=new Map,c=new Map;if(l){for(let[u,d,m]of[["abstractNum","abstractNumId",s],["num","numId",c]])for(let p of pt(i,u)){let g=lt(p,[`w:${d}`,d]);g!=null&&(m.has(g)?o("NUMBERING_DUPLICATE_ID",`Numbering part defines ${u} ${g} more than once.`,{[d]:g}):m.set(g,p))}for(let[u,d]of c){let m=nr(De(d,"abstractNumId")[0]);m==null?o("NUMBERING_ABSTRACT_UNDEFINED",`w:num ${u} has no w:abstractNumId.`,{numId:u}):s.has(m)||o("NUMBERING_ABSTRACT_UNDEFINED",`w:num ${u} references missing w:abstractNum ${m}.`,{numId:u,abstractNumId:m})}}let f=(u,d)=>{let m=c.get(u),p=s.get(nr(De(m,"abstractNumId")[0]));return!p||pt(p,"lvl").some(g=>gn(g)===d)?!0:De(m,"lvlOverride").some(g=>gn(g)===d&&De(g,"lvl").length>0)};for(let u of Array.from(a.getElementsByTagNameNS(ue,"p"))){let d=[nt(u).numPr,Ac(u)?.numPr];for(let m of d){if(!m?.numIdElement)continue;let p=nr(m.numIdElement);if(p==null||p===0)continue;if(!l||!c.has(p)){o("NUMBERING_NUM_UNDEFINED",`w:numId ${p} is used in the document but no w:num defines it.`,{numId:p});continue}let g=m.ilvlElement?nr(m.ilvlElement):null;g!=null&&!f(p,g)&&o("NUMBERING_LEVEL_UNDEFINED",`w:ilvl ${g} is used with w:numId ${p} but its abstractNum does not define that level.`,{numId:p,ilvl:g})}}return r}function Dw(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:!!Le(e)}function Sf(e){let t=j(e,"application/xml");return t.error||Dw(t.doc)?{...t,doc:null}:t}function Ef(e){if(!e)return[];let t=Array.from(e.getElementsByTagNameNS(B,"p"));return t.length>0?t:Array.from(e.getElementsByTagNameNS("*","p")).filter(r=>r?.localName==="p")}function Go(e,t){if(!e)return"";for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return""}function Uw(e){let t=Tc(e);if(!t)return{bold:!1,italic:!1};let r=Je(t,"rStyle"),n=Go(r,["w:val","val"]).toLowerCase(),o=n.includes("strong")||n.includes("bold"),a=n.includes("italic")||n.includes("emphasis");return{bold:!!Je(t,"b")||o,italic:!!Je(t,"i")||a}}function Rf(e){let t=[],r=Array.from(e?.getElementsByTagNameNS?.(B,"r")||[]);for(let n of r){if(!Qr(n,e,"accepted"))continue;let o=mr(n,{boundary:e,revisionView:"accepted"});o&&t.push({text:o,...Uw(n)})}return t}function Vs(e){return String(e||"").replace(/\r/g,"").split(`
|
|
194
|
+
</w:numbering>`.trim()}function kt(e){if(!e||e.nodeType!==1||e.localName!=="p")return!1;let t=Array.from(e.childNodes||[]).find(n=>Wo(n,"pPr")),r=t&&Array.from(t.childNodes||[]).find(n=>Wo(n,"rPr"));return!!r&&Array.from(r.childNodes||[]).some(n=>Wo(n,"del"))}function mn(e,t,r){let n=Ve(e);if(Ft(n))return{numberingXml:String(e||""),replacementNodes:Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[]};let o=new Map,a=new Map,i=Array.from(n.getElementsByTagNameNS("*","abstractNum"));for(let c of i){let f=ut(c,["w:abstractNumId","abstractNumId"]);if(f==null)continue;let u=Ko(r,"abstract");u!=null&&(o.set(f,u),Ef(c,"w:abstractNumId",u))}let l=Array.from(n.getElementsByTagNameNS("*","num"));for(let c of l){let f=ut(c,["w:numId","numId"]);if(f==null)continue;let u=Ko(r,"num");if(u==null)continue;a.set(f,u),Ef(c,"w:numId",u);let d=Array.from(c.getElementsByTagNameNS("*","abstractNumId"))[0]||null;if(d){let m=ut(d,["w:val","val"]);m!=null&&o.has(m)&&Ws(d,o.get(m))}}let s=Array.isArray(t)?t.map(c=>c?.cloneNode?c.cloneNode(!0):c):[];for(let c of s)if(!kt(c))for(let f of Bn(c)){let u=ut(f,["w:val","val"]);u!=null&&a.has(u)&&Ws(f,a.get(u))}return{numberingXml:Kt(n),replacementNodes:s}}var Ow=new Set(["ins","del","rPrChange","pPrChange"]),kw=/^\d{4}-\d{2}-\d{2}T/;function zr(e){return String(e?.localName||e?.nodeName||"").replace(/^.*:/,"")}function pn(e,t){return Array.from(e.getElementsByTagName("*")).filter(r=>zr(r)===t)}function gn(e,t){return e.getAttribute(`w:${t}`)||e.getAttribute(t)||""}function Mw(e){return e.getAttribute("xml:space")||e.getAttribute("space")||e.getAttributeNS?.("http://www.w3.org/XML/1998/namespace","space")||""}function Lw(e){return zr(e.parentNode)==="rPr"}function Bw(e){let t=r=>{let n=Ic(r),o=n.getElementsByTagName("parsererror")[0];if(o)throw new Error(o.textContent||"XML parse error");return n};try{return{doc:t(e)}}catch{try{return{doc:t(`<w:root xmlns:w="${B}">${e}</w:root>`)}}catch(r){return{error:r?.message||"XML parse error"}}}}function Mt(e){let t=[],r=(u,d,m)=>t.push({code:u,severity:d,message:m}),n=e&&typeof e=="object"&&(e.nodeType===9||e.nodeType===1);if(!n&&(typeof e!="string"||e.trim()===""))return r("PARSE_ERROR","error","Input is not non-empty OOXML or a parsed XML DOM."),{valid:!1,issues:t};let{doc:o,error:a}=n?{doc:e.nodeType===9?e:e.ownerDocument}:Bw(e);if(!o)return r("PARSE_ERROR","error",`OOXML does not parse as XML: ${a}`),{valid:!1,issues:t};let i=pn(o,"ins"),l=pn(o,"del"),s=i.concat(l);for(let u of pn(o,"p")){let d=Array.from(u.getElementsByTagName("*")).find(m=>m!==u&&zr(m)==="p");d&&r("NESTED_PARAGRAPH","error",`<${u.nodeName}> contains nested <${d.nodeName}>.`)}for(let u of pn(o,"body")){let d=Array.from(u.childNodes||[]).filter(p=>p.nodeType===1),m=d.map((p,g)=>zr(p)==="sectPr"?g:-1).filter(p=>p>=0);m.length>1?r("MULTIPLE_BODY_SECTPR","error","<w:body> contains multiple direct <w:sectPr> elements."):m.length===1&&m[0]!==d.length-1&&r("SECTPR_NOT_LAST","error","<w:sectPr> is not the last element child of <w:body>.")}for(let u of s){let m=Array.from(u.getElementsByTagName("*")).filter(p=>p!==u&&["ins","del"].includes(zr(p))).find(p=>zr(u)!=="ins"||zr(p)!=="del"?!0:p.parentNode!==u);m&&r("NESTED_REVISION","error",`<${u.nodeName}> (w:id="${gn(u,"id")}") contains invalid nested <${m.nodeName}>.`)}for(let u of l)pn(u,"t").length>0&&r("DEL_CONTAINS_T","error",`<w:del> (w:id="${gn(u,"id")}") contains <w:t>; deleted text must use <w:delText>.`);for(let u of s){let d=[];gn(u,"id")||d.push("w:id"),gn(u,"author")||d.push("w:author"),kw.test(gn(u,"date"))||d.push("w:date"),d.length>0&&r("MISSING_REVISION_METADATA","error",`<${u.nodeName}> is missing or has malformed ${d.join(", ")}.`)}let c=new Set;for(let u of Array.from(o.getElementsByTagName("*"))){if(!Ow.has(zr(u)))continue;let d=gn(u,"id");d&&(c.has(d)&&r("DUPLICATE_REVISION_ID","error",`Revision id ${d} appears more than once.`),c.add(d))}let f=pn(o,"t").concat(pn(o,"delText"));for(let u of f){let d=u.textContent||"";/^\s|\s$/.test(d)&&Mw(u)!=="preserve"&&r("MISSING_SPACE_PRESERVE","error",`<${u.nodeName}> has boundary whitespace without xml:space="preserve".`),d===""&&r("EMPTY_TEXT_ELEMENT","warning",`<${u.nodeName}> is empty.`)}for(let u of s){if(Lw(u))continue;Array.from(u.childNodes||[]).some(m=>m.nodeType===1)||r("EMPTY_REVISION_WRAPPER","warning",`<${u.nodeName}> (w:id="${gn(u,"id")}") wraps no content.`)}for(let u of mf(o)){let d=u.ownerAuthor||"unattributed";r("FOREIGN_PARAGRAPH_MARK_DELETION","warning",`Paragraph deleted by ${d} also contains non-empty insertion content from another author; Accept/Reject lifecycle may not preserve the apparent restoration.`)}return{valid:!t.some(u=>u.severity==="error"),issues:t}}function oi(e,t){return e?Array.from(e.childNodes||[]).filter(r=>r&&r.nodeType===1&&r.namespaceURI===fe&&r.localName===t):[]}function $w(e){return String(e||"").replace(/\|/g,"\\|").replace(/\r?\n/g,"<br>")}function Fw(e){let t=oi(e,"tr"),r=t.map(o=>oi(o,"tc").map(i=>{let l=oi(i,"p");return l.length===0?q(_e(i)):l.map(c=>q(_e(c))).filter(Boolean).join(`
|
|
195
|
+
`)})),n=r.reduce((o,a)=>Math.max(o,a.length),0);return r.forEach(o=>{for(;o.length<n;)o.push("")}),{matrix:r,rowElements:t,columnCount:n}}function Dw(e,t){if(!Array.isArray(e)||e.length===0||t<=0)return null;let r=e.map(l=>{let s=Array.isArray(l)?l.slice(0,t):[];for(;s.length<t;)s.push("");return s}),n=r[0],o=new Array(t).fill("---"),a=r.slice(1),i=l=>`| ${l.map(s=>$w(s)).join(" | ")} |`;return[i(n),i(o),...a.map(i)].join(`
|
|
196
|
+
`)}function Uw(e){if(!Array.isArray(e)||e.length<2)return!1;let t=e.map(r=>q(r)).filter(Boolean);return t.length<2?!1:t.every(r=>r===t[0])}function Rf(e){let t=String(e||"").trim();return t?!!(/^and$/i.test(t)||/^\[.*\]$/.test(t)||/^\(.*\)$/.test(t)||/:\s*$/.test(t)||t.length<=90&&!/[.!?]$/.test(t)&&/[:\[\]()]/.test(t)||/^[\[(]/.test(t)):!1}function Ks(e,t={}){let r=Number.isInteger(t?.maxScan)&&t.maxScan>0?t.maxScan:10,n=typeof t?.getParagraphText=="function"?t.getParagraphText:_e;if(!e||!e.parentNode)return null;let o=[e],a=e.nextSibling,i=0;for(;a&&i<r;){i+=1;let l=a.nextSibling;if(a.nodeType!==1||a.namespaceURI!==fe||a.localName!=="p"){a=l;continue}let s=String(n(a)||"").trim();if(!s){if(o.length>1)break;a=l;continue}if(!Rf(s))break;o.push(a),a=l}return o.length>1?o:null}function Gs(e,t,r={}){let n=typeof r.onInfo=="function"?r.onInfo:()=>{},o=typeof r.onWarn=="function"?r.onWarn:()=>{},a=String(t||"");if(!a.includes(`
|
|
197
|
+
`)||sn(a))return null;let i=a.split(/\r?\n/g).map(x=>x.trim()).filter(Boolean);if(i.length<2)return null;let l=r.tableElement||ct(e,"tbl"),s=ct(e,"tr"),c=ct(e,"tc");if(!l||!s||!c)return null;let f=q(r.currentParagraphText||_e(e)),u=q(i[0]);if(f&&u&&u!==f)return o("[Table] Multiline cell text did not anchor to original cell text; skipping table-row synthesis heuristic."),null;let{matrix:d,rowElements:m,columnCount:p}=Fw(l);if(d.length===0||p===0)return null;let g=m.indexOf(s),v=oi(s,"tc").indexOf(c);if(g<0||v<0||v>=p)return null;d[g][v]=i[0];let w=Uw(d[g]);w&&n("[Table] Symmetric row detected; mirroring inserted row values across columns.");for(let x=1;x<i.length;x++){let b=g+x,T=i[x];if(b<d.length&&!q(d[b][v]))if(w)for(let A=0;A<p;A++)q(d[b][A])||(d[b][A]=T);else d[b][v]=T;else{let A=new Array(p).fill("");if(w)for(let E=0;E<p;E++)A[E]=T;else A[v]=T;d.splice(Math.min(b,d.length),0,A)}}let y=Dw(d,p);return y?(n("[Table] Synthesized full markdown table from multiline cell edit for table-scope reconciliation."),y):null}var Cf=8,ai=["start","numFmt","lvlRestart","pStyle","isLgl","suff","lvlText","lvlPicBulletId","legacy","lvlJc","pPr","rPr"],Xe=(e,t)=>Array.from(e?.childNodes||[]).filter(r=>Wo(r,t)),ht=(e,t)=>Array.from(e?.getElementsByTagNameNS?.("*",t)||[]),nr=e=>{let t=e?.getAttribute?.("w:val")??e?.getAttribute?.("val"),r=Number.parseInt(String(t??""),10);return Number.isFinite(r)?r:null};function Go(e,t){if(e.nodeType===3||e.nodeType===4){let o=String(e.nodeValue||"").trim();return o?JSON.stringify(o):""}if(e.nodeType!==1)return"";let r=Array.from(e.attributes||[]).filter(o=>!/^xmlns(:|$)/.test(o.name)).filter(o=>!(t&&/^(w:)?(abstractNumId|numId)$/.test(o.name))).map(o=>`${o.localName||o.name}=${o.value}`).sort().join(",");if(t&&e.localName==="abstractNumId"&&e.parentNode?.localName==="num")return`<abstractNumId ${r.replace(/val=[^,]*/,"val=*")}/>`;let n=Array.from(e.childNodes||[]).map(o=>Go(o,t)).join("");return`<${e.localName} ${r}>${n}</>`}function Xw(e,t){let r=typeof e=="string"?Ve(e):e;if(!r||Ft(r))return null;let n=ht(r,"num").find(i=>ut(i,["w:numId","numId"])===Number(t));if(!n)return null;let o=nr(Xe(n,"abstractNumId")[0]),a=ht(r,"abstractNum").find(i=>ut(i,["w:abstractNumId","abstractNumId"])===o);return`${Go(n,!0)}|${a?Go(a,!0):"missing-abstract"}`}function Ho(e,t){let r=ht(e,"num").find(o=>ut(o,["w:numId","numId"])===Number(t)),n=nr(Xe(r,"abstractNumId")[0]);return n==null?null:ht(e,"abstractNum").find(o=>ut(o,["w:abstractNumId","abstractNumId"])===n)||null}function hn(e,t,r,n){let o=Xe(t,r)[0];if(!o){o=e.createElementNS(fe,`w:${r}`);let a=ai.indexOf(r),i=Array.from(t.childNodes||[]).find(l=>l.nodeType===1&&ai.indexOf(l.localName)>a);i?t.insertBefore(o,i):t.appendChild(o)}o.setAttribute("w:val",String(n))}function zw(e,t){let r=e.createElementNS(fe,"w:lvl");r.setAttribute("w:ilvl",String(t)),hn(e,r,"start",1),hn(e,r,"numFmt","decimal"),hn(e,r,"lvlText",`%${t+1}.`),hn(e,r,"lvlJc","left");let n=e.createElementNS(fe,"w:pPr"),o=e.createElementNS(fe,"w:ind");return o.setAttribute("w:left",String(720*(t+1))),o.setAttribute("w:hanging","360"),n.appendChild(o),r.appendChild(n),r}function jw(e,t){let r=t.ownerDocument;for(let n of["suff","lvlJc","pPr","rPr"]){for(let s of Xe(t,n))t.removeChild(s);let o=Xe(e,n)[0];if(!o)continue;let a=r.importNode(o,!0),i=ai.indexOf(n),l=Array.from(t.childNodes||[]).find(s=>s.nodeType===1&&ai.indexOf(s.localName)>i);l?t.insertBefore(a,l):t.appendChild(a)}}function _f(e,t){let r=e.ownerDocument,n=Object.entries(t||{}).map(([o,a])=>[Number(o),Number(a)]).filter(([o,a])=>Number.isInteger(o)&&o>=0&&o<=Cf&&Number.isInteger(a)&&a>=0).sort((o,a)=>o[0]-a[0]);for(let[o,a]of n){for(let s of Xe(e,"lvlOverride"))wn(s)===o&&e.removeChild(s);let i=r.createElementNS(fe,"w:lvlOverride");i.setAttribute("w:ilvl",String(o));let l=r.createElementNS(fe,"w:startOverride");l.setAttribute("w:val",String(a)),i.appendChild(l),e.appendChild(i)}}function wn(e){return ut(e,["w:ilvl","ilvl"])}function qo(e){let{numberingIdState:t,sourceNumberingXml:r,sourceNumId:n,levels:o=[],startOverrides:a}=e||{},i=to(t);if(!i)return null;let l=String(r||"").trim()?Ve(r):null,s=l&&!Ft(l)&&n!=null?Ho(l,n):null,c=new Map(ht(s,"lvl").map(w=>[wn(w),w]).filter(([w])=>w!=null)),f=Ve(`<w:numbering xmlns:w="${fe}"/>`),u=f.documentElement,d=f.createElementNS(fe,"w:abstractNum");d.setAttribute("w:abstractNumId",String(i.abstractNumId));let m=f.createElementNS(fe,"w:multiLevelType");m.setAttribute("w:val",Xe(s,"multiLevelType")[0]?.getAttribute("w:val")||"multilevel"),d.appendChild(m);let p=new Map(o.filter(w=>Number.isInteger(w?.ilvl)).map(w=>[w.ilvl,w])),g=Math.max(Cf,...c.keys(),...p.keys());for(let w=0;w<=g;w+=1){let y=c.get(w),x=y?f.importNode(y,!0):zw(f,w);for(let T of Xe(x,"pStyle"))x.removeChild(T);x.removeAttribute("w:tplc"),x.removeAttribute("w:tentative");let b=p.get(w);if(b){b.numFmt!=null&&hn(f,x,"numFmt",b.numFmt),b.lvlText!=null&&hn(f,x,"lvlText",b.lvlText),b.start!=null&&hn(f,x,"start",b.start);for(let T of b.dropChildren||[])for(let A of Xe(x,T))x.removeChild(A);if(b.dropRunFonts)for(let T of Xe(x,"rPr")){for(let A of Xe(T,"rFonts"))T.removeChild(A);Array.from(T.childNodes||[]).some(A=>A.nodeType===1)||x.removeChild(T)}}d.appendChild(x)}let h=f.createElementNS(fe,"w:num");h.setAttribute("w:numId",String(i.numId));let v=f.createElementNS(fe,"w:abstractNumId");return v.setAttribute("w:val",String(i.abstractNumId)),h.appendChild(v),_f(h,a),u.appendChild(d),u.appendChild(h),{numId:i.numId,abstractNumId:i.abstractNumId,numberingXml:Kt(f)}}function Pf(e){let t=new Map;for(let r of ht(e,"lvl")){let n=wn(r),o=ht(r,"numFmt")[0]?.getAttribute("w:val")||null;n!=null&&o&&t.set(n,o)}return t}function Hs(e){return e==="bullet"||e==="circle"||e==="square"?"bullet":e}function qs(e){return jt(e).map(t=>{let r=Xe(t.parentNode,"ilvl")[0];return{numIdElement:t,numId:nr(t),ilvl:r?nr(r)??0:0}})}function Vw(e,t,r,n){let o=n?.sourceNumberingXml;if(!e||!String(o||"").trim()||!Array.isArray(t))return null;let a=new Set;for(let p of r||[])for(let{numId:g}of qs(p))g!=null&&g!==0&&a.add(g);if(a.size!==1)return null;let[i]=a,l=Ve(o),s=Ve(e);if(Ft(l)||Ft(s))return null;let c=Ho(l,i);if(!c)return null;let f=Pf(c),u=[];for(let p of t)kt(p)||u.push(...qs(p));if(u.length===0)return null;let d=new Map;for(let{numId:p,ilvl:g}of u){if(p==null)return null;if(!d.has(p)){let w=Ho(s,p);if(!w)return null;d.set(p,Pf(w))}let h=d.get(p).get(g),v=f.get(g);if(!h||!v||Hs(h)!==Hs(v))return null}let m=t.map(p=>p?.cloneNode?p.cloneNode(!0):p);for(let p of m)if(!kt(p))for(let g of jt(p))g.setAttribute("w:val",String(i));return{numId:i,replacementNodes:m}}function Ys(e){let{numberingXml:t,replacementNodes:r,sourceParagraphs:n,numberingIdState:o,allowContinueSource:a=!0}=e||{};if(t&&o&&a){let i=Vw(t,r,n,o);if(i)return{policy:"continue-source",numberingXml:null,replacementNodes:i.replacementNodes,numId:i.numId}}if(t&&o){let i=mn(t,r,o);return{policy:"allocate",numberingXml:i.numberingXml,replacementNodes:i.replacementNodes}}return{policy:"passthrough",numberingXml:t??null,replacementNodes:r}}function Ww(e,t,r){let n=String(r||"").replace(/%\d+/g,"").trim()||".";return`list-format:${e}:${t}:${e==="bullet"?"":n}`}function Kw(e,t){let r=[];for(let p of t||[])kt(p)||r.push(...qs(p));if(r.length===0)return null;let{numId:n,ilvl:o}=r[0];if(n==null||n===0||r.some(p=>p.numId!==n||p.ilvl!==o))return null;let a=Ve(e);if(Ft(a))return null;let i=ht(a,"num").find(p=>ut(p,["w:numId","numId"])===Number(n)),l=Ho(a,n),s=ht(l,"lvl").find(p=>wn(p)===o),c=ht(s,"numFmt")[0]?.getAttribute("w:val");if(!i||!s||!c)return null;let f=ht(s,"lvlText")[0]?.getAttribute("w:val")||"",u=Xe(i,"lvlOverride").find(p=>wn(p)===o),d=nr(Xe(u,"startOverride")[0])??nr(ht(s,"start")[0])??1,m=Hs(c)==="bullet";return{numId:n,ilvl:o,count:r.length,isBullet:m,start:d,key:Ww(m?"bullet":c,o,f)}}function Of({numberingXml:e,replacementNodes:t,sequence:r,isNumIdLive:n}){if(!(r instanceof Map)||!e)return null;let o=Kw(e,t);if(!o)return null;let a=r.get(o.key)||null,l=a&&a.numId!=null&&(typeof n!="function"||n(a.numId))&&(o.isBullet||a.nextStartAt===o.start),s=o.isBullet?null:o.start+o.count;if(!l)return r.set(o.key,{numId:String(o.numId),nextStartAt:s}),null;let c=t.map(f=>f?.cloneNode?f.cloneNode(!0):f);for(let f of c)if(!kt(f))for(let u of jt(f))u.setAttribute("w:val",String(a.numId));return r.set(o.key,{numId:String(a.numId),nextStartAt:s}),{numId:a.numId,replacementNodes:c}}function Gw(e,t,r){let n=Array.from(e.childNodes||[]).filter(a=>a&&a.nodeType===1&&a.namespaceURI===fe),o=r==="abstract"?n.find(a=>a.localName==="num"||a.localName==="numIdMacAtCleanup"):n.find(a=>a.localName==="numIdMacAtCleanup");o?e.insertBefore(t,o):e.appendChild(t)}function kf(e,t,r={}){let n=String(e||""),o=String(t||"");if(!o.trim())return n;if(!n.trim())return o;try{let a=Ve(n),i=Ve(o);if(Ft(a)||Ft(i))return n;let l=a.documentElement,s=i.documentElement;if(!l||!s)return n;for(let[c,f,u]of[["abstract","abstractNum","abstractNumId"],["num","num","numId"]]){let d=new Map(Xe(l,f).map(m=>[ut(m,[`w:${u}`,u]),m]).filter(([m])=>m!=null));for(let m of Xe(s,f)){let p=ut(m,[`w:${u}`,u]);if(p==null)continue;let g=d.get(p);if(g){typeof r?.onConflict=="function"&&Go(g,!1)!==Go(m,!1)&&r.onConflict({kind:f,id:p});continue}let h=a.importNode(m,!0);Gw(l,h,c),d.set(p,h)}}return Kt(a)}catch{return n}}function vr(e,t,r={}){let n=String(e||"");for(let o of(Array.isArray(t)?t:[t]).filter(Boolean))n=kf(n,o,r);return n}function Mf(e,t,r=0){let n=Number(t),o=String(e?.sourceNumberingXml||""),a=o.trim()?Ve(o):null,i=a&&!Ft(a)?ht(a,"num").find(f=>ut(f,["w:numId","numId"])===n):null;if(!i)return e?.usedNumIds instanceof Set&&e.usedNumIds.has(n)?{ok:!0}:{ok:!1,reason:"unknown-num",message:`numbering.numId ${n} does not exist in the document's numbering definitions.`};let l=Ho(a,n);if(!l)return{ok:!1,reason:"missing-abstract",message:`numId ${n} points at an abstractNum that does not exist.`};let s=f=>Xe(f,"lvl").some(u=>Number.parseInt(u.getAttribute("w:ilvl")??u.getAttribute("ilvl")??"0",10)===r),c=Xe(i,"lvlOverride").some(f=>s(f));return!s(l)&&!c?{ok:!1,reason:"undefined-level",message:`numId ${n} does not define list level ${r}.`}:{ok:!0}}function ro(e,t){let r=[],n=new Set,o=(u,d,m={})=>{let p=`${u}:${m.numId??""}:${m.abstractNumId??""}:${m.ilvl??""}`;n.has(p)||(n.add(p),r.push({code:u,severity:"error",message:d,...m}))},a=typeof e=="string"?Ve(e):e;if(!a||Ft(a))return r;let i=typeof t=="string"?t.trim()?Ve(t):null:t||null,l=i&&!Ft(i),s=new Map,c=new Map;if(l){for(let[u,d,m]of[["abstractNum","abstractNumId",s],["num","numId",c]])for(let p of ht(i,u)){let g=ut(p,[`w:${d}`,d]);g!=null&&(m.has(g)?o("NUMBERING_DUPLICATE_ID",`Numbering part defines ${u} ${g} more than once.`,{[d]:g}):m.set(g,p))}for(let[u,d]of c){let m=nr(Xe(d,"abstractNumId")[0]);m==null?o("NUMBERING_ABSTRACT_UNDEFINED",`w:num ${u} has no w:abstractNumId.`,{numId:u}):s.has(m)||o("NUMBERING_ABSTRACT_UNDEFINED",`w:num ${u} references missing w:abstractNum ${m}.`,{numId:u,abstractNumId:m})}}let f=(u,d)=>{let m=c.get(u),p=s.get(nr(Xe(m,"abstractNumId")[0]));return!p||ht(p,"lvl").some(g=>wn(g)===d)?!0:Xe(m,"lvlOverride").some(g=>wn(g)===d&&Xe(g,"lvl").length>0)};for(let u of Array.from(a.getElementsByTagNameNS(fe,"p"))){let d=[at(u).numPr,Bc(u)?.numPr];for(let m of d){if(!m?.numIdElement)continue;let p=nr(m.numIdElement);if(p==null||p===0)continue;if(!l||!c.has(p)){o("NUMBERING_NUM_UNDEFINED",`w:numId ${p} is used in the document but no w:num defines it.`,{numId:p});continue}let g=m.ilvlElement?nr(m.ilvlElement):null;g!=null&&!f(p,g)&&o("NUMBERING_LEVEL_UNDEFINED",`w:ilvl ${g} is used with w:numId ${p} but its abstractNum does not define that level.`,{numId:p,ilvl:g})}}return r}function Hw(e){return!e||!e.documentElement||e.documentElement.localName==="parsererror"?!0:!!$e(e)}function Lf(e){let t=V(e,"application/xml");return t.error||Hw(t.doc)?{...t,doc:null}:t}function Bf(e){if(!e)return[];let t=Array.from(e.getElementsByTagNameNS(B,"p"));return t.length>0?t:Array.from(e.getElementsByTagNameNS("*","p")).filter(r=>r?.localName==="p")}function Yo(e,t){if(!e)return"";for(let r of t){let n=e.getAttribute(r);if(n!=null&&n!=="")return n}return""}function qw(e){let t=Lc(e);if(!t)return{bold:!1,italic:!1};let r=Qe(t,"rStyle"),n=Yo(r,["w:val","val"]).toLowerCase(),o=n.includes("strong")||n.includes("bold"),a=n.includes("italic")||n.includes("emphasis");return{bold:!!Qe(t,"b")||o,italic:!!Qe(t,"i")||a}}function $f(e){let t=[],r=Array.from(e?.getElementsByTagNameNS?.(B,"r")||[]);for(let n of r){if(!tn(n,e,"accepted"))continue;let o=gr(n,{boundary:e,revisionView:"accepted"});o&&t.push({text:o,...qw(n)})}return t}function Js(e){return String(e||"").replace(/\r/g,"").split(`
|
|
198
198
|
`).map(r=>r.replace(/[ \t]+/g," ").trim()).join(`
|
|
199
|
-
`).trim()}function
|
|
199
|
+
`).trim()}function Yw(e,t){let r=String(e||"");if(!r)return"";if(!t?.bold&&!t?.italic)return r;let n=r.match(/^(\s*)([\s\S]*?)(\s*)$/);if(!n)return r;let o=n[1]||"",a=n[2]||"",i=n[3]||"";if(!a.trim())return r;let l=a;return t.bold&&t.italic?l=`***${a}***`:t.bold?l=`**${a}**`:t.italic&&(l=`*${a}*`),`${o}${l}${i}`}function Jw(e){let{pPr:t,pStyleElement:r,outlineLvlElement:n}=at(e);if(!t)return null;let o=Yo(r,["w:val","val"]);if(o){let l=o.match(/^heading\s*([1-9])$/i);if(l){let s=Number.parseInt(l[1],10);if(Number.isInteger(s))return Math.min(Math.max(s,1),6)}}let a=Yo(n,["w:val","val"]),i=Number.parseInt(a,10);return Number.isInteger(i)&&i>=0?Math.min(i+1,6):null}function Zw(e){let{numPr:t}=at(e);if(!t)return null;let r=t.ilvlElement,n=t.numIdElement,o=Number.parseInt(Yo(r,["w:val","val"]),10),a=Yo(n,["w:val","val"]);return{level:Number.isInteger(o)&&o>=0?o:0,marker:a==="1"?"-":"1."}}function Qw(e){let t=$f(e).map(r=>r.text).join("");return Js(t)}function ev(e){let r=$f(e).map(i=>Yw(i.text,i)).join(""),n=Js(r);if(!n)return"";let o=Jw(e);if(o!=null)return`${"#".repeat(o)} ${n}`;let a=Zw(e);return a?`${" ".repeat(a.level)}${a.marker} ${n}`:n}function tv(e){return Ff(e).text}function Ff(e){let t=Lf(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=Bf(r);return n.length===0?{text:Js(r.documentElement?.textContent||""),status:"ok",warnings:t.warnings}:{text:n.map(Qw).join(`
|
|
200
200
|
|
|
201
|
-
`).trim(),status:"ok",warnings:t.warnings}}function
|
|
201
|
+
`).trim(),status:"ok",warnings:t.warnings}}function rv(e){return Df(e).text}function Df(e){let t=Lf(e);if(!t.doc)return{text:"",status:"error",error:t.error,warnings:t.warnings};let r=t.doc,n=Bf(r);return n.length===0?{text:"",status:"ok",warnings:t.warnings}:{text:n.map(ev).join(`
|
|
202
202
|
|
|
203
|
-
`).trim(),status:"ok",warnings:t.warnings}}var
|
|
204
|
-
<w:p w14:paraId="${
|
|
203
|
+
`).trim(),status:"ok",warnings:t.warnings}}var no="http://schemas.microsoft.com/office/word/2010/wordml",ft="http://schemas.microsoft.com/office/word/2012/wordml";function Zs(e){let t=Number.parseInt(String(e),10);return(Number.isFinite(t)?1879048192+(t>>>0)>>>0:1879048192).toString(16).toUpperCase().padStart(8,"0").slice(-8)}function Jo(e,t,r,n,o=Zs(e)){let a=t.split(" ").map(s=>s[0]).join("").toUpperCase()||"AI",i=Ze(r),l=Ze(t);return`<w:comment w:id="${e}" w:author="${l}" w:date="${n}" w:initials="${a}">
|
|
204
|
+
<w:p w14:paraId="${Ze(o)}" xmlns:w14="${no}">
|
|
205
205
|
<w:r><w:t>${i}</w:t></w:r>
|
|
206
206
|
</w:p>
|
|
207
|
-
</w:comment>`}function
|
|
207
|
+
</w:comment>`}function Qs(e){if(!e||e.length===0)return`<w:comments xmlns:w="${B}"></w:comments>`;let t=e.map(r=>Jo(r.id,r.author,r.content,r.date,r.paraId)).join(`
|
|
208
208
|
`);return`<w:comments xmlns:w="${B}">
|
|
209
209
|
${t}
|
|
210
|
-
</w:comments>`}function _f(e){let t=(e||[]).map(r=>{let n=r.paraIdParent?` w15:paraIdParent="${Ye(r.paraIdParent)}"`:"";return`<w15:commentEx w15:paraId="${Ye(r.paraId)}"${n} w15:done="${r.done?"1":"0"}"/>`}).join("");return`<w15:commentsEx xmlns:w15="${ct}">${t}</w15:commentsEx>`}var It=(e,t,r)=>e?.getAttribute?.(t)||e?.getAttribute?.(r)||"";function oi(e){let t=Array.from(e?.getElementsByTagNameNS?.("*","p")||[]);return t.length?t[t.length-1]:null}function xt(e){return It(oi(e),"w14:paraId","paraId").toUpperCase()}function qs(e,t){let r=new Set;for(let n of Array.from(e?.getElementsByTagNameNS("*","p")||[])){let o=It(n,"w14:paraId","paraId");o&&r.add(o.toUpperCase())}for(let n of Array.from(t?.getElementsByTagNameNS("*","commentEx")||[])){let o=It(n,"w15:paraId","paraId");o&&r.add(o.toUpperCase())}return r}function ai(e,t){let r=js(e),n=Number.parseInt(r,16)>>>0;for(;t.has(r);)n=n+1>>>0,r=n.toString(16).toUpperCase().padStart(8,"0");return t.add(r),r}var Ks=(e,t)=>{let r=j(e,"application/xml");return!r.doc||r.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${r.error?.message||"invalid XML"}`}}:{doc:r.doc}};function ii({commentsXml:e,commentsExtendedXml:t=null,commentId:r,resolved:n=!0}){if(!e)return{status:"error",error:{code:"COMMENTS_PART_MISSING",message:"Resolving a comment requires an existing word/comments.xml part."}};let o=Ks(e,"word/comments.xml");if(o.error)return{status:"error",error:o.error};let a=o.doc,i=T=>It(T,"w:id","id"),l=Array.from(a.getElementsByTagNameNS("*","comment")),s=l.find(T=>i(T)===String(r));if(!s)return{status:"error",error:{code:"COMMENT_NOT_FOUND",message:`Comment '${r}' was not found.`}};let c;if(t){let T=Ks(t,"word/commentsExtended.xml");if(T.error)return{status:"error",error:T.error};c=T.doc}else c=Ks(`<w15:commentsEx xmlns:w15="${ct}"/>`,"word/commentsExtended.xml").doc;let f=c.documentElement,u=T=>Array.from(f.getElementsByTagNameNS("*","commentEx")).find(A=>It(A,"w15:paraId","paraId").toUpperCase()===T)||null,d=qs(a,c),m=!1,g=(T=>{let A=xt(T);return A||(A=ai(i(T),d),oi(T)?.setAttributeNS(eo,"w14:paraId",A),m=!0),A})(s),h=u(g),v=h&&It(h,"w15:paraIdParent","paraIdParent").toUpperCase()||g,w=new Set([v,g]);for(let T of Array.from(f.getElementsByTagNameNS("*","commentEx")))It(T,"w15:paraIdParent","paraIdParent").toUpperCase()===v&&w.add(It(T,"w15:paraId","paraId").toUpperCase());let y=n?"1":"0",b=!t;for(let T of w){let A=u(T);A?It(A,"w15:done","done")!==y&&(A.setAttributeNS(ct,"w15:done",y),b=!0):(A=c.createElementNS(ct,"w15:commentEx"),A.setAttributeNS(ct,"w15:paraId",T),T!==v&&A.setAttributeNS(ct,"w15:paraIdParent",v),A.setAttributeNS(ct,"w15:done",y),f.appendChild(A),b=!0)}let I=new Map(l.map(T=>[xt(T),T])),E=[...w].map(T=>I.get(T)).filter(Boolean).map(i),N=I.get(v),R=se(),x=b||m;return{status:"ok",hasChanges:x,resolved:n,threadRootId:N?i(N):String(r),commentIds:E,...x?{commentsExtendedXml:R.serializeToString(c)}:{},...m?{commentsXml:R.serializeToString(a)}:{}}}var ni="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Of(e,t,r){let n=new Set(t.map(String)),o=g=>It(g,"w:id","id"),a=g=>Array.from(e.getElementsByTagNameNS("*",g)).filter(h=>n.has(o(h))),i=a("commentRangeStart"),l=a("commentReference");if(!i.length||!l.length)return!1;let s=i[i.length-1],c=l[l.length-1],f=c.parentNode?.localName==="r"?c.parentNode:c,u=(g,h)=>{let v=e.createElementNS(ni,`w:${g}`);return v.setAttributeNS(ni,"w:id",String(r)),h&&h.appendChild(v),v},d=(g,h)=>g.parentNode.insertBefore(h,g.nextSibling);d(s,u("commentRangeStart"));let m=u("commentRangeEnd"),p=e.createElementNS(ni,"w:r");return p.appendChild(e.createElementNS(ni,"w:rPr")),u("commentReference",p),d(f,m),d(m,p),!0}var Gs="http://schemas.microsoft.com/office/word/2016/wordml/cid",Hs="http://schemas.microsoft.com/office/word/2018/wordml/cex",Hw=(e,t)=>{let r=(Number.parseInt(e,16)^625341585)&2147483646,n=r.toString(16).toUpperCase().padStart(8,"0");for(;t.has(n);)r=r+2&2147483646,n=r.toString(16).toUpperCase().padStart(8,"0");return t.add(n),n};function kf({commentsXml:e,commentsIdsXml:t=null,commentsExtensibleXml:r=null}){let n={};if(!e||!t&&!r)return n;let o=j(e,"application/xml");if(!o.doc||o.error)return n;let a=se(),i=new Map;for(let m of Array.from(o.doc.getElementsByTagNameNS("*","comment"))){let p=xt(m);p&&i.set(p,m)}let l=null,s=new Map,c=new Set,f=!1;if(t){let m=j(t,"application/xml");if(!m.doc||m.error)return n;l=m.doc;let p=l.documentElement;for(let g of Array.from(p.getElementsByTagNameNS("*","commentId"))){let h=It(g,"w16cid:paraId","paraId").toUpperCase(),v=It(g,"w16cid:durableId","durableId").toUpperCase();if(v&&c.add(v),!i.has(h)){p.removeChild(g),f=!0;continue}s.set(h,v)}for(let g of i.keys()){if(s.has(g))continue;let h=Hw(g,c),v=l.createElementNS(Gs,"w16cid:commentId");v.setAttributeNS(Gs,"w16cid:paraId",g),v.setAttributeNS(Gs,"w16cid:durableId",h),p.appendChild(v),s.set(g,h),f=!0}}let u=null,d=!1;if(r&&l){let m=j(r,"application/xml");if(m.doc&&!m.error){u=m.doc;let p=u.documentElement,g=new Set(s.values()),h=new Set;for(let v of Array.from(p.getElementsByTagNameNS("*","commentExtensible"))){let w=It(v,"w16cex:durableId","durableId").toUpperCase();g.has(w)?h.add(w):(p.removeChild(v),d=!0)}for(let[v,w]of s){if(h.has(w))continue;let y=It(i.get(v),"w:date","date"),b=u.createElementNS(Hs,"w16cex:commentExtensible");b.setAttributeNS(Hs,"w16cex:durableId",w),y&&b.setAttributeNS(Hs,"w16cex:dateUtc",y),p.appendChild(b),d=!0}}}return f&&(n.commentsIdsXml=a.serializeToString(l)),d&&(n.commentsExtensibleXml=a.serializeToString(u)),n}var qw=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Yw=new TextEncoder;function qo(e){let t;if(typeof e=="string")t=Yw.encode(e);else if(e instanceof Uint8Array)t=e;else if(e instanceof ArrayBuffer)t=new Uint8Array(e);else if(ArrayBuffer.isView(e))t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else throw new TypeError("sha256 input must be a string, Uint8Array, Buffer, or ArrayBuffer.");let r=t.length,n=r*8,o=Math.ceil((r+9)/64)*64,a=new Uint8Array(o);a.set(t,0),a[r]=128;let i=new DataView(a.buffer,a.byteOffset,a.byteLength),l=Math.floor(n/4294967296),s=n>>>0;i.setUint32(o-8,l,!1),i.setUint32(o-4,s,!1);let c=1779033703,f=3144134277,u=1013904242,d=2773480762,m=1359893119,p=2600822924,g=528734635,h=1541459225,v=new Uint32Array(64);for(let y=0;y<o;y+=64){for(let S=0;S<16;S++)v[S]=i.getUint32(y+S*4,!1);for(let S=16;S<64;S++){let O=v[S-15],C=(O>>>7|O<<25)^(O>>>18|O<<14)^O>>>3,P=v[S-2],M=(P>>>17|P<<15)^(P>>>19|P<<13)^P>>>10;v[S]=v[S-16]+C+v[S-7]+M|0}let b=c,I=f,E=u,N=d,R=m,x=p,T=g,A=h;for(let S=0;S<64;S++){let O=(R>>>6|R<<26)^(R>>>11|R<<21)^(R>>>25|R<<7),C=R&x^~R&T,P=A+O+C+qw[S]+v[S]|0,M=(b>>>2|b<<30)^(b>>>13|b<<19)^(b>>>22|b<<10),_=b&I^b&E^I&E,k=M+_|0;A=T,T=x,x=R,R=N+P|0,N=E,E=I,I=b,b=P+k|0}c=c+b|0,f=f+I|0,u=u+E|0,d=d+N|0,m=m+R|0,p=p+x|0,g=g+T|0,h=h+A|0}let w=y=>(y>>>0).toString(16).padStart(8,"0");return w(c)+w(f)+w(u)+w(d)+w(m)+w(p)+w(g)+w(h)}var to=new TextEncoder;function Mf(e){if(typeof e!="string")throw new TypeError(`Entry name must be a string, got ${typeof e}`);let t=e.replace(/\\/g,"/");for(t=t.replace(/^\/+/,"");t.startsWith("./");)t=t.slice(2);if(t=t.replace(/\/+/g,"/"),!t)throw new Error(`Invalid empty entry name: "${e}"`);return t}function Ys({scope:e,entries:t=[]}){if(typeof e!="string"||!e)throw new TypeError("Revision token scope must be a non-empty string.");let r=to.encode("docx-redline-revision-token\0"),n=1,o=to.encode(e),a=[],i=new Set,l=Array.isArray(t)?t:t instanceof Map?Array.from(t.entries()):Object.entries(t||{});for(let d of l){if(!d)continue;let m=Array.isArray(d)?d[0]:d.name,p=Array.isArray(d)?d[1]:d.payload??d.bytes;if(m==null)continue;let g=Mf(String(m));if(i.has(g))throw new Error(`Duplicate normalized entry path detected: "${g}"`);i.add(g);let h;typeof p=="string"?h=to.encode(p):p instanceof Uint8Array?h=p:p&&typeof p.length=="number"?h=new Uint8Array(p):h=new Uint8Array(0),a.push({name:g,nameBytes:to.encode(g),payloadBytes:h})}a.sort((d,m)=>d.name<m.name?-1:d.name>m.name?1:0);let s=r.length+4+4+o.length+4;for(let d of a)s+=4+d.nameBytes.length+4+d.payloadBytes.length;let c=new Uint8Array(s),f=new DataView(c.buffer,c.byteOffset,c.byteLength),u=0;c.set(r,u),u+=r.length,f.setUint32(u,n,!1),u+=4,f.setUint32(u,o.length,!1),u+=4,c.set(o,u),u+=o.length,f.setUint32(u,a.length,!1),u+=4;for(let d of a)f.setUint32(u,d.nameBytes.length,!1),u+=4,c.set(d.nameBytes,u),u+=d.nameBytes.length,f.setUint32(u,d.payloadBytes.length,!1),u+=4,c.set(d.payloadBytes,u),u+=d.payloadBytes.length;return{framing:c,scope:e,version:n,coveredParts:a.map(d=>d.name)}}async function Lf({scope:e,entries:t=[],digestFn:r=null}){let{framing:n,coveredParts:o,version:a}=Ys({scope:e,entries:t}),i="";if(typeof r=="function")i=await r(n);else if(typeof globalThis.crypto?.subtle?.digest=="function"){let l=await globalThis.crypto.subtle.digest("SHA-256",n),s=new Uint8Array(l);i=Array.from(s).map(c=>c.toString(16).padStart(2,"0")).join("")}else i=qo(n);return{algorithm:"sha256",version:a,scope:e,value:i,coveredParts:o}}function Yo({scope:e,entries:t=[],digestFn:r=null}){if(r!=null&&typeof r!="function")throw new TypeError("computeRevisionTokenSync requires a synchronous digestFn when specified.");let{framing:n,coveredParts:o,version:a}=Ys({scope:e,entries:t}),i=typeof r=="function"?r(n):qo(n);return{algorithm:"sha256",version:a,scope:e,value:i,coveredParts:o}}function si(e){let t=[];if(e?.documentXml&&t.push({name:"word/document.xml",payload:e.documentXml}),e?.commentsXml&&t.push({name:"word/comments.xml",payload:e.commentsXml}),e?.commentsExtendedXml&&t.push({name:"word/commentsExtended.xml",payload:e.commentsExtendedXml}),e?.numberingXml&&t.push({name:"word/numbering.xml",payload:e.numberingXml}),e?.stylesXml&&t.push({name:"word/styles.xml",payload:e.stylesXml}),e?.parts instanceof Map)for(let[r,n]of e.parts.entries())t.push({name:r,payload:n});else if(e?.additionalParts&&typeof e.additionalParts=="object")for(let[r,n]of Object.entries(e.additionalParts))t.push({name:r,payload:n});return t}async function Jo(e,t={}){let r=si(e);return Lf({scope:"document-parts",entries:r,digestFn:t.digestFn})}function hn(e){return!e||typeof e!="object"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:"Revision token must be an object."}}:e.algorithm!=="sha256"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token algorithm: "${e.algorithm}". Expected "sha256".`}}:e.version!==1?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token version: "${e.version}". Expected 1.`}}:e.scope!=="document-parts"&&e.scope!=="package"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token scope: "${e.scope}". Expected "document-parts" or "package".`}}:typeof e.value!="string"||!/^[0-9a-f]{64}$/i.test(e.value.trim())?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:"Revision token value must be a 64-character hex string."}}:{valid:!0}}function wn(e,t){if(typeof e!="string"||typeof t!="string")return!1;let r=e.trim().toLowerCase(),n=t.trim().toLowerCase();if(r.length!==n.length)return!1;let o=to.encode(r),a=to.encode(n),i=0;for(let l=0;l<o.length;l++)i|=o[l]^a[l];return i===0}var xe=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"",qt=(e,t)=>Array.from(e?.getElementsByTagNameNS?.(B,t)||[]),wr=(e,t)=>qt(e,t)[0]||null,vn=(e,t)=>Array.from(e?.childNodes||[]).find(r=>r?.nodeType===1&&r.localName===t&&(!r.namespaceURI||r.namespaceURI===B))||null,Js=e=>vn(e,"pPr");function Bf(e,t){let r=e?.parentNode;for(;r;){if(r.localName===t&&(!r.namespaceURI||r.namespaceURI===B))return!0;r=r.parentNode}return!1}function li(e,t,r=!1){if(!e)return r?{error:{code:"MISSING_PART",message:`Missing ${t}.`}}:{doc:null};let n=j(e,"application/xml");return!n.doc||n.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${n.error?.message||"invalid XML"}`}}:{doc:n.doc,warnings:n.warnings||[]}}function Jw(e){let t=vn(Js(e),"numPr");if(!t)return null;let r=xe(vn(t,"numId"),"val");return!r||r==="0"?null:{numId:r,level:Number.parseInt(xe(vn(t,"ilvl"),"val")||"0",10)||0}}function Zw(e){let t=new Map;for(let n of qt(e,"abstractNum")){let o=new Map;for(let a of qt(n,"lvl")){let i=Number.parseInt(xe(a,"ilvl")||"0",10)||0;o.set(i,{start:Number.parseInt(xe(wr(a,"start"),"val")||"1",10)||1,format:xe(wr(a,"numFmt"),"val")||"decimal",text:xe(wr(a,"lvlText"),"val")||`%${i+1}.`})}t.set(xe(n,"abstractNumId"),o)}let r=new Map;for(let n of qt(e,"num")){let o=xe(wr(n,"abstractNumId"),"val"),a=new Map(t.get(o)||[]);for(let i of qt(n,"lvlOverride")){let l=Number.parseInt(xe(i,"ilvl")||"0",10)||0,s=wr(i,"lvl"),c={...a.get(l)||{start:1,format:"decimal",text:`%${l+1}.`}};s&&(c.start=Number.parseInt(xe(wr(s,"start"),"val")||String(c.start),10)||c.start,c.format=xe(wr(s,"numFmt"),"val")||c.format,c.text=xe(wr(s,"lvlText"),"val")||c.text);let f=wr(i,"startOverride");f&&(c.start=Number.parseInt(xe(f,"val")||String(c.start),10)||c.start),a.set(l,c)}r.set(xe(n,"numId"),a)}return r}function Ff(e,t){let r=Math.max(1,e),n="";for(;r>0;)r-=1,n=String.fromCharCode(97+r%26)+n,r=Math.floor(r/26);return t?n.toUpperCase():n}function $f(e){let t=[[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"]],r=e,n="";for(let[o,a]of t)for(;r>=o;)n+=a,r-=o;return n}function Qw(e,t){return t==="lowerLetter"?Ff(e,!1):t==="upperLetter"?Ff(e,!0):t==="lowerRoman"?$f(e).toLowerCase():t==="upperRoman"?$f(e):String(e)}function ev(e){let t=e?Zw(e):new Map,r=new Map;return n=>{if(!n?.numId)return null;let o=t.get(String(n.numId));if(!o)return{...n,label:null,format:null};let a=r.get(n.numId)||[],i=o.get(n.level)||{start:1,format:"decimal",text:`%${n.level+1}.`};a[n.level]=a[n.level]==null?i.start:a[n.level]+1,a.length=n.level+1,r.set(n.numId,a);let l=i.text.replace(/%([1-9])/g,(s,c)=>{let f=Number(c)-1,u=o.get(f)||i;return Qw(a[f]??u.start,u.format)});return{...n,label:l,format:i.format}}}function tv(e){let t=Js(e),n=xe(vn(t,"pStyle"),"val").match(/^heading\s*([1-9])$/i);if(n)return Math.min(Number(n[1]),6);let o=Number.parseInt(xe(vn(t,"outlineLvl"),"val"),10);return Number.isInteger(o)?Math.min(o+1,6):null}function rv(e,t){let r=[];for(let[l,s]of[["footnoteReference","footnote"],["endnoteReference","endnote"],["commentReference","comment"]])for(let c of qt(e,l))r.push({type:s,id:xe(c,"id")||null});let n=e.parentNode;for(;n&&n.localName!=="tc";)n=n.parentNode;let o=n?.parentNode;for(;o&&o.localName!=="tr";)o=o.parentNode;let a=o?.parentNode;for(;a&&a.localName!=="tbl";)a=a.parentNode;let i=e.ownerDocument;return{references:r,table:a?{tableIndex:Array.from(i.getElementsByTagNameNS(B,"tbl")).indexOf(a)+1,rowIndex:Array.from(a.getElementsByTagNameNS(B,"tr")).indexOf(o)+1,cellIndex:Array.from(o.getElementsByTagNameNS(B,"tc")).indexOf(n)+1}:null,empty:t.length===0}}function Df(e){let t=new Set;for(let r of["ins","del","moveFrom","moveTo","rPrChange","pPrChange"])for(let n of qt(e,r))xe(n,"author")&&t.add(xe(n,"author"));return[...t].sort()}function nv(e){let t=new Map;for(let r of qt(e,"comment")){let n=qt(r,"p");t.set(xe(r,"id"),{id:xe(r,"id"),author:xe(r,"author")||null,date:xe(r,"date")||null,text:n.map(o=>Q(o)).join(`
|
|
211
|
-
`),paraId:
|
|
212
|
-
`)}),n}function iv(e,t){let r=e;if(t.revisedOnly&&(r=r.filter(p=>p.hasRevisions)),t.inTable!=null&&(r=r.filter(p=>p.inTable===!!t.inTable)),t.skipEmpty&&(r=r.filter(p=>p.text.length>0)),t.search){let p=String(t.search).toLowerCase();r=r.filter(g=>g.text.toLowerCase().includes(p))}if(Array.isArray(t.indexes)){let p=new Set(t.indexes);r=r.filter(g=>p.has(g.index))}let n=1,o=e.length;t.range&&(n=Number(t.range.start??t.range[0]),o=Number(t.range.end??t.range[1]),r=r.filter(p=>p.index>=n&&p.index<=o));let a=r.length,i=Number.isInteger(t.after)&&t.after>0?t.after:null,l=i==null?r:r.filter(p=>p.index>i),s=Number.isInteger(t.limit)&&t.limit>0?t.limit:null,c=s==null?l:l.slice(0,s),f=c.length<l.length,u=Number.isInteger(t.around)&&t.around>0?t.around:0,d=!!t.search||u>0||s!=null||i!=null,m=c;if(u>0&&t.search){let p=new Set(c.map(v=>v.index)),g=new Map;for(let v of c){let w=Math.max(n,v.index-u),y=Math.min(o,v.index+u);for(let b=w;b<=y;b++){if(p.has(b))continue;let I=g.get(b)||[];I.push(v.index),g.set(b,I)}}let h=new Set([...p,...g.keys()]);m=e.filter(v=>h.has(v.index)).map(v=>p.has(v.index)?{...v,selectionRole:"match"}:{...v,selectionRole:"context",contextFor:g.get(v.index)||[]})}else d&&(m=c.map(p=>({...p,selectionRole:"match"})));return{paragraphs:m,...d?{selection:{...t.search?{search:String(t.search),caseSensitive:!1}:{},totalMatches:a,returnedMatches:c.length,returnedParagraphs:m.length,truncated:f,nextAfter:f&&c.length>0?c[c.length-1].index:null,...s!=null?{limit:s}:{},...i!=null?{after:i}:{},...u>0?{around:u}:{}}}:{}}}function ci(e,t={}){let r=li(e?.documentXml,"word/document.xml",!0);if(r.error)return{status:"error",error:r.error,paragraphs:[],comments:[],warnings:[]};let n=li(e?.commentsXml,"word/comments.xml"),o=li(e?.commentsExtendedXml,"word/commentsExtended.xml"),a=li(e?.numberingXml,"word/numbering.xml"),i=[...r.warnings||[]];n.error&&i.push(n.error.message),o.error&&i.push(o.error.message),a.error&&i.push(a.error.message);let l=nv(n.doc);ov(l,o.doc);let s=ev(a.doc),c=null,f=ae(r.doc),u=t.revisionView==="rejected"?"rejected":"accepted",d=av(f,u),m=f.map((y,b)=>{let I=Q(y,{revisionView:u}),E=tv(y);E&&(c={level:E,text:I});let N=[...new Set([...qt(y,"commentRangeStart"),...qt(y,"commentReference")].map(k=>xe(k,"id")).filter(Boolean))],R=Df(y),x=s(Jw(y)),T=xe(vn(Js(y),"pStyle"),"val")||null,A=rv(y,I),S=b+1,O=x?.label&&x.format!=="bullet"?x.label:null,C=c?.text||null,P=I.slice(0,t.excerptLength||120),M=E?I:O?[O,C].filter(Boolean).join(" \u2014 "):C?[C,P].filter(Boolean).join(" \u2014 "):P,_=Pa(y);return{index:S,ref:`P${S}`,paragraphId:Ke(y),fingerprint:_t(y,{text:I,index:S,revisionView:u}),revisionView:u,text:I,exactText:I,excerpt:P,humanReference:M,provision:O,inTable:Bf(y,"tc"),table:A.table,styleId:T,headingLevel:E,nearestHeading:c,list:x,structuralReferences:A.references,hasRevisions:R.length>0,revisionAuthors:R,commentIds:N,segments:_}});for(let y of m)for(let b of y.commentIds){let I=l.get(b)||{id:b,author:null,date:null,text:""};I.paragraphIndex??(I.paragraphIndex=y.index),I.targetRef??(I.targetRef=y.ref),I.anchoredText??(I.anchoredText=d.get(b)||y.text),l.set(b,I)}let p=iv(m,t);if(t.search&&p.selection&&p.selection.totalMatches===0){let y=String(t.search).toLowerCase(),b=u==="accepted"?"rejected":"accepted",I=1,E=f.length;t.range&&(I=Number(t.range.start??t.range[0]),E=Number(t.range.end??t.range[1]));let N=0;for(let R=0;R<f.length;R++){let x=R+1;if(t.range&&(x<I||x>E)||Array.isArray(t.indexes)&&!t.indexes.includes(x))continue;let T=f[R];if(t.inTable!=null&&Bf(T,"tc")!==!!t.inTable||t.revisedOnly&&Df(T).length===0)continue;let A=Q(T,{revisionView:b});t.skipEmpty&&A.length===0||A.toLowerCase().includes(y)&&N++}N>0&&(p.selection.hint=u==="accepted"?`0 matches in accepted view, but ${N} match${N===1?"":"es"} found in --view rejected. If searching for deleted text to restore, re-run with --view rejected.`:`0 matches in rejected view, but ${N} match${N===1?"":"es"} found in --view accepted. Re-run with --view accepted.`)}m=p.paragraphs;let g=[...new Set(m.flatMap(y=>y.revisionAuthors))].sort(),h=si(e),v=h.map(y=>y.name).sort(),w=null;return typeof t.digestFn=="function"&&(w=Yo({scope:"document-parts",entries:h,digestFn:t.digestFn})),{status:"ok",revisionToken:w,coveredParts:v,paragraphs:m,...p.selection?{selection:p.selection}:{},comments:[...l.values()],revisionAuthors:g,commentAuthors:[...new Set([...l.values()].map(y=>y.author).filter(Boolean))].sort(),counts:{paragraphs:m.length,comments:l.size,revisedParagraphs:m.filter(y=>y.hasRevisions).length},warnings:i}}function ro(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=So(e,"w:r"),o=[],a="";for(let i of n){if(!Qr(i,e,r))continue;let l=a.length,s=mr(i,{revisionView:r,boundary:e});a+=s,o.push({run:i,start:l,end:a.length})}return{fullText:a,runOffsets:o}}function Uf(e,t){if(!t)return[];let r=[],n=e.indexOf(t);for(;n!==-1;)r.push({start:n,end:n+t.length}),n=e.indexOf(t,n+1);return r}function zf(e){return String(e).replace(/[ \u00a0]/g," ")}function Qo(e,t,r=[]){return{code:e,message:t,...r.length>0?{candidates:r}:{}}}function Xf(e,t,r){let n=null,o=null,a=0,i=0;for(let{run:l,start:s,end:c}of e.runOffsets)t.start>=s&&t.start<c&&(n=l,a=t.start-s),t.end>s&&t.end<=c&&(o=l,i=t.end-s);return!n||!o?null:{found:!0,resolvedBy:r,...t,startRun:n,startOffset:a,endRun:o,endOffset:i}}function Vf(e,t,r=null){let n=e?.parentNode;for(;n&&n.nodeType===1&&n!==r&&(n.localName||n.nodeName.replace(/^.*:/,""))!=="p";){let o=n.localName||n.nodeName.replace(/^.*:/,"");if(t.includes(o))return{node:n,tag:o};n=n.parentNode}return null}function jf(e,t){if(!t||!t.found)return t;let r=e.runOffsets.filter(n=>n.end>t.start&&n.start<t.end).map(n=>n.run);for(let n of r){if(Vf(n,["del"]))return{found:!1,error:Qo("UNSAFE_REVISION_NESTING","Refusing to attach comment to pending deletion.",[t])};if(Vf(n,["moveFrom","moveTo"]))return{found:!1,error:Qo("UNSAFE_REVISION_NESTING","Refusing to comment on move revision until move lifecycle is designed.",[t])}}return t}function ea(e,t){let r=String(t??""),n=Uf(e.fullText,r);if(n.length>1)return{found:!1,error:Qo("AMBIGUOUS_ANCHOR",`Anchor text matched ${n.length} locations in the target paragraph.`,n)};if(n.length===1){let l=Xf(e,n[0],"exact_anchor");if(l)return jf(e,l)}let o=zf(r),a=zf(e.fullText),i=Uf(a,o);if(i.length>1)return{found:!1,error:Qo("AMBIGUOUS_ANCHOR",`Space-equivalent anchor text matched ${i.length} locations in the target paragraph.`,i)};if(i.length===1){let l=Xf(e,i[0],"space_equivalent_anchor");if(l)return jf(e,l)}return{found:!1,error:Qo("ANCHOR_NOT_FOUND",`Could not find anchor text in the target paragraph: "${r}".`)}}function Zo(e,t,r,n,o=!1){let a=F(e,"w:r");if(t){let l=t.cloneNode(!0);o||Bt(l,n),a.appendChild(l)}let i=F(e,"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=r,a.appendChild(i),a}function Wf(e,t,r,n,o=null,a=null,i=null){let l=o||ro(t),s=i||ea(l,r);if(!s.found||!s.startRun)return!1;let c=F(e,"w:commentRangeStart");c.setAttribute("w:id",String(n));let f=F(e,"w:commentRangeEnd");f.setAttribute("w:id",String(n));let u=F(e,"w:r"),d=F(e,"w:commentReference");if(d.setAttribute("w:id",String(n)),u.appendChild(d),s.startRun===s.endRun){let h=s.startRun,v=$e(h,"w:t");if(!v)return h.parentNode.insertBefore(c,h),h.nextSibling?(h.parentNode.insertBefore(f,h.nextSibling),f.parentNode.insertBefore(u,f.nextSibling)):(h.parentNode.appendChild(f),h.parentNode.appendChild(u)),!0;let w=v.textContent||"",y=w.substring(0,s.startOffset),b=w.substring(s.startOffset,s.endOffset),I=w.substring(s.endOffset),E=$e(h,"w:rPr"),N=h.parentNode;return y&&(N.insertBefore(Zo(e,E,y,a,!0),h),Bt(E,a)),N.insertBefore(c,h),v.textContent=b,h.nextSibling?N.insertBefore(f,h.nextSibling):N.appendChild(f),N.insertBefore(u,f.nextSibling||null),I&&N.insertBefore(Zo(e,E,I,a),u.nextSibling||null),!0}let m=$e(s.startRun,"w:t");if(m&&s.startOffset>0){let h=m.textContent||"",v=h.substring(0,s.startOffset),w=h.substring(s.startOffset);if(v){let y=$e(s.startRun,"w:rPr");s.startRun.parentNode.insertBefore(Zo(e,y,v,a,!0),s.startRun),Bt(y,a)}m.textContent=w}s.startRun.parentNode.insertBefore(c,s.startRun);let p=s.endRun||s.startRun,g=$e(p,"w:t");if(g&&s.endOffset<(g.textContent||"").length){let h=g.textContent||"",v=h.substring(0,s.endOffset),w=h.substring(s.endOffset);if(g.textContent=v,w){let y=$e(p,"w:rPr");p.nextSibling?p.parentNode.insertBefore(Zo(e,y,w,a),p.nextSibling):p.parentNode.appendChild(Zo(e,y,w,a))}}return p.nextSibling?(p.parentNode.insertBefore(f,p.nextSibling),f.parentNode.insertBefore(u,f.nextSibling)):(p.parentNode.appendChild(f),p.parentNode.appendChild(u)),!0}var no="http://schemas.microsoft.com/office/2006/xmlPackage",ta="http://schemas.openxmlformats.org/package/2006/relationships";function Kf(e,t){let r=se(),n=j(e,"text/xml"),o=n.doc,a=o?Le(o):null;if(n.error||a)return ke("[CommentEngine] Failed to parse package:",n.error?.message||a?.textContent),e;let i=o.documentElement,l=o.createElementNS(no,"pkg:part");l.setAttribute("pkg:name","/word/comments.xml"),l.setAttribute("pkg:contentType","application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");let s=o.createElementNS(no,"pkg:xmlData"),c=j(t,"text/xml").doc;if(!c)return e;s.appendChild(o.importNode(c.documentElement,!0)),l.appendChild(s),i.appendChild(l);let u=Ve(i,no,"part").find(d=>d.getAttribute("pkg:name")==="/word/_rels/document.xml.rels");if(u){let d=Ve(u,no,"xmlData");if(d.length>0){let m=Ve(d[0],ta,"Relationships");if(m.length>0){let p=m[0],g=Ve(p,ta,"Relationship");if(!g.some(v=>v.getAttribute("Type")?.includes("comments"))){let v=0;g.forEach(y=>{let b=y.getAttribute("Id"),I=parseInt(b?.replace("rId","")||"0",10);I>v&&(v=I)});let w=o.createElementNS(ta,"Relationship");w.setAttribute("Id",`rId${v+1}`),w.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),w.setAttribute("Target","comments.xml"),p.appendChild(w)}}}}else{let d=o.createElementNS(no,"pkg:part");d.setAttribute("pkg:name","/word/_rels/document.xml.rels"),d.setAttribute("pkg:contentType","application/vnd.openxmlformats-package.relationships+xml");let m=o.createElementNS(no,"pkg:xmlData"),p=o.createElementNS(ta,"Relationships"),g=o.createElementNS(ta,"Relationship");g.setAttribute("Id","rId1"),g.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),g.setAttribute("Target","comments.xml"),p.appendChild(g),m.appendChild(p),d.appendChild(m),i.appendChild(d)}return r.serializeToString(o)}function sv(e,t){let r=j(e,"text/xml"),n=r.doc?Le(r.doc):null;if(r.error||n){let o=r.error?.message||n?.textContent||"parse error";return{xmlDoc:null,warning:t(o),warnings:r.warnings,error:{code:"PARSE_ERROR",message:o}}}return{xmlDoc:r.doc,warning:null,warnings:r.warnings,error:null}}function Zs(e,t,r={}){let n=r?.author||oe(),o=ya(),a=[],i=[],l=[],s=[];if(!t||t.length===0)return{oxml:e,hasChanges:!1,commentsApplied:0,warnings:["No comments to inject"]};let c=se(),f=sv(e,h=>`Failed to parse OXML: ${h}`);if(a.push(...f.warnings||[]),!f.xmlDoc)return ke("[CommentEngine] Parse failure:",f.warning),{oxml:e,hasChanges:!1,commentsApplied:0,status:"error",error:f.error,warnings:[...a,f.warning]};let u=f.xmlDoc,d=Pr(u),m=So(u,"w:p");K(`[CommentEngine] Found ${m.length} paragraphs, processing ${t.length} comment requests`);let p=new Map;for(let h of t){let v=h.paragraphIndex-1;if(v<0||v>=m.length){let w=`Paragraph ${h.paragraphIndex} out of range (1-${m.length})`;a.push(w),s.push({code:"TARGET_NOT_FOUND",message:w,paragraphIndex:h.paragraphIndex});continue}p.set(v,(p.get(v)||0)+1)}let g=new Map;for(let[h,v]of t.entries()){let w=v.paragraphIndex-1;if(w<0||w>=m.length)continue;let y=m[w],b=g.get(w);b||(b=ro(y),g.set(w,b));let I=String(v.textToFind??""),E=ea(b,I),N=(p.get(w)||1)-1;if(p.set(w,N),!E.found){let T={...E.error,requestIndex:h+1,paragraphIndex:v.paragraphIndex};s.push(T),a.push(T.message),N===0&&g.delete(w);continue}let R=typeof r.commentIdAllocator=="function"?r.commentIdAllocator():xc();if(!Wf(u,y,I,R,b,d,E)){let T={code:"ANCHOR_INSERTION_FAILED",message:`Resolved comment anchor could not be inserted in paragraph ${v.paragraphIndex}.`,requestIndex:h+1,paragraphIndex:v.paragraphIndex};s.push(T),a.push(T.message),N===0&&g.delete(w);continue}i.push({id:R,content:v.commentContent,author:n,date:o}),l.push({requestIndex:h+1,paragraphIndex:v.paragraphIndex,text:I,resolvedBy:E.resolvedBy,start:E.start,end:E.end}),N>0?g.set(w,ro(y)):g.delete(w)}return i.length===0?{oxml:e,hasChanges:!1,commentsApplied:0,warnings:a,resolvedAnchors:l,...s.length>0?{status:"error",error:s[0],errors:s}:{}}:{oxml:c.serializeToString(u),hasChanges:!0,commentsXml:Ws(i),commentsApplied:i.length,placedComments:i,warnings:a,resolvedAnchors:l,...s.length>0?{status:"error",error:s[0],errors:s}:{}}}function lv(e,t){return Kf(e,t)}var cv="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function vr(e,t,r){return e?.getAttribute?.(t)||e?.getAttribute?.(r)||""}function ui(e,t){let r=j(e,"application/xml");return!r.doc||r.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${r.error?.message||"invalid XML"}`}}:{doc:r.doc}}function Qs({commentsXml:e,commentsExtendedXml:t=null,documentXml:r=null,parentCommentId:n,commentId:o,commentContent:a,author:i,date:l=new Date().toISOString()}){if(!e)return{status:"error",error:{code:"COMMENTS_PART_MISSING",message:"A comment reply requires an existing word/comments.xml part."}};let s=ui(e,"word/comments.xml");if(s.error)return{status:"error",error:s.error};let c=s.doc,f=Array.from(c.getElementsByTagNameNS("*","comment")).find(A=>vr(A,"w:id","id")===String(n));if(!f)return{status:"error",error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${n}' was not found.`}};let u=null;if(t){let A=ui(t,"word/commentsExtended.xml");if(A.error)return{status:"error",error:A.error};u=A.doc}let d=qs(c,u);if(r)for(let A of String(r).matchAll(/w14:paraId="([0-9A-Fa-f]{8})"/g))d.add(A[1].toUpperCase());let m=oi(f);if(!m)return{status:"error",error:{code:"PARENT_COMMENT_INVALID",message:`Parent comment '${n}' has no paragraph.`}};let p=xt(f);p?p=p.toUpperCase():(p=ai(n,d),m.setAttributeNS(eo,"w14:paraId",p));for(let A of Array.from(u?.getElementsByTagNameNS("*","commentEx")||[]))if(vr(A,"w15:paraId","paraId").toUpperCase()===p){let S=vr(A,"w15:paraIdParent","paraIdParent").toUpperCase();S&&(p=S);break}let g=[],h=Array.from(c.getElementsByTagNameNS("*","comment")),v=new Map(Array.from(u?.getElementsByTagNameNS("*","commentEx")||[]).map(A=>[vr(A,"w15:paraId","paraId").toUpperCase(),vr(A,"w15:paraIdParent","paraIdParent").toUpperCase()]));for(let A of h){let S=xt(A);(S===p||v.get(S)===p)&&g.push(vr(A,"w:id","id"))}let w=vr(h.find(A=>xt(A)===p),"w:id","id")||String(n),y=ai(o,d),b=ui(`<w:comments xmlns:w="${cv}" xmlns:w14="${eo}">${Ho(o,i,a,l,y)}</w:comments>`,"reply comment");c.documentElement.appendChild(c.importNode(b.doc.documentElement.firstChild,!0)),u||(u=ui(_f([]),"word/commentsExtended.xml").doc);let I=u.documentElement,N=Array.from(I.getElementsByTagNameNS("*","commentEx")).find(A=>vr(A,"w15:paraId","paraId").toUpperCase()===p);if(!N){let A=u.createElementNS(ct,"w15:commentEx");A.setAttributeNS(ct,"w15:paraId",p),A.setAttributeNS(ct,"w15:done","0"),I.appendChild(A)}let R=vr(N,"w15:done","done")==="1"?"1":"0",x=u.createElementNS(ct,"w15:commentEx");x.setAttributeNS(ct,"w15:paraId",y),x.setAttributeNS(ct,"w15:paraIdParent",p),x.setAttributeNS(ct,"w15:done",R),I.appendChild(x);let T=se();return{status:"ok",hasChanges:!0,commentsXml:T.serializeToString(c),commentsExtendedXml:T.serializeToString(u),commentsXmlMode:"replace",commentsExtendedXmlMode:"replace",commentId:o,parentCommentId:String(n),paraId:y,parentParaId:p,threadRootCommentId:w,threadCommentIds:g.length?g:[w]}}function oo(e){e?.parentNode&&e.parentNode.removeChild(e)}function Gf(e,t=["all"]){if(!e)return null;let r=e.cloneNode(!0);if(t.includes("all"))["w:b","w:i","w:u","w:strike","w:dstrike","w:color","w:sz","w:szCs","w:rFonts","w:highlight","w:vertAlign","w:spacing","w:w","w:kern","w:position"].forEach(o=>{r.querySelectorAll(`${o}, ${o.replace("w:","")}`).forEach(oo)});else{let n={bold:"w:b",italic:"w:i",underline:"w:u",strikethrough:"w:strike",doubleStrike:"w:dstrike",color:"w:color",highlight:"w:highlight",fontSize:"w:sz",fontSizeCs:"w:szCs",fontFamily:"w:rFonts",superscript:"w:vertAlign",subscript:"w:vertAlign"};t.forEach(o=>{let a=n[o];a&&r.querySelectorAll(`${a}, ${a.replace("w:","")}`).forEach(oo)})}return r.children.length>0?r:null}function uv(e,t,r){if(!t||!e)return e;let n=Xe(e);if(!n)return e;let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=n.getElementsByTagNameNS(o,"r"),i=n.getElementsByTagNameNS(o,"ins"),l=[...Array.from(a)];for(let s of i){let c=s.getElementsByTagNameNS(o,"r");l.push(...Array.from(c))}for(let s of l){let c=s.getElementsByTagNameNS(o,"t"),f=Array.from(c).map(u=>u.textContent).join("");if(f.includes(t)||f===t){let u=s.getElementsByTagNameNS(o,"rPr");if(u.length>0){let d=u[0],m=Gf(d,r);m?d.parentNode&&d.parentNode.replaceChild(m,d):oo(d)}}}return Kt(n)}var fv={yellow:"yellow",green:"green",cyan:"cyan",magenta:"magenta",blue:"blue",red:"red",darkblue:"darkBlue",darkcyan:"darkCyan",darkgreen:"darkGreen",darkmagenta:"darkMagenta",darkred:"darkRed",darkyellow:"darkYellow",gray25:"lightGray",gray50:"darkGray",black:"black",white:"white"};function dv(e,t,r="yellow",n={}){let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=fv[r.toLowerCase()]||"yellow",i=n?.generateRedlines??!1,l=n?.author||oe(),s=t;s?s=t.cloneNode(!0):s=F(e,"w:rPr");let c=null;i&&(c=F(e,"w:rPr"),Array.from(s.childNodes).forEach(d=>{d.nodeName!=="w:rPrChange"&&c.appendChild(d.cloneNode(!0))}));let f=s.getElementsByTagNameNS(o,"highlight");Array.from(f).forEach(oo);let u=F(e,"w:highlight");if(u.setAttributeNS(o,"w:val",a),s.appendChild(u),i&&c){let d=F(e,"w:rPrChange"),m=ce(l,e);d.setAttribute("w:id",String(m.id)),d.setAttribute("w:author",m.author),d.setAttribute("w:date",m.date),d.appendChild(c);let p=s.getElementsByTagNameNS(o,"rPrChange");Array.from(p).forEach(oo),s.appendChild(d)}return s}function el(e,t,r="yellow",n={}){if(!t||!e)return e;let o=Xe(e);if(!o)return e;let a;n?._revisionIdAllocator instanceof Fe?(a=n._revisionIdAllocator,cr(o,a)):a=Pr(o);let i="http://schemas.openxmlformats.org/wordprocessingml/2006/main",l=u=>{let d=u.getElementsByTagNameNS(i,"t");return Array.from(d).map(m=>m.textContent).join("")},s=Array.from(o.getElementsByTagNameNS(i,"r")),c=new WeakSet,f=(u,d,m)=>{let p=u.cloneNode(!0);c.has(u)?Bt(p,a):c.add(u);let g=p.getElementsByTagNameNS(i,"t");Array.from(g).forEach(oo);let h=F(o,"w:t");if(h.setAttribute("xml:space","preserve"),h.textContent=d,p.appendChild(h),m){let v=p.getElementsByTagNameNS(i,"rPr"),w=v.length>0?v[0]:null,y=dv(o,w,r,n);w?p.replaceChild(y,w):p.insertBefore(y,p.firstChild)}return p};for(let u of s){let d=l(u);if(!d)continue;let m=[],p=0;for(;p<=d.length-t.length;){let w=d.indexOf(t,p);if(w===-1)break;m.push(w),p=w+t.length}if(m.length===0)continue;let g=u.parentNode;if(!g){console.warn("[Highlight] Run parent is null; skipping. Likely already processed.");continue}let h=o.createDocumentFragment(),v=0;for(let w of m)w>v&&h.appendChild(f(u,d.slice(v,w),!1)),h.appendChild(f(u,d.slice(w,w+t.length),!0)),v=w+t.length;v<d.length&&h.appendChild(f(u,d.slice(v),!1)),g.replaceChild(h,u)}return Kt(o)}var yr="application/vnd.openxmlformats-officedocument.wordprocessingml",ra="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Hf=Object.freeze([{id:"document",path:"word/document.xml",pathPattern:null,contentType:`${yr}.document.main+xml`,legacyContentTypes:[],relType:`${ra}/officeDocument`,relTarget:null,verified:!0},{id:"numbering",path:"word/numbering.xml",pathPattern:null,contentType:`${yr}.numbering+xml`,legacyContentTypes:[],relType:`${ra}/numbering`,relTarget:"numbering.xml",verified:!1},{id:"comments",path:"word/comments.xml",pathPattern:null,contentType:`${yr}.comments+xml`,legacyContentTypes:[],relType:`${ra}/comments`,relTarget:"comments.xml",verified:!0},{id:"commentsExtended",path:"word/commentsExtended.xml",pathPattern:null,contentType:`${yr}.commentsExtended+xml`,legacyContentTypes:["application/vnd.ms-word.commentsExtended+xml"],relType:"http://schemas.microsoft.com/office/2011/relationships/commentsExtended",relTarget:"commentsExtended.xml",verified:!0},{id:"commentsIds",path:"word/commentsIds.xml",pathPattern:null,contentType:`${yr}.commentsIds+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2016/09/relationships/commentsIds",relTarget:"commentsIds.xml",verified:!0},{id:"commentsExtensible",path:"word/commentsExtensible.xml",pathPattern:null,contentType:`${yr}.commentsExtensible+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible",relTarget:"commentsExtensible.xml",verified:!0},{id:"people",path:"word/people.xml",pathPattern:null,contentType:`${yr}.people+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2011/relationships/people",relTarget:"people.xml",verified:!1},{id:"header",path:null,pathPattern:/^word\/header\d+\.xml$/i,contentType:`${yr}.header+xml`,legacyContentTypes:[],relType:`${ra}/header`,relTarget:null,verified:!0},{id:"footer",path:null,pathPattern:/^word\/footer\d+\.xml$/i,contentType:`${yr}.footer+xml`,legacyContentTypes:[],relType:`${ra}/footer`,relTarget:null,verified:!0}].map(e=>Object.freeze(e))),mv=new Map(Hf.map(e=>[e.id,e]));function yn(e){let t=mv.get(e);if(!t)throw new Error(`Unknown package part: ${e}`);return t}function pv(e){return String(e||"").replace(/^\/+/,"")}function tl(e){let t=pv(e),r=t.toLowerCase();return Hf.find(n=>n.path?n.path.toLowerCase()===r:n.pathPattern?.test(t))||null}function qf(e,t){let r=tl(e);return!r||!r.legacyContentTypes.includes(t)?null:r.contentType}var et="http://schemas.openxmlformats.org/wordprocessingml/2006/main",gv="http://schemas.openxmlformats.org/package/2006/content-types",hv="http://schemas.openxmlformats.org/package/2006/relationships",al=yn("numbering"),il=yn("comments"),sl=yn("commentsExtended"),Jf=al.relType,Zf=al.contentType,Qf=il.relType,ed=il.contentType,td=sl.relType,rl=sl.contentType,Yf=yn("document").path,fi=al.path,na=il.path,nl=sl.path,gt="[Content_Types].xml",$t="word/_rels/document.xml.rels";function je(e,t="xml"){let r=j(e,"application/xml");if(r.error||!r.doc){let n=new Error(`[XML parse error] ${t}: ${r.error?.message||"Unknown"}`);throw n.code="PARSE_ERROR",n}return r.doc}function di(e){return!!e&&e.nodeType===1&&e.namespaceURI===et&&e.localName==="sectPr"}function ll(e){return e.getElementsByTagNameNS("*","body")[0]||null}function rd(e){for(let t of Array.from(e.childNodes||[]))if(di(t))return t;return null}function wv(e,t){let r=rd(e);r?e.insertBefore(t,r):e.appendChild(t)}function mi(e){let t=ll(e);if(!t)return;let r=rd(t);if(!r)return;let n=r.nextSibling;for(;n;){let o=n.nextSibling;n.nodeType===1&&t.insertBefore(n,r),n=o}}function vv(e,t={}){let r=typeof t?.onInfo=="function"?t.onInfo:()=>{},n=e.getElementsByTagNameNS(et,"tc"),o=0;for(let a of Array.from(n)){let i=Array.from(a.childNodes||[]).filter(l=>l.nodeType===1&&l.namespaceURI===et&&l.localName==="p");for(let l of i){let s=Array.from(l.childNodes||[]).filter(c=>c.nodeType===1&&c.namespaceURI===et&&c.localName==="p");for(let c of s)a.insertBefore(c,l),o+=1}}return o>0&&r(`[Sanitize] Fixed ${o} nested w:p element(s) in table cells`),o}function ol(e){return e.getAttribute("pkg:name")||e.getAttribute("name")||""}function yv(e){let t=se(),r=je(e,"package OOXML"),n=Array.from(r.getElementsByTagNameNS("*","part")),o=n.find(u=>ol(u)==="/word/document.xml");if(!o)throw new Error("Package output missing /word/document.xml part");let a=o.getElementsByTagNameNS("*","xmlData")[0];if(!a)throw new Error("Package document part missing pkg:xmlData");let i=Array.from(a.childNodes||[]).find(u=>u.nodeType===1);if(!i)throw new Error("Package document part missing XML payload");let l=i.getElementsByTagNameNS("*","body")[0],s=l?Array.from(l.childNodes||[]).filter(u=>u.nodeType===1&&!di(u)):[i],c=n.find(u=>ol(u)==="/word/numbering.xml"),f=null;if(c){let u=c.getElementsByTagNameNS("*","xmlData")[0],d=u?Array.from(u.childNodes||[]).find(m=>m.nodeType===1):null;d&&(f=t.serializeToString(d))}return{replacementNodes:s,numberingXml:f,sourceType:"package"}}function cl(e){if(typeof e!="string"||!e.trim())return{replacementNodes:[],numberingXml:null,sourceType:"fragment",status:"error",error:{code:"PARSE_ERROR",message:"Reconciliation engine returned no OOXML payload for this operation"}};try{if(e.includes("<pkg:package"))return yv(e);if(e.includes("<w:document")){let o=je(e,"document OOXML"),a=o.getElementsByTagNameNS("*","body")[0];return{replacementNodes:a?Array.from(a.childNodes||[]).filter(l=>l.nodeType===1&&!di(l)):Array.from(o.childNodes||[]).filter(l=>l.nodeType===1),numberingXml:null,sourceType:"document"}}let t=`<root xmlns:w="${et}">${e}</root>`,r=je(t,"OOXML fragment");return{replacementNodes:Array.from(r.documentElement.childNodes||[]).filter(o=>o.nodeType===1),numberingXml:null,sourceType:"fragment"}}catch(t){return{replacementNodes:[],numberingXml:null,sourceType:"fragment",status:"error",error:{code:"PARSE_ERROR",message:t?.message||"Could not parse OOXML payload."}}}}function ul(e,t,r){let o=Array.from(e.getElementsByTagNameNS("*","Override")).find(i=>(i.getAttribute("PartName")||"").toLowerCase()===String(t).toLowerCase());if(o)return(o.getAttribute("ContentType")||"")===r?!1:(o.setAttribute("ContentType",r),!0);let a=e.createElementNS(gv,"Override");return a.setAttribute("PartName",t),a.setAttribute("ContentType",r),e.documentElement.appendChild(a),!0}function fl(e,t,r,n={}){let o=e.getElementsByTagNameNS("*","Relationships")[0]||e.documentElement,a=Array.from(o.getElementsByTagNameNS("*","Relationship"));if(a.some(f=>(f.getAttribute("Type")||"")===t))return!1;let l=0;for(let f of a){let u=f.getAttribute("Id")||"",d=Number.parseInt(u.replace(/^rId/i,""),10);Number.isFinite(d)&&(l=Math.max(l,d))}let s=`rId${l+1}`,c=e.createElementNS(hv,"Relationship");return c.setAttribute("Id",s),c.setAttribute("Type",t),c.setAttribute("Target",r),o.appendChild(c),n?._receiptCollector?n._receiptCollector.recordRelationship(s):n?._documentOperationSession?.receiptCollector&&n._documentOperationSession.receiptCollector.recordRelationship(s),!0}async function ut(e,t){let r=e.file(t);return r?r.async("string"):null}async function pi(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{},o=(Array.isArray(t)?t:[t]).filter(Boolean);if(o.length===0)return;let a=await ut(e,fi),i=[],l=hr(a,o,{onConflict:u=>i.push(u)});if(i.length>0){let u=i.map(d=>`${d.kind} ${d.id}`).join(", ");throw Object.assign(new Error(`Numbering id conflict: ${u} already exist with different content. Generated list numbering must be allocated from the document's own numbering state (pass the current numbering part to the operation runner).`),{code:"NUMBERING_ID_CONFLICT",conflicts:i})}n(a?"[Demo] Merging numbering.xml payload(s) into existing numbering definitions":"[Demo] Adding numbering.xml"),e.file(fi,l);let s=se(),c=await ut(e,gt);if(c){let u=je(c,gt);ul(u,"/word/numbering.xml",Zf)&&e.file(gt,s.serializeToString(u))}let f=await ut(e,$t);if(f){let u=je(f,$t);fl(u,Jf,"numbering.xml",r)&&e.file($t,s.serializeToString(u))}}async function dl(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{};if(!t)return;let o=se(),a=await ut(e,na);if(!a||r.replaceExisting===!0)n("[Demo] Adding comments.xml"),e.file(na,t);else{let s=je(a,"word/comments.xml (existing)"),c=je(t,"word/comments.xml (incoming)"),f=s.documentElement,u=new Set(Array.from(f.getElementsByTagNameNS(et,"comment")).map(d=>d.getAttribute("w:id")||d.getAttribute("id")).filter(Boolean));for(let d of Array.from(c.documentElement.getElementsByTagNameNS(et,"comment"))){let m=d.getAttribute("w:id")||d.getAttribute("id");if(m&&u.has(m))throw new Error(`Duplicate comment id: ${m}`);f.appendChild(s.importNode(d,!0))}e.file(na,o.serializeToString(s))}let i=await ut(e,gt);if(i){let s=je(i,gt);ul(s,"/word/comments.xml",ed)&&e.file(gt,o.serializeToString(s))}let l=await ut(e,$t);if(l){let s=je(l,$t);fl(s,Qf,"comments.xml",r)&&e.file($t,o.serializeToString(s))}}async function gi(e,t,r={}){if(!t)return;je(t,"word/commentsExtended.xml"),e.file(nl,t);let n=se(),o=await ut(e,gt);if(o){let i=je(o,gt);ul(i,"/word/commentsExtended.xml",rl)&&e.file(gt,n.serializeToString(i))}let a=await ut(e,$t);if(a){let i=je(a,$t);fl(i,td,"commentsExtended.xml",r)&&e.file($t,n.serializeToString(i))}}async function ao(e){let t=await ut(e,gt);if(!t)return[];let r=je(t,gt),n=[];for(let o of Array.from(r.getElementsByTagNameNS("*","Override"))){let a=o.getAttribute("PartName")||"",i=o.getAttribute("ContentType")||"",l=qf(a,i);l&&(o.setAttribute("ContentType",l),n.push({partName:a,from:i,to:l}))}return n.length>0&&e.file(gt,se().serializeToString(r)),n}async function Ur(e){let t=await ut(e,Yf);if(!t)throw new Error("Validation failed: missing word/document.xml");let r=je(t,Yf);mi(r);let n=ll(r);if(!n)throw new Error("Validation failed: word/document.xml has no w:body");let o=Array.from(n.childNodes||[]).filter(h=>h.nodeType===1),a=o.map((h,v)=>({node:h,index:v})).filter(h=>di(h.node)).map(h=>h.index);if(a.length>1)throw new Error("Validation failed: multiple body-level w:sectPr");if(a.length===1&&a[0]!==o.length-1)throw new Error("Validation failed: w:sectPr not last");let i=r.getElementsByTagNameNS(et,"tc");for(let h of Array.from(i))for(let v of Array.from(h.childNodes||[]).filter(w=>w.nodeType===1))if(v.namespaceURI===et&&v.localName==="p"&&Array.from(v.childNodes||[]).some(y=>y.nodeType===1&&y.namespaceURI===et&&y.localName==="p"))throw new Error("Validation failed: nested w:p");let l=r.getElementsByTagNameNS(et,"numPr").length>0,s=r.getElementsByTagNameNS(et,"commentRangeStart").length>0||r.getElementsByTagNameNS(et,"commentRangeEnd").length>0||r.getElementsByTagNameNS(et,"commentReference").length>0,c=await ut(e,fi),f=await ut(e,na),u=await ut(e,nl);if(u&&!f)throw new Error("Validation failed: commentsExtended part exists but comments part is missing");if(c)je(c,fi);else if(l)throw new Error("Validation failed: numbering used but part missing");if(f){let h=je(f,na),v=(M,_)=>Array.from(M.getElementsByTagNameNS(et,_)).map(k=>k.getAttribute("w:id")||k.getAttribute("id")).filter(k=>k!==""),w=new Set(v(r,"commentRangeStart")),y=new Set(v(r,"commentRangeEnd")),b=new Set(v(r,"commentReference")),I=v(h,"comment"),E=new Set(I),N=M=>Array.from(M).sort((_,k)=>Number(_)-Number(k)||_.localeCompare(k)),R=(M,_)=>N(new Set(Array.from(M).filter(k=>!_.has(k)))),x=N(new Set(I.filter((M,_)=>I.indexOf(M)!==_)));if(x.length>0)throw new Error(`Validation failed: duplicate comment definitions for id(s): ${x.join(", ")}`);let T=R(w,y),A=R(y,w);if(T.length>0||A.length>0){let M=[];throw T.length>0&&M.push(`start without end: ${T.join(", ")}`),A.length>0&&M.push(`end without start: ${A.join(", ")}`),new Error(`Validation failed: unbalanced comment range marker(s) (${M.join("; ")})`)}let S=R(new Set([...w,...y]),b);if(S.length>0)throw new Error(`Validation failed: comment range has no reference for id(s): ${S.join(", ")}`);let O=R(new Set([...w,...y,...b]),E);if(O.length>0)throw new Error(`Validation failed: comment usage has no definition for id(s): ${O.join(", ")}`);let C=new Set;if(u){let M=je(u,nl),_=new Map;for(let D of Array.from(h.getElementsByTagNameNS("*","comment"))){let z=D.getAttribute("w:id")||D.getAttribute("id"),W=xt(D);W&&_.set(W,z)}let k=new Set(_.keys()),L=new Set;for(let D of Array.from(M.getElementsByTagNameNS("*","commentEx"))){let z=D.getAttribute("w15:paraId")||D.getAttribute("paraId"),W=D.getAttribute("w15:paraIdParent")||D.getAttribute("paraIdParent");if(!z||!k.has(z.toUpperCase()))throw new Error(`Validation failed: commentsExtended entry has no matching comment paragraph: ${z||"(missing)"}`);if(L.has(z.toUpperCase()))throw new Error(`Validation failed: duplicate commentsExtended entry for paraId: ${z}`);if(L.add(z.toUpperCase()),W){if(!k.has(W.toUpperCase()))throw new Error(`Validation failed: commentsExtended parent paragraph was not found: ${W}`);C.add(_.get(z.toUpperCase()))}}}let P=R(new Set([...E].filter(M=>!C.has(M))),b);if(P.length>0)throw new Error(`Validation failed: comment definition has no document reference for id(s): ${P.join(", ")}`)}else if(s)throw new Error("Validation failed: comments used but part missing");let d=await ut(e,gt);if(!d)throw new Error(`Validation failed: missing ${gt}`);let m=je(d,gt),p=await ut(e,$t);if(!p)throw new Error(`Validation failed: missing ${$t}`);let g=je(p,$t);if(c){let h=Array.from(m.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/numbering.xml"&&(w.getAttribute("ContentType")||"")===Zf),v=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===Jf);if(!h)throw new Error("Validation failed: numbering CT override missing");if(!v)throw new Error("Validation failed: numbering rel missing")}if(f){let h=Array.from(m.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/comments.xml"&&(w.getAttribute("ContentType")||"")===ed),v=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===Qf);if(!h)throw new Error("Validation failed: comments CT override missing");if(!v)throw new Error("Validation failed: comments rel missing")}{let h=new Map;for(let b of Array.from(g.getElementsByTagNameNS("*","Relationship")))h.set(b.getAttribute("Id")||"",{type:b.getAttribute("Type")||"",target:b.getAttribute("Target")||""});let v=yn("header"),w=yn("footer"),y=new Map(Array.from(m.getElementsByTagNameNS("*","Override")).map(b=>[(b.getAttribute("PartName")||"").toLowerCase(),b.getAttribute("ContentType")||""]));for(let b of[...Array.from(r.getElementsByTagNameNS(et,"headerReference")),...Array.from(r.getElementsByTagNameNS(et,"footerReference"))]){let I=b.getAttributeNS?.("http://schemas.openxmlformats.org/officeDocument/2006/relationships","id")||b.getAttribute("r:id")||"",E=b.localName==="headerReference"?v:w,N=h.get(I);if(!N)throw new Error(`Validation failed: ${b.localName} ${I||"(no r:id)"} has no document relationship`);if(N.type!==E.relType)throw new Error(`Validation failed: ${b.localName} ${I} points at a relationship of the wrong type (${N.type})`);let R=N.target.startsWith("/")?N.target:`/word/${N.target}`,x=await ut(e,R.slice(1));if(!x)throw new Error(`Validation failed: ${b.localName} ${I} targets a missing part: ${R}`);je(x,R.slice(1));let T=y.get(R.toLowerCase());if(T!==E.contentType)throw new Error(`Validation failed: ${R} content type is ${T?`'${T}'`:"missing"}; Word expects '${E.contentType}'`)}}if(u){let h=Array.from(m.getElementsByTagNameNS("*","Override")).find(y=>(y.getAttribute("PartName")||"").toLowerCase()==="/word/commentsextended.xml");if(h&&h.getAttribute("ContentType")!==rl)throw new Error(`Validation failed: commentsExtended CT override has wrong content type '${h.getAttribute("ContentType")}' (Word expects '${rl}')`);let v=!!h,w=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(y=>(y.getAttribute("Type")||"")===td);if(!v)throw new Error("Validation failed: commentsExtended CT override missing");if(!w)throw new Error("Validation failed: commentsExtended rel missing")}}var io=Object.freeze({STRUCTURED_LIST_DIRECT:"structured_list_direct",EMPTY_FORMATTED_TEXT:"empty_formatted_text",EMPTY_HTML:"empty_html",BLOCK_HTML:"block_html",OOXML_ENGINE:"ooxml_engine"});function od(e){return!e||typeof e!="string"?e||"":e.replace(/\\n/g,`
|
|
213
|
-
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function
|
|
214
|
-
`)&&n.type!=="text"?{kind:
|
|
210
|
+
</w:comments>`}function Uf(e){let t=(e||[]).map(r=>{let n=r.paraIdParent?` w15:paraIdParent="${Ze(r.paraIdParent)}"`:"";return`<w15:commentEx w15:paraId="${Ze(r.paraId)}"${n} w15:done="${r.done?"1":"0"}"/>`}).join("");return`<w15:commentsEx xmlns:w15="${ft}">${t}</w15:commentsEx>`}var Nt=(e,t,r)=>e?.getAttribute?.(t)||e?.getAttribute?.(r)||"";function si(e){let t=Array.from(e?.getElementsByTagNameNS?.("*","p")||[]);return t.length?t[t.length-1]:null}function Tt(e){return Nt(si(e),"w14:paraId","paraId").toUpperCase()}function nl(e,t){let r=new Set;for(let n of Array.from(e?.getElementsByTagNameNS("*","p")||[])){let o=Nt(n,"w14:paraId","paraId");o&&r.add(o.toUpperCase())}for(let n of Array.from(t?.getElementsByTagNameNS("*","commentEx")||[])){let o=Nt(n,"w15:paraId","paraId");o&&r.add(o.toUpperCase())}return r}function li(e,t){let r=Zs(e),n=Number.parseInt(r,16)>>>0;for(;t.has(r);)n=n+1>>>0,r=n.toString(16).toUpperCase().padStart(8,"0");return t.add(r),r}var el=(e,t)=>{let r=V(e,"application/xml");return!r.doc||r.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${r.error?.message||"invalid XML"}`}}:{doc:r.doc}};function ci({commentsXml:e,commentsExtendedXml:t=null,commentId:r,resolved:n=!0}){if(!e)return{status:"error",error:{code:"COMMENTS_PART_MISSING",message:"Resolving a comment requires an existing word/comments.xml part."}};let o=el(e,"word/comments.xml");if(o.error)return{status:"error",error:o.error};let a=o.doc,i=R=>Nt(R,"w:id","id"),l=Array.from(a.getElementsByTagNameNS("*","comment")),s=l.find(R=>i(R)===String(r));if(!s)return{status:"error",error:{code:"COMMENT_NOT_FOUND",message:`Comment '${r}' was not found.`}};let c;if(t){let R=el(t,"word/commentsExtended.xml");if(R.error)return{status:"error",error:R.error};c=R.doc}else c=el(`<w15:commentsEx xmlns:w15="${ft}"/>`,"word/commentsExtended.xml").doc;let f=c.documentElement,u=R=>Array.from(f.getElementsByTagNameNS("*","commentEx")).find(S=>Nt(S,"w15:paraId","paraId").toUpperCase()===R)||null,d=nl(a,c),m=!1,g=(R=>{let S=Tt(R);return S||(S=li(i(R),d),si(R)?.setAttributeNS(no,"w14:paraId",S),m=!0),S})(s),h=u(g),v=h&&Nt(h,"w15:paraIdParent","paraIdParent").toUpperCase()||g,w=new Set([v,g]);for(let R of Array.from(f.getElementsByTagNameNS("*","commentEx")))Nt(R,"w15:paraIdParent","paraIdParent").toUpperCase()===v&&w.add(Nt(R,"w15:paraId","paraId").toUpperCase());let y=n?"1":"0",x=!t;for(let R of w){let S=u(R);S?Nt(S,"w15:done","done")!==y&&(S.setAttributeNS(ft,"w15:done",y),x=!0):(S=c.createElementNS(ft,"w15:commentEx"),S.setAttributeNS(ft,"w15:paraId",R),R!==v&&S.setAttributeNS(ft,"w15:paraIdParent",v),S.setAttributeNS(ft,"w15:done",y),f.appendChild(S),x=!0)}let b=new Map(l.map(R=>[Tt(R),R])),T=[...w].map(R=>b.get(R)).filter(Boolean).map(i),A=b.get(v),E=le(),I=x||m;return{status:"ok",hasChanges:I,resolved:n,threadRootId:A?i(A):String(r),commentIds:T,...I?{commentsExtendedXml:E.serializeToString(c)}:{},...m?{commentsXml:E.serializeToString(a)}:{}}}var ii="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Xf(e,t,r){let n=new Set(t.map(String)),o=g=>Nt(g,"w:id","id"),a=g=>Array.from(e.getElementsByTagNameNS("*",g)).filter(h=>n.has(o(h))),i=a("commentRangeStart"),l=a("commentReference");if(!i.length||!l.length)return!1;let s=i[i.length-1],c=l[l.length-1],f=c.parentNode?.localName==="r"?c.parentNode:c,u=(g,h)=>{let v=e.createElementNS(ii,`w:${g}`);return v.setAttributeNS(ii,"w:id",String(r)),h&&h.appendChild(v),v},d=(g,h)=>g.parentNode.insertBefore(h,g.nextSibling);d(s,u("commentRangeStart"));let m=u("commentRangeEnd"),p=e.createElementNS(ii,"w:r");return p.appendChild(e.createElementNS(ii,"w:rPr")),u("commentReference",p),d(f,m),d(m,p),!0}var tl="http://schemas.microsoft.com/office/word/2016/wordml/cid",rl="http://schemas.microsoft.com/office/word/2018/wordml/cex",nv=(e,t)=>{let r=(Number.parseInt(e,16)^625341585)&2147483646,n=r.toString(16).toUpperCase().padStart(8,"0");for(;t.has(n);)r=r+2&2147483646,n=r.toString(16).toUpperCase().padStart(8,"0");return t.add(n),n};function ui({commentsXml:e,commentsIdsXml:t=null,commentsExtensibleXml:r=null}){let n={};if(!e||!t&&!r)return n;let o=V(e,"application/xml");if(!o.doc||o.error)return n;let a=le(),i=new Map;for(let m of Array.from(o.doc.getElementsByTagNameNS("*","comment"))){let p=Tt(m);p&&i.set(p,m)}let l=null,s=new Map,c=new Set,f=!1;if(t){let m=V(t,"application/xml");if(!m.doc||m.error)return n;l=m.doc;let p=l.documentElement;for(let g of Array.from(p.getElementsByTagNameNS("*","commentId"))){let h=Nt(g,"w16cid:paraId","paraId").toUpperCase(),v=Nt(g,"w16cid:durableId","durableId").toUpperCase();if(v&&c.add(v),!i.has(h)){p.removeChild(g),f=!0;continue}s.set(h,v)}for(let g of i.keys()){if(s.has(g))continue;let h=nv(g,c),v=l.createElementNS(tl,"w16cid:commentId");v.setAttributeNS(tl,"w16cid:paraId",g),v.setAttributeNS(tl,"w16cid:durableId",h),p.appendChild(v),s.set(g,h),f=!0}}let u=null,d=!1;if(r&&l){let m=V(r,"application/xml");if(m.doc&&!m.error){u=m.doc;let p=u.documentElement,g=new Set(s.values()),h=new Set;for(let v of Array.from(p.getElementsByTagNameNS("*","commentExtensible"))){let w=Nt(v,"w16cex:durableId","durableId").toUpperCase();g.has(w)?h.add(w):(p.removeChild(v),d=!0)}for(let[v,w]of s){if(h.has(w))continue;let y=Nt(i.get(v),"w:date","date"),x=u.createElementNS(rl,"w16cex:commentExtensible");x.setAttributeNS(rl,"w16cex:durableId",w),y&&x.setAttributeNS(rl,"w16cex:dateUtc",y),p.appendChild(x),d=!0}}}return f&&(n.commentsIdsXml=a.serializeToString(l)),d&&(n.commentsExtensibleXml=a.serializeToString(u)),n}var ov=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),av=new TextEncoder;function Zo(e){let t;if(typeof e=="string")t=av.encode(e);else if(e instanceof Uint8Array)t=e;else if(e instanceof ArrayBuffer)t=new Uint8Array(e);else if(ArrayBuffer.isView(e))t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else throw new TypeError("sha256 input must be a string, Uint8Array, Buffer, or ArrayBuffer.");let r=t.length,n=r*8,o=Math.ceil((r+9)/64)*64,a=new Uint8Array(o);a.set(t,0),a[r]=128;let i=new DataView(a.buffer,a.byteOffset,a.byteLength),l=Math.floor(n/4294967296),s=n>>>0;i.setUint32(o-8,l,!1),i.setUint32(o-4,s,!1);let c=1779033703,f=3144134277,u=1013904242,d=2773480762,m=1359893119,p=2600822924,g=528734635,h=1541459225,v=new Uint32Array(64);for(let y=0;y<o;y+=64){for(let N=0;N<16;N++)v[N]=i.getUint32(y+N*4,!1);for(let N=16;N<64;N++){let O=v[N-15],C=(O>>>7|O<<25)^(O>>>18|O<<14)^O>>>3,P=v[N-2],M=(P>>>17|P<<15)^(P>>>19|P<<13)^P>>>10;v[N]=v[N-16]+C+v[N-7]+M|0}let x=c,b=f,T=u,A=d,E=m,I=p,R=g,S=h;for(let N=0;N<64;N++){let O=(E>>>6|E<<26)^(E>>>11|E<<21)^(E>>>25|E<<7),C=E&I^~E&R,P=S+O+C+ov[N]+v[N]|0,M=(x>>>2|x<<30)^(x>>>13|x<<19)^(x>>>22|x<<10),_=x&b^x&T^b&T,k=M+_|0;S=R,R=I,I=E,E=A+P|0,A=T,T=b,b=x,x=P+k|0}c=c+x|0,f=f+b|0,u=u+T|0,d=d+A|0,m=m+E|0,p=p+I|0,g=g+R|0,h=h+S|0}let w=y=>(y>>>0).toString(16).padStart(8,"0");return w(c)+w(f)+w(u)+w(d)+w(m)+w(p)+w(g)+w(h)}var oo=new TextEncoder;function zf(e){if(typeof e!="string")throw new TypeError(`Entry name must be a string, got ${typeof e}`);let t=e.replace(/\\/g,"/");for(t=t.replace(/^\/+/,"");t.startsWith("./");)t=t.slice(2);if(t=t.replace(/\/+/g,"/"),!t)throw new Error(`Invalid empty entry name: "${e}"`);return t}function ol({scope:e,entries:t=[]}){if(typeof e!="string"||!e)throw new TypeError("Revision token scope must be a non-empty string.");let r=oo.encode("docx-redline-revision-token\0"),n=1,o=oo.encode(e),a=[],i=new Set,l=Array.isArray(t)?t:t instanceof Map?Array.from(t.entries()):Object.entries(t||{});for(let d of l){if(!d)continue;let m=Array.isArray(d)?d[0]:d.name,p=Array.isArray(d)?d[1]:d.payload??d.bytes;if(m==null)continue;let g=zf(String(m));if(i.has(g))throw new Error(`Duplicate normalized entry path detected: "${g}"`);i.add(g);let h;typeof p=="string"?h=oo.encode(p):p instanceof Uint8Array?h=p:p&&typeof p.length=="number"?h=new Uint8Array(p):h=new Uint8Array(0),a.push({name:g,nameBytes:oo.encode(g),payloadBytes:h})}a.sort((d,m)=>d.name<m.name?-1:d.name>m.name?1:0);let s=r.length+4+4+o.length+4;for(let d of a)s+=4+d.nameBytes.length+4+d.payloadBytes.length;let c=new Uint8Array(s),f=new DataView(c.buffer,c.byteOffset,c.byteLength),u=0;c.set(r,u),u+=r.length,f.setUint32(u,n,!1),u+=4,f.setUint32(u,o.length,!1),u+=4,c.set(o,u),u+=o.length,f.setUint32(u,a.length,!1),u+=4;for(let d of a)f.setUint32(u,d.nameBytes.length,!1),u+=4,c.set(d.nameBytes,u),u+=d.nameBytes.length,f.setUint32(u,d.payloadBytes.length,!1),u+=4,c.set(d.payloadBytes,u),u+=d.payloadBytes.length;return{framing:c,scope:e,version:n,coveredParts:a.map(d=>d.name)}}async function jf({scope:e,entries:t=[],digestFn:r=null}){let{framing:n,coveredParts:o,version:a}=ol({scope:e,entries:t}),i="";if(typeof r=="function")i=await r(n);else if(typeof globalThis.crypto?.subtle?.digest=="function"){let l=await globalThis.crypto.subtle.digest("SHA-256",n),s=new Uint8Array(l);i=Array.from(s).map(c=>c.toString(16).padStart(2,"0")).join("")}else i=Zo(n);return{algorithm:"sha256",version:a,scope:e,value:i,coveredParts:o}}function Qo({scope:e,entries:t=[],digestFn:r=null}){if(r!=null&&typeof r!="function")throw new TypeError("computeRevisionTokenSync requires a synchronous digestFn when specified.");let{framing:n,coveredParts:o,version:a}=ol({scope:e,entries:t}),i=typeof r=="function"?r(n):Zo(n);return{algorithm:"sha256",version:a,scope:e,value:i,coveredParts:o}}function fi(e){let t=[];if(e?.documentXml&&t.push({name:"word/document.xml",payload:e.documentXml}),e?.commentsXml&&t.push({name:"word/comments.xml",payload:e.commentsXml}),e?.commentsExtendedXml&&t.push({name:"word/commentsExtended.xml",payload:e.commentsExtendedXml}),e?.numberingXml&&t.push({name:"word/numbering.xml",payload:e.numberingXml}),e?.stylesXml&&t.push({name:"word/styles.xml",payload:e.stylesXml}),e?.parts instanceof Map)for(let[r,n]of e.parts.entries())t.push({name:r,payload:n});else if(e?.additionalParts&&typeof e.additionalParts=="object")for(let[r,n]of Object.entries(e.additionalParts))t.push({name:r,payload:n});return t}async function ea(e,t={}){let r=fi(e);return jf({scope:"document-parts",entries:r,digestFn:t.digestFn})}function vn(e){return!e||typeof e!="object"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:"Revision token must be an object."}}:e.algorithm!=="sha256"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token algorithm: "${e.algorithm}". Expected "sha256".`}}:e.version!==1?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token version: "${e.version}". Expected 1.`}}:e.scope!=="document-parts"&&e.scope!=="package"?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:`Unsupported revision token scope: "${e.scope}". Expected "document-parts" or "package".`}}:typeof e.value!="string"||!/^[0-9a-f]{64}$/i.test(e.value.trim())?{valid:!1,error:{code:"INVALID_REVISION_TOKEN",message:"Revision token value must be a 64-character hex string."}}:{valid:!0}}function yn(e,t){if(typeof e!="string"||typeof t!="string")return!1;let r=e.trim().toLowerCase(),n=t.trim().toLowerCase();if(r.length!==n.length)return!1;let o=oo.encode(r),a=oo.encode(n),i=0;for(let l=0;l<o.length;l++)i|=o[l]^a[l];return i===0}var Ie=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"",qt=(e,t)=>Array.from(e?.getElementsByTagNameNS?.(B,t)||[]),yr=(e,t)=>qt(e,t)[0]||null,xn=(e,t)=>Array.from(e?.childNodes||[]).find(r=>r?.nodeType===1&&r.localName===t&&(!r.namespaceURI||r.namespaceURI===B))||null,al=e=>xn(e,"pPr");function Vf(e,t){let r=e?.parentNode;for(;r;){if(r.localName===t&&(!r.namespaceURI||r.namespaceURI===B))return!0;r=r.parentNode}return!1}function di(e,t,r=!1){if(!e)return r?{error:{code:"MISSING_PART",message:`Missing ${t}.`}}:{doc:null};let n=V(e,"application/xml");return!n.doc||n.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${n.error?.message||"invalid XML"}`}}:{doc:n.doc,warnings:n.warnings||[]}}function iv(e){let t=xn(al(e),"numPr");if(!t)return null;let r=Ie(xn(t,"numId"),"val");return!r||r==="0"?null:{numId:r,level:Number.parseInt(Ie(xn(t,"ilvl"),"val")||"0",10)||0}}function sv(e){let t=new Map;for(let n of qt(e,"abstractNum")){let o=new Map;for(let a of qt(n,"lvl")){let i=Number.parseInt(Ie(a,"ilvl")||"0",10)||0;o.set(i,{start:Number.parseInt(Ie(yr(a,"start"),"val")||"1",10)||1,format:Ie(yr(a,"numFmt"),"val")||"decimal",text:Ie(yr(a,"lvlText"),"val")||`%${i+1}.`})}t.set(Ie(n,"abstractNumId"),o)}let r=new Map;for(let n of qt(e,"num")){let o=Ie(yr(n,"abstractNumId"),"val"),a=new Map(t.get(o)||[]);for(let i of qt(n,"lvlOverride")){let l=Number.parseInt(Ie(i,"ilvl")||"0",10)||0,s=yr(i,"lvl"),c={...a.get(l)||{start:1,format:"decimal",text:`%${l+1}.`}};s&&(c.start=Number.parseInt(Ie(yr(s,"start"),"val")||String(c.start),10)||c.start,c.format=Ie(yr(s,"numFmt"),"val")||c.format,c.text=Ie(yr(s,"lvlText"),"val")||c.text);let f=yr(i,"startOverride");f&&(c.start=Number.parseInt(Ie(f,"val")||String(c.start),10)||c.start),a.set(l,c)}r.set(Ie(n,"numId"),a)}return r}function Wf(e,t){let r=Math.max(1,e),n="";for(;r>0;)r-=1,n=String.fromCharCode(97+r%26)+n,r=Math.floor(r/26);return t?n.toUpperCase():n}function Kf(e){let t=[[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"]],r=e,n="";for(let[o,a]of t)for(;r>=o;)n+=a,r-=o;return n}function lv(e,t){return t==="lowerLetter"?Wf(e,!1):t==="upperLetter"?Wf(e,!0):t==="lowerRoman"?Kf(e).toLowerCase():t==="upperRoman"?Kf(e):String(e)}function cv(e){let t=e?sv(e):new Map,r=new Map;return n=>{if(!n?.numId)return null;let o=t.get(String(n.numId));if(!o)return{...n,label:null,format:null};let a=r.get(n.numId)||[],i=o.get(n.level)||{start:1,format:"decimal",text:`%${n.level+1}.`};a[n.level]=a[n.level]==null?i.start:a[n.level]+1,a.length=n.level+1,r.set(n.numId,a);let l=i.text.replace(/%([1-9])/g,(s,c)=>{let f=Number(c)-1,u=o.get(f)||i;return lv(a[f]??u.start,u.format)});return{...n,label:l,format:i.format}}}function uv(e){let t=al(e),n=Ie(xn(t,"pStyle"),"val").match(/^heading\s*([1-9])$/i);if(n)return Math.min(Number(n[1]),6);let o=Number.parseInt(Ie(xn(t,"outlineLvl"),"val"),10);return Number.isInteger(o)?Math.min(o+1,6):null}function fv(e,t){let r=[];for(let[l,s]of[["footnoteReference","footnote"],["endnoteReference","endnote"],["commentReference","comment"]])for(let c of qt(e,l))r.push({type:s,id:Ie(c,"id")||null});let n=e.parentNode;for(;n&&n.localName!=="tc";)n=n.parentNode;let o=n?.parentNode;for(;o&&o.localName!=="tr";)o=o.parentNode;let a=o?.parentNode;for(;a&&a.localName!=="tbl";)a=a.parentNode;let i=e.ownerDocument;return{references:r,table:a?{tableIndex:Array.from(i.getElementsByTagNameNS(B,"tbl")).indexOf(a)+1,rowIndex:Array.from(a.getElementsByTagNameNS(B,"tr")).indexOf(o)+1,cellIndex:Array.from(o.getElementsByTagNameNS(B,"tc")).indexOf(n)+1}:null,empty:t.length===0}}function Gf(e){let t=new Set;for(let r of["ins","del","moveFrom","moveTo","rPrChange","pPrChange"])for(let n of qt(e,r))Ie(n,"author")&&t.add(Ie(n,"author"));return[...t].sort()}function dv(e){let t=new Map;for(let r of qt(e,"comment")){let n=qt(r,"p");t.set(Ie(r,"id"),{id:Ie(r,"id"),author:Ie(r,"author")||null,date:Ie(r,"date")||null,text:n.map(o=>Y(o)).join(`
|
|
211
|
+
`),paraId:Tt(r)||null})}return t}function mv(e,t){if(!t)return;let r=new Map([...e.values()].filter(n=>n.paraId).map(n=>[n.paraId.toUpperCase(),n]));for(let n of Array.from(t.getElementsByTagNameNS("*","commentEx"))){let o=n.getAttribute("w15:paraId")||n.getAttribute("paraId")||"",a=n.getAttribute("w15:paraIdParent")||n.getAttribute("paraIdParent")||"",i=r.get(o.toUpperCase());i&&(i.done=(n.getAttribute("w15:done")||n.getAttribute("done"))==="1",a&&(i.parentParaId=a,i.parentCommentId=r.get(a.toUpperCase())?.id||null))}}function pv(e,t){let r=new Map,n=new Map,o=null,a=l=>{for(let s of r.values())s.text+=l},i=l=>{for(let s of Array.from(l?.childNodes||[])){if(s?.nodeType!==1)continue;let c=s.localName;if(!(t==="accepted"&&(c==="del"||c==="moveFrom")||t==="rejected"&&(c==="ins"||c==="moveTo")))if(c==="commentRangeStart")r.set(Ie(s,"id"),{text:""});else if(c==="commentRangeEnd"){let f=Ie(s,"id");r.has(f)&&(n.set(f,r.get(f).text),r.delete(f))}else c==="r"?a(gr(s,{revisionView:t,boundary:o})):i(s)}};return e.forEach((l,s)=>{o=l,i(l),s<e.length-1&&r.size&&a(`
|
|
212
|
+
`)}),n}function gv(e,t){let r=e;if(t.revisedOnly&&(r=r.filter(p=>p.hasRevisions)),t.inTable!=null&&(r=r.filter(p=>p.inTable===!!t.inTable)),t.skipEmpty&&(r=r.filter(p=>p.text.length>0)),t.search){let p=String(t.search).toLowerCase();r=r.filter(g=>g.text.toLowerCase().includes(p))}if(Array.isArray(t.indexes)){let p=new Set(t.indexes);r=r.filter(g=>p.has(g.index))}let n=1,o=e.length;t.range&&(n=Number(t.range.start??t.range[0]),o=Number(t.range.end??t.range[1]),r=r.filter(p=>p.index>=n&&p.index<=o));let a=r.length,i=Number.isInteger(t.after)&&t.after>0?t.after:null,l=i==null?r:r.filter(p=>p.index>i),s=Number.isInteger(t.limit)&&t.limit>0?t.limit:null,c=s==null?l:l.slice(0,s),f=c.length<l.length,u=Number.isInteger(t.around)&&t.around>0?t.around:0,d=!!t.search||u>0||s!=null||i!=null,m=c;if(u>0&&t.search){let p=new Set(c.map(v=>v.index)),g=new Map;for(let v of c){let w=Math.max(n,v.index-u),y=Math.min(o,v.index+u);for(let x=w;x<=y;x++){if(p.has(x))continue;let b=g.get(x)||[];b.push(v.index),g.set(x,b)}}let h=new Set([...p,...g.keys()]);m=e.filter(v=>h.has(v.index)).map(v=>p.has(v.index)?{...v,selectionRole:"match"}:{...v,selectionRole:"context",contextFor:g.get(v.index)||[]})}else d&&(m=c.map(p=>({...p,selectionRole:"match"})));return{paragraphs:m,...d?{selection:{...t.search?{search:String(t.search),caseSensitive:!1}:{},totalMatches:a,returnedMatches:c.length,returnedParagraphs:m.length,truncated:f,nextAfter:f&&c.length>0?c[c.length-1].index:null,...s!=null?{limit:s}:{},...i!=null?{after:i}:{},...u>0?{around:u}:{}}}:{}}}function mi(e,t={}){let r=di(e?.documentXml,"word/document.xml",!0);if(r.error)return{status:"error",error:r.error,paragraphs:[],comments:[],warnings:[]};let n=di(e?.commentsXml,"word/comments.xml"),o=di(e?.commentsExtendedXml,"word/commentsExtended.xml"),a=di(e?.numberingXml,"word/numbering.xml"),i=[...r.warnings||[]];n.error&&i.push(n.error.message),o.error&&i.push(o.error.message),a.error&&i.push(a.error.message);let l=dv(n.doc);mv(l,o.doc);let s=cv(a.doc),c=null,f=se(r.doc),u=t.revisionView==="rejected"?"rejected":"accepted",d=pv(f,u),m=f.map((y,x)=>{let b=Y(y,{revisionView:u}),T=uv(y);T&&(c={level:T,text:b});let A=[...new Set([...qt(y,"commentRangeStart"),...qt(y,"commentReference")].map(k=>Ie(k,"id")).filter(Boolean))],E=Gf(y),I=s(iv(y)),R=Ie(xn(al(y),"pStyle"),"val")||null,S=fv(y,b),N=x+1,O=I?.label&&I.format!=="bullet"?I.label:null,C=c?.text||null,P=b.slice(0,t.excerptLength||120),M=T?b:O?[O,C].filter(Boolean).join(" \u2014 "):C?[C,P].filter(Boolean).join(" \u2014 "):P,_=Oa(y);return{index:N,ref:`P${N}`,paragraphId:He(y),fingerprint:Ot(y,{text:b,index:N,revisionView:u}),revisionView:u,text:b,exactText:b,excerpt:P,humanReference:M,provision:O,inTable:Vf(y,"tc"),table:S.table,styleId:R,headingLevel:T,nearestHeading:c,list:I,structuralReferences:S.references,hasRevisions:E.length>0,revisionAuthors:E,commentIds:A,segments:_}});for(let y of m)for(let x of y.commentIds){let b=l.get(x)||{id:x,author:null,date:null,text:""};b.paragraphIndex??(b.paragraphIndex=y.index),b.targetRef??(b.targetRef=y.ref),b.anchoredText??(b.anchoredText=d.get(x)||y.text),l.set(x,b)}let p=gv(m,t);if(t.search&&p.selection&&p.selection.totalMatches===0){let y=String(t.search).toLowerCase(),x=u==="accepted"?"rejected":"accepted",b=1,T=f.length;t.range&&(b=Number(t.range.start??t.range[0]),T=Number(t.range.end??t.range[1]));let A=0;for(let E=0;E<f.length;E++){let I=E+1;if(t.range&&(I<b||I>T)||Array.isArray(t.indexes)&&!t.indexes.includes(I))continue;let R=f[E];if(t.inTable!=null&&Vf(R,"tc")!==!!t.inTable||t.revisedOnly&&Gf(R).length===0)continue;let S=Y(R,{revisionView:x});t.skipEmpty&&S.length===0||S.toLowerCase().includes(y)&&A++}A>0&&(p.selection.hint=u==="accepted"?`0 matches in accepted view, but ${A} match${A===1?"":"es"} found in --view rejected. If searching for deleted text to restore, re-run with --view rejected.`:`0 matches in rejected view, but ${A} match${A===1?"":"es"} found in --view accepted. Re-run with --view accepted.`)}m=p.paragraphs;let g=[...new Set(m.flatMap(y=>y.revisionAuthors))].sort(),h=fi(e),v=h.map(y=>y.name).sort(),w=null;return typeof t.digestFn=="function"&&(w=Qo({scope:"document-parts",entries:h,digestFn:t.digestFn})),{status:"ok",revisionToken:w,coveredParts:v,paragraphs:m,...p.selection?{selection:p.selection}:{},comments:[...l.values()],revisionAuthors:g,commentAuthors:[...new Set([...l.values()].map(y=>y.author).filter(Boolean))].sort(),counts:{paragraphs:m.length,comments:l.size,revisedParagraphs:m.filter(y=>y.hasRevisions).length},warnings:i}}var Hf=e=>[e.author??null,e.text??"",e.anchoredText||""];function hv(e=[]){return e.filter(t=>t.kind!=="baseline").reduce((t,r)=>{let n={kind:r.kind,author:r.author||null,text:r.text,acceptedStart:r.acceptedStart??null,rejectedStart:r.rejectedStart??null},o=t.at(-1),a=i=>o[i]==null&&n[i]==null||o[i]!=null&&o[i]+o.text.length===n[i];return o&&o.kind===n.kind&&o.author===n.author&&a("acceptedStart")&&a("rejectedStart")?o.text+=n.text:t.push(n),t},[])}function il(e){let t=e?.comments||[];return{paragraphs:(e?.paragraphs||[]).map(r=>({text:r.exactText,inTable:r.inTable===!0,table:r.table?[r.table.rowIndex,r.table.cellIndex]:null,list:r.list?[r.list.format,r.list.level,r.list.label]:null,review:{present:r.hasRevisions===!0,authors:[...r.revisionAuthors||[]].sort(),segments:hv(r.segments)}})),comments:t.map(r=>{let n=r.parentCommentId!=null?t.find(o=>String(o.id)===String(r.parentCommentId)):null;return[...Hf(r),r.done===!0,n?Hf(n):r.parentCommentId!=null||r.parentParaId?"unresolved parent":null]}).map(r=>JSON.stringify(r)).sort()}}function wv(e,t){let r=il(e),n=il(t),o=[],a=(l,s,c)=>{o.length<10&&JSON.stringify(s)!==JSON.stringify(c)&&o.push({path:l,expected:s,actual:c})};a("paragraphs.length",r.paragraphs.length,n.paragraphs.length);let i=Math.max(r.paragraphs.length,n.paragraphs.length);for(let l=0;l<i;l++){let s=r.paragraphs[l]??null,c=n.paragraphs[l]??null;if(!s||!c){a(`paragraphs[${l}]`,s,c);continue}for(let f of["text","inTable","table","list","review"])a(`paragraphs[${l}].${f}`,s[f],c[f])}return a("comments",r.comments,n.comments),{matches:o.length===0,differences:o}}function ao(e,t={}){let r=t.revisionView==="current"?"accepted":t.revisionView||"accepted",n=Ro(e,"w:r"),o=[],a="";for(let i of n){if(!tn(i,e,r))continue;let l=a.length,s=gr(i,{revisionView:r,boundary:e});a+=s,o.push({run:i,start:l,end:a.length})}return{fullText:a,runOffsets:o}}function qf(e,t){if(!t)return[];let r=[],n=e.indexOf(t);for(;n!==-1;)r.push({start:n,end:n+t.length}),n=e.indexOf(t,n+1);return r}function Yf(e){return String(e).replace(/[ \u00a0]/g," ")}function ra(e,t,r=[]){return{code:e,message:t,...r.length>0?{candidates:r}:{}}}function Jf(e,t,r){let n=null,o=null,a=0,i=0;for(let{run:l,start:s,end:c}of e.runOffsets)t.start>=s&&t.start<c&&(n=l,a=t.start-s),t.end>s&&t.end<=c&&(o=l,i=t.end-s);return!n||!o?null:{found:!0,resolvedBy:r,...t,startRun:n,startOffset:a,endRun:o,endOffset:i}}function Zf(e,t,r=null){let n=e?.parentNode;for(;n&&n.nodeType===1&&n!==r&&(n.localName||n.nodeName.replace(/^.*:/,""))!=="p";){let o=n.localName||n.nodeName.replace(/^.*:/,"");if(t.includes(o))return{node:n,tag:o};n=n.parentNode}return null}function Qf(e,t){if(!t||!t.found)return t;let r=e.runOffsets.filter(n=>n.end>t.start&&n.start<t.end).map(n=>n.run);for(let n of r){if(Zf(n,["del"]))return{found:!1,error:ra("UNSAFE_REVISION_NESTING","Refusing to attach comment to pending deletion.",[t])};if(Zf(n,["moveFrom","moveTo"]))return{found:!1,error:ra("UNSAFE_REVISION_NESTING","Refusing to comment on move revision until move lifecycle is designed.",[t])}}return t}function na(e,t){let r=String(t??""),n=qf(e.fullText,r);if(n.length>1)return{found:!1,error:ra("AMBIGUOUS_ANCHOR",`Anchor text matched ${n.length} locations in the target paragraph.`,n)};if(n.length===1){let l=Jf(e,n[0],"exact_anchor");if(l)return Qf(e,l)}let o=Yf(r),a=Yf(e.fullText),i=qf(a,o);if(i.length>1)return{found:!1,error:ra("AMBIGUOUS_ANCHOR",`Space-equivalent anchor text matched ${i.length} locations in the target paragraph.`,i)};if(i.length===1){let l=Jf(e,i[0],"space_equivalent_anchor");if(l)return Qf(e,l)}return{found:!1,error:ra("ANCHOR_NOT_FOUND",`Could not find anchor text in the target paragraph: "${r}".`)}}function ta(e,t,r,n,o=!1){let a=$(e,"w:r");if(t){let l=t.cloneNode(!0);o||$t(l,n),a.appendChild(l)}let i=$(e,"w:t");return i.setAttribute("xml:space","preserve"),i.textContent=r,a.appendChild(i),a}function ed(e,t,r,n,o=null,a=null,i=null){let l=o||ao(t),s=i||na(l,r);if(!s.found||!s.startRun)return!1;let c=$(e,"w:commentRangeStart");c.setAttribute("w:id",String(n));let f=$(e,"w:commentRangeEnd");f.setAttribute("w:id",String(n));let u=$(e,"w:r"),d=$(e,"w:commentReference");if(d.setAttribute("w:id",String(n)),u.appendChild(d),s.startRun===s.endRun){let h=s.startRun,v=Ue(h,"w:t");if(!v)return h.parentNode.insertBefore(c,h),h.nextSibling?(h.parentNode.insertBefore(f,h.nextSibling),f.parentNode.insertBefore(u,f.nextSibling)):(h.parentNode.appendChild(f),h.parentNode.appendChild(u)),!0;let w=v.textContent||"",y=w.substring(0,s.startOffset),x=w.substring(s.startOffset,s.endOffset),b=w.substring(s.endOffset),T=Ue(h,"w:rPr"),A=h.parentNode;return y&&(A.insertBefore(ta(e,T,y,a,!0),h),$t(T,a)),A.insertBefore(c,h),v.textContent=x,h.nextSibling?A.insertBefore(f,h.nextSibling):A.appendChild(f),A.insertBefore(u,f.nextSibling||null),b&&A.insertBefore(ta(e,T,b,a),u.nextSibling||null),!0}let m=Ue(s.startRun,"w:t");if(m&&s.startOffset>0){let h=m.textContent||"",v=h.substring(0,s.startOffset),w=h.substring(s.startOffset);if(v){let y=Ue(s.startRun,"w:rPr");s.startRun.parentNode.insertBefore(ta(e,y,v,a,!0),s.startRun),$t(y,a)}m.textContent=w}s.startRun.parentNode.insertBefore(c,s.startRun);let p=s.endRun||s.startRun,g=Ue(p,"w:t");if(g&&s.endOffset<(g.textContent||"").length){let h=g.textContent||"",v=h.substring(0,s.endOffset),w=h.substring(s.endOffset);if(g.textContent=v,w){let y=Ue(p,"w:rPr");p.nextSibling?p.parentNode.insertBefore(ta(e,y,w,a),p.nextSibling):p.parentNode.appendChild(ta(e,y,w,a))}}return p.nextSibling?(p.parentNode.insertBefore(f,p.nextSibling),f.parentNode.insertBefore(u,f.nextSibling)):(p.parentNode.appendChild(f),p.parentNode.appendChild(u)),!0}var io="http://schemas.microsoft.com/office/2006/xmlPackage",oa="http://schemas.openxmlformats.org/package/2006/relationships";function td(e,t){let r=le(),n=V(e,"text/xml"),o=n.doc,a=o?$e(o):null;if(n.error||a)return Le("[CommentEngine] Failed to parse package:",n.error?.message||a?.textContent),e;let i=o.documentElement,l=o.createElementNS(io,"pkg:part");l.setAttribute("pkg:name","/word/comments.xml"),l.setAttribute("pkg:contentType","application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");let s=o.createElementNS(io,"pkg:xmlData"),c=V(t,"text/xml").doc;if(!c)return e;s.appendChild(o.importNode(c.documentElement,!0)),l.appendChild(s),i.appendChild(l);let u=Ke(i,io,"part").find(d=>d.getAttribute("pkg:name")==="/word/_rels/document.xml.rels");if(u){let d=Ke(u,io,"xmlData");if(d.length>0){let m=Ke(d[0],oa,"Relationships");if(m.length>0){let p=m[0],g=Ke(p,oa,"Relationship");if(!g.some(v=>v.getAttribute("Type")?.includes("comments"))){let v=0;g.forEach(y=>{let x=y.getAttribute("Id"),b=parseInt(x?.replace("rId","")||"0",10);b>v&&(v=b)});let w=o.createElementNS(oa,"Relationship");w.setAttribute("Id",`rId${v+1}`),w.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),w.setAttribute("Target","comments.xml"),p.appendChild(w)}}}}else{let d=o.createElementNS(io,"pkg:part");d.setAttribute("pkg:name","/word/_rels/document.xml.rels"),d.setAttribute("pkg:contentType","application/vnd.openxmlformats-package.relationships+xml");let m=o.createElementNS(io,"pkg:xmlData"),p=o.createElementNS(oa,"Relationships"),g=o.createElementNS(oa,"Relationship");g.setAttribute("Id","rId1"),g.setAttribute("Type","http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments"),g.setAttribute("Target","comments.xml"),p.appendChild(g),m.appendChild(p),d.appendChild(m),i.appendChild(d)}return r.serializeToString(o)}function vv(e,t){let r=V(e,"text/xml"),n=r.doc?$e(r.doc):null;if(r.error||n){let o=r.error?.message||n?.textContent||"parse error";return{xmlDoc:null,warning:t(o),warnings:r.warnings,error:{code:"PARSE_ERROR",message:o}}}return{xmlDoc:r.doc,warning:null,warnings:r.warnings,error:null}}function sl(e,t,r={}){let n=r?.author||ae(),o=Ia(),a=[],i=[],l=[],s=[];if(!t||t.length===0)return{oxml:e,hasChanges:!1,commentsApplied:0,warnings:["No comments to inject"]};let c=le(),f=vv(e,h=>`Failed to parse OXML: ${h}`);if(a.push(...f.warnings||[]),!f.xmlDoc)return Le("[CommentEngine] Parse failure:",f.warning),{oxml:e,hasChanges:!1,commentsApplied:0,status:"error",error:f.error,warnings:[...a,f.warning]};let u=f.xmlDoc,d=_r(u),m=Ro(u,"w:p");W(`[CommentEngine] Found ${m.length} paragraphs, processing ${t.length} comment requests`);let p=new Map;for(let h of t){let v=h.paragraphIndex-1;if(v<0||v>=m.length){let w=`Paragraph ${h.paragraphIndex} out of range (1-${m.length})`;a.push(w),s.push({code:"TARGET_NOT_FOUND",message:w,paragraphIndex:h.paragraphIndex});continue}p.set(v,(p.get(v)||0)+1)}let g=new Map;for(let[h,v]of t.entries()){let w=v.paragraphIndex-1;if(w<0||w>=m.length)continue;let y=m[w],x=g.get(w);x||(x=ao(y),g.set(w,x));let b=String(v.textToFind??""),T=na(x,b),A=(p.get(w)||1)-1;if(p.set(w,A),!T.found){let R={...T.error,requestIndex:h+1,paragraphIndex:v.paragraphIndex};s.push(R),a.push(R.message),A===0&&g.delete(w);continue}let E=typeof r.commentIdAllocator=="function"?r.commentIdAllocator():kc();if(!ed(u,y,b,E,x,d,T)){let R={code:"ANCHOR_INSERTION_FAILED",message:`Resolved comment anchor could not be inserted in paragraph ${v.paragraphIndex}.`,requestIndex:h+1,paragraphIndex:v.paragraphIndex};s.push(R),a.push(R.message),A===0&&g.delete(w);continue}i.push({id:E,content:v.commentContent,author:n,date:o}),l.push({requestIndex:h+1,paragraphIndex:v.paragraphIndex,text:b,resolvedBy:T.resolvedBy,start:T.start,end:T.end}),A>0?g.set(w,ao(y)):g.delete(w)}return i.length===0?{oxml:e,hasChanges:!1,commentsApplied:0,warnings:a,resolvedAnchors:l,...s.length>0?{status:"error",error:s[0],errors:s}:{}}:{oxml:c.serializeToString(u),hasChanges:!0,commentsXml:Qs(i),commentsApplied:i.length,placedComments:i,warnings:a,resolvedAnchors:l,...s.length>0?{status:"error",error:s[0],errors:s}:{}}}function yv(e,t){return td(e,t)}var xv="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function xr(e,t,r){return e?.getAttribute?.(t)||e?.getAttribute?.(r)||""}function pi(e,t){let r=V(e,"application/xml");return!r.doc||r.error?{error:{code:"PARSE_ERROR",message:`Could not parse ${t}: ${r.error?.message||"invalid XML"}`}}:{doc:r.doc}}function ll({commentsXml:e,commentsExtendedXml:t=null,documentXml:r=null,parentCommentId:n,commentId:o,commentContent:a,author:i,date:l=new Date().toISOString()}){if(!e)return{status:"error",error:{code:"COMMENTS_PART_MISSING",message:"A comment reply requires an existing word/comments.xml part."}};let s=pi(e,"word/comments.xml");if(s.error)return{status:"error",error:s.error};let c=s.doc,f=Array.from(c.getElementsByTagNameNS("*","comment")).find(S=>xr(S,"w:id","id")===String(n));if(!f)return{status:"error",error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${n}' was not found.`}};let u=null;if(t){let S=pi(t,"word/commentsExtended.xml");if(S.error)return{status:"error",error:S.error};u=S.doc}let d=nl(c,u);if(r)for(let S of String(r).matchAll(/\bw14:paraId="([0-9A-Fa-f]{8})"/g))d.add(S[1].toUpperCase());let m=si(f);if(!m)return{status:"error",error:{code:"PARENT_COMMENT_INVALID",message:`Parent comment '${n}' has no paragraph.`}};let p=Tt(f);p?p=p.toUpperCase():(p=li(n,d),m.setAttributeNS(no,"w14:paraId",p));for(let S of Array.from(u?.getElementsByTagNameNS("*","commentEx")||[]))if(xr(S,"w15:paraId","paraId").toUpperCase()===p){let N=xr(S,"w15:paraIdParent","paraIdParent").toUpperCase();N&&(p=N);break}let g=[],h=Array.from(c.getElementsByTagNameNS("*","comment")),v=new Map(Array.from(u?.getElementsByTagNameNS("*","commentEx")||[]).map(S=>[xr(S,"w15:paraId","paraId").toUpperCase(),xr(S,"w15:paraIdParent","paraIdParent").toUpperCase()]));for(let S of h){let N=Tt(S);(N===p||v.get(N)===p)&&g.push(xr(S,"w:id","id"))}let w=xr(h.find(S=>Tt(S)===p),"w:id","id")||String(n),y=li(o,d),x=pi(`<w:comments xmlns:w="${xv}" xmlns:w14="${no}">${Jo(o,i,a,l,y)}</w:comments>`,"reply comment");c.documentElement.appendChild(c.importNode(x.doc.documentElement.firstChild,!0)),u||(u=pi(Uf([]),"word/commentsExtended.xml").doc);let b=u.documentElement,A=Array.from(b.getElementsByTagNameNS("*","commentEx")).find(S=>xr(S,"w15:paraId","paraId").toUpperCase()===p);if(!A){let S=u.createElementNS(ft,"w15:commentEx");S.setAttributeNS(ft,"w15:paraId",p),S.setAttributeNS(ft,"w15:done","0"),b.appendChild(S)}let E=xr(A,"w15:done","done")==="1"?"1":"0",I=u.createElementNS(ft,"w15:commentEx");I.setAttributeNS(ft,"w15:paraId",y),I.setAttributeNS(ft,"w15:paraIdParent",p),I.setAttributeNS(ft,"w15:done",E),b.appendChild(I);let R=le();return{status:"ok",hasChanges:!0,commentsXml:R.serializeToString(c),commentsExtendedXml:R.serializeToString(u),commentsXmlMode:"replace",commentsExtendedXmlMode:"replace",commentId:o,parentCommentId:String(n),paraId:y,parentParaId:p,threadRootCommentId:w,threadCommentIds:g.length?g:[w]}}var br="application/vnd.openxmlformats-officedocument.wordprocessingml",aa="http://schemas.openxmlformats.org/officeDocument/2006/relationships",rd=Object.freeze([{id:"document",path:"word/document.xml",pathPattern:null,contentType:`${br}.document.main+xml`,legacyContentTypes:[],relType:`${aa}/officeDocument`,relTarget:null,verified:!0},{id:"numbering",path:"word/numbering.xml",pathPattern:null,contentType:`${br}.numbering+xml`,legacyContentTypes:[],relType:`${aa}/numbering`,relTarget:"numbering.xml",verified:!1},{id:"comments",path:"word/comments.xml",pathPattern:null,contentType:`${br}.comments+xml`,legacyContentTypes:[],relType:`${aa}/comments`,relTarget:"comments.xml",verified:!0},{id:"commentsExtended",path:"word/commentsExtended.xml",pathPattern:null,contentType:`${br}.commentsExtended+xml`,legacyContentTypes:["application/vnd.ms-word.commentsExtended+xml"],relType:"http://schemas.microsoft.com/office/2011/relationships/commentsExtended",relTarget:"commentsExtended.xml",verified:!0},{id:"commentsIds",path:"word/commentsIds.xml",pathPattern:null,contentType:`${br}.commentsIds+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2016/09/relationships/commentsIds",relTarget:"commentsIds.xml",verified:!0},{id:"commentsExtensible",path:"word/commentsExtensible.xml",pathPattern:null,contentType:`${br}.commentsExtensible+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible",relTarget:"commentsExtensible.xml",verified:!0},{id:"people",path:"word/people.xml",pathPattern:null,contentType:`${br}.people+xml`,legacyContentTypes:[],relType:"http://schemas.microsoft.com/office/2011/relationships/people",relTarget:"people.xml",verified:!1},{id:"header",path:null,pathPattern:/^word\/header\d+\.xml$/i,contentType:`${br}.header+xml`,legacyContentTypes:[],relType:`${aa}/header`,relTarget:null,verified:!0},{id:"footer",path:null,pathPattern:/^word\/footer\d+\.xml$/i,contentType:`${br}.footer+xml`,legacyContentTypes:[],relType:`${aa}/footer`,relTarget:null,verified:!0}].map(e=>Object.freeze(e))),bv=new Map(rd.map(e=>[e.id,e]));function bn(e){let t=bv.get(e);if(!t)throw new Error(`Unknown package part: ${e}`);return t}function Iv(e){return String(e||"").replace(/^\/+/,"")}function cl(e){let t=Iv(e),r=t.toLowerCase();return rd.find(n=>n.path?n.path.toLowerCase()===r:n.pathPattern?.test(t))||null}function nd(e,t){let r=cl(e);return!r||!r.legacyContentTypes.includes(t)?null:r.contentType}var rt="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Nv="http://schemas.openxmlformats.org/package/2006/content-types",Tv="http://schemas.openxmlformats.org/package/2006/relationships",ml=bn("numbering"),pl=bn("comments"),gl=bn("commentsExtended"),ad=ml.relType,id=ml.contentType,sd=pl.relType,ld=pl.contentType,cd=gl.relType,ul=gl.contentType,od=bn("document").path,gi=ml.path,hi=pl.path,fl=gl.path,wt="[Content_Types].xml",Dt="word/_rels/document.xml.rels";function ze(e,t="xml"){let r=V(e,"application/xml");if(r.error||!r.doc){let n=new Error(`[XML parse error] ${t}: ${r.error?.message||"Unknown"}`);throw n.code="PARSE_ERROR",n}return r.doc}function wi(e){return!!e&&e.nodeType===1&&e.namespaceURI===rt&&e.localName==="sectPr"}function hl(e){return e.getElementsByTagNameNS("*","body")[0]||null}function ud(e){for(let t of Array.from(e.childNodes||[]))if(wi(t))return t;return null}function Sv(e,t){let r=ud(e);r?e.insertBefore(t,r):e.appendChild(t)}function vi(e){let t=hl(e);if(!t)return;let r=ud(t);if(!r)return;let n=r.nextSibling;for(;n;){let o=n.nextSibling;n.nodeType===1&&t.insertBefore(n,r),n=o}}function Av(e,t={}){let r=typeof t?.onInfo=="function"?t.onInfo:()=>{},n=e.getElementsByTagNameNS(rt,"tc"),o=0;for(let a of Array.from(n)){let i=Array.from(a.childNodes||[]).filter(l=>l.nodeType===1&&l.namespaceURI===rt&&l.localName==="p");for(let l of i){let s=Array.from(l.childNodes||[]).filter(c=>c.nodeType===1&&c.namespaceURI===rt&&c.localName==="p");for(let c of s)a.insertBefore(c,l),o+=1}}return o>0&&r(`[Sanitize] Fixed ${o} nested w:p element(s) in table cells`),o}function dl(e){return e.getAttribute("pkg:name")||e.getAttribute("name")||""}function Ev(e){let t=le(),r=ze(e,"package OOXML"),n=Array.from(r.getElementsByTagNameNS("*","part")),o=n.find(u=>dl(u)==="/word/document.xml");if(!o)throw new Error("Package output missing /word/document.xml part");let a=o.getElementsByTagNameNS("*","xmlData")[0];if(!a)throw new Error("Package document part missing pkg:xmlData");let i=Array.from(a.childNodes||[]).find(u=>u.nodeType===1);if(!i)throw new Error("Package document part missing XML payload");let l=i.getElementsByTagNameNS("*","body")[0],s=l?Array.from(l.childNodes||[]).filter(u=>u.nodeType===1&&!wi(u)):[i],c=n.find(u=>dl(u)==="/word/numbering.xml"),f=null;if(c){let u=c.getElementsByTagNameNS("*","xmlData")[0],d=u?Array.from(u.childNodes||[]).find(m=>m.nodeType===1):null;d&&(f=t.serializeToString(d))}return{replacementNodes:s,numberingXml:f,sourceType:"package"}}function wl(e){if(typeof e!="string"||!e.trim())return{replacementNodes:[],numberingXml:null,sourceType:"fragment",status:"error",error:{code:"PARSE_ERROR",message:"Reconciliation engine returned no OOXML payload for this operation"}};try{if(e.includes("<pkg:package"))return Ev(e);if(e.includes("<w:document")){let o=ze(e,"document OOXML"),a=o.getElementsByTagNameNS("*","body")[0];return{replacementNodes:a?Array.from(a.childNodes||[]).filter(l=>l.nodeType===1&&!wi(l)):Array.from(o.childNodes||[]).filter(l=>l.nodeType===1),numberingXml:null,sourceType:"document"}}let t=`<root xmlns:w="${rt}">${e}</root>`,r=ze(t,"OOXML fragment");return{replacementNodes:Array.from(r.documentElement.childNodes||[]).filter(o=>o.nodeType===1),numberingXml:null,sourceType:"fragment"}}catch(t){return{replacementNodes:[],numberingXml:null,sourceType:"fragment",status:"error",error:{code:"PARSE_ERROR",message:t?.message||"Could not parse OOXML payload."}}}}function vl(e,t,r){let o=Array.from(e.getElementsByTagNameNS("*","Override")).find(i=>(i.getAttribute("PartName")||"").toLowerCase()===String(t).toLowerCase());if(o)return(o.getAttribute("ContentType")||"")===r?!1:(o.setAttribute("ContentType",r),!0);let a=e.createElementNS(Nv,"Override");return a.setAttribute("PartName",t),a.setAttribute("ContentType",r),e.documentElement.appendChild(a),!0}function yl(e,t,r,n={}){let o=e.getElementsByTagNameNS("*","Relationships")[0]||e.documentElement,a=Array.from(o.getElementsByTagNameNS("*","Relationship"));if(a.some(f=>(f.getAttribute("Type")||"")===t))return!1;let l=0;for(let f of a){let u=f.getAttribute("Id")||"",d=Number.parseInt(u.replace(/^rId/i,""),10);Number.isFinite(d)&&(l=Math.max(l,d))}let s=`rId${l+1}`,c=e.createElementNS(Tv,"Relationship");return c.setAttribute("Id",s),c.setAttribute("Type",t),c.setAttribute("Target",r),o.appendChild(c),n?._receiptCollector?n._receiptCollector.recordRelationship(s):n?._documentOperationSession?.receiptCollector&&n._documentOperationSession.receiptCollector.recordRelationship(s),!0}async function dt(e,t){let r=e.file(t);return r?r.async("string"):null}async function yi(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{},o=(Array.isArray(t)?t:[t]).filter(Boolean);if(o.length===0)return;let a=await dt(e,gi),i=[],l=vr(a,o,{onConflict:u=>i.push(u)});if(i.length>0){let u=i.map(d=>`${d.kind} ${d.id}`).join(", ");throw Object.assign(new Error(`Numbering id conflict: ${u} already exist with different content. Generated list numbering must be allocated from the document's own numbering state (pass the current numbering part to the operation runner).`),{code:"NUMBERING_ID_CONFLICT",conflicts:i})}n(a?"[Demo] Merging numbering.xml payload(s) into existing numbering definitions":"[Demo] Adding numbering.xml"),e.file(gi,l);let s=le(),c=await dt(e,wt);if(c){let u=ze(c,wt);vl(u,"/word/numbering.xml",id)&&e.file(wt,s.serializeToString(u))}let f=await dt(e,Dt);if(f){let u=ze(f,Dt);yl(u,ad,"numbering.xml",r)&&e.file(Dt,s.serializeToString(u))}}function xl(e,t,r={}){if(!e||r.replaceExisting===!0)return t;let n=ze(e,"word/comments.xml (existing)"),o=ze(t,"word/comments.xml (incoming)"),a=Array.from(o.documentElement.getElementsByTagNameNS(rt,"comment"));if(a.length===0)return e;let i=n.documentElement,l=new Set(Array.from(i.getElementsByTagNameNS(rt,"comment")).map(s=>s.getAttribute("w:id")||s.getAttribute("id")).filter(Boolean));for(let s of a){let c=s.getAttribute("w:id")||s.getAttribute("id");if(c&&l.has(c))throw Object.assign(new Error(`Duplicate comment id: ${c}`),{code:"DUPLICATE_COMMENT_ID",commentId:c});c&&l.add(c),i.appendChild(n.importNode(s,!0))}return le().serializeToString(n)}async function bl(e,t,r={}){let n=typeof r?.onInfo=="function"?r.onInfo:()=>{};if(!t)return;let o=le(),a=await dt(e,hi);(!a||r.replaceExisting===!0)&&n("[Demo] Adding comments.xml"),e.file(hi,xl(a,t,r));let i=await dt(e,wt);if(i){let s=ze(i,wt);vl(s,"/word/comments.xml",ld)&&e.file(wt,o.serializeToString(s))}let l=await dt(e,Dt);if(l){let s=ze(l,Dt);yl(s,sd,"comments.xml",r)&&e.file(Dt,o.serializeToString(s))}}async function xi(e,t,r={}){if(!t)return;ze(t,"word/commentsExtended.xml"),e.file(fl,t);let n=le(),o=await dt(e,wt);if(o){let i=ze(o,wt);vl(i,"/word/commentsExtended.xml",ul)&&e.file(wt,n.serializeToString(i))}let a=await dt(e,Dt);if(a){let i=ze(a,Dt);yl(i,cd,"commentsExtended.xml",r)&&e.file(Dt,n.serializeToString(i))}}async function so(e){let t=await dt(e,wt);if(!t)return[];let r=ze(t,wt),n=[];for(let o of Array.from(r.getElementsByTagNameNS("*","Override"))){let a=o.getAttribute("PartName")||"",i=o.getAttribute("ContentType")||"",l=nd(a,i);l&&(o.setAttribute("ContentType",l),n.push({partName:a,from:i,to:l}))}return n.length>0&&e.file(wt,le().serializeToString(r)),n}async function jr(e){let t=await dt(e,od);if(!t)throw new Error("Validation failed: missing word/document.xml");let r=ze(t,od);vi(r);let n=hl(r);if(!n)throw new Error("Validation failed: word/document.xml has no w:body");let o=Array.from(n.childNodes||[]).filter(h=>h.nodeType===1),a=o.map((h,v)=>({node:h,index:v})).filter(h=>wi(h.node)).map(h=>h.index);if(a.length>1)throw new Error("Validation failed: multiple body-level w:sectPr");if(a.length===1&&a[0]!==o.length-1)throw new Error("Validation failed: w:sectPr not last");let i=r.getElementsByTagNameNS(rt,"tc");for(let h of Array.from(i))for(let v of Array.from(h.childNodes||[]).filter(w=>w.nodeType===1))if(v.namespaceURI===rt&&v.localName==="p"&&Array.from(v.childNodes||[]).some(y=>y.nodeType===1&&y.namespaceURI===rt&&y.localName==="p"))throw new Error("Validation failed: nested w:p");let l=r.getElementsByTagNameNS(rt,"numPr").length>0,s=r.getElementsByTagNameNS(rt,"commentRangeStart").length>0||r.getElementsByTagNameNS(rt,"commentRangeEnd").length>0||r.getElementsByTagNameNS(rt,"commentReference").length>0,c=await dt(e,gi),f=await dt(e,hi),u=await dt(e,fl);if(u&&!f)throw new Error("Validation failed: commentsExtended part exists but comments part is missing");if(c)ze(c,gi);else if(l)throw new Error("Validation failed: numbering used but part missing");if(f){let h=ze(f,hi),v=(M,_)=>Array.from(M.getElementsByTagNameNS(rt,_)).map(k=>k.getAttribute("w:id")||k.getAttribute("id")).filter(k=>k!==""),w=new Set(v(r,"commentRangeStart")),y=new Set(v(r,"commentRangeEnd")),x=new Set(v(r,"commentReference")),b=v(h,"comment"),T=new Set(b),A=M=>Array.from(M).sort((_,k)=>Number(_)-Number(k)||_.localeCompare(k)),E=(M,_)=>A(new Set(Array.from(M).filter(k=>!_.has(k)))),I=A(new Set(b.filter((M,_)=>b.indexOf(M)!==_)));if(I.length>0)throw new Error(`Validation failed: duplicate comment definitions for id(s): ${I.join(", ")}`);let R=E(w,y),S=E(y,w);if(R.length>0||S.length>0){let M=[];throw R.length>0&&M.push(`start without end: ${R.join(", ")}`),S.length>0&&M.push(`end without start: ${S.join(", ")}`),new Error(`Validation failed: unbalanced comment range marker(s) (${M.join("; ")})`)}let N=E(new Set([...w,...y]),x);if(N.length>0)throw new Error(`Validation failed: comment range has no reference for id(s): ${N.join(", ")}`);let O=E(new Set([...w,...y,...x]),T);if(O.length>0)throw new Error(`Validation failed: comment usage has no definition for id(s): ${O.join(", ")}`);let C=new Set;if(u){let M=ze(u,fl),_=new Map;for(let D of Array.from(h.getElementsByTagNameNS("*","comment"))){let X=D.getAttribute("w:id")||D.getAttribute("id"),G=Tt(D);G&&_.set(G,X)}let k=new Set(_.keys()),L=new Set;for(let D of Array.from(M.getElementsByTagNameNS("*","commentEx"))){let X=D.getAttribute("w15:paraId")||D.getAttribute("paraId"),G=D.getAttribute("w15:paraIdParent")||D.getAttribute("paraIdParent");if(!X||!k.has(X.toUpperCase()))throw new Error(`Validation failed: commentsExtended entry has no matching comment paragraph: ${X||"(missing)"}`);if(L.has(X.toUpperCase()))throw new Error(`Validation failed: duplicate commentsExtended entry for paraId: ${X}`);if(L.add(X.toUpperCase()),G){if(!k.has(G.toUpperCase()))throw new Error(`Validation failed: commentsExtended parent paragraph was not found: ${G}`);C.add(_.get(X.toUpperCase()))}}}let P=E(new Set([...T].filter(M=>!C.has(M))),x);if(P.length>0)throw new Error(`Validation failed: comment definition has no document reference for id(s): ${P.join(", ")}`)}else if(s)throw new Error("Validation failed: comments used but part missing");let d=await dt(e,wt);if(!d)throw new Error(`Validation failed: missing ${wt}`);let m=ze(d,wt),p=await dt(e,Dt);if(!p)throw new Error(`Validation failed: missing ${Dt}`);let g=ze(p,Dt);if(c){let h=Array.from(m.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/numbering.xml"&&(w.getAttribute("ContentType")||"")===id),v=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===ad);if(!h)throw new Error("Validation failed: numbering CT override missing");if(!v)throw new Error("Validation failed: numbering rel missing")}if(f){let h=Array.from(m.getElementsByTagNameNS("*","Override")).some(w=>(w.getAttribute("PartName")||"").toLowerCase()==="/word/comments.xml"&&(w.getAttribute("ContentType")||"")===ld),v=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(w=>(w.getAttribute("Type")||"")===sd);if(!h)throw new Error("Validation failed: comments CT override missing");if(!v)throw new Error("Validation failed: comments rel missing")}{let h=new Map;for(let x of Array.from(g.getElementsByTagNameNS("*","Relationship")))h.set(x.getAttribute("Id")||"",{type:x.getAttribute("Type")||"",target:x.getAttribute("Target")||""});let v=bn("header"),w=bn("footer"),y=new Map(Array.from(m.getElementsByTagNameNS("*","Override")).map(x=>[(x.getAttribute("PartName")||"").toLowerCase(),x.getAttribute("ContentType")||""]));for(let x of[...Array.from(r.getElementsByTagNameNS(rt,"headerReference")),...Array.from(r.getElementsByTagNameNS(rt,"footerReference"))]){let b=x.getAttributeNS?.("http://schemas.openxmlformats.org/officeDocument/2006/relationships","id")||x.getAttribute("r:id")||"",T=x.localName==="headerReference"?v:w,A=h.get(b);if(!A)throw new Error(`Validation failed: ${x.localName} ${b||"(no r:id)"} has no document relationship`);if(A.type!==T.relType)throw new Error(`Validation failed: ${x.localName} ${b} points at a relationship of the wrong type (${A.type})`);let E=A.target.startsWith("/")?A.target:`/word/${A.target}`,I=await dt(e,E.slice(1));if(!I)throw new Error(`Validation failed: ${x.localName} ${b} targets a missing part: ${E}`);ze(I,E.slice(1));let R=y.get(E.toLowerCase());if(R!==T.contentType)throw new Error(`Validation failed: ${E} content type is ${R?`'${R}'`:"missing"}; Word expects '${T.contentType}'`)}}if(u){let h=Array.from(m.getElementsByTagNameNS("*","Override")).find(y=>(y.getAttribute("PartName")||"").toLowerCase()==="/word/commentsextended.xml");if(h&&h.getAttribute("ContentType")!==ul)throw new Error(`Validation failed: commentsExtended CT override has wrong content type '${h.getAttribute("ContentType")}' (Word expects '${ul}')`);let v=!!h,w=Array.from(g.getElementsByTagNameNS("*","Relationship")).some(y=>(y.getAttribute("Type")||"")===cd);if(!v)throw new Error("Validation failed: commentsExtended CT override missing");if(!w)throw new Error("Validation failed: commentsExtended rel missing")}}var Il=Object.freeze({comments:"commentsXml",commentsExtended:"commentsExtendedXml",commentsIds:"commentsIdsXml",commentsExtensible:"commentsExtensibleXml"}),Rv=e=>Object.fromEntries(Object.values(Il).map(t=>[t,e?.[t]||null]));function Pv(e={},t={}){let r=Rv(e),n={...r},o=f=>({status:"error",hasChanges:!1,parts:r,changedParts:[],addedParts:[],error:f}),a=t?.commentsXmlMode==="replace"?"replace":"merge",i=t?.commentsExtendedXmlMode==="replace"?"replace":"merge";for(let[f,u]of[...Object.values(Il).map(d=>[`parts.${d}`,r[d]]),["output.commentsXml",t?.commentsXml],["output.commentsExtendedXml",t?.commentsExtendedXml]])if(u!=null&&typeof u!="string")return o({code:"INVALID_COMMENT_PARTS",message:`${f} must be an XML string, null or omitted (got ${typeof u}).`});let l=(f,u,d,m)=>{let p;try{p=ze(f,m)}catch(g){throw Object.assign(g,{part:u})}if(p.documentElement?.localName!==d)throw Object.assign(new Error(`${m}: expected a <${d}> root element, found <${p.documentElement?.localName||"none"}>.`),{code:"INVALID_COMMENT_PARTS",part:u});return p};try{if(t?.commentsXml){let f=l(t.commentsXml,"comments","comments","word/comments.xml (incoming)"),u=new Set;for(let d of Array.from(f.getElementsByTagNameNS("*","comment"))){let m=d.getAttribute("w:id")||d.getAttribute("id");if(m){if(u.has(m))throw Object.assign(new Error(`Duplicate comment id: ${m}`),{code:"DUPLICATE_COMMENT_ID",commentId:m,part:"comments"});u.add(m)}}r.commentsXml&&l(r.commentsXml,"comments","comments","word/comments.xml (existing)"),r.commentsIdsXml&&l(r.commentsIdsXml,"commentsIds","commentsIds","word/commentsIds.xml (existing)"),r.commentsExtensibleXml&&l(r.commentsExtensibleXml,"commentsExtensible","commentsExtensible","word/commentsExtensible.xml (existing)"),n.commentsXml=xl(r.commentsXml,t.commentsXml,{replaceExisting:a==="replace"}),Object.assign(n,ui({commentsXml:n.commentsXml,commentsIdsXml:n.commentsIdsXml,commentsExtensibleXml:n.commentsExtensibleXml}))}if(t?.commentsExtendedXml){if(i!=="replace"&&r.commentsExtendedXml)return o({code:"UNSUPPORTED_EXISTING_COMMENT_THREAD_METADATA",part:"commentsExtended",message:'The output carries a commentsExtended delta (mode "merge") for parts that already have thread metadata; a delta cannot be merged into an existing commentsExtended.xml. Nothing was merged.'});l(t.commentsExtendedXml,"commentsExtended","commentsEx","word/commentsExtended.xml (incoming)"),n.commentsExtendedXml=t.commentsExtendedXml}}catch(f){return o({code:f?.code||"COMMENT_PARTS_MERGE_FAILED",message:f?.message||String(f),...f?.part||f?.code==="DUPLICATE_COMMENT_ID"?{part:f.part||"comments"}:{},...f?.commentId?{commentId:f.commentId}:{}})}let s=[],c=[];for(let[f,u]of Object.entries(Il))n[u]!==r[u]&&(s.push(f),r[u]||c.push(f));return{status:"ok",hasChanges:s.length>0,parts:n,changedParts:s,addedParts:c}}function lo(e){e?.parentNode&&e.parentNode.removeChild(e)}function fd(e,t=["all"]){if(!e)return null;let r=e.cloneNode(!0);if(t.includes("all"))["w:b","w:i","w:u","w:strike","w:dstrike","w:color","w:sz","w:szCs","w:rFonts","w:highlight","w:vertAlign","w:spacing","w:w","w:kern","w:position"].forEach(o=>{r.querySelectorAll(`${o}, ${o.replace("w:","")}`).forEach(lo)});else{let n={bold:"w:b",italic:"w:i",underline:"w:u",strikethrough:"w:strike",doubleStrike:"w:dstrike",color:"w:color",highlight:"w:highlight",fontSize:"w:sz",fontSizeCs:"w:szCs",fontFamily:"w:rFonts",superscript:"w:vertAlign",subscript:"w:vertAlign"};t.forEach(o=>{let a=n[o];a&&r.querySelectorAll(`${a}, ${a.replace("w:","")}`).forEach(lo)})}return r.children.length>0?r:null}function Cv(e,t,r){if(!t||!e)return e;let n=Ve(e);if(!n)return e;let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=n.getElementsByTagNameNS(o,"r"),i=n.getElementsByTagNameNS(o,"ins"),l=[...Array.from(a)];for(let s of i){let c=s.getElementsByTagNameNS(o,"r");l.push(...Array.from(c))}for(let s of l){let c=s.getElementsByTagNameNS(o,"t"),f=Array.from(c).map(u=>u.textContent).join("");if(f.includes(t)||f===t){let u=s.getElementsByTagNameNS(o,"rPr");if(u.length>0){let d=u[0],m=fd(d,r);m?d.parentNode&&d.parentNode.replaceChild(m,d):lo(d)}}}return Kt(n)}var _v={yellow:"yellow",green:"green",cyan:"cyan",magenta:"magenta",blue:"blue",red:"red",darkblue:"darkBlue",darkcyan:"darkCyan",darkgreen:"darkGreen",darkmagenta:"darkMagenta",darkred:"darkRed",darkyellow:"darkYellow",gray25:"lightGray",gray50:"darkGray",black:"black",white:"white"};function Ov(e,t,r="yellow",n={}){let o="http://schemas.openxmlformats.org/wordprocessingml/2006/main",a=_v[r.toLowerCase()]||"yellow",i=n?.generateRedlines??!1,l=n?.author||ae(),s=t;s?s=t.cloneNode(!0):s=$(e,"w:rPr");let c=null;i&&(c=$(e,"w:rPr"),Array.from(s.childNodes).forEach(d=>{d.nodeName!=="w:rPrChange"&&c.appendChild(d.cloneNode(!0))}));let f=s.getElementsByTagNameNS(o,"highlight");Array.from(f).forEach(lo);let u=$(e,"w:highlight");if(u.setAttributeNS(o,"w:val",a),s.appendChild(u),i&&c){let d=$(e,"w:rPrChange"),m=ue(l,e);d.setAttribute("w:id",String(m.id)),d.setAttribute("w:author",m.author),d.setAttribute("w:date",m.date),d.appendChild(c);let p=s.getElementsByTagNameNS(o,"rPrChange");Array.from(p).forEach(lo),s.appendChild(d)}return s}function Nl(e,t,r="yellow",n={}){if(!t||!e)return e;let o=Ve(e);if(!o)return e;let a;n?._revisionIdAllocator instanceof De?(a=n._revisionIdAllocator,cr(o,a)):a=_r(o);let i="http://schemas.openxmlformats.org/wordprocessingml/2006/main",l=u=>{let d=u.getElementsByTagNameNS(i,"t");return Array.from(d).map(m=>m.textContent).join("")},s=Array.from(o.getElementsByTagNameNS(i,"r")),c=new WeakSet,f=(u,d,m)=>{let p=u.cloneNode(!0);c.has(u)?$t(p,a):c.add(u);let g=p.getElementsByTagNameNS(i,"t");Array.from(g).forEach(lo);let h=$(o,"w:t");if(h.setAttribute("xml:space","preserve"),h.textContent=d,p.appendChild(h),m){let v=p.getElementsByTagNameNS(i,"rPr"),w=v.length>0?v[0]:null,y=Ov(o,w,r,n);w?p.replaceChild(y,w):p.insertBefore(y,p.firstChild)}return p};for(let u of s){let d=l(u);if(!d)continue;let m=[],p=0;for(;p<=d.length-t.length;){let w=d.indexOf(t,p);if(w===-1)break;m.push(w),p=w+t.length}if(m.length===0)continue;let g=u.parentNode;if(!g){console.warn("[Highlight] Run parent is null; skipping. Likely already processed.");continue}let h=o.createDocumentFragment(),v=0;for(let w of m)w>v&&h.appendChild(f(u,d.slice(v,w),!1)),h.appendChild(f(u,d.slice(w,w+t.length),!0)),v=w+t.length;v<d.length&&h.appendChild(f(u,d.slice(v),!1)),g.replaceChild(h,u)}return Kt(o)}var co=Object.freeze({STRUCTURED_LIST_DIRECT:"structured_list_direct",EMPTY_FORMATTED_TEXT:"empty_formatted_text",EMPTY_HTML:"empty_html",BLOCK_HTML:"block_html",OOXML_ENGINE:"ooxml_engine"});function md(e){return!e||typeof e!="string"?e||"":e.replace(/\\n/g,`
|
|
213
|
+
`).replace(/\\t/g," ").replace(/\\r/g,"\r")}function kv(e={}){let t=e.originalText||"",r=md(e.newContent||""),n=jo(r)||{type:"text",items:[]};return r.includes(`
|
|
214
|
+
`)&&n.type!=="text"?{kind:co.STRUCTURED_LIST_DIRECT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!0,isOriginalEmpty:dd(t),hasInlineFormatting:bi(r),hasBlockElements:Ii(r),hasMarkdownTable:ia(r)}}:dd(t)?bi(r)?{kind:co.EMPTY_FORMATTED_TEXT,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!0,hasBlockElements:Ii(r),hasMarkdownTable:ia(r)}}:{kind:co.EMPTY_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!0,hasInlineFormatting:!1,hasBlockElements:Ii(r),hasMarkdownTable:ia(r)}}:Ii(r)?{kind:co.BLOCK_HTML,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:bi(r),hasBlockElements:!0,hasMarkdownTable:ia(r)}}:{kind:co.OOXML_ENGINE,normalizedContent:r,parsedListData:n,flags:{hasStructuredListContent:!1,isOriginalEmpty:!1,hasInlineFormatting:bi(r),hasBlockElements:!1,hasMarkdownTable:ia(r)}}}function dd(e){return!e||e.trim().length===0}function ia(e){if(!e||!e.includes("|"))return!1;let t=xt(e);return t.rows.length>0||t.headers.length>0}function bi(e){return e?/(\*\*.+?\*\*|\*.+?\*|__.+?__|_.+?_|`.+?`|~~.+?~~|\+\+.+?\+\+)/.test(e):!1}function Ii(e){if(!e)return!1;let t=/^[\s]*[-*+]\s+/m.test(e),r=/^[\s]*\d+\.\s+/m.test(e),n=/^[\s]*\d+\.\d+(?:\.\d+)*\.?\s+/m.test(e),o=/^[\s]*[A-Za-z]\.\s+/m.test(e),a=/^[\s]*[ivxlcIVXLC]+\.\s+/m.test(e),i=/^[\s]*\([a-z]\)\s+/m.test(e),l=/\|.*\|.*\n/.test(e),s=/^#{1,9}\s/m.test(e),c=e.includes(`
|
|
215
215
|
|
|
216
|
-
`);return t||r||n||o||a||i||l||s||c}function
|
|
217
|
-
`);if(i){let s=/<(?:w:)?num\b[^>]*?\b(?:w:)?numId="([^"]+)"/g,c;for(;(c=s.exec(i))!==null;)a.add(c[1])}if(e?.documentXml&&typeof e.documentXml=="string"){let s=/<(?:w:)?numId\b[^>]*?\b(?:w:)?val="([^"]+)"/g,c;for(;(c=s.exec(e.documentXml))!==null;)a.add(c[1])}let l=new Set;if(e?.relationshipsXml&&typeof e.relationshipsXml=="string"){let s=/<Relationship\b[^>]*?\bId="([^"]+)"/g,c;for(;(c=s.exec(e.relationshipsXml))!==null;)l.add(c[1])}for(let s of r){if(Array.isArray(s.revisionItems)){for(let c of s.revisionItems)if(c.partName==="word/document.xml"&&!n.has(String(c.id)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed revision id '${c.id}' (kind: ${c.kind}) was not found in word/document.xml.`}}}if(Array.isArray(s.commentIds)){for(let c of s.commentIds)if(!o.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed comment id '${c}' was not found in word/comments.xml.`}}}if(Array.isArray(s.numberingIds)){for(let c of s.numberingIds)if(!a.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed numbering id '${c}' was not found in numbering parts or document.`}}}if(e?.relationshipsXml&&Array.isArray(s.relationshipIds)){for(let c of s.relationshipIds)if(!l.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed relationship id '${c}' was not found in document.xml.rels.`}}}}return{valid:!0}}var ad="http://schemas.openxmlformats.org/wordprocessingml/2006/main",xv="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Nv=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","sectPrChange","tblPrChange","tblGridChange","tcPrChange","trPrChange","numberingChange"]),Tv=new Set(["ins","del","moveFrom","moveTo"]),vi=(e,t,r)=>e?.getAttribute?.(t)||e?.getAttribute?.(r)||"";function Av(e){let t=String(e||"");if(t.startsWith("/"))return t.replace(/^\/+/,"");let r=["word"];for(let n of t.split("/"))n===".."?r.pop():n&&n!=="."&&r.push(n);return r.join("/")}function ml({documentXml:e,relsXml:t=null,settingsXml:r=null}){if(!e||!t)return[];let n=j(e,"application/xml"),o=j(t,"application/xml");if(!n.doc||n.error||!o.doc||o.error)return[];let a=new Map;for(let f of Array.from(o.doc.getElementsByTagNameNS("*","Relationship")))a.set(f.getAttribute("Id")||"",f.getAttribute("Target")||"");let i=!!r&&/<w:evenAndOddHeaders\b(?![^>]*w:val="(?:0|false|off)")/.test(r),l=new Map,s=new Map;return Array.from(n.doc.getElementsByTagNameNS(ad,"sectPr")).forEach((f,u)=>{let d=Array.from(f.childNodes||[]).some(m=>m.localName==="titlePg"&&!/^(0|false|off)$/i.test(vi(m,"w:val","val")));for(let m of Array.from(f.childNodes||[])){if(m.nodeType!==1||m.localName!=="headerReference"&&m.localName!=="footerReference")continue;let p=m.getAttributeNS?.(xv,"id")||m.getAttribute("r:id")||"",g=a.get(p);if(!g)continue;let h=Av(g),v=m.localName==="headerReference"?"header":"footer",w=vi(m,"w:type","type")||"default",y=l.get(h)||{path:h,kind:v,type:w,sections:[],applies:[],titlePgSections:0};y.sections.includes(u)||y.sections.push(u),d&&(y.titlePgSections+=1),l.set(h,y),s.set(`${v}:${w}`,h)}for(let m of s.values()){let p=l.get(m);p&&!p.applies.includes(u)&&p.applies.push(u)}}),Array.from(l.values()).map(f=>({path:f.path,kind:f.kind,type:f.type,sections:f.sections,appliesToSections:f.applies,sharedBySections:f.applies.length>1,active:f.type==="first"?f.titlePgSections>0:f.type==="even"?i:!0}))}function pl(e,t){let r=a=>({path:a.path,kind:a.kind,type:a.type,sections:a.sections,appliesToSections:a.appliesToSections});if(typeof t=="string"){let a=t.replace(/^\/+/,"").toLowerCase(),i=e.find(l=>l.path.toLowerCase()===a||l.path.toLowerCase()===`word/${a}`);return i?{part:i}:{error:{code:"PART_NOT_FOUND",message:`No header/footer part '${t}' is referenced by the document.`,candidates:e.map(r)}}}if(!t||typeof t!="object"||t.kind!=="header"&&t.kind!=="footer")return{error:{code:"INVALID_OPERATION",message:'part must be a part path or { kind: "header"|"footer", type?: "default"|"first"|"even", section?: number }.'}};let n=t.type||"default";if(!["default","first","even"].includes(n))return{error:{code:"INVALID_OPERATION",message:`part.type must be default, first or even (got '${n}').`}};let o=e.filter(a=>a.kind===t.kind&&a.type===n);return Number.isInteger(t.section)&&(o=o.filter(a=>a.appliesToSections.includes(t.section))),o.length===1?{part:o[0]}:o.length===0?{error:{code:"PART_NOT_FOUND",message:`The document has no ${n} ${t.kind}${Number.isInteger(t.section)?` for section ${t.section}`:""}.`,candidates:e.map(r)}}:{error:{code:"PART_AMBIGUOUS",message:`Several ${n} ${t.kind} parts exist; add "section" or use the part path.`,candidates:o.map(r)}}}function id(e){let t=tl(e);return t?.id==="header"||t?.id==="footer"}function gl(e){let t=j(e,"application/xml");if(!t.doc||t.error)return 0;let r=0,n=0,o=a=>{for(let i of Array.from(a.childNodes||[])){if(i.nodeType!==1)continue;let l=i.localName;if(l==="fldChar"){let s=vi(i,"w:fldCharType","fldCharType");s==="begin"?r+=1:s==="end"&&(r=Math.max(0,r-1));continue}if(Tv.has(l)&&r>0&&(n+=1),l==="fldSimple"){r+=1,o(i),r-=1;continue}o(i)}};return o(t.doc.documentElement),n}function sd(e){let t=new Set;for(let r of String(e||"").matchAll(/<w:(?:ins|del|moveFrom|moveTo|rPrChange|pPrChange|sectPrChange|tblPrChange|tblGridChange|tcPrChange|trPrChange|numberingChange)\b[^>]*?\bw:id="(\d+)"/g))t.add(r[1]);return t}function ld(e,t){let r=j(e,"application/xml");if(!r.doc||r.error)return{xml:e,renumbered:0,idMap:new Map};let n=new Map,o=1+Math.max(0,...Array.from(t,s=>Number(s)).filter(Number.isFinite)),a=new Set(t),i=0,l=s=>{for(let c of Array.from(s.childNodes||[]))if(c.nodeType===1){if(Nv.has(c.localName)){let f=vi(c,"w:id","id");if(f&&a.has(f)){for(;a.has(String(o));)o+=1;c.setAttributeNS(ad,"w:id",String(o)),n.set(f,String(o)),a.add(String(o)),i+=1}else f&&a.add(f)}l(c)}};return l(r.doc.documentElement),i>0?{xml:se().serializeToString(r.doc),renumbered:i,idMap:n}:{xml:e,renumbered:0,idMap:n}}var Sv=Object.freeze({INVALID_OPERATION:["request","request_fixable","change_request"],INVALID_AGENT_REQUEST:["request","request_fixable","change_request"],INVALID_FILTER:["request","request_fixable","change_request"],INVALID_OPERATIONS_FILE:["request","request_fixable","change_request"],OPERATIONS_REQUIRED:["request","request_fixable","change_request"],UNKNOWN_OPTION:["request","request_fixable","change_request"],UNEXPECTED_ARGUMENT:["request","request_fixable","change_request"],INVALID_ACTION:["request","request_fixable","change_request"],INVALID_PROFILE:["request","request_fixable","change_request"],INVALID_REVISION_TOKEN:["revision-check","request_fixable","change_request"],BATCH_OPERATION_FAILED:["batch-execution","request_fixable","inspect_failed_operations"],REVISION_TOKEN_SCOPE_MISMATCH:["revision-check","request_fixable","change_request"],REVISION_MISMATCH:["revision-check","target_refresh_required","reinspect"],TARGET_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],SOURCE_TARGET_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],TARGET_TEXT_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_FINGERPRINT_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_INDEX_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_OCCURRENCE_MISMATCH:["target-resolution","candidate_selection_required","choose_candidate"],STALE_TARGET_HANDLE:["target-resolution","target_refresh_required","reinspect"],TARGET_HANDLE_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],AMBIGUOUS_TARGET:["target-resolution","candidate_selection_required","choose_candidate"],TARGET_RANGE_INVALID:["target-resolution","request_fixable","change_target_range"],ANCHOR_NOT_FOUND:["anchor-resolution","request_fixable","change_anchor"],AMBIGUOUS_ANCHOR:["anchor-resolution","candidate_selection_required","choose_candidate"],PATCH_SOURCE_NOT_FOUND:["patch-compilation","request_fixable","change_patch"],AMBIGUOUS_PATCH_SOURCE:["patch-compilation","candidate_selection_required","choose_occurrence"],OVERLAPPING_PATCHES:["patch-compilation","source_conflict","combine_patches"],CONFLICTING_PATCHES:["patch-compilation","source_conflict","combine_patches"],PATCH_ROUNDTRIP_MISMATCH:["patch-validation","request_fixable","reinspect_and_narrow"],DIFF_TOKEN_LIMIT:["patch-compilation","request_fixable","narrow_operation"],STRUCTURED_CONTENT_INVALID:["request","request_fixable","change_request"],UNSUPPORTED_LIST_CONVERSION:["list-conversion","request_fixable","use_list_format_convert_plain"],UNSUPPORTED_LIST_FORMAT_CHANGE:["list-conversion","request_fixable","use_list_format_change_format"],LIST_MARKER_NOT_FOUND:["list-conversion","request_fixable","change_request"],LIST_MARKER_AMBIGUOUS:["list-conversion","request_fixable","set_list_format"],LIST_MARKER_UNSUPPORTED:["list-conversion","request_fixable","convert_in_host"],LIST_FORMAT_TARGET_IS_LIST:["list-conversion","request_fixable","use_paragraph_numbering"],LIST_FORMAT_STYLE_NUMBERED:["list-conversion","request_fixable","convert_in_host"],LIST_FORMAT_TARGET_NOT_LIST:["list-conversion","request_fixable","use_list_format_convert_plain"],LIST_FORMAT_MIXED_RANGE:["list-conversion","request_fixable","narrow_range"],LIST_FORMAT_STYLE_LINKED:["list-conversion","request_fixable","convert_in_host"],LIST_FORMAT_SPLIT_UNSUPPORTED:["list-conversion","request_fixable","extend_range_or_use_list_scope"],LIST_FORMAT_DEFINITION_UNSUPPORTED:["list-conversion","request_fixable","convert_in_host"],LIST_FORMAT_JOIN_INVALID:["list-conversion","request_fixable","change_request"],PARAGRAPH_NUMBERING_NOT_FOUND:["target-resolution","target_refresh_required","inspect_numbering"],PARAGRAPH_FORMAT_REVISION_CONFLICT:["target-safety","user_authorization_required","resolve_pending_revision"],UNSUPPORTED_INSERTION_AFFINITY:["request","request_fixable","change_request"],EXISTING_REVISIONS:["target-safety","policy_choice_required","set_option"],PART_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],PART_AMBIGUOUS:["target-resolution","candidate_selection_required","choose_candidate"],COMMENT_IN_HEADER_FOOTER:["request","request_fixable","change_request"],FIELD_EDIT_REFUSED:["target-safety","request_fixable","change_request"],COMMENT_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],PARENT_ANCHOR_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],COMMENTED_CONTENT_MERGE:["target-safety","user_authorization_required","resolve_comments"],COMMENTED_CONTENT_DELETE:["target-safety","user_authorization_required","resolve_comments"],OVERLAPPING_SOURCE_TARGETS:["batch-compilation","source_conflict","consolidate_operations"],OVERLAPPING_TEXT_EDITS:["batch-compilation","source_conflict","consolidate_operations"],REVISION_ORDER_CONFLICT:["batch-compilation","source_conflict","split_or_consolidate_operations"],LIST_FORMAT_COMPOSITION_CONFLICT:["batch-compilation","source_conflict","split_text_and_list_changes"],TARGET_CONSUMED_BY_OPERATION:["batch-execution","source_conflict","use_created_content_dependency"],CAPTURE_FANOUT_CONFLICT:["batch-compilation","source_conflict","split_or_chain_capture_consumers"],DUPLICATE_CAPTURE_KEY:["batch-compilation","request_fixable","rename_capture"],CAPTURE_NOT_FOUND:["batch-compilation","request_fixable","add_or_correct_capture"],CAPTURE_DEPENDENCY_CYCLE:["batch-compilation","source_conflict","replan_batch"],AMBIGUOUS_CAPTURE_SELECTION:["batch-compilation","candidate_selection_required","choose_candidate"],CAPTURE_STALE:["batch-execution","source_conflict","replan_batch"],GENERATED_OOXML_INVALID:["validation","library_or_builder_failure","report_library_failure"],REVISION_FIDELITY_VIOLATION:["verification","library_or_builder_failure","narrow_or_change_operation"],DOCUMENT_SERIALIZATION_FAILED:["serialization","library_or_builder_failure","report_library_failure"],PACKAGE_OPERATION_FAILED:["package","library_or_builder_failure","report_library_failure"],PACKAGE_VALIDATION:["package-validation","library_or_builder_failure","report_library_failure"],MUTATION_RECEIPT_MISMATCH:["receipt-validation","library_or_builder_failure","report_library_failure"],FOREIGN_PARAGRAPH_MARK_DELETION:["target-safety","policy_choice_required","use_restore_or_leave_deleted"],RESTORATION_STATE_REQUIRED:["target-safety","target_refresh_required","reinspect"],RESTORATION_COUNT_MISMATCH:["request","request_fixable","change_request"],REJECTED_INSERTION_STATE_REQUIRED:["target-safety","target_refresh_required","reinspect"],UNSAFE_REVISION_NESTING:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_REVISION_BOUNDARY:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_PARAGRAPH_BOUNDARY:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_DELETED_TABLE_ROW:["target-safety","manual_document_resolution","manual_resolution"],UNSUPPORTED_MOVE_REVISION:["target-safety","manual_document_resolution","manual_resolution"],SECTION_BREAK_PARAGRAPH:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_PARAGRAPH_PLACEMENT:["target-safety","manual_document_resolution","manual_resolution"],UNSUPPORTED_REVISION_VIEW_MUTATION:["target-safety","manual_document_resolution","manual_resolution"]});function Ev(e){let t=Array.isArray(e?.generatedIssues)?e.generatedIssues:Array.isArray(e?.issues)?e.issues:null;if(!t)return null;let r=new Map;for(let n of t){let o=n?.code||"UNKNOWN";r.set(o,(r.get(o)||0)+1)}return{total:t.length,byCode:Array.from(r,([n,o])=>({code:n,count:o}))}}function Rv(e){return Sv[e]||["operation","manual_document_resolution","inspect_error"]}function ht(e,t={}){let r=e&&typeof e=="object"?e:{},n=typeof r.code=="string"&&r.code?r.code:"OPERATION_ERROR",[o,a,i]=Rv(n),l={};for(let[m,p]of Object.entries(r))m==="name"||m==="stack"||m==="message"||m==="code"||(l[m]=p);let f={action:i,sameArgumentsSafe:!1,requiresReinspection:a==="target_refresh_required"||n==="PATCH_ROUNDTRIP_MISMATCH",requiresUserAuthorization:a==="user_authorization_required",...n==="EXISTING_REVISIONS"?{field:"existingRevisions",recommendedValue:"slice-cross-author"}:{},...r.recovery&&typeof r.recovery=="object"?r.recovery:{}},u=Ev(r),d={...t,...Array.isArray(r.revisionAuthors)?{revisionAuthors:r.revisionAuthors}:{},...r.currentPolicy?{currentPolicy:r.currentPolicy}:{}};return["TARGET_TEXT_MISMATCH","TARGET_FINGERPRINT_MISMATCH"].includes(n)&&Array.isArray(r.candidates)&&r.candidates.length===1&&(d.currentTarget=r.candidates[0],d.requiresRecomposeModified=!0),{recoveryVersion:1,code:n,message:r.message||String(e),stage:r.stage||o,category:r.category||a,...l,...Object.keys(d).length>0||r.context?{context:{...r.context||{},...d}}:{},...u?{issueSummary:u}:{},recovery:f}}function br({atomic:e=!1,rolledBack:t=!1,results:r=[],receipts:n=[],operationCount:o=null}={}){let a=Number.isInteger(o)?o:Math.max(r.length,n.length),i=new Set(r.map(u=>u?.index).filter(Number.isInteger)),l=r.filter(u=>u?.status==="error").map(u=>u.index).filter(Number.isInteger),s=n.filter(u=>u?.committed===!0).map(u=>u.operationIndex).filter(Number.isInteger),c=[];for(let u=1;u<=a;u+=1)i.has(u)||c.push(u);let f=t||e||s.length===0?"original":"output";return{base:f,committedIndexes:s,failedIndexes:l,unattemptedIndexes:c,replayWholeBatch:f==="original",sameArgumentsSafe:!1}}function bn(e,t,r){return ht({code:r,message:e,...t?{field:t}:{},recovery:{action:"change_request",sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}})}function yi(e,t,r,n,o={}){return ht({code:e,message:t,field:r,...o,recovery:{action:n,sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}})}function Pv(e,t){let r=[],n=0;for(;n<=e.length-t.length;){let o=e.indexOf(t,n);if(o<0)break;r.push(o),n=o+1}return r}function sa(e,t){return(e===" "||e==="\xA0")&&(t===" "||t==="\xA0")}function Cv(e,t){let r=[];for(let n=0;n<=e.length-t.length;n+=1){let o=!0;for(let a=0;a<t.length;a+=1){let i=e[n+a],l=t[a];if(i!==l&&!sa(i,l)){o=!1;break}}o&&r.push(n)}return r}function _v(e,t){let r=Pv(e,t);return r.length>0?{offsets:r,matchMode:"exact"}:{offsets:Cv(e,t),matchMode:"space_equivalent"}}function Ov(e,t,r){let n=r.split(""),o=0;for(;o<t.length&&o<r.length&&(t[o]===r[o]||sa(t[o],r[o]));)sa(e[o],r[o])&&(n[o]=e[o]),o+=1;let a=t.length-1,i=r.length-1;for(;a>=o&&i>=o&&(t[a]===r[i]||sa(t[a],r[i]));)sa(e[a],r[i])&&(n[i]=e[a]),a-=1,i-=1;return n.join("")}function kv(e,t,r){let n=Math.max(0,t-40),o=Math.min(e.length,t+r+40);return{start:t,end:t+r,excerpt:e.slice(n,o)}}function cd(e,t,r,n=120){let o=String(e??""),a=Math.max(0,Math.min(o.length,t)),i=Math.max(a,Math.min(o.length,r)),l=Math.floor((a+i)/2),s=Math.max(0,l-Math.floor(n/2)),c=Math.min(o.length,s+n);s=Math.max(0,c-n);let f=s>0?"\u2026":"",u=c<o.length?"\u2026":"",d=Math.max(0,n-f.length-u.length);return`${f}${o.slice(s,s+d)}${u}`}function bi(e,t="replacements",{invalidCode:r="INVALID_OPERATION"}={}){if(!Array.isArray(e)||e.length===0)return{ok:!1,error:bn("replacements must be a non-empty array.",t,r)};let n=[];for(let o=0;o<e.length;o+=1){let a=e[o],i=`${t}[${o}]`;if(!a||typeof a!="object"||Array.isArray(a))return{ok:!1,error:bn(`${i} must be an object.`,i,r)};if(typeof a.find!="string"||a.find.length===0)return{ok:!1,error:bn(`${i}.find must be a non-empty string.`,`${i}.find`,r)};if(typeof a.replace!="string")return{ok:!1,error:bn(`${i}.replace must be a string.`,`${i}.replace`,r)};if(a.find===a.replace)return{ok:!1,error:bn(`${i} must change the matched text.`,i,r)};let l=a.occurrence==null?null:Number(a.occurrence);if(l!=null&&(!Number.isInteger(l)||l<1))return{ok:!1,error:bn(`${i}.occurrence must be a positive integer.`,`${i}.occurrence`,r)};n.push({find:a.find,replace:a.replace,...l==null?{}:{occurrence:l}})}return{ok:!0,replacements:n}}function ud(e,t,r="replacements",n={}){let o=n.invalidCode||"INVALID_OPERATION";if(typeof e!="string")return{ok:!1,error:bn("Localized replacements require string source text.",r,o)};let a=bi(t,r,{invalidCode:o});if(!a.ok)return a;let i=[];for(let f=0;f<a.replacements.length;f+=1){let u=a.replacements[f],d=`${r}[${f}]`,m=u.occurrence??null,{offsets:p,matchMode:g}=_v(e,u.find);if(p.length===0||m!=null&&m>p.length)return{ok:!1,error:yi("PATCH_SOURCE_NOT_FOUND",m==null?`Patch source was not found: "${u.find}".`:`Occurrence ${m} of patch source was not found: "${u.find}".`,d,"change_patch",{matchCount:p.length})};if(m==null&&p.length>1)return{ok:!1,error:yi("AMBIGUOUS_PATCH_SOURCE",`Patch source matched ${p.length} locations; provide occurrence.`,d,"choose_occurrence",{candidates:p.map(w=>kv(e,w,u.find.length))})};let h=p[(m||1)-1],v=e.slice(h,h+u.find.length);i.push({requestIndex:f,start:h,end:h+u.find.length,find:u.find,replace:u.replace,effectiveReplace:g==="space_equivalent"?Ov(v,u.find,u.replace):u.replace,matchMode:g,occurrence:m||1})}i.sort((f,u)=>f.start-u.start||f.end-u.end||f.requestIndex-u.requestIndex);let l=[];for(let f of i){let u=l.at(-1);if(u&&f.start===u.start&&f.end===u.end){if(f.effectiveReplace!==u.effectiveReplace)return{ok:!1,error:yi("CONFLICTING_PATCHES",`Localized replacements ${u.requestIndex+1} and ${f.requestIndex+1} assign different text to the same source range.`,r,"combine_patches",{replacementIndexes:[u.requestIndex+1,f.requestIndex+1]})};continue}if(u&&f.start<u.end)return{ok:!1,error:yi("OVERLAPPING_PATCHES",`Localized replacements ${u.requestIndex+1} and ${f.requestIndex+1} overlap.`,r,"combine_patches",{replacementIndexes:[u.requestIndex+1,f.requestIndex+1]})};l.push(f)}let s=0,c="";for(let f of l)c+=e.slice(s,f.start),c+=f.effectiveReplace,s=f.end;return c+=e.slice(s),{ok:!0,desiredText:c,replacements:l.map(f=>({requestIndex:f.requestIndex+1,start:f.start,end:f.end,find:f.find,replace:f.replace,matchMode:f.matchMode,occurrence:f.occurrence,removedLength:f.end-f.start,insertedLength:f.effectiveReplace.length}))}}function fd(e,t,r={},n=null){if(!e||typeof e!="object")return null;let o=String(e.sourceText??""),a=String(e.desiredText??""),i=Array.isArray(e.replacements)?e.replacements:[],l=0,s=i.map(c=>{let f=c.start+l,u=f+c.replace.length;return l+=c.replace.length-(c.end-c.start),{find:c.find,replace:c.replace,...c.matchMode==="space_equivalent"?{matchMode:c.matchMode}:{},occurrence:c.occurrence,beforeExcerpt:cd(o,c.start,c.end),afterExcerpt:cd(a,f,u)}});return{kind:"localized_replacement",committed:!0,finalDisposition:"applied",target:{...r.paragraphId?{paragraphId:r.paragraphId}:{},...Number.isInteger(r.index)?{index:r.index}:{},...r.fingerprint?{fingerprint:r.fingerprint}:{},...n?.humanReference?{humanReference:n.humanReference}:{}},...n?{context:{...n}}:{},replacements:s,verification:{acceptedViewMatchesCompiledText:typeof t=="string"&&t===a}}}var dd=Object.freeze(["convert-plain","change-format","join"]),md=Object.freeze(["decimal","upperLetter","lowerLetter","upperRoman","lowerRoman","bullet"]),Mv=Object.freeze(["marker","none"]),Lv=Object.freeze(["list","range"]),hl=Object.freeze({"convert-plain":Object.freeze(["mode","kind","format","start","level","strip"]),"change-format":Object.freeze(["mode","kind","format","lvlText","start","level","scope"]),join:Object.freeze(["mode","continueFrom","scope"])}),gd=Object.freeze(["materializeMarker"]),Bv=new Set([...Object.values(hl).flat(),...gd]),hd="LIST_MARKER_NOT_FOUND",wd="LIST_MARKER_AMBIGUOUS",la="LIST_MARKER_UNSUPPORTED",vd="LIST_FORMAT_TARGET_IS_LIST",Ii="LIST_FORMAT_STYLE_NUMBERED",yd="LIST_FORMAT_TARGET_NOT_LIST",xi="LIST_FORMAT_MIXED_RANGE",bd="LIST_FORMAT_STYLE_LINKED",so="LIST_FORMAT_SPLIT_UNSUPPORTED",In="LIST_FORMAT_DEFINITION_UNSUPPORTED",Ni="LIST_FORMAT_JOIN_INVALID",Id="LIST_FORMAT_UNCHANGED",Fv="\u2022\\-*\u2013\xB7\u25AA\u25E6",zr="[ \\t\\u00a0]",$v=new RegExp(`^(${zr}*)(?:(\\d{1,3})|([A-Za-z]{1,7}))([.)])(${zr}+)(?=\\S)`),Dv=new RegExp(`^(${zr}*)([${Fv}])(${zr}+)(?=\\S)`),Uv=new RegExp(`^${zr}*\\d+(?:\\.\\d+)+\\.?${zr}+\\S`),zv=new RegExp(`^${zr}*\\((?:\\d{1,3}|[A-Za-z]{1,7})\\)${zr}+\\S`),Xv=/^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,pd={I:1,V:5,X:10,L:50,C:100,D:500,M:1e3};function xd(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var He=(e,t)=>({message:e,field:t});function Vv(e){return e.format!=null&&!md.includes(e.format)?He(`list.format must be one of: ${md.join(", ")}.`,"list.format"):e.kind!=null&&e.kind!=="bullet"&&e.kind!=="numbered"?He('list.kind must be "bullet" or "numbered".',"list.kind"):e.kind!=null&&e.format!=null&&e.kind==="bullet"!=(e.format==="bullet")?He(`list.kind "${e.kind}" contradicts list.format "${e.format}".`,"list.kind"):e.level!=null&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=8)?He("list.level must be an integer from 0 to 8.","list.level"):null}function wl(e,{bullet:t=!1,level:r=null}={}){if(typeof e!="string"||e.length<1||e.length>32)return"list.lvlText must be a string of 1 to 32 characters.";let n=e.match(/%./g)||[];if(t)return e.includes("%")||e.length>4?"A bullet list.lvlText is the bullet itself: 1 to 4 characters without % placeholders.":null;if(n.length===0)return'A numbered list.lvlText needs a %1..%9 placeholder (for example "%1." or "(%1)").';if(n.some(o=>!/^%[1-9]$/.test(o)))return"list.lvlText placeholders must be %1 to %9.";if(r!=null){if(!n.includes(`%${r+1}`))return`list.lvlText for level ${r} must contain its own placeholder %${r+1}.`;if(n.some(o=>Number(o.slice(1))>r+1))return`list.lvlText for level ${r} cannot reference a deeper level than %${r+1}.`}return null}function jv(e){return xd(e)?["paragraphId","fingerprint","exactText","text"].some(r=>typeof e[r]=="string"&&e[r].trim())?e.captureRef!=null||e.occurrence!=null||e.revisionView!=null&&e.revisionView!=="accepted"?He("list.continueFrom targets a batch-start accepted-view paragraph (no captureRef, occurrence or rejected view).","list.continueFrom"):null:He("list.continueFrom needs paragraphId, fingerprint or exactText.","list.continueFrom"):He("join needs list.continueFrom: a paragraph target { paragraphId, fingerprint?, exactText? } of an item of the list to continue.","list.continueFrom")}function Nd(e){if(!xd(e))return He('list-format operations require a "list" object.',"list");let t=Object.keys(e).filter(i=>!Bv.has(i));if(t.length>0)return He(`list has unsupported ${t.length===1?"key":"keys"}: ${t.join(", ")}.`,`list.${t[0]}`);let r=Object.keys(e).filter(i=>gd.includes(i));if(r.length>0)return He(`list.${r[0]} is not supported yet (detach is a later release).`,`list.${r[0]}`);if(!dd.includes(e.mode))return He(`list.mode must be one of: ${dd.join(", ")} (detach is not available yet).`,"list.mode");let n=Object.keys(e).filter(i=>!hl[e.mode].includes(i));if(n.length>0)return He(`list.${n[0]} does not apply to mode "${e.mode}" (it accepts: ${hl[e.mode].filter(i=>i!=="mode").join(", ")}).`,`list.${n[0]}`);if(e.scope!=null&&!Lv.includes(e.scope))return He(`list.scope must be "list" (every paragraph of the target's list) or "range" (only the target range).`,"list.scope");let o=Vv(e);if(o)return o;if(e.mode==="join")return jv(e.continueFrom);if(e.mode==="change-format"){if(e.format==null&&e.kind==null&&e.lvlText==null&&e.start==null)return He("change-format needs at least one of list.format, list.kind, list.lvlText or list.start.","list.format");if(e.kind==="numbered"&&e.format==null)return He('kind "numbered" does not say which numbering format; pass list.format (decimal, upperLetter, lowerLetter, upperRoman or lowerRoman).',"list.format");if(e.lvlText!=null){let i=(e.format??(e.kind==="bullet"?"bullet":null))==="bullet",l=wl(e.lvlText,{bullet:i,level:Number.isInteger(e.level)?e.level:null});if(l)return He(l,"list.lvlText")}if(e.start!=null){if(!(Number.isInteger(e.start)&&e.start>=1&&e.start<=32767))return He("list.start must be an integer from 1 to 32767.","list.start");if(e.scope==="range")return He('scope "range" continues the source count across the split; list.start applies to scope "list" only.',"list.start")}return null}if(e.strip!=null&&!Mv.includes(e.strip))return{message:'list.strip must be "marker" or "none".',field:"list.strip"};let a=e.strip||"marker";if(e.start!=null){if(a==="marker")return{message:'list.start is derived from the typed marker when strip is "marker"; omit it, or use strip: "none".',field:"list.start"};if(!(Number.isInteger(e.start)&&e.start>=1&&e.start<=32767))return{message:"list.start must be an integer from 1 to 32767.",field:"list.start"}}return a==="none"&&e.format==null&&e.kind!=="bullet"?{message:'strip: "none" leaves the text alone, so list.format (or kind: "bullet") must state the list format.',field:"list.format"}:null}function vl(e){let t=e.format||(e.kind==="bullet"?"bullet":null);return{mode:e.mode,format:t,kind:t?t==="bullet"?"bullet":"numbered":e.kind||null,level:Number.isInteger(e.level)?e.level:0,explicitLevel:Number.isInteger(e.level)?e.level:null,strip:e.strip||"marker",start:Number.isInteger(e.start)?e.start:null,lvlText:typeof e.lvlText=="string"?e.lvlText:null,scope:e.scope||"list",continueFrom:e.continueFrom??null}}function Wv(e){let t=e.toUpperCase();if(!t||!Xv.test(t))return null;let r=0;for(let n=0;n<t.length;n+=1){let o=pd[t[n]],a=pd[t[n+1]]||0;r+=o<a?-o:o}return r}function lo(e){let t=String(e??"");if(Uv.test(t))return{unsupported:"multilevel",marker:t.trim().split(/\s/)[0]};if(zv.test(t))return{unsupported:"parenthesized",marker:t.trim().split(/\s/)[0]};let r=Dv.exec(t);if(r)return{marker:r[2],terminator:"",bulletChar:r[2],prefixLength:r[0].length,candidates:[{format:"bullet",value:null}]};let n=$v.exec(t);if(!n)return null;let[o,,a,i,l]=n,s=`${a??i}${l}`,c={marker:s,terminator:l,prefixLength:o.length};if(a!=null){let p=Number.parseInt(a,10);return p<1?{unsupported:"zero",marker:s}:{...c,candidates:[{format:"decimal",value:p}]}}let f=i===i.toUpperCase(),u=i===i.toLowerCase();if(!f&&!u)return null;let d=[];i.length===1&&d.push({format:f?"upperLetter":"lowerLetter",value:i.toLowerCase().charCodeAt(0)-96});let m=Wv(i);return m!=null&&d.push({format:f?"upperRoman":"lowerRoman",value:m}),d.length===0?null:{...c,candidates:d}}function Td(e,t=null){if(e.length===0)return{error:{reason:"none"}};let r=new Set(e.map(i=>i.terminator)),n=new Set(e.filter(i=>i.bulletChar).map(i=>i.bulletChar));if(r.size>1||n.size>1)return{error:{reason:"mixed",markers:e.map(i=>i.marker)}};if(t){let i=e.find(l=>!l.candidates.some(s=>s.format===t));return i?{error:{reason:"format-mismatch",marker:i.marker,requestedFormat:t}}:{format:t}}let o=e[0].candidates.map(i=>i.format);for(let i of e.slice(1)){let l=i.candidates.map(s=>s.format);o=o.filter(s=>l.includes(s))}if(o.length===0)return{error:{reason:"mixed",markers:e.map(i=>i.marker)}};if(o.length===1)return{format:o[0]};let a=o.filter(i=>{if(e.length<2)return!1;let l=e.map(s=>s.candidates.find(c=>c.format===i).value);return l.every((s,c)=>c===0||s===l[c-1]+1)});return a.length===1?{format:a[0]}:{error:{reason:"ambiguous",marker:e[0].marker,formats:o}}}function Ad(e,t){return e.candidates.find(r=>r.format===t)?.value??null}function Sd({format:e,level:t,terminator:r=".",bulletChar:n=null}){return e==="bullet"?{ilvl:t,numFmt:"bullet",lvlText:n==="-"||n==="*"||!n?"\u2022":n}:{ilvl:t,numFmt:e,lvlText:`%${t+1}${r||"."}`}}function Ed({format:e,level:t,terminator:r="",bulletChar:n=null}){return`list-format:${e}:${t}:${e==="bullet"?n||"":r||"."}`}var Kv="LIST_MARKER_NOT_BOUND",Gv="UNSUPPORTED_LIST_CONVERSION",Hv="LIST_FORMAT_NOT_APPLIED",qv="UNSUPPORTED_LIST_FORMAT_CHANGE",Yv="UNKNOWN_PARAGRAPH_FORMAT_PROPERTY";var Pd="PARAGRAPH_NUMBERING_NOT_FOUND",Cd="PARAGRAPH_FORMAT_REVISION_CONFLICT",co=Object.freeze(["alignment","keepNext","keepLines","pageBreakBefore","style","numbering"]),Jv=Object.freeze({bullet:"bullet",decimal:"decimal",lowerAlpha:"lowerLetter",upperAlpha:"upperLetter",lowerRoman:"lowerRoman",upperRoman:"upperRoman"}),yl=new Set(["bullet","decimal","lowerLetter","upperLetter","lowerRoman","upperRoman"]);function Zv(e){return e==="literal"}function bl(e={}){return Zv(e.listMarkers)?"off":(e.strictListConversion!==void 0?e.strictListConversion===!0:e.atomic===!0)?"error":"warn"}function _d(e,t=80){let r=String(e??"");return r.length>t?`${r.slice(0,t)}...`:r}function Ti(e){let t=String(e??"");if(!t.trim()||/[\r\n]/.test(t))return null;let r=Kr(t,{allowZeroSpaceAfterMarker:!1,indentSpaces:2});return!r||!r.marker||r.markerType!=="bullet"&&!/[.)]$/.test(r.marker)?null:{marker:r.marker,kind:r.markerType==="bullet"?"bullet":"numbered",numberingStyle:r.numberingStyle,numFmt:Jv[r.numberingStyle]||"decimal",text:String(r.text||"").trim()}}function Od({originalText:e,modifiedText:t,targetIsListItem:r}){if(r)return null;let n=Ti(t);if(!n)return null;let o=Ti(e);return o&&o.kind===n.kind&&o.numFmt===n.numFmt?null:n}function Qv(e,t){if(t)return null;let r=e.numFmt==="bullet"?"bullet":e.numFmt,n={mode:"convert-plain",format:r,strip:"none"};if(r!=="bullet"){let a=lo(`${e.marker} x`)?.candidates?.find(i=>i.format===r)?.value;Number.isInteger(a)&&a>1&&(n.start=a)}return{type:"list-format",list:n}}function kd(e,{policy:t,targetText:r,operationIndex:n}={}){let o=t==="error",a=o?Gv:Kv,i=o?`Converting a plain paragraph to a list item is not supported by text edits: the new text begins with the list marker "${e.marker}", which would be written as literal text with no list binding. Use a list-format convert-plain operation on the paragraph (capability list-format-v1), or pass listMarkers: "literal" to keep the marker as text.`:`Modified text begins with the list marker "${e.marker}", but the marker was written as literal text; no list binding was created. A list-format convert-plain operation creates the list binding.`,l=Qv(e,!!Ti(r));return{code:a,severity:o?"error":"warning",message:i,listMarker:e.marker,requestedList:{kind:e.kind,format:e.numFmt},...r?{targetExcerpt:_d(r)}:{},...Number.isInteger(n)?{operationIndex:n}:{},recovery:{action:"use_list_format_convert_plain",hint:l?'Keep the paragraph text as it is and send a list-format operation on the same target (recovery.suggestedOperation plus your target), or pass listMarkers: "literal" to write the marker as text intentionally.':'Edit the text with a redline that starts with the typed marker, then convert it with a list-format convert-plain operation (strip: "marker"), or pass listMarkers: "literal" to write the marker as text intentionally.',...l?{suggestedOperation:l}:{},field:"listMarkers",allowedValue:"literal"}}}function ey(e,t,r){let n=d=>Array.from(e.getElementsByTagNameNS("*",d)),o=(d,m)=>d?.getAttribute?.(`w:${m}`)??d?.getAttribute?.(m)??null,a=(d,m)=>Array.from(d?.childNodes||[]).find(p=>p.nodeType===1&&p.localName===m)||null,i=n("num").find(d=>String(o(d,"numId"))===String(t));if(!i)return null;let l=Array.from(i.childNodes).filter(d=>d.nodeType===1&&d.localName==="lvlOverride").find(d=>Number(o(d,"ilvl")||0)===r),s=o(a(a(l,"lvl"),"numFmt"),"val");if(s)return{numFmt:s};let c=o(a(i,"abstractNumId"),"val"),f=n("abstractNum").find(d=>String(o(d,"abstractNumId"))===String(c));if(!f)return null;let u=Array.from(f.childNodes).filter(d=>d.nodeType===1&&d.localName==="lvl").find(d=>Number(o(d,"ilvl")||0)===r);return u?{numFmt:o(a(u,"numFmt"),"val")||"decimal"}:null}function ty(e,t,r=0){if(!String(e||"").trim()||t==null)return null;let n=j(String(e));if(!n?.doc)return null;let o=ey(n.doc,t,Number(r)||0);return o?{numFmt:o.numFmt,kind:o.numFmt==="bullet"?"bullet":"numbered"}:null}function ry({requested:e,sourceLevel:t}){if(!e||!t)return null;let r=e.kind==="bullet"?"bullet":"numbered";return r!==t.kind?{requested:e,source:t}:r==="numbered"&&yl.has(e.numFmt)&&yl.has(t.numFmt)&&e.numFmt!==t.numFmt?{requested:e,source:t}:null}function Md(e,{policy:t,numId:r,level:n,marker:o,targetText:a,operationIndex:i}={}){let l=t==="error",s=l?qv:Hv,c=(p,g)=>p==="bullet"?"a bullet list":`a numbered list${g?` (${g})`:""}`,f=e.requested.kind==="bullet"?"bullet":e.requested.numFmt||e.requested.format,u=c(e.requested.kind,f),d=c(e.source.kind,e.source.numFmt),m=yl.has(f)?{type:"list-format",list:{mode:"change-format",format:f,level:Number(n)||0,scope:"list"}}:null;return{code:s,severity:l?"error":"warning",message:`${l?"Changing the list format is not supported by text edits":"The requested list format was not applied"}: the list item keeps its source numbering definition (numId ${r}, ${d}); the edit asked for ${u}${o?` ("${o}")`:""}. A list-format change-format operation changes the list's format (capability list-format-change-v1).`,requestedList:{kind:e.requested.kind,format:f},sourceList:{numId:String(r),level:Number(n)||0,kind:e.source.kind,format:e.source.numFmt},...a?{targetExcerpt:_d(a)}:{},...Number.isInteger(i)?{operationIndex:i}:{},recovery:{action:"use_list_format_change_format",hint:m?`Text edits cannot change a list's kind or numbering format. Send recovery.suggestedOperation with a target on one item of the list as its own operation (scope "list" rebinds every item; scope "range" only a range that runs to the end of the list). Make any text edit in a separate redline without the new markers, targeting a different paragraph or a separate call. Or pass listMarkers: "literal" to accept the current result.`:`Text edits cannot change a list's kind or numbering format. Use a list-format change-format operation, or pass listMarkers: "literal" to accept the current result.`,...m?{suggestedOperation:m}:{},field:"listMarkers",allowedValue:"literal"}}}function Ld(e){if(e===null)return null;if(typeof e!="object"||Array.isArray(e))return"numbering must be null (remove the list binding) or an object { numId, level }.";let t=Object.keys(e).filter(a=>a!=="numId"&&a!=="level");if(t.length>0)return`numbering has unsupported ${t.length===1?"key":"keys"}: ${t.join(", ")}. Use only numId and level.`;let r=e.numId;if(!(Number.isInteger(r)&&r>=1||typeof r=="string"&&/^[1-9]\d*$/.test(r)))return"numbering.numId must be a positive integer (numId 0 is not a list; pass numbering: null to remove the binding).";let o=e.level;return o!==void 0&&!(Number.isInteger(o)&&o>=0&&o<=8)?"numbering.level must be an integer from 0 to 8.":null}function Ai(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>!co.includes(t))}function Bd(e){let t=e.map(r=>`"${r}"`).join(", ");return{code:Yv,severity:"warning",message:`paragraph-format ignored unsupported ${e.length===1?"property":"properties"} ${t}. Supported: ${co.join(", ")}.`,properties:e,recovery:{action:"change_request",hint:`Use only: ${co.join(", ")}.`}}}function Il(e){return`${e.code}: ${e.message}`}function Rd(e){return String(e??"").replace(/[\s\u00a0]+/g," ").trim()}function Fd({modifiedText:e,sourceItems:t,sourceNumberingXml:r}){if(!Array.isArray(t)||t.length===0)return null;let o=String(e??"").split(/\r?\n/).filter(i=>i.trim()).map(i=>({line:i,item:Ti(i)})),a=new Set;for(let i of t){let l=Rd(i.text),s=o.find((u,d)=>!a.has(d)&&Rd(u.item?u.item.text:u.line)===l);if(!s||(a.add(o.indexOf(s)),!s.item))continue;let c=ty(r,i.numId,i.ilvl),f=ry({requested:s.item,sourceLevel:c});if(f)return{mismatch:f,marker:s.item.marker,numId:i.numId,level:i.ilvl,targetText:i.text}}return null}var ny=new Set(["redline","replace","format","character-format","paragraph-format","list-format","list-change","table-reconciliation","insert","restore","delete","comment","comment_reply","comment_resolve","highlight"]),$d=Object.freeze(["merge-same-author","slice-cross-author","reject-input","accept-all-first","accept-all-first-keep-normalized"]);function ca(e){return $d.includes(e)}function Yt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Se(e){return typeof e=="string"&&e.trim().length>0}function oy(e){return e==="comment_reply"||e==="comment_resolve"}function ay(e){let t=e?.type;return t==="insert"&&e?.target?.revisionView==="rejected"?"rejected-insert":t==="restore"?"restore":t==="comment"||t==="comment_reply"||t==="comment_resolve"||t==="highlight"?t:t==="paragraph-format"?"paragraph-format":t==="list-format"?"list-format":t==="character-format"||t==="format"&&(e?.textToFormat!=null||e?.properties!=null)?"format":"redline"}function xn(e,t=null,r="accepted"){let n=r==="rejected"?"rejected":"accepted";return Yt(e)?{text:typeof e.exactText=="string"?e.exactText:typeof e.text=="string"?e.text:"",index:e.index??e.paragraphIndex??t??null,paragraphId:Se(e.paragraphId)?e.paragraphId.trim():null,occurrence:Number.isInteger(e.occurrence)&&e.occurrence>0?e.occurrence:null,inTable:typeof e.inTable=="boolean"?e.inTable:null,fingerprint:Se(e.fingerprint)?e.fingerprint.trim():Se(e.sourceFingerprint)?e.sourceFingerprint.trim():null,revisionView:e.revisionView==="rejected"?"rejected":e.revisionView==="accepted"?"accepted":n,captureRef:Se(e.captureRef)?e.captureRef.trim():null,select:typeof e.select=="string"?e.select:null}:{text:typeof e=="string"?e:"",index:t??null,paragraphId:null,occurrence:null,inTable:null,fingerprint:null,revisionView:n}}function Nt(e){let t=Yt(e)?e:{},r=ay(t),n=r==="restore"?"rejected":"accepted",o=xn(t.target,t.targetRef,n),a=t.targetEnd!=null?xn(t.targetEnd,t.targetEndRef,n):null;return{...t,operationId:Se(t.operationId)?t.operationId.trim():null,captureKey:Se(t.captureKey)?t.captureKey.trim():null,operationKind:r,anchor:Yt(t.anchor)?{exactText:typeof t.anchor.exactText=="string"?t.anchor.exactText:"",occurrence:Number.isInteger(t.anchor.occurrence)&&t.anchor.occurrence>0?t.anchor.occurrence:1,occurrenceExplicit:Number.isInteger(t.anchor.occurrence)&&t.anchor.occurrence>0,offset:Number.isInteger(t.anchor.offset)?t.anchor.offset:null}:null,targetDescriptor:o,targetEndDescriptor:a,target:o.text,targetRef:o.index,targetEndRef:a?.index??t.targetEndRef??null,...t.type==="delete"&&t.modified==null?{modified:""}:{}}}function Ir(e){if(!Yt(e))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation must be an object."}};let t=e.type;if(t!=null&&t!==""&&!ny.has(t))return{valid:!1,error:{code:"INVALID_OPERATION",message:`Unsupported operation type: "${String(t)}".`}};let r=Nt(e);if(Yt(e.target)&&e.target.revisionView!=null&&e.target.revisionView!=="accepted"&&e.target.revisionView!=="rejected")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Target revisionView must be "accepted" or "rejected" when provided.'}};if(Yt(e.targetEnd)&&e.targetEnd.revisionView!=null&&e.targetEnd.revisionView!=="accepted"&&e.targetEnd.revisionView!=="rejected")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Target revisionView must be "accepted" or "rejected" when provided.'}};if(e.operationId!=null&&(!Se(e.operationId)||e.operationId.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"operationId must be a non-empty string under 256 characters when provided."}};if(e.captureKey!=null&&(!Se(e.captureKey)||e.captureKey.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"captureKey must be a non-empty string under 256 characters when provided."}};if(Yt(e.target)&&e.target.captureRef!=null&&(!Se(e.target.captureRef)||e.target.captureRef.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"target.captureRef must be a non-empty string under 256 characters when provided."}};if(Yt(e.target)&&e.target.select!=null&&typeof e.target.select!="string")return{valid:!1,error:{code:"INVALID_OPERATION",message:"target.select must be a string when provided."}};let n=r.targetDescriptor;if(!oy(r.operationKind)&&!Se(n.text)&&n.index==null&&!n.paragraphId&&!n.fingerprint&&!n.captureRef)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation target must provide text, a paragraph index, a paragraphId, or a captureRef."}};if(n.occurrence!=null&&!Se(n.text))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Target occurrence requires target text."}};if(r.operationKind==="redline"){let o=typeof r.modified=="string",a=r.replacements!==void 0;if(o===a)return{valid:!1,error:{code:"INVALID_OPERATION",message:'Redline operations require exactly one of string "modified" or non-empty "replacements".'}};if(a){if(t!=null&&t!==""&&!["redline","replace"].includes(t))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements are supported only for redline or replace operations."}};if(n.revisionView!=="accepted"||n.captureRef||n.occurrence!=null||r.captureKey||r.targetEndDescriptor||r.targetEndRef!=null)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements v1 require one batch-start accepted-view paragraph target without captures, target occurrence, or a target range."}};let i=bi(r.replacements);if(!i.ok)return{valid:!1,error:i.error};if(i.replacements.some(l=>/\r|\n/.test(l.replace)))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements v1 cannot insert paragraph breaks."}};if(i.replacements.some(l=>/\r|\n/.test(l.find)))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Localized replacements v1 cannot span a line break; use one replacement per line or a full "modified" paragraph.'}};r.replacements=i.replacements}}if(r.operationKind==="rejected-insert"){if(!Se(r.modified))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Rejected-view insert operations require non-empty string "modified" text.'}};if(!r.anchor||!Se(r.anchor.exactText)||!Number.isInteger(r.anchor.offset)||r.anchor.offset<0||r.anchor.offset>r.anchor.exactText.length)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Rejected-view insert operations require anchor.exactText, a positive occurrence, and an offset within the anchor text."}};if(r.existingRevisions!=="slice-cross-author")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Rejected-view insert operations require existingRevisions: "slice-cross-author".'}}}if(r.operationKind==="restore"){let o=e.modified!==void 0,a=e.replacements!==void 0,i=Se(r.modified),l=Array.isArray(r.modified)&&r.modified.length>0&&r.modified.every(Se);if(o&&a)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore operations accept modified or replacements, not both."}};if(o&&!i&&!l)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore modified must be a non-empty string or non-empty string array."}};if(!o&&(n.revisionView!=="rejected"||!n.paragraphId&&!n.fingerprint||n.captureRef||n.occurrence!=null||r.captureKey||r.targetEndDescriptor||r.targetEndRef!=null||/\r|\n/.test(n.text||"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Verbatim and localized restore require one strong batch-start rejected-view paragraph target without captures, target occurrence, or a target range."}};if(a){let s=bi(r.replacements);if(!s.ok)return{valid:!1,error:s.error};if(s.replacements.some(c=>/\r|\n/.test(c.replace)))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized restore cannot insert paragraph breaks."}};r.replacements=s.replacements}if(r.generateRedlines===!1)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore operations require tracked changes and cannot set generateRedlines to false."}}}if(r.structuredContent!=null&&typeof r.structuredContent!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:"structuredContent must be a boolean when provided."}};if(r.pairReplacements!=null&&typeof r.pairReplacements!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:"pairReplacements must be a boolean when provided."}};if(r.listMarkers!=null&&r.listMarkers!=="literal")return{valid:!1,error:{code:"INVALID_OPERATION",message:'listMarkers must be "literal" when provided.'}};if(r.existingRevisions!=null&&!ca(r.existingRevisions))return{valid:!1,error:{code:"INVALID_OPERATION",message:`existingRevisions must be one of: ${$d.join(", ")}.`}};if(r.insertionAffinity!=null){if(!Yt(r.insertionAffinity))return{valid:!1,error:{code:"INVALID_OPERATION",message:"insertionAffinity must be an object when provided."}};let{formatting:o,hyperlink:a,revision:i,bookmark:l,comment:s}=r.insertionAffinity;if(o!=null&&!["left","right","none"].includes(o))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.formatting must be "left", "right", or "none".'}};if(a!=null&&!["inside","outside","preserve"].includes(a))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.hyperlink must be "inside", "outside", or "preserve".'}};if(i!=null&&!["coalesce_same_author","separate"].includes(i))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.revision must be "coalesce_same_author" or "separate".'}};if(l!=null&&!["inside","outside"].includes(l))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.bookmark must be "inside" or "outside".'}};if(s!=null&&!["inside","outside"].includes(s))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.comment must be "inside" or "outside".'}}}if(r.operationKind==="comment"&&!Se(r.commentContent))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment operations require a non-empty "commentContent" field.'}};if(r.operationKind==="comment_reply"){if(!Se(String(r.parentCommentId??"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment reply operations require a "parentCommentId".'}};if(!Se(r.commentContent))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment reply operations require a non-empty "commentContent" field.'}}}if(r.operationKind==="comment_resolve"){if(!Se(String(r.commentId??"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment resolve operations require a "commentId".'}};if(r.resolved!=null&&typeof r.resolved!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment resolve "resolved" must be a boolean when provided.'}}}if(r.operationKind==="highlight"){if(!Se(r.textToHighlight))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Highlight operations require a non-empty "textToHighlight" field.'}};if(r.color!=null&&!Se(r.color))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Highlight color must be a non-empty string when provided."}}}if(r.operationKind==="format"){if(!Se(r.textToFormat))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Format operations require a non-empty "textToFormat" field.'}};if(r.textOccurrence!=null&&(!Number.isInteger(r.textOccurrence)||r.textOccurrence<1))return{valid:!1,error:{code:"INVALID_OPERATION",message:"textOccurrence must be a positive integer when provided."}};if(!Yt(r.properties))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Format operations require a "properties" object.'}};if(r.formattingRevisionPolicy!=null&&!["always","coalesce-own-insertion"].includes(r.formattingRevisionPolicy))return{valid:!1,error:{code:"INVALID_OPERATION",message:'formattingRevisionPolicy must be "always" or "coalesce-own-insertion".'}}}if(r.operationKind==="paragraph-format"){if(!Yt(r.properties))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Paragraph-format operations require a "properties" object.'}};let o=Ai(r.properties);if(o.length>0)return{valid:!1,error:{code:"INVALID_OPERATION",message:`paragraph-format does not support ${o.length===1?"property":"properties"} ${o.map(a=>`"${a}"`).join(", ")}. Supported: ${co.join(", ")}.`,field:`properties.${o[0]}`,properties:o,recovery:{action:"change_request",hint:`Use only: ${co.join(", ")}.`}}};if(r.properties.numbering!==void 0){let a=Ld(r.properties.numbering);if(a)return{valid:!1,error:{code:"INVALID_OPERATION",message:a,field:"properties.numbering",recovery:{action:"change_request",hint:'Pass numbering as { "numId": <existing numId from inspect>, "level": 0 } or null.'}}}}}if(r.operationKind==="list-format"){let o=Nd(r.list);if(o)return{valid:!1,error:{code:"INVALID_OPERATION",message:o.message,field:o.field,recovery:{action:"change_request",hint:'Pass list as { "mode": "convert-plain" } (optional format, kind, level, strip "marker" | "none", start with strip "none"), { "mode": "change-format", "format": ... } (optional kind, lvlText, start, level, scope "list" | "range") or { "mode": "join", "continueFrom": { "paragraphId": ... } } (optional scope).'}}};if(e.modified!==void 0||e.replacements!==void 0)return{valid:!1,error:{code:"INVALID_OPERATION",message:"list-format changes list structure only; express text changes as a separate redline operation.",field:e.modified!==void 0?"modified":"replacements"}};if(n.captureRef||n.occurrence!=null||n.revisionView!=="accepted")return{valid:!1,error:{code:"INVALID_OPERATION",message:"list-format v1 targets batch-start accepted-view paragraphs without captures or target occurrence."}}}return r.author!=null&&!Se(r.author)?{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation author must be a non-empty string when provided."}}:{valid:!0,operation:r}}function Dt(e,t,r){return Se(e?.author)?e.author.trim():Se(t)?t.trim():Se(r)?r.trim():"Author"}var Xr=class{constructor(t,r={}){if(this.originalDocumentXml=typeof t=="string"?t:"",this.currentDocumentXml=this.originalDocumentXml,this.serializer=se(),this.parseResult=j(this.originalDocumentXml,"application/xml"),this.document=this.parseResult.doc||null,this.revisionIdAllocator=null,this.initialTargetReferenceSnapshot=null,this.paragraphIndex=null,this.invalidated=!1,this.hasChanges=!1,this.documentHasChanges=!1,this.deferSerialization=r?._deferDocumentSerialization===!0,this.instrumentation=r?._sessionInstrumentation||null,this.runtimeContext=null,this.commentsXml=null,this.commentsExtendedXml=null,this.commentsXmlMode="merge",this.commentsExtendedXmlMode="merge",this.numberingXmlParts=[],this.results=[],this.executionOrder=[],this.authorsUsed=new Set,this.captureTable=new Map,this.sourceTargetRegistry=null,this.nextCaptureParaId=1,this.receiptCollector=new aa,this.document){this.instrumentation?.onDocumentParse?.(this.originalDocumentXml),this.revisionIdAllocator=r?._revisionIdAllocator instanceof Fe?r._revisionIdAllocator:new Fe,this.revisionIdAllocator._receiptCollector=this.receiptCollector,cr(this.document,this.revisionIdAllocator),Rr(this.document,this.revisionIdAllocator);let n=this.getParagraphMetadataIndex();this.initialTargetReferenceSnapshot=Os(this.document,n)}}get valid(){return!!this.document&&!this.parseResult.error}setDocumentXml(t){this.currentDocumentXml=t,this.invalidateParagraphIndex()}invalidateParagraphIndex(){this.invalidated=!0,this.paragraphIndex=null}serialize(){return this.document?(this.instrumentation?.onDocumentSerialize?.(this.document),this.serializer.serializeToString(this.document)):this.currentDocumentXml}serializeCurrent(){return this.hasChanges?this.documentHasChanges?(this.currentDocumentXml=this.serialize(),this.currentDocumentXml):this.currentDocumentXml:this.originalDocumentXml}markMutationCommitted(t=!0){this.hasChanges=!0,this.documentHasChanges=this.documentHasChanges||t,t&&this.invalidateParagraphIndex()}generateParagraphId(){return(1073741824+this.nextCaptureParaId++).toString(16).toUpperCase()}createSavepoint(){return this.document?{document:this.document.cloneNode(!0),allocatorNextId:this.revisionIdAllocator?.nextId,allocatorOccupiedIds:this.revisionIdAllocator?.occupiedIds instanceof Set?new Set(this.revisionIdAllocator.occupiedIds):null,hasChanges:this.hasChanges,documentHasChanges:this.documentHasChanges,currentDocumentXml:this.currentDocumentXml,commentsXml:this.commentsXml,commentsExtendedXml:this.commentsExtendedXml,commentsXmlMode:this.commentsXmlMode,commentsExtendedXmlMode:this.commentsExtendedXmlMode,captureTable:Dd(this.captureTable),sourceTargetRegistry:this.sourceTargetRegistry?.createSavepoint?.(this.document)||null,nextCaptureParaId:this.nextCaptureParaId,receiptCollector:this.receiptCollector?this.receiptCollector.createSavepoint():null}:null}restoreSavepoint(t){t?.document&&(this.document=t.document,this.hasChanges=t.hasChanges,this.documentHasChanges=t.documentHasChanges===!0,this.currentDocumentXml=t.currentDocumentXml,this.commentsXml=t.commentsXml,this.commentsExtendedXml=t.commentsExtendedXml,this.commentsXmlMode=t.commentsXmlMode||"merge",this.commentsExtendedXmlMode=t.commentsExtendedXmlMode||"merge",this.captureTable=t.captureTable?Dd(t.captureTable):new Map,this.sourceTargetRegistry?.restoreSavepoint?.(this.document,t.sourceTargetRegistry),typeof t.nextCaptureParaId=="number"&&(this.nextCaptureParaId=t.nextCaptureParaId),this.revisionIdAllocator&&(this.revisionIdAllocator.nextId=t.allocatorNextId,t.allocatorOccupiedIds instanceof Set&&(this.revisionIdAllocator.occupiedIds=new Set(t.allocatorOccupiedIds)),this.revisionIdAllocator._receiptCollector=this.receiptCollector,Rr(this.document,this.revisionIdAllocator)),t.receiptCollector&&this.receiptCollector&&this.receiptCollector.restoreSavepoint(t.receiptCollector),this.invalidateParagraphIndex())}getParagraphIndex(){return this.getParagraphMetadataIndex().entries}getParagraphMetadataIndex(){return this.paragraphIndex?this.paragraphIndex:(this.paragraphIndex=rr(this.document),this.invalidated=!1,this.paragraphIndex)}rollback(){return this.currentDocumentXml=this.originalDocumentXml,this.hasChanges=!1,this.documentHasChanges=!1,this.captureTable.clear(),this.sourceTargetRegistry=null,this.receiptCollector?.clear(),this.originalDocumentXml}};function Dd(e){let t=new Map;if(e instanceof Map)for(let[r,n]of e.entries())t.set(r,JSON.parse(JSON.stringify(n)));return t}function Nn(e,t={}){let r=t?._revisionIdAllocator instanceof Fe?t._revisionIdAllocator:new Fe;return t?._documentOperationSession?.receiptCollector&&(r._receiptCollector=t._documentOperationSession.receiptCollector),cr(e,r),Rr(e,r),r}function Ud(e){if(!e||typeof e!="object")return{};let t={...e};return e.listFallbackSharedNumIdByKey instanceof Map&&(t.listFallbackSharedNumIdByKey=new Map(e.listFallbackSharedNumIdByKey)),e.tableStructuralRedlineKeys instanceof Set&&(t.tableStructuralRedlineKeys=new Set(e.tableStructuralRedlineKeys)),e.numberingIdState&&typeof e.numberingIdState=="object"&&(t.numberingIdState={...e.numberingIdState,usedNumIds:e.numberingIdState.usedNumIds instanceof Set?new Set(e.numberingIdState.usedNumIds):e.numberingIdState.usedNumIds,usedAbstractNumIds:e.numberingIdState.usedAbstractNumIds instanceof Set?new Set(e.numberingIdState.usedAbstractNumIds):e.numberingIdState.usedAbstractNumIds}),e.listFallbackSequenceState&&typeof e.listFallbackSequenceState=="object"&&(t.listFallbackSequenceState={...e.listFallbackSequenceState,explicitByNumberingKey:e.listFallbackSequenceState.explicitByNumberingKey instanceof Map?new Map(e.listFallbackSequenceState.explicitByNumberingKey):e.listFallbackSequenceState.explicitByNumberingKey}),t}function zd(e,t){if(!(!e||typeof e!="object")){if(e.listFallbackSharedNumIdByKey instanceof Map&&t.listFallbackSharedNumIdByKey instanceof Map){e.listFallbackSharedNumIdByKey.clear();for(let r of t.listFallbackSharedNumIdByKey)e.listFallbackSharedNumIdByKey.set(...r);t.listFallbackSharedNumIdByKey=e.listFallbackSharedNumIdByKey}if(e.tableStructuralRedlineKeys instanceof Set&&t.tableStructuralRedlineKeys instanceof Set){e.tableStructuralRedlineKeys.clear();for(let r of t.tableStructuralRedlineKeys)e.tableStructuralRedlineKeys.add(r);t.tableStructuralRedlineKeys=e.tableStructuralRedlineKeys}if(e.numberingIdState&&t.numberingIdState){for(let r of["usedNumIds","usedAbstractNumIds"])if(e.numberingIdState[r]instanceof Set&&t.numberingIdState[r]instanceof Set){e.numberingIdState[r].clear();for(let n of t.numberingIdState[r])e.numberingIdState[r].add(n);t.numberingIdState[r]=e.numberingIdState[r]}Object.assign(e.numberingIdState,t.numberingIdState),t.numberingIdState=e.numberingIdState}if(e.listFallbackSequenceState&&t.listFallbackSequenceState){let r=e.listFallbackSequenceState.explicitByNumberingKey,n=t.listFallbackSequenceState.explicitByNumberingKey;if(r instanceof Map&&n instanceof Map){r.clear();for(let o of n)r.set(...o);t.listFallbackSequenceState.explicitByNumberingKey=r}Object.assign(e.listFallbackSequenceState,t.listFallbackSequenceState),t.listFallbackSequenceState=e.listFallbackSequenceState}Object.assign(e,t)}}var Xd=new Set(["redline","restore","rejected-insert","list-format"]),Vd=new Set(["highlight","format","paragraph-format"]),iy="http://schemas.openxmlformats.org/wordprocessingml/2006/main",jd="LIST_FORMAT_COMPOSITION_CONFLICT",sy=new Set(["redline","replace"]);function Wd(e){let t=String(e??""),r=lo(t);return r?r.unsupported?`unsupported:${r.marker}`:t.slice(0,r.prefixLength):null}function ly(e,t){let r=e.operation;if(!sy.has(r?.type??"redline")||r.targetEnd!=null||r.targetEndRef!=null||r.anchor!=null||r.structuredContent===!0||r.part!=null||r.target?.revisionView==="rejected"||typeof r.modified!="string"||/[\r\n]/.test(r.modified))return{reason:"redline-shape",hint:"Pair a list-format only with a single-paragraph redline or replace of that paragraph: modified without line breaks, no targetEnd, anchor, part or structuredContent."};if(r.modified===t)return{reason:"redline-unchanged",hint:"The redline does not change the text; drop it and send only the list-format."};let n=Wd(t),o=Wd(r.modified);return n!==o?{reason:"marker-changed",sourceMarker:n,modifiedMarker:o,hint:'The redline adds, removes or changes the typed marker. Keep the marker text exactly as it is (the list-format strips it), and express a new label through list-format (strip "none" with format/start, or change-format).'}:null}function cy(e,t,r,n){let o=n.list?.mode;if(o!=="change-format"&&o!=="join")return[];if((n.list?.scope||"list")!=="list")return[];let a=r.sourceIds.map(l=>t.entries.get(l)?.paragraph).filter(Boolean),i=a.map(l=>_e(l)).find(Boolean);return i?Array.from(e.getElementsByTagNameNS(iy,"p")).filter(l=>a.includes(l)||Ot(l)?!1:_e(l)?.numId===i.numId):[]}function uy(e){let t={};if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="name"||r==="stack"||r==="message"||r==="code"||(t[r]=n);return{code:typeof e?.code=="string"&&e.code?e.code:"OPERATION_ERROR",message:e?.message||String(e),...t}}function fy(e,t){return!!t&&ae(e).includes(t)}function dy(e=[]){let t=[];for(let r of e)if(!(!r||r.nodeType!==1)){r.localName==="p"&&t.push(r);for(let n of Array.from(r.getElementsByTagNameNS?.("*","p")||[]))t.includes(n)||t.push(n)}return t}var Nl=class{constructor(t){this.document=t,this.nextId=1,this.entries=new Map,this.idsByNode=new WeakMap}register(t,r={}){let n=this.idsByNode.get(t);if(n)return n;let o=`S${this.nextId++}`;return this.entries.set(o,{sourceId:o,paragraph:t,sourceIndex:r.index||null,paragraphId:r.paragraphId||null,fingerprint:r.fingerprint||null,text:r.text||"",revisionView:r.revisionView==="rejected"?"rejected":"accepted",consumed:!1,consumedByOperation:null}),this.idsByNode.set(t,o),o}describe(t){let r=this.entries.get(t);return r?{sourceId:t,index:r.sourceIndex,paragraphId:r.paragraphId,fingerprint:r.fingerprint,text:r.text,revisionView:r.revisionView}:null}resolve(t,r=this.document){let n=this.entries.get(t);return n?n.consumed?{error:{code:"TARGET_CONSUMED_BY_OPERATION",message:`Compiled source target ${t} was consumed by operation ${n.consumedByOperation}.`,sourceTarget:this.describe(t),consumedByOperation:n.consumedByOperation}}:fy(r,n.paragraph)?{paragraph:n.paragraph,resolvedBy:"batch_source"}:{error:{code:"TARGET_CONSUMED_BY_OPERATION",message:`Compiled source target ${t} is no longer present in the live document.`,sourceTarget:this.describe(t),consumedByOperation:n.consumedByOperation}}:{error:{code:"SOURCE_TARGET_NOT_FOUND",message:`Compiled source target ${String(t)} was not found.`}}}createSavepoint(t=this.document){let r=ae(t);return new Map(Array.from(this.entries,([n,o])=>[n,{paragraphIndex:r.indexOf(o.paragraph),consumed:o.consumed,consumedByOperation:o.consumedByOperation}]))}restoreSavepoint(t,r){this.document=t,this.idsByNode=new WeakMap;let n=ae(t);for(let[o,a]of this.entries){let i=r instanceof Map?r.get(o):null;a.consumed=i?.consumed===!0,a.consumedByOperation=i?.consumedByOperation||null,a.paragraph=Number.isInteger(i?.paragraphIndex)&&i.paragraphIndex>=0&&n[i.paragraphIndex]||null,a.paragraph&&this.idsByNode.set(a.paragraph,o)}}previewSuccessor(t,r,n){let o=this.entries.get(t);if(!o||!o.paragraph)return null;if(!Array.isArray(r)||!r.includes(o.paragraph))return o.paragraph;let a=dy(n),i=o.paragraphId?a.filter(l=>Ke(l)===o.paragraphId):[];return i.length===1?i[0]:a.length===1?a[0]:null}commitMutation(t,r,n,o){let a=this.entries.get(t);if(!a||!Array.isArray(r)||!r.includes(a.paragraph))return;let i=this.previewSuccessor(t,r,n);if(i){a.paragraph=i,this.idsByNode.set(i,t);return}a.paragraph=null,a.consumed=!0,a.consumedByOperation=o}};function my(e,t){return{index:e.index,paragraphId:e.paragraphId,fingerprint:e.fingerprint,text:e.text,inTable:e.inTable,revisionView:t}}function xl(e,t,r,n,o,a={}){let i=t?.revisionView==="rejected"?"rejected":"accepted";o[i]||(o[i]=rr(e,{revisionView:i}));let l=o[i],s=an(e,{targetText:t.text,targetRef:t.index,targetDescriptor:t,opType:r,strictAmbiguity:n,paragraphMetadataIndex:l,metadataIndices:o,onInfo:a.onInfo,onWarn:a.onWarn}),c=l.byParagraph.get(s.paragraph);return{paragraph:s.paragraph,resolvedBy:s.resolvedBy,metadata:my(c,i)}}function Si(e,t,r,n,o,a={},i=null){return{code:e,message:t,operationIndexes:r.map(l=>l.index).sort((l,s)=>l-s),target:n,...a,recovery:{action:o,sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1,...i?{hint:i}:{}}}}function uo(e,t=[],r={}){let n=Array.isArray(t)?t:[],o=r.strictTargets!==!1,a=new Nl(e),i={accepted:rr(e,{revisionView:"accepted"}),rejected:null},l=[],s=[];for(let h=0;h<n.length;h+=1){let v=n[h],w=Ir(v),y=w.operation||Nt(v),b={index:h+1,operationKind:y.operationKind,operationId:y.operationId,sourceIds:[],warnings:[]},I={...v},E=y.targetDescriptor?.occurrence!=null&&!y.targetDescriptor?.paragraphId&&!y.targetDescriptor?.fingerprint,N=typeof y.targetDescriptor?.text=="string"&&/\r|\n/.test(y.targetDescriptor.text)&&!y.targetEndDescriptor&&!Array.isArray(y.replacements);if((E||N)&&(b.dynamic=!0),w.valid&&y.operationKind!=="comment_reply"&&y.operationKind!=="comment_resolve"&&!y.targetDescriptor?.captureRef&&!b.dynamic)try{let R=xl(e,y.targetDescriptor,y.operationKind,o,i,{onInfo:r.onInfo,onWarn:A=>b.warnings.push(String(A))}),x=a.register(R.paragraph,R.metadata);if(b.sourceIds.push(x),b.resolvedBy=R.resolvedBy,b.resolvedTarget=R.metadata,I._compiledSourceId=x,I._compiledResolvedBy=R.resolvedBy,b.warnings.length>0&&(I._compiledWarnings=b.warnings),Array.isArray(y.replacements)){let A=ud(R.metadata.text,y.replacements);if(!A.ok)throw Object.assign(new Error(A.error.message),A.error);I.modified=A.desiredText,delete I.replacements,I._localizedReplacementCompilation={sourceText:R.metadata.text,desiredText:A.desiredText,replacements:A.replacements};let S=Ir(I);if(!S.valid)throw Object.assign(new Error(S.error.message),S.error)}else if(y.operationKind==="restore"&&v.modified===void 0){I.modified=R.metadata.text;let A=Ir(I);if(!A.valid)throw Object.assign(new Error(A.error.message),A.error)}let T=y.targetEndDescriptor||(y.targetEndRef!=null?xn(null,y.targetEndRef,y.targetDescriptor.revisionView):null);if(T){let A=xl(e,T,y.operationKind,o,i,{onInfo:r.onInfo,onWarn:M=>b.warnings.push(String(M))}),S=a.register(A.paragraph,A.metadata);I._compiledSourceEndId=S;let O=ae(e),C=O.indexOf(R.paragraph),P=O.indexOf(A.paragraph);if(C<0||P<C)throw Object.assign(new Error("Target range is not a forward contiguous paragraph range."),{code:"TARGET_RANGE_INVALID"});for(let M of O.slice(C,P+1)){let k=(i[y.targetDescriptor.revisionView]||i.accepted).byParagraph.get(M);b.sourceIds.push(a.register(M,k||{}))}b.sourceIds=[...new Set(b.sourceIds)],b.resolvedTargetEnd=A.metadata}if(y.operationKind==="list-format"&&y.list?.continueFrom&&typeof y.list.continueFrom=="object"){let A;try{A=xl(e,xn(y.list.continueFrom,null,"accepted"),y.operationKind,o,i,{onInfo:r.onInfo,onWarn:S=>b.warnings.push(String(S))})}catch(S){throw Object.assign(S instanceof Error?S:new Error(String(S)),{field:"list.continueFrom"})}I._compiledContinueFromId=a.register(A.paragraph,A.metadata),b.resolvedContinueFrom=A.metadata}}catch(R){b.error=uy(R)}l.push(b),s.push(I)}let c=new Set(s.map(h=>h?.captureKey).filter(Boolean)),f=1;for(let h of l){if(h.error?.code!=="TARGET_NOT_FOUND")continue;let v=h.index-1,y=Nt(n[v]).targetDescriptor?.text;if(!y)continue;let b=n.flatMap((R,x)=>x===v||typeof R?.modified!="string"?[]:R.modified.split(/\r?\n/).map(A=>A.trim()).filter(Boolean).includes(y.trim())?[{candidate:R,producerIndex:x}]:[]);if(b.length!==1)continue;let[{candidate:I,producerIndex:E}]=b,N=I.captureKey||s[E].captureKey;if(!N){do N=`__batch_created_${f++}`;while(c.has(N));c.add(N),s[E].captureKey=N}s[v].target={captureRef:N,select:y},delete s[v]._compiledSourceId,delete s[v]._compiledResolvedBy,delete h.error,h.sourceIds=[],h.resolvedBy="created_content_dependency",h.createdByOperation=E+1,h.captureRef=N}let u=new Map,d=new Map;for(let h of l)if(!(h.error||h.dynamic)){for(let v of h.sourceIds)u.has(v)||u.set(v,[]),u.get(v).push(h);if(h.operationKind==="list-format"){let v=s[h.index-1];for(let w of cy(e,a,h,v)){let y=a.register(w,i.accepted.byParagraph.get(w)||{});h.sourceIds.includes(y)||((h.rebindSourceIds||(h.rebindSourceIds=[])).push(y),u.has(y)||u.set(y,[]),d.has(y)||d.set(y,[]),d.get(y).push(h))}}}let m=[],p=new Set,g=(h,v)=>{p.has(h)||(p.add(h),m.push(v))};for(let[h,v]of u){let w=d.get(h)||[],y=[...v,...w].filter(x=>Xd.has(x.operationKind)||Vd.has(x.operationKind)),b=y.filter(x=>x.operationKind==="list-format"),I=y.filter(x=>x.operationKind!=="list-format");if(b.length===1&&I.length===1&&I[0].operationKind==="redline"){let[x]=b,[T]=I,A=a.describe(h),S=ly({operation:s[T.index-1]},T.resolvedTarget?.text??A?.text??"");if(S){let P=[T,x];g(`list:${P.map(M=>M.index).sort().join(",")}`,Si(jd,`Operations ${P.map(M=>M.index).sort((M,_)=>M-_).join(", ")} combine a redline and a list-format on the same paragraph in a way that does not compose (${S.reason}).`,P,A,"split_text_and_list_changes",{reason:S.reason,...S.sourceMarker!==void 0?{sourceMarker:S.sourceMarker,modifiedMarker:S.modifiedMarker}:{}},S.hint));continue}let O=s[x.index-1],C=new Set(O._compiledRunAfter||[]);C.add(T.index-1),O._compiledRunAfter=[...C].sort((P,M)=>P-M),x.composedWith=[...new Set([...x.composedWith||[],T.index])],T.composedWith=[...new Set([...T.composedWith||[],x.index])];continue}if(w.length>0&&y.length>1){g(`rebind:${y.map(x=>x.index).sort().join(",")}`,Si(jd,`Operation ${w.map(x=>x.index).join(", ")} (list-format, scope "list") rebinds this list item, and operations ${y.filter(x=>!w.includes(x)).map(x=>x.index).join(", ")} also write it.`,y,a.describe(h),"split_text_and_list_changes",{reason:"list-rebind",rebindingOperationIndexes:w.map(x=>x.index)},'A list-format with scope "list" rewrites every item of the list; in the same batch only one single-paragraph redline per item can compose with it. Send the other change in a separate apply, or use scope "range".'));continue}let E=v,N=E.filter(x=>Xd.has(x.operationKind)),R=E.filter(x=>Vd.has(x.operationKind));if(N.length>1){let x=`text:${N.map(T=>T.index).sort().join(",")}`;p.has(x)||(p.add(x),m.push(Si("OVERLAPPING_SOURCE_TARGETS",`Operations ${N.map(T=>T.index).join(", ")} contain incompatible text writes to the same batch-start source target.`,N,a.describe(h),"consolidate_operations")))}if(N.length>0&&R.length>0){let x=[...N,...R],T=`format:${x.map(A=>A.index).sort().join(",")}`;p.has(T)||(p.add(T),m.push(Si("REVISION_ORDER_CONFLICT",`Operations ${x.map(A=>A.index).join(", ")} combine text and formatting writes on the same batch-start source target.`,x,a.describe(h),"split_or_consolidate_operations")))}}return{valid:m.length===0&&l.every(h=>!h.error),compiledOperations:s,bindings:l,conflicts:m,registry:a}}function Kd(e){return`${e?.source||""}${e?.severity||""}${e?.code||""}${e?.message||""}`}function Tn(e=[],t=[]){let r=new Map;for(let n of t||[]){let o=Kd(n);r.set(o,(r.get(o)||0)+1)}return(e||[]).filter(n=>{let o=Kd(n),a=r.get(o)||0;return a===0?!0:(r.set(o,a-1),!1)})}function An(e=[]){return(e||[]).filter(t=>t?.severity==="error")}var py="PARAGRAPH_FORMAT_REVISION_CONFLICT",gy=new Set(["pPr","bookmarkStart","bookmarkEnd","proofErr","commentRangeStart","commentRangeEnd","permStart","permEnd"]),hy=new Set(["rPr","t","tab","br","cr","noBreakHyphen","softHyphen","lastRenderedPageBreak"]),wy=new Set(["rPr","t","tab","lastRenderedPageBreak"]),ua=(e,t=80)=>{let r=String(e??"");return r.length>t?`${r.slice(0,t)}...`:r},Tl=e=>String(e?.localName||e?.nodeName||"").replace(/^.*:/,""),Al=e=>e?.getAttribute?.("w:val")??e?.getAttribute?.("val")??null;function fe(e,t,r={},n=null){return{ok:!1,error:{code:e,message:t,...r,...n?{recovery:n}:{}}}}function Ei(e){let t=String(e||"");return t.trim()&&j(t,"application/xml")?.doc||null}function Sl(e,t){if(!e)return null;let r=Array.from(e.getElementsByTagNameNS("*","style")).filter(a=>(a.getAttribute("w:type")??a.getAttribute("type"))==="paragraph"),n=new Map(r.map(a=>[a.getAttribute("w:styleId")??a.getAttribute("styleId"),a])),o=t?n.get(t):r.find(a=>["1","true","on"].includes(a.getAttribute("w:default")??a.getAttribute("default")));for(let a=0;o&&a<16;a+=1){let i=Je(de(o,"pPr"),"numPr"),l=Al(Je(i,"numId"));if(l!=null)return l==="0"?null:{numId:l,styleId:o.getAttribute("w:styleId")??o.getAttribute("styleId")};o=n.get(Al(de(o,"basedOn")))}return null}function vy(e,t,r){let n=[],o=0,a="";for(let i of Array.from(e.childNodes||[])){if(o>=t)break;if(i.nodeType!==1)continue;let l=Tl(i);if($(i,"r")){let s=jt(i),c=bt(s);if(c===0){if(Array.from(i.childNodes||[]).some(p=>p.nodeType===1&&!wy.has(Tl(p))))return{reason:"run-content"};continue}if(Array.from(i.childNodes||[]).filter(m=>m.nodeType===1).map(Tl).some(m=>!hy.has(m)))return{reason:"run-content"};let u=Math.min(t,o+c)-o,d=0;for(let m of s){if(d>=u)break;if(!$(m.node,"t")&&!$(m.node,"tab"))return{reason:"run-content"};d=m.end}n.push({run:i,start:o,end:o+c,pieces:s}),a+=s.map(m=>m.text).join(""),o+=c;continue}if(!gy.has(l))return{reason:l==="ins"||l==="del"||l==="moveTo"||l==="moveFrom"?"tracked-change":"container"}}return o<t||a.slice(0,t)!==r?{reason:"text-mismatch"}:{segments:n}}function yy(e,t,r,{author:n,generateRedlines:o,revisionIdAllocator:a}){for(let i of t){let{run:l,start:s,end:c,pieces:f}=i,u=Math.min(r,c)-s;if(u<=0)continue;let d=l.parentNode,m=de(l,"rPr");if(o){let p=Lr(e,Rt(e,f,0,u,!0),m);d.insertBefore(tr(e,"del",p,n),l)}if(u<c-s){let p=Lr(e,Rt(e,f,u,c-s,!1),m);o&&Bt(p,a),d.insertBefore(p,l)}d.removeChild(l)}}function El(e,t){return t==null?!1:Vt(e.documentElement).some(r=>Al(r)===String(t))}function Rl(e){if(!e||typeof e!="object")return null;(!e.listFallbackSequenceState||typeof e.listFallbackSequenceState!="object")&&(e.listFallbackSequenceState={explicitByNumberingKey:new Map});let t=e.listFallbackSequenceState;return t.explicitByNumberingKey instanceof Map||(t.explicitByNumberingKey=new Map),t.explicitByNumberingKey}function Pl(e,t){if(e?.numberingIdState)return e.numberingIdState;let r=Ht(e?.numberingXml||t?.numberingXml||void 0);return e&&typeof e=="object"&&(e.numberingIdState=r),r}function Cl(e,t,r,n={}){let o=n.generateRedlines!==!1,a=n.author,i=typeof n.paragraphIndexOf=="function"?n.paragraphIndexOf:()=>null,l=Ei(n.stylesXml),s=r.strip==="none"?"none":"marker",c=[],f=[];for(let A of t){let S=i(A),O=Q(A,{revisionView:"accepted"}),C=_e(A);if(C)return fe(vd,`Paragraph ${S??""} is already a list item (numId ${C.numId}, level ${C.ilvl}); convert-plain converts plain paragraphs only.`.replace(" "," "),{paragraphIndex:S,numId:C.numId,level:C.ilvl,targetExcerpt:ua(O)},{action:"use_paragraph_numbering",hint:"Narrow the range to plain paragraphs. To move a list item to another existing list or level, use paragraph-format with properties.numbering."});let P=nt(A),_=P.numPr?.numId==="0"?null:Sl(l,P.pStyle);if(_)return fe(Ii,`Paragraph ${S??""} is numbered by its style "${_.styleId}" (numId ${_.numId}); it is already a list item through the style.`.replace(" "," "),{paragraphIndex:S,styleId:_.styleId,numId:_.numId,targetExcerpt:ua(O)},{action:"convert_in_host",hint:"Style-linked numbering is not rebound by list-format-v1. Change the paragraph style or the style's numbering in the host."});if(!O.trim()){f.push({paragraph:A,paragraphIndex:S,reason:"empty"});continue}if(s==="none"){c.push({paragraph:A,paragraphIndex:S,text:O,parsed:null});continue}let k=lo(O);if(k?.unsupported){let L={multilevel:'multi-level markers such as "2.1." need a multi-level list definition',parenthesized:'parenthesized markers such as "(a)" are not supported',zero:"a marker value of 0 cannot start a Word list"}[k.unsupported];return fe(la,`The typed marker "${k.marker}" is not supported by list-format-v1: ${L}.`,{reason:k.unsupported,marker:k.marker,paragraphIndex:S,targetExcerpt:ua(O)},{action:"convert_in_host",hint:"Convert this paragraph in the host, or leave the marker as literal text."})}if(!k){f.push({paragraph:A,paragraphIndex:S,reason:"no-marker"});continue}c.push({paragraph:A,paragraphIndex:S,text:O,parsed:k})}if(c.length===0)return fe(hd,s==="marker"?'No target paragraph starts with a typed list marker (for example "A. ", "1. ", "iv. " or "- "), so there is nothing to strip.':"The target range has no non-empty paragraph to convert.",{targetExcerpt:ua(f[0]?Q(f[0].paragraph):"")},{action:"change_request",hint:'Target the paragraphs that carry the typed markers, or pass strip: "none" with list.format to bind paragraphs whose text has no marker.',field:"list.strip",allowedValue:"none"});let u=r.format;if(s==="marker"){let A=Td(c.map(S=>S.parsed),r.format);if(A.error){let{reason:S}=A.error;if(S==="ambiguous")return fe(wd,`The typed marker "${A.error.marker}" reads as ${A.error.formats.join(" or ")}; list-format will not guess.`,{marker:A.error.marker,formats:A.error.formats},{action:"set_list_format",hint:`Pass list.format (${A.error.formats.join(" or ")}).`,field:"list.format",allowedValues:A.error.formats});let O=S==="format-mismatch"?`The typed marker "${A.error.marker}" is not a ${A.error.requestedFormat} marker.`:`The target range mixes list markers (${[...new Set(A.error.markers)].join(", ")}); one convert-plain operation converts one list format.`;return fe(la,O,{reason:S,...A.error.marker?{marker:A.error.marker}:{},...A.error.markers?{markers:A.error.markers}:{}},{action:"change_request",hint:S==="format-mismatch"?"Omit list.format to use the typed marker, or correct it.":"Split the range into one operation per marker format."})}u=A.format}if(r.kind&&r.kind==="bullet"!=(u==="bullet"))return fe(la,`The typed markers are ${u} markers, not a ${r.kind} list.`,{reason:"format-mismatch",requestedKind:r.kind},{action:"change_request",hint:"Omit list.kind, or target paragraphs whose markers match it."});let d=s==="marker"?c[0].parsed.terminator:".",m=s==="marker"&&c[0].parsed.bulletChar||null,p=r.level||0;for(let A of c){let S=Je(de(A.paragraph,"pPr"),"pPrChange"),O=S?.getAttribute("w:author")??S?.getAttribute("author")??"";if(o&&S&&O!==a)return fe(py,`Paragraph ${A.paragraphIndex??""} already has a pending paragraph-property change by "${O||"unattributed"}". Overwriting its snapshot would change what Reject All restores.`.replace(" "," "),{pendingAuthor:O,paragraphIndex:A.paragraphIndex},{action:"resolve_pending_revision",hint:"Ask the user to accept or reject the existing paragraph formatting change first; this tool does not resolve revisions by other reviewers."});if(A.keepSnapshot=!!S,s==="marker"){let C=vy(A.paragraph,A.parsed.prefixLength,A.text.slice(0,A.parsed.prefixLength));if(C.reason)return fe(la,`The typed marker "${A.parsed.marker}" is not plain run text (${C.reason}), so it cannot be stripped as one tracked deletion.`,{reason:"marker-shape",shape:C.reason,marker:A.parsed.marker,paragraphIndex:A.paragraphIndex,targetExcerpt:ua(A.text)},{action:"convert_in_host",hint:"The marker sits inside a hyperlink, field, content control or pending revision. Resolve that markup first or convert the paragraph in the host."});A.segments=C.segments}}let g=Rl(n.runtimeContext),h=Ed({format:u,level:p,terminator:d,bulletChar:m}),v=g?.get(h)||null,w=v&&El(e,v.numId),y=s==="none"?r.start??(w&&Number.isInteger(v.nextStartAt)?v.nextStartAt:1):null;for(let A of c)u==="bullet"?A.value=null:s==="marker"?A.value=Ad(A.parsed,u):A.value=y++;let b=Pl(n.runtimeContext,n),I=Sd({format:u,level:p,terminator:d,bulletChar:m}),E=[],N=[],R=null,x=null;for(let[A,S]of c.entries()){if(!(A>0&&(u==="bullet"||S.value===x+1)))if(A===0&&w&&(u==="bullet"||v.nextStartAt===S.value))R=String(v.numId);else{let P=Ko({numberingIdState:b,levels:[I],startOverrides:S.value!=null&&S.value!==1?{[p]:S.value}:void 0});if(!P)return fe("NUMBERING_ID_EXHAUSTED","No numbering ids are available for a new list definition.",{},{action:"report_library_failure"});R=String(P.numId),N.push(P.numId),E.push(P.numberingXml)}S.numId=R,x=S.value}for(let A of c){let S=de(A.paragraph,"pPr");S||(S=F(e,"w:pPr"),A.paragraph.insertBefore(S,A.paragraph.firstChild)),o&&!A.keepSnapshot&&Wn(e,S,a),Vn(e,S,{numbering:{numId:A.numId,level:p}}),s==="marker"&&yy(e,A.segments,A.parsed.prefixLength,{author:a,generateRedlines:o,revisionIdAllocator:n.revisionIdAllocator||null})}let T=c[c.length-1];return g?.set(h,{numId:T.numId,nextStartAt:T.value!=null?T.value+1:null}),{ok:!0,format:u,level:p,strip:s,items:c.map(A=>({paragraph:A.paragraph,paragraphIndex:A.paragraphIndex,marker:A.parsed?.marker??null,value:A.value,numId:A.numId})),skipped:f,numberingXml:E.length>0?hr("",E):null,allocatedNumIds:N}}var Gd="http://schemas.openxmlformats.org/wordprocessingml/2006/main",by="PARAGRAPH_FORMAT_REVISION_CONFLICT",Ol=8,kl=(e,t=80)=>{let r=String(e??"");return r.length>t?`${r.slice(0,t)}...`:r},fo=e=>e?.getAttribute?.("w:val")??e?.getAttribute?.("val")??null,En=(e,t="val")=>{let r=e?.getAttribute?.(`w:${t}`)??e?.getAttribute?.(t),n=Number.parseInt(String(r??""),10);return Number.isFinite(n)?n:null},Sn=e=>e==="bullet";function Hd(e){let t=String(e||""),r=t.trim()?j(t,"application/xml")?.doc:null,n=new Map,o=new Map;if(!r)return{nums:n,abstracts:o};for(let a of Array.from(r.getElementsByTagNameNS("*","abstractNum"))){let i=En(a,"abstractNumId");i!=null&&!o.has(String(i))&&o.set(String(i),a)}for(let a of Array.from(r.getElementsByTagNameNS("*","num"))){let i=En(a,"numId");if(i==null||n.has(String(i)))continue;let l=new Map,s=new Set;for(let c of Ki(a,"lvlOverride")){let f=En(c,"ilvl")??0,u=En(de(c,"startOverride"));u!=null&&l.set(f,u),de(c,"lvl")&&s.add(f)}n.set(String(i),{element:a,abstractId:String(En(de(a,"abstractNumId"))??""),startOverrides:l,levelOverrides:s})}return{nums:n,abstracts:o}}function Iy(e,t){let r=e.nums.get(String(t));if(!r)return{reason:"missing"};let n=e.abstracts.get(r.abstractId);if(!n)return{reason:"missing"};let o=new Map;for(let l of Ki(n,"lvl")){let s=En(l,"ilvl")??0;o.set(s,{numFmt:fo(de(l,"numFmt"))||"decimal",lvlText:fo(de(l,"lvlText"))??"",start:En(de(l,"start"))??0,restart:!!de(l,"lvlRestart"),pStyle:fo(de(l,"pStyle"))})}let a=fo(de(n,"numStyleLink"))||fo(de(n,"styleLink")),i=[...o.values()].map(l=>l.pStyle).filter(Boolean);return{numId:String(t),num:r,abstract:n,abstractId:r.abstractId,levels:o,styleLink:a||null,levelStyles:i,startOf:l=>r.startOverrides.has(l)?r.startOverrides.get(l):o.get(l)?.start??0}}function xy(e,t){if(!e)return[];let r=[];for(let n of Array.from(e.getElementsByTagNameNS("*","style"))){let o=fo(Je(Je(de(n,"pPr"),"numPr"),"numId"));o!=null&&t.has(String(o))&&r.push(n.getAttribute("w:styleId")??n.getAttribute("styleId"))}return r}function Bl(e,t){let r=[];for(let n of Array.from(e.getElementsByTagNameNS(Gd,"p"))){let o=_e(n);!o||o.numId!==String(t)||r.push({paragraph:n,ilvl:o.ilvl,deleted:Ot(n),inTextbox:Ny(n,"txbxContent")})}return r}function Ny(e,t){for(let r=e?.parentNode;r&&r.nodeType===1;r=r.parentNode)if(r.localName===t)return!0;return!1}function Ty(e,t,r){return[...t.nums.entries()].filter(([o,a])=>o!==r.numId&&a.abstractId===r.abstractId).map(([o])=>o).filter(o=>Bl(e,o).some(a=>!a.deleted))}function _l(e,t,r=[]){let n=Array.from({length:Ol+1},(a,i)=>r[i]??null),o=[];for(let a of e){for(let i=0;i<a;i+=1)n[i]==null&&(n[i]=t(i));n[a]=n[a]==null?t(a):n[a]+1;for(let i=a+1;i<=Ol;i+=1)n[i]=null;o.push(n.slice(0,a+1))}return{values:o,counters:n}}function qd(e,{stylesDoc:t,indexOf:r,mode:n}){let o=[],a=[],i=[];for(let s of e){let c=r(s);if(Ot(s)){a.push({paragraph:s,paragraphIndex:c,reason:"tracked-deleted"});continue}let f=_e(s);if(f){o.push({paragraph:s,paragraphIndex:c,ilvl:f.ilvl,numId:f.numId});continue}let u=nt(s),d=u.numPr?.numId==="0"?null:Sl(t,u.pStyle);if(d)return fe(Ii,`Paragraph ${c??""} is numbered by its style "${d.styleId}" (numId ${d.numId}), not by a direct list binding; ${n} rebinds direct list items only.`.replace(" "," "),{paragraphIndex:c,styleId:d.styleId,numId:d.numId,targetExcerpt:kl(Q(s))},{action:"convert_in_host",hint:"Style-linked numbering is not rebound by list-format. Change the style's numbering in the host."});i.push({paragraph:s,paragraphIndex:c})}if(o.length===0)return fe(yd,`The target range has no list item; ${n} changes existing lists.`,{paragraphIndexes:i.map(s=>s.paragraphIndex),targetExcerpt:kl(i[0]?Q(i[0].paragraph):"")},{action:"use_list_format_convert_plain",hint:"To turn plain paragraphs into a list use list-format convert-plain (typed markers) or paragraph-format numbering (an existing list)."});if(i.length>0)return fe(xi,`The target range mixes list items and paragraphs that are not list items (paragraphs ${i.map(s=>s.paragraphIndex).join(", ")}).`,{reason:"non-list",paragraphIndexes:i.map(s=>s.paragraphIndex)},{action:"narrow_range",hint:'Target only list items: one paragraph of the list is enough with scope "list".'});let l=[...new Set(o.map(s=>s.numId))];return l.length>1?fe(xi,`The target range spans ${l.length} lists (numIds ${l.join(", ")}); one ${n} operation changes one list.`,{reason:"several-lists",numIds:l,paragraphIndexes:o.filter(s=>s.numId!==o[0].numId).map(s=>s.paragraphIndex)},{action:"narrow_range",hint:"Send one operation per list."}):{ok:!0,numId:l[0],items:o,skipped:a}}function Ml(e,t,r,{stylesDoc:n,role:o}){let a=Iy(t,r);if(a.reason==="missing")return fe(In,`numId ${r} (${o}) has no numbering definition in the numbering part, so its levels cannot be read.`,{reason:"missing",numId:String(r)},{action:"inspect_numbering",hint:"Bare document.xml callers must pass the package's word/numbering.xml as numberingXml."});if(a.num.levelOverrides.size>0)return fe(In,`numId ${r} (${o}) redefines level ${[...a.num.levelOverrides].join(", ")} inside its w:num (w:lvlOverride/w:lvl); list-format does not rebind such instance-level definitions.`,{reason:"level-override",numId:String(r),levels:[...a.num.levelOverrides]},{action:"convert_in_host",hint:"Change this list in the host."});let i=xy(n,new Set([String(r),...[...t.nums.entries()].filter(([,s])=>s.abstractId===a.abstractId).map(([s])=>s)]));if(a.styleLink||a.levelStyles.length>0||i.length>0){let s=[...new Set([a.styleLink,...a.levelStyles,...i].filter(Boolean))];return fe(bd,`numId ${r} (${o}) is style-linked (${s.map(c=>`"${c}"`).join(", ")}): paragraphs can join it through a style without a direct binding, so rebinding the direct items would split the list unpredictably.`,{numId:String(r),styleIds:s},{action:"convert_in_host",hint:"Style-linked lists (heading numbering, list styles) are not changed by list-format. Change the numbering of the style in the host."})}let l=Ty(e,t,a);return l.length>0?fe(so,`numId ${r} (${o}) shares its abstract definition ${a.abstractId} with numIds ${l.join(", ")}, which Word numbers as one continuous list; rebinding one of them would renumber the others.`,{reason:"shared-definition",numId:String(r),sharedNumIds:l},{action:"convert_in_host",hint:"Change these lists together in the host, or restart the other list first."}):a.num.element&&[...a.levels.keys()].length===0?fe(In,`numId ${r} (${o}) has no levels.`,{reason:"undefined-level",numId:String(r)},{action:"convert_in_host"}):{ok:!0,definition:a}}function Yd(e,t,r,n,o,a){let l=Bl(e,t).filter(d=>!d.deleted),s=l.find(d=>d.inTextbox);if(s)return fe(so,`numId ${t} has a list item inside a text box (paragraph ${o(s.paragraph)??"?"}); list-format changes body lists only.`,{reason:"textbox-member",numId:String(t)},{action:"convert_in_host",hint:"Change this list in the host."});let c=new Set(r.map(d=>d.paragraph));if(n==="list")return{ok:!0,rebind:l.map(d=>({...d,paragraphIndex:o(d.paragraph),inTarget:c.has(d.paragraph)})),preceding:[]};let f=l.findIndex(d=>c.has(d.paragraph)),u=l.slice(f).filter(d=>!c.has(d.paragraph));if(u.length>0){let d=o(l[l.length-1].paragraph);return fe(so,`scope "range" would split numId ${t} mid-sequence: ${u.length} later item(s) of the list (paragraphs ${u.map(m=>o(m.paragraph)).join(", ")}) would stay on the source list and renumber.`,{reason:"mid-sequence",numId:String(t),followingParagraphIndexes:u.map(m=>o(m.paragraph)),lastListParagraphIndex:d},{action:"extend_range_or_use_list_scope",hint:`Extend targetEnd to the last item of the list (paragraph ${d}), or use scope "list" to ${a==="join"?"join":"change"} the whole list.`})}return{ok:!0,rebind:l.slice(f).map(d=>({...d,paragraphIndex:o(d.paragraph),inTarget:!0})),preceding:l.slice(0,f)}}function Jd(e,{author:t,generateRedlines:r}){let n=e.filter(o=>!o.inTarget);if(!r&&n.length>0)return fe("INVALID_OPERATION",`An untracked (generateRedlines: false) list-format would rebind ${n.length} paragraph(s) outside the target (paragraphs ${n.map(o=>o.paragraphIndex).join(", ")}); untracked edits stay inside their target.`,{field:"generateRedlines",paragraphIndexes:n.map(o=>o.paragraphIndex)},{action:"change_request",hint:"Keep tracking on, or target the whole list with target..targetEnd."});for(let o of e){let a=Je(de(o.paragraph,"pPr"),"pPrChange"),i=a?.getAttribute("w:author")??a?.getAttribute("author")??"";if(r&&a&&i!==t)return fe(by,`Paragraph ${o.paragraphIndex??""} of the list already has a pending paragraph-property change by "${i||"unattributed"}". Overwriting its snapshot would change what Reject All restores.`.replace(" "," "),{pendingAuthor:i,paragraphIndex:o.paragraphIndex},{action:"resolve_pending_revision",hint:"Ask the user to accept or reject the existing paragraph formatting change first; this tool does not resolve revisions by other reviewers."});o.keepSnapshot=!!a}return{ok:!0}}function Zd(e,t,r,{author:n,generateRedlines:o}){for(let a of t){let i=de(a.paragraph,"pPr");i||(i=F(e,"w:pPr"),a.paragraph.insertBefore(i,a.paragraph.firstChild)),o&&!a.keepSnapshot&&Wn(e,i,n),Vn(e,i,{numbering:{numId:r,level:a.ilvl}}),a.numId=String(r)}}var Ll=(e,t={})=>({ok:!0,unchanged:!0,message:e,...t});function Qd(e,t,r,n={}){let o=n.generateRedlines!==!1,a=n.author,i=typeof n.paragraphIndexOf=="function"?n.paragraphIndexOf:()=>null,l=Ei(n.stylesXml),s=Hd(n.numberingXml),c=r.scope==="range"?"range":"list",f=qd(t,{stylesDoc:l,indexOf:i,mode:"change-format"});if(!f.ok)return f;let u=Ml(e,s,f.numId,{stylesDoc:l,role:"the target list"});if(!u.ok)return u;let{definition:d}=u,m=[...new Set(f.items.map(O=>O.ilvl))].sort((O,C)=>O-C);if(r.explicitLevel==null&&m.length>1)return fe(xi,`The target paragraphs use list levels ${m.join(", ")}; change-format redefines one level per operation.`,{reason:"levels",levels:m},{action:"set_list_level",hint:"Pass list.level, or target paragraphs of one level.",field:"list.level",allowedValues:m});let p=r.explicitLevel??m[0],g=d.levels.get(p);if(!g)return fe(In,`numId ${f.numId} does not define list level ${p}.`,{reason:"undefined-level",numId:f.numId,level:p},{action:"set_list_level",field:"list.level",allowedValues:[...d.levels.keys()]});let h=r.format??(r.kind==="bullet"?"bullet":g.numFmt),v=Sn(g.numFmt)!==Sn(h),w=r.lvlText??(v?Sn(h)?"\u2022":`%${p+1}.`:g.lvlText),y=wl(w,{bullet:Sn(h),level:p});if(y)return fe("INVALID_OPERATION",`${y} (level ${p}, format ${h})`,{field:"list.lvlText"},{action:"change_request",hint:Sn(h)?"Pass the bullet character as list.lvlText.":`Pass list.lvlText with %${p+1}, for example "%${p+1}."`});let b=Yd(e,f.numId,f.items,c,i,"change-format");if(!b.ok)return b;let I=O=>d.levels.get(O)?.start??0,E=new Map;for(let O=0;O<=Ol;O+=1)E.set(O,d.startOf(O));if(c==="range"&&b.preceding.length>0){if([...b.preceding,...b.rebind].some(L=>d.levels.get(L.ilvl)?.restart))return fe(In,`numId ${f.numId} uses w:lvlRestart, so the count a split would continue cannot be computed exactly.`,{reason:"level-restart",numId:f.numId},{action:"extend_range_or_use_list_scope",hint:'Use scope "list".'});let C=_l(b.preceding.map(L=>L.ilvl),d.startOf),P=b.rebind[0].ilvl;for(let L=0;L<P;L+=1)E.set(L,C.counters[L]??d.startOf(L));E.set(P,C.counters[P]==null?d.startOf(P):C.counters[P]+1);let M=_l(b.rebind.map(L=>L.ilvl),d.startOf,C.counters).values,k=_l(b.rebind.map(L=>L.ilvl),L=>E.get(L)).values.findIndex((L,D)=>JSON.stringify(L)!==JSON.stringify(M[D]));if(k>=0)return fe(so,`scope "range" cannot continue the count of numId ${f.numId} exactly: a level whose start must change restarts inside the range (paragraph ${b.rebind[k].paragraphIndex??"?"}), and Word applies a level start again on every restart.`,{reason:"nested-restart",numId:f.numId,paragraphIndex:b.rebind[k].paragraphIndex},{action:"extend_range_or_use_list_scope",hint:'Start the range at a top-level item of the list, or use scope "list".'})}if(r.start!=null&&E.set(p,r.start),!b.rebind.some(O=>O.ilvl===p))return Ll(`No paragraph of the ${c==="list"?"list":"range"} uses level ${p}; nothing would change.`,{level:p,sourceNumId:f.numId});let N=r.start!=null&&r.start!==d.startOf(p);if(h===g.numFmt&&w===g.lvlText&&!N)return Ll(`numId ${f.numId} level ${p} already has format ${h} with level text "${w}".`,{level:p,sourceNumId:f.numId});let R=Jd(b.rebind,{author:a,generateRedlines:o});if(!R.ok)return R;let x={};for(let[O,C]of E)C!==I(O)&&(x[O]=C);let T=new Map(Object.entries(x).map(([O,C])=>[Number(O),{ilvl:Number(O),start:C}]));T.set(p,{...T.get(p)||{},ilvl:p,numFmt:h,lvlText:w,...h!==g.numFmt?{dropChildren:v&&!Sn(h)?["isLgl","lvlPicBulletId","legacy"]:["isLgl"]}:{},...v&&!Sn(h)?{dropRunFonts:!0}:{}});let A=Pl(n.runtimeContext,n),S=Ko({numberingIdState:A,sourceNumberingXml:n.numberingXml,sourceNumId:f.numId,levels:[...T.values()]});return S?(Zd(e,b.rebind,S.numId,{author:a,generateRedlines:o}),{ok:!0,mode:"change-format",scope:c,format:h,level:p,lvlText:w,sourceNumId:f.numId,numId:String(S.numId),levelStarts:x,items:b.rebind.map(O=>({paragraph:O.paragraph,paragraphIndex:O.paragraphIndex,level:O.ilvl,numId:O.numId,sourceNumId:f.numId,inTarget:O.inTarget})),skipped:f.skipped,numberingXml:hr("",[S.numberingXml]),allocatedNumIds:[S.numId]}):fe("NUMBERING_ID_EXHAUSTED","No numbering ids are available for a new list definition.",{},{action:"report_library_failure"})}function em(e,t,r,n,o={}){let a=o.generateRedlines!==!1,i=o.author,l=typeof o.paragraphIndexOf=="function"?o.paragraphIndexOf:()=>null,s=Ei(o.stylesXml),c=Hd(o.numberingXml),f=n.scope==="range"?"range":"list",u=l(r),d=_e(r);if(!d||Ot(r))return fe(Ni,`list.continueFrom (paragraph ${u??"?"}) is ${d?"a tracked-deleted paragraph":"not a list item"}; join continues an existing list.`,{reason:d?"deleted":"not-a-list",paragraphIndex:u,targetExcerpt:kl(Q(r))},{action:"change_request",hint:"Point list.continueFrom at a live item of the list the target should continue.",field:"list.continueFrom"});if(t.includes(r))return fe(Ni,"list.continueFrom is inside the target range; it must be an item of an earlier list.",{reason:"inside-target",paragraphIndex:u},{action:"change_request",field:"list.continueFrom"});let m=qd(t,{stylesDoc:s,indexOf:l,mode:"join"});if(!m.ok)return m;if(m.numId===d.numId)return Ll(`The target already belongs to the list of list.continueFrom (numId ${m.numId}).`,{sourceNumId:m.numId});let p=Ml(e,c,m.numId,{stylesDoc:s,role:"the target list"});if(!p.ok)return p;let g=Ml(e,c,d.numId,{stylesDoc:s,role:"the list.continueFrom list"});if(!g.ok)return g;let h=Yd(e,m.numId,m.items,f,l,"join");if(!h.ok)return h;let v=Array.from(e.getElementsByTagNameNS(Gd,"p")),w=v.indexOf(h.rebind[0].paragraph),b=Bl(e,d.numId).filter(N=>!N.deleted).filter(N=>v.indexOf(N.paragraph)>w);if(b.length>0){let N=v.indexOf(r)>w?"after-target":"interleaved";return fe(N==="after-target"?Ni:so,N==="after-target"?"list.continueFrom comes after the target; join continues an earlier list.":`The list of list.continueFrom (numId ${d.numId}) has items after the joined paragraphs (paragraphs ${b.map(R=>l(R.paragraph)).join(", ")}); they would renumber.`,{reason:N,numId:d.numId,paragraphIndexes:b.map(R=>l(R.paragraph))},{action:"change_request",hint:"Join a list to the list that immediately precedes it.",field:"list.continueFrom"})}let I=h.rebind.find(N=>!g.definition.levels.has(N.ilvl));if(I)return fe(In,`numId ${d.numId} (the list.continueFrom list) does not define level ${I.ilvl}, which paragraph ${I.paragraphIndex??"?"} uses.`,{reason:"undefined-level",numId:d.numId,level:I.ilvl},{action:"convert_in_host"});let E=Jd(h.rebind,{author:i,generateRedlines:a});return E.ok?(Zd(e,h.rebind,d.numId,{author:i,generateRedlines:a}),{ok:!0,mode:"join",scope:f,sourceNumId:m.numId,numId:d.numId,continueFrom:{paragraphIndex:u,numId:d.numId},items:h.rebind.map(N=>({paragraph:N.paragraph,paragraphIndex:N.paragraphIndex,level:N.ilvl,numId:N.numId,sourceNumId:m.numId,inTarget:N.inTarget})),skipped:m.skipped,numberingXml:null,allocatedNumIds:[]}):E}var Ay=/^(\s*)((?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|[ivxlcIVXLC]+\.|[-*+\u2022]))\s+(.*)$/,tm=/(?:^|\s)(?:\d+(?:\.\d+)*\.?|[A-Za-z]\.|[ivxlcIVXLC]+\.)\s+/g;function Sy(e){let t=String(e||"").trim();if(!/^\d+(?:\.\d+)+\.?$/.test(t))return null;let r=t.replace(/\.$/,"").split(".");return Math.max(0,r.length-1)}function Ey(e){let t=String(e||"").split(/\r?\n/g).map(n=>n.trimEnd()).filter(n=>n.trim().length>0);if(t.length<2)return null;let r=[];for(let n of t){let o=n.match(Ay);if(!o)return null;let a=o[2],i=/^[-*+\u2022]$/.test(a)?"bullet":"numbered";r.push({marker:a,markerType:i,level:Math.floor((o[1]||"").length/2),outlineLevel:i==="numbered"?Sy(a):null,text:ln(o[3])})}return r.length>=2?r:null}function rm(e,t){if(!Array.isArray(e)||e.length===0)return null;let r=Ey(t);if(!r)return null;let n=e.map(d=>Z(Ce(d))),o=r.map(d=>Z(d.text));if(n.some(d=>!d)||o.some(d=>!d))return null;let a=e.map(d=>_e(d));if(a.some(d=>!d||!d.numId))return null;let i=String(a[0].numId);if(a.some(d=>String(d.numId)!==i))return null;let l=[],s=0;for(let d=0;d<o.length&&s<n.length;d+=1)o[d]===n[s]&&(l.push({originalIndex:s,modifiedIndex:d}),s+=1);if(s!==n.length)return null;let c=new Set(l.map(d=>d.modifiedIndex)),f=[];for(let d=0;d<r.length;d+=1)c.has(d)||f.push(d);if(f.length===0)return null;let u=r[0]?.level||0;return f.map(d=>{let m=l.find(b=>b.modifiedIndex>d)||null,p=[...l].reverse().find(b=>b.modifiedIndex<d)||null,g=m||p;if(!g)return null;let h=a[g.originalIndex]||a[0];if(!h)return null;let v=r[d],w=Math.max(0,v.level-u),y=Number.isInteger(v.outlineLevel)?v.outlineLevel:null;return{text:v.text,markerType:v.markerType,ilvl:y??Math.max(0,(h.ilvl||0)+w),numId:String(h.numId),insertBeforeOriginalIndex:m?m.originalIndex:null}}).filter(Boolean)}function Ry(e){return String(e||"").trim().split(/\s+/).filter(Boolean).length}function Py(e){let t=String(e||"");if(!t)return!1;let r=0,n=new RegExp(tm.source,tm.flags);for(;n.exec(t);)if(r+=1,r>=2)return!0;return!1}function nm(e,t){let r=String(e||"").trim(),n=String(t||"").trim();if(!r||!n||n===r||n.includes(`
|
|
218
|
-
`))return null;let o=
|
|
219
|
-
`))return null;let o=n.split(/\r?\n/g).map(l=>String(l||"").trim()).filter(Boolean);if(o.length<2)return null;let a=l=>
|
|
220
|
-
`)}:null}function
|
|
216
|
+
`);return t||r||n||o||a||i||l||s||c}function Mv(e){if(!e||typeof e!="string")return null;let t=e.match(/\b(?:w14:paraId|w:paraId|paraId)="([^"]+)"/i);return t?t[1]:null}var sa=class{constructor(){this.receipts=[],this.activeReceipt=null}beginOperation(t,r=null,n=null){this.activeReceipt={operationIndex:typeof t=="number"?t:1,...r?{operationId:String(r)}:{},attemptedDisposition:"applied",finalDisposition:"applied",committed:!0,...n?{authorUsed:String(n)}:{},revisionItems:[],commentIds:[],numberingIds:[],relationshipIds:[],affectedTargets:[],warnings:[]}}recordRevision(t,r="structural",n="word/document.xml"){if(!this.activeReceipt||t==null)return;let o=String(t);this.activeReceipt.revisionItems.some(a=>a.id===o&&a.kind===r&&a.partName===n)||this.activeReceipt.revisionItems.push({id:o,kind:r,partName:n})}recordComment(t,r="word/comments.xml"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.commentIds.includes(n)||this.activeReceipt.commentIds.push(n)}recordNumbering(t,r="word/numbering.xml"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.numberingIds.includes(n)||this.activeReceipt.numberingIds.push(n)}recordRelationship(t,r="word/_rels/document.xml.rels"){if(!this.activeReceipt||t==null)return;let n=String(t);this.activeReceipt.relationshipIds.includes(n)||this.activeReceipt.relationshipIds.push(n)}recordAffectedTarget(t){!this.activeReceipt||!t||this.activeReceipt.affectedTargets.push(JSON.parse(JSON.stringify(t)))}recordWarning(t){!this.activeReceipt||!t||this.activeReceipt.warnings.push(String(t))}commitOperation(t="applied"){if(!this.activeReceipt)return null;this.activeReceipt.attemptedDisposition=t,this.activeReceipt.finalDisposition=t,this.activeReceipt.committed=t==="applied";let r=JSON.parse(JSON.stringify(this.activeReceipt));return this.receipts.push(r),this.activeReceipt=null,r}abortOperation(t="refused"){if(!this.activeReceipt)return null;this.activeReceipt.attemptedDisposition=t,this.activeReceipt.finalDisposition=t,this.activeReceipt.committed=!1;let r=JSON.parse(JSON.stringify(this.activeReceipt));return this.activeReceipt=null,r}createSavepoint(){return{receipts:JSON.parse(JSON.stringify(this.receipts)),activeReceipt:this.activeReceipt?JSON.parse(JSON.stringify(this.activeReceipt)):null}}restoreSavepoint(t){t&&(this.receipts=Array.isArray(t.receipts)?JSON.parse(JSON.stringify(t.receipts)):[],this.activeReceipt=t.activeReceipt?JSON.parse(JSON.stringify(t.activeReceipt)):null)}clear(){this.receipts=[],this.activeReceipt=null}markRolledBack(){for(let t of this.receipts)t.attemptedDisposition==="applied"&&(t.finalDisposition="rolled_back",t.committed=!1);this.activeReceipt=null}getReceipts(){return JSON.parse(JSON.stringify(this.receipts))}getCurrentReceipt(){return this.activeReceipt?JSON.parse(JSON.stringify(this.activeReceipt)):null}};function ke(e,t=null,r=null,n="not_attempted"){return{operationIndex:typeof e=="number"?e:1,...t?{operationId:String(t)}:{},attemptedDisposition:n,finalDisposition:n,committed:!1,...r?{authorUsed:String(r)}:{},revisionItems:[],commentIds:[],numberingIds:[],relationshipIds:[],affectedTargets:[],warnings:[]}}function la(e,t){if(!Array.isArray(t)||t.length===0)return{valid:!0};let r=t.filter(s=>s&&s.committed===!0&&s.finalDisposition==="applied");if(r.length===0)return{valid:!0};let n=new Set;if(e?.documentXml&&typeof e.documentXml=="string"){let s=/<(?:w:)?(?:ins|del|rPrChange|pPrChange|moveFrom|moveTo)\b[^>]*?\b(?:w:)?id="([^"]+)"/g,c;for(;(c=s.exec(e.documentXml))!==null;)n.add(c[1])}let o=new Set;if(e?.commentsXml&&typeof e.commentsXml=="string"){let s=/<(?:w:)?comment\b[^>]*?\b(?:w:)?id="([^"]+)"/g,c;for(;(c=s.exec(e.commentsXml))!==null;)o.add(c[1])}let a=new Set,i=[e?.numberingXml,...e?.numberingXmlParts||[]].filter(Boolean).join(`
|
|
217
|
+
`);if(i){let s=/<(?:w:)?num\b[^>]*?\b(?:w:)?numId="([^"]+)"/g,c;for(;(c=s.exec(i))!==null;)a.add(c[1])}if(e?.documentXml&&typeof e.documentXml=="string"){let s=/<(?:w:)?numId\b[^>]*?\b(?:w:)?val="([^"]+)"/g,c;for(;(c=s.exec(e.documentXml))!==null;)a.add(c[1])}let l=new Set;if(e?.relationshipsXml&&typeof e.relationshipsXml=="string"){let s=/<Relationship\b[^>]*?\bId="([^"]+)"/g,c;for(;(c=s.exec(e.relationshipsXml))!==null;)l.add(c[1])}for(let s of r){if(Array.isArray(s.revisionItems)){for(let c of s.revisionItems)if(c.partName==="word/document.xml"&&!n.has(String(c.id)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed revision id '${c.id}' (kind: ${c.kind}) was not found in word/document.xml.`}}}if(Array.isArray(s.commentIds)){for(let c of s.commentIds)if(!o.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed comment id '${c}' was not found in word/comments.xml.`}}}if(Array.isArray(s.numberingIds)){for(let c of s.numberingIds)if(!a.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed numbering id '${c}' was not found in numbering parts or document.`}}}if(e?.relationshipsXml&&Array.isArray(s.relationshipIds)){for(let c of s.relationshipIds)if(!l.has(String(c)))return{valid:!1,error:{code:"RECEIPT_RECONCILIATION_FAILED",message:`Committed relationship id '${c}' was not found in document.xml.rels.`}}}}return{valid:!0}}var pd="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Lv="http://schemas.openxmlformats.org/officeDocument/2006/relationships",Bv=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","sectPrChange","tblPrChange","tblGridChange","tcPrChange","trPrChange","numberingChange"]),$v=new Set(["ins","del","moveFrom","moveTo"]),Ni=(e,t,r)=>e?.getAttribute?.(t)||e?.getAttribute?.(r)||"";function Fv(e){let t=String(e||"");if(t.startsWith("/"))return t.replace(/^\/+/,"");let r=["word"];for(let n of t.split("/"))n===".."?r.pop():n&&n!=="."&&r.push(n);return r.join("/")}function Tl({documentXml:e,relsXml:t=null,settingsXml:r=null}){if(!e||!t)return[];let n=V(e,"application/xml"),o=V(t,"application/xml");if(!n.doc||n.error||!o.doc||o.error)return[];let a=new Map;for(let f of Array.from(o.doc.getElementsByTagNameNS("*","Relationship")))a.set(f.getAttribute("Id")||"",f.getAttribute("Target")||"");let i=!!r&&/<w:evenAndOddHeaders\b(?![^>]*w:val="(?:0|false|off)")/.test(r),l=new Map,s=new Map;return Array.from(n.doc.getElementsByTagNameNS(pd,"sectPr")).forEach((f,u)=>{let d=Array.from(f.childNodes||[]).some(m=>m.localName==="titlePg"&&!/^(0|false|off)$/i.test(Ni(m,"w:val","val")));for(let m of Array.from(f.childNodes||[])){if(m.nodeType!==1||m.localName!=="headerReference"&&m.localName!=="footerReference")continue;let p=m.getAttributeNS?.(Lv,"id")||m.getAttribute("r:id")||"",g=a.get(p);if(!g)continue;let h=Fv(g),v=m.localName==="headerReference"?"header":"footer",w=Ni(m,"w:type","type")||"default",y=l.get(h)||{path:h,kind:v,type:w,sections:[],applies:[],titlePgSections:0};y.sections.includes(u)||y.sections.push(u),d&&(y.titlePgSections+=1),l.set(h,y),s.set(`${v}:${w}`,h)}for(let m of s.values()){let p=l.get(m);p&&!p.applies.includes(u)&&p.applies.push(u)}}),Array.from(l.values()).map(f=>({path:f.path,kind:f.kind,type:f.type,sections:f.sections,appliesToSections:f.applies,sharedBySections:f.applies.length>1,active:f.type==="first"?f.titlePgSections>0:f.type==="even"?i:!0}))}function Sl(e,t){let r=a=>({path:a.path,kind:a.kind,type:a.type,sections:a.sections,appliesToSections:a.appliesToSections});if(typeof t=="string"){let a=t.replace(/^\/+/,"").toLowerCase(),i=e.find(l=>l.path.toLowerCase()===a||l.path.toLowerCase()===`word/${a}`);return i?{part:i}:{error:{code:"PART_NOT_FOUND",message:`No header/footer part '${t}' is referenced by the document.`,candidates:e.map(r)}}}if(!t||typeof t!="object"||t.kind!=="header"&&t.kind!=="footer")return{error:{code:"INVALID_OPERATION",message:'part must be a part path or { kind: "header"|"footer", type?: "default"|"first"|"even", section?: number }.'}};let n=t.type||"default";if(!["default","first","even"].includes(n))return{error:{code:"INVALID_OPERATION",message:`part.type must be default, first or even (got '${n}').`}};let o=e.filter(a=>a.kind===t.kind&&a.type===n);return Number.isInteger(t.section)&&(o=o.filter(a=>a.appliesToSections.includes(t.section))),o.length===1?{part:o[0]}:o.length===0?{error:{code:"PART_NOT_FOUND",message:`The document has no ${n} ${t.kind}${Number.isInteger(t.section)?` for section ${t.section}`:""}.`,candidates:e.map(r)}}:{error:{code:"PART_AMBIGUOUS",message:`Several ${n} ${t.kind} parts exist; add "section" or use the part path.`,candidates:o.map(r)}}}function gd(e){let t=cl(e);return t?.id==="header"||t?.id==="footer"}function Al(e){let t=V(e,"application/xml");if(!t.doc||t.error)return 0;let r=0,n=0,o=a=>{for(let i of Array.from(a.childNodes||[])){if(i.nodeType!==1)continue;let l=i.localName;if(l==="fldChar"){let s=Ni(i,"w:fldCharType","fldCharType");s==="begin"?r+=1:s==="end"&&(r=Math.max(0,r-1));continue}if($v.has(l)&&r>0&&(n+=1),l==="fldSimple"){r+=1,o(i),r-=1;continue}o(i)}};return o(t.doc.documentElement),n}function hd(e){let t=new Set;for(let r of String(e||"").matchAll(/<w:(?:ins|del|moveFrom|moveTo|rPrChange|pPrChange|sectPrChange|tblPrChange|tblGridChange|tcPrChange|trPrChange|numberingChange)\b[^>]*?\bw:id="(\d+)"/g))t.add(r[1]);return t}function wd(e,t){let r=V(e,"application/xml");if(!r.doc||r.error)return{xml:e,renumbered:0,idMap:new Map};let n=new Map,o=1+Math.max(0,...Array.from(t,s=>Number(s)).filter(Number.isFinite)),a=new Set(t),i=0,l=s=>{for(let c of Array.from(s.childNodes||[]))if(c.nodeType===1){if(Bv.has(c.localName)){let f=Ni(c,"w:id","id");if(f&&a.has(f)){for(;a.has(String(o));)o+=1;c.setAttributeNS(pd,"w:id",String(o)),n.set(f,String(o)),a.add(String(o)),i+=1}else f&&a.add(f)}l(c)}};return l(r.doc.documentElement),i>0?{xml:le().serializeToString(r.doc),renumbered:i,idMap:n}:{xml:e,renumbered:0,idMap:n}}var Dv=Object.freeze({INVALID_OPERATION:["request","request_fixable","change_request"],INVALID_AGENT_REQUEST:["request","request_fixable","change_request"],INVALID_FILTER:["request","request_fixable","change_request"],INVALID_OPERATIONS_FILE:["request","request_fixable","change_request"],OPERATIONS_REQUIRED:["request","request_fixable","change_request"],UNKNOWN_OPTION:["request","request_fixable","change_request"],UNEXPECTED_ARGUMENT:["request","request_fixable","change_request"],INVALID_ACTION:["request","request_fixable","change_request"],INVALID_PROFILE:["request","request_fixable","change_request"],INVALID_REVISION_TOKEN:["revision-check","request_fixable","change_request"],BATCH_OPERATION_FAILED:["batch-execution","request_fixable","inspect_failed_operations"],REVISION_TOKEN_SCOPE_MISMATCH:["revision-check","request_fixable","change_request"],REVISION_MISMATCH:["revision-check","target_refresh_required","reinspect"],TARGET_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],SOURCE_TARGET_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],TARGET_TEXT_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_FINGERPRINT_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_INDEX_MISMATCH:["target-resolution","target_refresh_required","reinspect"],TARGET_OCCURRENCE_MISMATCH:["target-resolution","candidate_selection_required","choose_candidate"],STALE_TARGET_HANDLE:["target-resolution","target_refresh_required","reinspect"],TARGET_HANDLE_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],AMBIGUOUS_TARGET:["target-resolution","candidate_selection_required","choose_candidate"],TARGET_RANGE_INVALID:["target-resolution","request_fixable","change_target_range"],ANCHOR_NOT_FOUND:["anchor-resolution","request_fixable","change_anchor"],AMBIGUOUS_ANCHOR:["anchor-resolution","candidate_selection_required","choose_candidate"],PATCH_SOURCE_NOT_FOUND:["patch-compilation","request_fixable","change_patch"],AMBIGUOUS_PATCH_SOURCE:["patch-compilation","candidate_selection_required","choose_occurrence"],OVERLAPPING_PATCHES:["patch-compilation","source_conflict","combine_patches"],CONFLICTING_PATCHES:["patch-compilation","source_conflict","combine_patches"],PATCH_ROUNDTRIP_MISMATCH:["patch-validation","request_fixable","reinspect_and_narrow"],DIFF_TOKEN_LIMIT:["patch-compilation","request_fixable","narrow_operation"],STRUCTURED_CONTENT_INVALID:["request","request_fixable","change_request"],UNSUPPORTED_LIST_CONVERSION:["list-conversion","request_fixable","use_list_format_convert_plain"],UNSUPPORTED_LIST_FORMAT_CHANGE:["list-conversion","request_fixable","use_list_format_change_format"],LIST_MARKER_NOT_FOUND:["list-conversion","request_fixable","change_request"],LIST_MARKER_AMBIGUOUS:["list-conversion","request_fixable","set_list_format"],LIST_MARKER_UNSUPPORTED:["list-conversion","request_fixable","convert_in_host"],LIST_FORMAT_TARGET_IS_LIST:["list-conversion","request_fixable","use_paragraph_numbering"],LIST_FORMAT_STYLE_NUMBERED:["list-conversion","request_fixable","convert_in_host"],LIST_FORMAT_TARGET_NOT_LIST:["list-conversion","request_fixable","use_list_format_convert_plain"],LIST_FORMAT_MIXED_RANGE:["list-conversion","request_fixable","narrow_range"],LIST_FORMAT_STYLE_LINKED:["list-conversion","request_fixable","convert_in_host"],LIST_FORMAT_SPLIT_UNSUPPORTED:["list-conversion","request_fixable","extend_range_or_use_list_scope"],LIST_FORMAT_DEFINITION_UNSUPPORTED:["list-conversion","request_fixable","convert_in_host"],LIST_FORMAT_JOIN_INVALID:["list-conversion","request_fixable","change_request"],PARAGRAPH_NUMBERING_NOT_FOUND:["target-resolution","target_refresh_required","inspect_numbering"],PARAGRAPH_FORMAT_REVISION_CONFLICT:["target-safety","user_authorization_required","resolve_pending_revision"],UNSUPPORTED_INSERTION_AFFINITY:["request","request_fixable","change_request"],EXISTING_REVISIONS:["target-safety","policy_choice_required","set_option"],PART_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],PART_AMBIGUOUS:["target-resolution","candidate_selection_required","choose_candidate"],COMMENT_IN_HEADER_FOOTER:["request","request_fixable","change_request"],FIELD_EDIT_REFUSED:["target-safety","request_fixable","change_request"],COMMENT_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],PARENT_ANCHOR_NOT_FOUND:["target-resolution","target_refresh_required","reinspect"],COMMENTED_CONTENT_MERGE:["target-safety","user_authorization_required","resolve_comments"],COMMENTED_CONTENT_DELETE:["target-safety","user_authorization_required","resolve_comments"],OVERLAPPING_SOURCE_TARGETS:["batch-compilation","source_conflict","consolidate_operations"],OVERLAPPING_TEXT_EDITS:["batch-compilation","source_conflict","consolidate_operations"],REVISION_ORDER_CONFLICT:["batch-compilation","source_conflict","split_or_consolidate_operations"],LIST_FORMAT_COMPOSITION_CONFLICT:["batch-compilation","source_conflict","split_text_and_list_changes"],TARGET_CONSUMED_BY_OPERATION:["batch-execution","source_conflict","use_created_content_dependency"],CAPTURE_FANOUT_CONFLICT:["batch-compilation","source_conflict","split_or_chain_capture_consumers"],DUPLICATE_CAPTURE_KEY:["batch-compilation","request_fixable","rename_capture"],CAPTURE_NOT_FOUND:["batch-compilation","request_fixable","add_or_correct_capture"],CAPTURE_DEPENDENCY_CYCLE:["batch-compilation","source_conflict","replan_batch"],AMBIGUOUS_CAPTURE_SELECTION:["batch-compilation","candidate_selection_required","choose_candidate"],CAPTURE_STALE:["batch-execution","source_conflict","replan_batch"],GENERATED_OOXML_INVALID:["validation","library_or_builder_failure","report_library_failure"],REVISION_FIDELITY_VIOLATION:["verification","library_or_builder_failure","narrow_or_change_operation"],DOCUMENT_SERIALIZATION_FAILED:["serialization","library_or_builder_failure","report_library_failure"],PACKAGE_OPERATION_FAILED:["package","library_or_builder_failure","report_library_failure"],PACKAGE_VALIDATION:["package-validation","library_or_builder_failure","report_library_failure"],MUTATION_RECEIPT_MISMATCH:["receipt-validation","library_or_builder_failure","report_library_failure"],FOREIGN_PARAGRAPH_MARK_DELETION:["target-safety","policy_choice_required","use_restore_or_leave_deleted"],RESTORATION_STATE_REQUIRED:["target-safety","target_refresh_required","reinspect"],RESTORATION_COUNT_MISMATCH:["request","request_fixable","change_request"],REJECTED_INSERTION_STATE_REQUIRED:["target-safety","target_refresh_required","reinspect"],UNSAFE_REVISION_NESTING:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_REVISION_BOUNDARY:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_PARAGRAPH_BOUNDARY:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_DELETED_TABLE_ROW:["target-safety","manual_document_resolution","manual_resolution"],UNSUPPORTED_MOVE_REVISION:["target-safety","manual_document_resolution","manual_resolution"],SECTION_BREAK_PARAGRAPH:["target-safety","manual_document_resolution","manual_resolution"],UNSAFE_PARAGRAPH_PLACEMENT:["target-safety","manual_document_resolution","manual_resolution"],UNSUPPORTED_REVISION_VIEW_MUTATION:["target-safety","manual_document_resolution","manual_resolution"]});function Uv(e){let t=Array.isArray(e?.generatedIssues)?e.generatedIssues:Array.isArray(e?.issues)?e.issues:null;if(!t)return null;let r=new Map;for(let n of t){let o=n?.code||"UNKNOWN";r.set(o,(r.get(o)||0)+1)}return{total:t.length,byCode:Array.from(r,([n,o])=>({code:n,count:o}))}}function Xv(e){return Dv[e]||["operation","manual_document_resolution","inspect_error"]}function vt(e,t={}){let r=e&&typeof e=="object"?e:{},n=typeof r.code=="string"&&r.code?r.code:"OPERATION_ERROR",[o,a,i]=Xv(n),l={};for(let[m,p]of Object.entries(r))m==="name"||m==="stack"||m==="message"||m==="code"||(l[m]=p);let f={action:i,sameArgumentsSafe:!1,requiresReinspection:a==="target_refresh_required"||n==="PATCH_ROUNDTRIP_MISMATCH",requiresUserAuthorization:a==="user_authorization_required",...n==="EXISTING_REVISIONS"?{field:"existingRevisions",recommendedValue:"slice-cross-author"}:{},...r.recovery&&typeof r.recovery=="object"?r.recovery:{}},u=Uv(r),d={...t,...Array.isArray(r.revisionAuthors)?{revisionAuthors:r.revisionAuthors}:{},...r.currentPolicy?{currentPolicy:r.currentPolicy}:{}};return["TARGET_TEXT_MISMATCH","TARGET_FINGERPRINT_MISMATCH"].includes(n)&&Array.isArray(r.candidates)&&r.candidates.length===1&&(d.currentTarget=r.candidates[0],d.requiresRecomposeModified=!0),{recoveryVersion:1,code:n,message:r.message||String(e),stage:r.stage||o,category:r.category||a,...l,...Object.keys(d).length>0||r.context?{context:{...r.context||{},...d}}:{},...u?{issueSummary:u}:{},recovery:f}}function Ir({atomic:e=!1,rolledBack:t=!1,results:r=[],receipts:n=[],operationCount:o=null}={}){let a=Number.isInteger(o)?o:Math.max(r.length,n.length),i=new Set(r.map(u=>u?.index).filter(Number.isInteger)),l=r.filter(u=>u?.status==="error").map(u=>u.index).filter(Number.isInteger),s=n.filter(u=>u?.committed===!0).map(u=>u.operationIndex).filter(Number.isInteger),c=[];for(let u=1;u<=a;u+=1)i.has(u)||c.push(u);let f=t||e||s.length===0?"original":"output";return{base:f,committedIndexes:s,failedIndexes:l,unattemptedIndexes:c,replayWholeBatch:f==="original",sameArgumentsSafe:!1}}function In(e,t,r){return vt({code:r,message:e,...t?{field:t}:{},recovery:{action:"change_request",sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}})}function Ti(e,t,r,n,o={}){return vt({code:e,message:t,field:r,...o,recovery:{action:n,sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1}})}function zv(e,t){let r=[],n=0;for(;n<=e.length-t.length;){let o=e.indexOf(t,n);if(o<0)break;r.push(o),n=o+1}return r}function ca(e,t){return(e===" "||e==="\xA0")&&(t===" "||t==="\xA0")}function jv(e,t){let r=[];for(let n=0;n<=e.length-t.length;n+=1){let o=!0;for(let a=0;a<t.length;a+=1){let i=e[n+a],l=t[a];if(i!==l&&!ca(i,l)){o=!1;break}}o&&r.push(n)}return r}function Vv(e,t){let r=zv(e,t);return r.length>0?{offsets:r,matchMode:"exact"}:{offsets:jv(e,t),matchMode:"space_equivalent"}}function Wv(e,t,r){let n=r.split(""),o=0;for(;o<t.length&&o<r.length&&(t[o]===r[o]||ca(t[o],r[o]));)ca(e[o],r[o])&&(n[o]=e[o]),o+=1;let a=t.length-1,i=r.length-1;for(;a>=o&&i>=o&&(t[a]===r[i]||ca(t[a],r[i]));)ca(e[a],r[i])&&(n[i]=e[a]),a-=1,i-=1;return n.join("")}function Kv(e,t,r){let n=Math.max(0,t-40),o=Math.min(e.length,t+r+40);return{start:t,end:t+r,excerpt:e.slice(n,o)}}function vd(e,t,r,n=120){let o=String(e??""),a=Math.max(0,Math.min(o.length,t)),i=Math.max(a,Math.min(o.length,r)),l=Math.floor((a+i)/2),s=Math.max(0,l-Math.floor(n/2)),c=Math.min(o.length,s+n);s=Math.max(0,c-n);let f=s>0?"\u2026":"",u=c<o.length?"\u2026":"",d=Math.max(0,n-f.length-u.length);return`${f}${o.slice(s,s+d)}${u}`}function Si(e,t="replacements",{invalidCode:r="INVALID_OPERATION"}={}){if(!Array.isArray(e)||e.length===0)return{ok:!1,error:In("replacements must be a non-empty array.",t,r)};let n=[];for(let o=0;o<e.length;o+=1){let a=e[o],i=`${t}[${o}]`;if(!a||typeof a!="object"||Array.isArray(a))return{ok:!1,error:In(`${i} must be an object.`,i,r)};if(typeof a.find!="string"||a.find.length===0)return{ok:!1,error:In(`${i}.find must be a non-empty string.`,`${i}.find`,r)};if(typeof a.replace!="string")return{ok:!1,error:In(`${i}.replace must be a string.`,`${i}.replace`,r)};if(a.find===a.replace)return{ok:!1,error:In(`${i} must change the matched text.`,i,r)};let l=a.occurrence==null?null:Number(a.occurrence);if(l!=null&&(!Number.isInteger(l)||l<1))return{ok:!1,error:In(`${i}.occurrence must be a positive integer.`,`${i}.occurrence`,r)};n.push({find:a.find,replace:a.replace,...l==null?{}:{occurrence:l}})}return{ok:!0,replacements:n}}function yd(e,t,r="replacements",n={}){let o=n.invalidCode||"INVALID_OPERATION";if(typeof e!="string")return{ok:!1,error:In("Localized replacements require string source text.",r,o)};let a=Si(t,r,{invalidCode:o});if(!a.ok)return a;let i=[];for(let f=0;f<a.replacements.length;f+=1){let u=a.replacements[f],d=`${r}[${f}]`,m=u.occurrence??null,{offsets:p,matchMode:g}=Vv(e,u.find);if(p.length===0||m!=null&&m>p.length)return{ok:!1,error:Ti("PATCH_SOURCE_NOT_FOUND",m==null?`Patch source was not found: "${u.find}".`:`Occurrence ${m} of patch source was not found: "${u.find}".`,d,"change_patch",{matchCount:p.length})};if(m==null&&p.length>1)return{ok:!1,error:Ti("AMBIGUOUS_PATCH_SOURCE",`Patch source matched ${p.length} locations; provide occurrence.`,d,"choose_occurrence",{candidates:p.map(w=>Kv(e,w,u.find.length))})};let h=p[(m||1)-1],v=e.slice(h,h+u.find.length);i.push({requestIndex:f,start:h,end:h+u.find.length,find:u.find,replace:u.replace,effectiveReplace:g==="space_equivalent"?Wv(v,u.find,u.replace):u.replace,matchMode:g,occurrence:m||1})}i.sort((f,u)=>f.start-u.start||f.end-u.end||f.requestIndex-u.requestIndex);let l=[];for(let f of i){let u=l.at(-1);if(u&&f.start===u.start&&f.end===u.end){if(f.effectiveReplace!==u.effectiveReplace)return{ok:!1,error:Ti("CONFLICTING_PATCHES",`Localized replacements ${u.requestIndex+1} and ${f.requestIndex+1} assign different text to the same source range.`,r,"combine_patches",{replacementIndexes:[u.requestIndex+1,f.requestIndex+1]})};continue}if(u&&f.start<u.end)return{ok:!1,error:Ti("OVERLAPPING_PATCHES",`Localized replacements ${u.requestIndex+1} and ${f.requestIndex+1} overlap.`,r,"combine_patches",{replacementIndexes:[u.requestIndex+1,f.requestIndex+1]})};l.push(f)}let s=0,c="";for(let f of l)c+=e.slice(s,f.start),c+=f.effectiveReplace,s=f.end;return c+=e.slice(s),{ok:!0,desiredText:c,replacements:l.map(f=>({requestIndex:f.requestIndex+1,start:f.start,end:f.end,find:f.find,replace:f.replace,matchMode:f.matchMode,occurrence:f.occurrence,removedLength:f.end-f.start,insertedLength:f.effectiveReplace.length}))}}function xd(e,t,r={},n=null){if(!e||typeof e!="object")return null;let o=String(e.sourceText??""),a=String(e.desiredText??""),i=Array.isArray(e.replacements)?e.replacements:[],l=0,s=i.map(c=>{let f=c.start+l,u=f+c.replace.length;return l+=c.replace.length-(c.end-c.start),{find:c.find,replace:c.replace,...c.matchMode==="space_equivalent"?{matchMode:c.matchMode}:{},occurrence:c.occurrence,beforeExcerpt:vd(o,c.start,c.end),afterExcerpt:vd(a,f,u)}});return{kind:"localized_replacement",committed:!0,finalDisposition:"applied",target:{...r.paragraphId?{paragraphId:r.paragraphId}:{},...Number.isInteger(r.index)?{index:r.index}:{},...r.fingerprint?{fingerprint:r.fingerprint}:{},...n?.humanReference?{humanReference:n.humanReference}:{}},...n?{context:{...n}}:{},replacements:s,verification:{acceptedViewMatchesCompiledText:typeof t=="string"&&t===a}}}var bd=Object.freeze(["convert-plain","change-format","join"]),Id=Object.freeze(["decimal","upperLetter","lowerLetter","upperRoman","lowerRoman","bullet"]),Gv=Object.freeze(["marker","none"]),Hv=Object.freeze(["list","range"]),El=Object.freeze({"convert-plain":Object.freeze(["mode","kind","format","start","level","strip"]),"change-format":Object.freeze(["mode","kind","format","lvlText","start","level","scope"]),join:Object.freeze(["mode","continueFrom","scope"])}),Td=Object.freeze(["materializeMarker"]),qv=new Set([...Object.values(El).flat(),...Td]),Sd="LIST_MARKER_NOT_FOUND",Ad="LIST_MARKER_AMBIGUOUS",ua="LIST_MARKER_UNSUPPORTED",Ed="LIST_FORMAT_TARGET_IS_LIST",Ai="LIST_FORMAT_STYLE_NUMBERED",Rd="LIST_FORMAT_TARGET_NOT_LIST",Ei="LIST_FORMAT_MIXED_RANGE",Pd="LIST_FORMAT_STYLE_LINKED",uo="LIST_FORMAT_SPLIT_UNSUPPORTED",Nn="LIST_FORMAT_DEFINITION_UNSUPPORTED",Ri="LIST_FORMAT_JOIN_INVALID",Cd="LIST_FORMAT_UNCHANGED",Yv="\u2022\\-*\u2013\xB7\u25AA\u25E6",Vr="[ \\t\\u00a0]",Jv=new RegExp(`^(${Vr}*)(?:(\\d{1,3})|([A-Za-z]{1,7}))([.)])(${Vr}+)(?=\\S)`),Zv=new RegExp(`^(${Vr}*)([${Yv}])(${Vr}+)(?=\\S)`),Qv=new RegExp(`^${Vr}*\\d+(?:\\.\\d+)+\\.?${Vr}+\\S`),ey=new RegExp(`^${Vr}*\\((?:\\d{1,3}|[A-Za-z]{1,7})\\)${Vr}+\\S`),ty=/^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,Nd={I:1,V:5,X:10,L:50,C:100,D:500,M:1e3};function _d(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}var qe=(e,t)=>({message:e,field:t});function ry(e){return e.format!=null&&!Id.includes(e.format)?qe(`list.format must be one of: ${Id.join(", ")}.`,"list.format"):e.kind!=null&&e.kind!=="bullet"&&e.kind!=="numbered"?qe('list.kind must be "bullet" or "numbered".',"list.kind"):e.kind!=null&&e.format!=null&&e.kind==="bullet"!=(e.format==="bullet")?qe(`list.kind "${e.kind}" contradicts list.format "${e.format}".`,"list.kind"):e.level!=null&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=8)?qe("list.level must be an integer from 0 to 8.","list.level"):null}function Rl(e,{bullet:t=!1,level:r=null}={}){if(typeof e!="string"||e.length<1||e.length>32)return"list.lvlText must be a string of 1 to 32 characters.";let n=e.match(/%./g)||[];if(t)return e.includes("%")||e.length>4?"A bullet list.lvlText is the bullet itself: 1 to 4 characters without % placeholders.":null;if(n.length===0)return'A numbered list.lvlText needs a %1..%9 placeholder (for example "%1." or "(%1)").';if(n.some(o=>!/^%[1-9]$/.test(o)))return"list.lvlText placeholders must be %1 to %9.";if(r!=null){if(!n.includes(`%${r+1}`))return`list.lvlText for level ${r} must contain its own placeholder %${r+1}.`;if(n.some(o=>Number(o.slice(1))>r+1))return`list.lvlText for level ${r} cannot reference a deeper level than %${r+1}.`}return null}function ny(e){return _d(e)?["paragraphId","fingerprint","exactText","text"].some(r=>typeof e[r]=="string"&&e[r].trim())?e.captureRef!=null||e.occurrence!=null||e.revisionView!=null&&e.revisionView!=="accepted"?qe("list.continueFrom targets a batch-start accepted-view paragraph (no captureRef, occurrence or rejected view).","list.continueFrom"):null:qe("list.continueFrom needs paragraphId, fingerprint or exactText.","list.continueFrom"):qe("join needs list.continueFrom: a paragraph target { paragraphId, fingerprint?, exactText? } of an item of the list to continue.","list.continueFrom")}function Od(e){if(!_d(e))return qe('list-format operations require a "list" object.',"list");let t=Object.keys(e).filter(i=>!qv.has(i));if(t.length>0)return qe(`list has unsupported ${t.length===1?"key":"keys"}: ${t.join(", ")}.`,`list.${t[0]}`);let r=Object.keys(e).filter(i=>Td.includes(i));if(r.length>0)return qe(`list.${r[0]} is not supported yet (detach is a later release).`,`list.${r[0]}`);if(!bd.includes(e.mode))return qe(`list.mode must be one of: ${bd.join(", ")} (detach is not available yet).`,"list.mode");let n=Object.keys(e).filter(i=>!El[e.mode].includes(i));if(n.length>0)return qe(`list.${n[0]} does not apply to mode "${e.mode}" (it accepts: ${El[e.mode].filter(i=>i!=="mode").join(", ")}).`,`list.${n[0]}`);if(e.scope!=null&&!Hv.includes(e.scope))return qe(`list.scope must be "list" (every paragraph of the target's list) or "range" (only the target range).`,"list.scope");let o=ry(e);if(o)return o;if(e.mode==="join")return ny(e.continueFrom);if(e.mode==="change-format"){if(e.format==null&&e.kind==null&&e.lvlText==null&&e.start==null)return qe("change-format needs at least one of list.format, list.kind, list.lvlText or list.start.","list.format");if(e.kind==="numbered"&&e.format==null)return qe('kind "numbered" does not say which numbering format; pass list.format (decimal, upperLetter, lowerLetter, upperRoman or lowerRoman).',"list.format");if(e.lvlText!=null){let i=(e.format??(e.kind==="bullet"?"bullet":null))==="bullet",l=Rl(e.lvlText,{bullet:i,level:Number.isInteger(e.level)?e.level:null});if(l)return qe(l,"list.lvlText")}if(e.start!=null){if(!(Number.isInteger(e.start)&&e.start>=1&&e.start<=32767))return qe("list.start must be an integer from 1 to 32767.","list.start");if(e.scope==="range")return qe('scope "range" continues the source count across the split; list.start applies to scope "list" only.',"list.start")}return null}if(e.strip!=null&&!Gv.includes(e.strip))return{message:'list.strip must be "marker" or "none".',field:"list.strip"};let a=e.strip||"marker";if(e.start!=null){if(a==="marker")return{message:'list.start is derived from the typed marker when strip is "marker"; omit it, or use strip: "none".',field:"list.start"};if(!(Number.isInteger(e.start)&&e.start>=1&&e.start<=32767))return{message:"list.start must be an integer from 1 to 32767.",field:"list.start"}}return a==="none"&&e.format==null&&e.kind!=="bullet"?{message:'strip: "none" leaves the text alone, so list.format (or kind: "bullet") must state the list format.',field:"list.format"}:null}function Pl(e){let t=e.format||(e.kind==="bullet"?"bullet":null);return{mode:e.mode,format:t,kind:t?t==="bullet"?"bullet":"numbered":e.kind||null,level:Number.isInteger(e.level)?e.level:0,explicitLevel:Number.isInteger(e.level)?e.level:null,strip:e.strip||"marker",start:Number.isInteger(e.start)?e.start:null,lvlText:typeof e.lvlText=="string"?e.lvlText:null,scope:e.scope||"list",continueFrom:e.continueFrom??null}}function oy(e){let t=e.toUpperCase();if(!t||!ty.test(t))return null;let r=0;for(let n=0;n<t.length;n+=1){let o=Nd[t[n]],a=Nd[t[n+1]]||0;r+=o<a?-o:o}return r}function fo(e){let t=String(e??"");if(Qv.test(t))return{unsupported:"multilevel",marker:t.trim().split(/\s/)[0]};if(ey.test(t))return{unsupported:"parenthesized",marker:t.trim().split(/\s/)[0]};let r=Zv.exec(t);if(r)return{marker:r[2],terminator:"",bulletChar:r[2],prefixLength:r[0].length,candidates:[{format:"bullet",value:null}]};let n=Jv.exec(t);if(!n)return null;let[o,,a,i,l]=n,s=`${a??i}${l}`,c={marker:s,terminator:l,prefixLength:o.length};if(a!=null){let p=Number.parseInt(a,10);return p<1?{unsupported:"zero",marker:s}:{...c,candidates:[{format:"decimal",value:p}]}}let f=i===i.toUpperCase(),u=i===i.toLowerCase();if(!f&&!u)return null;let d=[];i.length===1&&d.push({format:f?"upperLetter":"lowerLetter",value:i.toLowerCase().charCodeAt(0)-96});let m=oy(i);return m!=null&&d.push({format:f?"upperRoman":"lowerRoman",value:m}),d.length===0?null:{...c,candidates:d}}function kd(e,t=null){if(e.length===0)return{error:{reason:"none"}};let r=new Set(e.map(i=>i.terminator)),n=new Set(e.filter(i=>i.bulletChar).map(i=>i.bulletChar));if(r.size>1||n.size>1)return{error:{reason:"mixed",markers:e.map(i=>i.marker)}};if(t){let i=e.find(l=>!l.candidates.some(s=>s.format===t));return i?{error:{reason:"format-mismatch",marker:i.marker,requestedFormat:t}}:{format:t}}let o=e[0].candidates.map(i=>i.format);for(let i of e.slice(1)){let l=i.candidates.map(s=>s.format);o=o.filter(s=>l.includes(s))}if(o.length===0)return{error:{reason:"mixed",markers:e.map(i=>i.marker)}};if(o.length===1)return{format:o[0]};let a=o.filter(i=>{if(e.length<2)return!1;let l=e.map(s=>s.candidates.find(c=>c.format===i).value);return l.every((s,c)=>c===0||s===l[c-1]+1)});return a.length===1?{format:a[0]}:{error:{reason:"ambiguous",marker:e[0].marker,formats:o}}}function Md(e,t){return e.candidates.find(r=>r.format===t)?.value??null}function Ld({format:e,level:t,terminator:r=".",bulletChar:n=null}){return e==="bullet"?{ilvl:t,numFmt:"bullet",lvlText:n==="-"||n==="*"||!n?"\u2022":n}:{ilvl:t,numFmt:e,lvlText:`%${t+1}${r||"."}`}}function Bd({format:e,level:t,terminator:r="",bulletChar:n=null}){return`list-format:${e}:${t}:${e==="bullet"?n||"":r||"."}`}var ay="LIST_MARKER_NOT_BOUND",iy="UNSUPPORTED_LIST_CONVERSION",sy="LIST_FORMAT_NOT_APPLIED",ly="UNSUPPORTED_LIST_FORMAT_CHANGE",cy="UNKNOWN_PARAGRAPH_FORMAT_PROPERTY";var Fd="PARAGRAPH_NUMBERING_NOT_FOUND",Dd="PARAGRAPH_FORMAT_REVISION_CONFLICT",mo=Object.freeze(["alignment","keepNext","keepLines","pageBreakBefore","style","numbering"]),uy=Object.freeze({bullet:"bullet",decimal:"decimal",lowerAlpha:"lowerLetter",upperAlpha:"upperLetter",lowerRoman:"lowerRoman",upperRoman:"upperRoman"}),Cl=new Set(["bullet","decimal","lowerLetter","upperLetter","lowerRoman","upperRoman"]);function fy(e){return e==="literal"}function _l(e={}){return fy(e.listMarkers)?"off":(e.strictListConversion!==void 0?e.strictListConversion===!0:e.atomic===!0)?"error":"warn"}function Ud(e,t=80){let r=String(e??"");return r.length>t?`${r.slice(0,t)}...`:r}function Pi(e){let t=String(e??"");if(!t.trim()||/[\r\n]/.test(t))return null;let r=qr(t,{allowZeroSpaceAfterMarker:!1,indentSpaces:2});return!r||!r.marker||r.markerType!=="bullet"&&!/[.)]$/.test(r.marker)?null:{marker:r.marker,kind:r.markerType==="bullet"?"bullet":"numbered",numberingStyle:r.numberingStyle,numFmt:uy[r.numberingStyle]||"decimal",text:String(r.text||"").trim()}}function Xd({originalText:e,modifiedText:t,targetIsListItem:r}){if(r)return null;let n=Pi(t);if(!n)return null;let o=Pi(e);return o&&o.kind===n.kind&&o.numFmt===n.numFmt?null:n}function dy(e,t){if(t)return null;let r=e.numFmt==="bullet"?"bullet":e.numFmt,n={mode:"convert-plain",format:r,strip:"none"};if(r!=="bullet"){let a=fo(`${e.marker} x`)?.candidates?.find(i=>i.format===r)?.value;Number.isInteger(a)&&a>1&&(n.start=a)}return{type:"list-format",list:n}}function zd(e,{policy:t,targetText:r,operationIndex:n}={}){let o=t==="error",a=o?iy:ay,i=o?`Converting a plain paragraph to a list item is not supported by text edits: the new text begins with the list marker "${e.marker}", which would be written as literal text with no list binding. Use a list-format convert-plain operation on the paragraph (capability list-format-v1), or pass listMarkers: "literal" to keep the marker as text.`:`Modified text begins with the list marker "${e.marker}", but the marker was written as literal text; no list binding was created. A list-format convert-plain operation creates the list binding.`,l=dy(e,!!Pi(r));return{code:a,severity:o?"error":"warning",message:i,listMarker:e.marker,requestedList:{kind:e.kind,format:e.numFmt},...r?{targetExcerpt:Ud(r)}:{},...Number.isInteger(n)?{operationIndex:n}:{},recovery:{action:"use_list_format_convert_plain",hint:l?'Keep the paragraph text as it is and send a list-format operation on the same target (recovery.suggestedOperation plus your target), or pass listMarkers: "literal" to write the marker as text intentionally.':'Edit the text with a redline that starts with the typed marker, then convert it with a list-format convert-plain operation (strip: "marker"), or pass listMarkers: "literal" to write the marker as text intentionally.',...l?{suggestedOperation:l}:{},field:"listMarkers",allowedValue:"literal"}}}function my(e,t,r){let n=d=>Array.from(e.getElementsByTagNameNS("*",d)),o=(d,m)=>d?.getAttribute?.(`w:${m}`)??d?.getAttribute?.(m)??null,a=(d,m)=>Array.from(d?.childNodes||[]).find(p=>p.nodeType===1&&p.localName===m)||null,i=n("num").find(d=>String(o(d,"numId"))===String(t));if(!i)return null;let l=Array.from(i.childNodes).filter(d=>d.nodeType===1&&d.localName==="lvlOverride").find(d=>Number(o(d,"ilvl")||0)===r),s=o(a(a(l,"lvl"),"numFmt"),"val");if(s)return{numFmt:s};let c=o(a(i,"abstractNumId"),"val"),f=n("abstractNum").find(d=>String(o(d,"abstractNumId"))===String(c));if(!f)return null;let u=Array.from(f.childNodes).filter(d=>d.nodeType===1&&d.localName==="lvl").find(d=>Number(o(d,"ilvl")||0)===r);return u?{numFmt:o(a(u,"numFmt"),"val")||"decimal"}:null}function py(e,t,r=0){if(!String(e||"").trim()||t==null)return null;let n=V(String(e));if(!n?.doc)return null;let o=my(n.doc,t,Number(r)||0);return o?{numFmt:o.numFmt,kind:o.numFmt==="bullet"?"bullet":"numbered"}:null}function gy({requested:e,sourceLevel:t}){if(!e||!t)return null;let r=e.kind==="bullet"?"bullet":"numbered";return r!==t.kind?{requested:e,source:t}:r==="numbered"&&Cl.has(e.numFmt)&&Cl.has(t.numFmt)&&e.numFmt!==t.numFmt?{requested:e,source:t}:null}function jd(e,{policy:t,numId:r,level:n,marker:o,targetText:a,operationIndex:i}={}){let l=t==="error",s=l?ly:sy,c=(p,g)=>p==="bullet"?"a bullet list":`a numbered list${g?` (${g})`:""}`,f=e.requested.kind==="bullet"?"bullet":e.requested.numFmt||e.requested.format,u=c(e.requested.kind,f),d=c(e.source.kind,e.source.numFmt),m=Cl.has(f)?{type:"list-format",list:{mode:"change-format",format:f,level:Number(n)||0,scope:"list"}}:null;return{code:s,severity:l?"error":"warning",message:`${l?"Changing the list format is not supported by text edits":"The requested list format was not applied"}: the list item keeps its source numbering definition (numId ${r}, ${d}); the edit asked for ${u}${o?` ("${o}")`:""}. A list-format change-format operation changes the list's format (capability list-format-change-v1).`,requestedList:{kind:e.requested.kind,format:f},sourceList:{numId:String(r),level:Number(n)||0,kind:e.source.kind,format:e.source.numFmt},...a?{targetExcerpt:Ud(a)}:{},...Number.isInteger(i)?{operationIndex:i}:{},recovery:{action:"use_list_format_change_format",hint:m?`Text edits cannot change a list's kind or numbering format. Send recovery.suggestedOperation with a target on one item of the list as its own operation (scope "list" rebinds every item; scope "range" only a range that runs to the end of the list). Make any text edit in a separate redline without the new markers, targeting a different paragraph or a separate call. Or pass listMarkers: "literal" to accept the current result.`:`Text edits cannot change a list's kind or numbering format. Use a list-format change-format operation, or pass listMarkers: "literal" to accept the current result.`,...m?{suggestedOperation:m}:{},field:"listMarkers",allowedValue:"literal"}}}function Vd(e){if(e===null)return null;if(typeof e!="object"||Array.isArray(e))return"numbering must be null (remove the list binding) or an object { numId, level }.";let t=Object.keys(e).filter(a=>a!=="numId"&&a!=="level");if(t.length>0)return`numbering has unsupported ${t.length===1?"key":"keys"}: ${t.join(", ")}. Use only numId and level.`;let r=e.numId;if(!(Number.isInteger(r)&&r>=1||typeof r=="string"&&/^[1-9]\d*$/.test(r)))return"numbering.numId must be a positive integer (numId 0 is not a list; pass numbering: null to remove the binding).";let o=e.level;return o!==void 0&&!(Number.isInteger(o)&&o>=0&&o<=8)?"numbering.level must be an integer from 0 to 8.":null}function Ci(e){return!e||typeof e!="object"?[]:Object.keys(e).filter(t=>!mo.includes(t))}function Wd(e){let t=e.map(r=>`"${r}"`).join(", ");return{code:cy,severity:"warning",message:`paragraph-format ignored unsupported ${e.length===1?"property":"properties"} ${t}. Supported: ${mo.join(", ")}.`,properties:e,recovery:{action:"change_request",hint:`Use only: ${mo.join(", ")}.`}}}function Ol(e){return`${e.code}: ${e.message}`}function $d(e){return String(e??"").replace(/[\s\u00a0]+/g," ").trim()}function Kd({modifiedText:e,sourceItems:t,sourceNumberingXml:r}){if(!Array.isArray(t)||t.length===0)return null;let o=String(e??"").split(/\r?\n/).filter(i=>i.trim()).map(i=>({line:i,item:Pi(i)})),a=new Set;for(let i of t){let l=$d(i.text),s=o.find((u,d)=>!a.has(d)&&$d(u.item?u.item.text:u.line)===l);if(!s||(a.add(o.indexOf(s)),!s.item))continue;let c=py(r,i.numId,i.ilvl),f=gy({requested:s.item,sourceLevel:c});if(f)return{mismatch:f,marker:s.item.marker,numId:i.numId,level:i.ilvl,targetText:i.text}}return null}var hy=new Set(["redline","replace","format","character-format","paragraph-format","list-format","list-change","table-reconciliation","insert","restore","delete","comment","comment_reply","comment_resolve","highlight"]),Gd=Object.freeze(["auto","merge-same-author","slice-cross-author","reject-input","accept-all-first","accept-all-first-keep-normalized"]);function fa(e){return Gd.includes(e)}function Yt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Re(e){return typeof e=="string"&&e.trim().length>0}function wy(e){return e==="comment_reply"||e==="comment_resolve"}function vy(e){let t=e?.type;return t==="insert"&&e?.target?.revisionView==="rejected"?"rejected-insert":t==="restore"?"restore":t==="comment"||t==="comment_reply"||t==="comment_resolve"||t==="highlight"?t:t==="paragraph-format"?"paragraph-format":t==="list-format"?"list-format":t==="character-format"||t==="format"&&(e?.textToFormat!=null||e?.properties!=null)?"format":"redline"}function Tn(e,t=null,r="accepted"){let n=r==="rejected"?"rejected":"accepted";return Yt(e)?{text:typeof e.exactText=="string"?e.exactText:typeof e.text=="string"?e.text:"",index:e.index??e.paragraphIndex??t??null,paragraphId:Re(e.paragraphId)?e.paragraphId.trim():null,occurrence:Number.isInteger(e.occurrence)&&e.occurrence>0?e.occurrence:null,inTable:typeof e.inTable=="boolean"?e.inTable:null,fingerprint:Re(e.fingerprint)?e.fingerprint.trim():Re(e.sourceFingerprint)?e.sourceFingerprint.trim():null,revisionView:e.revisionView==="rejected"?"rejected":e.revisionView==="accepted"?"accepted":n,captureRef:Re(e.captureRef)?e.captureRef.trim():null,select:typeof e.select=="string"?e.select:null}:{text:typeof e=="string"?e:"",index:t??null,paragraphId:null,occurrence:null,inTable:null,fingerprint:null,revisionView:n}}function St(e){let t=Yt(e)?e:{},r=vy(t),n=r==="restore"?"rejected":"accepted",o=Tn(t.target,t.targetRef,n),a=t.targetEnd!=null?Tn(t.targetEnd,t.targetEndRef,n):null;return{...t,operationId:Re(t.operationId)?t.operationId.trim():null,captureKey:Re(t.captureKey)?t.captureKey.trim():null,operationKind:r,anchor:Yt(t.anchor)?{exactText:typeof t.anchor.exactText=="string"?t.anchor.exactText:"",occurrence:Number.isInteger(t.anchor.occurrence)&&t.anchor.occurrence>0?t.anchor.occurrence:1,occurrenceExplicit:Number.isInteger(t.anchor.occurrence)&&t.anchor.occurrence>0,offset:Number.isInteger(t.anchor.offset)?t.anchor.offset:null}:null,targetDescriptor:o,targetEndDescriptor:a,target:o.text,targetRef:o.index,targetEndRef:a?.index??t.targetEndRef??null,...t.type==="delete"&&t.modified==null?{modified:""}:{}}}function Nr(e){if(!Yt(e))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation must be an object."}};let t=e.type;if(t!=null&&t!==""&&!hy.has(t))return{valid:!1,error:{code:"INVALID_OPERATION",message:`Unsupported operation type: "${String(t)}".`}};let r=St(e);if(Yt(e.target)&&e.target.revisionView!=null&&e.target.revisionView!=="accepted"&&e.target.revisionView!=="rejected")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Target revisionView must be "accepted" or "rejected" when provided.'}};if(Yt(e.targetEnd)&&e.targetEnd.revisionView!=null&&e.targetEnd.revisionView!=="accepted"&&e.targetEnd.revisionView!=="rejected")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Target revisionView must be "accepted" or "rejected" when provided.'}};if(e.operationId!=null&&(!Re(e.operationId)||e.operationId.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"operationId must be a non-empty string under 256 characters when provided."}};if(e.captureKey!=null&&(!Re(e.captureKey)||e.captureKey.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"captureKey must be a non-empty string under 256 characters when provided."}};if(Yt(e.target)&&e.target.captureRef!=null&&(!Re(e.target.captureRef)||e.target.captureRef.trim().length>256))return{valid:!1,error:{code:"INVALID_OPERATION",message:"target.captureRef must be a non-empty string under 256 characters when provided."}};if(Yt(e.target)&&e.target.select!=null&&typeof e.target.select!="string")return{valid:!1,error:{code:"INVALID_OPERATION",message:"target.select must be a string when provided."}};let n=r.targetDescriptor;if(!wy(r.operationKind)&&!Re(n.text)&&n.index==null&&!n.paragraphId&&!n.fingerprint&&!n.captureRef)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation target must provide text, a paragraph index, a paragraphId, or a captureRef."}};if(n.occurrence!=null&&!Re(n.text))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Target occurrence requires target text."}};if(r.operationKind==="redline"){let o=typeof r.modified=="string",a=r.replacements!==void 0;if(o===a)return{valid:!1,error:{code:"INVALID_OPERATION",message:'Redline operations require exactly one of string "modified" or non-empty "replacements".'}};if(a){if(t!=null&&t!==""&&!["redline","replace"].includes(t))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements are supported only for redline or replace operations."}};if(n.revisionView!=="accepted"||n.captureRef||n.occurrence!=null||r.captureKey||r.targetEndDescriptor||r.targetEndRef!=null)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements v1 require one batch-start accepted-view paragraph target without captures, target occurrence, or a target range."}};let i=Si(r.replacements);if(!i.ok)return{valid:!1,error:i.error};if(i.replacements.some(l=>/\r|\n/.test(l.replace)))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized replacements v1 cannot insert paragraph breaks."}};if(i.replacements.some(l=>/\r|\n/.test(l.find)))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Localized replacements v1 cannot span a line break; use one replacement per line or a full "modified" paragraph.'}};r.replacements=i.replacements}}if(r.operationKind==="rejected-insert"){if(!Re(r.modified))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Rejected-view insert operations require non-empty string "modified" text.'}};if(!r.anchor||!Re(r.anchor.exactText)||!Number.isInteger(r.anchor.offset)||r.anchor.offset<0||r.anchor.offset>r.anchor.exactText.length)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Rejected-view insert operations require anchor.exactText, a positive occurrence, and an offset within the anchor text."}};if(r.existingRevisions!=="slice-cross-author")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Rejected-view insert operations require existingRevisions: "slice-cross-author".'}}}if(r.operationKind==="restore"){let o=e.modified!==void 0,a=e.replacements!==void 0,i=Re(r.modified),l=Array.isArray(r.modified)&&r.modified.length>0&&r.modified.every(Re);if(o&&a)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore operations accept modified or replacements, not both."}};if(o&&!i&&!l)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore modified must be a non-empty string or non-empty string array."}};if(!o&&(n.revisionView!=="rejected"||!n.paragraphId&&!n.fingerprint||n.captureRef||n.occurrence!=null||r.captureKey||r.targetEndDescriptor||r.targetEndRef!=null||/\r|\n/.test(n.text||"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Verbatim and localized restore require one strong batch-start rejected-view paragraph target without captures, target occurrence, or a target range."}};if(a){let s=Si(r.replacements);if(!s.ok)return{valid:!1,error:s.error};if(s.replacements.some(c=>/\r|\n/.test(c.replace)))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Localized restore cannot insert paragraph breaks."}};r.replacements=s.replacements}if(r.generateRedlines===!1)return{valid:!1,error:{code:"INVALID_OPERATION",message:"Restore operations require tracked changes and cannot set generateRedlines to false."}}}if(r.structuredContent!=null&&typeof r.structuredContent!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:"structuredContent must be a boolean when provided."}};if(r.pairReplacements!=null&&typeof r.pairReplacements!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:"pairReplacements must be a boolean when provided."}};if(r.listMarkers!=null&&r.listMarkers!=="literal")return{valid:!1,error:{code:"INVALID_OPERATION",message:'listMarkers must be "literal" when provided.'}};if(r.existingRevisions!=null&&!fa(r.existingRevisions))return{valid:!1,error:{code:"INVALID_OPERATION",message:`existingRevisions must be one of: ${Gd.join(", ")}.`}};if(r.insertionAffinity!=null){if(!Yt(r.insertionAffinity))return{valid:!1,error:{code:"INVALID_OPERATION",message:"insertionAffinity must be an object when provided."}};let{formatting:o,hyperlink:a,revision:i,bookmark:l,comment:s}=r.insertionAffinity;if(o!=null&&!["left","right","none"].includes(o))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.formatting must be "left", "right", or "none".'}};if(a!=null&&!["inside","outside","preserve"].includes(a))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.hyperlink must be "inside", "outside", or "preserve".'}};if(i!=null&&!["coalesce_same_author","separate"].includes(i))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.revision must be "coalesce_same_author" or "separate".'}};if(l!=null&&!["inside","outside"].includes(l))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.bookmark must be "inside" or "outside".'}};if(s!=null&&!["inside","outside"].includes(s))return{valid:!1,error:{code:"INVALID_OPERATION",message:'insertionAffinity.comment must be "inside" or "outside".'}}}if(r.operationKind==="comment"&&!Re(r.commentContent))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment operations require a non-empty "commentContent" field.'}};if(r.operationKind==="comment_reply"){if(!Re(String(r.parentCommentId??"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment reply operations require a "parentCommentId".'}};if(!Re(r.commentContent))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment reply operations require a non-empty "commentContent" field.'}}}if(r.operationKind==="comment_resolve"){if(!Re(String(r.commentId??"")))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment resolve operations require a "commentId".'}};if(r.resolved!=null&&typeof r.resolved!="boolean")return{valid:!1,error:{code:"INVALID_OPERATION",message:'Comment resolve "resolved" must be a boolean when provided.'}}}if(r.operationKind==="highlight"){if(!Re(r.textToHighlight))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Highlight operations require a non-empty "textToHighlight" field.'}};if(r.color!=null&&!Re(r.color))return{valid:!1,error:{code:"INVALID_OPERATION",message:"Highlight color must be a non-empty string when provided."}}}if(r.operationKind==="format"){if(!Re(r.textToFormat))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Format operations require a non-empty "textToFormat" field.'}};if(r.textOccurrence!=null&&(!Number.isInteger(r.textOccurrence)||r.textOccurrence<1))return{valid:!1,error:{code:"INVALID_OPERATION",message:"textOccurrence must be a positive integer when provided."}};if(!Yt(r.properties))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Format operations require a "properties" object.'}};if(r.formattingRevisionPolicy!=null&&!["always","coalesce-own-insertion"].includes(r.formattingRevisionPolicy))return{valid:!1,error:{code:"INVALID_OPERATION",message:'formattingRevisionPolicy must be "always" or "coalesce-own-insertion".'}}}if(r.operationKind==="paragraph-format"){if(!Yt(r.properties))return{valid:!1,error:{code:"INVALID_OPERATION",message:'Paragraph-format operations require a "properties" object.'}};let o=Ci(r.properties);if(o.length>0)return{valid:!1,error:{code:"INVALID_OPERATION",message:`paragraph-format does not support ${o.length===1?"property":"properties"} ${o.map(a=>`"${a}"`).join(", ")}. Supported: ${mo.join(", ")}.`,field:`properties.${o[0]}`,properties:o,recovery:{action:"change_request",hint:`Use only: ${mo.join(", ")}.`}}};if(r.properties.numbering!==void 0){let a=Vd(r.properties.numbering);if(a)return{valid:!1,error:{code:"INVALID_OPERATION",message:a,field:"properties.numbering",recovery:{action:"change_request",hint:'Pass numbering as { "numId": <existing numId from inspect>, "level": 0 } or null.'}}}}}if(r.operationKind==="list-format"){let o=Od(r.list);if(o)return{valid:!1,error:{code:"INVALID_OPERATION",message:o.message,field:o.field,recovery:{action:"change_request",hint:'Pass list as { "mode": "convert-plain" } (optional format, kind, level, strip "marker" | "none", start with strip "none"), { "mode": "change-format", "format": ... } (optional kind, lvlText, start, level, scope "list" | "range") or { "mode": "join", "continueFrom": { "paragraphId": ... } } (optional scope).'}}};if(e.modified!==void 0||e.replacements!==void 0)return{valid:!1,error:{code:"INVALID_OPERATION",message:"list-format changes list structure only; express text changes as a separate redline operation.",field:e.modified!==void 0?"modified":"replacements"}};if(n.captureRef||n.occurrence!=null||n.revisionView!=="accepted")return{valid:!1,error:{code:"INVALID_OPERATION",message:"list-format v1 targets batch-start accepted-view paragraphs without captures or target occurrence."}}}return r.author!=null&&!Re(r.author)?{valid:!1,error:{code:"INVALID_OPERATION",message:"Operation author must be a non-empty string when provided."}}:{valid:!0,operation:r}}function Ut(e,t,r){return Re(e?.author)?e.author.trim():Re(t)?t.trim():Re(r)?r.trim():"Author"}var Wr=class{constructor(t,r={}){if(this.originalDocumentXml=typeof t=="string"?t:"",this.currentDocumentXml=this.originalDocumentXml,this.serializer=le(),this.parseResult=V(this.originalDocumentXml,"application/xml"),this.document=this.parseResult.doc||null,this.revisionIdAllocator=null,this.initialTargetReferenceSnapshot=null,this.paragraphIndex=null,this.invalidated=!1,this.hasChanges=!1,this.documentHasChanges=!1,this.deferSerialization=r?._deferDocumentSerialization===!0,this.instrumentation=r?._sessionInstrumentation||null,this.runtimeContext=null,this.commentsXml=null,this.commentsExtendedXml=null,this.commentsXmlMode="merge",this.commentsExtendedXmlMode="merge",this.numberingXmlParts=[],this.results=[],this.executionOrder=[],this.authorsUsed=new Set,this.captureTable=new Map,this.sourceTargetRegistry=null,this.nextCaptureParaId=1,this.receiptCollector=new sa,this.document){this.instrumentation?.onDocumentParse?.(this.originalDocumentXml),this.revisionIdAllocator=r?._revisionIdAllocator instanceof De?r._revisionIdAllocator:new De,this.revisionIdAllocator._receiptCollector=this.receiptCollector,cr(this.document,this.revisionIdAllocator),Cr(this.document,this.revisionIdAllocator);let n=this.getParagraphMetadataIndex();this.initialTargetReferenceSnapshot=Us(this.document,n)}}get valid(){return!!this.document&&!this.parseResult.error}setDocumentXml(t){this.currentDocumentXml=t,this.invalidateParagraphIndex()}invalidateParagraphIndex(){this.invalidated=!0,this.paragraphIndex=null}serialize(){return this.document?(this.instrumentation?.onDocumentSerialize?.(this.document),this.serializer.serializeToString(this.document)):this.currentDocumentXml}serializeCurrent(){return this.hasChanges?this.documentHasChanges?(this.currentDocumentXml=this.serialize(),this.currentDocumentXml):this.currentDocumentXml:this.originalDocumentXml}markMutationCommitted(t=!0){this.hasChanges=!0,this.documentHasChanges=this.documentHasChanges||t,t&&this.invalidateParagraphIndex()}generateParagraphId(){return(1073741824+this.nextCaptureParaId++).toString(16).toUpperCase()}createSavepoint(){return this.document?{document:this.document.cloneNode(!0),allocatorNextId:this.revisionIdAllocator?.nextId,allocatorOccupiedIds:this.revisionIdAllocator?.occupiedIds instanceof Set?new Set(this.revisionIdAllocator.occupiedIds):null,hasChanges:this.hasChanges,documentHasChanges:this.documentHasChanges,currentDocumentXml:this.currentDocumentXml,commentsXml:this.commentsXml,commentsExtendedXml:this.commentsExtendedXml,commentsXmlMode:this.commentsXmlMode,commentsExtendedXmlMode:this.commentsExtendedXmlMode,captureTable:Hd(this.captureTable),sourceTargetRegistry:this.sourceTargetRegistry?.createSavepoint?.(this.document)||null,nextCaptureParaId:this.nextCaptureParaId,receiptCollector:this.receiptCollector?this.receiptCollector.createSavepoint():null}:null}restoreSavepoint(t){t?.document&&(this.document=t.document,this.hasChanges=t.hasChanges,this.documentHasChanges=t.documentHasChanges===!0,this.currentDocumentXml=t.currentDocumentXml,this.commentsXml=t.commentsXml,this.commentsExtendedXml=t.commentsExtendedXml,this.commentsXmlMode=t.commentsXmlMode||"merge",this.commentsExtendedXmlMode=t.commentsExtendedXmlMode||"merge",this.captureTable=t.captureTable?Hd(t.captureTable):new Map,this.sourceTargetRegistry?.restoreSavepoint?.(this.document,t.sourceTargetRegistry),typeof t.nextCaptureParaId=="number"&&(this.nextCaptureParaId=t.nextCaptureParaId),this.revisionIdAllocator&&(this.revisionIdAllocator.nextId=t.allocatorNextId,t.allocatorOccupiedIds instanceof Set&&(this.revisionIdAllocator.occupiedIds=new Set(t.allocatorOccupiedIds)),this.revisionIdAllocator._receiptCollector=this.receiptCollector,Cr(this.document,this.revisionIdAllocator)),t.receiptCollector&&this.receiptCollector&&this.receiptCollector.restoreSavepoint(t.receiptCollector),this.invalidateParagraphIndex())}getParagraphIndex(){return this.getParagraphMetadataIndex().entries}getParagraphMetadataIndex(){return this.paragraphIndex?this.paragraphIndex:(this.paragraphIndex=rr(this.document),this.invalidated=!1,this.paragraphIndex)}rollback(){return this.currentDocumentXml=this.originalDocumentXml,this.hasChanges=!1,this.documentHasChanges=!1,this.captureTable.clear(),this.sourceTargetRegistry=null,this.receiptCollector?.clear(),this.originalDocumentXml}};function Hd(e){let t=new Map;if(e instanceof Map)for(let[r,n]of e.entries())t.set(r,JSON.parse(JSON.stringify(n)));return t}function Sn(e,t={}){let r=t?._revisionIdAllocator instanceof De?t._revisionIdAllocator:new De;return t?._documentOperationSession?.receiptCollector&&(r._receiptCollector=t._documentOperationSession.receiptCollector),cr(e,r),Cr(e,r),r}function qd(e){if(!e||typeof e!="object")return{};let t={...e};return e.listFallbackSharedNumIdByKey instanceof Map&&(t.listFallbackSharedNumIdByKey=new Map(e.listFallbackSharedNumIdByKey)),e.tableStructuralRedlineKeys instanceof Set&&(t.tableStructuralRedlineKeys=new Set(e.tableStructuralRedlineKeys)),e.numberingIdState&&typeof e.numberingIdState=="object"&&(t.numberingIdState={...e.numberingIdState,usedNumIds:e.numberingIdState.usedNumIds instanceof Set?new Set(e.numberingIdState.usedNumIds):e.numberingIdState.usedNumIds,usedAbstractNumIds:e.numberingIdState.usedAbstractNumIds instanceof Set?new Set(e.numberingIdState.usedAbstractNumIds):e.numberingIdState.usedAbstractNumIds}),e.listFallbackSequenceState&&typeof e.listFallbackSequenceState=="object"&&(t.listFallbackSequenceState={...e.listFallbackSequenceState,explicitByNumberingKey:e.listFallbackSequenceState.explicitByNumberingKey instanceof Map?new Map(e.listFallbackSequenceState.explicitByNumberingKey):e.listFallbackSequenceState.explicitByNumberingKey}),t}function Yd(e,t){if(!(!e||typeof e!="object")){if(e.listFallbackSharedNumIdByKey instanceof Map&&t.listFallbackSharedNumIdByKey instanceof Map){e.listFallbackSharedNumIdByKey.clear();for(let r of t.listFallbackSharedNumIdByKey)e.listFallbackSharedNumIdByKey.set(...r);t.listFallbackSharedNumIdByKey=e.listFallbackSharedNumIdByKey}if(e.tableStructuralRedlineKeys instanceof Set&&t.tableStructuralRedlineKeys instanceof Set){e.tableStructuralRedlineKeys.clear();for(let r of t.tableStructuralRedlineKeys)e.tableStructuralRedlineKeys.add(r);t.tableStructuralRedlineKeys=e.tableStructuralRedlineKeys}if(e.numberingIdState&&t.numberingIdState){for(let r of["usedNumIds","usedAbstractNumIds"])if(e.numberingIdState[r]instanceof Set&&t.numberingIdState[r]instanceof Set){e.numberingIdState[r].clear();for(let n of t.numberingIdState[r])e.numberingIdState[r].add(n);t.numberingIdState[r]=e.numberingIdState[r]}Object.assign(e.numberingIdState,t.numberingIdState),t.numberingIdState=e.numberingIdState}if(e.listFallbackSequenceState&&t.listFallbackSequenceState){let r=e.listFallbackSequenceState.explicitByNumberingKey,n=t.listFallbackSequenceState.explicitByNumberingKey;if(r instanceof Map&&n instanceof Map){r.clear();for(let o of n)r.set(...o);t.listFallbackSequenceState.explicitByNumberingKey=r}Object.assign(e.listFallbackSequenceState,t.listFallbackSequenceState),t.listFallbackSequenceState=e.listFallbackSequenceState}Object.assign(e,t)}}var Jd=new Set(["redline","restore","rejected-insert","list-format"]),Zd=new Set(["highlight","format","paragraph-format"]),yy="http://schemas.openxmlformats.org/wordprocessingml/2006/main",Qd="LIST_FORMAT_COMPOSITION_CONFLICT",xy=new Set(["redline","replace"]);function em(e){let t=String(e??""),r=fo(t);return r?r.unsupported?`unsupported:${r.marker}`:t.slice(0,r.prefixLength):null}function by(e,t){let r=e.operation;if(!xy.has(r?.type??"redline")||r.targetEnd!=null||r.targetEndRef!=null||r.anchor!=null||r.structuredContent===!0||r.part!=null||r.target?.revisionView==="rejected"||typeof r.modified!="string"||/[\r\n]/.test(r.modified))return{reason:"redline-shape",hint:"Pair a list-format only with a single-paragraph redline or replace of that paragraph: modified without line breaks, no targetEnd, anchor, part or structuredContent."};if(r.modified===t)return{reason:"redline-unchanged",hint:"The redline does not change the text; drop it and send only the list-format."};let n=em(t),o=em(r.modified);return n!==o?{reason:"marker-changed",sourceMarker:n,modifiedMarker:o,hint:'The redline adds, removes or changes the typed marker. Keep the marker text exactly as it is (the list-format strips it), and express a new label through list-format (strip "none" with format/start, or change-format).'}:null}function Iy(e,t,r,n){let o=n.list?.mode;if(o!=="change-format"&&o!=="join")return[];if((n.list?.scope||"list")!=="list")return[];let a=r.sourceIds.map(l=>t.entries.get(l)?.paragraph).filter(Boolean),i=a.map(l=>Oe(l)).find(Boolean);return i?Array.from(e.getElementsByTagNameNS(yy,"p")).filter(l=>a.includes(l)||kt(l)?!1:Oe(l)?.numId===i.numId):[]}function Ny(e){let t={};if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="name"||r==="stack"||r==="message"||r==="code"||(t[r]=n);return{code:typeof e?.code=="string"&&e.code?e.code:"OPERATION_ERROR",message:e?.message||String(e),...t}}function Ty(e,t){return!!t&&se(e).includes(t)}function Sy(e=[]){let t=[];for(let r of e)if(!(!r||r.nodeType!==1)){r.localName==="p"&&t.push(r);for(let n of Array.from(r.getElementsByTagNameNS?.("*","p")||[]))t.includes(n)||t.push(n)}return t}var Ml=class{constructor(t){this.document=t,this.nextId=1,this.entries=new Map,this.idsByNode=new WeakMap}register(t,r={}){let n=this.idsByNode.get(t);if(n)return n;let o=`S${this.nextId++}`;return this.entries.set(o,{sourceId:o,paragraph:t,sourceIndex:r.index||null,paragraphId:r.paragraphId||null,fingerprint:r.fingerprint||null,text:r.text||"",revisionView:r.revisionView==="rejected"?"rejected":"accepted",consumed:!1,consumedByOperation:null}),this.idsByNode.set(t,o),o}describe(t){let r=this.entries.get(t);return r?{sourceId:t,index:r.sourceIndex,paragraphId:r.paragraphId,fingerprint:r.fingerprint,text:r.text,revisionView:r.revisionView}:null}resolve(t,r=this.document){let n=this.entries.get(t);return n?n.consumed?{error:{code:"TARGET_CONSUMED_BY_OPERATION",message:`Compiled source target ${t} was consumed by operation ${n.consumedByOperation}.`,sourceTarget:this.describe(t),consumedByOperation:n.consumedByOperation}}:Ty(r,n.paragraph)?{paragraph:n.paragraph,resolvedBy:"batch_source"}:{error:{code:"TARGET_CONSUMED_BY_OPERATION",message:`Compiled source target ${t} is no longer present in the live document.`,sourceTarget:this.describe(t),consumedByOperation:n.consumedByOperation}}:{error:{code:"SOURCE_TARGET_NOT_FOUND",message:`Compiled source target ${String(t)} was not found.`}}}createSavepoint(t=this.document){let r=se(t);return new Map(Array.from(this.entries,([n,o])=>[n,{paragraphIndex:r.indexOf(o.paragraph),consumed:o.consumed,consumedByOperation:o.consumedByOperation}]))}restoreSavepoint(t,r){this.document=t,this.idsByNode=new WeakMap;let n=se(t);for(let[o,a]of this.entries){let i=r instanceof Map?r.get(o):null;a.consumed=i?.consumed===!0,a.consumedByOperation=i?.consumedByOperation||null,a.paragraph=Number.isInteger(i?.paragraphIndex)&&i.paragraphIndex>=0&&n[i.paragraphIndex]||null,a.paragraph&&this.idsByNode.set(a.paragraph,o)}}previewSuccessor(t,r,n){let o=this.entries.get(t);if(!o||!o.paragraph)return null;if(!Array.isArray(r)||!r.includes(o.paragraph))return o.paragraph;let a=Sy(n),i=o.paragraphId?a.filter(l=>He(l)===o.paragraphId):[];return i.length===1?i[0]:a.length===1?a[0]:null}commitMutation(t,r,n,o){let a=this.entries.get(t);if(!a||!Array.isArray(r)||!r.includes(a.paragraph))return;let i=this.previewSuccessor(t,r,n);if(i){a.paragraph=i,this.idsByNode.set(i,t);return}a.paragraph=null,a.consumed=!0,a.consumedByOperation=o}};function Ay(e,t){return{index:e.index,paragraphId:e.paragraphId,fingerprint:e.fingerprint,text:e.text,inTable:e.inTable,revisionView:t}}function kl(e,t,r,n,o,a={}){let i=t?.revisionView==="rejected"?"rejected":"accepted";o[i]||(o[i]=rr(e,{revisionView:i}));let l=o[i],s=ln(e,{targetText:t.text,targetRef:t.index,targetDescriptor:t,opType:r,strictAmbiguity:n,paragraphMetadataIndex:l,metadataIndices:o,onInfo:a.onInfo,onWarn:a.onWarn}),c=l.byParagraph.get(s.paragraph);return{paragraph:s.paragraph,resolvedBy:s.resolvedBy,metadata:Ay(c,i)}}function _i(e,t,r,n,o,a={},i=null){return{code:e,message:t,operationIndexes:r.map(l=>l.index).sort((l,s)=>l-s),target:n,...a,recovery:{action:o,sameArgumentsSafe:!1,requiresReinspection:!1,requiresUserAuthorization:!1,...i?{hint:i}:{}}}}function po(e,t=[],r={}){let n=Array.isArray(t)?t:[],o=r.strictTargets!==!1,a=new Ml(e),i={accepted:rr(e,{revisionView:"accepted"}),rejected:null},l=[],s=[];for(let h=0;h<n.length;h+=1){let v=n[h],w=Nr(v),y=w.operation||St(v),x={index:h+1,operationKind:y.operationKind,operationId:y.operationId,sourceIds:[],warnings:[]},b={...v},T=y.targetDescriptor?.occurrence!=null&&!y.targetDescriptor?.paragraphId&&!y.targetDescriptor?.fingerprint,A=typeof y.targetDescriptor?.text=="string"&&/\r|\n/.test(y.targetDescriptor.text)&&!y.targetEndDescriptor&&!Array.isArray(y.replacements);if((T||A)&&(x.dynamic=!0),w.valid&&y.operationKind!=="comment_reply"&&y.operationKind!=="comment_resolve"&&!y.targetDescriptor?.captureRef&&!x.dynamic)try{let E=kl(e,y.targetDescriptor,y.operationKind,o,i,{onInfo:r.onInfo,onWarn:S=>x.warnings.push(String(S))}),I=a.register(E.paragraph,E.metadata);if(x.sourceIds.push(I),x.resolvedBy=E.resolvedBy,x.resolvedTarget=E.metadata,b._compiledSourceId=I,b._compiledResolvedBy=E.resolvedBy,x.warnings.length>0&&(b._compiledWarnings=x.warnings),Array.isArray(y.replacements)){let S=yd(E.metadata.text,y.replacements);if(!S.ok)throw Object.assign(new Error(S.error.message),S.error);b.modified=S.desiredText,delete b.replacements,b._localizedReplacementCompilation={sourceText:E.metadata.text,desiredText:S.desiredText,replacements:S.replacements};let N=Nr(b);if(!N.valid)throw Object.assign(new Error(N.error.message),N.error)}else if(y.operationKind==="restore"&&v.modified===void 0){b.modified=E.metadata.text;let S=Nr(b);if(!S.valid)throw Object.assign(new Error(S.error.message),S.error)}let R=y.targetEndDescriptor||(y.targetEndRef!=null?Tn(null,y.targetEndRef,y.targetDescriptor.revisionView):null);if(R){let S=kl(e,R,y.operationKind,o,i,{onInfo:r.onInfo,onWarn:M=>x.warnings.push(String(M))}),N=a.register(S.paragraph,S.metadata);b._compiledSourceEndId=N;let O=se(e),C=O.indexOf(E.paragraph),P=O.indexOf(S.paragraph);if(C<0||P<C)throw Object.assign(new Error("Target range is not a forward contiguous paragraph range."),{code:"TARGET_RANGE_INVALID"});for(let M of O.slice(C,P+1)){let k=(i[y.targetDescriptor.revisionView]||i.accepted).byParagraph.get(M);x.sourceIds.push(a.register(M,k||{}))}x.sourceIds=[...new Set(x.sourceIds)],x.resolvedTargetEnd=S.metadata}if(y.operationKind==="list-format"&&y.list?.continueFrom&&typeof y.list.continueFrom=="object"){let S;try{S=kl(e,Tn(y.list.continueFrom,null,"accepted"),y.operationKind,o,i,{onInfo:r.onInfo,onWarn:N=>x.warnings.push(String(N))})}catch(N){throw Object.assign(N instanceof Error?N:new Error(String(N)),{field:"list.continueFrom"})}b._compiledContinueFromId=a.register(S.paragraph,S.metadata),x.resolvedContinueFrom=S.metadata}}catch(E){x.error=Ny(E)}l.push(x),s.push(b)}let c=new Set(s.map(h=>h?.captureKey).filter(Boolean)),f=1;for(let h of l){if(h.error?.code!=="TARGET_NOT_FOUND")continue;let v=h.index-1,y=St(n[v]).targetDescriptor?.text;if(!y)continue;let x=n.flatMap((E,I)=>I===v||typeof E?.modified!="string"?[]:E.modified.split(/\r?\n/).map(S=>S.trim()).filter(Boolean).includes(y.trim())?[{candidate:E,producerIndex:I}]:[]);if(x.length!==1)continue;let[{candidate:b,producerIndex:T}]=x,A=b.captureKey||s[T].captureKey;if(!A){do A=`__batch_created_${f++}`;while(c.has(A));c.add(A),s[T].captureKey=A}s[v].target={captureRef:A,select:y},delete s[v]._compiledSourceId,delete s[v]._compiledResolvedBy,delete h.error,h.sourceIds=[],h.resolvedBy="created_content_dependency",h.createdByOperation=T+1,h.captureRef=A}let u=new Map,d=new Map;for(let h of l)if(!(h.error||h.dynamic)){for(let v of h.sourceIds)u.has(v)||u.set(v,[]),u.get(v).push(h);if(h.operationKind==="list-format"){let v=s[h.index-1];for(let w of Iy(e,a,h,v)){let y=a.register(w,i.accepted.byParagraph.get(w)||{});h.sourceIds.includes(y)||((h.rebindSourceIds||(h.rebindSourceIds=[])).push(y),u.has(y)||u.set(y,[]),d.has(y)||d.set(y,[]),d.get(y).push(h))}}}let m=[],p=new Set,g=(h,v)=>{p.has(h)||(p.add(h),m.push(v))};for(let[h,v]of u){let w=d.get(h)||[],y=[...v,...w].filter(I=>Jd.has(I.operationKind)||Zd.has(I.operationKind)),x=y.filter(I=>I.operationKind==="list-format"),b=y.filter(I=>I.operationKind!=="list-format");if(x.length===1&&b.length===1&&b[0].operationKind==="redline"){let[I]=x,[R]=b,S=a.describe(h),N=by({operation:s[R.index-1]},R.resolvedTarget?.text??S?.text??"");if(N){let P=[R,I];g(`list:${P.map(M=>M.index).sort().join(",")}`,_i(Qd,`Operations ${P.map(M=>M.index).sort((M,_)=>M-_).join(", ")} combine a redline and a list-format on the same paragraph in a way that does not compose (${N.reason}).`,P,S,"split_text_and_list_changes",{reason:N.reason,...N.sourceMarker!==void 0?{sourceMarker:N.sourceMarker,modifiedMarker:N.modifiedMarker}:{}},N.hint));continue}let O=s[I.index-1],C=new Set(O._compiledRunAfter||[]);C.add(R.index-1),O._compiledRunAfter=[...C].sort((P,M)=>P-M),I.composedWith=[...new Set([...I.composedWith||[],R.index])],R.composedWith=[...new Set([...R.composedWith||[],I.index])];continue}if(w.length>0&&y.length>1){g(`rebind:${y.map(I=>I.index).sort().join(",")}`,_i(Qd,`Operation ${w.map(I=>I.index).join(", ")} (list-format, scope "list") rebinds this list item, and operations ${y.filter(I=>!w.includes(I)).map(I=>I.index).join(", ")} also write it.`,y,a.describe(h),"split_text_and_list_changes",{reason:"list-rebind",rebindingOperationIndexes:w.map(I=>I.index)},'A list-format with scope "list" rewrites every item of the list; in the same batch only one single-paragraph redline per item can compose with it. Send the other change in a separate apply, or use scope "range".'));continue}let T=v,A=T.filter(I=>Jd.has(I.operationKind)),E=T.filter(I=>Zd.has(I.operationKind));if(A.length>1){let I=`text:${A.map(R=>R.index).sort().join(",")}`;p.has(I)||(p.add(I),m.push(_i("OVERLAPPING_SOURCE_TARGETS",`Operations ${A.map(R=>R.index).join(", ")} contain incompatible text writes to the same batch-start source target.`,A,a.describe(h),"consolidate_operations")))}if(A.length>0&&E.length>0){let I=[...A,...E],R=`format:${I.map(S=>S.index).sort().join(",")}`;p.has(R)||(p.add(R),m.push(_i("REVISION_ORDER_CONFLICT",`Operations ${I.map(S=>S.index).join(", ")} combine text and formatting writes on the same batch-start source target.`,I,a.describe(h),"split_or_consolidate_operations")))}}return{valid:m.length===0&&l.every(h=>!h.error),compiledOperations:s,bindings:l,conflicts:m,registry:a}}function tm(e){return`${e?.source||""}${e?.severity||""}${e?.code||""}${e?.message||""}`}function An(e=[],t=[]){let r=new Map;for(let n of t||[]){let o=tm(n);r.set(o,(r.get(o)||0)+1)}return(e||[]).filter(n=>{let o=tm(n),a=r.get(o)||0;return a===0?!0:(r.set(o,a-1),!1)})}function En(e=[]){return(e||[]).filter(t=>t?.severity==="error")}var Ey="PARAGRAPH_FORMAT_REVISION_CONFLICT",Ry=new Set(["pPr","bookmarkStart","bookmarkEnd","proofErr","commentRangeStart","commentRangeEnd","permStart","permEnd"]),Py=new Set(["rPr","t","tab","br","cr","noBreakHyphen","softHyphen","lastRenderedPageBreak"]),Cy=new Set(["rPr","t","tab","lastRenderedPageBreak"]),da=(e,t=80)=>{let r=String(e??"");return r.length>t?`${r.slice(0,t)}...`:r},Ll=e=>String(e?.localName||e?.nodeName||"").replace(/^.*:/,""),Bl=e=>e?.getAttribute?.("w:val")??e?.getAttribute?.("val")??null;function de(e,t,r={},n=null){return{ok:!1,error:{code:e,message:t,...r,...n?{recovery:n}:{}}}}function Oi(e){let t=String(e||"");return t.trim()&&V(t,"application/xml")?.doc||null}function $l(e,t){if(!e)return null;let r=Array.from(e.getElementsByTagNameNS("*","style")).filter(a=>(a.getAttribute("w:type")??a.getAttribute("type"))==="paragraph"),n=new Map(r.map(a=>[a.getAttribute("w:styleId")??a.getAttribute("styleId"),a])),o=t?n.get(t):r.find(a=>["1","true","on"].includes(a.getAttribute("w:default")??a.getAttribute("default")));for(let a=0;o&&a<16;a+=1){let i=Qe(me(o,"pPr"),"numPr"),l=Bl(Qe(i,"numId"));if(l!=null)return l==="0"?null:{numId:l,styleId:o.getAttribute("w:styleId")??o.getAttribute("styleId")};o=n.get(Bl(me(o,"basedOn")))}return null}function _y(e,t,r){let n=[],o=0,a="";for(let i of Array.from(e.childNodes||[])){if(o>=t)break;if(i.nodeType!==1)continue;let l=Ll(i);if(F(i,"r")){let s=Vt(i),c=It(s);if(c===0){if(Array.from(i.childNodes||[]).some(p=>p.nodeType===1&&!Cy.has(Ll(p))))return{reason:"run-content"};continue}if(Array.from(i.childNodes||[]).filter(m=>m.nodeType===1).map(Ll).some(m=>!Py.has(m)))return{reason:"run-content"};let u=Math.min(t,o+c)-o,d=0;for(let m of s){if(d>=u)break;if(!F(m.node,"t")&&!F(m.node,"tab"))return{reason:"run-content"};d=m.end}n.push({run:i,start:o,end:o+c,pieces:s}),a+=s.map(m=>m.text).join(""),o+=c;continue}if(!Ry.has(l))return{reason:l==="ins"||l==="del"||l==="moveTo"||l==="moveFrom"?"tracked-change":"container"}}return o<t||a.slice(0,t)!==r?{reason:"text-mismatch"}:{segments:n}}function Oy(e,t,r,{author:n,generateRedlines:o,revisionIdAllocator:a}){for(let i of t){let{run:l,start:s,end:c,pieces:f}=i,u=Math.min(r,c)-s;if(u<=0)continue;let d=l.parentNode,m=me(l,"rPr");if(o){let p=Fr(e,Pt(e,f,0,u,!0),m);d.insertBefore(tr(e,"del",p,n),l)}if(u<c-s){let p=Fr(e,Pt(e,f,u,c-s,!1),m);o&&$t(p,a),d.insertBefore(p,l)}d.removeChild(l)}}function Fl(e,t){return t==null?!1:jt(e.documentElement).some(r=>Bl(r)===String(t))}function Dl(e){if(!e||typeof e!="object")return null;(!e.listFallbackSequenceState||typeof e.listFallbackSequenceState!="object")&&(e.listFallbackSequenceState={explicitByNumberingKey:new Map});let t=e.listFallbackSequenceState;return t.explicitByNumberingKey instanceof Map||(t.explicitByNumberingKey=new Map),t.explicitByNumberingKey}function Ul(e,t){if(e?.numberingIdState)return e.numberingIdState;let r=Ht(e?.numberingXml||t?.numberingXml||void 0);return e&&typeof e=="object"&&(e.numberingIdState=r),r}function Xl(e,t,r,n={}){let o=n.generateRedlines!==!1,a=n.author,i=typeof n.paragraphIndexOf=="function"?n.paragraphIndexOf:()=>null,l=Oi(n.stylesXml),s=r.strip==="none"?"none":"marker",c=[],f=[];for(let S of t){let N=i(S),O=Y(S,{revisionView:"accepted"}),C=Oe(S);if(C)return de(Ed,`Paragraph ${N??""} is already a list item (numId ${C.numId}, level ${C.ilvl}); convert-plain converts plain paragraphs only.`.replace(" "," "),{paragraphIndex:N,numId:C.numId,level:C.ilvl,targetExcerpt:da(O)},{action:"use_paragraph_numbering",hint:"Narrow the range to plain paragraphs. To move a list item to another existing list or level, use paragraph-format with properties.numbering."});let P=at(S),_=P.numPr?.numId==="0"?null:$l(l,P.pStyle);if(_)return de(Ai,`Paragraph ${N??""} is numbered by its style "${_.styleId}" (numId ${_.numId}); it is already a list item through the style.`.replace(" "," "),{paragraphIndex:N,styleId:_.styleId,numId:_.numId,targetExcerpt:da(O)},{action:"convert_in_host",hint:"Style-linked numbering is not rebound by list-format-v1. Change the paragraph style or the style's numbering in the host."});if(!O.trim()){f.push({paragraph:S,paragraphIndex:N,reason:"empty"});continue}if(s==="none"){c.push({paragraph:S,paragraphIndex:N,text:O,parsed:null});continue}let k=fo(O);if(k?.unsupported){let L={multilevel:'multi-level markers such as "2.1." need a multi-level list definition',parenthesized:'parenthesized markers such as "(a)" are not supported',zero:"a marker value of 0 cannot start a Word list"}[k.unsupported];return de(ua,`The typed marker "${k.marker}" is not supported by list-format-v1: ${L}.`,{reason:k.unsupported,marker:k.marker,paragraphIndex:N,targetExcerpt:da(O)},{action:"convert_in_host",hint:"Convert this paragraph in the host, or leave the marker as literal text."})}if(!k){f.push({paragraph:S,paragraphIndex:N,reason:"no-marker"});continue}c.push({paragraph:S,paragraphIndex:N,text:O,parsed:k})}if(c.length===0)return de(Sd,s==="marker"?'No target paragraph starts with a typed list marker (for example "A. ", "1. ", "iv. " or "- "), so there is nothing to strip.':"The target range has no non-empty paragraph to convert.",{targetExcerpt:da(f[0]?Y(f[0].paragraph):"")},{action:"change_request",hint:'Target the paragraphs that carry the typed markers, or pass strip: "none" with list.format to bind paragraphs whose text has no marker.',field:"list.strip",allowedValue:"none"});let u=r.format;if(s==="marker"){let S=kd(c.map(N=>N.parsed),r.format);if(S.error){let{reason:N}=S.error;if(N==="ambiguous")return de(Ad,`The typed marker "${S.error.marker}" reads as ${S.error.formats.join(" or ")}; list-format will not guess.`,{marker:S.error.marker,formats:S.error.formats},{action:"set_list_format",hint:`Pass list.format (${S.error.formats.join(" or ")}).`,field:"list.format",allowedValues:S.error.formats});let O=N==="format-mismatch"?`The typed marker "${S.error.marker}" is not a ${S.error.requestedFormat} marker.`:`The target range mixes list markers (${[...new Set(S.error.markers)].join(", ")}); one convert-plain operation converts one list format.`;return de(ua,O,{reason:N,...S.error.marker?{marker:S.error.marker}:{},...S.error.markers?{markers:S.error.markers}:{}},{action:"change_request",hint:N==="format-mismatch"?"Omit list.format to use the typed marker, or correct it.":"Split the range into one operation per marker format."})}u=S.format}if(r.kind&&r.kind==="bullet"!=(u==="bullet"))return de(ua,`The typed markers are ${u} markers, not a ${r.kind} list.`,{reason:"format-mismatch",requestedKind:r.kind},{action:"change_request",hint:"Omit list.kind, or target paragraphs whose markers match it."});let d=s==="marker"?c[0].parsed.terminator:".",m=s==="marker"&&c[0].parsed.bulletChar||null,p=r.level||0;for(let S of c){let N=Qe(me(S.paragraph,"pPr"),"pPrChange"),O=N?.getAttribute("w:author")??N?.getAttribute("author")??"";if(o&&N&&O!==a)return de(Ey,`Paragraph ${S.paragraphIndex??""} already has a pending paragraph-property change by "${O||"unattributed"}". Overwriting its snapshot would change what Reject All restores.`.replace(" "," "),{pendingAuthor:O,paragraphIndex:S.paragraphIndex},{action:"resolve_pending_revision",hint:"Ask the user to accept or reject the existing paragraph formatting change first; this tool does not resolve revisions by other reviewers."});if(S.keepSnapshot=!!N,s==="marker"){let C=_y(S.paragraph,S.parsed.prefixLength,S.text.slice(0,S.parsed.prefixLength));if(C.reason)return de(ua,`The typed marker "${S.parsed.marker}" is not plain run text (${C.reason}), so it cannot be stripped as one tracked deletion.`,{reason:"marker-shape",shape:C.reason,marker:S.parsed.marker,paragraphIndex:S.paragraphIndex,targetExcerpt:da(S.text)},{action:"convert_in_host",hint:"The marker sits inside a hyperlink, field, content control or pending revision. Resolve that markup first or convert the paragraph in the host."});S.segments=C.segments}}let g=Dl(n.runtimeContext),h=Bd({format:u,level:p,terminator:d,bulletChar:m}),v=g?.get(h)||null,w=v&&Fl(e,v.numId),y=s==="none"?r.start??(w&&Number.isInteger(v.nextStartAt)?v.nextStartAt:1):null;for(let S of c)u==="bullet"?S.value=null:s==="marker"?S.value=Md(S.parsed,u):S.value=y++;let x=Ul(n.runtimeContext,n),b=Ld({format:u,level:p,terminator:d,bulletChar:m}),T=[],A=[],E=null,I=null;for(let[S,N]of c.entries()){if(!(S>0&&(u==="bullet"||N.value===I+1)))if(S===0&&w&&(u==="bullet"||v.nextStartAt===N.value))E=String(v.numId);else{let P=qo({numberingIdState:x,levels:[b],startOverrides:N.value!=null&&N.value!==1?{[p]:N.value}:void 0});if(!P)return de("NUMBERING_ID_EXHAUSTED","No numbering ids are available for a new list definition.",{},{action:"report_library_failure"});E=String(P.numId),A.push(P.numId),T.push(P.numberingXml)}N.numId=E,I=N.value}for(let S of c){let N=me(S.paragraph,"pPr");N||(N=$(e,"w:pPr"),S.paragraph.insertBefore(N,S.paragraph.firstChild)),o&&!S.keepSnapshot&&Hn(e,N,a),Kn(e,N,{numbering:{numId:S.numId,level:p}}),s==="marker"&&Oy(e,S.segments,S.parsed.prefixLength,{author:a,generateRedlines:o,revisionIdAllocator:n.revisionIdAllocator||null})}let R=c[c.length-1];return g?.set(h,{numId:R.numId,nextStartAt:R.value!=null?R.value+1:null}),{ok:!0,format:u,level:p,strip:s,items:c.map(S=>({paragraph:S.paragraph,paragraphIndex:S.paragraphIndex,marker:S.parsed?.marker??null,value:S.value,numId:S.numId})),skipped:f,numberingXml:T.length>0?vr("",T):null,allocatedNumIds:A}}var rm="http://schemas.openxmlformats.org/wordprocessingml/2006/main",ky="PARAGRAPH_FORMAT_REVISION_CONFLICT",jl=8,Vl=(e,t=80)=>{let r=String(e??"");return r.length>t?`${r.slice(0,t)}...`:r},go=e=>e?.getAttribute?.("w:val")??e?.getAttribute?.("val")??null,Pn=(e,t="val")=>{let r=e?.getAttribute?.(`w:${t}`)??e?.getAttribute?.(t),n=Number.parseInt(String(r??""),10);return Number.isFinite(n)?n:null},Rn=e=>e==="bullet";function nm(e){let t=String(e||""),r=t.trim()?V(t,"application/xml")?.doc:null,n=new Map,o=new Map;if(!r)return{nums:n,abstracts:o};for(let a of Array.from(r.getElementsByTagNameNS("*","abstractNum"))){let i=Pn(a,"abstractNumId");i!=null&&!o.has(String(i))&&o.set(String(i),a)}for(let a of Array.from(r.getElementsByTagNameNS("*","num"))){let i=Pn(a,"numId");if(i==null||n.has(String(i)))continue;let l=new Map,s=new Set;for(let c of Zi(a,"lvlOverride")){let f=Pn(c,"ilvl")??0,u=Pn(me(c,"startOverride"));u!=null&&l.set(f,u),me(c,"lvl")&&s.add(f)}n.set(String(i),{element:a,abstractId:String(Pn(me(a,"abstractNumId"))??""),startOverrides:l,levelOverrides:s})}return{nums:n,abstracts:o}}function My(e,t){let r=e.nums.get(String(t));if(!r)return{reason:"missing"};let n=e.abstracts.get(r.abstractId);if(!n)return{reason:"missing"};let o=new Map;for(let l of Zi(n,"lvl")){let s=Pn(l,"ilvl")??0;o.set(s,{numFmt:go(me(l,"numFmt"))||"decimal",lvlText:go(me(l,"lvlText"))??"",start:Pn(me(l,"start"))??0,restart:!!me(l,"lvlRestart"),pStyle:go(me(l,"pStyle"))})}let a=go(me(n,"numStyleLink"))||go(me(n,"styleLink")),i=[...o.values()].map(l=>l.pStyle).filter(Boolean);return{numId:String(t),num:r,abstract:n,abstractId:r.abstractId,levels:o,styleLink:a||null,levelStyles:i,startOf:l=>r.startOverrides.has(l)?r.startOverrides.get(l):o.get(l)?.start??0}}function Ly(e,t){if(!e)return[];let r=[];for(let n of Array.from(e.getElementsByTagNameNS("*","style"))){let o=go(Qe(Qe(me(n,"pPr"),"numPr"),"numId"));o!=null&&t.has(String(o))&&r.push(n.getAttribute("w:styleId")??n.getAttribute("styleId"))}return r}function Gl(e,t){let r=[];for(let n of Array.from(e.getElementsByTagNameNS(rm,"p"))){let o=Oe(n);!o||o.numId!==String(t)||r.push({paragraph:n,ilvl:o.ilvl,deleted:kt(n),inTextbox:By(n,"txbxContent")})}return r}function By(e,t){for(let r=e?.parentNode;r&&r.nodeType===1;r=r.parentNode)if(r.localName===t)return!0;return!1}function $y(e,t,r){return[...t.nums.entries()].filter(([o,a])=>o!==r.numId&&a.abstractId===r.abstractId).map(([o])=>o).filter(o=>Gl(e,o).some(a=>!a.deleted))}function zl(e,t,r=[]){let n=Array.from({length:jl+1},(a,i)=>r[i]??null),o=[];for(let a of e){for(let i=0;i<a;i+=1)n[i]==null&&(n[i]=t(i));n[a]=n[a]==null?t(a):n[a]+1;for(let i=a+1;i<=jl;i+=1)n[i]=null;o.push(n.slice(0,a+1))}return{values:o,counters:n}}function om(e,{stylesDoc:t,indexOf:r,mode:n}){let o=[],a=[],i=[];for(let s of e){let c=r(s);if(kt(s)){a.push({paragraph:s,paragraphIndex:c,reason:"tracked-deleted"});continue}let f=Oe(s);if(f){o.push({paragraph:s,paragraphIndex:c,ilvl:f.ilvl,numId:f.numId});continue}let u=at(s),d=u.numPr?.numId==="0"?null:$l(t,u.pStyle);if(d)return de(Ai,`Paragraph ${c??""} is numbered by its style "${d.styleId}" (numId ${d.numId}), not by a direct list binding; ${n} rebinds direct list items only.`.replace(" "," "),{paragraphIndex:c,styleId:d.styleId,numId:d.numId,targetExcerpt:Vl(Y(s))},{action:"convert_in_host",hint:"Style-linked numbering is not rebound by list-format. Change the style's numbering in the host."});i.push({paragraph:s,paragraphIndex:c})}if(o.length===0)return de(Rd,`The target range has no list item; ${n} changes existing lists.`,{paragraphIndexes:i.map(s=>s.paragraphIndex),targetExcerpt:Vl(i[0]?Y(i[0].paragraph):"")},{action:"use_list_format_convert_plain",hint:"To turn plain paragraphs into a list use list-format convert-plain (typed markers) or paragraph-format numbering (an existing list)."});if(i.length>0)return de(Ei,`The target range mixes list items and paragraphs that are not list items (paragraphs ${i.map(s=>s.paragraphIndex).join(", ")}).`,{reason:"non-list",paragraphIndexes:i.map(s=>s.paragraphIndex)},{action:"narrow_range",hint:'Target only list items: one paragraph of the list is enough with scope "list".'});let l=[...new Set(o.map(s=>s.numId))];return l.length>1?de(Ei,`The target range spans ${l.length} lists (numIds ${l.join(", ")}); one ${n} operation changes one list.`,{reason:"several-lists",numIds:l,paragraphIndexes:o.filter(s=>s.numId!==o[0].numId).map(s=>s.paragraphIndex)},{action:"narrow_range",hint:"Send one operation per list."}):{ok:!0,numId:l[0],items:o,skipped:a}}function Wl(e,t,r,{stylesDoc:n,role:o}){let a=My(t,r);if(a.reason==="missing")return de(Nn,`numId ${r} (${o}) has no numbering definition in the numbering part, so its levels cannot be read.`,{reason:"missing",numId:String(r)},{action:"inspect_numbering",hint:"Bare document.xml callers must pass the package's word/numbering.xml as numberingXml."});if(a.num.levelOverrides.size>0)return de(Nn,`numId ${r} (${o}) redefines level ${[...a.num.levelOverrides].join(", ")} inside its w:num (w:lvlOverride/w:lvl); list-format does not rebind such instance-level definitions.`,{reason:"level-override",numId:String(r),levels:[...a.num.levelOverrides]},{action:"convert_in_host",hint:"Change this list in the host."});let i=Ly(n,new Set([String(r),...[...t.nums.entries()].filter(([,s])=>s.abstractId===a.abstractId).map(([s])=>s)]));if(a.styleLink||a.levelStyles.length>0||i.length>0){let s=[...new Set([a.styleLink,...a.levelStyles,...i].filter(Boolean))];return de(Pd,`numId ${r} (${o}) is style-linked (${s.map(c=>`"${c}"`).join(", ")}): paragraphs can join it through a style without a direct binding, so rebinding the direct items would split the list unpredictably.`,{numId:String(r),styleIds:s},{action:"convert_in_host",hint:"Style-linked lists (heading numbering, list styles) are not changed by list-format. Change the numbering of the style in the host."})}let l=$y(e,t,a);return l.length>0?de(uo,`numId ${r} (${o}) shares its abstract definition ${a.abstractId} with numIds ${l.join(", ")}, which Word numbers as one continuous list; rebinding one of them would renumber the others.`,{reason:"shared-definition",numId:String(r),sharedNumIds:l},{action:"convert_in_host",hint:"Change these lists together in the host, or restart the other list first."}):a.num.element&&[...a.levels.keys()].length===0?de(Nn,`numId ${r} (${o}) has no levels.`,{reason:"undefined-level",numId:String(r)},{action:"convert_in_host"}):{ok:!0,definition:a}}function am(e,t,r,n,o,a){let l=Gl(e,t).filter(d=>!d.deleted),s=l.find(d=>d.inTextbox);if(s)return de(uo,`numId ${t} has a list item inside a text box (paragraph ${o(s.paragraph)??"?"}); list-format changes body lists only.`,{reason:"textbox-member",numId:String(t)},{action:"convert_in_host",hint:"Change this list in the host."});let c=new Set(r.map(d=>d.paragraph));if(n==="list")return{ok:!0,rebind:l.map(d=>({...d,paragraphIndex:o(d.paragraph),inTarget:c.has(d.paragraph)})),preceding:[]};let f=l.findIndex(d=>c.has(d.paragraph)),u=l.slice(f).filter(d=>!c.has(d.paragraph));if(u.length>0){let d=o(l[l.length-1].paragraph);return de(uo,`scope "range" would split numId ${t} mid-sequence: ${u.length} later item(s) of the list (paragraphs ${u.map(m=>o(m.paragraph)).join(", ")}) would stay on the source list and renumber.`,{reason:"mid-sequence",numId:String(t),followingParagraphIndexes:u.map(m=>o(m.paragraph)),lastListParagraphIndex:d},{action:"extend_range_or_use_list_scope",hint:`Extend targetEnd to the last item of the list (paragraph ${d}), or use scope "list" to ${a==="join"?"join":"change"} the whole list.`})}return{ok:!0,rebind:l.slice(f).map(d=>({...d,paragraphIndex:o(d.paragraph),inTarget:!0})),preceding:l.slice(0,f)}}function im(e,{author:t,generateRedlines:r}){let n=e.filter(o=>!o.inTarget);if(!r&&n.length>0)return de("INVALID_OPERATION",`An untracked (generateRedlines: false) list-format would rebind ${n.length} paragraph(s) outside the target (paragraphs ${n.map(o=>o.paragraphIndex).join(", ")}); untracked edits stay inside their target.`,{field:"generateRedlines",paragraphIndexes:n.map(o=>o.paragraphIndex)},{action:"change_request",hint:"Keep tracking on, or target the whole list with target..targetEnd."});for(let o of e){let a=Qe(me(o.paragraph,"pPr"),"pPrChange"),i=a?.getAttribute("w:author")??a?.getAttribute("author")??"";if(r&&a&&i!==t)return de(ky,`Paragraph ${o.paragraphIndex??""} of the list already has a pending paragraph-property change by "${i||"unattributed"}". Overwriting its snapshot would change what Reject All restores.`.replace(" "," "),{pendingAuthor:i,paragraphIndex:o.paragraphIndex},{action:"resolve_pending_revision",hint:"Ask the user to accept or reject the existing paragraph formatting change first; this tool does not resolve revisions by other reviewers."});o.keepSnapshot=!!a}return{ok:!0}}function sm(e,t,r,{author:n,generateRedlines:o}){for(let a of t){let i=me(a.paragraph,"pPr");i||(i=$(e,"w:pPr"),a.paragraph.insertBefore(i,a.paragraph.firstChild)),o&&!a.keepSnapshot&&Hn(e,i,n),Kn(e,i,{numbering:{numId:r,level:a.ilvl}}),a.numId=String(r)}}var Kl=(e,t={})=>({ok:!0,unchanged:!0,message:e,...t});function lm(e,t,r,n={}){let o=n.generateRedlines!==!1,a=n.author,i=typeof n.paragraphIndexOf=="function"?n.paragraphIndexOf:()=>null,l=Oi(n.stylesXml),s=nm(n.numberingXml),c=r.scope==="range"?"range":"list",f=om(t,{stylesDoc:l,indexOf:i,mode:"change-format"});if(!f.ok)return f;let u=Wl(e,s,f.numId,{stylesDoc:l,role:"the target list"});if(!u.ok)return u;let{definition:d}=u,m=[...new Set(f.items.map(O=>O.ilvl))].sort((O,C)=>O-C);if(r.explicitLevel==null&&m.length>1)return de(Ei,`The target paragraphs use list levels ${m.join(", ")}; change-format redefines one level per operation.`,{reason:"levels",levels:m},{action:"set_list_level",hint:"Pass list.level, or target paragraphs of one level.",field:"list.level",allowedValues:m});let p=r.explicitLevel??m[0],g=d.levels.get(p);if(!g)return de(Nn,`numId ${f.numId} does not define list level ${p}.`,{reason:"undefined-level",numId:f.numId,level:p},{action:"set_list_level",field:"list.level",allowedValues:[...d.levels.keys()]});let h=r.format??(r.kind==="bullet"?"bullet":g.numFmt),v=Rn(g.numFmt)!==Rn(h),w=r.lvlText??(v?Rn(h)?"\u2022":`%${p+1}.`:g.lvlText),y=Rl(w,{bullet:Rn(h),level:p});if(y)return de("INVALID_OPERATION",`${y} (level ${p}, format ${h})`,{field:"list.lvlText"},{action:"change_request",hint:Rn(h)?"Pass the bullet character as list.lvlText.":`Pass list.lvlText with %${p+1}, for example "%${p+1}."`});let x=am(e,f.numId,f.items,c,i,"change-format");if(!x.ok)return x;let b=O=>d.levels.get(O)?.start??0,T=new Map;for(let O=0;O<=jl;O+=1)T.set(O,d.startOf(O));if(c==="range"&&x.preceding.length>0){if([...x.preceding,...x.rebind].some(L=>d.levels.get(L.ilvl)?.restart))return de(Nn,`numId ${f.numId} uses w:lvlRestart, so the count a split would continue cannot be computed exactly.`,{reason:"level-restart",numId:f.numId},{action:"extend_range_or_use_list_scope",hint:'Use scope "list".'});let C=zl(x.preceding.map(L=>L.ilvl),d.startOf),P=x.rebind[0].ilvl;for(let L=0;L<P;L+=1)T.set(L,C.counters[L]??d.startOf(L));T.set(P,C.counters[P]==null?d.startOf(P):C.counters[P]+1);let M=zl(x.rebind.map(L=>L.ilvl),d.startOf,C.counters).values,k=zl(x.rebind.map(L=>L.ilvl),L=>T.get(L)).values.findIndex((L,D)=>JSON.stringify(L)!==JSON.stringify(M[D]));if(k>=0)return de(uo,`scope "range" cannot continue the count of numId ${f.numId} exactly: a level whose start must change restarts inside the range (paragraph ${x.rebind[k].paragraphIndex??"?"}), and Word applies a level start again on every restart.`,{reason:"nested-restart",numId:f.numId,paragraphIndex:x.rebind[k].paragraphIndex},{action:"extend_range_or_use_list_scope",hint:'Start the range at a top-level item of the list, or use scope "list".'})}if(r.start!=null&&T.set(p,r.start),!x.rebind.some(O=>O.ilvl===p))return Kl(`No paragraph of the ${c==="list"?"list":"range"} uses level ${p}; nothing would change.`,{level:p,sourceNumId:f.numId});let A=r.start!=null&&r.start!==d.startOf(p);if(h===g.numFmt&&w===g.lvlText&&!A)return Kl(`numId ${f.numId} level ${p} already has format ${h} with level text "${w}".`,{level:p,sourceNumId:f.numId});let E=im(x.rebind,{author:a,generateRedlines:o});if(!E.ok)return E;let I={};for(let[O,C]of T)C!==b(O)&&(I[O]=C);let R=new Map(Object.entries(I).map(([O,C])=>[Number(O),{ilvl:Number(O),start:C}]));R.set(p,{...R.get(p)||{},ilvl:p,numFmt:h,lvlText:w,...h!==g.numFmt?{dropChildren:v&&!Rn(h)?["isLgl","lvlPicBulletId","legacy"]:["isLgl"]}:{},...v&&!Rn(h)?{dropRunFonts:!0}:{}});let S=Ul(n.runtimeContext,n),N=qo({numberingIdState:S,sourceNumberingXml:n.numberingXml,sourceNumId:f.numId,levels:[...R.values()]});return N?(sm(e,x.rebind,N.numId,{author:a,generateRedlines:o}),{ok:!0,mode:"change-format",scope:c,format:h,level:p,lvlText:w,sourceNumId:f.numId,numId:String(N.numId),levelStarts:I,items:x.rebind.map(O=>({paragraph:O.paragraph,paragraphIndex:O.paragraphIndex,level:O.ilvl,numId:O.numId,sourceNumId:f.numId,inTarget:O.inTarget})),skipped:f.skipped,numberingXml:vr("",[N.numberingXml]),allocatedNumIds:[N.numId]}):de("NUMBERING_ID_EXHAUSTED","No numbering ids are available for a new list definition.",{},{action:"report_library_failure"})}function cm(e,t,r,n,o={}){let a=o.generateRedlines!==!1,i=o.author,l=typeof o.paragraphIndexOf=="function"?o.paragraphIndexOf:()=>null,s=Oi(o.stylesXml),c=nm(o.numberingXml),f=n.scope==="range"?"range":"list",u=l(r),d=Oe(r);if(!d||kt(r))return de(Ri,`list.continueFrom (paragraph ${u??"?"}) is ${d?"a tracked-deleted paragraph":"not a list item"}; join continues an existing list.`,{reason:d?"deleted":"not-a-list",paragraphIndex:u,targetExcerpt:Vl(Y(r))},{action:"change_request",hint:"Point list.continueFrom at a live item of the list the target should continue.",field:"list.continueFrom"});if(t.includes(r))return de(Ri,"list.continueFrom is inside the target range; it must be an item of an earlier list.",{reason:"inside-target",paragraphIndex:u},{action:"change_request",field:"list.continueFrom"});let m=om(t,{stylesDoc:s,indexOf:l,mode:"join"});if(!m.ok)return m;if(m.numId===d.numId)return Kl(`The target already belongs to the list of list.continueFrom (numId ${m.numId}).`,{sourceNumId:m.numId});let p=Wl(e,c,m.numId,{stylesDoc:s,role:"the target list"});if(!p.ok)return p;let g=Wl(e,c,d.numId,{stylesDoc:s,role:"the list.continueFrom list"});if(!g.ok)return g;let h=am(e,m.numId,m.items,f,l,"join");if(!h.ok)return h;let v=Array.from(e.getElementsByTagNameNS(rm,"p")),w=v.indexOf(h.rebind[0].paragraph),x=Gl(e,d.numId).filter(A=>!A.deleted).filter(A=>v.indexOf(A.paragraph)>w);if(x.length>0){let A=v.indexOf(r)>w?"after-target":"interleaved";return de(A==="after-target"?Ri:uo,A==="after-target"?"list.continueFrom comes after the target; join continues an earlier list.":`The list of list.continueFrom (numId ${d.numId}) has items after the joined paragraphs (paragraphs ${x.map(E=>l(E.paragraph)).join(", ")}); they would renumber.`,{reason:A,numId:d.numId,paragraphIndexes:x.map(E=>l(E.paragraph))},{action:"change_request",hint:"Join a list to the list that immediately precedes it.",field:"list.continueFrom"})}let b=h.rebind.find(A=>!g.definition.levels.has(A.ilvl));if(b)return de(Nn,`numId ${d.numId} (the list.continueFrom list) does not define level ${b.ilvl}, which paragraph ${b.paragraphIndex??"?"} uses.`,{reason:"undefined-level",numId:d.numId,level:b.ilvl},{action:"convert_in_host"});let T=im(h.rebind,{author:i,generateRedlines:a});return T.ok?(sm(e,h.rebind,d.numId,{author:i,generateRedlines:a}),{ok:!0,mode:"join",scope:f,sourceNumId:m.numId,numId:d.numId,continueFrom:{paragraphIndex:u,numId:d.numId},items:h.rebind.map(A=>({paragraph:A.paragraph,paragraphIndex:A.paragraphIndex,level:A.ilvl,numId:A.numId,sourceNumId:m.numId,inTarget:A.inTarget})),skipped:m.skipped,numberingXml:null,allocatedNumIds:[]}):T}var Fy=/^(\s*)((?:\d+(?:\.\d+)*\.?|\((?:\d+|[a-zA-Z]|[ivxlcIVXLC]+)\)|[a-zA-Z]\.|[ivxlcIVXLC]+\.|[-*+\u2022]))\s+(.*)$/,um=/(?:^|\s)(?:\d+(?:\.\d+)*\.?|[A-Za-z]\.|[ivxlcIVXLC]+\.)\s+/g;function Dy(e){let t=String(e||"").trim();if(!/^\d+(?:\.\d+)+\.?$/.test(t))return null;let r=t.replace(/\.$/,"").split(".");return Math.max(0,r.length-1)}function Uy(e){let t=String(e||"").split(/\r?\n/g).map(n=>n.trimEnd()).filter(n=>n.trim().length>0);if(t.length<2)return null;let r=[];for(let n of t){let o=n.match(Fy);if(!o)return null;let a=o[2],i=/^[-*+\u2022]$/.test(a)?"bullet":"numbered";r.push({marker:a,markerType:i,level:Math.floor((o[1]||"").length/2),outlineLevel:i==="numbered"?Dy(a):null,text:un(o[3])})}return r.length>=2?r:null}function fm(e,t){if(!Array.isArray(e)||e.length===0)return null;let r=Uy(t);if(!r)return null;let n=e.map(d=>q(_e(d))),o=r.map(d=>q(d.text));if(n.some(d=>!d)||o.some(d=>!d))return null;let a=e.map(d=>Oe(d));if(a.some(d=>!d||!d.numId))return null;let i=String(a[0].numId);if(a.some(d=>String(d.numId)!==i))return null;let l=[],s=0;for(let d=0;d<o.length&&s<n.length;d+=1)o[d]===n[s]&&(l.push({originalIndex:s,modifiedIndex:d}),s+=1);if(s!==n.length)return null;let c=new Set(l.map(d=>d.modifiedIndex)),f=[];for(let d=0;d<r.length;d+=1)c.has(d)||f.push(d);if(f.length===0)return null;let u=r[0]?.level||0;return f.map(d=>{let m=l.find(x=>x.modifiedIndex>d)||null,p=[...l].reverse().find(x=>x.modifiedIndex<d)||null,g=m||p;if(!g)return null;let h=a[g.originalIndex]||a[0];if(!h)return null;let v=r[d],w=Math.max(0,v.level-u),y=Number.isInteger(v.outlineLevel)?v.outlineLevel:null;return{text:v.text,markerType:v.markerType,ilvl:y??Math.max(0,(h.ilvl||0)+w),numId:String(h.numId),insertBeforeOriginalIndex:m?m.originalIndex:null}}).filter(Boolean)}function Xy(e){return String(e||"").trim().split(/\s+/).filter(Boolean).length}function zy(e){let t=String(e||"");if(!t)return!1;let r=0,n=new RegExp(um.source,um.flags);for(;n.exec(t);)if(r+=1,r>=2)return!0;return!1}function dm(e,t){let r=String(e||"").trim(),n=String(t||"").trim();if(!r||!n||n===r||n.includes(`
|
|
218
|
+
`))return null;let o=q(r),a=s=>un(String(s||"").trim()).trim(),i=(s,c)=>{let f=a(c),u=q(f);return!f||f===r||Xy(f)<6||zy(f)||o&&u.includes(o)?null:{position:s,text:f}};if(n.endsWith(r)){let s=i("before",n.slice(0,-r.length));if(s)return s}if(n.startsWith(r)){let s=i("after",n.slice(r.length));if(s)return s}let l=q(n);if(!o||o===l)return null;if(l.endsWith(o)){let s=i("before",l.slice(0,-o.length));if(s)return s}if(l.startsWith(o)){let s=i("after",l.slice(o.length));if(s)return s}return null}function mm(e,t){let r=String(e||"").trim(),n=String(t||"");if(!r||!n||!n.includes(`
|
|
219
|
+
`))return null;let o=n.split(/\r?\n/g).map(l=>String(l||"").trim()).filter(Boolean);if(o.length<2)return null;let a=l=>q(String(l||"")),i=a(r);if(a(o[o.length-1])===i){let l=o.slice(0,-1).filter(Boolean);if(l.length>0)return{position:"before",paragraphs:l}}if(a(o[0])===i){let l=o.slice(1).filter(Boolean);if(l.length>0)return{position:"after",paragraphs:l}}return null}function pm(e){let t=String(e||"").split(/\r?\n/g).map(a=>a.trimEnd()).filter(a=>a.trim().length>0);if(t.length<3||t.findIndex(a=>a.trim().startsWith("|"))!==1)return null;let n=t.slice(1);if(!n.every(a=>a.trim().startsWith("|")))return null;let o=n[1].replace(/\s+/g,"");return/^\|:?-{3,}:?(?:(\|:?-{3,}:?)+\|?|\|)$/.test(o)?{paragraphMarkdown:t[0].trim(),tableText:n.join(`
|
|
220
|
+
`)}:null}function Tr(e,t){let r=new Error(t);return r.code=e,r}function gm(e,t,r){let n=[],o=!1,a=!1;for(let m of r||[])m&&(m.localName==="tbl"?(o=!0,n.push(...Array.from(m.getElementsByTagNameNS(B,"p")))):m.localName==="p"&&(at(m).numPr&&(a=!0),n.push(m)));let i=o?"table":a?"list":n.length>1?"range":"paragraph",l=[],s=[],c=[],f=[],u=e.document,d=se(u);for(let m of n){let p=He(m)||"";l.push(p);let g=Y(m);c.push(g);let h=d.indexOf(m)+1;s.push(Ot(m,{text:g,paragraphId:p||null,index:h>0?h:void 0,inTable:o||!!ct(m,"tbl")}));let v=m.parentNode?.localName||"body";f.push(`${v}/${m.localName}`)}return{captureKey:t.captureKey,operationIndex:typeof t.index=="number"?t.index:0,kind:i,generatedParagraphIds:l,fingerprints:s,expectedText:c,structuralPathHints:f,stale:!1}}function hm(e,t){if(!e||!(e instanceof Map)||!Array.isArray(t)||t.length===0)return;let r=new Set;for(let n of t)if(n){if(n.localName==="p"){let o=He(n);o&&r.add(o)}else if(typeof n.getElementsByTagNameNS=="function")for(let o of Array.from(n.getElementsByTagNameNS(B,"p"))){let a=He(o);a&&r.add(a)}}if(r.size!==0)for(let[,n]of e)n.stale||n.generatedParagraphIds.some(o=>o&&r.has(o))&&(n.stale=!0)}function wm(e,t,r,n="redline",o={}){let a=r?.captureRef;if(!a)throw Tr("INVALID_OPERATION","Operation target is missing captureRef.");if(!t||!t.captureTable||!t.captureTable.has(a))throw Tr("CAPTURE_NOT_FOUND",`Capture "${a}" was not found in the session capture table.`);let i=t.captureTable.get(a);if(i.stale)throw Tr("CAPTURE_STALE",`Capture "${a}" is stale; the captured content was modified or removed.`);let l=t.getParagraphMetadataIndex(),s=[];for(let d=0;d<i.expectedText.length;d++){let m=i.generatedParagraphIds[d],p=i.expectedText[d],g=null;if(m&&l.byId.has(m)&&(g=l.byId.get(m).paragraph),!g){let v=l.entries.find(w=>w.text===p||w.fingerprint===i.fingerprints[d]);v&&(g=v.paragraph)}if(!g||!g.parentNode)throw i.stale=!0,Tr("CAPTURE_STALE",`Capture "${a}" is stale; paragraph ${d+1} was removed from the document.`);let h=Y(g);if(h!==p)throw i.stale=!0,Tr("CAPTURE_STALE",`Capture "${a}" is stale; paragraph ${d+1} content drifted from "${p}" to "${h}".`);s.push(g)}if(s.length===0)throw i.stale=!0,Tr("CAPTURE_STALE",`Capture "${a}" is stale; no live paragraphs found.`);let c=r.select;if(c==null||c===""){if(s.length===1)return{paragraph:s[0],resolvedBy:"capture"};throw Tr("AMBIGUOUS_CAPTURE_SELECTION",`Capture "${a}" contains ${s.length} paragraphs; target.select is required to disambiguate.`)}let f=[],u=String(c).trim();if(u===":first"||u==="first")f=[s[0]];else if(u===":last"||u==="last")f=[s[s.length-1]];else if(/^\d+$/.test(u)){let d=parseInt(u,10);d>=1&&d<=s.length&&(f=[s[d-1]])}else{let d=s.filter(m=>Y(m).trim()===u);d.length>0?f=d:f=s.filter(m=>Y(m).includes(u))}if(f.length===0)throw Tr("TARGET_NOT_FOUND",`Target selection "${c}" was not found in capture "${a}".`);if(f.length>1)throw Tr("AMBIGUOUS_CAPTURE_SELECTION",`Target selection "${c}" matched ${f.length} paragraphs in capture "${a}".`);return{paragraph:f[0],resolvedBy:"capture"}}var ce="http://schemas.openxmlformats.org/wordprocessingml/2006/main",ma="http://schemas.microsoft.com/office/word/2010/wordml";function vm(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of Array.from(e?.getElementsByTagNameNS?.(ce,r)||[])){let o=n.getAttribute("w:id")||n.getAttribute("id");o!==""&&t.add(o)}return Array.from(t).sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function ym(e,t){return!t||typeof t!="object"?[]:e.map(r=>t[r]).filter(Boolean)}function Kr(e,t={}){let r=t?._documentOperationSession||null;return r?.valid&&r.document?{xmlDoc:r.document,serializer:r.serializer,operationSession:r}:{xmlDoc:V(e,"application/xml").doc,serializer:le(),operationSession:null}}function nt(e,t,r,n){return n?r:t.serializeToString(e)}async function wo(e,t,r,n={}){let o=await Do(e,t,r,n);return o?.useNativeApi&&typeof o?.oxml!="string"?Ce({...o,oxml:e,hasChanges:!1,warnings:[...Array.isArray(o?.warnings)?o.warnings:[],"Standalone mode cannot execute native Word API fallback for this operation."]}):o}async function jy(e,t,r,n={}){let o=typeof e=="string"?e:"",a=typeof r=="string"?r:String(r||""),i;try{i=xt(a)}catch{i={headers:[],rows:[]}}return(i?.headers?.length||0)>0||(i?.rows?.length||0)>0?{...await wo(o,t||"",a,n),isMarkdownTable:!0,tableData:i}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}function ho(e){return _e(e)}function xm(e,t=96){let r=String(e??"");return(r.length>t?`${r.slice(0,t)}\u2026`:r).replace(/\\/g,"\\\\").replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t").replace(/\u00a0/g,"\\u00A0").replace(/\u202f/g,"\\u202F").replace(/\u2060/g,"\\u2060")}function ki(e,t){return t>=e.length?"END":`U+${e.codePointAt(t).toString(16).toUpperCase().padStart(4,"0")}`}function Vy(e,t){let r=String(e??""),n=String(t??"");if(r===n)return{mode:"exact"};let o=[],a=Math.min(r.length,n.length);for(let l=0;l<a&&o.length<8;l++)r[l]!==n[l]&&o.push({offset:l,sourceCodePoint:ki(r,l),requestedCodePoint:ki(n,l)});return r.length!==n.length&&o.length<8&&o.push({offset:a,sourceCodePoint:ki(r,a),requestedCodePoint:ki(n,a)}),{mode:r.length===n.length&&r.replace(/\u00a0/g," ")===n.replace(/\u00a0/g," ")?"space_equivalent":"normalized",differences:o,sourceExcerpt:xm(r),requestedExcerpt:xm(n)}}function Hl(e,t,r,n,o){let a=o?.targetDescriptor?.revisionView==="rejected"?"rejected":"accepted",i=r?.revisionView===a?r:null,l=i?.index??se(e).indexOf(t)+1,s=i?.paragraphId??He(t),c=i?.inTable??!!ct(t,"tbl"),f=i?.text??Y(t,{revisionView:a}),u=i?.fingerprint??Ot(t,{text:f,index:l,paragraphId:s,inTable:c,revisionView:a});return{index:l,paragraphId:s,text:f,fingerprint:u,revisionView:a,inTable:c,targetTextMatch:Vy(f,o?.targetDescriptor?.text??o?.targetDescriptor?.exactText??n)}}function At(e,t,r,n,o=null,a={}){let i=typeof a?.onInfo=="function"?a.onInfo:()=>{},l=typeof a?.onWarn=="function"?a.onWarn:()=>{},s=a?._documentOperationSession||null,c=s?.getParagraphMetadataIndex?.()||null;if(a?._compiledSourceId&&a?._sourceTargetRegistry){let u=a._sourceTargetRegistry.resolve(a._compiledSourceId,e);if(u?.error||!u?.paragraph)return u;if(u.resolvedBy=a._compiledResolvedBy||u.resolvedBy,a?._resolutionCapture){let d=u.paragraph,m=c?.byParagraph?.get(d)||null;Object.assign(a._resolutionCapture,{resolvedBy:u.resolvedBy,resolvedTarget:Hl(e,d,m,t,a)})}return u}if(a?.targetDescriptor?.captureRef)try{let u=wm(e,s,a.targetDescriptor,n,a);if(a?._resolutionCapture&&u?.paragraph){let d=u.paragraph,m=c?.byParagraph?.get(d)||null;Object.assign(a._resolutionCapture,{resolvedBy:u.resolvedBy,resolvedTarget:Hl(e,d,m,t,a)})}return u}catch(u){return{error:{code:typeof u?.code=="string"&&u.code?u.code:"TARGET_NOT_FOUND",message:u?.message||String(u)}}}let f=Jn(e,{targetText:t,targetRef:r,opType:n,targetRefSnapshot:o?.targetRefSnapshot||null,targetDescriptor:a?.targetDescriptor||null,strictAmbiguity:a?.strictTargets===!0,paragraphMetadataIndex:c,onInfo:i,onWarn:l});if(a?._resolutionCapture&&f?.paragraph){let u=f.paragraph,d=c?.byParagraph?.get(u)||null;Object.assign(a._resolutionCapture,{resolvedBy:f.resolvedBy,resolvedTarget:Hl(e,u,d,t,a)})}return f}function Am(e,t,r,n,o,a={}){let i={...a,_resolutionCapture:null,onInfo:()=>{},onWarn:()=>{}},l=m=>{if(!m)return null;let p=se(e).indexOf(m);return p>=0?p:null},s;try{s=At(e,t,r,"redline",o,i)}catch{return null}let c=l(s?.paragraph);if(c===null)return null;let f=a.targetEndDescriptor||null,u=null;if(a._compiledSourceEndId&&a._sourceTargetRegistry)u=a._sourceTargetRegistry.resolve(a._compiledSourceEndId,e)?.paragraph||null;else if(f)u=At(e,f.text||"",f.index,"redline",o,{...i,targetDescriptor:f,_compiledSourceId:null})?.paragraph||null;else if(n)u=Jn(e,{targetRef:n,opType:"redline",targetRefSnapshot:o?.targetRefSnapshot||null,onInfo:()=>{},onWarn:()=>{}})?.paragraph||null;else return{from:c,to:c};let d=l(u);return d!==null&&d>=c?{from:c,to:d}:null}function Sr(e){return wl(e)}function Wy(e,t){if(!Array.isArray(e)||e.length===0||!Array.isArray(t)||!t.includes("Paragraph expanded to list fragment"))return e;let r=e[e.length-1];return!r||r.localName!=="p"||Array.from(r.childNodes||[]).some(o=>o.nodeType===1&&o.localName!=="pPr")?e:e.slice(0,-1)}function ot(e){vi(e)}function Ky(e){for(let t of Array.from(e?.getElementsByTagNameNS?.(ce,"proofErr")||[]))t.parentNode?.removeChild(t)}function Gy(e){e&&Ky(e)}function xe(e,t){return e&&Array.from(e.childNodes||[]).find(r=>r&&r.nodeType===1&&r.namespaceURI===ce&&r.localName===t)||null}function Hy(e,t){if(!e||!t)return null;let n=Array.from(e.getElementsByTagNameNS(ce,"tbl")).indexOf(t);return n>=0?n+1:null}function qy(e){return String(e||"").replace(/\r\n/g,`
|
|
221
221
|
`).split(`
|
|
222
222
|
`).map(t=>t.trim()).filter(Boolean).join(`
|
|
223
|
-
`)}function Fy(e,t,r){let n=Ly(e,t);if(!Number.isInteger(n)||n<1)return null;let o=By(r);return o?`table:${n}|payload:${o}`:null}function $y(e,t,r,n){let o=ye(t,"pPr");o||(o=F(e,"w:pPr"),t.insertBefore(o,t.firstChild));let a=ye(o,"numPr");a||(a=F(e,"w:numPr"),o.appendChild(a));let i=ye(a,"ilvl");i||(i=F(e,"w:ilvl"),a.appendChild(i)),i.setAttribute("w:val",String(Math.max(0,Number.parseInt(r,10)||0)));let l=ye(a,"numId");l||(l=F(e,"w:numId"),a.appendChild(l)),l.setAttribute("w:val",String(n))}function Ul(e,t,r,n,o,a={}){let i=a.generateRedlines!==!1,l=F(e,"w:p"),s=ye(t,"pPr");s&&l.appendChild(dt(s)),$y(e,l,r.ilvl,r.numId),i&&Yr(l,{author:o});let c=F(e,"w:r"),f=Array.from(t.getElementsByTagNameNS(le,"r"))[0]||null,u=f?ye(f,"rPr"):null;u&&c.appendChild(dt(u));let d=F(e,"w:t"),m=String(r.text||"").trim();if(/^\s|\s$/.test(m)&&d.setAttribute("xml:space","preserve"),d.textContent=m,c.appendChild(d),i){let p=n||ce(o,e),g=F(e,"w:ins");g.setAttribute("w:id",String(p.id)),g.setAttribute("w:author",p.author),g.setAttribute("w:date",p.date),g.appendChild(c),l.appendChild(g)}else l.appendChild(c);return l}function $l(e,t){let r=(e||[]).map(n=>t.serializeToString(n)).join("");return`<w:document xmlns:w="${le}"><w:body>${r}</w:body></w:document>`}function Dy({xmlDoc:e,explicitRangeParagraphs:t,insertionEntries:r,generateRedlines:n,author:o}){if(!Array.isArray(t)||t.length===0||!Array.isArray(r)||r.length===0)return!1;let a=t[0].parentNode;if(!a||t.some(l=>l.parentNode!==a))return!1;let i=t[t.length-1].nextSibling;for(let l of r){let s=l.insertBeforeOriginalIndex!=null?t[l.insertBeforeOriginalIndex]:t[t.length-1];if(!s)return!1;let c=Ul(e,s,{ilvl:l.ilvl,markerType:l.markerType,numId:l.numId,text:l.text},n?ce(o,e):null,o,{generateRedlines:n});l.insertBeforeOriginalIndex!=null?a.insertBefore(c,s):a.insertBefore(c,i)}return rt(e),!0}function Uy(e,t,r,n,o={}){let a=o.generateRedlines!==!1,i=F(e,"w:p"),l=F(e,"w:r"),s=F(e,"w:t"),c=String(t||"");if(/^\s|\s$/.test(c)&&s.setAttribute("xml:space","preserve"),s.textContent=c,l.appendChild(s),a){o.trackParagraphMark===!0&&Yr(i,{author:n});let f=r||ce(n,e,"ins"),u=F(e,"w:ins");u.setAttribute("w:id",String(f.id)),u.setAttribute("w:author",f.author),u.setAttribute("w:date",f.date),u.appendChild(l),i.appendChild(u)}else i.appendChild(l);return i}function zy(e,t){let r=F(e,"w:p"),n=ye(t,"pPr");n&&r.appendChild(dt(n));let o=F(e,"w:r"),a=Array.from(t.getElementsByTagNameNS(le,"r"))[0]||null,i=a?ye(a,"rPr"):null;i&&o.appendChild(dt(i));let l=F(e,"w:t");return l.textContent="",o.appendChild(l),r.appendChild(o),r}function vm(e,t,r,n,o={}){let a=F(e,"w:p"),i=o.sanitizeParagraphProperties===!0?ym(e,t):dt(ye(t,"pPr"));i&&a.appendChild(i),o.paragraphId&&a.setAttributeNS(fa,"w14:paraId",o.paragraphId),o.trackParagraphMark===!0&&Yr(a,{author:n});let l=F(e,"w:ins"),s=r||ce(n,e,"ins");l.setAttribute("w:id",String(s.id)),l.setAttribute("w:author",s.author),l.setAttribute("w:date",s.date);for(let c of Array.from(t.childNodes||[]))c?.nodeType===1&&c.namespaceURI===le&&c.localName==="pPr"||l.appendChild(c.cloneNode(!0));return a.appendChild(l),a}async function Xy(e,t,r,n,o,a={}){let i=a.generateRedlines!==!1,l=se(),s=zy(e,t),c=l.serializeToString(s),f=await po(c,"",String(r||""),{author:o,generateRedlines:!1}),u=null;return typeof f?.oxml=="string"&&(u=(Nr(f.oxml).replacementNodes||[]).find(m=>m&&m.nodeType===1&&m.namespaceURI===le&&m.localName==="p")||null),u?i?vm(e,u,n,o,a):u:Uy(e,r,n,o,{...a,generateRedlines:i})}function Vl(e){let t=new Set;for(let r of e||[])for(let n of kn(r)){let o=n.getAttribute("w:val")||n.getAttribute("val");o!=null&&o!==""&&t.add(String(o))}return Array.from(t)}function dm(e){return Array.from(e?.childNodes||[]).reduce((t,r)=>t+(r?.nodeType===1&&r.namespaceURI===le&&r.localName==="r"?jt(r).map(n=>n.text).join(""):""),"")}function Vy(e,t,r){let n=0,o=-1;for(let a=0;a<r;a++){if(o=e.indexOf(t,n),o<0)return-1;n=o+Math.max(t.length,1)}return o}function jy(e,t){if(!t)return 0;let r=0,n=0;for(;n<=e.length;){let o=e.indexOf(t,n);if(o<0)break;r+=1,n=o+t.length}return r}function Wy(e,t){let r=new Set(["commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"]);if(Array.from(e.getElementsByTagName?.("*")||[]).some(n=>r.has(n.localName)))return!0;for(let n of Array.from(t?.childNodes||[]))if(n.nodeType===1){if(!(n.namespaceURI===le&&n.localName==="r"))return!0;for(let o of Array.from(n.childNodes||[]))if(!(o.nodeType!==1||o.namespaceURI!==le)&&!["rPr","delText","t","tab","br","cr","noBreakHyphen","softHyphen"].includes(o.localName))return!0}return!1}function Ky(e,t){let r=0;for(let n of Array.from(e?.childNodes||[])){if(!(n?.nodeType===1&&n.namespaceURI===le&&n.localName==="r"))continue;let o=bt(jt(n));if(t<=r+o)return dt(ye(n,"rPr"));r+=o}return null}var Gy=new Set(["pStyle","numPr","ind","jc","spacing","tabs","keepNext","keepLines","outlineLvl","contextualSpacing"]);function zl(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function mm(e){return String(e||"").trim().toLowerCase()}function Hy(e,t="nextSibling"){let r=e?.[t]||null;for(;r;){if(r.nodeType===1&&r.namespaceURI===le&&r.localName==="p")return r;r=r[t]||null}return null}function ym(e,t){let r=ye(t,"pPr"),n=F(e,"w:pPr");if(!r)return n;for(let o of Array.from(r.childNodes||[]))o.nodeType!==1||o.namespaceURI!==le||Gy.has(o.localName)&&n.appendChild(e.importNode(o,!0));return n}function qy(e){let t=[],r=new Set;for(let o of Array.from(e?.getElementsByTagNameNS?.(le,"bookmarkStart")||[])){let a=zl(o,"name")||"(unnamed)";r.add(a)}for(let o of r)t.push(`RESTORATION_DROPPED_BOOKMARK:${o}`);let n=new Set;for(let o of["commentRangeStart","commentRangeEnd","commentReference"])for(let a of Array.from(e?.getElementsByTagNameNS?.(le,o)||[])){let i=zl(a,"id");i!==""&&n.add(i)}for(let o of n)t.push(`RESTORATION_DROPPED_COMMENT:${o}`);return t}function Yy(e){let t=["bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference"];for(let r of t)for(let n of Array.from(e?.getElementsByTagNameNS?.(le,r)||[]))n.parentNode?.removeChild(n);for(let r of Array.from(e?.getElementsByTagNameNS?.(le,"r")||[]))Array.from(r.childNodes||[]).some(o=>o.nodeType===1&&o.namespaceURI===le&&o.localName!=="rPr")||r.parentNode?.removeChild(r)}function Jy(e,t,r){let n=Fr(r.serializeToString(t),{allAuthors:!0}),a=j(n.oxml,"application/xml").doc?.getElementsByTagNameNS?.(le,"p")?.[0]||null;if(!a)return null;let i=F(e,"w:p");i.appendChild(ym(e,t));for(let l of Array.from(a.childNodes||[]))l.nodeType===1&&l.namespaceURI===le&&l.localName==="pPr"||i.appendChild(e.importNode(l,!0));return Yy(i),i}async function Zy(e,t,r,n,o){let a=Q(t);if(a===r)return t;let i=await po(o.serializeToString(t),a,r,{author:n,generateRedlines:!1,structuredContent:!1});if(i?.status==="error"||typeof i?.oxml!="string")return null;let s=(Nr(i.oxml).replacementNodes||[]).find(c=>c?.nodeType===1&&c.namespaceURI===le&&c.localName==="p");return s?e.importNode(s,!0):null}function Qy(e,t){let r=new Set(ae(e).map(o=>o.getAttributeNS?.(fa,"paraId")||o.getAttribute?.("w14:paraId")||"").filter(Boolean).map(o=>o.toUpperCase())),n=null;do n=t?.generateParagraphId?.()||(1073741824+r.size+1).toString(16).toUpperCase();while(r.has(n.toUpperCase()));return n}function eb(e,t,r,n){let o=e.documentElement;return o&&!o.getAttribute("xmlns:w14")&&o.setAttribute("xmlns:w14",fa),vm(e,t,null,r,{paragraphId:Qy(e,n),sanitizeParagraphProperties:!0,trackParagraphMark:!0})}function tb(e,t){let r=ye(e,"pPr"),n=ye(r,"rPr"),o=ye(n,"ins");return!!o&&mm(zl(o,"author"))===mm(t)}function rb(e,t){let r=[],n=e;for(let o=0;o<t;o++){if(n=Hy(n,"nextSibling"),!n)return[];r.push(n)}return r}function Xl(e){let t=j(e,"application/xml");return t.error||!t.doc?null:ae(t.doc).map(r=>Q(r))}function nb(e,t){return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>r===t[n])}function Pi(e,t){let r=t==="accept"?tn(e,{allAuthors:!0}):Fr(e,{allAuthors:!0});return Xl(r.oxml)}function ob(e,t,r,n){let o=j(e,"application/xml");if(o.error||!o.doc)return null;let a=o.doc,i=ae(a),l=i[t+n.length-1]||null;if(!l?.parentNode)return null;for(let c of[...r].sort((f,u)=>u-f)){let f=i[c];f?.parentNode?.removeChild(f)}let s=l.nextSibling;for(let c of n)l.parentNode.insertBefore(a.importNode(c,!0),s);return se().serializeToString(a)}function ab(e,t,r,n,o,a=[]){let i=kt(e),l=kt(t),s=Tn(l.issues,i.issues),c=a.flatMap(m=>kt(se().serializeToString(m)).issues.filter(p=>p.severity==="error")),f=An(s);if(f.length>0||c.length>0)return{valid:!1,stage:"validation",code:"GENERATED_OOXML_INVALID",generatedIssues:s,envelopeIssues:c,message:[...f,...c].map(m=>m.message).join(" ")};let u=ob(e,r,n,o);if(!u)return{valid:!1,stage:"expected-document",message:"Could not construct the restoration lifecycle oracle."};let d=[["current",Xl(u),Xl(t)],["accept-all",Pi(u,"accept"),Pi(t,"accept")],["reject-all",Pi(e,"reject"),Pi(t,"reject")]];for(let[m,p,g]of d)if(!nb(p,g))return{valid:!1,stage:m,expected:p,actual:g,message:`Paragraph restoration ${m} lifecycle text did not match the expected body-scoped paragraph sequence.`};return{valid:!0}}async function bm(e,t,r,n,o,a=null,i=null,l={}){let{serializer:s,xmlDoc:c,operationSession:f}=Vr(e,l);if(!c)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let u=Tt(c,t,a,"insert",i,l);if(u?.error||!u?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:u?.error||{code:"TARGET_NOT_FOUND",message:"Rejected-view insertion target was not found."}};let d=u.paragraph;if(!$r(d,o).matches)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"REJECTED_INSERTION_STATE_REQUIRED",message:"Rejected-view insertion requires a wholly deleted paragraph owned by another author."}};let p=nn(d,{requireFollowingParagraph:!1});if(p)return{documentXml:e,hasChanges:!1,status:"error",error:p};if(/\r|\n/.test(n))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Rejected-view insertion supports run-level text only; use restore for paragraph boundaries."}};let g=Q(d,{revisionView:"rejected"});if(!r.occurrenceExplicit&&jy(g,r.exactText)>1)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"AMBIGUOUS_ANCHOR",message:"The rejected-view insertion anchor is repeated; provide anchor.occurrence explicitly."}};let h=Vy(g,r.exactText,r.occurrence);if(h<0)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"ANCHOR_NOT_FOUND",message:"The rejected-view insertion anchor was not found at the requested occurrence."}};let v=h+r.offset,w=Array.from(d.childNodes||[]).filter(_=>_?.nodeType===1&&_.namespaceURI===le&&_.localName==="del");if(w.some(_=>Wy(d,_)))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_BOUNDARY",message:"The rejected-view insertion boundary contains comments, bookmarks, fields, hyperlinks, moves, or non-text run markup that cannot be split safely."}};let y=0,b=null,I=0;for(let _ of w){let k=dm(_).length;if(v>=y&&v<=y+k){b=_,I=v-y;break}y+=k}if(!b||w.map(dm).join("")!==g)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"The rejected-view anchor is not contained in a supported direct deletion carrier."}};let E=Ky(b,I),{leftCarrier:N,rightCarrier:R}=Oa(c,b,I,l._revisionIdAllocator||null),x=F(c,"w:ins"),T=ce(o,l._revisionIdAllocator||c,"ins");x.setAttribute("w:id",String(T.id)),x.setAttribute("w:author",T.author),x.setAttribute("w:date",T.date);let A=F(c,"w:r");E&&A.appendChild(E);let S=F(c,"w:t");/^\s|\s$/.test(n)&&S.setAttribute("xml:space","preserve"),S.textContent=n,A.appendChild(S),x.appendChild(A);let O=b.parentNode;N&&O.insertBefore(N,b),O.insertBefore(x,b),R&&O.insertBefore(R,b),l?._mutationRemovedNodes?.push(b),O.removeChild(b),l?._mutationLiveNodes?.push(d,x),f?.invalidateParagraphMetadata?.();let C=s.serializeToString(c),P=Q(d,{revisionView:"rejected"}),M=Q(d,{revisionView:"accepted"});return P!==g||!M.includes(n)?{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:"Rejected-view insertion did not preserve the deleted source and expose the requested inserted text."}}:{documentXml:C,hasChanges:!0,status:"ok"}}async function Im(e,t,r,n,o=null,a=null,i=null,l={}){let{serializer:s,xmlDoc:c,operationSession:f}=Vr(e,l);if(!c)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let u=Tt(c,t,o,"restore",i,l);if(u?.error||!u?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:u?.error||{code:"TARGET_NOT_FOUND",message:"Restoration target paragraph not found."}};let d=u.paragraph,m=[d];if(l._compiledSourceEndId){let O=Tt(c,l.targetEndDescriptor?.text||"",a,"restore",i,{...l,_compiledSourceId:l._compiledSourceEndId}),C=O?.paragraph?ae(c):[],P=C.indexOf(d),M=C.indexOf(O?.paragraph);m=P>=0&&M>=P?C.slice(P,M+1):null}else if(a)m=sn(c,o,a,{opType:"restore",targetRefSnapshot:i?.targetRefSnapshot||null,onInfo:l.onInfo,onWarn:l.onWarn});else if(l.targetEndDescriptor){let O=Tt(c,l.targetEndDescriptor.text,l.targetEndDescriptor.index,"restore",i,{...l,targetDescriptor:l.targetEndDescriptor,_compiledSourceId:l._compiledSourceEndId||null}),C=O?.paragraph?ae(c):[],P=C.indexOf(d),M=C.indexOf(O?.paragraph);m=P>=0&&M>=P?C.slice(P,M+1):null}if(!Array.isArray(m)||m.length===0||m[0]!==d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_COUNT_MISMATCH",message:"The restoration range could not be resolved as a contiguous paragraph block."}};let p=Array.isArray(r)?r.map(String):[String(r||"")];if(p.length!==m.length||p.some(O=>O.length===0))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_COUNT_MISMATCH",message:`Restoration requires exactly one non-empty replacement per source paragraph (${m.length} expected, ${p.length} received).`}};let g=d.parentNode;if(!g||m.some(O=>O.parentNode!==g))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_PARAGRAPH_PLACEMENT",message:"Restoration source paragraphs must be a contiguous block in one structural container."}};for(let O of m){let C=nn(O);if(C?.code==="UNSUPPORTED_MOVE_REVISION")return{documentXml:e,hasChanges:!1,status:"error",error:C};let P=$r(O,n);if(!P.matches)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_STATE_REQUIRED",message:P.hasParagraphMarkDeletion&&!P.foreignParagraphMarkDeletion?"Explicit cross-author restoration does not apply to a paragraph deleted by the current author; use merge-same-author.":"Explicit restoration requires a foreign paragraph-mark deletion with every pre-existing content node deleted.",...P.ownerAuthor?{ownerAuthor:P.ownerAuthor}:{}}};let M=C||nn(O);if(M)return{documentXml:e,hasChanges:!1,status:"error",error:M}}let h=m[m.length-1],v=rb(h,m.length),w=v.length===m.length&&v.every(O=>tb(O,n));if(w&&v.every((O,C)=>Q(O)===p[C]))return{documentXml:e,hasChanges:!1,status:"no-op",warnings:["An identical same-author paragraph restoration already exists."]};let y=s.serializeToString(c),b=ae(c),I=b.indexOf(d),E=w?v.map(O=>b.indexOf(O)):[],N=[],R=[];for(let O=0;O<m.length;O++){let C=m[O];R.push(...qy(C));let P=Jy(c,C,s),M=P?await Zy(c,P,p[O],n,s):null;if(!M)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:`Could not reconstruct restoration paragraph ${O+1} from its rejected revision view.`}};N.push(M)}let x=N.map(O=>{let C=c.importNode(O,!0);return eb(c,C,n,f)}),T=h.nextSibling;for(let O of x)g.insertBefore(O,T);if(w)for(let O of v)l?._mutationRemovedNodes?.push(O),O.parentNode?.removeChild(O);l?._mutationLiveNodes?.push(...x),rt(c);let A=s.serializeToString(c),S=ab(y,A,I,E,N,x);return S.valid?{documentXml:tt(c,s,e,f),hasChanges:!0,status:"ok",numberingXml:null,...R.length>0?{warnings:[...new Set(R)]}:{}}:{documentXml:e,hasChanges:!1,status:"error",error:{code:S.code||"PATCH_ROUNDTRIP_MISMATCH",message:S.message,stage:S.stage,...S.generatedIssues?{generatedIssues:S.generatedIssues}:{},...S.envelopeIssues?{envelopeIssues:S.envelopeIssues}:{},...S.expected?{expected:S.expected}:{},...S.actual?{actual:S.actual}:{}}}}async function ib({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:o,currentParagraphText:a,modifiedText:i,author:l,runtimeContext:s,revisionIdAllocator:c,generateRedlines:f=!0,onInfo:u=()=>{},options:d={}}){if(!o)return null;let m=t.serializeToString(o),p=un({oxml:m,originalText:a,modifiedText:i,allowExistingList:!1});if(!p||p.numberingKey!=="numbered:decimal:single"||!Number.isInteger(p.startAt)||p.startAt<1)return null;let g=Bs(p.listInput||i);if(!g)return null;u("[List] Applying explicit numeric header conversion with direct list binding.");let h=qa(p,s?.listFallbackSequenceState||null),v=p.startAt,w=s?.numberingIdState||null,y=null,b=null;if(h.type==="explicitReuse"&&h.numId)y=String(h.numId),u(`[List] Reusing explicit-start list sequence (${h.numberingKey} -> numId ${y}, next ${v+1}).`);else{let x=Zn(w);if(!x)return null;y=String(x.numId),b=ei(x.numId,x.abstractNumId,v),h.type==="explicitStartNew"&&u(`[List] Started explicit-start list sequence (${h.numberingKey} -> numId ${y}).`),u(`[List] Using isolated explicit-start numbering (start ${v}, numId ${y}, abstractNumId ${x.abstractNumId}).`)}let I=await po(t.serializeToString(o),a,g,{author:l,generateRedlines:f,_revisionIdAllocator:c});if(!I?.hasChanges||typeof I?.oxml!="string")return null;let N=Nr(I.oxml).replacementNodes;p.numberingKey&&s?.listFallbackSharedNumIdByKey instanceof Map&&s.listFallbackSharedNumIdByKey.delete(p.numberingKey),h.type==="explicitStartNew"||h.type==="explicitReuse"?Ya(s?.listFallbackSequenceState||null,h.numberingKey||p.numberingKey,y,v):zo(s?.listFallbackSequenceState||null,h.numberingKey||p.numberingKey),Ja(N,{numId:y,ilvl:0,clearParagraphPropertyChanges:!0,removeListPropertyNode:!0,trackPropertyChange:f?{author:l,revisionIdAllocator:c}:null});let R=o.parentNode;if(!R)return null;for(let x of N){let T=e.importNode(x,!0);let A=R.insertBefore(T,o);d?._mutationLiveNodes?.push(A)}if(d?._mutationRemovedNodes?.push(o),R.removeChild(o),rt(e),n?.receiptCollector&&b){let x=Vl(d?._mutationLiveNodes);for(let T of x)n.receiptCollector.recordNumbering(T)}return{documentXml:tt(e,t,r,n),hasChanges:!0,numberingXml:b}}var sb=Object.freeze({upperAlpha:"upperLetter",lowerAlpha:"lowerLetter",upperRoman:"upperRoman",lowerRoman:"lowerRoman",bullet:"bullet"});function lb({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:o,currentParagraphText:a,modifiedText:i,author:l,runtimeContext:s,revisionIdAllocator:c,generateRedlines:f=!0,onInfo:u=()=>{},options:d={}}){if(!o||_e(o)||Z(a)!==Z(i))return null;let m=un({oxml:t.serializeToString(o),originalText:a,modifiedText:i,allowExistingList:!1}),p=m?sb[m.numberingStyle]:null;if(!p)return null;let g=ae(e),h=Cl(e,[o],vl({mode:"convert-plain",format:p,strip:"marker"}),{author:l||oe(),generateRedlines:f,revisionIdAllocator:c,runtimeContext:s,stylesXml:s?.stylesXml||d.stylesXml||null,numberingXml:s?.numberingXml||d.numberingXml||null,paragraphIndexOf:v=>g.indexOf(v)+1});if(!h.ok)return u(`[List] In-place marker conversion declined (${h.error.code}); using the structural fallback.`),null;u(`[List] Converted typed ${p} marker in place (numId ${h.items[0].numId}).`),d?._mutationLiveNodes?.push(o);for(let v of h.allocatedNumIds)n?.receiptCollector?.recordNumbering(v);return rt(e),{documentXml:tt(e,t,r,n),hasChanges:!0,numberingXml:h.numberingXml}}var pm=["pStyle","keepNext","keepLines","pageBreakBefore","framePr","widowControl","numPr","suppressLineNumbers","pBdr","shd","tabs","suppressAutoHyphens","kinsoku","wordWrap","overflowPunct","topLinePunct","autoSpaceDE","autoSpaceDN","bidi","adjustRightInd","snapToGrid","spacing","ind","contextualSpacing","mirrorIndents","suppressOverlap","jc","textDirection","textAlignment","textboxTightWrap","outlineLvl","divId","cnfStyle","rPr","sectPr","pPrChange"],cb=new Set(["pStyle","numPr","rPr","sectPr","pPrChange"]);function ub(e,t,r){let n=t.filter(s=>s?.nodeType===1&&s.localName==="p"),o=(s,c)=>{let f=ye(ye(s,"pPr"),"rPr");return!!f&&!!ye(f,c)},a=n.find(s=>o(s,"del")),i=n.find(s=>!o(s,"del")),l=ye(r,"pPr");if(a&&l){let s=e.importNode(l,!0),c=ye(ye(a,"pPr"),"rPr"),f=c&&ye(c,"del");if(f){let u=ye(s,"rPr");if(!u){u=F(e,"w:rPr");let d=ye(s,"sectPr")||ye(s,"pPrChange");s.insertBefore(u,d||null)}Array.from(u.childNodes).forEach(d=>{d.nodeType===1&&(d.localName==="ins"||d.localName==="del")&&u.removeChild(d)}),u.appendChild(e.importNode(f,!0)),a.replaceChild(s,ye(a,"pPr"))}}if(i&&l){let s=ye(i,"pPr");s||(s=F(e,"w:pPr"),i.insertBefore(s,i.firstChild||null));for(let c of Array.from(l.childNodes)){if(c.nodeType!==1||cb.has(c.localName)||ye(s,c.localName))continue;let f=pm.indexOf(c.localName),u=Array.from(s.childNodes).find(d=>d.nodeType===1&&pm.indexOf(d.localName)>f);s.insertBefore(e.importNode(c,!0),u||null)}}if(i)for(let s of["paraId","textId"]){let c=r.getAttributeNS?.(fa,s)||r.getAttribute?.(`w14:${s}`);c&&i.setAttributeNS(fa,`w14:${s}`,c)}}async function fb({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:o,currentParagraphText:a,modifiedText:i,author:l,runtimeContext:s,revisionIdAllocator:c,generateRedlines:f=!0,onInfo:u=()=>{},options:d={}}){if(!o)return null;let m=t.serializeToString(o),p=un({oxml:m,originalText:a,modifiedText:i,allowExistingList:!1});if(!p)return null;u("[List] No textual diff but list marker detected; forcing structural list conversion fallback.");let g=await Yn(p,{author:l,generateRedlines:f,revisionIdAllocator:c,setAbstractStartOverride:!1});if(!g?.hasChanges||!g?.oxml)return u("[List] Structural list fallback produced no valid OOXML payload."),null;let h=Nr(g.oxml),v=h.replacementNodes,w=h.numberingXml||g?.numberingXml||null,y=Number.isInteger(p?.startAt)&&p.startAt>0,b=y&&p?.numberingStyle==="decimal",I=y&&!b,E=g?.listStructuralFallbackKey||p?.numberingKey||null,N=qa(p,s?.listFallbackSequenceState||null);if(b){let x=p.startAt,T=null,A=s?.numberingIdState||null;if(N.type==="explicitReuse"&&N.numId)T=String(N.numId),w=null,u(`[List] Reusing explicit-start list sequence (${N.numberingKey} -> numId ${T}, next ${x+1}).`);else if(A){let S=Zn(A);if(!S)return null;Za(v,S.numId),T=String(S.numId),w=ei(S.numId,S.abstractNumId,x),N.type==="explicitStartNew"&&u(`[List] Started explicit-start list sequence (${N.numberingKey} -> numId ${S.numId}).`),u(`[List] Using isolated explicit-start numbering (start ${x}, numId ${S.numId}, abstractNumId ${S.abstractNumId}).`)}else{let S=Qa(v);T=S?String(S):null,u(`[List] Using isolated list numbering with explicit start ${x}${S?` (numId ${S})`:""}.`)}E&&s?.listFallbackSharedNumIdByKey instanceof Map&&s.listFallbackSharedNumIdByKey.delete(E),N.type==="explicitStartNew"||N.type==="explicitReuse"?Ya(s?.listFallbackSequenceState||null,N.numberingKey||E,T,x):zo(s?.listFallbackSequenceState||null,N.numberingKey||E),T&&Ja(v,{numId:T,ilvl:0,clearParagraphPropertyChanges:!0,removeListPropertyNode:!0,trackPropertyChange:f?{author:l,revisionIdAllocator:c}:null})}else{if(w&&s?.numberingIdState){let x=fn(w,v,s.numberingIdState);v=x.replacementNodes,w=x.numberingXml}zo(s?.listFallbackSequenceState||null,N.numberingKey||E)}if(!b&&w&&s){let x=Nf({numberingXml:w,replacementNodes:v,sequence:Rl(s),isNumIdLive:T=>El(e,T)});x&&(v=x.replacementNodes,w=null,u(`[List] Continuing batch list numbering (numId ${x.numId}).`))}if(!b&&!I&&s?.listFallbackSharedNumIdByKey instanceof Map){let x=E?s.listFallbackSharedNumIdByKey.get(E):null;if(x)Za(v,x),w=null,u(`[List] Reusing shared list numbering (${E} -> numId ${x}).`);else if(E){let T=Qa(v);T&&(s.listFallbackSharedNumIdByKey.set(E,T),u(`[List] Captured shared list numbering (${E} -> numId ${T}).`))}}let R=o.parentNode;if(!R)return null;f&&ub(e,v,o);for(let x of v){let T=e.importNode(x,!0);let A=R.insertBefore(T,o);d?._mutationLiveNodes?.push(A)}if(d?._mutationRemovedNodes?.push(o),R.removeChild(o),rt(e),n?.receiptCollector&&w){let x=Vl(d?._mutationLiveNodes);for(let T of x)n.receiptCollector.recordNumbering(T)}return{documentXml:tt(e,t,r,n),hasChanges:!0,numberingXml:w}}function Dl(e,t){let{severity:r,...n}=t;return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:n}}function Ci(e){return e.length>0?{diagnostics:e,warnings:e.map(Il)}:{}}function gm({sourceParagraphs:e,modifiedText:t,runtimeContext:r,options:n}){let o=bl(n);if(o==="off")return null;let a=r?.numberingIdState?.sourceNumberingXml;if(!a)return null;let i=[];for(let s of e||[]){let c=_e(s);c&&i.push({text:mo(s),numId:c.numId,ilvl:c.ilvl})}let l=Fd({modifiedText:t,sourceItems:i,sourceNumberingXml:a});return l?Md(l.mismatch,{policy:o,numId:l.numId,level:l.level,marker:l.marker,targetText:l.targetText,operationIndex:n?._operationIndex}):null}async function xm(e,t,r,n,o=null,a=null,i=null,l={}){let s=l.generateRedlines!==!1,c=typeof l?.onInfo=="function"?l.onInfo:()=>{},f=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:u,xmlDoc:d,operationSession:m}=Vr(e,l);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||Nn(d,l),g=Tt(d,t,o,"redline",i,{...l,onInfo:c,onWarn:f});if(g?.error||!g?.paragraph)return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:g?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let h=g.paragraph;if(typeof r=="string"&&r.length>0){let X=$r(h,n);if(X.matches){let J=X.ownerAuthor||"unattributed";return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${J}). Use explicit paragraph restoration when supported.`,ownerAuthor:J}}}}My(h);let v=mo(h);if(r===""){let X=cm(h);if(X.length>0){let J=um(X,l._existingCommentDetails);return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"COMMENTED_CONTENT_DELETE",message:"Refusing to delete a paragraph with existing comments. Resolve or explicitly remove the comments before deleting the paragraph.",commentIds:X,...J.length>0?{comments:J}:{}}}}}let w=Wa(h,r,l);if(!w.valid)return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:w.code,message:w.message}};let y=Or(h),b=l.existingRevisions||"merge-same-author";if(y&&b!=="accept-all-first"&&b!=="accept-all-first-keep-normalized")if(b==="merge-same-author"||b==="slice-cross-author"){let X=qr(h),J=String(n||"").trim().toLowerCase(),be=X.length>0&&X.every(Te=>Te.trim().toLowerCase()===J);if(!be&&b==="merge-same-author")return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"EXISTING_REVISIONS",message:`Target paragraph contains tracked changes from another author (${X.length?X.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:X,currentPolicy:b}};let ve=be?cm(h):[];if(ve.length>0){let Te=um(ve,l._existingCommentDetails);return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:ve,...Te.length>0?{comments:Te}:{}}}}if(!be&&(h.getElementsByTagNameNS(le,"moveFrom").length>0||h.getElementsByTagNameNS(le,"moveTo").length>0))return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}}}else{let X=h.getElementsByTagNameNS(le,"del").length>0,J=h.getElementsByTagNameNS(le,"moveFrom").length>0||h.getElementsByTagNameNS(le,"moveTo").length>0;return X?{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Refusing to replace content with pending deletions; nesting revisions is unsafe."}}:J?{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Refusing to mutate content with move revisions until move lifecycle is designed."}}:{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"EXISTING_REVISIONS",message:'Target paragraph contains tracked changes and existingRevisions is "reject-input".'}}}if(r===""&&v===""&&!(y&&b==="merge-same-author"))return s?(Jr(h,{author:n}),l?._mutationLiveNodes?.push(h)):(l?._mutationRemovedNodes?.push(h),h.parentNode?.removeChild(h)),rt(d),{documentXml:tt(d,u,e,m),hasChanges:!0,numberingXml:null};let I=st(h,"tbl"),N=!!I&&!a&&typeof r=="string"&&r.includes(`
|
|
224
|
-
`)&&!
|
|
225
|
-
`)){let
|
|
226
|
-
`):
|
|
227
|
-
`):v||t,
|
|
228
|
-
`:m==="noBreakHyphen"&&(l+="\u2011")}let s=l.slice(0,r),c=l.slice(r),f=(d,m)=>{let p=m.split(/(\t|\n|\u2011)/);for(let g of p)if(g)if(g===" ")d.appendChild(
|
|
229
|
-
`)d.appendChild(
|
|
230
|
-
`:z==="noBreakHyphen"&&(L+="\u2011")}L.length>0&&C.push({run:M,text:L})}return C})(),y="",b=[];for(let C of w){let P=y.length;y+=C.text;let M=y.length;b.push({...C,start:P,end:M})}let I=l.targetDescriptor,E=Number.isInteger(l.textOccurrence)&&l.textOccurrence>0?l.textOccurrence:null,N=E??I?.occurrence??null,R=-1;if(N!=null&&N>0){let C=0,P=0;for(;P<=y.length-r.length;){let M=y.indexOf(r,P);if(M===-1)break;if(C++,C===N){R=M;break}P=M+1}}else R=y.indexOf(r);if(R===-1&&E!=null&&y.includes(r))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_SOURCE_NOT_FOUND",message:`Occurrence ${E} of text to format was not found in target paragraph: "${r}".`}};if(R===-1)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:`Text to format was not found in target paragraph: "${r}".`}};let x=R+r.length,T=[];for(let C of b)if(C.start<R&&C.end>R){let P=R-C.start,[M,_]=hm(d,C.run,P,p);T.push({run:M,start:C.start,end:R,text:C.text.slice(0,P)}),T.push({run:_,start:R,end:C.end,text:C.text.slice(P)})}else T.push(C);let A=[];for(let C of T)if(C.start<x&&C.end>x){let P=x-C.start,[M,_]=hm(d,C.run,P,p);A.push({run:M,start:C.start,end:x,text:C.text.slice(0,P)}),A.push({run:_,start:x,end:C.end,text:C.text.slice(P)})}else A.push(C);let S=A.filter(C=>C.start>=R&&C.end<=x),O=!1;for(let C of S){let P=C.run.getElementsByTagNameNS(le,"rPr")[0]||null;if(pu(P,n)){O=!0;break}}if(!O)return{documentXml:e,hasChanges:!1,status:"no-op"};for(let C of S){let P=C.run,M=P.getElementsByTagNameNS(le,"rPr")[0];M||(M=F(d,"w:rPr"),P.insertBefore(M,P.firstChild));let _=P.parentNode,k=!1;for(;_&&_!==h;){if(_.nodeType===1&&(_.localName==="ins"||_.nodeName==="w:ins")){(_.getAttribute("w:author")||_.getAttributeNS(le,"author"))===(o||oe())&&(k=!0);break}_=_.parentNode}let L=k&&l.formattingRevisionPolicy==="coalesce-own-insertion";s&&!L&&_o(d,M,o||oe()),gu(d,M,n)}return rt(d),l?._mutationLiveNodes?.push(h),{documentXml:tt(d,u,e,m),hasChanges:!0,status:"ok"}}async function Sm(e,t,r={},n,o=null,a=null,i={}){let l=i.generateRedlines!==!1,s=typeof i?.onInfo=="function"?i.onInfo:()=>{},c=typeof i?.onWarn=="function"?i.onWarn:()=>{},{serializer:f,xmlDoc:u,operationSession:d}=Vr(e,i);if(!u)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};d||Nn(u,i);let m=Tt(u,t,o,"paragraph-format",a,{...i,onInfo:s,onWarn:c});if(m?.error||!m?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:m?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let p=m.paragraph,g=p.getElementsByTagNameNS(le,"pPr")[0];g||(g=F(u,"w:pPr"),p.insertBefore(g,p.firstChild));let h=Ai(r),v=h.length>0?[Bd(h)]:[];if(r?.numbering){let y=Af(a?.numberingIdState,r.numbering.numId,Number(r.numbering.level)||0);if(!y.ok)return{documentXml:e,hasChanges:!1,status:"error",error:{code:Pd,message:`${y.message} paragraph-format.numbering binds to an existing list; it never creates one.`,field:"properties.numbering",numId:Number(r.numbering.numId),level:Number(r.numbering.level)||0,reason:y.reason,recovery:{action:"inspect_numbering",hint:"Inspect a paragraph already in the target list and pass its list.numId and list.level. To start a new list, use a list-change/redline operation."}}}}if(!hu(g,r))return{documentXml:e,hasChanges:!1,status:"no-op",...Ci(v)};if(l){let y=n||oe(),b=Je(g,"pPrChange"),I=b?.getAttribute("w:author")??b?.getAttribute("author")??"";if(b&&I!==y)return{documentXml:e,hasChanges:!1,status:"error",error:{code:Cd,message:`Target paragraph already has a pending paragraph-property change by "${I||"unattributed"}". Overwriting its snapshot would change what Reject All restores.`,pendingAuthor:I,recovery:{action:"resolve_pending_revision",hint:"Ask the user to accept or reject the existing paragraph formatting change first; this tool does not resolve revisions by other reviewers."}}};b||Wn(u,g,y)}return Vn(u,g,r),rt(u),i?._mutationLiveNodes?.push(p),{documentXml:tt(u,f,e,d),hasChanges:!0,status:"ok",...Ci(v)}}function Em(e,t,r,n,o,a,i){let l=Tt(e,t,r,o,a,i);if(l?.error||!l?.paragraph)return{error:l?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let s=l.paragraph;if(!(i._compiledSourceEndId||n!=null||i.targetEndDescriptor))return{paragraphs:[s]};let f=null;if(i._compiledSourceEndId||i.targetEndDescriptor){let u=Tt(e,i.targetEndDescriptor?.text||"",i._compiledSourceEndId?n:i.targetEndDescriptor?.index??n,o,a,{...i,...i.targetEndDescriptor?{targetDescriptor:i.targetEndDescriptor}:{},_compiledSourceId:i._compiledSourceEndId||null,_resolutionCapture:null});if(u?.error)return{error:u.error};let d=u?.paragraph?ae(e):[],m=d.indexOf(s),p=d.indexOf(u?.paragraph);f=m>=0&&p>=m?d.slice(m,p+1):null}else f=sn(e,r,n,{opType:o,targetRefSnapshot:a?.targetRefSnapshot||null,onInfo:i.onInfo,onWarn:i.onWarn});return!Array.isArray(f)||f.length===0||f[0]!==s?{error:{code:"TARGET_RANGE_INVALID",message:"targetEnd must resolve to the target paragraph or a paragraph after it."}}:{paragraphs:f}}async function Rm(e,t,r,n,o=null,a=null,i=null,l={}){let s=l.generateRedlines!==!1,c=typeof l?.onInfo=="function"?l.onInfo:()=>{},f=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:u,xmlDoc:d,operationSession:m}=Vr(e,l);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||Nn(d,l),g=Em(d,t,o,a,"list-format",i,{...l,onInfo:c,onWarn:f});if(g.error)return{documentXml:e,hasChanges:!1,status:"error",error:g.error};let h=g.paragraphs;if(h.some(b=>b.parentNode!==h[0].parentNode))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"TARGET_RANGE_INVALID",message:"A list-format range must stay inside one container (the body, or one table cell)."}};let v=ae(d),w=vl(r);if(w.mode==="change-format"||w.mode==="join")return db(d,h,w,{documentXml:e,serializer:u,operationSession:m,runtimeContext:i,options:l,author:n,generateRedlines:s,onInfo:c,onWarn:f,paragraphIndexOf:b=>{let I=v.indexOf(b);return I>=0?I+1:null}});let y=Cl(d,h,w,{author:n||oe(),generateRedlines:s,revisionIdAllocator:p,runtimeContext:i,stylesXml:i?.stylesXml||l.stylesXml||null,numberingXml:i?.numberingXml||l.numberingXml||null,paragraphIndexOf:b=>v.indexOf(b)+1});if(!y.ok)return{documentXml:e,hasChanges:!1,status:"error",error:y.error};for(let b of y.items)b.paragraph,l?._mutationLiveNodes?.push(b.paragraph);for(let b of y.allocatedNumIds)m?.receiptCollector?.recordNumbering(b);return rt(d),c(`[List] list-format convert-plain bound ${y.items.length} paragraph(s) as ${y.format} (numId ${[...new Set(y.items.map(b=>b.numId))].join(", ")}).`),{documentXml:tt(d,u,e,m),hasChanges:!0,status:"ok",numberingXml:y.numberingXml,list:{mode:"convert-plain",format:y.format,level:y.level,strip:y.strip,items:y.items.map(b=>({paragraphIndex:b.paragraphIndex,paragraphId:Ke(b.paragraph),marker:b.marker,value:b.value,numId:b.numId})),skipped:y.skipped.map(b=>({paragraphIndex:b.paragraphIndex,reason:b.reason}))}}}function db(e,t,r,n){let{documentXml:o,serializer:a,operationSession:i,runtimeContext:l,options:s,author:c,generateRedlines:f,onInfo:u,paragraphIndexOf:d}=n,m=b=>({documentXml:o,hasChanges:!1,status:"error",error:b}),p=l?.numberingIdState?.sourceNumberingXml||l?.numberingXml||s.numberingXml||"",g=Array.isArray(i?.numberingXmlParts)?i.numberingXmlParts:[],h=g.length>0?hr(p,g):p,v={author:c||oe(),generateRedlines:f,runtimeContext:l,stylesXml:l?.stylesXml||s.stylesXml||null,numberingXml:h,paragraphIndexOf:d},w;if(r.mode==="join"){let b=s.continueFromDescriptor||null,I=b?Tt(e,b.text||"",b.index??null,"list-format",l,{...s,targetDescriptor:b,_compiledSourceId:s._compiledContinueFromId||null,_compiledResolvedBy:null,_resolutionCapture:null}):null;if(!I?.paragraph)return m({code:I?.error?.code||"TARGET_NOT_FOUND",message:`list.continueFrom: ${I?.error?.message||"paragraph not found."}`,field:"list.continueFrom"});w=em(e,t,I.paragraph,r,v)}else w=Qd(e,t,r,v);if(!w.ok)return m(w.error);if(w.unchanged){let b=`${Id}: ${w.message}`;return n.onWarn?.(b),{documentXml:o,hasChanges:!1,status:"ok",warnings:[b]}}for(let b of w.items)b.paragraph,s?._mutationLiveNodes?.push(b.paragraph);for(let b of w.allocatedNumIds)i?.receiptCollector?.recordNumbering(b);rt(e);let y=w.items.filter(b=>!b.inTarget).length;return u(`[List] list-format ${w.mode} (${w.scope}) rebound ${w.items.length} paragraph(s) from numId ${w.sourceNumId} to numId ${w.numId}${y?` (${y} outside the target range)`:""}.`),{documentXml:tt(e,a,o,i),hasChanges:!0,status:"ok",numberingXml:w.numberingXml,list:{mode:w.mode,scope:w.scope,sourceNumId:w.sourceNumId,numId:w.numId,...w.mode==="change-format"?{format:w.format,level:w.level,lvlText:w.lvlText,levelStarts:w.levelStarts}:{continueFrom:w.continueFrom},items:w.items.map(b=>({paragraphIndex:b.paragraphIndex,paragraphId:Ke(b.paragraph),level:b.level,numId:b.numId,sourceNumId:b.sourceNumId,inTarget:b.inTarget})),skipped:w.skipped.map(b=>({paragraphIndex:b.paragraphIndex,reason:b.reason}))}}}var mb=new Set(["body","tc","txbxContent","footnote","endnote","comment","hdr","ftr"]),pb=new Set(["hyperlink","fldSimple","sdt","smartTag","customXml"]),gb=new Set(["rPr","pPrChange","sectPr"]),St=e=>{let t=e?.localName;return t?t.indexOf(":")<0?t:t.replace(/^.*:/,""):String(e?.nodeName||"").replace(/^.*:/,"")},go=e=>e?.nodeType===1&&(!e.namespaceURI||e.namespaceURI===B),jr=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"";function Cm(e,t){let r=[];if(!e)return r;let n=[];for(let o=e.lastChild;o;o=o.previousSibling)n.push(o);for(;n.length;){let o=n.pop();if(o.nodeType===1){o.namespaceURI===B&&o.localName===t&&r.push(o);for(let a=o.lastChild;a;a=a.previousSibling)n.push(a)}}return r}function At(e,t){for(let r=e?.firstChild;r;r=r.nextSibling)if(go(r)&&St(r)===t)return r;return null}function hb(e){let t=At(At(e,"pPr"),"rPr");if(!t)return null;for(let r=t.firstChild;r;r=r.nextSibling){if(!go(r))continue;let n=St(r);if(n==="ins"||n==="moveTo")return"ins";if(n==="del"||n==="moveFrom")return"del"}return null}function wb(e){for(let t=e.parentNode;t;t=t.parentNode)if(mb.has(St(t)))return t;return null}function vb(e,t){let r=t==="rejected"?"ins":"del";for(let n=e.parentNode;n;n=n.parentNode){let o=St(n);if(o==="tr"){if(At(At(n,"trPr"),r))return!0}else if(o==="tc"){let a=t==="rejected"?"cellIns":"cellDel";if(At(At(n,"tcPr"),a))return!0}else if(o==="body")break}return!1}function _m(e){let t=Array.from(e.attributes||[]).filter(n=>!/^xmlns(:|$)/.test(n.name)&&!/(^|:)(rsid\w*|paraId|textId)$/.test(n.name)).map(n=>`${n.name.replace(/^.*:/,"")}=${n.value}`).sort(),r=Array.from(e.childNodes||[]).filter(go).map(_m).sort();return`${St(e)}[${t.join(",")}]{${r.join("")}}`}function yb(e,t){let r=At(e,"pPr"),n=r;if(t==="rejected"){let i=At(r,"pPrChange");i&&(n=At(i,"pPr"))}let o=null,a=[];for(let i of Array.from(n?.childNodes||[]))if(!(!go(i)||gb.has(St(i)))){if(St(i)==="numPr"){o={numId:jr(At(i,"numId"),"val")||null,ilvl:jr(At(i,"ilvl"),"val")||"0"};continue}a.push(_m(i))}return{props:a.sort().join(""),numPr:o}}function bb(e){let t=St(e);if(t==="hyperlink")return`hyperlink:${e.getAttribute?.("r:id")||jr(e,"anchor")||""}`;if(t==="fldSimple")return`fldSimple:${jr(e,"instr").trim()}`;if(t==="sdt"){let r=At(e,"sdtPr");return`sdt:${jr(At(r,"id"),"val")}:${jr(At(r,"tag"),"val")}`}return`${t}:${jr(e,"element")||jr(e,"uri")}`}function Ib(e,t){let r="",n=[],o=(a,i)=>{for(let l=a.firstChild;l;l=l.nextSibling){if(!go(l))continue;let s=St(l);if(s!=="pPr"&&!(t==="rejected"&&(s==="ins"||s==="moveTo"))&&!(t==="accepted"&&(s==="del"||s==="moveFrom"))){if(s==="r"){let c=r.length;if(r+=mr(l,{revisionView:t,boundary:e}),r.length>c)for(let f of i)n.push({key:f,start:c,end:r.length});continue}o(l,pb.has(s)?[...i,bb(l)]:i)}}};return o(e,[]),{text:r,spans:n}}function xb(e){let t=new Map;for(let r of e){let n=t.get(r.key)||[],o=n[n.length-1];o&&o.end>=r.start?o.end=Math.max(o.end,r.end):n.push({...r}),t.set(r.key,n)}return[...t.values()].flat().sort((r,n)=>r.start-n.start||r.end-n.end||(r.key<n.key?-1:1)).map(r=>`${r.key}@${r.start}-${r.end}`)}function jl(e,t="rejected"){if(t!=="rejected"&&t!=="accepted")throw new Error(`Unknown revision view '${t}'.`);let r=Cm(e,"p"),n=t==="rejected"?"ins":"del",o=[],a=new Map;r.forEach((i,l)=>{if(vb(i,t))return;let s=wb(i),c=a.get(s)||null;a.delete(s);let{text:f,spans:u}=Ib(i,t),d=c?c.text.length:0,m={text:(c?.text||"")+f,spans:[...c?.spans||[],...u.map(p=>({...p,start:p.start+d,end:p.end+d}))]};if(hb(i)===n){a.set(s,{...m,paragraph:i,sourceIndex:l});return}o.push(Pm(i,m,t,s,l))});for(let[i,l]of a)!(t==="rejected"&&St(i)==="tc")&&l.text.length===0||o.push(Pm(l.paragraph,l,t,i,l.sourceIndex));return o.sort((i,l)=>i.sourceIndex-l.sourceIndex),Nb(e,r,o),o}function Nb(e,t,r){let n=St(e)==="body"?[e]:Cm(e,"body");for(let o of n){let a=Array.from(o.childNodes||[]).filter(l=>go(l)&&St(l)!=="sectPr"),i=a[a.length-1];!i||St(i)!=="tbl"||r.push({text:"",props:"",numPr:null,wrappers:[],container:"body",sourceIndex:t.length,implicit:!0})}}function Pm(e,t,r,n,o){let{props:a,numPr:i}=yb(e,r);return{text:t.text,props:a,numPr:i,wrappers:xb(t.spans),container:n?St(n):"root",sourceIndex:o}}var Om=Object.freeze(["enforce","warn","off"]),Bm="enforce",Wl=5,km=120,Rn=Object.freeze({REJECT_PARAGRAPH_COUNT:{explanation:"Reject All of the output has a different number of paragraphs than the source: a paragraph was created or removed without a tracked paragraph mark.",retry:"Target one paragraph at a time; add new paragraphs with a separate insertion instead of folding them into a replacement; do not merge or split paragraphs in the same operation as a text edit."},REJECT_PARAGRAPH_TEXT:{explanation:"Reject All of the output shows different paragraph text than the source: text, a tab or a manual line break changed without being tracked, or was reordered.",retry:"Use replacements (find/replace) for a small literal change, keep manual line breaks and tabs where they are, and retry with the exact current paragraph text from a fresh extraction."},REJECT_PARAGRAPH_PROPS:{explanation:"Reject All of the output shows different paragraph properties (style, alignment, spacing, indentation) than the source: a property changed without a tracked w:pPrChange.",retry:"Change paragraph formatting with a separate paragraph-format operation and keep the text edit free of style or list changes."},REJECT_NUMBERING_REFS:{explanation:"Reject All of the output puts a source paragraph in a different list or list level (numId/ilvl) than the source, so the restored document would number differently.",retry:"Edit list item text without changing list markers or indentation, and make list membership or level changes in their own operation."},ACCEPT_NEIGHBORS:{explanation:"An untracked edit changed a paragraph outside its target, so the change could not be reviewed or undone.",retry:"Re-extract the target and retry against exactly that paragraph; if the edit must span several paragraphs, use a tracked operation with an explicit targetEnd range."},UNTRACKED_CREATED_REVISION:{explanation:"An untracked edit (generateRedlines: false) created a tracked revision (w:ins, w:del, a move, a property change or a paragraph-mark revision) that was not in the source, so the edit is not the plain change the caller asked for.",retry:"Retry the same edit against the current extraction; if it is refused again the untracked path wrote a tracked revision, so report the operation instead of working around it, or make the edit tracked (generateRedlines: true) if a reviewable change is acceptable."},ACCEPT_INTENT:{explanation:"Accept All of the target of the operation would not read as the complete replacement text the operation declared: content was lost, duplicated or left out of the accepted result.",retry:"Re-extract the target paragraph(s) and retry with the exact current text as the basis; for a small literal change use replacements instead of complete modified text, and keep list, table and Markdown structure out of a plain-text edit."},REJECT_WRAPPERS:{explanation:"Reject All of the output moves text into or out of a hyperlink, field or content control compared with the source.",retry:"Keep the change entirely inside or entirely outside the hyperlink, field or content control, for example with replacements that do not cross its boundary."}});function ho(e){if(e==null)return null;let t=typeof e=="string"?e:JSON.stringify(e);return t.length>km?`${t.slice(0,km-3)}...`:t}function wo(e){return e?{sourceParagraphIndex:e.sourceIndex+1,container:e.container,text:ho(e.text)}:null}function Kl(e){return{document:e,accepted:null,rejected:null,revisionSignatures:null,numberingRefs:null}}function Pn(e,t,r){return e?e[r]||(e[r]=jl(t,r)):jl(t,r)}function Fm({before:e,after:t,baselineView:r="rejected",acceptedScope:n=null,beforeViews:o=null,afterViews:a=null}){let i=Array.isArray(t)?t:Pn(a,t,"rejected"),l=Array.isArray(e)?e:Pn(o,e,"rejected"),s=r==="accepted"&&!Array.isArray(e)?Eb(l,Pn(o,e,"accepted"),i,n):l,c=[],f=(u,d,m,p,g,h)=>{c.push({invariant:u,paragraph:d,expected:ho(m),actual:ho(p),explanation:Rn[u].explanation,source:wo(g),output:wo(h)})};if(s.length!==i.length){let u=0;for(;u<s.length&&u<i.length&&da(s[u],i[u]);)u++;return f("REJECT_PARAGRAPH_COUNT",u+1,`${s.length} paragraphs`,`${i.length} paragraphs`,s[u]||s[s.length-1],i[u]||i[i.length-1]),{ok:!1,violations:c,afterProjection:i}}for(let u=0;u<s.length&&c.length<Wl;u++){let d=s[u],m=i[u],p=u+1;d.container!==m.container?f("REJECT_PARAGRAPH_COUNT",p,`paragraph in ${d.container}`,`paragraph in ${m.container}`,d,m):d.text!==m.text?f("REJECT_PARAGRAPH_TEXT",p,d.text,m.text,d,m):(d.numPr?.numId??null)!==(m.numPr?.numId??null)||(d.numPr?.ilvl??null)!==(m.numPr?.ilvl??null)?f("REJECT_NUMBERING_REFS",p,d.numPr,m.numPr,d,m):d.props!==m.props?f("REJECT_PARAGRAPH_PROPS",p,d.props,m.props,d,m):d.wrappers.join("|")!==m.wrappers.join("|")&&f("REJECT_WRAPPERS",p,d.wrappers,m.wrappers,d,m)}return c.length?{ok:!1,violations:c,afterProjection:i}:{ok:!0,afterProjection:i}}var da=(e,t)=>e.text===t.text&&e.props===t.props&&e.container===t.container&&(e.numPr?.numId??null)===(t.numPr?.numId??null)&&(e.numPr?.ilvl??null)===(t.numPr?.ilvl??null)&&e.wrappers.join("|")===t.wrappers.join("|");function $m({before:e,after:t,targetSourceIndex:r,beforeViews:n=null,afterViews:o=null}){let a=[];for(let i of["accepted","rejected"]){let l=Pn(n,e,i),s=Pn(o,t,i),c=l.findIndex(m=>m.sourceIndex>=r);if(c<0)continue;let f=l.length-c-1,u=0;for(;u<c&&u<s.length&&da(l[u],s[u]);)u++;let d=0;for(;d<f&&d<s.length-u&&da(l[l.length-1-d],s[s.length-1-d]);)d++;if(u<c)a.push(Lm(u+1,l[u],s[u],i));else if(d<f){let m=l.length-1-d;a.push(Lm(m+1,l[m],s[s.length-1-d],i))}if(a.length)break}return a.length?{ok:!1,violations:a}:{ok:!0}}function Dm({before:e,after:t,numberingXmls:r,beforeViews:n=null,afterViews:o=null}){let a=d=>{let m=new Map;for(let p of kn(d)){let g=p.getAttribute("w:val");if(g===null||g===""||g==="0")continue;let v=Array.from(p.parentNode?.childNodes||[]).find(w=>w.nodeType===1&&_i(w)==="ilvl")?.getAttribute("w:val")||"0";m.has(g)||m.set(g,new Set),m.get(g).add(v)}return m},i=a(t);if(i.size===0)return{ok:!0};let l=a(e),s=(r||[]).filter(Boolean).join(`
|
|
231
|
-
`),
|
|
232
|
-
`),m=p=>p.replace(/\r?\n/g,"");return d===n||m(d)===m(n)?{ok:!0}:{ok:!1,violations:[{invariant:"ACCEPT_INTENT",paragraph:null,expected:n,actual:d,explanation:Rn.ACCEPT_INTENT.explanation,source:f[0]?wo(f[0]):null,output:u[0]?wo(u[0]):null}]}}var Sb=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","sectPrChange","tblPrChange","tblGridChange","tblPrExChange","trPrChange","tcPrChange","numberingChange","cellIns","cellDel","cellMerge"]),_i=e=>e.localName||String(e.nodeName).replace(/^.*:/,"");function Mm(e){let t=new Map,r=[e];for(;r.length;){let n=r.pop();if(n.nodeType===1&&Sb.has(_i(n))){let o=n.getAttribute("w:id");o!==null&&!t.has(o)&&t.set(o,n)}for(let o=n.firstChild;o;o=o.nextSibling)r.push(o)}return t}function Xm({before:e,after:t,beforeViews:r=null,afterViews:n=null}){let o=f=>`${_i(f)}|${f.getAttribute("w:author")}|${f.getAttribute("w:date")}`,a=f=>new Map([...f].map(([u,d])=>[u,o(d)])),i=r?.revisionSignatures;i||(i=a(Mm(e)),r&&(r.revisionSignatures=i));let l=Mm(t);n&&(n.revisionSignatures=a(l));let s=new Set(i.values()),c=[];for(let[f,u]of l){if(i.has(f)||s.has(o(u)))continue;let d=_i(u),m=u.getAttribute("w:author"),p=ho(u.textContent||"");if(c.push({invariant:"UNTRACKED_CREATED_REVISION",paragraph:null,expected:"no new revisions",actual:`w:${d} w:id=${f}${m?` by ${m}`:""}${p?` ("${p}")`:""}`,explanation:Rn.UNTRACKED_CREATED_REVISION.explanation,source:null,output:null}),c.length>=Wl)break}return c.length?{ok:!1,violations:c}:{ok:!0}}function Lm(e,t,r,n){return{invariant:"ACCEPT_NEIGHBORS",paragraph:e,view:n,expected:ho(t?.text??null),actual:ho(r?.text??null),explanation:Rn.ACCEPT_NEIGHBORS.explanation,source:wo(t),output:wo(r)}}function Eb(e,t,r,n){if(n&&Number.isInteger(n.from)&&Number.isInteger(n.to)){let c=f=>f.sourceIndex>=n.from&&f.sourceIndex<=n.to;return[...e.filter(f=>!c(f)),...t.filter(c)].sort((f,u)=>f.sourceIndex-u.sourceIndex)}let o=0;for(;o<e.length&&o<r.length&&da(e[o],r[o]);)o++;let a=0;for(;a<e.length-o&&a<r.length-o&&da(e[e.length-1-a],r[r.length-1-a]);)a++;if(o+a===e.length&&o+a===r.length)return e;let i=o>0?e[o-1].sourceIndex:-1,l=a>0?e[e.length-a].sourceIndex:1/0,s=t.filter(c=>c.sourceIndex>i&&c.sourceIndex<l);return[...e.slice(0,o),...s,...e.slice(e.length-a)]}function Gl(e,t={}){let r=e[0],n=r.source?`source paragraph ${r.source.sourceParagraphIndex}${r.source.text?` ("${r.source.text}")`:""}`:`paragraph ${r.paragraph} of the Reject All view`,o=[...new Set(e.map(i=>i.invariant))],a=t.mode||Bm;return{code:"REVISION_FIDELITY_VIOLATION",stage:"verification",message:`${a==="warn"?"Applied with a fidelity warning":"Refused, document unchanged"}: `+(r.invariant==="UNTRACKED_CREATED_REVISION"?`this untracked operation created a tracked revision (${r.invariant}: `:r.invariant==="ACCEPT_NEIGHBORS"?`this untracked operation changed a paragraph outside its target (${r.invariant} in the ${r.view} view at ${n}: `:r.invariant==="ACCEPT_INTENT"?`Accept All of this operation's target would not read as the requested text (${r.invariant} at ${n}: `:`Reject All of this operation's output would not restore the source (${r.invariant} at ${n}: `)+(r.invariant==="UNTRACKED_CREATED_REVISION"?`found ${r.actual}). `:`expected ${JSON.stringify(r.expected)}, got ${JSON.stringify(r.actual)}). `)+`${r.explanation} Retry: ${Rn[r.invariant].retry}`,violations:e,invariants:o,verificationMode:a,...t.baselineView==="accepted"?{baselineView:"accepted"}:{},recovery:{hint:Rn[r.invariant].retry,retryGuidance:o.map(i=>({invariant:i,retry:Rn[i].retry})),reportIfNarrowRetryFails:"If a narrower operation on the same paragraph is also refused, the shape is unsupported: report the violations with the operation; do not disable verification to force it through."}}}function Hl(e){return String(e||"").startsWith("accept-all-first")?"accepted":"rejected"}function ql(e){if(Om.includes(e))return e;let t=globalThis.process?.env?.DOCX_REDLINE_REVISION_FIDELITY;return Om.includes(t)?t:Bm}function Ne(e,t={}){return ht(e,t)}async function Yl(e,t,r,n=null,o={}){let a=typeof o._operationIndex=="number"?o._operationIndex:1,i={operationIndex:a,...typeof t?.operationId=="string"?{operationId:t.operationId}:{}},l=Ir(t);if(!l.valid){let x=Dt(t,r,oe());return{documentXml:e,hasChanges:!1,status:"error",error:Ne(l.error,i),operationType:Nt(t).operationKind,authorUsed:x,receipt:Oe(a,t?.operationId,x,"refused")}}let s=l.operation||Nt(t),c=Dt(s,r,oe());if(s.operationKind!=="comment_reply"&&s.operationKind!=="comment_resolve"&&s.operationKind!=="rejected-insert"&&s.operationKind!=="restore"&&(s.targetDescriptor?.revisionView==="rejected"||s.targetEndDescriptor?.revisionView==="rejected"))return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"UNSUPPORTED_REVISION_VIEW_MUTATION",message:"Targeting rejected revision view for mutation is not supported yet."},i),operationType:s.operationKind,authorUsed:c,receipt:Oe(a,s.operationId,c,"refused")};if(!o?._documentOperationSession&&o?.expectedRevision){let x=hn(o.expectedRevision);if(!x.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:x.error?.code||"INVALID_REVISION_TOKEN",message:x.error?.message||"Invalid revision token."},i),operationType:s.operationKind,authorUsed:c,receipt:Oe(a,s.operationId,c,"refused")};if(o.expectedRevision.scope!=="document-parts")return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'document-parts', got '${o.expectedRevision.scope}'.`},i),operationType:s.operationKind,authorUsed:c,receipt:Oe(a,s.operationId,c,"refused")};let T=await Jo({documentXml:e,commentsXml:n?.commentsXml||o.commentsXml,commentsExtendedXml:n?.commentsExtendedXml||o.commentsExtendedXml,numberingXml:n?.numberingXml||o.numberingXml,stylesXml:n?.stylesXml||o.stylesXml},o);if(!wn(T.value,o.expectedRevision.value))return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${o.expectedRevision.value}', current is '${T.value}'.`,expectedRevision:o.expectedRevision,currentRevision:T},i),operationType:s.operationKind,authorUsed:c,receipt:Oe(a,s.operationId,c,"refused")}}let f=o?._documentOperationSession instanceof Xr?o._documentOperationSession:new Xr(e,o);if(!f.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ne(f.parseResult.error,i),warnings:f.parseResult.warnings,operationType:s.operationKind,authorUsed:c,receipt:Oe(a,s.operationId,c,"refused")};if(Array.isArray(s.replacements)||s.operationKind==="restore"&&t?.modified===void 0){let x=uo(f.document,[t],{strictTargets:o.strictTargets!==!1,onInfo:o.onInfo,onWarn:o.onWarn}),T=x.bindings[0]?.error||x.conflicts[0]||null;if(T)return{documentXml:e,hasChanges:!1,status:"error",error:Ne(T,i),operationType:s.operationKind,authorUsed:c,receipt:Oe(a,s.operationId,c,"refused")};let A=Ir(x.compiledOperations[0]);if(!A.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ne(A.error,i),operationType:s.operationKind,authorUsed:c,receipt:Oe(a,s.operationId,c,"refused")};f.sourceTargetRegistry=x.registry,s=A.operation}if(Array.isArray(s.replacements)&&!s._localizedReplacementCompilation)return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"PATCH_ROUNDTRIP_MISMATCH",stage:"validation",message:"Localized replacements were not compiled against a batch-start paragraph target, so they were refused instead of applied."},i),operationType:s.operationKind,authorUsed:c,receipt:Oe(a,s.operationId,c,"refused")};let u={},d=null,m=f.createSavepoint(),p=f._fidelityViews?.document===f.document?f._fidelityViews:null;f._fidelityViews=null;let g={...p||Kl(null),document:m.document},h=Kl(f.document);f.receiptCollector?.beginOperation(a,s.operationId,c);let v=Array.isArray(s._compiledWarnings)?[...s._compiledWarnings]:[],w={...o,...typeof s.generateRedlines=="boolean"?{generateRedlines:s.generateRedlines}:{},...s.existingRevisions?{existingRevisions:s.existingRevisions}:{},structuredContent:typeof s.structuredContent=="boolean"?s.structuredContent:o.structuredContent!==!1,explicitStructuredContent:s.structuredContent===!0,...s._localizedReplacementCompilation&&s.structuredContent!==!0?{literalTextEdit:!0}:{},pairReplacements:typeof s.pairReplacements=="boolean"?s.pairReplacements:o.pairReplacements!==!1,...s.insertionAffinity?{insertionAffinity:s.insertionAffinity}:{},...s.listMarkers?{listMarkers:s.listMarkers}:{},...s.formattingRevisionPolicy?{formattingRevisionPolicy:s.formattingRevisionPolicy}:{},...s.operationKind==="format"&&Number.isInteger(s.textOccurrence)?{textOccurrence:s.textOccurrence}:{},targetDescriptor:s.targetDescriptor,targetEndDescriptor:s.targetEndDescriptor,_compiledSourceId:s._compiledSourceId||null,_compiledSourceEndId:s._compiledSourceEndId||null,...s.operationKind==="list-format"&&s.list?.continueFrom&&typeof s.list.continueFrom=="object"?{continueFromDescriptor:xn(s.list.continueFrom,null,"accepted"),_compiledContinueFromId:s._compiledContinueFromId||null}:{},_compiledResolvedBy:s._compiledResolvedBy||null,_sourceTargetRegistry:f.sourceTargetRegistry||null,_resolutionCapture:u,_revisionIdAllocator:f.revisionIdAllocator,_documentOperationSession:f,_mutationLiveNodes:[],_mutationRemovedNodes:[],onInfo:x=>{typeof o?.onInfo=="function"&&o.onInfo(x)},onWarn:x=>{v.push(String(x)),typeof o?.onWarn=="function"&&o.onWarn(x)}},y=!!(s.targetEndDescriptor||s.targetEndRef),b=ql(o.verifyRevisionFidelity),I=Hl(w.existingRevisions)==="accepted",E=s.operationKind==="redline"&&w.generateRedlines!==!1&&!s._localizedReplacementCompilation&&s.structuredContent!==!0&&Um(s.modified)&&!/\r?\n/.test(String(s.targetDescriptor?.exactText??s.targetDescriptor?.text??(typeof s.target=="string"?s.target:""))),N=b!=="off"&&f.document&&(y&&I||E)?wm(f.document,s.target,s.targetRef,s.targetEndRef,n,w):null,R=N?N.to:null;try{let x;if(s.operationKind==="comment_reply"){let S=f.commentsXml||n?.commentsXml||o.commentsXml,O=f.commentsExtendedXml||n?.commentsExtendedXml||o.commentsExtendedXml,C=typeof o.commentIdAllocator=="function"?o.commentIdAllocator():null;if(C==null&&S){let P=[...S.matchAll(/<(?:w:)?comment\b[^>]*\b(?:w:)?id=["'](\d+)["']/g)].map(M=>Number(M[1]));C=(P.length?Math.max(...P):-1)+1}C==null?x={documentXml:e,hasChanges:!1,status:"error",error:{code:"COMMENTS_PART_MISSING",message:"A comment reply requires an existing comments part."}}:(x=Qs({commentsXml:S,commentsExtendedXml:O,documentXml:e,parentCommentId:s.parentCommentId,commentId:C,commentContent:s.commentContent,author:c,date:s.date||new Date().toISOString()}),x.documentXml=e,x.status!=="error"&&x.hasChanges&&(!f.document||!Of(f.document,x.threadCommentIds,C)?x={documentXml:e,hasChanges:!1,status:"error",error:{code:"PARENT_ANCHOR_NOT_FOUND",message:`Comment '${s.parentCommentId}' has no anchor in the document body, so a reply cannot be placed.`}}:f.receiptCollector&&f.receiptCollector.recordComment(C)))}else if(s.operationKind==="comment_resolve"){let S=ii({commentsXml:f.commentsXml||n?.commentsXml||o.commentsXml,commentsExtendedXml:f.commentsExtendedXml||n?.commentsExtendedXml||o.commentsExtendedXml,commentId:s.commentId,resolved:s.resolved!==!1});x=S.status==="error"?{documentXml:e,hasChanges:!1,status:"error",error:S.error}:{documentXml:e,hasChanges:S.hasChanges,...S.commentsXml?{commentsXml:S.commentsXml,commentsXmlMode:"replace"}:{},...S.commentsExtendedXml?{commentsExtendedXml:S.commentsExtendedXml,commentsExtendedXmlMode:"replace"}:{},resolved:S.resolved,threadRootId:S.threadRootId,commentIds:S.commentIds}}else s.operationKind==="highlight"?x=await Nm(e,s.target,s.textToHighlight,s.color,c,s.targetRef,n,w):s.operationKind==="comment"?x=await Tm(e,s.target,s.textToComment,s.commentContent,c,s.targetRef,n,w):s.operationKind==="format"?x=await Am(e,s.target,s.textToFormat,s.properties,c,s.targetRef,n,w):s.operationKind==="paragraph-format"?x=await Sm(e,s.target,s.properties,c,s.targetRef,n,w):s.operationKind==="list-format"?x=await Rm(e,s.target,s.list,c,s.targetRef,s.targetEndRef,n,w):s.operationKind==="rejected-insert"?x=await bm(e,s.target,s.anchor,s.modified,c,s.targetRef,n,w):s.operationKind==="restore"?x=await Im(e,s.target,s.modified,c,s.targetRef,s.targetEndRef,n,w):x=await xm(e,s.target,s.modified,c,s.targetRef,s.targetEndRef,n,w);if((s.operationKind==="comment"||s.operationKind==="comment_reply")&&x?.hasChanges!==!0&&x?.status!=="error"&&!x?.error&&(x={...x,status:"error",error:{code:"COMMENT_NOT_APPLIED",message:"The comment operation completed without placing a comment."}}),v.length>0&&x){let S=Array.from(new Set([...Array.isArray(x.warnings)?x.warnings:[],...v]));x.warnings=S}let T=x?.status==="error"||!!x?.error,A=null;if(T||x?.hasChanges!==!0){f.restoreSavepoint(m);let S=T?"refused":"no_change";if(A=Oe(a,s.operationId,c,S),Array.isArray(x?.warnings))for(let O of x.warnings)A.warnings.push(String(O))}else{let S=kt(m.document),O=kt(f.document),C=Tn(O.issues,S.issues),P=An(C);if(P.length>0){f.restoreSavepoint(m),A=Oe(a,s.operationId,c,"refused");let L=[...new Set(P.map(D=>D.code))].join(", ");return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"GENERATED_OOXML_INVALID",stage:"validation",message:`Operation introduced invalid OOXML (${L}).`,generatedIssues:P},i),operationType:s.operationKind,authorUsed:c,receipt:A,...u}}if(s._localizedReplacementCompilation&&s.structuredContent!==!0){let L=null;if(s.operationKind==="restore"){let D=w._mutationLiveNodes.find(z=>z?.localName==="p");D&&(L=Q(D,{revisionView:"accepted"}))}else if(s._compiledSourceId&&f.sourceTargetRegistry){let D=f.sourceTargetRegistry.previewSuccessor(s._compiledSourceId,w._mutationRemovedNodes,w._mutationLiveNodes);D&&(L=Q(D,{revisionView:"accepted"}))}if(L!==s._localizedReplacementCompilation.desiredText){f.restoreSavepoint(m);let D="The localized replacement did not produce the compiled accepted text, so it was refused before commit to avoid losing content. Re-extract the paragraph and retry with its current text.",z=Oe(a,s.operationId,c,"refused");return z.warnings.push(D),{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"PATCH_ROUNDTRIP_MISMATCH",stage:"validation",message:D},i),warnings:[D],operationType:s.operationKind,authorUsed:c,receipt:z,...u}}}let M=ql(o.verifyRevisionFidelity),_=!s.targetEndDescriptor&&!s.targetEndRef?u.resolvedTarget?.index:null,k=M==="off"?null:w.generateRedlines!==!1?"tracked":Number.isInteger(_)?"untracked":null;if(k==="tracked"){let L=Hl(w.existingRevisions),D=u.resolvedTarget?.index,z=Number.isInteger(D)?y?Number.isInteger(R)&&R>=D-1?{from:D-1,to:R}:null:{from:D-1,to:D-1}:null,W=Fm({before:m.document,after:f.document,baselineView:L,acceptedScope:z,beforeViews:g,afterViews:h}),ee=Dm({before:m.document,after:f.document,numberingXmls:[n?.numberingXml||o.numberingXml,...f.numberingXmlParts||[],x.numberingXml],beforeViews:g,afterViews:h});if(ee.ok||(W.ok=!1,W.violations=[...W.violations||[],...ee.violations]),E&&N){let te=zm({before:m.document,after:f.document,range:N,modified:s.modified,beforeViews:g,afterViews:h});te.ok||(W.ok=!1,W.violations=[...W.violations||[],...te.violations])}if(!W.ok){let te=Gl(W.violations,{mode:M,baselineView:L}),G=`${te.code} (operation ${a}${s.operationId?` "${s.operationId}"`:""}): ${te.message}`;if(typeof o?.onWarn=="function"&&o.onWarn(G),M==="enforce"){f.restoreSavepoint(m),f._fidelityViews=g;let H=Oe(a,s.operationId,c,"refused");return H.warnings.push(G),{documentXml:e,hasChanges:!1,status:"error",error:Ne(te,i),warnings:[G],operationType:s.operationKind,authorUsed:c,receipt:H,...u}}x.warnings=[...Array.isArray(x.warnings)?x.warnings:[],G],x.revisionFidelityViolations=W.violations}}else{let L=k==="untracked"?$m({before:m.document,after:f.document,targetSourceIndex:_-1,beforeViews:g,afterViews:h}):{ok:!0};if(L.ok&&M!=="off"&&w.generateRedlines===!1&&(L=Xm({before:m.document,after:f.document,beforeViews:g,afterViews:h})),!L.ok){let D=Gl(L.violations,{mode:M}),z=`${D.code} (operation ${a}${s.operationId?` "${s.operationId}"`:""}): ${D.message}`;if(typeof o?.onWarn=="function"&&o.onWarn(z),M==="enforce"){f.restoreSavepoint(m),f._fidelityViews=g;let W=Oe(a,s.operationId,c,"refused");return W.warnings.push(z),{documentXml:e,hasChanges:!1,status:"error",error:Ne(D,i),warnings:[z],operationType:s.operationKind,authorUsed:c,receipt:W,...u}}x.warnings=[...Array.isArray(x.warnings)?x.warnings:[],z],x.revisionFidelityViolations=L.violations}}if((k==="tracked"||k==="untracked")&&(f._fidelityViews=h),f.markMutationCommitted(!0),s._compiledSourceId&&f.sourceTargetRegistry&&f.sourceTargetRegistry.commitMutation(s._compiledSourceId,w._mutationRemovedNodes,w._mutationLiveNodes,a),s._localizedReplacementCompilation){let L=null;if(s.operationKind==="restore"){let D=w._mutationLiveNodes.find(z=>z?.localName==="p");D&&(L=Q(D,{revisionView:"accepted"}))}else if(s._compiledSourceId&&f.sourceTargetRegistry){let D=f.sourceTargetRegistry.resolve(s._compiledSourceId,f.document);D.paragraph&&(L=Q(D.paragraph,{revisionView:"accepted"}))}d=fd(s._localizedReplacementCompilation,L,u.resolvedTarget||{},s._speculativeContext||null)}if(s.captureKey&&f.captureTable&&f.captureTable.set(s.captureKey,im(f,s,w._mutationLiveNodes)),w._mutationRemovedNodes?.length>0&&f.captureTable&&sm(f.captureTable,w._mutationRemovedNodes),u.resolvedTarget&&f.receiptCollector?.recordAffectedTarget(u.resolvedTarget),Array.isArray(x.warnings))for(let L of x.warnings)f.receiptCollector?.recordWarning(L);if(A=f.receiptCollector?.commitOperation("applied"),x.documentXml=f.deferSerialization?f.currentDocumentXml:f.serializeCurrent(),!f.deferSerialization&&A){let L=ia({documentXml:x.documentXml,commentsXml:x.commentsXml||null,numberingXml:x.numberingXml||null},[A]);if(!L.valid)return f.restoreSavepoint(m),A.finalDisposition="rolled_back",A.committed=!1,{documentXml:e,hasChanges:!1,status:"error",error:Ne(L.error,i),warnings:[L.error.message],operationType:s.operationKind,authorUsed:c,receipt:A,...u}}}return x?.error&&(x.error=Ne(x.error,i)),{...x,operationType:s.operationKind,authorUsed:c,receipt:A,...d?{change:d}:{},...u}}catch(x){f.restoreSavepoint(m);let T=Ne(x,i),A=Oe(a,s.operationId,c,"refused");return A.warnings.push(T.message),{documentXml:e,hasChanges:!1,status:"error",error:T,warnings:[T.message],operationType:s.operationKind,authorUsed:c,receipt:A,...u}}}var Vm="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function jm(e){return e?.type==="comment"||e?.type==="comment_reply"||e?.type==="comment_resolve"?0:1}function Oi(e=[]){let t=Array.isArray(e)?e:[],r=new Map;for(let c=0;c<t.length;c++){let f=t[c],u=f?.captureKey??f?.targetDescriptor?.captureKey;if(u!=null){if(typeof u!="string"||!u.trim()||u.trim().length>256)return{valid:!1,error:{code:"INVALID_OPERATION",message:`Operation ${c+1} declared an invalid captureKey: must be a non-empty string under 256 characters.`}};let d=u.trim();if(r.has(d)){let m=r.get(d);return{valid:!1,error:{code:"DUPLICATE_CAPTURE_KEY",message:`Duplicate capture key "${d}" declared by operations at indices ${m+1} and ${c+1}.`}}}r.set(d,c)}}let n=new Array(t.length).fill(0),o=Array.from({length:t.length},()=>new Set),a=Array.from({length:t.length},()=>new Set),i=new Map;for(let c=0;c<t.length;c++){let f=t[c],u=f?.target?.captureRef??f?.targetDescriptor?.captureRef;if(u!=null){if(typeof u!="string"||!u.trim()||u.trim().length>256)return{valid:!1,error:{code:"INVALID_OPERATION",message:`Operation ${c+1} referenced an invalid captureRef: must be a non-empty string under 256 characters.`}};let d=u.trim();if(!r.has(d))return{valid:!1,error:{code:"CAPTURE_NOT_FOUND",message:`Capture "${d}" referenced by operation ${c+1} was not found in the batch.`}};let m=r.get(d);if(m===c)return{valid:!1,error:{code:"CAPTURE_DEPENDENCY_CYCLE",message:`Capture dependency cycle detected: operation ${c+1} references its own capture "${d}".`}};a[c].has(m)||(a[c].add(m),o[m].add(c),n[c]++);let p=Nt(f).operationKind;p!=="comment"&&p!=="comment_reply"&&p!=="comment_resolve"&&(i.has(d)||i.set(d,[]),i.get(d).push({index:c,select:f?.target?.select??f?.targetDescriptor?.select??null}))}}for(let c=0;c<t.length;c++){let f=Array.isArray(t[c]?._compiledRunAfter)?t[c]._compiledRunAfter:[];for(let u of f)!Number.isInteger(u)||u<0||u>=t.length||u===c||a[c].has(u)||(a[c].add(u),o[u].add(c),n[c]++)}for(let[c,f]of i){if(f.length<2)continue;let u=f.map(m=>m.select),d=new Set(u);if(!(u.every(m=>typeof m=="string"&&m.length>0)&&d.size===u.length))return{valid:!1,error:{code:"CAPTURE_FANOUT_CONFLICT",message:`Capture "${c}" has overlapping or unscoped mutating consumers at operation indices ${f.map(m=>m.index+1).join(", ")}.`,operationIndexes:f.map(m=>m.index+1),captureRef:c}}}let l=[];for(let c=0;c<t.length;c++)n[c]===0&&l.push({operation:t[c],index:c});let s=[];for(;l.length>0;){l.sort((f,u)=>jm(f.operation)-jm(u.operation)||f.index-u.index);let c=l.shift();s.push(c);for(let f of o[c.index])n[f]--,n[f]===0&&l.push({operation:t[f],index:f})}return s.length<t.length?{valid:!1,error:{code:"CAPTURE_DEPENDENCY_CYCLE",message:"Capture dependency cycle detected among batch operations."}}:{valid:!0,scheduled:s,captureProducers:r}}function Rb(e,t){if(!t)return e;if(!e)return t;let r=j(e,"application/xml")?.doc,n=j(t,"application/xml")?.doc;if(!r||!n)return e;let o=se(),a=r.documentElement,i=new Set(Array.from(r.getElementsByTagNameNS(Vm,"comment")).map(l=>l.getAttribute("w:id")||l.getAttribute("id")).filter(Boolean));for(let l of Array.from(n.getElementsByTagNameNS(Vm,"comment"))){let s=l.getAttribute("w:id")||l.getAttribute("id");s&&i.has(s)||(a.appendChild(r.importNode(l,!0)),s&&i.add(s))}return o.serializeToString(r)}async function ki(e,t,r,n=null,o={}){let a=Array.isArray(t)?t:[],i=oe(),l=()=>a.map((S,O)=>Oe(O+1,S?.operationId,Dt(S,r,i),"not_attempted")),s=(S,O={})=>{let C=l();return{documentXml:e,hasChanges:!1,commentsXml:null,numberingXmlParts:[],results:[],receipts:C,executionOrder:[],authorsUsed:[],...o.atomic===!0?{rolledBack:!0}:{},status:"error",error:Ne(S),retryPlan:br({atomic:o.atomic===!0,rolledBack:o.atomic===!0,results:[],receipts:C,operationCount:a.length}),...O}};if(o.existingRevisions!=null&&!ca(o.existingRevisions))return s({code:"INVALID_OPERATION",message:`Unsupported existingRevisions policy: "${String(o.existingRevisions)}".`,field:"existingRevisions"});if(o?.expectedRevision){let S=hn(o.expectedRevision);if(!S.valid)return s({code:S.error?.code||"INVALID_REVISION_TOKEN",message:S.error?.message||"Invalid revision token."});if(o.expectedRevision.scope!=="document-parts")return s({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'document-parts', got '${o.expectedRevision.scope}'.`,expectedScope:"document-parts",actualScope:o.expectedRevision.scope});let O=await Jo({documentXml:e,commentsXml:n?.commentsXml||o.commentsXml,commentsExtendedXml:n?.commentsExtendedXml||o.commentsExtendedXml,numberingXml:n?.numberingXml||o.numberingXml,stylesXml:n?.stylesXml||o.stylesXml},o);if(!wn(O.value,o.expectedRevision.value))return s({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${o.expectedRevision.value}', current is '${O.value}'.`,expectedRevision:o.expectedRevision,currentRevision:O})}let c=o?._documentOperationSession instanceof Xr?o._documentOperationSession:new Xr(e,{...o,_deferDocumentSerialization:!0});if(!c.valid)return s(c.parseResult.error,{warnings:c.parseResult.warnings});let f=uo(c.document,a,{strictTargets:o.strictTargets!==!1,onInfo:o.onInfo,onWarn:o.onWarn});if(c.sourceTargetRegistry=f.registry,f.conflicts.length>0){let S=new Map;for(let P of f.conflicts)for(let M of P.operationIndexes)S.has(M)||S.set(M,P);let O=Array.from(S,([P,M])=>{let _=a[P-1],k=Dt(_,r,i),L=Ne(M,{operationIndex:P,..._?.operationId?{operationId:_.operationId}:{}});return{index:P,type:_?.type||"redline",operationType:Nt(_).operationKind,status:"error",authorUsed:k,error:L,receipt:Oe(P,_?.operationId,k,"refused")}}).sort((P,M)=>P.index-M.index),C=a.map((P,M)=>O.find(k=>k.index===M+1)?.receipt||Oe(M+1,P?.operationId,Dt(P,r,i),"not_attempted"));return{documentXml:e,hasChanges:!1,commentsXml:null,numberingXmlParts:[],results:O,receipts:C,executionOrder:[],authorsUsed:[],rolledBack:o.atomic===!0,status:"error",error:Ne(f.conflicts[0]),conflicts:f.conflicts.map(P=>Ne(P)),retryPlan:br({atomic:o.atomic===!0,rolledBack:o.atomic===!0,results:O,receipts:C,operationCount:a.length})}}let u=f.compiledOperations,d=Oi(u);if(!d.valid)return s(d.error);let m=d.scheduled,p=o.atomic===!0,g=o.continueOnError!==!1;if(n&&typeof n=="object"&&!n.numberingIdState){let S=typeof n.numberingXml=="string"&&n.numberingXml.trim()?n.numberingXml:void 0;n.numberingIdState=Ht(S)}let h=Ud(n);h.numberingIdState||(h.numberingIdState=Ht(void 0)),h.targetRefSnapshot instanceof Map||(h.targetRefSnapshot=c.initialTargetReferenceSnapshot),c.runtimeContext=h,a.some(S=>S?.type==="comment_reply"||S?.type==="comment_resolve")&&(c.commentsXml=h.commentsXml||o.commentsXml||null,c.commentsExtendedXml=h.commentsExtendedXml||o.commentsExtendedXml||null,c.commentsXmlMode="replace",c.commentsExtendedXmlMode="replace");let v=!1,w=c.results,y=c.executionOrder,b=c.authorsUsed,I=!1;for(let{operation:S,index:O}of m){y.push(O+1);let C=f.bindings[O];if(C?.error){I=!0;let P=Dt(S,r,i),M=Oe(O+1,S?.operationId,P,"refused"),_=Ne(C.error,{operationIndex:O+1,...S?.operationId?{operationId:S.operationId}:{}});if(M.warnings.push(_.message),w.push({index:O+1,type:S?.type||"redline",status:"error",operationType:Nt(S).operationKind,authorUsed:P,warnings:[_.message],error:_,receipt:M}),!g)break;continue}try{let P=await Yl(c.currentDocumentXml,S,r,h,{...o,_documentOperationSession:c,_deferDocumentSerialization:!0,_operationIndex:O+1});v=v||P.hasChanges===!0,c.commentsXml=P.commentsXmlMode==="replace"?P.commentsXml||c.commentsXml:Rb(c.commentsXml,P.commentsXml||null),c.commentsExtendedXml=(P.commentsExtendedXmlMode==="replace",P.commentsExtendedXml||c.commentsExtendedXml),P.commentsXmlMode==="replace"&&(c.commentsXmlMode="replace"),P.commentsExtendedXmlMode==="replace"&&(c.commentsExtendedXmlMode="replace"),P.numberingXml&&c.numberingXmlParts.push(P.numberingXml);let M=P.status==="error"||!!P.error;if(I=I||M,!M&&P.hasChanges&&P.authorUsed&&b.add(P.authorUsed),w.push({index:O+1,type:S?.type||"redline",status:M?"error":P.hasChanges?"applied":"no_change",operationType:P.operationType||"redline",authorUsed:P.authorUsed,...P.resolvedBy?{resolvedBy:P.resolvedBy}:{},...P.resolvedTarget?{resolvedTarget:P.resolvedTarget}:{},...P.resolvedAnchor?{resolvedAnchor:P.resolvedAnchor}:{},...P.change?{change:P.change}:{},...P.list&&!M?{list:P.list}:{},...P.operationType==="comment_resolve"&&!M?{resolved:P.resolved,threadRootId:P.threadRootId,commentIds:P.commentIds}:{},...Array.isArray(P.warnings)&&P.warnings.length>0?{warnings:P.warnings}:{},...Array.isArray(P.diagnostics)&&P.diagnostics.length>0?{diagnostics:P.diagnostics}:{},...P.error?{error:P.error}:{},...P.receipt?{receipt:P.receipt}:{}}),M&&!g)break}catch(P){let M=Ne(P,{operationIndex:O+1,...S?.operationId?{operationId:S.operationId}:{}});I=!0;let _=Dt(S,r,oe()),k=Oe(O+1,S?.operationId,_,"refused");if(k.warnings.push(M.message),w.push({index:O+1,type:S?.type||"redline",status:"error",operationType:Nt(S).operationKind,authorUsed:_,warnings:[M.message],error:M,receipt:k}),!g)break}}w.sort((S,O)=>S.index-O.index);let E=[];for(let S=0;S<a.length;S++){let O=S+1,C=w.find(P=>P.index===O);if(C?.receipt)E.push(C.receipt);else{let P=Oe(O,a[S]?.operationId,Dt(a[S],r,i),"not_attempted");E.push(P)}}let N=p&&I,R=e,x=null;if(!N&&v)try{R=c.serializeCurrent()}catch(S){x=Ne(S),N=!0}let T=null;if(!N&&v){let S=ia({documentXml:R,commentsXml:c.commentsXml,commentsExtendedXml:c.commentsExtendedXml,numberingXmlParts:c.numberingXmlParts},E);S.valid||(T=S.error,p&&(N=!0))}if(N){for(let S of w)S.receipt&&S.receipt.attemptedDisposition==="applied"&&(S.receipt.finalDisposition="rolled_back",S.receipt.committed=!1),S.change&&(S.change.finalDisposition="rolled_back",S.change.committed=!1);for(let S of E)S.attemptedDisposition==="applied"&&(S.finalDisposition="rolled_back",S.committed=!1)}else{for(let S of w)S.receipt&&S.receipt.attemptedDisposition==="applied"&&(S.receipt.committed=!0,S.receipt.finalDisposition="applied"),S.change&&(S.change.finalDisposition="applied",S.change.committed=!0);for(let S of E)S.attemptedDisposition==="applied"&&(S.committed=!0,S.finalDisposition="applied")}N||zd(n,h);let A={documentXml:N?c.rollback():R,hasChanges:N?!1:v,commentsXml:N?null:c.commentsXml,commentsExtendedXml:N?null:c.commentsExtendedXml,commentsXmlMode:c.commentsXmlMode,commentsExtendedXmlMode:c.commentsExtendedXmlMode,numberingXmlParts:N?[]:c.numberingXmlParts,results:[...w].sort((S,O)=>(S.index||0)-(O.index||0)),receipts:E.sort((S,O)=>S.operationIndex-O.operationIndex),executionOrder:y,authorsUsed:N?[]:Array.from(b),...N?{rolledBack:!0,status:"error",error:Ne({code:T?T.code:x?"DOCUMENT_SERIALIZATION_FAILED":"BATCH_OPERATION_FAILED",message:T?.message||x?.message||"Atomic batch rolled back because one or more operations failed."})}:T?{status:"error",error:Ne(T)}:I?{status:v?"partial":"error",error:Ne({code:"BATCH_OPERATION_FAILED",message:"One or more operations failed."})}:{status:"ok"}};return(A.status==="error"||A.status==="partial")&&(A.retryPlan=br({atomic:p,rolledBack:N,results:A.results,receipts:A.receipts,operationCount:a.length})),A}function vo(e,t={}){return ht(e,t)}function Pb(e){return e.operationKind==="list-format"?!0:e.operationKind!=="redline"||typeof e.modified!="string"?!1:e.modified.split(/\r?\n/).some(t=>/^\s*(?:[-+*]|\d+[.)])\s+/.test(t))}function Cb(e,t,r,n,o=null,a="accepted"){let i=o?.byParagraph?.get(t)||null,l=i?null:ae(e),s=i?.text??Q(t,{revisionView:a}),c=Z(n||""),f=Z(s);return{resolvedBy:r,resolvedTarget:{index:i?.index??l.indexOf(t)+1,paragraphId:i?.paragraphId??Ke(t),text:s,fingerprint:i?.fingerprint??_t(t,{text:s,revisionView:a}),inTable:i?.inTable??!!st(t,"tbl"),revisionView:a},matchDiagnostics:{exactTextMatch:typeof n=="string"&&n===s,normalizedTextMatch:!!c&&c===f,suppliedText:n||"",actualText:s,revisionView:a}}}function Wm(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of Array.from(e?.getElementsByTagNameNS?.("*",r)||[])){let o=n.getAttribute("w:id")||n.getAttribute("id");o!==""&&t.add(o)}return Array.from(t).sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function Mi(e,t,r,n={}){if(n.existingRevisions!=null&&!ca(n.existingRevisions))return{valid:!1,status:"error",error:vo({code:"INVALID_OPERATION",message:`Unsupported existingRevisions policy: "${String(n.existingRevisions)}".`}),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let o=j(e,"application/xml");if(o.error||!o.doc)return{valid:!1,status:"error",error:vo(o.error),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let a=o.doc,i={accepted:rr(a,{revisionView:"accepted"}),rejected:null},l=Array.isArray(t)?t:[],s=uo(a,l,{strictTargets:n.strictTargets!==!1,onInfo:n.onInfo,onWarn:n.onWarn}),c=Oi(s.compiledOperations);if(!c.valid)return{valid:!1,status:"error",error:vo(c.error),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let f=n.strictTargets!==!1,u=[],d=new Set,m=!1,p=!1;for(let y=0;y<l.length;y++){let b=l[y],I=s.bindings[y],E=s.compiledOperations[y],N=!I?.error&&E?._localizedReplacementCompilation?E:b,R=Ir(N),x=Nt(b),T=R.operation||x,A=Dt(T,r,oe());if(d.add(A),!R.valid){u.push({index:y+1,type:b?.type||"redline",operationType:T.operationKind,status:"error",authorUsed:A,error:R.error});continue}if(m=m||T.operationKind==="comment"||T.operationKind==="comment_reply",p=p||Pb(T),T.operationKind==="comment_resolve"){let C=String(T.commentId);u.push(n._existingCommentDetails?.[C]?{index:y+1,type:b.type,operationType:T.operationKind,status:"ready",authorUsed:A,resolvedBy:"comment_id",commentId:C}:{index:y+1,type:b.type,operationType:T.operationKind,status:"error",authorUsed:A,error:{code:"COMMENT_NOT_FOUND",message:`Comment '${C}' was not found.`}});continue}if(T.operationKind==="comment_reply"){let C=String(T.parentCommentId),P=n._existingCommentDetails?.[C];u.push(P?{index:y+1,type:b.type,operationType:T.operationKind,status:"ready",authorUsed:A,resolvedBy:"parent_comment",parentCommentId:C}:{index:y+1,type:b.type,operationType:T.operationKind,status:"error",authorUsed:A,error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${C}' was not found.`}});continue}if(T.targetDescriptor?.captureRef){u.push({index:y+1,type:b?.type||"redline",operationType:T.operationKind,status:"deferred",authorUsed:A,resolvedBy:"capture",captureRef:T.targetDescriptor.captureRef,...T.targetDescriptor.select?{select:T.targetDescriptor.select}:{}});continue}if(I?.error){u.push({index:y+1,type:b?.type||"redline",operationType:T.operationKind,status:"error",authorUsed:A,error:I.error});continue}if(I?.createdByOperation){u.push({index:y+1,type:b?.type||"redline",operationType:T.operationKind,status:"deferred",authorUsed:A,resolvedBy:"created_content_dependency",captureRef:I.captureRef,select:T.targetDescriptor.text,createdByOperation:I.createdByOperation});continue}let S=T.targetDescriptor?.revisionView==="rejected"?"rejected":"accepted",O=S==="rejected"?i.rejected||(i.rejected=rr(a,{revisionView:"rejected"})):i.accepted;try{let C;if(I.dynamic)C=an(a,{targetText:T.target,targetRef:T.targetRef,targetDescriptor:T.targetDescriptor,opType:T.operationKind,strictAmbiguity:f,paragraphMetadataIndex:O,metadataIndices:i,onInfo:n.onInfo,onWarn:n.onWarn});else{let H=s.registry.resolve(I.sourceIds[0],a);if(H.error)throw Object.assign(new Error(H.error.message),H.error);C={paragraph:H.paragraph,resolvedBy:I.resolvedBy,warnings:I.warnings}}let P=C.paragraph,M=Cb(a,P,C.resolvedBy,T.target,O,S),_=M.resolvedTarget.text,k=T.operationKind==="comment"?T.textToComment||_:T.operationKind==="highlight"?T.textToHighlight:T.operationKind==="format"?T.textToFormat:null,L=T.operationKind==="comment"&&k!=null?ea(ro(P,{revisionView:S}),k):null,D=k==null||(L?L.found:_.includes(k)),z=Or(P),W=T.existingRevisions||n.existingRevisions||"merge-same-author",te=T.operationKind==="redline"&&T.modified===""?Wm(P):[],G=null;if(T.operationKind==="restore"){let H=T.targetEndRef?sn(a,T.targetRef,T.targetEndRef,{opType:"restore",targetRefSnapshot:n.targetRefSnapshot||null,onInfo:n.onInfo,onWarn:n.onWarn}):[P];if(!T.targetEndRef&&T.targetEndDescriptor){let Re=an(a,{targetText:T.targetEndDescriptor.text,targetRef:T.targetEndDescriptor.index,targetDescriptor:T.targetEndDescriptor,opType:"restore",strictAmbiguity:f,paragraphMetadataIndex:O,metadataIndices:i,onInfo:n.onInfo,onWarn:n.onWarn}),ie=ae(a),Ue=ie.indexOf(P),Ee=ie.indexOf(Re?.paragraph);H=Ue>=0&&Ee>=Ue?ie.slice(Ue,Ee+1):null}let we=Array.isArray(T.modified)?T.modified:[T.modified];if(!H||H[0]!==P||we.length!==H.length)G={code:"RESTORATION_COUNT_MISMATCH",message:"Restoration requires one replacement for every paragraph in a contiguous resolved range."};else for(let Re of H){let ie=nn(Re);if(ie?.code==="UNSUPPORTED_MOVE_REVISION"){G=ie;break}let Ue=$r(Re,A),Ee=Ue.matches?ie||nn(Re):null;if(!Ue.matches){G={code:"RESTORATION_STATE_REQUIRED",message:"Explicit restoration requires a foreign paragraph-mark deletion with every pre-existing content node deleted.",...Ue.ownerAuthor?{ownerAuthor:Ue.ownerAuthor}:{}};break}if(Ee){G=Ee;break}}}else if(!D)G=L?.error||{code:"ANCHOR_NOT_FOUND",message:`Anchor text was not found in target paragraph: "${k}".`};else if(te.length>0){let H=te.map(we=>n._existingCommentDetails?.[we]).filter(Boolean);G={code:"COMMENTED_CONTENT_DELETE",message:"Refusing to delete a paragraph with existing comments. Resolve or explicitly remove the comments before deleting the paragraph.",commentIds:te,...H.length>0?{comments:H}:{}}}else if(T.operationKind==="redline"&&z&&W!=="accept-all-first"&&W!=="accept-all-first-keep-normalized")if(W==="merge-same-author"||W==="slice-cross-author"){let H=qr(P),we=String(A||"").trim().toLowerCase(),Re=H.length>0&&H.every(ie=>ie.trim().toLowerCase()===we);if(!Re&&W==="merge-same-author")G={code:"EXISTING_REVISIONS",message:`Target paragraph contains tracked changes from another author (${H.length?H.join(", "):"unattributed"}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:H,currentPolicy:W};else if(Re){let ie=Wm(P);if(ie.length>0){let Ue=ie.map(Ee=>n._existingCommentDetails?.[Ee]).filter(Boolean);G={code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:ie,...Ue.length>0?{comments:Ue}:{}}}}else(P.getElementsByTagNameNS(B,"moveFrom").length>0||P.getElementsByTagNameNS(B,"moveTo").length>0)&&(G={code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."})}else{let H=P.getElementsByTagNameNS(B,"del").length>0,we=P.getElementsByTagNameNS(B,"moveFrom").length>0||P.getElementsByTagNameNS(B,"moveTo").length>0;H?G={code:"UNSAFE_REVISION_NESTING",message:"Refusing to replace content with pending deletions; nesting revisions is unsafe."}:we?G={code:"UNSAFE_REVISION_NESTING",message:"Refusing to mutate content with move revisions until move lifecycle is designed."}:G={code:"EXISTING_REVISIONS",message:'Target paragraph contains tracked changes and existingRevisions is "reject-input".'}}if(!G&&T.operationKind==="redline"){let H=Wa(P,T.modified,n);H.valid||(G={code:H.code,message:H.message})}u.push({index:y+1,type:b?.type||"redline",operationType:T.operationKind,status:G?"error":"ready",authorUsed:A,...M,anchor:k==null?null:{text:k,found:D,...L?.found?{resolvedBy:L.resolvedBy,start:L.start,end:L.end}:{},...!L?.found&&Array.isArray(L?.error?.candidates)?{candidates:L.error.candidates}:{}},hasRevisions:z,existingRevisions:W,...C?.warnings?.length?{warnings:C.warnings}:{},...G?{error:G}:{}})}catch(C){u.push({index:y+1,type:b?.type||"redline",operationType:T.operationKind,status:"error",authorUsed:A,error:vo(C)})}}let g=s.conflicts,h=u.map(y=>y.error?{...y,error:vo(y.error,{operationIndex:y.index,...l[y.index-1]?.operationId?{operationId:l[y.index-1].operationId}:{}})}:y),v=g.map(y=>vo(y)),w=h.some(y=>y.status==="error");return{valid:!w&&v.length===0,status:!w&&v.length===0?"ok":"error",results:h,conflicts:v,authorsUsed:Array.from(d),requiredArtifacts:{comments:m,numbering:p}}}var ft=Uint8Array,Mt=Uint16Array,oc=Int32Array,Li=new ft([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Bi=new ft([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),ec=new ft([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),qm=function(e,t){for(var r=new Mt(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];for(var o=new oc(r[30]),n=1;n<30;++n)for(var a=r[n];a<r[n+1];++a)o[a]=a-r[n]<<5|n;return{b:r,r:o}},Ym=qm(Li,2),Jm=Ym.b,tc=Ym.r;Jm[28]=258,tc[258]=28;var Zm=qm(Bi,0),_b=Zm.b,Km=Zm.r,rc=new Mt(32768);for(pe=0;pe<32768;++pe)Tr=(pe&43690)>>1|(pe&21845)<<1,Tr=(Tr&52428)>>2|(Tr&13107)<<2,Tr=(Tr&61680)>>4|(Tr&3855)<<4,rc[pe]=((Tr&65280)>>8|(Tr&255)<<8)>>1;var Tr,pe,or=(function(e,t,r){for(var n=e.length,o=0,a=new Mt(t);o<n;++o)e[o]&&++a[e[o]-1];var i=new Mt(t);for(o=1;o<t;++o)i[o]=i[o-1]+a[o-1]<<1;var l;if(r){l=new Mt(1<<t);var s=15-t;for(o=0;o<n;++o)if(e[o])for(var c=o<<4|e[o],f=t-e[o],u=i[e[o]-1]++<<f,d=u|(1<<f)-1;u<=d;++u)l[rc[u]>>s]=c}else for(l=new Mt(n),o=0;o<n;++o)e[o]&&(l[o]=rc[i[e[o]-1]++]>>15-e[o]);return l}),Wr=new ft(288);for(pe=0;pe<144;++pe)Wr[pe]=8;var pe;for(pe=144;pe<256;++pe)Wr[pe]=9;var pe;for(pe=256;pe<280;++pe)Wr[pe]=7;var pe;for(pe=280;pe<288;++pe)Wr[pe]=8;var pe,ga=new ft(32);for(pe=0;pe<32;++pe)ga[pe]=5;var pe,Ob=or(Wr,9,0),kb=or(Wr,9,1),Mb=or(ga,5,0),Lb=or(ga,5,1),Jl=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Jt=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(t&7)&r},Zl=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(t&7)},ac=function(e){return(e+7)/8|0},Qm=function(e,t,r){return(t==null||t<0)&&(t=0),(r==null||r>e.length)&&(r=e.length),new ft(e.subarray(t,r))};var Bb=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Sr=function(e,t,r){var n=new Error(t||Bb[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Sr),!r)throw n;return n},Fb=function(e,t,r,n){var o=e.length,a=n?n.length:0;if(!o||t.f&&!t.l)return r||new ft(0);var i=!r,l=i||t.i!=2,s=t.i;i&&(r=new ft(o*3));var c=function(Ee){var wt=r.length;if(Ee>wt){var Y=new ft(Math.max(wt*2,Ee));Y.set(r),r=Y}},f=t.f||0,u=t.p||0,d=t.b||0,m=t.l,p=t.d,g=t.m,h=t.n,v=o*8;do{if(!m){f=Jt(e,u,1);var w=Jt(e,u+1,3);if(u+=3,w)if(w==1)m=kb,p=Lb,g=9,h=5;else if(w==2){var E=Jt(e,u,31)+257,N=Jt(e,u+10,15)+4,R=E+Jt(e,u+5,31)+1;u+=14;for(var x=new ft(R),T=new ft(19),A=0;A<N;++A)T[ec[A]]=Jt(e,u+A*3,7);u+=N*3;for(var S=Jl(T),O=(1<<S)-1,C=or(T,S,1),A=0;A<R;){var P=C[Jt(e,u,O)];u+=P&15;var y=P>>4;if(y<16)x[A++]=y;else{var M=0,_=0;for(y==16?(_=3+Jt(e,u,3),u+=2,M=x[A-1]):y==17?(_=3+Jt(e,u,7),u+=3):y==18&&(_=11+Jt(e,u,127),u+=7);_--;)x[A++]=M}}var k=x.subarray(0,E),L=x.subarray(E);g=Jl(k),h=Jl(L),m=or(k,g,1),p=or(L,h,1)}else Sr(1);else{var y=ac(u)+4,b=e[y-4]|e[y-3]<<8,I=y+b;if(I>o){s&&Sr(0);break}l&&c(d+b),r.set(e.subarray(y,I),d),t.b=d+=b,t.p=u=I*8,t.f=f;continue}if(u>v){s&&Sr(0);break}}l&&c(d+131072);for(var D=(1<<g)-1,z=(1<<h)-1,W=u;;W=u){var M=m[Zl(e,u)&D],ee=M>>4;if(u+=M&15,u>v){s&&Sr(0);break}if(M||Sr(2),ee<256)r[d++]=ee;else if(ee==256){W=u,m=null;break}else{var te=ee-254;if(ee>264){var A=ee-257,G=Li[A];te=Jt(e,u,(1<<G)-1)+Jm[A],u+=G}var H=p[Zl(e,u)&z],we=H>>4;H||Sr(3),u+=H&15;var L=_b[we];if(we>3){var G=Bi[we];L+=Zl(e,u)&(1<<G)-1,u+=G}if(u>v){s&&Sr(0);break}l&&c(d+131072);var Re=d+te;if(d<L){var ie=a-L,Ue=Math.min(L,Re);for(ie+d<0&&Sr(3);d<Ue;++d)r[d]=n[ie+d]}for(;d<Re;++d)r[d]=r[d-L]}}t.l=m,t.p=W,t.b=d,t.f=f,m&&(f=1,t.m=g,t.d=p,t.n=h)}while(!f);return d!=r.length&&i?Qm(r,0,d):r.subarray(0,d)},Ar=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},ma=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8,e[n+2]|=r>>16},Ql=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var o=r.length,a=r.slice();if(!o)return{t:tp,l:0};if(o==1){var i=new ft(r[0].s+1);return i[r[0].s]=1,{t:i,l:1}}r.sort(function(I,E){return I.f-E.f}),r.push({s:-1,f:25001});var l=r[0],s=r[1],c=0,f=1,u=2;for(r[0]={s:-1,f:l.f+s.f,l,r:s};f!=o-1;)l=r[r[c].f<r[u].f?c++:u++],s=r[c!=f&&r[c].f<r[u].f?c++:u++],r[f++]={s:-1,f:l.f+s.f,l,r:s};for(var d=a[0].s,n=1;n<o;++n)a[n].s>d&&(d=a[n].s);var m=new Mt(d+1),p=nc(r[f-1],m,0);if(p>t){var n=0,g=0,h=p-t,v=1<<h;for(a.sort(function(E,N){return m[N.s]-m[E.s]||E.f-N.f});n<o;++n){var w=a[n].s;if(m[w]>t)g+=v-(1<<p-m[w]),m[w]=t;else break}for(g>>=h;g>0;){var y=a[n].s;m[y]<t?g-=1<<t-m[y]++-1:++n}for(;n>=0&&g;--n){var b=a[n].s;m[b]==t&&(--m[b],++g)}p=t}return{t:new ft(m),l:p}},nc=function(e,t,r){return e.s==-1?Math.max(nc(e.l,t,r+1),nc(e.r,t,r+1)):t[e.s]=r},Gm=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new Mt(++t),n=0,o=e[0],a=1,i=function(s){r[n++]=s},l=1;l<=t;++l)if(e[l]==o&&l!=t)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=e[l]}return{c:r.subarray(0,n),n:t}},pa=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},ep=function(e,t,r){var n=r.length,o=ac(t+2);e[o]=n&255,e[o+1]=n>>8,e[o+2]=e[o]^255,e[o+3]=e[o+1]^255;for(var a=0;a<n;++a)e[o+a+4]=r[a];return(o+4+n)*8},Hm=function(e,t,r,n,o,a,i,l,s,c,f){Ar(t,f++,r),++o[256];for(var u=Ql(o,15),d=u.t,m=u.l,p=Ql(a,15),g=p.t,h=p.l,v=Gm(d),w=v.c,y=v.n,b=Gm(g),I=b.c,E=b.n,N=new Mt(19),R=0;R<w.length;++R)++N[w[R]&31];for(var R=0;R<I.length;++R)++N[I[R]&31];for(var x=Ql(N,7),T=x.t,A=x.l,S=19;S>4&&!T[ec[S-1]];--S);var O=c+5<<3,C=pa(o,Wr)+pa(a,ga)+i,P=pa(o,d)+pa(a,g)+i+14+3*S+pa(N,T)+2*N[16]+3*N[17]+7*N[18];if(s>=0&&O<=C&&O<=P)return ep(t,f,e.subarray(s,s+c));var M,_,k,L;if(Ar(t,f,1+(P<C)),f+=2,P<C){M=or(d,m,0),_=d,k=or(g,h,0),L=g;var D=or(T,A,0);Ar(t,f,y-257),Ar(t,f+5,E-1),Ar(t,f+10,S-4),f+=14;for(var R=0;R<S;++R)Ar(t,f+3*R,T[ec[R]]);f+=3*S;for(var z=[w,I],W=0;W<2;++W)for(var ee=z[W],R=0;R<ee.length;++R){var te=ee[R]&31;Ar(t,f,D[te]),f+=T[te],te>15&&(Ar(t,f,ee[R]>>5&127),f+=ee[R]>>12)}}else M=Ob,_=Wr,k=Mb,L=ga;for(var R=0;R<l;++R){var G=n[R];if(G>255){var te=G>>18&31;ma(t,f,M[te+257]),f+=_[te+257],te>7&&(Ar(t,f,G>>23&31),f+=Li[te]);var H=G&31;ma(t,f,k[H]),f+=L[H],H>3&&(ma(t,f,G>>5&8191),f+=Bi[H])}else ma(t,f,M[G]),f+=_[G]}return ma(t,f,M[256]),f+_[256]},$b=new oc([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),tp=new ft(0),Db=function(e,t,r,n,o,a){var i=a.z||e.length,l=new ft(n+i+5*(1+Math.ceil(i/7e3))+o),s=l.subarray(n,l.length-o),c=a.l,f=(a.r||0)&7;if(t){f&&(s[0]=a.r>>3);for(var u=$b[t-1],d=u>>13,m=u&8191,p=(1<<r)-1,g=a.p||new Mt(32768),h=a.h||new Mt(p+1),v=Math.ceil(r/3),w=2*v,y=function(V){return(e[V]^e[V+1]<<v^e[V+2]<<w)&p},b=new oc(25e3),I=new Mt(288),E=new Mt(32),N=0,R=0,x=a.i||0,T=0,A=a.w||0,S=0;x+2<i;++x){var O=y(x),C=x&32767,P=h[O];if(g[C]=P,h[O]=C,A<=x){var M=i-x;if((N>7e3||T>24576)&&(M>423||!c)){f=Hm(e,s,0,b,I,E,R,T,S,x-S,f),T=N=R=0,S=x;for(var _=0;_<286;++_)I[_]=0;for(var _=0;_<30;++_)E[_]=0}var k=2,L=0,D=m,z=C-P&32767;if(M>2&&O==y(x-z))for(var W=Math.min(d,M)-1,ee=Math.min(32767,x),te=Math.min(258,M);z<=ee&&--D&&C!=P;){if(e[x+k]==e[x+k-z]){for(var G=0;G<te&&e[x+G]==e[x+G-z];++G);if(G>k){if(k=G,L=z,G>W)break;for(var H=Math.min(z,G-2),we=0,_=0;_<H;++_){var Re=x-z+_&32767,ie=g[Re],Ue=Re-ie&32767;Ue>we&&(we=Ue,P=Re)}}}C=P,P=g[C],z+=C-P&32767}if(L){b[T++]=268435456|tc[k]<<18|Km[L];var Ee=tc[k]&31,wt=Km[L]&31;R+=Li[Ee]+Bi[wt],++I[257+Ee],++E[wt],A=x+k,++N}else b[T++]=e[x],++I[e[x]]}}for(x=Math.max(x,A);x<i;++x)b[T++]=e[x],++I[e[x]];f=Hm(e,s,c,b,I,E,R,T,S,x-S,f),c||(a.r=f&7|s[f/8|0]<<3,f-=7,a.h=h,a.p=g,a.i=x,a.w=A)}else{for(var x=a.w||0;x<i+c;x+=65535){var Y=x+65535;Y>=i&&(s[f/8|0]=c,Y=i),f=ep(s,f+1,e.subarray(x,Y))}a.i=i}return Qm(l,0,n+ac(f)+o)};var Ub=function(e,t,r,n,o){if(!o&&(o={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),i=new ft(a.length+e.length);i.set(a),i.set(e,a.length),e=i,o.w=a.length}return Db(e,t.level==null?6:t.level,t.mem==null?o.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,r,n,o)};function rp(e,t){return Ub(e,t||{},0,0)}function np(e,t){return Fb(e,{i:2},t&&t.out,t&&t.dictionary)}var zb=typeof TextDecoder<"u"&&new TextDecoder,Xb=0;try{zb.decode(tp,{stream:!0}),Xb=1}catch{}var ap=new TextEncoder,ip=new TextDecoder("utf-8"),Vb=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e})();function jb(e){let t=4294967295;for(let r=0;r<e.length;r++)t=Vb[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function yo(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof e=="string")return ap.encode(e);throw new TypeError("Invalid binary input: expected Uint8Array, Buffer, or ArrayBuffer.")}function op(e){let t=0;for(let o=0;o<e.length;o++)t+=e[o].length;let r=new Uint8Array(t),n=0;for(let o=0;o<e.length;o++)r.set(e[o],n),n+=e[o].length;return r}function bo(e){let t=yo(e);if(t.length<22)throw new Error("Invalid DOCX: ZIP end record not found.");let r=new DataView(t.buffer,t.byteOffset,t.byteLength),n=-1,o=Math.max(0,t.length-65535-22);for(let c=t.length-22;c>=o;c--)if(r.getUint32(c,!0)===101010256){n=c;break}if(n<0)throw new Error("Invalid DOCX: ZIP end record not found.");let a=r.getUint16(n+10,!0),i=r.getUint32(n+16,!0);if(a===65535||i===4294967295)throw new Error("Unsupported DOCX: ZIP64 archives are not supported.");let l=new Map,s=i;for(let c=0;c<a;c++){if(s+46>t.length||r.getUint32(s,!0)!==33639248)throw new Error("Invalid DOCX: central directory is corrupt.");let f=r.getUint16(s+8,!0),u=r.getUint16(s+10,!0);if(f&1)throw new Error("Unsupported DOCX: encrypted ZIP entries are not supported.");let d=r.getUint32(s+20,!0),m=r.getUint16(s+28,!0),p=r.getUint16(s+30,!0),g=r.getUint16(s+32,!0),h=r.getUint32(s+42,!0);if(s+46+m>t.length)throw new Error("Invalid DOCX: central directory entry name extends beyond bounds.");let v=ip.decode(t.subarray(s+46,s+46+m));if(h+30>t.length||r.getUint32(h,!0)!==67324752)throw new Error("Invalid DOCX: local entry is corrupt.");let w=r.getUint16(h+26,!0),y=r.getUint16(h+28,!0),b=h+30+w+y;if(b+d>t.length)throw new Error("Invalid DOCX: local entry data extends beyond archive bounds.");let I=t.subarray(b,b+d);if(u!==0&&u!==8)throw new Error(`Unsupported DOCX compression method: ${u}.`);let E=u===8?np(I):new Uint8Array(I);l.set(v,E),s+=46+m+p+g}return l}function sp(e){let t=e instanceof Map?Array.from(e.entries()):Symbol.iterator in Object(e)?Array.from(e):Object.entries(e||{}),r=[],n=[],o=0;for(let[s,c]of t){let f=ap.encode(s),u=yo(c),d=rp(u,{level:9}),m=d.length<u.length?8:0,p=m===8?d:u,g=jb(u),h=new Uint8Array(30),v=new DataView(h.buffer,h.byteOffset,30);v.setUint32(0,67324752,!0),v.setUint16(4,20,!0),v.setUint16(8,m,!0),v.setUint16(12,23585,!0),v.setUint32(14,g,!0),v.setUint32(18,p.length,!0),v.setUint32(22,u.length,!0),v.setUint16(26,f.length,!0),v.setUint16(28,0,!0),r.push(h,f,p);let w=new Uint8Array(46),y=new DataView(w.buffer,w.byteOffset,46);y.setUint32(0,33639248,!0),y.setUint16(4,20,!0),y.setUint16(6,20,!0),y.setUint16(10,m,!0),y.setUint16(14,23585,!0),y.setUint32(16,g,!0),y.setUint32(20,p.length,!0),y.setUint32(24,u.length,!0),y.setUint16(28,f.length,!0),y.setUint16(30,0,!0),y.setUint16(32,0,!0),y.setUint32(42,o,!0),n.push(w,f),o+=h.length+f.length+p.length}let a=op(n),i=new Uint8Array(22),l=new DataView(i.buffer,i.byteOffset,22);return l.setUint32(0,101010256,!0),l.setUint16(8,t.length,!0),l.setUint16(10,t.length,!0),l.setUint32(12,a.length,!0),l.setUint32(16,o,!0),op([...r,a,i])}var Er=class{constructor(t){this.entries=t instanceof Map?t:new Map(Object.entries(t||{}))}file(t,r){if(r!==void 0)return this.entries.set(t,yo(r)),this;let n=this.entries.get(t);return n?{async:async o=>o==="string"?ip.decode(n):new Uint8Array(n)}:null}};var ar=new TextEncoder,dp=new TextDecoder("utf-8"),re=(e,t)=>{let r=e.get(t);return r?typeof r=="string"?r:dp.decode(r):null};function lp(e){let t=kf({commentsXml:re(e,"word/comments.xml"),commentsIdsXml:re(e,"word/commentsIds.xml"),commentsExtensibleXml:re(e,"word/commentsExtensible.xml")});t.commentsIdsXml&&e.set("word/commentsIds.xml",ar.encode(t.commentsIdsXml)),t.commentsExtensibleXml&&e.set("word/commentsExtensible.xml",ar.encode(t.commentsExtensibleXml))}var Io=e=>new Map([...e].map(([t,r])=>[t,new Uint8Array(r)]));function me(e){return typeof Buffer<"u"&&typeof Buffer.from=="function"?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e}function ha(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function cp(e,t){let r=i=>!i||typeof i!="object"?i:i.attemptedDisposition!=="applied"&&i.committed!==!0?{...i}:{...i,committed:!1,finalDisposition:"rolled_back"},n=(e?.receipts||[]).map(r),o=new Map(n.map(i=>[i.operationIndex,i])),a=(e?.results||[]).map(i=>({...i,...i.receipt?{receipt:o.get(i.index)||r(i.receipt)}:{}}));return{results:a,receipts:n,executionOrder:e?.executionOrder||[],authorsUsed:[],rolledBack:!0,retryPlan:br({atomic:!0,rolledBack:!0,results:a,receipts:n,operationCount:t})}}function ic(e){let t;if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer?.(e))t=bo(e);else if(e instanceof Map)t=e;else if(e?.entries instanceof Map)t=e.entries;else if(typeof e?.toUint8Array=="function")t=bo(e.toUint8Array());else if(typeof e?.toBuffer=="function")t=bo(e.toBuffer());else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))t=bo(yo(e));else throw new TypeError("computePackageRevisionToken requires a Uint8Array, Buffer, Map of entries, or DocxDocument.");return Yo({scope:"package",entries:t})}var up=new Set(["comment","comment_reply","comment_resolve"]);function Wb(e){let r=(`${re(e,"word/document.xml")||""} ${re(e,"word/comments.xml")||""}`.match(/(?:w:)?id=["'](\d+)["']/g)||[]).reduce((n,o)=>Math.max(n,Number(o.match(/\d+/)?.[0]||0)),0)+1;return()=>r++}function fp(e){let t=re(e,"word/comments.xml");if(!t)return{};let r=j(t,"application/xml");if(!r.doc||r.error)return{};let n={};for(let o of Array.from(r.doc.getElementsByTagNameNS("*","comment"))){let a=o.getAttribute("w:id")||o.getAttribute("id");a!==""&&(n[a]={id:a,author:o.getAttribute("w:author")||o.getAttribute("author")||"",text:String(o.textContent||"").trim(),paraId:xt(o)||null})}return n}function Ut(e,t,r){let n=me(e);return{status:"error",hasChanges:!1,written:!1,rolledBack:!0,error:ht({code:t,message:r}),retryPlan:br({atomic:!0,rolledBack:!0}),artifactsChanged:[],uint8Array:e,toUint8Array:()=>new Uint8Array(e),buffer:n,toBuffer:()=>me(e)}}var Fi=class{constructor(t){this.originalBytes=yo(t),this.entries=bo(this.originalBytes)}get originalBuffer(){return me(this.originalBytes)}inspect(t={}){let r=t.digestFn||(o=>qo(o)),n=ci({documentXml:re(this.entries,"word/document.xml"),commentsXml:re(this.entries,"word/comments.xml"),commentsExtendedXml:re(this.entries,"word/commentsExtended.xml"),numberingXml:re(this.entries,"word/numbering.xml"),stylesXml:re(this.entries,"word/styles.xml")},{...t,digestFn:r});return n.status==="error"?n:{...n,headersFooters:this.inspectHeadersFooters()}}inspectHeadersFooters(){return ml({documentXml:re(this.entries,"word/document.xml"),relsXml:re(this.entries,"word/_rels/document.xml.rels"),settingsXml:re(this.entries,"word/settings.xml")}).map(t=>{let r=re(this.entries,t.path)||"",n=r?ci({documentXml:r}):{paragraphs:[]};return{...t,hasFields:/<w:fldChar\b|<w:fldSimple\b/.test(r),paragraphs:(n.paragraphs||[]).map(o=>({index:o.index,text:o.text}))}})}getRevisionToken(){return ic(this.entries)}get revisionToken(){return this.getRevisionToken()}preflight(t,r=oe(),n={}){let o=Array.isArray(t)?t:[],a=p=>Mi(re(this.entries,"word/document.xml"),p,r||oe(),{...n,_existingCommentDetails:fp(this.entries)});if(!o.some(p=>p&&typeof p=="object"&&p.part!=null))return a(t);let i=this.inspectHeadersFooters(),l=[],s=[],c=[],f=new Set,u=!0;o.forEach((p,g)=>{if(!p||typeof p!="object"||p.part==null){l.push({operation:p,origIndex:g});return}let h=pl(i,p.part),v=up.has(p.type)?{code:"COMMENT_IN_HEADER_FOOTER",message:"Word does not support comments in headers or footers."}:h.error;if(v){u=!1,s.push({index:g+1,type:p.type||"redline",status:"error",error:ht({...v,operationIndex:g+1})});return}let{part:w,...y}=p,b=Mi(re(this.entries,h.part.path),[y],r||oe(),{...n,_existingCommentDetails:{}});u=u&&b.valid;for(let I of b.results||[])s.push({...I,index:g+1,part:h.part.path});c.push(...b.conflicts||[]);for(let I of b.authorsUsed||[])f.add(I)});let d={comments:!1,numbering:!1};if(l.length){let p=a(l.map(g=>g.operation));u=u&&p.valid;for(let g of p.results||[])s.push({...g,index:l[g.index-1].origIndex+1});c.push(...p.conflicts||[]);for(let g of p.authorsUsed||[])f.add(g);d=p.requiredArtifacts||d}s.sort((p,g)=>p.index-g.index);let m=u&&c.length===0;return{valid:m,status:m?"ok":"error",results:s,conflicts:c,authorsUsed:[...f],requiredArtifacts:d}}toUint8Array(){return sp(this.entries)}toBuffer(){return me(this.toUint8Array())}async applyOperations(t,r={}){let n=Array.isArray(t)?t:[];return n.some(o=>o&&typeof o=="object"&&o.part!=null)?this.applyOperationsWithParts(n,r):this.applyBodyOperations(t,r)}async applyOperationsWithParts(t,r={}){let n=r.author||oe(),o=r.atomic===!0,a=this.entries,i=this.originalBytes,l=t.length,s=()=>{this.entries=a,this.originalBytes=i},c=()=>({uint8Array:i,toUint8Array:()=>new Uint8Array(i),buffer:me(i),toBuffer:()=>me(i)}),f=(_,k=[],L=[],D={})=>({status:"error",hasChanges:!1,written:!1,rolledBack:!0,results:k,receipts:L,executionOrder:[],authorsUsed:[],artifactsChanged:[],error:ht(_),retryPlan:br({atomic:!0,rolledBack:!0,results:k,receipts:L,operationCount:l}),validation:{originalIssues:[],generatedIssues:[]},...D,...c()});if(r.expectedRevision){let _=await this.applyBodyOperations([],{expectedRevision:r.expectedRevision});if(_.status==="error")return _}let u=ml({documentXml:re(this.entries,"word/document.xml"),relsXml:re(this.entries,"word/_rels/document.xml.rels"),settingsXml:re(this.entries,"word/settings.xml")}),d=[],m=[];for(let _=0;_<t.length;_++){let k=t[_];if(!k||typeof k!="object"||k.part==null){d.push({operation:k,origIndex:_});continue}if(up.has(k.type))return f({code:"COMMENT_IN_HEADER_FOOTER",message:`Operation ${_+1}: Word does not support comments in headers or footers.`,operationIndex:_+1});if(k.type==="list-format")return f({code:"INVALID_OPERATION",field:"part",message:`Operation ${_+1}: list-format is body-only in list-format-v1; headers and footers are not supported.`,operationIndex:_+1});let L=pl(u,k.part);if(L.error)return f({...L.error,message:`Operation ${_+1}: ${L.error.message}`,operationIndex:_+1});let{part:D,...z}=k;m.push({operation:z,origIndex:_,part:L.part})}let p=[],g=[],h=[],v=new Set,w=[],y=!1,b=!1,I=null;if(d.length){I=await this.applyBodyOperations(d.map(k=>k.operation),{...r,expectedRevision:void 0});let _=k=>d[k-1]?.origIndex+1;for(let k of I.results||[])p.push({...k,index:_(k.index),...k.receipt?{receipt:{...k.receipt,operationIndex:_(k.receipt.operationIndex)}}:{}});for(let k of I.receipts||[])g.push({...k,operationIndex:_(k.operationIndex)});for(let k of I.executionOrder||[])h.push(_(k));for(let k of I.authorsUsed||[])v.add(k);if(w.push(...I.validation?.originalIssues||[]),(I.status==="error"||I.rolledBack)&&(b=!0,o))return s(),{...I,results:p,receipts:g,executionOrder:h,written:!1,artifactsChanged:[],rolledBack:!0,...c()};y=I.hasChanges===!0}let E=Io(this.entries),N=new Er(E),R=new Set,{expectedRevision:x,...T}=r,A=(_,k)=>{b=!0;let L=ht({...k,operationIndex:_.origIndex+1});p.push({index:_.origIndex+1,type:_.operation.type||"redline",status:"error",authorUsed:n,part:_.part.path,error:L})};for(let _ of m){let k=_.part.path,L=re(E,k);if(!L){if(A(_,{code:"PART_NOT_FOUND",message:`Part '${k}' is referenced but missing from the package.`}),o)break;continue}let D=re(E,"word/numbering.xml"),z=await ki(L,[_.operation],n,{numberingIdState:Ht(D||void 0)},{...T,atomic:!0,strictTargets:r.strictTargets!==!1,_existingCommentDetails:{}}),W=z.results?.[0];if(z.rolledBack||z.status==="error"){if(A(_,W?.error||z.error||{code:"OPERATION_FAILED",message:"Operation failed."}),o)break;continue}if(!z.hasChanges){p.push({...W,index:_.origIndex+1,part:k});continue}if(gl(z.documentXml)>gl(L)){if(A(_,{code:"FIELD_EDIT_REFUSED",message:`The edit would change a field (for example PAGE or NUMPAGES) in ${k}. Word recomputes fields; edit the text around them instead.`}),o)break;continue}let ee=new Set;for(let[H,we]of E)if(!(H===k||!(H==="word/document.xml"||id(H))))for(let Re of sd(dp.decode(we)))ee.add(Re);let te=ld(z.documentXml,ee);E.set(k,ar.encode(te.xml));let G=H=>H?.revisionItems?{...H,revisionItems:H.revisionItems.map(we=>({...we,id:te.idMap.get(String(we.id))??we.id,partName:k}))}:H;z.numberingXmlParts?.length&&await pi(N,z.numberingXmlParts),R.add(k),y=!0,p.push({...W,index:_.origIndex+1,part:k,partSections:_.part.appliesToSections,...W?.receipt?{receipt:{...G(W.receipt),operationIndex:_.origIndex+1}}:{}}),z.receipts?.[0]&&g.push({...G(z.receipts[0]),operationIndex:_.origIndex+1}),h.push(_.origIndex+1);for(let H of z.authorsUsed||[])v.add(H)}let S=[];if(!(o&&b)){for(let _ of R){let k=kt(re(this.entries,_)).issues.map(D=>({source:_,...D})),L=kt(re(E,_)).issues.map(D=>({source:_,...D}));k.push(...Qn(re(this.entries,_),re(this.entries,"word/numbering.xml")).map(D=>({source:_,...D}))),L.push(...Qn(re(E,_),re(E,"word/numbering.xml")).map(D=>({source:_,...D}))),S.push(...An(Tn(L,k)))}if(r.validate!==!1&&R.size)try{await Ur(N)}catch(_){S.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:_.message})}}if(o&&b||S.length){s();let _=S.length?{code:"PACKAGE_OPERATION_FAILED",message:`Applied operations introduced invalid markup (${[...new Set(S.map(D=>D.code))].join(", ")}).`,issues:S}:{code:"BATCH_OPERATION_FAILED",message:"Atomic batch rolled back because one or more operations failed."},k=p.map(D=>D.receipt?{...D,receipt:{...D.receipt,committed:!1,finalDisposition:"rolled_back"}}:D).sort((D,z)=>D.index-z.index),L=g.map(D=>({...D,committed:!1,finalDisposition:"rolled_back"}));return f(_,k,L,{validation:{originalIssues:w,generatedIssues:S},issues:S})}p.sort((_,k)=>_.index-k.index),g.sort((_,k)=>_.operationIndex-k.operationIndex);let O=b?y?"partial":"error":"ok",C=b?{error:ht({code:"BATCH_OPERATION_FAILED",message:"One or more operations failed; the others were applied."})}:{};if(!R.size){let _=me(this.originalBytes);return{...I||{},results:p,receipts:g,executionOrder:h,authorsUsed:[...v],status:O,hasChanges:y,written:I?.written===!0,artifactsChanged:I?.artifactsChanged||[],validation:{originalIssues:w,generatedIssues:[]},...C,uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:_,toBuffer:()=>me(this.originalBytes)}}this.entries=E;let P=this.toUint8Array();this.originalBytes=P;let M=[...E].filter(([_,k])=>!a.has(_)||!ha(k,a.get(_))).map(([_])=>_);return{...I||{},status:O,hasChanges:!0,written:!0,results:p,receipts:g,executionOrder:h,authorsUsed:[...v],artifactsChanged:M,validation:{originalIssues:w,generatedIssues:[]},...C,uint8Array:P,toUint8Array:()=>new Uint8Array(P),buffer:me(P),inspection:this.inspect(),toBuffer:()=>me(P)}}async applyBodyOperations(t,r={}){let n=f=>{let u=[],d=[],m=me(this.originalBytes);return{status:"error",hasChanges:!1,written:!1,rolledBack:!0,results:u,receipts:d,artifactsChanged:[],error:ht(f),retryPlan:br({atomic:!0,rolledBack:!0,results:u,receipts:d,operationCount:Array.isArray(t)?t.length:0}),validation:{originalIssues:[],generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:m,toBuffer:()=>me(this.originalBytes)}};if(r?.expectedRevision){let f=hn(r.expectedRevision);if(!f.valid)return n({code:f.error?.code||"INVALID_REVISION_TOKEN",message:f.error?.message||"Invalid revision token."});if(r.expectedRevision.scope!=="package")return n({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'package', got '${r.expectedRevision.scope}'.`,expectedScope:"package",actualScope:r.expectedRevision.scope});let u=ic(this.entries);if(!wn(u.value,r.expectedRevision.value))return n({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${r.expectedRevision.value}', current is '${u.value}'.`,expectedRevision:r.expectedRevision,currentRevision:u})}let o=this.entries,a=Io(o),i=new Er(a),l=re(a,"word/document.xml"),s=[],c=null;try{if(!l)throw new Error("Missing word/document.xml.");s=kt(l).issues.map(E=>({source:"word/document.xml",...E})),s.push(...Qn(l,re(a,"word/numbering.xml")).map(E=>({source:"word/numbering.xml",...E})));try{await Ur(new Er(Io(o)))}catch(E){s.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:E.message})}let u={numberingIdState:Ht(re(a,"word/numbering.xml")||void 0),stylesXml:re(a,"word/styles.xml"),commentsXml:re(a,"word/comments.xml"),commentsExtendedXml:re(a,"word/commentsExtended.xml")},{expectedRevision:d,...m}=r,p=r.author||oe(),g=c=await ki(l,t,p,u,{...m,atomic:r.atomic===!0,strictTargets:r.strictTargets!==!1,_existingCommentDetails:fp(a),commentIdAllocator:Wb(a)});if(g.rolledBack||g.status==="error"){let E=me(this.originalBytes);return{...g,...cp(g,Array.isArray(t)?t.length:0),written:!1,artifactsChanged:[],validation:{originalIssues:s,generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:E,toBuffer:()=>me(this.originalBytes)}}if(!g.hasChanges){let E=me(this.originalBytes);return{...g,status:g.status||"ok",written:!1,artifactsChanged:[],validation:{originalIssues:s,generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:E,toBuffer:()=>me(this.originalBytes)}}(g.results||[]).some(E=>E?.status!=="error"&&E?.operationType!=="comment_resolve")&&a.set("word/document.xml",ar.encode(g.documentXml)),await pi(i,g.numberingXmlParts);let v=re(a,"word/comments.xml"),w=g.commentsXml||v;if(await dl(i,w,{replaceExisting:g.commentsXmlMode==="replace"||!g.commentsXml&&!!v}),g.commentsExtendedXml&&await gi(i,g.commentsExtendedXml,{replaceExisting:g.commentsExtendedXmlMode==="replace"}),await ao(i),lp(a),r.validate!==!1){let N=kt(g.documentXml).issues.map(T=>({source:"word/document.xml",...T}));N.push(...Qn(g.documentXml,re(a,"word/numbering.xml")).map(T=>({source:"word/numbering.xml",...T})));try{await Ur(i)}catch(T){N.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:T.message})}let R=Tn(N,s),x=An(R);if(x.length){let T=[...new Set(x.map(A=>A.code))].join(", ");throw Object.assign(new Error(`Applied operations introduced invalid revision markup (${T}); these are generated-output issues, not pre-existing input issues.`),{issues:x})}}this.entries=a;let y=this.toUint8Array();this.originalBytes=y;let b=me(y),I=[...a].filter(([E,N])=>!o.has(E)||!ha(N,o.get(E))).map(([E])=>E);return{...g,status:g.status||"ok",written:!0,artifactsChanged:I,validation:{originalIssues:s,generatedIssues:[]},uint8Array:y,toUint8Array:()=>new Uint8Array(y),buffer:b,inspection:this.inspect(),toBuffer:()=>me(y)}}catch(f){this.entries=o;let u=f.issues||[{source:"package",code:"PACKAGE_OPERATION_FAILED",severity:"error",message:f.message}],d=cp(c,Array.isArray(t)?t.length:0),m=me(this.originalBytes);return{...d,status:"error",hasChanges:!1,written:!1,artifactsChanged:[],error:ht({code:"PACKAGE_OPERATION_FAILED",message:f.message,stage:"package",issues:u}),validation:{originalIssues:s,generatedIssues:u},issues:u,uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:m,toBuffer:()=>me(this.originalBytes)}}}async resolveRevisions(t,r={}){let n=t==="accept"?tn:t==="reject"?Fr:null;if(!n)return Ut(this.originalBytes,"INVALID_ACTION",`Unknown revision action: ${t}`);let o=this.originalBytes,a=this.entries,i=Io(this.entries),l=new Er(i),s=n(re(i,"word/document.xml"),{author:r.author,allAuthors:r.allAuthors===!0});if(s.status==="error"||s.error)return Ut(o,s.error?.code||"REVISION_OPERATION_FAILED",s.error?.message||"Revision operation failed.");let c=new Map;for(let m of this.inspectHeadersFooters()){let p=re(i,m.path);if(!p)continue;let g=n(p,{author:r.author,allAuthors:r.allAuthors===!0});if(g.status==="error"||g.error)return Ut(o,g.error?.code||"REVISION_OPERATION_FAILED",`${m.path}: ${g.error?.message||"Revision operation failed."}`);g.hasChanges&&c.set(m.path,g.oxml)}if(!(s.hasChanges||c.size>0)){let m=me(o);return{...s,status:"ok",written:!1,artifactsChanged:[],uint8Array:o,toUint8Array:()=>new Uint8Array(o),buffer:m,toBuffer:()=>me(o)}}s.hasChanges&&i.set("word/document.xml",ar.encode(s.oxml));for(let[m,p]of c)i.set(m,ar.encode(p));try{await ao(l),r.validate!==!1&&await Ur(l)}catch(m){return Ut(o,"PACKAGE_VALIDATION",m.message)}this.entries=i;let u=this.toUint8Array();this.originalBytes=u;let d=me(u);return{...s,status:"ok",written:!0,hasChanges:!0,artifactsChanged:[...i].filter(([m,p])=>!a.has(m)||!ha(p,a.get(m))).map(([m])=>m),uint8Array:u,toUint8Array:()=>new Uint8Array(u),buffer:d,toBuffer:()=>me(u)}}async resolveComment(t,r={}){let n=this.originalBytes,o=Io(this.entries),a=r.resolved!==!1,i=u=>{let d=me(n);return{status:"ok",hasChanges:!1,written:!1,artifactsChanged:[],...u,uint8Array:n,toUint8Array:()=>new Uint8Array(n),buffer:d,toBuffer:()=>me(n)}},l=ii({commentsXml:re(o,"word/comments.xml"),commentsExtendedXml:re(o,"word/commentsExtended.xml"),commentId:t,resolved:a});if(l.status==="error")return Ut(n,l.error.code,l.error.message);if(!l.hasChanges)return i({resolved:a,threadRootId:l.threadRootId,commentIds:l.commentIds});let s=new Er(o);try{l.commentsXml&&o.set("word/comments.xml",ar.encode(l.commentsXml)),await gi(s,l.commentsExtendedXml,{replaceExisting:!0}),await ao(s),r.validate!==!1&&await Ur(s)}catch(u){return Ut(n,"PACKAGE_VALIDATION",u.message)}let c=[...o].filter(([u,d])=>!this.entries.has(u)||!ha(d,this.entries.get(u))).map(([u])=>u);this.entries=o;let f=this.toUint8Array();return this.originalBytes=f,{status:"ok",hasChanges:!0,written:!0,resolved:a,threadRootId:l.threadRootId,commentIds:l.commentIds,artifactsChanged:c,uint8Array:f,toUint8Array:()=>new Uint8Array(f),buffer:me(f),toBuffer:()=>me(f)}}async deleteComments(t={}){let r=this.originalBytes,n=Io(this.entries),o=re(n,"word/comments.xml"),a=me(r);if(!o)return{status:"ok",hasChanges:!1,written:!1,commentsRemoved:0,referencesRemoved:0,artifactsChanged:[],uint8Array:r,toUint8Array:()=>new Uint8Array(r),buffer:a,toBuffer:()=>me(r)};let i=j(o,"application/xml");if(!i.doc||i.error)return Ut(r,"PARSE_ERROR",i.error?.message||"Could not parse comments.xml.");let l=Array.isArray(t.ids)?new Set(t.ids.map(String)):null;if(l){let I=new Set(Array.from(i.doc.getElementsByTagNameNS("*","comment")).map(N=>N.getAttribute("w:id")||N.getAttribute("id"))),E=[...l].filter(N=>!I.has(N));if(E.length)return Ut(r,"COMMENT_NOT_FOUND",`Comment id(s) not found: ${E.join(", ")}.`)}let s=I=>l?l.has(I.getAttribute("w:id")||I.getAttribute("id")):t.allAuthors===!0||(I.getAttribute("w:author")||I.getAttribute("author"))===t.author,c=new Set(Array.from(i.doc.getElementsByTagNameNS("*","comment")).filter(s).map(I=>I.getAttribute("w:id")||I.getAttribute("id")).filter(Boolean));if(!c.size)return{status:"ok",hasChanges:!1,written:!1,commentsRemoved:0,referencesRemoved:0,artifactsChanged:[],uint8Array:r,toUint8Array:()=>new Uint8Array(r),buffer:a,toBuffer:()=>me(r)};let f=re(n,"word/commentsExtended.xml"),u=null,d=new Set;if(f){if(u=j(f,"application/xml"),!u.doc||u.error)return Ut(r,"PARSE_ERROR",u.error?.message||"Could not parse commentsExtended.xml.");let I=new Map;for(let N of Array.from(i.doc.getElementsByTagNameNS("*","comment"))){let R=N.getAttribute("w:id")||N.getAttribute("id"),x=xt(N);x&&I.set(x,R)}for(let[N,R]of I)c.has(R)&&d.add(N);let E=!0;for(;E;){E=!1;for(let N of Array.from(u.doc.getElementsByTagNameNS("*","commentEx"))){let R=(N.getAttribute("w15:paraId")||N.getAttribute("paraId")||"").toUpperCase(),x=(N.getAttribute("w15:paraIdParent")||N.getAttribute("paraIdParent")||"").toUpperCase();x&&d.has(x)&&!d.has(R)&&(d.add(R),I.has(R)&&c.add(I.get(R)),E=!0)}}}let m=l?o:Ss(o,{author:t.author,allAuthors:t.allAuthors===!0}).oxml,p=j(m,"application/xml");if(!p.doc||p.error)return Ut(r,"PARSE_ERROR",p.error?.message||"Could not parse updated comments.xml.");for(let I of Array.from(p.doc.getElementsByTagNameNS("*","comment"))){let E=I.getAttribute("w:id")||I.getAttribute("id");c.has(E)&&I.parentNode?.removeChild(I)}let g=j(re(n,"word/document.xml"),"application/xml");if(!g.doc||g.error)return Ut(r,"PARSE_ERROR",g.error?.message||"Could not parse document.xml.");let h=0;for(let I of["commentRangeStart","commentRangeEnd","commentReference"])for(let E of Array.from(g.doc.getElementsByTagNameNS("*",I))){let N=E.getAttribute("w:id")||E.getAttribute("id");if(!c.has(N)||!E.parentNode)continue;let R=E.parentNode;R.removeChild(E),h+=1,I==="commentReference"&&R.localName==="r"&&!Array.from(R.childNodes||[]).some(x=>x.nodeType===1&&x.localName!=="rPr")&&R.parentNode?.removeChild(R)}let v=se();if(n.set("word/comments.xml",ar.encode(v.serializeToString(p.doc))),u?.doc){for(let I of Array.from(u.doc.getElementsByTagNameNS("*","commentEx"))){let E=(I.getAttribute("w15:paraId")||I.getAttribute("paraId")||"").toUpperCase();d.has(E)&&I.parentNode?.removeChild(I)}n.set("word/commentsExtended.xml",ar.encode(v.serializeToString(u.doc)))}n.set("word/document.xml",ar.encode(v.serializeToString(g.doc)));try{lp(n);let I=new Er(n);await ao(I),t.validate!==!1&&await Ur(I)}catch(I){return Ut(r,"PACKAGE_VALIDATION",I.message)}let w=[...n].filter(([I,E])=>!this.entries.has(I)||!ha(E,this.entries.get(I))).map(([I])=>I);this.entries=n;let y=this.toUint8Array();this.originalBytes=y;let b=me(y);return{status:"ok",hasChanges:!0,written:!0,commentsRemoved:c.size,referencesRemoved:h,artifactsChanged:w,uint8Array:y,toUint8Array:()=>new Uint8Array(y),buffer:b,toBuffer:()=>me(y)}}};function Kb(e){return new Fi(e)}function Gb(e,t){let r=typeof t?.numberingXml=="string"&&t.numberingXml.trim()?t.numberingXml:null,n=t?.numberingIdState&&typeof t.numberingIdState=="object"?t.numberingIdState:r?Ht(r):null;if(!n||!e?.hasChanges||typeof e.oxml!="string"||!e.oxml.includes("/word/numbering.xml"))return e;let o=Xe(e.oxml),a=Array.from(o.getElementsByTagNameNS("*","part")),i=d=>{let p=a.find(g=>(g.getAttribute("pkg:name")||g.getAttribute("name"))===d)?.getElementsByTagNameNS("*","xmlData")[0];return p&&Array.from(p.childNodes).find(g=>g.nodeType===1)||null},l=i("/word/numbering.xml"),s=i("/word/document.xml")?.getElementsByTagNameNS("*","body")[0];if(!l||!s)return e;let c=Array.from(s.childNodes).filter(d=>d.nodeType===1&&d.localName!=="sectPr"),f=fn(Kt(l),c,n),u=o.importNode(Xe(f.numberingXml).documentElement,!0);return l.parentNode.replaceChild(u,l),c.forEach((d,m)=>s.replaceChild(f.replacementNodes[m],d)),{...e,oxml:Kt(o)}}async function mp(e,t,r,n={}){let o=await Bo(e,t,r,n),a=Gb(o,n);if(a?.useNativeApi&&typeof a?.oxml!="string"){let i=Array.isArray(a?.warnings)?a.warnings:[];return Pe({...a,oxml:e,hasChanges:!1,warnings:[...i,"Standalone mode cannot execute native Word API fallback for this operation."]})}return a}async function SP(e,t,r,n={}){let o=typeof e=="string"?e:"",a=typeof r=="string"?r:String(r||""),i;try{i=vt(a)}catch{i={headers:[],rows:[]}}return(i?.headers?.length||0)>0||(i?.rows?.length||0)>0?{...await mp(o,t||"",a,n),isMarkdownTable:!0,tableData:i}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}async function EP(e,t,r,n={}){let o=n.listFallbackAllowExistingList!==!1,a=n.sanitizeInput===!0?Ps(r):r,i=a!==r?["Input was sanitized; pass sanitizeInput: false to disable."]:[],l=un({oxml:e,originalText:t,modifiedText:a,allowExistingList:o}),s=n.preferListStructuralFallback!==!1,c=[];if(l&&s){let g=await Yn(l,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(g?.hasChanges&&g?.oxml){let h=_r(g.oxml,{includeNumbering:g.includeNumbering??!0,numberingXml:g.numberingXml}),v=Array.isArray(g?.warnings)?g.warnings:[];return Pe({oxml:h,hasChanges:!0,warnings:[...i,...v],listStructuralFallbackApplied:!0,listStructuralFallbackKey:g.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:g.numberingXml||null})}c=Array.isArray(g?.warnings)?g.warnings:[]}let f=await mp(e,t,r,n);if(!l)return{...f,warnings:[...Array.isArray(f?.warnings)?f.warnings:[],...c],listStructuralFallbackApplied:!1};if(s)return{...f,warnings:[...Array.isArray(f?.warnings)?f.warnings:[],...c],listStructuralFallbackApplied:!1};if(f?.hasChanges)return{...f,listStructuralFallbackApplied:!1};let u=await Yn(l,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(!u?.hasChanges||!u?.oxml){let g=Array.isArray(f?.warnings)?f.warnings:[],h=Array.isArray(u?.warnings)?u.warnings:[];return{...f,warnings:[...g,...h],listStructuralFallbackApplied:!1}}let d=_r(u.oxml,{includeNumbering:u.includeNumbering??!0,numberingXml:u.numberingXml}),m=Array.isArray(f?.warnings)?f.warnings:[],p=Array.isArray(u?.warnings)?u.warnings:[];return Pe({...f,oxml:d,hasChanges:!0,warnings:[...m,...c,...p],listStructuralFallbackApplied:!0,listStructuralFallbackKey:u.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:u.numberingXml||null})}export{On as ContainerKind,bc as ContentType,Lt as DiffOp,Fi as DocxDocument,B as NS_W,ur as NumberingService,aa as ReceiptCollector,Po as ReconciliationPipeline,io as RoutePlanKind,q as RunKind,ue as WORD_MAIN_NS,tn as acceptTrackedChangesInOoxml,Ko as allocateNumberingDefinition,Xs as allocateNumberingForReplacement,Ta as analyzeStructuredContent,Qs as applyCommentReplyToParts,uv as applyFormattingRemovalToOoxml,el as applyHighlightToOoxml,mp as applyRedlineToOxml,EP as applyRedlineToOxmlWithListFallback,xf as applyStartOverridesToNum,wn as areRevisionTokensEqual,Ho as buildCommentElement,Ws as buildCommentsPartXml,ei as buildExplicitDecimalMultilevelNumberingXml,fw as buildListMarkdown,bv as buildReconciliationPlan,Ys as buildRevisionTokenFraming,un as buildSingleLineListStructuralFallbackPlan,Os as buildTargetReferenceSnapshot,Ow as canonicalNumberingDefinition,zo as clearSingleLineListFallbackExplicitSequence,ff as collectContiguousListParagraphBlock,Jo as computeDocumentPartsRevisionToken,ic as computePackageRevisionToken,Lf as computeRevisionToken,Yo as computeRevisionTokenSync,Np as configureLogger,Sp as configureXmlProvider,Or as containsTrackedChanges,Mw as copyLevelGeometry,Ht as createDynamicNumberingIdState,Oe as createEmptyReceipt,_t as createParagraphFingerprint,Ss as deleteCommentsByAuthorInOoxml,Ja as enforceListBindingOnParagraphNodes,dl as ensureCommentsArtifactsInZip,gi as ensureCommentsExtendedArtifactsInZip,pi as ensureNumberingArtifactsInZip,Ye as escapeXml,Yn as executeSingleLineListStructuralFallback,Q as extractCanonicalParagraphText,si as extractDocumentPartsEntries,Qa as extractFirstParagraphNumId,Iv as extractParagraphIdFromOoxml,Pa as extractParagraphRevisionSegments,cl as extractReplacementNodesFromOoxml,st as findContainingWordElement,Cs as findParagraphByBestTextMatch,sf as findParagraphByReference,Va as findParagraphByStrictText,ja as findStrictTargetCandidates,fr as generateTableOoxml,ll as getBodyElementFromDocument,oe as getDefaultAuthor,ae as getDocumentParagraphNodes,ol as getPackagePartName,Ke as getParagraphId,_e as getParagraphListInfo,Ce as getParagraphText,zi as getPlatform,qr as getTrackedChangeAuthors,Ls as hasListItems,No as inferNumberingStyleFromMarker,$s as inferTableReplacementParagraphBlock,Bn as ingestOoxml,Gw as ingestWordOoxmlToMarkdown,Cf as ingestWordOoxmlToMarkdownResult,Kw as ingestWordOoxmlToPlainText,Pf as ingestWordOoxmlToPlainTextResult,Zs as injectCommentsIntoOoxml,lv as injectCommentsIntoPackage,wv as insertBodyElementBeforeSectPr,ci as inspectDocumentParts,yf as isLikelyStructuredTableSourceParagraph,on as isMarkdownTableText,Qr as isNodeVisibleInRevisionView,hr as mergeNumberingParts,Tf as mergeNumberingXmlBySchemaOrder,mi as normalizeBodySectionOrderStandalone,od as normalizeContentEscapesForRouting,dw as normalizeListItemsWithLevels,Mf as normalizeOpcEntryName,Z as normalizeWhitespaceForTargeting,Kb as openDocx,Za as overwriteParagraphNumIds,Uo as parseMarkdownListContent,Xe as parseOoxml,j as parseOoxmlSafe,_s as parseParagraphReference,Ms as planListInsertionOnlyEdit,Kg as planStructuredReplacement,Ge as preprocessMarkdown,mr as readCanonicalRunText,SP as reconcileMarkdownTableOoxml,ia as reconcileReceiptsAgainstOutput,Ya as recordSingleLineListFallbackExplicitSequence,Fr as rejectTrackedChangesInOoxml,fn as remapNumberingPayloadForDocument,Gf as removeFormattingFromRPr,ao as repairKnownContentTypes,Vo as reserveNextNumberingId,Zn as reserveNextNumberingIdPair,sn as resolveParagraphRangeByRefs,qa as resolveSingleLineListFallbackNumberingAction,an as resolveTargetParagraph,Hn as resolveTargetParagraphWithSnapshot,Ps as sanitizeAiResponse,vv as sanitizeNestedParagraphsInTables,Kt as serializeOoxml,it as serializeToOoxml,_p as setDefaultAuthor,Op as setPlatform,ow as splitLeadingParagraphMarker,nw as stripLeadingParagraphMarker,ln as stripRedundantLeadingListMarkers,Bs as stripSingleLineListMarkerPrefix,ks as synthesizeExpandedListScopeEdit,Ds as synthesizeTableMarkdownFromMultilineCellEdit,Ur as validateDocxPackage,Qn as validateNumberingIntegrity,kt as validateRedlineOoxml,hn as validateRevisionToken,_r as wrapInDocumentFragment};
|
|
223
|
+
`)}function Yy(e,t,r){let n=Hy(e,t);if(!Number.isInteger(n)||n<1)return null;let o=qy(r);return o?`table:${n}|payload:${o}`:null}function Jy(e,t,r,n){let o=xe(t,"pPr");o||(o=$(e,"w:pPr"),t.insertBefore(o,t.firstChild));let a=xe(o,"numPr");a||(a=$(e,"w:numPr"),o.appendChild(a));let i=xe(a,"ilvl");i||(i=$(e,"w:ilvl"),a.appendChild(i)),i.setAttribute("w:val",String(Math.max(0,Number.parseInt(r,10)||0)));let l=xe(a,"numId");l||(l=$(e,"w:numId"),a.appendChild(l)),l.setAttribute("w:val",String(n))}function Jl(e,t,r,n,o,a={}){let i=a.generateRedlines!==!1,l=$(e,"w:p"),s=xe(t,"pPr");s&&l.appendChild(pt(s)),Jy(e,l,r.ilvl,r.numId),i&&Zr(l,{author:o});let c=$(e,"w:r"),f=Array.from(t.getElementsByTagNameNS(ce,"r"))[0]||null,u=f?xe(f,"rPr"):null;u&&c.appendChild(pt(u));let d=$(e,"w:t"),m=String(r.text||"").trim();if(/^\s|\s$/.test(m)&&d.setAttribute("xml:space","preserve"),d.textContent=m,c.appendChild(d),i){let p=n||ue(o,e),g=$(e,"w:ins");g.setAttribute("w:id",String(p.id)),g.setAttribute("w:author",p.author),g.setAttribute("w:date",p.date),g.appendChild(c),l.appendChild(g)}else l.appendChild(c);return l}function ql(e,t){let r=(e||[]).map(n=>t.serializeToString(n)).join("");return`<w:document xmlns:w="${ce}"><w:body>${r}</w:body></w:document>`}function Zy({xmlDoc:e,explicitRangeParagraphs:t,insertionEntries:r,generateRedlines:n,author:o}){if(!Array.isArray(t)||t.length===0||!Array.isArray(r)||r.length===0)return!1;let a=t[0].parentNode;if(!a||t.some(l=>l.parentNode!==a))return!1;let i=t[t.length-1].nextSibling;for(let l of r){let s=l.insertBeforeOriginalIndex!=null?t[l.insertBeforeOriginalIndex]:t[t.length-1];if(!s)return!1;let c=Jl(e,s,{ilvl:l.ilvl,markerType:l.markerType,numId:l.numId,text:l.text},n?ue(o,e):null,o,{generateRedlines:n});l.insertBeforeOriginalIndex!=null?a.insertBefore(c,s):a.insertBefore(c,i)}return ot(e),!0}function Qy(e,t,r,n,o={}){let a=o.generateRedlines!==!1,i=$(e,"w:p"),l=$(e,"w:r"),s=$(e,"w:t"),c=String(t||"");if(/^\s|\s$/.test(c)&&s.setAttribute("xml:space","preserve"),s.textContent=c,l.appendChild(s),a){o.trackParagraphMark===!0&&Zr(i,{author:n});let f=r||ue(n,e,"ins"),u=$(e,"w:ins");u.setAttribute("w:id",String(f.id)),u.setAttribute("w:author",f.author),u.setAttribute("w:date",f.date),u.appendChild(l),i.appendChild(u)}else i.appendChild(l);return i}function ex(e,t){let r=$(e,"w:p"),n=xe(t,"pPr");n&&r.appendChild(pt(n));let o=$(e,"w:r"),a=Array.from(t.getElementsByTagNameNS(ce,"r"))[0]||null,i=a?xe(a,"rPr"):null;i&&o.appendChild(pt(i));let l=$(e,"w:t");return l.textContent="",o.appendChild(l),r.appendChild(o),r}function Em(e,t,r,n,o={}){let a=$(e,"w:p"),i=o.sanitizeParagraphProperties===!0?Rm(e,t):pt(xe(t,"pPr"));i&&a.appendChild(i),o.paragraphId&&a.setAttributeNS(ma,"w14:paraId",o.paragraphId),o.trackParagraphMark===!0&&Zr(a,{author:n});let l=$(e,"w:ins"),s=r||ue(n,e,"ins");l.setAttribute("w:id",String(s.id)),l.setAttribute("w:author",s.author),l.setAttribute("w:date",s.date);for(let c of Array.from(t.childNodes||[]))c?.nodeType===1&&c.namespaceURI===ce&&c.localName==="pPr"||l.appendChild(c.cloneNode(!0));return a.appendChild(l),a}async function tx(e,t,r,n,o,a={}){let i=a.generateRedlines!==!1,l=le(),s=ex(e,t),c=l.serializeToString(s),f=await wo(c,"",String(r||""),{author:o,generateRedlines:!1,...a.plainTextContent===!0?{structuredContent:!1,plainTextContent:!0}:{}}),u=null;return typeof f?.oxml=="string"&&(u=(Sr(f.oxml).replacementNodes||[]).find(m=>m&&m.nodeType===1&&m.namespaceURI===ce&&m.localName==="p")||null),u?i?Em(e,u,n,o,a):u:Qy(e,r,n,o,{...a,generateRedlines:i})}function ec(e){let t=new Set;for(let r of e||[])for(let n of Bn(r)){let o=n.getAttribute("w:val")||n.getAttribute("val");o!=null&&o!==""&&t.add(String(o))}return Array.from(t)}function bm(e){return Array.from(e?.childNodes||[]).reduce((t,r)=>t+(r?.nodeType===1&&r.namespaceURI===ce&&r.localName==="r"?Vt(r).map(n=>n.text).join(""):""),"")}function rx(e,t,r){let n=0,o=-1;for(let a=0;a<r;a++){if(o=e.indexOf(t,n),o<0)return-1;n=o+Math.max(t.length,1)}return o}function nx(e,t){if(!t)return 0;let r=0,n=0;for(;n<=e.length;){let o=e.indexOf(t,n);if(o<0)break;r+=1,n=o+t.length}return r}function ox(e,t){let r=new Set(["commentRangeStart","commentRangeEnd","commentReference","bookmarkStart","bookmarkEnd","moveFromRangeStart","moveFromRangeEnd","moveToRangeStart","moveToRangeEnd"]);if(Array.from(e.getElementsByTagName?.("*")||[]).some(n=>r.has(n.localName)))return!0;for(let n of Array.from(t?.childNodes||[]))if(n.nodeType===1){if(!(n.namespaceURI===ce&&n.localName==="r"))return!0;for(let o of Array.from(n.childNodes||[]))if(!(o.nodeType!==1||o.namespaceURI!==ce)&&!["rPr","delText","t","tab","br","cr","noBreakHyphen","softHyphen"].includes(o.localName))return!0}return!1}function ax(e,t){let r=0;for(let n of Array.from(e?.childNodes||[])){if(!(n?.nodeType===1&&n.namespaceURI===ce&&n.localName==="r"))continue;let o=It(Vt(n));if(t<=r+o)return pt(xe(n,"rPr"));r+=o}return null}var ix=new Set(["pStyle","numPr","ind","jc","spacing","tabs","keepNext","keepLines","outlineLvl","contextualSpacing"]);function Zl(e,t){return e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||""}function Im(e){return String(e||"").trim().toLowerCase()}function sx(e,t="nextSibling"){let r=e?.[t]||null;for(;r;){if(r.nodeType===1&&r.namespaceURI===ce&&r.localName==="p")return r;r=r[t]||null}return null}function Rm(e,t){let r=xe(t,"pPr"),n=$(e,"w:pPr");if(!r)return n;for(let o of Array.from(r.childNodes||[]))o.nodeType!==1||o.namespaceURI!==ce||ix.has(o.localName)&&n.appendChild(e.importNode(o,!0));return n}function lx(e){let t=[],r=new Set;for(let o of Array.from(e?.getElementsByTagNameNS?.(ce,"bookmarkStart")||[])){let a=Zl(o,"name")||"(unnamed)";r.add(a)}for(let o of r)t.push(`RESTORATION_DROPPED_BOOKMARK:${o}`);let n=new Set;for(let o of["commentRangeStart","commentRangeEnd","commentReference"])for(let a of Array.from(e?.getElementsByTagNameNS?.(ce,o)||[])){let i=Zl(a,"id");i!==""&&n.add(i)}for(let o of n)t.push(`RESTORATION_DROPPED_COMMENT:${o}`);return t}function cx(e){let t=["bookmarkStart","bookmarkEnd","commentRangeStart","commentRangeEnd","commentReference"];for(let r of t)for(let n of Array.from(e?.getElementsByTagNameNS?.(ce,r)||[]))n.parentNode?.removeChild(n);for(let r of Array.from(e?.getElementsByTagNameNS?.(ce,"r")||[]))Array.from(r.childNodes||[]).some(o=>o.nodeType===1&&o.namespaceURI===ce&&o.localName!=="rPr")||r.parentNode?.removeChild(r)}function ux(e,t,r){let n=Ur(r.serializeToString(t),{allAuthors:!0}),a=V(n.oxml,"application/xml").doc?.getElementsByTagNameNS?.(ce,"p")?.[0]||null;if(!a)return null;let i=$(e,"w:p");i.appendChild(Rm(e,t));for(let l of Array.from(a.childNodes||[]))l.nodeType===1&&l.namespaceURI===ce&&l.localName==="pPr"||i.appendChild(e.importNode(l,!0));return cx(i),i}async function fx(e,t,r,n,o){let a=Y(t);if(a===r)return t;let i=await wo(o.serializeToString(t),a,r,{author:n,generateRedlines:!1,structuredContent:!1});if(i?.status==="error"||typeof i?.oxml!="string")return null;let s=(Sr(i.oxml).replacementNodes||[]).find(c=>c?.nodeType===1&&c.namespaceURI===ce&&c.localName==="p");return s?e.importNode(s,!0):null}function dx(e,t){let r=new Set(se(e).map(o=>o.getAttributeNS?.(ma,"paraId")||o.getAttribute?.("w14:paraId")||"").filter(Boolean).map(o=>o.toUpperCase())),n=null;do n=t?.generateParagraphId?.()||(1073741824+r.size+1).toString(16).toUpperCase();while(r.has(n.toUpperCase()));return n}function mx(e,t,r,n){let o=e.documentElement;return o&&!o.getAttribute("xmlns:w14")&&o.setAttribute("xmlns:w14",ma),Em(e,t,null,r,{paragraphId:dx(e,n),sanitizeParagraphProperties:!0,trackParagraphMark:!0})}function px(e,t){let r=xe(e,"pPr"),n=xe(r,"rPr"),o=xe(n,"ins");return!!o&&Im(Zl(o,"author"))===Im(t)}function gx(e,t){let r=[],n=e;for(let o=0;o<t;o++){if(n=sx(n,"nextSibling"),!n)return[];r.push(n)}return r}function Ql(e){let t=V(e,"application/xml");return t.error||!t.doc?null:se(t.doc).map(r=>Y(r))}function hx(e,t){return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((r,n)=>r===t[n])}function Mi(e,t){let r=t==="accept"?nn(e,{allAuthors:!0}):Ur(e,{allAuthors:!0});return Ql(r.oxml)}function wx(e,t,r,n){let o=V(e,"application/xml");if(o.error||!o.doc)return null;let a=o.doc,i=se(a),l=i[t+n.length-1]||null;if(!l?.parentNode)return null;for(let c of[...r].sort((f,u)=>u-f)){let f=i[c];f?.parentNode?.removeChild(f)}let s=l.nextSibling;for(let c of n)l.parentNode.insertBefore(a.importNode(c,!0),s);return le().serializeToString(a)}function vx(e,t,r,n,o,a=[]){let i=Mt(e),l=Mt(t),s=An(l.issues,i.issues),c=a.flatMap(m=>Mt(le().serializeToString(m)).issues.filter(p=>p.severity==="error")),f=En(s);if(f.length>0||c.length>0)return{valid:!1,stage:"validation",code:"GENERATED_OOXML_INVALID",generatedIssues:s,envelopeIssues:c,message:[...f,...c].map(m=>m.message).join(" ")};let u=wx(e,r,n,o);if(!u)return{valid:!1,stage:"expected-document",message:"Could not construct the restoration lifecycle oracle."};let d=[["current",Ql(u),Ql(t)],["accept-all",Mi(u,"accept"),Mi(t,"accept")],["reject-all",Mi(e,"reject"),Mi(t,"reject")]];for(let[m,p,g]of d)if(!hx(p,g))return{valid:!1,stage:m,expected:p,actual:g,message:`Paragraph restoration ${m} lifecycle text did not match the expected body-scoped paragraph sequence.`};return{valid:!0}}async function Pm(e,t,r,n,o,a=null,i=null,l={}){let{serializer:s,xmlDoc:c,operationSession:f}=Kr(e,l);if(!c)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let u=At(c,t,a,"insert",i,l);if(u?.error||!u?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:u?.error||{code:"TARGET_NOT_FOUND",message:"Rejected-view insertion target was not found."}};let d=u.paragraph;if(!Xr(d,o).matches)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"REJECTED_INSERTION_STATE_REQUIRED",message:"Rejected-view insertion requires a wholly deleted paragraph owned by another author."}};let p=an(d,{requireFollowingParagraph:!1});if(p)return{documentXml:e,hasChanges:!1,status:"error",error:p};if(/\r|\n/.test(n))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_PARAGRAPH_BOUNDARY",message:"Rejected-view insertion supports run-level text only; use restore for paragraph boundaries."}};let g=Y(d,{revisionView:"rejected"});if(!r.occurrenceExplicit&&nx(g,r.exactText)>1)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"AMBIGUOUS_ANCHOR",message:"The rejected-view insertion anchor is repeated; provide anchor.occurrence explicitly."}};let h=rx(g,r.exactText,r.occurrence);if(h<0)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"ANCHOR_NOT_FOUND",message:"The rejected-view insertion anchor was not found at the requested occurrence."}};let v=h+r.offset,w=Array.from(d.childNodes||[]).filter(_=>_?.nodeType===1&&_.namespaceURI===ce&&_.localName==="del");if(w.some(_=>ox(d,_)))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_BOUNDARY",message:"The rejected-view insertion boundary contains comments, bookmarks, fields, hyperlinks, moves, or non-text run markup that cannot be split safely."}};let y=0,x=null,b=0;for(let _ of w){let k=bm(_).length;if(v>=y&&v<=y+k){x=_,b=v-y;break}y+=k}if(!x||w.map(bm).join("")!==g)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"The rejected-view anchor is not contained in a supported direct deletion carrier."}};let T=ax(x,b),{leftCarrier:A,rightCarrier:E}=La(c,x,b,l._revisionIdAllocator||null),I=$(c,"w:ins"),R=ue(o,l._revisionIdAllocator||c,"ins");I.setAttribute("w:id",String(R.id)),I.setAttribute("w:author",R.author),I.setAttribute("w:date",R.date);let S=$(c,"w:r");T&&S.appendChild(T);let N=$(c,"w:t");/^\s|\s$/.test(n)&&N.setAttribute("xml:space","preserve"),N.textContent=n,S.appendChild(N),I.appendChild(S);let O=x.parentNode;A&&O.insertBefore(A,x),O.insertBefore(I,x),E&&O.insertBefore(E,x),l?._mutationRemovedNodes?.push(x),O.removeChild(x),l?._mutationLiveNodes?.push(d,I),f?.invalidateParagraphMetadata?.();let C=s.serializeToString(c),P=Y(d,{revisionView:"rejected"}),M=Y(d,{revisionView:"accepted"});return P!==g||!M.includes(n)?{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:"Rejected-view insertion did not preserve the deleted source and expose the requested inserted text."}}:{documentXml:C,hasChanges:!0,status:"ok"}}async function Cm(e,t,r,n,o=null,a=null,i=null,l={}){let{serializer:s,xmlDoc:c,operationSession:f}=Kr(e,l);if(!c)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let u=At(c,t,o,"restore",i,l);if(u?.error||!u?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:u?.error||{code:"TARGET_NOT_FOUND",message:"Restoration target paragraph not found."}};let d=u.paragraph,m=[d];if(l._compiledSourceEndId){let O=At(c,l.targetEndDescriptor?.text||"",a,"restore",i,{...l,_compiledSourceId:l._compiledSourceEndId}),C=O?.paragraph?se(c):[],P=C.indexOf(d),M=C.indexOf(O?.paragraph);m=P>=0&&M>=P?C.slice(P,M+1):null}else if(a)m=cn(c,o,a,{opType:"restore",targetRefSnapshot:i?.targetRefSnapshot||null,onInfo:l.onInfo,onWarn:l.onWarn});else if(l.targetEndDescriptor){let O=At(c,l.targetEndDescriptor.text,l.targetEndDescriptor.index,"restore",i,{...l,targetDescriptor:l.targetEndDescriptor,_compiledSourceId:l._compiledSourceEndId||null}),C=O?.paragraph?se(c):[],P=C.indexOf(d),M=C.indexOf(O?.paragraph);m=P>=0&&M>=P?C.slice(P,M+1):null}if(!Array.isArray(m)||m.length===0||m[0]!==d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_COUNT_MISMATCH",message:"The restoration range could not be resolved as a contiguous paragraph block."}};let p=Array.isArray(r)?r.map(String):[String(r||"")];if(p.length!==m.length||p.some(O=>O.length===0))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_COUNT_MISMATCH",message:`Restoration requires exactly one non-empty replacement per source paragraph (${m.length} expected, ${p.length} received).`}};let g=d.parentNode;if(!g||m.some(O=>O.parentNode!==g))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"UNSAFE_PARAGRAPH_PLACEMENT",message:"Restoration source paragraphs must be a contiguous block in one structural container."}};for(let O of m){let C=an(O);if(C?.code==="UNSUPPORTED_MOVE_REVISION")return{documentXml:e,hasChanges:!1,status:"error",error:C};let P=Xr(O,n);if(!P.matches)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"RESTORATION_STATE_REQUIRED",message:P.hasParagraphMarkDeletion&&!P.foreignParagraphMarkDeletion?"Explicit cross-author restoration does not apply to a paragraph deleted by the current author; use merge-same-author.":"Explicit restoration requires a foreign paragraph-mark deletion with every pre-existing content node deleted.",...P.ownerAuthor?{ownerAuthor:P.ownerAuthor}:{}}};let M=C||an(O);if(M)return{documentXml:e,hasChanges:!1,status:"error",error:M}}let h=m[m.length-1],v=gx(h,m.length),w=v.length===m.length&&v.every(O=>px(O,n));if(w&&v.every((O,C)=>Y(O)===p[C]))return{documentXml:e,hasChanges:!1,status:"no-op",warnings:["An identical same-author paragraph restoration already exists."]};let y=s.serializeToString(c),x=se(c),b=x.indexOf(d),T=w?v.map(O=>x.indexOf(O)):[],A=[],E=[];for(let O=0;O<m.length;O++){let C=m[O];E.push(...lx(C));let P=ux(c,C,s),M=P?await fx(c,P,p[O],n,s):null;if(!M)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_ROUNDTRIP_MISMATCH",message:`Could not reconstruct restoration paragraph ${O+1} from its rejected revision view.`}};A.push(M)}let I=A.map(O=>{let C=c.importNode(O,!0);return mx(c,C,n,f)}),R=h.nextSibling;for(let O of I)g.insertBefore(O,R);if(w)for(let O of v)l?._mutationRemovedNodes?.push(O),O.parentNode?.removeChild(O);l?._mutationLiveNodes?.push(...I),ot(c);let S=s.serializeToString(c),N=vx(y,S,b,T,A,I);return N.valid?{documentXml:nt(c,s,e,f),hasChanges:!0,status:"ok",numberingXml:null,...E.length>0?{warnings:[...new Set(E)]}:{}}:{documentXml:e,hasChanges:!1,status:"error",error:{code:N.code||"PATCH_ROUNDTRIP_MISMATCH",message:N.message,stage:N.stage,...N.generatedIssues?{generatedIssues:N.generatedIssues}:{},...N.envelopeIssues?{envelopeIssues:N.envelopeIssues}:{},...N.expected?{expected:N.expected}:{},...N.actual?{actual:N.actual}:{}}}}async function yx({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:o,currentParagraphText:a,modifiedText:i,author:l,runtimeContext:s,revisionIdAllocator:c,generateRedlines:f=!0,onInfo:u=()=>{},options:d={}}){if(!o)return null;let m=t.serializeToString(o),p=dn({oxml:m,originalText:a,modifiedText:i,allowExistingList:!1});if(!p||p.numberingKey!=="numbered:decimal:single"||!Number.isInteger(p.startAt)||p.startAt<1)return null;let g=Vs(p.listInput||i);if(!g)return null;u("[List] Applying explicit numeric header conversion with direct list binding.");let h=Za(p,s?.listFallbackSequenceState||null),v=p.startAt,w=s?.numberingIdState||null,y=null,x=null;if(h.type==="explicitReuse"&&h.numId)y=String(h.numId),u(`[List] Reusing explicit-start list sequence (${h.numberingKey} -> numId ${y}, next ${v+1}).`);else{let I=to(w);if(!I)return null;y=String(I.numId),x=ni(I.numId,I.abstractNumId,v),h.type==="explicitStartNew"&&u(`[List] Started explicit-start list sequence (${h.numberingKey} -> numId ${y}).`),u(`[List] Using isolated explicit-start numbering (start ${v}, numId ${y}, abstractNumId ${I.abstractNumId}).`)}let b=await wo(t.serializeToString(o),a,g,{author:l,generateRedlines:f,_revisionIdAllocator:c});if(!b?.hasChanges||typeof b?.oxml!="string")return null;let A=Sr(b.oxml).replacementNodes;p.numberingKey&&s?.listFallbackSharedNumIdByKey instanceof Map&&s.listFallbackSharedNumIdByKey.delete(p.numberingKey),h.type==="explicitStartNew"||h.type==="explicitReuse"?Qa(s?.listFallbackSequenceState||null,h.numberingKey||p.numberingKey,y,v):Vo(s?.listFallbackSequenceState||null,h.numberingKey||p.numberingKey),ei(A,{numId:y,ilvl:0,clearParagraphPropertyChanges:!0,removeListPropertyNode:!0,trackPropertyChange:f?{author:l,revisionIdAllocator:c}:null});let E=o.parentNode;if(!E)return null;for(let I of A){let R=e.importNode(I,!0);let S=E.insertBefore(R,o);d?._mutationLiveNodes?.push(S)}if(d?._mutationRemovedNodes?.push(o),E.removeChild(o),ot(e),n?.receiptCollector&&x){let I=ec(d?._mutationLiveNodes);for(let R of I)n.receiptCollector.recordNumbering(R)}return{documentXml:nt(e,t,r,n),hasChanges:!0,numberingXml:x}}var xx=Object.freeze({upperAlpha:"upperLetter",lowerAlpha:"lowerLetter",upperRoman:"upperRoman",lowerRoman:"lowerRoman",bullet:"bullet"});function bx({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:o,currentParagraphText:a,modifiedText:i,author:l,runtimeContext:s,revisionIdAllocator:c,generateRedlines:f=!0,onInfo:u=()=>{},options:d={}}){if(!o||Oe(o)||q(a)!==q(i))return null;let m=dn({oxml:t.serializeToString(o),originalText:a,modifiedText:i,allowExistingList:!1}),p=m?xx[m.numberingStyle]:null;if(!p)return null;let g=se(e),h=Xl(e,[o],Pl({mode:"convert-plain",format:p,strip:"marker"}),{author:l||ae(),generateRedlines:f,revisionIdAllocator:c,runtimeContext:s,stylesXml:s?.stylesXml||d.stylesXml||null,numberingXml:s?.numberingXml||d.numberingXml||null,paragraphIndexOf:v=>g.indexOf(v)+1});if(!h.ok)return u(`[List] In-place marker conversion declined (${h.error.code}); using the structural fallback.`),null;u(`[List] Converted typed ${p} marker in place (numId ${h.items[0].numId}).`),d?._mutationLiveNodes?.push(o);for(let v of h.allocatedNumIds)n?.receiptCollector?.recordNumbering(v);return ot(e),{documentXml:nt(e,t,r,n),hasChanges:!0,numberingXml:h.numberingXml}}var Nm=["pStyle","keepNext","keepLines","pageBreakBefore","framePr","widowControl","numPr","suppressLineNumbers","pBdr","shd","tabs","suppressAutoHyphens","kinsoku","wordWrap","overflowPunct","topLinePunct","autoSpaceDE","autoSpaceDN","bidi","adjustRightInd","snapToGrid","spacing","ind","contextualSpacing","mirrorIndents","suppressOverlap","jc","textDirection","textAlignment","textboxTightWrap","outlineLvl","divId","cnfStyle","rPr","sectPr","pPrChange"],Ix=new Set(["pStyle","numPr","rPr","sectPr","pPrChange"]);function Nx(e,t,r){let n=t.filter(s=>s?.nodeType===1&&s.localName==="p"),o=(s,c)=>{let f=xe(xe(s,"pPr"),"rPr");return!!f&&!!xe(f,c)},a=n.find(s=>o(s,"del")),i=n.find(s=>!o(s,"del")),l=xe(r,"pPr");if(a&&l){let s=e.importNode(l,!0),c=xe(xe(a,"pPr"),"rPr"),f=c&&xe(c,"del");if(f){let u=xe(s,"rPr");if(!u){u=$(e,"w:rPr");let d=xe(s,"sectPr")||xe(s,"pPrChange");s.insertBefore(u,d||null)}Array.from(u.childNodes).forEach(d=>{d.nodeType===1&&(d.localName==="ins"||d.localName==="del")&&u.removeChild(d)}),u.appendChild(e.importNode(f,!0)),a.replaceChild(s,xe(a,"pPr"))}}if(i&&l){let s=xe(i,"pPr");s||(s=$(e,"w:pPr"),i.insertBefore(s,i.firstChild||null));for(let c of Array.from(l.childNodes)){if(c.nodeType!==1||Ix.has(c.localName)||xe(s,c.localName))continue;let f=Nm.indexOf(c.localName),u=Array.from(s.childNodes).find(d=>d.nodeType===1&&Nm.indexOf(d.localName)>f);s.insertBefore(e.importNode(c,!0),u||null)}}if(i)for(let s of["paraId","textId"]){let c=r.getAttributeNS?.(ma,s)||r.getAttribute?.(`w14:${s}`);c&&i.setAttributeNS(ma,`w14:${s}`,c)}}async function Tx({xmlDoc:e,serializer:t,documentXml:r,operationSession:n,targetParagraph:o,currentParagraphText:a,modifiedText:i,author:l,runtimeContext:s,revisionIdAllocator:c,generateRedlines:f=!0,onInfo:u=()=>{},options:d={}}){if(!o)return null;let m=t.serializeToString(o),p=dn({oxml:m,originalText:a,modifiedText:i,allowExistingList:!1});if(!p)return null;u("[List] No textual diff but list marker detected; forcing structural list conversion fallback.");let g=await Qn(p,{author:l,generateRedlines:f,revisionIdAllocator:c,setAbstractStartOverride:!1});if(!g?.hasChanges||!g?.oxml)return u("[List] Structural list fallback produced no valid OOXML payload."),null;let h=Sr(g.oxml),v=h.replacementNodes,w=h.numberingXml||g?.numberingXml||null,y=Number.isInteger(p?.startAt)&&p.startAt>0,x=y&&p?.numberingStyle==="decimal",b=y&&!x,T=g?.listStructuralFallbackKey||p?.numberingKey||null,A=Za(p,s?.listFallbackSequenceState||null);if(x){let I=p.startAt,R=null,S=s?.numberingIdState||null;if(A.type==="explicitReuse"&&A.numId)R=String(A.numId),w=null,u(`[List] Reusing explicit-start list sequence (${A.numberingKey} -> numId ${R}, next ${I+1}).`);else if(S){let N=to(S);if(!N)return null;ti(v,N.numId),R=String(N.numId),w=ni(N.numId,N.abstractNumId,I),A.type==="explicitStartNew"&&u(`[List] Started explicit-start list sequence (${A.numberingKey} -> numId ${N.numId}).`),u(`[List] Using isolated explicit-start numbering (start ${I}, numId ${N.numId}, abstractNumId ${N.abstractNumId}).`)}else{let N=ri(v);R=N?String(N):null,u(`[List] Using isolated list numbering with explicit start ${I}${N?` (numId ${N})`:""}.`)}T&&s?.listFallbackSharedNumIdByKey instanceof Map&&s.listFallbackSharedNumIdByKey.delete(T),A.type==="explicitStartNew"||A.type==="explicitReuse"?Qa(s?.listFallbackSequenceState||null,A.numberingKey||T,R,I):Vo(s?.listFallbackSequenceState||null,A.numberingKey||T),R&&ei(v,{numId:R,ilvl:0,clearParagraphPropertyChanges:!0,removeListPropertyNode:!0,trackPropertyChange:f?{author:l,revisionIdAllocator:c}:null})}else{if(w&&s?.numberingIdState){let I=mn(w,v,s.numberingIdState);v=I.replacementNodes,w=I.numberingXml}Vo(s?.listFallbackSequenceState||null,A.numberingKey||T)}if(!x&&w&&s){let I=Of({numberingXml:w,replacementNodes:v,sequence:Dl(s),isNumIdLive:R=>Fl(e,R)});I&&(v=I.replacementNodes,w=null,u(`[List] Continuing batch list numbering (numId ${I.numId}).`))}if(!x&&!b&&s?.listFallbackSharedNumIdByKey instanceof Map){let I=T?s.listFallbackSharedNumIdByKey.get(T):null;if(I)ti(v,I),w=null,u(`[List] Reusing shared list numbering (${T} -> numId ${I}).`);else if(T){let R=ri(v);R&&(s.listFallbackSharedNumIdByKey.set(T,R),u(`[List] Captured shared list numbering (${T} -> numId ${R}).`))}}let E=o.parentNode;if(!E)return null;f&&Nx(e,v,o);for(let I of v){let R=e.importNode(I,!0);let S=E.insertBefore(R,o);d?._mutationLiveNodes?.push(S)}if(d?._mutationRemovedNodes?.push(o),E.removeChild(o),ot(e),n?.receiptCollector&&w){let I=ec(d?._mutationLiveNodes);for(let R of I)n.receiptCollector.recordNumbering(R)}return{documentXml:nt(e,t,r,n),hasChanges:!0,numberingXml:w}}function Yl(e,t){let{severity:r,...n}=t;return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:n}}function Li(e){return e.length>0?{diagnostics:e,warnings:e.map(Ol)}:{}}function Tm({sourceParagraphs:e,modifiedText:t,runtimeContext:r,options:n}){let o=_l(n);if(o==="off")return null;let a=r?.numberingIdState?.sourceNumberingXml;if(!a)return null;let i=[];for(let s of e||[]){let c=Oe(s);c&&i.push({text:ho(s),numId:c.numId,ilvl:c.ilvl})}let l=Kd({modifiedText:t,sourceItems:i,sourceNumberingXml:a});return l?jd(l.mismatch,{policy:o,numId:l.numId,level:l.level,marker:l.marker,targetText:l.targetText,operationIndex:n?._operationIndex}):null}async function _m(e,t,r,n,o=null,a=null,i=null,l={}){let s=l.generateRedlines!==!1,c=typeof l?.onInfo=="function"?l.onInfo:()=>{},f=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:u,xmlDoc:d,operationSession:m}=Kr(e,l);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||Sn(d,l),g=At(d,t,o,"redline",i,{...l,onInfo:c,onWarn:f});if(g?.error||!g?.paragraph)return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:g?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let h=g.paragraph;if(typeof r=="string"&&r.length>0){let z=Xr(h,n);if(z.matches){let Q=z.ownerAuthor||"unattributed";return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"FOREIGN_PARAGRAPH_MARK_DELETION",message:`Refusing to add visible text to a paragraph whose paragraph mark is deleted by another author (${Q}). Use explicit paragraph restoration when supported.`,ownerAuthor:Q}}}}Gy(h);let v=ho(h);if(r===""){let z=vm(h);if(z.length>0){let Q=ym(z,l._existingCommentDetails);return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"COMMENTED_CONTENT_DELETE",message:"Refusing to delete a paragraph with existing comments. Resolve or explicitly remove the comments before deleting the paragraph.",commentIds:z,...Q.length>0?{comments:Q}:{}}}}}let w=Ha(h,r,l);if(!w.valid)return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:w.code,message:w.message}};let y=l.existingRevisions==="auto";y&&(l={...l,existingRevisions:Lr("auto",h,n)});let x=fr(h),b=l.existingRevisions||"merge-same-author";if(x&&b!=="accept-all-first"&&b!=="accept-all-first-keep-normalized")if(b==="merge-same-author"||b==="slice-cross-author"){let z=Mr(h),Q=String(n||"").trim().toLowerCase(),Te=z.length>0&&!dr(h)&&z.every(Ae=>Ae.trim().toLowerCase()===Q);if(!Te&&b==="merge-same-author")return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"EXISTING_REVISIONS",message:`Target paragraph contains tracked changes from another author (${[...z,...dr(h)?["unattributed"]:[]].join(", ")}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:z,currentPolicy:b}};let Se=Te?vm(h):[];if(Se.length>0){let Ae=ym(Se,l._existingCommentDetails);return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:Se,...Ae.length>0?{comments:Ae}:{}}}}if(!Te&&(h.getElementsByTagNameNS(ce,"moveFrom").length>0||h.getElementsByTagNameNS(ce,"moveTo").length>0))return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."}}}else{let z=h.getElementsByTagNameNS(ce,"del").length>0,Q=h.getElementsByTagNameNS(ce,"moveFrom").length>0||h.getElementsByTagNameNS(ce,"moveTo").length>0;return z?{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Refusing to replace content with pending deletions; nesting revisions is unsafe."}}:Q?{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"UNSAFE_REVISION_NESTING",message:"Refusing to mutate content with move revisions until move lifecycle is designed."}}:{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:{code:"EXISTING_REVISIONS",message:'Target paragraph contains tracked changes and existingRevisions is "reject-input".'}}}if(r===""&&v===""&&!(x&&b==="merge-same-author"))return s?(Qr(h,{author:n}),l?._mutationLiveNodes?.push(h)):(l?._mutationRemovedNodes?.push(h),h.parentNode?.removeChild(h)),ot(d),{documentXml:nt(d,u,e,m),hasChanges:!0,numberingXml:null};let T=ct(h,"tbl"),E=!!T&&!a&&typeof r=="string"&&r.includes(`
|
|
224
|
+
`)&&!sn(r)?Yy(d,T,r):null,I=i?.tableStructuralRedlineKeys instanceof Set?i.tableStructuralRedlineKeys:null;if(E&&I?.has(E))return c("[Table] Skipping duplicate table-structural redline for the same table/payload in this turn."),{documentXml:e,hasChanges:!1,numberingXml:null,warnings:["Skipped duplicate table-structural redline in the same turn."]};let S=(T?Gs(h,r,{tableElement:T,currentParagraphText:v,onInfo:c,onWarn:f}):null)||r,N=!!T&&sn(S),O=sn(S),C=null;if(!a&&(l._compiledSourceEndId||l.targetEndDescriptor)){let z=Bm(d,t,o,a,"redline",i,{...l,_resolutionCapture:null});if(z.error)return{documentXml:e,hasChanges:!1,status:"error",error:z.error};if(z.paragraphs.length>1){let Q=z.paragraphs[0].parentNode;if(z.paragraphs.some(Te=>Te.parentNode!==Q))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"TARGET_RANGE_INVALID",message:"A redline target range must stay inside one container (body, table cell, header, ...); it spans a table or other container boundary. Edit the paragraphs on each side separately."}};C=z.paragraphs}}let P=C||(a?cn(d,o,a,{opType:"redline",targetRefSnapshot:i?.targetRefSnapshot||null,onInfo:c,onWarn:f}):typeof t=="string"&&/\r?\n/.test(t)?Ba(d,t):null),M=Array.isArray(P)&&P.length>0;if(y&&M&&(l={...l,existingRevisions:Lr("auto",P,n)}),!N&&M){let z=fm(P,S);if(z&&z.length>0){c(`[List] Applying explicit-range insertion-only heuristic (${z.length} new item(s)).`);for(let Se of z)c(`[List] Explicit-range insertion: ilvl=${Se.ilvl}, markerType=${Se.markerType}, text="${String(Se.text||"").slice(0,80)}${String(Se.text||"").length>80?"\u2026":""}"`);let Q=Tm({sourceParagraphs:P,modifiedText:S,runtimeContext:i,options:l});if(Q?.severity==="error")return Yl(e,Q);if(Zy({xmlDoc:d,explicitRangeParagraphs:P,insertionEntries:z,generateRedlines:s,author:n}))return{documentXml:nt(d,u,e,m),hasChanges:!0,numberingXml:null,...Li(Q?[Q]:[])}}}let _=null;!P&&!N&&O&&(_=Ks(h,{getParagraphText:ho}),_?.length>1&&c(`[Table] Heuristic range expansion selected ${_.length} paragraph(s) for replacement.`));let k=Oe(h);if(k&&typeof S=="string"&&!S.includes(`
|
|
225
|
+
`)){let z=un(S);z&&z!==S.trim()&&(c("[List] Stripped redundant manual list marker prefix from single-line list item edit."),S=z)}N&&c("[Table] Markdown table edit detected in table cell target; applying reconciliation at table scope.");let L=l.explicitStructuredContent===!0,D=!L&&!N&&!M&&k?dm(v,S):null;if(D){c(`[List] Applying single-paragraph list adjacency insertion heuristic (${D.position}).`);let z=h.parentNode;if(!z)throw new Error("Target paragraph has no parent for adjacency list insertion");let Q=Jl(d,h,{ilvl:k.ilvl,numId:k.numId,markerType:"numbered",text:D.text},s?ue(n,d):null,n,{generateRedlines:s}),Te=D.position==="before"?h:h.nextSibling;return z.insertBefore(Q,Te),l?._mutationLiveNodes?.push(Q),ot(d),{documentXml:nt(d,u,e,m),hasChanges:!0,numberingXml:null}}let X=!N&&!M&&!k&&!T&&!a?pm(S):null,G=X?yt(X.paragraphMarkdown):null;if(X&&q(G.cleanText)===q(v)){let z=xt(X.tableText);if(z.headers.length>0||z.rows.length>0){c("[Table] Applying retained-paragraph table append heuristic.");let Q=h.parentNode;if(!Q)throw new Error("Target paragraph has no parent for table append");let Te=h.nextSibling;if(G.formatHints.length>0){let Ye=await wo(u.serializeToString(h),v||t,X.paragraphMarkdown,{author:n,generateRedlines:s,existingRevisions:l.existingRevisions||"merge-same-author",structuredContent:!1,_revisionIdAllocator:p});if(Ye?.status==="error")return{documentXml:e,hasChanges:!1,numberingXml:null,status:"error",error:Ye.error};if(Ye?.hasChanges){if(typeof Ye.oxml!="string")throw new Error("Reconciliation engine did not return OOXML for a changed paragraph format");for(let On of Sr(Ye.oxml).replacementNodes){let kn=d.importNode(On,!0);l?._mutationLiveNodes?.push(Q.insertBefore(kn,h))}l?._mutationRemovedNodes?.push(h),Q.removeChild(h)}}let Se=mr(z,{generateRedlines:s,author:n,revisionIdAllocator:p,trackAsBlock:!0});for(let Ye of Sr(Se).replacementNodes)l?._mutationLiveNodes?.push(Q.insertBefore(d.importNode(Ye,!0),Te));let Ae=Te;for(;Ae&&Ae.nodeType!==1;)Ae=Ae.nextSibling;if(!Ae||Ae.namespaceURI===ce&&Ae.localName==="sectPr"){let Ye=$(d,"w:p"),On=pt(xe(h,"pPr"));if(On){for(let kn of Array.from(On.childNodes))kn.nodeType===1&&["sectPr","numPr"].includes(kn.localName)&&On.removeChild(kn);Ye.appendChild(On)}s&&Zr(Ye,{author:n}),l?._mutationLiveNodes?.push(Q.insertBefore(Ye,Te))}return ot(d),{documentXml:nt(d,u,e,m),hasChanges:!0,numberingXml:null}}}let ee=!L&&!N&&!M&&!k?mm(v,S):null;if(ee){c(`[Text] Applying single-paragraph plain adjacency insertion heuristic (${ee.position}, count=${ee.paragraphs.length}).`);let z=h.parentNode;if(!z)throw new Error("Target paragraph has no parent for plain adjacency insertion");let Q=ee.position==="before"?h:h.nextSibling;for(let Te of ee.paragraphs){let Se=await tx(d,h,Te,s?ue(n,d):null,n,{generateRedlines:s,trackParagraphMark:!0,plainTextContent:l.plainTextContent===!0}),Ae=d.importNode(Se,!0);let ji=z.insertBefore(Ae,Q);l?._mutationLiveNodes?.push(ji)}return ot(d),{documentXml:nt(d,u,e,m),hasChanges:!0,numberingXml:null}}let J=!L&&!N&&!M?zs(h,S,{currentParagraphText:v,onInfo:c,onWarn:f}):null;if(J&&J.entries.length>0){let z=Tm({sourceParagraphs:[h],modifiedText:S,runtimeContext:i,options:l});if(z?.severity==="error")return Yl(e,z);c(`[List] Applying insertion-only list redline heuristic (${J.entries.length} new item(s)).`);for(let Se of J.entries)c(`[List] Insertion entry resolved: ilvl=${Se.ilvl}, markerType=${Se.markerType}, text="${String(Se.text||"").slice(0,80)}${String(Se.text||"").length>80?"\u2026":""}"`);let Q=h.parentNode;if(!Q)throw new Error("Target paragraph has no parent for list insertion");let Te=h.nextSibling;for(let Se of J.entries){let Ae=Jl(d,h,{...Se,numId:J.numId},s?ue(n,d):null,n,{generateRedlines:s});Q.insertBefore(Ae,Te),l?._mutationLiveNodes?.push(Ae)}return ot(d),{documentXml:nt(d,u,e,m),hasChanges:!0,numberingXml:null,...Li(z?[z]:[])}}let Z=!L&&!N&&!M?Xs(h,S,{currentParagraphText:v,onInfo:c,onWarn:f}):null,ie=!!Z&&Array.isArray(Z.paragraphs)&&Z.paragraphs.length>0;ie&&(S=Z.modifiedText);let ne=null;if(!L&&!N&&!ie&&!M){let z=await yx({xmlDoc:d,serializer:u,documentXml:e,operationSession:m,targetParagraph:h,currentParagraphText:v,modifiedText:S,author:n,runtimeContext:i,revisionIdAllocator:p,generateRedlines:s,onInfo:c,options:l});if(z)return z;let Q=bx({xmlDoc:d,serializer:u,documentXml:e,operationSession:m,targetParagraph:h,currentParagraphText:v,modifiedText:S,author:n,runtimeContext:i,revisionIdAllocator:p,generateRedlines:s,onInfo:c,options:l});if(Q)return Q;let Te=await Tx({xmlDoc:d,serializer:u,documentXml:e,operationSession:m,targetParagraph:h,currentParagraphText:v,modifiedText:S,author:n,runtimeContext:i,revisionIdAllocator:p,generateRedlines:s,onInfo:c,options:l});if(Te)return Te;let Se=_l(l);if(Se!=="off"&&!k){let Ae=Xd({originalText:v,modifiedText:S,targetIsListItem:!1});if(Ae&&(ne=zd(Ae,{policy:Se,targetText:v,operationIndex:l?._operationIndex}),Se==="error"))return Yl(e,ne)}}let re=ie?Z.originalText:P?P.map(z=>ho(z)).join(`
|
|
226
|
+
`):_?_.map(z=>ho(z)).join(`
|
|
227
|
+
`):v||t,We=N?u.serializeToString(T):ie?ql(Z.paragraphs,u):P?ql(P,u):_?ql(_,u):u.serializeToString(h),ge=O?await jy(We,re,S,{author:n,generateRedlines:s,existingRevisions:l.existingRevisions||"merge-same-author",structuredContent:l.structuredContent!==!1,explicitStructuredContent:l.explicitStructuredContent===!0,plainTextContent:l.plainTextContent===!0,_revisionIdAllocator:p,_isolatedTableCell:N}):await wo(We,re,S,{author:n,generateRedlines:s,existingRevisions:l.existingRevisions||"merge-same-author",structuredContent:l.structuredContent!==!1,explicitStructuredContent:l.explicitStructuredContent===!0,pairReplacements:l.pairReplacements===!0,insertionAffinity:l.insertionAffinity||null,literalTextEdit:l.literalTextEdit===!0,plainTextContent:l.plainTextContent===!0,_revisionIdAllocator:p,_isolatedTableCell:N});if(!ge?.hasChanges)return{documentXml:e,hasChanges:!1,numberingXml:null,status:ge?.status||"no-op",error:ge?.error};if(ge.useNativeApi&&!ge.oxml){let z="Format-only fallback requires native Word API; browser demo skipped this operation.";return f(`[WARN] ${z}`),{documentXml:e,hasChanges:!1,numberingXml:null,warnings:[z]}}if(typeof ge.oxml!="string")throw new Error("Reconciliation engine did not return OOXML for a changed redline operation");let he=Sr(ge.oxml),Me=Wy(he.replacementNodes,ge.warnings),K=he.numberingXml;if(K&&i?.numberingIdState){let z=Ys({numberingXml:K,replacementNodes:Me,sourceParagraphs:ie?Z.paragraphs:P||[h],numberingIdState:i.numberingIdState,allowContinueSource:!N});Me=z.replacementNodes,K=z.numberingXml}let j=N?[T]:ie?Z.paragraphs:P||_||[h],ye=j[0],Pe=ye.parentNode;for(let z of Me){let Q=d.importNode(z,!0);let Te=Pe.insertBefore(Q,ye);l?._mutationLiveNodes?.push(Te)}for(let z of j)z&&z.parentNode===Pe&&(l?._mutationRemovedNodes?.push(z),Pe.removeChild(z));if(ot(d),E&&I&&(N||T)&&I.add(E),m?.receiptCollector&&K){let z=ec(l?._mutationLiveNodes);for(let Q of z)m.receiptCollector.recordNumbering(Q)}return{documentXml:nt(d,u,e,m),hasChanges:!0,numberingXml:K,status:"ok",...ne?{diagnostics:[ne],warnings:[...Array.isArray(ge.warnings)?ge.warnings:[],Ol(ne)]}:Array.isArray(ge.warnings)&&ge.warnings.length>0?{warnings:ge.warnings}:{}}}async function Om(e,t,r,n,o,a=null,i=null,l={}){let s=l.generateRedlines!==!1,c=typeof l?.onInfo=="function"?l.onInfo:()=>{},f=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:u,xmlDoc:d,operationSession:m}=Kr(e,l);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||Sn(d,l),g=At(d,t,a,"highlight",i,{...l,onInfo:c,onWarn:f});if(g?.error||!g?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:g?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let h=g.paragraph,v=u.serializeToString(h),w=Nl(v,r,n,{generateRedlines:s,author:o,_revisionIdAllocator:p});if(!w||w===v)return{documentXml:e,hasChanges:!1};let{replacementNodes:y}=Sr(w),x=h.parentNode;for(let b of y){let T=d.importNode(b,!0);let A=x.insertBefore(T,h);l?._mutationLiveNodes?.push(A)}return l?._mutationRemovedNodes?.push(h),x.removeChild(h),ot(d),{documentXml:nt(d,u,e,m),hasChanges:!0}}async function km(e,t,r,n,o,a=null,i=null,l={}){let s=typeof l?.onInfo=="function"?l.onInfo:()=>{},c=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:f,xmlDoc:u,operationSession:d}=Kr(e,l);if(!u)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};d||Sn(u,l);let m=At(u,t,a,"comment",i,{...l,onInfo:s,onWarn:c});if(m?.error||!m?.paragraph)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:m?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let p=m.paragraph,g=f.serializeToString(p),h=typeof r=="string"&&r.length>0?r:ho(p),v=sl(g,[{paragraphIndex:1,textToFind:h,commentContent:n}],{author:o,commentIdAllocator:l.commentIdAllocator});if(v.status==="error"||v.error||!v.commentsApplied)return{documentXml:e,hasChanges:!1,commentsXml:null,status:"error",error:v.error||{code:"ANCHOR_INSERTION_FAILED",message:"The comment anchor was not applied to the resolved paragraph."},warnings:v.warnings||[]};let{replacementNodes:w}=Sr(v.oxml),y=p.parentNode;for(let x of w){let b=u.importNode(x,!0);let T=y.insertBefore(b,p);l?._mutationLiveNodes?.push(T)}if(l?._mutationRemovedNodes?.push(p),y.removeChild(p),ot(u),d?.receiptCollector&&Array.isArray(v.placedComments))for(let x of v.placedComments)d.receiptCollector.recordComment(x.id);return{documentXml:nt(u,f,e,d),hasChanges:!0,commentsXml:v.commentsXml||null,warnings:v.warnings||[],resolvedAnchor:v.resolvedAnchors?.[0]||null}}function Sm(e,t,r,n){let o=t.cloneNode(!0),a=t.cloneNode(!0);$t(a,n);let i=d=>{if(d.nodeType!==1)return!1;let m=d.localName||d.nodeName.replace(/^w:/,"");return["t","tab","br","noBreakHyphen","delText"].includes(m)};Array.from(o.childNodes).forEach(d=>{i(d)&&o.removeChild(d)}),Array.from(a.childNodes).forEach(d=>{i(d)&&a.removeChild(d)});let l="";for(let d of Array.from(t.childNodes)){if(d.nodeType!==1)continue;let m=d.localName||d.nodeName.replace(/^w:/,"");m==="t"?l+=d.textContent||"":m==="tab"?l+=" ":m==="br"?l+=`
|
|
228
|
+
`:m==="noBreakHyphen"&&(l+="\u2011")}let s=l.slice(0,r),c=l.slice(r),f=(d,m)=>{let p=m.split(/(\t|\n|\u2011)/);for(let g of p)if(g)if(g===" ")d.appendChild($(e,"w:tab"));else if(g===`
|
|
229
|
+
`)d.appendChild($(e,"w:br"));else if(g==="\u2011")d.appendChild($(e,"w:noBreakHyphen"));else{let h=$(e,"w:t");/^\s|\s$/.test(g)&&h.setAttribute("xml:space","preserve"),h.textContent=g,d.appendChild(h)}};f(o,s),f(a,c);let u=t.parentNode;return u.insertBefore(o,t),u.insertBefore(a,t),u.removeChild(t),[o,a]}async function Mm(e,t,r,n={},o,a=null,i=null,l={}){let s=l.generateRedlines!==!1,c=typeof l?.onInfo=="function"?l.onInfo:()=>{},f=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:u,xmlDoc:d,operationSession:m}=Kr(e,l);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||Sn(d,l),g=At(d,t,a,"format",i,{...l,onInfo:c,onWarn:f});if(g?.error||!g?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:g?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let h=g.paragraph,w=(()=>{let C=[],P=Array.from(h.getElementsByTagNameNS(ce,"r"));for(let M of P){let _=M.parentNode,k=!1;for(;_&&_!==h;){if(_.nodeType===1&&(_.localName==="del"||_.nodeName==="w:del")){k=!0;break}_=_.parentNode}if(k)continue;let L="";for(let D of Array.from(M.childNodes)){if(D.nodeType!==1)continue;let X=D.localName||D.nodeName.replace(/^w:/,"");X==="t"?L+=D.textContent||"":X==="tab"?L+=" ":X==="br"?L+=`
|
|
230
|
+
`:X==="noBreakHyphen"&&(L+="\u2011")}L.length>0&&C.push({run:M,text:L})}return C})(),y="",x=[];for(let C of w){let P=y.length;y+=C.text;let M=y.length;x.push({...C,start:P,end:M})}let b=l.targetDescriptor,T=Number.isInteger(l.textOccurrence)&&l.textOccurrence>0?l.textOccurrence:null,A=T??b?.occurrence??null,E=-1;if(A!=null&&A>0){let C=0,P=0;for(;P<=y.length-r.length;){let M=y.indexOf(r,P);if(M===-1)break;if(C++,C===A){E=M;break}P=M+1}}else E=y.indexOf(r);if(E===-1&&T!=null&&y.includes(r))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PATCH_SOURCE_NOT_FOUND",message:`Occurrence ${T} of text to format was not found in target paragraph: "${r}".`}};if(E===-1)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"TARGET_NOT_FOUND",message:`Text to format was not found in target paragraph: "${r}".`}};let I=E+r.length,R=[];for(let C of x)if(C.start<E&&C.end>E){let P=E-C.start,[M,_]=Sm(d,C.run,P,p);R.push({run:M,start:C.start,end:E,text:C.text.slice(0,P)}),R.push({run:_,start:E,end:C.end,text:C.text.slice(P)})}else R.push(C);let S=[];for(let C of R)if(C.start<I&&C.end>I){let P=I-C.start,[M,_]=Sm(d,C.run,P,p);S.push({run:M,start:C.start,end:I,text:C.text.slice(0,P)}),S.push({run:_,start:I,end:C.end,text:C.text.slice(P)})}else S.push(C);let N=S.filter(C=>C.start>=E&&C.end<=I),O=!1;for(let C of N){let P=C.run.getElementsByTagNameNS(ce,"rPr")[0]||null;if(Nu(P,n)){O=!0;break}}if(!O)return{documentXml:e,hasChanges:!1,status:"no-op"};for(let C of N){let P=C.run,M=P.getElementsByTagNameNS(ce,"rPr")[0];M||(M=$(d,"w:rPr"),P.insertBefore(M,P.firstChild));let _=P.parentNode,k=!1;for(;_&&_!==h;){if(_.nodeType===1&&(_.localName==="ins"||_.nodeName==="w:ins")){(_.getAttribute("w:author")||_.getAttributeNS(ce,"author"))===(o||ae())&&(k=!0);break}_=_.parentNode}let L=k&&l.formattingRevisionPolicy==="coalesce-own-insertion";s&&!L&&Mo(d,M,o||ae()),Tu(d,M,n)}return ot(d),l?._mutationLiveNodes?.push(h),{documentXml:nt(d,u,e,m),hasChanges:!0,status:"ok"}}async function Lm(e,t,r={},n,o=null,a=null,i={}){let l=i.generateRedlines!==!1,s=typeof i?.onInfo=="function"?i.onInfo:()=>{},c=typeof i?.onWarn=="function"?i.onWarn:()=>{},{serializer:f,xmlDoc:u,operationSession:d}=Kr(e,i);if(!u)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};d||Sn(u,i);let m=At(u,t,o,"paragraph-format",a,{...i,onInfo:s,onWarn:c});if(m?.error||!m?.paragraph)return{documentXml:e,hasChanges:!1,status:"error",error:m?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let p=m.paragraph,g=p.getElementsByTagNameNS(ce,"pPr")[0];g||(g=$(u,"w:pPr"),p.insertBefore(g,p.firstChild));let h=Ci(r),v=h.length>0?[Wd(h)]:[];if(r?.numbering){let y=Mf(a?.numberingIdState,r.numbering.numId,Number(r.numbering.level)||0);if(!y.ok)return{documentXml:e,hasChanges:!1,status:"error",error:{code:Fd,message:`${y.message} paragraph-format.numbering binds to an existing list; it never creates one.`,field:"properties.numbering",numId:Number(r.numbering.numId),level:Number(r.numbering.level)||0,reason:y.reason,recovery:{action:"inspect_numbering",hint:"Inspect a paragraph already in the target list and pass its list.numId and list.level. To start a new list, use a list-change/redline operation."}}}}if(!Su(g,r))return{documentXml:e,hasChanges:!1,status:"no-op",...Li(v)};if(l){let y=n||ae(),x=Qe(g,"pPrChange"),b=x?.getAttribute("w:author")??x?.getAttribute("author")??"";if(x&&b!==y)return{documentXml:e,hasChanges:!1,status:"error",error:{code:Dd,message:`Target paragraph already has a pending paragraph-property change by "${b||"unattributed"}". Overwriting its snapshot would change what Reject All restores.`,pendingAuthor:b,recovery:{action:"resolve_pending_revision",hint:"Ask the user to accept or reject the existing paragraph formatting change first; this tool does not resolve revisions by other reviewers."}}};x||Hn(u,g,y)}return Kn(u,g,r),ot(u),i?._mutationLiveNodes?.push(p),{documentXml:nt(u,f,e,d),hasChanges:!0,status:"ok",...Li(v)}}function Bm(e,t,r,n,o,a,i){let l=At(e,t,r,o,a,i);if(l?.error||!l?.paragraph)return{error:l?.error||{code:"TARGET_NOT_FOUND",message:"Target paragraph not found."}};let s=l.paragraph;if(!(i._compiledSourceEndId||n!=null||i.targetEndDescriptor))return{paragraphs:[s]};let f=null;if(i._compiledSourceEndId||i.targetEndDescriptor){let u=At(e,i.targetEndDescriptor?.text||"",i._compiledSourceEndId?n:i.targetEndDescriptor?.index??n,o,a,{...i,...i.targetEndDescriptor?{targetDescriptor:i.targetEndDescriptor}:{},_compiledSourceId:i._compiledSourceEndId||null,_resolutionCapture:null});if(u?.error)return{error:u.error};let d=u?.paragraph?se(e):[],m=d.indexOf(s),p=d.indexOf(u?.paragraph);f=m>=0&&p>=m?d.slice(m,p+1):null}else f=cn(e,r,n,{opType:o,targetRefSnapshot:a?.targetRefSnapshot||null,onInfo:i.onInfo,onWarn:i.onWarn});return!Array.isArray(f)||f.length===0||f[0]!==s?{error:{code:"TARGET_RANGE_INVALID",message:"targetEnd must resolve to the target paragraph or a paragraph after it."}}:{paragraphs:f}}async function $m(e,t,r,n,o=null,a=null,i=null,l={}){let s=l.generateRedlines!==!1,c=typeof l?.onInfo=="function"?l.onInfo:()=>{},f=typeof l?.onWarn=="function"?l.onWarn:()=>{},{serializer:u,xmlDoc:d,operationSession:m}=Kr(e,l);if(!d)return{documentXml:e,hasChanges:!1,status:"error",error:{code:"PARSE_ERROR",message:"Could not parse document OOXML."}};let p=m?.revisionIdAllocator||Sn(d,l),g=Bm(d,t,o,a,"list-format",i,{...l,onInfo:c,onWarn:f});if(g.error)return{documentXml:e,hasChanges:!1,status:"error",error:g.error};let h=g.paragraphs;if(h.some(x=>x.parentNode!==h[0].parentNode))return{documentXml:e,hasChanges:!1,status:"error",error:{code:"TARGET_RANGE_INVALID",message:"A list-format range must stay inside one container (the body, or one table cell)."}};let v=se(d),w=Pl(r);if(w.mode==="change-format"||w.mode==="join")return Sx(d,h,w,{documentXml:e,serializer:u,operationSession:m,runtimeContext:i,options:l,author:n,generateRedlines:s,onInfo:c,onWarn:f,paragraphIndexOf:x=>{let b=v.indexOf(x);return b>=0?b+1:null}});let y=Xl(d,h,w,{author:n||ae(),generateRedlines:s,revisionIdAllocator:p,runtimeContext:i,stylesXml:i?.stylesXml||l.stylesXml||null,numberingXml:i?.numberingXml||l.numberingXml||null,paragraphIndexOf:x=>v.indexOf(x)+1});if(!y.ok)return{documentXml:e,hasChanges:!1,status:"error",error:y.error};for(let x of y.items)x.paragraph,l?._mutationLiveNodes?.push(x.paragraph);for(let x of y.allocatedNumIds)m?.receiptCollector?.recordNumbering(x);return ot(d),c(`[List] list-format convert-plain bound ${y.items.length} paragraph(s) as ${y.format} (numId ${[...new Set(y.items.map(x=>x.numId))].join(", ")}).`),{documentXml:nt(d,u,e,m),hasChanges:!0,status:"ok",numberingXml:y.numberingXml,list:{mode:"convert-plain",format:y.format,level:y.level,strip:y.strip,items:y.items.map(x=>({paragraphIndex:x.paragraphIndex,paragraphId:He(x.paragraph),marker:x.marker,value:x.value,numId:x.numId})),skipped:y.skipped.map(x=>({paragraphIndex:x.paragraphIndex,reason:x.reason}))}}}function Sx(e,t,r,n){let{documentXml:o,serializer:a,operationSession:i,runtimeContext:l,options:s,author:c,generateRedlines:f,onInfo:u,paragraphIndexOf:d}=n,m=x=>({documentXml:o,hasChanges:!1,status:"error",error:x}),p=l?.numberingIdState?.sourceNumberingXml||l?.numberingXml||s.numberingXml||"",g=Array.isArray(i?.numberingXmlParts)?i.numberingXmlParts:[],h=g.length>0?vr(p,g):p,v={author:c||ae(),generateRedlines:f,runtimeContext:l,stylesXml:l?.stylesXml||s.stylesXml||null,numberingXml:h,paragraphIndexOf:d},w;if(r.mode==="join"){let x=s.continueFromDescriptor||null,b=x?At(e,x.text||"",x.index??null,"list-format",l,{...s,targetDescriptor:x,_compiledSourceId:s._compiledContinueFromId||null,_compiledResolvedBy:null,_resolutionCapture:null}):null;if(!b?.paragraph)return m({code:b?.error?.code||"TARGET_NOT_FOUND",message:`list.continueFrom: ${b?.error?.message||"paragraph not found."}`,field:"list.continueFrom"});w=cm(e,t,b.paragraph,r,v)}else w=lm(e,t,r,v);if(!w.ok)return m(w.error);if(w.unchanged){let x=`${Cd}: ${w.message}`;return n.onWarn?.(x),{documentXml:o,hasChanges:!1,status:"ok",warnings:[x]}}for(let x of w.items)x.paragraph,s?._mutationLiveNodes?.push(x.paragraph);for(let x of w.allocatedNumIds)i?.receiptCollector?.recordNumbering(x);ot(e);let y=w.items.filter(x=>!x.inTarget).length;return u(`[List] list-format ${w.mode} (${w.scope}) rebound ${w.items.length} paragraph(s) from numId ${w.sourceNumId} to numId ${w.numId}${y?` (${y} outside the target range)`:""}.`),{documentXml:nt(e,a,o,i),hasChanges:!0,status:"ok",numberingXml:w.numberingXml,list:{mode:w.mode,scope:w.scope,sourceNumId:w.sourceNumId,numId:w.numId,...w.mode==="change-format"?{format:w.format,level:w.level,lvlText:w.lvlText,levelStarts:w.levelStarts}:{continueFrom:w.continueFrom},items:w.items.map(x=>({paragraphIndex:x.paragraphIndex,paragraphId:He(x.paragraph),level:x.level,numId:x.numId,sourceNumId:x.sourceNumId,inTarget:x.inTarget})),skipped:w.skipped.map(x=>({paragraphIndex:x.paragraphIndex,reason:x.reason}))}}}var Ax=new Set(["body","tc","txbxContent","footnote","endnote","comment","hdr","ftr"]),Ex=new Set(["hyperlink","fldSimple","sdt","smartTag","customXml"]),Rx=new Set(["rPr","pPrChange","sectPr"]),Rt=e=>{let t=e?.localName;return t?t.indexOf(":")<0?t:t.replace(/^.*:/,""):String(e?.nodeName||"").replace(/^.*:/,"")},vo=e=>e?.nodeType===1&&(!e.namespaceURI||e.namespaceURI===B),Gr=(e,t)=>e?.getAttribute?.(`w:${t}`)||e?.getAttribute?.(t)||"";function Dm(e,t){let r=[];if(!e)return r;let n=[];for(let o=e.lastChild;o;o=o.previousSibling)n.push(o);for(;n.length;){let o=n.pop();if(o.nodeType===1){o.namespaceURI===B&&o.localName===t&&r.push(o);for(let a=o.lastChild;a;a=a.previousSibling)n.push(a)}}return r}function Et(e,t){for(let r=e?.firstChild;r;r=r.nextSibling)if(vo(r)&&Rt(r)===t)return r;return null}function Px(e){let t=Et(Et(e,"pPr"),"rPr");if(!t)return null;for(let r=t.firstChild;r;r=r.nextSibling){if(!vo(r))continue;let n=Rt(r);if(n==="ins"||n==="moveTo")return"ins";if(n==="del"||n==="moveFrom")return"del"}return null}function Cx(e){for(let t=e.parentNode;t;t=t.parentNode)if(Ax.has(Rt(t)))return t;return null}function _x(e,t){let r=t==="rejected"?"ins":"del";for(let n=e.parentNode;n;n=n.parentNode){let o=Rt(n);if(o==="tr"){if(Et(Et(n,"trPr"),r))return!0}else if(o==="tc"){let a=t==="rejected"?"cellIns":"cellDel";if(Et(Et(n,"tcPr"),a))return!0}else if(o==="body")break}return!1}function Um(e){let t=Array.from(e.attributes||[]).filter(n=>!/^xmlns(:|$)/.test(n.name)&&!/(^|:)(rsid\w*|paraId|textId)$/.test(n.name)).map(n=>`${n.name.replace(/^.*:/,"")}=${n.value}`).sort(),r=Array.from(e.childNodes||[]).filter(vo).map(Um).sort();return`${Rt(e)}[${t.join(",")}]{${r.join("")}}`}function Ox(e,t){let r=Et(e,"pPr"),n=r;if(t==="rejected"){let i=Et(r,"pPrChange");i&&(n=Et(i,"pPr"))}let o=null,a=[];for(let i of Array.from(n?.childNodes||[]))if(!(!vo(i)||Rx.has(Rt(i)))){if(Rt(i)==="numPr"){o={numId:Gr(Et(i,"numId"),"val")||null,ilvl:Gr(Et(i,"ilvl"),"val")||"0"};continue}a.push(Um(i))}return{props:a.sort().join(""),numPr:o}}function kx(e){let t=Rt(e);if(t==="hyperlink")return`hyperlink:${e.getAttribute?.("r:id")||Gr(e,"anchor")||""}`;if(t==="fldSimple")return`fldSimple:${Gr(e,"instr").trim()}`;if(t==="sdt"){let r=Et(e,"sdtPr");return`sdt:${Gr(Et(r,"id"),"val")}:${Gr(Et(r,"tag"),"val")}`}return`${t}:${Gr(e,"element")||Gr(e,"uri")}`}function Mx(e,t){let r="",n=[],o=(a,i)=>{for(let l=a.firstChild;l;l=l.nextSibling){if(!vo(l))continue;let s=Rt(l);if(s!=="pPr"&&!(t==="rejected"&&(s==="ins"||s==="moveTo"))&&!(t==="accepted"&&(s==="del"||s==="moveFrom"))){if(s==="r"){let c=r.length;if(r+=gr(l,{revisionView:t,boundary:e}),r.length>c)for(let f of i)n.push({key:f,start:c,end:r.length});continue}o(l,Ex.has(s)?[...i,kx(l)]:i)}}};return o(e,[]),{text:r,spans:n}}function Lx(e){let t=new Map;for(let r of e){let n=t.get(r.key)||[],o=n[n.length-1];o&&o.end>=r.start?o.end=Math.max(o.end,r.end):n.push({...r}),t.set(r.key,n)}return[...t.values()].flat().sort((r,n)=>r.start-n.start||r.end-n.end||(r.key<n.key?-1:1)).map(r=>`${r.key}@${r.start}-${r.end}`)}function tc(e,t="rejected"){if(t!=="rejected"&&t!=="accepted")throw new Error(`Unknown revision view '${t}'.`);let r=Dm(e,"p"),n=t==="rejected"?"ins":"del",o=[],a=new Map;r.forEach((i,l)=>{if(_x(i,t))return;let s=Cx(i),c=a.get(s)||null;a.delete(s);let{text:f,spans:u}=Mx(i,t),d=c?c.text.length:0,m={text:(c?.text||"")+f,spans:[...c?.spans||[],...u.map(p=>({...p,start:p.start+d,end:p.end+d}))]};if(Px(i)===n){a.set(s,{...m,paragraph:i,sourceIndex:l});return}o.push(Fm(i,m,t,s,l))});for(let[i,l]of a)!(t==="rejected"&&Rt(i)==="tc")&&l.text.length===0||o.push(Fm(l.paragraph,l,t,i,l.sourceIndex));return o.sort((i,l)=>i.sourceIndex-l.sourceIndex),Bx(e,r,o),o}function Bx(e,t,r){let n=Rt(e)==="body"?[e]:Dm(e,"body");for(let o of n){let a=Array.from(o.childNodes||[]).filter(l=>vo(l)&&Rt(l)!=="sectPr"),i=a[a.length-1];!i||Rt(i)!=="tbl"||r.push({text:"",props:"",numPr:null,wrappers:[],container:"body",sourceIndex:t.length,implicit:!0})}}function Fm(e,t,r,n,o){let{props:a,numPr:i}=Ox(e,r);return{text:t.text,props:a,numPr:i,wrappers:Lx(t.spans),container:n?Rt(n):"root",sourceIndex:o}}var Xm=Object.freeze(["enforce","warn","off"]),Wm="enforce",rc=5,zm=120,Cn=Object.freeze({REJECT_PARAGRAPH_COUNT:{explanation:"Reject All of the output has a different number of paragraphs than the source: a paragraph was created or removed without a tracked paragraph mark.",retry:"Target one paragraph at a time; add new paragraphs with a separate insertion instead of folding them into a replacement; do not merge or split paragraphs in the same operation as a text edit."},REJECT_PARAGRAPH_TEXT:{explanation:"Reject All of the output shows different paragraph text than the source: text, a tab or a manual line break changed without being tracked, or was reordered.",retry:"Use replacements (find/replace) for a small literal change, keep manual line breaks and tabs where they are, and retry with the exact current paragraph text from a fresh extraction."},REJECT_PARAGRAPH_PROPS:{explanation:"Reject All of the output shows different paragraph properties (style, alignment, spacing, indentation) than the source: a property changed without a tracked w:pPrChange.",retry:"Change paragraph formatting with a separate paragraph-format operation and keep the text edit free of style or list changes."},REJECT_NUMBERING_REFS:{explanation:"Reject All of the output puts a source paragraph in a different list or list level (numId/ilvl) than the source, so the restored document would number differently.",retry:"Edit list item text without changing list markers or indentation, and make list membership or level changes in their own operation."},ACCEPT_NEIGHBORS:{explanation:"An untracked edit changed a paragraph outside its target, so the change could not be reviewed or undone.",retry:"Re-extract the target and retry against exactly that paragraph; if the edit must span several paragraphs, use a tracked operation with an explicit targetEnd range."},UNTRACKED_CREATED_REVISION:{explanation:"An untracked edit (generateRedlines: false) created a tracked revision (w:ins, w:del, a move, a property change or a paragraph-mark revision) that was not in the source, so the edit is not the plain change the caller asked for.",retry:"Retry the same edit against the current extraction; if it is refused again the untracked path wrote a tracked revision, so report the operation instead of working around it, or make the edit tracked (generateRedlines: true) if a reviewable change is acceptable."},ACCEPT_INTENT:{explanation:"Accept All of the target of the operation would not read as the complete replacement text the operation declared: content was lost, duplicated or left out of the accepted result.",retry:"Re-extract the target paragraph(s) and retry with the exact current text as the basis; for a small literal change use replacements instead of complete modified text, and keep list, table and Markdown structure out of a plain-text edit."},REJECT_WRAPPERS:{explanation:"Reject All of the output moves text into or out of a hyperlink, field or content control compared with the source.",retry:"Keep the change entirely inside or entirely outside the hyperlink, field or content control, for example with replacements that do not cross its boundary."}});function yo(e){if(e==null)return null;let t=typeof e=="string"?e:JSON.stringify(e);return t.length>zm?`${t.slice(0,zm-3)}...`:t}function xo(e){return e?{sourceParagraphIndex:e.sourceIndex+1,container:e.container,text:yo(e.text)}:null}function nc(e){return{document:e,accepted:null,rejected:null,revisionSignatures:null,numberingRefs:null}}function _n(e,t,r){return e?e[r]||(e[r]=tc(t,r)):tc(t,r)}function Km({before:e,after:t,baselineView:r="rejected",acceptedScope:n=null,beforeViews:o=null,afterViews:a=null}){let i=Array.isArray(t)?t:_n(a,t,"rejected"),l=Array.isArray(e)?e:_n(o,e,"rejected"),s=r==="accepted"&&!Array.isArray(e)?zx(l,_n(o,e,"accepted"),i,n):l,c=[],f=(u,d,m,p,g,h)=>{c.push({invariant:u,paragraph:d,expected:yo(m),actual:yo(p),explanation:Cn[u].explanation,source:xo(g),output:xo(h)})};if(s.length!==i.length){let u=0;for(;u<s.length&&u<i.length&&ga(s[u],i[u]);)u++;return f("REJECT_PARAGRAPH_COUNT",u+1,`${s.length} paragraphs`,`${i.length} paragraphs`,s[u]||s[s.length-1],i[u]||i[i.length-1]),{ok:!1,violations:c,afterProjection:i}}for(let u=0;u<s.length&&c.length<rc;u++){let d=s[u],m=i[u],p=u+1;d.container!==m.container?f("REJECT_PARAGRAPH_COUNT",p,`paragraph in ${d.container}`,`paragraph in ${m.container}`,d,m):d.text!==m.text?f("REJECT_PARAGRAPH_TEXT",p,d.text,m.text,d,m):(d.numPr?.numId??null)!==(m.numPr?.numId??null)||(d.numPr?.ilvl??null)!==(m.numPr?.ilvl??null)?f("REJECT_NUMBERING_REFS",p,d.numPr,m.numPr,d,m):d.props!==m.props?f("REJECT_PARAGRAPH_PROPS",p,d.props,m.props,d,m):d.wrappers.join("|")!==m.wrappers.join("|")&&f("REJECT_WRAPPERS",p,d.wrappers,m.wrappers,d,m)}return c.length?{ok:!1,violations:c,afterProjection:i}:{ok:!0,afterProjection:i}}var ga=(e,t)=>e.text===t.text&&e.props===t.props&&e.container===t.container&&(e.numPr?.numId??null)===(t.numPr?.numId??null)&&(e.numPr?.ilvl??null)===(t.numPr?.ilvl??null)&&e.wrappers.join("|")===t.wrappers.join("|");function Gm({before:e,after:t,targetSourceIndex:r,beforeViews:n=null,afterViews:o=null}){let a=[];for(let i of["accepted","rejected"]){let l=_n(n,e,i),s=_n(o,t,i),c=l.findIndex(m=>m.sourceIndex>=r);if(c<0)continue;let f=l.length-c-1,u=0;for(;u<c&&u<s.length&&ga(l[u],s[u]);)u++;let d=0;for(;d<f&&d<s.length-u&&ga(l[l.length-1-d],s[s.length-1-d]);)d++;if(u<c)a.push(Vm(u+1,l[u],s[u],i));else if(d<f){let m=l.length-1-d;a.push(Vm(m+1,l[m],s[s.length-1-d],i))}if(a.length)break}return a.length?{ok:!1,violations:a}:{ok:!0}}var pa=new Map,$x=8;function Fx(e){let t=pa.get(e);if(t)return t;let r=new Map;for(let a of e.matchAll(/<(?:\w+:)?abstractNum\b([^>]*)>([\s\S]*?)<\/(?:\w+:)?abstractNum>/g)){let i=/abstractNumId="([^"]*)"/.exec(a[1])?.[1];if(i==null)continue;let l=r.get(i)||new Set;for(let s of a[2].matchAll(/<(?:\w+:)?lvl\b[^>]*?ilvl="([^"]*)"/g))l.add(s[1]);r.set(i,l)}let n=new Map;for(let a of e.matchAll(/<(?:\w+:)?num\b([^>]*)>([\s\S]*?)<\/(?:\w+:)?num>/g)){let i=/numId="([^"]*)"/.exec(a[1])?.[1],l=/abstractNumId[^>]*?val="([^"]*)"/.exec(a[2])?.[1];i!=null&&l!=null&&n.set(i,l)}let o={abstractLevels:r,numToAbstract:n};return pa.size>=$x&&pa.delete(pa.keys().next().value),pa.set(e,o),o}function Hm({before:e,after:t,numberingXmls:r}){let n=c=>{let f=new Map;for(let u of Bn(c)){let d=u.getAttribute("w:val");if(d===null||d===""||d==="0")continue;let p=Array.from(u.parentNode?.childNodes||[]).find(g=>g.nodeType===1&&Bi(g)==="ilvl")?.getAttribute("w:val")||"0";f.has(d)||f.set(d,new Set),f.get(d).add(p)}return f},o=n(t);if(o.size===0)return{ok:!0};let a=n(e),{abstractLevels:i,numToAbstract:l}=Fx((r||[]).filter(Boolean).join(`
|
|
231
|
+
`)),s=[];for(let[c,f]of o){if(a.has(c))continue;let u=l.get(c),d=u!=null?i.get(u):null,m=null;if(u==null)m=`numId ${c} has no w:num in the output numbering`;else if(!d)m=`numId ${c} points at missing w:abstractNum ${u}`;else{let p=[...f].find(g=>!d.has(g));p!==void 0&&(m=`numId ${c} level ${p} is not defined by w:abstractNum ${u}`)}if(m!==null&&(s.push({invariant:"REJECT_NUMBERING_REFS",paragraph:null,expected:`numId ${c} defined in the output numbering`,actual:m,explanation:"The output (or what Reject All restores) references a list numId that no numbering definition in the output provides, so Word would drop or renumber the list.",source:null,output:null}),s.length>=rc))break}return s.length?{ok:!1,violations:s}:{ok:!0}}var Dx=/\+\+|==|[*_#>`|~\[\]\\]/,Ux=/^\s*(?:[-+•●]|[A-Za-z0-9]{1,5}[.)]|\d[0-9.]*[.)]?|\(\w{1,4}\))\s/m;function qm(e){return typeof e=="string"&&e.length>0&&!Dx.test(e)&&!Ux.test(e)}function Ym({before:e,after:t,range:r,modified:n,beforeViews:o=null,afterViews:a=null}){let i=_n(o,e,"accepted"),l=_n(a,t,"accepted"),s=i.filter(p=>p.sourceIndex<r.from).length,c=i.filter(p=>p.sourceIndex>r.to).length,f=i.filter(p=>p.sourceIndex>=r.from&&p.sourceIndex<=r.to);if(f.length!==r.to-r.from+1||f.some(p=>p.container!=="body"))return{ok:!0,skipped:"target not positionally comparable"};let u=l.slice(s,Math.max(s,l.length-c)),d=u.map(p=>p.text).join(`
|
|
232
|
+
`),m=p=>p.replace(/\r?\n/g,"");return d===n||m(d)===m(n)?{ok:!0}:{ok:!1,violations:[{invariant:"ACCEPT_INTENT",paragraph:null,expected:n,actual:d,explanation:Cn.ACCEPT_INTENT.explanation,source:f[0]?xo(f[0]):null,output:u[0]?xo(u[0]):null}]}}var Xx=new Set(["ins","del","moveFrom","moveTo","rPrChange","pPrChange","sectPrChange","tblPrChange","tblGridChange","tblPrExChange","trPrChange","tcPrChange","numberingChange","cellIns","cellDel","cellMerge"]),Bi=e=>e.localName||String(e.nodeName).replace(/^.*:/,"");function jm(e){let t=new Map,r=[e];for(;r.length;){let n=r.pop();if(n.nodeType===1&&Xx.has(Bi(n))){let o=n.getAttribute("w:id");o!==null&&!t.has(o)&&t.set(o,n)}for(let o=n.firstChild;o;o=o.nextSibling)r.push(o)}return t}function Jm({before:e,after:t,beforeViews:r=null,afterViews:n=null}){let o=f=>`${Bi(f)}|${f.getAttribute("w:author")}|${f.getAttribute("w:date")}`,a=f=>new Map([...f].map(([u,d])=>[u,o(d)])),i=r?.revisionSignatures;i||(i=a(jm(e)),r&&(r.revisionSignatures=i));let l=jm(t);n&&(n.revisionSignatures=a(l));let s=new Set(i.values()),c=[];for(let[f,u]of l){if(i.has(f)||s.has(o(u)))continue;let d=Bi(u),m=u.getAttribute("w:author"),p=yo(u.textContent||"");if(c.push({invariant:"UNTRACKED_CREATED_REVISION",paragraph:null,expected:"no new revisions",actual:`w:${d} w:id=${f}${m?` by ${m}`:""}${p?` ("${p}")`:""}`,explanation:Cn.UNTRACKED_CREATED_REVISION.explanation,source:null,output:null}),c.length>=rc)break}return c.length?{ok:!1,violations:c}:{ok:!0}}function Vm(e,t,r,n){return{invariant:"ACCEPT_NEIGHBORS",paragraph:e,view:n,expected:yo(t?.text??null),actual:yo(r?.text??null),explanation:Cn.ACCEPT_NEIGHBORS.explanation,source:xo(t),output:xo(r)}}function zx(e,t,r,n){if(n&&Number.isInteger(n.from)&&Number.isInteger(n.to)){let c=f=>f.sourceIndex>=n.from&&f.sourceIndex<=n.to;return[...e.filter(f=>!c(f)),...t.filter(c)].sort((f,u)=>f.sourceIndex-u.sourceIndex)}let o=0;for(;o<e.length&&o<r.length&&ga(e[o],r[o]);)o++;let a=0;for(;a<e.length-o&&a<r.length-o&&ga(e[e.length-1-a],r[r.length-1-a]);)a++;if(o+a===e.length&&o+a===r.length)return e;let i=o>0?e[o-1].sourceIndex:-1,l=a>0?e[e.length-a].sourceIndex:1/0,s=t.filter(c=>c.sourceIndex>i&&c.sourceIndex<l);return[...e.slice(0,o),...s,...e.slice(e.length-a)]}function oc(e,t={}){let r=e[0],n=r.source?`source paragraph ${r.source.sourceParagraphIndex}${r.source.text?` ("${r.source.text}")`:""}`:`paragraph ${r.paragraph} of the Reject All view`,o=[...new Set(e.map(i=>i.invariant))],a=t.mode||Wm;return{code:"REVISION_FIDELITY_VIOLATION",stage:"verification",message:`${a==="warn"?"Applied with a fidelity warning":"Refused, document unchanged"}: `+(r.invariant==="UNTRACKED_CREATED_REVISION"?`this untracked operation created a tracked revision (${r.invariant}: `:r.invariant==="ACCEPT_NEIGHBORS"?`this untracked operation changed a paragraph outside its target (${r.invariant} in the ${r.view} view at ${n}: `:r.invariant==="ACCEPT_INTENT"?`Accept All of this operation's target would not read as the requested text (${r.invariant} at ${n}: `:`Reject All of this operation's output would not restore the source (${r.invariant} at ${n}: `)+(r.invariant==="UNTRACKED_CREATED_REVISION"?`found ${r.actual}). `:`expected ${JSON.stringify(r.expected)}, got ${JSON.stringify(r.actual)}). `)+`${r.explanation} Retry: ${Cn[r.invariant].retry}`,violations:e,invariants:o,verificationMode:a,...t.baselineView==="accepted"?{baselineView:"accepted"}:{},recovery:{hint:Cn[r.invariant].retry,retryGuidance:o.map(i=>({invariant:i,retry:Cn[i].retry})),reportIfNarrowRetryFails:"If a narrower operation on the same paragraph is also refused, the shape is unsupported: report the violations with the operation; do not disable verification to force it through."}}}function ac(e){return String(e||"").startsWith("accept-all-first")?"accepted":"rejected"}function ic(e){if(Xm.includes(e))return e;let t=globalThis.process?.env?.DOCX_REDLINE_REVISION_FIDELITY;return Xm.includes(t)?t:Wm}function Ne(e,t={}){return vt(e,t)}async function sc(e,t,r,n=null,o={}){let a=typeof o._operationIndex=="number"?o._operationIndex:1,i={operationIndex:a,...typeof t?.operationId=="string"?{operationId:t.operationId}:{}},l=Nr(t);if(!l.valid){let I=Ut(t,r,ae());return{documentXml:e,hasChanges:!1,status:"error",error:Ne(l.error,i),operationType:St(t).operationKind,authorUsed:I,receipt:ke(a,t?.operationId,I,"refused")}}let s=l.operation||St(t),c=Ut(s,r,ae());if(s.operationKind!=="comment_reply"&&s.operationKind!=="comment_resolve"&&s.operationKind!=="rejected-insert"&&s.operationKind!=="restore"&&(s.targetDescriptor?.revisionView==="rejected"||s.targetEndDescriptor?.revisionView==="rejected"))return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"UNSUPPORTED_REVISION_VIEW_MUTATION",message:"Targeting rejected revision view for mutation is not supported yet."},i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};if(!o?._documentOperationSession&&o?.expectedRevision){let I=vn(o.expectedRevision);if(!I.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:I.error?.code||"INVALID_REVISION_TOKEN",message:I.error?.message||"Invalid revision token."},i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};if(o.expectedRevision.scope!=="document-parts")return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'document-parts', got '${o.expectedRevision.scope}'.`},i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};let R=await ea({documentXml:e,commentsXml:n?.commentsXml||o.commentsXml,commentsExtendedXml:n?.commentsExtendedXml||o.commentsExtendedXml,numberingXml:n?.numberingXml||o.numberingXml,stylesXml:n?.stylesXml||o.stylesXml},o);if(!yn(R.value,o.expectedRevision.value))return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${o.expectedRevision.value}', current is '${R.value}'.`,expectedRevision:o.expectedRevision,currentRevision:R},i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")}}let f=o?._documentOperationSession instanceof Wr?o._documentOperationSession:new Wr(e,o);if(!f.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ne(f.parseResult.error,i),warnings:f.parseResult.warnings,operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};if(Array.isArray(s.replacements)||s.operationKind==="restore"&&t?.modified===void 0){let I=po(f.document,[t],{strictTargets:o.strictTargets!==!1,onInfo:o.onInfo,onWarn:o.onWarn}),R=I.bindings[0]?.error||I.conflicts[0]||null;if(R)return{documentXml:e,hasChanges:!1,status:"error",error:Ne(R,i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};let S=Nr(I.compiledOperations[0]);if(!S.valid)return{documentXml:e,hasChanges:!1,status:"error",error:Ne(S.error,i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};f.sourceTargetRegistry=I.registry,s=S.operation}if(Array.isArray(s.replacements)&&!s._localizedReplacementCompilation)return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"PATCH_ROUNDTRIP_MISMATCH",stage:"validation",message:"Localized replacements were not compiled against a batch-start paragraph target, so they were refused instead of applied."},i),operationType:s.operationKind,authorUsed:c,receipt:ke(a,s.operationId,c,"refused")};let u={},d=null,m=f.createSavepoint(),p=f._fidelityViews?.document===f.document?f._fidelityViews:null;f._fidelityViews=null;let g={...p||nc(null),document:m.document},h=nc(f.document);f.receiptCollector?.beginOperation(a,s.operationId,c);let v=Array.isArray(s._compiledWarnings)?[...s._compiledWarnings]:[],w={...o,...typeof s.generateRedlines=="boolean"?{generateRedlines:s.generateRedlines}:{},...s.existingRevisions?{existingRevisions:s.existingRevisions}:{},structuredContent:typeof s.structuredContent=="boolean"?s.structuredContent:o.structuredContent!==!1,explicitStructuredContent:s.structuredContent===!0,plainTextContent:s.structuredContent===!1||s.structuredContent==null&&o.structuredContent===!1,...s._localizedReplacementCompilation&&s.structuredContent!==!0?{literalTextEdit:!0}:{},pairReplacements:typeof s.pairReplacements=="boolean"?s.pairReplacements:o.pairReplacements!==!1,...s.insertionAffinity?{insertionAffinity:s.insertionAffinity}:{},...s.listMarkers?{listMarkers:s.listMarkers}:{},...s.formattingRevisionPolicy?{formattingRevisionPolicy:s.formattingRevisionPolicy}:{},...s.operationKind==="format"&&Number.isInteger(s.textOccurrence)?{textOccurrence:s.textOccurrence}:{},targetDescriptor:s.targetDescriptor,targetEndDescriptor:s.targetEndDescriptor,_compiledSourceId:s._compiledSourceId||null,_compiledSourceEndId:s._compiledSourceEndId||null,...s.operationKind==="list-format"&&s.list?.continueFrom&&typeof s.list.continueFrom=="object"?{continueFromDescriptor:Tn(s.list.continueFrom,null,"accepted"),_compiledContinueFromId:s._compiledContinueFromId||null}:{},_compiledResolvedBy:s._compiledResolvedBy||null,_sourceTargetRegistry:f.sourceTargetRegistry||null,_resolutionCapture:u,_revisionIdAllocator:f.revisionIdAllocator,_documentOperationSession:f,_mutationLiveNodes:[],_mutationRemovedNodes:[],onInfo:I=>{typeof o?.onInfo=="function"&&o.onInfo(I)},onWarn:I=>{v.push(String(I)),typeof o?.onWarn=="function"&&o.onWarn(I)}},y=!!(s.targetEndDescriptor||s.targetEndRef),x=ic(o.verifyRevisionFidelity),b=ac(w.existingRevisions)==="accepted",T=s.operationKind==="redline"&&w.generateRedlines!==!1&&!s._localizedReplacementCompilation&&s.structuredContent!==!0&&qm(s.modified)&&!/\r?\n/.test(String(s.targetDescriptor?.exactText??s.targetDescriptor?.text??(typeof s.target=="string"?s.target:""))),A=x!=="off"&&f.document&&(y&&b||T)?Am(f.document,s.target,s.targetRef,s.targetEndRef,n,w):null,E=A?A.to:null;try{let I;if(s.operationKind==="comment_reply"){let N=f.commentsXml||n?.commentsXml||o.commentsXml,O=f.commentsExtendedXml||n?.commentsExtendedXml||o.commentsExtendedXml,C=typeof o.commentIdAllocator=="function"?o.commentIdAllocator():null;if(C==null&&N){let P=[...N.matchAll(/<(?:w:)?comment\b[^>]*\b(?:w:)?id=["'](\d+)["']/g)].map(M=>Number(M[1]));C=(P.length?Math.max(...P):-1)+1}C==null?I={documentXml:e,hasChanges:!1,status:"error",error:{code:"COMMENTS_PART_MISSING",message:"A comment reply requires an existing comments part."}}:(I=ll({commentsXml:N,commentsExtendedXml:O,documentXml:e,parentCommentId:s.parentCommentId,commentId:C,commentContent:s.commentContent,author:c,date:s.date||new Date().toISOString()}),I.documentXml=e,I.status!=="error"&&I.hasChanges&&(!f.document||!Xf(f.document,I.threadCommentIds,C)?I={documentXml:e,hasChanges:!1,status:"error",error:{code:"PARENT_ANCHOR_NOT_FOUND",message:`Comment '${s.parentCommentId}' has no anchor in the document body, so a reply cannot be placed.`}}:f.receiptCollector&&f.receiptCollector.recordComment(C)))}else if(s.operationKind==="comment_resolve"){let N=ci({commentsXml:f.commentsXml||n?.commentsXml||o.commentsXml,commentsExtendedXml:f.commentsExtendedXml||n?.commentsExtendedXml||o.commentsExtendedXml,commentId:s.commentId,resolved:s.resolved!==!1});I=N.status==="error"?{documentXml:e,hasChanges:!1,status:"error",error:N.error}:{documentXml:e,hasChanges:N.hasChanges,...N.commentsXml?{commentsXml:N.commentsXml,commentsXmlMode:"replace"}:{},...N.commentsExtendedXml?{commentsExtendedXml:N.commentsExtendedXml,commentsExtendedXmlMode:"replace"}:{},resolved:N.resolved,threadRootId:N.threadRootId,commentIds:N.commentIds}}else s.operationKind==="highlight"?I=await Om(e,s.target,s.textToHighlight,s.color,c,s.targetRef,n,w):s.operationKind==="comment"?I=await km(e,s.target,s.textToComment,s.commentContent,c,s.targetRef,n,w):s.operationKind==="format"?I=await Mm(e,s.target,s.textToFormat,s.properties,c,s.targetRef,n,w):s.operationKind==="paragraph-format"?I=await Lm(e,s.target,s.properties,c,s.targetRef,n,w):s.operationKind==="list-format"?I=await $m(e,s.target,s.list,c,s.targetRef,s.targetEndRef,n,w):s.operationKind==="rejected-insert"?I=await Pm(e,s.target,s.anchor,s.modified,c,s.targetRef,n,w):s.operationKind==="restore"?I=await Cm(e,s.target,s.modified,c,s.targetRef,s.targetEndRef,n,w):I=await _m(e,s.target,s.modified,c,s.targetRef,s.targetEndRef,n,w);if((s.operationKind==="comment"||s.operationKind==="comment_reply")&&I?.hasChanges!==!0&&I?.status!=="error"&&!I?.error&&(I={...I,status:"error",error:{code:"COMMENT_NOT_APPLIED",message:"The comment operation completed without placing a comment."}}),v.length>0&&I){let N=Array.from(new Set([...Array.isArray(I.warnings)?I.warnings:[],...v]));I.warnings=N}let R=I?.status==="error"||!!I?.error,S=null;if(R||I?.hasChanges!==!0){f.restoreSavepoint(m);let N=R?"refused":"no_change";if(S=ke(a,s.operationId,c,N),Array.isArray(I?.warnings))for(let O of I.warnings)S.warnings.push(String(O))}else{let N=Mt(m.document),O=Mt(f.document),C=An(O.issues,N.issues),P=En(C);if(P.length>0){f.restoreSavepoint(m),S=ke(a,s.operationId,c,"refused");let L=[...new Set(P.map(D=>D.code))].join(", ");return{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"GENERATED_OOXML_INVALID",stage:"validation",message:`Operation introduced invalid OOXML (${L}).`,generatedIssues:P},i),operationType:s.operationKind,authorUsed:c,receipt:S,...u}}if(s._localizedReplacementCompilation&&s.structuredContent!==!0){let L=null;if(s.operationKind==="restore"){let D=w._mutationLiveNodes.find(X=>X?.localName==="p");D&&(L=Y(D,{revisionView:"accepted"}))}else if(s._compiledSourceId&&f.sourceTargetRegistry){let D=f.sourceTargetRegistry.previewSuccessor(s._compiledSourceId,w._mutationRemovedNodes,w._mutationLiveNodes);D&&(L=Y(D,{revisionView:"accepted"}))}if(L!==s._localizedReplacementCompilation.desiredText){f.restoreSavepoint(m);let D="The localized replacement did not produce the compiled accepted text, so it was refused before commit to avoid losing content. Re-extract the paragraph and retry with its current text.",X=ke(a,s.operationId,c,"refused");return X.warnings.push(D),{documentXml:e,hasChanges:!1,status:"error",error:Ne({code:"PATCH_ROUNDTRIP_MISMATCH",stage:"validation",message:D},i),warnings:[D],operationType:s.operationKind,authorUsed:c,receipt:X,...u}}}let M=ic(o.verifyRevisionFidelity),_=!s.targetEndDescriptor&&!s.targetEndRef?u.resolvedTarget?.index:null,k=M==="off"?null:w.generateRedlines!==!1?"tracked":Number.isInteger(_)?"untracked":null;if(k==="tracked"){let L=ac(w.existingRevisions),D=u.resolvedTarget?.index,X=Number.isInteger(D)?y?Number.isInteger(E)&&E>=D-1?{from:D-1,to:E}:null:{from:D-1,to:D-1}:null,G=Km({before:m.document,after:f.document,baselineView:L,acceptedScope:X,beforeViews:g,afterViews:h}),ee=Hm({before:m.document,after:f.document,numberingXmls:[n?.numberingXml||o.numberingXml,...f.numberingXmlParts||[],I.numberingXml],beforeViews:g,afterViews:h});if(ee.ok||(G.ok=!1,G.violations=[...G.violations||[],...ee.violations]),T&&A){let J=Ym({before:m.document,after:f.document,range:A,modified:s.modified,beforeViews:g,afterViews:h});J.ok||(G.ok=!1,G.violations=[...G.violations||[],...J.violations])}if(!G.ok){let J=oc(G.violations,{mode:M,baselineView:L}),Z=`${J.code} (operation ${a}${s.operationId?` "${s.operationId}"`:""}): ${J.message}`;if(typeof o?.onWarn=="function"&&o.onWarn(Z),M==="enforce"){f.restoreSavepoint(m),f._fidelityViews=g;let ie=ke(a,s.operationId,c,"refused");return ie.warnings.push(Z),{documentXml:e,hasChanges:!1,status:"error",error:Ne(J,i),warnings:[Z],operationType:s.operationKind,authorUsed:c,receipt:ie,...u}}I.warnings=[...Array.isArray(I.warnings)?I.warnings:[],Z],I.revisionFidelityViolations=G.violations}}else{let L=k==="untracked"?Gm({before:m.document,after:f.document,targetSourceIndex:_-1,beforeViews:g,afterViews:h}):{ok:!0};if(L.ok&&M!=="off"&&w.generateRedlines===!1&&(L=Jm({before:m.document,after:f.document,beforeViews:g,afterViews:h})),!L.ok){let D=oc(L.violations,{mode:M}),X=`${D.code} (operation ${a}${s.operationId?` "${s.operationId}"`:""}): ${D.message}`;if(typeof o?.onWarn=="function"&&o.onWarn(X),M==="enforce"){f.restoreSavepoint(m),f._fidelityViews=g;let G=ke(a,s.operationId,c,"refused");return G.warnings.push(X),{documentXml:e,hasChanges:!1,status:"error",error:Ne(D,i),warnings:[X],operationType:s.operationKind,authorUsed:c,receipt:G,...u}}I.warnings=[...Array.isArray(I.warnings)?I.warnings:[],X],I.revisionFidelityViolations=L.violations}}if((k==="tracked"||k==="untracked")&&(f._fidelityViews=h),f.markMutationCommitted(!0),s._compiledSourceId&&f.sourceTargetRegistry&&f.sourceTargetRegistry.commitMutation(s._compiledSourceId,w._mutationRemovedNodes,w._mutationLiveNodes,a),s._localizedReplacementCompilation){let L=null;if(s.operationKind==="restore"){let D=w._mutationLiveNodes.find(X=>X?.localName==="p");D&&(L=Y(D,{revisionView:"accepted"}))}else if(s._compiledSourceId&&f.sourceTargetRegistry){let D=f.sourceTargetRegistry.resolve(s._compiledSourceId,f.document);D.paragraph&&(L=Y(D.paragraph,{revisionView:"accepted"}))}d=xd(s._localizedReplacementCompilation,L,u.resolvedTarget||{},s._speculativeContext||null)}if(s.captureKey&&f.captureTable&&f.captureTable.set(s.captureKey,gm(f,s,w._mutationLiveNodes)),w._mutationRemovedNodes?.length>0&&f.captureTable&&hm(f.captureTable,w._mutationRemovedNodes),u.resolvedTarget&&f.receiptCollector?.recordAffectedTarget(u.resolvedTarget),Array.isArray(I.warnings))for(let L of I.warnings)f.receiptCollector?.recordWarning(L);if(S=f.receiptCollector?.commitOperation("applied"),I.documentXml=f.deferSerialization?f.currentDocumentXml:f.serializeCurrent(),!f.deferSerialization&&S){let L=la({documentXml:I.documentXml,commentsXml:I.commentsXml||null,numberingXml:I.numberingXml||null},[S]);if(!L.valid)return f.restoreSavepoint(m),S.finalDisposition="rolled_back",S.committed=!1,{documentXml:e,hasChanges:!1,status:"error",error:Ne(L.error,i),warnings:[L.error.message],operationType:s.operationKind,authorUsed:c,receipt:S,...u}}}return I?.error&&(I.error=Ne(I.error,i)),{...I,operationType:s.operationKind,authorUsed:c,receipt:S,...d?{change:d}:{},...u}}catch(I){f.restoreSavepoint(m);let R=Ne(I,i),S=ke(a,s.operationId,c,"refused");return S.warnings.push(R.message),{documentXml:e,hasChanges:!1,status:"error",error:R,warnings:[R.message],operationType:s.operationKind,authorUsed:c,receipt:S,...u}}}var Zm="http://schemas.openxmlformats.org/wordprocessingml/2006/main";function Qm(e){return e?.type==="comment"||e?.type==="comment_reply"||e?.type==="comment_resolve"?0:1}function $i(e=[]){let t=Array.isArray(e)?e:[],r=new Map;for(let c=0;c<t.length;c++){let f=t[c],u=f?.captureKey??f?.targetDescriptor?.captureKey;if(u!=null){if(typeof u!="string"||!u.trim()||u.trim().length>256)return{valid:!1,error:{code:"INVALID_OPERATION",message:`Operation ${c+1} declared an invalid captureKey: must be a non-empty string under 256 characters.`}};let d=u.trim();if(r.has(d)){let m=r.get(d);return{valid:!1,error:{code:"DUPLICATE_CAPTURE_KEY",message:`Duplicate capture key "${d}" declared by operations at indices ${m+1} and ${c+1}.`}}}r.set(d,c)}}let n=new Array(t.length).fill(0),o=Array.from({length:t.length},()=>new Set),a=Array.from({length:t.length},()=>new Set),i=new Map;for(let c=0;c<t.length;c++){let f=t[c],u=f?.target?.captureRef??f?.targetDescriptor?.captureRef;if(u!=null){if(typeof u!="string"||!u.trim()||u.trim().length>256)return{valid:!1,error:{code:"INVALID_OPERATION",message:`Operation ${c+1} referenced an invalid captureRef: must be a non-empty string under 256 characters.`}};let d=u.trim();if(!r.has(d))return{valid:!1,error:{code:"CAPTURE_NOT_FOUND",message:`Capture "${d}" referenced by operation ${c+1} was not found in the batch.`}};let m=r.get(d);if(m===c)return{valid:!1,error:{code:"CAPTURE_DEPENDENCY_CYCLE",message:`Capture dependency cycle detected: operation ${c+1} references its own capture "${d}".`}};a[c].has(m)||(a[c].add(m),o[m].add(c),n[c]++);let p=St(f).operationKind;p!=="comment"&&p!=="comment_reply"&&p!=="comment_resolve"&&(i.has(d)||i.set(d,[]),i.get(d).push({index:c,select:f?.target?.select??f?.targetDescriptor?.select??null}))}}for(let c=0;c<t.length;c++){let f=Array.isArray(t[c]?._compiledRunAfter)?t[c]._compiledRunAfter:[];for(let u of f)!Number.isInteger(u)||u<0||u>=t.length||u===c||a[c].has(u)||(a[c].add(u),o[u].add(c),n[c]++)}for(let[c,f]of i){if(f.length<2)continue;let u=f.map(m=>m.select),d=new Set(u);if(!(u.every(m=>typeof m=="string"&&m.length>0)&&d.size===u.length))return{valid:!1,error:{code:"CAPTURE_FANOUT_CONFLICT",message:`Capture "${c}" has overlapping or unscoped mutating consumers at operation indices ${f.map(m=>m.index+1).join(", ")}.`,operationIndexes:f.map(m=>m.index+1),captureRef:c}}}let l=[];for(let c=0;c<t.length;c++)n[c]===0&&l.push({operation:t[c],index:c});let s=[];for(;l.length>0;){l.sort((f,u)=>Qm(f.operation)-Qm(u.operation)||f.index-u.index);let c=l.shift();s.push(c);for(let f of o[c.index])n[f]--,n[f]===0&&l.push({operation:t[f],index:f})}return s.length<t.length?{valid:!1,error:{code:"CAPTURE_DEPENDENCY_CYCLE",message:"Capture dependency cycle detected among batch operations."}}:{valid:!0,scheduled:s,captureProducers:r}}function jx(e,t){if(!t)return e;if(!e)return t;let r=V(e,"application/xml")?.doc,n=V(t,"application/xml")?.doc;if(!r||!n)return e;let o=le(),a=r.documentElement,i=new Set(Array.from(r.getElementsByTagNameNS(Zm,"comment")).map(l=>l.getAttribute("w:id")||l.getAttribute("id")).filter(Boolean));for(let l of Array.from(n.getElementsByTagNameNS(Zm,"comment"))){let s=l.getAttribute("w:id")||l.getAttribute("id");s&&i.has(s)||(a.appendChild(r.importNode(l,!0)),s&&i.add(s))}return o.serializeToString(r)}async function Fi(e,t,r,n=null,o={}){let a=Array.isArray(t)?t:[],i=ae(),l=()=>a.map((N,O)=>ke(O+1,N?.operationId,Ut(N,r,i),"not_attempted")),s=(N,O={})=>{let C=l();return{documentXml:e,hasChanges:!1,commentsXml:null,numberingXmlParts:[],results:[],receipts:C,executionOrder:[],authorsUsed:[],...o.atomic===!0?{rolledBack:!0}:{},status:"error",error:Ne(N),retryPlan:Ir({atomic:o.atomic===!0,rolledBack:o.atomic===!0,results:[],receipts:C,operationCount:a.length}),...O}};if(o.existingRevisions!=null&&!fa(o.existingRevisions))return s({code:"INVALID_OPERATION",message:`Unsupported existingRevisions policy: "${String(o.existingRevisions)}".`,field:"existingRevisions"});if(o?.expectedRevision){let N=vn(o.expectedRevision);if(!N.valid)return s({code:N.error?.code||"INVALID_REVISION_TOKEN",message:N.error?.message||"Invalid revision token."});if(o.expectedRevision.scope!=="document-parts")return s({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'document-parts', got '${o.expectedRevision.scope}'.`,expectedScope:"document-parts",actualScope:o.expectedRevision.scope});let O=await ea({documentXml:e,commentsXml:n?.commentsXml||o.commentsXml,commentsExtendedXml:n?.commentsExtendedXml||o.commentsExtendedXml,numberingXml:n?.numberingXml||o.numberingXml,stylesXml:n?.stylesXml||o.stylesXml},o);if(!yn(O.value,o.expectedRevision.value))return s({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${o.expectedRevision.value}', current is '${O.value}'.`,expectedRevision:o.expectedRevision,currentRevision:O})}let c=o?._documentOperationSession instanceof Wr?o._documentOperationSession:new Wr(e,{...o,_deferDocumentSerialization:!0});if(!c.valid)return s(c.parseResult.error,{warnings:c.parseResult.warnings});let f=po(c.document,a,{strictTargets:o.strictTargets!==!1,onInfo:o.onInfo,onWarn:o.onWarn});if(c.sourceTargetRegistry=f.registry,f.conflicts.length>0){let N=new Map;for(let P of f.conflicts)for(let M of P.operationIndexes)N.has(M)||N.set(M,P);let O=Array.from(N,([P,M])=>{let _=a[P-1],k=Ut(_,r,i),L=Ne(M,{operationIndex:P,..._?.operationId?{operationId:_.operationId}:{}});return{index:P,type:_?.type||"redline",operationType:St(_).operationKind,status:"error",authorUsed:k,error:L,receipt:ke(P,_?.operationId,k,"refused")}}).sort((P,M)=>P.index-M.index),C=a.map((P,M)=>O.find(k=>k.index===M+1)?.receipt||ke(M+1,P?.operationId,Ut(P,r,i),"not_attempted"));return{documentXml:e,hasChanges:!1,commentsXml:null,numberingXmlParts:[],results:O,receipts:C,executionOrder:[],authorsUsed:[],rolledBack:o.atomic===!0,status:"error",error:Ne(f.conflicts[0]),conflicts:f.conflicts.map(P=>Ne(P)),retryPlan:Ir({atomic:o.atomic===!0,rolledBack:o.atomic===!0,results:O,receipts:C,operationCount:a.length})}}let u=f.compiledOperations,d=$i(u);if(!d.valid)return s(d.error);let m=d.scheduled,p=o.atomic===!0,g=o.continueOnError!==!1;if(n&&typeof n=="object"&&!n.numberingIdState){let N=typeof n.numberingXml=="string"&&n.numberingXml.trim()?n.numberingXml:void 0;n.numberingIdState=Ht(N)}let h=qd(n);h.numberingIdState||(h.numberingIdState=Ht(void 0)),h.targetRefSnapshot instanceof Map||(h.targetRefSnapshot=c.initialTargetReferenceSnapshot),c.runtimeContext=h,a.some(N=>N?.type==="comment_reply"||N?.type==="comment_resolve")&&(c.commentsXml=h.commentsXml||o.commentsXml||null,c.commentsExtendedXml=h.commentsExtendedXml||o.commentsExtendedXml||null,c.commentsXmlMode="replace",c.commentsExtendedXmlMode="replace");let v=!1,w=c.results,y=c.executionOrder,x=c.authorsUsed,b=!1;for(let{operation:N,index:O}of m){y.push(O+1);let C=f.bindings[O];if(C?.error){b=!0;let P=Ut(N,r,i),M=ke(O+1,N?.operationId,P,"refused"),_=Ne(C.error,{operationIndex:O+1,...N?.operationId?{operationId:N.operationId}:{}});if(M.warnings.push(_.message),w.push({index:O+1,type:N?.type||"redline",status:"error",operationType:St(N).operationKind,authorUsed:P,warnings:[_.message],error:_,receipt:M}),!g)break;continue}try{let P=await sc(c.currentDocumentXml,N,r,h,{...o,_documentOperationSession:c,_deferDocumentSerialization:!0,_operationIndex:O+1});v=v||P.hasChanges===!0,c.commentsXml=P.commentsXmlMode==="replace"?P.commentsXml||c.commentsXml:jx(c.commentsXml,P.commentsXml||null),c.commentsExtendedXml=(P.commentsExtendedXmlMode==="replace",P.commentsExtendedXml||c.commentsExtendedXml),P.commentsXmlMode==="replace"&&(c.commentsXmlMode="replace"),P.commentsExtendedXmlMode==="replace"&&(c.commentsExtendedXmlMode="replace"),P.numberingXml&&c.numberingXmlParts.push(P.numberingXml);let M=P.status==="error"||!!P.error;if(b=b||M,!M&&P.hasChanges&&P.authorUsed&&x.add(P.authorUsed),w.push({index:O+1,type:N?.type||"redline",status:M?"error":P.hasChanges?"applied":"no_change",operationType:P.operationType||"redline",authorUsed:P.authorUsed,...P.resolvedBy?{resolvedBy:P.resolvedBy}:{},...P.resolvedTarget?{resolvedTarget:P.resolvedTarget}:{},...P.resolvedAnchor?{resolvedAnchor:P.resolvedAnchor}:{},...P.change?{change:P.change}:{},...P.list&&!M?{list:P.list}:{},...P.operationType==="comment_resolve"&&!M?{resolved:P.resolved,threadRootId:P.threadRootId,commentIds:P.commentIds}:{},...Array.isArray(P.warnings)&&P.warnings.length>0?{warnings:P.warnings}:{},...Array.isArray(P.diagnostics)&&P.diagnostics.length>0?{diagnostics:P.diagnostics}:{},...P.error?{error:P.error}:{},...P.receipt?{receipt:P.receipt}:{}}),M&&!g)break}catch(P){let M=Ne(P,{operationIndex:O+1,...N?.operationId?{operationId:N.operationId}:{}});b=!0;let _=Ut(N,r,ae()),k=ke(O+1,N?.operationId,_,"refused");if(k.warnings.push(M.message),w.push({index:O+1,type:N?.type||"redline",status:"error",operationType:St(N).operationKind,authorUsed:_,warnings:[M.message],error:M,receipt:k}),!g)break}}w.sort((N,O)=>N.index-O.index);let T=[];for(let N=0;N<a.length;N++){let O=N+1,C=w.find(P=>P.index===O);if(C?.receipt)T.push(C.receipt);else{let P=ke(O,a[N]?.operationId,Ut(a[N],r,i),"not_attempted");T.push(P)}}let A=p&&b,E=e,I=null;if(!A&&v)try{E=c.serializeCurrent()}catch(N){I=Ne(N),A=!0}let R=null;if(!A&&v){let N=la({documentXml:E,commentsXml:c.commentsXml,commentsExtendedXml:c.commentsExtendedXml,numberingXmlParts:c.numberingXmlParts},T);N.valid||(R=N.error,p&&(A=!0))}if(A){for(let N of w)N.receipt&&N.receipt.attemptedDisposition==="applied"&&(N.receipt.finalDisposition="rolled_back",N.receipt.committed=!1),N.change&&(N.change.finalDisposition="rolled_back",N.change.committed=!1);for(let N of T)N.attemptedDisposition==="applied"&&(N.finalDisposition="rolled_back",N.committed=!1)}else{for(let N of w)N.receipt&&N.receipt.attemptedDisposition==="applied"&&(N.receipt.committed=!0,N.receipt.finalDisposition="applied"),N.change&&(N.change.finalDisposition="applied",N.change.committed=!0);for(let N of T)N.attemptedDisposition==="applied"&&(N.committed=!0,N.finalDisposition="applied")}A||Yd(n,h);let S={documentXml:A?c.rollback():E,hasChanges:A?!1:v,commentsXml:A?null:c.commentsXml,commentsExtendedXml:A?null:c.commentsExtendedXml,commentsXmlMode:c.commentsXmlMode,commentsExtendedXmlMode:c.commentsExtendedXmlMode,numberingXmlParts:A?[]:c.numberingXmlParts,results:[...w].sort((N,O)=>(N.index||0)-(O.index||0)),receipts:T.sort((N,O)=>N.operationIndex-O.operationIndex),executionOrder:y,authorsUsed:A?[]:Array.from(x),...A?{rolledBack:!0,status:"error",error:Ne({code:R?R.code:I?"DOCUMENT_SERIALIZATION_FAILED":"BATCH_OPERATION_FAILED",message:R?.message||I?.message||"Atomic batch rolled back because one or more operations failed."})}:R?{status:"error",error:Ne(R)}:b?{status:v?"partial":"error",error:Ne({code:"BATCH_OPERATION_FAILED",message:"One or more operations failed."})}:{status:"ok"}};return(S.status==="error"||S.status==="partial")&&(S.retryPlan=Ir({atomic:p,rolledBack:A,results:S.results,receipts:S.receipts,operationCount:a.length})),S}function bo(e,t={}){return vt(e,t)}function Vx(e){return e.operationKind==="list-format"?!0:e.operationKind!=="redline"||typeof e.modified!="string"?!1:e.modified.split(/\r?\n/).some(t=>/^\s*(?:[-+*]|\d+[.)])\s+/.test(t))}function Wx(e,t,r,n,o=null,a="accepted"){let i=o?.byParagraph?.get(t)||null,l=i?null:se(e),s=i?.text??Y(t,{revisionView:a}),c=q(n||""),f=q(s);return{resolvedBy:r,resolvedTarget:{index:i?.index??l.indexOf(t)+1,paragraphId:i?.paragraphId??He(t),text:s,fingerprint:i?.fingerprint??Ot(t,{text:s,revisionView:a}),inTable:i?.inTable??!!ct(t,"tbl"),revisionView:a},matchDiagnostics:{exactTextMatch:typeof n=="string"&&n===s,normalizedTextMatch:!!c&&c===f,suppliedText:n||"",actualText:s,revisionView:a}}}function ep(e){let t=new Set;for(let r of["commentRangeStart","commentRangeEnd","commentReference"])for(let n of Array.from(e?.getElementsByTagNameNS?.("*",r)||[])){let o=n.getAttribute("w:id")||n.getAttribute("id");o!==""&&t.add(o)}return Array.from(t).sort((r,n)=>Number(r)-Number(n)||r.localeCompare(n))}function Di(e,t,r,n={}){if(n.existingRevisions!=null&&!fa(n.existingRevisions))return{valid:!1,status:"error",error:bo({code:"INVALID_OPERATION",message:`Unsupported existingRevisions policy: "${String(n.existingRevisions)}".`}),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let o=V(e,"application/xml");if(o.error||!o.doc)return{valid:!1,status:"error",error:bo(o.error),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let a=o.doc,i={accepted:rr(a,{revisionView:"accepted"}),rejected:null},l=Array.isArray(t)?t:[],s=po(a,l,{strictTargets:n.strictTargets!==!1,onInfo:n.onInfo,onWarn:n.onWarn}),c=$i(s.compiledOperations);if(!c.valid)return{valid:!1,status:"error",error:bo(c.error),results:[],conflicts:[],authorsUsed:[],requiredArtifacts:{comments:!1,numbering:!1}};let f=n.strictTargets!==!1,u=[],d=new Set,m=!1,p=!1;for(let y=0;y<l.length;y++){let x=l[y],b=s.bindings[y],T=s.compiledOperations[y],A=!b?.error&&T?._localizedReplacementCompilation?T:x,E=Nr(A),I=St(x),R=E.operation||I,S=Ut(R,r,ae());if(d.add(S),!E.valid){u.push({index:y+1,type:x?.type||"redline",operationType:R.operationKind,status:"error",authorUsed:S,error:E.error});continue}if(m=m||R.operationKind==="comment"||R.operationKind==="comment_reply",p=p||Vx(R),R.operationKind==="comment_resolve"){let C=String(R.commentId);u.push(n._existingCommentDetails?.[C]?{index:y+1,type:x.type,operationType:R.operationKind,status:"ready",authorUsed:S,resolvedBy:"comment_id",commentId:C}:{index:y+1,type:x.type,operationType:R.operationKind,status:"error",authorUsed:S,error:{code:"COMMENT_NOT_FOUND",message:`Comment '${C}' was not found.`}});continue}if(R.operationKind==="comment_reply"){let C=String(R.parentCommentId),P=n._existingCommentDetails?.[C];u.push(P?{index:y+1,type:x.type,operationType:R.operationKind,status:"ready",authorUsed:S,resolvedBy:"parent_comment",parentCommentId:C}:{index:y+1,type:x.type,operationType:R.operationKind,status:"error",authorUsed:S,error:{code:"PARENT_COMMENT_NOT_FOUND",message:`Parent comment '${C}' was not found.`}});continue}if(R.targetDescriptor?.captureRef){u.push({index:y+1,type:x?.type||"redline",operationType:R.operationKind,status:"deferred",authorUsed:S,resolvedBy:"capture",captureRef:R.targetDescriptor.captureRef,...R.targetDescriptor.select?{select:R.targetDescriptor.select}:{}});continue}if(b?.error){u.push({index:y+1,type:x?.type||"redline",operationType:R.operationKind,status:"error",authorUsed:S,error:b.error});continue}if(b?.createdByOperation){u.push({index:y+1,type:x?.type||"redline",operationType:R.operationKind,status:"deferred",authorUsed:S,resolvedBy:"created_content_dependency",captureRef:b.captureRef,select:R.targetDescriptor.text,createdByOperation:b.createdByOperation});continue}let N=R.targetDescriptor?.revisionView==="rejected"?"rejected":"accepted",O=N==="rejected"?i.rejected||(i.rejected=rr(a,{revisionView:"rejected"})):i.accepted;try{let C;if(b.dynamic)C=ln(a,{targetText:R.target,targetRef:R.targetRef,targetDescriptor:R.targetDescriptor,opType:R.operationKind,strictAmbiguity:f,paragraphMetadataIndex:O,metadataIndices:i,onInfo:n.onInfo,onWarn:n.onWarn});else{let re=s.registry.resolve(b.sourceIds[0],a);if(re.error)throw Object.assign(new Error(re.error.message),re.error);C={paragraph:re.paragraph,resolvedBy:b.resolvedBy,warnings:b.warnings}}let P=C.paragraph,M=Wx(a,P,C.resolvedBy,R.target,O,N),_=M.resolvedTarget.text,k=R.operationKind==="comment"?R.textToComment||_:R.operationKind==="highlight"?R.textToHighlight:R.operationKind==="format"?R.textToFormat:null,L=R.operationKind==="comment"&&k!=null?na(ao(P,{revisionView:N}),k):null,D=k==null||(L?L.found:_.includes(k)),X=re=>{if(R.targetEndRef)return cn(a,R.targetRef,R.targetEndRef,{opType:re,targetRefSnapshot:n.targetRefSnapshot||null,onInfo:n.onInfo,onWarn:n.onWarn});if(!R.targetEndDescriptor)return[P];let We=ln(a,{targetText:R.targetEndDescriptor.text,targetRef:R.targetEndDescriptor.index,targetDescriptor:R.targetEndDescriptor,opType:re,strictAmbiguity:f,paragraphMetadataIndex:O,metadataIndices:i,onInfo:n.onInfo,onWarn:n.onWarn}),ge=se(a),he=ge.indexOf(P),Me=ge.indexOf(We?.paragraph);return he>=0&&Me>=he?ge.slice(he,Me+1):null},G=fr(P),ee=R.existingRevisions||n.existingRevisions||"merge-same-author",J=Lr(ee,ee==="auto"&&R.operationKind==="redline"&&(R.targetEndRef||R.targetEndDescriptor)&&X("redline")||P,S),ie=R.operationKind==="redline"&&R.modified===""?ep(P):[],ne=null;if(R.operationKind==="restore"){let re=X("restore"),We=Array.isArray(R.modified)?R.modified:[R.modified];if(!re||re[0]!==P||We.length!==re.length)ne={code:"RESTORATION_COUNT_MISMATCH",message:"Restoration requires one replacement for every paragraph in a contiguous resolved range."};else for(let ge of re){let he=an(ge);if(he?.code==="UNSUPPORTED_MOVE_REVISION"){ne=he;break}let Me=Xr(ge,S),K=Me.matches?he||an(ge):null;if(!Me.matches){ne={code:"RESTORATION_STATE_REQUIRED",message:"Explicit restoration requires a foreign paragraph-mark deletion with every pre-existing content node deleted.",...Me.ownerAuthor?{ownerAuthor:Me.ownerAuthor}:{}};break}if(K){ne=K;break}}}else if(!D)ne=L?.error||{code:"ANCHOR_NOT_FOUND",message:`Anchor text was not found in target paragraph: "${k}".`};else if(ie.length>0){let re=ie.map(We=>n._existingCommentDetails?.[We]).filter(Boolean);ne={code:"COMMENTED_CONTENT_DELETE",message:"Refusing to delete a paragraph with existing comments. Resolve or explicitly remove the comments before deleting the paragraph.",commentIds:ie,...re.length>0?{comments:re}:{}}}else if(R.operationKind==="redline"&&G&&J!=="accept-all-first"&&J!=="accept-all-first-keep-normalized")if(J==="merge-same-author"||J==="slice-cross-author"){let re=Mr(P),We=String(S||"").trim().toLowerCase(),ge=re.length>0&&!dr(P)&&re.every(he=>he.trim().toLowerCase()===We);if(!ge&&J==="merge-same-author")ne={code:"EXISTING_REVISIONS",message:`Target paragraph contains tracked changes from another author (${[...re,...dr(P)?["unattributed"]:[]].join(", ")}). Use existingRevisions: "slice-cross-author" for a surgical edit that preserves reviewer history; accepting or rejecting revisions requires separate authorization.`,revisionAuthors:re,currentPolicy:J};else if(ge){let he=ep(P);if(he.length>0){let Me=he.map(K=>n._existingCommentDetails?.[K]).filter(Boolean);ne={code:"COMMENTED_CONTENT_MERGE",message:"Refusing to merge existing revisions in commented content because reverting the prior revisions could remove or orphan comment anchors.",commentIds:he,...Me.length>0?{comments:Me}:{}}}}else(P.getElementsByTagNameNS(B,"moveFrom").length>0||P.getElementsByTagNameNS(B,"moveTo").length>0)&&(ne={code:"UNSAFE_REVISION_NESTING",message:"Cross-author slicing does not support pending move revisions."})}else{let re=P.getElementsByTagNameNS(B,"del").length>0,We=P.getElementsByTagNameNS(B,"moveFrom").length>0||P.getElementsByTagNameNS(B,"moveTo").length>0;re?ne={code:"UNSAFE_REVISION_NESTING",message:"Refusing to replace content with pending deletions; nesting revisions is unsafe."}:We?ne={code:"UNSAFE_REVISION_NESTING",message:"Refusing to mutate content with move revisions until move lifecycle is designed."}:ne={code:"EXISTING_REVISIONS",message:'Target paragraph contains tracked changes and existingRevisions is "reject-input".'}}if(!ne&&R.operationKind==="redline"){let re=Ha(P,R.modified,n);re.valid||(ne={code:re.code,message:re.message})}u.push({index:y+1,type:x?.type||"redline",operationType:R.operationKind,status:ne?"error":"ready",authorUsed:S,...M,anchor:k==null?null:{text:k,found:D,...L?.found?{resolvedBy:L.resolvedBy,start:L.start,end:L.end}:{},...!L?.found&&Array.isArray(L?.error?.candidates)?{candidates:L.error.candidates}:{}},hasRevisions:G,existingRevisions:J,...C?.warnings?.length?{warnings:C.warnings}:{},...ne?{error:ne}:{}})}catch(C){u.push({index:y+1,type:x?.type||"redline",operationType:R.operationKind,status:"error",authorUsed:S,error:bo(C)})}}let g=s.conflicts,h=u.map(y=>y.error?{...y,error:bo(y.error,{operationIndex:y.index,...l[y.index-1]?.operationId?{operationId:l[y.index-1].operationId}:{}})}:y),v=g.map(y=>bo(y)),w=h.some(y=>y.status==="error");return{valid:!w&&v.length===0,status:!w&&v.length===0?"ok":"error",results:h,conflicts:v,authorsUsed:Array.from(d),requiredArtifacts:{comments:m,numbering:p}}}var mt=Uint8Array,Lt=Uint16Array,gc=Int32Array,Ui=new mt([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Xi=new mt([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),fc=new mt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),op=function(e,t){for(var r=new Lt(31),n=0;n<31;++n)r[n]=t+=1<<e[n-1];for(var o=new gc(r[30]),n=1;n<30;++n)for(var a=r[n];a<r[n+1];++a)o[a]=a-r[n]<<5|n;return{b:r,r:o}},ap=op(Ui,2),ip=ap.b,dc=ap.r;ip[28]=258,dc[258]=28;var sp=op(Xi,0),Kx=sp.b,tp=sp.r,mc=new Lt(32768);for(we=0;we<32768;++we)Ar=(we&43690)>>1|(we&21845)<<1,Ar=(Ar&52428)>>2|(Ar&13107)<<2,Ar=(Ar&61680)>>4|(Ar&3855)<<4,mc[we]=((Ar&65280)>>8|(Ar&255)<<8)>>1;var Ar,we,or=(function(e,t,r){for(var n=e.length,o=0,a=new Lt(t);o<n;++o)e[o]&&++a[e[o]-1];var i=new Lt(t);for(o=1;o<t;++o)i[o]=i[o-1]+a[o-1]<<1;var l;if(r){l=new Lt(1<<t);var s=15-t;for(o=0;o<n;++o)if(e[o])for(var c=o<<4|e[o],f=t-e[o],u=i[e[o]-1]++<<f,d=u|(1<<f)-1;u<=d;++u)l[mc[u]>>s]=c}else for(l=new Lt(n),o=0;o<n;++o)e[o]&&(l[o]=mc[i[e[o]-1]++]>>15-e[o]);return l}),Hr=new mt(288);for(we=0;we<144;++we)Hr[we]=8;var we;for(we=144;we<256;++we)Hr[we]=9;var we;for(we=256;we<280;++we)Hr[we]=7;var we;for(we=280;we<288;++we)Hr[we]=8;var we,va=new mt(32);for(we=0;we<32;++we)va[we]=5;var we,Gx=or(Hr,9,0),Hx=or(Hr,9,1),qx=or(va,5,0),Yx=or(va,5,1),lc=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Jt=function(e,t,r){var n=t/8|0;return(e[n]|e[n+1]<<8)>>(t&7)&r},cc=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(t&7)},hc=function(e){return(e+7)/8|0},lp=function(e,t,r){return(t==null||t<0)&&(t=0),(r==null||r>e.length)&&(r=e.length),new mt(e.subarray(t,r))};var Jx=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Rr=function(e,t,r){var n=new Error(t||Jx[e]);if(n.code=e,Error.captureStackTrace&&Error.captureStackTrace(n,Rr),!r)throw n;return n},Zx=function(e,t,r,n){var o=e.length,a=n?n.length:0;if(!o||t.f&&!t.l)return r||new mt(0);var i=!r,l=i||t.i!=2,s=t.i;i&&(r=new mt(o*3));var c=function(he){var Me=r.length;if(he>Me){var K=new mt(Math.max(Me*2,he));K.set(r),r=K}},f=t.f||0,u=t.p||0,d=t.b||0,m=t.l,p=t.d,g=t.m,h=t.n,v=o*8;do{if(!m){f=Jt(e,u,1);var w=Jt(e,u+1,3);if(u+=3,w)if(w==1)m=Hx,p=Yx,g=9,h=5;else if(w==2){var T=Jt(e,u,31)+257,A=Jt(e,u+10,15)+4,E=T+Jt(e,u+5,31)+1;u+=14;for(var I=new mt(E),R=new mt(19),S=0;S<A;++S)R[fc[S]]=Jt(e,u+S*3,7);u+=A*3;for(var N=lc(R),O=(1<<N)-1,C=or(R,N,1),S=0;S<E;){var P=C[Jt(e,u,O)];u+=P&15;var y=P>>4;if(y<16)I[S++]=y;else{var M=0,_=0;for(y==16?(_=3+Jt(e,u,3),u+=2,M=I[S-1]):y==17?(_=3+Jt(e,u,7),u+=3):y==18&&(_=11+Jt(e,u,127),u+=7);_--;)I[S++]=M}}var k=I.subarray(0,T),L=I.subarray(T);g=lc(k),h=lc(L),m=or(k,g,1),p=or(L,h,1)}else Rr(1);else{var y=hc(u)+4,x=e[y-4]|e[y-3]<<8,b=y+x;if(b>o){s&&Rr(0);break}l&&c(d+x),r.set(e.subarray(y,b),d),t.b=d+=x,t.p=u=b*8,t.f=f;continue}if(u>v){s&&Rr(0);break}}l&&c(d+131072);for(var D=(1<<g)-1,X=(1<<h)-1,G=u;;G=u){var M=m[cc(e,u)&D],ee=M>>4;if(u+=M&15,u>v){s&&Rr(0);break}if(M||Rr(2),ee<256)r[d++]=ee;else if(ee==256){G=u,m=null;break}else{var J=ee-254;if(ee>264){var S=ee-257,Z=Ui[S];J=Jt(e,u,(1<<Z)-1)+ip[S],u+=Z}var ie=p[cc(e,u)&X],ne=ie>>4;ie||Rr(3),u+=ie&15;var L=Kx[ne];if(ne>3){var Z=Xi[ne];L+=cc(e,u)&(1<<Z)-1,u+=Z}if(u>v){s&&Rr(0);break}l&&c(d+131072);var re=d+J;if(d<L){var We=a-L,ge=Math.min(L,re);for(We+d<0&&Rr(3);d<ge;++d)r[d]=n[We+d]}for(;d<re;++d)r[d]=r[d-L]}}t.l=m,t.p=G,t.b=d,t.f=f,m&&(f=1,t.m=g,t.d=p,t.n=h)}while(!f);return d!=r.length&&i?lp(r,0,d):r.subarray(0,d)},Er=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8},ha=function(e,t,r){r<<=t&7;var n=t/8|0;e[n]|=r,e[n+1]|=r>>8,e[n+2]|=r>>16},uc=function(e,t){for(var r=[],n=0;n<e.length;++n)e[n]&&r.push({s:n,f:e[n]});var o=r.length,a=r.slice();if(!o)return{t:up,l:0};if(o==1){var i=new mt(r[0].s+1);return i[r[0].s]=1,{t:i,l:1}}r.sort(function(b,T){return b.f-T.f}),r.push({s:-1,f:25001});var l=r[0],s=r[1],c=0,f=1,u=2;for(r[0]={s:-1,f:l.f+s.f,l,r:s};f!=o-1;)l=r[r[c].f<r[u].f?c++:u++],s=r[c!=f&&r[c].f<r[u].f?c++:u++],r[f++]={s:-1,f:l.f+s.f,l,r:s};for(var d=a[0].s,n=1;n<o;++n)a[n].s>d&&(d=a[n].s);var m=new Lt(d+1),p=pc(r[f-1],m,0);if(p>t){var n=0,g=0,h=p-t,v=1<<h;for(a.sort(function(T,A){return m[A.s]-m[T.s]||T.f-A.f});n<o;++n){var w=a[n].s;if(m[w]>t)g+=v-(1<<p-m[w]),m[w]=t;else break}for(g>>=h;g>0;){var y=a[n].s;m[y]<t?g-=1<<t-m[y]++-1:++n}for(;n>=0&&g;--n){var x=a[n].s;m[x]==t&&(--m[x],++g)}p=t}return{t:new mt(m),l:p}},pc=function(e,t,r){return e.s==-1?Math.max(pc(e.l,t,r+1),pc(e.r,t,r+1)):t[e.s]=r},rp=function(e){for(var t=e.length;t&&!e[--t];);for(var r=new Lt(++t),n=0,o=e[0],a=1,i=function(s){r[n++]=s},l=1;l<=t;++l)if(e[l]==o&&l!=t)++a;else{if(!o&&a>2){for(;a>138;a-=138)i(32754);a>2&&(i(a>10?a-11<<5|28690:a-3<<5|12305),a=0)}else if(a>3){for(i(o),--a;a>6;a-=6)i(8304);a>2&&(i(a-3<<5|8208),a=0)}for(;a--;)i(o);a=1,o=e[l]}return{c:r.subarray(0,n),n:t}},wa=function(e,t){for(var r=0,n=0;n<t.length;++n)r+=e[n]*t[n];return r},cp=function(e,t,r){var n=r.length,o=hc(t+2);e[o]=n&255,e[o+1]=n>>8,e[o+2]=e[o]^255,e[o+3]=e[o+1]^255;for(var a=0;a<n;++a)e[o+a+4]=r[a];return(o+4+n)*8},np=function(e,t,r,n,o,a,i,l,s,c,f){Er(t,f++,r),++o[256];for(var u=uc(o,15),d=u.t,m=u.l,p=uc(a,15),g=p.t,h=p.l,v=rp(d),w=v.c,y=v.n,x=rp(g),b=x.c,T=x.n,A=new Lt(19),E=0;E<w.length;++E)++A[w[E]&31];for(var E=0;E<b.length;++E)++A[b[E]&31];for(var I=uc(A,7),R=I.t,S=I.l,N=19;N>4&&!R[fc[N-1]];--N);var O=c+5<<3,C=wa(o,Hr)+wa(a,va)+i,P=wa(o,d)+wa(a,g)+i+14+3*N+wa(A,R)+2*A[16]+3*A[17]+7*A[18];if(s>=0&&O<=C&&O<=P)return cp(t,f,e.subarray(s,s+c));var M,_,k,L;if(Er(t,f,1+(P<C)),f+=2,P<C){M=or(d,m,0),_=d,k=or(g,h,0),L=g;var D=or(R,S,0);Er(t,f,y-257),Er(t,f+5,T-1),Er(t,f+10,N-4),f+=14;for(var E=0;E<N;++E)Er(t,f+3*E,R[fc[E]]);f+=3*N;for(var X=[w,b],G=0;G<2;++G)for(var ee=X[G],E=0;E<ee.length;++E){var J=ee[E]&31;Er(t,f,D[J]),f+=R[J],J>15&&(Er(t,f,ee[E]>>5&127),f+=ee[E]>>12)}}else M=Gx,_=Hr,k=qx,L=va;for(var E=0;E<l;++E){var Z=n[E];if(Z>255){var J=Z>>18&31;ha(t,f,M[J+257]),f+=_[J+257],J>7&&(Er(t,f,Z>>23&31),f+=Ui[J]);var ie=Z&31;ha(t,f,k[ie]),f+=L[ie],ie>3&&(ha(t,f,Z>>5&8191),f+=Xi[ie])}else ha(t,f,M[Z]),f+=_[Z]}return ha(t,f,M[256]),f+_[256]},Qx=new gc([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),up=new mt(0),eb=function(e,t,r,n,o,a){var i=a.z||e.length,l=new mt(n+i+5*(1+Math.ceil(i/7e3))+o),s=l.subarray(n,l.length-o),c=a.l,f=(a.r||0)&7;if(t){f&&(s[0]=a.r>>3);for(var u=Qx[t-1],d=u>>13,m=u&8191,p=(1<<r)-1,g=a.p||new Lt(32768),h=a.h||new Lt(p+1),v=Math.ceil(r/3),w=2*v,y=function(j){return(e[j]^e[j+1]<<v^e[j+2]<<w)&p},x=new gc(25e3),b=new Lt(288),T=new Lt(32),A=0,E=0,I=a.i||0,R=0,S=a.w||0,N=0;I+2<i;++I){var O=y(I),C=I&32767,P=h[O];if(g[C]=P,h[O]=C,S<=I){var M=i-I;if((A>7e3||R>24576)&&(M>423||!c)){f=np(e,s,0,x,b,T,E,R,N,I-N,f),R=A=E=0,N=I;for(var _=0;_<286;++_)b[_]=0;for(var _=0;_<30;++_)T[_]=0}var k=2,L=0,D=m,X=C-P&32767;if(M>2&&O==y(I-X))for(var G=Math.min(d,M)-1,ee=Math.min(32767,I),J=Math.min(258,M);X<=ee&&--D&&C!=P;){if(e[I+k]==e[I+k-X]){for(var Z=0;Z<J&&e[I+Z]==e[I+Z-X];++Z);if(Z>k){if(k=Z,L=X,Z>G)break;for(var ie=Math.min(X,Z-2),ne=0,_=0;_<ie;++_){var re=I-X+_&32767,We=g[re],ge=re-We&32767;ge>ne&&(ne=ge,P=re)}}}C=P,P=g[C],X+=C-P&32767}if(L){x[R++]=268435456|dc[k]<<18|tp[L];var he=dc[k]&31,Me=tp[L]&31;E+=Ui[he]+Xi[Me],++b[257+he],++T[Me],S=I+k,++A}else x[R++]=e[I],++b[e[I]]}}for(I=Math.max(I,S);I<i;++I)x[R++]=e[I],++b[e[I]];f=np(e,s,c,x,b,T,E,R,N,I-N,f),c||(a.r=f&7|s[f/8|0]<<3,f-=7,a.h=h,a.p=g,a.i=I,a.w=S)}else{for(var I=a.w||0;I<i+c;I+=65535){var K=I+65535;K>=i&&(s[f/8|0]=c,K=i),f=cp(s,f+1,e.subarray(I,K))}a.i=i}return lp(l,0,n+hc(f)+o)};var tb=function(e,t,r,n,o){if(!o&&(o={l:1},t.dictionary)){var a=t.dictionary.subarray(-32768),i=new mt(a.length+e.length);i.set(a),i.set(e,a.length),e=i,o.w=a.length}return eb(e,t.level==null?6:t.level,t.mem==null?o.l?Math.ceil(Math.max(8,Math.min(13,Math.log(e.length)))*1.5):20:12+t.mem,r,n,o)};function fp(e,t){return tb(e,t||{},0,0)}function dp(e,t){return Zx(e,{i:2},t&&t.out,t&&t.dictionary)}var rb=typeof TextDecoder<"u"&&new TextDecoder,nb=0;try{rb.decode(up,{stream:!0}),nb=1}catch{}var pp=new TextEncoder,gp=new TextDecoder("utf-8"),ob=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e})();function ab(e){let t=4294967295;for(let r=0;r<e.length;r++)t=ob[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}function Io(e){if(e instanceof Uint8Array)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);if(typeof e=="string")return pp.encode(e);throw new TypeError("Invalid binary input: expected Uint8Array, Buffer, or ArrayBuffer.")}function mp(e){let t=0;for(let o=0;o<e.length;o++)t+=e[o].length;let r=new Uint8Array(t),n=0;for(let o=0;o<e.length;o++)r.set(e[o],n),n+=e[o].length;return r}function No(e){let t=Io(e);if(t.length<22)throw new Error("Invalid DOCX: ZIP end record not found.");let r=new DataView(t.buffer,t.byteOffset,t.byteLength),n=-1,o=Math.max(0,t.length-65535-22);for(let c=t.length-22;c>=o;c--)if(r.getUint32(c,!0)===101010256){n=c;break}if(n<0)throw new Error("Invalid DOCX: ZIP end record not found.");let a=r.getUint16(n+10,!0),i=r.getUint32(n+16,!0);if(a===65535||i===4294967295)throw new Error("Unsupported DOCX: ZIP64 archives are not supported.");let l=new Map,s=i;for(let c=0;c<a;c++){if(s+46>t.length||r.getUint32(s,!0)!==33639248)throw new Error("Invalid DOCX: central directory is corrupt.");let f=r.getUint16(s+8,!0),u=r.getUint16(s+10,!0);if(f&1)throw new Error("Unsupported DOCX: encrypted ZIP entries are not supported.");let d=r.getUint32(s+20,!0),m=r.getUint16(s+28,!0),p=r.getUint16(s+30,!0),g=r.getUint16(s+32,!0),h=r.getUint32(s+42,!0);if(s+46+m>t.length)throw new Error("Invalid DOCX: central directory entry name extends beyond bounds.");let v=gp.decode(t.subarray(s+46,s+46+m));if(h+30>t.length||r.getUint32(h,!0)!==67324752)throw new Error("Invalid DOCX: local entry is corrupt.");let w=r.getUint16(h+26,!0),y=r.getUint16(h+28,!0),x=h+30+w+y;if(x+d>t.length)throw new Error("Invalid DOCX: local entry data extends beyond archive bounds.");let b=t.subarray(x,x+d);if(u!==0&&u!==8)throw new Error(`Unsupported DOCX compression method: ${u}.`);let T=u===8?dp(b):new Uint8Array(b);l.set(v,T),s+=46+m+p+g}return l}function hp(e){let t=e instanceof Map?Array.from(e.entries()):Symbol.iterator in Object(e)?Array.from(e):Object.entries(e||{}),r=[],n=[],o=0;for(let[s,c]of t){let f=pp.encode(s),u=Io(c),d=fp(u,{level:9}),m=d.length<u.length?8:0,p=m===8?d:u,g=ab(u),h=new Uint8Array(30),v=new DataView(h.buffer,h.byteOffset,30);v.setUint32(0,67324752,!0),v.setUint16(4,20,!0),v.setUint16(8,m,!0),v.setUint16(12,23585,!0),v.setUint32(14,g,!0),v.setUint32(18,p.length,!0),v.setUint32(22,u.length,!0),v.setUint16(26,f.length,!0),v.setUint16(28,0,!0),r.push(h,f,p);let w=new Uint8Array(46),y=new DataView(w.buffer,w.byteOffset,46);y.setUint32(0,33639248,!0),y.setUint16(4,20,!0),y.setUint16(6,20,!0),y.setUint16(10,m,!0),y.setUint16(14,23585,!0),y.setUint32(16,g,!0),y.setUint32(20,p.length,!0),y.setUint32(24,u.length,!0),y.setUint16(28,f.length,!0),y.setUint16(30,0,!0),y.setUint16(32,0,!0),y.setUint32(42,o,!0),n.push(w,f),o+=h.length+f.length+p.length}let a=mp(n),i=new Uint8Array(22),l=new DataView(i.buffer,i.byteOffset,22);return l.setUint32(0,101010256,!0),l.setUint16(8,t.length,!0),l.setUint16(10,t.length,!0),l.setUint32(12,a.length,!0),l.setUint32(16,o,!0),mp([...r,a,i])}var Pr=class{constructor(t){this.entries=t instanceof Map?t:new Map(Object.entries(t||{}))}file(t,r){if(r!==void 0)return this.entries.set(t,Io(r)),this;let n=this.entries.get(t);return n?{async:async o=>o==="string"?gp.decode(n):new Uint8Array(n)}:null}};var ar=new TextEncoder,bp=new TextDecoder("utf-8"),te=(e,t)=>{let r=e.get(t);return r?typeof r=="string"?r:bp.decode(r):null};function wp(e){let t=ui({commentsXml:te(e,"word/comments.xml"),commentsIdsXml:te(e,"word/commentsIds.xml"),commentsExtensibleXml:te(e,"word/commentsExtensible.xml")});t.commentsIdsXml&&e.set("word/commentsIds.xml",ar.encode(t.commentsIdsXml)),t.commentsExtensibleXml&&e.set("word/commentsExtensible.xml",ar.encode(t.commentsExtensibleXml))}var To=e=>new Map([...e].map(([t,r])=>[t,new Uint8Array(r)]));function pe(e){return typeof Buffer<"u"&&typeof Buffer.from=="function"?Buffer.from(e.buffer,e.byteOffset,e.byteLength):e}function ya(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function vp(e,t){let r=i=>!i||typeof i!="object"?i:i.attemptedDisposition!=="applied"&&i.committed!==!0?{...i}:{...i,committed:!1,finalDisposition:"rolled_back"},n=(e?.receipts||[]).map(r),o=new Map(n.map(i=>[i.operationIndex,i])),a=(e?.results||[]).map(i=>({...i,...i.receipt?{receipt:o.get(i.index)||r(i.receipt)}:{}}));return{results:a,receipts:n,executionOrder:e?.executionOrder||[],authorsUsed:[],rolledBack:!0,retryPlan:Ir({atomic:!0,rolledBack:!0,results:a,receipts:n,operationCount:t})}}function wc(e){let t;if(e instanceof Uint8Array||typeof Buffer<"u"&&Buffer.isBuffer?.(e))t=No(e);else if(e instanceof Map)t=e;else if(e?.entries instanceof Map)t=e.entries;else if(typeof e?.toUint8Array=="function")t=No(e.toUint8Array());else if(typeof e?.toBuffer=="function")t=No(e.toBuffer());else if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))t=No(Io(e));else throw new TypeError("computePackageRevisionToken requires a Uint8Array, Buffer, Map of entries, or DocxDocument.");return Qo({scope:"package",entries:t})}var yp=new Set(["comment","comment_reply","comment_resolve"]);function ib(e){let r=(`${te(e,"word/document.xml")||""} ${te(e,"word/comments.xml")||""}`.match(/(?:w:)?id=["'](\d+)["']/g)||[]).reduce((n,o)=>Math.max(n,Number(o.match(/\d+/)?.[0]||0)),0)+1;return()=>r++}function xp(e){let t=te(e,"word/comments.xml");if(!t)return{};let r=V(t,"application/xml");if(!r.doc||r.error)return{};let n={};for(let o of Array.from(r.doc.getElementsByTagNameNS("*","comment"))){let a=o.getAttribute("w:id")||o.getAttribute("id");a!==""&&(n[a]={id:a,author:o.getAttribute("w:author")||o.getAttribute("author")||"",text:String(o.textContent||"").trim(),paraId:Tt(o)||null})}return n}function Xt(e,t,r){let n=pe(e);return{status:"error",hasChanges:!1,written:!1,rolledBack:!0,error:vt({code:t,message:r}),retryPlan:Ir({atomic:!0,rolledBack:!0}),artifactsChanged:[],uint8Array:e,toUint8Array:()=>new Uint8Array(e),buffer:n,toBuffer:()=>pe(e)}}var zi=class{constructor(t){this.originalBytes=Io(t),this.entries=No(this.originalBytes)}get originalBuffer(){return pe(this.originalBytes)}inspect(t={}){let r=t.digestFn||(o=>Zo(o)),n=mi({documentXml:te(this.entries,"word/document.xml"),commentsXml:te(this.entries,"word/comments.xml"),commentsExtendedXml:te(this.entries,"word/commentsExtended.xml"),numberingXml:te(this.entries,"word/numbering.xml"),stylesXml:te(this.entries,"word/styles.xml")},{...t,digestFn:r});return n.status==="error"?n:{...n,headersFooters:this.inspectHeadersFooters()}}inspectHeadersFooters(){return Tl({documentXml:te(this.entries,"word/document.xml"),relsXml:te(this.entries,"word/_rels/document.xml.rels"),settingsXml:te(this.entries,"word/settings.xml")}).map(t=>{let r=te(this.entries,t.path)||"",n=r?mi({documentXml:r}):{paragraphs:[]};return{...t,hasFields:/<w:fldChar\b|<w:fldSimple\b/.test(r),paragraphs:(n.paragraphs||[]).map(o=>({index:o.index,text:o.text}))}})}getRevisionToken(){return wc(this.entries)}get revisionToken(){return this.getRevisionToken()}preflight(t,r=ae(),n={}){let o=Array.isArray(t)?t:[],a=p=>Di(te(this.entries,"word/document.xml"),p,r||ae(),{...n,_existingCommentDetails:xp(this.entries)});if(!o.some(p=>p&&typeof p=="object"&&p.part!=null))return a(t);let i=this.inspectHeadersFooters(),l=[],s=[],c=[],f=new Set,u=!0;o.forEach((p,g)=>{if(!p||typeof p!="object"||p.part==null){l.push({operation:p,origIndex:g});return}let h=Sl(i,p.part),v=yp.has(p.type)?{code:"COMMENT_IN_HEADER_FOOTER",message:"Word does not support comments in headers or footers."}:h.error;if(v){u=!1,s.push({index:g+1,type:p.type||"redline",status:"error",error:vt({...v,operationIndex:g+1})});return}let{part:w,...y}=p,x=Di(te(this.entries,h.part.path),[y],r||ae(),{...n,_existingCommentDetails:{}});u=u&&x.valid;for(let b of x.results||[])s.push({...b,index:g+1,part:h.part.path});c.push(...x.conflicts||[]);for(let b of x.authorsUsed||[])f.add(b)});let d={comments:!1,numbering:!1};if(l.length){let p=a(l.map(g=>g.operation));u=u&&p.valid;for(let g of p.results||[])s.push({...g,index:l[g.index-1].origIndex+1});c.push(...p.conflicts||[]);for(let g of p.authorsUsed||[])f.add(g);d=p.requiredArtifacts||d}s.sort((p,g)=>p.index-g.index);let m=u&&c.length===0;return{valid:m,status:m?"ok":"error",results:s,conflicts:c,authorsUsed:[...f],requiredArtifacts:d}}toUint8Array(){return hp(this.entries)}toBuffer(){return pe(this.toUint8Array())}async applyOperations(t,r={}){let n=Array.isArray(t)?t:[];return n.some(o=>o&&typeof o=="object"&&o.part!=null)?this.applyOperationsWithParts(n,r):this.applyBodyOperations(t,r)}async applyOperationsWithParts(t,r={}){let n=r.author||ae(),o=r.atomic===!0,a=this.entries,i=this.originalBytes,l=t.length,s=()=>{this.entries=a,this.originalBytes=i},c=()=>({uint8Array:i,toUint8Array:()=>new Uint8Array(i),buffer:pe(i),toBuffer:()=>pe(i)}),f=(_,k=[],L=[],D={})=>({status:"error",hasChanges:!1,written:!1,rolledBack:!0,results:k,receipts:L,executionOrder:[],authorsUsed:[],artifactsChanged:[],error:vt(_),retryPlan:Ir({atomic:!0,rolledBack:!0,results:k,receipts:L,operationCount:l}),validation:{originalIssues:[],generatedIssues:[]},...D,...c()});if(r.expectedRevision){let _=await this.applyBodyOperations([],{expectedRevision:r.expectedRevision});if(_.status==="error")return _}let u=Tl({documentXml:te(this.entries,"word/document.xml"),relsXml:te(this.entries,"word/_rels/document.xml.rels"),settingsXml:te(this.entries,"word/settings.xml")}),d=[],m=[];for(let _=0;_<t.length;_++){let k=t[_];if(!k||typeof k!="object"||k.part==null){d.push({operation:k,origIndex:_});continue}if(yp.has(k.type))return f({code:"COMMENT_IN_HEADER_FOOTER",message:`Operation ${_+1}: Word does not support comments in headers or footers.`,operationIndex:_+1});if(k.type==="list-format")return f({code:"INVALID_OPERATION",field:"part",message:`Operation ${_+1}: list-format is body-only in list-format-v1; headers and footers are not supported.`,operationIndex:_+1});let L=Sl(u,k.part);if(L.error)return f({...L.error,message:`Operation ${_+1}: ${L.error.message}`,operationIndex:_+1});let{part:D,...X}=k;m.push({operation:X,origIndex:_,part:L.part})}let p=[],g=[],h=[],v=new Set,w=[],y=!1,x=!1,b=null;if(d.length){b=await this.applyBodyOperations(d.map(k=>k.operation),{...r,expectedRevision:void 0});let _=k=>d[k-1]?.origIndex+1;for(let k of b.results||[])p.push({...k,index:_(k.index),...k.receipt?{receipt:{...k.receipt,operationIndex:_(k.receipt.operationIndex)}}:{}});for(let k of b.receipts||[])g.push({...k,operationIndex:_(k.operationIndex)});for(let k of b.executionOrder||[])h.push(_(k));for(let k of b.authorsUsed||[])v.add(k);if(w.push(...b.validation?.originalIssues||[]),(b.status==="error"||b.rolledBack)&&(x=!0,o))return s(),{...b,results:p,receipts:g,executionOrder:h,written:!1,artifactsChanged:[],rolledBack:!0,...c()};y=b.hasChanges===!0}let T=To(this.entries),A=new Pr(T),E=new Set,{expectedRevision:I,...R}=r,S=(_,k)=>{x=!0;let L=vt({...k,operationIndex:_.origIndex+1});p.push({index:_.origIndex+1,type:_.operation.type||"redline",status:"error",authorUsed:n,part:_.part.path,error:L})};for(let _ of m){let k=_.part.path,L=te(T,k);if(!L){if(S(_,{code:"PART_NOT_FOUND",message:`Part '${k}' is referenced but missing from the package.`}),o)break;continue}let D=te(T,"word/numbering.xml"),X=await Fi(L,[_.operation],n,{numberingIdState:Ht(D||void 0)},{...R,atomic:!0,strictTargets:r.strictTargets!==!1,_existingCommentDetails:{}}),G=X.results?.[0];if(X.rolledBack||X.status==="error"){if(S(_,G?.error||X.error||{code:"OPERATION_FAILED",message:"Operation failed."}),o)break;continue}if(!X.hasChanges){p.push({...G,index:_.origIndex+1,part:k});continue}if(Al(X.documentXml)>Al(L)){if(S(_,{code:"FIELD_EDIT_REFUSED",message:`The edit would change a field (for example PAGE or NUMPAGES) in ${k}. Word recomputes fields; edit the text around them instead.`}),o)break;continue}let ee=new Set;for(let[ie,ne]of T)if(!(ie===k||!(ie==="word/document.xml"||gd(ie))))for(let re of hd(bp.decode(ne)))ee.add(re);let J=wd(X.documentXml,ee);T.set(k,ar.encode(J.xml));let Z=ie=>ie?.revisionItems?{...ie,revisionItems:ie.revisionItems.map(ne=>({...ne,id:J.idMap.get(String(ne.id))??ne.id,partName:k}))}:ie;X.numberingXmlParts?.length&&await yi(A,X.numberingXmlParts),E.add(k),y=!0,p.push({...G,index:_.origIndex+1,part:k,partSections:_.part.appliesToSections,...G?.receipt?{receipt:{...Z(G.receipt),operationIndex:_.origIndex+1}}:{}}),X.receipts?.[0]&&g.push({...Z(X.receipts[0]),operationIndex:_.origIndex+1}),h.push(_.origIndex+1);for(let ie of X.authorsUsed||[])v.add(ie)}let N=[];if(!(o&&x)){for(let _ of E){let k=Mt(te(this.entries,_)).issues.map(D=>({source:_,...D})),L=Mt(te(T,_)).issues.map(D=>({source:_,...D}));k.push(...ro(te(this.entries,_),te(this.entries,"word/numbering.xml")).map(D=>({source:_,...D}))),L.push(...ro(te(T,_),te(T,"word/numbering.xml")).map(D=>({source:_,...D}))),N.push(...En(An(L,k)))}if(r.validate!==!1&&E.size)try{await jr(A)}catch(_){N.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:_.message})}}if(o&&x||N.length){s();let _=N.length?{code:"PACKAGE_OPERATION_FAILED",message:`Applied operations introduced invalid markup (${[...new Set(N.map(D=>D.code))].join(", ")}).`,issues:N}:{code:"BATCH_OPERATION_FAILED",message:"Atomic batch rolled back because one or more operations failed."},k=p.map(D=>D.receipt?{...D,receipt:{...D.receipt,committed:!1,finalDisposition:"rolled_back"}}:D).sort((D,X)=>D.index-X.index),L=g.map(D=>({...D,committed:!1,finalDisposition:"rolled_back"}));return f(_,k,L,{validation:{originalIssues:w,generatedIssues:N},issues:N})}p.sort((_,k)=>_.index-k.index),g.sort((_,k)=>_.operationIndex-k.operationIndex);let O=x?y?"partial":"error":"ok",C=x?{error:vt({code:"BATCH_OPERATION_FAILED",message:"One or more operations failed; the others were applied."})}:{};if(!E.size){let _=pe(this.originalBytes);return{...b||{},results:p,receipts:g,executionOrder:h,authorsUsed:[...v],status:O,hasChanges:y,written:b?.written===!0,artifactsChanged:b?.artifactsChanged||[],validation:{originalIssues:w,generatedIssues:[]},...C,uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:_,toBuffer:()=>pe(this.originalBytes)}}this.entries=T;let P=this.toUint8Array();this.originalBytes=P;let M=[...T].filter(([_,k])=>!a.has(_)||!ya(k,a.get(_))).map(([_])=>_);return{...b||{},status:O,hasChanges:!0,written:!0,results:p,receipts:g,executionOrder:h,authorsUsed:[...v],artifactsChanged:M,validation:{originalIssues:w,generatedIssues:[]},...C,uint8Array:P,toUint8Array:()=>new Uint8Array(P),buffer:pe(P),inspection:this.inspect(),toBuffer:()=>pe(P)}}async applyBodyOperations(t,r={}){let n=f=>{let u=[],d=[],m=pe(this.originalBytes);return{status:"error",hasChanges:!1,written:!1,rolledBack:!0,results:u,receipts:d,artifactsChanged:[],error:vt(f),retryPlan:Ir({atomic:!0,rolledBack:!0,results:u,receipts:d,operationCount:Array.isArray(t)?t.length:0}),validation:{originalIssues:[],generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:m,toBuffer:()=>pe(this.originalBytes)}};if(r?.expectedRevision){let f=vn(r.expectedRevision);if(!f.valid)return n({code:f.error?.code||"INVALID_REVISION_TOKEN",message:f.error?.message||"Invalid revision token."});if(r.expectedRevision.scope!=="package")return n({code:"REVISION_TOKEN_SCOPE_MISMATCH",message:`Revision token scope mismatch: expected 'package', got '${r.expectedRevision.scope}'.`,expectedScope:"package",actualScope:r.expectedRevision.scope});let u=wc(this.entries);if(!yn(u.value,r.expectedRevision.value))return n({code:"REVISION_MISMATCH",message:`Document revision mismatch: expected '${r.expectedRevision.value}', current is '${u.value}'.`,expectedRevision:r.expectedRevision,currentRevision:u})}let o=this.entries,a=To(o),i=new Pr(a),l=te(a,"word/document.xml"),s=[],c=null;try{if(!l)throw new Error("Missing word/document.xml.");s=Mt(l).issues.map(T=>({source:"word/document.xml",...T})),s.push(...ro(l,te(a,"word/numbering.xml")).map(T=>({source:"word/numbering.xml",...T})));try{await jr(new Pr(To(o)))}catch(T){s.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:T.message})}let u={numberingIdState:Ht(te(a,"word/numbering.xml")||void 0),stylesXml:te(a,"word/styles.xml"),commentsXml:te(a,"word/comments.xml"),commentsExtendedXml:te(a,"word/commentsExtended.xml")},{expectedRevision:d,...m}=r,p=r.author||ae(),g=c=await Fi(l,t,p,u,{...m,atomic:r.atomic===!0,strictTargets:r.strictTargets!==!1,_existingCommentDetails:xp(a),commentIdAllocator:ib(a)});if(g.rolledBack||g.status==="error"){let T=pe(this.originalBytes);return{...g,...vp(g,Array.isArray(t)?t.length:0),written:!1,artifactsChanged:[],validation:{originalIssues:s,generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:T,toBuffer:()=>pe(this.originalBytes)}}if(!g.hasChanges){let T=pe(this.originalBytes);return{...g,status:g.status||"ok",written:!1,artifactsChanged:[],validation:{originalIssues:s,generatedIssues:[]},uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:T,toBuffer:()=>pe(this.originalBytes)}}(g.results||[]).some(T=>T?.status!=="error"&&T?.operationType!=="comment_resolve")&&a.set("word/document.xml",ar.encode(g.documentXml)),await yi(i,g.numberingXmlParts);let v=te(a,"word/comments.xml"),w=g.commentsXml||v;if(await bl(i,w,{replaceExisting:g.commentsXmlMode==="replace"||!g.commentsXml&&!!v}),g.commentsExtendedXml&&await xi(i,g.commentsExtendedXml,{replaceExisting:g.commentsExtendedXmlMode==="replace"}),await so(i),wp(a),r.validate!==!1){let A=Mt(g.documentXml).issues.map(R=>({source:"word/document.xml",...R}));A.push(...ro(g.documentXml,te(a,"word/numbering.xml")).map(R=>({source:"word/numbering.xml",...R})));try{await jr(i)}catch(R){A.push({source:"package",code:"PACKAGE_VALIDATION",severity:"error",message:R.message})}let E=An(A,s),I=En(E);if(I.length){let R=[...new Set(I.map(S=>S.code))].join(", ");throw Object.assign(new Error(`Applied operations introduced invalid revision markup (${R}); these are generated-output issues, not pre-existing input issues.`),{issues:I})}}this.entries=a;let y=this.toUint8Array();this.originalBytes=y;let x=pe(y),b=[...a].filter(([T,A])=>!o.has(T)||!ya(A,o.get(T))).map(([T])=>T);return{...g,status:g.status||"ok",written:!0,artifactsChanged:b,validation:{originalIssues:s,generatedIssues:[]},uint8Array:y,toUint8Array:()=>new Uint8Array(y),buffer:x,inspection:this.inspect(),toBuffer:()=>pe(y)}}catch(f){this.entries=o;let u=f.issues||[{source:"package",code:"PACKAGE_OPERATION_FAILED",severity:"error",message:f.message}],d=vp(c,Array.isArray(t)?t.length:0),m=pe(this.originalBytes);return{...d,status:"error",hasChanges:!1,written:!1,artifactsChanged:[],error:vt({code:"PACKAGE_OPERATION_FAILED",message:f.message,stage:"package",issues:u}),validation:{originalIssues:s,generatedIssues:u},issues:u,uint8Array:this.originalBytes,toUint8Array:()=>new Uint8Array(this.originalBytes),buffer:m,toBuffer:()=>pe(this.originalBytes)}}}async resolveRevisions(t,r={}){let n=t==="accept"?nn:t==="reject"?Ur:null;if(!n)return Xt(this.originalBytes,"INVALID_ACTION",`Unknown revision action: ${t}`);let o=this.originalBytes,a=this.entries,i=To(this.entries),l=new Pr(i),s=n(te(i,"word/document.xml"),{author:r.author,allAuthors:r.allAuthors===!0});if(s.status==="error"||s.error)return Xt(o,s.error?.code||"REVISION_OPERATION_FAILED",s.error?.message||"Revision operation failed.");let c=new Map;for(let m of this.inspectHeadersFooters()){let p=te(i,m.path);if(!p)continue;let g=n(p,{author:r.author,allAuthors:r.allAuthors===!0});if(g.status==="error"||g.error)return Xt(o,g.error?.code||"REVISION_OPERATION_FAILED",`${m.path}: ${g.error?.message||"Revision operation failed."}`);g.hasChanges&&c.set(m.path,g.oxml)}if(!(s.hasChanges||c.size>0)){let m=pe(o);return{...s,status:"ok",written:!1,artifactsChanged:[],uint8Array:o,toUint8Array:()=>new Uint8Array(o),buffer:m,toBuffer:()=>pe(o)}}s.hasChanges&&i.set("word/document.xml",ar.encode(s.oxml));for(let[m,p]of c)i.set(m,ar.encode(p));try{await so(l),r.validate!==!1&&await jr(l)}catch(m){return Xt(o,"PACKAGE_VALIDATION",m.message)}this.entries=i;let u=this.toUint8Array();this.originalBytes=u;let d=pe(u);return{...s,status:"ok",written:!0,hasChanges:!0,artifactsChanged:[...i].filter(([m,p])=>!a.has(m)||!ya(p,a.get(m))).map(([m])=>m),uint8Array:u,toUint8Array:()=>new Uint8Array(u),buffer:d,toBuffer:()=>pe(u)}}async resolveComment(t,r={}){let n=this.originalBytes,o=To(this.entries),a=r.resolved!==!1,i=u=>{let d=pe(n);return{status:"ok",hasChanges:!1,written:!1,artifactsChanged:[],...u,uint8Array:n,toUint8Array:()=>new Uint8Array(n),buffer:d,toBuffer:()=>pe(n)}},l=ci({commentsXml:te(o,"word/comments.xml"),commentsExtendedXml:te(o,"word/commentsExtended.xml"),commentId:t,resolved:a});if(l.status==="error")return Xt(n,l.error.code,l.error.message);if(!l.hasChanges)return i({resolved:a,threadRootId:l.threadRootId,commentIds:l.commentIds});let s=new Pr(o);try{l.commentsXml&&o.set("word/comments.xml",ar.encode(l.commentsXml)),await xi(s,l.commentsExtendedXml,{replaceExisting:!0}),await so(s),r.validate!==!1&&await jr(s)}catch(u){return Xt(n,"PACKAGE_VALIDATION",u.message)}let c=[...o].filter(([u,d])=>!this.entries.has(u)||!ya(d,this.entries.get(u))).map(([u])=>u);this.entries=o;let f=this.toUint8Array();return this.originalBytes=f,{status:"ok",hasChanges:!0,written:!0,resolved:a,threadRootId:l.threadRootId,commentIds:l.commentIds,artifactsChanged:c,uint8Array:f,toUint8Array:()=>new Uint8Array(f),buffer:pe(f),toBuffer:()=>pe(f)}}async deleteComments(t={}){let r=this.originalBytes,n=To(this.entries),o=te(n,"word/comments.xml"),a=pe(r);if(!o)return{status:"ok",hasChanges:!1,written:!1,commentsRemoved:0,referencesRemoved:0,artifactsChanged:[],uint8Array:r,toUint8Array:()=>new Uint8Array(r),buffer:a,toBuffer:()=>pe(r)};let i=V(o,"application/xml");if(!i.doc||i.error)return Xt(r,"PARSE_ERROR",i.error?.message||"Could not parse comments.xml.");let l=Array.isArray(t.ids)?new Set(t.ids.map(String)):null;if(l){let b=new Set(Array.from(i.doc.getElementsByTagNameNS("*","comment")).map(A=>A.getAttribute("w:id")||A.getAttribute("id"))),T=[...l].filter(A=>!b.has(A));if(T.length)return Xt(r,"COMMENT_NOT_FOUND",`Comment id(s) not found: ${T.join(", ")}.`)}let s=b=>l?l.has(b.getAttribute("w:id")||b.getAttribute("id")):t.allAuthors===!0||(b.getAttribute("w:author")||b.getAttribute("author"))===t.author,c=new Set(Array.from(i.doc.getElementsByTagNameNS("*","comment")).filter(s).map(b=>b.getAttribute("w:id")||b.getAttribute("id")).filter(Boolean));if(!c.size)return{status:"ok",hasChanges:!1,written:!1,commentsRemoved:0,referencesRemoved:0,artifactsChanged:[],uint8Array:r,toUint8Array:()=>new Uint8Array(r),buffer:a,toBuffer:()=>pe(r)};let f=te(n,"word/commentsExtended.xml"),u=null,d=new Set;if(f){if(u=V(f,"application/xml"),!u.doc||u.error)return Xt(r,"PARSE_ERROR",u.error?.message||"Could not parse commentsExtended.xml.");let b=new Map;for(let A of Array.from(i.doc.getElementsByTagNameNS("*","comment"))){let E=A.getAttribute("w:id")||A.getAttribute("id"),I=Tt(A);I&&b.set(I,E)}for(let[A,E]of b)c.has(E)&&d.add(A);let T=!0;for(;T;){T=!1;for(let A of Array.from(u.doc.getElementsByTagNameNS("*","commentEx"))){let E=(A.getAttribute("w15:paraId")||A.getAttribute("paraId")||"").toUpperCase(),I=(A.getAttribute("w15:paraIdParent")||A.getAttribute("paraIdParent")||"").toUpperCase();I&&d.has(I)&&!d.has(E)&&(d.add(E),b.has(E)&&c.add(b.get(E)),T=!0)}}}let m=l?o:Ms(o,{author:t.author,allAuthors:t.allAuthors===!0}).oxml,p=V(m,"application/xml");if(!p.doc||p.error)return Xt(r,"PARSE_ERROR",p.error?.message||"Could not parse updated comments.xml.");for(let b of Array.from(p.doc.getElementsByTagNameNS("*","comment"))){let T=b.getAttribute("w:id")||b.getAttribute("id");c.has(T)&&b.parentNode?.removeChild(b)}let g=V(te(n,"word/document.xml"),"application/xml");if(!g.doc||g.error)return Xt(r,"PARSE_ERROR",g.error?.message||"Could not parse document.xml.");let h=0;for(let b of["commentRangeStart","commentRangeEnd","commentReference"])for(let T of Array.from(g.doc.getElementsByTagNameNS("*",b))){let A=T.getAttribute("w:id")||T.getAttribute("id");if(!c.has(A)||!T.parentNode)continue;let E=T.parentNode;E.removeChild(T),h+=1,b==="commentReference"&&E.localName==="r"&&!Array.from(E.childNodes||[]).some(I=>I.nodeType===1&&I.localName!=="rPr")&&E.parentNode?.removeChild(E)}let v=le();if(n.set("word/comments.xml",ar.encode(v.serializeToString(p.doc))),u?.doc){for(let b of Array.from(u.doc.getElementsByTagNameNS("*","commentEx"))){let T=(b.getAttribute("w15:paraId")||b.getAttribute("paraId")||"").toUpperCase();d.has(T)&&b.parentNode?.removeChild(b)}n.set("word/commentsExtended.xml",ar.encode(v.serializeToString(u.doc)))}n.set("word/document.xml",ar.encode(v.serializeToString(g.doc)));try{wp(n);let b=new Pr(n);await so(b),t.validate!==!1&&await jr(b)}catch(b){return Xt(r,"PACKAGE_VALIDATION",b.message)}let w=[...n].filter(([b,T])=>!this.entries.has(b)||!ya(T,this.entries.get(b))).map(([b])=>b);this.entries=n;let y=this.toUint8Array();this.originalBytes=y;let x=pe(y);return{status:"ok",hasChanges:!0,written:!0,commentsRemoved:c.size,referencesRemoved:h,artifactsChanged:w,uint8Array:y,toUint8Array:()=>new Uint8Array(y),buffer:x,toBuffer:()=>pe(y)}}};function sb(e){return new zi(e)}function lb(e,t){let r=typeof t?.numberingXml=="string"&&t.numberingXml.trim()?t.numberingXml:null,n=t?.numberingIdState&&typeof t.numberingIdState=="object"?t.numberingIdState:r?Ht(r):null;if(!n||!e?.hasChanges||typeof e.oxml!="string"||!e.oxml.includes("/word/numbering.xml"))return e;let o=Ve(e.oxml),a=Array.from(o.getElementsByTagNameNS("*","part")),i=d=>{let p=a.find(g=>(g.getAttribute("pkg:name")||g.getAttribute("name"))===d)?.getElementsByTagNameNS("*","xmlData")[0];return p&&Array.from(p.childNodes).find(g=>g.nodeType===1)||null},l=i("/word/numbering.xml"),s=i("/word/document.xml")?.getElementsByTagNameNS("*","body")[0];if(!l||!s)return e;let c=Array.from(s.childNodes).filter(d=>d.nodeType===1&&d.localName!=="sectPr"),f=mn(Kt(l),c,n),u=o.importNode(Ve(f.numberingXml).documentElement,!0);return l.parentNode.replaceChild(u,l),c.forEach((d,m)=>s.replaceChild(f.replacementNodes[m],d)),{...e,oxml:Kt(o)}}async function Ip(e,t,r,n={}){let o=await Do(e,t,r,n),a=lb(o,n);if(a?.useNativeApi&&typeof a?.oxml!="string"){let i=Array.isArray(a?.warnings)?a.warnings:[];return Ce({...a,oxml:e,hasChanges:!1,warnings:[...i,"Standalone mode cannot execute native Word API fallback for this operation."]})}return a}async function WP(e,t,r,n={}){let o=typeof e=="string"?e:"",a=typeof r=="string"?r:String(r||""),i;try{i=xt(a)}catch{i={headers:[],rows:[]}}return(i?.headers?.length||0)>0||(i?.rows?.length||0)>0?{...await Ip(o,t||"",a,n),isMarkdownTable:!0,tableData:i}:{oxml:o,hasChanges:!1,isMarkdownTable:!1,warnings:["Could not parse Markdown table from input."]}}async function KP(e,t,r,n={}){let o=n.listFallbackAllowExistingList!==!1,a=n.sanitizeInput===!0?$s(r):r,i=a!==r?["Input was sanitized; pass sanitizeInput: false to disable."]:[],l=dn({oxml:e,originalText:t,modifiedText:a,allowExistingList:o}),s=n.preferListStructuralFallback!==!1,c=[];if(l&&s){let g=await Qn(l,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(g?.hasChanges&&g?.oxml){let h=kr(g.oxml,{includeNumbering:g.includeNumbering??!0,numberingXml:g.numberingXml}),v=Array.isArray(g?.warnings)?g.warnings:[];return Ce({oxml:h,hasChanges:!0,warnings:[...i,...v],listStructuralFallbackApplied:!0,listStructuralFallbackKey:g.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:g.numberingXml||null})}c=Array.isArray(g?.warnings)?g.warnings:[]}let f=await Ip(e,t,r,n);if(!l)return{...f,warnings:[...Array.isArray(f?.warnings)?f.warnings:[],...c],listStructuralFallbackApplied:!1};if(s)return{...f,warnings:[...Array.isArray(f?.warnings)?f.warnings:[],...c],listStructuralFallbackApplied:!1};if(f?.hasChanges)return{...f,listStructuralFallbackApplied:!1};let u=await Qn(l,{author:n.author,generateRedlines:n.generateRedlines,pipeline:n.listFallbackPipeline});if(!u?.hasChanges||!u?.oxml){let g=Array.isArray(f?.warnings)?f.warnings:[],h=Array.isArray(u?.warnings)?u.warnings:[];return{...f,warnings:[...g,...h],listStructuralFallbackApplied:!1}}let d=kr(u.oxml,{includeNumbering:u.includeNumbering??!0,numberingXml:u.numberingXml}),m=Array.isArray(f?.warnings)?f.warnings:[],p=Array.isArray(u?.warnings)?u.warnings:[];return Ce({...f,oxml:d,hasChanges:!0,warnings:[...m,...c,...p],listStructuralFallbackApplied:!0,listStructuralFallbackKey:u.listStructuralFallbackKey||null,listStructuralFallbackNumberingXml:u.numberingXml||null})}export{Ln as ContainerKind,_c as ContentType,Bt as DiffOp,zi as DocxDocument,B as NS_W,ur as NumberingService,sa as ReceiptCollector,Oo as ReconciliationPipeline,co as RoutePlanKind,H as RunKind,fe as WORD_MAIN_NS,nn as acceptTrackedChangesInOoxml,qo as allocateNumberingDefinition,Ys as allocateNumberingForReplacement,Ea as analyzeStructuredContent,ll as applyCommentReplyToParts,Cv as applyFormattingRemovalToOoxml,Nl as applyHighlightToOoxml,Ip as applyRedlineToOxml,KP as applyRedlineToOxmlWithListFallback,_f as applyStartOverridesToNum,yn as areRevisionTokensEqual,Jo as buildCommentElement,Qs as buildCommentsPartXml,ni as buildExplicitDecimalMultilevelNumberingXml,xw as buildListMarkdown,kv as buildReconciliationPlan,ol as buildRevisionTokenFraming,dn as buildSingleLineListStructuralFallbackPlan,Us as buildTargetReferenceSnapshot,Xw as canonicalNumberingDefinition,Vo as clearSingleLineListFallbackExplicitSequence,xf as collectContiguousListParagraphBlock,wv as compareDocumentInspections,ea as computeDocumentPartsRevisionToken,wc as computePackageRevisionToken,jf as computeRevisionToken,Qo as computeRevisionTokenSync,Op as configureLogger,Lp as configureXmlProvider,fr as containsTrackedChanges,jw as copyLevelGeometry,Ht as createDynamicNumberingIdState,ke as createEmptyReceipt,Ot as createParagraphFingerprint,Ms as deleteCommentsByAuthorInOoxml,ei as enforceListBindingOnParagraphNodes,bl as ensureCommentsArtifactsInZip,xi as ensureCommentsExtendedArtifactsInZip,yi as ensureNumberingArtifactsInZip,Ze as escapeXml,Qn as executeSingleLineListStructuralFallback,Y as extractCanonicalParagraphText,fi as extractDocumentPartsEntries,ri as extractFirstParagraphNumId,Mv as extractParagraphIdFromOoxml,Oa as extractParagraphRevisionSegments,wl as extractReplacementNodesFromOoxml,ct as findContainingWordElement,Fs as findParagraphByBestTextMatch,hf as findParagraphByReference,Ka as findParagraphByStrictText,Ga as findStrictTargetCandidates,mr as generateTableOoxml,hl as getBodyElementFromDocument,ae as getDefaultAuthor,se as getDocumentParagraphNodes,dl as getPackagePartName,He as getParagraphId,Oe as getParagraphListInfo,_e as getParagraphText,Gi as getPlatform,Mr as getTrackedChangeAuthors,js as hasListItems,So as inferNumberingStyleFromMarker,Ks as inferTableReplacementParagraphBlock,Dn as ingestOoxml,rv as ingestWordOoxmlToMarkdown,Df as ingestWordOoxmlToMarkdownResult,tv as ingestWordOoxmlToPlainText,Ff as ingestWordOoxmlToPlainTextResult,sl as injectCommentsIntoOoxml,yv as injectCommentsIntoPackage,Sv as insertBodyElementBeforeSectPr,mi as inspectDocumentParts,il as inspectionReviewShape,Rf as isLikelyStructuredTableSourceParagraph,sn as isMarkdownTableText,tn as isNodeVisibleInRevisionView,Pv as mergeCommentParts,vr as mergeNumberingParts,kf as mergeNumberingXmlBySchemaOrder,vi as normalizeBodySectionOrderStandalone,md as normalizeContentEscapesForRouting,bw as normalizeListItemsWithLevels,zf as normalizeOpcEntryName,q as normalizeWhitespaceForTargeting,sb as openDocx,ti as overwriteParagraphNumIds,jo as parseMarkdownListContent,Ve as parseOoxml,V as parseOoxmlSafe,Ds as parseParagraphReference,zs as planListInsertionOnlyEdit,th as planStructuredReplacement,yt as preprocessMarkdown,gr as readCanonicalRunText,WP as reconcileMarkdownTableOoxml,la as reconcileReceiptsAgainstOutput,Qa as recordSingleLineListFallbackExplicitSequence,Ur as rejectTrackedChangesInOoxml,mn as remapNumberingPayloadForDocument,fd as removeFormattingFromRPr,so as repairKnownContentTypes,Ko as reserveNextNumberingId,to as reserveNextNumberingIdPair,Lr as resolveExistingRevisionsPolicy,cn as resolveParagraphRangeByRefs,Za as resolveSingleLineListFallbackNumberingAction,ln as resolveTargetParagraph,Jn as resolveTargetParagraphWithSnapshot,$s as sanitizeAiResponse,Av as sanitizeNestedParagraphsInTables,Kt as serializeOoxml,lt as serializeToOoxml,Up as setDefaultAuthor,Xp as setPlatform,mw as splitLeadingParagraphMarker,dw as stripLeadingParagraphMarker,un as stripRedundantLeadingListMarkers,Vs as stripSingleLineListMarkerPrefix,Xs as synthesizeExpandedListScopeEdit,Gs as synthesizeTableMarkdownFromMultilineCellEdit,jr as validateDocxPackage,ro as validateNumberingIntegrity,Mt as validateRedlineOoxml,vn as validateRevisionToken,kr as wrapInDocumentFragment};
|
|
233
233
|
//# sourceMappingURL=docx-redline-js.esm.min.js.map
|