n8n-nodes-adeu 3.2.1 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,47 +1,47 @@
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,"&amp;").replace(r,"&lt;").replace(i,"&gt;").replace(s,"&para;<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 "&amp;":return "&";case "&lt;":return "<";case "&gt;":return ">";case "&quot;":return '"';case "&apos;":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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\r/g,"&#13;"):n}g(va,"escText");function ba(n){return /[&<>"\t\n\r]/.test(n)?n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\t/g,"&#9;").replace(/\n/g,"&#10;").replace(/\r/g,"&#13;"):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(`
1
+ 'use strict';var n8nWorkflow=require('n8n-workflow'),path=require('path');var qo=Object.create;var On=Object.defineProperty;var Yo=Object.getOwnPropertyDescriptor;var Go=Object.getOwnPropertyNames;var Jo=Object.getPrototypeOf,Vo=Object.prototype.hasOwnProperty;var g=(n,e)=>On(n,"name",{value:e,configurable:true});var jr=(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 Go(e))!Vo.call(n,i)&&i!==t&&On(n,i,{get:()=>e[i],enumerable:!(r=Yo(e,i))||r.enumerable});return n};var Lt=(n,e,t)=>(t=n!=null?qo(Jo(n)):{},Qo(On(t,"default",{value:n,enumerable:true}),n));var Fr=jr((Ku,Br)=>{Br.exports={createRequire:g(function(){return function(){return {}}},"createRequire")};});var Ht=jr((rf,dt)=>{var L=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"),Z=-1,K=1,Y=0;L.Diff=function(n,e){return [n,e]};L.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 L.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 L.Diff(Y,a)),l&&d.push(new L.Diff(Y,l)),this.diff_cleanupMerge(d),d};L.prototype.diff_compute_=function(n,e,t,r){var i;if(!n)return [new L.Diff(K,e)];if(!e)return [new L.Diff(Z,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 L.Diff(K,s.substring(0,a)),new L.Diff(Y,o),new L.Diff(K,s.substring(a+o.length))],n.length>e.length&&(i[0][0]=i[2][0]=Z),i;if(o.length==1)return [new L.Diff(Z,n),new L.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 L.Diff(Y,h)],p)}return t&&n.length>100&&e.length>100?this.diff_lineMode_(n,e,r):this.diff_bisect_(n,e,r)};L.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 L.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 Z: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};L.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 C=-w+p;C<=w-m;C+=2){var k=o+C,x;C==-w||C!=w&&d[k-1]<d[k+1]?x=d[k+1]:x=d[k-1]+1;for(var A=x-C;x<r&&A<i&&n.charAt(r-x-1)==e.charAt(i-A-1);)x++,A++;if(d[k]=x,x>r)m+=2;else if(A>i)p+=2;else if(!f){var b=o+u-C;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 L.Diff(Z,n),new L.Diff(K,e)]};L.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)};L.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}};L.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("");}};L.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};L.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};L.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++);}};L.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)),A=i.diff_commonSuffix(_.substring(0,m),p.substring(0,y));b.length<A+C&&(b=p.substring(y-A,y)+p.substring(y,y+C),v=_.substring(0,m-A),N=_.substring(m+C),k=p.substring(0,y-A),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)),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]};L.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 L.Diff(Z,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]==Z&&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 L.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 L.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]=Z,n[s+1][1]=c.substring(h),s++),s++;}s++;}};L.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(L.nonAlphaNumericRegex_),y=m.match(L.nonAlphaNumericRegex_),b=w&&p.match(L.whitespaceRegex_),v=y&&m.match(L.whitespaceRegex_),N=b&&p.match(L.linebreakRegex_),k=v&&m.match(L.linebreakRegex_),x=N&&h.match(L.blanklineEndRegex_),C=k&&_.match(L.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]==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++;}};L.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;L.whitespaceRegex_=/\s/;L.linebreakRegex_=/[\r\n]/;L.blanklineEndRegex_=/\n\r?\n$/;L.blanklineStartRegex_=/^\r?\n\r?\n/;L.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]==Z?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 L.Diff(Z,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);};L.prototype.diff_cleanupMerge=function(n){n.push(new L.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 Z: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 L.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 L.Diff(Z,i)),e++),s.length&&(n.splice(e,0,new L.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);};L.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]!==Z&&(r+=n[o][1].length),!(t>e));o++)i=t,s=r;return n.length!=o&&n[o][0]===Z?s:s+(e-i)};L.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,"&amp;").replace(r,"&lt;").replace(i,"&gt;").replace(s,"&para;<br>");switch(a){case K:e[o]='<ins style="background:#e6ffe6;">'+d+"</ins>";break;case Z:e[o]='<del style="background:#ffe6e6;">'+d+"</del>";break;case Y:e[o]="<span>"+d+"</span>";break}}return e.join("")};L.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("")};L.prototype.diff_text2=function(n){for(var e=[],t=0;t<n.length;t++)n[t][0]!==Z&&(e[t]=n[t][1]);return e.join("")};L.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 Z:r+=o.length;break;case Y:e+=Math.max(t,r),t=0,r=0;break}}return e+=Math.max(t,r),e};L.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 Z:e[t]="-"+n[t][1].length;break;case Y:e[t]="="+n[t][1].length;break}return e.join(" ").replace(/%20/g," ")};L.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 L.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 L.Diff(Y,d):t[r++]=new L.Diff(Z,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};L.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};L.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};L.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};L.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 L.Diff(Y,i));var s=e.substring(n.start2+n.length1,n.start2+n.length1+r);s&&n.diffs.push(new L.Diff(Y,s)),n.start1-=i.length,n.start2-=i.length,n.length1+=i.length+s.length,n.length2+=i.length+s.length;}};L.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 L.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 Z: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 L.patch_obj,a=0,c=u,l=d);break}h!==K&&(l+=_.length),h!==Z&&(d+=_.length);}return a&&(this.patch_addContext_(o,c),s.push(o)),s};L.prototype.patch_deepCopy=function(n){for(var e=[],t=0;t<n.length;t++){var r=n[t],i=new L.patch_obj;i.diffs=[];for(var s=0;s<r.diffs.length;s++)i.diffs[s]=new L.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};L.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]===Z&&(e=e.substring(0,l+h)+e.substring(l+this.diff_xIndex(u,f+p[1].length))),p[0]!==Z&&(f+=p[1].length);}}}}}return e=e.substring(t.length,e.length-t.length),[e,i]};L.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 L.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 L.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};L.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 L.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 L.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===Z&&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 L.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 L.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 L.Diff(Y,u))),l||n.splice(++t,0,a);}}};L.prototype.patch_toText=function(n){for(var e=[],t=0;t<n.length;t++)e[t]=n[t];return e.join("")};L.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 L.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 L.Diff(Z,l));else if(a=="+")o.diffs.push(new L.Diff(K,l));else if(a==" ")o.diffs.push(new L.Diff(Y,l));else {if(a=="@")break;if(a!=="")throw new Error('Invalid patch mode "'+a+'" in: '+l)}r++;}}return e};L.patch_obj=function(){this.diffs=[],this.start1=null,this.start2=null,this.length1=0,this.length2=0;};L.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 Z:r="-";break;case Y:r=" ";break}t[i+1]=r+encodeURI(this.diffs[i][1])+`
5
+ `;}return t.join("").replace(/%20/g," ")};dt.exports=L;dt.exports.diff_match_patch=L;dt.exports.DIFF_DELETE=Z;dt.exports.DIFF_INSERT=K;dt.exports.DIFF_EQUAL=Y;});var Xr=Lt(Fr());var Zo=(0, Xr.createRequire)("/"),lt,Ko,ea;try{lt=Zo("worker_threads"),Ko=lt.Worker,ea=lt.isMarkedAsUntransferable;}catch{}var ee=Uint8Array,ce=Uint16Array,Hn=Int32Array,zt=new ee([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]),Ut=new ee([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Bn=new ee([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),qr=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 Hn(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"),lt=qr(zt,2),Yr=lt.b,Fn=lt.r;Yr[28]=258,Fn[258]=28;var Gr=qr(Ut,0),ta=Gr.b,Lr=Gr.r,Ln=new ce(32768);for(J=0;J<32768;++J)Te=(J&43690)>>1|(J&21845)<<1,Te=(Te&52428)>>2|(Te&13107)<<2,Te=(Te&61680)>>4|(Te&3855)<<4,Ln[J]=((Te&65280)>>8|(Te&255)<<8)>>1;var Te,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[Ln[u]>>l]=d;}else for(a=new ce(r),i=0;i<r;++i)n[i]&&(a[i]=Ln[o[n[i]-1]++]>>15-n[i]);return a}),"hMap"),Me=new ee(288);for(J=0;J<144;++J)Me[J]=8;var J;for(J=144;J<256;++J)Me[J]=9;var J;for(J=256;J<280;++J)Me[J]=7;var J;for(J=280;J<288;++J)Me[J]=8;var J,kt=new ee(32);for(J=0;J<32;++J)kt[J]=5;var J,na=Ne(Me,9,0),ra=Ne(Me,9,1),ia=Ne(kt,5,0),sa=Ne(kt,5,1),Dn=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"),Rn=g(function(n,e){var t=e/8|0;return (n[t]|n[t+1]<<8|n[t+2]<<16)>>(e&7)},"bits16"),Xn=g(function(n){return (n+7)/8|0},"shft"),Ct=g(function(n,e,t){return (e==null||e<0)&&(e=0),(t==null||t>n.length)&&(t=n.length),new ee(n.subarray(e,t))},"slc");var oa=["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||oa[n]);if(r.code=n,Error.captureStackTrace&&Error.captureStackTrace(r,se),!t)throw r;return r},"err"),aa=g(function(n,e,t,r){var i=n.length,s=r?r.length:0;if(!i||e.f&&!e.l)return t||new ee(0);var o=!t,a=o||e.i!=2,l=e.i;o&&(t=new ee(i*3));var d=g(function(Re){var at=t.length;if(Re>at){var he=new ee(Math.max(at*2,Re));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=ra,_=sa,p=9,m=5;else if(y==2){var k=me(n,u,31)+257,x=me(n,u+10,15)+4,C=k+me(n,u+5,31)+1;u+=14;for(var A=new ee(C),T=new ee(19),I=0;I<x;++I)T[Bn[I]]=me(n,u+I*3,7);u+=x*3;for(var M=Dn(T),B=(1<<M)-1,D=Ne(T,M,1),I=0;I<C;){var j=D[me(n,u,B)];u+=j&15;var b=j>>4;if(b<16)A[I++]=b;else {var F=0,E=0;for(b==16?(E=3+me(n,u,3),u+=2,F=A[I-1]):b==17?(E=3+me(n,u,7),u+=3):b==18&&(E=11+me(n,u,127),u+=7);E--;)A[I++]=F;}}var $=A.subarray(0,k),P=A.subarray(k);p=Dn($),m=Dn(P),h=Ne($,p,1),_=Ne(P,m,1);}else se(1);else {var b=Xn(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,W=(1<<m)-1,U=u;;U=u){var F=h[Rn(n,u)&O],X=F>>4;if(u+=F&15,u>w){l&&se(0);break}if(F||se(2),X<256)t[f++]=X;else if(X==256){U=u,h=null;break}else {var z=X-254;if(X>264){var I=X-257,H=zt[I];z=me(n,u,(1<<H)-1)+Yr[I],u+=H;}var q=_[Rn(n,u)&W],V=q>>4;q||se(3),u+=q&15;var P=ta[V];if(V>3){var H=Ut[V];P+=Rn(n,u)&(1<<H)-1,u+=H;}if(u>w){l&&se(0);break}a&&d(f+131072);var Q=f+z;if(f<P){var fe=s-P,ot=Math.min(P,Q);for(fe+f<0&&se(3);f<ot;++f)t[f]=r[fe+f];}for(;f<Q;++f)t[f]=t[f-P];}}e.l=h,e.p=U,e.b=f,e.f=c,h&&(c=1,e.m=p,e.d=_,e.n=m);}while(!c);return f!=t.length&&o?Ct(t,0,f):t.subarray(0,f)},"inflt"),Se=g(function(n,e,t){t<<=e&7;var r=e/8|0;n[r]|=t,n[r+1]|=t>>8;},"wbits"),xt=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"),Mn=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:Vr,l:0};if(i==1){var o=new ee(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),_=Wn(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 ee(h),l:_}},"hTree"),Wn=g(function(n,e,t){return n.s==-1?Math.max(Wn(n.l,e,t+1),Wn(n.r,e,t+1)):e[n.s]=t},"ln"),Wr=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"),Nt=g(function(n,e){for(var t=0,r=0;r<e.length;++r)t+=n[r]*e[r];return t},"clen"),Jr=g(function(n,e,t){var r=t.length,i=Xn(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"),zr=g(function(n,e,t,r,i,s,o,a,l,d,c){Se(e,c++,t),++i[256];for(var u=Mn(i,15),f=u.t,h=u.l,_=Mn(s,15),p=_.t,m=_.l,w=Wr(f),y=w.c,b=w.n,v=Wr(p),N=v.c,k=v.n,x=new ce(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 A=Mn(x,7),T=A.t,I=A.l,M=19;M>4&&!T[Bn[M-1]];--M);var B=d+5<<3,D=Nt(i,Me)+Nt(s,kt)+o,j=Nt(i,f)+Nt(s,p)+o+14+3*M+Nt(x,T)+2*x[16]+3*x[17]+7*x[18];if(l>=0&&B<=D&&B<=j)return Jr(e,c,n.subarray(l,l+d));var F,E,$,P;if(Se(e,c,1+(j<D)),c+=2,j<D){F=Ne(f,h,0),E=f,$=Ne(p,m,0),P=p;var O=Ne(T,I,0);Se(e,c,b-257),Se(e,c+5,k-1),Se(e,c+10,M-4),c+=14;for(var C=0;C<M;++C)Se(e,c+3*C,T[Bn[C]]);c+=3*M;for(var W=[y,N],U=0;U<2;++U)for(var X=W[U],C=0;C<X.length;++C){var z=X[C]&31;Se(e,c,O[z]),c+=T[z],z>15&&(Se(e,c,X[C]>>5&127),c+=X[C]>>12);}}else F=na,E=Me,$=ia,P=kt;for(var C=0;C<a;++C){var H=r[C];if(H>255){var z=H>>18&31;xt(e,c,F[z+257]),c+=E[z+257],z>7&&(Se(e,c,H>>23&31),c+=zt[z]);var q=H&31;xt(e,c,$[q]),c+=P[q],q>3&&(xt(e,c,H>>5&8191),c+=Ut[q]);}else xt(e,c,F[H]),c+=E[H];}return xt(e,c,F[256]),c+E[256]},"wblk"),la=new Hn([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Vr=new ee(0),ca=g(function(n,e,t,r,i,s){var o=s.z||n.length,a=new ee(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=la[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(Ve){return (n[Ve]^n[Ve+1]<<w^n[Ve+2]<<y)&_},"hsh"),v=new Hn(25e3),N=new ce(288),k=new ce(32),x=0,C=0,A=s.i||0,T=0,I=s.w||0,M=0;A+2<o;++A){var B=b(A),D=A&32767,j=m[B];if(p[D]=j,m[B]=D,I<=A){var F=o-A;if((x>7e3||T>24576)&&(F>423||!d)){c=zr(n,l,0,v,N,k,C,T,M,A-M,c),T=x=C=0,M=A;for(var E=0;E<286;++E)N[E]=0;for(var E=0;E<30;++E)k[E]=0;}var $=2,P=0,O=h,W=D-j&32767;if(F>2&&B==b(A-W))for(var U=Math.min(f,F)-1,X=Math.min(32767,A),z=Math.min(258,F);W<=X&&--O&&D!=j;){if(n[A+$]==n[A+$-W]){for(var H=0;H<z&&n[A+H]==n[A+H-W];++H);if(H>$){if($=H,P=W,H>U)break;for(var q=Math.min(W,H-2),V=0,E=0;E<q;++E){var Q=A-W+E&32767,fe=p[Q],ot=Q-fe&32767;ot>V&&(V=ot,j=Q);}}}D=j,j=p[D],W+=D-j&32767;}if(P){v[T++]=268435456|Fn[$]<<18|Lr[P];var Re=Fn[$]&31,at=Lr[P]&31;C+=zt[Re]+Ut[at],++N[257+Re],++k[at],I=A+$,++x;}else v[T++]=n[A],++N[n[A]];}}for(A=Math.max(A,I);A<o;++A)v[T++]=n[A],++N[n[A]];c=zr(n,l,d,v,N,k,C,T,M,A-M,c),d||(s.r=c&7|l[c/8|0]<<3,c-=7,s.h=m,s.p=p,s.i=A,s.w=I);}else {for(var A=s.w||0;A<o+d;A+=65535){var he=A+65535;he>=o&&(l[c/8|0]=d,he=o),c=Jr(l,c+1,n.subarray(A,he));}s.i=o;}return Ct(a,0,r+Xn(c)+i)},"dflt"),da=(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})(),ua=g(function(){var n=-1;return {p:g(function(e){for(var t=n,r=0;r<e.length;++r)t=da[t&255^e[r]]^t>>>8;n=t;},"p"),d:g(function(){return ~n},"d")}},"crc");var fa=g(function(n,e,t,r,i){if(!i&&(i={l:1},e.dictionary)){var s=e.dictionary.subarray(-32768),o=new ee(s.length+n.length);o.set(s),o.set(n,s.length),n=o,i.w=s.length;}return ca(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"),Qr=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"),jn=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 ha(n,e){return fa(n,e||{},0,0)}g(ha,"deflateSync");function pa(n,e){return aa(n,{i:2},e&&e.out,e&&e.dictionary)}g(pa,"inflateSync");var Zr=g(function(n,e,t,r){for(var i in n){var s=n[i],o=e+i,a=r;Array.isArray(s)&&(a=Qr(r,s[1]),s=s[0]),ArrayBuffer.isView(s)?t[o]=[s,a]:(t[o+="/"]=[new ee(0),a],Zr(s,o,t,r));}},"fltn"),Ur=typeof TextEncoder<"u"&&new TextEncoder,zn=typeof TextDecoder<"u"&&new TextDecoder,_a=0;try{zn.decode(Vr,{stream:!0}),_a=1;}catch{}var ma=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:Ct(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 Wt(n,e){if(e){for(var t=new ee(n.length),r=0;r<n.length;++r)t[r]=n.charCodeAt(r);return t}if(Ur)return Ur.encode(n);for(var i=n.length,s=new ee(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 ee(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 Ct(s,0,o)}g(Wt,"strToU8");function Qe(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(zn)return zn.decode(n);var i=ma(n),s=i.s,t=i.r;return t.length&&se(8),s}}g(Qe,"strFromU8");var ga=g(function(n,e){return e+30+xe(n,e+26)+xe(n,e+28)},"slzh"),wa=g(function(n,e,t){var r=xe(n,e+28),i=xe(n,e+30),s=Qe(n.subarray(e+46,e+46+r),!(xe(n,e+8)&2048)),o=e+46+r,a=ya(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"),ya=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?jn(n,e+4+8*l):i,l?jn(n,e+4):s,d?jn(n,e+4+8*(l+a)):o,1];r<2&&se(13);}return [i,s,o,0]},"z64hs"),Un=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"),Hr=g(function(n,e,t,r,i,s,o,a){var l=r.length,d=t.extra,c=a&&a.length,u=Un(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"),va=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 Kr(n,e){e||(e={});var t={},r=[];Zr(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=Wt(o),f=u.length,h=d.comment,_=h&&Wt(h),p=_&&_.length,m=Un(d.extra);f>65535&&se(11);var w=c?ha(l,d):l,y=w.length,b=ua();b.p(l),r.push(Qr(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 ee(s+22),N=i,k=s-i,x=0;x<r.length;++x){var u=r[x];Hr(v,u.o,u,u.f,u.u,u.c.length);var C=30+u.f.length+Un(u.extra);v.set(u.c,u.o+C),Hr(v,i,u,u.f,u.u,u.c.length,u.o,u.m),i+=16+C+(u.m?u.m.length:0);}return va(v,i,r.length,k,N),v}g(Kr,"zipSync");function ct(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=wa(n,s,o),u=c[0],f=c[1],h=c[2],_=c[3],p=c[4],m=c[5],w=ga(n,m);s=p,(!l||l({name:_,size:f,originalSize:h,compression:u}))&&(u?u==8?t[_]=pa(n.subarray(w,w+f),{out:new ee(h)}):se(14,"unknown compression type "+u):t[_]=Ct(n,w,w+f));}return t}g(ct,"unzipSync");var _s=Lt(Ht()),js=Lt(Ht());var kr=Lt(Ht());var Ke=1,ur=3,fr=4,Yi=8,hr=9,Gi=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}},Mt=class Ji extends Gi{static{g(this,"_FastText");}constructor(e){super(),this.data=e;}data;nodeType=ur;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 Ji(this.data);return t.ownerDocument=this.ownerDocument,t}toString(){return hn(this)}},Vi=class Qi extends Mt{static{g(this,"_FastComment");}nodeType=Yi;cloneNode(e){let t=new Qi(this.data);return t.ownerDocument=this.ownerDocument,t}},ba=class Zi extends Mt{static{g(this,"_FastCData");}nodeType=fr;cloneNode(e){let t=new Zi(this.data);return t.ownerDocument=this.ownerDocument,t}},Ki=class extends Gi{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===hr?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===Ke){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}},es=class ts extends Ki{static{g(this,"_FastElement");}constructor(e){super(),this.tagName=e;}tagName;nodeType=Ke;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 hn(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===ur||r.nodeType===fr)e+=r.data;else if(r.nodeType===Ke){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 Mt(String(e));t.ownerDocument=this.ownerDocument,t.parentNode=this,this.childNodes.push(t);}this.ownerDocument&&this.ownerDocument._inc++;}cloneNode(e=false){let t=new ts(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}},xa=class extends Ki{static{g(this,"FastDocument");}nodeType=hr;_inc=1;documentElement=null;get nodeName(){return "#document"}createElement(n){let e=new es(n);return e.ownerDocument=this,e}createElementNS(n,e){return this.createElement(e)}createTextNode(n){let e=new Mt(String(n));return e.ownerDocument=this,e}createComment(n){let e=new Vi(String(n));return e.ownerDocument=this,e}toString(){return hn(this)}appendChild(n){let e=super.appendChild(n);return n.nodeType===Ke&&(this.documentElement=n),e}replaceChild(n,e){let t=super.replaceChild(n,e);return e===this.documentElement&&n.nodeType===Ke&&(this.documentElement=n),t}},Na=/&(?:amp|lt|gt|quot|apos|#x?[0-9a-fA-F]+);/g;function ns(n){return n.indexOf("&")<0?n:n.replace(Na,e=>{switch(e){case "&amp;":return "&";case "&lt;":return "<";case "&gt;":return ">";case "&quot;":return '"';case "&apos;":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(ns,"decodeEntities");function Kn(n){return n.indexOf("\r")<0?n:n.replace(/\r\n?/g,`
6
+ `)}g(Kn,"normalizeLineEnds");function ka(n){let e=Kn(n),t=/[\n\t]/.test(e)?e.replace(/[\n\t]/g," "):e;return ns(t)}g(ka,"normalizeAttrValue");var qn=new Set([32,9,10,13]);function Ca(n){n.charCodeAt(0)===65279&&(n=n.slice(1));let e=new xa,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 Mt(ns(Kn(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!==Ke||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 Vi(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 ba(Kn(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(qn.has(u)||u===62||u===47)break;l++;}if(l===r)throw new Error(`Invalid tag at offset ${o}`);let d=new es(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(qn.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&&qn.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,ka(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(Ca,"parseFastXml");function Ea(n){return /[&<>\r]/.test(n)?n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\r/g,"&#13;"):n}g(Ea,"escText");function Aa(n){return /[&<>"\t\n\r]/.test(n)?n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/\t/g,"&#9;").replace(/\n/g,"&#10;").replace(/\r/g,"&#13;"):n}g(Aa,"escAttr");function hn(n){let e=[],t=g(r=>{switch(r.nodeType){case Ke:{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,'="',Aa(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 ur:e.push(Ea(r.data));break;case fr:e.push("<![CDATA[",r.data,"]]>");break;case Yi:e.push("<!--",r.data,"-->");break;case hr:for(let i of r.childNodes)t(i);break}},"write");return t(n),e.join("")}g(hn,"serializeFastXml");function S(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(S,"findChild");function pn(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(pn,"findChildren");function rs(n,e){let t=typeof e=="string"?[e]:e,r=[],i=g((s,o)=>{if(!(o>Pa))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(rs,"findChildrenSdtTransparent");var Pa=100;function R(n,e){return Array.from(n.getElementsByTagName(e))}g(R,"findAllDescendants");function et(n){return n.startsWith("\uFEFF")&&(n=n.slice(1)),Ca(n)}g(et,"parseXml");function ei(n){let e=hn(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(ei,"serializeXml");var ln=1,pr=2147483647;function _r(n){return ((n&pr)>>>0||ln).toString(16).toUpperCase().padStart(8,"0")}g(_r,"toLongHexNumber");function Xt(){let n=pr-ln+1;return _r(ln+Math.floor(Math.random()*n))}g(Xt,"generateLongHexNumber");function ti(n){if(!/^[0-9A-Fa-f]{1,8}$/.test(n))return false;let e=parseInt(n,16);return e>=ln&&e<=pr}g(ti,"isWordReadableLongHexNumber");var er="__adeu_wp_index_cache",is="__adeu_clean_inc";function _n(n){return typeof n._inc=="number"?n._inc:null}g(_n,"docInc");function It(n){let e=_n(n);e!==null&&(n[is]=e);}g(It,"markPartClean");function mr(n){let e=_n(n);return e!==null&&n[is]===e}g(mr,"isPartClean");function Ta(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(Ta,"buildWpIndexMap");function Sa(n,e){let t=_n(n),r=n[er];(!r||t===null||r.inc!==t||!r.map.has(e))&&(r={inc:t??NaN,map:Ta(n)},n[er]=r);let i=r.map.get(e);return i===void 0?-1:i}g(Sa,"wpDocumentOrderIndex");function $a(n){let e=n[er],t=_n(n);e&&t!==null&&(e.inc=t);}g($a,"resyncAfterOwnAttributeMutation");function ss(n,e){let t=n.getElementsByTagName("w:p")[0],r=t?t.getAttribute("w14:paraId"):null;if(!r&&e){let i=n.ownerDocument,s=mr(i);t||(t=i.createElement("w:p"),n.appendChild(t));let o=Sa(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=_r(a),t.setAttribute("w14:paraId",r),$a(i),s&&It(i);}return {paraId:r,firstP:t}}g(ss,"resolve_cell_anchor");var en=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},os=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 en(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);}}}},Ia=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=et(t),i=new os(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 tn{static{g(this,"_DocumentObject");}constructor(e,t){this.pkg=e,this.part=t;}pkg;part;settings={oddAndEvenPagesHeaderFooter:false};sections=[];get element(){return S(this.part._element,"w:body")||this.part._element}static async load(e,t){let r=e instanceof Uint8Array?e:new Uint8Array(e),i=ct(r),s=new Ia(i),o=i["[Content_Types].xml"],a={};if(o){let _=et(Qe(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=Qe(p),w=et(m);It(w);let y=a["/"+_]||"application/xml",b=new os("/"+_,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 en(m,y,w,b==="External"));}}return new tn(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 en(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 en(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=ei(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):(tn.KNOWN_MC_IGNORABLE_URIS[l]&&(e._element.setAttribute(d,tn.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=ei(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)]=Wt(t),e.blob=t;let s=e._element.ownerDocument;s&&It(s);}return Buffer.from(Kr(this.pkg.unzipped))}},Oa=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}},Le=class{static{g(this,"Run");}constructor(n,e){this._element=n,this._parent=e;}_element;_parent;projTextOverride;sdtStack=Oa},Da=class{static{g(this,"Cell");}constructor(n,e){this._element=n,this._parent=e;}_element;_parent},Ra=class{static{g(this,"Row");}constructor(n,e){this._element=n,this._parent=e;for(let t of rs(this._element,"w:tc"))this.cells.push(new Da(t,this));}_element;_parent;cells=[]},Xe=class{static{g(this,"Table");}constructor(n,e){this._element=n,this._parent=e;for(let t of rs(this._element,"w:tr"))this.rows.push(new Ra(t,this));}_element;_parent;rows=[]},ni=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},gt="w:sdt",ja="w:sdtPr",it="w:sdtContent",Ba=[["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"]],Fa=new Set(["checkbox","picture","building-block","repeating","repeating-item"]),La=new Set(["sdtContentLocked","contentLocked"]);function Ze(n){return n?n.getAttribute("w:val")??n.getAttribute("w14:val"):null}g(Ze,"val");function Ot(n){return !(Fa.has(n.cls)||n.cls==="richtext"&&n.hasNestedSdt)}g(Ot,"isAnchored");function Be(n){let e=n.flags.map(t=>` ${t}`).join("");return `{#cc:${n.ordinal}${e}}`}g(Be,"openToken");function Fe(n){return `{#/cc:${n.ordinal}}`}g(Fe,"closeToken");var as=new Set(["\u2610","\u2611","\u2612"]),ls="[",cs="]";function gr(n){return n.checked?"x":" "}g(gr,"checkboxMark");function Wa(n,e=0){let t=S(n,ja),r="richtext";if(t){for(let[T,I]of Ba)if(S(t,I)){r=T;break}}let i=Ze(t?S(t,"w:alias"):null),s=Ze(t?S(t,"w:tag"):null),o=Ze(t?S(t,"w:id"):null),a=Ze(t?S(t,"w:lock"):null),l=a!==null&&La.has(a),d=a==="sdtLocked"||a==="sdtContentLocked",c=t?S(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&&S(t,"w:showingPlcHdr")),m=t?S(t,"w:temporary"):null,w=m?Ze(m):null,y=!!m&&(w===null||["1","true","on"].includes(w)),b=S(n,it),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?S(t,r==="dropdown"?"w:dropDownList":"w:comboBox"):null;if(T){let I=[];for(let M of Array.from(T.childNodes)){if(M.nodeType!==1||M.tagName!=="w:listItem")continue;let B=M.getAttribute("w:displayText"),D=M.getAttribute("w:value");I.push([B??D??"",D??B??""]);}N=I;}}let k=null;if(r==="checkbox"){let T=t?S(t,"w14:checkbox"):null,I=Ze(T?S(T,"w14:checked"):null);k=I==="1"||I==="true";}let x=null;if(r==="date"){let T=t?S(t,"w:date"):null;x=Ze(T?S(T,"w:dateFormat"):null);}let C=!!b&&R(b,gt).length>0,A=[];return l&&r!=="group"&&A.push("locked"),u&&A.push("bound"),r==="group"&&A.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:C,ordinal:e,flags:A}}g(Wa,"classifySdt");function za(n){return n?R(n,gt):[]}g(za,"iterSdtElementsInOrder");function mn(n){let e=new Map,t=0;for(let r of n)for(let i of za(r))t+=1,e.set(i,Wa(i,t));return e}g(mn,"assignOrdinals");var Ua=new Set(["sdt_start","sdt_end","checkbox_start","checkbox_mark","checkbox_end"]);function wr(n){return !!n&&Ua.has(n.type)&&"info"in n}g(wr,"isSdtEvent");var ds=["checkbox_start","checkbox_mark","checkbox_end"];function us(n,e){let t=e+1<n.length?n[e+1]:null;return wr(t)&&t.type==="checkbox_end"}g(us,"nextClosesCheckbox");function gn(n){return n?.element??n?._element??n}g(gn,"partElement");var yr=class{static{g(this,"BlockSdt");}constructor(n){this.element=n;}element};function fs(n){let e=n?.parentNode;if(e&&e.tagName===it){let t=e.parentNode;if(t&&t.tagName===gt)return t}return null}g(fs,"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"},te={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"},ri=["w14:paraId","w15:paraId","w15:paraIdParent","w16cid:paraId"],ii=["w16cid:durableId","w16cex:durableId"],Ha=["w14:textId","w:rsidR","w:rsidRPr","w:rsidRDefault","w:rsidP","w:rsidDel","w:rsidTr"],Xa=[{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"}],hs=class extends Error{static{g(this,"CommentThreadingError");}constructor(n){super(n),this.name="CommentThreadingError";}};function*tr(n){yield n;for(let e=0;e<n.childNodes.length;e++){let t=n.childNodes[e];t.nodeType===1&&(yield*tr(t));}}g(tr,"walkElements");var Dt=class ps{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(te.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,te.COMMENTS,r),this.doc.relateTo(e,ke.COMMENTS),e}_getOrCreateExtendedPart(){let e=this._getExistingPartByType(te.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,te.EXTENDED,r),this.doc.relateTo(e,ke.EXTENDED),e}_getOrCreateIdsPart(){let e=this._getExistingPartByType(te.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,te.IDS,r),this.doc.relateTo(e,ke.IDS),e}_getOrCreateExtensiblePart(){let e=this._getExistingPartByType(te.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,te.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 pn(t,"w:style")){let l=a.getAttribute("w:styleId");l&&r.add(l);let d=S(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 Xa)r.has(a.style_id)||i.has(a.name)||(t.appendChild(ps._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(te.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",te.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(te.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 Xt()}_generateDurableId(){return Xt()}_getInitials(e){return e?e.split(" ").filter(Boolean).map(t=>t[0]).join("").toUpperCase():""}_hasCommentsPart(){return this._commentsPart!==null||this._getExistingPartByType(te.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(te.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 [te.COMMENTS,te.EXTENDED,te.IDS,te.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)?Xt():_r(r);for(;t.has(i);)i=Xt();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 tr(d))for(let u of s){let f=c.getAttribute(u);f&&(ti(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(ri),i=t(ii);for(let s of e)for(let o of tr(s)){for(let a of ri){let l=r.get(o.getAttribute(a)??"");l&&o.setAttribute(a,l);}for(let a of ii){let l=i.get(o.getAttribute(a)??"");l&&o.setAttribute(a,l);}for(let a of Ha){let l=o.getAttribute(a);l&&!ti(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(te.EXTENDED)!==null,o=null;if(r!=null&&(o=this.resolveThreadParentParaId(r),!o))throw new hs(`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 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",l),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 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 We(n){({part:n.mainDocumentPart,relateTo:g(()=>{},"relateTo")});let r=Object.create(null),i=n.parts.find(l=>l.contentType===te.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===te.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(We,"extract_comments_data");var Yn=500,ut=200,qa=["{++","++}","{--","--}","{==","==}","{>>","<<}"];function ms(n){if(!n||!n.includes("{")&&!n.includes("}"))return n;for(let e of qa)if(n.includes(e)){let t=e.startsWith("{")?"{ "+e.slice(1):e.slice(0,-1)+" }";n=n.split(e).join(t);}return n}g(ms,"escape_critic_tokens");function si(n,e){return n.length<=e?n:n.slice(0,Math.max(1,e-3))+"..."}g(si,"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 Ya={"\u201C":'"',"\u201D":'"',"\u2018":"'","\u2019":"'"},Ga=/[\u201c\u201d\u2018\u2019]/g;function Pt(n){return n&&n.replace(Ga,e=>Ya[e])}g(Pt,"normalize_smart_quotes");function nr(n){return !!n&&/[\u201c\u201d\u2018\u2019]/.test(n)}g(nr,"has_smart_quotes");function Ja(n,e){if(!n||!e||!nr(n))return e;let t=Pt(n),r=Pt(e);if(t===r)return n;let s=new _s.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(Ja,"restore_document_typography");function Va(n,e,t){return !t||!n||!nr(n)||nr(e||"")?t:Ja(n,t)}g(Va,"restore_matched_typography");var vr=2e3,ze=class extends Error{static{g(this,"RegexTimeoutError");}pattern;constructor(n){super(`Regular expression exceeded the ${vr/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 gs(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(gs,"hasCatastrophicBacktrackingRisk");function wn(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(wn,"extractInlineRegexFlags");function cn(n,e=""){let{pattern:t,flags:r}=wn(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(cn,"compileRegexWithInlineFlags");function Qa(n,e,t=""){let{pattern:r,flags:i}=wn(n,t);if(gs(r))throw new ze(n);let s=i.includes("g")?i:i+"g",o=cn(r,s),a=Date.now(),l=[],d;for(;(d=o.exec(e))!==null;){if(Date.now()-a>vr)throw new ze(n);l.push({start:d.index,end:d.index+d[0].length}),d.index===o.lastIndex&&o.lastIndex++;}return l}g(Qa,"userFindAllMatches");function Za(n,e,t=""){let{pattern:r,flags:i}=wn(n,t);if(gs(r))throw new ze(n);let s=cn(r,i.replace("g","")),o=Date.now(),a=s.exec(e);if(Date.now()-o>vr)throw new ze(n);return a?{start:a.index,end:a.index+a[0].length}:null}g(Za,"userSearch");var ws="w:p",br="w:r",jt="w:t",ys="w:delText",vs="w:tab",bs="w:br",xs="w:cr",nn="\f",yn="w:rPr",Ka="w:rPrChange",el="w:commentReference",tl="w:footnoteReference",nl="w:endnoteReference",rl="w:fldChar",il="w:fldCharType",sl="w:instrText",ol="w:ins",Ns="w:del",je="w:id",Gn="w:author",Jn="w:date",al="w:commentRangeStart",ll="w:commentRangeEnd",cl="w:hyperlink",dl="r:id",ul="w:fldSimple",fl="w:instr",hl="w:bookmarkStart",pl="w:name",Rt="w:sdt",_l="w:smartTag",xr="w:sdtContent",ks="w:b",ml="w:i",_e="w:val",Nr="w:pPr",Cs="w:pStyle",Es="w:outlineLvl",gl="w:numPr",wl="w:numId",yl="w:ilvl",rr="w:drawing",ir="w:object",sr="w:pict",vl="wp:docPr",bl="v:imagedata",xl="o:title",Nl="w:txbxContent",kl="mc:AlternateContent",Cl="mc:Choice",El="mc:Fallback",oi=300;function ai(n){let e=[];for(let r of R(n,Nl))for(let i of R(r,jt))i.textContent&&e.push(i.textContent);let t=e.join(" ").split(/\s+/).filter(Boolean).join(" ");return t.length>oi&&(t=t.slice(0,oi).trimEnd()+"\u2026"),t}g(ai,"_textbox_text");function*li(n){let e=n.tagName;if(e===rr||e===ir){let t=R(n,vl)[0]||null,r="",i="0";t&&(r=t.getAttribute("descr")||t.getAttribute("title")||"",i=t.getAttribute("id")||"0");let s=ai(n);s&&(r=r?`Text box (${r}): ${s}`:`Text box: ${s}`),yield {type:"image",id:i,date:r};}else if(e===sr){let t=R(n,bl)[0]||null,r=t&&t.getAttribute(xl)||"",i=ai(n);i&&(r=r?`Text box (${r}): ${i}`:`Text box: ${i}`),(i||t)&&(yield {type:"image",id:"vml",date:r});}}g(li,"_graphic_marker_events");var Al=/Heading[ ]?([1-6])(?![0-9])/;function Pl(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(Pl,"_resolve_package");function Ae(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=S(d,"w:name"),_=h?h.getAttribute("w:val"):c;_&&typeof _=="string"&&(_.toLowerCase().startsWith("heading")?_=_.replace(/^heading/i,"Heading"):_.toLowerCase()==="title"&&(_="Title"));let p=S(d,"w:basedOn"),m=p?p.getAttribute("w:val"):null,w=null,y=null,b=null,v=S(d,"w:pPr");if(v){let x=S(v,"w:outlineLvl");if(x){let A=x.getAttribute("w:val");A&&/^\d+$/.test(A)&&(w=parseInt(A,10));}let C=S(v,"w:numPr");if(C){let A=S(C,"w:numId");if(A){let I=A.getAttribute("w:val");I&&I!=="0"&&(y=I);}let T=S(C,"w:ilvl");if(T){let I=T.getAttribute("w:val");I&&/^\d+$/.test(I)&&(b=parseInt(I,10));}}}let N=null,k=S(d,"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[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(Ae,"_get_style_cache");var Tl={abstract_nums:new Map,nums:new Map},Sl=/%([1-9])/g,$l=[[1e3,"M"],[900,"CM"],[500,"D"],[400,"CD"],[100,"C"],[90,"XC"],[50,"L"],[40,"XL"],[10,"X"],[9,"IX"],[5,"V"],[4,"IV"],[1,"I"]];function qt(n,e){let t=[];for(let r=0;r<n.childNodes.length;r++){let i=n.childNodes[r];i&&i.nodeType===1&&i.tagName===e&&t.push(i);}return t}g(qt,"_directChildren");function ci(n){let e=n.getAttribute("w:ilvl");if(e===null||!/^-?\d+$/.test(e))return null;let t=parseInt(e,10),r=1,i=S(n,"w:start");if(i){let p=i.getAttribute("w:val");p!==null&&/^-?\d+$/.test(p)&&(r=parseInt(p,10));}let s="decimal",o=S(n,"w:numFmt");if(o){let p=o.getAttribute("w:val");p&&(s=p);}let a=null,l=S(n,"w:lvlText");if(l){let p=l.getAttribute("w:val");p!==null&&(a=p);}let d=false,c=S(n,"w:isLgl");if(c){let p=c.getAttribute("w:val");d=p!=="0"&&p!=="false"&&p!=="off";}let u=null,f=S(n,"w:lvlRestart");if(f){let p=f.getAttribute("w:val");p!==null&&/^-?\d+$/.test(p)&&(u=parseInt(p,10));}let h=null,_=S(n,"w:pStyle");if(_){let p=_.getAttribute("w:val");p&&(h=p);}return {ilvl:t,start:r,num_fmt:s,lvl_text:a,is_lgl:d,lvl_restart:u,p_style:h}}g(ci,"_parse_level_element");function Il(n){let e=Pl(n);if(!e)return Tl;if(e._adeu_numbering_defs)return e._adeu_numbering_defs;let t=new Map,r=new Map,i=null;try{let o=(e.parts||[]).find(a=>String(a.partname).endsWith("/numbering.xml"));o&&(i=o._element);}catch{i=null;}if(i){for(let o of qt(i,"w:abstractNum")){let a=o.getAttribute("w:abstractNumId");if(a===null)continue;let l=new Map;for(let h of qt(o,"w:lvl")){let _=ci(h);_!==null&&l.set(_.ilvl,_);}let d=S(o,"w:numStyleLink"),c=d?d.getAttribute("w:val"):null,u=S(o,"w:styleLink"),f=u?u.getAttribute("w:val"):null;t.set(a,{levels:l,num_style_link:c,style_link:f});}for(let o of qt(i,"w:num")){let a=o.getAttribute("w:numId"),l=S(o,"w:abstractNumId");if(a===null||!l)continue;let d=l.getAttribute("w:val");if(!d)continue;let c=new Map;for(let u of qt(o,"w:lvlOverride")){let f=u.getAttribute("w:ilvl");if(f===null||!/^-?\d+$/.test(f))continue;let h=null,_=S(u,"w:startOverride");if(_){let w=_.getAttribute("w:val");w!==null&&/^-?\d+$/.test(w)&&(h=parseInt(w,10));}let p=S(u,"w:lvl"),m=p?ci(p):null;c.set(parseInt(f,10),{start_override:h,lvl:m});}r.set(a,{abstract_num_id:d,overrides:c});}}let s={abstract_nums:t,nums:r};return e._adeu_numbering_defs=s,s}g(Il,"_get_numbering_defs");function di(n,e,t){let r=n.abstract_nums.get(e);if(!r)return null;if(r.num_style_link&&r.levels.size===0){let i=r.num_style_link;for(let s of n.abstract_nums.values())if(s.style_link===i&&s.levels.size>0)return s;if(t){let s=t[i],o=s?s.num_id:null;if(o&&n.nums.has(o)){let a=n.nums.get(o).abstract_num_id;if(a!==e)return n.abstract_nums.get(a)??r}}}return r}g(di,"_resolve_abstract_num");function Ol(n,e){if(e==="none")return "";if(e==="decimalZero")return n>=0&&n<10?String(n).padStart(2,"0"):String(n);if(e==="lowerLetter"||e==="upperLetter"){if(n<1)return String(n);let t=e==="lowerLetter"?97:65;return String.fromCharCode(t+(n-1)%26).repeat(Math.floor((n-1)/26)+1)}if(e==="lowerRoman"||e==="upperRoman"){if(n<1||n>3999)return String(n);let t=n,r="";for(let[i,s]of $l)for(;t>=i;)r+=s,t-=i;return e==="lowerRoman"?r.toLowerCase():r}if(e==="ordinal"){let t=Math.abs(n),r=t%100,i="th";if(r<11||r>13){let s=t%10;s===1?i="st":s===2?i="nd":s===3&&(i="rd");}return `${n}${i}`}return String(n)}g(Ol,"_format_ooxml_num");var Ue=class{static{g(this,"NumberingTracker");}_defs;_style_cache;resolve_numbering;_counters=new Map;constructor(n,e,t=true){this._defs=Il(n),this._style_cache=e,this.resolve_numbering=t;}snapshot(){let n=new Map;for(let[e,t]of this._counters.entries())n.set(e,new Map(t));return n}restore(n){this._counters=new Map;for(let[e,t]of n.entries())this._counters.set(e,new Map(t));}_effective_level_def(n,e,t){let r=n.overrides.get(t);if(r&&r.lvl)return r.lvl;if(e.levels.has(t))return e.levels.get(t);for(let i=t;i>=0;i--){let s=n.overrides.get(i);if(s&&s.lvl)return s.lvl;if(e.levels.has(i))return e.levels.get(i)}return null}_initial_start(n,e,t){let r=n.overrides.get(t);if(r&&r.start_override!==null)return r.start_override;let i=this._effective_level_def(n,e,t);return i?i.start:1}infer_ilvl(n,e,t){if(e!=null)return e;let r=this._defs.nums.get(n);if(!r)return 0;let i=di(this._defs,r.abstract_num_id,this._style_cache);if(!i||!t)return 0;for(let[s,o]of r.overrides.entries())if(o.lvl&&o.lvl.p_style===t)return s;for(let[s,o]of i.levels.entries())if(o.p_style===t)return s;return 0}next_marker(n,e,t,r=false){let i=this.infer_ilvl(n,e,t),s=this._defs.nums.get(n);if(!s)return [r?"":"* ",i];let o=di(this._defs,s.abstract_num_id,this._style_cache);if(!o)return [r?"":"* ",i];let a=this._effective_level_def(s,o,i);if(!a)return [r?"":"* ",i];if(a.num_fmt==="bullet")return [r?"":"* ",i];if(!this.resolve_numbering)return [r?"":"1. ",i];let l=this._counters.get(n);l||(l=new Map,this._counters.set(n,l));for(let u=0;u<i;u++)l.has(u)||l.set(u,this._initial_start(s,o,u));l.has(i)?l.set(i,l.get(i)+1):l.set(i,this._initial_start(s,o,i));for(let u of Array.from(l.keys())){if(u<=i)continue;let f=this._effective_level_def(s,o,u),h=f?f.lvl_restart:null;if(h===null)l.delete(u);else {if(h===0)continue;i<=h-1&&l.delete(u);}}if(a.num_fmt==="none"&&!a.lvl_text)return ["",i];let c=(a.lvl_text!==null?a.lvl_text:a.num_fmt==="none"?"":`%${i+1}.`).replace(Sl,(u,f)=>{let h=parseInt(f,10)-1,_=l.has(h)?l.get(h):this._initial_start(s,o,h),p=this._effective_level_def(s,o,h),m=p?p.num_fmt:"decimal",w=a.is_lgl&&h<i&&m!=="none"?"decimal":m;return Ol(_,w)}).replace(/\t/g," ").trim();return [c?`${c} `:"",i]}};function As(n){if(!n)return null;let e=n.match(Al);return e?parseInt(e[1],10):null}g(As,"_detect_heading_level_from_name");function Ps(n){let e=S(n,Nr);if(!e)return false;let t=S(e,yn);return !!t&&!!S(t,Ns)}g(Ps,"paragraph_mark_is_deleted");function vn(n,e,t){e||([e,t]=Ae(n._parent.part||n._parent));let r=S(n._element,Nr);if(r){let a=S(r,Es);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=S(r,Cs);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"&&As(o)!==null)}g(vn,"is_native_heading");function Ts(n,e,t,r,i=true){let s=n._parent?n._parent.part||n._parent:null;e||([e,t]=Ae(s));let o=S(n._element,Nr),a=t;if(o){let _=S(o,Cs);_&&(a=_.getAttribute(_e)||t);}let l=a&&e?e[a]:null,d=l?l.name:a;d&&typeof d=="string"&&d.toLowerCase().startsWith("heading")&&(d=d.replace(/^heading/i,"Heading"));let c=null,u=null,f=false;if(o){let _=S(o,gl);if(_){let p=S(_,wl);if(p){let m=p.getAttribute(_e);if(m==="0")f=true;else if(m){c=m;let w=S(_,yl);if(w){let y=w.getAttribute(_e);y!==null&&/^\d+$/.test(y)&&(u=parseInt(y,10));}}}}}if(c===null&&!f&&l){let _=l.num_id;_&&(c=_,u===null&&(u=l.num_ilvl!==void 0?l.num_ilvl:null));}let h=null;if(o){let _=S(o,Es);if(_){let p=_.getAttribute(_e);if(p&&/^\d+$/.test(p)){let m=parseInt(p,10);m>=0&&m<=8&&(h=m+1);}}}if(h===null&&l&&l.outline_level!==null&&l.outline_level>=0&&l.outline_level<=8&&(h=l.outline_level+1),h===null&&d)if(d.startsWith("Heading")){let _=d.replace("Heading","").trim();/^\d+$/.test(_)&&(h=parseInt(_,10));}else d==="Title"&&(h=1);if(h!==null){let _="#".repeat(h)+" ";if(c!==null&&i){let p=r??new Ue(s,e,i),[m]=p.next_marker(c,u,a,true);if(m)return [_+m,_]}return [_,null]}if(c!==null){let _=r??new Ue(s,e,i),[p,m]=_.next_marker(c,u,a,false),w=" ".repeat(m);if(p==="* ")return [w+"* ",null];let y=w+"1. ";return p?[w+p,y]:[w,y]}if(d&&d!=="Normal"){let _=As(d);if(_!==null)return ["#".repeat(_)+" ",null]}if(!d||d==="Normal"){let _=false,p=n._element;for(;p;){if(p.tagName==="w:tc"){_=true;break}p=p.parentNode;}if(_)return ["",null];let m=n.text.trim();if(m&&m.length<100&&m===m.toUpperCase()){let w=false;if(l?.bold)w=true;else {let y=R(n._element,br);for(let b of y)if(R(b,jt).map(k=>k.textContent||"").join("").trim()){let k=S(b,yn);if(k){let x=S(k,ks);x&&x.getAttribute(_e)!=="0"&&x.getAttribute(_e)!=="false"&&(w=true);}break}}if(w)return ["## ",null]}}return ["",null]}g(Ts,"get_paragraph_prefix_with_canonical");function De(n,e,t,r,i=true){return Ts(n,e,t,r,i)[0]}g(De,"get_paragraph_prefix");function Ss(n,e,t){let r=De(n,e,t,null,false);return r?/^#+ /.test(r):false}g(Ss,"is_heading_paragraph");function $s(n,e=null){if(n.projTextOverride!==void 0)return ["",""];let t="",r="",i=S(n._element,yn),s=false,o=false;if(i){let a=S(i,ks);a&&a.getAttribute(_e)!=="0"&&a.getAttribute(_e)!=="false"&&(s=true);let l=S(i,ml);l&&l.getAttribute(_e)!=="0"&&l.getAttribute(_e)!=="false"&&(o=true);}if(e===null){let a=n._parent;e=a instanceof ie?vn(a):false;}return s&&!e&&(t+="**",r="**"+r),o&&(t+="_",r="_"+r),[t,r]}g($s,"get_run_style_markers");function Is(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(Is,"split_boundary_whitespace");function Os(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(Os,"compute_change_pair_map");function Dl(n,e,t){if(!e&&!t)return n;if(!n)return "";let r=g(s=>{let[o,a,l]=Is(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(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
-
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(`
19
-
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(`
22
-
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(`
24
-
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(`
26
-
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(`
34
- `,n-1)+1,r=this.full_text.indexOf(`
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===`
36
-
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]!==`
12
+ `):r(n)}g(Dl,"apply_formatting_to_segments");function Rl(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(Rl,"revisionBallotMark");function Ml(n){let e=S(n,xr);if(!e)return false;for(let t of R(e,br)){let r="";for(let i of R(t,jt))r+=i.textContent||"";if(as.has(r))return true}return false}g(Ml,"hasBallotRun");function jl(n,e,t){if(!t||!as.has(e))return;let r=n.parentNode;for(;r&&r.nodeType===1;){if(r.tagName===Rt){let i=t.get(r);return i&&i.cls==="checkbox"?i:void 0}r=r.parentNode;}}g(jl,"enclosingCheckbox");function Oe(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===jt||r.tagName===ys){let i=r.textContent||"";e+=i.replace(/\t/g," ");}else r.tagName===vs||r.tagName==="w:ptab"?e+=" ":r.tagName==="w:noBreakHyphen"?e+="-":r.tagName===bs?e+=r.getAttribute("w:type")==="page"?nn:`
13
+ `:r.tagName===xs&&(e+=`
14
+ `);}return e}g(Oe,"get_run_text");function*qe(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 Ma(s,n,n.note_type));}return}yield*Ds(t,n,e);}g(qe,"iter_block_items");function*Ds(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===ws)yield new ie(i,e);else if(i.tagName==="w:tbl")yield new Xe(i,e);else if(i.tagName===Rt){let s=S(i,xr);s&&(t?yield new yr(i):yield*Ds(s,e,t));}}}}g(Ds,"_iter_block_children");function*Bl(n){for(let[e]of tt(n))yield e;}g(Bl,"iter_document_parts");function*Fl(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===ws){let a=S(o,"w:pPr"),l=a&&S(a,"w:sectPr");l&&(yield l);}else if(o.tagName===Rt){let a=S(o,"w:sdtContent");a&&(yield*t(a));}}}}g(t,"walk"),yield*t(e);let r=S(e,"w:sectPr");r&&(yield r);}g(Fl,"_iter_sect_pr");function Ll(n){let e=n.pkg.getPartByPath("word/settings.xml");return e?S(e._element,"w:evenAndOddHeaders")!==null:false}g(Ll,"_odd_and_even_pages");function*ui(n,e){let t=e==="header"?"w:headerReference":"w:footerReference",r=Ll(n);for(let i of Fl(n)){let s=pn(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),S(i,"w:titlePg")!==null){let d=a(o("first"));d&&(yield d);}if(r){let d=a(o("even"));d&&(yield d);}}}g(ui,"_iter_section_parts");function*tt(n){for(let r of ui(n,"header"))yield [r,"header"];yield [n,"body"];for(let r of ui(n,"footer"))yield [r,"footer"];let e=n.pkg.getPartByPath("word/footnotes.xml"),t=n.pkg.getPartByPath("word/endnotes.xml");e&&(yield [new ni(e,"fn"),"footnotes"]),t&&(yield [new ni(t,"en"),"endnotes"]);}g(tt,"iter_document_parts_with_kind");function Wl(n){if(!n)return false;let e=n.toUpperCase().trim().split(/\s+/);return e.length>0&&(e[0]==="PAGE"||e[0]==="NUMPAGES")}g(Wl,"_is_page_instr");function Rs(n){return n?n.part?n.part:n.pkg&&n.pkg.mainDocumentPart?n.pkg.mainDocumentPart:n._parent?Rs(n._parent):null:null}g(Rs,"_get_part");function*bn(n,e){let t=false,r="",i=false,s=[];function*o(l){let d=null,c=S(l,yn);if(c){let u=S(c,Ka);u&&(d=u.getAttribute(je),yield {type:"fmt_start",id:d,author:u.getAttribute(Gn)||void 0,date:u.getAttribute(Jn)||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===rr||h===ir||h===sr)yield*li(f);else if(h===kl){let _=null;for(let p of [Cl,El]){for(let m of pn(f,p))if(_=S(m,rr)||S(m,ir)||S(m,sr),_)break;if(_)break}_&&(yield*li(_));}else if(h===el){let _=f.getAttribute(je);_&&(yield {type:"ref",id:_});}else if(h===tl){let _=f.getAttribute(je);_&&(yield {type:"footnote",id:_});}else if(h===nl){let _=f.getAttribute(je);_&&(yield {type:"endnote",id:_});}else if(h===rl){let _=f.getAttribute(il);if(_==="begin")t=true,r="";else if(_==="separate")if(Wl(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===sl&&t&&!i&&(r+=f.textContent||"");}if(!i){let u=new Le(l,n);s.length&&(u.sdtStack=s.slice());let f=jl(l,Oe(u),e);if(f){let h=Oe(u);u.projTextOverride=Rl(l,h)??gr(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===br)yield*o(c);else if(u===ol){let f=c.getAttribute(je);yield {type:"ins_start",id:f,author:c.getAttribute(Gn)||void 0,date:c.getAttribute(Jn)||void 0},yield*a(c),yield {type:"ins_end",id:f};}else if(u===Ns){let f=c.getAttribute(je);yield {type:"del_start",id:f,author:c.getAttribute(Gn)||void 0,date:c.getAttribute(Jn)||void 0},yield*a(c),yield {type:"del_end",id:f};}else if(u===al)yield {type:"start",id:c.getAttribute(je)};else if(u===ll)yield {type:"end",id:c.getAttribute(je)};else if(u===cl){let f=c.getAttribute(dl)||c.getAttribute("id"),h="",_=Rs(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===ul){let h=(c.getAttribute(fl)||"").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===hl){let f=c.getAttribute(pl);f&&(!f.startsWith("_")||f.startsWith("_Ref"))&&(yield {type:"bookmark",id:f});}else if(u===Rt||u===_l||u===xr){let f=e?e.get(c):void 0,h=!!f&&u===Rt;h&&s.push(f);try{f&&f.cls==="checkbox"&&!Ml(c)?(yield {type:"checkbox_start",info:f},yield {type:"checkbox_mark",info:f},yield {type:"checkbox_end",info:f}):!f||!Ot(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(bn,"iter_paragraph_content");var zl=new Set(["**","__","*","_"]),or=/\[~[^~\]]+~\]\(#[^)]+\)|(?<!!)\[(?!~)[^\]]+\]\((?!docx-image:)[^)]+\)|\{#(?!\/?cc:|cell:)[^}]+\}/g;function Ul(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(Ul,"isAnchorMarkerSyntax");function Yt(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(Yt,"bisectLeft");var Ee=class Ms{static{g(this,"_DocumentMapper");}doc;clean_view;original_view;resolve_numbering;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(e,t=false,r=false,i=true){this.doc=e,this.clean_view=t,this.original_view=r,this.resolve_numbering=i,this.comments_map=We(e.pkg),this._build_map();}_build_map(){let e=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=mn(Array.from(tt(this.doc)).map(([i])=>gn(i)));let t=0,r=false;for(let[i,s]of tt(this.doc)){this._current_part_index=t,this.part_names.push(String(i?.partname??i?.part?.partname??"").replace(/^\//,""));let o=this.spans.length,a=this._text_chunks.length,l=e;r&&(this._add_virtual_text(`
15
+
16
+ `,e,null),e+=2);let d=e,c=i.part||i,[u]=Ae(c),f=new Ue(c,u,this.resolve_numbering);e=this._map_blocks(i,e,false,f),e===d?(this.spans.length=o,this._text_chunks.length=a,e=l,this.part_ranges.push([e,e,s])):(r=true,this.part_ranges.push([d,e,s])),t++;}this.full_text=this._text_chunks.join(""),this._buildControlRanges(),this.appendix_start_index=-1;}_spanSdtStack(e){let t=this._current_block_sdt_stack,r=e?.sdtStack??[];return t.length===0?r:r.length===0?t.slice():[...t,...r]}_buildControlRanges(){let e=new Map;for(let t of this.spans)if(!(!t.sdt_stack||t.sdt_stack.length===0))for(let r of t.sdt_stack){let i=e.get(r);i===void 0?e.set(r,[t.start,t.end]):(t.start<i[0]&&(i[0]=t.start),t.end>i[1]&&(i[1]=t.end));}this.control_ranges=Array.from(e.entries()).map(([t,[r,i]])=>[r,i,t]).sort((t,r)=>t[0]-r[0]||r[1]-t[1]);}controls_at(e){return this.control_ranges.filter(([t,r])=>t<=e&&e<r).map(([,,t])=>t)}controls_intersecting(e,t){if(t<=0)return [];let r=e+t;return this.control_ranges.filter(([i,s])=>s>e&&i<r).map(([,,i])=>i)}_nonempty_part_ranges(){let e=[];for(let t=0;t<this.part_ranges.length;t++){let[r,i,s]=this.part_ranges[t];i>r&&e.push([t,r,i,s]);}return e}part_kind_of(e){return e>=0&&e<this.part_ranges.length?this.part_ranges[e][2]:null}part_kind_at(e){for(let[,t,r,i]of this._nonempty_part_ranges())if(t<=e&&e<=r)return i;return null}part_label_at(e){for(let[t,r,i,s]of this._nonempty_part_ranges())if(r<=e&&e<=i){if(s==="body")return "";let o=this.part_names[t]||"";return o?`${s} (${o})`:s}return ""}body_edge_line(e=false){for(let[t,r,i]of this.part_ranges)if(i==="body"&&r>t){let s=this.full_text.substring(t,r).split(`
17
+ `).map(o=>o.trim()).filter(o=>o);if(s.length)return (e?s[s.length-1]:s[0]).substring(0,80)}return ""}part_boundary_at(e){let t=this._nonempty_part_ranges();for(let r=1;r<t.length;r++){let[i,,s]=t[r-1],[o,a]=t[r];if(s<e&&e<=a)return [i,o]}return null}_map_blocks(e,t,r=false,i){let s=t,o=e.constructor.name,a=e.part||e,[l,d]=Ae(a),c=i??new Ue(a,l,this.resolve_numbering),u=false;if(o==="NotesPart"){let p=`---
18
+ ${e.note_type==="fn"?"## Footnotes":"## Endnotes"}`;this._add_virtual_text(p,s,null),s+=p.length,u=true;}let f=true,h=null;for(let _ of qe(e,true)){let p=_.constructor.name,m=this.spans.length,w=this._text_chunks.length,y=s;if(_ instanceof yr){if(u){let x=h instanceof ie?h:null;this._add_virtual_text(`
19
+
20
+ `,s,x),s+=2;}let b=this._sdt_infos.get(_.element),v=!!b&&Ot(b),N=r?"":`
21
+ `;if(v){let x=`${Be(b)}${N}`;this._add_virtual_text(x,s,null),s+=x.length;}let k=s;b&&this._current_block_sdt_stack.push(b);try{s=this._map_blocks({_element:S(_.element,"w:sdtContent"),part:e.part||e},s,r,c);}finally{b&&this._current_block_sdt_stack.pop();}if(s===k)this.spans.length=m,this._text_chunks.length=w,s=y;else {if(v){let x=`${N}${Fe(b)}`;this._add_virtual_text(x,s,null),s+=x.length;}u=true;}f=false;}else if(p==="FootnoteItem"){if(u){let v=h instanceof ie?h:null;this._add_virtual_text(`
22
+
23
+ `,s,v),s+=2;}let b=s;s=this._map_blocks(_,s,false,c),s===b?(this.spans.length=m,this._text_chunks.length=w,s=y):u=true;}else if(_ instanceof ie){let b=c.snapshot();if(u){let x=h instanceof ie?h:null;this._add_virtual_text(`
24
+
25
+ `,s,x),s+=2;}let[v,N]=Ts(_,l,d,c,this.resolve_numbering);if(f&&o==="FootnoteItem"){let x=`[^${e.note_type}-${e.id}]: `;this._add_virtual_text(x,s,_),s+=x.length;}v&&(this._add_virtual_text(v,s,_,null,false,N),s+=v.length);let k=s;if(s=this._map_paragraph_content(_,s,l,d),this.clean_view&&s===k&&Ps(_._element)){c.restore(b),this.spans.length=m,this._text_chunks.length=w,s=y,f=false;continue}f=false,u=true,h=_;}else if(_ instanceof Xe){if(u){let v=h instanceof ie?h:null;this._add_virtual_text(`
26
+
27
+ `,s,v),s+=2;}let b=s;s=this._map_table(_,s,c),s===b?(this.spans.length=m,this._text_chunks.length=w,s=y):u=true,f=false,h=_;}}return s}_wrappingControl(e){let t=fs(e);return t?this._sdt_infos.get(t)??null:null}_anchoredWrapper(e){let t=this._wrappingControl(e);return t&&Ot(t)?t:null}_map_table(e,t,r){let i=t,s=0;for(let o of e.rows){let a=o._element,l=S(a,"w:trPr"),d=l?S(l,"w:ins"):null,c=l?S(l,"w:del"):null;if(this.clean_view&&c||this.original_view&&d)continue;s>0&&(this._add_virtual_text(`
28
+ `,i,null),i+=1),d&&!this.clean_view&&!this.original_view?(this._add_virtual_text("{++ ",i,null),i+=4):c&&!this.clean_view&&!this.original_view&&(this._add_virtual_text("{-- ",i,null),i+=4);let u=this._wrappingControl(a),f=this._anchoredWrapper(a);if(f){let p=Be(f);this._add_virtual_text(p,i,null),i+=p.length;}let h=new Set,_=0;for(let p of o.cells){if(h.has(p))continue;h.add(p),_>0&&(this._add_virtual_text(" | ",i,null),i+=3);let m=this._wrappingControl(p._element),w=this._anchoredWrapper(p._element);if(w){let v=Be(w);this._add_virtual_text(v,i,null),i+=v.length;}let y=i,b=[u,m].filter(v=>v!==null);this._current_block_sdt_stack.push(...b);try{i=this._map_blocks(p,i,!0,r);}finally{for(let v=0;v<b.length;v++)this._current_block_sdt_stack.pop();}if(w){let v=Fe(w);this._add_virtual_text(v,i,null),i+=v.length;}if(!this.clean_view&&!this.original_view){let{paraId:v,firstP:N}=ss(p._element,i===y);if(v&&N){let k=new ie(N,p);if(this._add_virtual_text("",i,k),y<i){let C="";for(let A=this._text_chunks.length-1;A>=0;A--){let T=this._text_chunks[A];if(T){C=T[T.length-1];break}}C!==" "&&(this._add_virtual_text(" ",i,k),i+=1);}let x=`{#cell:${v}}`;this._add_virtual_text(x,i,k),i+=x.length;}}_+=1;}if(f){let p=Fe(f);this._add_virtual_text(p,i,null),i+=p.length;}if(d&&!this.clean_view&&!this.original_view){let p=` ++}{>>[Chg:${d.getAttribute("w:id")} insert] ${d.getAttribute("w:author")||"Unknown"}<<}`;this._add_virtual_text(p,i,null),i+=p.length;}else if(c&&!this.clean_view&&!this.original_view){let p=` --}{>>[Chg:${c.getAttribute("w:id")} delete] ${c.getAttribute("w:author")||"Unknown"}<<}`;this._add_virtual_text(p,i,null),i+=p.length;}if(s+=1,s===1){let p=new Set,m=0;for(let w of o.cells)p.has(w)||(p.add(w),m+=1);if(m>0){let w=Array(m).fill("---").join(" | ");this._add_virtual_text(`
29
+ `,i,null),i+=1,this._add_virtual_text(w,i,null),i+=w.length;}}}return i}_strip_markdown_formatting(e){let t=e;return t=t.replace(/^#+\s*/gm,""),t=t.replace(/\*\*(\w[\w\s]*\w|\w{2,})\*\*/g,"$1"),t=t.replace(/__(\w[\w\s]*\w|\w{2,})__/g,"$1"),t=t.replace(/(?<!\w)_(\w[\w\s]*\w|\w{2,})_(?!\w)/g,"$1"),t=t.replace(/(?<!\w)\*(\w[\w\s]*\w|\w{2,})\*(?!\w)/g,"$1"),t}_map_paragraph_content(e,t,r,i){let s=t,o={start:s,end:s,text:"",run:null,paragraph:e,part_index:this._current_part_index,sdt_stack:this._spanSdtStack()};this.spans.push(o);let a=new Set,l=Object.create(null),d=Object.create(null),c=Object.create(null),u=[],f=null,h=["",""],_=["",""],p=null,m=[],w=g(()=>{if(m.length===0)return;let[k,x]=h;k&&(this._add_virtual_text(k,s,e),s+=k.length);for(let[C,A,T,I,M,B,D]of m){if(C==="virtual")this._add_virtual_text(A,s,e,p);else {let j={start:s,end:s+A.length,text:A,run:T,paragraph:e,ins_id:M||void 0,del_id:B||void 0,hyperlink_id:p||void 0,comment_ids:D.length>0?D:void 0,part_index:this._current_part_index,run_offset:I,sdt_stack:this._spanSdtStack(T)};this.spans.push(j),this._text_chunks.push(A);}s+=A.length;}x&&(this._add_virtual_text(x,s,e),s+=x.length),m=[];},"flush_pending_runs"),y=Array.from(bn(e,this._sdt_infos)),b=Ss(e,r,i),v=vn(e,r,i),N=b;for(let k=0;k<y.length;k++){let x=y[k];if(x instanceof Le){let[C,A]=$s(x,v),T=[],I=Oe(x);if(N){if(I===""||/^\s*$/.test(I))continue;N=false;}let M=0,B=g(E=>{let[$,P,O]=Is(E);if(!P){T.push(["real",E,x,M]),M+=E.length;return}$&&(T.push(["real",$,x,M]),M+=$.length),C&&T.push(["virtual",C,null,0]),T.push(["real",P,x,M]),M+=P.length,A&&T.push(["virtual",A,null,0]),O&&(T.push(["real",O,x,M]),M+=O.length);},"append_wrapped");if(I.includes(`
30
+ `)&&(C||A)){let E=I.split(`
31
+ `);for(let $=0;$<E.length;$++)$>0&&(T.push(["real",`
32
+ `,x,M]),M+=1),E[$]&&B(E[$]);}else (C||A)&&I?B(I):I&&T.push(["real",I,x,0]);this.clean_view&&Object.keys(d).length>0,this.original_view&&Object.keys(l).length>0;let D=T.map(E=>E[1]).join(""),j=Object.keys(l).pop()||null,F=Object.keys(d).pop()||null;if(D&&!(this.clean_view&&F)&&!(this.original_view&&j)){let E=this.clean_view||this.original_view?["",""]:this._get_wrappers(j,F,a,c),$=[C,A];if(m.length>0&&E[0]===h[0]&&E[1]===h[1]){let P=g(U=>U.length>0&&/^\s+$/.test(U),"isWs"),O=T;if($[0]===_[0]&&$[1]===_[1]&&!(_[0]===""&&_[1]==="")){let U=m.length-1;for(;U>=0&&m[U][0]==="real"&&P(m[U][1]);)U--;let X=U>=0&&m[U][0]==="virtual"&&m[U][1]===_[1],z=0;for(;z<T.length&&T[z][0]==="real"&&P(T[z][1]);)z++;let H=z<T.length&&T[z][0]==="virtual"&&T[z][1]===$[0];X&&H&&(m.splice(U,1),O=T.slice(0,z).concat(T.slice(z+1)));}let W=Array.from(a);for(let[U,X,z,H]of O)m.push([U,X,z,H,j,F,W]);_=$;}else {w(),h=E,_=$;let P=Array.from(a);for(let[O,W,U,X]of T)m.push([O,W,U,X,j,F,P]);}}if(!this.clean_view&&!this.original_view){(Object.keys(l).length>0||Object.keys(d).length>0||a.size>0||Object.keys(c).length>0)&&u.push([{...l},{...d},new Set(a),{...c}]);let $=false;if(j!==null||F!==null||Object.keys(c).length>0||a.size>0){let O=k+1,W=false,U=Object.keys(l).length,X=Object.keys(d).length,z=Object.keys(c).length,H=new Set(a);for(;O<y.length;){let q=y[O];if(q instanceof Le){if(!Oe(q)){O++;continue}(U>0||X>0||z>0||H.size>0)&&(W=true);break}else {let V=q;V.type==="ins_start"?U++:V.type==="ins_end"?U=Math.max(0,U-1):V.type==="del_start"?X++:V.type==="del_end"?X=Math.max(0,X-1):V.type==="fmt_start"?z++:V.type==="fmt_end"?z=Math.max(0,z-1):V.type==="start"?H.add(V.id):V.type==="end"&&H.delete(V.id);}O++;}W&&($=true);}if(!$&&u.length>0){let O=this._build_merged_meta_block(u);if(O)if(us(y,k))f=O;else {w(),h=["",""],_=["",""];let W=`{>>${O}<<}`;this._add_virtual_text(W,s,e),s+=W.length;}u=[];}}}else if(wr(x)){N=false;let C=x.info;if(ds.includes(x.type)){if(this.clean_view&&Object.keys(d).length>0)continue;let T=x.type==="checkbox_start"?ls:x.type==="checkbox_end"?cs:gr(C),I=this.clean_view||this.original_view?["",""]:this._get_wrappers(Object.keys(l).pop()||null,Object.keys(d).pop()||null,a,c);if(m.length>0&&(I[0]!==h[0]||I[1]!==h[1])&&w(),m.length===0&&(h=I),m.push(["virtual",T,null,0,null,null,[]]),_=["",""],x.type==="checkbox_end"&&f){w(),h=["",""];let M=`{>>${f}<<}`;this._add_virtual_text(M,s,e),s+=M.length,f=null;}continue}w(),h=["",""],_=["",""];let A;x.type==="sdt_start"?(A=Be(C),!this.clean_view&&C.showingPlaceholder&&C.placeholderText&&(A+=`{>>placeholder: ${C.placeholderText}<<}`)):A=Fe(C),this._add_virtual_text(A,s,e),s+=A.length;}else {let C=x;if(N=false,w(),h=["",""],_=["",""],C.type==="start")a.add(C.id);else if(C.type==="end")a.delete(C.id);else if(C.type==="ins_start")l[C.id]=C;else if(C.type==="ins_end")delete l[C.id];else if(C.type==="del_start")d[C.id]=C;else if(C.type==="del_end")delete d[C.id];else if(C.type==="fmt_start")c[C.id]=C;else if(C.type==="fmt_end")delete c[C.id];else if(C.type==="image"){if(!(this.clean_view&&Object.keys(d).length>0||this.original_view&&Object.keys(l).length>0)){let I=`![${(C.date||"image").replace(/\]/g,")").replace(/\n/g," ")}](docx-image:${C.id})`;this._add_virtual_text(I,s,e,null,true),s+=I.length;}}else if(C.type==="footnote"||C.type==="endnote"){w(),h=["",""],_=["",""];let T=`[^${C.type==="footnote"?"fn":"en"}-${C.id}]`;this._add_virtual_text(T,s,e),s+=T.length;}else if(C.type==="hyperlink_start")w(),h=["",""],_=["",""],this._add_virtual_text("[",s,e,C.id),s+=1,p=C.id;else if(C.type==="hyperlink_end"){w(),h=["",""],_=["",""];let A=`](${C.date})`;this._add_virtual_text(A,s,e,C.id),s+=A.length,p=null;}else if(C.type==="xref_start")w(),h=["",""],_=["",""],this._add_virtual_text("[~",s,e),s+=2;else if(C.type==="xref_end"){w(),h=["",""],_=["",""];let A=`~](#${C.id})`;this._add_virtual_text(A,s,e),s+=A.length;}else if(C.type==="bookmark"){w(),h=["",""],_=["",""];let A=`{#${C.id}}`;this._add_virtual_text(A,s,e),s+=A.length;}}}if(w(),u.length>0){let k=this._build_merged_meta_block(u);if(k){let x=`{>>${k}<<}`;this._add_virtual_text(x,s,e),s+=x.length;}}return s}_get_wrappers(e,t,r,i){return t?["{--","--}"]:e?["{++","++}"]:r.size>0||Object.keys(i).length>0?["{==","==}"]:["",""]}_build_merged_meta_block(e){let t=[],r=[],i=new Set,s=Os(e),o=g(a=>s[a]?` (pairs with ${s[a]})`:"","pairSuffix");for(let[a,l,d,c]of e){for(let[f,h]of Object.entries(a)){let _=`Chg:${f}`;if(!i.has(_)){let p=h.author||"Unknown";t.push(`[${_} insert] ${p}${o(f)}`),i.add(_);}}for(let[f,h]of Object.entries(l)){let _=`Chg:${f}`;if(!i.has(_)){let p=h.author||"Unknown";t.push(`[${_} delete] ${p}${o(f)}`),i.add(_);}}for(let[f,h]of Object.entries(c)){let _=`Chg:${f}`;if(!i.has(_)){let p=h.author||"Unknown";t.push(`[${_} format] ${p}`),i.add(_);}}let u=Array.from(d).sort();for(let f of u){if(!this.comments_map[f])continue;let h=`Com:${f}`;if(!i.has(h)){let _=this.comments_map[f],p=`[${h}] ${_.author}`;_.date&&(p+=` @ ${_.date}`),_.resolved&&(p+="(RESOLVED)"),r.push(`${p}: ${ms(_.text)}`),i.add(h);}}}return [...t,...r].join(`
33
+ `)}_add_virtual_text(e,t,r,i=null,s=false,o=null){let a={start:t,end:t+e.length,text:e,run:null,paragraph:r,hyperlink_id:i||void 0,part_index:this._current_part_index,is_image_marker:s||void 0,sdt_stack:this._spanSdtStack(),canonical_prefix:o||void 0};this.spans.push(a),this._text_chunks.push(e);}_replace_smart_quotes(e){return e.replace(/“/g,'"').replace(/”/g,'"').replace(/‘/g,"'").replace(/’/g,"'")}_make_fuzzy_regex(e){e=this._strip_markdown_formatting(e),e=this._replace_smart_quotes(e);let t=[],r=/(\[_+\])|(\s+)|(['"])|([.,;:\/\-\[\](){}+=$?*!|#^<>\\%&@~`_])/g,i=0,s,o=g(l=>l.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"escapeRegExp");for(;(s=r.exec(e))!==null;){let l=e.substring(i,s.index);l&&t.push(o(l));let d=s[1],c=s[2],u=s[3],f=s[4];d?t.push("\\[_+\\]"):c?(t.push("(?:\\*\\*|__|\\*|_)?"),t.push("\\s+"),t.push("(?:\\*\\*|__|\\*|_)?")):u?u==="'"?t.push("[\u2018\u2019']"):t.push('["\u201C\u201D]'):f&&(t.push("(?:\\*\\*|__|\\*|_)?"),t.push(o(f)),t.push("(?:\\*\\*|__|\\*|_)?")),i=r.lastIndex;}let a=e.substring(i);return a&&t.push(o(a)),t.join("")}_get_plain_projection(){if(this._plain_projection===null){let e=[],t=[];for(let r of this.spans)if(!(r.run===null&&r.paragraph!==null&&zl.has(r.text))&&!Ul(r)){e.push(r.text);for(let i=r.start;i<r.end;i++)t.push(i);}this._plain_projection=[e.join(""),t];}return this._plain_projection}_find_plain_projection_matches(e){let[t,r]=this._get_plain_projection();if(t.length===this.full_text.length)return [];let i=this._replace_smart_quotes(this._strip_markdown_formatting(e));if(!i)return [];let s=this._replace_smart_quotes(t),o=[],a=0;for(;;){let l=s.indexOf(i,a);if(l===-1)break;let d=l+i.length,[c,u]=this._widen_to_anchor_markers(r[l],r[d-1]+1);o.push([c,u-c]),a=d;}return o}static _CALLER_CLAUSE_PREFIX_RE=/^([ \t]*(?:#+\s+)?(?:(?:§|Article|ARTICLE|Part|PART|Clause|CLAUSE|Section|SECTION|ust\.|pkt)\s+)?(?:\([a-zA-Z0-9]+\)|[0-9IVXLCDMa-zA-Z]+(?:\.[0-9a-zA-Z]+)*[.)]?)\s+)([\s\S]+)$/;_find_list_prefix_matches(e){if(!e)return [];let t=this._replace_smart_quotes(this.full_text),r=Ms._CALLER_CLAUSE_PREFIX_RE.exec(e),i=e.trimStart().startsWith("#"),s=[];for(let o of this.spans){if(o.run!==null||!o.canonical_prefix)continue;let a=o.canonical_prefix.trimStart().startsWith("#");if(i!==a)continue;let l=null;if(e.startsWith(o.canonical_prefix)?l=e.slice(o.canonical_prefix.length):r!==null&&(l=r[2]),!l)continue;let d=this._replace_smart_quotes(l),c=o.end+d.length;if(c<=t.length&&t.slice(o.end,c)===d){let u=o.end-o.start+l.length;this.range_is_virtual_only(o.start,u)||s.push([o.start,u]);}}return s}_widen_to_anchor_markers(e,t){let r=this.full_text.lastIndexOf(`
34
+ `,e-1)+1,i=this.full_text.indexOf(`
35
+ `,t);i===-1&&(i=this.full_text.length);let s=this.full_text.substring(r,i);for(let o of s.matchAll(or)){let a=r+o.index,l=a+o[0].length;a<t&&l>e&&(e=Math.min(e,a),t=Math.max(t,l));}return [e,t]}anchor_markers_in_range(e,t){let[r,i]=this._get_plain_projection(),s=e+t,o=Yt(i,e),a=Yt(i,s),l=i.slice(o,a),d=[],c=this.full_text.substring(e,s);for(let u of c.matchAll(or)){let f=e+u.index;d.push([u[0],Yt(l,f),Yt(l,f+u[0].length)]);}return [r.substring(o,a),d]}range_is_virtual_only(e,t){let r=e+t,i=this.spans.filter(s=>s.end>e&&s.start<r);return i.some(s=>s.run!==null)?false:!i.some(s=>s.run===null&&s.text.startsWith("{#"))}drop_virtual_only_matches(e){return e.filter(([t,r])=>!this.range_is_virtual_only(t,r))}find_match_index(e,t=false){if(t){try{let c=Za(e,this.full_text);if(c&&!this.range_is_virtual_only(c.start,c.end-c.start))return [c.start,c.end-c.start]}catch(c){if(c instanceof ze)throw c}return [-1,0]}let r=0;for(;;){let c=this.full_text.indexOf(e,r);if(c===-1)break;if(!this.range_is_virtual_only(c,e.length))return [c,e.length];r=c+1;}let i=this._replace_smart_quotes(this.full_text),s=this._replace_smart_quotes(e),o=i.indexOf(s);if(o!==-1)return [o,e.length];let a=this._strip_markdown_formatting(e);if(this.full_text.includes(a))return o=this.full_text.indexOf(a),[o,a.length];let l=this._find_plain_projection_matches(e);if(l.length>0)return l[0];try{let c=new RegExp(this._make_fuzzy_regex(e),"g");for(let u of this.full_text.matchAll(c))if(!this.range_is_virtual_only(u.index,u[0].length))return [u.index,u[0].length]}catch{}let d=this._find_list_prefix_matches(e);return d.length>0?d[0]:[-1,0]}find_all_match_indices(e,t=false){if(!e)return [];if(t){try{let c=Qa(e,this.full_text);if(c.length>0)return c.map(u=>[u.start,u.end-u.start])}catch(c){if(c instanceof ze)throw c}return []}let r=g((c,u)=>{let f=[];if(!u)return f;let h=0;for(;;){let _=c.indexOf(u,h);if(_===-1)break;f.push([_,u.length]),h=_+u.length;}return f},"findAllLiteral"),i=r(this.full_text,e);if(i.length>0)return i;let s=this._replace_smart_quotes(this.full_text),o=this._replace_smart_quotes(e);if(i=r(s,o),i.length>0)return i;let a=this._strip_markdown_formatting(e);if(i=r(this.full_text,a),i.length>0)return i;let l=this._find_plain_projection_matches(e);if(l.length>0)return l;try{let c=new RegExp(this._make_fuzzy_regex(e),"g"),u=[...this.full_text.matchAll(c)];if(u.length>0)return u.map(f=>[f.index,f[0].length])}catch{}let d=this._find_list_prefix_matches(e);return d.length>0?d:[]}find_target_runs(e){let[t,r]=this.find_match_index(e);return t===-1?[]:this._resolve_runs_at_range(t,t+r)}find_target_runs_by_index(e,t,r=true){return this._resolve_runs_at_range(e,e+t,r)}get_virtual_spans_in_range(e,t){let r=e+t;return this.spans.filter(i=>i.run===null&&i.text===`
36
+
37
+ `&&i.start>=e&&i.end<=r)}_resolve_runs_at_range(e,t,r=true){let i=this.spans.filter(w=>w.end>e&&w.start<t);if(i.length===0)return [];let s=i.filter(w=>w.run!==null);if(s.length===0)return [];let o=[];for(let w of s)o.some(y=>y===w.run)||o.push(w.run);let a=false,l=s[0],d=0,c=Math.max(e,l.start)-l.start+(l.run_offset||0);if(c>0){let w=o[0],[,y]=this._split_run_at_index(w,c);for(let b=0;b<o.length;b++)o[b]===w&&(o[b]=y);a=true,d=c;}let u=s[s.length-1],f=l.run===u.run,h=o[o.length-1],p=Math.min(u.end,t)-u.start+(u.run_offset||0);f&&d>0&&(p-=d);let m=Oe(h);if(p>0&&p<m.length){let[w]=this._split_run_at_index(h,p);o[o.length-1]=w,a=true;}return a&&r&&this._build_map(),o}get_insertion_anchor(e,t=true){let r=this.spans.filter(o=>o.end===e);if(r.length>0){for(let o=r.length-1;o>=0;o--)if(r[o].run)return [r[o].run,r[o].paragraph];for(let o=r.length-1;o>=0;o--){let a=r[o].paragraph;if(a){for(let l=this.spans.length-1;l>=0;l--){let d=this.spans[l];if(d.end<=e&&d.run!==null&&d.paragraph!==null&&d.paragraph._element===a._element)return [d.run,d.paragraph]}return [null,a]}}}let i=this.spans.filter(o=>o.start<e&&e<o.end);if(i.length>0){let o=i[0];if(o.run===null)return o.paragraph===null?this.get_insertion_anchor(o.end,t):[null,o.paragraph];{let a=e-o.start+(o.run_offset||0),[l]=this._split_run_at_index(o.run,a);return t&&this._build_map(),[l,o.paragraph]}}if(e===0&&this.spans.length>0){for(let o of this.spans)if(o.run)return [o.run,o.paragraph];for(let o of this.spans)if(o.paragraph)return [null,o.paragraph];return [null,null]}let s=this.spans.filter(o=>o.end<e);if(s.length>0){for(let o=s.length-1;o>=0;o--)if(s[o].run)return [s[o].run,s[o].paragraph];for(let o=s.length-1;o>=0;o--)if(s[o].paragraph)return [null,s[o].paragraph]}return [null,null]}_split_run_at_index(e,t){let r=Oe(e);r.substring(0,t);r.substring(t);let o=e._element.cloneNode(true),a=Array.from(o.childNodes);for(let f of a)f.nodeType===1&&f.tagName==="w:rPr"||o.removeChild(f);let l=g(f=>{let h=f.tagName;return h===jt||h===ys?(f.textContent||"").length:h===vs||h==="w:ptab"||h==="w:noBreakHyphen"||h===bs||h===xs?1:0},"_child_len"),d=0,c=Array.from(e._element.childNodes);for(let f of c){if(f.nodeType===1&&f.tagName==="w:rPr")continue;let h=f.nodeType===1?l(f):0;if(h===0)d<t||(e._element.removeChild(f),o.appendChild(f));else if(d+h<=t)d+=h;else if(d>=t)e._element.removeChild(f),o.appendChild(f),d+=h;else {let _=t-d,p=f.textContent||"",m=p.substring(0,_),w=p.substring(_);f.textContent=m,m.startsWith(" ")||m.endsWith(" ")||m.includes(`
38
+ `)?f.setAttribute("xml:space","preserve"):f.removeAttribute("xml:space");let y=f.cloneNode(true);y.textContent=w,w.startsWith(" ")||w.endsWith(" ")||w.includes(`
39
+ `)?y.setAttribute("xml:space","preserve"):y.removeAttribute("xml:space"),o.appendChild(y),d+=h;}}e._element.parentNode&&e._element.parentNode.insertBefore(o,e._element.nextSibling);let u=new Le(o,e._parent);return u.sdtStack=e.sdtStack,[e,u]}get_context_at_range(e,t){let r=this.spans.filter(i=>i.run&&i.end>e&&i.start<t);return r.length>0?r[0]:null}};function fi(n){return typeof n=="string"?n?[{text:n}]:[]:(n||[]).filter(e=>e&&e.text)}g(fi,"comment_entries");function Hl(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(Hl,"describe_invalid_comment");function hi(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(hi,"_count_standalone_underscores");var pi=new Set([".",",",";","!","?"]),Gt=g(n=>/[\p{L}\p{N}_]/u.test(n),"isWordChar");function Xl(n,e,t){for(let r of [n,e]){let i=r[t-1],s=r[t];if(!(/\s/.test(i)||/\s/.test(s))&&!(Gt(i)&&pi.has(s)&&(t+1>=r.length||!Gt(r[t+1])))&&!(Gt(s)&&pi.has(i)&&(t<2||!Gt(r[t-2]))))return true}return false}g(Xl,"splitsPrefixToken");function pt(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&&Xl(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=hi(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]!==`
40
40
  `;)r--;_=true;break}if(p===`
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(`
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=hi(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(pt,"trim_common_context");function ql(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(ql,"_words_to_chars");function Tt(n,e){let t=new kr.default.diff_match_patch;t.Diff_Timeout=2;let[r,i,s]=ql(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(Tt,"generate_edits_from_text");function Cr(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(Cr,"_sequence_opcodes");function Vn(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=Cr(t,r),s=0;for(let[o,a,l]of i)o==="equal"&&(s+=l-a);return 2*s/(t.length+r.length)}g(Vn,"_word_similarity_ratio");function ft(n){let e=n.split(`
42
+ `);return e.length>0&&e.every(t=>t.includes(" | "))}g(ft,"_is_table_blob");function _i(n,e){let t=n.split(`
43
43
  `),r=e.split(`
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
+ `);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(_i,"_table_blob_row_edits");function Yl(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(`
45
45
 
46
46
  `)||r.split(`
47
47
 
@@ -51,11 +51,11 @@ ${n.note_type==="fn"?"## Footnotes":"## Endnotes"}`;this._add_virtual_text(f,r,n
51
51
 
52
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+`
53
53
 
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
+ `,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(Yl,"_split_cross_paragraph_hunks");function rn(n,e){let t=n.trimEnd(),r=n.slice(t.length);e=e.trimEnd()+r;let s=n.split(`
55
55
 
56
56
  `),o=e.split(`
57
57
 
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
+ `),a=[],l=0;for(let u of s)a.push(l),l+=u.length+2;let d=Cr(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]+`
59
59
 
60
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(`
61
61
 
@@ -67,141 +67,145 @@ ${n.note_type==="fn"?"## Footnotes":"## Endnotes"}`;this._add_virtual_text(f,r,n
67
67
 
68
68
  `:w=`
69
69
 
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
+ `+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 E=0;E<h-f;E++){let $=s[f+E],P=o[_+E];if($===P)continue;let O=a[f+E],W=ft($)&&ft(P)?_i($,P):null;if(W!==null){c.push(...W);continue}if(Vn($,P)<.35)c.push({type:"modify",target_text:$,new_text:P,comment:"Diff: Replacement",_match_start_index:O});else {let U=Tt($,P);for(let X of U)X._match_start_index=(X._match_start_index||0)+O,c.push(X);}}continue}let w=s.slice(f,h),y=o.slice(_,p);if(w.some(ft)||y.some(ft)){let E=w.join(`
71
71
 
72
- `),S=y.join(`
72
+ `),$=y.join(`
73
73
 
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+`
74
+ `),P=Tt(E,$);for(let O of P)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},(E,$)=>Array.from({length:v},(P,O)=>Vn(w[$],y[O])));for(let E=b-1;E>=0;E--)for(let $=v-1;$>=0;$--){let P=N[E+1][$],O=["delete",E,$];N[E][$+1]>P&&(P=N[E][$+1],O=["insert",E,$]),x[E][$]>=.35&&x[E][$]+N[E+1][$+1]>=P&&(P=x[E][$]+N[E+1][$+1],O=["pair",E,$]),N[E][$]=P,k[E][$]=O;}let C=[],A=0,T=0;for(;A<b||T<v;)if(A===b)C.push(["insert",A,T]),T++;else if(T===v)C.push(["delete",A,T]),A++;else {let E=k[A][T];C.push(E),E[0]==="pair"?(A++,T++):E[0]==="delete"?A++:T++;}let I=[],M=0;for(;M<C.length;)if(C[M][0]==="pair")I.push(["pair",C[M][1],[C[M][2]]]),M++;else {let E=[],$=[];for(;M<C.length&&(C[M][0]==="delete"||C[M][0]==="insert");)C[M][0]==="delete"?E.push(C[M][1]):$.push(C[M][2]),M++;let P=Math.min(E.length,$.length);for(let O=0;O<P;O++)I.push(["pair",E[O],[$[O]]]);for(let O=P;O<E.length;O++)I.push(["delete",E[O],[]]);if($.length>P){let O=$.slice(P);I.length>0&&I[I.length-1][0]==="pair"?I[I.length-1][2].push(...O):I.push(["pending_insert",-1,O]);}}let B=[],D=[];for(let E of I)E[0]==="pending_insert"?D.push(...E[2]):E[0]==="pair"&&D.length>0?(B.push(["pair",E[1],[...D,...E[2]]]),D=[]):B.push(E);if(D.length>0&&B.length>0){for(let E=B.length-1;E>=0;E--)if(B[E][0]==="pair"){B[E][2].push(...D),D=[];break}}let j=-1;for(let E of B)E[0]==="pair"&&E[1]>j&&(j=E[1]);let F=h<s.length;for(let[E,$,P]of B){let O=f+$,W=a[O],U=s[O];if(E==="delete")if(F||$<j)c.push({type:"modify",target_text:U+`
75
75
 
76
- `,new_text:"",comment:"Diff: Text deleted",_match_start_index:L});else {let q=O>0?`
76
+ `,new_text:"",comment:"Diff: Text deleted",_match_start_index:W});else {let X=O>0?`
77
77
 
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(`
78
+ `+U:U,z=O>0?W-2:W;c.push({type:"modify",target_text:X,new_text:"",comment:"Diff: Text deleted",_match_start_index:z});}else if(E==="pair"){let X=P.map(z=>y[z]).join(`
79
79
 
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 (![alt](docx-image:N)) are read-only projections, so this difference cannot be expressed as a text edit \u2014 it was skipped; update the image or its alt text manually in Word."),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(`
80
+ `);if(U===X)continue;if(P.length===1&&ft(U)&&ft(X)){let z=_i(U,X);if(z!==null){c.push(...z);continue}}if(Vn(U,X)<.35)c.push({type:"modify",target_text:U,new_text:X,comment:"Diff: Replacement",_match_start_index:W});else {let z=Tt(U,X);for(let H of z)H._match_start_index=(H._match_start_index||0)+W,c.push(H);}}}}}return Yl(c)}g(rn,"generate_edits_via_paragraph_alignment");var sn=/!\[[^\]]*\]\(docx-image:[^)]*\)/g;function mi(n,e){let t=g(i=>i.replace(sn,"").replace(/\s+/g," ").trim(),"_normalized"),r=[];for(let i of n){let s=((i.target_text||"").match(sn)||[]).sort(),o=((i.new_text||"").match(sn)||[]).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(mi,"_drop_image_marker_hunks");function gi(n,e,t){let r=[];for(let o of e.matchAll(sn))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 (![alt](docx-image:N)) are read-only projections, so this difference cannot be expressed as a text edit \u2014 it was skipped; update the image or its alt text manually in Word."),s=true);}return i}g(gi,"_drop_marker_interior_hunks");function wi(n,e){for(let t of e.rows)if(n.substring(t.start,t.end)!==t.cells.join(" | "))return false;return true}g(wi,"_rows_are_plain");var ar="";function Gl(n,e){let t=n.map(s=>s.cells.join(ar)),r=e.map(s=>s.cells.join(ar)),i=Cr(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(Gl,"_table_row_opcodes");function Jl(n,e,t,r){let i=n.rows,s=e.rows,o=i.map(_=>_.cells.join(ar)),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(Jl,"_row_ops_for_table");function Er(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:[...gi(mi(rn(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(A=>m<=A.start&&A.end<=w),N=r.tables.filter(A=>y<=A.start&&A.end<=b),k=v.length===N.length&&v.every(A=>wi(n,A))&&N.every(A=>wi(t,A));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 A=rn(n.substring(m,w),t.substring(y,b));for(let T of A)T._match_start_index=(T._match_start_index||0)+m;s.push(...A);continue}let x=[[m,m],...v.map(A=>[A.start,A.end]),[w,w]],C=[[y,y],...N.map(A=>[A.start,A.end]),[b,b]];for(let A=0;A<x.length-1;A++){let T=x[A][1],I=x[A+1][0],M=C[A][1],B=C[A+1][0],D=rn(n.substring(T,I),t.substring(M,B));for(let j of D)j._match_start_index=(j._match_start_index||0)+T;if(s.push(...D),A<v.length){let j=v[A],F=N[A],E=Gl(j.rows,F.rows);if(E!==null)s.push(...Jl(j,F,E,i));else for(let $=0;$<j.rows.length;$++){let P=j.rows[$].cells.join(" | "),O=F.rows[$].cells.join(" | ");P!==O&&s.push({type:"modify",target_text:P,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(gi(mi(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(Er,"generate_structured_edits");function Ar(n,e){let t=g(c=>{let u=new Map;try{let f=ct(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(Ar,"collect_media_difference_warnings");function Bs(n,e,t=3){let r=new kr.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
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
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
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}
84
+ `)}g(Bs,"create_unified_diff");var dn=/\{\+\+|\{--|\{==|\{>>|\+\+\}|--\}|==\}|<<\}/g,Vl={"{++":"++}","{--":"--}","{==":"==}","{>>":"<<}"};function yi(n){if(!n)return true;if(/\{[=+\-><]?$/.test(n)||/^[=+\-><]?\}/.test(n))return false;let e=[];dn.lastIndex=0;let t;for(;(t=dn.exec(n))!==null;){let r=t[0];if(r.startsWith("{"))e.push(r);else if(e.length===0||Vl[e.pop()]!==r)return false}return e.length===0}g(yi,"_critic_payload_atomic");function Fs(n,e,t,r){let i=true;for(;i;){i=false;for(let s of [n,e]){let o=s.length-r;dn.lastIndex=0;let a;for(;(a=dn.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(Fs,"_clamp_trim_outside_critic_tokens");function Ql(n,e){let[t,r]=pt(n,e);return [t,r]=Fs(n,e,t,r),[n.substring(t,n.length-r),e.substring(t,e.length-r)]}g(Ql,"_word_patch_displays");function Zl(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]=Ql(i,s);if(yi(l)&&yi(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(Zl,"_merge_critic_split_hunks");function Ls(n,e,t="Original",r="Modified"){let i=Zl(Tt(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]=pt(d,c);[u,f]=Fs(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(Ls,"create_word_patch_diff");var vi=19e3,Ws=8,Kl="<!-- READONLY_BOUNDARY_START -->",ec=/^\s*(\d+)\s*-\s*(\d+)\s*$/;function zs(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=ec.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(zs,"parse_page_arg");var bi={"{++":"++}","{--":"--}","{==":"==}","{>>":"<<}"},tc=/\bChg:(\d+)\b/g;function nt(n){if(!n)return ["",""];let e=n.indexOf(Kl);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(nt,"split_structural_appendix");function rt(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:xi(d),page_content:d}],total_pages:1,body_pages:[""],body_page_offsets:[0]}}let t=nc(n),[r,i]=sc(t),s;if(e&&e.trim()){let l=e.trim();s=r.map(d=>d?`${d}
87
87
 
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]===`
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:xi(l),page_content:l})),total_pages:o,body_pages:r,body_page_offsets:i}}g(rt,"paginate");function nc(n){let e=rc(n),t=ic(e),r=[];for(let[i,s]of t)if(i.includes(nn)){let o=i.split(nn),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+nn.length;}}else r.push([i,s,false]);return r}g(nc,"_tokenize_into_atomic_blocks");function rc(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(bi))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(bi))if(n.startsWith(l,i)){e[l]>0&&e[l]--,i+=l.length,a=true;break}if(!a){if(n[i]===`
89
89
  `&&i+1<s&&n[i+1]===`
90
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}
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(rc,"_split_on_safe_paragraph_breaks");function ic(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}
92
92
 
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(`
93
+ ${d}`,l++;else break}e.push([a,i]),t=l;}return e}g(ic,"_merge_footnote_sections");function sc(n){if(!n.length)return [[""],[0]];let e=[],t=[],r=[],i=0,s=-1,o=g(()=>{r.length>0&&(e.push(r.join(`
94
94
 
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=[`
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>vi&&o(),r.length===0&&c>vi){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(sc,"_assemble_pages");function xi(n){let e=[...n.matchAll(tc)];return new Set(e.map(r=>r[1])).size}g(xi,"_count_tracked_changes");var oc=5,Ni=50;function ac(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,oc),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-Ni),f=Math.min(t.length,c+Ni),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(ac,"format_ambiguity_error");var lc="4.0.0";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 cc(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=S(d,"w:rPr"),f=S(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(cc,"coalesce_runs");function dc(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(dc,"strip_rsid");function uc(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(uc,"strip_para_ids");function fc(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(fc,"strip_proof_errors");function hc(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(hc,"strip_empty_properties");function pc(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(pc,"strip_hidden_text");function ki(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(ki,"count_tracked_changes");function _c(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(_c,"get_track_change_authors");function Ci(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(Ci,"_getElementText");function He(n,e=60){let t=n.replace(/\n/g," ").trim();return t.length<=e?t:t.substring(0,e-3)+"..."}g(He,"_truncate");function Ei(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(Ei,"_describe_textless_revision");function mc(n){let e=[],t=R(n.element,"w:ins"),r=R(n.element,"w:del");for(let o of t){let a=Ci(o).trim();a?e.push(` Accepted insertion: "${He(a,60)}"`):e.push(` Accepted insertion: ${Ei(o)}`);}for(let o of r){let a=Ci(o).trim();a?e.push(` Accepted deletion of: "${He(a,60)}"`):e.push(` Accepted deletion of: ${Ei(o)}`);}new Ft(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(mc,"accept_all_tracked_changes");function Jt(n){let e=We(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(Jt,"get_comments_summary");function gc(n){let e=We(n.pkg),t=Object.keys(e);if(t.length===0)return [];let r=[],i=new Dt(n);for(let[l,d]of Object.entries(e)){let c=d.resolved?"[Resolved]":"[Open]";r.push(` ${c} "${He(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(gc,"remove_all_comments");function wc(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(wc,"eject_comment_parts");function yc(n,e){let t=new Dt(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(yc,"replace_comment_authors");function vc(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(vc,"replace_change_authors");function bc(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(bc,"normalize_change_dates");function xc(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(xc,"normalize_comment_dates");function Nc(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(Nc,"scrub_doc_properties");function kc(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(kc,"scrub_timestamps");function Us(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(Us,"ejectPackageMembers");function Cc(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 [];Us(n,e,i=>i.includes("customXml"));for(let i of R(n.element,"w:sdtPr"))pn(i,"w:dataBinding").forEach(s=>i.removeChild(s));return [`Custom XML parts: ${Math.max(t.length,r.length)} removed`]}g(Cc,"strip_custom_xml");var Qn="docProps/custom.xml";function Ec(n){let e=n.pkg.getPartByPath(Qn),t=Object.keys(n.pkg.unzipped).includes(Qn);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} = "${He(a,60)}"`);}return Us(n,s=>s===Qn,s=>s.includes("docProps/custom.xml")),[`Custom document properties: ${Math.max(r.length,1)} removed (docProps/custom.xml)`].concat(r)}g(Ec,"strip_custom_properties");function Ac(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(Ac,"strip_document_variables");function Pc(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(Pc,"strip_image_alt_text");function Tc(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?`"${He(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(Tc,"detect_watermarks");function Sc(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: ${He(s,80)}`);break}}return t}g(Sc,"audit_hyperlinks");var $c="word/settings.xml",Ic=new Set(["readOnly","forms","comments","trackedChanges"]),Oc={readOnly:"read-only",forms:"fill-in-forms",comments:"comments-only",trackedChanges:"tracked-changes-only"},Et=Object.freeze({edit:null,enforced:false});function xn(n){return n.edit!==null&&n.enforced}g(xn,"isProtectionActive");function Pr(n){return n.edit===null?"unprotected":`${Oc[n.edit]??n.edit}, ${n.enforced?"enforced":"not enforced"}`}g(Pr,"describeProtection");function Dc(n){return n==null?true:!["0","false","off"].includes(n.toLowerCase())}g(Dc,"isTruthy");function Nn(n){let e=null;try{let s=n?.pkg?.getPartByPath?.($c);if(!s?._element)return Et;e=ne(s._element,"documentProtection")[0]??null;}catch{return Et}if(!e)return Et;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||!Ic.has(t)?Et:{edit:t,enforced:Dc(r)}}g(Nn,"readDocumentProtection");var kn="ignore_control_locks",St="ignore_document_protection",Tr="allow_untracked_writes",st=Object.freeze({ignore_control_locks:false,ignore_document_protection:false,allow_untracked_writes:false});function Rc(n){return n.ignore_control_locks||n.ignore_document_protection||n.allow_untracked_writes}g(Rc,"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} ${Mc(e.alternative)}`;return e.override&&(t+=` Pass ${e.override}=true to override deliberately.`),t.split(/\s+/).join(" ")}g(we,"gateError");function Mc(n){let e=n.replace(/\s+$/,"");return /[.!?:]$/.test(e)?e:`${e}.`}g(Mc,"endSentence");function jc(n){return n.find(e=>e.contentLocked)??null}g(jc,"lockedAncestor");function Bc(n,e,t=st){if(t.ignore_control_locks)return null;let r=jc(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:kn}):null}g(Bc,"checkContentLock");function Fc(n,e,t=st){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:kn})}g(Fc,"checkGroupRegion");function Lc(n,e,t,r=st){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:kn}):null}g(Lc,"checkDeleteLock");function Wc(n,e,t={}){let r=t.overrides??st;if(!xn(e)||r.ignore_document_protection)return null;let i=Pr(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:St}):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:St}):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:St}):null}g(Wc,"checkProtectionBlocksEdit");function zc(n,e,t,r=st){if(!xn(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 (${Pr(t)}). ${i} Remove the restriction in Word (Review -> Restrict Editing -> Stop Protection) or pass ${St}=true to override deliberately.`}g(zc,"checkProtectionBlocksReview");function Uc(n,e,t=st){return !xn(e)||e.edit!=="forms"||t.allow_untracked_writes?null:we(n,{subject:`the document is protected (${Pr(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:Tr})}g(Uc,"checkUntrackedWrite");function Hc(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(Hc,"checkPlaceholderTarget");var At=["[ ]","[x]"];function Xc(n,e,t,r){let i=e.find(o=>o.cls==="checkbox");if(!i)return null;let s=At;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(Xc,"checkCheckboxEdit");function qc(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(qc,"checkBoundControl");function Ai(n,e,t){let r=new Set(e),i=new Set(t);return n.filter(s=>r.has(s)!==i.has(s))}g(Ai,"crossedControlWalls");function Yc(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(Yc,"checkBlockMergeAcrossControl");function Gc(n){return `segmented at the boundary of ${n.map(ye).join(", ")}: only the text outside the control was changed`}g(Gc,"segmentationNote");function Jc(n,e){if(!Rc(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(`${kn}${r}`);}return n.ignore_document_protection&&t.push(St),n.allow_untracked_writes&&t.push(Tr),"Overrides: "+t.join(", ")}g(Jc,"overridesNote");function Vc(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(Vc,"boundedLevenshtein");function Qc(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+=Oe(new Le(r,n)));}return e}g(Qc,"_get_paragraph_text");var Sr="[A-Z][A-Za-z0-9\\s\\-&'\u2019]{1,60}",Zc=new RegExp(`^(?:[\\d.\\-()a-zA-Z]+\\s*)?["\u201C](${Sr})["\u201D]`,"d"),Kc=new RegExp(`(?<=[.;:!?])\\s+(?:[\\d.\\-()a-zA-Z]+\\s+)?["\u201C](${Sr})["\u201D]`,"dg"),ed=new RegExp(`\\([^)]*?["\u201C](${Sr})["\u201D][^)]*?\\)`,"dg");function td(n){let e=[],t=Zc.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(Kc)){let o=s.indices;o&&o[1]&&e.push([o[1][0],s[1].trim()]);}for(let s of n.matchAll(ed)){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(td,"extract_terms_from_paragraph");function nd(n,e){let t=Object.create(null),r=new Set,i=Object.create(null),s=[];for(let p of qe(n)){if(!(p instanceof ie))continue;let m=Qc(p).trim();if(!m)continue;for(let b of td(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=Vc(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(nd,"extract_all_domain_metadata");function rd(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(rd,"extract_document_settings_warnings");function id(n,e){try{let t=Od(n),r=Nn(n);return jd(t,r,'Read with mode="fields" for the full field ledger.')}catch{return []}}g(id,"content_controls_appendix_section");function sd(n,e){let[t,r,i]=nd(n,e),s=rd(n),o=[`
97
97
 
98
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(`
99
+ ## Document Settings`);for(let d of s)o.push(`- ${d}`);}let l=id(n);if(l.length>0&&(a=true,o.push(""),o.push(...l)),Object.keys(t).length>0){a=true,o.push(`
100
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
101
  ## Semantic Diagnostics`);for(let d of r)o.push(`- ${d}`);}if(Object.keys(i).length>0){a=true,o.push(`
102
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(`
103
+ `):""}g(sd,"build_structural_appendix");async function Ye(n,e=false,t=true,r=true){let i=await ae.load(Buffer.from(n));return Ge(i,e,t,false,false,r)}g(Ye,"extractTextFromBuffer");function Ge(n,e=false,t=true,r=false,i=false,s=true){let o=We(n.pkg),a=[],l=new Map,d=i?{part_ranges:[],tables:[]}:null,c=0,u=mn(Array.from(tt(n)).map(([h])=>gn(h)));for(let[h,_]of tt(n)){let p=a.length>0?c+2:c,m=h.part||h,[w]=Ae(m),y=new Ue(m,w,s),b=un(h,o,e,p,r?l:void 0,d?d.tables:void 0,u,false,y,s);b&&(a.length>0&&(c+=2),a.push(b),d&&d.part_ranges.push([c,c+b.length,_]),c+=b.length);}let f=a.join(`
104
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(`
105
+ `);if(t){let h=sd(n,f);h&&(f+=h);}return r?{text:f,paragraph_offsets:l}:d?{text:f,structure:d}:f}g(Ge,"_extractTextFromDoc");function un(n,e,t,r,i,s,o,a=false,l,d=true){let c=n.part||n,[u,f]=Ae(c),h=l??new Ue(c,u,d),_=[],p=r,m=true,w=true;if(n.constructor&&n.constructor.name==="NotesPart"){let b=`---
106
+ ${n.note_type==="fn"?"## Footnotes":"## Endnotes"}`;_.push(b),p+=b.length,m=false;}for(let y of qe(n,!!o)){m||(p+=2);let b=p;if(y instanceof yr){let v=o?o.get(y.element):void 0,N=!!v&&Ot(v),k=a?"":`
107
+ `,x=N?`${Be(v)}${k}`:"",C=un({_element:S(y.element,"w:sdtContent"),part:n.part||n},e,t,b+x.length,i,void 0,o,a,h,d);if(C){let A=N?`${x}${C}${k}${Fe(v)}`:C;_.push(A),p=b+A.length,m=false;}else m||(p-=2);w=false;}else if(y.constructor.name==="FootnoteItem"){let v=un(y,e,t,b,i,void 0,o,false,h,d);v?(_.push(v),p=b+v.length,m=false):m||(p-=2);}else if(y instanceof ie){let v=h.snapshot(),N=De(y,u,f,h,d);w&&n.constructor.name==="FootnoteItem"&&(N=`[^${n.note_type}-${n.id}]: `+N);let k=Bt(y,e,t,u,f,o);if(t&&!k&&Ps(y._element)){h.restore(v),m||(p-=2),w=false;continue}let x=N+k;_.push(x),i&&i.set(y._element,[b,x.length]),p=b+x.length,w=false,m=false;}else if(y instanceof Xe){let v=s?{start:b,end:b,rows:[]}:null,N=Cn(y,e,t,b,i,v,o,h,d);N?(_.push(N),p=b+N.length,m=false,v&&s&&(v.end=b+N.length,s.push(v))):m||(p-=2),w=false;}}return _.join(`
108
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(`![${P}](docx-image:${x.id})`);}}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(`
109
+ `)}g(un,"_extract_blocks");function Pi(n,e){if(!e)return null;let t=fs(n);if(!t)return null;let r=e.get(t);return r&&Ot(r)?r:null}g(Pi,"anchoredWrapper");function Cn(n,e,t,r,i,s,o,a,l=true){let d=[],c=0,u=r;for(let f of n.rows){let h=[],_=new Set,p=S(f._element,"w:trPr"),m=p?S(p,"w:ins"):null,w=p?S(p,"w:del"):null;if(t&&w)continue;let y=u+(c>0?1:0),v=y+(!t&&m||!t&&w?4:0),N=true;for(let C of f.cells){if(_.has(C))continue;_.add(C),N||(v+=3);let A=Pi(C._element,o),T=A?Be(A):"",I=un(C,e,t,v+T.length,i,void 0,o,true,a,l);if(A&&(I=`${T}${I}${Fe(A)}`),!t){let{paraId:M}=ss(C._element,!I||I.trim()==="");if(M){let B=I&&!I.endsWith(" ")?" ":"";I=I+`${B}{#cell:${M}}`;}}h.push(I),v+=I.length,N=false;}let k=h.join(" | "),x=Pi(f._element,o);if(x&&(k=`${Be(x)}${k}${Fe(x)}`),t||(m?k=`{++ ${k} ++}{>>[Chg:${m.getAttribute("w:id")} insert] ${m.getAttribute("w:author")||"Unknown"}<<}`:w&&(k=`{-- ${k} --}{>>[Chg:${w.getAttribute("w:id")} delete] ${w.getAttribute("w:author")||"Unknown"}<<}`)),d.push(k),u=y+k.length,s&&s.rows.push({start:y,end:u,cells:[...h]}),c++,c===1){let C=h.length;if(C>0){let A=Array(C).fill("---").join(" | ");d.push(A),u+=1+A.length;}}}return d.join(`
110
+ `)}g(Cn,"extract_table");function Bt(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(bn(n,s)),w=Ss(n,r,i),y=vn(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 Le){let[x,C]=$s(k,y),A=Oe(k);if(t&&Object.keys(l).length>0)continue;if(b){if(!A||!A.trim())continue;b=false;}let T=Dl(A,x,C);if(T){let I=t?["",""]:Ti(a,l,d,c),M=[x,C];if(h&&I[0]===_[0]&&I[1]===_[1]){let B=M[0].replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),D=M[0]!==""||M[1]!==""?T.match(new RegExp("^(\\s*)"+B)):null,j="";for(let E=h.length-1;E>=0;E--){let $=h[E];if(/\s/.test($))j=$+j;else break}let F=j?h.slice(0,-j.length):h;M[0]===p[0]&&M[1]===p[1]&&!(p[0]===""&&p[1]==="")&&F.endsWith(p[1])&&D!==null?h=F.slice(0,-p[1].length)+j+D[1]+T.slice(D[0].length):h+=T,p=M;}else v(),h=T,_=I,p=M;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 D=false;if(Object.keys(a).length>0||Object.keys(l).length>0||Object.keys(c).length>0||d.size>0){let F=N+1,E=false,$=Object.keys(a).length,P=Object.keys(l).length,O=Object.keys(c).length,W=new Set(d);for(;F<m.length;){let U=m[F];if(U instanceof Le){if(!Oe(U)){F++;continue}($>0||P>0||O>0||W.size>0)&&(E=true);break}else {let X=U;X.type==="ins_start"?$++:X.type==="ins_end"?$=Math.max(0,$-1):X.type==="del_start"?P++:X.type==="del_end"?P=Math.max(0,P-1):X.type==="fmt_start"?O++:X.type==="fmt_end"?O=Math.max(0,O-1):X.type==="start"?W.add(X.id):X.type==="end"&&W.delete(X.id);}F++;}E&&(D=true);}if(!D&&u.length>0){let F=Si(u,e);F&&(us(m,N)?f=F:(v(),o.push(`{>>${F}<<}`))),u.length=0;}}}}else if(wr(k)){b=false;let x=k.info;if(ds.includes(k.type)){if(t&&Object.keys(l).length>0)continue;let C=k.type==="checkbox_start"?ls:k.type==="checkbox_end"?cs:gr(x),A=t?["",""]:Ti(a,l,d,c);h&&(A[0]!==_[0]||A[1]!==_[1])&&(o.push(`${_[0]}${h}${_[1]}`),h=""),h||(_=A),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(Be(x)),!t&&x.showingPlaceholder&&x.placeholderText&&o.push(`{>>placeholder: ${x.placeholderText}<<}`)):o.push(Fe(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 C=(x.date||"image").replace(/\]/g,")").replace(/\n/g," ");o.push(`![${C}](docx-image:${x.id})`);}}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=Si(u,e);N&&o.push(`{>>${N}<<}`);}return o.join("")}g(Bt,"build_paragraph_text");function Ti(n,e,t,r){return Object.keys(e).length>0?["{--","--}"]:Object.keys(n).length>0?["{++","++}"]:t.size>0||Object.keys(r).length>0?["{==","==}"]:["",""]}g(Ti,"_get_wrappers");function Si(n,e){let t=[],r=[],i=new Set,s=Os(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}: ${ms(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(Si,"_build_merged_meta_block");var Hs=/^(#{1,6}) /,od=/^(?:ARTICLE|PART|SCHEDULE|EXHIBIT|ANNEX|APPENDIX)\s+[0-9IVXLCDMab]+\b/i,ad=/^(?:\d+\.\d+\.\d+(?:\.\d+)*\.?\s+\S|(?:Section|Paragraph|Clause|Item)\s+\d+(?:\.\d+)*\([a-z0-9]+\))/i,ld=/^(?:Section|Paragraph|Clause|Item)\s+\d+(?:\.\d+)*\b/i,cd=/^\d+(?:\.\d+)?\.\s+[A-Z]/,Xs=3;function qs(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(qs,"_assign_end_pages");function Ys(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 gd(n,e,r,i);let s=We(n.pkg),o=ud(n,s),a=[];for(let d=0;d<o.length;d++){let c=o[d];c.is_paragraph&&mt(c.item)&&pd(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=fn(f),_=Zs(f,s,u.prefix??""),p=An(f),m=_d(o,a,d,h),w=o.slice(c+1,m),y=dd(o,c+1,m),b=md(w),v=$r(u.start_offset,r);l.push({level:h,text:_,page:v,style:p,has_table:y,footnote_ids:b,end_page:v});}return qs(l,t.length),l}g(Ys,"extract_outline");function dd(n,e,t){for(let r=e;r<t;r++){let i=n[r];if(i.is_paragraph&&mt(i.item))return false;if(i.is_table)return true}return false}g(dd,"_direct_has_table");function ud(n,e){let t=Array.from(Bl(n)),r=0,i=null;for(let f of t){if(f===n){i=f;break}let h=Vs(f,e);h&&(r>0&&(r+=2),r+=h.length);}i?r>0&&(r+=2):(i=n,r=0);let s=[],o=r,a=true,l=i.part||i,[d,c]=Ae(l),u=new Ue(l,d);for(let f of qe(i))if(f instanceof ie){let h=De(f,d,c,u),_=Bt(f,e,false),p=(h+_).length;a||(o+=2),s.push({item:f,is_paragraph:true,is_table:false,start_offset:o,projected_length:p,prefix:h}),o+=p,a=false;}else if(f instanceof Xe){let h=u.snapshot(),_=Cn(f,e,false,0,void 0,null,void 0,u),p=_?_.length:0;a||(o+=2);let m=o;s.push({item:f,is_paragraph:false,is_table:true,start_offset:m,projected_length:p});let w=u.snapshot();u.restore(h),Js(f,m,s,e,u),u.restore(w),o+=p,a=false;}return s}g(ud,"_walk_doc_body");function Gs(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]=fd(c,i,s,r);if(f)return u;s=u,d++;}o++;}return t}g(Gs,"_compute_inner_block_offset");function fd(n,e,t,r){let i=t,s=true;for(let o of qe(n)){if(s||(i+=2),o instanceof ie){if(o._element===e)return [i,true];let a=De(o),l=Bt(o,r,false);i+=(a+l).length;}else if(o instanceof Xe){let a=Gs(o,new ie(e,null),i,r);if(a!==i&&hd(e,o._element))return [a,true];let l=Cn(o,r,false,0);i+=l?l.length:0;}s=false;}return [i,false]}g(fd,"_walk_cell_for_offset");function hd(n,e){let t=n.parentNode;for(;t;){if(t===e)return true;t=t.parentNode;}return false}g(hd,"_element_is_descendant");function Js(n,e,t,r,i){let s=new Set;for(let o of n.rows)for(let a of o.cells)if(!s.has(a)){s.add(a);for(let l of qe(a))if(l instanceof ie){let d=i?De(l,void 0,void 0,i):"",c=mt(l)?Gs(n,l,e,r):e;!d&&mt(l)&&(d=De(l)),t.push({item:l,is_paragraph:true,is_table:false,start_offset:c,projected_length:0,prefix:d});}else l instanceof Xe&&(t.push({item:l,is_paragraph:false,is_table:true,start_offset:e,projected_length:0}),Js(l,e,t,r,i));}}g(Js,"_record_table_inner_blocks_lite");function Vs(n,e,t){let r=[],i=n.constructor.name,s=n.part||n,[o]=Ae(s),a=t??new Ue(s,o);if(i==="NotesPart"){let d=n.note_type==="fn"?"## Footnotes":"## Endnotes";r.push(`---
112
+ ${d}`);}let l=true;for(let d of qe(n))if(d.constructor.name==="FootnoteItem"){let c=Vs(d,e,a);c&&r.push(c);}else if(d instanceof ie){let c=De(d,o,void 0,a);l&&i==="FootnoteItem"&&(c=`[^${n.note_type}-${n.id}]: ${c}`);let u=Bt(d,e,false);r.push(c+u),l=false;}else if(d instanceof Xe){let c=Cn(d,e,false,0,void 0,null,void 0,a);c&&r.push(c),l=false;}return r.join(`
113
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(`
114
+ `)}g(Vs,"_project_part");function En(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(s,"w:rPr"),d=false;if(l){let c=S(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?od.test(t)?1:ad.test(t)?3:ld.test(t)||cd.test(t)?2:null:null}g(En,"_structural_bold_heading_level");function mt(n){return Hs.test(De(n))?true:En(n)!==null}g(mt,"_is_heading");function pd(n,e){let t=Zs(n,e);if(!Qs(t))return false;if(An(n)!=="(heuristic)")return true;let i=(t.match(/\w+/g)||[]).length,s=En(n)!==null?2:Xs;return i>=s}g(pd,"_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 fn(n){let e=Hs.exec(De(n));if(e)return Math.min(e[1].length,6);let t=En(n);return t!==null?t:1}g(fn,"_heading_level");var $i=200;function Zs(n,e,t=""){let r=Bt(n,e,false),i=t?t.replace(/^#+\s+/,""):"",s=eo(i+r);return s=s.replace(/\n+/g," "),s=to(s),Ks(s.trim())}g(Zs,"_heading_text");function Ks(n){if(n.length<=$i)return n;let e=n.substring(0,$i),t=/\{#[^}\n]*$/.exec(e);return t!==null&&(e=e.substring(0,t.index)),e.trimEnd()+"\u2026"}g(Ks,"_truncate_outline_text");function eo(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(eo,"_strip_critic_markup");function to(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(to,"_strip_inline_formatting");function An(n){let[e,t]=Ae(n._parent.part||n._parent),r=S(n._element,"w:pPr"),i=t;if(r){let d=S(r,"w:pStyle");d&&(i=d.getAttribute("w:val")||t);}let s=null,o=false;if(r){let d=S(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(An,"_determine_heading_style");function _d(n,e,t,r){for(let i=t+1;i<e.length;i++){let s=e[i];if(fn(n[s].item)<=r)return s}return n.length}g(_d,"_find_owned_end");function md(n){let e=new Set,t=[];for(let r of n)if(r.is_paragraph)for(let i of bn(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(md,"_collect_footnote_ids");function no(n){return n.replace(/\{--.*?--\}/g,"").replace(/\{\+\+(.*?)\+\+\}/g,"$1").replace(/\{==(.*?)==\}/g,"$1").replace(/\{>>.*?<<\}/g,"").replace(/\{(?:>>|--).*$/g,"").replace(/\{\+\+|\{==|--\}|\+\+\}|<<\}|==\}/g,"").replace(/\*\*|__|[*_]/g,"").replace(/\{#[^}]+\}/g,"").trim()}g(no,"clean_breadcrumb");function $r(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($r,"offset_to_page");function gd(n,e,t,r){let i=[],s=new Set;function o(d){for(let c of qe(d))if(c.constructor.name==="FootnoteItem")o(c);else if(c instanceof ie)i.push(["p",c]);else if(c instanceof Xe){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&&mt(u)&&wd(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=fn(u),h=ro(u,e,r),_=An(u),p=c;for(let N=d+1;N<a.length;N++){let k=a[N],x=i[k][1];if(fn(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"&&mt(k))break;if(N==="t"){w=true;break}}let y=yd(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=$r(N,t);}l.push({level:f,text:h,page:v,style:_,has_table:w,footnote_ids:y,end_page:v});}return qs(l,t.length),l}g(gd,"_extract_outline_fast");function wd(n,e,t){let r=ro(n,e,t);if(!Qs(r))return false;if(An(n)!=="(heuristic)")return true;let s=r.match(/\w+/g)||[],o=En(n)!==null?2:Xs;return s.length>=o}g(wd,"_heading_passes_quality_filter_fast");function ro(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=eo(o);return a=a.replace(/\n+/g," "),a=to(a),a=a.replace(/^#+\s+/,""),Ks(a.trim())}g(ro,"_heading_text_fast");function yd(n){let e=new Set,t=[];for(let[r,i]of n)if(r==="p")for(let s of bn(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(yd,"_collect_footnote_ids_fast");var vd=100,bd=80,xd=8,Nd={readOnly:"read-only",forms:"fill-in-forms only",comments:"comments only",trackedChanges:"tracked-changes only"},kd={"repeating-item":"item"},io=new Set(["group","repeating","repeating-item"]);function so(n){if(n.edit===null)return "none";let e=Nd[n.edit]??n.edit;return n.enforced?`${e} (enforced)`:e}g(so,"protectionLabel");var Ii=/\{#(\/?)cc:(\d+)(?: [^}]*)?\}/g;function Cd(n){let e=new Map,t=new Map;Ii.lastIndex=0;let r;for(;(r=Ii.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(Cd,"scanAnchors");var Ed=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=no(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 Oi(n,e=bd){let t=no(n).replace(/\s+/g," ").trim();return t.length>e?t.slice(0,e)+"\u2026":t}g(Oi,"preview");function Ir(n){if(!n)return [];let e=[];for(let t=n.firstChild;t;t=t.nextSibling)t.nodeType===1&&e.push(t);return e}g(Ir,"childElements");function Pn(n){return n?.tagName??n?.nodeName??""}g(Pn,"tagOf");function Di(n){let e=S(n,it);return e?Ir(e).filter(t=>{let r=Pn(t);return r==="w:p"||r==="w:tbl"}):[]}g(Di,"blockChildren");function Ad(n){let e=S(n,it);return e?Ir(e).filter(t=>Pn(t)===gt):[]}g(Ad,"directChildSdts");function Pd(n){let e=S(n,it);return e?R(e,gt).length:0}g(Pd,"nestedSdtCount");function Vt(n,e){return n===1?`${n} ${e}`:`${n} ${e}s`}g(Vt,"plural");function Td(n){return n.cls==="group"?`wraps ${Vt(Di(n.element).length,"block")}, ${Vt(Pd(n.element),"nested field")}`:n.cls==="repeating"?Vt(Ad(n.element).length,"item"):n.cls==="repeating-item"?`wraps ${Vt(Di(n.element).length,"block")}`:null}g(Td,"extentFor");function Sd(n){let e=S(n.element,it);if(!e)return null;let t=Ir(e)[0];if(!t)return null;let r=Pn(t);return r==="w:tr"?"table row":r==="w:tc"?"table cell":null}g(Sd,"containerKind");function $d(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($d,"statesFor");function Id(n){let e=S(n,it);return e?R(e,"w:t").some(t=>(t.textContent??"").trim().length>0):false}g(Id,"hasText");function Od(n){let e=mn(Array.from(tt(n)).map(([o])=>gn(o))),t=0,r=0,i=0,s=0;for(let o of e.values())t+=1,io.has(o.cls)||o.cls==="checkbox"||(o.showingPlaceholder||!Id(o.element))&&(r+=1),(o.cls==="group"||o.contentLocked)&&(i+=1),o.bound&&(s+=1);return [t,r,i,s]}g(Od,"fieldSummary");function Or(n,e,t){let r=mn(Array.from(tt(n)).map(([c])=>gn(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(Pn(u)===gt){let f=r.get(u);if(f)return f.ordinal}u=u.parentNode??null;}return null},"parentOrdinal"),o=Cd(e),a=new Ed(e),l=[],d=0;for(let c of i){let u=o.get(c.ordinal);u&&(d=u[0]);let f=d,h=t?$r(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(!io.has(c.cls)){if(u){let b=Oi(e.slice(u[1],u[2]));b?p=b:y=true;}}y&&c.placeholderText&&(w=Oi(c.placeholderText)),l.push({ordinal:c.ordinal,cls_word:kd[c.cls]??c.cls,alias:c.alias,tag:c.tag,page:h,heading_path:_,container_kind:Sd(c),parent_ordinal:s(c),states:$d(c,y),value:p,checkbox_state:m,placeholder:w,options:c.options.map(([b])=>b),date_format:c.dateFormat,extent:Td(c),empty:y,locked:c.cls==="group"||c.contentLocked,bound:c.bound});}return l}g(Or,"collectFields");function Dd(n){return [n.length,n.filter(e=>e.empty).length,n.filter(e=>e.locked).length,n.filter(e=>e.bound).length]}g(Dd,"summaryCounts");function oo(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(oo,"summaryText");function Rd(n){return oo(Dd(n))}g(Rd,"fieldsSummary");function ao(n,e,t,r=0,i=vd){let s=[`# Fields: ${n}`,`Protection: ${so(t)} \xB7 ${Rd(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=>Md(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(ao,"renderLedger");function Md(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,xd),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(Md,"renderLine");function jd(n,e,t=""){if(n[0]===0&&e.edit===null)return [];let r=["## Content Controls","",`Protection: ${so(e)} \xB7 ${oo(n)}`];return t&&r.push(t),r}g(jd,"renderAppendixSection");var Qt=class extends Error{static{g(this,"FieldResolutionError");}constructor(n){super(n),this.name="FieldResolutionError";}},Bd=30;function Ri(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,Bd),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(Ri,"availableSummary");function Fd(n,e,t="strict"){if(!e||!e.trim())throw new Qt("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 Qt(`No content control with id 'CC:${o}'. ${Ri(n)}`)}let i=n.filter(o=>o.tag===e);if(i.length||(i=n.filter(o=>o.alias===e)),!i.length)throw new Qt(`No content control matches field '${e}'. ${Ri(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 Qt(`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(Fd,"resolveField");function Dr(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(Dr,"childrenOf");function Pe(n,e){for(let t of Dr(n))if(t.tagName===e)return t;return null}g(Pe,"findChild3");function lo(n,e){return n?.getElementsByTagName?Array.from(n.getElementsByTagName(e)):[]}g(lo,"descendants");function _t(n){return Pe(n,"w:sdtContent")}g(_t,"sdtContent");function wt(n){return Pe(n,"w:sdtPr")}g(wt,"sdtPr");function Ld(n){let e=_t(n);return e?lo(e,"w:r"):[]}g(Ld,"contentRuns");function Mi(n){let e=wt(n.element);if(!e)return false;let t=Pe(e,"w:showingPlcHdr");if(!t)return false;e.removeChild(t);let r=_t(n.element);if(r)for(let i of lo(r,"w:r"))i.parentNode?.removeChild(i);return true}g(Mi,"clearPlaceholder");function Wd(n){let e=_t(n),t=n.parentNode;if(!e||!t)return false;for(let r of Dr(e))t.insertBefore(r,n);return t.removeChild(n),true}g(Wd,"unwrapSdt");var zd=new Set(["text","richtext","dropdown","combobox","date","checkbox"]),Ud={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 Hd(n){let e=wt(n.element);if(!e)return false;let t=Pe(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(Hd,"isMultiline");function ji(n,e){if(zd.has(n))return null;let t=Ud[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(ji,"refuseClass");function Bi(n,e,t){if(n.cls==="dropdown"){let[,r]=co(n,t);return r?`CC:${e}: ${r}`:null}return n.cls==="date"?lr(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(`
118
118
 
119
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(`
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:
120
+ `)&&!Hd(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(Bi,"refuseValue");var Xd=new Set(["true","x","[x]","checked","1","yes","on"]),qd=new Set(["false","[ ]","[]","unchecked","0","no","off",""]);function Fi(n){let e=n.trim().toLowerCase();return Xd.has(e)?true:qd.has(e)?false:null}g(Fi,"parseCheckboxValue");function Yd(n,e){let t=e?["\u2612",null]:["\u2610",null],r=wt(n.element);if(!r)return t;let i=Pe(r,"w14:checkbox");if(!i)return t;let s=Pe(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(Yd,"checkboxGlyph");function Gd(n,e){let t=wt(n.element);if(!t)return;let r=Pe(t,"w14:checkbox");if(!r)return;let i=Pe(r,"w14:checked");i||(i=r.ownerDocument.createElement("w14:checked"),r.appendChild(i)),i.setAttribute("w14:val",e?"1":"0");}g(Gd,"setCheckboxChecked");function Jd(n){let e=Ld(n.element);return e.length?e[0]:null}g(Jd,"glyphRun");function co(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(co,"resolveOption");function Vd(n,e){return (n.options??[]).some(([t,r])=>t===e||!!r&&r===e)}g(Vd,"optionIsListed");function Qd(n,e){let t=wt(n.element);if(t)for(let r of ["w:dropDownList","w:comboBox"]){let i=Pe(t,r);if(i){i.setAttribute("w:lastValue",e);return}}}g(Qd,"setDropdownLastValue");var Zd=new Set(["yyyy","MM","M","dd","d"]);function lr(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(lr,"parseIsoDate");var Ie=g((n,e)=>String(n).padStart(e,"0"),"pad");function Kd(n,e){let[t,r,i]=n,s=`${Ie(t,4)}-${Ie(r,2)}-${Ie(i,2)}`;if(!e)return [s,false];let o=e.match(/[A-Za-z]+/g)??[];if(!o.length||o.some(l=>!Zd.has(l)))return [s,true];let a={yyyy:Ie(t,4),MM:Ie(r,2),M:String(r),dd:Ie(i,2),d:String(i)};return [e.replace(/[A-Za-z]+/g,l=>a[l]),false]}g(Kd,"renderDate");function eu(n,e){let t=wt(n.element);if(!t)return;let r=Pe(t,"w:date");if(!r)return;let[i,s,o]=e;r.setAttribute("w:fullDate",`${Ie(i,4)}-${Ie(s,2)}-${Ie(o,2)}T00:00:00Z`);}g(eu,"setFullDate");var tu=["ds:itemID","itemID"];function Li(n){return (n.split("/").pop()??"").replace(/\D/g,"")}g(Li,"digitsOf");var nu={"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 ru(n,e){if(!e)return null;let t=e.replace(/[{}]/g,"").toLowerCase(),r=n?.part?.package?.parts??[],i=nu[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 tu){let h=l.getAttribute?.(f);if(h){d=h;break}}if(!d||d.replace(/[{}]/g,"").toLowerCase()!==t)continue;let c=Li(String(a.partname)),u=o.find(f=>Li(String(f.partname))===c);if(u)return u}return null}g(ru,"findBoundStore");function iu(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(iu,"namespaceUriOf");function su(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(su,"parsePrefixMappings");function ou(n,e,t){let r=e.split("/").filter(a=>a.length>0);if(!r.length)return null;let i=su(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 _=Dr(o).filter(p=>s(p.tagName??p.nodeName)===f);if(h){let p=_.filter(m=>iu(m)===h);p.length&&(_=p);}if(_.length<c)return null;o=_[c-1];}return o}g(ou,"resolveBindingPath");function au(n,e,t,r){if(!e||!n?._element)return false;let i=ou(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(au,"writeBoundValue");var Wi=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 ht(n,e){e.parentNode&&e.parentNode.insertBefore(n,e.nextSibling);}g(ht,"insertAfter");function lu(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&&mr(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(lu,"takeSnapshot");function cu(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=et(t.blob);It(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(cu,"restoreSnapshot");function du(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(du,"stripMatchingHeadingHashes");function cr(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(cr,"extract_failed_indices");var Zt=class extends Error{static{g(this,"BatchValidationError");}errors;failed;constructor(n,e){super(`Batch validation failed:
123
123
  `+n.join(`
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(`
124
+ `)),this.name="BatchValidationError",this.errors=n,this.failed=e??cr(n);}};function zi(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(zi,"sequential_context_hint");var uu=/[\x00-\x08\x0b\x0c\x0e-\x1f]/g,Ui=/\[~[^~\]]+~\]\(#[^)]+\)|!\[[^\]]*\]\(docx-image:[^)]*\)|\[(?!~)[^\]]+\]\([^)]+\)/g,fu=/^#{1,6} /m,hu=/^[ \t]*\|.*\|[ \t]*$/m;function Hi(n,e){for(;n.endsWith(`
126
126
 
127
127
  `)&&e.endsWith(`
128
128
 
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 (![alt](docx-image:N)) are read-only projections of embedded images. They cannot be inserted, altered, or removed via text replacement \u2014 edit the text around the image instead.`);}if(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(`
129
+ `);)n=n.slice(0,-2),e=e.slice(0,-2);return [n,e]}g(Hi,"trimSharedTrailingParagraphMark");var Xi=/\{#\/?cc:\d+[^}]*\}/g,pu=/^\{#cc:(\d+)[^}]*\}(?:\{>>placeholder:[^<]*<<\})?\{#\/cc:\1\}$/,_u={"w:sectPr":new Set(["w:headerReference","w:footerReference"])},on=["w:ins","w:del"],an=["w:pPrChange","w:rPrChange","w:sectPrChange"],Kt=[...on,...an];function Zn(n){return n.startsWith("/")?n.substring(1):n}g(Zn,"normalize_part_name");var mu=["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 gu(n){if(!n)return null;let e=n.match(uu);return e?Array.from(new Set(e.map(r=>`0x${r.charCodeAt(0).toString(16).padStart(2,"0")}`))).sort().join(", "):null}g(gu,"describe_illegal_control_chars");function wu(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=Hl(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=gu(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 (![alt](docx-image:N)) are read-only projections of embedded images. They cannot be inserted, altered, or removed via text replacement \u2014 edit the text around the image instead.`);}if(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(Xi)||[],c=o.match(Xi)||[];!pu.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(wu,"validate_edit_strings");var Ft=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=st;protection=Et;_overridden_controls=[];removed_comment_notes=[];rollback_verified=true;id_discovery_hint;markup_mode="track_changes";resolve_numbering=true;_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.resolve_numbering=r?.resolve_numbering??true,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=Nn(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=mr(o);s._element.setAttribute("xmlns:w16du",i),a&&It(o);}this.current_id=this._scan_existing_ids(),this.mapper=new Ee(this.doc,false,false,this.resolve_numbering),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.comments_manager=new Dt(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]=pt(e,t);a=e.slice(f,e.length-h),l=t.slice(f,t.length-h),d=r+f,[a,l]=Hi(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(fu)&&!a(hu))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=Tt(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]=pt(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,ut),h=ge(h,ut);let _;if(!f&&!h){let m=ge(i,ut),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(`
131
131
  \u2026
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(`
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=ut*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,ut),_=ge(s,ut),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,Zn(this.doc.part.partname)]];for(let t of this.doc.pkg.parts)t!==this.doc.part&&mu.includes(t.contentType)&&e.push([t._element,Zn(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=Or(this.doc,e);return this._field_entries_cache=[e,t],t}_resolve_set_field_targets(e){return Fd(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&&Mi(d)&&(this._cc_anchor_pairs=null,this._field_entries_cache=null,this._field_entries_cache=null),_t(d.element)):null}}else i.set(a,o.index+o[0].length);}return null}_apply_checkbox_set_field(e,t,r){let i=Fi(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=Jd(r),[o,a]=Yd(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=S(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=_t(r.element);if(!h)return false;h.appendChild(u);}return Gd(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=ji(i(d),d.ordinal);if(!u&&c&&(u=Bi(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&&Mi(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]=co(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"&&!Vd(c,u)&&a.set(d.ordinal,`'${u}' is not in the option list`);}else if(c.cls==="date"){let u=lr(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]=Kd(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=_t(p.element)),p){if(p.cls==="dropdown"||p.cls==="combobox")Qd(p,_);else if(p.cls==="date"){let y=lr(e.value);y&&eu(p,y);}if(p.bound){let y=ru(this.doc,p.storeItemId),b=!!y&&au(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=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 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=S(a,"w:pPr");if(l){let d=S(l,"w:rPr"),c=d?S(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=S(b,"w:rPr");if(v){let N=S(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=S(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=S(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=S(d,"w:pPr"),u=c?S(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,_=S(a,"w:pPr");_||(_=h.createElement("w:pPr"),a.insertBefore(_,a.firstChild));let p=S(_,"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=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=_u[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 fi(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 fi(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]=Ae(t);return vn({_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 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=S(r,"w:outlineLvl");s&&r.removeChild(s);let o=S(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
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(`
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]??"",C=i.createElement("w:tc"),A=i.createElement("w:tcPr"),T=i.createElement("w:tcW");if(T.setAttribute("w:w",p),T.setAttribute("w:type","pct"),A.appendChild(T),N){let D=i.createElement("w:shd");D.setAttribute("w:val","clear"),D.setAttribute("w:color","auto"),D.setAttribute("w:fill","F2F2F2"),A.appendChild(D);}C.appendChild(A);let I=i.createElement("w:p"),M=N&&x&&!x.startsWith("**")?`**${x}**`:x,B=this._build_tracked_ins_for_line(M,r,t,i,s);B&&(I.appendChild(B),m=B),C.appendChild(I),b.appendChild(C);}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 E=t._element;for(;E&&E.tagName!=="w:p";)E=E.parentNode;c=E;}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 E=p;for(;E&&E.parentNode!==c;)if(E=E.parentNode,E===c){E=null;break}if(E){let $=m?E:E.nextSibling;for(;$;)$.nodeType===1&&f.has($.tagName)&&u.push($),$=$.nextSibling;}}else if(c!==null&&a){let E=c.firstChild;for(;E;)E.nodeType===1&&f.has(E.tagName)&&u.push(E),E=E.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,C=null;k||(C=this._build_tracked_ins_for_line((w===d[0],d[0]),t,i,l,o),x=C);let A=k?d:d.slice(1);if(A.length===0)return {first_node:x,last_p:null,last_ins:C,used_block_mode:false};if(!c)return {first_node:x,last_p:null,last_ins:C,used_block_mode:false};let T=c.parentNode;if(!T)return {first_node:x,last_p:null,last_ins:C,used_block_mode:false};let I=g((E,$)=>{T.insertBefore(E,$.nextSibling);},"insertAfterEl"),M=null,B=null,D=c,j=!k&&u.length>0,F=[];if(j){let E=S(c,"w:pPr");E||(E=l.createElement("w:pPr"),c.insertBefore(E,c.firstChild));let $=S(E,"w:rPr");if($)for(let O of Array.from($.childNodes))O.nodeType===1&&(O.tagName==="w:ins"||O.tagName==="w:del")&&($.removeChild(O),F.push(O));else $=l.createElement("w:rPr"),E.appendChild($);let P=this._create_track_change_tag("w:ins","",i);$.insertBefore(P,$.firstChild);}for(let E=0;E<A.length;E++){let $=A[E];if(G._is_markdown_pipe_table_block($)){let{tbl:z,last_ins:H}=this._build_markdown_table_element($,i,t,l,o);I(z,D),D=z,H&&(B=H),x||(x=z);continue}let[P,O]=this._parse_markdown_style($),W=l.createElement("w:p");if(O)this._set_paragraph_style(W,O);else {let z=S(c,"w:pPr");if(z){let H=this._clone_pPr_scrubbing_headings(z,c);(H.attributes.length>0||Array.from(H.childNodes).some(q=>q.nodeType===1))&&W.appendChild(H);}}let U=E===A.length-1;if(j&&U){if(F.length>0){let z=S(W,"w:pPr");z||(z=l.createElement("w:pPr"),W.insertBefore(z,W.firstChild));let H=S(z,"w:rPr");H||(H=l.createElement("w:rPr"),z.appendChild(H));for(let q=F.length-1;q>=0;q--)H.insertBefore(F[q],H.firstChild);}}else {let z=S(W,"w:pPr");z||(z=l.createElement("w:pPr"),W.insertBefore(z,W.firstChild));let H=S(z,"w:rPr");H||(H=l.createElement("w:rPr"),z.appendChild(H));let q=this._create_track_change_tag("w:ins","",i);H.insertBefore(q,H.firstChild);}let X=this._build_tracked_ins_for_line(P,t,i,l,o);X&&W.appendChild(X),I(W,D),D=W,M=W,B=X,x||(x=W);}if(!k&&M&&u.length>0)for(let E of u)E.parentNode?.removeChild(E),M.appendChild(E);return {first_node:x,last_p:M,last_ins:B,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=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 m of _){let w=S(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=S(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=S(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=S(i,l);d&&i.removeChild(d);}if(t.italic){let l=S(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=S(i,l);d&&i.removeChild(d);}if(t.strike){let l=S(i,"w:strike");l||(l=o.createElement("w:strike"),this._insert_rpr_child(i,l));}if(t.underline){let l=S(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=S(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=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=S(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,delete e._adeu_numbering_defs,"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 M of R(T,"w:lvl")){if((M.getAttribute("w:ilvl")||"0")!=="0")continue;let B=S(M,"w:numFmt");B&&B.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 M of a){let B=S(M,"w:abstractNumId");if(B&&B.getAttribute("w:val")===l){let D=M.getAttribute("w:numId");if(D&&D!=="0")return D}}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,delete e._adeu_numbering_defs,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 C=c.createElement("w:num");C.setAttribute("w:numId",String(d+1));let A=c.createElement("w:abstractNumId");return A.setAttribute("w:val",String(u+1)),C.appendChild(A),s.appendChild(C),delete e._adeu_numbering_cache,delete e._adeu_numbering_defs,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),ht(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),ht(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),ht(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=Wc(e,this.protection,{controls:f,isCommentOnly:p,overrides:c});if(m||!p&&(m=Uc(e,this.protection,c),m)||(m=Hc(e,t.target_text||"",u),m))return m;if(f.length===0)return null;if(!d&&(m=qc(e,f),m)||(m=Xc(e,f,t.target_text||"",t.new_text||""),m)||(m=Bc(e,f,c),m)||(m=Fc(e,f,c),m))return m;for(let y of f)if(this._deletes_entire_control(r,y,i,s,a)&&(m=Lc(e,[y],true,c),m))return m;if(o.includes(`
136
136
 
137
137
  `)&&!a.includes(`
138
138
 
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 (![alt](docx-image:N)). 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(`
139
+ `)){let y=Ai(f,h,_);if(m=Yc(e,y),m)return m}let w=Ai(f,h,_);if(w.length>0&&(t._warning=Gc(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(xn(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 Ee(this.doc,true,false,this.resolve_numbering)),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=ji(a?a.cls:o.cls_word,o.ordinal),!s&&a&&(s=Bi(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 _=Fi(e.value),p=l.checked?At[1]:At[0],m=_?At[1]:At[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(...wu(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{cn(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 Ee(this.doc,true,false,this.resolve_numbering)),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 Ee(this.doc,false,true,this.resolve_numbering));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,Yn)}"${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(ac(i+1+t,s.target_text,d,h));}if(l.length===1){let[h,_]=l[0],p=d.substring(h,h+_),m=G._restore_matched_list_prefix(c,h,p,s.target_text,s.new_text||""),w=G._reinject_anchor_markers(c,h,_,s.target_text,m);if(w===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 y=w,[b,v]=pt(p,y),N=p.length-v,k=p.substring(b,N),x=y.substring(b,y.length-v),A=c.part_ranges.filter(B=>B[1]>B[0]).length>1?Array.from(new Set(c.spans.filter(B=>B.run!==null&&B.end>h&&B.start<h+_).map(B=>B.part_index))).sort((B,D)=>B-D):[];if(A.length>1){let B=A.map(D=>c.part_kind_of(D)||"?").join(" \u2192 ");r.push(`- Edit ${i+1+t} Failed: target_text spans a structural document-part boundary (${B}). 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(A.length===1){let B=this._header_block_error(i+1+t,c,A[0],k,x);B&&r.push(B);}let T=h+b,I=h+_-v,M=this._check_control_gates(i+1+t,s,c,T,Math.max(I-T,0),k,x);if(M&&r.push(M),I>T&&c.spans.filter(D=>D.end>T&&D.start<I&&(D.run!==null||D.text.trim()!=="")).some(D=>D.is_image_marker)&&r.push(`- Edit ${i+1+t} Failed: the target overlaps a read-only image marker (![alt](docx-image:N)). Images cannot be edited or removed via text replacement \u2014 target the text around the image instead.`),s.comment&&(s.new_text||"")===(s.target_text||"")){let B=c.part_kind_at(h);B!==null&&B!=="body"&&r.push(`- Edit ${i+1+t} Failed: comments cannot be anchored inside a ${B} 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,_,k,x)&&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": ["...", "..."]}).`),k.includes(`
141
141
 
142
142
  `)&&!(p.split(`
143
143
 
144
- `).length===w.split(`
144
+ `).length===y.split(`
145
145
 
146
- `).length))if(k.includes(`
146
+ `).length))if(x.includes(`
147
147
 
148
- `)){let F=p.split(`
148
+ `)){let D=p.split(`
149
149
 
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(`
150
+ `);D.length>=2&&D[0].trim()!==""&&D[D.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 D=k.split(`
151
151
 
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(`
152
+ `);D.length>=2&&D[0].trim()!==""&&D[D.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((E,$)=>{let P=/^\d+$/.test(E)?parseInt(E,10):0,O=/^\d+$/.test($)?parseInt($,10):0;return P!==O?P-O:E.localeCompare($)}),C=x.length>0?`Chg:${x[0]}`:null,A=x.slice(0,2).map(E=>`Chg:${E}`).join(", "),T=A?` (e.g. ${A})`:"";v.length>1&&(T+=` (+${v.length-1} more)`);let I=C?`{"type": "accept", "target_id": "${C}"}`:"",M=a==="all"&&b?'or use match_mode="strict" or "first", or scope your edit outside of it.':"or scope your edit outside of it.",B=`- Edit ${i+1+t} Failed: Modification targets an active insertion from another author (`,D=`${T}). Accept first with ${I} ${M}`,j=Wi-B.length-D.length,F=B+si(N,j)+D;r.push(si(F,Wi));continue}}if(w.size>0&&a==="all"){let b=[],v=Array.from(w.keys()).sort();for(let N of v){let C=Array.from(w.get(N)).sort((A,T)=>{let I=A.split(":").pop()||"",M=T.split(":").pop()||"",B=/^\d+$/.test(I)?parseInt(I,10):0,D=/^\d+$/.test(M)?parseInt(M,10):0;return B!==D?B-D:A.localeCompare(T)}).join(", ");b.push(C?`${N} (e.g. ${C})`: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(`
153
153
  `)||!s.includes(" | "))return false;let o=s.split(`
154
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===`
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=We(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=et(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 Kt)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&&(cu(this.doc,e),this.current_id=t,this.mapper=new Ee(this.doc,false,false,this.resolve_numbering),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.comments_manager=new Dt(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 j of e)if(j&&typeof j=="object"&&j.type==="modify"&&j.target_text&&j.new_text){let[F,E]=du(j.target_text,j.new_text);j.target_text=F,j.new_text=E;}this.skipped_details=[],this._overridden_controls=[];let o=[],a=g(j=>t?t[j]:j,"idx_of"),l=g(j=>j!==null&&typeof j=="object"&&["accept","reject","reply"].includes(j.type),"is_action"),d=e.map((j,F)=>({c:j,i:a(F)})).filter(({c:j})=>l(j)),c=e.map((j,F)=>({c:j,i:a(F)})).filter(({c:j})=>!l(j)),u=d.map(({c:j})=>j),f=d.map(({i:j})=>j),h=c.map(({c:j})=>j),_=[];for(let j=0;j<u.length;j++){let F=zc(f[j]+1,u[j]?.type??"",this.protection,this.gate_overrides);F&&_.push(F);}_.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:j,i:F}of c){let E=this.validate_edits([j],F);E.length>0&&(m.push(...E),o.push([F,E.join(`
156
+ `)]));}let w=[..._,...m];if(w.length>0)throw o.unshift(...cr(_)),new Zt(w,o);let y=0,b=0,v=0,k=u.length>0||h.length>0?lu(this.doc):null,x=u.length>0?this._batch_fingerprint():null,C=this.current_id;if(u.length>0){try{let j=this.apply_review_actions(u,f);if(y=j[0],b=j[1],v=j[2],b>0&&(o.push(...cr(this.skipped_details)),!r))throw new Zt(this.skipped_details,o)}catch(j){if(!r)throw this._restore_batch_snapshot(k,C),this._verify_rollback(x),j}y>0&&(this.mapper._build_map(),this.clean_mapper&&this.clean_mapper._build_map());}let[A]=nt(this.mapper.full_text),I=rt(A,"").body_page_offsets,M=[],B=0,D=0;if(h.length>0){let j=g(E=>E._resolved_start_idx!==void 0&&E._resolved_start_idx!==null?E._resolved_start_idx:E._match_start_index!==void 0&&E._match_start_index!==null?E._match_start_index:null,"pinned_idx"),F=c.map(({c:E,i:$},P)=>({edit:E,i:P,orig_idx:$})).sort((E,$)=>{let P=j(E.edit),O=j($.edit);return P===null&&O===null?E.i-$.i:P===null?1:O===null?-1:O-P||E.i-$.i});{try{let E=[],$=0;for(let{edit:P,orig_idx:O}of F){let W;try{W=this.validate_edits([P],O);}catch(U){if(!(U instanceof ze))throw U;W=[`- Edit ${O+1} Failed: ${U.message}`];}if(W.length>0){let U=W.join(`
157
+ `);if(o.push([O,U]),$>0&&!r){let X=zi($);W=W.map(z=>z+X);}E.push(...W),P&&typeof P=="object"&&(P._error_msg=U);}else if(this.apply_edits([P],I),P._applied_status&&!P._any_sub_failure)$++,this.mapper=new Ee(this.doc,!1,!1,this.resolve_numbering),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.clean_mapper=null;else {let U=P._error_msg||`- Edit ${O+1} Failed: Failed to apply edit.`;if(P&&typeof P=="object"&&(P._error_msg=U),o.push([O,U]),$>0&&!r&&(U+=zi($)),E.push(U),!r)break;P._applied_status&&(this.mapper=new Ee(this.doc,!1,!1,this.resolve_numbering),this._cc_anchor_pairs=null,this._field_entries_cache=null,this.clean_mapper=null);}}if(!r&&E.length>0)throw new Zt(E,o)}catch(E){throw this._restore_batch_snapshot(k,C),this._verify_rollback(x),E}B=h.filter(E=>E._applied_status&&!E._any_sub_failure).length,D=h.length-B;for(let[E,$]of h.entries()){let P=$._applied_status||false,O=$._error_msg||null,W=null,U=null,X=$._warning||null;if(P){let Q=this._build_edit_context_previews($);W=Q[0],U=Q[1];}else X=X||this._check_punctuation_warning($.target_text||"");let H=Array.from(new Set(($._minted_change_ids||[]).map(Q=>String(Q)).filter(Boolean))).map(Q=>Q.startsWith("Chg:")?Q:`Chg:${Q}`),V=Array.from(new Set(($._minted_comment_ids||[]).map(Q=>String(Q)).filter(Boolean))).map(Q=>Q.startsWith("Com:")?Q:`Com:${Q}`);M.push({index:c[E].i,status:P?"applied":"failed",type:$.type||"modify",target_text:ge($.target_text||"",Yn),new_text:ge(G._report_new_text($),Yn),comment:$.comment??null,warning:X,error:O,critic_markup:W,clean_text:U,pages:$._pages||[],heading_path:$._heading_path||"",field:$._field||"",part:$._part||"",occurrences_modified:$._occurrences_modified||0,match_mode:$.match_mode||"strict",...H.length>0?{change_ids:H}:{},...V.length>0?{comment_ids:V}:{}});}}}if(B>0)try{this._warn_stranded_comment_anchors(C);}catch{}return {status:r&&o.length>0?"partial":"ok",author_impersonation_warning:s,overrides_note:Jc(this.gate_overrides,this._overridden_controls),failed:o.map(([j,F])=>({index:j,reason:F,error:F})),actions_applied:y,actions_skipped:b,actions_already_resolved:v,edits_applied:B,edits_skipped:D,occurrences_modified:M.reduce((j,F)=>j+(F.occurrences_modified||0),0),skipped_details:this.skipped_details,edits:M,...this._last_action_reports?.length?{actions:this._last_action_reports}:{},document_state:this._get_document_state_summary(),engine:"node",version:lc}}_get_document_state_summary(){let e=new Set;for(let t of [...on,...an])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}=wn(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]=nt(this.mapper.full_text);t=rt(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]=Hi(c.target_text,c.new_text)),c._active_mapper_ref||(this.clean_mapper||(this.clean_mapper=new Ee(this.doc,true,false,this.resolve_numbering)),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 ze))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&&Wd(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=S(d,"w:rPr");if(c){let u=S(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=S(u,"w:pPr"),h=f?S(f,"w:rPr"):null;return h?S(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 Kt)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 Kt)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=Zn(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 Kt)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(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([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(We(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(We(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 P=d.target_id.replace("Com:","");if(!this._existing_comment_ids().includes(P)){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,P,this.timestamp);}catch(U){if(U instanceof hs){s++,this.skipped_details.push(`- Action ${r(c)+1} Failed: reply on ${d.target_id} \u2014 ${U.message}`);continue}throw U}this._anchor_reply_comment(P,O),i++;let W=d.target_id.startsWith("Com:")?d.target_id:`Com:${P}`;this._last_action_reports.push({index:r(c),type:"reply",target_id:W,resolved_ids:[W],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(P=>P.id===f).map(P=>P.el),b=this._revisionsByTagIn("w:del",w).filter(P=>P.id===f).map(P=>P.el),v=[...y,...b],N=an.flatMap(P=>this._revisionsByTagIn(P,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(P=>P.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 P of v)for(let O of this._get_paired_nodes(P)){let W=O.getAttribute("w:id");W&&x.add(W);}let C=on.flatMap(P=>this._revisionsByTagIn(P,w)),A=-1;for(;A!==x.size;){A=x.size;for(let P of C)if(!(!P.id||!x.has(P.id)))for(let O of P.nested)O.id&&x.add(O.id);}let T=[];for(let P of on)for(let O of this._revisionsByTagIn(P,w))O.id&&x.has(O.id)&&T.push(O.el);let I=an.flatMap(P=>this._revisionsByTagIn(P,w).filter(O=>O.id!==null&&x.has(O.id)).map(O=>O.el)),M=(()=>{let P=v[0]??N[0]??null;for(;P;){if(P.nodeType===1&&P.tagName==="w:p")return P;P=P.parentNode;}return null})(),B=new Set;for(let P of [...T,...I]){let O=P.getAttribute("w:id");O&&B.add(O);}let D=this._comment_authors(),j=new Set(Object.keys(D)),F=[],E=[...T].sort((P,O)=>{let W=P.tagName==="w:del"&&P.parentNode?.tagName==="w:rPr"&&P.parentNode?.parentNode?.tagName==="w:pPr",U=O.tagName==="w:del"&&O.parentNode?.tagName==="w:rPr"&&O.parentNode?.parentNode?.tagName==="w:pPr";return W&&!U?-1:!W&&U?1:0});for(let P of E){let O=P.tagName==="w:ins",W=P.parentNode?P.parentNode.tagName:"",U=W==="w:trPr",X=W==="w:rPr"&&!!P.parentNode?.parentNode&&P.parentNode.parentNode.tagName==="w:pPr";if(u==="accept")if(O)if(U)P.parentNode?.removeChild(P);else {for(;P.firstChild;)P.parentNode?.insertBefore(P.firstChild,P);P.parentNode?.removeChild(P);}else if(this._clean_wrapping_comments(P),this._delete_comments_in_element(P),U){let z=P.parentNode?.parentNode;z?.parentNode?.removeChild(z);}else P.parentNode?.removeChild(P);else if(u==="reject")if(O){if(X){let z=P.parentNode;P.parentNode?.removeChild(P),z=z?.parentNode,z=z?.parentNode,z&&z.tagName==="w:p"&&F.push(z);continue}if(this._clean_wrapping_comments(P),this._delete_comments_in_element(P),U){let z=P.parentNode?.parentNode;z?.parentNode?.removeChild(z);}else P.parentNode?.removeChild(P);}else if(U)P.parentNode?.removeChild(P);else if(X){let z=P.parentNode,H=z?z.parentNode:null,q=H?H.parentNode:null;if(q&&q.tagName==="w:p"){let V=Array.from(q.childNodes),Q=V.filter(fe=>fe.nodeType===1&&fe.tagName==="w:del");if(Q.length>0){let fe=Q[Q.length-1],ot=V.indexOf(fe),Re=V.slice(ot+1);if(Re.some(he=>he.nodeType===1&&(he.tagName==="w:r"||he.tagName==="w:sdt"||he.getElementsByTagName("w:t").length>0))&&q.parentNode){let Ve=q.ownerDocument.createElement("w:p"),Mr=H.cloneNode(true),In=S(Mr,"w:rPr");if(In){let bt=S(In,"w:del");bt&&In.removeChild(bt);}Ve.appendChild(Mr);for(let bt of Re)q.removeChild(bt),Ve.appendChild(bt);q.parentNode.insertBefore(Ve,q.nextSibling);}}}P.parentNode?.removeChild(P);}else {let z=Array.from(P.getElementsByTagName("w:delText"));for(let H of z){let q=H.ownerDocument.createElement("w:t");q.textContent=H.textContent,H.hasAttribute("xml:space")&&q.setAttribute("xml:space","preserve"),H.parentNode?.replaceChild(q,H);}for(;P.firstChild;)P.parentNode?.insertBefore(P.firstChild,P);P.parentNode?.removeChild(P);}}this._resolve_rejected_mark_hosts(F);for(let P of I)u==="accept"?P.parentNode?.removeChild(P):P.tagName==="w:pPrChange"?this._revert_ppr_change(P):this._revert_props_change(P);for(let P of B)a.set(P,{type:u,part:w});i++;let $=Array.from(B).filter(Boolean).sort((P,O)=>Number(P)-Number(O)).map(P=>`Chg:${P}`);if(this._last_action_reports.push({index:r(c),type:u,target_id:d.target_id,resolved_ids:$.length>0?$:[d.target_id.startsWith("Chg:")?d.target_id:`Chg:${f}`],status:"applied"}),j.size>0){let P=new Set(this._existing_comment_ids()),O=Array.from(j).filter(W=>!P.has(W));O.length>0&&this.skipped_details.push(`- Note: ${u} on ${d.target_id} also removed ${G._describe_removed_comments(O,D)} (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 P=r(c)+1,O=M?Array.from(M.childNodes).find(W=>W.tagName==="w:r")??null:null;if(M&&O){let W=this._attach_comment(M,O,O,String(d.comment));W&&this.skipped_details.push(`- Note: Action ${P} ('${u}' on ${d.target_id}) \u2014 rationale recorded as Com:${W}.`);}else this.skipped_details.push(`- Note: Action ${P} ('${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=S(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):ht(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===`
158
158
 
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(`
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 _restore_matched_list_prefix(e,t,r,i,s){if(!s||!i||r===i)return s;for(let o of e.spans){if(o.start>t)break;if(o.start===t&&o.run===null&&o.canonical_prefix){if(!r.startsWith(o.text)||i.startsWith(o.text))return s;let a=r.slice(o.text.length);if(!a||i.length<=a.length)return s;let l=i.slice(0,i.length-a.length);return s.startsWith(l)?o.text+s.slice(l.length):s}}return s}static _reinject_anchor_markers(e,t,r,i,s){let o=g(y=>new RegExp(or.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=Pt(a),c=Pt(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 js.diff_match_patch,h=f.diff_main(d,Pt(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 Ee(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(cn(e.target_text),f);}catch{}G._flag_surviving_python_backreference(e,f);}f=G._restore_matched_list_prefix(o,d,u,e.target_text,f),f=Va(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),C=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:C,_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(Ui)],a=[...s.matchAll(Ui)];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 Zt([`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 C=y[x],A=b[x],T=C.trim(),I=A.trim(),M=t+N+(T?C.indexOf(T):0),B=e.comment!==null&&e.comment!==void 0&&x===k;if(T!==I||B){let D=this._word_diff_sub_edits(T,I,M,B?e.comment:null,true,i);for(let j of D)j._original_target_text=e.target_text,j._split_group_id=t,v.push(j);}N+=C.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]=pt(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(`
160
160
 
161
161
  `),m=o.split(`
162
162
 
163
163
  `);if(s.includes(`
164
164
 
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(`
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 C=e.comment&&!v?e.comment:null,A=this._word_diff_sub_edits(k,x,b,C,false,i);A.some(T=>T.comment!==null&&T.comment!==void 0)&&(v=true);for(let T of A)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 C=x[0]._element,A=x[x.length-1]._element,T=C;for(;T&&T.tagName!=="w:p";)T=T.parentNode;let I=A;for(;I&&I.tagName!=="w:p";)I=I.parentNode;if(T&&I){let M=g((j,F)=>{let E=j;for(;E.parentNode&&E.parentNode!==F;)E=E.parentNode;return E},"ascend_to_paragraph_child"),B=M(C,T),D=M(A,I);T===I?this._attach_comment(T,B,D,e.comment):this._attach_comment_spanning(T,B,I,D,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[F,E]=k,$=s.part_kind_of(F),P=s.part_kind_of(E);if($==="body"&&P!=="body"){let O=s.spans.filter(W=>W.run!==null&&W.part_index===F);O.length>0&&(N=O[O.length-1]);}}let C,A;if(N!==null?(C=N.run,A=N.paragraph,v.startsWith(`
166
166
  `)||(v=`
167
167
 
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.
168
+ `+v)):e._insert_host_el?(C=null,A=null):[C,A]=s.get_insertion_anchor(o,r),!C&&!A&&!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),M=null;{let F=s.spans.filter(E=>E.paragraph!==null&&E.start===o);F.length>0&&F[0].paragraph&&(M=F[0].paragraph._element);}if(I&&M&&M.parentNode){let F=M.parentNode,E=this.doc.part._element.ownerDocument,$=T.split(/[\r\n]+/).filter(U=>U!==""),P=null,O=null,W=null;for(let U of $){let[X,z]=this._parse_markdown_style(U),H=E.createElement("w:p");if(z)this._set_paragraph_style(H,z);else {let fe=S(M,"w:pPr");fe&&H.appendChild(this._clone_pPr_scrubbing_headings(fe,M));}let q=S(H,"w:pPr");q||(q=E.createElement("w:pPr"),H.insertBefore(q,H.firstChild));let V=S(q,"w:rPr");V||(V=E.createElement("w:rPr"),q.appendChild(V)),V.insertBefore(this._create_track_change_tag("w:ins","",u),V.firstChild);let Q=this._build_tracked_ins_for_line(X,C,u,E,l);Q&&H.appendChild(Q),F.insertBefore(H,M),P||(P=H),O=H,W=Q;}if(P){if(e.comment&&O&&W){let U=g((z,H)=>{let q=z;for(;q.parentNode&&q.parentNode!==H;)q=q.parentNode;return q},"ascend"),X=R(P,"w:ins")[0]||P;this._attach_comment_spanning(P,U(X,P),O,U(W,O),e.comment);}return true}}let B=l;o>0&&C&&s.spans.some(F=>F.end===o&&F.run===null&&(F.text.includes("*")||F.text.includes("_")))&&(B=true);let D=this._track_insert_multiline(v,C,A,u,null,B,o===0||C===null&&A!==null);if(!D.first_node)return false;if(D.first_node.tagName==="w:ins"){if(e._insert_host_el)e._insert_host_el.appendChild(D.first_node);else if(C){let F=C._element,E=F.parentNode;E&&E.tagName==="w:del"&&(F=E,E=F.parentNode);let $=o===0;E&&E.tagName==="w:ins"?this._insert_and_split_ins(E,F,D.first_node,$):$&&E?E.insertBefore(D.first_node,F):ht(D.first_node,F);}else if(A){let F=A._element,E=F.firstChild;for(;E&&E.tagName==="w:pPr";)E=E.nextSibling;F.insertBefore(D.first_node,E);}}if(e.comment){let F=g((E,$)=>{let P=E;for(;P.parentNode&&P.parentNode!==$;)P=P.parentNode;return P},"ascend_to_paragraph_child");if(D.last_p&&D.last_ins){let E=D.first_node;for(;E&&E.tagName!=="w:p";)E=E.parentNode;if(E){let $=D.first_node;D.first_node.tagName==="w:p"&&($=R(D.first_node,"w:ins")[0]||D.first_node);let P=F($,E),O=F(D.last_ins,D.last_p);this._attach_comment_spanning(E,P,D.last_p,O,e.comment);}}else {let E=D.first_node;for(;E&&E.tagName!=="w:p";)E=E.parentNode;if(E){let $=D.first_node;D.first_node.tagName==="w:p"&&($=R(D.first_node,"w:ins")[0]||D.first_node);let P=F($,E);this._attach_comment(E,P,P,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(A=>{let T=x.ownerDocument.createElement("w:delText");T.textContent=A.textContent,A.hasAttribute("xml:space")&&T.setAttribute("xml:space","preserve"),x.replaceChild(T,A);}),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 A=m.parentNode;A&&A.tagName==="w:ins"?this._insert_and_split_ins(A,m,x.first_node):ht(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 Le(k[k.length-1],v.paragraph):null,C=this._track_insert_multiline(e.new_text,x,v.paragraph,u,null,l);C.first_node&&N.appendChild(C.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),C=!this._paragraph_has_visible_content(k),A=i==="DELETION"||!e.new_text;if(A&&x){let B=S(N,"w:pPr");B||(B=N.ownerDocument.createElement("w:pPr"),N.insertBefore(B,N.firstChild));let D=S(B,"w:rPr");if(D||(D=N.ownerDocument.createElement("w:rPr"),B.appendChild(D)),!S(D,"w:del")){let j=this._create_track_change_tag("w:del","",c),F=S(D,"w:ins");F?D.insertBefore(j,F.nextSibling):D.insertBefore(j,D.firstChild);}continue}if(A&&!x&&C)continue;let T=S(N,"w:pPr");if(x){let B=S(k,"w:pPr"),D=B?B.cloneNode(true):N.ownerDocument.createElement("w:pPr");if(T){let j=S(T,"w:sectPr");j&&!S(D,"w:sectPr")&&D.appendChild(j.cloneNode(true)),N.removeChild(T);}N.insertBefore(D,N.firstChild),T=D;}T||(T=N.ownerDocument.createElement("w:pPr"),N.insertBefore(T,N.firstChild));let I=S(T,"w:rPr");if(I||(I=N.ownerDocument.createElement("w:rPr"),T.appendChild(I)),!S(I,"w:del")){let B=this._create_track_change_tag("w:del","",c),D=S(I,"w:ins");D?I.insertBefore(B,D.nextSibling):I.insertBefore(B,I.firstChild);}let M=Array.from(k.childNodes);for(let B of M)B.nodeType===1&&B.tagName==="w:pPr"||N.appendChild(B);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 M=T;for(;M.parentNode&&M.parentNode!==I;)M=M.parentNode;return M},"ascend_to_paragraph_child"),C=x(p,k),A=x(v,N);k===N?this._attach_comment(k,C,A,e.comment):this._attach_comment_spanning(k,C,N,A,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","",c),A=S(x,"w:ins");A?x.insertBefore(C,A.nextSibling):x.insertBefore(C,x.firstChild);}}return true}},yu=["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"],vu=["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"],bu=["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"],xu=[["w:tblPr",new Map(yu.map((n,e)=>[n,e]))],["w:pPr",new Map(vu.map((n,e)=>[n,e]))],["w:rPr",new Map(bu.map((n,e)=>[n,e]))]];function Nu(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(Nu,"reorder");function ku(n){let e=0;for(let[t,r]of xu)for(let i of R(n,t))Nu(i,r)&&e++;return e}g(ku,"repair_schema_order");var Cu=class extends Error{static{g(this,"ComparisonError");}details;constructor(n,e=[]){super(n),this.name="ComparisonError",this.details=e;}};async function uo(n,e,t,r=true){let i=g(async p=>Ge(await ae.load(p),r,false,false,true,false),"extract"),{text:s,structure:o}=await i(n),{text:a,structure:l}=await i(e),{edits:d,warnings:c}=Er(s,o,a,l),u=await ae.load(n),f=new Ft(u,t,{resolve_numbering:false}),[h,_]=f.apply_edits(d);if(_>0)throw new Cu(`${_} 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())ku(p);return {data:await u.save(),applied:h,warnings:[...c,...Ar(new Uint8Array(n),new Uint8Array(e))]}}g(uo,"build_redline_comparison");var Au=["{++","{--","{~~","{==","{>>"],Pu=/^> \*\*File Path:\*\*[^\n]*\n+/,Tu=/^> \*\*Page (\d+) of (\d+)\*\*[^\n]*\n+(?:---\n+)?/,Su=/\n+---\n+> \*\*Continues on page (\d+) of (\d+)\.\*\*[^\n]*\s*$/,$u=/\n+---\n+> \*\*Appendix available\.\*\*[^\n]*\s*$/,Iu=2e3,Tn=class extends Error{static{g(this,"TextRevisionError");}constructor(n){super(n),this.name="TextRevisionError";}},Ou=class extends Tn{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 Du(n){if(n&&n.trim())return n.trim();let e="".trim();return e||"Adeu AI (TS)"}g(Du,"get_default_author");function Ru(n){if(Au.some(e=>n.includes(e)))throw new Tn("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(Ru,"check_criticmarkup");function Mu(n){n=n.replace(Pu,"");let e=null,t=null,r=Tu.exec(n);r&&(e=parseInt(r[1],10),t=parseInt(r[2],10),n=n.slice(r[0].length)),n=n.replace($u,"");let i=Su.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(Mu,"strip_page_chrome");function ju(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>=Iu?.5:.75;if(o<=a)return;let l=r?`'${r}'`:"The revised text";throw new Tn(`${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.
169
169
  If the text is a partial extract, re-extract the ENTIRE document with \`--page all --clean-view\` and edit that.
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(`
170
+ If the mass deletion is intentional, re-run with --allow-major-deletions (over MCP: allow_major_deletions=True).`)}g(ju,"check_major_deletions");function _o(n){return n=n.replace(/([^|])\s+\{#cell:[^}]+\}/g,"$1"),n=n.replace(/\{#cell:[^}]+\}/g,""),n}g(_o,"strip_cell_anchors");function mo(n){return Ge(n,true,false)}g(mo,"_extract_clean_text_from_doc");function dr(n){return _o(n.replace(/^#+\s*/gm,""))}g(dr,"_normalize_virtual_projection_text");var Bu=new RegExp("\\p{C}|\\p{Z}","u");function qi(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!==" "&&Bu.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(qi,"_repr");var Fu=/^[ \t]*(?:(?:§|Article|ARTICLE|Part|PART|Clause|CLAUSE|Section|SECTION|ust\.|pkt)\s+)?(?:\([a-zA-Z0-9]+\)|[0-9IVXLCDMa-zA-Z]+(?:\.[0-9a-zA-Z]+)*[.)]?)\s+$/;function Lu(n,e){let t=new Ee(n,true),r="\0NUM\0 ",i=[];for(let l of t.spans)l.run===null&&l.canonical_prefix?i.push(r):i.push(l.text);let o=dr(i.join("").trim()).split(`
172
+
173
+ `),a=e.split(`
174
+
175
+ `);if(o.length!==a.length)return false;for(let l=0;l<o.length;l++){let d=o[l],c=a[l];if(!d.startsWith(r)){if(d!==c)return false;continue}let u=d.slice(r.length);if(!c.endsWith(u))return false;let f=c.slice(0,c.length-u.length);if(f&&!Fu.test(f))return false}return true}g(Lu,"_matches_allowing_auto_renumber");function Wu(n,e){let t=mo(n),r=dr(t.trim()),i=dr(e.trim());if(r!==i&&!Lu(n,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 ${qi(d)}, supplied text reads ${qi(c)}). The document structure could not fully realize the requested text (e.g. headings or table cells cannot be deleted via text replacement).`]}return [true,null]}g(Wu,"verify_clean_text");function zu(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(zu,"_default_output_path");function Uu(n){let e=path.basename(n,path.extname(n));return path.join(path.dirname(n),`${e}.unverified.docx`)}g(Uu,"_unverified_path");async function go(n){let{doc:e,input_path:t,revised_text:r}=n,{text:i,page:s,total:o}=Mu(r),a=_o(i);if(o!==null&&o>1)throw new Tn(`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.`);Ru(a);let l=mo(e);ju(l,a,n.allow_major_deletions??false);let d=rn(l,a),c=new Ft(e,Du(n.author)),u=c.process_batch(d),f=n.output_path?n.output_path:zu(t),[h,_]=Wu(c.doc,a);if(!h){let m=Uu(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 Ou(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(go,"apply_text_revision_core");var Hu=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(`
172
176
  `);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(`
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:
177
+ `)}};async function wo(n,e){let t=new Hu(e.filename,e.sanitize_mode||"full",e.author||null);if(e.sanitize_mode==="full"){let s=ki(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=_c(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=Jt(n);t.add_transform_lines(mc(n)),t.tracked_changes_accepted=o;let c=new Set(Jt(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} "${He(f.text||"",60)}" (${f.author||"Unknown"})`);}}}let a=Jt(n);t.comments_removed+=a.total,t.add_transform_lines(gc(n)),wc(n);}else if(e.sanitize_mode==="keep-markup"){let s=ki(n);t.tracked_changes_found=s[0]+s[1]+s[2],t.tracked_changes_kept=t.tracked_changes_found;let o=Jt(n);t.comments_kept=o.open;for(let a of o.comments)a.resolved||t.kept_comment_lines.push(`"${He(a.text||"",60)}" (${a.author||"Unknown"})`);e.author&&(t.add_transform_lines(yc(n,e.author)),t.add_transform_lines(vc(n,e.author)));}t.add_transform_lines(dc(n)),t.add_transform_lines(uc(n)),t.add_transform_lines(fc(n)),t.add_transform_lines(hc(n)),t.add_transform_lines(pc(n)),t.add_transform_lines(cc(n)),t.add_transform_lines(Nc(n)),t.add_transform_lines(kc(n)),t.add_transform_lines(Cc(n)),t.add_transform_lines(Ec(n)),t.add_transform_lines(Ac(n)),t.add_transform_lines(Pc(n));let r=Sc(n);for(let s of r)t.warnings.push(s);for(let s of Tc(n))t.warnings.push(s);if(t.add_transform_lines(bc(n)),t.add_transform_lines(xc(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 qu(i),{reportText:t.render(),outBuffer:i}}g(wo,"finalize_document");var Xu=[["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 qu(n){let e=ct(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=et(Qe(e["docProps/core.xml"]));for(let[s,o]of Xu)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=et(Qe(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:
174
178
  - `+r.join(`
175
179
  - `)+`
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(`
180
+ Refusing to report a clean document.`)}g(qu,"verifySanitizedPackage");var Yu=/\r\n|[\n\r\v\f\u001c-\u001e\u0085\u2028\u2029]/;var $t="Nothing was written. Recover in two calls: (1) re-apply this batch WITHOUT the failing edit(s); (2) fix the failing edit(s) in a separate small batch. Copy target_text verbatim from a fresh read of the CURRENT file, not from another tool's view of it.";var Gu=new Set(["invalid_changes_file","batch_validation_failed"]);function yo(n,e,t,r){let i=t.split(Yu).map(o=>o.trim()).filter(Boolean).join(" ");Gu.has(n)&&!i.includes($t)&&(i=i?`${i} ${$t}`:$t);let s={error:n,failed:e.map(([o,a])=>({index:o,reason:a})),message:i};return r!=null&&(s.errors=r),s}g(yo,"failure_envelope");var de="application/vnd.openxmlformats-officedocument.wordprocessingml.document",bo="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 yt(n){return {show:{resource:["document"],operation:[n]}}}g(yt,"docOpDisplayOptions");function xo(n,e){return e.split(".").reduce((t,r)=>{if(!(typeof t!="object"||t===null)&&Object.hasOwn(t,r))return t[r]},n)}g(xo,"getNestedProperty");async function Ju(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(Ju,"getDocxBuffer");async function ue(n,e){if(e.mode==="fromInput")return Ju.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 Je(n,e){let t=n.lastIndexOf(".");return `${t===-1?n:n.substring(0,t)}_${e}.docx`}g(Je,"buildOutputFileName");var vo={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 Vu(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(vo,r)?vo[r]:void 0;i===void 0?delete n.match_mode:n.match_mode=i;}}}g(Vu,"coerceChangeItemInPlace");function No(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)&&Vu(t),t})}g(No,"coerceChangesArray");function ko(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(ko,"parseJsonParameter");function Co(n,e){let t=n.message??"Unknown error",r=n.name??"",i=n.errors,s=Array.isArray(i)?i.join(`
177
181
  `):t,o=s.toLowerCase();if(r==="BatchValidationError"){let a="Batch validation failed.",l=`Review the listed failures:
178
182
  `+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
183
  `+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
184
  `+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
185
  `+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?`
186
+ `+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=yo("batch_validation_failed",d,s,i),u=c.failed.length?`
183
187
 
184
188
  Failed changes (0-based index into the submitted array):
185
189
  `+c.failed.map(f=>` [${f.index}] ${f.reason}`).join(`
186
190
  `):"";return new n8nWorkflow.NodeApiError(this.getNode(),c,{message:a,description:`${l}${u}
187
191
 
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}
192
+ ${$t}`,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}
189
193
 
190
194
  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}
191
195
 
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(`
196
+ 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(Co,"mapAdeuErrorToNodeApiError");function Qu(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(Qu,"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 Po(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(!Qu(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(Po,"executeHydrateToolOutput");var Sn=yt("extractMarkdown"),So=[{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:Sn},{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:Sn},{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:Sn},{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:Sn},{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 $o(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 Ye(l,false,false),[b]=nt(y),v=rt(b,""),N=Or(w,y,v.body_page_offsets),k=Nn(w),x=ao(d,N,k,m);return [{json:{fileName:d,mode:"fields",total_fields:N.length,markdown:x},pairedItem:{item:n}}]}let c=await Ye(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]=nt(c),h=rt(u,f);if(typeof s=="string"&&s.includes("-")){let[m,w]=zs(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+Ws-1,h.total_pages),N=h.pages.slice(y-1,v),k=N.map(C=>C.page_content).join(`
193
197
 
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:`[
198
+ `),x=N.reduce((C,A)=>C+A.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($o,"executeExtractMarkdown");var Io=[{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 Oo(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=Ge(o,false,true,true),[l]=nt(a.text),d=rt(l,""),c=Ys(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(Oo,"executeExtractOutline");var be={show:{resource:["document"],operation:["applyEdits"]}},Do=[{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:`[
195
199
  {
196
200
  "type": "modify",
197
201
  "target_text": "State of New York",
198
202
  "new_text": "State of Delaware",
199
203
  "comment": "Standardizing governing law."
200
204
  }
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}
205
+ ]`,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 Ro(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),M=this.getInputData()[n].json;if(f=xo(M,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=ko.call(this,I,n,"Changes (JSON)");}if(!Array.isArray(f))throw new Error("Changes must be an array of DocumentChange objects.");f=No(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 Ft(w,r,{id_discovery_hint:bo,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=Je(m,"redlined"),x=await this.helpers.prepareBinaryData(N,k,de),C=typeof this.isToolExecution=="function"&&this.isToolExecution(),A;if(C&&x.id){let I=this.getWorkflowStaticData("global");I.adeu_last_redlined={id:x.id,fileName:k,mimeType:de,timestamp:Date.now()},A=x.id;}let T;return s&&(T=await Ye(N,false)),[{json:{fileName:k,author:r,status:b.status??"ok",stats:b,...u!==""?{reasoning:u}:{},...T!==void 0?{markdown:T}:{},...A!==void 0?{redlinedBinaryId:A}:{}},binary:{...v,[t]:x},pairedItem:{item:n}}]}g(Ro,"executeApplyEdits");var vt=yt("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:vt},{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:vt},{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:vt},{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:vt},{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:vt},{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:vt}];async function jo(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=Je(c,"redlined"),h=await go({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(jo,"executeApplyTextRevision");var $n=yt("generateDiff"),Bo=[{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:$n},{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:$n},{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:$n},{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:$n},{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 Fo(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=Ar(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 uo(d,u,y,r),N=Je(c,"redlined"),k=this.getInputData()[n].binary??{},x=await this.helpers.prepareBinaryData(v.data,N,de),C=typeof this.isToolExecution=="function"&&this.isToolExecution(),A;if(C&&x.id){let T=this.getWorkflowStaticData("global");T.adeu_last_redlined={id:x.id,fileName:N,mimeType:de,timestamp:Date.now()},A=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}:{},...A!==void 0?{redlinedBinaryId:A}:{}},binary:{...k,[b]:x},pairedItem:{item:n}}]}if(i==="structuredChanges"){let y=await ae.load(d),b=await ae.load(u),v=Ge(y,r,false,false,true,false),N=Ge(b,r,false,false,true,false),{edits:k,warnings:x}=Er(v.text,v.structure,N.text,N.structure),C=[...h,...x];return [{json:{originalFileName:c,modifiedFileName:f,cleanView:r,diffFormat:i,changes:k,...C.length>0?{warnings:C}:{}},pairedItem:{item:n}}]}let _=await Ye(d,r,false,false),p=await Ye(u,r,false,false),m=i==="unified"?Bs(_,p):Ls(_,p,c,f);return (i==="unified"?m.trim()!=="":m.includes("@@ Word Patch @@"))||(m=`--- ${c}
202
206
  +++ ${f}
203
207
 
204
208
  No textual differences found between the documents.`),h.length>0&&(m=h.map(b=>`\u26A0\uFE0F ${b}`).join(`
205
209
  `)+`
206
210
 
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;
211
+ `+m),[{json:{originalFileName:c,modifiedFileName:f,cleanView:r,diffFormat:i,diff:m,...h.length>0?{warnings:h}:{}},pairedItem:{item:n}}]}g(Fo,"executeGenerateDiff");var Lo=[{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 Wo(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 wo(h,{filename:f,sanitize_mode:r,accept_all:i,protection_mode:a,author:s});if(!p)throw new Error(_);let m=Je(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(Wo,"executeFinalizeDocument");var zo=[{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"]}}},...So,...Io,...Do,...Mo,...Bo,...Lo,...Ao];var Xo=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"},...zo]};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 $o.call(this,s);break;case "extractOutline":o=await Oo.call(this,s);break;case "applyEdits":o=await Ro.call(this,s);break;case "applyTextRevision":o=await jo.call(this,s);break;case "generateDiff":o=await Fo.call(this,s);break;case "finalizeDocument":o=await Wo.call(this,s);break;case "hydrateToolOutput":o=await Po.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:Co.call(this,a,s)}return [t]}};exports.Adeu=Xo;