n8n-nodes-adeu 3.1.0 → 3.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -10
- package/dist/nodes/Adeu/Adeu.node.js +118 -105
- package/dist/nodes/Adeu/metafile-cjs.json +1 -1
- package/package.json +2 -2
|
@@ -1,46 +1,47 @@
|
|
|
1
|
-
'use strict';var n8nWorkflow=require('n8n-workflow'),path=require('path');var
|
|
2
|
-
`,l),d==-1&&(d=c.length-1);var h=c.substring(l,d+1);(r.hasOwnProperty?r.hasOwnProperty(h):r[h]!==void 0)?u+=String.fromCharCode(r[h]):(f==s&&(h=c.substring(l),d=c.length),u+=String.fromCharCode(f),r[h]=f,t[f++]=h),l=d+1;}return u}g(i,"diff_linesToCharsMunge_");var s=4e4,o=i(n);s=65535;var a=i(e);return {chars1:o,chars2:a,lineArray:t}};B.prototype.diff_charsToLines_=function(n,e){for(var t=0;t<n.length;t++){for(var r=n[t][1],i=[],s=0;s<r.length;s++)i[s]=e[r.charCodeAt(s)];n[t][1]=i.join("");}};B.prototype.diff_commonPrefix=function(n,e){if(!n||!e||n.charAt(0)!=e.charAt(0))return 0;for(var t=0,r=Math.min(n.length,e.length),i=r,s=0;t<i;)n.substring(s,i)==e.substring(s,i)?(t=i,s=t):r=i,i=Math.floor((r-t)/2+t);return i};B.prototype.diff_commonSuffix=function(n,e){if(!n||!e||n.charAt(n.length-1)!=e.charAt(e.length-1))return 0;for(var t=0,r=Math.min(n.length,e.length),i=r,s=0;t<i;)n.substring(n.length-i,n.length-s)==e.substring(e.length-i,e.length-s)?(t=i,s=t):r=i,i=Math.floor((r-t)/2+t);return i};B.prototype.diff_commonOverlap_=function(n,e){var t=n.length,r=e.length;if(t==0||r==0)return 0;t>r?n=n.substring(t-r):t<r&&(e=e.substring(0,t));var i=Math.min(t,r);if(n==e)return i;for(var s=0,o=1;;){var a=n.substring(i-o),c=e.indexOf(a);if(c==-1)return s;o+=c,(c==0||n.substring(i-o)==e.substring(0,o))&&(s=o,o++);}};B.prototype.diff_halfMatch_=function(n,e){if(this.Diff_Timeout<=0)return null;var t=n.length>e.length?n:e,r=n.length>e.length?e:n;if(t.length<4||r.length*2<t.length)return null;var i=this;function s(_,p,m){for(var w=_.substring(m,m+Math.floor(_.length/4)),y=-1,b="",v,N,k,x;(y=p.indexOf(w,y+1))!=-1;){var C=i.diff_commonPrefix(_.substring(m),p.substring(y)),E=i.diff_commonSuffix(_.substring(0,m),p.substring(0,y));b.length<E+C&&(b=p.substring(y-E,y)+p.substring(y,y+C),v=_.substring(0,m-E),N=_.substring(m+C),k=p.substring(0,y-E),x=p.substring(y+C));}return b.length*2>=_.length?[v,N,k,x,b]:null}g(s,"diff_halfMatchI_");var o=s(t,r,Math.ceil(t.length/4)),a=s(t,r,Math.ceil(t.length/2)),c;if(!o&&!a)return null;a?o?c=o[4].length>a[4].length?o:a:c=a:c=o;var u,l,d,f;n.length>e.length?(u=c[0],l=c[1],d=c[2],f=c[3]):(d=c[0],f=c[1],u=c[2],l=c[3]);var h=c[4];return [u,l,d,f,h]};B.prototype.diff_cleanupSemantic=function(n){for(var e=false,t=[],r=0,i=null,s=0,o=0,a=0,c=0,u=0;s<n.length;)n[s][0]==q?(t[r++]=s,o=c,a=u,c=0,u=0,i=n[s][1]):(n[s][0]==Q?c+=n[s][1].length:u+=n[s][1].length,i&&i.length<=Math.max(o,a)&&i.length<=Math.max(c,u)&&(n.splice(t[r-1],0,new B.Diff(J,i)),n[t[r-1]+1][0]=Q,r--,r--,s=r>0?t[r-1]:-1,o=0,a=0,c=0,u=0,i=null,e=true)),s++;for(e&&this.diff_cleanupMerge(n),this.diff_cleanupSemanticLossless(n),s=1;s<n.length;){if(n[s-1][0]==J&&n[s][0]==Q){var l=n[s-1][1],d=n[s][1],f=this.diff_commonOverlap_(l,d),h=this.diff_commonOverlap_(d,l);f>=h?(f>=l.length/2||f>=d.length/2)&&(n.splice(s,0,new B.Diff(q,d.substring(0,f))),n[s-1][1]=l.substring(0,l.length-f),n[s+1][1]=d.substring(f),s++):(h>=l.length/2||h>=d.length/2)&&(n.splice(s,0,new B.Diff(q,l.substring(0,h))),n[s-1][0]=Q,n[s-1][1]=d.substring(0,d.length-h),n[s+1][0]=J,n[s+1][1]=l.substring(h),s++),s++;}s++;}};B.prototype.diff_cleanupSemanticLossless=function(n){function e(h,_){if(!h||!_)return 6;var p=h.charAt(h.length-1),m=_.charAt(0),w=p.match(B.nonAlphaNumericRegex_),y=m.match(B.nonAlphaNumericRegex_),b=w&&p.match(B.whitespaceRegex_),v=y&&m.match(B.whitespaceRegex_),N=b&&p.match(B.linebreakRegex_),k=v&&m.match(B.linebreakRegex_),x=N&&h.match(B.blanklineEndRegex_),C=k&&_.match(B.blanklineStartRegex_);return x||C?5:N||k?4:w&&!b&&v?3:b||v?2:w||y?1:0}g(e,"diff_cleanupSemanticScore_");for(var t=1;t<n.length-1;){if(n[t-1][0]==q&&n[t+1][0]==q){var r=n[t-1][1],i=n[t][1],s=n[t+1][1],o=this.diff_commonSuffix(r,i);if(o){var a=i.substring(i.length-o);r=r.substring(0,r.length-o),i=a+i.substring(0,i.length-o),s=a+s;}for(var c=r,u=i,l=s,d=e(r,i)+e(i,s);i.charAt(0)===s.charAt(0);){r+=i.charAt(0),i=i.substring(1)+s.charAt(0),s=s.substring(1);var f=e(r,i)+e(i,s);f>=d&&(d=f,c=r,u=i,l=s);}n[t-1][1]!=c&&(c?n[t-1][1]=c:(n.splice(t-1,1),t--),n[t][1]=u,l?n[t+1][1]=l:(n.splice(t+1,1),t--));}t++;}};B.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;B.whitespaceRegex_=/\s/;B.linebreakRegex_=/[\r\n]/;B.blanklineEndRegex_=/\n\r?\n$/;B.blanklineStartRegex_=/^\r?\n\r?\n/;B.prototype.diff_cleanupEfficiency=function(n){for(var e=false,t=[],r=0,i=null,s=0,o=false,a=false,c=false,u=false;s<n.length;)n[s][0]==q?(n[s][1].length<this.Diff_EditCost&&(c||u)?(t[r++]=s,o=c,a=u,i=n[s][1]):(r=0,i=null),c=u=false):(n[s][0]==J?u=true:c=true,i&&(o&&a&&c&&u||i.length<this.Diff_EditCost/2&&o+a+c+u==3)&&(n.splice(t[r-1],0,new B.Diff(J,i)),n[t[r-1]+1][0]=Q,r--,i=null,o&&a?(c=u=true,r=0):(r--,s=r>0?t[r-1]:-1,c=u=false),e=true)),s++;e&&this.diff_cleanupMerge(n);};B.prototype.diff_cleanupMerge=function(n){n.push(new B.Diff(q,""));for(var e=0,t=0,r=0,i="",s="",o;e<n.length;)switch(n[e][0]){case Q:r++,s+=n[e][1],e++;break;case J:t++,i+=n[e][1],e++;break;case q:t+r>1?(t!==0&&r!==0&&(o=this.diff_commonPrefix(s,i),o!==0&&(e-t-r>0&&n[e-t-r-1][0]==q?n[e-t-r-1][1]+=s.substring(0,o):(n.splice(0,0,new B.Diff(q,s.substring(0,o))),e++),s=s.substring(o),i=i.substring(o)),o=this.diff_commonSuffix(s,i),o!==0&&(n[e][1]=s.substring(s.length-o)+n[e][1],s=s.substring(0,s.length-o),i=i.substring(0,i.length-o))),e-=t+r,n.splice(e,t+r),i.length&&(n.splice(e,0,new B.Diff(J,i)),e++),s.length&&(n.splice(e,0,new B.Diff(Q,s)),e++),e++):e!==0&&n[e-1][0]==q?(n[e-1][1]+=n[e][1],n.splice(e,1)):e++,r=0,t=0,i="",s="";break}n[n.length-1][1]===""&&n.pop();var a=false;for(e=1;e<n.length-1;)n[e-1][0]==q&&n[e+1][0]==q&&(n[e][1].substring(n[e][1].length-n[e-1][1].length)==n[e-1][1]?(n[e][1]=n[e-1][1]+n[e][1].substring(0,n[e][1].length-n[e-1][1].length),n[e+1][1]=n[e-1][1]+n[e+1][1],n.splice(e-1,1),a=true):n[e][1].substring(0,n[e+1][1].length)==n[e+1][1]&&(n[e-1][1]+=n[e+1][1],n[e][1]=n[e][1].substring(n[e+1][1].length)+n[e+1][1],n.splice(e+1,1),a=true)),e++;a&&this.diff_cleanupMerge(n);};B.prototype.diff_xIndex=function(n,e){var t=0,r=0,i=0,s=0,o;for(o=0;o<n.length&&(n[o][0]!==Q&&(t+=n[o][1].length),n[o][0]!==J&&(r+=n[o][1].length),!(t>e));o++)i=t,s=r;return n.length!=o&&n[o][0]===J?s:s+(e-i)};B.prototype.diff_prettyHtml=function(n){for(var e=[],t=/&/g,r=/</g,i=/>/g,s=/\n/g,o=0;o<n.length;o++){var a=n[o][0],c=n[o][1],u=c.replace(t,"&").replace(r,"<").replace(i,">").replace(s,"¶<br>");switch(a){case Q:e[o]='<ins style="background:#e6ffe6;">'+u+"</ins>";break;case J:e[o]='<del style="background:#ffe6e6;">'+u+"</del>";break;case q:e[o]="<span>"+u+"</span>";break}}return e.join("")};B.prototype.diff_text1=function(n){for(var e=[],t=0;t<n.length;t++)n[t][0]!==Q&&(e[t]=n[t][1]);return e.join("")};B.prototype.diff_text2=function(n){for(var e=[],t=0;t<n.length;t++)n[t][0]!==J&&(e[t]=n[t][1]);return e.join("")};B.prototype.diff_levenshtein=function(n){for(var e=0,t=0,r=0,i=0;i<n.length;i++){var s=n[i][0],o=n[i][1];switch(s){case Q:t+=o.length;break;case J:r+=o.length;break;case q:e+=Math.max(t,r),t=0,r=0;break}}return e+=Math.max(t,r),e};B.prototype.diff_toDelta=function(n){for(var e=[],t=0;t<n.length;t++)switch(n[t][0]){case Q:e[t]="+"+encodeURI(n[t][1]);break;case J:e[t]="-"+n[t][1].length;break;case q:e[t]="="+n[t][1].length;break}return e.join(" ").replace(/%20/g," ")};B.prototype.diff_fromDelta=function(n,e){for(var t=[],r=0,i=0,s=e.split(/\t/g),o=0;o<s.length;o++){var a=s[o].substring(1);switch(s[o].charAt(0)){case "+":try{t[r++]=new B.Diff(Q,decodeURI(a));}catch{throw new Error("Illegal escape in diff_fromDelta: "+a)}break;case "-":case "=":var c=parseInt(a,10);if(isNaN(c)||c<0)throw new Error("Invalid number in diff_fromDelta: "+a);var u=n.substring(i,i+=c);s[o].charAt(0)=="="?t[r++]=new B.Diff(q,u):t[r++]=new B.Diff(J,u);break;default:if(s[o])throw new Error("Invalid diff operation in diff_fromDelta: "+s[o])}}if(i!=n.length)throw new Error("Delta length ("+i+") does not equal source text length ("+n.length+").");return t};B.prototype.match_main=function(n,e,t){if(n==null||e==null||t==null)throw new Error("Null input. (match_main)");return t=Math.max(0,Math.min(t,n.length)),n==e?0:n.length?n.substring(t,t+e.length)==e?t:this.match_bitap_(n,e,t):-1};B.prototype.match_bitap_=function(n,e,t){if(e.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");var r=this.match_alphabet_(e),i=this;function s(v,N){var k=v/e.length,x=Math.abs(t-N);return i.Match_Distance?k+x/i.Match_Distance:x?1:k}g(s,"match_bitapScore_");var o=this.Match_Threshold,a=n.indexOf(e,t);a!=-1&&(o=Math.min(s(0,a),o),a=n.lastIndexOf(e,t+e.length),a!=-1&&(o=Math.min(s(0,a),o)));var c=1<<e.length-1;a=-1;for(var u,l,d=e.length+n.length,f,h=0;h<e.length;h++){for(u=0,l=d;u<l;)s(h,t+l)<=o?u=l:d=l,l=Math.floor((d-u)/2+u);d=l;var _=Math.max(1,t-l+1),p=Math.min(t+l,n.length)+e.length,m=Array(p+2);m[p+1]=(1<<h)-1;for(var w=p;w>=_;w--){var y=r[n.charAt(w-1)];if(h===0?m[w]=(m[w+1]<<1|1)&y:m[w]=(m[w+1]<<1|1)&y|((f[w+1]|f[w])<<1|1)|f[w+1],m[w]&c){var b=s(h,w-1);if(b<=o)if(o=b,a=w-1,a>t)_=Math.max(1,2*t-a);else break}}if(s(h+1,t)>o)break;f=m;}return a};B.prototype.match_alphabet_=function(n){for(var e={},t=0;t<n.length;t++)e[n.charAt(t)]=0;for(var t=0;t<n.length;t++)e[n.charAt(t)]|=1<<n.length-t-1;return e};B.prototype.patch_addContext_=function(n,e){if(e.length!=0){if(n.start2===null)throw Error("patch not initialized");for(var t=e.substring(n.start2,n.start2+n.length1),r=0;e.indexOf(t)!=e.lastIndexOf(t)&&t.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)r+=this.Patch_Margin,t=e.substring(n.start2-r,n.start2+n.length1+r);r+=this.Patch_Margin;var i=e.substring(n.start2-r,n.start2);i&&n.diffs.unshift(new B.Diff(q,i));var s=e.substring(n.start2+n.length1,n.start2+n.length1+r);s&&n.diffs.push(new B.Diff(q,s)),n.start1-=i.length,n.start2-=i.length,n.length1+=i.length+s.length,n.length2+=i.length+s.length;}};B.prototype.patch_make=function(n,e,t){var r,i;if(typeof n=="string"&&typeof e=="string"&&typeof t>"u")r=n,i=this.diff_main(r,e,true),i.length>2&&(this.diff_cleanupSemantic(i),this.diff_cleanupEfficiency(i));else if(n&&typeof n=="object"&&typeof e>"u"&&typeof t>"u")i=n,r=this.diff_text1(i);else if(typeof n=="string"&&e&&typeof e=="object"&&typeof t>"u")r=n,i=e;else if(typeof n=="string"&&typeof e=="string"&&t&&typeof t=="object")r=n,i=t;else throw new Error("Unknown call format to patch_make.");if(i.length===0)return [];for(var s=[],o=new B.patch_obj,a=0,c=0,u=0,l=r,d=r,f=0;f<i.length;f++){var h=i[f][0],_=i[f][1];switch(!a&&h!==q&&(o.start1=c,o.start2=u),h){case Q:o.diffs[a++]=i[f],o.length2+=_.length,d=d.substring(0,u)+_+d.substring(u);break;case J:o.length1+=_.length,o.diffs[a++]=i[f],d=d.substring(0,u)+d.substring(u+_.length);break;case q:_.length<=2*this.Patch_Margin&&a&&i.length!=f+1?(o.diffs[a++]=i[f],o.length1+=_.length,o.length2+=_.length):_.length>=2*this.Patch_Margin&&a&&(this.patch_addContext_(o,l),s.push(o),o=new B.patch_obj,a=0,l=d,c=u);break}h!==Q&&(c+=_.length),h!==J&&(u+=_.length);}return a&&(this.patch_addContext_(o,l),s.push(o)),s};B.prototype.patch_deepCopy=function(n){for(var e=[],t=0;t<n.length;t++){var r=n[t],i=new B.patch_obj;i.diffs=[];for(var s=0;s<r.diffs.length;s++)i.diffs[s]=new B.Diff(r.diffs[s][0],r.diffs[s][1]);i.start1=r.start1,i.start2=r.start2,i.length1=r.length1,i.length2=r.length2,e[t]=i;}return e};B.prototype.patch_apply=function(n,e){if(n.length==0)return [e,[]];n=this.patch_deepCopy(n);var t=this.patch_addPadding(n);e=t+e+t,this.patch_splitMax(n);for(var r=0,i=[],s=0;s<n.length;s++){var o=n[s].start2+r,a=this.diff_text1(n[s].diffs),c,u=-1;if(a.length>this.Match_MaxBits?(c=this.match_main(e,a.substring(0,this.Match_MaxBits),o),c!=-1&&(u=this.match_main(e,a.substring(a.length-this.Match_MaxBits),o+a.length-this.Match_MaxBits),(u==-1||c>=u)&&(c=-1))):c=this.match_main(e,a,o),c==-1)i[s]=false,r-=n[s].length2-n[s].length1;else {i[s]=true,r=c-o;var l;if(u==-1?l=e.substring(c,c+a.length):l=e.substring(c,u+this.Match_MaxBits),a==l)e=e.substring(0,c)+this.diff_text2(n[s].diffs)+e.substring(c+a.length);else {var d=this.diff_main(a,l,false);if(a.length>this.Match_MaxBits&&this.diff_levenshtein(d)/a.length>this.Patch_DeleteThreshold)i[s]=false;else {this.diff_cleanupSemanticLossless(d);for(var f=0,h,_=0;_<n[s].diffs.length;_++){var p=n[s].diffs[_];p[0]!==q&&(h=this.diff_xIndex(d,f)),p[0]===Q?e=e.substring(0,c+h)+p[1]+e.substring(c+h):p[0]===J&&(e=e.substring(0,c+h)+e.substring(c+this.diff_xIndex(d,f+p[1].length))),p[0]!==J&&(f+=p[1].length);}}}}}return e=e.substring(t.length,e.length-t.length),[e,i]};B.prototype.patch_addPadding=function(n){for(var e=this.Patch_Margin,t="",r=1;r<=e;r++)t+=String.fromCharCode(r);for(var r=0;r<n.length;r++)n[r].start1+=e,n[r].start2+=e;var i=n[0],s=i.diffs;if(s.length==0||s[0][0]!=q)s.unshift(new B.Diff(q,t)),i.start1-=e,i.start2-=e,i.length1+=e,i.length2+=e;else if(e>s[0][1].length){var o=e-s[0][1].length;s[0][1]=t.substring(s[0][1].length)+s[0][1],i.start1-=o,i.start2-=o,i.length1+=o,i.length2+=o;}if(i=n[n.length-1],s=i.diffs,s.length==0||s[s.length-1][0]!=q)s.push(new B.Diff(q,t)),i.length1+=e,i.length2+=e;else if(e>s[s.length-1][1].length){var o=e-s[s.length-1][1].length;s[s.length-1][1]+=t.substring(0,o),i.length1+=o,i.length2+=o;}return t};B.prototype.patch_splitMax=function(n){for(var e=this.Match_MaxBits,t=0;t<n.length;t++)if(!(n[t].length1<=e)){var r=n[t];n.splice(t--,1);for(var i=r.start1,s=r.start2,o="";r.diffs.length!==0;){var a=new B.patch_obj,c=true;for(a.start1=i-o.length,a.start2=s-o.length,o!==""&&(a.length1=a.length2=o.length,a.diffs.push(new B.Diff(q,o)));r.diffs.length!==0&&a.length1<e-this.Patch_Margin;){var u=r.diffs[0][0],l=r.diffs[0][1];u===Q?(a.length2+=l.length,s+=l.length,a.diffs.push(r.diffs.shift()),c=false):u===J&&a.diffs.length==1&&a.diffs[0][0]==q&&l.length>2*e?(a.length1+=l.length,i+=l.length,c=false,a.diffs.push(new B.Diff(u,l)),r.diffs.shift()):(l=l.substring(0,e-a.length1-this.Patch_Margin),a.length1+=l.length,i+=l.length,u===q?(a.length2+=l.length,s+=l.length):c=false,a.diffs.push(new B.Diff(u,l)),l==r.diffs[0][1]?r.diffs.shift():r.diffs[0][1]=r.diffs[0][1].substring(l.length));}o=this.diff_text2(a.diffs),o=o.substring(o.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]===q?a.diffs[a.diffs.length-1][1]+=d:a.diffs.push(new B.Diff(q,d))),c||n.splice(++t,0,a);}}};B.prototype.patch_toText=function(n){for(var e=[],t=0;t<n.length;t++)e[t]=n[t];return e.join("")};B.prototype.patch_fromText=function(n){var e=[];if(!n)return e;for(var t=n.split(`
|
|
3
|
-
`),r=0,i=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;r<t.length;){var s=t[r].match(i);if(!s)throw new Error("Invalid patch string: "+t[r]);var o=new
|
|
4
|
-
`],r,i=0;i<this.diffs.length;i++){switch(this.diffs[i][0]){case
|
|
5
|
-
`;}return t.join("").replace(/%20/g," ")};st.exports=B;st.exports.diff_match_patch=B;st.exports.DIFF_DELETE=J;st.exports.DIFF_INSERT=Q;st.exports.DIFF_EQUAL=q;});var Sr=Mt(Er());var Io=(0, Sr.createRequire)("/"),rt,Oo,Do;try{rt=Io("worker_threads"),Oo=rt.Worker,Do=rt.isMarkedAsUntransferable;}catch{}var K=Uint8Array,ae=Uint16Array,Dn=Int32Array,Bt=new K([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]),Ft=new K([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]),Pn=new K([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ir=g(function(n,e){for(var t=new ae(31),r=0;r<31;++r)t[r]=e+=1<<n[r-1];for(var i=new Dn(t[30]),r=1;r<30;++r)for(var s=t[r];s<t[r+1];++s)i[s]=s-t[r]<<5|r;return {b:t,r:i}},"freb"),rt=Ir(Bt,2),Or=rt.b,Tn=rt.r;Or[28]=258,Tn[258]=28;var Dr=Ir(Ft,0),Ro=Dr.b,Ar=Dr.r,$n=new ae(32768);for(Y=0;Y<32768;++Y)Ee=(Y&43690)>>1|(Y&21845)<<1,Ee=(Ee&52428)>>2|(Ee&13107)<<2,Ee=(Ee&61680)>>4|(Ee&3855)<<4,$n[Y]=((Ee&65280)>>8|(Ee&255)<<8)>>1;var Ee,Y,ve=g((function(n,e,t){for(var r=n.length,i=0,s=new ae(e);i<r;++i)n[i]&&++s[n[i]-1];var o=new ae(e);for(i=1;i<e;++i)o[i]=o[i-1]+s[i-1]<<1;var a;if(t){a=new ae(1<<e);var c=15-e;for(i=0;i<r;++i)if(n[i])for(var u=i<<4|n[i],l=e-n[i],d=o[n[i]-1]++<<l,f=d|(1<<l)-1;d<=f;++d)a[$n[d]>>c]=u;}else for(a=new ae(r),i=0;i<r;++i)n[i]&&(a[i]=$n[o[n[i]-1]++]>>15-n[i]);return a}),"hMap"),Ie=new K(288);for(Y=0;Y<144;++Y)Ie[Y]=8;var Y;for(Y=144;Y<256;++Y)Ie[Y]=9;var Y;for(Y=256;Y<280;++Y)Ie[Y]=7;var Y;for(Y=280;Y<288;++Y)Ie[Y]=8;var Y,bt=new K(32);for(Y=0;Y<32;++Y)bt[Y]=5;var Y,Mo=ve(Ie,9,0),jo=ve(Ie,9,1),Bo=ve(bt,5,0),Fo=ve(bt,5,1),kn=g(function(n){for(var e=n[0],t=1;t<n.length;++t)n[t]>e&&(e=n[t]);return e},"max"),he=g(function(n,e,t){var r=e/8|0;return (n[r]|n[r+1]<<8)>>(e&7)&t},"bits"),En=g(function(n,e){var t=e/8|0;return (n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},"bits16"),Rn=g(function(n){return (n+7)/8|0},"shft"),xt=g(function(n,e,t){return (e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length),new K(n.subarray(e,t))},"slc");var Wo=["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(n,e,t){var r=new Error(e||Wo[n]);if(r.code=n,Error.captureStackTrace&&Error.captureStackTrace(r,re),!t)throw r;return r},"err"),Lo=g(function(n,e,t,r){var i=n.length,s=r?r.length:0;if(!i||e.f&&!e.l)return t||new K(0);var o=!t,a=o||e.i!=2,c=e.i;o&&(t=new K(i*3));var u=g(function(tt){var fe=t.length;if(tt>fe){var we=new K(Math.max(fe*2,tt));we.set(t),t=we;}},"cbuf"),l=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){l=he(n,d,1);var y=he(n,d+1,3);if(d+=3,y)if(y==1)h=jo,_=Fo,p=9,m=5;else if(y==2){var k=he(n,d,31)+257,x=he(n,d+10,15)+4,C=k+he(n,d+5,31)+1;d+=14;for(var E=new K(C),P=new K(19),I=0;I<x;++I)P[Pn[I]]=he(n,d+I*3,7);d+=x*3;for(var M=kn(P),j=(1<<M)-1,F=ve(P,M,1),I=0;I<C;){var T=F[he(n,d,j)];d+=T&15;var b=T>>4;if(b<16)E[I++]=b;else {var O=0,D=0;for(b==16?(D=3+he(n,d,3),d+=2,O=E[I-1]):b==17?(D=3+he(n,d,7),d+=3):b==18&&(D=11+he(n,d,127),d+=7);D--;)E[I++]=O;}}var A=E.subarray(0,k),$=E.subarray(k);p=kn(A),m=kn($),h=ve(A,p,1),_=ve($,m,1);}else re(1);else {var b=Rn(d)+4,v=n[b-4]|n[b-3]<<8,N=b+v;if(N>i){c&&re(0);break}a&&u(f+v),t.set(n.subarray(b,N),f),e.b=f+=v,e.p=d=N*8,e.f=l;continue}if(d>w){c&&re(0);break}}a&&u(f+131072);for(var W=(1<<p)-1,z=(1<<m)-1,H=d;;H=d){var O=h[En(n,d)&W],L=O>>4;if(d+=O&15,d>w){c&&re(0);break}if(O||re(2),L<256)t[f++]=L;else if(L==256){H=d,h=null;break}else {var X=L-254;if(L>264){var I=L-257,U=Bt[I];X=he(n,d,(1<<U)-1)+Or[I],d+=U;}var G=_[En(n,d)&z],se=G>>4;G||re(3),d+=G&15;var $=Ro[se];if(se>3){var U=Ft[se];$+=En(n,d)&(1<<U)-1,d+=U;}if(d>w){c&&re(0);break}a&&u(f+131072);var oe=f+X;if(f<$){var et=s-$,He=Math.min($,oe);for(et+f<0&&re(3);f<He;++f)t[f]=r[et+f];}for(;f<oe;++f)t[f]=t[f-$];}}e.l=h,e.p=H,e.b=f,e.f=l,h&&(l=1,e.m=p,e.d=_,e.n=m);}while(!l);return f!=t.length&&o?xt(t,0,f):t.subarray(0,f)},"inflt"),Ae=g(function(n,e,t){t<<=e&7;var r=e/8|0;n[r]|=t,n[r+1]|=t>>8;},"wbits"),yt=g(function(n,e,t){t<<=e&7;var r=e/8|0;n[r]|=t,n[r+1]|=t>>8,n[r+2]|=t>>16;},"wbits16"),An=g(function(n,e){for(var t=[],r=0;r<n.length;++r)n[r]&&t.push({s:r,f:n[r]});var i=t.length,s=t.slice();if(!i)return {t:Mr,l:0};if(i==1){var o=new K(t[0].s+1);return o[t[0].s]=1,{t:o,l:1}}t.sort(function(N,k){return N.f-k.f}),t.push({s:-1,f:25001});var a=t[0],c=t[1],u=0,l=1,d=2;for(t[0]={s:-1,f:a.f+c.f,l:a,r:c};l!=i-1;)a=t[t[u].f<t[d].f?u++:d++],c=t[u!=l&&t[u].f<t[d].f?u++:d++],t[l++]={s:-1,f:a.f+c.f,l:a,r:c};for(var f=s[0].s,r=1;r<i;++r)s[r].s>f&&(f=s[r].s);var h=new ae(f+1),_=Sn(t[l-1],h,0);if(_>e){var r=0,p=0,m=_-e,w=1<<m;for(s.sort(function(k,x){return h[x.s]-h[k.s]||k.f-x.f});r<i;++r){var y=s[r].s;if(h[y]>e)p+=w-(1<<_-h[y]),h[y]=e;else break}for(p>>=m;p>0;){var b=s[r].s;h[b]<e?p-=1<<e-h[b]++-1:++r;}for(;r>=0&&p;--r){var v=s[r].s;h[v]==e&&(--h[v],++p);}_=e;}return {t:new K(h),l:_}},"hTree"),Sn=g(function(n,e,t){return n.s==-1?Math.max(Sn(n.l,e,t+1),Sn(n.r,e,t+1)):e[n.s]=t},"ln"),Cr=g(function(n){for(var e=n.length;e&&!n[--e];);for(var t=new ae(++e),r=0,i=n[0],s=1,o=g(function(c){t[r++]=c;},"w"),a=1;a<=e;++a)if(n[a]==i&&a!=e)++s;else {if(!i&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0);}else if(s>3){for(o(i),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0);}for(;s--;)o(i);s=1,i=n[a];}return {c:t.subarray(0,r),n:e}},"lc"),vt=g(function(n,e){for(var t=0,r=0;r<e.length;++r)t+=n[r]*e[r];return t},"clen"),Rr=g(function(n,e,t){var r=t.length,i=Rn(e+2);n[i]=r&255,n[i+1]=r>>8,n[i+2]=n[i]^255,n[i+3]=n[i+1]^255;for(var s=0;s<r;++s)n[i+s+4]=t[s];return (i+4+r)*8},"wfblk"),Pr=g(function(n,e,t,r,i,s,o,a,c,u,l){Ae(e,l++,t),++i[256];for(var d=An(i,15),f=d.t,h=d.l,_=An(s,15),p=_.t,m=_.l,w=Cr(f),y=w.c,b=w.n,v=Cr(p),N=v.c,k=v.n,x=new ae(19),C=0;C<y.length;++C)++x[y[C]&31];for(var C=0;C<N.length;++C)++x[N[C]&31];for(var E=An(x,7),P=E.t,I=E.l,M=19;M>4&&!P[Pn[M-1]];--M);var j=u+5<<3,F=vt(i,Ie)+vt(s,bt)+o,T=vt(i,f)+vt(s,p)+o+14+3*M+vt(x,P)+2*x[16]+3*x[17]+7*x[18];if(c>=0&&j<=F&&j<=T)return Rr(e,l,n.subarray(c,c+u));var O,D,A,$;if(Ae(e,l,1+(T<F)),l+=2,T<F){O=ve(f,h,0),D=f,A=ve(p,m,0),$=p;var W=ve(P,I,0);Ae(e,l,b-257),Ae(e,l+5,k-1),Ae(e,l+10,M-4),l+=14;for(var C=0;C<M;++C)Ae(e,l+3*C,P[Pn[C]]);l+=3*M;for(var z=[y,N],H=0;H<2;++H)for(var L=z[H],C=0;C<L.length;++C){var X=L[C]&31;Ae(e,l,W[X]),l+=P[X],X>15&&(Ae(e,l,L[C]>>5&127),l+=L[C]>>12);}}else O=Mo,D=Ie,A=Bo,$=bt;for(var C=0;C<a;++C){var U=r[C];if(U>255){var X=U>>18&31;yt(e,l,O[X+257]),l+=D[X+257],X>7&&(Ae(e,l,U>>23&31),l+=Bt[X]);var G=U&31;yt(e,l,A[G]),l+=$[G],G>3&&(yt(e,l,U>>5&8191),l+=Ft[G]);}else yt(e,l,O[U]),l+=D[U];}return yt(e,l,O[256]),l+D[256]},"wblk"),zo=new Dn([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Mr=new K(0),Uo=g(function(n,e,t,r,i,s){var o=s.z||n.length,a=new K(r+o+5*(1+Math.ceil(o/7e3))+i),c=a.subarray(r,a.length-i),u=s.l,l=(s.r||0)&7;if(e){l&&(c[0]=s.r>>3);for(var d=zo[e-1],f=d>>13,h=d&8191,_=(1<<t)-1,p=s.p||new ae(32768),m=s.h||new ae(_+1),w=Math.ceil(t/3),y=2*w,b=g(function(nt){return (n[nt]^n[nt+1]<<w^n[nt+2]<<y)&_},"hsh"),v=new Dn(25e3),N=new ae(288),k=new ae(32),x=0,C=0,E=s.i||0,P=0,I=s.w||0,M=0;E+2<o;++E){var j=b(E),F=E&32767,T=m[j];if(p[F]=T,m[j]=F,I<=E){var O=o-E;if((x>7e3||P>24576)&&(O>423||!u)){l=Pr(n,c,0,v,N,k,C,P,M,E-M,l),P=x=C=0,M=E;for(var D=0;D<286;++D)N[D]=0;for(var D=0;D<30;++D)k[D]=0;}var A=2,$=0,W=h,z=F-T&32767;if(O>2&&j==b(E-z))for(var H=Math.min(f,O)-1,L=Math.min(32767,E),X=Math.min(258,O);z<=L&&--W&&F!=T;){if(n[E+A]==n[E+A-z]){for(var U=0;U<X&&n[E+U]==n[E+U-z];++U);if(U>A){if(A=U,$=z,U>H)break;for(var G=Math.min(z,U-2),se=0,D=0;D<G;++D){var oe=E-z+D&32767,et=p[oe],He=oe-et&32767;He>se&&(se=He,T=oe);}}}F=T,T=p[F],z+=F-T&32767;}if($){v[P++]=268435456|Tn[A]<<18|Ar[$];var tt=Tn[A]&31,fe=Ar[$]&31;C+=Bt[tt]+Ft[fe],++N[257+tt],++k[fe],I=E+A,++x;}else v[P++]=n[E],++N[n[E]];}}for(E=Math.max(E,I);E<o;++E)v[P++]=n[E],++N[n[E]];l=Pr(n,c,u,v,N,k,C,P,M,E-M,l),u||(s.r=l&7|c[l/8|0]<<3,l-=7,s.h=m,s.p=p,s.i=E,s.w=I);}else {for(var E=s.w||0;E<o+u;E+=65535){var we=E+65535;we>=o&&(c[l/8|0]=u,we=o),l=Rr(c,l+1,n.subarray(E,we));}s.i=o;}return xt(a,0,r+Rn(l)+i)},"dflt"),Ho=(function(){for(var n=new Int32Array(256),e=0;e<256;++e){for(var t=e,r=9;--r;)t=(t&1&&-306674912)^t>>>1;n[e]=t;}return n})(),Xo=g(function(){var n=-1;return {p:g(function(e){for(var t=n,r=0;r<e.length;++r)t=Ho[t&255^e[r]]^t>>>8;n=t;},"p"),d:g(function(){return ~n},"d")}},"crc");var qo=g(function(n,e,t,r,i){if(!i&&(i={l:1},e.dictionary)){var s=e.dictionary.subarray(-32768),o=new K(s.length+n.length);o.set(s),o.set(n,s.length),n=o,i.w=s.length;}return Uo(n,e.level==null?6:e.level,e.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(n.length)))*1.5):20:12+e.mem,t,r,i)},"dopt"),jr=g(function(n,e){var t={};for(var r in n)t[r]=n[r];for(var r in e)t[r]=e[r];return t},"mrg");var ye=g(function(n,e){return n[e]|n[e+1]<<8},"b2"),ce=g(function(n,e){return (n[e]|n[e+1]<<8|n[e+2]<<16|n[e+3]<<24)>>>0},"b4"),Cn=g(function(n,e){return ce(n,e)+ce(n,e+4)*4294967296},"b8"),te=g(function(n,e,t){for(;t;++e)n[e]=t,t>>>=8;},"wbytes");function Yo(n,e){return qo(n,e||{},0,0)}g(Yo,"deflateSync");function Go(n,e){return Lo(n,{i:2},e&&e.out,e&&e.dictionary)}g(Go,"inflateSync");var Br=g(function(n,e,t,r){for(var i in n){var s=n[i],o=e+i,a=r;Array.isArray(s)&&(a=jr(r,s[1]),s=s[0]),ArrayBuffer.isView(s)?t[o]=[s,a]:(t[o+="/"]=[new K(0),a],Br(s,o,t,r));}},"fltn"),Tr=typeof TextEncoder<"u"&&new TextEncoder,In=typeof TextDecoder<"u"&&new TextDecoder,Jo=0;try{In.decode(Mr,{stream:!0}),Jo=1;}catch{}var Qo=g(function(n){for(var e="",t=0;;){var r=n[t++],i=(r>127)+(r>223)+(r>239);if(t+i>n.length)return {s:e,r:xt(n,t-1)};i?i==3?(r=((r&15)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,e+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?e+=String.fromCharCode((r&31)<<6|n[t++]&63):e+=String.fromCharCode((r&15)<<12|(n[t++]&63)<<6|n[t++]&63):e+=String.fromCharCode(r);}},"dutf8");function jt(n,e){if(e){for(var t=new K(n.length),r=0;r<n.length;++r)t[r]=n.charCodeAt(r);return t}if(Tr)return Tr.encode(n);for(var i=n.length,s=new K(n.length+(n.length>>1)),o=0,a=g(function(l){s[o++]=l;},"w"),r=0;r<i;++r){if(o+5>s.length){var c=new K(o+8+(i-r<<1));c.set(s),s=c;}var u=n.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)|n.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 xt(s,0,o)}g(jt,"strToU8");function Xe(n,e){if(e){for(var t="",r=0;r<n.length;r+=16384)t+=String.fromCharCode.apply(null,n.subarray(r,r+16384));return t}else {if(In)return In.decode(n);var i=Qo(n),s=i.s,t=i.r;return t.length&&re(8),s}}g(Xe,"strFromU8");var Vo=g(function(n,e){return e+30+ye(n,e+26)+ye(n,e+28)},"slzh"),Ko=g(function(n,e,t){var r=ye(n,e+28),i=ye(n,e+30),s=Xe(n.subarray(e+46,e+46+r),!(ye(n,e+8)&2048)),o=e+46+r,a=Zo(n,o,i,t,ce(n,e+20),ce(n,e+24),ce(n,e+42)),c=a[0],u=a[1],l=a[2];return [ye(n,e+10),c,u,s,o+i+ye(n,e+32),l]},"zh"),Zo=g(function(n,e,t,r,i,s,o){var a=i==4294967295,c=s==4294967295,u=o==4294967295,l=e+t,d=a+c+u;if(r&&d){for(;e+4<l;e+=4+ye(n,e+2))if(ye(n,e)==1)return [a?Cn(n,e+4+8*c):i,c?Cn(n,e+4):s,u?Cn(n,e+4+8*(c+a)):o,1];r<2&&re(13);}return [i,s,o,0]},"z64hs"),On=g(function(n){var e=0;if(n)for(var t in n){var r=n[t].length;r>65535&&re(9),e+=r+4;}return e},"exfl"),$r=g(function(n,e,t,r,i,s,o,a){var c=r.length,u=t.extra,l=a&&a.length,d=On(u);te(n,e,o!=null?33639248:67324752),e+=4,o!=null&&(n[e++]=20,n[e++]=t.os),n[e]=20,e+=2,n[e++]=t.flag<<1|(s<0&&8),n[e++]=i&&8,n[e++]=t.compression&255,n[e++]=t.compression>>8;var f=new Date(t.mtime==null?Date.now():t.mtime),h=f.getFullYear()-1980;if((h<0||h>119)&&re(10),te(n,e,h<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),e+=4,s!=-1&&(te(n,e,t.crc),te(n,e+4,s<0?-s-2:s),te(n,e+8,t.size)),te(n,e+12,c),te(n,e+14,d),e+=16,o!=null&&(te(n,e,l),te(n,e+6,t.attrs),te(n,e+10,o),e+=14),n.set(r,e),e+=c,d)for(var _ in u){var p=u[_],m=p.length;te(n,e,+_),te(n,e+2,m),n.set(p,e+4),e+=4+m;}return l&&(n.set(a,e),e+=l),e},"wzh"),ea=g(function(n,e,t,r,i){te(n,e,101010256),te(n,e+8,t),te(n,e+10,t),te(n,e+12,r),te(n,e+16,i);},"wzf");function Fr(n,e){e||(e={});var t={},r=[];Br(n,"",t,e);var i=0,s=0;for(var o in t){var a=t[o],c=a[0],u=a[1],l=u.level==0?0:8,d=jt(o),f=d.length,h=u.comment,_=h&&jt(h),p=_&&_.length,m=On(u.extra);f>65535&&re(11);var w=l?Yo(c,u):c,y=w.length,b=Xo();b.p(c),r.push(jr(u,{size:c.length,crc:b.d(),c:w,f:d,m:_,u:f!=o.length||_&&h.length!=p,o:i,compression:l})),i+=30+f+m+y,s+=76+2*(f+m)+(p||0)+y;}for(var v=new K(s+22),N=i,k=s-i,x=0;x<r.length;++x){var d=r[x];$r(v,d.o,d,d.f,d.u,d.c.length);var C=30+d.f.length+On(d.extra);v.set(d.c,d.o+C),$r(v,i,d,d.f,d.u,d.c.length,d.o,d.m),i+=16+C+(d.m?d.m.length:0);}return ea(v,i,r.length,k,N),v}g(Fr,"zipSync");function it(n,e){for(var t={},r=n.length-22;ce(n,r)!=101010256;--r)(!r||n.length-r>65558)&&re(13);var i=ye(n,r+8);if(!i)return {};var s=ce(n,r+16),o=ce(n,r-20)==117853008;if(o){var a=ce(n,r-12);o=ce(n,a)==101075792,o&&(i=ce(n,a+32),s=ce(n,a+48));}for(var c=e&&e.filter,u=0;u<i;++u){var l=Ko(n,s,o),d=l[0],f=l[1],h=l[2],_=l[3],p=l[4],m=l[5],w=Vo(n,m);s=p,(!c||c({name:_,size:f,originalSize:h,compression:d}))&&(d?d==8?t[_]=Go(n.subarray(w,w+f),{out:new K(h)}):re(14,"unknown compression type "+d):t[_]=xt(n,w,w+f));}return t}g(it,"unzipSync");var es=Mt(Wt()),vs=Mt(Wt());var pr=Mt(Wt());var Ye=1,tr=3,nr=4,Si=8,rr=9,Ii=class{static{g(this,"FastNode");}nodeType=0;parentNode=null;ownerDocument=null;get firstChild(){return null}get lastChild(){return null}get nextSibling(){let n=this.parentNode;if(!n)return null;let e=n.childNodes,t=e.indexOf(this);return t>=0&&t+1<e.length?e[t+1]:null}get previousSibling(){let n=this.parentNode;if(!n)return null;let e=n.childNodes,t=e.indexOf(this);return t>0?e[t-1]:null}},Ot=class Oi extends Ii{static{g(this,"_FastText");}constructor(e){super(),this.data=e;}data;nodeType=tr;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 t=new Oi(this.data);return t.ownerDocument=this.ownerDocument,t}toString(){return on(this)}},Di=class Ri extends Ot{static{g(this,"_FastComment");}nodeType=Si;cloneNode(e){let t=new Ri(this.data);return t.ownerDocument=this.ownerDocument,t}},ta=class Mi extends Ot{static{g(this,"_FastCData");}nodeType=nr;cloneNode(e){let t=new Mi(this.data);return t.ownerDocument=this.ownerDocument,t}},ji=class extends Ii{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 n=this.nodeType===rr?this:this.ownerDocument;n&&n._inc++;}appendChild(n){return n.parentNode&&n.parentNode.removeChild(n),this.childNodes.push(n),n.parentNode=this,this.bump(),n}insertBefore(n,e){if(!e)return this.appendChild(n);if(this.childNodes.indexOf(e)<0)throw new Error("insertBefore: reference node not a child");n.parentNode&&n.parentNode.removeChild(n);let r=this.childNodes.indexOf(e);return this.childNodes.splice(r,0,n),n.parentNode=this,this.bump(),n}removeChild(n){let e=this.childNodes.indexOf(n);if(e<0)throw new Error("removeChild: node is not a child");return this.childNodes.splice(e,1),n.parentNode=null,this.bump(),n}replaceChild(n,e){if(this.childNodes.indexOf(e)<0)throw new Error("replaceChild: node is not a child");n.parentNode&&n.parentNode.removeChild(n);let r=this.childNodes.indexOf(e);return this.childNodes[r]=n,n.parentNode=this,e.parentNode=null,this.bump(),e}getElementsByTagName(n){let e=[],t=n==="*",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===Ye){let s=i;(t||s.tagName===n)&&e.push(s);for(let o=s.childNodes.length-1;o>=0;o--)r.push(s.childNodes[o]);}}return e}},Bi=class Fi extends ji{static{g(this,"_FastElement");}constructor(e){super(),this.tagName=e;}tagName;nodeType=Ye;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(([t,r])=>({nodeType:2,name:t,value:r,nodeName:t,nodeValue:r,localName:t.indexOf(":")<0?t:t.slice(t.indexOf(":")+1),prefix:t.indexOf(":")<0?null:t.slice(0,t.indexOf(":")),ownerElement:this}));return e.item=t=>e[t]??null,e}toString(){return on(this)}getAttribute(e){let t=this.attrs;for(let r=0;r<t.length;r++)if(t[r][0]===e)return t[r][1];return null}hasAttribute(e){return this.getAttribute(e)!==null}setAttribute(e,t){let r=this.attrs;for(let i=0;i<r.length;i++)if(r[i][0]===e){r[i][1]=String(t),this.ownerDocument&&this.ownerDocument._inc++;return}r.push([e,String(t)]),this.ownerDocument&&this.ownerDocument._inc++;}removeAttribute(e){let t=this.attrs;for(let r=0;r<t.length;r++)if(t[r][0]===e){t.splice(r,1),this.ownerDocument&&this.ownerDocument._inc++;return}}get textContent(){let e="",t=[];for(let r=this.childNodes.length-1;r>=0;r--)t.push(this.childNodes[r]);for(;t.length;){let r=t.pop();if(r.nodeType===tr||r.nodeType===nr)e+=r.data;else if(r.nodeType===Ye){let i=r;for(let s=i.childNodes.length-1;s>=0;s--)t.push(i.childNodes[s]);}}return e}set textContent(e){for(let t of this.childNodes)t.parentNode=null;if(this.childNodes.length=0,e!==""&&e!==null&&e!==void 0){let t=new Ot(String(e));t.ownerDocument=this.ownerDocument,t.parentNode=this,this.childNodes.push(t);}this.ownerDocument&&this.ownerDocument._inc++;}cloneNode(e=false){let t=new Fi(this.tagName);if(t.ownerDocument=this.ownerDocument,this.attrs.length&&(t.attrs=this.attrs.map(([r,i])=>[r,i])),e)for(let r of this.childNodes){let i=r.cloneNode(true);i.parentNode=t,t.childNodes.push(i);}return t}},na=class extends ji{static{g(this,"FastDocument");}nodeType=rr;_inc=1;documentElement=null;get nodeName(){return "#document"}createElement(n){let e=new Bi(n);return e.ownerDocument=this,e}createElementNS(n,e){return this.createElement(e)}createTextNode(n){let e=new Ot(String(n));return e.ownerDocument=this,e}createComment(n){let e=new Di(String(n));return e.ownerDocument=this,e}toString(){return on(this)}appendChild(n){let e=super.appendChild(n);return n.nodeType===Ye&&(this.documentElement=n),e}replaceChild(n,e){let t=super.replaceChild(n,e);return e===this.documentElement&&n.nodeType===Ye&&(this.documentElement=n),t}},ra=/&(?:amp|lt|gt|quot|apos|#x?[0-9a-fA-F]+);/g;function Wi(n){return n.indexOf("&")<0?n:n.replace(ra,e=>{switch(e){case "&":return "&";case "<":return "<";case ">":return ">";case """:return '"';case "'":return "'";default:{let t=e.slice(2,-1),r=t[0]==="x"||t[0]==="X"?parseInt(t.slice(1),16):parseInt(t,10);return Number.isFinite(r)?String.fromCodePoint(r):e}}})}g(Wi,"decodeEntities");function zn(n){return n.indexOf("\r")<0?n:n.replace(/\r\n?/g,`
|
|
6
|
-
`)}g(
|
|
7
|
-
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"></Relationships>`)),i}},
|
|
8
|
-
`+t),this.pkg.unzipped[e.partname.substring(1)]=jt(t),e.blob=t;let r=e._element.ownerDocument;r&&Pt(r);}return Buffer.from(Fr(this.pkg.unzipped))}},ha=Object.freeze([]),ne=class{static{g(this,"Paragraph");}constructor(n,e){this._element=n,this._parent=e;}_element;_parent;get text(){let n="",e=this._element.getElementsByTagName("w:t");for(let t=0;t<e.length;t++)n+=e[t].textContent||"";return n}},je=class{static{g(this,"Run");}constructor(n,e){this._element=n,this._parent=e;}_element;_parent;projTextOverride;sdtStack=ha},pa=class{static{g(this,"Cell");}constructor(n,e){this._element=n,this._parent=e;}_element;_parent},_a=class{static{g(this,"Row");}constructor(n,e){this._element=n,this._parent=e;for(let t of Li(this._element,"w:tc"))this.cells.push(new pa(t,this));}_element;_parent;cells=[]},Le=class{static{g(this,"Table");}constructor(n,e){this._element=n,this._parent=e;for(let t of Li(this._element,"w:tr"))this.rows.push(new _a(t,this));}_element;_parent;rows=[]},zr=class{static{g(this,"NotesPart");}constructor(n,e){this.part=n,this.note_type=e,this._element=n._element;}part;note_type;_element},ma=class{static{g(this,"FootnoteItem");}constructor(n,e,t){this._element=n,this._parent=e,this.note_type=t,this.id=n.getAttribute("w:id")||"",this.part=e.part;}_element;_parent;note_type;id;part},ft="w:sdt",ga="w:sdtPr",Qe="w:sdtContent",wa=[["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"]],ya=new Set(["checkbox","picture","building-block","repeating","repeating-item"]),va=new Set(["sdtContentLocked","contentLocked"]);function qe(n){return n?n.getAttribute("w:val")??n.getAttribute("w14:val"):null}g(qe,"val");function Tt(n){return !(ya.has(n.cls)||n.cls==="richtext"&&n.hasNestedSdt)}g(Tt,"isAnchored");function Re(n){let e=n.flags.map(t=>` ${t}`).join("");return `{#cc:${n.ordinal}${e}}`}g(Re,"openToken");function Me(n){return `{#/cc:${n.ordinal}}`}g(Me,"closeToken");var qi=new Set(["\u2610","\u2611","\u2612"]),Yi="[",Gi="]";function ar(n){return n.checked?"x":" "}g(ar,"checkboxMark");function ba(n,e=0){let t=S(n,ga),r="richtext";if(t){for(let[P,I]of wa)if(S(t,I)){r=P;break}}let i=qe(t?S(t,"w:alias"):null),s=qe(t?S(t,"w:tag"):null),o=qe(t?S(t,"w:id"):null),a=qe(t?S(t,"w:lock"):null),c=a!==null&&va.has(a),u=a==="sdtLocked"||a==="sdtContentLocked",l=t?S(t,"w:dataBinding"):null,d=!!l,f=l?l.getAttribute("w:xpath"):null,h=l?l.getAttribute("w:storeItemID"):null,_=l?l.getAttribute("w:prefixMappings"):null,p=!!(t&&S(t,"w:showingPlcHdr")),m=t?S(t,"w:temporary"):null,w=m?qe(m):null,y=!!m&&(w===null||["1","true","on"].includes(w)),b=S(n,Qe),v=null;p&&b&&(v=R(b,"w:t").map(I=>I.textContent??"").join("").trim()||null);let N=[];if(r==="dropdown"||r==="combobox"){let P=t?S(t,r==="dropdown"?"w:dropDownList":"w:comboBox"):null;if(P){let I=[];for(let M of Array.from(P.childNodes)){if(M.nodeType!==1||M.tagName!=="w:listItem")continue;let j=M.getAttribute("w:displayText"),F=M.getAttribute("w:value");I.push([j??F??"",F??j??""]);}N=I;}}let k=null;if(r==="checkbox"){let P=t?S(t,"w14:checkbox"):null,I=qe(P?S(P,"w14:checked"):null);k=I==="1"||I==="true";}let x=null;if(r==="date"){let P=t?S(t,"w:date"):null;x=qe(P?S(P,"w:dateFormat"):null);}let C=!!b&&R(b,ft).length>0,E=[];return c&&r!=="group"&&E.push("locked"),d&&E.push("bound"),r==="group"&&E.push("group"),{element:n,cls:r,alias:i,tag:s,sdtId:o,contentLocked:c,deleteLocked:u,bound:d,bindingXpath:f,storeItemId:h,prefixMappings:_,showingPlaceholder:p,placeholderText:v,temporary:y,options:N,checked:k,dateFormat:x,hasNestedSdt:C,ordinal:e,flags:E}}g(ba,"classifySdt");function xa(n){return n?R(n,ft):[]}g(xa,"iterSdtElementsInOrder");function cn(n){let e=new Map,t=0;for(let r of n)for(let i of xa(r))t+=1,e.set(i,ba(i,t));return e}g(cn,"assignOrdinals");var Na=new Set(["sdt_start","sdt_end","checkbox_start","checkbox_mark","checkbox_end"]);function lr(n){return !!n&&Na.has(n.type)&&"info"in n}g(lr,"isSdtEvent");var Ji=["checkbox_start","checkbox_mark","checkbox_end"];function Qi(n,e){let t=e+1<n.length?n[e+1]:null;return lr(t)&&t.type==="checkbox_end"}g(Qi,"nextClosesCheckbox");function un(n){return n?.element??n?._element??n}g(un,"partElement");var cr=class{static{g(this,"BlockSdt");}constructor(n){this.element=n;}element};function Vi(n){let e=n?.parentNode;if(e&&e.tagName===Qe){let t=e.parentNode;if(t&&t.tagName===ft)return t}return null}g(Vi,"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"},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",STYLES:"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"},be={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",STYLES:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"},Ur=["w14:paraId","w15:paraId","w15:paraIdParent","w16cid:paraId"],Hr=["w16cid:durableId","w16cex:durableId"],ka=["w14:textId","w:rsidR","w:rsidRPr","w:rsidRDefault","w:rsidP","w:rsidDel","w:rsidTr"],Ea=[{style_id:"CommentReference",type:"character",name:"annotation reference",based_on:"DefaultParagraphFont",half_points:"16"},{style_id:"CommentText",type:"paragraph",name:"annotation text",based_on:"Normal",half_points:"20"}],Ki=class extends Error{static{g(this,"CommentThreadingError");}constructor(n){super(n),this.name="CommentThreadingError";}};function*Hn(n){yield n;for(let e=0;e<n.childNodes.length;e++){let t=n.childNodes[e];t.nodeType===1&&(yield*Hn(t));}}g(Hn,"walkElements");var $t=class Zi{static{g(this,"_CommentsManager");}constructor(e){this.doc=e;}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(e){this._nextId=e;}_getExistingPartByType(e){return this.doc.pkg.parts.find(t=>t.contentType===e)||null}_linkPart(e,t){for(let r of this.doc.part.rels.values())if(!r.isExternal&&r.target===e.partname.split("/").pop())return e;return this.doc.relateTo(e,t),e}_getOrCreateCommentsPart(){let e=this._getExistingPartByType(Z.COMMENTS);if(e)return this._linkPart(e,be.COMMENTS);let t=this.doc.pkg.nextPartname("/word/comments%d.xml"),r=`<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 e=this.doc.pkg.addPart(t,Z.COMMENTS,r),this.doc.relateTo(e,be.COMMENTS),e}_getOrCreateExtendedPart(){let e=this._getExistingPartByType(Z.EXTENDED);if(e)return this._linkPart(e,be.EXTENDED);let t=this.doc.pkg.nextPartname("/word/commentsExtended%d.xml"),r=`<w15:commentsEx xmlns:w15="${ie.w15}"></w15:commentsEx>`;return e=this.doc.pkg.addPart(t,Z.EXTENDED,r),this.doc.relateTo(e,be.EXTENDED),e}_getOrCreateIdsPart(){let e=this._getExistingPartByType(Z.IDS);if(e)return this._linkPart(e,be.IDS);let t=this.doc.pkg.nextPartname("/word/commentsIds%d.xml"),r=`<w16cid:commentsIds xmlns:w16cid="${ie.w16cid}"></w16cid:commentsIds>`;return e=this.doc.pkg.addPart(t,Z.IDS,r),this.doc.relateTo(e,be.IDS),e}_getOrCreateExtensiblePart(){let e=this._getExistingPartByType(Z.EXTENSIBLE);if(e)return this._linkPart(e,be.EXTENSIBLE);let t=this.doc.pkg.nextPartname("/word/commentsExtensible%d.xml"),r=`<w16cex:commentsExtensible xmlns:w16cex="${ie.w16cex}"></w16cex:commentsExtensible>`;return e=this.doc.pkg.addPart(t,Z.EXTENSIBLE,r),this.doc.relateTo(e,be.EXTENSIBLE),e}_ensureNamespaces(){let e=this._commentsPart?._element;if(!e)return;let t=[["w",ie.w],["w14",ie.w14],["w15",ie.w15],["w16cid",ie.w16cid],["w16cex",ie.w16cex],["mc",ie.mc]];for(let[s,o]of t)e.getAttribute(`xmlns:${s}`)!==o&&e.setAttribute(`xmlns:${s}`,o);let r=(e.getAttribute("mc:Ignorable")||"").split(/\s+/).filter(Boolean),i=[...new Set([...r,"w14","w15","w16cid","w16cex"])].join(" ");i!==r.join(" ")&&e.setAttribute("mc:Ignorable",i);}_ensureCommentStyles(){let t=this._getOrCreateStylesPart()._element,r=new Set,i=new Set;for(let a of an(t,"w:style")){let c=a.getAttribute("w:styleId");c&&r.add(c);let u=S(a,"w:name"),l=u?u.getAttribute("w:val"):null;l&&i.add(l.trim().toLowerCase());}let s=t.ownerDocument,o=0;for(let a of Ea)r.has(a.style_id)||i.has(a.name)||(t.appendChild(Zi._buildCommentStyle(s,a,r)),r.add(a.style_id),i.add(a.name),o++);o!==0&&delete this.doc.pkg._adeu_style_cache;}_getOrCreateStylesPart(){let e=this._getExistingPartByType(Z.STYLES)??this.doc.pkg.getPartByPath("word/styles.xml");if(e)return this._linkPart(e,be.STYLES);let t=`<w:styles xmlns:w="${ie.w}"></w:styles>`,r=this.doc.pkg.addPart("/word/styles.xml",Z.STYLES,t);return this.doc.relateTo(r,be.STYLES),r}static _buildCommentStyle(e,t,r){let i=e.createElement("w:style");i.setAttribute("w:type",t.type),i.setAttribute("w:styleId",t.style_id);let s=e.createElement("w:name");if(s.setAttribute("w:val",t.name),i.appendChild(s),r.has(t.based_on)){let l=e.createElement("w:basedOn");l.setAttribute("w:val",t.based_on),i.appendChild(l);}let o=e.createElement("w:uiPriority");o.setAttribute("w:val","99"),i.appendChild(o),i.appendChild(e.createElement("w:semiHidden")),i.appendChild(e.createElement("w:unhideWhenUsed"));let a=e.createElement("w:rPr"),c=e.createElement("w:sz");c.setAttribute("w:val",t.half_points),a.appendChild(c);let u=e.createElement("w:szCs");return u.setAttribute("w:val",t.half_points),a.appendChild(u),i.appendChild(a),i}_getNextCommentId(){let e=[0],t=this._getExistingPartByType(Z.COMMENTS);if(t){let r=R(t._element,"w:comment");for(let i of r){let s=i.getAttribute("w:id");s&&e.push(parseInt(s,10)||0);}}return Math.max(...e)+1}_generateHexId(){return Lt()}_generateDurableId(){return Lt()}_getInitials(e){return e?e.split(" ").filter(Boolean).map(t=>t[0]).join("").toUpperCase():""}_hasCommentsPart(){return this._commentsPart!==null||this._getExistingPartByType(Z.COMMENTS)!==null}_findParaIdForComment(e){if(!this._hasCommentsPart())return null;for(let t of R(this.commentsPart._element,"w:comment"))if(t.getAttribute("w:id")===e)for(let r of R(t,"w:p")){let i=r.getAttribute("w14:paraId");if(i)return i}return null}_findThreadRootParaId(e){let t=this._findParaIdForComment(e),r=this._getExistingPartByType(Z.EXTENDED);if(!t||!r)return t;for(let i=0;i<r._element.childNodes.length;i++){let s=r._element.childNodes[i];if(s.nodeType===1&&s.getAttribute("w15:paraId")===t){let o=s.getAttribute("w15:paraIdParent");if(o)return o}}return t}_existingCommentPartElements(){let e=[];for(let t of [Z.COMMENTS,Z.EXTENDED,Z.IDS,Z.EXTENSIBLE]){let r=this._getExistingPartByType(t);r&&e.push(r._element);}return e}_freeLongHexNumber(e,t){let r=parseInt(e,16),i=Number.isNaN(r)?Lt():sr(r);for(;t.has(i);)i=Lt();return i}_repairInheritedLongHexNumbers(){let e=this._existingCommentPartElements();if(e.length===0)return;let t=g(s=>{let o=new Set,a=[];for(let u of e)for(let l of Hn(u))for(let d of s){let f=l.getAttribute(d);f&&(Lr(f)?o.add(f.toUpperCase()):a.includes(f)||a.push(f));}let c=new Map;for(let u of a){let l=this._freeLongHexNumber(u,o);o.add(l),c.set(u,l);}return c},"remapFor"),r=t(Ur),i=t(Hr);for(let s of e)for(let o of Hn(s)){for(let a of Ur){let c=r.get(o.getAttribute(a)??"");c&&o.setAttribute(a,c);}for(let a of Hr){let c=i.get(o.getAttribute(a)??"");c&&o.setAttribute(a,c);}for(let a of ka){let c=o.getAttribute(a);c&&!Lr(c)&&o.setAttribute(a,this._freeLongHexNumber(c,new Set));}}}_adoptIntoModernComments(e){if(!this._hasCommentsPart())return null;let t=null;for(let o of R(this.commentsPart._element,"w:comment"))if(o.getAttribute("w:id")===e){t=o;break}if(!t)return null;let r=R(t,"w:p");if(r.length===0)return null;let i=null;for(let o of r){let a=o.getAttribute("w14:paraId");if(a){i=a;break}}i||(i=this._generateHexId(),r[0].setAttribute("w14:paraId",i));let s=g((o,a)=>{for(let c=0;c<o._element.childNodes.length;c++){let u=o._element.childNodes[c];if(u.nodeType===1&&u.getAttribute(a)===i)return true}return false},"hasChild");if(!s(this.extendedPart,"w15:paraId")){let a=this.extendedPart._element.ownerDocument.createElement("w15:commentEx");a.setAttribute("w15:paraId",i),a.setAttribute("w15:done","0"),this.extendedPart._element.appendChild(a);}if(!s(this.idsPart,"w16cid:paraId")){let a=this.idsPart._element.ownerDocument.createElement("w16cid:commentId");a.setAttribute("w16cid:paraId",i),a.setAttribute("w16cid:durableId",this._generateDurableId()),this.idsPart._element.appendChild(a);}return i}resolveThreadParentParaId(e){this._repairInheritedLongHexNumbers();let t=this._findThreadRootParaId(e),r=this._adoptIntoModernComments(e);return t??r}addComment(e,t,r=null,i){this._repairInheritedLongHexNumbers();let s=this._getExistingPartByType(Z.EXTENDED)!==null,o=null;if(r!=null&&(o=this.resolveThreadParentParaId(r),!o))throw new Ki(`Cannot thread a reply onto comment Com:${r}: 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.`);this._ensureCommentStyles();let a=this.nextId.toString();this.nextId++;let c=i??new Date().toISOString().replace(/\.\d{3}Z$/,"Z"),u=this.commentsPart._element.ownerDocument,l=u.createElement("w:comment");l.setAttribute("w:id",a),l.setAttribute("w:author",e),l.setAttribute("w:date",c);let d=this._getInitials(e);d&&l.setAttribute("w:initials",d),r&&!s&&l.setAttribute("w15:p",r);let f=this._generateHexId(),h=this._generateHexId(),_=u.createElement("w:p");_.setAttribute("w14:paraId",f),_.setAttribute("w14:textId","77777777"),_.setAttribute("w:rsidR",h),_.setAttribute("w:rsidRDefault",h),_.setAttribute("w:rsidP",h);let p=u.createElement("w:pPr"),m=u.createElement("w:pStyle");m.setAttribute("w:val","CommentText"),p.appendChild(m),_.appendChild(p);let w=u.createElement("w:r"),y=u.createElement("w:rPr"),b=u.createElement("w:rStyle");b.setAttribute("w:val","CommentReference"),y.appendChild(b),w.appendChild(y),w.appendChild(u.createElement("w:annotationRef")),_.appendChild(w);let v=u.createElement("w:r"),N=u.createElement("w:t");if(N.textContent=t,v.appendChild(N),_.appendChild(v),l.appendChild(_),this.commentsPart._element.appendChild(l),this.extendedPart){let x=this.extendedPart._element.ownerDocument.createElement("w15:commentEx");x.setAttribute("w15:paraId",f),o&&x.setAttribute("w15:paraIdParent",o),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",f),x.setAttribute("w16cid:durableId",this._generateDurableId()),this.idsPart._element.appendChild(x);}if(this.extensiblePart){let k=null;for(let x=0;x<this.idsPart._element.childNodes.length;x++){let C=this.idsPart._element.childNodes[x];if(C.nodeType===1&&C.getAttribute("w16cid:paraId")===f){k=C.getAttribute("w16cid:durableId");break}}if(k){let C=this.extensiblePart._element.ownerDocument.createElement("w16cex:commentExtensible");C.setAttribute("w16cex:durableId",k),C.setAttribute("w16cex:dateUtc",c),this.extensiblePart._element.appendChild(C);}}return a}deleteComment(e){if(!this.commentsPart)return;let t=null;for(let i of R(this.commentsPart._element,"w:comment"))if(i.getAttribute("w:id")===e){t=i;break}if(!t)return;let r=null;for(let i of R(t,"w:p")){let s=i.getAttribute("w14:paraId");if(s){r=s;break}}if(r){let i=[];if(this.extendedPart)for(let o=0;o<this.extendedPart._element.childNodes.length;o++){let a=this.extendedPart._element.childNodes[o];if(a.nodeType===1&&a.getAttribute("w15:paraIdParent")===r){let c=a.getAttribute("w15:paraId");if(c){for(let u of R(this.commentsPart._element,"w:comment"))for(let l of R(u,"w:p"))if(l.getAttribute("w14:paraId")===c){let d=u.getAttribute("w:id");d&&i.push(d);break}}}}for(let o of i)this.deleteComment(o);let s=null;if(this.idsPart){let o=[];for(let a=0;a<this.idsPart._element.childNodes.length;a++){let c=this.idsPart._element.childNodes[a];c.nodeType===1&&c.getAttribute("w16cid:paraId")===r&&(s=c.getAttribute("w16cid:durableId"),o.push(c));}o.forEach(a=>this.idsPart._element.removeChild(a));}if(this.extendedPart){let o=[];for(let a=0;a<this.extendedPart._element.childNodes.length;a++){let c=this.extendedPart._element.childNodes[a];c.nodeType===1&&c.getAttribute("w15:paraId")===r&&o.push(c);}o.forEach(a=>this.extendedPart._element.removeChild(a));}if(s&&this.extensiblePart){let o=[];for(let a=0;a<this.extensiblePart._element.childNodes.length;a++){let c=this.extensiblePart._element.childNodes[a];c.nodeType===1&&c.getAttribute("w16cex:durableId")===s&&o.push(c);}o.forEach(a=>this.extensiblePart._element.removeChild(a));}}t.parentNode&&t.parentNode.removeChild(t);}};function Be(n){({part:n.mainDocumentPart,relateTo:g(()=>{},"relateTo")});let r=Object.create(null),i=n.parts.find(c=>c.contentType===Z.COMMENTS);if(!i)return r;let s=Object.create(null),o=R(i._element,"w:comment");for(let c of o){let u=c.getAttribute("w:id");if(!u)continue;let l=c.getAttribute("w:author")||"Unknown",d=c.getAttribute("w:date")||"",f=false,h=c.getAttribute("w15:done");(h==="1"||h==="true"||h==="on")&&(f=true);let _=c.getAttribute("w15:p")||null,p=R(c,"w:p");for(let y of p){let b=y.getAttribute("w14:paraId");b&&(s[b]=u);}let m=[];for(let y of p){let b=R(y,"w:t");for(let v of b)v.textContent&&m.push(v.textContent);m.push(`
|
|
9
|
-
`);}let w=m.join("").trim();r[u]={author:l,text:w,date:d,resolved:f,parent_id:_};}let a=n.parts.find(c=>c.contentType===Z.EXTENDED);if(a){let c=a._element.childNodes;for(let u=0;u<c.length;u++){let l=c[u];if(l.nodeType!==1)continue;let d=l.getAttribute("w15:paraId"),f=l.getAttribute("w15:paraIdParent"),h=l.getAttribute("w15:done");if(d){let _=s[d];if(_&&r[_]){if(f){let p=s[f];p&&(r[_].parent_id=p);}(h==="1"||h==="true"||h==="on")&&(r[_].resolved=true);}}}}return r}g(Be,"extract_comments_data");var jn=500,ot=200,Aa=["{++","++}","{--","--}","{==","==}","{>>","<<}"];function ts(n){if(!n||!n.includes("{")&&!n.includes("}"))return n;for(let e of Aa)if(n.includes(e)){let t=e.startsWith("{")?"{ "+e.slice(1):e.slice(0,-1)+" }";n=n.split(e).join(t);}return n}g(ts,"escape_critic_tokens");function Xr(n,e){return n.length<=e?n:n.slice(0,Math.max(1,e-3))+"..."}g(Xr,"clamp_text");function pe(n,e){if(n==null||n.length<=e)return n;let t=Math.max(1,Math.floor(e*2/3)),r=Math.max(1,e-t),i=n.length-t-r;return `${n.slice(0,t)}\u2026 [${i.toLocaleString("en-US")} chars omitted] \u2026${n.slice(-r)}`}g(pe,"truncate_middle");var Ca={"\u201C":'"',"\u201D":'"',"\u2018":"'","\u2019":"'"},Pa=/[\u201c\u201d\u2018\u2019]/g;function Et(n){return n&&n.replace(Pa,e=>Ca[e])}g(Et,"normalize_smart_quotes");function Xn(n){return !!n&&/[\u201c\u201d\u2018\u2019]/.test(n)}g(Xn,"has_smart_quotes");function Ta(n,e){if(!n||!e||!Xn(n))return e;let t=Et(n),r=Et(e);if(t===r)return n;let s=new es.diff_match_patch().diff_main(t,r),o=[],a=0,c=0;for(let[u,l]of s)u===0?(o.push(n.substr(a,l.length)),a+=l.length,c+=l.length):u===-1?a+=l.length:(o.push(e.substr(c,l.length)),c+=l.length);return o.join("")}g(Ta,"restore_document_typography");function $a(n,e,t){return !t||!n||!Xn(n)||Xn(e||"")?t:Ta(n,t)}g($a,"restore_matched_typography");var ur=2e3,Fe=class extends Error{static{g(this,"RegexTimeoutError");}pattern;constructor(n){super(`Regular expression exceeded the ${ur/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=n;}};function ns(n){let e=false,t=false,r=[];for(let i=0;i<n.length;i++){let s=n[i];if(t){t=false;continue}if(s==="\\"){t=true;continue}if(e){s==="]"&&(e=false);continue}if(s==="["){e=true;continue}if(s==="("){r.push({hasInnerQuantifierOrPipe:false});continue}if(s===")"){if(r.length>0){let o=r.pop(),a=n.substring(i+1),c=a.match(/^(\*|\+|\{\d+\,\s*\}|\?)/),u=c?c[1]:"",l=u==="*"||u==="+"||/^\{\d+\,\s*\}/.test(a);if(l&&o.hasInnerQuantifierOrPipe)return true;r.length>0&&(o.hasInnerQuantifierOrPipe||l)&&(r[r.length-1].hasInnerQuantifierOrPipe=true);}continue}r.length>0&&(s==="|"||s==="*"||s==="+"||/^\{\d+\,\s*\}/.test(n.substring(i)))&&(r[r.length-1].hasInnerQuantifierOrPipe=true);}return false}g(ns,"hasCatastrophicBacktrackingRisk");function Sa(n,e,t=""){if(ns(n))throw new Fe(n);let r=t.includes("g")?t:t+"g",i=new RegExp(n,r),s=Date.now(),o=[],a;for(;(a=i.exec(e))!==null;){if(Date.now()-s>ur)throw new Fe(n);o.push({start:a.index,end:a.index+a[0].length}),a.index===i.lastIndex&&i.lastIndex++;}return o}g(Sa,"userFindAllMatches");function Ia(n,e,t=""){if(ns(n))throw new Fe(n);let r=new RegExp(n,t.replace("g","")),i=Date.now(),s=r.exec(e);if(Date.now()-i>ur)throw new Fe(n);return s?{start:s.index,end:s.index+s[0].length}:null}g(Ia,"userSearch");var rs="w:p",dr="w:r",Dt="w:t",is="w:delText",ss="w:tab",os="w:br",as="w:cr",Vt="\f",dn="w:rPr",Oa="w:rPrChange",Da="w:commentReference",Ra="w:footnoteReference",Ma="w:endnoteReference",ja="w:fldChar",Ba="w:fldCharType",Fa="w:instrText",Wa="w:ins",ls="w:del",Oe="w:id",Bn="w:author",Fn="w:date",La="w:commentRangeStart",za="w:commentRangeEnd",Ua="w:hyperlink",Ha="r:id",Xa="w:fldSimple",qa="w:instr",Ya="w:bookmarkStart",Ga="w:name",St="w:sdt",Ja="w:smartTag",fr="w:sdtContent",cs="w:b",Qa="w:i",ue="w:val",hr="w:pPr",us="w:pStyle",ds="w:outlineLvl",Va="w:numPr",Ka="w:numId",Za="w:ilvl",qn="w:drawing",Yn="w:object",Gn="w:pict",el="wp:docPr",tl="v:imagedata",nl="o:title",rl="w:txbxContent",il="mc:AlternateContent",sl="mc:Choice",ol="mc:Fallback",qr=300;function Yr(n){let e=[];for(let r of R(n,rl))for(let i of R(r,Dt))i.textContent&&e.push(i.textContent);let t=e.join(" ").split(/\s+/).filter(Boolean).join(" ");return t.length>qr&&(t=t.slice(0,qr).trimEnd()+"\u2026"),t}g(Yr,"_textbox_text");function*Gr(n){let e=n.tagName;if(e===qn||e===Yn){let t=R(n,el)[0]||null,r="",i="0";t&&(r=t.getAttribute("descr")||t.getAttribute("title")||"",i=t.getAttribute("id")||"0");let s=Yr(n);s&&(r=r?`Text box (${r}): ${s}`:`Text box: ${s}`),yield {type:"image",id:i,date:r};}else if(e===Gn){let t=R(n,tl)[0]||null,r=t&&t.getAttribute(nl)||"",i=Yr(n);i&&(r=r?`Text box (${r}): ${i}`:`Text box: ${i}`),(i||t)&&(yield {type:"image",id:"vml",date:r});}}g(Gr,"_graphic_marker_events");var al=/Heading[ ]?([1-6])(?![0-9])/;function ll(n){let e=n,t=new Set;for(;e&&!t.has(e);){if(t.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(ll,"_resolve_package");function ht(n){let e=n.package||n.pkg||(n.part?n.part.pkg:null);if(e&&e._adeu_style_cache)return e._adeu_style_cache;let t=Object.create(null),r=null,i=Object.create(null),s=e?.getPartByPath("word/styles.xml");if(!s){let u=[t,null];return e&&(e._adeu_style_cache=u),u}let o=R(s._element,"w:style");for(let u of o){let l=u.getAttribute("w:styleId");if(!l)continue;let d=u.getAttribute("w:type"),f=u.getAttribute("w:default")==="1"||u.getAttribute("w:default")==="true";d==="paragraph"&&f&&(r=l);let h=S(u,"w:name"),_=h?h.getAttribute("w:val"):l;_&&typeof _=="string"&&(_.toLowerCase().startsWith("heading")?_=_.replace(/^heading/i,"Heading"):_.toLowerCase()==="title"&&(_="Title"));let p=S(u,"w:basedOn"),m=p?p.getAttribute("w:val"):null,w=null,y=null,b=null,v=S(u,"w:pPr");if(v){let x=S(v,"w:outlineLvl");if(x){let E=x.getAttribute("w:val");E&&/^\d+$/.test(E)&&(w=parseInt(E,10));}let C=S(v,"w:numPr");if(C){let E=S(C,"w:numId");if(E){let I=E.getAttribute("w:val");I&&I!=="0"&&(y=I);}let P=S(C,"w:ilvl");if(P){let I=P.getAttribute("w:val");I&&/^\d+$/.test(I)&&(b=parseInt(I,10));}}}let N=null,k=S(u,"w:rPr");if(k){let x=S(k,"w:b");if(x){let C=x.getAttribute("w:val");N=C!=="0"&&C!=="false"&&C!=="off";}}i[l]={name:_,based_on:m,outline_level:w,bold:N,num_id:y,num_ilvl:b};}let a=g((u,l)=>{if(t[u])return t[u];if(l.has(u)||!i[u])return {name:u,outline_level:null,bold:false,num_id:null,num_ilvl:null};l.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 y=a(f,l);h===null&&(h=y.outline_level),d.bold===null&&(_=y.bold),p===null&&(p=y.num_id??null),m===null&&(m=y.num_ilvl??null);}let w={name:d.name,outline_level:h,bold:_,num_id:p,num_ilvl:m};return t[u]=w,w},"resolve_style");for(let u in i)a(u,new Set);let c=[t,r];return e&&(e._adeu_style_cache=c),c}g(ht,"_get_style_cache");function cl(n){let e=ll(n);if(!e)return {};if(e._adeu_numbering_cache)return e._adeu_numbering_cache;let t=Object.create(null),r=null;try{let i=(e.parts||[]).find(s=>String(s.partname).endsWith("/numbering.xml"));i&&(r=i._element);}catch{r=null;}if(r){let i=Object.create(null);for(let s of R(r,"w:abstractNum")){let o=s.getAttribute("w:abstractNumId");if(o===null)continue;let a={};for(let c of R(s,"w:lvl")){let u=c.getAttribute("w:ilvl"),l=S(c,"w:numFmt");if(u!==null&&/^-?\d+$/.test(u)&&l){let d=l.getAttribute("w:val");d&&(a[parseInt(u,10)]=d);}}i[o]=a;}for(let s of R(r,"w:num")){let o=s.getAttribute("w:numId"),a=S(s,"w:abstractNumId");if(o===null||!a)continue;let c=a.getAttribute("w:val");c!==null&&i[c]!==void 0&&(t[o]=i[c]);}}return e._adeu_numbering_cache=t,t}g(cl,"_get_numbering_cache");function ul(n,e,t){let r=null;if(e!=null){let i=cl(n)[e];if(i&&Object.keys(i).length>0&&(r=i[t]!==void 0?i[t]:null,r===null)){for(let s=t;s>=0;s--)if(i[s]!==void 0){r=i[s];break}}}return r!==null&&r!=="bullet"?"1. ":"* "}g(ul,"get_list_marker");function fs(n){if(!n)return null;let e=n.match(al);return e?parseInt(e[1],10):null}g(fs,"_detect_heading_level_from_name");function hs(n){let e=S(n,hr);if(!e)return false;let t=S(e,dn);return !!t&&!!S(t,ls)}g(hs,"paragraph_mark_is_deleted");function fn(n,e,t){e||([e,t]=ht(n._parent.part||n._parent));let r=S(n._element,hr);if(r){let a=S(r,ds);if(a){let c=a.getAttribute(ue);if(c&&/^\d+$/.test(c)){let u=parseInt(c,10);if(u>=0&&u<=8)return true}}}let i=t;if(r){let a=S(r,us);a&&(i=a.getAttribute(ue)||t);}let s=i&&e?e[i]:null;if(s&&s.outline_level!==null&&s.outline_level>=0&&s.outline_level<=8)return true;let o=s?s.name:i;return o&&typeof o=="string"&&o.toLowerCase().startsWith("heading")&&(o=o.replace(/^heading/i,"Heading")),!!(o?.startsWith("Heading")||o==="Title"||o&&o!=="Normal"&&fs(o)!==null)}g(fn,"is_native_heading");function ze(n,e,t){e||([e,t]=ht(n._parent.part||n._parent));let r=S(n._element,hr);if(r){let l=S(r,ds);if(l){let d=l.getAttribute(ue);if(d&&/^\d+$/.test(d)){let f=parseInt(d,10);if(f>=0&&f<=8)return "#".repeat(f+1)+" "}}}let i=t;if(r){let l=S(r,us);l&&(i=l.getAttribute(ue)||t);}let s=i&&e?e[i]:null;if(s&&s.outline_level!==null&&s.outline_level>=0&&s.outline_level<=8)return "#".repeat(s.outline_level+1)+" ";let o=s?s.name:i;if(o&&typeof o=="string"&&o.toLowerCase().startsWith("heading")&&(o=o.replace(/^heading/i,"Heading")),o?.startsWith("Heading")){let l=o.replace("Heading","").trim();if(/^\d+$/.test(l))return "#".repeat(parseInt(l,10))+" "}if(o==="Title")return "# ";let a=null,c=null,u=false;if(r){let l=S(r,Va);if(l){let d=S(l,Ka);if(d){let f=d.getAttribute(ue);if(f==="0")u=true;else if(f){a=f;let h=S(l,Za);if(h){let _=h.getAttribute(ue);_!==null&&/^\d+$/.test(_)&&(c=parseInt(_,10));}}}}}if(a===null&&!u&&s){let l=s.num_id;l&&(a=l,c===null&&(c=s.num_ilvl!==void 0?s.num_ilvl:null));}if(a!==null){let l=c!==null?c:0,d=ul(n._parent?n._parent.part||n._parent:null,a,l);return " ".repeat(l)+d}if(o&&o!=="Normal"){let l=fs(o);if(l!==null)return "#".repeat(l)+" "}if(!o||o==="Normal"){let l=false,d=n._element;for(;d;){if(d.tagName==="w:tc"){l=true;break}d=d.parentNode;}if(l)return "";let f=n.text.trim();if(f&&f.length<100&&f===f.toUpperCase()){let h=false;if(s?.bold)h=true;else {let _=R(n._element,dr);for(let p of _)if(R(p,Dt).map(y=>y.textContent||"").join("").trim()){let y=S(p,dn);if(y){let b=S(y,cs);b&&b.getAttribute(ue)!=="0"&&b.getAttribute(ue)!=="false"&&(h=true);}break}}if(h)return "## "}}return ""}g(ze,"get_paragraph_prefix");function ps(n,e,t){let r=ze(n,e,t);if(!r)return false;let i=r.trimEnd();return i.length>0&&i==="#".repeat(i.length)}g(ps,"is_heading_paragraph");function _s(n,e=null){if(n.projTextOverride!==void 0)return ["",""];let t="",r="",i=S(n._element,dn),s=false,o=false;if(i){let a=S(i,cs);a&&a.getAttribute(ue)!=="0"&&a.getAttribute(ue)!=="false"&&(s=true);let c=S(i,Qa);c&&c.getAttribute(ue)!=="0"&&c.getAttribute(ue)!=="false"&&(o=true);}if(e===null){let a=n._parent;e=a instanceof ne?fn(a):false;}return s&&!e&&(t+="**",r="**"+r),o&&(t+="_",r="_"+r),[t,r]}g(_s,"get_run_style_markers");function ms(n){let e=n.trim();if(!e)return ["","",n];let t=n.length-n.trimStart().length;return [n.substring(0,t),n.substring(t,t+e.length),n.substring(t+e.length)]}g(ms,"split_boundary_whitespace");function gs(n){let e=[],t=[],r=new Set;for(let[s,o]of n){let a=Object.entries(s),c=Object.entries(o);if(a.length===0&&c.length===0){t.length>0&&(e.push(t),t=[]);continue}let u=[];for(let[l,d]of a)r.has(l)||u.push([l,d&&d.author||"Unknown"]);for(let[l,d]of c)r.has(l)||u.push([l,d&&d.author||"Unknown"]);for(let[l,d]of u)r.add(l),t.length>0&&t[t.length-1][1]!==d&&(e.push(t),t=[]),t.push([l,d]);}t.length>0&&e.push(t);let i={};for(let s of e)if(!(s.length<2))for(let[o]of s)i[o]=s.filter(([a])=>a!==o).map(([a])=>`Chg:${a}`).join(", ");return i}g(gs,"compute_change_pair_map");function dl(n,e,t){if(!e&&!t)return n;if(!n)return "";let r=g(s=>{let[o,a,c]=ms(s);return a?`${o}${e}${a}${t}${c}`:s},"wrap");return n.includes(`
|
|
1
|
+
'use strict';var n8nWorkflow=require('n8n-workflow'),path=require('path');var Lo=Object.create;var Sn=Object.defineProperty;var Wo=Object.getOwnPropertyDescriptor;var zo=Object.getOwnPropertyNames;var Uo=Object.getPrototypeOf,Ho=Object.prototype.hasOwnProperty;var g=(n,e)=>Sn(n,"name",{value:e,configurable:true});var Dr=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports);var qo=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of zo(e))!Ho.call(n,i)&&i!==t&&Sn(n,i,{get:()=>e[i],enumerable:!(r=Wo(e,i))||r.enumerable});return n};var Ft=(n,e,t)=>(t=n!=null?Lo(Uo(n)):{},qo(Sn(t,"default",{value:n,enumerable:true}),n));var Mr=Dr((zu,Rr)=>{Rr.exports={createRequire:g(function(){return function(){return {}}},"createRequire")};});var Ut=Dr((Xu,lt)=>{var W=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"),Q=-1,K=1,Y=0;W.Diff=function(n,e){return [n,e]};W.prototype.diff_main=function(n,e,t,r){typeof r>"u"&&(this.Diff_Timeout<=0?r=Number.MAX_VALUE:r=new Date().getTime()+this.Diff_Timeout*1e3);var i=r;if(n==null||e==null)throw new Error("Null input. (diff_main)");if(n==e)return n?[new W.Diff(Y,n)]:[];typeof t>"u"&&(t=true);var s=t,o=this.diff_commonPrefix(n,e),a=n.substring(0,o);n=n.substring(o),e=e.substring(o),o=this.diff_commonSuffix(n,e);var l=n.substring(n.length-o);n=n.substring(0,n.length-o),e=e.substring(0,e.length-o);var d=this.diff_compute_(n,e,s,i);return a&&d.unshift(new W.Diff(Y,a)),l&&d.push(new W.Diff(Y,l)),this.diff_cleanupMerge(d),d};W.prototype.diff_compute_=function(n,e,t,r){var i;if(!n)return [new W.Diff(K,e)];if(!e)return [new W.Diff(Q,n)];var s=n.length>e.length?n:e,o=n.length>e.length?e:n,a=s.indexOf(o);if(a!=-1)return i=[new W.Diff(K,s.substring(0,a)),new W.Diff(Y,o),new W.Diff(K,s.substring(a+o.length))],n.length>e.length&&(i[0][0]=i[2][0]=Q),i;if(o.length==1)return [new W.Diff(Q,n),new W.Diff(K,e)];var l=this.diff_halfMatch_(n,e);if(l){var d=l[0],c=l[1],u=l[2],f=l[3],h=l[4],_=this.diff_main(d,u,t,r),p=this.diff_main(c,f,t,r);return _.concat([new W.Diff(Y,h)],p)}return t&&n.length>100&&e.length>100?this.diff_lineMode_(n,e,r):this.diff_bisect_(n,e,r)};W.prototype.diff_lineMode_=function(n,e,t){var r=this.diff_linesToChars_(n,e);n=r.chars1,e=r.chars2;var i=r.lineArray,s=this.diff_main(n,e,false,t);this.diff_charsToLines_(s,i),this.diff_cleanupSemantic(s),s.push(new W.Diff(Y,""));for(var o=0,a=0,l=0,d="",c="";o<s.length;){switch(s[o][0]){case K:l++,c+=s[o][1];break;case Q:a++,d+=s[o][1];break;case Y:if(a>=1&&l>=1){s.splice(o-a-l,a+l),o=o-a-l;for(var u=this.diff_main(d,c,false,t),f=u.length-1;f>=0;f--)s.splice(o,0,u[f]);o=o+u.length;}l=0,a=0,d="",c="";break}o++;}return s.pop(),s};W.prototype.diff_bisect_=function(n,e,t){for(var r=n.length,i=e.length,s=Math.ceil((r+i)/2),o=s,a=2*s,l=new Array(a),d=new Array(a),c=0;c<a;c++)l[c]=-1,d[c]=-1;l[o+1]=0,d[o+1]=0;for(var u=r-i,f=u%2!=0,h=0,_=0,p=0,m=0,w=0;w<s&&!(new Date().getTime()>t);w++){for(var y=-w+h;y<=w-_;y+=2){var b=o+y,v;y==-w||y!=w&&l[b-1]<l[b+1]?v=l[b+1]:v=l[b-1]+1;for(var N=v-y;v<r&&N<i&&n.charAt(v)==e.charAt(N);)v++,N++;if(l[b]=v,v>r)_+=2;else if(N>i)h+=2;else if(f){var k=o+u-y;if(k>=0&&k<a&&d[k]!=-1){var x=r-d[k];if(v>=x)return this.diff_bisectSplit_(n,e,v,N,t)}}}for(var P=-w+p;P<=w-m;P+=2){var k=o+P,x;P==-w||P!=w&&d[k-1]<d[k+1]?x=d[k+1]:x=d[k-1]+1;for(var E=x-P;x<r&&E<i&&n.charAt(r-x-1)==e.charAt(i-E-1);)x++,E++;if(d[k]=x,x>r)m+=2;else if(E>i)p+=2;else if(!f){var b=o+u-P;if(b>=0&&b<a&&l[b]!=-1){var v=l[b],N=o+v-b;if(x=r-x,v>=x)return this.diff_bisectSplit_(n,e,v,N,t)}}}}return [new W.Diff(Q,n),new W.Diff(K,e)]};W.prototype.diff_bisectSplit_=function(n,e,t,r,i){var s=n.substring(0,t),o=e.substring(0,r),a=n.substring(t),l=e.substring(r),d=this.diff_main(s,o,false,i),c=this.diff_main(a,l,false,i);return d.concat(c)};W.prototype.diff_linesToChars_=function(n,e){var t=[],r={};t[0]="";function i(l){for(var d="",c=0,u=-1,f=t.length;u<l.length-1;){u=l.indexOf(`
|
|
2
|
+
`,c),u==-1&&(u=l.length-1);var h=l.substring(c,u+1);(r.hasOwnProperty?r.hasOwnProperty(h):r[h]!==void 0)?d+=String.fromCharCode(r[h]):(f==s&&(h=l.substring(c),u=l.length),d+=String.fromCharCode(f),r[h]=f,t[f++]=h),c=u+1;}return d}g(i,"diff_linesToCharsMunge_");var s=4e4,o=i(n);s=65535;var a=i(e);return {chars1:o,chars2:a,lineArray:t}};W.prototype.diff_charsToLines_=function(n,e){for(var t=0;t<n.length;t++){for(var r=n[t][1],i=[],s=0;s<r.length;s++)i[s]=e[r.charCodeAt(s)];n[t][1]=i.join("");}};W.prototype.diff_commonPrefix=function(n,e){if(!n||!e||n.charAt(0)!=e.charAt(0))return 0;for(var t=0,r=Math.min(n.length,e.length),i=r,s=0;t<i;)n.substring(s,i)==e.substring(s,i)?(t=i,s=t):r=i,i=Math.floor((r-t)/2+t);return i};W.prototype.diff_commonSuffix=function(n,e){if(!n||!e||n.charAt(n.length-1)!=e.charAt(e.length-1))return 0;for(var t=0,r=Math.min(n.length,e.length),i=r,s=0;t<i;)n.substring(n.length-i,n.length-s)==e.substring(e.length-i,e.length-s)?(t=i,s=t):r=i,i=Math.floor((r-t)/2+t);return i};W.prototype.diff_commonOverlap_=function(n,e){var t=n.length,r=e.length;if(t==0||r==0)return 0;t>r?n=n.substring(t-r):t<r&&(e=e.substring(0,t));var i=Math.min(t,r);if(n==e)return i;for(var s=0,o=1;;){var a=n.substring(i-o),l=e.indexOf(a);if(l==-1)return s;o+=l,(l==0||n.substring(i-o)==e.substring(0,o))&&(s=o,o++);}};W.prototype.diff_halfMatch_=function(n,e){if(this.Diff_Timeout<=0)return null;var t=n.length>e.length?n:e,r=n.length>e.length?e:n;if(t.length<4||r.length*2<t.length)return null;var i=this;function s(_,p,m){for(var w=_.substring(m,m+Math.floor(_.length/4)),y=-1,b="",v,N,k,x;(y=p.indexOf(w,y+1))!=-1;){var P=i.diff_commonPrefix(_.substring(m),p.substring(y)),E=i.diff_commonSuffix(_.substring(0,m),p.substring(0,y));b.length<E+P&&(b=p.substring(y-E,y)+p.substring(y,y+P),v=_.substring(0,m-E),N=_.substring(m+P),k=p.substring(0,y-E),x=p.substring(y+P));}return b.length*2>=_.length?[v,N,k,x,b]:null}g(s,"diff_halfMatchI_");var o=s(t,r,Math.ceil(t.length/4)),a=s(t,r,Math.ceil(t.length/2)),l;if(!o&&!a)return null;a?o?l=o[4].length>a[4].length?o:a:l=a:l=o;var d,c,u,f;n.length>e.length?(d=l[0],c=l[1],u=l[2],f=l[3]):(u=l[0],f=l[1],d=l[2],c=l[3]);var h=l[4];return [d,c,u,f,h]};W.prototype.diff_cleanupSemantic=function(n){for(var e=false,t=[],r=0,i=null,s=0,o=0,a=0,l=0,d=0;s<n.length;)n[s][0]==Y?(t[r++]=s,o=l,a=d,l=0,d=0,i=n[s][1]):(n[s][0]==K?l+=n[s][1].length:d+=n[s][1].length,i&&i.length<=Math.max(o,a)&&i.length<=Math.max(l,d)&&(n.splice(t[r-1],0,new W.Diff(Q,i)),n[t[r-1]+1][0]=K,r--,r--,s=r>0?t[r-1]:-1,o=0,a=0,l=0,d=0,i=null,e=true)),s++;for(e&&this.diff_cleanupMerge(n),this.diff_cleanupSemanticLossless(n),s=1;s<n.length;){if(n[s-1][0]==Q&&n[s][0]==K){var c=n[s-1][1],u=n[s][1],f=this.diff_commonOverlap_(c,u),h=this.diff_commonOverlap_(u,c);f>=h?(f>=c.length/2||f>=u.length/2)&&(n.splice(s,0,new W.Diff(Y,u.substring(0,f))),n[s-1][1]=c.substring(0,c.length-f),n[s+1][1]=u.substring(f),s++):(h>=c.length/2||h>=u.length/2)&&(n.splice(s,0,new W.Diff(Y,c.substring(0,h))),n[s-1][0]=K,n[s-1][1]=u.substring(0,u.length-h),n[s+1][0]=Q,n[s+1][1]=c.substring(h),s++),s++;}s++;}};W.prototype.diff_cleanupSemanticLossless=function(n){function e(h,_){if(!h||!_)return 6;var p=h.charAt(h.length-1),m=_.charAt(0),w=p.match(W.nonAlphaNumericRegex_),y=m.match(W.nonAlphaNumericRegex_),b=w&&p.match(W.whitespaceRegex_),v=y&&m.match(W.whitespaceRegex_),N=b&&p.match(W.linebreakRegex_),k=v&&m.match(W.linebreakRegex_),x=N&&h.match(W.blanklineEndRegex_),P=k&&_.match(W.blanklineStartRegex_);return x||P?5:N||k?4:w&&!b&&v?3:b||v?2:w||y?1:0}g(e,"diff_cleanupSemanticScore_");for(var t=1;t<n.length-1;){if(n[t-1][0]==Y&&n[t+1][0]==Y){var r=n[t-1][1],i=n[t][1],s=n[t+1][1],o=this.diff_commonSuffix(r,i);if(o){var a=i.substring(i.length-o);r=r.substring(0,r.length-o),i=a+i.substring(0,i.length-o),s=a+s;}for(var l=r,d=i,c=s,u=e(r,i)+e(i,s);i.charAt(0)===s.charAt(0);){r+=i.charAt(0),i=i.substring(1)+s.charAt(0),s=s.substring(1);var f=e(r,i)+e(i,s);f>=u&&(u=f,l=r,d=i,c=s);}n[t-1][1]!=l&&(l?n[t-1][1]=l:(n.splice(t-1,1),t--),n[t][1]=d,c?n[t+1][1]=c:(n.splice(t+1,1),t--));}t++;}};W.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;W.whitespaceRegex_=/\s/;W.linebreakRegex_=/[\r\n]/;W.blanklineEndRegex_=/\n\r?\n$/;W.blanklineStartRegex_=/^\r?\n\r?\n/;W.prototype.diff_cleanupEfficiency=function(n){for(var e=false,t=[],r=0,i=null,s=0,o=false,a=false,l=false,d=false;s<n.length;)n[s][0]==Y?(n[s][1].length<this.Diff_EditCost&&(l||d)?(t[r++]=s,o=l,a=d,i=n[s][1]):(r=0,i=null),l=d=false):(n[s][0]==Q?d=true:l=true,i&&(o&&a&&l&&d||i.length<this.Diff_EditCost/2&&o+a+l+d==3)&&(n.splice(t[r-1],0,new W.Diff(Q,i)),n[t[r-1]+1][0]=K,r--,i=null,o&&a?(l=d=true,r=0):(r--,s=r>0?t[r-1]:-1,l=d=false),e=true)),s++;e&&this.diff_cleanupMerge(n);};W.prototype.diff_cleanupMerge=function(n){n.push(new W.Diff(Y,""));for(var e=0,t=0,r=0,i="",s="",o;e<n.length;)switch(n[e][0]){case K:r++,s+=n[e][1],e++;break;case Q:t++,i+=n[e][1],e++;break;case Y:t+r>1?(t!==0&&r!==0&&(o=this.diff_commonPrefix(s,i),o!==0&&(e-t-r>0&&n[e-t-r-1][0]==Y?n[e-t-r-1][1]+=s.substring(0,o):(n.splice(0,0,new W.Diff(Y,s.substring(0,o))),e++),s=s.substring(o),i=i.substring(o)),o=this.diff_commonSuffix(s,i),o!==0&&(n[e][1]=s.substring(s.length-o)+n[e][1],s=s.substring(0,s.length-o),i=i.substring(0,i.length-o))),e-=t+r,n.splice(e,t+r),i.length&&(n.splice(e,0,new W.Diff(Q,i)),e++),s.length&&(n.splice(e,0,new W.Diff(K,s)),e++),e++):e!==0&&n[e-1][0]==Y?(n[e-1][1]+=n[e][1],n.splice(e,1)):e++,r=0,t=0,i="",s="";break}n[n.length-1][1]===""&&n.pop();var a=false;for(e=1;e<n.length-1;)n[e-1][0]==Y&&n[e+1][0]==Y&&(n[e][1].substring(n[e][1].length-n[e-1][1].length)==n[e-1][1]?(n[e][1]=n[e-1][1]+n[e][1].substring(0,n[e][1].length-n[e-1][1].length),n[e+1][1]=n[e-1][1]+n[e+1][1],n.splice(e-1,1),a=true):n[e][1].substring(0,n[e+1][1].length)==n[e+1][1]&&(n[e-1][1]+=n[e+1][1],n[e][1]=n[e][1].substring(n[e+1][1].length)+n[e+1][1],n.splice(e+1,1),a=true)),e++;a&&this.diff_cleanupMerge(n);};W.prototype.diff_xIndex=function(n,e){var t=0,r=0,i=0,s=0,o;for(o=0;o<n.length&&(n[o][0]!==K&&(t+=n[o][1].length),n[o][0]!==Q&&(r+=n[o][1].length),!(t>e));o++)i=t,s=r;return n.length!=o&&n[o][0]===Q?s:s+(e-i)};W.prototype.diff_prettyHtml=function(n){for(var e=[],t=/&/g,r=/</g,i=/>/g,s=/\n/g,o=0;o<n.length;o++){var a=n[o][0],l=n[o][1],d=l.replace(t,"&").replace(r,"<").replace(i,">").replace(s,"¶<br>");switch(a){case K:e[o]='<ins style="background:#e6ffe6;">'+d+"</ins>";break;case Q:e[o]='<del style="background:#ffe6e6;">'+d+"</del>";break;case Y:e[o]="<span>"+d+"</span>";break}}return e.join("")};W.prototype.diff_text1=function(n){for(var e=[],t=0;t<n.length;t++)n[t][0]!==K&&(e[t]=n[t][1]);return e.join("")};W.prototype.diff_text2=function(n){for(var e=[],t=0;t<n.length;t++)n[t][0]!==Q&&(e[t]=n[t][1]);return e.join("")};W.prototype.diff_levenshtein=function(n){for(var e=0,t=0,r=0,i=0;i<n.length;i++){var s=n[i][0],o=n[i][1];switch(s){case K:t+=o.length;break;case Q:r+=o.length;break;case Y:e+=Math.max(t,r),t=0,r=0;break}}return e+=Math.max(t,r),e};W.prototype.diff_toDelta=function(n){for(var e=[],t=0;t<n.length;t++)switch(n[t][0]){case K:e[t]="+"+encodeURI(n[t][1]);break;case Q:e[t]="-"+n[t][1].length;break;case Y:e[t]="="+n[t][1].length;break}return e.join(" ").replace(/%20/g," ")};W.prototype.diff_fromDelta=function(n,e){for(var t=[],r=0,i=0,s=e.split(/\t/g),o=0;o<s.length;o++){var a=s[o].substring(1);switch(s[o].charAt(0)){case "+":try{t[r++]=new W.Diff(K,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 d=n.substring(i,i+=l);s[o].charAt(0)=="="?t[r++]=new W.Diff(Y,d):t[r++]=new W.Diff(Q,d);break;default:if(s[o])throw new Error("Invalid diff operation in diff_fromDelta: "+s[o])}}if(i!=n.length)throw new Error("Delta length ("+i+") does not equal source text length ("+n.length+").");return t};W.prototype.match_main=function(n,e,t){if(n==null||e==null||t==null)throw new Error("Null input. (match_main)");return t=Math.max(0,Math.min(t,n.length)),n==e?0:n.length?n.substring(t,t+e.length)==e?t:this.match_bitap_(n,e,t):-1};W.prototype.match_bitap_=function(n,e,t){if(e.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");var r=this.match_alphabet_(e),i=this;function s(v,N){var k=v/e.length,x=Math.abs(t-N);return i.Match_Distance?k+x/i.Match_Distance:x?1:k}g(s,"match_bitapScore_");var o=this.Match_Threshold,a=n.indexOf(e,t);a!=-1&&(o=Math.min(s(0,a),o),a=n.lastIndexOf(e,t+e.length),a!=-1&&(o=Math.min(s(0,a),o)));var l=1<<e.length-1;a=-1;for(var d,c,u=e.length+n.length,f,h=0;h<e.length;h++){for(d=0,c=u;d<c;)s(h,t+c)<=o?d=c:u=c,c=Math.floor((u-d)/2+d);u=c;var _=Math.max(1,t-c+1),p=Math.min(t+c,n.length)+e.length,m=Array(p+2);m[p+1]=(1<<h)-1;for(var w=p;w>=_;w--){var y=r[n.charAt(w-1)];if(h===0?m[w]=(m[w+1]<<1|1)&y:m[w]=(m[w+1]<<1|1)&y|((f[w+1]|f[w])<<1|1)|f[w+1],m[w]&l){var b=s(h,w-1);if(b<=o)if(o=b,a=w-1,a>t)_=Math.max(1,2*t-a);else break}}if(s(h+1,t)>o)break;f=m;}return a};W.prototype.match_alphabet_=function(n){for(var e={},t=0;t<n.length;t++)e[n.charAt(t)]=0;for(var t=0;t<n.length;t++)e[n.charAt(t)]|=1<<n.length-t-1;return e};W.prototype.patch_addContext_=function(n,e){if(e.length!=0){if(n.start2===null)throw Error("patch not initialized");for(var t=e.substring(n.start2,n.start2+n.length1),r=0;e.indexOf(t)!=e.lastIndexOf(t)&&t.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;)r+=this.Patch_Margin,t=e.substring(n.start2-r,n.start2+n.length1+r);r+=this.Patch_Margin;var i=e.substring(n.start2-r,n.start2);i&&n.diffs.unshift(new W.Diff(Y,i));var s=e.substring(n.start2+n.length1,n.start2+n.length1+r);s&&n.diffs.push(new W.Diff(Y,s)),n.start1-=i.length,n.start2-=i.length,n.length1+=i.length+s.length,n.length2+=i.length+s.length;}};W.prototype.patch_make=function(n,e,t){var r,i;if(typeof n=="string"&&typeof e=="string"&&typeof t>"u")r=n,i=this.diff_main(r,e,true),i.length>2&&(this.diff_cleanupSemantic(i),this.diff_cleanupEfficiency(i));else if(n&&typeof n=="object"&&typeof e>"u"&&typeof t>"u")i=n,r=this.diff_text1(i);else if(typeof n=="string"&&e&&typeof e=="object"&&typeof t>"u")r=n,i=e;else if(typeof n=="string"&&typeof e=="string"&&t&&typeof t=="object")r=n,i=t;else throw new Error("Unknown call format to patch_make.");if(i.length===0)return [];for(var s=[],o=new W.patch_obj,a=0,l=0,d=0,c=r,u=r,f=0;f<i.length;f++){var h=i[f][0],_=i[f][1];switch(!a&&h!==Y&&(o.start1=l,o.start2=d),h){case K:o.diffs[a++]=i[f],o.length2+=_.length,u=u.substring(0,d)+_+u.substring(d);break;case Q:o.length1+=_.length,o.diffs[a++]=i[f],u=u.substring(0,d)+u.substring(d+_.length);break;case Y:_.length<=2*this.Patch_Margin&&a&&i.length!=f+1?(o.diffs[a++]=i[f],o.length1+=_.length,o.length2+=_.length):_.length>=2*this.Patch_Margin&&a&&(this.patch_addContext_(o,c),s.push(o),o=new W.patch_obj,a=0,c=u,l=d);break}h!==K&&(l+=_.length),h!==Q&&(d+=_.length);}return a&&(this.patch_addContext_(o,c),s.push(o)),s};W.prototype.patch_deepCopy=function(n){for(var e=[],t=0;t<n.length;t++){var r=n[t],i=new W.patch_obj;i.diffs=[];for(var s=0;s<r.diffs.length;s++)i.diffs[s]=new W.Diff(r.diffs[s][0],r.diffs[s][1]);i.start1=r.start1,i.start2=r.start2,i.length1=r.length1,i.length2=r.length2,e[t]=i;}return e};W.prototype.patch_apply=function(n,e){if(n.length==0)return [e,[]];n=this.patch_deepCopy(n);var t=this.patch_addPadding(n);e=t+e+t,this.patch_splitMax(n);for(var r=0,i=[],s=0;s<n.length;s++){var o=n[s].start2+r,a=this.diff_text1(n[s].diffs),l,d=-1;if(a.length>this.Match_MaxBits?(l=this.match_main(e,a.substring(0,this.Match_MaxBits),o),l!=-1&&(d=this.match_main(e,a.substring(a.length-this.Match_MaxBits),o+a.length-this.Match_MaxBits),(d==-1||l>=d)&&(l=-1))):l=this.match_main(e,a,o),l==-1)i[s]=false,r-=n[s].length2-n[s].length1;else {i[s]=true,r=l-o;var c;if(d==-1?c=e.substring(l,l+a.length):c=e.substring(l,d+this.Match_MaxBits),a==c)e=e.substring(0,l)+this.diff_text2(n[s].diffs)+e.substring(l+a.length);else {var u=this.diff_main(a,c,false);if(a.length>this.Match_MaxBits&&this.diff_levenshtein(u)/a.length>this.Patch_DeleteThreshold)i[s]=false;else {this.diff_cleanupSemanticLossless(u);for(var f=0,h,_=0;_<n[s].diffs.length;_++){var p=n[s].diffs[_];p[0]!==Y&&(h=this.diff_xIndex(u,f)),p[0]===K?e=e.substring(0,l+h)+p[1]+e.substring(l+h):p[0]===Q&&(e=e.substring(0,l+h)+e.substring(l+this.diff_xIndex(u,f+p[1].length))),p[0]!==Q&&(f+=p[1].length);}}}}}return e=e.substring(t.length,e.length-t.length),[e,i]};W.prototype.patch_addPadding=function(n){for(var e=this.Patch_Margin,t="",r=1;r<=e;r++)t+=String.fromCharCode(r);for(var r=0;r<n.length;r++)n[r].start1+=e,n[r].start2+=e;var i=n[0],s=i.diffs;if(s.length==0||s[0][0]!=Y)s.unshift(new W.Diff(Y,t)),i.start1-=e,i.start2-=e,i.length1+=e,i.length2+=e;else if(e>s[0][1].length){var o=e-s[0][1].length;s[0][1]=t.substring(s[0][1].length)+s[0][1],i.start1-=o,i.start2-=o,i.length1+=o,i.length2+=o;}if(i=n[n.length-1],s=i.diffs,s.length==0||s[s.length-1][0]!=Y)s.push(new W.Diff(Y,t)),i.length1+=e,i.length2+=e;else if(e>s[s.length-1][1].length){var o=e-s[s.length-1][1].length;s[s.length-1][1]+=t.substring(0,o),i.length1+=o,i.length2+=o;}return t};W.prototype.patch_splitMax=function(n){for(var e=this.Match_MaxBits,t=0;t<n.length;t++)if(!(n[t].length1<=e)){var r=n[t];n.splice(t--,1);for(var i=r.start1,s=r.start2,o="";r.diffs.length!==0;){var a=new W.patch_obj,l=true;for(a.start1=i-o.length,a.start2=s-o.length,o!==""&&(a.length1=a.length2=o.length,a.diffs.push(new W.Diff(Y,o)));r.diffs.length!==0&&a.length1<e-this.Patch_Margin;){var d=r.diffs[0][0],c=r.diffs[0][1];d===K?(a.length2+=c.length,s+=c.length,a.diffs.push(r.diffs.shift()),l=false):d===Q&&a.diffs.length==1&&a.diffs[0][0]==Y&&c.length>2*e?(a.length1+=c.length,i+=c.length,l=false,a.diffs.push(new W.Diff(d,c)),r.diffs.shift()):(c=c.substring(0,e-a.length1-this.Patch_Margin),a.length1+=c.length,i+=c.length,d===Y?(a.length2+=c.length,s+=c.length):l=false,a.diffs.push(new W.Diff(d,c)),c==r.diffs[0][1]?r.diffs.shift():r.diffs[0][1]=r.diffs[0][1].substring(c.length));}o=this.diff_text2(a.diffs),o=o.substring(o.length-this.Patch_Margin);var u=this.diff_text1(r.diffs).substring(0,this.Patch_Margin);u!==""&&(a.length1+=u.length,a.length2+=u.length,a.diffs.length!==0&&a.diffs[a.diffs.length-1][0]===Y?a.diffs[a.diffs.length-1][1]+=u:a.diffs.push(new W.Diff(Y,u))),l||n.splice(++t,0,a);}}};W.prototype.patch_toText=function(n){for(var e=[],t=0;t<n.length;t++)e[t]=n[t];return e.join("")};W.prototype.patch_fromText=function(n){var e=[];if(!n)return e;for(var t=n.split(`
|
|
3
|
+
`),r=0,i=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;r<t.length;){var s=t[r].match(i);if(!s)throw new Error("Invalid patch string: "+t[r]);var o=new W.patch_obj;for(e.push(o),o.start1=parseInt(s[1],10),s[2]===""?(o.start1--,o.length1=1):s[2]=="0"?o.length1=0:(o.start1--,o.length1=parseInt(s[2],10)),o.start2=parseInt(s[3],10),s[4]===""?(o.start2--,o.length2=1):s[4]=="0"?o.length2=0:(o.start2--,o.length2=parseInt(s[4],10)),r++;r<t.length;){var a=t[r].charAt(0);try{var l=decodeURI(t[r].substring(1));}catch{throw new Error("Illegal escape in patch_fromText: "+l)}if(a=="-")o.diffs.push(new W.Diff(Q,l));else if(a=="+")o.diffs.push(new W.Diff(K,l));else if(a==" ")o.diffs.push(new W.Diff(Y,l));else {if(a=="@")break;if(a!=="")throw new Error('Invalid patch mode "'+a+'" in: '+l)}r++;}}return e};W.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0;};W.patch_obj.prototype.toString=function(){var n,e;this.length1===0?n=this.start1+",0":this.length1==1?n=this.start1+1:n=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 t=["@@ -"+n+" +"+e+` @@
|
|
4
|
+
`],r,i=0;i<this.diffs.length;i++){switch(this.diffs[i][0]){case K:r="+";break;case Q:r="-";break;case Y:r=" ";break}t[i+1]=r+encodeURI(this.diffs[i][1])+`
|
|
5
|
+
`;}return t.join("").replace(/%20/g," ")};lt.exports=W;lt.exports.diff_match_patch=W;lt.exports.DIFF_DELETE=Q;lt.exports.DIFF_INSERT=K;lt.exports.DIFF_EQUAL=Y;});var zr=Ft(Mr());var Xo=(0, zr.createRequire)("/"),ot,Yo,Go;try{ot=Xo("worker_threads"),Yo=ot.Worker,Go=ot.isMarkedAsUntransferable;}catch{}var Z=Uint8Array,ce=Uint16Array,zn=Int32Array,Wt=new Z([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]),zt=new Z([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]),Mn=new Z([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ur=g(function(n,e){for(var t=new ce(31),r=0;r<31;++r)t[r]=e+=1<<n[r-1];for(var i=new zn(t[30]),r=1;r<30;++r)for(var s=t[r];s<t[r+1];++s)i[s]=s-t[r]<<5|r;return {b:t,r:i}},"freb"),ot=Ur(Wt,2),Hr=ot.b,jn=ot.r;Hr[28]=258,jn[258]=28;var qr=Ur(zt,0),Jo=qr.b,jr=qr.r,Bn=new ce(32768);for(J=0;J<32768;++J)Ae=(J&43690)>>1|(J&21845)<<1,Ae=(Ae&52428)>>2|(Ae&13107)<<2,Ae=(Ae&61680)>>4|(Ae&3855)<<4,Bn[J]=((Ae&65280)>>8|(Ae&255)<<8)>>1;var Ae,J,Ne=g((function(n,e,t){for(var r=n.length,i=0,s=new ce(e);i<r;++i)n[i]&&++s[n[i]-1];var o=new ce(e);for(i=1;i<e;++i)o[i]=o[i-1]+s[i-1]<<1;var a;if(t){a=new ce(1<<e);var l=15-e;for(i=0;i<r;++i)if(n[i])for(var d=i<<4|n[i],c=e-n[i],u=o[n[i]-1]++<<c,f=u|(1<<c)-1;u<=f;++u)a[Bn[u]>>l]=d;}else for(a=new ce(r),i=0;i<r;++i)n[i]&&(a[i]=Bn[o[n[i]-1]++]>>15-n[i]);return a}),"hMap"),De=new Z(288);for(J=0;J<144;++J)De[J]=8;var J;for(J=144;J<256;++J)De[J]=9;var J;for(J=256;J<280;++J)De[J]=7;var J;for(J=280;J<288;++J)De[J]=8;var J,xt=new Z(32);for(J=0;J<32;++J)xt[J]=5;var J,Vo=Ne(De,9,0),Qo=Ne(De,9,1),Ko=Ne(xt,5,0),Zo=Ne(xt,5,1),In=g(function(n){for(var e=n[0],t=1;t<n.length;++t)n[t]>e&&(e=n[t]);return e},"max"),me=g(function(n,e,t){var r=e/8|0;return (n[r]|n[r+1]<<8)>>(e&7)&t},"bits"),On=g(function(n,e){var t=e/8|0;return (n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},"bits16"),Un=g(function(n){return (n+7)/8|0},"shft"),Nt=g(function(n,e,t){return (e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length),new Z(n.subarray(e,t))},"slc");var ea=["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"],se=g(function(n,e,t){var r=new Error(e||ea[n]);if(r.code=n,Error.captureStackTrace&&Error.captureStackTrace(r,se),!t)throw r;return r},"err"),ta=g(function(n,e,t,r){var i=n.length,s=r?r.length:0;if(!i||e.f&&!e.l)return t||new Z(0);var o=!t,a=o||e.i!=2,l=e.i;o&&(t=new Z(i*3));var d=g(function(Oe){var st=t.length;if(Oe>st){var he=new Z(Math.max(st*2,Oe));he.set(t),t=he;}},"cbuf"),c=e.f||0,u=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=me(n,u,1);var y=me(n,u+1,3);if(u+=3,y)if(y==1)h=Qo,_=Zo,p=9,m=5;else if(y==2){var k=me(n,u,31)+257,x=me(n,u+10,15)+4,P=k+me(n,u+5,31)+1;u+=14;for(var E=new Z(P),T=new Z(19),I=0;I<x;++I)T[Mn[I]]=me(n,u+I*3,7);u+=x*3;for(var D=In(T),F=(1<<D)-1,M=Ne(T,D,1),I=0;I<P;){var B=M[me(n,u,F)];u+=B&15;var b=B>>4;if(b<16)E[I++]=b;else {var j=0,C=0;for(b==16?(C=3+me(n,u,3),u+=2,j=E[I-1]):b==17?(C=3+me(n,u,7),u+=3):b==18&&(C=11+me(n,u,127),u+=7);C--;)E[I++]=j;}}var S=E.subarray(0,k),A=E.subarray(k);p=In(S),m=In(A),h=Ne(S,p,1),_=Ne(A,m,1);}else se(1);else {var b=Un(u)+4,v=n[b-4]|n[b-3]<<8,N=b+v;if(N>i){l&&se(0);break}a&&d(f+v),t.set(n.subarray(b,N),f),e.b=f+=v,e.p=u=N*8,e.f=c;continue}if(u>w){l&&se(0);break}}a&&d(f+131072);for(var O=(1<<p)-1,L=(1<<m)-1,H=u;;H=u){var j=h[On(n,u)&O],q=j>>4;if(u+=j&15,u>w){l&&se(0);break}if(j||se(2),q<256)t[f++]=q;else if(q==256){H=u,h=null;break}else {var z=q-254;if(q>264){var I=q-257,U=Wt[I];z=me(n,u,(1<<U)-1)+Hr[I],u+=U;}var X=_[On(n,u)&L],te=X>>4;X||se(3),u+=X&15;var A=Jo[te];if(te>3){var U=zt[te];A+=On(n,u)&(1<<U)-1,u+=U;}if(u>w){l&&se(0);break}a&&d(f+131072);var V=f+z;if(f<A){var fe=s-A,it=Math.min(A,V);for(fe+f<0&&se(3);f<it;++f)t[f]=r[fe+f];}for(;f<V;++f)t[f]=t[f-A];}}e.l=h,e.p=H,e.b=f,e.f=c,h&&(c=1,e.m=p,e.d=_,e.n=m);}while(!c);return f!=t.length&&o?Nt(t,0,f):t.subarray(0,f)},"inflt"),Pe=g(function(n,e,t){t<<=e&7;var r=e/8|0;n[r]|=t,n[r+1]|=t>>8;},"wbits"),vt=g(function(n,e,t){t<<=e&7;var r=e/8|0;n[r]|=t,n[r+1]|=t>>8,n[r+2]|=t>>16;},"wbits16"),Dn=g(function(n,e){for(var t=[],r=0;r<n.length;++r)n[r]&&t.push({s:r,f:n[r]});var i=t.length,s=t.slice();if(!i)return {t:Yr,l:0};if(i==1){var o=new Z(t[0].s+1);return o[t[0].s]=1,{t:o,l:1}}t.sort(function(N,k){return N.f-k.f}),t.push({s:-1,f:25001});var a=t[0],l=t[1],d=0,c=1,u=2;for(t[0]={s:-1,f:a.f+l.f,l:a,r:l};c!=i-1;)a=t[t[d].f<t[u].f?d++:u++],l=t[d!=c&&t[d].f<t[u].f?d++:u++],t[c++]={s:-1,f:a.f+l.f,l:a,r:l};for(var f=s[0].s,r=1;r<i;++r)s[r].s>f&&(f=s[r].s);var h=new ce(f+1),_=Fn(t[c-1],h,0);if(_>e){var r=0,p=0,m=_-e,w=1<<m;for(s.sort(function(k,x){return h[x.s]-h[k.s]||k.f-x.f});r<i;++r){var y=s[r].s;if(h[y]>e)p+=w-(1<<_-h[y]),h[y]=e;else break}for(p>>=m;p>0;){var b=s[r].s;h[b]<e?p-=1<<e-h[b]++-1:++r;}for(;r>=0&&p;--r){var v=s[r].s;h[v]==e&&(--h[v],++p);}_=e;}return {t:new Z(h),l:_}},"hTree"),Fn=g(function(n,e,t){return n.s==-1?Math.max(Fn(n.l,e,t+1),Fn(n.r,e,t+1)):e[n.s]=t},"ln"),Br=g(function(n){for(var e=n.length;e&&!n[--e];);for(var t=new ce(++e),r=0,i=n[0],s=1,o=g(function(l){t[r++]=l;},"w"),a=1;a<=e;++a)if(n[a]==i&&a!=e)++s;else {if(!i&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0);}else if(s>3){for(o(i),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0);}for(;s--;)o(i);s=1,i=n[a];}return {c:t.subarray(0,r),n:e}},"lc"),bt=g(function(n,e){for(var t=0,r=0;r<e.length;++r)t+=n[r]*e[r];return t},"clen"),Xr=g(function(n,e,t){var r=t.length,i=Un(e+2);n[i]=r&255,n[i+1]=r>>8,n[i+2]=n[i]^255,n[i+3]=n[i+1]^255;for(var s=0;s<r;++s)n[i+s+4]=t[s];return (i+4+r)*8},"wfblk"),Fr=g(function(n,e,t,r,i,s,o,a,l,d,c){Pe(e,c++,t),++i[256];for(var u=Dn(i,15),f=u.t,h=u.l,_=Dn(s,15),p=_.t,m=_.l,w=Br(f),y=w.c,b=w.n,v=Br(p),N=v.c,k=v.n,x=new ce(19),P=0;P<y.length;++P)++x[y[P]&31];for(var P=0;P<N.length;++P)++x[N[P]&31];for(var E=Dn(x,7),T=E.t,I=E.l,D=19;D>4&&!T[Mn[D-1]];--D);var F=d+5<<3,M=bt(i,De)+bt(s,xt)+o,B=bt(i,f)+bt(s,p)+o+14+3*D+bt(x,T)+2*x[16]+3*x[17]+7*x[18];if(l>=0&&F<=M&&F<=B)return Xr(e,c,n.subarray(l,l+d));var j,C,S,A;if(Pe(e,c,1+(B<M)),c+=2,B<M){j=Ne(f,h,0),C=f,S=Ne(p,m,0),A=p;var O=Ne(T,I,0);Pe(e,c,b-257),Pe(e,c+5,k-1),Pe(e,c+10,D-4),c+=14;for(var P=0;P<D;++P)Pe(e,c+3*P,T[Mn[P]]);c+=3*D;for(var L=[y,N],H=0;H<2;++H)for(var q=L[H],P=0;P<q.length;++P){var z=q[P]&31;Pe(e,c,O[z]),c+=T[z],z>15&&(Pe(e,c,q[P]>>5&127),c+=q[P]>>12);}}else j=Vo,C=De,S=Ko,A=xt;for(var P=0;P<a;++P){var U=r[P];if(U>255){var z=U>>18&31;vt(e,c,j[z+257]),c+=C[z+257],z>7&&(Pe(e,c,U>>23&31),c+=Wt[z]);var X=U&31;vt(e,c,S[X]),c+=A[X],X>3&&(vt(e,c,U>>5&8191),c+=zt[X]);}else vt(e,c,j[U]),c+=C[U];}return vt(e,c,j[256]),c+C[256]},"wblk"),na=new zn([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Yr=new Z(0),ra=g(function(n,e,t,r,i,s){var o=s.z||n.length,a=new Z(r+o+5*(1+Math.ceil(o/7e3))+i),l=a.subarray(r,a.length-i),d=s.l,c=(s.r||0)&7;if(e){c&&(l[0]=s.r>>3);for(var u=na[e-1],f=u>>13,h=u&8191,_=(1<<t)-1,p=s.p||new ce(32768),m=s.h||new ce(_+1),w=Math.ceil(t/3),y=2*w,b=g(function(Ge){return (n[Ge]^n[Ge+1]<<w^n[Ge+2]<<y)&_},"hsh"),v=new zn(25e3),N=new ce(288),k=new ce(32),x=0,P=0,E=s.i||0,T=0,I=s.w||0,D=0;E+2<o;++E){var F=b(E),M=E&32767,B=m[F];if(p[M]=B,m[F]=M,I<=E){var j=o-E;if((x>7e3||T>24576)&&(j>423||!d)){c=Fr(n,l,0,v,N,k,P,T,D,E-D,c),T=x=P=0,D=E;for(var C=0;C<286;++C)N[C]=0;for(var C=0;C<30;++C)k[C]=0;}var S=2,A=0,O=h,L=M-B&32767;if(j>2&&F==b(E-L))for(var H=Math.min(f,j)-1,q=Math.min(32767,E),z=Math.min(258,j);L<=q&&--O&&M!=B;){if(n[E+S]==n[E+S-L]){for(var U=0;U<z&&n[E+U]==n[E+U-L];++U);if(U>S){if(S=U,A=L,U>H)break;for(var X=Math.min(L,U-2),te=0,C=0;C<X;++C){var V=E-L+C&32767,fe=p[V],it=V-fe&32767;it>te&&(te=it,B=V);}}}M=B,B=p[M],L+=M-B&32767;}if(A){v[T++]=268435456|jn[S]<<18|jr[A];var Oe=jn[S]&31,st=jr[A]&31;P+=Wt[Oe]+zt[st],++N[257+Oe],++k[st],I=E+S,++x;}else v[T++]=n[E],++N[n[E]];}}for(E=Math.max(E,I);E<o;++E)v[T++]=n[E],++N[n[E]];c=Fr(n,l,d,v,N,k,P,T,D,E-D,c),d||(s.r=c&7|l[c/8|0]<<3,c-=7,s.h=m,s.p=p,s.i=E,s.w=I);}else {for(var E=s.w||0;E<o+d;E+=65535){var he=E+65535;he>=o&&(l[c/8|0]=d,he=o),c=Xr(l,c+1,n.subarray(E,he));}s.i=o;}return Nt(a,0,r+Un(c)+i)},"dflt"),ia=(function(){for(var n=new Int32Array(256),e=0;e<256;++e){for(var t=e,r=9;--r;)t=(t&1&&-306674912)^t>>>1;n[e]=t;}return n})(),sa=g(function(){var n=-1;return {p:g(function(e){for(var t=n,r=0;r<e.length;++r)t=ia[t&255^e[r]]^t>>>8;n=t;},"p"),d:g(function(){return ~n},"d")}},"crc");var oa=g(function(n,e,t,r,i){if(!i&&(i={l:1},e.dictionary)){var s=e.dictionary.subarray(-32768),o=new Z(s.length+n.length);o.set(s),o.set(n,s.length),n=o,i.w=s.length;}return ra(n,e.level==null?6:e.level,e.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(n.length)))*1.5):20:12+e.mem,t,r,i)},"dopt"),Gr=g(function(n,e){var t={};for(var r in n)t[r]=n[r];for(var r in e)t[r]=e[r];return t},"mrg");var xe=g(function(n,e){return n[e]|n[e+1]<<8},"b2"),pe=g(function(n,e){return (n[e]|n[e+1]<<8|n[e+2]<<16|n[e+3]<<24)>>>0},"b4"),Rn=g(function(n,e){return pe(n,e)+pe(n,e+4)*4294967296},"b8"),re=g(function(n,e,t){for(;t;++e)n[e]=t,t>>>=8;},"wbytes");function aa(n,e){return oa(n,e||{},0,0)}g(aa,"deflateSync");function la(n,e){return ta(n,{i:2},e&&e.out,e&&e.dictionary)}g(la,"inflateSync");var Jr=g(function(n,e,t,r){for(var i in n){var s=n[i],o=e+i,a=r;Array.isArray(s)&&(a=Gr(r,s[1]),s=s[0]),ArrayBuffer.isView(s)?t[o]=[s,a]:(t[o+="/"]=[new Z(0),a],Jr(s,o,t,r));}},"fltn"),Lr=typeof TextEncoder<"u"&&new TextEncoder,Ln=typeof TextDecoder<"u"&&new TextDecoder,ca=0;try{Ln.decode(Yr,{stream:!0}),ca=1;}catch{}var da=g(function(n){for(var e="",t=0;;){var r=n[t++],i=(r>127)+(r>223)+(r>239);if(t+i>n.length)return {s:e,r:Nt(n,t-1)};i?i==3?(r=((r&15)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63)-65536,e+=String.fromCharCode(55296|r>>10,56320|r&1023)):i&1?e+=String.fromCharCode((r&31)<<6|n[t++]&63):e+=String.fromCharCode((r&15)<<12|(n[t++]&63)<<6|n[t++]&63):e+=String.fromCharCode(r);}},"dutf8");function Lt(n,e){if(e){for(var t=new Z(n.length),r=0;r<n.length;++r)t[r]=n.charCodeAt(r);return t}if(Lr)return Lr.encode(n);for(var i=n.length,s=new Z(n.length+(n.length>>1)),o=0,a=g(function(c){s[o++]=c;},"w"),r=0;r<i;++r){if(o+5>s.length){var l=new Z(o+8+(i-r<<1));l.set(s),s=l;}var d=n.charCodeAt(r);d<128||e?a(d):d<2048?(a(192|d>>6),a(128|d&63)):d>55295&&d<57344?(d=65536+(d&1047552)|n.charCodeAt(++r)&1023,a(240|d>>18),a(128|d>>12&63),a(128|d>>6&63),a(128|d&63)):(a(224|d>>12),a(128|d>>6&63),a(128|d&63));}return Nt(s,0,o)}g(Lt,"strToU8");function Je(n,e){if(e){for(var t="",r=0;r<n.length;r+=16384)t+=String.fromCharCode.apply(null,n.subarray(r,r+16384));return t}else {if(Ln)return Ln.decode(n);var i=da(n),s=i.s,t=i.r;return t.length&&se(8),s}}g(Je,"strFromU8");var ua=g(function(n,e){return e+30+xe(n,e+26)+xe(n,e+28)},"slzh"),fa=g(function(n,e,t){var r=xe(n,e+28),i=xe(n,e+30),s=Je(n.subarray(e+46,e+46+r),!(xe(n,e+8)&2048)),o=e+46+r,a=ha(n,o,i,t,pe(n,e+20),pe(n,e+24),pe(n,e+42)),l=a[0],d=a[1],c=a[2];return [xe(n,e+10),l,d,s,o+i+xe(n,e+32),c]},"zh"),ha=g(function(n,e,t,r,i,s,o){var a=i==4294967295,l=s==4294967295,d=o==4294967295,c=e+t,u=a+l+d;if(r&&u){for(;e+4<c;e+=4+xe(n,e+2))if(xe(n,e)==1)return [a?Rn(n,e+4+8*l):i,l?Rn(n,e+4):s,d?Rn(n,e+4+8*(l+a)):o,1];r<2&&se(13);}return [i,s,o,0]},"z64hs"),Wn=g(function(n){var e=0;if(n)for(var t in n){var r=n[t].length;r>65535&&se(9),e+=r+4;}return e},"exfl"),Wr=g(function(n,e,t,r,i,s,o,a){var l=r.length,d=t.extra,c=a&&a.length,u=Wn(d);re(n,e,o!=null?33639248:67324752),e+=4,o!=null&&(n[e++]=20,n[e++]=t.os),n[e]=20,e+=2,n[e++]=t.flag<<1|(s<0&&8),n[e++]=i&&8,n[e++]=t.compression&255,n[e++]=t.compression>>8;var f=new Date(t.mtime==null?Date.now():t.mtime),h=f.getFullYear()-1980;if((h<0||h>119)&&se(10),re(n,e,h<<25|f.getMonth()+1<<21|f.getDate()<<16|f.getHours()<<11|f.getMinutes()<<5|f.getSeconds()>>1),e+=4,s!=-1&&(re(n,e,t.crc),re(n,e+4,s<0?-s-2:s),re(n,e+8,t.size)),re(n,e+12,l),re(n,e+14,u),e+=16,o!=null&&(re(n,e,c),re(n,e+6,t.attrs),re(n,e+10,o),e+=14),n.set(r,e),e+=l,u)for(var _ in d){var p=d[_],m=p.length;re(n,e,+_),re(n,e+2,m),n.set(p,e+4),e+=4+m;}return c&&(n.set(a,e),e+=c),e},"wzh"),pa=g(function(n,e,t,r,i){re(n,e,101010256),re(n,e+8,t),re(n,e+10,t),re(n,e+12,r),re(n,e+16,i);},"wzf");function Vr(n,e){e||(e={});var t={},r=[];Jr(n,"",t,e);var i=0,s=0;for(var o in t){var a=t[o],l=a[0],d=a[1],c=d.level==0?0:8,u=Lt(o),f=u.length,h=d.comment,_=h&&Lt(h),p=_&&_.length,m=Wn(d.extra);f>65535&&se(11);var w=c?aa(l,d):l,y=w.length,b=sa();b.p(l),r.push(Gr(d,{size:l.length,crc:b.d(),c:w,f:u,m:_,u:f!=o.length||_&&h.length!=p,o:i,compression:c})),i+=30+f+m+y,s+=76+2*(f+m)+(p||0)+y;}for(var v=new Z(s+22),N=i,k=s-i,x=0;x<r.length;++x){var u=r[x];Wr(v,u.o,u,u.f,u.u,u.c.length);var P=30+u.f.length+Wn(u.extra);v.set(u.c,u.o+P),Wr(v,i,u,u.f,u.u,u.c.length,u.o,u.m),i+=16+P+(u.m?u.m.length:0);}return pa(v,i,r.length,k,N),v}g(Vr,"zipSync");function at(n,e){for(var t={},r=n.length-22;pe(n,r)!=101010256;--r)(!r||n.length-r>65558)&&se(13);var i=xe(n,r+8);if(!i)return {};var s=pe(n,r+16),o=pe(n,r-20)==117853008;if(o){var a=pe(n,r-12);o=pe(n,a)==101075792,o&&(i=pe(n,a+32),s=pe(n,a+48));}for(var l=e&&e.filter,d=0;d<i;++d){var c=fa(n,s,o),u=c[0],f=c[1],h=c[2],_=c[3],p=c[4],m=c[5],w=ua(n,m);s=p,(!l||l({name:_,size:f,originalSize:h,compression:u}))&&(u?u==8?t[_]=la(n.subarray(w,w+f),{out:new Z(h)}):se(14,"unknown compression type "+u):t[_]=Nt(n,w,w+f));}return t}g(at,"unzipSync");var us=Ft(Ut()),Ss=Ft(Ut());var br=Ft(Ut());var Qe=1,lr=3,cr=4,Ui=8,dr=9,Hi=class{static{g(this,"FastNode");}nodeType=0;parentNode=null;ownerDocument=null;get firstChild(){return null}get lastChild(){return null}get nextSibling(){let n=this.parentNode;if(!n)return null;let e=n.childNodes,t=e.indexOf(this);return t>=0&&t+1<e.length?e[t+1]:null}get previousSibling(){let n=this.parentNode;if(!n)return null;let e=n.childNodes,t=e.indexOf(this);return t>0?e[t-1]:null}},Rt=class qi extends Hi{static{g(this,"_FastText");}constructor(e){super(),this.data=e;}data;nodeType=lr;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 t=new qi(this.data);return t.ownerDocument=this.ownerDocument,t}toString(){return un(this)}},Xi=class Yi extends Rt{static{g(this,"_FastComment");}nodeType=Ui;cloneNode(e){let t=new Yi(this.data);return t.ownerDocument=this.ownerDocument,t}},_a=class Gi extends Rt{static{g(this,"_FastCData");}nodeType=cr;cloneNode(e){let t=new Gi(this.data);return t.ownerDocument=this.ownerDocument,t}},Ji=class extends Hi{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 n=this.nodeType===dr?this:this.ownerDocument;n&&n._inc++;}appendChild(n){return n.parentNode&&n.parentNode.removeChild(n),this.childNodes.push(n),n.parentNode=this,this.bump(),n}insertBefore(n,e){if(!e)return this.appendChild(n);if(this.childNodes.indexOf(e)<0)throw new Error("insertBefore: reference node not a child");n.parentNode&&n.parentNode.removeChild(n);let r=this.childNodes.indexOf(e);return this.childNodes.splice(r,0,n),n.parentNode=this,this.bump(),n}removeChild(n){let e=this.childNodes.indexOf(n);if(e<0)throw new Error("removeChild: node is not a child");return this.childNodes.splice(e,1),n.parentNode=null,this.bump(),n}replaceChild(n,e){if(this.childNodes.indexOf(e)<0)throw new Error("replaceChild: node is not a child");n.parentNode&&n.parentNode.removeChild(n);let r=this.childNodes.indexOf(e);return this.childNodes[r]=n,n.parentNode=this,e.parentNode=null,this.bump(),e}getElementsByTagName(n){let e=[],t=n==="*",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===Qe){let s=i;(t||s.tagName===n)&&e.push(s);for(let o=s.childNodes.length-1;o>=0;o--)r.push(s.childNodes[o]);}}return e}},Vi=class Qi extends Ji{static{g(this,"_FastElement");}constructor(e){super(),this.tagName=e;}tagName;nodeType=Qe;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(([t,r])=>({nodeType:2,name:t,value:r,nodeName:t,nodeValue:r,localName:t.indexOf(":")<0?t:t.slice(t.indexOf(":")+1),prefix:t.indexOf(":")<0?null:t.slice(0,t.indexOf(":")),ownerElement:this}));return e.item=t=>e[t]??null,e}toString(){return un(this)}getAttribute(e){let t=this.attrs;for(let r=0;r<t.length;r++)if(t[r][0]===e)return t[r][1];return null}hasAttribute(e){return this.getAttribute(e)!==null}setAttribute(e,t){let r=this.attrs;for(let i=0;i<r.length;i++)if(r[i][0]===e){r[i][1]=String(t),this.ownerDocument&&this.ownerDocument._inc++;return}r.push([e,String(t)]),this.ownerDocument&&this.ownerDocument._inc++;}removeAttribute(e){let t=this.attrs;for(let r=0;r<t.length;r++)if(t[r][0]===e){t.splice(r,1),this.ownerDocument&&this.ownerDocument._inc++;return}}get textContent(){let e="",t=[];for(let r=this.childNodes.length-1;r>=0;r--)t.push(this.childNodes[r]);for(;t.length;){let r=t.pop();if(r.nodeType===lr||r.nodeType===cr)e+=r.data;else if(r.nodeType===Qe){let i=r;for(let s=i.childNodes.length-1;s>=0;s--)t.push(i.childNodes[s]);}}return e}set textContent(e){for(let t of this.childNodes)t.parentNode=null;if(this.childNodes.length=0,e!==""&&e!==null&&e!==void 0){let t=new Rt(String(e));t.ownerDocument=this.ownerDocument,t.parentNode=this,this.childNodes.push(t);}this.ownerDocument&&this.ownerDocument._inc++;}cloneNode(e=false){let t=new Qi(this.tagName);if(t.ownerDocument=this.ownerDocument,this.attrs.length&&(t.attrs=this.attrs.map(([r,i])=>[r,i])),e)for(let r of this.childNodes){let i=r.cloneNode(true);i.parentNode=t,t.childNodes.push(i);}return t}},ma=class extends Ji{static{g(this,"FastDocument");}nodeType=dr;_inc=1;documentElement=null;get nodeName(){return "#document"}createElement(n){let e=new Vi(n);return e.ownerDocument=this,e}createElementNS(n,e){return this.createElement(e)}createTextNode(n){let e=new Rt(String(n));return e.ownerDocument=this,e}createComment(n){let e=new Xi(String(n));return e.ownerDocument=this,e}toString(){return un(this)}appendChild(n){let e=super.appendChild(n);return n.nodeType===Qe&&(this.documentElement=n),e}replaceChild(n,e){let t=super.replaceChild(n,e);return e===this.documentElement&&n.nodeType===Qe&&(this.documentElement=n),t}},ga=/&(?:amp|lt|gt|quot|apos|#x?[0-9a-fA-F]+);/g;function Ki(n){return n.indexOf("&")<0?n:n.replace(ga,e=>{switch(e){case "&":return "&";case "<":return "<";case ">":return ">";case """:return '"';case "'":return "'";default:{let t=e.slice(2,-1),r=t[0]==="x"||t[0]==="X"?parseInt(t.slice(1),16):parseInt(t,10);return Number.isFinite(r)?String.fromCodePoint(r):e}}})}g(Ki,"decodeEntities");function Qn(n){return n.indexOf("\r")<0?n:n.replace(/\r\n?/g,`
|
|
6
|
+
`)}g(Qn,"normalizeLineEnds");function wa(n){let e=Qn(n),t=/[\n\t]/.test(e)?e.replace(/[\n\t]/g," "):e;return Ki(t)}g(wa,"normalizeAttrValue");var Hn=new Set([32,9,10,13]);function ya(n){n.charCodeAt(0)===65279&&(n=n.slice(1));let e=new ma,t=e,r=0,i=n.length,s=false;for(;r<i;){let o=n.indexOf("<",r);if(o<0){if(t!==e)throw new Error("Unexpected end of XML");if(/\S/.test(n.slice(r)))throw new Error("Content after document root");break}if(o>r&&t!==e){let u=n.slice(r,o),f=new Rt(Ki(Qn(u)));f.ownerDocument=e,f.parentNode=t,t.childNodes.push(f);}else if(o>r&&/\S/.test(n.slice(r,o)))throw new Error("Text content outside document root");r=o+1;let a=n.charCodeAt(r);if(a===47){let u=n.indexOf(">",r);if(u<0)throw new Error("Unterminated close tag");let f=n.slice(r+1,u).trim();if(t.nodeType!==Qe||t.tagName!==f)throw new Error(`Mismatched close tag </${f}>`);t=t.parentNode??e,r=u+1;continue}if(a===63){let u=n.indexOf("?>",r);if(u<0)throw new Error("Unterminated processing instruction");r=u+2;continue}if(a===33){if(n.startsWith("!--",r)){let f=n.indexOf("-->",r+3);if(f<0)throw new Error("Unterminated comment");let h=new Xi(n.slice(r+3,f));h.ownerDocument=e,t!==e&&(h.parentNode=t,t.childNodes.push(h)),r=f+3;continue}if(n.startsWith("![CDATA[",r)){let f=n.indexOf("]]>",r+8);if(f<0)throw new Error("Unterminated CDATA section");if(t!==e){let h=new _a(Qn(n.slice(r+8,f)));h.ownerDocument=e,h.parentNode=t,t.childNodes.push(h);}r=f+3;continue}let u=n.indexOf(">",r);if(u<0)throw new Error("Unterminated declaration");r=u+1;continue}let l=r;for(;l<i;){let u=n.charCodeAt(l);if(Hn.has(u)||u===62||u===47)break;l++;}if(l===r)throw new Error(`Invalid tag at offset ${o}`);let d=new Vi(n.slice(r,l));if(d.ownerDocument=e,t===e){if(s)throw new Error("Multiple document roots");s=true,e.childNodes.push(d),d.parentNode=e,e.documentElement=d;}else d.parentNode=t,t.childNodes.push(d);r=l;let c=false;for(;r<i;){let u=n.charCodeAt(r);if(u===62){r++;break}if(u===47){if(n.charCodeAt(r+1)!==62)throw new Error("Malformed self-close");c=true,r+=2;break}if(Hn.has(u)){r++;continue}let f=n.indexOf("=",r);if(f<0)throw new Error("Malformed attribute");let h=n.slice(r,f).trim(),_=f+1;for(;_<i&&Hn.has(n.charCodeAt(_));)_++;let p=n.charCodeAt(_);if(p!==34&&p!==39)throw new Error("Unquoted attribute value");let m=n.indexOf(String.fromCharCode(p),_+1);if(m<0)throw new Error("Unterminated attribute value");d.attrs.push([h,wa(n.slice(_+1,m))]),r=m+1;}c||(t=d);}if(t!==e)throw new Error("Unclosed element at end of document");if(!e.documentElement)throw new Error("Empty XML document");return e}g(ya,"parseFastXml");function va(n){return /[&<>\r]/.test(n)?n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\r/g," "):n}g(va,"escText");function ba(n){return /[&<>"\t\n\r]/.test(n)?n.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/\t/g,"	").replace(/\n/g," ").replace(/\r/g," "):n}g(ba,"escAttr");function un(n){let e=[],t=g(r=>{switch(r.nodeType){case Qe:{let i=r;e.push("<",i.tagName);for(let s=0;s<i.attrs.length;s++){let[o,a]=i.attrs[s];e.push(" ",o,'="',ba(a),'"');}if(i.childNodes.length===0)e.push("/>");else {e.push(">");for(let s of i.childNodes)t(s);e.push("</",i.tagName,">");}break}case lr:e.push(va(r.data));break;case cr:e.push("<![CDATA[",r.data,"]]>");break;case Ui:e.push("<!--",r.data,"-->");break;case dr:for(let i of r.childNodes)t(i);break}},"write");return t(n),e.join("")}g(un,"serializeFastXml");function $(n,e){for(let t=0;t<n.childNodes.length;t++){let r=n.childNodes[t];if(r.nodeType===1&&r.tagName===e)return r}return null}g($,"findChild");function fn(n,e){let t=[];for(let r=0;r<n.childNodes.length;r++){let i=n.childNodes[r];i.nodeType===1&&i.tagName===e&&t.push(i);}return t}g(fn,"findChildren");function Zi(n,e){let t=typeof e=="string"?[e]:e,r=[],i=g((s,o)=>{if(!(o>xa))for(let a=0;a<s.childNodes.length;a++){let l=s.childNodes[a];if(l.nodeType!==1)continue;let d=l;t.includes(d.tagName)?r.push(d):(d.tagName==="w:sdt"||d.tagName==="w:sdtContent")&&i(d,o+1);}},"visit");return i(n,0),r}g(Zi,"findChildrenSdtTransparent");var xa=100;function R(n,e){return Array.from(n.getElementsByTagName(e))}g(R,"findAllDescendants");function Ke(n){return n.startsWith("\uFEFF")&&(n=n.slice(1)),ya(n)}g(Ke,"parseXml");function Qr(n){let e=un(n),r=/<([a-zA-Z0-9_:]+)(\s+[^>]+?)(>|\/>)/.exec(e);if(r&&!r[1].startsWith("?")){let i=r.index,s=e.substring(0,i);if(!s.includes("<")||s.trim().startsWith("<?xml")&&(s.match(/</g)||[]).length===1){let a=r[0],l=`<${r[1]}`,d=r[2],c=r[3],u=/([a-zA-Z0-9_:]+)\s*=\s*(["'])(.*?)\2/g,f=[],h;for(;(h=u.exec(d))!==null;)f.push(h[0].trim());f.sort((p,m)=>{let w=p.split("=")[0].trim(),y=m.split("=")[0].trim(),b=w.startsWith("xmlns"),v=y.startsWith("xmlns");return b&&!v?-1:!b&&v?1:w<y?-1:w>y?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(Qr,"serializeXml");var on=1,ur=2147483647;function fr(n){return ((n&ur)>>>0||on).toString(16).toUpperCase().padStart(8,"0")}g(fr,"toLongHexNumber");function Ht(){let n=ur-on+1;return fr(on+Math.floor(Math.random()*n))}g(Ht,"generateLongHexNumber");function Kr(n){if(!/^[0-9A-Fa-f]{1,8}$/.test(n))return false;let e=parseInt(n,16);return e>=on&&e<=ur}g(Kr,"isWordReadableLongHexNumber");var Kn="__adeu_wp_index_cache",es="__adeu_clean_inc";function hn(n){return typeof n._inc=="number"?n._inc:null}g(hn,"docInc");function $t(n){let e=hn(n);e!==null&&(n[es]=e);}g($t,"markPartClean");function hr(n){let e=hn(n);return e!==null&&n[es]===e}g(hr,"isPartClean");function Na(n){let e=new Map,t=n.documentElement;if(!t)return e;let r=0;t.nodeType===1&&t.tagName==="w:p"&&e.set(t,r++);let i=[t],s=[0];for(;i.length;){let o=i.length-1,a=i[o].childNodes;if(!a||s[o]>=a.length){i.pop(),s.pop();continue}let l=a[s[o]++];l.nodeType===1&&(l.tagName==="w:p"&&e.set(l,r++),i.push(l),s.push(0));}return e}g(Na,"buildWpIndexMap");function ka(n,e){let t=hn(n),r=n[Kn];(!r||t===null||r.inc!==t||!r.map.has(e))&&(r={inc:t??NaN,map:Na(n)},n[Kn]=r);let i=r.map.get(e);return i===void 0?-1:i}g(ka,"wpDocumentOrderIndex");function Ca(n){let e=n[Kn],t=hn(n);e&&t!==null&&(e.inc=t);}g(Ca,"resyncAfterOwnAttributeMutation");function ts(n,e){let t=n.getElementsByTagName("w:p")[0],r=t?t.getAttribute("w14:paraId"):null;if(!r&&e){let i=n.ownerDocument,s=hr(i);t||(t=i.createElement("w:p"),n.appendChild(t));let o=ka(i,t),a=2166136261,l=`fallback-paraId-${o}`;for(let d=0;d<l.length;d++)a^=l.charCodeAt(d),a+=(a<<1)+(a<<4)+(a<<7)+(a<<8)+(a<<24);r=fr(a),t.setAttribute("w14:paraId",r),Ca(i),s&&$t(i);}return {paraId:r,firstP:t}}g(ts,"resolve_cell_anchor");var Kt=class{static{g(this,"Relationship");}constructor(n,e,t,r){this.id=n,this.type=e,this.target=t,this.isExternal=r;}id;type;target;isExternal},ns=class{static{g(this,"Part");}constructor(n,e,t,r){this.partname=n,this.blob=e,this.contentType=r,this._element=t;}partname;blob;contentType;rels=new Map;_element;package;addRelationship(n,e,t,r=false){if(this.rels.set(n,new Kt(n,e,t,r)),this.partname.endsWith(".rels")){let i=this._element.ownerDocument;if(i){let s=i.createElementNS("http://schemas.openxmlformats.org/package/2006/relationships","Relationship");s.setAttribute("Id",n),s.setAttribute("Type",e),s.setAttribute("Target",t),r&&s.setAttribute("TargetMode","External"),this._element.appendChild(s);}}}},Ea=class{static{g(this,"DocxPackage");}constructor(n){this.unzipped=n;}unzipped;parts=[];mainDocumentPart;getPartByPath(n){let e=n.startsWith("/")?n.substring(1):n;return this.parts.find(t=>t.partname===e||t.partname==="/"+e)}nextPartname(n){let e=1;for(;;){let t=n.replace("%d",e===1?"":e.toString());if(!this.getPartByPath(t))return t;e++;}}addPart(n,e,t){let r=Ke(t),i=new ns(n,t,r.documentElement,e);i.package=this,this.parts.push(i);let s=this.getPartByPath("[Content_Types].xml");if(s){let o=s._element.ownerDocument;if(o){let a=o.createElement("Override");a.setAttribute("PartName",n),a.setAttribute("ContentType",e),s._element.appendChild(a);}}return i}getOrCreateRelsPart(n){let e=n.split("/"),t=e.pop(),r=e.join("/")+"/_rels/"+t+".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}},ae=class Zt{static{g(this,"_DocumentObject");}constructor(e,t){this.pkg=e,this.part=t;}pkg;part;settings={oddAndEvenPagesHeaderFooter:false};sections=[];get element(){return $(this.part._element,"w:body")||this.part._element}static async load(e,t){let r=e instanceof Uint8Array?e:new Uint8Array(e),i=at(r),s=new Ea(i),o=i["[Content_Types].xml"],a={};if(o){let _=Ke(Je(o)),p=R(_.documentElement,"Override");for(let m of p)a[m.getAttribute("PartName")||""]=m.getAttribute("ContentType")||"";}let l=t?.onPart,d=Math.max(1,t?.partTickEvery??200),c=0;if(l)for(let _ of Object.keys(i))(_.endsWith(".xml")||_.endsWith(".rels"))&&c++;let u=0;for(let[_,p]of Object.entries(i))if(_.endsWith(".xml")||_.endsWith(".rels")){let m=Je(p),w=Ke(m);$t(w);let y=a["/"+_]||"application/xml",b=new ns("/"+_,m,w.documentElement,y);b.package=s,s.parts.push(b),u++,l&&u%d===0&&await l(u,c);}l&&c>0&&await l(c,c);let f=s.getPartByPath("word/document.xml");if(!f)throw new Error("Invalid DOCX: Missing word/document.xml");s.mainDocumentPart=f;let h=s.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"),y=p.getAttribute("Type"),b=p.getAttribute("TargetMode");m&&w&&y&&f.rels.set(m,new Kt(m,y,w,b==="External"));}}return new Zt(s,f)}relateTo(e,t){let r=1;for(;this.part.rels.has(`rId${r}`);)r++;let i=`rId${r}`,s=e.partname.split("/").pop();return this.part.rels.set(i,new Kt(i,t,s,false)),this.pkg.getOrCreateRelsPart(this.part.partname).addRelationship(i,t,s,false),i}relateToExternal(e,t){let r=1;for(;this.part.rels.has(`rId${r}`);)r++;let i=`rId${r}`;return this.part.rels.set(i,new Kt(i,t,e,true)),this.pkg.getOrCreateRelsPart(this.part.partname).addRelationship(i,t,e,true),i}static KNOWN_MC_IGNORABLE_URIS={w14:"http://schemas.microsoft.com/office/word/2010/wordml",wp14:"http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing",w15:"http://schemas.microsoft.com/office/word/2012/wordml",wp15:"http://schemas.microsoft.com/office/word/2012/wordprocessingDrawing",w16cid:"http://schemas.microsoft.com/office/word/2016/wordml/cid",w16cex:"http://schemas.microsoft.com/office/word/2018/wordml/cex",w16sdtdh:"http://schemas.microsoft.com/office/word/2020/wordml/sdtdatahash",w16du:"http://schemas.microsoft.com/office/word/2023/wordml/word16du"};async save(){for(let e of this.pkg.parts){let t=Qr(e._element.ownerDocument||e._element),r=false,i=e._element.getAttribute("mc:Ignorable");if(i){let o=i.trim().split(/\s+/).filter(Boolean),a=[];for(let l of o){let d=`xmlns:${l}`;e._element.hasAttribute(d)||t.includes(`${d}=`)?a.push(l):(Zt.KNOWN_MC_IGNORABLE_URIS[l]&&(e._element.setAttribute(d,Zt.KNOWN_MC_IGNORABLE_URIS[l]),a.push(l)),r=true);}a.length!==o.length&&(a.length>0?e._element.setAttribute("mc:Ignorable",a.join(" ")):e._element.removeAttribute("mc:Ignorable"),r=true);}t.includes("w16du:")&&!t.includes("xmlns:w16du=")&&(e._element.setAttribute("xmlns:w16du","http://schemas.microsoft.com/office/word/2023/wordml/word16du"),r=true),r&&(t=Qr(e._element.ownerDocument||e._element)),t.startsWith("<?xml")||(t=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
8
|
+
`+t),this.pkg.unzipped[e.partname.substring(1)]=Lt(t),e.blob=t;let s=e._element.ownerDocument;s&&$t(s);}return Buffer.from(Vr(this.pkg.unzipped))}},Aa=Object.freeze([]),ie=class{static{g(this,"Paragraph");}constructor(n,e){this._element=n,this._parent=e;}_element;_parent;get text(){let n="",e=this._element.getElementsByTagName("w:t");for(let t=0;t<e.length;t++)n+=e[t].textContent||"";return n}},Be=class{static{g(this,"Run");}constructor(n,e){this._element=n,this._parent=e;}_element;_parent;projTextOverride;sdtStack=Aa},Pa=class{static{g(this,"Cell");}constructor(n,e){this._element=n,this._parent=e;}_element;_parent},Ta=class{static{g(this,"Row");}constructor(n,e){this._element=n,this._parent=e;for(let t of Zi(this._element,"w:tc"))this.cells.push(new Pa(t,this));}_element;_parent;cells=[]},ze=class{static{g(this,"Table");}constructor(n,e){this._element=n,this._parent=e;for(let t of Zi(this._element,"w:tr"))this.rows.push(new Ta(t,this));}_element;_parent;rows=[]},Zr=class{static{g(this,"NotesPart");}constructor(n,e){this.part=n,this.note_type=e,this._element=n._element;}part;note_type;_element},$a=class{static{g(this,"FootnoteItem");}constructor(n,e,t){this._element=n,this._parent=e,this.note_type=t,this.id=n.getAttribute("w:id")||"",this.part=e.part;}_element;_parent;note_type;id;part},pt="w:sdt",Sa="w:sdtPr",nt="w:sdtContent",Ia=[["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"]],Oa=new Set(["checkbox","picture","building-block","repeating","repeating-item"]),Da=new Set(["sdtContentLocked","contentLocked"]);function Ve(n){return n?n.getAttribute("w:val")??n.getAttribute("w14:val"):null}g(Ve,"val");function St(n){return !(Oa.has(n.cls)||n.cls==="richtext"&&n.hasNestedSdt)}g(St,"isAnchored");function Me(n){let e=n.flags.map(t=>` ${t}`).join("");return `{#cc:${n.ordinal}${e}}`}g(Me,"openToken");function je(n){return `{#/cc:${n.ordinal}}`}g(je,"closeToken");var rs=new Set(["\u2610","\u2611","\u2612"]),is="[",ss="]";function pr(n){return n.checked?"x":" "}g(pr,"checkboxMark");function Ra(n,e=0){let t=$(n,Sa),r="richtext";if(t){for(let[T,I]of Ia)if($(t,I)){r=T;break}}let i=Ve(t?$(t,"w:alias"):null),s=Ve(t?$(t,"w:tag"):null),o=Ve(t?$(t,"w:id"):null),a=Ve(t?$(t,"w:lock"):null),l=a!==null&&Da.has(a),d=a==="sdtLocked"||a==="sdtContentLocked",c=t?$(t,"w:dataBinding"):null,u=!!c,f=c?c.getAttribute("w:xpath"):null,h=c?c.getAttribute("w:storeItemID"):null,_=c?c.getAttribute("w:prefixMappings"):null,p=!!(t&&$(t,"w:showingPlcHdr")),m=t?$(t,"w:temporary"):null,w=m?Ve(m):null,y=!!m&&(w===null||["1","true","on"].includes(w)),b=$(n,nt),v=null;p&&b&&(v=R(b,"w:t").map(I=>I.textContent??"").join("").trim()||null);let N=[];if(r==="dropdown"||r==="combobox"){let T=t?$(t,r==="dropdown"?"w:dropDownList":"w:comboBox"):null;if(T){let I=[];for(let D of Array.from(T.childNodes)){if(D.nodeType!==1||D.tagName!=="w:listItem")continue;let F=D.getAttribute("w:displayText"),M=D.getAttribute("w:value");I.push([F??M??"",M??F??""]);}N=I;}}let k=null;if(r==="checkbox"){let T=t?$(t,"w14:checkbox"):null,I=Ve(T?$(T,"w14:checked"):null);k=I==="1"||I==="true";}let x=null;if(r==="date"){let T=t?$(t,"w:date"):null;x=Ve(T?$(T,"w:dateFormat"):null);}let P=!!b&&R(b,pt).length>0,E=[];return l&&r!=="group"&&E.push("locked"),u&&E.push("bound"),r==="group"&&E.push("group"),{element:n,cls:r,alias:i,tag:s,sdtId:o,contentLocked:l,deleteLocked:d,bound:u,bindingXpath:f,storeItemId:h,prefixMappings:_,showingPlaceholder:p,placeholderText:v,temporary:y,options:N,checked:k,dateFormat:x,hasNestedSdt:P,ordinal:e,flags:E}}g(Ra,"classifySdt");function Ma(n){return n?R(n,pt):[]}g(Ma,"iterSdtElementsInOrder");function pn(n){let e=new Map,t=0;for(let r of n)for(let i of Ma(r))t+=1,e.set(i,Ra(i,t));return e}g(pn,"assignOrdinals");var ja=new Set(["sdt_start","sdt_end","checkbox_start","checkbox_mark","checkbox_end"]);function _r(n){return !!n&&ja.has(n.type)&&"info"in n}g(_r,"isSdtEvent");var os=["checkbox_start","checkbox_mark","checkbox_end"];function as(n,e){let t=e+1<n.length?n[e+1]:null;return _r(t)&&t.type==="checkbox_end"}g(as,"nextClosesCheckbox");function _n(n){return n?.element??n?._element??n}g(_n,"partElement");var mr=class{static{g(this,"BlockSdt");}constructor(n){this.element=n;}element};function ls(n){let e=n?.parentNode;if(e&&e.tagName===nt){let t=e.parentNode;if(t&&t.tagName===pt)return t}return null}g(ls,"wrappingSdt");var oe={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",STYLES:"application/vnd.openxmlformats-officedocument.wordprocessingml.styles+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",STYLES:"http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"},ei=["w14:paraId","w15:paraId","w15:paraIdParent","w16cid:paraId"],ti=["w16cid:durableId","w16cex:durableId"],Ba=["w14:textId","w:rsidR","w:rsidRPr","w:rsidRDefault","w:rsidP","w:rsidDel","w:rsidTr"],Fa=[{style_id:"CommentReference",type:"character",name:"annotation reference",based_on:"DefaultParagraphFont",half_points:"16"},{style_id:"CommentText",type:"paragraph",name:"annotation text",based_on:"Normal",half_points:"20"}],cs=class extends Error{static{g(this,"CommentThreadingError");}constructor(n){super(n),this.name="CommentThreadingError";}};function*Zn(n){yield n;for(let e=0;e<n.childNodes.length;e++){let t=n.childNodes[e];t.nodeType===1&&(yield*Zn(t));}}g(Zn,"walkElements");var It=class ds{static{g(this,"_CommentsManager");}constructor(e){this.doc=e;}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(e){this._nextId=e;}_getExistingPartByType(e){return this.doc.pkg.parts.find(t=>t.contentType===e)||null}_linkPart(e,t){for(let r of this.doc.part.rels.values())if(!r.isExternal&&r.target===e.partname.split("/").pop())return e;return this.doc.relateTo(e,t),e}_getOrCreateCommentsPart(){let e=this._getExistingPartByType(ee.COMMENTS);if(e)return this._linkPart(e,ke.COMMENTS);let t=this.doc.pkg.nextPartname("/word/comments%d.xml"),r=`<w:comments xmlns:w="${oe.w}" xmlns:w14="${oe.w14}" xmlns:w15="${oe.w15}" xmlns:w16cid="${oe.w16cid}" xmlns:w16cex="${oe.w16cex}" xmlns:mc="${oe.mc}" mc:Ignorable="w14 w15 w16cid w16cex"></w:comments>`;return e=this.doc.pkg.addPart(t,ee.COMMENTS,r),this.doc.relateTo(e,ke.COMMENTS),e}_getOrCreateExtendedPart(){let e=this._getExistingPartByType(ee.EXTENDED);if(e)return this._linkPart(e,ke.EXTENDED);let t=this.doc.pkg.nextPartname("/word/commentsExtended%d.xml"),r=`<w15:commentsEx xmlns:w15="${oe.w15}"></w15:commentsEx>`;return e=this.doc.pkg.addPart(t,ee.EXTENDED,r),this.doc.relateTo(e,ke.EXTENDED),e}_getOrCreateIdsPart(){let e=this._getExistingPartByType(ee.IDS);if(e)return this._linkPart(e,ke.IDS);let t=this.doc.pkg.nextPartname("/word/commentsIds%d.xml"),r=`<w16cid:commentsIds xmlns:w16cid="${oe.w16cid}"></w16cid:commentsIds>`;return e=this.doc.pkg.addPart(t,ee.IDS,r),this.doc.relateTo(e,ke.IDS),e}_getOrCreateExtensiblePart(){let e=this._getExistingPartByType(ee.EXTENSIBLE);if(e)return this._linkPart(e,ke.EXTENSIBLE);let t=this.doc.pkg.nextPartname("/word/commentsExtensible%d.xml"),r=`<w16cex:commentsExtensible xmlns:w16cex="${oe.w16cex}"></w16cex:commentsExtensible>`;return e=this.doc.pkg.addPart(t,ee.EXTENSIBLE,r),this.doc.relateTo(e,ke.EXTENSIBLE),e}_ensureNamespaces(){let e=this._commentsPart?._element;if(!e)return;let t=[["w",oe.w],["w14",oe.w14],["w15",oe.w15],["w16cid",oe.w16cid],["w16cex",oe.w16cex],["mc",oe.mc]];for(let[s,o]of t)e.getAttribute(`xmlns:${s}`)!==o&&e.setAttribute(`xmlns:${s}`,o);let r=(e.getAttribute("mc:Ignorable")||"").split(/\s+/).filter(Boolean),i=[...new Set([...r,"w14","w15","w16cid","w16cex"])].join(" ");i!==r.join(" ")&&e.setAttribute("mc:Ignorable",i);}_ensureCommentStyles(){let t=this._getOrCreateStylesPart()._element,r=new Set,i=new Set;for(let a of fn(t,"w:style")){let l=a.getAttribute("w:styleId");l&&r.add(l);let d=$(a,"w:name"),c=d?d.getAttribute("w:val"):null;c&&i.add(c.trim().toLowerCase());}let s=t.ownerDocument,o=0;for(let a of Fa)r.has(a.style_id)||i.has(a.name)||(t.appendChild(ds._buildCommentStyle(s,a,r)),r.add(a.style_id),i.add(a.name),o++);o!==0&&delete this.doc.pkg._adeu_style_cache;}_getOrCreateStylesPart(){let e=this._getExistingPartByType(ee.STYLES)??this.doc.pkg.getPartByPath("word/styles.xml");if(e)return this._linkPart(e,ke.STYLES);let t=`<w:styles xmlns:w="${oe.w}"></w:styles>`,r=this.doc.pkg.addPart("/word/styles.xml",ee.STYLES,t);return this.doc.relateTo(r,ke.STYLES),r}static _buildCommentStyle(e,t,r){let i=e.createElement("w:style");i.setAttribute("w:type",t.type),i.setAttribute("w:styleId",t.style_id);let s=e.createElement("w:name");if(s.setAttribute("w:val",t.name),i.appendChild(s),r.has(t.based_on)){let c=e.createElement("w:basedOn");c.setAttribute("w:val",t.based_on),i.appendChild(c);}let o=e.createElement("w:uiPriority");o.setAttribute("w:val","99"),i.appendChild(o),i.appendChild(e.createElement("w:semiHidden")),i.appendChild(e.createElement("w:unhideWhenUsed"));let a=e.createElement("w:rPr"),l=e.createElement("w:sz");l.setAttribute("w:val",t.half_points),a.appendChild(l);let d=e.createElement("w:szCs");return d.setAttribute("w:val",t.half_points),a.appendChild(d),i.appendChild(a),i}_getNextCommentId(){let e=[0],t=this._getExistingPartByType(ee.COMMENTS);if(t){let r=R(t._element,"w:comment");for(let i of r){let s=i.getAttribute("w:id");s&&e.push(parseInt(s,10)||0);}}return Math.max(...e)+1}_generateHexId(){return Ht()}_generateDurableId(){return Ht()}_getInitials(e){return e?e.split(" ").filter(Boolean).map(t=>t[0]).join("").toUpperCase():""}_hasCommentsPart(){return this._commentsPart!==null||this._getExistingPartByType(ee.COMMENTS)!==null}_findParaIdForComment(e){if(!this._hasCommentsPart())return null;for(let t of R(this.commentsPart._element,"w:comment"))if(t.getAttribute("w:id")===e)for(let r of R(t,"w:p")){let i=r.getAttribute("w14:paraId");if(i)return i}return null}_findThreadRootParaId(e){let t=this._findParaIdForComment(e),r=this._getExistingPartByType(ee.EXTENDED);if(!t||!r)return t;for(let i=0;i<r._element.childNodes.length;i++){let s=r._element.childNodes[i];if(s.nodeType===1&&s.getAttribute("w15:paraId")===t){let o=s.getAttribute("w15:paraIdParent");if(o)return o}}return t}_existingCommentPartElements(){let e=[];for(let t of [ee.COMMENTS,ee.EXTENDED,ee.IDS,ee.EXTENSIBLE]){let r=this._getExistingPartByType(t);r&&e.push(r._element);}return e}_freeLongHexNumber(e,t){let r=parseInt(e,16),i=Number.isNaN(r)?Ht():fr(r);for(;t.has(i);)i=Ht();return i}_repairInheritedLongHexNumbers(){let e=this._existingCommentPartElements();if(e.length===0)return;let t=g(s=>{let o=new Set,a=[];for(let d of e)for(let c of Zn(d))for(let u of s){let f=c.getAttribute(u);f&&(Kr(f)?o.add(f.toUpperCase()):a.includes(f)||a.push(f));}let l=new Map;for(let d of a){let c=this._freeLongHexNumber(d,o);o.add(c),l.set(d,c);}return l},"remapFor"),r=t(ei),i=t(ti);for(let s of e)for(let o of Zn(s)){for(let a of ei){let l=r.get(o.getAttribute(a)??"");l&&o.setAttribute(a,l);}for(let a of ti){let l=i.get(o.getAttribute(a)??"");l&&o.setAttribute(a,l);}for(let a of Ba){let l=o.getAttribute(a);l&&!Kr(l)&&o.setAttribute(a,this._freeLongHexNumber(l,new Set));}}}_adoptIntoModernComments(e){if(!this._hasCommentsPart())return null;let t=null;for(let o of R(this.commentsPart._element,"w:comment"))if(o.getAttribute("w:id")===e){t=o;break}if(!t)return null;let r=R(t,"w:p");if(r.length===0)return null;let i=null;for(let o of r){let a=o.getAttribute("w14:paraId");if(a){i=a;break}}i||(i=this._generateHexId(),r[0].setAttribute("w14:paraId",i));let s=g((o,a)=>{for(let l=0;l<o._element.childNodes.length;l++){let d=o._element.childNodes[l];if(d.nodeType===1&&d.getAttribute(a)===i)return true}return false},"hasChild");if(!s(this.extendedPart,"w15:paraId")){let a=this.extendedPart._element.ownerDocument.createElement("w15:commentEx");a.setAttribute("w15:paraId",i),a.setAttribute("w15:done","0"),this.extendedPart._element.appendChild(a);}if(!s(this.idsPart,"w16cid:paraId")){let a=this.idsPart._element.ownerDocument.createElement("w16cid:commentId");a.setAttribute("w16cid:paraId",i),a.setAttribute("w16cid:durableId",this._generateDurableId()),this.idsPart._element.appendChild(a);}return i}resolveThreadParentParaId(e){this._repairInheritedLongHexNumbers();let t=this._findThreadRootParaId(e),r=this._adoptIntoModernComments(e);return t??r}addComment(e,t,r=null,i){this._repairInheritedLongHexNumbers();let s=this._getExistingPartByType(ee.EXTENDED)!==null,o=null;if(r!=null&&(o=this.resolveThreadParentParaId(r),!o))throw new cs(`Cannot thread a reply onto comment Com:${r}: 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.`);this._ensureCommentStyles();let a=this.nextId.toString();this.nextId++;let l=i??new Date().toISOString().replace(/\.\d{3}Z$/,"Z"),d=this.commentsPart._element.ownerDocument,c=d.createElement("w:comment");c.setAttribute("w:id",a),c.setAttribute("w:author",e),c.setAttribute("w:date",l);let u=this._getInitials(e);u&&c.setAttribute("w:initials",u),r&&!s&&c.setAttribute("w15:p",r);let f=this._generateHexId(),h=this._generateHexId(),_=d.createElement("w:p");_.setAttribute("w14:paraId",f),_.setAttribute("w14:textId","77777777"),_.setAttribute("w:rsidR",h),_.setAttribute("w:rsidRDefault",h),_.setAttribute("w:rsidP",h);let p=d.createElement("w:pPr"),m=d.createElement("w:pStyle");m.setAttribute("w:val","CommentText"),p.appendChild(m),_.appendChild(p);let w=d.createElement("w:r"),y=d.createElement("w:rPr"),b=d.createElement("w:rStyle");b.setAttribute("w:val","CommentReference"),y.appendChild(b),w.appendChild(y),w.appendChild(d.createElement("w:annotationRef")),_.appendChild(w);let v=d.createElement("w:r"),N=d.createElement("w:t");if(N.textContent=t,v.appendChild(N),_.appendChild(v),c.appendChild(_),this.commentsPart._element.appendChild(c),this.extendedPart){let x=this.extendedPart._element.ownerDocument.createElement("w15:commentEx");x.setAttribute("w15:paraId",f),o&&x.setAttribute("w15:paraIdParent",o),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",f),x.setAttribute("w16cid:durableId",this._generateDurableId()),this.idsPart._element.appendChild(x);}if(this.extensiblePart){let k=null;for(let x=0;x<this.idsPart._element.childNodes.length;x++){let P=this.idsPart._element.childNodes[x];if(P.nodeType===1&&P.getAttribute("w16cid:paraId")===f){k=P.getAttribute("w16cid:durableId");break}}if(k){let P=this.extensiblePart._element.ownerDocument.createElement("w16cex:commentExtensible");P.setAttribute("w16cex:durableId",k),P.setAttribute("w16cex:dateUtc",l),this.extensiblePart._element.appendChild(P);}}return a}deleteComment(e){if(!this.commentsPart)return;let t=null;for(let i of R(this.commentsPart._element,"w:comment"))if(i.getAttribute("w:id")===e){t=i;break}if(!t)return;let r=null;for(let i of R(t,"w:p")){let s=i.getAttribute("w14:paraId");if(s){r=s;break}}if(r){let i=[];if(this.extendedPart)for(let o=0;o<this.extendedPart._element.childNodes.length;o++){let a=this.extendedPart._element.childNodes[o];if(a.nodeType===1&&a.getAttribute("w15:paraIdParent")===r){let l=a.getAttribute("w15:paraId");if(l){for(let d of R(this.commentsPart._element,"w:comment"))for(let c of R(d,"w:p"))if(c.getAttribute("w14:paraId")===l){let u=d.getAttribute("w:id");u&&i.push(u);break}}}}for(let o of i)this.deleteComment(o);let s=null;if(this.idsPart){let o=[];for(let a=0;a<this.idsPart._element.childNodes.length;a++){let l=this.idsPart._element.childNodes[a];l.nodeType===1&&l.getAttribute("w16cid:paraId")===r&&(s=l.getAttribute("w16cid:durableId"),o.push(l));}o.forEach(a=>this.idsPart._element.removeChild(a));}if(this.extendedPart){let o=[];for(let a=0;a<this.extendedPart._element.childNodes.length;a++){let l=this.extendedPart._element.childNodes[a];l.nodeType===1&&l.getAttribute("w15:paraId")===r&&o.push(l);}o.forEach(a=>this.extendedPart._element.removeChild(a));}if(s&&this.extensiblePart){let o=[];for(let a=0;a<this.extensiblePart._element.childNodes.length;a++){let l=this.extensiblePart._element.childNodes[a];l.nodeType===1&&l.getAttribute("w16cex:durableId")===s&&o.push(l);}o.forEach(a=>this.extensiblePart._element.removeChild(a));}}t.parentNode&&t.parentNode.removeChild(t);}};function Fe(n){({part:n.mainDocumentPart,relateTo:g(()=>{},"relateTo")});let r=Object.create(null),i=n.parts.find(l=>l.contentType===ee.COMMENTS);if(!i)return r;let s=Object.create(null),o=R(i._element,"w:comment");for(let l of o){let d=l.getAttribute("w:id");if(!d)continue;let c=l.getAttribute("w:author")||"Unknown",u=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 y of p){let b=y.getAttribute("w14:paraId");b&&(s[b]=d);}let m=[];for(let y of p){let b=R(y,"w:t");for(let v of b)v.textContent&&m.push(v.textContent);m.push(`
|
|
9
|
+
`);}let w=m.join("").trim();r[d]={author:c,text:w,date:u,resolved:f,parent_id:_};}let a=n.parts.find(l=>l.contentType===ee.EXTENDED);if(a){let l=a._element.childNodes;for(let d=0;d<l.length;d++){let c=l[d];if(c.nodeType!==1)continue;let u=c.getAttribute("w15:paraId"),f=c.getAttribute("w15:paraIdParent"),h=c.getAttribute("w15:done");if(u){let _=s[u];if(_&&r[_]){if(f){let p=s[f];p&&(r[_].parent_id=p);}(h==="1"||h==="true"||h==="on")&&(r[_].resolved=true);}}}}return r}g(Fe,"extract_comments_data");var qn=500,ct=200,La=["{++","++}","{--","--}","{==","==}","{>>","<<}"];function fs(n){if(!n||!n.includes("{")&&!n.includes("}"))return n;for(let e of La)if(n.includes(e)){let t=e.startsWith("{")?"{ "+e.slice(1):e.slice(0,-1)+" }";n=n.split(e).join(t);}return n}g(fs,"escape_critic_tokens");function ni(n,e){return n.length<=e?n:n.slice(0,Math.max(1,e-3))+"..."}g(ni,"clamp_text");function ge(n,e){if(n==null||n.length<=e)return n;let t=Math.max(1,Math.floor(e*2/3)),r=Math.max(1,e-t),i=n.length-t-r;return `${n.slice(0,t)}\u2026 [${i.toLocaleString("en-US")} chars omitted] \u2026${n.slice(-r)}`}g(ge,"truncate_middle");var Wa={"\u201C":'"',"\u201D":'"',"\u2018":"'","\u2019":"'"},za=/[\u201c\u201d\u2018\u2019]/g;function Et(n){return n&&n.replace(za,e=>Wa[e])}g(Et,"normalize_smart_quotes");function er(n){return !!n&&/[\u201c\u201d\u2018\u2019]/.test(n)}g(er,"has_smart_quotes");function Ua(n,e){if(!n||!e||!er(n))return e;let t=Et(n),r=Et(e);if(t===r)return n;let s=new us.diff_match_patch().diff_main(t,r),o=[],a=0,l=0;for(let[d,c]of s)d===0?(o.push(n.substr(a,c.length)),a+=c.length,l+=c.length):d===-1?a+=c.length:(o.push(e.substr(l,c.length)),l+=c.length);return o.join("")}g(Ua,"restore_document_typography");function Ha(n,e,t){return !t||!n||!er(n)||er(e||"")?t:Ua(n,t)}g(Ha,"restore_matched_typography");var gr=2e3,Le=class extends Error{static{g(this,"RegexTimeoutError");}pattern;constructor(n){super(`Regular expression exceeded the ${gr/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=n;}};function hs(n){let e=false,t=false,r=[];for(let i=0;i<n.length;i++){let s=n[i];if(t){t=false;continue}if(s==="\\"){t=true;continue}if(e){s==="]"&&(e=false);continue}if(s==="["){e=true;continue}if(s==="("){r.push({hasInnerQuantifierOrPipe:false});continue}if(s===")"){if(r.length>0){let o=r.pop(),a=n.substring(i+1),l=a.match(/^(\*|\+|\{\d+\,\s*\}|\?)/),d=l?l[1]:"",c=d==="*"||d==="+"||/^\{\d+\,\s*\}/.test(a);if(c&&o.hasInnerQuantifierOrPipe)return true;r.length>0&&(o.hasInnerQuantifierOrPipe||c)&&(r[r.length-1].hasInnerQuantifierOrPipe=true);}continue}r.length>0&&(s==="|"||s==="*"||s==="+"||/^\{\d+\,\s*\}/.test(n.substring(i)))&&(r[r.length-1].hasInnerQuantifierOrPipe=true);}return false}g(hs,"hasCatastrophicBacktrackingRisk");function mn(n,e=""){let t=new Set(e.split(""));return {pattern:n.replace(/(?<!\\)\(\?([ims]+)\)/g,(i,s)=>{for(let o of s)t.add(o);return ""}),flags:Array.from(t).join("")}}g(mn,"extractInlineRegexFlags");function an(n,e=""){let{pattern:t,flags:r}=mn(n,e);try{return new RegExp(t,r)}catch(i){if(/(?<!\\)\(\?([ims]+):/.test(t)){let s=new Set(r.split("")),o=t.replace(/(?<!\\)\(\?([ims]+):/g,(a,l)=>{for(let d of l)s.add(d);return "(?:"});return new RegExp(o,Array.from(s).join(""))}throw i}}g(an,"compileRegexWithInlineFlags");function qa(n,e,t=""){let{pattern:r,flags:i}=mn(n,t);if(hs(r))throw new Le(n);let s=i.includes("g")?i:i+"g",o=an(r,s),a=Date.now(),l=[],d;for(;(d=o.exec(e))!==null;){if(Date.now()-a>gr)throw new Le(n);l.push({start:d.index,end:d.index+d[0].length}),d.index===o.lastIndex&&o.lastIndex++;}return l}g(qa,"userFindAllMatches");function Xa(n,e,t=""){let{pattern:r,flags:i}=mn(n,t);if(hs(r))throw new Le(n);let s=an(r,i.replace("g","")),o=Date.now(),a=s.exec(e);if(Date.now()-o>gr)throw new Le(n);return a?{start:a.index,end:a.index+a[0].length}:null}g(Xa,"userSearch");var ps="w:p",wr="w:r",Mt="w:t",_s="w:delText",ms="w:tab",gs="w:br",ws="w:cr",en="\f",gn="w:rPr",Ya="w:rPrChange",Ga="w:commentReference",Ja="w:footnoteReference",Va="w:endnoteReference",Qa="w:fldChar",Ka="w:fldCharType",Za="w:instrText",el="w:ins",ys="w:del",Re="w:id",Xn="w:author",Yn="w:date",tl="w:commentRangeStart",nl="w:commentRangeEnd",rl="w:hyperlink",il="r:id",sl="w:fldSimple",ol="w:instr",al="w:bookmarkStart",ll="w:name",Ot="w:sdt",cl="w:smartTag",yr="w:sdtContent",vs="w:b",dl="w:i",_e="w:val",vr="w:pPr",bs="w:pStyle",xs="w:outlineLvl",ul="w:numPr",fl="w:numId",hl="w:ilvl",tr="w:drawing",nr="w:object",rr="w:pict",pl="wp:docPr",_l="v:imagedata",ml="o:title",gl="w:txbxContent",wl="mc:AlternateContent",yl="mc:Choice",vl="mc:Fallback",ri=300;function ii(n){let e=[];for(let r of R(n,gl))for(let i of R(r,Mt))i.textContent&&e.push(i.textContent);let t=e.join(" ").split(/\s+/).filter(Boolean).join(" ");return t.length>ri&&(t=t.slice(0,ri).trimEnd()+"\u2026"),t}g(ii,"_textbox_text");function*si(n){let e=n.tagName;if(e===tr||e===nr){let t=R(n,pl)[0]||null,r="",i="0";t&&(r=t.getAttribute("descr")||t.getAttribute("title")||"",i=t.getAttribute("id")||"0");let s=ii(n);s&&(r=r?`Text box (${r}): ${s}`:`Text box: ${s}`),yield {type:"image",id:i,date:r};}else if(e===rr){let t=R(n,_l)[0]||null,r=t&&t.getAttribute(ml)||"",i=ii(n);i&&(r=r?`Text box (${r}): ${i}`:`Text box: ${i}`),(i||t)&&(yield {type:"image",id:"vml",date:r});}}g(si,"_graphic_marker_events");var bl=/Heading[ ]?([1-6])(?![0-9])/;function xl(n){let e=n,t=new Set;for(;e&&!t.has(e);){if(t.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(xl,"_resolve_package");function _t(n){let e=n.package||n.pkg||(n.part?n.part.pkg:null);if(e&&e._adeu_style_cache)return e._adeu_style_cache;let t=Object.create(null),r=null,i=Object.create(null),s=e?.getPartByPath("word/styles.xml");if(!s){let d=[t,null];return e&&(e._adeu_style_cache=d),d}let o=R(s._element,"w:style");for(let d of o){let c=d.getAttribute("w:styleId");if(!c)continue;let u=d.getAttribute("w:type"),f=d.getAttribute("w:default")==="1"||d.getAttribute("w:default")==="true";u==="paragraph"&&f&&(r=c);let h=$(d,"w:name"),_=h?h.getAttribute("w:val"):c;_&&typeof _=="string"&&(_.toLowerCase().startsWith("heading")?_=_.replace(/^heading/i,"Heading"):_.toLowerCase()==="title"&&(_="Title"));let p=$(d,"w:basedOn"),m=p?p.getAttribute("w:val"):null,w=null,y=null,b=null,v=$(d,"w:pPr");if(v){let x=$(v,"w:outlineLvl");if(x){let E=x.getAttribute("w:val");E&&/^\d+$/.test(E)&&(w=parseInt(E,10));}let P=$(v,"w:numPr");if(P){let E=$(P,"w:numId");if(E){let I=E.getAttribute("w:val");I&&I!=="0"&&(y=I);}let T=$(P,"w:ilvl");if(T){let I=T.getAttribute("w:val");I&&/^\d+$/.test(I)&&(b=parseInt(I,10));}}}let N=null,k=$(d,"w:rPr");if(k){let x=$(k,"w:b");if(x){let P=x.getAttribute("w:val");N=P!=="0"&&P!=="false"&&P!=="off";}}i[c]={name:_,based_on:m,outline_level:w,bold:N,num_id:y,num_ilvl:b};}let a=g((d,c)=>{if(t[d])return t[d];if(c.has(d)||!i[d])return {name:d,outline_level:null,bold:false,num_id:null,num_ilvl:null};c.add(d);let u=i[d],f=u.based_on,h=u.outline_level,_=u.bold!==null?u.bold:false,p=u.num_id,m=u.num_ilvl;if(f){let y=a(f,c);h===null&&(h=y.outline_level),u.bold===null&&(_=y.bold),p===null&&(p=y.num_id??null),m===null&&(m=y.num_ilvl??null);}let w={name:u.name,outline_level:h,bold:_,num_id:p,num_ilvl:m};return t[d]=w,w},"resolve_style");for(let d in i)a(d,new Set);let l=[t,r];return e&&(e._adeu_style_cache=l),l}g(_t,"_get_style_cache");function Nl(n){let e=xl(n);if(!e)return {};if(e._adeu_numbering_cache)return e._adeu_numbering_cache;let t=Object.create(null),r=null;try{let i=(e.parts||[]).find(s=>String(s.partname).endsWith("/numbering.xml"));i&&(r=i._element);}catch{r=null;}if(r){let i=Object.create(null);for(let s of R(r,"w:abstractNum")){let o=s.getAttribute("w:abstractNumId");if(o===null)continue;let a={};for(let l of R(s,"w:lvl")){let d=l.getAttribute("w:ilvl"),c=$(l,"w:numFmt");if(d!==null&&/^-?\d+$/.test(d)&&c){let u=c.getAttribute("w:val");u&&(a[parseInt(d,10)]=u);}}i[o]=a;}for(let s of R(r,"w:num")){let o=s.getAttribute("w:numId"),a=$(s,"w:abstractNumId");if(o===null||!a)continue;let l=a.getAttribute("w:val");l!==null&&i[l]!==void 0&&(t[o]=i[l]);}}return e._adeu_numbering_cache=t,t}g(Nl,"_get_numbering_cache");function kl(n,e,t){let r=null;if(e!=null){let i=Nl(n)[e];if(i&&Object.keys(i).length>0&&(r=i[t]!==void 0?i[t]:null,r===null)){for(let s=t;s>=0;s--)if(i[s]!==void 0){r=i[s];break}}}return r!==null&&r!=="bullet"?"1. ":"* "}g(kl,"get_list_marker");function Ns(n){if(!n)return null;let e=n.match(bl);return e?parseInt(e[1],10):null}g(Ns,"_detect_heading_level_from_name");function ks(n){let e=$(n,vr);if(!e)return false;let t=$(e,gn);return !!t&&!!$(t,ys)}g(ks,"paragraph_mark_is_deleted");function wn(n,e,t){e||([e,t]=_t(n._parent.part||n._parent));let r=$(n._element,vr);if(r){let a=$(r,xs);if(a){let l=a.getAttribute(_e);if(l&&/^\d+$/.test(l)){let d=parseInt(l,10);if(d>=0&&d<=8)return true}}}let i=t;if(r){let a=$(r,bs);a&&(i=a.getAttribute(_e)||t);}let s=i&&e?e[i]:null;if(s&&s.outline_level!==null&&s.outline_level>=0&&s.outline_level<=8)return true;let o=s?s.name:i;return o&&typeof o=="string"&&o.toLowerCase().startsWith("heading")&&(o=o.replace(/^heading/i,"Heading")),!!(o?.startsWith("Heading")||o==="Title"||o&&o!=="Normal"&&Ns(o)!==null)}g(wn,"is_native_heading");function Ue(n,e,t){e||([e,t]=_t(n._parent.part||n._parent));let r=$(n._element,vr);if(r){let c=$(r,xs);if(c){let u=c.getAttribute(_e);if(u&&/^\d+$/.test(u)){let f=parseInt(u,10);if(f>=0&&f<=8)return "#".repeat(f+1)+" "}}}let i=t;if(r){let c=$(r,bs);c&&(i=c.getAttribute(_e)||t);}let s=i&&e?e[i]:null;if(s&&s.outline_level!==null&&s.outline_level>=0&&s.outline_level<=8)return "#".repeat(s.outline_level+1)+" ";let o=s?s.name:i;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 a=null,l=null,d=false;if(r){let c=$(r,ul);if(c){let u=$(c,fl);if(u){let f=u.getAttribute(_e);if(f==="0")d=true;else if(f){a=f;let h=$(c,hl);if(h){let _=h.getAttribute(_e);_!==null&&/^\d+$/.test(_)&&(l=parseInt(_,10));}}}}}if(a===null&&!d&&s){let c=s.num_id;c&&(a=c,l===null&&(l=s.num_ilvl!==void 0?s.num_ilvl:null));}if(a!==null){let c=l!==null?l:0,u=kl(n._parent?n._parent.part||n._parent:null,a,c);return " ".repeat(c)+u}if(o&&o!=="Normal"){let c=Ns(o);if(c!==null)return "#".repeat(c)+" "}if(!o||o==="Normal"){let c=false,u=n._element;for(;u;){if(u.tagName==="w:tc"){c=true;break}u=u.parentNode;}if(c)return "";let f=n.text.trim();if(f&&f.length<100&&f===f.toUpperCase()){let h=false;if(s?.bold)h=true;else {let _=R(n._element,wr);for(let p of _)if(R(p,Mt).map(y=>y.textContent||"").join("").trim()){let y=$(p,gn);if(y){let b=$(y,vs);b&&b.getAttribute(_e)!=="0"&&b.getAttribute(_e)!=="false"&&(h=true);}break}}if(h)return "## "}}return ""}g(Ue,"get_paragraph_prefix");function Cs(n,e,t){let r=Ue(n,e,t);if(!r)return false;let i=r.trimEnd();return i.length>0&&i==="#".repeat(i.length)}g(Cs,"is_heading_paragraph");function Es(n,e=null){if(n.projTextOverride!==void 0)return ["",""];let t="",r="",i=$(n._element,gn),s=false,o=false;if(i){let a=$(i,vs);a&&a.getAttribute(_e)!=="0"&&a.getAttribute(_e)!=="false"&&(s=true);let l=$(i,dl);l&&l.getAttribute(_e)!=="0"&&l.getAttribute(_e)!=="false"&&(o=true);}if(e===null){let a=n._parent;e=a instanceof ie?wn(a):false;}return s&&!e&&(t+="**",r="**"+r),o&&(t+="_",r="_"+r),[t,r]}g(Es,"get_run_style_markers");function As(n){let e=n.trim();if(!e)return ["","",n];let t=n.length-n.trimStart().length;return [n.substring(0,t),n.substring(t,t+e.length),n.substring(t+e.length)]}g(As,"split_boundary_whitespace");function Ps(n){let e=[],t=[],r=new Set;for(let[s,o]of n){let a=Object.entries(s),l=Object.entries(o);if(a.length===0&&l.length===0){t.length>0&&(e.push(t),t=[]);continue}let d=[];for(let[c,u]of a)r.has(c)||d.push([c,u&&u.author||"Unknown"]);for(let[c,u]of l)r.has(c)||d.push([c,u&&u.author||"Unknown"]);for(let[c,u]of d)r.add(c),t.length>0&&t[t.length-1][1]!==u&&(e.push(t),t=[]),t.push([c,u]);}t.length>0&&e.push(t);let i={};for(let s of e)if(!(s.length<2))for(let[o]of s)i[o]=s.filter(([a])=>a!==o).map(([a])=>`Chg:${a}`).join(", ");return i}g(Ps,"compute_change_pair_map");function Cl(n,e,t){if(!e&&!t)return n;if(!n)return "";let r=g(s=>{let[o,a,l]=As(s);return a?`${o}${e}${a}${t}${l}`:s},"wrap");return n.includes(`
|
|
10
10
|
`)?n.split(`
|
|
11
11
|
`).map(s=>s?r(s):"").join(`
|
|
12
|
-
`):r(n)}g(
|
|
13
|
-
`:r.tagName===
|
|
14
|
-
`);}return e}g(
|
|
12
|
+
`):r(n)}g(Cl,"apply_formatting_to_segments");function El(n,e){let t=n.parentNode;for(;t;){let r=t.tagName;if(r==="w:ins"||r==="w:del")return e==="\u2611"||e==="\u2612"?"x":" ";t=t.parentNode;}}g(El,"revisionBallotMark");function Al(n){let e=$(n,yr);if(!e)return false;for(let t of R(e,wr)){let r="";for(let i of R(t,Mt))r+=i.textContent||"";if(rs.has(r))return true}return false}g(Al,"hasBallotRun");function Pl(n,e,t){if(!t||!rs.has(e))return;let r=n.parentNode;for(;r&&r.nodeType===1;){if(r.tagName===Ot){let i=t.get(r);return i&&i.cls==="checkbox"?i:void 0}r=r.parentNode;}}g(Pl,"enclosingCheckbox");function Ie(n){if(n.projTextOverride!==void 0)return n.projTextOverride;let e="";for(let t=0;t<n._element.childNodes.length;t++){let r=n._element.childNodes[t];if(r.nodeType===1)if(r.tagName===Mt||r.tagName===_s){let i=r.textContent||"";e+=i.replace(/\t/g," ");}else r.tagName===ms||r.tagName==="w:ptab"?e+=" ":r.tagName==="w:noBreakHyphen"?e+="-":r.tagName===gs?e+=r.getAttribute("w:type")==="page"?en:`
|
|
13
|
+
`:r.tagName===ws&&(e+=`
|
|
14
|
+
`);}return e}g(Ie,"get_run_text");function*He(n,e=false){let t=n._element||n.element||n;if(n.constructor.name==="NotesPart"){let r=n.note_type==="fn"?"w:footnote":"w:endnote",i=R(t,r);for(let s of i){if(s.getAttribute("w:type")==="separator"||s.getAttribute("w:type")==="continuationSeparator")continue;let o=s.getAttribute("w:id");o!==null&&/^\s*[-+]?\d+\s*$/.test(o)&&parseInt(o,10)<=0||(yield new $a(s,n,n.note_type));}return}yield*Ts(t,n,e);}g(He,"iter_block_items");function*Ts(n,e,t=false){for(let r=0;r<n.childNodes.length;r++){let i=n.childNodes[r];if(i.nodeType===1){if(i.tagName===ps)yield new ie(i,e);else if(i.tagName==="w:tbl")yield new ze(i,e);else if(i.tagName===Ot){let s=$(i,yr);s&&(t?yield new mr(i):yield*Ts(s,e,t));}}}}g(Ts,"_iter_block_children");function*Tl(n){for(let[e]of Ze(n))yield e;}g(Tl,"iter_document_parts");function*$l(n){let e=n.element;function*t(i){for(let s=0;s<i.childNodes.length;s++){let o=i.childNodes[s];if(o.nodeType===1){if(o.tagName===ps){let a=$(o,"w:pPr"),l=a&&$(a,"w:sectPr");l&&(yield l);}else if(o.tagName===Ot){let a=$(o,"w:sdtContent");a&&(yield*t(a));}}}}g(t,"walk"),yield*t(e);let r=$(e,"w:sectPr");r&&(yield r);}g($l,"_iter_sect_pr");function Sl(n){let e=n.pkg.getPartByPath("word/settings.xml");return e?$(e._element,"w:evenAndOddHeaders")!==null:false}g(Sl,"_odd_and_even_pages");function*oi(n,e){let t=e==="header"?"w:headerReference":"w:footerReference",r=Sl(n);for(let i of $l(n)){let s=fn(i,t),o=g(d=>s.find(c=>(c.getAttribute("w:type")||"default")===d),"byType"),a=g(d=>{if(!d)return;let c=d.getAttribute("r:id");if(!c)return;let u=n.part.rels.get(c);if(!u)return;let f=u.target.replace(/^\/?word\//,"").replace(/^\//,"");return n.pkg.getPartByPath("word/"+f)},"resolve"),l=a(o("default"));if(l&&(yield l),$(i,"w:titlePg")!==null){let d=a(o("first"));d&&(yield d);}if(r){let d=a(o("even"));d&&(yield d);}}}g(oi,"_iter_section_parts");function*Ze(n){for(let r of oi(n,"header"))yield [r,"header"];yield [n,"body"];for(let r of oi(n,"footer"))yield [r,"footer"];let e=n.pkg.getPartByPath("word/footnotes.xml"),t=n.pkg.getPartByPath("word/endnotes.xml");e&&(yield [new Zr(e,"fn"),"footnotes"]),t&&(yield [new Zr(t,"en"),"endnotes"]);}g(Ze,"iter_document_parts_with_kind");function Il(n){if(!n)return false;let e=n.toUpperCase().trim().split(/\s+/);return e.length>0&&(e[0]==="PAGE"||e[0]==="NUMPAGES")}g(Il,"_is_page_instr");function $s(n){return n?n.part?n.part:n.pkg&&n.pkg.mainDocumentPart?n.pkg.mainDocumentPart:n._parent?$s(n._parent):null:null}g($s,"_get_part");function*yn(n,e){let t=false,r="",i=false,s=[];function*o(l){let d=null,c=$(l,gn);if(c){let u=$(c,Ya);u&&(d=u.getAttribute(Re),yield {type:"fmt_start",id:d,author:u.getAttribute(Xn)||void 0,date:u.getAttribute(Yn)||void 0});}for(let u=0;u<l.childNodes.length;u++){let f=l.childNodes[u];if(f.nodeType!==1)continue;let h=f.tagName;if(h===tr||h===nr||h===rr)yield*si(f);else if(h===wl){let _=null;for(let p of [yl,vl]){for(let m of fn(f,p))if(_=$(m,tr)||$(m,nr)||$(m,rr),_)break;if(_)break}_&&(yield*si(_));}else if(h===Ga){let _=f.getAttribute(Re);_&&(yield {type:"ref",id:_});}else if(h===Ja){let _=f.getAttribute(Re);_&&(yield {type:"footnote",id:_});}else if(h===Va){let _=f.getAttribute(Re);_&&(yield {type:"endnote",id:_});}else if(h===Qa){let _=f.getAttribute(Ka);if(_==="begin")t=true,r="";else if(_==="separate")if(Il(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]});}t=false,r="",i=false;}}else h===Za&&t&&!i&&(r+=f.textContent||"");}if(!i){let u=new Be(l,n);s.length&&(u.sdtStack=s.slice());let f=Pl(l,Ie(u),e);if(f){let h=Ie(u);u.projTextOverride=El(l,h)??pr(f),yield {type:"checkbox_start",info:f},yield u,yield {type:"checkbox_end",info:f};}else yield u;}d!==null&&(yield {type:"fmt_end",id:d});}g(o,"process_run_element");function*a(l){for(let d=0;d<l.childNodes.length;d++){let c=l.childNodes[d];if(c.nodeType!==1)continue;let u=c.tagName;if(u===wr)yield*o(c);else if(u===el){let f=c.getAttribute(Re);yield {type:"ins_start",id:f,author:c.getAttribute(Xn)||void 0,date:c.getAttribute(Yn)||void 0},yield*a(c),yield {type:"ins_end",id:f};}else if(u===ys){let f=c.getAttribute(Re);yield {type:"del_start",id:f,author:c.getAttribute(Xn)||void 0,date:c.getAttribute(Yn)||void 0},yield*a(c),yield {type:"del_end",id:f};}else if(u===tl)yield {type:"start",id:c.getAttribute(Re)};else if(u===nl)yield {type:"end",id:c.getAttribute(Re)};else if(u===rl){let f=c.getAttribute(il)||c.getAttribute("id"),h="",_=$s(n._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(u===sl){let h=(c.getAttribute(ol)||"").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(u===al){let f=c.getAttribute(ll);f&&(!f.startsWith("_")||f.startsWith("_Ref"))&&(yield {type:"bookmark",id:f});}else if(u===Ot||u===cl||u===yr){let f=e?e.get(c):void 0,h=!!f&&u===Ot;h&&s.push(f);try{f&&f.cls==="checkbox"&&!Al(c)?(yield {type:"checkbox_start",info:f},yield {type:"checkbox_mark",info:f},yield {type:"checkbox_end",info:f}):!f||!St(f)?yield*a(c):(yield {type:"sdt_start",info:f},f.showingPlaceholder||(yield*a(c)),yield {type:"sdt_end",info:f});}finally{h&&s.pop();}}}}g(a,"traverse_node"),yield*a(n._element);}g(yn,"iter_paragraph_content");var Ol=new Set(["**","__","*","_"]),ir=/\[~[^~\]]+~\]\(#[^)]+\)|(?<!!)\[(?!~)[^\]]+\]\((?!docx-image:)[^)]+\)|\{#(?!\/?cc:|cell:)[^}]+\}/g;function Dl(n){if(n.run!==null||n.paragraph===null)return false;let e=n.text;return e==="[~"||e.startsWith("~](#")||n.hyperlink_id&&(e==="["||e.startsWith("]("))?true:e.startsWith("{#")&&!e.startsWith("{#cc:")&&!e.startsWith("{#/cc:")&&!e.startsWith("{#cell:")}g(Dl,"isAnchorMarkerSyntax");function qt(n,e){let t=0,r=n.length;for(;t<r;){let i=t+r>>1;n[i]<e?t=i+1:r=i;}return t}g(qt,"bisectLeft");var Te=class{static{g(this,"DocumentMapper");}doc;clean_view;original_view;comments_map;full_text="";spans=[];appendix_start_index=-1;part_ranges=[];part_names=[];_current_part_index=0;_current_block_sdt_stack=[];control_ranges=[];_sdt_infos=new Map;_text_chunks=[];_plain_projection=null;constructor(n,e=false,t=false){this.doc=n,this.clean_view=e,this.original_view=t,this.comments_map=Fe(n.pkg),this._build_map();}_build_map(){let n=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=pn(Array.from(Ze(this.doc)).map(([r])=>_n(r)));let e=0,t=false;for(let[r,i]of Ze(this.doc)){this._current_part_index=e,this.part_names.push(String(r?.partname??r?.part?.partname??"").replace(/^\//,""));let s=this.spans.length,o=this._text_chunks.length,a=n;t&&(this._add_virtual_text(`
|
|
15
15
|
|
|
16
|
-
`,n,null),n+=2);let
|
|
17
|
-
|
|
16
|
+
`,n,null),n+=2);let l=n;n=this._map_blocks(r,n),n===l?(this.spans.length=s,this._text_chunks.length=o,n=a,this.part_ranges.push([n,n,i])):(t=true,this.part_ranges.push([l,n,i])),e++;}this.full_text=this._text_chunks.join(""),this._buildControlRanges(),this.appendix_start_index=-1;}_spanSdtStack(n){let e=this._current_block_sdt_stack,t=n?.sdtStack??[];return e.length===0?t:t.length===0?e.slice():[...e,...t]}_buildControlRanges(){let n=new Map;for(let e of this.spans)if(!(!e.sdt_stack||e.sdt_stack.length===0))for(let t of e.sdt_stack){let r=n.get(t);r===void 0?n.set(t,[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(n.entries()).map(([e,[t,r]])=>[t,r,e]).sort((e,t)=>e[0]-t[0]||t[1]-e[1]);}controls_at(n){return this.control_ranges.filter(([e,t])=>e<=n&&n<t).map(([,,e])=>e)}controls_intersecting(n,e){if(e<=0)return [];let t=n+e;return this.control_ranges.filter(([r,i])=>i>n&&r<t).map(([,,r])=>r)}_nonempty_part_ranges(){let n=[];for(let e=0;e<this.part_ranges.length;e++){let[t,r,i]=this.part_ranges[e];r>t&&n.push([e,t,r,i]);}return n}part_kind_of(n){return n>=0&&n<this.part_ranges.length?this.part_ranges[n][2]:null}part_kind_at(n){for(let[,e,t,r]of this._nonempty_part_ranges())if(e<=n&&n<=t)return r;return null}part_label_at(n){for(let[e,t,r,i]of this._nonempty_part_ranges())if(t<=n&&n<=r){if(i==="body")return "";let s=this.part_names[e]||"";return s?`${i} (${s})`:i}return ""}body_edge_line(n=false){for(let[e,t,r]of this.part_ranges)if(r==="body"&&t>e){let i=this.full_text.substring(e,t).split(`
|
|
17
|
+
`).map(s=>s.trim()).filter(s=>s);if(i.length)return (n?i[i.length-1]:i[0]).substring(0,80)}return ""}part_boundary_at(n){let e=this._nonempty_part_ranges();for(let t=1;t<e.length;t++){let[r,,i]=e[t-1],[s,o]=e[t];if(i<n&&n<=o)return [r,s]}return null}_map_blocks(n,e,t=false){let r=e,i=n.constructor.name,s=n.part||n,[o,a]=_t(s),l=false;if(i==="NotesPart"){let f=`---
|
|
18
|
+
${n.note_type==="fn"?"## Footnotes":"## Endnotes"}`;this._add_virtual_text(f,r,null),r+=f.length,l=true;}let d=true,c=null;for(let u of He(n,true)){let f=u.constructor.name,h=this.spans.length,_=this._text_chunks.length,p=r;if(u instanceof mr){if(l){let v=c instanceof ie?c:null;this._add_virtual_text(`
|
|
18
19
|
|
|
19
|
-
`,r,v),r+=2;}let m=this._sdt_infos.get(
|
|
20
|
-
`;if(w){let v=`${
|
|
20
|
+
`,r,v),r+=2;}let m=this._sdt_infos.get(u.element),w=!!m&&St(m),y=t?"":`
|
|
21
|
+
`;if(w){let v=`${Me(m)}${y}`;this._add_virtual_text(v,r,null),r+=v.length;}let b=r;m&&this._current_block_sdt_stack.push(m);try{r=this._map_blocks({_element:$(u.element,"w:sdtContent"),part:n.part||n},r,t);}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 v=`${y}${je(m)}`;this._add_virtual_text(v,r,null),r+=v.length;}l=true;}d=false;}else if(f==="FootnoteItem"){if(l){let w=c instanceof ie?c:null;this._add_virtual_text(`
|
|
21
22
|
|
|
22
|
-
`,r,w),r+=2;}let m=r;r=this._map_blocks(
|
|
23
|
+
`,r,w),r+=2;}let m=r;r=this._map_blocks(u,r),r===m?(this.spans.length=h,this._text_chunks.length=_,r=p):l=true;}else if(u instanceof ie){if(l){let b=c instanceof ie?c:null;this._add_virtual_text(`
|
|
23
24
|
|
|
24
|
-
`,r,b),r+=2;}let w=
|
|
25
|
+
`,r,b),r+=2;}let w=Ue(u,o,a);d&&i==="FootnoteItem"&&(w=`[^${n.note_type}-${n.id}]: `+w),w&&(this._add_virtual_text(w,r,u),r+=w.length);let y=r;if(r=this._map_paragraph_content(u,r,o,a),this.clean_view&&r===y&&ks(u._element)){this.spans.length=h,this._text_chunks.length=_,r=p,d=false;continue}d=false,l=true,c=u;}else if(u instanceof ze){if(l){let w=c instanceof ie?c:null;this._add_virtual_text(`
|
|
25
26
|
|
|
26
|
-
`,r,w),r+=2;}let m=r;r=this._map_table(
|
|
27
|
-
`,t,null),t+=1),a&&!this.clean_view&&!this.original_view?(this._add_virtual_text("{++ ",t,null),t+=4):
|
|
28
|
-
`,t,null),t+=1,this._add_virtual_text(p,t,null),t+=p.length;}}}return t}_strip_markdown_formatting(n){let e=n;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(n,e,t,r){let i=e,s={start:i,end:i,text:"",run:null,paragraph:n,part_index:this._current_part_index,sdt_stack:this._spanSdtStack()};this.spans.push(s);let o=new Set,a=Object.create(null),
|
|
29
|
-
`)&&(x||
|
|
30
|
-
`);for(let
|
|
31
|
-
`,k,I]),I+=1),
|
|
32
|
-
`)}_add_virtual_text(n,e,t,r=null,i=false){let s={start:e,end:e+n.length,text:n,run:null,paragraph:t,hyperlink_id:r||void 0,part_index:this._current_part_index,is_image_marker:i||void 0,sdt_stack:this._spanSdtStack()};this.spans.push(s),this._text_chunks.push(n);}_replace_smart_quotes(n){return n.replace(/“/g,'"').replace(/”/g,'"').replace(/‘/g,"'").replace(/’/g,"'")}_make_fuzzy_regex(n){n=this._strip_markdown_formatting(n),n=this._replace_smart_quotes(n);let e=[],t=/(\[_+\])|(\s+)|(['"])|([.,;:\/\-\[\](){}+=$?*!|#^<>\\%&@~`_])/g,r=0,i,s=g(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegExp");for(;(i=t.exec(n))!==null;){let a=n.substring(r,i.index);a&&e.push(s(a));let
|
|
27
|
+
`,r,w),r+=2;}let m=r;r=this._map_table(u,r),r===m?(this.spans.length=h,this._text_chunks.length=_,r=p):l=true,d=false,c=u;}}return r}_wrappingControl(n){let e=ls(n);return e?this._sdt_infos.get(e)??null:null}_anchoredWrapper(n){let e=this._wrappingControl(n);return e&&St(e)?e:null}_map_table(n,e){let t=e,r=0;for(let i of n.rows){let s=i._element,o=$(s,"w:trPr"),a=o?$(o,"w:ins"):null,l=o?$(o,"w:del"):null;if(this.clean_view&&l||this.original_view&&a)continue;r>0&&(this._add_virtual_text(`
|
|
28
|
+
`,t,null),t+=1),a&&!this.clean_view&&!this.original_view?(this._add_virtual_text("{++ ",t,null),t+=4):l&&!this.clean_view&&!this.original_view&&(this._add_virtual_text("{-- ",t,null),t+=4);let d=this._wrappingControl(s),c=this._anchoredWrapper(s);if(c){let h=Me(c);this._add_virtual_text(h,t,null),t+=h.length;}let u=new Set,f=0;for(let h of i.cells){if(u.has(h))continue;u.add(h),f>0&&(this._add_virtual_text(" | ",t,null),t+=3);let _=this._wrappingControl(h._element),p=this._anchoredWrapper(h._element);if(p){let y=Me(p);this._add_virtual_text(y,t,null),t+=y.length;}let m=t,w=[d,_].filter(y=>y!==null);this._current_block_sdt_stack.push(...w);try{t=this._map_blocks(h,t,!0);}finally{for(let y=0;y<w.length;y++)this._current_block_sdt_stack.pop();}if(p){let y=je(p);this._add_virtual_text(y,t,null),t+=y.length;}if(!this.clean_view&&!this.original_view){let{paraId:y,firstP:b}=ts(h._element,t===m);if(y&&b){let v=new ie(b,h);if(this._add_virtual_text("",t,v),m<t){let k="";for(let x=this._text_chunks.length-1;x>=0;x--){let P=this._text_chunks[x];if(P){k=P[P.length-1];break}}k!==" "&&(this._add_virtual_text(" ",t,v),t+=1);}let N=`{#cell:${y}}`;this._add_virtual_text(N,t,v),t+=N.length;}}f+=1;}if(c){let h=je(c);this._add_virtual_text(h,t,null),t+=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,t,null),t+=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,t,null),t+=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(`
|
|
29
|
+
`,t,null),t+=1,this._add_virtual_text(p,t,null),t+=p.length;}}}return t}_strip_markdown_formatting(n){let e=n;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(n,e,t,r){let i=e,s={start:i,end:i,text:"",run:null,paragraph:n,part_index:this._current_part_index,sdt_stack:this._spanSdtStack()};this.spans.push(s);let o=new Set,a=Object.create(null),l=Object.create(null),d=Object.create(null),c=[],u=null,f=["",""],h=["",""],_=null,p=[],m=g(()=>{if(p.length===0)return;let[N,k]=f;N&&(this._add_virtual_text(N,i,n),i+=N.length);for(let[x,P,E,T,I,D,F]of p){if(x==="virtual")this._add_virtual_text(P,i,n,_);else {let M={start:i,end:i+P.length,text:P,run:E,paragraph:n,ins_id:I||void 0,del_id:D||void 0,hyperlink_id:_||void 0,comment_ids:F.length>0?F:void 0,part_index:this._current_part_index,run_offset:T,sdt_stack:this._spanSdtStack(E)};this.spans.push(M),this._text_chunks.push(P);}i+=P.length;}k&&(this._add_virtual_text(k,i,n),i+=k.length),p=[];},"flush_pending_runs"),w=Array.from(yn(n,this._sdt_infos)),y=Cs(n,t,r),b=wn(n,t,r),v=y;for(let N=0;N<w.length;N++){let k=w[N];if(k instanceof Be){let[x,P]=Es(k,b),E=[],T=Ie(k);if(v){if(T===""||/^\s*$/.test(T))continue;v=false;}let I=0,D=g(j=>{let[C,S,A]=As(j);if(!S){E.push(["real",j,k,I]),I+=j.length;return}C&&(E.push(["real",C,k,I]),I+=C.length),x&&E.push(["virtual",x,null,0]),E.push(["real",S,k,I]),I+=S.length,P&&E.push(["virtual",P,null,0]),A&&(E.push(["real",A,k,I]),I+=A.length);},"append_wrapped");if(T.includes(`
|
|
30
|
+
`)&&(x||P)){let j=T.split(`
|
|
31
|
+
`);for(let C=0;C<j.length;C++)C>0&&(E.push(["real",`
|
|
32
|
+
`,k,I]),I+=1),j[C]&&D(j[C]);}else (x||P)&&T?D(T):T&&E.push(["real",T,k,0]);this.clean_view&&Object.keys(l).length>0,this.original_view&&Object.keys(a).length>0;let F=E.map(j=>j[1]).join(""),M=Object.keys(a).pop()||null,B=Object.keys(l).pop()||null;if(F&&!(this.clean_view&&B)&&!(this.original_view&&M)){let j=this.clean_view||this.original_view?["",""]:this._get_wrappers(M,B,o,d),C=[x,P];if(p.length>0&&j[0]===f[0]&&j[1]===f[1]){let S=g(L=>L.length>0&&/^\s+$/.test(L),"isWs"),A=E;if(C[0]===h[0]&&C[1]===h[1]&&!(h[0]===""&&h[1]==="")){let L=p.length-1;for(;L>=0&&p[L][0]==="real"&&S(p[L][1]);)L--;let H=L>=0&&p[L][0]==="virtual"&&p[L][1]===h[1],q=0;for(;q<E.length&&E[q][0]==="real"&&S(E[q][1]);)q++;let z=q<E.length&&E[q][0]==="virtual"&&E[q][1]===C[0];H&&z&&(p.splice(L,1),A=E.slice(0,q).concat(E.slice(q+1)));}let O=Array.from(o);for(let[L,H,q,z]of A)p.push([L,H,q,z,M,B,O]);h=C;}else {m(),f=j,h=C;let S=Array.from(o);for(let[A,O,L,H]of E)p.push([A,O,L,H,M,B,S]);}}if(!this.clean_view&&!this.original_view){(Object.keys(a).length>0||Object.keys(l).length>0||o.size>0||Object.keys(d).length>0)&&c.push([{...a},{...l},new Set(o),{...d}]);let C=false;if(M!==null||B!==null||Object.keys(d).length>0||o.size>0){let A=N+1,O=false,L=Object.keys(a).length,H=Object.keys(l).length,q=Object.keys(d).length,z=new Set(o);for(;A<w.length;){let U=w[A];if(U instanceof Be){if(!Ie(U)){A++;continue}(L>0||H>0||q>0||z.size>0)&&(O=true);break}else {let X=U;X.type==="ins_start"?L++:X.type==="ins_end"?L=Math.max(0,L-1):X.type==="del_start"?H++:X.type==="del_end"?H=Math.max(0,H-1):X.type==="fmt_start"?q++:X.type==="fmt_end"?q=Math.max(0,q-1):X.type==="start"?z.add(X.id):X.type==="end"&&z.delete(X.id);}A++;}O&&(C=true);}if(!C&&c.length>0){let A=this._build_merged_meta_block(c);if(A)if(as(w,N))u=A;else {m(),f=["",""],h=["",""];let O=`{>>${A}<<}`;this._add_virtual_text(O,i,n),i+=O.length;}c=[];}}}else if(_r(k)){v=false;let x=k.info;if(os.includes(k.type)){if(this.clean_view&&Object.keys(l).length>0)continue;let E=k.type==="checkbox_start"?is:k.type==="checkbox_end"?ss:pr(x),T=this.clean_view||this.original_view?["",""]:this._get_wrappers(Object.keys(a).pop()||null,Object.keys(l).pop()||null,o,d);if(p.length>0&&(T[0]!==f[0]||T[1]!==f[1])&&m(),p.length===0&&(f=T),p.push(["virtual",E,null,0,null,null,[]]),h=["",""],k.type==="checkbox_end"&&u){m(),f=["",""];let I=`{>>${u}<<}`;this._add_virtual_text(I,i,n),i+=I.length,u=null;}continue}m(),f=["",""],h=["",""];let P;k.type==="sdt_start"?(P=Me(x),!this.clean_view&&x.showingPlaceholder&&x.placeholderText&&(P+=`{>>placeholder: ${x.placeholderText}<<}`)):P=je(x),this._add_virtual_text(P,i,n),i+=P.length;}else {let x=k;if(v=false,m(),f=["",""],h=["",""],x.type==="start")o.add(x.id);else if(x.type==="end")o.delete(x.id);else if(x.type==="ins_start")a[x.id]=x;else if(x.type==="ins_end")delete a[x.id];else if(x.type==="del_start")l[x.id]=x;else if(x.type==="del_end")delete l[x.id];else if(x.type==="fmt_start")d[x.id]=x;else if(x.type==="fmt_end")delete d[x.id];else if(x.type==="image"){if(!(this.clean_view&&Object.keys(l).length>0||this.original_view&&Object.keys(a).length>0)){let T=`![${(x.date||"image").replace(/\]/g,")").replace(/\n/g," ")}](docx-image:${x.id})`;this._add_virtual_text(T,i,n,null,true),i+=T.length;}}else if(x.type==="footnote"||x.type==="endnote"){m(),f=["",""],h=["",""];let E=`[^${x.type==="footnote"?"fn":"en"}-${x.id}]`;this._add_virtual_text(E,i,n),i+=E.length;}else if(x.type==="hyperlink_start")m(),f=["",""],h=["",""],this._add_virtual_text("[",i,n,x.id),i+=1,_=x.id;else if(x.type==="hyperlink_end"){m(),f=["",""],h=["",""];let P=`](${x.date})`;this._add_virtual_text(P,i,n,x.id),i+=P.length,_=null;}else if(x.type==="xref_start")m(),f=["",""],h=["",""],this._add_virtual_text("[~",i,n),i+=2;else if(x.type==="xref_end"){m(),f=["",""],h=["",""];let P=`~](#${x.id})`;this._add_virtual_text(P,i,n),i+=P.length;}else if(x.type==="bookmark"){m(),f=["",""],h=["",""];let P=`{#${x.id}}`;this._add_virtual_text(P,i,n),i+=P.length;}}}if(m(),c.length>0){let N=this._build_merged_meta_block(c);if(N){let k=`{>>${N}<<}`;this._add_virtual_text(k,i,n),i+=k.length;}}return i}_get_wrappers(n,e,t,r){return e?["{--","--}"]:n?["{++","++}"]:t.size>0||Object.keys(r).length>0?["{==","==}"]:["",""]}_build_merged_meta_block(n){let e=[],t=[],r=new Set,i=Ps(n),s=g(o=>i[o]?` (pairs with ${i[o]})`:"","pairSuffix");for(let[o,a,l,d]of n){for(let[u,f]of Object.entries(o)){let h=`Chg:${u}`;if(!r.has(h)){let _=f.author||"Unknown";e.push(`[${h} insert] ${_}${s(u)}`),r.add(h);}}for(let[u,f]of Object.entries(a)){let h=`Chg:${u}`;if(!r.has(h)){let _=f.author||"Unknown";e.push(`[${h} delete] ${_}${s(u)}`),r.add(h);}}for(let[u,f]of Object.entries(d)){let h=`Chg:${u}`;if(!r.has(h)){let _=f.author||"Unknown";e.push(`[${h} format] ${_}`),r.add(h);}}let c=Array.from(l).sort();for(let u of c){if(!this.comments_map[u])continue;let f=`Com:${u}`;if(!r.has(f)){let h=this.comments_map[u],_=`[${f}] ${h.author}`;h.date&&(_+=` @ ${h.date}`),h.resolved&&(_+="(RESOLVED)"),t.push(`${_}: ${fs(h.text)}`),r.add(f);}}}return [...e,...t].join(`
|
|
33
|
+
`)}_add_virtual_text(n,e,t,r=null,i=false){let s={start:e,end:e+n.length,text:n,run:null,paragraph:t,hyperlink_id:r||void 0,part_index:this._current_part_index,is_image_marker:i||void 0,sdt_stack:this._spanSdtStack()};this.spans.push(s),this._text_chunks.push(n);}_replace_smart_quotes(n){return n.replace(/“/g,'"').replace(/”/g,'"').replace(/‘/g,"'").replace(/’/g,"'")}_make_fuzzy_regex(n){n=this._strip_markdown_formatting(n),n=this._replace_smart_quotes(n);let e=[],t=/(\[_+\])|(\s+)|(['"])|([.,;:\/\-\[\](){}+=$?*!|#^<>\\%&@~`_])/g,r=0,i,s=g(a=>a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegExp");for(;(i=t.exec(n))!==null;){let a=n.substring(r,i.index);a&&e.push(s(a));let l=i[1],d=i[2],c=i[3],u=i[4];l?e.push("\\[_+\\]"):d?(e.push("(?:\\*\\*|__|\\*|_)?"),e.push("\\s+"),e.push("(?:\\*\\*|__|\\*|_)?")):c?c==="'"?e.push("[\u2018\u2019']"):e.push('["\u201C\u201D]'):u&&(e.push("(?:\\*\\*|__|\\*|_)?"),e.push(s(u)),e.push("(?:\\*\\*|__|\\*|_)?")),r=t.lastIndex;}let o=n.substring(r);return o&&e.push(s(o)),e.join("")}_get_plain_projection(){if(this._plain_projection===null){let n=[],e=[];for(let t of this.spans)if(!(t.run===null&&t.paragraph!==null&&Ol.has(t.text))&&!Dl(t)){n.push(t.text);for(let r=t.start;r<t.end;r++)e.push(r);}this._plain_projection=[n.join(""),e];}return this._plain_projection}_find_plain_projection_matches(n){let[e,t]=this._get_plain_projection();if(e.length===this.full_text.length)return [];let r=this._replace_smart_quotes(this._strip_markdown_formatting(n));if(!r)return [];let i=this._replace_smart_quotes(e),s=[],o=0;for(;;){let a=i.indexOf(r,o);if(a===-1)break;let l=a+r.length,[d,c]=this._widen_to_anchor_markers(t[a],t[l-1]+1);s.push([d,c-d]),o=l;}return s}_widen_to_anchor_markers(n,e){let t=this.full_text.lastIndexOf(`
|
|
33
34
|
`,n-1)+1,r=this.full_text.indexOf(`
|
|
34
|
-
`,e);r===-1&&(r=this.full_text.length);let i=this.full_text.substring(t,r);for(let s of i.matchAll(
|
|
35
|
+
`,e);r===-1&&(r=this.full_text.length);let i=this.full_text.substring(t,r);for(let s of i.matchAll(ir)){let o=t+s.index,a=o+s[0].length;o<e&&a>n&&(n=Math.min(n,o),e=Math.max(e,a));}return [n,e]}anchor_markers_in_range(n,e){let[t,r]=this._get_plain_projection(),i=n+e,s=qt(r,n),o=qt(r,i),a=r.slice(s,o),l=[],d=this.full_text.substring(n,i);for(let c of d.matchAll(ir)){let u=n+c.index;l.push([c[0],qt(a,u),qt(a,u+c[0].length)]);}return [t.substring(s,o),l]}range_is_virtual_only(n,e){let t=n+e,r=this.spans.filter(i=>i.end>n&&i.start<t);return r.some(i=>i.run!==null)?false:!r.some(i=>i.run===null&&i.text.startsWith("{#"))}drop_virtual_only_matches(n){return n.filter(([e,t])=>!this.range_is_virtual_only(e,t))}find_match_index(n,e=false){if(e){try{let l=Xa(n,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 Le)throw l}return [-1,0]}let t=0;for(;;){let l=this.full_text.indexOf(n,t);if(l===-1)break;if(!this.range_is_virtual_only(l,n.length))return [l,n.length];t=l+1;}let r=this._replace_smart_quotes(this.full_text),i=this._replace_smart_quotes(n),s=r.indexOf(i);if(s!==-1)return [s,n.length];let o=this._strip_markdown_formatting(n);if(this.full_text.includes(o))return s=this.full_text.indexOf(o),[s,o.length];let a=this._find_plain_projection_matches(n);if(a.length>0)return a[0];try{let l=new RegExp(this._make_fuzzy_regex(n),"g");for(let d of this.full_text.matchAll(l))if(!this.range_is_virtual_only(d.index,d[0].length))return [d.index,d[0].length]}catch{}return [-1,0]}find_all_match_indices(n,e=false){if(!n)return [];if(e){try{let l=qa(n,this.full_text);if(l.length>0)return l.map(d=>[d.start,d.end-d.start])}catch(l){if(l instanceof Le)throw l}return []}let t=g((l,d)=>{let c=[];if(!d)return c;let u=0;for(;;){let f=l.indexOf(d,u);if(f===-1)break;c.push([f,d.length]),u=f+d.length;}return c},"findAllLiteral"),r=t(this.full_text,n);if(r.length>0)return r;let i=this._replace_smart_quotes(this.full_text),s=this._replace_smart_quotes(n);if(r=t(i,s),r.length>0)return r;let o=this._strip_markdown_formatting(n);if(r=t(this.full_text,o),r.length>0)return r;let a=this._find_plain_projection_matches(n);if(a.length>0)return a;try{let l=new RegExp(this._make_fuzzy_regex(n),"g"),d=[...this.full_text.matchAll(l)];if(d.length>0)return d.map(c=>[c.index,c[0].length])}catch{}return []}find_target_runs(n){let[e,t]=this.find_match_index(n);return e===-1?[]:this._resolve_runs_at_range(e,e+t)}find_target_runs_by_index(n,e,t=true){return this._resolve_runs_at_range(n,n+e,t)}get_virtual_spans_in_range(n,e){let t=n+e;return this.spans.filter(r=>r.run===null&&r.text===`
|
|
35
36
|
|
|
36
|
-
`&&r.start>=n&&r.end<=t)}_resolve_runs_at_range(n,e,t=true){let r=this.spans.filter(m=>m.end>n&&m.start<e);if(r.length===0)return [];let i=r.filter(m=>m.run!==null);if(i.length===0)return [];let s=[];for(let m of i)s.some(w=>w===m.run)||s.push(m.run);let o=false,a=i[0],
|
|
37
|
-
`)?
|
|
38
|
-
`)?w.setAttribute("xml:space","preserve"):w.removeAttribute("xml:space"),s.appendChild(w),
|
|
37
|
+
`&&r.start>=n&&r.end<=t)}_resolve_runs_at_range(n,e,t=true){let r=this.spans.filter(m=>m.end>n&&m.start<e);if(r.length===0)return [];let i=r.filter(m=>m.run!==null);if(i.length===0)return [];let s=[];for(let m of i)s.some(w=>w===m.run)||s.push(m.run);let o=false,a=i[0],l=0,d=Math.max(n,a.start)-a.start+(a.run_offset||0);if(d>0){let m=s[0],[,w]=this._split_run_at_index(m,d);for(let y=0;y<s.length;y++)s[y]===m&&(s[y]=w);o=true,l=d;}let c=i[i.length-1],u=a.run===c.run,f=s[s.length-1],_=Math.min(c.end,e)-c.start+(c.run_offset||0);u&&l>0&&(_-=l);let p=Ie(f);if(_>0&&_<p.length){let[m]=this._split_run_at_index(f,_);s[s.length-1]=m,o=true;}return o&&t&&this._build_map(),s}get_insertion_anchor(n,e=true){let t=this.spans.filter(s=>s.end===n);if(t.length>0){for(let s=t.length-1;s>=0;s--)if(t[s].run)return [t[s].run,t[s].paragraph];for(let s=t.length-1;s>=0;s--){let o=t[s].paragraph;if(o){for(let a=this.spans.length-1;a>=0;a--){let l=this.spans[a];if(l.end<=n&&l.run!==null&&l.paragraph!==null&&l.paragraph._element===o._element)return [l.run,l.paragraph]}return [null,o]}}}let r=this.spans.filter(s=>s.start<n&&n<s.end);if(r.length>0){let s=r[0];if(s.run===null)return s.paragraph===null?this.get_insertion_anchor(s.end,e):[null,s.paragraph];{let o=n-s.start+(s.run_offset||0),[a]=this._split_run_at_index(s.run,o);return e&&this._build_map(),[a,s.paragraph]}}if(n===0&&this.spans.length>0){for(let s of this.spans)if(s.run)return [s.run,s.paragraph];for(let s of this.spans)if(s.paragraph)return [null,s.paragraph];return [null,null]}let i=this.spans.filter(s=>s.end<n);if(i.length>0){for(let s=i.length-1;s>=0;s--)if(i[s].run)return [i[s].run,i[s].paragraph];for(let s=i.length-1;s>=0;s--)if(i[s].paragraph)return [null,i[s].paragraph]}return [null,null]}_split_run_at_index(n,e){let t=Ie(n);t.substring(0,e);t.substring(e);let s=n._element.cloneNode(true),o=Array.from(s.childNodes);for(let u of o)u.nodeType===1&&u.tagName==="w:rPr"||s.removeChild(u);let a=g(u=>{let f=u.tagName;return f===Mt||f===_s?(u.textContent||"").length:f===ms||f==="w:ptab"||f==="w:noBreakHyphen"||f===gs||f===ws?1:0},"_child_len"),l=0,d=Array.from(n._element.childNodes);for(let u of d){if(u.nodeType===1&&u.tagName==="w:rPr")continue;let f=u.nodeType===1?a(u):0;if(f===0)l<e||(n._element.removeChild(u),s.appendChild(u));else if(l+f<=e)l+=f;else if(l>=e)n._element.removeChild(u),s.appendChild(u),l+=f;else {let h=e-l,_=u.textContent||"",p=_.substring(0,h),m=_.substring(h);u.textContent=p,p.startsWith(" ")||p.endsWith(" ")||p.includes(`
|
|
38
|
+
`)?u.setAttribute("xml:space","preserve"):u.removeAttribute("xml:space");let w=u.cloneNode(true);w.textContent=m,m.startsWith(" ")||m.endsWith(" ")||m.includes(`
|
|
39
|
+
`)?w.setAttribute("xml:space","preserve"):w.removeAttribute("xml:space"),s.appendChild(w),l+=f;}}n._element.parentNode&&n._element.parentNode.insertBefore(s,n._element.nextSibling);let c=new Be(s,n._parent);return c.sdtStack=n.sdtStack,[n,c]}get_context_at_range(n,e){let t=this.spans.filter(r=>r.run&&r.end>n&&r.start<e);return t.length>0?t[0]:null}};function ai(n){return typeof n=="string"?n?[{text:n}]:[]:(n||[]).filter(e=>e&&e.text)}g(ai,"comment_entries");function Rl(n){if(n==null||typeof n=="string")return null;if(!Array.isArray(n))return "`comment` must be a string or a list of {text, author?} objects.";for(let[e,t]of n.entries()){if(!t||typeof t!="object"||typeof t.text!="string")return `\`comment[${e}]\` must be an object with a string \`text\` (and an optional string \`author\`).`;let r=t.author;if(r!=null&&typeof r!="string")return `\`comment[${e}].author\` must be a string.`}return null}g(Rl,"describe_invalid_comment");function li(n){let e=0,t=0,r=n.length,i=g(s=>/[a-zA-Z0-9]/.test(s),"isAlnum");for(;t<r;){if(n[t]==="_"){let s=false;(t>0&&n[t-1]==="_"||t<r-1&&n[t+1]==="_")&&(s=true);let o=false;t>0&&i(n[t-1])&&t<r-1&&i(n[t+1])&&(o=true),!s&&!o&&e++;}t++;}return e}g(li,"_count_standalone_underscores");var ci=new Set([".",",",";","!","?"]),Xt=g(n=>/[\p{L}\p{N}_]/u.test(n),"isWordChar");function Ml(n,e,t){for(let r of [n,e]){let i=r[t-1],s=r[t];if(!(/\s/.test(i)||/\s/.test(s))&&!(Xt(i)&&ci.has(s)&&(t+1>=r.length||!Xt(r[t+1])))&&!(Xt(s)&&ci.has(i)&&(t<2||!Xt(r[t-2]))))return true}return false}g(Ml,"splitsPrefixToken");function ft(n,e){if(!n||!e)return [0,0];let t=g(d=>/\s/.test(d),"isSpace"),r=0,i=Math.min(n.length,e.length);for(;r<i&&n[r]===e[r];)r++;if(r<n.length&&r<e.length)for(;r>0&&Ml(n,e,r);)r--;for(;r>0;){if(r<n.length){let p=n.substring(r-1,r+1);if(p==="**"||p==="__"){r--;continue}}let d=n.substring(0,r),c=(d.match(/\*\*/g)||[]).length,u=(d.match(/__/g)||[]).length,f=li(d);if(c%2!==0){r=d.lastIndexOf("**");continue}if(u%2!==0){r=d.lastIndexOf("__");continue}if(f%2!==0){let p=d.length-1,m=g(w=>/[a-zA-Z0-9]/.test(w),"isAlnum");for(;p>=0;){if(d[p]==="_"&&(p===0||d[p-1]!=="_")&&(p===d.length-1||d[p+1]!=="_")&&!(p>0&&m(d[p-1])&&p<d.length-1&&m(d[p+1]))){r=p;break}p--;}continue}let h=r,_=false;for(;h>0;){let p=n[h-1];if(p==="#"){for(r=h-1;r>0&&n[r-1]!==`
|
|
39
40
|
`;)r--;_=true;break}if(p===`
|
|
40
|
-
`)break;h--;}if(!_)break}let s=0,o=n.length-r,a=e.length-r,
|
|
41
|
-
`);return e.length>0&&e.every(t=>t.includes(" | "))}g(
|
|
41
|
+
`)break;h--;}if(!_)break}let s=0,o=n.length-r,a=e.length-r,l=Math.min(o,a);for(;s<l&&n[n.length-1-s]===e[e.length-1-s];)s++;if(s>0)for(;s>0;){let d=false;s<n.length&&(d=!t(n[n.length-1-s])&&!t(n[n.length-s]));let c=false;if(s<e.length&&(c=!t(e[e.length-1-s])&&!t(e[e.length-s])),d||c)s--;else break}for(;s>0;){let d=n.length-s;if(d>0){let _=n.substring(d-1,d+1);if(_==="**"||_==="__"){s--;continue}}let c=n.substring(n.length-s),u=(c.match(/\*\*/g)||[]).length,f=(c.match(/__/g)||[]).length,h=li(c);if(u%2!==0){s-=c.indexOf("**")+2;continue}if(f%2!==0){s-=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]))){s-=_+1;break}_++;}continue}break}s>0&&/^\s+$/.test(n.substring(n.length-s))&&(s=0);for(let d of ["**","__","_"]){let c=d.length,u=n.substring(r,n.length-s),f=e.substring(r,e.length-s);u.startsWith(d)&&f.startsWith(d)&&u.endsWith(d)&&f.endsWith(d)&&u.length>=2*c&&f.length>=2*c&&(r+=c,s+=c);}return [r,s]}g(ft,"trim_common_context");function jl(n,e){let t=[],r=Object.create(null),i=/(\s+|[\p{L}\p{N}_]+|[^\p{L}\p{N}_\s])/gu,s=g(o=>{let a=o.split(i).filter(Boolean),l="";for(let d of a)if(d in r)l+=String.fromCharCode(r[d]);else {let c=t.length;r[d]=c,t.push(d),l+=String.fromCharCode(c);}return l},"encode_text");return [s(n),s(e),t]}g(jl,"_words_to_chars");function At(n,e){let t=new br.default.diff_match_patch;t.Diff_Timeout=2;let[r,i,s]=jl(n,e),o=t.diff_main(r,i,false);t.diff_cleanupSemantic(o);for(let c=0;c<o.length;c++){let u=o[c][1],f="";for(let h=0;h<u.length;h++)f+=s[u.charCodeAt(h)];o[c][1]=f;}let a=[],l=0,d=null;for(let[c,u]of o)if(c===0){if(d){let[f,h]=d;a.push({type:"modify",target_text:h,new_text:"",comment:"Diff: Text deleted",_match_start_index:f}),d=null;}l+=u.length;}else if(c===-1)d=[l,u],l+=u.length;else if(c===1)if(d){let[f,h]=d;a.push({type:"modify",target_text:h,new_text:u,comment:"Diff: Replacement",_match_start_index:f}),d=null;}else a.push({type:"modify",target_text:"",new_text:u,comment:"Diff: Text inserted",_match_start_index:l});if(d){let[c,u]=d;a.push({type:"modify",target_text:u,new_text:"",comment:"Diff: Text deleted",_match_start_index:c});}return a}g(At,"generate_edits_from_text");function xr(n,e){let t=n.length,r=e.length,i=[];for(let h=0;h<=t;h++)i.push(new Int32Array(r+1));for(let h=t-1;h>=0;h--)for(let _=r-1;_>=0;_--)i[h][_]=n[h]===e[_]?i[h+1][_+1]+1:Math.max(i[h+1][_],i[h][_+1]);let s=[],o=0,a=0,l=0,d=0,c=0,u=0,f=g(()=>{if(c===0&&u===0)return;let h=c>0&&u>0?"replace":c>0?"delete":"insert";s.push([h,l,l+c,d,d+u]),c=0,u=0;},"flushPending");for(;o<t||a<r;)if(o<t&&a<r&&n[o]===e[a]){f();let h=o,_=a;for(;o<t&&a<r&&n[o]===e[a];)o++,a++;s.push(["equal",h,o,_,a]);}else c===0&&u===0&&(l=o,d=a),a<r&&(o===t||i[o][a+1]>=i[o+1][a])?(u++,a++):(c++,o++);return f(),s}g(xr,"_sequence_opcodes");function Gn(n,e){let t=n.trim().split(/\s+/).filter(Boolean),r=e.trim().split(/\s+/).filter(Boolean);if(t.length===0&&r.length===0)return 1;if(t.length===0||r.length===0)return 0;let i=xr(t,r),s=0;for(let[o,a,l]of i)o==="equal"&&(s+=l-a);return 2*s/(t.length+r.length)}g(Gn,"_word_similarity_ratio");function dt(n){let e=n.split(`
|
|
42
|
+
`);return e.length>0&&e.every(t=>t.includes(" | "))}g(dt,"_is_table_blob");function di(n,e){let t=n.split(`
|
|
42
43
|
`),r=e.split(`
|
|
43
|
-
`);if(t.length!==r.length)return null;let i=[];for(let s=0;s<t.length;s++)t[s]!==r[s]&&i.push({type:"modify",target_text:t[s],new_text:r[s],comment:"Diff: Table row modified",_is_table_edit:true});return i}g(
|
|
44
|
+
`);if(t.length!==r.length)return null;let i=[];for(let s=0;s<t.length;s++)t[s]!==r[s]&&i.push({type:"modify",target_text:t[s],new_text:r[s],comment:"Diff: Table row modified",_is_table_edit:true});return i}g(di,"_table_blob_row_edits");function Bl(n){let e=[];for(let t of n){let r=t.target_text||"",i=t.new_text||"",s=t._match_start_index;if(s==null||!r.includes(`
|
|
44
45
|
|
|
45
46
|
`)||r.split(`
|
|
46
47
|
|
|
@@ -48,85 +49,95 @@ ${n.note_type==="fn"?"## Footnotes":"## Endnotes"}`;this._add_virtual_text(f,r,n
|
|
|
48
49
|
|
|
49
50
|
`).length-1){e.push(t);continue}let o=r.split(`
|
|
50
51
|
|
|
51
|
-
`);if(o.length<2||!o[0].trim()||!o[o.length-1].trim()){e.push(t);continue}let a=s;for(let
|
|
52
|
+
`);if(o.length<2||!o[0].trim()||!o[o.length-1].trim()){e.push(t);continue}let a=s;for(let l of o.slice(0,-1))e.push({type:"modify",target_text:l+`
|
|
52
53
|
|
|
53
|
-
`,new_text:"",comment:t.comment||"Diff: Text deleted",_match_start_index:a}),a+=
|
|
54
|
+
`,new_text:"",comment:t.comment||"Diff: Text deleted",_match_start_index:a}),a+=l.length+2;e.push({type:"modify",target_text:o[o.length-1],new_text:i,comment:t.comment,_match_start_index:a});}return e}g(Bl,"_split_cross_paragraph_hunks");function tn(n,e){let t=n.trimEnd(),r=n.slice(t.length);e=e.trimEnd()+r;let s=n.split(`
|
|
54
55
|
|
|
55
56
|
`),o=e.split(`
|
|
56
57
|
|
|
57
|
-
`),a=[],
|
|
58
|
+
`),a=[],l=0;for(let u of s)a.push(l),l+=u.length+2;let d=xr(s,o),c=[];for(let[u,f,h,_,p]of d){if(u==="equal")continue;let m=f<a.length?a[f]:n.length;if(u==="delete")if(h<s.length){let w=m;for(let y=f;y<h;y++){let b=s[y]+`
|
|
58
59
|
|
|
59
|
-
`;
|
|
60
|
+
`;c.push({type:"modify",target_text:b,new_text:"",comment:"Diff: Text deleted",_match_start_index:w}),w+=b.length;}}else {let w=s.slice(f,h).join(`
|
|
60
61
|
|
|
61
62
|
`),y=m;f>0&&(w=`
|
|
62
63
|
|
|
63
|
-
`+w,y-=2),
|
|
64
|
+
`+w,y-=2),c.push({type:"modify",target_text:w,new_text:"",comment:"Diff: Text deleted",_match_start_index:y});}else if(u==="insert"){let w=o.slice(_,p).join(`
|
|
64
65
|
|
|
65
66
|
`);f<s.length?w=w+`
|
|
66
67
|
|
|
67
68
|
`:w=`
|
|
68
69
|
|
|
69
|
-
`+w,
|
|
70
|
+
`+w,c.push({type:"modify",target_text:"",new_text:w,comment:"Diff: Text inserted",_match_start_index:m});}else if(u==="replace"){if(h-f===p-_){for(let C=0;C<h-f;C++){let S=s[f+C],A=o[_+C];if(S===A)continue;let O=a[f+C],L=dt(S)&&dt(A)?di(S,A):null;if(L!==null){c.push(...L);continue}if(Gn(S,A)<.35)c.push({type:"modify",target_text:S,new_text:A,comment:"Diff: Replacement",_match_start_index:O});else {let H=At(S,A);for(let q of H)q._match_start_index=(q._match_start_index||0)+O,c.push(q);}}continue}let w=s.slice(f,h),y=o.slice(_,p);if(w.some(dt)||y.some(dt)){let C=w.join(`
|
|
70
71
|
|
|
71
|
-
`),y
|
|
72
|
+
`),S=y.join(`
|
|
72
73
|
|
|
73
|
-
`),
|
|
74
|
-
`).slice(-t));let l=[];for(l.push(...u.map(f=>` ${f}`));a<s.length;){let[f,h]=s[a],_=h.replace(/\n$/,"").split(`
|
|
75
|
-
`);if(f===0){if(_.length>t*2)break;l.push(..._.map(p=>` ${p}`));}else {let p=f===-1?"-":"+";l.push(..._.map(m=>`${p}${m}`));}a++;}let d=[];a<s.length&&s[a][0]===0&&(d=s[a][1].replace(/\n$/,"").split(`
|
|
76
|
-
`).slice(0,t)),l.push(...d.map(f=>` ${f}`)),o.push("@@ ... @@"),o.push(...l);}return o.length===2?"":o.join(`
|
|
77
|
-
`)}g(ks,"create_unified_diff");var nn=/\{\+\+|\{--|\{==|\{>>|\+\+\}|--\}|==\}|<<\}/g,Pl={"{++":"++}","{--":"--}","{==":"==}","{>>":"<<}"};function ni(n){if(!n)return true;if(/\{[=+\-><]?$/.test(n)||/^[=+\-><]?\}/.test(n))return false;let e=[];nn.lastIndex=0;let t;for(;(t=nn.exec(n))!==null;){let r=t[0];if(r.startsWith("{"))e.push(r);else if(e.length===0||Pl[e.pop()]!==r)return false}return e.length===0}g(ni,"_critic_payload_atomic");function Es(n,e,t,r){let i=true;for(;i;){i=false;for(let s of [n,e]){let o=s.length-r;nn.lastIndex=0;let a;for(;(a=nn.exec(s))!==null;){let c=a.index,u=a.index+a[0].length;if(t>c&&t<u&&(t=c,i=true),o>c&&o<u){r=s.length-u,i=true;break}}}}return [Math.max(0,t),Math.max(0,r)]}g(Es,"_clamp_trim_outside_critic_tokens");function Tl(n,e){let[t,r]=lt(n,e);return [t,r]=Es(n,e,t,r),[n.substring(t,n.length-r),e.substring(t,e.length-r)]}g(Tl,"_word_patch_displays");function $l(n,e){let t=[],r=0;for(;r<n.length;){let i=n[r].target_text||"",s=n[r].new_text||"",o=n[r]._match_start_index||0,a=r+1;for(;;){let[c,u]=Tl(i,s);if(ni(c)&&ni(u)||a>=n.length)break;let l=n[a],d=l._match_start_index||0,f=o+i.length,h=d>=f?e.substring(f,d):"";i=i+h+(l.target_text||""),s=s+h+(l.new_text||""),a++;}a>r+1?t.push({...n[r],target_text:i,new_text:s,_match_start_index:o}):t.push(n[r]),r=a;}return t}g($l,"_merge_critic_split_hunks");function As(n,e,t="Original",r="Modified"){let i=$l(tn(n,e),n),s=[`--- ${t}`,`+++ ${r}`,""],o=40;for(let a of i){let c=a._match_start_index||0,u=a.target_text||"",l=a.new_text||"",[d,f]=lt(u,l);[d,f]=Es(u,l,d,f);let h=u.length-f,_=l.length-f,p=u.substring(d,h),m=l.substring(d,_),w=c+d,y=w+p.length,b=Math.max(0,w-o),v=n.substring(b,w);b>0&&(v="..."+v);let N=Math.min(n.length,y+o),k=n.substring(y,N);N<n.length&&(k=k+"..."),v=v.replace(/\n/g," ").replace(/\r/g,""),k=k.replace(/\n/g," ").replace(/\r/g,""),s.push("@@ Word Patch @@"),s.push(` ${v}`),p&&s.push(`- ${p}`),m&&s.push(`+ ${m}`),s.push(` ${k}`),s.push("");}return s.join(`
|
|
78
|
-
`)}g(As,"create_word_patch_diff");var ri=19e3;var Sl="<!-- READONLY_BOUNDARY_START -->";var ii={"{++":"++}","{--":"--}","{==":"==}","{>>":"<<}"},Il=/\bChg:(\d+)\b/g;function ut(n){if(!n)return ["",""];let e=n.indexOf(Sl);if(e===-1)return [n,""];let t=n.lastIndexOf(`
|
|
79
|
-
`,e)+1,r=n.substring(0,t).trimEnd(),i=n.substring(t);return [r,i]}g(ut,"split_structural_appendix");function dt(n,e=""){if(!n){let u=e?e.trim():"";return {pages:[{page:1,total_pages:1,has_next:false,has_prev:false,tracked_change_count:si(u),page_content:u}],total_pages:1,body_pages:[""],body_page_offsets:[0]}}let t=Ol(n),[r,i]=Ml(t),s;if(e&&e.trim()){let c=e.trim();s=r.map(u=>u?`${u}
|
|
74
|
+
`),A=At(C,S);for(let O of A)O._match_start_index=(O._match_start_index||0)+m,c.push(O);continue}let b=w.length,v=y.length,N=Array.from({length:b+1},()=>new Array(v+1).fill(0)),k=Array.from({length:b+1},()=>new Array(v+1).fill(null)),x=Array.from({length:b},(C,S)=>Array.from({length:v},(A,O)=>Gn(w[S],y[O])));for(let C=b-1;C>=0;C--)for(let S=v-1;S>=0;S--){let A=N[C+1][S],O=["delete",C,S];N[C][S+1]>A&&(A=N[C][S+1],O=["insert",C,S]),x[C][S]>=.35&&x[C][S]+N[C+1][S+1]>=A&&(A=x[C][S]+N[C+1][S+1],O=["pair",C,S]),N[C][S]=A,k[C][S]=O;}let P=[],E=0,T=0;for(;E<b||T<v;)if(E===b)P.push(["insert",E,T]),T++;else if(T===v)P.push(["delete",E,T]),E++;else {let C=k[E][T];P.push(C),C[0]==="pair"?(E++,T++):C[0]==="delete"?E++:T++;}let I=[],D=0;for(;D<P.length;)if(P[D][0]==="pair")I.push(["pair",P[D][1],[P[D][2]]]),D++;else {let C=[],S=[];for(;D<P.length&&(P[D][0]==="delete"||P[D][0]==="insert");)P[D][0]==="delete"?C.push(P[D][1]):S.push(P[D][2]),D++;let A=Math.min(C.length,S.length);for(let O=0;O<A;O++)I.push(["pair",C[O],[S[O]]]);for(let O=A;O<C.length;O++)I.push(["delete",C[O],[]]);if(S.length>A){let O=S.slice(A);I.length>0&&I[I.length-1][0]==="pair"?I[I.length-1][2].push(...O):I.push(["pending_insert",-1,O]);}}let F=[],M=[];for(let C of I)C[0]==="pending_insert"?M.push(...C[2]):C[0]==="pair"&&M.length>0?(F.push(["pair",C[1],[...M,...C[2]]]),M=[]):F.push(C);if(M.length>0&&F.length>0){for(let C=F.length-1;C>=0;C--)if(F[C][0]==="pair"){F[C][2].push(...M),M=[];break}}let B=-1;for(let C of F)C[0]==="pair"&&C[1]>B&&(B=C[1]);let j=h<s.length;for(let[C,S,A]of F){let O=f+S,L=a[O],H=s[O];if(C==="delete")if(j||S<B)c.push({type:"modify",target_text:H+`
|
|
80
75
|
|
|
81
|
-
|
|
82
|
-
`&&i+1<s&&n[i+1]===`
|
|
83
|
-
`&&Object.values(e).every(c=>c===0)){let c=n.substring(r,i);c&&t.push([c,r]);let u=i;for(;u<s&&n[u]===`
|
|
84
|
-
`;)u++;i=u,r=i;continue}i++;}}if(r<s){let o=n.substring(r,s);o&&t.push([o,r]);}return t}g(Dl,"_split_on_safe_paragraph_breaks");function Rl(n){if(!n.length)return n;let e=[],t=0;for(;t<n.length;){let[r,i]=n[t],s=r.trimStart();if(!(s.startsWith("## Footnotes")||s.startsWith("## Endnotes"))){e.push([r,i]),t++;continue}let a=r,c=t+1;for(;c<n.length;){let[u]=n[c],l=u.trimStart();if(l.startsWith("[^fn-")||l.startsWith("[^en-"))a=`${a}
|
|
76
|
+
`,new_text:"",comment:"Diff: Text deleted",_match_start_index:L});else {let q=O>0?`
|
|
85
77
|
|
|
86
|
-
|
|
78
|
+
`+H:H,z=O>0?L-2:L;c.push({type:"modify",target_text:q,new_text:"",comment:"Diff: Text deleted",_match_start_index:z});}else if(C==="pair"){let q=A.map(z=>y[z]).join(`
|
|
87
79
|
|
|
88
|
-
`)),
|
|
89
|
-
`)}g(Bl,"format_ambiguity_error");var Fl="3.1.0";function ee(n,e){let t=[],r=n.getElementsByTagName("*");for(let i=0;i<r.length;i++){let s=r[i].tagName;(s===e||s.endsWith(":"+e))&&t.push(r[i]);}return t}g(ee,"findDescendantsByLocalName");function Wl(n){let e=0;function t(o,a){let c=o?o.toString():"",u=a?a.toString():"";return c===u}g(t,"areRunsIdentical");function r(o){let a=["w:t","w:tab","w:br","w:cr","w:delText","w:rPr"];for(let c=0;c<o.childNodes.length;c++){let u=o.childNodes[c];if(u.nodeType===1){let l=u.tagName;if(!a.includes(l))return true}}return false}g(r,"hasSpecialContent");function i(o){let a=Array.from(o.childNodes).filter(u=>u.nodeType===1),c=0;for(;c<a.length-1;){let u=a[c],l=a[c+1];if(u.tagName==="w:r"&&l.tagName==="w:r"&&!r(u)&&!r(l)){let d=S(u,"w:rPr"),f=S(l,"w:rPr");if(t(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(l.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||"",y=m+w;h.textContent=y,y.trim()!==y&&h.setAttribute("xml:space","preserve");}else u.appendChild(p),(p.tagName==="w:t"||p.tagName==="w:delText")&&(h=p);o.removeChild(l),a.splice(c+1,1),e++;continue}}["w:ins","w:del","w:hyperlink","w:sdt","w:smartTag","w:fldSimple","w:sdtContent"].includes(u.tagName)&&i(u),c++;}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 s=R(n.element,"w:p");for(let o of s)i(o);return e?[`Adjacent identical runs coalesced: ${e}`]:[]}g(Wl,"coalesce_runs");function Ll(n){let e=0,t=["w:rsidR","w:rsidRPr","w:rsidRDefault","w:rsidP","w:rsidDel","w:rsidSect","w:rsidTr"],r=n.element.getElementsByTagName("*");for(let s=0;s<r.length;s++)for(let o of t)r[s].hasAttribute(o)&&(r[s].removeAttribute(o),e++);let i=R(n.element,"w:rsids");for(let s of i)s.parentNode&&(s.parentNode.removeChild(s),e++);return e?[`rsid attributes: ${e} removed`]:[]}g(Ll,"strip_rsid");function zl(n){let e=0,t=["w14:paraId","w14:textId"],r=n.element.getElementsByTagName("*");for(let i=0;i<r.length;i++)for(let s of t)r[i].hasAttribute(s)&&(r[i].removeAttribute(s),e++);return e?[`Paragraph/text IDs: ${e} removed`]:[]}g(zl,"strip_para_ids");function Ul(n){let e=R(n.element,"w:proofErr");return e.forEach(t=>t.parentNode?.removeChild(t)),e.length?[`Spell check markers: ${e.length} removed`]:[]}g(Ul,"strip_proof_errors");function Hl(n){let e=0;for(let t of ["w:rPr","w:pPr"]){let r=R(n.element,t);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(Hl,"strip_empty_properties");function Xl(n){let e=0,t=R(n.element,"w:rPr");for(let r of t)if(S(r,"w:vanish")||S(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(Xl,"strip_hidden_text");function ai(n){let e=R(n.element,"w:ins").length,t=R(n.element,"w:del").length,r=R(n.element,"w:rPrChange").length+R(n.element,"w:pPrChange").length+R(n.element,"w:sectPrChange").length;return [e,t,r]}g(ai,"count_tracked_changes");function ql(n){let e=new Set;for(let t of ["w:ins","w:del","w:rPrChange","w:pPrChange","w:sectPrChange"])for(let r of R(n.element,t)){let i=r.getAttribute("w:author");i&&e.add(i);}return e}g(ql,"get_track_change_authors");function li(n){let e=[],t=R(n,"w:t");for(let i of t)i.textContent&&e.push(i.textContent);let r=R(n,"w:delText");for(let i of r)i.textContent&&e.push(i.textContent);return e.join("")}g(li,"_getElementText");function We(n,e=60){let t=n.replace(/\n/g," ").trim();return t.length<=e?t:t.substring(0,e-3)+"..."}g(We,"_truncate");function ci(n){let e=n.parentNode;if(e&&e.tagName==="w:rPr"){let t=e.parentNode;if(t&&t.tagName==="w:pPr")return "(paragraph mark)"}return e&&e.tagName==="w:trPr"?"(table row)":"(no visible text)"}g(ci,"_describe_textless_revision");function Yl(n){let e=[],t=R(n.element,"w:ins"),r=R(n.element,"w:del");for(let o of t){let a=li(o).trim();a?e.push(` Accepted insertion: "${We(a,60)}"`):e.push(` Accepted insertion: ${ci(o)}`);}for(let o of r){let a=li(o).trim();a?e.push(` Accepted deletion of: "${We(a,60)}"`):e.push(` Accepted deletion of: ${ci(o)}`);}new yn(n).accept_all_revisions();for(let o of ["w:rPrChange","w:pPrChange","w:sectPrChange"])for(let a of R(n.element,o))a.parentNode?.removeChild(a);let s=t.length+r.length;return s?[`Tracked changes auto-accepted: ${s}`].concat(e):[]}g(Yl,"accept_all_tracked_changes");function Xt(n){let e=Be(n.pkg),t=[],r=0,i=0;for(let[s,o]of Object.entries(e))o.resolved?i++:r++,t.push({id:s,...o});return {total:t.length,open:r,resolved:i,comments:t}}g(Xt,"get_comments_summary");function Gl(n){let e=Be(n.pkg),t=Object.keys(e);if(t.length===0)return [];let r=[],i=new $t(n);for(let[c,u]of Object.entries(e)){let l=u.resolved?"[Resolved]":"[Open]";r.push(` ${l} "${We(u.text||"",60)}" (${u.author||"Unknown"})`),i.deleteComment(c);}for(let c of ["w:commentRangeStart","w:commentRangeEnd"])for(let u of R(n.element,c))u.parentNode?.removeChild(u);let s=R(n.element,"w:commentReference");for(let c of s){let u=c.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(c));}let o=Object.values(e).filter(c=>c.resolved).length,a=Object.values(e).filter(c=>!c.resolved).length;return [`Comments removed: ${t.length} (${o} resolved, ${a} open)`].concat(r)}g(Gl,"remove_all_comments");function Jl(n){let e=n.pkg,t=new Set;for(let i of e.parts)if(i.partname.toLowerCase().includes("comments")){t.add(i.partname);let s=i.partname.startsWith("/")?i.partname:"/"+i.partname,o=i.partname.startsWith("/")?i.partname.substring(1):i.partname;t.add(s),t.add(o);}if(t.size===0)return;for(let i of e.parts)if(i.partname.endsWith(".rels")){let s=R(i._element,"Relationship"),o=[];for(let a of s)if((a.getAttribute("Target")||"").toLowerCase().includes("comments")){o.push(a);let u=i.partname.replace("/_rels/","/").replace(".rels",""),l=e.getPartByPath(u);if(l){let d=a.getAttribute("Id");d&&l.rels.delete(d);}}for(let a of o)a.parentNode?.removeChild(a);}let r=e.getPartByPath("[Content_Types].xml");if(r){let i=R(r._element,"Override"),s=[];for(let o of i){let a=o.getAttribute("PartName")||"";(t.has(a)||a.toLowerCase().includes("comments"))&&s.push(o);}for(let o of s)o.parentNode?.removeChild(o);}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(Jl,"eject_comment_parts");function Ql(n,e){let t=new $t(n);if(!t.commentsPart)return [];let r=new Set,i=R(t.commentsPart._element,"w:comment");for(let s of i){let o=s.getAttribute("w:author");if(o&&(r.add(o),s.setAttribute("w:author",e)),s.hasAttribute("w:initials")){let a=e.split(" ").filter(Boolean).map(c=>c[0]).join("").toUpperCase();s.setAttribute("w:initials",a);}}return r.size?[`Comment authors replaced: ${Array.from(r).sort().join(", ")} \u2192 "${e}"`]:[]}g(Ql,"replace_comment_authors");function Vl(n,e){let t=new Set;for(let r of ["w:ins","w:del","w:rPrChange","w:pPrChange"])for(let i of R(n.element,r)){let s=i.getAttribute("w:author");s&&(t.add(s),i.setAttribute("w:author",e));}return t.size?[`Track change authors replaced: ${Array.from(t).sort().join(", ")} \u2192 "${e}"`]:[]}g(Vl,"replace_change_authors");function Kl(n){let e=0,t="2025-01-01T00:00:00Z";for(let r of ["w:ins","w:del","w:rPrChange","w:pPrChange"])for(let i of R(n.element,r))i.hasAttribute("w:date")&&(i.setAttribute("w:date",t),e++);return e?[`Track change timestamps: ${e} normalized`]:[]}g(Kl,"normalize_change_dates");function Zl(n){let e=0,t="2025-01-01T00:00:00Z";for(let r of n.pkg.parts)if(r.contentType.includes("comments")){for(let i of R(r._element,"w:comment"))i.hasAttribute("w:date")&&(i.setAttribute("w:date",t),e++);for(let i of R(r._element,"w16cex:commentExtensible"))i.hasAttribute("w16cex:dateUtc")&&(i.setAttribute("w16cex:dateUtc",t),e++);}return e?[`Comment timestamps: ${e} normalized`]:[]}g(Zl,"normalize_comment_dates");function ec(n){let e=[],t=n.pkg.getPartByPath("docProps/core.xml");if(t){ee(t._element,"creator").forEach(u=>{u.textContent&&(e.push(`Author: ${u.textContent}`),u.textContent="");}),ee(t._element,"lastModifiedBy").forEach(u=>{u.textContent&&(e.push(`Last modified by: ${u.textContent}`),u.textContent="");}),ee(t._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,l]of a)ee(t._element,u).forEach(d=>{d.textContent&&(e.push(`${l}: ${d.textContent}`),d.textContent="");});ee(t._element,"revision").forEach(u=>{u.textContent&&parseInt(u.textContent)>1&&(e.push(`Revision count: ${u.textContent} \u2192 1`),u.textContent="1");});}let r=n.pkg.getPartByPath("docProps/app.xml");if(r){let i=r._element,s=["TotalTime","Words","Characters","Paragraphs","Lines","CharactersWithSpaces"];for(let a of s)ee(i,a).forEach(c=>{c.textContent&&c.textContent!=="0"&&(a==="TotalTime"&&e.push(`Total editing time: ${c.textContent} minutes`),c.textContent="0");});let o=["Template","Manager","Company"];for(let a of o)ee(i,a).forEach(c=>{c.textContent&&(e.push(`${a}: ${c.textContent}`),c.textContent="");});}return e.length?["Metadata scrubbed:",...e.map(i=>` ${i}`)]:[]}g(ec,"scrub_doc_properties");function tc(n){let e=false,t="1970-01-01T00:00:00Z",r=n.pkg.getPartByPath("docProps/core.xml");if(r)for(let i of ["created","modified","lastPrinted"])ee(r._element,i).forEach(s=>{s.textContent&&s.textContent!==t&&(s.textContent=t,e=true);});return e?["Timestamps normalized to epoch"]:[]}g(tc,"scrub_timestamps");function Cs(n,e,t){let r=n.pkg,i=g(o=>o.startsWith("/")?o.substring(1):o,"normalized");for(let o of r.parts){if(!o.partname.endsWith(".rels"))continue;let a=[];for(let c of R(o._element,"Relationship")){let u=c.getAttribute("Target")||"";if(t(u)){a.push(c);let l=o.partname.replace("/_rels/","/").replace(".rels",""),d=r.getPartByPath(l);if(d){let f=c.getAttribute("Id");f&&d.rels.delete(f);}}}a.forEach(c=>c.parentNode?.removeChild(c));}let s=r.getPartByPath("[Content_Types].xml");if(s){let o=[];for(let a of R(s._element,"Override")){let c=a.getAttribute("PartName")||"";e(i(c))&&o.push(a);}o.forEach(a=>a.parentNode?.removeChild(a));}r.parts=r.parts.filter(o=>!e(i(o.partname)));for(let o of Object.keys(r.unzipped))e(i(o))&&delete r.unzipped[o];}g(Cs,"ejectPackageMembers");function nc(n){let e=g(i=>i.startsWith("customXml/"),"isCustomXml"),t=n.pkg.parts.filter(i=>e(i.partname.startsWith("/")?i.partname.substring(1):i.partname)),r=Object.keys(n.pkg.unzipped).filter(e);if(t.length===0&&r.length===0)return [];Cs(n,e,i=>i.includes("customXml"));for(let i of R(n.element,"w:sdtPr"))an(i,"w:dataBinding").forEach(s=>i.removeChild(s));return [`Custom XML parts: ${Math.max(t.length,r.length)} removed`]}g(nc,"strip_custom_xml");var Wn="docProps/custom.xml";function rc(n){let e=n.pkg.getPartByPath(Wn),t=Object.keys(n.pkg.unzipped).includes(Wn);if(!e&&!t)return [];let r=[];if(e)for(let s of ee(e._element,"property")){let o=s.getAttribute("name")||"(unnamed)",a=(s.textContent||"").trim();r.push(` Custom property removed: ${o} = "${We(a,60)}"`);}return Cs(n,s=>s===Wn,s=>s.includes("docProps/custom.xml")),[`Custom document properties: ${Math.max(r.length,1)} removed (docProps/custom.xml)`].concat(r)}g(rc,"strip_custom_properties");function ic(n){let e=n.pkg.getPartByPath("word/settings.xml");if(!e)return [];let t=[],r=false;for(let s of ee(e._element,"docVars")){for(let o of Array.from(s.childNodes)){let a=o,c=a.tagName||"";(c==="docVar"||c.endsWith(":docVar"))&&t.push(a.getAttribute("w:name")||a.getAttribute("name")||"(unnamed)");}s.parentNode?.removeChild(s),r=true;}for(let s of ee(e._element,"docVar"))t.push(s.getAttribute("w:name")||s.getAttribute("name")||"(unnamed)"),s.parentNode?.removeChild(s),r=true;if(!r)return [];let i=Array.from(new Set(t)).sort().join(", ")||"(unnamed)";return [`Document variables: ${t.length} removed (${i})`]}g(ic,"strip_document_variables");function sc(n){let e=0;for(let t of ee(n.element,"docPr")){let r=t.getAttribute("descr");if(r){let i=r.length<10,s=r.includes(".")&&r.length<60;(i||s)&&(t.removeAttribute("descr"),e++);}}return e?[`Image alt text: ${e} auto-generated descriptions removed`]:[]}g(sc,"strip_image_alt_text");function oc(n){let e=[],t=new Set;for(let r of n.pkg.parts){let i=String(r.partname),s;if(i.startsWith("/word/header"))s="header";else if(i.startsWith("/word/footer"))s="footer";else if(i==="/word/document.xml")s="body";else continue;let o;try{o=ee(r._element,"textpath");}catch{continue}for(let a of o){let c=(a.getAttribute("string")||"").trim(),u=`${s}${c}`;if(t.has(u))continue;t.add(u);let l=c?`"${We(c,60)}"`:"(no text)";e.push(`Watermark-like text object in ${s}: ${l} \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(oc,"detect_watermarks");function ac(n){let e=["sharepoint.com","onedrive.com",".internal","intranet","localhost","10.","192.168.","172.16."],t=[],r=n.pkg.getOrCreateRelsPart(n.part.partname);for(let i of R(r._element,"Relationship"))if(i.getAttribute("TargetMode")==="External"){let s=i.getAttribute("Target")||"";for(let o of e)if(s.toLowerCase().includes(o.toLowerCase())){t.push(`Hyperlink targets internal URL: ${We(s,80)}`);break}}return t}g(ac,"audit_hyperlinks");var lc="word/settings.xml",cc=new Set(["readOnly","forms","comments","trackedChanges"]),uc={readOnly:"read-only",forms:"fill-in-forms",comments:"comments-only",trackedChanges:"tracked-changes-only"},Nt=Object.freeze({edit:null,enforced:false});function pn(n){return n.edit!==null&&n.enforced}g(pn,"isProtectionActive");function _r(n){return n.edit===null?"unprotected":`${uc[n.edit]??n.edit}, ${n.enforced?"enforced":"not enforced"}`}g(_r,"describeProtection");function dc(n){return n==null?true:!["0","false","off"].includes(n.toLowerCase())}g(dc,"isTruthy");function Ps(n){let e=null;try{let s=n?.pkg?.getPartByPath?.(lc);if(!s?._element)return Nt;e=ee(s._element,"documentProtection")[0]??null;}catch{return Nt}if(!e)return Nt;let t=null,r=null,i=e.attributes;if(i)for(let s=0;s<i.length;s++){let o=i[s],a=(o.name??"").split(":").pop()??"";a==="edit"?t=o.value:a==="enforcement"&&(r=o.value);}return t===null||!cc.has(t)?Nt:{edit:t,enforced:dc(r)}}g(Ps,"readDocumentProtection");var _n="ignore_control_locks",At="ignore_document_protection",mr="allow_untracked_writes",Ve=Object.freeze({ignore_control_locks:false,ignore_document_protection:false,allow_untracked_writes:false});function fc(n){return n.ignore_control_locks||n.ignore_document_protection||n.allow_untracked_writes}g(fc,"anyOverrideUsed");function me(n){let e=[`CC:${n.ordinal}`];return n.alias&&e.push(`"${n.alias}"`),n.tag&&e.push(`(tag: ${n.tag})`),e.join(" ")}g(me,"describeControl");function _e(n,e){let t=`- Edit ${n} Failed: ${e.subject} ${e.rule} ${hc(e.alternative)}`;return e.override&&(t+=` Pass ${e.override}=true to override deliberately.`),t.split(/\s+/).join(" ")}g(_e,"gateError");function hc(n){let e=n.replace(/\s+$/,"");return /[.!?:]$/.test(e)?e:`${e}.`}g(hc,"endSentence");function pc(n){return n.find(e=>e.contentLocked)??null}g(pc,"lockedAncestor");function _c(n,e,t=Ve){if(t.ignore_control_locks)return null;let r=pc(e);return r?_e(n,{subject:`edit targets content inside ${me(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:_n}):null}g(_c,"checkContentLock");function mc(n,e,t=Ve){if(t.ignore_control_locks)return null;let r=e.find(i=>i.cls==="group");return !r||e.some(i=>i.cls!=="group")?null:_e(n,{subject:`edit targets text inside ${me(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:_n})}g(mc,"checkGroupRegion");function gc(n,e,t,r=Ve){if(r.ignore_control_locks||!t)return null;let i=e.find(s=>s.deleteLocked);return i?_e(n,{subject:`edit would remove ${me(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:_n}):null}g(gc,"checkDeleteLock");function wc(n,e,t={}){let r=t.overrides??Ve;if(!pn(e)||r.ignore_document_protection)return null;let i=_r(e);return e.edit==="readOnly"?_e(n,{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:At}):e.edit==="comments"?t.isCommentOnly?null:_e(n,{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:At}):e.edit==="forms"?(t.controls??[]).some(o=>o.cls!=="group")?null:_e(n,{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:At}):null}g(wc,"checkProtectionBlocksEdit");function yc(n,e,t,r=Ve){if(!pn(t)||r.ignore_document_protection||e!=="accept"&&e!=="reject"||t.edit!=="trackedChanges"&&t.edit!=="readOnly")return null;let i=t.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 ${n} Failed: the document is protected (${_r(t)}). ${i} Remove the restriction in Word (Review -> Restrict Editing -> Stop Protection) or pass ${At}=true to override deliberately.`}g(yc,"checkProtectionBlocksReview");function vc(n,e,t=Ve){return !pn(e)||e.edit!=="forms"||t.allow_untracked_writes?null:_e(n,{subject:`the document is protected (${_r(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:mr})}g(vc,"checkUntrackedWrite");function bc(n,e,t){let r=(e||"").trim();if(!r)return null;for(let i of t){if(!i.showingPlaceholder)continue;let s=(i.placeholderText||"").trim();if(!(!s||!s.includes(r)))return _e(n,{subject:`target_text is the placeholder text of ${me(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(bc,"checkPlaceholderTarget");var kt=["[ ]","[x]"];function xc(n,e,t,r){let i=e.find(o=>o.cls==="checkbox");if(!i)return null;let s=kt;return s.includes(t.trim())&&s.includes(r.trim())?null:_e(n,{subject:`edit targets ${me(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(xc,"checkCheckboxEdit");function Nc(n,e){let t=e.find(i=>i.bound);if(!t)return null;let r=t.bindingXpath?` (bound to ${t.bindingXpath})`:"";return _e(n,{subject:`edit targets the content of ${me(t)}, 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(Nc,"checkBoundControl");function ui(n,e,t){let r=new Set(e),i=new Set(t);return n.filter(s=>r.has(s)!==i.has(s))}g(ui,"crossedControlWalls");function kc(n,e){if(e.length===0)return null;let t=e.map(me).join(", ");return _e(n,{subject:`edit merges paragraphs across the boundary of ${t}.`,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(kc,"checkBlockMergeAcrossControl");function Ec(n){return `segmented at the boundary of ${n.map(me).join(", ")}: only the text outside the control was changed`}g(Ec,"segmentationNote");function Ac(n,e){if(!fc(n))return null;let t=[];if(n.ignore_control_locks){let r=e.length>0?` (${e.map(me).join(", ")} edited inside locked controls)`:"";t.push(`${_n}${r}`);}return n.ignore_document_protection&&t.push(At),n.allow_untracked_writes&&t.push(mr),"Overrides: "+t.join(", ")}g(Ac,"overridesNote");function Cc(n,e,t=2){if(n===e)return 0;if(Math.abs(n.length-e.length)>t)return t+1;if(n.length===0)return e.length<=t?e.length:t+1;if(e.length===0)return n.length<=t?n.length:t+1;if(n.length>e.length){let i=n;n=e,e=i;}let r=Array.from({length:n.length+1},(i,s)=>s);for(let i=1;i<=e.length;i++){let s=[i],o=i;for(let a=1;a<=n.length;a++){let c=n[a-1]===e[i-1]?0:1,u=Math.min(r[a]+1,s[a-1]+1,r[a-1]+c);s.push(u),u<o&&(o=u);}if(o>t)return t+1;r=s;}return r[n.length]<=t?r[n.length]:t+1}g(Cc,"boundedLevenshtein");function Pc(n){let e="",t=R(n._element,"w:r");for(let r of t)e+=Se(new je(r,n));return e}g(Pc,"_get_paragraph_text");var gr="[A-Z][A-Za-z0-9\\s\\-&'\u2019]{1,60}",Tc=new RegExp(`^(?:[\\d.\\-()a-zA-Z]+\\s*)?["\u201C](${gr})["\u201D]`,"d"),$c=new RegExp(`(?<=[.;:!?])\\s+(?:[\\d.\\-()a-zA-Z]+\\s+)?["\u201C](${gr})["\u201D]`,"dg"),Sc=new RegExp(`\\([^)]*?["\u201C](${gr})["\u201D][^)]*?\\)`,"dg");function Ic(n){let e=[],t=Tc.exec(n);t&&t.indices&&t.indices[1]&&e.push([t.indices[1][0],t[1].trim()]);for(let s of n.matchAll($c)){let o=s.indices;o&&o[1]&&e.push([o[1][0],s[1].trim()]);}for(let s of n.matchAll(Sc)){let o=s.indices;o&&o[1]&&e.push([o[1][0],s[1].trim()]);}let r=[],i=new Set;e.sort((s,o)=>s[0]-o[0]);for(let[s,o]of e)i.has(s)||(i.add(s),r.push(o));return r}g(Ic,"extract_terms_from_paragraph");function Oc(n,e){let t=Object.create(null),r=new Set,i=Object.create(null),s=[];for(let p of Ue(n)){if(!(p instanceof ne))continue;let m=Pc(p).trim();if(!m)continue;for(let b of Ic(m))t[b]?r.add(b):t[b]={count:0};let w=m.length>60?m.substring(0,60)+"...":m,y=R(p._element,"*");for(let b of y){if(b.tagName==="w:bookmarkStart"){let N=b.getAttribute("w:name");N&&(!N.startsWith("_")||N.startsWith("_Ref"))&&(i[N]||(i[N]={anchored_to:w,referenced_from:[]}));}let v=null;if(b.tagName==="w:fldSimple"){let k=(b.getAttribute("w:instr")||"").trim().split(/\s+/);k.length>1&&k[0]==="REF"&&(v=k[1]);}else if(b.tagName==="w:instrText"){let k=(b.textContent||"").trim().split(/\s+/);k.length>1&&k[0]==="REF"&&(v=k[1]);}v&&s.push([v,w]);}}for(let[p,m]of s)i[p]&&i[p].referenced_from.push(m);let o=[],a=Object.keys(t);if(a.length>0){let p=a.sort((b,v)=>v.length-b.length),m=g(b=>b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegExp"),w=p.map(m).join("|"),y=new RegExp(`(?<!["\u201C])\\b(${w})\\b(?![\u201D"])`,"g");for(let b of e.matchAll(y)){let v=b[1];t[v]&&t[v].count++;}for(let b of a)t[b].count===0&&(delete t[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 c=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,l=new Set(e.match(u)||[]),d=new Set(Object.keys(t)),f={};for(let p of d){let m=p[0].toLowerCase();f[m]||(f[m]=[]),f[m].push(p);}let h=Object.create(null);for(let p of l){let m=p.trim(),w=m.split(/\s+/);for(;w.length>0;){let v=w[0],N=v.charAt(0).toUpperCase()+v.slice(1).toLowerCase();if(c.has(N))w.shift();else break}if(m=w.join(" "),m.length<4||d.has(m))continue;let y=m[0].toLowerCase(),b=f[y]||[];if(m.length>5)for(let[v,N]of Object.entries(f))v!==y&&(b=b.concat(N));for(let v of b){if(Math.abs(m.length-v.length)>2||m===v+"s"||m===v+"es"||v===m+"s"||v===m+"es")continue;let N=Cc(m,v,2);N===0||N>2||v.length<=5&&(N>1||m[0].toLowerCase()!==v[0].toLowerCase())||(h[v]||(h[v]=[]),h[v].includes(m)||h[v].push(m));}}for(let[p,m]of Object.entries(h)){m.sort();let w=m.map(y=>`'${y}'`).join(", ");o.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"),o.sort((p,m)=>{let w=_(p),y=_(m);return w!==y?w-y:p.localeCompare(m)}),[t,o,i]}g(Oc,"extract_all_domain_metadata");function Dc(n){let e=[],t=n.pkg.getPartByPath("word/settings.xml");if(!t)return e;let r=g(o=>{if(!o.hasAttribute("w:val"))return true;let a=(o.getAttribute("w:val")||"").toLowerCase();return a!=="0"&&a!=="false"&&a!=="off"},"isTruthy2"),i=ee(t._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 s=ee(t._element,"removeDateAndTime");return s.length>0&&r(s[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(Dc,"extract_document_settings_warnings");function Rc(n,e){try{let t=su(n),r=Ps(n);return lu(t,r,'Read with mode="fields" for the full field ledger.')}catch{return []}}g(Rc,"content_controls_appendix_section");function Mc(n,e){let[t,r,i]=Oc(n,e),s=Dc(n),o=[`
|
|
80
|
+
`);if(H===q)continue;if(A.length===1&&dt(H)&&dt(q)){let z=di(H,q);if(z!==null){c.push(...z);continue}}if(Gn(H,q)<.35)c.push({type:"modify",target_text:H,new_text:q,comment:"Diff: Replacement",_match_start_index:L});else {let z=At(H,q);for(let U of z)U._match_start_index=(U._match_start_index||0)+L,c.push(U);}}}}}return Bl(c)}g(tn,"generate_edits_via_paragraph_alignment");var nn=/!\[[^\]]*\]\(docx-image:[^)]*\)/g;function ui(n,e){let t=g(i=>i.replace(nn,"").replace(/\s+/g," ").trim(),"_normalized"),r=[];for(let i of n){let s=((i.target_text||"").match(nn)||[]).sort(),o=((i.new_text||"").match(nn)||[]).sort();if(JSON.stringify(s)===JSON.stringify(o)){r.push(i);continue}t(i.target_text||"")===t(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(ui,"_drop_image_marker_hunks");function fi(n,e,t){let r=[];for(let o of e.matchAll(nn))r.push([o.index,o.index+o[0].length]);if(r.length===0)return n;let i=[],s=false;for(let o of n){let a=o._match_start_index;if(a==null){i.push(o);continue}let l=a+(o.target_text||"").length;if(!r.some(([c,u])=>c<l&&a<u&&!(a<=c&&u<=l))){i.push(o);continue}s||(t.push("An image's alternative text differs between the documents. Image markers () 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."),s=true);}return i}g(fi,"_drop_marker_interior_hunks");function hi(n,e){for(let t of e.rows)if(n.substring(t.start,t.end)!==t.cells.join(" | "))return false;return true}g(hi,"_rows_are_plain");var sr="";function Fl(n,e){let t=n.map(s=>s.cells.join(sr)),r=e.map(s=>s.cells.join(sr)),i=xr(t,r);for(let[s,o,a,l,d]of i)if(s==="insert"||s==="delete"||s==="replace"&&a-o!==d-l)return i;return null}g(Fl,"_table_row_opcodes");function Ll(n,e,t,r){let i=n.rows,s=e.rows,o=i.map(_=>_.cells.join(sr)),a=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 l=new Set,d={};for(let[_,p,m,w,y]of t)if(_==="delete")for(let b=p;b<m;b++)l.add(b);else if(_==="replace"){let b=Math.min(m-p,y-w);for(let v=p+b;v<m;v++)l.add(v);for(let v=0;v<b;v++)d[p+v]=a(s[w+v]);}let c=[];for(let _=0;_<i.length;_++)l.has(_)||c.push(_);let u=g(_=>d[_]!==void 0?d[_]:a(i[_]),"anchor_text"),f=g((_,p)=>{let m=[],w=c.filter(b=>b<p),y=c.filter(b=>b>=p);if(w.length>0){let b=w[w.length-1],v=u(b);for(let N of [..._].reverse())m.push({type:"insert_row",target_text:v,position:"below",cells:[...N.cells],_match_start_index:i[b].start});}else if(y.length>0){let b=y[0],v=u(b);for(let N of _)m.push({type:"insert_row",target_text:v,position:"above",cells:[...N.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,y]of t)if(_!=="equal")if(_==="replace"){let b=Math.min(m-p,y-w);for(let N=0;N<b;N++){let k=a(i[p+N]),x=a(s[w+N]);k!==x&&h.push({type:"modify",target_text:k,new_text:x,comment:"Diff: Table row modified",_is_table_edit:true});}for(let N=p+b;N<m;N++)h.push({type:"delete_row",target_text:a(i[N]),_match_start_index:i[N].start});let v=s.slice(w+b,y);v.length>0&&h.push(...f(v,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(s.slice(w,y),p));return h}g(Ll,"_row_ops_for_table");function Nr(n,e,t,r){let i=[],s=[],o=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(o)!==JSON.stringify(a))return i.push(`The documents have different part layouts (${o.join(" + ")||"none"} vs ${a.join(" + ")||"none"}); comparing flattened text instead. Header/footer additions or removals cannot be expressed as text edits.`),{edits:[...fi(ui(tn(n,t),i),n,i)],warnings:i};let l=e.part_ranges.filter(([p,m])=>m>p).map(([p,m])=>[p,m]),d=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],[y,b]=d[p],v=e.tables.filter(E=>m<=E.start&&E.end<=w),N=r.tables.filter(E=>y<=E.start&&E.end<=b),k=v.length===N.length&&v.every(E=>hi(n,E))&&N.every(E=>hi(t,E));if(v.length!==N.length&&i.push(`A ${o[p]} part has ${v.length} table(s) in the original but ${N.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 E=tn(n.substring(m,w),t.substring(y,b));for(let T of E)T._match_start_index=(T._match_start_index||0)+m;s.push(...E);continue}let x=[[m,m],...v.map(E=>[E.start,E.end]),[w,w]],P=[[y,y],...N.map(E=>[E.start,E.end]),[b,b]];for(let E=0;E<x.length-1;E++){let T=x[E][1],I=x[E+1][0],D=P[E][1],F=P[E+1][0],M=tn(n.substring(T,I),t.substring(D,F));for(let B of M)B._match_start_index=(B._match_start_index||0)+T;if(s.push(...M),E<v.length){let B=v[E],j=N[E],C=Fl(B.rows,j.rows);if(C!==null)s.push(...Ll(B,j,C,i));else for(let S=0;S<B.rows.length;S++){let A=B.rows[S].cells.join(" | "),O=j.rows[S].cells.join(" | ");A!==O&&s.push({type:"modify",target_text:A,new_text:O,comment:"Diff: Table row modified",_is_table_edit:true});}}}}let c=g((p,m)=>{let w=0,y=0;for(;;){let b=p.indexOf(m,y);if(b===-1)break;w++,y=b+m.length;}return w},"countOccurrences"),u=false;for(let p of s)(p.type==="insert_row"||p.type==="delete_row"||p._is_table_edit)&&!u&&p.target_text&&c(n,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.`),u=true);let f=s.filter(p=>p.type==="modify"),h=new Set(fi(ui(f,i),n,i)),_=s.filter(p=>p.type!=="modify"||h.has(p));for(let p of _)p.type==="modify"&&typeof p.comment=="string"&&p.comment.startsWith("Diff:")&&delete p.comment;return {edits:_,warnings:i}}g(Nr,"generate_structured_edits");function kr(n,e){let t=g(c=>{let u=new Map;try{let f=at(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;u.set(h,`${_.length}:${p.toString(16)}:${m.toString(16)}`);}}catch{return new Map}return u},"media_hashes"),r=t(n),i=t(e),s=[],o=[],a=[];for(let[c,u]of r)i.has(c)?i.get(c)!==u&&s.push(c):a.push(c);for(let c of i.keys())r.has(c)||o.push(c);if(s.sort(),o.sort(),a.sort(),s.length+o.length+a.length===0)return [];let l=[];s.length&&l.push(`${s.length} changed`),o.length&&l.push(`${o.length} added`),a.length&&l.push(`${a.length} removed`);let d=[...s,...o,...a].slice(0,5).join(", ");return [`The documents' embedded media differ (${l.join(", ")}: ${d}). 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 Is(n,e,t=3){let r=new br.default.diff_match_patch;r.Diff_Timeout=2;let i=r.diff_linesToChars_(n,e),s=r.diff_main(i.chars1,i.chars2,false);r.diff_charsToLines_(s,i.lineArray);let o=[];o.push("--- Original"),o.push("+++ Modified");let a=0;for(;a<s.length;){for(;a<s.length&&s[a][0]===0;)a++;if(a>=s.length)break;let l=a,d=[];l>0&&s[l-1][0]===0&&(d=s[l-1][1].replace(/\n$/,"").split(`
|
|
81
|
+
`).slice(-t));let c=[];for(c.push(...d.map(f=>` ${f}`));a<s.length;){let[f,h]=s[a],_=h.replace(/\n$/,"").split(`
|
|
82
|
+
`);if(f===0){if(_.length>t*2)break;c.push(..._.map(p=>` ${p}`));}else {let p=f===-1?"-":"+";c.push(..._.map(m=>`${p}${m}`));}a++;}let u=[];a<s.length&&s[a][0]===0&&(u=s[a][1].replace(/\n$/,"").split(`
|
|
83
|
+
`).slice(0,t)),c.push(...u.map(f=>` ${f}`)),o.push("@@ ... @@"),o.push(...c);}return o.length===2?"":o.join(`
|
|
84
|
+
`)}g(Is,"create_unified_diff");var ln=/\{\+\+|\{--|\{==|\{>>|\+\+\}|--\}|==\}|<<\}/g,Wl={"{++":"++}","{--":"--}","{==":"==}","{>>":"<<}"};function pi(n){if(!n)return true;if(/\{[=+\-><]?$/.test(n)||/^[=+\-><]?\}/.test(n))return false;let e=[];ln.lastIndex=0;let t;for(;(t=ln.exec(n))!==null;){let r=t[0];if(r.startsWith("{"))e.push(r);else if(e.length===0||Wl[e.pop()]!==r)return false}return e.length===0}g(pi,"_critic_payload_atomic");function Os(n,e,t,r){let i=true;for(;i;){i=false;for(let s of [n,e]){let o=s.length-r;ln.lastIndex=0;let a;for(;(a=ln.exec(s))!==null;){let l=a.index,d=a.index+a[0].length;if(t>l&&t<d&&(t=l,i=true),o>l&&o<d){r=s.length-d,i=true;break}}}}return [Math.max(0,t),Math.max(0,r)]}g(Os,"_clamp_trim_outside_critic_tokens");function zl(n,e){let[t,r]=ft(n,e);return [t,r]=Os(n,e,t,r),[n.substring(t,n.length-r),e.substring(t,e.length-r)]}g(zl,"_word_patch_displays");function Ul(n,e){let t=[],r=0;for(;r<n.length;){let i=n[r].target_text||"",s=n[r].new_text||"",o=n[r]._match_start_index||0,a=r+1;for(;;){let[l,d]=zl(i,s);if(pi(l)&&pi(d)||a>=n.length)break;let c=n[a],u=c._match_start_index||0,f=o+i.length,h=u>=f?e.substring(f,u):"";i=i+h+(c.target_text||""),s=s+h+(c.new_text||""),a++;}a>r+1?t.push({...n[r],target_text:i,new_text:s,_match_start_index:o}):t.push(n[r]),r=a;}return t}g(Ul,"_merge_critic_split_hunks");function Ds(n,e,t="Original",r="Modified"){let i=Ul(At(n,e),n),s=[`--- ${t}`,`+++ ${r}`,""],o=40;for(let a of i){let l=a._match_start_index||0,d=a.target_text||"",c=a.new_text||"",[u,f]=ft(d,c);[u,f]=Os(d,c,u,f);let h=d.length-f,_=c.length-f,p=d.substring(u,h),m=c.substring(u,_),w=l+u,y=w+p.length,b=Math.max(0,w-o),v=n.substring(b,w);b>0&&(v="..."+v);let N=Math.min(n.length,y+o),k=n.substring(y,N);N<n.length&&(k=k+"..."),v=v.replace(/\n/g," ").replace(/\r/g,""),k=k.replace(/\n/g," ").replace(/\r/g,""),s.push("@@ Word Patch @@"),s.push(` ${v}`),p&&s.push(`- ${p}`),m&&s.push(`+ ${m}`),s.push(` ${k}`),s.push("");}return s.join(`
|
|
85
|
+
`)}g(Ds,"create_word_patch_diff");var _i=19e3,Rs=8,Hl="<!-- READONLY_BOUNDARY_START -->",ql=/^\s*(\d+)\s*-\s*(\d+)\s*$/;function Ms(n){let e=g(t=>{throw new Error(`Invalid page parameter: '${t}'. Provide a positive integer, page range (e.g. '2-6'), or 'all'.`)},"bad");if(n==null)return ["single",1];if(typeof n=="number")return (!Number.isInteger(n)||n<1)&&e(n),["single",n];if(typeof n=="string"){let t=n.trim().replace(/^['"]+|['"]+$/g,"").trim();if(t||e(n),t.toLowerCase()==="all")return ["all",null];let r=ql.exec(t);if(r){let s=parseInt(r[1],10),o=parseInt(r[2],10);return (s<1||o<1)&&e(n),["range",[s,o]]}/^\d+$/.test(t)||e(n);let i=parseInt(t,10);return i<1&&e(n),["single",i]}return e(n)}g(Ms,"parse_page_arg");var mi={"{++":"++}","{--":"--}","{==":"==}","{>>":"<<}"},Xl=/\bChg:(\d+)\b/g;function et(n){if(!n)return ["",""];let e=n.indexOf(Hl);if(e===-1)return [n,""];let t=n.lastIndexOf(`
|
|
86
|
+
`,e)+1,r=n.substring(0,t).trimEnd(),i=n.substring(t);return [r,i]}g(et,"split_structural_appendix");function tt(n,e=""){if(!n){let d=e?e.trim():"";return {pages:[{page:1,total_pages:1,has_next:false,has_prev:false,tracked_change_count:gi(d),page_content:d}],total_pages:1,body_pages:[""],body_page_offsets:[0]}}let t=Yl(n),[r,i]=Vl(t),s;if(e&&e.trim()){let l=e.trim();s=r.map(d=>d?`${d}
|
|
90
87
|
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
## Named Anchors`);for(let[u,l]of Object.entries(i)){o.push(`- ${u} \u2192 Anchored to: "${l.anchored_to}"`);for(let d of l.referenced_from)o.push(` - Referenced from: "${d}"`);}}return a?o.join(`
|
|
96
|
-
`):""}g(Mc,"build_structural_appendix");async function Ke(n,e=false,t=true){let r=await de.load(n);return Ze(r,e,t)}g(Ke,"extractTextFromBuffer");function Ze(n,e=false,t=true,r=false,i=false){let s=Be(n.pkg),o=[],a=new Map,c=i?{part_ranges:[],tables:[]}:null,u=0,l=cn(Array.from(Je(n)).map(([f])=>un(f)));for(let[f,h]of Je(n)){let _=o.length>0?u+2:u,p=rn(f,s,e,_,r?a:void 0,c?c.tables:void 0,l);p&&(o.length>0&&(u+=2),o.push(p),c&&c.part_ranges.push([u,u+p.length,h]),u+=p.length);}let d=o.join(`
|
|
88
|
+
${l}`:l);}else s=[...r];let o=s.length;return {pages:s.map((l,d)=>({page:d+1,total_pages:o,has_next:d+1<o,has_prev:d+1>1,tracked_change_count:gi(l),page_content:l})),total_pages:o,body_pages:r,body_page_offsets:i}}g(tt,"paginate");function Yl(n){let e=Gl(n),t=Jl(e),r=[];for(let[i,s]of t)if(i.includes(en)){let o=i.split(en),a=s;for(let l=0;l<o.length;l++){let d=o[l],c=l===o.length-1;(d||!c)&&r.push([d,a,!c]),a+=d.length+en.length;}}else r.push([i,s,false]);return r}g(Yl,"_tokenize_into_atomic_blocks");function Gl(n){let e={"++}":0,"--}":0,"==}":0,"<<}":0},t=[],r=0,i=0,s=n.length;for(;i<s;){let o=false;for(let[l,d]of Object.entries(mi))if(n.startsWith(l,i)){e[d]++,i+=l.length,o=true;break}if(o)continue;let a=false;for(let l of Object.values(mi))if(n.startsWith(l,i)){e[l]>0&&e[l]--,i+=l.length,a=true;break}if(!a){if(n[i]===`
|
|
89
|
+
`&&i+1<s&&n[i+1]===`
|
|
90
|
+
`&&Object.values(e).every(l=>l===0)){let l=n.substring(r,i);l&&t.push([l,r]);let d=i;for(;d<s&&n[d]===`
|
|
91
|
+
`;)d++;i=d,r=i;continue}i++;}}if(r<s){let o=n.substring(r,s);o&&t.push([o,r]);}return t}g(Gl,"_split_on_safe_paragraph_breaks");function Jl(n){if(!n.length)return n;let e=[],t=0;for(;t<n.length;){let[r,i]=n[t],s=r.trimStart();if(!(s.startsWith("## Footnotes")||s.startsWith("## Endnotes"))){e.push([r,i]),t++;continue}let a=r,l=t+1;for(;l<n.length;){let[d]=n[l],c=d.trimStart();if(c.startsWith("[^fn-")||c.startsWith("[^en-"))a=`${a}
|
|
97
92
|
|
|
98
|
-
|
|
99
|
-
${n.note_type==="fn"?"## Footnotes":"## Endnotes"}`;d.push(m),f+=m.length,h=false;}for(let p of Ue(n,!!o)){h||(f+=2);let m=f;if(p instanceof cr){let w=o?o.get(p.element):void 0,y=!!w&&Tt(w),b=a?"":`
|
|
100
|
-
`,v=y?`${Re(w)}${b}`:"",N=rn({_element:S(p.element,"w:sdtContent"),part:n.part||n},e,t,m+v.length,i,void 0,o,a);if(N){let k=y?`${v}${N}${b}${Me(w)}`:N;d.push(k),f=m+k.length,h=false;}else h||(f-=2);_=false;}else if(p.constructor.name==="FootnoteItem"){let w=rn(p,e,t,m,i,void 0,o);w?(d.push(w),f=m+w.length,h=false):h||(f-=2);}else if(p instanceof ne){let w=ze(p,u,l);_&&n.constructor.name==="FootnoteItem"&&(w=`[^${n.note_type}-${n.id}]: `+w);let y=Rt(p,e,t,u,l,o);if(t&&!y&&hs(p._element)){h||(f-=2),_=false;continue}let b=w+y;d.push(b),i&&i.set(p._element,[m,b.length]),f=m+b.length,_=false,h=false;}else if(p instanceof Le){let w=s?{start:m,end:m,rows:[]}:null,y=mn(p,e,t,m,i,w,o);y?(d.push(y),f=m+y.length,h=false,w&&s&&(w.end=m+y.length,s.push(w))):h||(f-=2),_=false;}}return d.join(`
|
|
93
|
+
${d}`,l++;else break}e.push([a,i]),t=l;}return e}g(Jl,"_merge_footnote_sections");function Vl(n){if(!n.length)return [[""],[0]];let e=[],t=[],r=[],i=0,s=-1,o=g(()=>{r.length>0&&(e.push(r.join(`
|
|
101
94
|
|
|
102
|
-
`)
|
|
103
|
-
`)}g(mn,"extract_table");function Rt(n,e,t,r,i,s){let o=[],a=Object.create(null),c=Object.create(null),u=new Set,l=Object.create(null),d=[],f=null,h="",_=["",""],p=["",""],m=Array.from(hn(n,s)),w=ps(n,r,i),y=fn(n,r,i),b=w,v=g(()=>{h&&(o.push(`${_[0]}${h}${_[1]}`),h="",_=["",""],p=["",""]);},"flushPending");for(let N=0;N<m.length;N++){let k=m[N];if(k instanceof je){let[x,C]=_s(k,y),E=Se(k);if(t&&Object.keys(c).length>0)continue;if(b){if(!E||!E.trim())continue;b=false;}let P=dl(E,x,C);if(P){let I=t?["",""]:fi(a,c,u,l),M=[x,C];if(h&&I[0]===_[0]&&I[1]===_[1]){let j=M[0].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),F=M[0]!==""||M[1]!==""?P.match(new RegExp("^(\\s*)"+j)):null,T="";for(let D=h.length-1;D>=0;D--){let A=h[D];if(/\s/.test(A))T=A+T;else break}let O=T?h.slice(0,-T.length):h;M[0]===p[0]&&M[1]===p[1]&&!(p[0]===""&&p[1]==="")&&O.endsWith(p[1])&&F!==null?h=O.slice(0,-p[1].length)+T+F[1]+P.slice(F[0].length):h+=P,p=M;}else v(),h=P,_=I,p=M;if(!t){(Object.keys(a).length>0||Object.keys(c).length>0||u.size>0||Object.keys(l).length>0)&&d.push([{...a},{...c},new Set(u),{...l}]);let F=false;if(Object.keys(a).length>0||Object.keys(c).length>0||Object.keys(l).length>0||u.size>0){let O=N+1,D=false,A=Object.keys(a).length,$=Object.keys(c).length,W=Object.keys(l).length,z=new Set(u);for(;O<m.length;){let H=m[O];if(H instanceof je){if(!Se(H)){O++;continue}(A>0||$>0||W>0||z.size>0)&&(D=true);break}else {let L=H;L.type==="ins_start"?A++:L.type==="ins_end"?A=Math.max(0,A-1):L.type==="del_start"?$++:L.type==="del_end"?$=Math.max(0,$-1):L.type==="fmt_start"?W++:L.type==="fmt_end"?W=Math.max(0,W-1):L.type==="start"?z.add(L.id):L.type==="end"&&z.delete(L.id);}O++;}D&&(F=true);}if(!F&&d.length>0){let O=hi(d,e);O&&(Qi(m,N)?f=O:(v(),o.push(`{>>${O}<<}`))),d.length=0;}}}}else if(lr(k)){b=false;let x=k.info;if(Ji.includes(k.type)){if(t&&Object.keys(c).length>0)continue;let C=k.type==="checkbox_start"?Yi:k.type==="checkbox_end"?Gi:ar(x),E=t?["",""]:fi(a,c,u,l);h&&(E[0]!==_[0]||E[1]!==_[1])&&(o.push(`${_[0]}${h}${_[1]}`),h=""),h||(_=E),h+=C,p=["",""],k.type==="checkbox_end"&&f&&(o.push(`${_[0]}${h}${_[1]}`),h="",_=["",""],o.push(`{>>${f}<<}`),f=null);continue}v(),k.type==="sdt_start"?(o.push(Re(x)),!t&&x.showingPlaceholder&&x.placeholderText&&o.push(`{>>placeholder: ${x.placeholderText}<<}`)):o.push(Me(x));}else {let x=k;if(b=false,["ins_start","ins_end","del_start","del_end","fmt_start","fmt_end"].includes(x.type)||v(),x.type==="start")u.add(x.id);else if(x.type==="end")u.delete(x.id);else if(x.type==="ins_start")a[x.id]=x;else if(x.type==="ins_end")delete a[x.id];else if(x.type==="del_start")c[x.id]=x;else if(x.type==="del_end")delete c[x.id];else if(x.type==="fmt_start")l[x.id]=x;else if(x.type==="fmt_end")delete l[x.id];else if(x.type==="image"){if(!(t&&Object.keys(c).length>0)){let C=(x.date||"image").replace(/\]/g,")").replace(/\n/g," ");o.push(``);}}else x.type==="footnote"||x.type==="endnote"?(v(),o.push(`[^${x.type==="footnote"?"fn":"en"}-${x.id}]`)):x.type==="hyperlink_start"?(v(),o.push("[")):x.type==="hyperlink_end"?(v(),o.push(`](${x.date})`)):x.type==="xref_start"?(v(),o.push("[~")):x.type==="xref_end"?(v(),o.push(`~](#${x.id})`)):x.type==="bookmark"&&(v(),o.push(`{#${x.id}}`));}}if(v(),d.length>0){let N=hi(d,e);N&&o.push(`{>>${N}<<}`);}return o.join("")}g(Rt,"build_paragraph_text");function fi(n,e,t,r){return Object.keys(e).length>0?["{--","--}"]:Object.keys(n).length>0?["{++","++}"]:t.size>0||Object.keys(r).length>0?["{==","==}"]:["",""]}g(fi,"_get_wrappers");function hi(n,e){let t=[],r=[],i=new Set,s=gs(n),o=g(c=>s[c]?` (pairs with ${s[c]})`:"","pairSuffix");for(let[c,u,l,d]of n){let f=g(function(p){if(!e[p])return;let m=`Com:${p}`;if(i.has(m))return;let w=e[p],y=`[${m}] ${w.author}`;if(w.date&&(y+=` @ ${w.date}`),w.resolved&&(y+="(RESOLVED)"),r.push(`${y}: ${ts(w.text)}`),i.add(m),h[p]){let b=h[p].sort((v,N)=>(e[v]?.date||"").localeCompare(e[N]?.date||""));for(let v of b)f(v);}},"render_comment2");for(let[p,m]of Object.entries(c)){let w=`Chg:${p}`;i.has(w)||(t.push(`[${w} insert] ${m.author||"Unknown"}${o(p)}`),i.add(w));}for(let[p,m]of Object.entries(u)){let w=`Chg:${p}`;i.has(w)||(t.push(`[${w} delete] ${m.author||"Unknown"}${o(p)}`),i.add(w));}for(let[p,m]of Object.entries(d)){let w=`Chg:${p}`;i.has(w)||(t.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(l).sort();for(let p of _)f(p);}return [...t,...r].join(`
|
|
104
|
-
`)}g(hi,"_build_merged_meta_block");var Ts=/^(#{1,6}) /,$s=3;function Ss(n,e){for(let t=0;t<n.length;t++){let r=n[t],i=e;for(let s=t+1;s<n.length;s++)if(n[s].level<=r.level){i=n[s].page>r.page?n[s].page-1:r.page;break}r.end_page=i;}}g(Ss,"_assign_end_pages");function Is(n,e,t,r,i=null){if(t.length!==r.length)throw new Error("body_pages and body_page_offsets length mismatch");if(i)return Hc(n,e,r,i);let s=Be(n.pkg),o=Bc(n,s),a=[];for(let u=0;u<o.length;u++){let l=o[u];l.is_paragraph&&It(l.item)&&Lc(l.item,s)&&a.push(u);}if(a.length===0)return [];let c=[];for(let u=0;u<a.length;u++){let l=a[u],d=o[l],f=d.item,h=sn(f),_=js(f,s),p=gn(f),m=zc(o,a,u,h),w=o.slice(l+1,m),y=jc(o,l+1,m),b=Uc(w),v=wr(d.start_offset,r);c.push({level:h,text:_,page:v,style:p,has_table:y,footnote_ids:b,end_page:v});}return Ss(c,t.length),c}g(Is,"extract_outline");function jc(n,e,t){for(let r=e;r<t;r++){let i=n[r];if(i.is_paragraph&&It(i.item))return false;if(i.is_table)return true}return false}g(jc,"_direct_has_table");function Bc(n,e){let t=Array.from(_l(n)),r=0,i=null;for(let c of t){if(c===n){i=c;break}let u=Rs(c,e);u&&(r>0&&(r+=2),r+=u.length);}i?r>0&&(r+=2):(i=n,r=0);let s=[],o=r,a=true;for(let c of Ue(i))if(c instanceof ne){let u=ze(c),l=Rt(c,e,false),d=(u+l).length;a||(o+=2),s.push({item:c,is_paragraph:true,is_table:false,start_offset:o,projected_length:d}),o+=d,a=false;}else if(c instanceof Le){let u=mn(c,e,false,0),l=u?u.length:0;a||(o+=2);let d=o;s.push({item:c,is_paragraph:false,is_table:true,start_offset:d,projected_length:l}),Ds(c,d,s,e),o+=l,a=false;}return s}g(Bc,"_walk_doc_body");function Os(n,e,t,r){let i=e._element,s=t,o=0;for(let a of n.rows){if(o>0)if(o===1){let l=n.rows[0],d=new Set,f=0;for(let _ of l.cells)d.has(_)||(d.add(_),f+=1);let h=f>0?Array(f).fill("---").join(" | ").length:0;s+=1+h+1;}else s+=1;let c=new Set,u=0;for(let l of a.cells){if(c.has(l))continue;c.add(l),u>0&&(s+=3);let[d,f]=Fc(l,i,s,r);if(f)return d;s=d,u++;}o++;}return t}g(Os,"_compute_inner_block_offset");function Fc(n,e,t,r){let i=t,s=true;for(let o of Ue(n)){if(s||(i+=2),o instanceof ne){if(o._element===e)return [i,true];let a=ze(o),c=Rt(o,r,false);i+=(a+c).length;}else if(o instanceof Le){let a=Os(o,new ne(e,null),i,r);if(a!==i&&Wc(e,o._element))return [a,true];let c=mn(o,r,false,0);i+=c?c.length:0;}s=false;}return [i,false]}g(Fc,"_walk_cell_for_offset");function Wc(n,e){let t=n.parentNode;for(;t;){if(t===e)return true;t=t.parentNode;}return false}g(Wc,"_element_is_descendant");function Ds(n,e,t,r){let i=new Set;for(let s of n.rows)for(let o of s.cells)if(!i.has(o)){i.add(o);for(let a of Ue(o))if(a instanceof ne){let c=It(a)?Os(n,a,e,r):e;t.push({item:a,is_paragraph:true,is_table:false,start_offset:c,projected_length:0});}else a instanceof Le&&(t.push({item:a,is_paragraph:false,is_table:true,start_offset:e,projected_length:0}),Ds(a,e,t,r));}}g(Ds,"_record_table_inner_blocks_lite");function Rs(n,e){let t=[],r=n.constructor.name;if(r==="NotesPart"){let s=n.note_type==="fn"?"## Footnotes":"## Endnotes";t.push(`---
|
|
105
|
-
${s}`);}let i=true;for(let s of Ue(n))if(s.constructor.name==="FootnoteItem"){let o=Rs(s,e);o&&t.push(o);}else if(s instanceof ne){let o=ze(s);i&&r==="FootnoteItem"&&(o=`[^${n.note_type}-${n.id}]: ${o}`);let a=Rt(s,e,false);t.push(o+a),i=false;}else if(s instanceof Le){let o=mn(s,e,false,0);o&&t.push(o),i=false;}return t.join(`
|
|
95
|
+
`)),t.push(s)),r=[],i=0,s=-1;},"flush_current");for(let[a,l,d]of n){let c=a.length,u=c+(r.length>0?2:0);if(r.length>0&&i+u>_i&&o(),r.length===0&&c>_i){e.push(a),t.push(l);continue}r.length===0&&(s=l),r.push(a),i+=i>0?u:c,d&&o();}return o(),e.length?[e,t]:[[""],[0]]}g(Vl,"_assemble_pages");function gi(n){let e=[...n.matchAll(Xl)];return new Set(e.map(r=>r[1])).size}g(gi,"_count_tracked_changes");var Ql=5,wi=50;function Kl(n,e,t,r){let i=r.length;if(i<2)throw new Error(`format_ambiguity_error requires at least 2 matches, got ${i}`);let s=r.slice(0,Ql),o=i-s.length,a=[`- Edit ${n} Failed: Ambiguous match. Target text appears ${i} times. First ${s.length} occurrences:`];for(let l=0;l<s.length;l++){let[d,c]=s[l],u=Math.max(0,d-wi),f=Math.min(t.length,c+wi),h=t.substring(u,d).replace(/\n/g," "),_=t.substring(c,f).replace(/\n/g," "),p=t.substring(d,c).replace(/\n/g," ");p.length>50&&(p=p.substring(0,25)+"..."+p.substring(p.length-20));let m=u>0?"...":"",w=f<t.length?"...":"";a.push(` ${l+1}. "${m}${h}[${p}]${_}${w}"`);}return o>0&&a.push(` ... and ${o} 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(`
|
|
96
|
+
`)}g(Kl,"format_ambiguity_error");var Zl="3.2.1";function ne(n,e){let t=[],r=n.getElementsByTagName("*");for(let i=0;i<r.length;i++){let s=r[i].tagName;(s===e||s.endsWith(":"+e))&&t.push(r[i]);}return t}g(ne,"findDescendantsByLocalName");function ec(n){let e=0;function t(o,a){let l=o?o.toString():"",d=a?a.toString():"";return l===d}g(t,"areRunsIdentical");function r(o){let a=["w:t","w:tab","w:br","w:cr","w:delText","w:rPr"];for(let l=0;l<o.childNodes.length;l++){let d=o.childNodes[l];if(d.nodeType===1){let c=d.tagName;if(!a.includes(c))return true}}return false}g(r,"hasSpecialContent");function i(o){let a=Array.from(o.childNodes).filter(d=>d.nodeType===1),l=0;for(;l<a.length-1;){let d=a[l],c=a[l+1];if(d.tagName==="w:r"&&c.tagName==="w:r"&&!r(d)&&!r(c)){let u=$(d,"w:rPr"),f=$(c,"w:rPr");if(t(u,f)){let h=null;for(let p=0;p<d.childNodes.length;p++){let m=d.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||"",y=m+w;h.textContent=y,y.trim()!==y&&h.setAttribute("xml:space","preserve");}else d.appendChild(p),(p.tagName==="w:t"||p.tagName==="w:delText")&&(h=p);o.removeChild(c),a.splice(l+1,1),e++;continue}}["w:ins","w:del","w:hyperlink","w:sdt","w:smartTag","w:fldSimple","w:sdtContent"].includes(d.tagName)&&i(d),l++;}if(a.length>0){let d=a[a.length-1];["w:ins","w:del","w:hyperlink","w:sdt","w:smartTag","w:fldSimple","w:sdtContent"].includes(d.tagName)&&i(d);}}g(i,"coalesceContainer");let s=R(n.element,"w:p");for(let o of s)i(o);return e?[`Adjacent identical runs coalesced: ${e}`]:[]}g(ec,"coalesce_runs");function tc(n){let e=0,t=["w:rsidR","w:rsidRPr","w:rsidRDefault","w:rsidP","w:rsidDel","w:rsidSect","w:rsidTr"],r=n.element.getElementsByTagName("*");for(let s=0;s<r.length;s++)for(let o of t)r[s].hasAttribute(o)&&(r[s].removeAttribute(o),e++);let i=R(n.element,"w:rsids");for(let s of i)s.parentNode&&(s.parentNode.removeChild(s),e++);return e?[`rsid attributes: ${e} removed`]:[]}g(tc,"strip_rsid");function nc(n){let e=0,t=["w14:paraId","w14:textId"],r=n.element.getElementsByTagName("*");for(let i=0;i<r.length;i++)for(let s of t)r[i].hasAttribute(s)&&(r[i].removeAttribute(s),e++);return e?[`Paragraph/text IDs: ${e} removed`]:[]}g(nc,"strip_para_ids");function rc(n){let e=R(n.element,"w:proofErr");return e.forEach(t=>t.parentNode?.removeChild(t)),e.length?[`Spell check markers: ${e.length} removed`]:[]}g(rc,"strip_proof_errors");function ic(n){let e=0;for(let t of ["w:rPr","w:pPr"]){let r=R(n.element,t);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(ic,"strip_empty_properties");function sc(n){let e=0,t=R(n.element,"w:rPr");for(let r of t)if($(r,"w:vanish")||$(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(sc,"strip_hidden_text");function yi(n){let e=R(n.element,"w:ins").length,t=R(n.element,"w:del").length,r=R(n.element,"w:rPrChange").length+R(n.element,"w:pPrChange").length+R(n.element,"w:sectPrChange").length;return [e,t,r]}g(yi,"count_tracked_changes");function oc(n){let e=new Set;for(let t of ["w:ins","w:del","w:rPrChange","w:pPrChange","w:sectPrChange"])for(let r of R(n.element,t)){let i=r.getAttribute("w:author");i&&e.add(i);}return e}g(oc,"get_track_change_authors");function vi(n){let e=[],t=R(n,"w:t");for(let i of t)i.textContent&&e.push(i.textContent);let r=R(n,"w:delText");for(let i of r)i.textContent&&e.push(i.textContent);return e.join("")}g(vi,"_getElementText");function We(n,e=60){let t=n.replace(/\n/g," ").trim();return t.length<=e?t:t.substring(0,e-3)+"..."}g(We,"_truncate");function bi(n){let e=n.parentNode;if(e&&e.tagName==="w:rPr"){let t=e.parentNode;if(t&&t.tagName==="w:pPr")return "(paragraph mark)"}return e&&e.tagName==="w:trPr"?"(table row)":"(no visible text)"}g(bi,"_describe_textless_revision");function ac(n){let e=[],t=R(n.element,"w:ins"),r=R(n.element,"w:del");for(let o of t){let a=vi(o).trim();a?e.push(` Accepted insertion: "${We(a,60)}"`):e.push(` Accepted insertion: ${bi(o)}`);}for(let o of r){let a=vi(o).trim();a?e.push(` Accepted deletion of: "${We(a,60)}"`):e.push(` Accepted deletion of: ${bi(o)}`);}new Bt(n).accept_all_revisions();for(let o of ["w:rPrChange","w:pPrChange","w:sectPrChange"])for(let a of R(n.element,o))a.parentNode?.removeChild(a);let s=t.length+r.length;return s?[`Tracked changes auto-accepted: ${s}`].concat(e):[]}g(ac,"accept_all_tracked_changes");function Yt(n){let e=Fe(n.pkg),t=[],r=0,i=0;for(let[s,o]of Object.entries(e))o.resolved?i++:r++,t.push({id:s,...o});return {total:t.length,open:r,resolved:i,comments:t}}g(Yt,"get_comments_summary");function lc(n){let e=Fe(n.pkg),t=Object.keys(e);if(t.length===0)return [];let r=[],i=new It(n);for(let[l,d]of Object.entries(e)){let c=d.resolved?"[Resolved]":"[Open]";r.push(` ${c} "${We(d.text||"",60)}" (${d.author||"Unknown"})`),i.deleteComment(l);}for(let l of ["w:commentRangeStart","w:commentRangeEnd"])for(let d of R(n.element,l))d.parentNode?.removeChild(d);let s=R(n.element,"w:commentReference");for(let l of s){let d=l.parentNode;d&&((d.tagName==="w:r"||d.tagName.endsWith(":r"))&&Array.from(d.childNodes).filter(u=>u.nodeType===1&&u.tagName!=="w:rPr"&&u.tagName!=="rPr").length<=1?d.parentNode?.removeChild(d):d.removeChild(l));}let o=Object.values(e).filter(l=>l.resolved).length,a=Object.values(e).filter(l=>!l.resolved).length;return [`Comments removed: ${t.length} (${o} resolved, ${a} open)`].concat(r)}g(lc,"remove_all_comments");function cc(n){let e=n.pkg,t=new Set;for(let i of e.parts)if(i.partname.toLowerCase().includes("comments")){t.add(i.partname);let s=i.partname.startsWith("/")?i.partname:"/"+i.partname,o=i.partname.startsWith("/")?i.partname.substring(1):i.partname;t.add(s),t.add(o);}if(t.size===0)return;for(let i of e.parts)if(i.partname.endsWith(".rels")){let s=R(i._element,"Relationship"),o=[];for(let a of s)if((a.getAttribute("Target")||"").toLowerCase().includes("comments")){o.push(a);let d=i.partname.replace("/_rels/","/").replace(".rels",""),c=e.getPartByPath(d);if(c){let u=a.getAttribute("Id");u&&c.rels.delete(u);}}for(let a of o)a.parentNode?.removeChild(a);}let r=e.getPartByPath("[Content_Types].xml");if(r){let i=R(r._element,"Override"),s=[];for(let o of i){let a=o.getAttribute("PartName")||"";(t.has(a)||a.toLowerCase().includes("comments"))&&s.push(o);}for(let o of s)o.parentNode?.removeChild(o);}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(cc,"eject_comment_parts");function dc(n,e){let t=new It(n);if(!t.commentsPart)return [];let r=new Set,i=R(t.commentsPart._element,"w:comment");for(let s of i){let o=s.getAttribute("w:author");if(o&&(r.add(o),s.setAttribute("w:author",e)),s.hasAttribute("w:initials")){let a=e.split(" ").filter(Boolean).map(l=>l[0]).join("").toUpperCase();s.setAttribute("w:initials",a);}}return r.size?[`Comment authors replaced: ${Array.from(r).sort().join(", ")} \u2192 "${e}"`]:[]}g(dc,"replace_comment_authors");function uc(n,e){let t=new Set;for(let r of ["w:ins","w:del","w:rPrChange","w:pPrChange"])for(let i of R(n.element,r)){let s=i.getAttribute("w:author");s&&(t.add(s),i.setAttribute("w:author",e));}return t.size?[`Track change authors replaced: ${Array.from(t).sort().join(", ")} \u2192 "${e}"`]:[]}g(uc,"replace_change_authors");function fc(n){let e=0,t="2025-01-01T00:00:00Z";for(let r of ["w:ins","w:del","w:rPrChange","w:pPrChange"])for(let i of R(n.element,r))i.hasAttribute("w:date")&&(i.setAttribute("w:date",t),e++);return e?[`Track change timestamps: ${e} normalized`]:[]}g(fc,"normalize_change_dates");function hc(n){let e=0,t="2025-01-01T00:00:00Z";for(let r of n.pkg.parts)if(r.contentType.includes("comments")){for(let i of R(r._element,"w:comment"))i.hasAttribute("w:date")&&(i.setAttribute("w:date",t),e++);for(let i of R(r._element,"w16cex:commentExtensible"))i.hasAttribute("w16cex:dateUtc")&&(i.setAttribute("w16cex:dateUtc",t),e++);}return e?[`Comment timestamps: ${e} normalized`]:[]}g(hc,"normalize_comment_dates");function pc(n){let e=[],t=n.pkg.getPartByPath("docProps/core.xml");if(t){ne(t._element,"creator").forEach(d=>{d.textContent&&(e.push(`Author: ${d.textContent}`),d.textContent="");}),ne(t._element,"lastModifiedBy").forEach(d=>{d.textContent&&(e.push(`Last modified by: ${d.textContent}`),d.textContent="");}),ne(t._element,"title").forEach(d=>{d.textContent&&e.push(`Title kept (review manually): "${d.textContent}"`);});let a=[["category","Category"],["keywords","Keywords"],["subject","Subject"],["contentStatus","Content status"],["description","Description/comments"],["identifier","Identifier"],["language","Language"],["version","Version"]];for(let[d,c]of a)ne(t._element,d).forEach(u=>{u.textContent&&(e.push(`${c}: ${u.textContent}`),u.textContent="");});ne(t._element,"revision").forEach(d=>{d.textContent&&parseInt(d.textContent)>1&&(e.push(`Revision count: ${d.textContent} \u2192 1`),d.textContent="1");});}let r=n.pkg.getPartByPath("docProps/app.xml");if(r){let i=r._element,s=["TotalTime","Words","Characters","Paragraphs","Lines","CharactersWithSpaces"];for(let a of s)ne(i,a).forEach(l=>{l.textContent&&l.textContent!=="0"&&(a==="TotalTime"&&e.push(`Total editing time: ${l.textContent} minutes`),l.textContent="0");});let o=["Template","Manager","Company"];for(let a of o)ne(i,a).forEach(l=>{l.textContent&&(e.push(`${a}: ${l.textContent}`),l.textContent="");});}return e.length?["Metadata scrubbed:",...e.map(i=>` ${i}`)]:[]}g(pc,"scrub_doc_properties");function _c(n){let e=false,t="1970-01-01T00:00:00Z",r=n.pkg.getPartByPath("docProps/core.xml");if(r)for(let i of ["created","modified","lastPrinted"])ne(r._element,i).forEach(s=>{s.textContent&&s.textContent!==t&&(s.textContent=t,e=true);});return e?["Timestamps normalized to epoch"]:[]}g(_c,"scrub_timestamps");function js(n,e,t){let r=n.pkg,i=g(o=>o.startsWith("/")?o.substring(1):o,"normalized");for(let o of r.parts){if(!o.partname.endsWith(".rels"))continue;let a=[];for(let l of R(o._element,"Relationship")){let d=l.getAttribute("Target")||"";if(t(d)){a.push(l);let c=o.partname.replace("/_rels/","/").replace(".rels",""),u=r.getPartByPath(c);if(u){let f=l.getAttribute("Id");f&&u.rels.delete(f);}}}a.forEach(l=>l.parentNode?.removeChild(l));}let s=r.getPartByPath("[Content_Types].xml");if(s){let o=[];for(let a of R(s._element,"Override")){let l=a.getAttribute("PartName")||"";e(i(l))&&o.push(a);}o.forEach(a=>a.parentNode?.removeChild(a));}r.parts=r.parts.filter(o=>!e(i(o.partname)));for(let o of Object.keys(r.unzipped))e(i(o))&&delete r.unzipped[o];}g(js,"ejectPackageMembers");function mc(n){let e=g(i=>i.startsWith("customXml/"),"isCustomXml"),t=n.pkg.parts.filter(i=>e(i.partname.startsWith("/")?i.partname.substring(1):i.partname)),r=Object.keys(n.pkg.unzipped).filter(e);if(t.length===0&&r.length===0)return [];js(n,e,i=>i.includes("customXml"));for(let i of R(n.element,"w:sdtPr"))fn(i,"w:dataBinding").forEach(s=>i.removeChild(s));return [`Custom XML parts: ${Math.max(t.length,r.length)} removed`]}g(mc,"strip_custom_xml");var Jn="docProps/custom.xml";function gc(n){let e=n.pkg.getPartByPath(Jn),t=Object.keys(n.pkg.unzipped).includes(Jn);if(!e&&!t)return [];let r=[];if(e)for(let s of ne(e._element,"property")){let o=s.getAttribute("name")||"(unnamed)",a=(s.textContent||"").trim();r.push(` Custom property removed: ${o} = "${We(a,60)}"`);}return js(n,s=>s===Jn,s=>s.includes("docProps/custom.xml")),[`Custom document properties: ${Math.max(r.length,1)} removed (docProps/custom.xml)`].concat(r)}g(gc,"strip_custom_properties");function wc(n){let e=n.pkg.getPartByPath("word/settings.xml");if(!e)return [];let t=[],r=false;for(let s of ne(e._element,"docVars")){for(let o of Array.from(s.childNodes)){let a=o,l=a.tagName||"";(l==="docVar"||l.endsWith(":docVar"))&&t.push(a.getAttribute("w:name")||a.getAttribute("name")||"(unnamed)");}s.parentNode?.removeChild(s),r=true;}for(let s of ne(e._element,"docVar"))t.push(s.getAttribute("w:name")||s.getAttribute("name")||"(unnamed)"),s.parentNode?.removeChild(s),r=true;if(!r)return [];let i=Array.from(new Set(t)).sort().join(", ")||"(unnamed)";return [`Document variables: ${t.length} removed (${i})`]}g(wc,"strip_document_variables");function yc(n){let e=0;for(let t of ne(n.element,"docPr")){let r=t.getAttribute("descr");if(r){let i=r.length<10,s=r.includes(".")&&r.length<60;(i||s)&&(t.removeAttribute("descr"),e++);}}return e?[`Image alt text: ${e} auto-generated descriptions removed`]:[]}g(yc,"strip_image_alt_text");function vc(n){let e=[],t=new Set;for(let r of n.pkg.parts){let i=String(r.partname),s;if(i.startsWith("/word/header"))s="header";else if(i.startsWith("/word/footer"))s="footer";else if(i==="/word/document.xml")s="body";else continue;let o;try{o=ne(r._element,"textpath");}catch{continue}for(let a of o){let l=(a.getAttribute("string")||"").trim(),d=`${s}${l}`;if(t.has(d))continue;t.add(d);let c=l?`"${We(l,60)}"`:"(no text)";e.push(`Watermark-like text object in ${s}: ${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(vc,"detect_watermarks");function bc(n){let e=["sharepoint.com","onedrive.com",".internal","intranet","localhost","10.","192.168.","172.16."],t=[],r=n.pkg.getOrCreateRelsPart(n.part.partname);for(let i of R(r._element,"Relationship"))if(i.getAttribute("TargetMode")==="External"){let s=i.getAttribute("Target")||"";for(let o of e)if(s.toLowerCase().includes(o.toLowerCase())){t.push(`Hyperlink targets internal URL: ${We(s,80)}`);break}}return t}g(bc,"audit_hyperlinks");var xc="word/settings.xml",Nc=new Set(["readOnly","forms","comments","trackedChanges"]),kc={readOnly:"read-only",forms:"fill-in-forms",comments:"comments-only",trackedChanges:"tracked-changes-only"},kt=Object.freeze({edit:null,enforced:false});function vn(n){return n.edit!==null&&n.enforced}g(vn,"isProtectionActive");function Cr(n){return n.edit===null?"unprotected":`${kc[n.edit]??n.edit}, ${n.enforced?"enforced":"not enforced"}`}g(Cr,"describeProtection");function Cc(n){return n==null?true:!["0","false","off"].includes(n.toLowerCase())}g(Cc,"isTruthy");function bn(n){let e=null;try{let s=n?.pkg?.getPartByPath?.(xc);if(!s?._element)return kt;e=ne(s._element,"documentProtection")[0]??null;}catch{return kt}if(!e)return kt;let t=null,r=null,i=e.attributes;if(i)for(let s=0;s<i.length;s++){let o=i[s],a=(o.name??"").split(":").pop()??"";a==="edit"?t=o.value:a==="enforcement"&&(r=o.value);}return t===null||!Nc.has(t)?kt:{edit:t,enforced:Cc(r)}}g(bn,"readDocumentProtection");var xn="ignore_control_locks",Pt="ignore_document_protection",Er="allow_untracked_writes",rt=Object.freeze({ignore_control_locks:false,ignore_document_protection:false,allow_untracked_writes:false});function Ec(n){return n.ignore_control_locks||n.ignore_document_protection||n.allow_untracked_writes}g(Ec,"anyOverrideUsed");function ye(n){let e=[`CC:${n.ordinal}`];return n.alias&&e.push(`"${n.alias}"`),n.tag&&e.push(`(tag: ${n.tag})`),e.join(" ")}g(ye,"describeControl");function we(n,e){let t=`- Edit ${n} Failed: ${e.subject} ${e.rule} ${Ac(e.alternative)}`;return e.override&&(t+=` Pass ${e.override}=true to override deliberately.`),t.split(/\s+/).join(" ")}g(we,"gateError");function Ac(n){let e=n.replace(/\s+$/,"");return /[.!?:]$/.test(e)?e:`${e}.`}g(Ac,"endSentence");function Pc(n){return n.find(e=>e.contentLocked)??null}g(Pc,"lockedAncestor");function Tc(n,e,t=rt){if(t.ignore_control_locks)return null;let r=Pc(e);return r?we(n,{subject:`edit targets content inside ${ye(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:xn}):null}g(Tc,"checkContentLock");function $c(n,e,t=rt){if(t.ignore_control_locks)return null;let r=e.find(i=>i.cls==="group");return !r||e.some(i=>i.cls!=="group")?null:we(n,{subject:`edit targets text inside ${ye(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:xn})}g($c,"checkGroupRegion");function Sc(n,e,t,r=rt){if(r.ignore_control_locks||!t)return null;let i=e.find(s=>s.deleteLocked);return i?we(n,{subject:`edit would remove ${ye(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:xn}):null}g(Sc,"checkDeleteLock");function Ic(n,e,t={}){let r=t.overrides??rt;if(!vn(e)||r.ignore_document_protection)return null;let i=Cr(e);return e.edit==="readOnly"?we(n,{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:Pt}):e.edit==="comments"?t.isCommentOnly?null:we(n,{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:Pt}):e.edit==="forms"?(t.controls??[]).some(o=>o.cls!=="group")?null:we(n,{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:Pt}):null}g(Ic,"checkProtectionBlocksEdit");function Oc(n,e,t,r=rt){if(!vn(t)||r.ignore_document_protection||e!=="accept"&&e!=="reject"||t.edit!=="trackedChanges"&&t.edit!=="readOnly")return null;let i=t.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 ${n} Failed: the document is protected (${Cr(t)}). ${i} Remove the restriction in Word (Review -> Restrict Editing -> Stop Protection) or pass ${Pt}=true to override deliberately.`}g(Oc,"checkProtectionBlocksReview");function Dc(n,e,t=rt){return !vn(e)||e.edit!=="forms"||t.allow_untracked_writes?null:we(n,{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:Er})}g(Dc,"checkUntrackedWrite");function Rc(n,e,t){let r=(e||"").trim();if(!r)return null;for(let i of t){if(!i.showingPlaceholder)continue;let s=(i.placeholderText||"").trim();if(!(!s||!s.includes(r)))return we(n,{subject:`target_text is the placeholder text of ${ye(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(Rc,"checkPlaceholderTarget");var Ct=["[ ]","[x]"];function Mc(n,e,t,r){let i=e.find(o=>o.cls==="checkbox");if(!i)return null;let s=Ct;return s.includes(t.trim())&&s.includes(r.trim())?null:we(n,{subject:`edit targets ${ye(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(Mc,"checkCheckboxEdit");function jc(n,e){let t=e.find(i=>i.bound);if(!t)return null;let r=t.bindingXpath?` (bound to ${t.bindingXpath})`:"";return we(n,{subject:`edit targets the content of ${ye(t)}, 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(jc,"checkBoundControl");function xi(n,e,t){let r=new Set(e),i=new Set(t);return n.filter(s=>r.has(s)!==i.has(s))}g(xi,"crossedControlWalls");function Bc(n,e){if(e.length===0)return null;let t=e.map(ye).join(", ");return we(n,{subject:`edit merges paragraphs across the boundary of ${t}.`,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(Bc,"checkBlockMergeAcrossControl");function Fc(n){return `segmented at the boundary of ${n.map(ye).join(", ")}: only the text outside the control was changed`}g(Fc,"segmentationNote");function Lc(n,e){if(!Ec(n))return null;let t=[];if(n.ignore_control_locks){let r=e.length>0?` (${e.map(ye).join(", ")} edited inside locked controls)`:"";t.push(`${xn}${r}`);}return n.ignore_document_protection&&t.push(Pt),n.allow_untracked_writes&&t.push(Er),"Overrides: "+t.join(", ")}g(Lc,"overridesNote");function Wc(n,e,t=2){if(n===e)return 0;if(Math.abs(n.length-e.length)>t)return t+1;if(n.length===0)return e.length<=t?e.length:t+1;if(e.length===0)return n.length<=t?n.length:t+1;if(n.length>e.length){let i=n;n=e,e=i;}let r=Array.from({length:n.length+1},(i,s)=>s);for(let i=1;i<=e.length;i++){let s=[i],o=i;for(let a=1;a<=n.length;a++){let l=n[a-1]===e[i-1]?0:1,d=Math.min(r[a]+1,s[a-1]+1,r[a-1]+l);s.push(d),d<o&&(o=d);}if(o>t)return t+1;r=s;}return r[n.length]<=t?r[n.length]:t+1}g(Wc,"boundedLevenshtein");function zc(n){let e="",t=R(n._element,"w:r");for(let r of t){let i=false,s=r.parentNode;for(;s&&s.nodeType===1;){if(s.tagName==="w:del"){i=true;break}s=s.parentNode;}i||(e+=Ie(new Be(r,n)));}return e}g(zc,"_get_paragraph_text");var Ar="[A-Z][A-Za-z0-9\\s\\-&'\u2019]{1,60}",Uc=new RegExp(`^(?:[\\d.\\-()a-zA-Z]+\\s*)?["\u201C](${Ar})["\u201D]`,"d"),Hc=new RegExp(`(?<=[.;:!?])\\s+(?:[\\d.\\-()a-zA-Z]+\\s+)?["\u201C](${Ar})["\u201D]`,"dg"),qc=new RegExp(`\\([^)]*?["\u201C](${Ar})["\u201D][^)]*?\\)`,"dg");function Xc(n){let e=[],t=Uc.exec(n);t&&t.indices&&t.indices[1]&&n.slice(t[0].length).trim()&&e.push([t.indices[1][0],t[1].trim()]);for(let s of n.matchAll(Hc)){let o=s.indices;o&&o[1]&&e.push([o[1][0],s[1].trim()]);}for(let s of n.matchAll(qc)){let o=s.indices;o&&o[1]&&e.push([o[1][0],s[1].trim()]);}let r=[],i=new Set;e.sort((s,o)=>s[0]-o[0]);for(let[s,o]of e)i.has(s)||(i.add(s),r.push(o));return r}g(Xc,"extract_terms_from_paragraph");function Yc(n,e){let t=Object.create(null),r=new Set,i=Object.create(null),s=[];for(let p of He(n)){if(!(p instanceof ie))continue;let m=zc(p).trim();if(!m)continue;for(let b of Xc(m))t[b]?r.add(b):t[b]={count:0};let w=m.length>60?m.substring(0,60)+"...":m,y=R(p._element,"*");for(let b of y){if(b.tagName==="w:bookmarkStart"){let N=b.getAttribute("w:name");N&&(!N.startsWith("_")||N.startsWith("_Ref"))&&(i[N]||(i[N]={anchored_to:w,referenced_from:[]}));}let v=null;if(b.tagName==="w:fldSimple"){let k=(b.getAttribute("w:instr")||"").trim().split(/\s+/);k.length>1&&k[0]==="REF"&&(v=k[1]);}else if(b.tagName==="w:instrText"){let k=(b.textContent||"").trim().split(/\s+/);k.length>1&&k[0]==="REF"&&(v=k[1]);}v&&s.push([v,w]);}}for(let[p,m]of s)i[p]&&i[p].referenced_from.push(m);let o=[],a=Object.keys(t);if(a.length>0){let p=a.sort((b,v)=>v.length-b.length),m=g(b=>b.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegExp"),w=p.map(m).join("|"),y=new RegExp(`(?<!["\u201C])\\b(${w})\\b(?![\u201D"])`,"g");for(let b of e.matchAll(y)){let v=b[1];t[v]&&t[v].count++;}for(let b of a)t[b].count===0&&(delete t[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 l=new Set(["The","This","That","Such","A","An","Any","All","Some","No","Every","Each","As","In","Of","For","To","On","By","With"]),d=/\b[A-Z][a-zA-Z]*(?:\s+[A-Z][a-zA-Z]*)*\b/g,c=new Set(e.match(d)||[]),u=new Set(Object.keys(t)),f={};for(let p of u){let m=p[0].toLowerCase();f[m]||(f[m]=[]),f[m].push(p);}let h=Object.create(null);for(let p of c){let m=p.trim(),w=m.split(/\s+/);for(;w.length>0;){let v=w[0],N=v.charAt(0).toUpperCase()+v.slice(1).toLowerCase();if(l.has(N))w.shift();else break}if(m=w.join(" "),m.length<4||u.has(m))continue;let y=m[0].toLowerCase(),b=f[y]||[];if(m.length>5)for(let[v,N]of Object.entries(f))v!==y&&(b=b.concat(N));for(let v of b){if(Math.abs(m.length-v.length)>2||m===v+"s"||m===v+"es"||v===m+"s"||v===m+"es")continue;let N=Wc(m,v,2);N===0||N>2||v.length<=5&&(N>1||m[0].toLowerCase()!==v[0].toLowerCase())||(h[v]||(h[v]=[]),h[v].includes(m)||h[v].push(m));}}for(let[p,m]of Object.entries(h)){m.sort();let w=m.map(y=>`'${y}'`).join(", ");o.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"),o.sort((p,m)=>{let w=_(p),y=_(m);return w!==y?w-y:p.localeCompare(m)}),[t,o,i]}g(Yc,"extract_all_domain_metadata");function Gc(n){let e=[],t=n.pkg.getPartByPath("word/settings.xml");if(!t)return e;let r=g(o=>{if(!o.hasAttribute("w:val"))return true;let a=(o.getAttribute("w:val")||"").toLowerCase();return a!=="0"&&a!=="false"&&a!=="off"},"isTruthy2"),i=ne(t._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 s=ne(t._element,"removeDateAndTime");return s.length>0&&r(s[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(Gc,"extract_document_settings_warnings");function Jc(n,e){try{let t=kd(n),r=bn(n);return Pd(t,r,'Read with mode="fields" for the full field ledger.')}catch{return []}}g(Jc,"content_controls_appendix_section");function Vc(n,e){let[t,r,i]=Yc(n,e),s=Gc(n),o=[`
|
|
106
97
|
|
|
107
|
-
|
|
108
|
-
|
|
98
|
+
---`,"","<!-- 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(s.length>0){a=true,o.push(`
|
|
99
|
+
## Document Settings`);for(let d of s)o.push(`- ${d}`);}let l=Jc(n);if(l.length>0&&(a=true,o.push(""),o.push(...l)),Object.keys(t).length>0){a=true,o.push(`
|
|
100
|
+
## Defined Terms`);for(let[d,c]of Object.entries(t))o.push(`- "${d}" \u2014 used ${c.count} time${c.count===1?"":"s"}.`);}if(r.length>0){a=true,o.push(`
|
|
101
|
+
## Semantic Diagnostics`);for(let d of r)o.push(`- ${d}`);}if(Object.keys(i).length>0){a=true,o.push(`
|
|
102
|
+
## Named Anchors`);for(let[d,c]of Object.entries(i)){o.push(`- ${d} \u2192 Anchored to: "${c.anchored_to}"`);for(let u of c.referenced_from)o.push(` - Referenced from: "${u}"`);}}return a?o.join(`
|
|
103
|
+
`):""}g(Vc,"build_structural_appendix");async function qe(n,e=false,t=true){let r=await ae.load(n);return Xe(r,e,t)}g(qe,"extractTextFromBuffer");function Xe(n,e=false,t=true,r=false,i=false){let s=Fe(n.pkg),o=[],a=new Map,l=i?{part_ranges:[],tables:[]}:null,d=0,c=pn(Array.from(Ze(n)).map(([f])=>_n(f)));for(let[f,h]of Ze(n)){let _=o.length>0?d+2:d,p=cn(f,s,e,_,r?a:void 0,l?l.tables:void 0,c);p&&(o.length>0&&(d+=2),o.push(p),l&&l.part_ranges.push([d,d+p.length,h]),d+=p.length);}let u=o.join(`
|
|
104
|
+
|
|
105
|
+
`);if(t){let f=Vc(n,u);f&&(u+=f);}return r?{text:u,paragraph_offsets:a}:l?{text:u,structure:l}:u}g(Xe,"_extractTextFromDoc");function cn(n,e,t,r,i,s,o,a=false){let l=n.part||n,[d,c]=_t(l),u=[],f=r,h=true,_=true;if(n.constructor&&n.constructor.name==="NotesPart"){let m=`---
|
|
106
|
+
${n.note_type==="fn"?"## Footnotes":"## Endnotes"}`;u.push(m),f+=m.length,h=false;}for(let p of He(n,!!o)){h||(f+=2);let m=f;if(p instanceof mr){let w=o?o.get(p.element):void 0,y=!!w&&St(w),b=a?"":`
|
|
107
|
+
`,v=y?`${Me(w)}${b}`:"",N=cn({_element:$(p.element,"w:sdtContent"),part:n.part||n},e,t,m+v.length,i,void 0,o,a);if(N){let k=y?`${v}${N}${b}${je(w)}`:N;u.push(k),f=m+k.length,h=false;}else h||(f-=2);_=false;}else if(p.constructor.name==="FootnoteItem"){let w=cn(p,e,t,m,i,void 0,o);w?(u.push(w),f=m+w.length,h=false):h||(f-=2);}else if(p instanceof ie){let w=Ue(p,d,c);_&&n.constructor.name==="FootnoteItem"&&(w=`[^${n.note_type}-${n.id}]: `+w);let y=jt(p,e,t,d,c,o);if(t&&!y&&ks(p._element)){h||(f-=2),_=false;continue}let b=w+y;u.push(b),i&&i.set(p._element,[m,b.length]),f=m+b.length,_=false,h=false;}else if(p instanceof ze){let w=s?{start:m,end:m,rows:[]}:null,y=Nn(p,e,t,m,i,w,o);y?(u.push(y),f=m+y.length,h=false,w&&s&&(w.end=m+y.length,s.push(w))):h||(f-=2),_=false;}}return u.join(`
|
|
108
|
+
|
|
109
|
+
`)}g(cn,"_extract_blocks");function Ni(n,e){if(!e)return null;let t=ls(n);if(!t)return null;let r=e.get(t);return r&&St(r)?r:null}g(Ni,"anchoredWrapper");function Nn(n,e,t,r,i,s,o){let a=[],l=0,d=r;for(let c of n.rows){let u=[],f=new Set,h=$(c._element,"w:trPr"),_=h?$(h,"w:ins"):null,p=h?$(h,"w:del"):null;if(t&&p)continue;let m=d+(l>0?1:0),y=m+(!t&&_||!t&&p?4:0),b=true;for(let k of c.cells){if(f.has(k))continue;f.add(k),b||(y+=3);let x=Ni(k._element,o),P=x?Me(x):"",E=cn(k,e,t,y+P.length,i,void 0,o,true);if(x&&(E=`${P}${E}${je(x)}`),!t){let{paraId:T}=ts(k._element,!E||E.trim()==="");if(T){let I=E&&!E.endsWith(" ")?" ":"";E=E+`${I}{#cell:${T}}`;}}u.push(E),y+=E.length,b=false;}let v=u.join(" | "),N=Ni(c._element,o);if(N&&(v=`${Me(N)}${v}${je(N)}`),t||(_?v=`{++ ${v} ++}{>>[Chg:${_.getAttribute("w:id")} insert] ${_.getAttribute("w:author")||"Unknown"}<<}`:p&&(v=`{-- ${v} --}{>>[Chg:${p.getAttribute("w:id")} delete] ${p.getAttribute("w:author")||"Unknown"}<<}`)),a.push(v),d=m+v.length,s&&s.rows.push({start:m,end:d,cells:[...u]}),l++,l===1){let k=u.length;if(k>0){let x=Array(k).fill("---").join(" | ");a.push(x),d+=1+x.length;}}}return a.join(`
|
|
110
|
+
`)}g(Nn,"extract_table");function jt(n,e,t,r,i,s){let o=[],a=Object.create(null),l=Object.create(null),d=new Set,c=Object.create(null),u=[],f=null,h="",_=["",""],p=["",""],m=Array.from(yn(n,s)),w=Cs(n,r,i),y=wn(n,r,i),b=w,v=g(()=>{h&&(o.push(`${_[0]}${h}${_[1]}`),h="",_=["",""],p=["",""]);},"flushPending");for(let N=0;N<m.length;N++){let k=m[N];if(k instanceof Be){let[x,P]=Es(k,y),E=Ie(k);if(t&&Object.keys(l).length>0)continue;if(b){if(!E||!E.trim())continue;b=false;}let T=Cl(E,x,P);if(T){let I=t?["",""]:ki(a,l,d,c),D=[x,P];if(h&&I[0]===_[0]&&I[1]===_[1]){let F=D[0].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),M=D[0]!==""||D[1]!==""?T.match(new RegExp("^(\\s*)"+F)):null,B="";for(let C=h.length-1;C>=0;C--){let S=h[C];if(/\s/.test(S))B=S+B;else break}let j=B?h.slice(0,-B.length):h;D[0]===p[0]&&D[1]===p[1]&&!(p[0]===""&&p[1]==="")&&j.endsWith(p[1])&&M!==null?h=j.slice(0,-p[1].length)+B+M[1]+T.slice(M[0].length):h+=T,p=D;}else v(),h=T,_=I,p=D;if(!t){(Object.keys(a).length>0||Object.keys(l).length>0||d.size>0||Object.keys(c).length>0)&&u.push([{...a},{...l},new Set(d),{...c}]);let M=false;if(Object.keys(a).length>0||Object.keys(l).length>0||Object.keys(c).length>0||d.size>0){let j=N+1,C=false,S=Object.keys(a).length,A=Object.keys(l).length,O=Object.keys(c).length,L=new Set(d);for(;j<m.length;){let H=m[j];if(H instanceof Be){if(!Ie(H)){j++;continue}(S>0||A>0||O>0||L.size>0)&&(C=true);break}else {let q=H;q.type==="ins_start"?S++:q.type==="ins_end"?S=Math.max(0,S-1):q.type==="del_start"?A++:q.type==="del_end"?A=Math.max(0,A-1):q.type==="fmt_start"?O++:q.type==="fmt_end"?O=Math.max(0,O-1):q.type==="start"?L.add(q.id):q.type==="end"&&L.delete(q.id);}j++;}C&&(M=true);}if(!M&&u.length>0){let j=Ci(u,e);j&&(as(m,N)?f=j:(v(),o.push(`{>>${j}<<}`))),u.length=0;}}}}else if(_r(k)){b=false;let x=k.info;if(os.includes(k.type)){if(t&&Object.keys(l).length>0)continue;let P=k.type==="checkbox_start"?is:k.type==="checkbox_end"?ss:pr(x),E=t?["",""]:ki(a,l,d,c);h&&(E[0]!==_[0]||E[1]!==_[1])&&(o.push(`${_[0]}${h}${_[1]}`),h=""),h||(_=E),h+=P,p=["",""],k.type==="checkbox_end"&&f&&(o.push(`${_[0]}${h}${_[1]}`),h="",_=["",""],o.push(`{>>${f}<<}`),f=null);continue}v(),k.type==="sdt_start"?(o.push(Me(x)),!t&&x.showingPlaceholder&&x.placeholderText&&o.push(`{>>placeholder: ${x.placeholderText}<<}`)):o.push(je(x));}else {let x=k;if(b=false,["ins_start","ins_end","del_start","del_end","fmt_start","fmt_end"].includes(x.type)||v(),x.type==="start")d.add(x.id);else if(x.type==="end")d.delete(x.id);else if(x.type==="ins_start")a[x.id]=x;else if(x.type==="ins_end")delete a[x.id];else if(x.type==="del_start")l[x.id]=x;else if(x.type==="del_end")delete l[x.id];else if(x.type==="fmt_start")c[x.id]=x;else if(x.type==="fmt_end")delete c[x.id];else if(x.type==="image"){if(!(t&&Object.keys(l).length>0)){let P=(x.date||"image").replace(/\]/g,")").replace(/\n/g," ");o.push(``);}}else x.type==="footnote"||x.type==="endnote"?(v(),o.push(`[^${x.type==="footnote"?"fn":"en"}-${x.id}]`)):x.type==="hyperlink_start"?(v(),o.push("[")):x.type==="hyperlink_end"?(v(),o.push(`](${x.date})`)):x.type==="xref_start"?(v(),o.push("[~")):x.type==="xref_end"?(v(),o.push(`~](#${x.id})`)):x.type==="bookmark"&&(v(),o.push(`{#${x.id}}`));}}if(v(),u.length>0){let N=Ci(u,e);N&&o.push(`{>>${N}<<}`);}return o.join("")}g(jt,"build_paragraph_text");function ki(n,e,t,r){return Object.keys(e).length>0?["{--","--}"]:Object.keys(n).length>0?["{++","++}"]:t.size>0||Object.keys(r).length>0?["{==","==}"]:["",""]}g(ki,"_get_wrappers");function Ci(n,e){let t=[],r=[],i=new Set,s=Ps(n),o=g(l=>s[l]?` (pairs with ${s[l]})`:"","pairSuffix");for(let[l,d,c,u]of n){let f=g(function(p){if(!e[p])return;let m=`Com:${p}`;if(i.has(m))return;let w=e[p],y=`[${m}] ${w.author}`;if(w.date&&(y+=` @ ${w.date}`),w.resolved&&(y+="(RESOLVED)"),r.push(`${y}: ${fs(w.text)}`),i.add(m),h[p]){let b=h[p].sort((v,N)=>(e[v]?.date||"").localeCompare(e[N]?.date||""));for(let v of b)f(v);}},"render_comment2");for(let[p,m]of Object.entries(l)){let w=`Chg:${p}`;i.has(w)||(t.push(`[${w} insert] ${m.author||"Unknown"}${o(p)}`),i.add(w));}for(let[p,m]of Object.entries(d)){let w=`Chg:${p}`;i.has(w)||(t.push(`[${w} delete] ${m.author||"Unknown"}${o(p)}`),i.add(w));}for(let[p,m]of Object.entries(u)){let w=`Chg:${p}`;i.has(w)||(t.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 [...t,...r].join(`
|
|
111
|
+
`)}g(Ci,"_build_merged_meta_block");var Bs=/^(#{1,6}) /,Qc=/^(?:ARTICLE|PART|SCHEDULE|EXHIBIT|ANNEX|APPENDIX)\s+[0-9IVXLCDMab]+\b/i,Kc=/^(?:\d+\.\d+\.\d+(?:\.\d+)*\.?\s+\S|(?:Section|Paragraph|Clause|Item)\s+\d+(?:\.\d+)*\([a-z0-9]+\))/i,Zc=/^(?:Section|Paragraph|Clause|Item)\s+\d+(?:\.\d+)*\b/i,ed=/^\d+(?:\.\d+)?\.\s+[A-Z]/,Fs=3;function Ls(n,e){for(let t=0;t<n.length;t++){let r=n[t],i=e;for(let s=t+1;s<n.length;s++)if(n[s].level<=r.level){i=n[s].page>r.page?n[s].page-1:r.page;break}r.end_page=i;}}g(Ls,"_assign_end_pages");function Ws(n,e,t,r,i=null){if(t.length!==r.length)throw new Error("body_pages and body_page_offsets length mismatch");if(i)return ld(n,e,r,i);let s=Fe(n.pkg),o=nd(n,s),a=[];for(let d=0;d<o.length;d++){let c=o[d];c.is_paragraph&&Dt(c.item)&&sd(c.item,s)&&a.push(d);}if(a.length===0)return [];let l=[];for(let d=0;d<a.length;d++){let c=a[d],u=o[c],f=u.item,h=dn(f),_=Xs(f,s),p=Cn(f),m=od(o,a,d,h),w=o.slice(c+1,m),y=td(o,c+1,m),b=ad(w),v=Pr(u.start_offset,r);l.push({level:h,text:_,page:v,style:p,has_table:y,footnote_ids:b,end_page:v});}return Ls(l,t.length),l}g(Ws,"extract_outline");function td(n,e,t){for(let r=e;r<t;r++){let i=n[r];if(i.is_paragraph&&Dt(i.item))return false;if(i.is_table)return true}return false}g(td,"_direct_has_table");function nd(n,e){let t=Array.from(Tl(n)),r=0,i=null;for(let l of t){if(l===n){i=l;break}let d=Hs(l,e);d&&(r>0&&(r+=2),r+=d.length);}i?r>0&&(r+=2):(i=n,r=0);let s=[],o=r,a=true;for(let l of He(i))if(l instanceof ie){let d=Ue(l),c=jt(l,e,false),u=(d+c).length;a||(o+=2),s.push({item:l,is_paragraph:true,is_table:false,start_offset:o,projected_length:u}),o+=u,a=false;}else if(l instanceof ze){let d=Nn(l,e,false,0),c=d?d.length:0;a||(o+=2);let u=o;s.push({item:l,is_paragraph:false,is_table:true,start_offset:u,projected_length:c}),Us(l,u,s,e),o+=c,a=false;}return s}g(nd,"_walk_doc_body");function zs(n,e,t,r){let i=e._element,s=t,o=0;for(let a of n.rows){if(o>0)if(o===1){let c=n.rows[0],u=new Set,f=0;for(let _ of c.cells)u.has(_)||(u.add(_),f+=1);let h=f>0?Array(f).fill("---").join(" | ").length:0;s+=1+h+1;}else s+=1;let l=new Set,d=0;for(let c of a.cells){if(l.has(c))continue;l.add(c),d>0&&(s+=3);let[u,f]=rd(c,i,s,r);if(f)return u;s=u,d++;}o++;}return t}g(zs,"_compute_inner_block_offset");function rd(n,e,t,r){let i=t,s=true;for(let o of He(n)){if(s||(i+=2),o instanceof ie){if(o._element===e)return [i,true];let a=Ue(o),l=jt(o,r,false);i+=(a+l).length;}else if(o instanceof ze){let a=zs(o,new ie(e,null),i,r);if(a!==i&&id(e,o._element))return [a,true];let l=Nn(o,r,false,0);i+=l?l.length:0;}s=false;}return [i,false]}g(rd,"_walk_cell_for_offset");function id(n,e){let t=n.parentNode;for(;t;){if(t===e)return true;t=t.parentNode;}return false}g(id,"_element_is_descendant");function Us(n,e,t,r){let i=new Set;for(let s of n.rows)for(let o of s.cells)if(!i.has(o)){i.add(o);for(let a of He(o))if(a instanceof ie){let l=Dt(a)?zs(n,a,e,r):e;t.push({item:a,is_paragraph:true,is_table:false,start_offset:l,projected_length:0});}else a instanceof ze&&(t.push({item:a,is_paragraph:false,is_table:true,start_offset:e,projected_length:0}),Us(a,e,t,r));}}g(Us,"_record_table_inner_blocks_lite");function Hs(n,e){let t=[],r=n.constructor.name;if(r==="NotesPart"){let s=n.note_type==="fn"?"## Footnotes":"## Endnotes";t.push(`---
|
|
112
|
+
${s}`);}let i=true;for(let s of He(n))if(s.constructor.name==="FootnoteItem"){let o=Hs(s,e);o&&t.push(o);}else if(s instanceof ie){let o=Ue(s);i&&r==="FootnoteItem"&&(o=`[^${n.note_type}-${n.id}]: ${o}`);let a=jt(s,e,false);t.push(o+a),i=false;}else if(s instanceof ze){let o=Nn(s,e,false,0);o&&t.push(o),i=false;}return t.join(`
|
|
113
|
+
|
|
114
|
+
`)}g(Hs,"_project_part");function kn(n){let e=n._element;for(;e;){if(e.tagName==="w:tc")return null;e=e.parentNode;}let t=n.text.trim();if(!t||t.length>=120||t.endsWith("."))return null;let r=R(n._element,"w:r"),i=false;for(let s of r){if(!R(s,"w:t").map(c=>c.textContent||"").join("").trim())continue;i=true;let l=$(s,"w:rPr"),d=false;if(l){let c=$(l,"w:b");if(c){let u=c.getAttribute("w:val");u!=="0"&&u!=="false"&&u!=="off"&&(d=true);}}if(!d)return null}return i?Qc.test(t)?1:Kc.test(t)?3:Zc.test(t)||ed.test(t)?2:null:null}g(kn,"_structural_bold_heading_level");function Dt(n){return Bs.test(Ue(n))?true:kn(n)!==null}g(Dt,"_is_heading");function sd(n,e){let t=Xs(n,e);if(!qs(t))return false;if(Cn(n)!=="(heuristic)")return true;let i=(t.match(/\w+/g)||[]).length,s=kn(n)!==null?2:Fs;return i>=s}g(sd,"_heading_passes_quality_filter");function qs(n){if(!n)return false;let e=n.replace(/\{#[^}]+\}/g,"");return /\w/.test(e)}g(qs,"_heading_text_has_words");function dn(n){let e=Bs.exec(Ue(n));if(e)return Math.min(e[1].length,6);let t=kn(n);return t!==null?t:1}g(dn,"_heading_level");var Ei=200;function Xs(n,e){let t=jt(n,e,false),r=Gs(t);return r=r.replace(/\n+/g," "),r=Js(r),Ys(r.trim())}g(Xs,"_heading_text");function Ys(n){if(n.length<=Ei)return n;let e=n.substring(0,Ei),t=/\{#[^}\n]*$/.exec(e);return t!==null&&(e=e.substring(0,t.index)),e.trimEnd()+"\u2026"}g(Ys,"_truncate_outline_text");function Gs(n){return n?(n=n.replace(/\{--[\s\S]*?--\}/g,""),n=n.replace(/\{>>[\s\S]*?<<\}/g,""),n=n.replace(/\{\+\+([\s\S]*?)\+\+\}/g,"$1"),n=n.replace(/\{==([\s\S]*?)==\}/g,"$1"),n):""}g(Gs,"_strip_critic_markup");function Js(n){if(!n)return "";let e=[];return n=n.replace(/\{#[^}]+\}|_{3,}/g,t=>(e.push(t),`\0${e.length-1}\0`)),n=n.replace(/\*\*(.+?)\*\*/g,"$1"),n=n.replace(/__(.+?)__/g,"$1"),n=n.replace(/(?<!\w)_(\S(?:.*?\S)?)_(?!\w)/g,"$1"),n=n.replace(/\x00(\d+)\x00/g,(t,r)=>e[Number(r)]),n}g(Js,"_strip_inline_formatting");function Cn(n){let[e,t]=_t(n._parent.part||n._parent),r=$(n._element,"w:pPr"),i=t;if(r){let d=$(r,"w:pStyle");d&&(i=d.getAttribute("w:val")||t);}let s=null,o=false;if(r){let d=$(r,"w:outlineLvl");d&&/^\d+$/.test(d.getAttribute("w:val")||"")&&(s=parseInt(d.getAttribute("w:val"),10));}s===null&&i&&e&&e[i]&&(s=e[i].outline_level,o=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")),o&&s!==null&&(l&&(l.startsWith("Heading")||l==="Title")||(s=null)),s!==null&&s>=0&&s<=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 od(n,e,t,r){for(let i=t+1;i<e.length;i++){let s=e[i];if(dn(n[s].item)<=r)return s}return n.length}g(od,"_find_owned_end");function ad(n){let e=new Set,t=[];for(let r of n)if(r.is_paragraph)for(let i of yn(r.item)){if(!("type"in i))continue;let s="";if(i.type==="footnote")s=`fn-${i.id}`;else if(i.type==="endnote")s=`en-${i.id}`;else continue;e.has(s)||(e.add(s),t.push(s));}return t}g(ad,"_collect_footnote_ids");function Vs(n){return n.replace(/\{--.*?--\}/g,"").replace(/\{\+\+(.*?)\+\+\}/g,"$1").replace(/\{==(.*?)==\}/g,"$1").replace(/\{>>.*?<<\}/g,"").replace(/\{(?:>>|--).*$/g,"").replace(/\{\+\+|\{==|--\}|\+\+\}|<<\}|==\}/g,"").replace(/\*\*|__|[*_]/g,"").replace(/\{#[^}]+\}/g,"").trim()}g(Vs,"clean_breadcrumb");function Pr(n,e){if(!e||e.length===0)return 1;let t=1;for(let r=0;r<e.length&&n>=e[r];r++)t=r+1;return t}g(Pr,"offset_to_page");function ld(n,e,t,r){let i=[],s=new Set;function o(d){for(let c of He(d))if(c.constructor.name==="FootnoteItem")o(c);else if(c instanceof ie)i.push(["p",c]);else if(c instanceof ze){i.push(["t",c]);for(let f of c.rows)for(let h of f.cells)s.has(h._element)||(s.add(h._element),o(h));}}g(o,"walk"),o(n);let a=[];for(let d=0;d<i.length;d++){let[c,u]=i[d];if(c!=="p")continue;let f=false;r instanceof Map?f=r.has(u._element):f=u._element in r,f&&Dt(u)&&cd(u,e,r)&&a.push(d);}if(a.length===0)return [];let l=[];for(let d=0;d<a.length;d++){let c=a[d],u=i[c][1],f=dn(u),h=Qs(u,e,r),_=Cn(u),p=c;for(let N=d+1;N<a.length;N++){let k=a[N],x=i[k][1];if(dn(x)<=f){p=k;break}}p===c&&(p=i.length);let m=i.slice(c+1,p),w=false;for(let[N,k]of m){if(N==="p"&&Dt(k))break;if(N==="t"){w=true;break}}let y=dd(m),b;r instanceof Map?b=r.get(u._element):b=r[u._element];let v=1;if(b!==void 0){let[N]=b;v=Pr(N,t);}l.push({level:f,text:h,page:v,style:_,has_table:w,footnote_ids:y,end_page:v});}return Ls(l,t.length),l}g(ld,"_extract_outline_fast");function cd(n,e,t){let r=Qs(n,e,t);if(!qs(r))return false;if(Cn(n)!=="(heuristic)")return true;let s=r.match(/\w+/g)||[],o=kn(n)!==null?2:Fs;return s.length>=o}g(cd,"_heading_passes_quality_filter_fast");function Qs(n,e,t){let r;if(t instanceof Map?r=t.get(n._element):r=t[n._element],r===void 0)return "";let[i,s]=r,o=e.substring(i,i+s),a=Gs(o);return a=a.replace(/\n+/g," "),a=Js(a),a=a.replace(/^#+\s+/,""),Ys(a.trim())}g(Qs,"_heading_text_fast");function dd(n){let e=new Set,t=[];for(let[r,i]of n)if(r==="p")for(let s of yn(i)){if(!("type"in s))continue;let o="";if(s.type==="footnote")o=`fn-${s.id}`;else if(s.type==="endnote")o=`en-${s.id}`;else continue;e.has(o)||(e.add(o),t.push(o));}return t}g(dd,"_collect_footnote_ids_fast");var ud=100,fd=80,hd=8,pd={readOnly:"read-only",forms:"fill-in-forms only",comments:"comments only",trackedChanges:"tracked-changes only"},_d={"repeating-item":"item"},Ks=new Set(["group","repeating","repeating-item"]);function Zs(n){if(n.edit===null)return "none";let e=pd[n.edit]??n.edit;return n.enforced?`${e} (enforced)`:e}g(Zs,"protectionLabel");var Ai=/\{#(\/?)cc:(\d+)(?: [^}]*)?\}/g;function md(n){let e=new Map,t=new Map;Ai.lastIndex=0;let r;for(;(r=Ai.exec(n))!==null;){let s=Number(r[2]);r[1]?t.has(s)||t.set(s,r.index):e.has(s)||e.set(s,[r.index,r.index+r[0].length]);}let i=new Map;for(let[s,[o,a]]of e){let l=t.get(s);l!==void 0&&l>=a&&i.set(s,[o,a,l]);}return i}g(md,"scanAnchors");var gd=class{static{g(this,"HeadingIndex");}starts=[];paths=[];constructor(n){let e=[],t=0;for(let r of n.split(`
|
|
115
|
+
`)){let i=r.match(/^(#{1,6})\s+(.*)/);if(i){let s=i[1].length,o=Vs(i[2]);for(o.length>80&&(o=o.slice(0,80)+"...");e.length>0&&e[e.length-1].level>=s;)e.pop();let a=(e.length>0?e[e.length-1].path:[]).concat([o]);e.push({level:s,path:a}),this.starts.push(t),this.paths.push(a.join(" > "));}t+=r.length+1;}}pathAt(n){if(this.starts.length===0)return "";let e=0,t=this.starts.length-1,r=-1;for(;e<=t;){let i=e+t>>1;this.starts[i]<=n?(r=i,e=i+1):t=i-1;}return r>=0?this.paths[r]:""}};function Pi(n,e=fd){let t=Vs(n).replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e)+"\u2026":t}g(Pi,"preview");function Tr(n){if(!n)return [];let e=[];for(let t=n.firstChild;t;t=t.nextSibling)t.nodeType===1&&e.push(t);return e}g(Tr,"childElements");function En(n){return n?.tagName??n?.nodeName??""}g(En,"tagOf");function Ti(n){let e=$(n,nt);return e?Tr(e).filter(t=>{let r=En(t);return r==="w:p"||r==="w:tbl"}):[]}g(Ti,"blockChildren");function wd(n){let e=$(n,nt);return e?Tr(e).filter(t=>En(t)===pt):[]}g(wd,"directChildSdts");function yd(n){let e=$(n,nt);return e?R(e,pt).length:0}g(yd,"nestedSdtCount");function Gt(n,e){return n===1?`${n} ${e}`:`${n} ${e}s`}g(Gt,"plural");function vd(n){return n.cls==="group"?`wraps ${Gt(Ti(n.element).length,"block")}, ${Gt(yd(n.element),"nested field")}`:n.cls==="repeating"?Gt(wd(n.element).length,"item"):n.cls==="repeating-item"?`wraps ${Gt(Ti(n.element).length,"block")}`:null}g(vd,"extentFor");function bd(n){let e=$(n.element,nt);if(!e)return null;let t=Tr(e)[0];if(!t)return null;let r=En(t);return r==="w:tr"?"table row":r==="w:tc"?"table cell":null}g(bd,"containerKind");function xd(n,e){let t=[];return e&&t.push("EMPTY"),n.contentLocked?t.push("LOCKED (contents)"):n.cls==="group"?t.push("LOCKED (group)"):n.deleteLocked&&t.push("LOCKED (no-delete)"),n.bound&&t.push(`BOUND \u2192 ${n.bindingXpath??""}`.trimEnd()),n.temporary&&t.push("TEMPORARY"),t}g(xd,"statesFor");function Nd(n){let e=$(n,nt);return e?R(e,"w:t").some(t=>(t.textContent??"").trim().length>0):false}g(Nd,"hasText");function kd(n){let e=pn(Array.from(Ze(n)).map(([o])=>_n(o))),t=0,r=0,i=0,s=0;for(let o of e.values())t+=1,Ks.has(o.cls)||o.cls==="checkbox"||(o.showingPlaceholder||!Nd(o.element))&&(r+=1),(o.cls==="group"||o.contentLocked)&&(i+=1),o.bound&&(s+=1);return [t,r,i,s]}g(kd,"fieldSummary");function $r(n,e,t){let r=pn(Array.from(Ze(n)).map(([c])=>_n(c))),i=Array.from(r.values()).sort((c,u)=>c.ordinal-u.ordinal),s=g(c=>{let u=c.element?.parentNode??null;for(;u;){if(En(u)===pt){let f=r.get(u);if(f)return f.ordinal}u=u.parentNode??null;}return null},"parentOrdinal"),o=md(e),a=new gd(e),l=[],d=0;for(let c of i){let u=o.get(c.ordinal);u&&(d=u[0]);let f=d,h=t?Pr(f,t):1,_=a.pathAt(f),p=null,m=null,w=null,y=c.showingPlaceholder;if(c.cls==="checkbox")m=c.checked?"checked":"unchecked";else if(!Ks.has(c.cls)){if(u){let b=Pi(e.slice(u[1],u[2]));b?p=b:y=true;}}y&&c.placeholderText&&(w=Pi(c.placeholderText)),l.push({ordinal:c.ordinal,cls_word:_d[c.cls]??c.cls,alias:c.alias,tag:c.tag,page:h,heading_path:_,container_kind:bd(c),parent_ordinal:s(c),states:xd(c,y),value:p,checkbox_state:m,placeholder:w,options:c.options.map(([b])=>b),date_format:c.dateFormat,extent:vd(c),empty:y,locked:c.cls==="group"||c.contentLocked,bound:c.bound});}return l}g($r,"collectFields");function Cd(n){return [n.length,n.filter(e=>e.empty).length,n.filter(e=>e.locked).length,n.filter(e=>e.bound).length]}g(Cd,"summaryCounts");function eo(n){let[e,t,r,i]=n;return e===0?"no content controls":`${e} content controls \u2014 ${t} empty \xB7 ${r} locked \xB7 ${i} bound`}g(eo,"summaryText");function Ed(n){return eo(Cd(n))}g(Ed,"fieldsSummary");function to(n,e,t,r=0,i=ud){let s=[`# Fields: ${n}`,`Protection: ${Zs(t)} \xB7 ${Ed(e)}`];if(e.length===0)return [...s,"","No content controls."].join(`
|
|
116
|
+
`);let o=e.length,a=Math.max(0,Math.min(r,o)),l=e.slice(a,a+i),d=Math.max(...e.map(f=>`CC:${f.ordinal}`.length)),c=l.map(f=>Ad(f,d)),u=o-(a+l.length);if(u>0){let f=a+l.length;c.push(`\u2026 ${u} more \u2014 pass fields_offset=${f} to continue.`);}return [...s,"",...c].join(`
|
|
117
|
+
`)}g(to,"renderLedger");function Ad(n,e){let t=`CC:${n.ordinal}`.padEnd(e)+" "+n.cls_word,r=[];n.alias&&r.push(`"${n.alias}"`),n.tag&&r.push(`(tag: ${n.tag})`),r.length>0&&(t+=" "+r.join(" "));let i=[`p${n.page}`+(n.heading_path?` \xB7 ${n.heading_path}`:"")];if(n.container_kind&&i.push(n.container_kind),n.parent_ordinal!==null&&i.push(`in CC:${n.parent_ordinal}`),i.push(...n.states),n.checkbox_state?i.push(n.checkbox_state):n.value!==null&&i.push(`value: "${n.value}"`),n.placeholder&&i.push(`placeholder: "${n.placeholder}"`),n.options.length>0){let s=n.options.slice(0,hd),o=s.join(" | "),a=n.options.length-s.length;a>0&&(o+=` | \u2026 (+${a} more)`),i.push(`options: ${o}`);}return n.date_format&&i.push(`format: ${n.date_format}`),n.extent&&i.push(n.extent),t+i.map(s=>` \u2014 ${s}`).join("")}g(Ad,"renderLine");function Pd(n,e,t=""){if(n[0]===0&&e.edit===null)return [];let r=["## Content Controls","",`Protection: ${Zs(e)} \xB7 ${eo(n)}`];return t&&r.push(t),r}g(Pd,"renderAppendixSection");var Jt=class extends Error{static{g(this,"FieldResolutionError");}constructor(n){super(n),this.name="FieldResolutionError";}},Td=30;function $i(n){if(!n.length)return "This document has no content controls.";let e=[];for(let i of n)for(let s of [i.tag,i.alias])s&&!e.includes(s)&&e.push(s);let t=e.slice(0,Td),r=e.length>t.length?` (+${e.length-t.length} more)`:"";if(!t.length){let i=Math.max(...n.map(s=>s.ordinal));return `This document's ${n.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: "+t.join(", ")+r+". Run read_docx with mode='fields' for the full list with ids."}g($i,"availableSummary");function $d(n,e,t="strict"){if(!e||!e.trim())throw new Jt("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 o=Number(r[1]),a=n.filter(l=>l.ordinal===o);if(a.length)return a;throw new Jt(`No content control with id 'CC:${o}'. ${$i(n)}`)}let i=n.filter(o=>o.tag===e);if(i.length||(i=n.filter(o=>o.alias===e)),!i.length)throw new Jt(`No content control matches field '${e}'. ${$i(n)}`);if(i.length===1||t==="all")return [...i];if(t==="first")return [i[0]];let s=i.map(o=>`CC:${o.ordinal}`).join(", ");throw new Jt(`Field '${e}' matches ${i.length} controls (${s}). 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($d,"resolveField");function Sr(n){let e=[],t=n?.childNodes;if(!t)return e;for(let r=0;r<t.length;r++)t[r].nodeType===1&&e.push(t[r]);return e}g(Sr,"childrenOf");function Ee(n,e){for(let t of Sr(n))if(t.tagName===e)return t;return null}g(Ee,"findChild3");function no(n,e){return n?.getElementsByTagName?Array.from(n.getElementsByTagName(e)):[]}g(no,"descendants");function ht(n){return Ee(n,"w:sdtContent")}g(ht,"sdtContent");function mt(n){return Ee(n,"w:sdtPr")}g(mt,"sdtPr");function Sd(n){let e=ht(n);return e?no(e,"w:r"):[]}g(Sd,"contentRuns");function Si(n){let e=mt(n.element);if(!e)return false;let t=Ee(e,"w:showingPlcHdr");if(!t)return false;e.removeChild(t);let r=ht(n.element);if(r)for(let i of no(r,"w:r"))i.parentNode?.removeChild(i);return true}g(Si,"clearPlaceholder");function Id(n){let e=ht(n),t=n.parentNode;if(!e||!t)return false;for(let r of Sr(e))t.insertBefore(r,n);return t.removeChild(n),true}g(Id,"unwrapSdt");var Od=new Set(["text","richtext","dropdown","combobox","date","checkbox"]),Dd={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 Rd(n){let e=mt(n.element);if(!e)return false;let t=Ee(e,"w:text");if(!t)return false;let r=t.getAttribute("w:multiLine");return r!==null&&r!==""&&!["0","false","off"].includes(String(r).toLowerCase())}g(Rd,"isMultiline");function Ii(n,e){if(Od.has(n))return null;let t=Dd[n]??"set_field fills value-bearing fields only.";return `CC:${e} is a ${n} and is not a value-bearing field. ${t} set_field fills text, rich-text, dropdown, combobox, date and checkbox controls.`}g(Ii,"refuseClass");function Oi(n,e,t){if(n.cls==="dropdown"){let[,r]=ro(n,t);return r?`CC:${e}: ${r}`:null}return n.cls==="date"?or(t)===null?`CC:${e} is a date control; '${t}' is not a date. Use the canonical YYYY-MM-DD form (e.g. 2026-03-01).`:null:n.cls!=="text"?null:t.includes(`
|
|
109
118
|
|
|
110
119
|
`)?`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.`:t.includes(`
|
|
111
|
-
`)&&!
|
|
112
|
-
`))return [n,e];let t=n.match(/^(#+)\s+/),r=e.match(/^(#+)\s+/);if(t&&r&&t[1]===r[1]){let i=t[1],s=n.substring(i.length).trimStart(),o=e.substring(i.length).trimStart();return [s,o]}return [n,e]}g(
|
|
113
|
-
`)[0]:"",s=e.exec(i);if(s){let o=parseInt(s[1],10)-1,a=r.split("Failed: "),
|
|
120
|
+
`)&&!Rd(n)?`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(Oi,"refuseValue");var Md=new Set(["true","x","[x]","checked","1","yes","on"]),jd=new Set(["false","[ ]","[]","unchecked","0","no","off",""]);function Di(n){let e=n.trim().toLowerCase();return Md.has(e)?true:jd.has(e)?false:null}g(Di,"parseCheckboxValue");function Bd(n,e){let t=e?["\u2612",null]:["\u2610",null],r=mt(n.element);if(!r)return t;let i=Ee(r,"w14:checkbox");if(!i)return t;let s=Ee(i,e?"w14:checkedState":"w14:uncheckedState");if(!s)return t;let o=s.getAttribute("w14:val"),a=s.getAttribute("w14:font");return [o?String.fromCodePoint(parseInt(o,16)):t[0],a||null]}g(Bd,"checkboxGlyph");function Fd(n,e){let t=mt(n.element);if(!t)return;let r=Ee(t,"w14:checkbox");if(!r)return;let i=Ee(r,"w14:checked");i||(i=r.ownerDocument.createElement("w14:checked"),r.appendChild(i)),i.setAttribute("w14:val",e?"1":"0");}g(Fd,"setCheckboxChecked");function Ld(n){let e=Sd(n.element);return e.length?e[0]:null}g(Ld,"glyphRun");function ro(n,e){let t=n.options??[];if(!t.length)return [e,null];for(let[i]of t)if(i===e)return [i,null];for(let[i,s]of t)if(s&&s===e)return [i,null];if(n.cls==="combobox")return [e,null];let r=t.map(([i])=>i).join(" | ");return [null,`'${e}' is not one of this dropdown's options. Choose one of: ${r}.`]}g(ro,"resolveOption");function Wd(n,e){return (n.options??[]).some(([t,r])=>t===e||!!r&&r===e)}g(Wd,"optionIsListed");function zd(n,e){let t=mt(n.element);if(t)for(let r of ["w:dropDownList","w:comboBox"]){let i=Ee(t,r);if(i){i.setAttribute("w:lastValue",e);return}}}g(zd,"setDropdownLastValue");var Ud=new Set(["yyyy","MM","M","dd","d"]);function or(n){let e=/^(\d{4})-(\d{2})-(\d{2})$/.exec(n.trim());if(!e)return null;let t=Number(e[1]),r=Number(e[2]),i=Number(e[3]),s=new Date(Date.UTC(t,r-1,i));return s.getUTCFullYear()!==t||s.getUTCMonth()!==r-1||s.getUTCDate()!==i?null:[t,r,i]}g(or,"parseIsoDate");var Se=g((n,e)=>String(n).padStart(e,"0"),"pad");function Hd(n,e){let[t,r,i]=n,s=`${Se(t,4)}-${Se(r,2)}-${Se(i,2)}`;if(!e)return [s,false];let o=e.match(/[A-Za-z]+/g)??[];if(!o.length||o.some(l=>!Ud.has(l)))return [s,true];let a={yyyy:Se(t,4),MM:Se(r,2),M:String(r),dd:Se(i,2),d:String(i)};return [e.replace(/[A-Za-z]+/g,l=>a[l]),false]}g(Hd,"renderDate");function qd(n,e){let t=mt(n.element);if(!t)return;let r=Ee(t,"w:date");if(!r)return;let[i,s,o]=e;r.setAttribute("w:fullDate",`${Se(i,4)}-${Se(s,2)}-${Se(o,2)}T00:00:00Z`);}g(qd,"setFullDate");var Xd=["ds:itemID","itemID"];function Ri(n){return (n.split("/").pop()??"").replace(/\D/g,"")}g(Ri,"digitsOf");var Yd={"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 Gd(n,e){if(!e)return null;let t=e.replace(/[{}]/g,"").toLowerCase(),r=n?.part?.package?.parts??[],i=Yd[t];if(i)return r.find(l=>String(l.partname).replace(/^\//,"")===i)??null;let s=r.filter(a=>String(a.partname).includes("/customXml/itemProps")),o=r.filter(a=>String(a.partname).includes("/customXml/item")&&!String(a.partname).includes("itemProps"));for(let a of s){let l=a._element;if(!l)continue;let d=null;for(let f of Xd){let h=l.getAttribute?.(f);if(h){d=h;break}}if(!d||d.replace(/[{}]/g,"").toLowerCase()!==t)continue;let c=Ri(String(a.partname)),u=o.find(f=>Ri(String(f.partname))===c);if(u)return u}return null}g(Gd,"findBoundStore");function Jd(n){let e=n?.tagName??n?.nodeName??"",t=e.indexOf(":"),r=t===-1?"xmlns":`xmlns:${e.slice(0,t)}`;for(let i=n;i&&i.nodeType===1;i=i.parentNode){let s=i.getAttribute?.(r);if(s)return s}return null}g(Jd,"namespaceUriOf");function Vd(n){let e={};if(!n)return e;let t=/xmlns:([\w.-]+)\s*=\s*['"]([^'"]*)['"]/g,r;for(;(r=t.exec(n))!==null;)e[r[1]]=r[2];return e}g(Vd,"parsePrefixMappings");function Qd(n,e,t){let r=e.split("/").filter(a=>a.length>0);if(!r.length)return null;let i=Vd(t),s=g(a=>a?.split(":").pop(),"localOf"),o=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 d=l[1],c=l[2]?Number(l[2]):1,u=d.lastIndexOf(":"),f=u===-1?d:d.slice(u+1),h=u===-1?void 0:i[d.slice(0,u)];if(a===0){let p=n.tagName??n.nodeName;if(s(p)!==f||c!==1)return null;o=n;continue}let _=Sr(o).filter(p=>s(p.tagName??p.nodeName)===f);if(h){let p=_.filter(m=>Jd(m)===h);p.length&&(_=p);}if(_.length<c)return null;o=_[c-1];}return o}g(Qd,"resolveBindingPath");function Kd(n,e,t,r){if(!e||!n?._element)return false;let i=Qd(n._element,e,r);if(!i)return false;for(let s of Array.from(i.childNodes??[]))i.removeChild(s);return i.appendChild(i.ownerDocument.createTextNode(t)),true}g(Kd,"writeBoundValue");var Mi=280,$e=30;function le(n){let e=n.nextSibling;for(;e;){if(e.nodeType===1)return e;e=e.nextSibling;}return null}g(le,"getNextElement");function Ce(n){let e=n.previousSibling;for(;e;){if(e.nodeType===1)return e;e=e.previousSibling;}return null}g(Ce,"getPreviousElement");function ut(n,e){e.parentNode&&e.parentNode.insertBefore(n,e.nextSibling);}g(ut,"insertAfter");function Zd(n){let e=[...n.pkg.parts],t={...n.pkg.unzipped},r=new Map,i=new Map,s=new Set;for(let o of e){if(r.set(o,new Map(o.rels)),!o._element)continue;let a=o._element.ownerDocument;a&&hr(a)&&typeof o.blob=="string"?s.add(o):i.set(o,o._element.cloneNode(true));}return {parts:e,unzipped:t,rels:r,elements:i,blobRestores:s}}g(Zd,"takeSnapshot");function eu(n,e){n.pkg.parts=[...e.parts];for(let t of Object.keys(n.pkg.unzipped))delete n.pkg.unzipped[t];for(let[t,r]of Object.entries(e.unzipped))n.pkg.unzipped[t]=r;for(let t of e.parts){if(t.rels=new Map(e.rels.get(t)),e.blobRestores&&e.blobRestores.has(t)){let i=Ke(t.blob);$t(i),t._element=i.documentElement;continue}let r=e.elements.get(t);if(r&&t._element){let i=t._element.ownerDocument;i&&i.documentElement&&i.replaceChild(r,i.documentElement),t._element=r;}}}g(eu,"restoreSnapshot");function tu(n,e){if(!n||!e)return [n,e];if(e.includes(`
|
|
121
|
+
`))return [n,e];let t=n.match(/^(#+)\s+/),r=e.match(/^(#+)\s+/);if(t&&r&&t[1]===r[1]){let i=t[1],s=n.substring(i.length).trimStart(),o=e.substring(i.length).trimStart();return [s,o]}return [n,e]}g(tu,"stripMatchingHeadingHashes");function ar(n){let e=/^-\s*(?:Action|Edit|Note: Action)\s+(\d+)\b/i,t=[];for(let r of n){let i=r?r.split(`
|
|
122
|
+
`)[0]:"",s=e.exec(i);if(s){let o=parseInt(s[1],10)-1,a=r.split("Failed: "),l=a.length>1?a.slice(1).join("Failed: ").trim():r.trim();t.push([o,l]);}else t.push([0,r.trim()]);}return t}g(ar,"extract_failed_indices");var Vt=class extends Error{static{g(this,"BatchValidationError");}errors;failed;constructor(n,e){super(`Batch validation failed:
|
|
114
123
|
`+n.join(`
|
|
115
|
-
`)),this.name="BatchValidationError",this.errors=n,this.failed=e??
|
|
116
|
-
Note: ${n} 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(
|
|
124
|
+
`)),this.name="BatchValidationError",this.errors=n,this.failed=e??ar(n);}};function ji(n){return `
|
|
125
|
+
Note: ${n} 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(ji,"sequential_context_hint");var nu=/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,Bi=/\[~[^~\]]+~\]\(#[^)]+\)|!\[[^\]]*\]\(docx-image:[^)]*\)|\[(?!~)[^\]]+\]\([^)]+\)/g,ru=/^#{1,6} /m,iu=/^[ \t]*\|.*\|[ \t]*$/m;function Fi(n,e){for(;n.endsWith(`
|
|
117
126
|
|
|
118
127
|
`)&&e.endsWith(`
|
|
119
128
|
|
|
120
|
-
`);)n=n.slice(0,-2),e=e.slice(0,-2);return [n,e]}g(Ci,"trimSharedTrailingParagraphMark");var Pi=/\{#\/?cc:\d+[^}]*\}/g,ju=/^\{#cc:(\d+)[^}]*\}(?:\{>>placeholder:[^<]*<<\})?\{#\/cc:\1\}$/,Bu={"w:sectPr":new Set(["w:headerReference","w:footerReference"])},Zn=["w:ins","w:del"],er=["w:pPrChange","w:rPrChange","w:sectPrChange"],Jt=[...Zn,...er];function Ln(n){return n.startsWith("/")?n.substring(1):n}g(Ln,"normalize_part_name");var Fu=["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 Wu(n){if(!n)return null;let e=n.match(Mu);return e?Array.from(new Set(e.map(r=>`0x${r.charCodeAt(0).toString(16).padStart(2,"0")}`))).sort().join(", "):null}g(Wu,"describe_illegal_control_chars");function Lu(n,e=0){let t=[];for(let r=0;r<n.length;r++){let i=n[r],s=i.target_text||"",o=i.new_text??i.value??"",a=[["target_text",s],["new_text",o]],c=bl(i.comment);c?t.push(`- Edit ${r+1+e} Failed: ${c}`):Array.isArray(i.comment)?i.comment.forEach((u,l)=>{a.push([`comment[${l}].text`,u.text||""]),u.author&&a.push([`comment[${l}].author`,u.author]);}):i.comment&&a.push(["comment",i.comment]),(i.cells||[]).forEach((u,l)=>{a.push([`cells[${l}]`,u||""]);});for(let[u,l]of a){let d=Wu(l);d&&t.push(`- Edit ${r+1+e} Failed: \`${u}\` contains control character(s) (${d}) that cannot be stored in a DOCX. Remove them and re-submit.`);}if((o.includes("{++")||o.includes("{--")||o.includes("{>>")||o.includes("{=="))&&t.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.`),s.includes("[^")||o.includes("[^")){let u=(s.match(/\[\^(?:fn|en)-[^\]]+\]/g)||[]).sort(),l=(o.match(/\[\^(?:fn|en)-[^\]]+\]/g)||[]).sort();JSON.stringify(u)!==JSON.stringify(l)&&(l.length>u.length||l.some(d=>l.filter(f=>f===d).length>u.filter(f=>f===d).length)?t.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.`):t.push(`- Edit ${r+1+e} Failed: Cannot delete footnote/endnote references via text replace. The marker corresponds to a structural XML element.`));}if(s.includes("](")||o.includes("](")){let u=(s.match(/\[(?!~)[^\]]+\]\([^)]+\)/g)||[]).sort(),l=(o.match(/\[(?!~)[^\]]+\]\([^)]+\)/g)||[]).sort();u.length!==l.length?l.length>u.length?t.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).`):t.push(`- Edit ${r+1+e} Failed: Cannot delete hyperlinks via text replace. The marker corresponds to a structural XML element.`):u.length>1&&JSON.stringify(u)!==JSON.stringify(l)&&t.push(`- Edit ${r+1+e} Failed: Can only edit or retarget one hyperlink per text replacement. Please split into multiple edits.`);}if(s.includes("[~")||o.includes("[~")){let u=s.match(/\[~[^~]+~\]\(#[^\)]+\)/g)||[],l=o.match(/\[~[^~]+~\]\(#[^\)]+\)/g)||[];u.length!==l.length?l.length>u.length?t.push(`- Edit ${r+1+e} Failed: Cannot insert cross-references via text replace. Markers are read-only projections.`):t.push(`- Edit ${r+1+e} Failed: Cannot delete cross-references via text replace. The marker corresponds to a structural XML element.`):JSON.stringify(u)!==JSON.stringify(l)&&t.push(`- Edit ${r+1+e} Failed: Modifying or retargeting cross-reference markers is disallowed to prevent dependency corruption.`);}if(s.includes("docx-image:")||o.includes("docx-image:")){let u=(s.match(/!\[[^\]]*\]\(docx-image:[^)]*\)/g)||[]).sort(),l=(o.match(/!\[[^\]]*\]\(docx-image:[^)]*\)/g)||[]).sort();JSON.stringify(u)!==JSON.stringify(l)&&t.push(`- Edit ${r+1+e} Failed: image markers () 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(s.includes("{#")||o.includes("{#")){let u=s.match(/\{#[^\}]+\}/g)||[],l=o.match(/\{#[^\}]+\}/g)||[];for(let d of l)if(l.filter(f=>f===d).length>u.filter(f=>f===d).length){t.push(`- Edit ${r+1+e} Failed: Cannot modify or insert internal anchor markers (\`{#...}\`). These represent structural XML bookmarks.`);break}}if(s.includes("{#")&&s.includes("cc:")||o.includes("cc:")){let u=s.match(Pi)||[],l=o.match(Pi)||[];!ju.test(s.trim())&&(u.length!==l.length||u.some((f,h)=>f!==l[h]))&&t.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"&&o){let u=o.split(/[\r\n]+/);for(let l of u){let d=l.trimStart();if(d.startsWith("#######")){let f=d.length-d.replace(/^#+/,"").length;if(d.substring(f).startsWith(" ")||d.substring(f)===""){t.push(`- Edit ${r+1+e} Failed: Heading level ${f} is not supported (maximum is 6).`);break}}}}(s.includes("READONLY_BOUNDARY_START")||o.includes("READONLY_BOUNDARY_START")||s.includes("# Document Structure (Read-Only)")||o.includes("# Document Structure (Read-Only)")||s.includes("Document Structure (Read-Only)")||o.includes("Document Structure (Read-Only)"))&&t.push(`- Edit ${r+1+e} Failed: Modification targets the read-only boundary (Structural Appendix). This section cannot be edited.`);}return t}g(Lu,"validate_edit_strings");var yn=class V{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=Ve;protection=Nt;_overridden_controls=[];removed_comment_notes=[];rollback_verified=true;id_discovery_hint;_revisionIndex=null;constructor(e,t="Adeu AI (TS)",r){this.doc=e,this.author=t,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=Ps(e),r?.timestamp instanceof Date?this.timestamp=r.timestamp.toISOString().replace(/\.\d{3}Z$/,"Z"):typeof r?.timestamp=="string"?this.timestamp=r.timestamp:this.timestamp=new Date().toISOString().replace(/\.\d{3}Z$/,"Z");let i="http://schemas.microsoft.com/office/word/2023/wordml/word16du";for(let s of this.doc.pkg.parts)if(s===this.doc.part&&!s._element.hasAttribute("xmlns:w16du")){let o=s._element.ownerDocument,a=or(o);s._element.setAttribute("xmlns:w16du",i),a&&Pt(o);}this.current_id=this._scan_existing_ids(),this.mapper=new Ce(this.doc),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.comments_manager=new $t(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,t,r,i,s,o){let a,c,u,l;if(e===t)a=e,c=t,u=r,l="COMMENT_ONLY";else {let[f,h]=lt(e,t);a=e.slice(f,e.length-h),c=t.slice(f,t.length-h),u=r+f,[a,c]=Ci(a,c),!a&&c?l="INSERTION":a&&!c?l="DELETION":l="MODIFICATION";}let d={type:"modify",target_text:a,new_text:c,comment:i};return d._resolved_start_idx=u,d._match_start_index=u,d._active_mapper_ref=o,d._internal_op=l,s&&(d._is_table_edit=true),[d]}_word_diff_sub_edits(e,t,r,i=null,s=false,o=null){if(i!=null)return this._single_commented_sub_edit(e,t,r,i,s,o);let a=[];try{a=tn(e,t);}catch{a=[];}let c=g(d=>{let f=d.trim();return f.length>0&&/^[*_]+$/.test(f)},"_marker_only");if(a=a.filter(d=>!((!d.target_text||c(d.target_text))&&(!d.new_text||c(d.new_text))&&(d.target_text||d.new_text))),!a||a.length===0){let d={type:"modify",target_text:e,new_text:t,comment:i};return d._resolved_start_idx=r,d._match_start_index=r,d._active_mapper_ref=o,s&&(d._is_table_edit=true),e===t?d._internal_op="COMMENT_ONLY":!e&&t?d._internal_op="INSERTION":e&&!t?d._internal_op="DELETION":e&&t?d._internal_op="MODIFICATION":d._internal_op="COMMENT_ONLY",[d]}let u=[],l=false;for(let d of a){let f=r+(d._match_start_index||0),h=i!==null&&!l;h&&(l=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=o,s&&(_._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,t){if(!e)return "";let r=e;if(t&&(r=r.replace(/^\^/,"").replace(/\$$/,""),r=r.replace(/^\\s\*/,"").replace(/\\s\*$/,""),r=r.replace(/\\([.^$*+?()[\]{}|\\/])/g,"$1")),r=r.trim(),(!r||r===e)&&!t)return "";let i=this.mapper.full_text.indexOf(r);if(i!==-1){let s=Math.max(0,i-15),o=Math.min(this.mapper.full_text.length,i+r.length+15),a=this.mapper.full_text.substring(s,o).replace(/\n/g," ");return `
|
|
121
|
-
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,t){e=e.replace(/\{>>[\s\S]*?<<\}/g,"");for(let[r,i]of
|
|
129
|
+
`);)n=n.slice(0,-2),e=e.slice(0,-2);return [n,e]}g(Fi,"trimSharedTrailingParagraphMark");var Li=/\{#\/?cc:\d+[^}]*\}/g,su=/^\{#cc:(\d+)[^}]*\}(?:\{>>placeholder:[^<]*<<\})?\{#\/cc:\1\}$/,ou={"w:sectPr":new Set(["w:headerReference","w:footerReference"])},rn=["w:ins","w:del"],sn=["w:pPrChange","w:rPrChange","w:sectPrChange"],Qt=[...rn,...sn];function Vn(n){return n.startsWith("/")?n.substring(1):n}g(Vn,"normalize_part_name");var au=["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 lu(n){if(!n)return null;let e=n.match(nu);return e?Array.from(new Set(e.map(r=>`0x${r.charCodeAt(0).toString(16).padStart(2,"0")}`))).sort().join(", "):null}g(lu,"describe_illegal_control_chars");function cu(n,e=0){let t=[];for(let r=0;r<n.length;r++){let i=n[r],s=i.target_text||"",o=i.new_text??i.value??"",a=[["target_text",s],["new_text",o]],l=Rl(i.comment);l?t.push(`- Edit ${r+1+e} Failed: ${l}`):Array.isArray(i.comment)?i.comment.forEach((d,c)=>{a.push([`comment[${c}].text`,d.text||""]),d.author&&a.push([`comment[${c}].author`,d.author]);}):i.comment&&a.push(["comment",i.comment]),(i.cells||[]).forEach((d,c)=>{a.push([`cells[${c}]`,d||""]);});for(let[d,c]of a){let u=lu(c);u&&t.push(`- Edit ${r+1+e} Failed: \`${d}\` contains control character(s) (${u}) that cannot be stored in a DOCX. Remove them and re-submit.`);}if((o.includes("{++")||o.includes("{--")||o.includes("{>>")||o.includes("{=="))&&t.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.`),s.includes("[^")||o.includes("[^")){let d=(s.match(/\[\^(?:fn|en)-[^\]]+\]/g)||[]).sort(),c=(o.match(/\[\^(?:fn|en)-[^\]]+\]/g)||[]).sort();JSON.stringify(d)!==JSON.stringify(c)&&(c.length>d.length||c.some(u=>c.filter(f=>f===u).length>d.filter(f=>f===u).length)?t.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.`):t.push(`- Edit ${r+1+e} Failed: Cannot delete footnote/endnote references via text replace. The marker corresponds to a structural XML element.`));}if(s.includes("](")||o.includes("](")){let d=(s.match(/\[(?!~)[^\]]+\]\([^)]+\)/g)||[]).sort(),c=(o.match(/\[(?!~)[^\]]+\]\([^)]+\)/g)||[]).sort();d.length!==c.length?c.length>d.length?t.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).`):t.push(`- Edit ${r+1+e} Failed: Cannot delete hyperlinks via text replace. The marker corresponds to a structural XML element.`):d.length>1&&JSON.stringify(d)!==JSON.stringify(c)&&t.push(`- Edit ${r+1+e} Failed: Can only edit or retarget one hyperlink per text replacement. Please split into multiple edits.`);}if(s.includes("[~")||o.includes("[~")){let d=s.match(/\[~[^~]+~\]\(#[^\)]+\)/g)||[],c=o.match(/\[~[^~]+~\]\(#[^\)]+\)/g)||[];d.length!==c.length?c.length>d.length?t.push(`- Edit ${r+1+e} Failed: Cannot insert cross-references via text replace. Markers are read-only projections.`):t.push(`- Edit ${r+1+e} Failed: Cannot delete cross-references via text replace. The marker corresponds to a structural XML element.`):JSON.stringify(d)!==JSON.stringify(c)&&t.push(`- Edit ${r+1+e} Failed: Modifying or retargeting cross-reference markers is disallowed to prevent dependency corruption.`);}if(s.includes("docx-image:")||o.includes("docx-image:")){let d=(s.match(/!\[[^\]]*\]\(docx-image:[^)]*\)/g)||[]).sort(),c=(o.match(/!\[[^\]]*\]\(docx-image:[^)]*\)/g)||[]).sort();JSON.stringify(d)!==JSON.stringify(c)&&t.push(`- Edit ${r+1+e} Failed: image markers () 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(s.includes("{#")||o.includes("{#")){let d=s.match(/\{#[^\}]+\}/g)||[],c=o.match(/\{#[^\}]+\}/g)||[];for(let u of c)if(c.filter(f=>f===u).length>d.filter(f=>f===u).length){t.push(`- Edit ${r+1+e} Failed: Cannot modify or insert internal anchor markers (\`{#...}\`). These represent structural XML bookmarks.`);break}}if(s.includes("{#")&&s.includes("cc:")||o.includes("cc:")){let d=s.match(Li)||[],c=o.match(Li)||[];!su.test(s.trim())&&(d.length!==c.length||d.some((f,h)=>f!==c[h]))&&t.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"&&o){let d=o.split(/[\r\n]+/);for(let c of d){let u=c.trimStart();if(u.startsWith("#######")){let f=u.length-u.replace(/^#+/,"").length;if(u.substring(f).startsWith(" ")||u.substring(f)===""){t.push(`- Edit ${r+1+e} Failed: Heading level ${f} is not supported (maximum is 6).`);break}}}}(s.includes("READONLY_BOUNDARY_START")||o.includes("READONLY_BOUNDARY_START")||s.includes("# Document Structure (Read-Only)")||o.includes("# Document Structure (Read-Only)")||s.includes("Document Structure (Read-Only)")||o.includes("Document Structure (Read-Only)"))&&t.push(`- Edit ${r+1+e} Failed: Modification targets the read-only boundary (Structural Appendix). This section cannot be edited.`);}return t}g(cu,"validate_edit_strings");var Bt=class G{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=rt;protection=kt;_overridden_controls=[];removed_comment_notes=[];rollback_verified=true;id_discovery_hint;markup_mode="track_changes";_in_process_batch=false;_revisionIndex=null;constructor(e,t="Adeu AI (TS)",r){this.doc=e,this.author=t,this.id_discovery_hint=r?.id_discovery_hint??null,this.markup_mode=r?.markup_mode==="manual"?"manual":"track_changes",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=bn(e),r?.timestamp instanceof Date?this.timestamp=r.timestamp.toISOString().replace(/\.\d{3}Z$/,"Z"):typeof r?.timestamp=="string"?this.timestamp=r.timestamp:this.timestamp=new Date().toISOString().replace(/\.\d{3}Z$/,"Z");let i="http://schemas.microsoft.com/office/word/2023/wordml/word16du";for(let s of this.doc.pkg.parts)if(s===this.doc.part&&!s._element.hasAttribute("xmlns:w16du")){let o=s._element.ownerDocument,a=hr(o);s._element.setAttribute("xmlns:w16du",i),a&&$t(o);}this.current_id=this._scan_existing_ids(),this.mapper=new Te(this.doc),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.comments_manager=new It(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,t,r,i,s,o){let a,l,d,c;if(e===t)a=e,l=t,d=r,c="COMMENT_ONLY";else {let[f,h]=ft(e,t);a=e.slice(f,e.length-h),l=t.slice(f,t.length-h),d=r+f,[a,l]=Fi(a,l),!a&&l?c="INSERTION":a&&!l?c="DELETION":c="MODIFICATION";}let u={type:"modify",target_text:a,new_text:l,comment:i};return u._resolved_start_idx=d,u._match_start_index=d,u._active_mapper_ref=o,u._internal_op=c,s&&(u._is_table_edit=true),[u]}_header_block_error(e,t,r,i,s){let o=t.part_kind_of(r);if(o!=="header"&&o!=="footer")return null;let a=g(p=>p.test(s)&&!p.test(i),"adds");if(!a(ru)&&!a(iu))return null;let l=t.part_names[r]||"",d=`page ${o}`+(l?` (${l})`:""),[c,u]=o==="header"?["first","start"]:["last","end"],f=t.body_edge_line(o==="footer"),h=f?`: '${f}'`:"",_=f?t.full_text.split(f).length-1:0;return _>1&&(h+=o==="header"?` (it appears ${_} times: pass match_mode="first")`:` (it appears ${_} times: include the paragraph before it so the target is unique)`),`- Edit ${e} Failed: target_text is in the ${d}, which repeats on every page; headings and tables cannot be added there. To add content at the ${u} of the document, target the ${c} body paragraph instead${h}. Wording changes inside the ${o} are still allowed.`}_report_target(e){let t=e._parent_edit_ref,r;return t&&(t.target_text||"").trim()?r=t.target_text:(r=e.target_text||"insertion",!r.trim()&&e._original_target_text&&(r=e._original_target_text)),r.trim().substring(0,40)||"insertion"}_word_diff_sub_edits(e,t,r,i=null,s=false,o=null){if(i!=null)return this._single_commented_sub_edit(e,t,r,i,s,o);let a=[];try{a=At(e,t);}catch{a=[];}let l=g(u=>{let f=u.trim();return f.length>0&&/^[*_]+$/.test(f)},"_marker_only");a=a.filter(u=>!((!u.target_text||l(u.target_text))&&(!u.new_text||l(u.new_text))&&(u.target_text||u.new_text)));for(let u of a)u.target_text&&l(u.target_text)&&u.new_text&&!l(u.new_text)&&(u.target_text="");if(!a||a.length===0){let u={type:"modify",target_text:e,new_text:t,comment:i};return u._resolved_start_idx=r,u._match_start_index=r,u._active_mapper_ref=o,s&&(u._is_table_edit=true),e===t?u._internal_op="COMMENT_ONLY":!e&&t?u._internal_op="INSERTION":e&&!t?u._internal_op="DELETION":e&&t?u._internal_op="MODIFICATION":u._internal_op="COMMENT_ONLY",[u]}let d=[],c=false;for(let u of a){let f=r+(u._match_start_index||0),h=i!==null&&!c;h&&(c=true);let _={type:"modify",target_text:u.target_text,new_text:u.new_text,comment:h?i:null};_._resolved_start_idx=f,_._match_start_index=f,_._active_mapper_ref=o,s&&(_._is_table_edit=true);let p=u.target_text,m=u.new_text;!p&&m?_._internal_op="INSERTION":p&&!m?_._internal_op="DELETION":p&&m?_._internal_op="MODIFICATION":_._internal_op="COMMENT_ONLY",d.push(_);}return d}_nearest_match_hint(e,t){if(!e)return "";let r=e;if(t&&(r=r.replace(/^\^/,"").replace(/\$$/,""),r=r.replace(/^\\s\*/,"").replace(/\\s\*$/,""),r=r.replace(/\\([.^$*+?()[\]{}|\\/])/g,"$1")),r=r.trim(),(!r||r===e)&&!t)return "";let i=this.mapper.full_text.indexOf(r);if(i!==-1){let s=Math.max(0,i-15),o=Math.min(this.mapper.full_text.length,i+r.length+15),a=this.mapper.full_text.substring(s,o).replace(/\n/g," ");return `
|
|
130
|
+
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,t){e=e.replace(/\{>>[\s\S]*?<<\}/g,"");for(let[r,i]of G._PREVIEW_WRAPPER_PAIRS)if(t==="before"){let s=0,o=0,a=0;for(;a<e.length;)e.startsWith(r,a)?(s+=1,a+=r.length):e.startsWith(i,a)?(s===0?o=a+i.length:s-=1,a+=i.length):a+=1;e=e.substring(o);}else {let s=[],o=0;for(;o<e.length;)e.startsWith(r,o)?(s.push(o),o+=r.length):e.startsWith(i,o)?(s.length>0&&s.pop(),o+=i.length):o+=1;s.length>0&&(e=e.substring(0,s[0]));}return t==="before"?e=e.replace(/^[-+=<>]{0,2}\}/,""):e=e.replace(/\{[-+=<>]{0,2}$/,""),e}_capture_preview_context(e){if(e.type!=="modify")return;let t=e._resolved_start_idx;if(t==null)return;let i=(e._active_mapper_ref||this.mapper).full_text;if(!i)return;let s=(e.target_text||"").length,o=i.substring(Math.max(0,t-$e),t),a=i.substring(t+s,t+s+$e);e._preview_context=[G._tidy_preview_context(o,"before"),G._tidy_preview_context(a,"after")];}_capture_parent_preview_context(e){if(!e||e.type!=="modify"||e._preview_context||!e._preview_span)return;let[t,r]=e._preview_span,s=(e._preview_mapper_ref||this.mapper).full_text;if(!s)return;let o=s.substring(Math.max(0,t-$e),t),a=s.substring(t+r,t+r+$e);e._preview_context=[G._tidy_preview_context(o,"before"),G._tidy_preview_context(a,"after")];}_build_full_match_preview(e){let[t,r]=e._preview_context,i=e._preview_matched_text||"",s=e._preview_new_text!==void 0&&e._preview_new_text!==null?e._preview_new_text:e.new_text||"",[o,a]=this._parse_markdown_style(i),[l,d]=this._parse_markdown_style(s);a&&a.startsWith("Heading")&&(t=t+i.substring(0,i.length-o.length),i=o),d&&d.startsWith("Heading")&&(s=l);let[c,u]=ft(i,s),f=i.substring(c,i.length-u),h=s.substring(c,s.length-u);t=t+i.substring(0,c),u&&(r=i.substring(i.length-u)+r),f=ge(f,ct),h=ge(h,ct);let _;if(!f&&!h){let m=ge(i,ct),w=m?`{==${m}==}`:"";_=`${t.substring(0,t.length-i.length)}${w}${r}`;}else {let m=f?`{--${f}--}`:"",w=h?`{++${h}++}`:"";_=`${t}${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 t=new Set((e._minted_change_ids||[]).map(w=>String(w))),r=new Set((e._minted_comment_ids||[]).map(w=>String(w)));if(t.size===0&&r.size===0)return null;let i=this.mapper;i.full_text||i._build_map();let s=i.full_text;if(!s)return null;let o=[];for(let w of i.spans)(w.ins_id&&t.has(String(w.ins_id))||w.del_id&&t.has(String(w.del_id))||r.size>0&&w.comment_ids&&w.comment_ids.some(b=>r.has(String(b))))&&o.push([w.start,w.end]);if(o.length===0)return null;let a=/\{>>[\s\S]*?<<\}/g,l=[],d;for(;(d=a.exec(s))!==null;)l.push([d.index,d.index+d[0].length]);let c=s,u=g(w=>w,"to_visible");if(l.length>0){let w=[],y=0;for(let[b,v]of l)w.push(s.substring(y,b)),y=v;w.push(s.substring(y)),c=w.join(""),u=g(b=>{let v=0;for(let[N,k]of l)if(b>=k)v+=k-N;else if(b>N){v+=b-N;break}else break;return b-v},"to_visible");}o.sort((w,y)=>w[0]-y[0]);let f=[];for(let[w,y]of o){let b=u(w),v=u(y),N=Math.max(0,b-$e),k=Math.min(c.length,v+$e),x=f.length>0?f[f.length-1]:null;x&&N<=x[1]?x[1]=Math.max(x[1],k):f.push([N,k]);}let h=[];for(let[w,y]of f){let b=c.substring(w,y);b=G._tidy_preview_context(b,"before"),b=G._tidy_preview_context(b,"after"),h.push(b);}let _=h.join(`
|
|
122
131
|
\u2026
|
|
123
|
-
`),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=
|
|
124
|
-
`),a=[],c=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<c){let h=d[2].replace(/\*\*|__|[*_]/g,"").replace(/\{#[^}]+\}/g,"").trim();if(h.length>80&&(h=h.substring(0,80)+"..."),a.unshift(h),c=f,f===1)break}}}return [a.join(" > "),i]}accept_all_revisions(e=false){let t=this._revision_roots(),r=0,i=0,s=0;for(let f of t){r+=R(f,"w:ins").length,i+=R(f,"w:del").length;for(let h of ["w:rPrChange","w:pPrChange","w:sectPrChange"])s+=R(f,h).length;}let o=this._comment_authors(),a=new Set(Object.keys(o));this.removed_comment_notes=[];for(let f of t){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=S(m,"w:pPr");if(w){let y=S(w,"w:rPr"),b=y?S(y,"w:del"):null;if(y&&b){let v=false;for(let N of ["w:t","w:tab","w:br"]){for(let k of R(m,N)){if(N==="w:t"&&!k.textContent)continue;let x=false,C=k.parentNode;for(;C&&C!==m;){if(C.tagName==="w:del"){x=true;break}C=C.parentNode;}if(!x){v=true;break}}if(v)break}v||this._is_last_paragraph_in_cell(m)?y.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 y=w.parentNode;y&&y.parentNode&&y.parentNode.removeChild(y);}else w.removeChild(m);}for(let m of R(f,"w:pPrChange"))m.parentNode?.removeChild(m);}if(e)for(let f of t){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 c=this.doc.pkg,u=new Set;for(let f of c.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 c.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 y=h.partname.replace("/_rels/","/").replace(".rels",""),b=c.getPartByPath(y);if(b){let v=m.getAttribute("Id");v&&b.rels.delete(v);}}for(let m of p)m.parentNode?.removeChild(m);}let f=c.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);}c.parts=c.parts.filter(h=>!h.partname.toLowerCase().includes("comments"));for(let h of Object.keys(c.unzipped))h.toLowerCase().includes("comments")&&delete c.unzipped[h];}let l=new Set(this._existing_comment_ids()),d=Array.from(a).filter(f=>!l.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:i,accepted_formatting:s,removed_comments:d.length}}reject_all_revisions(){let e=this._revision_roots();for(let t of e){for(let o of R(t,"w:pPrChange"))this._revert_ppr_change(o);let r=R(t,"w:ins");for(let o of r){let a=o.parentNode;if(a)if(this._clean_wrapping_comments(o),this._delete_comments_in_element(o),a.tagName==="w:trPr"){let c=a.parentNode;c&&c.parentNode&&c.parentNode.removeChild(c);}else a.removeChild(o);}let i=R(t,"w:p");for(let o of i){let a=S(o,"w:pPr");if(a){let c=S(a,"w:rPr"),u=c?S(c,"w:del"):null;if(c&&u){c.removeChild(u);let l=Array.from(o.childNodes),d=l.filter(f=>f.nodeType===1&&f.tagName==="w:del");if(d.length>0){let f=d[d.length-1],h=l.indexOf(f),_=l.slice(h+1);if(_.some(m=>m.nodeType===1&&(m.tagName==="w:r"||m.tagName==="w:sdt"||m.getElementsByTagName("w:t").length>0))&&o.parentNode){let w=o.ownerDocument.createElement("w:p"),y=a.cloneNode(true),b=S(y,"w:rPr");if(b){let v=S(b,"w:del");v&&b.removeChild(v);}w.appendChild(y);for(let v of _)o.removeChild(v),w.appendChild(v);o.parentNode.insertBefore(w,o.nextSibling);}}}}}let s=R(t,"w:del");for(let o of s){let a=o.parentNode;if(!a)continue;if(a.tagName==="w:trPr"){a.removeChild(o);continue}let c=Array.from(o.getElementsByTagName("w:delText"));for(let u of c){let l=o.ownerDocument.createElement("w:t");l.textContent=u.textContent,u.hasAttribute("xml:space")&&l.setAttribute("xml:space","preserve"),u.parentNode?.replaceChild(l,u);}for(;o.firstChild;)a.insertBefore(o.firstChild,o);a.removeChild(o);}}}_revert_ppr_change(e){let t=e.parentNode;if(!t||t.tagName!=="w:pPr")return;let r=t.parentNode;if(!r)return;let i=S(e,"w:pPr");if(i){let s=i.cloneNode(true);Array.from(s.childNodes).some(a=>a.nodeType===1)?r.replaceChild(s,t):r.removeChild(t);}else r.removeChild(t);}_revert_props_change(e){let t=e.parentNode;if(!t)return;let r=Array.from(e.childNodes).find(s=>s.nodeType===1);t.removeChild(e);let i=Bu[t.tagName];for(let s of Array.from(t.childNodes)){if(s.nodeType!==1)continue;let o=s;o.tagName==="w:rPr"&&(S(o,"w:ins")||S(o,"w:del"))||i?.has(o.tagName)||t.removeChild(s);}if(r)for(let s of Array.from(r.childNodes))s.nodeType===1&&t.appendChild(s.cloneNode(true));}_getNextId(){return this.current_id++,this.current_id.toString()}_create_track_change_tag(e,t="",r=null){let s=this.doc.part._element.ownerDocument.createElement(e),o=r!==null?r:this._getNextId();return s.setAttribute("w:id",o),s.setAttribute("w:author",t||this.author),s.setAttribute("w:date",this.timestamp),s.setAttribute("w16du:dateUtc",this.timestamp),s}_set_text_content(e,t){e.textContent=t,t.trim()!==t&&e.setAttribute("xml:space","preserve");}_comment_anchor_in_main_story(e){let t=e;for(;t.parentNode&&t.parentNode.nodeType===1;)t=t.parentNode;return t.tagName==="w:document"}_skip_comment_outside_main_story(e,t){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",s=`- Warning: the comment "${t.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(s),true}_attach_comment(e,t,r,i){let s=null;for(let o of Qr(i)){let a=this._attach_one_comment(e,t,r,o.text,o.author);s=s??a;}return s}_attach_one_comment(e,t,r,i,s){if(!i||!e||!t||!r||this._skip_comment_outside_main_story(e,i))return null;let o=this.comments_manager.addComment(s||this.author,i,null,this.timestamp),a=e.ownerDocument,c=a.createElement("w:commentRangeStart");c.setAttribute("w:id",o);let u=a.createElement("w:commentRangeEnd");u.setAttribute("w:id",o);let l=a.createElement("w:r"),d=a.createElement("w:rPr"),f=a.createElement("w:rStyle");f.setAttribute("w:val","CommentReference"),d.appendChild(f),l.appendChild(d);let h=a.createElement("w:commentReference");h.setAttribute("w:id",o),l.appendChild(h),e.insertBefore(c,t);let _=r.nextSibling;return _?(e.insertBefore(u,_),e.insertBefore(l,u.nextSibling)):(e.appendChild(u),e.appendChild(l)),o}_attach_comment_spanning(e,t,r,i,s){for(let o of Qr(s))this._attach_one_comment_spanning(e,t,r,i,o.text,o.author);}_attach_one_comment_spanning(e,t,r,i,s,o){if(!s||!e||!r||this._skip_comment_outside_main_story(e,s)||this._skip_comment_outside_main_story(r,s))return;let a=this.comments_manager.addComment(o||this.author,s,null,this.timestamp),c=e.ownerDocument,u=r.ownerDocument,l=c.createElement("w:commentRangeStart");l.setAttribute("w:id",a);let d=u.createElement("w:commentRangeEnd");d.setAttribute("w:id",a);let f=u.createElement("w:r"),h=u.createElement("w:rPr"),_=u.createElement("w:rStyle");_.setAttribute("w:val","CommentReference"),h.appendChild(_),f.appendChild(h);let p=u.createElement("w:commentReference");p.setAttribute("w:id",a),f.appendChild(p),e.insertBefore(l,t);let m=i.nextSibling;m?(r.insertBefore(d,m),r.insertBefore(f,d.nextSibling)):(r.appendChild(d),r.appendChild(f));}_is_native_heading_element(e){try{let t=this.doc.part||this.doc,[r,i]=ht(t);return fn({_element:e},r,i)}catch{return false}}_clone_pPr_scrubbing_headings(e,t=null){let r=e.cloneNode(true),i=S(r,"w:pStyle");if(i){let o=i.getAttribute("w:val");o&&(o.startsWith("Heading")||o==="Title"||o.replace(/\s+/g,"").startsWith("Heading")||t!==null&&this._is_native_heading_element(t))&&r.removeChild(i);}let s=S(r,"w:outlineLvl");return s&&r.removeChild(s),r}_track_insert_multiline(e,t,r,i,s=null,o=false,a=false){if(!e)return {first_node:null,last_p:null,last_ins:null,used_block_mode:false};let c=this.doc.part._element.ownerDocument,u=e.split(/[\r\n]+/),l=null;if(r!==null)l=r._element;else if(t!==null){let F=t._element;for(;F&&F.tagName!=="w:p";)F=F.parentNode;l=F;}let d=[],f=new Set(["w:r","w:ins","w:del"]),h=s&&s.parentNode?s:null,_=t!==null&&t._element.parentNode?t._element:null,p=h??_,m=a&&h===null&&_!==null;if(l!==null&&p!==null){let F=p;for(;F&&F.parentNode!==l;)if(F=F.parentNode,F===l){F=null;break}if(F){let T=m?F:F.nextSibling;for(;T;)T.nodeType===1&&f.has(T.tagName)&&d.push(T),T=T.nextSibling;}}else if(l!==null&&a){let F=l.firstChild;for(;F;)F.nodeType===1&&f.has(F.tagName)&&d.push(F),F=F.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,y]=this._parse_markdown_style(u[0]),b=l!==null,v=/[\r\n]/.test(e),N=y!==null&&b&&v,k=null,x=null;N||(x=this._build_tracked_ins_for_line((w===u[0],u[0]),t,i,c,o),k=x);let C=N?u:u.slice(1);if(C.length===0)return {first_node:k,last_p:null,last_ins:x,used_block_mode:false};if(!l)return {first_node:k,last_p:null,last_ins:x,used_block_mode:false};let E=l.parentNode;if(!E)return {first_node:k,last_p:null,last_ins:x,used_block_mode:false};let P=g((F,T)=>{E.insertBefore(F,T.nextSibling);},"insertAfterEl"),I=null,M=null,j=l;for(let F=0;F<C.length;F++){let T=C[F],[O,D]=this._parse_markdown_style(T),A=c.createElement("w:p");if(D)this._set_paragraph_style(A,D);else {let L=S(l,"w:pPr");L&&A.appendChild(this._clone_pPr_scrubbing_headings(L,l));}let $=S(A,"w:pPr");$||($=c.createElement("w:pPr"),A.insertBefore($,A.firstChild));let W=S($,"w:rPr");W||(W=c.createElement("w:rPr"),$.appendChild(W));let z=this._create_track_change_tag("w:ins","",i);W.appendChild(z);let H=this._build_tracked_ins_for_line(O,t,i,c,o);H&&A.appendChild(H),P(A,j),j=A,I=A,M=H,k||(k=A);}if(!N&&I&&d.length>0)for(let F of d)F.parentNode?.removeChild(F),I.appendChild(F);return {first_node:k,last_p:I,last_ins:M,used_block_mode:N}}_build_tracked_ins_for_line(e,t,r,i,s=false){if(!e&&e!=="")return null;let o=this._create_track_change_tag("w:ins","",r),a=this._parse_inline_markdown(e);if(a.length===0)return null;for(let[c,u]of a){let l=i.createElement("w:r");if(t&&t._element){let f=S(t._element,"w:rPr");if(f){let h=f.cloneNode(true),_=["w:vanish","w:strike","w:dstrike","w:i","w:iCs"];s&&_.push("w:b","w:bCs");for(let p of _){let m=S(h,p);m&&h.removeChild(m);}l.appendChild(h);}}this._apply_run_props(l,u,false);let d=i.createElement("w:t");this._set_text_content(d,c),l.appendChild(d),o.appendChild(l);}return o}_parse_markdown_style(e){let t=e.trimStart();if(t.startsWith("#")){let i=0,s=t;for(;s.startsWith("#");)i++,s=s.substring(1);if(s.startsWith(" "))return [s.trim(),`Heading ${i}`]}if(t.startsWith("* ")||t.startsWith("- "))return [t.substring(2).trim(),"List Paragraph"];let r=t.match(/^1\.\s+/);return r?[t.substring(r[0].length).trim(),"List Number"]:[e,null]}_edit_declares_emphasis(e){for(let t of [e?.target_text,e?.new_text]){if(!t||!t.includes("**")&&!t.includes("_"))continue;if(this._parse_inline_markdown(t).some(([,i])=>i&&Object.keys(i).length>0))return true}return false}_is_escaped(e,t){let r=0,i=t-1;for(;i>=0&&e[i]==="\\";)r++,i--;return r%2===1}_unescape_markdown(e){return e.replace(/\\([\\*_])/g,"$1")}_is_word_char(e){return /[\p{L}\p{N}_]/u.test(e)}_is_space(e){return e==="\uFEFF"?false:/^\s$/u.test(e)||e==="\x85"||e>=""&&e<=""}_prev_char(e,t){if(t<=0)return "";let r=e.charCodeAt(t-1);if(r>=56320&&r<=57343&&t-2>=0){let i=e.charCodeAt(t-2);if(i>=55296&&i<=56319)return e.slice(t-2,t)}return e[t-1]}_next_char(e,t){if(t>=e.length)return "";let r=e.charCodeAt(t);if(r>=55296&&r<=56319&&t+1<e.length){let i=e.charCodeAt(t+1);if(i>=56320&&i<=57343)return e.slice(t,t+2)}return e[t]}_find_next_emphasis(e){let t=e.length,r=0;for(;r<t;){if(r+1<t&&e.substring(r,r+2)==="**"&&!this._is_escaped(e,r)&&r+2<t&&e[r+2]!=="*"&&!this._is_space(this._next_char(e,r+2))){let i=r+2;for(;i+1<t;)if(e.substring(i,i+2)==="**"&&!this._is_escaped(e,i)){if(!this._is_space(this._prev_char(e,i))){let s=e.substring(r+2,i);if(s&&!/^[*]+$/.test(s))return [r,i+2,"bold",s]}i+=2;}else i++;}if(e[r]==="_"&&!this._is_escaped(e,r)){let i=r>0&&e[r-1]==="_",s=r+1<t&&e[r+1]==="_",o=r>0&&this._is_word_char(this._prev_char(e,r)),a=r+1===t||this._is_space(this._next_char(e,r+1));if(!i&&!s&&!o&&!a){let c=r+1;for(;c<t;){if(e[c]==="_"&&!this._is_escaped(e,c)){let u=this._is_space(this._prev_char(e,c)),l=e[c-1]==="_",d=c+1<t&&e[c+1]==="_",f=c+1<t&&this._is_word_char(this._next_char(e,c+1));if(!u&&!l&&!d&&!f){let h=e.substring(r+1,c);if(h&&!/^[_]+$/.test(h))return [r,c+1,"italic",h]}}c++;}}}r++;}return null}_parse_inline_markdown(e,t={}){if(!e)return [];let r=this._find_next_emphasis(e);if(!r)return [[this._unescape_markdown(e),t]];let[i,s,o,a]=r,c=e.substring(0,i),u=e.substring(s),l=[];c&&l.push([this._unescape_markdown(c),t]);let d={...t};return o==="bold"?d.bold=true:d.italic=true,l.push(...this._parse_inline_markdown(a,d)),l.push(...this._parse_inline_markdown(u,t)),l}_apply_run_props(e,t,r=false){if(!t){if(!r)return;t={};}let i=S(e,"w:rPr");if(!i&&(t.bold||t.italic||r)&&(i=e.ownerDocument.createElement("w:rPr"),e.appendChild(i)),i){let s=e.ownerDocument;if(t.bold){let o=S(i,"w:b");o||(o=s.createElement("w:b"),i.appendChild(o)),o.setAttribute("w:val","1");}else if(r){let o=S(i,"w:b");o&&i.removeChild(o);}if(t.italic){let o=S(i,"w:i");o||(o=s.createElement("w:i"),i.appendChild(o)),o.setAttribute("w:val","1");}else if(r){let o=S(i,"w:i");o&&i.removeChild(o);}}}_set_paragraph_style(e,t,r=null){let i=e.ownerDocument,s=S(e,"w:pPr");s&&e.removeChild(s);let o=i.createElement("w:pPr"),a=i.createElement("w:pStyle"),c=t.replace(/\s+/g,"");if(a.setAttribute("w:val",c),o.appendChild(a),c==="ListParagraph"){let u=this._ensure_bullet_num_id();if(u){let l=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),l.appendChild(d),l.appendChild(f),o.appendChild(l);}}if(r!==null){let u=this._create_track_change_tag("w:pPrChange","",r),l=s?s.cloneNode(true):i.createElement("w:pPr"),d=S(l,"w:pPrChange");d&&l.removeChild(d),u.appendChild(l),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,t="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(P=>String(P.partname).replace(/^\//,"")==="word/numbering.xml");if(!i){let P=`<w:numbering xmlns:w="${t}"><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",V._NUMBERING_CT,P),this.doc.relateTo(i,V._NUMBERING_RT);}catch{return null}return delete e._adeu_numbering_cache,"1"}let s=i._element,o=R(s,"w:abstractNum"),a=R(s,"w:num"),c=null;for(let P of o){let I=P.getAttribute("w:abstractNumId");if(I!==null){for(let M of R(P,"w:lvl")){if((M.getAttribute("w:ilvl")||"0")!=="0")continue;let j=S(M,"w:numFmt");j&&j.getAttribute("w:val")==="bullet"&&(c=I);break}if(c!==null)break}}let u=0;for(let P of a){let I=parseInt(P.getAttribute("w:numId")||"0",10);!isNaN(I)&&I>u&&(u=I);}let l=s.ownerDocument;if(c!==null){for(let M of a){let j=S(M,"w:abstractNumId");if(j&&j.getAttribute("w:val")===c){let F=M.getAttribute("w:numId");if(F&&F!=="0")return F}}let P=l.createElement("w:num");P.setAttribute("w:numId",String(u+1));let I=l.createElement("w:abstractNumId");return I.setAttribute("w:val",c),P.appendChild(I),s.appendChild(P),delete e._adeu_numbering_cache,String(u+1)}let d=-1;for(let P of o){let I=parseInt(P.getAttribute("w:abstractNumId")||"-1",10);!isNaN(I)&&I>d&&(d=I);}let f=l.createElement("w:abstractNum");f.setAttribute("w:abstractNumId",String(d+1));let h=l.createElement("w:multiLevelType");h.setAttribute("w:val","singleLevel"),f.appendChild(h);let _=l.createElement("w:lvl");_.setAttribute("w:ilvl","0");let p=l.createElement("w:start");p.setAttribute("w:val","1"),_.appendChild(p);let m=l.createElement("w:numFmt");m.setAttribute("w:val","bullet"),_.appendChild(m);let w=l.createElement("w:lvlText");w.setAttribute("w:val","\uF0B7"),_.appendChild(w);let y=l.createElement("w:lvlJc");y.setAttribute("w:val","left"),_.appendChild(y);let b=l.createElement("w:pPr"),v=l.createElement("w:ind");v.setAttribute("w:left","720"),v.setAttribute("w:hanging","360"),b.appendChild(v),_.appendChild(b);let N=l.createElement("w:rPr"),k=l.createElement("w:rFonts");k.setAttribute("w:ascii","Symbol"),k.setAttribute("w:hAnsi","Symbol"),k.setAttribute("w:hint","default"),N.appendChild(k),_.appendChild(N),f.appendChild(_);let x=a.find(P=>P.parentNode===s)||null;x?s.insertBefore(f,x):s.appendChild(f);let C=l.createElement("w:num");C.setAttribute("w:numId",String(u+1));let E=l.createElement("w:abstractNumId");return E.setAttribute("w:val",String(d+1)),C.appendChild(E),s.appendChild(C),delete e._adeu_numbering_cache,String(u+1)}_anchor_reply_comment(e,t){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 s=i[0],o=r.createElement("w:commentRangeStart");o.setAttribute("w:id",t),at(o,s);let a=R(this.doc.element,"w:commentRangeEnd").filter(m=>m.getAttribute("w:id")===e);if(a.length===0)return;let c=a[0],u=R(this.doc.element,"w:commentReference").filter(m=>m.getAttribute("w:id")===e),l=c;if(u.length>0){let m=u[0];m.parentNode&&m.parentNode.tagName==="w:r"&&(l=m.parentNode);}let d=r.createElement("w:commentRangeEnd");d.setAttribute("w:id",t),at(d,l);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",t),f.appendChild(p),at(f,d);}_clean_wrapping_comments(e){let t=0,r=e;for(;;){let l=De(r);if(l&&(l.tagName==="w:ins"||l.tagName==="w:del"))r=l;else break}let i=e;for(;;){let l=Te(i);if(l&&(l.tagName==="w:ins"||l.tagName==="w:del"))i=l;else break}let s=[],o=De(r);for(;o;)if(o.tagName==="w:commentRangeStart")s.push(o),o=De(o);else if(o.tagName==="w:rPr"||o.tagName==="w:pPr")o=De(o);else break;let a=[],c=Te(i);for(;c;)if(c.tagName==="w:commentRangeEnd")a.push(c),c=Te(c);else if(c.tagName==="w:r"&&R(c,"w:commentReference").length>0)a.push(c),c=Te(c);else if(c.tagName==="w:commentReference")a.push(c),c=Te(c);else break;let u=new Set;for(let l of a)if(l.tagName==="w:commentRangeEnd"){let d=l.getAttribute("w:id");d&&u.add(d);}else {let d=R(l,"w:commentReference")[0];if(!d&&l.tagName==="w:commentReference"&&(d=l),d){let f=d.getAttribute("w:id");f&&u.add(f);}}for(let l of s){let d=l.getAttribute("w:id");if(d&&u.has(d)){this.comments_manager.deleteComment(d),t++,l.parentNode&&l.parentNode.removeChild(l);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 t}_delete_comments_in_element(e){let t=0,r=R(e,"w:commentReference");for(let i of r){let s=i.getAttribute("w:id");if(s){this.comments_manager.deleteComment(s),t++;for(let o of ["w:commentRangeStart","w:commentRangeEnd"]){let a=R(this.doc.element,o);for(let c of a)c.getAttribute("w:id")===s&&c.parentNode&&c.parentNode.removeChild(c);}}}return t}_control_gate_context(e,t,r){let i=typeof e?.controls_intersecting=="function"?e.controls_intersecting(t,r):[],s=typeof e?.controls_at=="function"?e.controls_at(t):[],o=typeof e?.controls_at=="function"?e.controls_at(Math.max(t+r-1,t)):[];return [i,s,o]}_deletes_entire_control(e,t,r,i,s){if(s.trim()!=="")return false;let a=(e?.control_ranges??[]).find(f=>f[2]===t);if(!a)return false;let[c,u]=a,l=r<=c&&r+i>=u,d=r<c||r+i>u;return l&&d}_check_control_gates(e,t,r,i,s,o="",a="",c=null,u=false){let l=this.gate_overrides,d=Array.from(r?._sdt_infos?.values()??[]),[f,h,_]=this._control_gate_context(r,i,s);c!==null&&(f=c);let p=!!t.comment&&(t.new_text||"")===(t.target_text||""),m=wc(e,this.protection,{controls:f,isCommentOnly:p,overrides:l});if(m||!p&&(m=vc(e,this.protection,l),m)||(m=bc(e,t.target_text||"",d),m))return m;if(f.length===0)return null;if(!u&&(m=Nc(e,f),m)||(m=xc(e,f,t.target_text||"",t.new_text||""),m)||(m=_c(e,f,l),m)||(m=mc(e,f,l),m))return m;for(let y of f)if(this._deletes_entire_control(r,y,i,s,a)&&(m=gc(e,[y],true,l),m))return m;if(o.includes(`
|
|
132
|
+
`),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=ct*2+4*$e;return [ge(_,m),ge(p,m)]}_build_edit_context_previews(e){if(e.type!=="modify")return [null,null];let t=this._build_postapply_previews(e);if(t)return t;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||"",s=e.new_text||"",[o,a]=this._parse_markdown_style(i);if(a&&a.startsWith("Heading")){let b=i.length-o.length;r+=b,i=o;}let[l,d]=this._parse_markdown_style(s);d&&d.startsWith("Heading")&&(s=l);let c=i.length,u,f;if(e._preview_context)[u,f]=e._preview_context;else {let v=(e._active_mapper_ref||this.mapper).full_text;if(!v)return [null,null];u=G._tidy_preview_context(v.substring(Math.max(0,r-$e),r),"before"),f=G._tidy_preview_context(v.substring(r+c,r+c+$e),"after");}let h=ge(i,ct),_=ge(s,ct),p=h?`{--${h}--}`:"",m=_?`{++${_}++}`:"",w=`${u}${p}${m}${f}`,y=w;return y=y.replace(/\{>>.*?<<\}/gs,""),y=y.replace(/\{--.*?--\}/gs,""),y=y.replace(/\{\+\+(.*?)\+\+\}/gs,"$1"),[w,y]}_revision_roots(){let e=[this.doc.element];for(let t of this.doc.pkg.parts)t!==this.doc.part&&t.contentType.includes("wordprocessingml")&&t.contentType.endsWith("+xml")&&e.push(t._element);return e}_story_roots(){let e=[[this.doc.element,Vn(this.doc.part.partname)]];for(let t of this.doc.pkg.parts)t!==this.doc.part&&au.includes(t.contentType)&&e.push([t._element,Vn(t.partname)]);return e}_scan_existing_ids(){let e=0;for(let t of this._revision_roots())for(let r of ["w:ins","w:del","w:pPrChange"]){let i=R(t,r);for(let s of i){let o=parseInt(s.getAttribute("w:id")||"0",10);!isNaN(o)&&o>e&&(e=o);}}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 t=$r(this.doc,e);return this._field_entries_cache=[e,t],t}_resolve_set_field_targets(e){return $d(this._field_entries(),e.field,e.match_mode||"strict")}_sdt_info_for_ordinal(e){let t=this.mapper._sdt_infos;if(!t)return null;for(let r of t.values())if(r.ordinal===e)return r;return null}_cc_content_range(e){this._field_label_at(0);for(let[t,r,i]of this._cc_anchor_pairs??[])if(i===e)return [t,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,t){let r=e?.full_text??"";if(!r)return null;let i=new Map,s=/\{#(\/?)cc:(\d+)(?: [^}]*)?\}/g,o;for(;(o=s.exec(r))!==null;){let a=Number(o[2]);if(o[1]){let l=i.get(a);if(i.delete(a),l!==void 0&&l===o.index&&o.index===t){let d=this._sdt_info_for_ordinal(a);return d?(d.showingPlaceholder&&Si(d)&&(this._cc_anchor_pairs=null,this._field_entries_cache=null,this._field_entries_cache=null),ht(d.element)):null}}else i.set(a,o.index+o[0].length);}return null}_apply_checkbox_set_field(e,t,r){let i=Di(e.value);if(i===null){let h=`CC:${t.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 s=Ld(r),[o,a]=Bd(r,i),l=this.doc.part._element.ownerDocument,d=s?s.cloneNode(true):l.createElement("w:r");for(let h of Array.from(d.getElementsByTagName("w:t")))h.parentNode?.removeChild(h);let c=l.createElement("w:t");if(c.appendChild(l.createTextNode(o)),d.appendChild(c),a){let h=$(d,"w:rPr");h||(h=l.createElement("w:rPr"),d.insertBefore(h,d.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 u=this._create_track_change_tag("w:ins","",this._getNextId());u.appendChild(d);let f=s?s.parentNode:null;if(f){f.insertBefore(u,s);let h=this._create_track_change_tag("w:del","",this._getNextId()),_=s.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,s);}else {let h=ht(r.element);if(!h)return false;h.appendChild(u);}return Fd(r,i),e._applied_status=true,e._occurrences_modified=(e._occurrences_modified||0)+1,true}_resolve_set_field(e,t){let r;try{r=this._resolve_set_field_targets(e);}catch(d){e._applied_status=false,e._error_msg=d?.message??String(d),this.skipped_details.push(`- ${e._error_msg}`);return}let i=g(d=>{let c=this._sdt_info_for_ordinal(d.ordinal);return c?c.cls:d.cls_word},"clsOf");for(let d of r){let c=this._sdt_info_for_ordinal(d.ordinal),u=Ii(i(d),d.ordinal);if(!u&&c&&(u=Oi(c,d.ordinal,e.value)),u){e._applied_status=false,e._error_msg=u,this.skipped_details.push(`- ${u}`);return}}let s=false;for(let d of r){let c=this._sdt_info_for_ordinal(d.ordinal);c?.showingPlaceholder&&Si(c)&&(s=true);}s&&this._invalidate_projection_caches();let o=new Map,a=new Map;for(let d of r){let c=this._sdt_info_for_ordinal(d.ordinal);if(c){if(c.cls==="dropdown"||c.cls==="combobox"){let[u,f]=ro(c,e.value);if(f){let h=`CC:${d.ordinal}: ${f}`;e._applied_status=false,e._error_msg=h,this.skipped_details.push(`- ${h}`);return}o.set(d.ordinal,u),c.cls==="combobox"&&!Wd(c,u)&&a.set(d.ordinal,`'${u}' is not in the option list`);}else if(c.cls==="date"){let u=or(e.value);if(!u){let _=`CC:${d.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]=Hd(u,c.dateFormat);o.set(d.ordinal,f),h&&a.set(d.ordinal,`the control's date format '${c.dateFormat}' is not supported in v1; wrote the canonical ${f}`);}}}let l=r.filter(d=>i(d)==="checkbox");if(l.length){let d=true;for(let c of l){let u=this._sdt_info_for_ordinal(c.ordinal);(!u||!this._apply_checkbox_set_field(e,c,u))&&(d=false);}d&&this._invalidate_projection_caches();return}for(let d of r){let c=this._cc_content_range(d.ordinal);if(!c){let y=`CC:${d.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=y,this.skipped_details.push(`- ${y}`);return}let[u,f]=c,h=this.mapper.full_text.slice(u,f),_=o.get(d.ordinal)??e.value,p=this._sdt_info_for_ordinal(d.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=u,m._active_mapper_ref=this.mapper,m._parent_edit_ref=e,!h&&p&&(m._insert_host_el=ht(p.element)),p){if(p.cls==="dropdown"||p.cls==="combobox")zd(p,_);else if(p.cls==="date"){let y=or(e.value);y&&qd(p,y);}if(p.bound){let y=Gd(this.doc,p.storeItemId),b=!!y&&Kd(y,p.bindingXpath,_,p.prefixMappings),v=a.get(d.ordinal),N=v?`; ${v}`:"";a.set(d.ordinal,b?`bound store ${p.bindingXpath} updated to match${N}`:`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.${N}`);}if(p.temporary){m._unwrap_sdt_after=p.element;let y=a.get(d.ordinal),b="this control was temporary and has been unwrapped, as Word does on any edit";a.set(d.ordinal,y?`${y}; ${b}`:b);}}let w=a.get(d.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=u,e._resolved_proxy_edit=m),t.push([m,_]);}}_field_label_at(e){if(this._cc_anchor_pairs===null){let a=[],l=this.mapper.full_text,d=new Map,c=/\{#(\/?)cc:(\d+)(?: [^}]*)?\}/g,u;for(;(u=c.exec(l))!==null;){let f=Number(u[2]);if(u[1]){let h=d.get(f);h!==void 0&&(d.delete(f),a.push([h,u.index,f]));}else d.set(f,u.index+u[0].length);}this._cc_anchor_pairs=a;}let t=null;for(let[a,l,d]of this._cc_anchor_pairs)a<=e&&e<=l&&(t===null||l-a<t[1]-t[0])&&(t=[a,l,d]);if(t===null)return "";let r=t[2],i=null,s=this.mapper._sdt_infos;if(s){for(let a of s.values())if(a.ordinal===r){i=a;break}}let o=`CC:${r}`;return i?.alias&&(o+=` "${i.alias}"`),i?.tag&&(o+=` (tag: ${i.tag})`),o}_get_heading_path_and_page(e,t,r){let i=1;for(let d=0;d<r.length&&e>=r[d];d++)i=d+1;let o=t.substring(0,e).split(`
|
|
133
|
+
`),a=[],l=999;for(let d=o.length-1;d>=0;d--){let u=o[d].match(/^(#{1,6})\s+(.*)/);if(u){let f=u[1].length;if(f<l){let h=u[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 t=this._revision_roots(),r=0,i=0,s=0;for(let f of t){r+=R(f,"w:ins").length,i+=R(f,"w:del").length;for(let h of ["w:rPrChange","w:pPrChange","w:sectPrChange"])s+=R(f,h).length;}let o=this._comment_authors(),a=new Set(Object.keys(o));this.removed_comment_notes=[];for(let f of t){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=$(m,"w:pPr");if(w){let y=$(w,"w:rPr"),b=y?$(y,"w:del"):null;if(y&&b){let v=false;for(let N of ["w:t","w:tab","w:br"]){for(let k of R(m,N)){if(N==="w:t"&&!k.textContent)continue;let x=false,P=k.parentNode;for(;P&&P!==m;){if(P.tagName==="w:del"){x=true;break}P=P.parentNode;}if(!x){v=true;break}}if(v)break}v||this._is_last_paragraph_in_cell(m)?y.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 y=w.parentNode;y&&y.parentNode&&y.parentNode.removeChild(y);}else w.removeChild(m);}for(let m of R(f,"w:pPrChange"))m.parentNode?.removeChild(m);}if(e)for(let f of t){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,d=new Set;for(let f of l.parts)if(e&&f.partname.toLowerCase().includes("comments")){d.add(f.partname);let h=f.partname.startsWith("/")?f.partname:"/"+f.partname,_=f.partname.startsWith("/")?f.partname.substring(1):f.partname;d.add(h),d.add(_);}if(d.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 y=h.partname.replace("/_rels/","/").replace(".rels",""),b=l.getPartByPath(y);if(b){let v=m.getAttribute("Id");v&&b.rels.delete(v);}}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")||"";(d.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()),u=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=u.map(f=>`Com:${f} (by ${o[f]??"Unknown"})`),this._prune_empty_paragraph_properties(),{accepted_insertions:r,accepted_deletions:i,accepted_formatting:s,removed_comments:u.length}}reject_all_revisions(){let e=this._revision_roots();for(let t of e){for(let a of R(t,"w:pPrChange"))this._revert_ppr_change(a);let r=R(t,"w:ins"),i=[];for(let a of r){let l=a.parentNode;if(!l)continue;if(this._clean_wrapping_comments(a),this._delete_comments_in_element(a),l.tagName==="w:trPr"){let c=l.parentNode;c&&c.parentNode&&c.parentNode.removeChild(c);continue}let d=l.parentNode;if(l.tagName==="w:rPr"&&d&&d.tagName==="w:pPr"){l.removeChild(a),!Array.from(l.childNodes).some(f=>f.nodeType===1)&&(!l.attributes||l.attributes.length===0)&&d.removeChild(l);let u=d.parentNode;u&&u.tagName==="w:p"&&i.push(u);continue}l.removeChild(a);}this._resolve_rejected_mark_hosts(i);let s=R(t,"w:p");for(let a of s){let l=$(a,"w:pPr");if(l){let d=$(l,"w:rPr"),c=d?$(d,"w:del"):null;if(d&&c){d.removeChild(c);let u=Array.from(a.childNodes),f=u.filter(h=>h.nodeType===1&&h.tagName==="w:del");if(f.length>0){let h=f[f.length-1],_=u.indexOf(h),p=u.slice(_+1);if(p.some(w=>w.nodeType===1&&(w.tagName==="w:r"||w.tagName==="w:sdt"||w.getElementsByTagName("w:t").length>0))&&a.parentNode){let y=a.ownerDocument.createElement("w:p"),b=l.cloneNode(true),v=$(b,"w:rPr");if(v){let N=$(v,"w:del");N&&v.removeChild(N);}y.appendChild(b);for(let N of p)a.removeChild(N),y.appendChild(N);a.parentNode.insertBefore(y,a.nextSibling);}}}}}let o=R(t,"w:del");for(let a of o){let l=a.parentNode;if(!l)continue;if(l.tagName==="w:trPr"){l.removeChild(a);continue}let d=Array.from(a.getElementsByTagName("w:delText"));for(let c of d){let u=a.ownerDocument.createElement("w:t");u.textContent=c.textContent,c.hasAttribute("xml:space")&&u.setAttribute("xml:space","preserve"),c.parentNode?.replaceChild(u,c);}for(;a.firstChild;)l.insertBefore(a.firstChild,a);l.removeChild(a);}}this._prune_empty_paragraph_properties();}_prune_empty_paragraph_properties(){let e=g(t=>!Array.from(t.childNodes).some(r=>r.nodeType===1)&&t.attributes.length===0,"isEmpty");for(let t of this._revision_roots())for(let r of R(t,"w:pPr")){let i=$(r,"w:rPr");i&&e(i)&&r.removeChild(i);let s=r.parentNode;s&&s.tagName==="w:p"&&e(r)&&s.removeChild(r);}}_resolve_rejected_mark_hosts(e){if(e.length===0)return;let t=[],r=new Set;for(let a of e)r.has(a)||(r.add(a),t.push(a));let i=new Set(["w:r","w:del","w:ins","w:sdt","w:hyperlink","w:fldSimple","w:smartTag","w:oMath","w:oMathPara"]),s=g(a=>{for(let l of Array.from(a.childNodes)){if(l.nodeType!==1)continue;let d=l;if(d.tagName!=="w:pPr"){if(i.has(d.tagName))return true;for(let c of i)if(d.getElementsByTagName(c).length>0)return true}}return false},"hasContent"),o=[];for(let a of t){let l=a.parentNode;if(l){if(s(a))o.push(a);else if(!this._is_last_paragraph_in_cell(a)){let d=Array.from(a.childNodes).filter(c=>c.nodeType===1&&c.tagName!=="w:pPr");if(d.length>0){let c=le(a);for(;c&&c.tagName!=="w:p";)c=le(c);let u=Ce(a);for(;u&&u.tagName!=="w:p";)u=Ce(u);if(c){let f=$(c,"w:pPr"),h=f?f.nextSibling:c.firstChild;for(let _ of d)a.removeChild(_),c.insertBefore(_,h);}else if(u)for(let f of d)a.removeChild(f),u.appendChild(f);}l.removeChild(a);}}}for(let a of o.reverse()){let l=a.parentNode;if(!l)continue;let d=le(a);for(;d&&d.tagName!=="w:p";)d=le(d);if(d){let c=$(d,"w:pPr"),u=c?$(c,"w:rPr"):null;if(u){let f=Array.from(u.childNodes).filter(h=>h.nodeType===1&&(h.tagName==="w:ins"||h.tagName==="w:del"));if(f.length>0){let h=a.ownerDocument,_=$(a,"w:pPr");_||(_=h.createElement("w:pPr"),a.insertBefore(_,a.firstChild));let p=$(_,"w:rPr");p||(p=h.createElement("w:rPr"),_.appendChild(p));for(let m=f.length-1;m>=0;m--)u.removeChild(f[m]),p.insertBefore(f[m],p.firstChild);}}for(let f of Array.from(d.childNodes))f.nodeType===1&&f.tagName==="w:pPr"||(d.removeChild(f),a.appendChild(f));l.removeChild(d);}else {let c=Ce(a);for(;c&&c.tagName!=="w:p";)c=Ce(c);if(c&&!this._is_last_paragraph_in_cell(a)){for(let u of Array.from(a.childNodes))u.nodeType===1&&u.tagName==="w:pPr"||(a.removeChild(u),c.appendChild(u));l.removeChild(a);}}}}_revert_ppr_change(e){let t=e.parentNode;if(!t||t.tagName!=="w:pPr")return;let r=t.parentNode;if(!r)return;let i=$(e,"w:pPr");if(i){let s=i.cloneNode(true);Array.from(s.childNodes).some(a=>a.nodeType===1)?r.replaceChild(s,t):r.removeChild(t);}else r.removeChild(t);}_revert_props_change(e){let t=e.parentNode;if(!t)return;let r=Array.from(e.childNodes).find(s=>s.nodeType===1);t.removeChild(e);let i=ou[t.tagName];for(let s of Array.from(t.childNodes)){if(s.nodeType!==1)continue;let o=s;o.tagName==="w:rPr"&&($(o,"w:ins")||$(o,"w:del"))||i?.has(o.tagName)||t.removeChild(s);}if(r)for(let s of Array.from(r.childNodes))s.nodeType===1&&t.appendChild(s.cloneNode(true));}_getNextId(){return this.current_id++,this.current_id.toString()}_create_track_change_tag(e,t="",r=null){let s=this.doc.part._element.ownerDocument.createElement(e),o=r!==null?r:this._getNextId();return s.setAttribute("w:id",o),s.setAttribute("w:author",t||this.author),s.setAttribute("w:date",this.timestamp),s.setAttribute("w16du:dateUtc",this.timestamp),s}_set_text_content(e,t){e.textContent=t,t.trim()!==t&&e.setAttribute("xml:space","preserve");}_comment_anchor_in_main_story(e){let t=e;for(;t.parentNode&&t.parentNode.nodeType===1;)t=t.parentNode;return t.tagName==="w:document"}_skip_comment_outside_main_story(e,t){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",s=`- Warning: the comment "${t.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(s),true}_attach_comment(e,t,r,i){let s=null;for(let o of ai(i)){let a=this._attach_one_comment(e,t,r,o.text,o.author);s=s??a;}return s}_attach_one_comment(e,t,r,i,s){if(!i||!e||!t||!r||this._skip_comment_outside_main_story(e,i))return null;let o=this.comments_manager.addComment(s||this.author,i,null,this.timestamp),a=e.ownerDocument,l=a.createElement("w:commentRangeStart");l.setAttribute("w:id",o);let d=a.createElement("w:commentRangeEnd");d.setAttribute("w:id",o);let c=a.createElement("w:r"),u=a.createElement("w:rPr"),f=a.createElement("w:rStyle");f.setAttribute("w:val","CommentReference"),u.appendChild(f),c.appendChild(u);let h=a.createElement("w:commentReference");h.setAttribute("w:id",o),c.appendChild(h),e.insertBefore(l,t);let _=r.nextSibling;return _?(e.insertBefore(d,_),e.insertBefore(c,d.nextSibling)):(e.appendChild(d),e.appendChild(c)),o}_attach_comment_spanning(e,t,r,i,s){for(let o of ai(s))this._attach_one_comment_spanning(e,t,r,i,o.text,o.author);}_attach_one_comment_spanning(e,t,r,i,s,o){if(!s||!e||!r||this._skip_comment_outside_main_story(e,s)||this._skip_comment_outside_main_story(r,s))return;let a=this.comments_manager.addComment(o||this.author,s,null,this.timestamp),l=e.ownerDocument,d=r.ownerDocument,c=l.createElement("w:commentRangeStart");c.setAttribute("w:id",a);let u=d.createElement("w:commentRangeEnd");u.setAttribute("w:id",a);let f=d.createElement("w:r"),h=d.createElement("w:rPr"),_=d.createElement("w:rStyle");_.setAttribute("w:val","CommentReference"),h.appendChild(_),f.appendChild(h);let p=d.createElement("w:commentReference");p.setAttribute("w:id",a),f.appendChild(p),e.insertBefore(c,t);let m=i.nextSibling;m?(r.insertBefore(u,m),r.insertBefore(f,u.nextSibling)):(r.appendChild(u),r.appendChild(f));}_is_native_heading_element(e){try{let t=this.doc.part||this.doc,[r,i]=_t(t);return wn({_element:e},r,i)}catch{return false}}_clone_pPr_scrubbing_headings(e,t=null){let r=e.cloneNode(true),i=$(r,"w:pStyle");if(i){let a=i.getAttribute("w:val");a&&(a.startsWith("Heading")||a==="Title"||a.replace(/\s+/g,"").startsWith("Heading")||t!==null&&this._is_native_heading_element(t))&&r.removeChild(i);}let s=$(r,"w:outlineLvl");s&&r.removeChild(s);let o=$(r,"w:rPr");if(o){for(let l of Array.from(o.childNodes))l.nodeType===1&&(l.tagName==="w:ins"||l.tagName==="w:del")&&o.removeChild(l);!Array.from(o.childNodes).some(l=>l.nodeType===1)&&(!o.attributes||o.attributes.length===0)&&r.removeChild(o);}return r}static _is_pipe_table_row(e){let t=e.trim();return t.startsWith("|")&&t.endsWith("|")&&(t.match(/\|/g)||[]).length>=2}static _group_markdown_table_blocks(e){let t=[],r=0;for(;r<e.length;){if(G._is_pipe_table_row(e[r])){let i=[e[r].trim()],s=r+1;for(;s<e.length&&(G._is_pipe_table_row(e[s])||e[s]==="");)G._is_pipe_table_row(e[s])&&i.push(e[s].trim()),s++;if(i.length>=2){t.push(i.join(`
|
|
134
|
+
`)),r=s;continue}}t.push(e[r]),r++;}return t}static _is_markdown_pipe_table_block(e){if(!e.includes(`
|
|
135
|
+
`))return false;let t=e.split(/\r?\n/).map(r=>r.trim()).filter(Boolean);return t.length>=2&&t.every(r=>G._is_pipe_table_row(r))}_build_markdown_table_element(e,t,r,i,s){let a=e.split(/\r?\n/).map(w=>w.trim()).filter(Boolean).map(w=>w.slice(1,-1).split("|").map(y=>y.trim())),l=false;a.length>=2&&a[1].every(w=>w===""||/^:?-{2,}:?$/.test(w))&&(l=true,a=[a[0],...a.slice(2)]);let d=Math.max(1,...a.map(w=>w.length)),c=i.createElement("w:tbl"),u=i.createElement("w:tblPr"),f=i.createElement("w:tblW");f.setAttribute("w:w","5000"),f.setAttribute("w:type","pct"),u.appendChild(f);let h=i.createElement("w:tblBorders");for(let w of ["top","left","bottom","right","insideH","insideV"]){let y=i.createElement(`w:${w}`);y.setAttribute("w:val","single"),y.setAttribute("w:sz","4"),y.setAttribute("w:space","0"),y.setAttribute("w:color","BFBFBF"),h.appendChild(y);}u.appendChild(h),c.appendChild(u);let _=i.createElement("w:tblGrid");for(let w=0;w<d;w++)_.appendChild(i.createElement("w:gridCol"));c.appendChild(_);let p=String(Math.max(1,Math.floor(5e3/Math.max(1,d)))),m=null;for(let w=0;w<a.length;w++){let y=a[w],b=i.createElement("w:tr"),v=i.createElement("w:trPr"),N=l&&w===0;N&&v.appendChild(i.createElement("w:tblHeader")),v.appendChild(this._create_track_change_tag("w:ins","",t)),b.appendChild(v);for(let k=0;k<d;k++){let x=y[k]??"",P=i.createElement("w:tc"),E=i.createElement("w:tcPr"),T=i.createElement("w:tcW");if(T.setAttribute("w:w",p),T.setAttribute("w:type","pct"),E.appendChild(T),N){let M=i.createElement("w:shd");M.setAttribute("w:val","clear"),M.setAttribute("w:color","auto"),M.setAttribute("w:fill","F2F2F2"),E.appendChild(M);}P.appendChild(E);let I=i.createElement("w:p"),D=N&&x&&!x.startsWith("**")?`**${x}**`:x,F=this._build_tracked_ins_for_line(D,r,t,i,s);F&&(I.appendChild(F),m=F),P.appendChild(I),b.appendChild(P);}c.appendChild(b);}return {tbl:c,last_ins:m}}_track_insert_multiline(e,t,r,i,s=null,o=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,d=G._group_markdown_table_blocks(e.split(/[\r\n]+/)),c=null;if(r!==null)c=r._element;else if(t!==null){let C=t._element;for(;C&&C.tagName!=="w:p";)C=C.parentNode;c=C;}let u=[],f=new Set(["w:r","w:ins","w:del"]),h=s&&s.parentNode?s:null,_=t!==null&&t._element.parentNode?t._element:null,p=h??_,m=a&&h===null&&_!==null;if(c!==null&&p!==null){let C=p;for(;C&&C.parentNode!==c;)if(C=C.parentNode,C===c){C=null;break}if(C){let S=m?C:C.nextSibling;for(;S;)S.nodeType===1&&f.has(S.tagName)&&u.push(S),S=S.nextSibling;}}else if(c!==null&&a){let C=c.firstChild;for(;C;)C.nodeType===1&&f.has(C.tagName)&&u.push(C),C=C.nextSibling;}for(;d.length>1&&d[d.length-1]===""&&u.length===0;)d.pop();if(d.length===0)return {first_node:null,last_p:null,last_ins:null,used_block_mode:false};let[w,y]=this._parse_markdown_style(d[0]),b=c!==null,v=/[\r\n]/.test(e),N=G._is_markdown_pipe_table_block(d[0]),k=(y!==null||N)&&b&&v,x=null,P=null;k||(P=this._build_tracked_ins_for_line((w===d[0],d[0]),t,i,l,o),x=P);let E=k?d:d.slice(1);if(E.length===0)return {first_node:x,last_p:null,last_ins:P,used_block_mode:false};if(!c)return {first_node:x,last_p:null,last_ins:P,used_block_mode:false};let T=c.parentNode;if(!T)return {first_node:x,last_p:null,last_ins:P,used_block_mode:false};let I=g((C,S)=>{T.insertBefore(C,S.nextSibling);},"insertAfterEl"),D=null,F=null,M=c,B=!k&&u.length>0,j=[];if(B){let C=$(c,"w:pPr");C||(C=l.createElement("w:pPr"),c.insertBefore(C,c.firstChild));let S=$(C,"w:rPr");if(S)for(let O of Array.from(S.childNodes))O.nodeType===1&&(O.tagName==="w:ins"||O.tagName==="w:del")&&(S.removeChild(O),j.push(O));else S=l.createElement("w:rPr"),C.appendChild(S);let A=this._create_track_change_tag("w:ins","",i);S.insertBefore(A,S.firstChild);}for(let C=0;C<E.length;C++){let S=E[C];if(G._is_markdown_pipe_table_block(S)){let{tbl:z,last_ins:U}=this._build_markdown_table_element(S,i,t,l,o);I(z,M),M=z,U&&(F=U),x||(x=z);continue}let[A,O]=this._parse_markdown_style(S),L=l.createElement("w:p");if(O)this._set_paragraph_style(L,O);else {let z=$(c,"w:pPr");if(z){let U=this._clone_pPr_scrubbing_headings(z,c);(U.attributes.length>0||Array.from(U.childNodes).some(X=>X.nodeType===1))&&L.appendChild(U);}}let H=C===E.length-1;if(B&&H){if(j.length>0){let z=$(L,"w:pPr");z||(z=l.createElement("w:pPr"),L.insertBefore(z,L.firstChild));let U=$(z,"w:rPr");U||(U=l.createElement("w:rPr"),z.appendChild(U));for(let X=j.length-1;X>=0;X--)U.insertBefore(j[X],U.firstChild);}}else {let z=$(L,"w:pPr");z||(z=l.createElement("w:pPr"),L.insertBefore(z,L.firstChild));let U=$(z,"w:rPr");U||(U=l.createElement("w:rPr"),z.appendChild(U));let X=this._create_track_change_tag("w:ins","",i);U.insertBefore(X,U.firstChild);}let q=this._build_tracked_ins_for_line(A,t,i,l,o);q&&L.appendChild(q),I(L,M),M=L,D=L,F=q,x||(x=L);}if(!k&&D&&u.length>0)for(let C of u)C.parentNode?.removeChild(C),D.appendChild(C);return {first_node:x,last_p:D,last_ins:F,used_block_mode:k}}_build_tracked_ins_for_line(e,t,r,i,s=false){if(!e&&e!=="")return null;let o=this._create_track_change_tag("w:ins","",r),a=this._parse_inline_markdown(e);if(a.length===0)return null;for(let[l,d]of a){let c=i.createElement("w:r");if(t&&t._element){let f=$(t._element,"w:rPr");if(f){let h=f.cloneNode(true),_=["w:vanish","w:strike","w:dstrike","w:i","w:iCs"];s&&_.push("w:b","w:bCs");for(let m of _){let w=$(h,m);w&&h.removeChild(w);}(Array.from(h.childNodes).some(m=>m.nodeType===1)||h.attributes&&h.attributes.length>0)&&c.appendChild(h);}}this._apply_run_props(c,d,false);let u=i.createElement("w:t");this._set_text_content(u,l),c.appendChild(u),o.appendChild(c);}return o}_parse_markdown_style(e){let t=e.trimStart();if(t.startsWith("#")){let i=0,s=t;for(;s.startsWith("#");)i++,s=s.substring(1);if(s.startsWith(" "))return [s.trim(),`Heading ${i}`]}if(t.startsWith("* ")||t.startsWith("- "))return [t.substring(2).trim(),"List Paragraph"];let r=t.match(/^1\.\s+/);return r?[t.substring(r[0].length).trim(),"List Number"]:[e,null]}_edit_declares_emphasis(e){for(let t of [e?.target_text,e?.new_text]){if(!t||!t.includes("**")&&!t.includes("_"))continue;if(this._parse_inline_markdown(t).some(([,i])=>i&&Object.keys(i).length>0))return true}return false}_is_escaped(e,t){let r=0,i=t-1;for(;i>=0&&e[i]==="\\";)r++,i--;return r%2===1}_unescape_markdown(e){return e.replace(/\\([\\*_])/g,"$1")}_is_word_char(e){return /[\p{L}\p{N}_]/u.test(e)}_is_space(e){return e==="\uFEFF"?false:/^\s$/u.test(e)||e==="\x85"||e>=""&&e<=""}_prev_char(e,t){if(t<=0)return "";let r=e.charCodeAt(t-1);if(r>=56320&&r<=57343&&t-2>=0){let i=e.charCodeAt(t-2);if(i>=55296&&i<=56319)return e.slice(t-2,t)}return e[t-1]}_next_char(e,t){if(t>=e.length)return "";let r=e.charCodeAt(t);if(r>=55296&&r<=56319&&t+1<e.length){let i=e.charCodeAt(t+1);if(i>=56320&&i<=57343)return e.slice(t,t+2)}return e[t]}_find_next_emphasis(e){let t=e.length,r=0;for(;r<t;){if(r+1<t&&e.substring(r,r+2)==="**"&&!this._is_escaped(e,r)&&r+2<t&&e[r+2]!=="*"&&!this._is_space(this._next_char(e,r+2))){let i=r+2;for(;i+1<t;)if(e.substring(i,i+2)==="**"&&!this._is_escaped(e,i)){if(!this._is_space(this._prev_char(e,i))){let s=e.substring(r+2,i);if(s&&!/^[*]+$/.test(s))return [r,i+2,"bold",s]}i+=2;}else i++;}if(e[r]==="_"&&!this._is_escaped(e,r)){let i=r>0&&e[r-1]==="_",s=r+1<t&&e[r+1]==="_",o=r>0&&this._is_word_char(this._prev_char(e,r)),a=r+1===t||this._is_space(this._next_char(e,r+1));if(!i&&!s&&!o&&!a){let l=r+1;for(;l<t;){if(e[l]==="_"&&!this._is_escaped(e,l)){let d=this._is_space(this._prev_char(e,l)),c=e[l-1]==="_",u=l+1<t&&e[l+1]==="_",f=l+1<t&&this._is_word_char(this._next_char(e,l+1));if(!d&&!c&&!u&&!f){let h=e.substring(r+1,l);if(h&&!/^[_]+$/.test(h))return [r,l+1,"italic",h]}}l++;}}}r++;}return null}_parse_inline_markdown(e,t={}){if(!e)return [];let r=this._find_next_emphasis(e);if(!r)return [[this._unescape_markdown(e),t]];let[i,s,o,a]=r,l=e.substring(0,i),d=e.substring(s),c=[];l&&c.push([this._unescape_markdown(l),t]);let u={...t};return o==="bold"?u.bold=true:u.italic=true,c.push(...this._parse_inline_markdown(a,u)),c.push(...this._parse_inline_markdown(d,t)),c}static CT_RPR_ORDER=["w:ins","w:del","w:moveFrom","w:moveTo","w:rStyle","w:rFonts","w:b","w:bCs","w:i","w:iCs","w:caps","w:smallCaps","w:strike","w:dstrike","w:outline","w:shadow","w:emboss","w:imprint","w:noProof","w:snapToGrid","w:vanish","w:webHidden","w:color","w:spacing","w:w","w:kern","w:position","w:sz","w:szCs","w:highlight","w:u","w:effect","w:bdr","w:shd","w:fitText","w:vertAlign","w:rtl","w:cs","w:em","w:lang","w:eastAsianLayout","w:specVanish","w:oMath","w:rPrChange"];_insert_rpr_child(e,t){let r=G.CT_RPR_ORDER.indexOf(t.tagName);if(r===-1){e.appendChild(t);return}for(let i of Array.from(e.childNodes)){if(i.nodeType!==1)continue;let s=G.CT_RPR_ORDER.indexOf(i.tagName);if(s>r||s===-1){e.insertBefore(t,i);return}}e.appendChild(t);}_apply_run_props(e,t,r=false){if(!t){if(!r)return;t={};}let i=$(e,"w:rPr"),s=t.bold||t.italic||t.underline||t.strike||t.color;if(!i&&(s||r)&&(i=e.ownerDocument.createElement("w:rPr"),e.insertBefore(i,e.firstChild)),i){let o=e.ownerDocument;if(t.bold){let l=$(i,"w:b");l||(l=o.createElement("w:b"),this._insert_rpr_child(i,l)),l.setAttribute("w:val","1");}else if(r)for(let l of ["w:b","w:bCs"]){let d=$(i,l);d&&i.removeChild(d);}if(t.italic){let l=$(i,"w:i");l||(l=o.createElement("w:i"),this._insert_rpr_child(i,l)),l.setAttribute("w:val","1");}else if(r)for(let l of ["w:i","w:iCs"]){let d=$(i,l);d&&i.removeChild(d);}if(t.strike){let l=$(i,"w:strike");l||(l=o.createElement("w:strike"),this._insert_rpr_child(i,l));}if(t.underline){let l=$(i,"w:u");l||(l=o.createElement("w:u"),this._insert_rpr_child(i,l)),l.setAttribute("w:val",typeof t.underline=="string"?t.underline:"single");}if(t.color){let l=$(i,"w:color");l||(l=o.createElement("w:color"),this._insert_rpr_child(i,l)),l.setAttribute("w:val",String(t.color).replace(/^#/,""));}!Array.from(i.childNodes).some(l=>l.nodeType===1)&&(!i.attributes||i.attributes.length===0)&&e.removeChild(i);}}_set_paragraph_style(e,t,r=null){let i=e.ownerDocument,s=$(e,"w:pPr");s&&e.removeChild(s);let o=i.createElement("w:pPr"),a=i.createElement("w:pStyle"),l=t.replace(/\s+/g,"");if(a.setAttribute("w:val",l),o.appendChild(a),l==="ListParagraph"){let d=this._ensure_bullet_num_id();if(d){let c=i.createElement("w:numPr"),u=i.createElement("w:ilvl");u.setAttribute("w:val","0");let f=i.createElement("w:numId");f.setAttribute("w:val",d),c.appendChild(u),c.appendChild(f),o.appendChild(c);}}if(r!==null){let d=this._create_track_change_tag("w:pPrChange","",r),c=s?s.cloneNode(true):i.createElement("w:pPr"),u=$(c,"w:pPrChange");u&&c.removeChild(u),d.appendChild(c),o.appendChild(d);}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,t="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(T=>String(T.partname).replace(/^\//,"")==="word/numbering.xml");if(!i){let T=`<w:numbering xmlns:w="${t}"><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",G._NUMBERING_CT,T),this.doc.relateTo(i,G._NUMBERING_RT);}catch{return null}return delete e._adeu_numbering_cache,"1"}let s=i._element,o=R(s,"w:abstractNum"),a=R(s,"w:num"),l=null;for(let T of o){let I=T.getAttribute("w:abstractNumId");if(I!==null){for(let D of R(T,"w:lvl")){if((D.getAttribute("w:ilvl")||"0")!=="0")continue;let F=$(D,"w:numFmt");F&&F.getAttribute("w:val")==="bullet"&&(l=I);break}if(l!==null)break}}let d=0;for(let T of a){let I=parseInt(T.getAttribute("w:numId")||"0",10);!isNaN(I)&&I>d&&(d=I);}let c=s.ownerDocument;if(l!==null){for(let D of a){let F=$(D,"w:abstractNumId");if(F&&F.getAttribute("w:val")===l){let M=D.getAttribute("w:numId");if(M&&M!=="0")return M}}let T=c.createElement("w:num");T.setAttribute("w:numId",String(d+1));let I=c.createElement("w:abstractNumId");return I.setAttribute("w:val",l),T.appendChild(I),s.appendChild(T),delete e._adeu_numbering_cache,String(d+1)}let u=-1;for(let T of o){let I=parseInt(T.getAttribute("w:abstractNumId")||"-1",10);!isNaN(I)&&I>u&&(u=I);}let f=c.createElement("w:abstractNum");f.setAttribute("w:abstractNumId",String(u+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 y=c.createElement("w:lvlJc");y.setAttribute("w:val","left"),_.appendChild(y);let b=c.createElement("w:pPr"),v=c.createElement("w:ind");v.setAttribute("w:left","720"),v.setAttribute("w:hanging","360"),b.appendChild(v),_.appendChild(b);let N=c.createElement("w:rPr"),k=c.createElement("w:rFonts");k.setAttribute("w:ascii","Symbol"),k.setAttribute("w:hAnsi","Symbol"),k.setAttribute("w:hint","default"),N.appendChild(k),_.appendChild(N),f.appendChild(_);let x=a.find(T=>T.parentNode===s)||null;x?s.insertBefore(f,x):s.appendChild(f);let P=c.createElement("w:num");P.setAttribute("w:numId",String(d+1));let E=c.createElement("w:abstractNumId");return E.setAttribute("w:val",String(u+1)),P.appendChild(E),s.appendChild(P),delete e._adeu_numbering_cache,String(d+1)}_anchor_reply_comment(e,t){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 s=i[0],o=r.createElement("w:commentRangeStart");o.setAttribute("w:id",t),ut(o,s);let a=R(this.doc.element,"w:commentRangeEnd").filter(m=>m.getAttribute("w:id")===e);if(a.length===0)return;let l=a[0],d=R(this.doc.element,"w:commentReference").filter(m=>m.getAttribute("w:id")===e),c=l;if(d.length>0){let m=d[0];m.parentNode&&m.parentNode.tagName==="w:r"&&(c=m.parentNode);}let u=r.createElement("w:commentRangeEnd");u.setAttribute("w:id",t),ut(u,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",t),f.appendChild(p),ut(f,u);}_clean_wrapping_comments(e){let t=0,r=e;for(;;){let c=Ce(r);if(c&&(c.tagName==="w:ins"||c.tagName==="w:del"))r=c;else break}let i=e;for(;;){let c=le(i);if(c&&(c.tagName==="w:ins"||c.tagName==="w:del"))i=c;else break}let s=[],o=Ce(r);for(;o;)if(o.tagName==="w:commentRangeStart")s.push(o),o=Ce(o);else if(o.tagName==="w:rPr"||o.tagName==="w:pPr")o=Ce(o);else break;let a=[],l=le(i);for(;l;)if(l.tagName==="w:commentRangeEnd")a.push(l),l=le(l);else if(l.tagName==="w:r"&&R(l,"w:commentReference").length>0)a.push(l),l=le(l);else if(l.tagName==="w:commentReference")a.push(l),l=le(l);else break;let d=new Set;for(let c of a)if(c.tagName==="w:commentRangeEnd"){let u=c.getAttribute("w:id");u&&d.add(u);}else {let u=R(c,"w:commentReference")[0];if(!u&&c.tagName==="w:commentReference"&&(u=c),u){let f=u.getAttribute("w:id");f&&d.add(f);}}for(let c of s){let u=c.getAttribute("w:id");if(u&&d.has(u)){this.comments_manager.deleteComment(u),t++,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===u&&f.parentNode&&f.parentNode.removeChild(f);}}}return t}_delete_comments_in_element(e){let t=0,r=R(e,"w:commentReference");for(let i of r){let s=i.getAttribute("w:id");if(s){this.comments_manager.deleteComment(s),t++;for(let o of ["w:commentRangeStart","w:commentRangeEnd"]){let a=R(this.doc.element,o);for(let l of a)l.getAttribute("w:id")===s&&l.parentNode&&l.parentNode.removeChild(l);}}}return t}_control_gate_context(e,t,r){let i=typeof e?.controls_intersecting=="function"?e.controls_intersecting(t,r):[],s=typeof e?.controls_at=="function"?e.controls_at(t):[],o=typeof e?.controls_at=="function"?e.controls_at(Math.max(t+r-1,t)):[];return [i,s,o]}_deletes_entire_control(e,t,r,i,s){if(s.trim()!=="")return false;let a=(e?.control_ranges??[]).find(f=>f[2]===t);if(!a)return false;let[l,d]=a,c=r<=l&&r+i>=d,u=r<l||r+i>d;return c&&u}_check_control_gates(e,t,r,i,s,o="",a="",l=null,d=false){let c=this.gate_overrides,u=Array.from(r?._sdt_infos?.values()??[]),[f,h,_]=this._control_gate_context(r,i,s);l!==null&&(f=l);let p=!!t.comment&&(t.new_text||"")===(t.target_text||""),m=Ic(e,this.protection,{controls:f,isCommentOnly:p,overrides:c});if(m||!p&&(m=Dc(e,this.protection,c),m)||(m=Rc(e,t.target_text||"",u),m))return m;if(f.length===0)return null;if(!d&&(m=jc(e,f),m)||(m=Mc(e,f,t.target_text||"",t.new_text||""),m)||(m=Tc(e,f,c),m)||(m=$c(e,f,c),m))return m;for(let y of f)if(this._deletes_entire_control(r,y,i,s,a)&&(m=Sc(e,[y],true,c),m))return m;if(o.includes(`
|
|
125
136
|
|
|
126
137
|
`)&&!a.includes(`
|
|
127
138
|
|
|
128
|
-
`)){let y=
|
|
129
|
-
"${
|
|
139
|
+
`)){let y=xi(f,h,_);if(m=Bc(e,y),m)return m}let w=xi(f,h,_);if(w.length>0&&(t._warning=Fc(w)),c.ignore_control_locks)for(let y of f)(y.contentLocked||y.cls==="group")&&(this._overridden_controls.includes(y)||this._overridden_controls.push(y));return null}_apply_gate_refusal(e,t,r,i=false){let s=this.gate_overrides;if(vn(this.protection)&&!s.ignore_document_protection&&this.protection.edit==="readOnly")return "document is read-only protected";let o=typeof e?.controls_intersecting=="function"?e.controls_intersecting(t,r):[];if(o.length===0)return null;let a=o.find(d=>d.bound);if(a&&!i)return `${ye(a)} is data-bound`;if(s.ignore_control_locks)return null;let l=o.find(d=>d.contentLocked);return l?`${ye(l)} is content-locked`:null}_resolve_structural_table_edit(e){let t=this.mapper.drop_virtual_only_matches(this.mapper.find_all_match_indices(e.target_text)),r=this.mapper;if(t.length===0&&(this.clean_mapper||(this.clean_mapper=new Te(this.doc,true)),t=this.clean_mapper.drop_virtual_only_matches(this.clean_mapper.find_all_match_indices(e.target_text)),r=this.clean_mapper),t.length===0){let d=(e.target_text||"").trim().substring(0,40);return {sub_edits:[],err_msg:`- Failed to apply structural edit targeting: '${d}...'`}}let i=e.match_mode||"strict",s=[],o=new Set;for(let d of t){let c=d[0],[u,f]=r.get_insertion_anchor(c,false),h=null;u?h=u._element:f&&(h=f._element);let _=h;for(;_&&_.tagName!=="w:tr";)_=_.parentNode;_&&!o.has(_)&&(o.add(_),s.push(d));}if(s.length===0){let d=(e.target_text||"").trim().substring(0,40);return {sub_edits:[],err_msg:`- Failed to locate row target: '${d}...'`}}let a=s;(i==="strict"||i==="first")&&(a=s.slice(0,1));let l=[];if(i==="all"||a.length>1)for(let d of a){let c={...e,_resolved_start_idx:d[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,t){let r=[],i;try{i=this._resolve_set_field_targets(e);}catch(o){return [`- Edit ${t} Failed: ${o?.message??o}`]}let s=null;for(let o of i){let a=this._sdt_info_for_ordinal(o.ordinal);if(s=Ii(a?a.cls:o.cls_word,o.ordinal),!s&&a&&(s=Oi(a,o.ordinal,e.value)),s)return [`- Edit ${t} Failed: ${s}`]}for(let o of i){let a=this._cc_content_range(o.ordinal),l=this._sdt_info_for_ordinal(o.ordinal);if(!a){if(!l||l.cls!=="checkbox")continue;let _=Di(e.value),p=l.checked?Ct[1]:Ct[0],m=_?Ct[1]:Ct[0],w=this._check_control_gates(t,{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[d,c]=a,u=this.mapper.full_text.slice(d,c),f={type:"modify",target_text:u,new_text:e.value,comment:e.comment??null};f._parent_edit_ref=e;let h=this._check_control_gates(t,f,this.mapper,d,c-d,u,e.value,l?[l]:null,true);if(h){r.push(h);break}}return r}validate_edits(e,t=0){let r=[];this.mapper.full_text||this.mapper._build_map(),r.push(...cu(e,t));for(let i=0;i<e.length;i++){let s=e[i];if(typeof s!="object"||s===null){r.push(`- Edit ${i+1+t} Failed: Invalid change format. Expected a JSON object, but received a primitive ${typeof s}. Do not pass raw strings.`);continue}if(s.type==="set_field"){r.push(...this._validate_set_field_edit(s,i+1+t));continue}if(s._match_start_index!==void 0&&s._match_start_index!==null||s._resolved_start_idx!==void 0&&s._resolved_start_idx!==null)continue;if(s.target_text===void 0||s.target_text===null||!String(s.target_text).trim()){s.type==="insert_row"?r.push(`- Edit ${i+1+t} Failed: insert_row requires target_text (text inside an existing row to anchor on) and cells (the new row's cell values).`):s.type==="delete_row"?r.push(`- Edit ${i+1+t} Failed: delete_row requires target_text (text inside the row to delete).`):r.push(`- Edit ${i+1+t} 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(s.type==="modify"&&(s.new_text===void 0||s.new_text===null))if(s.comment&&String(s.comment).trim())s.new_text=s.target_text;else {r.push(`- Edit ${i+1+t} 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=s.regex||false,a=s.match_mode||"strict";if(o)try{an(s.target_text);}catch(h){r.push(`- Edit ${i+1+t} 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(s.target_text,o)),d=this.mapper.full_text,c=this.mapper;l.length===0&&(this.clean_mapper||(this.clean_mapper=new Te(this.doc,true)),l=this.clean_mapper.drop_virtual_only_matches(this.clean_mapper.find_all_match_indices(s.target_text,o)),l.length>0&&(d=this.clean_mapper.full_text,c=this.clean_mapper)),d===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 u=false,f=new Set;if(l.length===0){this.original_mapper||(this.original_mapper=new Te(this.doc,false,true));let h=this.original_mapper.drop_virtual_only_matches(this.original_mapper.find_all_match_indices(s.target_text,o));if(h.length>0){u=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 y=w.run._element;for(;y;){if(y.nodeType===1&&y.tagName==="w:del"){let b=y.getAttribute("w:author");b&&f.add(b);break}y=y.parentNode;}}}}}if(l.length===0)if(u){let h=f.size>0?`by ${Array.from(f).sort().join(", ")}`:"by an existing revision";r.push(`- Edit ${i+1+t} 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(s.target_text,o);r.push(`- Edit ${i+1+t} Failed: Target text not found in document:
|
|
140
|
+
"${ge(s.target_text,qn)}"${h}`);}else if(l.length>1&&a==="strict")if(s.target_text.includes("|"))l=l.slice(0,1);else {let h=l.map(([_,p])=>[_,_+p]);r.push(Kl(i+1+t,s.target_text,d,h));}if(l.length===1){let[h,_]=l[0],p=d.substring(h,h+_),m=G._reinject_anchor_markers(c,h,_,s.target_text,s.new_text||"");if(m===null){r.push(`- Edit ${i+1+t} Failed: target_text runs across a hyperlink or cross-reference whose visible text the replacement changes or removes. Keep that text unchanged and edit only around it, or copy the marker exactly as read_docx shows it ([text](url) for a hyperlink) into both target_text and new_text.`);continue}let w=m,[y,b]=ft(p,w),v=p.length-b,N=p.substring(y,v),k=w.substring(y,w.length-b),P=c.part_ranges.filter(D=>D[1]>D[0]).length>1?Array.from(new Set(c.spans.filter(D=>D.run!==null&&D.end>h&&D.start<h+_).map(D=>D.part_index))).sort((D,F)=>D-F):[];if(P.length>1){let D=P.map(F=>c.part_kind_of(F)||"?").join(" \u2192 ");r.push(`- Edit ${i+1+t} Failed: target_text spans a structural document-part boundary (${D}). 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).`);}else if(P.length===1){let D=this._header_block_error(i+1+t,c,P[0],N,k);D&&r.push(D);}let E=h+y,T=h+_-b,I=this._check_control_gates(i+1+t,s,c,E,Math.max(T-E,0),N,k);if(I&&r.push(I),T>E&&c.spans.filter(F=>F.end>E&&F.start<T&&(F.run!==null||F.text.trim()!=="")).some(F=>F.is_image_marker)&&r.push(`- Edit ${i+1+t} Failed: the target overlaps a read-only image marker (). Images cannot be edited or removed via text replacement \u2014 target the text around the image instead.`),s.comment&&(s.new_text||"")===(s.target_text||"")){let D=c.part_kind_at(h);D!==null&&D!=="body"&&r.push(`- Edit ${i+1+t} Failed: comments cannot be anchored inside a ${D} part \u2014 Word only supports comments in the main document body. Comment on the related body text instead.`);}if(G._introduces_table_row_text(c,h,_,N,k)&&r.push(`- Edit ${i+1+t} 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": ["...", "..."]}).`),N.includes(`
|
|
130
141
|
|
|
131
142
|
`)&&!(p.split(`
|
|
132
143
|
|
|
@@ -134,61 +145,63 @@ ${s}`);}let i=true;for(let s of Ue(n))if(s.constructor.name==="FootnoteItem"){le
|
|
|
134
145
|
|
|
135
146
|
`).length))if(k.includes(`
|
|
136
147
|
|
|
137
|
-
`)){let
|
|
148
|
+
`)){let F=p.split(`
|
|
138
149
|
|
|
139
|
-
`);
|
|
150
|
+
`);F.length>=2&&F[0].trim()!==""&&F[F.length-1].trim()!==""&&r.push(`- Edit ${i+1+t} 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 F=N.split(`
|
|
140
151
|
|
|
141
|
-
`);
|
|
152
|
+
`);F.length>=2&&F[0].trim()!==""&&F[F.length-1].trim()!==""&&r.push(`- Edit ${i+1+t} 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,y=false;for(let b of p){if(b.run===null)continue;let v=false;if(b.ins_id){let N=R(this.doc.element,"w:ins").filter(k=>k.getAttribute("w:id")===b.ins_id);if(N.length>0){let k=N[0].getAttribute("w:author");k&&k!==this.author&&(m.has(k)||m.set(k,new Set),m.get(k).add(b.ins_id),v=true);}}v||(y=true);}for(let b of p)if(b.comment_ids)for(let v of b.comment_ids){let N=this.mapper.comments_map[v];N&&N.author&&N.author!==this.author&&(w.has(N.author)||w.set(N.author,new Set),w.get(N.author).add(`Com:${v}`));}if(m.size>0){let b=!y;if(!((a==="strict"||a==="first")&&b)){let v=Array.from(m.keys()).sort(),N=v[0],x=Array.from(m.get(N)).sort((C,S)=>{let A=/^\d+$/.test(C)?parseInt(C,10):0,O=/^\d+$/.test(S)?parseInt(S,10):0;return A!==O?A-O:C.localeCompare(S)}),P=x.length>0?`Chg:${x[0]}`:null,E=x.slice(0,2).map(C=>`Chg:${C}`).join(", "),T=E?` (e.g. ${E})`:"";v.length>1&&(T+=` (+${v.length-1} more)`);let I=P?`{"type": "accept", "target_id": "${P}"}`:"",D=a==="all"&&b?'or use match_mode="strict" or "first", or scope your edit outside of it.':"or scope your edit outside of it.",F=`- Edit ${i+1+t} Failed: Modification targets an active insertion from another author (`,M=`${T}). Accept first with ${I} ${D}`,B=Mi-F.length-M.length,j=F+ni(N,B)+M;r.push(ni(j,Mi));continue}}if(w.size>0&&a==="all"){let b=[],v=Array.from(w.keys()).sort();for(let N of v){let P=Array.from(w.get(N)).sort((E,T)=>{let I=E.split(":").pop()||"",D=T.split(":").pop()||"",F=/^\d+$/.test(I)?parseInt(I,10):0,M=/^\d+$/.test(D)?parseInt(D,10):0;return F!==M?F-M:E.localeCompare(T)}).join(", ");b.push(P?`${N} (e.g. ${P})`:N);}r.push(`- Edit ${i+1+t} 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((s.type==="insert_row"||s.type==="delete_row")&&l.length>0){let[h,_]=l[0],p=G._column_count_at(c,h,_);p===null?r.push(`- Edit ${i+1+t} Failed: ${s.type} target text was found, but it is not inside a table row. Anchor the operation on text that appears within the table.`):s.type==="insert_row"&&Array.isArray(s.cells)&&s.cells.length>p&&r.push(`- Edit ${i+1+t} Failed: insert_row provides ${s.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,t,r,i,s){if(!s.includes(`
|
|
142
153
|
`)||!s.includes(" | "))return false;let o=s.split(`
|
|
143
|
-
`).filter(
|
|
144
|
-
`).filter(
|
|
145
|
-
`)]));}let w=[..._,...m];if(w.length>0)throw o.unshift(...
|
|
146
|
-
`);if(o.push([W,H]),A>0&&!r){let L=Ei(A);z=z.map(X=>X+L);}D.push(...z),$&&typeof $=="object"&&($._error_msg=H);}else if(this.apply_edits([$],I),$._applied_status&&!$._any_sub_failure)A++,this.mapper=new Ce(this.doc),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.clean_mapper=null;else {let H=$._error_msg||`- Edit ${W+1} Failed: Failed to apply edit.`;if($&&typeof $=="object"&&($._error_msg=H),o.push([W,H]),A>0&&!r&&(H+=Ei(A)),D.push(H),!r)break;$._applied_status&&(this.mapper=new Ce(this.doc),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.clean_mapper=null);}}if(!r&&D.length>0)throw new Gt(D,o)}catch(D){throw this._restore_batch_snapshot(k,C),this._verify_rollback(x),D}j=h.filter(D=>D._applied_status&&!D._any_sub_failure).length,F=h.length-j;for(let[D,A]of h.entries()){let $=A._applied_status||false,W=A._error_msg||null,z=null,H=null,L=A._warning||null;if($){let X=this._build_edit_context_previews(A);z=X[0],H=X[1];}else L=L||this._check_punctuation_warning(A.target_text||"");M.push({index:l[D].i,status:$?"applied":"failed",type:A.type||"modify",target_text:pe(A.target_text||"",jn),new_text:pe(V._report_new_text(A),jn),comment:A.comment??null,warning:L,error:W,critic_markup:z,clean_text:H,pages:A._pages||[],heading_path:A._heading_path||"",field:A._field||"",occurrences_modified:A._occurrences_modified||0,match_mode:A.match_mode||"strict"});}}}if(j>0)try{this._warn_stranded_comment_anchors(C);}catch{}return {status:r&&o.length>0?"partial":"ok",author_impersonation_warning:s,overrides_note:Ac(this.gate_overrides,this._overridden_controls),failed:o.map(([T,O])=>({index:T,reason:O,error:O})),actions_applied:y,actions_skipped:b,actions_already_resolved:v,edits_applied:j,edits_skipped:F,occurrences_modified:M.reduce((T,O)=>T+(O.occurrences_modified||0),0),skipped_details:this.skipped_details,edits:M,engine:"node",version:Fl}}static _flag_surviving_python_backreference(e,t){let r=/\\(\d+)|\\g<(\d+)>/.exec(e.new_text||"");if(!r||!t.includes(r[0]))return;let i=0;try{let o=new RegExp(`(?:${e.target_text})|`).exec("");i=o?o.length-1:0;}catch{return}let s=parseInt(r[1]??r[2],10);s>0&&s<=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 $${s} (\\N and \\g<N> are Python syntax). If you meant literal text, ignore this warning.`);}static _ids_needed(e){let t=e._internal_op;return t==null&&(!e.target_text&&e.new_text?t="INSERTION":e.target_text&&!e.new_text?t="DELETION":t="MODIFICATION"),t==="STYLE_ONLY"?[false,false]:(t==="STYLE_AND_TEXT"&&(e.target_text&&e.new_text?t="MODIFICATION":!e.target_text&&e.new_text?t="INSERTION":e.target_text&&!e.new_text?t="DELETION":t="COMMENT_ONLY"),[t==="DELETION"||t==="MODIFICATION",t==="INSERTION"||t==="MODIFICATION"])}apply_edits(e,t=[]){let i=0;if(!t||t.length===0){let[l]=ut(this.mapper.full_text);t=dt(l,"").body_page_offsets;}let s=[];for(let l of e){if(typeof l!="object"||l===null){i++;continue}l._applied_status=false,l._error_msg=null,l._any_sub_failure=false,l._minted_change_ids=[],l._minted_comment_ids=[],l._reserved_del_id=null,l._reserved_ins_id=null,l._reserved_row_id=null;}for(let l of e)if(!(typeof l!="object"||l===null)){if(l.type==="set_field"){this._resolve_set_field(l,s),l._error_msg&&(i+=1);continue}if(l._resolved_start_idx!==void 0&&l._resolved_start_idx!==null||l._match_start_index!==void 0&&l._match_start_index!==null){if((l._resolved_start_idx===void 0||l._resolved_start_idx===null)&&(l._resolved_start_idx=l._match_start_index),l.type==="modify"&&!l._internal_op&&l.target_text&&l.new_text&&([l.target_text,l.new_text]=Ci(l.target_text,l.new_text)),l._active_mapper_ref||(this.clean_mapper||(this.clean_mapper=new Ce(this.doc,true)),l._active_mapper_ref=this.clean_mapper),l.type==="modify"&&!l.target_text&&l.new_text&&!l._insert_host_el){let d=this._empty_control_fill_host(l._active_mapper_ref,l._resolved_start_idx??0);d&&(l._insert_host_el=d);}s.push([l,l.new_text||null]);}else if(l.type==="insert_row"||l.type==="delete_row"){let{sub_edits:d,err_msg:f}=this._resolve_structural_table_edit(l);f?(i++,l._applied_status=false,this.skipped_details.push(f),l._error_msg=f):s.push(...d);}else {let d;try{d=this._pre_resolve_heuristic_edit(l);}catch(f){if(!(f instanceof Fe))throw f;i++,l._applied_status=false;let h=`- Failed to apply edit targeting: '${(l.target_text||"").substring(0,40)}...' (${f.message})`;this.skipped_details.push(h),l._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=l,(l._resolved_start_idx===void 0||l._resolved_start_idx===null)&&(l._resolved_start_idx=f._resolved_start_idx),l._resolved_proxy_edit||(l._resolved_proxy_edit=f),s.push([f,f.new_text]);else d._resolved_start_idx=d._match_start_index,d._parent_edit_ref=l,l._resolved_start_idx=d._resolved_start_idx,l._resolved_proxy_edit=d,s.push([d,d.new_text]);else {i++,l._applied_status=false;let _=`- Failed to apply edit targeting: '${(l.target_text||"insertion").trim().substring(0,40)}...'`;this.skipped_details.push(_),l._error_msg=_;}}}s.sort((l,d)=>(d[0]._resolved_start_idx||0)-(l[0]._resolved_start_idx||0));{let l=[...s].sort((d,f)=>(d[0]._resolved_start_idx||0)-(f[0]._resolved_start_idx||0));for(let[d]of l){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[l]of s)this._capture_preview_context(l),l._parent_edit_ref&&this._capture_parent_preview_context(l._parent_edit_ref);let o=[],a=new Set;for(let[l,d]of s){let f=l._resolved_start_idx||0,h=l.type==="insert_row"?f:f+(l.target_text?l.target_text.length:0);if(o.some(([y,b])=>f<b&&h>y)){i++;let v=`- Skipped overlapping edit targeting: '${(l.target_text||"insertion").trim().substring(0,40)}...'`;this.skipped_details.push(v),l._applied_status=false,l._error_msg=v,l._any_sub_failure=true;let N=l._parent_edit_ref;N&&(N._applied_status=false,N._error_msg=v,N._any_sub_failure=true);continue}let p=false,m=this.current_id,w=this.comments_manager.nextId;if(l.type==="modify"?p=this._apply_single_edit_indexed(l,d,false):(l.type==="insert_row"||l.type==="delete_row")&&(p=this._apply_table_edit(l,false)),p&&l._unwrap_sdt_after&&fu(l._unwrap_sdt_after),p){let y=l._parent_edit_ref||l;Array.isArray(y._minted_change_ids)||(y._minted_change_ids=[]);for(let b=m+1;b<=this.current_id;b++)y._minted_change_ids.push(String(b));Array.isArray(y._minted_comment_ids)||(y._minted_comment_ids=[]);for(let b=w;b<this.comments_manager.nextId;b++)y._minted_comment_ids.push(String(b));}if(p){let y=l._split_group_id,b=y==null||!a.has(y);b&&y!==void 0&&y!==null&&a.add(y),o.push([f,h]),l._applied_status=true;let v=l._parent_edit_ref;if(v){v._applied_status=true,b&&(v._occurrences_modified=(v._occurrences_modified||0)+1);let[N,k]=this._get_heading_path_and_page(f,this.mapper.full_text,t),x=v._pages||[];x.includes(k)||x.unshift(k),v._pages=x,v._heading_path=N,v._field=this._field_label_at(f);}else {b&&(l._occurrences_modified=(l._occurrences_modified||0)+1);let[N,k]=this._get_heading_path_and_page(f,this.mapper.full_text,t),x=l._pages||[];x.includes(k)||x.unshift(k),l._pages=x,l._heading_path=N,l._field=this._field_label_at(f);}}else {i++;let v=`- Failed to apply edit targeting: '${(l.target_text||"insertion").trim().substring(0,40)}...'`;this.skipped_details.push(v),l._applied_status=false,l._error_msg=v,l._any_sub_failure=true;let N=l._parent_edit_ref;N&&(N._any_sub_failure=true,N._applied_status||(N._applied_status=false,N._error_msg=v));}}let c=0,u=0;for(let l of e){if(typeof l!="object"||l===null){u++;continue}l._applied_status&&!l._any_sub_failure?c++:u++;}return [c,u]}_paragraph_has_visible_content(e){for(let t of ["w:t","w:tab","w:br"]){let r=R(e,t);for(let i of r){let s=false,o=i.parentNode;for(;o&&o!==e.parentNode;){if(o.tagName==="w:del"){s=true;break}o=o.parentNode;}if(!s){if(t==="w:t"&&!i.textContent)continue;return true}}}return false}_is_last_paragraph_in_cell(e){let t=e.parentNode;for(;t&&t.tagName!=="w:tc";)t=t.parentNode;return t?R(t,"w:p").length<=1:false}_get_paired_nodes(e){let t=[],r=e.getAttribute("w:author"),i=new Set(["w:commentRangeStart","w:commentRangeEnd","w:commentReference","w:rPr","w:pPr"]),s=new Set,o=g(d=>{let f=d.getAttribute("w:id");f&&s.add(f);},"add_id");o(e);let a=g(d=>{let f=d;for(;f&&f.tagName!=="w:p";)f=f.parentNode;return f},"paragraph_of"),c=g(d=>{let f=S(d,"w:pPr"),h=f?S(f,"w:rPr"):null;return h?S(h,"w:ins"):null},"mark_of"),u=g(d=>{let f=c(d);if(!f||f.getAttribute("w:author")!==r)return false;let h=f.getAttribute("w:id");return h!==null&&s.has(h)},"boundary_is_ours"),l=g((d,f)=>{let h=a(d),_=f==="next"?d.nextSibling:d.previousSibling;for(;;){if(!_){if(!h)break;if(f==="next"){let m=Te(h);for(;m&&m.tagName!=="w:p";)m=Te(m);if(!m||!u(m))break;h=m,_=m.firstChild;}else {if(!u(h))break;let m=De(h);for(;m&&m.tagName!=="w:p";)m=De(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){t.push(p),o(p),_=f==="next"?_.nextSibling:_.previousSibling;continue}break}},"walk");return l(e,"next"),l(e,"prev"),t}_resolution_group_ids(e,t=null){let r=[...this._revisionsByTagIn("w:ins",t),...this._revisionsByTagIn("w:del",t)].filter(s=>s.id===e).map(s=>s.el),i=new Set;if(r.length===0)return this._revisionsByTagIn("w:pPrChange",t).some(o=>o.id===e)&&i.add(e),i;i.add(e);for(let s of r)for(let o of this._get_paired_nodes(s)){let a=o.getAttribute("w:id");a&&i.add(a);}return i}validate_action_pairing(e,t){let r=[],i=g(o=>t?t[o]:o,"gidx"),s=new Map;for(let o=0;o<e.length;o++){let a=e[o];if(a.type!=="accept"&&a.type!=="reject")continue;let c=String(a.target_id??"");if(c.startsWith("Com:"))continue;let u=c.startsWith("Chg:")?c.slice(4):c,{part:l,error:d}=this._action_part_filter(a);if(d)continue;let f=l;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=s.get(_(m));if(w!==void 0&&w[1]!==a.type){p=w;break}}if(p!==null){let[m,w,y]=p;r.push(`- Action ${i(o)+1} Failed: conflicting actions on one replacement \u2014 Action ${i(m)+1} applies '${w}' to Chg:${y}, 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)s.has(_(m))||s.set(_(m),[o,a.type,u]);}return r}_buildRevisionIndex(e){let t=new Map;for(let i of Jt)t.set(i,[]);let r=[];for(let[i,s]of e){let o=i.ownerDocument;r.push({el:i,doc:o,inc:typeof o?._inc=="number"?o._inc:null});let a=[i],c=[0],u=[],l=[];for(;a.length;){let d=a.length-1,f=a[d].childNodes;if(!f||c[d]>=f.length){for(a.pop(),c.pop();l.length&&l[l.length-1]>a.length;)l.pop(),u.pop();continue}let h=f[c[d]++];if(h.nodeType!==1)continue;let _=t.get(h.tagName),p=null;_&&(p={el:h,id:h.getAttribute("w:id"),part:s,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),c.push(0),p&&m&&(u.push(p),l.push(a.length));}}return {roots:r,byTag:t}}_getRevisionIndex(){let e=this._story_roots(),t=this._revisionIndex;if(t!==null&&t.roots.length===e.length&&t.roots.every((s,o)=>{let a=e[o][0],c=a.ownerDocument;return s.el===a&&s.doc===c&&s.inc!==null&&typeof c?._inc=="number"&&s.inc===c._inc}))return t;let i=this._buildRevisionIndex(e);return this._revisionIndex=i,i}_revisionsByTag(e){return this._getRevisionIndex().byTag.get(e)??[]}_revisionsByTagIn(e,t){let r=this._revisionsByTag(e);return t===null?r:r.filter(i=>i.part===t)}_parts_holding_id(e){let t=[];for(let r of Jt)for(let i of this._revisionsByTag(r))i.id===e&&!t.includes(i.part)&&t.push(i.part);return t}_action_part_filter(e){let t=e.part;if(t==null||t==="")return {part:null};let r=this._story_roots().map(([,s])=>s);if(typeof t!="string")return {part:null,error:`\`part\` must be a string naming a package part (one of: ${r.join(", ")}).`};let i=Ln(t);return r.includes(i)?{part:i}:{part:null,error:`part '${t}' 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 t of Jt)for(let r of this._revisionsByTag(t))r.id&&e.add(r.id);return Array.from(e).sort((t,r)=>{let i=/^\d+$/.test(t)?parseInt(t,10):0,s=/^\d+$/.test(r)?parseInt(r,10):0;return i-s||t.localeCompare(r)})}_warn_stranded_comment_anchors(e){let t;try{t=R(this.doc.element,"w:commentRangeStart");}catch{return}if(t.length===0)return;let r=g(c=>{let u=new Map,l=0,d=g(f=>{u.set(f,l++);for(let h=f.firstChild;h;h=h.nextSibling)h.nodeType===1&&d(h);},"walk");return d(c),u},"order"),i=g(c=>{let u=c.parentNode;for(;u&&u.nodeType===1;){if(u.tagName==="w:p")return u;u=u.parentNode;}return null},"paragraphOf"),s=g((c,u)=>{let l=c.parentNode;for(;l&&l.nodeType===1&&l!==u;){if(l.tagName==="w:del")return true;l=l.parentNode;}return false},"hasDeletedAncestorWithin"),o=null,a=[];for(let c of t){let u=c.getAttribute("w:id");if(!u)continue;let l=i(c);if(!l)continue;let d=R(l,"w:commentRangeEnd").find(b=>b.getAttribute("w:id")===u);if(!d)continue;let f=r(l),h=f.get(c),_=f.get(d);if(h===void 0||_===void 0||_<h)continue;let p="";for(let b of R(l,"w:t")){let v=f.get(b);v===void 0||v<h||v>_||s(b,l)||(p+=b.textContent||"");}if(!p.trim())continue;let m=false,w=false,y=false;for(let b of R(l,"w:del")){let v=f.get(b);if(v===void 0)continue;let N=v<h?"before":v>_?"after":null;if(!N||!R(b,"w:delText").some(C=>(C.textContent||"").trim()))continue;N==="before"?m=true:w=true;let x=b.getAttribute("w:id")||"";/^\d+$/.test(x)&&parseInt(x,10)>e&&(y=true);}m&&w&&y&&(o===null&&(o=this._comment_authors()),a.push([u,p.trim()]));}for(let[c,u]of a){let l=o?.[c],d=l?`comment Com:${c} (by ${l})`:`comment Com:${c}`;this.skipped_details.push(`- Warning: this batch deleted text on both sides of ${d} but left its anchored text "${pe(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(Be(this.doc.pkg));}catch{e=[];}return e.sort((t,r)=>{let i=/^\d+$/.test(t)?parseInt(t,10):0,s=/^\d+$/.test(r)?parseInt(r,10):0;return i-s||t.localeCompare(r)})}_comment_authors(){let e={};try{for(let[t,r]of Object.entries(Be(this.doc.pkg)))e[t]=r?.author||"Unknown";}catch{}return e}static _describe_removed_comments(e,t){let r=[...e].sort((s,o)=>{let a=/^\d+$/.test(s)?parseInt(s,10):0,c=/^\d+$/.test(o)?parseInt(o,10):0;return a-c||s.localeCompare(o)}),i=r.map(s=>t[s]?`Com:${s} (by ${t[s]})`:`Com:${s}`).join(", ");return `${r.length===1?"comment":"comments"} ${i}`}static _format_id_list(e,t,r=20){let i=e.slice(0,r),s=i.map(o=>`${t}${o}`).join(", ");return e.length>i.length&&(s+=`, \u2026 (+${e.length-i.length} more)`),s}_action_not_found_error(e,t,r="- Failed to apply action:"){let i=this._existing_change_ids(),s=this._existing_comment_ids(),o=e.startsWith("Chg:")||e.startsWith("Com:"),a=e.replace(/^(Chg:|Com:)/,""),c=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(t==="reply"){let d=o?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\`. ${c}`;let f=s.length>0?`Comment ids in this document: ${V._format_id_list(s,"Com:")}. `:"This document has no comments to reply to. ";return `${r} reply on ${d} \u2014 no comment with that id exists. ${f}${c}`}let u=o?e:`Chg:${a}`;if(s.includes(a))return `${r} ${t} 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\`. ${c}`;let l=i.length>0?`Tracked-change ids in this document: ${V._format_id_list(i,"Chg:")}. `:"This document has no tracked changes. ";return `${r} ${t} on ${u} \u2014 no tracked change with that id exists (it may already have been accepted or rejected, or the id is stale). ${l}${c}`}_not_found_in_part_error(e,t,r,i="- Failed to apply action:"){let s=e.replace(/^(Chg:|Com:)/,""),o=e.startsWith("Chg:")?e:`Chg:${s}`,a=this._parts_holding_id(s),c=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} ${t} on ${o} \u2014 no tracked change with w:id=${s} exists in part '${r}'. ${c}${u}`}_ambiguous_part_error(e,t,r,i){let s=e.replace(/^Chg:/,"");return `${i} ${t} on Chg:${s} is ambiguous: revisions with w:id=${s} 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": "${t}", "target_id": "${s}", "part": "${r[0]}"}.`}apply_review_actions(e,t){let r=g(u=>t?t[u]:u,"gidx"),i=0,s=0,o=0,a=new Map,c=e.map((u,l)=>({action:u,pos:l})).sort((u,l)=>{let d=u.action.type==="reply"?0:1,f=l.action.type==="reply"?0:1;return d!==f?d-f:u.pos-l.pos});for(let{action:u,pos:l}of c){let d=u.type;if(d==="reply"){let A=u.target_id.replace("Com:","");if(!this._existing_comment_ids().includes(A)){s++,this.skipped_details.push(this._action_not_found_error(u.target_id,"reply",`- Action ${r(l)+1} Failed:`));continue}let $;try{$=this.comments_manager.addComment(this.author,u.text,A,this.timestamp);}catch(W){if(W instanceof Ki){s++,this.skipped_details.push(`- Action ${r(l)+1} Failed: reply on ${u.target_id} \u2014 ${W.message}`);continue}throw W}this._anchor_reply_comment(A,$),i++;continue}let f=u.target_id.replace("Chg:",""),{part:h,error:_}=this._action_part_filter(u);if(_){s++,this.skipped_details.push(`- Action ${r(l)+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){o++,this.skipped_details.push(`- Note: Action ${r(l)+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(l)+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.`),s++;continue}let m=this._parts_holding_id(f),w=h;if(w===null){if(m.length>1){s++,this.skipped_details.push(this._ambiguous_part_error(u.target_id,d,m,`- Action ${r(l)+1} Failed:`));continue}w=m.length===1?m[0]:null;}let y=this._revisionsByTagIn("w:ins",w).filter(A=>A.id===f).map(A=>A.el),b=this._revisionsByTagIn("w:del",w).filter(A=>A.id===f).map(A=>A.el),v=[...y,...b],N=er.flatMap(A=>this._revisionsByTagIn(A,w).filter($=>$.id===f).map($=>$.el));if(v.length===0&&N.length===0){s++,this.skipped_details.push(h!==null?this._not_found_in_part_error(u.target_id,d,h,`- Action ${r(l)+1} Failed:`):this._action_not_found_error(u.target_id,d,`- Action ${r(l)+1} Failed:`));continue}let k=Array.from(new Set([...v,...N].map(A=>A.getAttribute("w:author")||"Unknown"))).sort();if(k.length>1){s++,this.skipped_details.push(`- Failed to apply action: ${d} on Chg:${f} is ambiguous. The document contains ${v.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 x=new Set([f]);for(let A of v)for(let $ of this._get_paired_nodes(A)){let W=$.getAttribute("w:id");W&&x.add(W);}let C=Zn.flatMap(A=>this._revisionsByTagIn(A,w)),E=-1;for(;E!==x.size;){E=x.size;for(let A of C)if(!(!A.id||!x.has(A.id)))for(let $ of A.nested)$.id&&x.add($.id);}let P=[];for(let A of Zn)for(let $ of this._revisionsByTagIn(A,w))$.id&&x.has($.id)&&P.push($.el);let I=er.flatMap(A=>this._revisionsByTagIn(A,w).filter($=>$.id!==null&&x.has($.id)).map($=>$.el)),M=(()=>{let A=v[0]??N[0]??null;for(;A;){if(A.nodeType===1&&A.tagName==="w:p")return A;A=A.parentNode;}return null})(),j=new Set;for(let A of [...P,...I]){let $=A.getAttribute("w:id");$&&j.add($);}let F=this._comment_authors(),T=new Set(Object.keys(F)),O=[],D=[...P].sort((A,$)=>{let W=A.tagName==="w:del"&&A.parentNode?.tagName==="w:rPr"&&A.parentNode?.parentNode?.tagName==="w:pPr",z=$.tagName==="w:del"&&$.parentNode?.tagName==="w:rPr"&&$.parentNode?.parentNode?.tagName==="w:pPr";return W&&!z?-1:!W&&z?1:0});for(let A of D){let $=A.tagName==="w:ins",W=A.parentNode?A.parentNode.tagName:"",z=W==="w:trPr",H=W==="w:rPr"&&!!A.parentNode?.parentNode&&A.parentNode.parentNode.tagName==="w:pPr";if(d==="accept")if($)if(z)A.parentNode?.removeChild(A);else {for(;A.firstChild;)A.parentNode?.insertBefore(A.firstChild,A);A.parentNode?.removeChild(A);}else if(this._clean_wrapping_comments(A),this._delete_comments_in_element(A),z){let L=A.parentNode?.parentNode;L?.parentNode?.removeChild(L);}else A.parentNode?.removeChild(A);else if(d==="reject")if($){if(H){let L=A.parentNode;A.parentNode?.removeChild(A),L=L?.parentNode,L=L?.parentNode,L&&L.tagName==="w:p"&&O.push(L);continue}if(this._clean_wrapping_comments(A),this._delete_comments_in_element(A),z){let L=A.parentNode?.parentNode;L?.parentNode?.removeChild(L);}else A.parentNode?.removeChild(A);}else if(z)A.parentNode?.removeChild(A);else if(H){let L=A.parentNode,X=L?L.parentNode:null,U=X?X.parentNode:null;if(U&&U.tagName==="w:p"){let G=Array.from(U.childNodes),se=G.filter(oe=>oe.nodeType===1&&oe.tagName==="w:del");if(se.length>0){let oe=se[se.length-1],et=G.indexOf(oe),He=G.slice(et+1);if(He.some(fe=>fe.nodeType===1&&(fe.tagName==="w:r"||fe.tagName==="w:sdt"||fe.getElementsByTagName("w:t").length>0))&&U.parentNode){let we=U.ownerDocument.createElement("w:p"),nt=X.cloneNode(true),xn=S(nt,"w:rPr");if(xn){let wt=S(xn,"w:del");wt&&xn.removeChild(wt);}we.appendChild(nt);for(let wt of He)U.removeChild(wt),we.appendChild(wt);U.parentNode.insertBefore(we,U.nextSibling);}}}A.parentNode?.removeChild(A);}else {let L=Array.from(A.getElementsByTagName("w:delText"));for(let X of L){let U=X.ownerDocument.createElement("w:t");U.textContent=X.textContent,X.hasAttribute("xml:space")&&U.setAttribute("xml:space","preserve"),X.parentNode?.replaceChild(U,X);}for(;A.firstChild;)A.parentNode?.insertBefore(A.firstChild,A);A.parentNode?.removeChild(A);}}for(let A of O.reverse()){if(!A.parentNode)continue;let $=De(A);for(;$&&$.tagName!=="w:p";)$=De($);if($){for(let W of Array.from(A.childNodes))W.nodeType===1&&W.tagName==="w:pPr"||$.appendChild(W);A.parentNode.removeChild(A);}}for(let A of I)d==="accept"?A.parentNode?.removeChild(A):A.tagName==="w:pPrChange"?this._revert_ppr_change(A):this._revert_props_change(A);for(let A of j)a.set(A,{type:d,part:w});if(i++,T.size>0){let A=new Set(this._existing_comment_ids()),$=Array.from(T).filter(W=>!A.has(W));$.length>0&&this.skipped_details.push(`- Note: ${d} on ${u.target_id} also removed ${V._describe_removed_comments($,F)} (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 A=r(l)+1,$=M?Array.from(M.childNodes).find(W=>W.tagName==="w:r")??null:null;if(M&&$){let W=this._attach_comment(M,$,$,String(u.comment));W&&this.skipped_details.push(`- Note: Action ${A} ('${d}' on ${u.target_id}) \u2014 rationale recorded as Com:${W}.`);}else this.skipped_details.push(`- Note: Action ${A} ('${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,s,o]}_apply_table_edit(e,t){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,[s,o]=i.get_insertion_anchor(r,t),a=null;if(s?a=s._element:o&&(a=o._element),!a)return false;let c=a;for(;c&&c.tagName!=="w:tr";)c=c.parentNode;if(!c)return false;let u=(e._reserved_row_id??null)!==null?String(e._reserved_row_id):null;if(e.type==="delete_row"){let l=S(c,"w:trPr");return l||(l=c.ownerDocument.createElement("w:trPr"),c.insertBefore(l,c.firstChild)),l.appendChild(this._create_track_change_tag("w:del","",u)),true}else if(e.type==="insert_row"){let l=c.ownerDocument.createElement("w:tr"),d=c.ownerDocument.createElement("w:trPr");l.appendChild(d),d.appendChild(this._create_track_change_tag("w:ins","",u));let f=R(c,"w:tc").filter(_=>_.parentNode===c).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=c.ownerDocument.createElement("w:tc"),m=c.ownerDocument.createElement("w:p"),w=c.ownerDocument.createElement("w:r"),y=c.ownerDocument.createElement("w:t");y.textContent=_,_.trim()!==_&&y.setAttribute("xml:space","preserve"),w.appendChild(y),m.appendChild(w),p.appendChild(m),l.appendChild(p);}return e.position==="above"?c.parentNode?.insertBefore(l,c):at(l,c),true}return false}_match_spans_whole_paragraph(e,t,r){let i=t+r,s=new Map;for(let o of e.spans){if(o.paragraph===null||o.paragraph===void 0||o.run===null&&o.text===`
|
|
154
|
+
`).filter(l=>l.includes(" | ")).length,a=i.split(`
|
|
155
|
+
`).filter(l=>l.includes(" | ")).length;return o<=a?false:G._column_count_at(e,t,Math.max(r,1))!==null}static _column_count_at(e,t,r){for(let i of e.spans){if(i.end<=t||i.start>=t+r)continue;let s=null;for(i.run!==null?s=i.run._element:i.paragraph!==null&&(s=i.paragraph._element);s;){if(s.nodeType===1&&s.tagName==="w:tr")return R(s,"w:tc").filter(o=>o.parentNode===s).length;s=s.parentNode;}}return null}validate_review_actions(e,t,r=false){let i=[],s=g(l=>t?t[l]:l,"gidx"),o=new Map,a=new Set;for(let l=0;l<e.length;l++){let d=e[l],c=d.type,u=d.target_id??"";if(c==="reply"){if(!String(d.text??"").trim()){i.push(`- Action ${s(l)+1} Failed: reply text for ${u} is empty or whitespace-only. Word would show a blank comment bubble \u2014 provide the reply content in 'text'.`);continue}let f=u+"\0"+String(d.text).trim();a.has(f)&&i.push(`- Action ${s(l)+1} Failed: duplicate reply \u2014 this batch already replies to ${u} with the same text. Remove the duplicate action.`),a.add(f);}else if(c==="accept"||c==="reject"){let{part:f}=this._action_part_filter(d),h=`${f??""}\0${u}`,_=o.get(h);if(_!==void 0){let[p,m]=_;m===c?i.push(`- Action ${s(l)+1} Failed: duplicate action \u2014 Action ${s(p)+1} in this batch already applies '${c}' to ${u}. A change can only be resolved once; remove the duplicate action.`):i.push(`- Action ${s(l)+1} Failed: conflicting actions \u2014 Action ${s(p)+1} in this batch applies '${m}' to ${u}, but this action applies '${c}'. Decide the outcome and keep exactly one of them.`);}else o.set(h,[l,c]);}}if(i.length>0||r)return i;for(let l=0;l<e.length;l++){let d=e[l],c=d.type;if(c==="reply"){let u=d.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")===u)),f||i.push(this._action_not_found_error(d.target_id,"reply",`- Action ${s(l)+1} Failed:`));}else if(c==="accept"||c==="reject"){let u=d.target_id.replace("Chg:",""),{part:f,error:h}=this._action_part_filter(d);if(h){i.push(`- Action ${s(l)+1} Failed: ${c} on ${d.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===u)){_=true;break}_||i.push(f!==null?this._not_found_in_part_error(d.target_id,c,f,`- Action ${s(l)+1} Failed:`):this._action_not_found_error(d.target_id,c,`- Action ${s(l)+1} Failed:`));}}return i}get_pending_revision_authors(){let e=new Set,t=g(r=>{if(r)try{if(typeof r.getAttribute=="function"){let s=r.getAttribute("w:author");s&&e.add(s);}let i=R(r,"*");for(let s of i){let o=s.getAttribute("w:author");o&&e.add(o);}}catch{}},"collect");try{this.doc?.element&&t(this.doc.element);}catch{}try{if(this.doc?.pkg){let r=Fe(this.doc.pkg);for(let i of Object.values(r)){let s=i?.author;s&&s!=="Unknown"&&e.add(s);}}}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 s=String(i.partname||"").toLowerCase();if(!(String(i.contentType||"")==="application/vnd.ms-word.people+xml"||s.includes("people")))try{let a=i._element;!a&&i.blob&&(a=Ke(i.blob)),a&&t(a);}catch{}}}catch{}return e}process_batch(e,t,r=false){this._in_process_batch=true;try{let i=this._process_batch_inner(e,t,r);if(this.markup_mode==="manual"){this._convert_revisions_to_manual_markup();for(let s of i?.edits||[])delete s.change_ids;i&&(i.document_state=this._get_document_state_summary());}return i}finally{this._in_process_batch=false;}}_process_batch_inner(e,t,r=false){return Array.isArray(e)&&(e=e.map(i=>{if(typeof i=="string")try{let s=JSON.parse(i);return s!==null&&typeof s=="object"?s:i}catch{return i}return i})),this._process_batch_internal(e,t,r)}_batch_fingerprint(){let e=0,t=new Set;for(let r of Qt)for(let i of this._revisionsByTag(r))e++,i.id&&t.add(i.id);return [e,[...t].sort().join(","),this._existing_comment_ids().join(",")].join("|")}_restore_batch_snapshot(e,t){e&&(eu(this.doc,e),this.current_id=t,this.mapper=new Te(this.doc),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.comments_manager=new It(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,t,r=false){this.rollback_verified=true;let i=this.get_pending_revision_authors(),s=this.author&&i.has(this.author)?`[!] Warning: acting author '${this.author}' matches an author with pending revisions in this document.`:null;for(let B of e)if(B&&typeof B=="object"&&B.type==="modify"&&B.target_text&&B.new_text){let[j,C]=tu(B.target_text,B.new_text);B.target_text=j,B.new_text=C;}this.skipped_details=[],this._overridden_controls=[];let o=[],a=g(B=>t?t[B]:B,"idx_of"),l=g(B=>B!==null&&typeof B=="object"&&["accept","reject","reply"].includes(B.type),"is_action"),d=e.map((B,j)=>({c:B,i:a(j)})).filter(({c:B})=>l(B)),c=e.map((B,j)=>({c:B,i:a(j)})).filter(({c:B})=>!l(B)),u=d.map(({c:B})=>B),f=d.map(({i:B})=>B),h=c.map(({c:B})=>B),_=[];for(let B=0;B<u.length;B++){let j=Oc(f[B]+1,u[B]?.type??"",this.protection,this.gate_overrides);j&&_.push(j);}_.length===0&&(_=u.length>0?this.validate_review_actions(u,f,r):[]),u.length>0&&_.length===0&&(_=this.validate_action_pairing(u,f));let p=h.length>0&&_.length>0,m=[];if(p)for(let{c:B,i:j}of c){let C=this.validate_edits([B],j);C.length>0&&(m.push(...C),o.push([j,C.join(`
|
|
156
|
+
`)]));}let w=[..._,...m];if(w.length>0)throw o.unshift(...ar(_)),new Vt(w,o);let y=0,b=0,v=0,k=u.length>0||h.length>0?Zd(this.doc):null,x=u.length>0?this._batch_fingerprint():null,P=this.current_id;if(u.length>0){try{let B=this.apply_review_actions(u,f);if(y=B[0],b=B[1],v=B[2],b>0&&(o.push(...ar(this.skipped_details)),!r))throw new Vt(this.skipped_details,o)}catch(B){if(!r)throw this._restore_batch_snapshot(k,P),this._verify_rollback(x),B}y>0&&(this.mapper._build_map(),this.clean_mapper&&this.clean_mapper._build_map());}let[E]=et(this.mapper.full_text),I=tt(E,"").body_page_offsets,D=[],F=0,M=0;if(h.length>0){let B=g(C=>C._resolved_start_idx!==void 0&&C._resolved_start_idx!==null?C._resolved_start_idx:C._match_start_index!==void 0&&C._match_start_index!==null?C._match_start_index:null,"pinned_idx"),j=c.map(({c:C,i:S},A)=>({edit:C,i:A,orig_idx:S})).sort((C,S)=>{let A=B(C.edit),O=B(S.edit);return A===null&&O===null?C.i-S.i:A===null?1:O===null?-1:O-A||C.i-S.i});{try{let C=[],S=0;for(let{edit:A,orig_idx:O}of j){let L;try{L=this.validate_edits([A],O);}catch(H){if(!(H instanceof Le))throw H;L=[`- Edit ${O+1} Failed: ${H.message}`];}if(L.length>0){let H=L.join(`
|
|
157
|
+
`);if(o.push([O,H]),S>0&&!r){let q=ji(S);L=L.map(z=>z+q);}C.push(...L),A&&typeof A=="object"&&(A._error_msg=H);}else if(this.apply_edits([A],I),A._applied_status&&!A._any_sub_failure)S++,this.mapper=new Te(this.doc),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.clean_mapper=null;else {let H=A._error_msg||`- Edit ${O+1} Failed: Failed to apply edit.`;if(A&&typeof A=="object"&&(A._error_msg=H),o.push([O,H]),S>0&&!r&&(H+=ji(S)),C.push(H),!r)break;A._applied_status&&(this.mapper=new Te(this.doc),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.clean_mapper=null);}}if(!r&&C.length>0)throw new Vt(C,o)}catch(C){throw this._restore_batch_snapshot(k,P),this._verify_rollback(x),C}F=h.filter(C=>C._applied_status&&!C._any_sub_failure).length,M=h.length-F;for(let[C,S]of h.entries()){let A=S._applied_status||false,O=S._error_msg||null,L=null,H=null,q=S._warning||null;if(A){let V=this._build_edit_context_previews(S);L=V[0],H=V[1];}else q=q||this._check_punctuation_warning(S.target_text||"");let U=Array.from(new Set((S._minted_change_ids||[]).map(V=>String(V)).filter(Boolean))).map(V=>V.startsWith("Chg:")?V:`Chg:${V}`),te=Array.from(new Set((S._minted_comment_ids||[]).map(V=>String(V)).filter(Boolean))).map(V=>V.startsWith("Com:")?V:`Com:${V}`);D.push({index:c[C].i,status:A?"applied":"failed",type:S.type||"modify",target_text:ge(S.target_text||"",qn),new_text:ge(G._report_new_text(S),qn),comment:S.comment??null,warning:q,error:O,critic_markup:L,clean_text:H,pages:S._pages||[],heading_path:S._heading_path||"",field:S._field||"",part:S._part||"",occurrences_modified:S._occurrences_modified||0,match_mode:S.match_mode||"strict",...U.length>0?{change_ids:U}:{},...te.length>0?{comment_ids:te}:{}});}}}if(F>0)try{this._warn_stranded_comment_anchors(P);}catch{}return {status:r&&o.length>0?"partial":"ok",author_impersonation_warning:s,overrides_note:Lc(this.gate_overrides,this._overridden_controls),failed:o.map(([B,j])=>({index:B,reason:j,error:j})),actions_applied:y,actions_skipped:b,actions_already_resolved:v,edits_applied:F,edits_skipped:M,occurrences_modified:D.reduce((B,j)=>B+(j.occurrences_modified||0),0),skipped_details:this.skipped_details,edits:D,...this._last_action_reports?.length?{actions:this._last_action_reports}:{},document_state:this._get_document_state_summary(),engine:"node",version:Zl}}_get_document_state_summary(){let e=new Set;for(let t of [...rn,...sn])for(let r of this._revisionsByTagIn(t,null))r.id&&e.add(r.id);return {tracked_changes:e.size,comments:this._existing_comment_ids().length}}static _flag_surviving_python_backreference(e,t){let r=/\\(\d+)|\\g<(\d+)>/.exec(e.new_text||"");if(!r||!t.includes(r[0]))return;let i=0;try{let{pattern:o,flags:a}=mn(e.target_text,""),l=new RegExp(`(?:${o})|`,a).exec("");i=l?l.length-1:0;}catch{return}let s=parseInt(r[1]??r[2],10);s>0&&s<=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 $${s} (\\N and \\g<N> are Python syntax). If you meant literal text, ignore this warning.`);}static _ids_needed(e){let t=e._internal_op;return t==null&&(!e.target_text&&e.new_text?t="INSERTION":e.target_text&&!e.new_text?t="DELETION":t="MODIFICATION"),t==="STYLE_ONLY"?[false,false]:(t==="STYLE_AND_TEXT"&&(e.target_text&&e.new_text?t="MODIFICATION":!e.target_text&&e.new_text?t="INSERTION":e.target_text&&!e.new_text?t="DELETION":t="COMMENT_ONLY"),[t==="DELETION"||t==="MODIFICATION",t==="INSERTION"||t==="MODIFICATION"])}apply_edits(e,t=[]){let i=0;if(!t||t.length===0){let[c]=et(this.mapper.full_text);t=tt(c,"").body_page_offsets;}let s=[];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,s),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]=Fi(c.target_text,c.new_text)),c._active_mapper_ref||(this.clean_mapper||(this.clean_mapper=new Te(this.doc,true)),c._active_mapper_ref=this.clean_mapper),c.type==="modify"&&!c.target_text&&c.new_text&&!c._insert_host_el){let u=this._empty_control_fill_host(c._active_mapper_ref,c._resolved_start_idx??0);u&&(c._insert_host_el=u);}s.push([c,c.new_text||null]);}else if(c.type==="insert_row"||c.type==="delete_row"){let{sub_edits:u,err_msg:f}=this._resolve_structural_table_edit(c);f?(i++,c._applied_status=false,this.skipped_details.push(f),c._error_msg=f):s.push(...u);}else {let u;try{u=this._pre_resolve_heuristic_edit(c);}catch(f){if(!(f instanceof Le))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(u)if(Array.isArray(u))for(let f of u)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),s.push([f,f.new_text]);else u._resolved_start_idx=u._match_start_index,u._parent_edit_ref=c,c._resolved_start_idx=u._resolved_start_idx,c._resolved_proxy_edit=u,s.push([u,u.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=_;}}}s.sort((c,u)=>(u[0]._resolved_start_idx||0)-(c[0]._resolved_start_idx||0));{let c=[...s].sort((u,f)=>(u[0]._resolved_start_idx||0)-(f[0]._resolved_start_idx||0));for(let[u]of c){let f=u._parent_edit_ref||u;if(Array.isArray(f._minted_change_ids)||(f._minted_change_ids=[]),u.type==="insert_row"||u.type==="delete_row"){u._reserved_row_id==null&&(u._reserved_row_id=this._getNextId(),f._minted_change_ids.push(u._reserved_row_id));continue}if(u.type!=="modify")continue;let[h,_]=G._ids_needed(u);h&&u._reserved_del_id==null&&(u._reserved_del_id=this._getNextId(),f._minted_change_ids.push(u._reserved_del_id)),_&&u._reserved_ins_id==null&&(u._reserved_ins_id=this._getNextId(),f._minted_change_ids.push(u._reserved_ins_id));}}for(let[c]of s)this._capture_preview_context(c),c._parent_edit_ref&&this._capture_parent_preview_context(c._parent_edit_ref);let o=[],a=new Set;for(let[c,u]of s){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(([y,b])=>f<b&&h>y)){i++;let b=`- Skipped overlapping edit targeting: '${this._report_target(c)}...'`;this.skipped_details.push(b),c._applied_status=false,c._error_msg=b,c._any_sub_failure=true;let v=c._parent_edit_ref;v&&(v._applied_status=false,v._error_msg=b,v._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,u,false):(c.type==="insert_row"||c.type==="delete_row")&&(p=this._apply_table_edit(c,false)),p&&c._unwrap_sdt_after&&Id(c._unwrap_sdt_after),p){let y=c._parent_edit_ref||c;Array.isArray(y._minted_change_ids)||(y._minted_change_ids=[]);for(let b=m+1;b<=this.current_id;b++)y._minted_change_ids.push(String(b));Array.isArray(y._minted_comment_ids)||(y._minted_comment_ids=[]);for(let b=w;b<this.comments_manager.nextId;b++)y._minted_comment_ids.push(String(b));}if(p){let y=c._split_group_id,b=y==null||!a.has(y);b&&y!==void 0&&y!==null&&a.add(y),o.push([f,h]),c._applied_status=true;let v=c._parent_edit_ref;if(v){v._applied_status=true,b&&(v._occurrences_modified=(v._occurrences_modified||0)+1);let[N,k]=this._get_heading_path_and_page(f,this.mapper.full_text,t),x=v._pages||[];x.includes(k)||x.unshift(k),v._pages=x,v._heading_path=N,v._field=this._field_label_at(f),v._part=(c._active_mapper_ref||this.mapper).part_label_at(f);}else {b&&(c._occurrences_modified=(c._occurrences_modified||0)+1);let[N,k]=this._get_heading_path_and_page(f,this.mapper.full_text,t),x=c._pages||[];x.includes(k)||x.unshift(k),c._pages=x,c._heading_path=N,c._field=this._field_label_at(f),c._part=(c._active_mapper_ref||this.mapper).part_label_at(f);}}else {i++;let b=`- Failed to apply edit targeting: '${this._report_target(c)}...'`;this.skipped_details.push(b),c._applied_status=false,c._error_msg=b,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=b));}}let l=0,d=0;for(let c of e){if(typeof c!="object"||c===null){d++;continue}c._applied_status&&!c._any_sub_failure?l++:d++;}return this.markup_mode==="manual"&&!this._in_process_batch&&this._convert_revisions_to_manual_markup(),[l,d]}_convert_revisions_to_manual_markup(){let e=this._revision_roots(),t=["w:rPrChange","w:pPrChange","w:tblPrChange","w:trPrChange","w:tcPrChange","w:sectPrChange"];for(let r of e){for(let i of t)for(let s of R(r,i))s.parentNode&&s.parentNode.removeChild(s);for(let i of R(r,"w:del")){let s=i.parentNode;if(!s)continue;if(s.tagName==="w:rPr"){s.removeChild(i);let d=s.parentNode,c=Array.from(s.childNodes).some(u=>u.nodeType===1);d&&!c&&(!s.attributes||s.attributes.length===0)&&d.removeChild(s);continue}if(s.tagName==="w:trPr"){let d=s.parentNode;if(s.removeChild(i),d)for(let c of R(d,"w:r"))this._apply_run_props(c,{strike:true});continue}let o=le(i),a=false;if(o&&o.tagName==="w:ins"){let d=R(i,"w:delText").map(u=>u.textContent||"").join(""),c=R(o,"w:t").map(u=>u.textContent||"").join("");d.length>0&&c.length>0&&!/\s$/.test(d)&&!/^\s/.test(c)&&!",.;:!?)];".includes(c[0])&&(a=true);}let l=i.ownerDocument;for(let d of R(i,"w:r")){for(let u of R(d,"w:delText")){let f=l.createElement("w:t");this._set_text_content(f,u.textContent||""),u.parentNode&&(u.parentNode.insertBefore(f,u),u.parentNode.removeChild(u));}let c=$(d,"w:rPr");if(c){let u=$(c,"w:u");u&&c.removeChild(u);}this._apply_run_props(d,{strike:true});}for(let d of Array.from(i.childNodes))i.removeChild(d),s.insertBefore(d,i);if(a){let d=l.createElement("w:r"),c=l.createElement("w:t");this._set_text_content(c," "),d.appendChild(c),s.insertBefore(d,i);}s.removeChild(i);}for(let i of R(r,"w:ins")){let s=i.parentNode;if(s){if(s.tagName==="w:rPr"||s.tagName==="w:trPr"){s.removeChild(i);let o=s.parentNode,a=Array.from(s.childNodes).some(l=>l.nodeType===1);s.tagName==="w:rPr"&&o&&!a&&(!s.attributes||s.attributes.length===0)&&o.removeChild(s);continue}for(let o of R(i,"w:r"))this._apply_run_props(o,{bold:true,underline:"single",color:"C00000"});for(let o of Array.from(i.childNodes))i.removeChild(o),s.insertBefore(o,i);s.removeChild(i);}}}}_paragraph_has_visible_content(e){for(let t of ["w:t","w:tab","w:br"]){let r=R(e,t);for(let i of r){let s=false,o=i.parentNode;for(;o&&o!==e.parentNode;){if(o.tagName==="w:del"){s=true;break}o=o.parentNode;}if(!s){if(t==="w:t"&&!i.textContent)continue;return true}}}return false}_is_last_paragraph_in_cell(e){let t=e.parentNode;for(;t&&t.tagName!=="w:tc";)t=t.parentNode;return t?R(t,"w:p").length<=1:false}_get_paired_nodes(e){let t=[],r=e.getAttribute("w:author"),i=new Set(["w:commentRangeStart","w:commentRangeEnd","w:commentReference","w:rPr","w:pPr"]),s=new Set,o=g(u=>{let f=u.getAttribute("w:id");f&&s.add(f);},"add_id");o(e);let a=g(u=>{let f=u;for(;f&&f.tagName!=="w:p";)f=f.parentNode;return f},"paragraph_of"),l=g(u=>{let f=$(u,"w:pPr"),h=f?$(f,"w:rPr"):null;return h?$(h,"w:ins"):null},"mark_of"),d=g(u=>{let f=l(u);if(!f||f.getAttribute("w:author")!==r)return false;let h=f.getAttribute("w:id");return h!==null&&s.has(h)},"boundary_is_ours"),c=g((u,f)=>{let h=a(u),_=f==="next"?u.nextSibling:u.previousSibling;for(;;){if(!_){if(!h)break;if(f==="next"){let m=le(h);for(;m&&m.tagName!=="w:p";)m=le(m);if(!m||!d(m))break;h=m,_=m.firstChild;}else {if(!d(h))break;let m=Ce(h);for(;m&&m.tagName!=="w:p";)m=Ce(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){t.push(p),o(p),_=f==="next"?_.nextSibling:_.previousSibling;continue}break}},"walk");return c(e,"next"),c(e,"prev"),t}_resolution_group_ids(e,t=null){let r=[...this._revisionsByTagIn("w:ins",t),...this._revisionsByTagIn("w:del",t)].filter(s=>s.id===e).map(s=>s.el),i=new Set;if(r.length===0)return this._revisionsByTagIn("w:pPrChange",t).some(o=>o.id===e)&&i.add(e),i;i.add(e);for(let s of r)for(let o of this._get_paired_nodes(s)){let a=o.getAttribute("w:id");a&&i.add(a);}return i}validate_action_pairing(e,t){let r=[],i=g(o=>t?t[o]:o,"gidx"),s=new Map;for(let o=0;o<e.length;o++){let a=e[o];if(a.type!=="accept"&&a.type!=="reject")continue;let l=String(a.target_id??"");if(l.startsWith("Com:"))continue;let d=l.startsWith("Chg:")?l.slice(4):l,{part:c,error:u}=this._action_part_filter(a);if(u)continue;let f=c;if(f===null){let m=this._parts_holding_id(d);if(m.length!==1)continue;f=m[0];}let h=this._resolution_group_ids(d,f);if(h.size===0)continue;let _=g(m=>`${f}\0${m}`,"group_key"),p=null;for(let m of h){let w=s.get(_(m));if(w!==void 0&&w[1]!==a.type){p=w;break}}if(p!==null){let[m,w,y]=p;r.push(`- Action ${i(o)+1} Failed: conflicting actions on one replacement \u2014 Action ${i(m)+1} applies '${w}' to Chg:${y}, and Chg:${d} 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)s.has(_(m))||s.set(_(m),[o,a.type,d]);}return r}_buildRevisionIndex(e){let t=new Map;for(let i of Qt)t.set(i,[]);let r=[];for(let[i,s]of e){let o=i.ownerDocument;r.push({el:i,doc:o,inc:typeof o?._inc=="number"?o._inc:null});let a=[i],l=[0],d=[],c=[];for(;a.length;){let u=a.length-1,f=a[u].childNodes;if(!f||l[u]>=f.length){for(a.pop(),l.pop();c.length&&c[c.length-1]>a.length;)c.pop(),d.pop();continue}let h=f[l[u]++];if(h.nodeType!==1)continue;let _=t.get(h.tagName),p=null;_&&(p={el:h,id:h.getAttribute("w:id"),part:s,nested:[]},_.push(p));let m=h.tagName==="w:ins"||h.tagName==="w:del";if(p&&m)for(let w of d)w.nested.push(p);a.push(h),l.push(0),p&&m&&(d.push(p),c.push(a.length));}}return {roots:r,byTag:t}}_getRevisionIndex(){let e=this._story_roots(),t=this._revisionIndex;if(t!==null&&t.roots.length===e.length&&t.roots.every((s,o)=>{let a=e[o][0],l=a.ownerDocument;return s.el===a&&s.doc===l&&s.inc!==null&&typeof l?._inc=="number"&&s.inc===l._inc}))return t;let i=this._buildRevisionIndex(e);return this._revisionIndex=i,i}_revisionsByTag(e){return this._getRevisionIndex().byTag.get(e)??[]}_revisionsByTagIn(e,t){let r=this._revisionsByTag(e);return t===null?r:r.filter(i=>i.part===t)}_parts_holding_id(e){let t=[];for(let r of Qt)for(let i of this._revisionsByTag(r))i.id===e&&!t.includes(i.part)&&t.push(i.part);return t}_action_part_filter(e){let t=e.part;if(t==null||t==="")return {part:null};let r=this._story_roots().map(([,s])=>s);if(typeof t!="string")return {part:null,error:`\`part\` must be a string naming a package part (one of: ${r.join(", ")}).`};let i=Vn(t);return r.includes(i)?{part:i}:{part:null,error:`part '${t}' 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 t of Qt)for(let r of this._revisionsByTag(t))r.id&&e.add(r.id);return Array.from(e).sort((t,r)=>{let i=/^\d+$/.test(t)?parseInt(t,10):0,s=/^\d+$/.test(r)?parseInt(r,10):0;return i-s||t.localeCompare(r)})}_warn_stranded_comment_anchors(e){let t;try{t=R(this.doc.element,"w:commentRangeStart");}catch{return}if(t.length===0)return;let r=g(l=>{let d=new Map,c=0,u=g(f=>{d.set(f,c++);for(let h=f.firstChild;h;h=h.nextSibling)h.nodeType===1&&u(h);},"walk");return u(l),d},"order"),i=g(l=>{let d=l.parentNode;for(;d&&d.nodeType===1;){if(d.tagName==="w:p")return d;d=d.parentNode;}return null},"paragraphOf"),s=g((l,d)=>{let c=l.parentNode;for(;c&&c.nodeType===1&&c!==d;){if(c.tagName==="w:del")return true;c=c.parentNode;}return false},"hasDeletedAncestorWithin"),o=null,a=[];for(let l of t){let d=l.getAttribute("w:id");if(!d)continue;let c=i(l);if(!c)continue;let u=R(c,"w:commentRangeEnd").find(b=>b.getAttribute("w:id")===d);if(!u)continue;let f=r(c),h=f.get(l),_=f.get(u);if(h===void 0||_===void 0||_<h)continue;let p="";for(let b of R(c,"w:t")){let v=f.get(b);v===void 0||v<h||v>_||s(b,c)||(p+=b.textContent||"");}if(!p.trim())continue;let m=false,w=false,y=false;for(let b of R(c,"w:del")){let v=f.get(b);if(v===void 0)continue;let N=v<h?"before":v>_?"after":null;if(!N||!R(b,"w:delText").some(P=>(P.textContent||"").trim()))continue;N==="before"?m=true:w=true;let x=b.getAttribute("w:id")||"";/^\d+$/.test(x)&&parseInt(x,10)>e&&(y=true);}m&&w&&y&&(o===null&&(o=this._comment_authors()),a.push([d,p.trim()]));}for(let[l,d]of a){let c=o?.[l],u=c?`comment Com:${l} (by ${c})`:`comment Com:${l}`;this.skipped_details.push(`- Warning: this batch deleted text on both sides of ${u} but left its anchored text "${ge(d,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(Fe(this.doc.pkg));}catch{e=[];}return e.sort((t,r)=>{let i=/^\d+$/.test(t)?parseInt(t,10):0,s=/^\d+$/.test(r)?parseInt(r,10):0;return i-s||t.localeCompare(r)})}_comment_authors(){let e={};try{for(let[t,r]of Object.entries(Fe(this.doc.pkg)))e[t]=r?.author||"Unknown";}catch{}return e}static _describe_removed_comments(e,t){let r=[...e].sort((s,o)=>{let a=/^\d+$/.test(s)?parseInt(s,10):0,l=/^\d+$/.test(o)?parseInt(o,10):0;return a-l||s.localeCompare(o)}),i=r.map(s=>t[s]?`Com:${s} (by ${t[s]})`:`Com:${s}`).join(", ");return `${r.length===1?"comment":"comments"} ${i}`}static _format_id_list(e,t,r=20){let i=e.slice(0,r),s=i.map(o=>`${t}${o}`).join(", ");return e.length>i.length&&(s+=`, \u2026 (+${e.length-i.length} more)`),s}_action_not_found_error(e,t,r="- Failed to apply action:"){let i=this._existing_change_ids(),s=this._existing_comment_ids(),o=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(t==="reply"){let u=o?e:`Com:${a}`;if(i.includes(a))return `${r} reply on ${u} \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=s.length>0?`Comment ids in this document: ${G._format_id_list(s,"Com:")}. `:"This document has no comments to reply to. ";return `${r} reply on ${u} \u2014 no comment with that id exists. ${f}${l}`}let d=o?e:`Chg:${a}`;if(s.includes(a))return `${r} ${t} on ${d} \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: ${G._format_id_list(i,"Chg:")}. `:"This document has no tracked changes. ";return `${r} ${t} on ${d} \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,t,r,i="- Failed to apply action:"){let s=e.replace(/^(Chg:|Com:)/,""),o=e.startsWith("Chg:")?e:`Chg:${s}`,a=this._parts_holding_id(s),l=a.length>0?`Revisions with that id exist in: ${a.join(", ")}. `:"",d=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} ${t} on ${o} \u2014 no tracked change with w:id=${s} exists in part '${r}'. ${l}${d}`}_ambiguous_part_error(e,t,r,i){let s=e.replace(/^Chg:/,"");return `${i} ${t} on Chg:${s} is ambiguous: revisions with w:id=${s} 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": "${t}", "target_id": "${s}", "part": "${r[0]}"}.`}apply_review_actions(e,t){let r=g(d=>t?t[d]:d,"gidx"),i=0,s=0,o=0;this._last_action_reports=[];let a=new Map,l=e.map((d,c)=>({action:d,pos:c})).sort((d,c)=>{let u=d.action.type==="reply"?0:1,f=c.action.type==="reply"?0:1;return u!==f?u-f:d.pos-c.pos});for(let{action:d,pos:c}of l){let u=d.type;if(u==="reply"){let A=d.target_id.replace("Com:","");if(!this._existing_comment_ids().includes(A)){s++,this.skipped_details.push(this._action_not_found_error(d.target_id,"reply",`- Action ${r(c)+1} Failed:`));continue}let O;try{O=this.comments_manager.addComment(this.author,d.text,A,this.timestamp);}catch(H){if(H instanceof cs){s++,this.skipped_details.push(`- Action ${r(c)+1} Failed: reply on ${d.target_id} \u2014 ${H.message}`);continue}throw H}this._anchor_reply_comment(A,O),i++;let L=d.target_id.startsWith("Com:")?d.target_id:`Com:${A}`;this._last_action_reports.push({index:r(c),type:"reply",target_id:L,resolved_ids:[L],status:"applied"});continue}let f=d.target_id.replace("Chg:",""),{part:h,error:_}=this._action_part_filter(d);if(_){s++,this.skipped_details.push(`- Action ${r(c)+1} Failed: ${u} on ${d.target_id} \u2014 ${_}`);continue}let p=a.get(f);if(p!==void 0&&(h===null||h===p.part)){if(p.type===u){o++,this.skipped_details.push(`- Note: Action ${r(c)+1} ('${u}' on ${d.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 '${u}' on ${d.target_id}, but the change was already resolved as '${p.type}' together with its replacement pair by an earlier action in this batch.`),s++;continue}let m=this._parts_holding_id(f),w=h;if(w===null){if(m.length>1){s++,this.skipped_details.push(this._ambiguous_part_error(d.target_id,u,m,`- Action ${r(c)+1} Failed:`));continue}w=m.length===1?m[0]:null;}let y=this._revisionsByTagIn("w:ins",w).filter(A=>A.id===f).map(A=>A.el),b=this._revisionsByTagIn("w:del",w).filter(A=>A.id===f).map(A=>A.el),v=[...y,...b],N=sn.flatMap(A=>this._revisionsByTagIn(A,w).filter(O=>O.id===f).map(O=>O.el));if(v.length===0&&N.length===0){s++,this.skipped_details.push(h!==null?this._not_found_in_part_error(d.target_id,u,h,`- Action ${r(c)+1} Failed:`):this._action_not_found_error(d.target_id,u,`- Action ${r(c)+1} Failed:`));continue}let k=Array.from(new Set([...v,...N].map(A=>A.getAttribute("w:author")||"Unknown"))).sort();if(k.length>1){s++,this.skipped_details.push(`- Failed to apply action: ${u} on Chg:${f} is ambiguous. The document contains ${v.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 x=new Set([f]);for(let A of v)for(let O of this._get_paired_nodes(A)){let L=O.getAttribute("w:id");L&&x.add(L);}let P=rn.flatMap(A=>this._revisionsByTagIn(A,w)),E=-1;for(;E!==x.size;){E=x.size;for(let A of P)if(!(!A.id||!x.has(A.id)))for(let O of A.nested)O.id&&x.add(O.id);}let T=[];for(let A of rn)for(let O of this._revisionsByTagIn(A,w))O.id&&x.has(O.id)&&T.push(O.el);let I=sn.flatMap(A=>this._revisionsByTagIn(A,w).filter(O=>O.id!==null&&x.has(O.id)).map(O=>O.el)),D=(()=>{let A=v[0]??N[0]??null;for(;A;){if(A.nodeType===1&&A.tagName==="w:p")return A;A=A.parentNode;}return null})(),F=new Set;for(let A of [...T,...I]){let O=A.getAttribute("w:id");O&&F.add(O);}let M=this._comment_authors(),B=new Set(Object.keys(M)),j=[],C=[...T].sort((A,O)=>{let L=A.tagName==="w:del"&&A.parentNode?.tagName==="w:rPr"&&A.parentNode?.parentNode?.tagName==="w:pPr",H=O.tagName==="w:del"&&O.parentNode?.tagName==="w:rPr"&&O.parentNode?.parentNode?.tagName==="w:pPr";return L&&!H?-1:!L&&H?1:0});for(let A of C){let O=A.tagName==="w:ins",L=A.parentNode?A.parentNode.tagName:"",H=L==="w:trPr",q=L==="w:rPr"&&!!A.parentNode?.parentNode&&A.parentNode.parentNode.tagName==="w:pPr";if(u==="accept")if(O)if(H)A.parentNode?.removeChild(A);else {for(;A.firstChild;)A.parentNode?.insertBefore(A.firstChild,A);A.parentNode?.removeChild(A);}else if(this._clean_wrapping_comments(A),this._delete_comments_in_element(A),H){let z=A.parentNode?.parentNode;z?.parentNode?.removeChild(z);}else A.parentNode?.removeChild(A);else if(u==="reject")if(O){if(q){let z=A.parentNode;A.parentNode?.removeChild(A),z=z?.parentNode,z=z?.parentNode,z&&z.tagName==="w:p"&&j.push(z);continue}if(this._clean_wrapping_comments(A),this._delete_comments_in_element(A),H){let z=A.parentNode?.parentNode;z?.parentNode?.removeChild(z);}else A.parentNode?.removeChild(A);}else if(H)A.parentNode?.removeChild(A);else if(q){let z=A.parentNode,U=z?z.parentNode:null,X=U?U.parentNode:null;if(X&&X.tagName==="w:p"){let te=Array.from(X.childNodes),V=te.filter(fe=>fe.nodeType===1&&fe.tagName==="w:del");if(V.length>0){let fe=V[V.length-1],it=te.indexOf(fe),Oe=te.slice(it+1);if(Oe.some(he=>he.nodeType===1&&(he.tagName==="w:r"||he.tagName==="w:sdt"||he.getElementsByTagName("w:t").length>0))&&X.parentNode){let Ge=X.ownerDocument.createElement("w:p"),Or=U.cloneNode(true),$n=$(Or,"w:rPr");if($n){let yt=$($n,"w:del");yt&&$n.removeChild(yt);}Ge.appendChild(Or);for(let yt of Oe)X.removeChild(yt),Ge.appendChild(yt);X.parentNode.insertBefore(Ge,X.nextSibling);}}}A.parentNode?.removeChild(A);}else {let z=Array.from(A.getElementsByTagName("w:delText"));for(let U of z){let X=U.ownerDocument.createElement("w:t");X.textContent=U.textContent,U.hasAttribute("xml:space")&&X.setAttribute("xml:space","preserve"),U.parentNode?.replaceChild(X,U);}for(;A.firstChild;)A.parentNode?.insertBefore(A.firstChild,A);A.parentNode?.removeChild(A);}}this._resolve_rejected_mark_hosts(j);for(let A of I)u==="accept"?A.parentNode?.removeChild(A):A.tagName==="w:pPrChange"?this._revert_ppr_change(A):this._revert_props_change(A);for(let A of F)a.set(A,{type:u,part:w});i++;let S=Array.from(F).filter(Boolean).sort((A,O)=>Number(A)-Number(O)).map(A=>`Chg:${A}`);if(this._last_action_reports.push({index:r(c),type:u,target_id:d.target_id,resolved_ids:S.length>0?S:[d.target_id.startsWith("Chg:")?d.target_id:`Chg:${f}`],status:"applied"}),B.size>0){let A=new Set(this._existing_comment_ids()),O=Array.from(B).filter(L=>!A.has(L));O.length>0&&this.skipped_details.push(`- Note: ${u} on ${d.target_id} also removed ${G._describe_removed_comments(O,M)} (including any reply thread) because its anchor was inside the resolved change. This note is informational \u2014 the action itself succeeded.`);}if(d.comment&&String(d.comment).trim()){let A=r(c)+1,O=D?Array.from(D.childNodes).find(L=>L.tagName==="w:r")??null:null;if(D&&O){let L=this._attach_comment(D,O,O,String(d.comment));L&&this.skipped_details.push(`- Note: Action ${A} ('${u}' on ${d.target_id}) \u2014 rationale recorded as Com:${L}.`);}else this.skipped_details.push(`- Note: Action ${A} ('${u}' on ${d.target_id}) \u2014 the rationale could not be anchored (the resolved text left no surviving run); the ${u} itself succeeded.`);}}return i>0&&this._prune_empty_paragraph_properties(),[i,s,o]}_apply_table_edit(e,t){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,[s,o]=i.get_insertion_anchor(r,t),a=null;if(s?a=s._element:o&&(a=o._element),!a)return false;let l=a;for(;l&&l.tagName!=="w:tr";)l=l.parentNode;if(!l)return false;let d=(e._reserved_row_id??null)!==null?String(e._reserved_row_id):null;if(e.type==="delete_row"){let c=$(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","",d)),true}else if(e.type==="insert_row"){let c=l.ownerDocument.createElement("w:tr"),u=l.ownerDocument.createElement("w:trPr");c.appendChild(u),u.appendChild(this._create_track_change_tag("w:ins","",d));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"),y=l.ownerDocument.createElement("w:t");y.textContent=_,_.trim()!==_&&y.setAttribute("xml:space","preserve"),w.appendChild(y),m.appendChild(w),p.appendChild(m),c.appendChild(p);}return e.position==="above"?l.parentNode?.insertBefore(c,l):ut(c,l),true}return false}_match_spans_whole_paragraph(e,t,r){let i=t+r,s=new Map;for(let o of e.spans){if(o.paragraph===null||o.paragraph===void 0||o.run===null&&o.text===`
|
|
147
158
|
|
|
148
|
-
`)continue;let a=s.get(o.paragraph),
|
|
159
|
+
`)continue;let a=s.get(o.paragraph),l=o.run!==null&&o.run!==void 0?o.start:1/0;a===void 0?s.set(o.paragraph,[o.start,o.end,l]):(o.start<a[0]&&(a[0]=o.start),o.end>a[1]&&(a[1]=o.end),l<a[2]&&(a[2]=l));}for(let[o,a,l]of s.values())if(a===i&&(o===t||l===t))return true;return false}static _restore_matched_whitespace(e,t,r){if(!r||!e||!t||!/[\r\n]/.test(t)||!/[\r\n]/.test(r))return r;let i=Math.min(t.length,r.length),s=0;for(;s<i&&t[s]===r[s];)s++;let o=0;for(;o<i-s&&t[t.length-1-o]===r[r.length-1-o];)o++;if(s===0&&o===0)return r;let a=g(f=>f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegExp"),l=e.replace(/(\*\*|__|_)/g,""),d=r.slice(0,s),c=r.slice(s,o>0?r.length-o:r.length),u=o>0?r.slice(r.length-o):"";if(/[\r\n]/.test(d)){let f=Array.from(d.matchAll(/(\S+)([ \t]*[\r\n]+[ \t\r\n]*)/g));for(let h of f){let _=h[1],p=h[2];if(!l.includes(_+p)){let m=l.match(new RegExp(a(_)+"([ \\t]+)"));m&&(d=d.replace(_+p,_+m[1]));}}}if(/[\r\n]/.test(u)){let f=Array.from(u.matchAll(/([ \t]*[\r\n]+[ \t\r\n]*)(\S+)/g));for(let h of f){let _=h[1],p=h[2];if(!l.includes(_+p)){let m=l.match(new RegExp("([ \\t]+)"+a(p)));m&&(u=u.replace(_+p,m[1]+p));}}}return d+c+u}static _reinject_anchor_markers(e,t,r,i,s){let o=g(y=>new RegExp(ir.source).test(y),"has_marker");if(!s||o(i||"")||!o(e.full_text.substring(t,t+r)))return s;let[a,l]=e.anchor_markers_in_range(t,r);if(l.length===0)return s;let d=Et(a),c=Et(e._strip_markdown_formatting(i)),u=c?d.indexOf(c):-1;u>=0&&(s=a.substring(0,u)+s+a.substring(u+c.length));let f=new Ss.diff_match_patch,h=f.diff_main(d,Et(s)),_=new Array(a.length).fill(null),p=0,m=0;for(let[y,b]of h){if(y===0)for(let v=0;v<b.length;v++)_[p+v]=m+v;y!==1&&(p+=b.length),y!==-1&&(m+=b.length);}let w=[];for(let[y,b,v]of l){if(b===v){let k;b<a.length&&_[b]!==null?k=_[b]:b>0&&_[b-1]!==null?k=_[b-1]+1:k=f.diff_xIndex(h,b),w.push([k,k,y]);continue}let N=_.slice(b,v);if(N.some(k=>k===null)||N[N.length-1]-N[0]!==v-b-1)return null;w.push([N[0],N[N.length-1]+1,y]);}w.sort((y,b)=>b[0]-y[0]||b[1]-y[1]);for(let[y,b,v]of w)s=s.substring(0,y)+v+s.substring(b);return s}_pre_resolve_heuristic_edit(e){if(!e.target_text)return null;let t=e.regex||false,r=e.match_mode||"strict",i=this.mapper.drop_virtual_only_matches(this.mapper.find_all_match_indices(e.target_text,t)),s=false;if(i.length===0)if(this.clean_mapper||(this.clean_mapper=new Te(this.doc,true)),i=this.clean_mapper.drop_virtual_only_matches(this.clean_mapper.find_all_match_indices(e.target_text,t)),i.length>0)s=true;else return null;let o=s?this.clean_mapper:this.mapper,a=[];for(let[d,c]of i){let u=o.spans.filter(f=>f.run!==null&&f.end>d&&f.start<d+c);(u.length===0||u.some(f=>!f.del_id))&&a.push([d,c]);}if(a.length===0)return null;(r==="strict"||r==="first")&&(a=a.slice(0,1));let l=[];for(let[d,c]of a){let u=o.full_text.substring(d,d+c),f=e.new_text||"";if(/^\{#cell:[^}]+\}$/.test(u.trim())){let y=f;y=y.split(u.trim()).join("");let b=o.spans.find(v=>v.start<=d&&d<v.end&&v.paragraph!==null);if(b&&y){let v=o.spans.filter(N=>N.end<=d&&N.run!==null&&N.paragraph!==null&&N.paragraph._element===b.paragraph._element).map(N=>N.text).join("");if(v){for(let N of [v,v.replace(/\s+$/,"")])if(N&&y.startsWith(N)){y=y.substring(N.length).replace(/^\s+/,"");break}y&&!/\s$/.test(v)&&!/^\s/.test(y)&&(y=" "+y);}}y?l.push({type:"modify",target_text:"",new_text:y,comment:e.comment,_match_start_index:d,_internal_op:"INSERTION",_active_mapper_ref:o}):e.comment&&l.push({type:"modify",target_text:"",new_text:"",comment:e.comment,_match_start_index:d,_internal_op:"COMMENT_ONLY",_active_mapper_ref:o});continue}if(t&&f){try{f=u.replace(an(e.target_text),f);}catch{}G._flag_surviving_python_backreference(e,f);}f=Ha(u,e.target_text,f),f=G._restore_matched_whitespace(u,e.target_text,f);let h=G._reinject_anchor_markers(o,d,c,e.target_text,f);if(h===null)continue;f=h,e._preview_span||(e._preview_span=[d,c],e._preview_matched_text=u,e._preview_new_text=f,e._preview_mapper_ref=o);let[_,p]=this._parse_markdown_style(e.target_text),[m,w]=this._parse_markdown_style(f);if(p!==w&&this._match_spans_whole_paragraph(o,d,c)){let[y]=this._parse_markdown_style(u),b=y,v=m,N=b===v?"STYLE_ONLY":"STYLE_AND_TEXT",k=u.indexOf(y),x=d+(k!==-1?k:0),P=w!==null?w:"Normal";l.push({type:"modify",target_text:b,new_text:v,comment:e.comment,_match_start_index:x,_internal_op:N,_new_style:P,_active_mapper_ref:o});continue}for(let y of this._resolve_single_match(e,d,c,o,u,f))l.push(y);}return l.length===0?null:r==="all"||l.length>1?l:l[0]}_split_around_kept_markers(e,t,r,i,s){if(i===s||!i.includes("]("))return null;let o=[...i.matchAll(Bi)],a=[...s.matchAll(Bi)];if(o.length===0||o.length!==a.length||o.some((f,h)=>f[0]!==a[h][0]))return null;let l=[],d=e.comment,c=0,u=0;for(let f=0;f<=o.length;f++){let h=o[f],_=a[f],p=i.substring(c,h?h.index:i.length),m=s.substring(u,_?_.index:s.length);if(p!==m){let w={type:"modify",target_text:p,new_text:m,comment:d};d=null,l.push(...this._resolve_single_match(w,t+c,p.length,r,p,m));}h&&_&&(c=h.index+h[0].length,u=_.index+_[0].length);}for(let f of l)f._split_group_id=t;return l.length>0?l:null}_resolve_single_match(e,t,r,i,s,o){let a=this._split_around_kept_markers(e,t,i,s,o);if(a!==null)return a;let l=[];if(s===o||e.target_text===o)return l.push({type:"modify",target_text:s,new_text:s,comment:e.comment,_match_start_index:t,_internal_op:"COMMENT_ONLY",_active_mapper_ref:i}),l;let d=false;if(i&&(d=i.spans.some(y=>y.text===" | "&&(y.run===null||y.run===void 0)&&y.start<t+r&&y.end>t)),d){let y=s.split("|"),b=o.split("|");if(y.length!==b.length)throw new Vt([`Target text spans ${y.length} table cells, but replacement provides ${b.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(y.length>1){let v=[],N=0,k=0;for(let x=0;x<y.length;x++)if(y[x].trim()!==b[x].trim()){k=x;break}for(let x=0;x<y.length;x++){let P=y[x],E=b[x],T=P.trim(),I=E.trim(),D=t+N+(T?P.indexOf(T):0),F=e.comment!==null&&e.comment!==void 0&&x===k;if(T!==I||F){let M=this._word_diff_sub_edits(T,I,D,F?e.comment:null,true,i);for(let B of M)B._original_target_text=e.target_text,B._split_group_id=t,v.push(B);}N+=P.length+1;}for(let x of v)l.push(x);return l}}let c=false;e.target_text&&(e.target_text.includes("**")||e.target_text.includes("_"))&&(c=true),o&&(o.includes("**")||o.includes("_"))&&(c=true);let u="",f="",h="",_=t;if(o.startsWith(s))u="INSERTION",h=o.substring(s.length),_=t+r;else {let[y,b]=ft(s,o),v=s.length-b,N=o.length-b;f=s.substring(y,v),h=o.substring(y,N),_=t+y;}if(c){if(!f&&h)u="INSERTION";else if(f&&!h)u="DELETION";else if(f&&h)u="MODIFICATION";else return l.push({type:"modify",target_text:f,new_text:h,comment:e.comment,_match_start_index:_,_internal_op:"COMMENT_ONLY",_active_mapper_ref:i}),l;return l.push({type:"modify",target_text:f,new_text:h,comment:e.comment,_resolved_start_idx:_,_match_start_index:_,_internal_op:u,_active_mapper_ref:i}),l}let p=s.split(`
|
|
149
160
|
|
|
150
161
|
`),m=o.split(`
|
|
151
162
|
|
|
152
163
|
`);if(s.includes(`
|
|
153
164
|
|
|
154
|
-
`)&&p.length===m.length){let y=[],b=t,v=false;for(let N=0;N<p.length;N++){let k=p[N],x=m[N];if(k!==x){let
|
|
165
|
+
`)&&p.length===m.length){let y=[],b=t,v=false;for(let N=0;N<p.length;N++){let k=p[N],x=m[N];if(k!==x){let P=e.comment&&!v?e.comment:null,E=this._word_diff_sub_edits(k,x,b,P,false,i);E.some(T=>T.comment!==null&&T.comment!==void 0)&&(v=true);for(let T of E)T._split_group_id=t,y.push(T);}b+=k.length+2;}if(y.length>0){for(let N of y)l.push(N);return l}}if(!f&&h)return l.push({type:"modify",target_text:"",new_text:h,comment:e.comment,_resolved_start_idx:_,_match_start_index:_,_internal_op:"INSERTION",_active_mapper_ref:i}),l;let w=this._word_diff_sub_edits(s,o,t,e.comment,false,i);for(let y of w)y._split_group_id=t,l.push(y);return l}_insert_and_split_ins(e,t,r,i=false){let s=e.parentNode;if(!s)return;let o=e.cloneNode(false),a=e.cloneNode(false),l=false;for(let d of Array.from(e.childNodes))e.removeChild(d),i&&d===t&&(l=true),l?a.appendChild(d):(o.appendChild(d),d===t&&(l=true));o.childNodes.length>0&&s.insertBefore(o,e),s.insertBefore(r,e),a.childNodes.length>0&&s.insertBefore(a,e),s.removeChild(e);}_apply_comment_only(e,t,r,i,s){let o=t.find_target_runs_by_index(r,i,s);if(o.length===0)return false;if(!e.comment)return true;let a=o[0]._element,l=o[o.length-1]._element,d=a;for(;d&&d.tagName!=="w:p";)d=d.parentNode;let c=l;for(;c&&c.tagName!=="w:p";)c=c.parentNode;if(!d||!c)return false;let u=g((_,p)=>{let m=_;for(;m.parentNode&&m.parentNode!==p;)m=m.parentNode;return m},"ascend_to_paragraph_child"),f=u(a,d),h=u(l,c);return d===c?this._attach_comment(d,f,h,e.comment):this._attach_comment_spanning(d,f,c,h,e.comment),true}_apply_single_edit_indexed(e,t,r){let i=e._internal_op,s=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,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),d=null;if(i==="STYLE_ONLY"||i==="STYLE_AND_TEXT"){let[v,N]=s.get_insertion_anchor(o,r),k=null;if(N)k=N._element;else if(v){let x=v._element;for(;x&&x.tagName!=="w:p";)x=x.parentNode;k=x;}if(k&&e._new_style&&(i==="STYLE_ONLY"?this._set_paragraph_style(k,e._new_style,this._getNextId()):d=k),i==="STYLE_ONLY"){if(e.comment){let x=s.find_target_runs_by_index(o,a,r);if(x.length>0){let P=x[0]._element,E=x[x.length-1]._element,T=P;for(;T&&T.tagName!=="w:p";)T=T.parentNode;let I=E;for(;I&&I.tagName!=="w:p";)I=I.parentNode;if(T&&I){let D=g((B,j)=>{let C=B;for(;C.parentNode&&C.parentNode!==j;)C=C.parentNode;return C},"ascend_to_paragraph_child"),F=D(P,T),M=D(E,I);T===I?this._attach_comment(T,F,M,e.comment):this._attach_comment_spanning(T,F,I,M,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,u=["INSERTION","MODIFICATION"].includes(i)?(e._reserved_ins_id??null)!==null?String(e._reserved_ins_id):this._getNextId():null;if(d&&e._new_style&&this._set_paragraph_style(d,e._new_style,u??c??this._getNextId()),i==="COMMENT_ONLY")return this._apply_comment_only(e,s,o,a,r);if(i==="INSERTION"){let v=e.new_text||"",N=null,k=typeof s.part_boundary_at=="function"?s.part_boundary_at(o):null,x=!e.target_text&&(e._parent_edit_ref===void 0||e._parent_edit_ref===null);if(k!==null&&x){let[j,C]=k,S=s.part_kind_of(j),A=s.part_kind_of(C);if(S==="body"&&A!=="body"){let O=s.spans.filter(L=>L.run!==null&&L.part_index===j);O.length>0&&(N=O[O.length-1]);}}let P,E;if(N!==null?(P=N.run,E=N.paragraph,v.startsWith(`
|
|
155
166
|
`)||(v=`
|
|
156
167
|
|
|
157
|
-
`+v)):e._insert_host_el?(C=null,E=null):[C,E]=s.get_insertion_anchor(o,r),!C&&!E&&!e._insert_host_el||V._introduces_table_row_text(s,o,1,"",v))return false;let P=v,I=N===null&&/\n\s*$/.test(P),M=null;{let T=s.spans.filter(O=>O.paragraph!==null&&O.start===o);T.length>0&&T[0].paragraph&&(M=T[0].paragraph._element);}if(I&&M&&M.parentNode){let T=M.parentNode,O=this.doc.part._element.ownerDocument,D=P.split(/[\r\n]+/).filter(z=>z!==""),A=null,$=null,W=null;for(let z of D){let[H,L]=this._parse_markdown_style(z),X=O.createElement("w:p");if(L)this._set_paragraph_style(X,L);else {let oe=S(M,"w:pPr");oe&&X.appendChild(this._clone_pPr_scrubbing_headings(oe,M));}let U=S(X,"w:pPr");U||(U=O.createElement("w:pPr"),X.insertBefore(U,X.firstChild));let G=S(U,"w:rPr");G||(G=O.createElement("w:rPr"),U.appendChild(G)),G.appendChild(this._create_track_change_tag("w:ins","",d));let se=this._build_tracked_ins_for_line(H,C,d,O,c);se&&X.appendChild(se),T.insertBefore(X,M),A||(A=X),$=X,W=se;}if(A){if(e.comment&&$&&W){let z=g((L,X)=>{let U=L;for(;U.parentNode&&U.parentNode!==X;)U=U.parentNode;return U},"ascend"),H=R(A,"w:ins")[0]||A;this._attach_comment_spanning(A,z(H,A),$,z(W,$),e.comment);}return true}}let j=this._track_insert_multiline(v,C,E,d,null,c,o===0||C===null&&E!==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(C){let T=C._element,O=T.parentNode;O&&O.tagName==="w:del"&&(T=O,O=T.parentNode);let D=o===0;O&&O.tagName==="w:ins"?this._insert_and_split_ins(O,T,j.first_node,D):D&&O?O.insertBefore(j.first_node,T):at(j.first_node,T);}else if(E){let T=E._element,O=T.firstChild;for(;O&&O.tagName==="w:pPr";)O=O.nextSibling;T.insertBefore(j.first_node,O);}}if(e.comment){let T=g((O,D)=>{let A=O;for(;A.parentNode&&A.parentNode!==D;)A=A.parentNode;return A},"ascend_to_paragraph_child");if(j.last_p&&j.last_ins){let O=j.first_node;for(;O&&O.tagName!=="w:p";)O=O.parentNode;if(O){let D=j.first_node;j.first_node.tagName==="w:p"&&(D=R(j.first_node,"w:ins")[0]||j.first_node);let A=T(D,O),$=T(j.last_ins,j.last_p);this._attach_comment_spanning(O,A,j.last_p,$,e.comment);}}else {let O=j.first_node;for(;O&&O.tagName!=="w:p";)O=O.parentNode;if(O){let D=j.first_node;j.first_node.tagName==="w:p"&&(D=R(j.first_node,"w:ins")[0]||j.first_node);let A=T(D,O);this._attach_comment(O,A,A,e.comment);}}}return true}if((i==="DELETION"||i==="MODIFICATION")&&a&&s.part_ranges.filter(v=>v[1]>v[0]).length>1){let v=new Set;for(let N of s.spans)N.run!==null&&N.end>o&&N.start<o+a&&v.add(N.part_index);if(v.size>1)return false}if((i==="DELETION"||i==="MODIFICATION")&&a){let v=this._apply_gate_refusal(s,o,a,e._parent_edit_ref?.type==="set_field");if(v)return e._error_msg||(e._error_msg=v),false}let f=s.find_target_runs_by_index(o,a,r),h=s.get_virtual_spans_in_range(o,a);if(f.length===0&&h.length===0)return false;let _=new Set;for(let v of f){let N=v._element.parentNode;for(;N&&N.tagName!=="w:p";)N=N.parentNode;N&&_.add(N);}let p=null,m=null;for(let v of f){let N=m!==null&&v._element.previousSibling===m,k=N?m:this._create_track_change_tag("w:del","",p===null?l:null),x=v._element.cloneNode(true);Array.from(x.getElementsByTagName("w:t")).forEach(E=>{let P=x.ownerDocument.createElement("w:delText");P.textContent=E.textContent,E.hasAttribute("xml:space")&&P.setAttribute("xml:space","preserve"),x.replaceChild(P,E);}),k.appendChild(x),N?v._element.parentNode?.removeChild(v._element):v._element.parentNode?.replaceChild(k,v._element),p===null&&(p=k),m=k;}let w=null,y=null,b=null;if(i==="MODIFICATION"&&e.new_text&&m){let v=m;for(;v&&v.tagName!=="w:p";)v=v.parentNode;let N=v?new ne(v,null):null,k=f.length>0?f[f.length-1]:null,x=this._track_insert_multiline(e.new_text,k,N,d,m,c);if(x.first_node){if(x.first_node.tagName==="w:ins"){let E=m.parentNode;E&&E.tagName==="w:ins"?this._insert_and_split_ins(E,m,x.first_node):at(x.first_node,m),w=x.first_node;}else w=x.last_ins;y=x.last_p,b=x.last_ins;}}if(i==="DELETION"||i==="MODIFICATION"){if(i==="MODIFICATION"&&f.length===0&&h.length>0&&e.new_text){let v=h[0];if(v.paragraph){let N=v.paragraph._element,k=R(N,"w:r"),x=k.length>0?new je(k[k.length-1],v.paragraph):null,C=this._track_insert_multiline(e.new_text,x,v.paragraph,d,null,c);C.first_node&&N.appendChild(C.first_node);}}for(let v of [...h].reverse())if(v.paragraph){let N=v.paragraph._element,k=Te(N);for(;k&&k.tagName!=="w:p";)k=Te(k);if(k&&k.tagName==="w:p"){let x=!this._paragraph_has_visible_content(N),C=S(N,"w:pPr");if(x){let I=S(k,"w:pPr"),M=I?I.cloneNode(true):N.ownerDocument.createElement("w:pPr");if(C){let j=S(C,"w:sectPr");j&&!S(M,"w:sectPr")&&M.appendChild(j.cloneNode(true)),N.removeChild(C);}N.insertBefore(M,N.firstChild),C=M;}C||(C=N.ownerDocument.createElement("w:pPr"),N.insertBefore(C,N.firstChild));let E=S(C,"w:rPr");if(E||(E=N.ownerDocument.createElement("w:rPr"),C.appendChild(E)),!S(E,"w:del")){let I=this._create_track_change_tag("w:del","",l);E.appendChild(I);}let P=Array.from(k.childNodes);for(let I of P)I.nodeType===1&&I.tagName==="w:pPr"||N.appendChild(I);k.parentNode&&k.parentNode.removeChild(k);}}}if(e.comment&&p!==null){let v,N;if(y&&b)v=b,N=y;else {let P=w!==null?w:m;for(v=P,N=P;N&&N.tagName!=="w:p";)N=N.parentNode;}let k=p;for(;k&&k.tagName!=="w:p";)k=k.parentNode;if(!k||!N)return true;let x=g((P,I)=>{let M=P;for(;M.parentNode&&M.parentNode!==I;)M=M.parentNode;return M},"ascend_to_paragraph_child"),C=x(p,k),E=x(v,N);k===N?this._attach_comment(k,C,E,e.comment):this._attach_comment_spanning(k,C,N,E,e.comment);}for(let v of _)if(!this._paragraph_has_visible_content(v)){let k=S(v,"w:pPr");k||(k=v.ownerDocument.createElement("w:pPr"),v.insertBefore(k,v.firstChild));let x=S(k,"w:rPr");if(x||(x=v.ownerDocument.createElement("w:rPr"),k.appendChild(x)),!S(x,"w:del")){let C=this._create_track_change_tag("w:del","",l);x.appendChild(C);}}return true}},Uu=["{++","{--","{~~","{==","{>>"],Hu=/^> \*\*File Path:\*\*[^\n]*\n+/,Xu=/^> \*\*Page (\d+) of (\d+)\*\*[^\n]*\n+(?:---\n+)?/,qu=/\n+---\n+> \*\*Continues on page (\d+) of (\d+)\.\*\*[^\n]*\s*$/,Yu=/\n+---\n+> \*\*Appendix available\.\*\*[^\n]*\s*$/,Gu=2e3,vn=class extends Error{static{g(this,"TextRevisionError");}constructor(n){super(n),this.name="TextRevisionError";}},Ju=class extends vn{static{g(this,"TextRevisionVerificationError");}constructor(n,e,t,r,i){super(n),this.unverified_path=e,this.output_path=t,this.stats=r,this.unverified_bytes=i,this.name="TextRevisionVerificationError";}unverified_path;output_path;stats;unverified_bytes};function Qu(n){if(n&&n.trim())return n.trim();let e="".trim();return e||"Adeu AI (TS)"}g(Qu,"get_default_author");function Vu(n){if(Uu.some(e=>n.includes(e)))throw new vn("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(Vu,"check_criticmarkup");function Ku(n){n=n.replace(Hu,"");let e=null,t=null,r=Xu.exec(n);r&&(e=parseInt(r[1],10),t=parseInt(r[2],10),n=n.slice(r[0].length)),n=n.replace(Yu,"");let i=qu.exec(n);return i&&(e===null&&(e=parseInt(i[1],10)-1),t===null&&(t=parseInt(i[2],10)),n=n.slice(0,i.index)),{text:n,page:e,total:t}}g(Ku,"strip_page_chrome");function Zu(n,e,t=false,r){if(t)return;let i=n.length,s=e.length;if(i===0)return;let o=(i-s)/i,a=i>=Gu?.5:.75;if(o<=a)return;let c=r?`'${r}'`:"The revised text";throw new vn(`${c} is ~${Math.floor(o*100)}% shorter than the document's clean text (${s.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.
|
|
168
|
+
`+v)):e._insert_host_el?(P=null,E=null):[P,E]=s.get_insertion_anchor(o,r),!P&&!E&&!e._insert_host_el||G._introduces_table_row_text(s,o,1,"",v))return false;let T=v,I=N===null&&/\n\s*$/.test(T),D=null;{let j=s.spans.filter(C=>C.paragraph!==null&&C.start===o);j.length>0&&j[0].paragraph&&(D=j[0].paragraph._element);}if(I&&D&&D.parentNode){let j=D.parentNode,C=this.doc.part._element.ownerDocument,S=T.split(/[\r\n]+/).filter(H=>H!==""),A=null,O=null,L=null;for(let H of S){let[q,z]=this._parse_markdown_style(H),U=C.createElement("w:p");if(z)this._set_paragraph_style(U,z);else {let fe=$(D,"w:pPr");fe&&U.appendChild(this._clone_pPr_scrubbing_headings(fe,D));}let X=$(U,"w:pPr");X||(X=C.createElement("w:pPr"),U.insertBefore(X,U.firstChild));let te=$(X,"w:rPr");te||(te=C.createElement("w:rPr"),X.appendChild(te)),te.insertBefore(this._create_track_change_tag("w:ins","",u),te.firstChild);let V=this._build_tracked_ins_for_line(q,P,u,C,l);V&&U.appendChild(V),j.insertBefore(U,D),A||(A=U),O=U,L=V;}if(A){if(e.comment&&O&&L){let H=g((z,U)=>{let X=z;for(;X.parentNode&&X.parentNode!==U;)X=X.parentNode;return X},"ascend"),q=R(A,"w:ins")[0]||A;this._attach_comment_spanning(A,H(q,A),O,H(L,O),e.comment);}return true}}let F=l;o>0&&P&&s.spans.some(j=>j.end===o&&j.run===null&&(j.text.includes("*")||j.text.includes("_")))&&(F=true);let M=this._track_insert_multiline(v,P,E,u,null,F,o===0||P===null&&E!==null);if(!M.first_node)return false;if(M.first_node.tagName==="w:ins"){if(e._insert_host_el)e._insert_host_el.appendChild(M.first_node);else if(P){let j=P._element,C=j.parentNode;C&&C.tagName==="w:del"&&(j=C,C=j.parentNode);let S=o===0;C&&C.tagName==="w:ins"?this._insert_and_split_ins(C,j,M.first_node,S):S&&C?C.insertBefore(M.first_node,j):ut(M.first_node,j);}else if(E){let j=E._element,C=j.firstChild;for(;C&&C.tagName==="w:pPr";)C=C.nextSibling;j.insertBefore(M.first_node,C);}}if(e.comment){let j=g((C,S)=>{let A=C;for(;A.parentNode&&A.parentNode!==S;)A=A.parentNode;return A},"ascend_to_paragraph_child");if(M.last_p&&M.last_ins){let C=M.first_node;for(;C&&C.tagName!=="w:p";)C=C.parentNode;if(C){let S=M.first_node;M.first_node.tagName==="w:p"&&(S=R(M.first_node,"w:ins")[0]||M.first_node);let A=j(S,C),O=j(M.last_ins,M.last_p);this._attach_comment_spanning(C,A,M.last_p,O,e.comment);}}else {let C=M.first_node;for(;C&&C.tagName!=="w:p";)C=C.parentNode;if(C){let S=M.first_node;M.first_node.tagName==="w:p"&&(S=R(M.first_node,"w:ins")[0]||M.first_node);let A=j(S,C);this._attach_comment(C,A,A,e.comment);}}}return true}if((i==="DELETION"||i==="MODIFICATION")&&a&&s.part_ranges.filter(v=>v[1]>v[0]).length>1){let v=new Set;for(let N of s.spans)N.run!==null&&N.end>o&&N.start<o+a&&v.add(N.part_index);if(v.size>1)return false}if((i==="DELETION"||i==="MODIFICATION")&&a){let v=this._apply_gate_refusal(s,o,a,e._parent_edit_ref?.type==="set_field");if(v)return e._error_msg||(e._error_msg=v),false}let f=s.find_target_runs_by_index(o,a,r),h=s.get_virtual_spans_in_range(o,a);if(f.length===0&&h.length===0)return false;let _=new Set;for(let v of f){let N=v._element.parentNode;for(;N&&N.tagName!=="w:p";)N=N.parentNode;N&&_.add(N);}let p=null,m=null;for(let v of f){let N=m!==null&&v._element.previousSibling===m,k=N?m:this._create_track_change_tag("w:del","",p===null?c:null),x=v._element.cloneNode(true);Array.from(x.getElementsByTagName("w:t")).forEach(E=>{let T=x.ownerDocument.createElement("w:delText");T.textContent=E.textContent,E.hasAttribute("xml:space")&&T.setAttribute("xml:space","preserve"),x.replaceChild(T,E);}),k.appendChild(x),N?v._element.parentNode?.removeChild(v._element):v._element.parentNode?.replaceChild(k,v._element),p===null&&(p=k),m=k;}let w=null,y=null,b=null;if(i==="MODIFICATION"&&e.new_text&&m){let v=m;for(;v&&v.tagName!=="w:p";)v=v.parentNode;let N=v?new ie(v,null):null,k=f.length>0?f[f.length-1]:null,x=this._track_insert_multiline(e.new_text,k,N,u,m,l);if(x.first_node){if(x.first_node.tagName==="w:ins"){let E=m.parentNode;E&&E.tagName==="w:ins"?this._insert_and_split_ins(E,m,x.first_node):ut(x.first_node,m),w=x.first_node;}else w=x.last_ins;y=x.last_p,b=x.last_ins;}}if(i==="DELETION"||i==="MODIFICATION"){if(i==="MODIFICATION"&&f.length===0&&h.length>0&&e.new_text){let v=h[0];if(v.paragraph){let N=v.paragraph._element,k=R(N,"w:r"),x=k.length>0?new Be(k[k.length-1],v.paragraph):null,P=this._track_insert_multiline(e.new_text,x,v.paragraph,u,null,l);P.first_node&&N.appendChild(P.first_node);}}for(let v of [...h].reverse())if(v.paragraph){let N=v.paragraph._element,k=le(N);for(;k&&k.tagName!=="w:p";)k=le(k);if(k&&k.tagName==="w:p"){let x=!this._paragraph_has_visible_content(N),P=!this._paragraph_has_visible_content(k),E=i==="DELETION"||!e.new_text;if(E&&x){let F=$(N,"w:pPr");F||(F=N.ownerDocument.createElement("w:pPr"),N.insertBefore(F,N.firstChild));let M=$(F,"w:rPr");if(M||(M=N.ownerDocument.createElement("w:rPr"),F.appendChild(M)),!$(M,"w:del")){let B=this._create_track_change_tag("w:del","",c),j=$(M,"w:ins");j?M.insertBefore(B,j.nextSibling):M.insertBefore(B,M.firstChild);}continue}if(E&&!x&&P)continue;let T=$(N,"w:pPr");if(x){let F=$(k,"w:pPr"),M=F?F.cloneNode(true):N.ownerDocument.createElement("w:pPr");if(T){let B=$(T,"w:sectPr");B&&!$(M,"w:sectPr")&&M.appendChild(B.cloneNode(true)),N.removeChild(T);}N.insertBefore(M,N.firstChild),T=M;}T||(T=N.ownerDocument.createElement("w:pPr"),N.insertBefore(T,N.firstChild));let I=$(T,"w:rPr");if(I||(I=N.ownerDocument.createElement("w:rPr"),T.appendChild(I)),!$(I,"w:del")){let F=this._create_track_change_tag("w:del","",c),M=$(I,"w:ins");M?I.insertBefore(F,M.nextSibling):I.insertBefore(F,I.firstChild);}let D=Array.from(k.childNodes);for(let F of D)F.nodeType===1&&F.tagName==="w:pPr"||N.appendChild(F);k.parentNode&&k.parentNode.removeChild(k);}}}if(e.comment&&p!==null){let v,N;if(y&&b)v=b,N=y;else {let T=w!==null?w:m;for(v=T,N=T;N&&N.tagName!=="w:p";)N=N.parentNode;}let k=p;for(;k&&k.tagName!=="w:p";)k=k.parentNode;if(!k||!N)return true;let x=g((T,I)=>{let D=T;for(;D.parentNode&&D.parentNode!==I;)D=D.parentNode;return D},"ascend_to_paragraph_child"),P=x(p,k),E=x(v,N);k===N?this._attach_comment(k,P,E,e.comment):this._attach_comment_spanning(k,P,N,E,e.comment);}for(let v of _)if(!this._paragraph_has_visible_content(v)){let k=$(v,"w:pPr");k||(k=v.ownerDocument.createElement("w:pPr"),v.insertBefore(k,v.firstChild));let x=$(k,"w:rPr");if(x||(x=v.ownerDocument.createElement("w:rPr"),k.appendChild(x)),!$(x,"w:del")){let P=this._create_track_change_tag("w:del","",c),E=$(x,"w:ins");E?x.insertBefore(P,E.nextSibling):x.insertBefore(P,x.firstChild);}}return true}},du=["w:tblStyle","w:tblpPr","w:tblOverlap","w:bidiVisual","w:tblStyleRowBandSize","w:tblStyleColBandSize","w:tblW","w:jc","w:tblCellSpacing","w:tblInd","w:tblBorders","w:shd","w:tblLayout","w:tblCellMar","w:tblLook","w:tblCaption","w:tblDescription","w:tblPrChange"],uu=["w:pStyle","w:keepNext","w:keepLines","w:pageBreakBefore","w:framePr","w:widowControl","w:numPr","w:suppressLineNumbers","w:pBdr","w:shd","w:tabs","w:suppressAutoHyphens","w:kinsoku","w:wordWrap","w:overflowPunct","w:topLinePunct","w:autoSpaceDE","w:autoSpaceDN","w:bidi","w:adjustRightInd","w:snapToGrid","w:spacing","w:ind","w:contextualSpacing","w:mirrorIndents","w:suppressOverlap","w:jc","w:textDirection","w:textAlignment","w:textboxTightWrap","w:outlineLvl","w:divId","w:cnfStyle","w:rPr","w:sectPr","w:pPrChange"],fu=["w:ins","w:del","w:moveFrom","w:moveTo","w:rStyle","w:rFonts","w:b","w:bCs","w:i","w:iCs","w:caps","w:smallCaps","w:strike","w:dstrike","w:outline","w:shadow","w:emboss","w:imprint","w:noProof","w:snapToGrid","w:vanish","w:webHidden","w:color","w:spacing","w:w","w:kern","w:position","w:sz","w:szCs","w:highlight","w:u","w:effect","w:bdr","w:shd","w:fitText","w:vertAlign","w:rtl","w:cs","w:em","w:lang","w:eastAsianLayout","w:specVanish","w:oMath","w:rPrChange"],hu=[["w:tblPr",new Map(du.map((n,e)=>[n,e]))],["w:pPr",new Map(uu.map((n,e)=>[n,e]))],["w:rPr",new Map(fu.map((n,e)=>[n,e]))]];function pu(n,e){let t=Array.from(n.childNodes),r=g(l=>l.nodeType===1&&e.has(l.tagName),"isKnown"),i=t.filter(r),s=[...i].sort((l,d)=>e.get(l.tagName)-e.get(d.tagName));if(s.every((l,d)=>l===i[d]))return false;let o=0,a=t.map(l=>r(l)?s[o++]:l);for(let l of t)n.removeChild(l);for(let l of a)n.appendChild(l);return true}g(pu,"reorder");function _u(n){let e=0;for(let[t,r]of hu)for(let i of R(n,t))pu(i,r)&&e++;return e}g(_u,"repair_schema_order");var mu=class extends Error{static{g(this,"ComparisonError");}details;constructor(n,e=[]){super(n),this.name="ComparisonError",this.details=e;}};async function io(n,e,t,r=true){let i=g(async p=>Xe(await ae.load(p),r,false,false,true),"extract"),{text:s,structure:o}=await i(n),{text:a,structure:l}=await i(e),{edits:d,warnings:c}=Nr(s,o,a,l),u=await ae.load(n),f=new Bt(u,t),[h,_]=f.apply_edits(d);if(_>0)throw new mu(`${_} of ${d.length} computed change(s) could not be written as tracked changes, so no redline was saved: a partial redline would show those passages as unchanged.`,[...f.skipped_details]);for(let p of f._revision_roots())_u(p);return {data:await u.save(),applied:h,warnings:[...c,...kr(new Uint8Array(n),new Uint8Array(e))]}}g(io,"build_redline_comparison");var wu=["{++","{--","{~~","{==","{>>"],yu=/^> \*\*File Path:\*\*[^\n]*\n+/,vu=/^> \*\*Page (\d+) of (\d+)\*\*[^\n]*\n+(?:---\n+)?/,bu=/\n+---\n+> \*\*Continues on page (\d+) of (\d+)\.\*\*[^\n]*\s*$/,xu=/\n+---\n+> \*\*Appendix available\.\*\*[^\n]*\s*$/,Nu=2e3,An=class extends Error{static{g(this,"TextRevisionError");}constructor(n){super(n),this.name="TextRevisionError";}},ku=class extends An{static{g(this,"TextRevisionVerificationError");}constructor(n,e,t,r,i){super(n),this.unverified_path=e,this.output_path=t,this.stats=r,this.unverified_bytes=i,this.name="TextRevisionVerificationError";}unverified_path;output_path;stats;unverified_bytes};function Cu(n){if(n&&n.trim())return n.trim();let e="".trim();return e||"Adeu AI (TS)"}g(Cu,"get_default_author");function Eu(n){if(wu.some(e=>n.includes(e)))throw new An("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(Eu,"check_criticmarkup");function Au(n){n=n.replace(yu,"");let e=null,t=null,r=vu.exec(n);r&&(e=parseInt(r[1],10),t=parseInt(r[2],10),n=n.slice(r[0].length)),n=n.replace(xu,"");let i=bu.exec(n);return i&&(e===null&&(e=parseInt(i[1],10)-1),t===null&&(t=parseInt(i[2],10)),n=n.slice(0,i.index)),{text:n,page:e,total:t}}g(Au,"strip_page_chrome");function Pu(n,e,t=false,r){if(t)return;let i=n.length,s=e.length;if(i===0)return;let o=(i-s)/i,a=i>=Nu?.5:.75;if(o<=a)return;let l=r?`'${r}'`:"The revised text";throw new An(`${l} is ~${Math.floor(o*100)}% shorter than the document's clean text (${s.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.
|
|
158
169
|
If the text is a partial extract, re-extract the ENTIRE document with \`--page all --clean-view\` and edit that.
|
|
159
|
-
If the mass deletion is intentional, re-run with --allow-major-deletions (over MCP: allow_major_deletions=True).`)}g(
|
|
160
|
-
`)t+="\\n";else if(r==="\r")t+="\\r";else if(r===" ")t+="\\t";else if(r===e)t+=`\\${e}`;else if(r!==" "&&
|
|
170
|
+
If the mass deletion is intentional, re-run with --allow-major-deletions (over MCP: allow_major_deletions=True).`)}g(Pu,"check_major_deletions");function lo(n){return n=n.replace(/([^|])\s+\{#cell:[^}]+\}/g,"$1"),n=n.replace(/\{#cell:[^}]+\}/g,""),n}g(lo,"strip_cell_anchors");function co(n){return Xe(n,true,false)}g(co,"_extract_clean_text_from_doc");function Wi(n){return lo(n.replace(/^#+\s*/gm,""))}g(Wi,"_normalize_virtual_projection_text");var Tu=new RegExp("\\p{C}|\\p{Z}","u");function zi(n){let e=n.includes("'")&&!n.includes('"')?'"':"'",t="";for(let r of n)if(r==="\\")t+="\\\\";else if(r===`
|
|
171
|
+
`)t+="\\n";else if(r==="\r")t+="\\r";else if(r===" ")t+="\\t";else if(r===e)t+=`\\${e}`;else if(r!==" "&&Tu.test(r)){let i=r.codePointAt(0),[s,o]=i<256?["x",2]:i<65536?["u",4]:["U",8];t+=`\\${s}${i.toString(16).padStart(o,"0")}`;}else t+=r;return `${e}${t}${e}`}g(zi,"_repr");function $u(n,e){let t=co(n),r=Wi(t.trim()),i=Wi(e.trim());if(r!==i){let s=Array.from(r),o=Array.from(i),a=0,l=Math.min(s.length,o.length);for(;a<l&&s[a]===o[a];)a++;let d=s.slice(a,a+40).join(""),c=o.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 ${zi(d)}, supplied text reads ${zi(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($u,"verify_clean_text");function Su(n){let e=path.dirname(n),t=path.basename(n),r=t.lastIndexOf("."),i=r===-1?t:t.slice(0,r);return i.endsWith("_redlined")||i.endsWith("_processed")?n:path.join(e,`${i}_redlined.docx`)}g(Su,"_default_output_path");function Iu(n){let e=path.basename(n,path.extname(n));return path.join(path.dirname(n),`${e}.unverified.docx`)}g(Iu,"_unverified_path");async function uo(n){let{doc:e,input_path:t,revised_text:r}=n,{text:i,page:s,total:o}=Au(r),a=lo(i);if(o!==null&&o>1)throw new An(`Text revision looks like page ${s||"?"} 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.`);Eu(a);let l=co(e);Pu(l,a,n.allow_major_deletions??false);let d=tn(l,a),c=new Bt(e,Cu(n.author)),u=c.process_batch(d),f=n.output_path?n.output_path:Su(t),[h,_]=$u(c.doc,a);if(!h){let m=Iu(f),w=await c.doc.save(),y=`${_} Nothing was written to '${f}'; a diagnostic copy was kept at '${m}' \u2014 it is NOT the requested document.`;if(u.verified=false,u.verification_error=y,u.error="verification_failed",u.edits_skipped=(u.edits_applied||0)+(u.edits_skipped||0),u.edits_applied=0,u.actions_skipped=(u.actions_applied||0)+(u.actions_skipped||0),u.actions_applied=0,u.output_path=null,u.unverified_output_path=m,u.edits)for(let b of u.edits)b.status="failed",b.error="Not applied: post-apply verification failed.",b.critic_markup=null,b.clean_text=null;throw new ku(y,m,f,u,w)}let p=await c.doc.save();return u.output_path=f,u.verified=true,{stats:u,output_path:f,out_bytes:p}}g(uo,"apply_text_revision_core");var Ou=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(n,e="full",t=null){this.filename=n,this.mode=e,this.author=t;}add_transform_lines(n){for(let e of n){let t=e.toLowerCase();t.includes("tracked change")||t.includes("insertion")||t.includes("deletion")||t.includes("accepted")?this.change_lines.push(e):t.includes("author")||t.includes("template")||t.includes("company")||t.includes("manager")||t.includes("metadata")||t.includes("timestamp")||t.includes("custom xml")||t.includes("custom propert")||t.includes("identifier")||t.includes("document variable")||t.includes("language")||t.includes("version")||t.includes("last modified by")||t.includes("revision count")||t.includes("last printed")||t.includes("description/comments")?this.metadata_lines.push(e):t.includes("comment")||t.includes("[open]")||t.includes("[resolved]")?t.includes("kept")||t.includes("visible")?this.kept_comment_lines.push(e):this.removed_comment_lines.push(e):t.includes("hyperlink")||t.includes("warning")?this.warnings.push(e):this.structural_lines.push(e);}}render(){let n="\u2550".repeat(50),e=[n,`Finalization Report: ${this.filename}`],t=[];if(this.mode==="keep-markup"&&t.push("--keep-markup"),this.author&&t.push(`--author "${this.author}"`),this.tracked_changes_accepted>0&&t.push("--accept-all"),t.length>0&&e.push(`Options: ${t.join(" ")}`),e.push(n),this.status==="blocked")return e.push(""),e.push(`BLOCKED: ${this.blocked_reason}`),e.push(n),e.join(`
|
|
161
172
|
`);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(n),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(n),e.join(`
|
|
162
|
-
`)}};async function
|
|
173
|
+
`)}};async function fo(n,e){let t=new Ou(e.filename,e.sanitize_mode||"full",e.author||null);if(e.sanitize_mode==="full"){let s=yi(n),o=s[0]+s[1]+s[2];if(t.tracked_changes_found=o,o>0&&!e.accept_all)return t.status="blocked",t.blocked_reason=`Document contains ${o} unresolved tracked changes (${s[0]} insertions, ${s[1]} deletions, ${s[2]} formatting). Review in Word first, set accept_all=true, or set sanitize_mode='keep-markup'.`,{reportText:t.render()};if(o>0){let l=oc(n);l.size>1&&t.warnings.push(`Multiple authors detected in tracked changes: ${Array.from(l).sort().join(", ")}. Review per-change list before sending.`);let d=Yt(n);t.add_transform_lines(ac(n)),t.tracked_changes_accepted=o;let c=new Set(Yt(n).comments.map(f=>f.id)),u=d.comments.filter(f=>!c.has(f.id));if(u.length>0){t.comments_removed+=u.length,t.removed_comment_lines.push(`Comments removed: ${u.length} (anchored to auto-accepted tracked changes)`);for(let f of u){let h=f.resolved?"[Resolved]":"[Open]";t.removed_comment_lines.push(` ${h} "${We(f.text||"",60)}" (${f.author||"Unknown"})`);}}}let a=Yt(n);t.comments_removed+=a.total,t.add_transform_lines(lc(n)),cc(n);}else if(e.sanitize_mode==="keep-markup"){let s=yi(n);t.tracked_changes_found=s[0]+s[1]+s[2],t.tracked_changes_kept=t.tracked_changes_found;let o=Yt(n);t.comments_kept=o.open;for(let a of o.comments)a.resolved||t.kept_comment_lines.push(`"${We(a.text||"",60)}" (${a.author||"Unknown"})`);e.author&&(t.add_transform_lines(dc(n,e.author)),t.add_transform_lines(uc(n,e.author)));}t.add_transform_lines(tc(n)),t.add_transform_lines(nc(n)),t.add_transform_lines(rc(n)),t.add_transform_lines(ic(n)),t.add_transform_lines(sc(n)),t.add_transform_lines(ec(n)),t.add_transform_lines(pc(n)),t.add_transform_lines(_c(n)),t.add_transform_lines(mc(n)),t.add_transform_lines(gc(n)),t.add_transform_lines(wc(n)),t.add_transform_lines(yc(n));let r=bc(n);for(let s of r)t.warnings.push(s);for(let s of vc(n))t.warnings.push(s);if(t.add_transform_lines(fc(n)),t.add_transform_lines(hc(n)),e.protection_mode==="read_only"||e.protection_mode==="encrypt"){e.protection_mode==="encrypt"&&t.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 s=n.pkg.getPartByPath("word/settings.xml");if(s){let o=s._element.ownerDocument,a=ne(s._element,"documentProtection")[0];a||(a=o.createElement("w:documentProtection"),s._element.appendChild(a)),a.setAttribute("w:edit","readOnly"),a.setAttribute("w:enforcement","1"),t.structural_lines.push("Document locked (Read-Only enforcement injected into settings.xml)");}}e.export_pdf&&t.warnings.push("PDF export requires the Python/Word COM environment and is skipped in this zero-dependency Node agent.");for(let s of n.pkg.parts)if((s===n.part||s.contentType.includes("wordprocessingml")&&s.contentType.endsWith("+xml"))&&s._element.hasAttribute("xmlns:w16du")){let o=false;if(Array.from(s._element.attributes||[]).some(a=>a.name.startsWith("w16du:")&&a.name!=="xmlns:w16du")&&(o=true),!o){let a=R(s._element,"*");for(let l of a)if(l.tagName.startsWith("w16du:")||Array.from(l.attributes||[]).some(d=>d.name.startsWith("w16du:"))){o=true;break}}o||s._element.removeAttribute("xmlns:w16du");}t.warnings.length>0&&(t.status="clean_with_warnings");let i=await n.save();return Ru(i),{reportText:t.render(),outBuffer:i}}g(fo,"finalize_document");var Du=[["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 Ru(n){let e=at(new Uint8Array(n)),t=Object.keys(e),r=[];if(t.includes("docProps/custom.xml")&&r.push("docProps/custom.xml (custom document properties) is still in the package"),t.some(i=>i.startsWith("customXml/"))&&r.push("customXml/* parts are still in the package"),t.includes("docProps/core.xml")){let i=Ke(Je(e["docProps/core.xml"]));for(let[s,o]of Du)for(let a of ne(i.documentElement,s))(a.textContent||"").trim()&&r.push(`core property ${o} still contains a value`);}if(t.includes("word/settings.xml")){let i=Ke(Je(e["word/settings.xml"]));ne(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:
|
|
163
174
|
- `+r.join(`
|
|
164
175
|
- `)+`
|
|
165
|
-
Refusing to report a clean document.`)}g(
|
|
166
|
-
`):t,o=s.toLowerCase();if(r==="BatchValidationError"){let a="Batch validation failed.",
|
|
167
|
-
`+s;o.includes("target text not found")?(a="An edit could not be applied: target text not found.",
|
|
168
|
-
`+s):o.includes("comment range from another author")?(a="A match_mode='all' edit would sweep through another author's comment range.",
|
|
169
|
-
`+s):o.includes("another author")||o.includes("nested")?(a="An edit overlaps with a pending tracked change by another author.",
|
|
170
|
-
`+s):o.includes("control character")?(a="An edit contains invalid XML control characters.",
|
|
171
|
-
`+s):o.includes("criticmarkup tags")&&(a="Do not manually include CriticMarkup tags in new_text.",
|
|
176
|
+
Refusing to report a clean document.`)}g(Ru,"verifySanitizedPackage");var Mu=/\r\n|[\n\r\v\f\u001c-\u001e\u0085\u2028\u2029]/;var Tt="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 ju=new Set(["invalid_changes_file","batch_validation_failed"]);function ho(n,e,t,r){let i=t.split(Mu).map(o=>o.trim()).filter(Boolean).join(" ");ju.has(n)&&!i.includes(Tt)&&(i=i?`${i} ${Tt}`:Tt);let s={error:n,failed:e.map(([o,a])=>({index:o,reason:a})),message:i};return r!=null&&(s.errors=r),s}g(ho,"failure_envelope");var de="application/vnd.openxmlformats-officedocument.wordprocessingml.document",_o="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 gt(n){return {show:{resource:["document"],operation:[n]}}}g(gt,"docOpDisplayOptions");function mo(n,e){return e.split(".").reduce((t,r)=>{if(!(typeof t!="object"||t===null)&&Object.hasOwn(t,r))return t[r]},n)}g(mo,"getNestedProperty");async function Bu(n,e){let t=this.getInputData()[n];if(!t.binary||!t.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:n});let r=t.binary[e],i=await this.helpers.getBinaryDataBuffer(n,e),s=r.fileName??"document.docx";return {buffer:i,fileName:s}}g(Bu,"getDocxBuffer");async function ue(n,e){if(e.mode==="fromInput")return Bu.call(this,n,e.binaryPropertyName);let{sourceNodeName:t,binaryPropertyName:r}=e,i="sourceBinaryId"in e?e.sourceBinaryId:void 0;if(i&&i.trim()!=="")try{let u=await this.helpers.getBinaryStream(i);return {buffer:await this.helpers.binaryToBuffer(u),fileName:"document.docx"}}catch(u){throw new n8nWorkflow.NodeApiError(this.getNode(),{message:u.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:n})}if(!t||t.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:n});let s=t.replace(/'/g,"\\'"),o=`{{ $('${s}').first().binary.${r} }}`,a;try{a=this.evaluateExpression(o,n);}catch(u){throw new n8nWorkflow.NodeApiError(this.getNode(),{message:u.message},{message:`Failed to resolve binary from source node '${t}'.`,description:`Could not evaluate '${o}'. Verify the source node name is exactly correct (case-sensitive, including spaces and punctuation). Underlying error: ${u.message}`,itemIndex:n})}if(a==null||typeof a!="object"){let u=`{{ $('${s}').first().json }}`,f;try{f=this.evaluateExpression(u,n);}catch{f=void 0;}if(f==null)throw new n8nWorkflow.NodeApiError(this.getNode(),{message:"Source node produced no output"},{message:`Source node '${t}' has no output.`,description:`The expression '${o}' resolved to undefined and the node appears not to have executed in this run. Verify that '${t}' is upstream of this Adeu node, that its name matches exactly (case-sensitive), and that it has run successfully.`,itemIndex:n});let h="";try{let _=this.evaluateExpression(`{{ Object.keys($('${s}').first().binary || {}) }}`,n);Array.isArray(_)&&_.length>0?h=` Available binary properties on '${t}': `+_.map(p=>`'${p}'`).join(", ")+".":Array.isArray(_)&&_.length===0&&(h=` Source node '${t}' has no binary properties at all.`);}catch{}throw new n8nWorkflow.NodeApiError(this.getNode(),{message:"Binary property not found"},{message:`Source node '${t}' 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:n})}let l=a,d;try{if(l.id){let u=await this.helpers.getBinaryStream(l.id);d=await this.helpers.binaryToBuffer(u);}else if(l.data)d=Buffer.from(l.data,"base64");else throw new Error("Resolved binary metadata has neither an 'id' nor 'data' field.")}catch(u){throw new n8nWorkflow.NodeApiError(this.getNode(),{message:u.message},{message:`Failed to read binary content from source node '${t}'.`,description:`The binary metadata was found on property '${r}', but its contents could not be loaded. Underlying error: ${u.message}`,itemIndex:n})}let c=l.fileName??"document.docx";return {buffer:d,fileName:c}}g(ue,"getDocxBufferFromSource");function Ye(n,e){let t=n.lastIndexOf(".");return `${t===-1?n:n.substring(0,t)}_${e}.docx`}g(Ye,"buildOutputFileName");var po={strict:"strict",exact:"strict",single:"strict",first:"first","first-occurrence":"first","first-only":"first",first_only:"first",firstonly:"first",all:"all",global:"all",bulk:"all",alloccurrences:"all",all_occurrences:"all","all-occurrences":"all",every:"all"};function Fu(n){if(n===null||typeof n!="object"||Array.isArray(n))return;let e=typeof n.comment=="string"&&n.comment.trim()!==""||Array.isArray(n.comment)&&n.comment.some(t=>t&&typeof t.text=="string"&&t.text.trim()!=="");if((!("type"in n)||n.type===void 0||n.type===null)&&("cells"in n?n.type="insert_row":"text"in n&&"target_id"in n?n.type="reply":"field"in n&&"value"in n?n.type="set_field":"target_text"in n&&("new_text"in n||e)&&(n.type="modify")),n.type==="modify"&&(n.new_text===void 0||n.new_text===null)&&typeof n.target_text=="string"&&e&&(n.new_text=n.target_text),"match_mode"in n){let t=n.match_mode;if(typeof t!="string")delete n.match_mode;else {let r=t.trim().toLowerCase(),i=Object.hasOwn(po,r)?po[r]:void 0;i===void 0?delete n.match_mode:n.match_mode=i;}}}g(Fu,"coerceChangeItemInPlace");function go(n){return n.map(e=>{let t=e;if(typeof e=="string")try{let r=JSON.parse(e);t=r!==null&&typeof r=="object"?r:e;}catch{t=e;}return t!==null&&typeof t=="object"&&!Array.isArray(t)&&Fu(t),t})}g(go,"coerceChangesArray");function wo(n,e,t){if(n==null||n==="")throw new n8nWorkflow.NodeOperationError(this.getNode(),`Parameter "${t}" is empty`,{description:`Provide a JSON value for "${t}".`,itemIndex:e});if(typeof n=="object")return n;let r=n.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 "${t}" is not valid JSON`,{description:i.message,itemIndex:e})}}g(wo,"parseJsonParameter");function yo(n,e){let t=n.message??"Unknown error",r=n.name??"",i=n.errors,s=Array.isArray(i)?i.join(`
|
|
177
|
+
`):t,o=s.toLowerCase();if(r==="BatchValidationError"){let a="Batch validation failed.",l=`Review the listed failures:
|
|
178
|
+
`+s;o.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"+s):o.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"+s):o.includes("read-only")||o.includes("readonly")?(a="An edit targeted a read-only structural element.",l=`The Structural Appendix and locked cross-reference targets cannot be modified directly via text replacement (plain-text target_text resolves across hyperlinks, cross-references, and bookmarks automatically when kept intact):
|
|
179
|
+
`+s):o.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:
|
|
180
|
+
`+s):o.includes("another author")||o.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:
|
|
181
|
+
`+s):o.includes("control character")?(a="An edit contains invalid XML control characters.",l=`Remove non-printable control characters from your edit string before submitting:
|
|
182
|
+
`+s):o.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"+s);let d=n.failed??[],c=ho("batch_validation_failed",d,s,i),u=c.failed.length?`
|
|
172
183
|
|
|
173
184
|
Failed changes (0-based index into the submitted array):
|
|
174
|
-
`+
|
|
175
|
-
`):"";return new n8nWorkflow.NodeApiError(this.getNode(),
|
|
185
|
+
`+c.failed.map(f=>` [${f.index}] ${f.reason}`).join(`
|
|
186
|
+
`):"";return new n8nWorkflow.NodeApiError(this.getNode(),c,{message:a,description:`${l}${u}
|
|
176
187
|
|
|
177
|
-
${
|
|
188
|
+
${Tt}`,itemIndex:e})}return r==="TextRevisionVerificationError"?new n8nWorkflow.NodeApiError(this.getNode(),{message:t},{message:"The revised text could not be realized in the document, so nothing was applied.",description:`${t}
|
|
178
189
|
|
|
179
190
|
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:t},{message:"The revised text was refused before anything was applied.",description:`${t}
|
|
180
191
|
|
|
181
|
-
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:t},{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:t},{message:"Adeu engine error.",description:t,itemIndex:e})}g(so,"mapAdeuErrorToNodeApiError");function dd(n){if(!n||typeof n!="object")return false;let e=n;return typeof e.id=="string"&&typeof e.fileName=="string"&&typeof e.mimeType=="string"}g(dd,"isStashedBinaryEntry");var ao=[{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\\you\\.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 lo(n){let e=this.getNodeParameter("staticDataKey",n),t=this.getNodeParameter("outputBinaryPropertyName",n),r=this.getNodeParameter("onMissing",n),i=this.getNodeParameter("clearAfterRead",n),s=this.getWorkflowStaticData("global"),o=s[e];if(!dd(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:n});return [{json:{hydrated:false},pairedItem:{item:n}}]}let{id:a,fileName:c,mimeType:u}=o,l;try{let p=await this.helpers.getBinaryStream(a);l=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:n})}let d=u||Ne,f=await this.helpers.prepareBinaryData(l,c,d);i&&delete s[e];let h=this.getNodeParameter("outputPathTemplate",n,""),_;if(h.trim()!==""){let p=c.replace(/\.docx$/i,""),m=c.match(/\.docx$/i)?.[0]??".docx",w=new Date().toISOString().replace(/[:.]/g,"-").replace(/Z$/,"");_=h.replaceAll("{baseName}",p).replaceAll("{timestamp}",w).replaceAll("{fileName}",c).replaceAll("{ext}",m);}return [{json:{hydrated:true,fileName:c,sourceBinaryId:a,mimeType:d,..._!==void 0?{outputPath:_}:{}},binary:{[t]:f},pairedItem:{item:n}}]}g(lo,"executeHydrateToolOutput");var xr=_t("extractMarkdown"),co=[{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:xr},{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:xr},{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:xr},{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 uo(n){let e=this.getNodeParameter("binaryPropertyName",n),t=this.getNodeParameter("cleanView",n),r=this.getNodeParameter("includeAppendix",n,true),i=this.getNodeParameter("page",n,0),o=this.getNodeParameter("documentSource",n,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",n,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",n,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:a,fileName:c}=await le.call(this,n,o),u=await Ke(a,t,r);if(!i||i===0)return [{json:{fileName:c,cleanView:t,markdown:u},pairedItem:{item:n}}];let[l,d]=ut(u),f=dt(l,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:n});let h=f.pages[i-1];return [{json:{fileName:c,cleanView:t,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:n}}]}g(uo,"executeExtractMarkdown");var fo=[{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 ho(n){let e=this.getNodeParameter("binaryPropertyName",n),r=this.getNodeParameter("documentSource",n,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",n,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",n,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:i,fileName:s}=await le.call(this,n,r),o=await de.load(i),a=Ze(o,false,true,true),[c]=ut(a.text),u=dt(c,""),l=Is(o,c,u.body_pages,u.body_page_offsets,a.paragraph_offsets);return [{json:{fileName:s,total_pages:u.total_pages,outline:l.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:n}}]}g(ho,"executeExtractOutline");var ke={show:{resource:["document"],operation:["applyEdits"]}},po=[{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:ke},{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:ke},{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:ke},{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:ke},{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:ke},{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:`[
|
|
192
|
+
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:t},{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:t},{message:"Adeu engine error.",description:t,itemIndex:e})}g(yo,"mapAdeuErrorToNodeApiError");function Lu(n){if(!n||typeof n!="object")return false;let e=n;return typeof e.id=="string"&&typeof e.fileName=="string"&&typeof e.mimeType=="string"}g(Lu,"isStashedBinaryEntry");var bo=[{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\\you\\.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 xo(n){let e=this.getNodeParameter("staticDataKey",n),t=this.getNodeParameter("outputBinaryPropertyName",n),r=this.getNodeParameter("onMissing",n),i=this.getNodeParameter("clearAfterRead",n),s=this.getWorkflowStaticData("global"),o=s[e];if(!Lu(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:n});return [{json:{hydrated:false},pairedItem:{item:n}}]}let{id:a,fileName:l,mimeType:d}=o,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:n})}let u=d||de,f=await this.helpers.prepareBinaryData(c,l,u);i&&delete s[e];let h=this.getNodeParameter("outputPathTemplate",n,""),_;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:u,..._!==void 0?{outputPath:_}:{}},binary:{[t]:f},pairedItem:{item:n}}]}g(xo,"executeHydrateToolOutput");var Pn=gt("extractMarkdown"),ko=[{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:Pn},{displayName:"Mode",name:"mode",type:"options",default:"full",description:"Projection mode. 'Full' (default) returns the document body in Markdown/CriticMarkup. 'Fields (Content Controls)' returns the form-fields ledger with CC:<N> IDs, tags, aliases, types, lock/binding state, and current values for use with set_field.",options:[{name:"Full Document",value:"full",description:"Full or page-scoped Markdown/CriticMarkup projection"},{name:"Fields (Content Controls)",value:"fields",description:"Form-fields ledger listing every content control (CC:<N>, tag, alias, type, state, value)"}],displayOptions:Pn},{displayName:"Fields Offset",name:"fieldsOffset",type:"number",default:0,typeOptions:{minValue:0},description:"0-based entry offset when paging through a long Fields ledger",displayOptions:{show:{resource:["document"],operation:["extractMarkdown"],mode:["fields"]}}},{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:Pn},{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:Pn},{displayName:"Page",name:"page",type:"number",default:0,typeOptions:{minValue:0},description:"Optional 1-based page number or 'N-M' page range (up to 8 pages in one call when passed via expression/AI tool, e.g. '2-5') to return only a slice of the projected document (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 (or 'N-M'), only that page or range 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 Co(n){let e=this.getNodeParameter("binaryPropertyName",n),t=this.getNodeParameter("mode",n,"full"),r=this.getNodeParameter("cleanView",n,false),i=this.getNodeParameter("includeAppendix",n,true),s=this.getNodeParameter("page",n,0),a=this.getNodeParameter("documentSource",n,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",n,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",n,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:l,fileName:d}=await ue.call(this,n,a);if(t==="fields"){let m=this.getNodeParameter("fieldsOffset",n,0),w=await ae.load(l),y=await qe(l,false,false),[b]=et(y),v=tt(b,""),N=$r(w,y,v.body_page_offsets),k=bn(w),x=to(d,N,k,m);return [{json:{fileName:d,mode:"fields",total_fields:N.length,markdown:x},pairedItem:{item:n}}]}let c=await qe(l,r,i);if(!s||s===0||typeof s=="string"&&(s.trim()==="0"||s.trim().toLowerCase()==="all"))return [{json:{fileName:d,cleanView:r,markdown:c},pairedItem:{item:n}}];let[u,f]=et(c),h=tt(u,f);if(typeof s=="string"&&s.includes("-")){let[m,w]=Ms(s.trim().replace(/^['"]|['"]$/g,""));if(m==="range"&&Array.isArray(w)){let[y,b]=w;if(y>h.total_pages)throw new n8nWorkflow.NodeOperationError(this.getNode(),`Requested page ${y} exceeds total_pages (${h.total_pages}). Call extractOutline to discover the page count first.`,{itemIndex:n});let v=Math.min(b,y+Rs-1,h.total_pages),N=h.pages.slice(y-1,v),k=N.map(P=>P.page_content).join(`
|
|
193
|
+
|
|
194
|
+
`),x=N.reduce((P,E)=>P+E.tracked_change_count,0);return [{json:{fileName:d,cleanView:r,markdown:k,page:`${y}-${b}`,total_pages:h.total_pages,has_next:v<h.total_pages,has_prev:y>1,tracked_change_count:x},pairedItem:{item:n}}]}}let _=typeof s=="number"?s:Number(s);if(!Number.isInteger(_)||_<1||_>h.total_pages)throw new n8nWorkflow.NodeOperationError(this.getNode(),`Requested page ${s} exceeds total_pages (${h.total_pages}). Call extractOutline to discover the page count first.`,{itemIndex:n});let p=h.pages[_-1];return [{json:{fileName:d,cleanView:r,markdown:p.page_content,page:p.page,total_pages:p.total_pages,has_next:p.has_next,has_prev:p.has_prev,tracked_change_count:p.tracked_change_count},pairedItem:{item:n}}]}g(Co,"executeExtractMarkdown");var Eo=[{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 Ao(n){let e=this.getNodeParameter("binaryPropertyName",n),r=this.getNodeParameter("documentSource",n,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",n,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",n,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:i,fileName:s}=await ue.call(this,n,r),o=await ae.load(i),a=Xe(o,false,true,true),[l]=et(a.text),d=tt(l,""),c=Ws(o,l,d.body_pages,d.body_page_offsets,a.paragraph_offsets);return [{json:{fileName:s,total_pages:d.total_pages,outline:c.map(u=>({level:u.level,text:u.text,page:u.page,end_page:u.end_page,style:u.style,has_table:u.has_table,footnote_ids:u.footnote_ids}))},pairedItem:{item:n}}]}g(Ao,"executeExtractOutline");var be={show:{resource:["document"],operation:["applyEdits"]}},Po=[{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:be},{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:be},{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:be},{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:be},{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:be},{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:`[
|
|
182
195
|
{
|
|
183
196
|
"type": "modify",
|
|
184
197
|
"target_text": "State of New York",
|
|
185
198
|
"new_text": "State of Delaware",
|
|
186
199
|
"comment": "Standardizing governing law."
|
|
187
200
|
}
|
|
188
|
-
]`,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:ke},{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:ke},{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:ke},{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:ke},{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:ke}];async function _o(n){let e=this.getNodeParameter("binaryPropertyName",n),t=this.getNodeParameter("outputBinaryPropertyName",n),r=this.getNodeParameter("author",n),i=this.getNodeParameter("editsSource",n),s=this.getNodeParameter("returnMarkdown",n),o=this.getNodeParameter("allowPartial",n,false),a=this.getNodeParameter("ignoreControlLocks",n,false),c=this.getNodeParameter("ignoreDocumentProtection",n,false),u=this.getNodeParameter("allowUntrackedWrites",n,false),l=this.getNodeParameter("reasoning",n,""),d;if(i==="fromInputJson"){let P=this.getNodeParameter("editsJsonPath",n),I=this.getInputData()[n].json;if(d=no(I,P),d===void 0)throw new Error(`No property "${P}" found on the input item JSON. Verify the upstream node produced it, or switch "Edits Source" to "Define Below".`)}else {let P=this.getNodeParameter("editsJson",n);d=io.call(this,P,n,"Changes (JSON)");}if(!Array.isArray(d))throw new Error("Changes must be an array of DocumentChange objects.");d=ro(d);let h=this.getNodeParameter("documentSource",n,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",n,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",n,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:_,fileName:p}=await le.call(this,n,h),m=await de.load(_),y=new yn(m,r,{id_discovery_hint:to,ignore_control_locks:a,ignore_document_protection:c,allow_untracked_writes:u}).process_batch(d,void 0,o),b=this.getInputData()[n].binary??{},v=await m.save(),N=mt(p,"redlined"),k=await this.helpers.prepareBinaryData(v,N,Ne),x=typeof this.isToolExecution=="function"&&this.isToolExecution(),C;if(x&&k.id){let P=this.getWorkflowStaticData("global");P.adeu_last_redlined={id:k.id,fileName:N,mimeType:Ne,timestamp:Date.now()},C=k.id;}let E;return s&&(E=await Ke(v,false)),[{json:{fileName:N,author:r,status:y.status??"ok",stats:y,...l!==""?{reasoning:l}:{},...E!==void 0?{markdown:E}:{},...C!==void 0?{redlinedBinaryId:C}:{}},binary:{...b,[t]:k},pairedItem:{item:n}}]}g(_o,"executeApplyEdits");var gt=_t("applyTextRevision"),mo=[{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:gt},{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:gt},{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:gt},{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:gt},{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:gt},{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:gt}];async function go(n){let e=this.getNodeParameter("binaryPropertyName",n),t=this.getNodeParameter("outputBinaryPropertyName",n),r=this.getNodeParameter("author",n),i=this.getNodeParameter("revisedText",n),s=this.getNodeParameter("allowMajorDeletions",n,false),o=this.getNodeParameter("reasoning",n,""),c=this.getNodeParameter("documentSource",n,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",n,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",n,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:u,fileName:l}=await le.call(this,n,c),d=await de.load(u),f=mt(l,"redlined"),h=await Vs({doc:d,input_path:l,output_path:f,revised_text:i,author:r,allow_major_deletions:s}),_=h.stats;delete _.output_path,delete _.unverified_output_path;let p=Buffer.from(h.out_bytes),m=await this.helpers.prepareBinaryData(p,f,Ne),w=typeof this.isToolExecution=="function"&&this.isToolExecution(),y;if(w&&m.id){let v=this.getWorkflowStaticData("global");v.adeu_last_redlined={id:m.id,fileName:f,mimeType:Ne,timestamp:Date.now()},y=m.id;}let b=this.getInputData()[n].binary??{};return [{json:{fileName:f,author:r,stats:_,...o!==""?{reasoning:o}:{},...y!==void 0?{redlinedBinaryId:y}:{}},binary:{...b,[t]:m},pairedItem:{item:n}}]}g(go,"executeApplyTextRevision");var bn=_t("generateDiff"),wo=[{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:bn},{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:bn},{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:bn},{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:bn},{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 yo(n){let e=this.getNodeParameter("originalBinaryPropertyName",n),t=this.getNodeParameter("modifiedBinaryPropertyName",n),r=this.getNodeParameter("cleanView",n),i=this.getNodeParameter("diffFormat",n,"wordPatch"),s=this.getNodeParameter("originalDocumentSource",n,"fromInput"),o=this.getNodeParameter("modifiedDocumentSource",n,"fromInput"),a=s==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("originalSourceNodeName",n,""),binaryPropertyName:e}:{mode:"fromInput",binaryPropertyName:e},c=o==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("modifiedSourceNodeName",n,""),binaryPropertyName:t}:{mode:"fromInput",binaryPropertyName:t},{buffer:u,fileName:l}=await le.call(this,n,a),{buffer:d,fileName:f}=await le.call(this,n,c),h=Ns(new Uint8Array(u),new Uint8Array(d));if(i==="structuredChanges"){let y=await de.load(u),b=await de.load(d),v=Ze(y,r,false,false,true),N=Ze(b,r,false,false,true),{edits:k,warnings:x}=xs(v.text,v.structure,N.text,N.structure),C=[...h,...x];return [{json:{originalFileName:l,modifiedFileName:f,cleanView:r,diffFormat:i,changes:k,...C.length>0?{warnings:C}:{}},pairedItem:{item:n}}]}let _=await Ke(u,r,false),p=await Ke(d,r,false),m=i==="unified"?ks(_,p):As(_,p,l,f);return (i==="unified"?m.trim()!=="":m.includes("@@ Word Patch @@"))||(m=`--- ${l}
|
|
201
|
+
]`,required:true,description:`JSON-encoded string containing an array of DocumentChange objects. Changes evaluate SEQUENTIALLY: each item runs against the document state produced by preceding items in the same batch. type='modify': requires target_text (string \u2014 plain text resolves across hyperlinks, cross-references, and bookmarks; empty table cells emit \`{#cell:<id>}\`) and new_text (string \u2014 supports '#'\u2013'######' headings, '**bold**', '_italic_', '\\n\\n' paragraph splits, and Markdown pipe tables \`| H1 | H2 |\\n|---|---|\\n| A | B |\`; omit new_text with a comment to annotate without changing text; empty string deletes); optional comment (string or \`[{text, author?}]\`). 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 (supports inline flags like \`(?i)\`) 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='set_field': requires field (string like 'CC:3', tag, or alias from Extract Markdown mode='fields') and value (string \u2014 checkboxes take true/false, dates YYYY-MM-DD, dropdowns a listed option); optional match_mode and comment. 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). Unless 'Allow Partial Application' is enabled, the whole batch is validated atomically: if any single edit fails, 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:be},{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:be},{displayName:"Markup Mode",name:"markupMode",type:"options",default:"track_changes",description:"How modifications are recorded in the output .docx. 'Track Changes' (default) writes native Word <w:ins> and <w:del> revision tags. 'Manual (Inline Formatting)' writes deletions as strikethrough runs and insertions as bold underlined red (#C00000) runs with native Word comments, emitting zero tracked revisions.",options:[{name:"Track Changes",value:"track_changes",description:"Native Word <w:ins> and <w:del> tracked revisions"},{name:"Manual (Inline Formatting)",value:"manual",description:"Strikethrough deletions and underlined red insertions with comments (no <w:ins>/<w:del>)"}],displayOptions:be},{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:be},{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:be},{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:be}];async function To(n){let e=this.getNodeParameter("binaryPropertyName",n),t=this.getNodeParameter("outputBinaryPropertyName",n),r=this.getNodeParameter("author",n),i=this.getNodeParameter("editsSource",n),s=this.getNodeParameter("returnMarkdown",n),o=this.getNodeParameter("allowPartial",n,false),a=this.getNodeParameter("ignoreControlLocks",n,false),l=this.getNodeParameter("ignoreDocumentProtection",n,false),d=this.getNodeParameter("allowUntrackedWrites",n,false),c=this.getNodeParameter("markupMode",n,"track_changes"),u=this.getNodeParameter("reasoning",n,""),f;if(i==="fromInputJson"){let I=this.getNodeParameter("editsJsonPath",n),D=this.getInputData()[n].json;if(f=mo(D,I),f===void 0)throw new Error(`No property "${I}" found on the input item JSON. Verify the upstream node produced it, or switch "Edits Source" to "Define Below".`)}else {let I=this.getNodeParameter("editsJson",n);f=wo.call(this,I,n,"Changes (JSON)");}if(!Array.isArray(f))throw new Error("Changes must be an array of DocumentChange objects.");f=go(f);let _=this.getNodeParameter("documentSource",n,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",n,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",n,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:p,fileName:m}=await ue.call(this,n,_),w=await ae.load(p),b=new Bt(w,r,{id_discovery_hint:_o,ignore_control_locks:a,ignore_document_protection:l,allow_untracked_writes:d,markup_mode:c}).process_batch(f,void 0,o),v=this.getInputData()[n].binary??{},N=await w.save(),k=Ye(m,"redlined"),x=await this.helpers.prepareBinaryData(N,k,de),P=typeof this.isToolExecution=="function"&&this.isToolExecution(),E;if(P&&x.id){let I=this.getWorkflowStaticData("global");I.adeu_last_redlined={id:x.id,fileName:k,mimeType:de,timestamp:Date.now()},E=x.id;}let T;return s&&(T=await qe(N,false)),[{json:{fileName:k,author:r,status:b.status??"ok",stats:b,...u!==""?{reasoning:u}:{},...T!==void 0?{markdown:T}:{},...E!==void 0?{redlinedBinaryId:E}:{}},binary:{...v,[t]:x},pairedItem:{item:n}}]}g(To,"executeApplyEdits");var wt=gt("applyTextRevision"),$o=[{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:wt},{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:wt},{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:wt},{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:wt},{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:wt},{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:wt}];async function So(n){let e=this.getNodeParameter("binaryPropertyName",n),t=this.getNodeParameter("outputBinaryPropertyName",n),r=this.getNodeParameter("author",n),i=this.getNodeParameter("revisedText",n),s=this.getNodeParameter("allowMajorDeletions",n,false),o=this.getNodeParameter("reasoning",n,""),l=this.getNodeParameter("documentSource",n,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",n,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",n,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:d,fileName:c}=await ue.call(this,n,l),u=await ae.load(d),f=Ye(c,"redlined"),h=await uo({doc:u,input_path:c,output_path:f,revised_text:i,author:r,allow_major_deletions:s}),_=h.stats;delete _.output_path,delete _.unverified_output_path;let p=Buffer.from(h.out_bytes),m=await this.helpers.prepareBinaryData(p,f,de),w=typeof this.isToolExecution=="function"&&this.isToolExecution(),y;if(w&&m.id){let v=this.getWorkflowStaticData("global");v.adeu_last_redlined={id:m.id,fileName:f,mimeType:de,timestamp:Date.now()},y=m.id;}let b=this.getInputData()[n].binary??{};return [{json:{fileName:f,author:r,stats:_,...o!==""?{reasoning:o}:{},...y!==void 0?{redlinedBinaryId:y}:{}},binary:{...b,[t]:m},pairedItem:{item:n}}]}g(So,"executeApplyTextRevision");var Tn=gt("generateDiff"),Io=[{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:Tn},{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:Tn},{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:Tn},{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:Tn},{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. 'Redlined DOCX' produces a tracked-changes .docx comparing Original and Modified in one transactional step.",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"},{name:"Redlined DOCX (One-Step Comparison)",value:"redlineDocx",description:"Transactional tracked-changes .docx comparing original and modified in one step"}],displayOptions:{show:{resource:["document"],operation:["generateDiff"]}}},{displayName:"Author Name",name:"author",type:"string",default:"Adeu Redline",placeholder:"e.g. AI Legal Counsel",description:"Author name attributed to all tracked changes in the generated comparison .docx",displayOptions:{show:{resource:["document"],operation:["generateDiff"],diffFormat:["redlineDocx"]}}},{displayName:"Output Binary Property",name:"outputBinaryPropertyName",type:"string",default:"data",placeholder:"e.g. data",description:"Name of the binary property where the redlined comparison .docx will be written",displayOptions:{show:{resource:["document"],operation:["generateDiff"],diffFormat:["redlineDocx"]}}}];async function Oo(n){let e=this.getNodeParameter("originalBinaryPropertyName",n),t=this.getNodeParameter("modifiedBinaryPropertyName",n),r=this.getNodeParameter("cleanView",n),i=this.getNodeParameter("diffFormat",n,"wordPatch"),s=this.getNodeParameter("originalDocumentSource",n,"fromInput"),o=this.getNodeParameter("modifiedDocumentSource",n,"fromInput"),a=s==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("originalSourceNodeName",n,""),binaryPropertyName:e}:{mode:"fromInput",binaryPropertyName:e},l=o==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("modifiedSourceNodeName",n,""),binaryPropertyName:t}:{mode:"fromInput",binaryPropertyName:t},{buffer:d,fileName:c}=await ue.call(this,n,a),{buffer:u,fileName:f}=await ue.call(this,n,l),h=kr(new Uint8Array(d),new Uint8Array(u));if(i==="redlineDocx"){let y=this.getNodeParameter("author",n,"Adeu Redline"),b=this.getNodeParameter("outputBinaryPropertyName",n,"data"),v=await io(d,u,y,r),N=Ye(c,"redlined"),k=this.getInputData()[n].binary??{},x=await this.helpers.prepareBinaryData(v.data,N,de),P=typeof this.isToolExecution=="function"&&this.isToolExecution(),E;if(P&&x.id){let T=this.getWorkflowStaticData("global");T.adeu_last_redlined={id:x.id,fileName:N,mimeType:de,timestamp:Date.now()},E=x.id;}return [{json:{originalFileName:c,modifiedFileName:f,fileName:N,author:y,cleanView:r,diffFormat:i,edits_applied:v.applied,...v.warnings.length>0?{warnings:v.warnings}:{},...E!==void 0?{redlinedBinaryId:E}:{}},binary:{...k,[b]:x},pairedItem:{item:n}}]}if(i==="structuredChanges"){let y=await ae.load(d),b=await ae.load(u),v=Xe(y,r,false,false,true),N=Xe(b,r,false,false,true),{edits:k,warnings:x}=Nr(v.text,v.structure,N.text,N.structure),P=[...h,...x];return [{json:{originalFileName:c,modifiedFileName:f,cleanView:r,diffFormat:i,changes:k,...P.length>0?{warnings:P}:{}},pairedItem:{item:n}}]}let _=await qe(d,r,false),p=await qe(u,r,false),m=i==="unified"?Is(_,p):Ds(_,p,c,f);return (i==="unified"?m.trim()!=="":m.includes("@@ Word Patch @@"))||(m=`--- ${c}
|
|
189
202
|
+++ ${f}
|
|
190
203
|
|
|
191
204
|
No textual differences found between the documents.`),h.length>0&&(m=h.map(b=>`\u26A0\uFE0F ${b}`).join(`
|
|
192
205
|
`)+`
|
|
193
206
|
|
|
194
|
-
`+m),[{json:{originalFileName:l,modifiedFileName:f,cleanView:r,diffFormat:i,diff:m,...h.length>0?{warnings:h}:{}},pairedItem:{item:n}}]}g(yo,"executeGenerateDiff");var vo=[{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 bo(n){let e=this.getNodeParameter("binaryPropertyName",n),t=this.getNodeParameter("outputBinaryPropertyName",n),r=this.getNodeParameter("sanitizeMode",n),i=false;r==="full"&&(i=this.getNodeParameter("acceptAll",n));let s=null;if(r==="keep-markup"){let b=this.getNodeParameter("authorOverride",n);s=b.trim()===""?null:b;}let a=this.getNodeParameter("protectionMode",n)==="read_only"?"read_only":null,c=this.getNodeParameter("reasoning",n,""),l=this.getNodeParameter("documentSource",n,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",n,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",n,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:d,fileName:f}=await le.call(this,n,l),h=await de.load(d),{reportText:_,outBuffer:p}=await Ks(h,{filename:f,sanitize_mode:r,accept_all:i,protection_mode:a,author:s});if(!p)throw new Error(_);let m=mt(f,"finalized"),w=await this.helpers.prepareBinaryData(p,m,Ne),y=this.getInputData()[n].binary??{};return [{json:{fileName:m,sanitizeMode:r,report:_,...c!==""?{reasoning:c}:{}},binary:{...y,[t]:w},pairedItem:{item:n}}]}g(bo,"executeFinalizeDocument");var xo=[{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"]}}},...co,...fo,...po,...mo,...wo,...vo,...ao];var Eo=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"},...xo]};async execute(){let e=this.getInputData(),t=[],r=this.getNodeParameter("resource",0),i=this.getNodeParameter("operation",0);for(let s=0;s<e.length;s++)try{let o;if(r==="document")switch(i){case "extractMarkdown":o=await uo.call(this,s);break;case "extractOutline":o=await ho.call(this,s);break;case "applyEdits":o=await _o.call(this,s);break;case "applyTextRevision":o=await go.call(this,s);break;case "generateDiff":o=await yo.call(this,s);break;case "finalizeDocument":o=await bo.call(this,s);break;case "hydrateToolOutput":o=await lo.call(this,s);break;default:throw new n8nWorkflow.NodeOperationError(this.getNode(),`Unsupported operation: ${i}`,{itemIndex:s})}else throw new n8nWorkflow.NodeOperationError(this.getNode(),`Unsupported resource: ${r}`,{itemIndex:s});t.push(...o);}catch(o){if(this.continueOnFail()){t.push({json:{error:o.message},pairedItem:{item:s}});continue}let a=o;throw a.name==="NodeOperationError"||a.name==="NodeApiError"?a:so.call(this,a,s)}return [t]}};exports.Adeu=Eo;
|
|
207
|
+
`+m),[{json:{originalFileName:c,modifiedFileName:f,cleanView:r,diffFormat:i,diff:m,...h.length>0?{warnings:h}:{}},pairedItem:{item:n}}]}g(Oo,"executeGenerateDiff");var Do=[{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 Ro(n){let e=this.getNodeParameter("binaryPropertyName",n),t=this.getNodeParameter("outputBinaryPropertyName",n),r=this.getNodeParameter("sanitizeMode",n),i=false;r==="full"&&(i=this.getNodeParameter("acceptAll",n));let s=null;if(r==="keep-markup"){let b=this.getNodeParameter("authorOverride",n);s=b.trim()===""?null:b;}let a=this.getNodeParameter("protectionMode",n)==="read_only"?"read_only":null,l=this.getNodeParameter("reasoning",n,""),c=this.getNodeParameter("documentSource",n,"fromInput")==="fromNode"?{mode:"fromNode",sourceNodeName:this.getNodeParameter("sourceNodeName",n,""),binaryPropertyName:e,sourceBinaryId:this.getNodeParameter("sourceBinaryId",n,"")}:{mode:"fromInput",binaryPropertyName:e},{buffer:u,fileName:f}=await ue.call(this,n,c),h=await ae.load(u),{reportText:_,outBuffer:p}=await fo(h,{filename:f,sanitize_mode:r,accept_all:i,protection_mode:a,author:s});if(!p)throw new Error(_);let m=Ye(f,"finalized"),w=await this.helpers.prepareBinaryData(p,m,de),y=this.getInputData()[n].binary??{};return [{json:{fileName:m,sanitizeMode:r,report:_,...l!==""?{reasoning:l}:{}},binary:{...y,[t]:w},pairedItem:{item:n}}]}g(Ro,"executeFinalizeDocument");var Mo=[{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, set_field, accept, reject, reply, insert_row, delete_row) sequentially as native Word tracked changes (or manual inline formatting) and comments. modify edits support match_mode ('strict'|'first'|'all'), regex (boolean), Markdown headings/bold/italic/'\\n\\n' splits/pipe tables, `{#cell:<id>}` empty-cell anchors, and single or multi-author comments (`[{text, author?}]`). By default the batch is pre-validated atomically; set 'Allow Partial Application' to apply the changes that validate and report the rest in 'stats.failed' with 0-based indices."},{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 (or a Fields Content Controls ledger when Mode is 'fields'). Each tracked change is tagged with an ID (Chg:N, Com:N) for use in Apply Edits. Supports an optional Page number or 'N-M' page range to fetch a slice 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, unified diff, structured DocumentChange JSON array, or a one-step redlined comparison .docx (`diffFormat='redlineDocx'`) between two .docx files."},{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"]}}},...ko,...Eo,...Po,...$o,...Io,...Do,...bo];var Fo=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 or one-step redline comparisons, and sanitize/finalize documents. Seven operations on the Document resource: (1) Extract Markdown \u2014 project a .docx into Markdown plus a Semantic Appendix (or a Fields Content Controls ledger in mode='fields'); toggle Clean View to simulate Accept All; pass an optional Page number or 'N-M' page range to fetch a slice of a large document. (2) Extract Outline \u2014 return a token-cheap structural map (headings with level, page number, end_page, 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 sequentially as native Word tracked changes (or manual strikethrough/underline formatting when Markup Mode is 'manual'); modify edits support match_mode ('strict'|'first'|'all'), regex (boolean), Markdown headings/bold/italic/'\\n\\n' splits/pipe tables, `{#cell:<id>}` empty-cell anchors, and single or multi-author comments; set_field fills content controls by CC:<N>, tag, or alias. (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 diff, unified diff, structured DocumentChange JSON array, or a one-step redlined .docx comparison (`diffFormat='redlineDocx'`) 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, Apply Text Revision, or Generate Diff (`redlineDocx`) 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, and changes in a batch evaluate SEQUENTIALLY against the state produced by prior changes. type='modify' requires target_text (string \u2014 plain text resolves across hyperlinks, cross-references, and bookmarks; empty table cells emit `{#cell:<id>}`) and new_text (string \u2014 supports '#'\u2013'######' headings, '**bold**', '_italic_', '\\n\\n' paragraph splits, and Markdown pipe tables `| H1 | H2 |\\n|---|---|\\n| A | B |`; omit new_text with a comment to annotate without changing text; empty string deletes); optional comment (string or `[{text, author?}]`); optional match_mode ('strict'|'first'|'all', default 'strict'); optional regex (boolean, default false \u2014 when true, target_text is an ES2022 RegExp pattern with optional inline flags like `(?i)`, and new_text may reference $1, $2 capture groups). type='set_field' requires field (string like 'CC:3', tag, or alias from Extract Markdown mode='fields') and value (string \u2014 checkboxes take true/false, dates YYYY-MM-DD, dropdowns a listed option); optional match_mode and comment. type='accept' or type='reject' requires target_id (string like 'Chg:12' from the Markdown projection); optional part (e.g. 'word/header1.xml' when the same id exists in several parts); 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"},...Mo]};async execute(){let e=this.getInputData(),t=[],r=this.getNodeParameter("resource",0),i=this.getNodeParameter("operation",0);for(let s=0;s<e.length;s++)try{let o;if(r==="document")switch(i){case "extractMarkdown":o=await Co.call(this,s);break;case "extractOutline":o=await Ao.call(this,s);break;case "applyEdits":o=await To.call(this,s);break;case "applyTextRevision":o=await So.call(this,s);break;case "generateDiff":o=await Oo.call(this,s);break;case "finalizeDocument":o=await Ro.call(this,s);break;case "hydrateToolOutput":o=await xo.call(this,s);break;default:throw new n8nWorkflow.NodeOperationError(this.getNode(),`Unsupported operation: ${i}`,{itemIndex:s})}else throw new n8nWorkflow.NodeOperationError(this.getNode(),`Unsupported resource: ${r}`,{itemIndex:s});t.push(...o);}catch(o){if(this.continueOnFail()){t.push({json:{error:o.message},pairedItem:{item:s}});continue}let a=o;throw a.name==="NodeOperationError"||a.name==="NodeApiError"?a:yo.call(this,a,s)}return [t]}};exports.Adeu=Fo;
|