n8n-nodes-adeu 2.4.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,177 +1,190 @@
1
- 'use strict';var n8nWorkflow=require('n8n-workflow'),path=require('path');var Yi=Object.create;var Dt=Object.defineProperty;var Vi=Object.getOwnPropertyDescriptor;var Zi=Object.getOwnPropertyNames;var Ki=Object.getPrototypeOf,es=Object.prototype.hasOwnProperty;var g=(t,e)=>Dt(t,"name",{value:e,configurable:true});var Cn=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ts=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Zi(e))!es.call(t,s)&&s!==n&&Dt(t,s,{get:()=>e[s],enumerable:!(r=Vi(e,s))||r.enumerable});return t};var Mt=(t,e,n)=>(n=t!=null?Yi(Ki(t)):{},ts(Dt(n,"default",{value:t,enumerable:true}),t));var Tn=Cn((vl,Pn)=>{Pn.exports={createRequire:g(function(){return function(){return {}}},"createRequire")};});var Gt=Cn((kl,Ue)=>{var R=g(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;},"diff_match_patch"),G=-1,Q=1,H=0;R.Diff=function(t,e){return [t,e]};R.prototype.diff_main=function(t,e,n,r){typeof r>"u"&&(this.Diff_Timeout<=0?r=Number.MAX_VALUE:r=new Date().getTime()+this.Diff_Timeout*1e3);var s=r;if(t==null||e==null)throw new Error("Null input. (diff_main)");if(t==e)return t?[new R.Diff(H,t)]:[];typeof n>"u"&&(n=true);var i=n,o=this.diff_commonPrefix(t,e),l=t.substring(0,o);t=t.substring(o),e=e.substring(o),o=this.diff_commonSuffix(t,e);var a=t.substring(t.length-o);t=t.substring(0,t.length-o),e=e.substring(0,e.length-o);var u=this.diff_compute_(t,e,i,s);return l&&u.unshift(new R.Diff(H,l)),a&&u.push(new R.Diff(H,a)),this.diff_cleanupMerge(u),u};R.prototype.diff_compute_=function(t,e,n,r){var s;if(!t)return [new R.Diff(Q,e)];if(!e)return [new R.Diff(G,t)];var i=t.length>e.length?t:e,o=t.length>e.length?e:t,l=i.indexOf(o);if(l!=-1)return s=[new R.Diff(Q,i.substring(0,l)),new R.Diff(H,o),new R.Diff(Q,i.substring(l+o.length))],t.length>e.length&&(s[0][0]=s[2][0]=G),s;if(o.length==1)return [new R.Diff(G,t),new R.Diff(Q,e)];var a=this.diff_halfMatch_(t,e);if(a){var u=a[0],c=a[1],d=a[2],f=a[3],h=a[4],_=this.diff_main(u,d,n,r),p=this.diff_main(c,f,n,r);return _.concat([new R.Diff(H,h)],p)}return n&&t.length>100&&e.length>100?this.diff_lineMode_(t,e,r):this.diff_bisect_(t,e,r)};R.prototype.diff_lineMode_=function(t,e,n){var r=this.diff_linesToChars_(t,e);t=r.chars1,e=r.chars2;var s=r.lineArray,i=this.diff_main(t,e,false,n);this.diff_charsToLines_(i,s),this.diff_cleanupSemantic(i),i.push(new R.Diff(H,""));for(var o=0,l=0,a=0,u="",c="";o<i.length;){switch(i[o][0]){case Q:a++,c+=i[o][1];break;case G:l++,u+=i[o][1];break;case H:if(l>=1&&a>=1){i.splice(o-l-a,l+a),o=o-l-a;for(var d=this.diff_main(u,c,false,n),f=d.length-1;f>=0;f--)i.splice(o,0,d[f]);o=o+d.length;}a=0,l=0,u="",c="";break}o++;}return i.pop(),i};R.prototype.diff_bisect_=function(t,e,n){for(var r=t.length,s=e.length,i=Math.ceil((r+s)/2),o=i,l=2*i,a=new Array(l),u=new Array(l),c=0;c<l;c++)a[c]=-1,u[c]=-1;a[o+1]=0,u[o+1]=0;for(var d=r-s,f=d%2!=0,h=0,_=0,p=0,m=0,y=0;y<i&&!(new Date().getTime()>n);y++){for(var x=-y+h;x<=y-_;x+=2){var b=o+x,w;x==-y||x!=y&&a[b-1]<a[b+1]?w=a[b+1]:w=a[b-1]+1;for(var v=w-x;w<r&&v<s&&t.charAt(w)==e.charAt(v);)w++,v++;if(a[b]=w,w>r)_+=2;else if(v>s)h+=2;else if(f){var N=o+d-x;if(N>=0&&N<l&&u[N]!=-1){var k=r-u[N];if(w>=k)return this.diff_bisectSplit_(t,e,w,v,n)}}}for(var C=-y+p;C<=y-m;C+=2){var N=o+C,k;C==-y||C!=y&&u[N-1]<u[N+1]?k=u[N+1]:k=u[N-1]+1;for(var A=k-C;k<r&&A<s&&t.charAt(r-k-1)==e.charAt(s-A-1);)k++,A++;if(u[N]=k,k>r)m+=2;else if(A>s)p+=2;else if(!f){var b=o+d-C;if(b>=0&&b<l&&a[b]!=-1){var w=a[b],v=o+w-b;if(k=r-k,w>=k)return this.diff_bisectSplit_(t,e,w,v,n)}}}}return [new R.Diff(G,t),new R.Diff(Q,e)]};R.prototype.diff_bisectSplit_=function(t,e,n,r,s){var i=t.substring(0,n),o=e.substring(0,r),l=t.substring(n),a=e.substring(r),u=this.diff_main(i,o,false,s),c=this.diff_main(l,a,false,s);return u.concat(c)};R.prototype.diff_linesToChars_=function(t,e){var n=[],r={};n[0]="";function s(a){for(var u="",c=0,d=-1,f=n.length;d<a.length-1;){d=a.indexOf(`
2
- `,c),d==-1&&(d=a.length-1);var h=a.substring(c,d+1);(r.hasOwnProperty?r.hasOwnProperty(h):r[h]!==void 0)?u+=String.fromCharCode(r[h]):(f==i&&(h=a.substring(c),d=a.length),u+=String.fromCharCode(f),r[h]=f,n[f++]=h),c=d+1;}return u}g(s,"diff_linesToCharsMunge_");var i=4e4,o=s(t);i=65535;var l=s(e);return {chars1:o,chars2:l,lineArray:n}};R.prototype.diff_charsToLines_=function(t,e){for(var n=0;n<t.length;n++){for(var r=t[n][1],s=[],i=0;i<r.length;i++)s[i]=e[r.charCodeAt(i)];t[n][1]=s.join("");}};R.prototype.diff_commonPrefix=function(t,e){if(!t||!e||t.charAt(0)!=e.charAt(0))return 0;for(var n=0,r=Math.min(t.length,e.length),s=r,i=0;n<s;)t.substring(i,s)==e.substring(i,s)?(n=s,i=n):r=s,s=Math.floor((r-n)/2+n);return s};R.prototype.diff_commonSuffix=function(t,e){if(!t||!e||t.charAt(t.length-1)!=e.charAt(e.length-1))return 0;for(var n=0,r=Math.min(t.length,e.length),s=r,i=0;n<s;)t.substring(t.length-s,t.length-i)==e.substring(e.length-s,e.length-i)?(n=s,i=n):r=s,s=Math.floor((r-n)/2+n);return s};R.prototype.diff_commonOverlap_=function(t,e){var n=t.length,r=e.length;if(n==0||r==0)return 0;n>r?t=t.substring(n-r):n<r&&(e=e.substring(0,n));var s=Math.min(n,r);if(t==e)return s;for(var i=0,o=1;;){var l=t.substring(s-o),a=e.indexOf(l);if(a==-1)return i;o+=a,(a==0||t.substring(s-o)==e.substring(0,o))&&(i=o,o++);}};R.prototype.diff_halfMatch_=function(t,e){if(this.Diff_Timeout<=0)return null;var n=t.length>e.length?t:e,r=t.length>e.length?e:t;if(n.length<4||r.length*2<n.length)return null;var s=this;function i(_,p,m){for(var y=_.substring(m,m+Math.floor(_.length/4)),x=-1,b="",w,v,N,k;(x=p.indexOf(y,x+1))!=-1;){var C=s.diff_commonPrefix(_.substring(m),p.substring(x)),A=s.diff_commonSuffix(_.substring(0,m),p.substring(0,x));b.length<A+C&&(b=p.substring(x-A,x)+p.substring(x,x+C),w=_.substring(0,m-A),v=_.substring(m+C),N=p.substring(0,x-A),k=p.substring(x+C));}return b.length*2>=_.length?[w,v,N,k,b]:null}g(i,"diff_halfMatchI_");var o=i(n,r,Math.ceil(n.length/4)),l=i(n,r,Math.ceil(n.length/2)),a;if(!o&&!l)return null;l?o?a=o[4].length>l[4].length?o:l:a=l:a=o;var u,c,d,f;t.length>e.length?(u=a[0],c=a[1],d=a[2],f=a[3]):(d=a[0],f=a[1],u=a[2],c=a[3]);var h=a[4];return [u,c,d,f,h]};R.prototype.diff_cleanupSemantic=function(t){for(var e=false,n=[],r=0,s=null,i=0,o=0,l=0,a=0,u=0;i<t.length;)t[i][0]==H?(n[r++]=i,o=a,l=u,a=0,u=0,s=t[i][1]):(t[i][0]==Q?a+=t[i][1].length:u+=t[i][1].length,s&&s.length<=Math.max(o,l)&&s.length<=Math.max(a,u)&&(t.splice(n[r-1],0,new R.Diff(G,s)),t[n[r-1]+1][0]=Q,r--,r--,i=r>0?n[r-1]:-1,o=0,l=0,a=0,u=0,s=null,e=true)),i++;for(e&&this.diff_cleanupMerge(t),this.diff_cleanupSemanticLossless(t),i=1;i<t.length;){if(t[i-1][0]==G&&t[i][0]==Q){var c=t[i-1][1],d=t[i][1],f=this.diff_commonOverlap_(c,d),h=this.diff_commonOverlap_(d,c);f>=h?(f>=c.length/2||f>=d.length/2)&&(t.splice(i,0,new R.Diff(H,d.substring(0,f))),t[i-1][1]=c.substring(0,c.length-f),t[i+1][1]=d.substring(f),i++):(h>=c.length/2||h>=d.length/2)&&(t.splice(i,0,new R.Diff(H,c.substring(0,h))),t[i-1][0]=Q,t[i-1][1]=d.substring(0,d.length-h),t[i+1][0]=G,t[i+1][1]=c.substring(h),i++),i++;}i++;}};R.prototype.diff_cleanupSemanticLossless=function(t){function e(h,_){if(!h||!_)return 6;var p=h.charAt(h.length-1),m=_.charAt(0),y=p.match(R.nonAlphaNumericRegex_),x=m.match(R.nonAlphaNumericRegex_),b=y&&p.match(R.whitespaceRegex_),w=x&&m.match(R.whitespaceRegex_),v=b&&p.match(R.linebreakRegex_),N=w&&m.match(R.linebreakRegex_),k=v&&h.match(R.blanklineEndRegex_),C=N&&_.match(R.blanklineStartRegex_);return k||C?5:v||N?4:y&&!b&&w?3:b||w?2:y||x?1:0}g(e,"diff_cleanupSemanticScore_");for(var n=1;n<t.length-1;){if(t[n-1][0]==H&&t[n+1][0]==H){var r=t[n-1][1],s=t[n][1],i=t[n+1][1],o=this.diff_commonSuffix(r,s);if(o){var l=s.substring(s.length-o);r=r.substring(0,r.length-o),s=l+s.substring(0,s.length-o),i=l+i;}for(var a=r,u=s,c=i,d=e(r,s)+e(s,i);s.charAt(0)===i.charAt(0);){r+=s.charAt(0),s=s.substring(1)+i.charAt(0),i=i.substring(1);var f=e(r,s)+e(s,i);f>=d&&(d=f,a=r,u=s,c=i);}t[n-1][1]!=a&&(a?t[n-1][1]=a:(t.splice(n-1,1),n--),t[n][1]=u,c?t[n+1][1]=c:(t.splice(n+1,1),n--));}n++;}};R.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;R.whitespaceRegex_=/\s/;R.linebreakRegex_=/[\r\n]/;R.blanklineEndRegex_=/\n\r?\n$/;R.blanklineStartRegex_=/^\r?\n\r?\n/;R.prototype.diff_cleanupEfficiency=function(t){for(var e=false,n=[],r=0,s=null,i=0,o=false,l=false,a=false,u=false;i<t.length;)t[i][0]==H?(t[i][1].length<this.Diff_EditCost&&(a||u)?(n[r++]=i,o=a,l=u,s=t[i][1]):(r=0,s=null),a=u=false):(t[i][0]==G?u=true:a=true,s&&(o&&l&&a&&u||s.length<this.Diff_EditCost/2&&o+l+a+u==3)&&(t.splice(n[r-1],0,new R.Diff(G,s)),t[n[r-1]+1][0]=Q,r--,s=null,o&&l?(a=u=true,r=0):(r--,i=r>0?n[r-1]:-1,a=u=false),e=true)),i++;e&&this.diff_cleanupMerge(t);};R.prototype.diff_cleanupMerge=function(t){t.push(new R.Diff(H,""));for(var e=0,n=0,r=0,s="",i="",o;e<t.length;)switch(t[e][0]){case Q:r++,i+=t[e][1],e++;break;case G:n++,s+=t[e][1],e++;break;case H:n+r>1?(n!==0&&r!==0&&(o=this.diff_commonPrefix(i,s),o!==0&&(e-n-r>0&&t[e-n-r-1][0]==H?t[e-n-r-1][1]+=i.substring(0,o):(t.splice(0,0,new R.Diff(H,i.substring(0,o))),e++),i=i.substring(o),s=s.substring(o)),o=this.diff_commonSuffix(i,s),o!==0&&(t[e][1]=i.substring(i.length-o)+t[e][1],i=i.substring(0,i.length-o),s=s.substring(0,s.length-o))),e-=n+r,t.splice(e,n+r),s.length&&(t.splice(e,0,new R.Diff(G,s)),e++),i.length&&(t.splice(e,0,new R.Diff(Q,i)),e++),e++):e!==0&&t[e-1][0]==H?(t[e-1][1]+=t[e][1],t.splice(e,1)):e++,r=0,n=0,s="",i="";break}t[t.length-1][1]===""&&t.pop();var l=false;for(e=1;e<t.length-1;)t[e-1][0]==H&&t[e+1][0]==H&&(t[e][1].substring(t[e][1].length-t[e-1][1].length)==t[e-1][1]?(t[e][1]=t[e-1][1]+t[e][1].substring(0,t[e][1].length-t[e-1][1].length),t[e+1][1]=t[e-1][1]+t[e+1][1],t.splice(e-1,1),l=true):t[e][1].substring(0,t[e+1][1].length)==t[e+1][1]&&(t[e-1][1]+=t[e+1][1],t[e][1]=t[e][1].substring(t[e+1][1].length)+t[e+1][1],t.splice(e+1,1),l=true)),e++;l&&this.diff_cleanupMerge(t);};R.prototype.diff_xIndex=function(t,e){var n=0,r=0,s=0,i=0,o;for(o=0;o<t.length&&(t[o][0]!==Q&&(n+=t[o][1].length),t[o][0]!==G&&(r+=t[o][1].length),!(n>e));o++)s=n,i=r;return t.length!=o&&t[o][0]===G?i:i+(e-s)};R.prototype.diff_prettyHtml=function(t){for(var e=[],n=/&/g,r=/</g,s=/>/g,i=/\n/g,o=0;o<t.length;o++){var l=t[o][0],a=t[o][1],u=a.replace(n,"&amp;").replace(r,"&lt;").replace(s,"&gt;").replace(i,"&para;<br>");switch(l){case Q:e[o]='<ins style="background:#e6ffe6;">'+u+"</ins>";break;case G:e[o]='<del style="background:#ffe6e6;">'+u+"</del>";break;case H:e[o]="<span>"+u+"</span>";break}}return e.join("")};R.prototype.diff_text1=function(t){for(var e=[],n=0;n<t.length;n++)t[n][0]!==Q&&(e[n]=t[n][1]);return e.join("")};R.prototype.diff_text2=function(t){for(var e=[],n=0;n<t.length;n++)t[n][0]!==G&&(e[n]=t[n][1]);return e.join("")};R.prototype.diff_levenshtein=function(t){for(var e=0,n=0,r=0,s=0;s<t.length;s++){var i=t[s][0],o=t[s][1];switch(i){case Q:n+=o.length;break;case G:r+=o.length;break;case H:e+=Math.max(n,r),n=0,r=0;break}}return e+=Math.max(n,r),e};R.prototype.diff_toDelta=function(t){for(var e=[],n=0;n<t.length;n++)switch(t[n][0]){case Q:e[n]="+"+encodeURI(t[n][1]);break;case G:e[n]="-"+t[n][1].length;break;case H:e[n]="="+t[n][1].length;break}return e.join(" ").replace(/%20/g," ")};R.prototype.diff_fromDelta=function(t,e){for(var n=[],r=0,s=0,i=e.split(/\t/g),o=0;o<i.length;o++){var l=i[o].substring(1);switch(i[o].charAt(0)){case "+":try{n[r++]=new R.Diff(Q,decodeURI(l));}catch{throw new Error("Illegal escape in diff_fromDelta: "+l)}break;case "-":case "=":var a=parseInt(l,10);if(isNaN(a)||a<0)throw new Error("Invalid number in diff_fromDelta: "+l);var u=t.substring(s,s+=a);i[o].charAt(0)=="="?n[r++]=new R.Diff(H,u):n[r++]=new R.Diff(G,u);break;default:if(i[o])throw new Error("Invalid diff operation in diff_fromDelta: "+i[o])}}if(s!=t.length)throw new Error("Delta length ("+s+") does not equal source text length ("+t.length+").");return n};R.prototype.match_main=function(t,e,n){if(t==null||e==null||n==null)throw new Error("Null input. (match_main)");return n=Math.max(0,Math.min(n,t.length)),t==e?0:t.length?t.substring(n,n+e.length)==e?n:this.match_bitap_(t,e,n):-1};R.prototype.match_bitap_=function(t,e,n){if(e.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");var r=this.match_alphabet_(e),s=this;function i(w,v){var N=w/e.length,k=Math.abs(n-v);return s.Match_Distance?N+k/s.Match_Distance:k?1:N}g(i,"match_bitapScore_");var o=this.Match_Threshold,l=t.indexOf(e,n);l!=-1&&(o=Math.min(i(0,l),o),l=t.lastIndexOf(e,n+e.length),l!=-1&&(o=Math.min(i(0,l),o)));var a=1<<e.length-1;l=-1;for(var u,c,d=e.length+t.length,f,h=0;h<e.length;h++){for(u=0,c=d;u<c;)i(h,n+c)<=o?u=c:d=c,c=Math.floor((d-u)/2+u);d=c;var _=Math.max(1,n-c+1),p=Math.min(n+c,t.length)+e.length,m=Array(p+2);m[p+1]=(1<<h)-1;for(var y=p;y>=_;y--){var x=r[t.charAt(y-1)];if(h===0?m[y]=(m[y+1]<<1|1)&x:m[y]=(m[y+1]<<1|1)&x|((f[y+1]|f[y])<<1|1)|f[y+1],m[y]&a){var b=i(h,y-1);if(b<=o)if(o=b,l=y-1,l>n)_=Math.max(1,2*n-l);else break}}if(i(h+1,n)>o)break;f=m;}return l};R.prototype.match_alphabet_=function(t){for(var e={},n=0;n<t.length;n++)e[t.charAt(n)]=0;for(var n=0;n<t.length;n++)e[t.charAt(n)]|=1<<t.length-n-1;return e};R.prototype.patch_addContext_=function(t,e){if(e.length!=0){if(t.start2===null)throw Error("patch not initialized");for(var n=e.substring(t.start2,t.start2+t.length1),r=0;e.indexOf(n)!=e.lastIndexOf(n)&&n.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)r+=this.Patch_Margin,n=e.substring(t.start2-r,t.start2+t.length1+r);r+=this.Patch_Margin;var s=e.substring(t.start2-r,t.start2);s&&t.diffs.unshift(new R.Diff(H,s));var i=e.substring(t.start2+t.length1,t.start2+t.length1+r);i&&t.diffs.push(new R.Diff(H,i)),t.start1-=s.length,t.start2-=s.length,t.length1+=s.length+i.length,t.length2+=s.length+i.length;}};R.prototype.patch_make=function(t,e,n){var r,s;if(typeof t=="string"&&typeof e=="string"&&typeof n>"u")r=t,s=this.diff_main(r,e,true),s.length>2&&(this.diff_cleanupSemantic(s),this.diff_cleanupEfficiency(s));else if(t&&typeof t=="object"&&typeof e>"u"&&typeof n>"u")s=t,r=this.diff_text1(s);else if(typeof t=="string"&&e&&typeof e=="object"&&typeof n>"u")r=t,s=e;else if(typeof t=="string"&&typeof e=="string"&&n&&typeof n=="object")r=t,s=n;else throw new Error("Unknown call format to patch_make.");if(s.length===0)return [];for(var i=[],o=new R.patch_obj,l=0,a=0,u=0,c=r,d=r,f=0;f<s.length;f++){var h=s[f][0],_=s[f][1];switch(!l&&h!==H&&(o.start1=a,o.start2=u),h){case Q:o.diffs[l++]=s[f],o.length2+=_.length,d=d.substring(0,u)+_+d.substring(u);break;case G:o.length1+=_.length,o.diffs[l++]=s[f],d=d.substring(0,u)+d.substring(u+_.length);break;case H:_.length<=2*this.Patch_Margin&&l&&s.length!=f+1?(o.diffs[l++]=s[f],o.length1+=_.length,o.length2+=_.length):_.length>=2*this.Patch_Margin&&l&&(this.patch_addContext_(o,c),i.push(o),o=new R.patch_obj,l=0,c=d,a=u);break}h!==Q&&(a+=_.length),h!==G&&(u+=_.length);}return l&&(this.patch_addContext_(o,c),i.push(o)),i};R.prototype.patch_deepCopy=function(t){for(var e=[],n=0;n<t.length;n++){var r=t[n],s=new R.patch_obj;s.diffs=[];for(var i=0;i<r.diffs.length;i++)s.diffs[i]=new R.Diff(r.diffs[i][0],r.diffs[i][1]);s.start1=r.start1,s.start2=r.start2,s.length1=r.length1,s.length2=r.length2,e[n]=s;}return e};R.prototype.patch_apply=function(t,e){if(t.length==0)return [e,[]];t=this.patch_deepCopy(t);var n=this.patch_addPadding(t);e=n+e+n,this.patch_splitMax(t);for(var r=0,s=[],i=0;i<t.length;i++){var o=t[i].start2+r,l=this.diff_text1(t[i].diffs),a,u=-1;if(l.length>this.Match_MaxBits?(a=this.match_main(e,l.substring(0,this.Match_MaxBits),o),a!=-1&&(u=this.match_main(e,l.substring(l.length-this.Match_MaxBits),o+l.length-this.Match_MaxBits),(u==-1||a>=u)&&(a=-1))):a=this.match_main(e,l,o),a==-1)s[i]=false,r-=t[i].length2-t[i].length1;else {s[i]=true,r=a-o;var c;if(u==-1?c=e.substring(a,a+l.length):c=e.substring(a,u+this.Match_MaxBits),l==c)e=e.substring(0,a)+this.diff_text2(t[i].diffs)+e.substring(a+l.length);else {var d=this.diff_main(l,c,false);if(l.length>this.Match_MaxBits&&this.diff_levenshtein(d)/l.length>this.Patch_DeleteThreshold)s[i]=false;else {this.diff_cleanupSemanticLossless(d);for(var f=0,h,_=0;_<t[i].diffs.length;_++){var p=t[i].diffs[_];p[0]!==H&&(h=this.diff_xIndex(d,f)),p[0]===Q?e=e.substring(0,a+h)+p[1]+e.substring(a+h):p[0]===G&&(e=e.substring(0,a+h)+e.substring(a+this.diff_xIndex(d,f+p[1].length))),p[0]!==G&&(f+=p[1].length);}}}}}return e=e.substring(n.length,e.length-n.length),[e,s]};R.prototype.patch_addPadding=function(t){for(var e=this.Patch_Margin,n="",r=1;r<=e;r++)n+=String.fromCharCode(r);for(var r=0;r<t.length;r++)t[r].start1+=e,t[r].start2+=e;var s=t[0],i=s.diffs;if(i.length==0||i[0][0]!=H)i.unshift(new R.Diff(H,n)),s.start1-=e,s.start2-=e,s.length1+=e,s.length2+=e;else if(e>i[0][1].length){var o=e-i[0][1].length;i[0][1]=n.substring(i[0][1].length)+i[0][1],s.start1-=o,s.start2-=o,s.length1+=o,s.length2+=o;}if(s=t[t.length-1],i=s.diffs,i.length==0||i[i.length-1][0]!=H)i.push(new R.Diff(H,n)),s.length1+=e,s.length2+=e;else if(e>i[i.length-1][1].length){var o=e-i[i.length-1][1].length;i[i.length-1][1]+=n.substring(0,o),s.length1+=o,s.length2+=o;}return n};R.prototype.patch_splitMax=function(t){for(var e=this.Match_MaxBits,n=0;n<t.length;n++)if(!(t[n].length1<=e)){var r=t[n];t.splice(n--,1);for(var s=r.start1,i=r.start2,o="";r.diffs.length!==0;){var l=new R.patch_obj,a=true;for(l.start1=s-o.length,l.start2=i-o.length,o!==""&&(l.length1=l.length2=o.length,l.diffs.push(new R.Diff(H,o)));r.diffs.length!==0&&l.length1<e-this.Patch_Margin;){var u=r.diffs[0][0],c=r.diffs[0][1];u===Q?(l.length2+=c.length,i+=c.length,l.diffs.push(r.diffs.shift()),a=false):u===G&&l.diffs.length==1&&l.diffs[0][0]==H&&c.length>2*e?(l.length1+=c.length,s+=c.length,a=false,l.diffs.push(new R.Diff(u,c)),r.diffs.shift()):(c=c.substring(0,e-l.length1-this.Patch_Margin),l.length1+=c.length,s+=c.length,u===H?(l.length2+=c.length,i+=c.length):a=false,l.diffs.push(new R.Diff(u,c)),c==r.diffs[0][1]?r.diffs.shift():r.diffs[0][1]=r.diffs[0][1].substring(c.length));}o=this.diff_text2(l.diffs),o=o.substring(o.length-this.Patch_Margin);var d=this.diff_text1(r.diffs).substring(0,this.Patch_Margin);d!==""&&(l.length1+=d.length,l.length2+=d.length,l.diffs.length!==0&&l.diffs[l.diffs.length-1][0]===H?l.diffs[l.diffs.length-1][1]+=d:l.diffs.push(new R.Diff(H,d))),a||t.splice(++n,0,l);}}};R.prototype.patch_toText=function(t){for(var e=[],n=0;n<t.length;n++)e[n]=t[n];return e.join("")};R.prototype.patch_fromText=function(t){var e=[];if(!t)return e;for(var n=t.split(`
3
- `),r=0,s=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;r<n.length;){var i=n[r].match(s);if(!i)throw new Error("Invalid patch string: "+n[r]);var o=new R.patch_obj;for(e.push(o),o.start1=parseInt(i[1],10),i[2]===""?(o.start1--,o.length1=1):i[2]=="0"?o.length1=0:(o.start1--,o.length1=parseInt(i[2],10)),o.start2=parseInt(i[3],10),i[4]===""?(o.start2--,o.length2=1):i[4]=="0"?o.length2=0:(o.start2--,o.length2=parseInt(i[4],10)),r++;r<n.length;){var l=n[r].charAt(0);try{var a=decodeURI(n[r].substring(1));}catch{throw new Error("Illegal escape in patch_fromText: "+a)}if(l=="-")o.diffs.push(new R.Diff(G,a));else if(l=="+")o.diffs.push(new R.Diff(Q,a));else if(l==" ")o.diffs.push(new R.Diff(H,a));else {if(l=="@")break;if(l!=="")throw new Error('Invalid patch mode "'+l+'" in: '+a)}r++;}}return e};R.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0;};R.patch_obj.prototype.toString=function(){var t,e;this.length1===0?t=this.start1+",0":this.length1==1?t=this.start1+1:t=this.start1+1+","+this.length1,this.length2===0?e=this.start2+",0":this.length2==1?e=this.start2+1:e=this.start2+1+","+this.length2;for(var n=["@@ -"+t+" +"+e+` @@
4
- `],r,s=0;s<this.diffs.length;s++){switch(this.diffs[s][0]){case Q:r="+";break;case G:r="-";break;case H:r=" ";break}n[s+1]=r+encodeURI(this.diffs[s][1])+`
5
- `;}return n.join("").replace(/%20/g," ")};Ue.exports=R;Ue.exports.diff_match_patch=R;Ue.exports.DIFF_DELETE=G;Ue.exports.DIFF_INSERT=Q;Ue.exports.DIFF_EQUAL=H;});var Mn=Mt(Tn());var ns=(0, Mn.createRequire)("/"),ze,rs,is;try{ze=ns("worker_threads"),rs=ze.Worker,is=ze.isMarkedAsUntransferable;}catch{}var Y=Uint8Array,se=Uint16Array,Jt=Int32Array,ft=new Y([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]),ht=new Y([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]),Wt=new Y([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Rn=g(function(t,e){for(var n=new se(31),r=0;r<31;++r)n[r]=e+=1<<t[r-1];for(var s=new Jt(n[30]),r=1;r<30;++r)for(var i=n[r];i<n[r+1];++i)s[i]=i-n[r]<<5|r;return {b:n,r:s}},"freb"),ze=Rn(ft,2),jn=ze.b,zt=ze.r;jn[28]=258,zt[258]=28;var Bn=Rn(ht,0),ss=Bn.b,In=Bn.r,Lt=new se(32768);for(X=0;X<32768;++X)we=(X&43690)>>1|(X&21845)<<1,we=(we&52428)>>2|(we&13107)<<2,we=(we&61680)>>4|(we&3855)<<4,Lt[X]=((we&65280)>>8|(we&255)<<8)>>1;var we,X,_e=g((function(t,e,n){for(var r=t.length,s=0,i=new se(e);s<r;++s)t[s]&&++i[t[s]-1];var o=new se(e);for(s=1;s<e;++s)o[s]=o[s-1]+i[s-1]<<1;var l;if(n){l=new se(1<<e);var a=15-e;for(s=0;s<r;++s)if(t[s])for(var u=s<<4|t[s],c=e-t[s],d=o[t[s]-1]++<<c,f=d|(1<<c)-1;d<=f;++d)l[Lt[d]>>a]=u;}else for(l=new se(r),s=0;s<r;++s)t[s]&&(l[s]=Lt[o[t[s]-1]++]>>15-t[s]);return l}),"hMap"),Ne=new Y(288);for(X=0;X<144;++X)Ne[X]=8;var X;for(X=144;X<256;++X)Ne[X]=9;var X;for(X=256;X<280;++X)Ne[X]=7;var X;for(X=280;X<288;++X)Ne[X]=8;var X,tt=new Y(32);for(X=0;X<32;++X)tt[X]=5;var X,os=_e(Ne,9,0),as=_e(Ne,9,1),ls=_e(tt,5,0),cs=_e(tt,5,1),Rt=g(function(t){for(var e=t[0],n=1;n<t.length;++n)t[n]>e&&(e=t[n]);return e},"max"),ue=g(function(t,e,n){var r=e/8|0;return (t[r]|t[r+1]<<8)>>(e&7)&n},"bits"),jt=g(function(t,e){var n=e/8|0;return (t[n]|t[n+1]<<8|t[n+2]<<16)>>(e&7)},"bits16"),Xt=g(function(t){return (t+7)/8|0},"shft"),nt=g(function(t,e,n){return (e==null||e<0)&&(e=0),(n==null||n>t.length)&&(n=t.length),new Y(t.subarray(e,n))},"slc");var us=["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"],te=g(function(t,e,n){var r=new Error(e||us[t]);if(r.code=t,Error.captureStackTrace&&Error.captureStackTrace(r,te),!n)throw r;return r},"err"),ds=g(function(t,e,n,r){var s=t.length,i=r?r.length:0;if(!s||e.f&&!e.l)return n||new Y(0);var o=!n,l=o||e.i!=2,a=e.i;o&&(n=new Y(s*3));var u=g(function(Ve){var Ze=n.length;if(Ve>Ze){var We=new Y(Math.max(Ze*2,Ve));We.set(n),n=We;}},"cbuf"),c=e.f||0,d=e.p||0,f=e.b||0,h=e.l,_=e.d,p=e.m,m=e.n,y=s*8;do{if(!h){c=ue(t,d,1);var x=ue(t,d+1,3);if(d+=3,x)if(x==1)h=as,_=cs,p=9,m=5;else if(x==2){var N=ue(t,d,31)+257,k=ue(t,d+10,15)+4,C=N+ue(t,d+5,31)+1;d+=14;for(var A=new Y(C),T=new Y(19),D=0;D<k;++D)T[Wt[D]]=ue(t,d+D*3,7);d+=k*3;for(var j=Rt(T),E=(1<<j)-1,I=_e(T,j,1),D=0;D<C;){var P=I[ue(t,d,E)];d+=P&15;var b=P>>4;if(b<16)A[D++]=b;else {var S=0,$=0;for(b==16?($=3+ue(t,d,3),d+=2,S=A[D-1]):b==17?($=3+ue(t,d,7),d+=3):b==18&&($=11+ue(t,d,127),d+=7);$--;)A[D++]=S;}}var O=A.subarray(0,N),F=A.subarray(N);p=Rt(O),m=Rt(F),h=_e(O,p,1),_=_e(F,m,1);}else te(1);else {var b=Xt(d)+4,w=t[b-4]|t[b-3]<<8,v=b+w;if(v>s){a&&te(0);break}l&&u(f+w),n.set(t.subarray(b,v),f),e.b=f+=w,e.p=d=v*8,e.f=c;continue}if(d>y){a&&te(0);break}}l&&u(f+131072);for(var W=(1<<p)-1,L=(1<<m)-1,U=d;;U=d){var S=h[jt(t,d)&W],q=S>>4;if(d+=S&15,d>y){a&&te(0);break}if(S||te(2),q<256)n[f++]=q;else if(q==256){U=d,h=null;break}else {var J=q-254;if(q>264){var D=q-257,z=ft[D];J=ue(t,d,(1<<z)-1)+jn[D],d+=z;}var ne=_[jt(t,d)&L],he=ne>>4;ne||te(3),d+=ne&15;var F=ss[he];if(he>3){var z=ht[he];F+=jt(t,d)&(1<<z)-1,d+=z;}if(d>y){a&&te(0);break}l&&u(f+131072);var ge=f+J;if(f<F){var ct=i-F,ut=Math.min(F,ge);for(ct+f<0&&te(3);f<ut;++f)n[f]=r[ct+f];}for(;f<ge;++f)n[f]=n[f-F];}}e.l=h,e.p=U,e.b=f,e.f=c,h&&(c=1,e.m=p,e.d=_,e.n=m);}while(!c);return f!=n.length&&o?nt(n,0,f):n.subarray(0,f)},"inflt"),ye=g(function(t,e,n){n<<=e&7;var r=e/8|0;t[r]|=n,t[r+1]|=n>>8;},"wbits"),Ke=g(function(t,e,n){n<<=e&7;var r=e/8|0;t[r]|=n,t[r+1]|=n>>8,t[r+2]|=n>>16;},"wbits16"),Bt=g(function(t,e){for(var n=[],r=0;r<t.length;++r)t[r]&&n.push({s:r,f:t[r]});var s=n.length,i=n.slice();if(!s)return {t:Wn,l:0};if(s==1){var o=new Y(n[0].s+1);return o[n[0].s]=1,{t:o,l:1}}n.sort(function(v,N){return v.f-N.f}),n.push({s:-1,f:25001});var l=n[0],a=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:l.f+a.f,l,r:a};c!=s-1;)l=n[n[u].f<n[d].f?u++:d++],a=n[u!=c&&n[u].f<n[d].f?u++:d++],n[c++]={s:-1,f:l.f+a.f,l,r:a};for(var f=i[0].s,r=1;r<s;++r)i[r].s>f&&(f=i[r].s);var h=new se(f+1),_=Ut(n[c-1],h,0);if(_>e){var r=0,p=0,m=_-e,y=1<<m;for(i.sort(function(N,k){return h[k.s]-h[N.s]||N.f-k.f});r<s;++r){var x=i[r].s;if(h[x]>e)p+=y-(1<<_-h[x]),h[x]=e;else break}for(p>>=m;p>0;){var b=i[r].s;h[b]<e?p-=1<<e-h[b]++-1:++r;}for(;r>=0&&p;--r){var w=i[r].s;h[w]==e&&(--h[w],++p);}_=e;}return {t:new Y(h),l:_}},"hTree"),Ut=g(function(t,e,n){return t.s==-1?Math.max(Ut(t.l,e,n+1),Ut(t.r,e,n+1)):e[t.s]=n},"ln"),Sn=g(function(t){for(var e=t.length;e&&!t[--e];);for(var n=new se(++e),r=0,s=t[0],i=1,o=g(function(a){n[r++]=a;},"w"),l=1;l<=e;++l)if(t[l]==s&&l!=e)++i;else {if(!s&&i>2){for(;i>138;i-=138)o(32754);i>2&&(o(i>10?i-11<<5|28690:i-3<<5|12305),i=0);}else if(i>3){for(o(s),--i;i>6;i-=6)o(8304);i>2&&(o(i-3<<5|8208),i=0);}for(;i--;)o(s);i=1,s=t[l];}return {c:n.subarray(0,r),n:e}},"lc"),et=g(function(t,e){for(var n=0,r=0;r<e.length;++r)n+=t[r]*e[r];return n},"clen"),Fn=g(function(t,e,n){var r=n.length,s=Xt(e+2);t[s]=r&255,t[s+1]=r>>8,t[s+2]=t[s]^255,t[s+3]=t[s+1]^255;for(var i=0;i<r;++i)t[s+i+4]=n[i];return (s+4+r)*8},"wfblk"),$n=g(function(t,e,n,r,s,i,o,l,a,u,c){ye(e,c++,n),++s[256];for(var d=Bt(s,15),f=d.t,h=d.l,_=Bt(i,15),p=_.t,m=_.l,y=Sn(f),x=y.c,b=y.n,w=Sn(p),v=w.c,N=w.n,k=new se(19),C=0;C<x.length;++C)++k[x[C]&31];for(var C=0;C<v.length;++C)++k[v[C]&31];for(var A=Bt(k,7),T=A.t,D=A.l,j=19;j>4&&!T[Wt[j-1]];--j);var E=u+5<<3,I=et(s,Ne)+et(i,tt)+o,P=et(s,f)+et(i,p)+o+14+3*j+et(k,T)+2*k[16]+3*k[17]+7*k[18];if(a>=0&&E<=I&&E<=P)return Fn(e,c,t.subarray(a,a+u));var S,$,O,F;if(ye(e,c,1+(P<I)),c+=2,P<I){S=_e(f,h,0),$=f,O=_e(p,m,0),F=p;var W=_e(T,D,0);ye(e,c,b-257),ye(e,c+5,N-1),ye(e,c+10,j-4),c+=14;for(var C=0;C<j;++C)ye(e,c+3*C,T[Wt[C]]);c+=3*j;for(var L=[x,v],U=0;U<2;++U)for(var q=L[U],C=0;C<q.length;++C){var J=q[C]&31;ye(e,c,W[J]),c+=T[J],J>15&&(ye(e,c,q[C]>>5&127),c+=q[C]>>12);}}else S=os,$=Ne,O=ls,F=tt;for(var C=0;C<l;++C){var z=r[C];if(z>255){var J=z>>18&31;Ke(e,c,S[J+257]),c+=$[J+257],J>7&&(ye(e,c,z>>23&31),c+=ft[J]);var ne=z&31;Ke(e,c,O[ne]),c+=F[ne],ne>3&&(Ke(e,c,z>>5&8191),c+=ht[ne]);}else Ke(e,c,S[z]),c+=$[z];}return Ke(e,c,S[256]),c+$[256]},"wblk"),fs=new Jt([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Wn=new Y(0),hs=g(function(t,e,n,r,s,i){var o=i.z||t.length,l=new Y(r+o+5*(1+Math.ceil(o/7e3))+s),a=l.subarray(r,l.length-s),u=i.l,c=(i.r||0)&7;if(e){c&&(a[0]=i.r>>3);for(var d=fs[e-1],f=d>>13,h=d&8191,_=(1<<n)-1,p=i.p||new se(32768),m=i.h||new se(_+1),y=Math.ceil(n/3),x=2*y,b=g(function(Ot){return (t[Ot]^t[Ot+1]<<y^t[Ot+2]<<x)&_},"hsh"),w=new Jt(25e3),v=new se(288),N=new se(32),k=0,C=0,A=i.i||0,T=0,D=i.w||0,j=0;A+2<o;++A){var E=b(A),I=A&32767,P=m[E];if(p[I]=P,m[E]=I,D<=A){var S=o-A;if((k>7e3||T>24576)&&(S>423||!u)){c=$n(t,a,0,w,v,N,C,T,j,A-j,c),T=k=C=0,j=A;for(var $=0;$<286;++$)v[$]=0;for(var $=0;$<30;++$)N[$]=0;}var O=2,F=0,W=h,L=I-P&32767;if(S>2&&E==b(A-L))for(var U=Math.min(f,S)-1,q=Math.min(32767,A),J=Math.min(258,S);L<=q&&--W&&I!=P;){if(t[A+O]==t[A+O-L]){for(var z=0;z<J&&t[A+z]==t[A+z-L];++z);if(z>O){if(O=z,F=L,z>U)break;for(var ne=Math.min(L,z-2),he=0,$=0;$<ne;++$){var ge=A-L+$&32767,ct=p[ge],ut=ge-ct&32767;ut>he&&(he=ut,P=ge);}}}I=P,P=p[I],L+=I-P&32767;}if(F){w[T++]=268435456|zt[O]<<18|In[F];var Ve=zt[O]&31,Ze=In[F]&31;C+=ft[Ve]+ht[Ze],++v[257+Ve],++N[Ze],D=A+O,++k;}else w[T++]=t[A],++v[t[A]];}}for(A=Math.max(A,D);A<o;++A)w[T++]=t[A],++v[t[A]];c=$n(t,a,u,w,v,N,C,T,j,A-j,c),u||(i.r=c&7|a[c/8|0]<<3,c-=7,i.h=m,i.p=p,i.i=A,i.w=D);}else {for(var A=i.w||0;A<o+u;A+=65535){var We=A+65535;We>=o&&(a[c/8|0]=u,We=o),c=Fn(a,c+1,t.subarray(A,We));}i.i=o;}return nt(l,0,r+Xt(c)+s)},"dflt"),ps=(function(){for(var t=new Int32Array(256),e=0;e<256;++e){for(var n=e,r=9;--r;)n=(n&1&&-306674912)^n>>>1;t[e]=n;}return t})(),_s=g(function(){var t=-1;return {p:g(function(e){for(var n=t,r=0;r<e.length;++r)n=ps[n&255^e[r]]^n>>>8;t=n;},"p"),d:g(function(){return ~t},"d")}},"crc");var ms=g(function(t,e,n,r,s){if(!s&&(s={l:1},e.dictionary)){var i=e.dictionary.subarray(-32768),o=new Y(i.length+t.length);o.set(i),o.set(t,i.length),t=o,s.w=i.length;}return hs(t,e.level==null?6:e.level,e.mem==null?s.l?Math.ceil(Math.max(8,Math.min(13,Math.log(t.length)))*1.5):20:12+e.mem,n,r,s)},"dopt"),zn=g(function(t,e){var n={};for(var r in t)n[r]=t[r];for(var r in e)n[r]=e[r];return n},"mrg");var pe=g(function(t,e){return t[e]|t[e+1]<<8},"b2"),ae=g(function(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0},"b4"),Ft=g(function(t,e){return ae(t,e)+ae(t,e+4)*4294967296},"b8"),ee=g(function(t,e,n){for(;n;++e)t[e]=n,n>>>=8;},"wbytes");function gs(t,e){return ms(t,e||{},0,0)}g(gs,"deflateSync");function ws(t,e){return ds(t,{i:2},e&&e.out,e&&e.dictionary)}g(ws,"inflateSync");var Ln=g(function(t,e,n,r){for(var s in t){var i=t[s],o=e+s,l=r;Array.isArray(i)&&(l=zn(r,i[1]),i=i[0]),ArrayBuffer.isView(i)?n[o]=[i,l]:(n[o+="/"]=[new Y(0),l],Ln(i,o,n,r));}},"fltn"),On=typeof TextEncoder<"u"&&new TextEncoder,Ht=typeof TextDecoder<"u"&&new TextDecoder,ys=0;try{Ht.decode(Wn,{stream:!0}),ys=1;}catch{}var vs=g(function(t){for(var e="",n=0;;){var r=t[n++],s=(r>127)+(r>223)+(r>239);if(n+s>t.length)return {s:e,r:nt(t,n-1)};s?s==3?(r=((r&15)<<18|(t[n++]&63)<<12|(t[n++]&63)<<6|t[n++]&63)-65536,e+=String.fromCharCode(55296|r>>10,56320|r&1023)):s&1?e+=String.fromCharCode((r&31)<<6|t[n++]&63):e+=String.fromCharCode((r&15)<<12|(t[n++]&63)<<6|t[n++]&63):e+=String.fromCharCode(r);}},"dutf8");function dt(t,e){if(e){for(var n=new Y(t.length),r=0;r<t.length;++r)n[r]=t.charCodeAt(r);return n}if(On)return On.encode(t);for(var s=t.length,i=new Y(t.length+(t.length>>1)),o=0,l=g(function(c){i[o++]=c;},"w"),r=0;r<s;++r){if(o+5>i.length){var a=new Y(o+8+(s-r<<1));a.set(i),i=a;}var u=t.charCodeAt(r);u<128||e?l(u):u<2048?(l(192|u>>6),l(128|u&63)):u>55295&&u<57344?(u=65536+(u&1047552)|t.charCodeAt(++r)&1023,l(240|u>>18),l(128|u>>12&63),l(128|u>>6&63),l(128|u&63)):(l(224|u>>12),l(128|u>>6&63),l(128|u&63));}return nt(i,0,o)}g(dt,"strToU8");function De(t,e){if(e){for(var n="",r=0;r<t.length;r+=16384)n+=String.fromCharCode.apply(null,t.subarray(r,r+16384));return n}else {if(Ht)return Ht.decode(t);var s=vs(t),i=s.s,n=s.r;return n.length&&te(8),i}}g(De,"strFromU8");var bs=g(function(t,e){return e+30+pe(t,e+26)+pe(t,e+28)},"slzh"),xs=g(function(t,e,n){var r=pe(t,e+28),s=pe(t,e+30),i=De(t.subarray(e+46,e+46+r),!(pe(t,e+8)&2048)),o=e+46+r,l=Ns(t,o,s,n,ae(t,e+20),ae(t,e+24),ae(t,e+42)),a=l[0],u=l[1],c=l[2];return [pe(t,e+10),a,u,i,o+s+pe(t,e+32),c]},"zh"),Ns=g(function(t,e,n,r,s,i,o){var l=s==4294967295,a=i==4294967295,u=o==4294967295,c=e+n,d=l+a+u;if(r&&d){for(;e+4<c;e+=4+pe(t,e+2))if(pe(t,e)==1)return [l?Ft(t,e+4+8*a):s,a?Ft(t,e+4):i,u?Ft(t,e+4+8*(a+l)):o,1];r<2&&te(13);}return [s,i,o,0]},"z64hs"),qt=g(function(t){var e=0;if(t)for(var n in t){var r=t[n].length;r>65535&&te(9),e+=r+4;}return e},"exfl"),Dn=g(function(t,e,n,r,s,i,o,l){var a=r.length,u=n.extra,c=l&&l.length,d=qt(u);ee(t,e,o!=null?33639248:67324752),e+=4,o!=null&&(t[e++]=20,t[e++]=n.os),t[e]=20,e+=2,t[e++]=n.flag<<1|(i<0&&8),t[e++]=s&&8,t[e++]=n.compression&255,t[e++]=n.compression>>8;var f=new Date(n.mtime==null?Date.now():n.mtime),h=f.getFullYear()-1980;if((h<0||h>119)&&te(10),ee(t,e,h<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),e+=4,i!=-1&&(ee(t,e,n.crc),ee(t,e+4,i<0?-i-2:i),ee(t,e+8,n.size)),ee(t,e+12,a),ee(t,e+14,d),e+=16,o!=null&&(ee(t,e,c),ee(t,e+6,n.attrs),ee(t,e+10,o),e+=14),t.set(r,e),e+=a,d)for(var _ in u){var p=u[_],m=p.length;ee(t,e,+_),ee(t,e+2,m),t.set(p,e+4),e+=4+m;}return c&&(t.set(l,e),e+=c),e},"wzh"),ks=g(function(t,e,n,r,s){ee(t,e,101010256),ee(t,e+8,n),ee(t,e+10,n),ee(t,e+12,r),ee(t,e+16,s);},"wzf");function Un(t,e){e||(e={});var n={},r=[];Ln(t,"",n,e);var s=0,i=0;for(var o in n){var l=n[o],a=l[0],u=l[1],c=u.level==0?0:8,d=dt(o),f=d.length,h=u.comment,_=h&&dt(h),p=_&&_.length,m=qt(u.extra);f>65535&&te(11);var y=c?gs(a,u):a,x=y.length,b=_s();b.p(a),r.push(zn(u,{size:a.length,crc:b.d(),c:y,f:d,m:_,u:f!=o.length||_&&h.length!=p,o:s,compression:c})),s+=30+f+m+x,i+=76+2*(f+m)+(p||0)+x;}for(var w=new Y(i+22),v=s,N=i-s,k=0;k<r.length;++k){var d=r[k];Dn(w,d.o,d,d.f,d.u,d.c.length);var C=30+d.f.length+qt(d.extra);w.set(d.c,d.o+C),Dn(w,s,d,d.f,d.u,d.c.length,d.o,d.m),s+=16+C+(d.m?d.m.length:0);}return ks(w,s,r.length,N,v),w}g(Un,"zipSync");function Le(t,e){for(var n={},r=t.length-22;ae(t,r)!=101010256;--r)(!r||t.length-r>65558)&&te(13);var s=pe(t,r+8);if(!s)return {};var i=ae(t,r+16),o=ae(t,r-20)==117853008;if(o){var l=ae(t,r-12);o=ae(t,l)==101075792,o&&(s=ae(t,l+32),i=ae(t,l+48));}for(var a=e&&e.filter,u=0;u<s;++u){var c=xs(t,i,o),d=c[0],f=c[1],h=c[2],_=c[3],p=c[4],m=c[5],y=bs(t,m);i=p,(!a||a({name:_,size:f,originalSize:h,compression:d}))&&(d?d==8?n[_]=ws(t.subarray(y,y+f),{out:new Y(h)}):te(14,"unknown compression type "+d):n[_]=nt(t,y,y+f));}return n}g(Le,"unzipSync");var Dr=Mt(Gt());var Nn=Mt(Gt());var Re=1,hn=3,pn=4,wr=8,_n=9,yr=class{static{g(this,"FastNode");}nodeType=0;parentNode=null;ownerDocument=null;get firstChild(){return null}get lastChild(){return null}get nextSibling(){let t=this.parentNode;if(!t)return null;let e=t.childNodes,n=e.indexOf(this);return n>=0&&n+1<e.length?e[n+1]:null}get previousSibling(){let t=this.parentNode;if(!t)return null;let e=t.childNodes,n=e.indexOf(this);return n>0?e[n-1]:null}},at=class vr extends yr{static{g(this,"_FastText");}constructor(e){super(),this.data=e;}data;nodeType=hn;get nodeName(){return "#text"}get nodeValue(){return this.data}set nodeValue(e){this.data=e;}get textContent(){return this.data}set textContent(e){this.data=e,this.ownerDocument&&this.ownerDocument._inc++;}cloneNode(e){let n=new vr(this.data);return n.ownerDocument=this.ownerDocument,n}toString(){return Et(this)}},br=class xr extends at{static{g(this,"_FastComment");}nodeType=wr;cloneNode(e){let n=new xr(this.data);return n.ownerDocument=this.ownerDocument,n}},Es=class Nr extends at{static{g(this,"_FastCData");}nodeType=pn;cloneNode(e){let n=new Nr(this.data);return n.ownerDocument=this.ownerDocument,n}},kr=class extends yr{static{g(this,"FastParent");}childNodes=[];get firstChild(){return this.childNodes.length?this.childNodes[0]:null}get lastChild(){return this.childNodes.length?this.childNodes[this.childNodes.length-1]:null}hasChildNodes(){return this.childNodes.length>0}bump(){let t=this.nodeType===_n?this:this.ownerDocument;t&&t._inc++;}appendChild(t){return t.parentNode&&t.parentNode.removeChild(t),this.childNodes.push(t),t.parentNode=this,this.bump(),t}insertBefore(t,e){if(!e)return this.appendChild(t);if(this.childNodes.indexOf(e)<0)throw new Error("insertBefore: reference node not a child");t.parentNode&&t.parentNode.removeChild(t);let r=this.childNodes.indexOf(e);return this.childNodes.splice(r,0,t),t.parentNode=this,this.bump(),t}removeChild(t){let e=this.childNodes.indexOf(t);if(e<0)throw new Error("removeChild: node is not a child");return this.childNodes.splice(e,1),t.parentNode=null,this.bump(),t}replaceChild(t,e){if(this.childNodes.indexOf(e)<0)throw new Error("replaceChild: node is not a child");t.parentNode&&t.parentNode.removeChild(t);let r=this.childNodes.indexOf(e);return this.childNodes[r]=t,t.parentNode=this,e.parentNode=null,this.bump(),e}getElementsByTagName(t){let e=[],n=t==="*",r=[];for(let s=this.childNodes.length-1;s>=0;s--)r.push(this.childNodes[s]);for(;r.length;){let s=r.pop();if(s.nodeType===Re){let i=s;(n||i.tagName===t)&&e.push(i);for(let o=i.childNodes.length-1;o>=0;o--)r.push(i.childNodes[o]);}}return e}},Er=class Ar extends kr{static{g(this,"_FastElement");}constructor(e){super(),this.tagName=e;}tagName;nodeType=Re;attrs=[];get nodeName(){return this.tagName}get localName(){let e=this.tagName.indexOf(":");return e<0?this.tagName:this.tagName.slice(e+1)}get prefix(){let e=this.tagName.indexOf(":");return e<0?null:this.tagName.slice(0,e)}get nodeValue(){return null}get attributes(){let e=this.attrs.map(([n,r])=>({nodeType:2,name:n,value:r,nodeName:n,nodeValue:r,localName:n.indexOf(":")<0?n:n.slice(n.indexOf(":")+1),prefix:n.indexOf(":")<0?null:n.slice(0,n.indexOf(":")),ownerElement:this}));return e.item=n=>e[n]??null,e}toString(){return Et(this)}getAttribute(e){let n=this.attrs;for(let r=0;r<n.length;r++)if(n[r][0]===e)return n[r][1];return null}hasAttribute(e){return this.getAttribute(e)!==null}setAttribute(e,n){let r=this.attrs;for(let s=0;s<r.length;s++)if(r[s][0]===e){r[s][1]=String(n),this.ownerDocument&&this.ownerDocument._inc++;return}r.push([e,String(n)]),this.ownerDocument&&this.ownerDocument._inc++;}removeAttribute(e){let n=this.attrs;for(let r=0;r<n.length;r++)if(n[r][0]===e){n.splice(r,1),this.ownerDocument&&this.ownerDocument._inc++;return}}get textContent(){let e="",n=[];for(let r=this.childNodes.length-1;r>=0;r--)n.push(this.childNodes[r]);for(;n.length;){let r=n.pop();if(r.nodeType===hn||r.nodeType===pn)e+=r.data;else if(r.nodeType===Re){let s=r;for(let i=s.childNodes.length-1;i>=0;i--)n.push(s.childNodes[i]);}}return e}set textContent(e){for(let n of this.childNodes)n.parentNode=null;if(this.childNodes.length=0,e!==""&&e!==null&&e!==void 0){let n=new at(String(e));n.ownerDocument=this.ownerDocument,n.parentNode=this,this.childNodes.push(n);}this.ownerDocument&&this.ownerDocument._inc++;}cloneNode(e=false){let n=new Ar(this.tagName);if(n.ownerDocument=this.ownerDocument,this.attrs.length&&(n.attrs=this.attrs.map(([r,s])=>[r,s])),e)for(let r of this.childNodes){let s=r.cloneNode(true);s.parentNode=n,n.childNodes.push(s);}return n}},As=class extends kr{static{g(this,"FastDocument");}nodeType=_n;_inc=1;documentElement=null;get nodeName(){return "#document"}createElement(t){let e=new Er(t);return e.ownerDocument=this,e}createElementNS(t,e){return this.createElement(e)}createTextNode(t){let e=new at(String(t));return e.ownerDocument=this,e}createComment(t){let e=new br(String(t));return e.ownerDocument=this,e}toString(){return Et(this)}appendChild(t){let e=super.appendChild(t);return t.nodeType===Re&&(this.documentElement=t),e}replaceChild(t,e){let n=super.replaceChild(t,e);return e===this.documentElement&&t.nodeType===Re&&(this.documentElement=t),n}},Cs=/&(?:amp|lt|gt|quot|apos|#x?[0-9a-fA-F]+);/g;function Cr(t){return t.indexOf("&")<0?t:t.replace(Cs,e=>{switch(e){case "&amp;":return "&";case "&lt;":return "<";case "&gt;":return ">";case "&quot;":return '"';case "&apos;":return "'";default:{let n=e.slice(2,-1),r=n[0]==="x"||n[0]==="X"?parseInt(n.slice(1),16):parseInt(n,10);return Number.isFinite(r)?String.fromCodePoint(r):e}}})}g(Cr,"decodeEntities");function tn(t){return t.indexOf("\r")<0?t:t.replace(/\r\n?/g,`
6
- `)}g(tn,"normalizeLineEnds");function Ps(t){let e=tn(t),n=/[\n\t]/.test(e)?e.replace(/[\n\t]/g," "):e;return Cr(n)}g(Ps,"normalizeAttrValue");var Qt=new Set([32,9,10,13]);function Ts(t){t.charCodeAt(0)===65279&&(t=t.slice(1));let e=new As,n=e,r=0,s=t.length,i=false;for(;r<s;){let o=t.indexOf("<",r);if(o<0){if(n!==e)throw new Error("Unexpected end of XML");if(/\S/.test(t.slice(r)))throw new Error("Content after document root");break}if(o>r&&n!==e){let d=t.slice(r,o),f=new at(Cr(tn(d)));f.ownerDocument=e,f.parentNode=n,n.childNodes.push(f);}else if(o>r&&/\S/.test(t.slice(r,o)))throw new Error("Text content outside document root");r=o+1;let l=t.charCodeAt(r);if(l===47){let d=t.indexOf(">",r);if(d<0)throw new Error("Unterminated close tag");let f=t.slice(r+1,d).trim();if(n.nodeType!==Re||n.tagName!==f)throw new Error(`Mismatched close tag </${f}>`);n=n.parentNode??e,r=d+1;continue}if(l===63){let d=t.indexOf("?>",r);if(d<0)throw new Error("Unterminated processing instruction");r=d+2;continue}if(l===33){if(t.startsWith("!--",r)){let f=t.indexOf("-->",r+3);if(f<0)throw new Error("Unterminated comment");let h=new br(t.slice(r+3,f));h.ownerDocument=e,n!==e&&(h.parentNode=n,n.childNodes.push(h)),r=f+3;continue}if(t.startsWith("![CDATA[",r)){let f=t.indexOf("]]>",r+8);if(f<0)throw new Error("Unterminated CDATA section");if(n!==e){let h=new Es(tn(t.slice(r+8,f)));h.ownerDocument=e,h.parentNode=n,n.childNodes.push(h);}r=f+3;continue}let d=t.indexOf(">",r);if(d<0)throw new Error("Unterminated declaration");r=d+1;continue}let a=r;for(;a<s;){let d=t.charCodeAt(a);if(Qt.has(d)||d===62||d===47)break;a++;}if(a===r)throw new Error(`Invalid tag at offset ${o}`);let u=new Er(t.slice(r,a));if(u.ownerDocument=e,n===e){if(i)throw new Error("Multiple document roots");i=true,e.childNodes.push(u),u.parentNode=e,e.documentElement=u;}else u.parentNode=n,n.childNodes.push(u);r=a;let c=false;for(;r<s;){let d=t.charCodeAt(r);if(d===62){r++;break}if(d===47){if(t.charCodeAt(r+1)!==62)throw new Error("Malformed self-close");c=true,r+=2;break}if(Qt.has(d)){r++;continue}let f=t.indexOf("=",r);if(f<0)throw new Error("Malformed attribute");let h=t.slice(r,f).trim(),_=f+1;for(;_<s&&Qt.has(t.charCodeAt(_));)_++;let p=t.charCodeAt(_);if(p!==34&&p!==39)throw new Error("Unquoted attribute value");let m=t.indexOf(String.fromCharCode(p),_+1);if(m<0)throw new Error("Unterminated attribute value");u.attrs.push([h,Ps(t.slice(_+1,m))]),r=m+1;}c||(n=u);}if(n!==e)throw new Error("Unclosed element at end of document");if(!e.documentElement)throw new Error("Empty XML document");return e}g(Ts,"parseFastXml");function Is(t){return /[&<>\r]/.test(t)?t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\r/g,"&#13;"):t}g(Is,"escText");function Ss(t){return /[&<>"\t\n\r]/.test(t)?t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\t/g,"&#9;").replace(/\n/g,"&#10;").replace(/\r/g,"&#13;"):t}g(Ss,"escAttr");function Et(t){let e=[],n=g(r=>{switch(r.nodeType){case Re:{let s=r;e.push("<",s.tagName);for(let i=0;i<s.attrs.length;i++){let[o,l]=s.attrs[i];e.push(" ",o,'="',Ss(l),'"');}if(s.childNodes.length===0)e.push("/>");else {e.push(">");for(let i of s.childNodes)n(i);e.push("</",s.tagName,">");}break}case hn:e.push(Is(r.data));break;case pn:e.push("<![CDATA[",r.data,"]]>");break;case wr:e.push("<!--",r.data,"-->");break;case _n:for(let s of r.childNodes)n(s);break}},"write");return n(t),e.join("")}g(Et,"serializeFastXml");function B(t,e){for(let n=0;n<t.childNodes.length;n++){let r=t.childNodes[n];if(r.nodeType===1&&r.tagName===e)return r}return null}g(B,"findChild");function Pr(t,e){let n=[];for(let r=0;r<t.childNodes.length;r++){let s=t.childNodes[r];s.nodeType===1&&s.tagName===e&&n.push(s);}return n}g(Pr,"findChildren");function M(t,e){return Array.from(t.getElementsByTagName(e))}g(M,"findAllDescendants");function je(t){return t.startsWith("\uFEFF")&&(t=t.slice(1)),Ts(t)}g(je,"parseXml");function Hn(t){let e=Et(t),r=/<([a-zA-Z0-9_:]+)(\s+[^>]+?)(>|\/>)/.exec(e);if(r&&!r[1].startsWith("?")){let s=r.index,i=e.substring(0,s);if(!i.includes("<")||i.trim().startsWith("<?xml")&&(i.match(/</g)||[]).length===1){let l=r[0],a=`<${r[1]}`,u=r[2],c=r[3],d=/([a-zA-Z0-9_:]+)\s*=\s*(["'])(.*?)\2/g,f=[],h;for(;(h=d.exec(u))!==null;)f.push(h[0].trim());f.sort((p,m)=>{let y=p.split("=")[0].trim(),x=m.split("=")[0].trim(),b=y.startsWith("xmlns"),w=x.startsWith("xmlns");return b&&!w?-1:!b&&w?1:y<x?-1:y>x?1:0});let _=f.length>0?`${a} ${f.join(" ")}${c}`:`${a}${c}`;e=e.substring(0,s)+_+e.substring(s+l.length);}}return e}g(Hn,"serializeXml");var bt=1,mn=2147483647;function gn(t){return ((t&mn)>>>0||bt).toString(16).toUpperCase().padStart(8,"0")}g(gn,"toLongHexNumber");function pt(){let t=mn-bt+1;return gn(bt+Math.floor(Math.random()*t))}g(pt,"generateLongHexNumber");function qn(t){if(!/^[0-9A-Fa-f]{1,8}$/.test(t))return false;let e=parseInt(t,16);return e>=bt&&e<=mn}g(qn,"isWordReadableLongHexNumber");var nn="__adeu_wp_index_cache",Tr="__adeu_clean_inc";function At(t){return typeof t._inc=="number"?t._inc:null}g(At,"docInc");function it(t){let e=At(t);e!==null&&(t[Tr]=e);}g(it,"markPartClean");function wn(t){let e=At(t);return e!==null&&t[Tr]===e}g(wn,"isPartClean");function $s(t){let e=new Map,n=t.documentElement;if(!n)return e;let r=0;n.nodeType===1&&n.tagName==="w:p"&&e.set(n,r++);let s=[n],i=[0];for(;s.length;){let o=s.length-1,l=s[o].childNodes;if(!l||i[o]>=l.length){s.pop(),i.pop();continue}let a=l[i[o]++];a.nodeType===1&&(a.tagName==="w:p"&&e.set(a,r++),s.push(a),i.push(0));}return e}g($s,"buildWpIndexMap");function Os(t,e){let n=At(t),r=t[nn];(!r||n===null||r.inc!==n||!r.map.has(e))&&(r={inc:n??NaN,map:$s(t)},t[nn]=r);let s=r.map.get(e);return s===void 0?-1:s}g(Os,"wpDocumentOrderIndex");function Ds(t){let e=t[nn],n=At(t);e&&n!==null&&(e.inc=n);}g(Ds,"resyncAfterOwnAttributeMutation");function Ir(t,e){let n=t.getElementsByTagName("w:p")[0],r=n?n.getAttribute("w14:paraId"):null;if(!r&&e){let s=t.ownerDocument,i=wn(s);n||(n=s.createElement("w:p"),t.appendChild(n));let o=Os(s,n),l=2166136261,a=`fallback-paraId-${o}`;for(let u=0;u<a.length;u++)l^=a.charCodeAt(u),l+=(l<<1)+(l<<4)+(l<<7)+(l<<8)+(l<<24);r=gn(l),n.setAttribute("w14:paraId",r),Ds(s),i&&it(s);}return {paraId:r,firstP:n}}g(Ir,"resolve_cell_anchor");var wt=class{static{g(this,"Relationship");}constructor(t,e,n,r){this.id=t,this.type=e,this.target=n,this.isExternal=r;}id;type;target;isExternal},Sr=class{static{g(this,"Part");}constructor(t,e,n,r){this.partname=t,this.blob=e,this.contentType=r,this._element=n;}partname;blob;contentType;rels=new Map;_element;package;addRelationship(t,e,n,r=false){if(this.rels.set(t,new wt(t,e,n,r)),this.partname.endsWith(".rels")){let s=this._element.ownerDocument;if(s){let i=s.createElementNS("http://schemas.openxmlformats.org/package/2006/relationships","Relationship");i.setAttribute("Id",t),i.setAttribute("Type",e),i.setAttribute("Target",n),r&&i.setAttribute("TargetMode","External"),this._element.appendChild(i);}}}},Ms=class{static{g(this,"DocxPackage");}constructor(t){this.unzipped=t;}unzipped;parts=[];mainDocumentPart;getPartByPath(t){let e=t.startsWith("/")?t.substring(1):t;return this.parts.find(n=>n.partname===e||n.partname==="/"+e)}nextPartname(t){let e=1;for(;;){let n=t.replace("%d",e===1?"":e.toString());if(!this.getPartByPath(n))return n;e++;}}addPart(t,e,n){let r=je(n),s=new Sr(t,n,r.documentElement,e);s.package=this,this.parts.push(s);let i=this.getPartByPath("[Content_Types].xml");if(i){let o=i._element.ownerDocument;if(o){let l=o.createElement("Override");l.setAttribute("PartName",t),l.setAttribute("ContentType",e),i._element.appendChild(l);}}return s}getOrCreateRelsPart(t){let e=t.split("/"),n=e.pop(),r=e.join("/")+"/_rels/"+n+".rels",s=this.getPartByPath(r);return s||(s=this.addPart(r,"application/vnd.openxmlformats-package.relationships+xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
7
- <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>`)),s}},ce=class $r{static{g(this,"_DocumentObject");}constructor(e,n){this.pkg=e,this.part=n;}pkg;part;settings={oddAndEvenPagesHeaderFooter:false};sections=[];get element(){return B(this.part._element,"w:body")||this.part._element}static async load(e,n){let r=e instanceof Uint8Array?e:new Uint8Array(e),s=Le(r),i=new Ms(s),o=s["[Content_Types].xml"],l={};if(o){let _=je(De(o)),p=M(_.documentElement,"Override");for(let m of p)l[m.getAttribute("PartName")||""]=m.getAttribute("ContentType")||"";}let a=n?.onPart,u=Math.max(1,n?.partTickEvery??200),c=0;if(a)for(let _ of Object.keys(s))(_.endsWith(".xml")||_.endsWith(".rels"))&&c++;let d=0;for(let[_,p]of Object.entries(s))if(_.endsWith(".xml")||_.endsWith(".rels")){let m=De(p),y=je(m);it(y);let x=l["/"+_]||"application/xml",b=new Sr("/"+_,m,y.documentElement,x);b.package=i,i.parts.push(b),d++,a&&d%u===0&&await a(d,c);}a&&c>0&&await a(c,c);let f=i.getPartByPath("word/document.xml");if(!f)throw new Error("Invalid DOCX: Missing word/document.xml");i.mainDocumentPart=f;let h=i.getPartByPath("word/_rels/document.xml.rels");if(h){let _=M(h._element,"Relationship");for(let p of _){let m=p.getAttribute("Id"),y=p.getAttribute("Target"),x=p.getAttribute("Type"),b=p.getAttribute("TargetMode");m&&y&&x&&f.rels.set(m,new wt(m,x,y,b==="External"));}}return new $r(i,f)}relateTo(e,n){let r=1;for(;this.part.rels.has(`rId${r}`);)r++;let s=`rId${r}`,i=e.partname.split("/").pop();this.part.rels.set(s,new wt(s,n,i,false)),this.pkg.getOrCreateRelsPart(this.part.partname).addRelationship(s,n,i,false);}relateToExternal(e,n){let r=1;for(;this.part.rels.has(`rId${r}`);)r++;let s=`rId${r}`;return this.part.rels.set(s,new wt(s,n,e,true)),this.pkg.getOrCreateRelsPart(this.part.partname).addRelationship(s,n,e,true),s}async save(){for(let e of this.pkg.parts){let n=Hn(e._element.ownerDocument||e._element);n.includes("w16du:")&&!n.includes("xmlns:w16du=")&&(e._element.setAttribute("xmlns:w16du","http://schemas.microsoft.com/office/word/2023/wordml/word16du"),n=Hn(e._element.ownerDocument||e._element)),n.startsWith("<?xml")||(n=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
8
- `+n),this.pkg.unzipped[e.partname.substring(1)]=dt(n),e.blob=n;let r=e._element.ownerDocument;r&&it(r);}return Buffer.from(Un(this.pkg.unzipped))}},ie=class{static{g(this,"Paragraph");}constructor(t,e){this._element=t,this._parent=e;}_element;_parent;get text(){let t="",e=this._element.getElementsByTagName("w:t");for(let n=0;n<e.length;n++)t+=e[n].textContent||"";return t}},Ce=class{static{g(this,"Run");}constructor(t,e){this._element=t,this._parent=e;}_element;_parent},Rs=class{static{g(this,"Cell");}constructor(t,e){this._element=t,this._parent=e;}_element;_parent},js=class{static{g(this,"Row");}constructor(t,e){this._element=t,this._parent=e;let n=this._element.getElementsByTagName("w:tc");for(let r=0;r<n.length;r++)this.cells.push(new Rs(n[r],this));}_element;_parent;cells=[]},Se=class{static{g(this,"Table");}constructor(t,e){this._element=t,this._parent=e;let n=this._element.getElementsByTagName("w:tr");for(let r=0;r<n.length;r++)this.rows.push(new js(n[r],this));}_element;_parent;rows=[]},Jn=class{static{g(this,"NotesPart");}constructor(t,e){this.part=t,this.note_type=e,this._element=t._element;}part;note_type;_element},Bs=class{static{g(this,"FootnoteItem");}constructor(t,e,n){this._element=t,this._parent=e,this.note_type=n,this.id=t.getAttribute("w:id")||"",this.part=e.part;}_element;_parent;note_type;id;part},re={w:"http://schemas.openxmlformats.org/wordprocessingml/2006/main",w14:"http://schemas.microsoft.com/office/word/2010/wordml",w15:"http://schemas.microsoft.com/office/word/2012/wordml",w16cid:"http://schemas.microsoft.com/office/word/2016/wordml/cid",w16cex:"http://schemas.microsoft.com/office/word/2018/wordml/cex",mc:"http://schemas.openxmlformats.org/markup-compatibility/2006"},Z={COMMENTS:"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",EXTENDED:"application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml",IDS:"application/vnd.openxmlformats-officedocument.wordprocessingml.commentsIds+xml",EXTENSIBLE:"application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtensible+xml"},ke={COMMENTS:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",EXTENDED:"http://schemas.microsoft.com/office/2011/relationships/commentsExtended",IDS:"http://schemas.microsoft.com/office/2016/09/relationships/commentsIds",EXTENSIBLE:"http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible"},Xn=["w14:paraId","w15:paraId","w15:paraIdParent","w16cid:paraId"],Gn=["w16cid:durableId","w16cex:durableId"],Fs=["w14:textId","w:rsidR","w:rsidRPr","w:rsidRDefault","w:rsidP","w:rsidDel","w:rsidTr"],Or=class extends Error{static{g(this,"CommentThreadingError");}constructor(t){super(t),this.name="CommentThreadingError";}};function*rn(t){yield t;for(let e=0;e<t.childNodes.length;e++){let n=t.childNodes[e];n.nodeType===1&&(yield*rn(n));}}g(rn,"walkElements");var st=class{static{g(this,"CommentsManager");}constructor(t){this.doc=t;}doc;_commentsPart=null;_extendedPart=null;_idsPart=null;_extensiblePart=null;_nextId=null;get commentsPart(){return this._commentsPart||(this._commentsPart=this._getOrCreateCommentsPart(),this._ensureNamespaces()),this._commentsPart}get extendedPart(){return this._extendedPart||(this._extendedPart=this._getOrCreateExtendedPart()),this._extendedPart}get idsPart(){return this._idsPart||(this._idsPart=this._getOrCreateIdsPart()),this._idsPart}get extensiblePart(){return this._extensiblePart||(this._extensiblePart=this._getOrCreateExtensiblePart()),this._extensiblePart}get nextId(){return this._nextId===null&&(this._nextId=this._getNextCommentId()),this._nextId}set nextId(t){this._nextId=t;}_getExistingPartByType(t){return this.doc.pkg.parts.find(e=>e.contentType===t)||null}_linkPart(t,e){for(let n of this.doc.part.rels.values())if(!n.isExternal&&n.target===t.partname.split("/").pop())return t;return this.doc.relateTo(t,e),t}_getOrCreateCommentsPart(){let t=this._getExistingPartByType(Z.COMMENTS);if(t)return this._linkPart(t,ke.COMMENTS);let e=this.doc.pkg.nextPartname("/word/comments%d.xml"),n=`<w:comments xmlns:w="${re.w}" xmlns:w14="${re.w14}" xmlns:w15="${re.w15}" xmlns:w16cid="${re.w16cid}" xmlns:w16cex="${re.w16cex}" xmlns:mc="${re.mc}" mc:Ignorable="w14 w15 w16cid w16cex"></w:comments>`;return t=this.doc.pkg.addPart(e,Z.COMMENTS,n),this.doc.relateTo(t,ke.COMMENTS),t}_getOrCreateExtendedPart(){let t=this._getExistingPartByType(Z.EXTENDED);if(t)return this._linkPart(t,ke.EXTENDED);let e=this.doc.pkg.nextPartname("/word/commentsExtended%d.xml"),n=`<w15:commentsEx xmlns:w15="${re.w15}"></w15:commentsEx>`;return t=this.doc.pkg.addPart(e,Z.EXTENDED,n),this.doc.relateTo(t,ke.EXTENDED),t}_getOrCreateIdsPart(){let t=this._getExistingPartByType(Z.IDS);if(t)return this._linkPart(t,ke.IDS);let e=this.doc.pkg.nextPartname("/word/commentsIds%d.xml"),n=`<w16cid:commentsIds xmlns:w16cid="${re.w16cid}"></w16cid:commentsIds>`;return t=this.doc.pkg.addPart(e,Z.IDS,n),this.doc.relateTo(t,ke.IDS),t}_getOrCreateExtensiblePart(){let t=this._getExistingPartByType(Z.EXTENSIBLE);if(t)return this._linkPart(t,ke.EXTENSIBLE);let e=this.doc.pkg.nextPartname("/word/commentsExtensible%d.xml"),n=`<w16cex:commentsExtensible xmlns:w16cex="${re.w16cex}"></w16cex:commentsExtensible>`;return t=this.doc.pkg.addPart(e,Z.EXTENSIBLE,n),this.doc.relateTo(t,ke.EXTENSIBLE),t}_ensureNamespaces(){let t=this._commentsPart?._element;if(!t)return;let e=[["xmlns:w",re.w],["xmlns:w14",re.w14],["xmlns:w15",re.w15],["xmlns:w16cid",re.w16cid],["xmlns:w16cex",re.w16cex],["xmlns:mc",re.mc]];for(let[n,r]of e)t.getAttribute(n)||t.setAttribute(n,r);}_getNextCommentId(){let t=[0],e=this._getExistingPartByType(Z.COMMENTS);if(e){let n=M(e._element,"w:comment");for(let r of n){let s=r.getAttribute("w:id");s&&t.push(parseInt(s,10)||0);}}return Math.max(...t)+1}_generateHexId(){return pt()}_generateDurableId(){return pt()}_getInitials(t){return t?t.split(" ").filter(Boolean).map(e=>e[0]).join("").toUpperCase():""}_hasCommentsPart(){return this._commentsPart!==null||this._getExistingPartByType(Z.COMMENTS)!==null}_findParaIdForComment(t){if(!this._hasCommentsPart())return null;for(let e of M(this.commentsPart._element,"w:comment"))if(e.getAttribute("w:id")===t)for(let n of M(e,"w:p")){let r=n.getAttribute("w14:paraId");if(r)return r}return null}_findThreadRootParaId(t){let e=this._findParaIdForComment(t),n=this._getExistingPartByType(Z.EXTENDED);if(!e||!n)return e;for(let r=0;r<n._element.childNodes.length;r++){let s=n._element.childNodes[r];if(s.nodeType===1&&s.getAttribute("w15:paraId")===e){let i=s.getAttribute("w15:paraIdParent");if(i)return i}}return e}_existingCommentPartElements(){let t=[];for(let e of [Z.COMMENTS,Z.EXTENDED,Z.IDS,Z.EXTENSIBLE]){let n=this._getExistingPartByType(e);n&&t.push(n._element);}return t}_freeLongHexNumber(t,e){let n=parseInt(t,16),r=Number.isNaN(n)?pt():gn(n);for(;e.has(r);)r=pt();return r}_repairInheritedLongHexNumbers(){let t=this._existingCommentPartElements();if(t.length===0)return;let e=g(s=>{let i=new Set,o=[];for(let a of t)for(let u of rn(a))for(let c of s){let d=u.getAttribute(c);d&&(qn(d)?i.add(d.toUpperCase()):o.includes(d)||o.push(d));}let l=new Map;for(let a of o){let u=this._freeLongHexNumber(a,i);i.add(u),l.set(a,u);}return l},"remapFor"),n=e(Xn),r=e(Gn);for(let s of t)for(let i of rn(s)){for(let o of Xn){let l=n.get(i.getAttribute(o)??"");l&&i.setAttribute(o,l);}for(let o of Gn){let l=r.get(i.getAttribute(o)??"");l&&i.setAttribute(o,l);}for(let o of Fs){let l=i.getAttribute(o);l&&!qn(l)&&i.setAttribute(o,this._freeLongHexNumber(l,new Set));}}}_adoptIntoModernComments(t){if(!this._hasCommentsPart())return null;let e=null;for(let i of M(this.commentsPart._element,"w:comment"))if(i.getAttribute("w:id")===t){e=i;break}if(!e)return null;let n=M(e,"w:p");if(n.length===0)return null;let r=null;for(let i of n){let o=i.getAttribute("w14:paraId");if(o){r=o;break}}r||(r=this._generateHexId(),n[0].setAttribute("w14:paraId",r));let s=g((i,o)=>{for(let l=0;l<i._element.childNodes.length;l++){let a=i._element.childNodes[l];if(a.nodeType===1&&a.getAttribute(o)===r)return true}return false},"hasChild");if(!s(this.extendedPart,"w15:paraId")){let o=this.extendedPart._element.ownerDocument.createElement("w15:commentEx");o.setAttribute("w15:paraId",r),o.setAttribute("w15:done","0"),this.extendedPart._element.appendChild(o);}if(!s(this.idsPart,"w16cid:paraId")){let o=this.idsPart._element.ownerDocument.createElement("w16cid:commentId");o.setAttribute("w16cid:paraId",r),o.setAttribute("w16cid:durableId",this._generateDurableId()),this.idsPart._element.appendChild(o);}return r}resolveThreadParentParaId(t){this._repairInheritedLongHexNumbers();let e=this._findThreadRootParaId(t),n=this._adoptIntoModernComments(t);return e??n}addComment(t,e,n=null){this._repairInheritedLongHexNumbers();let r=this._getExistingPartByType(Z.EXTENDED)!==null,s=null;if(n!=null&&(s=this.resolveThreadParentParaId(n),!s))throw new Or(`Cannot thread a reply onto comment Com:${n}: the comment has no resolvable paragraph identity (w14:paraId) in word/comments.xml, so Word would render the reply as a separate top-level comment instead of a reply. Refusing to create an unthreaded comment.`);let i=this.nextId.toString();this.nextId++;let o=new Date().toISOString().replace(/\.\d{3}Z$/,"Z"),l=this.commentsPart._element.ownerDocument,a=l.createElement("w:comment");a.setAttribute("w:id",i),a.setAttribute("w:author",t),a.setAttribute("w:date",o);let u=this._getInitials(t);u&&a.setAttribute("w:initials",u),n&&!r&&a.setAttribute("w15:p",n);let c=this._generateHexId(),d=this._generateHexId(),f=l.createElement("w:p");f.setAttribute("w14:paraId",c),f.setAttribute("w14:textId","77777777"),f.setAttribute("w:rsidR",d),f.setAttribute("w:rsidRDefault",d),f.setAttribute("w:rsidP",d);let h=l.createElement("w:pPr"),_=l.createElement("w:pStyle");_.setAttribute("w:val","CommentText"),h.appendChild(_),f.appendChild(h);let p=l.createElement("w:r"),m=l.createElement("w:rPr"),y=l.createElement("w:rStyle");y.setAttribute("w:val","CommentReference"),m.appendChild(y),p.appendChild(m),p.appendChild(l.createElement("w:annotationRef")),f.appendChild(p);let x=l.createElement("w:r"),b=l.createElement("w:t");if(b.textContent=e,x.appendChild(b),f.appendChild(x),a.appendChild(f),this.commentsPart._element.appendChild(a),this.extendedPart){let v=this.extendedPart._element.ownerDocument.createElement("w15:commentEx");v.setAttribute("w15:paraId",c),s&&v.setAttribute("w15:paraIdParent",s),v.setAttribute("w15:done","0"),this.extendedPart._element.appendChild(v);}if(this.idsPart){let v=this.idsPart._element.ownerDocument.createElement("w16cid:commentId");v.setAttribute("w16cid:paraId",c),v.setAttribute("w16cid:durableId",this._generateDurableId()),this.idsPart._element.appendChild(v);}if(this.extensiblePart){let w=null;for(let v=0;v<this.idsPart._element.childNodes.length;v++){let N=this.idsPart._element.childNodes[v];if(N.nodeType===1&&N.getAttribute("w16cid:paraId")===c){w=N.getAttribute("w16cid:durableId");break}}if(w){let N=this.extensiblePart._element.ownerDocument.createElement("w16cex:commentExtensible");N.setAttribute("w16cex:durableId",w),N.setAttribute("w16cex:dateUtc",o),this.extensiblePart._element.appendChild(N);}}return i}deleteComment(t){if(!this.commentsPart)return;let e=null;for(let r of M(this.commentsPart._element,"w:comment"))if(r.getAttribute("w:id")===t){e=r;break}if(!e)return;let n=null;for(let r of M(e,"w:p")){let s=r.getAttribute("w14:paraId");if(s){n=s;break}}if(n){let r=[];if(this.extendedPart)for(let i=0;i<this.extendedPart._element.childNodes.length;i++){let o=this.extendedPart._element.childNodes[i];if(o.nodeType===1&&o.getAttribute("w15:paraIdParent")===n){let l=o.getAttribute("w15:paraId");if(l){for(let a of M(this.commentsPart._element,"w:comment"))for(let u of M(a,"w:p"))if(u.getAttribute("w14:paraId")===l){let c=a.getAttribute("w:id");c&&r.push(c);break}}}}for(let i of r)this.deleteComment(i);let s=null;if(this.idsPart){let i=[];for(let o=0;o<this.idsPart._element.childNodes.length;o++){let l=this.idsPart._element.childNodes[o];l.nodeType===1&&l.getAttribute("w16cid:paraId")===n&&(s=l.getAttribute("w16cid:durableId"),i.push(l));}i.forEach(o=>this.idsPart._element.removeChild(o));}if(this.extendedPart){let i=[];for(let o=0;o<this.extendedPart._element.childNodes.length;o++){let l=this.extendedPart._element.childNodes[o];l.nodeType===1&&l.getAttribute("w15:paraId")===n&&i.push(l);}i.forEach(o=>this.extendedPart._element.removeChild(o));}if(s&&this.extensiblePart){let i=[];for(let o=0;o<this.extensiblePart._element.childNodes.length;o++){let l=this.extensiblePart._element.childNodes[o];l.nodeType===1&&l.getAttribute("w16cex:durableId")===s&&i.push(l);}i.forEach(o=>this.extensiblePart._element.removeChild(o));}}e.parentNode&&e.parentNode.removeChild(e);}};function Pe(t){({part:t.mainDocumentPart,relateTo:g(()=>{},"relateTo")});let r={},s=t.parts.find(a=>a.contentType===Z.COMMENTS);if(!s)return r;let i={},o=M(s._element,"w:comment");for(let a of o){let u=a.getAttribute("w:id");if(!u)continue;let c=a.getAttribute("w:author")||"Unknown",d=a.getAttribute("w:date")||"",f=false,h=a.getAttribute("w15:done");(h==="1"||h==="true"||h==="on")&&(f=true);let _=a.getAttribute("w15:p")||null,p=M(a,"w:p");for(let x of p){let b=x.getAttribute("w14:paraId");b&&(i[b]=u);}let m=[];for(let x of p){let b=M(x,"w:t");for(let w of b)w.textContent&&m.push(w.textContent);m.push(`
9
- `);}let y=m.join("").trim();r[u]={author:c,text:y,date:d,resolved:f,parent_id:_};}let l=t.parts.find(a=>a.contentType===Z.EXTENDED);if(l){let a=l._element.childNodes;for(let u=0;u<a.length;u++){let c=a[u];if(c.nodeType!==1)continue;let d=c.getAttribute("w15:paraId"),f=c.getAttribute("w15:paraIdParent"),h=c.getAttribute("w15:done");if(d){let _=i[d];if(_&&r[_]){if(f){let p=i[f];p&&(r[_].parent_id=p);}(h==="1"||h==="true"||h==="on")&&(r[_].resolved=true);}}}}return r}g(Pe,"extract_comments_data");var Yt=500,He=200,Ws=["{++","++}","{--","--}","{==","==}","{>>","<<}"];function Mr(t){if(!t||!t.includes("{")&&!t.includes("}"))return t;for(let e of Ws)if(t.includes(e)){let n=e.startsWith("{")?"{ "+e.slice(1):e.slice(0,-1)+" }";t=t.split(e).join(n);}return t}g(Mr,"escape_critic_tokens");function Qn(t,e){return t.length<=e?t:t.slice(0,Math.max(1,e-3))+"..."}g(Qn,"clamp_text");function de(t,e){if(t==null||t.length<=e)return t;let n=Math.max(1,Math.floor(e*2/3)),r=Math.max(1,e-n),s=t.length-n-r;return `${t.slice(0,n)}\u2026 [${s.toLocaleString("en-US")} chars omitted] \u2026${t.slice(-r)}`}g(de,"truncate_middle");var zs={"\u201C":'"',"\u201D":'"',"\u2018":"'","\u2019":"'"},Ls=/[\u201c\u201d\u2018\u2019]/g;function Yn(t){return t&&t.replace(Ls,e=>zs[e])}g(Yn,"normalize_smart_quotes");function sn(t){return !!t&&/[\u201c\u201d\u2018\u2019]/.test(t)}g(sn,"has_smart_quotes");function Us(t,e){if(!t||!e||!sn(t))return e;let n=Yn(t),r=Yn(e);if(n===r)return t;let i=new Dr.diff_match_patch().diff_main(n,r),o=[],l=0,a=0;for(let[u,c]of i)u===0?(o.push(t.substr(l,c.length)),l+=c.length,a+=c.length):u===-1?l+=c.length:(o.push(e.substr(a,c.length)),a+=c.length);return o.join("")}g(Us,"restore_document_typography");function Hs(t,e,n){return !n||!t||!sn(t)||sn(e||"")?n:Us(t,n)}g(Hs,"restore_matched_typography");var yn=2e3,Te=class extends Error{static{g(this,"RegexTimeoutError");}pattern;constructor(t){super(`Regular expression exceeded the ${yn/1e3}s matching time budget (catastrophic backtracking). Simplify the pattern \u2014 nested quantifiers like (a+)+ are the usual cause \u2014 or use a literal target instead.`),this.name="RegexTimeoutError",this.pattern=t;}};function Rr(t){let e=false,n=false,r=[];for(let s=0;s<t.length;s++){let i=t[s];if(n){n=false;continue}if(i==="\\"){n=true;continue}if(e){i==="]"&&(e=false);continue}if(i==="["){e=true;continue}if(i==="("){r.push({hasInnerQuantifierOrPipe:false});continue}if(i===")"){if(r.length>0){let o=r.pop(),l=t.substring(s+1),a=l.match(/^(\*|\+|\{\d+\,\s*\}|\?)/),u=a?a[1]:"",c=u==="*"||u==="+"||/^\{\d+\,\s*\}/.test(l);if(c&&o.hasInnerQuantifierOrPipe)return true;r.length>0&&(o.hasInnerQuantifierOrPipe||c)&&(r[r.length-1].hasInnerQuantifierOrPipe=true);}continue}r.length>0&&(i==="|"||i==="*"||i==="+"||/^\{\d+\,\s*\}/.test(t.substring(s)))&&(r[r.length-1].hasInnerQuantifierOrPipe=true);}return false}g(Rr,"hasCatastrophicBacktrackingRisk");function qs(t,e,n=""){if(Rr(t))throw new Te(t);let r=n.includes("g")?n:n+"g",s=new RegExp(t,r),i=Date.now(),o=[],l;for(;(l=s.exec(e))!==null;){if(Date.now()-i>yn)throw new Te(t);o.push({start:l.index,end:l.index+l[0].length}),l.index===s.lastIndex&&s.lastIndex++;}return o}g(qs,"userFindAllMatches");function Js(t,e,n=""){if(Rr(t))throw new Te(t);let r=new RegExp(t,n.replace("g","")),s=Date.now(),i=r.exec(e);if(Date.now()-s>yn)throw new Te(t);return i?{start:i.index,end:i.index+i[0].length}:null}g(Js,"userSearch");var Xs="w:p",jr="w:r",vn="w:t",Gs="w:delText",Qs="w:tab",Ys="w:br",Vs="w:cr",bn="w:rPr",Zs="w:rPrChange",Ks="w:commentReference",eo="w:footnoteReference",to="w:endnoteReference",no="w:fldChar",ro="w:fldCharType",io="w:instrText",so="w:ins",oo="w:del",Ee="w:id",Vt="w:author",Zt="w:date",ao="w:commentRangeStart",lo="w:commentRangeEnd",co="w:hyperlink",uo="r:id",fo="w:fldSimple",ho="w:instr",po="w:bookmarkStart",_o="w:name",Br="w:sdt",mo="w:smartTag",Fr="w:sdtContent",Wr="w:b",go="w:i",le="w:val",zr="w:pPr",Lr="w:pStyle",Ur="w:outlineLvl",wo="w:numPr",yo="w:numId",vo="w:ilvl",on="w:drawing",an="w:object",ln="w:pict",bo="wp:docPr",xo="v:imagedata",No="o:title",ko="w:txbxContent",Eo="mc:AlternateContent",Ao="mc:Choice",Co="mc:Fallback",Vn=300;function Zn(t){let e=[];for(let r of M(t,ko))for(let s of M(r,vn))s.textContent&&e.push(s.textContent);let n=e.join(" ").split(/\s+/).filter(Boolean).join(" ");return n.length>Vn&&(n=n.slice(0,Vn).trimEnd()+"\u2026"),n}g(Zn,"_textbox_text");function*Kn(t){let e=t.tagName;if(e===on||e===an){let n=M(t,bo)[0]||null,r="",s="0";n&&(r=n.getAttribute("descr")||n.getAttribute("title")||"",s=n.getAttribute("id")||"0");let i=Zn(t);i&&(r=r?`Text box (${r}): ${i}`:`Text box: ${i}`),yield {type:"image",id:s,date:r};}else if(e===ln){let n=M(t,xo)[0]||null,r=n&&n.getAttribute(No)||"",s=Zn(t);s&&(r=r?`Text box (${r}): ${s}`:`Text box: ${s}`),(s||n)&&(yield {type:"image",id:"vml",date:r});}}g(Kn,"_graphic_marker_events");var Po=/Heading[ ]?([1-6])(?![0-9])/;function To(t){let e=t,n=new Set;for(;e&&!n.has(e);){if(n.add(e),e.package)return e.package;if(e.pkg)return e.pkg;if(e.part&&(e.part.package||e.part.pkg))return e.part.package||e.part.pkg;e=e._parent||e.part||null;}return null}g(To,"_resolve_package");function Qe(t){let e=t.package||t.pkg||(t.part?t.part.pkg:null);if(e&&e._adeu_style_cache)return e._adeu_style_cache;let n={},r=null,s={},i=e?.getPartByPath("word/styles.xml");if(!i){let u=[n,null];return e&&(e._adeu_style_cache=u),u}let o=M(i._element,"w:style");for(let u of o){let c=u.getAttribute("w:styleId");if(!c)continue;let d=u.getAttribute("w:type"),f=u.getAttribute("w:default")==="1"||u.getAttribute("w:default")==="true";d==="paragraph"&&f&&(r=c);let h=B(u,"w:name"),_=h?h.getAttribute("w:val"):c;_&&typeof _=="string"&&(_.toLowerCase().startsWith("heading")?_=_.replace(/^heading/i,"Heading"):_.toLowerCase()==="title"&&(_="Title"));let p=B(u,"w:basedOn"),m=p?p.getAttribute("w:val"):null,y=null,x=null,b=null,w=B(u,"w:pPr");if(w){let k=B(w,"w:outlineLvl");if(k){let A=k.getAttribute("w:val");A&&/^\d+$/.test(A)&&(y=parseInt(A,10));}let C=B(w,"w:numPr");if(C){let A=B(C,"w:numId");if(A){let D=A.getAttribute("w:val");D&&D!=="0"&&(x=D);}let T=B(C,"w:ilvl");if(T){let D=T.getAttribute("w:val");D&&/^\d+$/.test(D)&&(b=parseInt(D,10));}}}let v=null,N=B(u,"w:rPr");if(N){let k=B(N,"w:b");if(k){let C=k.getAttribute("w:val");v=C!=="0"&&C!=="false"&&C!=="off";}}s[c]={name:_,based_on:m,outline_level:y,bold:v,num_id:x,num_ilvl:b};}let l=g((u,c)=>{if(n[u])return n[u];if(c.has(u)||!s[u])return {name:u,outline_level:null,bold:false,num_id:null,num_ilvl:null};c.add(u);let d=s[u],f=d.based_on,h=d.outline_level,_=d.bold!==null?d.bold:false,p=d.num_id,m=d.num_ilvl;if(f){let x=l(f,c);h===null&&(h=x.outline_level),d.bold===null&&(_=x.bold),p===null&&(p=x.num_id??null),m===null&&(m=x.num_ilvl??null);}let y={name:d.name,outline_level:h,bold:_,num_id:p,num_ilvl:m};return n[u]=y,y},"resolve_style");for(let u in s)l(u,new Set);let a=[n,r];return e&&(e._adeu_style_cache=a),a}g(Qe,"_get_style_cache");function Io(t){let e=To(t);if(!e)return {};if(e._adeu_numbering_cache)return e._adeu_numbering_cache;let n={},r=null;try{let s=(e.parts||[]).find(i=>String(i.partname).endsWith("/numbering.xml"));s&&(r=s._element);}catch{r=null;}if(r){let s={};for(let i of M(r,"w:abstractNum")){let o=i.getAttribute("w:abstractNumId");if(o===null)continue;let l={};for(let a of M(i,"w:lvl")){let u=a.getAttribute("w:ilvl"),c=B(a,"w:numFmt");if(u!==null&&/^-?\d+$/.test(u)&&c){let d=c.getAttribute("w:val");d&&(l[parseInt(u,10)]=d);}}s[o]=l;}for(let i of M(r,"w:num")){let o=i.getAttribute("w:numId"),l=B(i,"w:abstractNumId");if(o===null||!l)continue;let a=l.getAttribute("w:val");a!==null&&s[a]!==void 0&&(n[o]=s[a]);}}return e._adeu_numbering_cache=n,n}g(Io,"_get_numbering_cache");function So(t,e,n){let r=null;if(e!=null){let s=Io(t)[e];if(s&&Object.keys(s).length>0&&(r=s[n]!==void 0?s[n]:null,r===null)){for(let i=n;i>=0;i--)if(s[i]!==void 0){r=s[i];break}}}return r!==null&&r!=="bullet"?"1. ":"* "}g(So,"get_list_marker");function Hr(t){if(!t)return null;let e=t.match(Po);return e?parseInt(e[1],10):null}g(Hr,"_detect_heading_level_from_name");function Ct(t,e,n){e||([e,n]=Qe(t._parent.part||t._parent));let r=B(t._element,zr);if(r){let l=B(r,Ur);if(l){let a=l.getAttribute(le);if(a&&/^\d+$/.test(a)){let u=parseInt(a,10);if(u>=0&&u<=8)return true}}}let s=n;if(r){let l=B(r,Lr);l&&(s=l.getAttribute(le)||n);}let i=s&&e?e[s]:null;if(i&&i.outline_level!==null&&i.outline_level>=0&&i.outline_level<=8)return true;let o=i?i.name:s;return o&&typeof o=="string"&&o.toLowerCase().startsWith("heading")&&(o=o.replace(/^heading/i,"Heading")),!!(o?.startsWith("Heading")||o==="Title"||o&&o!=="Normal"&&Hr(o)!==null)}g(Ct,"is_native_heading");function $e(t,e,n){e||([e,n]=Qe(t._parent.part||t._parent));let r=B(t._element,zr);if(r){let c=B(r,Ur);if(c){let d=c.getAttribute(le);if(d&&/^\d+$/.test(d)){let f=parseInt(d,10);if(f>=0&&f<=8)return "#".repeat(f+1)+" "}}}let s=n;if(r){let c=B(r,Lr);c&&(s=c.getAttribute(le)||n);}let i=s&&e?e[s]:null;if(i&&i.outline_level!==null&&i.outline_level>=0&&i.outline_level<=8)return "#".repeat(i.outline_level+1)+" ";let o=i?i.name:s;if(o&&typeof o=="string"&&o.toLowerCase().startsWith("heading")&&(o=o.replace(/^heading/i,"Heading")),o?.startsWith("Heading")){let c=o.replace("Heading","").trim();if(/^\d+$/.test(c))return "#".repeat(parseInt(c,10))+" "}if(o==="Title")return "# ";let l=null,a=null,u=false;if(r){let c=B(r,wo);if(c){let d=B(c,yo);if(d){let f=d.getAttribute(le);if(f==="0")u=true;else if(f){l=f;let h=B(c,vo);if(h){let _=h.getAttribute(le);_!==null&&/^\d+$/.test(_)&&(a=parseInt(_,10));}}}}}if(l===null&&!u&&i){let c=i.num_id;c&&(l=c,a===null&&(a=i.num_ilvl!==void 0?i.num_ilvl:null));}if(l!==null){let c=a!==null?a:0,d=So(t._parent?t._parent.part||t._parent:null,l,c);return " ".repeat(c)+d}if(o&&o!=="Normal"){let c=Hr(o);if(c!==null)return "#".repeat(c)+" "}if(!o||o==="Normal"){let c=false,d=t._element;for(;d;){if(d.tagName==="w:tc"){c=true;break}d=d.parentNode;}if(c)return "";let f=t.text.trim();if(f&&f.length<100&&f===f.toUpperCase()){let h=false;if(i?.bold)h=true;else {let _=M(t._element,jr);for(let p of _)if(M(p,vn).map(x=>x.textContent||"").join("").trim()){let x=B(p,bn);if(x){let b=B(x,Wr);b&&b.getAttribute(le)!=="0"&&b.getAttribute(le)!=="false"&&(h=true);}break}}if(h)return "## "}}return ""}g($e,"get_paragraph_prefix");function qr(t,e,n){let r=$e(t,e,n);if(!r)return false;let s=r.trimEnd();return s.length>0&&s==="#".repeat(s.length)}g(qr,"is_heading_paragraph");function Jr(t,e=null){let n="",r="",s=B(t._element,bn),i=false,o=false;if(s){let l=B(s,Wr);l&&l.getAttribute(le)!=="0"&&l.getAttribute(le)!=="false"&&(i=true);let a=B(s,go);a&&a.getAttribute(le)!=="0"&&a.getAttribute(le)!=="false"&&(o=true);}if(e===null){let l=t._parent;e=l instanceof ie?Ct(l):false;}return i&&!e&&(n+="**",r="**"+r),o&&(n+="_",r="_"+r),[n,r]}g(Jr,"get_run_style_markers");function Xr(t){let e=t.trim();if(!e)return ["","",t];let n=t.length-t.trimStart().length;return [t.substring(0,n),t.substring(n,n+e.length),t.substring(n+e.length)]}g(Xr,"split_boundary_whitespace");function Gr(t){let e=[],n=[],r=new Set;for(let[i,o]of t){let l=Object.entries(i),a=Object.entries(o);if(l.length===0&&a.length===0){n.length>0&&(e.push(n),n=[]);continue}let u=[];for(let[c,d]of l)r.has(c)||u.push([c,d&&d.author||"Unknown"]);for(let[c,d]of a)r.has(c)||u.push([c,d&&d.author||"Unknown"]);for(let[c,d]of u)r.add(c),n.length>0&&n[n.length-1][1]!==d&&(e.push(n),n=[]),n.push([c,d]);}n.length>0&&e.push(n);let s={};for(let i of e)if(!(i.length<2))for(let[o]of i)s[o]=i.filter(([l])=>l!==o).map(([l])=>`Chg:${l}`).join(", ");return s}g(Gr,"compute_change_pair_map");function $o(t,e,n){if(!e&&!n)return t;if(!t)return "";let r=g(i=>{let[o,l,a]=Xr(i);return l?`${o}${e}${l}${n}${a}`:i},"wrap");return t.includes(`
1
+ 'use strict';var n8nWorkflow=require('n8n-workflow'),path=require('path');var ds=Object.create;var _n=Object.defineProperty;var fs=Object.getOwnPropertyDescriptor;var hs=Object.getOwnPropertyNames;var ps=Object.getPrototypeOf,_s=Object.prototype.hasOwnProperty;var g=(t,e)=>_n(t,"name",{value:e,configurable:true});var gr=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var ms=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of hs(e))!_s.call(t,i)&&i!==n&&_n(t,i,{get:()=>e[i],enumerable:!(r=fs(e,i))||r.enumerable});return t};var mn=(t,e,n)=>(n=t!=null?ds(ps(t)):{},ms(_n(n,"default",{value:t,enumerable:true}),t));var yr=gr((ed,wr)=>{wr.exports={createRequire:g(function(){return function(){return {}}},"createRequire")};});var Tn=gr((id,et)=>{var F=g(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;},"diff_match_patch"),J=-1,Q=1,H=0;F.Diff=function(t,e){return [t,e]};F.prototype.diff_main=function(t,e,n,r){typeof r>"u"&&(this.Diff_Timeout<=0?r=Number.MAX_VALUE:r=new Date().getTime()+this.Diff_Timeout*1e3);var i=r;if(t==null||e==null)throw new Error("Null input. (diff_main)");if(t==e)return t?[new F.Diff(H,t)]:[];typeof n>"u"&&(n=true);var o=n,s=this.diff_commonPrefix(t,e),a=t.substring(0,s);t=t.substring(s),e=e.substring(s),s=this.diff_commonSuffix(t,e);var l=t.substring(t.length-s);t=t.substring(0,t.length-s),e=e.substring(0,e.length-s);var u=this.diff_compute_(t,e,o,i);return a&&u.unshift(new F.Diff(H,a)),l&&u.push(new F.Diff(H,l)),this.diff_cleanupMerge(u),u};F.prototype.diff_compute_=function(t,e,n,r){var i;if(!t)return [new F.Diff(Q,e)];if(!e)return [new F.Diff(J,t)];var o=t.length>e.length?t:e,s=t.length>e.length?e:t,a=o.indexOf(s);if(a!=-1)return i=[new F.Diff(Q,o.substring(0,a)),new F.Diff(H,s),new F.Diff(Q,o.substring(a+s.length))],t.length>e.length&&(i[0][0]=i[2][0]=J),i;if(s.length==1)return [new F.Diff(J,t),new F.Diff(Q,e)];var l=this.diff_halfMatch_(t,e);if(l){var u=l[0],c=l[1],d=l[2],f=l[3],h=l[4],_=this.diff_main(u,d,n,r),p=this.diff_main(c,f,n,r);return _.concat([new F.Diff(H,h)],p)}return n&&t.length>100&&e.length>100?this.diff_lineMode_(t,e,r):this.diff_bisect_(t,e,r)};F.prototype.diff_lineMode_=function(t,e,n){var r=this.diff_linesToChars_(t,e);t=r.chars1,e=r.chars2;var i=r.lineArray,o=this.diff_main(t,e,false,n);this.diff_charsToLines_(o,i),this.diff_cleanupSemantic(o),o.push(new F.Diff(H,""));for(var s=0,a=0,l=0,u="",c="";s<o.length;){switch(o[s][0]){case Q:l++,c+=o[s][1];break;case J:a++,u+=o[s][1];break;case H:if(a>=1&&l>=1){o.splice(s-a-l,a+l),s=s-a-l;for(var d=this.diff_main(u,c,false,n),f=d.length-1;f>=0;f--)o.splice(s,0,d[f]);s=s+d.length;}l=0,a=0,u="",c="";break}s++;}return o.pop(),o};F.prototype.diff_bisect_=function(t,e,n){for(var r=t.length,i=e.length,o=Math.ceil((r+i)/2),s=o,a=2*o,l=new Array(a),u=new Array(a),c=0;c<a;c++)l[c]=-1,u[c]=-1;l[s+1]=0,u[s+1]=0;for(var d=r-i,f=d%2!=0,h=0,_=0,p=0,m=0,w=0;w<o&&!(new Date().getTime()>n);w++){for(var v=-w+h;v<=w-_;v+=2){var b=s+v,y;v==-w||v!=w&&l[b-1]<l[b+1]?y=l[b+1]:y=l[b-1]+1;for(var x=y-v;y<r&&x<i&&t.charAt(y)==e.charAt(x);)y++,x++;if(l[b]=y,y>r)_+=2;else if(x>i)h+=2;else if(f){var k=s+d-v;if(k>=0&&k<a&&u[k]!=-1){var N=r-u[k];if(y>=N)return this.diff_bisectSplit_(t,e,y,x,n)}}}for(var P=-w+p;P<=w-m;P+=2){var k=s+P,N;P==-w||P!=w&&u[k-1]<u[k+1]?N=u[k+1]:N=u[k-1]+1;for(var A=N-P;N<r&&A<i&&t.charAt(r-N-1)==e.charAt(i-A-1);)N++,A++;if(u[k]=N,N>r)m+=2;else if(A>i)p+=2;else if(!f){var b=s+d-P;if(b>=0&&b<a&&l[b]!=-1){var y=l[b],x=s+y-b;if(N=r-N,y>=N)return this.diff_bisectSplit_(t,e,y,x,n)}}}}return [new F.Diff(J,t),new F.Diff(Q,e)]};F.prototype.diff_bisectSplit_=function(t,e,n,r,i){var o=t.substring(0,n),s=e.substring(0,r),a=t.substring(n),l=e.substring(r),u=this.diff_main(o,s,false,i),c=this.diff_main(a,l,false,i);return u.concat(c)};F.prototype.diff_linesToChars_=function(t,e){var n=[],r={};n[0]="";function i(l){for(var u="",c=0,d=-1,f=n.length;d<l.length-1;){d=l.indexOf(`
2
+ `,c),d==-1&&(d=l.length-1);var h=l.substring(c,d+1);(r.hasOwnProperty?r.hasOwnProperty(h):r[h]!==void 0)?u+=String.fromCharCode(r[h]):(f==o&&(h=l.substring(c),d=l.length),u+=String.fromCharCode(f),r[h]=f,n[f++]=h),c=d+1;}return u}g(i,"diff_linesToCharsMunge_");var o=4e4,s=i(t);o=65535;var a=i(e);return {chars1:s,chars2:a,lineArray:n}};F.prototype.diff_charsToLines_=function(t,e){for(var n=0;n<t.length;n++){for(var r=t[n][1],i=[],o=0;o<r.length;o++)i[o]=e[r.charCodeAt(o)];t[n][1]=i.join("");}};F.prototype.diff_commonPrefix=function(t,e){if(!t||!e||t.charAt(0)!=e.charAt(0))return 0;for(var n=0,r=Math.min(t.length,e.length),i=r,o=0;n<i;)t.substring(o,i)==e.substring(o,i)?(n=i,o=n):r=i,i=Math.floor((r-n)/2+n);return i};F.prototype.diff_commonSuffix=function(t,e){if(!t||!e||t.charAt(t.length-1)!=e.charAt(e.length-1))return 0;for(var n=0,r=Math.min(t.length,e.length),i=r,o=0;n<i;)t.substring(t.length-i,t.length-o)==e.substring(e.length-i,e.length-o)?(n=i,o=n):r=i,i=Math.floor((r-n)/2+n);return i};F.prototype.diff_commonOverlap_=function(t,e){var n=t.length,r=e.length;if(n==0||r==0)return 0;n>r?t=t.substring(n-r):n<r&&(e=e.substring(0,n));var i=Math.min(n,r);if(t==e)return i;for(var o=0,s=1;;){var a=t.substring(i-s),l=e.indexOf(a);if(l==-1)return o;s+=l,(l==0||t.substring(i-s)==e.substring(0,s))&&(o=s,s++);}};F.prototype.diff_halfMatch_=function(t,e){if(this.Diff_Timeout<=0)return null;var n=t.length>e.length?t:e,r=t.length>e.length?e:t;if(n.length<4||r.length*2<n.length)return null;var i=this;function o(_,p,m){for(var w=_.substring(m,m+Math.floor(_.length/4)),v=-1,b="",y,x,k,N;(v=p.indexOf(w,v+1))!=-1;){var P=i.diff_commonPrefix(_.substring(m),p.substring(v)),A=i.diff_commonSuffix(_.substring(0,m),p.substring(0,v));b.length<A+P&&(b=p.substring(v-A,v)+p.substring(v,v+P),y=_.substring(0,m-A),x=_.substring(m+P),k=p.substring(0,v-A),N=p.substring(v+P));}return b.length*2>=_.length?[y,x,k,N,b]:null}g(o,"diff_halfMatchI_");var s=o(n,r,Math.ceil(n.length/4)),a=o(n,r,Math.ceil(n.length/2)),l;if(!s&&!a)return null;a?s?l=s[4].length>a[4].length?s:a:l=a:l=s;var u,c,d,f;t.length>e.length?(u=l[0],c=l[1],d=l[2],f=l[3]):(d=l[0],f=l[1],u=l[2],c=l[3]);var h=l[4];return [u,c,d,f,h]};F.prototype.diff_cleanupSemantic=function(t){for(var e=false,n=[],r=0,i=null,o=0,s=0,a=0,l=0,u=0;o<t.length;)t[o][0]==H?(n[r++]=o,s=l,a=u,l=0,u=0,i=t[o][1]):(t[o][0]==Q?l+=t[o][1].length:u+=t[o][1].length,i&&i.length<=Math.max(s,a)&&i.length<=Math.max(l,u)&&(t.splice(n[r-1],0,new F.Diff(J,i)),t[n[r-1]+1][0]=Q,r--,r--,o=r>0?n[r-1]:-1,s=0,a=0,l=0,u=0,i=null,e=true)),o++;for(e&&this.diff_cleanupMerge(t),this.diff_cleanupSemanticLossless(t),o=1;o<t.length;){if(t[o-1][0]==J&&t[o][0]==Q){var c=t[o-1][1],d=t[o][1],f=this.diff_commonOverlap_(c,d),h=this.diff_commonOverlap_(d,c);f>=h?(f>=c.length/2||f>=d.length/2)&&(t.splice(o,0,new F.Diff(H,d.substring(0,f))),t[o-1][1]=c.substring(0,c.length-f),t[o+1][1]=d.substring(f),o++):(h>=c.length/2||h>=d.length/2)&&(t.splice(o,0,new F.Diff(H,c.substring(0,h))),t[o-1][0]=Q,t[o-1][1]=d.substring(0,d.length-h),t[o+1][0]=J,t[o+1][1]=c.substring(h),o++),o++;}o++;}};F.prototype.diff_cleanupSemanticLossless=function(t){function e(h,_){if(!h||!_)return 6;var p=h.charAt(h.length-1),m=_.charAt(0),w=p.match(F.nonAlphaNumericRegex_),v=m.match(F.nonAlphaNumericRegex_),b=w&&p.match(F.whitespaceRegex_),y=v&&m.match(F.whitespaceRegex_),x=b&&p.match(F.linebreakRegex_),k=y&&m.match(F.linebreakRegex_),N=x&&h.match(F.blanklineEndRegex_),P=k&&_.match(F.blanklineStartRegex_);return N||P?5:x||k?4:w&&!b&&y?3:b||y?2:w||v?1:0}g(e,"diff_cleanupSemanticScore_");for(var n=1;n<t.length-1;){if(t[n-1][0]==H&&t[n+1][0]==H){var r=t[n-1][1],i=t[n][1],o=t[n+1][1],s=this.diff_commonSuffix(r,i);if(s){var a=i.substring(i.length-s);r=r.substring(0,r.length-s),i=a+i.substring(0,i.length-s),o=a+o;}for(var l=r,u=i,c=o,d=e(r,i)+e(i,o);i.charAt(0)===o.charAt(0);){r+=i.charAt(0),i=i.substring(1)+o.charAt(0),o=o.substring(1);var f=e(r,i)+e(i,o);f>=d&&(d=f,l=r,u=i,c=o);}t[n-1][1]!=l&&(l?t[n-1][1]=l:(t.splice(n-1,1),n--),t[n][1]=u,c?t[n+1][1]=c:(t.splice(n+1,1),n--));}n++;}};F.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;F.whitespaceRegex_=/\s/;F.linebreakRegex_=/[\r\n]/;F.blanklineEndRegex_=/\n\r?\n$/;F.blanklineStartRegex_=/^\r?\n\r?\n/;F.prototype.diff_cleanupEfficiency=function(t){for(var e=false,n=[],r=0,i=null,o=0,s=false,a=false,l=false,u=false;o<t.length;)t[o][0]==H?(t[o][1].length<this.Diff_EditCost&&(l||u)?(n[r++]=o,s=l,a=u,i=t[o][1]):(r=0,i=null),l=u=false):(t[o][0]==J?u=true:l=true,i&&(s&&a&&l&&u||i.length<this.Diff_EditCost/2&&s+a+l+u==3)&&(t.splice(n[r-1],0,new F.Diff(J,i)),t[n[r-1]+1][0]=Q,r--,i=null,s&&a?(l=u=true,r=0):(r--,o=r>0?n[r-1]:-1,l=u=false),e=true)),o++;e&&this.diff_cleanupMerge(t);};F.prototype.diff_cleanupMerge=function(t){t.push(new F.Diff(H,""));for(var e=0,n=0,r=0,i="",o="",s;e<t.length;)switch(t[e][0]){case Q:r++,o+=t[e][1],e++;break;case J:n++,i+=t[e][1],e++;break;case H:n+r>1?(n!==0&&r!==0&&(s=this.diff_commonPrefix(o,i),s!==0&&(e-n-r>0&&t[e-n-r-1][0]==H?t[e-n-r-1][1]+=o.substring(0,s):(t.splice(0,0,new F.Diff(H,o.substring(0,s))),e++),o=o.substring(s),i=i.substring(s)),s=this.diff_commonSuffix(o,i),s!==0&&(t[e][1]=o.substring(o.length-s)+t[e][1],o=o.substring(0,o.length-s),i=i.substring(0,i.length-s))),e-=n+r,t.splice(e,n+r),i.length&&(t.splice(e,0,new F.Diff(J,i)),e++),o.length&&(t.splice(e,0,new F.Diff(Q,o)),e++),e++):e!==0&&t[e-1][0]==H?(t[e-1][1]+=t[e][1],t.splice(e,1)):e++,r=0,n=0,i="",o="";break}t[t.length-1][1]===""&&t.pop();var a=false;for(e=1;e<t.length-1;)t[e-1][0]==H&&t[e+1][0]==H&&(t[e][1].substring(t[e][1].length-t[e-1][1].length)==t[e-1][1]?(t[e][1]=t[e-1][1]+t[e][1].substring(0,t[e][1].length-t[e-1][1].length),t[e+1][1]=t[e-1][1]+t[e+1][1],t.splice(e-1,1),a=true):t[e][1].substring(0,t[e+1][1].length)==t[e+1][1]&&(t[e-1][1]+=t[e+1][1],t[e][1]=t[e][1].substring(t[e+1][1].length)+t[e+1][1],t.splice(e+1,1),a=true)),e++;a&&this.diff_cleanupMerge(t);};F.prototype.diff_xIndex=function(t,e){var n=0,r=0,i=0,o=0,s;for(s=0;s<t.length&&(t[s][0]!==Q&&(n+=t[s][1].length),t[s][0]!==J&&(r+=t[s][1].length),!(n>e));s++)i=n,o=r;return t.length!=s&&t[s][0]===J?o:o+(e-i)};F.prototype.diff_prettyHtml=function(t){for(var e=[],n=/&/g,r=/</g,i=/>/g,o=/\n/g,s=0;s<t.length;s++){var a=t[s][0],l=t[s][1],u=l.replace(n,"&amp;").replace(r,"&lt;").replace(i,"&gt;").replace(o,"&para;<br>");switch(a){case Q:e[s]='<ins style="background:#e6ffe6;">'+u+"</ins>";break;case J:e[s]='<del style="background:#ffe6e6;">'+u+"</del>";break;case H:e[s]="<span>"+u+"</span>";break}}return e.join("")};F.prototype.diff_text1=function(t){for(var e=[],n=0;n<t.length;n++)t[n][0]!==Q&&(e[n]=t[n][1]);return e.join("")};F.prototype.diff_text2=function(t){for(var e=[],n=0;n<t.length;n++)t[n][0]!==J&&(e[n]=t[n][1]);return e.join("")};F.prototype.diff_levenshtein=function(t){for(var e=0,n=0,r=0,i=0;i<t.length;i++){var o=t[i][0],s=t[i][1];switch(o){case Q:n+=s.length;break;case J:r+=s.length;break;case H:e+=Math.max(n,r),n=0,r=0;break}}return e+=Math.max(n,r),e};F.prototype.diff_toDelta=function(t){for(var e=[],n=0;n<t.length;n++)switch(t[n][0]){case Q:e[n]="+"+encodeURI(t[n][1]);break;case J:e[n]="-"+t[n][1].length;break;case H:e[n]="="+t[n][1].length;break}return e.join(" ").replace(/%20/g," ")};F.prototype.diff_fromDelta=function(t,e){for(var n=[],r=0,i=0,o=e.split(/\t/g),s=0;s<o.length;s++){var a=o[s].substring(1);switch(o[s].charAt(0)){case "+":try{n[r++]=new F.Diff(Q,decodeURI(a));}catch{throw new Error("Illegal escape in diff_fromDelta: "+a)}break;case "-":case "=":var l=parseInt(a,10);if(isNaN(l)||l<0)throw new Error("Invalid number in diff_fromDelta: "+a);var u=t.substring(i,i+=l);o[s].charAt(0)=="="?n[r++]=new F.Diff(H,u):n[r++]=new F.Diff(J,u);break;default:if(o[s])throw new Error("Invalid diff operation in diff_fromDelta: "+o[s])}}if(i!=t.length)throw new Error("Delta length ("+i+") does not equal source text length ("+t.length+").");return n};F.prototype.match_main=function(t,e,n){if(t==null||e==null||n==null)throw new Error("Null input. (match_main)");return n=Math.max(0,Math.min(n,t.length)),t==e?0:t.length?t.substring(n,n+e.length)==e?n:this.match_bitap_(t,e,n):-1};F.prototype.match_bitap_=function(t,e,n){if(e.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");var r=this.match_alphabet_(e),i=this;function o(y,x){var k=y/e.length,N=Math.abs(n-x);return i.Match_Distance?k+N/i.Match_Distance:N?1:k}g(o,"match_bitapScore_");var s=this.Match_Threshold,a=t.indexOf(e,n);a!=-1&&(s=Math.min(o(0,a),s),a=t.lastIndexOf(e,n+e.length),a!=-1&&(s=Math.min(o(0,a),s)));var l=1<<e.length-1;a=-1;for(var u,c,d=e.length+t.length,f,h=0;h<e.length;h++){for(u=0,c=d;u<c;)o(h,n+c)<=s?u=c:d=c,c=Math.floor((d-u)/2+u);d=c;var _=Math.max(1,n-c+1),p=Math.min(n+c,t.length)+e.length,m=Array(p+2);m[p+1]=(1<<h)-1;for(var w=p;w>=_;w--){var v=r[t.charAt(w-1)];if(h===0?m[w]=(m[w+1]<<1|1)&v:m[w]=(m[w+1]<<1|1)&v|((f[w+1]|f[w])<<1|1)|f[w+1],m[w]&l){var b=o(h,w-1);if(b<=s)if(s=b,a=w-1,a>n)_=Math.max(1,2*n-a);else break}}if(o(h+1,n)>s)break;f=m;}return a};F.prototype.match_alphabet_=function(t){for(var e={},n=0;n<t.length;n++)e[t.charAt(n)]=0;for(var n=0;n<t.length;n++)e[t.charAt(n)]|=1<<t.length-n-1;return e};F.prototype.patch_addContext_=function(t,e){if(e.length!=0){if(t.start2===null)throw Error("patch not initialized");for(var n=e.substring(t.start2,t.start2+t.length1),r=0;e.indexOf(n)!=e.lastIndexOf(n)&&n.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)r+=this.Patch_Margin,n=e.substring(t.start2-r,t.start2+t.length1+r);r+=this.Patch_Margin;var i=e.substring(t.start2-r,t.start2);i&&t.diffs.unshift(new F.Diff(H,i));var o=e.substring(t.start2+t.length1,t.start2+t.length1+r);o&&t.diffs.push(new F.Diff(H,o)),t.start1-=i.length,t.start2-=i.length,t.length1+=i.length+o.length,t.length2+=i.length+o.length;}};F.prototype.patch_make=function(t,e,n){var r,i;if(typeof t=="string"&&typeof e=="string"&&typeof n>"u")r=t,i=this.diff_main(r,e,true),i.length>2&&(this.diff_cleanupSemantic(i),this.diff_cleanupEfficiency(i));else if(t&&typeof t=="object"&&typeof e>"u"&&typeof n>"u")i=t,r=this.diff_text1(i);else if(typeof t=="string"&&e&&typeof e=="object"&&typeof n>"u")r=t,i=e;else if(typeof t=="string"&&typeof e=="string"&&n&&typeof n=="object")r=t,i=n;else throw new Error("Unknown call format to patch_make.");if(i.length===0)return [];for(var o=[],s=new F.patch_obj,a=0,l=0,u=0,c=r,d=r,f=0;f<i.length;f++){var h=i[f][0],_=i[f][1];switch(!a&&h!==H&&(s.start1=l,s.start2=u),h){case Q:s.diffs[a++]=i[f],s.length2+=_.length,d=d.substring(0,u)+_+d.substring(u);break;case J:s.length1+=_.length,s.diffs[a++]=i[f],d=d.substring(0,u)+d.substring(u+_.length);break;case H:_.length<=2*this.Patch_Margin&&a&&i.length!=f+1?(s.diffs[a++]=i[f],s.length1+=_.length,s.length2+=_.length):_.length>=2*this.Patch_Margin&&a&&(this.patch_addContext_(s,c),o.push(s),s=new F.patch_obj,a=0,c=d,l=u);break}h!==Q&&(l+=_.length),h!==J&&(u+=_.length);}return a&&(this.patch_addContext_(s,c),o.push(s)),o};F.prototype.patch_deepCopy=function(t){for(var e=[],n=0;n<t.length;n++){var r=t[n],i=new F.patch_obj;i.diffs=[];for(var o=0;o<r.diffs.length;o++)i.diffs[o]=new F.Diff(r.diffs[o][0],r.diffs[o][1]);i.start1=r.start1,i.start2=r.start2,i.length1=r.length1,i.length2=r.length2,e[n]=i;}return e};F.prototype.patch_apply=function(t,e){if(t.length==0)return [e,[]];t=this.patch_deepCopy(t);var n=this.patch_addPadding(t);e=n+e+n,this.patch_splitMax(t);for(var r=0,i=[],o=0;o<t.length;o++){var s=t[o].start2+r,a=this.diff_text1(t[o].diffs),l,u=-1;if(a.length>this.Match_MaxBits?(l=this.match_main(e,a.substring(0,this.Match_MaxBits),s),l!=-1&&(u=this.match_main(e,a.substring(a.length-this.Match_MaxBits),s+a.length-this.Match_MaxBits),(u==-1||l>=u)&&(l=-1))):l=this.match_main(e,a,s),l==-1)i[o]=false,r-=t[o].length2-t[o].length1;else {i[o]=true,r=l-s;var c;if(u==-1?c=e.substring(l,l+a.length):c=e.substring(l,u+this.Match_MaxBits),a==c)e=e.substring(0,l)+this.diff_text2(t[o].diffs)+e.substring(l+a.length);else {var d=this.diff_main(a,c,false);if(a.length>this.Match_MaxBits&&this.diff_levenshtein(d)/a.length>this.Patch_DeleteThreshold)i[o]=false;else {this.diff_cleanupSemanticLossless(d);for(var f=0,h,_=0;_<t[o].diffs.length;_++){var p=t[o].diffs[_];p[0]!==H&&(h=this.diff_xIndex(d,f)),p[0]===Q?e=e.substring(0,l+h)+p[1]+e.substring(l+h):p[0]===J&&(e=e.substring(0,l+h)+e.substring(l+this.diff_xIndex(d,f+p[1].length))),p[0]!==J&&(f+=p[1].length);}}}}}return e=e.substring(n.length,e.length-n.length),[e,i]};F.prototype.patch_addPadding=function(t){for(var e=this.Patch_Margin,n="",r=1;r<=e;r++)n+=String.fromCharCode(r);for(var r=0;r<t.length;r++)t[r].start1+=e,t[r].start2+=e;var i=t[0],o=i.diffs;if(o.length==0||o[0][0]!=H)o.unshift(new F.Diff(H,n)),i.start1-=e,i.start2-=e,i.length1+=e,i.length2+=e;else if(e>o[0][1].length){var s=e-o[0][1].length;o[0][1]=n.substring(o[0][1].length)+o[0][1],i.start1-=s,i.start2-=s,i.length1+=s,i.length2+=s;}if(i=t[t.length-1],o=i.diffs,o.length==0||o[o.length-1][0]!=H)o.push(new F.Diff(H,n)),i.length1+=e,i.length2+=e;else if(e>o[o.length-1][1].length){var s=e-o[o.length-1][1].length;o[o.length-1][1]+=n.substring(0,s),i.length1+=s,i.length2+=s;}return n};F.prototype.patch_splitMax=function(t){for(var e=this.Match_MaxBits,n=0;n<t.length;n++)if(!(t[n].length1<=e)){var r=t[n];t.splice(n--,1);for(var i=r.start1,o=r.start2,s="";r.diffs.length!==0;){var a=new F.patch_obj,l=true;for(a.start1=i-s.length,a.start2=o-s.length,s!==""&&(a.length1=a.length2=s.length,a.diffs.push(new F.Diff(H,s)));r.diffs.length!==0&&a.length1<e-this.Patch_Margin;){var u=r.diffs[0][0],c=r.diffs[0][1];u===Q?(a.length2+=c.length,o+=c.length,a.diffs.push(r.diffs.shift()),l=false):u===J&&a.diffs.length==1&&a.diffs[0][0]==H&&c.length>2*e?(a.length1+=c.length,i+=c.length,l=false,a.diffs.push(new F.Diff(u,c)),r.diffs.shift()):(c=c.substring(0,e-a.length1-this.Patch_Margin),a.length1+=c.length,i+=c.length,u===H?(a.length2+=c.length,o+=c.length):l=false,a.diffs.push(new F.Diff(u,c)),c==r.diffs[0][1]?r.diffs.shift():r.diffs[0][1]=r.diffs[0][1].substring(c.length));}s=this.diff_text2(a.diffs),s=s.substring(s.length-this.Patch_Margin);var d=this.diff_text1(r.diffs).substring(0,this.Patch_Margin);d!==""&&(a.length1+=d.length,a.length2+=d.length,a.diffs.length!==0&&a.diffs[a.diffs.length-1][0]===H?a.diffs[a.diffs.length-1][1]+=d:a.diffs.push(new F.Diff(H,d))),l||t.splice(++n,0,a);}}};F.prototype.patch_toText=function(t){for(var e=[],n=0;n<t.length;n++)e[n]=t[n];return e.join("")};F.prototype.patch_fromText=function(t){var e=[];if(!t)return e;for(var n=t.split(`
3
+ `),r=0,i=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;r<n.length;){var o=n[r].match(i);if(!o)throw new Error("Invalid patch string: "+n[r]);var s=new F.patch_obj;for(e.push(s),s.start1=parseInt(o[1],10),o[2]===""?(s.start1--,s.length1=1):o[2]=="0"?s.length1=0:(s.start1--,s.length1=parseInt(o[2],10)),s.start2=parseInt(o[3],10),o[4]===""?(s.start2--,s.length2=1):o[4]=="0"?s.length2=0:(s.start2--,s.length2=parseInt(o[4],10)),r++;r<n.length;){var a=n[r].charAt(0);try{var l=decodeURI(n[r].substring(1));}catch{throw new Error("Illegal escape in patch_fromText: "+l)}if(a=="-")s.diffs.push(new F.Diff(J,l));else if(a=="+")s.diffs.push(new F.Diff(Q,l));else if(a==" ")s.diffs.push(new F.Diff(H,l));else {if(a=="@")break;if(a!=="")throw new Error('Invalid patch mode "'+a+'" in: '+l)}r++;}}return e};F.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0;};F.patch_obj.prototype.toString=function(){var t,e;this.length1===0?t=this.start1+",0":this.length1==1?t=this.start1+1:t=this.start1+1+","+this.length1,this.length2===0?e=this.start2+",0":this.length2==1?e=this.start2+1:e=this.start2+1+","+this.length2;for(var n=["@@ -"+t+" +"+e+` @@
4
+ `],r,i=0;i<this.diffs.length;i++){switch(this.diffs[i][0]){case Q:r="+";break;case J:r="-";break;case H:r=" ";break}n[i+1]=r+encodeURI(this.diffs[i][1])+`
5
+ `;}return n.join("").replace(/%20/g," ")};et.exports=F;et.exports.diff_match_patch=F;et.exports.DIFF_DELETE=J;et.exports.DIFF_INSERT=Q;et.exports.DIFF_EQUAL=H;});var Er=mn(yr());var gs=(0, Er.createRequire)("/"),Ze,ws,ys;try{Ze=gs("worker_threads"),ws=Ze.Worker,ys=Ze.isMarkedAsUntransferable;}catch{}var V=Uint8Array,oe=Uint16Array,Cn=Int32Array,Ot=new V([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]),Dt=new V([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]),bn=new V([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ar=g(function(t,e){for(var n=new oe(31),r=0;r<31;++r)n[r]=e+=1<<t[r-1];for(var i=new Cn(n[30]),r=1;r<30;++r)for(var o=n[r];o<n[r+1];++o)i[o]=o-n[r]<<5|r;return {b:n,r:i}},"freb"),Ze=Ar(Ot,2),Cr=Ze.b,xn=Ze.r;Cr[28]=258,xn[258]=28;var Pr=Ar(Dt,0),vs=Pr.b,vr=Pr.r,Nn=new oe(32768);for(G=0;G<32768;++G)xe=(G&43690)>>1|(G&21845)<<1,xe=(xe&52428)>>2|(xe&13107)<<2,xe=(xe&61680)>>4|(xe&3855)<<4,Nn[G]=((xe&65280)>>8|(xe&255)<<8)>>1;var xe,G,ge=g((function(t,e,n){for(var r=t.length,i=0,o=new oe(e);i<r;++i)t[i]&&++o[t[i]-1];var s=new oe(e);for(i=1;i<e;++i)s[i]=s[i-1]+o[i-1]<<1;var a;if(n){a=new oe(1<<e);var l=15-e;for(i=0;i<r;++i)if(t[i])for(var u=i<<4|t[i],c=e-t[i],d=s[t[i]-1]++<<c,f=d|(1<<c)-1;d<=f;++d)a[Nn[d]>>l]=u;}else for(a=new oe(r),i=0;i<r;++i)t[i]&&(a[i]=Nn[s[t[i]-1]++]>>15-t[i]);return a}),"hMap"),Te=new V(288);for(G=0;G<144;++G)Te[G]=8;var G;for(G=144;G<256;++G)Te[G]=9;var G;for(G=256;G<280;++G)Te[G]=7;var G;for(G=280;G<288;++G)Te[G]=8;var G,gt=new V(32);for(G=0;G<32;++G)gt[G]=5;var G,bs=ge(Te,9,0),xs=ge(Te,9,1),Ns=ge(gt,5,0),ks=ge(gt,5,1),gn=g(function(t){for(var e=t[0],n=1;n<t.length;++n)t[n]>e&&(e=t[n]);return e},"max"),ue=g(function(t,e,n){var r=e/8|0;return (t[r]|t[r+1]<<8)>>(e&7)&n},"bits"),wn=g(function(t,e){var n=e/8|0;return (t[n]|t[n+1]<<8|t[n+2]<<16)>>(e&7)},"bits16"),Pn=g(function(t){return (t+7)/8|0},"shft"),wt=g(function(t,e,n){return (e==null||e<0)&&(e=0),(n==null||n>t.length)&&(n=t.length),new V(t.subarray(e,n))},"slc");var Es=["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"],re=g(function(t,e,n){var r=new Error(e||Es[t]);if(r.code=t,Error.captureStackTrace&&Error.captureStackTrace(r,re),!n)throw r;return r},"err"),As=g(function(t,e,n,r){var i=t.length,o=r?r.length:0;if(!i||e.f&&!e.l)return n||new V(0);var s=!n,a=s||e.i!=2,l=e.i;s&&(n=new V(i*3));var u=g(function(ht){var pt=n.length;if(ht>pt){var Ve=new V(Math.max(pt*2,ht));Ve.set(n),n=Ve;}},"cbuf"),c=e.f||0,d=e.p||0,f=e.b||0,h=e.l,_=e.d,p=e.m,m=e.n,w=i*8;do{if(!h){c=ue(t,d,1);var v=ue(t,d+1,3);if(d+=3,v)if(v==1)h=xs,_=ks,p=9,m=5;else if(v==2){var k=ue(t,d,31)+257,N=ue(t,d+10,15)+4,P=k+ue(t,d+5,31)+1;d+=14;for(var A=new V(P),C=new V(19),T=0;T<N;++T)C[bn[T]]=ue(t,d+T*3,7);d+=N*3;for(var M=gn(C),j=(1<<M)-1,B=ge(C,M,1),T=0;T<P;){var $=B[ue(t,d,j)];d+=$&15;var b=$>>4;if(b<16)A[T++]=b;else {var I=0,E=0;for(b==16?(E=3+ue(t,d,3),d+=2,I=A[T-1]):b==17?(E=3+ue(t,d,7),d+=3):b==18&&(E=11+ue(t,d,127),d+=7);E--;)A[T++]=I;}}var S=A.subarray(0,k),D=A.subarray(k);p=gn(S),m=gn(D),h=ge(S,p,1),_=ge(D,m,1);}else re(1);else {var b=Pn(d)+4,y=t[b-4]|t[b-3]<<8,x=b+y;if(x>i){l&&re(0);break}a&&u(f+y),n.set(t.subarray(b,x),f),e.b=f+=y,e.p=d=x*8,e.f=c;continue}if(d>w){l&&re(0);break}}a&&u(f+131072);for(var U=(1<<p)-1,z=(1<<m)-1,W=d;;W=d){var I=h[wn(t,d)&U],L=I>>4;if(d+=I&15,d>w){l&&re(0);break}if(I||re(2),L<256)n[f++]=L;else if(L==256){W=d,h=null;break}else {var X=L-254;if(L>264){var T=L-257,q=Ot[T];X=ue(t,d,(1<<q)-1)+Cr[T],d+=q;}var Y=_[wn(t,d)&z],_e=Y>>4;Y||re(3),d+=Y&15;var D=vs[_e];if(_e>3){var q=Dt[_e];D+=wn(t,d)&(1<<q)-1,d+=q;}if(d>w){l&&re(0);break}a&&u(f+131072);var be=f+X;if(f<D){var $t=o-D,St=Math.min(D,be);for($t+f<0&&re(3);f<St;++f)n[f]=r[$t+f];}for(;f<be;++f)n[f]=n[f-D];}}e.l=h,e.p=W,e.b=f,e.f=c,h&&(c=1,e.m=p,e.d=_,e.n=m);}while(!c);return f!=n.length&&s?wt(n,0,f):n.subarray(0,f)},"inflt"),Ne=g(function(t,e,n){n<<=e&7;var r=e/8|0;t[r]|=n,t[r+1]|=n>>8;},"wbits"),_t=g(function(t,e,n){n<<=e&7;var r=e/8|0;t[r]|=n,t[r+1]|=n>>8,t[r+2]|=n>>16;},"wbits16"),yn=g(function(t,e){for(var n=[],r=0;r<t.length;++r)t[r]&&n.push({s:r,f:t[r]});var i=n.length,o=n.slice();if(!i)return {t:$r,l:0};if(i==1){var s=new V(n[0].s+1);return s[n[0].s]=1,{t:s,l:1}}n.sort(function(x,k){return x.f-k.f}),n.push({s:-1,f:25001});var a=n[0],l=n[1],u=0,c=1,d=2;for(n[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=i-1;)a=n[n[u].f<n[d].f?u++:d++],l=n[u!=c&&n[u].f<n[d].f?u++:d++],n[c++]={s:-1,f:a.f+l.f,l:a,r:l};for(var f=o[0].s,r=1;r<i;++r)o[r].s>f&&(f=o[r].s);var h=new oe(f+1),_=kn(n[c-1],h,0);if(_>e){var r=0,p=0,m=_-e,w=1<<m;for(o.sort(function(k,N){return h[N.s]-h[k.s]||k.f-N.f});r<i;++r){var v=o[r].s;if(h[v]>e)p+=w-(1<<_-h[v]),h[v]=e;else break}for(p>>=m;p>0;){var b=o[r].s;h[b]<e?p-=1<<e-h[b]++-1:++r;}for(;r>=0&&p;--r){var y=o[r].s;h[y]==e&&(--h[y],++p);}_=e;}return {t:new V(h),l:_}},"hTree"),kn=g(function(t,e,n){return t.s==-1?Math.max(kn(t.l,e,n+1),kn(t.r,e,n+1)):e[t.s]=n},"ln"),br=g(function(t){for(var e=t.length;e&&!t[--e];);for(var n=new oe(++e),r=0,i=t[0],o=1,s=g(function(l){n[r++]=l;},"w"),a=1;a<=e;++a)if(t[a]==i&&a!=e)++o;else {if(!i&&o>2){for(;o>138;o-=138)s(32754);o>2&&(s(o>10?o-11<<5|28690:o-3<<5|12305),o=0);}else if(o>3){for(s(i),--o;o>6;o-=6)s(8304);o>2&&(s(o-3<<5|8208),o=0);}for(;o--;)s(i);o=1,i=t[a];}return {c:n.subarray(0,r),n:e}},"lc"),mt=g(function(t,e){for(var n=0,r=0;r<e.length;++r)n+=t[r]*e[r];return n},"clen"),Tr=g(function(t,e,n){var r=n.length,i=Pn(e+2);t[i]=r&255,t[i+1]=r>>8,t[i+2]=t[i]^255,t[i+3]=t[i+1]^255;for(var o=0;o<r;++o)t[i+o+4]=n[o];return (i+4+r)*8},"wfblk"),xr=g(function(t,e,n,r,i,o,s,a,l,u,c){Ne(e,c++,n),++i[256];for(var d=yn(i,15),f=d.t,h=d.l,_=yn(o,15),p=_.t,m=_.l,w=br(f),v=w.c,b=w.n,y=br(p),x=y.c,k=y.n,N=new oe(19),P=0;P<v.length;++P)++N[v[P]&31];for(var P=0;P<x.length;++P)++N[x[P]&31];for(var A=yn(N,7),C=A.t,T=A.l,M=19;M>4&&!C[bn[M-1]];--M);var j=u+5<<3,B=mt(i,Te)+mt(o,gt)+s,$=mt(i,f)+mt(o,p)+s+14+3*M+mt(N,C)+2*N[16]+3*N[17]+7*N[18];if(l>=0&&j<=B&&j<=$)return Tr(e,c,t.subarray(l,l+u));var I,E,S,D;if(Ne(e,c,1+($<B)),c+=2,$<B){I=ge(f,h,0),E=f,S=ge(p,m,0),D=p;var U=ge(C,T,0);Ne(e,c,b-257),Ne(e,c+5,k-1),Ne(e,c+10,M-4),c+=14;for(var P=0;P<M;++P)Ne(e,c+3*P,C[bn[P]]);c+=3*M;for(var z=[v,x],W=0;W<2;++W)for(var L=z[W],P=0;P<L.length;++P){var X=L[P]&31;Ne(e,c,U[X]),c+=C[X],X>15&&(Ne(e,c,L[P]>>5&127),c+=L[P]>>12);}}else I=bs,E=Te,S=Ns,D=gt;for(var P=0;P<a;++P){var q=r[P];if(q>255){var X=q>>18&31;_t(e,c,I[X+257]),c+=E[X+257],X>7&&(Ne(e,c,q>>23&31),c+=Ot[X]);var Y=q&31;_t(e,c,S[Y]),c+=D[Y],Y>3&&(_t(e,c,q>>5&8191),c+=Dt[Y]);}else _t(e,c,I[q]),c+=E[q];}return _t(e,c,I[256]),c+E[256]},"wblk"),Cs=new Cn([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),$r=new V(0),Ps=g(function(t,e,n,r,i,o){var s=o.z||t.length,a=new V(r+s+5*(1+Math.ceil(s/7e3))+i),l=a.subarray(r,a.length-i),u=o.l,c=(o.r||0)&7;if(e){c&&(l[0]=o.r>>3);for(var d=Cs[e-1],f=d>>13,h=d&8191,_=(1<<n)-1,p=o.p||new oe(32768),m=o.h||new oe(_+1),w=Math.ceil(n/3),v=2*w,b=g(function(pn){return (t[pn]^t[pn+1]<<w^t[pn+2]<<v)&_},"hsh"),y=new Cn(25e3),x=new oe(288),k=new oe(32),N=0,P=0,A=o.i||0,C=0,T=o.w||0,M=0;A+2<s;++A){var j=b(A),B=A&32767,$=m[j];if(p[B]=$,m[j]=B,T<=A){var I=s-A;if((N>7e3||C>24576)&&(I>423||!u)){c=xr(t,l,0,y,x,k,P,C,M,A-M,c),C=N=P=0,M=A;for(var E=0;E<286;++E)x[E]=0;for(var E=0;E<30;++E)k[E]=0;}var S=2,D=0,U=h,z=B-$&32767;if(I>2&&j==b(A-z))for(var W=Math.min(f,I)-1,L=Math.min(32767,A),X=Math.min(258,I);z<=L&&--U&&B!=$;){if(t[A+S]==t[A+S-z]){for(var q=0;q<X&&t[A+q]==t[A+q-z];++q);if(q>S){if(S=q,D=z,q>W)break;for(var Y=Math.min(z,q-2),_e=0,E=0;E<Y;++E){var be=A-z+E&32767,$t=p[be],St=be-$t&32767;St>_e&&(_e=St,$=be);}}}B=$,$=p[B],z+=B-$&32767;}if(D){y[C++]=268435456|xn[S]<<18|vr[D];var ht=xn[S]&31,pt=vr[D]&31;P+=Ot[ht]+Dt[pt],++x[257+ht],++k[pt],T=A+S,++N;}else y[C++]=t[A],++x[t[A]];}}for(A=Math.max(A,T);A<s;++A)y[C++]=t[A],++x[t[A]];c=xr(t,l,u,y,x,k,P,C,M,A-M,c),u||(o.r=c&7|l[c/8|0]<<3,c-=7,o.h=m,o.p=p,o.i=A,o.w=T);}else {for(var A=o.w||0;A<s+u;A+=65535){var Ve=A+65535;Ve>=s&&(l[c/8|0]=u,Ve=s),c=Tr(l,c+1,t.subarray(A,Ve));}o.i=s;}return wt(a,0,r+Pn(c)+i)},"dflt"),Ts=(function(){for(var t=new Int32Array(256),e=0;e<256;++e){for(var n=e,r=9;--r;)n=(n&1&&-306674912)^n>>>1;t[e]=n;}return t})(),$s=g(function(){var t=-1;return {p:g(function(e){for(var n=t,r=0;r<e.length;++r)n=Ts[n&255^e[r]]^n>>>8;t=n;},"p"),d:g(function(){return ~t},"d")}},"crc");var Ss=g(function(t,e,n,r,i){if(!i&&(i={l:1},e.dictionary)){var o=e.dictionary.subarray(-32768),s=new V(o.length+t.length);s.set(o),s.set(t,o.length),t=s,i.w=o.length;}return Ps(t,e.level==null?6:e.level,e.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(t.length)))*1.5):20:12+e.mem,n,r,i)},"dopt"),Sr=g(function(t,e){var n={};for(var r in t)n[r]=t[r];for(var r in e)n[r]=e[r];return n},"mrg");var me=g(function(t,e){return t[e]|t[e+1]<<8},"b2"),ae=g(function(t,e){return (t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24)>>>0},"b4"),vn=g(function(t,e){return ae(t,e)+ae(t,e+4)*4294967296},"b8"),te=g(function(t,e,n){for(;n;++e)t[e]=n,n>>>=8;},"wbytes");function Is(t,e){return Ss(t,e||{},0,0)}g(Is,"deflateSync");function Os(t,e){return As(t,{i:2},e&&e.out,e&&e.dictionary)}g(Os,"inflateSync");var Ir=g(function(t,e,n,r){for(var i in t){var o=t[i],s=e+i,a=r;Array.isArray(o)&&(a=Sr(r,o[1]),o=o[0]),ArrayBuffer.isView(o)?n[s]=[o,a]:(n[s+="/"]=[new V(0),a],Ir(o,s,n,r));}},"fltn"),Nr=typeof TextEncoder<"u"&&new TextEncoder,En=typeof TextDecoder<"u"&&new TextDecoder,Ds=0;try{En.decode($r,{stream:!0}),Ds=1;}catch{}var Rs=g(function(t){for(var e="",n=0;;){var r=t[n++],i=(r>127)+(r>223)+(r>239);if(n+i>t.length)return {s:e,r:wt(t,n-1)};i?i==3?(r=((r&15)<<18|(t[n++]&63)<<12|(t[n++]&63)<<6|t[n++]&63)-65536,e+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?e+=String.fromCharCode((r&31)<<6|t[n++]&63):e+=String.fromCharCode((r&15)<<12|(t[n++]&63)<<6|t[n++]&63):e+=String.fromCharCode(r);}},"dutf8");function It(t,e){if(e){for(var n=new V(t.length),r=0;r<t.length;++r)n[r]=t.charCodeAt(r);return n}if(Nr)return Nr.encode(t);for(var i=t.length,o=new V(t.length+(t.length>>1)),s=0,a=g(function(c){o[s++]=c;},"w"),r=0;r<i;++r){if(s+5>o.length){var l=new V(s+8+(i-r<<1));l.set(o),o=l;}var u=t.charCodeAt(r);u<128||e?a(u):u<2048?(a(192|u>>6),a(128|u&63)):u>55295&&u<57344?(u=65536+(u&1047552)|t.charCodeAt(++r)&1023,a(240|u>>18),a(128|u>>12&63),a(128|u>>6&63),a(128|u&63)):(a(224|u>>12),a(128|u>>6&63),a(128|u&63));}return wt(o,0,s)}g(It,"strToU8");function ze(t,e){if(e){for(var n="",r=0;r<t.length;r+=16384)n+=String.fromCharCode.apply(null,t.subarray(r,r+16384));return n}else {if(En)return En.decode(t);var i=Rs(t),o=i.s,n=i.r;return n.length&&re(8),o}}g(ze,"strFromU8");var Ms=g(function(t,e){return e+30+me(t,e+26)+me(t,e+28)},"slzh"),js=g(function(t,e,n){var r=me(t,e+28),i=me(t,e+30),o=ze(t.subarray(e+46,e+46+r),!(me(t,e+8)&2048)),s=e+46+r,a=Bs(t,s,i,n,ae(t,e+20),ae(t,e+24),ae(t,e+42)),l=a[0],u=a[1],c=a[2];return [me(t,e+10),l,u,o,s+i+me(t,e+32),c]},"zh"),Bs=g(function(t,e,n,r,i,o,s){var a=i==4294967295,l=o==4294967295,u=s==4294967295,c=e+n,d=a+l+u;if(r&&d){for(;e+4<c;e+=4+me(t,e+2))if(me(t,e)==1)return [a?vn(t,e+4+8*l):i,l?vn(t,e+4):o,u?vn(t,e+4+8*(l+a)):s,1];r<2&&re(13);}return [i,o,s,0]},"z64hs"),An=g(function(t){var e=0;if(t)for(var n in t){var r=t[n].length;r>65535&&re(9),e+=r+4;}return e},"exfl"),kr=g(function(t,e,n,r,i,o,s,a){var l=r.length,u=n.extra,c=a&&a.length,d=An(u);te(t,e,s!=null?33639248:67324752),e+=4,s!=null&&(t[e++]=20,t[e++]=n.os),t[e]=20,e+=2,t[e++]=n.flag<<1|(o<0&&8),t[e++]=i&&8,t[e++]=n.compression&255,t[e++]=n.compression>>8;var f=new Date(n.mtime==null?Date.now():n.mtime),h=f.getFullYear()-1980;if((h<0||h>119)&&re(10),te(t,e,h<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),e+=4,o!=-1&&(te(t,e,n.crc),te(t,e+4,o<0?-o-2:o),te(t,e+8,n.size)),te(t,e+12,l),te(t,e+14,d),e+=16,s!=null&&(te(t,e,c),te(t,e+6,n.attrs),te(t,e+10,s),e+=14),t.set(r,e),e+=l,d)for(var _ in u){var p=u[_],m=p.length;te(t,e,+_),te(t,e+2,m),t.set(p,e+4),e+=4+m;}return c&&(t.set(a,e),e+=c),e},"wzh"),Fs=g(function(t,e,n,r,i){te(t,e,101010256),te(t,e+8,n),te(t,e+10,n),te(t,e+12,r),te(t,e+16,i);},"wzf");function Or(t,e){e||(e={});var n={},r=[];Ir(t,"",n,e);var i=0,o=0;for(var s in n){var a=n[s],l=a[0],u=a[1],c=u.level==0?0:8,d=It(s),f=d.length,h=u.comment,_=h&&It(h),p=_&&_.length,m=An(u.extra);f>65535&&re(11);var w=c?Is(l,u):l,v=w.length,b=$s();b.p(l),r.push(Sr(u,{size:l.length,crc:b.d(),c:w,f:d,m:_,u:f!=s.length||_&&h.length!=p,o:i,compression:c})),i+=30+f+m+v,o+=76+2*(f+m)+(p||0)+v;}for(var y=new V(o+22),x=i,k=o-i,N=0;N<r.length;++N){var d=r[N];kr(y,d.o,d,d.f,d.u,d.c.length);var P=30+d.f.length+An(d.extra);y.set(d.c,d.o+P),kr(y,i,d,d.f,d.u,d.c.length,d.o,d.m),i+=16+P+(d.m?d.m.length:0);}return Fs(y,i,r.length,k,x),y}g(Or,"zipSync");function Ke(t,e){for(var n={},r=t.length-22;ae(t,r)!=101010256;--r)(!r||t.length-r>65558)&&re(13);var i=me(t,r+8);if(!i)return {};var o=ae(t,r+16),s=ae(t,r-20)==117853008;if(s){var a=ae(t,r-12);s=ae(t,a)==101075792,s&&(i=ae(t,a+32),o=ae(t,a+48));}for(var l=e&&e.filter,u=0;u<i;++u){var c=js(t,o,s),d=c[0],f=c[1],h=c[2],_=c[3],p=c[4],m=c[5],w=Ms(t,m);o=p,(!l||l({name:_,size:f,originalSize:h,compression:d}))&&(d?d==8?n[_]=Os(t.subarray(w,w+f),{out:new V(h)}):re(14,"unknown compression type "+d):n[_]=wt(t,w,w+f));}return n}g(Ke,"unzipSync");var Xi=mn(Tn());var lr=mn(Tn());var He=1,Jn=3,Yn=4,Ni=8,Qn=9,ki=class{static{g(this,"FastNode");}nodeType=0;parentNode=null;ownerDocument=null;get firstChild(){return null}get lastChild(){return null}get nextSibling(){let t=this.parentNode;if(!t)return null;let e=t.childNodes,n=e.indexOf(this);return n>=0&&n+1<e.length?e[n+1]:null}get previousSibling(){let t=this.parentNode;if(!t)return null;let e=t.childNodes,n=e.indexOf(this);return n>0?e[n-1]:null}},Pt=class Ei extends ki{static{g(this,"_FastText");}constructor(e){super(),this.data=e;}data;nodeType=Jn;get nodeName(){return "#text"}get nodeValue(){return this.data}set nodeValue(e){this.data=e;}get textContent(){return this.data}set textContent(e){this.data=e,this.ownerDocument&&this.ownerDocument._inc++;}cloneNode(e){let n=new Ei(this.data);return n.ownerDocument=this.ownerDocument,n}toString(){return Vt(this)}},Ai=class Ci extends Pt{static{g(this,"_FastComment");}nodeType=Ni;cloneNode(e){let n=new Ci(this.data);return n.ownerDocument=this.ownerDocument,n}},Ws=class Pi extends Pt{static{g(this,"_FastCData");}nodeType=Yn;cloneNode(e){let n=new Pi(this.data);return n.ownerDocument=this.ownerDocument,n}},Ti=class extends ki{static{g(this,"FastParent");}childNodes=[];get firstChild(){return this.childNodes.length?this.childNodes[0]:null}get lastChild(){return this.childNodes.length?this.childNodes[this.childNodes.length-1]:null}hasChildNodes(){return this.childNodes.length>0}bump(){let t=this.nodeType===Qn?this:this.ownerDocument;t&&t._inc++;}appendChild(t){return t.parentNode&&t.parentNode.removeChild(t),this.childNodes.push(t),t.parentNode=this,this.bump(),t}insertBefore(t,e){if(!e)return this.appendChild(t);if(this.childNodes.indexOf(e)<0)throw new Error("insertBefore: reference node not a child");t.parentNode&&t.parentNode.removeChild(t);let r=this.childNodes.indexOf(e);return this.childNodes.splice(r,0,t),t.parentNode=this,this.bump(),t}removeChild(t){let e=this.childNodes.indexOf(t);if(e<0)throw new Error("removeChild: node is not a child");return this.childNodes.splice(e,1),t.parentNode=null,this.bump(),t}replaceChild(t,e){if(this.childNodes.indexOf(e)<0)throw new Error("replaceChild: node is not a child");t.parentNode&&t.parentNode.removeChild(t);let r=this.childNodes.indexOf(e);return this.childNodes[r]=t,t.parentNode=this,e.parentNode=null,this.bump(),e}getElementsByTagName(t){let e=[],n=t==="*",r=[];for(let i=this.childNodes.length-1;i>=0;i--)r.push(this.childNodes[i]);for(;r.length;){let i=r.pop();if(i.nodeType===He){let o=i;(n||o.tagName===t)&&e.push(o);for(let s=o.childNodes.length-1;s>=0;s--)r.push(o.childNodes[s]);}}return e}},$i=class Si extends Ti{static{g(this,"_FastElement");}constructor(e){super(),this.tagName=e;}tagName;nodeType=He;attrs=[];get nodeName(){return this.tagName}get localName(){let e=this.tagName.indexOf(":");return e<0?this.tagName:this.tagName.slice(e+1)}get prefix(){let e=this.tagName.indexOf(":");return e<0?null:this.tagName.slice(0,e)}get nodeValue(){return null}get attributes(){let e=this.attrs.map(([n,r])=>({nodeType:2,name:n,value:r,nodeName:n,nodeValue:r,localName:n.indexOf(":")<0?n:n.slice(n.indexOf(":")+1),prefix:n.indexOf(":")<0?null:n.slice(0,n.indexOf(":")),ownerElement:this}));return e.item=n=>e[n]??null,e}toString(){return Vt(this)}getAttribute(e){let n=this.attrs;for(let r=0;r<n.length;r++)if(n[r][0]===e)return n[r][1];return null}hasAttribute(e){return this.getAttribute(e)!==null}setAttribute(e,n){let r=this.attrs;for(let i=0;i<r.length;i++)if(r[i][0]===e){r[i][1]=String(n),this.ownerDocument&&this.ownerDocument._inc++;return}r.push([e,String(n)]),this.ownerDocument&&this.ownerDocument._inc++;}removeAttribute(e){let n=this.attrs;for(let r=0;r<n.length;r++)if(n[r][0]===e){n.splice(r,1),this.ownerDocument&&this.ownerDocument._inc++;return}}get textContent(){let e="",n=[];for(let r=this.childNodes.length-1;r>=0;r--)n.push(this.childNodes[r]);for(;n.length;){let r=n.pop();if(r.nodeType===Jn||r.nodeType===Yn)e+=r.data;else if(r.nodeType===He){let i=r;for(let o=i.childNodes.length-1;o>=0;o--)n.push(i.childNodes[o]);}}return e}set textContent(e){for(let n of this.childNodes)n.parentNode=null;if(this.childNodes.length=0,e!==""&&e!==null&&e!==void 0){let n=new Pt(String(e));n.ownerDocument=this.ownerDocument,n.parentNode=this,this.childNodes.push(n);}this.ownerDocument&&this.ownerDocument._inc++;}cloneNode(e=false){let n=new Si(this.tagName);if(n.ownerDocument=this.ownerDocument,this.attrs.length&&(n.attrs=this.attrs.map(([r,i])=>[r,i])),e)for(let r of this.childNodes){let i=r.cloneNode(true);i.parentNode=n,n.childNodes.push(i);}return n}},Ls=class extends Ti{static{g(this,"FastDocument");}nodeType=Qn;_inc=1;documentElement=null;get nodeName(){return "#document"}createElement(t){let e=new $i(t);return e.ownerDocument=this,e}createElementNS(t,e){return this.createElement(e)}createTextNode(t){let e=new Pt(String(t));return e.ownerDocument=this,e}createComment(t){let e=new Ai(String(t));return e.ownerDocument=this,e}toString(){return Vt(this)}appendChild(t){let e=super.appendChild(t);return t.nodeType===He&&(this.documentElement=t),e}replaceChild(t,e){let n=super.replaceChild(t,e);return e===this.documentElement&&t.nodeType===He&&(this.documentElement=t),n}},zs=/&(?:amp|lt|gt|quot|apos|#x?[0-9a-fA-F]+);/g;function Ii(t){return t.indexOf("&")<0?t:t.replace(zs,e=>{switch(e){case "&amp;":return "&";case "&lt;":return "<";case "&gt;":return ">";case "&quot;":return '"';case "&apos;":return "'";default:{let n=e.slice(2,-1),r=n[0]==="x"||n[0]==="X"?parseInt(n.slice(1),16):parseInt(n,10);return Number.isFinite(r)?String.fromCodePoint(r):e}}})}g(Ii,"decodeEntities");function Mn(t){return t.indexOf("\r")<0?t:t.replace(/\r\n?/g,`
6
+ `)}g(Mn,"normalizeLineEnds");function Us(t){let e=Mn(t),n=/[\n\t]/.test(e)?e.replace(/[\n\t]/g," "):e;return Ii(n)}g(Us,"normalizeAttrValue");var $n=new Set([32,9,10,13]);function Hs(t){t.charCodeAt(0)===65279&&(t=t.slice(1));let e=new Ls,n=e,r=0,i=t.length,o=false;for(;r<i;){let s=t.indexOf("<",r);if(s<0){if(n!==e)throw new Error("Unexpected end of XML");if(/\S/.test(t.slice(r)))throw new Error("Content after document root");break}if(s>r&&n!==e){let d=t.slice(r,s),f=new Pt(Ii(Mn(d)));f.ownerDocument=e,f.parentNode=n,n.childNodes.push(f);}else if(s>r&&/\S/.test(t.slice(r,s)))throw new Error("Text content outside document root");r=s+1;let a=t.charCodeAt(r);if(a===47){let d=t.indexOf(">",r);if(d<0)throw new Error("Unterminated close tag");let f=t.slice(r+1,d).trim();if(n.nodeType!==He||n.tagName!==f)throw new Error(`Mismatched close tag </${f}>`);n=n.parentNode??e,r=d+1;continue}if(a===63){let d=t.indexOf("?>",r);if(d<0)throw new Error("Unterminated processing instruction");r=d+2;continue}if(a===33){if(t.startsWith("!--",r)){let f=t.indexOf("-->",r+3);if(f<0)throw new Error("Unterminated comment");let h=new Ai(t.slice(r+3,f));h.ownerDocument=e,n!==e&&(h.parentNode=n,n.childNodes.push(h)),r=f+3;continue}if(t.startsWith("![CDATA[",r)){let f=t.indexOf("]]>",r+8);if(f<0)throw new Error("Unterminated CDATA section");if(n!==e){let h=new Ws(Mn(t.slice(r+8,f)));h.ownerDocument=e,h.parentNode=n,n.childNodes.push(h);}r=f+3;continue}let d=t.indexOf(">",r);if(d<0)throw new Error("Unterminated declaration");r=d+1;continue}let l=r;for(;l<i;){let d=t.charCodeAt(l);if($n.has(d)||d===62||d===47)break;l++;}if(l===r)throw new Error(`Invalid tag at offset ${s}`);let u=new $i(t.slice(r,l));if(u.ownerDocument=e,n===e){if(o)throw new Error("Multiple document roots");o=true,e.childNodes.push(u),u.parentNode=e,e.documentElement=u;}else u.parentNode=n,n.childNodes.push(u);r=l;let c=false;for(;r<i;){let d=t.charCodeAt(r);if(d===62){r++;break}if(d===47){if(t.charCodeAt(r+1)!==62)throw new Error("Malformed self-close");c=true,r+=2;break}if($n.has(d)){r++;continue}let f=t.indexOf("=",r);if(f<0)throw new Error("Malformed attribute");let h=t.slice(r,f).trim(),_=f+1;for(;_<i&&$n.has(t.charCodeAt(_));)_++;let p=t.charCodeAt(_);if(p!==34&&p!==39)throw new Error("Unquoted attribute value");let m=t.indexOf(String.fromCharCode(p),_+1);if(m<0)throw new Error("Unterminated attribute value");u.attrs.push([h,Us(t.slice(_+1,m))]),r=m+1;}c||(n=u);}if(n!==e)throw new Error("Unclosed element at end of document");if(!e.documentElement)throw new Error("Empty XML document");return e}g(Hs,"parseFastXml");function Xs(t){return /[&<>\r]/.test(t)?t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\r/g,"&#13;"):t}g(Xs,"escText");function qs(t){return /[&<>"\t\n\r]/.test(t)?t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\t/g,"&#9;").replace(/\n/g,"&#10;").replace(/\r/g,"&#13;"):t}g(qs,"escAttr");function Vt(t){let e=[],n=g(r=>{switch(r.nodeType){case He:{let i=r;e.push("<",i.tagName);for(let o=0;o<i.attrs.length;o++){let[s,a]=i.attrs[o];e.push(" ",s,'="',qs(a),'"');}if(i.childNodes.length===0)e.push("/>");else {e.push(">");for(let o of i.childNodes)n(o);e.push("</",i.tagName,">");}break}case Jn:e.push(Xs(r.data));break;case Yn:e.push("<![CDATA[",r.data,"]]>");break;case Ni:e.push("<!--",r.data,"-->");break;case Qn:for(let i of r.childNodes)n(i);break}},"write");return n(t),e.join("")}g(Vt,"serializeFastXml");function O(t,e){for(let n=0;n<t.childNodes.length;n++){let r=t.childNodes[n];if(r.nodeType===1&&r.tagName===e)return r}return null}g(O,"findChild");function Vn(t,e){let n=[];for(let r=0;r<t.childNodes.length;r++){let i=t.childNodes[r];i.nodeType===1&&i.tagName===e&&n.push(i);}return n}g(Vn,"findChildren");function Oi(t,e){let n=typeof e=="string"?[e]:e,r=[],i=g((o,s)=>{if(!(s>Gs))for(let a=0;a<o.childNodes.length;a++){let l=o.childNodes[a];if(l.nodeType!==1)continue;let u=l;n.includes(u.tagName)?r.push(u):(u.tagName==="w:sdt"||u.tagName==="w:sdtContent")&&i(u,s+1);}},"visit");return i(t,0),r}g(Oi,"findChildrenSdtTransparent");var Gs=100;function R(t,e){return Array.from(t.getElementsByTagName(e))}g(R,"findAllDescendants");function Xe(t){return t.startsWith("\uFEFF")&&(t=t.slice(1)),Hs(t)}g(Xe,"parseXml");function Dr(t){let e=Vt(t),r=/<([a-zA-Z0-9_:]+)(\s+[^>]+?)(>|\/>)/.exec(e);if(r&&!r[1].startsWith("?")){let i=r.index,o=e.substring(0,i);if(!o.includes("<")||o.trim().startsWith("<?xml")&&(o.match(/</g)||[]).length===1){let a=r[0],l=`<${r[1]}`,u=r[2],c=r[3],d=/([a-zA-Z0-9_:]+)\s*=\s*(["'])(.*?)\2/g,f=[],h;for(;(h=d.exec(u))!==null;)f.push(h[0].trim());f.sort((p,m)=>{let w=p.split("=")[0].trim(),v=m.split("=")[0].trim(),b=w.startsWith("xmlns"),y=v.startsWith("xmlns");return b&&!y?-1:!b&&y?1:w<v?-1:w>v?1:0});let _=f.length>0?`${l} ${f.join(" ")}${c}`:`${l}${c}`;e=e.substring(0,i)+_+e.substring(i+a.length);}}return e}g(Dr,"serializeXml");var qt=1,Zn=2147483647;function Kn(t){return ((t&Zn)>>>0||qt).toString(16).toUpperCase().padStart(8,"0")}g(Kn,"toLongHexNumber");function Rt(){let t=Zn-qt+1;return Kn(qt+Math.floor(Math.random()*t))}g(Rt,"generateLongHexNumber");function Rr(t){if(!/^[0-9A-Fa-f]{1,8}$/.test(t))return false;let e=parseInt(t,16);return e>=qt&&e<=Zn}g(Rr,"isWordReadableLongHexNumber");var jn="__adeu_wp_index_cache",Di="__adeu_clean_inc";function Zt(t){return typeof t._inc=="number"?t._inc:null}g(Zt,"docInc");function Nt(t){let e=Zt(t);e!==null&&(t[Di]=e);}g(Nt,"markPartClean");function er(t){let e=Zt(t);return e!==null&&t[Di]===e}g(er,"isPartClean");function Js(t){let e=new Map,n=t.documentElement;if(!n)return e;let r=0;n.nodeType===1&&n.tagName==="w:p"&&e.set(n,r++);let i=[n],o=[0];for(;i.length;){let s=i.length-1,a=i[s].childNodes;if(!a||o[s]>=a.length){i.pop(),o.pop();continue}let l=a[o[s]++];l.nodeType===1&&(l.tagName==="w:p"&&e.set(l,r++),i.push(l),o.push(0));}return e}g(Js,"buildWpIndexMap");function Ys(t,e){let n=Zt(t),r=t[jn];(!r||n===null||r.inc!==n||!r.map.has(e))&&(r={inc:n??NaN,map:Js(t)},t[jn]=r);let i=r.map.get(e);return i===void 0?-1:i}g(Ys,"wpDocumentOrderIndex");function Qs(t){let e=t[jn],n=Zt(t);e&&n!==null&&(e.inc=n);}g(Qs,"resyncAfterOwnAttributeMutation");function Ri(t,e){let n=t.getElementsByTagName("w:p")[0],r=n?n.getAttribute("w14:paraId"):null;if(!r&&e){let i=t.ownerDocument,o=er(i);n||(n=i.createElement("w:p"),t.appendChild(n));let s=Ys(i,n),a=2166136261,l=`fallback-paraId-${s}`;for(let u=0;u<l.length;u++)a^=l.charCodeAt(u),a+=(a<<1)+(a<<4)+(a<<7)+(a<<8)+(a<<24);r=Kn(a),n.setAttribute("w14:paraId",r),Qs(i),o&&Nt(i);}return {paraId:r,firstP:n}}g(Ri,"resolve_cell_anchor");var zt=class{static{g(this,"Relationship");}constructor(t,e,n,r){this.id=t,this.type=e,this.target=n,this.isExternal=r;}id;type;target;isExternal},Mi=class{static{g(this,"Part");}constructor(t,e,n,r){this.partname=t,this.blob=e,this.contentType=r,this._element=n;}partname;blob;contentType;rels=new Map;_element;package;addRelationship(t,e,n,r=false){if(this.rels.set(t,new zt(t,e,n,r)),this.partname.endsWith(".rels")){let i=this._element.ownerDocument;if(i){let o=i.createElementNS("http://schemas.openxmlformats.org/package/2006/relationships","Relationship");o.setAttribute("Id",t),o.setAttribute("Type",e),o.setAttribute("Target",n),r&&o.setAttribute("TargetMode","External"),this._element.appendChild(o);}}}},Vs=class{static{g(this,"DocxPackage");}constructor(t){this.unzipped=t;}unzipped;parts=[];mainDocumentPart;getPartByPath(t){let e=t.startsWith("/")?t.substring(1):t;return this.parts.find(n=>n.partname===e||n.partname==="/"+e)}nextPartname(t){let e=1;for(;;){let n=t.replace("%d",e===1?"":e.toString());if(!this.getPartByPath(n))return n;e++;}}addPart(t,e,n){let r=Xe(n),i=new Mi(t,n,r.documentElement,e);i.package=this,this.parts.push(i);let o=this.getPartByPath("[Content_Types].xml");if(o){let s=o._element.ownerDocument;if(s){let a=s.createElement("Override");a.setAttribute("PartName",t),a.setAttribute("ContentType",e),o._element.appendChild(a);}}return i}getOrCreateRelsPart(t){let e=t.split("/"),n=e.pop(),r=e.join("/")+"/_rels/"+n+".rels",i=this.getPartByPath(r);return i||(i=this.addPart(r,"application/vnd.openxmlformats-package.relationships+xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
7
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>`)),i}},ce=class ji{static{g(this,"_DocumentObject");}constructor(e,n){this.pkg=e,this.part=n;}pkg;part;settings={oddAndEvenPagesHeaderFooter:false};sections=[];get element(){return O(this.part._element,"w:body")||this.part._element}static async load(e,n){let r=e instanceof Uint8Array?e:new Uint8Array(e),i=Ke(r),o=new Vs(i),s=i["[Content_Types].xml"],a={};if(s){let _=Xe(ze(s)),p=R(_.documentElement,"Override");for(let m of p)a[m.getAttribute("PartName")||""]=m.getAttribute("ContentType")||"";}let l=n?.onPart,u=Math.max(1,n?.partTickEvery??200),c=0;if(l)for(let _ of Object.keys(i))(_.endsWith(".xml")||_.endsWith(".rels"))&&c++;let d=0;for(let[_,p]of Object.entries(i))if(_.endsWith(".xml")||_.endsWith(".rels")){let m=ze(p),w=Xe(m);Nt(w);let v=a["/"+_]||"application/xml",b=new Mi("/"+_,m,w.documentElement,v);b.package=o,o.parts.push(b),d++,l&&d%u===0&&await l(d,c);}l&&c>0&&await l(c,c);let f=o.getPartByPath("word/document.xml");if(!f)throw new Error("Invalid DOCX: Missing word/document.xml");o.mainDocumentPart=f;let h=o.getPartByPath("word/_rels/document.xml.rels");if(h){let _=R(h._element,"Relationship");for(let p of _){let m=p.getAttribute("Id"),w=p.getAttribute("Target"),v=p.getAttribute("Type"),b=p.getAttribute("TargetMode");m&&w&&v&&f.rels.set(m,new zt(m,v,w,b==="External"));}}return new ji(o,f)}relateTo(e,n){let r=1;for(;this.part.rels.has(`rId${r}`);)r++;let i=`rId${r}`,o=e.partname.split("/").pop();return this.part.rels.set(i,new zt(i,n,o,false)),this.pkg.getOrCreateRelsPart(this.part.partname).addRelationship(i,n,o,false),i}relateToExternal(e,n){let r=1;for(;this.part.rels.has(`rId${r}`);)r++;let i=`rId${r}`;return this.part.rels.set(i,new zt(i,n,e,true)),this.pkg.getOrCreateRelsPart(this.part.partname).addRelationship(i,n,e,true),i}async save(){for(let e of this.pkg.parts){let n=Dr(e._element.ownerDocument||e._element);n.includes("w16du:")&&!n.includes("xmlns:w16du=")&&(e._element.setAttribute("xmlns:w16du","http://schemas.microsoft.com/office/word/2023/wordml/word16du"),n=Dr(e._element.ownerDocument||e._element)),n.startsWith("<?xml")||(n=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
8
+ `+n),this.pkg.unzipped[e.partname.substring(1)]=It(n),e.blob=n;let r=e._element.ownerDocument;r&&Nt(r);}return Buffer.from(Or(this.pkg.unzipped))}},Zs=Object.freeze([]),ne=class{static{g(this,"Paragraph");}constructor(t,e){this._element=t,this._parent=e;}_element;_parent;get text(){let t="",e=this._element.getElementsByTagName("w:t");for(let n=0;n<e.length;n++)t+=e[n].textContent||"";return t}},Re=class{static{g(this,"Run");}constructor(t,e){this._element=t,this._parent=e;}_element;_parent;projTextOverride;sdtStack=Zs},Ks=class{static{g(this,"Cell");}constructor(t,e){this._element=t,this._parent=e;}_element;_parent},ea=class{static{g(this,"Row");}constructor(t,e){this._element=t,this._parent=e;for(let n of Oi(this._element,"w:tc"))this.cells.push(new Ks(n,this));}_element;_parent;cells=[]},Fe=class{static{g(this,"Table");}constructor(t,e){this._element=t,this._parent=e;for(let n of Oi(this._element,"w:tr"))this.rows.push(new ea(n,this));}_element;_parent;rows=[]},Mr=class{static{g(this,"NotesPart");}constructor(t,e){this.part=t,this.note_type=e,this._element=t._element;}part;note_type;_element},ta=class{static{g(this,"FootnoteItem");}constructor(t,e,n){this._element=t,this._parent=e,this.note_type=n,this.id=t.getAttribute("w:id")||"",this.part=e.part;}_element;_parent;note_type;id;part},at="w:sdt",na="w:sdtPr",Ge="w:sdtContent",ra=[["checkbox","w14:checkbox"],["dropdown","w:dropDownList"],["combobox","w:comboBox"],["date","w:date"],["picture","w:picture"],["building-block","w:docPartObj"],["building-block","w:docPartList"],["group","w:group"],["repeating","w15:repeatingSection"],["repeating-item","w15:repeatingSectionItem"],["text","w:text"]],ia=new Set(["checkbox","picture","building-block","repeating","repeating-item"]),oa=new Set(["sdtContentLocked","contentLocked"]);function Ue(t){return t?t.getAttribute("w:val")??t.getAttribute("w14:val"):null}g(Ue,"val");function kt(t){return !(ia.has(t.cls)||t.cls==="richtext"&&t.hasNestedSdt)}g(kt,"isAnchored");function Oe(t){let e=t.flags.map(n=>` ${n}`).join("");return `{#cc:${t.ordinal}${e}}`}g(Oe,"openToken");function De(t){return `{#/cc:${t.ordinal}}`}g(De,"closeToken");var Bi=new Set(["\u2610","\u2611","\u2612"]),Fi="[",Wi="]";function tr(t){return t.checked?"x":" "}g(tr,"checkboxMark");function sa(t,e=0){let n=O(t,na),r="richtext";if(n){for(let[C,T]of ra)if(O(n,T)){r=C;break}}let i=Ue(n?O(n,"w:alias"):null),o=Ue(n?O(n,"w:tag"):null),s=Ue(n?O(n,"w:id"):null),a=Ue(n?O(n,"w:lock"):null),l=a!==null&&oa.has(a),u=a==="sdtLocked"||a==="sdtContentLocked",c=n?O(n,"w:dataBinding"):null,d=!!c,f=c?c.getAttribute("w:xpath"):null,h=c?c.getAttribute("w:storeItemID"):null,_=c?c.getAttribute("w:prefixMappings"):null,p=!!(n&&O(n,"w:showingPlcHdr")),m=n?O(n,"w:temporary"):null,w=m?Ue(m):null,v=!!m&&(w===null||["1","true","on"].includes(w)),b=O(t,Ge),y=null;p&&b&&(y=R(b,"w:t").map(T=>T.textContent??"").join("").trim()||null);let x=[];if(r==="dropdown"||r==="combobox"){let C=n?O(n,r==="dropdown"?"w:dropDownList":"w:comboBox"):null;if(C){let T=[];for(let M of Array.from(C.childNodes)){if(M.nodeType!==1||M.tagName!=="w:listItem")continue;let j=M.getAttribute("w:displayText"),B=M.getAttribute("w:value");T.push([j??B??"",B??j??""]);}x=T;}}let k=null;if(r==="checkbox"){let C=n?O(n,"w14:checkbox"):null,T=Ue(C?O(C,"w14:checked"):null);k=T==="1"||T==="true";}let N=null;if(r==="date"){let C=n?O(n,"w:date"):null;N=Ue(C?O(C,"w:dateFormat"):null);}let P=!!b&&R(b,at).length>0,A=[];return l&&r!=="group"&&A.push("locked"),d&&A.push("bound"),r==="group"&&A.push("group"),{element:t,cls:r,alias:i,tag:o,sdtId:s,contentLocked:l,deleteLocked:u,bound:d,bindingXpath:f,storeItemId:h,prefixMappings:_,showingPlaceholder:p,placeholderText:y,temporary:v,options:x,checked:k,dateFormat:N,hasNestedSdt:P,ordinal:e,flags:A}}g(sa,"classifySdt");function aa(t){return t?R(t,at):[]}g(aa,"iterSdtElementsInOrder");function Kt(t){let e=new Map,n=0;for(let r of t)for(let i of aa(r))n+=1,e.set(i,sa(i,n));return e}g(Kt,"assignOrdinals");var la=new Set(["sdt_start","sdt_end","checkbox_start","checkbox_mark","checkbox_end"]);function nr(t){return !!t&&la.has(t.type)&&"info"in t}g(nr,"isSdtEvent");var Li=["checkbox_start","checkbox_mark","checkbox_end"];function zi(t,e){let n=e+1<t.length?t[e+1]:null;return nr(n)&&n.type==="checkbox_end"}g(zi,"nextClosesCheckbox");function en(t){return t?.element??t?._element??t}g(en,"partElement");var rr=class{static{g(this,"BlockSdt");}constructor(t){this.element=t;}element};function Ui(t){let e=t?.parentNode;if(e&&e.tagName===Ge){let n=e.parentNode;if(n&&n.tagName===at)return n}return null}g(Ui,"wrappingSdt");var ie={w:"http://schemas.openxmlformats.org/wordprocessingml/2006/main",w14:"http://schemas.microsoft.com/office/word/2010/wordml",w15:"http://schemas.microsoft.com/office/word/2012/wordml",w16cid:"http://schemas.microsoft.com/office/word/2016/wordml/cid",w16cex:"http://schemas.microsoft.com/office/word/2018/wordml/cex",mc:"http://schemas.openxmlformats.org/markup-compatibility/2006"},ee={COMMENTS:"application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml",EXTENDED:"application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml",IDS:"application/vnd.openxmlformats-officedocument.wordprocessingml.commentsIds+xml",EXTENSIBLE:"application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtensible+xml"},$e={COMMENTS:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments",EXTENDED:"http://schemas.microsoft.com/office/2011/relationships/commentsExtended",IDS:"http://schemas.microsoft.com/office/2016/09/relationships/commentsIds",EXTENSIBLE:"http://schemas.microsoft.com/office/2018/08/relationships/commentsExtensible"},jr=["w14:paraId","w15:paraId","w15:paraIdParent","w16cid:paraId"],Br=["w16cid:durableId","w16cex:durableId"],ca=["w14:textId","w:rsidR","w:rsidRPr","w:rsidRDefault","w:rsidP","w:rsidDel","w:rsidTr"],Hi=class extends Error{static{g(this,"CommentThreadingError");}constructor(t){super(t),this.name="CommentThreadingError";}};function*Bn(t){yield t;for(let e=0;e<t.childNodes.length;e++){let n=t.childNodes[e];n.nodeType===1&&(yield*Bn(n));}}g(Bn,"walkElements");var Et=class{static{g(this,"CommentsManager");}constructor(t){this.doc=t;}doc;_commentsPart=null;_extendedPart=null;_idsPart=null;_extensiblePart=null;_nextId=null;get commentsPart(){return this._commentsPart||(this._commentsPart=this._getOrCreateCommentsPart(),this._ensureNamespaces()),this._commentsPart}get extendedPart(){return this._extendedPart||(this._extendedPart=this._getOrCreateExtendedPart()),this._extendedPart}get idsPart(){return this._idsPart||(this._idsPart=this._getOrCreateIdsPart()),this._idsPart}get extensiblePart(){return this._extensiblePart||(this._extensiblePart=this._getOrCreateExtensiblePart()),this._extensiblePart}get nextId(){return this._nextId===null&&(this._nextId=this._getNextCommentId()),this._nextId}set nextId(t){this._nextId=t;}_getExistingPartByType(t){return this.doc.pkg.parts.find(e=>e.contentType===t)||null}_linkPart(t,e){for(let n of this.doc.part.rels.values())if(!n.isExternal&&n.target===t.partname.split("/").pop())return t;return this.doc.relateTo(t,e),t}_getOrCreateCommentsPart(){let t=this._getExistingPartByType(ee.COMMENTS);if(t)return this._linkPart(t,$e.COMMENTS);let e=this.doc.pkg.nextPartname("/word/comments%d.xml"),n=`<w:comments xmlns:w="${ie.w}" xmlns:w14="${ie.w14}" xmlns:w15="${ie.w15}" xmlns:w16cid="${ie.w16cid}" xmlns:w16cex="${ie.w16cex}" xmlns:mc="${ie.mc}" mc:Ignorable="w14 w15 w16cid w16cex"></w:comments>`;return t=this.doc.pkg.addPart(e,ee.COMMENTS,n),this.doc.relateTo(t,$e.COMMENTS),t}_getOrCreateExtendedPart(){let t=this._getExistingPartByType(ee.EXTENDED);if(t)return this._linkPart(t,$e.EXTENDED);let e=this.doc.pkg.nextPartname("/word/commentsExtended%d.xml"),n=`<w15:commentsEx xmlns:w15="${ie.w15}"></w15:commentsEx>`;return t=this.doc.pkg.addPart(e,ee.EXTENDED,n),this.doc.relateTo(t,$e.EXTENDED),t}_getOrCreateIdsPart(){let t=this._getExistingPartByType(ee.IDS);if(t)return this._linkPart(t,$e.IDS);let e=this.doc.pkg.nextPartname("/word/commentsIds%d.xml"),n=`<w16cid:commentsIds xmlns:w16cid="${ie.w16cid}"></w16cid:commentsIds>`;return t=this.doc.pkg.addPart(e,ee.IDS,n),this.doc.relateTo(t,$e.IDS),t}_getOrCreateExtensiblePart(){let t=this._getExistingPartByType(ee.EXTENSIBLE);if(t)return this._linkPart(t,$e.EXTENSIBLE);let e=this.doc.pkg.nextPartname("/word/commentsExtensible%d.xml"),n=`<w16cex:commentsExtensible xmlns:w16cex="${ie.w16cex}"></w16cex:commentsExtensible>`;return t=this.doc.pkg.addPart(e,ee.EXTENSIBLE,n),this.doc.relateTo(t,$e.EXTENSIBLE),t}_ensureNamespaces(){let t=this._commentsPart?._element;if(!t)return;let e=[["xmlns:w",ie.w],["xmlns:w14",ie.w14],["xmlns:w15",ie.w15],["xmlns:w16cid",ie.w16cid],["xmlns:w16cex",ie.w16cex],["xmlns:mc",ie.mc]];for(let[n,r]of e)t.getAttribute(n)||t.setAttribute(n,r);}_getNextCommentId(){let t=[0],e=this._getExistingPartByType(ee.COMMENTS);if(e){let n=R(e._element,"w:comment");for(let r of n){let i=r.getAttribute("w:id");i&&t.push(parseInt(i,10)||0);}}return Math.max(...t)+1}_generateHexId(){return Rt()}_generateDurableId(){return Rt()}_getInitials(t){return t?t.split(" ").filter(Boolean).map(e=>e[0]).join("").toUpperCase():""}_hasCommentsPart(){return this._commentsPart!==null||this._getExistingPartByType(ee.COMMENTS)!==null}_findParaIdForComment(t){if(!this._hasCommentsPart())return null;for(let e of R(this.commentsPart._element,"w:comment"))if(e.getAttribute("w:id")===t)for(let n of R(e,"w:p")){let r=n.getAttribute("w14:paraId");if(r)return r}return null}_findThreadRootParaId(t){let e=this._findParaIdForComment(t),n=this._getExistingPartByType(ee.EXTENDED);if(!e||!n)return e;for(let r=0;r<n._element.childNodes.length;r++){let i=n._element.childNodes[r];if(i.nodeType===1&&i.getAttribute("w15:paraId")===e){let o=i.getAttribute("w15:paraIdParent");if(o)return o}}return e}_existingCommentPartElements(){let t=[];for(let e of [ee.COMMENTS,ee.EXTENDED,ee.IDS,ee.EXTENSIBLE]){let n=this._getExistingPartByType(e);n&&t.push(n._element);}return t}_freeLongHexNumber(t,e){let n=parseInt(t,16),r=Number.isNaN(n)?Rt():Kn(n);for(;e.has(r);)r=Rt();return r}_repairInheritedLongHexNumbers(){let t=this._existingCommentPartElements();if(t.length===0)return;let e=g(i=>{let o=new Set,s=[];for(let l of t)for(let u of Bn(l))for(let c of i){let d=u.getAttribute(c);d&&(Rr(d)?o.add(d.toUpperCase()):s.includes(d)||s.push(d));}let a=new Map;for(let l of s){let u=this._freeLongHexNumber(l,o);o.add(u),a.set(l,u);}return a},"remapFor"),n=e(jr),r=e(Br);for(let i of t)for(let o of Bn(i)){for(let s of jr){let a=n.get(o.getAttribute(s)??"");a&&o.setAttribute(s,a);}for(let s of Br){let a=r.get(o.getAttribute(s)??"");a&&o.setAttribute(s,a);}for(let s of ca){let a=o.getAttribute(s);a&&!Rr(a)&&o.setAttribute(s,this._freeLongHexNumber(a,new Set));}}}_adoptIntoModernComments(t){if(!this._hasCommentsPart())return null;let e=null;for(let o of R(this.commentsPart._element,"w:comment"))if(o.getAttribute("w:id")===t){e=o;break}if(!e)return null;let n=R(e,"w:p");if(n.length===0)return null;let r=null;for(let o of n){let s=o.getAttribute("w14:paraId");if(s){r=s;break}}r||(r=this._generateHexId(),n[0].setAttribute("w14:paraId",r));let i=g((o,s)=>{for(let a=0;a<o._element.childNodes.length;a++){let l=o._element.childNodes[a];if(l.nodeType===1&&l.getAttribute(s)===r)return true}return false},"hasChild");if(!i(this.extendedPart,"w15:paraId")){let s=this.extendedPart._element.ownerDocument.createElement("w15:commentEx");s.setAttribute("w15:paraId",r),s.setAttribute("w15:done","0"),this.extendedPart._element.appendChild(s);}if(!i(this.idsPart,"w16cid:paraId")){let s=this.idsPart._element.ownerDocument.createElement("w16cid:commentId");s.setAttribute("w16cid:paraId",r),s.setAttribute("w16cid:durableId",this._generateDurableId()),this.idsPart._element.appendChild(s);}return r}resolveThreadParentParaId(t){this._repairInheritedLongHexNumbers();let e=this._findThreadRootParaId(t),n=this._adoptIntoModernComments(t);return e??n}addComment(t,e,n=null){this._repairInheritedLongHexNumbers();let r=this._getExistingPartByType(ee.EXTENDED)!==null,i=null;if(n!=null&&(i=this.resolveThreadParentParaId(n),!i))throw new Hi(`Cannot thread a reply onto comment Com:${n}: the comment has no resolvable paragraph identity (w14:paraId) in word/comments.xml, so Word would render the reply as a separate top-level comment instead of a reply. Refusing to create an unthreaded comment.`);let o=this.nextId.toString();this.nextId++;let s=new Date().toISOString().replace(/\.\d{3}Z$/,"Z"),a=this.commentsPart._element.ownerDocument,l=a.createElement("w:comment");l.setAttribute("w:id",o),l.setAttribute("w:author",t),l.setAttribute("w:date",s);let u=this._getInitials(t);u&&l.setAttribute("w:initials",u),n&&!r&&l.setAttribute("w15:p",n);let c=this._generateHexId(),d=this._generateHexId(),f=a.createElement("w:p");f.setAttribute("w14:paraId",c),f.setAttribute("w14:textId","77777777"),f.setAttribute("w:rsidR",d),f.setAttribute("w:rsidRDefault",d),f.setAttribute("w:rsidP",d);let h=a.createElement("w:pPr"),_=a.createElement("w:pStyle");_.setAttribute("w:val","CommentText"),h.appendChild(_),f.appendChild(h);let p=a.createElement("w:r"),m=a.createElement("w:rPr"),w=a.createElement("w:rStyle");w.setAttribute("w:val","CommentReference"),m.appendChild(w),p.appendChild(m),p.appendChild(a.createElement("w:annotationRef")),f.appendChild(p);let v=a.createElement("w:r"),b=a.createElement("w:t");if(b.textContent=e,v.appendChild(b),f.appendChild(v),l.appendChild(f),this.commentsPart._element.appendChild(l),this.extendedPart){let x=this.extendedPart._element.ownerDocument.createElement("w15:commentEx");x.setAttribute("w15:paraId",c),i&&x.setAttribute("w15:paraIdParent",i),x.setAttribute("w15:done","0"),this.extendedPart._element.appendChild(x);}if(this.idsPart){let x=this.idsPart._element.ownerDocument.createElement("w16cid:commentId");x.setAttribute("w16cid:paraId",c),x.setAttribute("w16cid:durableId",this._generateDurableId()),this.idsPart._element.appendChild(x);}if(this.extensiblePart){let y=null;for(let x=0;x<this.idsPart._element.childNodes.length;x++){let k=this.idsPart._element.childNodes[x];if(k.nodeType===1&&k.getAttribute("w16cid:paraId")===c){y=k.getAttribute("w16cid:durableId");break}}if(y){let k=this.extensiblePart._element.ownerDocument.createElement("w16cex:commentExtensible");k.setAttribute("w16cex:durableId",y),k.setAttribute("w16cex:dateUtc",s),this.extensiblePart._element.appendChild(k);}}return o}deleteComment(t){if(!this.commentsPart)return;let e=null;for(let r of R(this.commentsPart._element,"w:comment"))if(r.getAttribute("w:id")===t){e=r;break}if(!e)return;let n=null;for(let r of R(e,"w:p")){let i=r.getAttribute("w14:paraId");if(i){n=i;break}}if(n){let r=[];if(this.extendedPart)for(let o=0;o<this.extendedPart._element.childNodes.length;o++){let s=this.extendedPart._element.childNodes[o];if(s.nodeType===1&&s.getAttribute("w15:paraIdParent")===n){let a=s.getAttribute("w15:paraId");if(a){for(let l of R(this.commentsPart._element,"w:comment"))for(let u of R(l,"w:p"))if(u.getAttribute("w14:paraId")===a){let c=l.getAttribute("w:id");c&&r.push(c);break}}}}for(let o of r)this.deleteComment(o);let i=null;if(this.idsPart){let o=[];for(let s=0;s<this.idsPart._element.childNodes.length;s++){let a=this.idsPart._element.childNodes[s];a.nodeType===1&&a.getAttribute("w16cid:paraId")===n&&(i=a.getAttribute("w16cid:durableId"),o.push(a));}o.forEach(s=>this.idsPart._element.removeChild(s));}if(this.extendedPart){let o=[];for(let s=0;s<this.extendedPart._element.childNodes.length;s++){let a=this.extendedPart._element.childNodes[s];a.nodeType===1&&a.getAttribute("w15:paraId")===n&&o.push(a);}o.forEach(s=>this.extendedPart._element.removeChild(s));}if(i&&this.extensiblePart){let o=[];for(let s=0;s<this.extensiblePart._element.childNodes.length;s++){let a=this.extensiblePart._element.childNodes[s];a.nodeType===1&&a.getAttribute("w16cex:durableId")===i&&o.push(a);}o.forEach(s=>this.extensiblePart._element.removeChild(s));}}e.parentNode&&e.parentNode.removeChild(e);}};function Me(t){({part:t.mainDocumentPart,relateTo:g(()=>{},"relateTo")});let r={},i=t.parts.find(l=>l.contentType===ee.COMMENTS);if(!i)return r;let o={},s=R(i._element,"w:comment");for(let l of s){let u=l.getAttribute("w:id");if(!u)continue;let c=l.getAttribute("w:author")||"Unknown",d=l.getAttribute("w:date")||"",f=false,h=l.getAttribute("w15:done");(h==="1"||h==="true"||h==="on")&&(f=true);let _=l.getAttribute("w15:p")||null,p=R(l,"w:p");for(let v of p){let b=v.getAttribute("w14:paraId");b&&(o[b]=u);}let m=[];for(let v of p){let b=R(v,"w:t");for(let y of b)y.textContent&&m.push(y.textContent);m.push(`
9
+ `);}let w=m.join("").trim();r[u]={author:c,text:w,date:d,resolved:f,parent_id:_};}let a=t.parts.find(l=>l.contentType===ee.EXTENDED);if(a){let l=a._element.childNodes;for(let u=0;u<l.length;u++){let c=l[u];if(c.nodeType!==1)continue;let d=c.getAttribute("w15:paraId"),f=c.getAttribute("w15:paraIdParent"),h=c.getAttribute("w15:done");if(d){let _=o[d];if(_&&r[_]){if(f){let p=o[f];p&&(r[_].parent_id=p);}(h==="1"||h==="true"||h==="on")&&(r[_].resolved=true);}}}}return r}g(Me,"extract_comments_data");var Sn=500,tt=200,ua=["{++","++}","{--","--}","{==","==}","{>>","<<}"];function qi(t){if(!t||!t.includes("{")&&!t.includes("}"))return t;for(let e of ua)if(t.includes(e)){let n=e.startsWith("{")?"{ "+e.slice(1):e.slice(0,-1)+" }";t=t.split(e).join(n);}return t}g(qi,"escape_critic_tokens");function Fr(t,e){return t.length<=e?t:t.slice(0,Math.max(1,e-3))+"..."}g(Fr,"clamp_text");function de(t,e){if(t==null||t.length<=e)return t;let n=Math.max(1,Math.floor(e*2/3)),r=Math.max(1,e-n),i=t.length-n-r;return `${t.slice(0,n)}\u2026 [${i.toLocaleString("en-US")} chars omitted] \u2026${t.slice(-r)}`}g(de,"truncate_middle");var da={"\u201C":'"',"\u201D":'"',"\u2018":"'","\u2019":"'"},fa=/[\u201c\u201d\u2018\u2019]/g;function Wr(t){return t&&t.replace(fa,e=>da[e])}g(Wr,"normalize_smart_quotes");function Fn(t){return !!t&&/[\u201c\u201d\u2018\u2019]/.test(t)}g(Fn,"has_smart_quotes");function ha(t,e){if(!t||!e||!Fn(t))return e;let n=Wr(t),r=Wr(e);if(n===r)return t;let o=new Xi.diff_match_patch().diff_main(n,r),s=[],a=0,l=0;for(let[u,c]of o)u===0?(s.push(t.substr(a,c.length)),a+=c.length,l+=c.length):u===-1?a+=c.length:(s.push(e.substr(l,c.length)),l+=c.length);return s.join("")}g(ha,"restore_document_typography");function pa(t,e,n){return !n||!t||!Fn(t)||Fn(e||"")?n:ha(t,n)}g(pa,"restore_matched_typography");var ir=2e3,je=class extends Error{static{g(this,"RegexTimeoutError");}pattern;constructor(t){super(`Regular expression exceeded the ${ir/1e3}s matching time budget (catastrophic backtracking). Simplify the pattern \u2014 nested quantifiers like (a+)+ are the usual cause \u2014 or use a literal target instead.`),this.name="RegexTimeoutError",this.pattern=t;}};function Gi(t){let e=false,n=false,r=[];for(let i=0;i<t.length;i++){let o=t[i];if(n){n=false;continue}if(o==="\\"){n=true;continue}if(e){o==="]"&&(e=false);continue}if(o==="["){e=true;continue}if(o==="("){r.push({hasInnerQuantifierOrPipe:false});continue}if(o===")"){if(r.length>0){let s=r.pop(),a=t.substring(i+1),l=a.match(/^(\*|\+|\{\d+\,\s*\}|\?)/),u=l?l[1]:"",c=u==="*"||u==="+"||/^\{\d+\,\s*\}/.test(a);if(c&&s.hasInnerQuantifierOrPipe)return true;r.length>0&&(s.hasInnerQuantifierOrPipe||c)&&(r[r.length-1].hasInnerQuantifierOrPipe=true);}continue}r.length>0&&(o==="|"||o==="*"||o==="+"||/^\{\d+\,\s*\}/.test(t.substring(i)))&&(r[r.length-1].hasInnerQuantifierOrPipe=true);}return false}g(Gi,"hasCatastrophicBacktrackingRisk");function _a(t,e,n=""){if(Gi(t))throw new je(t);let r=n.includes("g")?n:n+"g",i=new RegExp(t,r),o=Date.now(),s=[],a;for(;(a=i.exec(e))!==null;){if(Date.now()-o>ir)throw new je(t);s.push({start:a.index,end:a.index+a[0].length}),a.index===i.lastIndex&&i.lastIndex++;}return s}g(_a,"userFindAllMatches");function ma(t,e,n=""){if(Gi(t))throw new je(t);let r=new RegExp(t,n.replace("g","")),i=Date.now(),o=r.exec(e);if(Date.now()-i>ir)throw new je(t);return o?{start:o.index,end:o.index+o[0].length}:null}g(ma,"userSearch");var Ji="w:p",or="w:r",tn="w:t",ga="w:delText",wa="w:tab",ya="w:br",va="w:cr",Ut="\f",nn="w:rPr",ba="w:rPrChange",xa="w:commentReference",Na="w:footnoteReference",ka="w:endnoteReference",Ea="w:fldChar",Aa="w:fldCharType",Ca="w:instrText",Pa="w:ins",Yi="w:del",Se="w:id",In="w:author",On="w:date",Ta="w:commentRangeStart",$a="w:commentRangeEnd",Sa="w:hyperlink",Ia="r:id",Oa="w:fldSimple",Da="w:instr",Ra="w:bookmarkStart",Ma="w:name",At="w:sdt",ja="w:smartTag",sr="w:sdtContent",Qi="w:b",Ba="w:i",le="w:val",ar="w:pPr",Vi="w:pStyle",Zi="w:outlineLvl",Fa="w:numPr",Wa="w:numId",La="w:ilvl",Wn="w:drawing",Ln="w:object",zn="w:pict",za="wp:docPr",Ua="v:imagedata",Ha="o:title",Xa="w:txbxContent",qa="mc:AlternateContent",Ga="mc:Choice",Ja="mc:Fallback",Lr=300;function zr(t){let e=[];for(let r of R(t,Xa))for(let i of R(r,tn))i.textContent&&e.push(i.textContent);let n=e.join(" ").split(/\s+/).filter(Boolean).join(" ");return n.length>Lr&&(n=n.slice(0,Lr).trimEnd()+"\u2026"),n}g(zr,"_textbox_text");function*Ur(t){let e=t.tagName;if(e===Wn||e===Ln){let n=R(t,za)[0]||null,r="",i="0";n&&(r=n.getAttribute("descr")||n.getAttribute("title")||"",i=n.getAttribute("id")||"0");let o=zr(t);o&&(r=r?`Text box (${r}): ${o}`:`Text box: ${o}`),yield {type:"image",id:i,date:r};}else if(e===zn){let n=R(t,Ua)[0]||null,r=n&&n.getAttribute(Ha)||"",i=zr(t);i&&(r=r?`Text box (${r}): ${i}`:`Text box: ${i}`),(i||n)&&(yield {type:"image",id:"vml",date:r});}}g(Ur,"_graphic_marker_events");var Ya=/Heading[ ]?([1-6])(?![0-9])/;function Qa(t){let e=t,n=new Set;for(;e&&!n.has(e);){if(n.add(e),e.package)return e.package;if(e.pkg)return e.pkg;if(e.part&&(e.part.package||e.part.pkg))return e.part.package||e.part.pkg;e=e._parent||e.part||null;}return null}g(Qa,"_resolve_package");function lt(t){let e=t.package||t.pkg||(t.part?t.part.pkg:null);if(e&&e._adeu_style_cache)return e._adeu_style_cache;let n={},r=null,i={},o=e?.getPartByPath("word/styles.xml");if(!o){let u=[n,null];return e&&(e._adeu_style_cache=u),u}let s=R(o._element,"w:style");for(let u of s){let c=u.getAttribute("w:styleId");if(!c)continue;let d=u.getAttribute("w:type"),f=u.getAttribute("w:default")==="1"||u.getAttribute("w:default")==="true";d==="paragraph"&&f&&(r=c);let h=O(u,"w:name"),_=h?h.getAttribute("w:val"):c;_&&typeof _=="string"&&(_.toLowerCase().startsWith("heading")?_=_.replace(/^heading/i,"Heading"):_.toLowerCase()==="title"&&(_="Title"));let p=O(u,"w:basedOn"),m=p?p.getAttribute("w:val"):null,w=null,v=null,b=null,y=O(u,"w:pPr");if(y){let N=O(y,"w:outlineLvl");if(N){let A=N.getAttribute("w:val");A&&/^\d+$/.test(A)&&(w=parseInt(A,10));}let P=O(y,"w:numPr");if(P){let A=O(P,"w:numId");if(A){let T=A.getAttribute("w:val");T&&T!=="0"&&(v=T);}let C=O(P,"w:ilvl");if(C){let T=C.getAttribute("w:val");T&&/^\d+$/.test(T)&&(b=parseInt(T,10));}}}let x=null,k=O(u,"w:rPr");if(k){let N=O(k,"w:b");if(N){let P=N.getAttribute("w:val");x=P!=="0"&&P!=="false"&&P!=="off";}}i[c]={name:_,based_on:m,outline_level:w,bold:x,num_id:v,num_ilvl:b};}let a=g((u,c)=>{if(n[u])return n[u];if(c.has(u)||!i[u])return {name:u,outline_level:null,bold:false,num_id:null,num_ilvl:null};c.add(u);let d=i[u],f=d.based_on,h=d.outline_level,_=d.bold!==null?d.bold:false,p=d.num_id,m=d.num_ilvl;if(f){let v=a(f,c);h===null&&(h=v.outline_level),d.bold===null&&(_=v.bold),p===null&&(p=v.num_id??null),m===null&&(m=v.num_ilvl??null);}let w={name:d.name,outline_level:h,bold:_,num_id:p,num_ilvl:m};return n[u]=w,w},"resolve_style");for(let u in i)a(u,new Set);let l=[n,r];return e&&(e._adeu_style_cache=l),l}g(lt,"_get_style_cache");function Va(t){let e=Qa(t);if(!e)return {};if(e._adeu_numbering_cache)return e._adeu_numbering_cache;let n={},r=null;try{let i=(e.parts||[]).find(o=>String(o.partname).endsWith("/numbering.xml"));i&&(r=i._element);}catch{r=null;}if(r){let i={};for(let o of R(r,"w:abstractNum")){let s=o.getAttribute("w:abstractNumId");if(s===null)continue;let a={};for(let l of R(o,"w:lvl")){let u=l.getAttribute("w:ilvl"),c=O(l,"w:numFmt");if(u!==null&&/^-?\d+$/.test(u)&&c){let d=c.getAttribute("w:val");d&&(a[parseInt(u,10)]=d);}}i[s]=a;}for(let o of R(r,"w:num")){let s=o.getAttribute("w:numId"),a=O(o,"w:abstractNumId");if(s===null||!a)continue;let l=a.getAttribute("w:val");l!==null&&i[l]!==void 0&&(n[s]=i[l]);}}return e._adeu_numbering_cache=n,n}g(Va,"_get_numbering_cache");function Za(t,e,n){let r=null;if(e!=null){let i=Va(t)[e];if(i&&Object.keys(i).length>0&&(r=i[n]!==void 0?i[n]:null,r===null)){for(let o=n;o>=0;o--)if(i[o]!==void 0){r=i[o];break}}}return r!==null&&r!=="bullet"?"1. ":"* "}g(Za,"get_list_marker");function Ki(t){if(!t)return null;let e=t.match(Ya);return e?parseInt(e[1],10):null}g(Ki,"_detect_heading_level_from_name");function eo(t){let e=O(t,ar);if(!e)return false;let n=O(e,nn);return !!n&&!!O(n,Yi)}g(eo,"paragraph_mark_is_deleted");function rn(t,e,n){e||([e,n]=lt(t._parent.part||t._parent));let r=O(t._element,ar);if(r){let a=O(r,Zi);if(a){let l=a.getAttribute(le);if(l&&/^\d+$/.test(l)){let u=parseInt(l,10);if(u>=0&&u<=8)return true}}}let i=n;if(r){let a=O(r,Vi);a&&(i=a.getAttribute(le)||n);}let o=i&&e?e[i]:null;if(o&&o.outline_level!==null&&o.outline_level>=0&&o.outline_level<=8)return true;let s=o?o.name:i;return s&&typeof s=="string"&&s.toLowerCase().startsWith("heading")&&(s=s.replace(/^heading/i,"Heading")),!!(s?.startsWith("Heading")||s==="Title"||s&&s!=="Normal"&&Ki(s)!==null)}g(rn,"is_native_heading");function We(t,e,n){e||([e,n]=lt(t._parent.part||t._parent));let r=O(t._element,ar);if(r){let c=O(r,Zi);if(c){let d=c.getAttribute(le);if(d&&/^\d+$/.test(d)){let f=parseInt(d,10);if(f>=0&&f<=8)return "#".repeat(f+1)+" "}}}let i=n;if(r){let c=O(r,Vi);c&&(i=c.getAttribute(le)||n);}let o=i&&e?e[i]:null;if(o&&o.outline_level!==null&&o.outline_level>=0&&o.outline_level<=8)return "#".repeat(o.outline_level+1)+" ";let s=o?o.name:i;if(s&&typeof s=="string"&&s.toLowerCase().startsWith("heading")&&(s=s.replace(/^heading/i,"Heading")),s?.startsWith("Heading")){let c=s.replace("Heading","").trim();if(/^\d+$/.test(c))return "#".repeat(parseInt(c,10))+" "}if(s==="Title")return "# ";let a=null,l=null,u=false;if(r){let c=O(r,Fa);if(c){let d=O(c,Wa);if(d){let f=d.getAttribute(le);if(f==="0")u=true;else if(f){a=f;let h=O(c,La);if(h){let _=h.getAttribute(le);_!==null&&/^\d+$/.test(_)&&(l=parseInt(_,10));}}}}}if(a===null&&!u&&o){let c=o.num_id;c&&(a=c,l===null&&(l=o.num_ilvl!==void 0?o.num_ilvl:null));}if(a!==null){let c=l!==null?l:0,d=Za(t._parent?t._parent.part||t._parent:null,a,c);return " ".repeat(c)+d}if(s&&s!=="Normal"){let c=Ki(s);if(c!==null)return "#".repeat(c)+" "}if(!s||s==="Normal"){let c=false,d=t._element;for(;d;){if(d.tagName==="w:tc"){c=true;break}d=d.parentNode;}if(c)return "";let f=t.text.trim();if(f&&f.length<100&&f===f.toUpperCase()){let h=false;if(o?.bold)h=true;else {let _=R(t._element,or);for(let p of _)if(R(p,tn).map(v=>v.textContent||"").join("").trim()){let v=O(p,nn);if(v){let b=O(v,Qi);b&&b.getAttribute(le)!=="0"&&b.getAttribute(le)!=="false"&&(h=true);}break}}if(h)return "## "}}return ""}g(We,"get_paragraph_prefix");function to(t,e,n){let r=We(t,e,n);if(!r)return false;let i=r.trimEnd();return i.length>0&&i==="#".repeat(i.length)}g(to,"is_heading_paragraph");function no(t,e=null){if(t.projTextOverride!==void 0)return ["",""];let n="",r="",i=O(t._element,nn),o=false,s=false;if(i){let a=O(i,Qi);a&&a.getAttribute(le)!=="0"&&a.getAttribute(le)!=="false"&&(o=true);let l=O(i,Ba);l&&l.getAttribute(le)!=="0"&&l.getAttribute(le)!=="false"&&(s=true);}if(e===null){let a=t._parent;e=a instanceof ne?rn(a):false;}return o&&!e&&(n+="**",r="**"+r),s&&(n+="_",r="_"+r),[n,r]}g(no,"get_run_style_markers");function ro(t){let e=t.trim();if(!e)return ["","",t];let n=t.length-t.trimStart().length;return [t.substring(0,n),t.substring(n,n+e.length),t.substring(n+e.length)]}g(ro,"split_boundary_whitespace");function io(t){let e=[],n=[],r=new Set;for(let[o,s]of t){let a=Object.entries(o),l=Object.entries(s);if(a.length===0&&l.length===0){n.length>0&&(e.push(n),n=[]);continue}let u=[];for(let[c,d]of a)r.has(c)||u.push([c,d&&d.author||"Unknown"]);for(let[c,d]of l)r.has(c)||u.push([c,d&&d.author||"Unknown"]);for(let[c,d]of u)r.add(c),n.length>0&&n[n.length-1][1]!==d&&(e.push(n),n=[]),n.push([c,d]);}n.length>0&&e.push(n);let i={};for(let o of e)if(!(o.length<2))for(let[s]of o)i[s]=o.filter(([a])=>a!==s).map(([a])=>`Chg:${a}`).join(", ");return i}g(io,"compute_change_pair_map");function Ka(t,e,n){if(!e&&!n)return t;if(!t)return "";let r=g(o=>{let[s,a,l]=ro(o);return a?`${s}${e}${a}${n}${l}`:o},"wrap");return t.includes(`
10
10
  `)?t.split(`
11
- `).map(i=>i?r(i):"").join(`
12
- `):r(t)}g($o,"apply_formatting_to_segments");function Me(t){let e="";for(let n=0;n<t._element.childNodes.length;n++){let r=t._element.childNodes[n];if(r.nodeType===1)if(r.tagName===vn||r.tagName===Gs){let s=r.textContent||"";e+=s.replace(/\t/g," ");}else r.tagName===Qs?e+=" ":(r.tagName===Ys||r.tagName===Vs)&&(e+=`
13
- `);}return e}g(Me,"get_run_text");function*Oe(t){let e=t._element||t.element||t;if(t.constructor.name==="NotesPart"){let n=t.note_type==="fn"?"w:footnote":"w:endnote",r=M(e,n);for(let s of r){if(s.getAttribute("w:type")==="separator"||s.getAttribute("w:type")==="continuationSeparator")continue;let i=s.getAttribute("w:id");i!==null&&/^\s*[-+]?\d+\s*$/.test(i)&&parseInt(i,10)<=0||(yield new Bs(s,t,t.note_type));}return}yield*Qr(e,t);}g(Oe,"iter_block_items");function*Qr(t,e){for(let n=0;n<t.childNodes.length;n++){let r=t.childNodes[n];if(r.nodeType===1){if(r.tagName===Xs)yield new ie(r,e);else if(r.tagName==="w:tbl")yield new Se(r,e);else if(r.tagName===Br){let s=B(r,Fr);s&&(yield*Qr(s,e));}}}}g(Qr,"_iter_block_children");function*Oo(t){for(let[e]of xn(t))yield e;}g(Oo,"iter_document_parts");function*xn(t){let e=t.pkg.parts.filter(i=>i.contentType==="application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml");for(let i of e)yield [i,"header"];yield [t,"body"];let n=t.pkg.parts.filter(i=>i.contentType==="application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml");for(let i of n)yield [i,"footer"];let r=t.pkg.getPartByPath("word/footnotes.xml"),s=t.pkg.getPartByPath("word/endnotes.xml");r&&(yield [new Jn(r,"fn"),"footnotes"]),s&&(yield [new Jn(s,"en"),"endnotes"]);}g(xn,"iter_document_parts_with_kind");function Do(t){if(!t)return false;let e=t.toUpperCase().trim().split(/\s+/);return e.length>0&&(e[0]==="PAGE"||e[0]==="NUMPAGES")}g(Do,"_is_page_instr");function Yr(t){return t?t.part?t.part:t.pkg&&t.pkg.mainDocumentPart?t.pkg.mainDocumentPart:t._parent?Yr(t._parent):null:null}g(Yr,"_get_part");function*Pt(t){let e=false,n="",r=false;function*s(o){let l=null,a=B(o,bn);if(a){let u=B(a,Zs);u&&(l=u.getAttribute(Ee),yield {type:"fmt_start",id:l,author:u.getAttribute(Vt)||void 0,date:u.getAttribute(Zt)||void 0});}for(let u=0;u<o.childNodes.length;u++){let c=o.childNodes[u];if(c.nodeType!==1)continue;let d=c.tagName;if(d===on||d===an||d===ln)yield*Kn(c);else if(d===Eo){let f=null;for(let h of [Ao,Co]){for(let _ of Pr(c,h))if(f=B(_,on)||B(_,an)||B(_,ln),f)break;if(f)break}f&&(yield*Kn(f));}else if(d===Ks){let f=c.getAttribute(Ee);f&&(yield {type:"ref",id:f});}else if(d===eo){let f=c.getAttribute(Ee);f&&(yield {type:"footnote",id:f});}else if(d===to){let f=c.getAttribute(Ee);f&&(yield {type:"endnote",id:f});}else if(d===no){let f=c.getAttribute(ro);if(f==="begin")e=true,n="";else if(f==="separate")if(Do(n))r=true;else {let h=n.trim().split(/\s+/);h.length>1&&h[0]==="REF"&&(yield {type:"xref_start",id:h[1]});}else if(f==="end"){if(!r){let h=n.trim().split(/\s+/);h.length>1&&h[0]==="REF"&&(yield {type:"xref_end",id:h[1]});}e=false,n="",r=false;}}else d===io&&e&&!r&&(n+=c.textContent||"");}r||(yield new Ce(o,t)),l!==null&&(yield {type:"fmt_end",id:l});}g(s,"process_run_element");function*i(o){for(let l=0;l<o.childNodes.length;l++){let a=o.childNodes[l];if(a.nodeType!==1)continue;let u=a.tagName;if(u===jr)yield*s(a);else if(u===so){let c=a.getAttribute(Ee);yield {type:"ins_start",id:c,author:a.getAttribute(Vt)||void 0,date:a.getAttribute(Zt)||void 0},yield*i(a),yield {type:"ins_end",id:c};}else if(u===oo){let c=a.getAttribute(Ee);yield {type:"del_start",id:c,author:a.getAttribute(Vt)||void 0,date:a.getAttribute(Zt)||void 0},yield*i(a),yield {type:"del_end",id:c};}else if(u===ao)yield {type:"start",id:a.getAttribute(Ee)};else if(u===lo)yield {type:"end",id:a.getAttribute(Ee)};else if(u===co){let c=a.getAttribute(uo)||a.getAttribute("id"),d="",f=Yr(t._parent);if(c&&f){let h=f.rels.get(c);h&&h.isExternal&&(d=h.target);}d&&(yield {type:"hyperlink_start",id:c,date:d}),yield*i(a),d&&(yield {type:"hyperlink_end",id:c,date:d});}else if(u===fo){let d=(a.getAttribute(ho)||"").trim().split(/\s+/),f=d.length>1&&d[0]==="REF"?d[1]:"";f&&(yield {type:"xref_start",id:f}),yield*i(a),f&&(yield {type:"xref_end",id:f});}else if(u===po){let c=a.getAttribute(_o);c&&(!c.startsWith("_")||c.startsWith("_Ref"))&&(yield {type:"bookmark",id:c});}else (u===Br||u===mo||u===Fr)&&(yield*i(a));}}g(i,"traverse_node"),yield*i(t._element);}g(Pt,"iter_paragraph_content");var Mo=new Set(["**","__","*","_"]),ve=class{static{g(this,"DocumentMapper");}doc;clean_view;original_view;comments_map;full_text="";spans=[];appendix_start_index=-1;part_ranges=[];_current_part_index=0;_text_chunks=[];_plain_projection=null;constructor(t,e=false,n=false){this.doc=t,this.clean_view=e,this.original_view=n,this.comments_map=Pe(t.pkg),this._build_map();}_build_map(){let t=0;this.spans=[],this._text_chunks=[],this.full_text="",this._plain_projection=null,this.part_ranges=[],this._current_part_index=0;let e=0;for(let[n,r]of xn(this.doc)){this._current_part_index=e;let s=t;t=this._map_blocks(n,t),this.part_ranges.push([s,t,r]),this.spans.length>0&&this.spans[this.spans.length-1].text!==`
11
+ `).map(o=>o?r(o):"").join(`
12
+ `):r(t)}g(Ka,"apply_formatting_to_segments");function el(t,e){let n=t.parentNode;for(;n;){let r=n.tagName;if(r==="w:ins"||r==="w:del")return e==="\u2611"||e==="\u2612"?"x":" ";n=n.parentNode;}}g(el,"revisionBallotMark");function tl(t){let e=O(t,sr);if(!e)return false;for(let n of R(e,or)){let r="";for(let i of R(n,tn))r+=i.textContent||"";if(Bi.has(r))return true}return false}g(tl,"hasBallotRun");function nl(t,e,n){if(!n||!Bi.has(e))return;let r=t.parentNode;for(;r&&r.nodeType===1;){if(r.tagName===At){let i=n.get(r);return i&&i.cls==="checkbox"?i:void 0}r=r.parentNode;}}g(nl,"enclosingCheckbox");function Pe(t){if(t.projTextOverride!==void 0)return t.projTextOverride;let e="";for(let n=0;n<t._element.childNodes.length;n++){let r=t._element.childNodes[n];if(r.nodeType===1)if(r.tagName===tn||r.tagName===ga){let i=r.textContent||"";e+=i.replace(/\t/g," ");}else r.tagName===wa||r.tagName==="w:ptab"?e+=" ":r.tagName==="w:noBreakHyphen"?e+="-":r.tagName===ya?e+=r.getAttribute("w:type")==="page"?Ut:`
13
+ `:r.tagName===va&&(e+=`
14
+ `);}return e}g(Pe,"get_run_text");function*Le(t,e=false){let n=t._element||t.element||t;if(t.constructor.name==="NotesPart"){let r=t.note_type==="fn"?"w:footnote":"w:endnote",i=R(n,r);for(let o of i){if(o.getAttribute("w:type")==="separator"||o.getAttribute("w:type")==="continuationSeparator")continue;let s=o.getAttribute("w:id");s!==null&&/^\s*[-+]?\d+\s*$/.test(s)&&parseInt(s,10)<=0||(yield new ta(o,t,t.note_type));}return}yield*oo(n,t,e);}g(Le,"iter_block_items");function*oo(t,e,n=false){for(let r=0;r<t.childNodes.length;r++){let i=t.childNodes[r];if(i.nodeType===1){if(i.tagName===Ji)yield new ne(i,e);else if(i.tagName==="w:tbl")yield new Fe(i,e);else if(i.tagName===At){let o=O(i,sr);o&&(n?yield new rr(i):yield*oo(o,e,n));}}}}g(oo,"_iter_block_children");function*rl(t){for(let[e]of qe(t))yield e;}g(rl,"iter_document_parts");function*il(t){let e=t.element;function*n(i){for(let o=0;o<i.childNodes.length;o++){let s=i.childNodes[o];if(s.nodeType===1){if(s.tagName===Ji){let a=O(s,"w:pPr"),l=a&&O(a,"w:sectPr");l&&(yield l);}else if(s.tagName===At){let a=O(s,"w:sdtContent");a&&(yield*n(a));}}}}g(n,"walk"),yield*n(e);let r=O(e,"w:sectPr");r&&(yield r);}g(il,"_iter_sect_pr");function ol(t){let e=t.pkg.getPartByPath("word/settings.xml");return e?O(e._element,"w:evenAndOddHeaders")!==null:false}g(ol,"_odd_and_even_pages");function*Hr(t,e){let n=e==="header"?"w:headerReference":"w:footerReference",r=ol(t);for(let i of il(t)){let o=Vn(i,n),s=g(u=>o.find(c=>(c.getAttribute("w:type")||"default")===u),"byType"),a=g(u=>{if(!u)return;let c=u.getAttribute("r:id");if(!c)return;let d=t.part.rels.get(c);if(!d)return;let f=d.target.replace(/^\/?word\//,"").replace(/^\//,"");return t.pkg.getPartByPath("word/"+f)},"resolve"),l=a(s("default"));if(l&&(yield l),O(i,"w:titlePg")!==null){let u=a(s("first"));u&&(yield u);}if(r){let u=a(s("even"));u&&(yield u);}}}g(Hr,"_iter_section_parts");function*qe(t){for(let r of Hr(t,"header"))yield [r,"header"];yield [t,"body"];for(let r of Hr(t,"footer"))yield [r,"footer"];let e=t.pkg.getPartByPath("word/footnotes.xml"),n=t.pkg.getPartByPath("word/endnotes.xml");e&&(yield [new Mr(e,"fn"),"footnotes"]),n&&(yield [new Mr(n,"en"),"endnotes"]);}g(qe,"iter_document_parts_with_kind");function sl(t){if(!t)return false;let e=t.toUpperCase().trim().split(/\s+/);return e.length>0&&(e[0]==="PAGE"||e[0]==="NUMPAGES")}g(sl,"_is_page_instr");function so(t){return t?t.part?t.part:t.pkg&&t.pkg.mainDocumentPart?t.pkg.mainDocumentPart:t._parent?so(t._parent):null:null}g(so,"_get_part");function*on(t,e){let n=false,r="",i=false,o=[];function*s(l){let u=null,c=O(l,nn);if(c){let d=O(c,ba);d&&(u=d.getAttribute(Se),yield {type:"fmt_start",id:u,author:d.getAttribute(In)||void 0,date:d.getAttribute(On)||void 0});}for(let d=0;d<l.childNodes.length;d++){let f=l.childNodes[d];if(f.nodeType!==1)continue;let h=f.tagName;if(h===Wn||h===Ln||h===zn)yield*Ur(f);else if(h===qa){let _=null;for(let p of [Ga,Ja]){for(let m of Vn(f,p))if(_=O(m,Wn)||O(m,Ln)||O(m,zn),_)break;if(_)break}_&&(yield*Ur(_));}else if(h===xa){let _=f.getAttribute(Se);_&&(yield {type:"ref",id:_});}else if(h===Na){let _=f.getAttribute(Se);_&&(yield {type:"footnote",id:_});}else if(h===ka){let _=f.getAttribute(Se);_&&(yield {type:"endnote",id:_});}else if(h===Ea){let _=f.getAttribute(Aa);if(_==="begin")n=true,r="";else if(_==="separate")if(sl(r))i=true;else {let p=r.trim().split(/\s+/);p.length>1&&p[0]==="REF"&&(yield {type:"xref_start",id:p[1]});}else if(_==="end"){if(!i){let p=r.trim().split(/\s+/);p.length>1&&p[0]==="REF"&&(yield {type:"xref_end",id:p[1]});}n=false,r="",i=false;}}else h===Ca&&n&&!i&&(r+=f.textContent||"");}if(!i){let d=new Re(l,t);o.length&&(d.sdtStack=o.slice());let f=nl(l,Pe(d),e);if(f){let h=Pe(d);d.projTextOverride=el(l,h)??tr(f),yield {type:"checkbox_start",info:f},yield d,yield {type:"checkbox_end",info:f};}else yield d;}u!==null&&(yield {type:"fmt_end",id:u});}g(s,"process_run_element");function*a(l){for(let u=0;u<l.childNodes.length;u++){let c=l.childNodes[u];if(c.nodeType!==1)continue;let d=c.tagName;if(d===or)yield*s(c);else if(d===Pa){let f=c.getAttribute(Se);yield {type:"ins_start",id:f,author:c.getAttribute(In)||void 0,date:c.getAttribute(On)||void 0},yield*a(c),yield {type:"ins_end",id:f};}else if(d===Yi){let f=c.getAttribute(Se);yield {type:"del_start",id:f,author:c.getAttribute(In)||void 0,date:c.getAttribute(On)||void 0},yield*a(c),yield {type:"del_end",id:f};}else if(d===Ta)yield {type:"start",id:c.getAttribute(Se)};else if(d===$a)yield {type:"end",id:c.getAttribute(Se)};else if(d===Sa){let f=c.getAttribute(Ia)||c.getAttribute("id"),h="",_=so(t._parent);if(f&&_){let p=_.rels.get(f);p&&p.isExternal&&(h=p.target);}h&&(yield {type:"hyperlink_start",id:f,date:h}),yield*a(c),h&&(yield {type:"hyperlink_end",id:f,date:h});}else if(d===Oa){let h=(c.getAttribute(Da)||"").trim().split(/\s+/),_=h.length>1&&h[0]==="REF"?h[1]:"";_&&(yield {type:"xref_start",id:_}),yield*a(c),_&&(yield {type:"xref_end",id:_});}else if(d===Ra){let f=c.getAttribute(Ma);f&&(!f.startsWith("_")||f.startsWith("_Ref"))&&(yield {type:"bookmark",id:f});}else if(d===At||d===ja||d===sr){let f=e?e.get(c):void 0,h=!!f&&d===At;h&&o.push(f);try{f&&f.cls==="checkbox"&&!tl(c)?(yield {type:"checkbox_start",info:f},yield {type:"checkbox_mark",info:f},yield {type:"checkbox_end",info:f}):!f||!kt(f)?yield*a(c):(yield {type:"sdt_start",info:f},f.showingPlaceholder||(yield*a(c)),yield {type:"sdt_end",info:f});}finally{h&&o.pop();}}}}g(a,"traverse_node"),yield*a(t._element);}g(on,"iter_paragraph_content");var al=new Set(["**","__","*","_"]),ke=class{static{g(this,"DocumentMapper");}doc;clean_view;original_view;comments_map;full_text="";spans=[];appendix_start_index=-1;part_ranges=[];_current_part_index=0;_current_block_sdt_stack=[];control_ranges=[];_sdt_infos=new Map;_text_chunks=[];_plain_projection=null;constructor(t,e=false,n=false){this.doc=t,this.clean_view=e,this.original_view=n,this.comments_map=Me(t.pkg),this._build_map();}_build_map(){let t=0;this.spans=[],this._text_chunks=[],this.full_text="",this._plain_projection=null,this.part_ranges=[],this._current_part_index=0,this._current_block_sdt_stack=[],this.control_ranges=[],this._sdt_infos=Kt(Array.from(qe(this.doc)).map(([r])=>en(r)));let e=0,n=false;for(let[r,i]of qe(this.doc)){this._current_part_index=e;let o=this.spans.length,s=this._text_chunks.length,a=t;n&&(this._add_virtual_text(`
14
15
 
15
- `&&(this._add_virtual_text(`
16
+ `,t,null),t+=2);let l=t;t=this._map_blocks(r,t),t===l?(this.spans.length=o,this._text_chunks.length=s,t=a,this.part_ranges.push([t,t,i])):(n=true,this.part_ranges.push([l,t,i])),e++;}this.full_text=this._text_chunks.join(""),this._buildControlRanges(),this.appendix_start_index=-1;}_spanSdtStack(t){let e=this._current_block_sdt_stack,n=t?.sdtStack??[];return e.length===0?n:n.length===0?e.slice():[...e,...n]}_buildControlRanges(){let t=new Map;for(let e of this.spans)if(!(!e.sdt_stack||e.sdt_stack.length===0))for(let n of e.sdt_stack){let r=t.get(n);r===void 0?t.set(n,[e.start,e.end]):(e.start<r[0]&&(r[0]=e.start),e.end>r[1]&&(r[1]=e.end));}this.control_ranges=Array.from(t.entries()).map(([e,[n,r]])=>[n,r,e]).sort((e,n)=>e[0]-n[0]||n[1]-e[1]);}controls_at(t){return this.control_ranges.filter(([e,n])=>e<=t&&t<n).map(([,,e])=>e)}controls_intersecting(t,e){if(e<=0)return [];let n=t+e;return this.control_ranges.filter(([r,i])=>i>t&&r<n).map(([,,r])=>r)}_nonempty_part_ranges(){let t=[];for(let e=0;e<this.part_ranges.length;e++){let[n,r,i]=this.part_ranges[e];r>n&&t.push([e,n,r,i]);}return t}part_kind_of(t){return t>=0&&t<this.part_ranges.length?this.part_ranges[t][2]:null}part_kind_at(t){for(let[,e,n,r]of this._nonempty_part_ranges())if(e<=t&&t<=n)return r;return null}part_boundary_at(t){let e=this._nonempty_part_ranges();for(let n=1;n<e.length;n++){let[r,,i]=e[n-1],[o,s]=e[n];if(i<t&&t<=s)return [r,o]}return null}_map_blocks(t,e,n=false){let r=e,i=t.constructor.name,o=t.part||t,[s,a]=lt(o),l=false;if(i==="NotesPart"){let f=`---
17
+ ${t.note_type==="fn"?"## Footnotes":"## Endnotes"}`;this._add_virtual_text(f,r,null),r+=f.length,l=true;}let u=true,c=null;for(let d of Le(t,true)){let f=d.constructor.name,h=this.spans.length,_=this._text_chunks.length,p=r;if(d instanceof rr){if(l){let y=c instanceof ne?c:null;this._add_virtual_text(`
16
18
 
17
- `,t,null),t+=2),e++;}for(;this.spans.length>0&&this.spans[this.spans.length-1].text===`
19
+ `,r,y),r+=2;}let m=this._sdt_infos.get(d.element),w=!!m&&kt(m),v=n?"":`
20
+ `;if(w){let y=`${Oe(m)}${v}`;this._add_virtual_text(y,r,null),r+=y.length;}let b=r;m&&this._current_block_sdt_stack.push(m);try{r=this._map_blocks({_element:O(d.element,"w:sdtContent"),part:t.part||t},r,n);}finally{m&&this._current_block_sdt_stack.pop();}if(r===b)this.spans.length=h,this._text_chunks.length=_,r=p;else {if(w){let y=`${v}${De(m)}`;this._add_virtual_text(y,r,null),r+=y.length;}l=true;}u=false;}else if(f==="FootnoteItem"){if(l){let w=c instanceof ne?c:null;this._add_virtual_text(`
18
21
 
19
- `;)this.spans.pop(),this._text_chunks.pop();this.full_text=this._text_chunks.join(""),this.appendix_start_index=-1;}_nonempty_part_ranges(){let t=[];for(let e=0;e<this.part_ranges.length;e++){let[n,r,s]=this.part_ranges[e];r>n&&t.push([e,n,r,s]);}return t}part_kind_of(t){return t>=0&&t<this.part_ranges.length?this.part_ranges[t][2]:null}part_kind_at(t){for(let[,e,n,r]of this._nonempty_part_ranges())if(e<=t&&t<=n)return r;return null}part_boundary_at(t){let e=this._nonempty_part_ranges();for(let n=1;n<e.length;n++){let[r,,s]=e[n-1],[i,o]=e[n];if(s<t&&t<=o)return [r,i]}return null}_map_blocks(t,e){let n=e,r=t.constructor.name,s=t.part||t,[i,o]=Qe(s);if(r==="NotesPart"){let c=`---
20
- ${t.note_type==="fn"?"## Footnotes":"## Endnotes"}`;this._add_virtual_text(c,n,null),n+=c.length,this._add_virtual_text(`
22
+ `,r,w),r+=2;}let m=r;r=this._map_blocks(d,r),r===m?(this.spans.length=h,this._text_chunks.length=_,r=p):l=true;}else if(d instanceof ne){if(l){let b=c instanceof ne?c:null;this._add_virtual_text(`
21
23
 
22
- `,n,null),n+=2;}let l=true,a=null;for(let u of Oe(t))if(u.constructor.name==="FootnoteItem")n=this._map_blocks(u,n);else if(u instanceof ie){if(!l){let f=a instanceof ie?a:null;this._add_virtual_text(`
24
+ `,r,b),r+=2;}let w=We(d,s,a);u&&i==="FootnoteItem"&&(w=`[^${t.note_type}-${t.id}]: `+w),w&&(this._add_virtual_text(w,r,d),r+=w.length);let v=r;if(r=this._map_paragraph_content(d,r,s,a),this.clean_view&&r===v&&eo(d._element)){this.spans.length=h,this._text_chunks.length=_,r=p,u=false;continue}u=false,l=true,c=d;}else if(d instanceof Fe){if(l){let w=c instanceof ne?c:null;this._add_virtual_text(`
23
25
 
24
- `,n,f),n+=2;}let d=$e(u,i,o);l&&r==="FootnoteItem"&&(d=`[^${t.note_type}-${t.id}]: `+d),d&&(this._add_virtual_text(d,n,u),n+=d.length),n=this._map_paragraph_content(u,n,i,o),l=false,a=u;}else if(u instanceof Se){if(!l){let d=a instanceof ie?a:null;this._add_virtual_text(`
26
+ `,r,w),r+=2;}let m=r;r=this._map_table(d,r),r===m?(this.spans.length=h,this._text_chunks.length=_,r=p):l=true,u=false,c=d;}}return r}_wrappingControl(t){let e=Ui(t);return e?this._sdt_infos.get(e)??null:null}_anchoredWrapper(t){let e=this._wrappingControl(t);return e&&kt(e)?e:null}_map_table(t,e){let n=e,r=0;for(let i of t.rows){let o=i._element,s=O(o,"w:trPr"),a=s?O(s,"w:ins"):null,l=s?O(s,"w:del"):null;if(this.clean_view&&l||this.original_view&&a)continue;r>0&&(this._add_virtual_text(`
27
+ `,n,null),n+=1),a&&!this.clean_view&&!this.original_view?(this._add_virtual_text("{++ ",n,null),n+=4):l&&!this.clean_view&&!this.original_view&&(this._add_virtual_text("{-- ",n,null),n+=4);let u=this._wrappingControl(o),c=this._anchoredWrapper(o);if(c){let h=Oe(c);this._add_virtual_text(h,n,null),n+=h.length;}let d=new Set,f=0;for(let h of i.cells){if(d.has(h))continue;d.add(h),f>0&&(this._add_virtual_text(" | ",n,null),n+=3);let _=this._wrappingControl(h._element),p=this._anchoredWrapper(h._element);if(p){let v=Oe(p);this._add_virtual_text(v,n,null),n+=v.length;}let m=n,w=[u,_].filter(v=>v!==null);this._current_block_sdt_stack.push(...w);try{n=this._map_blocks(h,n,!0);}finally{for(let v=0;v<w.length;v++)this._current_block_sdt_stack.pop();}if(p){let v=De(p);this._add_virtual_text(v,n,null),n+=v.length;}if(!this.clean_view&&!this.original_view){let{paraId:v,firstP:b}=Ri(h._element,n===m);if(v&&b){let y=new ne(b,h);if(this._add_virtual_text("",n,y),m<n){let k="";for(let N=this._text_chunks.length-1;N>=0;N--){let P=this._text_chunks[N];if(P){k=P[P.length-1];break}}k!==" "&&(this._add_virtual_text(" ",n,y),n+=1);}let x=`{#cell:${v}}`;this._add_virtual_text(x,n,y),n+=x.length;}}f+=1;}if(c){let h=De(c);this._add_virtual_text(h,n,null),n+=h.length;}if(a&&!this.clean_view&&!this.original_view){let h=` ++}{>>[Chg:${a.getAttribute("w:id")} insert] ${a.getAttribute("w:author")||"Unknown"}<<}`;this._add_virtual_text(h,n,null),n+=h.length;}else if(l&&!this.clean_view&&!this.original_view){let h=` --}{>>[Chg:${l.getAttribute("w:id")} delete] ${l.getAttribute("w:author")||"Unknown"}<<}`;this._add_virtual_text(h,n,null),n+=h.length;}if(r+=1,r===1){let h=new Set,_=0;for(let p of i.cells)h.has(p)||(h.add(p),_+=1);if(_>0){let p=Array(_).fill("---").join(" | ");this._add_virtual_text(`
28
+ `,n,null),n+=1,this._add_virtual_text(p,n,null),n+=p.length;}}}return n}_strip_markdown_formatting(t){let e=t;return e=e.replace(/^#+\s*/gm,""),e=e.replace(/\*\*(\w[\w\s]*\w|\w{2,})\*\*/g,"$1"),e=e.replace(/__(\w[\w\s]*\w|\w{2,})__/g,"$1"),e=e.replace(/(?<!\w)_(\w[\w\s]*\w|\w{2,})_(?!\w)/g,"$1"),e=e.replace(/(?<!\w)\*(\w[\w\s]*\w|\w{2,})\*(?!\w)/g,"$1"),e}_map_paragraph_content(t,e,n,r){let i=e,o={start:i,end:i,text:"",run:null,paragraph:t,part_index:this._current_part_index,sdt_stack:this._spanSdtStack()};this.spans.push(o);let s=new Set,a={},l={},u={},c=[],d=null,f=["",""],h=["",""],_=null,p=[],m=g(()=>{if(p.length===0)return;let[x,k]=f;x&&(this._add_virtual_text(x,i,t),i+=x.length);for(let[N,P,A,C,T,M,j]of p){if(N==="virtual")this._add_virtual_text(P,i,t,_);else {let B={start:i,end:i+P.length,text:P,run:A,paragraph:t,ins_id:T||void 0,del_id:M||void 0,hyperlink_id:_||void 0,comment_ids:j.length>0?j:void 0,part_index:this._current_part_index,run_offset:C,sdt_stack:this._spanSdtStack(A)};this.spans.push(B),this._text_chunks.push(P);}i+=P.length;}k&&(this._add_virtual_text(k,i,t),i+=k.length),p=[];},"flush_pending_runs"),w=Array.from(on(t,this._sdt_infos)),v=to(t,n,r),b=rn(t,n,r),y=v;for(let x=0;x<w.length;x++){let k=w[x];if(k instanceof Re){let[N,P]=no(k,b),A=[],C=Pe(k);if(y){if(C===""||/^\s*$/.test(C))continue;y=false;}let T=0,M=g(I=>{let[E,S,D]=ro(I);if(!S){A.push(["real",I,k,T]),T+=I.length;return}E&&(A.push(["real",E,k,T]),T+=E.length),N&&A.push(["virtual",N,null,0]),A.push(["real",S,k,T]),T+=S.length,P&&A.push(["virtual",P,null,0]),D&&(A.push(["real",D,k,T]),T+=D.length);},"append_wrapped");if(C.includes(`
29
+ `)&&(N||P)){let I=C.split(`
30
+ `);for(let E=0;E<I.length;E++)E>0&&(A.push(["real",`
31
+ `,k,T]),T+=1),I[E]&&M(I[E]);}else (N||P)&&C?M(C):C&&A.push(["real",C,k,0]);this.clean_view&&Object.keys(l).length>0,this.original_view&&Object.keys(a).length>0;let j=A.map(I=>I[1]).join(""),B=Object.keys(a).pop()||null,$=Object.keys(l).pop()||null;if(j&&!(this.clean_view&&$)&&!(this.original_view&&B)){let I=this.clean_view||this.original_view?["",""]:this._get_wrappers(B,$,s,u),E=[N,P];if(p.length>0&&I[0]===f[0]&&I[1]===f[1]){let S=g(z=>z.length>0&&/^\s+$/.test(z),"isWs"),D=A;if(E[0]===h[0]&&E[1]===h[1]&&!(h[0]===""&&h[1]==="")){let z=p.length-1;for(;z>=0&&p[z][0]==="real"&&S(p[z][1]);)z--;let W=z>=0&&p[z][0]==="virtual"&&p[z][1]===h[1],L=0;for(;L<A.length&&A[L][0]==="real"&&S(A[L][1]);)L++;let X=L<A.length&&A[L][0]==="virtual"&&A[L][1]===E[0];W&&X&&(p.splice(z,1),D=A.slice(0,L).concat(A.slice(L+1)));}let U=Array.from(s);for(let[z,W,L,X]of D)p.push([z,W,L,X,B,$,U]);h=E;}else {m(),f=I,h=E;let S=Array.from(s);for(let[D,U,z,W]of A)p.push([D,U,z,W,B,$,S]);}}if(!this.clean_view&&!this.original_view){(Object.keys(a).length>0||Object.keys(l).length>0||s.size>0||Object.keys(u).length>0)&&c.push([{...a},{...l},new Set(s),{...u}]);let E=false;if(B!==null||$!==null||Object.keys(u).length>0||s.size>0){let D=x+1,U=false,z=Object.keys(a).length,W=Object.keys(l).length,L=Object.keys(u).length,X=new Set(s);for(;D<w.length;){let q=w[D];if(q instanceof Re){if(!Pe(q)){D++;continue}(z>0||W>0||L>0||X.size>0)&&(U=true);break}else {let Y=q;Y.type==="ins_start"?z++:Y.type==="ins_end"?z=Math.max(0,z-1):Y.type==="del_start"?W++:Y.type==="del_end"?W=Math.max(0,W-1):Y.type==="fmt_start"?L++:Y.type==="fmt_end"?L=Math.max(0,L-1):Y.type==="start"?X.add(Y.id):Y.type==="end"&&X.delete(Y.id);}D++;}U&&(E=true);}if(!E&&c.length>0){let D=this._build_merged_meta_block(c);if(D)if(zi(w,x))d=D;else {m(),f=["",""],h=["",""];let U=`{>>${D}<<}`;this._add_virtual_text(U,i,t),i+=U.length;}c=[];}}}else if(nr(k)){y=false;let N=k.info;if(Li.includes(k.type)){if(this.clean_view&&Object.keys(l).length>0)continue;let A=k.type==="checkbox_start"?Fi:k.type==="checkbox_end"?Wi:tr(N),C=this.clean_view||this.original_view?["",""]:this._get_wrappers(Object.keys(a).pop()||null,Object.keys(l).pop()||null,s,u);if(p.length>0&&(C[0]!==f[0]||C[1]!==f[1])&&m(),p.length===0&&(f=C),p.push(["virtual",A,null,0,null,null,[]]),h=["",""],k.type==="checkbox_end"&&d){m(),f=["",""];let T=`{>>${d}<<}`;this._add_virtual_text(T,i,t),i+=T.length,d=null;}continue}m(),f=["",""],h=["",""];let P;k.type==="sdt_start"?(P=Oe(N),!this.clean_view&&N.showingPlaceholder&&N.placeholderText&&(P+=`{>>placeholder: ${N.placeholderText}<<}`)):P=De(N),this._add_virtual_text(P,i,t),i+=P.length;}else {let N=k;if(y=false,m(),f=["",""],h=["",""],N.type==="start")s.add(N.id);else if(N.type==="end")s.delete(N.id);else if(N.type==="ins_start")a[N.id]=N;else if(N.type==="ins_end")delete a[N.id];else if(N.type==="del_start")l[N.id]=N;else if(N.type==="del_end")delete l[N.id];else if(N.type==="fmt_start")u[N.id]=N;else if(N.type==="fmt_end")delete u[N.id];else if(N.type==="image"){if(!(this.clean_view&&Object.keys(l).length>0||this.original_view&&Object.keys(a).length>0)){let C=`![${(N.date||"image").replace(/\]/g,")").replace(/\n/g," ")}](docx-image:${N.id})`;this._add_virtual_text(C,i,t,null,true),i+=C.length;}}else if(N.type==="footnote"||N.type==="endnote"){m(),f=["",""],h=["",""];let A=`[^${N.type==="footnote"?"fn":"en"}-${N.id}]`;this._add_virtual_text(A,i,t),i+=A.length;}else if(N.type==="hyperlink_start")m(),f=["",""],h=["",""],this._add_virtual_text("[",i,t,N.id),i+=1,_=N.id;else if(N.type==="hyperlink_end"){m(),f=["",""],h=["",""];let P=`](${N.date})`;this._add_virtual_text(P,i,t,N.id),i+=P.length,_=null;}else if(N.type==="xref_start")m(),f=["",""],h=["",""],this._add_virtual_text("[~",i,t),i+=2;else if(N.type==="xref_end"){m(),f=["",""],h=["",""];let P=`~](#${N.id})`;this._add_virtual_text(P,i,t),i+=P.length;}else if(N.type==="bookmark"){m(),f=["",""],h=["",""];let P=`{#${N.id}}`;this._add_virtual_text(P,i,t),i+=P.length;}}}if(m(),c.length>0){let x=this._build_merged_meta_block(c);if(x){let k=`{>>${x}<<}`;this._add_virtual_text(k,i,t),i+=k.length;}}return i}_get_wrappers(t,e,n,r){return e?["{--","--}"]:t?["{++","++}"]:n.size>0||Object.keys(r).length>0?["{==","==}"]:["",""]}_build_merged_meta_block(t){let e=[],n=[],r=new Set,i=io(t),o=g(s=>i[s]?` (pairs with ${i[s]})`:"","pairSuffix");for(let[s,a,l,u]of t){for(let[d,f]of Object.entries(s)){let h=`Chg:${d}`;if(!r.has(h)){let _=f.author||"Unknown";e.push(`[${h} insert] ${_}${o(d)}`),r.add(h);}}for(let[d,f]of Object.entries(a)){let h=`Chg:${d}`;if(!r.has(h)){let _=f.author||"Unknown";e.push(`[${h} delete] ${_}${o(d)}`),r.add(h);}}for(let[d,f]of Object.entries(u)){let h=`Chg:${d}`;if(!r.has(h)){let _=f.author||"Unknown";e.push(`[${h} format] ${_}`),r.add(h);}}let c=Array.from(l).sort();for(let d of c){if(!this.comments_map[d])continue;let f=`Com:${d}`;if(!r.has(f)){let h=this.comments_map[d],_=`[${f}] ${h.author}`;h.date&&(_+=` @ ${h.date}`),h.resolved&&(_+="(RESOLVED)"),n.push(`${_}: ${qi(h.text)}`),r.add(f);}}}return [...e,...n].join(`
32
+ `)}_add_virtual_text(t,e,n,r=null,i=false){let o={start:e,end:e+t.length,text:t,run:null,paragraph:n,hyperlink_id:r||void 0,part_index:this._current_part_index,is_image_marker:i||void 0,sdt_stack:this._spanSdtStack()};this.spans.push(o),this._text_chunks.push(t);}_replace_smart_quotes(t){return t.replace(/“/g,'"').replace(/”/g,'"').replace(/‘/g,"'").replace(/’/g,"'")}_make_fuzzy_regex(t){t=this._strip_markdown_formatting(t),t=this._replace_smart_quotes(t);let e=[],n=/(\[_+\])|(\s+)|(['"])|([.,;:\/\-\[\](){}+=$?*!|#^<>\\%&@~`_])/g,r=0,i,o=g(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegExp");for(;(i=n.exec(t))!==null;){let a=t.substring(r,i.index);a&&e.push(o(a));let l=i[1],u=i[2],c=i[3],d=i[4];l?e.push("\\[_+\\]"):u?(e.push("(?:\\*\\*|__|\\*|_)?"),e.push("\\s+"),e.push("(?:\\*\\*|__|\\*|_)?")):c?c==="'"?e.push("[\u2018\u2019']"):e.push('["\u201C\u201D]'):d&&(e.push("(?:\\*\\*|__|\\*|_)?"),e.push(o(d)),e.push("(?:\\*\\*|__|\\*|_)?")),r=n.lastIndex;}let s=t.substring(r);return s&&e.push(o(s)),e.join("")}_get_plain_projection(){if(this._plain_projection===null){let t=[],e=[];for(let n of this.spans)if(!(n.run===null&&n.paragraph!==null&&al.has(n.text))){t.push(n.text);for(let r=n.start;r<n.end;r++)e.push(r);}this._plain_projection=[t.join(""),e];}return this._plain_projection}_find_plain_projection_matches(t){let[e,n]=this._get_plain_projection();if(e.length===this.full_text.length)return [];let r=this._replace_smart_quotes(this._strip_markdown_formatting(t));if(!r)return [];let i=this._replace_smart_quotes(e),o=[],s=0;for(;;){let a=i.indexOf(r,s);if(a===-1)break;let l=a+r.length,u=n[a],c=n[l-1]+1;o.push([u,c-u]),s=l;}return o}range_is_virtual_only(t,e){let n=t+e,r=this.spans.filter(i=>i.end>t&&i.start<n);return r.some(i=>i.run!==null)?false:!r.some(i=>i.run===null&&i.text.startsWith("{#"))}drop_virtual_only_matches(t){return t.filter(([e,n])=>!this.range_is_virtual_only(e,n))}find_match_index(t,e=false){if(e){try{let l=ma(t,this.full_text);if(l&&!this.range_is_virtual_only(l.start,l.end-l.start))return [l.start,l.end-l.start]}catch(l){if(l instanceof je)throw l}return [-1,0]}let n=0;for(;;){let l=this.full_text.indexOf(t,n);if(l===-1)break;if(!this.range_is_virtual_only(l,t.length))return [l,t.length];n=l+1;}let r=this._replace_smart_quotes(this.full_text),i=this._replace_smart_quotes(t),o=r.indexOf(i);if(o!==-1)return [o,t.length];let s=this._strip_markdown_formatting(t);if(this.full_text.includes(s))return o=this.full_text.indexOf(s),[o,s.length];let a=this._find_plain_projection_matches(t);if(a.length>0)return a[0];try{let l=new RegExp(this._make_fuzzy_regex(t),"g");for(let u of this.full_text.matchAll(l))if(!this.range_is_virtual_only(u.index,u[0].length))return [u.index,u[0].length]}catch{}return [-1,0]}find_all_match_indices(t,e=false){if(!t)return [];if(e){try{let l=_a(t,this.full_text);if(l.length>0)return l.map(u=>[u.start,u.end-u.start])}catch(l){if(l instanceof je)throw l}return []}let n=g((l,u)=>{let c=[];if(!u)return c;let d=0;for(;;){let f=l.indexOf(u,d);if(f===-1)break;c.push([f,u.length]),d=f+u.length;}return c},"findAllLiteral"),r=n(this.full_text,t);if(r.length>0)return r;let i=this._replace_smart_quotes(this.full_text),o=this._replace_smart_quotes(t);if(r=n(i,o),r.length>0)return r;let s=this._strip_markdown_formatting(t);if(r=n(this.full_text,s),r.length>0)return r;let a=this._find_plain_projection_matches(t);if(a.length>0)return a;try{let l=new RegExp(this._make_fuzzy_regex(t),"g"),u=[...this.full_text.matchAll(l)];if(u.length>0)return u.map(c=>[c.index,c[0].length])}catch{}return []}find_target_runs(t){let[e,n]=this.find_match_index(t);return e===-1?[]:this._resolve_runs_at_range(e,e+n)}find_target_runs_by_index(t,e,n=true){return this._resolve_runs_at_range(t,t+e,n)}get_virtual_spans_in_range(t,e){let n=t+e;return this.spans.filter(r=>r.run===null&&r.text===`
25
33
 
26
- `,n,d),n+=2;}n=this._map_table(u,n),l=false,a=u;}return n}_map_table(t,e){let n=e,r=0;for(let s of t.rows){let i=s._element,o=B(i,"w:trPr"),l=o?B(o,"w:ins"):null,a=o?B(o,"w:del"):null;if(this.clean_view&&a||this.original_view&&l)continue;r>0&&(this._add_virtual_text(`
27
- `,n,null),n+=1),l&&!this.clean_view&&!this.original_view?(this._add_virtual_text("{++ ",n,null),n+=4):a&&!this.clean_view&&!this.original_view&&(this._add_virtual_text("{-- ",n,null),n+=4);let u=new Set,c=0;for(let d of s.cells){if(u.has(d))continue;u.add(d),c>0&&(this._add_virtual_text(" | ",n,null),n+=3);let f=n;if(n=this._map_blocks(d,n),!this.clean_view&&!this.original_view){let{paraId:h,firstP:_}=Ir(d._element,n===f);if(h&&_){let p=new ie(_,d);this._add_virtual_text("",n,p),n>f&&(this._add_virtual_text(" ",n,p),n+=1);let y=`{#cell:${h}}`;this._add_virtual_text(y,n,p),n+=y.length;}}c+=1;}if(l&&!this.clean_view&&!this.original_view){let d=` ++}{>>[Chg:${l.getAttribute("w:id")} insert] ${l.getAttribute("w:author")||"Unknown"}<<}`;this._add_virtual_text(d,n,null),n+=d.length;}else if(a&&!this.clean_view&&!this.original_view){let d=` --}{>>[Chg:${a.getAttribute("w:id")} delete] ${a.getAttribute("w:author")||"Unknown"}<<}`;this._add_virtual_text(d,n,null),n+=d.length;}if(r+=1,r===1){let d=new Set,f=0;for(let h of s.cells)d.has(h)||(d.add(h),f+=1);if(f>0){let h=Array(f).fill("---").join(" | ");this._add_virtual_text(`
28
- `,n,null),n+=1,this._add_virtual_text(h,n,null),n+=h.length;}}}return n}_strip_markdown_formatting(t){let e=t;return e=e.replace(/^#+\s*/gm,""),e=e.replace(/\*\*(\w[\w\s]*\w|\w{2,})\*\*/g,"$1"),e=e.replace(/__(\w[\w\s]*\w|\w{2,})__/g,"$1"),e=e.replace(/(?<!\w)_(\w[\w\s]*\w|\w{2,})_(?!\w)/g,"$1"),e=e.replace(/(?<!\w)\*(\w[\w\s]*\w|\w{2,})\*(?!\w)/g,"$1"),e}_map_paragraph_content(t,e,n,r){let s=e,i={start:s,end:s,text:"",run:null,paragraph:t,part_index:this._current_part_index};this.spans.push(i);let o=new Set,l={},a={},u={},c=[],d=["",""],f=["",""],h=null,_=[],p=g(()=>{if(_.length===0)return;let[w,v]=d;w&&(this._add_virtual_text(w,s,t),s+=w.length);for(let[N,k,C,A,T,D,j]of _){if(N==="virtual")this._add_virtual_text(k,s,t,h);else {let E={start:s,end:s+k.length,text:k,run:C,paragraph:t,ins_id:T||void 0,del_id:D||void 0,hyperlink_id:h||void 0,comment_ids:j.length>0?j:void 0,part_index:this._current_part_index,run_offset:A};this.spans.push(E),this._text_chunks.push(k);}s+=k.length;}v&&(this._add_virtual_text(v,s,t),s+=v.length),_=[];},"flush_pending_runs"),m=Array.from(Pt(t)),y=qr(t,n,r),x=Ct(t,n,r),b=y;for(let w=0;w<m.length;w++){let v=m[w];if(v instanceof Ce){let[N,k]=Jr(v,x),C=[],A=Me(v);if(b){if(A===""||/^\s*$/.test(A))continue;b=false;}let T=0,D=g(P=>{let[S,$,O]=Xr(P);if(!$){C.push(["real",P,v,T]),T+=P.length;return}S&&(C.push(["real",S,v,T]),T+=S.length),N&&C.push(["virtual",N,null,0]),C.push(["real",$,v,T]),T+=$.length,k&&C.push(["virtual",k,null,0]),O&&(C.push(["real",O,v,T]),T+=O.length);},"append_wrapped");if(A.includes(`
29
- `)&&(N||k)){let P=A.split(`
30
- `);for(let S=0;S<P.length;S++)S>0&&(C.push(["real",`
31
- `,v,T]),T+=1),P[S]&&D(P[S]);}else (N||k)&&A?D(A):(N&&C.push(["virtual",N,null,0]),A&&C.push(["real",A,v,0]),k&&C.push(["virtual",k,null,0]));this.clean_view&&Object.keys(a).length>0,this.original_view&&Object.keys(l).length>0;let j=C.map(P=>P[1]).join(""),E=Object.keys(l).pop()||null,I=Object.keys(a).pop()||null;if(j&&!(this.clean_view&&I)&&!(this.original_view&&E)){let P=this.clean_view||this.original_view?["",""]:this._get_wrappers(E,I,o,u),S=[N,k];if(_.length>0&&P[0]===d[0]&&P[1]===d[1]){let $=false;S[0]===f[0]&&S[1]===f[1]&&f[0]!==""&&_[_.length-1][0]==="virtual"&&_[_.length-1][1]===f[1]&&(_.pop(),$=true);let O=Array.from(o);for(let[F,W,L,U]of C){if($&&F==="virtual"&&W===S[0]){$=false;continue}_.push([F,W,L,U,E,I,O]);}f=S;}else {p(),d=P,f=S;let $=Array.from(o);for(let[O,F,W,L]of C)_.push([O,F,W,L,E,I,$]);}}if(!this.clean_view&&!this.original_view){(Object.keys(l).length>0||Object.keys(a).length>0||o.size>0||Object.keys(u).length>0)&&c.push([{...l},{...a},new Set(o),{...u}]);let S=false;if(E!==null||I!==null||Object.keys(u).length>0||o.size>0){let O=w+1,F=false,W=Object.keys(l).length,L=Object.keys(a).length,U=Object.keys(u).length,q=new Set(o);for(;O<m.length;){let J=m[O];if(J instanceof Ce){if(!Me(J)){O++;continue}(W>0||L>0||U>0||q.size>0)&&(F=true);break}else {let z=J;z.type==="ins_start"?W++:z.type==="ins_end"?W=Math.max(0,W-1):z.type==="del_start"?L++:z.type==="del_end"?L=Math.max(0,L-1):z.type==="fmt_start"?U++:z.type==="fmt_end"?U=Math.max(0,U-1):z.type==="start"?q.add(z.id):z.type==="end"&&q.delete(z.id);}O++;}F&&(S=true);}if(!S&&c.length>0){let O=this._build_merged_meta_block(c);if(O){p(),d=["",""],f=["",""];let F=`{>>${O}<<}`;this._add_virtual_text(F,s,t),s+=F.length;}c=[];}}}else {let N=v;if(b=false,p(),d=["",""],f=["",""],N.type==="start")o.add(N.id);else if(N.type==="end")o.delete(N.id);else if(N.type==="ins_start")l[N.id]=N;else if(N.type==="ins_end")delete l[N.id];else if(N.type==="del_start")a[N.id]=N;else if(N.type==="del_end")delete a[N.id];else if(N.type==="fmt_start")u[N.id]=N;else if(N.type==="fmt_end")delete u[N.id];else if(N.type==="image"){if(!(this.clean_view&&Object.keys(a).length>0||this.original_view&&Object.keys(l).length>0)){let A=`![${(N.date||"image").replace(/\]/g,")").replace(/\n/g," ")}](docx-image:${N.id})`;this._add_virtual_text(A,s,t,null,true),s+=A.length;}}else if(N.type==="footnote"||N.type==="endnote"){p(),d=["",""],f=["",""];let C=`[^${N.type==="footnote"?"fn":"en"}-${N.id}]`;this._add_virtual_text(C,s,t),s+=C.length;}else if(N.type==="hyperlink_start")p(),d=["",""],f=["",""],this._add_virtual_text("[",s,t,N.id),s+=1,h=N.id;else if(N.type==="hyperlink_end"){p(),d=["",""],f=["",""];let k=`](${N.date})`;this._add_virtual_text(k,s,t,N.id),s+=k.length,h=null;}else if(N.type==="xref_start")p(),d=["",""],f=["",""],this._add_virtual_text("[~",s,t),s+=2;else if(N.type==="xref_end"){p(),d=["",""],f=["",""];let k=`~](#${N.id})`;this._add_virtual_text(k,s,t),s+=k.length;}else if(N.type==="bookmark"){p(),d=["",""],f=["",""];let k=`{#${N.id}}`;this._add_virtual_text(k,s,t),s+=k.length;}}}if(p(),c.length>0){let w=this._build_merged_meta_block(c);if(w){let v=`{>>${w}<<}`;this._add_virtual_text(v,s,t),s+=v.length;}}return s}_get_wrappers(t,e,n,r){return e?["{--","--}"]:t?["{++","++}"]:n.size>0||Object.keys(r).length>0?["{==","==}"]:["",""]}_build_merged_meta_block(t){let e=[],n=[],r=new Set,s=Gr(t),i=g(o=>s[o]?` (pairs with ${s[o]})`:"","pairSuffix");for(let[o,l,a,u]of t){for(let[d,f]of Object.entries(o)){let h=`Chg:${d}`;if(!r.has(h)){let _=f.author||"Unknown";e.push(`[${h} insert] ${_}${i(d)}`),r.add(h);}}for(let[d,f]of Object.entries(l)){let h=`Chg:${d}`;if(!r.has(h)){let _=f.author||"Unknown";e.push(`[${h} delete] ${_}${i(d)}`),r.add(h);}}for(let[d,f]of Object.entries(u)){let h=`Chg:${d}`;if(!r.has(h)){let _=f.author||"Unknown";e.push(`[${h} format] ${_}`),r.add(h);}}let c=Array.from(a).sort();for(let d of c){if(!this.comments_map[d])continue;let f=`Com:${d}`;if(!r.has(f)){let h=this.comments_map[d],_=`[${f}] ${h.author}`;h.date&&(_+=` @ ${h.date}`),h.resolved&&(_+="(RESOLVED)"),n.push(`${_}: ${Mr(h.text)}`),r.add(f);}}}return [...e,...n].join(`
32
- `)}_add_virtual_text(t,e,n,r=null,s=false){let i={start:e,end:e+t.length,text:t,run:null,paragraph:n,hyperlink_id:r||void 0,part_index:this._current_part_index,is_image_marker:s||void 0};this.spans.push(i),this._text_chunks.push(t);}_replace_smart_quotes(t){return t.replace(/“/g,'"').replace(/”/g,'"').replace(/‘/g,"'").replace(/’/g,"'")}_make_fuzzy_regex(t){t=this._strip_markdown_formatting(t),t=this._replace_smart_quotes(t);let e=[],n=/(\[_+\])|(\s+)|(['"])|([.,;:\/\-\[\](){}+=$?*!|#^<>\\%&@~`_])/g,r=0,s,i=g(l=>l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegExp");for(;(s=n.exec(t))!==null;){let l=t.substring(r,s.index);l&&e.push(i(l));let a=s[1],u=s[2],c=s[3],d=s[4];a?e.push("\\[_+\\]"):u?(e.push("(?:\\*\\*|__|\\*|_)?"),e.push("\\s+"),e.push("(?:\\*\\*|__|\\*|_)?")):c?c==="'"?e.push("[\u2018\u2019']"):e.push('["\u201C\u201D]'):d&&(e.push("(?:\\*\\*|__|\\*|_)?"),e.push(i(d)),e.push("(?:\\*\\*|__|\\*|_)?")),r=n.lastIndex;}let o=t.substring(r);return o&&e.push(i(o)),e.join("")}_get_plain_projection(){if(this._plain_projection===null){let t=[],e=[];for(let n of this.spans)if(!(n.run===null&&n.paragraph!==null&&Mo.has(n.text))){t.push(n.text);for(let r=n.start;r<n.end;r++)e.push(r);}this._plain_projection=[t.join(""),e];}return this._plain_projection}_find_plain_projection_matches(t){let[e,n]=this._get_plain_projection();if(e.length===this.full_text.length)return [];let r=this._replace_smart_quotes(this._strip_markdown_formatting(t));if(!r)return [];let s=this._replace_smart_quotes(e),i=[],o=0;for(;;){let l=s.indexOf(r,o);if(l===-1)break;let a=l+r.length,u=n[l],c=n[a-1]+1;i.push([u,c-u]),o=a;}return i}range_is_virtual_only(t,e){let n=t+e,r=this.spans.filter(s=>s.end>t&&s.start<n);return r.some(s=>s.run!==null)?false:!r.some(s=>s.run===null&&s.text.startsWith("{#"))}drop_virtual_only_matches(t){return t.filter(([e,n])=>!this.range_is_virtual_only(e,n))}find_match_index(t,e=false){if(e){try{let a=Js(t,this.full_text);if(a&&!this.range_is_virtual_only(a.start,a.end-a.start))return [a.start,a.end-a.start]}catch(a){if(a instanceof Te)throw a}return [-1,0]}let n=0;for(;;){let a=this.full_text.indexOf(t,n);if(a===-1)break;if(!this.range_is_virtual_only(a,t.length))return [a,t.length];n=a+1;}let r=this._replace_smart_quotes(this.full_text),s=this._replace_smart_quotes(t),i=r.indexOf(s);if(i!==-1)return [i,t.length];let o=this._strip_markdown_formatting(t);if(this.full_text.includes(o))return i=this.full_text.indexOf(o),[i,o.length];let l=this._find_plain_projection_matches(t);if(l.length>0)return l[0];try{let a=new RegExp(this._make_fuzzy_regex(t),"g");for(let u of this.full_text.matchAll(a))if(!this.range_is_virtual_only(u.index,u[0].length))return [u.index,u[0].length]}catch{}return [-1,0]}find_all_match_indices(t,e=false){if(!t)return [];if(e){try{let a=qs(t,this.full_text);if(a.length>0)return a.map(u=>[u.start,u.end-u.start])}catch(a){if(a instanceof Te)throw a}return []}let n=g((a,u)=>{let c=[];if(!u)return c;let d=0;for(;;){let f=a.indexOf(u,d);if(f===-1)break;c.push([f,u.length]),d=f+u.length;}return c},"findAllLiteral"),r=n(this.full_text,t);if(r.length>0)return r;let s=this._replace_smart_quotes(this.full_text),i=this._replace_smart_quotes(t);if(r=n(s,i),r.length>0)return r;let o=this._strip_markdown_formatting(t);if(r=n(this.full_text,o),r.length>0)return r;let l=this._find_plain_projection_matches(t);if(l.length>0)return l;try{let a=new RegExp(this._make_fuzzy_regex(t),"g"),u=[...this.full_text.matchAll(a)];if(u.length>0)return u.map(c=>[c.index,c[0].length])}catch{}return []}find_target_runs(t){let[e,n]=this.find_match_index(t);return e===-1?[]:this._resolve_runs_at_range(e,e+n)}find_target_runs_by_index(t,e,n=true){return this._resolve_runs_at_range(t,t+e,n)}get_virtual_spans_in_range(t,e){let n=t+e;return this.spans.filter(r=>r.run===null&&r.text===`
33
-
34
- `&&r.start>=t&&r.end<=n)}_resolve_runs_at_range(t,e,n=true){let r=this.spans.filter(m=>m.end>t&&m.start<e);if(r.length===0)return [];let s=r.filter(m=>m.run!==null);if(s.length===0)return [];let i=[];for(let m of s)i.some(y=>y===m.run)||i.push(m.run);let o=false,l=s[0],a=0,u=Math.max(t,l.start)-l.start+(l.run_offset||0);if(u>0){let m=i[0],[,y]=this._split_run_at_index(m,u);for(let x=0;x<i.length;x++)i[x]===m&&(i[x]=y);o=true,a=u;}let c=s[s.length-1],d=l.run===c.run,f=i[i.length-1],_=Math.min(c.end,e)-c.start+(c.run_offset||0);d&&a>0&&(_-=a);let p=Me(f);if(_>0&&_<p.length){let[m]=this._split_run_at_index(f,_);i[i.length-1]=m,o=true;}return o&&n&&this._build_map(),i}get_insertion_anchor(t,e=true){let n=this.spans.filter(i=>i.end===t);if(n.length>0){for(let i=n.length-1;i>=0;i--)if(n[i].run)return [n[i].run,n[i].paragraph];for(let i=n.length-1;i>=0;i--){let o=n[i].paragraph;if(o){for(let l=this.spans.length-1;l>=0;l--){let a=this.spans[l];if(a.end<=t&&a.run!==null&&a.paragraph!==null&&a.paragraph._element===o._element)return [a.run,a.paragraph]}return [null,o]}}}let r=this.spans.filter(i=>i.start<t&&t<i.end);if(r.length>0){let i=r[0];if(i.run===null)return i.paragraph===null?this.get_insertion_anchor(i.end,e):[null,i.paragraph];{let o=t-i.start+(i.run_offset||0),[l]=this._split_run_at_index(i.run,o);return e&&this._build_map(),[l,i.paragraph]}}if(t===0&&this.spans.length>0){for(let i of this.spans)if(i.run)return [i.run,i.paragraph];for(let i of this.spans)if(i.paragraph)return [null,i.paragraph];return [null,null]}let s=this.spans.filter(i=>i.end<t);if(s.length>0){for(let i=s.length-1;i>=0;i--)if(s[i].run)return [s[i].run,s[i].paragraph];for(let i=s.length-1;i>=0;i--)if(s[i].paragraph)return [null,s[i].paragraph]}return [null,null]}_split_run_at_index(t,e){let n=Me(t),r=n.substring(0,e),s=n.substring(e);this._set_run_text_elements(t._element,r);let i=t._element.cloneNode(true);this._set_run_text_elements(i,s),t._element.parentNode&&t._element.parentNode.insertBefore(i,t._element.nextSibling);let o=new Ce(i,t._parent);return [t,o]}_set_run_text_elements(t,e){let n=[];for(let s=0;s<t.childNodes.length;s++){let i=t.childNodes[s];i.nodeType===1&&["w:t","w:delText","w:br","w:cr","w:tab"].includes(i.tagName)&&n.push(i);}for(let s of n)t.removeChild(s);let r=t.ownerDocument;if(r){let s=r.createElement("w:t");s.textContent=e,e.trim()!==e&&s.setAttribute("xml:space","preserve"),t.appendChild(s);}}get_context_at_range(t,e){let n=this.spans.filter(r=>r.run&&r.end>t&&r.start<e);return n.length>0?n[0]:null}};function er(t){let e=0,n=0,r=t.length,s=g(i=>/[a-zA-Z0-9]/.test(i),"isAlnum");for(;n<r;){if(t[n]==="_"){let i=false;(n>0&&t[n-1]==="_"||n<r-1&&t[n+1]==="_")&&(i=true);let o=false;n>0&&s(t[n-1])&&n<r-1&&s(t[n+1])&&(o=true),!i&&!o&&e++;}n++;}return e}g(er,"_count_standalone_underscores");function Je(t,e){if(!t||!e)return [0,0];let n=g(u=>/\s/.test(u),"isSpace"),r=0,s=Math.min(t.length,e.length);for(;r<s&&t[r]===e[r];)r++;if(r<t.length&&r<e.length)for(;r>0;){let u=!n(t[r-1])&&!n(t[r]),c=!n(e[r-1])&&!n(e[r]);if(u||c)r--;else break}for(;r>0;){if(r<t.length){let p=t.substring(r-1,r+1);if(p==="**"||p==="__"){r--;continue}}let u=t.substring(0,r),c=(u.match(/\*\*/g)||[]).length,d=(u.match(/__/g)||[]).length,f=er(u);if(c%2!==0){r=u.lastIndexOf("**");continue}if(d%2!==0){r=u.lastIndexOf("__");continue}if(f%2!==0){let p=u.length-1,m=g(y=>/[a-zA-Z0-9]/.test(y),"isAlnum");for(;p>=0;){if(u[p]==="_"&&(p===0||u[p-1]!=="_")&&(p===u.length-1||u[p+1]!=="_")&&!(p>0&&m(u[p-1])&&p<u.length-1&&m(u[p+1]))){r=p;break}p--;}continue}let h=r,_=false;for(;h>0;){let p=t[h-1];if(p==="#"){for(r=h-1;r>0&&t[r-1]!==`
34
+ `&&r.start>=t&&r.end<=n)}_resolve_runs_at_range(t,e,n=true){let r=this.spans.filter(m=>m.end>t&&m.start<e);if(r.length===0)return [];let i=r.filter(m=>m.run!==null);if(i.length===0)return [];let o=[];for(let m of i)o.some(w=>w===m.run)||o.push(m.run);let s=false,a=i[0],l=0,u=Math.max(t,a.start)-a.start+(a.run_offset||0);if(u>0){let m=o[0],[,w]=this._split_run_at_index(m,u);for(let v=0;v<o.length;v++)o[v]===m&&(o[v]=w);s=true,l=u;}let c=i[i.length-1],d=a.run===c.run,f=o[o.length-1],_=Math.min(c.end,e)-c.start+(c.run_offset||0);d&&l>0&&(_-=l);let p=Pe(f);if(_>0&&_<p.length){let[m]=this._split_run_at_index(f,_);o[o.length-1]=m,s=true;}return s&&n&&this._build_map(),o}get_insertion_anchor(t,e=true){let n=this.spans.filter(o=>o.end===t);if(n.length>0){for(let o=n.length-1;o>=0;o--)if(n[o].run)return [n[o].run,n[o].paragraph];for(let o=n.length-1;o>=0;o--){let s=n[o].paragraph;if(s){for(let a=this.spans.length-1;a>=0;a--){let l=this.spans[a];if(l.end<=t&&l.run!==null&&l.paragraph!==null&&l.paragraph._element===s._element)return [l.run,l.paragraph]}return [null,s]}}}let r=this.spans.filter(o=>o.start<t&&t<o.end);if(r.length>0){let o=r[0];if(o.run===null)return o.paragraph===null?this.get_insertion_anchor(o.end,e):[null,o.paragraph];{let s=t-o.start+(o.run_offset||0),[a]=this._split_run_at_index(o.run,s);return e&&this._build_map(),[a,o.paragraph]}}if(t===0&&this.spans.length>0){for(let o of this.spans)if(o.run)return [o.run,o.paragraph];for(let o of this.spans)if(o.paragraph)return [null,o.paragraph];return [null,null]}let i=this.spans.filter(o=>o.end<t);if(i.length>0){for(let o=i.length-1;o>=0;o--)if(i[o].run)return [i[o].run,i[o].paragraph];for(let o=i.length-1;o>=0;o--)if(i[o].paragraph)return [null,i[o].paragraph]}return [null,null]}_split_run_at_index(t,e){let n=Pe(t),r=n.substring(0,e),i=n.substring(e);this._set_run_text_elements(t._element,r);let o=t._element.cloneNode(true);this._set_run_text_elements(o,i),t._element.parentNode&&t._element.parentNode.insertBefore(o,t._element.nextSibling);let s=new Re(o,t._parent);return [t,s]}_set_run_text_elements(t,e){let n=[];for(let i=0;i<t.childNodes.length;i++){let o=t.childNodes[i];o.nodeType===1&&["w:t","w:delText","w:br","w:cr","w:tab"].includes(o.tagName)&&n.push(o);}for(let i of n)t.removeChild(i);let r=t.ownerDocument;if(r){let i=r.createElement("w:t");i.textContent=e,e.trim()!==e&&i.setAttribute("xml:space","preserve"),t.appendChild(i);}}get_context_at_range(t,e){let n=this.spans.filter(r=>r.run&&r.end>t&&r.start<e);return n.length>0?n[0]:null}};function Xr(t){let e=0,n=0,r=t.length,i=g(o=>/[a-zA-Z0-9]/.test(o),"isAlnum");for(;n<r;){if(t[n]==="_"){let o=false;(n>0&&t[n-1]==="_"||n<r-1&&t[n+1]==="_")&&(o=true);let s=false;n>0&&i(t[n-1])&&n<r-1&&i(t[n+1])&&(s=true),!o&&!s&&e++;}n++;}return e}g(Xr,"_count_standalone_underscores");function rt(t,e){if(!t||!e)return [0,0];let n=g(u=>/\s/.test(u),"isSpace"),r=0,i=Math.min(t.length,e.length);for(;r<i&&t[r]===e[r];)r++;if(r<t.length&&r<e.length)for(;r>0;){let u=!n(t[r-1])&&!n(t[r]),c=!n(e[r-1])&&!n(e[r]);if(u||c)r--;else break}for(;r>0;){if(r<t.length){let p=t.substring(r-1,r+1);if(p==="**"||p==="__"){r--;continue}}let u=t.substring(0,r),c=(u.match(/\*\*/g)||[]).length,d=(u.match(/__/g)||[]).length,f=Xr(u);if(c%2!==0){r=u.lastIndexOf("**");continue}if(d%2!==0){r=u.lastIndexOf("__");continue}if(f%2!==0){let p=u.length-1,m=g(w=>/[a-zA-Z0-9]/.test(w),"isAlnum");for(;p>=0;){if(u[p]==="_"&&(p===0||u[p-1]!=="_")&&(p===u.length-1||u[p+1]!=="_")&&!(p>0&&m(u[p-1])&&p<u.length-1&&m(u[p+1]))){r=p;break}p--;}continue}let h=r,_=false;for(;h>0;){let p=t[h-1];if(p==="#"){for(r=h-1;r>0&&t[r-1]!==`
35
35
  `;)r--;_=true;break}if(p===`
36
- `)break;h--;}if(!_)break}let i=0,o=t.length-r,l=e.length-r,a=Math.min(o,l);for(;i<a&&t[t.length-1-i]===e[e.length-1-i];)i++;if(i>0)for(;i>0;){let u=false;i<t.length&&(u=!n(t[t.length-1-i])&&!n(t[t.length-i]));let c=false;if(i<e.length&&(c=!n(e[e.length-1-i])&&!n(e[e.length-i])),u||c)i--;else break}for(;i>0;){let u=t.length-i;if(u>0){let _=t.substring(u-1,u+1);if(_==="**"||_==="__"){i--;continue}}let c=t.substring(t.length-i),d=(c.match(/\*\*/g)||[]).length,f=(c.match(/__/g)||[]).length,h=er(c);if(d%2!==0){i-=c.indexOf("**")+2;continue}if(f%2!==0){i-=c.indexOf("__")+2;continue}if(h%2!==0){let _=0,p=g(m=>/[a-zA-Z0-9]/.test(m),"isAlnum");for(;_<c.length;){if(c[_]==="_"&&(_===0||c[_-1]!=="_")&&(_===c.length-1||c[_+1]!=="_")&&!(_>0&&p(c[_-1])&&_<c.length-1&&p(c[_+1]))){i-=_+1;break}_++;}continue}break}i>0&&/^\s+$/.test(t.substring(t.length-i))&&(i=0);for(let u of ["**","__","_"]){let c=u.length,d=t.substring(r,t.length-i),f=e.substring(r,e.length-i);d.startsWith(u)&&f.startsWith(u)&&d.endsWith(u)&&f.endsWith(u)&&d.length>=2*c&&f.length>=2*c&&(r+=c,i+=c);}return [r,i]}g(Je,"trim_common_context");function Ro(t,e){let n=[],r={},s=/(\s+|[\p{L}\p{N}_]+|[^\p{L}\p{N}_\s])/gu,i=g(o=>{let l=o.split(s).filter(Boolean),a="";for(let u of l)if(u in r)a+=String.fromCharCode(r[u]);else {let c=n.length;r[u]=c,n.push(u),a+=String.fromCharCode(c);}return a},"encode_text");return [i(t),i(e),n]}g(Ro,"_words_to_chars");function xt(t,e){let n=new Nn.default.diff_match_patch;n.Diff_Timeout=2;let[r,s,i]=Ro(t,e),o=n.diff_main(r,s,false);n.diff_cleanupSemantic(o);for(let c=0;c<o.length;c++){let d=o[c][1],f="";for(let h=0;h<d.length;h++)f+=i[d.charCodeAt(h)];o[c][1]=f;}let l=[],a=0,u=null;for(let[c,d]of o)if(c===0){if(u){let[f,h]=u;l.push({type:"modify",target_text:h,new_text:"",comment:"Diff: Text deleted",_match_start_index:f}),u=null;}a+=d.length;}else if(c===-1)u=[a,d],a+=d.length;else if(c===1)if(u){let[f,h]=u;l.push({type:"modify",target_text:h,new_text:d,comment:"Diff: Replacement",_match_start_index:f}),u=null;}else l.push({type:"modify",target_text:"",new_text:d,comment:"Diff: Text inserted",_match_start_index:a});if(u){let[c,d]=u;l.push({type:"modify",target_text:d,new_text:"",comment:"Diff: Text deleted",_match_start_index:c});}return l}g(xt,"generate_edits_from_text");function Vr(t,e){let n=t.length,r=e.length,s=[];for(let h=0;h<=n;h++)s.push(new Int32Array(r+1));for(let h=n-1;h>=0;h--)for(let _=r-1;_>=0;_--)s[h][_]=t[h]===e[_]?s[h+1][_+1]+1:Math.max(s[h+1][_],s[h][_+1]);let i=[],o=0,l=0,a=0,u=0,c=0,d=0,f=g(()=>{if(c===0&&d===0)return;let h=c>0&&d>0?"replace":c>0?"delete":"insert";i.push([h,a,a+c,u,u+d]),c=0,d=0;},"flushPending");for(;o<n||l<r;)if(o<n&&l<r&&t[o]===e[l]){f();let h=o,_=l;for(;o<n&&l<r&&t[o]===e[l];)o++,l++;i.push(["equal",h,o,_,l]);}else c===0&&d===0&&(a=o,u=l),l<r&&(o===n||s[o][l+1]>=s[o+1][l])?(d++,l++):(c++,o++);return f(),i}g(Vr,"_sequence_opcodes");function _t(t){let e=t.split(`
37
- `);return e.length>0&&e.every(n=>n.includes(" | "))}g(_t,"_is_table_blob");function jo(t,e){let n=t.split(`
36
+ `)break;h--;}if(!_)break}let o=0,s=t.length-r,a=e.length-r,l=Math.min(s,a);for(;o<l&&t[t.length-1-o]===e[e.length-1-o];)o++;if(o>0)for(;o>0;){let u=false;o<t.length&&(u=!n(t[t.length-1-o])&&!n(t[t.length-o]));let c=false;if(o<e.length&&(c=!n(e[e.length-1-o])&&!n(e[e.length-o])),u||c)o--;else break}for(;o>0;){let u=t.length-o;if(u>0){let _=t.substring(u-1,u+1);if(_==="**"||_==="__"){o--;continue}}let c=t.substring(t.length-o),d=(c.match(/\*\*/g)||[]).length,f=(c.match(/__/g)||[]).length,h=Xr(c);if(d%2!==0){o-=c.indexOf("**")+2;continue}if(f%2!==0){o-=c.indexOf("__")+2;continue}if(h%2!==0){let _=0,p=g(m=>/[a-zA-Z0-9]/.test(m),"isAlnum");for(;_<c.length;){if(c[_]==="_"&&(_===0||c[_-1]!=="_")&&(_===c.length-1||c[_+1]!=="_")&&!(_>0&&p(c[_-1])&&_<c.length-1&&p(c[_+1]))){o-=_+1;break}_++;}continue}break}o>0&&/^\s+$/.test(t.substring(t.length-o))&&(o=0);for(let u of ["**","__","_"]){let c=u.length,d=t.substring(r,t.length-o),f=e.substring(r,e.length-o);d.startsWith(u)&&f.startsWith(u)&&d.endsWith(u)&&f.endsWith(u)&&d.length>=2*c&&f.length>=2*c&&(r+=c,o+=c);}return [r,o]}g(rt,"trim_common_context");function ll(t,e){let n=[],r={},i=/(\s+|[\p{L}\p{N}_]+|[^\p{L}\p{N}_\s])/gu,o=g(s=>{let a=s.split(i).filter(Boolean),l="";for(let u of a)if(u in r)l+=String.fromCharCode(r[u]);else {let c=n.length;r[u]=c,n.push(u),l+=String.fromCharCode(c);}return l},"encode_text");return [o(t),o(e),n]}g(ll,"_words_to_chars");function Gt(t,e){let n=new lr.default.diff_match_patch;n.Diff_Timeout=2;let[r,i,o]=ll(t,e),s=n.diff_main(r,i,false);n.diff_cleanupSemantic(s);for(let c=0;c<s.length;c++){let d=s[c][1],f="";for(let h=0;h<d.length;h++)f+=o[d.charCodeAt(h)];s[c][1]=f;}let a=[],l=0,u=null;for(let[c,d]of s)if(c===0){if(u){let[f,h]=u;a.push({type:"modify",target_text:h,new_text:"",comment:"Diff: Text deleted",_match_start_index:f}),u=null;}l+=d.length;}else if(c===-1)u=[l,d],l+=d.length;else if(c===1)if(u){let[f,h]=u;a.push({type:"modify",target_text:h,new_text:d,comment:"Diff: Replacement",_match_start_index:f}),u=null;}else a.push({type:"modify",target_text:"",new_text:d,comment:"Diff: Text inserted",_match_start_index:l});if(u){let[c,d]=u;a.push({type:"modify",target_text:d,new_text:"",comment:"Diff: Text deleted",_match_start_index:c});}return a}g(Gt,"generate_edits_from_text");function ao(t,e){let n=t.length,r=e.length,i=[];for(let h=0;h<=n;h++)i.push(new Int32Array(r+1));for(let h=n-1;h>=0;h--)for(let _=r-1;_>=0;_--)i[h][_]=t[h]===e[_]?i[h+1][_+1]+1:Math.max(i[h+1][_],i[h][_+1]);let o=[],s=0,a=0,l=0,u=0,c=0,d=0,f=g(()=>{if(c===0&&d===0)return;let h=c>0&&d>0?"replace":c>0?"delete":"insert";o.push([h,l,l+c,u,u+d]),c=0,d=0;},"flushPending");for(;s<n||a<r;)if(s<n&&a<r&&t[s]===e[a]){f();let h=s,_=a;for(;s<n&&a<r&&t[s]===e[a];)s++,a++;o.push(["equal",h,s,_,a]);}else c===0&&d===0&&(l=s,u=a),a<r&&(s===n||i[s][a+1]>=i[s+1][a])?(d++,a++):(c++,s++);return f(),o}g(ao,"_sequence_opcodes");function Mt(t){let e=t.split(`
37
+ `);return e.length>0&&e.every(n=>n.includes(" | "))}g(Mt,"_is_table_blob");function cl(t,e){let n=t.split(`
38
38
  `),r=e.split(`
39
- `);if(n.length!==r.length)return null;let s=[];for(let i=0;i<n.length;i++)n[i]!==r[i]&&s.push({type:"modify",target_text:n[i],new_text:r[i],comment:"Diff: Table row modified",_is_table_edit:true});return s}g(jo,"_table_blob_row_edits");function Bo(t){let e=[];for(let n of t){let r=n.target_text||"",s=n.new_text||"",i=n._match_start_index;if(i==null||!r.includes(`
39
+ `);if(n.length!==r.length)return null;let i=[];for(let o=0;o<n.length;o++)n[o]!==r[o]&&i.push({type:"modify",target_text:n[o],new_text:r[o],comment:"Diff: Table row modified",_is_table_edit:true});return i}g(cl,"_table_blob_row_edits");function ul(t){let e=[];for(let n of t){let r=n.target_text||"",i=n.new_text||"",o=n._match_start_index;if(o==null||!r.includes(`
40
40
 
41
41
  `)||r.split(`
42
42
 
43
- `).length-1===s.split(`
43
+ `).length-1===i.split(`
44
+
45
+ `).length-1){e.push(n);continue}let s=r.split(`
46
+
47
+ `);if(s.length<2||!s[0].trim()||!s[s.length-1].trim()){e.push(n);continue}let a=o;for(let l of s.slice(0,-1))e.push({type:"modify",target_text:l+`
48
+
49
+ `,new_text:"",comment:n.comment||"Diff: Text deleted",_match_start_index:a}),a+=l.length+2;e.push({type:"modify",target_text:s[s.length-1],new_text:i,comment:n.comment,_match_start_index:a});}return e}g(ul,"_split_cross_paragraph_hunks");function Ht(t,e){let n=t.trimEnd(),r=t.slice(n.length);e=e.trimEnd()+r;let o=t.split(`
44
50
 
45
- `).length-1){e.push(n);continue}let o=r.split(`
51
+ `),s=e.split(`
46
52
 
47
- `);if(o.length<2||!o[0].trim()||!o[o.length-1].trim()){e.push(n);continue}let l=i;for(let a of o.slice(0,-1))e.push({type:"modify",target_text:a+`
53
+ `),a=[],l=0;for(let d of o)a.push(l),l+=d.length+2;let u=ao(o,s),c=[];for(let[d,f,h,_,p]of u){if(d==="equal")continue;let m=f<a.length?a[f]:t.length;if(d==="delete")if(h<o.length){let w=m;for(let v=f;v<h;v++){let b=o[v]+`
48
54
 
49
- `,new_text:"",comment:n.comment||"Diff: Text deleted",_match_start_index:l}),l+=a.length+2;e.push({type:"modify",target_text:o[o.length-1],new_text:s,comment:n.comment,_match_start_index:l});}return e}g(Bo,"_split_cross_paragraph_hunks");function yt(t,e){let n=t.trimEnd(),r=t.slice(n.length);e=e.trimEnd()+r;let i=t.split(`
55
+ `;c.push({type:"modify",target_text:b,new_text:"",comment:"Diff: Text deleted",_match_start_index:w}),w+=b.length;}}else {let w=o.slice(f,h).join(`
50
56
 
51
- `),o=e.split(`
57
+ `),v=m;f>0&&(w=`
52
58
 
53
- `),l=[],a=0;for(let d of i)l.push(a),a+=d.length+2;let u=Vr(i,o),c=[];for(let[d,f,h,_,p]of u){if(d==="equal")continue;let m=f<l.length?l[f]:t.length;if(d==="delete")if(h<i.length){let y=m;for(let x=f;x<h;x++){let b=i[x]+`
59
+ `+w,v-=2),c.push({type:"modify",target_text:w,new_text:"",comment:"Diff: Text deleted",_match_start_index:v});}else if(d==="insert"){let w=s.slice(_,p).join(`
54
60
 
55
- `;c.push({type:"modify",target_text:b,new_text:"",comment:"Diff: Text deleted",_match_start_index:y}),y+=b.length;}}else {let y=i.slice(f,h).join(`
61
+ `);f<o.length?w=w+`
56
62
 
57
- `),x=m;f>0&&(y=`
63
+ `:w=`
58
64
 
59
- `+y,x-=2),c.push({type:"modify",target_text:y,new_text:"",comment:"Diff: Text deleted",_match_start_index:x});}else if(d==="insert"){let y=o.slice(_,p).join(`
65
+ `+w,c.push({type:"modify",target_text:"",new_text:w,comment:"Diff: Text inserted",_match_start_index:m});}else if(d==="replace"){if(h-f===p-_&&Array.from({length:h-f}).some((y,x)=>Mt(o[f+x])||Mt(s[_+x]))){for(let y=0;y<h-f;y++){let x=o[f+y],k=s[_+y];if(x===k)continue;let N=a[f+y],P=Mt(x)&&Mt(k)?cl(x,k):null;if(P!==null){c.push(...P);continue}let A=Gt(x,k);for(let C of A)C._match_start_index=(C._match_start_index||0)+N,c.push(C);}continue}let w=o.slice(f,h).join(`
60
66
 
61
- `);f<i.length?y=y+`
67
+ `),v=s.slice(_,p).join(`
62
68
 
63
- `:y=`
69
+ `),b=Gt(w,v);for(let y of b)y._match_start_index=(y._match_start_index||0)+m,c.push(y);}}return ul(c)}g(Ht,"generate_edits_via_paragraph_alignment");var Xt=/!\[[^\]]*\]\(docx-image:[^)]*\)/g;function qr(t,e){let n=g(i=>i.replace(Xt,"").replace(/\s+/g," ").trim(),"_normalized"),r=[];for(let i of t){let o=((i.target_text||"").match(Xt)||[]).sort(),s=((i.new_text||"").match(Xt)||[]).sort();if(JSON.stringify(o)===JSON.stringify(s)){r.push(i);continue}n(i.target_text||"")===n(i.new_text||"")?e.push("An inline image was added or removed between the documents. Images cannot be transferred by text edits \u2014 the image-only difference was skipped; apply it manually in Word."):e.push("A text change overlapping an added/removed inline image was skipped \u2014 images cannot be transferred by text edits. Apply that section manually in Word.");}return r}g(qr,"_drop_image_marker_hunks");function Gr(t,e,n){let r=[];for(let s of e.matchAll(Xt))r.push([s.index,s.index+s[0].length]);if(r.length===0)return t;let i=[],o=false;for(let s of t){let a=s._match_start_index;if(a==null){i.push(s);continue}let l=a+(s.target_text||"").length;if(!r.some(([c,d])=>c<l&&a<d&&!(a<=c&&d<=l))){i.push(s);continue}o||(n.push("An image's alternative text differs between the documents. Image markers (![alt](docx-image:N)) are read-only projections, so this difference cannot be expressed as a text edit \u2014 it was skipped; update the image or its alt text manually in Word."),o=true);}return i}g(Gr,"_drop_marker_interior_hunks");function Jr(t,e){for(let n of e.rows)if(t.substring(n.start,n.end)!==n.cells.join(" | "))return false;return true}g(Jr,"_rows_are_plain");var Un="";function dl(t,e){let n=t.map(o=>o.cells.join(Un)),r=e.map(o=>o.cells.join(Un)),i=ao(n,r);for(let[o,s,a,l,u]of i)if(o==="insert"||o==="delete"||o==="replace"&&a-s!==u-l)return i;return null}g(dl,"_table_row_opcodes");function fl(t,e,n,r){let i=t.rows,o=e.rows,s=i.map(_=>_.cells.join(Un)),a=g(_=>_.cells.join(" | "),"row_text");new Set(s).size!==s.length&&r.push("A table contains rows with identical text; the generated row operations anchor by row text and may be rejected as ambiguous at apply time. If that happens, apply the row changes with explicit insert_row/delete_row edits.");let l=new Set,u={};for(let[_,p,m,w,v]of n)if(_==="delete")for(let b=p;b<m;b++)l.add(b);else if(_==="replace"){let b=Math.min(m-p,v-w);for(let y=p+b;y<m;y++)l.add(y);for(let y=0;y<b;y++)u[p+y]=a(o[w+y]);}let c=[];for(let _=0;_<i.length;_++)l.has(_)||c.push(_);let d=g(_=>u[_]!==void 0?u[_]:a(i[_]),"anchor_text"),f=g((_,p)=>{let m=[],w=c.filter(b=>b<p),v=c.filter(b=>b>=p);if(w.length>0){let b=w[w.length-1],y=d(b);for(let x of [..._].reverse())m.push({type:"insert_row",target_text:y,position:"below",cells:[...x.cells],_match_start_index:i[b].start});}else if(v.length>0){let b=v[0],y=d(b);for(let x of _)m.push({type:"insert_row",target_text:y,position:"above",cells:[...x.cells],_match_start_index:i[b].start});}else r.push("A table gained rows but no original row survives to anchor them; these row insertions were skipped \u2014 add them with explicit insert_row operations.");return m},"insert_ops"),h=[];for(let[_,p,m,w,v]of n)if(_!=="equal")if(_==="replace"){let b=Math.min(m-p,v-w);for(let x=0;x<b;x++){let k=a(i[p+x]),N=a(o[w+x]);k!==N&&h.push({type:"modify",target_text:k,new_text:N,comment:"Diff: Table row modified",_is_table_edit:true});}for(let x=p+b;x<m;x++)h.push({type:"delete_row",target_text:a(i[x]),_match_start_index:i[x].start});let y=o.slice(w+b,v);y.length>0&&h.push(...f(y,m));}else if(_==="delete")for(let b=p;b<m;b++)h.push({type:"delete_row",target_text:a(i[b]),_match_start_index:i[b].start});else _==="insert"&&h.push(...f(o.slice(w,v),p));return h}g(fl,"_row_ops_for_table");function lo(t,e,n,r){let i=[],o=[],s=e.part_ranges.filter(([p,m])=>m>p).map(([,,p])=>p),a=r.part_ranges.filter(([p,m])=>m>p).map(([,,p])=>p);if(JSON.stringify(s)!==JSON.stringify(a))return i.push(`The documents have different part layouts (${s.join(" + ")||"none"} vs ${a.join(" + ")||"none"}); comparing flattened text instead. Header/footer additions or removals cannot be expressed as text edits.`),{edits:[...Gr(qr(Ht(t,n),i),t,i)],warnings:i};let l=e.part_ranges.filter(([p,m])=>m>p).map(([p,m])=>[p,m]),u=r.part_ranges.filter(([p,m])=>m>p).map(([p,m])=>[p,m]);for(let p=0;p<l.length;p++){let[m,w]=l[p],[v,b]=u[p],y=e.tables.filter(A=>m<=A.start&&A.end<=w),x=r.tables.filter(A=>v<=A.start&&A.end<=b),k=y.length===x.length&&y.every(A=>Jr(t,A))&&x.every(A=>Jr(n,A));if(y.length!==x.length&&i.push(`A ${s[p]} part has ${y.length} table(s) in the original but ${x.length} in the modified document; its tables were compared as plain text. Adding or removing whole tables is not supported via diff/apply.`),!k){let A=Ht(t.substring(m,w),n.substring(v,b));for(let C of A)C._match_start_index=(C._match_start_index||0)+m;o.push(...A);continue}let N=[[m,m],...y.map(A=>[A.start,A.end]),[w,w]],P=[[v,v],...x.map(A=>[A.start,A.end]),[b,b]];for(let A=0;A<N.length-1;A++){let C=N[A][1],T=N[A+1][0],M=P[A][1],j=P[A+1][0],B=Ht(t.substring(C,T),n.substring(M,j));for(let $ of B)$._match_start_index=($._match_start_index||0)+C;if(o.push(...B),A<y.length){let $=y[A],I=x[A],E=dl($.rows,I.rows);if(E!==null)o.push(...fl($,I,E,i));else for(let S=0;S<$.rows.length;S++){let D=$.rows[S].cells.join(" | "),U=I.rows[S].cells.join(" | ");D!==U&&o.push({type:"modify",target_text:D,new_text:U,comment:"Diff: Table row modified",_is_table_edit:true});}}}}let c=g((p,m)=>{let w=0,v=0;for(;;){let b=p.indexOf(m,v);if(b===-1)break;w++,v=b+m.length;}return w},"countOccurrences"),d=false;for(let p of o)(p.type==="insert_row"||p.type==="delete_row"||p._is_table_edit)&&!d&&p.target_text&&c(t,p.target_text)>1&&(i.push(`The row anchor "${p.target_text.substring(0,60)}" appears more than once in the document. Applying this diff from its JSON output may be rejected as ambiguous \u2014 make the anchor rows unique, or apply the row changes with explicit insert_row/delete_row edits.`),d=true);let f=o.filter(p=>p.type==="modify"),h=new Set(Gr(qr(f,i),t,i));return {edits:o.filter(p=>p.type!=="modify"||h.has(p)),warnings:i}}g(lo,"generate_structured_edits");function co(t,e){let n=g(c=>{let d=new Map;try{let f=Ke(c);for(let[h,_]of Object.entries(f)){if(!h.startsWith("word/media/"))continue;let p=2166136261,m=3421674724;for(let w=0;w<_.length;w++)p=Math.imul(p^_[w],16777619)>>>0,m=Math.imul(m^_[_.length-1-w],16777619)>>>0;d.set(h,`${_.length}:${p.toString(16)}:${m.toString(16)}`);}}catch{return new Map}return d},"media_hashes"),r=n(t),i=n(e),o=[],s=[],a=[];for(let[c,d]of r)i.has(c)?i.get(c)!==d&&o.push(c):a.push(c);for(let c of i.keys())r.has(c)||s.push(c);if(o.sort(),s.sort(),a.sort(),o.length+s.length+a.length===0)return [];let l=[];o.length&&l.push(`${o.length} changed`),s.length&&l.push(`${s.length} added`),a.length&&l.push(`${a.length} removed`);let u=[...o,...s,...a].slice(0,5).join(", ");return [`The documents' embedded media differ (${l.join(", ")}: ${u}). This diff compares TEXT only \u2014 an empty edit list does not mean the documents are visually identical. Image changes must be applied manually in Word.`]}g(co,"collect_media_difference_warnings");function uo(t,e,n=3){let r=new lr.default.diff_match_patch;r.Diff_Timeout=2;let i=r.diff_linesToChars_(t,e),o=r.diff_main(i.chars1,i.chars2,false);r.diff_charsToLines_(o,i.lineArray);let s=[];s.push("--- Original"),s.push("+++ Modified");let a=0;for(;a<o.length;){for(;a<o.length&&o[a][0]===0;)a++;if(a>=o.length)break;let l=a,u=[];l>0&&o[l-1][0]===0&&(u=o[l-1][1].replace(/\n$/,"").split(`
70
+ `).slice(-n));let c=[];for(c.push(...u.map(f=>` ${f}`));a<o.length;){let[f,h]=o[a],_=h.replace(/\n$/,"").split(`
71
+ `);if(f===0){if(_.length>n*2)break;c.push(..._.map(p=>` ${p}`));}else {let p=f===-1?"-":"+";c.push(..._.map(m=>`${p}${m}`));}a++;}let d=[];a<o.length&&o[a][0]===0&&(d=o[a][1].replace(/\n$/,"").split(`
72
+ `).slice(0,n)),c.push(...d.map(f=>` ${f}`)),s.push("@@ ... @@"),s.push(...c);}return s.length===2?"":s.join(`
73
+ `)}g(uo,"create_unified_diff");var Jt=/\{\+\+|\{--|\{==|\{>>|\+\+\}|--\}|==\}|<<\}/g,hl={"{++":"++}","{--":"--}","{==":"==}","{>>":"<<}"};function Yr(t){if(!t)return true;if(/\{[=+\-><]?$/.test(t)||/^[=+\-><]?\}/.test(t))return false;let e=[];Jt.lastIndex=0;let n;for(;(n=Jt.exec(t))!==null;){let r=n[0];if(r.startsWith("{"))e.push(r);else if(e.length===0||hl[e.pop()]!==r)return false}return e.length===0}g(Yr,"_critic_payload_atomic");function fo(t,e,n,r){let i=true;for(;i;){i=false;for(let o of [t,e]){let s=o.length-r;Jt.lastIndex=0;let a;for(;(a=Jt.exec(o))!==null;){let l=a.index,u=a.index+a[0].length;if(n>l&&n<u&&(n=l,i=true),s>l&&s<u){r=o.length-u,i=true;break}}}}return [Math.max(0,n),Math.max(0,r)]}g(fo,"_clamp_trim_outside_critic_tokens");function pl(t,e){let[n,r]=rt(t,e);return [n,r]=fo(t,e,n,r),[t.substring(n,t.length-r),e.substring(n,e.length-r)]}g(pl,"_word_patch_displays");function _l(t,e){let n=[],r=0;for(;r<t.length;){let i=t[r].target_text||"",o=t[r].new_text||"",s=t[r]._match_start_index||0,a=r+1;for(;;){let[l,u]=pl(i,o);if(Yr(l)&&Yr(u)||a>=t.length)break;let c=t[a],d=c._match_start_index||0,f=s+i.length,h=d>=f?e.substring(f,d):"";i=i+h+(c.target_text||""),o=o+h+(c.new_text||""),a++;}a>r+1?n.push({...t[r],target_text:i,new_text:o,_match_start_index:s}):n.push(t[r]),r=a;}return n}g(_l,"_merge_critic_split_hunks");function ho(t,e,n="Original",r="Modified"){let i=_l(Gt(t,e),t),o=[`--- ${n}`,`+++ ${r}`,""],s=40;for(let a of i){let l=a._match_start_index||0,u=a.target_text||"",c=a.new_text||"",[d,f]=rt(u,c);[d,f]=fo(u,c,d,f);let h=u.length-f,_=c.length-f,p=u.substring(d,h),m=c.substring(d,_),w=l+d,v=w+p.length,b=Math.max(0,w-s),y=t.substring(b,w);b>0&&(y="..."+y);let x=Math.min(t.length,v+s),k=t.substring(v,x);x<t.length&&(k=k+"..."),y=y.replace(/\n/g," ").replace(/\r/g,""),k=k.replace(/\n/g," ").replace(/\r/g,""),o.push("@@ Word Patch @@"),o.push(` ${y}`),p&&o.push(`- ${p}`),m&&o.push(`+ ${m}`),o.push(` ${k}`),o.push("");}return o.join(`
74
+ `)}g(ho,"create_word_patch_diff");var Qr=19e3;var ml="<!-- READONLY_BOUNDARY_START -->";var Vr={"{++":"++}","{--":"--}","{==":"==}","{>>":"<<}"},gl=/\bChg:(\d+)\b/g;function ot(t){if(!t)return ["",""];let e=t.indexOf(ml);if(e===-1)return [t,""];let n=t.lastIndexOf(`
75
+ `,e)+1,r=t.substring(0,n).trimEnd(),i=t.substring(n);return [r,i]}g(ot,"split_structural_appendix");function st(t,e=""){if(!t){let u=e?e.trim():"";return {pages:[{page:1,total_pages:1,has_next:false,has_prev:false,tracked_change_count:Zr(u),page_content:u}],total_pages:1,body_pages:[""],body_page_offsets:[0]}}let n=wl(t),[r,i]=bl(n),o;if(e&&e.trim()){let l=e.trim();o=r.map(u=>u?`${u}
64
76
 
65
- `+y,c.push({type:"modify",target_text:"",new_text:y,comment:"Diff: Text inserted",_match_start_index:m});}else if(d==="replace"){if(h-f===p-_&&Array.from({length:h-f}).some((w,v)=>_t(i[f+v])||_t(o[_+v]))){for(let w=0;w<h-f;w++){let v=i[f+w],N=o[_+w];if(v===N)continue;let k=l[f+w],C=_t(v)&&_t(N)?jo(v,N):null;if(C!==null){c.push(...C);continue}let A=xt(v,N);for(let T of A)T._match_start_index=(T._match_start_index||0)+k,c.push(T);}continue}let y=i.slice(f,h).join(`
77
+ ${l}`:l);}else o=[...r];let s=o.length;return {pages:o.map((l,u)=>({page:u+1,total_pages:s,has_next:u+1<s,has_prev:u+1>1,tracked_change_count:Zr(l),page_content:l})),total_pages:s,body_pages:r,body_page_offsets:i}}g(st,"paginate");function wl(t){let e=yl(t),n=vl(e),r=[];for(let[i,o]of n)if(i.includes(Ut)){let s=i.split(Ut),a=o;for(let l=0;l<s.length;l++){let u=s[l],c=l===s.length-1;(u||!c)&&r.push([u,a,!c]),a+=u.length+Ut.length;}}else r.push([i,o,false]);return r}g(wl,"_tokenize_into_atomic_blocks");function yl(t){let e={"++}":0,"--}":0,"==}":0,"<<}":0},n=[],r=0,i=0,o=t.length;for(;i<o;){let s=false;for(let[l,u]of Object.entries(Vr))if(t.startsWith(l,i)){e[u]++,i+=l.length,s=true;break}if(s)continue;let a=false;for(let l of Object.values(Vr))if(t.startsWith(l,i)){e[l]>0&&e[l]--,i+=l.length,a=true;break}if(!a){if(t[i]===`
78
+ `&&i+1<o&&t[i+1]===`
79
+ `&&Object.values(e).every(l=>l===0)){let l=t.substring(r,i);l&&n.push([l,r]);let u=i;for(;u<o&&t[u]===`
80
+ `;)u++;i=u,r=i;continue}i++;}}if(r<o){let s=t.substring(r,o);s&&n.push([s,r]);}return n}g(yl,"_split_on_safe_paragraph_breaks");function vl(t){if(!t.length)return t;let e=[],n=0;for(;n<t.length;){let[r,i]=t[n],o=r.trimStart();if(!(o.startsWith("## Footnotes")||o.startsWith("## Endnotes"))){e.push([r,i]),n++;continue}let a=r,l=n+1;for(;l<t.length;){let[u]=t[l],c=u.trimStart();if(c.startsWith("[^fn-")||c.startsWith("[^en-"))a=`${a}
66
81
 
67
- `),x=o.slice(_,p).join(`
82
+ ${u}`,l++;else break}e.push([a,i]),n=l;}return e}g(vl,"_merge_footnote_sections");function bl(t){if(!t.length)return [[""],[0]];let e=[],n=[],r=[],i=0,o=-1,s=g(()=>{r.length>0&&(e.push(r.join(`
68
83
 
69
- `),b=xt(y,x);for(let w of b)w._match_start_index=(w._match_start_index||0)+m,c.push(w);}}return Bo(c)}g(yt,"generate_edits_via_paragraph_alignment");var vt=/!\[[^\]]*\]\(docx-image:[^)]*\)/g;function tr(t,e){let n=g(s=>s.replace(vt,"").replace(/\s+/g," ").trim(),"_normalized"),r=[];for(let s of t){let i=((s.target_text||"").match(vt)||[]).sort(),o=((s.new_text||"").match(vt)||[]).sort();if(JSON.stringify(i)===JSON.stringify(o)){r.push(s);continue}n(s.target_text||"")===n(s.new_text||"")?e.push("An inline image was added or removed between the documents. Images cannot be transferred by text edits \u2014 the image-only difference was skipped; apply it manually in Word."):e.push("A text change overlapping an added/removed inline image was skipped \u2014 images cannot be transferred by text edits. Apply that section manually in Word.");}return r}g(tr,"_drop_image_marker_hunks");function nr(t,e,n){let r=[];for(let o of e.matchAll(vt))r.push([o.index,o.index+o[0].length]);if(r.length===0)return t;let s=[],i=false;for(let o of t){let l=o._match_start_index;if(l==null){s.push(o);continue}let a=l+(o.target_text||"").length;if(!r.some(([c,d])=>c<a&&l<d&&!(l<=c&&d<=a))){s.push(o);continue}i||(n.push("An image's alternative text differs between the documents. Image markers (![alt](docx-image:N)) are read-only projections, so this difference cannot be expressed as a text edit \u2014 it was skipped; update the image or its alt text manually in Word."),i=true);}return s}g(nr,"_drop_marker_interior_hunks");function rr(t,e){for(let n of e.rows)if(t.substring(n.start,n.end)!==n.cells.join(" | "))return false;return true}g(rr,"_rows_are_plain");var cn="";function Fo(t,e){let n=t.map(i=>i.cells.join(cn)),r=e.map(i=>i.cells.join(cn)),s=Vr(n,r);for(let[i,o,l,a,u]of s)if(i==="insert"||i==="delete"||i==="replace"&&l-o!==u-a)return s;return null}g(Fo,"_table_row_opcodes");function Wo(t,e,n,r){let s=t.rows,i=e.rows,o=s.map(_=>_.cells.join(cn)),l=g(_=>_.cells.join(" | "),"row_text");new Set(o).size!==o.length&&r.push("A table contains rows with identical text; the generated row operations anchor by row text and may be rejected as ambiguous at apply time. If that happens, apply the row changes with explicit insert_row/delete_row edits.");let a=new Set,u={};for(let[_,p,m,y,x]of n)if(_==="delete")for(let b=p;b<m;b++)a.add(b);else if(_==="replace"){let b=Math.min(m-p,x-y);for(let w=p+b;w<m;w++)a.add(w);for(let w=0;w<b;w++)u[p+w]=l(i[y+w]);}let c=[];for(let _=0;_<s.length;_++)a.has(_)||c.push(_);let d=g(_=>u[_]!==void 0?u[_]:l(s[_]),"anchor_text"),f=g((_,p)=>{let m=[],y=c.filter(b=>b<p),x=c.filter(b=>b>=p);if(y.length>0){let b=y[y.length-1],w=d(b);for(let v of [..._].reverse())m.push({type:"insert_row",target_text:w,position:"below",cells:[...v.cells],_match_start_index:s[b].start});}else if(x.length>0){let b=x[0],w=d(b);for(let v of _)m.push({type:"insert_row",target_text:w,position:"above",cells:[...v.cells],_match_start_index:s[b].start});}else r.push("A table gained rows but no original row survives to anchor them; these row insertions were skipped \u2014 add them with explicit insert_row operations.");return m},"insert_ops"),h=[];for(let[_,p,m,y,x]of n)if(_!=="equal")if(_==="replace"){let b=Math.min(m-p,x-y);for(let v=0;v<b;v++){let N=l(s[p+v]),k=l(i[y+v]);N!==k&&h.push({type:"modify",target_text:N,new_text:k,comment:"Diff: Table row modified",_is_table_edit:true});}for(let v=p+b;v<m;v++)h.push({type:"delete_row",target_text:l(s[v]),_match_start_index:s[v].start});let w=i.slice(y+b,x);w.length>0&&h.push(...f(w,m));}else if(_==="delete")for(let b=p;b<m;b++)h.push({type:"delete_row",target_text:l(s[b]),_match_start_index:s[b].start});else _==="insert"&&h.push(...f(i.slice(y,x),p));return h}g(Wo,"_row_ops_for_table");function Zr(t,e,n,r){let s=[],i=[],o=e.part_ranges.filter(([p,m])=>m>p).map(([,,p])=>p),l=r.part_ranges.filter(([p,m])=>m>p).map(([,,p])=>p);if(JSON.stringify(o)!==JSON.stringify(l))return s.push(`The documents have different part layouts (${o.join(" + ")||"none"} vs ${l.join(" + ")||"none"}); comparing flattened text instead. Header/footer additions or removals cannot be expressed as text edits.`),{edits:[...nr(tr(yt(t,n),s),t,s)],warnings:s};let a=e.part_ranges.filter(([p,m])=>m>p).map(([p,m])=>[p,m]),u=r.part_ranges.filter(([p,m])=>m>p).map(([p,m])=>[p,m]);for(let p=0;p<a.length;p++){let[m,y]=a[p],[x,b]=u[p],w=e.tables.filter(A=>m<=A.start&&A.end<=y),v=r.tables.filter(A=>x<=A.start&&A.end<=b),N=w.length===v.length&&w.every(A=>rr(t,A))&&v.every(A=>rr(n,A));if(w.length!==v.length&&s.push(`A ${o[p]} part has ${w.length} table(s) in the original but ${v.length} in the modified document; its tables were compared as plain text. Adding or removing whole tables is not supported via diff/apply.`),!N){let A=yt(t.substring(m,y),n.substring(x,b));for(let T of A)T._match_start_index=(T._match_start_index||0)+m;i.push(...A);continue}let k=[[m,m],...w.map(A=>[A.start,A.end]),[y,y]],C=[[x,x],...v.map(A=>[A.start,A.end]),[b,b]];for(let A=0;A<k.length-1;A++){let T=k[A][1],D=k[A+1][0],j=C[A][1],E=C[A+1][0],I=yt(t.substring(T,D),n.substring(j,E));for(let P of I)P._match_start_index=(P._match_start_index||0)+T;if(i.push(...I),A<w.length){let P=w[A],S=v[A],$=Fo(P.rows,S.rows);if($!==null)i.push(...Wo(P,S,$,s));else for(let O=0;O<P.rows.length;O++){let F=P.rows[O].cells.join(" | "),W=S.rows[O].cells.join(" | ");F!==W&&i.push({type:"modify",target_text:F,new_text:W,comment:"Diff: Table row modified",_is_table_edit:true});}}}}let c=g((p,m)=>{let y=0,x=0;for(;;){let b=p.indexOf(m,x);if(b===-1)break;y++,x=b+m.length;}return y},"countOccurrences"),d=false;for(let p of i)(p.type==="insert_row"||p.type==="delete_row"||p._is_table_edit)&&!d&&p.target_text&&c(t,p.target_text)>1&&(s.push(`The row anchor "${p.target_text.substring(0,60)}" appears more than once in the document. Applying this diff from its JSON output may be rejected as ambiguous \u2014 make the anchor rows unique, or apply the row changes with explicit insert_row/delete_row edits.`),d=true);let f=i.filter(p=>p.type==="modify"),h=new Set(nr(tr(f,s),t,s));return {edits:i.filter(p=>p.type!=="modify"||h.has(p)),warnings:s}}g(Zr,"generate_structured_edits");function Kr(t,e){let n=g(c=>{let d=new Map;try{let f=Le(c);for(let[h,_]of Object.entries(f)){if(!h.startsWith("word/media/"))continue;let p=2166136261,m=3421674724;for(let y=0;y<_.length;y++)p=Math.imul(p^_[y],16777619)>>>0,m=Math.imul(m^_[_.length-1-y],16777619)>>>0;d.set(h,`${_.length}:${p.toString(16)}:${m.toString(16)}`);}}catch{return new Map}return d},"media_hashes"),r=n(t),s=n(e),i=[],o=[],l=[];for(let[c,d]of r)s.has(c)?s.get(c)!==d&&i.push(c):l.push(c);for(let c of s.keys())r.has(c)||o.push(c);if(i.sort(),o.sort(),l.sort(),i.length+o.length+l.length===0)return [];let a=[];i.length&&a.push(`${i.length} changed`),o.length&&a.push(`${o.length} added`),l.length&&a.push(`${l.length} removed`);let u=[...i,...o,...l].slice(0,5).join(", ");return [`The documents' embedded media differ (${a.join(", ")}: ${u}). This diff compares TEXT only \u2014 an empty edit list does not mean the documents are visually identical. Image changes must be applied manually in Word.`]}g(Kr,"collect_media_difference_warnings");function ei(t,e,n=3){let r=new Nn.default.diff_match_patch;r.Diff_Timeout=2;let s=r.diff_linesToChars_(t,e),i=r.diff_main(s.chars1,s.chars2,false);r.diff_charsToLines_(i,s.lineArray);let o=[];o.push("--- Original"),o.push("+++ Modified");let l=0;for(;l<i.length;){for(;l<i.length&&i[l][0]===0;)l++;if(l>=i.length)break;let a=l,u=[];a>0&&i[a-1][0]===0&&(u=i[a-1][1].replace(/\n$/,"").split(`
70
- `).slice(-n));let c=[];for(c.push(...u.map(f=>` ${f}`));l<i.length;){let[f,h]=i[l],_=h.replace(/\n$/,"").split(`
71
- `);if(f===0){if(_.length>n*2)break;c.push(..._.map(p=>` ${p}`));}else {let p=f===-1?"-":"+";c.push(..._.map(m=>`${p}${m}`));}l++;}let d=[];l<i.length&&i[l][0]===0&&(d=i[l][1].replace(/\n$/,"").split(`
72
- `).slice(0,n)),c.push(...d.map(f=>` ${f}`)),o.push("@@ ... @@"),o.push(...c);}return o.length===2?"":o.join(`
73
- `)}g(ei,"create_unified_diff");var Nt=/\{\+\+|\{--|\{==|\{>>|\+\+\}|--\}|==\}|<<\}/g,zo={"{++":"++}","{--":"--}","{==":"==}","{>>":"<<}"};function ir(t){if(!t)return true;if(/\{[=+\-><]?$/.test(t)||/^[=+\-><]?\}/.test(t))return false;let e=[];Nt.lastIndex=0;let n;for(;(n=Nt.exec(t))!==null;){let r=n[0];if(r.startsWith("{"))e.push(r);else if(e.length===0||zo[e.pop()]!==r)return false}return e.length===0}g(ir,"_critic_payload_atomic");function ti(t,e,n,r){let s=true;for(;s;){s=false;for(let i of [t,e]){let o=i.length-r;Nt.lastIndex=0;let l;for(;(l=Nt.exec(i))!==null;){let a=l.index,u=l.index+l[0].length;if(n>a&&n<u&&(n=a,s=true),o>a&&o<u){r=i.length-u,s=true;break}}}}return [Math.max(0,n),Math.max(0,r)]}g(ti,"_clamp_trim_outside_critic_tokens");function Lo(t,e){let[n,r]=Je(t,e);return [n,r]=ti(t,e,n,r),[t.substring(n,t.length-r),e.substring(n,e.length-r)]}g(Lo,"_word_patch_displays");function Uo(t,e){let n=[],r=0;for(;r<t.length;){let s=t[r].target_text||"",i=t[r].new_text||"",o=t[r]._match_start_index||0,l=r+1;for(;;){let[a,u]=Lo(s,i);if(ir(a)&&ir(u)||l>=t.length)break;let c=t[l],d=c._match_start_index||0,f=o+s.length,h=d>=f?e.substring(f,d):"";s=s+h+(c.target_text||""),i=i+h+(c.new_text||""),l++;}l>r+1?n.push({...t[r],target_text:s,new_text:i,_match_start_index:o}):n.push(t[r]),r=l;}return n}g(Uo,"_merge_critic_split_hunks");function ni(t,e,n="Original",r="Modified"){let s=Uo(xt(t,e),t),i=[`--- ${n}`,`+++ ${r}`,""],o=40;for(let l of s){let a=l._match_start_index||0,u=l.target_text||"",c=l.new_text||"",[d,f]=Je(u,c);[d,f]=ti(u,c,d,f);let h=u.length-f,_=c.length-f,p=u.substring(d,h),m=c.substring(d,_),y=a+d,x=y+p.length,b=Math.max(0,y-o),w=t.substring(b,y);b>0&&(w="..."+w);let v=Math.min(t.length,x+o),N=t.substring(x,v);v<t.length&&(N=N+"..."),w=w.replace(/\n/g," ").replace(/\r/g,""),N=N.replace(/\n/g," ").replace(/\r/g,""),i.push("@@ Word Patch @@"),i.push(` ${w}`),p&&i.push(`- ${p}`),m&&i.push(`+ ${m}`),i.push(` ${N}`),i.push("");}return i.join(`
74
- `)}g(ni,"create_word_patch_diff");var sr=19e3;var Ho="<!-- READONLY_BOUNDARY_START -->";var or={"{++":"++}","{--":"--}","{==":"==}","{>>":"<<}"},qo=/\bChg:(\d+)\b/g;function Xe(t){if(!t)return ["",""];let e=t.indexOf(Ho);if(e===-1)return [t,""];let n=t.lastIndexOf(`
75
- `,e)+1,r=t.substring(0,n).trimEnd(),s=t.substring(n);return [r,s]}g(Xe,"split_structural_appendix");function Ge(t,e=""){if(!t){let u=e?e.trim():"";return {pages:[{page:1,total_pages:1,has_next:false,has_prev:false,tracked_change_count:ar(u),page_content:u}],total_pages:1,body_pages:[""],body_page_offsets:[0]}}let n=Jo(t),[r,s]=Qo(n),i;if(e&&e.trim()){let a=e.trim();i=r.map(u=>u?`${u}
84
+ `)),n.push(o)),r=[],i=0,o=-1;},"flush_current");for(let[a,l,u]of t){let c=a.length,d=c+(r.length>0?2:0);if(r.length>0&&i+d>Qr&&s(),r.length===0&&c>Qr){e.push(a),n.push(l);continue}r.length===0&&(o=l),r.push(a),i+=i>0?d:c,u&&s();}return s(),e.length?[e,n]:[[""],[0]]}g(bl,"_assemble_pages");function Zr(t){let e=[...t.matchAll(gl)];return new Set(e.map(r=>r[1])).size}g(Zr,"_count_tracked_changes");var xl=5,Kr=50;function Nl(t,e,n,r){let i=r.length;if(i<2)throw new Error(`format_ambiguity_error requires at least 2 matches, got ${i}`);let o=r.slice(0,xl),s=i-o.length,a=[`- Edit ${t} Failed: Ambiguous match. Target text appears ${i} times. First ${o.length} occurrences:`];for(let l=0;l<o.length;l++){let[u,c]=o[l],d=Math.max(0,u-Kr),f=Math.min(n.length,c+Kr),h=n.substring(d,u).replace(/\n/g," "),_=n.substring(c,f).replace(/\n/g," "),p=n.substring(u,c).replace(/\n/g," ");p.length>50&&(p=p.substring(0,25)+"..."+p.substring(p.length-20));let m=d>0?"...":"",w=f<n.length?"...":"";a.push(` ${l+1}. "${m}${h}[${p}]${_}${w}"`);}return s>0&&a.push(` ... and ${s} more occurrence(s) not shown.`),a.push(" To resolve, re-send this edit using ONE of these strategies:"),a.push(' 1. RECOMMENDED: Provide more surrounding context in your target_text to uniquely identify a single location (keep the default "match_mode": "strict").'),a.push(` 2. Set "match_mode": "all" to modify ALL ${i} occurrences \u2014 only after verifying from the occurrence list above that EVERY occurrence should change.`),a.push(' 3. Set "match_mode": "first" to modify only the FIRST occurrence \u2014 only after verifying the first occurrence above is the one you intend to change.'),a.join(`
85
+ `)}g(Nl,"format_ambiguity_error");var kl="3.0.0";function K(t,e){let n=[],r=t.getElementsByTagName("*");for(let i=0;i<r.length;i++){let o=r[i].tagName;(o===e||o.endsWith(":"+e))&&n.push(r[i]);}return n}g(K,"findDescendantsByLocalName");function El(t){let e=0;function n(s,a){let l=s?s.toString():"",u=a?a.toString():"";return l===u}g(n,"areRunsIdentical");function r(s){let a=["w:t","w:tab","w:br","w:cr","w:delText","w:rPr"];for(let l=0;l<s.childNodes.length;l++){let u=s.childNodes[l];if(u.nodeType===1){let c=u.tagName;if(!a.includes(c))return true}}return false}g(r,"hasSpecialContent");function i(s){let a=Array.from(s.childNodes).filter(u=>u.nodeType===1),l=0;for(;l<a.length-1;){let u=a[l],c=a[l+1];if(u.tagName==="w:r"&&c.tagName==="w:r"&&!r(u)&&!r(c)){let d=O(u,"w:rPr"),f=O(c,"w:rPr");if(n(d,f)){let h=null;for(let p=0;p<u.childNodes.length;p++){let m=u.childNodes[p];m.nodeType===1&&(m.tagName==="w:t"||m.tagName==="w:delText")&&(h=m);}let _=Array.from(c.childNodes).filter(p=>p.nodeType===1);for(let p of _)if(p.tagName!=="w:rPr")if((p.tagName==="w:t"||p.tagName==="w:delText")&&h&&h.tagName===p.tagName){let m=h.textContent||"",w=p.textContent||"",v=m+w;h.textContent=v,v.trim()!==v&&h.setAttribute("xml:space","preserve");}else u.appendChild(p),(p.tagName==="w:t"||p.tagName==="w:delText")&&(h=p);s.removeChild(c),a.splice(l+1,1),e++;continue}}["w:ins","w:del","w:hyperlink","w:sdt","w:smartTag","w:fldSimple","w:sdtContent"].includes(u.tagName)&&i(u),l++;}if(a.length>0){let u=a[a.length-1];["w:ins","w:del","w:hyperlink","w:sdt","w:smartTag","w:fldSimple","w:sdtContent"].includes(u.tagName)&&i(u);}}g(i,"coalesceContainer");let o=R(t.element,"w:p");for(let s of o)i(s);return e?[`Adjacent identical runs coalesced: ${e}`]:[]}g(El,"coalesce_runs");function Al(t){let e=0,n=["w:rsidR","w:rsidRPr","w:rsidRDefault","w:rsidP","w:rsidDel","w:rsidSect","w:rsidTr"],r=t.element.getElementsByTagName("*");for(let o=0;o<r.length;o++)for(let s of n)r[o].hasAttribute(s)&&(r[o].removeAttribute(s),e++);let i=R(t.element,"w:rsids");for(let o of i)o.parentNode&&(o.parentNode.removeChild(o),e++);return e?[`rsid attributes: ${e} removed`]:[]}g(Al,"strip_rsid");function Cl(t){let e=0,n=["w14:paraId","w14:textId"],r=t.element.getElementsByTagName("*");for(let i=0;i<r.length;i++)for(let o of n)r[i].hasAttribute(o)&&(r[i].removeAttribute(o),e++);return e?[`Paragraph/text IDs: ${e} removed`]:[]}g(Cl,"strip_para_ids");function Pl(t){let e=R(t.element,"w:proofErr");return e.forEach(n=>n.parentNode?.removeChild(n)),e.length?[`Spell check markers: ${e.length} removed`]:[]}g(Pl,"strip_proof_errors");function Tl(t){let e=0;for(let n of ["w:rPr","w:pPr"]){let r=R(t.element,n);for(let i of r)(i.childNodes.length===0||i.childNodes.length===1&&i.childNodes[0].nodeType===3&&!i.childNodes[0].textContent?.trim())&&(i.parentNode?.removeChild(i),e++);}return e?[`Empty property elements: ${e} removed`]:[]}g(Tl,"strip_empty_properties");function $l(t){let e=0,n=R(t.element,"w:rPr");for(let r of n)if(O(r,"w:vanish")||O(r,"w:webHidden")){let i=r.parentNode;i&&i.tagName==="w:r"&&i.parentNode&&(i.parentNode.removeChild(i),e++);}return e?[`Hidden text runs: ${e} removed`]:[]}g($l,"strip_hidden_text");function ei(t){let e=R(t.element,"w:ins").length,n=R(t.element,"w:del").length,r=R(t.element,"w:rPrChange").length+R(t.element,"w:pPrChange").length+R(t.element,"w:sectPrChange").length;return [e,n,r]}g(ei,"count_tracked_changes");function Sl(t){let e=new Set;for(let n of ["w:ins","w:del","w:rPrChange","w:pPrChange","w:sectPrChange"])for(let r of R(t.element,n)){let i=r.getAttribute("w:author");i&&e.add(i);}return e}g(Sl,"get_track_change_authors");function ti(t){let e=[],n=R(t,"w:t");for(let i of n)i.textContent&&e.push(i.textContent);let r=R(t,"w:delText");for(let i of r)i.textContent&&e.push(i.textContent);return e.join("")}g(ti,"_getElementText");function Be(t,e=60){let n=t.replace(/\n/g," ").trim();return n.length<=e?n:n.substring(0,e-3)+"..."}g(Be,"_truncate");function ni(t){let e=t.parentNode;if(e&&e.tagName==="w:rPr"){let n=e.parentNode;if(n&&n.tagName==="w:pPr")return "(paragraph mark)"}return e&&e.tagName==="w:trPr"?"(table row)":"(no visible text)"}g(ni,"_describe_textless_revision");function Il(t){let e=[],n=R(t.element,"w:ins"),r=R(t.element,"w:del");for(let s of n){let a=ti(s).trim();a?e.push(` Accepted insertion: "${Be(a,60)}"`):e.push(` Accepted insertion: ${ni(s)}`);}for(let s of r){let a=ti(s).trim();a?e.push(` Accepted deletion of: "${Be(a,60)}"`):e.push(` Accepted deletion of: ${ni(s)}`);}new dn(t).accept_all_revisions();for(let s of ["w:rPrChange","w:pPrChange","w:sectPrChange"])for(let a of R(t.element,s))a.parentNode?.removeChild(a);let o=n.length+r.length;return o?[`Tracked changes auto-accepted: ${o}`].concat(e):[]}g(Il,"accept_all_tracked_changes");function jt(t){let e=Me(t.pkg),n=[],r=0,i=0;for(let[o,s]of Object.entries(e))s.resolved?i++:r++,n.push({id:o,...s});return {total:n.length,open:r,resolved:i,comments:n}}g(jt,"get_comments_summary");function Ol(t){let e=Me(t.pkg),n=Object.keys(e);if(n.length===0)return [];let r=[],i=new Et(t);for(let[l,u]of Object.entries(e)){let c=u.resolved?"[Resolved]":"[Open]";r.push(` ${c} "${Be(u.text||"",60)}" (${u.author||"Unknown"})`),i.deleteComment(l);}for(let l of ["w:commentRangeStart","w:commentRangeEnd"])for(let u of R(t.element,l))u.parentNode?.removeChild(u);let o=R(t.element,"w:commentReference");for(let l of o){let u=l.parentNode;u&&((u.tagName==="w:r"||u.tagName.endsWith(":r"))&&Array.from(u.childNodes).filter(d=>d.nodeType===1&&d.tagName!=="w:rPr"&&d.tagName!=="rPr").length<=1?u.parentNode?.removeChild(u):u.removeChild(l));}let s=Object.values(e).filter(l=>l.resolved).length,a=Object.values(e).filter(l=>!l.resolved).length;return [`Comments removed: ${n.length} (${s} resolved, ${a} open)`].concat(r)}g(Ol,"remove_all_comments");function Dl(t){let e=t.pkg,n=new Set;for(let i of e.parts)if(i.partname.toLowerCase().includes("comments")){n.add(i.partname);let o=i.partname.startsWith("/")?i.partname:"/"+i.partname,s=i.partname.startsWith("/")?i.partname.substring(1):i.partname;n.add(o),n.add(s);}if(n.size===0)return;for(let i of e.parts)if(i.partname.endsWith(".rels")){let o=R(i._element,"Relationship"),s=[];for(let a of o)if((a.getAttribute("Target")||"").toLowerCase().includes("comments")){s.push(a);let u=i.partname.replace("/_rels/","/").replace(".rels",""),c=e.getPartByPath(u);if(c){let d=a.getAttribute("Id");d&&c.rels.delete(d);}}for(let a of s)a.parentNode?.removeChild(a);}let r=e.getPartByPath("[Content_Types].xml");if(r){let i=R(r._element,"Override"),o=[];for(let s of i){let a=s.getAttribute("PartName")||"";(n.has(a)||a.toLowerCase().includes("comments"))&&o.push(s);}for(let s of o)s.parentNode?.removeChild(s);}e.parts=e.parts.filter(i=>!i.partname.toLowerCase().includes("comments"));for(let i of Object.keys(e.unzipped))i.toLowerCase().includes("comments")&&delete e.unzipped[i];}g(Dl,"eject_comment_parts");function Rl(t,e){let n=new Et(t);if(!n.commentsPart)return [];let r=new Set,i=R(n.commentsPart._element,"w:comment");for(let o of i){let s=o.getAttribute("w:author");if(s&&(r.add(s),o.setAttribute("w:author",e)),o.hasAttribute("w:initials")){let a=e.split(" ").filter(Boolean).map(l=>l[0]).join("").toUpperCase();o.setAttribute("w:initials",a);}}return r.size?[`Comment authors replaced: ${Array.from(r).sort().join(", ")} \u2192 "${e}"`]:[]}g(Rl,"replace_comment_authors");function Ml(t,e){let n=new Set;for(let r of ["w:ins","w:del","w:rPrChange","w:pPrChange"])for(let i of R(t.element,r)){let o=i.getAttribute("w:author");o&&(n.add(o),i.setAttribute("w:author",e));}return n.size?[`Track change authors replaced: ${Array.from(n).sort().join(", ")} \u2192 "${e}"`]:[]}g(Ml,"replace_change_authors");function jl(t){let e=0,n="2025-01-01T00:00:00Z";for(let r of ["w:ins","w:del","w:rPrChange","w:pPrChange"])for(let i of R(t.element,r))i.hasAttribute("w:date")&&(i.setAttribute("w:date",n),e++);return e?[`Track change timestamps: ${e} normalized`]:[]}g(jl,"normalize_change_dates");function Bl(t){let e=0,n="2025-01-01T00:00:00Z";for(let r of t.pkg.parts)if(r.contentType.includes("comments")){for(let i of R(r._element,"w:comment"))i.hasAttribute("w:date")&&(i.setAttribute("w:date",n),e++);for(let i of R(r._element,"w16cex:commentExtensible"))i.hasAttribute("w16cex:dateUtc")&&(i.setAttribute("w16cex:dateUtc",n),e++);}return e?[`Comment timestamps: ${e} normalized`]:[]}g(Bl,"normalize_comment_dates");function Fl(t){let e=[],n=t.pkg.getPartByPath("docProps/core.xml");if(n){K(n._element,"creator").forEach(u=>{u.textContent&&(e.push(`Author: ${u.textContent}`),u.textContent="");}),K(n._element,"lastModifiedBy").forEach(u=>{u.textContent&&(e.push(`Last modified by: ${u.textContent}`),u.textContent="");}),K(n._element,"title").forEach(u=>{u.textContent&&e.push(`Title kept (review manually): "${u.textContent}"`);});let a=[["category","Category"],["keywords","Keywords"],["subject","Subject"],["contentStatus","Content status"],["description","Description/comments"],["identifier","Identifier"],["language","Language"],["version","Version"]];for(let[u,c]of a)K(n._element,u).forEach(d=>{d.textContent&&(e.push(`${c}: ${d.textContent}`),d.textContent="");});K(n._element,"revision").forEach(u=>{u.textContent&&parseInt(u.textContent)>1&&(e.push(`Revision count: ${u.textContent} \u2192 1`),u.textContent="1");});}let r=t.pkg.getPartByPath("docProps/app.xml");if(r){let i=r._element,o=["TotalTime","Words","Characters","Paragraphs","Lines","CharactersWithSpaces"];for(let a of o)K(i,a).forEach(l=>{l.textContent&&l.textContent!=="0"&&(a==="TotalTime"&&e.push(`Total editing time: ${l.textContent} minutes`),l.textContent="0");});let s=["Template","Manager","Company"];for(let a of s)K(i,a).forEach(l=>{l.textContent&&(e.push(`${a}: ${l.textContent}`),l.textContent="");});}return e.length?["Metadata scrubbed:",...e.map(i=>` ${i}`)]:[]}g(Fl,"scrub_doc_properties");function Wl(t){let e=false,n="1970-01-01T00:00:00Z",r=t.pkg.getPartByPath("docProps/core.xml");if(r)for(let i of ["created","modified","lastPrinted"])K(r._element,i).forEach(o=>{o.textContent&&o.textContent!==n&&(o.textContent=n,e=true);});return e?["Timestamps normalized to epoch"]:[]}g(Wl,"scrub_timestamps");function po(t,e,n){let r=t.pkg,i=g(s=>s.startsWith("/")?s.substring(1):s,"normalized");for(let s of r.parts){if(!s.partname.endsWith(".rels"))continue;let a=[];for(let l of R(s._element,"Relationship")){let u=l.getAttribute("Target")||"";if(n(u)){a.push(l);let c=s.partname.replace("/_rels/","/").replace(".rels",""),d=r.getPartByPath(c);if(d){let f=l.getAttribute("Id");f&&d.rels.delete(f);}}}a.forEach(l=>l.parentNode?.removeChild(l));}let o=r.getPartByPath("[Content_Types].xml");if(o){let s=[];for(let a of R(o._element,"Override")){let l=a.getAttribute("PartName")||"";e(i(l))&&s.push(a);}s.forEach(a=>a.parentNode?.removeChild(a));}r.parts=r.parts.filter(s=>!e(i(s.partname)));for(let s of Object.keys(r.unzipped))e(i(s))&&delete r.unzipped[s];}g(po,"ejectPackageMembers");function Ll(t){let e=g(i=>i.startsWith("customXml/"),"isCustomXml"),n=t.pkg.parts.filter(i=>e(i.partname.startsWith("/")?i.partname.substring(1):i.partname)),r=Object.keys(t.pkg.unzipped).filter(e);if(n.length===0&&r.length===0)return [];po(t,e,i=>i.includes("customXml"));for(let i of R(t.element,"w:sdtPr"))Vn(i,"w:dataBinding").forEach(o=>i.removeChild(o));return [`Custom XML parts: ${Math.max(n.length,r.length)} removed`]}g(Ll,"strip_custom_xml");var Dn="docProps/custom.xml";function zl(t){let e=t.pkg.getPartByPath(Dn),n=Object.keys(t.pkg.unzipped).includes(Dn);if(!e&&!n)return [];let r=[];if(e)for(let o of K(e._element,"property")){let s=o.getAttribute("name")||"(unnamed)",a=(o.textContent||"").trim();r.push(` Custom property removed: ${s} = "${Be(a,60)}"`);}return po(t,o=>o===Dn,o=>o.includes("docProps/custom.xml")),[`Custom document properties: ${Math.max(r.length,1)} removed (docProps/custom.xml)`].concat(r)}g(zl,"strip_custom_properties");function Ul(t){let e=t.pkg.getPartByPath("word/settings.xml");if(!e)return [];let n=[],r=false;for(let o of K(e._element,"docVars")){for(let s of Array.from(o.childNodes)){let a=s,l=a.tagName||"";(l==="docVar"||l.endsWith(":docVar"))&&n.push(a.getAttribute("w:name")||a.getAttribute("name")||"(unnamed)");}o.parentNode?.removeChild(o),r=true;}for(let o of K(e._element,"docVar"))n.push(o.getAttribute("w:name")||o.getAttribute("name")||"(unnamed)"),o.parentNode?.removeChild(o),r=true;if(!r)return [];let i=Array.from(new Set(n)).sort().join(", ")||"(unnamed)";return [`Document variables: ${n.length} removed (${i})`]}g(Ul,"strip_document_variables");function Hl(t){let e=0;for(let n of K(t.element,"docPr")){let r=n.getAttribute("descr");if(r){let i=r.length<10,o=r.includes(".")&&r.length<60;(i||o)&&(n.removeAttribute("descr"),e++);}}return e?[`Image alt text: ${e} auto-generated descriptions removed`]:[]}g(Hl,"strip_image_alt_text");function Xl(t){let e=[],n=new Set;for(let r of t.pkg.parts){let i=String(r.partname),o;if(i.startsWith("/word/header"))o="header";else if(i.startsWith("/word/footer"))o="footer";else if(i==="/word/document.xml")o="body";else continue;let s;try{s=K(r._element,"textpath");}catch{continue}for(let a of s){let l=(a.getAttribute("string")||"").trim(),u=`${o}${l}`;if(n.has(u))continue;n.add(u);let c=l?`"${Be(l,60)}"`:"(no text)";e.push(`Watermark-like text object in ${o}: ${c} \u2014 NOT removed. It remains in the document package and may render in other applications; review and remove it in Word if it must not reach the counterparty.`);}}return e}g(Xl,"detect_watermarks");function ql(t){let e=["sharepoint.com","onedrive.com",".internal","intranet","localhost","10.","192.168.","172.16."],n=[],r=t.pkg.getOrCreateRelsPart(t.part.partname);for(let i of R(r._element,"Relationship"))if(i.getAttribute("TargetMode")==="External"){let o=i.getAttribute("Target")||"";for(let s of e)if(o.toLowerCase().includes(s.toLowerCase())){n.push(`Hyperlink targets internal URL: ${Be(o,80)}`);break}}return n}g(ql,"audit_hyperlinks");var Gl="word/settings.xml",Jl=new Set(["readOnly","forms","comments","trackedChanges"]),Yl={readOnly:"read-only",forms:"fill-in-forms",comments:"comments-only",trackedChanges:"tracked-changes-only"},yt=Object.freeze({edit:null,enforced:false});function sn(t){return t.edit!==null&&t.enforced}g(sn,"isProtectionActive");function cr(t){return t.edit===null?"unprotected":`${Yl[t.edit]??t.edit}, ${t.enforced?"enforced":"not enforced"}`}g(cr,"describeProtection");function Ql(t){return t==null?true:!["0","false","off"].includes(t.toLowerCase())}g(Ql,"isTruthy");function _o(t){let e=null;try{let o=t?.pkg?.getPartByPath?.(Gl);if(!o?._element)return yt;e=K(o._element,"documentProtection")[0]??null;}catch{return yt}if(!e)return yt;let n=null,r=null,i=e.attributes;if(i)for(let o=0;o<i.length;o++){let s=i[o],a=(s.name??"").split(":").pop()??"";a==="edit"?n=s.value:a==="enforcement"&&(r=s.value);}return n===null||!Jl.has(n)?yt:{edit:n,enforced:Ql(r)}}g(_o,"readDocumentProtection");var an="ignore_control_locks",bt="ignore_document_protection",ur="allow_untracked_writes",Je=Object.freeze({ignore_control_locks:false,ignore_document_protection:false,allow_untracked_writes:false});function Vl(t){return t.ignore_control_locks||t.ignore_document_protection||t.allow_untracked_writes}g(Vl,"anyOverrideUsed");function he(t){let e=[`CC:${t.ordinal}`];return t.alias&&e.push(`"${t.alias}"`),t.tag&&e.push(`(tag: ${t.tag})`),e.join(" ")}g(he,"describeControl");function fe(t,e){let n=`- Edit ${t} Failed: ${e.subject} ${e.rule} ${Zl(e.alternative)}`;return e.override&&(n+=` Pass ${e.override}=true to override deliberately.`),n.split(/\s+/).join(" ")}g(fe,"gateError");function Zl(t){let e=t.replace(/\s+$/,"");return /[.!?:]$/.test(e)?e:`${e}.`}g(Zl,"endSentence");function Kl(t){return t.find(e=>e.contentLocked)??null}g(Kl,"lockedAncestor");function ec(t,e,n=Je){if(n.ignore_control_locks)return null;let r=Kl(e);return r?fe(t,{subject:`edit targets content inside ${he(r)}, which is content-locked (sdtContentLocked).`,rule:"Word refuses edits inside locked controls, so this edit would silently fail to appear in the document.",alternative:"Remove the lock in Word (Developer -> Properties)",override:an}):null}g(ec,"checkContentLock");function tc(t,e,n=Je){if(n.ignore_control_locks)return null;let r=e.find(i=>i.cls==="group");return !r||e.some(i=>i.cls!=="group")?null:fe(t,{subject:`edit targets text inside ${he(r)}, which is a group (a locked region).`,rule:"Word treats a group's own text as fixed boilerplate and only permits edits to the fields nested inside it.",alternative:"Target one of the nested controls instead",override:an})}g(tc,"checkGroupRegion");function nc(t,e,n,r=Je){if(r.ignore_control_locks||!n)return null;let i=e.find(o=>o.deleteLocked);return i?fe(t,{subject:`edit would remove ${he(i)} itself, which is delete-locked (sdtLocked).`,rule:"Word refuses to delete a locked control, and hoisting its content out would dissolve the wrapper.",alternative:"Delete the control's CONTENT instead (the wrapper stays, leaving an empty field)",override:an}):null}g(nc,"checkDeleteLock");function rc(t,e,n={}){let r=n.overrides??Je;if(!sn(e)||r.ignore_document_protection)return null;let i=cr(e);return e.edit==="readOnly"?fe(t,{subject:`the document is protected (${i}).`,rule:"Word blocks every modification while read-only protection is enforced.",alternative:"Remove the restriction in Word (Review -> Restrict Editing -> Stop Protection)",override:bt}):e.edit==="comments"?n.isCommentOnly?null:fe(t,{subject:`the document is protected (${i}).`,rule:"Word permits only comments while comments-only protection is enforced; text mutations are blocked.",alternative:"Attach a comment instead (set new_text equal to target_text and supply comment)",override:bt}):e.edit==="forms"?(n.controls??[]).some(s=>s.cls!=="group")?null:fe(t,{subject:`the document is protected (${i}).`,rule:"Word permits only form-field fills while fill-in-forms protection is enforced; body text outside a content control is locked.",alternative:"Target the content of a form field instead",override:bt}):null}g(rc,"checkProtectionBlocksEdit");function ic(t,e,n,r=Je){if(!sn(n)||r.ignore_document_protection||e!=="accept"&&e!=="reject"||n.edit!=="trackedChanges"&&n.edit!=="readOnly")return null;let i=n.edit==="readOnly"?"Word blocks every modification while read-only protection is enforced.":"Resolving revisions is exactly what this protection forbids, so Word refuses Accept and Reject.";return `- Action ${t} Failed: the document is protected (${cr(n)}). ${i} Remove the restriction in Word (Review -> Restrict Editing -> Stop Protection) or pass ${bt}=true to override deliberately.`}g(ic,"checkProtectionBlocksReview");function oc(t,e,n=Je){return !sn(e)||e.edit!=="forms"||n.allow_untracked_writes?null:fe(t,{subject:`the document is protected (${cr(e)}).`,rule:"Word records fills in a forms-protected document as UNTRACKED changes, so Adeu cannot honour its guarantee that every write is a tracked change.",alternative:"Remove the protection to write tracked changes normally",override:ur})}g(oc,"checkUntrackedWrite");function sc(t,e,n){let r=(e||"").trim();if(!r)return null;for(let i of n){if(!i.showingPlaceholder)continue;let o=(i.placeholderText||"").trim();if(!(!o||!o.includes(r)))return fe(t,{subject:`target_text is the placeholder text of ${he(i)}, which is EMPTY.`,rule:"Placeholder text is a ghost prompt, not content: Word discards it as soon as the field is filled, so an edit to it would be silently lost.",alternative:`Fill the field with set_field, or insert at its empty pair {#cc:${i.ordinal}}{#/cc:${i.ordinal}}`})}return null}g(sc,"checkPlaceholderTarget");var vt=["[ ]","[x]"];function ac(t,e,n,r){let i=e.find(s=>s.cls==="checkbox");if(!i)return null;let o=vt;return o.includes(n.trim())&&o.includes(r.trim())?null:fe(t,{subject:`edit targets ${he(i)}, which is a checkbox.`,rule:"Its [x] / [ ] projection reflects the w14:checked state rather than editable text, so replacing it with other text would leave the checkbox state unchanged.",alternative:"Toggle it by replacing [x] with [ ] (or the reverse), or use set_field"})}g(ac,"checkCheckboxEdit");function lc(t,e){let n=e.find(i=>i.bound);if(!n)return null;let r=n.bindingXpath?` (bound to ${n.bindingXpath})`:"";return fe(t,{subject:`edit targets the content of ${he(n)}, which is data-bound${r}.`,rule:"Its text is a projection of an XML data store, and Word re-reads that store when the document opens, so an edit that skips the store is reverted.",alternative:"Use set_field, which writes the control and its bound store together"})}g(lc,"checkBoundControl");function ri(t,e,n){let r=new Set(e),i=new Set(n);return t.filter(o=>r.has(o)!==i.has(o))}g(ri,"crossedControlWalls");function cc(t,e){if(e.length===0)return null;let n=e.map(he).join(", ");return fe(t,{subject:`edit merges paragraphs across the boundary of ${n}.`,rule:"Content may not be hoisted into or out of a content control by a merge: the wrapper would gain or lose text that was never scoped to it.",alternative:"Split this into two edits, one on each side of the control boundary"})}g(cc,"checkBlockMergeAcrossControl");function uc(t){return `segmented at the boundary of ${t.map(he).join(", ")}: only the text outside the control was changed`}g(uc,"segmentationNote");function dc(t,e){if(!Vl(t))return null;let n=[];if(t.ignore_control_locks){let r=e.length>0?` (${e.map(he).join(", ")} edited inside locked controls)`:"";n.push(`${an}${r}`);}return t.ignore_document_protection&&n.push(bt),t.allow_untracked_writes&&n.push(ur),"Overrides: "+n.join(", ")}g(dc,"overridesNote");function fc(t,e,n=2){if(t===e)return 0;if(Math.abs(t.length-e.length)>n)return n+1;if(t.length===0)return e.length<=n?e.length:n+1;if(e.length===0)return t.length<=n?t.length:n+1;if(t.length>e.length){let i=t;t=e,e=i;}let r=Array.from({length:t.length+1},(i,o)=>o);for(let i=1;i<=e.length;i++){let o=[i],s=i;for(let a=1;a<=t.length;a++){let l=t[a-1]===e[i-1]?0:1,u=Math.min(r[a]+1,o[a-1]+1,r[a-1]+l);o.push(u),u<s&&(s=u);}if(s>n)return n+1;r=o;}return r[t.length]<=n?r[t.length]:n+1}g(fc,"boundedLevenshtein");function hc(t){let e="",n=R(t._element,"w:r");for(let r of n)e+=Pe(new Re(r,t));return e}g(hc,"_get_paragraph_text");var dr="[A-Z][A-Za-z0-9\\s\\-&'\u2019]{1,60}",pc=new RegExp(`^(?:[\\d.\\-()a-zA-Z]+\\s*)?["\u201C](${dr})["\u201D]`,"d"),_c=new RegExp(`(?<=[.;:!?])\\s+(?:[\\d.\\-()a-zA-Z]+\\s+)?["\u201C](${dr})["\u201D]`,"dg"),mc=new RegExp(`\\([^)]*?["\u201C](${dr})["\u201D][^)]*?\\)`,"dg");function gc(t){let e=[],n=pc.exec(t);n&&n.indices&&n.indices[1]&&e.push([n.indices[1][0],n[1].trim()]);for(let o of t.matchAll(_c)){let s=o.indices;s&&s[1]&&e.push([s[1][0],o[1].trim()]);}for(let o of t.matchAll(mc)){let s=o.indices;s&&s[1]&&e.push([s[1][0],o[1].trim()]);}let r=[],i=new Set;e.sort((o,s)=>o[0]-s[0]);for(let[o,s]of e)i.has(o)||(i.add(o),r.push(s));return r}g(gc,"extract_terms_from_paragraph");function wc(t,e){let n={},r=new Set,i={},o=[];for(let p of Le(t)){if(!(p instanceof ne))continue;let m=hc(p).trim();if(!m)continue;for(let b of gc(m))n[b]?r.add(b):n[b]={count:0};let w=m.length>60?m.substring(0,60)+"...":m,v=R(p._element,"*");for(let b of v){if(b.tagName==="w:bookmarkStart"){let x=b.getAttribute("w:name");x&&(!x.startsWith("_")||x.startsWith("_Ref"))&&(i[x]||(i[x]={anchored_to:w,referenced_from:[]}));}let y=null;if(b.tagName==="w:fldSimple"){let k=(b.getAttribute("w:instr")||"").trim().split(/\s+/);k.length>1&&k[0]==="REF"&&(y=k[1]);}else if(b.tagName==="w:instrText"){let k=(b.textContent||"").trim().split(/\s+/);k.length>1&&k[0]==="REF"&&(y=k[1]);}y&&o.push([y,w]);}}for(let[p,m]of o)i[p]&&i[p].referenced_from.push(m);let s=[],a=Object.keys(n);if(a.length>0){let p=a.sort((b,y)=>y.length-b.length),m=g(b=>b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegExp"),w=p.map(m).join("|"),v=new RegExp(`(?<!["\u201C])\\b(${w})\\b(?![\u201D"])`,"g");for(let b of e.matchAll(v)){let y=b[1];n[y]&&n[y].count++;}for(let b of a)n[b].count===0&&(delete n[b],r.has(b)||s.push(`[Warning] Unused Definition: '${b}' is defined but never used.`));}for(let p of r)s.push(`[Error] Duplicate Definition: '${p}' is defined multiple times.`);let l=new Set(["The","This","That","Such","A","An","Any","All","Some","No","Every","Each","As","In","Of","For","To","On","By","With"]),u=/\b[A-Z][a-zA-Z]*(?:\s+[A-Z][a-zA-Z]*)*\b/g,c=new Set(e.match(u)||[]),d=new Set(Object.keys(n)),f={};for(let p of d){let m=p[0].toLowerCase();f[m]||(f[m]=[]),f[m].push(p);}let h={};for(let p of c){let m=p.trim(),w=m.split(/\s+/);for(;w.length>0;){let y=w[0],x=y.charAt(0).toUpperCase()+y.slice(1).toLowerCase();if(l.has(x))w.shift();else break}if(m=w.join(" "),m.length<4||d.has(m))continue;let v=m[0].toLowerCase(),b=f[v]||[];if(m.length>5)for(let[y,x]of Object.entries(f))y!==v&&(b=b.concat(x));for(let y of b){if(Math.abs(m.length-y.length)>2||m===y+"s"||m===y+"es"||y===m+"s"||y===m+"es")continue;let x=fc(m,y,2);x===0||x>2||y.length<=5&&(x>1||m[0].toLowerCase()!==y[0].toLowerCase())||(h[y]||(h[y]=[]),h[y].includes(m)||h[y].push(m));}}for(let[p,m]of Object.entries(h)){m.sort();let w=m.map(v=>`'${v}'`).join(", ");s.push(`[Info] Possible Typos for '${p}': Found ${w}`);}function _(p){return p.startsWith("[Error]")?0:p.startsWith("[Warning]")?1:2}return g(_,"diag_sort_key"),s.sort((p,m)=>{let w=_(p),v=_(m);return w!==v?w-v:p.localeCompare(m)}),[n,s,i]}g(wc,"extract_all_domain_metadata");function yc(t){let e=[],n=t.pkg.getPartByPath("word/settings.xml");if(!n)return e;let r=g(s=>{if(!s.hasAttribute("w:val"))return true;let a=(s.getAttribute("w:val")||"").toLowerCase();return a!=="0"&&a!=="false"&&a!=="off"},"isTruthy2"),i=K(n._element,"removePersonalInformation");i.length>0&&r(i[0])&&e.push("[Warning] Privacy flag `removePersonalInformation` is enabled in word/settings.xml. Microsoft Word will strip the `w:author`, `w:initials`, and `w:date` attributes from every tracked change and comment the next time this document is opened and saved. Edits made by this agent will lose attribution, breaking audit trails and any multi-turn workflow that relies on identifying prior edits.");let o=K(n._element,"removeDateAndTime");return o.length>0&&r(o[0])&&e.push("[Warning] Privacy flag `removeDateAndTime` is enabled in word/settings.xml. Microsoft Word will strip the `w:date` attribute from every tracked change and comment the next time this document is opened and saved. Timestamps on this agent's edits will be lost on the next Word save."),e}g(yc,"extract_document_settings_warnings");function vc(t,e){try{let n=Hc(t),r=_o(t);return Gc(n,r,'Read with mode="fields" for the full field ledger.')}catch{return []}}g(vc,"content_controls_appendix_section");function bc(t,e){let[n,r,i]=wc(t,e),o=yc(t),s=[`
76
86
 
77
- ${a}`:a);}else i=[...r];let o=i.length;return {pages:i.map((a,u)=>({page:u+1,total_pages:o,has_next:u+1<o,has_prev:u+1>1,tracked_change_count:ar(a),page_content:a})),total_pages:o,body_pages:r,body_page_offsets:s}}g(Ge,"paginate");function Jo(t){let e=Xo(t);return Go(e)}g(Jo,"_tokenize_into_atomic_blocks");function Xo(t){let e={"++}":0,"--}":0,"==}":0,"<<}":0},n=[],r=0,s=0,i=t.length;for(;s<i;){let o=false;for(let[a,u]of Object.entries(or))if(t.startsWith(a,s)){e[u]++,s+=a.length,o=true;break}if(o)continue;let l=false;for(let a of Object.values(or))if(t.startsWith(a,s)){e[a]>0&&e[a]--,s+=a.length,l=true;break}if(!l){if(t[s]===`
78
- `&&s+1<i&&t[s+1]===`
79
- `&&Object.values(e).every(a=>a===0)){let a=t.substring(r,s);a&&n.push([a,r]);let u=s;for(;u<i&&t[u]===`
80
- `;)u++;s=u,r=s;continue}s++;}}if(r<i){let o=t.substring(r,i);o&&n.push([o,r]);}return n}g(Xo,"_split_on_safe_paragraph_breaks");function Go(t){if(!t.length)return t;let e=[],n=0;for(;n<t.length;){let[r,s]=t[n],i=r.trimStart();if(!(i.startsWith("## Footnotes")||i.startsWith("## Endnotes"))){e.push([r,s]),n++;continue}let l=r,a=n+1;for(;a<t.length;){let[u]=t[a],c=u.trimStart();if(c.startsWith("[^fn-")||c.startsWith("[^en-"))l=`${l}
87
+ ---`,"","<!-- READONLY_BOUNDARY_START -->","# Document Structure (Read-Only)","The content below is metadata describing the document's reference structure. Do not include this section in any tracked changes or edits \u2014 it is for your context only and will be discarded on write."],a=false;if(o.length>0){a=true,s.push(`
88
+ ## Document Settings`);for(let u of o)s.push(`- ${u}`);}let l=vc(t);if(l.length>0&&(a=true,s.push(""),s.push(...l)),Object.keys(n).length>0){a=true,s.push(`
89
+ ## Defined Terms`);for(let[u,c]of Object.entries(n))s.push(`- "${u}" \u2014 used ${c.count} time${c.count===1?"":"s"}.`);}if(r.length>0){a=true,s.push(`
90
+ ## Semantic Diagnostics`);for(let u of r)s.push(`- ${u}`);}if(Object.keys(i).length>0){a=true,s.push(`
91
+ ## Named Anchors`);for(let[u,c]of Object.entries(i)){s.push(`- ${u} \u2192 Anchored to: "${c.anchored_to}"`);for(let d of c.referenced_from)s.push(` - Referenced from: "${d}"`);}}return a?s.join(`
92
+ `):""}g(bc,"build_structural_appendix");async function Ye(t,e=false,n=true){let r=await ce.load(t);return Qe(r,e,n)}g(Ye,"extractTextFromBuffer");function Qe(t,e=false,n=true,r=false,i=false){let o=Me(t.pkg),s=[],a=new Map,l=i?{part_ranges:[],tables:[]}:null,u=0,c=Kt(Array.from(qe(t)).map(([f])=>en(f)));for(let[f,h]of qe(t)){let _=s.length>0?u+2:u,p=Yt(f,o,e,_,r?a:void 0,l?l.tables:void 0,c);p&&(s.length>0&&(u+=2),s.push(p),l&&l.part_ranges.push([u,u+p.length,h]),u+=p.length);}let d=s.join(`
81
93
 
82
- ${u}`,a++;else break}e.push([l,s]),n=a;}return e}g(Go,"_merge_footnote_sections");function Qo(t){if(!t.length)return [[""],[0]];let e=[],n=[],r=[],s=0,i=-1,o=g(()=>{r.length>0&&(e.push(r.join(`
94
+ `);if(n){let f=bc(t,d);f&&(d+=f);}return r?{text:d,paragraph_offsets:a}:l?{text:d,structure:l}:d}g(Qe,"_extractTextFromDoc");function Yt(t,e,n,r,i,o,s,a=false){let l=t.part||t,[u,c]=lt(l),d=[],f=r,h=true,_=true;if(t.constructor&&t.constructor.name==="NotesPart"){let m=`---
95
+ ${t.note_type==="fn"?"## Footnotes":"## Endnotes"}`;d.push(m),f+=m.length,h=false;}for(let p of Le(t,!!s)){h||(f+=2);let m=f;if(p instanceof rr){let w=s?s.get(p.element):void 0,v=!!w&&kt(w),b=a?"":`
96
+ `,y=v?`${Oe(w)}${b}`:"",x=Yt({_element:O(p.element,"w:sdtContent"),part:t.part||t},e,n,m+y.length,i,void 0,s,a);if(x){let k=v?`${y}${x}${b}${De(w)}`:x;d.push(k),f=m+k.length,h=false;}else h||(f-=2);_=false;}else if(p.constructor.name==="FootnoteItem"){let w=Yt(p,e,n,m,i,void 0,s);w?(d.push(w),f=m+w.length,h=false):h||(f-=2);}else if(p instanceof ne){let w=We(p,u,c);_&&t.constructor.name==="FootnoteItem"&&(w=`[^${t.note_type}-${t.id}]: `+w);let v=Tt(p,e,n,u,c,s);if(n&&!v&&eo(p._element)){h||(f-=2),_=false;continue}let b=w+v;d.push(b),i&&i.set(p._element,[m,b.length]),f=m+b.length,_=false,h=false;}else if(p instanceof Fe){let w=o?{start:m,end:m,rows:[]}:null,v=ln(p,e,n,m,i,w,s);v?(d.push(v),f=m+v.length,h=false,w&&o&&(w.end=m+v.length,o.push(w))):h||(f-=2),_=false;}}return d.join(`
83
97
 
84
- `)),n.push(i)),r=[],s=0,i=-1;},"flush_current");for(let[l,a]of t){let u=l.length,c=u+(r.length>0?2:0);if(r.length>0&&s+c>sr&&o(),r.length===0&&u>sr){e.push(l),n.push(a);continue}r.length===0&&(i=a),r.push(l),s+=s>0?c:u;}return o(),e.length?[e,n]:[[""],[0]]}g(Qo,"_assemble_pages");function ar(t){let e=[...t.matchAll(qo)];return new Set(e.map(r=>r[1])).size}g(ar,"_count_tracked_changes");var Yo=5,lr=50;function Vo(t,e,n,r){let s=r.length;if(s<2)throw new Error(`format_ambiguity_error requires at least 2 matches, got ${s}`);let i=r.slice(0,Yo),o=s-i.length,l=[`- Edit ${t} Failed: Ambiguous match. Target text appears ${s} times. First ${i.length} occurrences:`];for(let a=0;a<i.length;a++){let[u,c]=i[a],d=Math.max(0,u-lr),f=Math.min(n.length,c+lr),h=n.substring(d,u).replace(/\n/g," "),_=n.substring(c,f).replace(/\n/g," "),p=n.substring(u,c).replace(/\n/g," ");p.length>50&&(p=p.substring(0,25)+"..."+p.substring(p.length-20));let m=d>0?"...":"",y=f<n.length?"...":"";l.push(` ${a+1}. "${m}${h}[${p}]${_}${y}"`);}return o>0&&l.push(` ... and ${o} more occurrence(s) not shown.`),l.push(" To resolve, re-send this edit using ONE of these strategies:"),l.push(' 1. RECOMMENDED: Provide more surrounding context in your target_text to uniquely identify a single location (keep the default "match_mode": "strict").'),l.push(` 2. Set "match_mode": "all" to modify ALL ${s} occurrences \u2014 only after verifying from the occurrence list above that EVERY occurrence should change.`),l.push(' 3. Set "match_mode": "first" to modify only the FIRST occurrence \u2014 only after verifying the first occurrence above is the one you intend to change.'),l.join(`
85
- `)}g(Vo,"format_ambiguity_error");var Zo="2.4.1",cr=280,be=30;function xe(t){let e=t.nextSibling;for(;e;){if(e.nodeType===1)return e;e=e.nextSibling;}return null}g(xe,"getNextElement");function Ae(t){let e=t.previousSibling;for(;e;){if(e.nodeType===1)return e;e=e.previousSibling;}return null}g(Ae,"getPreviousElement");function qe(t,e){e.parentNode&&e.parentNode.insertBefore(t,e.nextSibling);}g(qe,"insertAfter");function Ko(t){let e=[...t.pkg.parts],n={...t.pkg.unzipped},r=new Map,s=new Map,i=new Set;for(let o of e){if(r.set(o,new Map(o.rels)),!o._element)continue;let l=o._element.ownerDocument;l&&wn(l)&&typeof o.blob=="string"?i.add(o):s.set(o,o._element.cloneNode(true));}return {parts:e,unzipped:n,rels:r,elements:s,blobRestores:i}}g(Ko,"takeSnapshot");function ea(t,e){t.pkg.parts=[...e.parts];for(let n of Object.keys(t.pkg.unzipped))delete t.pkg.unzipped[n];for(let[n,r]of Object.entries(e.unzipped))t.pkg.unzipped[n]=r;for(let n of e.parts){if(n.rels=new Map(e.rels.get(n)),e.blobRestores&&e.blobRestores.has(n)){let s=je(n.blob);it(s),n._element=s.documentElement;continue}let r=e.elements.get(n);if(r&&n._element){let s=n._element.ownerDocument;s&&s.documentElement&&s.replaceChild(r,s.documentElement),n._element=r;}}}g(ea,"restoreSnapshot");function ta(t,e){if(!t||!e)return [t,e];if(e.includes(`
86
- `))return [t,e];let n=t.match(/^(#+)\s+/),r=e.match(/^(#+)\s+/);if(n&&r&&n[1]===r[1]){let s=n[1],i=t.substring(s.length).trimStart(),o=e.substring(s.length).trimStart();return [i,o]}return [t,e]}g(ta,"stripMatchingHeadingHashes");function un(t){let e=/^-\s*(?:Action|Edit|Note: Action)\s+(\d+)\b/i,n=[];for(let r of t){let s=r?r.split(`
87
- `)[0]:"",i=e.exec(s);if(i){let o=parseInt(i[1],10)-1,l=r.split("Failed: "),a=l.length>1?l.slice(1).join("Failed: ").trim():r.trim();n.push([o,a]);}else n.push([0,r.trim()]);}return n}g(un,"extract_failed_indices");var mt=class extends Error{static{g(this,"BatchValidationError");}errors;failed;constructor(t,e){super(`Batch validation failed:
98
+ `)}g(Yt,"_extract_blocks");function ii(t,e){if(!e)return null;let n=Ui(t);if(!n)return null;let r=e.get(n);return r&&kt(r)?r:null}g(ii,"anchoredWrapper");function ln(t,e,n,r,i,o,s){let a=[],l=0,u=r;for(let c of t.rows){let d=[],f=new Set,h=O(c._element,"w:trPr"),_=h?O(h,"w:ins"):null,p=h?O(h,"w:del"):null;if(n&&p)continue;let m=u+(l>0?1:0),v=m+(!n&&_||!n&&p?4:0),b=true;for(let k of c.cells){if(f.has(k))continue;f.add(k),b||(v+=3);let N=ii(k._element,s),P=N?Oe(N):"",A=Yt(k,e,n,v+P.length,i,void 0,s,true);if(N&&(A=`${P}${A}${De(N)}`),!n){let{paraId:C}=Ri(k._element,!A||A.trim()==="");if(C){let T=A&&!A.endsWith(" ")?" ":"";A=A+`${T}{#cell:${C}}`;}}d.push(A),v+=A.length,b=false;}let y=d.join(" | "),x=ii(c._element,s);if(x&&(y=`${Oe(x)}${y}${De(x)}`),n||(_?y=`{++ ${y} ++}{>>[Chg:${_.getAttribute("w:id")} insert] ${_.getAttribute("w:author")||"Unknown"}<<}`:p&&(y=`{-- ${y} --}{>>[Chg:${p.getAttribute("w:id")} delete] ${p.getAttribute("w:author")||"Unknown"}<<}`)),a.push(y),u=m+y.length,o&&o.rows.push({start:m,end:u,cells:[...d]}),l++,l===1){let k=d.length;if(k>0){let N=Array(k).fill("---").join(" | ");a.push(N),u+=1+N.length;}}}return a.join(`
99
+ `)}g(ln,"extract_table");function Tt(t,e,n,r,i,o){let s=[],a={},l={},u=new Set,c={},d=[],f=null,h="",_=["",""],p=["",""],m=Array.from(on(t,o)),w=to(t,r,i),v=rn(t,r,i),b=w,y=g(()=>{h&&(s.push(`${_[0]}${h}${_[1]}`),h="",_=["",""],p=["",""]);},"flushPending");for(let x=0;x<m.length;x++){let k=m[x];if(k instanceof Re){let[N,P]=no(k,v),A=Pe(k);if(n&&Object.keys(l).length>0)continue;if(b){if(!A||!A.trim())continue;b=false;}let C=Ka(A,N,P);if(C){let T=n?["",""]:oi(a,l,u,c),M=[N,P];if(h&&T[0]===_[0]&&T[1]===_[1]){let j=M[0].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=M[0]!==""||M[1]!==""?C.match(new RegExp("^(\\s*)"+j)):null,$="";for(let E=h.length-1;E>=0;E--){let S=h[E];if(/\s/.test(S))$=S+$;else break}let I=$?h.slice(0,-$.length):h;M[0]===p[0]&&M[1]===p[1]&&!(p[0]===""&&p[1]==="")&&I.endsWith(p[1])&&B!==null?h=I.slice(0,-p[1].length)+$+B[1]+C.slice(B[0].length):h+=C,p=M;}else y(),h=C,_=T,p=M;if(!n){(Object.keys(a).length>0||Object.keys(l).length>0||u.size>0||Object.keys(c).length>0)&&d.push([{...a},{...l},new Set(u),{...c}]);let B=false;if(Object.keys(a).length>0||Object.keys(l).length>0||Object.keys(c).length>0||u.size>0){let I=x+1,E=false,S=Object.keys(a).length,D=Object.keys(l).length,U=Object.keys(c).length,z=new Set(u);for(;I<m.length;){let W=m[I];if(W instanceof Re){if(!Pe(W)){I++;continue}(S>0||D>0||U>0||z.size>0)&&(E=true);break}else {let L=W;L.type==="ins_start"?S++:L.type==="ins_end"?S=Math.max(0,S-1):L.type==="del_start"?D++:L.type==="del_end"?D=Math.max(0,D-1):L.type==="fmt_start"?U++:L.type==="fmt_end"?U=Math.max(0,U-1):L.type==="start"?z.add(L.id):L.type==="end"&&z.delete(L.id);}I++;}E&&(B=true);}if(!B&&d.length>0){let I=si(d,e);I&&(zi(m,x)?f=I:(y(),s.push(`{>>${I}<<}`))),d.length=0;}}}}else if(nr(k)){b=false;let N=k.info;if(Li.includes(k.type)){if(n&&Object.keys(l).length>0)continue;let P=k.type==="checkbox_start"?Fi:k.type==="checkbox_end"?Wi:tr(N),A=n?["",""]:oi(a,l,u,c);h&&(A[0]!==_[0]||A[1]!==_[1])&&(s.push(`${_[0]}${h}${_[1]}`),h=""),h||(_=A),h+=P,p=["",""],k.type==="checkbox_end"&&f&&(s.push(`${_[0]}${h}${_[1]}`),h="",_=["",""],s.push(`{>>${f}<<}`),f=null);continue}y(),k.type==="sdt_start"?(s.push(Oe(N)),!n&&N.showingPlaceholder&&N.placeholderText&&s.push(`{>>placeholder: ${N.placeholderText}<<}`)):s.push(De(N));}else {let N=k;if(b=false,["ins_start","ins_end","del_start","del_end","fmt_start","fmt_end"].includes(N.type)||y(),N.type==="start")u.add(N.id);else if(N.type==="end")u.delete(N.id);else if(N.type==="ins_start")a[N.id]=N;else if(N.type==="ins_end")delete a[N.id];else if(N.type==="del_start")l[N.id]=N;else if(N.type==="del_end")delete l[N.id];else if(N.type==="fmt_start")c[N.id]=N;else if(N.type==="fmt_end")delete c[N.id];else if(N.type==="image"){if(!(n&&Object.keys(l).length>0)){let P=(N.date||"image").replace(/\]/g,")").replace(/\n/g," ");s.push(`![${P}](docx-image:${N.id})`);}}else N.type==="footnote"||N.type==="endnote"?(y(),s.push(`[^${N.type==="footnote"?"fn":"en"}-${N.id}]`)):N.type==="hyperlink_start"?(y(),s.push("[")):N.type==="hyperlink_end"?(y(),s.push(`](${N.date})`)):N.type==="xref_start"?(y(),s.push("[~")):N.type==="xref_end"?(y(),s.push(`~](#${N.id})`)):N.type==="bookmark"&&(y(),s.push(`{#${N.id}}`));}}if(y(),d.length>0){let x=si(d,e);x&&s.push(`{>>${x}<<}`);}return s.join("")}g(Tt,"build_paragraph_text");function oi(t,e,n,r){return Object.keys(e).length>0?["{--","--}"]:Object.keys(t).length>0?["{++","++}"]:n.size>0||Object.keys(r).length>0?["{==","==}"]:["",""]}g(oi,"_get_wrappers");function si(t,e){let n=[],r=[],i=new Set,o=io(t),s=g(l=>o[l]?` (pairs with ${o[l]})`:"","pairSuffix");for(let[l,u,c,d]of t){let f=g(function(p){if(!e[p])return;let m=`Com:${p}`;if(i.has(m))return;let w=e[p],v=`[${m}] ${w.author}`;if(w.date&&(v+=` @ ${w.date}`),w.resolved&&(v+="(RESOLVED)"),r.push(`${v}: ${qi(w.text)}`),i.add(m),h[p]){let b=h[p].sort((y,x)=>(e[y]?.date||"").localeCompare(e[x]?.date||""));for(let y of b)f(y);}},"render_comment2");for(let[p,m]of Object.entries(l)){let w=`Chg:${p}`;i.has(w)||(n.push(`[${w} insert] ${m.author||"Unknown"}${s(p)}`),i.add(w));}for(let[p,m]of Object.entries(u)){let w=`Chg:${p}`;i.has(w)||(n.push(`[${w} delete] ${m.author||"Unknown"}${s(p)}`),i.add(w));}for(let[p,m]of Object.entries(d)){let w=`Chg:${p}`;i.has(w)||(n.push(`[${w} format] ${m.author||"Unknown"}`),i.add(w));}let h={};for(let[p,m]of Object.entries(e)){let w=m.parent_id;w&&(h[w]||(h[w]=[]),h[w].push(p));}let _=Array.from(c).sort();for(let p of _)f(p);}return [...n,...r].join(`
100
+ `)}g(si,"_build_merged_meta_block");var mo=/^(#{1,6}) /,go=3;function wo(t,e){for(let n=0;n<t.length;n++){let r=t[n],i=e;for(let o=n+1;o<t.length;o++)if(t[o].level<=r.level){i=t[o].page>r.page?t[o].page-1:r.page;break}r.end_page=i;}}g(wo,"_assign_end_pages");function yo(t,e,n,r,i=null){if(n.length!==r.length)throw new Error("body_pages and body_page_offsets length mismatch");if(i)return Tc(t,e,r,i);let o=Me(t.pkg),s=Nc(t,o),a=[];for(let u=0;u<s.length;u++){let c=s[u];c.is_paragraph&&Ct(c.item)&&Ac(c.item,o)&&a.push(u);}if(a.length===0)return [];let l=[];for(let u=0;u<a.length;u++){let c=a[u],d=s[c],f=d.item,h=Qt(f),_=ko(f,o),p=cn(f),m=Cc(s,a,u,h),w=s.slice(c+1,m),v=xc(s,c+1,m),b=Pc(w),y=fr(d.start_offset,r);l.push({level:h,text:_,page:y,style:p,has_table:v,footnote_ids:b,end_page:y});}return wo(l,n.length),l}g(yo,"extract_outline");function xc(t,e,n){for(let r=e;r<n;r++){let i=t[r];if(i.is_paragraph&&Ct(i.item))return false;if(i.is_table)return true}return false}g(xc,"_direct_has_table");function Nc(t,e){let n=Array.from(rl(t)),r=0,i=null;for(let l of n){if(l===t){i=l;break}let u=xo(l,e);u&&(r>0&&(r+=2),r+=u.length);}i?r>0&&(r+=2):(i=t,r=0);let o=[],s=r,a=true;for(let l of Le(i))if(l instanceof ne){let u=We(l),c=Tt(l,e,false),d=(u+c).length;a||(s+=2),o.push({item:l,is_paragraph:true,is_table:false,start_offset:s,projected_length:d}),s+=d,a=false;}else if(l instanceof Fe){let u=ln(l,e,false,0),c=u?u.length:0;a||(s+=2);let d=s;o.push({item:l,is_paragraph:false,is_table:true,start_offset:d,projected_length:c}),bo(l,d,o,e),s+=c,a=false;}return o}g(Nc,"_walk_doc_body");function vo(t,e,n,r){let i=e._element,o=n,s=0;for(let a of t.rows){if(s>0)if(s===1){let c=t.rows[0],d=new Set,f=0;for(let _ of c.cells)d.has(_)||(d.add(_),f+=1);let h=f>0?Array(f).fill("---").join(" | ").length:0;o+=1+h+1;}else o+=1;let l=new Set,u=0;for(let c of a.cells){if(l.has(c))continue;l.add(c),u>0&&(o+=3);let[d,f]=kc(c,i,o,r);if(f)return d;o=d,u++;}s++;}return n}g(vo,"_compute_inner_block_offset");function kc(t,e,n,r){let i=n,o=true;for(let s of Le(t)){if(o||(i+=2),s instanceof ne){if(s._element===e)return [i,true];let a=We(s),l=Tt(s,r,false);i+=(a+l).length;}else if(s instanceof Fe){let a=vo(s,new ne(e,null),i,r);if(a!==i&&Ec(e,s._element))return [a,true];let l=ln(s,r,false,0);i+=l?l.length:0;}o=false;}return [i,false]}g(kc,"_walk_cell_for_offset");function Ec(t,e){let n=t.parentNode;for(;n;){if(n===e)return true;n=n.parentNode;}return false}g(Ec,"_element_is_descendant");function bo(t,e,n,r){let i=new Set;for(let o of t.rows)for(let s of o.cells)if(!i.has(s)){i.add(s);for(let a of Le(s))if(a instanceof ne){let l=Ct(a)?vo(t,a,e,r):e;n.push({item:a,is_paragraph:true,is_table:false,start_offset:l,projected_length:0});}else a instanceof Fe&&(n.push({item:a,is_paragraph:false,is_table:true,start_offset:e,projected_length:0}),bo(a,e,n,r));}}g(bo,"_record_table_inner_blocks_lite");function xo(t,e){let n=[],r=t.constructor.name;if(r==="NotesPart"){let o=t.note_type==="fn"?"## Footnotes":"## Endnotes";n.push(`---
101
+ ${o}`);}let i=true;for(let o of Le(t))if(o.constructor.name==="FootnoteItem"){let s=xo(o,e);s&&n.push(s);}else if(o instanceof ne){let s=We(o);i&&r==="FootnoteItem"&&(s=`[^${t.note_type}-${t.id}]: ${s}`);let a=Tt(o,e,false);n.push(s+a),i=false;}else if(o instanceof Fe){let s=ln(o,e,false,0);s&&n.push(s),i=false;}return n.join(`
102
+
103
+ `)}g(xo,"_project_part");function Ct(t){return mo.test(We(t))}g(Ct,"_is_heading");function Ac(t,e){let n=ko(t,e);return No(n)?cn(t)!=="(heuristic)"?true:(n.match(/\w+/g)||[]).length>=go:false}g(Ac,"_heading_passes_quality_filter");function No(t){if(!t)return false;let e=t.replace(/\{#[^}]+\}/g,"");return /\w/.test(e)}g(No,"_heading_text_has_words");function Qt(t){let e=mo.exec(We(t));return e?Math.min(e[1].length,6):1}g(Qt,"_heading_level");var ai=200;function ko(t,e){let n=Tt(t,e,false),r=Ao(n);return r=r.replace(/\n+/g," "),r=Co(r),Eo(r.trim())}g(ko,"_heading_text");function Eo(t){if(t.length<=ai)return t;let e=t.substring(0,ai),n=/\{#[^}\n]*$/.exec(e);return n!==null&&(e=e.substring(0,n.index)),e.trimEnd()+"\u2026"}g(Eo,"_truncate_outline_text");function Ao(t){return t?(t=t.replace(/\{--[\s\S]*?--\}/g,""),t=t.replace(/\{>>[\s\S]*?<<\}/g,""),t=t.replace(/\{\+\+([\s\S]*?)\+\+\}/g,"$1"),t=t.replace(/\{==([\s\S]*?)==\}/g,"$1"),t):""}g(Ao,"_strip_critic_markup");function Co(t){if(!t)return "";let e=[];return t=t.replace(/\{#[^}]+\}|_{3,}/g,n=>(e.push(n),`\0${e.length-1}\0`)),t=t.replace(/\*\*(.+?)\*\*/g,"$1"),t=t.replace(/__(.+?)__/g,"$1"),t=t.replace(/(?<!\w)_(\S(?:.*?\S)?)_(?!\w)/g,"$1"),t=t.replace(/\x00(\d+)\x00/g,(n,r)=>e[Number(r)]),t}g(Co,"_strip_inline_formatting");function cn(t){let[e,n]=lt(t._parent.part||t._parent),r=O(t._element,"w:pPr"),i=n;if(r){let u=O(r,"w:pStyle");u&&(i=u.getAttribute("w:val")||n);}let o=null,s=false;if(r){let u=O(r,"w:outlineLvl");u&&/^\d+$/.test(u.getAttribute("w:val")||"")&&(o=parseInt(u.getAttribute("w:val"),10));}o===null&&i&&e&&e[i]&&(o=e[i].outline_level,s=true);let l=i&&e&&e[i]?e[i].name:i;return l&&typeof l=="string"&&(l.toLowerCase().startsWith("heading")?l=l.replace(/^heading/i,"Heading"):l.toLowerCase()==="title"&&(l="Title")),s&&o!==null&&(l&&(l.startsWith("Heading")||l==="Title")||(o=null)),o!==null&&o>=0&&o<=8?l&&(l.startsWith("Heading")||l==="Title")?l:"(outline_level)":l&&(l.startsWith("Heading")||l==="Title")||l&&/Heading[ ]?([1-6])(?![0-9])/.test(l)?l:"(heuristic)"}g(cn,"_determine_heading_style");function Cc(t,e,n,r){for(let i=n+1;i<e.length;i++){let o=e[i];if(Qt(t[o].item)<=r)return o}return t.length}g(Cc,"_find_owned_end");function Pc(t){let e=new Set,n=[];for(let r of t)if(r.is_paragraph)for(let i of on(r.item)){if(!("type"in i))continue;let o="";if(i.type==="footnote")o=`fn-${i.id}`;else if(i.type==="endnote")o=`en-${i.id}`;else continue;e.has(o)||(e.add(o),n.push(o));}return n}g(Pc,"_collect_footnote_ids");function Po(t){return t.replace(/\{--.*?--\}/g,"").replace(/\{\+\+(.*?)\+\+\}/g,"$1").replace(/\{==(.*?)==\}/g,"$1").replace(/\{>>.*?<<\}/g,"").replace(/\{(?:>>|--).*$/g,"").replace(/\{\+\+|\{==|--\}|\+\+\}|<<\}|==\}/g,"").replace(/\*\*|__|[*_]/g,"").replace(/\{#[^}]+\}/g,"").trim()}g(Po,"clean_breadcrumb");function fr(t,e){if(!e||e.length===0)return 1;let n=1;for(let r=0;r<e.length&&t>=e[r];r++)n=r+1;return n}g(fr,"offset_to_page");function Tc(t,e,n,r){let i=[],o=new Set;function s(u){for(let c of Le(u))if(c.constructor.name==="FootnoteItem")s(c);else if(c instanceof ne)i.push(["p",c]);else if(c instanceof Fe){i.push(["t",c]);for(let f of c.rows)for(let h of f.cells)o.has(h._element)||(o.add(h._element),s(h));}}g(s,"walk"),s(t);let a=[];for(let u=0;u<i.length;u++){let[c,d]=i[u];if(c!=="p")continue;let f=false;r instanceof Map?f=r.has(d._element):f=d._element in r,f&&Ct(d)&&$c(d,e,r)&&a.push(u);}if(a.length===0)return [];let l=[];for(let u=0;u<a.length;u++){let c=a[u],d=i[c][1],f=Qt(d),h=To(d,e,r),_=cn(d),p=c;for(let x=u+1;x<a.length;x++){let k=a[x],N=i[k][1];if(Qt(N)<=f){p=k;break}}p===c&&(p=i.length);let m=i.slice(c+1,p),w=false;for(let[x,k]of m){if(x==="p"&&Ct(k))break;if(x==="t"){w=true;break}}let v=Sc(m),b;r instanceof Map?b=r.get(d._element):b=r[d._element];let y=1;if(b!==void 0){let[x]=b;y=fr(x,n);}l.push({level:f,text:h,page:y,style:_,has_table:w,footnote_ids:v,end_page:y});}return wo(l,n.length),l}g(Tc,"_extract_outline_fast");function $c(t,e,n){let r=To(t,e,n);return No(r)?cn(t)!=="(heuristic)"?true:(r.match(/\w+/g)||[]).length>=go:false}g($c,"_heading_passes_quality_filter_fast");function To(t,e,n){let r;if(n instanceof Map?r=n.get(t._element):r=n[t._element],r===void 0)return "";let[i,o]=r,s=e.substring(i,i+o),a=Ao(s);return a=a.replace(/\n+/g," "),a=Co(a),a=a.replace(/^#+\s+/,""),Eo(a.trim())}g(To,"_heading_text_fast");function Sc(t){let e=new Set,n=[];for(let[r,i]of t)if(r==="p")for(let o of on(i)){if(!("type"in o))continue;let s="";if(o.type==="footnote")s=`fn-${o.id}`;else if(o.type==="endnote")s=`en-${o.id}`;else continue;e.has(s)||(e.add(s),n.push(s));}return n}g(Sc,"_collect_footnote_ids_fast");var Ic=80;var Oc={readOnly:"read-only",forms:"fill-in-forms only",comments:"comments only",trackedChanges:"tracked-changes only"},Dc={"repeating-item":"item"},$o=new Set(["group","repeating","repeating-item"]);function Rc(t){if(t.edit===null)return "none";let e=Oc[t.edit]??t.edit;return t.enforced?`${e} (enforced)`:e}g(Rc,"protectionLabel");var li=/\{#(\/?)cc:(\d+)(?: [^}]*)?\}/g;function Mc(t){let e=new Map,n=new Map;li.lastIndex=0;let r;for(;(r=li.exec(t))!==null;){let o=Number(r[2]);r[1]?n.has(o)||n.set(o,r.index):e.has(o)||e.set(o,[r.index,r.index+r[0].length]);}let i=new Map;for(let[o,[s,a]]of e){let l=n.get(o);l!==void 0&&l>=a&&i.set(o,[s,a,l]);}return i}g(Mc,"scanAnchors");var jc=class{static{g(this,"HeadingIndex");}starts=[];paths=[];constructor(t){let e=[],n=0;for(let r of t.split(`
104
+ `)){let i=r.match(/^(#{1,6})\s+(.*)/);if(i){let o=i[1].length,s=Po(i[2]);for(s.length>80&&(s=s.slice(0,80)+"...");e.length>0&&e[e.length-1].level>=o;)e.pop();let a=(e.length>0?e[e.length-1].path:[]).concat([s]);e.push({level:o,path:a}),this.starts.push(n),this.paths.push(a.join(" > "));}n+=r.length+1;}}pathAt(t){if(this.starts.length===0)return "";let e=0,n=this.starts.length-1,r=-1;for(;e<=n;){let i=e+n>>1;this.starts[i]<=t?(r=i,e=i+1):n=i-1;}return r>=0?this.paths[r]:""}};function ci(t,e=Ic){let n=Po(t).replace(/\s+/g," ").trim();return n.length>e?n.slice(0,e)+"\u2026":n}g(ci,"preview");function hr(t){if(!t)return [];let e=[];for(let n=t.firstChild;n;n=n.nextSibling)n.nodeType===1&&e.push(n);return e}g(hr,"childElements");function un(t){return t?.tagName??t?.nodeName??""}g(un,"tagOf");function ui(t){let e=O(t,Ge);return e?hr(e).filter(n=>{let r=un(n);return r==="w:p"||r==="w:tbl"}):[]}g(ui,"blockChildren");function Bc(t){let e=O(t,Ge);return e?hr(e).filter(n=>un(n)===at):[]}g(Bc,"directChildSdts");function Fc(t){let e=O(t,Ge);return e?R(e,at).length:0}g(Fc,"nestedSdtCount");function Bt(t,e){return t===1?`${t} ${e}`:`${t} ${e}s`}g(Bt,"plural");function Wc(t){return t.cls==="group"?`wraps ${Bt(ui(t.element).length,"block")}, ${Bt(Fc(t.element),"nested field")}`:t.cls==="repeating"?Bt(Bc(t.element).length,"item"):t.cls==="repeating-item"?`wraps ${Bt(ui(t.element).length,"block")}`:null}g(Wc,"extentFor");function Lc(t){let e=O(t.element,Ge);if(!e)return null;let n=hr(e)[0];if(!n)return null;let r=un(n);return r==="w:tr"?"table row":r==="w:tc"?"table cell":null}g(Lc,"containerKind");function zc(t,e){let n=[];return e&&n.push("EMPTY"),t.contentLocked?n.push("LOCKED (contents)"):t.cls==="group"?n.push("LOCKED (group)"):t.deleteLocked&&n.push("LOCKED (no-delete)"),t.bound&&n.push(`BOUND \u2192 ${t.bindingXpath??""}`.trimEnd()),t.temporary&&n.push("TEMPORARY"),n}g(zc,"statesFor");function Uc(t){let e=O(t,Ge);return e?R(e,"w:t").some(n=>(n.textContent??"").trim().length>0):false}g(Uc,"hasText");function Hc(t){let e=Kt(Array.from(qe(t)).map(([s])=>en(s))),n=0,r=0,i=0,o=0;for(let s of e.values())n+=1,$o.has(s.cls)||s.cls==="checkbox"||(s.showingPlaceholder||!Uc(s.element))&&(r+=1),(s.cls==="group"||s.contentLocked)&&(i+=1),s.bound&&(o+=1);return [n,r,i,o]}g(Hc,"fieldSummary");function Xc(t,e,n){let r=Kt(Array.from(qe(t)).map(([c])=>en(c))),i=Array.from(r.values()).sort((c,d)=>c.ordinal-d.ordinal),o=g(c=>{let d=c.element?.parentNode??null;for(;d;){if(un(d)===at){let f=r.get(d);if(f)return f.ordinal}d=d.parentNode??null;}return null},"parentOrdinal"),s=Mc(e),a=new jc(e),l=[],u=0;for(let c of i){let d=s.get(c.ordinal);d&&(u=d[0]);let f=u,h=n?fr(f,n):1,_=a.pathAt(f),p=null,m=null,w=null,v=c.showingPlaceholder;if(c.cls==="checkbox")m=c.checked?"checked":"unchecked";else if(!$o.has(c.cls)){if(d){let b=ci(e.slice(d[1],d[2]));b?p=b:v=true;}}v&&c.placeholderText&&(w=ci(c.placeholderText)),l.push({ordinal:c.ordinal,cls_word:Dc[c.cls]??c.cls,alias:c.alias,tag:c.tag,page:h,heading_path:_,container_kind:Lc(c),parent_ordinal:o(c),states:zc(c,v),value:p,checkbox_state:m,placeholder:w,options:c.options.map(([b])=>b),date_format:c.dateFormat,extent:Wc(c),empty:v,locked:c.cls==="group"||c.contentLocked,bound:c.bound});}return l}g(Xc,"collectFields");function qc(t){let[e,n,r,i]=t;return e===0?"no content controls":`${e} content controls \u2014 ${n} empty \xB7 ${r} locked \xB7 ${i} bound`}g(qc,"summaryText");function Gc(t,e,n=""){if(t[0]===0&&e.edit===null)return [];let r=["## Content Controls","",`Protection: ${Rc(e)} \xB7 ${qc(t)}`];return n&&r.push(n),r}g(Gc,"renderAppendixSection");var Ft=class extends Error{static{g(this,"FieldResolutionError");}constructor(t){super(t),this.name="FieldResolutionError";}},Jc=30;function di(t){if(!t.length)return "This document has no content controls.";let e=[];for(let i of t)for(let o of [i.tag,i.alias])o&&!e.includes(o)&&e.push(o);let n=e.slice(0,Jc),r=e.length>n.length?` (+${e.length-n.length} more)`:"";if(!n.length){let i=Math.max(...t.map(o=>o.ordinal));return `This document's ${t.length} controls have no tags or aliases; target them by id, CC:1 .. CC:${i}. Run read_docx with mode='fields' for the list.`}return "Available: "+n.join(", ")+r+". Run read_docx with mode='fields' for the full list with ids."}g(di,"availableSummary");function Yc(t,e,n="strict"){if(!e||!e.trim())throw new Ft("set_field requires 'field': the 'CC:<N>' id, tag, or alias of the control to fill. Run read_docx with mode='fields' to list them.");let r=/^CC:(\d+)$/.exec(e.trim());if(r){let s=Number(r[1]),a=t.filter(l=>l.ordinal===s);if(a.length)return a;throw new Ft(`No content control with id 'CC:${s}'. ${di(t)}`)}let i=t.filter(s=>s.tag===e);if(i.length||(i=t.filter(s=>s.alias===e)),!i.length)throw new Ft(`No content control matches field '${e}'. ${di(t)}`);if(i.length===1||n==="all")return [...i];if(n==="first")return [i[0]];let o=i.map(s=>`CC:${s.ordinal}`).join(", ");throw new Ft(`Field '${e}' matches ${i.length} controls (${o}). Target one by its 'CC:<N>' id, or set match_mode='first' to take the first or match_mode='all' to fill every occurrence.`)}g(Yc,"resolveField");function pr(t){let e=[],n=t?.childNodes;if(!n)return e;for(let r=0;r<n.length;r++)n[r].nodeType===1&&e.push(n[r]);return e}g(pr,"childrenOf");function we(t,e){for(let n of pr(t))if(n.tagName===e)return n;return null}g(we,"findChild4");function So(t,e){return t?.getElementsByTagName?Array.from(t.getElementsByTagName(e)):[]}g(So,"descendants");function it(t){return we(t,"w:sdtContent")}g(it,"sdtContent");function ct(t){return we(t,"w:sdtPr")}g(ct,"sdtPr");function Qc(t){let e=it(t);return e?So(e,"w:r"):[]}g(Qc,"contentRuns");function fi(t){let e=ct(t.element);if(!e)return false;let n=we(e,"w:showingPlcHdr");if(!n)return false;e.removeChild(n);let r=it(t.element);if(r)for(let i of So(r,"w:r"))i.parentNode?.removeChild(i);return true}g(fi,"clearPlaceholder");function Vc(t){let e=it(t),n=t.parentNode;if(!e||!n)return false;for(let r of pr(e))n.insertBefore(r,t);return n.removeChild(t),true}g(Vc,"unwrapSdt");var Zc=new Set(["text","richtext","dropdown","combobox","date","checkbox"]),Kc={group:"Edit the fields nested inside it individually - each has its own CC: id.",repeating:"Fill the fields inside a specific item instead; repeating-section operations (add/remove item) are not supported in v1.","repeating-item":"Fill the fields inside the item instead; repeating-section operations (add/remove item) are not supported in v1.",picture:"Picture controls hold an image, which set_field cannot write.","building-block":"Building-block galleries insert document parts, not text."};function eu(t){let e=ct(t.element);if(!e)return false;let n=we(e,"w:text");if(!n)return false;let r=n.getAttribute("w:multiLine");return r!==null&&r!==""&&!["0","false","off"].includes(String(r).toLowerCase())}g(eu,"isMultiline");function hi(t,e){if(Zc.has(t))return null;let n=Kc[t]??"set_field fills value-bearing fields only.";return `CC:${e} is a ${t} and is not a value-bearing field. ${n} set_field fills text, rich-text, dropdown, combobox, date and checkbox controls.`}g(hi,"refuseClass");function pi(t,e,n){if(t.cls==="dropdown"){let[,r]=Io(t,n);return r?`CC:${e}: ${r}`:null}return t.cls==="date"?Hn(n)===null?`CC:${e} is a date control; '${n}' is not a date. Use the canonical YYYY-MM-DD form (e.g. 2026-03-01).`:null:t.cls!=="text"?null:n.includes(`
105
+
106
+ `)?`CC:${e} is a plain-text control and cannot hold paragraphs. Remove the blank line, or use a rich-text control for multi-paragraph content.`:n.includes(`
107
+ `)&&!eu(t)?`CC:${e} is a single-line plain-text control and cannot hold a line break. Remove the newline, or set the control's multiLine property in Word.`:null}g(pi,"refuseValue");var tu=new Set(["true","x","[x]","checked","1","yes","on"]),nu=new Set(["false","[ ]","[]","unchecked","0","no","off",""]);function _i(t){let e=t.trim().toLowerCase();return tu.has(e)?true:nu.has(e)?false:null}g(_i,"parseCheckboxValue");function ru(t,e){let n=e?["\u2612",null]:["\u2610",null],r=ct(t.element);if(!r)return n;let i=we(r,"w14:checkbox");if(!i)return n;let o=we(i,e?"w14:checkedState":"w14:uncheckedState");if(!o)return n;let s=o.getAttribute("w14:val"),a=o.getAttribute("w14:font");return [s?String.fromCodePoint(parseInt(s,16)):n[0],a||null]}g(ru,"checkboxGlyph");function iu(t,e){let n=ct(t.element);if(!n)return;let r=we(n,"w14:checkbox");if(!r)return;let i=we(r,"w14:checked");i||(i=r.ownerDocument.createElement("w14:checked"),r.appendChild(i)),i.setAttribute("w14:val",e?"1":"0");}g(iu,"setCheckboxChecked");function ou(t){let e=Qc(t.element);return e.length?e[0]:null}g(ou,"glyphRun");function Io(t,e){let n=t.options??[];if(!n.length)return [e,null];for(let[i]of n)if(i===e)return [i,null];for(let[i,o]of n)if(o&&o===e)return [i,null];if(t.cls==="combobox")return [e,null];let r=n.map(([i])=>i).join(" | ");return [null,`'${e}' is not one of this dropdown's options. Choose one of: ${r}.`]}g(Io,"resolveOption");function su(t,e){return (t.options??[]).some(([n,r])=>n===e||!!r&&r===e)}g(su,"optionIsListed");function au(t,e){let n=ct(t.element);if(n)for(let r of ["w:dropDownList","w:comboBox"]){let i=we(n,r);if(i){i.setAttribute("w:lastValue",e);return}}}g(au,"setDropdownLastValue");var lu=new Set(["yyyy","MM","M","dd","d"]);function Hn(t){let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t.trim());if(!e)return null;let n=Number(e[1]),r=Number(e[2]),i=Number(e[3]),o=new Date(Date.UTC(n,r-1,i));return o.getUTCFullYear()!==n||o.getUTCMonth()!==r-1||o.getUTCDate()!==i?null:[n,r,i]}g(Hn,"parseIsoDate");var Ce=g((t,e)=>String(t).padStart(e,"0"),"pad");function cu(t,e){let[n,r,i]=t,o=`${Ce(n,4)}-${Ce(r,2)}-${Ce(i,2)}`;if(!e)return [o,false];let s=e.match(/[A-Za-z]+/g)??[];if(!s.length||s.some(l=>!lu.has(l)))return [o,true];let a={yyyy:Ce(n,4),MM:Ce(r,2),M:String(r),dd:Ce(i,2),d:String(i)};return [e.replace(/[A-Za-z]+/g,l=>a[l]),false]}g(cu,"renderDate");function uu(t,e){let n=ct(t.element);if(!n)return;let r=we(n,"w:date");if(!r)return;let[i,o,s]=e;r.setAttribute("w:fullDate",`${Ce(i,4)}-${Ce(o,2)}-${Ce(s,2)}T00:00:00Z`);}g(uu,"setFullDate");var du=["ds:itemID","itemID"];function mi(t){return (t.split("/").pop()??"").replace(/\D/g,"")}g(mi,"digitsOf");var fu={"6c3c8bc8-f283-45ae-878a-bab7291924a1":"docProps/core.xml","6668398d-a668-4e3e-a5eb-62b293d839f1":"docProps/app.xml","55af091b-3c7a-41e3-b477-f2fdaa23cfda":"docProps/custom.xml"};function hu(t,e){if(!e)return null;let n=e.replace(/[{}]/g,"").toLowerCase(),r=t?.part?.package?.parts??[],i=fu[n];if(i)return r.find(l=>String(l.partname).replace(/^\//,"")===i)??null;let o=r.filter(a=>String(a.partname).includes("/customXml/itemProps")),s=r.filter(a=>String(a.partname).includes("/customXml/item")&&!String(a.partname).includes("itemProps"));for(let a of o){let l=a._element;if(!l)continue;let u=null;for(let f of du){let h=l.getAttribute?.(f);if(h){u=h;break}}if(!u||u.replace(/[{}]/g,"").toLowerCase()!==n)continue;let c=mi(String(a.partname)),d=s.find(f=>mi(String(f.partname))===c);if(d)return d}return null}g(hu,"findBoundStore");function pu(t){let e=t?.tagName??t?.nodeName??"",n=e.indexOf(":"),r=n===-1?"xmlns":`xmlns:${e.slice(0,n)}`;for(let i=t;i&&i.nodeType===1;i=i.parentNode){let o=i.getAttribute?.(r);if(o)return o}return null}g(pu,"namespaceUriOf");function _u(t){let e={};if(!t)return e;let n=/xmlns:([\w.-]+)\s*=\s*['"]([^'"]*)['"]/g,r;for(;(r=n.exec(t))!==null;)e[r[1]]=r[2];return e}g(_u,"parsePrefixMappings");function mu(t,e,n){let r=e.split("/").filter(a=>a.length>0);if(!r.length)return null;let i=_u(n),o=g(a=>a?.split(":").pop(),"localOf"),s=null;for(let a=0;a<r.length;a++){let l=/^([A-Za-z_][\w.-]*(?::[A-Za-z_][\w.-]*)?)(?:\[(\d+)\])?$/.exec(r[a]);if(!l)return null;let u=l[1],c=l[2]?Number(l[2]):1,d=u.lastIndexOf(":"),f=d===-1?u:u.slice(d+1),h=d===-1?void 0:i[u.slice(0,d)];if(a===0){let p=t.tagName??t.nodeName;if(o(p)!==f||c!==1)return null;s=t;continue}let _=pr(s).filter(p=>o(p.tagName??p.nodeName)===f);if(h){let p=_.filter(m=>pu(m)===h);p.length&&(_=p);}if(_.length<c)return null;s=_[c-1];}return s}g(mu,"resolveBindingPath");function gu(t,e,n,r){if(!e||!t?._element)return false;let i=mu(t._element,e,r);if(!i)return false;for(let o of Array.from(i.childNodes??[]))i.removeChild(o);return i.appendChild(i.ownerDocument.createTextNode(n)),true}g(gu,"writeBoundValue");var gi=280,Ee=30;function Ae(t){let e=t.nextSibling;for(;e;){if(e.nodeType===1)return e;e=e.nextSibling;}return null}g(Ae,"getNextElement");function Ie(t){let e=t.previousSibling;for(;e;){if(e.nodeType===1)return e;e=e.previousSibling;}return null}g(Ie,"getPreviousElement");function nt(t,e){e.parentNode&&e.parentNode.insertBefore(t,e.nextSibling);}g(nt,"insertAfter");function wu(t){let e=[...t.pkg.parts],n={...t.pkg.unzipped},r=new Map,i=new Map,o=new Set;for(let s of e){if(r.set(s,new Map(s.rels)),!s._element)continue;let a=s._element.ownerDocument;a&&er(a)&&typeof s.blob=="string"?o.add(s):i.set(s,s._element.cloneNode(true));}return {parts:e,unzipped:n,rels:r,elements:i,blobRestores:o}}g(wu,"takeSnapshot");function yu(t,e){t.pkg.parts=[...e.parts];for(let n of Object.keys(t.pkg.unzipped))delete t.pkg.unzipped[n];for(let[n,r]of Object.entries(e.unzipped))t.pkg.unzipped[n]=r;for(let n of e.parts){if(n.rels=new Map(e.rels.get(n)),e.blobRestores&&e.blobRestores.has(n)){let i=Xe(n.blob);Nt(i),n._element=i.documentElement;continue}let r=e.elements.get(n);if(r&&n._element){let i=n._element.ownerDocument;i&&i.documentElement&&i.replaceChild(r,i.documentElement),n._element=r;}}}g(yu,"restoreSnapshot");function vu(t,e){if(!t||!e)return [t,e];if(e.includes(`
108
+ `))return [t,e];let n=t.match(/^(#+)\s+/),r=e.match(/^(#+)\s+/);if(n&&r&&n[1]===r[1]){let i=n[1],o=t.substring(i.length).trimStart(),s=e.substring(i.length).trimStart();return [o,s]}return [t,e]}g(vu,"stripMatchingHeadingHashes");function Xn(t){let e=/^-\s*(?:Action|Edit|Note: Action)\s+(\d+)\b/i,n=[];for(let r of t){let i=r?r.split(`
109
+ `)[0]:"",o=e.exec(i);if(o){let s=parseInt(o[1],10)-1,a=r.split("Failed: "),l=a.length>1?a.slice(1).join("Failed: ").trim():r.trim();n.push([s,l]);}else n.push([0,r.trim()]);}return n}g(Xn,"extract_failed_indices");var Wt=class extends Error{static{g(this,"BatchValidationError");}errors;failed;constructor(t,e){super(`Batch validation failed:
88
110
  `+t.join(`
89
- `)),this.name="BatchValidationError",this.errors=t,this.failed=e??un(t);}};function ur(t){return `
90
- Note: ${t} earlier edit(s) in this batch validated against the intermediate document state; because this batch failed, it was rolled back and nothing was saved. Batches apply sequentially \u2014 each edit must target the document text as it reads AFTER the preceding edits (e.g. target the replacement text an earlier edit introduced, not the original wording).`}g(ur,"sequential_context_hint");var na=/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,ra={"w:sectPr":new Set(["w:headerReference","w:footerReference"])},dn=["w:ins","w:del"],fn=["w:pPrChange","w:rPrChange","w:sectPrChange"],Kt=[...dn,...fn];function ia(t){if(!t)return null;let e=t.match(na);return e?Array.from(new Set(e.map(r=>`0x${r.charCodeAt(0).toString(16).padStart(2,"0")}`))).sort().join(", "):null}g(ia,"describe_illegal_control_chars");function sa(t,e=0){let n=[];for(let r=0;r<t.length;r++){let s=t[r],i=s.target_text||"",o=s.new_text||"",l=[["target_text",i],["new_text",o]];s.comment&&l.push(["comment",s.comment]),(s.cells||[]).forEach((a,u)=>{l.push([`cells[${u}]`,a||""]);});for(let[a,u]of l){let c=ia(u);c&&n.push(`- Edit ${r+1+e} Failed: \`${a}\` contains control character(s) (${c}) that cannot be stored in a DOCX. Remove them and re-submit.`);}if((o.includes("{++")||o.includes("{--")||o.includes("{>>")||o.includes("{=="))&&n.push(`- Edit ${r+1+e} Failed: Do not manually write CriticMarkup tags ({++, {--, {>>, {==) in \`new_text\`. The engine handles redlining automatically. To add a comment, use the \`comment\` parameter.`),i.includes("[^")||o.includes("[^")){let a=(i.match(/\[\^(?:fn|en)-[^\]]+\]/g)||[]).sort(),u=(o.match(/\[\^(?:fn|en)-[^\]]+\]/g)||[]).sort();JSON.stringify(a)!==JSON.stringify(u)&&(u.length>a.length||u.some(c=>u.filter(d=>d===c).length>a.filter(d=>d===c).length)?n.push(`- Edit ${r+1+e} Failed: Cannot insert footnote/endnote markers via text replace. Markers like \`[^fn-N]\` are read-only projections. Use Word's References menu.`):n.push(`- Edit ${r+1+e} Failed: Cannot delete footnote/endnote references via text replace. The marker corresponds to a structural XML element.`));}if(i.includes("](")||o.includes("](")){let a=(i.match(/\[(?!~)[^\]]+\]\([^)]+\)/g)||[]).sort(),u=(o.match(/\[(?!~)[^\]]+\]\([^)]+\)/g)||[]).sort();a.length!==u.length?u.length>a.length?n.push(`- Edit ${r+1+e} Failed: Cannot insert hyperlinks via text replace. Inserting new hyperlinks is not supported; insert the display text instead (editing the text or URL of an existing link IS supported).`):n.push(`- Edit ${r+1+e} Failed: Cannot delete hyperlinks via text replace. The marker corresponds to a structural XML element.`):a.length>1&&JSON.stringify(a)!==JSON.stringify(u)&&n.push(`- Edit ${r+1+e} Failed: Can only edit or retarget one hyperlink per text replacement. Please split into multiple edits.`);}if(i.includes("[~")||o.includes("[~")){let a=i.match(/\[~[^~]+~\]\(#[^\)]+\)/g)||[],u=o.match(/\[~[^~]+~\]\(#[^\)]+\)/g)||[];a.length!==u.length?u.length>a.length?n.push(`- Edit ${r+1+e} Failed: Cannot insert cross-references via text replace. Markers are read-only projections.`):n.push(`- Edit ${r+1+e} Failed: Cannot delete cross-references via text replace. The marker corresponds to a structural XML element.`):JSON.stringify(a)!==JSON.stringify(u)&&n.push(`- Edit ${r+1+e} Failed: Modifying or retargeting cross-reference markers is disallowed to prevent dependency corruption.`);}if(i.includes("docx-image:")||o.includes("docx-image:")){let a=(i.match(/!\[[^\]]*\]\(docx-image:[^)]*\)/g)||[]).sort(),u=(o.match(/!\[[^\]]*\]\(docx-image:[^)]*\)/g)||[]).sort();JSON.stringify(a)!==JSON.stringify(u)&&n.push(`- Edit ${r+1+e} Failed: image markers (![alt](docx-image:N)) are read-only projections of embedded images. They cannot be inserted, altered, or removed via text replacement \u2014 edit the text around the image instead.`);}if(i.includes("{#")||o.includes("{#")){let a=i.match(/\{#[^\}]+\}/g)||[],u=o.match(/\{#[^\}]+\}/g)||[];for(let c of u)if(u.filter(d=>d===c).length>a.filter(d=>d===c).length){n.push(`- Edit ${r+1+e} Failed: Cannot modify or insert internal anchor markers (\`{#...}\`). These represent structural XML bookmarks.`);break}}if(s.type==="modify"&&o){let a=o.split(/[\r\n]+/);for(let u of a){let c=u.trimStart();if(c.startsWith("#######")){let d=c.length-c.replace(/^#+/,"").length;if(c.substring(d).startsWith(" ")||c.substring(d)===""){n.push(`- Edit ${r+1+e} Failed: Heading level ${d} is not supported (maximum is 6).`);break}}}}(i.includes("READONLY_BOUNDARY_START")||o.includes("READONLY_BOUNDARY_START")||i.includes("# Document Structure (Read-Only)")||o.includes("# Document Structure (Read-Only)")||i.includes("Document Structure (Read-Only)")||o.includes("Document Structure (Read-Only)"))&&n.push(`- Edit ${r+1+e} Failed: Modification targets the read-only boundary (Structural Appendix). This section cannot be edited.`);}return n}g(sa,"validate_edit_strings");var Tt=class V{static{g(this,"_RedlineEngine");}doc;author;timestamp;current_id;mapper;comments_manager;clean_mapper=null;original_mapper=null;skipped_details=[];removed_comment_notes=[];rollback_verified=true;id_discovery_hint;_revisionIndex=null;constructor(e,n="Adeu AI (TS)",r){this.doc=e,this.author=n,this.id_discovery_hint=r?.id_discovery_hint??null,this.timestamp=new Date().toISOString().replace(/\.\d{3}Z$/,"Z");let s="http://schemas.microsoft.com/office/word/2023/wordml/word16du";for(let i of this.doc.pkg.parts)if(i===this.doc.part&&!i._element.hasAttribute("xmlns:w16du")){let o=i._element.ownerDocument,l=wn(o);i._element.setAttribute("xmlns:w16du",s),l&&it(o);}this.current_id=this._scan_existing_ids(),this.mapper=new ve(this.doc),this.comments_manager=new st(this.doc);}_check_punctuation_warning(e){return !e||e.length>20||e.includes(" ")?null:e.includes("_")||e.includes("-")?`Warning: target_text '${e}' contains tokenization-splitting punctuation ('_' or '-'). This can trigger mid-word splits in the diff engine. Consider using a longer plain-prose anchor.`:null}_single_commented_sub_edit(e,n,r,s,i,o){let l,a,u,c;if(e===n)l=e,a=n,u=r,c="COMMENT_ONLY";else {let[f,h]=Je(e,n);l=e.slice(f,e.length-h),a=n.slice(f,n.length-h),u=r+f,!l&&a?c="INSERTION":l&&!a?c="DELETION":c="MODIFICATION";}let d={type:"modify",target_text:l,new_text:a,comment:s};return d._resolved_start_idx=u,d._match_start_index=u,d._active_mapper_ref=o,d._internal_op=c,i&&(d._is_table_edit=true),[d]}_word_diff_sub_edits(e,n,r,s=null,i=false,o=null){if(s!=null)return this._single_commented_sub_edit(e,n,r,s,i,o);let l=[];try{l=xt(e,n);}catch{l=[];}let a=g(d=>{let f=d.trim();return f.length>0&&/^[*_]+$/.test(f)},"_marker_only");if(l=l.filter(d=>!((!d.target_text||a(d.target_text))&&(!d.new_text||a(d.new_text))&&(d.target_text||d.new_text))),!l||l.length===0){let d={type:"modify",target_text:e,new_text:n,comment:s};return d._resolved_start_idx=r,d._match_start_index=r,d._active_mapper_ref=o,i&&(d._is_table_edit=true),e===n?d._internal_op="COMMENT_ONLY":!e&&n?d._internal_op="INSERTION":e&&!n?d._internal_op="DELETION":e&&n?d._internal_op="MODIFICATION":d._internal_op="COMMENT_ONLY",[d]}let u=[],c=false;for(let d of l){let f=r+(d._match_start_index||0),h=s!==null&&!c;h&&(c=true);let _={type:"modify",target_text:d.target_text,new_text:d.new_text,comment:h?s:null};_._resolved_start_idx=f,_._match_start_index=f,_._active_mapper_ref=o,i&&(_._is_table_edit=true);let p=d.target_text,m=d.new_text;!p&&m?_._internal_op="INSERTION":p&&!m?_._internal_op="DELETION":p&&m?_._internal_op="MODIFICATION":_._internal_op="COMMENT_ONLY",u.push(_);}return u}_nearest_match_hint(e,n){if(!e)return "";let r=e;if(n&&(r=r.replace(/^\^/,"").replace(/\$$/,""),r=r.replace(/^\\s\*/,"").replace(/\\s\*$/,""),r=r.replace(/\\([.^$*+?()[\]{}|\\/])/g,"$1")),r=r.trim(),(!r||r===e)&&!n)return "";let s=this.mapper.full_text.indexOf(r);if(s!==-1){let i=Math.max(0,s-15),o=Math.min(this.mapper.full_text.length,s+r.length+15),l=this.mapper.full_text.substring(i,o).replace(/\n/g," ");return `
91
- Did you mean the literal "${r}"? It appears in the document (\u2026${l}\u2026). If you used a regex, drop the ^/$ anchors \u2014 they match the start/end of the entire document, not a line.`}return ""}static _PREVIEW_WRAPPER_PAIRS=[["{--","--}"],["{++","++}"],["{==","==}"],["{>>","<<}"]];static _tidy_preview_context(e,n){e=e.replace(/\{>>[\s\S]*?<<\}/g,"");for(let[r,s]of V._PREVIEW_WRAPPER_PAIRS)if(n==="before"){let i=0,o=0,l=0;for(;l<e.length;)e.startsWith(r,l)?(i+=1,l+=r.length):e.startsWith(s,l)?(i===0?o=l+s.length:i-=1,l+=s.length):l+=1;e=e.substring(o);}else {let i=[],o=0;for(;o<e.length;)e.startsWith(r,o)?(i.push(o),o+=r.length):e.startsWith(s,o)?(i.length>0&&i.pop(),o+=s.length):o+=1;i.length>0&&(e=e.substring(0,i[0]));}return n==="before"?e=e.replace(/^[-+=<>]{0,2}\}/,""):e=e.replace(/\{[-+=<>]{0,2}$/,""),e}_capture_preview_context(e){if(e.type!=="modify")return;let n=e._resolved_start_idx;if(n==null)return;let s=(e._active_mapper_ref||this.mapper).full_text;if(!s)return;let i=(e.target_text||"").length,o=s.substring(Math.max(0,n-be),n),l=s.substring(n+i,n+i+be);e._preview_context=[V._tidy_preview_context(o,"before"),V._tidy_preview_context(l,"after")];}_capture_parent_preview_context(e){if(!e||e.type!=="modify"||e._preview_context||!e._preview_span)return;let[n,r]=e._preview_span,i=(e._preview_mapper_ref||this.mapper).full_text;if(!i)return;let o=i.substring(Math.max(0,n-be),n),l=i.substring(n+r,n+r+be);e._preview_context=[V._tidy_preview_context(o,"before"),V._tidy_preview_context(l,"after")];}_build_full_match_preview(e){let[n,r]=e._preview_context,s=e._preview_matched_text||"",i=e._preview_new_text!==void 0&&e._preview_new_text!==null?e._preview_new_text:e.new_text||"",[o,l]=this._parse_markdown_style(s),[a,u]=this._parse_markdown_style(i);l&&l.startsWith("Heading")&&(n=n+s.substring(0,s.length-o.length),s=o),u&&u.startsWith("Heading")&&(i=a);let[c,d]=Je(s,i),f=s.substring(c,s.length-d),h=i.substring(c,i.length-d);n=n+s.substring(0,c),d&&(r=s.substring(s.length-d)+r),f=de(f,He),h=de(h,He);let _;if(!f&&!h){let m=de(s,He),y=m?`{==${m}==}`:"";_=`${n.substring(0,n.length-s.length)}${y}${r}`;}else {let m=f?`{--${f}--}`:"",y=h?`{++${h}++}`:"";_=`${n}${m}${y}${r}`;}let p=_;return p=p.replace(/\{>>[\s\S]*?<<\}/g,""),p=p.replace(/\{--[\s\S]*?--\}/g,""),p=p.replace(/\{\+\+([\s\S]*?)\+\+\}/g,"$1"),[_,p]}static _report_new_text(e){return e&&e.type==="insert_row"&&Array.isArray(e.cells)?e.cells.join(" | "):e&&e.new_text||""}_build_postapply_previews(e){let n=new Set((e._minted_change_ids||[]).map(y=>String(y))),r=new Set((e._minted_comment_ids||[]).map(y=>String(y)));if(n.size===0&&r.size===0)return null;let s=this.mapper;s.full_text||s._build_map();let i=s.full_text;if(!i)return null;let o=[];for(let y of s.spans)(y.ins_id&&n.has(String(y.ins_id))||y.del_id&&n.has(String(y.del_id))||r.size>0&&y.comment_ids&&y.comment_ids.some(b=>r.has(String(b))))&&o.push([y.start,y.end]);if(o.length===0)return null;let l=/\{>>[\s\S]*?<<\}/g,a=[],u;for(;(u=l.exec(i))!==null;)a.push([u.index,u.index+u[0].length]);let c=i,d=g(y=>y,"to_visible");if(a.length>0){let y=[],x=0;for(let[b,w]of a)y.push(i.substring(x,b)),x=w;y.push(i.substring(x)),c=y.join(""),d=g(b=>{let w=0;for(let[v,N]of a)if(b>=N)w+=N-v;else if(b>v){w+=b-v;break}else break;return b-w},"to_visible");}o.sort((y,x)=>y[0]-x[0]);let f=[];for(let[y,x]of o){let b=d(y),w=d(x),v=Math.max(0,b-be),N=Math.min(c.length,w+be),k=f.length>0?f[f.length-1]:null;k&&v<=k[1]?k[1]=Math.max(k[1],N):f.push([v,N]);}let h=[];for(let[y,x]of f){let b=c.substring(y,x);b=V._tidy_preview_context(b,"before"),b=V._tidy_preview_context(b,"after"),h.push(b);}let _=h.join(`
111
+ `)),this.name="BatchValidationError",this.errors=t,this.failed=e??Xn(t);}};function wi(t){return `
112
+ Note: ${t} earlier edit(s) in this batch validated against the intermediate document state; because this batch failed, it was rolled back and nothing was saved. Batches apply sequentially \u2014 each edit must target the document text as it reads AFTER the preceding edits (e.g. target the replacement text an earlier edit introduced, not the original wording).`}g(wi,"sequential_context_hint");var bu=/[\x00-\x08\x0b\x0c\x0e-\x1f]/g;function yi(t,e){for(;t.endsWith(`
113
+
114
+ `)&&e.endsWith(`
115
+
116
+ `);)t=t.slice(0,-2),e=e.slice(0,-2);return [t,e]}g(yi,"trimSharedTrailingParagraphMark");var vi=/\{#\/?cc:\d+[^}]*\}/g,xu=/^\{#cc:(\d+)[^}]*\}(?:\{>>placeholder:[^<]*<<\})?\{#\/cc:\1\}$/,Nu={"w:sectPr":new Set(["w:headerReference","w:footerReference"])},qn=["w:ins","w:del"],Gn=["w:pPrChange","w:rPrChange","w:sectPrChange"],Lt=[...qn,...Gn];function Rn(t){return t.startsWith("/")?t.substring(1):t}g(Rn,"normalize_part_name");var ku=["application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml","application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml","application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml","application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml"];function Eu(t){if(!t)return null;let e=t.match(bu);return e?Array.from(new Set(e.map(r=>`0x${r.charCodeAt(0).toString(16).padStart(2,"0")}`))).sort().join(", "):null}g(Eu,"describe_illegal_control_chars");function Au(t,e=0){let n=[];for(let r=0;r<t.length;r++){let i=t[r],o=i.target_text||"",s=i.new_text??i.value??"",a=[["target_text",o],["new_text",s]];i.comment&&a.push(["comment",i.comment]),(i.cells||[]).forEach((l,u)=>{a.push([`cells[${u}]`,l||""]);});for(let[l,u]of a){let c=Eu(u);c&&n.push(`- Edit ${r+1+e} Failed: \`${l}\` contains control character(s) (${c}) that cannot be stored in a DOCX. Remove them and re-submit.`);}if((s.includes("{++")||s.includes("{--")||s.includes("{>>")||s.includes("{=="))&&n.push(`- Edit ${r+1+e} Failed: Do not manually write CriticMarkup tags ({++, {--, {>>, {==) in \`new_text\`. The engine handles redlining automatically. To add a comment, use the \`comment\` parameter.`),o.includes("[^")||s.includes("[^")){let l=(o.match(/\[\^(?:fn|en)-[^\]]+\]/g)||[]).sort(),u=(s.match(/\[\^(?:fn|en)-[^\]]+\]/g)||[]).sort();JSON.stringify(l)!==JSON.stringify(u)&&(u.length>l.length||u.some(c=>u.filter(d=>d===c).length>l.filter(d=>d===c).length)?n.push(`- Edit ${r+1+e} Failed: Cannot insert footnote/endnote markers via text replace. Markers like \`[^fn-N]\` are read-only projections. Use Word's References menu.`):n.push(`- Edit ${r+1+e} Failed: Cannot delete footnote/endnote references via text replace. The marker corresponds to a structural XML element.`));}if(o.includes("](")||s.includes("](")){let l=(o.match(/\[(?!~)[^\]]+\]\([^)]+\)/g)||[]).sort(),u=(s.match(/\[(?!~)[^\]]+\]\([^)]+\)/g)||[]).sort();l.length!==u.length?u.length>l.length?n.push(`- Edit ${r+1+e} Failed: Cannot insert hyperlinks via text replace. Inserting new hyperlinks is not supported; insert the display text instead (editing the text or URL of an existing link IS supported).`):n.push(`- Edit ${r+1+e} Failed: Cannot delete hyperlinks via text replace. The marker corresponds to a structural XML element.`):l.length>1&&JSON.stringify(l)!==JSON.stringify(u)&&n.push(`- Edit ${r+1+e} Failed: Can only edit or retarget one hyperlink per text replacement. Please split into multiple edits.`);}if(o.includes("[~")||s.includes("[~")){let l=o.match(/\[~[^~]+~\]\(#[^\)]+\)/g)||[],u=s.match(/\[~[^~]+~\]\(#[^\)]+\)/g)||[];l.length!==u.length?u.length>l.length?n.push(`- Edit ${r+1+e} Failed: Cannot insert cross-references via text replace. Markers are read-only projections.`):n.push(`- Edit ${r+1+e} Failed: Cannot delete cross-references via text replace. The marker corresponds to a structural XML element.`):JSON.stringify(l)!==JSON.stringify(u)&&n.push(`- Edit ${r+1+e} Failed: Modifying or retargeting cross-reference markers is disallowed to prevent dependency corruption.`);}if(o.includes("docx-image:")||s.includes("docx-image:")){let l=(o.match(/!\[[^\]]*\]\(docx-image:[^)]*\)/g)||[]).sort(),u=(s.match(/!\[[^\]]*\]\(docx-image:[^)]*\)/g)||[]).sort();JSON.stringify(l)!==JSON.stringify(u)&&n.push(`- Edit ${r+1+e} Failed: image markers (![alt](docx-image:N)) are read-only projections of embedded images. They cannot be inserted, altered, or removed via text replacement \u2014 edit the text around the image instead.`);}if(o.includes("{#")||s.includes("{#")){let l=o.match(/\{#[^\}]+\}/g)||[],u=s.match(/\{#[^\}]+\}/g)||[];for(let c of u)if(u.filter(d=>d===c).length>l.filter(d=>d===c).length){n.push(`- Edit ${r+1+e} Failed: Cannot modify or insert internal anchor markers (\`{#...}\`). These represent structural XML bookmarks.`);break}}if(o.includes("{#")&&o.includes("cc:")||s.includes("cc:")){let l=o.match(vi)||[],u=s.match(vi)||[];!xu.test(o.trim())&&(l.length!==u.length||l.some((d,f)=>d!==u[f]))&&n.push(`- Edit ${r+1+e} Failed: Cannot insert, alter, or remove content-control anchor markers (\`{#cc:N}\` / \`{#/cc:N}\`). They are read-only projections of the control's structure, not text. Edit the content BETWEEN the anchors, keeping both tokens in \`new_text\` exactly as they appear.`);}if(i.type==="modify"&&s){let l=s.split(/[\r\n]+/);for(let u of l){let c=u.trimStart();if(c.startsWith("#######")){let d=c.length-c.replace(/^#+/,"").length;if(c.substring(d).startsWith(" ")||c.substring(d)===""){n.push(`- Edit ${r+1+e} Failed: Heading level ${d} is not supported (maximum is 6).`);break}}}}(o.includes("READONLY_BOUNDARY_START")||s.includes("READONLY_BOUNDARY_START")||o.includes("# Document Structure (Read-Only)")||s.includes("# Document Structure (Read-Only)")||o.includes("Document Structure (Read-Only)")||s.includes("Document Structure (Read-Only)"))&&n.push(`- Edit ${r+1+e} Failed: Modification targets the read-only boundary (Structural Appendix). This section cannot be edited.`);}return n}g(Au,"validate_edit_strings");var dn=class Z{static{g(this,"_RedlineEngine");}doc;author;timestamp;current_id;mapper;_cc_anchor_pairs=null;_field_entries_cache=null;comments_manager;clean_mapper=null;original_mapper=null;skipped_details=[];gate_overrides=Je;protection=yt;_overridden_controls=[];removed_comment_notes=[];rollback_verified=true;id_discovery_hint;_revisionIndex=null;constructor(e,n="Adeu AI (TS)",r){this.doc=e,this.author=n,this.id_discovery_hint=r?.id_discovery_hint??null,this.gate_overrides={ignore_control_locks:r?.ignore_control_locks??false,ignore_document_protection:r?.ignore_document_protection??false,allow_untracked_writes:r?.allow_untracked_writes??false},this.protection=_o(e),this.timestamp=new Date().toISOString().replace(/\.\d{3}Z$/,"Z");let i="http://schemas.microsoft.com/office/word/2023/wordml/word16du";for(let o of this.doc.pkg.parts)if(o===this.doc.part&&!o._element.hasAttribute("xmlns:w16du")){let s=o._element.ownerDocument,a=er(s);o._element.setAttribute("xmlns:w16du",i),a&&Nt(s);}this.current_id=this._scan_existing_ids(),this.mapper=new ke(this.doc),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.comments_manager=new Et(this.doc);}_check_punctuation_warning(e){return !e||e.length>20||e.includes(" ")?null:e.includes("_")||e.includes("-")?`Warning: target_text '${e}' contains tokenization-splitting punctuation ('_' or '-'). This can trigger mid-word splits in the diff engine. Consider using a longer plain-prose anchor.`:null}_single_commented_sub_edit(e,n,r,i,o,s){let a,l,u,c;if(e===n)a=e,l=n,u=r,c="COMMENT_ONLY";else {let[f,h]=rt(e,n);a=e.slice(f,e.length-h),l=n.slice(f,n.length-h),u=r+f,[a,l]=yi(a,l),!a&&l?c="INSERTION":a&&!l?c="DELETION":c="MODIFICATION";}let d={type:"modify",target_text:a,new_text:l,comment:i};return d._resolved_start_idx=u,d._match_start_index=u,d._active_mapper_ref=s,d._internal_op=c,o&&(d._is_table_edit=true),[d]}_word_diff_sub_edits(e,n,r,i=null,o=false,s=null){if(i!=null)return this._single_commented_sub_edit(e,n,r,i,o,s);let a=[];try{a=Gt(e,n);}catch{a=[];}let l=g(d=>{let f=d.trim();return f.length>0&&/^[*_]+$/.test(f)},"_marker_only");if(a=a.filter(d=>!((!d.target_text||l(d.target_text))&&(!d.new_text||l(d.new_text))&&(d.target_text||d.new_text))),!a||a.length===0){let d={type:"modify",target_text:e,new_text:n,comment:i};return d._resolved_start_idx=r,d._match_start_index=r,d._active_mapper_ref=s,o&&(d._is_table_edit=true),e===n?d._internal_op="COMMENT_ONLY":!e&&n?d._internal_op="INSERTION":e&&!n?d._internal_op="DELETION":e&&n?d._internal_op="MODIFICATION":d._internal_op="COMMENT_ONLY",[d]}let u=[],c=false;for(let d of a){let f=r+(d._match_start_index||0),h=i!==null&&!c;h&&(c=true);let _={type:"modify",target_text:d.target_text,new_text:d.new_text,comment:h?i:null};_._resolved_start_idx=f,_._match_start_index=f,_._active_mapper_ref=s,o&&(_._is_table_edit=true);let p=d.target_text,m=d.new_text;!p&&m?_._internal_op="INSERTION":p&&!m?_._internal_op="DELETION":p&&m?_._internal_op="MODIFICATION":_._internal_op="COMMENT_ONLY",u.push(_);}return u}_nearest_match_hint(e,n){if(!e)return "";let r=e;if(n&&(r=r.replace(/^\^/,"").replace(/\$$/,""),r=r.replace(/^\\s\*/,"").replace(/\\s\*$/,""),r=r.replace(/\\([.^$*+?()[\]{}|\\/])/g,"$1")),r=r.trim(),(!r||r===e)&&!n)return "";let i=this.mapper.full_text.indexOf(r);if(i!==-1){let o=Math.max(0,i-15),s=Math.min(this.mapper.full_text.length,i+r.length+15),a=this.mapper.full_text.substring(o,s).replace(/\n/g," ");return `
117
+ Did you mean the literal "${r}"? It appears in the document (\u2026${a}\u2026). If you used a regex, drop the ^/$ anchors \u2014 they match the start/end of the entire document, not a line.`}return ""}static _PREVIEW_WRAPPER_PAIRS=[["{--","--}"],["{++","++}"],["{==","==}"],["{>>","<<}"]];static _tidy_preview_context(e,n){e=e.replace(/\{>>[\s\S]*?<<\}/g,"");for(let[r,i]of Z._PREVIEW_WRAPPER_PAIRS)if(n==="before"){let o=0,s=0,a=0;for(;a<e.length;)e.startsWith(r,a)?(o+=1,a+=r.length):e.startsWith(i,a)?(o===0?s=a+i.length:o-=1,a+=i.length):a+=1;e=e.substring(s);}else {let o=[],s=0;for(;s<e.length;)e.startsWith(r,s)?(o.push(s),s+=r.length):e.startsWith(i,s)?(o.length>0&&o.pop(),s+=i.length):s+=1;o.length>0&&(e=e.substring(0,o[0]));}return n==="before"?e=e.replace(/^[-+=<>]{0,2}\}/,""):e=e.replace(/\{[-+=<>]{0,2}$/,""),e}_capture_preview_context(e){if(e.type!=="modify")return;let n=e._resolved_start_idx;if(n==null)return;let i=(e._active_mapper_ref||this.mapper).full_text;if(!i)return;let o=(e.target_text||"").length,s=i.substring(Math.max(0,n-Ee),n),a=i.substring(n+o,n+o+Ee);e._preview_context=[Z._tidy_preview_context(s,"before"),Z._tidy_preview_context(a,"after")];}_capture_parent_preview_context(e){if(!e||e.type!=="modify"||e._preview_context||!e._preview_span)return;let[n,r]=e._preview_span,o=(e._preview_mapper_ref||this.mapper).full_text;if(!o)return;let s=o.substring(Math.max(0,n-Ee),n),a=o.substring(n+r,n+r+Ee);e._preview_context=[Z._tidy_preview_context(s,"before"),Z._tidy_preview_context(a,"after")];}_build_full_match_preview(e){let[n,r]=e._preview_context,i=e._preview_matched_text||"",o=e._preview_new_text!==void 0&&e._preview_new_text!==null?e._preview_new_text:e.new_text||"",[s,a]=this._parse_markdown_style(i),[l,u]=this._parse_markdown_style(o);a&&a.startsWith("Heading")&&(n=n+i.substring(0,i.length-s.length),i=s),u&&u.startsWith("Heading")&&(o=l);let[c,d]=rt(i,o),f=i.substring(c,i.length-d),h=o.substring(c,o.length-d);n=n+i.substring(0,c),d&&(r=i.substring(i.length-d)+r),f=de(f,tt),h=de(h,tt);let _;if(!f&&!h){let m=de(i,tt),w=m?`{==${m}==}`:"";_=`${n.substring(0,n.length-i.length)}${w}${r}`;}else {let m=f?`{--${f}--}`:"",w=h?`{++${h}++}`:"";_=`${n}${m}${w}${r}`;}let p=_;return p=p.replace(/\{>>[\s\S]*?<<\}/g,""),p=p.replace(/\{--[\s\S]*?--\}/g,""),p=p.replace(/\{\+\+([\s\S]*?)\+\+\}/g,"$1"),[_,p]}static _report_new_text(e){return e&&e.type==="insert_row"&&Array.isArray(e.cells)?e.cells.join(" | "):e&&e.new_text||""}_build_postapply_previews(e){let n=new Set((e._minted_change_ids||[]).map(w=>String(w))),r=new Set((e._minted_comment_ids||[]).map(w=>String(w)));if(n.size===0&&r.size===0)return null;let i=this.mapper;i.full_text||i._build_map();let o=i.full_text;if(!o)return null;let s=[];for(let w of i.spans)(w.ins_id&&n.has(String(w.ins_id))||w.del_id&&n.has(String(w.del_id))||r.size>0&&w.comment_ids&&w.comment_ids.some(b=>r.has(String(b))))&&s.push([w.start,w.end]);if(s.length===0)return null;let a=/\{>>[\s\S]*?<<\}/g,l=[],u;for(;(u=a.exec(o))!==null;)l.push([u.index,u.index+u[0].length]);let c=o,d=g(w=>w,"to_visible");if(l.length>0){let w=[],v=0;for(let[b,y]of l)w.push(o.substring(v,b)),v=y;w.push(o.substring(v)),c=w.join(""),d=g(b=>{let y=0;for(let[x,k]of l)if(b>=k)y+=k-x;else if(b>x){y+=b-x;break}else break;return b-y},"to_visible");}s.sort((w,v)=>w[0]-v[0]);let f=[];for(let[w,v]of s){let b=d(w),y=d(v),x=Math.max(0,b-Ee),k=Math.min(c.length,y+Ee),N=f.length>0?f[f.length-1]:null;N&&x<=N[1]?N[1]=Math.max(N[1],k):f.push([x,k]);}let h=[];for(let[w,v]of f){let b=c.substring(w,v);b=Z._tidy_preview_context(b,"before"),b=Z._tidy_preview_context(b,"after"),h.push(b);}let _=h.join(`
92
118
  \u2026
93
- `),p=_;p=p.replace(/\{>>[\s\S]*?<<\}/g,""),p=p.replace(/\{--[\s\S]*?--\}/g,""),p=p.replace(/\{\+\+([\s\S]*?)\+\+\}/g,"$1"),p=p.replace(/\{==([\s\S]*?)==\}/g,"$1");let m=He*2+4*be;return [de(_,m),de(p,m)]}_build_edit_context_previews(e){if(e.type!=="modify")return [null,null];let n=this._build_postapply_previews(e);if(n)return n;if(e._preview_span&&e._preview_context)return this._build_full_match_preview(e);e._resolved_proxy_edit&&(e=e._resolved_proxy_edit);let r=e._resolved_start_idx;if(r==null)return [null,null];let s=e.target_text||"",i=e.new_text||"",[o,l]=this._parse_markdown_style(s);if(l&&l.startsWith("Heading")){let b=s.length-o.length;r+=b,s=o;}let[a,u]=this._parse_markdown_style(i);u&&u.startsWith("Heading")&&(i=a);let c=s.length,d,f;if(e._preview_context)[d,f]=e._preview_context;else {let w=(e._active_mapper_ref||this.mapper).full_text;if(!w)return [null,null];d=V._tidy_preview_context(w.substring(Math.max(0,r-be),r),"before"),f=V._tidy_preview_context(w.substring(r+c,r+c+be),"after");}let h=de(s,He),_=de(i,He),p=h?`{--${h}--}`:"",m=_?`{++${_}++}`:"",y=`${d}${p}${m}${f}`,x=y;return x=x.replace(/\{>>.*?<<\}/gs,""),x=x.replace(/\{--.*?--\}/gs,""),x=x.replace(/\{\+\+(.*?)\+\+\}/gs,"$1"),[y,x]}_scan_existing_ids(){let e=0;for(let n of ["w:ins","w:del","w:pPrChange"]){let r=M(this.doc.element,n);for(let s of r){let i=parseInt(s.getAttribute("w:id")||"0",10);!isNaN(i)&&i>e&&(e=i);}}return e}_get_heading_path_and_page(e,n,r){let s=1;for(let u=0;u<r.length&&e>=r[u];u++)s=u+1;let o=n.substring(0,e).split(`
94
- `),l=[],a=999;for(let u=o.length-1;u>=0;u--){let d=o[u].match(/^(#{1,6})\s+(.*)/);if(d){let f=d[1].length;if(f<a){let h=d[2].replace(/\*\*|__|[*_]/g,"").replace(/\{#[^}]+\}/g,"").trim();if(h.length>80&&(h=h.substring(0,80)+"..."),l.unshift(h),a=f,f===1)break}}}return [l.join(" > "),s]}accept_all_revisions(e=false){let n=[this.doc.element];for(let f of this.doc.pkg.parts)f!==this.doc.part&&f.contentType.includes("wordprocessingml")&&f.contentType.endsWith("+xml")&&n.push(f._element);let r=0,s=0,i=0;for(let f of n){r+=M(f,"w:ins").length,s+=M(f,"w:del").length;for(let h of ["w:rPrChange","w:pPrChange","w:sectPrChange"])i+=M(f,h).length;}let o=this._comment_authors(),l=new Set(Object.keys(o));this.removed_comment_notes=[];for(let f of n){let h=M(f,"w:ins");for(let m of h){this._clean_wrapping_comments(m);let y=m.parentNode;if(y){if(y.tagName==="w:trPr"){y.removeChild(m);continue}for(;m.firstChild;)y.insertBefore(m.firstChild,m);y.removeChild(m);}}let _=M(f,"w:p");for(let m of _){let y=B(m,"w:pPr");if(y){let x=B(y,"w:rPr"),b=x?B(x,"w:del"):null;if(x&&b){let w=false;for(let v of ["w:t","w:tab","w:br"]){for(let N of M(m,v)){if(v==="w:t"&&!N.textContent)continue;let k=false,C=N.parentNode;for(;C&&C!==m;){if(C.tagName==="w:del"){k=true;break}C=C.parentNode;}if(!k){w=true;break}}if(w)break}w||this._is_last_paragraph_in_cell(m)?x.removeChild(b):(this._clean_wrapping_comments(m),this._delete_comments_in_element(m),m.parentNode&&m.parentNode.removeChild(m));}}}let p=M(f,"w:del");for(let m of p){this._clean_wrapping_comments(m),this._delete_comments_in_element(m);let y=m.parentNode;if(y)if(y.tagName==="w:trPr"){let x=y.parentNode;x&&x.parentNode&&x.parentNode.removeChild(x);}else y.removeChild(m);}for(let m of M(f,"w:pPrChange"))m.parentNode?.removeChild(m);}if(e)for(let f of n){for(let _ of ["w:commentRangeStart","w:commentRangeEnd"])for(let p of M(f,_))p.parentNode?.removeChild(p);let h=M(f,"w:commentReference");for(let _ of h){let p=_.parentNode;p&&((p.tagName==="w:r"||p.tagName.endsWith(":r"))&&Array.from(p.childNodes).filter(y=>y.nodeType===1&&y.tagName!=="w:rPr"&&y.tagName!=="rPr").length<=1?p.parentNode?.removeChild(p):p.removeChild(_));}}let a=this.doc.pkg,u=new Set;for(let f of a.parts)if(e&&f.partname.toLowerCase().includes("comments")){u.add(f.partname);let h=f.partname.startsWith("/")?f.partname:"/"+f.partname,_=f.partname.startsWith("/")?f.partname.substring(1):f.partname;u.add(h),u.add(_);}if(u.size>0){for(let h of a.parts)if(h.partname.endsWith(".rels")){let _=M(h._element,"Relationship"),p=[];for(let m of _)if((m.getAttribute("Target")||"").toLowerCase().includes("comments")){p.push(m);let x=h.partname.replace("/_rels/","/").replace(".rels",""),b=a.getPartByPath(x);if(b){let w=m.getAttribute("Id");w&&b.rels.delete(w);}}for(let m of p)m.parentNode?.removeChild(m);}let f=a.getPartByPath("[Content_Types].xml");if(f){let h=M(f._element,"Override"),_=[];for(let p of h){let m=p.getAttribute("PartName")||"";(u.has(m)||m.toLowerCase().includes("comments"))&&_.push(p);}for(let p of _)p.parentNode?.removeChild(p);}a.parts=a.parts.filter(h=>!h.partname.toLowerCase().includes("comments"));for(let h of Object.keys(a.unzipped))h.toLowerCase().includes("comments")&&delete a.unzipped[h];}let c=new Set(this._existing_comment_ids()),d=Array.from(l).filter(f=>!c.has(f)).sort((f,h)=>{let _=/^\d+$/.test(f)?parseInt(f,10):0,p=/^\d+$/.test(h)?parseInt(h,10):0;return _-p||f.localeCompare(h)});return this.removed_comment_notes=d.map(f=>`Com:${f} (by ${o[f]??"Unknown"})`),{accepted_insertions:r,accepted_deletions:s,accepted_formatting:i,removed_comments:d.length}}reject_all_revisions(){let e=[this.doc.element];for(let n of this.doc.pkg.parts)n!==this.doc.part&&n.contentType.includes("wordprocessingml")&&n.contentType.endsWith("+xml")&&e.push(n._element);for(let n of e){for(let o of M(n,"w:pPrChange"))this._revert_ppr_change(o);let r=M(n,"w:ins");for(let o of r){let l=o.parentNode;if(l)if(this._clean_wrapping_comments(o),this._delete_comments_in_element(o),l.tagName==="w:trPr"){let a=l.parentNode;a&&a.parentNode&&a.parentNode.removeChild(a);}else l.removeChild(o);}let s=M(n,"w:p");for(let o of s){let l=B(o,"w:pPr");if(l){let a=B(l,"w:rPr"),u=a?B(a,"w:del"):null;a&&u&&a.removeChild(u);}}let i=M(n,"w:del");for(let o of i){let l=o.parentNode;if(!l)continue;if(l.tagName==="w:trPr"){l.removeChild(o);continue}let a=Array.from(o.getElementsByTagName("w:delText"));for(let u of a){let c=o.ownerDocument.createElement("w:t");c.textContent=u.textContent,u.hasAttribute("xml:space")&&c.setAttribute("xml:space","preserve"),u.parentNode?.replaceChild(c,u);}for(;o.firstChild;)l.insertBefore(o.firstChild,o);l.removeChild(o);}}}_revert_ppr_change(e){let n=e.parentNode;if(!n||n.tagName!=="w:pPr")return;let r=n.parentNode;if(!r)return;let s=B(e,"w:pPr");if(s){let i=s.cloneNode(true);Array.from(i.childNodes).some(l=>l.nodeType===1)?r.replaceChild(i,n):r.removeChild(n);}else r.removeChild(n);}_revert_props_change(e){let n=e.parentNode;if(!n)return;let r=Array.from(e.childNodes).find(i=>i.nodeType===1);n.removeChild(e);let s=ra[n.tagName];for(let i of Array.from(n.childNodes)){if(i.nodeType!==1)continue;let o=i;o.tagName==="w:rPr"&&(B(o,"w:ins")||B(o,"w:del"))||s?.has(o.tagName)||n.removeChild(i);}if(r)for(let i of Array.from(r.childNodes))i.nodeType===1&&n.appendChild(i.cloneNode(true));}_getNextId(){return this.current_id++,this.current_id.toString()}_create_track_change_tag(e,n="",r=null){let i=this.doc.part._element.ownerDocument.createElement(e),o=r!==null?r:this._getNextId();return i.setAttribute("w:id",o),i.setAttribute("w:author",n||this.author),i.setAttribute("w:date",this.timestamp),i.setAttribute("w16du:dateUtc",this.timestamp),i}_set_text_content(e,n){e.textContent=n,n.trim()!==n&&e.setAttribute("xml:space","preserve");}_comment_anchor_in_main_story(e){let n=e;for(;n.parentNode&&n.parentNode.nodeType===1;)n=n.parentNode;return n.tagName==="w:document"}_skip_comment_outside_main_story(e,n){if(this._comment_anchor_in_main_story(e))return false;let r=e;for(;r.parentNode&&r.parentNode.nodeType===1;)r=r.parentNode;let s={"w:ftr":"footer","w:hdr":"header","w:footnotes":"footnote","w:endnotes":"endnote"}[r.tagName]||"non-body",i=`- Warning: the comment "${n.substring(0,60)}" was NOT attached: Word does not support comments inside a ${s} part, and writing one produces a document other applications cannot open. The tracked change itself was applied.`;return this.skipped_details.push(i),true}_attach_comment(e,n,r,s){if(!s||!e||!n||!r||this._skip_comment_outside_main_story(e,s))return null;let i=this.comments_manager.addComment(this.author,s),o=e.ownerDocument,l=o.createElement("w:commentRangeStart");l.setAttribute("w:id",i);let a=o.createElement("w:commentRangeEnd");a.setAttribute("w:id",i);let u=o.createElement("w:r"),c=o.createElement("w:rPr"),d=o.createElement("w:rStyle");d.setAttribute("w:val","CommentReference"),c.appendChild(d),u.appendChild(c);let f=o.createElement("w:commentReference");f.setAttribute("w:id",i),u.appendChild(f),e.insertBefore(l,n);let h=r.nextSibling;return h?(e.insertBefore(a,h),e.insertBefore(u,a.nextSibling)):(e.appendChild(a),e.appendChild(u)),i}_attach_comment_spanning(e,n,r,s,i){if(!i||!e||!r||this._skip_comment_outside_main_story(e,i)||this._skip_comment_outside_main_story(r,i))return;let o=this.comments_manager.addComment(this.author,i),l=e.ownerDocument,a=r.ownerDocument,u=l.createElement("w:commentRangeStart");u.setAttribute("w:id",o);let c=a.createElement("w:commentRangeEnd");c.setAttribute("w:id",o);let d=a.createElement("w:r"),f=a.createElement("w:rPr"),h=a.createElement("w:rStyle");h.setAttribute("w:val","CommentReference"),f.appendChild(h),d.appendChild(f);let _=a.createElement("w:commentReference");_.setAttribute("w:id",o),d.appendChild(_),e.insertBefore(u,n);let p=s.nextSibling;p?(r.insertBefore(c,p),r.insertBefore(d,c.nextSibling)):(r.appendChild(c),r.appendChild(d));}_is_native_heading_element(e){try{let n=this.doc.part||this.doc,[r,s]=Qe(n);return Ct({_element:e},r,s)}catch{return false}}_clone_pPr_scrubbing_headings(e,n=null){let r=e.cloneNode(true),s=B(r,"w:pStyle");if(s){let o=s.getAttribute("w:val");o&&(o.startsWith("Heading")||o==="Title"||o.replace(/\s+/g,"").startsWith("Heading")||n!==null&&this._is_native_heading_element(n))&&r.removeChild(s);}let i=B(r,"w:outlineLvl");return i&&r.removeChild(i),r}_track_insert_multiline(e,n,r,s,i=null,o=false,l=false){if(!e)return {first_node:null,last_p:null,last_ins:null,used_block_mode:false};let a=this.doc.part._element.ownerDocument,u=e.split(/[\r\n]+/),c=null;if(r!==null)c=r._element;else if(n!==null){let I=n._element;for(;I&&I.tagName!=="w:p";)I=I.parentNode;c=I;}let d=[],f=new Set(["w:r","w:ins","w:del"]),h=i&&i.parentNode?i:null,_=n!==null&&n._element.parentNode?n._element:null,p=h??_,m=l&&h===null&&_!==null;if(c!==null&&p!==null){let I=p;for(;I&&I.parentNode!==c;)if(I=I.parentNode,I===c){I=null;break}if(I){let P=m?I:I.nextSibling;for(;P;)P.nodeType===1&&f.has(P.tagName)&&d.push(P),P=P.nextSibling;}}else if(c!==null&&l){let I=c.firstChild;for(;I;)I.nodeType===1&&f.has(I.tagName)&&d.push(I),I=I.nextSibling;}for(;u.length>1&&u[u.length-1]===""&&d.length===0;)u.pop();if(u.length===0)return {first_node:null,last_p:null,last_ins:null,used_block_mode:false};let[y,x]=this._parse_markdown_style(u[0]),b=c!==null,w=/[\r\n]/.test(e),v=x!==null&&b&&w,N=null,k=null;v||(k=this._build_tracked_ins_for_line((y===u[0],u[0]),n,s,a,o),N=k);let C=v?u:u.slice(1);if(C.length===0)return {first_node:N,last_p:null,last_ins:k,used_block_mode:false};if(!c)return {first_node:N,last_p:null,last_ins:k,used_block_mode:false};let A=c.parentNode;if(!A)return {first_node:N,last_p:null,last_ins:k,used_block_mode:false};let T=g((I,P)=>{A.insertBefore(I,P.nextSibling);},"insertAfterEl"),D=null,j=null,E=c;for(let I=0;I<C.length;I++){let P=C[I],[S,$]=this._parse_markdown_style(P),O=a.createElement("w:p");if($)this._set_paragraph_style(O,$);else {let q=B(c,"w:pPr");q&&O.appendChild(this._clone_pPr_scrubbing_headings(q,c));}let F=B(O,"w:pPr");F||(F=a.createElement("w:pPr"),O.insertBefore(F,O.firstChild));let W=B(F,"w:rPr");W||(W=a.createElement("w:rPr"),F.appendChild(W));let L=this._create_track_change_tag("w:ins","",s);W.appendChild(L);let U=this._build_tracked_ins_for_line(S,n,s,a,o);U&&O.appendChild(U),T(O,E),E=O,D=O,j=U,N||(N=O);}if(!v&&D&&d.length>0)for(let I of d)I.parentNode?.removeChild(I),D.appendChild(I);return {first_node:N,last_p:D,last_ins:j,used_block_mode:v}}_build_tracked_ins_for_line(e,n,r,s,i=false){if(!e&&e!=="")return null;let o=this._create_track_change_tag("w:ins","",r),l=this._parse_inline_markdown(e);if(l.length===0)return null;for(let[a,u]of l){let c=s.createElement("w:r");if(n&&n._element){let f=B(n._element,"w:rPr");if(f){let h=f.cloneNode(true),_=["w:vanish","w:strike","w:dstrike","w:i","w:iCs"];i&&_.push("w:b","w:bCs");for(let p of _){let m=B(h,p);m&&h.removeChild(m);}c.appendChild(h);}}this._apply_run_props(c,u,false);let d=s.createElement("w:t");this._set_text_content(d,a),c.appendChild(d),o.appendChild(c);}return o}_parse_markdown_style(e){let n=e.trimStart();if(n.startsWith("#")){let s=0,i=n;for(;i.startsWith("#");)s++,i=i.substring(1);if(i.startsWith(" "))return [i.trim(),`Heading ${s}`]}if(n.startsWith("* ")||n.startsWith("- "))return [n.substring(2).trim(),"List Paragraph"];let r=n.match(/^1\.\s+/);return r?[n.substring(r[0].length).trim(),"List Number"]:[e,null]}_edit_declares_emphasis(e){for(let n of [e?.target_text,e?.new_text]){if(!n||!n.includes("**")&&!n.includes("_"))continue;if(this._parse_inline_markdown(n).some(([,s])=>s&&Object.keys(s).length>0))return true}return false}_parse_inline_markdown(e,n={}){if(!e)return [];let r=/(\*\*.*?\*\*)|(_.*?_)/,s=e.match(r);if(!s)return [[e,n]];let i=s.index,o=s[0],l=i+o.length,a=o.startsWith("**"),u=a?o.substring(2,o.length-2):o.substring(1,o.length-1),c=e.substring(0,i),d=e.substring(l),f=[];c&&f.push([c,n]);let h={...n};return a?h.bold=true:h.italic=true,f.push(...this._parse_inline_markdown(u,h)),f.push(...this._parse_inline_markdown(d,n)),f}_apply_run_props(e,n,r=false){if(!n){if(!r)return;n={};}let s=B(e,"w:rPr");if(!s&&(n.bold||n.italic||r)&&(s=e.ownerDocument.createElement("w:rPr"),e.appendChild(s)),s){let i=e.ownerDocument;if(n.bold){let o=B(s,"w:b");o||(o=i.createElement("w:b"),s.appendChild(o)),o.setAttribute("w:val","1");}else if(r){let o=B(s,"w:b");o&&s.removeChild(o);}if(n.italic){let o=B(s,"w:i");o||(o=i.createElement("w:i"),s.appendChild(o)),o.setAttribute("w:val","1");}else if(r){let o=B(s,"w:i");o&&s.removeChild(o);}}}_set_paragraph_style(e,n,r=null){let s=e.ownerDocument,i=B(e,"w:pPr");i&&e.removeChild(i);let o=s.createElement("w:pPr"),l=s.createElement("w:pStyle"),a=n.replace(/\s+/g,"");if(l.setAttribute("w:val",a),o.appendChild(l),a==="ListParagraph"){let u=this._ensure_bullet_num_id();if(u){let c=s.createElement("w:numPr"),d=s.createElement("w:ilvl");d.setAttribute("w:val","0");let f=s.createElement("w:numId");f.setAttribute("w:val",u),c.appendChild(d),c.appendChild(f),o.appendChild(c);}}if(r!==null){let u=this._create_track_change_tag("w:pPrChange","",r),c=i?i.cloneNode(true):s.createElement("w:pPr"),d=B(c,"w:pPrChange");d&&c.removeChild(d),u.appendChild(c),o.appendChild(u);}e.insertBefore(o,e.firstChild);}static _NUMBERING_CT="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml";static _NUMBERING_RT="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering";_ensure_bullet_num_id(){let e=this.doc.pkg,n="http://schemas.openxmlformats.org/wordprocessingml/2006/main",r='<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="\uF0B7"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr><w:rPr><w:rFonts w:ascii="Symbol" w:hAnsi="Symbol" w:hint="default"/></w:rPr></w:lvl>',s=e.parts.find(T=>String(T.partname).replace(/^\//,"")==="word/numbering.xml");if(!s){let T=`<w:numbering xmlns:w="${n}"><w:abstractNum w:abstractNumId="0"><w:multiLevelType w:val="singleLevel"/>`+r+'</w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>';try{s=e.addPart("/word/numbering.xml",V._NUMBERING_CT,T),this.doc.relateTo(s,V._NUMBERING_RT);}catch{return null}return delete e._adeu_numbering_cache,"1"}let i=s._element,o=M(i,"w:abstractNum"),l=M(i,"w:num"),a=null;for(let T of o){let D=T.getAttribute("w:abstractNumId");if(D!==null){for(let j of M(T,"w:lvl")){if((j.getAttribute("w:ilvl")||"0")!=="0")continue;let E=B(j,"w:numFmt");E&&E.getAttribute("w:val")==="bullet"&&(a=D);break}if(a!==null)break}}let u=0;for(let T of l){let D=parseInt(T.getAttribute("w:numId")||"0",10);!isNaN(D)&&D>u&&(u=D);}let c=i.ownerDocument;if(a!==null){for(let j of l){let E=B(j,"w:abstractNumId");if(E&&E.getAttribute("w:val")===a){let I=j.getAttribute("w:numId");if(I&&I!=="0")return I}}let T=c.createElement("w:num");T.setAttribute("w:numId",String(u+1));let D=c.createElement("w:abstractNumId");return D.setAttribute("w:val",a),T.appendChild(D),i.appendChild(T),delete e._adeu_numbering_cache,String(u+1)}let d=-1;for(let T of o){let D=parseInt(T.getAttribute("w:abstractNumId")||"-1",10);!isNaN(D)&&D>d&&(d=D);}let f=c.createElement("w:abstractNum");f.setAttribute("w:abstractNumId",String(d+1));let h=c.createElement("w:multiLevelType");h.setAttribute("w:val","singleLevel"),f.appendChild(h);let _=c.createElement("w:lvl");_.setAttribute("w:ilvl","0");let p=c.createElement("w:start");p.setAttribute("w:val","1"),_.appendChild(p);let m=c.createElement("w:numFmt");m.setAttribute("w:val","bullet"),_.appendChild(m);let y=c.createElement("w:lvlText");y.setAttribute("w:val","\uF0B7"),_.appendChild(y);let x=c.createElement("w:lvlJc");x.setAttribute("w:val","left"),_.appendChild(x);let b=c.createElement("w:pPr"),w=c.createElement("w:ind");w.setAttribute("w:left","720"),w.setAttribute("w:hanging","360"),b.appendChild(w),_.appendChild(b);let v=c.createElement("w:rPr"),N=c.createElement("w:rFonts");N.setAttribute("w:ascii","Symbol"),N.setAttribute("w:hAnsi","Symbol"),N.setAttribute("w:hint","default"),v.appendChild(N),_.appendChild(v),f.appendChild(_);let k=l.find(T=>T.parentNode===i)||null;k?i.insertBefore(f,k):i.appendChild(f);let C=c.createElement("w:num");C.setAttribute("w:numId",String(u+1));let A=c.createElement("w:abstractNumId");return A.setAttribute("w:val",String(d+1)),C.appendChild(A),i.appendChild(C),delete e._adeu_numbering_cache,String(u+1)}_anchor_reply_comment(e,n){let r=this.doc.part._element.ownerDocument,s=M(this.doc.element,"w:commentRangeStart").filter(m=>m.getAttribute("w:id")===e);if(s.length===0)return;let i=s[0],o=r.createElement("w:commentRangeStart");o.setAttribute("w:id",n),qe(o,i);let l=M(this.doc.element,"w:commentRangeEnd").filter(m=>m.getAttribute("w:id")===e);if(l.length===0)return;let a=l[0],u=M(this.doc.element,"w:commentReference").filter(m=>m.getAttribute("w:id")===e),c=a;if(u.length>0){let m=u[0];m.parentNode&&m.parentNode.tagName==="w:r"&&(c=m.parentNode);}let d=r.createElement("w:commentRangeEnd");d.setAttribute("w:id",n),qe(d,c);let f=r.createElement("w:r"),h=r.createElement("w:rPr"),_=r.createElement("w:rStyle");_.setAttribute("w:val","CommentReference"),h.appendChild(_),f.appendChild(h);let p=r.createElement("w:commentReference");p.setAttribute("w:id",n),f.appendChild(p),qe(f,d);}_clean_wrapping_comments(e){let n=0,r=e;for(;;){let c=Ae(r);if(c&&(c.tagName==="w:ins"||c.tagName==="w:del"))r=c;else break}let s=e;for(;;){let c=xe(s);if(c&&(c.tagName==="w:ins"||c.tagName==="w:del"))s=c;else break}let i=[],o=Ae(r);for(;o;)if(o.tagName==="w:commentRangeStart")i.push(o),o=Ae(o);else if(o.tagName==="w:rPr"||o.tagName==="w:pPr")o=Ae(o);else break;let l=[],a=xe(s);for(;a;)if(a.tagName==="w:commentRangeEnd")l.push(a),a=xe(a);else if(a.tagName==="w:r"&&M(a,"w:commentReference").length>0)l.push(a),a=xe(a);else if(a.tagName==="w:commentReference")l.push(a),a=xe(a);else break;let u=new Set;for(let c of l)if(c.tagName==="w:commentRangeEnd"){let d=c.getAttribute("w:id");d&&u.add(d);}else {let d=M(c,"w:commentReference")[0];if(!d&&c.tagName==="w:commentReference"&&(d=c),d){let f=d.getAttribute("w:id");f&&u.add(f);}}for(let c of i){let d=c.getAttribute("w:id");if(d&&u.has(d)){this.comments_manager.deleteComment(d),n++,c.parentNode&&c.parentNode.removeChild(c);for(let f of l){let h=null;if(f.tagName==="w:commentRangeEnd")h=f.getAttribute("w:id");else {let _=M(f,"w:commentReference")[0];!_&&f.tagName==="w:commentReference"&&(_=f),_&&(h=_.getAttribute("w:id"));}h===d&&f.parentNode&&f.parentNode.removeChild(f);}}}return n}_delete_comments_in_element(e){let n=0,r=M(e,"w:commentReference");for(let s of r){let i=s.getAttribute("w:id");if(i){this.comments_manager.deleteComment(i),n++;for(let o of ["w:commentRangeStart","w:commentRangeEnd"]){let l=M(this.doc.element,o);for(let a of l)a.getAttribute("w:id")===i&&a.parentNode&&a.parentNode.removeChild(a);}}}return n}validate_edits(e,n=0){let r=[];this.mapper.full_text||this.mapper._build_map(),r.push(...sa(e,n));for(let s=0;s<e.length;s++){let i=e[s];if(typeof i!="object"||i===null){r.push(`- Edit ${s+1+n} Failed: Invalid change format. Expected a JSON object, but received a primitive ${typeof i}. Do not pass raw strings.`);continue}if(i._match_start_index!==void 0&&i._match_start_index!==null||i._resolved_start_idx!==void 0&&i._resolved_start_idx!==null)continue;if(i.target_text===void 0||i.target_text===null||!String(i.target_text).trim()){i.type==="insert_row"?r.push(`- Edit ${s+1+n} Failed: insert_row requires target_text (text inside an existing row to anchor on) and cells (the new row's cell values).`):i.type==="delete_row"?r.push(`- Edit ${s+1+n} Failed: delete_row requires target_text (text inside the row to delete).`):r.push(`- Edit ${s+1+n} Failed: target_text is empty. Pure insertions are expressed as a replacement: put the text immediately around the insertion point in target_text and repeat it (plus the new text) in new_text.`);continue}if(i.type==="modify"&&(i.new_text===void 0||i.new_text===null))if(i.comment&&String(i.comment).trim())i.new_text=i.target_text;else {r.push(`- Edit ${s+1+n} Failed: modify requires new_text (an empty string deletes the target; to attach a comment without changing the text, supply the comment and omit new_text).`);continue}let o=i.regex||false,l=i.match_mode||"strict";if(o)try{new RegExp(i.target_text);}catch(h){r.push(`- Edit ${s+1+n} Failed: target_text is not a valid regular expression (${h?.message??h}). Fix the pattern, or set "regex": false to match the text literally.`);continue}let a=this.mapper.drop_virtual_only_matches(this.mapper.find_all_match_indices(i.target_text,o)),u=this.mapper.full_text,c=this.mapper;a.length===0&&(this.clean_mapper||(this.clean_mapper=new ve(this.doc,true)),a=this.clean_mapper.drop_virtual_only_matches(this.clean_mapper.find_all_match_indices(i.target_text,o)),a.length>0&&(u=this.clean_mapper.full_text,c=this.clean_mapper)),u===this.mapper.full_text&&a.length>0&&(a=a.filter(([_,p])=>{let m=this.mapper.spans.filter(y=>y.run!==null&&y.end>_&&y.start<_+p);return m.length===0?true:m.some(y=>!y.del_id)}));let d=false,f=new Set;if(a.length===0){this.original_mapper||(this.original_mapper=new ve(this.doc,false,true));let h=this.original_mapper.drop_virtual_only_matches(this.original_mapper.find_all_match_indices(i.target_text,o));if(h.length>0){d=true;for(let[_,p]of h){let m=this.original_mapper.spans.filter(y=>y.end>_&&y.start<_+p);for(let y of m)if(y.run!==null){let x=y.run._element;for(;x;){if(x.nodeType===1&&x.tagName==="w:del"){let b=x.getAttribute("w:author");b&&f.add(b);break}x=x.parentNode;}}}}}if(a.length===0)if(d){let h=f.size>0?`by ${Array.from(f).sort().join(", ")}`:"by an existing revision";r.push(`- Edit ${s+1+n} Failed: Target text matches text inside a tracked deletion ${h}. Reject/accept that change first or target the active replacement text instead.`);}else {let h=this._nearest_match_hint(i.target_text,o);r.push(`- Edit ${s+1+n} Failed: Target text not found in document:
95
- "${de(i.target_text,Yt)}"${h}`);}else if(a.length>1&&l==="strict")if(i.target_text.includes("|"))a=a.slice(0,1);else {let h=a.map(([_,p])=>[_,_+p]);r.push(Vo(s+1+n,i.target_text,u,h));}if(a.length===1){let[h,_]=a[0],p=u.substring(h,h+_),[m,y]=Je(p,i.new_text||""),x=p.length-y,b=p.substring(m,x),w=(i.new_text||"").substring(m,(i.new_text||"").length-y),N=c.part_ranges.filter(A=>A[1]>A[0]).length>1?Array.from(new Set(c.spans.filter(A=>A.run!==null&&A.end>h&&A.start<h+_).map(A=>A.part_index))).sort((A,T)=>A-T):[];if(N.length>1){let A=N.map(T=>c.part_kind_of(T)||"?").join(" \u2192 ");r.push(`- Edit ${s+1+n} Failed: target_text spans a structural document-part boundary (${A}). Headers, body, footers and footnotes are separate Word parts \u2014 an edit cannot cross between them. Anchor the edit on text within a single part (split it into one edit per part if both sides must change).`);}let k=h+m,C=h+_-y;if(C>k&&c.spans.filter(T=>T.end>k&&T.start<C&&(T.run!==null||T.text.trim()!=="")).some(T=>T.is_image_marker)&&r.push(`- Edit ${s+1+n} Failed: the target overlaps a read-only image marker (![alt](docx-image:N)). Images cannot be edited or removed via text replacement \u2014 target the text around the image instead.`),i.comment&&(i.new_text||"")===(i.target_text||"")){let A=c.part_kind_at(h);A!==null&&A!=="body"&&r.push(`- Edit ${s+1+n} Failed: comments cannot be anchored inside a ${A} part \u2014 Word only supports comments in the main document body. Comment on the related body text instead.`);}if(V._introduces_table_row_text(c,h,_,b,w)&&r.push(`- Edit ${s+1+n} Failed: new_text introduces a pipe-delimited row line inside a table. Text replacement cannot create table rows \u2014 use the structured 'insert_row' operation instead (e.g. {"type": "insert_row", "target_text": "<anchor row text>", "cells": ["...", "..."]}).`),b.includes(`
119
+ `),p=_;p=p.replace(/\{>>[\s\S]*?<<\}/g,""),p=p.replace(/\{--[\s\S]*?--\}/g,""),p=p.replace(/\{\+\+([\s\S]*?)\+\+\}/g,"$1"),p=p.replace(/\{==([\s\S]*?)==\}/g,"$1");let m=tt*2+4*Ee;return [de(_,m),de(p,m)]}_build_edit_context_previews(e){if(e.type!=="modify")return [null,null];let n=this._build_postapply_previews(e);if(n)return n;if(e._preview_span&&e._preview_context)return this._build_full_match_preview(e);e._resolved_proxy_edit&&(e=e._resolved_proxy_edit);let r=e._resolved_start_idx;if(r==null)return [null,null];let i=e.target_text||"",o=e.new_text||"",[s,a]=this._parse_markdown_style(i);if(a&&a.startsWith("Heading")){let b=i.length-s.length;r+=b,i=s;}let[l,u]=this._parse_markdown_style(o);u&&u.startsWith("Heading")&&(o=l);let c=i.length,d,f;if(e._preview_context)[d,f]=e._preview_context;else {let y=(e._active_mapper_ref||this.mapper).full_text;if(!y)return [null,null];d=Z._tidy_preview_context(y.substring(Math.max(0,r-Ee),r),"before"),f=Z._tidy_preview_context(y.substring(r+c,r+c+Ee),"after");}let h=de(i,tt),_=de(o,tt),p=h?`{--${h}--}`:"",m=_?`{++${_}++}`:"",w=`${d}${p}${m}${f}`,v=w;return v=v.replace(/\{>>.*?<<\}/gs,""),v=v.replace(/\{--.*?--\}/gs,""),v=v.replace(/\{\+\+(.*?)\+\+\}/gs,"$1"),[w,v]}_revision_roots(){let e=[this.doc.element];for(let n of this.doc.pkg.parts)n!==this.doc.part&&n.contentType.includes("wordprocessingml")&&n.contentType.endsWith("+xml")&&e.push(n._element);return e}_story_roots(){let e=[[this.doc.element,Rn(this.doc.part.partname)]];for(let n of this.doc.pkg.parts)n!==this.doc.part&&ku.includes(n.contentType)&&e.push([n._element,Rn(n.partname)]);return e}_scan_existing_ids(){let e=0;for(let n of this._revision_roots())for(let r of ["w:ins","w:del","w:pPrChange"]){let i=R(n,r);for(let o of i){let s=parseInt(o.getAttribute("w:id")||"0",10);!isNaN(s)&&s>e&&(e=s);}}return e}_field_entries(){let e=this.mapper.full_text;if(this._field_entries_cache&&this._field_entries_cache[0]===e)return this._field_entries_cache[1];let n=Xc(this.doc,e);return this._field_entries_cache=[e,n],n}_resolve_set_field_targets(e){return Yc(this._field_entries(),e.field,e.match_mode||"strict")}_sdt_info_for_ordinal(e){let n=this.mapper._sdt_infos;if(!n)return null;for(let r of n.values())if(r.ordinal===e)return r;return null}_cc_content_range(e){this._field_label_at(0);for(let[n,r,i]of this._cc_anchor_pairs??[])if(i===e)return [n,r];return null}_invalidate_projection_caches(){this.mapper._build_map(),this._cc_anchor_pairs=null,this._field_entries_cache=null,this._field_entries_cache=null;}_empty_control_fill_host(e,n){let r=e?.full_text??"";if(!r)return null;let i=new Map,o=/\{#(\/?)cc:(\d+)(?: [^}]*)?\}/g,s;for(;(s=o.exec(r))!==null;){let a=Number(s[2]);if(s[1]){let l=i.get(a);if(i.delete(a),l!==void 0&&l===s.index&&s.index===n){let u=this._sdt_info_for_ordinal(a);return u?(u.showingPlaceholder&&fi(u)&&(this._cc_anchor_pairs=null,this._field_entries_cache=null,this._field_entries_cache=null),it(u.element)):null}}else i.set(a,s.index+s[0].length);}return null}_apply_checkbox_set_field(e,n,r){let i=_i(e.value);if(i===null){let h=`CC:${n.ordinal} is a checkbox; '${e.value}' is neither checked nor unchecked. Use true/false (also accepted: x, [x], 1, 0, yes, no).`;return e._applied_status=false,e._error_msg=h,this.skipped_details.push(`- ${h}`),false}let o=ou(r),[s,a]=ru(r,i),l=this.doc.part._element.ownerDocument,u=o?o.cloneNode(true):l.createElement("w:r");for(let h of Array.from(u.getElementsByTagName("w:t")))h.parentNode?.removeChild(h);let c=l.createElement("w:t");if(c.appendChild(l.createTextNode(s)),u.appendChild(c),a){let h=O(u,"w:rPr");h||(h=l.createElement("w:rPr"),u.insertBefore(h,u.firstChild));for(let p of Array.from(h.getElementsByTagName("w:rFonts")))p.parentNode?.removeChild(p);let _=l.createElement("w:rFonts");for(let p of ["w:ascii","w:hAnsi","w:eastAsia","w:cs"])_.setAttribute(p,a);h.insertBefore(_,h.firstChild);}let d=this._create_track_change_tag("w:ins","",this._getNextId());d.appendChild(u);let f=o?o.parentNode:null;if(f){f.insertBefore(d,o);let h=this._create_track_change_tag("w:del","",this._getNextId()),_=o.cloneNode(true);for(let p of Array.from(_.getElementsByTagName("w:t"))){let m=l.createElement("w:delText");for(;p.firstChild;)m.appendChild(p.firstChild);for(let w=0;w<p.attributes.length;w++)m.setAttribute(p.attributes[w].name,p.attributes[w].value);p.parentNode?.replaceChild(m,p);}h.appendChild(_),f.replaceChild(h,o);}else {let h=it(r.element);if(!h)return false;h.appendChild(d);}return iu(r,i),e._applied_status=true,e._occurrences_modified=(e._occurrences_modified||0)+1,true}_resolve_set_field(e,n){let r;try{r=this._resolve_set_field_targets(e);}catch(u){e._applied_status=false,e._error_msg=u?.message??String(u),this.skipped_details.push(`- ${e._error_msg}`);return}let i=g(u=>{let c=this._sdt_info_for_ordinal(u.ordinal);return c?c.cls:u.cls_word},"clsOf");for(let u of r){let c=this._sdt_info_for_ordinal(u.ordinal),d=hi(i(u),u.ordinal);if(!d&&c&&(d=pi(c,u.ordinal,e.value)),d){e._applied_status=false,e._error_msg=d,this.skipped_details.push(`- ${d}`);return}}let o=false;for(let u of r){let c=this._sdt_info_for_ordinal(u.ordinal);c?.showingPlaceholder&&fi(c)&&(o=true);}o&&this._invalidate_projection_caches();let s=new Map,a=new Map;for(let u of r){let c=this._sdt_info_for_ordinal(u.ordinal);if(c){if(c.cls==="dropdown"||c.cls==="combobox"){let[d,f]=Io(c,e.value);if(f){let h=`CC:${u.ordinal}: ${f}`;e._applied_status=false,e._error_msg=h,this.skipped_details.push(`- ${h}`);return}s.set(u.ordinal,d),c.cls==="combobox"&&!su(c,d)&&a.set(u.ordinal,`'${d}' is not in the option list`);}else if(c.cls==="date"){let d=Hn(e.value);if(!d){let _=`CC:${u.ordinal} is a date control; '${e.value}' is not a date. Use the canonical YYYY-MM-DD form (e.g. 2026-03-01).`;e._applied_status=false,e._error_msg=_,this.skipped_details.push(`- ${_}`);return}let[f,h]=cu(d,c.dateFormat);s.set(u.ordinal,f),h&&a.set(u.ordinal,`the control's date format '${c.dateFormat}' is not supported in v1; wrote the canonical ${f}`);}}}let l=r.filter(u=>i(u)==="checkbox");if(l.length){let u=true;for(let c of l){let d=this._sdt_info_for_ordinal(c.ordinal);(!d||!this._apply_checkbox_set_field(e,c,d))&&(u=false);}u&&this._invalidate_projection_caches();return}for(let u of r){let c=this._cc_content_range(u.ordinal);if(!c){let v=`CC:${u.ordinal} has no editable content span, so set_field cannot write to it. Run read_docx with mode='fields' to see what this control is.`;e._applied_status=false,e._error_msg=v,this.skipped_details.push(`- ${v}`);return}let[d,f]=c,h=this.mapper.full_text.slice(d,f),_=s.get(u.ordinal)??e.value,p=this._sdt_info_for_ordinal(u.ordinal),m={type:"modify",target_text:h,new_text:_,comment:e.comment??null};if(m._internal_op=h?_?"MODIFICATION":"DELETION":"INSERTION",m._resolved_start_idx=d,m._active_mapper_ref=this.mapper,m._parent_edit_ref=e,!h&&p&&(m._insert_host_el=it(p.element)),p){if(p.cls==="dropdown"||p.cls==="combobox")au(p,_);else if(p.cls==="date"){let v=Hn(e.value);v&&uu(p,v);}if(p.bound){let v=hu(this.doc,p.storeItemId),b=!!v&&gu(v,p.bindingXpath,_,p.prefixMappings),y=a.get(u.ordinal),x=y?`; ${y}`:"";a.set(u.ordinal,b?`bound store ${p.bindingXpath} updated to match${x}`:`WARNING: this field is bound to ${p.bindingXpath} but the data store could not be resolved, so only the visible text was updated. If the store is restored later, Word will overwrite this edit from it.${x}`);}if(p.temporary){m._unwrap_sdt_after=p.element;let v=a.get(u.ordinal),b="this control was temporary and has been unwrapped, as Word does on any edit";a.set(u.ordinal,v?`${v}; ${b}`:b);}}let w=a.get(u.ordinal);w&&(e._warning=e._warning?`${e._warning}; ${w}`:w),(e._resolved_start_idx===void 0||e._resolved_start_idx===null)&&(e._resolved_start_idx=d,e._resolved_proxy_edit=m),n.push([m,_]);}}_field_label_at(e){if(this._cc_anchor_pairs===null){let a=[],l=this.mapper.full_text,u=new Map,c=/\{#(\/?)cc:(\d+)(?: [^}]*)?\}/g,d;for(;(d=c.exec(l))!==null;){let f=Number(d[2]);if(d[1]){let h=u.get(f);h!==void 0&&(u.delete(f),a.push([h,d.index,f]));}else u.set(f,d.index+d[0].length);}this._cc_anchor_pairs=a;}let n=null;for(let[a,l,u]of this._cc_anchor_pairs)a<=e&&e<=l&&(n===null||l-a<n[1]-n[0])&&(n=[a,l,u]);if(n===null)return "";let r=n[2],i=null,o=this.mapper._sdt_infos;if(o){for(let a of o.values())if(a.ordinal===r){i=a;break}}let s=`CC:${r}`;return i?.alias&&(s+=` "${i.alias}"`),i?.tag&&(s+=` (tag: ${i.tag})`),s}_get_heading_path_and_page(e,n,r){let i=1;for(let u=0;u<r.length&&e>=r[u];u++)i=u+1;let s=n.substring(0,e).split(`
120
+ `),a=[],l=999;for(let u=s.length-1;u>=0;u--){let d=s[u].match(/^(#{1,6})\s+(.*)/);if(d){let f=d[1].length;if(f<l){let h=d[2].replace(/\*\*|__|[*_]/g,"").replace(/\{#[^}]+\}/g,"").trim();if(h.length>80&&(h=h.substring(0,80)+"..."),a.unshift(h),l=f,f===1)break}}}return [a.join(" > "),i]}accept_all_revisions(e=false){let n=this._revision_roots(),r=0,i=0,o=0;for(let f of n){r+=R(f,"w:ins").length,i+=R(f,"w:del").length;for(let h of ["w:rPrChange","w:pPrChange","w:sectPrChange"])o+=R(f,h).length;}let s=this._comment_authors(),a=new Set(Object.keys(s));this.removed_comment_notes=[];for(let f of n){let h=R(f,"w:ins");for(let m of h){this._clean_wrapping_comments(m);let w=m.parentNode;if(w){if(w.tagName==="w:trPr"){w.removeChild(m);continue}for(;m.firstChild;)w.insertBefore(m.firstChild,m);w.removeChild(m);}}let _=R(f,"w:p");for(let m of _){let w=O(m,"w:pPr");if(w){let v=O(w,"w:rPr"),b=v?O(v,"w:del"):null;if(v&&b){let y=false;for(let x of ["w:t","w:tab","w:br"]){for(let k of R(m,x)){if(x==="w:t"&&!k.textContent)continue;let N=false,P=k.parentNode;for(;P&&P!==m;){if(P.tagName==="w:del"){N=true;break}P=P.parentNode;}if(!N){y=true;break}}if(y)break}y||this._is_last_paragraph_in_cell(m)?v.removeChild(b):(this._clean_wrapping_comments(m),this._delete_comments_in_element(m),m.parentNode&&m.parentNode.removeChild(m));}}}let p=R(f,"w:del");for(let m of p){this._clean_wrapping_comments(m),this._delete_comments_in_element(m);let w=m.parentNode;if(w)if(w.tagName==="w:trPr"){let v=w.parentNode;v&&v.parentNode&&v.parentNode.removeChild(v);}else w.removeChild(m);}for(let m of R(f,"w:pPrChange"))m.parentNode?.removeChild(m);}if(e)for(let f of n){for(let _ of ["w:commentRangeStart","w:commentRangeEnd"])for(let p of R(f,_))p.parentNode?.removeChild(p);let h=R(f,"w:commentReference");for(let _ of h){let p=_.parentNode;p&&((p.tagName==="w:r"||p.tagName.endsWith(":r"))&&Array.from(p.childNodes).filter(w=>w.nodeType===1&&w.tagName!=="w:rPr"&&w.tagName!=="rPr").length<=1?p.parentNode?.removeChild(p):p.removeChild(_));}}let l=this.doc.pkg,u=new Set;for(let f of l.parts)if(e&&f.partname.toLowerCase().includes("comments")){u.add(f.partname);let h=f.partname.startsWith("/")?f.partname:"/"+f.partname,_=f.partname.startsWith("/")?f.partname.substring(1):f.partname;u.add(h),u.add(_);}if(u.size>0){for(let h of l.parts)if(h.partname.endsWith(".rels")){let _=R(h._element,"Relationship"),p=[];for(let m of _)if((m.getAttribute("Target")||"").toLowerCase().includes("comments")){p.push(m);let v=h.partname.replace("/_rels/","/").replace(".rels",""),b=l.getPartByPath(v);if(b){let y=m.getAttribute("Id");y&&b.rels.delete(y);}}for(let m of p)m.parentNode?.removeChild(m);}let f=l.getPartByPath("[Content_Types].xml");if(f){let h=R(f._element,"Override"),_=[];for(let p of h){let m=p.getAttribute("PartName")||"";(u.has(m)||m.toLowerCase().includes("comments"))&&_.push(p);}for(let p of _)p.parentNode?.removeChild(p);}l.parts=l.parts.filter(h=>!h.partname.toLowerCase().includes("comments"));for(let h of Object.keys(l.unzipped))h.toLowerCase().includes("comments")&&delete l.unzipped[h];}let c=new Set(this._existing_comment_ids()),d=Array.from(a).filter(f=>!c.has(f)).sort((f,h)=>{let _=/^\d+$/.test(f)?parseInt(f,10):0,p=/^\d+$/.test(h)?parseInt(h,10):0;return _-p||f.localeCompare(h)});return this.removed_comment_notes=d.map(f=>`Com:${f} (by ${s[f]??"Unknown"})`),{accepted_insertions:r,accepted_deletions:i,accepted_formatting:o,removed_comments:d.length}}reject_all_revisions(){let e=this._revision_roots();for(let n of e){for(let s of R(n,"w:pPrChange"))this._revert_ppr_change(s);let r=R(n,"w:ins");for(let s of r){let a=s.parentNode;if(a)if(this._clean_wrapping_comments(s),this._delete_comments_in_element(s),a.tagName==="w:trPr"){let l=a.parentNode;l&&l.parentNode&&l.parentNode.removeChild(l);}else a.removeChild(s);}let i=R(n,"w:p");for(let s of i){let a=O(s,"w:pPr");if(a){let l=O(a,"w:rPr"),u=l?O(l,"w:del"):null;l&&u&&l.removeChild(u);}}let o=R(n,"w:del");for(let s of o){let a=s.parentNode;if(!a)continue;if(a.tagName==="w:trPr"){a.removeChild(s);continue}let l=Array.from(s.getElementsByTagName("w:delText"));for(let u of l){let c=s.ownerDocument.createElement("w:t");c.textContent=u.textContent,u.hasAttribute("xml:space")&&c.setAttribute("xml:space","preserve"),u.parentNode?.replaceChild(c,u);}for(;s.firstChild;)a.insertBefore(s.firstChild,s);a.removeChild(s);}}}_revert_ppr_change(e){let n=e.parentNode;if(!n||n.tagName!=="w:pPr")return;let r=n.parentNode;if(!r)return;let i=O(e,"w:pPr");if(i){let o=i.cloneNode(true);Array.from(o.childNodes).some(a=>a.nodeType===1)?r.replaceChild(o,n):r.removeChild(n);}else r.removeChild(n);}_revert_props_change(e){let n=e.parentNode;if(!n)return;let r=Array.from(e.childNodes).find(o=>o.nodeType===1);n.removeChild(e);let i=Nu[n.tagName];for(let o of Array.from(n.childNodes)){if(o.nodeType!==1)continue;let s=o;s.tagName==="w:rPr"&&(O(s,"w:ins")||O(s,"w:del"))||i?.has(s.tagName)||n.removeChild(o);}if(r)for(let o of Array.from(r.childNodes))o.nodeType===1&&n.appendChild(o.cloneNode(true));}_getNextId(){return this.current_id++,this.current_id.toString()}_create_track_change_tag(e,n="",r=null){let o=this.doc.part._element.ownerDocument.createElement(e),s=r!==null?r:this._getNextId();return o.setAttribute("w:id",s),o.setAttribute("w:author",n||this.author),o.setAttribute("w:date",this.timestamp),o.setAttribute("w16du:dateUtc",this.timestamp),o}_set_text_content(e,n){e.textContent=n,n.trim()!==n&&e.setAttribute("xml:space","preserve");}_comment_anchor_in_main_story(e){let n=e;for(;n.parentNode&&n.parentNode.nodeType===1;)n=n.parentNode;return n.tagName==="w:document"}_skip_comment_outside_main_story(e,n){if(this._comment_anchor_in_main_story(e))return false;let r=e;for(;r.parentNode&&r.parentNode.nodeType===1;)r=r.parentNode;let i={"w:ftr":"footer","w:hdr":"header","w:footnotes":"footnote","w:endnotes":"endnote"}[r.tagName]||"non-body",o=`- Warning: the comment "${n.substring(0,60)}" was NOT attached: Word does not support comments inside a ${i} part, and writing one produces a document other applications cannot open. The tracked change itself was applied.`;return this.skipped_details.push(o),true}_attach_comment(e,n,r,i){if(!i||!e||!n||!r||this._skip_comment_outside_main_story(e,i))return null;let o=this.comments_manager.addComment(this.author,i),s=e.ownerDocument,a=s.createElement("w:commentRangeStart");a.setAttribute("w:id",o);let l=s.createElement("w:commentRangeEnd");l.setAttribute("w:id",o);let u=s.createElement("w:r"),c=s.createElement("w:rPr"),d=s.createElement("w:rStyle");d.setAttribute("w:val","CommentReference"),c.appendChild(d),u.appendChild(c);let f=s.createElement("w:commentReference");f.setAttribute("w:id",o),u.appendChild(f),e.insertBefore(a,n);let h=r.nextSibling;return h?(e.insertBefore(l,h),e.insertBefore(u,l.nextSibling)):(e.appendChild(l),e.appendChild(u)),o}_attach_comment_spanning(e,n,r,i,o){if(!o||!e||!r||this._skip_comment_outside_main_story(e,o)||this._skip_comment_outside_main_story(r,o))return;let s=this.comments_manager.addComment(this.author,o),a=e.ownerDocument,l=r.ownerDocument,u=a.createElement("w:commentRangeStart");u.setAttribute("w:id",s);let c=l.createElement("w:commentRangeEnd");c.setAttribute("w:id",s);let d=l.createElement("w:r"),f=l.createElement("w:rPr"),h=l.createElement("w:rStyle");h.setAttribute("w:val","CommentReference"),f.appendChild(h),d.appendChild(f);let _=l.createElement("w:commentReference");_.setAttribute("w:id",s),d.appendChild(_),e.insertBefore(u,n);let p=i.nextSibling;p?(r.insertBefore(c,p),r.insertBefore(d,c.nextSibling)):(r.appendChild(c),r.appendChild(d));}_is_native_heading_element(e){try{let n=this.doc.part||this.doc,[r,i]=lt(n);return rn({_element:e},r,i)}catch{return false}}_clone_pPr_scrubbing_headings(e,n=null){let r=e.cloneNode(true),i=O(r,"w:pStyle");if(i){let s=i.getAttribute("w:val");s&&(s.startsWith("Heading")||s==="Title"||s.replace(/\s+/g,"").startsWith("Heading")||n!==null&&this._is_native_heading_element(n))&&r.removeChild(i);}let o=O(r,"w:outlineLvl");return o&&r.removeChild(o),r}_track_insert_multiline(e,n,r,i,o=null,s=false,a=false){if(!e)return {first_node:null,last_p:null,last_ins:null,used_block_mode:false};let l=this.doc.part._element.ownerDocument,u=e.split(/[\r\n]+/),c=null;if(r!==null)c=r._element;else if(n!==null){let B=n._element;for(;B&&B.tagName!=="w:p";)B=B.parentNode;c=B;}let d=[],f=new Set(["w:r","w:ins","w:del"]),h=o&&o.parentNode?o:null,_=n!==null&&n._element.parentNode?n._element:null,p=h??_,m=a&&h===null&&_!==null;if(c!==null&&p!==null){let B=p;for(;B&&B.parentNode!==c;)if(B=B.parentNode,B===c){B=null;break}if(B){let $=m?B:B.nextSibling;for(;$;)$.nodeType===1&&f.has($.tagName)&&d.push($),$=$.nextSibling;}}else if(c!==null&&a){let B=c.firstChild;for(;B;)B.nodeType===1&&f.has(B.tagName)&&d.push(B),B=B.nextSibling;}for(;u.length>1&&u[u.length-1]===""&&d.length===0;)u.pop();if(u.length===0)return {first_node:null,last_p:null,last_ins:null,used_block_mode:false};let[w,v]=this._parse_markdown_style(u[0]),b=c!==null,y=/[\r\n]/.test(e),x=v!==null&&b&&y,k=null,N=null;x||(N=this._build_tracked_ins_for_line((w===u[0],u[0]),n,i,l,s),k=N);let P=x?u:u.slice(1);if(P.length===0)return {first_node:k,last_p:null,last_ins:N,used_block_mode:false};if(!c)return {first_node:k,last_p:null,last_ins:N,used_block_mode:false};let A=c.parentNode;if(!A)return {first_node:k,last_p:null,last_ins:N,used_block_mode:false};let C=g((B,$)=>{A.insertBefore(B,$.nextSibling);},"insertAfterEl"),T=null,M=null,j=c;for(let B=0;B<P.length;B++){let $=P[B],[I,E]=this._parse_markdown_style($),S=l.createElement("w:p");if(E)this._set_paragraph_style(S,E);else {let L=O(c,"w:pPr");L&&S.appendChild(this._clone_pPr_scrubbing_headings(L,c));}let D=O(S,"w:pPr");D||(D=l.createElement("w:pPr"),S.insertBefore(D,S.firstChild));let U=O(D,"w:rPr");U||(U=l.createElement("w:rPr"),D.appendChild(U));let z=this._create_track_change_tag("w:ins","",i);U.appendChild(z);let W=this._build_tracked_ins_for_line(I,n,i,l,s);W&&S.appendChild(W),C(S,j),j=S,T=S,M=W,k||(k=S);}if(!x&&T&&d.length>0)for(let B of d)B.parentNode?.removeChild(B),T.appendChild(B);return {first_node:k,last_p:T,last_ins:M,used_block_mode:x}}_build_tracked_ins_for_line(e,n,r,i,o=false){if(!e&&e!=="")return null;let s=this._create_track_change_tag("w:ins","",r),a=this._parse_inline_markdown(e);if(a.length===0)return null;for(let[l,u]of a){let c=i.createElement("w:r");if(n&&n._element){let f=O(n._element,"w:rPr");if(f){let h=f.cloneNode(true),_=["w:vanish","w:strike","w:dstrike","w:i","w:iCs"];o&&_.push("w:b","w:bCs");for(let p of _){let m=O(h,p);m&&h.removeChild(m);}c.appendChild(h);}}this._apply_run_props(c,u,false);let d=i.createElement("w:t");this._set_text_content(d,l),c.appendChild(d),s.appendChild(c);}return s}_parse_markdown_style(e){let n=e.trimStart();if(n.startsWith("#")){let i=0,o=n;for(;o.startsWith("#");)i++,o=o.substring(1);if(o.startsWith(" "))return [o.trim(),`Heading ${i}`]}if(n.startsWith("* ")||n.startsWith("- "))return [n.substring(2).trim(),"List Paragraph"];let r=n.match(/^1\.\s+/);return r?[n.substring(r[0].length).trim(),"List Number"]:[e,null]}_edit_declares_emphasis(e){for(let n of [e?.target_text,e?.new_text]){if(!n||!n.includes("**")&&!n.includes("_"))continue;if(this._parse_inline_markdown(n).some(([,i])=>i&&Object.keys(i).length>0))return true}return false}_parse_inline_markdown(e,n={}){if(!e)return [];let r=/(\*\*.*?\*\*)|(_.*?_)/,i=e.match(r);if(!i)return [[e,n]];let o=i.index,s=i[0],a=o+s.length,l=s.startsWith("**"),u=l?s.substring(2,s.length-2):s.substring(1,s.length-1),c=e.substring(0,o),d=e.substring(a),f=[];c&&f.push([c,n]);let h={...n};return l?h.bold=true:h.italic=true,f.push(...this._parse_inline_markdown(u,h)),f.push(...this._parse_inline_markdown(d,n)),f}_apply_run_props(e,n,r=false){if(!n){if(!r)return;n={};}let i=O(e,"w:rPr");if(!i&&(n.bold||n.italic||r)&&(i=e.ownerDocument.createElement("w:rPr"),e.appendChild(i)),i){let o=e.ownerDocument;if(n.bold){let s=O(i,"w:b");s||(s=o.createElement("w:b"),i.appendChild(s)),s.setAttribute("w:val","1");}else if(r){let s=O(i,"w:b");s&&i.removeChild(s);}if(n.italic){let s=O(i,"w:i");s||(s=o.createElement("w:i"),i.appendChild(s)),s.setAttribute("w:val","1");}else if(r){let s=O(i,"w:i");s&&i.removeChild(s);}}}_set_paragraph_style(e,n,r=null){let i=e.ownerDocument,o=O(e,"w:pPr");o&&e.removeChild(o);let s=i.createElement("w:pPr"),a=i.createElement("w:pStyle"),l=n.replace(/\s+/g,"");if(a.setAttribute("w:val",l),s.appendChild(a),l==="ListParagraph"){let u=this._ensure_bullet_num_id();if(u){let c=i.createElement("w:numPr"),d=i.createElement("w:ilvl");d.setAttribute("w:val","0");let f=i.createElement("w:numId");f.setAttribute("w:val",u),c.appendChild(d),c.appendChild(f),s.appendChild(c);}}if(r!==null){let u=this._create_track_change_tag("w:pPrChange","",r),c=o?o.cloneNode(true):i.createElement("w:pPr"),d=O(c,"w:pPrChange");d&&c.removeChild(d),u.appendChild(c),s.appendChild(u);}e.insertBefore(s,e.firstChild);}static _NUMBERING_CT="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml";static _NUMBERING_RT="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering";_ensure_bullet_num_id(){let e=this.doc.pkg,n="http://schemas.openxmlformats.org/wordprocessingml/2006/main",r='<w:lvl w:ilvl="0"><w:start w:val="1"/><w:numFmt w:val="bullet"/><w:lvlText w:val="\uF0B7"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="720" w:hanging="360"/></w:pPr><w:rPr><w:rFonts w:ascii="Symbol" w:hAnsi="Symbol" w:hint="default"/></w:rPr></w:lvl>',i=e.parts.find(C=>String(C.partname).replace(/^\//,"")==="word/numbering.xml");if(!i){let C=`<w:numbering xmlns:w="${n}"><w:abstractNum w:abstractNumId="0"><w:multiLevelType w:val="singleLevel"/>`+r+'</w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num></w:numbering>';try{i=e.addPart("/word/numbering.xml",Z._NUMBERING_CT,C),this.doc.relateTo(i,Z._NUMBERING_RT);}catch{return null}return delete e._adeu_numbering_cache,"1"}let o=i._element,s=R(o,"w:abstractNum"),a=R(o,"w:num"),l=null;for(let C of s){let T=C.getAttribute("w:abstractNumId");if(T!==null){for(let M of R(C,"w:lvl")){if((M.getAttribute("w:ilvl")||"0")!=="0")continue;let j=O(M,"w:numFmt");j&&j.getAttribute("w:val")==="bullet"&&(l=T);break}if(l!==null)break}}let u=0;for(let C of a){let T=parseInt(C.getAttribute("w:numId")||"0",10);!isNaN(T)&&T>u&&(u=T);}let c=o.ownerDocument;if(l!==null){for(let M of a){let j=O(M,"w:abstractNumId");if(j&&j.getAttribute("w:val")===l){let B=M.getAttribute("w:numId");if(B&&B!=="0")return B}}let C=c.createElement("w:num");C.setAttribute("w:numId",String(u+1));let T=c.createElement("w:abstractNumId");return T.setAttribute("w:val",l),C.appendChild(T),o.appendChild(C),delete e._adeu_numbering_cache,String(u+1)}let d=-1;for(let C of s){let T=parseInt(C.getAttribute("w:abstractNumId")||"-1",10);!isNaN(T)&&T>d&&(d=T);}let f=c.createElement("w:abstractNum");f.setAttribute("w:abstractNumId",String(d+1));let h=c.createElement("w:multiLevelType");h.setAttribute("w:val","singleLevel"),f.appendChild(h);let _=c.createElement("w:lvl");_.setAttribute("w:ilvl","0");let p=c.createElement("w:start");p.setAttribute("w:val","1"),_.appendChild(p);let m=c.createElement("w:numFmt");m.setAttribute("w:val","bullet"),_.appendChild(m);let w=c.createElement("w:lvlText");w.setAttribute("w:val","\uF0B7"),_.appendChild(w);let v=c.createElement("w:lvlJc");v.setAttribute("w:val","left"),_.appendChild(v);let b=c.createElement("w:pPr"),y=c.createElement("w:ind");y.setAttribute("w:left","720"),y.setAttribute("w:hanging","360"),b.appendChild(y),_.appendChild(b);let x=c.createElement("w:rPr"),k=c.createElement("w:rFonts");k.setAttribute("w:ascii","Symbol"),k.setAttribute("w:hAnsi","Symbol"),k.setAttribute("w:hint","default"),x.appendChild(k),_.appendChild(x),f.appendChild(_);let N=a.find(C=>C.parentNode===o)||null;N?o.insertBefore(f,N):o.appendChild(f);let P=c.createElement("w:num");P.setAttribute("w:numId",String(u+1));let A=c.createElement("w:abstractNumId");return A.setAttribute("w:val",String(d+1)),P.appendChild(A),o.appendChild(P),delete e._adeu_numbering_cache,String(u+1)}_anchor_reply_comment(e,n){let r=this.doc.part._element.ownerDocument,i=R(this.doc.element,"w:commentRangeStart").filter(m=>m.getAttribute("w:id")===e);if(i.length===0)return;let o=i[0],s=r.createElement("w:commentRangeStart");s.setAttribute("w:id",n),nt(s,o);let a=R(this.doc.element,"w:commentRangeEnd").filter(m=>m.getAttribute("w:id")===e);if(a.length===0)return;let l=a[0],u=R(this.doc.element,"w:commentReference").filter(m=>m.getAttribute("w:id")===e),c=l;if(u.length>0){let m=u[0];m.parentNode&&m.parentNode.tagName==="w:r"&&(c=m.parentNode);}let d=r.createElement("w:commentRangeEnd");d.setAttribute("w:id",n),nt(d,c);let f=r.createElement("w:r"),h=r.createElement("w:rPr"),_=r.createElement("w:rStyle");_.setAttribute("w:val","CommentReference"),h.appendChild(_),f.appendChild(h);let p=r.createElement("w:commentReference");p.setAttribute("w:id",n),f.appendChild(p),nt(f,d);}_clean_wrapping_comments(e){let n=0,r=e;for(;;){let c=Ie(r);if(c&&(c.tagName==="w:ins"||c.tagName==="w:del"))r=c;else break}let i=e;for(;;){let c=Ae(i);if(c&&(c.tagName==="w:ins"||c.tagName==="w:del"))i=c;else break}let o=[],s=Ie(r);for(;s;)if(s.tagName==="w:commentRangeStart")o.push(s),s=Ie(s);else if(s.tagName==="w:rPr"||s.tagName==="w:pPr")s=Ie(s);else break;let a=[],l=Ae(i);for(;l;)if(l.tagName==="w:commentRangeEnd")a.push(l),l=Ae(l);else if(l.tagName==="w:r"&&R(l,"w:commentReference").length>0)a.push(l),l=Ae(l);else if(l.tagName==="w:commentReference")a.push(l),l=Ae(l);else break;let u=new Set;for(let c of a)if(c.tagName==="w:commentRangeEnd"){let d=c.getAttribute("w:id");d&&u.add(d);}else {let d=R(c,"w:commentReference")[0];if(!d&&c.tagName==="w:commentReference"&&(d=c),d){let f=d.getAttribute("w:id");f&&u.add(f);}}for(let c of o){let d=c.getAttribute("w:id");if(d&&u.has(d)){this.comments_manager.deleteComment(d),n++,c.parentNode&&c.parentNode.removeChild(c);for(let f of a){let h=null;if(f.tagName==="w:commentRangeEnd")h=f.getAttribute("w:id");else {let _=R(f,"w:commentReference")[0];!_&&f.tagName==="w:commentReference"&&(_=f),_&&(h=_.getAttribute("w:id"));}h===d&&f.parentNode&&f.parentNode.removeChild(f);}}}return n}_delete_comments_in_element(e){let n=0,r=R(e,"w:commentReference");for(let i of r){let o=i.getAttribute("w:id");if(o){this.comments_manager.deleteComment(o),n++;for(let s of ["w:commentRangeStart","w:commentRangeEnd"]){let a=R(this.doc.element,s);for(let l of a)l.getAttribute("w:id")===o&&l.parentNode&&l.parentNode.removeChild(l);}}}return n}_control_gate_context(e,n,r){let i=typeof e?.controls_intersecting=="function"?e.controls_intersecting(n,r):[],o=typeof e?.controls_at=="function"?e.controls_at(n):[],s=typeof e?.controls_at=="function"?e.controls_at(Math.max(n+r-1,n)):[];return [i,o,s]}_deletes_entire_control(e,n,r,i,o){if(o.trim()!=="")return false;let a=(e?.control_ranges??[]).find(f=>f[2]===n);if(!a)return false;let[l,u]=a,c=r<=l&&r+i>=u,d=r<l||r+i>u;return c&&d}_check_control_gates(e,n,r,i,o,s="",a="",l=null,u=false){let c=this.gate_overrides,d=Array.from(r?._sdt_infos?.values()??[]),[f,h,_]=this._control_gate_context(r,i,o);l!==null&&(f=l);let p=!!n.comment&&(n.new_text||"")===(n.target_text||""),m=rc(e,this.protection,{controls:f,isCommentOnly:p,overrides:c});if(m||!p&&(m=oc(e,this.protection,c),m)||(m=sc(e,n.target_text||"",d),m))return m;if(f.length===0)return null;if(!u&&(m=lc(e,f),m)||(m=ac(e,f,n.target_text||"",n.new_text||""),m)||(m=ec(e,f,c),m)||(m=tc(e,f,c),m))return m;for(let v of f)if(this._deletes_entire_control(r,v,i,o,a)&&(m=nc(e,[v],true,c),m))return m;if(s.includes(`
121
+
122
+ `)&&!a.includes(`
123
+
124
+ `)){let v=ri(f,h,_);if(m=cc(e,v),m)return m}let w=ri(f,h,_);if(w.length>0&&(n._warning=uc(w)),c.ignore_control_locks)for(let v of f)(v.contentLocked||v.cls==="group")&&(this._overridden_controls.includes(v)||this._overridden_controls.push(v));return null}_apply_gate_refusal(e,n,r,i=false){let o=this.gate_overrides;if(sn(this.protection)&&!o.ignore_document_protection&&this.protection.edit==="readOnly")return "document is read-only protected";let s=typeof e?.controls_intersecting=="function"?e.controls_intersecting(n,r):[];if(s.length===0)return null;let a=s.find(u=>u.bound);if(a&&!i)return `${he(a)} is data-bound`;if(o.ignore_control_locks)return null;let l=s.find(u=>u.contentLocked);return l?`${he(l)} is content-locked`:null}_resolve_structural_table_edit(e){let n=this.mapper.drop_virtual_only_matches(this.mapper.find_all_match_indices(e.target_text)),r=this.mapper;if(n.length===0&&(this.clean_mapper||(this.clean_mapper=new ke(this.doc,true)),n=this.clean_mapper.drop_virtual_only_matches(this.clean_mapper.find_all_match_indices(e.target_text)),r=this.clean_mapper),n.length===0){let u=(e.target_text||"").trim().substring(0,40);return {sub_edits:[],err_msg:`- Failed to apply structural edit targeting: '${u}...'`}}let i=e.match_mode||"strict",o=[],s=new Set;for(let u of n){let c=u[0],[d,f]=r.get_insertion_anchor(c,false),h=null;d?h=d._element:f&&(h=f._element);let _=h;for(;_&&_.tagName!=="w:tr";)_=_.parentNode;_&&!s.has(_)&&(s.add(_),o.push(u));}if(o.length===0){let u=(e.target_text||"").trim().substring(0,40);return {sub_edits:[],err_msg:`- Failed to locate row target: '${u}...'`}}let a=o;(i==="strict"||i==="first")&&(a=o.slice(0,1));let l=[];if(i==="all"||a.length>1)for(let u of a){let c={...e,_resolved_start_idx:u[0],_active_mapper_ref:r,_parent_edit_ref:e};l.push([c,null]);}else e._resolved_start_idx=a[0][0],e._active_mapper_ref=r,l.push([e,null]);return {sub_edits:l,err_msg:null}}_validate_set_field_edit(e,n){let r=[],i;try{i=this._resolve_set_field_targets(e);}catch(s){return [`- Edit ${n} Failed: ${s?.message??s}`]}let o=null;for(let s of i){let a=this._sdt_info_for_ordinal(s.ordinal);if(o=hi(a?a.cls:s.cls_word,s.ordinal),!o&&a&&(o=pi(a,s.ordinal,e.value)),o)return [`- Edit ${n} Failed: ${o}`]}for(let s of i){let a=this._cc_content_range(s.ordinal),l=this._sdt_info_for_ordinal(s.ordinal);if(!a){if(!l||l.cls!=="checkbox")continue;let _=_i(e.value),p=l.checked?vt[1]:vt[0],m=_?vt[1]:vt[0],w=this._check_control_gates(n,{type:"modify",target_text:p,new_text:m,comment:null},this.mapper,0,0,p,m,[l],true);if(w){r.push(w);break}continue}let[u,c]=a,d=this.mapper.full_text.slice(u,c),f={type:"modify",target_text:d,new_text:e.value,comment:e.comment??null};f._parent_edit_ref=e;let h=this._check_control_gates(n,f,this.mapper,u,c-u,d,e.value,l?[l]:null,true);if(h){r.push(h);break}}return r}validate_edits(e,n=0){let r=[];this.mapper.full_text||this.mapper._build_map(),r.push(...Au(e,n));for(let i=0;i<e.length;i++){let o=e[i];if(typeof o!="object"||o===null){r.push(`- Edit ${i+1+n} Failed: Invalid change format. Expected a JSON object, but received a primitive ${typeof o}. Do not pass raw strings.`);continue}if(o.type==="set_field"){r.push(...this._validate_set_field_edit(o,i+1+n));continue}if(o._match_start_index!==void 0&&o._match_start_index!==null||o._resolved_start_idx!==void 0&&o._resolved_start_idx!==null)continue;if(o.target_text===void 0||o.target_text===null||!String(o.target_text).trim()){o.type==="insert_row"?r.push(`- Edit ${i+1+n} Failed: insert_row requires target_text (text inside an existing row to anchor on) and cells (the new row's cell values).`):o.type==="delete_row"?r.push(`- Edit ${i+1+n} Failed: delete_row requires target_text (text inside the row to delete).`):r.push(`- Edit ${i+1+n} Failed: target_text is empty. Pure insertions are expressed as a replacement: put the text immediately around the insertion point in target_text and repeat it (plus the new text) in new_text.`);continue}if(o.type==="modify"&&(o.new_text===void 0||o.new_text===null))if(o.comment&&String(o.comment).trim())o.new_text=o.target_text;else {r.push(`- Edit ${i+1+n} Failed: modify requires new_text (an empty string deletes the target; to attach a comment without changing the text, supply the comment and omit new_text).`);continue}let s=o.regex||false,a=o.match_mode||"strict";if(s)try{new RegExp(o.target_text);}catch(h){r.push(`- Edit ${i+1+n} Failed: target_text is not a valid regular expression (${h?.message??h}). Fix the pattern, or set "regex": false to match the text literally.`);continue}let l=this.mapper.drop_virtual_only_matches(this.mapper.find_all_match_indices(o.target_text,s)),u=this.mapper.full_text,c=this.mapper;l.length===0&&(this.clean_mapper||(this.clean_mapper=new ke(this.doc,true)),l=this.clean_mapper.drop_virtual_only_matches(this.clean_mapper.find_all_match_indices(o.target_text,s)),l.length>0&&(u=this.clean_mapper.full_text,c=this.clean_mapper)),u===this.mapper.full_text&&l.length>0&&(l=l.filter(([_,p])=>{let m=this.mapper.spans.filter(w=>w.run!==null&&w.end>_&&w.start<_+p);return m.length===0?true:m.some(w=>!w.del_id)}));let d=false,f=new Set;if(l.length===0){this.original_mapper||(this.original_mapper=new ke(this.doc,false,true));let h=this.original_mapper.drop_virtual_only_matches(this.original_mapper.find_all_match_indices(o.target_text,s));if(h.length>0){d=true;for(let[_,p]of h){let m=this.original_mapper.spans.filter(w=>w.end>_&&w.start<_+p);for(let w of m)if(w.run!==null){let v=w.run._element;for(;v;){if(v.nodeType===1&&v.tagName==="w:del"){let b=v.getAttribute("w:author");b&&f.add(b);break}v=v.parentNode;}}}}}if(l.length===0)if(d){let h=f.size>0?`by ${Array.from(f).sort().join(", ")}`:"by an existing revision";r.push(`- Edit ${i+1+n} Failed: Target text matches text inside a tracked deletion ${h}. Reject/accept that change first or target the active replacement text instead.`);}else {let h=this._nearest_match_hint(o.target_text,s);r.push(`- Edit ${i+1+n} Failed: Target text not found in document:
125
+ "${de(o.target_text,Sn)}"${h}`);}else if(l.length>1&&a==="strict")if(o.target_text.includes("|"))l=l.slice(0,1);else {let h=l.map(([_,p])=>[_,_+p]);r.push(Nl(i+1+n,o.target_text,u,h));}if(l.length===1){let[h,_]=l[0],p=u.substring(h,h+_),[m,w]=rt(p,o.new_text||""),v=p.length-w,b=p.substring(m,v),y=(o.new_text||"").substring(m,(o.new_text||"").length-w),k=c.part_ranges.filter(C=>C[1]>C[0]).length>1?Array.from(new Set(c.spans.filter(C=>C.run!==null&&C.end>h&&C.start<h+_).map(C=>C.part_index))).sort((C,T)=>C-T):[];if(k.length>1){let C=k.map(T=>c.part_kind_of(T)||"?").join(" \u2192 ");r.push(`- Edit ${i+1+n} Failed: target_text spans a structural document-part boundary (${C}). Headers, body, footers and footnotes are separate Word parts \u2014 an edit cannot cross between them. Anchor the edit on text within a single part (split it into one edit per part if both sides must change).`);}let N=h+m,P=h+_-w,A=this._check_control_gates(i+1+n,o,c,N,Math.max(P-N,0),b,y);if(A&&r.push(A),P>N&&c.spans.filter(T=>T.end>N&&T.start<P&&(T.run!==null||T.text.trim()!=="")).some(T=>T.is_image_marker)&&r.push(`- Edit ${i+1+n} Failed: the target overlaps a read-only image marker (![alt](docx-image:N)). Images cannot be edited or removed via text replacement \u2014 target the text around the image instead.`),o.comment&&(o.new_text||"")===(o.target_text||"")){let C=c.part_kind_at(h);C!==null&&C!=="body"&&r.push(`- Edit ${i+1+n} Failed: comments cannot be anchored inside a ${C} part \u2014 Word only supports comments in the main document body. Comment on the related body text instead.`);}if(Z._introduces_table_row_text(c,h,_,b,y)&&r.push(`- Edit ${i+1+n} Failed: new_text introduces a pipe-delimited row line inside a table. Text replacement cannot create table rows \u2014 use the structured 'insert_row' operation instead (e.g. {"type": "insert_row", "target_text": "<anchor row text>", "cells": ["...", "..."]}).`),b.includes(`
96
126
 
97
127
  `)&&!(p.split(`
98
128
 
99
- `).length===(i.new_text||"").split(`
129
+ `).length===(o.new_text||"").split(`
100
130
 
101
- `).length))if(w.includes(`
131
+ `).length))if(y.includes(`
102
132
 
103
133
  `)){let T=p.split(`
104
134
 
105
- `);T.length>=2&&T[0].trim()!==""&&T[T.length-1].trim()!==""&&r.push(`- Edit ${s+1+n} Failed: target_text spans a paragraph boundary with body text on both sides. The paragraph break is a structural element, not literal text, so it cannot be replaced as a single span without corrupting the document. Split this into one edit per paragraph.`);}else {let T=b.split(`
135
+ `);T.length>=2&&T[0].trim()!==""&&T[T.length-1].trim()!==""&&r.push(`- Edit ${i+1+n} Failed: target_text spans a paragraph boundary with body text on both sides. The paragraph break is a structural element, not literal text, so it cannot be replaced as a single span without corrupting the document. Split this into one edit per paragraph.`);}else {let T=b.split(`
106
136
 
107
- `);T.length>=2&&T[0].trim()!==""&&T[T.length-1].trim()!==""&&r.push(`- Edit ${s+1+n} Failed: target_text spans a paragraph boundary with body text on both sides. The paragraph break is a structural element, not literal text, so it cannot be replaced as a single span without corrupting the document. Split this into one edit per paragraph.`);}}for(let[h,_]of a){let p=c.spans.filter(b=>b.end>h&&b.start<h+_),m=new Map,y=new Map,x=false;for(let b of p){if(b.run===null)continue;let w=false;if(b.ins_id){let v=M(this.doc.element,"w:ins").filter(N=>N.getAttribute("w:id")===b.ins_id);if(v.length>0){let N=v[0].getAttribute("w:author");N&&N!==this.author&&(m.has(N)||m.set(N,new Set),m.get(N).add(b.ins_id),w=true);}}w||(x=true);}for(let b of p)if(b.comment_ids)for(let w of b.comment_ids){let v=this.mapper.comments_map[w];v&&v.author&&v.author!==this.author&&(y.has(v.author)||y.set(v.author,new Set),y.get(v.author).add(`Com:${w}`));}if(m.size>0){let b=!x;if(!((l==="strict"||l==="first")&&b)){let w=Array.from(m.keys()).sort(),v=w[0],k=Array.from(m.get(v)).sort(($,O)=>{let F=/^\d+$/.test($)?parseInt($,10):0,W=/^\d+$/.test(O)?parseInt(O,10):0;return F!==W?F-W:$.localeCompare(O)}),C=k.length>0?`Chg:${k[0]}`:null,A=k.slice(0,2).map($=>`Chg:${$}`).join(", "),T=A?` (e.g. ${A})`:"";w.length>1&&(T+=` (+${w.length-1} more)`);let D=C?`{"type": "accept", "target_id": "${C}"}`:"",j=l==="all"&&b?'or use match_mode="strict" or "first", or scope your edit outside of it.':"or scope your edit outside of it.",E=`- Edit ${s+1+n} Failed: Modification targets an active insertion from another author (`,I=`${T}). Accept first with ${D} ${j}`,P=cr-E.length-I.length,S=E+Qn(v,P)+I;r.push(Qn(S,cr));continue}}if(y.size>0&&l==="all"){let b=[],w=Array.from(y.keys()).sort();for(let v of w){let C=Array.from(y.get(v)).sort((A,T)=>{let D=A.split(":").pop()||"",j=T.split(":").pop()||"",E=/^\d+$/.test(D)?parseInt(D,10):0,I=/^\d+$/.test(j)?parseInt(j,10):0;return E!==I?E-I:A.localeCompare(T)}).join(", ");b.push(C?`${v} (e.g. ${C})`:v);}r.push(`- Edit ${s+1+n} Failed: match_mode="all" would sweep through a comment range from another author (${b.join(", ")}). Target the commented text deliberately with match_mode "strict" or "first", or scope your edit outside of it.`);}}if((i.type==="insert_row"||i.type==="delete_row")&&a.length>0){let[h,_]=a[0],p=V._column_count_at(c,h,_);p===null?r.push(`- Edit ${s+1+n} Failed: ${i.type} target text was found, but it is not inside a table row. Anchor the operation on text that appears within the table.`):i.type==="insert_row"&&Array.isArray(i.cells)&&i.cells.length>p&&r.push(`- Edit ${s+1+n} Failed: insert_row provides ${i.cells.length} cells but the target table has ${p} column(s). The extra cell(s) would be dropped. Provide at most ${p} cells \u2014 rows given fewer cells are padded with empty ones.`);}}return r}static _introduces_table_row_text(e,n,r,s,i){if(!i.includes(`
108
- `)||!i.includes(" | "))return false;let o=i.split(`
109
- `).filter(a=>a.includes(" | ")).length,l=s.split(`
110
- `).filter(a=>a.includes(" | ")).length;return o<=l?false:V._column_count_at(e,n,Math.max(r,1))!==null}static _column_count_at(e,n,r){for(let s of e.spans){if(s.end<=n||s.start>=n+r)continue;let i=null;for(s.run!==null?i=s.run._element:s.paragraph!==null&&(i=s.paragraph._element);i;){if(i.nodeType===1&&i.tagName==="w:tr")return M(i,"w:tc").filter(o=>o.parentNode===i).length;i=i.parentNode;}}return null}validate_review_actions(e,n,r=false){let s=[],i=g(a=>n?n[a]:a,"gidx"),o=new Map,l=new Set;for(let a=0;a<e.length;a++){let u=e[a],c=u.type,d=u.target_id??"";if(c==="reply"){if(!String(u.text??"").trim()){s.push(`- Action ${i(a)+1} Failed: reply text for ${d} is empty or whitespace-only. Word would show a blank comment bubble \u2014 provide the reply content in 'text'.`);continue}let f=d+"\0"+String(u.text).trim();l.has(f)&&s.push(`- Action ${i(a)+1} Failed: duplicate reply \u2014 this batch already replies to ${d} with the same text. Remove the duplicate action.`),l.add(f);}else if(c==="accept"||c==="reject"){let f=o.get(d);if(f!==void 0){let[h,_]=f;_===c?s.push(`- Action ${i(a)+1} Failed: duplicate action \u2014 Action ${i(h)+1} in this batch already applies '${c}' to ${d}. A change can only be resolved once; remove the duplicate action.`):s.push(`- Action ${i(a)+1} Failed: conflicting actions \u2014 Action ${i(h)+1} in this batch applies '${_}' to ${d}, but this action applies '${c}'. Decide the outcome and keep exactly one of them.`);}else o.set(d,[a,c]);}}if(s.length>0||r)return s;for(let a=0;a<e.length;a++){let u=e[a],c=u.type;if(c==="reply"){let d=u.target_id.replace("Com:",""),f=false,h=this.doc.pkg.parts.find(_=>_.contentType==="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");h&&(f=M(h._element,"w:comment").some(p=>p.getAttribute("w:id")===d)),f||s.push(this._action_not_found_error(u.target_id,"reply",`- Action ${i(a)+1} Failed:`));}else if(c==="accept"||c==="reject"){let d=u.target_id.replace("Chg:",""),f=M(this.doc.element,"w:ins").filter(p=>p.getAttribute("w:id")===d),h=M(this.doc.element,"w:del").filter(p=>p.getAttribute("w:id")===d),_=M(this.doc.element,"w:pPrChange").filter(p=>p.getAttribute("w:id")===d);f.length===0&&h.length===0&&_.length===0&&s.push(this._action_not_found_error(u.target_id,c,`- Action ${i(a)+1} Failed:`));}}return s}get_pending_revision_authors(){let e=new Set,n=g(r=>{if(r)try{if(typeof r.getAttribute=="function"){let i=r.getAttribute("w:author");i&&e.add(i);}let s=M(r,"*");for(let i of s){let o=i.getAttribute("w:author");o&&e.add(o);}}catch{}},"collect");try{this.doc?.element&&n(this.doc.element);}catch{}try{if(this.doc?.pkg){let r=Pe(this.doc.pkg);for(let s of Object.values(r)){let i=s?.author;i&&i!=="Unknown"&&e.add(i);}}}catch{}try{let r=this.doc?.pkg?.parts||[];for(let s of r){if(s===this.doc?.part||!String(s.contentType||"").endsWith("+xml"))continue;let i=String(s.partname||"").toLowerCase();if(!(String(s.contentType||"")==="application/vnd.ms-word.people+xml"||i.includes("people")))try{let l=s._element;!l&&s.blob&&(l=je(s.blob)),l&&n(l);}catch{}}}catch{}return e}process_batch(e,n,r=false){return Array.isArray(e)&&(e=e.map(s=>{if(typeof s=="string")try{let i=JSON.parse(s);return i!==null&&typeof i=="object"?i:s}catch{return s}return s})),this._process_batch_internal(e,n,r)}_batch_fingerprint(){let e=0,n=new Set;for(let r of Kt)for(let s of this._revisionsByTag(r))e++,s.id&&n.add(s.id);return [e,[...n].sort().join(","),this._existing_comment_ids().join(",")].join("|")}_restore_batch_snapshot(e,n){e&&(ea(this.doc,e),this.current_id=n,this.mapper=new ve(this.doc),this.comments_manager=new st(this.doc),this.clean_mapper=null,this._revisionIndex=null);}_verify_rollback(e){if(e!==null)try{this.rollback_verified=this._batch_fingerprint()===e;}catch{this.rollback_verified=false;}}_process_batch_internal(e,n,r=false){this.rollback_verified=true;let s=this.get_pending_revision_authors(),i=this.author&&s.has(this.author)?`[!] Warning: acting author '${this.author}' matches an author with pending revisions in this document.`:null;for(let P of e)if(P&&typeof P=="object"&&P.type==="modify"&&P.target_text&&P.new_text){let[S,$]=ta(P.target_text,P.new_text);P.target_text=S,P.new_text=$;}this.skipped_details=[];let o=[],l=g(P=>n?n[P]:P,"idx_of"),a=g(P=>P!==null&&typeof P=="object"&&["accept","reject","reply"].includes(P.type),"is_action"),u=e.map((P,S)=>({c:P,i:l(S)})).filter(({c:P})=>a(P)),c=e.map((P,S)=>({c:P,i:l(S)})).filter(({c:P})=>!a(P)),d=u.map(({c:P})=>P),f=u.map(({i:P})=>P),h=c.map(({c:P})=>P),_=d.length>0?this.validate_review_actions(d,f,r):[];d.length>0&&_.length===0&&(_=this.validate_action_pairing(d,f));let p=h.length>0&&_.length>0,m=[];if(p)for(let{c:P,i:S}of c){let $=this.validate_edits([P],S);$.length>0&&(m.push(...$),o.push([S,$.join(`
111
- `)]));}let y=[..._,...m];if(y.length>0)throw o.unshift(...un(_)),new mt(y,o);let x=0,b=0,w=0,N=d.length>0||h.length>0?Ko(this.doc):null,k=d.length>0?this._batch_fingerprint():null,C=this.current_id;if(d.length>0){try{let P=this.apply_review_actions(d,f);if(x=P[0],b=P[1],w=P[2],b>0&&(o.push(...un(this.skipped_details)),!r))throw new mt(this.skipped_details,o)}catch(P){if(!r)throw this._restore_batch_snapshot(N,C),this._verify_rollback(k),P}x>0&&(this.mapper._build_map(),this.clean_mapper&&this.clean_mapper._build_map());}let[A]=Xe(this.mapper.full_text),D=Ge(A,"").body_page_offsets,j=[],E=0,I=0;if(h.length>0){let P=g($=>$._resolved_start_idx!==void 0&&$._resolved_start_idx!==null?$._resolved_start_idx:$._match_start_index!==void 0&&$._match_start_index!==null?$._match_start_index:null,"pinned_idx"),S=c.map(({c:$,i:O},F)=>({edit:$,i:F,orig_idx:O})).sort(($,O)=>{let F=P($.edit),W=P(O.edit);return F===null&&W===null?$.i-O.i:F===null?1:W===null?-1:W-F||$.i-O.i});{try{let $=[],O=0;for(let{edit:F,orig_idx:W}of S){let L;try{L=this.validate_edits([F],W);}catch(U){if(!(U instanceof Te))throw U;L=[`- Edit ${W+1} Failed: ${U.message}`];}if(L.length>0){let U=L.join(`
112
- `);if(o.push([W,U]),O>0&&!r){let q=ur(O);L=L.map(J=>J+q);}$.push(...L),F&&typeof F=="object"&&(F._error_msg=U);}else if(this.apply_edits([F],D),F._applied_status&&!F._any_sub_failure)O++,this.mapper=new ve(this.doc),this.clean_mapper=null;else {let U=F._error_msg||`- Edit ${W+1} Failed: Failed to apply edit.`;if(F&&typeof F=="object"&&(F._error_msg=U),o.push([W,U]),O>0&&!r&&(U+=ur(O)),$.push(U),!r)break;F._applied_status&&(this.mapper=new ve(this.doc),this.clean_mapper=null);}}if(!r&&$.length>0)throw new mt($,o)}catch($){throw this._restore_batch_snapshot(N,C),this._verify_rollback(k),$}E=h.filter($=>$._applied_status&&!$._any_sub_failure).length,I=h.length-E;for(let $ of h){let O=$._applied_status||false,F=$._error_msg||null,W=null,L=null,U=$._warning||null;if(O){let q=this._build_edit_context_previews($);W=q[0],L=q[1];}else U=U||this._check_punctuation_warning($.target_text||"");j.push({status:O?"applied":"failed",type:$.type||"modify",target_text:de($.target_text||"",Yt),new_text:de(V._report_new_text($),Yt),comment:$.comment??null,warning:U,error:F,critic_markup:W,clean_text:L,pages:$._pages||[],heading_path:$._heading_path||"",occurrences_modified:$._occurrences_modified||0,match_mode:$.match_mode||"strict"});}}}if(E>0)try{this._warn_stranded_comment_anchors(C);}catch{}return {status:r&&o.length>0?"partial":"ok",author_impersonation_warning:i,failed:o.map(([P,S])=>({index:P,reason:S,error:S})),actions_applied:x,actions_skipped:b,actions_already_resolved:w,edits_applied:E,edits_skipped:I,occurrences_modified:j.reduce((P,S)=>P+(S.occurrences_modified||0),0),skipped_details:this.skipped_details,edits:j,engine:"node",version:Zo}}static _flag_surviving_python_backreference(e,n){let r=/\\(\d+)|\\g<(\d+)>/.exec(e.new_text||"");if(!r||!n.includes(r[0]))return;let s=0;try{let o=new RegExp(`(?:${e.target_text})|`).exec("");s=o?o.length-1:0;}catch{return}let i=parseInt(r[1]??r[2],10);i>0&&i<=s&&(e._warning=`new_text contains '${r[0]}', which JavaScript's replace does not expand \u2014 the literal text '${r[0]}' was written into the document. For a capture-group backreference use $${i} (\\N and \\g<N> are Python syntax). If you meant literal text, ignore this warning.`);}static _ids_needed(e){let n=e._internal_op;return n==null&&(!e.target_text&&e.new_text?n="INSERTION":e.target_text&&!e.new_text?n="DELETION":n="MODIFICATION"),n==="STYLE_ONLY"?[false,false]:(n==="STYLE_AND_TEXT"&&(e.target_text&&e.new_text?n="MODIFICATION":!e.target_text&&e.new_text?n="INSERTION":e.target_text&&!e.new_text?n="DELETION":n="COMMENT_ONLY"),[n==="DELETION"||n==="MODIFICATION",n==="INSERTION"||n==="MODIFICATION"])}apply_edits(e,n=[]){if(!n||n.length===0){let[c]=Xe(this.mapper.full_text);n=Ge(c,"").body_page_offsets;}let i=[];for(let c of e){if(typeof c!="object"||c===null){continue}c._applied_status=false,c._error_msg=null,c._any_sub_failure=false,c._minted_change_ids=[],c._minted_comment_ids=[],c._reserved_del_id=null,c._reserved_ins_id=null,c._reserved_row_id=null;}for(let c of e)if(!(typeof c!="object"||c===null))if(c._resolved_start_idx!==void 0&&c._resolved_start_idx!==null||c._match_start_index!==void 0&&c._match_start_index!==null)(c._resolved_start_idx===void 0||c._resolved_start_idx===null)&&(c._resolved_start_idx=c._match_start_index),c._active_mapper_ref||(this.clean_mapper||(this.clean_mapper=new ve(this.doc,true)),c._active_mapper_ref=this.clean_mapper),i.push([c,c.new_text||null]);else if(c.type==="insert_row"||c.type==="delete_row"){let d=this.mapper.drop_virtual_only_matches(this.mapper.find_all_match_indices(c.target_text)),f=this.mapper;if(d.length===0&&(this.clean_mapper||(this.clean_mapper=new ve(this.doc,true)),d=this.clean_mapper.drop_virtual_only_matches(this.clean_mapper.find_all_match_indices(c.target_text)),f=this.clean_mapper),d.length>0){let h=c.match_mode||"strict",_=[],p=new Set;for(let m of d){let y=m[0],[x,b]=f.get_insertion_anchor(y,false),w=null;x?w=x._element:b&&(w=b._element);let v=w;for(;v&&v.tagName!=="w:tr";)v=v.parentNode;v&&(p.has(v)||(p.add(v),_.push(m)));}if(_.length>0){let m=_;if((h==="strict"||h==="first")&&(m=_.slice(0,1)),h==="all"||m.length>1)for(let y of m){let x={...c,_resolved_start_idx:y[0],_active_mapper_ref:f,_parent_edit_ref:c};i.push([x,null]);}else c._resolved_start_idx=m[0][0],c._active_mapper_ref=f,i.push([c,null]);}else {c._applied_status=false;let y=`- Failed to locate row target: '${(c.target_text||"").trim().substring(0,40)}...'`;this.skipped_details.push(y),c._error_msg=y;}}else {c._applied_status=false;let _=`- Failed to locate row target: '${(c.target_text||"").trim().substring(0,40)}...'`;this.skipped_details.push(_),c._error_msg=_;}}else {let d;try{d=this._pre_resolve_heuristic_edit(c);}catch(f){if(!(f instanceof Te))throw f;c._applied_status=false;let h=`- Failed to apply edit targeting: '${(c.target_text||"").substring(0,40)}...' (${f.message})`;this.skipped_details.push(h),c._error_msg=h;continue}if(d)if(Array.isArray(d))for(let f of d)f._resolved_start_idx=f._match_start_index,f._parent_edit_ref=c,(c._resolved_start_idx===void 0||c._resolved_start_idx===null)&&(c._resolved_start_idx=f._resolved_start_idx),c._resolved_proxy_edit||(c._resolved_proxy_edit=f),i.push([f,f.new_text]);else d._resolved_start_idx=d._match_start_index,d._parent_edit_ref=c,c._resolved_start_idx=d._resolved_start_idx,c._resolved_proxy_edit=d,i.push([d,d.new_text]);else {c._applied_status=false;let _=`- Failed to apply edit targeting: '${(c.target_text||"insertion").trim().substring(0,40)}...'`;this.skipped_details.push(_),c._error_msg=_;}}i.sort((c,d)=>(d[0]._resolved_start_idx||0)-(c[0]._resolved_start_idx||0));{let c=[...i].sort((d,f)=>(d[0]._resolved_start_idx||0)-(f[0]._resolved_start_idx||0));for(let[d]of c){let f=d._parent_edit_ref||d;if(Array.isArray(f._minted_change_ids)||(f._minted_change_ids=[]),d.type==="insert_row"||d.type==="delete_row"){d._reserved_row_id==null&&(d._reserved_row_id=this._getNextId(),f._minted_change_ids.push(d._reserved_row_id));continue}if(d.type!=="modify")continue;let[h,_]=V._ids_needed(d);h&&d._reserved_del_id==null&&(d._reserved_del_id=this._getNextId(),f._minted_change_ids.push(d._reserved_del_id)),_&&d._reserved_ins_id==null&&(d._reserved_ins_id=this._getNextId(),f._minted_change_ids.push(d._reserved_ins_id));}}for(let[c]of i)this._capture_preview_context(c),c._parent_edit_ref&&this._capture_parent_preview_context(c._parent_edit_ref);let o=[],l=new Set;for(let[c,d]of i){let f=c._resolved_start_idx||0,h=c.type==="insert_row"?f:f+(c.target_text?c.target_text.length:0);if(o.some(([x,b])=>f<b&&h>x)){let w=`- Skipped overlapping edit targeting: '${(c.target_text||"insertion").trim().substring(0,40)}...'`;this.skipped_details.push(w),c._applied_status=false,c._error_msg=w,c._any_sub_failure=true;let v=c._parent_edit_ref;v&&(v._applied_status=false,v._error_msg=w,v._any_sub_failure=true);continue}let p=false,m=this.current_id,y=this.comments_manager.nextId;if(c.type==="modify"?p=this._apply_single_edit_indexed(c,d,false):(c.type==="insert_row"||c.type==="delete_row")&&(p=this._apply_table_edit(c,false)),p){let x=c._parent_edit_ref||c;Array.isArray(x._minted_change_ids)||(x._minted_change_ids=[]);for(let b=m+1;b<=this.current_id;b++)x._minted_change_ids.push(String(b));Array.isArray(x._minted_comment_ids)||(x._minted_comment_ids=[]);for(let b=y;b<this.comments_manager.nextId;b++)x._minted_comment_ids.push(String(b));}if(p){let x=c._split_group_id,b=x==null||!l.has(x);b&&x!==void 0&&x!==null&&l.add(x),o.push([f,h]),c._applied_status=true;let w=c._parent_edit_ref;if(w){w._applied_status=true,b&&(w._occurrences_modified=(w._occurrences_modified||0)+1);let[v,N]=this._get_heading_path_and_page(f,this.mapper.full_text,n),k=w._pages||[];k.includes(N)||k.unshift(N),w._pages=k,w._heading_path=v;}else {b&&(c._occurrences_modified=(c._occurrences_modified||0)+1);let[v,N]=this._get_heading_path_and_page(f,this.mapper.full_text,n),k=c._pages||[];k.includes(N)||k.unshift(N),c._pages=k,c._heading_path=v;}}else {let w=`- Failed to apply edit targeting: '${(c.target_text||"insertion").trim().substring(0,40)}...'`;this.skipped_details.push(w),c._applied_status=false,c._error_msg=w,c._any_sub_failure=true;let v=c._parent_edit_ref;v&&(v._any_sub_failure=true,v._applied_status||(v._applied_status=false,v._error_msg=w));}}let a=0,u=0;for(let c of e){if(typeof c!="object"||c===null){u++;continue}c._applied_status&&!c._any_sub_failure?a++:u++;}return [a,u]}_paragraph_has_visible_content(e){for(let n of ["w:t","w:tab","w:br"]){let r=M(e,n);for(let s of r){let i=false,o=s.parentNode;for(;o&&o!==e.parentNode;){if(o.tagName==="w:del"){i=true;break}o=o.parentNode;}if(!i){if(n==="w:t"&&!s.textContent)continue;return true}}}return false}_is_last_paragraph_in_cell(e){let n=e.parentNode;for(;n&&n.tagName!=="w:tc";)n=n.parentNode;return n?M(n,"w:p").length<=1:false}_get_paired_nodes(e){let n=[],r=e.getAttribute("w:author"),s=new Set(["w:commentRangeStart","w:commentRangeEnd","w:commentReference","w:rPr","w:pPr"]),i=new Set,o=g(d=>{let f=d.getAttribute("w:id");f&&i.add(f);},"add_id");o(e);let l=g(d=>{let f=d;for(;f&&f.tagName!=="w:p";)f=f.parentNode;return f},"paragraph_of"),a=g(d=>{let f=B(d,"w:pPr"),h=f?B(f,"w:rPr"):null;return h?B(h,"w:ins"):null},"mark_of"),u=g(d=>{let f=a(d);if(!f||f.getAttribute("w:author")!==r)return false;let h=f.getAttribute("w:id");return h!==null&&i.has(h)},"boundary_is_ours"),c=g((d,f)=>{let h=l(d),_=f==="next"?d.nextSibling:d.previousSibling;for(;;){if(!_){if(!h)break;if(f==="next"){let m=xe(h);for(;m&&m.tagName!=="w:p";)m=xe(m);if(!m||!u(m))break;h=m,_=m.firstChild;}else {if(!u(h))break;let m=Ae(h);for(;m&&m.tagName!=="w:p";)m=Ae(m);if(!m)break;h=m,_=m.lastChild;}continue}if(_.nodeType!==1){_=f==="next"?_.nextSibling:_.previousSibling;continue}let p=_;if(s.has(p.tagName)){_=f==="next"?_.nextSibling:_.previousSibling;continue}if((p.tagName==="w:ins"||p.tagName==="w:del")&&p.getAttribute("w:author")===r){n.push(p),o(p),_=f==="next"?_.nextSibling:_.previousSibling;continue}break}},"walk");return c(e,"next"),c(e,"prev"),n}_resolution_group_ids(e){let n=[...M(this.doc.element,"w:ins"),...M(this.doc.element,"w:del")].filter(s=>s.getAttribute("w:id")===e),r=new Set;if(n.length===0)return M(this.doc.element,"w:pPrChange").some(i=>i.getAttribute("w:id")===e)&&r.add(e),r;r.add(e);for(let s of n)for(let i of this._get_paired_nodes(s)){let o=i.getAttribute("w:id");o&&r.add(o);}return r}validate_action_pairing(e,n){let r=[],s=g(o=>n?n[o]:o,"gidx"),i=new Map;for(let o=0;o<e.length;o++){let l=e[o];if(l.type!=="accept"&&l.type!=="reject")continue;let a=String(l.target_id??"");if(a.startsWith("Com:"))continue;let u=a.startsWith("Chg:")?a.slice(4):a,c=this._resolution_group_ids(u);if(c.size===0)continue;let d=null;for(let f of c){let h=i.get(f);if(h!==void 0&&h[1]!==l.type){d=h;break}}if(d!==null){let[f,h,_]=d;r.push(`- Action ${s(o)+1} Failed: conflicting actions on one replacement \u2014 Action ${s(f)+1} applies '${h}' to Chg:${_}, and Chg:${u} is part of the same change (a replacement's contiguous del+ins pair resolves as one unit, so '${h}' already decides both sides). Accepting one side and rejecting the other is contradictory \u2014 decide the outcome and submit exactly one action for the pair.`);continue}for(let f of c)i.has(f)||i.set(f,[o,l.type,u]);}return r}_buildRevisionIndex(e,n){let r=new Map;for(let u of Kt)r.set(u,[]);let i=[this.doc.element],o=[0],l=[],a=[];for(;i.length;){let u=i.length-1,c=i[u].childNodes;if(!c||o[u]>=c.length){for(i.pop(),o.pop();a.length&&a[a.length-1]>i.length;)a.pop(),l.pop();continue}let d=c[o[u]++];if(d.nodeType!==1)continue;let f=r.get(d.tagName),h=null;f&&(h={el:d,id:d.getAttribute("w:id"),nested:[]},f.push(h));let _=d.tagName==="w:ins"||d.tagName==="w:del";if(h&&_)for(let p of l)p.nested.push(h);i.push(d),o.push(0),h&&_&&(l.push(h),a.push(i.length));}return {doc:e,inc:n,byTag:r}}_getRevisionIndex(){let e=this.doc.element.ownerDocument,n=typeof e?._inc=="number"?e._inc:null,r=this._revisionIndex;if(r&&r.doc===e&&n!==null&&r.inc===n)return r;let s=this._buildRevisionIndex(e,n);return this._revisionIndex=s,s}_revisionsByTag(e){return this._getRevisionIndex().byTag.get(e)??[]}_existing_change_ids(){let e=new Set;for(let n of Kt)for(let r of this._revisionsByTag(n))r.id&&e.add(r.id);return Array.from(e).sort((n,r)=>{let s=/^\d+$/.test(n)?parseInt(n,10):0,i=/^\d+$/.test(r)?parseInt(r,10):0;return s-i||n.localeCompare(r)})}_warn_stranded_comment_anchors(e){let n;try{n=M(this.doc.element,"w:commentRangeStart");}catch{return}if(n.length===0)return;let r=g(a=>{let u=new Map,c=0,d=g(f=>{u.set(f,c++);for(let h=f.firstChild;h;h=h.nextSibling)h.nodeType===1&&d(h);},"walk");return d(a),u},"order"),s=g(a=>{let u=a.parentNode;for(;u&&u.nodeType===1;){if(u.tagName==="w:p")return u;u=u.parentNode;}return null},"paragraphOf"),i=g((a,u)=>{let c=a.parentNode;for(;c&&c.nodeType===1&&c!==u;){if(c.tagName==="w:del")return true;c=c.parentNode;}return false},"hasDeletedAncestorWithin"),o=null,l=[];for(let a of n){let u=a.getAttribute("w:id");if(!u)continue;let c=s(a);if(!c)continue;let d=M(c,"w:commentRangeEnd").find(b=>b.getAttribute("w:id")===u);if(!d)continue;let f=r(c),h=f.get(a),_=f.get(d);if(h===void 0||_===void 0||_<h)continue;let p="";for(let b of M(c,"w:t")){let w=f.get(b);w===void 0||w<h||w>_||i(b,c)||(p+=b.textContent||"");}if(!p.trim())continue;let m=false,y=false,x=false;for(let b of M(c,"w:del")){let w=f.get(b);if(w===void 0)continue;let v=w<h?"before":w>_?"after":null;if(!v||!M(b,"w:delText").some(C=>(C.textContent||"").trim()))continue;v==="before"?m=true:y=true;let k=b.getAttribute("w:id")||"";/^\d+$/.test(k)&&parseInt(k,10)>e&&(x=true);}m&&y&&x&&(o===null&&(o=this._comment_authors()),l.push([u,p.trim()]));}for(let[a,u]of l){let c=o?.[a],d=c?`comment Com:${a} (by ${c})`:`comment Com:${a}`;this.skipped_details.push(`- Warning: this batch deleted text on both sides of ${d} but left its anchored text "${de(u,60)}" in place, so once the changes are accepted that text stands alone in its sentence. If you kept it to preserve the comment's anchor, re-read the sentence; if you meant to remove the clause, extend one edit over the anchored text too. The edits themselves were applied.`);}}existing_change_ids(){return this._existing_change_ids()}_existing_comment_ids(){let e=[];try{e=Object.keys(Pe(this.doc.pkg));}catch{e=[];}return e.sort((n,r)=>{let s=/^\d+$/.test(n)?parseInt(n,10):0,i=/^\d+$/.test(r)?parseInt(r,10):0;return s-i||n.localeCompare(r)})}_comment_authors(){let e={};try{for(let[n,r]of Object.entries(Pe(this.doc.pkg)))e[n]=r?.author||"Unknown";}catch{}return e}static _describe_removed_comments(e,n){let r=[...e].sort((i,o)=>{let l=/^\d+$/.test(i)?parseInt(i,10):0,a=/^\d+$/.test(o)?parseInt(o,10):0;return l-a||i.localeCompare(o)}),s=r.map(i=>n[i]?`Com:${i} (by ${n[i]})`:`Com:${i}`).join(", ");return `${r.length===1?"comment":"comments"} ${s}`}static _format_id_list(e,n,r=20){let s=e.slice(0,r),i=s.map(o=>`${n}${o}`).join(", ");return e.length>s.length&&(i+=`, \u2026 (+${e.length-s.length} more)`),i}_action_not_found_error(e,n,r="- Failed to apply action:"){let s=this._existing_change_ids(),i=this._existing_comment_ids(),o=e.startsWith("Chg:")||e.startsWith("Com:"),l=e.replace(/^(Chg:|Com:)/,""),a=this.id_discovery_hint||"Call `read_docx` with `mode='changes'` on the document again to list the current change (Chg:) and comment (Com:) ids \u2014 ids shift between document states.";if(n==="reply"){let d=o?e:`Com:${l}`;if(s.includes(l))return `${r} reply on ${d} \u2014 Chg:${l} is a tracked-change id, not a comment. \`reply\` adds to an existing comment thread (Com:\u2026); to comment on a change instead, apply a modify with a \`comment\`. ${a}`;let f=i.length>0?`Comment ids in this document: ${V._format_id_list(i,"Com:")}. `:"This document has no comments to reply to. ";return `${r} reply on ${d} \u2014 no comment with that id exists. ${f}${a}`}let u=o?e:`Chg:${l}`;if(i.includes(l))return `${r} ${n} on ${u} \u2014 Com:${l} is a comment id, not a tracked change. accept/reject act on tracked changes (Chg:\u2026); to respond to a comment use \`reply\`. ${a}`;let c=s.length>0?`Tracked-change ids in this document: ${V._format_id_list(s,"Chg:")}. `:"This document has no tracked changes. ";return `${r} ${n} on ${u} \u2014 no tracked change with that id exists (it may already have been accepted or rejected, or the id is stale). ${c}${a}`}apply_review_actions(e,n){let r=g(u=>n?n[u]:u,"gidx"),s=0,i=0,o=0,l=new Map,a=e.map((u,c)=>({action:u,pos:c})).sort((u,c)=>{let d=u.action.type==="reply"?0:1,f=c.action.type==="reply"?0:1;return d!==f?d-f:u.pos-c.pos});for(let{action:u,pos:c}of a){let d=u.type;if(d==="reply"){let E=u.target_id.replace("Com:","");if(!this._existing_comment_ids().includes(E)){i++,this.skipped_details.push(this._action_not_found_error(u.target_id,"reply",`- Action ${r(c)+1} Failed:`));continue}let I;try{I=this.comments_manager.addComment(this.author,u.text,E);}catch(P){if(P instanceof Or){i++,this.skipped_details.push(`- Action ${r(c)+1} Failed: reply on ${u.target_id} \u2014 ${P.message}`);continue}throw P}this._anchor_reply_comment(E,I),s++;continue}let f=u.target_id.replace("Chg:",""),h=l.get(f);if(h!==void 0){if(h===d){o++,this.skipped_details.push(`- Note: Action ${r(c)+1} ('${d}' on ${u.target_id}) had no additional effect \u2014 the change was already resolved together with its replacement pair by an earlier action in this batch. Counted as already_resolved, not applied.`);continue}this.skipped_details.push(`- Action ${r(c)+1} Failed: contradictory action \u2014 '${d}' on ${u.target_id}, but the change was already resolved as '${h}' together with its replacement pair by an earlier action in this batch.`),i++;continue}let _=this._revisionsByTag("w:ins").filter(E=>E.id===f).map(E=>E.el),p=this._revisionsByTag("w:del").filter(E=>E.id===f).map(E=>E.el),m=[..._,...p],y=fn.flatMap(E=>this._revisionsByTag(E).filter(I=>I.id===f).map(I=>I.el));if(m.length===0&&y.length===0){i++,this.skipped_details.push(this._action_not_found_error(u.target_id,d,`- Action ${r(c)+1} Failed:`));continue}let x=Array.from(new Set([...m,...y].map(E=>E.getAttribute("w:author")||"Unknown"))).sort();if(x.length>1){i++,this.skipped_details.push(`- Failed to apply action: ${d} on Chg:${f} is ambiguous. The document contains ${m.length} tracked-change elements sharing w:id=${f} from different authors (${x.join(", ")}) \u2014 duplicate revision IDs produced outside this engine (e.g. by a document merge or copy-paste). Acting on this ID would resolve all of them at once. Resolve these changes individually in Word, or apply the intended outcome as an explicit text edit instead.`);continue}let b=new Set([f]);for(let E of m)for(let I of this._get_paired_nodes(E)){let P=I.getAttribute("w:id");P&&b.add(P);}let w=dn.flatMap(E=>this._revisionsByTag(E)),v=-1;for(;v!==b.size;){v=b.size;for(let E of w)if(!(!E.id||!b.has(E.id)))for(let I of E.nested)I.id&&b.add(I.id);}let N=[];for(let E of dn)for(let I of this._revisionsByTag(E))I.id&&b.has(I.id)&&N.push(I.el);let k=fn.flatMap(E=>this._revisionsByTag(E).filter(I=>I.id!==null&&b.has(I.id)).map(I=>I.el)),C=(()=>{let E=m[0]??y[0]??null;for(;E;){if(E.nodeType===1&&E.tagName==="w:p")return E;E=E.parentNode;}return null})(),A=new Set;for(let E of [...N,...k]){let I=E.getAttribute("w:id");I&&A.add(I);}let T=this._comment_authors(),D=new Set(Object.keys(T)),j=[];for(let E of N){let I=E.tagName==="w:ins",P=E.parentNode?E.parentNode.tagName:"",S=P==="w:trPr",$=I&&P==="w:rPr"&&!!E.parentNode?.parentNode&&E.parentNode.parentNode.tagName==="w:pPr";if(d==="accept")if(I)if(S)E.parentNode?.removeChild(E);else {for(;E.firstChild;)E.parentNode?.insertBefore(E.firstChild,E);E.parentNode?.removeChild(E);}else if(this._clean_wrapping_comments(E),this._delete_comments_in_element(E),S){let O=E.parentNode?.parentNode;O?.parentNode?.removeChild(O);}else E.parentNode?.removeChild(E);else if(d==="reject")if(I){if($){let O=E.parentNode;E.parentNode?.removeChild(E),O=O?.parentNode,O=O?.parentNode,O&&O.tagName==="w:p"&&j.push(O);continue}if(this._clean_wrapping_comments(E),this._delete_comments_in_element(E),S){let O=E.parentNode?.parentNode;O?.parentNode?.removeChild(O);}else E.parentNode?.removeChild(E);}else if(S)E.parentNode?.removeChild(E);else {let O=Array.from(E.getElementsByTagName("w:delText"));for(let F of O){let W=F.ownerDocument.createElement("w:t");W.textContent=F.textContent,F.hasAttribute("xml:space")&&W.setAttribute("xml:space","preserve"),F.parentNode?.replaceChild(W,F);}for(;E.firstChild;)E.parentNode?.insertBefore(E.firstChild,E);E.parentNode?.removeChild(E);}}for(let E of j.reverse()){if(!E.parentNode)continue;let I=Ae(E);for(;I&&I.tagName!=="w:p";)I=Ae(I);if(I){for(let P of Array.from(E.childNodes))P.nodeType===1&&P.tagName==="w:pPr"||I.appendChild(P);E.parentNode.removeChild(E);}}for(let E of k)d==="accept"?E.parentNode?.removeChild(E):E.tagName==="w:pPrChange"?this._revert_ppr_change(E):this._revert_props_change(E);for(let E of A)l.set(E,d);if(s++,D.size>0){let E=new Set(this._existing_comment_ids()),I=Array.from(D).filter(P=>!E.has(P));I.length>0&&this.skipped_details.push(`- Note: ${d} on ${u.target_id} also removed ${V._describe_removed_comments(I,T)} (including any reply thread) because its anchor was inside the resolved change. This note is informational \u2014 the action itself succeeded.`);}if(u.comment&&String(u.comment).trim()){let E=r(c)+1,I=C?Array.from(C.childNodes).find(P=>P.tagName==="w:r")??null:null;if(C&&I){let P=this._attach_comment(C,I,I,String(u.comment));P&&this.skipped_details.push(`- Note: Action ${E} ('${d}' on ${u.target_id}) \u2014 rationale recorded as Com:${P}.`);}else this.skipped_details.push(`- Note: Action ${E} ('${d}' on ${u.target_id}) \u2014 the rationale could not be anchored (the resolved text left no surviving run); the ${d} itself succeeded.`);}}return [s,i,o]}_apply_table_edit(e,n){let r=e._resolved_start_idx!==void 0&&e._resolved_start_idx!==null?e._resolved_start_idx:e._match_start_index||0,s=e._active_mapper_ref||this.mapper,[i,o]=s.get_insertion_anchor(r,n),l=null;if(i?l=i._element:o&&(l=o._element),!l)return false;let a=l;for(;a&&a.tagName!=="w:tr";)a=a.parentNode;if(!a)return false;let u=(e._reserved_row_id??null)!==null?String(e._reserved_row_id):null;if(e.type==="delete_row"){let c=B(a,"w:trPr");return c||(c=a.ownerDocument.createElement("w:trPr"),a.insertBefore(c,a.firstChild)),c.appendChild(this._create_track_change_tag("w:del","",u)),true}else if(e.type==="insert_row"){let c=a.ownerDocument.createElement("w:tr"),d=a.ownerDocument.createElement("w:trPr");c.appendChild(d),d.appendChild(this._create_track_change_tag("w:ins","",u));let f=M(a,"w:tc").filter(_=>_.parentNode===a).length,h=Array.isArray(e.cells)?[...e.cells]:[];if(f>0){for(;h.length<f;)h.push("");h=h.slice(0,f);}for(let _ of h){let p=a.ownerDocument.createElement("w:tc"),m=a.ownerDocument.createElement("w:p"),y=a.ownerDocument.createElement("w:r"),x=a.ownerDocument.createElement("w:t");x.textContent=_,_.trim()!==_&&x.setAttribute("xml:space","preserve"),y.appendChild(x),m.appendChild(y),p.appendChild(m),c.appendChild(p);}return e.position==="above"?a.parentNode?.insertBefore(c,a):qe(c,a),true}return false}_match_spans_whole_paragraph(e,n,r){let s=n+r,i=new Map;for(let o of e.spans){if(o.paragraph===null||o.paragraph===void 0||o.run===null&&o.text===`
137
+ `);T.length>=2&&T[0].trim()!==""&&T[T.length-1].trim()!==""&&r.push(`- Edit ${i+1+n} Failed: target_text spans a paragraph boundary with body text on both sides. The paragraph break is a structural element, not literal text, so it cannot be replaced as a single span without corrupting the document. Split this into one edit per paragraph.`);}}for(let[h,_]of l){let p=c.spans.filter(b=>b.end>h&&b.start<h+_),m=new Map,w=new Map,v=false;for(let b of p){if(b.run===null)continue;let y=false;if(b.ins_id){let x=R(this.doc.element,"w:ins").filter(k=>k.getAttribute("w:id")===b.ins_id);if(x.length>0){let k=x[0].getAttribute("w:author");k&&k!==this.author&&(m.has(k)||m.set(k,new Set),m.get(k).add(b.ins_id),y=true);}}y||(v=true);}for(let b of p)if(b.comment_ids)for(let y of b.comment_ids){let x=this.mapper.comments_map[y];x&&x.author&&x.author!==this.author&&(w.has(x.author)||w.set(x.author,new Set),w.get(x.author).add(`Com:${y}`));}if(m.size>0){let b=!v;if(!((a==="strict"||a==="first")&&b)){let y=Array.from(m.keys()).sort(),x=y[0],N=Array.from(m.get(x)).sort((E,S)=>{let D=/^\d+$/.test(E)?parseInt(E,10):0,U=/^\d+$/.test(S)?parseInt(S,10):0;return D!==U?D-U:E.localeCompare(S)}),P=N.length>0?`Chg:${N[0]}`:null,A=N.slice(0,2).map(E=>`Chg:${E}`).join(", "),C=A?` (e.g. ${A})`:"";y.length>1&&(C+=` (+${y.length-1} more)`);let T=P?`{"type": "accept", "target_id": "${P}"}`:"",M=a==="all"&&b?'or use match_mode="strict" or "first", or scope your edit outside of it.':"or scope your edit outside of it.",j=`- Edit ${i+1+n} Failed: Modification targets an active insertion from another author (`,B=`${C}). Accept first with ${T} ${M}`,$=gi-j.length-B.length,I=j+Fr(x,$)+B;r.push(Fr(I,gi));continue}}if(w.size>0&&a==="all"){let b=[],y=Array.from(w.keys()).sort();for(let x of y){let P=Array.from(w.get(x)).sort((A,C)=>{let T=A.split(":").pop()||"",M=C.split(":").pop()||"",j=/^\d+$/.test(T)?parseInt(T,10):0,B=/^\d+$/.test(M)?parseInt(M,10):0;return j!==B?j-B:A.localeCompare(C)}).join(", ");b.push(P?`${x} (e.g. ${P})`:x);}r.push(`- Edit ${i+1+n} Failed: match_mode="all" would sweep through a comment range from another author (${b.join(", ")}). Target the commented text deliberately with match_mode "strict" or "first", or scope your edit outside of it.`);}}if((o.type==="insert_row"||o.type==="delete_row")&&l.length>0){let[h,_]=l[0],p=Z._column_count_at(c,h,_);p===null?r.push(`- Edit ${i+1+n} Failed: ${o.type} target text was found, but it is not inside a table row. Anchor the operation on text that appears within the table.`):o.type==="insert_row"&&Array.isArray(o.cells)&&o.cells.length>p&&r.push(`- Edit ${i+1+n} Failed: insert_row provides ${o.cells.length} cells but the target table has ${p} column(s). The extra cell(s) would be dropped. Provide at most ${p} cells \u2014 rows given fewer cells are padded with empty ones.`);}}return r}static _introduces_table_row_text(e,n,r,i,o){if(!o.includes(`
138
+ `)||!o.includes(" | "))return false;let s=o.split(`
139
+ `).filter(l=>l.includes(" | ")).length,a=i.split(`
140
+ `).filter(l=>l.includes(" | ")).length;return s<=a?false:Z._column_count_at(e,n,Math.max(r,1))!==null}static _column_count_at(e,n,r){for(let i of e.spans){if(i.end<=n||i.start>=n+r)continue;let o=null;for(i.run!==null?o=i.run._element:i.paragraph!==null&&(o=i.paragraph._element);o;){if(o.nodeType===1&&o.tagName==="w:tr")return R(o,"w:tc").filter(s=>s.parentNode===o).length;o=o.parentNode;}}return null}validate_review_actions(e,n,r=false){let i=[],o=g(l=>n?n[l]:l,"gidx"),s=new Map,a=new Set;for(let l=0;l<e.length;l++){let u=e[l],c=u.type,d=u.target_id??"";if(c==="reply"){if(!String(u.text??"").trim()){i.push(`- Action ${o(l)+1} Failed: reply text for ${d} is empty or whitespace-only. Word would show a blank comment bubble \u2014 provide the reply content in 'text'.`);continue}let f=d+"\0"+String(u.text).trim();a.has(f)&&i.push(`- Action ${o(l)+1} Failed: duplicate reply \u2014 this batch already replies to ${d} with the same text. Remove the duplicate action.`),a.add(f);}else if(c==="accept"||c==="reject"){let{part:f}=this._action_part_filter(u),h=`${f??""}\0${d}`,_=s.get(h);if(_!==void 0){let[p,m]=_;m===c?i.push(`- Action ${o(l)+1} Failed: duplicate action \u2014 Action ${o(p)+1} in this batch already applies '${c}' to ${d}. A change can only be resolved once; remove the duplicate action.`):i.push(`- Action ${o(l)+1} Failed: conflicting actions \u2014 Action ${o(p)+1} in this batch applies '${m}' to ${d}, but this action applies '${c}'. Decide the outcome and keep exactly one of them.`);}else s.set(h,[l,c]);}}if(i.length>0||r)return i;for(let l=0;l<e.length;l++){let u=e[l],c=u.type;if(c==="reply"){let d=u.target_id.replace("Com:",""),f=false,h=this.doc.pkg.parts.find(_=>_.contentType==="application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");h&&(f=R(h._element,"w:comment").some(p=>p.getAttribute("w:id")===d)),f||i.push(this._action_not_found_error(u.target_id,"reply",`- Action ${o(l)+1} Failed:`));}else if(c==="accept"||c==="reject"){let d=u.target_id.replace("Chg:",""),{part:f,error:h}=this._action_part_filter(u);if(h){i.push(`- Action ${o(l)+1} Failed: ${c} on ${u.target_id} \u2014 ${h}`);continue}let _=false;for(let p of ["w:ins","w:del","w:pPrChange"])if(this._revisionsByTagIn(p,f).some(m=>m.id===d)){_=true;break}_||i.push(f!==null?this._not_found_in_part_error(u.target_id,c,f,`- Action ${o(l)+1} Failed:`):this._action_not_found_error(u.target_id,c,`- Action ${o(l)+1} Failed:`));}}return i}get_pending_revision_authors(){let e=new Set,n=g(r=>{if(r)try{if(typeof r.getAttribute=="function"){let o=r.getAttribute("w:author");o&&e.add(o);}let i=R(r,"*");for(let o of i){let s=o.getAttribute("w:author");s&&e.add(s);}}catch{}},"collect");try{this.doc?.element&&n(this.doc.element);}catch{}try{if(this.doc?.pkg){let r=Me(this.doc.pkg);for(let i of Object.values(r)){let o=i?.author;o&&o!=="Unknown"&&e.add(o);}}}catch{}try{let r=this.doc?.pkg?.parts||[];for(let i of r){if(i===this.doc?.part||!String(i.contentType||"").endsWith("+xml"))continue;let o=String(i.partname||"").toLowerCase();if(!(String(i.contentType||"")==="application/vnd.ms-word.people+xml"||o.includes("people")))try{let a=i._element;!a&&i.blob&&(a=Xe(i.blob)),a&&n(a);}catch{}}}catch{}return e}process_batch(e,n,r=false){return Array.isArray(e)&&(e=e.map(i=>{if(typeof i=="string")try{let o=JSON.parse(i);return o!==null&&typeof o=="object"?o:i}catch{return i}return i})),this._process_batch_internal(e,n,r)}_batch_fingerprint(){let e=0,n=new Set;for(let r of Lt)for(let i of this._revisionsByTag(r))e++,i.id&&n.add(i.id);return [e,[...n].sort().join(","),this._existing_comment_ids().join(",")].join("|")}_restore_batch_snapshot(e,n){e&&(yu(this.doc,e),this.current_id=n,this.mapper=new ke(this.doc),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.comments_manager=new Et(this.doc),this.clean_mapper=null,this._revisionIndex=null);}_verify_rollback(e){if(e!==null)try{this.rollback_verified=this._batch_fingerprint()===e;}catch{this.rollback_verified=false;}}_process_batch_internal(e,n,r=false){this.rollback_verified=true;let i=this.get_pending_revision_authors(),o=this.author&&i.has(this.author)?`[!] Warning: acting author '${this.author}' matches an author with pending revisions in this document.`:null;for(let $ of e)if($&&typeof $=="object"&&$.type==="modify"&&$.target_text&&$.new_text){let[I,E]=vu($.target_text,$.new_text);$.target_text=I,$.new_text=E;}this.skipped_details=[],this._overridden_controls=[];let s=[],a=g($=>n?n[$]:$,"idx_of"),l=g($=>$!==null&&typeof $=="object"&&["accept","reject","reply"].includes($.type),"is_action"),u=e.map(($,I)=>({c:$,i:a(I)})).filter(({c:$})=>l($)),c=e.map(($,I)=>({c:$,i:a(I)})).filter(({c:$})=>!l($)),d=u.map(({c:$})=>$),f=u.map(({i:$})=>$),h=c.map(({c:$})=>$),_=[];for(let $=0;$<d.length;$++){let I=ic(f[$]+1,d[$]?.type??"",this.protection,this.gate_overrides);I&&_.push(I);}_.length===0&&(_=d.length>0?this.validate_review_actions(d,f,r):[]),d.length>0&&_.length===0&&(_=this.validate_action_pairing(d,f));let p=h.length>0&&_.length>0,m=[];if(p)for(let{c:$,i:I}of c){let E=this.validate_edits([$],I);E.length>0&&(m.push(...E),s.push([I,E.join(`
141
+ `)]));}let w=[..._,...m];if(w.length>0)throw s.unshift(...Xn(_)),new Wt(w,s);let v=0,b=0,y=0,k=d.length>0||h.length>0?wu(this.doc):null,N=d.length>0?this._batch_fingerprint():null,P=this.current_id;if(d.length>0){try{let $=this.apply_review_actions(d,f);if(v=$[0],b=$[1],y=$[2],b>0&&(s.push(...Xn(this.skipped_details)),!r))throw new Wt(this.skipped_details,s)}catch($){if(!r)throw this._restore_batch_snapshot(k,P),this._verify_rollback(N),$}v>0&&(this.mapper._build_map(),this.clean_mapper&&this.clean_mapper._build_map());}let[A]=ot(this.mapper.full_text),T=st(A,"").body_page_offsets,M=[],j=0,B=0;if(h.length>0){let $=g(E=>E._resolved_start_idx!==void 0&&E._resolved_start_idx!==null?E._resolved_start_idx:E._match_start_index!==void 0&&E._match_start_index!==null?E._match_start_index:null,"pinned_idx"),I=c.map(({c:E,i:S},D)=>({edit:E,i:D,orig_idx:S})).sort((E,S)=>{let D=$(E.edit),U=$(S.edit);return D===null&&U===null?E.i-S.i:D===null?1:U===null?-1:U-D||E.i-S.i});{try{let E=[],S=0;for(let{edit:D,orig_idx:U}of I){let z;try{z=this.validate_edits([D],U);}catch(W){if(!(W instanceof je))throw W;z=[`- Edit ${U+1} Failed: ${W.message}`];}if(z.length>0){let W=z.join(`
142
+ `);if(s.push([U,W]),S>0&&!r){let L=wi(S);z=z.map(X=>X+L);}E.push(...z),D&&typeof D=="object"&&(D._error_msg=W);}else if(this.apply_edits([D],T),D._applied_status&&!D._any_sub_failure)S++,this.mapper=new ke(this.doc),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.clean_mapper=null;else {let W=D._error_msg||`- Edit ${U+1} Failed: Failed to apply edit.`;if(D&&typeof D=="object"&&(D._error_msg=W),s.push([U,W]),S>0&&!r&&(W+=wi(S)),E.push(W),!r)break;D._applied_status&&(this.mapper=new ke(this.doc),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.clean_mapper=null);}}if(!r&&E.length>0)throw new Wt(E,s)}catch(E){throw this._restore_batch_snapshot(k,P),this._verify_rollback(N),E}j=h.filter(E=>E._applied_status&&!E._any_sub_failure).length,B=h.length-j;for(let E of h){let S=E._applied_status||false,D=E._error_msg||null,U=null,z=null,W=E._warning||null;if(S){let L=this._build_edit_context_previews(E);U=L[0],z=L[1];}else W=W||this._check_punctuation_warning(E.target_text||"");M.push({status:S?"applied":"failed",type:E.type||"modify",target_text:de(E.target_text||"",Sn),new_text:de(Z._report_new_text(E),Sn),comment:E.comment??null,warning:W,error:D,critic_markup:U,clean_text:z,pages:E._pages||[],heading_path:E._heading_path||"",field:E._field||"",occurrences_modified:E._occurrences_modified||0,match_mode:E.match_mode||"strict"});}}}if(j>0)try{this._warn_stranded_comment_anchors(P);}catch{}return {status:r&&s.length>0?"partial":"ok",author_impersonation_warning:o,overrides_note:dc(this.gate_overrides,this._overridden_controls),failed:s.map(([$,I])=>({index:$,reason:I,error:I})),actions_applied:v,actions_skipped:b,actions_already_resolved:y,edits_applied:j,edits_skipped:B,occurrences_modified:M.reduce(($,I)=>$+(I.occurrences_modified||0),0),skipped_details:this.skipped_details,edits:M,engine:"node",version:kl}}static _flag_surviving_python_backreference(e,n){let r=/\\(\d+)|\\g<(\d+)>/.exec(e.new_text||"");if(!r||!n.includes(r[0]))return;let i=0;try{let s=new RegExp(`(?:${e.target_text})|`).exec("");i=s?s.length-1:0;}catch{return}let o=parseInt(r[1]??r[2],10);o>0&&o<=i&&(e._warning=`new_text contains '${r[0]}', which JavaScript's replace does not expand \u2014 the literal text '${r[0]}' was written into the document. For a capture-group backreference use $${o} (\\N and \\g<N> are Python syntax). If you meant literal text, ignore this warning.`);}static _ids_needed(e){let n=e._internal_op;return n==null&&(!e.target_text&&e.new_text?n="INSERTION":e.target_text&&!e.new_text?n="DELETION":n="MODIFICATION"),n==="STYLE_ONLY"?[false,false]:(n==="STYLE_AND_TEXT"&&(e.target_text&&e.new_text?n="MODIFICATION":!e.target_text&&e.new_text?n="INSERTION":e.target_text&&!e.new_text?n="DELETION":n="COMMENT_ONLY"),[n==="DELETION"||n==="MODIFICATION",n==="INSERTION"||n==="MODIFICATION"])}apply_edits(e,n=[]){let i=0;if(!n||n.length===0){let[c]=ot(this.mapper.full_text);n=st(c,"").body_page_offsets;}let o=[];for(let c of e){if(typeof c!="object"||c===null){i++;continue}c._applied_status=false,c._error_msg=null,c._any_sub_failure=false,c._minted_change_ids=[],c._minted_comment_ids=[],c._reserved_del_id=null,c._reserved_ins_id=null,c._reserved_row_id=null;}for(let c of e)if(!(typeof c!="object"||c===null)){if(c.type==="set_field"){this._resolve_set_field(c,o),c._error_msg&&(i+=1);continue}if(c._resolved_start_idx!==void 0&&c._resolved_start_idx!==null||c._match_start_index!==void 0&&c._match_start_index!==null){if((c._resolved_start_idx===void 0||c._resolved_start_idx===null)&&(c._resolved_start_idx=c._match_start_index),c.type==="modify"&&!c._internal_op&&c.target_text&&c.new_text&&([c.target_text,c.new_text]=yi(c.target_text,c.new_text)),c._active_mapper_ref||(this.clean_mapper||(this.clean_mapper=new ke(this.doc,true)),c._active_mapper_ref=this.clean_mapper),c.type==="modify"&&!c.target_text&&c.new_text&&!c._insert_host_el){let d=this._empty_control_fill_host(c._active_mapper_ref,c._resolved_start_idx??0);d&&(c._insert_host_el=d);}o.push([c,c.new_text||null]);}else if(c.type==="insert_row"||c.type==="delete_row"){let{sub_edits:d,err_msg:f}=this._resolve_structural_table_edit(c);f?(i++,c._applied_status=false,this.skipped_details.push(f),c._error_msg=f):o.push(...d);}else {let d;try{d=this._pre_resolve_heuristic_edit(c);}catch(f){if(!(f instanceof je))throw f;i++,c._applied_status=false;let h=`- Failed to apply edit targeting: '${(c.target_text||"").substring(0,40)}...' (${f.message})`;this.skipped_details.push(h),c._error_msg=h;continue}if(d)if(Array.isArray(d))for(let f of d)f._resolved_start_idx=f._match_start_index,f._parent_edit_ref=c,(c._resolved_start_idx===void 0||c._resolved_start_idx===null)&&(c._resolved_start_idx=f._resolved_start_idx),c._resolved_proxy_edit||(c._resolved_proxy_edit=f),o.push([f,f.new_text]);else d._resolved_start_idx=d._match_start_index,d._parent_edit_ref=c,c._resolved_start_idx=d._resolved_start_idx,c._resolved_proxy_edit=d,o.push([d,d.new_text]);else {i++,c._applied_status=false;let _=`- Failed to apply edit targeting: '${(c.target_text||"insertion").trim().substring(0,40)}...'`;this.skipped_details.push(_),c._error_msg=_;}}}o.sort((c,d)=>(d[0]._resolved_start_idx||0)-(c[0]._resolved_start_idx||0));{let c=[...o].sort((d,f)=>(d[0]._resolved_start_idx||0)-(f[0]._resolved_start_idx||0));for(let[d]of c){let f=d._parent_edit_ref||d;if(Array.isArray(f._minted_change_ids)||(f._minted_change_ids=[]),d.type==="insert_row"||d.type==="delete_row"){d._reserved_row_id==null&&(d._reserved_row_id=this._getNextId(),f._minted_change_ids.push(d._reserved_row_id));continue}if(d.type!=="modify")continue;let[h,_]=Z._ids_needed(d);h&&d._reserved_del_id==null&&(d._reserved_del_id=this._getNextId(),f._minted_change_ids.push(d._reserved_del_id)),_&&d._reserved_ins_id==null&&(d._reserved_ins_id=this._getNextId(),f._minted_change_ids.push(d._reserved_ins_id));}}for(let[c]of o)this._capture_preview_context(c),c._parent_edit_ref&&this._capture_parent_preview_context(c._parent_edit_ref);let s=[],a=new Set;for(let[c,d]of o){let f=c._resolved_start_idx||0,h=c.type==="insert_row"?f:f+(c.target_text?c.target_text.length:0);if(s.some(([v,b])=>f<b&&h>v)){i++;let y=`- Skipped overlapping edit targeting: '${(c.target_text||"insertion").trim().substring(0,40)}...'`;this.skipped_details.push(y),c._applied_status=false,c._error_msg=y,c._any_sub_failure=true;let x=c._parent_edit_ref;x&&(x._applied_status=false,x._error_msg=y,x._any_sub_failure=true);continue}let p=false,m=this.current_id,w=this.comments_manager.nextId;if(c.type==="modify"?p=this._apply_single_edit_indexed(c,d,false):(c.type==="insert_row"||c.type==="delete_row")&&(p=this._apply_table_edit(c,false)),p&&c._unwrap_sdt_after&&Vc(c._unwrap_sdt_after),p){let v=c._parent_edit_ref||c;Array.isArray(v._minted_change_ids)||(v._minted_change_ids=[]);for(let b=m+1;b<=this.current_id;b++)v._minted_change_ids.push(String(b));Array.isArray(v._minted_comment_ids)||(v._minted_comment_ids=[]);for(let b=w;b<this.comments_manager.nextId;b++)v._minted_comment_ids.push(String(b));}if(p){let v=c._split_group_id,b=v==null||!a.has(v);b&&v!==void 0&&v!==null&&a.add(v),s.push([f,h]),c._applied_status=true;let y=c._parent_edit_ref;if(y){y._applied_status=true,b&&(y._occurrences_modified=(y._occurrences_modified||0)+1);let[x,k]=this._get_heading_path_and_page(f,this.mapper.full_text,n),N=y._pages||[];N.includes(k)||N.unshift(k),y._pages=N,y._heading_path=x,y._field=this._field_label_at(f);}else {b&&(c._occurrences_modified=(c._occurrences_modified||0)+1);let[x,k]=this._get_heading_path_and_page(f,this.mapper.full_text,n),N=c._pages||[];N.includes(k)||N.unshift(k),c._pages=N,c._heading_path=x,c._field=this._field_label_at(f);}}else {i++;let y=`- Failed to apply edit targeting: '${(c.target_text||"insertion").trim().substring(0,40)}...'`;this.skipped_details.push(y),c._applied_status=false,c._error_msg=y,c._any_sub_failure=true;let x=c._parent_edit_ref;x&&(x._any_sub_failure=true,x._applied_status||(x._applied_status=false,x._error_msg=y));}}let l=0,u=0;for(let c of e){if(typeof c!="object"||c===null){u++;continue}c._applied_status&&!c._any_sub_failure?l++:u++;}return [l,u]}_paragraph_has_visible_content(e){for(let n of ["w:t","w:tab","w:br"]){let r=R(e,n);for(let i of r){let o=false,s=i.parentNode;for(;s&&s!==e.parentNode;){if(s.tagName==="w:del"){o=true;break}s=s.parentNode;}if(!o){if(n==="w:t"&&!i.textContent)continue;return true}}}return false}_is_last_paragraph_in_cell(e){let n=e.parentNode;for(;n&&n.tagName!=="w:tc";)n=n.parentNode;return n?R(n,"w:p").length<=1:false}_get_paired_nodes(e){let n=[],r=e.getAttribute("w:author"),i=new Set(["w:commentRangeStart","w:commentRangeEnd","w:commentReference","w:rPr","w:pPr"]),o=new Set,s=g(d=>{let f=d.getAttribute("w:id");f&&o.add(f);},"add_id");s(e);let a=g(d=>{let f=d;for(;f&&f.tagName!=="w:p";)f=f.parentNode;return f},"paragraph_of"),l=g(d=>{let f=O(d,"w:pPr"),h=f?O(f,"w:rPr"):null;return h?O(h,"w:ins"):null},"mark_of"),u=g(d=>{let f=l(d);if(!f||f.getAttribute("w:author")!==r)return false;let h=f.getAttribute("w:id");return h!==null&&o.has(h)},"boundary_is_ours"),c=g((d,f)=>{let h=a(d),_=f==="next"?d.nextSibling:d.previousSibling;for(;;){if(!_){if(!h)break;if(f==="next"){let m=Ae(h);for(;m&&m.tagName!=="w:p";)m=Ae(m);if(!m||!u(m))break;h=m,_=m.firstChild;}else {if(!u(h))break;let m=Ie(h);for(;m&&m.tagName!=="w:p";)m=Ie(m);if(!m)break;h=m,_=m.lastChild;}continue}if(_.nodeType!==1){_=f==="next"?_.nextSibling:_.previousSibling;continue}let p=_;if(i.has(p.tagName)){_=f==="next"?_.nextSibling:_.previousSibling;continue}if((p.tagName==="w:ins"||p.tagName==="w:del")&&p.getAttribute("w:author")===r){n.push(p),s(p),_=f==="next"?_.nextSibling:_.previousSibling;continue}break}},"walk");return c(e,"next"),c(e,"prev"),n}_resolution_group_ids(e,n=null){let r=[...this._revisionsByTagIn("w:ins",n),...this._revisionsByTagIn("w:del",n)].filter(o=>o.id===e).map(o=>o.el),i=new Set;if(r.length===0)return this._revisionsByTagIn("w:pPrChange",n).some(s=>s.id===e)&&i.add(e),i;i.add(e);for(let o of r)for(let s of this._get_paired_nodes(o)){let a=s.getAttribute("w:id");a&&i.add(a);}return i}validate_action_pairing(e,n){let r=[],i=g(s=>n?n[s]:s,"gidx"),o=new Map;for(let s=0;s<e.length;s++){let a=e[s];if(a.type!=="accept"&&a.type!=="reject")continue;let l=String(a.target_id??"");if(l.startsWith("Com:"))continue;let u=l.startsWith("Chg:")?l.slice(4):l,{part:c,error:d}=this._action_part_filter(a);if(d)continue;let f=c;if(f===null){let m=this._parts_holding_id(u);if(m.length!==1)continue;f=m[0];}let h=this._resolution_group_ids(u,f);if(h.size===0)continue;let _=g(m=>`${f}\0${m}`,"group_key"),p=null;for(let m of h){let w=o.get(_(m));if(w!==void 0&&w[1]!==a.type){p=w;break}}if(p!==null){let[m,w,v]=p;r.push(`- Action ${i(s)+1} Failed: conflicting actions on one replacement \u2014 Action ${i(m)+1} applies '${w}' to Chg:${v}, and Chg:${u} is part of the same change (a replacement's contiguous del+ins pair resolves as one unit, so '${w}' already decides both sides). Accepting one side and rejecting the other is contradictory \u2014 decide the outcome and submit exactly one action for the pair.`);continue}for(let m of h)o.has(_(m))||o.set(_(m),[s,a.type,u]);}return r}_buildRevisionIndex(e){let n=new Map;for(let i of Lt)n.set(i,[]);let r=[];for(let[i,o]of e){let s=i.ownerDocument;r.push({el:i,doc:s,inc:typeof s?._inc=="number"?s._inc:null});let a=[i],l=[0],u=[],c=[];for(;a.length;){let d=a.length-1,f=a[d].childNodes;if(!f||l[d]>=f.length){for(a.pop(),l.pop();c.length&&c[c.length-1]>a.length;)c.pop(),u.pop();continue}let h=f[l[d]++];if(h.nodeType!==1)continue;let _=n.get(h.tagName),p=null;_&&(p={el:h,id:h.getAttribute("w:id"),part:o,nested:[]},_.push(p));let m=h.tagName==="w:ins"||h.tagName==="w:del";if(p&&m)for(let w of u)w.nested.push(p);a.push(h),l.push(0),p&&m&&(u.push(p),c.push(a.length));}}return {roots:r,byTag:n}}_getRevisionIndex(){let e=this._story_roots(),n=this._revisionIndex;if(n!==null&&n.roots.length===e.length&&n.roots.every((o,s)=>{let a=e[s][0],l=a.ownerDocument;return o.el===a&&o.doc===l&&o.inc!==null&&typeof l?._inc=="number"&&o.inc===l._inc}))return n;let i=this._buildRevisionIndex(e);return this._revisionIndex=i,i}_revisionsByTag(e){return this._getRevisionIndex().byTag.get(e)??[]}_revisionsByTagIn(e,n){let r=this._revisionsByTag(e);return n===null?r:r.filter(i=>i.part===n)}_parts_holding_id(e){let n=[];for(let r of Lt)for(let i of this._revisionsByTag(r))i.id===e&&!n.includes(i.part)&&n.push(i.part);return n}_action_part_filter(e){let n=e.part;if(n==null||n==="")return {part:null};let r=this._story_roots().map(([,o])=>o);if(typeof n!="string")return {part:null,error:`\`part\` must be a string naming a package part (one of: ${r.join(", ")}).`};let i=Rn(n);return r.includes(i)?{part:i}:{part:null,error:`part '${n}' is not a package part that can carry tracked changes. Parts addressable by accept/reject: ${r.join(", ")}.`}}_existing_change_ids(){let e=new Set;for(let n of Lt)for(let r of this._revisionsByTag(n))r.id&&e.add(r.id);return Array.from(e).sort((n,r)=>{let i=/^\d+$/.test(n)?parseInt(n,10):0,o=/^\d+$/.test(r)?parseInt(r,10):0;return i-o||n.localeCompare(r)})}_warn_stranded_comment_anchors(e){let n;try{n=R(this.doc.element,"w:commentRangeStart");}catch{return}if(n.length===0)return;let r=g(l=>{let u=new Map,c=0,d=g(f=>{u.set(f,c++);for(let h=f.firstChild;h;h=h.nextSibling)h.nodeType===1&&d(h);},"walk");return d(l),u},"order"),i=g(l=>{let u=l.parentNode;for(;u&&u.nodeType===1;){if(u.tagName==="w:p")return u;u=u.parentNode;}return null},"paragraphOf"),o=g((l,u)=>{let c=l.parentNode;for(;c&&c.nodeType===1&&c!==u;){if(c.tagName==="w:del")return true;c=c.parentNode;}return false},"hasDeletedAncestorWithin"),s=null,a=[];for(let l of n){let u=l.getAttribute("w:id");if(!u)continue;let c=i(l);if(!c)continue;let d=R(c,"w:commentRangeEnd").find(b=>b.getAttribute("w:id")===u);if(!d)continue;let f=r(c),h=f.get(l),_=f.get(d);if(h===void 0||_===void 0||_<h)continue;let p="";for(let b of R(c,"w:t")){let y=f.get(b);y===void 0||y<h||y>_||o(b,c)||(p+=b.textContent||"");}if(!p.trim())continue;let m=false,w=false,v=false;for(let b of R(c,"w:del")){let y=f.get(b);if(y===void 0)continue;let x=y<h?"before":y>_?"after":null;if(!x||!R(b,"w:delText").some(P=>(P.textContent||"").trim()))continue;x==="before"?m=true:w=true;let N=b.getAttribute("w:id")||"";/^\d+$/.test(N)&&parseInt(N,10)>e&&(v=true);}m&&w&&v&&(s===null&&(s=this._comment_authors()),a.push([u,p.trim()]));}for(let[l,u]of a){let c=s?.[l],d=c?`comment Com:${l} (by ${c})`:`comment Com:${l}`;this.skipped_details.push(`- Warning: this batch deleted text on both sides of ${d} but left its anchored text "${de(u,60)}" in place, so once the changes are accepted that text stands alone in its sentence. If you kept it to preserve the comment's anchor, re-read the sentence; if you meant to remove the clause, extend one edit over the anchored text too. The edits themselves were applied.`);}}existing_change_ids(){return this._existing_change_ids()}_existing_comment_ids(){let e=[];try{e=Object.keys(Me(this.doc.pkg));}catch{e=[];}return e.sort((n,r)=>{let i=/^\d+$/.test(n)?parseInt(n,10):0,o=/^\d+$/.test(r)?parseInt(r,10):0;return i-o||n.localeCompare(r)})}_comment_authors(){let e={};try{for(let[n,r]of Object.entries(Me(this.doc.pkg)))e[n]=r?.author||"Unknown";}catch{}return e}static _describe_removed_comments(e,n){let r=[...e].sort((o,s)=>{let a=/^\d+$/.test(o)?parseInt(o,10):0,l=/^\d+$/.test(s)?parseInt(s,10):0;return a-l||o.localeCompare(s)}),i=r.map(o=>n[o]?`Com:${o} (by ${n[o]})`:`Com:${o}`).join(", ");return `${r.length===1?"comment":"comments"} ${i}`}static _format_id_list(e,n,r=20){let i=e.slice(0,r),o=i.map(s=>`${n}${s}`).join(", ");return e.length>i.length&&(o+=`, \u2026 (+${e.length-i.length} more)`),o}_action_not_found_error(e,n,r="- Failed to apply action:"){let i=this._existing_change_ids(),o=this._existing_comment_ids(),s=e.startsWith("Chg:")||e.startsWith("Com:"),a=e.replace(/^(Chg:|Com:)/,""),l=this.id_discovery_hint||"Call `read_docx` with `mode='changes'` on the document again to list the current change (Chg:) and comment (Com:) ids \u2014 ids shift between document states.";if(n==="reply"){let d=s?e:`Com:${a}`;if(i.includes(a))return `${r} reply on ${d} \u2014 Chg:${a} is a tracked-change id, not a comment. \`reply\` adds to an existing comment thread (Com:\u2026); to comment on a change instead, apply a modify with a \`comment\`. ${l}`;let f=o.length>0?`Comment ids in this document: ${Z._format_id_list(o,"Com:")}. `:"This document has no comments to reply to. ";return `${r} reply on ${d} \u2014 no comment with that id exists. ${f}${l}`}let u=s?e:`Chg:${a}`;if(o.includes(a))return `${r} ${n} on ${u} \u2014 Com:${a} is a comment id, not a tracked change. accept/reject act on tracked changes (Chg:\u2026); to respond to a comment use \`reply\`. ${l}`;let c=i.length>0?`Tracked-change ids in this document: ${Z._format_id_list(i,"Chg:")}. `:"This document has no tracked changes. ";return `${r} ${n} on ${u} \u2014 no tracked change with that id exists (it may already have been accepted or rejected, or the id is stale). ${c}${l}`}_not_found_in_part_error(e,n,r,i="- Failed to apply action:"){let o=e.replace(/^(Chg:|Com:)/,""),s=e.startsWith("Chg:")?e:`Chg:${o}`,a=this._parts_holding_id(o),l=a.length>0?`Revisions with that id exist in: ${a.join(", ")}. `:"",u=this.id_discovery_hint||"Call `read_docx` with `mode='changes'` on the document again to list the current change (Chg:) and comment (Com:) ids \u2014 ids shift between document states.";return `${i} ${n} on ${s} \u2014 no tracked change with w:id=${o} exists in part '${r}'. ${l}${u}`}_ambiguous_part_error(e,n,r,i){let o=e.replace(/^Chg:/,"");return `${i} ${n} on Chg:${o} is ambiguous: revisions with w:id=${o} exist in ${r.length} document parts (${r.join(", ")}). Revision ids are numbered per part, so the bare id cannot name one change. Re-issue the action with \`part\` set to the part whose change you mean, e.g. {"type": "${n}", "target_id": "${o}", "part": "${r[0]}"}.`}apply_review_actions(e,n){let r=g(u=>n?n[u]:u,"gidx"),i=0,o=0,s=0,a=new Map,l=e.map((u,c)=>({action:u,pos:c})).sort((u,c)=>{let d=u.action.type==="reply"?0:1,f=c.action.type==="reply"?0:1;return d!==f?d-f:u.pos-c.pos});for(let{action:u,pos:c}of l){let d=u.type;if(d==="reply"){let E=u.target_id.replace("Com:","");if(!this._existing_comment_ids().includes(E)){o++,this.skipped_details.push(this._action_not_found_error(u.target_id,"reply",`- Action ${r(c)+1} Failed:`));continue}let S;try{S=this.comments_manager.addComment(this.author,u.text,E);}catch(D){if(D instanceof Hi){o++,this.skipped_details.push(`- Action ${r(c)+1} Failed: reply on ${u.target_id} \u2014 ${D.message}`);continue}throw D}this._anchor_reply_comment(E,S),i++;continue}let f=u.target_id.replace("Chg:",""),{part:h,error:_}=this._action_part_filter(u);if(_){o++,this.skipped_details.push(`- Action ${r(c)+1} Failed: ${d} on ${u.target_id} \u2014 ${_}`);continue}let p=a.get(f);if(p!==void 0&&(h===null||h===p.part)){if(p.type===d){s++,this.skipped_details.push(`- Note: Action ${r(c)+1} ('${d}' on ${u.target_id}) had no additional effect \u2014 the change was already resolved together with its replacement pair by an earlier action in this batch. Counted as already_resolved, not applied.`);continue}this.skipped_details.push(`- Action ${r(c)+1} Failed: contradictory action \u2014 '${d}' on ${u.target_id}, but the change was already resolved as '${p.type}' together with its replacement pair by an earlier action in this batch.`),o++;continue}let m=this._parts_holding_id(f),w=h;if(w===null){if(m.length>1){o++,this.skipped_details.push(this._ambiguous_part_error(u.target_id,d,m,`- Action ${r(c)+1} Failed:`));continue}w=m.length===1?m[0]:null;}let v=this._revisionsByTagIn("w:ins",w).filter(E=>E.id===f).map(E=>E.el),b=this._revisionsByTagIn("w:del",w).filter(E=>E.id===f).map(E=>E.el),y=[...v,...b],x=Gn.flatMap(E=>this._revisionsByTagIn(E,w).filter(S=>S.id===f).map(S=>S.el));if(y.length===0&&x.length===0){o++,this.skipped_details.push(h!==null?this._not_found_in_part_error(u.target_id,d,h,`- Action ${r(c)+1} Failed:`):this._action_not_found_error(u.target_id,d,`- Action ${r(c)+1} Failed:`));continue}let k=Array.from(new Set([...y,...x].map(E=>E.getAttribute("w:author")||"Unknown"))).sort();if(k.length>1){o++,this.skipped_details.push(`- Failed to apply action: ${d} on Chg:${f} is ambiguous. The document contains ${y.length} tracked-change elements sharing w:id=${f} from different authors (${k.join(", ")}) \u2014 duplicate revision IDs produced outside this engine (e.g. by a document merge or copy-paste). Acting on this ID would resolve all of them at once. Resolve these changes individually in Word, or apply the intended outcome as an explicit text edit instead.`);continue}let N=new Set([f]);for(let E of y)for(let S of this._get_paired_nodes(E)){let D=S.getAttribute("w:id");D&&N.add(D);}let P=qn.flatMap(E=>this._revisionsByTagIn(E,w)),A=-1;for(;A!==N.size;){A=N.size;for(let E of P)if(!(!E.id||!N.has(E.id)))for(let S of E.nested)S.id&&N.add(S.id);}let C=[];for(let E of qn)for(let S of this._revisionsByTagIn(E,w))S.id&&N.has(S.id)&&C.push(S.el);let T=Gn.flatMap(E=>this._revisionsByTagIn(E,w).filter(S=>S.id!==null&&N.has(S.id)).map(S=>S.el)),M=(()=>{let E=y[0]??x[0]??null;for(;E;){if(E.nodeType===1&&E.tagName==="w:p")return E;E=E.parentNode;}return null})(),j=new Set;for(let E of [...C,...T]){let S=E.getAttribute("w:id");S&&j.add(S);}let B=this._comment_authors(),$=new Set(Object.keys(B)),I=[];for(let E of C){let S=E.tagName==="w:ins",D=E.parentNode?E.parentNode.tagName:"",U=D==="w:trPr",z=S&&D==="w:rPr"&&!!E.parentNode?.parentNode&&E.parentNode.parentNode.tagName==="w:pPr";if(d==="accept")if(S)if(U)E.parentNode?.removeChild(E);else {for(;E.firstChild;)E.parentNode?.insertBefore(E.firstChild,E);E.parentNode?.removeChild(E);}else if(this._clean_wrapping_comments(E),this._delete_comments_in_element(E),U){let W=E.parentNode?.parentNode;W?.parentNode?.removeChild(W);}else E.parentNode?.removeChild(E);else if(d==="reject")if(S){if(z){let W=E.parentNode;E.parentNode?.removeChild(E),W=W?.parentNode,W=W?.parentNode,W&&W.tagName==="w:p"&&I.push(W);continue}if(this._clean_wrapping_comments(E),this._delete_comments_in_element(E),U){let W=E.parentNode?.parentNode;W?.parentNode?.removeChild(W);}else E.parentNode?.removeChild(E);}else if(U)E.parentNode?.removeChild(E);else {let W=Array.from(E.getElementsByTagName("w:delText"));for(let L of W){let X=L.ownerDocument.createElement("w:t");X.textContent=L.textContent,L.hasAttribute("xml:space")&&X.setAttribute("xml:space","preserve"),L.parentNode?.replaceChild(X,L);}for(;E.firstChild;)E.parentNode?.insertBefore(E.firstChild,E);E.parentNode?.removeChild(E);}}for(let E of I.reverse()){if(!E.parentNode)continue;let S=Ie(E);for(;S&&S.tagName!=="w:p";)S=Ie(S);if(S){for(let D of Array.from(E.childNodes))D.nodeType===1&&D.tagName==="w:pPr"||S.appendChild(D);E.parentNode.removeChild(E);}}for(let E of T)d==="accept"?E.parentNode?.removeChild(E):E.tagName==="w:pPrChange"?this._revert_ppr_change(E):this._revert_props_change(E);for(let E of j)a.set(E,{type:d,part:w});if(i++,$.size>0){let E=new Set(this._existing_comment_ids()),S=Array.from($).filter(D=>!E.has(D));S.length>0&&this.skipped_details.push(`- Note: ${d} on ${u.target_id} also removed ${Z._describe_removed_comments(S,B)} (including any reply thread) because its anchor was inside the resolved change. This note is informational \u2014 the action itself succeeded.`);}if(u.comment&&String(u.comment).trim()){let E=r(c)+1,S=M?Array.from(M.childNodes).find(D=>D.tagName==="w:r")??null:null;if(M&&S){let D=this._attach_comment(M,S,S,String(u.comment));D&&this.skipped_details.push(`- Note: Action ${E} ('${d}' on ${u.target_id}) \u2014 rationale recorded as Com:${D}.`);}else this.skipped_details.push(`- Note: Action ${E} ('${d}' on ${u.target_id}) \u2014 the rationale could not be anchored (the resolved text left no surviving run); the ${d} itself succeeded.`);}}return [i,o,s]}_apply_table_edit(e,n){let r=e._resolved_start_idx!==void 0&&e._resolved_start_idx!==null?e._resolved_start_idx:e._match_start_index||0,i=e._active_mapper_ref||this.mapper,[o,s]=i.get_insertion_anchor(r,n),a=null;if(o?a=o._element:s&&(a=s._element),!a)return false;let l=a;for(;l&&l.tagName!=="w:tr";)l=l.parentNode;if(!l)return false;let u=(e._reserved_row_id??null)!==null?String(e._reserved_row_id):null;if(e.type==="delete_row"){let c=O(l,"w:trPr");return c||(c=l.ownerDocument.createElement("w:trPr"),l.insertBefore(c,l.firstChild)),c.appendChild(this._create_track_change_tag("w:del","",u)),true}else if(e.type==="insert_row"){let c=l.ownerDocument.createElement("w:tr"),d=l.ownerDocument.createElement("w:trPr");c.appendChild(d),d.appendChild(this._create_track_change_tag("w:ins","",u));let f=R(l,"w:tc").filter(_=>_.parentNode===l).length,h=Array.isArray(e.cells)?[...e.cells]:[];if(f>0){for(;h.length<f;)h.push("");h=h.slice(0,f);}for(let _ of h){let p=l.ownerDocument.createElement("w:tc"),m=l.ownerDocument.createElement("w:p"),w=l.ownerDocument.createElement("w:r"),v=l.ownerDocument.createElement("w:t");v.textContent=_,_.trim()!==_&&v.setAttribute("xml:space","preserve"),w.appendChild(v),m.appendChild(w),p.appendChild(m),c.appendChild(p);}return e.position==="above"?l.parentNode?.insertBefore(c,l):nt(c,l),true}return false}_match_spans_whole_paragraph(e,n,r){let i=n+r,o=new Map;for(let s of e.spans){if(s.paragraph===null||s.paragraph===void 0||s.run===null&&s.text===`
113
143
 
114
- `)continue;let l=i.get(o.paragraph),a=o.run!==null&&o.run!==void 0?o.start:1/0;l===void 0?i.set(o.paragraph,[o.start,o.end,a]):(o.start<l[0]&&(l[0]=o.start),o.end>l[1]&&(l[1]=o.end),a<l[2]&&(l[2]=a));}for(let[o,l,a]of i.values())if(l===s&&(o===n||a===n))return true;return false}_pre_resolve_heuristic_edit(e){if(!e.target_text)return null;let n=e.regex||false,r=e.match_mode||"strict",s=this.mapper.drop_virtual_only_matches(this.mapper.find_all_match_indices(e.target_text,n)),i=false;if(s.length===0)if(this.clean_mapper||(this.clean_mapper=new ve(this.doc,true)),s=this.clean_mapper.drop_virtual_only_matches(this.clean_mapper.find_all_match_indices(e.target_text,n)),s.length>0)i=true;else return null;let o=i?this.clean_mapper:this.mapper,l=[];for(let[u,c]of s){let d=o.spans.filter(f=>f.run!==null&&f.end>u&&f.start<u+c);(d.length===0||d.some(f=>!f.del_id))&&l.push([u,c]);}if(l.length===0)return null;(r==="strict"||r==="first")&&(l=l.slice(0,1));let a=[];for(let[u,c]of l){let d=o.full_text.substring(u,u+c),f=e.new_text||"";if(/^\{#cell:[^}]+\}$/.test(d.trim())){let T=f;T=T.split(d.trim()).join("");let D=o.spans.find(j=>j.start<=u&&u<j.end&&j.paragraph!==null);if(D&&T){let j=o.spans.filter(E=>E.end<=u&&E.run!==null&&E.paragraph!==null&&E.paragraph._element===D.paragraph._element).map(E=>E.text).join("");if(j){for(let E of [j,j.replace(/\s+$/,"")])if(E&&T.startsWith(E)){T=T.substring(E.length).replace(/^\s+/,"");break}T&&!/\s$/.test(j)&&!/^\s/.test(T)&&(T=" "+T);}}T?a.push({type:"modify",target_text:"",new_text:T,comment:e.comment,_match_start_index:u,_internal_op:"INSERTION",_active_mapper_ref:o}):e.comment&&a.push({type:"modify",target_text:"",new_text:"",comment:e.comment,_match_start_index:u,_internal_op:"COMMENT_ONLY",_active_mapper_ref:o});continue}if(n&&f){try{f=d.replace(new RegExp(e.target_text),f);}catch{}V._flag_surviving_python_backreference(e,f);}f=Hs(d,e.target_text,f),e._preview_span||(e._preview_span=[u,c],e._preview_matched_text=d,e._preview_new_text=f,e._preview_mapper_ref=o);let[h,_]=this._parse_markdown_style(e.target_text),[p,m]=this._parse_markdown_style(f);if(_!==m&&this._match_spans_whole_paragraph(o,u,c)){let[T]=this._parse_markdown_style(d),D=T,j=p,E=D===j?"STYLE_ONLY":"STYLE_AND_TEXT",I=d.indexOf(T),P=u+(I!==-1?I:0),S=m!==null?m:"Normal";a.push({type:"modify",target_text:D,new_text:j,comment:e.comment,_match_start_index:P,_internal_op:E,_new_style:S,_active_mapper_ref:o});continue}if(d===f||e.target_text===f){a.push({type:"modify",target_text:d,new_text:d,comment:e.comment,_match_start_index:u,_internal_op:"COMMENT_ONLY",_active_mapper_ref:o});continue}let y=false;if(o&&(y=o.spans.some(T=>T.text===" | "&&(T.run===null||T.run===void 0)&&T.start<u+c&&T.end>u)),y){let T=d.split("|"),D=f.split("|");if(T.length!==D.length)throw new mt([`Target text spans ${T.length} table cells, but replacement provides ${D.length}. To modify text without altering table structure (rows or columns), ensure the replacement contains the exact same number of '|' separators (e.g., replace with 'CellC | ' to empty the second cell).`]);if(T.length>1){let j=[],E=0,I=0;for(let P=0;P<T.length;P++)if(T[P].trim()!==D[P].trim()){I=P;break}for(let P=0;P<T.length;P++){let S=T[P],$=D[P],O=S.trim(),F=$.trim(),W=u+E+(O?S.indexOf(O):0),L=e.comment!==null&&e.comment!==void 0&&P===I;if(O!==F||L){let U=this._word_diff_sub_edits(O,F,W,L?e.comment:null,true,o);for(let q of U)q._original_target_text=e.target_text,q._split_group_id=u,j.push(q);}E+=S.length+1;}for(let P of j)a.push(P);continue}}let x=false;e.target_text&&(e.target_text.includes("**")||e.target_text.includes("_"))&&(x=true),f&&(f.includes("**")||f.includes("_"))&&(x=true);let b="",w="",v="",N=u;if(f.startsWith(d))b="INSERTION",v=f.substring(d.length),N=u+c;else {let[T,D]=Je(d,f),j=d.length-D,E=f.length-D;w=d.substring(T,j),v=f.substring(T,E),N=u+T;}if(x){if(!w&&v)b="INSERTION";else if(w&&!v)b="DELETION";else if(w&&v)b="MODIFICATION";else {a.push({type:"modify",target_text:w,new_text:v,comment:e.comment,_match_start_index:N,_internal_op:"COMMENT_ONLY",_active_mapper_ref:o});continue}a.push({type:"modify",target_text:w,new_text:v,comment:e.comment,_resolved_start_idx:N,_match_start_index:N,_internal_op:b,_active_mapper_ref:o});continue}let k=d.split(`
144
+ `)continue;let a=o.get(s.paragraph),l=s.run!==null&&s.run!==void 0?s.start:1/0;a===void 0?o.set(s.paragraph,[s.start,s.end,l]):(s.start<a[0]&&(a[0]=s.start),s.end>a[1]&&(a[1]=s.end),l<a[2]&&(a[2]=l));}for(let[s,a,l]of o.values())if(a===i&&(s===n||l===n))return true;return false}_pre_resolve_heuristic_edit(e){if(!e.target_text)return null;let n=e.regex||false,r=e.match_mode||"strict",i=this.mapper.drop_virtual_only_matches(this.mapper.find_all_match_indices(e.target_text,n)),o=false;if(i.length===0)if(this.clean_mapper||(this.clean_mapper=new ke(this.doc,true)),i=this.clean_mapper.drop_virtual_only_matches(this.clean_mapper.find_all_match_indices(e.target_text,n)),i.length>0)o=true;else return null;let s=o?this.clean_mapper:this.mapper,a=[];for(let[u,c]of i){let d=s.spans.filter(f=>f.run!==null&&f.end>u&&f.start<u+c);(d.length===0||d.some(f=>!f.del_id))&&a.push([u,c]);}if(a.length===0)return null;(r==="strict"||r==="first")&&(a=a.slice(0,1));let l=[];for(let[u,c]of a){let d=s.full_text.substring(u,u+c),f=e.new_text||"";if(/^\{#cell:[^}]+\}$/.test(d.trim())){let C=f;C=C.split(d.trim()).join("");let T=s.spans.find(M=>M.start<=u&&u<M.end&&M.paragraph!==null);if(T&&C){let M=s.spans.filter(j=>j.end<=u&&j.run!==null&&j.paragraph!==null&&j.paragraph._element===T.paragraph._element).map(j=>j.text).join("");if(M){for(let j of [M,M.replace(/\s+$/,"")])if(j&&C.startsWith(j)){C=C.substring(j.length).replace(/^\s+/,"");break}C&&!/\s$/.test(M)&&!/^\s/.test(C)&&(C=" "+C);}}C?l.push({type:"modify",target_text:"",new_text:C,comment:e.comment,_match_start_index:u,_internal_op:"INSERTION",_active_mapper_ref:s}):e.comment&&l.push({type:"modify",target_text:"",new_text:"",comment:e.comment,_match_start_index:u,_internal_op:"COMMENT_ONLY",_active_mapper_ref:s});continue}if(n&&f){try{f=d.replace(new RegExp(e.target_text),f);}catch{}Z._flag_surviving_python_backreference(e,f);}f=pa(d,e.target_text,f),e._preview_span||(e._preview_span=[u,c],e._preview_matched_text=d,e._preview_new_text=f,e._preview_mapper_ref=s);let[h,_]=this._parse_markdown_style(e.target_text),[p,m]=this._parse_markdown_style(f);if(_!==m&&this._match_spans_whole_paragraph(s,u,c)){let[C]=this._parse_markdown_style(d),T=C,M=p,j=T===M?"STYLE_ONLY":"STYLE_AND_TEXT",B=d.indexOf(C),$=u+(B!==-1?B:0),I=m!==null?m:"Normal";l.push({type:"modify",target_text:T,new_text:M,comment:e.comment,_match_start_index:$,_internal_op:j,_new_style:I,_active_mapper_ref:s});continue}if(d===f||e.target_text===f){l.push({type:"modify",target_text:d,new_text:d,comment:e.comment,_match_start_index:u,_internal_op:"COMMENT_ONLY",_active_mapper_ref:s});continue}let w=false;if(s&&(w=s.spans.some(C=>C.text===" | "&&(C.run===null||C.run===void 0)&&C.start<u+c&&C.end>u)),w){let C=d.split("|"),T=f.split("|");if(C.length!==T.length)throw new Wt([`Target text spans ${C.length} table cells, but replacement provides ${T.length}. To modify text without altering table structure (rows or columns), ensure the replacement contains the exact same number of '|' separators (e.g., replace with 'CellC | ' to empty the second cell).`]);if(C.length>1){let M=[],j=0,B=0;for(let $=0;$<C.length;$++)if(C[$].trim()!==T[$].trim()){B=$;break}for(let $=0;$<C.length;$++){let I=C[$],E=T[$],S=I.trim(),D=E.trim(),U=u+j+(S?I.indexOf(S):0),z=e.comment!==null&&e.comment!==void 0&&$===B;if(S!==D||z){let W=this._word_diff_sub_edits(S,D,U,z?e.comment:null,true,s);for(let L of W)L._original_target_text=e.target_text,L._split_group_id=u,M.push(L);}j+=I.length+1;}for(let $ of M)l.push($);continue}}let v=false;e.target_text&&(e.target_text.includes("**")||e.target_text.includes("_"))&&(v=true),f&&(f.includes("**")||f.includes("_"))&&(v=true);let b="",y="",x="",k=u;if(f.startsWith(d))b="INSERTION",x=f.substring(d.length),k=u+c;else {let[C,T]=rt(d,f),M=d.length-T,j=f.length-T;y=d.substring(C,M),x=f.substring(C,j),k=u+C;}if(v){if(!y&&x)b="INSERTION";else if(y&&!x)b="DELETION";else if(y&&x)b="MODIFICATION";else {l.push({type:"modify",target_text:y,new_text:x,comment:e.comment,_match_start_index:k,_internal_op:"COMMENT_ONLY",_active_mapper_ref:s});continue}l.push({type:"modify",target_text:y,new_text:x,comment:e.comment,_resolved_start_idx:k,_match_start_index:k,_internal_op:b,_active_mapper_ref:s});continue}let N=d.split(`
115
145
 
116
- `),C=f.split(`
146
+ `),P=f.split(`
117
147
 
118
148
  `);if(d.includes(`
119
149
 
120
- `)&&k.length===C.length){let T=[],D=u,j=false;for(let E=0;E<k.length;E++){let I=k[E],P=C[E];if(I!==P){let S=e.comment&&!j?e.comment:null,$=this._word_diff_sub_edits(I,P,D,S,false,o);$.some(O=>O.comment!==null&&O.comment!==void 0)&&(j=true);for(let O of $)O._split_group_id=u,T.push(O);}D+=I.length+2;}if(T.length>0){for(let E of T)a.push(E);continue}}if(!w&&v){a.push({type:"modify",target_text:"",new_text:v,comment:e.comment,_resolved_start_idx:N,_match_start_index:N,_internal_op:"INSERTION",_active_mapper_ref:o});continue}let A=this._word_diff_sub_edits(d,f,u,e.comment,false,o);for(let T of A)T._split_group_id=u,a.push(T);}return a.length===0?null:r==="all"||a.length>1?a:a[0]}_insert_and_split_ins(e,n,r,s=false){let i=e.parentNode;if(!i)return;let o=e.cloneNode(false),l=e.cloneNode(false),a=false;for(let u of Array.from(e.childNodes))e.removeChild(u),s&&u===n&&(a=true),a?l.appendChild(u):(o.appendChild(u),u===n&&(a=true));o.childNodes.length>0&&i.insertBefore(o,e),i.insertBefore(r,e),l.childNodes.length>0&&i.insertBefore(l,e),i.removeChild(e);}_apply_single_edit_indexed(e,n,r){let s=e._internal_op,i=e._active_mapper_ref||this.mapper,o=e._resolved_start_idx!==void 0&&e._resolved_start_idx!==null?e._resolved_start_idx:e._match_start_index||0,l=e.target_text?e.target_text.length:0;s==null&&(!e.target_text&&e.new_text?s="INSERTION":e.target_text&&!e.new_text?s="DELETION":s="MODIFICATION");let a=this._edit_declares_emphasis(e),u=null;if(s==="STYLE_ONLY"||s==="STYLE_AND_TEXT"){let[w,v]=i.get_insertion_anchor(o,r),N=null;if(v)N=v._element;else if(w){let k=w._element;for(;k&&k.tagName!=="w:p";)k=k.parentNode;N=k;}if(N&&e._new_style&&(s==="STYLE_ONLY"?this._set_paragraph_style(N,e._new_style,this._getNextId()):u=N),s==="STYLE_ONLY"){if(e.comment){let k=i.find_target_runs_by_index(o,l,r);if(k.length>0){let C=k[0]._element,A=k[k.length-1]._element,T=C;for(;T&&T.tagName!=="w:p";)T=T.parentNode;let D=A;for(;D&&D.tagName!=="w:p";)D=D.parentNode;if(T&&D){let j=g((P,S)=>{let $=P;for(;$.parentNode&&$.parentNode!==S;)$=$.parentNode;return $},"ascend_to_paragraph_child"),E=j(C,T),I=j(A,D);T===D?this._attach_comment(T,E,I,e.comment):this._attach_comment_spanning(T,E,D,I,e.comment);}}}return true}e.target_text&&e.new_text?s="MODIFICATION":!e.target_text&&e.new_text?s="INSERTION":e.target_text&&!e.new_text?s="DELETION":s="COMMENT_ONLY";}let c=["DELETION","MODIFICATION"].includes(s)?(e._reserved_del_id??null)!==null?String(e._reserved_del_id):this._getNextId():null,d=["INSERTION","MODIFICATION"].includes(s)?(e._reserved_ins_id??null)!==null?String(e._reserved_ins_id):this._getNextId():null;if(u&&e._new_style&&this._set_paragraph_style(u,e._new_style,d??c??this._getNextId()),s==="COMMENT_ONLY"){let w=i.find_target_runs_by_index(o,l,r);if(w.length===0)return false;if(!e.comment)return true;let v=w[0]._element,N=w[w.length-1]._element,k=v;for(;k&&k.tagName!=="w:p";)k=k.parentNode;let C=N;for(;C&&C.tagName!=="w:p";)C=C.parentNode;if(!k||!C)return false;let A=g((j,E)=>{let I=j;for(;I.parentNode&&I.parentNode!==E;)I=I.parentNode;return I},"ascend_to_paragraph_child"),T=A(v,k),D=A(N,C);return k===C?this._attach_comment(k,T,D,e.comment):this._attach_comment_spanning(k,T,C,D,e.comment),true}if(s==="INSERTION"){let w=e.new_text||"",v=null,N=typeof i.part_boundary_at=="function"?i.part_boundary_at(o):null,k=!e.target_text&&(e._parent_edit_ref===void 0||e._parent_edit_ref===null);if(N!==null&&k){let[P,S]=N,$=i.part_kind_of(P),O=i.part_kind_of(S);if($==="body"&&O!=="body"){let F=i.spans.filter(W=>W.run!==null&&W.part_index===P);F.length>0&&(v=F[F.length-1]);}}let C,A;if(v!==null?(C=v.run,A=v.paragraph,w.startsWith(`
121
- `)||(w=`
122
-
123
- `+w)):[C,A]=i.get_insertion_anchor(o,r),!C&&!A||V._introduces_table_row_text(i,o,1,"",w))return false;let T=w,D=v===null&&/\n\s*$/.test(T),j=null;{let P=i.spans.filter(S=>S.paragraph!==null&&S.start===o);P.length>0&&P[0].paragraph&&(j=P[0].paragraph._element);}if(D&&j&&j.parentNode){let P=j.parentNode,S=this.doc.part._element.ownerDocument,$=T.split(/[\r\n]+/).filter(L=>L!==""),O=null,F=null,W=null;for(let L of $){let[U,q]=this._parse_markdown_style(L),J=S.createElement("w:p");if(q)this._set_paragraph_style(J,q);else {let ge=B(j,"w:pPr");ge&&J.appendChild(this._clone_pPr_scrubbing_headings(ge,j));}let z=B(J,"w:pPr");z||(z=S.createElement("w:pPr"),J.insertBefore(z,J.firstChild));let ne=B(z,"w:rPr");ne||(ne=S.createElement("w:rPr"),z.appendChild(ne)),ne.appendChild(this._create_track_change_tag("w:ins","",d));let he=this._build_tracked_ins_for_line(U,C,d,S,a);he&&J.appendChild(he),P.insertBefore(J,j),O||(O=J),F=J,W=he;}if(O){if(e.comment&&F&&W){let L=g((q,J)=>{let z=q;for(;z.parentNode&&z.parentNode!==J;)z=z.parentNode;return z},"ascend"),U=M(O,"w:ins")[0]||O;this._attach_comment_spanning(O,L(U,O),F,L(W,F),e.comment);}return true}}let E=this._track_insert_multiline(w,C,A,d,null,a,o===0||C===null&&A!==null);if(!E.first_node)return false;if(E.first_node.tagName==="w:ins"){if(C){let P=C._element,S=P.parentNode;S&&S.tagName==="w:del"&&(P=S,S=P.parentNode);let $=o===0;S&&S.tagName==="w:ins"?this._insert_and_split_ins(S,P,E.first_node,$):$&&S?S.insertBefore(E.first_node,P):qe(E.first_node,P);}else if(A){let P=A._element,S=P.firstChild;for(;S&&S.tagName==="w:pPr";)S=S.nextSibling;P.insertBefore(E.first_node,S);}}if(e.comment){let P=g((S,$)=>{let O=S;for(;O.parentNode&&O.parentNode!==$;)O=O.parentNode;return O},"ascend_to_paragraph_child");if(E.last_p&&E.last_ins){let S=E.first_node;for(;S&&S.tagName!=="w:p";)S=S.parentNode;if(S){let $=E.first_node;E.first_node.tagName==="w:p"&&($=M(E.first_node,"w:ins")[0]||E.first_node);let O=P($,S),F=P(E.last_ins,E.last_p);this._attach_comment_spanning(S,O,E.last_p,F,e.comment);}}else {let S=E.first_node;for(;S&&S.tagName!=="w:p";)S=S.parentNode;if(S){let $=E.first_node;E.first_node.tagName==="w:p"&&($=M(E.first_node,"w:ins")[0]||E.first_node);let O=P($,S);this._attach_comment(S,O,O,e.comment);}}}return true}if((s==="DELETION"||s==="MODIFICATION")&&l&&i.part_ranges.filter(w=>w[1]>w[0]).length>1){let w=new Set;for(let v of i.spans)v.run!==null&&v.end>o&&v.start<o+l&&w.add(v.part_index);if(w.size>1)return false}let f=i.find_target_runs_by_index(o,l,r),h=i.get_virtual_spans_in_range(o,l);if(f.length===0&&h.length===0)return false;let _=new Set;for(let w of f){let v=w._element.parentNode;for(;v&&v.tagName!=="w:p";)v=v.parentNode;v&&_.add(v);}let p=null,m=null;for(let w of f){let v=this._create_track_change_tag("w:del","",c),N=w._element.cloneNode(true);Array.from(N.getElementsByTagName("w:t")).forEach(C=>{let A=N.ownerDocument.createElement("w:delText");A.textContent=C.textContent,C.hasAttribute("xml:space")&&A.setAttribute("xml:space","preserve"),N.replaceChild(A,C);}),v.appendChild(N),w._element.parentNode?.replaceChild(v,w._element),p===null&&(p=v),m=v;}let y=null,x=null,b=null;if(s==="MODIFICATION"&&e.new_text&&m){let w=m;for(;w&&w.tagName!=="w:p";)w=w.parentNode;let v=w?new ie(w,null):null,N=f.length>0?f[f.length-1]:null,k=this._track_insert_multiline(e.new_text,N,v,d,m,a);if(k.first_node){if(k.first_node.tagName==="w:ins"){let A=m.parentNode;A&&A.tagName==="w:ins"?this._insert_and_split_ins(A,m,k.first_node):qe(k.first_node,m),y=k.first_node;}else y=k.last_ins;x=k.last_p,b=k.last_ins;}}if(s==="DELETION"||s==="MODIFICATION"){if(s==="MODIFICATION"&&f.length===0&&h.length>0&&e.new_text){let w=h[0];if(w.paragraph){let v=w.paragraph._element,N=M(v,"w:r"),k=N.length>0?new Ce(N[N.length-1],w.paragraph):null,C=this._track_insert_multiline(e.new_text,k,w.paragraph,d,null,a);C.first_node&&v.appendChild(C.first_node);}}for(let w of [...h].reverse())if(w.paragraph){let v=w.paragraph._element,N=xe(v);for(;N&&N.tagName!=="w:p";)N=xe(N);if(N&&N.tagName==="w:p"){let k=!this._paragraph_has_visible_content(v),C=B(v,"w:pPr");if(k){let D=B(N,"w:pPr"),j=D?D.cloneNode(true):v.ownerDocument.createElement("w:pPr");if(C){let E=B(C,"w:sectPr");E&&!B(j,"w:sectPr")&&j.appendChild(E.cloneNode(true)),v.removeChild(C);}v.insertBefore(j,v.firstChild),C=j;}C||(C=v.ownerDocument.createElement("w:pPr"),v.insertBefore(C,v.firstChild));let A=B(C,"w:rPr");if(A||(A=v.ownerDocument.createElement("w:rPr"),C.appendChild(A)),!B(A,"w:del")){let D=this._create_track_change_tag("w:del");A.appendChild(D);}let T=Array.from(N.childNodes);for(let D of T)D.nodeType===1&&D.tagName==="w:pPr"||v.appendChild(D);N.parentNode&&N.parentNode.removeChild(N);}}}if(e.comment&&p!==null){let w,v;if(x&&b)w=b,v=x;else {let T=y!==null?y:m;for(w=T,v=T;v&&v.tagName!=="w:p";)v=v.parentNode;}let N=p;for(;N&&N.tagName!=="w:p";)N=N.parentNode;if(!N||!v)return true;let k=g((T,D)=>{let j=T;for(;j.parentNode&&j.parentNode!==D;)j=j.parentNode;return j},"ascend_to_paragraph_child"),C=k(p,N),A=k(w,v);N===v?this._attach_comment(N,C,A,e.comment):this._attach_comment_spanning(N,C,v,A,e.comment);}for(let w of _)if(!this._paragraph_has_visible_content(w)){let N=B(w,"w:pPr");N||(N=w.ownerDocument.createElement("w:pPr"),w.insertBefore(N,w.firstChild));let k=B(N,"w:rPr");if(k||(k=w.ownerDocument.createElement("w:rPr"),N.appendChild(k)),!B(k,"w:del")){let C=this._create_track_change_tag("w:del");k.appendChild(C);}}return true}};function K(t,e){let n=[],r=t.getElementsByTagName("*");for(let s=0;s<r.length;s++){let i=r[s].tagName;(i===e||i.endsWith(":"+e))&&n.push(r[s]);}return n}g(K,"findDescendantsByLocalName");function oa(t){let e=0;function n(o,l){let a=o?o.toString():"",u=l?l.toString():"";return a===u}g(n,"areRunsIdentical");function r(o){let l=["w:t","w:tab","w:br","w:cr","w:delText","w:rPr"];for(let a=0;a<o.childNodes.length;a++){let u=o.childNodes[a];if(u.nodeType===1){let c=u.tagName;if(!l.includes(c))return true}}return false}g(r,"hasSpecialContent");function s(o){let l=Array.from(o.childNodes).filter(u=>u.nodeType===1),a=0;for(;a<l.length-1;){let u=l[a],c=l[a+1];if(u.tagName==="w:r"&&c.tagName==="w:r"&&!r(u)&&!r(c)){let d=B(u,"w:rPr"),f=B(c,"w:rPr");if(n(d,f)){let h=null;for(let p=0;p<u.childNodes.length;p++){let m=u.childNodes[p];m.nodeType===1&&(m.tagName==="w:t"||m.tagName==="w:delText")&&(h=m);}let _=Array.from(c.childNodes).filter(p=>p.nodeType===1);for(let p of _)if(p.tagName!=="w:rPr")if((p.tagName==="w:t"||p.tagName==="w:delText")&&h&&h.tagName===p.tagName){let m=h.textContent||"",y=p.textContent||"",x=m+y;h.textContent=x,x.trim()!==x&&h.setAttribute("xml:space","preserve");}else u.appendChild(p),(p.tagName==="w:t"||p.tagName==="w:delText")&&(h=p);o.removeChild(c),l.splice(a+1,1),e++;continue}}["w:ins","w:del","w:hyperlink","w:sdt","w:smartTag","w:fldSimple","w:sdtContent"].includes(u.tagName)&&s(u),a++;}if(l.length>0){let u=l[l.length-1];["w:ins","w:del","w:hyperlink","w:sdt","w:smartTag","w:fldSimple","w:sdtContent"].includes(u.tagName)&&s(u);}}g(s,"coalesceContainer");let i=M(t.element,"w:p");for(let o of i)s(o);return e?[`Adjacent identical runs coalesced: ${e}`]:[]}g(oa,"coalesce_runs");function aa(t){let e=0,n=["w:rsidR","w:rsidRPr","w:rsidRDefault","w:rsidP","w:rsidDel","w:rsidSect","w:rsidTr"],r=t.element.getElementsByTagName("*");for(let i=0;i<r.length;i++)for(let o of n)r[i].hasAttribute(o)&&(r[i].removeAttribute(o),e++);let s=M(t.element,"w:rsids");for(let i of s)i.parentNode&&(i.parentNode.removeChild(i),e++);return e?[`rsid attributes: ${e} removed`]:[]}g(aa,"strip_rsid");function la(t){let e=0,n=["w14:paraId","w14:textId"],r=t.element.getElementsByTagName("*");for(let s=0;s<r.length;s++)for(let i of n)r[s].hasAttribute(i)&&(r[s].removeAttribute(i),e++);return e?[`Paragraph/text IDs: ${e} removed`]:[]}g(la,"strip_para_ids");function ca(t){let e=M(t.element,"w:proofErr");return e.forEach(n=>n.parentNode?.removeChild(n)),e.length?[`Spell check markers: ${e.length} removed`]:[]}g(ca,"strip_proof_errors");function ua(t){let e=0;for(let n of ["w:rPr","w:pPr"]){let r=M(t.element,n);for(let s of r)(s.childNodes.length===0||s.childNodes.length===1&&s.childNodes[0].nodeType===3&&!s.childNodes[0].textContent?.trim())&&(s.parentNode?.removeChild(s),e++);}return e?[`Empty property elements: ${e} removed`]:[]}g(ua,"strip_empty_properties");function da(t){let e=0,n=M(t.element,"w:rPr");for(let r of n)if(B(r,"w:vanish")||B(r,"w:webHidden")){let s=r.parentNode;s&&s.tagName==="w:r"&&s.parentNode&&(s.parentNode.removeChild(s),e++);}return e?[`Hidden text runs: ${e} removed`]:[]}g(da,"strip_hidden_text");function dr(t){let e=M(t.element,"w:ins").length,n=M(t.element,"w:del").length,r=M(t.element,"w:rPrChange").length+M(t.element,"w:pPrChange").length+M(t.element,"w:sectPrChange").length;return [e,n,r]}g(dr,"count_tracked_changes");function fa(t){let e=new Set;for(let n of ["w:ins","w:del","w:rPrChange","w:pPrChange","w:sectPrChange"])for(let r of M(t.element,n)){let s=r.getAttribute("w:author");s&&e.add(s);}return e}g(fa,"get_track_change_authors");function fr(t){let e=[],n=M(t,"w:t");for(let s of n)s.textContent&&e.push(s.textContent);let r=M(t,"w:delText");for(let s of r)s.textContent&&e.push(s.textContent);return e.join("")}g(fr,"_getElementText");function Ie(t,e=60){let n=t.replace(/\n/g," ").trim();return n.length<=e?n:n.substring(0,e-3)+"..."}g(Ie,"_truncate");function hr(t){let e=t.parentNode;if(e&&e.tagName==="w:rPr"){let n=e.parentNode;if(n&&n.tagName==="w:pPr")return "(paragraph mark)"}return e&&e.tagName==="w:trPr"?"(table row)":"(no visible text)"}g(hr,"_describe_textless_revision");function ha(t){let e=[],n=M(t.element,"w:ins"),r=M(t.element,"w:del");for(let o of n){let l=fr(o).trim();l?e.push(` Accepted insertion: "${Ie(l,60)}"`):e.push(` Accepted insertion: ${hr(o)}`);}for(let o of r){let l=fr(o).trim();l?e.push(` Accepted deletion of: "${Ie(l,60)}"`):e.push(` Accepted deletion of: ${hr(o)}`);}new Tt(t).accept_all_revisions();for(let o of ["w:rPrChange","w:pPrChange","w:sectPrChange"])for(let l of M(t.element,o))l.parentNode?.removeChild(l);let i=n.length+r.length;return i?[`Tracked changes auto-accepted: ${i}`].concat(e):[]}g(ha,"accept_all_tracked_changes");function gt(t){let e=Pe(t.pkg),n=[],r=0,s=0;for(let[i,o]of Object.entries(e))o.resolved?s++:r++,n.push({id:i,...o});return {total:n.length,open:r,resolved:s,comments:n}}g(gt,"get_comments_summary");function pa(t){let e=Pe(t.pkg),n=Object.keys(e);if(n.length===0)return [];let r=[],s=new st(t);for(let[a,u]of Object.entries(e)){let c=u.resolved?"[Resolved]":"[Open]";r.push(` ${c} "${Ie(u.text||"",60)}" (${u.author||"Unknown"})`),s.deleteComment(a);}for(let a of ["w:commentRangeStart","w:commentRangeEnd"])for(let u of M(t.element,a))u.parentNode?.removeChild(u);let i=M(t.element,"w:commentReference");for(let a of i){let u=a.parentNode;u&&((u.tagName==="w:r"||u.tagName.endsWith(":r"))&&Array.from(u.childNodes).filter(d=>d.nodeType===1&&d.tagName!=="w:rPr"&&d.tagName!=="rPr").length<=1?u.parentNode?.removeChild(u):u.removeChild(a));}let o=Object.values(e).filter(a=>a.resolved).length,l=Object.values(e).filter(a=>!a.resolved).length;return [`Comments removed: ${n.length} (${o} resolved, ${l} open)`].concat(r)}g(pa,"remove_all_comments");function _a(t){let e=t.pkg,n=new Set;for(let s of e.parts)if(s.partname.toLowerCase().includes("comments")){n.add(s.partname);let i=s.partname.startsWith("/")?s.partname:"/"+s.partname,o=s.partname.startsWith("/")?s.partname.substring(1):s.partname;n.add(i),n.add(o);}if(n.size===0)return;for(let s of e.parts)if(s.partname.endsWith(".rels")){let i=M(s._element,"Relationship"),o=[];for(let l of i)if((l.getAttribute("Target")||"").toLowerCase().includes("comments")){o.push(l);let u=s.partname.replace("/_rels/","/").replace(".rels",""),c=e.getPartByPath(u);if(c){let d=l.getAttribute("Id");d&&c.rels.delete(d);}}for(let l of o)l.parentNode?.removeChild(l);}let r=e.getPartByPath("[Content_Types].xml");if(r){let s=M(r._element,"Override"),i=[];for(let o of s){let l=o.getAttribute("PartName")||"";(n.has(l)||l.toLowerCase().includes("comments"))&&i.push(o);}for(let o of i)o.parentNode?.removeChild(o);}e.parts=e.parts.filter(s=>!s.partname.toLowerCase().includes("comments"));for(let s of Object.keys(e.unzipped))s.toLowerCase().includes("comments")&&delete e.unzipped[s];}g(_a,"eject_comment_parts");function ma(t,e){let n=new st(t);if(!n.commentsPart)return [];let r=new Set,s=M(n.commentsPart._element,"w:comment");for(let i of s){let o=i.getAttribute("w:author");if(o&&(r.add(o),i.setAttribute("w:author",e)),i.hasAttribute("w:initials")){let l=e.split(" ").filter(Boolean).map(a=>a[0]).join("").toUpperCase();i.setAttribute("w:initials",l);}}return r.size?[`Comment authors replaced: ${Array.from(r).sort().join(", ")} \u2192 "${e}"`]:[]}g(ma,"replace_comment_authors");function ga(t,e){let n=new Set;for(let r of ["w:ins","w:del","w:rPrChange","w:pPrChange"])for(let s of M(t.element,r)){let i=s.getAttribute("w:author");i&&(n.add(i),s.setAttribute("w:author",e));}return n.size?[`Track change authors replaced: ${Array.from(n).sort().join(", ")} \u2192 "${e}"`]:[]}g(ga,"replace_change_authors");function wa(t){let e=0,n="2025-01-01T00:00:00Z";for(let r of ["w:ins","w:del","w:rPrChange","w:pPrChange"])for(let s of M(t.element,r))s.hasAttribute("w:date")&&(s.setAttribute("w:date",n),e++);return e?[`Track change timestamps: ${e} normalized`]:[]}g(wa,"normalize_change_dates");function ya(t){let e=0,n="2025-01-01T00:00:00Z";for(let r of t.pkg.parts)if(r.contentType.includes("comments")){for(let s of M(r._element,"w:comment"))s.hasAttribute("w:date")&&(s.setAttribute("w:date",n),e++);for(let s of M(r._element,"w16cex:commentExtensible"))s.hasAttribute("w16cex:dateUtc")&&(s.setAttribute("w16cex:dateUtc",n),e++);}return e?[`Comment timestamps: ${e} normalized`]:[]}g(ya,"normalize_comment_dates");function va(t){let e=[],n=t.pkg.getPartByPath("docProps/core.xml");if(n){K(n._element,"creator").forEach(u=>{u.textContent&&(e.push(`Author: ${u.textContent}`),u.textContent="");}),K(n._element,"lastModifiedBy").forEach(u=>{u.textContent&&(e.push(`Last modified by: ${u.textContent}`),u.textContent="");}),K(n._element,"title").forEach(u=>{u.textContent&&e.push(`Title kept (review manually): "${u.textContent}"`);});let l=[["category","Category"],["keywords","Keywords"],["subject","Subject"],["contentStatus","Content status"],["description","Description/comments"],["identifier","Identifier"],["language","Language"],["version","Version"]];for(let[u,c]of l)K(n._element,u).forEach(d=>{d.textContent&&(e.push(`${c}: ${d.textContent}`),d.textContent="");});K(n._element,"revision").forEach(u=>{u.textContent&&parseInt(u.textContent)>1&&(e.push(`Revision count: ${u.textContent} \u2192 1`),u.textContent="1");});}let r=t.pkg.getPartByPath("docProps/app.xml");if(r){let s=r._element,i=["TotalTime","Words","Characters","Paragraphs","Lines","CharactersWithSpaces"];for(let l of i)K(s,l).forEach(a=>{a.textContent&&a.textContent!=="0"&&(l==="TotalTime"&&e.push(`Total editing time: ${a.textContent} minutes`),a.textContent="0");});let o=["Template","Manager","Company"];for(let l of o)K(s,l).forEach(a=>{a.textContent&&(e.push(`${l}: ${a.textContent}`),a.textContent="");});}return e.length?["Metadata scrubbed:",...e.map(s=>` ${s}`)]:[]}g(va,"scrub_doc_properties");function ba(t){let e=false,n="1970-01-01T00:00:00Z",r=t.pkg.getPartByPath("docProps/core.xml");if(r)for(let s of ["created","modified","lastPrinted"])K(r._element,s).forEach(i=>{i.textContent&&i.textContent!==n&&(i.textContent=n,e=true);});return e?["Timestamps normalized to epoch"]:[]}g(ba,"scrub_timestamps");function ai(t,e,n){let r=t.pkg,s=g(o=>o.startsWith("/")?o.substring(1):o,"normalized");for(let o of r.parts){if(!o.partname.endsWith(".rels"))continue;let l=[];for(let a of M(o._element,"Relationship")){let u=a.getAttribute("Target")||"";if(n(u)){l.push(a);let c=o.partname.replace("/_rels/","/").replace(".rels",""),d=r.getPartByPath(c);if(d){let f=a.getAttribute("Id");f&&d.rels.delete(f);}}}l.forEach(a=>a.parentNode?.removeChild(a));}let i=r.getPartByPath("[Content_Types].xml");if(i){let o=[];for(let l of M(i._element,"Override")){let a=l.getAttribute("PartName")||"";e(s(a))&&o.push(l);}o.forEach(l=>l.parentNode?.removeChild(l));}r.parts=r.parts.filter(o=>!e(s(o.partname)));for(let o of Object.keys(r.unzipped))e(s(o))&&delete r.unzipped[o];}g(ai,"ejectPackageMembers");function xa(t){let e=g(s=>s.startsWith("customXml/"),"isCustomXml"),n=t.pkg.parts.filter(s=>e(s.partname.startsWith("/")?s.partname.substring(1):s.partname)),r=Object.keys(t.pkg.unzipped).filter(e);if(n.length===0&&r.length===0)return [];ai(t,e,s=>s.includes("customXml"));for(let s of M(t.element,"w:sdtPr"))Pr(s,"w:dataBinding").forEach(i=>s.removeChild(i));return [`Custom XML parts: ${Math.max(n.length,r.length)} removed`]}g(xa,"strip_custom_xml");var en="docProps/custom.xml";function Na(t){let e=t.pkg.getPartByPath(en),n=Object.keys(t.pkg.unzipped).includes(en);if(!e&&!n)return [];let r=[];if(e)for(let i of K(e._element,"property")){let o=i.getAttribute("name")||"(unnamed)",l=(i.textContent||"").trim();r.push(` Custom property removed: ${o} = "${Ie(l,60)}"`);}return ai(t,i=>i===en,i=>i.includes("docProps/custom.xml")),[`Custom document properties: ${Math.max(r.length,1)} removed (docProps/custom.xml)`].concat(r)}g(Na,"strip_custom_properties");function ka(t){let e=t.pkg.getPartByPath("word/settings.xml");if(!e)return [];let n=[],r=false;for(let i of K(e._element,"docVars")){for(let o of Array.from(i.childNodes)){let l=o,a=l.tagName||"";(a==="docVar"||a.endsWith(":docVar"))&&n.push(l.getAttribute("w:name")||l.getAttribute("name")||"(unnamed)");}i.parentNode?.removeChild(i),r=true;}for(let i of K(e._element,"docVar"))n.push(i.getAttribute("w:name")||i.getAttribute("name")||"(unnamed)"),i.parentNode?.removeChild(i),r=true;if(!r)return [];let s=Array.from(new Set(n)).sort().join(", ")||"(unnamed)";return [`Document variables: ${n.length} removed (${s})`]}g(ka,"strip_document_variables");function Ea(t){let e=0;for(let n of K(t.element,"docPr")){let r=n.getAttribute("descr");if(r){let s=r.length<10,i=r.includes(".")&&r.length<60;(s||i)&&(n.removeAttribute("descr"),e++);}}return e?[`Image alt text: ${e} auto-generated descriptions removed`]:[]}g(Ea,"strip_image_alt_text");function Aa(t){let e=[],n=new Set;for(let r of t.pkg.parts){let s=String(r.partname),i;if(s.startsWith("/word/header"))i="header";else if(s.startsWith("/word/footer"))i="footer";else if(s==="/word/document.xml")i="body";else continue;let o;try{o=K(r._element,"textpath");}catch{continue}for(let l of o){let a=(l.getAttribute("string")||"").trim(),u=`${i}${a}`;if(n.has(u))continue;n.add(u);let c=a?`"${Ie(a,60)}"`:"(no text)";e.push(`Watermark-like text object in ${i}: ${c} \u2014 NOT removed. It remains in the document package and may render in other applications; review and remove it in Word if it must not reach the counterparty.`);}}return e}g(Aa,"detect_watermarks");function Ca(t){let e=["sharepoint.com","onedrive.com",".internal","intranet","localhost","10.","192.168.","172.16."],n=[],r=t.pkg.getOrCreateRelsPart(t.part.partname);for(let s of M(r._element,"Relationship"))if(s.getAttribute("TargetMode")==="External"){let i=s.getAttribute("Target")||"";for(let o of e)if(i.toLowerCase().includes(o.toLowerCase())){n.push(`Hyperlink targets internal URL: ${Ie(i,80)}`);break}}return n}g(Ca,"audit_hyperlinks");function Pa(t,e,n=2){if(t===e)return 0;if(Math.abs(t.length-e.length)>n)return n+1;if(t.length===0)return e.length<=n?e.length:n+1;if(e.length===0)return t.length<=n?t.length:n+1;if(t.length>e.length){let s=t;t=e,e=s;}let r=Array.from({length:t.length+1},(s,i)=>i);for(let s=1;s<=e.length;s++){let i=[s],o=s;for(let l=1;l<=t.length;l++){let a=t[l-1]===e[s-1]?0:1,u=Math.min(r[l]+1,i[l-1]+1,r[l-1]+a);i.push(u),u<o&&(o=u);}if(o>n)return n+1;r=i;}return r[t.length]<=n?r[t.length]:n+1}g(Pa,"boundedLevenshtein");function Ta(t){let e="",n=M(t._element,"w:r");for(let r of n)e+=Me(new Ce(r,t));return e}g(Ta,"_get_paragraph_text");var kn="[A-Z][A-Za-z0-9\\s\\-&'\u2019]{1,60}",Ia=new RegExp(`^(?:[\\d.\\-()a-zA-Z]+\\s*)?["\u201C](${kn})["\u201D]`,"d"),Sa=new RegExp(`(?<=[.;:!?])\\s+(?:[\\d.\\-()a-zA-Z]+\\s+)?["\u201C](${kn})["\u201D]`,"dg"),$a=new RegExp(`\\([^)]*?["\u201C](${kn})["\u201D][^)]*?\\)`,"dg");function Oa(t){let e=[],n=Ia.exec(t);n&&n.indices&&n.indices[1]&&e.push([n.indices[1][0],n[1].trim()]);for(let i of t.matchAll(Sa)){let o=i.indices;o&&o[1]&&e.push([o[1][0],i[1].trim()]);}for(let i of t.matchAll($a)){let o=i.indices;o&&o[1]&&e.push([o[1][0],i[1].trim()]);}let r=[],s=new Set;e.sort((i,o)=>i[0]-o[0]);for(let[i,o]of e)s.has(i)||(s.add(i),r.push(o));return r}g(Oa,"extract_terms_from_paragraph");function Da(t,e){let n={},r=new Set,s={},i=[];for(let p of Oe(t)){if(!(p instanceof ie))continue;let m=Ta(p).trim();if(!m)continue;for(let b of Oa(m))n[b]?r.add(b):n[b]={count:0};let y=m.length>60?m.substring(0,60)+"...":m,x=M(p._element,"*");for(let b of x){if(b.tagName==="w:bookmarkStart"){let v=b.getAttribute("w:name");v&&(!v.startsWith("_")||v.startsWith("_Ref"))&&(s[v]||(s[v]={anchored_to:y,referenced_from:[]}));}let w=null;if(b.tagName==="w:fldSimple"){let N=(b.getAttribute("w:instr")||"").trim().split(/\s+/);N.length>1&&N[0]==="REF"&&(w=N[1]);}else if(b.tagName==="w:instrText"){let N=(b.textContent||"").trim().split(/\s+/);N.length>1&&N[0]==="REF"&&(w=N[1]);}w&&i.push([w,y]);}}for(let[p,m]of i)s[p]&&s[p].referenced_from.push(m);let o=[],l=Object.keys(n);if(l.length>0){let p=l.sort((b,w)=>w.length-b.length),m=g(b=>b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegExp"),y=p.map(m).join("|"),x=new RegExp(`(?<!["\u201C])\\b(${y})\\b(?![\u201D"])`,"g");for(let b of e.matchAll(x)){let w=b[1];n[w]&&n[w].count++;}for(let b of l)n[b].count===0&&(delete n[b],r.has(b)||o.push(`[Warning] Unused Definition: '${b}' is defined but never used.`));}for(let p of r)o.push(`[Error] Duplicate Definition: '${p}' is defined multiple times.`);let a=new Set(["The","This","That","Such","A","An","Any","All","Some","No","Every","Each","As","In","Of","For","To","On","By","With"]),u=/\b[A-Z][a-zA-Z]*(?:\s+[A-Z][a-zA-Z]*)*\b/g,c=new Set(e.match(u)||[]),d=new Set(Object.keys(n)),f={};for(let p of d){let m=p[0].toLowerCase();f[m]||(f[m]=[]),f[m].push(p);}let h={};for(let p of c){let m=p.trim(),y=m.split(/\s+/);for(;y.length>0;){let w=y[0],v=w.charAt(0).toUpperCase()+w.slice(1).toLowerCase();if(a.has(v))y.shift();else break}if(m=y.join(" "),m.length<4||d.has(m))continue;let x=m[0].toLowerCase(),b=f[x]||[];if(m.length>5)for(let[w,v]of Object.entries(f))w!==x&&(b=b.concat(v));for(let w of b){if(Math.abs(m.length-w.length)>2||m===w+"s"||m===w+"es"||w===m+"s"||w===m+"es")continue;let v=Pa(m,w,2);v===0||v>2||w.length<=5&&(v>1||m[0].toLowerCase()!==w[0].toLowerCase())||(h[w]||(h[w]=[]),h[w].includes(m)||h[w].push(m));}}for(let[p,m]of Object.entries(h)){m.sort();let y=m.map(x=>`'${x}'`).join(", ");o.push(`[Info] Possible Typos for '${p}': Found ${y}`);}function _(p){return p.startsWith("[Error]")?0:p.startsWith("[Warning]")?1:2}return g(_,"diag_sort_key"),o.sort((p,m)=>{let y=_(p),x=_(m);return y!==x?y-x:p.localeCompare(m)}),[n,o,s]}g(Da,"extract_all_domain_metadata");function Ma(t){let e=[],n=t.pkg.getPartByPath("word/settings.xml");if(!n)return e;let r=g(o=>{if(!o.hasAttribute("w:val"))return true;let l=(o.getAttribute("w:val")||"").toLowerCase();return l!=="0"&&l!=="false"&&l!=="off"},"isTruthy"),s=K(n._element,"removePersonalInformation");s.length>0&&r(s[0])&&e.push("[Warning] Privacy flag `removePersonalInformation` is enabled in word/settings.xml. Microsoft Word will strip the `w:author`, `w:initials`, and `w:date` attributes from every tracked change and comment the next time this document is opened and saved. Edits made by this agent will lose attribution, breaking audit trails and any multi-turn workflow that relies on identifying prior edits.");let i=K(n._element,"removeDateAndTime");return i.length>0&&r(i[0])&&e.push("[Warning] Privacy flag `removeDateAndTime` is enabled in word/settings.xml. Microsoft Word will strip the `w:date` attribute from every tracked change and comment the next time this document is opened and saved. Timestamps on this agent's edits will be lost on the next Word save."),e}g(Ma,"extract_document_settings_warnings");function Ra(t,e){let[n,r,s]=Da(t,e),i=Ma(t),o=[`
150
+ `)&&N.length===P.length){let C=[],T=u,M=false;for(let j=0;j<N.length;j++){let B=N[j],$=P[j];if(B!==$){let I=e.comment&&!M?e.comment:null,E=this._word_diff_sub_edits(B,$,T,I,false,s);E.some(S=>S.comment!==null&&S.comment!==void 0)&&(M=true);for(let S of E)S._split_group_id=u,C.push(S);}T+=B.length+2;}if(C.length>0){for(let j of C)l.push(j);continue}}if(!y&&x){l.push({type:"modify",target_text:"",new_text:x,comment:e.comment,_resolved_start_idx:k,_match_start_index:k,_internal_op:"INSERTION",_active_mapper_ref:s});continue}let A=this._word_diff_sub_edits(d,f,u,e.comment,false,s);for(let C of A)C._split_group_id=u,l.push(C);}return l.length===0?null:r==="all"||l.length>1?l:l[0]}_insert_and_split_ins(e,n,r,i=false){let o=e.parentNode;if(!o)return;let s=e.cloneNode(false),a=e.cloneNode(false),l=false;for(let u of Array.from(e.childNodes))e.removeChild(u),i&&u===n&&(l=true),l?a.appendChild(u):(s.appendChild(u),u===n&&(l=true));s.childNodes.length>0&&o.insertBefore(s,e),o.insertBefore(r,e),a.childNodes.length>0&&o.insertBefore(a,e),o.removeChild(e);}_apply_comment_only(e,n,r,i,o){let s=n.find_target_runs_by_index(r,i,o);if(s.length===0)return false;if(!e.comment)return true;let a=s[0]._element,l=s[s.length-1]._element,u=a;for(;u&&u.tagName!=="w:p";)u=u.parentNode;let c=l;for(;c&&c.tagName!=="w:p";)c=c.parentNode;if(!u||!c)return false;let d=g((_,p)=>{let m=_;for(;m.parentNode&&m.parentNode!==p;)m=m.parentNode;return m},"ascend_to_paragraph_child"),f=d(a,u),h=d(l,c);return u===c?this._attach_comment(u,f,h,e.comment):this._attach_comment_spanning(u,f,c,h,e.comment),true}_apply_single_edit_indexed(e,n,r){let i=e._internal_op,o=e._active_mapper_ref||this.mapper,s=e._resolved_start_idx!==void 0&&e._resolved_start_idx!==null?e._resolved_start_idx:e._match_start_index||0,a=e.target_text?e.target_text.length:0;i==null&&(!e.target_text&&e.new_text?i="INSERTION":e.target_text&&!e.new_text?i="DELETION":i="MODIFICATION");let l=this._edit_declares_emphasis(e),u=null;if(i==="STYLE_ONLY"||i==="STYLE_AND_TEXT"){let[y,x]=o.get_insertion_anchor(s,r),k=null;if(x)k=x._element;else if(y){let N=y._element;for(;N&&N.tagName!=="w:p";)N=N.parentNode;k=N;}if(k&&e._new_style&&(i==="STYLE_ONLY"?this._set_paragraph_style(k,e._new_style,this._getNextId()):u=k),i==="STYLE_ONLY"){if(e.comment){let N=o.find_target_runs_by_index(s,a,r);if(N.length>0){let P=N[0]._element,A=N[N.length-1]._element,C=P;for(;C&&C.tagName!=="w:p";)C=C.parentNode;let T=A;for(;T&&T.tagName!=="w:p";)T=T.parentNode;if(C&&T){let M=g(($,I)=>{let E=$;for(;E.parentNode&&E.parentNode!==I;)E=E.parentNode;return E},"ascend_to_paragraph_child"),j=M(P,C),B=M(A,T);C===T?this._attach_comment(C,j,B,e.comment):this._attach_comment_spanning(C,j,T,B,e.comment);}}}return true}e.target_text&&e.new_text?i="MODIFICATION":!e.target_text&&e.new_text?i="INSERTION":e.target_text&&!e.new_text?i="DELETION":i="COMMENT_ONLY";}let c=["DELETION","MODIFICATION"].includes(i)?(e._reserved_del_id??null)!==null?String(e._reserved_del_id):this._getNextId():null,d=["INSERTION","MODIFICATION"].includes(i)?(e._reserved_ins_id??null)!==null?String(e._reserved_ins_id):this._getNextId():null;if(u&&e._new_style&&this._set_paragraph_style(u,e._new_style,d??c??this._getNextId()),i==="COMMENT_ONLY")return this._apply_comment_only(e,o,s,a,r);if(i==="INSERTION"){let y=e.new_text||"",x=null,k=typeof o.part_boundary_at=="function"?o.part_boundary_at(s):null,N=!e.target_text&&(e._parent_edit_ref===void 0||e._parent_edit_ref===null);if(k!==null&&N){let[$,I]=k,E=o.part_kind_of($),S=o.part_kind_of(I);if(E==="body"&&S!=="body"){let D=o.spans.filter(U=>U.run!==null&&U.part_index===$);D.length>0&&(x=D[D.length-1]);}}let P,A;if(x!==null?(P=x.run,A=x.paragraph,y.startsWith(`
151
+ `)||(y=`
124
152
 
125
- ---`,"","<!-- READONLY_BOUNDARY_START -->","# Document Structure (Read-Only)","The content below is metadata describing the document's reference structure. Do not include this section in any tracked changes or edits \u2014 it is for your context only and will be discarded on write."],l=false;if(i.length>0){l=true,o.push(`
126
- ## Document Settings`);for(let a of i)o.push(`- ${a}`);}if(Object.keys(n).length>0){l=true,o.push(`
127
- ## Defined Terms`);for(let[a,u]of Object.entries(n))o.push(`- "${a}" \u2014 used ${u.count} time${u.count===1?"":"s"}.`);}if(r.length>0){l=true,o.push(`
128
- ## Semantic Diagnostics`);for(let a of r)o.push(`- ${a}`);}if(Object.keys(s).length>0){l=true,o.push(`
129
- ## Named Anchors`);for(let[a,u]of Object.entries(s)){o.push(`- ${a} \u2192 Anchored to: "${u.anchored_to}"`);for(let c of u.referenced_from)o.push(` - Referenced from: "${c}"`);}}return l?o.join(`
130
- `):""}g(Ra,"build_structural_appendix");async function Be(t,e=false,n=true){let r=await ce.load(t);return Fe(r,e,n)}g(Be,"extractTextFromBuffer");function Fe(t,e=false,n=true,r=false,s=false){let i=Pe(t.pkg),o=[],l=new Map,a=s?{part_ranges:[],tables:[]}:null,u=0;for(let[d,f]of xn(t)){let h=o.length>0?u+2:u,_=En(d,i,e,h,r?l:void 0,a?a.tables:void 0);_&&(o.length>0&&(u+=2),o.push(_),a&&a.part_ranges.push([u,u+_.length,f]),u+=_.length);}let c=o.join(`
131
-
132
- `);if(n){let d=Ra(t,c);d&&(c+=d);}return r?{text:c,paragraph_offsets:l}:a?{text:c,structure:a}:c}g(Fe,"_extractTextFromDoc");function En(t,e,n,r,s,i){let o=t.part||t,[l,a]=Qe(o),u=[],c=r,d=true,f=true;if(t.constructor&&t.constructor.name==="NotesPart"){let _=`---
133
- ${t.note_type==="fn"?"## Footnotes":"## Endnotes"}`;u.push(_),c+=_.length,d=false;}for(let h of Oe(t)){d||(c+=2);let _=c;if(h.constructor.name==="FootnoteItem"){let p=En(h,e,n,_,s);p?(u.push(p),c=_+p.length,d=false):d||(c-=2);}else if(h instanceof ie){let p=$e(h,l,a);f&&t.constructor.name==="FootnoteItem"&&(p=`[^${t.note_type}-${t.id}]: `+p);let m=lt(h,e,n,l,a),y=p+m;u.push(y),s&&s.set(h._element,[_,y.length]),c=_+y.length,f=false,d=false;}else if(h instanceof Se){let p=i?{start:_,end:_,rows:[]}:null,m=It(h,e,n,_,s,p);m?(u.push(m),c=_+m.length,d=false,p&&i&&(p.end=_+m.length,i.push(p))):d||(c-=2),f=false;}}return u.join(`
134
-
135
- `)}g(En,"_extract_blocks");function It(t,e,n,r,s,i){let o=[],l=0,a=r;for(let u of t.rows){let c=[],d=new Set,f=B(u._element,"w:trPr"),h=f?B(f,"w:ins"):null,_=f?B(f,"w:del"):null;if(n&&_)continue;let p=a+(l>0?1:0),y=p+(!n&&h||!n&&_?4:0),x=true;for(let w of u.cells){if(d.has(w))continue;d.add(w),x||(y+=3);let v=En(w,e,n,y,s);if(!n){let{paraId:N}=Ir(w._element,!v||v.trim()==="");if(N){let C=`${v?" ":""}{#cell:${N}}`;v=v+C;}}c.push(v),y+=v.length,x=false;}let b=c.join(" | ");if(n||(h?b=`{++ ${b} ++}{>>[Chg:${h.getAttribute("w:id")} insert] ${h.getAttribute("w:author")||"Unknown"}<<}`:_&&(b=`{-- ${b} --}{>>[Chg:${_.getAttribute("w:id")} delete] ${_.getAttribute("w:author")||"Unknown"}<<}`)),o.push(b),a=p+b.length,i&&i.rows.push({start:p,end:a,cells:[...c]}),l++,l===1){let w=c.length;if(w>0){let v=Array(w).fill("---").join(" | ");o.push(v),a+=1+v.length;}}}return o.join(`
136
- `)}g(It,"extract_table");function lt(t,e,n,r,s){let i=[],o={},l={},a=new Set,u={},c=[],d="",f=["",""],h=["",""],_=Array.from(Pt(t)),p=qr(t,r,s),m=Ct(t,r,s),y=p;for(let x=0;x<_.length;x++){let b=_[x];if(b instanceof Ce){let[w,v]=Jr(b,m),N=Me(b);if(n&&Object.keys(l).length>0)continue;if(y){if(!N||!N.trim())continue;y=false;}let k=$o(N,w,v);if(k){let C=n?["",""]:ja(o,l,a,u),A=[w,v];if(d&&C[0]===f[0]&&C[1]===f[1]){let T=A[0].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),D=A[0]!==""||A[1]!==""?k.match(new RegExp("^(\\s*)"+T)):null;A[0]===h[0]&&A[1]===h[1]&&h[0]!==""&&d.endsWith(h[1])&&D!==null?d=d.slice(0,-h[1].length)+D[1]+k.slice(D[0].length):d+=k,h=A;}else d&&i.push(`${f[0]}${d}${f[1]}`),d=k,f=C,h=A;if(!n){(Object.keys(o).length>0||Object.keys(l).length>0||a.size>0||Object.keys(u).length>0)&&c.push([{...o},{...l},new Set(a),{...u}]);let D=false;if(Object.keys(o).length>0||Object.keys(l).length>0||Object.keys(u).length>0||a.size>0){let E=x+1,I=false,P=Object.keys(o).length,S=Object.keys(l).length,$=Object.keys(u).length,O=new Set(a);for(;E<_.length;){let F=_[E];if(F instanceof Ce){if(!Me(F)){E++;continue}(P>0||S>0||$>0||O.size>0)&&(I=true);break}else {let W=F;W.type==="ins_start"?P++:W.type==="ins_end"?P=Math.max(0,P-1):W.type==="del_start"?S++:W.type==="del_end"?S=Math.max(0,S-1):W.type==="fmt_start"?$++:W.type==="fmt_end"?$=Math.max(0,$-1):W.type==="start"?O.add(W.id):W.type==="end"&&O.delete(W.id);}E++;}I&&(D=true);}if(!D&&c.length>0){let E=pr(c,e);E&&(d&&(i.push(`${f[0]}${d}${f[1]}`),d="",f=["",""],h=["",""]),i.push(`{>>${E}<<}`)),c.length=0;}}}}else {let w=b;if(y=false,["ins_start","ins_end","del_start","del_end","fmt_start","fmt_end"].includes(w.type)||d&&(i.push(`${f[0]}${d}${f[1]}`),d="",f=["",""],h=["",""]),w.type==="start")a.add(w.id);else if(w.type==="end")a.delete(w.id);else if(w.type==="ins_start")o[w.id]=w;else if(w.type==="ins_end")delete o[w.id];else if(w.type==="del_start")l[w.id]=w;else if(w.type==="del_end")delete l[w.id];else if(w.type==="fmt_start")u[w.id]=w;else if(w.type==="fmt_end")delete u[w.id];else if(w.type==="image"){if(!(n&&Object.keys(l).length>0)){let v=(w.date||"image").replace(/\]/g,")").replace(/\n/g," ");i.push(`![${v}](docx-image:${w.id})`);}}else w.type==="footnote"||w.type==="endnote"?(d&&(i.push(`${f[0]}${d}${f[1]}`),d="",f=["",""],h=["",""]),i.push(`[^${w.type==="footnote"?"fn":"en"}-${w.id}]`)):w.type==="hyperlink_start"?(d&&(i.push(`${f[0]}${d}${f[1]}`),d="",f=["",""],h=["",""]),i.push("[")):w.type==="hyperlink_end"?(d&&(i.push(`${f[0]}${d}${f[1]}`),d="",f=["",""],h=["",""]),i.push(`](${w.date})`)):w.type==="xref_start"?(d&&(i.push(`${f[0]}${d}${f[1]}`),d="",f=["",""],h=["",""]),i.push("[~")):w.type==="xref_end"?(d&&(i.push(`${f[0]}${d}${f[1]}`),d="",f=["",""],h=["",""]),i.push(`~](#${w.id})`)):w.type==="bookmark"&&(d&&(i.push(`${f[0]}${d}${f[1]}`),d="",f=["",""],h=["",""]),i.push(`{#${w.id}}`));}}if(d&&i.push(`${f[0]}${d}${f[1]}`),c.length>0){let x=pr(c,e);x&&i.push(`{>>${x}<<}`);}return i.join("")}g(lt,"build_paragraph_text");function ja(t,e,n,r){return Object.keys(e).length>0?["{--","--}"]:Object.keys(t).length>0?["{++","++}"]:n.size>0||Object.keys(r).length>0?["{==","==}"]:["",""]}g(ja,"_get_wrappers");function pr(t,e){let n=[],r=[],s=new Set,i=Gr(t),o=g(a=>i[a]?` (pairs with ${i[a]})`:"","pairSuffix");for(let[a,u,c,d]of t){let f=g(function(p){if(!e[p])return;let m=`Com:${p}`;if(s.has(m))return;let y=e[p],x=`[${m}] ${y.author}`;if(y.date&&(x+=` @ ${y.date}`),y.resolved&&(x+="(RESOLVED)"),r.push(`${x}: ${Mr(y.text)}`),s.add(m),h[p]){let b=h[p].sort((w,v)=>(e[w]?.date||"").localeCompare(e[v]?.date||""));for(let w of b)f(w);}},"render_comment2");for(let[p,m]of Object.entries(a)){let y=`Chg:${p}`;s.has(y)||(n.push(`[${y} insert] ${m.author||"Unknown"}${o(p)}`),s.add(y));}for(let[p,m]of Object.entries(u)){let y=`Chg:${p}`;s.has(y)||(n.push(`[${y} delete] ${m.author||"Unknown"}${o(p)}`),s.add(y));}for(let[p,m]of Object.entries(d)){let y=`Chg:${p}`;s.has(y)||(n.push(`[${y} format] ${m.author||"Unknown"}`),s.add(y));}let h={};for(let[p,m]of Object.entries(e)){let y=m.parent_id;y&&(h[y]||(h[y]=[]),h[y].push(p));}let _=Array.from(c).sort();for(let p of _)f(p);}return [...n,...r].join(`
137
- `)}g(pr,"_build_merged_meta_block");var Ba=["{++","{--","{~~","{==","{>>"],Fa=/^> \*\*File Path:\*\*[^\n]*\n+/,Wa=/^> \*\*Page (\d+) of (\d+)\*\*[^\n]*\n+(?:---\n+)?/,za=/\n+---\n+> \*\*Continues on page (\d+) of (\d+)\.\*\*[^\n]*\s*$/,La=/\n+---\n+> \*\*Appendix available\.\*\*[^\n]*\s*$/,Ua=2e3,St=class extends Error{static{g(this,"TextRevisionError");}constructor(t){super(t),this.name="TextRevisionError";}},Ha=class extends St{static{g(this,"TextRevisionVerificationError");}constructor(t,e,n,r,s){super(t),this.unverified_path=e,this.output_path=n,this.stats=r,this.unverified_bytes=s,this.name="TextRevisionVerificationError";}unverified_path;output_path;stats;unverified_bytes};function qa(t){if(t&&t.trim())return t.trim();let e="".trim();return e||"Adeu AI (TS)"}g(qa,"get_default_author");function Ja(t){if(Ba.some(e=>t.includes(e)))throw new St("Revised text contains CriticMarkup tokens ({++..++}, {--..--}, {~~..~>..~~}, {==..==}, {>>..<<}). `apply_text_revision` compares text against the document's CLEAN view, so CriticMarkup tokens would be diffed into the document as literal prose.")}g(Ja,"check_criticmarkup");function Xa(t){t=t.replace(Fa,"");let e=null,n=null,r=Wa.exec(t);r&&(e=parseInt(r[1],10),n=parseInt(r[2],10),t=t.slice(r[0].length)),t=t.replace(La,"");let s=za.exec(t);return s&&(e===null&&(e=parseInt(s[1],10)-1),n===null&&(n=parseInt(s[2],10)),t=t.slice(0,s.index)),{text:t,page:e,total:n}}g(Xa,"strip_page_chrome");function Ga(t,e,n=false,r){if(n)return;let s=t.length,i=e.length;if(s===0)return;let o=(s-i)/s,l=s>=Ua?.5:.75;if(o<=l)return;let a=r?`'${r}'`:"The revised text";throw new St(`${a} is ~${Math.floor(o*100)}% shorter than the document's clean text (${i.toLocaleString("en-US")} vs ${s.toLocaleString("en-US")} characters, threshold is >${Math.floor(l*100)}% deletion). Applying it would delete the majority of the document as tracked deletions.
153
+ `+y)):e._insert_host_el?(P=null,A=null):[P,A]=o.get_insertion_anchor(s,r),!P&&!A&&!e._insert_host_el||Z._introduces_table_row_text(o,s,1,"",y))return false;let C=y,T=x===null&&/\n\s*$/.test(C),M=null;{let $=o.spans.filter(I=>I.paragraph!==null&&I.start===s);$.length>0&&$[0].paragraph&&(M=$[0].paragraph._element);}if(T&&M&&M.parentNode){let $=M.parentNode,I=this.doc.part._element.ownerDocument,E=C.split(/[\r\n]+/).filter(z=>z!==""),S=null,D=null,U=null;for(let z of E){let[W,L]=this._parse_markdown_style(z),X=I.createElement("w:p");if(L)this._set_paragraph_style(X,L);else {let be=O(M,"w:pPr");be&&X.appendChild(this._clone_pPr_scrubbing_headings(be,M));}let q=O(X,"w:pPr");q||(q=I.createElement("w:pPr"),X.insertBefore(q,X.firstChild));let Y=O(q,"w:rPr");Y||(Y=I.createElement("w:rPr"),q.appendChild(Y)),Y.appendChild(this._create_track_change_tag("w:ins","",d));let _e=this._build_tracked_ins_for_line(W,P,d,I,l);_e&&X.appendChild(_e),$.insertBefore(X,M),S||(S=X),D=X,U=_e;}if(S){if(e.comment&&D&&U){let z=g((L,X)=>{let q=L;for(;q.parentNode&&q.parentNode!==X;)q=q.parentNode;return q},"ascend"),W=R(S,"w:ins")[0]||S;this._attach_comment_spanning(S,z(W,S),D,z(U,D),e.comment);}return true}}let j=this._track_insert_multiline(y,P,A,d,null,l,s===0||P===null&&A!==null);if(!j.first_node)return false;if(j.first_node.tagName==="w:ins"){if(e._insert_host_el)e._insert_host_el.appendChild(j.first_node);else if(P){let $=P._element,I=$.parentNode;I&&I.tagName==="w:del"&&($=I,I=$.parentNode);let E=s===0;I&&I.tagName==="w:ins"?this._insert_and_split_ins(I,$,j.first_node,E):E&&I?I.insertBefore(j.first_node,$):nt(j.first_node,$);}else if(A){let $=A._element,I=$.firstChild;for(;I&&I.tagName==="w:pPr";)I=I.nextSibling;$.insertBefore(j.first_node,I);}}if(e.comment){let $=g((I,E)=>{let S=I;for(;S.parentNode&&S.parentNode!==E;)S=S.parentNode;return S},"ascend_to_paragraph_child");if(j.last_p&&j.last_ins){let I=j.first_node;for(;I&&I.tagName!=="w:p";)I=I.parentNode;if(I){let E=j.first_node;j.first_node.tagName==="w:p"&&(E=R(j.first_node,"w:ins")[0]||j.first_node);let S=$(E,I),D=$(j.last_ins,j.last_p);this._attach_comment_spanning(I,S,j.last_p,D,e.comment);}}else {let I=j.first_node;for(;I&&I.tagName!=="w:p";)I=I.parentNode;if(I){let E=j.first_node;j.first_node.tagName==="w:p"&&(E=R(j.first_node,"w:ins")[0]||j.first_node);let S=$(E,I);this._attach_comment(I,S,S,e.comment);}}}return true}if((i==="DELETION"||i==="MODIFICATION")&&a&&o.part_ranges.filter(y=>y[1]>y[0]).length>1){let y=new Set;for(let x of o.spans)x.run!==null&&x.end>s&&x.start<s+a&&y.add(x.part_index);if(y.size>1)return false}if((i==="DELETION"||i==="MODIFICATION")&&a){let y=this._apply_gate_refusal(o,s,a,e._parent_edit_ref?.type==="set_field");if(y)return e._error_msg||(e._error_msg=y),false}let f=o.find_target_runs_by_index(s,a,r),h=o.get_virtual_spans_in_range(s,a);if(f.length===0&&h.length===0)return false;let _=new Set;for(let y of f){let x=y._element.parentNode;for(;x&&x.tagName!=="w:p";)x=x.parentNode;x&&_.add(x);}let p=null,m=null;for(let y of f){let x=this._create_track_change_tag("w:del","",c),k=y._element.cloneNode(true);Array.from(k.getElementsByTagName("w:t")).forEach(P=>{let A=k.ownerDocument.createElement("w:delText");A.textContent=P.textContent,P.hasAttribute("xml:space")&&A.setAttribute("xml:space","preserve"),k.replaceChild(A,P);}),x.appendChild(k),y._element.parentNode?.replaceChild(x,y._element),p===null&&(p=x),m=x;}let w=null,v=null,b=null;if(i==="MODIFICATION"&&e.new_text&&m){let y=m;for(;y&&y.tagName!=="w:p";)y=y.parentNode;let x=y?new ne(y,null):null,k=f.length>0?f[f.length-1]:null,N=this._track_insert_multiline(e.new_text,k,x,d,m,l);if(N.first_node){if(N.first_node.tagName==="w:ins"){let A=m.parentNode;A&&A.tagName==="w:ins"?this._insert_and_split_ins(A,m,N.first_node):nt(N.first_node,m),w=N.first_node;}else w=N.last_ins;v=N.last_p,b=N.last_ins;}}if(i==="DELETION"||i==="MODIFICATION"){if(i==="MODIFICATION"&&f.length===0&&h.length>0&&e.new_text){let y=h[0];if(y.paragraph){let x=y.paragraph._element,k=R(x,"w:r"),N=k.length>0?new Re(k[k.length-1],y.paragraph):null,P=this._track_insert_multiline(e.new_text,N,y.paragraph,d,null,l);P.first_node&&x.appendChild(P.first_node);}}for(let y of [...h].reverse())if(y.paragraph){let x=y.paragraph._element,k=Ae(x);for(;k&&k.tagName!=="w:p";)k=Ae(k);if(k&&k.tagName==="w:p"){let N=!this._paragraph_has_visible_content(x),P=O(x,"w:pPr");if(N){let T=O(k,"w:pPr"),M=T?T.cloneNode(true):x.ownerDocument.createElement("w:pPr");if(P){let j=O(P,"w:sectPr");j&&!O(M,"w:sectPr")&&M.appendChild(j.cloneNode(true)),x.removeChild(P);}x.insertBefore(M,x.firstChild),P=M;}P||(P=x.ownerDocument.createElement("w:pPr"),x.insertBefore(P,x.firstChild));let A=O(P,"w:rPr");if(A||(A=x.ownerDocument.createElement("w:rPr"),P.appendChild(A)),!O(A,"w:del")){let T=this._create_track_change_tag("w:del");A.appendChild(T);}let C=Array.from(k.childNodes);for(let T of C)T.nodeType===1&&T.tagName==="w:pPr"||x.appendChild(T);k.parentNode&&k.parentNode.removeChild(k);}}}if(e.comment&&p!==null){let y,x;if(v&&b)y=b,x=v;else {let C=w!==null?w:m;for(y=C,x=C;x&&x.tagName!=="w:p";)x=x.parentNode;}let k=p;for(;k&&k.tagName!=="w:p";)k=k.parentNode;if(!k||!x)return true;let N=g((C,T)=>{let M=C;for(;M.parentNode&&M.parentNode!==T;)M=M.parentNode;return M},"ascend_to_paragraph_child"),P=N(p,k),A=N(y,x);k===x?this._attach_comment(k,P,A,e.comment):this._attach_comment_spanning(k,P,x,A,e.comment);}for(let y of _)if(!this._paragraph_has_visible_content(y)){let k=O(y,"w:pPr");k||(k=y.ownerDocument.createElement("w:pPr"),y.insertBefore(k,y.firstChild));let N=O(k,"w:rPr");if(N||(N=y.ownerDocument.createElement("w:rPr"),k.appendChild(N)),!O(N,"w:del")){let P=this._create_track_change_tag("w:del");N.appendChild(P);}}return true}},Pu=["{++","{--","{~~","{==","{>>"],Tu=/^> \*\*File Path:\*\*[^\n]*\n+/,$u=/^> \*\*Page (\d+) of (\d+)\*\*[^\n]*\n+(?:---\n+)?/,Su=/\n+---\n+> \*\*Continues on page (\d+) of (\d+)\.\*\*[^\n]*\s*$/,Iu=/\n+---\n+> \*\*Appendix available\.\*\*[^\n]*\s*$/,Ou=2e3,fn=class extends Error{static{g(this,"TextRevisionError");}constructor(t){super(t),this.name="TextRevisionError";}},Du=class extends fn{static{g(this,"TextRevisionVerificationError");}constructor(t,e,n,r,i){super(t),this.unverified_path=e,this.output_path=n,this.stats=r,this.unverified_bytes=i,this.name="TextRevisionVerificationError";}unverified_path;output_path;stats;unverified_bytes};function Ru(t){if(t&&t.trim())return t.trim();let e="".trim();return e||"Adeu AI (TS)"}g(Ru,"get_default_author");function Mu(t){if(Pu.some(e=>t.includes(e)))throw new fn("Revised text contains CriticMarkup tokens ({++..++}, {--..--}, {~~..~>..~~}, {==..==}, {>>..<<}). `apply_text_revision` compares text against the document's CLEAN view, so CriticMarkup tokens would be diffed into the document as literal prose.")}g(Mu,"check_criticmarkup");function ju(t){t=t.replace(Tu,"");let e=null,n=null,r=$u.exec(t);r&&(e=parseInt(r[1],10),n=parseInt(r[2],10),t=t.slice(r[0].length)),t=t.replace(Iu,"");let i=Su.exec(t);return i&&(e===null&&(e=parseInt(i[1],10)-1),n===null&&(n=parseInt(i[2],10)),t=t.slice(0,i.index)),{text:t,page:e,total:n}}g(ju,"strip_page_chrome");function Bu(t,e,n=false,r){if(n)return;let i=t.length,o=e.length;if(i===0)return;let s=(i-o)/i,a=i>=Ou?.5:.75;if(s<=a)return;let l=r?`'${r}'`:"The revised text";throw new fn(`${l} is ~${Math.floor(s*100)}% shorter than the document's clean text (${o.toLocaleString("en-US")} vs ${i.toLocaleString("en-US")} characters, threshold is >${Math.floor(a*100)}% deletion). Applying it would delete the majority of the document as tracked deletions.
138
154
  If the text is a partial extract, re-extract the ENTIRE document with \`--page all --clean-view\` and edit that.
139
- If the mass deletion is intentional, re-run with --allow-major-deletions (over MCP: allow_major_deletions=True).`)}g(Ga,"check_major_deletions");function li(t){return Fe(t,true,false)}g(li,"_extract_clean_text_from_doc");function _r(t){return t.replace(/^#+\s*/gm,"")}g(_r,"_normalize_virtual_projection_text");var Qa=new RegExp("\\p{C}|\\p{Z}","u");function mr(t){let e=t.includes("'")&&!t.includes('"')?'"':"'",n="";for(let r of t)if(r==="\\")n+="\\\\";else if(r===`
140
- `)n+="\\n";else if(r==="\r")n+="\\r";else if(r===" ")n+="\\t";else if(r===e)n+=`\\${e}`;else if(r!==" "&&Qa.test(r)){let s=r.codePointAt(0),[i,o]=s<256?["x",2]:s<65536?["u",4]:["U",8];n+=`\\${i}${s.toString(16).padStart(o,"0")}`;}else n+=r;return `${e}${n}${e}`}g(mr,"_repr");function Ya(t,e){let n=li(t),r=_r(n.trim()),s=_r(e.trim());if(r!==s){let i=Array.from(r),o=Array.from(s),l=Math.min(i.length,o.length),a=l;for(let c=0;c<l;c++)if(i[c]!==o[c]){a=c;break}return [false,`Post-apply verification failed: the applied document's clean text does not match the supplied text (first divergence at character ${a}: applied reads ${mr(i.slice(a,a+40).join(""))}, supplied text reads ${mr(o.slice(a,a+40).join(""))}). The document structure could not fully realize the requested text (e.g. headings or table cells cannot be deleted via text replacement).`]}return [true,null]}g(Ya,"verify_clean_text");function Va(t){let e=path.basename(t,path.extname(t));return e.endsWith("_redlined")||e.endsWith("_processed")?t:path.join(path.dirname(t),`${e}_redlined.docx`)}g(Va,"_default_output_path");function Za(t){let e=path.basename(t,path.extname(t));return path.join(path.dirname(t),`${e}.unverified.docx`)}g(Za,"_unverified_path");async function ci(t){let{doc:e,input_path:n,revised_text:r}=t,{text:s,page:i,total:o}=Xa(r);if(o!==null&&o>1)throw new St(`Text revision looks like page ${i||"?"} of ${o} of a paginated extract \u2014 it contains only part of the document, and applying it would delete every page not present. Re-extract the ENTIRE document first with --page all --clean-view.`);Ja(s);let l=li(e);Ga(l,s,t.allow_major_deletions??false);let a=yt(l,s),u=new Tt(e,qa(t.author)),c=u.process_batch(a),d=t.output_path?t.output_path:Va(n),[f,h]=Ya(u.doc,s);if(!f){let p=Za(d),m=await u.doc.save(),y=`${h} Nothing was written to '${d}'; a diagnostic copy was kept at '${p}' \u2014 it is NOT the requested document.`;if(c.verified=false,c.verification_error=y,c.error="verification_failed",c.edits_skipped=(c.edits_applied||0)+(c.edits_skipped||0),c.edits_applied=0,c.actions_skipped=(c.actions_applied||0)+(c.actions_skipped||0),c.actions_applied=0,c.output_path=null,c.unverified_output_path=p,c.edits)for(let x of c.edits)x.status="failed",x.error="Not applied: post-apply verification failed.",x.critic_markup=null,x.clean_text=null;throw new Ha(y,p,d,c,m)}let _=await u.doc.save();return c.output_path=d,c.verified=true,{stats:c,output_path:d,out_bytes:_}}g(ci,"apply_text_revision_core");var ui=/^(#{1,6}) /,di=3;function fi(t,e){for(let n=0;n<t.length;n++){let r=t[n],s=e;for(let i=n+1;i<t.length;i++)if(t[i].level<=r.level){s=t[i].page>r.page?t[i].page-1:r.page;break}r.end_page=s;}}g(fi,"_assign_end_pages");function hi(t,e,n,r,s=null){if(n.length!==r.length)throw new Error("body_pages and body_page_offsets length mismatch");if(s)return ol(t,e,r,s);let i=Pe(t.pkg),o=el(t,i),l=[];for(let u=0;u<o.length;u++){let c=o[u];c.is_paragraph&&ot(c.item)&&rl(c.item,i)&&l.push(u);}if(l.length===0)return [];let a=[];for(let u=0;u<l.length;u++){let c=l[u],d=o[c],f=d.item,h=kt(f),_=wi(f,i),p=$t(f),m=il(o,l,u,h),y=o.slice(c+1,m),x=Ka(o,c+1,m),b=sl(y),w=xi(d.start_offset,r);a.push({level:h,text:_,page:w,style:p,has_table:x,footnote_ids:b,end_page:w});}return fi(a,n.length),a}g(hi,"extract_outline");function Ka(t,e,n){for(let r=e;r<n;r++){let s=t[r];if(s.is_paragraph&&ot(s.item))return false;if(s.is_table)return true}return false}g(Ka,"_direct_has_table");function el(t,e){let n=Array.from(Oo(t)),r=0,s=null;for(let a of n){if(a===t){s=a;break}let u=mi(a,e);u&&(r>0&&(r+=2),r+=u.length);}s?r>0&&(r+=2):(s=t,r=0);let i=[],o=r,l=true;for(let a of Oe(s))if(a instanceof ie){let u=$e(a),c=lt(a,e,false),d=(u+c).length;l||(o+=2),i.push({item:a,is_paragraph:true,is_table:false,start_offset:o,projected_length:d}),o+=d,l=false;}else if(a instanceof Se){let u=It(a,e,false,0),c=u?u.length:0;l||(o+=2);let d=o;i.push({item:a,is_paragraph:false,is_table:true,start_offset:d,projected_length:c}),_i(a,d,i,e),o+=c,l=false;}return i}g(el,"_walk_doc_body");function pi(t,e,n,r){let s=e._element,i=n,o=0;for(let l of t.rows){if(o>0)if(o===1){let c=t.rows[0],d=new Set,f=0;for(let _ of c.cells)d.has(_)||(d.add(_),f+=1);let h=f>0?Array(f).fill("---").join(" | ").length:0;i+=1+h+1;}else i+=1;let a=new Set,u=0;for(let c of l.cells){if(a.has(c))continue;a.add(c),u>0&&(i+=3);let[d,f]=tl(c,s,i,r);if(f)return d;i=d,u++;}o++;}return n}g(pi,"_compute_inner_block_offset");function tl(t,e,n,r){let s=n,i=true;for(let o of Oe(t)){if(i||(s+=2),o instanceof ie){if(o._element===e)return [s,true];let l=$e(o),a=lt(o,r,false);s+=(l+a).length;}else if(o instanceof Se){let l=pi(o,new ie(e,null),s,r);if(l!==s&&nl(e,o._element))return [l,true];let a=It(o,r,false,0);s+=a?a.length:0;}i=false;}return [s,false]}g(tl,"_walk_cell_for_offset");function nl(t,e){let n=t.parentNode;for(;n;){if(n===e)return true;n=n.parentNode;}return false}g(nl,"_element_is_descendant");function _i(t,e,n,r){let s=new Set;for(let i of t.rows)for(let o of i.cells)if(!s.has(o)){s.add(o);for(let l of Oe(o))if(l instanceof ie){let a=ot(l)?pi(t,l,e,r):e;n.push({item:l,is_paragraph:true,is_table:false,start_offset:a,projected_length:0});}else l instanceof Se&&(n.push({item:l,is_paragraph:false,is_table:true,start_offset:e,projected_length:0}),_i(l,e,n,r));}}g(_i,"_record_table_inner_blocks_lite");function mi(t,e){let n=[],r=t.constructor.name;if(r==="NotesPart"){let i=t.note_type==="fn"?"## Footnotes":"## Endnotes";n.push(`---
141
- ${i}`);}let s=true;for(let i of Oe(t))if(i.constructor.name==="FootnoteItem"){let o=mi(i,e);o&&n.push(o);}else if(i instanceof ie){let o=$e(i);s&&r==="FootnoteItem"&&(o=`[^${t.note_type}-${t.id}]: ${o}`);let l=lt(i,e,false);n.push(o+l),s=false;}else if(i instanceof Se){let o=It(i,e,false,0);o&&n.push(o),s=false;}return n.join(`
142
-
143
- `)}g(mi,"_project_part");function ot(t){return ui.test($e(t))}g(ot,"_is_heading");function rl(t,e){let n=wi(t,e);return gi(n)?$t(t)!=="(heuristic)"?true:(n.match(/\w+/g)||[]).length>=di:false}g(rl,"_heading_passes_quality_filter");function gi(t){if(!t)return false;let e=t.replace(/\{#[^}]+\}/g,"");return /\w/.test(e)}g(gi,"_heading_text_has_words");function kt(t){let e=ui.exec($e(t));return e?Math.min(e[1].length,6):1}g(kt,"_heading_level");var gr=200;function wi(t,e){let n=lt(t,e,false),r=vi(n);return r=r.replace(/\n+/g," "),r=bi(r),yi(r.trim())}g(wi,"_heading_text");function yi(t){return t.length<=gr?t:t.substring(0,gr)+"\u2026"}g(yi,"_truncate_outline_text");function vi(t){return t?(t=t.replace(/\{--[\s\S]*?--\}/g,""),t=t.replace(/\{>>[\s\S]*?<<\}/g,""),t=t.replace(/\{\+\+([\s\S]*?)\+\+\}/g,"$1"),t=t.replace(/\{==([\s\S]*?)==\}/g,"$1"),t):""}g(vi,"_strip_critic_markup");function bi(t){if(!t)return "";let e=[];return t=t.replace(/\{#[^}]+\}|_{3,}/g,n=>(e.push(n),`\0${e.length-1}\0`)),t=t.replace(/\*\*(.+?)\*\*/g,"$1"),t=t.replace(/__(.+?)__/g,"$1"),t=t.replace(/(?<!\w)_(\S(?:.*?\S)?)_(?!\w)/g,"$1"),t=t.replace(/\x00(\d+)\x00/g,(n,r)=>e[Number(r)]),t}g(bi,"_strip_inline_formatting");function $t(t){let[e,n]=Qe(t._parent.part||t._parent),r=B(t._element,"w:pPr"),s=n;if(r){let u=B(r,"w:pStyle");u&&(s=u.getAttribute("w:val")||n);}let i=null,o=false;if(r){let u=B(r,"w:outlineLvl");u&&/^\d+$/.test(u.getAttribute("w:val")||"")&&(i=parseInt(u.getAttribute("w:val"),10));}i===null&&s&&e&&e[s]&&(i=e[s].outline_level,o=true);let a=s&&e&&e[s]?e[s].name:s;return a&&typeof a=="string"&&(a.toLowerCase().startsWith("heading")?a=a.replace(/^heading/i,"Heading"):a.toLowerCase()==="title"&&(a="Title")),o&&i!==null&&(a&&(a.startsWith("Heading")||a==="Title")||(i=null)),i!==null&&i>=0&&i<=8?a&&(a.startsWith("Heading")||a==="Title")?a:"(outline_level)":a&&(a.startsWith("Heading")||a==="Title")||a&&/Heading[ ]?([1-6])(?![0-9])/.test(a)?a:"(heuristic)"}g($t,"_determine_heading_style");function il(t,e,n,r){for(let s=n+1;s<e.length;s++){let i=e[s];if(kt(t[i].item)<=r)return i}return t.length}g(il,"_find_owned_end");function sl(t){let e=new Set,n=[];for(let r of t)if(r.is_paragraph)for(let s of Pt(r.item)){if(!("type"in s))continue;let i="";if(s.type==="footnote")i=`fn-${s.id}`;else if(s.type==="endnote")i=`en-${s.id}`;else continue;e.has(i)||(e.add(i),n.push(i));}return n}g(sl,"_collect_footnote_ids");function xi(t,e){if(!e||e.length===0)return 1;let n=1;for(let r=0;r<e.length&&t>=e[r];r++)n=r+1;return n}g(xi,"offset_to_page");function ol(t,e,n,r){let s=[],i=new Set;function o(u){for(let c of Oe(u))if(c.constructor.name==="FootnoteItem")o(c);else if(c instanceof ie)s.push(["p",c]);else if(c instanceof Se){s.push(["t",c]);for(let f of c.rows)for(let h of f.cells)i.has(h._element)||(i.add(h._element),o(h));}}g(o,"walk"),o(t);let l=[];for(let u=0;u<s.length;u++){let[c,d]=s[u];if(c!=="p")continue;let f=false;r instanceof Map?f=r.has(d._element):f=d._element in r,f&&ot(d)&&al(d,e,r)&&l.push(u);}if(l.length===0)return [];let a=[];for(let u=0;u<l.length;u++){let c=l[u],d=s[c][1],f=kt(d),h=Ni(d,e,r),_=$t(d),p=c;for(let v=u+1;v<l.length;v++){let N=l[v],k=s[N][1];if(kt(k)<=f){p=N;break}}p===c&&(p=s.length);let m=s.slice(c+1,p),y=false;for(let[v,N]of m){if(v==="p"&&ot(N))break;if(v==="t"){y=true;break}}let x=ll(m),b;r instanceof Map?b=r.get(d._element):b=r[d._element];let w=1;if(b!==void 0){let[v]=b;w=xi(v,n);}a.push({level:f,text:h,page:w,style:_,has_table:y,footnote_ids:x,end_page:w});}return fi(a,n.length),a}g(ol,"_extract_outline_fast");function al(t,e,n){let r=Ni(t,e,n);return gi(r)?$t(t)!=="(heuristic)"?true:(r.match(/\w+/g)||[]).length>=di:false}g(al,"_heading_passes_quality_filter_fast");function Ni(t,e,n){let r;if(n instanceof Map?r=n.get(t._element):r=n[t._element],r===void 0)return "";let[s,i]=r,o=e.substring(s,s+i),l=vi(o);return l=l.replace(/\n+/g," "),l=bi(l),l=l.replace(/^#+\s+/,""),yi(l.trim())}g(Ni,"_heading_text_fast");function ll(t){let e=new Set,n=[];for(let[r,s]of t)if(r==="p")for(let i of Pt(s)){if(!("type"in i))continue;let o="";if(i.type==="footnote")o=`fn-${i.id}`;else if(i.type==="endnote")o=`en-${i.id}`;else continue;e.has(o)||(e.add(o),n.push(o));}return n}g(ll,"_collect_footnote_ids_fast");var cl=class{static{g(this,"SanitizeReport");}filename;mode;author;tracked_changes_found=0;tracked_changes_accepted=0;tracked_changes_kept=0;change_lines=[];comments_removed=0;comments_kept=0;removed_comment_lines=[];kept_comment_lines=[];metadata_lines=[];structural_lines=[];warnings=[];status="clean";blocked_reason=null;constructor(t,e="full",n=null){this.filename=t,this.mode=e,this.author=n;}add_transform_lines(t){for(let e of t){let n=e.toLowerCase();n.includes("tracked change")||n.includes("insertion")||n.includes("deletion")||n.includes("accepted")?this.change_lines.push(e):n.includes("author")||n.includes("template")||n.includes("company")||n.includes("manager")||n.includes("metadata")||n.includes("timestamp")||n.includes("custom xml")||n.includes("custom propert")||n.includes("identifier")||n.includes("document variable")||n.includes("language")||n.includes("version")||n.includes("last modified by")||n.includes("revision count")||n.includes("last printed")||n.includes("description/comments")?this.metadata_lines.push(e):n.includes("comment")||n.includes("[open]")||n.includes("[resolved]")?n.includes("kept")||n.includes("visible")?this.kept_comment_lines.push(e):this.removed_comment_lines.push(e):n.includes("hyperlink")||n.includes("warning")?this.warnings.push(e):this.structural_lines.push(e);}}render(){let t="\u2550".repeat(50),e=[t,`Finalization Report: ${this.filename}`],n=[];if(this.mode==="keep-markup"&&n.push("--keep-markup"),this.author&&n.push(`--author "${this.author}"`),this.tracked_changes_accepted>0&&n.push("--accept-all"),n.length>0&&e.push(`Options: ${n.join(" ")}`),e.push(t),this.status==="blocked")return e.push(""),e.push(`BLOCKED: ${this.blocked_reason}`),e.push(t),e.join(`
155
+ If the mass deletion is intentional, re-run with --allow-major-deletions (over MCP: allow_major_deletions=True).`)}g(Bu,"check_major_deletions");function Mo(t){return t=t.replace(/([^|])\s+\{#cell:[^}]+\}/g,"$1"),t=t.replace(/\{#cell:[^}]+\}/g,""),t}g(Mo,"strip_cell_anchors");function jo(t){return Qe(t,true,false)}g(jo,"_extract_clean_text_from_doc");function bi(t){return Mo(t.replace(/^#+\s*/gm,""))}g(bi,"_normalize_virtual_projection_text");var Fu=new RegExp("\\p{C}|\\p{Z}","u");function xi(t){let e=t.includes("'")&&!t.includes('"')?'"':"'",n="";for(let r of t)if(r==="\\")n+="\\\\";else if(r===`
156
+ `)n+="\\n";else if(r==="\r")n+="\\r";else if(r===" ")n+="\\t";else if(r===e)n+=`\\${e}`;else if(r!==" "&&Fu.test(r)){let i=r.codePointAt(0),[o,s]=i<256?["x",2]:i<65536?["u",4]:["U",8];n+=`\\${o}${i.toString(16).padStart(s,"0")}`;}else n+=r;return `${e}${n}${e}`}g(xi,"_repr");function Wu(t,e){let n=jo(t),r=bi(n.trim()),i=bi(e.trim());if(r!==i){let o=Array.from(r),s=Array.from(i),a=0,l=Math.min(o.length,s.length);for(;a<l&&o[a]===s[a];)a++;let u=o.slice(a,a+40).join(""),c=s.slice(a,a+40).join("");return [false,`Post-apply verification failed: the applied document's clean text does not match the supplied text (first divergence at character ${a}: applied reads ${xi(u)}, supplied text reads ${xi(c)}). The document structure could not fully realize the requested text (e.g. headings or table cells cannot be deleted via text replacement).`]}return [true,null]}g(Wu,"verify_clean_text");function Lu(t){let e=path.dirname(t),n=path.basename(t),r=n.lastIndexOf("."),i=r===-1?n:n.slice(0,r);return i.endsWith("_redlined")||i.endsWith("_processed")?t:path.join(e,`${i}_redlined.docx`)}g(Lu,"_default_output_path");function zu(t){let e=path.basename(t,path.extname(t));return path.join(path.dirname(t),`${e}.unverified.docx`)}g(zu,"_unverified_path");async function Bo(t){let{doc:e,input_path:n,revised_text:r}=t,{text:i,page:o,total:s}=ju(r),a=Mo(i);if(s!==null&&s>1)throw new fn(`Text revision looks like page ${o||"?"} of ${s} of a paginated extract \u2014 it contains only part of the document, and applying it would delete every page not present. Re-extract the ENTIRE document first with --page all --clean-view.`);Mu(a);let l=jo(e);Bu(l,a,t.allow_major_deletions??false);let u=Ht(l,a),c=new dn(e,Ru(t.author)),d=c.process_batch(u),f=t.output_path?t.output_path:Lu(n),[h,_]=Wu(c.doc,a);if(!h){let m=zu(f),w=await c.doc.save(),v=`${_} Nothing was written to '${f}'; a diagnostic copy was kept at '${m}' \u2014 it is NOT the requested document.`;if(d.verified=false,d.verification_error=v,d.error="verification_failed",d.edits_skipped=(d.edits_applied||0)+(d.edits_skipped||0),d.edits_applied=0,d.actions_skipped=(d.actions_applied||0)+(d.actions_skipped||0),d.actions_applied=0,d.output_path=null,d.unverified_output_path=m,d.edits)for(let b of d.edits)b.status="failed",b.error="Not applied: post-apply verification failed.",b.critic_markup=null,b.clean_text=null;throw new Du(v,m,f,d,w)}let p=await c.doc.save();return d.output_path=f,d.verified=true,{stats:d,output_path:f,out_bytes:p}}g(Bo,"apply_text_revision_core");var Uu=class{static{g(this,"SanitizeReport");}filename;mode;author;tracked_changes_found=0;tracked_changes_accepted=0;tracked_changes_kept=0;change_lines=[];comments_removed=0;comments_kept=0;removed_comment_lines=[];kept_comment_lines=[];metadata_lines=[];structural_lines=[];warnings=[];status="clean";blocked_reason=null;constructor(t,e="full",n=null){this.filename=t,this.mode=e,this.author=n;}add_transform_lines(t){for(let e of t){let n=e.toLowerCase();n.includes("tracked change")||n.includes("insertion")||n.includes("deletion")||n.includes("accepted")?this.change_lines.push(e):n.includes("author")||n.includes("template")||n.includes("company")||n.includes("manager")||n.includes("metadata")||n.includes("timestamp")||n.includes("custom xml")||n.includes("custom propert")||n.includes("identifier")||n.includes("document variable")||n.includes("language")||n.includes("version")||n.includes("last modified by")||n.includes("revision count")||n.includes("last printed")||n.includes("description/comments")?this.metadata_lines.push(e):n.includes("comment")||n.includes("[open]")||n.includes("[resolved]")?n.includes("kept")||n.includes("visible")?this.kept_comment_lines.push(e):this.removed_comment_lines.push(e):n.includes("hyperlink")||n.includes("warning")?this.warnings.push(e):this.structural_lines.push(e);}}render(){let t="\u2550".repeat(50),e=[t,`Finalization Report: ${this.filename}`],n=[];if(this.mode==="keep-markup"&&n.push("--keep-markup"),this.author&&n.push(`--author "${this.author}"`),this.tracked_changes_accepted>0&&n.push("--accept-all"),n.length>0&&e.push(`Options: ${n.join(" ")}`),e.push(t),this.status==="blocked")return e.push(""),e.push(`BLOCKED: ${this.blocked_reason}`),e.push(t),e.join(`
144
157
  `);if(this.mode==="keep-markup"&&(this.tracked_changes_kept>0||this.comments_kept>0)){if(e.push(""),e.push("VISIBLE TO COUNTERPARTY"),this.tracked_changes_kept>0&&e.push(` Tracked changes: ${this.tracked_changes_kept}`),this.comments_kept>0){e.push(` Open comments: ${this.comments_kept}`);for(let r of this.kept_comment_lines)e.push(` ${r}`);}this.author&&e.push(` Author on all markup: "${this.author}"`);}if(this.change_lines.length>0){e.push(""),e.push("TRACKED CHANGES");for(let r of this.change_lines)e.push(` ${r}`);}if(this.removed_comment_lines.length>0){e.push(""),e.push("COMMENTS (stripped)");for(let r of this.removed_comment_lines)e.push(` ${r}`);}if(this.metadata_lines.length>0){e.push(""),e.push("METADATA");for(let r of this.metadata_lines)e.push(` ${r}`);}if(this.structural_lines.length>0){e.push(""),e.push("STRUCTURAL & PROTECTION");for(let r of this.structural_lines)e.push(` ${r}`);}if(this.warnings.length>0){e.push(""),e.push("WARNINGS");for(let r of this.warnings)e.push(` \u26A0 ${r}`);}return e.push(""),e.push(t),this.warnings.length>0?e.push(`Result: CLEAN WITH WARNINGS (${this.warnings.length} warning${this.warnings.length>1?"s":""})`):this.mode==="keep-markup"?e.push("Result: CLEAN"):e.push(`Result: CLEAN (${this.tracked_changes_found} changes resolved, ${this.comments_removed} comments removed)`),e.push(t),e.join(`
145
- `)}};async function ki(t,e){let n=new cl(e.filename,e.sanitize_mode||"full",e.author||null);if(e.sanitize_mode==="full"){let i=dr(t),o=i[0]+i[1]+i[2];if(n.tracked_changes_found=o,o>0&&!e.accept_all)return n.status="blocked",n.blocked_reason=`Document contains ${o} unresolved tracked changes (${i[0]} insertions, ${i[1]} deletions, ${i[2]} formatting). Review in Word first, set accept_all=true, or set sanitize_mode='keep-markup'.`,{reportText:n.render()};if(o>0){let a=fa(t);a.size>1&&n.warnings.push(`Multiple authors detected in tracked changes: ${Array.from(a).sort().join(", ")}. Review per-change list before sending.`);let u=gt(t);n.add_transform_lines(ha(t)),n.tracked_changes_accepted=o;let c=new Set(gt(t).comments.map(f=>f.id)),d=u.comments.filter(f=>!c.has(f.id));if(d.length>0){n.comments_removed+=d.length,n.removed_comment_lines.push(`Comments removed: ${d.length} (anchored to auto-accepted tracked changes)`);for(let f of d){let h=f.resolved?"[Resolved]":"[Open]";n.removed_comment_lines.push(` ${h} "${Ie(f.text||"",60)}" (${f.author||"Unknown"})`);}}}let l=gt(t);n.comments_removed+=l.total,n.add_transform_lines(pa(t)),_a(t);}else if(e.sanitize_mode==="keep-markup"){let i=dr(t);n.tracked_changes_found=i[0]+i[1]+i[2],n.tracked_changes_kept=n.tracked_changes_found;let o=gt(t);n.comments_kept=o.open;for(let l of o.comments)l.resolved||n.kept_comment_lines.push(`"${Ie(l.text||"",60)}" (${l.author||"Unknown"})`);e.author&&(n.add_transform_lines(ma(t,e.author)),n.add_transform_lines(ga(t,e.author)));}n.add_transform_lines(aa(t)),n.add_transform_lines(la(t)),n.add_transform_lines(ca(t)),n.add_transform_lines(ua(t)),n.add_transform_lines(da(t)),n.add_transform_lines(oa(t)),n.add_transform_lines(va(t)),n.add_transform_lines(ba(t)),n.add_transform_lines(xa(t)),n.add_transform_lines(Na(t)),n.add_transform_lines(ka(t)),n.add_transform_lines(Ea(t));let r=Ca(t);for(let i of r)n.warnings.push(i);for(let i of Aa(t))n.warnings.push(i);if(n.add_transform_lines(wa(t)),n.add_transform_lines(ya(t)),e.protection_mode==="read_only"||e.protection_mode==="encrypt"){e.protection_mode==="encrypt"&&n.warnings.push("Encryption mode (AES compound wrappers) is strictly unsupported in the zero-dependency Node engine. Falling back to native Word Read-Only lock.");let i=t.pkg.getPartByPath("word/settings.xml");if(i){let o=i._element.ownerDocument,l=K(i._element,"documentProtection")[0];l||(l=o.createElement("w:documentProtection"),i._element.appendChild(l)),l.setAttribute("w:edit","readOnly"),l.setAttribute("w:enforcement","1"),n.structural_lines.push("Document locked (Read-Only enforcement injected into settings.xml)");}}e.export_pdf&&n.warnings.push("PDF export requires the Python/Word COM environment and is skipped in this zero-dependency Node agent.");for(let i of t.pkg.parts)if((i===t.part||i.contentType.includes("wordprocessingml")&&i.contentType.endsWith("+xml"))&&i._element.hasAttribute("xmlns:w16du")){let o=false;if(Array.from(i._element.attributes||[]).some(l=>l.name.startsWith("w16du:")&&l.name!=="xmlns:w16du")&&(o=true),!o){let l=M(i._element,"*");for(let a of l)if(a.tagName.startsWith("w16du:")||Array.from(a.attributes||[]).some(u=>u.name.startsWith("w16du:"))){o=true;break}}o||i._element.removeAttribute("xmlns:w16du");}n.warnings.length>0&&(n.status="clean_with_warnings");let s=await t.save();return dl(s),{reportText:n.render(),outBuffer:s}}g(ki,"finalize_document");var ul=[["creator","author (dc:creator)"],["lastModifiedBy","last modified by (cp:lastModifiedBy)"],["identifier","identifier (dc:identifier)"],["description","description (dc:description)"],["keywords","keywords (cp:keywords)"],["category","category (cp:category)"],["subject","subject (dc:subject)"],["contentStatus","content status (cp:contentStatus)"],["language","language (dc:language)"],["version","version (cp:version)"]];function dl(t){let e=Le(new Uint8Array(t)),n=Object.keys(e),r=[];if(n.includes("docProps/custom.xml")&&r.push("docProps/custom.xml (custom document properties) is still in the package"),n.some(s=>s.startsWith("customXml/"))&&r.push("customXml/* parts are still in the package"),n.includes("docProps/core.xml")){let s=je(De(e["docProps/core.xml"]));for(let[i,o]of ul)for(let l of K(s.documentElement,i))(l.textContent||"").trim()&&r.push(`core property ${o} still contains a value`);}if(n.includes("word/settings.xml")){let s=je(De(e["word/settings.xml"]));K(s.documentElement,"docVar").length>0&&r.push("word/settings.xml still contains document variables (w:docVar)");}if(r.length>0)throw new Error(`Sanitize integrity check failed \u2014 the saved package still contains metadata this run claims to remove:
158
+ `)}};async function Fo(t,e){let n=new Uu(e.filename,e.sanitize_mode||"full",e.author||null);if(e.sanitize_mode==="full"){let o=ei(t),s=o[0]+o[1]+o[2];if(n.tracked_changes_found=s,s>0&&!e.accept_all)return n.status="blocked",n.blocked_reason=`Document contains ${s} unresolved tracked changes (${o[0]} insertions, ${o[1]} deletions, ${o[2]} formatting). Review in Word first, set accept_all=true, or set sanitize_mode='keep-markup'.`,{reportText:n.render()};if(s>0){let l=Sl(t);l.size>1&&n.warnings.push(`Multiple authors detected in tracked changes: ${Array.from(l).sort().join(", ")}. Review per-change list before sending.`);let u=jt(t);n.add_transform_lines(Il(t)),n.tracked_changes_accepted=s;let c=new Set(jt(t).comments.map(f=>f.id)),d=u.comments.filter(f=>!c.has(f.id));if(d.length>0){n.comments_removed+=d.length,n.removed_comment_lines.push(`Comments removed: ${d.length} (anchored to auto-accepted tracked changes)`);for(let f of d){let h=f.resolved?"[Resolved]":"[Open]";n.removed_comment_lines.push(` ${h} "${Be(f.text||"",60)}" (${f.author||"Unknown"})`);}}}let a=jt(t);n.comments_removed+=a.total,n.add_transform_lines(Ol(t)),Dl(t);}else if(e.sanitize_mode==="keep-markup"){let o=ei(t);n.tracked_changes_found=o[0]+o[1]+o[2],n.tracked_changes_kept=n.tracked_changes_found;let s=jt(t);n.comments_kept=s.open;for(let a of s.comments)a.resolved||n.kept_comment_lines.push(`"${Be(a.text||"",60)}" (${a.author||"Unknown"})`);e.author&&(n.add_transform_lines(Rl(t,e.author)),n.add_transform_lines(Ml(t,e.author)));}n.add_transform_lines(Al(t)),n.add_transform_lines(Cl(t)),n.add_transform_lines(Pl(t)),n.add_transform_lines(Tl(t)),n.add_transform_lines($l(t)),n.add_transform_lines(El(t)),n.add_transform_lines(Fl(t)),n.add_transform_lines(Wl(t)),n.add_transform_lines(Ll(t)),n.add_transform_lines(zl(t)),n.add_transform_lines(Ul(t)),n.add_transform_lines(Hl(t));let r=ql(t);for(let o of r)n.warnings.push(o);for(let o of Xl(t))n.warnings.push(o);if(n.add_transform_lines(jl(t)),n.add_transform_lines(Bl(t)),e.protection_mode==="read_only"||e.protection_mode==="encrypt"){e.protection_mode==="encrypt"&&n.warnings.push("Encryption mode (AES compound wrappers) is strictly unsupported in the zero-dependency Node engine. Falling back to native Word Read-Only lock.");let o=t.pkg.getPartByPath("word/settings.xml");if(o){let s=o._element.ownerDocument,a=K(o._element,"documentProtection")[0];a||(a=s.createElement("w:documentProtection"),o._element.appendChild(a)),a.setAttribute("w:edit","readOnly"),a.setAttribute("w:enforcement","1"),n.structural_lines.push("Document locked (Read-Only enforcement injected into settings.xml)");}}e.export_pdf&&n.warnings.push("PDF export requires the Python/Word COM environment and is skipped in this zero-dependency Node agent.");for(let o of t.pkg.parts)if((o===t.part||o.contentType.includes("wordprocessingml")&&o.contentType.endsWith("+xml"))&&o._element.hasAttribute("xmlns:w16du")){let s=false;if(Array.from(o._element.attributes||[]).some(a=>a.name.startsWith("w16du:")&&a.name!=="xmlns:w16du")&&(s=true),!s){let a=R(o._element,"*");for(let l of a)if(l.tagName.startsWith("w16du:")||Array.from(l.attributes||[]).some(u=>u.name.startsWith("w16du:"))){s=true;break}}s||o._element.removeAttribute("xmlns:w16du");}n.warnings.length>0&&(n.status="clean_with_warnings");let i=await t.save();return Xu(i),{reportText:n.render(),outBuffer:i}}g(Fo,"finalize_document");var Hu=[["creator","author (dc:creator)"],["lastModifiedBy","last modified by (cp:lastModifiedBy)"],["identifier","identifier (dc:identifier)"],["description","description (dc:description)"],["keywords","keywords (cp:keywords)"],["category","category (cp:category)"],["subject","subject (dc:subject)"],["contentStatus","content status (cp:contentStatus)"],["language","language (dc:language)"],["version","version (cp:version)"]];function Xu(t){let e=Ke(new Uint8Array(t)),n=Object.keys(e),r=[];if(n.includes("docProps/custom.xml")&&r.push("docProps/custom.xml (custom document properties) is still in the package"),n.some(i=>i.startsWith("customXml/"))&&r.push("customXml/* parts are still in the package"),n.includes("docProps/core.xml")){let i=Xe(ze(e["docProps/core.xml"]));for(let[o,s]of Hu)for(let a of K(i.documentElement,o))(a.textContent||"").trim()&&r.push(`core property ${s} still contains a value`);}if(n.includes("word/settings.xml")){let i=Xe(ze(e["word/settings.xml"]));K(i.documentElement,"docVar").length>0&&r.push("word/settings.xml still contains document variables (w:docVar)");}if(r.length>0)throw new Error(`Sanitize integrity check failed \u2014 the saved package still contains metadata this run claims to remove:
146
159
  - `+r.join(`
147
160
  - `)+`
148
- Refusing to report a clean document.`)}g(dl,"verifySanitizedPackage");var fl=/\r\n|[\n\r\v\f\u001c-\u001e\u0085\u2028\u2029]/;var rt="Nothing was written. Recover in two calls: (1) re-apply this batch WITHOUT the failing edit(s); (2) fix the failing edit(s) in a separate small batch. Copy target_text verbatim from a fresh read of the CURRENT file, not from another tool's view of it.";var hl=new Set(["invalid_changes_file","batch_validation_failed"]);function Ei(t,e,n,r){let s=n.split(fl).map(o=>o.trim()).filter(Boolean).join(" ");hl.has(t)&&!s.includes(rt)&&(s=s?`${s} ${rt}`:rt);let i={error:t,failed:e.map(([o,l])=>({index:o,reason:l})),message:s};return r!=null&&(i.errors=r),i}g(Ei,"failure_envelope");var me="application/vnd.openxmlformats-officedocument.wordprocessingml.document",Ai="Run the Extract Markdown operation on the current document again to list the current change (Chg:) and comment (Com:) ids \u2014 ids shift between document states.";function Ci(t,e){return e.split(".").reduce((n,r)=>{if(n&&typeof n=="object")return n[r]},t)}g(Ci,"getNestedProperty");async function pl(t,e){let n=this.getInputData()[t];if(!n.binary||!n.binary[e])throw new n8nWorkflow.NodeOperationError(this.getNode(),`No binary data found on property "${e}"`,{description:"Verify that the upstream node produced binary data and that the property name matches.",itemIndex:t});let r=n.binary[e],s=await this.helpers.getBinaryDataBuffer(t,e),i=r.fileName??"document.docx";return {buffer:s,fileName:i}}g(pl,"getDocxBuffer");async function oe(t,e){if(e.mode==="fromInput")return pl.call(this,t,e.binaryPropertyName);let{sourceNodeName:n,binaryPropertyName:r}=e,s="sourceBinaryId"in e?e.sourceBinaryId:void 0;if(s&&s.trim()!=="")try{let d=await this.helpers.getBinaryStream(s);return {buffer:await this.helpers.binaryToBuffer(d),fileName:"document.docx"}}catch(d){throw new n8nWorkflow.NodeApiError(this.getNode(),{message:d.message},{message:`Failed to load document from Binary ID '${s}'.`,description:`The binary with ID '${s}' could not be loaded. This usually means the binary has expired, been garbage-collected, or the ID is incorrect.`,itemIndex:t})}if(!n||n.trim()==="")throw new n8nWorkflow.NodeApiError(this.getNode(),{message:"Source Node Name is empty"},{message:"Source Node Name is required when Document Source is 'From Another Node'.",description:"Set 'Source Node Name' to the exact name of the node in this workflow whose output holds the .docx binary (e.g. the trigger node). Node names are case-sensitive and must match the node label in the canvas exactly.",itemIndex:t});let i=n.replace(/'/g,"\\'"),o=`{{ $('${i}').first().binary.${r} }}`,l;try{l=this.evaluateExpression(o,t);}catch(d){throw new n8nWorkflow.NodeApiError(this.getNode(),{message:d.message},{message:`Failed to resolve binary from source node '${n}'.`,description:`Could not evaluate '${o}'. Verify the source node name is exactly correct (case-sensitive, including spaces and punctuation). Underlying error: ${d.message}`,itemIndex:t})}if(l==null||typeof l!="object"){let d=`{{ $('${i}').first().json }}`,f;try{f=this.evaluateExpression(d,t);}catch{f=void 0;}if(f==null)throw new n8nWorkflow.NodeApiError(this.getNode(),{message:"Source node produced no output"},{message:`Source node '${n}' has no output.`,description:`The expression '${o}' resolved to undefined and the node appears not to have executed in this run. Verify that '${n}' is upstream of this Adeu node, that its name matches exactly (case-sensitive), and that it has run successfully.`,itemIndex:t});let h="";try{let _=this.evaluateExpression(`{{ Object.keys($('${i}').first().binary || {}) }}`,t);Array.isArray(_)&&_.length>0?h=` Available binary properties on '${n}': `+_.map(p=>`'${p}'`).join(", ")+".":Array.isArray(_)&&_.length===0&&(h=` Source node '${n}' has no binary properties at all.`);}catch{}throw new n8nWorkflow.NodeApiError(this.getNode(),{message:"Binary property not found"},{message:`Source node '${n}' has no binary on property '${r}'.`,description:`The expression '${o}' resolved to undefined.${h} Update 'Binary Property Name' to match an existing property, or change the source node so it outputs the .docx on the expected property.`,itemIndex:t})}let a=l,u;try{if(a.id){let d=await this.helpers.getBinaryStream(a.id);u=await this.helpers.binaryToBuffer(d);}else if(a.data)u=Buffer.from(a.data,"base64");else throw new Error("Resolved binary metadata has neither an 'id' nor 'data' field.")}catch(d){throw new n8nWorkflow.NodeApiError(this.getNode(),{message:d.message},{message:`Failed to read binary content from source node '${n}'.`,description:`The binary metadata was found on property '${r}', but its contents could not be loaded. Underlying error: ${d.message}`,itemIndex:t})}let c=a.fileName??"document.docx";return {buffer:u,fileName:c}}g(oe,"getDocxBufferFromSource");function Ye(t,e){let n=t.lastIndexOf(".");return `${n===-1?t:t.substring(0,n)}_${e}.docx`}g(Ye,"buildOutputFileName");var _l={strict:"strict",exact:"strict",single:"strict",first:"first","first-occurrence":"first","first-only":"first",all:"all",global:"all",bulk:"all",alloccurrences:"all","all-occurrences":"all",every:"all"};function ml(t){if(!(t===null||typeof t!="object"||Array.isArray(t))&&((!("type"in t)||t.type===void 0||t.type===null)&&("cells"in t?t.type="insert_row":"text"in t&&"target_id"in t?t.type="reply":"target_text"in t&&"new_text"in t&&(t.type="modify")),"match_mode"in t)){let e=t.match_mode;if(typeof e!="string")delete t.match_mode;else {let n=_l[e.trim().toLowerCase()];n===void 0?delete t.match_mode:t.match_mode=n;}}}g(ml,"coerceChangeItemInPlace");function Pi(t){return t.map(e=>{let n=e;if(typeof e=="string")try{let r=JSON.parse(e);n=r!==null&&typeof r=="object"?r:e;}catch{n=e;}return n!==null&&typeof n=="object"&&!Array.isArray(n)&&ml(n),n})}g(Pi,"coerceChangesArray");function Ti(t,e,n){if(t==null||t==="")throw new n8nWorkflow.NodeOperationError(this.getNode(),`Parameter "${n}" is empty`,{description:`Provide a JSON value for "${n}".`,itemIndex:e});if(typeof t=="object")return t;let r=t.trim();r.startsWith("```")&&(r=r.replace(/^```[a-zA-Z]*\n?/,""),r=r.replace(/\n?```$/,"")),r=r.trim();try{return JSON.parse(r)}catch(s){throw new n8nWorkflow.NodeOperationError(this.getNode(),`Parameter "${n}" is not valid JSON`,{description:s.message,itemIndex:e})}}g(Ti,"parseJsonParameter");function Ii(t,e){let n=t.message??"Unknown error",r=t.name??"",s=t.errors,i=Array.isArray(s)?s.join(`
149
- `):n,o=i.toLowerCase();if(r==="BatchValidationError"){let l="Batch validation failed.",a=`Review the listed failures:
150
- `+i;o.includes("target text not found")?(l="An edit could not be applied: target text not found.",a="Verify the exact `target_text` string \u2014 including punctuation and whitespace \u2014 against the document. Check the individual failures:\n"+i):o.includes("ambiguous match")?(l="An edit matched multiple locations in the document.",a="Provide more surrounding context in `target_text` to uniquely identify the location:\n"+i):o.includes("read-only")||o.includes("readonly")?(l="An edit targeted a read-only structural element.",a=`Cross-references, footnotes, hyperlinks, and the Structural Appendix cannot be modified via text replacement:
151
- `+i):o.includes("comment range from another author")?(l="A match_mode='all' edit would sweep through another author's comment range.",a=`Bulk replacements are blocked from running through foreign comment ranges. Target the commented text deliberately with match_mode 'strict' or 'first', or scope the edit outside of it:
152
- `+i):o.includes("another author")||o.includes("nested")?(l="An edit overlaps with a pending tracked change by another author.",a=`Accept or reject the conflicting change first, or scope your edit outside of it:
153
- `+i):o.includes("control character")?(l="An edit contains invalid XML control characters.",a=`Remove non-printable control characters from your edit string before submitting:
154
- `+i):o.includes("criticmarkup tags")&&(l="Do not manually include CriticMarkup tags in new_text.",a="The engine applies tracked change tags automatically. Pass clean replacement text in `new_text`:\n"+i);let u=t.failed??[],c=Ei("batch_validation_failed",u,i,s),d=c.failed.length?`
161
+ Refusing to report a clean document.`)}g(Xu,"verifySanitizedPackage");var qu=/\r\n|[\n\r\v\f\u001c-\u001e\u0085\u2028\u2029]/;var xt="Nothing was written. Recover in two calls: (1) re-apply this batch WITHOUT the failing edit(s); (2) fix the failing edit(s) in a separate small batch. Copy target_text verbatim from a fresh read of the CURRENT file, not from another tool's view of it.";var Gu=new Set(["invalid_changes_file","batch_validation_failed"]);function Wo(t,e,n,r){let i=n.split(qu).map(s=>s.trim()).filter(Boolean).join(" ");Gu.has(t)&&!i.includes(xt)&&(i=i?`${i} ${xt}`:xt);let o={error:t,failed:e.map(([s,a])=>({index:s,reason:a})),message:i};return r!=null&&(o.errors=r),o}g(Wo,"failure_envelope");var ye="application/vnd.openxmlformats-officedocument.wordprocessingml.document",Lo="Run the Extract Markdown operation on the current document again to list the current change (Chg:) and comment (Com:) ids \u2014 ids shift between document states.";function ut(t){return {show:{resource:["document"],operation:[t]}}}g(ut,"docOpDisplayOptions");function zo(t,e){return e.split(".").reduce((n,r)=>{if(n&&typeof n=="object")return n[r]},t)}g(zo,"getNestedProperty");async function Ju(t,e){let n=this.getInputData()[t];if(!n.binary||!n.binary[e])throw new n8nWorkflow.NodeOperationError(this.getNode(),`No binary data found on property "${e}"`,{description:"Verify that the upstream node produced binary data and that the property name matches.",itemIndex:t});let r=n.binary[e],i=await this.helpers.getBinaryDataBuffer(t,e),o=r.fileName??"document.docx";return {buffer:i,fileName:o}}g(Ju,"getDocxBuffer");async function se(t,e){if(e.mode==="fromInput")return Ju.call(this,t,e.binaryPropertyName);let{sourceNodeName:n,binaryPropertyName:r}=e,i="sourceBinaryId"in e?e.sourceBinaryId:void 0;if(i&&i.trim()!=="")try{let d=await this.helpers.getBinaryStream(i);return {buffer:await this.helpers.binaryToBuffer(d),fileName:"document.docx"}}catch(d){throw new n8nWorkflow.NodeApiError(this.getNode(),{message:d.message},{message:`Failed to load document from Binary ID '${i}'.`,description:`The binary with ID '${i}' could not be loaded. This usually means the binary has expired, been garbage-collected, or the ID is incorrect.`,itemIndex:t})}if(!n||n.trim()==="")throw new n8nWorkflow.NodeApiError(this.getNode(),{message:"Source Node Name is empty"},{message:"Source Node Name is required when Document Source is 'From Another Node'.",description:"Set 'Source Node Name' to the exact name of the node in this workflow whose output holds the .docx binary (e.g. the trigger node). Node names are case-sensitive and must match the node label in the canvas exactly.",itemIndex:t});let o=n.replace(/'/g,"\\'"),s=`{{ $('${o}').first().binary.${r} }}`,a;try{a=this.evaluateExpression(s,t);}catch(d){throw new n8nWorkflow.NodeApiError(this.getNode(),{message:d.message},{message:`Failed to resolve binary from source node '${n}'.`,description:`Could not evaluate '${s}'. Verify the source node name is exactly correct (case-sensitive, including spaces and punctuation). Underlying error: ${d.message}`,itemIndex:t})}if(a==null||typeof a!="object"){let d=`{{ $('${o}').first().json }}`,f;try{f=this.evaluateExpression(d,t);}catch{f=void 0;}if(f==null)throw new n8nWorkflow.NodeApiError(this.getNode(),{message:"Source node produced no output"},{message:`Source node '${n}' has no output.`,description:`The expression '${s}' resolved to undefined and the node appears not to have executed in this run. Verify that '${n}' is upstream of this Adeu node, that its name matches exactly (case-sensitive), and that it has run successfully.`,itemIndex:t});let h="";try{let _=this.evaluateExpression(`{{ Object.keys($('${o}').first().binary || {}) }}`,t);Array.isArray(_)&&_.length>0?h=` Available binary properties on '${n}': `+_.map(p=>`'${p}'`).join(", ")+".":Array.isArray(_)&&_.length===0&&(h=` Source node '${n}' has no binary properties at all.`);}catch{}throw new n8nWorkflow.NodeApiError(this.getNode(),{message:"Binary property not found"},{message:`Source node '${n}' has no binary on property '${r}'.`,description:`The expression '${s}' resolved to undefined.${h} Update 'Binary Property Name' to match an existing property, or change the source node so it outputs the .docx on the expected property.`,itemIndex:t})}let l=a,u;try{if(l.id){let d=await this.helpers.getBinaryStream(l.id);u=await this.helpers.binaryToBuffer(d);}else if(l.data)u=Buffer.from(l.data,"base64");else throw new Error("Resolved binary metadata has neither an 'id' nor 'data' field.")}catch(d){throw new n8nWorkflow.NodeApiError(this.getNode(),{message:d.message},{message:`Failed to read binary content from source node '${n}'.`,description:`The binary metadata was found on property '${r}', but its contents could not be loaded. Underlying error: ${d.message}`,itemIndex:t})}let c=l.fileName??"document.docx";return {buffer:u,fileName:c}}g(se,"getDocxBufferFromSource");function dt(t,e){let n=t.lastIndexOf(".");return `${n===-1?t:t.substring(0,n)}_${e}.docx`}g(dt,"buildOutputFileName");var Yu={strict:"strict",exact:"strict",single:"strict",first:"first","first-occurrence":"first","first-only":"first",all:"all",global:"all",bulk:"all",alloccurrences:"all","all-occurrences":"all",every:"all"};function Qu(t){if(!(t===null||typeof t!="object"||Array.isArray(t))&&((!("type"in t)||t.type===void 0||t.type===null)&&("cells"in t?t.type="insert_row":"text"in t&&"target_id"in t?t.type="reply":"target_text"in t&&"new_text"in t&&(t.type="modify")),"match_mode"in t)){let e=t.match_mode;if(typeof e!="string")delete t.match_mode;else {let n=Yu[e.trim().toLowerCase()];n===void 0?delete t.match_mode:t.match_mode=n;}}}g(Qu,"coerceChangeItemInPlace");function Uo(t){return t.map(e=>{let n=e;if(typeof e=="string")try{let r=JSON.parse(e);n=r!==null&&typeof r=="object"?r:e;}catch{n=e;}return n!==null&&typeof n=="object"&&!Array.isArray(n)&&Qu(n),n})}g(Uo,"coerceChangesArray");function Ho(t,e,n){if(t==null||t==="")throw new n8nWorkflow.NodeOperationError(this.getNode(),`Parameter "${n}" is empty`,{description:`Provide a JSON value for "${n}".`,itemIndex:e});if(typeof t=="object")return t;let r=t.trim();r.startsWith("```")&&(r=r.replace(/^```[a-zA-Z]*\n?/,""),r=r.replace(/\n?```$/,"")),r=r.trim();try{return JSON.parse(r)}catch(i){throw new n8nWorkflow.NodeOperationError(this.getNode(),`Parameter "${n}" is not valid JSON`,{description:i.message,itemIndex:e})}}g(Ho,"parseJsonParameter");function Xo(t,e){let n=t.message??"Unknown error",r=t.name??"",i=t.errors,o=Array.isArray(i)?i.join(`
162
+ `):n,s=o.toLowerCase();if(r==="BatchValidationError"){let a="Batch validation failed.",l=`Review the listed failures:
163
+ `+o;s.includes("target text not found")?(a="An edit could not be applied: target text not found.",l="Verify the exact `target_text` string \u2014 including punctuation and whitespace \u2014 against the document. Check the individual failures:\n"+o):s.includes("ambiguous match")?(a="An edit matched multiple locations in the document.",l="Provide more surrounding context in `target_text` to uniquely identify the location:\n"+o):s.includes("read-only")||s.includes("readonly")?(a="An edit targeted a read-only structural element.",l=`Cross-references, footnotes, hyperlinks, and the Structural Appendix cannot be modified via text replacement:
164
+ `+o):s.includes("comment range from another author")?(a="A match_mode='all' edit would sweep through another author's comment range.",l=`Bulk replacements are blocked from running through foreign comment ranges. Target the commented text deliberately with match_mode 'strict' or 'first', or scope the edit outside of it:
165
+ `+o):s.includes("another author")||s.includes("nested")?(a="An edit overlaps with a pending tracked change by another author.",l=`Accept or reject the conflicting change first, or scope your edit outside of it:
166
+ `+o):s.includes("control character")?(a="An edit contains invalid XML control characters.",l=`Remove non-printable control characters from your edit string before submitting:
167
+ `+o):s.includes("criticmarkup tags")&&(a="Do not manually include CriticMarkup tags in new_text.",l="The engine applies tracked change tags automatically. Pass clean replacement text in `new_text`:\n"+o);let u=t.failed??[],c=Wo("batch_validation_failed",u,o,i),d=c.failed.length?`
155
168
 
156
169
  Failed changes (0-based index into the submitted array):
157
170
  `+c.failed.map(f=>` [${f.index}] ${f.reason}`).join(`
158
- `):"";return new n8nWorkflow.NodeApiError(this.getNode(),c,{message:l,description:`${a}${d}
171
+ `):"";return new n8nWorkflow.NodeApiError(this.getNode(),c,{message:a,description:`${l}${d}
159
172
 
160
- ${rt}`,itemIndex:e})}return r==="TextRevisionVerificationError"?new n8nWorkflow.NodeApiError(this.getNode(),{message:n},{message:"The revised text could not be realized in the document, so nothing was applied.",description:`${n}
173
+ ${xt}`,itemIndex:e})}return r==="TextRevisionVerificationError"?new n8nWorkflow.NodeApiError(this.getNode(),{message:n},{message:"The revised text could not be realized in the document, so nothing was applied.",description:`${n}
161
174
 
162
175
  No file is written by this node \u2014 ignore the paths named above; the input document is returned unchanged and no binary is produced. Structure such as headings, table rows, and footnotes cannot be removed by text replacement. Re-read the document with the Extract Markdown operation (Clean View on, Page 0), edit that exact text, and resend it in 'Revised Text'.`,itemIndex:e}):r==="TextRevisionError"?new n8nWorkflow.NodeApiError(this.getNode(),{message:n},{message:"The revised text was refused before anything was applied.",description:`${n}
163
176
 
164
- Send the COMPLETE clean text of the document in 'Revised Text' \u2014 read it with the Extract Markdown operation using Clean View on and Page 0 \u2014 with no CriticMarkup tags. If the revision is genuinely meant to delete most of the document, switch 'Allow Major Deletions' on.`,itemIndex:e}):o.includes("invalid docx")||o.includes("missing word/document.xml")?new n8nWorkflow.NodeApiError(this.getNode(),{message:n},{message:"The document could not be opened.",description:"Verify the input binary is a valid .docx file (not .doc, .pdf, or another format).",itemIndex:e}):new n8nWorkflow.NodeApiError(this.getNode(),{message:n},{message:"Adeu engine error.",description:n,itemIndex:e})}g(Ii,"mapAdeuErrorToNodeApiError");function gl(t){if(!t||typeof t!="object")return false;let e=t;return typeof e.id=="string"&&typeof e.fileName=="string"&&typeof e.mimeType=="string"}g(gl,"isStashedBinaryEntry");var $i=[{displayName:"Static Data Key",name:"staticDataKey",type:"string",default:"adeu_last_redlined",required:true,placeholder:"e.g. adeu_last_redlined",description:"Key in workflow global static data to read the stashed binary metadata from (string). When the Apply Edits operation runs as an AI Agent tool, n8n's tool wrapper strips the binary from its output before any downstream node can see it. To work around that, Apply Edits writes the binary's storage id into workflow static data under 'adeu_last_redlined'. This operation reads that entry back, fetches the original buffer via getBinaryStream, and attaches a fresh IBinaryData onto the outgoing item. Leave the default unless you've customized the stash key on the Apply Edits side.",displayOptions:{show:{resource:["document"],operation:["hydrateToolOutput"]}}},{displayName:"Output Binary Property",name:"outputBinaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property on the outgoing item that will hold the hydrated .docx (string, e.g. 'data'). Downstream nodes (e.g. Write Binary File, Gmail send) should be configured to read from this property name.",displayOptions:{show:{resource:["document"],operation:["hydrateToolOutput"]}}},{displayName:"On Missing",name:"onMissing",type:"options",default:"emit_empty",description:"What to do when no stashed binary entry is found under the configured key. 'Emit Empty' is the typical AI Agent path: emits an item with json.hydrated=false and no binary, so a downstream If node can gate any write step on whether the LLM actually called Apply Edits this turn. 'Throw' is for deterministic pipelines where the stash MUST be present and a missing entry indicates a workflow bug.",options:[{name:"Emit Empty",value:"emit_empty",description:"Emit a single item with JSON.hydrated=false and no binary. Downstream If on JSON.hydrated gates the write."},{name:"Throw",value:"throw",description:"Throw a NodeOperationError. Use when a missing stash indicates a workflow bug."}],displayOptions:{show:{resource:["document"],operation:["hydrateToolOutput"]}}},{displayName:"Clear After Read",name:"clearAfterRead",type:"boolean",default:true,description:"Whether to delete the static data entry after a successful hydration so it does not leak across workflow runs. Set false if you want to inspect or re-read the entry from a later node in the same run.",displayOptions:{show:{resource:["document"],operation:["hydrateToolOutput"]}}},{displayName:"Output Path Template",name:"outputPathTemplate",type:"string",default:"",placeholder:"e.g. C:\\Users\\Uzair\\.n8n-files\\{baseName}_{timestamp}.docx",description:"Optional template to compute the final write path on disk, returned on the output JSON as 'outputPath'. If set, you can configure downstream Write nodes to simply read '{{ $json.outputPath }}' with zero escaping risks. Supports these placeholders: '{baseName}' (filename with extension stripped), '{timestamp}' (current ISO 8601 timestamp with colons and dots replaced by dashes for Windows file compatibility), '{fileName}' (the stashed filename including extension), and '{ext}' (e.g., '.docx').",displayOptions:{show:{resource:["document"],operation:["hydrateToolOutput"]}}}];async function Oi(t){let e=this.getNodeParameter("staticDataKey",t),n=this.getNodeParameter("outputBinaryPropertyName",t),r=this.getNodeParameter("onMissing",t),s=this.getNodeParameter("clearAfterRead",t),i=this.getWorkflowStaticData("global"),o=i[e];if(!gl(o)){if(r==="throw")throw new n8nWorkflow.NodeOperationError(this.getNode(),`No stashed binary found under static data key "${e}".`,{description:"The Apply Edits operation writes a stash entry into workflow static data only when it runs as an AI Agent tool and produces a binary. Verify that Apply Edits was actually called by the agent this turn, that it ran successfully, and that the key matches the one used on the writing side.",itemIndex:t});return [{json:{hydrated:false},pairedItem:{item:t}}]}let{id:l,fileName:a,mimeType:u}=o,c;try{let p=await this.helpers.getBinaryStream(l);c=await this.helpers.binaryToBuffer(p);}catch(p){throw new n8nWorkflow.NodeOperationError(this.getNode(),`Failed to load stashed binary (id=${l}) from external storage.`,{description:`The stash entry under "${e}" points at binary id "${l}", but the underlying data could not be loaded. This usually means the binary has been garbage-collected (n8n's execution data retention may be too short) or external storage is unavailable. Underlying error: ${p.message}`,itemIndex:t})}let d=u||me,f=await this.helpers.prepareBinaryData(c,a,d);s&&delete i[e];let h=this.getNodeParameter("outputPathTemplate",t,""),_;if(h.trim()!==""){let p=a.replace(/\.docx$/i,""),m=a.match(/\.docx$/i)?.[0]??".docx",y=new Date().toISOString().replace(/[:.]/g,"-").replace(/Z$/,"");_=h.replaceAll("{baseName}",p).replaceAll("{timestamp}",y).replaceAll("{fileName}",a).replaceAll("{ext}",m);}return [{json:{hydrated:true,fileName:a,sourceBinaryId:l,mimeType:d,..._!==void 0?{outputPath:_}:{}},binary:{[n]:f},pairedItem:{item:t}}]}g(Oi,"executeHydrateToolOutput");var Di=[{displayName:"Input Binary Property",name:"binaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property holding the .docx file (string, e.g. 'data'). In 'From Connected Input' mode this reads from the current item; in 'From Another Node' mode this specifies which property on the source node's output to read. Must be a valid .docx (not .doc, .pdf, or another format).",displayOptions:{show:{resource:["document"],operation:["extractMarkdown"]}}},{displayName:"Clean View",name:"cleanView",type:"boolean",default:false,description:"Whether to project the document as if all pending tracked changes were accepted (simulates Accept All). When false (default), all tracked changes are surfaced inline as CriticMarkup ({++ins++}, {--del--}, {>>comment<<}) so an AI can review and resolve them. Use false to review counterparty edits; use true to generate net-new redlines against a clean baseline.",displayOptions:{show:{resource:["document"],operation:["extractMarkdown"]}}},{displayName:"Include Appendix",name:"includeAppendix",type:"boolean",default:true,description:"Whether to include the Structural Appendix (defined terms, cross-reference anchors, and potential typos) at the end of the projection. True by default for rich LLM context.",displayOptions:{show:{resource:["document"],operation:["extractMarkdown"]}}},{displayName:"Page",name:"page",type:"number",default:0,typeOptions:{minValue:0},description:"Optional 1-based page number to return only one page of the projected document (integer, default 0). When 0 (default), the full Markdown body plus the Structural Appendix is returned in the 'markdown' field and pagination metadata is omitted. When >= 1, only that page is returned in the 'markdown' field and the JSON output includes pagination metadata: page, total_pages, has_next, has_prev, tracked_change_count. Pages are ~19,000-character chunks of the projected body with the Structural Appendix appended to each page. Use the extractOutline operation first to discover how many pages exist and what each page contains. If the requested page exceeds total_pages, an error is thrown.",displayOptions:{show:{resource:["document"],operation:["extractMarkdown"]}}}];async function Mi(t){let e=this.getNodeParameter("binaryPropertyName",t),n=this.getNodeParameter("cleanView",t),r=this.getNodeParameter("includeAppendix",t,true),s=this.getNodeParameter("page",t,0),o=this.getNodeParameter("documentSource",t,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",t,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",t,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:l,fileName:a}=await oe.call(this,t,o),u=await Be(l,n,r);if(!s||s===0)return [{json:{fileName:a,cleanView:n,markdown:u},pairedItem:{item:t}}];let[c,d]=Xe(u),f=Ge(c,d);if(s>f.total_pages)throw new n8nWorkflow.NodeOperationError(this.getNode(),`Requested page ${s} exceeds total_pages (${f.total_pages}). Call extractOutline to discover the page count first.`,{itemIndex:t});let h=f.pages[s-1];return [{json:{fileName:a,cleanView:n,markdown:h.page_content,page:h.page,total_pages:h.total_pages,has_next:h.has_next,has_prev:h.has_prev,tracked_change_count:h.tracked_change_count},pairedItem:{item:t}}]}g(Mi,"executeExtractMarkdown");var Ri=[{displayName:"Input Binary Property",name:"binaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property holding the .docx file (string, e.g. 'data'). In 'From Connected Input' mode this reads from the current item; in 'From Another Node' mode this specifies which property on the source node's output to read. Must be a valid .docx.",displayOptions:{show:{resource:["document"],operation:["extractOutline"]}}}];async function ji(t){let e=this.getNodeParameter("binaryPropertyName",t),r=this.getNodeParameter("documentSource",t,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",t,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",t,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:s,fileName:i}=await oe.call(this,t,r),o=await ce.load(s),l=Fe(o,false,true,true),[a]=Xe(l.text),u=Ge(a,""),c=hi(o,a,u.body_pages,u.body_page_offsets,l.paragraph_offsets);return [{json:{fileName:i,total_pages:u.total_pages,outline:c.map(d=>({level:d.level,text:d.text,page:d.page,end_page:d.end_page,style:d.style,has_table:d.has_table,footnote_ids:d.footnote_ids}))},pairedItem:{item:t}}]}g(ji,"executeExtractOutline");var Bi=[{displayName:"Reasoning",name:"reasoning",type:"string",default:"",typeOptions:{rows:2},description:"Why these edits are being made. State your reasoning BEFORE the changes \u2014 what you intend to change and why \u2014 then produce the Changes (JSON) array. This field is captured for auditability and is NOT forwarded into the redline engine; its only purpose is to make the AI reason first, which improves edit quality. Safe to leave empty in deterministic (non-AI) pipelines.",displayOptions:{show:{resource:["document"],operation:["applyEdits"]}}},{displayName:"Input Binary Property",name:"binaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property holding the .docx file (string, e.g. 'data'). In 'From Connected Input' mode this reads from the current item; in 'From Another Node' mode this specifies which property on the source node's output to read. The file must be a valid .docx.",displayOptions:{show:{resource:["document"],operation:["applyEdits"]}}},{displayName:"Output Binary Property",name:"outputBinaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property on the outgoing item that will hold the redlined .docx file (string, e.g. 'data'). If equal to the input property name, the original binary is overwritten on the outgoing item.",displayOptions:{show:{resource:["document"],operation:["applyEdits"]}}},{displayName:"Author",name:"author",type:"string",default:"Adeu AI",placeholder:"e.g. AI Reviewer",description:"Author name attached to all tracked changes and comments produced by this operation (string, e.g. 'AI Reviewer'). Shows up in Word's review pane as the author of every redline and comment created in this batch.",displayOptions:{show:{resource:["document"],operation:["applyEdits"]}}},{displayName:"Edits Source",name:"editsSource",type:"options",noDataExpression:true,default:"fromInputJson",description:"Where to read the list of DocumentChange objects from. Use 'Define Below' to read the array from the Changes (JSON) field on this node \u2014 this is the typical AI Agent path, since the LLM generates the array as a tool call argument that lands on that field via $fromAI(). Use 'From Input JSON' to read the array from a property on the upstream item's JSON, for deterministic pipelines where a non-AI node (HTTP Request, Code, etc.) has pre-populated it.",options:[{name:"Define Below",value:"defineBelow",description:"Read the array from the Changes (JSON) field on this node. Use for AI Agent workflows \u2014 the LLM populates that field via $fromAI() as a tool call argument."},{name:"From Input JSON",value:"fromInputJson",description:"Read the array from a property on the upstream item's JSON. Use for deterministic pipelines where a non-AI node has pre-populated the changes array."}],displayOptions:{show:{resource:["document"],operation:["applyEdits"]}}},{displayName:"JSON Path on Input Item",name:"editsJsonPath",type:"string",default:"changes",required:true,placeholder:"e.g. data.changes",description:"Property path on the input item JSON whose value is the array of DocumentChange objects (string, dot-notation supported, e.g. 'changes' or 'data.changes'). Must resolve to an array; throws an error otherwise.",displayOptions:{show:{resource:["document"],operation:["applyEdits"],editsSource:["fromInputJson"]}}},{displayName:"Changes (JSON)",name:"editsJson",type:"string",default:`[
177
+ Send the COMPLETE clean text of the document in 'Revised Text' \u2014 read it with the Extract Markdown operation using Clean View on and Page 0 \u2014 with no CriticMarkup tags. If the revision is genuinely meant to delete most of the document, switch 'Allow Major Deletions' on.`,itemIndex:e}):s.includes("invalid docx")||s.includes("missing word/document.xml")?new n8nWorkflow.NodeApiError(this.getNode(),{message:n},{message:"The document could not be opened.",description:"Verify the input binary is a valid .docx file (not .doc, .pdf, or another format).",itemIndex:e}):new n8nWorkflow.NodeApiError(this.getNode(),{message:n},{message:"Adeu engine error.",description:n,itemIndex:e})}g(Xo,"mapAdeuErrorToNodeApiError");function Vu(t){if(!t||typeof t!="object")return false;let e=t;return typeof e.id=="string"&&typeof e.fileName=="string"&&typeof e.mimeType=="string"}g(Vu,"isStashedBinaryEntry");var Go=[{displayName:"Static Data Key",name:"staticDataKey",type:"string",default:"adeu_last_redlined",required:true,placeholder:"e.g. adeu_last_redlined",description:"Key in workflow global static data to read the stashed binary metadata from (string). When the Apply Edits operation runs as an AI Agent tool, n8n's tool wrapper strips the binary from its output before any downstream node can see it. To work around that, Apply Edits writes the binary's storage id into workflow static data under 'adeu_last_redlined'. This operation reads that entry back, fetches the original buffer via getBinaryStream, and attaches a fresh IBinaryData onto the outgoing item. Leave the default unless you've customized the stash key on the Apply Edits side.",displayOptions:{show:{resource:["document"],operation:["hydrateToolOutput"]}}},{displayName:"Output Binary Property",name:"outputBinaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property on the outgoing item that will hold the hydrated .docx (string, e.g. 'data'). Downstream nodes (e.g. Write Binary File, Gmail send) should be configured to read from this property name.",displayOptions:{show:{resource:["document"],operation:["hydrateToolOutput"]}}},{displayName:"On Missing",name:"onMissing",type:"options",default:"emit_empty",description:"What to do when no stashed binary entry is found under the configured key. 'Emit Empty' is the typical AI Agent path: emits an item with json.hydrated=false and no binary, so a downstream If node can gate any write step on whether the LLM actually called Apply Edits this turn. 'Throw' is for deterministic pipelines where the stash MUST be present and a missing entry indicates a workflow bug.",options:[{name:"Emit Empty",value:"emit_empty",description:"Emit a single item with JSON.hydrated=false and no binary. Downstream If on JSON.hydrated gates the write."},{name:"Throw",value:"throw",description:"Throw a NodeOperationError. Use when a missing stash indicates a workflow bug."}],displayOptions:{show:{resource:["document"],operation:["hydrateToolOutput"]}}},{displayName:"Clear After Read",name:"clearAfterRead",type:"boolean",default:true,description:"Whether to delete the static data entry after a successful hydration so it does not leak across workflow runs. Set false if you want to inspect or re-read the entry from a later node in the same run.",displayOptions:{show:{resource:["document"],operation:["hydrateToolOutput"]}}},{displayName:"Output Path Template",name:"outputPathTemplate",type:"string",default:"",placeholder:"e.g. C:\\Users\\Uzair\\.n8n-files\\{baseName}_{timestamp}.docx",description:"Optional template to compute the final write path on disk, returned on the output JSON as 'outputPath'. If set, you can configure downstream Write nodes to simply read '{{ $json.outputPath }}' with zero escaping risks. Supports these placeholders: '{baseName}' (filename with extension stripped), '{timestamp}' (current ISO 8601 timestamp with colons and dots replaced by dashes for Windows file compatibility), '{fileName}' (the stashed filename including extension), and '{ext}' (e.g., '.docx').",displayOptions:{show:{resource:["document"],operation:["hydrateToolOutput"]}}}];async function Jo(t){let e=this.getNodeParameter("staticDataKey",t),n=this.getNodeParameter("outputBinaryPropertyName",t),r=this.getNodeParameter("onMissing",t),i=this.getNodeParameter("clearAfterRead",t),o=this.getWorkflowStaticData("global"),s=o[e];if(!Vu(s)){if(r==="throw")throw new n8nWorkflow.NodeOperationError(this.getNode(),`No stashed binary found under static data key "${e}".`,{description:"The Apply Edits operation writes a stash entry into workflow static data only when it runs as an AI Agent tool and produces a binary. Verify that Apply Edits was actually called by the agent this turn, that it ran successfully, and that the key matches the one used on the writing side.",itemIndex:t});return [{json:{hydrated:false},pairedItem:{item:t}}]}let{id:a,fileName:l,mimeType:u}=s,c;try{let p=await this.helpers.getBinaryStream(a);c=await this.helpers.binaryToBuffer(p);}catch(p){throw new n8nWorkflow.NodeOperationError(this.getNode(),`Failed to load stashed binary (id=${a}) from external storage.`,{description:`The stash entry under "${e}" points at binary id "${a}", but the underlying data could not be loaded. This usually means the binary has been garbage-collected (n8n's execution data retention may be too short) or external storage is unavailable. Underlying error: ${p.message}`,itemIndex:t})}let d=u||ye,f=await this.helpers.prepareBinaryData(c,l,d);i&&delete o[e];let h=this.getNodeParameter("outputPathTemplate",t,""),_;if(h.trim()!==""){let p=l.replace(/\.docx$/i,""),m=l.match(/\.docx$/i)?.[0]??".docx",w=new Date().toISOString().replace(/[:.]/g,"-").replace(/Z$/,"");_=h.replaceAll("{baseName}",p).replaceAll("{timestamp}",w).replaceAll("{fileName}",l).replaceAll("{ext}",m);}return [{json:{hydrated:true,fileName:l,sourceBinaryId:a,mimeType:d,..._!==void 0?{outputPath:_}:{}},binary:{[n]:f},pairedItem:{item:t}}]}g(Jo,"executeHydrateToolOutput");var mr=ut("extractMarkdown"),Yo=[{displayName:"Input Binary Property",name:"binaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property holding the .docx file (string, e.g. 'data'). In 'From Connected Input' mode this reads from the current item; in 'From Another Node' mode this specifies which property on the source node's output to read. Must be a valid .docx (not .doc, .pdf, or another format).",displayOptions:mr},{displayName:"Clean View",name:"cleanView",type:"boolean",default:false,description:"Whether to project the document as if all pending tracked changes were accepted (simulates Accept All). When false (default), all tracked changes are surfaced inline as CriticMarkup ({++ins++}, {--del--}, {>>comment<<}) so an AI can review and resolve them. Use false to review counterparty edits; use true to generate net-new redlines against a clean baseline.",displayOptions:mr},{displayName:"Include Appendix",name:"includeAppendix",type:"boolean",default:true,description:"Whether to include the Structural Appendix (defined terms, cross-reference anchors, and potential typos) at the end of the projection. True by default for rich LLM context.",displayOptions:mr},{displayName:"Page",name:"page",type:"number",default:0,typeOptions:{minValue:0},description:"Optional 1-based page number to return only one page of the projected document (integer, default 0). When 0 (default), the full Markdown body plus the Structural Appendix is returned in the 'markdown' field and pagination metadata is omitted. When >= 1, only that page is returned in the 'markdown' field and the JSON output includes pagination metadata: page, total_pages, has_next, has_prev, tracked_change_count. Pages are ~19,000-character chunks of the projected body with the Structural Appendix appended to each page. Use the extractOutline operation first to discover how many pages exist and what each page contains. If the requested page exceeds total_pages, an error is thrown.",displayOptions:{show:{resource:["document"],operation:["extractMarkdown"]}}}];async function Qo(t){let e=this.getNodeParameter("binaryPropertyName",t),n=this.getNodeParameter("cleanView",t),r=this.getNodeParameter("includeAppendix",t,true),i=this.getNodeParameter("page",t,0),s=this.getNodeParameter("documentSource",t,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",t,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",t,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:a,fileName:l}=await se.call(this,t,s),u=await Ye(a,n,r);if(!i||i===0)return [{json:{fileName:l,cleanView:n,markdown:u},pairedItem:{item:t}}];let[c,d]=ot(u),f=st(c,d);if(i>f.total_pages)throw new n8nWorkflow.NodeOperationError(this.getNode(),`Requested page ${i} exceeds total_pages (${f.total_pages}). Call extractOutline to discover the page count first.`,{itemIndex:t});let h=f.pages[i-1];return [{json:{fileName:l,cleanView:n,markdown:h.page_content,page:h.page,total_pages:h.total_pages,has_next:h.has_next,has_prev:h.has_prev,tracked_change_count:h.tracked_change_count},pairedItem:{item:t}}]}g(Qo,"executeExtractMarkdown");var Vo=[{displayName:"Input Binary Property",name:"binaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property holding the .docx file (string, e.g. 'data'). In 'From Connected Input' mode this reads from the current item; in 'From Another Node' mode this specifies which property on the source node's output to read. Must be a valid .docx.",displayOptions:{show:{resource:["document"],operation:["extractOutline"]}}}];async function Zo(t){let e=this.getNodeParameter("binaryPropertyName",t),r=this.getNodeParameter("documentSource",t,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",t,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",t,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:i,fileName:o}=await se.call(this,t,r),s=await ce.load(i),a=Qe(s,false,true,true),[l]=ot(a.text),u=st(l,""),c=yo(s,l,u.body_pages,u.body_page_offsets,a.paragraph_offsets);return [{json:{fileName:o,total_pages:u.total_pages,outline:c.map(d=>({level:d.level,text:d.text,page:d.page,end_page:d.end_page,style:d.style,has_table:d.has_table,footnote_ids:d.footnote_ids}))},pairedItem:{item:t}}]}g(Zo,"executeExtractOutline");var ve={show:{resource:["document"],operation:["applyEdits"]}},Ko=[{displayName:"Reasoning",name:"reasoning",type:"string",default:"",typeOptions:{rows:2},description:"Why these edits are being made. State your reasoning BEFORE the changes \u2014 what you intend to change and why \u2014 then produce the Changes (JSON) array. This field is captured for auditability and is NOT forwarded into the redline engine; its only purpose is to make the AI reason first, which improves edit quality. Safe to leave empty in deterministic (non-AI) pipelines.",displayOptions:ve},{displayName:"Input Binary Property",name:"binaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property holding the .docx file (string, e.g. 'data'). In 'From Connected Input' mode this reads from the current item; in 'From Another Node' mode this specifies which property on the source node's output to read. The file must be a valid .docx.",displayOptions:ve},{displayName:"Output Binary Property",name:"outputBinaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property on the outgoing item that will hold the redlined .docx file (string, e.g. 'data'). If equal to the input property name, the original binary is overwritten on the outgoing item.",displayOptions:ve},{displayName:"Author",name:"author",type:"string",default:"Adeu AI",placeholder:"e.g. AI Reviewer",description:"Author name attached to all tracked changes and comments produced by this operation (string, e.g. 'AI Reviewer'). Shows up in Word's review pane as the author of every redline and comment created in this batch.",displayOptions:ve},{displayName:"Edits Source",name:"editsSource",type:"options",noDataExpression:true,default:"fromInputJson",description:"Where to read the list of DocumentChange objects from. Use 'Define Below' to read the array from the Changes (JSON) field on this node \u2014 this is the typical AI Agent path, since the LLM generates the array as a tool call argument that lands on that field via $fromAI(). Use 'From Input JSON' to read the array from a property on the upstream item's JSON, for deterministic pipelines where a non-AI node (HTTP Request, Code, etc.) has pre-populated it.",options:[{name:"Define Below",value:"defineBelow",description:"Read the array from the Changes (JSON) field on this node. Use for AI Agent workflows \u2014 the LLM populates that field via $fromAI() as a tool call argument."},{name:"From Input JSON",value:"fromInputJson",description:"Read the array from a property on the upstream item's JSON. Use for deterministic pipelines where a non-AI node has pre-populated the changes array."}],displayOptions:ve},{displayName:"JSON Path on Input Item",name:"editsJsonPath",type:"string",default:"changes",required:true,placeholder:"e.g. data.changes",description:"Property path on the input item JSON whose value is the array of DocumentChange objects (string, dot-notation supported, e.g. 'changes' or 'data.changes'). Must resolve to an array; throws an error otherwise.",displayOptions:{show:{resource:["document"],operation:["applyEdits"],editsSource:["fromInputJson"]}}},{displayName:"Changes (JSON)",name:"editsJson",type:"string",default:`[
165
178
  {
166
179
  "type": "modify",
167
180
  "target_text": "State of New York",
168
181
  "new_text": "State of Delaware",
169
182
  "comment": "Standardizing governing law."
170
183
  }
171
- ]`,required:true,description:`JSON-encoded string containing an array of DocumentChange objects. Each object has a 'type' field discriminator and type-specific fields. type='modify': requires target_text (string, copied EXACTLY from the source including punctuation, spacing, and case) and new_text (string); optional comment (string). Optional match_mode (one of 'strict' | 'first' | 'all', default 'strict'): 'strict' fails on ambiguous matches; 'first' silently anchors to the first occurrence; 'all' applies the same replacement to every occurrence in linear document order. Optional regex (boolean, default false): when true, target_text is interpreted as an ES2022 RegExp pattern and new_text may reference capture groups via $1, $2, etc. Combine with match_mode='all' for global regex replacements. Never include CriticMarkup tags like {++ ++} or {-- --} in new_text \u2014 the engine applies tracking automatically. Never target text already inside another author's pending tracked change. type='accept': requires target_id (string like 'Chg:12' from the Markdown projection); optional comment. type='reject': requires target_id (string like 'Chg:12'); optional comment. type='reply': requires target_id (string like 'Com:45') and text (string). type='insert_row': requires target_text (string anchoring a table cell), position ('above' or 'below'), and cells (array of strings, one per column). type='delete_row': requires target_text (string anchoring the row to delete). The whole batch is validated atomically: if any single edit fails (target text not found, ambiguous match under match_mode='strict', read-only target, overlapping another author's change), the entire batch is rejected and the document is left untouched. Example: '[{"type":"modify","target_text":"within thirty (30) days","new_text":"within forty-five (45) days","comment":"Per playbook.","match_mode":"all"}]'. Markdown code fences (\`\`\`json ... \`\`\`) wrapping the value are stripped automatically.`,typeOptions:{rows:10},displayOptions:{show:{resource:["document"],operation:["applyEdits"],editsSource:["defineBelow"]}}},{displayName:"Return Markdown Output",name:"returnMarkdown",type:"boolean",default:true,description:"Whether to auto-extract the post-edit document as Markdown (with CriticMarkup) and include it in the outgoing JSON under the 'markdown' field. Useful for feeding the updated state back into a downstream AI Agent for review or further edits. Adds extraction overhead per call.",displayOptions:{show:{resource:["document"],operation:["applyEdits"]}}},{displayName:"Allow Partial Application",name:"allowPartial",type:"boolean",default:false,description:"Whether to keep the changes that validate and report the ones that fail, instead of rejecting the whole batch. False (default) is transactional: if any single change is invalid, nothing is applied and the document is returned untouched. True is salvage mode: valid changes are applied and saved, 'status' on the output JSON reads 'partial', and 'stats.failed' lists each failure with its 0-based index in the submitted array. Salvage mode is for AI Agent loops that will fix and resubmit the rejected changes; do not use it where a half-applied redline would be shipped as final.",displayOptions:{show:{resource:["document"],operation:["applyEdits"]}}}];async function Fi(t){let e=this.getNodeParameter("binaryPropertyName",t),n=this.getNodeParameter("outputBinaryPropertyName",t),r=this.getNodeParameter("author",t),s=this.getNodeParameter("editsSource",t),i=this.getNodeParameter("returnMarkdown",t),o=this.getNodeParameter("allowPartial",t,false),l=this.getNodeParameter("reasoning",t,""),a;if(s==="fromInputJson"){let k=this.getNodeParameter("editsJsonPath",t),C=this.getInputData()[t].json;if(a=Ci(C,k),a===void 0)throw new Error(`No property "${k}" found on the input item JSON. Verify the upstream node produced it, or switch "Edits Source" to "Define Below".`)}else {let k=this.getNodeParameter("editsJson",t);a=Ti.call(this,k,t,"Changes (JSON)");}if(!Array.isArray(a))throw new Error("Changes must be an array of DocumentChange objects.");a=Pi(a);let c=this.getNodeParameter("documentSource",t,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",t,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",t,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:d,fileName:f}=await oe.call(this,t,c),h=await ce.load(d),p=new Tt(h,r,{id_discovery_hint:Ai}).process_batch(a,void 0,o),m=this.getInputData()[t].binary??{},y=await h.save(),x=Ye(f,"redlined"),b=await this.helpers.prepareBinaryData(y,x,me),w=typeof this.isToolExecution=="function"&&this.isToolExecution(),v;if(w&&b.id){let k=this.getWorkflowStaticData("global");k.adeu_last_redlined={id:b.id,fileName:x,mimeType:me,timestamp:Date.now()},v=b.id;}let N;return i&&(N=await Be(y,false)),[{json:{fileName:x,author:r,status:p.status??"ok",stats:p,...l!==""?{reasoning:l}:{},...N!==void 0?{markdown:N}:{},...v!==void 0?{redlinedBinaryId:v}:{}},binary:{...m,[n]:b},pairedItem:{item:t}}]}g(Fi,"executeApplyEdits");var Wi=[{displayName:"Reasoning",name:"reasoning",type:"string",default:"",typeOptions:{rows:2},description:"Why this revision is being applied. State your reasoning BEFORE the revised text \u2014 what you intend to change and why. This field is captured for auditability and is NOT forwarded into the redline engine; its only purpose is to make the AI reason first. Safe to leave empty in deterministic (non-AI) pipelines.",displayOptions:{show:{resource:["document"],operation:["applyTextRevision"]}}},{displayName:"Input Binary Property",name:"binaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property holding the .docx file (string, e.g. 'data'). In 'From Connected Input' mode this reads from the current item; in 'From Another Node' mode this specifies which property on the source node's output to read. The file must be a valid .docx.",displayOptions:{show:{resource:["document"],operation:["applyTextRevision"]}}},{displayName:"Output Binary Property",name:"outputBinaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property on the outgoing item that will hold the redlined .docx file (string, e.g. 'data'). If equal to the input property name, the original binary is overwritten on the outgoing item.",displayOptions:{show:{resource:["document"],operation:["applyTextRevision"]}}},{displayName:"Author",name:"author",type:"string",default:"Adeu AI",placeholder:"e.g. AI Reviewer",description:"Author name attached to every tracked change this revision produces (string, e.g. 'AI Reviewer'). Shows up in Word's review pane as the author of each redline.",displayOptions:{show:{resource:["document"],operation:["applyTextRevision"]}}},{displayName:"Revised Text",name:"revisedText",type:"string",default:"",required:true,typeOptions:{rows:10},description:"The COMPLETE revised clean text of the document. Read it first with the Extract Markdown operation using Clean View on and Page 0 (whole document), edit that text, then send all of it back \u2014 the engine diffs this against the document's clean view and turns the difference into tracked changes. Never include CriticMarkup tags ({++ ++}, {-- --}, {>> <<}); they would be applied as literal prose and are rejected. Never send a single page of a paginated extract: everything missing from this text is applied as a tracked deletion. A revision that removes more than 50% of the characters (75% for documents under 2,000 characters) is refused unless 'Allow Major Deletions' is on. After applying, the engine re-reads the document's clean text and compares it to this value; if they differ, nothing is returned and the operation fails, because some structure (headings, table rows, footnotes) cannot be removed by text replacement.",displayOptions:{show:{resource:["document"],operation:["applyTextRevision"]}}},{displayName:"Allow Major Deletions",name:"allowMajorDeletions",type:"boolean",default:false,description:"Whether to allow a revision that deletes more than 50% of the document's characters (more than 75% for documents under 2,000 characters). False (default) refuses such a revision on the assumption that the supplied text is a partial extract rather than the whole document.",displayOptions:{show:{resource:["document"],operation:["applyTextRevision"]}}}];async function zi(t){let e=this.getNodeParameter("binaryPropertyName",t),n=this.getNodeParameter("outputBinaryPropertyName",t),r=this.getNodeParameter("author",t),s=this.getNodeParameter("revisedText",t),i=this.getNodeParameter("allowMajorDeletions",t,false),o=this.getNodeParameter("reasoning",t,""),a=this.getNodeParameter("documentSource",t,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",t,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",t,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:u,fileName:c}=await oe.call(this,t,a),d=await ce.load(u),f=Ye(c,"redlined"),h=await ci({doc:d,input_path:c,output_path:f,revised_text:s,author:r,allow_major_deletions:i}),_=h.stats;delete _.output_path,delete _.unverified_output_path;let p=Buffer.from(h.out_bytes),m=await this.helpers.prepareBinaryData(p,f,me),y=typeof this.isToolExecution=="function"&&this.isToolExecution(),x;if(y&&m.id){let w=this.getWorkflowStaticData("global");w.adeu_last_redlined={id:m.id,fileName:f,mimeType:me,timestamp:Date.now()},x=m.id;}let b=this.getInputData()[t].binary??{};return [{json:{fileName:f,author:r,stats:_,...o!==""?{reasoning:o}:{},...x!==void 0?{redlinedBinaryId:x}:{}},binary:{...b,[n]:m},pairedItem:{item:t}}]}g(zi,"executeApplyTextRevision");var Li=[{displayName:"Original Document Source",name:"originalDocumentSource",type:"options",default:"fromInput",description:"Where to read the original (baseline) .docx file from. 'From Connected Input' reads from the current item; 'From Another Node' reads from a named upstream node \u2014 required when this node is called as an AI Agent tool.",options:[{name:"From Connected Input",value:"fromInput"},{name:"From Another Node",value:"fromNode"}],displayOptions:{show:{resource:["document"],operation:["generateDiff"]}}},{displayName:"Original Source Node Name",name:"originalSourceNodeName",type:"string",default:"",required:true,placeholder:"e.g. Download Original",description:"Exact name of the node whose output binary holds the original (baseline) .docx (string, case-sensitive). Must match the node label in the canvas exactly.",displayOptions:{show:{resource:["document"],operation:["generateDiff"],originalDocumentSource:["fromNode"]}}},{displayName:"Original Binary Property",name:"originalBinaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property holding the original (baseline) .docx file (string, e.g. 'data'). In 'From Connected Input' mode this reads from the current item; in 'From Another Node' mode this specifies which property on the source node's output to read.",displayOptions:{show:{resource:["document"],operation:["generateDiff"]}}},{displayName:"Modified Document Source",name:"modifiedDocumentSource",type:"options",default:"fromInput",description:"Where to read the modified (compared-to) .docx file from. 'From Connected Input' reads from the current item; 'From Another Node' reads from a named upstream node \u2014 required when this node is called as an AI Agent tool.",options:[{name:"From Connected Input",value:"fromInput"},{name:"From Another Node",value:"fromNode"}],displayOptions:{show:{resource:["document"],operation:["generateDiff"]}}},{displayName:"Modified Source Node Name",name:"modifiedSourceNodeName",type:"string",default:"",required:true,placeholder:"e.g. Apply Edits",description:"Exact name of the node whose output binary holds the modified (compared-to) .docx (string, case-sensitive). Must match the node label in the canvas exactly.",displayOptions:{show:{resource:["document"],operation:["generateDiff"],modifiedDocumentSource:["fromNode"]}}},{displayName:"Modified Binary Property",name:"modifiedBinaryPropertyName",type:"string",default:"data2",required:true,placeholder:"e.g. data2",description:"Name of the binary property holding the modified (compared-to) .docx file (string, e.g. 'data2'). In 'From Connected Input' mode this reads from the current item and must be different from the original property; in 'From Another Node' mode this specifies which property on the source node's output to read.",displayOptions:{show:{resource:["document"],operation:["generateDiff"]}}},{displayName:"Clean View",name:"cleanView",type:"boolean",default:true,description:"Whether to compare the Accept All clean view of both documents. When true (default, recommended), diffs reflect the final content as if all tracked changes were accepted. When false, diffs the raw CriticMarkup-projected text including pending change markers \u2014 useful for auditing tracked-change differences themselves.",displayOptions:{show:{resource:["document"],operation:["generateDiff"]}}},{displayName:"Diff Format",name:"diffFormat",type:"options",default:"wordPatch",description:"Format of the output diff. 'Word Patch' (default) produces an Adeu @@ Word Patch @@ text string showing sub-word modifications. 'Unified' produces a standard Git-style unified diff string. 'Structured Changes' produces a JSON array of DocumentChange objects suitable for feeding directly into Apply Edits.",options:[{name:"Word Patch",value:"wordPatch",description:"Adeu @@ Word Patch @@ sub-word text diff format"},{name:"Unified Diff",value:"unified",description:"Standard Git-style unified text diff format"},{name:"Structured Changes (JSON)",value:"structuredChanges",description:"JSON array of DocumentChange objects that transform original into modified"}],displayOptions:{show:{resource:["document"],operation:["generateDiff"]}}}];async function Ui(t){let e=this.getNodeParameter("originalBinaryPropertyName",t),n=this.getNodeParameter("modifiedBinaryPropertyName",t),r=this.getNodeParameter("cleanView",t),s=this.getNodeParameter("diffFormat",t,"wordPatch"),i=this.getNodeParameter("originalDocumentSource",t,"fromInput"),o=this.getNodeParameter("modifiedDocumentSource",t,"fromInput"),l=i==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("originalSourceNodeName",t,""),binaryPropertyName:e}:{mode:"fromInput",binaryPropertyName:e},a=o==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("modifiedSourceNodeName",t,""),binaryPropertyName:n}:{mode:"fromInput",binaryPropertyName:n},{buffer:u,fileName:c}=await oe.call(this,t,l),{buffer:d,fileName:f}=await oe.call(this,t,a),h=Kr(new Uint8Array(u),new Uint8Array(d));if(s==="structuredChanges"){let x=await ce.load(u),b=await ce.load(d),w=Fe(x,r,false,false,true),v=Fe(b,r,false,false,true),{edits:N,warnings:k}=Zr(w.text,w.structure,v.text,v.structure),C=[...h,...k];return [{json:{originalFileName:c,modifiedFileName:f,cleanView:r,diffFormat:s,changes:N,...C.length>0?{warnings:C}:{}},pairedItem:{item:t}}]}let _=await Be(u,r,false),p=await Be(d,r,false),m=s==="unified"?ei(_,p):ni(_,p,c,f);return (s==="unified"?m.trim()!=="":m.includes("@@ Word Patch @@"))||(m=`--- ${c}
184
+ ]`,required:true,description:`JSON-encoded string containing an array of DocumentChange objects. Each object has a 'type' field discriminator and type-specific fields. type='modify': requires target_text (string, copied EXACTLY from the source including punctuation, spacing, and case) and new_text (string); optional comment (string). Optional match_mode (one of 'strict' | 'first' | 'all', default 'strict'): 'strict' fails on ambiguous matches; 'first' silently anchors to the first occurrence; 'all' applies the same replacement to every occurrence in linear document order. Optional regex (boolean, default false): when true, target_text is interpreted as an ES2022 RegExp pattern and new_text may reference capture groups via $1, $2, etc. Combine with match_mode='all' for global regex replacements. Never include CriticMarkup tags like {++ ++} or {-- --} in new_text \u2014 the engine applies tracking automatically. Never target text already inside another author's pending tracked change. type='accept': requires target_id (string like 'Chg:12' from the Markdown projection); optional part (string like 'word/header1.xml' \u2014 revision ids are numbered per package part, so pass it only when the same id exists in several parts and the batch reports the ambiguity); optional comment. type='reject': requires target_id (string like 'Chg:12'); optional part as for accept; optional comment. type='reply': requires target_id (string like 'Com:45') and text (string). type='insert_row': requires target_text (string anchoring a table cell), position ('above' or 'below'), and cells (array of strings, one per column). type='delete_row': requires target_text (string anchoring the row to delete). The whole batch is validated atomically: if any single edit fails (target text not found, ambiguous match under match_mode='strict', read-only target, overlapping another author's change), the entire batch is rejected and the document is left untouched. Example: '[{"type":"modify","target_text":"within thirty (30) days","new_text":"within forty-five (45) days","comment":"Per playbook.","match_mode":"all"}]'. Markdown code fences (\`\`\`json ... \`\`\`) wrapping the value are stripped automatically.`,typeOptions:{rows:10},displayOptions:{show:{resource:["document"],operation:["applyEdits"],editsSource:["defineBelow"]}}},{displayName:"Return Markdown Output",name:"returnMarkdown",type:"boolean",default:true,description:"Whether to auto-extract the post-edit document as Markdown (with CriticMarkup) and include it in the outgoing JSON under the 'markdown' field. Useful for feeding the updated state back into a downstream AI Agent for review or further edits. Adds extraction overhead per call.",displayOptions:ve},{displayName:"Allow Partial Application",name:"allowPartial",type:"boolean",default:false,description:"Whether to keep the changes that validate and report the ones that fail, instead of rejecting the whole batch. False (default) is transactional: if any single change is invalid, nothing is applied and the document is returned untouched. True is salvage mode: valid changes are applied and saved, 'status' on the output JSON reads 'partial', and 'stats.failed' lists each failure with its 0-based index in the submitted array. Salvage mode is for AI Agent loops that will fix and resubmit the rejected changes; do not use it where a half-applied redline would be shipped as final.",displayOptions:ve},{displayName:"Ignore Content Control Locks",name:"ignoreControlLocks",type:"boolean",default:false,description:"Whether to apply edits even inside content-locked or grouped content controls. Word itself refuses these edits, so by default Adeu rejects them rather than reporting a success the document will not contain. Enable only when the document owner has accepted that the lock is wrong.",displayOptions:ve},{displayName:"Ignore Document Protection",name:"ignoreDocumentProtection",type:"boolean",default:false,description:"Whether to apply changes even when the document carries enforced editing protection (read-only, fill-in-forms, comments-only or tracked-changes-only). The restriction is honoured as the author's stated intent, not cracked; this bypasses it deliberately.",displayOptions:ve},{displayName:"Allow Untracked Writes",name:"allowUntrackedWrites",type:"boolean",default:false,description:"Whether to permit writes that Word records WITHOUT tracked changes. Applies only to fill-in-forms-protected documents, where Word does not record revisions at all and Adeu cannot honour its always-tracked guarantee. Separate from Ignore Document Protection because it concedes Adeu's own output guarantee rather than bypassing the author's restriction; every such write is flagged.",displayOptions:ve}];async function es(t){let e=this.getNodeParameter("binaryPropertyName",t),n=this.getNodeParameter("outputBinaryPropertyName",t),r=this.getNodeParameter("author",t),i=this.getNodeParameter("editsSource",t),o=this.getNodeParameter("returnMarkdown",t),s=this.getNodeParameter("allowPartial",t,false),a=this.getNodeParameter("ignoreControlLocks",t,false),l=this.getNodeParameter("ignoreDocumentProtection",t,false),u=this.getNodeParameter("allowUntrackedWrites",t,false),c=this.getNodeParameter("reasoning",t,""),d;if(i==="fromInputJson"){let C=this.getNodeParameter("editsJsonPath",t),T=this.getInputData()[t].json;if(d=zo(T,C),d===void 0)throw new Error(`No property "${C}" found on the input item JSON. Verify the upstream node produced it, or switch "Edits Source" to "Define Below".`)}else {let C=this.getNodeParameter("editsJson",t);d=Ho.call(this,C,t,"Changes (JSON)");}if(!Array.isArray(d))throw new Error("Changes must be an array of DocumentChange objects.");d=Uo(d);let h=this.getNodeParameter("documentSource",t,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",t,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",t,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:_,fileName:p}=await se.call(this,t,h),m=await ce.load(_),v=new dn(m,r,{id_discovery_hint:Lo,ignore_control_locks:a,ignore_document_protection:l,allow_untracked_writes:u}).process_batch(d,void 0,s),b=this.getInputData()[t].binary??{},y=await m.save(),x=dt(p,"redlined"),k=await this.helpers.prepareBinaryData(y,x,ye),N=typeof this.isToolExecution=="function"&&this.isToolExecution(),P;if(N&&k.id){let C=this.getWorkflowStaticData("global");C.adeu_last_redlined={id:k.id,fileName:x,mimeType:ye,timestamp:Date.now()},P=k.id;}let A;return o&&(A=await Ye(y,false)),[{json:{fileName:x,author:r,status:v.status??"ok",stats:v,...c!==""?{reasoning:c}:{},...A!==void 0?{markdown:A}:{},...P!==void 0?{redlinedBinaryId:P}:{}},binary:{...b,[n]:k},pairedItem:{item:t}}]}g(es,"executeApplyEdits");var ft=ut("applyTextRevision"),ts=[{displayName:"Reasoning",name:"reasoning",type:"string",default:"",typeOptions:{rows:2},description:"Why this revision is being applied. State your reasoning BEFORE the revised text \u2014 what you intend to change and why. This field is captured for auditability and is NOT forwarded into the redline engine; its only purpose is to make the AI reason first. Safe to leave empty in deterministic (non-AI) pipelines.",displayOptions:ft},{displayName:"Input Binary Property",name:"binaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property holding the .docx file (string, e.g. 'data'). In 'From Connected Input' mode this reads from the current item; in 'From Another Node' mode this specifies which property on the source node's output to read. The file must be a valid .docx.",displayOptions:ft},{displayName:"Output Binary Property",name:"outputBinaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property on the outgoing item that will hold the redlined .docx file (string, e.g. 'data'). If equal to the input property name, the original binary is overwritten on the outgoing item.",displayOptions:ft},{displayName:"Author",name:"author",type:"string",default:"Adeu AI",placeholder:"e.g. AI Reviewer",description:"Author name attached to every tracked change this revision produces (string, e.g. 'AI Reviewer'). Shows up in Word's review pane as the author of each redline.",displayOptions:ft},{displayName:"Revised Text",name:"revisedText",type:"string",default:"",required:true,typeOptions:{rows:10},description:"The COMPLETE revised clean text of the document. Read it first with the Extract Markdown operation using Clean View on and Page 0 (whole document), edit that text, then send all of it back \u2014 the engine diffs this against the document's clean view and turns the difference into tracked changes. Never include CriticMarkup tags ({++ ++}, {-- --}, {>> <<}); they would be applied as literal prose and are rejected. Never send a single page of a paginated extract: everything missing from this text is applied as a tracked deletion. A revision that removes more than 50% of the characters (75% for documents under 2,000 characters) is refused unless 'Allow Major Deletions' is on. After applying, the engine re-reads the document's clean text and compares it to this value; if they differ, nothing is returned and the operation fails, because some structure (headings, table rows, footnotes) cannot be removed by text replacement.",displayOptions:ft},{displayName:"Allow Major Deletions",name:"allowMajorDeletions",type:"boolean",default:false,description:"Whether to allow a revision that deletes more than 50% of the document's characters (more than 75% for documents under 2,000 characters). False (default) refuses such a revision on the assumption that the supplied text is a partial extract rather than the whole document.",displayOptions:ft}];async function ns(t){let e=this.getNodeParameter("binaryPropertyName",t),n=this.getNodeParameter("outputBinaryPropertyName",t),r=this.getNodeParameter("author",t),i=this.getNodeParameter("revisedText",t),o=this.getNodeParameter("allowMajorDeletions",t,false),s=this.getNodeParameter("reasoning",t,""),l=this.getNodeParameter("documentSource",t,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",t,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",t,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:u,fileName:c}=await se.call(this,t,l),d=await ce.load(u),f=dt(c,"redlined"),h=await Bo({doc:d,input_path:c,output_path:f,revised_text:i,author:r,allow_major_deletions:o}),_=h.stats;delete _.output_path,delete _.unverified_output_path;let p=Buffer.from(h.out_bytes),m=await this.helpers.prepareBinaryData(p,f,ye),w=typeof this.isToolExecution=="function"&&this.isToolExecution(),v;if(w&&m.id){let y=this.getWorkflowStaticData("global");y.adeu_last_redlined={id:m.id,fileName:f,mimeType:ye,timestamp:Date.now()},v=m.id;}let b=this.getInputData()[t].binary??{};return [{json:{fileName:f,author:r,stats:_,...s!==""?{reasoning:s}:{},...v!==void 0?{redlinedBinaryId:v}:{}},binary:{...b,[n]:m},pairedItem:{item:t}}]}g(ns,"executeApplyTextRevision");var hn=ut("generateDiff"),rs=[{displayName:"Original Document Source",name:"originalDocumentSource",type:"options",default:"fromInput",description:"Where to read the original (baseline) .docx file from. 'From Connected Input' reads from the current item; 'From Another Node' reads from a named upstream node \u2014 required when this node is called as an AI Agent tool.",options:[{name:"From Connected Input",value:"fromInput"},{name:"From Another Node",value:"fromNode"}],displayOptions:hn},{displayName:"Original Source Node Name",name:"originalSourceNodeName",type:"string",default:"",required:true,placeholder:"e.g. Download Original",description:"Exact name of the node whose output binary holds the original (baseline) .docx (string, case-sensitive). Must match the node label in the canvas exactly.",displayOptions:{show:{resource:["document"],operation:["generateDiff"],originalDocumentSource:["fromNode"]}}},{displayName:"Original Binary Property",name:"originalBinaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property holding the original (baseline) .docx file (string, e.g. 'data'). In 'From Connected Input' mode this reads from the current item; in 'From Another Node' mode this specifies which property on the source node's output to read.",displayOptions:hn},{displayName:"Modified Document Source",name:"modifiedDocumentSource",type:"options",default:"fromInput",description:"Where to read the modified (compared-to) .docx file from. 'From Connected Input' reads from the current item; 'From Another Node' reads from a named upstream node \u2014 required when this node is called as an AI Agent tool.",options:[{name:"From Connected Input",value:"fromInput"},{name:"From Another Node",value:"fromNode"}],displayOptions:hn},{displayName:"Modified Source Node Name",name:"modifiedSourceNodeName",type:"string",default:"",required:true,placeholder:"e.g. Apply Edits",description:"Exact name of the node whose output binary holds the modified (compared-to) .docx (string, case-sensitive). Must match the node label in the canvas exactly.",displayOptions:{show:{resource:["document"],operation:["generateDiff"],modifiedDocumentSource:["fromNode"]}}},{displayName:"Modified Binary Property",name:"modifiedBinaryPropertyName",type:"string",default:"data2",required:true,placeholder:"e.g. data2",description:"Name of the binary property holding the modified (compared-to) .docx file (string, e.g. 'data2'). In 'From Connected Input' mode this reads from the current item and must be different from the original property; in 'From Another Node' mode this specifies which property on the source node's output to read.",displayOptions:hn},{displayName:"Clean View",name:"cleanView",type:"boolean",default:true,description:"Whether to compare the Accept All clean view of both documents. When true (default, recommended), diffs reflect the final content as if all tracked changes were accepted. When false, diffs the raw CriticMarkup-projected text including pending change markers \u2014 useful for auditing tracked-change differences themselves.",displayOptions:{show:{resource:["document"],operation:["generateDiff"]}}},{displayName:"Diff Format",name:"diffFormat",type:"options",default:"wordPatch",description:"Format of the output diff. 'Word Patch' (default) produces an Adeu @@ Word Patch @@ text string showing sub-word modifications. 'Unified' produces a standard Git-style unified diff string. 'Structured Changes' produces a JSON array of DocumentChange objects suitable for feeding directly into Apply Edits.",options:[{name:"Word Patch",value:"wordPatch",description:"Adeu @@ Word Patch @@ sub-word text diff format"},{name:"Unified Diff",value:"unified",description:"Standard Git-style unified text diff format"},{name:"Structured Changes (JSON)",value:"structuredChanges",description:"JSON array of DocumentChange objects that transform original into modified"}],displayOptions:{show:{resource:["document"],operation:["generateDiff"]}}}];async function is(t){let e=this.getNodeParameter("originalBinaryPropertyName",t),n=this.getNodeParameter("modifiedBinaryPropertyName",t),r=this.getNodeParameter("cleanView",t),i=this.getNodeParameter("diffFormat",t,"wordPatch"),o=this.getNodeParameter("originalDocumentSource",t,"fromInput"),s=this.getNodeParameter("modifiedDocumentSource",t,"fromInput"),a=o==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("originalSourceNodeName",t,""),binaryPropertyName:e}:{mode:"fromInput",binaryPropertyName:e},l=s==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("modifiedSourceNodeName",t,""),binaryPropertyName:n}:{mode:"fromInput",binaryPropertyName:n},{buffer:u,fileName:c}=await se.call(this,t,a),{buffer:d,fileName:f}=await se.call(this,t,l),h=co(new Uint8Array(u),new Uint8Array(d));if(i==="structuredChanges"){let v=await ce.load(u),b=await ce.load(d),y=Qe(v,r,false,false,true),x=Qe(b,r,false,false,true),{edits:k,warnings:N}=lo(y.text,y.structure,x.text,x.structure),P=[...h,...N];return [{json:{originalFileName:c,modifiedFileName:f,cleanView:r,diffFormat:i,changes:k,...P.length>0?{warnings:P}:{}},pairedItem:{item:t}}]}let _=await Ye(u,r,false),p=await Ye(d,r,false),m=i==="unified"?uo(_,p):ho(_,p,c,f);return (i==="unified"?m.trim()!=="":m.includes("@@ Word Patch @@"))||(m=`--- ${c}
172
185
  +++ ${f}
173
186
 
174
187
  No textual differences found between the documents.`),h.length>0&&(m=h.map(b=>`\u26A0\uFE0F ${b}`).join(`
175
188
  `)+`
176
189
 
177
- `+m),[{json:{originalFileName:c,modifiedFileName:f,cleanView:r,diffFormat:s,diff:m,...h.length>0?{warnings:h}:{}},pairedItem:{item:t}}]}g(Ui,"executeGenerateDiff");var Hi=[{displayName:"Reasoning",name:"reasoning",type:"string",default:"",typeOptions:{rows:2},description:"Why the document is being finalized now \u2014 e.g. what state it's in and why it's ready for distribution. State your reasoning BEFORE choosing the sanitize mode and options. This field is captured for auditability and is NOT forwarded into the finalize engine; its only purpose is to make the AI reason first. Safe to leave empty in deterministic (non-AI) pipelines.",displayOptions:{show:{resource:["document"],operation:["finalizeDocument"]}}},{displayName:"Input Binary Property",name:"binaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property holding the .docx file (string, e.g. 'data'). In 'From Connected Input' mode this reads from the current item; in 'From Another Node' mode this specifies which property on the source node's output to read. The file must be a valid .docx.",displayOptions:{show:{resource:["document"],operation:["finalizeDocument"]}}},{displayName:"Output Binary Property",name:"outputBinaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property on the outgoing item that will hold the finalized .docx file (string, e.g. 'data'). If equal to the input property name, the original binary is overwritten on the outgoing item.",displayOptions:{show:{resource:["document"],operation:["finalizeDocument"]}}},{displayName:"Sanitize Mode",name:"sanitizeMode",type:"options",default:"full",description:"How aggressively to sanitize the document before distribution. One of: 'baseline' (minimal metadata cleanup only), 'full' (strip metadata AND require all tracked changes resolved or auto-accepted), 'keep-markup' (strip metadata but preserve visible tracked changes and comments, optionally with author rewrite).",options:[{name:"Baseline",value:"baseline",description:"Minimal sanitization: strip RSID attributes, paragraph IDs, and proof errors only. Leaves tracked changes, comments, authors, and other metadata untouched."},{name:"Full",value:"full",description:"Strip metadata (authors, RSIDs, paragraph IDs, proof errors) and require all tracked changes and comments to be resolved. If pending tracked changes exist and 'Accept All Tracked Changes' is false, the operation is blocked and an error is thrown."},{name:"Keep Markup",value:"keep-markup",description:"Strip metadata but preserve all visible tracked changes and comments. Use 'Author Override' to rewrite the author name on every preserved redline and comment (e.g. replace 'AI Reviewer' with your firm name)."}],displayOptions:{show:{resource:["document"],operation:["finalizeDocument"]}}},{displayName:"Accept All Tracked Changes",name:"acceptAll",type:"boolean",default:false,description:"Whether to auto-accept all pending tracked changes before sanitization. Only applies when Sanitize Mode is 'full'. When false (default), the operation throws an error if any pending tracked changes exist, forcing the caller to resolve them first. If multiple distinct authors are detected in pending changes, a warning is included in the report to alert you of potential silent smuggles.",displayOptions:{show:{resource:["document"],operation:["finalizeDocument"],sanitizeMode:["full"]}}},{displayName:"Author Override",name:"authorOverride",type:"string",default:"",placeholder:"e.g. My Firm",description:"Only applies when Sanitize Mode is 'keep-markup'. Optional string. When set, replaces the author name on every preserved tracked change and comment with this value (e.g. 'My Law Firm'). Leave empty to keep original authors intact.",displayOptions:{show:{resource:["document"],operation:["finalizeDocument"],sanitizeMode:["keep-markup"]}}},{displayName:"Protection Mode",name:"protectionMode",type:"options",default:"none",description:"Optionally lock the finalized document. 'none' (default) leaves the document unlocked. 'read_only' injects a native Word read-only enforcement flag into settings.xml \u2014 Word users see a read-only banner and cannot edit without explicitly unlocking. AES encryption is not supported in this engine.",options:[{name:"None",value:"none"},{name:"Read Only",value:"read_only"}],displayOptions:{show:{resource:["document"],operation:["finalizeDocument"]}}}];async function qi(t){let e=this.getNodeParameter("binaryPropertyName",t),n=this.getNodeParameter("outputBinaryPropertyName",t),r=this.getNodeParameter("sanitizeMode",t),s=false;r==="full"&&(s=this.getNodeParameter("acceptAll",t));let i=null;if(r==="keep-markup"){let b=this.getNodeParameter("authorOverride",t);i=b.trim()===""?null:b;}let l=this.getNodeParameter("protectionMode",t)==="read_only"?"read_only":null,a=this.getNodeParameter("reasoning",t,""),c=this.getNodeParameter("documentSource",t,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",t,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",t,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:d,fileName:f}=await oe.call(this,t,c),h=await ce.load(d),{reportText:_,outBuffer:p}=await ki(h,{filename:f,sanitize_mode:r,accept_all:s,protection_mode:l,author:i});if(!p)throw new Error(_);let m=Ye(f,"finalized"),y=await this.helpers.prepareBinaryData(p,m,me),x=this.getInputData()[t].binary??{};return [{json:{fileName:m,sanitizeMode:r,report:_,...a!==""?{reasoning:a}:{}},binary:{...x,[n]:y},pairedItem:{item:t}}]}g(qi,"executeFinalizeDocument");var Ji=[{displayName:"Operation",name:"operation",type:"options",noDataExpression:true,displayOptions:{show:{resource:["document"]}},options:[{name:"Apply Edits",value:"applyEdits",action:"Apply tracked changes to document",description:"Apply a JSON array of DocumentChange objects (modify, accept, reject, reply, insert_row, delete_row) as native Word tracked changes and comments. modify edits support match_mode ('strict'|'first'|'all') and regex (boolean) for targeted multi-occurrence writes. The whole batch is pre-validated atomically: if any single edit is invalid, the entire batch is rejected with a per-edit error report and the document is left untouched. Set 'Allow Partial Application' to apply the changes that validate and report the rest in 'stats.failed' with 0-based indices; the output 'status' then reads 'partial'."},{name:"Apply Text Revision",value:"applyTextRevision",action:"Apply a whole revised text as tracked changes",description:"Diff the complete revised clean text of a document against the document's own clean view and apply the difference as native Word tracked changes. Use this when an AI rewrote the whole document instead of producing a list of targeted edits. A post-apply gate re-reads the result and fails the operation if its clean text does not match the text supplied, so a document that cannot realize the revision is never returned."},{name:"Extract Markdown",value:"extractMarkdown",action:"Extract markdown from document",description:"Project the .docx into LLM-friendly Markdown with CriticMarkup ({++ins++}, {--del--}, {>>comment<<}) plus a Semantic Appendix listing defined terms, cross-references, and potential typos. Each tracked change is tagged with a stable ID (Chg:N, Com:N) for use in Apply Edits. Supports an optional Page parameter to fetch only one page of a large document (paired with Extract Outline for navigation)."},{name:"Extract Outline",value:"extractOutline",action:"Extract a structural outline of the document",description:"Return a token-cheap structural map of the .docx: a JSON array of headings with their level (1-6), text, page number (`page`), last page of the range the heading owns (`end_page`), paragraph style, whether the section directly contains a table, and any footnote/endnote IDs scoped to that section. Also returns total_pages. Use this as a navigation primitive for large documents \u2014 call it first to discover structure, then call Extract Markdown with a specific Page to drill into the relevant section."},{name:"Finalize",value:"finalizeDocument",action:"Sanitize metadata and lock the document for distribution",description:"Strip author names, internal IDs, RSIDs, and proof errors; optionally auto-accept all pending tracked changes; optionally lock the document read-only. Use before sending to counterparties or signers."},{name:"Generate Diff",value:"generateDiff",action:"Generate diff between documents",description:"Produce a sub-word level @@ Word Patch @@ diff between two .docx files. Reads the document text via the same Markdown projection used by Extract Markdown, so the diff respects CriticMarkup and Clean View settings."},{name:"Hydrate Tool Output",value:"hydrateToolOutput",action:"Hydrate a redlined binary stashed by Apply Edits as a tool",description:"Read a binary's storage id from workflow static data (where Apply Edits stashes it when run as an AI Agent tool) and re-attach the binary to a main-flow item. Necessary because n8n's AI Agent tool wrapper strips binaries from tool outputs, so the redlined .docx produced by an apply_edits tool call cannot reach downstream nodes directly. Place this node downstream of the AI Agent on the main connection, then route its output into Write Binary File, Gmail (attachment), Slack (file upload), etc."}],default:"extractMarkdown"},{displayName:"Document Source",name:"documentSource",type:"options",default:"fromInput",description:"Where to read the .docx file from. 'From Connected Input' reads the binary on the current input item \u2014 use this in deterministic pipelines (e.g. Gmail Trigger \u2192 Adeu \u2192 Gmail Reply). 'From Another Node' fetches the binary from a named upstream node by name \u2014 use this when the Adeu node is called as an AI Agent tool, since the Agent cannot pass binary data through JSON arguments.",options:[{name:"From Connected Input",value:"fromInput",description:"Read the binary from the current item's binary attachment. Default behavior for deterministic workflows."},{name:"From Another Node",value:"fromNode",description:"Read the binary from a named upstream node. Required when this node is used as an AI Agent tool."}],displayOptions:{show:{resource:["document"],operation:["applyEdits","extractMarkdown","extractOutline","finalizeDocument","applyTextRevision"]}}},{displayName:"Source Node Name",name:"sourceNodeName",type:"string",default:"",required:true,placeholder:"e.g. Gmail Trigger",description:"Exact name of the node in this workflow whose output binary holds the .docx file (string, case-sensitive). Must match the node's label in the canvas exactly, including spaces and punctuation. The referenced node must have already executed in this run and produced binary output on the property named in 'Input Binary Property'.",displayOptions:{show:{resource:["document"],operation:["applyEdits","extractMarkdown","extractOutline","finalizeDocument","applyTextRevision"],documentSource:["fromNode"]}}},{displayName:"Source Binary ID",name:"sourceBinaryId",type:"string",default:"",placeholder:"e.g. filesystem-v2:...",description:"Optional. When set (such as by an AI Agent during a multi-turn conversation), the node will load the document directly from this binary storage ID instead of reading from the source node. Leave empty on the first call to default to the baseline source node.",displayOptions:{show:{resource:["document"],operation:["applyEdits","extractMarkdown","extractOutline","finalizeDocument","applyTextRevision"],documentSource:["fromNode"]}}},...Di,...Ri,...Bi,...Wi,...Li,...Hi,...$i];var Qi=class{static{g(this,"Adeu");}description={displayName:"Adeu",name:"adeu",icon:{light:"file:adeu.svg",dark:"file:adeu-dark.svg"},group:["transform"],version:1,subtitle:'={{$parameter["operation"]}}',description:"Operate on Microsoft Word (.docx) files: extract LLM-friendly Markdown with CriticMarkup, navigate large documents via a structural outline, apply tracked changes and comments, generate sub-word diffs, and sanitize/finalize documents. Seven operations on the Document resource: (1) Extract Markdown \u2014 project a .docx into Markdown plus a Semantic Appendix; toggle Clean View to simulate Accept All; pass an optional Page number to fetch only one page of a large document. (2) Extract Outline \u2014 return a token-cheap structural map (headings with level, page number, paragraph style, has_table, footnote IDs) plus total_pages. Pair with Extract Markdown to navigate large documents. (3) Apply Edits \u2014 apply a JSON array of DocumentChange objects as native Word tracked changes; modify edits support match_mode ('strict'|'first'|'all') and regex (boolean); the entire batch is pre-validated atomically and rejected if any single edit is invalid. (4) Apply Text Revision \u2014 hand back the COMPLETE revised clean text of the document and let the engine diff it against the clean view and write the tracked changes; it refuses CriticMarkup and partial-page text, and fails without returning a document when the applied result's clean text does not match the text supplied. (5) Generate Diff \u2014 produce a @@ Word Patch @@ sub-word level diff between two .docx files. (6) Finalize Document \u2014 strip metadata, optionally accept all pending markup, and optionally lock the file read-only. (7) Hydrate Tool Output \u2014 re-attach a redlined .docx that Apply Edits or Apply Text Revision stashed while running as an AI Agent tool; place it on the main line downstream of the Agent, because n8n's tool wrapper strips binaries from tool output. DocumentChange schema (used by Apply Edits): each object has a 'type' field discriminator. type='modify' requires target_text (string, copied EXACTLY from the source including punctuation, spacing, and case) and new_text (string); optional comment (string); optional match_mode ('strict'|'first'|'all', default 'strict'); optional regex (boolean, default false \u2014 when true, target_text is an ES2022 RegExp pattern and new_text may reference $1, $2 capture groups). type='accept' or type='reject' requires target_id (string like 'Chg:12' from the Markdown projection); optional 'comment'. type='reply' requires target_id (string like 'Com:45') and text (string). type='insert_row' requires target_text (string), position ('above' or 'below'), and cells (array of strings). type='delete_row' requires target_text (string). Never wrap new_text in CriticMarkup tags like {++ ++} or {-- --}; the engine applies tracking automatically. Never target text already wrapped in another author's pending tracked change; accept or reject their change first by target_id. Binary handling for AI Agents: this tool cannot receive .docx files through JSON arguments because JSON cannot carry binary data. To process a document, set 'Document Source' to 'From Another Node' and 'Source Node Name' to the exact name of the workflow node that produced the .docx binary (typically the trigger node, e.g. 'Gmail Trigger', 'When clicking Test workflow', or an HTTP Request node configured to download a file). Node names are case-sensitive and must match the canvas label exactly. For the Generate Diff operation, set both 'Original Source Node Name' and 'Modified Source Node Name' independently.",defaults:{name:"Adeu"},usableAsTool:true,inputs:[n8nWorkflow.NodeConnectionTypes.Main],outputs:[n8nWorkflow.NodeConnectionTypes.Main],credentials:[],properties:[{displayName:"Resource",name:"resource",type:"options",noDataExpression:true,options:[{name:"Document",value:"document"}],default:"document"},...Ji]};async execute(){let e=this.getInputData(),n=[],r=this.getNodeParameter("resource",0),s=this.getNodeParameter("operation",0);for(let i=0;i<e.length;i++)try{let o;if(r==="document")switch(s){case "extractMarkdown":o=await Mi.call(this,i);break;case "extractOutline":o=await ji.call(this,i);break;case "applyEdits":o=await Fi.call(this,i);break;case "applyTextRevision":o=await zi.call(this,i);break;case "generateDiff":o=await Ui.call(this,i);break;case "finalizeDocument":o=await qi.call(this,i);break;case "hydrateToolOutput":o=await Oi.call(this,i);break;default:throw new n8nWorkflow.NodeOperationError(this.getNode(),`Unsupported operation: ${s}`,{itemIndex:i})}else throw new n8nWorkflow.NodeOperationError(this.getNode(),`Unsupported resource: ${r}`,{itemIndex:i});n.push(...o);}catch(o){if(this.continueOnFail()){n.push({json:{error:o.message},pairedItem:{item:i}});continue}let l=o;throw l.name==="NodeOperationError"||l.name==="NodeApiError"?l:Ii.call(this,l,i)}return [n]}};exports.Adeu=Qi;
190
+ `+m),[{json:{originalFileName:c,modifiedFileName:f,cleanView:r,diffFormat:i,diff:m,...h.length>0?{warnings:h}:{}},pairedItem:{item:t}}]}g(is,"executeGenerateDiff");var os=[{displayName:"Reasoning",name:"reasoning",type:"string",default:"",typeOptions:{rows:2},description:"Why the document is being finalized now \u2014 e.g. what state it's in and why it's ready for distribution. State your reasoning BEFORE choosing the sanitize mode and options. This field is captured for auditability and is NOT forwarded into the finalize engine; its only purpose is to make the AI reason first. Safe to leave empty in deterministic (non-AI) pipelines.",displayOptions:{show:{resource:["document"],operation:["finalizeDocument"]}}},{displayName:"Input Binary Property",name:"binaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property holding the .docx file (string, e.g. 'data'). In 'From Connected Input' mode this reads from the current item; in 'From Another Node' mode this specifies which property on the source node's output to read. The file must be a valid .docx.",displayOptions:{show:{resource:["document"],operation:["finalizeDocument"]}}},{displayName:"Output Binary Property",name:"outputBinaryPropertyName",type:"string",default:"data",required:true,placeholder:"e.g. data",description:"Name of the binary property on the outgoing item that will hold the finalized .docx file (string, e.g. 'data'). If equal to the input property name, the original binary is overwritten on the outgoing item.",displayOptions:{show:{resource:["document"],operation:["finalizeDocument"]}}},{displayName:"Sanitize Mode",name:"sanitizeMode",type:"options",default:"full",description:"How aggressively to sanitize the document before distribution. One of: 'baseline' (minimal metadata cleanup only), 'full' (strip metadata AND require all tracked changes resolved or auto-accepted), 'keep-markup' (strip metadata but preserve visible tracked changes and comments, optionally with author rewrite).",options:[{name:"Baseline",value:"baseline",description:"Minimal sanitization: strip RSID attributes, paragraph IDs, and proof errors only. Leaves tracked changes, comments, authors, and other metadata untouched."},{name:"Full",value:"full",description:"Strip metadata (authors, RSIDs, paragraph IDs, proof errors) and require all tracked changes and comments to be resolved. If pending tracked changes exist and 'Accept All Tracked Changes' is false, the operation is blocked and an error is thrown."},{name:"Keep Markup",value:"keep-markup",description:"Strip metadata but preserve all visible tracked changes and comments. Use 'Author Override' to rewrite the author name on every preserved redline and comment (e.g. replace 'AI Reviewer' with your firm name)."}],displayOptions:{show:{resource:["document"],operation:["finalizeDocument"]}}},{displayName:"Accept All Tracked Changes",name:"acceptAll",type:"boolean",default:false,description:"Whether to auto-accept all pending tracked changes before sanitization. Only applies when Sanitize Mode is 'full'. When false (default), the operation throws an error if any pending tracked changes exist, forcing the caller to resolve them first. If multiple distinct authors are detected in pending changes, a warning is included in the report to alert you of potential silent smuggles.",displayOptions:{show:{resource:["document"],operation:["finalizeDocument"],sanitizeMode:["full"]}}},{displayName:"Author Override",name:"authorOverride",type:"string",default:"",placeholder:"e.g. My Firm",description:"Only applies when Sanitize Mode is 'keep-markup'. Optional string. When set, replaces the author name on every preserved tracked change and comment with this value (e.g. 'My Law Firm'). Leave empty to keep original authors intact.",displayOptions:{show:{resource:["document"],operation:["finalizeDocument"],sanitizeMode:["keep-markup"]}}},{displayName:"Protection Mode",name:"protectionMode",type:"options",default:"none",description:"Optionally lock the finalized document. 'none' (default) leaves the document unlocked. 'read_only' injects a native Word read-only enforcement flag into settings.xml \u2014 Word users see a read-only banner and cannot edit without explicitly unlocking. AES encryption is not supported in this engine.",options:[{name:"None",value:"none"},{name:"Read Only",value:"read_only"}],displayOptions:{show:{resource:["document"],operation:["finalizeDocument"]}}}];async function ss(t){let e=this.getNodeParameter("binaryPropertyName",t),n=this.getNodeParameter("outputBinaryPropertyName",t),r=this.getNodeParameter("sanitizeMode",t),i=false;r==="full"&&(i=this.getNodeParameter("acceptAll",t));let o=null;if(r==="keep-markup"){let b=this.getNodeParameter("authorOverride",t);o=b.trim()===""?null:b;}let a=this.getNodeParameter("protectionMode",t)==="read_only"?"read_only":null,l=this.getNodeParameter("reasoning",t,""),c=this.getNodeParameter("documentSource",t,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",t,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",t,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:d,fileName:f}=await se.call(this,t,c),h=await ce.load(d),{reportText:_,outBuffer:p}=await Fo(h,{filename:f,sanitize_mode:r,accept_all:i,protection_mode:a,author:o});if(!p)throw new Error(_);let m=dt(f,"finalized"),w=await this.helpers.prepareBinaryData(p,m,ye),v=this.getInputData()[t].binary??{};return [{json:{fileName:m,sanitizeMode:r,report:_,...l!==""?{reasoning:l}:{}},binary:{...v,[n]:w},pairedItem:{item:t}}]}g(ss,"executeFinalizeDocument");var as=[{displayName:"Operation",name:"operation",type:"options",noDataExpression:true,displayOptions:{show:{resource:["document"]}},options:[{name:"Apply Edits",value:"applyEdits",action:"Apply tracked changes to document",description:"Apply a JSON array of DocumentChange objects (modify, accept, reject, reply, insert_row, delete_row) as native Word tracked changes and comments. modify edits support match_mode ('strict'|'first'|'all') and regex (boolean) for targeted multi-occurrence writes. The whole batch is pre-validated atomically: if any single edit is invalid, the entire batch is rejected with a per-edit error report and the document is left untouched. Set 'Allow Partial Application' to apply the changes that validate and report the rest in 'stats.failed' with 0-based indices; the output 'status' then reads 'partial'."},{name:"Apply Text Revision",value:"applyTextRevision",action:"Apply a whole revised text as tracked changes",description:"Diff the complete revised clean text of a document against the document's own clean view and apply the difference as native Word tracked changes. Use this when an AI rewrote the whole document instead of producing a list of targeted edits. A post-apply gate re-reads the result and fails the operation if its clean text does not match the text supplied, so a document that cannot realize the revision is never returned."},{name:"Extract Markdown",value:"extractMarkdown",action:"Extract markdown from document",description:"Project the .docx into LLM-friendly Markdown with CriticMarkup ({++ins++}, {--del--}, {>>comment<<}) plus a Semantic Appendix listing defined terms, cross-references, and potential typos. Each tracked change is tagged with a stable ID (Chg:N, Com:N) for use in Apply Edits. Supports an optional Page parameter to fetch only one page of a large document (paired with Extract Outline for navigation)."},{name:"Extract Outline",value:"extractOutline",action:"Extract a structural outline of the document",description:"Return a token-cheap structural map of the .docx: a JSON array of headings with their level (1-6), text, page number (`page`), last page of the range the heading owns (`end_page`), paragraph style, whether the section directly contains a table, and any footnote/endnote IDs scoped to that section. Also returns total_pages. Use this as a navigation primitive for large documents \u2014 call it first to discover structure, then call Extract Markdown with a specific Page to drill into the relevant section."},{name:"Finalize",value:"finalizeDocument",action:"Sanitize metadata and lock the document for distribution",description:"Strip author names, internal IDs, RSIDs, and proof errors; optionally auto-accept all pending tracked changes; optionally lock the document read-only. Use before sending to counterparties or signers."},{name:"Generate Diff",value:"generateDiff",action:"Generate diff between documents",description:"Produce a sub-word level @@ Word Patch @@ diff between two .docx files. Reads the document text via the same Markdown projection used by Extract Markdown, so the diff respects CriticMarkup and Clean View settings."},{name:"Hydrate Tool Output",value:"hydrateToolOutput",action:"Hydrate a redlined binary stashed by Apply Edits as a tool",description:"Read a binary's storage id from workflow static data (where Apply Edits stashes it when run as an AI Agent tool) and re-attach the binary to a main-flow item. Necessary because n8n's AI Agent tool wrapper strips binaries from tool outputs, so the redlined .docx produced by an apply_edits tool call cannot reach downstream nodes directly. Place this node downstream of the AI Agent on the main connection, then route its output into Write Binary File, Gmail (attachment), Slack (file upload), etc."}],default:"extractMarkdown"},{displayName:"Document Source",name:"documentSource",type:"options",default:"fromInput",description:"Where to read the .docx file from. 'From Connected Input' reads the binary on the current input item \u2014 use this in deterministic pipelines (e.g. Gmail Trigger \u2192 Adeu \u2192 Gmail Reply). 'From Another Node' fetches the binary from a named upstream node by name \u2014 use this when the Adeu node is called as an AI Agent tool, since the Agent cannot pass binary data through JSON arguments.",options:[{name:"From Connected Input",value:"fromInput",description:"Read the binary from the current item's binary attachment. Default behavior for deterministic workflows."},{name:"From Another Node",value:"fromNode",description:"Read the binary from a named upstream node. Required when this node is used as an AI Agent tool."}],displayOptions:{show:{resource:["document"],operation:["applyEdits","extractMarkdown","extractOutline","finalizeDocument","applyTextRevision"]}}},{displayName:"Source Node Name",name:"sourceNodeName",type:"string",default:"",required:true,placeholder:"e.g. Gmail Trigger",description:"Exact name of the node in this workflow whose output binary holds the .docx file (string, case-sensitive). Must match the node's label in the canvas exactly, including spaces and punctuation. The referenced node must have already executed in this run and produced binary output on the property named in 'Input Binary Property'.",displayOptions:{show:{resource:["document"],operation:["applyEdits","extractMarkdown","extractOutline","finalizeDocument","applyTextRevision"],documentSource:["fromNode"]}}},{displayName:"Source Binary ID",name:"sourceBinaryId",type:"string",default:"",placeholder:"e.g. filesystem-v2:...",description:"Optional. When set (such as by an AI Agent during a multi-turn conversation), the node will load the document directly from this binary storage ID instead of reading from the source node. Leave empty on the first call to default to the baseline source node.",displayOptions:{show:{resource:["document"],operation:["applyEdits","extractMarkdown","extractOutline","finalizeDocument","applyTextRevision"],documentSource:["fromNode"]}}},...Yo,...Vo,...Ko,...ts,...rs,...os,...Go];var us=class{static{g(this,"Adeu");}description={displayName:"Adeu",name:"adeu",icon:{light:"file:adeu.svg",dark:"file:adeu-dark.svg"},group:["transform"],version:1,subtitle:'={{$parameter["operation"]}}',description:"Operate on Microsoft Word (.docx) files: extract LLM-friendly Markdown with CriticMarkup, navigate large documents via a structural outline, apply tracked changes and comments, generate sub-word diffs, and sanitize/finalize documents. Seven operations on the Document resource: (1) Extract Markdown \u2014 project a .docx into Markdown plus a Semantic Appendix; toggle Clean View to simulate Accept All; pass an optional Page number to fetch only one page of a large document. (2) Extract Outline \u2014 return a token-cheap structural map (headings with level, page number, paragraph style, has_table, footnote IDs) plus total_pages. Pair with Extract Markdown to navigate large documents. (3) Apply Edits \u2014 apply a JSON array of DocumentChange objects as native Word tracked changes; modify edits support match_mode ('strict'|'first'|'all') and regex (boolean); the entire batch is pre-validated atomically and rejected if any single edit is invalid. (4) Apply Text Revision \u2014 hand back the COMPLETE revised clean text of the document and let the engine diff it against the clean view and write the tracked changes; it refuses CriticMarkup and partial-page text, and fails without returning a document when the applied result's clean text does not match the text supplied. (5) Generate Diff \u2014 produce a @@ Word Patch @@ sub-word level diff between two .docx files. (6) Finalize Document \u2014 strip metadata, optionally accept all pending markup, and optionally lock the file read-only. (7) Hydrate Tool Output \u2014 re-attach a redlined .docx that Apply Edits or Apply Text Revision stashed while running as an AI Agent tool; place it on the main line downstream of the Agent, because n8n's tool wrapper strips binaries from tool output. DocumentChange schema (used by Apply Edits): each object has a 'type' field discriminator. type='modify' requires target_text (string, copied EXACTLY from the source including punctuation, spacing, and case) and new_text (string); optional comment (string); optional match_mode ('strict'|'first'|'all', default 'strict'); optional regex (boolean, default false \u2014 when true, target_text is an ES2022 RegExp pattern and new_text may reference $1, $2 capture groups). type='accept' or type='reject' requires target_id (string like 'Chg:12' from the Markdown projection); optional 'comment'. type='reply' requires target_id (string like 'Com:45') and text (string). type='insert_row' requires target_text (string), position ('above' or 'below'), and cells (array of strings). type='delete_row' requires target_text (string). Never wrap new_text in CriticMarkup tags like {++ ++} or {-- --}; the engine applies tracking automatically. Never target text already wrapped in another author's pending tracked change; accept or reject their change first by target_id. Binary handling for AI Agents: this tool cannot receive .docx files through JSON arguments because JSON cannot carry binary data. To process a document, set 'Document Source' to 'From Another Node' and 'Source Node Name' to the exact name of the workflow node that produced the .docx binary (typically the trigger node, e.g. 'Gmail Trigger', 'When clicking Test workflow', or an HTTP Request node configured to download a file). Node names are case-sensitive and must match the canvas label exactly. For the Generate Diff operation, set both 'Original Source Node Name' and 'Modified Source Node Name' independently.",defaults:{name:"Adeu"},usableAsTool:true,inputs:[n8nWorkflow.NodeConnectionTypes.Main],outputs:[n8nWorkflow.NodeConnectionTypes.Main],credentials:[],properties:[{displayName:"Resource",name:"resource",type:"options",noDataExpression:true,options:[{name:"Document",value:"document"}],default:"document"},...as]};async execute(){let e=this.getInputData(),n=[],r=this.getNodeParameter("resource",0),i=this.getNodeParameter("operation",0);for(let o=0;o<e.length;o++)try{let s;if(r==="document")switch(i){case "extractMarkdown":s=await Qo.call(this,o);break;case "extractOutline":s=await Zo.call(this,o);break;case "applyEdits":s=await es.call(this,o);break;case "applyTextRevision":s=await ns.call(this,o);break;case "generateDiff":s=await is.call(this,o);break;case "finalizeDocument":s=await ss.call(this,o);break;case "hydrateToolOutput":s=await Jo.call(this,o);break;default:throw new n8nWorkflow.NodeOperationError(this.getNode(),`Unsupported operation: ${i}`,{itemIndex:o})}else throw new n8nWorkflow.NodeOperationError(this.getNode(),`Unsupported resource: ${r}`,{itemIndex:o});n.push(...s);}catch(s){if(this.continueOnFail()){n.push({json:{error:s.message},pairedItem:{item:o}});continue}let a=s;throw a.name==="NodeOperationError"||a.name==="NodeApiError"?a:Xo.call(this,a,o)}return [n]}};exports.Adeu=us;